@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
@@ -54,6 +54,10 @@ class APIValidationError extends InstaBrainError {
54
54
  // Quote business errors (ADB / GIGDB / IB Term)
55
55
  'stateNotFound': 'The state code provided is not recognized by the system.',
56
56
  'NotAvailableForState': 'Product is not available in the specified state.',
57
+ // Get Quote request-validation state cascade — distinct from the
58
+ // post-validation NotAvailableForState above.
59
+ 'ProductNotAvailableForState': 'This product is not available in the selected state. Try a different state, or a product offered there.',
60
+ 'AgentNotLicensedForState': 'The agent is not licensed in the selected state. Quotes can only be run in states the agent is licensed for.',
57
61
  'QuoteNotEligibleForGivenConditions': 'Product is not available for the given combination of state, age, or tobacco usage.',
58
62
  'CoverageNotAvailable': 'The requested coverage amount is not available for the given conditions.',
59
63
  'RiderNotAvailable': 'The requested rider is not available in this state or for this age.',
@@ -68,6 +72,7 @@ class APIValidationError extends InstaBrainError {
68
72
  'agentNotFound': 'The quote cannot be linked to an agent account. Please verify the agent token and try again.',
69
73
  'internalServerError': 'An unexpected error occurred while processing the application. Please retry; if the issue persists, contact InstaBrain support.',
70
74
  'InvalidRequestFormat': 'The request format is invalid. Inspect value.fields for per-field details.',
75
+ 'PivotNotAvailable': 'This application cannot be switched to an alternative product. It may not be eligible, or it may already have been converted.',
71
76
  'QuoteNotFound': 'No previous quote found for this opportunity. Please create a quote first.',
72
77
  'ApplicationLimitReached': 'An application with the same SSN, email, or phone already has a policy generated within the last 30 days.',
73
78
  'SecureSignRelatedError': 'A signing-related error occurred. Please try again.',
@@ -81,19 +86,43 @@ class APIValidationError extends InstaBrainError {
81
86
  'MessageNotDelivered': 'SMS delivery failed. Retry or switch to email.',
82
87
  'FidelityFinalSubmitError': 'Fidelity carrier rejected or failed to process the submission. Contact support with the opportunityId.',
83
88
  'FinalSubmitStatusNotSupported': 'Underwriting status polling is not supported for this product — Final Expense only.',
89
+ // Credit card payment — iframe gates
90
+ 'TcIframeLinkAlreadyGenerated': 'A payment link was already generated for this application. Reuse the existing link; a new one can only be issued after the current card attempt fails.',
91
+ 'CcPaymentIframeNotSupportedForProduct': 'Credit card payment is not available for this product. Use EFT payment instead.',
92
+ 'ApplicationNotReady': 'The application is not ready for this step. Complete the start-application step successfully, then retry.',
93
+ 'EftPaymentAlreadyCompleted': 'An EFT payment has already been completed for this application. EFT and credit card cannot both be used.',
94
+ // Credit card decline codes (ADB / GIGDB charge at final submit)
95
+ 'PaymentCvvInvalid': 'The card security code (CVV) was rejected. Please re-enter the card details.',
96
+ 'PaymentDeclinedContactBank': 'The card was declined. The cardholder should contact their bank, then try a different card.',
97
+ 'PaymentDeclined': 'The card was declined. Please try a different card.',
98
+ 'PaymentDeclinedPermanent': 'The card was permanently declined. Please use a different card.',
99
+ 'PaymentPinLocked': 'The card PIN is locked. Please use a different card.',
100
+ 'PaymentInsufficientFunds': 'The card has insufficient funds. Please use a different card.',
101
+ 'PaymentProcessingError': 'The payment processor could not complete the charge. Please try again or use a different card.',
102
+ 'PaymentSuspectedFraud': 'The charge was blocked as suspected fraud. Please use a different card.',
103
+ 'PaymentCardExpired': 'The card has expired. Please use a different card.',
104
+ 'PaymentInvalidCardData': 'The card details entered were invalid. Please re-enter them.',
105
+ 'PaymentCardError': 'There was a problem with the card. Please try a different card.',
106
+ 'PaymentContactBank': 'The card issuer requires the cardholder to contact their bank before this charge can proceed.',
107
+ 'PaymentRelatedError': 'The payment could not be completed. Capture a new card and retry the submission.',
108
+ // IB Term / Pure Term Start Application
109
+ 'dataNotFound': 'The quote could not be found for the supplied quoteResponseId. Create a new quote and retry.',
110
+ // Final Submit — pre-submit gates (checked in this order)
111
+ 'SecureSignNotCompleted': 'Secure signing is not complete. Finish the PIN flow before submitting.',
112
+ 'LatestPaymentNotSuccessful': 'The most recent payment attempt failed. Capture a new card and poll until approved, then retry final submit.',
84
113
  'AgentLogout': 'Agent session has expired. Please re-authenticate.',
85
114
  'InvalidBirthCountry': 'The birth country provided is not valid.',
86
115
  'InvalidBirthState': 'The birth state provided is not valid.',
87
116
  'InvalidResidenceState': 'The residence state provided is not valid.',
88
117
  'OneOfTheExistingCoveragesQuestionsNotFound': 'One or more existing coverage questions were not answered.',
89
- 'PaymentAlreadyMade': 'Payment has already been made for this application.',
118
+ 'PaymentAlreadyMade': 'A successful payment already exists for this application. EFT and credit card are mutually exclusive per opportunity.',
90
119
  'ErrorInSaveEftPaymentDetails': 'Failed to save EFT payment details. Please verify account information.',
91
120
  'InvalidPaymentScheduledDate': 'The scheduled payment date is not valid.',
92
121
  'ThirdPartyQuoteError': 'An error occurred while retrieving the quote.',
93
122
  'InvalidQuoteParameters': 'The quote parameters provided are not valid.',
94
123
  'InvalidStateCode': 'State not supported for ADB (MA, NH, AK unavailable; CA coming next release).',
95
124
  'InvalidAdbAgeRange': 'Age must be between 20 and 59 for ADB.',
96
- 'paymentNotMade': 'EFT payment must be completed before submitting the application.'
125
+ 'paymentNotMade': 'No payment has been completed — either none was started, or a credit card capture is still pending. Complete payment, then retry final submit.'
97
126
  };
98
127
  return errorMessages[this.errorCode] || this.message;
99
128
  }
@@ -125,9 +125,41 @@ export interface ThirdPartyGigdbAppReq {
125
125
  /** Required for KS or WA when willOtherCoverageBeReplacedOrFinanced === true */
126
126
  willOtherCoverageBeReplacedOrFinancedData?: GigdbWillOtherCoverageBeReplacedOrFinancedData | null;
127
127
  }
128
+ /**
129
+ * Request body for `POST /api/ThirdPartyPayment/save-eft-payment`.
130
+ *
131
+ * Shared across all full-flow products (GIGDB, ADB, Final Expense). Call after
132
+ * Start Application and before Prepare Signing Docs. Once EFT is saved, quote
133
+ * updates for the same `opportunityId` are blocked.
134
+ *
135
+ * Every field is required server-side. Format failures return
136
+ * `InvalidRequestFormat` with the offending PascalCase key under `value.fields`.
137
+ */
128
138
  export interface ThirdPartyEftPaymentReq {
139
+ /**
140
+ * The `opportunityId` from the Start Application response.
141
+ *
142
+ * Unlike `getCcPaymentIframeUrl()`, this endpoint applies **no
143
+ * application-readiness gate** — it only checks that the opportunity exists
144
+ * and that payment has not already completed. Still call it after Start
145
+ * Application in the integration flow.
146
+ *
147
+ * Errors: `OpportunityId is required.` / `OpportunityId does not exist.`
148
+ * (`InvalidRequestFormat`), or `PaymentAlreadyMade` when a successful payment
149
+ * already exists.
150
+ */
129
151
  opportunityId: string;
152
+ /**
153
+ * Name on the bank account. **Max 100 characters**, and may contain only
154
+ * **letters, spaces, hyphens, and apostrophes**.
155
+ *
156
+ * Errors: `Account holder name is required.` /
157
+ * `Account holder name must be 100 characters or fewer.` /
158
+ * `Account holder name may only contain letters, spaces, hyphens, and apostrophes.`
159
+ */
130
160
  accountHolderName: string | null;
161
+ /** 9-digit US bank routing number. Error: `Routing number must be 9 digits.` */
131
162
  routingNumber: string | null;
163
+ /** Bank account number, 4–17 digits. Error: `Account number must be 4 to 17 digits.` */
132
164
  accountNumber: string | null;
133
165
  }
@@ -237,8 +237,11 @@ export interface IBTermChildRiderInfo {
237
237
  /**
238
238
  * Request body for `POST /api/ThirdPartyIBTermApplication/start-application`.
239
239
  *
240
- * Source of truth: `THIRD_PARTY_ERROR_CODES.md` (IB Term Start Application section,
241
- * 2026-05). IB Term has product-specific fields ADB and GIGDB do not — height,
240
+ * Source of truth: the IB Term Start Application API page. The single
241
+ * `THIRD_PARTY_ERROR_CODES.md` catalog it previously cited has been retired —
242
+ * validation and business errors are now documented per endpoint instead.
243
+ *
244
+ * IB Term has product-specific fields ADB and GIGDB do not — height,
242
245
  * weight, driver license, primary care physician, structured tobacco/nicotine
243
246
  * usage, and the Dependent Child Rider's nested child + child-existing-coverage
244
247
  * arrays.
@@ -11,6 +11,8 @@ export * from './adb.types';
11
11
  export * from './ibterm.types';
12
12
  export * from './pureterm.types';
13
13
  export * from './finalexpense.types';
14
+ export * from './payment.types';
15
+ export * from './pivot.types';
14
16
  export * from './secure-sign.types';
15
17
  /**
16
18
  * Base configuration for the InstaBrain SDK
@@ -28,4 +28,6 @@ __exportStar(require("./adb.types"), exports);
28
28
  __exportStar(require("./ibterm.types"), exports);
29
29
  __exportStar(require("./pureterm.types"), exports);
30
30
  __exportStar(require("./finalexpense.types"), exports);
31
+ __exportStar(require("./payment.types"), exports);
32
+ __exportStar(require("./pivot.types"), exports);
31
33
  __exportStar(require("./secure-sign.types"), exports);
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Card-capture status reported by
3
+ * `GET /api/ThirdPartyPayment/cc-payment-status`.
4
+ *
5
+ * `'pending'` is the only non-terminal value. Note that `'approved'` means the
6
+ * card **details were captured**, not that money moved:
7
+ * - **ADB / GIGDB** — the stored card is charged later, at `finalSubmit()`.
8
+ * - **Final Expense** — the carrier collects after underwriting; `finalSubmit()`
9
+ * never charges.
10
+ */
11
+ export type CcPaymentStatus = 'pending' | 'approved' | 'failed';
12
+ /**
13
+ * Response from `GET /api/ThirdPartyPayment/cc-payment-status`.
14
+ *
15
+ * Drive polling loops off {@link shouldContinuePolling} rather than comparing
16
+ * `status` — same convention as the Final Expense underwriting poller.
17
+ */
18
+ export interface ThirdPartyCcPaymentStatusRes {
19
+ status: CcPaymentStatus;
20
+ /** `true` only while `status` is `'pending'`; `false` for `'approved'` / `'failed'`. */
21
+ shouldContinuePolling: boolean;
22
+ }
23
+ /**
24
+ * Tuning options for {@link PaymentService.pollCcPaymentStatus}.
25
+ * All durations are in milliseconds.
26
+ *
27
+ * The status endpoint is rate-limited to **1 request per 10 seconds** per
28
+ * `opportunityId`, so `intervalMs` should never be set below `10_000`.
29
+ */
30
+ export interface PollCcPaymentStatusOptions {
31
+ /**
32
+ * Interval between polls. Default `10_000` (10s) — matches the documented
33
+ * rate limit. Do not go below `10_000` or the endpoint returns HTTP 429.
34
+ */
35
+ intervalMs?: number;
36
+ /**
37
+ * Client-side safety net. Default `1_800_000` (30 min) — the same budget as
38
+ * the Final Expense underwriting poller. Unlike that flow (which the backend
39
+ * terminates with `'TimedOut'` at 30 min), card capture has **no server-side
40
+ * timeout** — it simply stays `'pending'` until the applicant finishes the
41
+ * hosted form, so this budget is the only stop. On expiry the poll resolves
42
+ * with the last response rather than throwing.
43
+ */
44
+ maxTotalDurationMs?: number;
45
+ /**
46
+ * Progress callback invoked after every poll, including the terminal one.
47
+ * Useful for surfacing "waiting for card capture…" feedback instead of
48
+ * awaiting silently. Receives the result, the 1-based attempt number, and
49
+ * milliseconds elapsed since polling began.
50
+ */
51
+ onPoll?: (result: ThirdPartyCcPaymentStatusRes, attempt: number, elapsedMs: number) => void;
52
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // ── Credit Card Payment (shared — ADB / GIGDB / Final Expense) ───────────────
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,122 @@
1
+ import { PaymentFrequency } from './enums';
2
+ /**
3
+ * GIGDB pivot — offering an alternative product after a Final Expense decline.
4
+ *
5
+ * The flow starts from a Final Expense `startApplication()` that returned
6
+ * `isDeclined: true` with a **non-zero** `opportunityId`. That id is the key for
7
+ * every call below.
8
+ *
9
+ * 1. `getPivotQuotes(opportunityId)` → alternative quote options
10
+ * 2. `customizePivotQuote(request)` → optional re-price on a new
11
+ * face amount / payment frequency
12
+ * 3. `convertPivotToApplication(request)` → creates the alternative-product
13
+ * application, returns a NEW id
14
+ *
15
+ * After conversion, continue with the alternative product's own lifecycle using
16
+ * the **new** `opportunityId` — starting with its get-existing-quote, since the
17
+ * convert response deliberately carries no premium.
18
+ */
19
+ /**
20
+ * A single alternative-product quote option.
21
+ *
22
+ * Returned both as an element of {@link PivotQuotesResp.quotes} and as the whole
23
+ * body of {@link CustomizePivotQuoteResp} — the shapes are identical.
24
+ */
25
+ export interface PivotQuote {
26
+ /**
27
+ * Product identifier for the alternative product, e.g. `"InstaGIGDB"`.
28
+ *
29
+ * **Persist this.** It is required on both `customizePivotQuote()` and
30
+ * `convertPivotToApplication()`. Always use the value the API returned — do
31
+ * not construct or assume a code.
32
+ */
33
+ pivotProductCode: string;
34
+ /** Display title, e.g. `"InstaBrain Guaranteed Issue"`. */
35
+ productTitle: string;
36
+ /** Total premium at the requested payment frequency. */
37
+ quoteAmount: number;
38
+ /** Coverage amount in dollars. */
39
+ coverageAmount: number;
40
+ /** Payment frequency (Monthly or Annually). */
41
+ paymentFrequency: PaymentFrequency;
42
+ /** Term length in years, or `null` for whole-life products such as GIGDB. */
43
+ termLength: number | null;
44
+ /** Riders included in the quote. Empty array when none apply. */
45
+ riders: Array<{
46
+ riderValue: string;
47
+ riderLabel: string | null;
48
+ }>;
49
+ }
50
+ /**
51
+ * Response from `GET /api/ThirdPartyPivot/get-pivot-quotes`.
52
+ *
53
+ * Calling this repeatedly for the same opportunity is safe.
54
+ */
55
+ export interface PivotQuotesResp {
56
+ /**
57
+ * Why the pivot was offered, e.g. `"ApplicationDeclineOrNotEligible"`.
58
+ * Display or log only — do not branch business logic on it.
59
+ */
60
+ pivotReason: string;
61
+ /** Available alternative-product quotes. */
62
+ quotes: PivotQuote[];
63
+ }
64
+ /**
65
+ * Request body for `POST /api/ThirdPartyPivot/customize-pivot-quote`.
66
+ *
67
+ * Optional step — only call it when the applicant wants a different coverage
68
+ * amount or billing frequency than the default pivot quote offered.
69
+ */
70
+ export interface CustomizePivotQuoteReq {
71
+ /** The declined Final Expense `opportunityId`. Must be non-zero. */
72
+ opportunityId: string;
73
+ /** **Required.** Use the value returned by `getPivotQuotes()`. */
74
+ pivotProductCode: string;
75
+ /**
76
+ * Desired coverage in dollars. Outside the alternative product's allowed
77
+ * range, or off its required increment, returns `CoverageNotAvailable`.
78
+ * GIGDB is $5,000–$25,000 in $1,000 increments.
79
+ */
80
+ faceAmount: number;
81
+ /** `Monthly` or `Annually` only. */
82
+ paymentFreq: PaymentFrequency;
83
+ }
84
+ /**
85
+ * Response from `POST /api/ThirdPartyPivot/customize-pivot-quote` — the same
86
+ * shape as one {@link PivotQuote} from the pivot-quotes list.
87
+ */
88
+ export type CustomizePivotQuoteResp = PivotQuote;
89
+ /**
90
+ * Request body for `POST /api/ThirdPartyPivot/convert-pivot-to-application`.
91
+ *
92
+ * `faceAmount` and `paymentFreq` are required on **every** call — they are not
93
+ * carried over from a prior `customizePivotQuote()`, so send the values the
94
+ * applicant actually confirmed.
95
+ */
96
+ export interface ConvertPivotToApplicationReq {
97
+ /** The declined Final Expense `opportunityId`. Must be non-zero. */
98
+ opportunityId: string;
99
+ /** **Required.** Use the value returned by `getPivotQuotes()`. */
100
+ pivotProductCode: string;
101
+ /** Confirmed coverage in dollars. Required every call. */
102
+ faceAmount: number;
103
+ /** Confirmed billing frequency. Required every call. */
104
+ paymentFreq: PaymentFrequency;
105
+ }
106
+ /**
107
+ * Response from `POST /api/ThirdPartyPivot/convert-pivot-to-application`.
108
+ *
109
+ * Deliberately carries no premium — fetch it from the alternative product's own
110
+ * get-existing-quote endpoint using the new `opportunityId`.
111
+ */
112
+ export interface ConvertPivotToApplicationResp {
113
+ /**
114
+ * The **new** opportunity for the alternative-product application.
115
+ *
116
+ * This replaces the Final Expense id for all subsequent calls on that
117
+ * product — get-existing-quote, update quote, payment, signing, final submit.
118
+ */
119
+ opportunityId: string;
120
+ /** Which product the new opportunity belongs to, e.g. `"InstaGIGDB"`. */
121
+ productCode: string;
122
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,59 +1,214 @@
1
1
  import { Gender, PaymentFrequency, PureTermRateClass, HealthClass } from './enums';
2
2
  import { ThirdPartyQuoteReqHeight, ThirdPartyQuoteReqRider } from './quote.types';
3
+ import { IBTermStartApplicationReq } from './ibterm.types';
4
+ /**
5
+ * Query parameters for the Pure Term rider lookup
6
+ * (`GET /api/ThirdPartyIbPureTermLookup/get-rider-details`).
7
+ *
8
+ * The `getPureTermRiderDetails()` facade takes positional arguments to match the
9
+ * IB Term convention; this interface is exported for callers who prefer to type
10
+ * their own request object.
11
+ */
12
+ export interface PureTermRiderDetailsRequest {
13
+ /** Two-letter US state code (e.g. "TX"). */
14
+ stateCode: string;
15
+ /** Applicant age, integer, 18–60 inclusive. */
16
+ age: number;
17
+ /** Whether the applicant uses nicotine. Must be sent explicitly — not optional. */
18
+ flagNicotineUse: boolean;
19
+ }
20
+ /** A single Pure Term rider option returned for a state/age/nicotine combination. */
21
+ export interface PureTermRider {
22
+ /**
23
+ * Pass into the Pure Term Quote request `riders[n].rider` to include this rider
24
+ * in the quote. Typed as string; tighten to an enum once the concrete value set
25
+ * is known.
26
+ */
27
+ riderCode: string;
28
+ /** Display title for UI rendering. */
29
+ riderTitle: string;
30
+ /** Display description for UI rendering. */
31
+ riderDescription: string;
32
+ }
33
+ /**
34
+ * Response from `GET /api/ThirdPartyIbPureTermLookup/get-rider-details`.
35
+ *
36
+ * Optional pre-quote step that filters available Pure Term riders by state, age,
37
+ * and nicotine use. When `flagProductNotAvailableForState` is `true`, the
38
+ * `riders` array is empty and Pure Term is not available for the given inputs —
39
+ * do not proceed to the Quote API.
40
+ *
41
+ * Shape is identical to the IB Term rider lookup response; the two products
42
+ * differ only in endpoint path and underlying availability rules.
43
+ */
44
+ export interface PureTermRiderDetailsResp {
45
+ /**
46
+ * `true` → Pure Term not available for the given `stateCode` / `age` /
47
+ * `flagNicotineUse` combination (e.g. WY, NY); the SDK returns this response
48
+ * as-is (it is a valid business state, not an error).
49
+ *
50
+ * `false` → Pure Term is available; `riders` lists the eligible rider options
51
+ * (may still be empty if no optional riders are configured for the combo).
52
+ */
53
+ flagProductNotAvailableForState: boolean;
54
+ /** Available riders for the state/age/nicotine combo. */
55
+ riders: PureTermRider[];
56
+ }
3
57
  /**
4
58
  * Request body for `POST /api/ThirdPartyIbPureTermQuote/get`.
5
59
  *
6
60
  * Source of truth: ThirdPartyTermQuoteRequest.cs (InstaPureTerm product).
7
61
  *
8
- * **Validation rules (enforced server-side):**
9
- * - `benefitPeriod` is required.
10
- * - **One rating input group is required** — supply ONE of:
11
- * (a) `rateClass`, OR
12
- * (b) `healthClass`, OR
13
- * (c) `height` + `weightInLbs` (both together).
14
- * - `age` OR `dateOfBirth` required; resolved age must be 18–60. When both
15
- * are provided, `dateOfBirth` takes priority.
16
- * - `stateCode` required.
62
+ * Pure Term uses the **same request shape and validation model as IB Term**;
63
+ * what differs is the product data — rate classes (which add Rated C / Rated D),
64
+ * term lengths (which add 15), and the coverage / benefit-period tables.
65
+ *
66
+ * **Validation rules, in the order the server checks them:**
67
+ * 1. `benefitPeriod` is required.
68
+ * 2. `stateCode`, when present, must be a state where Pure Term is available
69
+ * (not available in WY / NY).
70
+ * 3. At least one of `rateClass`, `healthClass`, or (`height` **and**
71
+ * `weightInLbs`) must be provided.
72
+ * 4. `rateClass`, when present, must be a valid Pure Term rate class.
73
+ * 5. `healthClass`, when present, must be valid.
74
+ * 6. `height` / `weightInLbs`, when present, must be a valid combination.
75
+ * 7. Age — derived from `dateOfBirth` when present, else `age` — must be 18–60
76
+ * inclusive.
77
+ * 8. `riders`, when present, must be valid for Pure Term.
78
+ * 9. When `stateCode` and (`age` or `dateOfBirth`) are present, `benefitPeriod`
79
+ * is checked against carrier availability (`BenefitPeriodNotAvailable`) and
80
+ * `faceAmount` against coverage rules (`CoverageNotAvailable`).
81
+ *
82
+ * **Error surfacing happens in two stages.** Request validation issues dedicated
83
+ * top-level codes only for `BenefitPeriodNotAvailable` and
84
+ * `CoverageNotAvailable`; every other failure at that stage — including an
85
+ * invalid rate class — surfaces as `InvalidRequestFormat` with a PascalCase
86
+ * field key under `value.fields`, at most one message per field.
87
+ *
88
+ * Once validation passes, the request runs through the shared quote-eligibility
89
+ * pipeline, which can still return top-level `NotAvailableForState`,
90
+ * `QuoteNotEligibleForGivenConditions`, `RiderNotAvailable`,
91
+ * `RiderFaceAmountNotValid`, or `outsideBuildChart`. Handle the full IB Term
92
+ * code set — do not assume those never occur for Pure Term.
17
93
  */
18
94
  export interface ThirdPartyPureTermQuoteReq {
19
95
  /**
20
- * Coverage amount in dollars.
21
- * Age-based limits apply — same schedule as IB Term.
22
- */
23
- faceAmount?: number | null;
24
- /** Term length in years. **Required.** Available: 10, 20, 30 (state/age/tobacco dependent). */
25
- benefitPeriod?: number | null;
26
- /** Whether the applicant uses tobacco or nicotine. */
27
- flagTobaccoUse: boolean;
28
- /** Applicant gender. */
29
- gender?: Gender | null;
30
- /** 2-letter US state code. Required. */
31
- stateCode?: string | null;
32
- /** Rate class — one of the three rating groups (†). */
96
+ * Coverage amount in dollars. **Required.**
97
+ *
98
+ * Allowed range depends on state, age, and nicotine use:
99
+ * up to age 55 — $50,000–$1,000,000; age 56 — max $900,000;
100
+ * 57 — $800,000; 58 — $700,000; 59 — $600,000; 60 — $500,000.
101
+ * Out-of-range values return `CoverageNotAvailable`.
102
+ */
103
+ faceAmount: number;
104
+ /**
105
+ * Term length in years. **Required.**
106
+ *
107
+ * Availability by age and nicotine use:
108
+ * ages 18–45 → 10, 15, 20, 30; ages 46–50 non-smoker → 10, 15, 20, 30;
109
+ * ages 46–50 smoker → 10, 15, 20; ages 51–60 → 10, 15, 20.
110
+ * Disallowed values return `BenefitPeriodNotAvailable`.
111
+ *
112
+ * Note 15 is a Pure-Term-only term length — IB Term offers 10 / 20 / 30.
113
+ */
114
+ benefitPeriod: number;
115
+ /** Applicant gender. **Required.** */
116
+ gender: Gender;
117
+ /**
118
+ * 2-letter US state code (e.g. "TX"). **Required.**
119
+ *
120
+ * Pure Term is not available in WY or NY. Send `stateCode` only — do **not**
121
+ * send `zipCode` on the Pure Term quote.
122
+ */
123
+ stateCode: string;
124
+ /** Payment frequency. **Required.** */
125
+ paymentFreq: PaymentFrequency;
126
+ /**
127
+ * Whether the applicant uses tobacco or nicotine.
128
+ * Defaults to `false` server-side when omitted.
129
+ */
130
+ flagTobaccoUse?: boolean | null;
131
+ /**
132
+ * Rate class — one of the three rating groups.
133
+ *
134
+ * Pure Term does **not** offer `Guaranteed`, unlike the general IB Term list.
135
+ * An invalid value returns `InvalidRequestFormat` with the field message
136
+ * "Rate class is invalid. Allowed values: Preferred Plus, Preferred, Standard,
137
+ * Standard Extra, Rated C, Rated D."
138
+ */
33
139
  rateClass?: PureTermRateClass | null;
34
- /** Health class — one of the three rating groups (†). */
140
+ /** Health class — one of the three rating groups. Case-insensitive server-side. */
35
141
  healthClass?: HealthClass | null;
36
142
  /**
37
143
  * Applicant height. Required together with `weightInLbs` when using the
38
144
  * height/weight rating path. Omit when rating via `rateClass` or `healthClass`.
145
+ * `feet` must be 1–8 and `inches` 0–11.
39
146
  */
40
147
  height?: ThirdPartyQuoteReqHeight | null;
41
148
  /** Applicant weight in lbs. Required together with `height`. */
42
149
  weightInLbs?: number | null;
43
150
  /** Applicant age (18–60). Provide `age` OR `dateOfBirth`. */
44
151
  age?: number | null;
45
- /** Applicant date of birth (ISO 8601). Takes priority over `age` when both are provided. */
152
+ /**
153
+ * Applicant date of birth (ISO 8601, e.g. `1990-10-10`). Must be in the past.
154
+ * Takes priority over `age` when both are provided.
155
+ */
46
156
  dateOfBirth?: string | null;
47
- /** Riders to include. Use `riderCode` values returned by the rider lookup endpoint. */
157
+ /**
158
+ * Riders to include. Omit or send `null` to quote without riders — the array is
159
+ * validated only when sent. Use `riderCode` values from
160
+ * {@link PureTermRiderDetailsResp}. A rider's face amount must not exceed
161
+ * `faceAmount`. Typical ranges: ADB Rider $25,000–$250,000;
162
+ * Dependent Child Rider $5,000–$25,000.
163
+ */
48
164
  riders?: ThirdPartyQuoteReqRider[] | null;
49
- /** Payment frequency. */
50
- paymentFreq?: PaymentFrequency | null;
51
- /** First name — alphabetic only. Lead capture. */
165
+ /** First name — alphabetic only when provided. Lead capture. */
52
166
  firstName?: string | null;
53
- /** Last name — alphabetic only. Lead capture. */
167
+ /** Last name — alphabetic only when provided. Lead capture. */
54
168
  lastName?: string | null;
55
- /** Email address. Lead capture. */
169
+ /** Email address — validated only when provided. Lead capture. */
56
170
  email?: string | null;
57
- /** Phone number — 10-digit local or E.164 format. Lead capture. */
171
+ /**
172
+ * Phone number — 10 digits or `+1XXXXXXXXXX` when provided. Formatted on
173
+ * success. Lead capture.
174
+ */
58
175
  phoneNum?: string | null;
59
176
  }
177
+ /**
178
+ * Request shape for the Pure Term Get Existing Quote lookup
179
+ * (`GET /api/ThirdPartyIbPureTermQuote/get-existing-quote?opportunityId={guid}`).
180
+ *
181
+ * The `getPureTermExistingQuote()` facade takes a plain `opportunityId` string to
182
+ * match the IB Term / ADB / GIGDB convention; this interface is exported for
183
+ * callers who prefer to type their own request object. `opportunityId` must be a
184
+ * valid UUID.
185
+ */
186
+ export interface PureTermGetExistingQuoteRequest {
187
+ opportunityId: string;
188
+ }
189
+ /**
190
+ * Request body for `POST /api/ThirdPartyPureTermApplication/start-application`.
191
+ *
192
+ * The backend shares one request contract between IB Term and Pure Term
193
+ * start-application — same fields, same nesting, same optionality, same
194
+ * validation messages. This alias exists so Pure Term integrations read
195
+ * naturally; it is structurally the same type as
196
+ * {@link IBTermStartApplicationReq}, not a divergent shape.
197
+ *
198
+ * **Pure Term differences are behavioral, not structural:**
199
+ * - `quoteResponseId` must come from a Pure Term quote and belong to the Pure
200
+ * Term product, otherwise: "QuoteResponseId does not exist or does not belong
201
+ * to the requested product."
202
+ * - `childRiderInfo` is required only when the Dependent Child Rider was selected
203
+ * on the originating quote, and must **not** be sent otherwise — sending it
204
+ * without the rider fails with "Child rider was not included in the quote.
205
+ * Cannot add child rider details."
206
+ * - `tobaccoNicotineUsage.cigarUsagePerYear` is required only when
207
+ * `productTypesUsed` is **exactly** `['cigars']`. When cigars are selected
208
+ * alongside other product types it is not required.
209
+ * - `physicianDetails.stateCode` rejects both `"Outside Of The USA"` and
210
+ * `"OutsideUSA"`.
211
+ * - Pure Term does **not** run the `ApplicationLimitReached` duplicate
212
+ * SSN/email/phone check (that applies to ADB / GIGDB / Final Expense).
213
+ */
214
+ export type PureTermStartApplicationReq = IBTermStartApplicationReq;
@@ -2,7 +2,15 @@
2
2
  * Extract an error code from an API response.
3
3
  *
4
4
  * 1. Checks `response.errorCode` first (structured field).
5
- * 2. Falls back to scanning `response.error` string for known error code substrings.
5
+ * 2. Then an exact match against `response.error`.
6
+ * 3. Falls back to scanning `response.error` for known error codes as
7
+ * substrings, preferring the **longest** match.
8
+ *
9
+ * The longest-match rule matters because several codes are prefixes of others —
10
+ * e.g. `PaymentDeclined` is contained in both `PaymentDeclinedPermanent` and
11
+ * `PaymentDeclinedContactBank`. Returning the first match in enum-declaration
12
+ * order would silently report the less specific code, breaking `isErrorType()`
13
+ * and `getUserFriendlyMessage()` for the more specific one.
6
14
  *
7
15
  * @returns The error code string if found, `null` otherwise.
8
16
  */
@@ -11,7 +11,15 @@ const ALL_KNOWN_ERROR_CODES = Object.values(enums_1.APIErrorCode);
11
11
  * Extract an error code from an API response.
12
12
  *
13
13
  * 1. Checks `response.errorCode` first (structured field).
14
- * 2. Falls back to scanning `response.error` string for known error code substrings.
14
+ * 2. Then an exact match against `response.error`.
15
+ * 3. Falls back to scanning `response.error` for known error codes as
16
+ * substrings, preferring the **longest** match.
17
+ *
18
+ * The longest-match rule matters because several codes are prefixes of others —
19
+ * e.g. `PaymentDeclined` is contained in both `PaymentDeclinedPermanent` and
20
+ * `PaymentDeclinedContactBank`. Returning the first match in enum-declaration
21
+ * order would silently report the less specific code, breaking `isErrorType()`
22
+ * and `getUserFriendlyMessage()` for the more specific one.
15
23
  *
16
24
  * @returns The error code string if found, `null` otherwise.
17
25
  */
@@ -20,11 +28,18 @@ function extractErrorCode(response) {
20
28
  return response.errorCode;
21
29
  }
22
30
  if (response.error && typeof response.error === 'string') {
31
+ const errorText = response.error;
32
+ // An exact match is unambiguous — take it before any substring scanning.
33
+ if (ALL_KNOWN_ERROR_CODES.includes(errorText)) {
34
+ return errorText;
35
+ }
36
+ let longestMatch = null;
23
37
  for (const code of ALL_KNOWN_ERROR_CODES) {
24
- if (response.error.includes(code)) {
25
- return code;
38
+ if (errorText.includes(code) && (longestMatch === null || code.length > longestMatch.length)) {
39
+ longestMatch = code;
26
40
  }
27
41
  }
42
+ return longestMatch;
28
43
  }
29
44
  return null;
30
45
  }