feat(notificaciones): global send flags + editable schedules
The "Flags del envío" panel lived inside the Servicios tab and only
governed the four bulk jobs. The pólizas half had no debug at all, so
there was no way to test a renewal notice without mailing a real
customer. The panel now lives in the /notificaciones shell above the
tabs and both halves read it.
`debug` on the renewal path diverts to the same override inbox as the
servicios jobs and deliberately does NOT write the `RenewalNotice` row
or advance the sweep's `lastSuccessfulAt` — the customer was not
notified, so nothing may gate the letter they are still owed.
`ignoreDayRestriction` and `useEmailLimit` stay estado-de-cuenta-only
and are labelled as such.
Both automatic sweeps are now operator-editable. The renewal cadence
was a `@Cron("0 6 * * *")` literal and servicios had no automatic run
at all; both now resolve through `NotificationScheduleService`, which
stores the cadence in `app_settings` and reinstalls the cron job on
save — no redeploy, no restart. Defaults preserve current behaviour:
pólizas 06:00 daily, servicios off. A scheduled run never inherits the
UI flags; it always sends for real.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,12 +4,17 @@ import {
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
ServiceUnavailableException,
|
||||
} from "@nestjs/common";
|
||||
import { Cron } from "@nestjs/schedule";
|
||||
import { AuditService } from "../common/audit.service";
|
||||
import { MailService } from "../mail/mail.service";
|
||||
import { NotificationLogService } from "../notifications/notification-log.service";
|
||||
import {
|
||||
NotificationScheduleService,
|
||||
SCHEDULE_TIME_ZONE,
|
||||
} from "../notifications/notification-schedule.service";
|
||||
import { DEBUG_RECIPIENT } from "../notifications/notification.types";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
RenewalLetterPolicy,
|
||||
@@ -25,7 +30,9 @@ export const RENEWAL_CADENCE = [
|
||||
] as const;
|
||||
|
||||
const JOB_NAME = "renewal-email-sweep";
|
||||
const TIME_ZONE = "America/Tijuana";
|
||||
/** The window maths runs in office time; the cadence itself is owned by
|
||||
* `NotificationScheduleService`, which uses the same zone. */
|
||||
const TIME_ZONE = SCHEDULE_TIME_ZONE;
|
||||
const DAY_MS = 86400000;
|
||||
|
||||
export function dateInTimeZone(now: Date, timeZone = TIME_ZONE): Date {
|
||||
@@ -57,7 +64,7 @@ export function renewalWindow(
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RenewalsService {
|
||||
export class RenewalsService implements OnModuleInit {
|
||||
private readonly logger = new Logger(RenewalsService.name);
|
||||
|
||||
constructor(
|
||||
@@ -65,9 +72,19 @@ export class RenewalsService {
|
||||
private readonly mail: MailService,
|
||||
private readonly audit: AuditService,
|
||||
private readonly notificationLog: NotificationLogService,
|
||||
private readonly schedule: NotificationScheduleService,
|
||||
) {}
|
||||
|
||||
@Cron("0 6 * * *", { timeZone: TIME_ZONE })
|
||||
/** The cadence used to be a `@Cron("0 6 * * *")` literal here; it is now
|
||||
* operator-editable, and the stored value defaults to that same 06:00
|
||||
* daily run. */
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.schedule.register("polizas", () => this.scheduledSweep());
|
||||
}
|
||||
|
||||
/** The unattended run always sends for real: `debug` is a per-click switch
|
||||
* in the UI, never persisted, so the schedule cannot inherit a forgotten
|
||||
* test toggle and silently stop mailing customers. */
|
||||
async scheduledSweep(): Promise<void> {
|
||||
try {
|
||||
await this.sweep();
|
||||
@@ -105,7 +122,8 @@ export class RenewalsService {
|
||||
);
|
||||
}
|
||||
|
||||
async sweep(userId?: string) {
|
||||
async sweep(userId?: string, flags: { debug?: boolean } = {}) {
|
||||
const debug = !!flags.debug;
|
||||
const now = new Date();
|
||||
const state = await this.acquireLock(now);
|
||||
|
||||
@@ -138,13 +156,14 @@ export class RenewalsService {
|
||||
// HTTP response.
|
||||
await this.recordLog(policy, cadence.generation, "", {
|
||||
status: "SKIPPED_NO_EMAIL",
|
||||
debug,
|
||||
});
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.deliver(policy, cadence.generation, to, userId);
|
||||
await this.deliver(policy, cadence.generation, to, userId, debug);
|
||||
sent++;
|
||||
} catch (error) {
|
||||
failures.push({
|
||||
@@ -156,8 +175,18 @@ export class RenewalsService {
|
||||
}
|
||||
}
|
||||
|
||||
const result = { eligible, sent, skipped, failed: failures.length, failures };
|
||||
await this.releaseLock(failures.length === 0 ? now : null);
|
||||
const result = {
|
||||
eligible,
|
||||
sent,
|
||||
skipped,
|
||||
failed: failures.length,
|
||||
failures,
|
||||
debug,
|
||||
};
|
||||
// A debug run must not advance `lastSuccessfulAt`: it wrote no
|
||||
// RenewalNotice rows, so the days it "covered" are still owed, and
|
||||
// narrowing tomorrow's window back to a single day would drop them.
|
||||
await this.releaseLock(!debug && failures.length === 0 ? now : null);
|
||||
void this.audit.log(userId, "renewalNotice.sweep", result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -172,8 +201,17 @@ export class RenewalsService {
|
||||
* so a letter sent by hand is marked exactly like a swept one and drops
|
||||
* off the pending list. Refuses a generation already sent so a double
|
||||
* click can't mail the customer twice.
|
||||
*
|
||||
* Under `debug` the notice is NOT marked as sent, so the row stays in the
|
||||
* pending list — the customer has still not been told anything.
|
||||
*/
|
||||
async sendOne(policyId: string, generation: number, userId?: string) {
|
||||
async sendOne(
|
||||
policyId: string,
|
||||
generation: number,
|
||||
userId?: string,
|
||||
flags: { debug?: boolean } = {},
|
||||
) {
|
||||
const debug = !!flags.debug;
|
||||
if (!this.mail.available) {
|
||||
throw new ServiceUnavailableException(
|
||||
"El servicio de correo no está configurado.",
|
||||
@@ -195,16 +233,21 @@ export class RenewalsService {
|
||||
throw new BadRequestException("El cliente no tiene correo registrado.");
|
||||
}
|
||||
|
||||
const { sentAt, providerMessageId } = await this.deliver(
|
||||
const { sentAt, providerMessageId, addressedTo } = await this.deliver(
|
||||
policy,
|
||||
generation,
|
||||
to,
|
||||
userId,
|
||||
debug,
|
||||
);
|
||||
return {
|
||||
policyId,
|
||||
generation,
|
||||
to,
|
||||
// The address the mail actually went to — under debug that is the
|
||||
// override inbox, and the UI says so rather than claiming the customer
|
||||
// was notified.
|
||||
to: addressedTo,
|
||||
debug,
|
||||
sentAt: sentAt.toISOString(),
|
||||
providerMessageId,
|
||||
};
|
||||
@@ -216,67 +259,79 @@ export class RenewalsService {
|
||||
* pending list, and an `email_notification_log` row, which is the send
|
||||
* history the /notificaciones "Registro de envíos" reads. A failed send
|
||||
* writes only the second — there is no notice to gate on — and rethrows so
|
||||
* the sweep counts it as a failure. */
|
||||
* the sweep counts it as a failure.
|
||||
*
|
||||
* Under `debug` the mail is diverted to `DEBUG_RECIPIENT` and the
|
||||
* `RenewalNotice` row is deliberately skipped: the customer was not
|
||||
* notified, so nothing may gate the letter they are still owed. Only the
|
||||
* log row is written, flagged `debug`. */
|
||||
private async deliver(
|
||||
policy: RenewalLetterPolicy,
|
||||
generation: number,
|
||||
to: string,
|
||||
userId?: string,
|
||||
debug = false,
|
||||
) {
|
||||
const letter = toRenewalLetterRow(policy, generation);
|
||||
const message = renderRenewalEmail(letter);
|
||||
const addressedTo = debug ? DEBUG_RECIPIENT : to;
|
||||
|
||||
let result: Awaited<ReturnType<MailService["send"]>>;
|
||||
try {
|
||||
result = await this.mail.send({
|
||||
to,
|
||||
to: addressedTo,
|
||||
toName: letter.customerName,
|
||||
subject: message.subject,
|
||||
html: message.html,
|
||||
xTracking: "renewals",
|
||||
xTracking: debug ? "debug" : "renewals",
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
await this.recordLog(policy, generation, to, {
|
||||
await this.recordLog(policy, generation, addressedTo, {
|
||||
status: "FAILED",
|
||||
error: detail,
|
||||
debug,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
const sentAt = new Date();
|
||||
|
||||
await this.prisma.renewalNotice.upsert({
|
||||
where: {
|
||||
policyId_generation: { policyId: policy.id, generation },
|
||||
},
|
||||
create: {
|
||||
policyId: policy.id,
|
||||
generation,
|
||||
channel: "EMAIL",
|
||||
sentAt,
|
||||
sentById: userId,
|
||||
providerMessageId: result.messageId,
|
||||
},
|
||||
update: {
|
||||
channel: "EMAIL",
|
||||
sentAt,
|
||||
sentById: userId,
|
||||
providerMessageId: result.messageId,
|
||||
},
|
||||
});
|
||||
await this.recordLog(policy, generation, to, {
|
||||
if (!debug) {
|
||||
await this.prisma.renewalNotice.upsert({
|
||||
where: {
|
||||
policyId_generation: { policyId: policy.id, generation },
|
||||
},
|
||||
create: {
|
||||
policyId: policy.id,
|
||||
generation,
|
||||
channel: "EMAIL",
|
||||
sentAt,
|
||||
sentById: userId,
|
||||
providerMessageId: result.messageId,
|
||||
},
|
||||
update: {
|
||||
channel: "EMAIL",
|
||||
sentAt,
|
||||
sentById: userId,
|
||||
providerMessageId: result.messageId,
|
||||
},
|
||||
});
|
||||
}
|
||||
await this.recordLog(policy, generation, addressedTo, {
|
||||
status: "SENT",
|
||||
providerMessageId: result.messageId || undefined,
|
||||
providerResponse: result.response || undefined,
|
||||
sendDate: sentAt,
|
||||
debug,
|
||||
});
|
||||
void this.audit.log(userId, "renewalNotice.send", {
|
||||
policyId: policy.id,
|
||||
generation,
|
||||
debug,
|
||||
providerMessageId: result.messageId,
|
||||
});
|
||||
return { sentAt, providerMessageId: result.messageId };
|
||||
return { sentAt, providerMessageId: result.messageId, addressedTo };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -299,6 +354,7 @@ export class RenewalsService {
|
||||
providerResponse?: string;
|
||||
error?: string;
|
||||
sendDate?: Date;
|
||||
debug?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
const letter = toRenewalLetterRow(policy, generation);
|
||||
@@ -317,7 +373,7 @@ export class RenewalsService {
|
||||
subject: message.subject,
|
||||
bodySnapshot: message.html,
|
||||
status: outcome.status,
|
||||
debug: false,
|
||||
debug: !!outcome.debug,
|
||||
providerMessageId: outcome.providerMessageId,
|
||||
providerResponse: outcome.providerResponse,
|
||||
error: outcome.error,
|
||||
|
||||
Reference in New Issue
Block a user