38667-vm/backend/src/db/api/products.js
2026-02-21 13:56:02 +00:00

696 lines
17 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 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,
tiktok_product_key: data.tiktok_product_key
||
null
,
title: data.title
||
null
,
price: data.price
||
null
,
currency: data.currency
||
null
,
shop_name: data.shop_name
||
null
,
shop_key: data.shop_key
||
null
,
category: data.category
||
null
,
primary_image_url: data.primary_image_url
||
null
,
product_url: data.product_url
||
null
,
is_active: data.is_active
||
false
,
first_seen_at: data.first_seen_at
||
null
,
last_seen_at: data.last_seen_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
belongsToId: products.id,
},
data.product_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,
tiktok_product_key: item.tiktok_product_key
||
null
,
title: item.title
||
null
,
price: item.price
||
null
,
currency: item.currency
||
null
,
shop_name: item.shop_name
||
null
,
shop_key: item.shop_key
||
null
,
category: item.category
||
null
,
primary_image_url: item.primary_image_url
||
null
,
product_url: item.product_url
||
null
,
is_active: item.is_active
||
false
,
first_seen_at: item.first_seen_at
||
null
,
last_seen_at: item.last_seen_at
||
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: 'product_images',
belongsToId: products[i].id,
},
data[i].product_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 updatePayload = {};
if (data.tiktok_product_key !== undefined) updatePayload.tiktok_product_key = data.tiktok_product_key;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.shop_name !== undefined) updatePayload.shop_name = data.shop_name;
if (data.shop_key !== undefined) updatePayload.shop_key = data.shop_key;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.primary_image_url !== undefined) updatePayload.primary_image_url = data.primary_image_url;
if (data.product_url !== undefined) updatePayload.product_url = data.product_url;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.first_seen_at !== undefined) updatePayload.first_seen_at = data.first_seen_at;
if (data.last_seen_at !== undefined) updatePayload.last_seen_at = data.last_seen_at;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
belongsToId: products.id,
},
data.product_images,
options,
);
return products;
}
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.product_metrics_product = await products.getProduct_metrics_product({
transaction
});
output.viral_videos_product = await products.getViral_videos_product({
transaction
});
output.supplier_matches_product = await products.getSupplier_matches_product({
transaction
});
output.user_tracked_products_product = await products.getUser_tracked_products_product({
transaction
});
output.product_images = await products.getProduct_images({
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.file,
as: 'product_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tiktok_product_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'tiktok_product_key',
filter.tiktok_product_key,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'title',
filter.title,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'currency',
filter.currency,
),
};
}
if (filter.shop_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'shop_name',
filter.shop_name,
),
};
}
if (filter.shop_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'shop_key',
filter.shop_key,
),
};
}
if (filter.category) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'category',
filter.category,
),
};
}
if (filter.primary_image_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'primary_image_url',
filter.primary_image_url,
),
};
}
if (filter.product_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'product_url',
filter.product_url,
),
};
}
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.first_seen_atRange) {
const [start, end] = filter.first_seen_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
first_seen_at: {
...where.first_seen_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
first_seen_at: {
...where.first_seen_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_seen_atRange) {
const [start, end] = filter.last_seen_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_seen_at: {
...where.last_seen_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_seen_at: {
...where.last_seen_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
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.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,
}));
}
};