@moneylion/engine-api 1.0.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.
@@ -0,0 +1,220 @@
1
+ import { object, array, union, intersection, oneOf, constant, string, optional as optionalUndefined, number, boolean, } from "@mojotech/json-type-validation";
2
+ const optional = (d) => union(optionalUndefined(d), constant(null));
3
+ export const cardPurposeDecoder = union(constant("balance_transfer"), constant("cash_back"), constant("earning_rewards"), constant("improve_credit"), constant("low_interest"), constant("new_to_credit"), constant("student"), constant("travel_incentives"));
4
+ export const termUnitDecoder = union(constant("day"), constant("month"), constant("year"), constant("open"));
5
+ export const introOfferTypeDecoder = union(constant("miles"), constant("points"), constant("statement_credit"));
6
+ export const cardTypeDecoder = union(constant("visa"), constant("mastercard"), constant("american_express"), constant("discover"));
7
+ export const providedCreditRatingDecoder = union(constant("excellent"), constant("good"), constant("fair"), constant("poor"), constant("limited"), constant("unknown"));
8
+ export const cardBenefitDecoder = oneOf(constant("No Foreign Transaction Fees"), constant("Purchase Protection"), constant("Return Protection"), constant("Price Protection"), constant("Fraud Protection"), constant("Extended Warranty"), constant("Travel Accident Insurance"), constant("Trip Interruption Insurance"), constant("Car Rental Insurance"), constant("Baggage Insurance"), constant("Baggage Delay Insurance"), constant("Hotel Burglary Insurance"), constant("Travel & Emergency Assistance"), constant("Roadside Assistance"), constant("Concierge Service"), constant("Lounge Access"), constant("Identity Theft Assistance"), constant("In-Flight Savings"), constant("Free Checked Bag"), constant("Priority Boarding"), constant("No Blackout Dates"), constant("Free Companion Ticket"), constant("Discount Companion Ticket"), constant("Global Entry or TSA PreCheck"), constant("Private Jet Perks"), constant("Lounge Access Discount"), constant("24/7 Cardholder Support"), constant("Authorized User"), constant("Entertainment Access"), constant("Airline Fee Credit"), constant("Late Fee Pass"), constant("Credit Score Reporting"), constant("No Flight Change Fees"), constant("24/7 Account Monitoring"), constant("Amex Offers"), constant("Visa Signature Offers"), constant("MasterCard Offers"), constant("Free Hotel Stay"), constant("Extended Hotel Stay"), constant("Dining Concierge"), constant("2 Lounge Passes"), constant("Hilton Honors Silver Membership"), constant("Hilton Honors Gold Membership"), constant("World of Hyatt Discoverist Status"), constant("SPG Gold Membership"), constant("Marriott Rewards Silver Status"), constant("Hertz Presidents Circle Elite Status"), constant("2 Free Checked Bags"), constant("Auto Discounts"), constant("InCircle Partnership"), constant("ShopRunner"), constant("WiFi Access"), constant("ShopSafe"), constant("BoA Preferred Rewards"), constant("MasterCard Fuel Rewards Network"), constant("Missed Event Ticket Protection"), constant("Account Freezing"), constant("Cell Phone Protection"), constant("GPA Rewards"), constant("In-Flight WiFi Credit"), constant("Citi Private Pass"), constant("Priceless Cities"), constant("The Hotel Collection"), constant("By Invitation Only"), constant("Luxury Hotel Collection"), constant("Expedia+ Silver Status"), constant("Expedia+ Gold Status"), constant("$100 American Airlines Discount"), constant("Disney Parks Perks and Savings"), constant("Ritz-Carlton Gold Elite Status"), constant("Ritz-Carlton Club Level Upgrade"), constant("Annual Travel Credit"), constant("IHG Platinum Elite Status"), constant("QuickBooks Connect"), constant("ReceiptMatch"), constant("Employee Spending Limits"), constant("FX International Payments"), constant("No Pre-Set Spending Limit"), constant("Purchase Financing"), constant("Amex Open Savings"), constant("Amazon Special Financing"), constant("$100 Ritz-Carlton Hotel Credit"), constant("British Airways Companion Ticket"), constant("Mercedes-Benz Gift Certificates"), constant("Mercedes-Benz Excess Mileage Waiver"), constant("JetBlue Annual Statement Credit"), constant("20% Discount on Delta Flights for Delta Private Jet Members"), constant("Expense Report Features"), constant("Business Cell Phone Protection"), constant("Free Shipping on most Target.com orders"), constant("30 Extra Days for Returns"), constant("Free clothing altertaions"), constant("Personal shopping"), constant("Shopmyway Savings"), constant("Online Subscription Credit"), constant("Uber Exclusive Access"), constant("Airline Benefits"), constant("Hotel Benefits"), constant("Other Travel Benefits"), constant("Emergency Assistance"), constant("Experiences"), constant("Shopping Benefits"), constant("Cardholder Benefits"), constant("Enhanced Security"), constant("Business Benefits"), constant("Other Benefits"), constant("In-Flight Discounts"), constant("Fee Coverage"), constant("Flight Credits & Discounts"), constant("Hotel Membership Status"), constant("Hotel Credit & Free Stays"), constant("Travel Credit"), constant("Travel Experiences Programs"), constant("Car Rental Membership Status"), constant("Extra Gas Rewards"), constant("Shopping Protection"), constant("Shopping Discounts"), constant("Free Shipping"), constant("The Boingo American Express Preferred Plan"), constant("AirSpace Lounge"), constant("Uber Monthly Credit"), constant("Ride Share Benefits"), constant("Delta Sky Club"), constant("Admirals Club Membership"), constant("Priority Pass Select Membership (Prestige)"), constant("Priority Pass Select Membership (Standard Plus)"), constant("Daily Breakfast"), constant("Early Check-in & Late Check-out"), constant("Room Upgrades"), constant("Complementary WiFi"), constant("Amex Hotel Collection Credit"), constant("Temporary Account Numbers"), constant("One-Time 50% Discount on Companion Ticket"), constant("Airline Travel Credit"), constant("United Club Membership"), constant("Chip Technology"), constant("Earn More Miles for Sharing Travel Stories"), constant("Mastercard World Elite Concierge and Luxury Travel Benefits"), constant("20% Savings on Delta In-Flight Purchases"), constant("25% Savings on United In-Flight Food and Drink Purchases"), constant("$100 Hilton Properties Credit"), constant("$250 Hilton Resort Credit"), constant("Hilton Honors Diamond Membership"), constant("Free Birthday Gift"), constant("2x Points During Your Birthday Month"), constant("Car Rental VIP Perks"), constant("Free shipping with the purchase of a bra"), constant("Monthly Dining Credit"), constant("Amazon Prime Student"));
9
+ export const creditCardOfferDetailsDecoder = object({
10
+ cardName: optional(string()),
11
+ cardImageUrl: string(),
12
+ cardPurposes: optional(array(cardPurposeDecoder)),
13
+ ratesUrl: optional(string()),
14
+ maxPurchaseApr: optional(number()),
15
+ minPurchaseApr: optional(number()),
16
+ purchaseAprText: optional(string()),
17
+ maxPurchaseIntroApr: optional(number()),
18
+ minPurchaseIntroApr: optional(number()),
19
+ purchaseIntroAprTerm: optional(number()),
20
+ purchaseIntroAprTermUnit: optional(termUnitDecoder),
21
+ purchaseIntroAprText: optional(string()),
22
+ maxCashAdvanceApr: optional(number()),
23
+ minCashAdvanceApr: optional(number()),
24
+ cashAdvanceAprText: optional(string()),
25
+ maxCashAdvanceIntroApr: optional(number()),
26
+ minCashAdvanceIntroApr: optional(number()),
27
+ cashAdvanceIntroAprTerm: optional(number()),
28
+ cashAdvanceIntroAprTermUnit: optional(termUnitDecoder),
29
+ cashAdvanceIntroAprText: optional(string()),
30
+ maxBalanceTransferApr: optional(number()),
31
+ minBalanceTransferApr: optional(number()),
32
+ balanceTransferAprText: optional(string()),
33
+ maxBalanceTransferIntroApr: optional(number()),
34
+ minBalanceTransferIntroApr: optional(number()),
35
+ balanceTransferIntroAprTerm: optional(number()),
36
+ balanceTransferIntroAprTermUnit: optional(termUnitDecoder),
37
+ balanceTransferIntroAprText: optional(string()),
38
+ maxAnnualFee: optional(number()),
39
+ minAnnualFee: optional(number()),
40
+ annualIntroFee: optional(number()),
41
+ annualIntroFeeTerm: optional(number()),
42
+ introOfferAmount: optional(number()),
43
+ introOfferText: optional(string()),
44
+ introOfferType: optional(introOfferTypeDecoder),
45
+ details: optional(array(string())),
46
+ additionalDetails: optional(array(string())),
47
+ cardType: cardTypeDecoder,
48
+ minimumCreditLine: optional(number()),
49
+ minimumPenaltyApr: optional(number()),
50
+ maximumPenaltyApr: optional(number()),
51
+ balanceTransferFee: optional(number()),
52
+ cashAdvanceFee: optional(number()),
53
+ lateFee: optional(number()),
54
+ foreignExchangeFee: optional(number()),
55
+ accountOpeningFee: optional(number()),
56
+ returnPaymentFee: optional(number()),
57
+ monthlyServiceFee: optional(number()),
58
+ recommendedCreditRatings: optional(array(providedCreditRatingDecoder)),
59
+ preQualified: boolean(),
60
+ preApproved: boolean(),
61
+ preSelected: boolean(),
62
+ foreignTransactionFee: optional(number()),
63
+ cardBenefits: optional(array(cardBenefitDecoder)),
64
+ });
65
+ export const partnerDecoder = object({
66
+ uuid: string(),
67
+ name: string(),
68
+ description: string(),
69
+ disclaimer: string(),
70
+ supportsPreSelect: boolean(),
71
+ shouldDisplayPreSelect: boolean(),
72
+ supportsPersonalizedOffers: boolean(),
73
+ imageUrl: string(),
74
+ subtextOverride: optional(string()),
75
+ });
76
+ export const productTypeDecoder = union(constant("credit_card"), constant("insurance"), constant("life_insurance"), constant("loan"), constant("mortgage"), constant("savings"), constant("other"));
77
+ export const productSubTypeDecoder = oneOf(constant("credit_card"), constant("secured_card"), constant("personal_loan"), constant("secured_loan"), constant("student_loan_refinance"), constant("co_applicant_loan"), constant("line_of_credit"), constant("automobile_refinance"), constant("home_equity_line_of_credit"), constant("purchase"), constant("refinance"), constant("savings_account"), constant("money_market_account"), constant("certificate_of_deposit"), constant("individual_retirement_account"), constant("cash_management_account"), constant("high_interest_checking"), constant("checking"), constant("accidental_death_benefits"), constant("term_life"), constant("term_life_instant"), constant("whole_life"), constant("debt_relief"), constant("installment_loans"), constant("credit_builder"), constant("cash_advance"), constant("credit_repair"), constant("education_offers"), constant("employment_opportunity"), constant("financial_wellness"), constant("direct_affiliate"), constant("overdraft_protection"), constant("revenue_based_financing"), constant("uncategorized"));
78
+ export const offerDecoder = object({
79
+ uuid: string(),
80
+ partner: partnerDecoder,
81
+ marketplace: optional(partnerDecoder),
82
+ productType: productTypeDecoder,
83
+ productSubType: productSubTypeDecoder,
84
+ url: string(),
85
+ recommendationScore: optional(number()),
86
+ disclaimer: optional(string()),
87
+ productSubTypeDisclaimer: optional(string()),
88
+ expiresAt: optional(string()),
89
+ });
90
+ export const creditCardOfferDecoder = intersection(object({
91
+ details: creditCardOfferDetailsDecoder,
92
+ }), offerDecoder);
93
+ export const originatorImageDecoder = object({
94
+ sizeKey: string(),
95
+ url: string(),
96
+ });
97
+ export const originatorDecoder = object({
98
+ key: string(),
99
+ name: string(),
100
+ description: optional(string()),
101
+ images: array(originatorImageDecoder),
102
+ disclaimer: optional(string()),
103
+ companyUuid: optional(string()),
104
+ financialInstitutionUuid: optional(string()),
105
+ });
106
+ export const aprTypeDecoder = union(constant("variable"), constant("regular"), constant("fixed"));
107
+ export const loanOfferDecoder = object({
108
+ uuid: string(),
109
+ productType: productTypeDecoder,
110
+ productSubType: productSubTypeDecoder,
111
+ productSubTypeDisclaimer: optional(string()),
112
+ url: optional(string()),
113
+ originator: originatorDecoder,
114
+ originatorId: optional(string()),
115
+ preQualified: boolean(),
116
+ preApproved: boolean(),
117
+ secured: boolean(),
118
+ coApplicant: boolean(),
119
+ sponsored: boolean(),
120
+ maxAmount: number(),
121
+ minAmount: optional(number()),
122
+ termLength: number(),
123
+ termUnit: termUnitDecoder,
124
+ displayTermUnit: optional(string()),
125
+ termDescription: optional(string()),
126
+ maxApr: optional(number()),
127
+ minApr: optional(number()),
128
+ meanApr: optional(number()),
129
+ aprType: aprTypeDecoder,
130
+ aprDescription: optional(string()),
131
+ feeRate: optional(number()),
132
+ maxFeeRate: optional(number()),
133
+ minFeeRate: optional(number()),
134
+ feeFixed: optional(number()),
135
+ maxFeeFixed: optional(number()),
136
+ minFeeFixed: optional(number()),
137
+ allowPrepayment: boolean(),
138
+ prepaymentFee: optional(number()),
139
+ monthlyPayment: optional(number()),
140
+ maxMonthlyPayment: optional(number()),
141
+ minMonthlyPayment: optional(number()),
142
+ monthlyPaymentDescription: optional(string()),
143
+ meanMonthlyPayment: optional(number()),
144
+ maxTotalPayment: optional(number()),
145
+ minTotalPayment: optional(number()),
146
+ meanTotalPayment: optional(number()),
147
+ recommendationScore: optional(number()),
148
+ payout: optional(number()),
149
+ conversionProbability: optional(number()),
150
+ terms: optional(string()),
151
+ amountPrefix: optional(string()),
152
+ });
153
+ export const mortgageLoanTypeDecoder = union(constant("fifteen_year_fixed"), constant("thirty_year_fixed"), constant("five_one_adjustable"), constant("seven_one_adjustable"), constant("ten_one_adjustable"));
154
+ export const mortgageAdjustmentTypeDecoder = union(constant("credits"), constant("par"), constant("points"));
155
+ export const mortageOfferDetailsDecoder = object({
156
+ interestRate: number(),
157
+ loanType: mortgageLoanTypeDecoder,
158
+ priceAdjustment: number(),
159
+ monthlyPayment: number(),
160
+ netClosingCosts: number(),
161
+ apr: number(),
162
+ loanTerm: number(),
163
+ adjustmentType: mortgageAdjustmentTypeDecoder,
164
+ });
165
+ export const mortgageOfferDecoder = intersection(object({
166
+ details: mortageOfferDetailsDecoder,
167
+ }), offerDecoder);
168
+ export const compoundingMethodDecoder = union(constant("annually"), constant("continuous"), constant("daily"), constant("monthly"), constant("quarterly"), constant("semiAnnually"), constant("simple"), constant("weekly"));
169
+ export const federalInsuranceTypeDecoder = union(constant("fdic"), constant("ncua"));
170
+ export const savingsOfferDetailsDecoder = object({
171
+ name: optional(string()),
172
+ description: optional(string()),
173
+ details: optional(string()),
174
+ rate: optional(number()),
175
+ annualPercentYield: number(),
176
+ compoundingMethod: compoundingMethodDecoder,
177
+ introductoryPeriodMonths: optional(number()),
178
+ introductoryRate: optional(number()),
179
+ minimumDeposit: number(),
180
+ minimumDepositWithFees: optional(number()),
181
+ monthlyFee: number(),
182
+ checkWriting: optional(boolean()),
183
+ effectiveAsOf: string(),
184
+ federalInsuranceType: optional(federalInsuranceTypeDecoder),
185
+ });
186
+ export const savingsOfferDecoder = intersection(object({
187
+ details: savingsOfferDetailsDecoder,
188
+ }), offerDecoder);
189
+ export const specialOfferDecoder = object({
190
+ uuid: string(),
191
+ name: string(),
192
+ desc: string(),
193
+ url: string(),
194
+ partnerName: string(),
195
+ partnerImageUrl: string(),
196
+ recommendationScore: optional(number()),
197
+ payout: optional(number()),
198
+ productSubType: productSubTypeDecoder,
199
+ });
200
+ export const pendingResponseDecoder = object({
201
+ partner: partnerDecoder,
202
+ productTypes: array(productTypeDecoder),
203
+ });
204
+ export const rateTableDecoder = object({
205
+ uuid: string(),
206
+ leadUuid: string(),
207
+ loanAmount: optional(number()),
208
+ embedUrl: optional(string()),
209
+ partnerPageUrl: optional(string()),
210
+ creditCardOffers: array(creditCardOfferDecoder),
211
+ loanOffers: array(loanOfferDecoder),
212
+ mortgageOffers: array(mortgageOfferDecoder),
213
+ savingsOffers: array(savingsOfferDecoder),
214
+ specialOffers: array(specialOfferDecoder),
215
+ pendingOriginators: array(originatorDecoder),
216
+ pendingResponses: array(pendingResponseDecoder),
217
+ });
218
+ export const leadUuidDecoder = object({
219
+ uuid: string(),
220
+ });
@@ -0,0 +1,3 @@
1
+ export { Client } from "./client.js";
2
+ export * from "./leads.js";
3
+ export * from "./rate_tables.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Client } from "./client.js";
2
+ export * from "./leads.js";
3
+ export * from "./rate_tables.js";
@@ -0,0 +1,54 @@
1
+ import { AsyncRateTable, RateTable } from "./rate_tables.js";
2
+ import { components } from "./generated/schema";
3
+ export type LeadCreateData = components["schemas"]["LeadCreateData"];
4
+ /**
5
+ * The class used to manage leads.
6
+ * Both blocking and non-blocking methods are provided, depending on when you want to resolve the returned Rate Table.
7
+ */
8
+ export declare class Leads {
9
+ private client;
10
+ /**
11
+ * Create a new instance of the Leads class.
12
+ *
13
+ * @param host - A hostname used to construct a Client instance.
14
+ * @param auth_token - An authentication token used to construct a Client instance.
15
+ */
16
+ constructor(host: string, auth_token: string);
17
+ /**
18
+ * Create a new lead.
19
+ *
20
+ * @param lead - An object representing the required information to create a Lead.
21
+ *
22
+ * @returns AsyncRateTable
23
+ *
24
+ * @remarks
25
+ * This method returns an AsyncRateTable.
26
+ * Use the resolve method on the returned object to retrieve the final Rate Table.
27
+ */
28
+ create(lead: LeadCreateData): Promise<AsyncRateTable>;
29
+ /**
30
+ * Create a new lead, immediately resolving the final Rate Table.
31
+ *
32
+ * @param lead - An object representing the required information to create a Lead.
33
+ *
34
+ * @returns RateTable
35
+ *
36
+ * @remarks
37
+ * This method will immediately resolve the final Rate Table.
38
+ * This may mean waiting a significant amount of time before it is finalized.
39
+ * Only use this if you can handle waiting for that amount of time.
40
+ */
41
+ createBlocking(lead: LeadCreateData): Promise<RateTable>;
42
+ /**
43
+ * Update an existing lead, merging the given data with the already existing data.
44
+ *
45
+ * @param leadUuid - The UUID of the lead to be updated.
46
+ * @param lead - New lead data to merge into the lead.
47
+ *
48
+ * @returns lead uuid
49
+ *
50
+ * @remarks
51
+ * This method returns the UUID of the lead that was updated.
52
+ */
53
+ update(leadUuid: string, lead: LeadCreateData): Promise<string>;
54
+ }
package/dist/leads.js ADDED
@@ -0,0 +1,86 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Client } from "./client.js";
11
+ import { AsyncRateTable } from "./rate_tables.js";
12
+ import { leadUuidDecoder, rateTableDecoder } from "./decoders.js";
13
+ /**
14
+ * The class used to manage leads.
15
+ * Both blocking and non-blocking methods are provided, depending on when you want to resolve the returned Rate Table.
16
+ */
17
+ export class Leads {
18
+ /**
19
+ * Create a new instance of the Leads class.
20
+ *
21
+ * @param host - A hostname used to construct a Client instance.
22
+ * @param auth_token - An authentication token used to construct a Client instance.
23
+ */
24
+ constructor(host, auth_token) {
25
+ this.client = new Client(host, auth_token);
26
+ }
27
+ /**
28
+ * Create a new lead.
29
+ *
30
+ * @param lead - An object representing the required information to create a Lead.
31
+ *
32
+ * @returns AsyncRateTable
33
+ *
34
+ * @remarks
35
+ * This method returns an AsyncRateTable.
36
+ * Use the resolve method on the returned object to retrieve the final Rate Table.
37
+ */
38
+ create(lead) {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ const resp = yield this.client.post("leads/rateTables", lead);
41
+ const rateTable = rateTableDecoder.runWithException(resp);
42
+ const asyncRateTable = new AsyncRateTable({
43
+ rateTable,
44
+ client: this.client,
45
+ });
46
+ return asyncRateTable;
47
+ });
48
+ }
49
+ /**
50
+ * Create a new lead, immediately resolving the final Rate Table.
51
+ *
52
+ * @param lead - An object representing the required information to create a Lead.
53
+ *
54
+ * @returns RateTable
55
+ *
56
+ * @remarks
57
+ * This method will immediately resolve the final Rate Table.
58
+ * This may mean waiting a significant amount of time before it is finalized.
59
+ * Only use this if you can handle waiting for that amount of time.
60
+ */
61
+ createBlocking(lead) {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const resp = yield this.client.post("blocking/leads/rateTables", lead);
64
+ const rateTable = rateTableDecoder.runWithException(resp);
65
+ return rateTable;
66
+ });
67
+ }
68
+ /**
69
+ * Update an existing lead, merging the given data with the already existing data.
70
+ *
71
+ * @param leadUuid - The UUID of the lead to be updated.
72
+ * @param lead - New lead data to merge into the lead.
73
+ *
74
+ * @returns lead uuid
75
+ *
76
+ * @remarks
77
+ * This method returns the UUID of the lead that was updated.
78
+ */
79
+ update(leadUuid, lead) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const resp = yield this.client.patch(`leads/${leadUuid}`, lead);
82
+ const leadUuidResponse = leadUuidDecoder.runWithException(resp);
83
+ return leadUuidResponse.uuid;
84
+ });
85
+ }
86
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,231 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { describe, expect, test, beforeAll, afterEach, afterAll, } from "@jest/globals";
11
+ import { Leads } from "./leads";
12
+ import { setupServer } from "msw/node";
13
+ import { http, HttpResponse } from "msw";
14
+ import { AsyncRateTable } from "./rate_tables";
15
+ const testLeadData = {
16
+ personalInformation: {
17
+ firstName: "testFirst",
18
+ lastName: "testLast",
19
+ email: "test@test.com",
20
+ city: "New York",
21
+ state: "NY",
22
+ primaryPhone: "4842017710",
23
+ address1: "245 W 17th St",
24
+ zipcode: "10011",
25
+ dateOfBirth: "1987-01-01",
26
+ ssn: "222-33-4444",
27
+ },
28
+ personalReferenceInformation: {},
29
+ loanInformation: {
30
+ purpose: "credit_card_refi",
31
+ loanAmount: 10000,
32
+ },
33
+ sessionInformation: {
34
+ ipAddress: "x.x.x.x",
35
+ },
36
+ mortgageInformation: {
37
+ propertyStatus: "rent",
38
+ },
39
+ creditCardInformation: {},
40
+ savingsInformation: {},
41
+ creditInformation: {
42
+ providedCreditRating: "excellent",
43
+ },
44
+ financialInformation: {
45
+ employmentStatus: "employed",
46
+ employmentPayFrequency: "biweekly",
47
+ annualIncome: 100000,
48
+ },
49
+ employmentInformation: {
50
+ directDeposit: true,
51
+ },
52
+ legalInformation: {
53
+ consentsToFcra: true,
54
+ consentsToSms: false,
55
+ consentsToTcpa: true,
56
+ tcpaLanguage: 'By tapping "See my offers", I am consenting to MoneyLion sharing the information above with ML Enterprise Inc. and their network of financial services partners to see what offers I may receive for financial products and services, which may include debt relief, credit repair, credit monitoring or other related services.',
57
+ },
58
+ educationInformation: {
59
+ educationLevel: "bachelors",
60
+ },
61
+ coApplicantInformation: {},
62
+ healthInformation: {},
63
+ refinanceLoans: [],
64
+ identificationInformation: {},
65
+ productTypes: ["loan", "other"],
66
+ };
67
+ const fullRateTable = {
68
+ uuid: "full-rate-table-uuid",
69
+ leadUuid: "full-lead-uuid",
70
+ loanAmount: 10000,
71
+ creditCardOffers: [],
72
+ loanOffers: [],
73
+ mortgageOffers: [],
74
+ savingsOffers: [],
75
+ specialOffers: [
76
+ {
77
+ uuid: "full-special-offer-uuid",
78
+ name: "Mock Credit Builder Offer",
79
+ desc: "Description of the credit builder offer",
80
+ url: "https://offers.engine.tech/ref/d6888b75-5454-498c-8710-e4c22daaf64e",
81
+ partnerName: "Engine Demo Loans Demand Sub Account 1",
82
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account-wjksncio.svg",
83
+ recommendationScore: 10,
84
+ payout: 0.1,
85
+ productSubType: "credit_builder",
86
+ },
87
+ {
88
+ uuid: "full-special-offer-uuid-2",
89
+ name: "Mock Debt Relief Offer",
90
+ desc: "Description of the debt relief offer",
91
+ url: "https://offers.engine.tech/ref/567beb02-9230-4bad-b60a-b2311bad400b",
92
+ partnerName: "Engine Demo Loans Demand Sub Account 2",
93
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account_2-wjkurpux.svg",
94
+ recommendationScore: 10,
95
+ payout: 0.1,
96
+ productSubType: "debt_relief",
97
+ },
98
+ {
99
+ uuid: "full-special-offer-uuid-3",
100
+ name: "Mock Installment Loans Offer",
101
+ desc: "Description of the installment loans offer",
102
+ url: "https://offers.engine.tech/ref/ec88908d-bdee-4b5d-8c49-2268167ea3c5",
103
+ partnerName: "Engine Demo Loans Demand Sub Account 3",
104
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account_3-wjkuspug.svg",
105
+ recommendationScore: 10,
106
+ payout: 0.1,
107
+ productSubType: "installment_loans",
108
+ },
109
+ ],
110
+ pendingOriginators: [],
111
+ pendingResponses: [],
112
+ };
113
+ const pendingRateTable = {
114
+ uuid: "pending-rate-table-uuid",
115
+ leadUuid: "pending-lead-uuid",
116
+ loanAmount: 20000,
117
+ creditCardOffers: [],
118
+ loanOffers: [],
119
+ mortgageOffers: [],
120
+ savingsOffers: [],
121
+ specialOffers: [
122
+ {
123
+ uuid: "pending-special-offer-uuid",
124
+ name: "Mock Credit Builder Offer",
125
+ desc: "Description of the credit builder offer",
126
+ url: "https://offers.engine.tech/ref/d6888b75-5454-498c-8710-e4c22daaf64e",
127
+ partnerName: "Engine Demo Loans Demand Sub Account 1",
128
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account-wjksncio.svg",
129
+ recommendationScore: 10,
130
+ payout: 0.1,
131
+ productSubType: "credit_builder",
132
+ },
133
+ {
134
+ uuid: "pending-special-offer-uuid-2",
135
+ name: "Mock Debt Relief Offer",
136
+ desc: "Description of the debt relief offer",
137
+ url: "https://offers.engine.tech/ref/567beb02-9230-4bad-b60a-b2311bad400b",
138
+ partnerName: "Engine Demo Loans Demand Sub Account 2",
139
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account_2-wjkurpux.svg",
140
+ recommendationScore: 10,
141
+ payout: 0.1,
142
+ productSubType: "debt_relief",
143
+ },
144
+ {
145
+ uuid: "pending-special-offer-uuid-3",
146
+ name: "Mock Installment Loans Offer",
147
+ desc: "Description of the installment loans offer",
148
+ url: "https://offers.engine.tech/ref/ec88908d-bdee-4b5d-8c49-2268167ea3c5",
149
+ partnerName: "Engine Demo Loans Demand Sub Account 3",
150
+ partnerImageUrl: "https://s3.amazonaws.com/images.evenfinancial.com/logos/dev/engine_demo_loans_demand_sub_account_3-wjkuspug.svg",
151
+ recommendationScore: 10,
152
+ payout: 0.1,
153
+ productSubType: "installment_loans",
154
+ },
155
+ ],
156
+ pendingOriginators: [],
157
+ pendingResponses: [
158
+ {
159
+ partner: {
160
+ uuid: "partner-uuid",
161
+ name: "partner",
162
+ description: "partner-description",
163
+ disclaimer: "partner-disclaimer",
164
+ supportsPreSelect: false,
165
+ shouldDisplayPreSelect: false,
166
+ supportsPersonalizedOffers: false,
167
+ imageUrl: "partner-image",
168
+ },
169
+ productTypes: ["credit_card"],
170
+ },
171
+ ],
172
+ };
173
+ const doublePollUuid = "double-poll-uuid";
174
+ const testHost = "https://engine.com";
175
+ const token = "good_auth_token";
176
+ const patchLeadUuid = "patch-lead-uuid";
177
+ const patchLeadUuidResponse = "patch-lead-uuid-response";
178
+ const handlers = [
179
+ http.post(`${testHost}/blocking/leads/rateTables`, () => {
180
+ return new HttpResponse(JSON.stringify(fullRateTable), { status: 200 });
181
+ }),
182
+ http.post(`${testHost}/leads/rateTables`, () => {
183
+ return new HttpResponse(JSON.stringify(pendingRateTable), {
184
+ status: 200,
185
+ });
186
+ }),
187
+ http.get(`${testHost}/originator/rateTables/${pendingRateTable["uuid"]}`, () => {
188
+ return new HttpResponse(JSON.stringify(fullRateTable), {
189
+ status: 200,
190
+ });
191
+ }),
192
+ http.get(`${testHost}/originator/rateTables/${doublePollUuid}`, () => {
193
+ return new HttpResponse(JSON.stringify(pendingRateTable), {
194
+ status: 200,
195
+ });
196
+ }),
197
+ http.patch(`${testHost}/leads/${patchLeadUuid}`, () => {
198
+ return new HttpResponse(JSON.stringify({
199
+ uuid: patchLeadUuidResponse,
200
+ }));
201
+ }),
202
+ ];
203
+ const server = setupServer(...handlers);
204
+ describe("Leads", () => {
205
+ beforeAll(() => server.listen({
206
+ onUnhandledRequest: "error",
207
+ }));
208
+ afterEach(() => server.resetHandlers());
209
+ afterAll(() => server.close());
210
+ test("Blocking leads endpoint returns a resolved rate table", () => __awaiter(void 0, void 0, void 0, function* () {
211
+ const leads = new Leads(testHost, token);
212
+ const resp = yield leads.createBlocking(testLeadData);
213
+ expect(resp).toEqual(fullRateTable);
214
+ }));
215
+ test("Async leads endpoint returns an async rate table", () => __awaiter(void 0, void 0, void 0, function* () {
216
+ const leads = new Leads(testHost, token);
217
+ const resp = yield leads.create(testLeadData);
218
+ expect(resp).toBeInstanceOf(AsyncRateTable);
219
+ }));
220
+ test("Async leads endpoint can be further resolved to a final rate table", () => __awaiter(void 0, void 0, void 0, function* () {
221
+ const leads = new Leads(testHost, token);
222
+ const resp = yield leads.create(testLeadData);
223
+ const rateTable = yield resp.resolve();
224
+ expect(rateTable).toEqual(fullRateTable);
225
+ }));
226
+ test("Patch leads endpoint returns the uuid of the lead", () => __awaiter(void 0, void 0, void 0, function* () {
227
+ const leads = new Leads(testHost, token);
228
+ const resp = yield leads.update(patchLeadUuid, testLeadData);
229
+ expect(resp).toEqual(patchLeadUuidResponse);
230
+ }));
231
+ });
@@ -0,0 +1,45 @@
1
+ import { Client } from "./client.js";
2
+ import { FixedRateTable } from "./decoders.js";
3
+ export type RateTable = FixedRateTable;
4
+ export interface AsyncRateTableCtorArgs {
5
+ rateTable?: RateTable;
6
+ client?: Client;
7
+ uuid?: string;
8
+ host?: string;
9
+ auth_token?: string;
10
+ }
11
+ /**
12
+ * The class used to fetch rate tables from the Engine API.
13
+ * This class will handle polling the rate tables endpoint until the pending responses are fulfilled.
14
+ */
15
+ export declare class AsyncRateTable {
16
+ private rateTable?;
17
+ private client;
18
+ private uuid?;
19
+ /**
20
+ * Construct a new AsyncRateTable instance.
21
+ * @param rateTable - An existing Rate Table structure to start from.
22
+ * @param uuid - A UUID of an existing Rate Table to fetch.
23
+ * @param client - A Client instance to use for fetching the data.
24
+ * @param host - A host used to construct a Client instance if none is provided.
25
+ * @param auth_token - An authentication token used to construct a Client instance if none is provided.
26
+ *
27
+ * @remarks
28
+ * Either one of rateTable or uuid is required, but providing both is an error.
29
+ * Similarly, provide either a pre-constructed Client instance or the host and auth_token parameters to construct one but not both.
30
+ */
31
+ constructor({ rateTable, uuid, client, host, auth_token, }: AsyncRateTableCtorArgs);
32
+ /**
33
+ * Resolve the async Rate Table into a real Rate Table.
34
+ *
35
+ * @returns A Rate Table with no pending responses.
36
+ *
37
+ * @remarks
38
+ *
39
+ * This will only make a network request if one is required.
40
+ * A network request is required if only a UUID was provided to the constructor, or if the provided Rate Table has pending responses.
41
+ * This method will also poll the API every second until the returned Rate Table has no more pending responses.
42
+ */
43
+ resolve(): Promise<RateTable>;
44
+ private getRateTable;
45
+ }