38293-vm/backend/src/db/api/product_variants.js
2026-02-08 15:46:10 +00:00

610 lines
15 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 Product_variantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.create(
{
id: data.id || undefined,
variant_name: data.variant_name
||
null
,
sku: data.sku
||
null
,
size: data.size
||
null
,
color_name: data.color_name
||
null
,
color_hex: data.color_hex
||
null
,
price: data.price
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await product_variants.setProduct( data.product || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: product_variants.id,
},
data.images,
options,
);
return product_variants;
}
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 product_variantsData = data.map((item, index) => ({
id: item.id || undefined,
variant_name: item.variant_name
||
null
,
sku: item.sku
||
null
,
size: item.size
||
null
,
color_name: item.color_name
||
null
,
color_hex: item.color_hex
||
null
,
price: item.price
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const product_variants = await db.product_variants.bulkCreate(product_variantsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < product_variants.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: product_variants[i].id,
},
data[i].images,
options,
);
}
return product_variants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.variant_name !== undefined) updatePayload.variant_name = data.variant_name;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.size !== undefined) updatePayload.size = data.size;
if (data.color_name !== undefined) updatePayload.color_name = data.color_name;
if (data.color_hex !== undefined) updatePayload.color_hex = data.color_hex;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await product_variants.update(updatePayload, {transaction});
if (data.product !== undefined) {
await product_variants.setProduct(
data.product,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: product_variants.id,
},
data.images,
options,
);
return product_variants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of product_variants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of product_variants) {
await record.destroy({transaction});
}
});
return product_variants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findByPk(id, options);
await product_variants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await product_variants.destroy({
transaction
});
return product_variants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findOne(
{ where },
{ transaction },
);
if (!product_variants) {
return product_variants;
}
const output = product_variants.get({plain: true});
output.cart_items_product_variant = await product_variants.getCart_items_product_variant({
transaction
});
output.product = await product_variants.getProduct({
transaction
});
output.images = await product_variants.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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.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.variant_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'variant_name',
filter.variant_name,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'sku',
filter.sku,
),
};
}
if (filter.color_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'color_name',
filter.color_name,
),
};
}
if (filter.color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'color_hex',
filter.color_hex,
),
};
}
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.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.size) {
where = {
...where,
size: filter.size,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_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.product_variants.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(
'product_variants',
'variant_name',
query,
),
],
};
}
const records = await db.product_variants.findAll({
attributes: [ 'id', 'variant_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['variant_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.variant_name,
}));
}
};