Add scheduled invoice delivery

This commit is contained in:
2026-08-17 13:54:45 -04:00
parent 29589c1f32
commit 67ab6b78bd
26 changed files with 2099 additions and 835 deletions
+19 -2
View File
@@ -6,9 +6,11 @@ import {
completeJob,
failJob,
jobTypes,
markScheduledInvoiceJobFailed,
scheduleDueRecurringInvoiceJobs,
type BackgroundJob,
} from "../../web/src/server/jobs/queue";
import { sendScheduledInvoice } from "./send-invoice";
const workerId = `beenvoice-worker:${randomUUID()}`;
const pollMs = Number(process.env.WORKER_POLL_MS ?? 2_000);
@@ -17,7 +19,11 @@ let stopping = false;
let working = false;
let scheduling = false;
function log(level: "info" | "error", event: string, fields: Record<string, unknown> = {}) {
function log(
level: "info" | "error",
event: string,
fields: Record<string, unknown> = {},
) {
const record = JSON.stringify({
timestamp: new Date().toISOString(),
level,
@@ -59,6 +65,10 @@ async function handleJob(job: BackgroundJob) {
await generateRecurringInvoice(job);
return;
}
if (job.type === jobTypes.sendInvoice) {
await sendScheduledInvoice(job);
return;
}
throw new Error(`No handler registered for ${job.type}`);
}
@@ -72,9 +82,16 @@ async function drainJobs() {
try {
await handleJob(job);
await completeJob(job.id);
log("info", "job.completed", { jobId: job.id, jobType: job.type, attempts: job.attempts });
log("info", "job.completed", {
jobId: job.id,
jobType: job.type,
attempts: job.attempts,
});
} catch (error) {
const terminal = await failJob(job, error);
if (terminal && job.type === jobTypes.sendInvoice) {
await markScheduledInvoiceJobFailed(job);
}
log("error", "job.failed", {
jobId: job.id,
jobType: job.type,
+41
View File
@@ -0,0 +1,41 @@
import type { BackgroundJob } from "../../web/src/server/jobs/queue";
function requiredPayloadString(job: BackgroundJob, key: string): string {
const value = job.payload[key];
if (typeof value !== "string" || !value) {
throw new Error(`Invalid scheduled invoice job payload: ${key}`);
}
return value;
}
export async function sendScheduledInvoice(job: BackgroundJob) {
const appUrl =
process.env.APP_INTERNAL_URL?.replace(/\/$/, "") ?? "http://app:3000";
const secret = process.env.CRON_SECRET;
if (!secret)
throw new Error("CRON_SECRET is required for scheduled invoice delivery");
const response = await fetch(`${appUrl}/api/internal/jobs/send-invoice`, {
method: "POST",
headers: {
Authorization: `Bearer ${secret}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
...job.payload,
jobId: job.id,
idempotencyKey: job.idempotencyKey,
invoiceId: requiredPayloadString(job, "invoiceId"),
actorUserId: requiredPayloadString(job, "actorUserId"),
}),
});
const result = (await response.json().catch(() => ({}))) as {
error?: string;
};
if (!response.ok) {
throw new Error(
result.error ?? `Invoice delivery request failed (${response.status})`,
);
}
return result;
}