33874/backend/src/db/api/cameras.js
2025-09-04 06:10:27 +00:00

357 lines
8.4 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CamerasDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cameras = await db.cameras.create(
{
id: data.id || undefined,
ip_address: data.ip_address || null,
location: data.location || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cameras.setTenant(data.tenant || null, {
transaction,
});
await cameras.setApartments(data.apartments || null, {
transaction,
});
return cameras;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const camerasData = data.map((item, index) => ({
id: item.id || undefined,
ip_address: item.ip_address || null,
location: item.location || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cameras = await db.cameras.bulkCreate(camerasData, { transaction });
// For each item created, replace relation files
return cameras;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const cameras = await db.cameras.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.ip_address !== undefined)
updatePayload.ip_address = data.ip_address;
if (data.location !== undefined) updatePayload.location = data.location;
updatePayload.updatedById = currentUser.id;
await cameras.update(updatePayload, { transaction });
if (data.tenant !== undefined) {
await cameras.setTenant(
data.tenant,
{ transaction },
);
}
if (data.apartments !== undefined) {
await cameras.setApartments(
data.apartments,
{ transaction },
);
}
return cameras;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cameras = await db.cameras.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cameras) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of cameras) {
await record.destroy({ transaction });
}
});
return cameras;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cameras = await db.cameras.findByPk(id, options);
await cameras.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await cameras.destroy({
transaction,
});
return cameras;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cameras = await db.cameras.findOne({ where }, { transaction });
if (!cameras) {
return cameras;
}
const output = cameras.get({ plain: true });
output.tenant = await cameras.getTenant({
transaction,
});
output.apartments = await cameras.getApartments({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userApartments = (user && user.apartments?.id) || null;
if (userApartments) {
if (options?.currentUser?.apartmentsId) {
where.apartmentsId = options.currentUser.apartmentsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant
? {
[Op.or]: [
{
id: {
[Op.in]: filter.tenant
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.tenant
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.apartments,
as: 'apartments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike('cameras', 'ip_address', filter.ip_address),
};
}
if (filter.location) {
where = {
...where,
[Op.and]: Utils.ilike('cameras', 'location', filter.location),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.apartments) {
const listItems = filter.apartments.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
apartmentsId: { [Op.or]: listItems },
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.apartmentsId;
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.cameras.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(
query,
limit,
offset,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('cameras', 'ip_address', query),
],
};
}
const records = await db.cameras.findAll({
attributes: ['id', 'ip_address'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['ip_address', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.ip_address,
}));
}
};