2026-02-02 12:41:10 +00:00

764 lines
19 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 GamesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const games = await db.games.create(
{
id: data.id || undefined,
title: data.title
||
null
,
sku: data.sku
||
null
,
description: data.description
||
null
,
price: data.price
||
null
,
discount_price: data.discount_price
||
null
,
release_date: data.release_date
||
null
,
rating: data.rating
||
null
,
stock: data.stock
||
null
,
is_featured: data.is_featured
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await games.setDeveloper( data.developer || null, {
transaction,
});
await games.setPlatforms(data.platforms || [], {
transaction,
});
await games.setGenres(data.genres || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.games.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: games.id,
},
data.cover_images,
options,
);
return games;
}
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 gamesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
sku: item.sku
||
null
,
description: item.description
||
null
,
price: item.price
||
null
,
discount_price: item.discount_price
||
null
,
release_date: item.release_date
||
null
,
rating: item.rating
||
null
,
stock: item.stock
||
null
,
is_featured: item.is_featured
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const games = await db.games.bulkCreate(gamesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < games.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.games.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: games[i].id,
},
data[i].cover_images,
options,
);
}
return games;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const games = await db.games.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.discount_price !== undefined) updatePayload.discount_price = data.discount_price;
if (data.release_date !== undefined) updatePayload.release_date = data.release_date;
if (data.rating !== undefined) updatePayload.rating = data.rating;
if (data.stock !== undefined) updatePayload.stock = data.stock;
if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
updatePayload.updatedById = currentUser.id;
await games.update(updatePayload, {transaction});
if (data.developer !== undefined) {
await games.setDeveloper(
data.developer,
{ transaction }
);
}
if (data.platforms !== undefined) {
await games.setPlatforms(data.platforms, { transaction });
}
if (data.genres !== undefined) {
await games.setGenres(data.genres, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.games.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: games.id,
},
data.cover_images,
options,
);
return games;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const games = await db.games.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of games) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of games) {
await record.destroy({transaction});
}
});
return games;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const games = await db.games.findByPk(id, options);
await games.update({
deletedBy: currentUser.id
}, {
transaction,
});
await games.destroy({
transaction
});
return games;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const games = await db.games.findOne(
{ where },
{ transaction },
);
if (!games) {
return games;
}
const output = games.get({plain: true});
output.order_items_game = await games.getOrder_items_game({
transaction
});
output.reviews_game = await games.getReviews_game({
transaction
});
output.developer = await games.getDeveloper({
transaction
});
output.cover_images = await games.getCover_images({
transaction
});
output.platforms = await games.getPlatforms({
transaction
});
output.genres = await games.getGenres({
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.developers,
as: 'developer',
where: filter.developer ? {
[Op.or]: [
{ id: { [Op.in]: filter.developer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.developer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.platforms,
as: 'platforms',
required: false,
},
{
model: db.genres,
as: 'genres',
required: false,
},
{
model: db.file,
as: 'cover_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'games',
'title',
filter.title,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'games',
'sku',
filter.sku,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'games',
'description',
filter.description,
),
};
}
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.discount_priceRange) {
const [start, end] = filter.discount_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_price: {
...where.discount_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_price: {
...where.discount_price,
[Op.lte]: end,
},
};
}
}
if (filter.release_dateRange) {
const [start, end] = filter.release_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
release_date: {
...where.release_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
release_date: {
...where.release_date,
[Op.lte]: end,
},
};
}
}
if (filter.ratingRange) {
const [start, end] = filter.ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating: {
...where.rating,
[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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_featured) {
where = {
...where,
is_featured: filter.is_featured,
};
}
if (filter.platforms) {
const searchTerms = filter.platforms.split('|');
include = [
{
model: db.platforms,
as: 'platforms_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.genres) {
const searchTerms = filter.genres.split('|');
include = [
{
model: db.genres,
as: 'genres_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
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.games.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(
'games',
'title',
query,
),
],
};
}
const records = await db.games.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,
}));
}
};