33624/backend/src/db/api/beds.js
2025-08-25 21:19:49 +00:00

415 lines
9.5 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 BedsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beds = await db.beds.create(
{
id: data.id || undefined,
type: data.type || null,
total: data.total || null,
available: data.available || null,
is_available: data.is_available || false,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await beds.setHospital(data.hospital || null, {
transaction,
});
await beds.setTenants(data.tenants || null, {
transaction,
});
return beds;
}
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 bedsData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type || null,
total: item.total || null,
available: item.available || null,
is_available: item.is_available || false,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const beds = await db.beds.bulkCreate(bedsData, { transaction });
// For each item created, replace relation files
return beds;
}
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 beds = await db.beds.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.total !== undefined) updatePayload.total = data.total;
if (data.available !== undefined) updatePayload.available = data.available;
if (data.is_available !== undefined)
updatePayload.is_available = data.is_available;
updatePayload.updatedById = currentUser.id;
await beds.update(updatePayload, { transaction });
if (data.hospital !== undefined) {
await beds.setHospital(
data.hospital,
{ transaction },
);
}
if (data.tenants !== undefined) {
await beds.setTenants(
data.tenants,
{ transaction },
);
}
return beds;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beds = await db.beds.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of beds) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of beds) {
await record.destroy({ transaction });
}
});
return beds;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beds = await db.beds.findByPk(id, options);
await beds.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await beds.destroy({
transaction,
});
return beds;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const beds = await db.beds.findOne({ where }, { transaction });
if (!beds) {
return beds;
}
const output = beds.get({ plain: true });
output.hospital = await beds.getHospital({
transaction,
});
output.tenants = await beds.getTenants({
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 userTenants = (user && user.tenants?.id) || null;
if (userTenants) {
if (options?.currentUser?.tenantsId) {
where.tenantsId = options.currentUser.tenantsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.hospitals,
as: 'hospital',
where: filter.hospital
? {
[Op.or]: [
{
id: {
[Op.in]: filter.hospital
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.hospital
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.tenants,
as: 'tenants',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.type) {
where = {
...where,
[Op.and]: Utils.ilike('beds', 'type', filter.type),
};
}
if (filter.totalRange) {
const [start, end] = filter.totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total: {
...where.total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total: {
...where.total,
[Op.lte]: end,
},
};
}
}
if (filter.availableRange) {
const [start, end] = filter.availableRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available: {
...where.available,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available: {
...where.available,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.is_available) {
where = {
...where,
is_available: filter.is_available,
};
}
if (filter.tenants) {
const listItems = filter.tenants.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
tenantsId: { [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.tenantsId;
}
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.beds.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('beds', 'type', query),
],
};
}
const records = await db.beds.findAll({
attributes: ['id', 'type'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.type,
}));
}
};