31818/backend/src/db/api/matches.js
2025-05-28 13:39:48 +00:00

425 lines
10 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 MatchesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matches = await db.matches.create(
{
id: data.id || undefined,
match_date: data.match_date || null,
home_score: data.home_score || null,
away_score: data.away_score || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await matches.setHome_team(data.home_team || null, {
transaction,
});
await matches.setAway_team(data.away_team || null, {
transaction,
});
return matches;
}
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 matchesData = data.map((item, index) => ({
id: item.id || undefined,
match_date: item.match_date || null,
home_score: item.home_score || null,
away_score: item.away_score || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const matches = await db.matches.bulkCreate(matchesData, { transaction });
// For each item created, replace relation files
return matches;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matches = await db.matches.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.match_date !== undefined)
updatePayload.match_date = data.match_date;
if (data.home_score !== undefined)
updatePayload.home_score = data.home_score;
if (data.away_score !== undefined)
updatePayload.away_score = data.away_score;
updatePayload.updatedById = currentUser.id;
await matches.update(updatePayload, { transaction });
if (data.home_team !== undefined) {
await matches.setHome_team(
data.home_team,
{ transaction },
);
}
if (data.away_team !== undefined) {
await matches.setAway_team(
data.away_team,
{ transaction },
);
}
return matches;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matches = await db.matches.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of matches) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of matches) {
await record.destroy({ transaction });
}
});
return matches;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matches = await db.matches.findByPk(id, options);
await matches.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await matches.destroy({
transaction,
});
return matches;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const matches = await db.matches.findOne({ where }, { transaction });
if (!matches) {
return matches;
}
const output = matches.get({ plain: true });
output.home_team = await matches.getHome_team({
transaction,
});
output.away_team = await matches.getAway_team({
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.teams,
as: 'home_team',
where: filter.home_team
? {
[Op.or]: [
{
id: {
[Op.in]: filter.home_team
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.home_team
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.teams,
as: 'away_team',
where: filter.away_team
? {
[Op.or]: [
{
id: {
[Op.in]: filter.away_team
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.away_team
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
match_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
match_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.match_dateRange) {
const [start, end] = filter.match_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
match_date: {
...where.match_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
match_date: {
...where.match_date,
[Op.lte]: end,
},
};
}
}
if (filter.home_scoreRange) {
const [start, end] = filter.home_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
home_score: {
...where.home_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
home_score: {
...where.home_score,
[Op.lte]: end,
},
};
}
}
if (filter.away_scoreRange) {
const [start, end] = filter.away_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
away_score: {
...where.away_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
away_score: {
...where.away_score,
[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.matches.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('matches', 'match_date', query),
],
};
}
const records = await db.matches.findAll({
attributes: ['id', 'match_date'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['match_date', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.match_date,
}));
}
};