@instabrain-sdks/api-client 2.3.3 → 2.4.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.
@@ -6,8 +6,9 @@ import { GigdbService } from '../services/gigdb.service';
6
6
  import { AdbService } from '../services/adb.service';
7
7
  import { IBTermService } from '../services/ibterm.service';
8
8
  import { PureTermService } from '../services/pureterm.service';
9
+ import { FinalExpenseService } from '../services/finalexpense.service';
9
10
  import { SecureSignService } from '../services/secure-sign.service';
10
- import { InstaBrainConfig, Environment, ThirdPartyQuoteReq, ThirdPartyQuoteResp, ThirdPartyStartApplicationReq, ThirdPartyStartAppResp, AgentPortalReq, ThirdPartyProspectsResp, ThirdPartySalesReportRes, ThirdPartyApplicationReportRes, ThirdPartyGigdbQuoteRequest, ThirdPartyGigdbUpdateQuoteReq, ThirdPartyGigdbAppReq, ThirdPartyEftPaymentReq, ThirdPartyAdbQuoteRequest, ThirdPartyAdbUpdateQuoteReq, ThirdPartyAdbAppReq, ThirdPartyAdbStartAppResp, AdbRiderDetailsResp, IBTermRiderDetailsResp, IBTermStartApplicationReq, ThirdPartyPureTermQuoteReq, ThirdPartySendPinReq, ThirdPartyResendPinReq, ThirdPartyVerifyPinReq, ThirdPartyPrepareDocsResp, ThirdPartySendPinResp, ThirdPartyResendPinResp, ThirdPartyVerifyPinResp, ThirdPartyFinalSubmitResp } from '../types';
11
+ import { InstaBrainConfig, Environment, ThirdPartyQuoteReq, ThirdPartyQuoteResp, ThirdPartyStartApplicationReq, ThirdPartyStartAppResp, AgentPortalReq, ThirdPartyProspectsResp, ThirdPartySalesReportRes, ThirdPartyApplicationReportRes, ThirdPartyGigdbQuoteRequest, ThirdPartyGigdbUpdateQuoteReq, ThirdPartyGigdbAppReq, ThirdPartyEftPaymentReq, ThirdPartyAdbQuoteRequest, ThirdPartyAdbUpdateQuoteReq, ThirdPartyAdbAppReq, ThirdPartyAdbStartAppResp, AdbRiderDetailsResp, IBTermRiderDetailsResp, IBTermStartApplicationReq, ThirdPartyPureTermQuoteReq, ThirdPartyFinalExpenseQuoteReq, ThirdPartyFinalExpenseQuoteRes, ThirdPartyFinalExpenseUpdateQuoteReq, ThirdPartyFinalExpenseStartApplicationReq, ThirdPartyFinalExpenseStartApplicationRes, ThirdPartyFinalExpensePingRes, PollUnderwritingStatusOptions, ThirdPartySendPinReq, ThirdPartyResendPinReq, ThirdPartyVerifyPinReq, ThirdPartyPrepareDocsResp, ThirdPartySendPinResp, ThirdPartyResendPinResp, ThirdPartyVerifyPinResp, ThirdPartyFinalSubmitResp } from '../types';
11
12
  /**
12
13
  * Main InstaBrain SDK client
13
14
  */
@@ -21,6 +22,7 @@ export declare class InstaBrainClient {
21
22
  readonly adb: AdbService;
22
23
  readonly ibterm: IBTermService;
23
24
  readonly pureTerm: PureTermService;
25
+ readonly finalExpense: FinalExpenseService;
24
26
  readonly secureSign: SecureSignService;
25
27
  constructor(config?: InstaBrainConfig);
26
28
  /**
@@ -79,8 +81,9 @@ export declare class InstaBrainClient {
79
81
  */
80
82
  startGigdbApplication(request: ThirdPartyGigdbAppReq): Promise<ThirdPartyStartAppResp>;
81
83
  /**
82
- * Save EFT payment details for a GIGDB or ADB application
83
- * Must be called after startGigdbApplication / startAdbApplication and before the SecureSign flow.
84
+ * Save EFT payment details for a GIGDB, ADB, or Final Expense application.
85
+ * Must be called after startGigdbApplication / startAdbApplication /
86
+ * startFinalExpenseApplication and before the SecureSign flow.
84
87
  * @param request - The EFT payment request with opportunityId and bank account details
85
88
  * @returns Promise resolving to true on success
86
89
  */
@@ -197,6 +200,64 @@ export declare class InstaBrainClient {
197
200
  * @returns Promise with the quote response containing quoteResponseId
198
201
  */
199
202
  getPureTermQuote(request: ThirdPartyPureTermQuoteReq): Promise<ThirdPartyQuoteResp>;
203
+ /**
204
+ * Get a Final Expense insurance quote (simplified-issue whole life, ages 50–85).
205
+ *
206
+ * `faceAmount`, `gender`, `stateCode`, `paymentFreq`, and `flagTobaccoUse` are
207
+ * required. Supply `age` OR `dateOfBirth` (resolved age 50–85). The response
208
+ * `selectedQuote.quoteResponseId` is the token for `startFinalExpenseApplication()`.
209
+ *
210
+ * @param request - The Final Expense quote request parameters
211
+ * @returns Promise with the quote response containing quoteResponseId
212
+ */
213
+ getFinalExpenseQuote(request: ThirdPartyFinalExpenseQuoteReq): Promise<ThirdPartyFinalExpenseQuoteRes>;
214
+ /**
215
+ * Start a Final Expense application from a prior Final Expense quote.
216
+ *
217
+ * `isDeclined: true` is a valid success response (knockout), not an error.
218
+ * After a non-declined start, continue with `saveEftPayment()`, the Secure
219
+ * Sign flow, then `finalSubmit()` — and poll `pollFinalExpenseUnderwritingStatus()`
220
+ * because Final Expense underwrites asynchronously.
221
+ *
222
+ * @param request - The Final Expense start-application request payload
223
+ * @returns Promise with `opportunityId`, `isDeclined`, and `isQuoteChanged`
224
+ */
225
+ startFinalExpenseApplication(request: ThirdPartyFinalExpenseStartApplicationReq): Promise<ThirdPartyFinalExpenseStartApplicationRes>;
226
+ /**
227
+ * Get the existing Final Expense quote for an in-flight opportunity by ID.
228
+ * Use `selectedQuote.quoteResponseId` as `quoteResponseId` on start application.
229
+ *
230
+ * @param opportunityId - UUID from a prior Final Expense quote/application flow
231
+ * @returns Promise with the current quote response
232
+ */
233
+ getFinalExpenseExistingQuote(opportunityId: string): Promise<ThirdPartyFinalExpenseQuoteRes>;
234
+ /**
235
+ * Update the face amount and/or payment frequency on an existing Final Expense
236
+ * quote. Blocked once EFT payment is recorded for the opportunity.
237
+ *
238
+ * @param request - The update-quote request (`opportunityId`, `faceAmount`, `paymentFreq`)
239
+ * @returns Promise with the recalculated quote response
240
+ */
241
+ updateFinalExpenseQuote(request: ThirdPartyFinalExpenseUpdateQuoteReq): Promise<ThirdPartyFinalExpenseQuoteRes>;
242
+ /**
243
+ * Single poll of the Final Expense asynchronous underwriting status. Call after
244
+ * `finalSubmit()` returns `applicationStatus: 'InProgress'`. Final Expense only —
245
+ * ADB/GIGDB return `400 FinalSubmitStatusNotSupported`.
246
+ *
247
+ * @param opportunityId - The `opportunityId` from the start-application response
248
+ * @returns Promise with the current `applicationStatus` and `policyNumber`
249
+ */
250
+ pingFinalExpenseUnderwritingStatus(opportunityId: string): Promise<ThirdPartyFinalExpensePingRes>;
251
+ /**
252
+ * Poll the Final Expense asynchronous underwriting decision until a terminal
253
+ * status is reached or the time budget is exhausted (two-phase: every 10s for
254
+ * 7 min, then every 5 min up to 30 min total; all configurable).
255
+ *
256
+ * @param opportunityId - The `opportunityId` from the start-application response
257
+ * @param options - Optional polling cadence overrides
258
+ * @returns Promise with the final ping response (terminal status, or last `'InProgress'` on timeout)
259
+ */
260
+ pollFinalExpenseUnderwritingStatus(opportunityId: string, options?: PollUnderwritingStatusOptions): Promise<ThirdPartyFinalExpensePingRes>;
200
261
  /**
201
262
  * Prepare the signing package and check available delivery channels
202
263
  * Always call this first in the signing flow. If isSignCompleted is true, skip to finalSubmit().
@@ -10,6 +10,7 @@ const gigdb_service_1 = require("../services/gigdb.service");
10
10
  const adb_service_1 = require("../services/adb.service");
11
11
  const ibterm_service_1 = require("../services/ibterm.service");
12
12
  const pureterm_service_1 = require("../services/pureterm.service");
13
+ const finalexpense_service_1 = require("../services/finalexpense.service");
13
14
  const secure_sign_service_1 = require("../services/secure-sign.service");
14
15
  /**
15
16
  * Main InstaBrain SDK client
@@ -25,6 +26,7 @@ class InstaBrainClient {
25
26
  this.adb = new adb_service_1.AdbService(this.httpClient);
26
27
  this.ibterm = new ibterm_service_1.IBTermService(this.httpClient);
27
28
  this.pureTerm = new pureterm_service_1.PureTermService(this.httpClient);
29
+ this.finalExpense = new finalexpense_service_1.FinalExpenseService(this.httpClient);
28
30
  this.secureSign = new secure_sign_service_1.SecureSignService(this.httpClient);
29
31
  }
30
32
  /**
@@ -106,8 +108,9 @@ class InstaBrainClient {
106
108
  return this.gigdb.startApplication(request);
107
109
  }
108
110
  /**
109
- * Save EFT payment details for a GIGDB or ADB application
110
- * Must be called after startGigdbApplication / startAdbApplication and before the SecureSign flow.
111
+ * Save EFT payment details for a GIGDB, ADB, or Final Expense application.
112
+ * Must be called after startGigdbApplication / startAdbApplication /
113
+ * startFinalExpenseApplication and before the SecureSign flow.
111
114
  * @param request - The EFT payment request with opportunityId and bank account details
112
115
  * @returns Promise resolving to true on success
113
116
  */
@@ -253,6 +256,77 @@ class InstaBrainClient {
253
256
  async getPureTermQuote(request) {
254
257
  return this.pureTerm.getQuote(request);
255
258
  }
259
+ // ── Final Expense Methods ──────────────────────────────────────────────
260
+ /**
261
+ * Get a Final Expense insurance quote (simplified-issue whole life, ages 50–85).
262
+ *
263
+ * `faceAmount`, `gender`, `stateCode`, `paymentFreq`, and `flagTobaccoUse` are
264
+ * required. Supply `age` OR `dateOfBirth` (resolved age 50–85). The response
265
+ * `selectedQuote.quoteResponseId` is the token for `startFinalExpenseApplication()`.
266
+ *
267
+ * @param request - The Final Expense quote request parameters
268
+ * @returns Promise with the quote response containing quoteResponseId
269
+ */
270
+ async getFinalExpenseQuote(request) {
271
+ return this.finalExpense.getQuote(request);
272
+ }
273
+ /**
274
+ * Start a Final Expense application from a prior Final Expense quote.
275
+ *
276
+ * `isDeclined: true` is a valid success response (knockout), not an error.
277
+ * After a non-declined start, continue with `saveEftPayment()`, the Secure
278
+ * Sign flow, then `finalSubmit()` — and poll `pollFinalExpenseUnderwritingStatus()`
279
+ * because Final Expense underwrites asynchronously.
280
+ *
281
+ * @param request - The Final Expense start-application request payload
282
+ * @returns Promise with `opportunityId`, `isDeclined`, and `isQuoteChanged`
283
+ */
284
+ async startFinalExpenseApplication(request) {
285
+ return this.finalExpense.startApplication(request);
286
+ }
287
+ /**
288
+ * Get the existing Final Expense quote for an in-flight opportunity by ID.
289
+ * Use `selectedQuote.quoteResponseId` as `quoteResponseId` on start application.
290
+ *
291
+ * @param opportunityId - UUID from a prior Final Expense quote/application flow
292
+ * @returns Promise with the current quote response
293
+ */
294
+ async getFinalExpenseExistingQuote(opportunityId) {
295
+ return this.finalExpense.getExistingQuote(opportunityId);
296
+ }
297
+ /**
298
+ * Update the face amount and/or payment frequency on an existing Final Expense
299
+ * quote. Blocked once EFT payment is recorded for the opportunity.
300
+ *
301
+ * @param request - The update-quote request (`opportunityId`, `faceAmount`, `paymentFreq`)
302
+ * @returns Promise with the recalculated quote response
303
+ */
304
+ async updateFinalExpenseQuote(request) {
305
+ return this.finalExpense.updateQuote(request);
306
+ }
307
+ /**
308
+ * Single poll of the Final Expense asynchronous underwriting status. Call after
309
+ * `finalSubmit()` returns `applicationStatus: 'InProgress'`. Final Expense only —
310
+ * ADB/GIGDB return `400 FinalSubmitStatusNotSupported`.
311
+ *
312
+ * @param opportunityId - The `opportunityId` from the start-application response
313
+ * @returns Promise with the current `applicationStatus` and `policyNumber`
314
+ */
315
+ async pingFinalExpenseUnderwritingStatus(opportunityId) {
316
+ return this.finalExpense.pingUnderwritingStatus(opportunityId);
317
+ }
318
+ /**
319
+ * Poll the Final Expense asynchronous underwriting decision until a terminal
320
+ * status is reached or the time budget is exhausted (two-phase: every 10s for
321
+ * 7 min, then every 5 min up to 30 min total; all configurable).
322
+ *
323
+ * @param opportunityId - The `opportunityId` from the start-application response
324
+ * @param options - Optional polling cadence overrides
325
+ * @returns Promise with the final ping response (terminal status, or last `'InProgress'` on timeout)
326
+ */
327
+ async pollFinalExpenseUnderwritingStatus(opportunityId, options) {
328
+ return this.finalExpense.pollUnderwritingStatus(opportunityId, options);
329
+ }
256
330
  // ── Secure Sign Methods ─────────────────────────────────────────────
257
331
  /**
258
332
  * Prepare the signing package and check available delivery channels
@@ -13,11 +13,22 @@ export declare class ApplicationService extends BaseService {
13
13
  */
14
14
  startApplication(applicationRequest: ThirdPartyStartApplicationReq): Promise<ThirdPartyStartAppResp>;
15
15
  /**
16
- * Submit the application to the carrier for a final underwriting decision
16
+ * Submit the application to the carrier for a final underwriting decision.
17
17
  * Shared across all products. Call after the signing flow is complete.
18
- * Note: A null policyNumber does not indicate failure — it means the carrier has not yet issued a number (pending decision).
18
+ *
19
+ * Response shape differs by product:
20
+ * - **ADB / GIGDB (synchronous):** `policyNumber` is non-null; `applicationStatus` is absent.
21
+ * - **Final Expense (asynchronous):** `policyNumber` is `null` and
22
+ * `applicationStatus` is `'InProgress'`. Callers must check
23
+ * `applicationStatus === 'InProgress'` and then poll
24
+ * `pollFinalExpenseUnderwritingStatus(opportunityId)` for the terminal decision.
25
+ *
26
+ * Note: a `null` policyNumber does not indicate failure.
27
+ * Note: `finalSubmit` can only be called once per `opportunityId` — subsequent
28
+ * calls return `"Application has already been final submitted."`.
29
+ *
19
30
  * @param opportunityId - The OpportunityId from the Start Application response
20
- * @returns Promise with the final submit response containing policyNumber
31
+ * @returns Promise with the final submit response (`policyNumber`, optional `applicationStatus`)
21
32
  */
22
33
  finalSubmit(opportunityId: string): Promise<ThirdPartyFinalSubmitResp>;
23
34
  }
@@ -18,11 +18,22 @@ class ApplicationService extends base_service_1.BaseService {
18
18
  return this.post('start application', '/api/ThirdPartyStartApp/start-application', applicationRequest);
19
19
  }
20
20
  /**
21
- * Submit the application to the carrier for a final underwriting decision
21
+ * Submit the application to the carrier for a final underwriting decision.
22
22
  * Shared across all products. Call after the signing flow is complete.
23
- * Note: A null policyNumber does not indicate failure — it means the carrier has not yet issued a number (pending decision).
23
+ *
24
+ * Response shape differs by product:
25
+ * - **ADB / GIGDB (synchronous):** `policyNumber` is non-null; `applicationStatus` is absent.
26
+ * - **Final Expense (asynchronous):** `policyNumber` is `null` and
27
+ * `applicationStatus` is `'InProgress'`. Callers must check
28
+ * `applicationStatus === 'InProgress'` and then poll
29
+ * `pollFinalExpenseUnderwritingStatus(opportunityId)` for the terminal decision.
30
+ *
31
+ * Note: a `null` policyNumber does not indicate failure.
32
+ * Note: `finalSubmit` can only be called once per `opportunityId` — subsequent
33
+ * calls return `"Application has already been final submitted."`.
34
+ *
24
35
  * @param opportunityId - The OpportunityId from the Start Application response
25
- * @returns Promise with the final submit response containing policyNumber
36
+ * @returns Promise with the final submit response (`policyNumber`, optional `applicationStatus`)
26
37
  */
27
38
  async finalSubmit(opportunityId) {
28
39
  return this.post('submit application', '/api/ThirdPartyApplication/final-submit', null, { params: { opportunityId } });
@@ -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;
@@ -472,7 +472,7 @@ export declare enum APIErrorCode {
472
472
  BenefitPeriodNotAvailable = "BenefitPeriodNotAvailable",
473
473
  /** IB Term Quote only — height + weight fall outside the carrier's acceptable build chart. */
474
474
  OutsideBuildChart = "outsideBuildChart",
475
- /** ADB / GIGDB Start Application only — same SSN, email, or phone already has a policy generated within the last 30 days. IB Term does NOT use this code. */
475
+ /** ADB / GIGDB / Final Expense Start Application only — same SSN, email, or phone already has a policy generated within the last 30 days. IB Term does NOT use this code. */
476
476
  ApplicationLimitReached = "ApplicationLimitReached",
477
477
  /** Quote state and `Address.State` on Start Application refer to different US states (case-insensitive compare). Returned only after request validation passes. */
478
478
  StateMismatchIdentified = "StateMismatchIdentified",
@@ -502,6 +502,8 @@ export declare enum APIErrorCode {
502
502
  PaymentNotMade = "paymentNotMade",
503
503
  /** Fidelity carrier rejected or failed to process final submit. */
504
504
  FidelityFinalSubmitError = "FidelityFinalSubmitError",
505
+ /** Underwriting status polling is not supported for the product (ADB/GIGDB) — Final Expense only. Returned by `pingFinalExpenseUnderwritingStatus()` / `pollFinalExpenseUnderwritingStatus()` for a non-Final-Expense opportunity. */
506
+ FinalSubmitStatusNotSupported = "FinalSubmitStatusNotSupported",
505
507
  AgentLogout = "AgentLogout",
506
508
  /** Top-level code returned by `getExistingIBTermQuote()` / `getExistingGigdbQuote()` / `getExistingAdbQuote()` when no quote is on file for the opportunityId. HTTP 400, `value: null`. */
507
509
  QuoteNotFound = "QuoteNotFound",
@@ -508,7 +508,7 @@ var APIErrorCode;
508
508
  /** IB Term Quote only — height + weight fall outside the carrier's acceptable build chart. */
509
509
  APIErrorCode["OutsideBuildChart"] = "outsideBuildChart";
510
510
  // ─── Start Application — duplicate-detection limit ───────────────────────
511
- /** ADB / GIGDB Start Application only — same SSN, email, or phone already has a policy generated within the last 30 days. IB Term does NOT use this code. */
511
+ /** ADB / GIGDB / Final Expense Start Application only — same SSN, email, or phone already has a policy generated within the last 30 days. IB Term does NOT use this code. */
512
512
  APIErrorCode["ApplicationLimitReached"] = "ApplicationLimitReached";
513
513
  // ─── Start Application — business top-level errors (ADB / GIGDB / IB Term) ─
514
514
  /** Quote state and `Address.State` on Start Application refer to different US states (case-insensitive compare). Returned only after request validation passes. */
@@ -542,6 +542,8 @@ var APIErrorCode;
542
542
  APIErrorCode["PaymentNotMade"] = "paymentNotMade";
543
543
  /** Fidelity carrier rejected or failed to process final submit. */
544
544
  APIErrorCode["FidelityFinalSubmitError"] = "FidelityFinalSubmitError";
545
+ /** Underwriting status polling is not supported for the product (ADB/GIGDB) — Final Expense only. Returned by `pingFinalExpenseUnderwritingStatus()` / `pollFinalExpenseUnderwritingStatus()` for a non-Final-Expense opportunity. */
546
+ APIErrorCode["FinalSubmitStatusNotSupported"] = "FinalSubmitStatusNotSupported";
545
547
  // ─── Session ─────────────────────────────────────────────────────────────
546
548
  APIErrorCode["AgentLogout"] = "AgentLogout";
547
549
  // ─── Get Existing Quote ──────────────────────────────────────────────────
@@ -80,6 +80,7 @@ class APIValidationError extends InstaBrainError {
80
80
  'EmailDeliveryFailed': 'Email delivery failed. Retry or switch to SMS.',
81
81
  'MessageNotDelivered': 'SMS delivery failed. Retry or switch to email.',
82
82
  'FidelityFinalSubmitError': 'Fidelity carrier rejected or failed to process the submission. Contact support with the opportunityId.',
83
+ 'FinalSubmitStatusNotSupported': 'Underwriting status polling is not supported for this product — Final Expense only.',
83
84
  'AgentLogout': 'Agent session has expired. Please re-authenticate.',
84
85
  'InvalidBirthCountry': 'The birth country provided is not valid.',
85
86
  'InvalidBirthState': 'The birth state provided is not valid.',