@instabrain-sdks/api-client 2.3.3 → 2.5.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.
- package/README.md +1140 -85
- package/dist/client/instabrain-client.d.ts +187 -11
- package/dist/client/instabrain-client.js +212 -10
- package/dist/services/application.service.d.ts +41 -3
- package/dist/services/application.service.js +41 -3
- package/dist/services/finalexpense.service.d.ts +129 -0
- package/dist/services/finalexpense.service.js +210 -0
- package/dist/services/gigdb.service.d.ts +25 -3
- package/dist/services/gigdb.service.js +25 -3
- package/dist/services/payment.service.d.ts +94 -0
- package/dist/services/payment.service.js +161 -0
- package/dist/services/pureterm.service.d.ts +96 -10
- package/dist/services/pureterm.service.js +100 -8
- package/dist/services/secure-sign.service.d.ts +19 -3
- package/dist/services/secure-sign.service.js +19 -3
- package/dist/types/enums.d.ts +77 -3
- package/dist/types/enums.js +89 -4
- package/dist/types/errors.js +27 -2
- package/dist/types/finalexpense.types.d.ts +459 -0
- package/dist/types/finalexpense.types.js +2 -0
- package/dist/types/gigdb.types.d.ts +32 -0
- package/dist/types/ibterm.types.d.ts +5 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +2 -0
- package/dist/types/payment.types.d.ts +52 -0
- package/dist/types/payment.types.js +3 -0
- package/dist/types/pureterm.types.d.ts +186 -31
- package/dist/types/secure-sign.types.d.ts +25 -3
- package/dist/utils/error-utils.d.ts +9 -1
- package/dist/utils/error-utils.js +18 -3
- package/dist/utils/http-client.js +11 -2
- package/package.json +1 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { HttpClient } from '../utils/http-client';
|
|
2
|
+
import { BaseService } from './base.service';
|
|
3
|
+
import { ThirdPartyFinalExpenseQuoteReq, ThirdPartyFinalExpenseQuoteRes, ThirdPartyFinalExpenseUpdateQuoteReq, ThirdPartyFinalExpenseStartApplicationReq, ThirdPartyFinalExpenseStartApplicationRes, ThirdPartyFinalExpensePingRes, PollUnderwritingStatusOptions } from '../types/finalexpense.types';
|
|
4
|
+
/**
|
|
5
|
+
* Final Expense (InstaFinalExpense) service.
|
|
6
|
+
*
|
|
7
|
+
* Simplified-issue whole life for ages 50–85, face $5k–$50k, distributed through
|
|
8
|
+
* Fidelity Life. Full flow (same as GIGDB / ADB):
|
|
9
|
+
* 1. getQuote() → quoteResponseId
|
|
10
|
+
* 2. startApplication() → opportunityId (or isDeclined=true)
|
|
11
|
+
* 3. InstaBrainClient.saveEftPayment() → true (shared endpoint)
|
|
12
|
+
* 4. SecureSign flow → (shared — use SecureSignService)
|
|
13
|
+
* 5. InstaBrainClient.finalSubmit() → applicationStatus: 'InProgress' (async!)
|
|
14
|
+
* 6. pollUnderwritingStatus() → terminal status + policyNumber
|
|
15
|
+
*
|
|
16
|
+
* Unlike ADB/GIGDB (synchronous underwriting that resolves in final-submit),
|
|
17
|
+
* Final Expense underwrites **asynchronously** — `finalSubmit()` returns
|
|
18
|
+
* `applicationStatus: 'InProgress'` with `policyNumber: null`, and the partner
|
|
19
|
+
* must poll {@link pingUnderwritingStatus} / {@link pollUnderwritingStatus}
|
|
20
|
+
* until a terminal status.
|
|
21
|
+
*/
|
|
22
|
+
export declare class FinalExpenseService extends BaseService {
|
|
23
|
+
constructor(httpClient: HttpClient);
|
|
24
|
+
/**
|
|
25
|
+
* Get a Final Expense insurance quote.
|
|
26
|
+
*
|
|
27
|
+
* `faceAmount`, `gender`, `stateCode`, `paymentFreq`, and `flagTobaccoUse` are
|
|
28
|
+
* required. Supply `age` OR `dateOfBirth` (resolved age 50–85). The response
|
|
29
|
+
* `selectedQuote.quoteResponseId` is the token for {@link startApplication}.
|
|
30
|
+
*
|
|
31
|
+
* @param request - The Final Expense quote request payload.
|
|
32
|
+
* @returns Promise with the quote response including `quoteResponseId`.
|
|
33
|
+
*/
|
|
34
|
+
getQuote(request: ThirdPartyFinalExpenseQuoteReq): Promise<ThirdPartyFinalExpenseQuoteRes>;
|
|
35
|
+
/**
|
|
36
|
+
* Start a Final Expense application from a prior Final Expense quote.
|
|
37
|
+
*
|
|
38
|
+
* Uses the dedicated `ThirdPartyFinalExpenseApplication` controller. Note:
|
|
39
|
+
* `isDeclined: true` is a valid success response (knockout), not an error —
|
|
40
|
+
* any health question set to `true`, or `isPayerAlsoOwnerAndInsured` /
|
|
41
|
+
* `isHoldingValidDriverLicense` set to `false`, returns HTTP 200 with
|
|
42
|
+
* `isDeclined: true`.
|
|
43
|
+
*
|
|
44
|
+
* @param request - The Final Expense start-application request payload.
|
|
45
|
+
* @returns Promise with `opportunityId`, `isDeclined`, and `isQuoteChanged`.
|
|
46
|
+
*/
|
|
47
|
+
startApplication(request: ThirdPartyFinalExpenseStartApplicationReq): Promise<ThirdPartyFinalExpenseStartApplicationRes>;
|
|
48
|
+
/**
|
|
49
|
+
* Get the existing quote for an in-flight Final Expense opportunity.
|
|
50
|
+
*
|
|
51
|
+
* Use to resume or review a previously created Final Expense quote by its
|
|
52
|
+
* opportunity ID without re-quoting. Returns the same shape as
|
|
53
|
+
* {@link getQuote}. Use `selectedQuote.quoteResponseId` as `quoteResponseId`
|
|
54
|
+
* on start application.
|
|
55
|
+
*
|
|
56
|
+
* @param opportunityId - UUID from a prior Final Expense quote/application flow.
|
|
57
|
+
* @returns Promise with the current quote response.
|
|
58
|
+
*/
|
|
59
|
+
getExistingQuote(opportunityId: string): Promise<ThirdPartyFinalExpenseQuoteRes>;
|
|
60
|
+
/**
|
|
61
|
+
* Update the face amount and/or payment frequency on an existing Final Expense
|
|
62
|
+
* quote. Only `faceAmount` and `paymentFreq` can change — nicotine, state, and
|
|
63
|
+
* age cannot. Blocked once a successful EFT payment has been recorded
|
|
64
|
+
* (returns `"Quote update is not allowed when payment is already made."`).
|
|
65
|
+
*
|
|
66
|
+
* @param request - The update-quote request (`opportunityId`, `faceAmount`, `paymentFreq`).
|
|
67
|
+
* @returns Promise with the recalculated quote response.
|
|
68
|
+
*/
|
|
69
|
+
updateQuote(request: ThirdPartyFinalExpenseUpdateQuoteReq): Promise<ThirdPartyFinalExpenseQuoteRes>;
|
|
70
|
+
/**
|
|
71
|
+
* Single poll of the asynchronous underwriting decision status (Final Expense
|
|
72
|
+
* only). Call after `finalSubmit()` returns `applicationStatus: 'InProgress'`.
|
|
73
|
+
*
|
|
74
|
+
* `'InProgress'` is the only non-terminal status. When `applicationStatus` is
|
|
75
|
+
* `'Approved'`, `policyNumber` is populated. Calling this for ADB/GIGDB
|
|
76
|
+
* returns `400 FinalSubmitStatusNotSupported`.
|
|
77
|
+
*
|
|
78
|
+
* @param opportunityId - The `opportunityId` from the start-application response.
|
|
79
|
+
* @returns Promise with the current `applicationStatus` and `policyNumber`.
|
|
80
|
+
*/
|
|
81
|
+
pingUnderwritingStatus(opportunityId: string): Promise<ThirdPartyFinalExpensePingRes>;
|
|
82
|
+
/**
|
|
83
|
+
* Poll the asynchronous underwriting decision until it is complete or the
|
|
84
|
+
* time budget is exhausted.
|
|
85
|
+
*
|
|
86
|
+
* Two-phase strategy (configurable via {@link PollUnderwritingStatusOptions}):
|
|
87
|
+
* poll every 10s for the first 7 minutes, then every 5 minutes up to 30
|
|
88
|
+
* minutes total. Stops as soon as the backend reports the decision is
|
|
89
|
+
* complete — it prefers the authoritative `shouldContinuePolling === false`
|
|
90
|
+
* signal, and falls back to `applicationStatus !== 'InProgress'` for older
|
|
91
|
+
* backends that predate that field. The backend returns a terminal
|
|
92
|
+
* `'TimedOut'` status at 30 minutes; the client-side `maxTotalDurationMs`
|
|
93
|
+
* budget is a safety net that resolves with the last response if that is
|
|
94
|
+
* somehow not reached.
|
|
95
|
+
*
|
|
96
|
+
* The status endpoint is rate-limited to 1 request / 2s per `opportunityId`;
|
|
97
|
+
* a `429` mid-poll is transparently retried after the documented
|
|
98
|
+
* `Retry-After: 2` (see {@link RATE_LIMIT_RETRY_MS}) rather than aborting the
|
|
99
|
+
* poll. The default 10s / 5min cadence stays well within the limit.
|
|
100
|
+
*
|
|
101
|
+
* @param opportunityId - The `opportunityId` from the start-application response.
|
|
102
|
+
* @param options - Optional polling cadence overrides.
|
|
103
|
+
* @returns Promise with the final ping response (terminal decision, or the last response on timeout).
|
|
104
|
+
*/
|
|
105
|
+
pollUnderwritingStatus(opportunityId: string, options?: PollUnderwritingStatusOptions): Promise<ThirdPartyFinalExpensePingRes>;
|
|
106
|
+
/**
|
|
107
|
+
* Decide whether to continue polling. Prefers the backend's authoritative
|
|
108
|
+
* `shouldContinuePolling` flag; falls back to the status check for backends
|
|
109
|
+
* that predate that field.
|
|
110
|
+
*/
|
|
111
|
+
private shouldKeepPolling;
|
|
112
|
+
/**
|
|
113
|
+
* Single `pingUnderwritingStatus` call that transparently retries a `429`
|
|
114
|
+
* (rate limit) after `RATE_LIMIT_RETRY_MS`, as long as another attempt still
|
|
115
|
+
* fits within the poll deadline.
|
|
116
|
+
*
|
|
117
|
+
* When the retry budget is exhausted on a `429`, resolves with `fallback` (the
|
|
118
|
+
* last known response) rather than aborting the managed poll — matching the
|
|
119
|
+
* documented "never aborts on rate limiting / resolves with the last
|
|
120
|
+
* response" contract. If no `fallback` is available (the very first ping, which
|
|
121
|
+
* has no prior response), the `429` propagates. Any non-`429` error always
|
|
122
|
+
* propagates.
|
|
123
|
+
*/
|
|
124
|
+
private pingWithRateLimitRetry;
|
|
125
|
+
/**
|
|
126
|
+
* Promise-based sleep. Extracted so tests can drive polling with fake timers.
|
|
127
|
+
*/
|
|
128
|
+
protected delay(ms: number): Promise<void>;
|
|
129
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FinalExpenseService = void 0;
|
|
4
|
+
const errors_1 = require("../types/errors");
|
|
5
|
+
const base_service_1 = require("./base.service");
|
|
6
|
+
/** Default two-phase polling cadence for {@link FinalExpenseService.pollUnderwritingStatus}. */
|
|
7
|
+
const DEFAULT_POLL_OPTIONS = {
|
|
8
|
+
fastPhaseDurationMs: 7 * 60 * 1000, // 7 min
|
|
9
|
+
fastIntervalMs: 10 * 1000, // 10s
|
|
10
|
+
slowIntervalMs: 5 * 60 * 1000, // 5 min
|
|
11
|
+
maxTotalDurationMs: 30 * 60 * 1000, // 30 min
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Wait applied before retrying a `pollUnderwritingStatus` request that was
|
|
15
|
+
* rate-limited (HTTP 429). Matches the endpoint's documented `Retry-After: 2`.
|
|
16
|
+
*/
|
|
17
|
+
const RATE_LIMIT_RETRY_MS = 2000;
|
|
18
|
+
/**
|
|
19
|
+
* Final Expense (InstaFinalExpense) service.
|
|
20
|
+
*
|
|
21
|
+
* Simplified-issue whole life for ages 50–85, face $5k–$50k, distributed through
|
|
22
|
+
* Fidelity Life. Full flow (same as GIGDB / ADB):
|
|
23
|
+
* 1. getQuote() → quoteResponseId
|
|
24
|
+
* 2. startApplication() → opportunityId (or isDeclined=true)
|
|
25
|
+
* 3. InstaBrainClient.saveEftPayment() → true (shared endpoint)
|
|
26
|
+
* 4. SecureSign flow → (shared — use SecureSignService)
|
|
27
|
+
* 5. InstaBrainClient.finalSubmit() → applicationStatus: 'InProgress' (async!)
|
|
28
|
+
* 6. pollUnderwritingStatus() → terminal status + policyNumber
|
|
29
|
+
*
|
|
30
|
+
* Unlike ADB/GIGDB (synchronous underwriting that resolves in final-submit),
|
|
31
|
+
* Final Expense underwrites **asynchronously** — `finalSubmit()` returns
|
|
32
|
+
* `applicationStatus: 'InProgress'` with `policyNumber: null`, and the partner
|
|
33
|
+
* must poll {@link pingUnderwritingStatus} / {@link pollUnderwritingStatus}
|
|
34
|
+
* until a terminal status.
|
|
35
|
+
*/
|
|
36
|
+
class FinalExpenseService extends base_service_1.BaseService {
|
|
37
|
+
constructor(httpClient) {
|
|
38
|
+
super(httpClient);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Get a Final Expense insurance quote.
|
|
42
|
+
*
|
|
43
|
+
* `faceAmount`, `gender`, `stateCode`, `paymentFreq`, and `flagTobaccoUse` are
|
|
44
|
+
* required. Supply `age` OR `dateOfBirth` (resolved age 50–85). The response
|
|
45
|
+
* `selectedQuote.quoteResponseId` is the token for {@link startApplication}.
|
|
46
|
+
*
|
|
47
|
+
* @param request - The Final Expense quote request payload.
|
|
48
|
+
* @returns Promise with the quote response including `quoteResponseId`.
|
|
49
|
+
*/
|
|
50
|
+
async getQuote(request) {
|
|
51
|
+
return this.post('get Final Expense quote', '/api/ThirdPartyIbFinalExpenseQuote/get', request);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Start a Final Expense application from a prior Final Expense quote.
|
|
55
|
+
*
|
|
56
|
+
* Uses the dedicated `ThirdPartyFinalExpenseApplication` controller. Note:
|
|
57
|
+
* `isDeclined: true` is a valid success response (knockout), not an error —
|
|
58
|
+
* any health question set to `true`, or `isPayerAlsoOwnerAndInsured` /
|
|
59
|
+
* `isHoldingValidDriverLicense` set to `false`, returns HTTP 200 with
|
|
60
|
+
* `isDeclined: true`.
|
|
61
|
+
*
|
|
62
|
+
* @param request - The Final Expense start-application request payload.
|
|
63
|
+
* @returns Promise with `opportunityId`, `isDeclined`, and `isQuoteChanged`.
|
|
64
|
+
*/
|
|
65
|
+
async startApplication(request) {
|
|
66
|
+
return this.post('start Final Expense application', '/api/ThirdPartyFinalExpenseApplication/start-application', request);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Get the existing quote for an in-flight Final Expense opportunity.
|
|
70
|
+
*
|
|
71
|
+
* Use to resume or review a previously created Final Expense quote by its
|
|
72
|
+
* opportunity ID without re-quoting. Returns the same shape as
|
|
73
|
+
* {@link getQuote}. Use `selectedQuote.quoteResponseId` as `quoteResponseId`
|
|
74
|
+
* on start application.
|
|
75
|
+
*
|
|
76
|
+
* @param opportunityId - UUID from a prior Final Expense quote/application flow.
|
|
77
|
+
* @returns Promise with the current quote response.
|
|
78
|
+
*/
|
|
79
|
+
async getExistingQuote(opportunityId) {
|
|
80
|
+
return this.get('get existing Final Expense quote', '/api/ThirdPartyIbFinalExpenseQuote/get-existing-quote', { params: { opportunityId } });
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Update the face amount and/or payment frequency on an existing Final Expense
|
|
84
|
+
* quote. Only `faceAmount` and `paymentFreq` can change — nicotine, state, and
|
|
85
|
+
* age cannot. Blocked once a successful EFT payment has been recorded
|
|
86
|
+
* (returns `"Quote update is not allowed when payment is already made."`).
|
|
87
|
+
*
|
|
88
|
+
* @param request - The update-quote request (`opportunityId`, `faceAmount`, `paymentFreq`).
|
|
89
|
+
* @returns Promise with the recalculated quote response.
|
|
90
|
+
*/
|
|
91
|
+
async updateQuote(request) {
|
|
92
|
+
return this.post('update Final Expense quote', '/api/ThirdPartyIbFinalExpenseQuote/update', request);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Single poll of the asynchronous underwriting decision status (Final Expense
|
|
96
|
+
* only). Call after `finalSubmit()` returns `applicationStatus: 'InProgress'`.
|
|
97
|
+
*
|
|
98
|
+
* `'InProgress'` is the only non-terminal status. When `applicationStatus` is
|
|
99
|
+
* `'Approved'`, `policyNumber` is populated. Calling this for ADB/GIGDB
|
|
100
|
+
* returns `400 FinalSubmitStatusNotSupported`.
|
|
101
|
+
*
|
|
102
|
+
* @param opportunityId - The `opportunityId` from the start-application response.
|
|
103
|
+
* @returns Promise with the current `applicationStatus` and `policyNumber`.
|
|
104
|
+
*/
|
|
105
|
+
async pingUnderwritingStatus(opportunityId) {
|
|
106
|
+
return this.get('ping Final Expense underwriting status', '/api/ThirdPartyApplication/final-submit-status', { params: { opportunityId } });
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Poll the asynchronous underwriting decision until it is complete or the
|
|
110
|
+
* time budget is exhausted.
|
|
111
|
+
*
|
|
112
|
+
* Two-phase strategy (configurable via {@link PollUnderwritingStatusOptions}):
|
|
113
|
+
* poll every 10s for the first 7 minutes, then every 5 minutes up to 30
|
|
114
|
+
* minutes total. Stops as soon as the backend reports the decision is
|
|
115
|
+
* complete — it prefers the authoritative `shouldContinuePolling === false`
|
|
116
|
+
* signal, and falls back to `applicationStatus !== 'InProgress'` for older
|
|
117
|
+
* backends that predate that field. The backend returns a terminal
|
|
118
|
+
* `'TimedOut'` status at 30 minutes; the client-side `maxTotalDurationMs`
|
|
119
|
+
* budget is a safety net that resolves with the last response if that is
|
|
120
|
+
* somehow not reached.
|
|
121
|
+
*
|
|
122
|
+
* The status endpoint is rate-limited to 1 request / 2s per `opportunityId`;
|
|
123
|
+
* a `429` mid-poll is transparently retried after the documented
|
|
124
|
+
* `Retry-After: 2` (see {@link RATE_LIMIT_RETRY_MS}) rather than aborting the
|
|
125
|
+
* poll. The default 10s / 5min cadence stays well within the limit.
|
|
126
|
+
*
|
|
127
|
+
* @param opportunityId - The `opportunityId` from the start-application response.
|
|
128
|
+
* @param options - Optional polling cadence overrides.
|
|
129
|
+
* @returns Promise with the final ping response (terminal decision, or the last response on timeout).
|
|
130
|
+
*/
|
|
131
|
+
async pollUnderwritingStatus(opportunityId, options = {}) {
|
|
132
|
+
const { fastPhaseDurationMs, fastIntervalMs, slowIntervalMs, maxTotalDurationMs } = {
|
|
133
|
+
...DEFAULT_POLL_OPTIONS,
|
|
134
|
+
...options,
|
|
135
|
+
};
|
|
136
|
+
const onPoll = options.onPoll;
|
|
137
|
+
const start = Date.now();
|
|
138
|
+
const deadline = start + maxTotalDurationMs;
|
|
139
|
+
let attempt = 1;
|
|
140
|
+
let last = await this.pingWithRateLimitRetry(opportunityId, deadline);
|
|
141
|
+
onPoll === null || onPoll === void 0 ? void 0 : onPoll(last, attempt, Date.now() - start);
|
|
142
|
+
while (this.shouldKeepPolling(last)) {
|
|
143
|
+
const elapsed = Date.now() - start;
|
|
144
|
+
if (elapsed >= maxTotalDurationMs) {
|
|
145
|
+
// Time budget exhausted — return the last response.
|
|
146
|
+
return last;
|
|
147
|
+
}
|
|
148
|
+
const interval = elapsed < fastPhaseDurationMs ? fastIntervalMs : slowIntervalMs;
|
|
149
|
+
// Never sleep past the remaining budget.
|
|
150
|
+
const wait = Math.min(interval, maxTotalDurationMs - elapsed);
|
|
151
|
+
await this.delay(wait);
|
|
152
|
+
attempt += 1;
|
|
153
|
+
last = await this.pingWithRateLimitRetry(opportunityId, deadline, last);
|
|
154
|
+
onPoll === null || onPoll === void 0 ? void 0 : onPoll(last, attempt, Date.now() - start);
|
|
155
|
+
}
|
|
156
|
+
return last;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Decide whether to continue polling. Prefers the backend's authoritative
|
|
160
|
+
* `shouldContinuePolling` flag; falls back to the status check for backends
|
|
161
|
+
* that predate that field.
|
|
162
|
+
*/
|
|
163
|
+
shouldKeepPolling(res) {
|
|
164
|
+
if (typeof res.shouldContinuePolling === 'boolean') {
|
|
165
|
+
return res.shouldContinuePolling;
|
|
166
|
+
}
|
|
167
|
+
return res.applicationStatus === 'InProgress';
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Single `pingUnderwritingStatus` call that transparently retries a `429`
|
|
171
|
+
* (rate limit) after `RATE_LIMIT_RETRY_MS`, as long as another attempt still
|
|
172
|
+
* fits within the poll deadline.
|
|
173
|
+
*
|
|
174
|
+
* When the retry budget is exhausted on a `429`, resolves with `fallback` (the
|
|
175
|
+
* last known response) rather than aborting the managed poll — matching the
|
|
176
|
+
* documented "never aborts on rate limiting / resolves with the last
|
|
177
|
+
* response" contract. If no `fallback` is available (the very first ping, which
|
|
178
|
+
* has no prior response), the `429` propagates. Any non-`429` error always
|
|
179
|
+
* propagates.
|
|
180
|
+
*/
|
|
181
|
+
async pingWithRateLimitRetry(opportunityId, deadline, fallback) {
|
|
182
|
+
for (;;) {
|
|
183
|
+
try {
|
|
184
|
+
return await this.pingUnderwritingStatus(opportunityId);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
const isRateLimited = error instanceof errors_1.InstaBrainError && error.statusCode === 429;
|
|
188
|
+
if (isRateLimited) {
|
|
189
|
+
if (Date.now() + RATE_LIMIT_RETRY_MS <= deadline) {
|
|
190
|
+
await this.delay(RATE_LIMIT_RETRY_MS);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
// Budget exhausted while rate-limited — resolve with the last known
|
|
194
|
+
// response instead of aborting the poll (documented contract).
|
|
195
|
+
if (fallback !== undefined) {
|
|
196
|
+
return fallback;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Promise-based sleep. Extracted so tests can drive polling with fake timers.
|
|
205
|
+
*/
|
|
206
|
+
delay(ms) {
|
|
207
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
exports.FinalExpenseService = FinalExpenseService;
|
|
@@ -21,9 +21,31 @@ export declare class GigdbService extends BaseService {
|
|
|
21
21
|
*/
|
|
22
22
|
startApplication(request: ThirdPartyGigdbAppReq): Promise<ThirdPartyStartAppResp>;
|
|
23
23
|
/**
|
|
24
|
-
* Save EFT payment details for
|
|
25
|
-
*
|
|
26
|
-
*
|
|
24
|
+
* Save bank-account (EFT) payment details for an in-progress application.
|
|
25
|
+
*
|
|
26
|
+
* Shared endpoint — used by GIGDB, ADB, and Final Expense. Call after Start
|
|
27
|
+
* Application and before `prepareDocsAndGetDeliveryChannels()`.
|
|
28
|
+
*
|
|
29
|
+
* Validation: `accountHolderName` is required, max 100 characters, and may
|
|
30
|
+
* contain only letters, spaces, hyphens, and apostrophes; `routingNumber` is
|
|
31
|
+
* exactly 9 digits; `accountNumber` is 4–17 digits. Failures return
|
|
32
|
+
* `InvalidRequestFormat` with the field under `value.fields`.
|
|
33
|
+
*
|
|
34
|
+
* Business rules:
|
|
35
|
+
* - **EFT and credit card are mutually exclusive** per `opportunityId`.
|
|
36
|
+
* A successful payment that already exists (a prior EFT save, or a card
|
|
37
|
+
* that has already been charged) returns `PaymentAlreadyMade`. Afterwards,
|
|
38
|
+
* `getCcPaymentIframeUrl()` returns `EftPaymentAlreadyCompleted`.
|
|
39
|
+
* - No application-readiness gate here, unlike `getCcPaymentIframeUrl()` —
|
|
40
|
+
* only that the opportunity exists and payment has not completed.
|
|
41
|
+
* - Once saved, quote updates for the same opportunity are blocked.
|
|
42
|
+
* - A successful save **satisfies the payment prerequisite for
|
|
43
|
+
* `finalSubmit()`** — no charge runs again at final submit, and neither
|
|
44
|
+
* `paymentNotMade` nor `LatestPaymentNotSuccessful` will be returned for
|
|
45
|
+
* payment reasons.
|
|
46
|
+
*
|
|
47
|
+
* @param request - The EFT payment request with opportunityId and bank account details
|
|
48
|
+
* @returns Promise resolving to true on success
|
|
27
49
|
*/
|
|
28
50
|
saveEftPayment(request: ThirdPartyEftPaymentReq): Promise<boolean>;
|
|
29
51
|
/**
|
|
@@ -28,9 +28,31 @@ class GigdbService extends base_service_1.BaseService {
|
|
|
28
28
|
return this.post('start GIGDB application', '/api/ThirdPartyGigdbApplication/start-application', request);
|
|
29
29
|
}
|
|
30
30
|
/**
|
|
31
|
-
* Save EFT payment details for
|
|
32
|
-
*
|
|
33
|
-
*
|
|
31
|
+
* Save bank-account (EFT) payment details for an in-progress application.
|
|
32
|
+
*
|
|
33
|
+
* Shared endpoint — used by GIGDB, ADB, and Final Expense. Call after Start
|
|
34
|
+
* Application and before `prepareDocsAndGetDeliveryChannels()`.
|
|
35
|
+
*
|
|
36
|
+
* Validation: `accountHolderName` is required, max 100 characters, and may
|
|
37
|
+
* contain only letters, spaces, hyphens, and apostrophes; `routingNumber` is
|
|
38
|
+
* exactly 9 digits; `accountNumber` is 4–17 digits. Failures return
|
|
39
|
+
* `InvalidRequestFormat` with the field under `value.fields`.
|
|
40
|
+
*
|
|
41
|
+
* Business rules:
|
|
42
|
+
* - **EFT and credit card are mutually exclusive** per `opportunityId`.
|
|
43
|
+
* A successful payment that already exists (a prior EFT save, or a card
|
|
44
|
+
* that has already been charged) returns `PaymentAlreadyMade`. Afterwards,
|
|
45
|
+
* `getCcPaymentIframeUrl()` returns `EftPaymentAlreadyCompleted`.
|
|
46
|
+
* - No application-readiness gate here, unlike `getCcPaymentIframeUrl()` —
|
|
47
|
+
* only that the opportunity exists and payment has not completed.
|
|
48
|
+
* - Once saved, quote updates for the same opportunity are blocked.
|
|
49
|
+
* - A successful save **satisfies the payment prerequisite for
|
|
50
|
+
* `finalSubmit()`** — no charge runs again at final submit, and neither
|
|
51
|
+
* `paymentNotMade` nor `LatestPaymentNotSuccessful` will be returned for
|
|
52
|
+
* payment reasons.
|
|
53
|
+
*
|
|
54
|
+
* @param request - The EFT payment request with opportunityId and bank account details
|
|
55
|
+
* @returns Promise resolving to true on success
|
|
34
56
|
*/
|
|
35
57
|
async saveEftPayment(request) {
|
|
36
58
|
const result = await this.post('save EFT payment', '/api/ThirdPartyPayment/save-eft-payment', request, undefined, true // allowNullValue — API returns BaseResponse<boolean>
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { HttpClient } from '../utils/http-client';
|
|
2
|
+
import { BaseService } from './base.service';
|
|
3
|
+
import { ThirdPartyCcPaymentStatusRes, PollCcPaymentStatusOptions } from '../types/payment.types';
|
|
4
|
+
/**
|
|
5
|
+
* Credit card payment service (shared — **ADB, GIGDB, and Final Expense only**).
|
|
6
|
+
*
|
|
7
|
+
* Card capture happens in a TrustCommerce hosted iframe. The SDK never touches
|
|
8
|
+
* card data — it hands you a URL to render, then reports when capture completes.
|
|
9
|
+
*
|
|
10
|
+
* Flow (slots between Start Application and Prepare Signing Docs):
|
|
11
|
+
* 1. getIframeUrl(opportunityId) → URL to render; **persist it**
|
|
12
|
+
* 2. applicant submits the hosted form
|
|
13
|
+
* 3. pollCcPaymentStatus(...) → until `approved`
|
|
14
|
+
* 4. Secure Sign → InstaBrainClient.finalSubmit()
|
|
15
|
+
*
|
|
16
|
+
* Key rules:
|
|
17
|
+
* - **Persist and reuse the URL.** A new link is only issued once the latest
|
|
18
|
+
* attempt has `failed`. Calling {@link getIframeUrl} again while capture is
|
|
19
|
+
* `pending` **or** already `approved` returns `TcIframeLinkAlreadyGenerated`.
|
|
20
|
+
* - **EFT and credit card are mutually exclusive** per opportunity. After a
|
|
21
|
+
* successful `saveEftPayment()`, this endpoint returns `EftPaymentAlreadyCompleted`.
|
|
22
|
+
* - `'approved'` means the card was **captured**, not charged. ADB/GIGDB charge
|
|
23
|
+
* at `finalSubmit()`; for Final Expense the carrier collects after underwriting.
|
|
24
|
+
* - **Not supported for IB Term / Pure Term** — returns
|
|
25
|
+
* `CcPaymentIframeNotSupportedForProduct`. Those products use the shared EFT
|
|
26
|
+
* endpoint or hand off via their returned links.
|
|
27
|
+
*/
|
|
28
|
+
export declare class PaymentService extends BaseService {
|
|
29
|
+
constructor(httpClient: HttpClient);
|
|
30
|
+
/**
|
|
31
|
+
* Get the TrustCommerce hosted iframe URL for card capture.
|
|
32
|
+
*
|
|
33
|
+
* Call after Start Application has completed successfully and before Prepare
|
|
34
|
+
* Signing Docs. **Persist the returned URL keyed by `opportunityId`** and
|
|
35
|
+
* reuse it while {@link pollCcPaymentStatus} reports `'pending'` — requesting
|
|
36
|
+
* a second link before the current attempt fails returns
|
|
37
|
+
* `TcIframeLinkAlreadyGenerated`.
|
|
38
|
+
*
|
|
39
|
+
* Errors (all HTTP 400, each a distinct top-level code):
|
|
40
|
+
* - `InvalidRequestFormat` — `opportunityId` missing or unknown
|
|
41
|
+
* - `CcPaymentIframeNotSupportedForProduct` — product is not ADB / GIGDB / Final Expense
|
|
42
|
+
* - `ApplicationNotReady` — Start Application has not completed successfully
|
|
43
|
+
* - `EftPaymentAlreadyCompleted` — a successful EFT payment already exists
|
|
44
|
+
* - `TcIframeLinkAlreadyGenerated` — a link exists and the latest attempt has not failed
|
|
45
|
+
*
|
|
46
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
47
|
+
* @returns Promise resolving to the fully-qualified iframe URL.
|
|
48
|
+
*/
|
|
49
|
+
getIframeUrl(opportunityId: string): Promise<string>;
|
|
50
|
+
/**
|
|
51
|
+
* Single check of credit card capture status.
|
|
52
|
+
*
|
|
53
|
+
* Rate-limited to 1 request per 10 seconds per `opportunityId`; exceeding it
|
|
54
|
+
* throws an `InstaBrainError` with `statusCode: 429`. This method does **not**
|
|
55
|
+
* auto-retry — use {@link pollCcPaymentStatus} for a managed loop.
|
|
56
|
+
*
|
|
57
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
58
|
+
* @returns Promise with the current `status` and `shouldContinuePolling`.
|
|
59
|
+
*/
|
|
60
|
+
getCcPaymentStatus(opportunityId: string): Promise<ThirdPartyCcPaymentStatusRes>;
|
|
61
|
+
/**
|
|
62
|
+
* Poll card-capture status until it resolves or the time budget is exhausted.
|
|
63
|
+
*
|
|
64
|
+
* Polls every 10s (configurable) and stops as soon as `shouldContinuePolling`
|
|
65
|
+
* is `false` — i.e. `'approved'` or `'failed'`. A `429` is transparently
|
|
66
|
+
* retried after the documented `Retry-After: 10` rather than aborting the poll.
|
|
67
|
+
*
|
|
68
|
+
* This method **never requests a new iframe URL**. On `'failed'` it returns and
|
|
69
|
+
* the caller needs to call {@link getIframeUrl} again for a fresh capture.
|
|
70
|
+
*
|
|
71
|
+
* On budget expiry it resolves with the last response (still `'pending'`)
|
|
72
|
+
* rather than throwing — inspect `status` to detect it.
|
|
73
|
+
*
|
|
74
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
75
|
+
* @param options - Optional cadence overrides.
|
|
76
|
+
* @returns Promise with the terminal response, or the last `'pending'` one on timeout.
|
|
77
|
+
*/
|
|
78
|
+
pollCcPaymentStatus(opportunityId: string, options?: PollCcPaymentStatusOptions): Promise<ThirdPartyCcPaymentStatusRes>;
|
|
79
|
+
/**
|
|
80
|
+
* Single status call that transparently retries a `429` (rate limit) after
|
|
81
|
+
* {@link RATE_LIMIT_RETRY_MS}, as long as another attempt fits within the poll
|
|
82
|
+
* deadline.
|
|
83
|
+
*
|
|
84
|
+
* When the retry budget is exhausted on a `429`, resolves with `fallback` (the
|
|
85
|
+
* last known response) rather than aborting the managed poll. If no `fallback`
|
|
86
|
+
* exists (the very first call), the `429` propagates. Any non-`429` error
|
|
87
|
+
* always propagates.
|
|
88
|
+
*/
|
|
89
|
+
private getStatusWithRateLimitRetry;
|
|
90
|
+
/**
|
|
91
|
+
* Promise-based sleep. Extracted so tests can drive polling with fake timers.
|
|
92
|
+
*/
|
|
93
|
+
protected delay(ms: number): Promise<void>;
|
|
94
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PaymentService = void 0;
|
|
4
|
+
const errors_1 = require("../types/errors");
|
|
5
|
+
const base_service_1 = require("./base.service");
|
|
6
|
+
/** Default polling cadence for {@link PaymentService.pollCcPaymentStatus}. */
|
|
7
|
+
const DEFAULT_POLL_OPTIONS = {
|
|
8
|
+
intervalMs: 10 * 1000, // 10s — matches the documented rate limit
|
|
9
|
+
maxTotalDurationMs: 30 * 60 * 1000, // 30 min client-side safety net — matches the Final Expense poller
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Wait applied before retrying a rate-limited (HTTP 429) status request.
|
|
13
|
+
* The endpoint documents `Retry-After: 10` — note this is a **different** value
|
|
14
|
+
* from the Final Expense underwriting poller's 2s.
|
|
15
|
+
*/
|
|
16
|
+
const RATE_LIMIT_RETRY_MS = 10 * 1000;
|
|
17
|
+
/**
|
|
18
|
+
* Credit card payment service (shared — **ADB, GIGDB, and Final Expense only**).
|
|
19
|
+
*
|
|
20
|
+
* Card capture happens in a TrustCommerce hosted iframe. The SDK never touches
|
|
21
|
+
* card data — it hands you a URL to render, then reports when capture completes.
|
|
22
|
+
*
|
|
23
|
+
* Flow (slots between Start Application and Prepare Signing Docs):
|
|
24
|
+
* 1. getIframeUrl(opportunityId) → URL to render; **persist it**
|
|
25
|
+
* 2. applicant submits the hosted form
|
|
26
|
+
* 3. pollCcPaymentStatus(...) → until `approved`
|
|
27
|
+
* 4. Secure Sign → InstaBrainClient.finalSubmit()
|
|
28
|
+
*
|
|
29
|
+
* Key rules:
|
|
30
|
+
* - **Persist and reuse the URL.** A new link is only issued once the latest
|
|
31
|
+
* attempt has `failed`. Calling {@link getIframeUrl} again while capture is
|
|
32
|
+
* `pending` **or** already `approved` returns `TcIframeLinkAlreadyGenerated`.
|
|
33
|
+
* - **EFT and credit card are mutually exclusive** per opportunity. After a
|
|
34
|
+
* successful `saveEftPayment()`, this endpoint returns `EftPaymentAlreadyCompleted`.
|
|
35
|
+
* - `'approved'` means the card was **captured**, not charged. ADB/GIGDB charge
|
|
36
|
+
* at `finalSubmit()`; for Final Expense the carrier collects after underwriting.
|
|
37
|
+
* - **Not supported for IB Term / Pure Term** — returns
|
|
38
|
+
* `CcPaymentIframeNotSupportedForProduct`. Those products use the shared EFT
|
|
39
|
+
* endpoint or hand off via their returned links.
|
|
40
|
+
*/
|
|
41
|
+
class PaymentService extends base_service_1.BaseService {
|
|
42
|
+
constructor(httpClient) {
|
|
43
|
+
super(httpClient);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Get the TrustCommerce hosted iframe URL for card capture.
|
|
47
|
+
*
|
|
48
|
+
* Call after Start Application has completed successfully and before Prepare
|
|
49
|
+
* Signing Docs. **Persist the returned URL keyed by `opportunityId`** and
|
|
50
|
+
* reuse it while {@link pollCcPaymentStatus} reports `'pending'` — requesting
|
|
51
|
+
* a second link before the current attempt fails returns
|
|
52
|
+
* `TcIframeLinkAlreadyGenerated`.
|
|
53
|
+
*
|
|
54
|
+
* Errors (all HTTP 400, each a distinct top-level code):
|
|
55
|
+
* - `InvalidRequestFormat` — `opportunityId` missing or unknown
|
|
56
|
+
* - `CcPaymentIframeNotSupportedForProduct` — product is not ADB / GIGDB / Final Expense
|
|
57
|
+
* - `ApplicationNotReady` — Start Application has not completed successfully
|
|
58
|
+
* - `EftPaymentAlreadyCompleted` — a successful EFT payment already exists
|
|
59
|
+
* - `TcIframeLinkAlreadyGenerated` — a link exists and the latest attempt has not failed
|
|
60
|
+
*
|
|
61
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
62
|
+
* @returns Promise resolving to the fully-qualified iframe URL.
|
|
63
|
+
*/
|
|
64
|
+
async getIframeUrl(opportunityId) {
|
|
65
|
+
return this.get('get credit card iframe URL', '/api/ThirdPartyPayment/get-iframe-url', {
|
|
66
|
+
params: { opportunityId },
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Single check of credit card capture status.
|
|
71
|
+
*
|
|
72
|
+
* Rate-limited to 1 request per 10 seconds per `opportunityId`; exceeding it
|
|
73
|
+
* throws an `InstaBrainError` with `statusCode: 429`. This method does **not**
|
|
74
|
+
* auto-retry — use {@link pollCcPaymentStatus} for a managed loop.
|
|
75
|
+
*
|
|
76
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
77
|
+
* @returns Promise with the current `status` and `shouldContinuePolling`.
|
|
78
|
+
*/
|
|
79
|
+
async getCcPaymentStatus(opportunityId) {
|
|
80
|
+
return this.get('get credit card payment status', '/api/ThirdPartyPayment/cc-payment-status', {
|
|
81
|
+
params: { opportunityId },
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Poll card-capture status until it resolves or the time budget is exhausted.
|
|
86
|
+
*
|
|
87
|
+
* Polls every 10s (configurable) and stops as soon as `shouldContinuePolling`
|
|
88
|
+
* is `false` — i.e. `'approved'` or `'failed'`. A `429` is transparently
|
|
89
|
+
* retried after the documented `Retry-After: 10` rather than aborting the poll.
|
|
90
|
+
*
|
|
91
|
+
* This method **never requests a new iframe URL**. On `'failed'` it returns and
|
|
92
|
+
* the caller needs to call {@link getIframeUrl} again for a fresh capture.
|
|
93
|
+
*
|
|
94
|
+
* On budget expiry it resolves with the last response (still `'pending'`)
|
|
95
|
+
* rather than throwing — inspect `status` to detect it.
|
|
96
|
+
*
|
|
97
|
+
* @param opportunityId - The `opportunityId` from the Start Application response.
|
|
98
|
+
* @param options - Optional cadence overrides.
|
|
99
|
+
* @returns Promise with the terminal response, or the last `'pending'` one on timeout.
|
|
100
|
+
*/
|
|
101
|
+
async pollCcPaymentStatus(opportunityId, options = {}) {
|
|
102
|
+
const { intervalMs, maxTotalDurationMs } = { ...DEFAULT_POLL_OPTIONS, ...options };
|
|
103
|
+
const onPoll = options.onPoll;
|
|
104
|
+
const start = Date.now();
|
|
105
|
+
const deadline = start + maxTotalDurationMs;
|
|
106
|
+
let attempt = 1;
|
|
107
|
+
let last = await this.getStatusWithRateLimitRetry(opportunityId, deadline);
|
|
108
|
+
onPoll === null || onPoll === void 0 ? void 0 : onPoll(last, attempt, Date.now() - start);
|
|
109
|
+
while (last.shouldContinuePolling) {
|
|
110
|
+
const elapsed = Date.now() - start;
|
|
111
|
+
if (elapsed >= maxTotalDurationMs) {
|
|
112
|
+
// Budget exhausted — return the last response rather than throwing.
|
|
113
|
+
return last;
|
|
114
|
+
}
|
|
115
|
+
// Never sleep past the remaining budget.
|
|
116
|
+
const wait = Math.min(intervalMs, maxTotalDurationMs - elapsed);
|
|
117
|
+
await this.delay(wait);
|
|
118
|
+
attempt += 1;
|
|
119
|
+
last = await this.getStatusWithRateLimitRetry(opportunityId, deadline, last);
|
|
120
|
+
onPoll === null || onPoll === void 0 ? void 0 : onPoll(last, attempt, Date.now() - start);
|
|
121
|
+
}
|
|
122
|
+
return last;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Single status call that transparently retries a `429` (rate limit) after
|
|
126
|
+
* {@link RATE_LIMIT_RETRY_MS}, as long as another attempt fits within the poll
|
|
127
|
+
* deadline.
|
|
128
|
+
*
|
|
129
|
+
* When the retry budget is exhausted on a `429`, resolves with `fallback` (the
|
|
130
|
+
* last known response) rather than aborting the managed poll. If no `fallback`
|
|
131
|
+
* exists (the very first call), the `429` propagates. Any non-`429` error
|
|
132
|
+
* always propagates.
|
|
133
|
+
*/
|
|
134
|
+
async getStatusWithRateLimitRetry(opportunityId, deadline, fallback) {
|
|
135
|
+
for (;;) {
|
|
136
|
+
try {
|
|
137
|
+
return await this.getCcPaymentStatus(opportunityId);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const isRateLimited = error instanceof errors_1.InstaBrainError && error.statusCode === 429;
|
|
141
|
+
if (isRateLimited) {
|
|
142
|
+
if (Date.now() + RATE_LIMIT_RETRY_MS <= deadline) {
|
|
143
|
+
await this.delay(RATE_LIMIT_RETRY_MS);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (fallback !== undefined) {
|
|
147
|
+
return fallback;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Promise-based sleep. Extracted so tests can drive polling with fake timers.
|
|
156
|
+
*/
|
|
157
|
+
delay(ms) {
|
|
158
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
exports.PaymentService = PaymentService;
|