74 lines
2.5 KiB
JavaScript
74 lines
2.5 KiB
JavaScript
const { query } = require('../database/db');
|
|
|
|
const ALLOWED_REPORT_TYPES = new Set(['daily', 'end_cycle']);
|
|
|
|
class DashboardReportSnapshot {
|
|
static normalizeReportType(reportType) {
|
|
if (reportType == null || reportType === '') return 'daily';
|
|
if (ALLOWED_REPORT_TYPES.has(reportType)) return reportType;
|
|
const error = new Error('Invalid reportType');
|
|
error.code = 'INVALID_REPORT_TYPE';
|
|
throw error;
|
|
}
|
|
|
|
static formatRow(row) {
|
|
if (!row) return null;
|
|
return {
|
|
id: row.id,
|
|
cycleId: row.cycle_id,
|
|
kandangId: row.kandang_id,
|
|
upToDay: row.up_to_day,
|
|
generatedAt: row.generated_at,
|
|
reportType: row.report_type || 'daily',
|
|
payload: row.payload,
|
|
createdAt: row.created_at,
|
|
updatedAt: row.updated_at,
|
|
};
|
|
}
|
|
|
|
static async getByCycleAndKandang(cycleId, kandangId, reportType = 'daily') {
|
|
if (kandangId === null || kandangId === undefined || kandangId === '') {
|
|
return null;
|
|
}
|
|
const type = this.normalizeReportType(reportType);
|
|
const result = await query(
|
|
`SELECT * FROM dashboard_report_snapshots
|
|
WHERE cycle_id = $1 AND kandang_id = $2 AND report_type = $3
|
|
LIMIT 1`,
|
|
[cycleId, kandangId, type]
|
|
);
|
|
return result.rows[0] ? this.formatRow(result.rows[0]) : null;
|
|
}
|
|
|
|
static async upsert({ cycleId, kandangId, upToDay, payload, generatedAt, reportType }) {
|
|
if (kandangId === null || kandangId === undefined || kandangId === '') {
|
|
throw new Error('kandangId is required');
|
|
}
|
|
if (!cycleId) {
|
|
throw new Error('cycleId is required');
|
|
}
|
|
if (upToDay === null || upToDay === undefined || !Number.isFinite(Number(upToDay))) {
|
|
throw new Error('upToDay is required');
|
|
}
|
|
|
|
const type = this.normalizeReportType(reportType);
|
|
const generated = generatedAt ? new Date(generatedAt) : new Date();
|
|
const result = await query(
|
|
`INSERT INTO dashboard_report_snapshots
|
|
(cycle_id, kandang_id, payload, up_to_day, generated_at, report_type)
|
|
VALUES ($1, $2, $3::jsonb, $4, $5, $6)
|
|
ON CONFLICT (cycle_id, kandang_id, report_type)
|
|
DO UPDATE SET
|
|
payload = EXCLUDED.payload,
|
|
up_to_day = EXCLUDED.up_to_day,
|
|
generated_at = EXCLUDED.generated_at,
|
|
updated_at = CURRENT_TIMESTAMP
|
|
RETURNING *`,
|
|
[cycleId, kandangId, JSON.stringify(payload ?? {}), Number(upToDay), generated, type]
|
|
);
|
|
return this.formatRow(result.rows[0]);
|
|
}
|
|
}
|
|
|
|
module.exports = DashboardReportSnapshot;
|