@ambushsoftworks/nestjs-payments-graphql 0.1.0

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.
Files changed (217) hide show
  1. package/dist/constants.d.ts +17 -0
  2. package/dist/constants.js +21 -0
  3. package/dist/constants.js.map +1 -0
  4. package/dist/dto/create-installment.input.d.ts +5 -0
  5. package/dist/dto/create-installment.input.js +39 -0
  6. package/dist/dto/create-installment.input.js.map +1 -0
  7. package/dist/dto/create-invoice.input.d.ts +13 -0
  8. package/dist/dto/create-invoice.input.js +95 -0
  9. package/dist/dto/create-invoice.input.js.map +1 -0
  10. package/dist/dto/create-line-item.input.d.ts +10 -0
  11. package/dist/dto/create-line-item.input.js +77 -0
  12. package/dist/dto/create-line-item.input.js.map +1 -0
  13. package/dist/dto/create-payment-plan.input.d.ts +11 -0
  14. package/dist/dto/create-payment-plan.input.js +76 -0
  15. package/dist/dto/create-payment-plan.input.js.map +1 -0
  16. package/dist/dto/create-recurring-invoice.input.d.ts +18 -0
  17. package/dist/dto/create-recurring-invoice.input.js +117 -0
  18. package/dist/dto/create-recurring-invoice.input.js.map +1 -0
  19. package/dist/dto/create-recurring-line-item.input.d.ts +10 -0
  20. package/dist/dto/create-recurring-line-item.input.js +77 -0
  21. package/dist/dto/create-recurring-line-item.input.js.map +1 -0
  22. package/dist/dto/create-refund.input.d.ts +5 -0
  23. package/dist/dto/create-refund.input.js +43 -0
  24. package/dist/dto/create-refund.input.js.map +1 -0
  25. package/dist/dto/index.d.ts +8 -0
  26. package/dist/dto/index.js +20 -0
  27. package/dist/dto/index.js.map +1 -0
  28. package/dist/dto/invoice-filter.input.d.ts +10 -0
  29. package/dist/dto/invoice-filter.input.js +64 -0
  30. package/dist/dto/invoice-filter.input.js.map +1 -0
  31. package/dist/dto/payment-plan-filter.input.d.ts +7 -0
  32. package/dist/dto/payment-plan-filter.input.js +46 -0
  33. package/dist/dto/payment-plan-filter.input.js.map +1 -0
  34. package/dist/dto/record-manual-payment.input.d.ts +9 -0
  35. package/dist/dto/record-manual-payment.input.js +58 -0
  36. package/dist/dto/record-manual-payment.input.js.map +1 -0
  37. package/dist/dto/recurring-invoice-filter.input.d.ts +7 -0
  38. package/dist/dto/recurring-invoice-filter.input.js +46 -0
  39. package/dist/dto/recurring-invoice-filter.input.js.map +1 -0
  40. package/dist/dto/update-invoice-metadata.input.d.ts +3 -0
  41. package/dist/dto/update-invoice-metadata.input.js +30 -0
  42. package/dist/dto/update-invoice-metadata.input.js.map +1 -0
  43. package/dist/dto/update-payment-config.input.d.ts +8 -0
  44. package/dist/dto/update-payment-config.input.js +61 -0
  45. package/dist/dto/update-payment-config.input.js.map +1 -0
  46. package/dist/dto/update-recurring-template.input.d.ts +12 -0
  47. package/dist/dto/update-recurring-template.input.js +89 -0
  48. package/dist/dto/update-recurring-template.input.js.map +1 -0
  49. package/dist/dto/upsert-payment-provider.input.d.ts +5 -0
  50. package/dist/dto/upsert-payment-provider.input.js +43 -0
  51. package/dist/dto/upsert-payment-provider.input.js.map +1 -0
  52. package/dist/dto/validators/is-metadata.d.ts +1 -0
  53. package/dist/dto/validators/is-metadata.js +41 -0
  54. package/dist/dto/validators/is-metadata.js.map +1 -0
  55. package/dist/exceptions/index.d.ts +34 -0
  56. package/dist/exceptions/index.js +73 -0
  57. package/dist/exceptions/index.js.map +1 -0
  58. package/dist/gateways/gateway-registry.service.d.ts +10 -0
  59. package/dist/gateways/gateway-registry.service.js +45 -0
  60. package/dist/gateways/gateway-registry.service.js.map +1 -0
  61. package/dist/gateways/payment-gateway.interface.d.ts +50 -0
  62. package/dist/gateways/payment-gateway.interface.js +3 -0
  63. package/dist/gateways/payment-gateway.interface.js.map +1 -0
  64. package/dist/gateways/recurring-payment-gateway.interface.d.ts +32 -0
  65. package/dist/gateways/recurring-payment-gateway.interface.js +3 -0
  66. package/dist/gateways/recurring-payment-gateway.interface.js.map +1 -0
  67. package/dist/gateways/stripe/stripe-webhook.controller.d.ts +24 -0
  68. package/dist/gateways/stripe/stripe-webhook.controller.js +150 -0
  69. package/dist/gateways/stripe/stripe-webhook.controller.js.map +1 -0
  70. package/dist/gateways/stripe/stripe.gateway.d.ts +84 -0
  71. package/dist/gateways/stripe/stripe.gateway.js +424 -0
  72. package/dist/gateways/stripe/stripe.gateway.js.map +1 -0
  73. package/dist/index.d.ts +70 -0
  74. package/dist/index.js +147 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/interfaces/invoice-repository.interface.d.ts +23 -0
  77. package/dist/interfaces/invoice-repository.interface.js +3 -0
  78. package/dist/interfaces/invoice-repository.interface.js.map +1 -0
  79. package/dist/interfaces/payment-config-repository.interface.d.ts +11 -0
  80. package/dist/interfaces/payment-config-repository.interface.js +3 -0
  81. package/dist/interfaces/payment-config-repository.interface.js.map +1 -0
  82. package/dist/interfaces/payment-customer-repository.interface.d.ts +6 -0
  83. package/dist/interfaces/payment-customer-repository.interface.js +3 -0
  84. package/dist/interfaces/payment-customer-repository.interface.js.map +1 -0
  85. package/dist/interfaces/payment-email.interfaces.d.ts +74 -0
  86. package/dist/interfaces/payment-email.interfaces.js +3 -0
  87. package/dist/interfaces/payment-email.interfaces.js.map +1 -0
  88. package/dist/interfaces/payment-event-listener.interface.d.ts +61 -0
  89. package/dist/interfaces/payment-event-listener.interface.js +3 -0
  90. package/dist/interfaces/payment-event-listener.interface.js.map +1 -0
  91. package/dist/interfaces/payment-plan-repository.interface.d.ts +16 -0
  92. package/dist/interfaces/payment-plan-repository.interface.js +3 -0
  93. package/dist/interfaces/payment-plan-repository.interface.js.map +1 -0
  94. package/dist/interfaces/payment-repository.interface.d.ts +13 -0
  95. package/dist/interfaces/payment-repository.interface.js +3 -0
  96. package/dist/interfaces/payment-repository.interface.js.map +1 -0
  97. package/dist/interfaces/recurring-invoice-repository.interface.d.ts +16 -0
  98. package/dist/interfaces/recurring-invoice-repository.interface.js +3 -0
  99. package/dist/interfaces/recurring-invoice-repository.interface.js.map +1 -0
  100. package/dist/interfaces/refund-repository.interface.d.ts +8 -0
  101. package/dist/interfaces/refund-repository.interface.js +3 -0
  102. package/dist/interfaces/refund-repository.interface.js.map +1 -0
  103. package/dist/interfaces/transaction-manager.interface.d.ts +19 -0
  104. package/dist/interfaces/transaction-manager.interface.js +3 -0
  105. package/dist/interfaces/transaction-manager.interface.js.map +1 -0
  106. package/dist/interfaces/webhook-idempotency-repository.interface.d.ts +5 -0
  107. package/dist/interfaces/webhook-idempotency-repository.interface.js +3 -0
  108. package/dist/interfaces/webhook-idempotency-repository.interface.js.map +1 -0
  109. package/dist/models/e-transfer-instructions.model.d.ts +11 -0
  110. package/dist/models/e-transfer-instructions.model.js +56 -0
  111. package/dist/models/e-transfer-instructions.model.js.map +1 -0
  112. package/dist/models/index.d.ts +13 -0
  113. package/dist/models/index.js +36 -0
  114. package/dist/models/index.js.map +1 -0
  115. package/dist/models/invoice-client.model.d.ts +5 -0
  116. package/dist/models/invoice-client.model.js +32 -0
  117. package/dist/models/invoice-client.model.js.map +1 -0
  118. package/dist/models/invoice-line-item.model.d.ts +14 -0
  119. package/dist/models/invoice-line-item.model.js +72 -0
  120. package/dist/models/invoice-line-item.model.js.map +1 -0
  121. package/dist/models/invoice.model.d.ts +86 -0
  122. package/dist/models/invoice.model.js +210 -0
  123. package/dist/models/invoice.model.js.map +1 -0
  124. package/dist/models/online-payment-session.model.d.ts +6 -0
  125. package/dist/models/online-payment-session.model.js +40 -0
  126. package/dist/models/online-payment-session.model.js.map +1 -0
  127. package/dist/models/paginated-invoices.model.d.ts +5 -0
  128. package/dist/models/paginated-invoices.model.js +19 -0
  129. package/dist/models/paginated-invoices.model.js.map +1 -0
  130. package/dist/models/paginated-payment-plans.model.d.ts +5 -0
  131. package/dist/models/paginated-payment-plans.model.js +19 -0
  132. package/dist/models/paginated-payment-plans.model.js.map +1 -0
  133. package/dist/models/paginated-recurring-invoices.model.d.ts +5 -0
  134. package/dist/models/paginated-recurring-invoices.model.js +19 -0
  135. package/dist/models/paginated-recurring-invoices.model.js.map +1 -0
  136. package/dist/models/paginated.model.d.ts +6 -0
  137. package/dist/models/paginated.model.js +30 -0
  138. package/dist/models/paginated.model.js.map +1 -0
  139. package/dist/models/payment-config.model.d.ts +21 -0
  140. package/dist/models/payment-config.model.js +98 -0
  141. package/dist/models/payment-config.model.js.map +1 -0
  142. package/dist/models/payment-method-setup.model.d.ts +4 -0
  143. package/dist/models/payment-method-setup.model.js +32 -0
  144. package/dist/models/payment-method-setup.model.js.map +1 -0
  145. package/dist/models/payment-plan-installment.model.d.ts +12 -0
  146. package/dist/models/payment-plan-installment.model.js +57 -0
  147. package/dist/models/payment-plan-installment.model.js.map +1 -0
  148. package/dist/models/payment-plan.model.d.ts +25 -0
  149. package/dist/models/payment-plan.model.js +105 -0
  150. package/dist/models/payment-plan.model.js.map +1 -0
  151. package/dist/models/payment.model.d.ts +23 -0
  152. package/dist/models/payment.model.js +102 -0
  153. package/dist/models/payment.model.js.map +1 -0
  154. package/dist/models/recurring-invoice-line-item.model.d.ts +14 -0
  155. package/dist/models/recurring-invoice-line-item.model.js +72 -0
  156. package/dist/models/recurring-invoice-line-item.model.js.map +1 -0
  157. package/dist/models/recurring-invoice.model.d.ts +43 -0
  158. package/dist/models/recurring-invoice.model.js +157 -0
  159. package/dist/models/recurring-invoice.model.js.map +1 -0
  160. package/dist/models/refund.model.d.ts +15 -0
  161. package/dist/models/refund.model.js +73 -0
  162. package/dist/models/refund.model.js.map +1 -0
  163. package/dist/payments.module.d.ts +54 -0
  164. package/dist/payments.module.js +211 -0
  165. package/dist/payments.module.js.map +1 -0
  166. package/dist/register-payment-enums.d.ts +1 -0
  167. package/dist/register-payment-enums.js +18 -0
  168. package/dist/register-payment-enums.js.map +1 -0
  169. package/dist/services/customer.service.d.ts +15 -0
  170. package/dist/services/customer.service.js +63 -0
  171. package/dist/services/customer.service.js.map +1 -0
  172. package/dist/services/default-payment-email-templates.d.ts +8 -0
  173. package/dist/services/default-payment-email-templates.js +249 -0
  174. package/dist/services/default-payment-email-templates.js.map +1 -0
  175. package/dist/services/e-transfer.service.d.ts +35 -0
  176. package/dist/services/e-transfer.service.js +93 -0
  177. package/dist/services/e-transfer.service.js.map +1 -0
  178. package/dist/services/invoice-number.service.d.ts +9 -0
  179. package/dist/services/invoice-number.service.js +56 -0
  180. package/dist/services/invoice-number.service.js.map +1 -0
  181. package/dist/services/invoice.service.d.ts +66 -0
  182. package/dist/services/invoice.service.js +293 -0
  183. package/dist/services/invoice.service.js.map +1 -0
  184. package/dist/services/payment-config.service.d.ts +26 -0
  185. package/dist/services/payment-config.service.js +90 -0
  186. package/dist/services/payment-config.service.js.map +1 -0
  187. package/dist/services/payment-email.service.d.ts +20 -0
  188. package/dist/services/payment-email.service.js +153 -0
  189. package/dist/services/payment-email.service.js.map +1 -0
  190. package/dist/services/payment-plan.service.d.ts +47 -0
  191. package/dist/services/payment-plan.service.js +264 -0
  192. package/dist/services/payment-plan.service.js.map +1 -0
  193. package/dist/services/payment.service.d.ts +65 -0
  194. package/dist/services/payment.service.js +532 -0
  195. package/dist/services/payment.service.js.map +1 -0
  196. package/dist/services/recurring-interval.util.d.ts +3 -0
  197. package/dist/services/recurring-interval.util.js +43 -0
  198. package/dist/services/recurring-interval.util.js.map +1 -0
  199. package/dist/services/recurring-invoice.service.d.ts +88 -0
  200. package/dist/services/recurring-invoice.service.js +450 -0
  201. package/dist/services/recurring-invoice.service.js.map +1 -0
  202. package/dist/services/refund.service.d.ts +44 -0
  203. package/dist/services/refund.service.js +373 -0
  204. package/dist/services/refund.service.js.map +1 -0
  205. package/dist/services/static-branding-resolver.d.ts +6 -0
  206. package/dist/services/static-branding-resolver.js +13 -0
  207. package/dist/services/static-branding-resolver.js.map +1 -0
  208. package/dist/types/index.d.ts +240 -0
  209. package/dist/types/index.js +19 -0
  210. package/dist/types/index.js.map +1 -0
  211. package/dist/types/payment-customer.types.d.ts +15 -0
  212. package/dist/types/payment-customer.types.js +3 -0
  213. package/dist/types/payment-customer.types.js.map +1 -0
  214. package/dist/types/recurring-invoice.types.d.ts +84 -0
  215. package/dist/types/recurring-invoice.types.js +3 -0
  216. package/dist/types/recurring-invoice.types.js.map +1 -0
  217. package/package.json +70 -0
@@ -0,0 +1,88 @@
1
+ import { type OnModuleInit } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+ import type { IRecurringInvoiceRepository } from '../interfaces/recurring-invoice-repository.interface';
4
+ import type { RecurringInvoice, RecurringInvoiceWithItems, RecurringInvoiceFilter } from '../types/recurring-invoice.types';
5
+ import type { InvoiceWithItems } from '../types';
6
+ import { InvoiceService } from './invoice.service';
7
+ import { PaymentService } from './payment.service';
8
+ import { PaymentConfigService } from './payment-config.service';
9
+ import { CustomerService } from './customer.service';
10
+ import { GatewayRegistryService } from '../gateways/gateway-registry.service';
11
+ export interface CreateRecurringInvoiceInput {
12
+ intervalUnit: 'DAYS' | 'MONTHS';
13
+ intervalValue: number;
14
+ anchorDate: Date;
15
+ nextInvoiceAt?: Date;
16
+ clientDetailsId: string;
17
+ currency?: string;
18
+ taxRate?: number;
19
+ autoSend?: boolean;
20
+ notes?: string;
21
+ clientNotes?: string;
22
+ referenceType?: string;
23
+ referenceId?: string;
24
+ metadata?: Record<string, unknown> | null;
25
+ lineItems?: Array<{
26
+ description: string;
27
+ quantity: number;
28
+ unitPrice: number;
29
+ sortOrder?: number;
30
+ isTaxable?: boolean;
31
+ referenceType?: string;
32
+ referenceId?: string;
33
+ metadata?: Record<string, unknown> | null;
34
+ }>;
35
+ }
36
+ export interface UpdateRecurringTemplateInput {
37
+ taxRate?: number;
38
+ currency?: string;
39
+ notes?: string | null;
40
+ clientNotes?: string | null;
41
+ referenceType?: string | null;
42
+ referenceId?: string | null;
43
+ metadata?: Record<string, unknown> | null;
44
+ autoSend?: boolean;
45
+ lineItems?: Array<{
46
+ description: string;
47
+ quantity: number;
48
+ unitPrice: number;
49
+ sortOrder?: number;
50
+ isTaxable?: boolean;
51
+ referenceType?: string;
52
+ referenceId?: string;
53
+ metadata?: Record<string, unknown> | null;
54
+ }>;
55
+ }
56
+ export declare class RecurringInvoiceService implements OnModuleInit {
57
+ private readonly repo;
58
+ private readonly invoiceService;
59
+ private readonly paymentService;
60
+ private readonly configService;
61
+ private readonly customerService;
62
+ private readonly gatewayRegistry;
63
+ private readonly moduleRef;
64
+ private readonly logger;
65
+ private paymentEventListener;
66
+ constructor(repo: IRecurringInvoiceRepository, invoiceService: InvoiceService, paymentService: PaymentService, configService: PaymentConfigService, customerService: CustomerService, gatewayRegistry: GatewayRegistryService, moduleRef: ModuleRef);
67
+ onModuleInit(): void;
68
+ create(divisionId: string, input: CreateRecurringInvoiceInput, createdBy: string): Promise<RecurringInvoiceWithItems>;
69
+ pause(id: string, divisionId: string, pausedBy: string, reason?: string): Promise<RecurringInvoice>;
70
+ resume(id: string, divisionId: string): Promise<RecurringInvoice>;
71
+ cancel(id: string, divisionId: string, cancelledBy: string, reason?: string): Promise<RecurringInvoice>;
72
+ updateTemplate(id: string, divisionId: string, input: UpdateRecurringTemplateInput): Promise<RecurringInvoiceWithItems>;
73
+ findById(divisionId: string, id: string): Promise<RecurringInvoiceWithItems | null>;
74
+ findByDivision(divisionId: string, filter?: RecurringInvoiceFilter, skip?: number, take?: number): Promise<{
75
+ items: RecurringInvoice[];
76
+ totalCount: number;
77
+ }>;
78
+ processDueRecurringInvoices(now: Date): Promise<{
79
+ generated: number;
80
+ errors: number;
81
+ }>;
82
+ triggerRecurringInvoice(id: string, divisionId: string): Promise<InvoiceWithItems>;
83
+ private generateInvoiceFromConfig;
84
+ private attemptAutoCharge;
85
+ private handleChargeFailure;
86
+ private resolveTaxRate;
87
+ private findAndVerifyDivision;
88
+ }
@@ -0,0 +1,450 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var RecurringInvoiceService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.RecurringInvoiceService = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const core_1 = require("@nestjs/core");
19
+ const constants_1 = require("../constants");
20
+ const exceptions_1 = require("../exceptions");
21
+ const invoice_service_1 = require("./invoice.service");
22
+ const payment_service_1 = require("./payment.service");
23
+ const payment_config_service_1 = require("./payment-config.service");
24
+ const customer_service_1 = require("./customer.service");
25
+ const gateway_registry_service_1 = require("../gateways/gateway-registry.service");
26
+ const recurring_interval_util_1 = require("./recurring-interval.util");
27
+ const UPDATABLE_STATUSES = new Set(['ACTIVE', 'PAUSED']);
28
+ const CANCELLABLE_STATUSES = new Set(['ACTIVE', 'PAUSED']);
29
+ const TRIGGERABLE_STATUSES = new Set(['ACTIVE', 'PAUSED']);
30
+ class SimpleDecimal {
31
+ constructor(value) {
32
+ this.value = value;
33
+ }
34
+ toNumber() {
35
+ return this.value;
36
+ }
37
+ toString() {
38
+ return String(this.value);
39
+ }
40
+ }
41
+ let RecurringInvoiceService = RecurringInvoiceService_1 = class RecurringInvoiceService {
42
+ constructor(repo, invoiceService, paymentService, configService, customerService, gatewayRegistry, moduleRef) {
43
+ this.repo = repo;
44
+ this.invoiceService = invoiceService;
45
+ this.paymentService = paymentService;
46
+ this.configService = configService;
47
+ this.customerService = customerService;
48
+ this.gatewayRegistry = gatewayRegistry;
49
+ this.moduleRef = moduleRef;
50
+ this.logger = new common_1.Logger(RecurringInvoiceService_1.name);
51
+ this.paymentEventListener = null;
52
+ }
53
+ onModuleInit() {
54
+ try {
55
+ this.paymentEventListener = this.moduleRef.get(constants_1.PAYMENT_EVENT_LISTENER, {
56
+ strict: false,
57
+ });
58
+ this.logger.log('Payment event listener resolved successfully');
59
+ }
60
+ catch {
61
+ this.paymentEventListener = null;
62
+ this.logger.log('No payment event listener registered — recurring invoice events disabled');
63
+ }
64
+ }
65
+ async create(divisionId, input, createdBy) {
66
+ if (input.intervalValue < 1) {
67
+ throw new exceptions_1.InvalidRecurringInvoiceStateException('intervalValue must be >= 1');
68
+ }
69
+ const nextInvoiceAt = input.nextInvoiceAt ??
70
+ (0, recurring_interval_util_1.computeNextInvoiceDate)(input.anchorDate, input.intervalUnit, input.intervalValue, 1);
71
+ const taxRate = await this.resolveTaxRate(divisionId, input.taxRate);
72
+ const createData = {
73
+ divisionId,
74
+ intervalUnit: input.intervalUnit,
75
+ intervalValue: input.intervalValue,
76
+ anchorDate: input.anchorDate,
77
+ nextInvoiceAt,
78
+ clientDetailsId: input.clientDetailsId,
79
+ createdBy,
80
+ currency: input.currency,
81
+ taxRate,
82
+ autoSend: input.autoSend,
83
+ notes: input.notes,
84
+ clientNotes: input.clientNotes,
85
+ referenceType: input.referenceType,
86
+ referenceId: input.referenceId,
87
+ metadata: input.metadata,
88
+ };
89
+ const config = await this.repo.create(createData);
90
+ if (input.lineItems && input.lineItems.length > 0) {
91
+ for (let i = 0; i < input.lineItems.length; i++) {
92
+ const item = input.lineItems[i];
93
+ await this.repo.createLineItem({
94
+ recurringInvoiceId: config.id,
95
+ description: item.description,
96
+ quantity: item.quantity,
97
+ unitPrice: item.unitPrice,
98
+ sortOrder: item.sortOrder ?? i,
99
+ isTaxable: item.isTaxable,
100
+ referenceType: item.referenceType,
101
+ referenceId: item.referenceId,
102
+ metadata: item.metadata,
103
+ });
104
+ }
105
+ }
106
+ const result = await this.repo.findByIdWithItems(config.id);
107
+ if (!result) {
108
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${config.id} not found after creation`);
109
+ }
110
+ return result;
111
+ }
112
+ async pause(id, divisionId, pausedBy, reason) {
113
+ const config = await this.findAndVerifyDivision(id, divisionId);
114
+ if (config.status !== 'ACTIVE') {
115
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Cannot pause recurring invoice in "${config.status}" status. Must be ACTIVE.`);
116
+ }
117
+ return this.repo.update(id, {
118
+ status: 'PAUSED',
119
+ pausedAt: new Date(),
120
+ pausedBy,
121
+ });
122
+ }
123
+ async resume(id, divisionId) {
124
+ const config = await this.findAndVerifyDivision(id, divisionId);
125
+ if (config.status !== 'PAUSED') {
126
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Cannot resume recurring invoice in "${config.status}" status. Must be PAUSED.`);
127
+ }
128
+ const now = new Date();
129
+ let nextInvoiceAt = config.nextInvoiceAt;
130
+ if (nextInvoiceAt <= now) {
131
+ const currentCycle = (0, recurring_interval_util_1.computeCycleCount)(config.anchorDate, now, config.intervalUnit, config.intervalValue);
132
+ nextInvoiceAt = (0, recurring_interval_util_1.computeNextInvoiceDate)(config.anchorDate, config.intervalUnit, config.intervalValue, currentCycle + 1);
133
+ }
134
+ return this.repo.update(id, {
135
+ status: 'ACTIVE',
136
+ pausedAt: null,
137
+ pausedBy: null,
138
+ consecutiveFailures: 0,
139
+ nextInvoiceAt,
140
+ });
141
+ }
142
+ async cancel(id, divisionId, cancelledBy, reason) {
143
+ const config = await this.findAndVerifyDivision(id, divisionId);
144
+ if (!CANCELLABLE_STATUSES.has(config.status)) {
145
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Cannot cancel recurring invoice in "${config.status}" status. Must be ACTIVE or PAUSED.`);
146
+ }
147
+ return this.repo.update(id, {
148
+ status: 'CANCELLED',
149
+ cancelledAt: new Date(),
150
+ cancelledBy,
151
+ cancelReason: reason ?? null,
152
+ });
153
+ }
154
+ async updateTemplate(id, divisionId, input) {
155
+ const config = await this.findAndVerifyDivision(id, divisionId);
156
+ if (!UPDATABLE_STATUSES.has(config.status)) {
157
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Cannot update recurring invoice in "${config.status}" status. Must be ACTIVE or PAUSED.`);
158
+ }
159
+ const updateData = {};
160
+ if (input.taxRate !== undefined) {
161
+ updateData.taxRate = new SimpleDecimal(input.taxRate);
162
+ }
163
+ if (input.currency !== undefined) {
164
+ updateData.currency = input.currency;
165
+ }
166
+ if (input.notes !== undefined) {
167
+ updateData.notes = input.notes;
168
+ }
169
+ if (input.clientNotes !== undefined) {
170
+ updateData.clientNotes = input.clientNotes;
171
+ }
172
+ if (input.referenceType !== undefined) {
173
+ updateData.referenceType = input.referenceType;
174
+ }
175
+ if (input.referenceId !== undefined) {
176
+ updateData.referenceId = input.referenceId;
177
+ }
178
+ if (input.metadata !== undefined) {
179
+ updateData.metadata = input.metadata;
180
+ }
181
+ if (input.autoSend !== undefined) {
182
+ updateData.autoSend = input.autoSend;
183
+ }
184
+ if (Object.keys(updateData).length > 0) {
185
+ await this.repo.update(id, updateData);
186
+ }
187
+ if (input.lineItems !== undefined) {
188
+ const lineItemData = input.lineItems.map((item, i) => ({
189
+ recurringInvoiceId: id,
190
+ description: item.description,
191
+ quantity: item.quantity,
192
+ unitPrice: item.unitPrice,
193
+ sortOrder: item.sortOrder ?? i,
194
+ isTaxable: item.isTaxable,
195
+ referenceType: item.referenceType,
196
+ referenceId: item.referenceId,
197
+ metadata: item.metadata,
198
+ }));
199
+ await this.repo.replaceLineItems(id, lineItemData);
200
+ }
201
+ const result = await this.repo.findByIdWithItems(id);
202
+ if (!result) {
203
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${id} not found after update`);
204
+ }
205
+ return result;
206
+ }
207
+ async findById(divisionId, id) {
208
+ const config = await this.repo.findByIdWithItems(id);
209
+ if (!config) {
210
+ return null;
211
+ }
212
+ if (config.divisionId !== divisionId) {
213
+ return null;
214
+ }
215
+ return config;
216
+ }
217
+ async findByDivision(divisionId, filter, skip, take) {
218
+ return this.repo.findByDivision(divisionId, filter, skip, take);
219
+ }
220
+ async processDueRecurringInvoices(now) {
221
+ let generated = 0;
222
+ let errors = 0;
223
+ const computeNextDateFn = (config) => {
224
+ const currentCycle = (0, recurring_interval_util_1.computeCycleCount)(config.anchorDate, config.nextInvoiceAt, config.intervalUnit, config.intervalValue);
225
+ return (0, recurring_interval_util_1.computeNextInvoiceDate)(config.anchorDate, config.intervalUnit, config.intervalValue, currentCycle + 1);
226
+ };
227
+ let batchSize;
228
+ do {
229
+ const claimed = await this.repo.claimDueRecurringInvoices(now, 100, computeNextDateFn);
230
+ batchSize = claimed.length;
231
+ for (const config of claimed) {
232
+ try {
233
+ await this.generateInvoiceFromConfig(config);
234
+ generated++;
235
+ }
236
+ catch (error) {
237
+ errors++;
238
+ this.logger.error(`Failed to generate invoice for recurring config ${config.id}: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error.stack : undefined);
239
+ }
240
+ }
241
+ } while (batchSize > 0);
242
+ if (generated > 0 || errors > 0) {
243
+ this.logger.log(`Recurring invoice processing complete: ${generated} generated, ${errors} errors`);
244
+ }
245
+ return { generated, errors };
246
+ }
247
+ async triggerRecurringInvoice(id, divisionId) {
248
+ const config = await this.repo.findByIdWithItems(id);
249
+ if (!config) {
250
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${id} not found`);
251
+ }
252
+ if (config.divisionId !== divisionId) {
253
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${id} does not belong to division ${divisionId}`);
254
+ }
255
+ if (!TRIGGERABLE_STATUSES.has(config.status)) {
256
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Cannot trigger recurring invoice in "${config.status}" status. Must be ACTIVE or PAUSED.`);
257
+ }
258
+ return this.generateInvoiceFromConfig(config);
259
+ }
260
+ async generateInvoiceFromConfig(config) {
261
+ const invoiceInput = {
262
+ clientDetailsId: config.clientDetailsId,
263
+ currency: config.currency,
264
+ taxRate: config.taxRate.toNumber(),
265
+ notes: config.notes ?? undefined,
266
+ clientNotes: config.clientNotes ?? undefined,
267
+ referenceType: config.referenceType ?? undefined,
268
+ referenceId: config.referenceId ?? undefined,
269
+ metadata: config.metadata,
270
+ recurringInvoiceId: config.id,
271
+ lineItems: config.templateLineItems.map((item) => ({
272
+ description: item.description,
273
+ quantity: item.quantity,
274
+ unitPrice: item.unitPrice,
275
+ sortOrder: item.sortOrder,
276
+ isTaxable: item.isTaxable,
277
+ referenceType: item.referenceType ?? undefined,
278
+ referenceId: item.referenceId ?? undefined,
279
+ metadata: item.metadata,
280
+ })),
281
+ };
282
+ const invoice = await this.invoiceService.createInvoice(config.divisionId, invoiceInput, config.createdBy);
283
+ if (config.autoSend) {
284
+ try {
285
+ const paymentConfig = await this.configService.getConfig(config.divisionId);
286
+ const eTransferEnabled = paymentConfig?.eTransferEnabled ?? false;
287
+ const eTransferAutoDeposit = paymentConfig?.eTransferAutoDeposit ?? false;
288
+ const eTransferConfig = eTransferEnabled &&
289
+ paymentConfig?.eTransferEmail &&
290
+ paymentConfig?.eTransferRecipient
291
+ ? {
292
+ eTransferEmail: paymentConfig.eTransferEmail,
293
+ eTransferRecipient: paymentConfig.eTransferRecipient,
294
+ }
295
+ : undefined;
296
+ await this.invoiceService.sendInvoice(invoice.id, eTransferEnabled, eTransferAutoDeposit, eTransferConfig);
297
+ }
298
+ catch (error) {
299
+ this.logger.error(`Failed to auto-send invoice ${invoice.id} for recurring config ${config.id}: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error.stack : undefined);
300
+ }
301
+ }
302
+ if (config.autoCharge) {
303
+ await this.attemptAutoCharge(config, invoice);
304
+ }
305
+ await this.repo.update(config.id, {
306
+ lastGeneratedAt: new Date(),
307
+ });
308
+ if (this.paymentEventListener?.onRecurringInvoiceGenerated) {
309
+ try {
310
+ const event = {
311
+ recurringInvoiceId: config.id,
312
+ invoiceId: invoice.id,
313
+ divisionId: config.divisionId,
314
+ referenceType: config.referenceType,
315
+ referenceId: config.referenceId,
316
+ isAutoCharge: config.autoCharge,
317
+ metadata: config.metadata,
318
+ };
319
+ await this.paymentEventListener.onRecurringInvoiceGenerated(event);
320
+ }
321
+ catch (error) {
322
+ this.logger.error(`Failed to fire onRecurringInvoiceGenerated event for config ${config.id}: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error.stack : undefined);
323
+ }
324
+ }
325
+ return invoice;
326
+ }
327
+ async attemptAutoCharge(config, invoice) {
328
+ try {
329
+ const customer = await this.customerService.findCustomer(config.divisionId, config.clientDetailsId, 'stripe');
330
+ if (!customer) {
331
+ this.logger.warn(`Auto-charge enabled for recurring invoice ${config.id} but no payment customer found — skipping auto-charge`);
332
+ await this.handleChargeFailure(config, invoice, 'no_payment_customer');
333
+ return;
334
+ }
335
+ const gateway = this.gatewayRegistry.getRecurring('stripe');
336
+ const result = await gateway.createOffSessionPayment({
337
+ providerCustomerId: customer.providerCustomerId,
338
+ amount: invoice.total,
339
+ currency: invoice.currency,
340
+ description: `Invoice ${invoice.invoiceNumber}`,
341
+ metadata: {
342
+ invoiceId: invoice.id,
343
+ recurringInvoiceId: config.id,
344
+ },
345
+ });
346
+ if (result.status === 'succeeded') {
347
+ await this.paymentService.recordAutoChargePayment({
348
+ invoiceId: invoice.id,
349
+ amount: invoice.total,
350
+ currency: invoice.currency,
351
+ provider: 'stripe',
352
+ providerPaymentId: result.providerPaymentId,
353
+ receiptUrl: result.receiptUrl,
354
+ });
355
+ await this.repo.update(config.id, {
356
+ consecutiveFailures: 0,
357
+ lastFailureReason: null,
358
+ });
359
+ this.logger.log(`Auto-charge succeeded for recurring invoice ${config.id}, invoice ${invoice.id}`);
360
+ }
361
+ else {
362
+ const failureReason = result.failureReason ?? result.status;
363
+ await this.handleChargeFailure(config, invoice, failureReason);
364
+ }
365
+ }
366
+ catch (error) {
367
+ this.logger.error(`Auto-charge error for recurring invoice ${config.id}: ${error instanceof Error ? error.message : String(error)}`);
368
+ await this.handleChargeFailure(config, invoice, error instanceof Error ? error.message : 'unknown_error');
369
+ }
370
+ }
371
+ async handleChargeFailure(config, invoice, failureReason) {
372
+ const newFailureCount = config.consecutiveFailures + 1;
373
+ const shouldPause = newFailureCount >= 3;
374
+ await this.repo.update(config.id, {
375
+ consecutiveFailures: newFailureCount,
376
+ lastFailureReason: failureReason,
377
+ ...(shouldPause
378
+ ? {
379
+ status: 'PAUSED',
380
+ pausedAt: new Date(),
381
+ pausedBy: 'system',
382
+ }
383
+ : {}),
384
+ });
385
+ if (this.paymentEventListener?.onRecurringPaymentFailed) {
386
+ try {
387
+ await this.paymentEventListener.onRecurringPaymentFailed({
388
+ recurringInvoiceId: config.id,
389
+ invoiceId: invoice.id,
390
+ divisionId: config.divisionId,
391
+ referenceType: config.referenceType,
392
+ referenceId: config.referenceId,
393
+ failureReason,
394
+ consecutiveFailures: newFailureCount,
395
+ isPaused: shouldPause,
396
+ metadata: config.metadata,
397
+ });
398
+ }
399
+ catch (err) {
400
+ this.logger.warn(`Recurring payment failed event listener error: ${err instanceof Error ? err.message : String(err)}`);
401
+ }
402
+ }
403
+ if (shouldPause && this.paymentEventListener?.onRecurringInvoicePaused) {
404
+ try {
405
+ await this.paymentEventListener.onRecurringInvoicePaused({
406
+ recurringInvoiceId: config.id,
407
+ divisionId: config.divisionId,
408
+ reason: `Auto-paused after ${newFailureCount} consecutive payment failures (last: ${failureReason})`,
409
+ metadata: config.metadata,
410
+ });
411
+ }
412
+ catch (err) {
413
+ this.logger.warn(`Recurring invoice paused event listener error: ${err instanceof Error ? err.message : String(err)}`);
414
+ }
415
+ }
416
+ this.logger.warn(`Auto-charge failed for recurring invoice ${config.id}: ${failureReason} (failures: ${newFailureCount}${shouldPause ? ', auto-paused' : ''})`);
417
+ }
418
+ async resolveTaxRate(divisionId, inputTaxRate) {
419
+ if (inputTaxRate !== undefined) {
420
+ return new SimpleDecimal(inputTaxRate);
421
+ }
422
+ const config = await this.configService.getConfig(divisionId);
423
+ if (config?.defaultTaxRate) {
424
+ return config.defaultTaxRate;
425
+ }
426
+ return new SimpleDecimal(0);
427
+ }
428
+ async findAndVerifyDivision(id, divisionId) {
429
+ const config = await this.repo.findById(id);
430
+ if (!config) {
431
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${id} not found`);
432
+ }
433
+ if (config.divisionId !== divisionId) {
434
+ throw new exceptions_1.InvalidRecurringInvoiceStateException(`Recurring invoice ${id} does not belong to division ${divisionId}`);
435
+ }
436
+ return config;
437
+ }
438
+ };
439
+ exports.RecurringInvoiceService = RecurringInvoiceService;
440
+ exports.RecurringInvoiceService = RecurringInvoiceService = RecurringInvoiceService_1 = __decorate([
441
+ (0, common_1.Injectable)(),
442
+ __param(0, (0, common_1.Inject)(constants_1.RECURRING_INVOICE_REPOSITORY)),
443
+ __metadata("design:paramtypes", [Object, invoice_service_1.InvoiceService,
444
+ payment_service_1.PaymentService,
445
+ payment_config_service_1.PaymentConfigService,
446
+ customer_service_1.CustomerService,
447
+ gateway_registry_service_1.GatewayRegistryService,
448
+ core_1.ModuleRef])
449
+ ], RecurringInvoiceService);
450
+ //# sourceMappingURL=recurring-invoice.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recurring-invoice.service.js","sourceRoot":"","sources":["../../src/services/recurring-invoice.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAA+E;AAC/E,uCAAyC;AAEzC,4CAGsB;AAatB,8CAAsE;AACtE,uDAA4E;AAC5E,uDAAmD;AACnD,qEAAgE;AAChE,yDAAqD;AACrD,mFAA8E;AAC9E,uEAGmC;AAGnC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAGzD,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAG3D,MAAM,oBAAoB,G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;QAErB,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;YAC/B,OAAO,IAAI,aAAa,CAAC,YAAY,CAAC,CAAC;QACzC,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAC9D,IAAI,MAAM,EAAE,cAAc,EAAE,CAAC;YAC3B,OAAO,MAAM,CAAC,cAAc,CAAC;QAC/B,CAAC;QAED,OAAO,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;IAOO,KAAK,CAAC,qBAAqB,CACjC,EAAU,EACV,UAAkB;QAElB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,kDAAqC,CAC7C,qBAAqB,EAAE,YAAY,CACpC,CAAC;QACJ,CAAC;QAED,IAAI,MAAM,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;YACrC,MAAM,IAAI,kDAAqC,CAC7C,qBAAqB,EAAE,gCAAgC,UAAU,EAAE,CACpE,CAAC;QACJ,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAA;AAjsBY,0DAAuB;kCAAvB,uBAAuB;IADnC,IAAA,mBAAU,GAAE;IAMR,WAAA,IAAA,eAAM,EAAC,wCAA4B,CAAC,CAAA;6CAEJ,gCAAc;QACd,gCAAc;QACf,6CAAoB;QAClB,kCAAe;QACf,iDAAsB;QAC5B,gBAAS;GAZ5B,uBAAuB,CAisBnC"}
@@ -0,0 +1,44 @@
1
+ import { type OnModuleInit } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+ import type { IInvoiceRepository } from '../interfaces/invoice-repository.interface';
4
+ import type { IPaymentRepository } from '../interfaces/payment-repository.interface';
5
+ import type { IRefundRepository } from '../interfaces/refund-repository.interface';
6
+ import type { IWebhookIdempotencyRepository } from '../interfaces/webhook-idempotency-repository.interface';
7
+ import type { ITransactionManager } from '../interfaces/transaction-manager.interface';
8
+ import type { Refund } from '../types';
9
+ import type { PaymentWebhookEvent } from '../gateways/payment-gateway.interface';
10
+ import { GatewayRegistryService } from '../gateways/gateway-registry.service';
11
+ export interface CreateRefundInput {
12
+ paymentId: string;
13
+ amount?: number;
14
+ reason?: string;
15
+ createdBy: string;
16
+ }
17
+ export declare class RefundService implements OnModuleInit {
18
+ private readonly invoiceRepo;
19
+ private readonly paymentRepo;
20
+ private readonly refundRepo;
21
+ private readonly webhookIdempotencyRepo;
22
+ private readonly transactionManager;
23
+ private readonly gatewayRegistry;
24
+ private readonly moduleRef;
25
+ private readonly logger;
26
+ private paymentEventListener;
27
+ private paymentEmailService;
28
+ constructor(invoiceRepo: IInvoiceRepository, paymentRepo: IPaymentRepository, refundRepo: IRefundRepository, webhookIdempotencyRepo: IWebhookIdempotencyRepository, transactionManager: ITransactionManager, gatewayRegistry: GatewayRegistryService, moduleRef: ModuleRef);
29
+ onModuleInit(): void;
30
+ createRefund(input: CreateRefundInput): Promise<Refund>;
31
+ handleRefundSucceeded(event: PaymentWebhookEvent): Promise<void>;
32
+ handleRefundFailed(event: PaymentWebhookEvent): Promise<void>;
33
+ refundInvoice(invoiceId: string, createdBy: string): Promise<void>;
34
+ findRefundsByPaymentId(paymentId: string): Promise<Refund[]>;
35
+ private createOnlineRefund;
36
+ private createManualRefund;
37
+ private recalculateInvoiceAmounts;
38
+ private updatePaymentRefundStatus;
39
+ private sendRefundEmail;
40
+ private buildRefundSnapshot;
41
+ private emitRefundEvent;
42
+ private enrichRefundSnapshot;
43
+ private findRefundByProviderRefundId;
44
+ }