@instabrain-sdks/api-client 2.5.0 → 2.7.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 (38) hide show
  1. package/LICENSE.md +31 -0
  2. package/README.md +684 -66
  3. package/dist/client/instabrain-client.d.ts +96 -14
  4. package/dist/client/instabrain-client.js +102 -13
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +5 -1
  7. package/dist/services/adb.service.d.ts +1 -1
  8. package/dist/services/adb.service.js +1 -1
  9. package/dist/services/application.service.d.ts +9 -2
  10. package/dist/services/application.service.js +9 -2
  11. package/dist/services/finalexpense.service.d.ts +24 -6
  12. package/dist/services/finalexpense.service.js +24 -6
  13. package/dist/services/gigdb.service.d.ts +19 -8
  14. package/dist/services/gigdb.service.js +20 -9
  15. package/dist/services/ibterm.service.d.ts +17 -5
  16. package/dist/services/ibterm.service.js +17 -5
  17. package/dist/services/pivot.service.d.ts +104 -0
  18. package/dist/services/pivot.service.js +116 -0
  19. package/dist/services/pureterm.service.d.ts +12 -4
  20. package/dist/services/pureterm.service.js +12 -4
  21. package/dist/types/application.types.d.ts +27 -5
  22. package/dist/types/constants.d.ts +11 -0
  23. package/dist/types/constants.js +12 -1
  24. package/dist/types/enums.d.ts +55 -5
  25. package/dist/types/enums.js +66 -5
  26. package/dist/types/errors.d.ts +4 -4
  27. package/dist/types/errors.js +8 -2
  28. package/dist/types/gigdb.types.d.ts +34 -7
  29. package/dist/types/ibterm.types.d.ts +9 -0
  30. package/dist/types/index.d.ts +2 -0
  31. package/dist/types/index.js +2 -0
  32. package/dist/types/pivot.types.d.ts +122 -0
  33. package/dist/types/pivot.types.js +2 -0
  34. package/dist/types/webhook.types.d.ts +55 -0
  35. package/dist/types/webhook.types.js +3 -0
  36. package/dist/utils/webhook-signature.d.ts +72 -0
  37. package/dist/utils/webhook-signature.js +172 -0
  38. package/package.json +27 -16
package/README.md CHANGED
@@ -7,7 +7,7 @@ TypeScript SDK for Node.js. All operations go through `InstaBrainClient` — req
7
7
  **Products covered:** GIGDB, ADB, IB Term, Pure Term.
8
8
 
9
9
  - **GIGDB & ADB** — full client flow: `get*Quote()` → `start*Application()` → `saveEftPayment()` → SecureSign methods → `finalSubmit()`.
10
- - **IB Term** — client flow ends at `startIBTermApplication()`; use returned `agentLink` / `applicantLink` / `eAppAgentLink` for the InstaBrain frontend.
10
+ - **IB Term** — client flow ends at `startIBTermApplication()`; use returned `agentLink` / `applicantLink` / `eAppAgentLink` for the InstaBrain frontend. The shared `saveEftPayment()` is the one optional exception.
11
11
  - **Pure Term** — pre-fill flow: `getPureTermQuote()` → `startPureTermApplication()`; use returned links for the InstaBrain frontend.
12
12
 
13
13
  ```typescript
@@ -59,31 +59,40 @@ Credentials (`userId` and `accessToken`) are provisioned during onboarding.
59
59
  - [Get existing quote](#final-expense--get-existing-quote)
60
60
  - [Update quote](#final-expense--update-quote)
61
61
  - [Underwriting status (async)](#final-expense--underwriting-status-async)
62
- 9. [Shared methods — GIGDB, ADB & Final Expense](#shared-methods--gigdb-adb--final-expense)
63
- - [Payment — EFT or credit card](#payment--eft-or-credit-card)
64
- - [Get credit card iframe URL](#get-credit-card-iframe-url)
65
- - [Credit card payment status](#credit-card-payment-status)
66
- - [Save EFT payment](#save-eft-payment)
67
- - [Prepare docs & get delivery channels](#prepare-docs--get-delivery-channels)
68
- - [Send PIN & get documents link](#send-pin--get-documents-link)
69
- - [Resend PIN](#resend-pin)
70
- - [Verify PIN](#verify-pin)
71
- - [Final submit](#final-submit)
72
- 10. [Reporting](#reporting)
73
- - [Request fields](#request-fields-shared-shape)
74
- - [Filters (`SQLOperator`)](#filters--sqloperator-enum)
75
- - [Response shapes](#response-shapes)
76
- 11. [Enums & Constants](#enums--constants)
77
- 12. [Beneficiary Reference](#beneficiary-reference)
62
+ - [GIGDB pivot after a decline](#gigdb-pivot--after-a-final-expense-decline)
63
+ 9. [Generic start application](#generic-start-application)
64
+ 10. [Application-status webhooks](#application-status-webhooks)
65
+ - [Registering for webhooks](#registering-for-webhooks)
66
+ - [Your endpoint](#your-endpoint)
67
+ - [Verifying signatures](#verifying-signatures)
68
+ - [Envelope & events](#envelope--events)
69
+ - [Idempotency & ordering](#idempotency--ordering)
70
+ - [Delivery is best-effort](#delivery-is-best-effort)
71
+ 11. [Shared methods — GIGDB, ADB & Final Expense](#shared-methods--gigdb-adb--final-expense)
72
+ - [Payment — EFT or credit card](#payment--eft-or-credit-card)
73
+ - [Get credit card iframe URL](#get-credit-card-iframe-url)
74
+ - [Credit card payment status](#credit-card-payment-status)
75
+ - [Save EFT payment](#save-eft-payment)
76
+ - [Prepare docs & get delivery channels](#prepare-docs--get-delivery-channels)
77
+ - [Send PIN & get documents link](#send-pin--get-documents-link)
78
+ - [Resend PIN](#resend-pin)
79
+ - [Verify PIN](#verify-pin)
80
+ - [Final submit](#final-submit)
81
+ 12. [Reporting](#reporting)
82
+ - [Request fields](#request-fields-shared-shape)
83
+ - [Filters (`SQLOperator`)](#filters--sqloperator-enum)
84
+ - [Response shapes](#response-shapes)
85
+ 13. [Enums & Constants](#enums--constants)
86
+ 14. [Beneficiary Reference](#beneficiary-reference)
78
87
  - [No extra fields](#variant-1--no-extra-fields)
79
88
  - [Named person](#variant-2--named-person)
80
89
  - [Named entity](#variant-3--named-entity)
81
- 13. [Error Handling](#error-handling)
90
+ 15. [Error Handling](#error-handling)
82
91
  - [Error class hierarchy](#error-class-hierarchy)
83
92
  - [Using `APIValidationError`](#using-apivalidationerror)
84
93
  - [`BaseResponse<T>` envelope](#baseresponset-envelope)
85
94
  - [Field-level error messages](#field-level-error-messages)
86
- 14. [Error codes (`APIErrorCode`)](#apierrorcode-reference)
95
+ 16. [Error codes (`APIErrorCode`)](#apierrorcode-reference)
87
96
  - [Quote errors](#quote-errors)
88
97
  - [Start application errors](#start-application-errors)
89
98
  - [Payment & quote update errors](#payment--quote-update-errors)
@@ -91,15 +100,17 @@ Credentials (`userId` and `accessToken`) are provisioned during onboarding.
91
100
  - [Final submit errors](#final-submit-errors)
92
101
  - [Session](#session)
93
102
  - [Deprecated codes (reference only)](#deprecated-codes-reference-only)
94
- 15. [Environment Configuration](#environment-configuration)
95
- 16. [Token Management](#token-management)
96
- 17. [Examples Directory](#examples-directory)
97
- 18. [Support](#support)
103
+ 17. [Environment Configuration](#environment-configuration)
104
+ 18. [Token Management](#token-management)
105
+ 19. [Examples Directory](#examples-directory)
106
+ 20. [Support](#support)
98
107
 
99
108
  ---
100
109
 
101
110
  ## Installation
102
111
 
112
+ > **Proprietary License Notice.** This package is proprietary software, not open-source software. Downloading, installing, copying, accessing, or using it is subject to [LICENSE.md](LICENSE.md). Without an executed InstaBrain agreement, use is limited to one ninety-day, non-production evaluation; production, commercial, and end-user-facing use requires an executed agreement.
113
+
103
114
  ```bash
104
115
  npm install @instabrain-sdks/api-client
105
116
  ```
@@ -196,9 +207,9 @@ await client.authenticate(userId, accessToken);
196
207
 
197
208
  | Field | Type | Required | Description | Validation Error |
198
209
  |---|---|---|---|---|
199
- | `faceAmount` | `number` | Yes | Coverage amount in dollars ($5,000–$25,000) | `Coverage amount (FaceAmount) is required.` |
210
+ | `faceAmount` | `number` | Yes | Coverage amount in dollars ($5,000–$25,000, in $1,000 increments; flat across ages 50–85) | `Coverage amount (FaceAmount) is required.` |
200
211
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
201
- | `stateCode` | `string` | Yes | 2-letter US state code | `State code is required.` / `State code is not valid.` / `This product is not available for the selected state.` |
212
+ | `stateCode` | `string` | Yes | 2-letter US state code | `State code is required.` / `State code is not valid.` |
202
213
  | `age` | `number` | Yes* | Applicant age — must be 50–85 | `Either age or date of birth must be provided.` / `Age must be between 50 and 85 for GIGDB.` |
203
214
  | `dateOfBirth` | `string` (ISO 8601) | Yes* | Date of birth — derived age must be 50–85 | `Date of birth must be a valid date.` |
204
215
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -229,6 +240,8 @@ await client.authenticate(userId, accessToken);
229
240
  | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` for details |
230
241
  | `StateNotFound` | State code not recognized |
231
242
  | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
243
+ | `ProductNotAvailableForState` | Request validation — GIGDB has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
244
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
232
245
  | `NotAvailableForState` | GIGDB not available in the requested state |
233
246
  | `QuoteNotEligibleForGivenConditions` | State / age / smoker combination not eligible |
234
247
  | `CoverageNotAvailable` | Face amount outside allowed range for state / age / smoker |
@@ -783,9 +796,9 @@ No field-validation errors are returned for this method.
783
796
 
784
797
  | Field | Type | Required | Description | Validation Error |
785
798
  |---|---|---|---|---|
786
- | `faceAmount` | `number` | Yes | Coverage amount ($50,000–$300,000) | `Coverage amount (FaceAmount) is required.` |
799
+ | `faceAmount` | `number` | Yes | Coverage amount ($50,000–$300,000, in $1,000 increments; flat across ages 20–59) | `Coverage amount (FaceAmount) is required.` |
787
800
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
788
- | `stateCode` | `string` | Yes | 2-letter US state — not MA, NH, AK, CA | `State code is required.` / `State code is not valid.` / `This state is currently not supported.` / `This product is not available for the selected state.` |
801
+ | `stateCode` | `string` | Yes | 2-letter US state — not MA, NH, AK, CA | `State code is required.` / `State code is not valid.` / `This state is currently not supported.` |
789
802
  | `age` | `number` | Yes* | Must be 20–59 | `Either age or date of birth must be provided.` / `Age must be between 20 and 59 for ADB.` |
790
803
  | `dateOfBirth` | `string` (ISO 8601) | Yes* | Derived age must be 20–59 | `Date of birth must be a valid date.` |
791
804
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -815,6 +828,8 @@ No field-validation errors are returned for this method.
815
828
  | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
816
829
  | `StateNotFound` | State code not recognized |
817
830
  | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
831
+ | `ProductNotAvailableForState` | Request validation — ADB has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
832
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
818
833
  | `NotAvailableForState` | ADB not available in the requested state |
819
834
  | `QuoteNotEligibleForGivenConditions` | State / age combination not eligible |
820
835
  | `CoverageNotAvailable` | Face amount outside allowed range |
@@ -1109,7 +1124,7 @@ const updatedQuote = await client.updateAdbQuote({
1109
1124
 
1110
1125
  **InstaBrain Term** — term life product, no medical exam.
1111
1126
 
1112
- This is a **pre-fill flow**: use `getQuote()` and `startIBTermApplication()`, then hand off via `agentLink`, `applicantLink`, and `eAppAgentLink`. Do **not** call `saveEftPayment()`, SecureSign methods, or `finalSubmit()` for IB Term.
1127
+ This is a **pre-fill flow**: use `getQuote()` and `startIBTermApplication()`, then hand off via `agentLink`, `applicantLink`, and `eAppAgentLink`. Do **not** call SecureSign methods, `finalSubmit()`, or the credit-card iframe for IB Term. The shared [`saveEftPayment()`](#save-eft-payment) is allowed.
1113
1128
 
1114
1129
  - **Eligible ages:** 18–60
1115
1130
  - **Not available in:** WY, NY
@@ -1125,13 +1140,16 @@ This is a **pre-fill flow**: use `getQuote()` and `startIBTermApplication()`, th
1125
1140
  └── flagProductNotAvailableForState = true → STOP
1126
1141
  1. [`getQuote()`](#ib-term--get-quote) Get quote → quoteResponseId
1127
1142
  2. [`startIBTermApplication()`](#ib-term--start-application) Start app → agentLink / applicantLink
1128
- ├── isDeclined = true → STOP
1143
+ ├── isDeclined = true + empty / all-zero opportunityId → STOP (knockout, no application)
1144
+ ├── isDeclined = true + real opportunityId → keep the id and any links
1129
1145
  └── isQuoteChanged = true → re-present updated premium, then hand off via links
1130
1146
  3. [`getExistingIBTermQuote()`](#ib-term--get-existing-quote) [Optional] Re-fetch prior quote for resumed session
1131
1147
 
1132
1148
  → Direct agent or applicant to agentLink / applicantLink / eAppAgentLink
1133
1149
  All remaining steps (underwriting, payment, signing) complete inside the InstaBrain frontend.
1134
- No further `InstaBrainClient` methods for IB Term.
1150
+ No further `InstaBrainClient` methods for IB Term, except the optional shared saveEftPayment()
1151
+ (bank payment, including Pay Later). To follow the outcome, opt in to
1152
+ application-status webhooks on start-application (see Application-status webhooks).
1135
1153
  ```
1136
1154
 
1137
1155
  ---
@@ -1210,7 +1228,7 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1210
1228
  | `benefitPeriod` | `number` | Yes | Term: 10, 20, or 30 years (state/age/nicotine dependent) | `Benefit period is required.` |
1211
1229
  | `flagTobaccoUse` | `boolean` | No | Defaults to `false` when omitted | — |
1212
1230
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
1213
- | `stateCode` | `string` | Yes | 2-letter US state — do **not** send `zipCode` for IB Term | `State code is required.` / `State code is not valid.` / `This product is not available for the selected state.` |
1231
+ | `stateCode` | `string` | Yes | 2-letter US state — do **not** send `zipCode` for IB Term | `State code is required.` / `State code is not valid.` |
1214
1232
  | `rateClass` | `RateClass` | One of † | `"Preferred Plus"`, `"Preferred"`, `"Standard"`, `"Standard Extra"` | `Either RateClass, HealthClass, or Height and WeightInLbs must be provided.` / `Rate class is invalid. Allowed values: Preferred Plus, Preferred, Standard, Standard Extra.` |
1215
1233
  | `healthClass` | `HealthClass` | One of † | `"excellent"`, `"great"`, `"good"`, `"average"` (case-insensitive) | `Health class is invalid. Allowed values: excellent, great, good, average.` |
1216
1234
  | `height` | `ThirdPartyQuoteReqHeight \| null` | One of † | `feet` (1–8), `inches` (0–11) — required with `weightInLbs` | `Height or weight is invalid.` |
@@ -1268,6 +1286,8 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1268
1286
  | `AgeNotFound` | `null` | Neither age nor date of birth supplied, or age could not be derived |
1269
1287
  | `BenefitPeriodNotAvailable` | `fields` object present | `benefitPeriod` not allowed for state/age/nicotine |
1270
1288
  | `CoverageNotAvailable` | `fields` object present | `faceAmount` out of range for state/age/nicotine |
1289
+ | `ProductNotAvailableForState` | Request validation — IB Term has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
1290
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
1271
1291
  | `NotAvailableForState` | `null` | Product not available in this state |
1272
1292
  | `QuoteNotEligibleForGivenConditions` | `null` | State/age/nicotine combination not eligible |
1273
1293
  | `OutsideBuildChart` | `null` | Height/weight outside carrier build chart |
@@ -1331,7 +1351,7 @@ Many fields are **optional** — validated only when sent. Backend validation fi
1331
1351
 
1332
1352
  **Always required:** `quoteResponseId`, `firstName`, `lastName`, `email`, `phoneNumber`, `isUsCitizenOrIsPermanentResident`, `isPayerAlsoOwnerAndInsured`, `height`, `weight`, `isHoldingValidDriverLicense`, `areListedConditionsNotApplicable`.
1333
1353
 
1334
- **Optional — validated when sent:** `address`, `dateOfBirth`, `socialSecurityNumber`, `birthJurisdiction`, `driverLicenseState`, `driverLicenseNumber`, `hasPrimaryCarePhysician` / `physicianDetails`, `tobaccoNicotineUsage`, `hasExistingCoverage` / `existingCoverageData`, `beneficiaryDetails`.
1354
+ **Optional — validated when sent:** `address`, `dateOfBirth`, `socialSecurityNumber`, `birthJurisdiction`, `driverLicenseState`, `driverLicenseNumber`, `hasPrimaryCarePhysician` / `physicianDetails`, `tobaccoNicotineUsage`, `hasExistingCoverage` / `existingCoverageData`, `beneficiaryDetails`, `webhookRegistrationDetails`.
1335
1355
 
1336
1356
  **Conditional:** `childRiderInfo` — required when Dependent Child Rider is on the quote; must not be sent otherwise.
1337
1357
 
@@ -1497,6 +1517,25 @@ IB Term accepts only: `Person`, `Trust`, `Insured Estate`, `All Children Of The
1497
1517
  > Total `insuranceAmount` for entries where `toBeReplaced = false` must not exceed $100,000.
1498
1518
 
1499
1519
 
1520
+ ***
1521
+
1522
+ ### Webhook Registration (optional)
1523
+
1524
+ Opt in to [application-status webhooks](#application-status-webhooks) for the opportunity this call creates. Omit `webhookRegistrationDetails` or pass `null` for no callbacks — both are treated the same.
1525
+
1526
+ | Field | Type | Required | Validation Error |
1527
+ |---|---|---|---|
1528
+ | `webhookRegistrationDetails` | `WebhookRegistrationDetails \| null` | No | — |
1529
+ | `webhookRegistrationDetails.callbackUrl` | `string` | When the object is sent | `Webhook registration callbackUrl is required when webhookRegistrationDetails is provided.` / `callbackUrl must be at most 2048 characters.` / `callbackUrl must be an absolute HTTPS URL.` |
1530
+ | `webhookRegistrationDetails.secretKey` | `string` | When the object is sent | `Webhook registration secretKey is required when webhookRegistrationDetails is provided.` / `secretKey must be between 16 and 256 characters.` |
1531
+
1532
+ - `callbackUrl` must be an absolute **HTTPS** URL, max 2048 characters, in **both sandbox and production** — `http://` is rejected. Use a public HTTPS tunnel for local testing.
1533
+ - `secretKey` is 16–256 characters. Keep it server-side; you need it to verify every delivery.
1534
+ - An empty object `{}` is not a skip — both fields are then required, and the request fails.
1535
+ - Invalid details fail the whole request with `InvalidRequestFormat` under `value.fields['WebhookRegistrationDetails.CallbackUrl']` / `['WebhookRegistrationDetails.SecretKey']`, and **no application is created**.
1536
+ - One callback per opportunity. It cannot be changed after start-application.
1537
+
1538
+
1500
1539
  ***
1501
1540
 
1502
1541
  ### Business Rules
@@ -1513,7 +1552,12 @@ IB Term accepts only: `Person`, `Trust`, `Insured Estate`, `All Children Of The
1513
1552
 
1514
1553
  ### Knockout Rules
1515
1554
 
1516
- Returns `isDeclined: true` on a successful response — the SDK does **not** throw.
1555
+ Returns `isDeclined: true` on a successful response — the SDK does **not** throw. Read `isDeclined` **together with `opportunityId`**:
1556
+
1557
+ - **Knockout** — `opportunityId` is empty or all-zero. No application exists, no links are returned, and no webhook is registered. Stop.
1558
+ - **Declined after the application was created** — `opportunityId` is a real GUID. Keep it, and keep `agentLink` / `applicantLink` / `eAppAgentLink` if they are present. Trust this response; do not wait for a `Declined` webhook for this call.
1559
+
1560
+ These inputs are knockouts:
1517
1561
 
1518
1562
  - `isPayerAlsoOwnerAndInsured = false`
1519
1563
  - `isUsCitizenOrIsPermanentResident = false`
@@ -1548,14 +1592,14 @@ When `isQuoteChanged = true`, the carrier adjusted the premium. Re-present the u
1548
1592
 
1549
1593
  | Field | Type | Description |
1550
1594
  |---|---|---|
1551
- | `opportunityId` | `string` | All-zero UUID when declined before opportunity creation |
1552
- | `isDeclined` | `boolean` | `true` = knockout; stop the flow |
1595
+ | `opportunityId` | `string` | Empty or all-zero UUID on a knockout (no application). Same value as the webhook `opportunityUid` |
1596
+ | `isDeclined` | `boolean` | `true` = declined. Stop only when `opportunityId` is empty or all-zero; otherwise keep the id and links |
1553
1597
  | `isQuoteChanged` | `boolean` | `true` = carrier adjusted premium; re-present before handoff |
1554
1598
  | `agentLink` | `string\|null` | Agent Conversational UI |
1555
1599
  | `applicantLink` | `string\|null` | Applicant Conversational UI |
1556
1600
  | `eAppAgentLink` | `string\|null` | Agent E-App |
1557
1601
 
1558
- > After a non-declined response, direct the agent or applicant to the appropriate link. All remaining steps (underwriting, payment, signing) complete inside the InstaBrain frontend.
1602
+ > After a non-declined response, direct the agent or applicant to the appropriate link. All remaining steps (underwriting, payment, signing) complete inside the InstaBrain frontend — bank payment can alternatively be saved with the shared [`saveEftPayment()`](#save-eft-payment). To follow the outcome, send `webhookRegistrationDetails` on this start-application call — see [application-status webhooks](#application-status-webhooks) (delivery is best-effort).
1559
1603
 
1560
1604
 
1561
1605
  ***
@@ -1586,16 +1630,22 @@ const appResp = await client.startIBTermApplication({
1586
1630
  beneficiaryDetails: {
1587
1631
  beneficiaryType: BeneficiaryType.Person,
1588
1632
  beneficiaryPerson: { firstName: 'Mary', lastName: 'Smith', relationship: BeneficiaryRelationship.Spouse }
1633
+ },
1634
+ // Optional — receive application-status webhooks for this opportunity
1635
+ webhookRegistrationDetails: {
1636
+ callbackUrl: 'https://partner.example.com/webhooks/instabrain',
1637
+ secretKey: process.env.INSTABRAIN_WEBHOOK_SECRET!
1589
1638
  }
1590
1639
  });
1591
1640
 
1592
- if (appResp.isDeclined) {
1593
- return;
1641
+ const ALL_ZERO = '00000000-0000-0000-0000-000000000000';
1642
+ if (appResp.isDeclined && (!appResp.opportunityId || appResp.opportunityId === ALL_ZERO)) {
1643
+ return; // Knockout — no application exists
1594
1644
  }
1595
1645
  if (appResp.isQuoteChanged) {
1596
1646
  // Re-present updated premium before directing to link
1597
1647
  }
1598
- // Hand off to InstaBrain frontend
1648
+ // Hand off to InstaBrain frontend. Persist opportunityId to match webhook deliveries.
1599
1649
  console.log('Applicant link:', appResp.applicantLink);
1600
1650
  ```
1601
1651
 
@@ -1683,13 +1733,16 @@ Coverage and benefit-period availability tables are Pure-Term-specific — see [
1683
1733
  └── flagProductNotAvailableForState = true → STOP (not sold in this state)
1684
1734
  2. [`getPureTermQuote()`](#pure-term--get-quote) Get quote → quoteResponseId
1685
1735
  3. [`startPureTermApplication()`](#pure-term--start-application) Start app → opportunityId + links
1686
- ├── isDeclined = true → STOP (knockout)
1736
+ ├── isDeclined = true + empty / all-zero opportunityId → STOP (knockout, no application)
1737
+ ├── isDeclined = true + real opportunityId → keep the id and any links
1687
1738
  └── isQuoteChanged = true → re-present updated premium, then hand off via links
1688
1739
 
1689
1740
  [`getPureTermExistingQuote()`](#pure-term--get-existing-quote) (optional) Re-fetch the stored quote
1690
1741
 
1691
1742
  → Direct agent or applicant to agentLink / applicantLink / eAppAgentLink
1692
- All remaining steps complete inside the InstaBrain frontend.
1743
+ All remaining steps complete inside the InstaBrain frontend (the shared saveEftPayment() is
1744
+ allowed for bank payment). To follow the outcome, opt in to
1745
+ application-status webhooks on start-application (see Application-status webhooks).
1693
1746
  ```
1694
1747
 
1695
1748
  ---
@@ -1772,7 +1825,7 @@ Provide at least one rating group (†) and one age input (‡).
1772
1825
  | `benefitPeriod` | `number` | Yes | Term: 10, 15, 20, or 30 years (state/age/tobacco dependent) | `Benefit period is required.` |
1773
1826
  | `flagTobaccoUse` | `boolean` | No | Defaults to `false` when omitted | — |
1774
1827
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
1775
- | `stateCode` | `string` | Yes | 2-letter US state code. Send `stateCode` only — do **not** send `zipCode` | `State code is required.` / `State code is not valid.` / `This product is not available for the selected state.` |
1828
+ | `stateCode` | `string` | Yes | 2-letter US state code. Send `stateCode` only — do **not** send `zipCode` | `State code is required.` / `State code is not valid.` |
1776
1829
  | `rateClass` | `PureTermRateClass` | One of † | `"Preferred Plus"`, `"Preferred"`, `"Standard"`, `"Standard Extra"`, `"Rated C"`, `"Rated D"` | `Either RateClass, HealthClass, or Height and WeightInLbs must be provided.` / `Rate class is invalid. Allowed values: Preferred Plus, Preferred, Standard, Standard Extra, Rated C, Rated D.` |
1777
1830
  | `healthClass` | `HealthClass` | One of † | `"excellent"`, `"great"`, `"good"`, `"average"` (case-insensitive) | `Health class is invalid.` |
1778
1831
  | `height` | `ThirdPartyQuoteReqHeight \| null` | One of † | `feet` (1–8), `inches` (0–11) — required with `weightInLbs` | `Height or weight is invalid.` |
@@ -1841,6 +1894,8 @@ The server applies these in order. Only rules 9's two outcomes get dedicated top
1841
1894
  | `AgeNotFound` | `null` | Neither age nor date of birth supplied, or age could not be derived |
1842
1895
  | `BenefitPeriodNotAvailable` | `fields` object present | `benefitPeriod` not allowed for state/age/nicotine |
1843
1896
  | `CoverageNotAvailable` | `fields` object present | `faceAmount` out of range for state/age/nicotine |
1897
+ | `ProductNotAvailableForState` | Request validation — Pure Term has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
1898
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
1844
1899
  | `NotAvailableForState` | `null` | Product not available in this state |
1845
1900
  | `QuoteNotEligibleForGivenConditions` | `null` | State/age/nicotine combination not eligible |
1846
1901
  | `OutsideBuildChart` | `null` | Height/weight outside carrier build chart |
@@ -1961,7 +2016,7 @@ console.log(existing.selectedQuote.quoteAmount, existing.selectedQuote.benefitPe
1961
2016
 
1962
2017
  **Method:** `client.startPureTermApplication(request)` · **Type:** `PureTermStartApplicationReq`
1963
2018
 
1964
- A **dedicated** Pure Term endpoint. This is separate from the generic `client.startApplication()`, which is unchanged and still serves other products — do not substitute one for the other.
2019
+ A **dedicated** Pure Term endpoint. This is separate from the [generic `client.startApplication()`](#generic-start-application) — do not substitute one for the other.
1965
2020
 
1966
2021
  The backend shares one request contract between IB Term and Pure Term start-application: same fields, same nesting, same optionality, same validation messages. `PureTermStartApplicationReq` is therefore the same structure as `IBTermStartApplicationReq`, and the full field-by-field tables in [IB Term — Start Application](#ib-term--start-application) apply here unchanged. Only the differences are listed below.
1967
2022
 
@@ -1973,6 +2028,7 @@ The backend shares one request contract between IB Term and Pure Term start-appl
1973
2028
  | Field | Type | Required | Description |
1974
2029
  |---|---|---|---|
1975
2030
  | `quoteResponseId` | `string` | Yes | UUID from `getPureTermQuote()` — must belong to the **Pure Term** product |
2031
+ | `webhookRegistrationDetails` | `WebhookRegistrationDetails \| null` | No | Opt in to [application-status webhooks](#application-status-webhooks). Same rules and messages as [IB Term — Webhook Registration](#webhook-registration-optional) |
1976
2032
  | *(all other fields)* | — | — | Identical to [IB Term — Start Application](#ib-term--start-application) |
1977
2033
 
1978
2034
  > `proCode` does **not** apply here — it belongs to the generic `startApplication()` only.
@@ -1982,7 +2038,7 @@ The backend shares one request contract between IB Term and Pure Term start-appl
1982
2038
 
1983
2039
  ### Business Rules
1984
2040
 
1985
- 1. `isDeclined: true` is a valid success response (knockout) — the SDK does **not** throw.
2041
+ 1. `isDeclined: true` is a valid success response — the SDK does **not** throw. Stop only on a knockout (empty or all-zero `opportunityId`); with a real `opportunityId`, keep the id and any links.
1986
2042
  2. When `isQuoteChanged = true`, the carrier adjusted the premium. Re-present it before directing the applicant to the link, or call `getPureTermExistingQuote()` to read the updated quote.
1987
2043
  3. `quoteResponseId` must belong to Pure Term, otherwise: `QuoteResponseId does not exist or does not belong to the requested product.`
1988
2044
  4. `address.state` (when sent) must match the quote state — a mismatch returns `StateMismatchIdentified`.
@@ -1991,13 +2047,14 @@ The backend shares one request contract between IB Term and Pure Term start-appl
1991
2047
  7. `physicianDetails.stateCode` rejects both `"Outside Of The USA"` and `"OutsideUSA"`.
1992
2048
  8. Pure Term does **not** run the `ApplicationLimitReached` duplicate SSN/email/phone check (that applies to GIGDB, ADB, and Final Expense).
1993
2049
  9. Validation returns at most one message per field; `value.fields` keys are PascalCase and may be nested (e.g. `ChildRiderInfo.IsAnyChildTakingMedication`).
2050
+ 10. `webhookRegistrationDetails` follows the IB Term rules: omit or `null` for no callbacks; when sent, `callbackUrl` (absolute HTTPS in sandbox and production) and `secretKey` (16–256 characters) are both required. Invalid details fail with `InvalidRequestFormat` and no application is created.
1994
2051
 
1995
2052
 
1996
2053
  ***
1997
2054
 
1998
2055
  ### Knockout Rules
1999
2056
 
2000
- Any of the following returns HTTP `200` with `isDeclined: true` — the SDK does **not** throw. Check the field explicitly.
2057
+ Any of the following returns HTTP `200` with `isDeclined: true` and an empty or all-zero `opportunityId` — no application exists, and no webhook is registered. The SDK does **not** throw; check the fields explicitly. When `isDeclined` is `true` with a **real** `opportunityId`, the application was declined after it was created — keep the id and any returned links, and do not wait for a `Declined` webhook for this call.
2001
2058
 
2002
2059
  - `isUsCitizenOrIsPermanentResident = false`
2003
2060
  - `isPayerAlsoOwnerAndInsured = false`
@@ -2028,14 +2085,14 @@ Start Application is one shared service across both Term products, so the code s
2028
2085
 
2029
2086
  | Field | Type | Description |
2030
2087
  |---|---|---|
2031
- | `opportunityId` | `string` | All-zero UUID when declined before opportunity creation — never `null` |
2032
- | `isDeclined` | `boolean` | `true` = knockout; stop the flow |
2088
+ | `opportunityId` | `string` | Empty or all-zero UUID on a knockout (no application). Same value as the webhook `opportunityUid` |
2089
+ | `isDeclined` | `boolean` | `true` = declined. Stop only when `opportunityId` is empty or all-zero; otherwise keep the id and links |
2033
2090
  | `isQuoteChanged` | `boolean` | `true` = carrier adjusted premium; re-present before handoff |
2034
2091
  | `agentLink` | `string \| null` | Agent Conversational UI |
2035
2092
  | `applicantLink` | `string \| null` | Applicant Conversational UI |
2036
2093
  | `eAppAgentLink` | `string \| null` | Agent E-App |
2037
2094
 
2038
- > After a non-declined response, direct the agent or applicant to the appropriate link. All remaining steps (underwriting, payment, signing) complete inside the InstaBrain frontend. Do not pass this `opportunityId` to `finalSubmit()`, the SecureSign methods, or the credit-card iframe.
2095
+ > After a non-declined response, direct the agent or applicant to the appropriate link. All remaining steps (underwriting, payment, signing) complete inside the InstaBrain frontend — bank payment can alternatively be saved with the shared [`saveEftPayment()`](#save-eft-payment). Do not pass this `opportunityId` to `finalSubmit()`, the SecureSign methods, or the credit-card iframe. To follow the outcome, send `webhookRegistrationDetails` on this start-application call — see [application-status webhooks](#application-status-webhooks) (delivery is best-effort).
2039
2096
 
2040
2097
 
2041
2098
  ***
@@ -2083,18 +2140,24 @@ const appResp = await client.startPureTermApplication({
2083
2140
  lastName: 'Doe',
2084
2141
  relationship: BeneficiaryRelationship.Spouse
2085
2142
  }
2143
+ },
2144
+ // Optional — receive application-status webhooks for this opportunity
2145
+ webhookRegistrationDetails: {
2146
+ callbackUrl: 'https://partner.example.com/webhooks/instabrain',
2147
+ secretKey: process.env.INSTABRAIN_WEBHOOK_SECRET!
2086
2148
  }
2087
2149
  // childRiderInfo — send ONLY when the Dependent Child Rider is on the quote
2088
2150
  });
2089
2151
 
2090
- if (appResp.isDeclined) {
2091
- return;
2152
+ const ALL_ZERO = '00000000-0000-0000-0000-000000000000';
2153
+ if (appResp.isDeclined && (!appResp.opportunityId || appResp.opportunityId === ALL_ZERO)) {
2154
+ return; // Knockout — no application exists
2092
2155
  }
2093
2156
  if (appResp.isQuoteChanged) {
2094
2157
  const updated = await client.getPureTermExistingQuote(appResp.opportunityId);
2095
2158
  // Re-present updated premium before directing to link
2096
2159
  }
2097
- // Hand off to InstaBrain frontend
2160
+ // Hand off to InstaBrain frontend. Persist opportunityId to match webhook deliveries.
2098
2161
  console.log('Applicant link:', appResp.applicantLink);
2099
2162
  ```
2100
2163
 
@@ -2118,7 +2181,9 @@ This is a **full-flow product** like GIGDB and ADB: quote → start application
2118
2181
  ```
2119
2182
  1. getFinalExpenseQuote() Get quote → quoteResponseId
2120
2183
  2. startFinalExpenseApplication() Start app → opportunityId
2121
- └── isDeclined = true → STOP (knockout)
2184
+ ├── isDeclined = true + all-zero opportunityId → STOP (no application, no pivot)
2185
+ └── isDeclined = true + real opportunityId → STOP the FE flow, but keep the id:
2186
+ it is the input to the GIGDB pivot (step 7)
2122
2187
  3. saveEftPayment() Save bank details (shared method)
2123
2188
  4. Secure Sign flow prepareDocs → sendPin → verifyPin (shared)
2124
2189
  5. finalSubmit() → applicationStatus: 'InProgress' (async!)
@@ -2128,6 +2193,12 @@ This is a **full-flow product** like GIGDB and ADB: quote → start application
2128
2193
  └── (timeout) → resume manually with pingFinalExpenseUnderwritingStatus()
2129
2194
  ```
2130
2195
 
2196
+ ```
2197
+ 7. getPivotQuotes() Only after a decline with a real opportunityId
2198
+ 8. customizePivotQuote() Optional — re-price coverage / frequency
2199
+ 9. convertPivotToApplication() → NEW opportunityId on the alternative product
2200
+ ```
2201
+
2131
2202
  Optional: `getFinalExpenseExistingQuote(opportunityId)` to re-fetch a quote, and `updateFinalExpenseQuote()` to change `faceAmount` / `paymentFreq` before payment.
2132
2203
 
2133
2204
  ---
@@ -2144,9 +2215,9 @@ The response `selectedQuote.quoteResponseId` is the token for `startFinalExpense
2144
2215
 
2145
2216
  | Field | Type | Required | Description | Validation Error |
2146
2217
  |---|---|---|---|---|
2147
- | `faceAmount` | `number` | Yes | Coverage amount ($5,000–$50,000) | `Coverage amount (FaceAmount) is required.` |
2218
+ | `faceAmount` | `number` | Yes | Coverage amount — $5,000–$50,000 for ages 50–80, $5,000–$40,000 for ages 81–85 | `Coverage amount (FaceAmount) is required.` |
2148
2219
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
2149
- | `stateCode` | `string` | Yes | 2-letter US state code; product must be available there | `State code is required.` / `State code is not valid.` / `This product is not available for the selected state.` |
2220
+ | `stateCode` | `string` | Yes | 2-letter US state code; product must be available there | `State code is required.` / `State code is not valid.` |
2150
2221
  | `age` | `number` | Yes‡ | 50–85 | `Either age or date of birth must be provided.` / `Age must be between 50 and 85.` |
2151
2222
  | `dateOfBirth` | `string` (ISO 8601) | Yes‡ | Wins over `age` when both provided; derived age 50–85 | `Date of birth must be a valid date.` |
2152
2223
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -2160,6 +2231,27 @@ The response `selectedQuote.quoteResponseId` is the token for `startFinalExpense
2160
2231
 
2161
2232
  > **‡** Provide `age` OR `dateOfBirth`. When both are sent, `dateOfBirth` takes priority.
2162
2233
 
2234
+
2235
+ ***
2236
+
2237
+ ### Error Codes
2238
+
2239
+ | Code | When |
2240
+ |---|---|
2241
+ | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
2242
+ | `StateNotFound` | State code not recognized |
2243
+ | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
2244
+ | `HeightNotValid` | `height.feet` / `height.inches` out of range |
2245
+ | `ProductNotAvailableForState` | Request validation — Final Expense has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
2246
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
2247
+ | `NotAvailableForState` | Post-validation eligibility — product not available in the state (`value: null`) |
2248
+ | `QuoteNotEligibleForGivenConditions` | State / age / nicotine combination not eligible |
2249
+ | `CoverageNotAvailable` | Face amount outside the allowed range for the age band |
2250
+ | `BenefitPeriodNotAvailable` | Benefit period not allowed for state / age / nicotine |
2251
+
2252
+ > `stateCode` is validated as a cascade that stops at the first failure: required/recognized → product available → agent licensed. See [Quote Errors](#quote-errors) for the full ordering and the distinction between `ProductNotAvailableForState` and `NotAvailableForState`.
2253
+
2254
+
2163
2255
  ***
2164
2256
 
2165
2257
  ### Response
@@ -2304,12 +2396,20 @@ All six fields are required when `includeSecondaryAddressee = true`. When `inclu
2304
2396
 
2305
2397
  ### Knockout summary — returns `isDeclined: true` (not thrown)
2306
2398
 
2399
+ A decline alone no longer tells you whether an application exists. **Branch on `isDeclined` *and* on whether `opportunityId` is all-zero.**
2400
+
2401
+ **All-zero `opportunityId`** — these hard stops fire before an application is created, so there is nothing to pivot from:
2402
+
2307
2403
  - `isPayerAlsoOwnerAndInsured === false`
2308
2404
  - `isUsCitizen === false` AND `isLegalUsResident === false`
2309
2405
  - `isHoldingValidDriverLicense === false`
2406
+ - Height/weight outside the Final Expense build chart
2407
+
2408
+ **Real (non-zero) `opportunityId`** — the application exists but Final Expense declined it. Stop the Final Expense sale path, but retain the id: it is the input to the [GIGDB pivot](#gigdb-pivot--after-a-final-expense-decline).
2409
+
2310
2410
  - Any of the 13 health-prequalification booleans `=== true`
2311
2411
  - Respiratory decline rules above
2312
- - Height/weight outside the Final Expense build chart (decline occurs after opportunity creation — `opportunityId` is a real GUID)
2412
+ - Later underwriting declines
2313
2413
 
2314
2414
  ***
2315
2415
 
@@ -2336,8 +2436,8 @@ All six fields are required when `includeSecondaryAddressee = true`. When `inclu
2336
2436
 
2337
2437
  | Field | Type | Description |
2338
2438
  |---|---|---|
2339
- | `opportunityId` | `string` | All-zero GUID when declined before opportunity creation; real GUID otherwise |
2340
- | `isDeclined` | `boolean` | `true` = knockout / underwriting decline; stop the flow |
2439
+ | `opportunityId` | `string` | All-zero GUID only for the four pre-creation hard stops above; a **real GUID** for every other decline — and that id is what the [GIGDB pivot](#gigdb-pivot--after-a-final-expense-decline) needs |
2440
+ | `isDeclined` | `boolean` | `true` = knockout / underwriting decline; stop the Final Expense flow. Check `opportunityId` before giving up — non-zero means a pivot is available |
2341
2441
  | `isQuoteChanged` | `boolean` | `true` = tobacco flag or DOB triggered a requote; re-present premium |
2342
2442
 
2343
2443
  ***
@@ -2641,9 +2741,453 @@ if (submit.applicationStatus === 'InProgress') {
2641
2741
 
2642
2742
  ---
2643
2743
 
2744
+ ## GIGDB Pivot — after a Final Expense decline
2745
+
2746
+ When Final Expense declines an application **but still creates one** (`isDeclined: true` with a non-zero `opportunityId`), the applicant can be offered an alternative product instead of being turned away. Today that alternative is GIGDB.
2747
+
2748
+ The pivot is not a product of its own — all three methods key off the **declined Final Expense `opportunityId`**.
2749
+
2750
+ ```
2751
+ 1. getPivotQuotes(opportunityId) Alternative quote options
2752
+ 2. customizePivotQuote(request) Optional — re-price coverage / frequency
2753
+ 3. convertPivotToApplication(request) Creates the application → NEW opportunityId
2754
+ 4. getExistingGigdbQuote(newId) Read the current premium
2755
+ 5. … continue the alternative product's normal lifecycle
2756
+ ```
2757
+
2758
+ **Entry condition — check both fields.** Call these methods only when Final Expense start-application returned `isDeclined: true` **and** a non-zero `opportunityId`. Do not call them for approved applications, for all-zero declines, or for products that do not support pivot (today, Final Expense is the only source product).
2759
+
2760
+ ***
2761
+
2762
+ ### Get Pivot Quotes
2763
+
2764
+ **Method:** `client.getPivotQuotes(opportunityId)` · **Endpoint:** `GET /api/ThirdPartyPivot/get-pivot-quotes`
2765
+
2766
+ Calling this repeatedly for the same opportunity is safe.
2767
+
2768
+ **Response:**
2769
+
2770
+ | Field | Type | Description |
2771
+ |---|---|---|
2772
+ | `pivotReason` | `string` | Why the pivot was offered, e.g. `"ApplicationDeclineOrNotEligible"`. Display / log only — do not branch business logic on it |
2773
+ | `quotes` | `PivotQuote[]` | The available alternative-product quotes |
2774
+
2775
+ **`PivotQuote`:**
2776
+
2777
+ | Field | Type | Description |
2778
+ |---|---|---|
2779
+ | `pivotProductCode` | `string` | **Persist this.** Required by both `customizePivotQuote()` and `convertPivotToApplication()`. Use the value the API returned (e.g. `"InstaGIGDB"`) — never construct one |
2780
+ | `productTitle` | `string` | Display title, e.g. `"InstaBrain Guaranteed Issue"` |
2781
+ | `quoteAmount` | `number` | Total premium at the requested payment frequency |
2782
+ | `coverageAmount` | `number` | Coverage in dollars |
2783
+ | `paymentFrequency` | `PaymentFrequency` | Payment frequency (Monthly or Annually) |
2784
+ | `termLength` | `number \| null` | Term in years, or `null` for whole-life products such as GIGDB |
2785
+ | `riders` | `Array<{ riderValue: string; riderLabel: string \| null }>` | Riders included in the quote; empty array when none apply |
2786
+
2787
+ **Error Codes:**
2788
+
2789
+ | Code | HTTP | When |
2790
+ |---|---|---|
2791
+ | `InvalidRequestFormat` | `400` | Missing / malformed / unknown `opportunityId`, or a source product that does not support pivot — inspect `value.fields` |
2792
+ | `PivotNotAvailable` | `400` | The opportunity cannot be pivoted. Top-level, `value: null` — a business state, not a bad request |
2793
+ | — | `403` | `opportunityId` is not authorized for this token. No body |
2794
+
2795
+ **Example:**
2796
+
2797
+ ```typescript
2798
+ const appResp = await client.startFinalExpenseApplication(request);
2799
+
2800
+ const ALL_ZERO = '00000000-0000-0000-0000-000000000000';
2801
+ if (appResp.isDeclined) {
2802
+ if (appResp.opportunityId === ALL_ZERO) {
2803
+ // No application was created — nothing to pivot from.
2804
+ return;
2805
+ }
2806
+
2807
+ const pivot = await client.getPivotQuotes(appResp.opportunityId);
2808
+ console.log(pivot.pivotReason); // 'ApplicationDeclineOrNotEligible'
2809
+ const offer = pivot.quotes[0];
2810
+ console.log(offer.productTitle, offer.quoteAmount, offer.coverageAmount);
2811
+
2812
+ // Persist BOTH for the next two calls.
2813
+ const { opportunityId } = appResp;
2814
+ const { pivotProductCode } = offer;
2815
+ }
2816
+ ```
2817
+
2818
+ ***
2819
+
2820
+ ### Customize Pivot Quote
2821
+
2822
+ **Method:** `client.customizePivotQuote(request)` · **Endpoint:** `POST /api/ThirdPartyPivot/customize-pivot-quote`
2823
+
2824
+ Optional — only call it when the applicant wants a different coverage amount or billing frequency than the default pivot quote. The response is a single quote item with the same shape as one element of `quotes[]`.
2825
+
2826
+ This does **not** persist the choice: `convertPivotToApplication()` still requires `faceAmount` and `paymentFreq` to be sent explicitly.
2827
+
2828
+ **Request Fields:**
2829
+
2830
+ | Field | Type | Required | Description |
2831
+ |---|---|---|---|
2832
+ | `opportunityId` | `string` | Yes | The declined Final Expense opportunity |
2833
+ | `pivotProductCode` | `string` | Yes | Value from `getPivotQuotes()` |
2834
+ | `faceAmount` | `number` | Yes | Desired coverage in dollars. GIGDB: $5,000–$25,000 in $1,000 increments |
2835
+ | `paymentFreq` | `PaymentFrequency` | Yes | `Monthly` or `Annually` only |
2836
+
2837
+ **Error Codes:**
2838
+
2839
+ | Code | HTTP | When |
2840
+ |---|---|---|
2841
+ | `InvalidRequestFormat` | `400` | Missing / malformed body fields, unknown `opportunityId`, or an invalid `pivotProductCode` |
2842
+ | `CoverageNotAvailable` | `400` | `faceAmount` outside the alternative product's range or off its required increment. Top-level, `value: null` |
2843
+ | `PivotNotAvailable` | `400` | The opportunity cannot be pivoted, or pricing could not produce a quote |
2844
+ | — | `403` | `opportunityId` not authorized for this token |
2845
+
2846
+ **Example:**
2847
+
2848
+ ```typescript
2849
+ const repriced = await client.customizePivotQuote({
2850
+ opportunityId,
2851
+ pivotProductCode,
2852
+ faceAmount: 25000,
2853
+ paymentFreq: PaymentFrequency.Monthly,
2854
+ });
2855
+
2856
+ console.log(repriced.quoteAmount); // 52.25
2857
+ console.log(repriced.coverageAmount); // 25000
2858
+ ```
2859
+
2860
+ ***
2861
+
2862
+ ### Convert Pivot to Application
2863
+
2864
+ **Method:** `client.convertPivotToApplication(request)` · **Endpoint:** `POST /api/ThirdPartyPivot/convert-pivot-to-application`
2865
+
2866
+ Call only once the applicant has confirmed the coverage amount and payment frequency they want.
2867
+
2868
+ **Request Fields:**
2869
+
2870
+ | Field | Type | Required | Description |
2871
+ |---|---|---|---|
2872
+ | `opportunityId` | `string` | Yes | The declined Final Expense opportunity |
2873
+ | `pivotProductCode` | `string` | Yes | Value from `getPivotQuotes()` |
2874
+ | `faceAmount` | `number` | Yes | Confirmed coverage. **Required every call** — not carried over from a prior `customizePivotQuote()` |
2875
+ | `paymentFreq` | `PaymentFrequency` | Yes | Confirmed billing frequency. Required every call |
2876
+
2877
+ **Response:**
2878
+
2879
+ | Field | Type | Description |
2880
+ |---|---|---|
2881
+ | `opportunityId` | `string` | **The NEW opportunity**, on the alternative product. Persist it — it replaces the Final Expense id for every subsequent call |
2882
+ | `productCode` | `string` | Which product the new opportunity belongs to, e.g. `"InstaGIGDB"` |
2883
+
2884
+ **Business Rules:**
2885
+
2886
+ - The response carries **no premium by design**. Call the alternative product's get-existing-quote with the new `opportunityId` to read the current amount.
2887
+ - **Do not retry after a successful conversion** — a second attempt on the same opportunity returns `PivotNotAvailable`.
2888
+ - The Final Expense `opportunityId` is finished at this point. Everything that follows — quote, payment, signing, final submit — uses the new one.
2889
+
2890
+ **Error Codes:**
2891
+
2892
+ | Code | HTTP | When |
2893
+ |---|---|---|
2894
+ | `InvalidRequestFormat` | `400` | Missing / malformed body fields, unknown `opportunityId` (`OpportunityId does not exist.`), unsupported product, or an invalid `pivotProductCode` |
2895
+ | `CoverageNotAvailable` | `400` | `faceAmount` outside range or off-increment |
2896
+ | `PivotNotAvailable` | `400` | No longer fit to pivot — e.g. already converted |
2897
+ | — | `403` | `opportunityId` not authorized for this token |
2898
+
2899
+ > An unknown `opportunityId` is `InvalidRequestFormat`, not a dedicated business code. Handle `CoverageNotAvailable` and `PivotNotAvailable` separately from format failures — they arrive top-level with `value: null`.
2900
+
2901
+ **Example — full pivot flow:**
2902
+
2903
+ ```typescript
2904
+ const converted = await client.convertPivotToApplication({
2905
+ opportunityId, // the DECLINED Final Expense id
2906
+ pivotProductCode,
2907
+ faceAmount: 25000,
2908
+ paymentFreq: PaymentFrequency.Monthly,
2909
+ });
2910
+
2911
+ console.log(converted.productCode); // 'InstaGIGDB'
2912
+ const gigdbOpportunityId = converted.opportunityId; // NEW id — persist it
2913
+
2914
+ // No premium in the convert response — read it from the new product.
2915
+ const quote = await client.getExistingGigdbQuote(gigdbOpportunityId);
2916
+ console.log(quote.selectedQuote.quoteAmount);
2917
+
2918
+ // Continue the GIGDB lifecycle with the new id.
2919
+ await client.saveEftPayment({ opportunityId: gigdbOpportunityId, /* … */ } as any);
2920
+ ```
2921
+
2922
+ ---
2923
+
2924
+ ## Generic Start Application
2925
+
2926
+ **Method:** `client.startApplication(request)` · **Type:** `ThirdPartyStartApplicationReq` · **Endpoint:** `POST /api/ThirdPartyStartApp/start-application`
2927
+
2928
+ The older, generic start-application endpoint. It starts an application from a quote and returns `opportunityId` plus links for the InstaBrain frontend. Pass `proCode` to start a specific product variant.
2929
+
2930
+ > For IB Term and Pure Term, InstaBrain recommends the dedicated [`startIBTermApplication()`](#ib-term--start-application) and [`startPureTermApplication()`](#pure-term--start-application), which carry the full request contract.
2931
+
2932
+
2933
+ ***
2934
+
2935
+ ### Request Fields
2936
+
2937
+ | Field | Type | Required | Description |
2938
+ |---|---|---|---|
2939
+ | `quoteResponseId` | `string` | Yes | UUID from the product quote response |
2940
+ | `firstName` | `string \| null` | Yes — pass `null` if not collected | Overrides the first name given on the quote |
2941
+ | `lastName` | `string \| null` | Yes — pass `null` if not collected | Overrides the last name given on the quote |
2942
+ | `email` | `string \| null` | Yes — pass `null` if not collected | Applicant email |
2943
+ | `phoneNumber` | `string \| null` | Yes — pass `null` if not collected | Applicant phone |
2944
+ | `proCode` | `string \| null` | No | Product variant code. Omit to start the base product; contact InstaBrain support for the correct code |
2945
+ | `webhookRegistrationDetails` | `WebhookRegistrationDetails \| null` | No | Opt in to [application-status webhooks](#application-status-webhooks). Same rules and messages as [IB Term — Webhook Registration](#webhook-registration-optional) |
2946
+
2947
+
2948
+ ***
2949
+
2950
+ ### Response
2951
+
2952
+ | Field | Type | Description |
2953
+ |---|---|---|
2954
+ | `opportunityId` | `string` | GUID of the created application. Same value as the webhook `opportunityUid` — persist it |
2955
+ | `agentLink` | `string \| null` | Agent Conversational UI |
2956
+ | `applicantLink` | `string \| null` | Applicant Conversational UI |
2957
+ | `eAppAgentLink` | `string \| null` | Agent E-App |
2958
+ | `isDeclined` | `boolean` | Normally `false` on this route's success path |
2959
+ | `isQuoteChanged` | `boolean` | Normally `false` on this route's success path |
2960
+
2961
+ > Consumer-facing platforms should always use `applicantLink`. `agentLink` and `eAppAgentLink` are for agent-facing interfaces only.
2962
+
2963
+
2964
+ ***
2965
+
2966
+ ### Error Codes
2967
+
2968
+ | Code | When |
2969
+ |---|---|
2970
+ | `InvalidRequestFormat` | Any validation failure, including invalid `webhookRegistrationDetails` — inspect `value.fields` |
2971
+
2972
+ > This route does not return `ApplicationLimitReached`. An invalid or expired token surfaces as `AuthenticationError`.
2973
+
2974
+
2975
+ ***
2976
+
2977
+ ### Example
2978
+
2979
+ ```typescript
2980
+ const appResp = await client.startApplication({
2981
+ quoteResponseId,
2982
+ firstName: 'Jane',
2983
+ lastName: 'Doe',
2984
+ email: 'jane.doe@example.com',
2985
+ phoneNumber: '5551234567',
2986
+ // Optional — receive application-status webhooks for this opportunity
2987
+ webhookRegistrationDetails: {
2988
+ callbackUrl: 'https://partner.example.com/webhooks/instabrain',
2989
+ secretKey: process.env.INSTABRAIN_WEBHOOK_SECRET!
2990
+ }
2991
+ });
2992
+
2993
+ // Persist opportunityId — webhook deliveries carry it as opportunityUid.
2994
+ console.log(appResp.opportunityId, appResp.applicantLink);
2995
+ ```
2996
+
2997
+ ---
2998
+
2999
+ ## Application-status Webhooks
3000
+
3001
+ InstaBrain can POST application-status events — payment, documents signed, policy issued, declined, pivoted — to an HTTPS endpoint you run. This is not a method you call: you opt in on start-application, and InstaBrain calls you.
3002
+
3003
+ ```
3004
+ 1. start…Application({ …, webhookRegistrationDetails }) → persist opportunityId
3005
+ 2. InstaBrain POSTs each event to your callbackUrl
3006
+ 3. verifyWebhookSignature(rawBody, timestamp, signature, secretKey)
3007
+ ├── false → respond 401
3008
+ └── true → parse JSON, store eventId (dedupe), respond 2xx fast, process asynchronously
3009
+ ```
3010
+
3011
+ Delivery is **best-effort** — see [Delivery is best-effort](#delivery-is-best-effort).
3012
+
3013
+
3014
+ ***
3015
+
3016
+ ### Registering for Webhooks
3017
+
3018
+ Send `webhookRegistrationDetails` on start-application. Only three methods accept it:
3019
+
3020
+ | Method | Registers webhooks |
3021
+ |---|---|
3022
+ | [`startIBTermApplication()`](#ib-term--start-application) | Yes |
3023
+ | [`startPureTermApplication()`](#pure-term--start-application) | Yes |
3024
+ | [`startApplication()`](#generic-start-application) (generic) | Yes |
3025
+ | `startAdbApplication()`, `startGigdbApplication()`, `startFinalExpenseApplication()` | **No** — the field is silently ignored: no error, and no callbacks |
3026
+
3027
+ ```typescript
3028
+ webhookRegistrationDetails: {
3029
+ callbackUrl: 'https://partner.example.com/webhooks/instabrain', // absolute HTTPS, max 2048
3030
+ secretKey: process.env.INSTABRAIN_WEBHOOK_SECRET! // 16–256 characters
3031
+ }
3032
+ ```
3033
+
3034
+ - Omit the field or pass `null` for no callbacks — both are treated the same. An empty object `{}` fails validation.
3035
+ - `callbackUrl` must be an absolute **HTTPS** URL in **both sandbox and production** — `http://` is rejected. For local testing, use a public HTTPS tunnel.
3036
+ - Invalid details fail the whole request with `InvalidRequestFormat` (messages under `value.fields['WebhookRegistrationDetails.CallbackUrl']` / `['WebhookRegistrationDetails.SecretKey']`), and **no application is created**. The limits are also exported, for reference, as `WEBHOOK_REGISTRATION_LIMITS`.
3037
+ - A knockout decline (empty or all-zero `opportunityId`) registers nothing.
3038
+ - One callback per opportunity. There is no API to change the URL or secret after start-application, so keep a copy of the secret.
3039
+ - If registration itself fails after the application was created, start-application still succeeds. If you opted in and receive no events, contact InstaBrain.
3040
+
3041
+
3042
+ ***
3043
+
3044
+ ### Your Endpoint
3045
+
3046
+ InstaBrain sends `POST {callbackUrl}` with `Content-Type: application/json` and waits up to **30 seconds** for a response. Store the `eventId`, return **2xx** straight away, and do the real work asynchronously.
3047
+
3048
+ | Your response | What InstaBrain does |
3049
+ |---|---|
3050
+ | `2xx` | Delivered. No retry |
3051
+ | `429` or `5xx` | Retried |
3052
+ | No HTTP response — connection or other transport failure | Retried |
3053
+ | Any other `4xx` | **Not retried** — the event is dropped |
3054
+
3055
+ - Retries: up to **5** after the first attempt, waiting **1, 2, 4, 8, and 16 minutes**.
3056
+ - **Every attempt is signed afresh**: a retry carries a new `X-InstaBrain-Timestamp` and `X-InstaBrain-Signature`. The body and `eventId` stay the same.
3057
+ - Return a 4xx only for a request you want dropped — such as a failed signature check. A bug in your handler should surface as a 5xx, so the event is retried.
3058
+
3059
+ **Where deliveries come from**
3060
+
3061
+ - Deliveries are sent server-to-server from InstaBrain's backend. They don't come from a browser, or from any API you call.
3062
+ - If your endpoint restricts inbound traffic by IP, contact [helpdesk@instabrain.io](mailto:helpdesk@instabrain.io) for InstaBrain's outbound IP addresses (sandbox and production), and allowlist them **before** you register a `callbackUrl`. A blocked delivery counts as a transport failure: it is retried 5 times over about 31 minutes and then dropped, and you never receive an error.
3063
+ - An IP allowlist is extra protection only. Always verify every delivery with `verifyWebhookSignature()`.
3064
+
3065
+ | Header | `WEBHOOK_HEADERS` key | Value |
3066
+ |---|---|---|
3067
+ | `X-InstaBrain-Timestamp` | `TIMESTAMP` | Unix time in seconds (UTC), plain digits — e.g. `1757588400` |
3068
+ | `X-InstaBrain-Signature` | `SIGNATURE` | Lowercase hex HMAC-SHA256 of `{timestamp}.{rawBody}` |
3069
+ | `X-InstaBrain-Event-Id` | `EVENT_ID` | Same value as the body `eventId`. **Not covered by the signature** |
3070
+ | `Content-Type` | — | Always `application/json` |
3071
+
3072
+ `WEBHOOK_HEADERS` holds the lowercase names Node.js uses for `req.headers`.
3073
+
3074
+
3075
+ ***
3076
+
3077
+ ### Verifying Signatures
3078
+
3079
+ Verify **every** delivery before trusting it, with `verifyWebhookSignature()`. It computes HMAC-SHA256 of `{timestamp}.{rawBody}` with your `secretKey`, compares it to `X-InstaBrain-Signature` in constant time, and checks the timestamp is within 5 minutes of now.
3080
+
3081
+ ```typescript
3082
+ import express from 'express';
3083
+ import { verifyWebhookSignature, WEBHOOK_HEADERS } from '@instabrain-sdks/api-client';
3084
+
3085
+ const app = express();
3086
+
3087
+ // express.raw() on this route, ahead of any app-wide express.json(), keeps req.body as the
3088
+ // exact bytes InstaBrain signed.
3089
+ app.post('/webhooks/instabrain', express.raw({ type: 'application/json' }), (req, res) => {
3090
+ const ok = verifyWebhookSignature(
3091
+ req.body, // raw Buffer — never re-stringified JSON
3092
+ req.headers[WEBHOOK_HEADERS.TIMESTAMP],
3093
+ req.headers[WEBHOOK_HEADERS.SIGNATURE],
3094
+ process.env.INSTABRAIN_WEBHOOK_SECRET!
3095
+ );
3096
+ if (!ok) {
3097
+ res.sendStatus(401);
3098
+ return;
3099
+ }
3100
+
3101
+ const event = JSON.parse(req.body.toString('utf8'));
3102
+ // 1. Skip if event.eventId was already stored; otherwise store it.
3103
+ // 2. Respond 2xx now, and handle event.data.event asynchronously.
3104
+ res.sendStatus(200);
3105
+ });
3106
+ ```
3107
+
3108
+ **Pass the body exactly as received.** Parsing and re-stringifying it (`JSON.stringify(JSON.parse(body))`) can change spacing or escaping and break the signature — and because compact bodies often survive the round trip, the bug can stay hidden until production. The helper accepts a `string`, `Buffer`, `Uint8Array`, or `ArrayBuffer`. In fetch-style handlers (e.g. Next.js route handlers), pass `await req.text()` as the body and read the headers with `req.headers.get(WEBHOOK_HEADERS.TIMESTAMP)` and `req.headers.get(WEBHOOK_HEADERS.SIGNATURE)` — bracket access on a fetch `Headers` object returns `undefined`, which fails verification.
3109
+
3110
+ | Outcome | When | What to do |
3111
+ |---|---|---|
3112
+ | Returns `true` | Signature matches and the timestamp is within tolerance | Parse the body and handle the event |
3113
+ | Returns `false` | Missing, malformed, stale, or wrong signature or timestamp | Respond `401` |
3114
+ | Throws `TypeError` | Empty `secretKey`, a body that is not a string or bytes (e.g. an already-parsed object), or invalid options | If it happens on every InstaBrain delivery, fix your setup. Your framework answers `500`, so InstaBrain retries — but only 5 times over about 31 minutes; after that the event is lost. A stray request with a non-JSON `Content-Type` or no body can also land here, because body parsers then leave `req.body` as `{}` or `undefined` — one `TypeError` alone is not proof of misconfiguration |
3115
+
3116
+ - The timestamp window is **300 seconds** in either direction. Because every retry is signed afresh, a legitimate delivery never falls outside it. Keep your server clock in sync: a clock more than 5 minutes off rejects every delivery.
3117
+ - Options: `{ toleranceSeconds }` changes the window (`Infinity` disables it); `{ nowSeconds }` overrides the clock, in **seconds**, for tests.
3118
+ - Uppercase hex signatures are accepted.
3119
+ - `TypeError` is a standard JavaScript error, **not** an `InstaBrainError`.
3120
+ - Keep `secretKey` server-side. Never log it, and never build start-application requests in a browser.
3121
+
3122
+
3123
+ ***
3124
+
3125
+ ### Envelope & Events
3126
+
3127
+ Every delivery is one JSON envelope (camelCase). The SDK deliberately does **not** type the payload — InstaBrain may add events and fields over time. Parse it after verifying, and ignore what you don't recognise.
3128
+
3129
+ | Field | Type | Description |
3130
+ |---|---|---|
3131
+ | `eventId` | `string` (GUID) | Unique per event; retries reuse it. Deduplicate on this |
3132
+ | `webhookType` | `string` | Always `applicationStatus` |
3133
+ | `sequenceNo` | `number` | Order of events **for this `opportunityUid`**, starting at 1 |
3134
+ | `occurredOn` | `string` (ISO-8601, UTC) | When the event happened |
3135
+ | `product` | `string` | Webhook product code — see below |
3136
+ | `opportunityUid` | `string` (GUID) | Same value as the start-application `opportunityId` |
3137
+ | `data` | `object` | Event-specific fields. Always includes `data.event` |
3138
+ | `eventHistory` | `array \| null` | `null` on non-final events. On final events, the earlier envelopes for this opportunity (possibly `[]`), excluding the current one |
3139
+
3140
+ **`product` codes:** `InstaTerm` (IB Term), `InstaPureTerm` (Pure Term), `InstaADB` (ADB), `InstaGIGDB` (GIGDB), `InstaFinalExpense` (Final Expense). These are webhook codes. They match the quote-response `productName` for every product except Pure Term, whose quote `productName` is `"InstaBrain Pure Term"` — so don't treat the two strings as interchangeable. Tolerate values not in this list.
3141
+
3142
+ | `data.event` | Final? | When | Other `data` fields |
3143
+ |---|---|---|---|
3144
+ | `Payment` | No | **IB Term / Pure Term:** payment collected. **ADB / GIGDB / Final Expense:** payment details stored | `paymentMethod`: `EFT` or `CreditCard` |
3145
+ | `DocumentsSigned` | No | Applicant PIN verified / documents signed | — |
3146
+ | `PolicyIssued` | Yes | Policy issued, including scheduled issue | `policyNumber`, `faceAmount`, `premiumAmount`, `paymentFrequency` (nullable), `isPolicyScheduled`, `effectiveDate` (nullable) |
3147
+ | `Declined` | Yes | Declined after the application exists | — |
3148
+ | `Pivoted` | Yes | The application moved to an alternative product | `pivotFromUid`, `pivotToUid`, `pivotFromProductCode`, `pivotToProductCode` |
3149
+
3150
+ - **`Declined` is not a hard stop.** When the product allows a pivot, `Pivoted` can follow `Declined` on the same `opportunityUid` — keep accepting events.
3151
+ - **A `Declined` webhook is not the start-application `isDeclined`.** Trust the start-application response for that call; a `Declined` POST is not guaranteed at start-application time.
3152
+ - **On `Pivoted`**, the event is posted for the *source* `opportunityUid`, and the same `callbackUrl` and `secretKey` are copied to the new application. Later events arrive with `opportunityUid = pivotToUid`, and its `sequenceNo` starts again at 1. If you look up the secret per opportunity, map `pivotToUid` to the same secret.
3153
+
3154
+ Example — a `Payment` delivery:
3155
+
3156
+ ```json
3157
+ {
3158
+ "eventId": "9c2e1f4a-1111-2222-3333-444455556666",
3159
+ "webhookType": "applicationStatus",
3160
+ "sequenceNo": 1,
3161
+ "occurredOn": "2026-09-11T06:00:00Z",
3162
+ "product": "InstaTerm",
3163
+ "opportunityUid": "7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d",
3164
+ "data": { "event": "Payment", "paymentMethod": "EFT" },
3165
+ "eventHistory": null
3166
+ }
3167
+ ```
3168
+
3169
+
3170
+ ***
3171
+
3172
+ ### Idempotency & Ordering
3173
+
3174
+ - The same event can arrive more than once — after a retry, for example. **Deduplicate on the `eventId` inside the verified body**, and store it before you return 2xx.
3175
+ - Don't rely on the `X-InstaBrain-Event-Id` header alone: it carries the same value, but the signature does not cover it.
3176
+ - Use `sequenceNo`, not arrival order, to order events for an opportunity.
3177
+ - Final events carry `eventHistory`, so you can rebuild earlier stages without having stored every POST.
3178
+
3179
+
3180
+ ***
3181
+
3182
+ ### Delivery is Best-Effort
3183
+
3184
+ A successful start-application does not guarantee delivery. Events can be missed — for example when your endpoint answers with a non-retryable 4xx, when retries run out, or when registration fails after the application was created. Treat webhooks as best-effort notifications rather than a guaranteed feed. If you opted in and see no events for an opportunity, contact InstaBrain.
3185
+
3186
+ ---
3187
+
2644
3188
  ## Shared methods — GIGDB, ADB & Final Expense
2645
3189
 
2646
- These methods apply to **GIGDB, ADB, and Final Expense**. IB Term and Pure Term use the frontend links returned by Start Application and do **not** call these.
3190
+ These methods apply to **GIGDB, ADB, and Final Expense**. IB Term and Pure Term use the frontend links returned by Start Application and do **not** call these — with one exception: [`saveEftPayment()`](#save-eft-payment) applies to **every product**, including IB Term and Pure Term. The credit-card iframe, the SecureSign methods, and `finalSubmit()` remain GIGDB / ADB / Final Expense only.
2647
3191
 
2648
3192
  ---
2649
3193
 
@@ -2795,7 +3339,7 @@ Each maps to a distinct `APIErrorCode` with its own `getUserFriendlyMessage()`.
2795
3339
  **Method:** `client.saveEftPayment(request)` · **Type:** `ThirdPartyEftPaymentReq`
2796
3340
 
2797
3341
 
2798
- Saves bank account details for premium payment. Call after Start Application, before Prepare Docs. Once saved, quote updates are blocked.
3342
+ Saves bank account details for premium payment — shared by **every product**. Call after Start Application and, for full-flow products, before Prepare Docs. Once saved, quote updates are blocked. Send `payLaterDate` to schedule the draft for a future date ([Pay Later](#pay-later)).
2799
3343
 
2800
3344
 
2801
3345
  ***
@@ -2808,8 +3352,26 @@ Saves bank account details for premium payment. Call after Start Application, be
2808
3352
  | `accountHolderName` | `string` | Yes | `Account holder name is required.` / `Account holder name must be 100 characters or fewer.` / `Account holder name may only contain letters, spaces, hyphens, and apostrophes.` |
2809
3353
  | `routingNumber` | `string` | Yes | `Routing number is required.` / `Routing number must be 9 digits.` |
2810
3354
  | `accountNumber` | `string` | Yes | `Account number is required.` / `Account number must be 4 to 17 digits.` |
3355
+ | `payLaterDate` | `string` (`yyyy-MM-dd`) | No | `Pay later is not available for this opportunity.` (`PayLaterNotAvailable`) / `PayLaterDate must be after today and within the pay later window for this opportunity.` (`InvalidPaymentScheduledDate`) |
3356
+
3357
+ > `accountHolderName` must be at most 100 characters **and** pass the name format rules — in practice about **35** characters: letters, spaces, hyphens, apostrophes, and `*`; no consecutive special characters; and it must end with a letter. A name that fails these rules, including one longer than about 35 characters, returns `Account holder name may only contain letters, spaces, hyphens, and apostrophes.`
3358
+
3359
+
3360
+ ***
3361
+
3362
+ ### Pay Later
3363
+
3364
+ Send `payLaterDate` to schedule the bank draft for a future date; omit it to draft immediately. There is no separate flag — sending the date is the opt-in.
3365
+
3366
+ - **Format:** `yyyy-MM-dd`, date only. Don't send a time or a UTC offset: an offset can shift the value to a different day before the date part is taken.
3367
+ - **"Today" is the current UTC date,** not your local date. In the US evening UTC is often already the next day, so a local "tomorrow" can be "today" in UTC — and be rejected. Compute the date in UTC.
3368
+ - **Earliest:** tomorrow (UTC). Today or earlier returns `InvalidPaymentScheduledDate`.
3369
+ - **Latest:** whichever comes first of the platform's pay later window — **30 days** after today (UTC) by default — and the applicant's next birthday. The birthday itself is allowed.
3370
+ - **On the applicant's birthday (UTC date)** no `payLaterDate` is accepted. Omit it to draft immediately, or retry the next day (UTC), when the full window applies again.
3371
+ - **`Time-Zone` header:** the SDK doesn't send one. If you add one through `InstaBrainConfig.headers`, it cannot widen the range — and when its date differs from the UTC date, dates beyond the window (30 days by default) after the header's date are rejected too.
3372
+ - **Availability:** when Pay Later is switched off on the platform, any `payLaterDate` returns `PayLaterNotAvailable`. Retry without it to draft immediately. The switch is environment-wide — despite the message wording ("…for this opportunity"), it is not specific to the opportunity.
2811
3373
 
2812
- > `accountHolderName` accepts **letters, spaces, hyphens, and apostrophes only** — max 100 characters. Digits and other punctuation are rejected.
3374
+ The SDK does not check the window itself: it depends on per-opportunity data and server settings. Handle the two error codes below instead.
2813
3375
 
2814
3376
 
2815
3377
  ***
@@ -2820,6 +3382,7 @@ Saves bank account details for premium payment. Call after Start Application, be
2820
3382
  2. **EFT and credit card are mutually exclusive per `opportunityId`.** A successful payment that already exists — a prior EFT save, or a card that has already been charged — returns `PaymentAlreadyMade`. After a successful EFT save, [`getCcPaymentIframeUrl()`](#get-credit-card-iframe-url) returns `EftPaymentAlreadyCompleted`.
2821
3383
  3. **No application-readiness gate here.** Unlike `getCcPaymentIframeUrl()`, this endpoint does not require Start Application to be fully complete at request validation — it only checks that the opportunity exists and that payment has not already completed. Still call it after Start Application in the integration flow.
2822
3384
  4. A successful save **satisfies the payment prerequisite for [`finalSubmit()`](#final-submit)** — no charge runs again at final submit, and neither `paymentNotMade` nor `LatestPaymentNotSuccessful` will be returned for payment reasons.
3385
+ 5. **Pay Later** is EFT only — see [Pay Later](#pay-later) for the allowed range.
2823
3386
 
2824
3387
 
2825
3388
  ***
@@ -2828,8 +3391,11 @@ Saves bank account details for premium payment. Call after Start Application, be
2828
3391
 
2829
3392
  | Code | When |
2830
3393
  |---|---|
2831
- | `InvalidRequestFormat` | Any field validation failure, or `opportunityId` does not exist — inspect `value.fields` |
3394
+ | `InvalidRequestFormat` | A format failure on `opportunityId`, `accountHolderName`, `routingNumber`, or `accountNumber`, or `opportunityId` does not exist — inspect `value.fields`. `payLaterDate` failures use the two codes below |
2832
3395
  | `PaymentAlreadyMade` | A successful payment already exists for this opportunity (prior EFT save, or a card already charged) |
3396
+ | `InvalidPaymentScheduledDate` | `payLaterDate` is outside the allowed range — see [Pay Later](#pay-later). Message under `value.fields.PayLaterDate` |
3397
+ | `PayLaterNotAvailable` | `payLaterDate` was sent while Pay Later is switched off on the platform. Retry without it. Message under `value.fields.PayLaterDate` |
3398
+ | `ErrorInSaveEftPaymentDetails` | The EFT details could not be saved |
2833
3399
 
2834
3400
  > A credit card that was only **captured** and not yet charged does not trigger `PaymentAlreadyMade` at request validation. Do not rely on that edge case — treat the two payment methods as mutually exclusive.
2835
3401
 
@@ -2838,7 +3404,18 @@ Saves bank account details for premium payment. Call after Start Application, be
2838
3404
 
2839
3405
  ### Response
2840
3406
 
2841
- `flagStatus: true` with `value: null` on success.
3407
+ `flagStatus: true` on success, with `value` holding a confirmation message and per-field validation results:
3408
+
3409
+ ```json
3410
+ {
3411
+ "message": "Account Details saved successfully!",
3412
+ "accountNameValidation": { "flagAnswerValidation": true, "answerValidationMessage": null },
3413
+ "accountNumberValidation": { "flagAnswerValidation": true, "answerValidationMessage": null },
3414
+ "routingNumberValidation": { "flagAnswerValidation": true, "answerValidationMessage": null }
3415
+ }
3416
+ ```
3417
+
3418
+ > `saveEftPayment()` is typed `Promise<boolean>` for backward compatibility, but at runtime it resolves to this `value` object. Treat any resolved value as success — failures throw.
2842
3419
 
2843
3420
 
2844
3421
  ***
@@ -2855,6 +3432,33 @@ await client.saveEftPayment({
2855
3432
  // After this point, quote updates are blocked
2856
3433
  ```
2857
3434
 
3435
+ **Pay Later** — draft on a future date, computed in UTC:
3436
+
3437
+ ```typescript
3438
+ import { APIErrorCode, APIValidationError } from '@instabrain-sdks/api-client';
3439
+
3440
+ // Earliest allowed date is tomorrow in UTC — 'yyyy-MM-dd'
3441
+ const tomorrowUtc = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
3442
+
3443
+ try {
3444
+ await client.saveEftPayment({
3445
+ opportunityId,
3446
+ accountHolderName: 'Jane Doe',
3447
+ routingNumber: '021000021',
3448
+ accountNumber: '123456789012',
3449
+ payLaterDate: tomorrowUtc
3450
+ });
3451
+ } catch (err) {
3452
+ if (err instanceof APIValidationError && err.isErrorType(APIErrorCode.PayLaterNotAvailable)) {
3453
+ // Pay Later is switched off — save again without payLaterDate to draft now
3454
+ } else if (err instanceof APIValidationError && err.isErrorType(APIErrorCode.InvalidPaymentScheduledDate)) {
3455
+ console.log(err.response?.value?.fields?.PayLaterDate); // outside the allowed range
3456
+ } else {
3457
+ throw err;
3458
+ }
3459
+ }
3460
+ ```
3461
+
2858
3462
  ---
2859
3463
 
2860
3464
  ## Prepare Docs & Get Delivery Channels
@@ -3593,7 +4197,9 @@ Some enum members remain in the package for backward compatibility but are **not
3593
4197
  | `InvalidRequestFormat` | `'InvalidRequestFormat'` | Any field validation failure — inspect `value.fields` |
3594
4198
  | `StateNotFound` | `'stateNotFound'` | State code not recognized |
3595
4199
  | `AgeNotFound` | `'AgeNotFound'` | Neither age nor date of birth supplied, or age could not be derived |
3596
- | `NotAvailableForState` | `'NotAvailableForState'` | Product not available in state |
4200
+ | `ProductNotAvailableForState` | `'ProductNotAvailableForState'` | **Request validation** — product has no carrier config for the state, or is flagged unavailable there. `value.fields.StateCode` |
4201
+ | `AgentNotLicensedForState` | `'AgentNotLicensedForState'` | **Request validation** — authenticated agent is not licensed in that state, or the agent could not be resolved. `value.fields.StateCode` |
4202
+ | `NotAvailableForState` | `'NotAvailableForState'` | **Post-validation eligibility** — product not available in state, determined after validation passed. `value: null` |
3597
4203
  | `QuoteNotEligibleForGivenConditions` | `'QuoteNotEligibleForGivenConditions'` | State/age/nicotine combo not eligible |
3598
4204
  | `CoverageNotAvailable` | `'CoverageNotAvailable'` | Face amount out of range |
3599
4205
  | `RiderNotAvailable` | `'RiderNotAvailable'` | Rider unavailable for product/state |
@@ -3602,6 +4208,16 @@ Some enum members remain in the package for backward compatibility but are **not
3602
4208
  | `OutsideBuildChart` | `'outsideBuildChart'` | Height & weight provided and outside carrier build chart |
3603
4209
  | `HeightNotValid` | `'HeightNotValid'` | `height.feet` / `height.inches` out of range (feet 1–8, inches 0–11) |
3604
4210
 
4211
+ > **`stateCode` is checked as a cascade, stopping at the first failure**, on every product's Get Quote:
4212
+ >
4213
+ > 1. required / recognized state → `InvalidRequestFormat`
4214
+ > 2. product available in that state → `ProductNotAvailableForState`
4215
+ > 3. agent licensed in that state → `AgentNotLicensedForState`
4216
+ >
4217
+ > Because it stops at the first failure, an agent-licensing problem is only visible once product availability passes — a state can fail both, and you will only see the first.
4218
+ >
4219
+ > **`ProductNotAvailableForState` and `NotAvailableForState` are different codes at different stages** and must not be collapsed. The first is request validation with the message under `value.fields.StateCode`; the second is post-validation eligibility with `value: null`. The cascade codes apply to **Get Quote only** — not start-application, update quote, or get-existing-quote.
4220
+
3605
4221
  **Which codes each product returns** — the rider codes are the main difference, so branch per product rather than assuming one shared list:
3606
4222
 
3607
4223
  | Product | Business codes returned as top-level `error` |
@@ -3624,6 +4240,7 @@ Some enum members remain in the package for backward compatibility but are **not
3624
4240
  | `AgentNotFound` | `'agentNotFound'` | All | Quote cannot be linked to agent account — verify credentials |
3625
4241
  | `InternalServerError` | `'internalServerError'` | All | Unexpected backend failure — retry; if persistent contact support |
3626
4242
  | `DataNotFound` | `'dataNotFound'` | IB Term, Pure Term | The quote referenced by `quoteResponseId` could not be found — create a new quote |
4243
+ | `PivotNotAvailable` | `'PivotNotAvailable'` | Pivot methods | The opportunity cannot be pivoted — not eligible, pricing produced no quote, or it was already converted once. Top-level with `value: null` — a business state, not a malformed request |
3627
4244
 
3628
4245
  **Three outcome shapes — do not conflate them.** Start Application distinguishes field validation, business failure, and knockout:
3629
4246
 
@@ -3642,7 +4259,10 @@ Some enum members remain in the package for backward compatibility but are **not
3642
4259
 
3643
4260
  | Code | String Value | Products | When |
3644
4261
  |---|---|---|---|
3645
- | `PaymentAlreadyMade` | `'PaymentAlreadyMade'` | ADB, GIGDB, Final Expense | `update*Quote()` or `saveEftPayment()` when a **successful** payment already exists — a prior EFT save, or a card already charged. A card that was only captured and not yet charged does not trigger this |
4262
+ | `PaymentAlreadyMade` | `'PaymentAlreadyMade'` | All (`saveEftPayment()`); ADB, GIGDB, Final Expense (`update*Quote()`) | `update*Quote()` or `saveEftPayment()` when a **successful** payment already exists — a prior EFT save, or a card already charged. A card that was only captured and not yet charged does not trigger this |
4263
+ | `InvalidPaymentScheduledDate` | `'InvalidPaymentScheduledDate'` | All | `saveEftPayment()` — `payLaterDate` is outside the allowed range: today (UTC) or earlier, beyond the pay later window (30 days by default), after the applicant's next birthday, or sent on the birthday (UTC). Message under `value.fields.PayLaterDate` — see [Pay Later](#pay-later) |
4264
+ | `PayLaterNotAvailable` | `'PayLaterNotAvailable'` | All | `saveEftPayment()` — `payLaterDate` was sent while Pay Later is switched off on the platform. Retry without it to draft immediately. Message under `value.fields.PayLaterDate` |
4265
+ | `ErrorInSaveEftPaymentDetails` | `'ErrorInSaveEftPaymentDetails'` | All | `saveEftPayment()` — the EFT details could not be saved |
3646
4266
  | `EftPaymentAlreadyCompleted` | `'EftPaymentAlreadyCompleted'` | ADB, GIGDB, Final Expense | `getCcPaymentIframeUrl()` after a successful EFT save — the two methods are mutually exclusive per opportunity |
3647
4267
  | `ApplicationNotReady` | `'ApplicationNotReady'` | ADB, GIGDB, Final Expense | `getCcPaymentIframeUrl()` or `prepareDocsAndGetDeliveryChannels()` before Start Application has completed successfully. **Retryable** — complete Start Application, then call again |
3648
4268
 
@@ -3697,12 +4317,10 @@ Not documented as active responses. Kept on `APIErrorCode` for older integration
3697
4317
  | `HeightNotValid` | `'HeightNotValid'` |
3698
4318
  | `DocumentsNotViewed` | `'DocumentsNotViewed'` |
3699
4319
  | `ThirdPartyQuoteError` | `'ThirdPartyQuoteError'` |
3700
- | `ErrorInSaveEftPaymentDetails` | `'ErrorInSaveEftPaymentDetails'` |
3701
4320
  | `InvalidBirthCountry` | `'InvalidBirthCountry'` |
3702
4321
  | `InvalidBirthState` | `'InvalidBirthState'` |
3703
4322
  | `InvalidResidenceState` | `'InvalidResidenceState'` |
3704
4323
  | `OneOfTheExistingCoveragesQuestionsNotFound` | `'OneOfTheExistingCoveragesQuestionsNotFound'` |
3705
- | `InvalidPaymentScheduledDate` | `'InvalidPaymentScheduledDate'` |
3706
4324
  | `InvalidQuoteParameters` | `'InvalidQuoteParameters'` |
3707
4325
  | `InvalidStateCode` | `'InvalidStateCode'` |
3708
4326
  | `InvalidAdbAgeRange` | `'InvalidAdbAgeRange'` |