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, name: data.name || null, status: data.status || null, category: data.category || null, code: data.code || null, purchase_price: data.purchase_price || null, purchase_date: data.purchase_date || null, rental_price_per_hour: data.rental_price_per_hour || null, rental_price_per_day: data.rental_price_per_day || null, total_revenue: data.total_revenue || null, number_of_rentals: data.number_of_rentals || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await inventory.setCompanies(data.companies || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.inventory.getTableName(), belongsToColumn: 'images', belongsToId: inventory.id, }, data.images, options, ); 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, name: item.name || null, status: item.status || null, category: item.category || null, code: item.code || null, purchase_price: item.purchase_price || null, purchase_date: item.purchase_date || null, rental_price_per_hour: item.rental_price_per_hour || null, rental_price_per_day: item.rental_price_per_day || null, total_revenue: item.total_revenue || null, number_of_rentals: item.number_of_rentals || 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 for (let i = 0; i < inventory.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.inventory.getTableName(), belongsToColumn: 'images', belongsToId: inventory[i].id, }, data[i].images, options, ); } return inventory; } 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 inventory = await db.inventory.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.name !== undefined) updatePayload.name = data.name; if (data.status !== undefined) updatePayload.status = data.status; if (data.category !== undefined) updatePayload.category = data.category; if (data.code !== undefined) updatePayload.code = data.code; if (data.purchase_price !== undefined) updatePayload.purchase_price = data.purchase_price; if (data.purchase_date !== undefined) updatePayload.purchase_date = data.purchase_date; if (data.rental_price_per_hour !== undefined) updatePayload.rental_price_per_hour = data.rental_price_per_hour; if (data.rental_price_per_day !== undefined) updatePayload.rental_price_per_day = data.rental_price_per_day; if (data.total_revenue !== undefined) updatePayload.total_revenue = data.total_revenue; if (data.number_of_rentals !== undefined) updatePayload.number_of_rentals = data.number_of_rentals; updatePayload.updatedById = currentUser.id; await inventory.update(updatePayload, { transaction }); if (data.companies !== undefined) { await inventory.setCompanies( data.companies, { transaction }, ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.inventory.getTableName(), belongsToColumn: 'images', belongsToId: inventory.id, }, data.images, options, ); 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.images = await inventory.getImages({ transaction, }); output.companies = await inventory.getCompanies({ 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 userCompanies = (user && user.companies?.id) || null; if (userCompanies) { if (options?.currentUser?.companiesId) { where.companiesId = options.currentUser.companiesId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.companies, as: 'companies', }, { model: db.file, as: 'images', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.name) { where = { ...where, [Op.and]: Utils.ilike('inventory', 'name', filter.name), }; } if (filter.status) { where = { ...where, [Op.and]: Utils.ilike('inventory', 'status', filter.status), }; } if (filter.category) { where = { ...where, [Op.and]: Utils.ilike('inventory', 'category', filter.category), }; } if (filter.code) { where = { ...where, [Op.and]: Utils.ilike('inventory', 'code', filter.code), }; } if (filter.purchase_priceRange) { const [start, end] = filter.purchase_priceRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, purchase_price: { ...where.purchase_price, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, purchase_price: { ...where.purchase_price, [Op.lte]: end, }, }; } } if (filter.purchase_dateRange) { const [start, end] = filter.purchase_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, purchase_date: { ...where.purchase_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, purchase_date: { ...where.purchase_date, [Op.lte]: end, }, }; } } if (filter.rental_price_per_hourRange) { const [start, end] = filter.rental_price_per_hourRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, rental_price_per_hour: { ...where.rental_price_per_hour, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, rental_price_per_hour: { ...where.rental_price_per_hour, [Op.lte]: end, }, }; } } if (filter.rental_price_per_dayRange) { const [start, end] = filter.rental_price_per_dayRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, rental_price_per_day: { ...where.rental_price_per_day, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, rental_price_per_day: { ...where.rental_price_per_day, [Op.lte]: end, }, }; } } if (filter.total_revenueRange) { const [start, end] = filter.total_revenueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, total_revenue: { ...where.total_revenue, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, total_revenue: { ...where.total_revenue, [Op.lte]: end, }, }; } } if (filter.number_of_rentalsRange) { const [start, end] = filter.number_of_rentalsRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, number_of_rentals: { ...where.number_of_rentals, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, number_of_rentals: { ...where.number_of_rentals, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.companies) { const listItems = filter.companies.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, companiesId: { [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.companiesId; } 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, globalAccess, organizationId, ) { let where = {}; if (!globalAccess && organizationId) { where.organizationId = organizationId; } if (query) { where = { [Op.or]: [ { ['id']: Utils.uuid(query) }, Utils.ilike('inventory', 'name', query), ], }; } const records = await db.inventory.findAll({ attributes: ['id', 'name'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['name', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.name, })); } };