40048-vm/backend/src/db/api/tenancies.js
2026-05-21 14:26:36 +00:00

675 lines
17 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 TenanciesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenancies = await db.tenancies.create(
{
id: data.id || undefined,
status: data.status
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
agreed_monthly_price: data.agreed_monthly_price
||
null
,
deposit_amount: data.deposit_amount
||
null
,
billing_day_of_month: data.billing_day_of_month
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tenancies.setBoarding_house( data.boarding_house || null, {
transaction,
});
await tenancies.setTenant( data.tenant || null, {
transaction,
});
await tenancies.setApplication( data.application || null, {
transaction,
});
return tenancies;
}
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 tenanciesData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
agreed_monthly_price: item.agreed_monthly_price
||
null
,
deposit_amount: item.deposit_amount
||
null
,
billing_day_of_month: item.billing_day_of_month
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tenancies = await db.tenancies.bulkCreate(tenanciesData, { transaction });
// For each item created, replace relation files
return tenancies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tenancies = await db.tenancies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.agreed_monthly_price !== undefined) updatePayload.agreed_monthly_price = data.agreed_monthly_price;
if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
if (data.billing_day_of_month !== undefined) updatePayload.billing_day_of_month = data.billing_day_of_month;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await tenancies.update(updatePayload, {transaction});
if (data.boarding_house !== undefined) {
await tenancies.setBoarding_house(
data.boarding_house,
{ transaction }
);
}
if (data.tenant !== undefined) {
await tenancies.setTenant(
data.tenant,
{ transaction }
);
}
if (data.application !== undefined) {
await tenancies.setApplication(
data.application,
{ transaction }
);
}
return tenancies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenancies = await db.tenancies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tenancies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tenancies) {
await record.destroy({transaction});
}
});
return tenancies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tenancies = await db.tenancies.findByPk(id, options);
await tenancies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tenancies.destroy({
transaction
});
return tenancies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tenancies = await db.tenancies.findOne(
{ where },
{ transaction },
);
if (!tenancies) {
return tenancies;
}
const output = tenancies.get({plain: true});
output.payments_tenancy = await tenancies.getPayments_tenancy({
transaction
});
output.boarding_house = await tenancies.getBoarding_house({
transaction
});
output.tenant = await tenancies.getTenant({
transaction
});
output.application = await tenancies.getApplication({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.boarding_houses,
as: 'boarding_house',
where: filter.boarding_house ? {
[Op.or]: [
{ id: { [Op.in]: filter.boarding_house.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.boarding_house.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.house_applications,
as: 'application',
where: filter.application ? {
[Op.or]: [
{ id: { [Op.in]: filter.application.split('|').map(term => Utils.uuid(term)) } },
{
move_in_preference: {
[Op.or]: filter.application.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenancies',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.agreed_monthly_priceRange) {
const [start, end] = filter.agreed_monthly_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
agreed_monthly_price: {
...where.agreed_monthly_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
agreed_monthly_price: {
...where.agreed_monthly_price,
[Op.lte]: end,
},
};
}
}
if (filter.deposit_amountRange) {
const [start, end] = filter.deposit_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deposit_amount: {
...where.deposit_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deposit_amount: {
...where.deposit_amount,
[Op.lte]: end,
},
};
}
}
if (filter.billing_day_of_monthRange) {
const [start, end] = filter.billing_day_of_monthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
billing_day_of_month: {
...where.billing_day_of_month,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
billing_day_of_month: {
...where.billing_day_of_month,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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,
},
};
}
}
}
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.tenancies.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tenancies',
'notes',
query,
),
],
};
}
const records = await db.tenancies.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};