67 lines
1.9 KiB
TypeScript
Executable File
67 lines
1.9 KiB
TypeScript
Executable File
import HistoryModel from '../models/history.model';
|
|
import { Op } from 'sequelize';
|
|
|
|
interface GetHistoryParams {
|
|
shopId?: number | null;
|
|
plu?: number | null;
|
|
action?: string | null;
|
|
dateFrom?: number | null;
|
|
dateTo?: number | null;
|
|
page?: number;
|
|
pageSize?: number;
|
|
}
|
|
|
|
interface HistoryResponse {
|
|
history: HistoryModel[];
|
|
page: number;
|
|
pageSize: number;
|
|
totalPages: number;
|
|
totalHistory: number;
|
|
}
|
|
|
|
class HistoryService {
|
|
async createHistory(action: string, shop_id: number, plu: number, old_data: JSON, new_data: JSON): Promise<HistoryModel> {
|
|
const history = await HistoryModel.create({ action, shop_id, plu, old_data, new_data });
|
|
return history;
|
|
}
|
|
|
|
async getHistory({
|
|
shopId = null,
|
|
plu = null,
|
|
action = null,
|
|
dateFrom = null,
|
|
dateTo = null,
|
|
page = 1,
|
|
pageSize = 10
|
|
}: GetHistoryParams): Promise<HistoryResponse> {
|
|
const offset = (page - 1) * pageSize;
|
|
const limit = pageSize;
|
|
|
|
const where: any = {};
|
|
if (dateFrom) {
|
|
const formattedDateFrom = new Date(dateFrom * 1000).toISOString();
|
|
where.createdAt = { ...where.createdAt, [Op.gt]: formattedDateFrom };
|
|
}
|
|
if (dateTo) {
|
|
const formattedDateTo = new Date(dateTo * 1000).toISOString();
|
|
where.createdAt = { ...where.createdAt, [Op.lt]: formattedDateTo };
|
|
}
|
|
|
|
if (shopId) where.shop_id = shopId;
|
|
if (plu) where.plu = plu;
|
|
if (action) where.action = action;
|
|
|
|
const history = await HistoryModel.findAndCountAll({ limit, offset, where });
|
|
const totalPages = Math.ceil(history.count / pageSize);
|
|
|
|
return {
|
|
history: history.rows,
|
|
page,
|
|
pageSize,
|
|
totalPages,
|
|
totalHistory: history.count
|
|
};
|
|
}
|
|
}
|
|
|
|
export default new HistoryService(); |