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 ListingsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const listings = await db.listings.create( { id: data.id || undefined, title: data.title || null, quantity: data.quantity || null, price: data.price || null, harvest_date: data.harvest_date || null, availability_date: data.availability_date || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await listings.setFarmer(data.farmer || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.listings.getTableName(), belongsToColumn: 'images', belongsToId: listings.id, }, data.images, options, ); return listings; } 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 listingsData = data.map((item, index) => ({ id: item.id || undefined, title: item.title || null, quantity: item.quantity || null, price: item.price || null, harvest_date: item.harvest_date || null, availability_date: item.availability_date || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const listings = await db.listings.bulkCreate(listingsData, { transaction, }); // For each item created, replace relation files for (let i = 0; i < listings.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.listings.getTableName(), belongsToColumn: 'images', belongsToId: listings[i].id, }, data[i].images, options, ); } return listings; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const listings = await db.listings.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.title !== undefined) updatePayload.title = data.title; if (data.quantity !== undefined) updatePayload.quantity = data.quantity; if (data.price !== undefined) updatePayload.price = data.price; if (data.harvest_date !== undefined) updatePayload.harvest_date = data.harvest_date; if (data.availability_date !== undefined) updatePayload.availability_date = data.availability_date; updatePayload.updatedById = currentUser.id; await listings.update(updatePayload, { transaction }); if (data.farmer !== undefined) { await listings.setFarmer( data.farmer, { transaction }, ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.listings.getTableName(), belongsToColumn: 'images', belongsToId: listings.id, }, data.images, options, ); return listings; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const listings = await db.listings.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of listings) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of listings) { await record.destroy({ transaction }); } }); return listings; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const listings = await db.listings.findByPk(id, options); await listings.update( { deletedBy: currentUser.id, }, { transaction, }, ); await listings.destroy({ transaction, }); return listings; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const listings = await db.listings.findOne({ where }, { transaction }); if (!listings) { return listings; } const output = listings.get({ plain: true }); output.orders_listing = await listings.getOrders_listing({ transaction, }); output.farmer = await listings.getFarmer({ transaction, }); output.images = await listings.getImages({ 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.farmers, as: 'farmer', where: filter.farmer ? { [Op.or]: [ { id: { [Op.in]: filter.farmer .split('|') .map((term) => Utils.uuid(term)), }, }, { name: { [Op.or]: filter.farmer .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.file, as: 'images', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.title) { where = { ...where, [Op.and]: Utils.ilike('listings', 'title', filter.title), }; } if (filter.calendarStart && filter.calendarEnd) { where = { ...where, [Op.or]: [ { harvest_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, { availability_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, ], }; } 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.priceRange) { const [start, end] = filter.priceRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, price: { ...where.price, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, price: { ...where.price, [Op.lte]: end, }, }; } } if (filter.harvest_dateRange) { const [start, end] = filter.harvest_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, harvest_date: { ...where.harvest_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, harvest_date: { ...where.harvest_date, [Op.lte]: end, }, }; } } if (filter.availability_dateRange) { const [start, end] = filter.availability_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, availability_date: { ...where.availability_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, availability_date: { ...where.availability_date, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } 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.listings.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('listings', 'title', query), ], }; } const records = await db.listings.findAll({ attributes: ['id', 'title'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['title', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.title, })); } };