import { Result } from "sim-shared/domain/Result.js"; import { QueryResult } from "pg"; import { PgClient } from "sim-shared/infrastructure/PgClient.js"; import { AxiosError } from "axios"; export type PauseCancelTask = { id: number; iccid: string; operation_type: "suspend" | "terminate", last_checked?: Date | null; activation_date?: Date | null; next_check?: Date | null; completed_date?: Date | null; error?: string | null; } export type CreatePauseCancelTaskDTO = Pick export type UpdatePauseCancelTaskDTO = Pick export type FinishPauseCancelTaskDTO = Pick /** * Repositorio para compensar los problemas de cacelcaiones/pausas de objenious a * la hora aplicarlo sobre una linea con el billing a test. */ export class PauseCancelTaskRepository { constructor( private readonly pgClient: PgClient ) { } /** * Obtiene las siguientes que se pueden lanzar, puede haber más pero * estan pendientes */ public async getPending(): Promise> { const sql = ` SELECT * FROM pause_cancel_tasks WHERE completed_date IS NULL AND (next_check <= NOW() OR next_check IS NULL) ORDER BY id ASC; `; try { const res: QueryResult = await this.pgClient.query(sql); return { data: res.rows } } catch (e) { return { error: (e as AxiosError).message } } } public async addTask(task: CreatePauseCancelTaskDTO): Promise> { const sql = ` INSERT INTO pause_cancel_tasks (iccid, activation_date, next_check, last_checked, operation_type) VALUES ($1, $2, $3, now(), $4) RETURNING *; `; try { const values = [task.iccid, task.activation_date, task.next_check, task.operation_type]; const res: QueryResult = await this.pgClient.query(sql, values); return { data: res.rows[0] } } catch (e) { return { error: (e as AxiosError).message } } } /** * Se ha vuelto a comprobar la tarea pero sigue en test */ public async updateTask(updateData: UpdatePauseCancelTaskDTO): Promise> { const sql = ` UPDATE pause_cancel_tasks SET last_checked = now(), next_check = $1 WHERE id = $2 RETURNING *; `; try { const res = await this.pgClient.query(sql, [updateData.next_check, updateData.id]); return { data: res.rows[0] } } catch (e) { return { error: (e as AxiosError).message } } } /** * La tarea ha termiando bien o mal */ public async finishTask(finishData: FinishPauseCancelTaskDTO) { const sql = ` UPDATE pause_cancel_tasks SET completed_date = NOW(), error = $1 WHERE id = $2 RETURNING *; `; try { const res = await this.pgClient.query(sql, [finishData.error, finishData.id]); return { data: res.rows[0] } } catch (e) { return { error: (e as AxiosError).message } } } }