37980-vm/backend/src/db/api/products.js
2026-01-30 19:04:14 +00:00

736 lines
19 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const EmailSender = require('../../services/email');
const BackInStockEmail = require('../../services/email/list/backInStock');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProductsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.create(
{
id: data.id || undefined,
title: data.title
||
null
,
slug: data.slug
||
null
,
description: data.description
||
null
,
price: data.price
||
null
,
sku: data.sku
||
null
,
stock: data.stock
||
null
,
active: data.active
||
false
,
created_on: data.created_on
||
null
,
updated_on: data.updated_on
||
null
,
sellerId: data.sellerId || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await products.setCategory( data.category || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'images',
belongsToId: products.id,
},
data.images,
options,
);
return products;
}
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 productsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
slug: item.slug
||
null
,
description: item.description
||
null
,
price: item.price
||
null
,
sku: item.sku
||
null
,
stock: item.stock
||
null
,
active: item.active
||
false
,
created_on: item.created_on
||
null
,
updated_on: item.updated_on
||
null
,
sellerId: item.sellerId || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const products = await db.products.bulkCreate(productsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < products.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'images',
belongsToId: products[i].id,
},
data[i].images,
options,
);
}
return products;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, {}, {transaction});
const oldStock = Number(products.stock || 0);
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.stock !== undefined) updatePayload.stock = data.stock;
if (data.active !== undefined) updatePayload.active = data.active;
if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
if (data.updated_on !== undefined) updatePayload.updated_on = data.updated_on;
if (data.sellerId !== undefined) updatePayload.sellerId = data.sellerId;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
if (data.category !== undefined) {
await products.setCategory(
data.category,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'images',
belongsToId: products.id,
},
data.images,
options,
);
const newStock = Number(products.stock || 0);
if (oldStock === 0 && newStock > 0) {
this.sendBackInStockNotifications(products).catch(console.error);
}
return products;
}
static async sendBackInStockNotifications(product) {
try {
const wishlists = await db.wishlists.findAll({
where: { productId: product.id },
include: [{ model: db.users, as: 'user' }]
});
for (const wishlist of wishlists) {
if (wishlist.user && wishlist.user.email) {
const productUrl = `${config.uiUrl}/products/${product.id}`;
const email = new BackInStockEmail(
wishlist.user.email,
product.title,
productUrl
);
if (EmailSender.isConfigured) {
await new EmailSender(email).send();
} else {
console.log('Email not configured, skipping back in stock notification for', wishlist.user.email);
}
}
}
} catch (error) {
console.error('Error sending back in stock notifications:', error);
}
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of products) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of products) {
await record.destroy({transaction});
}
});
return products;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, options);
await products.update({
deletedBy: currentUser.id
}, {
transaction,
});
await products.destroy({
transaction
});
return products;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findOne(
{ where },
{ transaction },
);
if (!products) {
return products;
}
const output = products.get({plain: true});
output.order_items_product = await products.getOrder_items_product({
transaction
});
output.cart_items_product = await products.getCart_items_product({
transaction
});
output.images = await products.getImages({
transaction
});
output.category = await products.getCategory({
transaction
});
output.reviews = await products.getReviews({
transaction,
include: [{ model: db.users, as: 'user', attributes: ['id', 'firstName', 'lastName'] }],
order: [['createdAt', 'DESC']]
});
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.categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'images',
},
{
model: db.reviews,
as: 'reviews',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.sellerId) {
where = {
...where,
sellerId: Utils.uuid(filter.sellerId),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'title',
filter.title,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'slug',
filter.slug,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'description',
filter.description,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'sku',
filter.sku,
),
};
}
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.stockRange) {
const [start, end] = filter.stockRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stock: {
...where.stock,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stock: {
...where.stock,
[Op.lte]: end,
},
};
}
}
if (filter.created_onRange) {
const [start, end] = filter.created_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.lte]: end,
},
};
}
}
if (filter.updated_onRange) {
const [start, end] = filter.updated_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_on: {
...where.updated_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_on: {
...where.updated_on,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.products.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(
'products',
'title',
query,
),
],
};
}
const records = await db.products.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,
}));
}
static async getRecommendations(productId, limit = 4) {
const product = await db.products.findByPk(productId);
if (!product) return [];
return db.products.findAll({
where: {
id: { [Op.ne]: productId },
categoryId: product.categoryId,
active: true
},
include: [
{ model: db.file, as: 'images' },
{ model: db.categories, as: 'category' }
],
limit: Number(limit),
order: db.sequelize.random() // Random recommendations from same category
});
}
};