39477-vm/backend/src/db/api/invoices.js
2026-04-05 01:41:33 +00:00

843 lines
21 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 InvoicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.create(
{
id: data.id || undefined,
invoice_number: data.invoice_number
||
null
,
issued_at: data.issued_at
||
null
,
status: data.status
||
null
,
exchange_rate: data.exchange_rate
||
null
,
pricing_currency: data.pricing_currency
||
null
,
subtotal_usd: data.subtotal_usd
||
null
,
discount_usd: data.discount_usd
||
null
,
total_usd: data.total_usd
||
null
,
total_syp: data.total_syp
||
null
,
profit_usd: data.profit_usd
||
null
,
payment_method: data.payment_method
||
null
,
payment_status: data.payment_status
||
null
,
note: data.note
||
null
,
is_printed: data.is_printed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoices.setStore( data.store || null, {
transaction,
});
await invoices.setCustomer( data.customer || null, {
transaction,
});
await invoices.setCashier( data.cashier || null, {
transaction,
});
return invoices;
}
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 invoicesData = data.map((item, index) => ({
id: item.id || undefined,
invoice_number: item.invoice_number
||
null
,
issued_at: item.issued_at
||
null
,
status: item.status
||
null
,
exchange_rate: item.exchange_rate
||
null
,
pricing_currency: item.pricing_currency
||
null
,
subtotal_usd: item.subtotal_usd
||
null
,
discount_usd: item.discount_usd
||
null
,
total_usd: item.total_usd
||
null
,
total_syp: item.total_syp
||
null
,
profit_usd: item.profit_usd
||
null
,
payment_method: item.payment_method
||
null
,
payment_status: item.payment_status
||
null
,
note: item.note
||
null
,
is_printed: item.is_printed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invoices = await db.invoices.bulkCreate(invoicesData, { transaction });
// For each item created, replace relation files
return invoices;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.exchange_rate !== undefined) updatePayload.exchange_rate = data.exchange_rate;
if (data.pricing_currency !== undefined) updatePayload.pricing_currency = data.pricing_currency;
if (data.subtotal_usd !== undefined) updatePayload.subtotal_usd = data.subtotal_usd;
if (data.discount_usd !== undefined) updatePayload.discount_usd = data.discount_usd;
if (data.total_usd !== undefined) updatePayload.total_usd = data.total_usd;
if (data.total_syp !== undefined) updatePayload.total_syp = data.total_syp;
if (data.profit_usd !== undefined) updatePayload.profit_usd = data.profit_usd;
if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
if (data.payment_status !== undefined) updatePayload.payment_status = data.payment_status;
if (data.note !== undefined) updatePayload.note = data.note;
if (data.is_printed !== undefined) updatePayload.is_printed = data.is_printed;
updatePayload.updatedById = currentUser.id;
await invoices.update(updatePayload, {transaction});
if (data.store !== undefined) {
await invoices.setStore(
data.store,
{ transaction }
);
}
if (data.customer !== undefined) {
await invoices.setCustomer(
data.customer,
{ transaction }
);
}
if (data.cashier !== undefined) {
await invoices.setCashier(
data.cashier,
{ transaction }
);
}
return invoices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invoices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invoices) {
await record.destroy({transaction});
}
});
return invoices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findByPk(id, options);
await invoices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invoices.destroy({
transaction
});
return invoices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findOne(
{ where },
{ transaction },
);
if (!invoices) {
return invoices;
}
const output = invoices.get({plain: true});
output.invoice_items_invoice = await invoices.getInvoice_items_invoice({
transaction
});
output.payments_invoice = await invoices.getPayments_invoice({
transaction
});
output.store = await invoices.getStore({
transaction
});
output.customer = await invoices.getCustomer({
transaction
});
output.cashier = await invoices.getCashier({
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.stores,
as: 'store',
where: filter.store ? {
[Op.or]: [
{ id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'cashier',
where: filter.cashier ? {
[Op.or]: [
{ id: { [Op.in]: filter.cashier.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.cashier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.invoice_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'invoice_number',
filter.invoice_number,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'note',
filter.note,
),
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.exchange_rateRange) {
const [start, end] = filter.exchange_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
exchange_rate: {
...where.exchange_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
exchange_rate: {
...where.exchange_rate,
[Op.lte]: end,
},
};
}
}
if (filter.subtotal_usdRange) {
const [start, end] = filter.subtotal_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal_usd: {
...where.subtotal_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal_usd: {
...where.subtotal_usd,
[Op.lte]: end,
},
};
}
}
if (filter.discount_usdRange) {
const [start, end] = filter.discount_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_usd: {
...where.discount_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_usd: {
...where.discount_usd,
[Op.lte]: end,
},
};
}
}
if (filter.total_usdRange) {
const [start, end] = filter.total_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_usd: {
...where.total_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_usd: {
...where.total_usd,
[Op.lte]: end,
},
};
}
}
if (filter.total_sypRange) {
const [start, end] = filter.total_sypRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_syp: {
...where.total_syp,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_syp: {
...where.total_syp,
[Op.lte]: end,
},
};
}
}
if (filter.profit_usdRange) {
const [start, end] = filter.profit_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
profit_usd: {
...where.profit_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
profit_usd: {
...where.profit_usd,
[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.pricing_currency) {
where = {
...where,
pricing_currency: filter.pricing_currency,
};
}
if (filter.payment_method) {
where = {
...where,
payment_method: filter.payment_method,
};
}
if (filter.payment_status) {
where = {
...where,
payment_status: filter.payment_status,
};
}
if (filter.is_printed) {
where = {
...where,
is_printed: filter.is_printed,
};
}
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.invoices.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(
'invoices',
'invoice_number',
query,
),
],
};
}
const records = await db.invoices.findAll({
attributes: [ 'id', 'invoice_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['invoice_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.invoice_number,
}));
}
};