37386-vm/backend/src/db/api/inventory.js
2026-01-12 11:51:16 +00:00

458 lines
11 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 InventoryDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.create(
{
id: data.id || undefined,
quantity: data.quantity
||
null
,
location: data.location
||
null
,
change_type: data.change_type
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory.setVariant( data.variant || null, {
transaction,
});
return inventory;
}
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 inventoryData = data.map((item, index) => ({
id: item.id || undefined,
quantity: item.quantity
||
null
,
location: item.location
||
null
,
change_type: item.change_type
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory = await db.inventory.bulkCreate(inventoryData, { transaction });
// For each item created, replace relation files
return inventory;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.location !== undefined) updatePayload.location = data.location;
if (data.change_type !== undefined) updatePayload.change_type = data.change_type;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await inventory.update(updatePayload, {transaction});
if (data.variant !== undefined) {
await inventory.setVariant(
data.variant,
{ transaction }
);
}
return inventory;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory) {
await record.destroy({transaction});
}
});
return inventory;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findByPk(id, options);
await inventory.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory.destroy({
transaction
});
return inventory;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findOne(
{ where },
{ transaction },
);
if (!inventory) {
return inventory;
}
const output = inventory.get({plain: true});
output.variant = await inventory.getVariant({
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.product_variants,
as: 'variant',
where: filter.variant ? {
[Op.or]: [
{ id: { [Op.in]: filter.variant.split('|').map(term => Utils.uuid(term)) } },
{
sku: {
[Op.or]: filter.variant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.location) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory',
'location',
filter.location,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory',
'note',
filter.note,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.change_type) {
where = {
...where,
change_type: filter.change_type,
};
}
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.inventory.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(
'inventory',
'location',
query,
),
],
};
}
const records = await db.inventory.findAll({
attributes: [ 'id', 'location' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['location', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.location,
}));
}
};