@velaro/cli 1.4.243 → 1.4.244

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,909 +0,0 @@
1
- // velaro billing-subscription — standalone, entitlement-decoupled recurring billing subscriptions
2
- // (BillingSubscriptionController). See project_billing_subscription_target_decoupling.md — these
3
- // records do not require a v20 SiteId and work for any product (v10/v20/none).
4
- import path from 'node:path';
5
- import { request } from '../api.js';
6
- import { loadStaff } from '../staff-optional.js';
7
-
8
- function money(cents) {
9
- return `$${(cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
10
- }
11
-
12
- async function createSubscription(args) {
13
- if (!args.customer || !args.start || !args.end) {
14
- console.error('Usage: velaro billing-subscription create --customer "Liberty Mutual" --start 2026-11-17 --end 2027-11-16 [--po 4500175509] [--cadence annual] [--payment-method cash] [--total-cents 7357397] [--net-terms 30] [--lead-days 30] [--enable-billing] [--stripe-customer-id cus_...] [--force]');
15
- process.exit(1);
16
- }
17
- const body = {
18
- customerName: args.customer,
19
- poNumber: args.po,
20
- targetSystem: args.target,
21
- targetAccountId: args.targetAccountId,
22
- billingCadence: args.cadence ?? 'annual',
23
- paymentMethod: args.paymentMethod ?? 'cash',
24
- billingEnabled: !!args.enableBilling,
25
- contractSignedDate: args.signed,
26
- serviceStartDate: args.start,
27
- serviceEndDate: args.end,
28
- nextBillDate: args.nextBillDate,
29
- invoiceLeadDays: args.leadDays ?? 30,
30
- netTermsDays: args.netTerms ?? 30,
31
- cancellationNoticeDays: args.cancellationNoticeDays ?? 30,
32
- totalContractValueCents: args.totalCents ?? 0,
33
- recurringAmountCents: args.recurringAmountCents,
34
- stripeCustomerId: args.stripeCustomerId,
35
- notes: args.notes,
36
- force: !!args.force,
37
- };
38
- const result = await request('POST', '/api/BillingSubscription', body);
39
- console.log(`Subscription created: ID=${result.id}`);
40
- }
41
-
42
- async function deleteSubscription(id, args) {
43
- const sub = await request('GET', `/api/BillingSubscription/${id}`);
44
- const invoices = Array.isArray(sub.invoices) ? sub.invoices : [];
45
- console.log(`\nAbout to permanently delete BillingSubscription ${id}\n${'-'.repeat(60)}`);
46
- console.log(` Customer: ${sub.customerName}`);
47
- console.log(` Period: ${sub.serviceStartDate?.slice(0, 10)} .. ${sub.serviceEndDate?.slice(0, 10)}`);
48
- console.log(` Invoices to be cascade-deleted (${invoices.length}):`);
49
- for (const inv of invoices) {
50
- console.log(` - ${inv.invoiceNumberFormatted} ${money(inv.totalCents)} status=${inv.status}`);
51
- }
52
- if (!args.confirm) {
53
- console.log('\nAdd --confirm to actually delete this subscription. No changes made.\n');
54
- return;
55
- }
56
- const result = await request('DELETE', `/api/BillingSubscription/${id}`);
57
- console.log(`\n\x1b[32mDeleted subscription ${result.subscriptionId} (${result.customerName}) and ${result.deletedInvoiceCount} invoice(s).\x1b[0m\n`);
58
- }
59
-
60
- async function deleteInvoice(invoiceId, args) {
61
- if (!args.confirm) {
62
- console.log(`\nAdd --confirm to permanently delete invoice ${invoiceId}. No changes made.`);
63
- console.log('(Delete is refused server-side if the invoice has a recorded payment or has already been sent/paid/voided.)\n');
64
- return;
65
- }
66
- const result = await request('DELETE', `/api/BillingSubscription/invoice/${invoiceId}`);
67
- console.log(`\x1b[32mDeleted invoice ${result.invoiceNumberFormatted} (id=${result.invoiceId}) from subscription ${result.subscriptionId}.\x1b[0m`);
68
- }
69
-
70
- async function attachStripeCustomer(id, args) {
71
- if (!args.email && !args.stripeCustomerId) {
72
- console.error('Usage: velaro billing-subscription attach-stripe-customer <id> --email billing@customer.com (looks up or creates a Stripe customer by email)');
73
- console.error(' or: velaro billing-subscription attach-stripe-customer <id> --stripe-customer-id cus_xxx (attach a known Stripe customer ID directly)');
74
- process.exit(1);
75
- }
76
- const body = { email: args.email, stripeCustomerId: args.stripeCustomerId };
77
- const result = await request('POST', `/api/BillingSubscription/${id}/stripe-customer`, body);
78
- console.log(`Subscription ${result.id} attached to Stripe customer ${result.stripeCustomerId}`);
79
- }
80
-
81
- async function listSubscriptions() {
82
- const rows = await request('GET', '/api/BillingSubscription');
83
- if (!Array.isArray(rows) || rows.length === 0) {
84
- console.log('No billing subscriptions on file.');
85
- return;
86
- }
87
- console.log(`\nBilling Subscriptions (${rows.length})\n${'-'.repeat(60)}`);
88
- for (const s of rows) {
89
- console.log(` [${s.id}] ${s.customerName} PO=${s.poNumber ?? '(none)'} ${s.billingCadence}/${s.paymentMethod} billingEnabled=${s.billingEnabled} stripeCustomerId=${s.stripeCustomerId ?? '(none)'}`);
90
- console.log(` ${s.serviceStartDate?.slice(0, 10)} .. ${s.serviceEndDate?.slice(0, 10)}`);
91
- }
92
- console.log('');
93
- }
94
-
95
- function daysFromNow(dateStr) {
96
- const target = new Date(dateStr + 'T00:00:00Z');
97
- const today = new Date(new Date().toISOString().slice(0, 10) + 'T00:00:00Z');
98
- return Math.round((target - today) / 86400000);
99
- }
100
-
101
- async function renewalsReport(args) {
102
- const withinDays = args.withinDays ?? 9999;
103
- const rows = await request('GET', '/api/BillingSubscription');
104
- if (!Array.isArray(rows) || rows.length === 0) {
105
- console.log('No billing subscriptions on file.');
106
- return;
107
- }
108
- const report = rows.map(s => {
109
- const end = s.serviceEndDate?.slice(0, 10);
110
- const daysToRenewal = end ? daysFromNow(end) : null;
111
- const cancelDeadline = end ? new Date(new Date(end + 'T00:00:00Z').getTime() - s.cancellationNoticeDays * 86400000).toISOString().slice(0, 10) : null;
112
- const daysToCancelDeadline = cancelDeadline ? daysFromNow(cancelDeadline) : null;
113
- return { ...s, end, daysToRenewal, cancelDeadline, daysToCancelDeadline };
114
- })
115
- .filter(r => r.daysToRenewal == null || r.daysToRenewal <= withinDays)
116
- .sort((a, b) => (a.daysToRenewal ?? Infinity) - (b.daysToRenewal ?? Infinity));
117
-
118
- console.log(`\nRenewal Report${args.withinDays ? ` (within ${withinDays} days)` : ''}\n${'-'.repeat(90)}`);
119
- for (const r of report) {
120
- const canStillCancel = r.daysToCancelDeadline != null && r.daysToCancelDeadline >= 0;
121
- const status = r.daysToCancelDeadline == null
122
- ? 'no end date on file'
123
- : canStillCancel
124
- ? `can still cancel — ${r.daysToCancelDeadline}d left to give notice`
125
- : `PAST cancellation window — will auto-renew (deadline was ${r.cancelDeadline})`;
126
- console.log(` [${r.id}] ${r.customerName} renews ${r.end} (${r.daysToRenewal}d) ${status}`);
127
- }
128
- console.log('');
129
- }
130
-
131
- async function getSubscription(id) {
132
- const sub = await request('GET', `/api/BillingSubscription/${id}`);
133
- console.log(JSON.stringify(sub, null, 2));
134
- }
135
-
136
- async function generateInvoice(id, args) {
137
- if (!args.lineDescription || args.amountCents == null) {
138
- console.error('Usage: velaro billing-subscription invoice <id> --line-description "Annual" --amount-cents 7357397 [--pre-generate] [--po ...] [--invoice-date YYYY-MM-DD] [--due-date YYYY-MM-DD] [--service-start YYYY-MM-DD] [--service-end YYYY-MM-DD] [--notes ...] [--number-mode sequential|random-jitter] [--number-max-jitter 10] [--invoice-number 50042]');
139
- process.exit(1);
140
- }
141
- const body = {
142
- poNumber: args.po,
143
- servicePeriodStart: args.serviceStart,
144
- servicePeriodEnd: args.serviceEnd,
145
- invoiceDate: args.invoiceDate,
146
- dueDate: args.dueDate,
147
- isPreGenerated: !!args.preGenerate,
148
- internalNotes: args.notes,
149
- lineItems: [{ description: args.lineDescription, amountCents: Number(args.amountCents) }],
150
- numberMode: args.numberMode ?? 'sequential',
151
- numberMaxJitter: args.numberMaxJitter ?? 10,
152
- manualInvoiceNumber: args.invoiceNumber != null ? Number(args.invoiceNumber) : undefined,
153
- };
154
- const invoice = await request('POST', `/api/BillingSubscription/${id}/invoice`, body);
155
- console.log(`Invoice ${invoice.invoiceNumberFormatted} (id=${invoice.id}) — ${money(invoice.totalCents)}, status=${invoice.status}`);
156
- }
157
-
158
- async function recordPayment(invoiceId, args) {
159
- if (args.amountCents == null) {
160
- console.error('Usage: velaro billing-subscription payment <invoiceId> --amount-cents 7357397 [--method cash|check|ach|wire|card] [--date YYYY-MM-DD] [--reference "..."] [--note "..."]');
161
- process.exit(1);
162
- }
163
- const body = {
164
- amountCents: Number(args.amountCents),
165
- method: args.method ?? 'cash',
166
- paymentDate: args.date,
167
- reference: args.reference,
168
- note: args.note,
169
- };
170
- const payment = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/payment`, body);
171
- console.log(`Payment recorded: id=${payment.id}, amount=${money(payment.amountCents)}, method=${payment.method}`);
172
- // The server-side shared payment-applied handler has already run (RecordPaymentAsync); show the
173
- // resulting billing clock so the operator sees what the payment did.
174
- try {
175
- printExpiry(await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/expiry`));
176
- } catch (e) {
177
- console.log(`(paid-through lookup failed: ${e.message})`);
178
- }
179
- }
180
-
181
- function printExpiry(e) {
182
- const d = (v) => (v ? String(v).slice(0, 10) : '(none)');
183
- console.log(`Subscription ${e.subscriptionId} (${e.customerName}): paid-through=${d(e.paidThroughAt)}, policy=${e.expiryPolicy}, grace=${e.gracePeriodDays}d, ` +
184
- `effective-expiry=${e.expiryPolicy === 'NeverExpire' ? 'never' : d(e.effectiveExpiresAt)}` +
185
- (e.overrideActive ? `, OVERRIDE until ${d(e.expiryOverrideUntil)} (${e.expiryOverrideReason ?? 'no reason'})` : ''));
186
- }
187
-
188
- async function showExpiry(id) {
189
- printExpiry(await request('GET', `/api/BillingSubscription/${id}/expiry`));
190
- }
191
-
192
- async function setExpiryPolicy(id, args) {
193
- if (!args.policy || !args.reason) {
194
- console.error('Usage: velaro billing-subscription set-expiry-policy <id> --policy Default|CustomGrace|NeverExpire [--grace-days N] --reason "..."');
195
- process.exit(1);
196
- }
197
- printExpiry(await request('POST', `/api/BillingSubscription/${id}/expiry-policy`, {
198
- expiryPolicy: args.policy,
199
- gracePeriodDays: args.graceDays != null ? Number(args.graceDays) : undefined,
200
- reason: args.reason,
201
- }));
202
- }
203
-
204
- async function sendInvoice(invoiceId, args) {
205
- const res = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/send${args.force ? '?force=true' : ''}`, {});
206
- if (res.alreadySent) console.log(`Invoice ${invoiceId} was already sent ${res.sentAt}; nothing sent (use --force to resend).`);
207
- else console.log(`Invoice ${invoiceId} sent to ${res.recipient} at ${res.sentAt}${res.payLinkIncluded ? ' (pay link included)' : ' (no pay link)'}.`);
208
- }
209
-
210
- function printReminders(v) {
211
- console.log(`Subscription ${v.id} (${v.customerName}): reminders ${v.enabled ? 'ON' : 'OFF'}`);
212
- console.log(` cadence (days from due): ${v.cadence}${v.cadenceIsDefault ? ' (default)' : ''}`);
213
- console.log(` contact email: ${v.contactEmail ?? '(none)'}; resolved recipient: ${v.resolvedRecipient ?? '(none, sends will fail)'}`);
214
- console.log(` expiry policy: ${v.expiryPolicy}; effective expiry: ${v.effectiveExpiry ?? 'never'}`);
215
- for (const i of v.openInvoices || []) {
216
- console.log(` invoice ${i.id} ${i.invoiceNumberFormatted} due ${i.dueDate} sent ${i.sentAt ?? 'NO'} reminders ${i.reminderCount} last ${i.lastReminderSentAt ?? '-'}`);
217
- }
218
- }
219
-
220
- async function reminders(id, args) {
221
- const change = args.on || args.off || args.cadence != null || args.email != null;
222
- if (args.on && args.off) { console.error('Use only one of --on / --off.'); process.exit(1); }
223
- if (!change) return printReminders(await request('GET', `/api/BillingSubscription/${id}/reminders`));
224
- const body = {};
225
- if (args.on) body.enabled = true;
226
- if (args.off) body.enabled = false;
227
- if (args.cadence != null) body.cadence = String(args.cadence);
228
- if (args.email != null) body.contactEmail = String(args.email);
229
- printReminders(await request('POST', `/api/BillingSubscription/${id}/reminders`, body));
230
- }
231
-
232
- async function pushExpiry(id, args) {
233
- if (!args.reason || (!args.clear && !args.until)) {
234
- console.error('Usage: velaro billing-subscription push-expiry <id> --until YYYY-MM-DD --reason "..." (or --clear --reason "...")');
235
- process.exit(1);
236
- }
237
- printExpiry(await request('POST', `/api/BillingSubscription/${id}/expiry-override`, {
238
- until: args.until ? new Date(args.until).toISOString() : undefined,
239
- reason: args.reason,
240
- clear: !!args.clear,
241
- }));
242
- }
243
-
244
- async function listPayments(invoiceId) {
245
- const result = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/payments`);
246
- console.log(`\nPayments for invoice ${invoiceId}\n${'-'.repeat(50)}`);
247
- for (const p of result.payments) {
248
- console.log(` [${p.id}] ${money(p.amountCents)} ${p.method} ${p.paymentDate?.slice(0, 10)} ref=${p.reference ?? '(none)'}`);
249
- }
250
- console.log(`\nBalance: applied ${money(result.balance.appliedCents)} / total ${money(result.balance.totalCents)} — remaining ${money(result.balance.remainingCents)} — paidInFull=${result.balance.paidInFull}\n`);
251
- }
252
-
253
- async function qboStatus(invoiceId) {
254
- const result = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/qbo-sync-status`);
255
- console.log(`Invoice ${result.invoice.invoiceNumberFormatted}: QBO status = ${result.invoice.qboSyncStatus ?? '(none)'}`);
256
- for (const p of result.payments) {
257
- console.log(` Payment ${p.id}: QBO status = ${p.qboSyncStatus ?? '(none)'}, syncedAt = ${p.qboSyncedAt ?? '(never)'}`);
258
- }
259
- }
260
-
261
- async function invoiceSendLog(invoiceId) {
262
- const result = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/send-log`);
263
- const inv = result.invoice;
264
- console.log(`Invoice ${inv.invoiceNumberFormatted}: SentAt = ${inv.sentAt ?? '(never)'}, failures = ${inv.sendFailureCount}${inv.lastSendError ? `, lastError = ${inv.lastSendError}` : ''}`);
265
- if (result.log.length === 0) {
266
- console.log(' No send attempts recorded.');
267
- return;
268
- }
269
- for (const l of result.log) {
270
- const statusUpdate = l.statusUpdatedAtUtc ? ` (updated ${l.statusUpdatedAtUtc})` : '';
271
- const detail = l.statusDetail ? ` -- ${l.statusDetail}` : '';
272
- console.log(` [${l.sentAtUtc}] ${l.recipientRole} ${l.recipientEmail}: ${l.status}${statusUpdate}${detail} (acsMessageId=${l.acsMessageId ?? 'none'})`);
273
- }
274
- }
275
-
276
- async function provisionPlaceholderSite(id, args) {
277
- if (!args.tier) {
278
- console.error('Usage: velaro billing-subscription provision-placeholder-site <id> --tier Professional [--admin-email placeholder+staxbill-123@velaro.com] [--preview]');
279
- process.exit(1);
280
- }
281
- const body = {
282
- subscriptionTier: args.tier,
283
- adminEmailOverride: args.adminEmail,
284
- preview: !!args.preview,
285
- };
286
- const result = await request('POST', `/api/BillingSubscription/${id}/provision-placeholder-site`, body);
287
-
288
- if (args.preview) {
289
- console.log(`\nPreview: provision-placeholder-site for subscription ${result.subscriptionId}\n${'-'.repeat(60)}`);
290
- console.log(` Company: ${result.companyName}`);
291
- console.log(` Admin: ${result.adminEmail}`);
292
- console.log(` Tier: ${result.subscriptionTier}`);
293
- if (result.existingSiteId != null) {
294
- console.log(` SiteId: ${result.existingSiteId} (already allocated -- would be REUSED, not re-allocated)`);
295
- } else {
296
- console.log(` SiteId: (would allocate a new placeholder id -- not shown here, preview never consumes a sequence value)`);
297
- }
298
- console.log(' No writes made (--preview).\n');
299
- return;
300
- }
301
-
302
- if (result.provisioningSucceeded) {
303
- console.log(`\x1b[32mOK: placeholder site ${result.siteId} provisioned for subscription ${result.subscriptionId}\x1b[0m`);
304
- console.log(` Company: ${result.companyName}`);
305
- console.log(` Admin: ${result.adminEmail}`);
306
- console.log(` Tier: ${result.subscriptionTier}`);
307
- if (result.wasAlreadyAllocated) console.log(` (SiteId was already allocated by a prior call -- resumed, not re-allocated.)`);
308
- } else {
309
- console.error(`\x1b[31mSiteId ${result.siteId} is allocated but provisioning FAILED: ${result.provisioningError}\x1b[0m`);
310
- console.error(` Check site ${result.siteId} manually, or retry this same command -- it will resume against the same SiteId, not allocate a new one.`);
311
- process.exit(1);
312
- }
313
- }
314
-
315
- async function recognitionSchedule(invoiceId) {
316
- const rows = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/recognition-schedule`);
317
- console.log(`\nRevenue recognition schedule for invoice ${invoiceId}\n${'-'.repeat(50)}`);
318
- for (const r of rows) {
319
- console.log(` ${r.recognitionMonth.slice(0, 7)} ${money(r.amountCents)} [${r.status}]`);
320
- }
321
- console.log(`\nTotal: ${money(rows.reduce((sum, r) => sum + r.amountCents, 0))}\n`);
322
- }
323
-
324
- async function setAutoRenew(id, args) {
325
- if (args.autoRenew == null) {
326
- console.error('Usage: velaro billing-subscription set-auto-renew <id> --auto-renew true|false');
327
- process.exit(1);
328
- }
329
- const body = { autoRenew: args.autoRenew === 'true' || args.autoRenew === true };
330
- const result = await request('PUT', `/api/BillingSubscription/${id}/auto-renew`, body);
331
- console.log(`Subscription ${result.id}: AutoRenew = ${result.autoRenew}`);
332
- }
333
-
334
- async function cancelSub(id, args) {
335
- if (!args.mode) {
336
- console.error('Usage: velaro billing-subscription cancel <id> --mode bill_more_periods|shutdown_accelerate|shutdown_keep_recognizing|shutdown_after_covered [--extra-periods N] [--effective-date YYYY-MM-DD] [--reason "..."]');
337
- process.exit(1);
338
- }
339
- const r = await request('POST', `/api/BillingSubscription/${id}/cancel`, {
340
- mode: args.mode, extraPeriods: args.extraPeriods, effectiveDate: args.effectiveDate, reason: args.reason,
341
- });
342
- console.log(`Subscription ${r.subscriptionId}: ${r.mode}, service ends ${r.serviceEndDate}, accelerated cents ${r.acceleratedCents}`);
343
- }
344
-
345
- async function oneTimeInvoice(id, args) {
346
- if (!args.description || args.amountCents == null) {
347
- console.error('Usage: velaro billing-subscription one-time-invoice <id> --description "..." --amount-cents N [--date YYYY-MM-DD] [--po X]');
348
- process.exit(1);
349
- }
350
- const r = await request('POST', `/api/BillingSubscription/${id}/one-time-invoice`, {
351
- invoiceDate: args.date, poNumber: args.po,
352
- lineItems: [{ description: args.description, amountCents: args.amountCents }],
353
- });
354
- console.log(`One-time invoice ${r.invoiceNumber} (id ${r.id}) total ${money(r.totalCents)} status ${r.status}`);
355
- }
356
-
357
- async function midTermUpgrade(id, args) {
358
- if (args.newAmountCents == null) {
359
- console.error('Usage: velaro billing-subscription mid-term-upgrade <id> --new-amount-cents N [--effective-date YYYY-MM-DD] [--reason "..."]');
360
- process.exit(1);
361
- }
362
- const r = await request('POST', `/api/BillingSubscription/${id}/mid-term-upgrade`, {
363
- newRecurringAmountCents: args.newAmountCents, effectiveDate: args.effectiveDate, reason: args.reason,
364
- });
365
- console.log(`Subscription ${r.subscriptionId}: ${money(r.oldRecurringAmountCents)} -> ${money(r.newRecurringAmountCents)}, proration ${money(r.prorationCents)} co-terminous to ${r.coTermEnd}`);
366
- }
367
-
368
- async function scheduleCadenceChange(id, args) {
369
- if (args.cadence && !args.effectiveAt) {
370
- console.error('Usage: velaro billing-subscription schedule-cadence-change <id> --cadence annual|monthly|quarterly --effective-at YYYY-MM-DD');
371
- console.error(' or: velaro billing-subscription schedule-cadence-change <id> --cancel (cancels a previously-scheduled change)');
372
- process.exit(1);
373
- }
374
- const body = args.cancel
375
- ? { pendingCadence: null, effectiveAt: null }
376
- : { pendingCadence: args.cadence, effectiveAt: args.effectiveAt };
377
- const result = await request('PUT', `/api/BillingSubscription/${id}/schedule-cadence-change`, body);
378
- if (result.pendingBillingCadence) {
379
- console.log(`Subscription ${result.id}: scheduled to change to ${result.pendingBillingCadence} on ${result.pendingCadenceEffectiveAt?.slice(0, 10)}`);
380
- } else {
381
- console.log(`Subscription ${result.id}: no cadence change scheduled.`);
382
- }
383
- }
384
-
385
- async function correctPayment(paymentId, args) {
386
- if (!args.field || args.reason == null) {
387
- console.error('Usage: velaro billing-subscription payment-correct <paymentId> --field date|amount-cents|method|reference|note --value <v> --reason "..."');
388
- process.exit(1);
389
- }
390
- const body = { field: args.field, value: args.value != null ? String(args.value) : undefined, reason: args.reason };
391
- const result = await request('POST', `/api/BillingSubscription/payment/${paymentId}/correct`, body);
392
- console.log(`Payment ${result.id} corrected: ${args.field} -> ${args.value}`);
393
- }
394
-
395
- async function paymentHistory(paymentId) {
396
- const result = await request('GET', `/api/BillingSubscription/payment/${paymentId}/history`);
397
- console.log(`\nPayment ${paymentId} -- live value\n${'-'.repeat(60)}`);
398
- console.log(` Amount: ${money(result.payment.amountCents)}`);
399
- console.log(` Date: ${result.payment.paymentDate?.slice(0, 10)}`);
400
- console.log(` Method: ${result.payment.method}`);
401
- console.log(` Reference: ${result.payment.reference ?? '(none)'}`);
402
- console.log(` Note: ${result.payment.note ?? '(none)'}`);
403
- console.log(`\nCorrection history (${result.corrections.length})\n${'-'.repeat(60)}`);
404
- for (const c of result.corrections) {
405
- console.log(` [${c.correctedAt?.slice(0, 19)}] ${c.fieldName}: "${c.oldValue}" -> "${c.newValue}" (by ${c.correctedBy}: ${c.reason})`);
406
- }
407
- console.log('');
408
- }
409
-
410
- async function correctInvoice(invoiceId, args) {
411
- if (!args.field || args.reason == null) {
412
- console.error('Usage: velaro billing-subscription invoice-correct <invoiceId> --field po-number|invoice-date|due-date|total-cents|internal-notes|service-period-start|service-period-end --value <v> --reason "..."');
413
- process.exit(1);
414
- }
415
- const body = { field: args.field, value: args.value != null ? String(args.value) : undefined, reason: args.reason };
416
- const result = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/correct`, body);
417
- console.log(`Invoice ${result.invoiceNumberFormatted} (id=${result.id}) corrected: ${args.field} -> ${args.value}`);
418
- }
419
-
420
- async function invoiceHistory(invoiceId) {
421
- const result = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/history`);
422
- console.log(`\nInvoice ${result.invoice.invoiceNumberFormatted} -- live value\n${'-'.repeat(60)}`);
423
- console.log(` Total: ${money(result.invoice.totalCents)}`);
424
- console.log(` PO: ${result.invoice.poNumber ?? '(none)'}`);
425
- console.log(` Invoice date / due date: ${result.invoice.invoiceDate?.slice(0, 10)} / ${result.invoice.dueDate?.slice(0, 10)}`);
426
- console.log(`\nCorrection history (${result.corrections.length})\n${'-'.repeat(60)}`);
427
- for (const c of result.corrections) {
428
- console.log(` [${c.correctedAt?.slice(0, 19)}] ${c.fieldName}: "${c.oldValue}" -> "${c.newValue}" (by ${c.correctedBy}: ${c.reason})`);
429
- }
430
- console.log('');
431
- }
432
-
433
- async function correctSubscription(subscriptionId, args) {
434
- if (!args.field || !args.reason) {
435
- console.error('Usage: velaro billing-subscription subscription-correct <id> --field service-start-date|service-end-date|next-bill-date|po-number|notes|recurring-amount-cents|target-system|target-account-id|parallel-billing-mode|billing-cutover-date|external-billing-system|external-billing-account-id|auto-charge-enabled|invoice-delivery-action|invoice-recipient-emails|invoice-cc-emails|invoice-bcc-emails|contract-id|grace-period-days|auto-expire-after-grace-period|exclude-from-entitlement-sync|exclude-from-bulk-price-import --value <v> --reason "..." [--clear] [--force]');
436
- process.exit(1);
437
- }
438
- const body = {
439
- field: args.field,
440
- value: args.value != null ? String(args.value) : undefined,
441
- reason: args.reason,
442
- clear: !!args.clear,
443
- force: !!args.force,
444
- };
445
- const result = await request('POST', `/api/BillingSubscription/${subscriptionId}/correct`, body);
446
- const sub = result.subscription;
447
- const shownValue = args.clear ? '(cleared)' : (args.value ?? '(cleared/none)');
448
- console.log(`Subscription ${sub.id} (${sub.customerName}) corrected: ${args.field} -> ${shownValue}`);
449
- if (result.invoicesNeedingReconciliation && result.invoicesNeedingReconciliation.length > 0) {
450
- console.log(`\n\x1b[33mWARNING\x1b[0m: ${result.invoicesNeedingReconciliation.length} existing invoice(s) on this subscription were NOT updated: ids ${result.invoicesNeedingReconciliation.join(', ')}.`);
451
- console.log(` Reconcile each with: velaro billing-subscription invoice-correct <invoiceId> --field service-period-start|service-period-end --value <v> --reason "..."`);
452
- }
453
- }
454
-
455
- async function subscriptionHistory(subscriptionId) {
456
- const result = await request('GET', `/api/BillingSubscription/${subscriptionId}/history`);
457
- const sub = result.subscription;
458
- console.log(`\nSubscription ${sub.id} (${sub.customerName}) -- live value\n${'-'.repeat(60)}`);
459
- console.log(` Service period: ${sub.serviceStartDate?.slice(0, 10)} -- ${sub.serviceEndDate?.slice(0, 10)}`);
460
- console.log(` Next bill date: ${sub.nextBillDate?.slice(0, 10) ?? '(none)'}`);
461
- console.log(` PO: ${sub.poNumber ?? '(none)'}`);
462
- console.log(`\nCorrection history (${result.corrections.length})\n${'-'.repeat(60)}`);
463
- for (const c of result.corrections) {
464
- console.log(` [${c.correctedAt?.slice(0, 19)}] ${c.fieldName}: "${c.oldValue}" -> "${c.newValue}" (by ${c.correctedBy}: ${c.reason})`);
465
- }
466
- console.log('');
467
- }
468
-
469
- async function reissueInvoice(invoiceId, args) {
470
- if (!args.reason) {
471
- console.error('Usage: velaro billing-subscription invoice-reissue <invoiceId> --reason "..." [--service-period-start <date>] [--service-period-end <date>] [--po-number <v>]');
472
- process.exit(1);
473
- }
474
- const body = {
475
- reason: args.reason,
476
- servicePeriodStart: args.servicePeriodStart,
477
- servicePeriodEnd: args.servicePeriodEnd,
478
- poNumber: args.poNumber,
479
- internalNotes: args.internalNotes,
480
- };
481
- const result = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/reissue`, body);
482
- console.log(`Invoice ${invoiceId} superseded. New invoice: ${result.invoiceNumberFormatted} (id=${result.id}).`);
483
- }
484
-
485
- async function releaseInvoice(invoiceId) {
486
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/release`, {});
487
- console.log(`Invoice ${invoiceId} released: status ${r.status}, sends at ${r.readyToSendAt?.slice(0, 10)}.`);
488
- }
489
-
490
- async function testFireInvoice(invoiceId) {
491
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/test-fire`, {});
492
- console.log(`Test-fire sent to internal recipients only: ${(r.recipients || []).join(', ')}`);
493
- }
494
-
495
- async function issueNow(id, args) {
496
- const path = args.subscription
497
- ? `/api/BillingSubscription/${id}/issue-now`
498
- : `/api/BillingSubscription/invoice/${id}/issue-now`;
499
- const r = await request('POST', path, {});
500
- console.log(`Issued now: ${r.invoiceNumberFormatted} (id=${r.id}), dated ${r.invoiceDate?.slice(0, 10)}, status ${r.status}.`);
501
- }
502
-
503
- async function regenerateInvoice(invoiceId) {
504
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/regenerate`, {});
505
- console.log(`Regenerated: ${r.invoiceNumberFormatted} (id=${r.id}), total ${money(r.totalCents)}.`);
506
- }
507
-
508
- async function materializeInvoice(subscriptionId) {
509
- const r = await request('POST', `/api/BillingSubscription/${subscriptionId}/materialize`, {});
510
- console.log(`Materialized ${r.invoiceNumberFormatted} (id=${r.id}), status ${r.status}.`);
511
- }
512
-
513
- async function upcomingInvoices(args) {
514
- const rows = await request('GET', `/api/BillingSubscription/upcoming?days=${args.days || 30}`);
515
- if (!rows.length) { console.log('No upcoming invoices.'); return; }
516
- for (const u of rows) {
517
- console.log(` [${u.kind}] sub ${u.subscriptionId} ${u.customerName} ${u.servicePeriodStart?.slice(0, 10)}..${u.servicePeriodEnd?.slice(0, 10)} sends ${u.sendAt?.slice(0, 10)} ${money(u.amountCents)} ${u.status || ''}${u.invoiceId ? ' (invoice ' + u.invoiceId + ')' : ''}${u.willSend ? '' : ' [WILL NOT SEND]'}`);
518
- }
519
- }
520
-
521
- async function copyInvoice(invoiceId, args) {
522
- const body = {
523
- servicePeriodStart: args.servicePeriodStart,
524
- servicePeriodEnd: args.servicePeriodEnd,
525
- invoiceDate: args.invoiceDate,
526
- poNumber: args.poNumber,
527
- };
528
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/copy`, body);
529
- console.log(`Invoice ${invoiceId} copied to DRAFT ${r.invoiceNumberFormatted} (id=${r.id}), total ${money(r.totalCents)}. Edit with invoice-correct, then finalize.`);
530
- }
531
-
532
- async function copySubscription(id, args) {
533
- if (!args.name) {
534
- console.error('Usage: velaro billing-subscription subscription-copy <id> --name "New customer name" [--service-start-date <date>] [--service-end-date <date>]');
535
- process.exit(1);
536
- }
537
- const body = { newCustomerName: args.name, serviceStartDate: args.serviceStartDate, serviceEndDate: args.serviceEndDate };
538
- const r = await request('POST', `/api/BillingSubscription/${id}/copy`, body);
539
- console.log(`Subscription ${id} copied to inactive draft id=${r.id} ("${r.customerName}"). BillingEnabled=false, AutoCharge=false, no NextBillDate.`);
540
- }
541
-
542
- async function pauseBilling(id, args) {
543
- const body = { resumeDate: args.resumeDate, invoiceBehavior: args.invoiceBehavior, reason: args.reason };
544
- const r = await request('POST', `/api/BillingSubscription/${id}/pause`, body);
545
- console.log(`Billing paused for subscription ${id} (behavior=${r.pauseInvoiceBehavior}, resume=${r.billingResumeDate || 'manual'}).`);
546
- }
547
-
548
- async function resumeBilling(id) {
549
- const r = await request('POST', `/api/BillingSubscription/${id}/resume`, {});
550
- console.log(`Billing resumed for subscription ${id}. Next bill date: ${r.nextBillDate || 'none'}.`);
551
- }
552
-
553
- async function voidInvoice(invoiceId, args) {
554
- if (!args.reason) {
555
- console.error('Usage: velaro billing-subscription invoice-void <invoiceId> --reason "..."');
556
- process.exit(1);
557
- }
558
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/void`, { reason: args.reason });
559
- console.log(`Invoice ${r.invoiceNumberFormatted} voided.`);
560
- }
561
-
562
- async function creditNote(invoiceId, args) {
563
- if (!args.reason || (args.amountCents === undefined && !args.lines)) {
564
- console.error('Usage: velaro billing-subscription credit-note <invoiceId> --reason "..." (--amount-cents <n> | --lines "<lineItemId>:<cents>,<lineItemId>:<cents>")');
565
- process.exit(1);
566
- }
567
- const body = { reason: args.reason };
568
- if (args.lines) {
569
- body.lines = String(args.lines).split(',').map((p) => {
570
- const [id, cents] = p.split(':');
571
- return { lineItemId: parseInt(id, 10), amountCents: parseInt(cents, 10) };
572
- });
573
- } else {
574
- body.amountCents = Number(args.amountCents);
575
- }
576
- const r = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/credit-note`, body);
577
- const due = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/amount-due`);
578
- console.log(`Credit note ${r.creditNoteNumber} (id=${r.id}) for ${money(r.amountCents)} issued. Amount due now: ${money(due.amountDueCents)}.`);
579
- }
580
-
581
- async function creditNoteVoid(creditNoteId, args) {
582
- const r = await request('POST', `/api/BillingSubscription/credit-note/${creditNoteId}/void`, { reason: args.reason });
583
- console.log(`Credit note ${r.creditNoteNumber} voided.`);
584
- }
585
-
586
- async function creditNotes(invoiceId) {
587
- const rows = await request('GET', `/api/BillingSubscription/invoice/${invoiceId}/credit-notes`);
588
- if (!rows.length) { console.log('No credit notes.'); return; }
589
- for (const r of rows) console.log(`${r.id}\t${r.creditNoteNumber}\t${money(r.amountCents)}\t${r.status}\t${r.reason}`);
590
- }
591
-
592
- async function runRenewalSweep() {
593
- const result = await request('POST', '/api/BillingSubscription/renewal-sweep/run', {});
594
- console.log(result.message || 'Renewal sweep triggered.');
595
- }
596
-
597
- async function runDunningReport() {
598
- const report = await request('POST', '/api/BillingSubscription/dunning-report/run', {});
599
- if (report.length === 0) {
600
- console.log('No past-due invoices.');
601
- return;
602
- }
603
- console.log(`\n${report.length} past-due invoice(s):\n${'-'.repeat(80)}`);
604
- for (const r of report) {
605
- let flag = r.willAutoExpire ? '\x1b[31mAUTO-EXPIRING\x1b[0m' : (r.pastGracePeriod ? '\x1b[33mPAST GRACE PERIOD\x1b[0m' : 'within grace period');
606
- if (r.expiryPolicy === 'NeverExpire') flag += ' NEVER-EXPIRE';
607
- if (r.overrideActive) flag += ` OVERRIDE until ${String(r.overrideUntil).slice(0, 10)}`;
608
- console.log(` Sub ${r.subscriptionId} (${r.customerName}) -- ${r.invoiceNumberFormatted}: ${money(r.amountOwedCents)} owed, ${r.daysPastDue}d past due (grace ${r.gracePeriodDays}d) [${flag}]`);
609
- }
610
- console.log('');
611
- }
612
-
613
- async function revenueReport(args) {
614
- const params = new URLSearchParams();
615
- if (args.fromMonth) params.set('fromMonth', args.fromMonth);
616
- if (args.throughMonth) params.set('throughMonth', args.throughMonth);
617
- const qs = params.toString() ? `?${params.toString()}` : '';
618
- const rows = await request('GET', `/api/BillingSubscription/reports/revenue-recognition${qs}`);
619
- if (rows.length === 0) {
620
- console.log('No recognized revenue rows in range.');
621
- return;
622
- }
623
- console.log(`\nRecognized revenue by month (excludes voided/superseded schedule rows)\n${'-'.repeat(60)}`);
624
- for (const r of rows) {
625
- console.log(` ${r.recognitionMonth.slice(0, 7)} ${money(r.totalCents)} (${r.rowCount} row${r.rowCount === 1 ? '' : 's'})`);
626
- }
627
- console.log(`\nTotal: ${money(rows.reduce((sum, r) => sum + r.totalCents, 0))}\n`);
628
- }
629
-
630
- async function reissueAudit() {
631
- const rows = await request('GET', '/api/BillingSubscription/reports/reissues');
632
- if (rows.length === 0) {
633
- console.log('No reissued/superseded invoices.');
634
- return;
635
- }
636
- console.log(`\n${rows.length} reissued/superseded invoice(s):\n${'-'.repeat(80)}`);
637
- for (const r of rows) {
638
- const chainParts = [];
639
- if (r.reissuedFromInvoiceId) chainParts.push(`reissue of invoice ${r.reissuedFromInvoiceId}`);
640
- if (r.supersededByInvoiceId) chainParts.push(`superseded by invoice ${r.supersededByInvoiceId}`);
641
- const chain = chainParts.length ? chainParts.join(', ') : 'no linked invoice';
642
- console.log(` ${r.invoiceNumberFormatted} (id ${r.id}, sub ${r.subscriptionId}, ${r.customerName}) -- ${money(r.totalCents)} [${r.status}] -- ${chain}`);
643
- if (r.internalNotes) console.log(` notes: ${r.internalNotes.split('\n').pop()}`);
644
- }
645
- console.log('');
646
- }
647
-
648
- async function qboSync(invoiceId, args) {
649
- const live = !!args.live && !args.dryRun;
650
- const result = await request('POST', `/api/BillingSubscription/invoice/${invoiceId}/qbo-sync`, { live });
651
- const tag = result.success ? '\x1b[32mOK\x1b[0m' : '\x1b[31mFAILED\x1b[0m';
652
- console.log(`${tag} invoice ${invoiceId}: live=${result.live} outcome=${result.outcome} qboInvoiceId=${result.qboInvoiceId ?? '(none)'}`);
653
- if (result.detail) console.log(` ${result.detail}`);
654
- if (!args.live) console.log(' (dry-run -- pass --live to actually call the QBO client (currently a no-op, no real credentials configured))');
655
- }
656
-
657
- async function anomalies() {
658
- const rows = await request('GET', '/api/BillingSubscription/anomalies');
659
- if (!Array.isArray(rows) || rows.length === 0) {
660
- console.log('No flagged anomalies.');
661
- return;
662
- }
663
- console.log(`\nFlagged invoices needing review (${rows.length})\n${'-'.repeat(70)}`);
664
- for (const r of rows) {
665
- console.log(` [invoice ${r.id}] ${r.invoiceNumberFormatted} ${r.customerName} ${money(r.totalCents)} (subscription ${r.subscriptionId})`);
666
- console.log(` ${r.anomalyReason}`);
667
- }
668
- console.log('');
669
- }
670
-
671
- async function anomalyClear(invoiceId, args) {
672
- const result = await request('POST', `/api/BillingSubscription/anomaly/${invoiceId}/clear`, { note: args.note });
673
- console.log(`Anomaly cleared on invoice ${result.id} by ${result.anomalyClearedBy} at ${result.anomalyClearedAt}`);
674
- }
675
-
676
- async function generateDocument(invoiceId, args) {
677
- const type = args.type;
678
- if (type !== 'invoice' && type !== 'receipt' && type !== 'quote') {
679
- console.error('Usage: velaro billing-subscription document <invoiceId> --type invoice|receipt|quote [--out <path>]');
680
- process.exit(1);
681
- }
682
-
683
- const [{ invoice, subscription }, paymentsResult] = await Promise.all([
684
- request('GET', `/api/BillingSubscription/invoice/${invoiceId}`),
685
- request('GET', `/api/BillingSubscription/invoice/${invoiceId}/payments`),
686
- ]);
687
-
688
- // A quote's default filename must not embed the real INV- number either -- that's the exact
689
- // file that would get attached/emailed to a prospect, defeating the point of the QUO- reference
690
- // rendered inside the PDF itself.
691
- const defaultRef = type === 'quote'
692
- ? `QUO-${invoice.invoiceNumber ?? invoiceId}`
693
- : (invoice.invoiceNumberFormatted ?? `invoice-${invoiceId}`);
694
- const outPath = args.out ?? path.resolve(process.cwd(), `${defaultRef}-${type}.pdf`);
695
-
696
- try {
697
- const pdfMod = await loadStaff('lib/pdf/billing-document.js');
698
- if (!pdfMod) throw new Error('Billing PDF generation is a Velaro staff tool and is not part of the public CLI.');
699
- await pdfMod.generateBillingDocument({
700
- invoice,
701
- subscription,
702
- payments: paymentsResult.payments,
703
- balance: paymentsResult.balance,
704
- type,
705
- outPath,
706
- });
707
- } catch (err) {
708
- console.error(`\x1b[31mFailed to generate ${type}: ${err.message}\x1b[0m`);
709
- process.exit(1);
710
- }
711
-
712
- console.log(`\x1b[32mGenerated ${type} for invoice ${invoice.invoiceNumberFormatted} -> ${outPath}\x1b[0m`);
713
- }
714
-
715
- export const billingSubscriptionCommand = {
716
- command: 'billing-subscription <subcommand>',
717
- describe: 'Manage standalone billing subscriptions, invoices, payments, and QBO dry-run sync status',
718
- builder: (yargs) =>
719
- yargs
720
- .command('list', 'List all billing subscriptions', {}, () => listSubscriptions())
721
- .command('get <id>', 'Get a subscription by ID (with invoices)', {}, (args) => getSubscription(args.id))
722
- .command('create', 'Create a new billing subscription', {
723
- customer: { type: 'string' },
724
- po: { type: 'string' },
725
- target: { type: 'string' },
726
- 'target-account-id': { type: 'string' },
727
- cadence: { type: 'string', default: 'annual' },
728
- 'payment-method': { type: 'string', default: 'cash' },
729
- signed: { type: 'string' },
730
- start: { type: 'string' },
731
- end: { type: 'string' },
732
- 'next-bill-date': { type: 'string' },
733
- 'lead-days': { type: 'number' },
734
- 'net-terms': { type: 'number' },
735
- 'cancellation-notice-days': { type: 'number' },
736
- 'total-cents': { type: 'number' },
737
- 'recurring-amount-cents': { type: 'number', describe: 'Amount billed on EACH renewal invoice -- required before the renewal sweep will invoice this subscription' },
738
- notes: { type: 'string' },
739
- 'enable-billing': { type: 'boolean', default: false },
740
- 'stripe-customer-id': { type: 'string' },
741
- force: { type: 'boolean', default: false, describe: 'Bypass the duplicate-subscription guard (same customer, overlapping service period)' },
742
- }, (args) => createSubscription(args))
743
- .command('delete <id>', 'Permanently delete a subscription and its invoices -- refused if any invoice has a payment or was already sent/paid/voided', {
744
- confirm: { type: 'boolean', default: false, describe: 'Required to actually delete -- without it, only prints what would be deleted' },
745
- }, (args) => deleteSubscription(args.id, args))
746
- .command('delete-invoice <invoiceId>', 'Permanently delete a single invoice -- refused if it has a payment or was already sent/paid/voided', {
747
- confirm: { type: 'boolean', default: false, describe: 'Required to actually delete' },
748
- }, (args) => deleteInvoice(args.invoiceId, args))
749
- .command('attach-stripe-customer <id>', 'Look up (by email) or create a Stripe customer and permanently attach it to a subscription', {
750
- email: { type: 'string' },
751
- 'stripe-customer-id': { type: 'string' },
752
- }, (args) => attachStripeCustomer(args.id, args))
753
- .command('invoice <id>', 'Generate (or pre-generate) an invoice for a subscription', {
754
- 'line-description': { type: 'string' },
755
- 'amount-cents': { type: 'number' },
756
- po: { type: 'string' },
757
- 'invoice-date': { type: 'string' },
758
- 'due-date': { type: 'string' },
759
- 'service-start': { type: 'string' },
760
- 'service-end': { type: 'string' },
761
- 'pre-generate': { type: 'boolean', default: false },
762
- notes: { type: 'string' },
763
- 'number-mode': { type: 'string', default: 'sequential', describe: 'sequential | random-jitter' },
764
- 'number-max-jitter': { type: 'number', default: 10, describe: 'Max jitter (inclusive) when --number-mode random-jitter' },
765
- 'invoice-number': { type: 'number', describe: 'Explicit manual override -- bypasses --number-mode entirely' },
766
- }, (args) => generateInvoice(args.id, args))
767
- .command('provision-placeholder-site <id>', 'Allocate (or resume) a placeholder v20 SiteId and provision a real placeholder site under it via messaging', {
768
- tier: { type: 'string', describe: 'Subscription tier (required, no default -- e.g. Starter, Professional, Enterprise)' },
769
- 'admin-email': { type: 'string', describe: 'Override the default placeholder+staxbill-<id>@velaro.com admin email' },
770
- preview: { type: 'boolean', default: false, describe: 'Show what would happen without allocating or calling messaging' },
771
- }, (args) => provisionPlaceholderSite(args.id, args))
772
- .command('recognition-schedule <invoiceId>', 'Show the monthly revenue-recognition schedule for an invoice', {}, (args) => recognitionSchedule(args.invoiceId))
773
- .command('payment <invoiceId>', 'Record a payment against an invoice', {
774
- 'amount-cents': { type: 'number' },
775
- method: { type: 'string', default: 'cash' },
776
- date: { type: 'string' },
777
- reference: { type: 'string' },
778
- note: { type: 'string' },
779
- }, (args) => recordPayment(args.invoiceId, args))
780
- .command('expiry <id>', 'Show paid-through date, expiry policy and any push-ahead override', {}, (args) => showExpiry(args.id))
781
- .command('set-expiry-policy <id>', 'Set ExpiryPolicy (Default|CustomGrace|NeverExpire) and grace days (audited)', {
782
- policy: { type: 'string' },
783
- 'grace-days': { type: 'number' },
784
- reason: { type: 'string' },
785
- }, (args) => setExpiryPolicy(args.id, args))
786
- .command('send-invoice <invoiceId>', 'Email the invoice to the customer (idempotent; sets SentAt; --force resends)', {
787
- force: { type: 'boolean', default: false },
788
- }, (args) => sendInvoice(args.invoiceId, args))
789
- .command('reminders <id>', 'Show or set payment reminders (--on/--off, --cadence "-7,-1,0,3,7,14" or "" for default, --email addr)', {
790
- on: { type: 'boolean', default: false },
791
- off: { type: 'boolean', default: false },
792
- cadence: { type: 'string' },
793
- email: { type: 'string' },
794
- }, (args) => reminders(args.id, args))
795
- .command('push-expiry <id>', 'Hold access open until a date without changing PaidThroughAt (audited; --clear removes)', {
796
- until: { type: 'string' },
797
- reason: { type: 'string' },
798
- clear: { type: 'boolean', default: false },
799
- }, (args) => pushExpiry(args.id, args))
800
- .command('payments <invoiceId>', 'List payments + balance for an invoice', {}, (args) => listPayments(args.invoiceId))
801
- .command('qbo-status <invoiceId>', 'Show QBO dry-run sync status for an invoice and its payments', {}, (args) => qboStatus(args.invoiceId))
802
- .command('invoice-send-log <invoiceId>', 'Show the durable send/delivery audit log for an invoice -- every recipient, ACS message id, and delivered/bounced/complaint outcome', {}, (args) => invoiceSendLog(args.invoiceId))
803
- .command('renewals', 'List subscriptions by upcoming renewal date, flagging who is still cancellable vs past their cancellation-notice deadline', {
804
- 'within-days': { type: 'number', desc: 'Only show renewals within this many days (default: all)' },
805
- }, (args) => renewalsReport(args))
806
- .command('set-auto-renew <id>', 'Set whether a subscription auto-renews at ServiceEndDate (data flag only -- no sweep enforces it yet)', {
807
- 'auto-renew': { type: 'string', describe: 'true or false' },
808
- }, (args) => setAutoRenew(args.id, args))
809
- .command('cancel <id>', 'Cancel a subscription: bill_more_periods | shutdown_accelerate | shutdown_keep_recognizing | shutdown_after_covered', {
810
- mode: { type: 'string' }, 'extra-periods': { type: 'number' }, 'effective-date': { type: 'string' }, reason: { type: 'string' },
811
- }, (args) => cancelSub(args.id, args))
812
- .command('one-time-invoice <id>', 'Create a one-time invoice (setup/NRE/true-up)', {
813
- description: { type: 'string' }, 'amount-cents': { type: 'number' }, date: { type: 'string' }, po: { type: 'string' },
814
- }, (args) => oneTimeInvoice(args.id, args))
815
- .command('mid-term-upgrade <id>', 'Mid-term upgrade prorated to the current period end (blocks flip-flop within 90 days)', {
816
- 'new-amount-cents': { type: 'number' }, 'effective-date': { type: 'string' }, reason: { type: 'string' },
817
- }, (args) => midTermUpgrade(args.id, args))
818
- .command('schedule-cadence-change <id>', 'Schedule (or cancel) a future BillingCadence change, applied by the hourly sweep once the effective date passes', {
819
- cadence: { type: 'string', describe: 'annual | monthly | quarterly' },
820
- 'effective-at': { type: 'string', describe: 'YYYY-MM-DD the change takes effect' },
821
- cancel: { type: 'boolean', default: false, describe: 'Cancel a previously-scheduled change instead of setting one' },
822
- }, (args) => scheduleCadenceChange(args.id, args))
823
- .command('payment-correct <paymentId>', 'Correct a field on an already-recorded payment (audited, never a silent overwrite)', {
824
- field: { type: 'string', describe: 'date | amount-cents | method | reference | note' },
825
- value: { type: 'string' },
826
- reason: { type: 'string' },
827
- }, (args) => correctPayment(args.paymentId, args))
828
- .command('payment-history <paymentId>', 'Show a payment\'s live value plus every correction ever applied', {}, (args) => paymentHistory(args.paymentId))
829
- .command('invoice-correct <invoiceId>', 'Correct a field on an already-generated invoice (audited, never a silent overwrite)', {
830
- field: { type: 'string', describe: 'po-number | invoice-date | due-date | total-cents | internal-notes | service-period-start | service-period-end' },
831
- value: { type: 'string' },
832
- reason: { type: 'string' },
833
- }, (args) => correctInvoice(args.invoiceId, args))
834
- .command('invoice-history <invoiceId>', 'Show an invoice\'s live value plus every correction ever applied', {}, (args) => invoiceHistory(args.invoiceId))
835
- .command('subscription-correct <id>', 'Correct a field on an existing subscription (audited, never a silent overwrite) -- does NOT touch any invoice already generated against the old dates', {
836
- field: { type: 'string', describe: 'service-start-date|service-end-date|next-bill-date|po-number|notes|recurring-amount-cents|target-system|target-account-id|parallel-billing-mode|billing-cutover-date|external-billing-system|external-billing-account-id|auto-charge-enabled|invoice-delivery-action|invoice-recipient-emails|invoice-cc-emails|invoice-bcc-emails|contract-id|grace-period-days|auto-expire-after-grace-period|exclude-from-entitlement-sync|exclude-from-bulk-price-import' },
837
- value: { type: 'string' },
838
- reason: { type: 'string' },
839
- clear: { type: 'boolean', default: false, describe: 'Explicitly blank out po-number/notes instead of providing --value' },
840
- force: { type: 'boolean', default: false, describe: 'Bypass the customer-name overlap guard when correcting service-start-date/service-end-date' },
841
- }, (args) => correctSubscription(args.id, args))
842
- .command('subscription-history <id>', 'Show a subscription\'s live value plus every correction ever applied', {}, (args) => subscriptionHistory(args.id))
843
- .command('invoice-reissue <invoiceId>', 'Mark an invoice superseded and generate a corrected replacement (kept for audit/historical reasons, never deleted)', {
844
- reason: { type: 'string' },
845
- 'service-period-start': { type: 'string' },
846
- 'service-period-end': { type: 'string' },
847
- 'po-number': { type: 'string' },
848
- 'internal-notes': { type: 'string' },
849
- }, (args) => reissueInvoice(args.invoiceId, args))
850
- .command('release <invoiceId>', 'Release a pending_send_gate invoice to ready_to_send (the Activate action)', {}, (args) => releaseInvoice(args.invoiceId))
851
- .command('test-fire <invoiceId>', 'Send the real invoice email to internal recipients only', {}, (args) => testFireInvoice(args.invoiceId))
852
- .command('issue-now <id>', 'Issue an invoice early, dated today (id = invoice id, or subscription id with --subscription)', {
853
- subscription: { type: 'boolean', default: false },
854
- }, (args) => issueNow(args.id, args))
855
- .command('regenerate <invoiceId>', 'Reissue an unsent invoice with totals regenerated from its line items', {}, (args) => regenerateInvoice(args.invoiceId))
856
- .command('materialize <subscriptionId>', 'Create the next projected invoice for a subscription now', {}, (args) => materializeInvoice(args.subscriptionId))
857
- .command('upcoming', 'List invoices due to send and projected invoices in the next N days', {
858
- days: { type: 'number', default: 30 },
859
- }, (args) => upcomingInvoices(args))
860
- .command('invoice-copy <invoiceId>', 'Clone an invoice into a new DRAFT with a new number (no payments, PDF, or sent state copied)', {
861
- 'service-period-start': { type: 'string' },
862
- 'service-period-end': { type: 'string' },
863
- 'invoice-date': { type: 'string' },
864
- 'po-number': { type: 'string' },
865
- }, (args) => copyInvoice(args.invoiceId, args))
866
- .command('subscription-copy <id>', 'Clone a subscription into a new INACTIVE draft (no billing, no auto-charge, new name required)', {
867
- name: { type: 'string', describe: 'New customer name (required)' },
868
- 'service-start-date': { type: 'string' },
869
- 'service-end-date': { type: 'string' },
870
- }, (args) => copySubscription(args.id, args))
871
- .command('pause <id>', 'Pause recurring billing. The renewal job skips it and auto-resumes at --resume-date', {
872
- 'resume-date': { type: 'string', describe: 'ISO date to auto-resume (optional)' },
873
- 'invoice-behavior': { type: 'string', describe: 'skip (default) | keep_draft | void' },
874
- reason: { type: 'string' },
875
- }, (args) => pauseBilling(args.id, args))
876
- .command('resume <id>', 'Resume paused recurring billing now', {}, (args) => resumeBilling(args.id))
877
- .command('invoice-void <invoiceId>', 'Void a finalized invoice (finalized invoices cannot be deleted, only voided)', {
878
- reason: { type: 'string' },
879
- }, (args) => voidInvoice(args.invoiceId, args))
880
- .command('credit-note <invoiceId>', 'Issue a credit note against an invoice (total or line-level; cannot exceed invoice total)', {
881
- reason: { type: 'string' },
882
- 'amount-cents': { type: 'number' },
883
- lines: { type: 'string', describe: 'lineItemId:cents,lineItemId:cents' },
884
- }, (args) => creditNote(args.invoiceId, args))
885
- .command('credit-notes <invoiceId>', 'List credit notes for an invoice', {}, (args) => creditNotes(args.invoiceId))
886
- .command('credit-note-void <creditNoteId>', 'Void a credit note (restores the amount due)', {
887
- reason: { type: 'string' },
888
- }, (args) => creditNoteVoid(args.creditNoteId, args))
889
- .command('renewal-sweep', 'Manually run the recurring-invoice generator now (same code the daily Hangfire sweep calls)', {}, () => runRenewalSweep())
890
- .command('dunning-report', 'Show past-due invoices and grace-period status (report-only unless a subscription has AutoExpireAfterGracePeriod enabled)', {}, () => runDunningReport())
891
- .command('revenue-report', 'Portfolio-wide recognized revenue by month (built on the same revenue-schedule rows recognition-schedule reads per-invoice)', {
892
- 'from-month': { type: 'string', describe: 'ISO date -- only recognition months on/after this date' },
893
- 'through-month': { type: 'string', describe: 'ISO date -- only recognition months on/before this date' },
894
- }, (args) => revenueReport({ fromMonth: args.fromMonth, throughMonth: args.throughMonth }))
895
- .command('reissue-audit', 'List every invoice that has been superseded (reissued) or is itself a reissue replacement', {}, () => reissueAudit())
896
- .command('qbo-sync <invoiceId>', 'Sync an invoice to QuickBooks (idempotent upsert). Dry-run unless --live is passed.', {
897
- live: { type: 'boolean', default: false, describe: 'Actually call the QBO client (currently NoopQboClient -- no real credentials configured, makes no real API call)' },
898
- }, (args) => qboSync(args.invoiceId, args))
899
- .command('anomalies', 'List invoices currently flagged for anomaly review', {}, () => anomalies())
900
- .command('anomaly-clear <invoiceId>', 'Acknowledge/clear a flagged anomaly on an invoice', {
901
- note: { type: 'string' },
902
- }, (args) => anomalyClear(args.invoiceId, args))
903
- .command('document <invoiceId>', 'Generate a polished, on-brand invoice, receipt, or quote PDF for an invoice. --type receipt is refused unless the invoice is recorded as paid in full. --type quote renders the same invoice record without a due date/INV- number, for pre-sale use.', {
904
- type: { type: 'string', describe: 'invoice | receipt | quote' },
905
- out: { type: 'string', describe: 'Output file path (default: ./<InvoiceNumber>-<type>.pdf in the current directory)' },
906
- }, (args) => generateDocument(args.invoiceId, args))
907
- .demandCommand(1, 'Specify a subcommand: list | get | create | delete | delete-invoice | attach-stripe-customer | invoice | provision-placeholder-site | recognition-schedule | payment | payments | qbo-status | invoice-send-log | renewals | set-auto-renew | cancel | one-time-invoice | mid-term-upgrade | schedule-cadence-change | payment-correct | payment-history | invoice-correct | invoice-history | subscription-correct | subscription-history | invoice-reissue | release | test-fire | issue-now | regenerate | materialize | upcoming | renewal-sweep | dunning-report | revenue-report | reissue-audit | qbo-sync | anomalies | anomaly-clear | document | invoice-copy | subscription-copy | pause | resume | invoice-void | credit-note | credit-notes | credit-note-void | send-invoice | reminders'),
908
- handler: () => {},
909
- };