@instabrain-sdks/api-client 2.4.0 → 2.6.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 (34) hide show
  1. package/LICENSE.md +31 -0
  2. package/README.md +820 -81
  3. package/dist/client/instabrain-client.d.ts +170 -9
  4. package/dist/client/instabrain-client.js +189 -8
  5. package/dist/services/application.service.d.ts +29 -2
  6. package/dist/services/application.service.js +29 -2
  7. package/dist/services/finalexpense.service.d.ts +23 -5
  8. package/dist/services/finalexpense.service.js +23 -5
  9. package/dist/services/gigdb.service.d.ts +25 -3
  10. package/dist/services/gigdb.service.js +25 -3
  11. package/dist/services/payment.service.d.ts +94 -0
  12. package/dist/services/payment.service.js +161 -0
  13. package/dist/services/pivot.service.d.ts +104 -0
  14. package/dist/services/pivot.service.js +116 -0
  15. package/dist/services/pureterm.service.d.ts +96 -10
  16. package/dist/services/pureterm.service.js +100 -8
  17. package/dist/services/secure-sign.service.d.ts +19 -3
  18. package/dist/services/secure-sign.service.js +19 -3
  19. package/dist/types/enums.d.ts +112 -3
  20. package/dist/types/enums.js +134 -4
  21. package/dist/types/errors.js +31 -2
  22. package/dist/types/gigdb.types.d.ts +32 -0
  23. package/dist/types/ibterm.types.d.ts +5 -2
  24. package/dist/types/index.d.ts +2 -0
  25. package/dist/types/index.js +2 -0
  26. package/dist/types/payment.types.d.ts +52 -0
  27. package/dist/types/payment.types.js +3 -0
  28. package/dist/types/pivot.types.d.ts +122 -0
  29. package/dist/types/pivot.types.js +2 -0
  30. package/dist/types/pureterm.types.d.ts +186 -31
  31. package/dist/utils/error-utils.d.ts +9 -1
  32. package/dist/utils/error-utils.js +18 -3
  33. package/dist/utils/http-client.js +11 -2
  34. package/package.json +9 -4
package/README.md CHANGED
@@ -8,7 +8,7 @@ TypeScript SDK for Node.js. All operations go through `InstaBrainClient` — req
8
8
 
9
9
  - **GIGDB & ADB** — full client flow: `get*Quote()` → `start*Application()` → `saveEftPayment()` → SecureSign methods → `finalSubmit()`.
10
10
  - **IB Term** — client flow ends at `startIBTermApplication()`; use returned `agentLink` / `applicantLink` / `eAppAgentLink` for the InstaBrain frontend.
11
- - **Pure Term** — pre-fill flow: `getPureTermQuote()` → `startApplication()`; use returned links for the InstaBrain frontend.
11
+ - **Pure Term** — pre-fill flow: `getPureTermQuote()` → `startPureTermApplication()`; use returned links for the InstaBrain frontend.
12
12
 
13
13
  ```typescript
14
14
  import { InstaBrainClient } from '@instabrain-sdks/api-client';
@@ -48,7 +48,9 @@ Credentials (`userId` and `accessToken`) are provisioned during onboarding.
48
48
  - [Get existing quote](#ib-term--get-existing-quote)
49
49
  7. [Pure Term](#pure-term)
50
50
  - [Integration flow](#integration-flow-3)
51
+ - [Rider lookup](#pure-term--rider-lookup)
51
52
  - [Get quote](#pure-term--get-quote)
53
+ - [Get existing quote](#pure-term--get-existing-quote)
52
54
  - [Start application](#pure-term--start-application)
53
55
  8. [Final Expense](#final-expense)
54
56
  - [Integration flow](#integration-flow-4)
@@ -57,7 +59,11 @@ Credentials (`userId` and `accessToken`) are provisioned during onboarding.
57
59
  - [Get existing quote](#final-expense--get-existing-quote)
58
60
  - [Update quote](#final-expense--update-quote)
59
61
  - [Underwriting status (async)](#final-expense--underwriting-status-async)
62
+ - [GIGDB pivot after a decline](#gigdb-pivot--after-a-final-expense-decline)
60
63
  9. [Shared methods — GIGDB, ADB & Final Expense](#shared-methods--gigdb-adb--final-expense)
64
+ - [Payment — EFT or credit card](#payment--eft-or-credit-card)
65
+ - [Get credit card iframe URL](#get-credit-card-iframe-url)
66
+ - [Credit card payment status](#credit-card-payment-status)
61
67
  - [Save EFT payment](#save-eft-payment)
62
68
  - [Prepare docs & get delivery channels](#prepare-docs--get-delivery-channels)
63
69
  - [Send PIN & get documents link](#send-pin--get-documents-link)
@@ -95,6 +101,8 @@ Credentials (`userId` and `accessToken`) are provisioned during onboarding.
95
101
 
96
102
  ## Installation
97
103
 
104
+ > **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.
105
+
98
106
  ```bash
99
107
  npm install @instabrain-sdks/api-client
100
108
  ```
@@ -191,9 +199,9 @@ await client.authenticate(userId, accessToken);
191
199
 
192
200
  | Field | Type | Required | Description | Validation Error |
193
201
  |---|---|---|---|---|
194
- | `faceAmount` | `number` | Yes | Coverage amount in dollars ($5,000–$25,000) | `Coverage amount (FaceAmount) is required.` |
202
+ | `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.` |
195
203
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
196
- | `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.` |
204
+ | `stateCode` | `string` | Yes | 2-letter US state code | `State code is required.` / `State code is not valid.` |
197
205
  | `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.` |
198
206
  | `dateOfBirth` | `string` (ISO 8601) | Yes* | Date of birth — derived age must be 50–85 | `Date of birth must be a valid date.` |
199
207
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -224,6 +232,8 @@ await client.authenticate(userId, accessToken);
224
232
  | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` for details |
225
233
  | `StateNotFound` | State code not recognized |
226
234
  | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
235
+ | `ProductNotAvailableForState` | Request validation — GIGDB has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
236
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
227
237
  | `NotAvailableForState` | GIGDB not available in the requested state |
228
238
  | `QuoteNotEligibleForGivenConditions` | State / age / smoker combination not eligible |
229
239
  | `CoverageNotAvailable` | Face amount outside allowed range for state / age / smoker |
@@ -778,9 +788,9 @@ No field-validation errors are returned for this method.
778
788
 
779
789
  | Field | Type | Required | Description | Validation Error |
780
790
  |---|---|---|---|---|
781
- | `faceAmount` | `number` | Yes | Coverage amount ($50,000–$300,000) | `Coverage amount (FaceAmount) is required.` |
791
+ | `faceAmount` | `number` | Yes | Coverage amount ($50,000–$300,000, in $1,000 increments; flat across ages 20–59) | `Coverage amount (FaceAmount) is required.` |
782
792
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
783
- | `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.` |
793
+ | `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.` |
784
794
  | `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.` |
785
795
  | `dateOfBirth` | `string` (ISO 8601) | Yes* | Derived age must be 20–59 | `Date of birth must be a valid date.` |
786
796
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -810,6 +820,8 @@ No field-validation errors are returned for this method.
810
820
  | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
811
821
  | `StateNotFound` | State code not recognized |
812
822
  | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
823
+ | `ProductNotAvailableForState` | Request validation — ADB has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
824
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
813
825
  | `NotAvailableForState` | ADB not available in the requested state |
814
826
  | `QuoteNotEligibleForGivenConditions` | State / age combination not eligible |
815
827
  | `CoverageNotAvailable` | Face amount outside allowed range |
@@ -1205,7 +1217,7 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1205
1217
  | `benefitPeriod` | `number` | Yes | Term: 10, 20, or 30 years (state/age/nicotine dependent) | `Benefit period is required.` |
1206
1218
  | `flagTobaccoUse` | `boolean` | No | Defaults to `false` when omitted | — |
1207
1219
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
1208
- | `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.` |
1220
+ | `stateCode` | `string` | Yes | 2-letter US state — do **not** send `zipCode` for IB Term | `State code is required.` / `State code is not valid.` |
1209
1221
  | `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.` |
1210
1222
  | `healthClass` | `HealthClass` | One of † | `"excellent"`, `"great"`, `"good"`, `"average"` (case-insensitive) | `Health class is invalid. Allowed values: excellent, great, good, average.` |
1211
1223
  | `height` | `ThirdPartyQuoteReqHeight \| null` | One of † | `feet` (1–8), `inches` (0–11) — required with `weightInLbs` | `Height or weight is invalid.` |
@@ -1263,6 +1275,8 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1263
1275
  | `AgeNotFound` | `null` | Neither age nor date of birth supplied, or age could not be derived |
1264
1276
  | `BenefitPeriodNotAvailable` | `fields` object present | `benefitPeriod` not allowed for state/age/nicotine |
1265
1277
  | `CoverageNotAvailable` | `fields` object present | `faceAmount` out of range for state/age/nicotine |
1278
+ | `ProductNotAvailableForState` | Request validation — IB Term has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
1279
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
1266
1280
  | `NotAvailableForState` | `null` | Product not available in this state |
1267
1281
  | `QuoteNotEligibleForGivenConditions` | `null` | State/age/nicotine combination not eligible |
1268
1282
  | `OutsideBuildChart` | `null` | Height/weight outside carrier build chart |
@@ -1644,27 +1658,108 @@ const { quoteResponseId, quoteAmount } = quoteResp.selectedQuote;
1644
1658
 
1645
1659
  ## Pure Term
1646
1660
 
1647
- **InstaBrain Pure Term** — simplified term life product.
1661
+ **InstaBrain Pure Term** — term life product.
1648
1662
 
1649
- This is a **pre-fill flow**: use `getPureTermQuote()` then `startApplication()`, then hand off via `agentLink`, `applicantLink`, and `eAppAgentLink`. Do **not** call `saveEftPayment()`, SecureSign methods, or `finalSubmit()` for Pure Term.
1663
+ This is a **pre-fill flow**: quote, start the application via the dedicated Pure Term endpoint, then hand off via `agentLink`, `applicantLink`, and `eAppAgentLink`. All remaining underwriting and signing happens inside the InstaBrain frontend — the same hand-off family as IB Term.
1650
1664
 
1651
1665
  - **Eligible ages:** 18–60
1652
1666
  - **Rating:** `rateClass`, `healthClass`, or `height` + `weightInLbs`
1653
- - **Term lengths:** 10, 20, or 30 years (`benefitPeriod`)
1667
+ - **Term lengths:** 10, 15, 20, or 30 years (`benefitPeriod`) — age and nicotine dependent
1668
+ - **Not available in:** WY, NY
1669
+ - **Dedicated controller:** start application posts to `ThirdPartyPureTermApplication` (not the generic `ThirdPartyStartApp`)
1670
+
1671
+ > **Do not** wire a Pure Term `opportunityId` into `finalSubmit()`, the SecureSign methods, or the credit-card iframe — the credit-card iframe is not supported for this product and returns `CcPaymentIframeNotSupportedForProduct`. Shared `saveEftPayment()` is allowed.
1672
+
1673
+ > **Pure Term follows the same Term SDK pattern as [IB Term](#ib-term)** — rider lookup → quote → start application → link hand-off, with an optional existing-quote fetch. Shared behavior, error models, business rules, and knockouts are the same; treat the IB Term sections as the reference and read the differences below as an overlay.
1674
+
1675
+ **Product differences from IB Term:**
1676
+
1677
+ | Topic | IB Term | Pure Term |
1678
+ |---|---|---|
1679
+ | `benefitPeriod` | 10 / 20 / 30 | 10 / **15** / 20 / 30 |
1680
+ | `rateClass` | Preferred Plus, Preferred, Standard, Standard Extra (`RateClass`) | The same four **plus Rated C and Rated D** (`PureTermRateClass`) |
1681
+ | Living benefits | Included | **Not offered** |
1682
+ | Identity checks | Quote / opportunity must be IB Term | Quote / opportunity must be Pure Term |
1683
+
1684
+ Coverage and benefit-period availability tables are Pure-Term-specific — see [Get Quote](#pure-term--get-quote).
1654
1685
 
1655
1686
  ---
1656
1687
 
1657
1688
  ## Integration flow
1658
1689
 
1659
1690
  ```
1660
- 1. [`getPureTermQuote()`](#pure-term--get-quote) Get quote → quoteResponseId
1661
- 2. [`startApplication()`](#pure-term--start-application) Start app → agentLink / applicantLink
1662
- ├── isDeclined = true → STOP
1691
+ 1. [`getPureTermRiderDetails()`](#pure-term--rider-lookup) (optional) Rider availability + codes
1692
+ └── flagProductNotAvailableForState = true → STOP (not sold in this state)
1693
+ 2. [`getPureTermQuote()`](#pure-term--get-quote) Get quote → quoteResponseId
1694
+ 3. [`startPureTermApplication()`](#pure-term--start-application) Start app → opportunityId + links
1695
+ ├── isDeclined = true → STOP (knockout)
1663
1696
  └── isQuoteChanged = true → re-present updated premium, then hand off via links
1664
1697
 
1698
+ [`getPureTermExistingQuote()`](#pure-term--get-existing-quote) (optional) Re-fetch the stored quote
1699
+
1665
1700
  → Direct agent or applicant to agentLink / applicantLink / eAppAgentLink
1666
1701
  All remaining steps complete inside the InstaBrain frontend.
1667
- No further InstaBrainClient methods for Pure Term.
1702
+ ```
1703
+
1704
+ ---
1705
+
1706
+ ## Pure Term — Rider Lookup
1707
+
1708
+ **Method:** `client.getPureTermRiderDetails(stateCode, age, flagNicotineUse)` · **Returns:** `PureTermRiderDetailsResp`
1709
+
1710
+ Optional pre-quote step. Filters the available Pure Term riders by state, age, and nicotine use so you can present the correct choices before quoting.
1711
+
1712
+
1713
+ ***
1714
+
1715
+ ### Request Fields
1716
+
1717
+ All three are sent as query-string parameters.
1718
+
1719
+ | Parameter | Type | Required | Description |
1720
+ |---|---|---|---|
1721
+ | `stateCode` | `string` | Yes | 2-letter US state code (e.g. `"TX"`) |
1722
+ | `age` | `number` | Yes | Integer, 18–60 inclusive |
1723
+ | `flagNicotineUse` | `boolean` | Yes | Must be sent explicitly as `true` or `false` — not optional |
1724
+
1725
+
1726
+ ***
1727
+
1728
+ ### Business Rules
1729
+
1730
+ 1. `flagProductNotAvailableForState: true` with an empty `riders` array is a **valid `200` response**, not an error — the SDK returns it as-is and does not throw. Pure Term is not sold in every state (e.g. WY, NY).
1731
+ 2. Use `riderCode` from the response as `riders[n].rider` in the Pure Term quote request.
1732
+ 3. Backend validation failures (invalid state, age out of range) surface through the SDK error model as usual.
1733
+
1734
+
1735
+ ***
1736
+
1737
+ ### Response
1738
+
1739
+ | Field | Type | Description |
1740
+ |---|---|---|
1741
+ | `flagProductNotAvailableForState` | `boolean` | `true` = product unavailable for this state/age/nicotine combination; `riders` is empty |
1742
+ | `riders` | `PureTermRider[]` | Available rider options |
1743
+ | `riders[].riderCode` | `string` | Pass as `riders[n].rider` on the quote |
1744
+ | `riders[].riderTitle` | `string` | Display title |
1745
+ | `riders[].riderDescription` | `string` | Display description |
1746
+
1747
+
1748
+ ***
1749
+
1750
+ ### Example
1751
+
1752
+ ```typescript
1753
+ const riderInfo = await client.getPureTermRiderDetails('TX', 35, false);
1754
+
1755
+ if (riderInfo.flagProductNotAvailableForState) {
1756
+ // Pure Term is not sold for this state/age/nicotine combination — stop here.
1757
+ return;
1758
+ }
1759
+
1760
+ for (const rider of riderInfo.riders) {
1761
+ console.log(rider.riderCode, '—', rider.riderTitle);
1762
+ }
1668
1763
  ```
1669
1764
 
1670
1765
  ---
@@ -1678,16 +1773,16 @@ This is a **pre-fill flow**: use `getPureTermQuote()` then `startApplication()`,
1678
1773
 
1679
1774
  ### Request Fields
1680
1775
 
1681
- Provide exactly one rating group (†) and exactly one age input (‡).
1776
+ Provide at least one rating group (†) and one age input (‡).
1682
1777
 
1683
1778
  | Field | Type | Required | Description | Validation Error |
1684
1779
  |---|---|---|---|---|
1685
- | `faceAmount` | `number` | Yes | Coverage amount — age-based limits apply | `Coverage amount (FaceAmount) is required.` |
1686
- | `benefitPeriod` | `number` | Yes | Term: 10, 20, or 30 years (state/age/tobacco dependent) | `Benefit period is required.` |
1780
+ | `faceAmount` | `number` | Yes | Coverage amount — age-based limits apply (see below) | `Coverage amount (FaceAmount) is required.` |
1781
+ | `benefitPeriod` | `number` | Yes | Term: 10, 15, 20, or 30 years (state/age/tobacco dependent) | `Benefit period is required.` |
1687
1782
  | `flagTobaccoUse` | `boolean` | No | Defaults to `false` when omitted | — |
1688
1783
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
1689
- | `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.` |
1690
- | `rateClass` | `RateClass` | One of † | `"Preferred Plus"`, `"Preferred"`, `"Standard"`, `"Standard Extra"` | `Either RateClass, HealthClass, or Height and WeightInLbs must be provided.` |
1784
+ | `stateCode` | `string` | Yes | 2-letter US state code. Send `stateCode` only — do **not** send `zipCode` | `State code is required.` / `State code is not valid.` |
1785
+ | `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.` |
1691
1786
  | `healthClass` | `HealthClass` | One of † | `"excellent"`, `"great"`, `"good"`, `"average"` (case-insensitive) | `Health class is invalid.` |
1692
1787
  | `height` | `ThirdPartyQuoteReqHeight \| null` | One of † | `feet` (1–8), `inches` (0–11) — required with `weightInLbs` | `Height or weight is invalid.` |
1693
1788
  | `weightInLbs` | `number \| null` | One of † | Paired with `height` | — |
@@ -1700,24 +1795,89 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1700
1795
  | `email` | `string` | No | Lead capture | `Please enter a valid email address.` |
1701
1796
  | `phoneNum` | `string` | No | 10 digits or E.164 — lead capture | `Phone number format is incorrect.` |
1702
1797
 
1703
- > **†** Supply exactly **one** rating group: `rateClass`, OR `healthClass`, OR both `height` and `weightInLbs`.
1798
+ > **†** Supply **at least one** rating group: `rateClass`, `healthClass`, or both `height` and `weightInLbs`. Sending more than one is accepted — the requirement is that at least one is present.
1704
1799
  > **‡** Provide `age` OR `dateOfBirth`. When both are sent, `dateOfBirth` takes priority.
1705
1800
 
1801
+ **Coverage limits by age** — `faceAmount` outside these ranges returns `CoverageNotAvailable`:
1802
+
1803
+ | Age | Allowed `faceAmount` |
1804
+ |---|---|
1805
+ | Up to 55 | $50,000 – $1,000,000 |
1806
+ | 56 | up to $900,000 |
1807
+ | 57 | up to $800,000 |
1808
+ | 58 | up to $700,000 |
1809
+ | 59 | up to $600,000 |
1810
+ | 60 | up to $500,000 |
1811
+
1812
+ **Benefit periods by age and nicotine use** — other values return `BenefitPeriodNotAvailable`:
1813
+
1814
+ | Age | Non-smoker | Smoker |
1815
+ |---|---|---|
1816
+ | 18–45 | 10, 15, 20, 30 | 10, 15, 20, 30 |
1817
+ | 46–50 | 10, 15, 20, 30 | 10, 15, 20 |
1818
+ | 51–60 | 10, 15, 20 | 10, 15, 20 |
1819
+
1820
+ > **15 is a Pure-Term-only term length.** IB Term offers 10 / 20 / 30 — do not reuse IB Term's benefit-period rules here.
1821
+
1822
+
1823
+ ***
1824
+
1825
+ ### Validation Rules
1826
+
1827
+ The server applies these in order. Only rules 9's two outcomes get dedicated top-level error codes; everything else surfaces as `InvalidRequestFormat` with PascalCase field keys under `value.fields` (at most one message per field).
1828
+
1829
+ 1. `benefitPeriod` is required.
1830
+ 2. `stateCode`, when present, must be a state where Pure Term is available.
1831
+ 3. At least one of `rateClass`, `healthClass`, or (`height` **and** `weightInLbs`) must be provided.
1832
+ 4. `rateClass`, when present, must be a valid **Pure Term** rate class — note Pure Term does **not** offer `Guaranteed`.
1833
+ 5. `healthClass`, when present, must be valid (case-insensitive).
1834
+ 6. `height` / `weightInLbs`, when present, must be a valid combination.
1835
+ 7. Age — from `dateOfBirth` when present, else `age` — must be 18–60 inclusive.
1836
+ 8. `riders`, when present, must be valid for Pure Term.
1837
+ 9. When `stateCode` and (`age` or `dateOfBirth`) are present: `benefitPeriod` is checked against carrier availability (`BenefitPeriodNotAvailable`) and `faceAmount` against coverage rules (`CoverageNotAvailable`).
1838
+
1706
1839
 
1707
1840
  ***
1708
1841
 
1709
1842
  ### Error Codes
1710
1843
 
1711
- | Code | When |
1712
- |---|---|
1713
- | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
1714
- | `BenefitPeriodNotAvailable` | `benefitPeriod` not allowed for state/age/nicotine combination |
1715
- | `CoverageNotAvailable` | `faceAmount` outside allowed range for state/age/nicotine |
1716
- | `NotAvailableForState` | Pure Term not available in the requested state |
1717
- | `QuoteNotEligibleForGivenConditions` | State/age/nicotine combination not eligible |
1718
- | `OutsideBuildChart` | Height/weight outside carrier build chart |
1719
- | `RiderNotAvailable` | Rider unavailable for product or state |
1720
- | `RiderFaceAmountNotValid` | Rider face amount outside allowed range |
1844
+ `getPureTermQuote()` throws `APIValidationError` when the server returns `flagStatus: false`. The code set matches [IB Term](#ib-term--get-quote):
1845
+
1846
+ | Code | `err.response.value` | When |
1847
+ |---|---|---|
1848
+ | `InvalidRequestFormat` | `fields` object present | Any field validation failure |
1849
+ | `StateNotFound` | `null` | State code not recognized |
1850
+ | `AgeNotFound` | `null` | Neither age nor date of birth supplied, or age could not be derived |
1851
+ | `BenefitPeriodNotAvailable` | `fields` object present | `benefitPeriod` not allowed for state/age/nicotine |
1852
+ | `CoverageNotAvailable` | `fields` object present | `faceAmount` out of range for state/age/nicotine |
1853
+ | `ProductNotAvailableForState` | Request validation — Pure Term has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
1854
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
1855
+ | `NotAvailableForState` | `null` | Product not available in this state |
1856
+ | `QuoteNotEligibleForGivenConditions` | `null` | State/age/nicotine combination not eligible |
1857
+ | `OutsideBuildChart` | `null` | Height/weight outside carrier build chart |
1858
+ | `RiderNotAvailable` | `null` | Rider not available for this product/state |
1859
+ | `RiderFaceAmountNotValid` | `null` | Rider face amount outside allowed range |
1860
+
1861
+ > **Two stages produce these.** Request validation issues dedicated top-level codes only for `BenefitPeriodNotAvailable` and `CoverageNotAvailable` — everything else at that stage, **including an invalid rate class**, arrives as `InvalidRequestFormat` with a PascalCase key under `value.fields`. Once validation passes, the request still runs through the shared quote-eligibility pipeline, which can return `NotAvailableForState`, `QuoteNotEligibleForGivenConditions`, `RiderNotAvailable`, `RiderFaceAmountNotValid`, or `OutsideBuildChart`. Do not assume those never occur for Pure Term.
1862
+
1863
+ ```typescript
1864
+ import { APIValidationError, APIErrorCode } from '@instabrain-sdks/api-client';
1865
+
1866
+ try {
1867
+ await client.getPureTermQuote(request);
1868
+ } catch (err) {
1869
+ if (err instanceof APIValidationError) {
1870
+ if (err.isErrorType(APIErrorCode.BenefitPeriodNotAvailable)) {
1871
+ // Offer a different term length for this age / state / nicotine combination
1872
+ } else if (err.isErrorType(APIErrorCode.CoverageNotAvailable)) {
1873
+ // Offer a face amount inside the age band
1874
+ } else {
1875
+ // InvalidRequestFormat — per-field messages
1876
+ console.log(err.response?.value?.fields);
1877
+ }
1878
+ }
1879
+ }
1880
+ ```
1721
1881
 
1722
1882
 
1723
1883
  ***
@@ -1726,12 +1886,16 @@ Provide exactly one rating group (†) and exactly one age input (‡).
1726
1886
 
1727
1887
  | Field | Type | Description |
1728
1888
  |---|---|---|
1729
- | `productName` | `string` | `"InstaPureTerm"` |
1730
- | `selectedQuote.quoteResponseId` | `string` | Pass as `quoteResponseId` in `startApplication()` |
1889
+ | `productName` | `string` | `"InstaBrain Pure Term"` |
1890
+ | `selectedQuote.quoteResponseId` | `string` | Pass as `quoteResponseId` in `startPureTermApplication()` |
1731
1891
  | `selectedQuote.quoteAmount` | `number` | Premium at requested payment frequency |
1892
+ | `selectedQuote.premiumSaveWhenSelectingAnnual` | `number \| null` | Annual-billing savings vs monthly; `null` when already `Annually` |
1893
+ | `selectedQuote.maxQuoteAmount` | `number \| null` | Upper premium bound for the quoted profile |
1894
+ | `selectedQuote.minQuoteAmount` | `number \| null` | Lower premium bound for the quoted profile |
1732
1895
  | `selectedQuote.faceAmount` | `number` | Coverage amount |
1733
1896
  | `selectedQuote.benefitPeriod` | `number \| null` | Term length in years |
1734
1897
  | `selectedQuote.paymentFrequency` | `string \| null` | `"Monthly"` or `"Annually"` |
1898
+ | `selectedQuote.selectedRiders` | `object[]` | Riders on the quote — `rider`, `riderFaceAmount`, `riderQuoteAmount`. Subtract every `riderQuoteAmount` from `quoteAmount` to derive the base premium |
1735
1899
 
1736
1900
 
1737
1901
  ***
@@ -1757,12 +1921,60 @@ const { quoteResponseId, quoteAmount } = quoteResp.selectedQuote;
1757
1921
 
1758
1922
  ---
1759
1923
 
1924
+ ## Pure Term — Get Existing Quote
1925
+
1926
+ **Method:** `client.getPureTermExistingQuote(opportunityId)` · **Returns:** `ThirdPartyQuoteResp`
1927
+
1928
+ Re-fetches a previously generated Pure Term quote by its opportunity ID, without re-quoting. Use it to resume or review an in-flight opportunity — for example when `isQuoteChanged` came back `true` from start application.
1929
+
1930
+
1931
+ ***
1932
+
1933
+ ### Request Fields
1934
+
1935
+ | Parameter | Type | Required | Description |
1936
+ |---|---|---|---|
1937
+ | `opportunityId` | `string` | Yes | Valid UUID, passed as a **query-string** parameter (not a body field) |
1938
+
1939
+
1940
+ ***
1941
+
1942
+ ### Business Rules
1943
+
1944
+ 1. The response reuses the same shape as `getPureTermQuote()` — `productName` is `"InstaBrain Pure Term"`.
1945
+ 2. Unlike rider-lookup product-unavailability, a not-found result here **is** an error and is thrown through the SDK error model — it is not a valid business state.
1946
+
1947
+
1948
+ ***
1949
+
1950
+ ### Error Codes
1951
+
1952
+ | Code | When |
1953
+ |---|---|
1954
+ | `InvalidRequestFormat` | Missing, empty, or non-GUID `opportunityId` (`OpportunityId is required.` / `OpportunityId does not exist.`), or the opportunity belongs to another product (`OpportunityId does not match selected product.`) |
1955
+ | `QuoteNotFound` | The opportunity exists but has no stored quote (top-level, `value: null`) |
1956
+
1957
+ > A valid but unauthorized `opportunityId` returns HTTP `403`.
1958
+
1959
+
1960
+ ***
1961
+
1962
+ ### Example
1963
+
1964
+ ```typescript
1965
+ const existing = await client.getPureTermExistingQuote(opportunityId);
1966
+ console.log(existing.selectedQuote.quoteAmount, existing.selectedQuote.benefitPeriod);
1967
+ ```
1968
+
1969
+ ---
1970
+
1760
1971
  ## Pure Term — Start Application
1761
1972
 
1762
- **Method:** `client.startApplication(request)` · **Type:** `ThirdPartyStartApplicationReq`
1973
+ **Method:** `client.startPureTermApplication(request)` · **Type:** `PureTermStartApplicationReq`
1763
1974
 
1975
+ 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.
1764
1976
 
1765
- This is the **generic** start-application endpoint shared across products that use the pre-fill link hand-off flow. For Pure Term, call this after `getPureTermQuote()` using the `quoteResponseId` from the quote response.
1977
+ 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.
1766
1978
 
1767
1979
 
1768
1980
  ***
@@ -1771,12 +1983,10 @@ This is the **generic** start-application endpoint shared across products that u
1771
1983
 
1772
1984
  | Field | Type | Required | Description |
1773
1985
  |---|---|---|---|
1774
- | `quoteResponseId` | `string` | Yes | UUID from `getPureTermQuote()` |
1775
- | `firstName` | `string \| null` | Yes | Applicant first name |
1776
- | `lastName` | `string \| null` | Yes | Applicant last name |
1777
- | `email` | `string \| null` | Yes | Applicant email address |
1778
- | `phoneNumber` | `string \| null` | Yes | Applicant phone number — 10-digit local or E.164 |
1779
- | `proCode` | `string \| null` | No | Product variant code. When omitted the base product is started. Contact InstaBrain support for the correct code if a specific variant is required. |
1986
+ | `quoteResponseId` | `string` | Yes | UUID from `getPureTermQuote()` — must belong to the **Pure Term** product |
1987
+ | *(all other fields)* | — | — | Identical to [IB Term — Start Application](#ib-term--start-application) |
1988
+
1989
+ > `proCode` does **not** apply here — it belongs to the generic `startApplication()` only.
1780
1990
 
1781
1991
 
1782
1992
  ***
@@ -1784,14 +1994,43 @@ This is the **generic** start-application endpoint shared across products that u
1784
1994
  ### Business Rules
1785
1995
 
1786
1996
  1. `isDeclined: true` is a valid success response (knockout) — the SDK does **not** throw.
1787
- 2. When `isQuoteChanged = true`, the carrier adjusted the premium. Re-present the updated premium to the applicant before directing them to the link.
1997
+ 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.
1998
+ 3. `quoteResponseId` must belong to Pure Term, otherwise: `QuoteResponseId does not exist or does not belong to the requested product.`
1999
+ 4. `address.state` (when sent) must match the quote state — a mismatch returns `StateMismatchIdentified`.
2000
+ 5. `childRiderInfo` is required **only** when the Dependent Child Rider was selected on the originating quote, and must **not** be sent otherwise — sending it without the rider fails with `Child rider was not included in the quote. Cannot add child rider details.`
2001
+ 6. `tobaccoNicotineUsage.cigarUsagePerYear` is required only when `productTypesUsed` is **exactly** `['cigars']`. When cigars are selected alongside other product types it is not required.
2002
+ 7. `physicianDetails.stateCode` rejects both `"Outside Of The USA"` and `"OutsideUSA"`.
2003
+ 8. Pure Term does **not** run the `ApplicationLimitReached` duplicate SSN/email/phone check (that applies to GIGDB, ADB, and Final Expense).
2004
+ 9. Validation returns at most one message per field; `value.fields` keys are PascalCase and may be nested (e.g. `ChildRiderInfo.IsAnyChildTakingMedication`).
1788
2005
 
1789
2006
 
1790
2007
  ***
1791
2008
 
1792
2009
  ### Knockout Rules
1793
2010
 
1794
- Returns `isDeclined: true` on a successful response — the SDK does **not** throw. Check the field explicitly; do not treat it as an exception.
2011
+ Any of the following returns HTTP `200` with `isDeclined: true` — the SDK does **not** throw. Check the field explicitly.
2012
+
2013
+ - `isUsCitizenOrIsPermanentResident = false`
2014
+ - `isPayerAlsoOwnerAndInsured = false`
2015
+ - `isHoldingValidDriverLicense = false`
2016
+ - `areListedConditionsNotApplicable = false`
2017
+ - Any of the four `childRiderInfo` knockout questions = `true`
2018
+ - Height / weight outside the carrier's allowed limits
2019
+
2020
+
2021
+ ***
2022
+
2023
+ ### Error Codes
2024
+
2025
+ Start Application is one shared service across both Term products, so the code set matches [IB Term](#ib-term--start-application). Business failures return HTTP `400` with `value: null`.
2026
+
2027
+ | Code | `err.response.value` | When |
2028
+ |---|---|---|
2029
+ | `InvalidRequestFormat` | `fields` object present | Any field validation failure |
2030
+ | `StateMismatchIdentified` | `null` | Quote state ≠ `address.state` |
2031
+ | `AgentNotFound` | `null` | Quote cannot be linked to the agent account — verify credentials |
2032
+ | `DataNotFound` | `null` | The quote response could not be found for the supplied `quoteResponseId` |
2033
+ | `InternalServerError` | `null` | Unexpected backend failure — retry; contact support if persistent |
1795
2034
 
1796
2035
 
1797
2036
  ***
@@ -1800,14 +2039,14 @@ Returns `isDeclined: true` on a successful response — the SDK does **not** thr
1800
2039
 
1801
2040
  | Field | Type | Description |
1802
2041
  |---|---|---|
1803
- | `opportunityId` | `string` | All-zero UUID when declined before opportunity creation |
2042
+ | `opportunityId` | `string` | All-zero UUID when declined before opportunity creation — never `null` |
1804
2043
  | `isDeclined` | `boolean` | `true` = knockout; stop the flow |
1805
2044
  | `isQuoteChanged` | `boolean` | `true` = carrier adjusted premium; re-present before handoff |
1806
2045
  | `agentLink` | `string \| null` | Agent Conversational UI |
1807
2046
  | `applicantLink` | `string \| null` | Applicant Conversational UI |
1808
2047
  | `eAppAgentLink` | `string \| null` | Agent E-App |
1809
2048
 
1810
- > 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.
2049
+ > 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.
1811
2050
 
1812
2051
 
1813
2052
  ***
@@ -1815,19 +2054,55 @@ Returns `isDeclined: true` on a successful response — the SDK does **not** thr
1815
2054
  ### Example
1816
2055
 
1817
2056
  ```typescript
1818
- const appResp = await client.startApplication({
2057
+ import {
2058
+ Gender,
2059
+ BeneficiaryType,
2060
+ BeneficiaryRelationship,
2061
+ TobaccoNicotineLastUsedPeriod
2062
+ } from '@instabrain-sdks/api-client';
2063
+
2064
+ const appResp = await client.startPureTermApplication({
1819
2065
  quoteResponseId,
1820
2066
  firstName: 'Jane',
1821
2067
  lastName: 'Doe',
1822
2068
  email: 'jane.doe@example.com',
1823
2069
  phoneNumber: '5551234567',
1824
- // proCode: 'VARIANT_CODE' // omit to start the base product
2070
+ isUsCitizenOrIsPermanentResident: true,
2071
+ isPayerAlsoOwnerAndInsured: true,
2072
+ dateOfBirth: '1989-03-15',
2073
+ socialSecurityNumber: '123456789',
2074
+ address: { addressLine1: '123 Main St', city: 'Austin', state: 'TX', zipcode: '78701' },
2075
+ birthJurisdiction: { country: 'US', state: 'TX' },
2076
+ height: { feet: 5, inches: 6 },
2077
+ weight: 140,
2078
+ isHoldingValidDriverLicense: true,
2079
+ driverLicenseState: 'TX',
2080
+ driverLicenseNumber: 'D12345678',
2081
+ hasPrimaryCarePhysician: false,
2082
+ physicianDetails: null,
2083
+ tobaccoNicotineUsage: {
2084
+ lastUsedPeriod: TobaccoNicotineLastUsedPeriod.Never,
2085
+ lastTimeUsed: null,
2086
+ productTypesUsed: null
2087
+ },
2088
+ areListedConditionsNotApplicable: true,
2089
+ hasExistingCoverage: false,
2090
+ beneficiaryDetails: {
2091
+ beneficiaryType: BeneficiaryType.Person,
2092
+ beneficiaryPerson: {
2093
+ firstName: 'John',
2094
+ lastName: 'Doe',
2095
+ relationship: BeneficiaryRelationship.Spouse
2096
+ }
2097
+ }
2098
+ // childRiderInfo — send ONLY when the Dependent Child Rider is on the quote
1825
2099
  });
1826
2100
 
1827
2101
  if (appResp.isDeclined) {
1828
2102
  return;
1829
2103
  }
1830
2104
  if (appResp.isQuoteChanged) {
2105
+ const updated = await client.getPureTermExistingQuote(appResp.opportunityId);
1831
2106
  // Re-present updated premium before directing to link
1832
2107
  }
1833
2108
  // Hand off to InstaBrain frontend
@@ -1854,7 +2129,9 @@ This is a **full-flow product** like GIGDB and ADB: quote → start application
1854
2129
  ```
1855
2130
  1. getFinalExpenseQuote() Get quote → quoteResponseId
1856
2131
  2. startFinalExpenseApplication() Start app → opportunityId
1857
- └── isDeclined = true → STOP (knockout)
2132
+ ├── isDeclined = true + all-zero opportunityId → STOP (no application, no pivot)
2133
+ └── isDeclined = true + real opportunityId → STOP the FE flow, but keep the id:
2134
+ it is the input to the GIGDB pivot (step 7)
1858
2135
  3. saveEftPayment() Save bank details (shared method)
1859
2136
  4. Secure Sign flow prepareDocs → sendPin → verifyPin (shared)
1860
2137
  5. finalSubmit() → applicationStatus: 'InProgress' (async!)
@@ -1864,6 +2141,12 @@ This is a **full-flow product** like GIGDB and ADB: quote → start application
1864
2141
  └── (timeout) → resume manually with pingFinalExpenseUnderwritingStatus()
1865
2142
  ```
1866
2143
 
2144
+ ```
2145
+ 7. getPivotQuotes() Only after a decline with a real opportunityId
2146
+ 8. customizePivotQuote() Optional — re-price coverage / frequency
2147
+ 9. convertPivotToApplication() → NEW opportunityId on the alternative product
2148
+ ```
2149
+
1867
2150
  Optional: `getFinalExpenseExistingQuote(opportunityId)` to re-fetch a quote, and `updateFinalExpenseQuote()` to change `faceAmount` / `paymentFreq` before payment.
1868
2151
 
1869
2152
  ---
@@ -1880,9 +2163,9 @@ The response `selectedQuote.quoteResponseId` is the token for `startFinalExpense
1880
2163
 
1881
2164
  | Field | Type | Required | Description | Validation Error |
1882
2165
  |---|---|---|---|---|
1883
- | `faceAmount` | `number` | Yes | Coverage amount ($5,000–$50,000) | `Coverage amount (FaceAmount) is required.` |
2166
+ | `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.` |
1884
2167
  | `gender` | `Gender` | Yes | `Gender.Male`, `Gender.Female` | `Gender is required.` / `Invalid gender.` |
1885
- | `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.` |
2168
+ | `stateCode` | `string` | Yes | 2-letter US state code; product must be available there | `State code is required.` / `State code is not valid.` |
1886
2169
  | `age` | `number` | Yes‡ | 50–85 | `Either age or date of birth must be provided.` / `Age must be between 50 and 85.` |
1887
2170
  | `dateOfBirth` | `string` (ISO 8601) | Yes‡ | Wins over `age` when both provided; derived age 50–85 | `Date of birth must be a valid date.` |
1888
2171
  | `paymentFreq` | `PaymentFrequency` | Yes | `"Monthly"` or `"Annually"` | `Payment frequency is required.` / `Invalid payment frequency.` |
@@ -1896,6 +2179,27 @@ The response `selectedQuote.quoteResponseId` is the token for `startFinalExpense
1896
2179
 
1897
2180
  > **‡** Provide `age` OR `dateOfBirth`. When both are sent, `dateOfBirth` takes priority.
1898
2181
 
2182
+
2183
+ ***
2184
+
2185
+ ### Error Codes
2186
+
2187
+ | Code | When |
2188
+ |---|---|
2189
+ | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
2190
+ | `StateNotFound` | State code not recognized |
2191
+ | `AgeNotFound` | Neither age nor date of birth supplied, or age could not be derived |
2192
+ | `HeightNotValid` | `height.feet` / `height.inches` out of range |
2193
+ | `ProductNotAvailableForState` | Request validation — Final Expense has no carrier configuration for that state, or is flagged unavailable there. Message under `value.fields.StateCode` |
2194
+ | `AgentNotLicensedForState` | Request validation — the authenticated agent is not licensed in that state. Message under `value.fields.StateCode` |
2195
+ | `NotAvailableForState` | Post-validation eligibility — product not available in the state (`value: null`) |
2196
+ | `QuoteNotEligibleForGivenConditions` | State / age / nicotine combination not eligible |
2197
+ | `CoverageNotAvailable` | Face amount outside the allowed range for the age band |
2198
+ | `BenefitPeriodNotAvailable` | Benefit period not allowed for state / age / nicotine |
2199
+
2200
+ > `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`.
2201
+
2202
+
1899
2203
  ***
1900
2204
 
1901
2205
  ### Response
@@ -2040,12 +2344,20 @@ All six fields are required when `includeSecondaryAddressee = true`. When `inclu
2040
2344
 
2041
2345
  ### Knockout summary — returns `isDeclined: true` (not thrown)
2042
2346
 
2347
+ A decline alone no longer tells you whether an application exists. **Branch on `isDeclined` *and* on whether `opportunityId` is all-zero.**
2348
+
2349
+ **All-zero `opportunityId`** — these hard stops fire before an application is created, so there is nothing to pivot from:
2350
+
2043
2351
  - `isPayerAlsoOwnerAndInsured === false`
2044
2352
  - `isUsCitizen === false` AND `isLegalUsResident === false`
2045
2353
  - `isHoldingValidDriverLicense === false`
2354
+ - Height/weight outside the Final Expense build chart
2355
+
2356
+ **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).
2357
+
2046
2358
  - Any of the 13 health-prequalification booleans `=== true`
2047
2359
  - Respiratory decline rules above
2048
- - Height/weight outside the Final Expense build chart (decline occurs after opportunity creation — `opportunityId` is a real GUID)
2360
+ - Later underwriting declines
2049
2361
 
2050
2362
  ***
2051
2363
 
@@ -2072,8 +2384,8 @@ All six fields are required when `includeSecondaryAddressee = true`. When `inclu
2072
2384
 
2073
2385
  | Field | Type | Description |
2074
2386
  |---|---|---|
2075
- | `opportunityId` | `string` | All-zero GUID when declined before opportunity creation; real GUID otherwise |
2076
- | `isDeclined` | `boolean` | `true` = knockout / underwriting decline; stop the flow |
2387
+ | `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 |
2388
+ | `isDeclined` | `boolean` | `true` = knockout / underwriting decline; stop the Final Expense flow. Check `opportunityId` before giving up — non-zero means a pivot is available |
2077
2389
  | `isQuoteChanged` | `boolean` | `true` = tobacco flag or DOB triggered a requote; re-present premium |
2078
2390
 
2079
2391
  ***
@@ -2377,12 +2689,335 @@ if (submit.applicationStatus === 'InProgress') {
2377
2689
 
2378
2690
  ---
2379
2691
 
2692
+ ## GIGDB Pivot — after a Final Expense decline
2693
+
2694
+ 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.
2695
+
2696
+ The pivot is not a product of its own — all three methods key off the **declined Final Expense `opportunityId`**.
2697
+
2698
+ ```
2699
+ 1. getPivotQuotes(opportunityId) Alternative quote options
2700
+ 2. customizePivotQuote(request) Optional — re-price coverage / frequency
2701
+ 3. convertPivotToApplication(request) Creates the application → NEW opportunityId
2702
+ 4. getExistingGigdbQuote(newId) Read the current premium
2703
+ 5. … continue the alternative product's normal lifecycle
2704
+ ```
2705
+
2706
+ **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).
2707
+
2708
+ ***
2709
+
2710
+ ### Get Pivot Quotes
2711
+
2712
+ **Method:** `client.getPivotQuotes(opportunityId)` · **Endpoint:** `GET /api/ThirdPartyPivot/get-pivot-quotes`
2713
+
2714
+ Calling this repeatedly for the same opportunity is safe.
2715
+
2716
+ **Response:**
2717
+
2718
+ | Field | Type | Description |
2719
+ |---|---|---|
2720
+ | `pivotReason` | `string` | Why the pivot was offered, e.g. `"ApplicationDeclineOrNotEligible"`. Display / log only — do not branch business logic on it |
2721
+ | `quotes` | `PivotQuote[]` | The available alternative-product quotes |
2722
+
2723
+ **`PivotQuote`:**
2724
+
2725
+ | Field | Type | Description |
2726
+ |---|---|---|
2727
+ | `pivotProductCode` | `string` | **Persist this.** Required by both `customizePivotQuote()` and `convertPivotToApplication()`. Use the value the API returned (e.g. `"InstaGIGDB"`) — never construct one |
2728
+ | `productTitle` | `string` | Display title, e.g. `"InstaBrain Guaranteed Issue"` |
2729
+ | `quoteAmount` | `number` | Total premium at the requested payment frequency |
2730
+ | `coverageAmount` | `number` | Coverage in dollars |
2731
+ | `paymentFrequency` | `PaymentFrequency` | Payment frequency (Monthly or Annually) |
2732
+ | `termLength` | `number \| null` | Term in years, or `null` for whole-life products such as GIGDB |
2733
+ | `riders` | `Array<{ riderValue: string; riderLabel: string \| null }>` | Riders included in the quote; empty array when none apply |
2734
+
2735
+ **Error Codes:**
2736
+
2737
+ | Code | HTTP | When |
2738
+ |---|---|---|
2739
+ | `InvalidRequestFormat` | `400` | Missing / malformed / unknown `opportunityId`, or a source product that does not support pivot — inspect `value.fields` |
2740
+ | `PivotNotAvailable` | `400` | The opportunity cannot be pivoted. Top-level, `value: null` — a business state, not a bad request |
2741
+ | — | `403` | `opportunityId` is not authorized for this token. No body |
2742
+
2743
+ **Example:**
2744
+
2745
+ ```typescript
2746
+ const appResp = await client.startFinalExpenseApplication(request);
2747
+
2748
+ const ALL_ZERO = '00000000-0000-0000-0000-000000000000';
2749
+ if (appResp.isDeclined) {
2750
+ if (appResp.opportunityId === ALL_ZERO) {
2751
+ // No application was created — nothing to pivot from.
2752
+ return;
2753
+ }
2754
+
2755
+ const pivot = await client.getPivotQuotes(appResp.opportunityId);
2756
+ console.log(pivot.pivotReason); // 'ApplicationDeclineOrNotEligible'
2757
+ const offer = pivot.quotes[0];
2758
+ console.log(offer.productTitle, offer.quoteAmount, offer.coverageAmount);
2759
+
2760
+ // Persist BOTH for the next two calls.
2761
+ const { opportunityId } = appResp;
2762
+ const { pivotProductCode } = offer;
2763
+ }
2764
+ ```
2765
+
2766
+ ***
2767
+
2768
+ ### Customize Pivot Quote
2769
+
2770
+ **Method:** `client.customizePivotQuote(request)` · **Endpoint:** `POST /api/ThirdPartyPivot/customize-pivot-quote`
2771
+
2772
+ 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[]`.
2773
+
2774
+ This does **not** persist the choice: `convertPivotToApplication()` still requires `faceAmount` and `paymentFreq` to be sent explicitly.
2775
+
2776
+ **Request Fields:**
2777
+
2778
+ | Field | Type | Required | Description |
2779
+ |---|---|---|---|
2780
+ | `opportunityId` | `string` | Yes | The declined Final Expense opportunity |
2781
+ | `pivotProductCode` | `string` | Yes | Value from `getPivotQuotes()` |
2782
+ | `faceAmount` | `number` | Yes | Desired coverage in dollars. GIGDB: $5,000–$25,000 in $1,000 increments |
2783
+ | `paymentFreq` | `PaymentFrequency` | Yes | `Monthly` or `Annually` only |
2784
+
2785
+ **Error Codes:**
2786
+
2787
+ | Code | HTTP | When |
2788
+ |---|---|---|
2789
+ | `InvalidRequestFormat` | `400` | Missing / malformed body fields, unknown `opportunityId`, or an invalid `pivotProductCode` |
2790
+ | `CoverageNotAvailable` | `400` | `faceAmount` outside the alternative product's range or off its required increment. Top-level, `value: null` |
2791
+ | `PivotNotAvailable` | `400` | The opportunity cannot be pivoted, or pricing could not produce a quote |
2792
+ | — | `403` | `opportunityId` not authorized for this token |
2793
+
2794
+ **Example:**
2795
+
2796
+ ```typescript
2797
+ const repriced = await client.customizePivotQuote({
2798
+ opportunityId,
2799
+ pivotProductCode,
2800
+ faceAmount: 25000,
2801
+ paymentFreq: PaymentFrequency.Monthly,
2802
+ });
2803
+
2804
+ console.log(repriced.quoteAmount); // 52.25
2805
+ console.log(repriced.coverageAmount); // 25000
2806
+ ```
2807
+
2808
+ ***
2809
+
2810
+ ### Convert Pivot to Application
2811
+
2812
+ **Method:** `client.convertPivotToApplication(request)` · **Endpoint:** `POST /api/ThirdPartyPivot/convert-pivot-to-application`
2813
+
2814
+ Call only once the applicant has confirmed the coverage amount and payment frequency they want.
2815
+
2816
+ **Request Fields:**
2817
+
2818
+ | Field | Type | Required | Description |
2819
+ |---|---|---|---|
2820
+ | `opportunityId` | `string` | Yes | The declined Final Expense opportunity |
2821
+ | `pivotProductCode` | `string` | Yes | Value from `getPivotQuotes()` |
2822
+ | `faceAmount` | `number` | Yes | Confirmed coverage. **Required every call** — not carried over from a prior `customizePivotQuote()` |
2823
+ | `paymentFreq` | `PaymentFrequency` | Yes | Confirmed billing frequency. Required every call |
2824
+
2825
+ **Response:**
2826
+
2827
+ | Field | Type | Description |
2828
+ |---|---|---|
2829
+ | `opportunityId` | `string` | **The NEW opportunity**, on the alternative product. Persist it — it replaces the Final Expense id for every subsequent call |
2830
+ | `productCode` | `string` | Which product the new opportunity belongs to, e.g. `"InstaGIGDB"` |
2831
+
2832
+ **Business Rules:**
2833
+
2834
+ - The response carries **no premium by design**. Call the alternative product's get-existing-quote with the new `opportunityId` to read the current amount.
2835
+ - **Do not retry after a successful conversion** — a second attempt on the same opportunity returns `PivotNotAvailable`.
2836
+ - The Final Expense `opportunityId` is finished at this point. Everything that follows — quote, payment, signing, final submit — uses the new one.
2837
+
2838
+ **Error Codes:**
2839
+
2840
+ | Code | HTTP | When |
2841
+ |---|---|---|
2842
+ | `InvalidRequestFormat` | `400` | Missing / malformed body fields, unknown `opportunityId` (`OpportunityId does not exist.`), unsupported product, or an invalid `pivotProductCode` |
2843
+ | `CoverageNotAvailable` | `400` | `faceAmount` outside range or off-increment |
2844
+ | `PivotNotAvailable` | `400` | No longer fit to pivot — e.g. already converted |
2845
+ | — | `403` | `opportunityId` not authorized for this token |
2846
+
2847
+ > 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`.
2848
+
2849
+ **Example — full pivot flow:**
2850
+
2851
+ ```typescript
2852
+ const converted = await client.convertPivotToApplication({
2853
+ opportunityId, // the DECLINED Final Expense id
2854
+ pivotProductCode,
2855
+ faceAmount: 25000,
2856
+ paymentFreq: PaymentFrequency.Monthly,
2857
+ });
2858
+
2859
+ console.log(converted.productCode); // 'InstaGIGDB'
2860
+ const gigdbOpportunityId = converted.opportunityId; // NEW id — persist it
2861
+
2862
+ // No premium in the convert response — read it from the new product.
2863
+ const quote = await client.getExistingGigdbQuote(gigdbOpportunityId);
2864
+ console.log(quote.selectedQuote.quoteAmount);
2865
+
2866
+ // Continue the GIGDB lifecycle with the new id.
2867
+ await client.saveEftPayment({ opportunityId: gigdbOpportunityId, /* … */ } as any);
2868
+ ```
2869
+
2870
+ ---
2871
+
2380
2872
  ## Shared methods — GIGDB, ADB & Final Expense
2381
2873
 
2382
2874
  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.
2383
2875
 
2384
2876
  ---
2385
2877
 
2878
+ ## Payment — EFT or Credit Card
2879
+
2880
+ The payment step sits between Start Application and Prepare Docs, and offers **two mutually exclusive options** for a given `opportunityId`:
2881
+
2882
+ ```
2883
+ Start Application
2884
+ → Payment — choose exactly ONE:
2885
+ EFT: saveEftPayment()
2886
+ Credit card: getCcPaymentIframeUrl() → render iframe → pollCcPaymentStatus()
2887
+ → Prepare Docs → PIN → finalSubmit()
2888
+ ```
2889
+
2890
+ Pick one per opportunity. After a successful EFT save, `getCcPaymentIframeUrl()` returns `EftPaymentAlreadyCompleted`.
2891
+
2892
+ **Who charges the card, and when** — the most important distinction:
2893
+
2894
+ | Product | Card charged at | `finalSubmit()` payment-decline errors? |
2895
+ |---|---|---|
2896
+ | ADB / GIGDB | **`finalSubmit()`**, by InstaBrain | **Yes** — see the decline codes below |
2897
+ | Final Expense | **Never at `finalSubmit()`** — the carrier collects after underwriting | **No** |
2898
+
2899
+ `'approved'` means the card was **captured**, not charged — for every product.
2900
+
2901
+ ---
2902
+
2903
+ ## Get Credit Card Iframe URL
2904
+
2905
+ **Method:** `client.getCcPaymentIframeUrl(opportunityId)` · **Returns:** `Promise<string>`
2906
+
2907
+ Returns the TrustCommerce hosted-page URL for card capture. The SDK never handles card data — render this URL and let the applicant complete the form. **Supported for ADB, GIGDB, and Final Expense only.**
2908
+
2909
+ > **Persist the returned URL keyed by `opportunityId` and reuse it.** A new link is only issued once the latest attempt has **failed**. Calling this again while capture is `pending` *or* already `approved` returns `TcIframeLinkAlreadyGenerated` — that's a signal to reuse the URL you already have, not an error to recover from.
2910
+
2911
+ ### Request
2912
+
2913
+ | Parameter | Type | Required | Description |
2914
+ |---|---|---|---|
2915
+ | `opportunityId` | `string` (query) | Yes | The `opportunityId` from Start Application |
2916
+
2917
+ ### Response
2918
+
2919
+ | Field | Type | Description |
2920
+ |---|---|---|
2921
+ | *(return value)* | `string` | The fully-qualified TrustCommerce iframe URL |
2922
+
2923
+ ### Error Codes
2924
+
2925
+ All return HTTP 400, each as a **distinct** top-level code.
2926
+
2927
+ | Code | When | What to do |
2928
+ |---|---|---|
2929
+ | `InvalidRequestFormat` | `opportunityId` missing or unknown | Fix the ID |
2930
+ | `CcPaymentIframeNotSupportedForProduct` | Product is not ADB / GIGDB / Final Expense | Use `saveEftPayment()` instead (IB Term / Pure Term) |
2931
+ | `ApplicationNotReady` | Start Application has not completed successfully | Complete start application, then retry |
2932
+ | `EftPaymentAlreadyCompleted` | A successful EFT payment already exists | EFT and card are mutually exclusive — nothing to do |
2933
+ | `TcIframeLinkAlreadyGenerated` | A link exists and the latest attempt has not failed | **Reuse the stored URL**; only request a new one after `'failed'` |
2934
+
2935
+ ### Example
2936
+
2937
+ ```typescript
2938
+ const iframeUrl = await client.getCcPaymentIframeUrl(opportunityId);
2939
+ // Persist it — you'll need it again while status is 'pending'.
2940
+ await savePaymentUrl(opportunityId, iframeUrl);
2941
+ // Render iframeUrl to the applicant.
2942
+ ```
2943
+
2944
+ ---
2945
+
2946
+ ## Credit Card Payment Status
2947
+
2948
+ **Methods:** `client.pollCcPaymentStatus(opportunityId, options?)` (recommended) · `client.getCcPaymentStatus(opportunityId)` (single check)
2949
+ **Type:** `ThirdPartyCcPaymentStatusRes`
2950
+
2951
+ Reports whether card capture has completed. Drive your loop off `shouldContinuePolling`, not the `status` string.
2952
+
2953
+ ### Response
2954
+
2955
+ | Field | Type | Description |
2956
+ |---|---|---|
2957
+ | `status` | `CcPaymentStatus` | `'pending'` · `'approved'` · `'failed'` |
2958
+ | `shouldContinuePolling` | `boolean` | `true` only while `'pending'` |
2959
+
2960
+ ### Status values
2961
+
2962
+ | `status` | `shouldContinuePolling` | Meaning | What to do next |
2963
+ |---|---|---|---|
2964
+ | `pending` | `true` | Capture in progress, or the iframe was never opened | Keep polling. **Reuse the stored URL** — do not call `getCcPaymentIframeUrl()`. Do not call `finalSubmit()` (returns `paymentNotMade`). |
2965
+ | `approved` | `false` | Card captured successfully | Proceed to Prepare Docs → signing → `finalSubmit()` |
2966
+ | `failed` | `false` | Declined in the iframe, or (ADB/GIGDB) the `finalSubmit()` charge failed | Call `getCcPaymentIframeUrl()` for a **new** card, then poll again. Do not call `finalSubmit()` (returns `LatestPaymentNotSuccessful`). |
2967
+
2968
+ ### Polling options (`PollCcPaymentStatusOptions`)
2969
+
2970
+ | Option | Default | Meaning |
2971
+ |---|---|---|
2972
+ | `intervalMs` | `10_000` (10s) | Interval between polls — matches the rate limit. **Never set below `10_000`.** |
2973
+ | `maxTotalDurationMs` | `1_800_000` (30 min) | Client-side safety net, matching the Final Expense poller. Card capture has no server-side timeout — it stays `'pending'` until the applicant finishes, so this budget is the only stop. On expiry the poll resolves with the last response rather than throwing. |
2974
+ | `onPoll` | — | `(result, attempt, elapsedMs) => void`, invoked after every poll including the terminal one. Use it to show "waiting for card capture…" instead of awaiting silently. |
2975
+
2976
+ > **Rate limit:** 1 request per 10 seconds per `opportunityId`; exceeding it returns HTTP `429` with `Retry-After: 10`. `pollCcPaymentStatus()` **transparently retries** a 429 after that delay — the managed poll never aborts on rate limiting. A single `getCcPaymentStatus()` call does **not** auto-retry; handle the 429 yourself.
2977
+
2978
+ > `pollCcPaymentStatus()` **never requests a new iframe URL**, including on `'failed'` — the applicant must re-enter card details, so that call is always yours to make.
2979
+
2980
+ ### Example — full card-capture flow
2981
+
2982
+ ```typescript
2983
+ const iframeUrl = await client.getCcPaymentIframeUrl(opportunityId);
2984
+ // …render iframeUrl, applicant submits the card…
2985
+
2986
+ const result = await client.pollCcPaymentStatus(opportunityId, {
2987
+ onPoll: (r, attempt, ms) =>
2988
+ console.log(`poll #${attempt} (${Math.round(ms / 1000)}s): ${r.status}`),
2989
+ });
2990
+
2991
+ switch (result.status) {
2992
+ case 'approved':
2993
+ // Card captured — continue to signing, then finalSubmit().
2994
+ break;
2995
+ case 'failed':
2996
+ // Capture a NEW card, then poll again.
2997
+ await client.getCcPaymentIframeUrl(opportunityId);
2998
+ break;
2999
+ case 'pending':
3000
+ // Budget expired without the applicant finishing — resume later.
3001
+ break;
3002
+ }
3003
+ ```
3004
+
3005
+ ### Recovery after a decline (ADB / GIGDB)
3006
+
3007
+ When `finalSubmit()` fails with a payment decline, the application is **not** submitted:
3008
+
3009
+ 1. `pollCcPaymentStatus()` reports `'failed'` on the next poll
3010
+ 2. Calling `finalSubmit()` again immediately returns `LatestPaymentNotSuccessful`
3011
+ 3. Call `getCcPaymentIframeUrl()` for a new capture → poll to `'approved'` → retry `finalSubmit()`
3012
+
3013
+ **Decline codes** (ADB / GIGDB only — Final Expense never produces these):
3014
+
3015
+ `PaymentCvvInvalid` · `PaymentDeclinedContactBank` · `PaymentDeclined` · `PaymentDeclinedPermanent` · `PaymentPinLocked` · `PaymentInsufficientFunds` · `PaymentProcessingError` · `PaymentSuspectedFraud` · `PaymentCardExpired` · `PaymentInvalidCardData` · `PaymentCardError` · `PaymentContactBank` · `PaymentRelatedError`
3016
+
3017
+ Each maps to a distinct `APIErrorCode` with its own `getUserFriendlyMessage()`.
3018
+
3019
+ ---
3020
+
2386
3021
  ## Save EFT Payment
2387
3022
 
2388
3023
  **Method:** `client.saveEftPayment(request)` · **Type:** `ThirdPartyEftPaymentReq`
@@ -2397,17 +3032,22 @@ Saves bank account details for premium payment. Call after Start Application, be
2397
3032
 
2398
3033
  | Field | Type | Required | Validation Error |
2399
3034
  |---|---|---|---|
2400
- | `opportunityId` | `string` | Yes | `OpportunityId is required.` |
2401
- | `accountHolderName` | `string` | Yes | `Account holder name is required.` / `Account holder name must be 100 characters or fewer.` |
3035
+ | `opportunityId` | `string` | Yes | `OpportunityId is required.` / `OpportunityId does not exist.` |
3036
+ | `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.` |
2402
3037
  | `routingNumber` | `string` | Yes | `Routing number is required.` / `Routing number must be 9 digits.` |
2403
3038
  | `accountNumber` | `string` | Yes | `Account number is required.` / `Account number must be 4 to 17 digits.` |
2404
3039
 
3040
+ > `accountHolderName` accepts **letters, spaces, hyphens, and apostrophes only** — max 100 characters. Digits and other punctuation are rejected.
3041
+
2405
3042
 
2406
3043
  ***
2407
3044
 
2408
3045
  ### Business Rules
2409
3046
 
2410
3047
  1. Once EFT payment is saved, quote update calls for the same `opportunityId` are blocked.
3048
+ 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`.
3049
+ 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.
3050
+ 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.
2411
3051
 
2412
3052
 
2413
3053
  ***
@@ -2416,8 +3056,10 @@ Saves bank account details for premium payment. Call after Start Application, be
2416
3056
 
2417
3057
  | Code | When |
2418
3058
  |---|---|
2419
- | `InvalidRequestFormat` | Any field validation failure — inspect `value.fields` |
2420
- | `PaymentAlreadyMade` | EFT already saved for this opportunity |
3059
+ | `InvalidRequestFormat` | Any field validation failure, or `opportunityId` does not exist — inspect `value.fields` |
3060
+ | `PaymentAlreadyMade` | A successful payment already exists for this opportunity (prior EFT save, or a card already charged) |
3061
+
3062
+ > 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.
2421
3063
 
2422
3064
 
2423
3065
  ***
@@ -2448,7 +3090,7 @@ await client.saveEftPayment({
2448
3090
  **Method:** `client.prepareDocsAndGetDeliveryChannels(opportunityId)`
2449
3091
 
2450
3092
 
2451
- Always call this first in the signing flow. Prepares e-signature documents server-side and returns available delivery channels.
3093
+ Always call this first in the signing flow. Prepares e-signature documents server-side and returns available delivery channels. Applies to **ADB, GIGDB, and Final Expense**.
2452
3094
 
2453
3095
 
2454
3096
  ***
@@ -2465,6 +3107,8 @@ Always call this first in the signing flow. Prepares e-signature documents serve
2465
3107
  ### Business Rules
2466
3108
 
2467
3109
  1. If `isSignCompleted = true`, documents are already signed — skip Send PIN, Resend PIN, and Verify PIN. Call Final Submit directly.
3110
+ 2. `isSmsAvailable` / `isEmailAvailable` determine which channels may be selected in [Send PIN](#send-pin--get-documents-link) — only an available channel is accepted.
3111
+ 3. **Start Application must have completed successfully** before this endpoint can be called. If not, it returns `ApplicationNotReady` — the same lifecycle gate [`getCcPaymentIframeUrl()`](#get-credit-card-iframe-url) applies.
2468
3112
 
2469
3113
 
2470
3114
  ***
@@ -2474,11 +3118,14 @@ Always call this first in the signing flow. Prepares e-signature documents serve
2474
3118
  | Code | When |
2475
3119
  |---|---|
2476
3120
  | `InvalidRequestFormat` | `OpportunityId is required.` / `OpportunityId does not exist.` / `Documents are already signed.` (field-level) |
3121
+ | `ApplicationNotReady` | Start Application has not completed successfully, or signing was called too early. Message: `Application is not ready for e-signing. Complete Start Application successfully, then retry.` |
2477
3122
  | `DocumentsAlreadySigned` | Documents already completed for this opportunity |
2478
3123
  | `SecureSignRelatedError` | Generic SecureSign failure during document preparation — retry; if persistent, contact support |
2479
3124
 
2480
3125
  > When signing is already complete, you may see `DocumentsAlreadySigned` or the `InvalidRequestFormat` field message `"Documents are already signed."` — both are terminal; do not retry Prepare Docs / Send PIN.
2481
3126
 
3127
+ > `ApplicationNotReady` is **retryable** — unlike the terminal codes above. Complete Start Application, then call this again.
3128
+
2482
3129
 
2483
3130
  ***
2484
3131
 
@@ -2709,7 +3356,7 @@ if (verifyResp.isVerified) {
2709
3356
  **Method:** `client.finalSubmit(opportunityId)`
2710
3357
 
2711
3358
 
2712
- Submits the signed application to the carrier. Can only be called once per opportunity.
3359
+ Submits the signed application to the carrier.
2713
3360
 
2714
3361
 
2715
3362
  ***
@@ -2718,9 +3365,7 @@ Submits the signed application to the carrier. Can only be called once per oppor
2718
3365
 
2719
3366
  | Field | Type | Required | Validation Error |
2720
3367
  |---|---|---|---|
2721
- | `opportunityId` | `string` | Yes | `OpportunityId is required.` / `OpportunityId does not exist.` / `Application has already been final submitted.` |
2722
-
2723
- > `"Application has already been final submitted."` is a terminal state — do not retry.
3368
+ | `opportunityId` | `string` | Yes | `OpportunityId is required.` / `OpportunityId does not exist.` |
2724
3369
 
2725
3370
  > Throws `AuthenticationError` when `opportunityId` is not authorized for the current JWT.
2726
3371
 
@@ -2729,11 +3374,49 @@ Submits the signed application to the carrier. Can only be called once per oppor
2729
3374
 
2730
3375
  ### Business Rules
2731
3376
 
2732
- 1. Can only be called once. Subsequent calls for the same `opportunityId` are rejected.
3377
+ 1. **A repeat call after a successful submit is idempotent.** The API does not re-submit to the carrier or re-charge payment — it returns the existing result, including the same `policyNumber`. Do not guard against it client-side or treat it as an error.
2733
3378
  2. `policyNumber` may be `null` — carrier decisions can be async/pending. A `null` on `flagStatus: true` is **not** an error.
2734
3379
  3. **Response shape differs by product:**
2735
3380
  - **ADB / GIGDB (synchronous):** `policyNumber` is a non-null string; `applicationStatus` is **absent**.
2736
3381
  - **Final Expense (asynchronous):** `policyNumber` is `null` and `applicationStatus` is `'InProgress'`. Check `applicationStatus === 'InProgress'` and then poll [`pollFinalExpenseUnderwritingStatus()`](#final-expense--underwriting-status-async).
3382
+ 4. **Payment must already be successful.** How that is satisfied depends on the method:
3383
+ - **EFT (all products)** — collected at `saveEftPayment()`; no charge runs here.
3384
+ - **Credit card, ADB / GIGDB** — the captured card is charged here, and the application is submitted only if the charge succeeds. A decline returns a `Payment*` code and the application is **not** submitted.
3385
+ - **Credit card, Final Expense** — capture to `approved` is required, but InstaBrain does not charge here; the carrier collects after underwriting. Final Expense never returns a `Payment*` decline code.
3386
+
3387
+
3388
+ ***
3389
+
3390
+ ### Pre-Submit Gates
3391
+
3392
+ Three checks run in this order. They are **separate, distinguishable codes** — do not collapse the last two into one client-side case.
3393
+
3394
+ | Order | Code | Meaning | Recovery |
3395
+ |---|---|---|---|
3396
+ | 1 | `SecureSignNotCompleted` | Signing is not finished | Complete the PIN flow, or confirm `isSignCompleted` from prepare-docs |
3397
+ | 2 | `paymentNotMade` | Nothing to submit yet — no payment was started, **or** a card capture is still `pending` | Finish the iframe and poll to `approved`, or save EFT. While pending, **reuse the stored iframe URL** — do not request a new one |
3398
+ | 3 | `LatestPaymentNotSuccessful` | A payment was attempted and the latest attempt **failed** | Call `getCcPaymentIframeUrl()` for a new capture, poll to `approved`, then retry |
3399
+
3400
+ > The distinction matters: `paymentNotMade` means "keep waiting or start a payment"; `LatestPaymentNotSuccessful` means "a payment was tried and it failed — start a new capture." Retrying final submit after a decline without a new successful capture returns `LatestPaymentNotSuccessful`, not another decline code.
3401
+
3402
+ ```typescript
3403
+ import { APIValidationError, APIErrorCode } from '@instabrain-sdks/api-client';
3404
+
3405
+ try {
3406
+ const resp = await client.finalSubmit(opportunityId);
3407
+ } catch (err) {
3408
+ if (err instanceof APIValidationError) {
3409
+ if (err.isErrorType(APIErrorCode.SecureSignNotCompleted)) {
3410
+ // Finish signing first
3411
+ } else if (err.isErrorType(APIErrorCode.PaymentNotMade)) {
3412
+ // Reuse the existing iframe URL and keep polling — do NOT request a new one
3413
+ } else if (err.isErrorType(APIErrorCode.LatestPaymentNotSuccessful)) {
3414
+ // Start a fresh capture
3415
+ const url = await client.getCcPaymentIframeUrl(opportunityId);
3416
+ }
3417
+ }
3418
+ }
3419
+ ```
2737
3420
 
2738
3421
 
2739
3422
  ***
@@ -2742,9 +3425,12 @@ Submits the signed application to the carrier. Can only be called once per oppor
2742
3425
 
2743
3426
  | Code | When |
2744
3427
  |---|---|
2745
- | `InvalidRequestFormat` | `opportunityId` missing, not found, or already submitted |
2746
- | `PaymentNotMade` | EFT not saved — call `saveEftPayment()` first |
3428
+ | `InvalidRequestFormat` | `opportunityId` missing or not found |
3429
+ | `SecureSignNotCompleted` | Signing not complete — gate 1 |
3430
+ | `paymentNotMade` | No payment started, or card capture still pending — gate 2 |
3431
+ | `LatestPaymentNotSuccessful` | Latest payment attempt failed — gate 3 |
2747
3432
  | `FidelityFinalSubmitError` | Fidelity carrier rejected or failed to process the final submission — contact support with the `opportunityId` |
3433
+ | `Payment*` decline codes | ADB / GIGDB only — the card charge was declined at final submit and the application was **not** submitted. See [Get credit card iframe URL](#get-credit-card-iframe-url) |
2748
3434
 
2749
3435
 
2750
3436
  ***
@@ -3032,10 +3718,24 @@ Named entity types: `Business` · `Corporation` · `CharitableOrganization` · `
3032
3718
  ```
3033
3719
  InstaBrainError
3034
3720
  ├── AuthenticationError — invalid credentials, expired JWT, or unauthorized opportunityId
3035
- ├── ValidationError — client-side / transport validation before a successful response
3036
- └── APIValidationError — server returned flagStatus: false (check APIErrorCode)
3721
+ ├── ValidationError — retained for backward compatibility; no longer thrown by the SDK
3722
+ └── APIValidationError — business / validation failure (check APIErrorCode)
3723
+ ```
3724
+
3725
+ **`APIValidationError` covers both failure shapes.** The API reports a rejected request two ways — HTTP `400` with a top-level `error`, or HTTP `200` with `flagStatus: false` — and which one you get varies by endpoint. Both now produce an `APIValidationError` with the same `errorCode` and `response`, so a single `catch` handles either:
3726
+
3727
+ ```typescript
3728
+ catch (err) {
3729
+ if (err instanceof APIValidationError) {
3730
+ err.isErrorType(APIErrorCode.ApplicationNotReady); // works on both paths
3731
+ err.getUserFriendlyMessage();
3732
+ err.response?.value?.fields; // per-field detail
3733
+ }
3734
+ }
3037
3735
  ```
3038
3736
 
3737
+ > `ValidationError` is still exported so existing `import` statements keep compiling, but nothing in the SDK throws it. If you have a `catch` branch testing `err instanceof ValidationError`, switch it to `APIValidationError`.
3738
+
3039
3739
 
3040
3740
  ***
3041
3741
 
@@ -3109,25 +3809,48 @@ if (err instanceof APIValidationError && err.isErrorType(APIErrorCode.InvalidReq
3109
3809
 
3110
3810
  Active `APIErrorCode` enum members match the tables below. Compare failures with `err.isErrorType(APIErrorCode.X)` — do not rely on raw string casing; use the **String Value** column when logging or debugging.
3111
3811
 
3112
- Deprecated enum members (`QuoteNotFound`, `HeightNotValid`, `DocumentsNotViewed`, and others) remain in the package for backward compatibility but are **not** listed here; the API surfaces those cases via `InvalidRequestFormat` and `value.fields` instead.
3812
+ Some enum members remain in the package for backward compatibility but are **not** listed here; the API surfaces those cases via `InvalidRequestFormat` and `value.fields` instead. Note that scope is **per product** — a code that is field-level for one product can be a top-level business code for another, so a member being absent from one product's table does not make it dead.
3113
3813
 
3114
3814
 
3115
3815
  ***
3116
3816
 
3117
3817
  ### Quote Errors
3118
3818
 
3119
- | Code | String Value | Products | When |
3120
- |---|---|---|---|
3121
- | `InvalidRequestFormat` | `'InvalidRequestFormat'` | All | Any validation failure — inspect `value.fields` |
3122
- | `StateNotFound` | `'stateNotFound'` | All quotes | State code not recognized |
3123
- | `AgeNotFound` | `'AgeNotFound'` | All quotes | Neither age nor date of birth supplied, or age could not be derived |
3124
- | `NotAvailableForState` | `'NotAvailableForState'` | All quotes | Product not available in state |
3125
- | `QuoteNotEligibleForGivenConditions` | `'QuoteNotEligibleForGivenConditions'` | All quotes | State/age/nicotine combo not eligible |
3126
- | `CoverageNotAvailable` | `'CoverageNotAvailable'` | All quotes | Face amount out of range |
3127
- | `RiderNotAvailable` | `'RiderNotAvailable'` | ADB, IB Term | Rider unavailable for product/state |
3128
- | `RiderFaceAmountNotValid` | `'RiderFaceAmountNotValid'` | ADB, IB Term | Rider face amount out of range |
3129
- | `BenefitPeriodNotAvailable` | `'BenefitPeriodNotAvailable'` | IB Term | Benefit period not allowed for state/age/nicotine |
3130
- | `OutsideBuildChart` | `'outsideBuildChart'` | IB Term | Height & weight provided and outside carrier build chart |
3819
+ | Code | String Value | When |
3820
+ |---|---|---|
3821
+ | `InvalidRequestFormat` | `'InvalidRequestFormat'` | Any field validation failure — inspect `value.fields` |
3822
+ | `StateNotFound` | `'stateNotFound'` | State code not recognized |
3823
+ | `AgeNotFound` | `'AgeNotFound'` | Neither age nor date of birth supplied, or age could not be derived |
3824
+ | `ProductNotAvailableForState` | `'ProductNotAvailableForState'` | **Request validation** — product has no carrier config for the state, or is flagged unavailable there. `value.fields.StateCode` |
3825
+ | `AgentNotLicensedForState` | `'AgentNotLicensedForState'` | **Request validation** — authenticated agent is not licensed in that state, or the agent could not be resolved. `value.fields.StateCode` |
3826
+ | `NotAvailableForState` | `'NotAvailableForState'` | **Post-validation eligibility** — product not available in state, determined after validation passed. `value: null` |
3827
+ | `QuoteNotEligibleForGivenConditions` | `'QuoteNotEligibleForGivenConditions'` | State/age/nicotine combo not eligible |
3828
+ | `CoverageNotAvailable` | `'CoverageNotAvailable'` | Face amount out of range |
3829
+ | `RiderNotAvailable` | `'RiderNotAvailable'` | Rider unavailable for product/state |
3830
+ | `RiderFaceAmountNotValid` | `'RiderFaceAmountNotValid'` | Rider face amount out of range |
3831
+ | `BenefitPeriodNotAvailable` | `'BenefitPeriodNotAvailable'` | Benefit period not allowed for state/age/nicotine |
3832
+ | `OutsideBuildChart` | `'outsideBuildChart'` | Height & weight provided and outside carrier build chart |
3833
+ | `HeightNotValid` | `'HeightNotValid'` | `height.feet` / `height.inches` out of range (feet 1–8, inches 0–11) |
3834
+
3835
+ > **`stateCode` is checked as a cascade, stopping at the first failure**, on every product's Get Quote:
3836
+ >
3837
+ > 1. required / recognized state → `InvalidRequestFormat`
3838
+ > 2. product available in that state → `ProductNotAvailableForState`
3839
+ > 3. agent licensed in that state → `AgentNotLicensedForState`
3840
+ >
3841
+ > 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.
3842
+ >
3843
+ > **`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.
3844
+
3845
+ **Which codes each product returns** — the rider codes are the main difference, so branch per product rather than assuming one shared list:
3846
+
3847
+ | Product | Business codes returned as top-level `error` |
3848
+ |---|---|
3849
+ | **ADB** | `QuoteNotEligibleForGivenConditions`, `NotAvailableForState`, `CoverageNotAvailable`, `RiderNotAvailable`, `RiderFaceAmountNotValid` |
3850
+ | **GIGDB** | `QuoteNotEligibleForGivenConditions`, `NotAvailableForState`, `CoverageNotAvailable` — rider codes do **not** apply |
3851
+ | **Final Expense** | `stateNotFound`, `AgeNotFound`, `HeightNotValid`, `BenefitPeriodNotAvailable`, `QuoteNotEligibleForGivenConditions`, `NotAvailableForState`, `CoverageNotAvailable` |
3852
+ | **IB Term** | `BenefitPeriodNotAvailable`, `CoverageNotAvailable`, `outsideBuildChart`, `QuoteNotEligibleForGivenConditions`, `NotAvailableForState`, `RiderNotAvailable`, `RiderFaceAmountNotValid` |
3853
+ | **Pure Term** | Same set as IB Term. Request validation produces dedicated codes only for `BenefitPeriodNotAvailable` / `CoverageNotAvailable` (everything else is field-level `InvalidRequestFormat`), but the shared eligibility pipeline that runs **after** validation can still return `NotAvailableForState`, `QuoteNotEligibleForGivenConditions`, `RiderNotAvailable`, `RiderFaceAmountNotValid`, and `outsideBuildChart` |
3131
3854
 
3132
3855
 
3133
3856
  ***
@@ -3136,10 +3859,22 @@ Deprecated enum members (`QuoteNotFound`, `HeightNotValid`, `DocumentsNotViewed`
3136
3859
 
3137
3860
  | Code | String Value | Products | When |
3138
3861
  |---|---|---|---|
3139
- | `ApplicationLimitReached` | `'ApplicationLimitReached'` | ADB, GIGDB, Final Expense | Same SSN/email/phone has policy within last 30 days. Not used by IB Term. |
3862
+ | `ApplicationLimitReached` | `'ApplicationLimitReached'` | ADB, GIGDB, Final Expense | Same SSN/email/phone has policy within last 30 days. Not used by IB Term or Pure Term. |
3140
3863
  | `StateMismatchIdentified` | `'StateMismatchIdentified'` | All | Quote state ≠ application address state — re-quote |
3141
3864
  | `AgentNotFound` | `'agentNotFound'` | All | Quote cannot be linked to agent account — verify credentials |
3142
3865
  | `InternalServerError` | `'internalServerError'` | All | Unexpected backend failure — retry; if persistent contact support |
3866
+ | `DataNotFound` | `'dataNotFound'` | IB Term, Pure Term | The quote referenced by `quoteResponseId` could not be found — create a new quote |
3867
+ | `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 |
3868
+
3869
+ **Three outcome shapes — do not conflate them.** Start Application distinguishes field validation, business failure, and knockout:
3870
+
3871
+ | Outcome | HTTP | Response shape | Codes |
3872
+ |---|---|---|---|
3873
+ | **Field validation** | `400` | `value.fields` populated with per-field messages | `InvalidRequestFormat`, `ApplicationLimitReached` |
3874
+ | **Business failure** | `400` | `value: null`, top-level `error` | `StateMismatchIdentified`, `agentNotFound`, `internalServerError`, `dataNotFound` |
3875
+ | **Decline / knockout** | **`200`** | `flagStatus: true`, `value.isDeclined: true` | **None** — a knockout is *not* an error code and the SDK does **not** throw |
3876
+
3877
+ > The decline row is the one that trips integrations up: a knockout arrives as a **successful** response. Check `resp.isDeclined` explicitly — it will never reach your `catch` block.
3143
3878
 
3144
3879
 
3145
3880
  ***
@@ -3148,7 +3883,9 @@ Deprecated enum members (`QuoteNotFound`, `HeightNotValid`, `DocumentsNotViewed`
3148
3883
 
3149
3884
  | Code | String Value | Products | When |
3150
3885
  |---|---|---|---|
3151
- | `PaymentAlreadyMade` | `'PaymentAlreadyMade'` | ADB, GIGDB | `update*Quote()` or `saveEftPayment()` after EFT is already saved for the opportunity |
3886
+ | `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 |
3887
+ | `EftPaymentAlreadyCompleted` | `'EftPaymentAlreadyCompleted'` | ADB, GIGDB, Final Expense | `getCcPaymentIframeUrl()` after a successful EFT save — the two methods are mutually exclusive per opportunity |
3888
+ | `ApplicationNotReady` | `'ApplicationNotReady'` | ADB, GIGDB, Final Expense | `getCcPaymentIframeUrl()` or `prepareDocsAndGetDeliveryChannels()` before Start Application has completed successfully. **Retryable** — complete Start Application, then call again |
3152
3889
 
3153
3890
 
3154
3891
  ***
@@ -3173,7 +3910,9 @@ Deprecated enum members (`QuoteNotFound`, `HeightNotValid`, `DocumentsNotViewed`
3173
3910
 
3174
3911
  | Code | String Value | When |
3175
3912
  |---|---|---|
3176
- | `PaymentNotMade` | `'paymentNotMade'` | EFT not saved — call `saveEftPayment()` before `finalSubmit()` |
3913
+ | `SecureSignNotCompleted` | `'SecureSignNotCompleted'` | **Gate 1** — signing not finished. Complete the PIN flow, or confirm `isSignCompleted` from prepare-docs |
3914
+ | `PaymentNotMade` | `'paymentNotMade'` | **Gate 2** — nothing to submit yet: no payment was started, **or** a card capture is still `pending`. Finish the capture and poll to `approved`, or call `saveEftPayment()`. Reuse the stored iframe URL while pending |
3915
+ | `LatestPaymentNotSuccessful` | `'LatestPaymentNotSuccessful'` | **Gate 3** — a payment was attempted and the latest attempt **failed**. Call `getCcPaymentIframeUrl()` for a new capture, poll to `approved`, then retry |
3177
3916
  | `FidelityFinalSubmitError` | `'FidelityFinalSubmitError'` | Fidelity carrier rejected or failed to process the submission — contact support with the `opportunityId` |
3178
3917
  | `FinalSubmitStatusNotSupported` | `'FinalSubmitStatusNotSupported'` | Underwriting status polling attempted for a non-Final-Expense product — `pingFinalExpenseUnderwritingStatus()` / `pollFinalExpenseUnderwritingStatus()` are Final Expense only |
3179
3918