115 lines
4.2 KiB
TypeScript
115 lines
4.2 KiB
TypeScript
import { mapWithConcurrency } from "@toolctrl/foundation";
|
|
|
|
/**
|
|
* Marketing-Funnel Phase 3 (Phase 05 #80) — trial-expiring trigger cron.
|
|
*
|
|
* Daily cron-style worker that scans active tenant subscriptions whose
|
|
* trial window ends within the configured horizon (default 3 days).
|
|
* For every match a `tenant.trial_expiring` outbox event is emitted;
|
|
* downstream the email-sequence trigger handler enrols
|
|
* trial-reminder sequences.
|
|
*
|
|
* Storage + clock + outbox publisher are injected so the handler is
|
|
* fully unit-testable. Intended production wiring is a daily BullMQ
|
|
* scheduled-job from `apps/worker/src/index.ts`; as of this slice the
|
|
* runner is not registered by the worker entrypoint.
|
|
*
|
|
* Idempotency: the dispatchKey is
|
|
* `tenant.trial_expiring.<tenantId>.<YYYY-MM-DD>` so re-running the
|
|
* cron on the same day is a no-op even on worker restart.
|
|
*/
|
|
|
|
export interface TrialExpiringRow {
|
|
readonly tenantId: string;
|
|
readonly tenantEmail: string | null;
|
|
readonly tenantName: string | null;
|
|
readonly trialEndsAt: Date;
|
|
}
|
|
|
|
export interface TrialExpiringStore {
|
|
findExpiringTrials(args: { now: Date; horizonDays: number; limit: number }): Promise<readonly TrialExpiringRow[]>;
|
|
}
|
|
|
|
export interface TrialExpiringPublisher {
|
|
publish(args: { type: string; payload: Record<string, unknown>; dispatchKey: string; tenantId?: string | null }): Promise<{ ok: boolean }>;
|
|
}
|
|
|
|
export interface TrialExpiringLogger {
|
|
info?: (record: Record<string, unknown>, message?: string) => void;
|
|
warn?: (record: Record<string, unknown>, message?: string) => void;
|
|
error: (record: Record<string, unknown>, message?: string) => void;
|
|
}
|
|
|
|
export interface TrialExpiringCronDeps {
|
|
readonly store: TrialExpiringStore;
|
|
readonly publisher: TrialExpiringPublisher;
|
|
readonly logger?: TrialExpiringLogger;
|
|
readonly now?: () => Date;
|
|
/** Trial-end horizon in days. Default 3 (matches "Trial Expiring" sequence). */
|
|
readonly horizonDays?: number;
|
|
/** Hard cap per cron tick. */
|
|
readonly limit?: number;
|
|
/** Max outbox publishes at once. Default 10. */
|
|
readonly concurrency?: number;
|
|
}
|
|
|
|
export interface TrialExpiringCronResult {
|
|
readonly scanned: number;
|
|
readonly emitted: number;
|
|
readonly skipped: number;
|
|
}
|
|
|
|
const DEFAULT_HORIZON_DAYS = 3;
|
|
const DEFAULT_LIMIT = 500;
|
|
|
|
function isoDate(d: Date): string {
|
|
return d.toISOString().slice(0, 10);
|
|
}
|
|
|
|
export async function runTrialExpiringTriggerCron(deps: TrialExpiringCronDeps): Promise<TrialExpiringCronResult> {
|
|
if (process.env.MARKETING_SEQUENCES_ENABLED !== "true") {
|
|
deps.logger?.info?.({ op: "trial.expiring.skipped" }, "marketing sequences disabled by env");
|
|
return { scanned: 0, emitted: 0, skipped: 0 };
|
|
}
|
|
const now = (deps.now ?? (() => new Date()))();
|
|
const horizonDays = deps.horizonDays ?? DEFAULT_HORIZON_DAYS;
|
|
const limit = deps.limit ?? DEFAULT_LIMIT;
|
|
const today = isoDate(now);
|
|
|
|
const rows = await deps.store.findExpiringTrials({ now, horizonDays, limit });
|
|
let emitted = 0;
|
|
let skipped = 0;
|
|
await mapWithConcurrency(rows, deps.concurrency ?? 10, async (row) => {
|
|
const daysRemaining = Math.max(0, Math.ceil((row.trialEndsAt.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)));
|
|
const dispatchKey = `tenant.trial_expiring.${row.tenantId}.${today}`;
|
|
try {
|
|
await deps.publisher.publish({
|
|
type: "tenant.trial_expiring",
|
|
tenantId: row.tenantId,
|
|
payload: {
|
|
tenantId: row.tenantId,
|
|
email: row.tenantEmail,
|
|
recipientName: row.tenantName,
|
|
tenant: {
|
|
id: row.tenantId,
|
|
name: row.tenantName,
|
|
email: row.tenantEmail,
|
|
trialEndsAt: row.trialEndsAt.toISOString(),
|
|
},
|
|
daysRemaining,
|
|
},
|
|
dispatchKey,
|
|
});
|
|
emitted += 1;
|
|
} catch (error) {
|
|
skipped += 1;
|
|
deps.logger?.error(
|
|
{ op: "trial.expiring.publish_failed", tenantId: row.tenantId, error: error instanceof Error ? error.message : String(error) },
|
|
"trial-expiring outbox publish failed"
|
|
);
|
|
}
|
|
});
|
|
deps.logger?.info?.({ op: "trial.expiring.done", scanned: rows.length, emitted, skipped, horizonDays }, "trial-expiring trigger cron complete");
|
|
return { scanned: rows.length, emitted, skipped };
|
|
}
|