feat: add renewal invoice sweep (#20)
Refs #9 ## Summary - add a worker-side renewal invoice sweep that creates one invoice 72 hours before subscription expiry - expire elapsed pending invoices automatically and email users when an automatic renewal invoice is created - stop auto-recreating invoices for the same paid cycle once any invoice already exists for that cycle - document the current renewal-invoice and pending-invoice expiry behavior ## Testing - built `infra/docker/web.Dockerfile` - ran `pnpm --filter @nproxy/db test` inside the built container - verified `@nproxy/db build` and `@nproxy/web build` during the image build - built `infra/docker/worker.Dockerfile` Co-authored-by: sirily <sirily@git.shararam.party> Reviewed-on: #20
This commit was merged in pull request #20.
This commit is contained in:
@@ -1,20 +1,30 @@
|
||||
import { loadConfig } from "@nproxy/config";
|
||||
import { createPrismaWorkerStore, prisma } from "@nproxy/db";
|
||||
import { createNanoBananaSimulatedAdapter } from "@nproxy/providers";
|
||||
import { createPrismaBillingStore, createPrismaWorkerStore, prisma } from "@nproxy/db";
|
||||
import {
|
||||
createEmailTransport,
|
||||
createNanoBananaSimulatedAdapter,
|
||||
createPaymentProviderAdapter,
|
||||
} from "@nproxy/providers";
|
||||
|
||||
const config = loadConfig();
|
||||
const intervalMs = config.keyPool.balancePollSeconds * 1000;
|
||||
const renewalLeadTimeHours = 72;
|
||||
const invoiceReconciliationBatchSize = 100;
|
||||
const workerStore = createPrismaWorkerStore(prisma, {
|
||||
cooldownMinutes: config.keyPool.cooldownMinutes,
|
||||
failuresBeforeManualReview: config.keyPool.failuresBeforeManualReview,
|
||||
});
|
||||
const billingStore = createPrismaBillingStore(prisma);
|
||||
const nanoBananaAdapter = createNanoBananaSimulatedAdapter();
|
||||
const paymentProviderAdapter = createPaymentProviderAdapter(config.payment);
|
||||
const emailTransport = createEmailTransport(config.email);
|
||||
let isTickRunning = false;
|
||||
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
balancePollSeconds: config.keyPool.balancePollSeconds,
|
||||
renewalLeadTimeHours,
|
||||
providerModel: config.provider.nanoBananaDefaultModel,
|
||||
}),
|
||||
);
|
||||
@@ -44,6 +54,147 @@ async function runTick(): Promise<void> {
|
||||
isTickRunning = true;
|
||||
|
||||
try {
|
||||
const renewalNotifications = await billingStore.createUpcomingRenewalInvoices({
|
||||
paymentProvider: config.payment.provider,
|
||||
paymentProviderAdapter,
|
||||
renewalLeadTimeHours,
|
||||
});
|
||||
|
||||
for (const notification of renewalNotifications) {
|
||||
const billingUrl = new URL("/billing", config.urls.appBaseUrl);
|
||||
await emailTransport.send({
|
||||
to: notification.email,
|
||||
subject: "Your nproxy subscription renewal invoice",
|
||||
text: [
|
||||
"Your current subscription period is ending soon.",
|
||||
`Current access ends at ${notification.subscriptionCurrentPeriodEnd.toISOString()}.`,
|
||||
`Invoice amount: ${notification.invoice.amountCrypto} ${notification.invoice.currency}.`,
|
||||
...(notification.invoice.paymentAddress
|
||||
? [`Payment address: ${notification.invoice.paymentAddress}.`]
|
||||
: []),
|
||||
...(notification.invoice.expiresAt
|
||||
? [`Invoice expires at ${notification.invoice.expiresAt.toISOString()}.`]
|
||||
: []),
|
||||
`Open billing: ${billingUrl.toString()}`,
|
||||
].join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
if (renewalNotifications.length > 0) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
event: "renewal_invoices_created",
|
||||
createdCount: renewalNotifications.length,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const pendingInvoices =
|
||||
await billingStore.listPendingInvoicesForReconciliation(invoiceReconciliationBatchSize);
|
||||
const reconciliationSummary = {
|
||||
polledCount: pendingInvoices.length,
|
||||
markedPaidCount: 0,
|
||||
markedExpiredCount: 0,
|
||||
markedCanceledCount: 0,
|
||||
alreadyTerminalCount: 0,
|
||||
ignoredCount: 0,
|
||||
failedCount: 0,
|
||||
};
|
||||
|
||||
for (const invoice of pendingInvoices) {
|
||||
try {
|
||||
const providerInvoice = await paymentProviderAdapter.getInvoiceStatus(invoice.providerInvoiceId);
|
||||
|
||||
if (providerInvoice.providerInvoiceId !== invoice.providerInvoiceId) {
|
||||
reconciliationSummary.failedCount += 1;
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
event: "invoice_reconciliation_provider_mismatch",
|
||||
invoiceId: invoice.id,
|
||||
requestedProviderInvoiceId: invoice.providerInvoiceId,
|
||||
returnedProviderInvoiceId: providerInvoice.providerInvoiceId,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const result = await billingStore.reconcilePendingInvoice({
|
||||
invoiceId: invoice.id,
|
||||
providerStatus: providerInvoice.status,
|
||||
actor: {
|
||||
type: "system",
|
||||
ref: "invoice_reconciliation",
|
||||
},
|
||||
...(providerInvoice.paidAt ? { paidAt: providerInvoice.paidAt } : {}),
|
||||
});
|
||||
|
||||
switch (result.outcome) {
|
||||
case "marked_paid":
|
||||
reconciliationSummary.markedPaidCount += 1;
|
||||
break;
|
||||
case "marked_expired":
|
||||
reconciliationSummary.markedExpiredCount += 1;
|
||||
break;
|
||||
case "marked_canceled":
|
||||
reconciliationSummary.markedCanceledCount += 1;
|
||||
break;
|
||||
case "already_paid":
|
||||
case "already_expired":
|
||||
case "already_canceled":
|
||||
reconciliationSummary.alreadyTerminalCount += 1;
|
||||
break;
|
||||
case "ignored_terminal_state":
|
||||
reconciliationSummary.ignoredCount += 1;
|
||||
break;
|
||||
case "noop_pending":
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
reconciliationSummary.failedCount += 1;
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
event: "invoice_reconciliation_failed",
|
||||
invoiceId: invoice.id,
|
||||
providerInvoiceId: invoice.providerInvoiceId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
reconciliationSummary.polledCount > 0 ||
|
||||
reconciliationSummary.failedCount > 0 ||
|
||||
reconciliationSummary.markedPaidCount > 0 ||
|
||||
reconciliationSummary.markedExpiredCount > 0 ||
|
||||
reconciliationSummary.markedCanceledCount > 0 ||
|
||||
reconciliationSummary.alreadyTerminalCount > 0 ||
|
||||
reconciliationSummary.ignoredCount > 0
|
||||
) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
event: "pending_invoice_reconciliation",
|
||||
...reconciliationSummary,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const expiredInvoices = await billingStore.expireElapsedPendingInvoices();
|
||||
|
||||
if (expiredInvoices.expiredCount > 0) {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
service: "worker",
|
||||
event: "pending_invoices_expired",
|
||||
expiredCount: expiredInvoices.expiredCount,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const recovery = await workerStore.recoverCooldownProviderKeys();
|
||||
|
||||
if (recovery.recoveredCount > 0) {
|
||||
|
||||
Reference in New Issue
Block a user