/**
* Represents a book.
* @constructor
*/
function setStaticVars() {
if (mar.STATIC) return;
mar.STATIC = "Y";
mar.YES = "Y"; // some generic statics for yes
mar.NO = "N"; // and no
mar.NEEDED = 1; // the function is needed
mar.COMPLETE = 2; // complete
mar.NOTPOSSIBLE = 3; // not possible
mar.R = 1;
mar.L = 2;
mar.LOAN_TYPE_PURCHASE = "purchase";
mar.LOAN_TYPE_REFINANCE = "refinance";
mar.PROPERTY_TYPE_SFR = "sfr";
mar.PROPERTY_TYPE_CONDO = "condo";
mar.PROPERTY_TYPE_DUPLEX = "duplex";
mar.PROPERTY_TYPE_TRIPLEX = "triplex";
mar.PROPERTY_TYPE_FOURPLEX = "fourplex";
mar.PROPERTY_TYPE_OTHER = "other";
mar.COMMUNITY_OPTION_HIGH = "chigh";
mar.COMMUNITY_OPTION_LOW = "clow";
mar.COMMUNITY_OPTION_NONE = "non";
mar.LOAN_TERM_30 = "tol30";
mar.LOAN_TERM_20 = "tol20";
mar.LOAN_TERM_15 = "tol15";
mar.LOAN_TERM_10 = "tol10";
mar.OCCUPANCY_OCCUPIED_BY_ME = "occupancy_by_me";
mar.OCCUPANCY_PRIMARY = "occupancy_by_me";
mar.OCCUPANCY_2ND_HOME = "occupancy_secondhom";
mar.OCCUPANCY_INVESTMENT = "occupancy_investment";
mar.INCOMETYPE_W2 = "w2";
mar.INCOMETYPE_LLC = "llc";
mar.INCOMETYPE_CORP = "corp";
mar.INCOMETYPE_SOCIALSECURITY = "ssec";
mar.INCOMETYPE_DISABILIY = "dis";
mar.INCOMETYPE_CHILDSUPPORT = "child";
mar.INCOMETYPE_ALIMONY = "alimony";
mar.INCOMETYPE_PENSION = "pension";
mar.INCOMETYPE_NONE = "none";
mar.FREQ_WEEKLY = "weekly";
mar.FREQ_BIWEEKLY = "biweekly";
mar.FREQ_SEMIMONTHLY = "semimonthly";
mar.FREQ_HOURLY = "hourly";
mar.FREQ_MONTHLY = "monthly";
mar.FREQ_YEARLY = "yearly";
mar.MORTGAGEOPTION_SAME = "same";
mar.MORTGAGEOPTION_ADJ10 = "adj10";
mar.MORTGAGEOPTION_ADJ7 = "adj7";
mar.MORTGAGEOPTION_ADJ5 = "adj5";
mar.LESS10 = "less10";
mar.MORE10 = "more10";
mar.LESS24 = "less24";
mar.MORE24 = "more24";
mar.INCOME_BASED_REPAYMENTS = "ibr";
mar.DEFERRED_REPAYMENTS = "def";
mar.LTV = 93;
mar.COMPANY_OBJECTIVE = 99.5;
mar.PROGRAMME_CONVENTIONAL = "conv";
mar.PROGRAMME_FHA = "fha";
mar.PROGRAMME_VA = "va";
mar.PROGRAMME_HOMEREADY = "homeready";
mar.PROGRAMME_JUMBO = "jumbo";
mar.SALARY_FREQUENCY_WEEKLY = "weekly";
mar.SALARY_FREQUENCY_BIWEEKLY = "biweekly";
mar.SALARY_FREQUENCY_SEMIMONTHLY = "semimonthly";
mar.SALARY_FREQUENCY_HOURLY = "hourly";
mar.SALARY_FREQUENCY_MONTHLY = "monthly";
mar.SALARY_FREQUENCY_YEARLY = "yearly";
mar.MORTGAGENOTLISTED = "nl";
mar.MORTGAGEFREE = "free";
mar.MORTGAGE = "mortgage"
mar.HELOC = "heloc"
mar.APPLICANT_TYPE = {
SPOUSE : "spouse",
COBORROWER : "coborrower",
COBORROWER_NON_RESIDENT : "coborrower_nonresident"
};
mar.PIPELINE = {};
mar.PIPELINE.statuses_order = [1000,900,600,500,700,400,300,200,800,100,1100];
mar.PIPELINE.statuses = {
"1000" : {
title : "CTC",
description : "Clear to Close - file will leave underwriter and processor, and go to final QC and closing department",
color : "#ffffff",
bgcolor : "#cccccc",
sortorder : 100
},
"900" : {
title : "Processing",
description : "We has a goal of reaching 75% of files Clear to Close in 7 business days from this start date",
color : "#ffffff",
bgcolor : "#00cc00",
sortorder : 200
},
"600" : {
title : "In Underwriting",
description : "File is with the Underwriter awaiting approval",
color : "#ffffff",
bgcolor : "#347ba6",
sortorder : 300
},
"500" : {
title : "Ready to submit",
description : "High touch client, we are almost ready to send file into underwriting. Less than 3 conditions.",
color : "#ffffff",
bgcolor : "#00a7d1",
sortorder : 400
},
"700" : {
title : "Suspended",
description : "File is not approvable for the underwriter (yet)",
color : "#ffffff",
bgcolor : "#cc0000",
sortorder : 500
},
"400" : {
title : "Collecting",
description : "Client is interested in our proposal, and has taken action, but not enough for us to finalize.",
color : "#ffffff",
bgcolor : "#da8c09",
sortorder : 600
},
"300" : {
title : "Waiting to start",
description : "We spoke to client, made a plan based on their story, and gave client homework to do.",
color : "#ffffff",
bgcolor : "#0000cc",
sortorder : 700
},
"200" : {
title : "Lead received",
description : "We recently have received the clients information, but we have not spoken yet.",
color : "#ffffff",
bgcolor : "#008c4b",
sortorder : 800
},
"800" : {
title : "Pre Qualified",
description : "File has gone through underwriting, and is approved with conditions, a property contract is missing",
color : "#ffffff",
bgcolor : "#003300",
sortorder : 900
},
"100" : {
title : "Not Active",
description : "For multiple reasons",
color : "#cccccc",
bgcolor : "#ffffff",
sortorder : 1000
},
"1100" : {
title : "CLOSED",
description : "Closed",
color : "#ffffff",
bgcolor : "#cccccc",
sortorder : 1100
}
};
mar.PIPELINE.checklist = {}
mar.PIPELINE.checklist.sectionsorder = []; /* left for compatibility , was large */
mar.PIPELINE.checklist.sections = {}; /* left for compatibility , was large */
mar.PIPELINE.checklist.tasks = {} /* left for compatibility , was large */
mar.PIPELINE.xsd = {}
mar.PIPELINE.xsd.masks = {
ENCOMPASS_STARTED : 64,
ELAINE_STARTED : 2,
ELAINE_STARTED : 2,
//
ENC_FOL_INACTIVE : 8,
ENC_FOL_PROSPECT : 4,
ENC_FOL_ACTIVE : 16,
ENC_FOL_CLOSED : 32,
//
EL_MS_INACTIVE : 32,
EL_MS_PROBLEM : 16777216,
//
el_start : 2,
el_rev_start : 4,
el_com_nodoc : 8,
el_com_collecting : 16,
el_com_inactive : 32,
el_com_problem : (2097152*2*2*2),
//
flag_prob_credit : 2,
flag_prob_income : 4,
flag_prob_assets : 8,
flag_prob_liabilities : 16,
//
___id : "masks"
}
mar.PIPELINE.idd = function(item, appid) {
console.error(`idd`,item, appid);
if (MAR.getOpt(item,"encompassid","") !== "") return item.encompassid.substring(6);
if (MAR.getOpt(item,"vfolder","") === "closed") return `C${appid}`;
if (MAR.getOpt(item,"vfolder","") === "active") return `A${appid}`;
if (MAR.getOpt(item,"vfolder","") === "inactive") return `I${appid}`;
if (MAR.getOpt(item,"vfolder","") === "prospects") return `P${appid}`;
return `L${appid}`;
}
/**
*
VFOLDER INACTIVE PROSPECTS ACTIVE CLOSED OTHER
ENC FOLDER F 2 F 1 F 3 F 4 F (not 1234)
MILESTONES EL4 6+1 10 21 EL 0
EL5 6+2 11 22
6+3 12 23
7 13
8 14
9 15
16
17
18
19
20
#confluence:vfolder_asssignment calculation of vfolder
*/
mar.PIPELINE.logic = {};
mar.PIPELINE.logic.calcStatus = function({mo_pipeline, mo_folder, mo_flag, status, app}){
/**
* is this ENCOMPASS or ELAINE or BOTH
*/
let is_encompass = ((mo_pipeline & mar.PIPELINE.xsd.masks.ENCOMPASS_STARTED) > 0);
let is_elaine = ((mo_pipeline & mar.PIPELINE.xsd.masks.ELAINE_STARTED ) > 0);
/**
* Work out the FOLDER
*/
let folder = "other";
if (is_encompass === true) {
folder = "prospects"
}
if ((mo_folder & mar.PIPELINE.xsd.masks.ENC_FOL_INACTIVE) > 0) folder = "inactive";
else if ((mo_folder & mar.PIPELINE.xsd.masks.ENC_FOL_ACTIVE) > 0) folder = "active";
else if ((mo_folder & mar.PIPELINE.xsd.masks.ENC_FOL_CLOSED) > 0) folder = "closed";
else if ((mo_folder & mar.PIPELINE.xsd.masks.ENC_FOL_PROSPECT) > 0) folder = "prospects";
/**
* If necessary work this out on the basis of the actual statuses
*/
if ((mo_pipeline & mar.PIPELINE.xsd.masks.EL_MS_INACTIVE) > 0) folder = "inactive";
if ((mo_pipeline & mar.PIPELINE.xsd.masks.EL_MS_PROBLEM) > 0) folder = "inactive";
if (is_encompass === false) {
folder = "leads";
if (status && status.startsWith(`lead_`)) {
if (status === `lead_h`) folder = `coldadleads`;
if (status === `lead_w`) folder = `coldadleads`;
if (status === `lead_c`) folder = `coldadleads`;
if (status === `lead_d`) folder = `inactive`;
if (status === `lead_a`) folder = `leads`;
} else {
let f = MAR.getOpt(mar.PIPELINE.stages_ui, `${status}.f`, null);
if (f === `l`) folder = `leads`;
if (f === `p`) folder = `prospects`;
if (f === `a`) folder = `active`;
if (f === `c`) folder = `closed`;
if (f === `i`) folder = `inactive`;
}
}
if (status && status === "deleted") {
folder = "inactive";
}
if (status && status === "inuntil") {
folder = "inactive";
}
if (status && status === "paused") { /* encompass version of paused */
folder = "inactive";
}
if (status && MAR.getOpt(mar.PIPELINE.stages_ui, `${status}.c`,"") === "red") {
folder = "inactive";
}
if (status && status === "fun") {
folder = "closed";
}
/**
* applied
*/
let el_complete1003 = ((mo_pipeline & mar.PIPELINE.xsd.masks.el_com_nodoc) > 0);
return {
vfolder : folder,
el_complete1003 : el_complete1003,
is_encompass : is_encompass,
is_elaine : is_elaine,
mo_pipeline : mo_pipeline,
mo_folder : mo_folder,
mo_flag : mo_flag,
status : status
}
};
mar.fbmodel = function(s) {
/*
* fblchat|',chat_in_cnt,'|',chat_in_last)
*/
let S = (typeof s === "string") ? s.split("|") : [];
function cnt() {
return MAR.getOpt(S,"1",-1);
}
function lastchat() {
return MAR.getOpt(S,"2",-1);
}
return {
cnt : cnt,
last : lastchat,
lastchat : lastchat,
___id : "Model"
}
}
mar.PIPELINE.logic.calcShouldLeadStatusBeBumped = function(app) {
/**
* it is a advert lead
*/
let start_status = app.status;
let fbm = mar.fbmodel(app.fblead_model);
if (app.status.startsWith(`lead_c`)) {
if (app.origin3.startsWith(`landing_`)) app.status = `lead_w`;
if (app.origin3.startsWith(`fb_link_cac`)) app.status = `lead_w`;
if (fbm.cnt() > 0) app.status = `lead_w`;
if (app.badge !== '') app.status = `lead_w`;
}
else if (app.status.startsWith(`lead_w`)) {
}
console.log(`calcShouldLeadStatusBeBumped ${app.status} // ${start_status} // ${app.origin3}`);
if (app.status !== start_status) return true;
return false;
}
mar.PIPELINE.stages = {
adhoc_origin_lpdirect_joint : { mask : 0, cat : "preq", d : "started from joint landing page"},
adhoc_origin_lpdirect : { mask : 0, cat : "preq", d : "started from loan officer landing page"},
adhoc_origin_lpreferal_joint : { mask : 0, cat : "preq", d : "refered from joint landing page"},
adhoc_origin_lpreferal : { mask : 0, cat : "preq", d : "refered from loan officer landing page"},
adhoc_origin_loi_joint : { mask : 0, cat : "preq", d : "started from loi with a partner"},
adhoc_origin_loi : { mask : 0, cat : "preq", d : "started from loi"},
adhoc_origin_fb01 : { mask : 0, cat : "preq", d : "Client reponded to a Facebook Marketplace ad"},
adhoc_origin_prequalbot : { mask : 0, cat : "preq", d : "Client reponded to a Facebook Marketplace ad"},
adhoc_origin_adlink : { mask : 0, cat : "preq", d : "Client reponded to a Facebook Marketplace ad"},
//
en_start : { mask : 6, cat : "preq", d : "App started in Encompass" },
//
adhoc_origin_rev_webhook : { mask : 0, cat : "preq", d : "Started from encompass vi Webhook"},
adhoc_origin_rev_webhook_ready : { mask : 0, cat : "preq", d : "Client informed of Webhook application"},
//
el_rev_start : { mask : 2, cat : "preq", d : "Reverse webhook from Encompass" },
el_start : { mask : 1, cat : "preq", d : "App started in Elaine" },
//
adhoc_origin_com_lo_sent : { mask : 0, cat : "preq", d : "message sent to LO"},
adhoc_origin_com_re_sent : { mask : 0, cat : "preq", d : "Copy of loan invitation sent to REF Partner"},
adhoc_origin_com_cl_sent : { mask : 0, cat : "preq", d : "Invitation to open loan onine sent to client"},
//
adhoc_app_client_engaged : { mask : 0, cat : "preq", d : "Client engaged wth the app"},
adhoc_app_client_verified_tel : { mask : 0, cat : "preq", d : "Client verified their telephone number for the 1st time in the app"},
adhoc_app_whatsapp_selected : { mask : 0, cat : "preq", d : "Client verified their use of whatsapp in the app"},
adhoc_origin_com_cl_sms_sent : { mask : 0, cat : "preq", d : "Client was sent a sms with the link again after verification"},
//
adhoc_app_trig_chat1 : { mask : 0, cat : "preq", d : "Chat triggered"},
adhoc_app_trig_chat_submitted : { mask : 0, cat : "preq", d : "Chat triggered"},
adhoc_app_trig_chat_submitted_lo :
{ mask : 0, cat : "preq", d : "SumbChat triitted message sent to LO"},
//
el_com_nodoc : { mask : 3, cat : "preq", d : "App submitted in Elaine" },
el_com_collecting : { mask : 4, cat : "preq", d : "Data collection started in Elaine" },
el_com_initial_docs : { mask : 33, cat : "preq", d : "Initial docs uploaded in Elaine" },
en_prequal : { mask : 7, cat : "preq", d : "Inquiry / Prequal " },
en_b_prequal : { mask : 25, cat : "preq", d : "Builder prequal" },
en_b_review : { mask : 26, cat : "preq", d : "Builder review" },
en_appcomplete : { mask : 8, cat : "appcomplete", d: "Application complete" },
en_smr : { mask : 9, cat : "disclosed", d : "Sales manager review" },
en_disdesk : { mask : 10, cat : "disclosed", d : "Disclosure desk" },
en_loanpack : { mask : 11, cat : "opening", d : "Loan package" },
en_comsetup : { mask : 12, cat : "opening", d : "Compliance & set up" },
en_procacc : { mask : 13, cat : "processor", d : "Processor accepted" },
en_b_con_p_p : { mask : 27, cat : "processor", d : "Construction project prequal" },
en_b_con_p_r : { mask : 28, cat : "processor", d : "Construction project review" },
en_sub : { mask : 14, cat : "processor", d : "Submittal" },
en_initund : { mask : 15, cat : "processor", d : "Inital underwrite" },
en_cond_sub : { mask : 16, cat : "underwritten", d : "Conditional submitted" },
en_c2c : { mask : 17, cat : "c2c", d : "Clear to close" },
en_closch : { mask : 18, cat : "c2c", d : "Closing scheduled" },
en_docs : { mask : 19, cat : "c2c", d : "Docs out" },
en_b_con_fnd : { mask : 32, cat : "c2c", d : "Construction funding" },
en_b_con_pha : { mask : 31, cat : "c2c", d : "Construction phase" },
en_b_mod : { mask : 29, cat : "c2c", d : "Modification" },
en_funding : { mask : 30, cat : "aftersales", d : "Funding" },
en_shipping : { mask : 21, cat : "aftersales", d : "Shipping" },
en_purchasing : { mask : 22, cat : "aftersales", d : "Purchasing" },
en_completion : { mask : 23, cat : "aftersales", d : "Completion" },
flag_prob_credit : { mask : 1, cat : "", d : "" },
flag_prob_income : { mask : 2, cat : "", d : "" },
flag_prob_assets : { mask : 3, cat : "", d : "" },
flag_prob_liabilities : { mask : 4, cat : "", d : "" },
folder_test_train : { mask : 1, cat : "", d : "" },
folder_prospects : { mask : 2, cat : "", d : "" },
folder_prop_inactive : { mask : 3, cat : "", d : "" },
folder_active : { mask : 4, cat : "", d : "" },
folder_closed : { mask : 5, cat : "", d : "" },
folder_inactive : { mask : 3, cat : "", d : "" },
flag_tcpa_block : { mask : 5, cat : "", d : "" },
el_com_inactive : { mask : 5, cat : "", d : "" },
el_com_problem : { mask : 24, cat : "", d : "" }
}
mar.PIPELINE.stages_index = {};
for (let x in mar.PIPELINE.stages) {
let cat = mar.PIPELINE.stages[x].cat;
if (cat === "") continue;
if (cat in mar.PIPELINE.stages_index === false) mar.PIPELINE.stages_index[cat] = [];
mar.PIPELINE.stages_index[cat].push(x)
}
mar.PIPELINE.miletones_ui = {
preq : { name : "Inquiry / Prequal"},
appcomplete : { name : "Ready to disclose"},
// smr : { name : "Sales manager review"},
disclosed : { name : "Disclosure sent"},
opening : { name : "Opening"},
processor : { name : "Processor"},
underwritten : { name : "Underwritten"},
resub : { name : "Resubmitted"}, /// none
c2c : { name : "CTC"},
aftersales : { name : "After sales"},
};
/**
* db = docbot yes/no
* dr = daily report yes / no
*/
mar.PIPELINE.stages_ui = {
lead_d : { long : "Ad Drip" , f : "l" , name : "Ad. Drip Lead" , c : "red" , cat : "", so : 200, short : "Ad-Drip" },
lead_c : { long : "Ad Cold" , f : "l" , name : "Ad. Cold Lead" , c : "orangeAC" , cat : "", so : 7, short : "Ad-Cold" },
lead_w : { long : "Ad Warm" , f : "l" , name : "Ad. Warm Lead" , c : "yellow" , cat : "", so : 8, short : "Ad-Warm" },
lead : { long : "Referral" , f : "l" , name : "Referral" , c : "blueL" , cat : "", so : 10, short : "Referral" },
lead_a : { long : "Lead" , f : "l" , name : "Lead" , c : "blue2" , cat : "", so : 11, short : "Lead" },
// lead_h : { long : "Hot Lead" , f : "l" , name : "Hot Lead" , c : "greenAH" , cat : "", so : 9, short : "Hot Lead" },
// prq : { long : "No doc" , f : "l" , name : "File started - no docs" , c : "grey" , cat : "", so : 20, short : "Started" },
prq : { long : "Application" , f : "p" , name : "File started - no docs" , c : "blue" , cat : "", so : 20, short : "Started" , enc : true },
// paused : { long : "Paused" , f : "i" , name : "Paused" , c : "grey" , cat : "", so : 21, short : "Paused" },
// notstart : { long : "Not Start" , f : "l" , name : "Lead waiting to start" , c : "blue" , cat : "", so : 22, short : "NoStart" },
// offering : { long : "Offering" , f : "p" , name : "Prequalified lead making offers" , c : "grey" , cat : "", so : 24, short : "Offer" },
collect : { long : "Collecting" , f : "p" , name : "Lead collecting docs" , c : "blue1" , cat : "", so : 25, short : "Collect" , enc : true },
prequal : { long : "Prequal" , f : "p" , name : "Prequalified Lead" , c : "green" , cat : "", so : 27, short : "Prequal" , enc : true },
hot : { long : "4 submit" , f : "a" , name : "Ready to submit" , c : "yellow1" , cat : "", so : 30, short : "4 subm" , enc : true , nel : true},
rdy : { long : "4 Disc" , f : "a" , name : "Ready to Disclose" , c : "orange1" , cat : "", so : 40, short : "4 disc" , enc : true , nel : true }, //rename
// smr : { long : "MngReview" , f : "a" , name : "Sales manager review" , c : "orange1" , cat : "", so : 50, short : "MngRev" , nel : true},
dcl : { long : "Pkg Sent" , f : "a" , name : "Disclosuse sent" , c : "orange1" , cat : "", so : 60, short : "PkgSent" , enc : true , nel : true }, // rename
lpr : { long : "Pkg Rcvd" , f : "a" , name : "Signed Package recieved" , c : "purple" , cat : "", so : 70, short : "PkgRcvd" , enc : true , nel : true }, // new
opn : { long : "2 Process" , f : "a" , name : "Sent to processing" , c : "purple" , cat : "", so : 72, short : "2 Proc" , enc : true , dr :false }, // rename
prc : { long : "Processing" , f : "a" , name : "Processor accepted" , c : "purple" , cat : "", so : 80, short : "Procng" , enc : true , dr:false, hastle : true , limit : 3 },
sub : { long : "Submitted" , f : "a" , name : "Submitted" , c : "purple" , cat : "", so : 90, short : "Submit" , enc : true , limit : 3 , db:false},
iund : { long : "Underwriting" , f : "a" , name : "Initial Underwriting" , c : "purple" , cat : "", so : 100, short : "Ini UW" , enc : true , db:false },
apr : { long : "Approved" , f : "a" , name : "UW - Approved" , c : "green1" , cat : "", so : 100, short : "Approved" , enc : true , db:false },
sus : { long : "Suspended" , f : "a" , name : "UW - Suspended" , c : "red1" , cat : "", so : 110, short : "Suspnd" , enc : true , db:false },
wit : { long : "Withdrawn" , f : "a" , name : "UW - Withdrawn" , c : "red1" , cat : "", so : 112, short : "Withdrw" , enc : true , db:false },
can : { long : "Cancelled" , f : "a" , name : "UW - Cancelled" , c : "red1" , cat : "", so : 114, short : "Cancel" , enc : true , db:false },
rsub : { long : "Resubmit" , f : "a" , name : "Conditional Submitted" , c : "green1" , cat : "", so : 120, short : "ReSub" , enc : true , db:false },
c2c : { long : "c2c" , f : "a" , name : "Clear to Close" , c : "green1" , cat : "", so : 130, short : "C2C" , enc : true , db:false },
cls : { long : "Closing" , f : "c" , name : "Closing" , c : "green1" , cat : "", so : 140, short : "Closing" , enc : true , db:false },
fun : { long : "Funded" , f : "c" , name : "Funded" , c : "green1" , cat : "", so : 150, short : "Funded" , enc : true , db:false },
mia : { long : "No respon" , f : "i" , name : "No Response" , c : "red" , cat : "", so : 160, short : "NoResp" , db:false },
ncrt : { long : "No credit" , f : "i" , name : "Low Credit" , c : "red" , cat : "", so : 170, short : "NoCred" , db:false },
ncsh : { long : "Low CTC" , f : "i" , name : "Low Cash to Close" , c : "red" , cat : "", so : 180, short : "NoCash" , db:false },
ninc : { long : "No Inc" , f : "i" , name : "No Income" , c : "red" , cat : "", so : 190, short : "NoInc" , db:false },
den : { long : "Denied" , f : "i" , name : "Denied" , c : "red" , cat : "", so : 200, short : "Denied" , db:false },
inuntil : { long : "Pause Until" , f : "i" , name : "Paused Until" , c : "grey" , cat : "", so : 5, short : "Paused" , db:false },
deleted : { long : "Deleted" , f : "i" , name : "Delete" , c : "red" , cat : "", so : 300, short : "Delete" , db:false }
};
mar.PIPELINE.stages2_ui = {
PR : { long : "Prequal" , name : "Prequal" , c : "grey" , cat : "", so : 10 },
OF : { long : "Offering" , name : "Offering" , c : "yellow" , cat : "", so : 20 },
CO : { long : "Contract" , name : "Contract" , c : "green" , cat : "", so : 30 },
RE : { long : "Refi" , name : "Refi" , c : "blue" , cat : "", so : 40 }
};
mar.PIPELINE.flags_ui = {
ADVSNT : { long : "Advice Sent" , name : "AdviceSent" , c : "grey" , cat : "", so : 10 }
};
// LEAD - Incomplete Lead | Gray | Leads from Elaine, no complete 1003
// PRQ - Lead | Gray | Complete 1003, or came in through Encompass
// HOT - Hot Lead | Yellow | Any lead that is a refi, or offering or live
// RDY - Application Ready | Orange | Any lead where the milestone app ready is hit
// DCL - Disclosed | Orange | Any lead where the Sales Manager Review milestone is successfully hit
// OPN - Opening | Green | Any lead where the Signed Loan Package milestone is hit
// PRC - Processor | Green | Any lead where the Processor Accepted Milestone is hit
// SUB - Submittal | Green | Any lead where the Submittal Milestone is hit
// APR - Approved | Green | Any lead where Initial Underwrite milestone is hit, and status is Conditional Approval (not sure if you can get these)
// SUS - Suspended | Red | Any lead where the Initial Underwrite milestone is hit, and the status is Suspended (not sure if you can get these)
//
// RSUB - Conditional Submitted| Green | Any lead where the Conditional Submittal Milestone is hit |
// CTC - Clear to Close | Blue | Any lead where the Clear to Close milestone is hit
// CLS - Closed | Blue | Any lead where the Closed milestone is hit
// FUN - Funded | Blue | Any lead where the Funded milestone is hit
//
// MIA - No Response | Red | Any Incomplete lead, Lead, Hot Lead Application Ready can get this, move to Inactive Folder
// NCRT - Low Credit | Red | Any Incomplete lead, Lead, Hot Lead Application Ready can get this, move to Inactive Folder
// NCSH - Low Cash to Close | Red | Any Incomplete lead, Lead, Hot Lead Application Ready can get this, move to Inactive Folder
// NINC - No Income | Red | Any Incomplete lead, Lead, Hot Lead Application Ready can get this, move to Inactive Folder
// DEN - Denied | Red | Any file moved to Inactive by corporate, move to Inactive Folder
mar.PIPELINE.logic.calcState = function({mo_pipeline, mo_folder, mo_flag, status, paused_until_date,uw_status, _is_allowed_back_to_prq, app, encompass = true}){
let remove = function(arr, s) {
return arr.filter(function(v) {
return (v !== s);
});
}
if (typeof _is_allowed_back_to_prq !== "boolean") _is_allowed_back_to_prq = true;
/**
* is this ENCOMPASS or ELAINE or BOTH
*/
let sm = mar.PIPELINE.stages;
let s = []
let is_encompass = ((mo_pipeline & Math.pow(2, sm.en_start.mask)) > 0);
let is_elaine = ((mo_pipeline & Math.pow(2, sm.el_start.mask)) > 0);
//
//| en_start | pipeline | 1 |
// | en_prequal | pipeline | fd9b998c-47d3-4659-bc3e-ce7e3a9dae5c |
//| en_b_prequal | pipeline | 9380c315-fe23-45d9-b993-27e73da70326 |
//| en_b_review | pipeline | 1a255fe3-8ba7-4e33-bafa-99a15daa4302 |
//| en_smr | pipeline | 9297196d-c769-4236-b20f-314dacdfcfaa |
//sign pack recieved | en_loanpack | pipeline | 5c7f1035-3eac-4775-b8cb-439e8f21b4e8 |
//sent to processing | en_comsetup | pipeline | 3c7ac210-27d6-49d5-9eda-a4eb81dc208a |
//processor accepted | en_procacc | pipeline | bda610da-9e96-443c-a3a5-6473c45772db |
//| en_b_con_p_p | pipeline | 4dd3a376-4d96-4381-be87-3fe5c0234fef |
//| en_b_con_p_r | pipeline | 0d64ed07-fc6a-4cdd-977e-e34ef83ee556 |
//submitted | en_sub | pipeline | 3 |
//initial underwrite | en_initund | pipeline | 157c3cbb-8f68-4099-ada8-66a2ba49d64f |
//conditional submit | en_cond_sub | pipeline | 80dcf250-3c95-4673-a726-160eec345f49 |
//clear to close | en_c2c | pipeline | 4 |
// | en_closch | pipeline | e6896d81-2cf3-4b1d-8f4e-47e94d89f897 |
//ready for docs | en_docs | pipeline | 850dd7ea-6d0e-41fa-b979-d598aa9bac13 |
//| en_b_con_fnd | pipeline | b860b749-5694-4018-bd56-5219c63a81d8 |
//| en_b_con_pha | pipeline | 80a1f5ac-9197-472e-8ee1-6d2dfe5a16b8 |
//| en_b_mod | pipeline | fc632352-6f20-488b-aa06-8f82afd5486a |
// | en_funding | pipeline | 6 |
// | en_shipping | pipeline | 70367ac9-ec21-4be4-a548-8d5710eb6cee |
// | en_purchasing | pipeline | c6cf77b0-2156-42ef-91aa-2d5def0af3c3 |
// | en_completion | pipeline | 7 |
//
if (is_encompass === true) {
if (typeof uw_status !== "string") uw_status = "";
uw_status = uw_status.trim();
// s = ["prq","paused","notstart","prequal","offering","collect", "hot","mia","ncrt","ncsh","ninc"];
// s = ["prq","paused","notstart","prequal","collect", "hot","mia","ncrt","ncsh","ninc"];
s = ["prq","paused","prequal","collect", "hot","mia","ncrt","ncsh","ninc"];
// if ((mo_pipeline & Math.pow(2, sm.en_prequal.mask)) > 0) s = ["prq","paused","notstart","prequal","offering","collect","hot","mia","ncrt","ncsh","ninc"];
// if ((mo_pipeline & Math.pow(2, sm.en_prequal.mask)) > 0) s = ["prq","paused","notstart","prequal","collect","hot","mia","ncrt","ncsh","ninc"];
if ((mo_pipeline & Math.pow(2, sm.en_prequal.mask)) > 0) s = ["prq","paused","prequal","collect","hot","mia","ncrt","ncsh","ninc"];
if ((mo_pipeline & Math.pow(2, sm.en_appcomplete.mask)) > 0) s = ["rdy"];
if ((mo_pipeline & Math.pow(2, sm.en_smr.mask)) > 0) s = ["dcl"];
if ((mo_pipeline & Math.pow(2, sm.en_disdesk.mask)) > 0) s = ["dcl"];
if ((mo_pipeline & Math.pow(2, sm.en_loanpack.mask)) > 0) s = ["lpr"];
if ((mo_pipeline & Math.pow(2, sm.en_comsetup.mask)) > 0) s = ["opn"];
if ((mo_pipeline & Math.pow(2, sm.en_procacc.mask)) > 0) s = ["prc"];
if ((mo_pipeline & Math.pow(2, sm.en_b_con_p_p.mask)) > 0) s = ["prc"];
if ((mo_pipeline & Math.pow(2, sm.en_b_con_p_r.mask)) > 0) s = ["prc"];
if ((mo_pipeline & Math.pow(2, sm.en_sub.mask)) > 0) s = ["sub"];
if ((mo_pipeline & Math.pow(2, sm.en_initund.mask)) > 0) s = ["iund"];
if (uw_status.toLowerCase().startsWith("approved")) s = ["apr"];
if (uw_status.toLowerCase().startsWith("denied")) s = ["den"];
if (uw_status.toLowerCase().startsWith("suspended")) s = ["sus"];
if (uw_status.toLowerCase().startsWith("withdrawn")) s = ["wit"];
if (uw_status.toLowerCase().startsWith("cancelled")) s = ["can"];
if ((mo_pipeline & Math.pow(2, sm.en_cond_sub.mask)) > 0) s = ["rsub"];
if ((mo_pipeline & Math.pow(2, sm.en_c2c.mask)) > 0) s = ["c2c"];
if ((mo_pipeline & Math.pow(2, sm.en_closch.mask)) > 0) s = ["cls"];
if ((mo_pipeline & Math.pow(2, sm.en_docs.mask)) > 0) s = ["cls"];
if ((mo_pipeline & Math.pow(2, sm.en_b_con_fnd.mask)) > 0) s = ["cls"];
if ((mo_pipeline & Math.pow(2, sm.en_b_con_pha.mask)) > 0) s = ["cls"];
if ((mo_pipeline & Math.pow(2, sm.en_b_mod.mask)) > 0) s = ["cls"];
if ((mo_pipeline & Math.pow(2, sm.en_funding.mask)) > 0) s = ["fun"];
if ((mo_pipeline & Math.pow(2, sm.en_shipping.mask)) > 0) s = ["fun"];
if ((mo_pipeline & Math.pow(2, sm.en_purchasing.mask)) > 0) s = ["fun"];
if ((mo_pipeline & Math.pow(2, sm.en_completion.mask)) > 0) s = ["fun"];
} else {
s = ["lead","lead_a","lead_w","lead_c","lead_d","mia","ncrt","ncsh","ninc"];
// if ((mo_pipeline & Math.pow(2, sm.el_com_nodoc.mask)) > 0) s = ["prq", "paused","notstart","prequal","offering","collect", "lead","hot","mia","ncrt","ncsh","ninc"];
// if ((mo_pipeline & Math.pow(2, sm.el_com_nodoc.mask)) > 0) s = ["prq", "paused","notstart","prequal","collect", "lead","hot","mia","ncrt","ncsh","ninc"];
if ((mo_pipeline & Math.pow(2, sm.el_com_nodoc.mask)) > 0) s = ["prq", "paused","prequal","collect", "lead","lead_a","lead_w","lead_c","lead_d","hot","mia","ncrt","ncsh","ninc"];
if (status === "lead_w") {
s = remove(s, "lead_c");
}
else if (status === "lead_h") {
s = remove(s, "lead_w");
s = remove(s, "lead_c");
}
else if (status !== "lead_c" && status !== "lead_d") {
// s = remove(s, "lead_h");
s = remove(s, "lead_w");
s = remove(s, "lead_c");
s = remove(s, "lead_d");
}
}
if (_is_allowed_back_to_prq === false && s.indexOf("prq") > -1) {
s = s.filter(function(v){
return (v !== "prq");
});
}
/**
* if not Encompass, then add all the items here
*/
if (is_encompass === false && !encompass) {
for (let x in mar.PIPELINE.stages_ui) {
let stage = mar.PIPELINE.stages_ui[x];
if (MAR.getOpt(stage, "enc", false) === true && s.indexOf(x) < 0) {
s.push(x);
}
}
}
s.push("deleted");
s.push("inuntil");
return {
vstate : s, /* list of possible states */
is_encompass : is_encompass,
is_elaine : is_elaine,
mo_pipeline : mo_pipeline,
mo_folder : mo_folder,
mo_flag : mo_flag,
status : status,
_is_allowed_back_to_prq : _is_allowed_back_to_prq
}
return S;
};
if ("notes" in mar === false) {
mar.notes = {
statuses : {
NEW : "New",
CLEARED : "Cleared"
},
types : {
tocleear : "Note that requires clearing",
justanote : "Inormation only",
reminder : "Reminder"
},
alarmmethods : {
timeline : "posting an alert in the pipeline",
text : "sending a text message"
},
alarms : {
everyone : "everyone i selected",
me : "just me"
}
}
}
if ("roles" in mar === false) {
mar.roles = {
telemarketer : "Tele-marketer",
assignedto : "Loan officer",
lo_assistant : "Loan officer assistant",
loa2 : "Loan officer assistant 2",
file_opener : "Loan opener",
branch_manager : "Branch manager",
branch_processor : "Branch processor",
pre_submit : "Pre-submit",
disclosure : "Disclosure",
QC : "QC",
production_manager : "Production manager",
processing_manager : "Processing manager",
divisional_manager : "Divisional manager",
regional_manager : "Regional manager",
underwriter : "Underwriter",
loan_committee : "Loan committee",
loan_closer : "Loan closer",
condo_processor : "Condo processor",
filestarter : "file starter",
complianceoff : "compliance officer"
};
/*
* approles
* If there is an aprole of
*
* 0 - this will not be presented per loan
* 1 - this is per loan and will on ADMINUSER ID
* 2 - this is per loan and will an ADDRESSBOOK ID
* 3 -
*
* If there is an ENC_ROLEID then this has to be an ADMINUSER
* If there is an ENCID then this is an ADDRESSBOOK
*
* p2
* de = display on empty Y/N
* so = sort order (-1 = never display)
*
*
* if role == 1 and enc_role_id not present then it can be assigned internally
*
*
*
*/
mar.approles = {
admin : { mask : 1, desc : "Elaine Administrator", aprole : 0 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"Y"},sd : "adm"},
branchadmin : { mask : 4, desc : "Branch administrator", aprole : 0 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"Y"},sd : "bra"},
referral_id : { mask : 32, desc : "Referal partner", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"Y"},sd : "refp"},
realtor : { mask : 32, desc : "Realtor", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"Y"},sd : "rea", stype : "realtor"}, // special type of realtor
corporateprocessor : { mask : 128, desc : "Corporate processor", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "cpr", enc_roleid : 5},
assignedto : { mask : 8, desc : "Loan officer", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"Y"},sd : "lo", enc : "LOAN_OFFICER", encid : 1, enc_roleid : 1, search_mask : (16+8)},
lo_assistant : { mask : 16, desc : "Loan officer assistant", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:10 ,ro:"N",de:"Y"},sd : "loa", enc_roleid : 21, search_mask : (16+8) },
loa2 : { mask : 16, desc : "Loan officer assistant2", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:11 ,ro:"N",de:"Y"},sd : "la2", enc_roleid : 36, search_mask : (16+8) },
file_opener : { mask : Math.pow(2, 9), desc : "Loan opener", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "lop"},
loan_processor : { mask : 0, desc : "Loan processor", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:11 ,ro:"N",de:"N"},sd : "lpr", enc : "LOAN_PROCESSOR", encid : 0 },
branch_manager : { mask : Math.pow(2, 10), desc : "Branch manager", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "brm", enc_roleid : 34 },
branch_processor : { mask : Math.pow(2, 11), desc : "Branch processor", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "brp"},
pre_submit : { mask : Math.pow(2, 12), desc : "Pre-submit", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "pre"},
disclosure : { mask : Math.pow(2, 13), desc : "Disclosure", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "dis"},
QC : { mask : Math.pow(2, 14), desc : "QC Auditor", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "wc", enc_roleid : 35 },
production_manager : { mask : Math.pow(2, 15), desc : "Production manager", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "prm", enc_roleid : 22 },
processing_manager : { mask : Math.pow(2, 16), desc : "Processing manager", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "pom"},
divisional_manager : { mask : Math.pow(2, 17), desc : "Divisional manager", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "dma"},
regional_manager : { mask : Math.pow(2, 18), desc : "Regional manager", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "rma"},
underwriter : { mask : 64, desc : "Underwriter", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "und", enc : "UNDERWRITER", encid : 23, enc_roleid : 25},
loan_committee : { mask : Math.pow(2, 19), desc : "Loan committee", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "lco"},
condo_processor : { mask : Math.pow(2, 20), desc : "Condo processor", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "cpr"},
telemarketer : { mask : Math.pow(2, 21), desc : "Tele-marketer", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:15 ,ro:"N",de:"Y"},sd : "tel"},
filestarter : { mask : Math.pow(2, 22), desc : "File starter", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "fst", enc_roleid : 0, search_mask : (16+8+ Math.pow(2, 22)) },
complianceoff : { mask : Math.pow(2, 23), desc : "Compliance officer", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "cof", enc_roleid : 23 },
titlecompany : { mask : Math.pow(2, 8), desc : "Title company", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:50 ,ro:"N",de:"Y"},sd : "tco", enc : "TITLE_COMPANY", encid : 8},
broker_lender : { mask : 0, desc : "Broker Lender", aprole : 0 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ebl", enc : "BROKER_LENDER", encid : 2 },
broker_lender_ca : { mask : 0, desc : "Broker Lender Comp Agent", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eba", enc : "BROKER_LENDERSsnCompanyAgent", encid : 3 },
broker_lender_co : { mask : 0, desc : "Broker Lender Company", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ebc", enc : "BROKER_LENDERSsnCompany", encid : 4 },
lender_investor : { mask : 0, desc : "Lender Investor", aprole : 0 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eli", enc : "LENDER_INVESTOR", encid : 5 },
appraisal_co : { mask : 0, desc : "Appraisal company", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eac", enc : "APPRAISAL_COMPANY", encid : 6 },
escrow_co : { mask : 0, desc : "Escrow Company", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:55 ,ro:"N",de:"Y"},sd : "eec", enc : "ESCROW_COMPANY", encid : 7 },
buyers_attourny : { mask : 0, desc : "Buyers Attorney", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:80 ,ro:"N",de:"Y"},sd : "ebb", enc : "BUYERS_ATTORNEY", encid : 9 },
sellers_attourny : { mask : 0, desc : "Sellers Attorney", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:82 ,ro:"N",de:"Y"},sd : "esa", enc : "SELLERS_ATTORNEY", encid : 10 },
buyers_agent : { mask : 0, desc : "Buyers Agent", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:60 ,ro:"N",de:"Y"},sd : "ebg", enc : "BUYERS_AGENT", encid : 11 }, // realtor
sellers_agent : { mask : 0, desc : "Sellers Agent", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:65 ,ro:"N",de:"Y"},sd : "esg", enc : "SELLERS_AGENT", encid : 12 },
seller : { mask : 0, desc : "Sellers", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "es1", enc : "SELLER", encid : 13 },
seller2 : { mask : 0, desc : "Sellers2", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "es2", enc : "SELLER 2", encid : 14 },
seller3 : { mask : 0, desc : "Sellers3", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "es3", enc : "SELLER 3", encid : 15 },
seller4 : { mask : 0, desc : "Sellers4", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "es4", enc : "SELLER 4", encid : 16 },
builder : { mask : 0, desc : "Builder", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:90 ,ro:"N",de:"Y"},sd : "ebu", enc : "BUILDER", encid : 17 },
hazard_insurance : { mask : 0, desc : "Hazard Insurance", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:70 ,ro:"N",de:"Y"},sd : "ehi", enc : "HAZARD_INSURANCE", encid : 18 },
mortgage_insurance : { mask : 0, desc : "Mortgage Insurance", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:74 ,ro:"N",de:"Y"},sd : "emi", enc : "MORTGAGE_INSURANCE", encid : 19 },
surveyor : { mask : 0, desc : "Surveyor", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "esu", enc : "SURVEYOR", encid : 20 },
flood_insurance : { mask : 0, desc : "Flood insurance", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:72 ,ro:"N",de:"Y"},sd : "efi", enc : "FLOOD_INSURANCE", encid : 21 },
credit_company : { mask : 0, desc : "Credit company", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ecc", enc : "CREDIT_COMPANY", encid : 22 },
servicing : { mask : 0, desc : "Servicing", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "esv", enc : "SERVICING", encid : 24 },
doc_signing : { mask : 0, desc : "Doc signing", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eds", enc : "DOC_SIGNING", encid : 25 },
warehouse : { mask : 0, desc : "Warehouse", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ewa", enc : "WAREHOUSE", encid : 26 },
financial_planner : { mask : 0, desc : "Financial planner", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "efp", enc : "FINANCIAL_PLANNER", encid : 27 },
investor : { mask : 0, desc : "Investor", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ein", enc : "INVESTOR", encid : 28 },
assignto : { mask : 0, desc : "Assignto", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eas", enc : "ASSIGNTO", encid : 29 },
broker : { mask : 0, desc : "Broker", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ebr", enc : "BROKER", encid : 30 },
docspreparedby : { mask : 0, desc : "Docspreparedby", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "edp", enc : "DOCSPREPAREDBY", encid : 31 },
custom1 : { mask : 0, desc : "Custom 1", aprole : 3 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ec1", enc : "CUSTOM", encid : 32 },
custom2 : { mask : 0, desc : "Custom 2", aprole : 3 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ec2", enc : "CUSTOM", encid : 33 },
custom3 : { mask : 0, desc : "Custom 3", aprole : 3 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ec3", enc : "CUSTOM", encid : 34 },
custom4 : { mask : 0, desc : "Custom 4", aprole : 3 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ec4", enc : "CUSTOM", encid : 35 },
mortgagee : { mask : 0, desc : "Mortgagee", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "emo", enc : "MORTGAGEE", encid : 36 },
notary : { mask : 0, desc : "Notary", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "eno", enc : "NOTARY", encid : 37 },
loan_closer : { mask : Math.pow(2, 24), desc : "Loan closer", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ecl", enc : "LOAN_CLOSER", encid : 38, enc_roleid : 26, enc_role_ro : true },
loan_underwriter : { mask : 0, desc : "Loan underwriter", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "elu", enc : "LOAN_UNDERWRITER", encid : 39 },
shipper : { mask : Math.pow(2, 25), desc : "Shipper ", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "shp", enc : "SHIPPER", enc_roleid : 32, enc_role_ro : true }, // needs encid
post_closer : { mask : Math.pow(2, 26), desc : "Post closer", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "pcl", enc : "POST_CLOSER", enc_roleid : 30, enc_role_ro : true }, // needs encid
funder : { mask : Math.pow(2, 27), desc : "Funder", aprole : 1 ,dc : 0, ch : 0 ,p2:{so:100 ,ro:"N",de:"N"},sd : "fnd", enc : "FUNDER", enc_roleid : 33, enc_role_ro : true }, // needs encid
settlement_agent : { mask : 0, desc : "Settlement agent", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "est", enc : "SETTLEMENT_AGENT", encid : 40 },
architect : { mask : 0, desc : "Architect", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:92 ,ro:"N",de:"Y"},sd : "ear", enc : "ARCHITECT", encid : 41 },
generalcontractor : { mask : 0, desc : "General contractor", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:94 ,ro:"N",de:"Y"},sd : "egc", enc : "GENERALCONTRACTOR", encid : 42 },
appointmentofdes : { mask : 0, desc : "Appointmentofdesignee", aprole : 2 ,dc : 0, ch : 0 ,p2:{so:1000 ,ro:"N",de:"N"},sd : "ead", enc : "APPOINTMENTOFDESIGNEE", encid : 43 }
};
mar.approles_is_assignable_via_encompass = function(role) {
if (role in mar.approles === false) return false;
let enc_roleid = MAR.getOpt(mar.approles[role], "enc_roleid", false);
if (enc_roleid === false) return false;
let enc_role_ro = MAR.getOpt(mar.approles[role], "enc_role_ro", false);
if (enc_role_ro === true) return false;
return true;
}
mar.approleByMask = function(mask) {
for (let x in mar.approles) {
let itm = mar.approles[x];
if ((MAR.getOpt(itm,"mask",0) & mask) > 0) {
return {
code : x,
approle : itm
}
}
}
return false;
}
mar.approleByEnc = function(enc) {
for (let x in mar.approles) {
let itm = mar.approles[x];
if (MAR.getOpt(itm,"enc","") === enc) {
return {
code : x,
approle : itm
}
}
}
return false;
}
mar.approleBySd = function(sd, app) {
console.warn("approleBySd");
sd = sd.toLowerCase();
for (let i=0; i < 10; i++) {
if (sd === `b${i+1}`) {
return {
type : "client",
id : i,
desc : `Borrower ${i+1}`,
approle : {},
obj : (app) ? MAR.getOpt(app,`_names.${i}`,false) : false
}
}
}
for (let x in mar.approles) {
let itm = mar.approles[x];
if (MAR.getOpt(itm,"sd","") === sd) {
if (itm.aprole > 1) {
let obj = false;
let fc = (app) ? MAR.getOpt(app, "_filecontacts",[]) : [];
for (let x of fc) {
if (x.type === itm.enc) {
obj = x;
}
}
return {
type : "filecontact",
code : itm.enc,
desc : itm.desc,
approle : itm,
obj : obj
}
} else {
let obj = false;
if (app) {
if (`${x}_obj` in app) {
obj = app[`${x}_obj`];
}
}
return {
type : MAR.getOpt(itm, "stype","approle"),
code : x,
desc : itm.desc,
approle : itm,
obj : obj
}
}
}
}
return {
type : "404",
role : sd,
obj : false
}
}
/*
{
"loanAssociateType": "User",
"id": "moduber",
"name": "Marvin Oduber",
"phone": "561-886-0300",
"cellPhone": "305-989-5205",
"fax": "561-886-0301",
"email": "MOduber@usmtg.com",
"roleName": "Loan Officer",
"roleId": "1"
},
*/
/*
"contactType": "LOAN_PROCESSOR"
*/
}
mar.isEmpty = function() {
var a = arguments;
var l = a.length;
var i = 0;
var undef;
if (l === 0) return true;
while (i !== l) {
if (a[i] === undef || a[i] === null) return true;
i++
}
return false;
}
mar.sections = [
"menu_simple",
"scenario_simple",
"rate_simple",
"income_simple",
"declarations_simple",
"applicant_another_applicant",
"assets_simple",
"tiger_simple",
"liabilities_hard",
"liabilities_soft",
"liabilities_soft2",
"liabilities_simple",
"reo_simple",
"play",
"needs_list"
];
mar.sectionNames = {
menu_simple : "Intro screen",
scenario_simple : "Your Scenario",
rate_simple : "Your Rate",
income_simple : "Your Income",
declarations_simple : "Your Declarations",
applicant_another_applicant : "Add another Applicant",
assets_simple : "Your Assets",
tiger_simple : "Your Decision",
liabilities_hard : "Hard pull",
liabilities_soft : "Soft Pull",
liabilities_soft2 : "Soft Pull p2",
liabilities_simple : "Your Liabilities",
reo_simple : "Your Realestate",
play : "Predict DU",
needs_list : "Your Task List"
};
mar.sectionAllowed = {
menu_simple : function() {
return 1;
},
scenario_simple : function() {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
var hps = hasPassedSection("scenario_simple");
if (hps == 1) return 0;
return 1;
},
rate_simple : function() {
return 5;
},
income_simple : function(applicantnum) {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
if ("income" in mar.answers.v2 == false) return 0;
var noa = mar.answers.v2.applicants.length;
var elm = mar.answers.v2.income;
if (elm.length < noa) return 0;
var hps = hasPassedSection("income_simple");
if (hps == 1) return 0;
return 1;
},
declarations_simple : function(applicantnum) {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
if ("declarations" in mar.answers.v2 == false) return 0;
var noa = mar.answers.v2.applicants.length;
var elm = mar.answers.v2.declarations;
if (elm.length < noa) return 0;
var hps = hasPassedSection("declarations_simple");
if (hps == 1) return 0;
return 1;
},
applicant_another_applicant : function() {
return 5;
},
assets_simple : function(applicantnum) {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
if ("assets" in mar.answers.v2 == false) return 0;
var elm = mar.answers.v2.assets;
var wasupdated = false;
for (var x in elm) {
var y = elm[x];
if ("updated_by" in y && y.updated_by != "") wasupdated = true;
}
if (!wasupdated) return 0;
var hps = hasPassedSection("assets_simple");
if (hps == 1) return 0;
return 1;
},
tiger_simple : function(applicantnum) {
return 5;
},
liabilities_hard : function(applicantnum) {
return 5;
},
liabilities_soft : function(applicantnum) {
return 5;
},
liabilities_soft2 : function() {
return 5;
},
liabilities_simple : function() {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
if ("liabilities" in mar.answers.v2 == false) return 0;
var hps = hasPassedSection("liabilities_simple");
if (hps == 1) return 0;
return 1;
},
reo_simple : function(applicantnum) {
if ("answers" in mar == false) return 0;
if ("v2" in mar.answers == false) return 0;
if ("intro_type_of_route" in mar.answers.v2 &&
mar.answers.v2.intro_type_of_route == "short") return 5;
},
play : function() {
return 9;
},
needs_list : function(applicantnum) {
return 0;
}
};
mar.logtypes = {
"sms-to-lo" : { d : "SMS to Loan Officer", level : 0 },
"sms-to-QC" : { d : "SMS to QC", level : 0 },
"sms-to-tel" : { d : "SMS to Number", level : 0 },
"test" : { d : "TEST", level : 0 },
"info" : { d : "Info!", level : 0 },
"info-statuschange-lead" : { d : "Automatic Lead Status Change", level : 0 },
"info-followup-lead" : { d : "Automatic Follow Up", level : 0 },
"sms-to-client" : { d : "SMS to Client", level : 0 },
"sms-to-realtor" : { d : "SMS to Realtor", level : 0 },
"email-to-client" : { d : "Email to Client", level : 0 },
"sms-to-lo_assistant" : { d : "SMS to LOA", level : 0 }
};
mar.nextsectionfrom = function(From) {
if (From == "scenario_simple") return "income_simple"; //"phone_number"; // return "rate_simple";
if (From === "rate_simple") return "phone_number";
if (From === "phone_number") return "income_simple";
if (From == "income_simple") return "declarations_simple";
}
mar.prevsectionfrom = function(From) {
if (From === "income_simple") return "scenario_simple"; //"phone_number";
if (From === "phone_number") return "scenario_simple"; // return "rate_simple";
if (From == "rate_simple") return "scenario_simple";
}
if (("txt" in mar) == false ) {
mar.txt = {};
mar.txt.soon = "Contract soon";
mar.txt.just_looking = "Just looking";
mar.txt.contract = "Under contract";
mar.txt.one_month = "1-3 months";
mar.txt.three_months = "3-6 months";
mar.txt.conv = "Conventional";
mar.txt.fha = "FHA";
mar.txt.va = "VA";
mar.txt.jumbo = "Jumbo";
mar.txt.hr = "Home Ready";
mar.txt.heloc = "HELOC";
mar.txt.intonly = "DSCR-Investor";
mar.txt.primary = "Primary";
mar.txt.investment = "Investment";
mar.txt.secondary = "Second home";
mar.txt.refinance = "Rate and term refi";
mar.txt.refinance_ = "Rate and term refi";
mar.txt.refinance_cashout = "Cash-out refi";
mar.txt.refinance_closing = "Limited cash-out refi";
mar.txt.refinance_nclosing = "Rate and term refi";
mar.txt.refinance_noclosing = "Rate and term refi";
mar.txt.purchase = "Purchase";
mar.txt.use2_primary = "Primary";
mar.txt.use2_sell = "Sell before transaction";
mar.txt.use2_secondary = "Second home";
mar.txt.use2_investment = "Investment";
mar.txt.use2_market = "Put on market";
mar.txt.use2_yes = "Subject property";
mar.txt.occupancy_by_me = "Primary";
mar.txt.occupancy_secondhom = "Second home";
mar.txt.occupancy_investment = "Investment";
mar.txt.occupancy_by_me_summary = "a primary home";
mar.txt.occupancy_secondhom_summary = "a second home";
mar.txt.occupancy_investment_summary = "an investment property";
mar.txt.short_occupancy_by_me = "OOC";
mar.txt.short_occupancy_secondhom = "2ND";
mar.txt.short_occupancy_investment = "INV"
mar.txt.sfr = "Single family residence";
mar.txt.condo = "Condo";
mar.txt.duplex = "Duplex";
mar.txt.triplex = "Triplex";
mar.txt.fourplex = "Fourplex";
mar.txt.other = "Other";
mar.txt.rat_refi = "Rate and term refi";
mar.txt.limit_cash_out_refi = "Limited cash out refi";
mar.txt.cash_out_refi = "Cash out refi";
mar.txt.purchase = "Purchase";
mar.txt.refi = "rate and term refi";
mar.txt.refi_occupancy_1 = "primary";
mar.txt.refi_occupancy_2 = "secondary";
mar.txt.refi_occupancy_3 = "investment";
mar.txt.refi_occupancy_1_summary = "a primary";
mar.txt.refi_occupancy_2_summary = "a secondary";
mar.txt.refi_occupancy_3_summary = "a investment";
// mar.txt.refi_type_01 = "";
// mar.txt.refi_type_02 = "";
// mar.txt.refi_type_03 = "";
mar.txt._sfr = "Single family home or townhouse";
mar.txt._condo = "Condo";
mar.txt._duplex = "Duplex / two family home";
mar.txt._triplex = "Triplex / three family home";
mar.txt._fourplex = "Fourplex / four family home";
mar.txt._other = "Other";
mar.txt.non = "No HOA fees";
mar.txt.chigh = "Luxury community";
mar.txt.clow = "Normal community";
mar.txt.w2 = "Salary";
mar.txt.llc = "Self-employment";
mar.txt.k1 = "Corporation K1";
mar.txt.rental = "Rental";
mar.txt.dis = "Disability";
mar.txt.child = "Child support/Alimony";
mar.txt.alimony = "Alimony";
mar.txt.instalmentloan = "Installment Loan";
mar.txt.carloan = "Car Loan";
mar.txt.carlease = "Car Lease";
mar.txt.creditcard = "Credit Card";
mar.txt.irstax = "Tax Debt";
mar.txt.ssec = "Social Security";
mar.txt.pension = "Pension";
mar.txt.mortgage = "Mortgage";
mar.txt.ng = "National Guard";
mar.txt.credit_report_key = "Credit Report Fee";
mar.txt.buydown_points = "Points";
mar.txt.buydown_lender_credit = "Points to receive";
mar.txt.cwp_done_in_encompass = "Done in encompass";
mar.txt.cwp_done_on_paper = "Done on paper";
mar.txt.cwp_no_document = "There is no documen";
mar.txt.cwp_other = "Other";
mar.txt.cwp_on = "Other (on)";
mar.txt.pipeline_myfocus = "My Focus view";
mar.txt.pipeline_my = "My Client view";
mar.txt.pipeline_branch = "Branch view";
mar.txt.pipeline_company = "Company view";
mar.txt.cond_head_toolbar = "";
mar.txt.cond_head_head = "Loan and Conditions";
mar.txt.cond_head_assets = "Assets";
mar.txt.cond_head_income = "Income";
mar.txt.cond_head_personal = "Miscellaneous";
mar.txt.cond_head_declarations = "Declarations";
mar.txt.cond_head_reo = "Real Estate Owned";
mar.txt.cond_head_property = "Subject Property";
mar.txt.cond_head_liabilities = "Credit";
mar.txt.cond_head_credit = "Credit";
mar.txt.cond_head_miscelaneous = "Miscellaneous";
mar.txt.cond_head_additional = "Additional";
mar.txt.cond_head_loi = "Permissions"; //"Checklist";
mar.txt.cond_head_uw_conditions = "Underwriter Conditions - Please review, rename and re-assign conditions to client where needed"; //"Checklist";
mar.txt.cond_order_toolbar = 2;
mar.txt.cond_order_head = 5;
mar.txt.cond_order_uw_conditions= 7;
mar.txt.cond_order_personal = 10;
mar.txt.cond_order_assets = 20;
mar.txt.cond_order_income = 30;
mar.txt.cond_order_declarations = 32;
mar.txt.cond_order_liabilities = 40;
mar.txt.cond_order_credit = 50;
mar.txt.cond_order_reo = 60;
mar.txt.cond_order_property = 70;
mar.txt.cond_order_miscelaneous = 90;
mar.txt.cond_order_additional = 91;
mar.txt.cond_order_loi = 95;
mar.txt.cond_order_liabilities = 6;
mar.txt.cond_order_credit = 7;
mar.txt.hw_head_reo = "Real Estate Owned";
mar.txt.hw_head_property = "Subject Property";
mar.txt.c7 = "chapter 7";
mar.txt.c11 = "chapter 11";
mar.txt.c13 = "chapter 13";
mar.txt.never = "Never";
mar.txt.weekly = "Once a week";
mar.txt.biweekly = "Twice a week";
mar.txt.any = "As frequently as necessary";
mar.txt.tcpa_Y = "Permission granted";
mar.txt.tcpa_N = "Permission blocked";
mar.txt.tcpa_ = "Permission not given";
mar.txt.base = "Base";
mar.txt.bonus = "Bonus";
mar.txt.overtime = "Overtime";
mar.txt.commission = "Commission";
mar.txt.other = "Other";
mar.txt.com_freq_doc_updates = "Automated updates on missing documentation";
mar.txt.com_freq_loan_proposals = "Automated updates on loan proposals";
mar.txt.com_freq_loan_other = "Automated updates other items related to your loan application";
mar.txt.com_freq_commercial = "Automated commercial messages";
mar.txt.com_method_email = "Permission to contact client by Email";
mar.txt.com_method_sms = "Permission to contact client by Text";
mar.txt.spouse = "Spouse";
mar.txt.coborrower = "Co-Borrower";
mar.txt.coborrower_nonresident = "Non Occupant";
mar.txt.salq_weekly = "What is your gross base weekly salary, before taxes";
mar.txt.salq_biweekly = "What is your gross base bi-weekly salary, before taxes";
mar.txt.salq_semimonthly = "What gross base bi-monthly salary, before taxes";
mar.txt.salq_monthly = "What is your gross base monthly salary, before taxes";
mar.txt.salq_hourly = "What is your gross base hourly rate, before taxes";
mar.txt.salq_yearly = "What is your gross base annual salary, before taxes";
mar.txt.liabilities_simple_card_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_carloan_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_carlease_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_instalmentloan_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_studentloan_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_child_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_alimony_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.liabilities_simple_mortgage_close_error = "You left some field empty, if there is no balance or minimum payment please enter a 0 (zero)";
mar.txt.reo_simple_property_close_error_free_noloantax = "On a mortgage free property you still need to enter a value for the tax";
mar.txt.reo_simple_property_close_error_free_hoa_nohoa = "If you specify that you pay HOA fees you must enter a value";
mar.txt.reo_simple_property_close_error_noproprtytype = "You have to specify a property type, choose 'other' if your type is not listed";
mar.txt.reo_simple_property_close_error_nopurchasedate = "You must enter a purchase date";
mar.txt.reo_simple_property_close_error_nopurchasedatep = "You must enter a purchase date in the past";
mar.txt.reo_simple_property_close_error_nopurchaseprice = "You must specify a purchase price";
mar.txt.reo_simple_property_close_error_novalue = "You must specify a current value or best estimate";
mar.txt.reo_simple_property_close_error_nouse = "You did not tell us the current use of the property";
mar.txt.reo_simple_property_close_error_primary_nouse2 = "You specified this as your primary but did not tell us your plans for the property";
/* not listed */
mar.txt.reo_simple_property_close_error_nl_nobalance = "You have to enter a total mortgage balance";
mar.txt.reo_simple_property_close_error_nl_nomonthly = "You have to enter a mortgage monthly amount";
mar.txt.reo_simple_property_close_error_free_noloantax = "You still need to enter a value for the tax";
mar.txt.reo_simple_property_close_error_free_noinsurance = "You still need to enter a value for the insurance";
mar.txt.reo_simple_property_close_error_nl_nolloantax = "You still need to enter a value for the tax";
mar.txt.reo_simple_property_close_error_nl_noinsurance = "You still need to enter a value for the insurance";
mar.txt.reo_simple_property_close_error_noloantype = "You have to specify a loan type";
mar.txt.reo_simple_property_close_error_hoa_nohoa = "You still need to enter a value for the HOA fees";
mar.txt.rperm_share_calcs = "Permission to share loan calculations";
mar.txt.rperm_share_docs = "Permission to share list of docs";
mar.txt.rperm_share_underwriting = "Permission to share underwriting report";
mar.txt.rperm_share_appraisal = "Permission to share appraisal";
mar.txt.bpmi_rad_more20 = "BPMI";
mar.txt["app-soft"] = "soft pulled by Elaine";
mar.txt["app-hard"] = "hard pulled by Elaine";
mar.txt["enc"] = "pulled via Encompass";
mar.txt.ytd_base = "Year to date Base";
mar.txt.ytd_bonus = "Year to date Bonus";
mar.txt.ytd_overtime = "Year to date Overtime";
mar.txt.ytd_commission = "Year to date Commission";
mar.txt.ytd_tips = "Year to date Tips";
mar.txt.employer_name = "Name of employer";
mar.txt.name_of_employee = "Name of employee";
mar.txt.year = "Year";
mar.txt.PRC = "processor";
mar.txt.LO = "Loan officer";
mar.txt.LOA = "LOA";
mar.txt.OPN = "opener";
mar.txt.CLS = "closer";
mar.txt.fixed = "Fixed rate";
mar.txt.arm = "Adjustable rate";
mar.txt.uw_conditions = "Underwriter";
mar.txt.rq_lbl_pmt = `Principle & Interest`;
mar.txt.rq_lbl_mi = `M.I.`;
mar.txt.rq_lbl_tax = `Tax`;
mar.txt.rq_lbl_hoa = `HOA`;
mar.txt.rq_lbl_hoi = `HOI`;
mar.txt.rq_lbl_rent = `Rent`;
mar.txt.rq_lbl_estimate = `Estimate`;
}
if (("_txt" in mar) == false ) {
mar._txt = function(TXT0) {
let TXT = TXT0;
if (arguments.length > 1) {
TXT = Array.from(arguments).join("");
TXT0 = Array.from(arguments)[1];
}
if (TXT in mar.txt === false) return TXT0;
var retval = mar.txt[TXT];
if (typeof retval === 'function') {
return retval(TXT);
}
return retval
}
mar._txtdef = function(TXT,DEF) {
if (TXT in mar.txt === false) return DEF;
var retval = mar.txt[TXT];
if (typeof retval === 'function') {
return retval(TXT);
}
return retval
}
}
if ("num" in mar == false) {
mar.num = function(N) {
if (N) return parseFloat(N,10);
return 0;
}
}
if ("href" in mar == false) {
mar.href = function(elm) {
let $elm = $(elm);
let url = $elm.data("href");
mvc.go(url);
}
}
if ("fromhomework" in mar == false) {
mar.fromhomework = function(v) {
mar._tmp_fromhomework = (arguments.length === 0) ? true : v;
}
mar.is_fromhomework = function(v) {
return MAR.getOpt(mar, "_tmp_fromhomework", false);
}
}
if ("digits" in mar == false) {
mar.digits = function(S) {
if (!S) return "";
if (S == null) return "";
try {
return S.replace(/\D/g,'');
} catch(E) {}
return "";
}
}
if ("capitalize" in mar == false) {
mar.capitalize = function(S) {
if (!S) return "";
if (S == null) return "";
try {
//https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript/196991#196991
return S.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
} catch(E) {}
return "";
}
}
if ("messagetype" in mar == false) {
mar.messagetype = {
CHANGEOFPERSONNEL : {
tag : "change-of-personnel",
title : "Change of personnel",
subscribelist : "_changeofpersonnel"
}
}
}
mar.HW = {
BASE_STRUCT : {
NEED : 0,
TITLE : 1,
FULLID : 2,
LONGTITLE : 3,
SHORTTITLE : 4,
META : 5,
/* META */
ISLOX : 0,
ISIMMEDIATE : 1,
ISINTERNAL : 2,
LINK : 3,
AS_LOX_PARENT : 4,
N2N : 5, // this is a parent of x
N2N_REV : 6, // this is a child of x
PAGE_CNT : 7, // Page count
END : 99
/* END META */
},
HOMEWORK_STRUCT : {
NEED : 0,
TITLE : 1,
FULLID : 2,
LONGTITLE : 3,
SHORTTITLE : 4,
HWTYPE : 5,
STATUSES : 6,
/* STATUSES */
STATUS : "status",
HIDDEN : "hidden",
HWSTATUS : "hwstatus",
HWTITLE : "hwtitle",
N2N : "n2n",
EXDATA : "exdata",
DC : "dc",
APPLICNTNUM : "applicantnum",
DISP_TYPE : "display_type",
DISP_SEC : "display_sec",
STA_META : "meta",
END : 99,
/* END STATUSES */
NOTHING : 7,
META : 8,
/* META */
ISLOX : 0,
ISINTERNAL : 1,
OBJ : 2,
DATA : 3,
LINK : 4,
NAME : 5, /* name of condition e.g. "stock_statement" od "ID-DL"
AS_LOX_PARENT : 6,
END : 99,
/* END META */
NOTHING2 : 9,
OBJ2 : 10,
LINK : 11
},
NEEDS_WITH_DATA_STRUCT : {
NEED : 0,
NEED_DATA : 1,
INBS : 2,
PAGE_CNT : 3, // Page coun
N2N : 4, // this is a parent of X
N2N_REV : 5, // this is a child of X
END : 99
}
}
}
// base64
if (typeof window != "undefined") { // nodejs
var _btoa = function(str) {
return window.btoa( unescape( encodeURIComponent( str ) ) );
}
var _atob = function(str) {
return decodeURIComponent( escape( window.atob( str ) ) )
}
}
function getPipelineStatics() {
if (!mar.STATIC) setStaticVars();
return mar.pipeline;
}
/**
* returns and array [section index , section count]
*/
function getSectionProgress(SECTION) {
if (!mar.STATIC) setStaticVars();
if (SECTION && SECTION != "") {
for (var i=0; i < mar.sections.length; i++) {
if (mar.sections[i] == SECTION) {
return [i,mar.sections.length];
}
}
}
return [0,mar.sections.length];
}
function hasPassedSection(SECTION) {
if (!mar.STATIC) setStaticVars();
if (!mar.answers.v2) mar.answers.v2 = {};
if (!mar.answers.v2.state) mar.answers.v2.state = {}
if (!mar.answers.v2.state.highestSection) mar.answers.v2.state.highestSection = "";
if (!mar.answers.v2.state.currentSection) mar.answers.v2.state.currentSection = "";
var idx0 = mar.sections.indexOf(mar.answers.v2.state.highestSection); // idx0 = needs = 10
var idx1 = mar.sections.indexOf(SECTION); // idx1 = scenario = 2
// console.error(`hasPassedSection ${SECTION} high(${mar.answers.v2.state.highestSection}) ${idx0}/${idx1}`)
if (idx0 < idx1) return 1; // higest is higher than what we ask
if (idx0 > idx1) return -1; // we have not reached it yet
return 0; // we they are the same
}
function isNewHighestSection(SECTION) {
if (!mar.STATIC) setStaticVars();
if (!mar.answers.v2) mar.answers.v2 = {};
if (!mar.answers.v2.state) mar.answers.v2.state = {}
if (!mar.answers.v2.state.highestSection) mar.answers.v2.state.highestSection = "";
if (!mar.answers.v2.state.currentSection) mar.answers.v2.state.currentSection = "";
if (mar.answers.v2.state.highestSection == SECTION) return false;
var idx0 = mar.sections.indexOf(mar.answers.v2.state.highestSection);
var idx1 = mar.sections.indexOf(SECTION);
return (idx1 > idx0);
}
function isSectionBefore(SECTION1, SECTION2) {
var idx0 = mar.sections.indexOf(SECTION1);
var idx1 = mar.sections.indexOf(SECTION2);
return (idx0 <= idx1);
}
/**
* set the highest section
*/
function setHighestSection(SECTION) {
if (isNewHighestSection(SECTION)) {
mar.answers.v2.state.highestSection = SECTION;
mar.answers.v2.state.currentSection = SECTION;
return true;
}
mar.answers.v2.state.currentSection = SECTION;
return false;
}
/**
* get the highest allowable section
*/
function getHighestAllowableSection(APPLICANTNUM) {
if (!mar.STATIC) setStaticVars();
if (!mar.answers.v2) mar.answers.v2 = {};
if (!mar.answers.v2.state) mar.answers.v2.state = {}
if (!mar.answers.v2.state.highestSection) mar.answers.v2.state.highestSection = "";
//var hs = mar.answers.v2.state.highestSection;
for (x in mar.sectionAllowed) {
var allowed = mar.sectionAllowed[x](APPLICANTNUM)
if (allowed == 0) return x;
}
return mar.answers.v2.state.highestSection;
}
/**
* get the highest section
*/
function getHighestSection() {
if (!mar.STATIC) setStaticVars();
if (!mar.answers.v2) mar.answers.v2 = {};
if (!mar.answers.v2.state) mar.answers.v2.state = {}
if (!mar.answers.v2.state.highestSection) mar.answers.v2.state.highestSection = "";
return mar.answers.v2.state.highestSection;
}
/**
* get the current section
*/
function getCurrentSection() {
if (!mar.STATIC) setStaticVars();
if (!mar.answers.v2) mar.answers.v2 = {};
if (!mar.answers.v2.state) mar.answers.v2.state = {}
if (!mar.answers.v2.state.highestSection) mar.answers.v2.state.highestSection = "";
if (!mar.answers.v2.state.currentSection) mar.answers.v2.state.currentSection = "";
return mar.answers.v2.state.currentSection;
}
/**
* function to get the employent history
*/
function getEmploymentHistory(n) {
if (!mar.STATIC) setStaticVars();
var jobs = [];
if ("items" in mar.answers.v2.income[n]) {
mar.answers.v2.income[n].items.forEach(function(item){
if ("address" in item == false) {
item.address = MAR.getBucket("/income/address/"+item.uuid);
}
jobs.push(item);
});
}
else if ("w2" in mar.answers.v2.income[n] && "items" in mar.answers.v2.income[n].w2) {
mar.answers.v2.income[n].w2.items.forEach(function(item){
jobs.push(getBucket(item));
});
}
return jobs;
}
/**
* function to get income
*/
function getIncome_v2(PROG,QI) {
return MAR.income.getIncome_v2(PROG,QI);
}
function getLiabilities_import_tlimports() {
if (!mar.STATIC) setStaticVars();
if ("liabilities" in mar.answers.v2 == false) mar.answers.v2.liabilities = [];
if ("tlimports" in mar.answers.v2 == false) return;
let rv = {};
let tli = mar.answers.v2.tlimports;
let lia = mar.answers.v2.liabilities;
let liadel = getScenario_data("deleted_liabilities",[]);
let dbg = [];
dbg.push({lia_len : lia.length});
for (let x in tli) {
dbg.push(`Loop tli[${x}]`);
if (liadel.indexOf(x) > -1) {
continue;
}
let found = false;
for (let i=0; i < lia.length; i++) {
dbg.push(`Loop lia[${i}] sig:(${lia[i].sig})`);
let _sig = MAR.getOpt(lia[i], `sig`,false);
let _match = false;
if (_sig === false) {
_match = false;
}
else if (_sig === x) {
_match = true;
} else {
(function(){
/**
* Cater for
* "Finance-43001565466080-NAVY_FEDERAL_CR_UNION-2021-12-22-Installment-Automobile-FinanceCreditUnions"
* "Finance-XXXXXXXXXX6080-NAVY_FEDERAL_CR_UNION-2021-12-22-Installment-Automobile-FinanceCreditUnions"
*
* - or-
*
* "Miscellaneous-****************-THD/CBNA-2019-12-30-Revolving-CreditCard-MiscellaneousRetail"
* "Miscellaneous-603532******-THD/CBNA-2019-12-30-Revolving-CreditCard-MiscellaneousRetail"
*/
let x_arr = x.split(`-`);
let y_arr = _sig.split(`-`);
if (x_arr.length !== y_arr.length) return; // no match
if (x_arr.length < 2) return; // no account number - no match
let x_typ = x_arr.shift();
let y_typ = y_arr.shift();
if (x_typ !== y_typ) return; // 1st parts the same;
let x_acc = x_arr.shift();
let y_acc = y_arr.shift();
if (x_arr.join(`-`) !== x_arr.join(`-`)) return; // the rest of the line is diffferent, no match
let x_acc_d = MAR.digits(x_acc);
let y_acc_d = MAR.digits(y_acc);
if (x_acc_d === y_acc_d) {
_match = true; // Full digit ony match
return;
}
if (x_acc_d.length === 0 || y_acc_d.length === 0) {
_match = true; // if either of the two are no length - assume match
return;
}
if (x_acc.length !== y_acc.length) return; // account numbers different lengths - no match
let x_acc_a = x_acc.split(``); // [X,X,X,1,2,3]
let y_acc_a = y_acc.split(``); // [0,1,1,1,2,3]
while (x_acc_a.length > 0) {
let x_char = x_acc_a.pop();
let y_char = y_acc_a.pop();
if (x_char === y_char) continue;
if (x_char === `X`) continue;
if (y_char === `X`) continue;
if (x_char === `*`) continue;
if (y_char === `*`) continue;
return; // one char is different - no match
}
_match = true;
})();
}
if (_match) {
dbg.push(`Loop MATCH`);
lia[i]._updated = new Date().getTime();
/**
* update andy changes
*/
let fields_to_update = ["balance","monthly","nolate","terms","odate","acnum","name"];
for (let y of fields_to_update) {
let v = MAR.getOpt(tli[x], y, null);
let v1 = MAR.getOpt(lia[i], y, false);
if (v !== null && v1 !== v) {
lia[i][y] = v
}
}
found = true;
break;
}
}
dbg.push(`Loop END found(${found})`);
if (found === false) {
lia.push(tli[x])
lia[lia.length-1]._update_added = new Date().getTime();
lia[lia.length-1].verified = "N";
}
}
setScenario_data("tlimports_dbg",dbg);
return rv;
}
/**
* GET LIABILTIES / LIABILITY
*/
function getLiabilities_v2(n) {
if (!mar.STATIC) setStaticVars();
if ("liabilities" in mar.answers.v2 == false) return [];
getLiabilities_import_tlimports();
for (let i=0; i < mar.answers.v2.liabilities.length; i++) {
let item = mar.answers.v2.liabilities[i];
if (item.type === "installmentloan") {
item.type = `instalmentloan`;
}
if (item.type === "child") {
// debugger
}
}
if (mar.isEmpty(n)) return mar.answers.v2.liabilities
var retval = mar.answers.v2.liabilities[n];
if (!retval) retval = {};
/**
* calculate a months left
*/
if ("balance" in retval && "monthly" in retval) {
if ("months" in retval) {
retval.monthsleft = (retval.months)
} else {
retval.monthsleft = (retval.balance/retval.monthly)
}
} else {
retval.monthsleft = 0;
}
if ("monthly" in retval == false) {
retval.monthly = 0;
}
if ("balance" in retval == false) {
retval.balance = 0;
}
/**
* borrower / co borrower
*/
retval.BC = "B";
if ("signer" in retval && retval.signer != "borrower") retval.BC = "C";
/**
* set the payoff flag
*/
retval.payoff = "N";
/**
* set the omit flag
*/
if ("omit" in retval == false) {
retval.omit = "N";
}
return retval;
}
function getLiabilityAssignments(ino) {
let retval = [];
for (var i=0; i < 8; i++) {
if ((ino & Math.pow(2,i)) == Math.pow(2,i)) retval.push(i);
}
return retval;
}
function getLiabilityFirstAssignment(ino) {
for (var i=0; i < 8; i++) {
if ((ino & Math.pow(2,i)) == Math.pow(2,i)) return (i);
}
return -1;
}
/**
* GET ALL THE POSSIBLE OPTIONS FOR ASSIGNMENT
*/
function getOptions_v2(PROG) {
retval = {
applicants : [],
assets : [],
employers : [],
bankaccounts : [],
addresses : []
};
var applicantNames = getApplicantsNames_v2();
var i=0;
applicantNames.forEach(function(an){
retval.applicants.push({ k: i++, v : an.name});
})
var assets = getAssets_v2("web");
var i=0;
assets.detailmatrix.forEach(function(item){
retval.assets.push({ k: i++, v : item[0]+" - "+item[2]});
})
var buckets = getBuckets("");
for ( var x in buckets) {
var y = buckets[x];
if (y && "type" in y && y.type == "emp") {
retval.employers.push({ k: x, v : y.name});
continue;
}
if (y && "bank" in y) {
retval.bankaccounts.push({ k: x, v : y.bank});
continue;
}
if (x.indexOf("/applicants/address/") === 0) {
retval.addresses.push({ k: x, v : y.address});
continue;
}
}
return retval;
}
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
try {
if (input.indexOf("#") > -1) input = input.replace(/=/g, '=');
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
} catch (E) {
return input;
}
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
/**
* GET ASSETS
*/
function getAssets_v2(PROG,TYPE) {
if (!mar.STATIC) setStaticVars();
if (typeof PROG !== "string") PROG = "web";
if (typeof TYPE !== "string") TYPE = false;
var retval = {
total : 0,
has_unverified_items : false,
per_applicant : [0,0,0,0,0,0,0,0],
detailmatrix : [],
matching_cnt : 0
};
retval.detailmatrix.push(["TYPE","APPLICANT","NAME","BALANCE","OTHERTYPE","CLEARED","SELFDEC_BAL","CLEARED_VAL","TP"]);
/**
* clear all the warnings for assets
*/
rules.clearwarnings("assets")
var __t = "";
//console.log("assets",mar.answers.v2.assets);
if (!mar.answers.v2.assets) {
mar.answers.v2.assets = {};
}
console.log("JC", mar.answers.Y, mar.answers.M, mar.answers.TP);
let assettypes = ["bank","k401","stock","nprf","gifts","cash","emd","ira","other","savings"]
let arr = function(S) {
if (typeof S == "string") return S.split(",");
return S;
}
if ("items" in mar.answers.v2.assets) {
MAR.assets.addGidsToItems(mar.answers.v2.assets.items);
MAR.assets.repairGroups2();
MAR.assets.setAnyEmptyBankStatements();
/**
* make sure there are no empty income types
*/
for (let i=0; i < assettypes.length; i++) {
let _assettype = assettypes[i];
if (_assettype in mar.answers.v2.assets == false || mar.answers.v2.assets[_assettype] == false) {
mar.answers.v2.assets[_assettype] = {
total : 0
}
} else {
mar.answers.v2.assets[_assettype].total = 0;
}
}
for (let i=0; i < mar.answers.v2.assets.items.length; i++) {
let ass = mar.answers.v2.assets.items[i];
if (ass === false) continue;
if (MAR.getOpt(ass,"balance",null) === null && MAR.getOpt(ass,"__enc_balance",null) !== null) {
ass.balance = ass.__enc_balance;
}
if (MAR.getOpt(ass, "__deleted", "") === "Y") continue;
if (ass.type == ""|| ass.type === "undefined") ass.type = "other";
if (TYPE !== false && TYPE !== "" && TYPE !== ass.type) continue;
retval.matching_cnt++;
ass.enc_id = `${ass.gid}/${ass.gidindex}`;
if (MAR.getOpt(ass, "verified", "").toUpperCase() === "N") retval.has_unverified_items = true;
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
ass.vapplicantnum = MAR.applicants.vid(num(ass.applicantnum));
ass._M = MAR.application.M();
ass._Y = MAR.application.Y();
ass._TP = MAR.application.TP();
//if (ass.applicantnum > 10) ass.applicantnum = 0;
(function(){
let cd = MAR.getOpt(mar.answers, "cleared_dates", {});
for (let x in cd) {
if (x.startsWith("/assets/") && x.indexOf(ass.uuid) > -1) {
ass._cleared_dates = cd[x];
return;
}
if (typeof ass.gid === "string") {
if (x.startsWith("/assets/") && x.indexOf(ass.gid) > -1) {
ass._cleared_dates = cd[x];
return;
}
}
}
ass._cleared_dates = false;
})();
if (ass.type == "bank") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
var val = __v;
var cantake = __cantake;
ass.institution_nameb64 = ("institution_name" in ass) ? Base64.encode(ass.institution_name) : "-";
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
if (ass.applicantnum > 10) ass.applicantnum = 0;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_bankitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.bank.total += __v;
mar.answers.v2.assets.bank.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
let _who = "";
if ("whose_name" in ass) {
_who = ass.whose_name
}
retval.detailmatrix.push([
"checking",
_who,
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
let __who = (typeof _who === "string") ? _who : _who.join(",");
if (__who.split(",").length > 0 && num(__who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(__who.split(",")[0])] += num(__v);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
}
if (ass.type == "k401") {
var __v = num(ass.balance);
var __cantake = ass.can_take_freely;
var __n = ("institution_name" in ass) ? ass.institution_name : "";
/* rules */
var val = __v;
var cantake = __cantake;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
ass.part2 = ("institution_name" in ass) ? Base64.encode(""+ass.institution_name+"") : "";
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
if (ass.applicantnum > 10) ass.applicantnum = 0;
let warning_type = "assets_k401item";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.k401.total += __v;
mar.answers.v2.assets.k401.active = true;
retval.total += __v;
__t = "item "+i + " / " + __cantake;
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
let _who = "";
if ("whose_name" in ass) {
_who = ass.whose_name
}
retval.detailmatrix.push([
"retirement",
_who,
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
let __who = (typeof _who === "string") ? _who : _who.join(",");
if (__who.split(",").length > 0 && num(__who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(__who.split(",")[0])] += num(__v);
}
if (ass.type == "stock") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
var val = __v;
var cantake = __cantake;
ass.val = val;
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
if (ass.applicantnum > 10) ass.applicantnum = 0;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_stockitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.stock.total += __v;
mar.answers.v2.assets.stock.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
let _who = "";
if ("whose_name" in ass) {
_who = ass.whose_name
}
retval.detailmatrix.push([
"stock",
_who,
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
let __who = (typeof _who === "string") ? _who : _who.join(",");
if (__who.split(",").length > 0 && num(__who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(__who.split(",")[0])] += num(__v);
}
if (ass.type == "nprf") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "Net Proceeds from Sale";
var val = __v;
var cantake = __cantake;
ass.val = val;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_nprfitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.nprf.total += __v;
mar.answers.v2.assets.nprf.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
retval.detailmatrix.push([
"proceedsfromsale",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
if (ass.type == "gifts") {
var __v = num(ass.balance);
var __fromrelative = ass.fromrelative;
var __n = ("institution_name" in ass) ? ass.institution_name : "";
/* rules */
var val = __v;
var fromrelative = __fromrelative;
ass.nameb64 = ("can_get_gift_letter_name" in ass) ? Base64.encode(ass.can_get_gift_letter_name) : "-";
ass.relationshipb64 = ("can_get_gift_letter_relationship" in ass) ? Base64.encode(ass.can_get_gift_letter_relationship) : "-";
ass.phoneb64 = ("can_get_gift_letter_phone_number" in ass) ? Base64.encode(ass.can_get_gift_letter_phone_number) : "-";
ass.emailb64 = ("can_get_gift_letter_email" in ass) ? Base64.encode(ass.can_get_gift_letter_email) : "-";
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_giftsitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
val : val,
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.gifts.total += __v;
mar.answers.v2.assets.gifts.active = true;
// retval.k401 += __v;
retval.total += __v;
__t = "item "+i + "/" + __fromrelative + "/"+ass.relationshipb64;
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
retval.detailmatrix.push([
"gifts",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
if (ass.type == "emd") {
var __v = num(ass.balance);
var val = __v;
ass.val = val;
var __n = ("institution_name" in ass) ? ass.institution_name : "Earnest Money Deposit";
if ("last4digitsuuid" in ass) {
let _linkedasset = MAR.assets.getByUUID(ass.last4digitsuuid);
if (_linkedasset !== false) {
ass.last4digits = MAR.getOpt(_linkedasset, "last4digits","");
}
}
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_emditem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.emd.total += __v;
mar.answers.v2.assets.emd.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
retval.detailmatrix.push([
"emd",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
if (ass.type == "cash") {
var __v = num(ass.balance);
if ("how_obtained" in ass) {
if (ass.how_obtained == "sold") {
ass.can_take_freely = ("have_bill_of_sale" in ass) ? ass.have_bill_of_sale : "";
}
if (ass.how_obtained == "labor") {
ass.can_take_freely = ("can_provide_invoices" in ass) ? ass.can_provide_invoices : "";
}
if (ass.how_obtained == "gift") {
ass.can_take_freely = ("can_get_gift_letter" in ass) ? ass.can_get_gift_letter : "";
// ["ass.can_get_gift_letter_name", "Text - if gift"],
// ["ass.can_get_gift_letter_relationship", "Text - if gift"],
// ["ass.can_get_gift_letter_phone_number", "Text - if gift"],
// ["ass.can_get_gift_letter_email", "Text - if gift"],
// ["ass.can_get_gift_letter_permission", "Y/N - if gift"],
}
}
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
ass.applicantnum = ("whose_name" in ass) ? ass.whose_name[0] : 0;
/* rules */
var val = __v;
var cantake = __cantake;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_cashitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.cash.total += __v;
mar.answers.v2.assets.cash.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
retval.detailmatrix.push([
"cash",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
if (ass.type == "savings") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
var val = __v;
var cantake = __cantake;
ass.institution_nameb64 = ("institution_name" in ass) ? Base64.encode(ass.institution_name) : "-";
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
if (ass.applicantnum > 10) ass.applicantnum = 0;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_bankitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.savings.total += __v;
mar.answers.v2.assets.savings.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
let _who = "";
if ("whose_name" in ass) {
_who = ass.whose_name
}
retval.detailmatrix.push([
"savings",
_who,
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
let __who = (typeof _who === "string") ? _who : _who.join(",");
if (__who.split(",").length > 0 && num(__who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(__who.split(",")[0])] += num(__v);
// retval.per_applicant[0] += num(__v);
// var __v = num(ass.balance);
// var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
// var __n = ("institution_name" in ass) ? ass.institution_name : "";
//
// /* rules */
// var val = __v;
// var cantake = __cantake;
// rules.get("assets_savingsitem").forEach(function(item){
// eval("var _fn = "+item+";");
// _fn(PROG);
// _fn = null;
// });
// __v = val;
//
// mar.answers.v2.assets.savings.total += __v;
// mar.answers.v2.assets.savings.active = true;
// retval.total += __v;
//
// __t = "item "+i
//
// retval.detailmatrix.push([
// "savings",
// "",
// __n, // name
// __v, // vlaue
// __t, // notes
// i
// ]);
}
if (ass.type == "ira") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
/* rules */
var val = __v;
var cantake = __cantake;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
ass.part2 = ("institution_name" in ass) ? Base64.encode(""+ass.institution_name+"") : "";
ass.applicantnum = ("whose_name" in ass) ? arr(ass.whose_name)[0] : 0;
if (ass.applicantnum > 10) ass.applicantnum = 0;
let warning_type = "assets_iraitem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.ira.total += __v;
mar.answers.v2.assets.ira.active = true;
retval.total += __v;
__t = "item "+i
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
retval.detailmatrix.push([
"ira",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
"",
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
if (ass.type == "other") {
var __v = num(ass.balance);
var __cantake = ("can_take_freely" in ass) ? ass.can_take_freely : "";
//var __n = ("otherdescription" in ass) ? ass.otherdescription : "";
var __n = ("institution_name" in ass) ? ass.institution_name : "";
var __d = ass.otherdescription
var __on = ass.other_name
/* rules */
var val = __v;
var cantake = __cantake;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
val = ebval;
}
});
ass.warnings=[];
let warning_type = "assets_otheritem";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(ass.applicantnum),
item : ass
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
ass.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
__v = val;
ass._calcbalance = __v;
MAR.ifOptNum(ass, "__enc_balance", function(ebval){
if (ebval !== __v) {
__v = ebval;
}
});
ass._balance = __v;
mar.answers.v2.assets.other.total += __v;
mar.answers.v2.assets.other.active = true;
retval.total += __v;
__t = "item "+i+__d;
let __l4 = ("last4digits" in ass) ? ass.last4digits : "";
ass.enc_type = MAR.assets.getOtherTypeByText(__d,__on);
retval.detailmatrix.push([
"other",
"",
__n, // name
__v, // vlaue
__t, // notes
i,
__l4,
ass.uuid,
ass.enc_id,
ass.enc_type,
MAR.getOpt(ass,"cleared","")+"|"+MAR.getOpt(ass,"cleared_tp","")
]);
// if (_who.split(",").length > 0 && num(_who.split(",")[0]) < MAR.MAXBORROWERS) retval.per_applicant[num(_who.split(",")[0])] += num(__v);
retval.per_applicant[0] += num(__v);
}
}
} else {
/**
* old code
*/
}
retval.total = num(retval.total.toFixed(0));
retval.cleared_tot = 0;
retval.selfdec_tot = 0;
for (let i=1; i < retval.detailmatrix.length; i++) {
let itm = retval.detailmatrix[i];
if (itm[10].startsWith("Y")) {
itm.push(itm[3]);
itm.push(0);
itm.push(itm[10].split("|")[1]);
itm[10] = itm[10].split("|")[0];
retval.cleared_tot += itm[3];
} else {
itm.push(0);
itm.push(itm[3]);
itm.push(itm[10].split("|")[1]);
itm[10] = itm[10].split("|")[0];
retval.selfdec_tot += itm[3];
}
}
retval.detailmatrix.push(["","","","","","","total:",retval.total,"","","",retval.cleared_tot,retval.selfdec_tot,""]);
//console.log(mar.answers.v2.assets);
return retval;
}
/**
* declarations
*/
function getDeclarations_with_rules_v2 (PROG) {
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
var declarations = getDeclarations_v2();
if (declarations) {
/**
* clear all the warnings for assets
*/
rules.clearwarnings("declarations")
var applicantLength = getApplicants_v2().length;
for (var i=0; i < declarations.length; i++) {
if (i >= applicantLength) continue;
var first_time_buyer = "N";
var d = declarations[i];
var applicantnum = i;
var vapplicantnum = MAR.applicants.vid(applicantnum);
/* rules */
rules.get("declarations_judgements").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_bancruptcy").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_forclosure").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_lawsuit").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_shortsale").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_transferoftitle").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_delinquent").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_alimonyorchild").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_downpaymentborrowed").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_comakerendorsement").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_ownedproperty").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_ownrealestate").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_military").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i);
_fn = null;
});
/* rules */
rules.get("declarations_citizenship").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i,{
d : d
});
_fn = null;
});
declarations[i].first_time_buyer = first_time_buyer;
}
}
return declarations;
}
function isV2(SECTION) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if (!SECTION) return true;
if (SECTION in mar.answers.v2 == false) return false;
return true;
}
function getDeclarations_v2 () {
if (!mar.STATIC) setStaticVars();
if (!isV2("declarations")) return [];
var _s = getScenario_v2();
/**
* copy the new scenario based citizenship information over the declarations ones
*/
for (var i=0; i < mar.answers.v2.declarations.length; i++) {
/**
* if there is a new style then we can use all the elements
*/
if ("scenario_applicant"+(i+1)+"_usc" in _s) {
mar.answers.v2.declarations[i].us_citizen = _s["scenario_applicant"+(i+1)+"_usc"];
mar.answers.v2.declarations[i].greencard = _s["scenario_applicant"+(i+1)+"_gch"];
mar.answers.v2.declarations[i].visa_type = _s["scenario_applicant"+(i+1)+"_visa_type"];
mar.answers.v2.declarations[i].cntry = _s["scenario_applicant"+(i+1)+"_cntry"];
}
var _d = mar.answers.v2.declarations[i];
var citizenship = "";
if (_d.us_citizen == "Y") citizenship = "usc";
if (_d.us_citizen == "N" && _d.greencard == "Y") citizenship = "gch";
if (_d.us_citizen == "N" && _d.greencard == "N") citizenship = "neither";
mar.answers.v2.declarations[i].citizenship = citizenship;
if ("applicants" in mar.answers.v2) {
if (mar.answers.v2.applicants.length > i) {
mar.answers.v2.applicants[i].citizenship = citizenship;
}
}
/**
* now do the same for property owneship
*/
if ("has_applicant"+(i+1)+"_owned_property_in_last_3_years" in _s) {
mar.answers.v2.declarations[i].credit_owned_other_property_3yrs
= _s["has_applicant"+(i+1)+"_owned_property_in_last_3_years"];
mar.answers.v2.declarations[i].credit_owned_other_property_3yrs_type
= _s["has_applicant"+(i+1)+"_owned_property_in_last_3_years_type"];
mar.answers.v2.declarations[i].credit_owned_other_property_3yrs_how
= _s["has_applicant"+(i+1)+"_owned_property_in_last_3_years_how"];
mar.answers.v2.declarations[i].credit_currently_own_realestate
= _s["does_applicant"+(i+1)+"_own_property"];
}
/**
* now do the same copy for VA
*/
if ("has_applicant"+(i+1)+"_served_in_us_forces" in _s) {
mar.answers.v2.declarations[i].credit_currently_or_previously_served
= _s["has_applicant"+(i+1)+"_served_in_us_forces"];
mar.answers.v2.declarations[i].va_employment
= _s["va_employment"+(i+1)];
mar.answers.v2.declarations[i].va_disabled
= _s["va_disabled"+(i+1)];
mar.answers.v2.declarations[i].va_disabled_percentage
= _s["va_disabled"+(i+1)+"_percentage"];
mar.answers.v2.declarations[i].vafirst_time_use
= _s["vafirst_time_use"+(i+1)];
}
if ("additional_mortgage" in _d === false) _d.additional_mortgage = "";
if ("additional_loan" in _d === false) _d.additional_loan = "";
if ("priority_lein" in _d === false) _d.priority_lein = "";
if ("special_realtionship" in _d === false) _d.special_realtionship = "";
function add_date(str,pfx,d) {
let da = (typeof d !== "undefined") ? d : MAR.getOpt(_d, str, false);
if (da === false || da.trim() === "") {
return "(date not specified)";
}
let current_date = new Date();
let past_date = new Date(da);
var diff = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());
if (diff <= 12) diff = `${diff} months`;
else if (diff % 12 === 0) diff = `${~~(diff/12)} years`;
else if (diff % 12 === 1) diff = `${~~(diff/12)} years 1 month`;
else diff = `${~~(diff/12)} years ${diff%12} months`;
return `(${pfx}${diff} ago)`
}
_d.derogatories = [];
if (MAR.getOpt(_d, "credit_has_judgements", "") === "Y") _d.derogatories.push(`outstanding judgement`);
if (MAR.getOpt(_d, "credit_has_bancruptcy", "") === "Y") {
let s = [`bankruptcy`];
let c = MAR.getOpt(_d, "credit_has_bancruptcy_chapter", "");
let r = MAR.getOpt(_d, "credit_has_bancruptcy_resolved", "")
let d = MAR.getOpt(_d, "credit_has_bancruptcy_resolution_date", "")
if (c !== "") s.push(`${mar._txt(c)}`);
if (r === "dismissed" || r === "discharged") {
s.push(add_date(false, `${r} `, d));
} else if (r !== "") {
s.push(`${r}`);
}
_d.derogatories.push(s.join(" "));
}
if (MAR.getOpt(_d, "credit_has_forclosures", "") === "Y") {
_d.derogatories.push(`foreclosure ${add_date("credit_has_forclosures__date","dismissed ")}`);
}
if (MAR.getOpt(_d, "credit_has_lawsuit", "") === "Y") {
if (MAR.getOpt(_d, "credit_has_lawsuit_cost_money", "") === "Y") {
_d.derogatories.push(`lawsuit with financial impact`);
} else {
_d.derogatories.push(`lawsuit without financial impact`);
}
}
if (MAR.getOpt(_d, "credit_has_shortsale", "") === "Y") {
let s = [`short sale`];
let t = MAR.getOpt(_d, "credit_has_shortsale_title", "");
let d = MAR.getOpt(_d, "credit_has_shortsale_date", "")
if (t === "Y") s.push("on title")
if (t === "N") s.push("not on title")
s.push(add_date(false, `sale date `, d));
_d.derogatories.push(s.join(" "));
}
if (MAR.getOpt(_d, "credit_has_transferoftitle", "") === "Y") {
let s = [`transfer of title`];
let d = MAR.getOpt(_d, "credit_has_transferoftitle__date", "")
s.push(add_date(false, `date `, d));
_d.derogatories.push(s.join(" "));
}
if (MAR.getOpt(_d, "credit_delinquent_on_federal_debt", "") === "Y") {
if (MAR.getOpt(_d, "credit_delinquent_on_federal_debt_type", "") === "tax") {
_d.derogatories.push(`delinquent on federal debt`);
}
if (MAR.getOpt(_d, "credit_delinquent_on_federal_debt_type", "") === "mortgage") {
_d.derogatories.push(`delinquent on mortgage or loan`);
}
if (MAR.getOpt(_d, "credit_delinquent_on_federal_debt_type", "") === "both") {
_d.derogatories.push(`delinquent on both federal debt and mortgage/loan`);
}
}
if (MAR.getOpt(_d, "credit_obligated_to_pay_alimony_or_child", "") === "Y") _d.derogatories.push(`alimony or child support obligation`);
if (MAR.getOpt(_d, "credit_irs_plan", "") === "Y") _d.derogatories.push(`irs payment plan`);
if (MAR.getOpt(_d, "credit_downpayment_borrowed", "") === "Y") {
let v = MAR.getOpt(_d, "credit_downpayment_borrowed_value", "");
_d.derogatories.push(`will borrow part of the downpayment (\$${v})`);
}
if (MAR.getOpt(_d, "credit_comaker_or_endorser", "") === "Y") _d.derogatories.push(`comaker or endorser`);
if (MAR.getOpt(_d, "additional_mortgage", "") === "Y") _d.derogatories.push(`applying for additional mortgage`);
if (MAR.getOpt(_d, "additional_loan", "") === "Y") _d.derogatories.push(`applying for additional credit`);
if (MAR.getOpt(_d, "priority_lein", "") === "Y") _d.derogatories.push(`subject to a priority lien`);
/*
"credit_owned_other_property_3yrs": "Y",
"credit_owned_other_property_3yrs_type": "1",
"credit_owned_other_property_3yrs_how": "25",
"credit_currently_own_realestate": "Y",
*/
}
return mar.answers.v2.declarations;
}
function getDeclaration_v2 (n) {
if (!mar.STATIC) setStaticVars();
return getDeclarations_v2()[n];
}
/**
* get applicants
*/
function getApplicants_v2() {
if (!mar.STATIC) setStaticVars();
return mar.answers.v2.applicants;
}
/**
* get applicants
*/
function getApplicants_num() {
if (!mar.STATIC) setStaticVars();
return mar.answers.v2.applicants.length;
}
/**
* get applicants
*/
function getApplicant_v2(n) {
if (!mar.STATIC) setStaticVars();
return MAR.getOpt(getApplicants_v2(), `${n}`, {});
}
/*
* {
* "bucketid":"/applicants/data/0/b085bac4-f5af-4fd0-9d83-d7a78ca489a3",
* "uuid":"b085bac4-f5af-4fd0-9d83-d7a78ca489a3",
* "fn":"Laudine","ln":"Carter","mn":"",
* "sn":"111111111",
* "em":"j@j.com",
* "ph":"1001010101",
* "db":"1980-01-01",
* "ms":"U",
* "de":"0",
* "age1":"","age2":"","age3":"","age4":"","age5":"","age6":"",
* "h1":"Y",
* "h2":"",
* "h3":"",
* "h4":"",
* "ge":""
* }
*
*/
function getApplicant_bucket(n){
var applicant = getApplicantBucket(n);
if (applicant == null) return "";
return JSON.stringify(applicant);
}
function getApplicant_generic_bucket(n,VAR){
var applicant = getApplicantBucket(n);
if (applicant == null) return "";
if (VAR in applicant) return applicant[VAR];
return "";
}
function getApplicant_dob(n){ return getApplicant_generic_bucket(n,"db"); }
function getApplicant_sn(n){ return getApplicant_generic_bucket(n,"sn"); }
function getApplicant_em(n){ return getApplicant_generic_bucket(n,"em"); }
function getApplicant_ph(n){ return getApplicant_generic_bucket(n,"ph"); }
function getApplicant_ms(n){ return getApplicant_generic_bucket(n,"ms"); }
function getApplicant_h1(n){ return getApplicant_generic_bucket(n,"h1"); }
function getApplicant_h2(n){ return getApplicant_generic_bucket(n,"h2"); }
function getApplicant_h3(n){ return getApplicant_generic_bucket(n,"h3"); }
function getApplicant_h4(n){ return getApplicant_generic_bucket(n,"h4"); }
function getApplicant_ge(n){ return getApplicant_generic_bucket(n,"ge"); }
function getApplicant_fn(n){ return getApplicant_generic_bucket(n,"fn"); }
function getApplicant_ln(n){ return getApplicant_generic_bucket(n,"ln"); }
function getApplicant_addresses_ashtml(n){
var ads = getApplicantAddresses(n);
var rv = "";
if (ads == null) return rv;
ads.forEach(function(ad){
rv += "
"+addressToString(ad)+"
";
})
return rv;
}
function getApplicant_current_address_ashtml(n){
var ads = MAR.getApplicantAddressCurrent(n);
var rv = "";
if (ads == null) return rv;
ads.forEach(function(ad){
rv += ""+addressToString(ad)+"
";
})
return rv;
}
function getApplicant_current_address(n){
var ads = MAR.getApplicantAddressCurrent(n);
var rv = "";
if (ads == null) return rv;
if (ads.length === 0) return rv;
return MAR.getOpt(ads[0], "address" , "");
}
function getApplicant_current_address_for_esign(n){
var ads = MAR.getApplicantAddressCurrent(n);
var rv = "";
if (ads == null) return rv;
if (ads.length === 0) return rv;
return addressToString( MAR.getOpt(ads[0], "address" , "")).replace(//g, "").replace(/<\/div>/g, "\n");
}
/**
* buckets
*/
function notnull(v,obj) {
if (v in obj) return obj[v];
return "";
}
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = MAR.Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function getApplicantBucket(n) {
var _applicant = getApplicant_v2(n);
if ("bucketid" in _applicant) {
let _rv = getBucket(_applicant.bucketid);
try {
if (_rv !== null && _rv !== false) {
_da = MAR.Date(_rv.db);
_rv._da = _da;
_rv.ag = _calculateAge(_da);
}
} catch (E) {
console.warn(E);
}
return _rv;
}
return null;
}
/**
*
*/
function getApplicantAddresses(n) {
var _applicant = getApplicant_v2(n);
var retval = [];
if ("addresses" in _applicant) {
_applicant.addresses.forEach(function(bucketid){
retval.push(getBucket(bucketid));
})
}
return retval;
}
/**
* @namespace MAR_scenario
*/
/**
* @namespace MAR_buckets
*/
/**
* @namespace MAR_applicants
*/
/**
* @namespace MAR
*/
var MAR = (function(){
let MAXBORROWERS = 8;
/**
* Generate a UUID
* @alias MAR.uuidv4
* @memberof MAR
*/
function uuidv4() {
if (typeof el_uuid === "undefined") {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
} else {
return el_uuid.gen();
}
}
/**
* Generate a human version of a number e.g. third, fourth
* @alias MAR.th
* @memberof MAR
*/
function th(n) {
if (n == 1) return "first";
if (n == 2) return "second";
if (n == 3) return "third";
if (n == 4) return "fourth";
if (n == 5) return "fifth";
if (n == 6) return "sixth";
if (n == 7) return "seventh";
if (n == 8) return "eight";
if (n == 9) return "nineth";
if (n == 10) return "tenth";
return "";
}
/**
* Generate a human version of a number e.g. 1st 2nd
* @alias MAR.rd
* @memberof MAR
*/
function rd(n) {
if (n == 1) return "1st";
if (n == 2) return "2nd";
if (n == 3) return "3rd";
if (n == 4) return "4th";
if (n == 5) return "5th";
if (n == 6) return "6th";
if (n == 7) return "7th";
if (n == 8) return "8th";
if (n == 9) return "9th";
if (n == 10) return "10th";
return "";
}
/**
* Generate a human version of a number e.g. 1st 2nd
* @alias MAR.numName
* @memberof MAR
*/
function numName(n) {
if (n == 1) return "one";
if (n == 2) return "two";
if (n == 3) return "three";
if (n == 4) return "four";
if (n == 5) return "five";
if (n == 6) return "six";
if (n == 7) return "seven";
if (n == 8) return "eight";
if (n == 9) return "nine";
if (n == 10) return "ten";
return "";
}
/**
* Get an options value
* @alias MAR.equalsIgnoreCase
* @memberof MAR
*/
function equalsIgnoreCase(a , b) {
if (typeof a !== "string") return false;
if (typeof b !== "string") return false;
return (a.toLowerCase() === b.toLowerCase());
}
/**
* Get an options value
* @alias strCmp
* @memberof MAR
*/
function strCmp(a , b) {
return (`${a}` === `${b}`);
}
/**
* Get an options value
* @alias MAR.contains_string
* @memberof MAR
*/
function contains_string(Str, S) {
if (typeof Str !== "string") return false;
if (typeof S === "string") {
return (Str.indexOf(S) > -1);
}
if (Array.isArray(S) === true) {
for (let i=0; i < S.length; i++) {
if (typeof S[i] === "string" && Str.indexOf(S[i]) > -1) return true;
}
}
return false;
}
/**
* Get an options value
* @alias MAR.contains_string_ignore_case
* @memberof MAR
*/
function contains_string_ignore_case(Str, S) {
if (typeof Str !== "string") return false;
return contains_string(Str.toLowerCase(), S);
}
/**
* Get an options value
* @alias MAR.notNull
* @memberof MAR
*/
let notNull = function(VAR, DEF) {
if (typeof VAR === "undefined") return DEF;
if (VAR === null) return DEF;
if (typeof VAR === "number") return VAR;
if (typeof VAR === "string") return VAR;
if (!VAR) return DEF;
return VAR;
}
function createIfNotExist(obj, fld, def) {
if (typeof obj !== "object") return;
if (fld in obj) return;
obj[fld] = def
}
/**
* Get an options value
* @alias MAR.getOpt
* @memberof MAR
*/
function getOpt(obj , fld, def, ignore_dots = false) {
if (typeof obj === 'undefined') return def;
if (typeof obj === 'boolean') return def;
if (typeof obj === 'number') return def;
if (typeof obj === 'string') return def;
if (obj === null) return def;
if (Array.isArray(fld)) {
for (let i=0; i < fld.length; i++) {
let val = getOpt(obj, fld[i], null);
if (val !== null) {
return val;
}
}
return def;
}
if (fld.indexOf(".") < 0 || ignore_dots === true) {
if (fld in obj) return obj[fld];
return def;
}
let keys = fld.split(".");
let obref = obj;
while (keys.length > 1) {
let _key = keys.shift();
if (obref === false) return def;
if (typeof obref === 'undefined') return def;
if (typeof obref === 'boolean') return def;
if (typeof obref === 'number') return def;
if (typeof obref === 'string') return def;
if (obref === null) return def;
if (_key in obref == false) return def;
obref = obref[_key]
}
if (obref === null) return def;
if (typeof obref !== 'object') return def;
fld = keys[0];
if (fld in obref) return obref[fld];
return def;
}
/**
* Get an options value and escape the "'"
* @alias MAR.getOptS
* @memberof MAR
*/
function getOptS(obj , fld, def) {
let rv = getOpt(obj, fld, def);
if (typeof rv === "string") rv = rv.replace(/'/g, "'");
return rv;
}
/**
* Get an options but empty string is also false
* @alias MAR.getOptEmptyString
* @memberof MAR
*/
function getOptEmptyString(obj , fld, def) {
let rv = getOpt(obj, fld, def);
if (typeof rv === "string" && rv === "") return def;
return rv;
}
/**
* Get an options value and escape the "'"
* @alias MAR.getOptS
* @memberof MAR
*/
function getOptNum(obj , fld, def) {
let rv = getOpt(obj, fld, null);
if (rv === null) return def;
return num(rv);
}
/**
* Get return null if the value matched any of the array
* @alias MAR.getOptS
* @memberof MAR
*/
function nullIf(val, arr) {
for (let i=0; i < arr.length; i++) {
if (val === arr[i]) return null;
}
return val;
}
/**
* Get an options value and escape the "'"
* @alias MAR.getOptString
* @memberof MAR
*/
function getOptString(obj , fld, def) {
let rv = getOpt(obj, fld, null);
if (rv === null) return def;
if (typeof rv !== "string") return def;
return rv;
}
/**
* Delete an options value
* @alias MAR.delOpt
* @memberof MAR
*/
function delOpt(obj , fld) {
if (fld.indexOf(".") < 0) {
if (fld in obj) delete obj[fld];
return;
}
let keys = fld.split(".");
let obref = obj;
while (keys.length > 1) {
let _key = keys.shift();
if (_key in obref == false) return;
obref = obref[_key]
}
fld = keys[0];
if (fld in obref) delete obref[fld];
return;
}
/**
* if an options value
* @alias MAR.ifOpt
* @memberof MAR
*/
function ifOpt(obj, fld, fn, elsefn) {
let _val = getOpt(obj, fld, null);
if (_val !== null) {
fn (_val)
} else {
if (elsefn) elsefn();
}
}
/**
* if an options value
* @alias MAR.ifOpt
* @memberof MAR
*/
function ifOptNum(obj, fld, fn, elsefn) {
let _val = getOpt(obj, fld, null);
if (_val !== null) {
fn (num(_val))
} else {
if (elsefn) elsefn();
}
}
/**
* if an options value
* @alias MAR.ifOpt
* @memberof MAR
*/
function ifOpts(obj, flds, fn, elsefn) {
let rv = {};
let found = false;
for (let i=0; i < flds.length; i++) {
ifOpt(obj, flds[i], function(val) {
rv[flds[i]] = val;
found = true;
})
}
if (found) {
fn (rv)
} else {
if (elsefn) elsefn();
}
}
/**
* if an options value
* @alias MAR.ifNotOpt
* @memberof MAR
*/
function ifNotOpt(obj, fld, fn) {
if (fld in obj === false) {
fn ()
}
}
/**
* extend or replace an object
* @alias MAR.extend_replace
* @memberof MAR
*/
function extend_replace(obj, obj1) {
for (let x in obj1) {
obj[x] = obj1[x]
}
}
/**
* create a key if not present
* @alias MAR.createOpt
* @memberof MAR
*/
function createOpt(obj, key, val) {
if (key in obj === false) obj[key] = val;
}
/**
* Set an options value
* @alias MAR.setOpt
* @memberof MAR
*/
function setOpt(ob, key, val) {
let changed = false;
if (key.indexOf(".") < 0) {
changed = (key in ob) ? isDiff(ob[key], val) : true;
ob[key] = val;
return changed;
}
let keys = key.split(".");
let obref = ob;
while (keys.length > 1) {
let _key = keys.shift();
if (_key in obref == false) {
changed = true;
obref[_key] = {}
}
obref = obref[_key]
}
changed = (keys[0] in obref) ? isDiff(obref[keys[0]], val) : true;
obref[keys[0]] = val;
return changed;
}
/**
* Push an options value
* @alias MAR.pushOpt
* @memberof MAR
*/
function pushOpt(ob, key, val) {
let val1 = getOpt(ob, key, []);
if (!val1) val1 = [];
val1.push(val);
setOpt(ob, key, val1);
}
/**
* Push an options value
* @alias MAR.isEmpty
* @memberof MAR
*/
function isEmpty(ob) {
if (typeof ob !== "object") return true;
return (Object.keys(ob).length === 0);
}
/**
* Push an options value
* @alias isEmptyString
* @memberof MAR
*/
function isEmptyString(ob) {
return (typeof ob === "string" && ob === "");
}
/**
* Push an options value
* @alias isEmptyString
* @memberof MAR
*/
function isNonEmptyString(ob) {
return (typeof ob === "string" && ob !== "");
}
/**
* Push an options value
* @alias MAR.isDiff
* @memberof MAR
*/
function isDiff(a , b) {
if (a === b) return false;
return true;
}
/**
* if an options value
* @alias array_to_kv
* @memberof MAR
*/
function array_to_kv(arr, k_name, v_name) {
let rv = {};
for (let i=0; i < arr.length; i++) {
ifOpt(arr[i], k_name, function(k_val) {
ifOpt(arr[i], v_name, function(v_val) {
rv[k_val] = v_val;
});
});
}
return rv;
}
/**
* number array an options value
* @alias MAR.numberArray
* @memberof MAR
*/
function numberArray(arr) {
let _arr = arr;
for (let i=0; i < _arr.length; i++) {
if (typeof _arr[i] === "string") {
_arr[i] = parseInt(_arr[i],10);
}
}
function contains(n) {
if (typeof n === "string") n = parseInt(n,10);
return (_arr.indexOf(n) > -1);
}
function raw() {
return _arr;
}
return {
raw : raw,
contains : contains,
___id : "number array"
}
}
/**
* Get scenario data
* @alias MAR.getScenario_data
* @memberof MAR
*/
function _getScenario_data(key,def) {
return getScenario_data(key,def);
}
/**
* Push an options value
* @alias MAR.is_refi
* @memberof MAR
*/
function is_refi() {
let loan_type = getV2_data("loan_type","purchase");
let REFI = (loan_type != "purchase");
return REFI;
}
/**
* Push an options value
* @alias MAR.is_phase_rq
* @memberof MAR
*/
function is_phase_rq() {
if (typeof mar.WE_ARE_FROM_LOI === "boolean" && mar.WE_ARE_FROM_LOI === true) return false;
let phase = getScenario_data("phase" , "");
if (phase.startsWith("rq")) return true;
return false;
}
/**
* Push an options value
* @alias MAR.is_phase_rq_password
* @memberof MAR
*/
function is_phase_rq_password() {
if (typeof mar.WE_ARE_FROM_LOI === "boolean" && mar.WE_ARE_FROM_LOI === true) return false;
let phase = getScenario_data("phase" , "");
if (phase.startsWith("rq-password")) return true;
return false;
}
/**
* Push an options value
* @alias MAR.is_refi_cashout
* @memberof MAR
*/
function is_refi_cashout() {
if (is_refi() === false) return false;
let options = getScenario_data("refi_options" , "");
return (options === "cashout");
}
/**
* Push an options value
* @alias MAR.is_refi_cashout
* @memberof MAR
*/
function is_refi_limited_cashout() {
if (is_refi() === false) return false;
let options = getScenario_data("refi_options" , "");
return (options === "closing");
}
/**
* Push an options value
* @alias MAR.is_refi_cashout
* @memberof MAR
*/
function is_refi_rat() {
if (is_refi() === false) return false;
let options = getScenario_data("refi_options" , "");
return (options === "nclosing" || options === "noclosing");
}
/**
* Push an options value
* @alias MAR.is_purchase
* @memberof MAR
*/
function is_purchase() {
return !MAR.is_refi();
}
/**
* get applicant pairs for encompass and 4506t?
* @function
* @memberof MAR_applicants
*/
function get_ssns() {
let _applicants = getApplicants_v2();
return _applicants;
}
/**
* get applicant pairs for encompass and 4506t?
* @function
* @memberof MAR_applicants
*/
function getBorrowerPairs() {
let _applicants = getApplicants_v2();
let bp_array = [];
let bp_rev = {};
let bp_fwd = [];
let dbg = [];
let double_arr = [[false,false],[false,false],[false,false],[false,false],[false,false],[false,false],[false,false],[false,false]];
let there_are_bps = false;
/**
* bp_array is
* [ 0: { borrower : false|num , coborrower : false|num, brelate : "spouse", t4506joint : t/f }]
* [ 1: { borrower : false|num , coborrower : false, brelate : "spouse", t4506joint : f }]
* [ 2: { borrower : false|num , coborrower : false, brelate : "spouse", t4506joint : f }]
*
*/
(function look_for_gaps() {
let there_are_no_gaps = false;
let valve = 8;
while (valve > 0 && there_are_no_gaps !== true) {
let pairs = [false,false,false,false,false,false,false,false];
let act_pairs = [[false,false],[false,false],[false,false],[false,false],[false,false],[false,false],[false,false],[false,false]]
let high_pair = 0;
for (let i=0; i < _applicants.length ; i++) {
let _applicant = getApplicant_v2(i);
let type = _applicant.type; // borrower, coborrower, spouse, nonoccupentcoborrower
if ("bp" in _applicant == true && _applicant.bp !== "") { // 0B 0C 1B 1C
there_are_bps = true;
let _bp = _applicant.bp.split(""); // [0,C]
let _bpnum = num(_bp[0]); // 0
let _bpbc = _bp[1]; // C
pairs[_bpnum] = true; // pairs [0] = true
if (_bpbc === "B") {
act_pairs[_bpnum][0] = i;
}
if (_bpbc === "C") {
act_pairs[_bpnum][1] = i;
}
if (_bpnum > high_pair) high_pair = _bpnum;
}
}
there_are_no_gaps = true;
for (let i=0; i < high_pair; i++) {
if (pairs[i] === false) {
/**
* there is a gap
*/
for (let j = i+1; j < (high_pair+1); j++) {
let _act_pair = act_pairs[j];
if (_act_pair[0] !== false) {
mar.answers.v2.applicants[_act_pair[0]].bp = `${(j-1)}B`;
}
if (_act_pair[1] !== false) {
mar.answers.v2.applicants[_act_pair[1]].bp = `${(j-1)}C`;
}
}
there_are_no_gaps = false;
valve--;
_applicants = getApplicants_v2();
break;
}
}
dbg.push({lookforpairs : pairs});
}
})();
for (let i=0; i < _applicants.length ; i++) {
let _applicant = getApplicant_v2(i);
let type = _applicant.type; // borrower, coborrower, spouse, nonoccupentcoborrower
if ("bp" in _applicant == true && _applicant.bp !== "") { // 0B 0C 1B 1C
let _bp = _applicant.bp.split("");
let _bpnum = num(_bp[0]);
let _bpbc = (_bp[1] == "C") ? "coborrower" : "borrower";
while (bp_array.length <= _bpnum) {
bp_array.push({
borrower : false,
coborrower : false,
t4506joint : false
})
}
bp_rev[_applicant.bp] = i;
bp_fwd[i] = _applicant.bp;
bp_array[_bpnum][_bpbc] = i;
dbg.push(`applicant ${i} HAD a BP of ${_applicant.bp}`);
continue;
}
if (bp_array.length == 0) {
bp_array.push({
borrower : 0,
coborrower : false,
t4506joint : false
})
bp_fwd[0] = "0B";
bp_rev["0B"] = 0;
dbg.push(`applicant ${i} WAS THE FIRST`);
continue;
}
if (type == "spouse") {
if (bp_array[0].coborrower === false) {
bp_array[0].coborrower = i;
bp_array[0].corelate = type;
bp_array[0].t4506joint = getApplicantsAreJoint(0,1);
bp_array[0].t4506jointdbg = getApplicantsAreJointDbg(0,1);
bp_fwd[i] = "0C";
bp_rev["0C"] = i;
dbg.push(`applicant ${i} WAS A SPOUSE AND WAS ADDED TO 0`);
}
continue;
}
if (bp_array.length > 0) {
bp_array.push({
borrower : i,
coborrower : false,
brelate : type,
t4506joint : false
})
bp_fwd[i] = `${(bp_array.length - 1)}B`;
bp_rev[`${(bp_array.length - 1)}B`] = i;
dbg.push(`applicant ${i} WAS NORMAL AND BECAME ${bp_fwd[i]} `);
continue;
}
// if (bp_array.length == 2) {
// bp_array.push({
// borrower : 0,
// coborrower : false,
// brelate : type,
// t4506joint : false
// })
// bp_fwd[i] = `${(bp_array.length - 1)}B`;
// bp_rev[`${(bp_array.length - 1)}B`] = i;
// continue;
// }
}
/**
* fill in the 4506ts
*/
for (let i=0; i < bp_array.length; i++) {
let pair = bp_array[i];
if (pair.borrower !== false && pair.coborrower !== false) {
pair.t4506joint = getApplicantsAreJoint(pair.borrower,pair.coborrower);
pair.t4506jointdbg = getApplicantsAreJointDbg(pair.borrower,pair.coborrower);
}
}
/**
* create the borrowe pairings for encompass
*/
let index = [];
let indexobj = {};
for (let i=0; i < bp_array.length; i++) {
let pair = bp_array[i];
index[pair.borrower] = {
appindex : i,
type : "borrower"
}
indexobj[`b${pair.borrower}`] = {
appindex : i,
type : "borrower"
}
double_arr[i][0] = pair.borrower;
if (pair.coborrower !== false) {
index[pair.coborrower] = {
appindex : i,
type : "coborrower"
}
indexobj[`b${pair.coborrower}`] = {
appindex : i,
type : "coborrower"
}
double_arr[i][1] = pair.coborrower;
}
}
let script_pairs = [];
let pairs_string = JSON.stringify(double_arr);
for (let i=0; i < double_arr.length; i++) {
let pair = double_arr[i];
if (pair[0] === false) {
script_pairs.push(`-`);
continue;
}
if (pair[1] === false) {
script_pairs.push(`${pair[0]}`);
continue;
}
script_pairs.push(`${pair[0]}-${pair[1]}`);
continue;
}
if (there_are_bps) {
for (let i=0; i < bp_fwd.length ; i++) {
let _applicant = mar.answers.v2.applicants[i];
if ("bp" in _applicant === false) {
_applicant.bp = bp_fwd[i];
}
}
}
let applicants = {};
for (let i=0; i < _applicants.length; i++) {
let appl = getApplicantsNames_v2(i);
MAR.ifOpt(appl, "sn", function(v){
let sn = MAR.digits(v);
applicants[sn] = appl;
});
}
return {
pairs : bp_array,
bp_rev : bp_rev,
bp_fwd : bp_fwd,
indexarr : index,
indexobj : indexobj,
double_arr : double_arr,
script_pairs : script_pairs,
pairs_string : pairs_string,
applicants : applicants,
dbg : dbg
}
}
/**
* Does the applicatioare the applicants joint?
* @function
* @memberof MAR_applicants
*/
function getApplicantsSpouse(N) {
if (N === 0) {
for (let i=1; i < getApplicants_v2().length; i++) {
let _applicant = getApplicant_v2(i);
if ("type" in _applicant == false) continue;
if (_applicant.type === "spouse") return i;
if (_applicant.type === "partner") return i;
}
} else {
let _applicant = getApplicant_v2(N);
if ("type" in _applicant == false) return false;
if (_applicant.type === "spouse") return 0;
if (_applicant.type === "partner") return 0;
}
return false;
}
/**
* Does the applicatioare the applicants joint?
* @function
* @memberof MAR_applicants
*/
function getApplicants_JointApplicant(N) {
for (let i=0; i < getApplicants_v2().length; i++) {
if (N === i) continue;
if (i < N) {
if (getApplicantsShareAddress(i , N)) {
return i;
}
} else {
if (getApplicantsShareAddress(N , i)) {
return i;
}
}
}
return false;
}
/**
* are the applicants joint?
* @function
* @memberof MAR_applicants
*/
function getApplicantsShareAddress(N , N1) {
if (arguments.length == 0) {
N = 0;
N1 = 1;
}
if (getApplicants_v2().length < 2) return false;
let _applicant0 = getApplicant_v2(N);
let _applicant1 = getApplicant_v2(N1);
if ("type" in _applicant1 == false) return false;
if (_applicant1.type != "spouse") return false;
if ("addresses" in _applicant0 == false) return false;
if ("addresses" in _applicant1 == false) return false;
if (_applicant0.addresses.length != _applicant0.addresses.length) return false;
for (let i=0; i < _applicant0.addresses.length; i++) {
let _left = JSON.stringify(_applicant0.addresses[i]);
for (let j=0; j < _applicant1.addresses.length; j++) {
let _right = JSON.stringify(_applicant1.addresses[j]);
if (_left === _right) return true;
}
}
return false
}
/**
* are the applicants joint?
* @function
* @memberof MAR_applicants
*/
function getApplicantsAreJoint(N , N1) {
if (arguments.length == 0) {
N = 0;
N1 = 1;
}
if (getApplicants_v2().length < 2) return false;
let _applicant0 = getApplicant_v2(N);
let _applicant1 = getApplicant_v2(N1);
if ("type" in _applicant1 == false) return false;
if (_applicant1.type != "spouse") return false;
if ("addresses" in _applicant0 == false) return false;
if ("addresses" in _applicant1 == false) return false;
if (_applicant0.addresses.length != _applicant0.addresses.length) return false;
for (let i=0; i < _applicant0.addresses.length; i++) {
let _left = JSON.stringify(_applicant0.addresses[i]);
let _right = JSON.stringify(_applicant1.addresses[i]);
if (_left != _right) return false;
}
return true;
}
function getApplicantsAreJointDbg(N , N1) {
if (arguments.length == 0) {
N = 0;
N1 = 1;
}
if (getApplicants_v2().length < 2) return "length not 2"
let _applicant0 = getApplicant_v2(N);
let _applicant1 = getApplicant_v2(N1);
if ("type" in _applicant1 == false) return "no type in type";
if (_applicant1.type != "spouse") return "not spouse";
if ("addresses" in _applicant0 == false) return "no addresses in applicant 0";
if ("addresses" in _applicant1 == false) return "no addresses in applicant 1";
if (_applicant0.addresses.length != _applicant0.addresses.length) return "Applicant address lengths dont match";
for (let i=0; i < _applicant0.addresses.length; i++) {
let _left = MAR.getOpt(getBucket(_applicant0.addresses[i]), "address","");
let _right = MAR.getOpt(getBucket(_applicant1.addresses[i]), "address","");
if (_left != _right) return ["the 2 addresses don't match",_left,_right] ;
}
return true;
}
/**
* make a safe version of he ssn
* @function
* @memberof MAR_applicants
*/
function safe_sn(sn) {
if (typeof sn == "undefined") {
return "00000000"
}
return sn.replace(/[ -]/g,"");
}
/**
* is current address rented and will continue
* @function
* @memberof MAR_applicants
*/
function is_current_address_rented_and_will_continue() {
// there is no primary index so lets see if they rent and will continue to rent
let current_address = MAR.getApplicantAddressCurrent(0);
if (current_address.length === 0) return false
if (MAR.getOpt(current_address,"0.use","") !== "rent") return false;
if (MAR.getOpt(current_address,"0.rentwillcontinue","") !== "Y") return false;
return MAR.getOptNum(current_address,"0.rent",0);
}
/**
* get the applicant addresses in the order current , past , only if necessary
* @function
* @memberof MAR_applicants
*/
function getApplicantsCurrentRent() {
let _applicants = getApplicants_v2();
let rent = 0;
let ca = [];
for (let i=0; i < _applicants.length; i++) {
let current_address = getApplicantAddressCurrent(i);
ca.push(current_address);
for (let j=0; j < current_address.length; j++) {
rent += num(current_address[j].rent);
}
}
return rent;
// return {
// ca : ca,
// rent : rent
// }
}
/**
* get the applicant addresses in the order current , past , only if necessary
* @function
* @memberof MAR_applicants
*/
function getApplicantAddresses4506t(n) {
try {
var _applicant = getApplicant_v2(n);
var retval = [];
if ("addresses" in _applicant) {
let ca = false;
let ia = false;
_applicant.addresses.forEach(function(bucketid){
let ad = getBucket(bucketid);
if (ca == false && ad.type == "current") ca = ad;
if (ia == false && ad.appears_on_tax_returns == "Y") ia = ad;
})
if (ca) retval.push(ca);
if (ia && JSON.stringify(ca) != JSON.stringify(ia)) retval.push(ia);
}
return retval;
} catch (E) {
console.log(`Error in getApplicantAddresses4506t for Applicant ${n}`,E);
return [];
}
}
/**
* get the applicant answered that they do own realestate
* @function
* @memberof MAR_applicants
*/
function getApplicantDoesOwnRealestate(i) {
var _d = getDeclarations_v2();
if (_d[i] && _d[i].credit_currently_own_realestate == mar.YES) return true;
return false;
}
/**
* get whether any applicant answered that they do own realestate
* @function
* @memberof MAR_applicants
*/
function getApplicantsDoOwnRealestate() {
var _d = getDeclarations_v2();
//console.log("getDoOwnRealestate",_d);
for (var i=0; i < _d.length; i++) {
if (_d[i] && _d[i].credit_currently_own_realestate == mar.YES) return true;
}
return false;
}
/**
* get whether any applicant answered that they do own realestate
* @function
* @memberof MAR_applicants
*/
function removeBorrower(N) {
MAR.applicants.remove(N);
}
let HMDA_OTHER_ASIAN = "Other Asian";
let HMDA_OTHER_PA = "Other Pacific Islander";
let HMDA_OTHER_HISPANIC = "Other Hispanic";
let HMDA = {
h2 : {
"0" : "I don't wish to furnish this information",
"1" : "Hispanic or Latino",
"2" : "Not Hispanic or Latino",
"3" : "Not Applicable"
},
h2_secondary1 : {
"mexican" : "Mexican",
"puerto rican" : "Puerto Rican",
"cuban" : "Cuban",
"other_hispanic" : "Other Hispanic",
HMDA_OTHER_HISPANIC : "Other Hispanic"
},
h3 : {
"0" : "I don't wish to furnish this information",
"1" : "American Indian or Alaska Nativ",
"2" : "Asian",
"3" : "Black of African America",
"4" : "Native Hawaiian or Other Pacific Islander",
"5" : "White",
"6" : "Not Applicable"
},
choice_native_indian_other_type : "Tribe",
h3_secondary1 : {
"asian indian" : "Asian Indian",
"chinese" : "Chinese",
"filipino" : "Filipino",
"japanese" : "Japanese",
"korean" : "Korean",
"vietnamese" : "Vietnamese",
HMDA_OTHER_ASIAN : "Other Asian"
},
choice_other_asian : "",
h3_secondary2 : {
"native hawaiian" : "Native Hawaiian",
"samoan" : "Samoan",
"guamanian or chorro" : "Guamanian or chorro",
"japanese" : "Japanese",
"korean" : "Korean",
"vietnamese" : "Vietnamese",
HMDA_OTHER_PA : "Other Pacific Islander"
},
choice_pacific_other : "",
h4 : {
"M" : "Male",
"F" : "Female"
}
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getEmails() {
let retval = [];
let gem = function(obj) {
for (x in obj) {
if (x == "email" && obj[x] != "") retval.push(obj[x])
else if (x == "em" && obj[x] != "") retval.push(obj[x])
else if (typeof obj[x] === "object") gem(obj[x])
}
}
gem(mar.answers.v2);
return retval.sort().filter(function(el,i,a){return i===a.indexOf(el)})
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getTels() {
let retval = [];
let gem = function(obj) {
for (x in obj) {
if (x == "tel" && obj[x] != "") retval.push(obj[x])
else if (x == "phone" && obj[x] != "") retval.push(obj[x])
else if (x == "ph" && obj[x] != "") retval.push(obj[x])
else if (typeof obj[x] === "object") gem(obj[x])
}
}
gem(mar.answers.v2);
return retval.sort().filter(function(el,i,a){return i===a.indexOf(el)})
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getNames() {
let retval = [];
let gem = function(obj) {
for (x in obj) {
if (x.endsWith("_name") && obj[x] != "") {
if (x.startsWith("institution_")) continue;
if (x.startsWith("small_")) continue;
if (x.startsWith("whose_")) continue;
if (x.startsWith("account_")) continue;
retval.push(obj[x])
// retval.push(`${x} ${obj[x]}`)
}
else if (x == "na" && obj[x] != "") retval.push(obj[x])
else if (typeof obj[x] === "object") gem(obj[x])
}
}
gem(mar.answers.v2);
return retval.sort().filter(function(el,i,a){return i===a.indexOf(el)})
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getApplicantLastTaxYear(n) {
var _applicant = getApplicant_v2(n);
try {
var _bucket = JSON.parse(getApplicant_bucket(n));
if ("ty" in _bucket) {
return num(_bucket.ty);
}
} catch (E) {
}
return getCurrentYearForTax(n);
// return num(new Date().getFullYear()-1);
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getCurrentYear(n) {
return num(new Date().getFullYear());
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getCurrentYearForTax(n) {
let year = num(new Date().getFullYear());
let month = (new Date().getMonth() + 1);
// if (month < 4) year--;
if (month < 1) year--;
return year;
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getCurrentYearForIncome(n) {
return num(new Date().getFullYear());
}
/**
* get the applicantlast Tax Year filed
* @function
* @memberof MAR_applicants
*/
function getCurrentYearForReoRental(n) {
return num(new Date().getFullYear())-1;
}
/**
* get the applicant HMDA in various formats
* @function
* @memberof MAR_applicants
*/
function getApplicantHMDA(n, format) {
var _applicant = getApplicant_v2(n);
try {
var _bucket = JSON.parse(getApplicant_bucket(n));
} catch (E) {
if (format == "html") {
return ""
} else {
return {};
}
}
if (arguments.length < 2 || !format ) {
}
if (format == "html") {
var retval = "";
if (_bucket.h1 != "Y") {
retval += "
Not Answered
";
} else {
// h2
retval += "
Ethnicity : ";
retval += HMDA.h2[_bucket.h2];
if (_bucket.h2 == "1") {
if (_bucket.h2_secondary1 == "other_hispanic") {
retval += ", " + _bucket.h2s1t;
} else {
retval += ", " + HMDA.h2_secondary1[_bucket.h2s1];
}
}
retval += "
";
retval += "
RACE : ";
retval += HMDA.h3[_bucket.h3];
if (_bucket.h3 == "2") {
if (_bucket.h3s1 == HMDA_OTHER_ASIAN) {
retval += ", " +_bucket.h3s1t;
} else {
retval += ", " +HMDA.h3_secondary1[_bucket.h3s1];
}
}
if (_bucket.h3 == "4") {
if (_bucket.h3s2 == HMDA_OTHER_PA) {
retval += ", " +_bucket.h3s2t;
} else {
retval += ", " +HMDA.h3_secondary2[_bucket.h3s2];
}
}
retval += "
";
retval += "
SEX : ";
retval += HMDA.h4[_bucket.h4];
retval += "
";
}
return retval.wrap("
","
");
//_bucket.h1;
} else if (format == "encompass") {
} else {
var retval = {
h1 : _bucket.h1,
h2 : HMDA.h2[_bucket.h2],
h3 : HMDA.h3[_bucket.h3],
h4 : HMDA.h4[_bucket.h4],
h2_secondary1 : HMDA.h3_secondary2[_bucket.h2s1],
choice_hispanic_other : _bucket.h2s1t,
h3_secondary1 : HMDA.h3_secondary2[_bucket.h3s1],
choice_other_asian : _bucket.h3s1t,
h3_secondary2 : HMDA.h3_secondary2[_bucket.h3s2],
choice_pacific_other : _bucket.h3s2t
};
return retval;
}
}
/**
* get the applicant phone
* @memberof MAR_applicants
*/
function getApplicantPhone(n) {
var _applicant = getApplicant_v2(n);
try {
var _bucket = JSON.parse(getApplicant_bucket(n));
} catch (E) {
return "";
}
if (_bucket && "ph" in _bucket) return _bucket.ph;
return "";
}
/**
* get the applicant email
* @memberof MAR_applicants
*/
function getApplicantEmail(n) {
var _applicant = getApplicant_v2(n);
try {
var _bucket = JSON.parse(getApplicant_bucket(n));
} catch (E) {
return "";
}
if (_bucket && "em" in _bucket) return _bucket.em;
return "";
}
/**
* get the applicant address on Current
* @memberof MAR_applicants
*/
function getApplicantAddressCurrent(n) {
var _applicant = getApplicant_v2(n);
var retval = [];
if ("addresses" in _applicant) {
let ca = false;
_applicant.addresses.forEach(function(bucketid){
let ad = getBucket(bucketid);
if (ca == false && ad.type == "current") ca = ad;
})
if (ca) retval.push(ca);
}
return retval;
}
/**
* @memberof MAR_applicants
*/
function simplify_address(ad) {
let parts = ad.split("|");
while (parts.length < 5) parts.push("");
while (parts.length > 5) parts.pop();
for (let i=0; i < parts.length; i++) parts[i] = parts[i].trim();
return parts.join("|");
}
/**
* @memberof MAR_applicants
*/
function getUsedAddressList() {
var addresses = [];
if ("buckets" in mar.answers.v2) {
for (x in mar.answers.v2.buckets) {
if ("address" in mar.answers.v2.buckets[x]) {
var ad = mar.answers.v2.buckets[x].address;
if (ad != null && ad.indexOf("|") > -1) {
ad = simplify_address(ad);
if (ad.split("|").length > 3 && ad.split("|")[1].trim().length > 0 && ad.split("|")[2].trim().length > 0) {
if (addresses.includes(ad) == false) {
addresses.push(ad);
}
}
}
}
if ("ad" in mar.answers.v2.buckets[x]) {
var ad = mar.answers.v2.buckets[x].ad;
if (ad != null && ad.indexOf("|") > -1) {
ad = simplify_address(ad);
if (ad.split("|").length > 3 && ad.split("|")[1].trim().length > 0 && ad.split("|")[2].trim().length > 0) {
if (addresses.includes(ad) == false) {
addresses.push(ad);
}
}
}
}
}
}
if ("reo" in mar.answers.v2) {
for (x in mar.answers.v2.reo) {
if (mar.answers.v2.reo[x] && "address" in mar.answers.v2.reo[x]) {
var ad = mar.answers.v2.reo[x].address;
if (ad != null && ad.indexOf("|") > -1) {
ad = simplify_address(ad);
if (ad.split("|").length > 3 && ad.split("|")[1].trim().length > 0 && ad.split("|")[2].trim().length > 0) {
if (addresses.includes(ad) == false) {
addresses.push(ad);
}
}
}
}
}
}
return addresses;
}
/**
* @memberof MAR_applicants
*/
function addAddressBucket(ad) {
if (arguments.length == 0) return false; // no parameterd
if (!ad) return false; // false parameter
if (ad.trim().length == 0) return false; // empty parameter
let addresses = getUsedAddressList();
for (let i=0; i < addresses.length; i++) {
if (ad == addresses[i]) return false; // exists already
}
let newuuid = uuidv4();
let newbucketid = "/address/"+newuuid;
mar.answers.v2.buckets[newuuid] = {
bucketid : newbucketid,
uuid : newuuid,
address : ad
}
return newbucketid;
}
// buckets: - {
// /applicants/address/0/875b4ff5-b13b-444a-98f8-16260bdbafef: - {
// bucketid: "/applicants/address/0/875b4ff5-b13b-444a-98f8-16260bdbafef",
// uuid: "875b4ff5-b13b-444a-98f8-16260bdbafef",
// address: "1130 Massachusetts Avenue|Lexington|MA|02420|",
// }
/**
* @memberof MAR_buckets
*/
function getBucket(bucketid) {
if ("buckets" in mar.answers.v2) {
if (bucketid in mar.answers.v2.buckets) {
return mar.answers.v2.buckets[bucketid];
}
}
return null;
}
/**
* @memberof MAR_buckets
*/
function getBucketByUUID(uuid) {
if ("buckets" in mar.answers.v2) {
for (bucketid in mar.answers.v2.buckets) {
if (mar.answers.v2.buckets[bucketid]) {
if ("uuid" in mar.answers.v2.buckets[bucketid]) {
if (mar.answers.v2.buckets[bucketid].uuid == uuid) {
return mar.answers.v2.buckets[bucketid];
}
}
}
}
}
return false;
}
/**
* @memberof MAR_buckets
*/
function getBuckets() {
if ("buckets" in mar.answers.v2) {
return mar.answers.v2.buckets;
}
return {};
}
/**
* @memberof MAR_applicants
*/
function getApplicantBucketID(n) {
var _applicant = getApplicant_v2(n);
if ("bucketid" in _applicant) {
return _applicant.bucketid;
}
return null;
}
/**
* @memberof MAR_applicants
*/
function setApplicantName(n, name) {
setScenario_data("applicant_"+(n+1)+"_name",name);
if (getApplicantBucketID(n) != null) {
var bucketid = getApplicantBucketID(n);
mar.answers.v2.buckets[bucketid].fn = name
}
}
/**
* @memberof MAR_buckets
*/
function setBucket(bucketid,data) {
if ("buckets" in mar.answers.v2 == false) {
mar.answers.v2.buckets=[];
}
mar.answers.v2.buckets[bucketid] = data;
}
/**
* @memberof MAR_applicants
*
* input 0 street 1 city 2 state 3 zip 4 unit
*
*/
function addressUnitToString(ad) {
let unit = "";
if (ad === false) return "";
if (ad === null) return "";
if (Array.isArray(ad)) {
if (ad.length < 5) return "";
unit = ad[4];
} else if (typeof ad === "object") {
unit = MAR.getOpt(ad, "unit", "");
}
if (unit === "") return "";
if (unit.startsWith("*")) return unit.substring("1");
return unit;
}
/**
* @memberof MAR_applicants
*
* input
*/
function addressToString(ad) {
// retval = JSON.stringify(ad);
// return retval;
if (ad) {
let adr = false;
let _ad = false;
if (typeof ad === "string") adr = ad;
else if ("city" in ad) _ad = ad;
else if ("address" in ad) adr = ad.address;
if (adr !== false || _ad !== false) {
if (_ad === false) _ad = addressFromString(adr);
if (_ad.address.indexOf(",") > -1) {
let _ads = _ad.address.split(",");
let rv = "";
let u = ` ${addressUnitToString(_ad)}`;
for (let x of _ads) {
rv += `
${capitalizeFirstLetter(x)}${addressUnitToString(_ads)}${u}
`; // add on the unit
u = "";
}
rv += "
"+capitalizeFirstLetter(_ad.city)+" "+_ad.state.toUpperCase()+" "+_ad.zip+"
";
return rv;
} else {
return "
"+capitalizeFirstLetter(_ad.address)+" "+addressUnitToString(_ad)+"
" +
"
"+capitalizeFirstLetter(_ad.city)+" "+_ad.state.toUpperCase()+" "+_ad.zip+"
";
}
}
}
if (ad) {
if ("address" in ad) ad += ad.address;
}
return "";
}
/**
* @memberof MAR_applicants
*/
function addressToVal(ad) {
let adr = [
MAR.getOpt(ad,"address",""),
MAR.getOpt(ad,"city",""),
MAR.getOpt(ad,"state",""),
MAR.getOpt(ad,"zip",""),
MAR.getOpt(ad,"unit","")
].join("|");
return adr;
}
/**
* @memberof MAR_applicants
*/
function addressToPlainString(ad) {
// retval = JSON.stringify(ad);
// return retval;
if (ad) {
var _ad = false;
if (typeof ad === "string" && ad.indexOf("|") > -1) _ad = addressFromString(ad);
else if ("address" in ad) _ad = addressFromString(ad.address);
if (_ad !== false) {
let retval = "";
let _ads = (_ad.address + " " + _ad.unit).split(",");
for (let x of _ads) {
retval += capitalizeFirstLetter(x) + ",";
}
// if (_ad.unit && _ad.unit != "")
// retval += " "+_ad.unit;
retval += " "+capitalizeFirstLetter(_ad.city);
retval += ", "+_ad.state.toUpperCase()+" "+_ad.zip;
return retval;
}
}
if (ad) {
if ("address" in ad) ad += ad.address;
}
return "";
}
let EncompassUnitTypes = [
"Apartment",
"Basement",
"Building",
"Condo",
"Department",
"Floor",
"Front",
"Hangar",
"Key",
"Lobby",
"Lot",
"Lower",
"Office",
"Penthouse",
"Pier",
"Rear",
"Room",
"Side",
"Space",
"Stop",
"Suite",
"Trailer",
"Unit",
"Upper"
];
function is_validEncompassUnitType(S) {
if (typeof S !== "string") return false;
return (EncompassUnitTypes.indexOf(S) > -1);
}
function ElaineUnitType_to_EncompassUnitType(S) {
if (S === "Suite") return "Suite";
if (S === "Ste") return "Suite";
if (S === "Unit") return "Unit";
if (S === "#") return "Unit";
if (S === "Bldg") return "Building";
if (S === "Floor") return "Floor";
if (S === "Apt") return "Apartment";
return S;
}
function Elain_unit_to_Encompass_unit(unit, addressLine1) {
let rv = {
unit_type : "",
unit_num : "",
address_addon : "",
addressLine1 : addressLine1
};
if (typeof unit !== "string") return rv;
if (unit.startsWith("*")) { // *Apt 54
let parts = unit.substring("1").split(" "); // ["Apt","54"]
rv.unit_type = ElaineUnitType_to_EncompassUnitType(parts[0]); // "Apartment"
rv.unit_num = (parts.length > 1) ? parts[1] : ""; // "54"
return rv;
}
// Key 651
let parts = unit.split(" "); // ["Key","651"]
if (is_validEncompassUnitType(parts[0])) { // true
rv.unit_type = parts[0]; // "Key"
rv.unit_num = (parts.length > 1) ? parts[1] : ""; // "651"
}
// Quay F1
rv.address_addon = unit; // "Quay 54"
rv.addressLine1 += ` ${unit}` // 100 Quantum Way Quay 54
return rv;
}
function createElaineUnit_from_encompassUnits(unittype, unitnum) {
let rv = "";
if (unittype === "Suite") unittype = "*Suite";
if (unittype === "Unit") unittype = "*Unit";
if (unittype === "Building") unittype = "*Bldg";
if (unittype === "Floor") unittype = "*Floor";
if (unittype === "Apartment") unittype = "*Apt";
return `${unittype} ${unitnum}`;
}
/**
* @memberof MAR_applicants
*/
function addressFromString(ad) {
var retval = {
address : "",
city : "",
state : "",
zip : "",
z4 : "",
unit : "",
unit_type : "",
unit_number : "",
enc : false
};
if (ad && ad != "") {
try {
var adparts = ad.split("|");
if (adparts.length > 3) {
retval.address = adparts[0];
retval.city = adparts[1];
retval.state = adparts[2];
retval.zip = adparts[3];
retval.z4 = "";
retval.unit = (adparts.length > 4) ? adparts[4] : "";
retval.enc = Elain_unit_to_Encompass_unit(retval.unit,retval.address);
if (retval.unit.indexOf("*") === 0) {
let rvu = retval.unit.substring(1).split(" ");
retval.unit_type = rvu[0];
if (rvu.length > 1) {
retval.unit_number = rvu[1];
}
retval.unit = retval.unit.substring(1);
}
return retval;
}
} catch (E) {
console.warn(E,ad)
}
}
return retval;
}
/**
* @memberof MAR
*/
function movieLinkToPlayer(movielink, width) {
let isYoutube = false;
let youtubeid = false;
let isVimeo = false;
let vimeoid = false;
let vimeoclientid = false;
if (!width) width = 90;
if (typeof movielink !== "string") return "";
var movie_split = movielink.split(":");
if (movie_split.length > 1) {
if (movie_split[0] == "youtube") {
isYoutube = true;
youtubeid = movie_split[1];
}
}
if (movielink.startsWith("http") === true) {
//https://www.youtube.com/watch?v=8LfpcU1AuiM",
if (movielink.indexOf("youtube") > -1) {
let veq = movielink.indexOf("v=");
if (veq > 0) {
let vp = movielink.substring(veq+2).split("&")[0];
isYoutube = true;
youtubeid = vp;
}
}
if (movielink.indexOf("youtu.be/") > -1) {
let veq = movielink.indexOf(".be/");
if (veq > 0) {
let vp = movielink.substring(veq+4).split("?")[0];
isYoutube = true;
youtubeid = vp;
}
}
if (movielink.indexOf("https://vimeo.com/") === 0) {
isVimeo = true;
vimeoid = movielink.substring(18).split("/")[0];
vimeoclientid = movielink.substring(18).split("/")[1];
}
}
if (isYoutube) {
return `
VIDEO `
}
if (isVimeo) {
// return `vimeo player id ${vimeoid} clientid ${vimeoclientid}`;
return `
`+
`
DELIVERED from LAW CHEN on Vimeo .
`;
}
return "";
}
/**
* @memberof MAR
*/
function capitalizeFirstLetter(string) {
if (typeof string !== "string") return string;
if (string.length === 0) return "";
return string[0].toUpperCase() + string.slice(1);
}
/**
* @memberof MAR
*/
function capitalizeFirstLetters(string) {
if (typeof string !== "string") return string;
if (string.length === 0) return "";
let parts = string.split(" ");
for (let i=0; i < parts.length; i++) {
parts[i] = capitalizeFirstLetter(parts[i])
}
return parts.join(" ");
}
/**
* @memberof MAR_scenario
*/
function county_display(T) {
if (!T) return "";
var t = T.split('|');
var t1 = t[1].split('(');
var t10 = t1[0].split(':');
if (t10.length != 2) return capitalizeFirstLetter(t1[0].toLowerCase());
return capitalizeFirstLetter(t10[0].trim().toLowerCase()) + " " + capitalizeFirstLetter(t10[1].trim().toLowerCase())
//return t1[0];
}
/**
* @memberof MAR_scenario
*/
function county_name(T) {
if (!T) return "";
var t = T.split('|');
var t1 = t[1].split('(');
var t10 = t1[0].split(':');
if (t10.length != 2) return capitalizeFirstLetter(t1[0].toLowerCase());
return capitalizeFirstLetter(t10[1].trim().toLowerCase())
//return t1[0];
}
/**
* @memberof MAR_scenario
*/
function county_number(T) {
if (!T) return "";
var t = T.split('|');
return t[0];
}
/**
* @memberof MAR_scenario
*/
var county2ziptable = null;
var countytable = null;
/**
* @memberof MAR_scenario
*/
function county2zip_old(county) {
if (county2ziptable == null) {
var js = fs.readFileSync('data-tables/libs/zip2fips.json').toString();
eval("county2ziptable = "+js);
}
let c = num(county)
for (let x in county2ziptable) {
if (num(county2ziptable[x]) == c) return x;
}
return "";
}
/**
* @memberof MAR_scenario
*/
function county2zip(county) {
if (county === ``) return ``;
if (county2ziptable == null) {
var js = fs.readFileSync('data-tables/libs/zip2fips_array.json').toString();
eval("county2ziptable = "+js);
}
let c = num(county)
for (let i=0; i < county2ziptable.length; i++) {
if (num(county2ziptable[i][1]) == c) return county2ziptable[i][0];
}
return "";
}
/**
* @memberof MAR_scenario
*/
function zip2county(zip) {
if (county2ziptable == null) {
var js = fs.readFileSync('data-tables/libs/zip2fips_array.json').toString();
eval("county2ziptable = "+js);
}
let z = num(zip)
for (let i=0; i < county2ziptable.length; i++) {
if (num(county2ziptable[i][0]) == z) return county2ziptable[i][1];
}
return "";
}
/**
* @memberof MAR_scenario
*/
function countynum2text(countynum) {
if (countytable == null) {
var js = fs.readFileSync('data-tables/__counties.json').toString();
eval("countytable = "+js);
}
let c = `${countynum}|`;
for (let i=0; i < countytable.counties.length; i++) {
if (countytable.counties[i].startsWith(c)) return countytable.counties[i]
}
return "";
}
/**
* @memberof MAR_scenario
*/
function countynum2Full(countynum) {
if (countytable == null) {
var js = fs.readFileSync('data-tables/__counties.json').toString();
eval("countytable = "+js);
}
let c = `${countynum}|`;
for (let i=0; i < countytable.counties.length; i++) {
if (countytable.counties[i].startsWith(c)) return countytable
}
return "";
}
/**
* @memberof MAR_scenario
*/
function county_formatted(cnty) {
/**
* get County "37021|NORTH CAROLINA : BUNCOMBE (37021)"
*/
if (typeof cnty !== "string" || cnty.trim().length === 0 || cnty.indexOf("|") < 0) {
return "";
}
let countynum = getCounty_v2(cnty);
let state_name = cnty.split(":")[0].split("|")[1].trim();
let county_name = cnty.split(":")[1].split("(")[0].trim();
let state_code = MAR.stateCode(state_name);
return `${county_name}, ${state_code}`;
}
/**
* @memberof MAR_scenario
*/
function county_state(cnty) {
/**
* get County "37021|NORTH CAROLINA : BUNCOMBE (37021)"
*/
if (typeof cnty !== "string" || cnty.trim().length === 0 || cnty.indexOf("|") < 0) {
return "";
}
let countynum = getCounty_v2(cnty);
let state_name = cnty.split(":")[0].split("|")[1].trim();
let county_name = cnty.split(":")[1].split("(")[0].trim();
let state_code = MAR.stateCode(state_name);
return `${state_code}`;
}
/**
* @memberof MAR_scenario
*/
function stateCode(state, name) {
let us_states = [
{
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
{
"name": "American Samoa",
"abbreviation": "AS"
},
{
"name": "Arizona",
"abbreviation": "AZ"
},
{
"name": "Arkansas",
"abbreviation": "AR"
},
{
"name": "California",
"abbreviation": "CA"
},
{
"name": "Colorado",
"abbreviation": "CO"
},
{
"name": "Connecticut",
"abbreviation": "CT"
},
{
"name": "Delaware",
"abbreviation": "DE"
},
{
"name": "District Of Columbia",
"abbreviation": "DC"
},
{
"name": "Florida",
"abbreviation": "FL"
},
{
"name": "Georgia",
"abbreviation": "GA"
},
{
"name": "Hawaii",
"abbreviation": "HI"
},
{
"name": "Idaho",
"abbreviation": "ID"
},
{
"name": "Illinois",
"abbreviation": "IL"
},
{
"name": "Indiana",
"abbreviation": "IN"
},
{
"name": "Iowa",
"abbreviation": "IA"
},
{
"name": "Kansas",
"abbreviation": "KS"
},
{
"name": "Kentucky",
"abbreviation": "KY"
},
{
"name": "Louisiana",
"abbreviation": "LA"
},
{
"name": "Maine",
"abbreviation": "ME"
},
// {
// "name": "Marshall Islands",
// "abbreviation": "MH"
// },
{
"name": "Maryland",
"abbreviation": "MD"
},
{
"name": "Massachusetts",
"abbreviation": "MA"
},
{
"name": "Michigan",
"abbreviation": "MI"
},
{
"name": "Minnesota",
"abbreviation": "MN"
},
{
"name": "Mississippi",
"abbreviation": "MS"
},
{
"name": "Missouri",
"abbreviation": "MO"
},
{
"name": "Montana",
"abbreviation": "MT"
},
{
"name": "Nebraska",
"abbreviation": "NE"
},
{
"name": "Nevada",
"abbreviation": "NV"
},
{
"name": "New Hampshire",
"abbreviation": "NH"
},
{
"name": "New Jersey",
"abbreviation": "NJ"
},
{
"name": "New Mexico",
"abbreviation": "NM"
},
{
"name": "New York",
"abbreviation": "NY"
},
{
"name": "North Carolina",
"abbreviation": "NC"
},
{
"name": "North Dakota",
"abbreviation": "ND"
},
{
"name": "Ohio",
"abbreviation": "OH"
},
{
"name": "Oklahoma",
"abbreviation": "OK"
},
{
"name": "Oregon",
"abbreviation": "OR"
},
{
"name": "Pennsylvania",
"abbreviation": "PA"
},
// {
// "name": "Puerto Rico",
// "abbreviation": "PR"
// },
{
"name": "Rhode Island",
"abbreviation": "RI"
},
{
"name": "South Carolina",
"abbreviation": "SC"
},
{
"name": "South Dakota",
"abbreviation": "SD"
},
{
"name": "Tennessee",
"abbreviation": "TN"
},
{
"name": "Texas",
"abbreviation": "TX"
},
{
"name": "Utah",
"abbreviation": "UT"
},
{
"name": "Vermont",
"abbreviation": "VT"
},
// {
// "name": "Virgin Islands",
// "abbreviation": "VI"
// },
{
"name": "Virginia",
"abbreviation": "VA"
},
{
"name": "Washington",
"abbreviation": "WA"
},
{
"name": "West Virginia",
"abbreviation": "WV"
},
{
"name": "Wisconsin",
"abbreviation": "WI"
},
{
"name": "Wyoming",
"abbreviation": "WY"
}
];
if (arguments.length === 0) {
let rv = {};
for (let i=0; i < us_states.length; i++) {
rv[us_states[i].abbreviation.toUpperCase()] = us_states[i].name;
}
return rv;
}
if (typeof name === "boolean" && name === true) {
// this is reverse
if (typeof state !== "string") return "";
if (state.length !== 2) return "";
state = state.toUpperCase();
for (let i=0; i < us_states.length; i++) {
if (us_states[i].abbreviation.toUpperCase() === state) {
return us_states[i].name;
}
}
return "";
}
if (typeof state !== "string") return "";
if (state.length === 2) return state.toUpperCase();
state = state.toLowerCase();
for (let i=0; i < us_states.length; i++) {
if (us_states[i].name.toLowerCase() === state) {
return us_states[i].abbreviation;
}
}
return "";
}
/**
* thanks : https://anthonylouisdagostino.com/bounding-boxes-for-all-us-states/
* and https://stackoverflow.com/questions/21871190/google-geocode-autocomplete-limit-state
*
*/
let state_boundaries = {
AL : [-88.473227,30.223334,-84.88908,35.008028],
AK : [-179.148909,51.214183,179.77847,71.365162],
AS : [-171.089874,-14.548699,-168.1433,-11.046934],
AZ : [-114.81651,31.332177,-109.045223,37.00426],
AR : [-94.617919,33.004106,-89.644395,36.4996],
CA : [-124.409591,32.534156,-114.131211,42.009518],
CO : [-109.060253,36.992426,-102.041524,41.003444],
MP : [144.886331,14.110472,146.064818,20.553802],
CT : [-73.727775,40.980144,-71.786994,42.050587],
DE : [-75.788658,38.451013,-75.048939,39.839007],
DC : [-77.119759,38.791645,-76.909395,38.99511],
FL : [-87.634938,24.523096,-80.031362,31.000888],
GA : [-85.605165,30.357851,-80.839729,35.000659],
GU : [144.618068,13.234189,144.956712,13.654383],
HI : [-178.334698,18.910361,-154.806773,28.402123],
ID : [-117.243027,41.988057,-111.043564,49.001146],
IL : [-91.513079,36.970298,-87.494756,42.508481],
IN : [-88.09776,37.771742,-84.784579,41.760592],
IA : [-96.639704,40.375501,-90.140061,43.501196],
KS : [-102.051744,36.993016,-94.588413,40.003162],
KY : [-89.571509,36.497129,-81.964971,39.147458],
LA : [-94.043147,28.928609,-88.817017,33.019457],
ME : [-71.083924,42.977764,-66.949895,47.459686],
MD : [-79.487651,37.911717,-75.048939,39.723043],
MA : [-73.508142,41.237964,-69.928393,42.886589],
MI : [-90.418136,41.696118,-82.413474,48.2388],
MN : [-97.239209,43.499356,-89.491739,49.384358],
MS : [-91.655009,30.173943,-88.097888,34.996052],
MO : [-95.774704,35.995683,-89.098843,40.61364],
MT : [-116.050003,44.358221,-104.039138,49.00139],
NE : [-104.053514,39.999998,-95.30829,43.001708],
NV : [-120.005746,35.001857,-114.039648,42.002207],
NH : [-72.557247,42.69699,-70.610621,45.305476],
NJ : [-75.559614,38.928519,-73.893979,41.357423],
NM : [-109.050173,31.332301,-103.001964,37.000232],
NY : [-79.762152,40.496103,-71.856214,45.01585],
NC : [-84.321869,33.842316,-75.460621,36.588117],
ND : [-104.0489,45.935054,-96.554507,49.000574],
OH : [-84.820159,38.403202,-80.518693,41.977523],
OK : [-103.002565,33.615833,-94.430662,37.002206],
OR : [-124.566244,41.991794,-116.463504,46.292035],
PA : [-80.519891,39.7198,-74.689516,42.26986],
PR : [-67.945404,17.88328,-65.220703,18.515683],
RI : [-71.862772,41.146339,-71.12057,42.018798],
SC : [-83.35391,32.0346,-78.54203,35.215402],
SD : [-104.057698,42.479635,-96.436589,45.94545],
TN : [-90.310298,34.982972,-81.6469,36.678118],
TX : [-106.645646,25.837377,-93.508292,36.500704],
VI : [-65.085452,17.673976,-64.564907,18.412655],
UT : [-114.052962,36.997968,-109.041058,42.001567],
VT : [-73.43774,42.726853,-71.464555,45.016659],
VA : [-83.675395,36.540738,-75.242266,39.466012],
WA : [-124.763068,45.543541,-116.915989,49.002494],
WV : [-82.644739,37.201483,-77.719519,40.638801],
WI : [-92.888114,42.491983,-86.805415,47.080621],
WY : [-111.056888,40.994746,-104.05216,45.005904]
};
/**
* @memberof MAR_scenario
*/
function zip2county_full(code) {
let zc = zip2county(code);
let zn = countynum2text(zc);
if (zn === "") zn = `${code}|FLORIDA : UNKNOWN (${code})`;
var cityarea = context.global.zipcodes.lookup(code);
let city = MAR.getOpt(cityarea, "city");
let area = cityarea
return {
status : 0,
code : zc,
name : zn,
city : city,
area : area
};
}
/**
* @memberof MAR_scenario
*/
function getTBDaddress() {
var _scenario = getScenario_v2();
var build_period = _scenario.build_period;
var countycode = county_number(_scenario.property_county);
var zip = county2zip(countycode);
var units = getPropertyUnits_v2();
var city = "";
try {
var cityarea = context.global.zipcodes.lookup(zip)
city = MAR.getOpt(cityarea, "city", "");
} catch (E) {
console.warn(E);
city = "";
}
return "TBD, "+city+", "+zip+ " FL";
}
/**
* @memberof MAR
*/
function telF (tel,def) {
if (!tel || tel.trim().length == 0) return (arguments.length == 1) ? tel : def;
try {
if (typeof context !== "undefined") {
return context.global.lpn.format(tel, 'US', 'National')
}
return libphonenumber.format(tel, 'US', 'National')
} catch(E) {
console.warn("function cfc.telF", E);
retrun (arguments.length == 1) ? tel : def;
}
}
/**
* @memberof MAR_scenario
*/
function getSummaryHoi() {
var _s = getScenario_v2();
var insurance_disp = "";
if (_s.scenario_i_know_my_insurance == "Y") {
if (_s.refi_home_insurance_cost != 0) {
insurance_disp += "
Ins : $"+(num(_s.refi_home_insurance_cost)/12).toFixed(0)+"/m
";
}
if (num(_s.scenario_tax) != 0) {
insurance_disp += "
Tax : $"+(num(_s.scenario_tax)/12).toFixed(0)+"/m
";
}
if (_s.property_near_to_water == "Y") {
insurance_disp += "
Near to water/flood
";
//if (REFI || PURCHASE_AND_UNDER_CONTRACT) {
if (num(_s.scenario_flood) > 0) {
insurance_disp += "
Flood : $"+(num(_s.scenario_flood)/12).toFixed(0)+"/m
";
}
//}
}
} else {
var square_foot = txt("#square_foot.du-var");
var build_period = txt("#build_period");
if (_s.square_foot != "") {
insurance_disp += ("
Size : "+_s.square_foot+" sq. ft
");
}
if (_s.build_period != "") {
insurance_disp += ("
Build : "+_s.build_period+"
");
}
if (num(_s.scenario_tax) != 0) {
insurance_disp += "
Tax : $"+num(_s.scenario_tax)+"
";
}
var property_near_to_water = yn("#property_near_to_water");
if (_s.property_near_to_water == "Y") {
insurance_disp += "
Near to water/flood
";
//if (REFI || PURCHASE_AND_UNDER_CONTRACT) {
if (num(_s.scenario_flood) > 0) {
insurance_disp += "
Flood : $"+num(_s.scenario_flood)+"
";
}
//}
}
var _he = getScenario_data("hoi_estimate",false);
if (_he) {
if ("hoa_estimate" in _he) {
insurance_disp += ("
Est : $"+Math.floor(_he.ins_estimate + _he.flood_estimate)+"/y
");
insurance_disp += ("
Est : $"+Math.floor((_he.ins_estimate + _he.flood_estimate) /12)+"/m
");
}
}
}
if (_s.loan_type != "purchase") {
insurance_disp = "";
if (_s.refi_home_insurance_cost != 0) {
insurance_disp += "
Ins : $"+(num(_s.refi_home_insurance_cost)/12).toFixed(0)+"
";
}
// var scenario_tax = txt("#scenario_tax");
// var refi_tax_cost = num(scenario_tax);
if (_s.scenario_tax != 0) {
insurance_disp += "
Tax : $"+(num(_s.scenario_tax)/12).toFixed(0)+"
";
}
//
// var property_near_to_water = yn("#property_near_to_water");
if (_s.property_near_to_water == "Y") {
insurance_disp += "
Near to water/flood
";
// if (REFI || PURCHASE_AND_UNDER_CONTRACT) {
if (num(_s.scenario_flood) > 0) {
insurance_disp += "
Flood : $"+(num(_s.scenario_flood)/12).toFixed(0)+"
";
}
// }
}
}
return insurance_disp;
}
/**
* @memberof MAR_scenario
*/
function getSummary() {
}
/**
* @memberof MAR_scenario
*/
function getSummaryHoa() {
var hoa_disp = "";
var _s = getScenario_v2();
if (_s.property_type_community_options == "cknow") {
if (_s.hoa_estimate != "") {
hoa_disp += "
HOA est : $"+num(_s.hoa_estimate)+"
";
}
} else {
hoa_disp += mar._txt(_s.property_type_community_options);
}
/**
* if they want us to estimate for them we need to know the square footage and we may not have asked
* this before if they did not ask us to estimate the insurance
*/
if (_s.property_type_community_options == "chigh" || _s.property_type_community_options == "clow") {
// var sqft = square_foot;
// var cnty = county_number(txt("#property_county"));
// var ptype = radio("property_type");
// var copt = property_type_community_options;
if (_s.square_foot != "") {
hoa_disp += ("
size : "+_s.square_foot+" sq. ft
");
}
var _he = getScenario_data("hoi_estimate",false);
if (_he) {
if ("hoa_estimate" in _he) {
hoa_disp += ("
Est : $"+Math.floor(_he.hoa_estimate)+"/y
");
hoa_disp += ("
Est : $"+Math.floor(_he.hoa_estimate/12)+"/m
");
}
}
}
if (_s.loan_type != "purchase") {
if (_s.scenario_hoa != "") {
hoa_disp = "$"+_s.scenario_hoa;
}
}
return hoa_disp;
}
/**
* @memberof MAR_applicants
*
* @param {string} ROLE current role 're','c1','c2','c2','lo'
*
* @returns {int} status -1,0,1,2
*
*/
function getConsents(ROLE) {
let status = false;
let applicantid = false;
let theRealStatus = function(bucket) {
if ("consents" in bucket == false) return -1; // no consents at all
if ("credit" in bucket.consents == false) return 0; // no record of the credit
if ("t4506" in bucket.consents == false) return 0; // ditto t4506
if ("ec" in bucket.consents == false) return 0; // ditto ec
if (bucket.consents.credit == "N") return 0; // credit is N
if (bucket.consents.t4506 == "N") return 0; // ditto 4506t
if (bucket.consents.ec == "N") return 0; // ditto ec
return 1;
}
if (typeof ROLE !== 'undefined' && ROLE == "re") {
status = 9;
} else {
if (ROLE == "cl") applicantid=0;
if (ROLE == "c2") applicantid=1
if (ROLE == "c3") applicantid=2;
if (ROLE == "lo") {
if ("lo" in mar.answers.v2 == false) {
mar.answers.v2.lo = {};
mar.fakesave();
}
if ("consent_soft_bucketid" in mar.answers.v2.lo == true) {
var bucketid = mar.answers.v2.lo.consent_soft_bucketid;
var bucket = mar.answers.v2.buckets[bucketid];
status = theRealStatus(bucket);
}
} else {
if ("consent_soft_bucketid" in mar.answers.v2.applicants[applicantid] == true) {
var bucketid = mar.answers.v2.applicants[applicantid].consent_soft_bucketid;
var bucket = mar.answers.v2.buckets[bucketid];
status = theRealStatus(bucket);
}
}
}
return status;
}
function isPersonalData_complete(n) {
let _applicant = getApplicant_v2(n);
return true;
}
function isAddressData_complete(n) {
let _applicant = getApplicant_v2(n);
if ("addresses" in _applicant == false) return `no addresses for applicant ${n}`;
if (_applicant.addresses.length == 0) return `address length is 0 for applicant ${n}`;
let totalmonths = 0;
let appears_on_tax_returns = 0;
let appears_on_drivers_license = 0;
let items = _applicant.addresses;
(function() {
for (var i=0; i < items.length; i++) {
var bucketid = items[i];
if (bucketid in mar.answers.v2.buckets) {
var bucket = mar.answers.v2.buckets[bucketid];
var uuid = bucket.uuid;
var address = bucket.address;
var type = bucket.type;
var years = bucket.years;
var months = bucket.months;
if (bucket.appears_on_tax_returns == "Y") appears_on_tax_returns = 1;
if (bucket.appears_on_drivers_license == "Y") appears_on_drivers_license = 1;
totalmonths += (parseInt(years,10)*12)+parseInt(months);
}
}
})();
if (totalmonths < 24) return `total months less than 24 for applicant ${n}`;
if (appears_on_tax_returns == 0) return `tax return address not found for applicant ${n}`;
if (appears_on_tax_returns == 0) return `tax return address not found for applicant ${n}`;
return true;
}
/**
* @memberof MAR_scenario
*/
function isReadyFor4506tStatus() {
return false;
let _numberofapplicants = getApplicants_v2().length;
if (_numberofapplicants == 0) return "no applicants";
for (let i=0; i < _numberofapplicants; i++) {
let pdc = isPersonalData_complete(i);
let adc = isAddressData_complete(i);
if (pdc !== true) return pdc;
if (adc !== true) return adc;
}
return true;
}
/**
* @memberof MAR_scenario
*/
function isLive() {
if (!context) return false;
if ("global" in context == false) return false;
if ("cache" in context.global == false) return false;
if ("app_status" in context.global.cache == false) return false;
if ("app_status" in context.global.cache == false) return false;
if ("appid" in mar.answers == false) return false;
let key = `a${mar.answers.appid}`;
let status = (key in context.global.cache.app_status == true) ? context.global.cache.app_status[key] : "";
if (status == "L") return true;
return false;
}
/**
* @memberof MAR_scenario
*/
function isUnderContract() {
if (MAR.getOpt(mar, "answers.v2.scenario.loan_type_purchase_options","") == "contract") return true;
let loan_type = MAR.getOpt(mar, "answers.v2.scenario.loan_type","");
if (loan_type !== "" && loan_type !== "purchase") {
return true;
}
return false;
}
/**
* @memberof MAR_scenario
*/
function realtor_options(S) {
//appraisal_information
//loan_calcs_and_docs
//direct_underwriting_report
return MAR.getOpt(mar, `answers.v2.scenario.realtor_permission_${S}`,``);
}
/**
* @memberof MAR_scenario
*/
function isOffering() {
if (mar.answers.v2.scenario.loan_type_purchase_options == "contract") return true;
if (mar.answers.v2.scenario.loan_type_purchase_options == "soon") return true;
return false;
}
/**
* @memberof MAR_scenario
*/
function fixFirstTimeBuyer() {
/**
* set the has ANY applicant owned property
*/
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years = "N";
for (i=1; i < 4; i++) {
var __property = "has_applicant"+i+"_owned_property_in_last_3_years";
if (__property in mar.answers.v2.scenario && mar.answers.v2.scenario[__property] == "Y"){
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years = "Y";
}
}
}
/**
* @memberof MAR_scenario
*/
function isFirstTimeBuyer() {
fixFirstTimeBuyer();
return (getScenario_data("has_any_applicant_owned_property_in_last_3_years","N") == "N");
}
/**
* @memberof MAR_scenario
*/
function ownsProperty(n) {
let applicantNum = `${num(n)+1}`;
return (getScenario_data("does_applicant"+applicantNum+"_own_property","") === "Y");
}
/**
* @memberof MAR_scenario
*/
function ownsPropertyUnanswered(n) {
let applicantNum = `${num(n)+1}`;
return (getScenario_data("does_applicant"+applicantNum+"_own_property","") === "");
}
/**
* @memberof MAR_scenario
*/
function ownsPrimary(n) {
let a_current = MAR.getApplicantAddressCurrent(n);
if (a_current.length == 0) return false;
if (MAR.getOpt(a_current[0],"use","") === "own") {
return true;
}
return false;
}
/**
* @memberof MAR_scenario
*/
function isMccEligible() {
var pt = getScenario_data("property_type","");
var use = getScenario_data("occupancy_type","");
var secondA = getScenario_data("second_applicant","");
var thirdA = getScenario_data("third_applicant","");
if (use == "occupancy_investment") return false;
if ((pt == "sfr" || pt == "condo") == false) return false;
if (isFirstTimeBuyer() == false) return false;
if (secondA == mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT) return false;
if (thirdA == mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT) return false;
return true;
}
/**
* @memberof MAR_scenario
*/
function rec_prog() {
var use = getScenario_data("occupancy_type","");
if (use === mar.OCCUPANCY_INVESTMENT) return "conv";
if (use === mar.OCCUPANCY_2ND_HOME) return "conv";
if (isVaEligible()) return "va";
if (MAR.getOpt(mar.answers.v2.scenario, `has_applicant1_served_in_us_forces`, "") === "") {
if (MAR.getOpt(mar.answers.v2.scenario, `target_va`, "") === "Y") {
return "va"
}
}
let cscore = num(MAR.getOpt(mar.answers.v2, `cscore`, ""));
let rv = "conv";
if (cscore > 100 && cscore < 700) {
rv = "fha";
}
return rv;
}
/**
* @memberof MAR_scenario
*/
function rec_progs() {
var use = getScenario_data("occupancy_type","");
if (use === mar.OCCUPANCY_INVESTMENT) return ["conv","jumbo"];
if (use === mar.OCCUPANCY_2ND_HOME) return ["conv","jumbo"];
if (isVaEligible()) return ["va","fha","conv","jumbo"];
if (MAR.getOpt(mar.answers.v2.scenario, `has_applicant1_served_in_us_forces`, "") === "") {
if (MAR.getOpt(mar.answers.v2.scenario, `target_va`, "") === "Y") {
return ["va","fha","conv","jumbo"];
}
}
let cscore = num(MAR.getOpt(mar.answers.v2, `cscore`, ""));
let rv = ["conv","fha","jumbo"];
if (cscore > 100 && cscore < 640) {
rv = ["fha"];
}
return rv;
}
/**
* @memberof MAR_scenario
*/
function rec_min_dp() {
let prog = rec_prog();
if (prog === "va") {
return 0;
}
if (MAR.getOpt(mar.answers.v2.scenario, `target_fthb`, "") === "Y") {
return 3;
}
return 5;
}
/**
* @memberof MAR_scenario
*/
function set_target_va(val) {
MAR.setOpt(mar.answers.v2.scenario, `target_va`, val)
}
/**
* @memberof MAR_scenario
*/
function isVaEligible() {
/**
* set the has ANY applicant owned property
*/
mar.answers.v2.scenario.is_va_eligible = "N";
for (i=1; i < 4; i++) {
var __eligible = "has_applicant"+i+"_served_in_us_forces";
if (__eligible in mar.answers.v2.scenario && mar.answers.v2.scenario[__eligible] == "Y"){
mar.answers.v2.scenario.is_va_eligible = "Y";
return true;
}
}
return false;
}
/**
* get Property type
* @memberof MAR_scenario
*/
function getPropertyType_v2(_sc) {
/**
* type of property
*/
if (!mar.STATIC) setStaticVars();
if (arguments.length == 0 || !_sc) {
_sc = mar.answers.v2.scenario;
}
var retval = "";
if (_sc.property_type == mar.PROPERTY_TYPE_SFR) retval = "sfr";
if (_sc.property_type == mar.PROPERTY_TYPE_CONDO) retval = "condo";
if (_sc.property_type == mar.PROPERTY_TYPE_DUPLEX) retval = "2unit";
if (_sc.property_type == mar.PROPERTY_TYPE_TRIPLEX) retval = "3unit";
if (_sc.property_type == mar.PROPERTY_TYPE_FOURPLEX) retval = "4unit";
if (_sc.property_type == mar.PROPERTY_TYPE_OTHER) retval = "Other";
return retval;
}
/**
* get the type of loan
* @memberof MAR_scenario
*/
function getLoanType_v2(_sc) {
return _sc.loan_type;
}
/**
* refinance options
* @memberof MAR_scenario
*/
function getRefi_v2(_sc) {
if (!mar.STATIC) setStaticVars();
var retval = {
loan_type_refinance_takehome_value : 0,
refi_home_insurance_cost : 0,
flood_estimate : 0
}
if (getLoanType(_sc) && getLoanType(_sc) == mar.LOAN_TYPE_REFINANCE) {
retval = {
loan_type_refinance_takehome_value : num(_sc.loan_type_refinance_takehome_value),
refi_home_insurance_cost : num(_sc.refi_home_insurance_cost),
flood_estimate : num(_sc.flood_estimate)
};
}
return retval;
}
/**
* @namespace MAR.math
*/
var math = (function(){
/**
* @memberof MAR.math
*/
function PMT(rate, nperiod, pv, fv, type) {
// http://stackoverflow.com/questions/5294074/pmt-function-in-javascript
if (!fv) fv = 0;
if (!type) type = 0;
if (rate == 0) return -(pv + fv)/nperiod;
var pvif = Math.pow(1 + rate, nperiod);
var pmt = rate / (pvif - 1) * -(pv * pvif + fv);
if (type == 1) {
pmt /= (1 + rate);
};
return pmt;
}
/**
* @memberof MAR.math
*/
function middleCreditScore(arr) {
if (arr.length == 0) return 0;
if (arr.length == 1) return arr[0];
if (arr.length == 3) return arr.sort()[1];//Math.floor(max(min(arr[0],arr[1]), min(max(arr[0],arr[1]),arr[2]))); // thanks https://stackoverflow.com/questions/1582356/fastest-way-of-finding-the-middle-value-of-a-triple
/**
* fall back to average
*/
let sum = arr.reduce(function(a, b) { return a + b; });
let avg = sum / arr.length;
return Math.floor(avg);
}
function lowestCreditScore(arr) {
let lowest = false;
for (let i=0; i < arr.length; i++) {
if (lowest === false || arr[i] < lowest) lowest = arr[i];
}
return lowest;
}
function lowest() {
let rv = false;
for (let i=0; i < arguments.length; i++) {
if (rv === false || arguments[i] < rv) rv = arguments[i];
}
return rv;
}
function low(arr) {
let lowest = false;
for (let i=0; i < arr.length; i++) {
if (lowest === false || arr[i] < lowest) lowest = arr[i];
}
return lowest;
}
function high(arr) {
let highest = false;
for (let i=0; i < arr.length; i++) {
if (highest === false || arr[i] > highest) highest = arr[i];
}
return highest;
}
return {
PMT : PMT,
low : low,
high : high,
lowest : lowest,
lowestCreditScore : lowestCreditScore,
middleCreditScore : middleCreditScore,
___id : "math"
}
})();
/**
* @memberof MAR
*/
var addVariableCLosingCostsToApproximate_costs_t = {
Insurance_Factor : 0,
Property_Tax : 0,
HOA_SFR_nolux_pm : 0,
HOA_SFR_Lux_pm : 0,
HOA_Cond_lux_pm : 0,
HOA_Cond_nolux_pm : 0,
sqft_int : 0
}
/**
* @memberof MAR
* -- never called , depreciated --
*/
function addVariableCLosingCostsToApproximate_costs(obj /*addVariableCLosingCostsToApproximate_costs_t*/) {
/**
*
* from HOI HOA Matrix
* ===================
* Insurance_Factor 2.9
* Property_Tax 0.009
* HOA_SFR_nolux_pm 0.06
* HOA_SFR_Lux_pm 0.4
* HOA_Cond_lux_pm 0.85
* HOA_Cond_nolux_pm 0.4
*
*/
}
//additional_lender_credit
let RS = {
processing_fee : { lbl : "Processing fee", filter : [""], apr : false, qm : true, cols : [""] },
underwriting_fee : { lbl : "Underwriting fee", filter : [""], apr : false, qm : true, cols : [""] },
additional_lender_credit: { lbl : "Additional lender credit", filter : [""], apr : false, qm : true, cols : [""] , template : `hidden` },
A : { lbl : "Appraisal fee", filter : ["",""], apr : true, qm : true, cols : ["SFR/Condo","other"] , same_as : `appraisal_fee` },
B : { lbl : "Condo Questionairre", filter : [""], apr : false, qm : true, cols : [""] , same_as : `condo_questionairre` },
RRA : { lbl : "Rent Roll Analysis", filter : [""], apr : false, qm : true, cols : ["If Needed"] , same_as : `rent_roll_analysis`},
credit_report_key : { lbl : "Credit report fee", filter : [""], apr : true, qm : true, cols : [""] },
E : { lbl : "Title search", filter : ["p"], apr : false, qm : true, cols : ["Purchase"] , same_as : `title_search`},
various_endorsements : { lbl : "Various endorsements", filter : [""], apr : false, qm : true, cols : [""] },
title_settlement_fee : { lbl : "Title settlement fee", filter : ["p","r"], apr : false, qm : true, cols : ["Purchase", "Refi"] },
C : { lbl : "Mortgage policy (x loan)", filter : ["p","r"], apr : true, qm : true, cols : ["Purchase","Refi"] , same_as : `mortgage_policy`},
F : { lbl : "Owner title ins", filter : ["p"], apr : true, qm : true, cols : ["Purchase"] , same_as : `owner_title_insurance`},
recording_fee : { lbl : "Recording fee", filter : [""], apr : true, qm : true, cols : [""] },
D : { lbl : "Survey", filter : ["r"], apr : true, qm : true, cols : ["Refi Condo"] , same_as : `survey`},
G : { lbl : "Fl Doc Stamps", filter : ["p"], apr : false, qm : true, cols : ["(Purch) N x loan"] , same_as : `fl_doc_stamps`},
H : { lbl : "State taxes", filter : ["p"], apr : false, qm : true, cols : ["(Purch) N x loan"] , same_as : `state_taxes`}
}
//owner_title_insurance
/**
* default values , only called internally
*/
let RDEF = {
processing_fee : [625],
underwriting_fee : [799],
additional_lender_credit : [0],
A : [475,625], // appraisal fee
B : [350], // condo questionairre
RRA : [150], // Rent Roll Analysis
credit_report_key : [65],
E : [172], // title search
various_endorsements : [50],
title_settlement_fee : [495,595],
C : [0.00585,0.00330], // Mortgage policy
F : [172], // Owner title Ins
recording_fee : [250],
D : [350], // Survey
G : [0.0035], // Fl Doc Stamps
H : [0.002] // State Taxes
};
function getRatesheet() {
return {
RS : RS,
R : RDEF
}
}
function get_estimated_closing_date( ans = false) {
if (ans !== false) {
mar.answers = ans;
}
let Moment = (typeof context === "object") ? context.global.moment : moment;
let start_d = moment();
if (MAR.application.isRefi()) {
let closing_d = (function(){
let plus_50 = start_d.clone().add(50, "day");
if (plus_50.date() > 15) {
plus_50.date(15);
} else {
plus_50.subtract(1, "month")
plus_50.date(15);
}
return plus_50;
})();
return closing_d.format("YYYY-MM-DD");
} else {
let closing_d = (function(){
let timeframe = getScenario_data("loan_type_purchase_options",``);
if (timeframe === `contract`) {
let plus_50 = start_d.clone().add(14, "days");
return plus_50;
}
else if (timeframe === `soon`) {
let plus_50 = start_d.clone().add(30, "days");
return plus_50;
}
else if (timeframe === `one_month`) {
let plus_50 = start_d.clone().add(60, "days");
return plus_50;
}
else if (timeframe === `three_months`) {
let plus_50 = start_d.clone().add(90, "days");
return plus_50;
}
else if (timeframe === `just_looking`) {
let plus_50 = start_d.clone().add(90, "days");
return plus_50;
}
else {
let plus_50 = start_d.clone().add(30, "days");
return plus_50;
}
})();
return closing_d.format("YYYY-MM-DD");
}
}
/**
* @memberof MAR
*
* called from
* _universal.js
* libs/durunner.app.js
* libs/durunner.api.chatbot.js
*
*/
function getApproximateClosingCosts(max_loan, final_ufmi, buydown_points, ptype_str, loantype_str, hoipm_int, hoapm_int, taxpm_int, rate_dbl,dbg_arr, {
hoi_due_date,
refi_date_now,
closing_date = false,
branch,
prog,
ratesheet,
over_ratesheet,
refi_mort_rate,
refi_mort_terms,
refi_mort_pmtinc,
refi_mort_escrow,
refi_mort_sdate,
tax_due,
propertyvalue = 0,
opt_rra_needed = ``, // '' or true or false
adjusters = {}
}) {
let Moment = (typeof context === "object") ? context.global.moment : moment;
if (arguments.length > 3) {
/* -- take it from the variales -- */
var property_type = ptype_str;
var loan_type = (loantype_str.toLowerCase().indexOf("refi") > -1 || loantype_str.toLowerCase().indexOf("cashout") > -1) ? mar.LOAN_TYPE_REFINANCE : mar.LOAN_TYPE_PURCHASE;
} else {
/* -- take it from the answers -- */
var property_type = getPropertyType_v2(mar.answers.v2.scenario);
var loan_type = getLoanType_v2(mar.answers.v2.scenario);
}
var dbg = (arguments.length > 9 && dbg_arr !== false);
if (dbg) dbg_arr.push(`gacc start`);
let trace = false;
if (trace) console.log(`ACC ${loantype_str} -> ${loan_type}`);
let R = JSON.parse(JSON.stringify(RDEF)); /* -- these are the default values for the standard items -- */
if (typeof ratesheet === "object") {
for (let x in ratesheet) {
if (typeof ratesheet[x] === "object" && ratesheet[x].length === R[x].length) {
R[x] = ratesheet[x];
if (trace) console.log(`RS replace ${x} with ${JSON.stringify(ratesheet[x])}`); /* -- the ratesheet values that would overview the R[] -- */
}
}
}
if (typeof over_ratesheet === "object") {
for (let x in over_ratesheet) {
if (typeof over_ratesheet[x] === "object" && over_ratesheet[x].length === R[x].length) {
for (let j=0; j < R[x].length; j++) {
if (typeof over_ratesheet[x][j] === "number") {
R[x][j] = over_ratesheet[x][j];
if (trace) console.log(`RS OVER replace ${x}[${j}] with ${JSON.stringify(over_ratesheet[x][j])}`);
} else {
if (trace) console.log(`RS OVER NOT replace ${x}[${j}] with ${JSON.stringify(over_ratesheet[x][j])} type ${typeof over_ratesheet[x][j]}`);
}
}
}
}
}
var hoipm = (arguments.length > 5) ? hoipm_int : 0;
var hoapm = (arguments.length > 6) ? hoapm_int : 0;
var taxpm = (arguments.length > 7) ? taxpm_int : 0;
var rate = (arguments.length > 8) ? rate_dbl : 0.06;
let escrows = {};
if (arguments.length < 3 || !buydown_points) buydown_points = 0;
var A = (property_type == mar.PROPERTY_TYPE_SFR || property_type == mar.PROPERTY_TYPE_CONDO) ? R.A[0] : R.A[1]; /* if fha +$25 */
/*
fha diff
*/
var B = (property_type == mar.PROPERTY_TYPE_CONDO) ? R.B[0] : 0; /* fixed */
var C = (loan_type !== mar.LOAN_TYPE_REFINANCE) ? (R.C[0] * max_loan) : (R.C[1] * max_loan); /* todo not sure, for 2 states !! */
var D = (loan_type !== mar.LOAN_TYPE_REFINANCE && property_type != mar.PROPERTY_TYPE_CONDO) ? R.D[0] : 0;
/*
if you are buying a condo then 350
*/
var E = (loan_type == mar.LOAN_TYPE_REFINANCE) ? 0 : R.E[0]; /* only if purchase , add 125 */
/*
if loan amount < 100k then loan /1000 * 5.75
if < 1m then loan /100 * 5
otherwise 2.5
** this is C becasue it is a refi
refi & have copy of old owners policy
if loan amount < 100k then loan /1000 * 3.3
if < 1m then loan /100 * 3
otherwise 2
*/
escrows.tax_months = 4;
escrows.hoi_months = 2;
escrows.int_days = 15;
if (typeof closing_date === "string" && closing_date.trim().length > 0) {
let closing_d = moment(new Date(closing_date));
escrows.day_of_month = closing_d.date();
escrows.days_in_month = closing_d.daysInMonth();
escrows.int_days = (escrows.days_in_month - escrows.day_of_month);
if (escrows.day_of_month < 3) {
escrows.int_days = (escrows.day_of_month*-1);
escrows.tax_months = 3;
escrows.hoi_months = 1;
}
}
var F = (loan_type !== mar.LOAN_TYPE_REFINANCE) ? R.F[0] : 0; /* todo per county */
var G = (loan_type !== mar.LOAN_TYPE_REFINANCE) ? (R.G[0] * max_loan) : 0 ; /* todo per state */
// var H = (loan_type !== mar.LOAN_TYPE_REFINANCE) ? (R.H[0] * max_loan) : 0 ; /* todo per state */
var H = (R.H[0] * max_loan); /* todo per state */
var I = Math.round(taxpm * escrows.tax_months);
var J = Math.round(hoipm * escrows.hoi_months);
var JJ = (loan_type === mar.LOAN_TYPE_PURCHASE) ? Math.round(hoipm * 12) : 0; /* first year ins premium to prepaids */
var K = Math.round(((max_loan * rate) / 365) * escrows.int_days);
var RRA = 0;
if (opt_rra_needed === `` && loan_type !== mar.LOAN_TYPE_REFINANCE) {
RRA = R.RRA[0];
} else if (opt_rra_needed === `y` || opt_rra_needed === `Y` || opt_rra_needed === true) {
RRA = R.RRA[0];
}
if (loan_type == mar.LOAN_TYPE_REFINANCE) {
//hoi_due_date
// let Moment = (typeof context === "object") ? context.global.moment : moment;
let start_d = (typeof refi_date_now === "string") ? moment(new Date(refi_date_now)) : moment();
let closing_d = (function(){
if (typeof closing_date === "string" && closing_date.trim().length > 0) {
return moment(new Date(closing_date));
}
let plus_50 = start_d.clone().add(50, "day");
if (plus_50.date() > 15) {
plus_50.date(15);
} else {
plus_50.subtract(1, "month")
plus_50.date(15);
}
return plus_50;
})();
escrows.day_of_month = closing_d.date(); // e.g. 18
escrows.days_in_month = closing_d.daysInMonth();
escrows.start_d = start_d.format("YYYY-MM-DD");
escrows.closing_d = closing_d.format("YYYY-MM-DD");
let firstpay_d = closing_d.clone().add(2, "month").date(1);
if (escrows.day_of_month < 3) {
escrows.int_days = (closing_d.date()*-1); // escrows.days_in_month - closing_d.date(); /* e.g. 31 - 18 */
firstpay_d = closing_d.clone().add(1, "month").date(1);
// bump up the date maybe
} else {
escrows.int_days = escrows.days_in_month - closing_d.date(); /* e.g. 31 - 18 */
}
escrows.firstpay_d = firstpay_d.format("YYYY-MM-DD");
K = Math.round(((max_loan * rate) / 365) * escrows.int_days); // per day rate
if (trace) console.log(`ACC start_d ${start_d} -> closing_d ${closing_d} -> firstpay_d ${firstpay_d} -> hoi_due_date ${hoi_due_date} -> ${typeof hoi_due_date}`);
if (typeof hoi_due_date === "string") {
let hoi_dd = moment(new Date(hoi_due_date));
let now_d = moment();
if (hoi_dd.isBefore(firstpay_d)) {
hoi_dd.add(1, "year");
}
let diff_mo = hoi_dd.diff(firstpay_d, "months");
let missing_payments = (12 - diff_mo);
if (trace) console.log(`ACC hoi_dd ${hoi_dd} -> diff_mo ${diff_mo} -> missing_payments ${missing_payments} -> hoipm ${hoipm}`);
J = Math.round(hoipm * missing_payments);
escrows.hoi_dd = hoi_dd.format("YYYY-MM-DD");
escrows.hoi_months = missing_payments;
}
(function() {
let tax_dd = moment().month(10).day(1);
if (typeof tax_due === "string" && tax_due.trim() !== "") {
tax_dd = moment(new Date(tax_due));
}
let now_d = moment();
let closing_d = moment(escrows.closing_d);
if (tax_dd.isBefore(firstpay_d)) {
tax_dd.add(1, "year");
}
let diff_mo = tax_dd.diff(firstpay_d, "months",true);
let missing_payments = (12 - Math.abs(Math.round(diff_mo)));
escrows.tax_dbg = (`ACC IF1 closing_d ${closing_d} / firstpay_d ${firstpay_d} / tax_dd ${tax_dd} -> diff_mo ${diff_mo} -> missing_payments ${missing_payments}`);
// let missing_payments = 0;
// if (tax_dd.isBefore(closing_d)) {
// // paid off before closing , just need months uo to 1st payment
// let diff_mo = closing_d.diff(firstpay_d, "months",true);
// missing_payments = Math.abs(Math.round(diff_mo));
// escrows.tax_dbg = (`ACC IF1 closing_d ${closing_d} / firstpay_d ${firstpay_d} / tax_dd ${tax_dd} -> diff_mo ${diff_mo} -> missing_payments ${missing_payments}`);
// }
// else if (tax_dd.isBefore(firstpay_d)) {
// // paid off before closing , just need months uo to 1st payment
// let diff_mo = tax_dd.diff(firstpay_d, "months",true);
// missing_payments = 12 + Math.abs(Math.round(diff_mo));
// escrows.tax_dbg = (`ACC IF2 tax_dd ${tax_dd} / firstpay_d ${firstpay_d} / tax_dd ${tax_dd} -> diff_mo ${diff_mo} -> missing_payments ${missing_payments}`);
// } else {
// let diff_mo = tax_dd.diff(firstpay_d, "months",true);
// missing_payments = (12 - Math.abs(Math.round(diff_mo)));
// escrows.tax_dbg = (`ACC IF3 tax_dd ${tax_dd} / firstpay_d ${firstpay_d} / tax_dd ${tax_dd} -> diff_mo ${diff_mo} -> missing_payments ${missing_payments}`);
// }
I = Math.round(taxpm * missing_payments);
escrows.tax_dd = tax_dd.format("YYYY-MM-DD");
escrows.tax_months = missing_payments;
})();
}
(function alf(){
if (dbg) dbg_arr.push(`alf-start`);
let alf = MAR.getOpt(R, "additional_lender_credit.0",0);
if (dbg) dbg_arr.push(`alf[${alf}]`);
})();
var costs = {
"processing_fee" : R.processing_fee[0], /* fixed (per branch) was 500*/
"underwriting_fee" : R.underwriting_fee[0], /* fixed (per branch) was 999 */
//"doc_prep_fee" : 0,
"appraisal_fee" : (A),
"credit_report_key" : R.credit_report_key[0],// 35 or 70 /* fixed (per company) */
"buydown_points" : (buydown_points) > 0 ? buydown_points : 0, /* need full rate sheet */
"buydown_lender_credit" : (buydown_points) < 0 ? buydown_points : 0,
"flood_certification_fee" : 00, /* fixed (per comapny) was 16 */
"tax_service" : 00, /* fixed (per comapny) was 80*/
"re_inspection_fee" : 0, /* fixed (per comapny) */
"condo_questionairre" : (B),
"rent_roll_analysis" : (RRA),
"title_review_fee" : 0,
"title_search" : (E), /* depends on title company, if you use matt lerner */
"additional_lender_credit" : MAR.getOpt(R, "additional_lender_credit.0",0),
"various_endorsements" : R.various_endorsements[0], /* depends on title company */
"title_settlement_fee" : (loan_type == mar.LOAN_TYPE_REFINANCE) ? R.title_settlement_fee[0] : R.title_settlement_fee[1], /* 595 refi, 495 pur*/ /* depends on title company */
"mortgage_policy" : 0,
"owner_title_insurance" : (F),
"recording_fee" : R.recording_fee[0], /* fixed (maybe per state) */
"endorsements" : 0,
"fl_doc_stamps" : 0, /* warning in 95% of cases the seller pays this amount*/
"state_taxes" : 0, /* combine the last 2 */
"mcc_class" : (0), /* not sure , if ftb then 250 */
"survey" : (D), /* fixed */
"pest_inspection" : 0, /* non mandatory */
"ad_valoram_taxes" : 0,
"upfront_mi" : final_ufmi,
"end" : 0, /* paid outside of closing cost */
"taxes_escrow" : I, /* put 4/12 of average house size in county*/
"insurance_escrow" : J, /* put 2/12 of average house size in county*/
"home_insurance_escrow" : JJ,
"flood_insurance_escrow" : 0,
"daily_interest" : 0 /* put 1/2 mo of interest on purchase price 6% of loan amount / 365 * 15*/
};
MAR.ifOpt(adjusters, "rq_custom_table", function(v){
for (let i=0; i < v.length; i++) {
let itm = v[i];
let calctype = MAR.getOpt(itm, `calctype`,``);
if (calctype === `pla`) {
let perc = MAR.getOptNum(itm, `perc`,0)
itm.val = Math.round(num(max_loan) * num(perc) / 100);
}
if (calctype === `ppp`) {
let perc = MAR.getOptNum(itm, `perc`,0)
itm.val = Math.round(num(propertyvalue) * num(perc) / 100);
}
if (calctype === `pdi`) {
let perc = MAR.getOptNum(itm, `perc`,0)
itm.val = Math.round((num(propertyvalue) - num(max_loan)) * num(perc) / 100);
}
if (calctype === `pp`) {
let months = MAR.getOptNum(itm, `months`,0)
let monthly = MAR.getOptNum(itm, `monthly`,0)
itm.val = Math.round(num(months) * num(monthly));
}
if (num(itm.val) !== 0) {
let lbl = "_"+itm.lbl.replace(/ /g,"_");
costs[lbl] = num(itm.val);
}
}
});
var fixedcosts = 0;
for (let x in costs) {
fixedcosts += costs[x];
}
costs.mortgage_policy = C;
costs.fl_doc_stamps = G;
costs.state_taxes = H;
costs.daily_interest = K;
var totalcost = 0;
for (let x in costs) {
totalcost += costs[x];
if (dbg && costs[x] > 0) dbg_arr.push("{"+x+"="+costs[x]+"}")
}
return {
costs : costs,
total : totalcost,
total10 : totalcost*1.35,
fixed : fixedcosts,
variable : (totalcost -fixedcosts) / max_loan,
escrows : escrows
}
}
/**
* @memberof MAR
*/
function getNiceMIname(MI) {
if (MI == "bpmi_rad_more20") return "BPMI";
if (MI == "split_uphigh_rad") return "UPHI";
if (MI == "split_uplow_rad") return "UPLO";
if (MI == "ufmi_more20") return "UFMI";
if (MI == "bpmi_FHA") return "BPMI";
return MI
}
/**
* application Navigation
* @namespace MAR.declarations
*/
var applicationNavObj = (function(){
let orderTable = [
"intro",
"general",
"timeframe",
"scenario",
"property",
"estimate",
"realtorinfo",
"assets",
"personalinfo",
"income",
"liabilities",
"homework"
];
function setHadToDoAll() {
for (let i=0; i < orderTable.length; i++) {
let section = orderTable[i];
setScenario_data(`_sec_${section}_verified`, "N");
}
for (let x in mar.answers.v2.scenario) {
if (x.startsWith("_page_") && x.endsWith("_verified")) {
delete mar.answers.v2.scenario[x];
}
}
}
function loanWasImported() {
return (getScenario_data("__application_imported_from_encompass","N") === "Y");
}
function loanWasImportedAndNotVerified() {
if (getScenario_data("__application_imported_from_encompass","N") !== "Y") return false;
if (getScenario_data("__application_imported_from_encompass_needs_verification","N") === "Y") return true;
return false;
}
function loanWasImportedAndHasUnverifiedIncomeChange() {
if (getScenario_data("__application_imported_from_encompass_needs_verification_incomechange","N") === "Y") return true;
return false;
}
function loanWasNotImportedAndNotSubmitted() {
if (getScenario_data("__application_imported_from_encompass","N") === "Y") return false;
return (getScenario_data("__application_submitted","N") !== "Y");
}
function loanWasSubmitted() {
if (loanWasImported() === true) {
return !loanWasImportedAndNotVerified();
} else {
return !loanWasNotImportedAndNotSubmitted();
}
}
function pageVerified(pagename,YN) {
if (!loanWasImported()) return true;
if (arguments.length > 1) {
setScenario_data(`_page_${pagename}_verified`, YN);
return;
}
return (getScenario_data(`_page_${pagename}_verified`, "N") === "Y");
}
let verifictions = {};
verifictions.sectionIsVerified_intro = function() {
return true;
}
verifictions.sectionIsVerified_general = function() {
if (!pageVerified("encompass-intro")) return "#import-encompass-intro";
return true;
}
verifictions.sectionIsVerified_timeframe = function() {
if (!pageVerified("timeframe")) { debugger; return "#scenario-timeframe";}
return true;
}
verifictions.sectionIsVerified_scenario = function() {
for (var i=0; i < mar.answers.v2.applicants.length; i++) {
if (!pageVerified(`creditscore.${i}`)) return `#scenario-creditscore.${i}`;
}
return true;
}
verifictions.sectionIsVerified_property = function() {
return true;
}
verifictions.sectionIsVerified_estimate = function() {
return true;
}
verifictions.sectionIsVerified_realtorinfo = function() {
return true;
}
verifictions.sectionIsVerified_assets = function() {
return true;
}
verifictions.sectionIsVerified_personalinfo = function() {
return true;
}
verifictions.sectionIsVerified_income = function() {
return true;
}
verifictions.sectionIsVerified_liabilities = function() {
return true;
}
verifictions.sectionIsVerified_homework = function() {
return true;
}
function sectionIsVerified(section) {
if (loanWasImported() == false) return true;
// if (getScenario_data(`_sec_${section}_verified`, "Y") === "Y") {
// return true;
// }
if (`sectionIsVerified_${section}` in verifictions == true) {
let isverified = verifictions[`sectionIsVerified_${section}`]();
if (isverified !== true) return isverified;
// setScenario_data(`_sec_${section}_verified`, "Y");
mar.fakesave();
}
return true;
}
function hasEnteredReatorInfo(answers) {
if (getScenario_data("loan_type" ,"purchase",answers) !== "purchase") return true;
if (getScenario_data("have_own_realtor" ,false,answers) == false) return "#scenario-realtor";
if (getScenario_data("have_own_realtor" ,false,answers) == "N") return true;
if (getScenario_data("realtor_name" ,false,answers) == false) return "#scenario-realtor";
return true
}
function hasEnteredAssets() {
//if (getScenario_data("__application_imported_from_encompass_purpose" ,"").indexOf("Refinance") > -1) return true
let _assets = getAssets_v2();
// if (_assets.has_unverified_items === true) return "#assets-choice";
if (_assets.total == 0 && MAR.is_refi() === false) return "#assets-choice";
// if (isRefi() === false && _assets.total == 0) return "#assets-choice";
return true;
}
function hasEnteredAssetsEver() {
//if (getScenario_data("__application_imported_from_encompass_purpose" ,"").indexOf("Refinance") > -1) return true
let _assets = getAssets_v2();
// if (_assets.has_unverified_items === true) return "#assets-choice";
if (_assets.total == 0 && MAR.is_refi() === false) return "#assets-choice";
if (getScenario_data("__assets_passed","") !== "Y") return "#assets-choice";
return true;
}
function missingFields() {
let applicantLength = getApplicants_v2().length;
let missingfields = [];
for (let i=0; i < applicantLength; i++) {
if (MAR.getOpt(getApplicantBucket(i), "ty" , "") === "") return `#scenario-personaldata.${i}`;
let adc = MAR.getApplicantAddressCurrent(i)[0];
if (MAR.getOpt(adc, "appears_on_drivers_license" , "") === "") return `#scenario-addresshistory.${i}.0`;
if (MAR.getOpt(adc, "appears_on_tax_returns" , "") === "") return `#scenario-addresshistory.${i}.0`;
if (MAR.getOpt(adc, "years" , "") === "") return `#scenario-addresshistory.${i}.0`;
if (MAR.getOpt(adc, "months" , "") === "") return `#scenario-addresshistory.${i}.0`;
}
}
function hasEnteredPersonalInfoByApplicant(applicantnum) {
let _scenario = getScenario_v2();
let i = applicantnum;
let sta = "";
sta = sup_data_status(`/applicants/address/_${i}/sup-data/personal-data`);
if (sta < 1) return `#scenario-personaldata.${i}`;
sta = sup_data_status(`/applicants/address/_${i}/sup-data/address-history`);
if (sta < 1) return `#scenario-addresshistory.${i}`;
return true;
}
function hasEnteredPersonalInfo(ROLE) {
let _scenario = getScenario_v2();
let _names = getApplicantsNames_v2();
let _applicantcount = _names.length;
for (let i=0; i < _applicantcount; i++) {
let sta = "";
sta = sup_data_status(`/applicants/address/_${i}/sup-data/personal-data`);
if (sta < 1) console.error("cfc sup data 1",sup_data.lasterror);
if (sta < 1) return `#scenario-personaldata.${i}`;
sta = sup_data_status(`/applicants/address/_${i}/sup-data/address-history`);
if (sta < 1) console.error("cfc sup data 2",sup_data.lasterror);
if (sta < 1) return `#scenario-addresshistory.${i}`;
if (i == 0) {
if (arguments.length == 0) {
ROLE = __ROLE;
}
let c = 0;
// let c = MAR.getConsents(ROLE);
if (getScenario_data(`authorizations-credit-ed_${i}_passed`,"N") != "Y") c = 0; else c = 1;
if (c == 0) return `#authorizations-credit-ed.${i}`;
}
}
return true;
}
function hasEnteredIncomeByApplicant(applicantnum, include_verfied_check = true) {
let i = applicantnum;
let _scenario = getScenario_v2();
getIncome_v2();
if (mar.answers.v2.income.length < (applicantnum+1)) return `#income-how.${i}`;
if ("items" in mar.answers.v2.income[i] == false) return `#income-how.${i}`;
if (mar.answers.v2.income[i].items.length == 0) return `#income-how.${i}`;
for (let j=0; j < mar.answers.v2.income[i].items.length; j++) {
if (MAR.getOpt(mar.answers.v2.income[i].items[j], "verified", "") === "N") {
if (include_verfied_check) {
return `#income-how.${i}`;
}
}
}
return true
}
function hasEnteredIncomeEverByApplicant(applicantnum) {
let i = applicantnum;
let _scenario = getScenario_v2();
getIncome_v2();
if (mar.answers.v2.income.length < (applicantnum+1)) return false;
if ("items" in mar.answers.v2.income[i] == false) return false;
if (mar.answers.v2.income[i].items.length == 0) return false;
return true
}
function hasEnteredIncome(include_verfied_check = true) {
let _scenario = getScenario_v2();
let _names = getApplicantsNames_v2();
let _applicantcount = _names.length
getIncome_v2();
for (let i=0; i < _applicantcount; i++) {
if (mar.answers.v2.income.length < _applicantcount) return `#income-how.${i}`;
if ("items" in mar.answers.v2.income[i] == false) return `#income-how.${i}`;
if (mar.answers.v2.income[i].items.length == 0) return `#income-how.${i}`;
for (let j=0; j < mar.answers.v2.income[i].items.length; j++) {
if (MAR.getOpt(mar.answers.v2.income[i].items[j], "verified", "") === "N") {
if (include_verfied_check) {
return `#income-how.${i}`;
}
}
}
}
return true
}
function hasEnteredIncomeEver(include_verfied_check = true) {
let _scenario = getScenario_v2();
let _names = getApplicantsNames_v2();
let _applicantcount = _names.length
getIncome_v2();
if (_applicantcount > 1) _applicantcount = 1;
for (let i=0; i < _applicantcount; i++) {
if (mar.answers.v2.income.length < _applicantcount) return `#income-how.${i}`;
if ("items" in mar.answers.v2.income[i] == false) return `#income-how.${i}`;
if (mar.answers.v2.income[i].items.length == 0) return `#income-how.${i}`;
for (let j=0; j < mar.answers.v2.income[i].items.length; j++) {
if (MAR.getOpt(mar.answers.v2.income[i].items[j], "verified", "") === "N") {
if (include_verfied_check) {
return `#income-how.${i}`;
}
}
}
}
return true
}
function hasEnteredLiabilitiesEver(answers) {
if (getScenario_data("__liabilities_passed" ,false,answers) == false) return "#liabilities-home";
return true;
}
function hasEnteredReoEver(answers){
if (getScenario_data("__reo_passed_0" ,false,answers) == false) return "#reo-home";
return true;
}
function hasEnteredLoxEver(answers) {
if (getScenario_data("__application_submitted" ,false,answers) == false) return "#lox";
return true;
}
return {
hasEnteredReatorInfo : hasEnteredReatorInfo,
hasEnteredAssets : hasEnteredAssets,
hasEnteredAssetsEver : hasEnteredAssetsEver,
hasEnteredPersonalInfo : hasEnteredPersonalInfo,
hasEnteredPersonalInfoByApplicant : hasEnteredPersonalInfoByApplicant,
hasEnteredIncome : hasEnteredIncome,
hasEnteredIncomeEver : hasEnteredIncomeEver,
hasEnteredIncomeByApplicant : hasEnteredIncomeByApplicant,
hasEnteredIncomeEverByApplicant : hasEnteredIncomeEverByApplicant,
hasEnteredLiabilitiesEver : hasEnteredLiabilitiesEver,
hasEnteredReoEver : hasEnteredReoEver,
hasEnteredLoxEver : hasEnteredLoxEver,
/**
* section verification
*/
orderTable : orderTable,
setHadToDoAll : setHadToDoAll,
loanWasImported : loanWasImported,
loanWasImportedAndNotVerified : loanWasImportedAndNotVerified,
loanWasImportedAndHasUnverifiedIncomeChange
: loanWasImportedAndHasUnverifiedIncomeChange,
loanWasNotImportedAndNotSubmitted : loanWasNotImportedAndNotSubmitted,
loanWasSubmitted : loanWasSubmitted,
pageVerified : pageVerified,
verifictions : verifictions,
sectionIsVerified : sectionIsVerified,
/**
* id
*/
____id : "app nav"
}
})()
/**
* cf
* @namespace MAR.encompass
*/
var encompassObj = (function(){
let current = {
borrowers : {
}
};
function _swal({ msg, cancel, cancelfn, ok, okfn}){
var s = document.createElement("div");
s.setAttribute("class","normal-form");
s.innerHTML = `${msg}
`;
swal({
title : "Encompass",
className : (ok === "") ? "midelinfopopupOneButton" : "middleInfoPopup",
content : s,
buttons : {
cancel : (typeof cancel === "string") ? cancel : "cancel",
call : {
text: (typeof ok === "string") ? ok : "ok",
value: "continue",
closeModal: false
}
}
})
.then((act) => {
if (act == "continue") {
if (typeof okfn === "function") {
okfn()
} else {
swal.close();
}
} else {
if (typeof cancelfn === "function") {
cancelfn()
}
}
})
}
function isSynchedSync(appid) {
if (typeof appid === "undefined") appid = mar.ID;
return new Promise(function(resolve, reject) {
$.get(`/api/encompass/appHelpers/is_synced?appid=${appid}`, function(rv){
resolve(rv);
});
});
}
function waitSync(n) {
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve()
},n);
});
}
let isBorrowerInEncompass_rv = false;
function isBorrowerInEncompass(appid) {
if (typeof appid === "undefined") appid = mar.ID;
return new Promise(function(resolve, reject) {
$.get(`/api/encompass/appHelpers/is_there_a_new_borrower?appid=${appid}`, function(rv){
isBorrowerInEncompass_rv = rv;
resolve(rv);
});
});
}
function uploadNewBorrowerToEncompass(appid, bp) {
if (typeof appid === "undefined") appid = mar.ID;
let url = `/api/encompass/appHelpers/upload_new_borrowers?appid=${appid}&update=y&borrowers=${bp}`;
return new Promise(function(resolve, reject) {
$.get(url, function(rv){
resolve(rv);
});
});
}
function uploadNewBorrowerToEncompassTfSync(appid, tf) {
if (typeof appid === "undefined") appid = mar.ID;
let url = `/api/encompass/appHelpers/upload_new_borrowers?appid=${appid}&update=y&tf=${tf}`;
return new Promise(function(resolve, reject) {
$.get(url, function(rv){
resolve(rv);
});
});
}
async function app_check_diffs_assetsSync(appid, applicantid) {
if (typeof appid === "undefined") appid = mar.ID;
if (typeof applicantid === "undefined") applicantid = 0;
let isSynchedObj = await MAR.encompass.isSynchedSync(appid)
if (isSynchedObj.synched === false) {
return {
status : -1,
statusMsg : "not syched"
};
return;
}
if (isBorrowerInEncompass_rv === false) {
await isBorrowerInEncompass(appid);
}
let ssn = MAR.digits(getApplicant_sn(applicantid));
let bc = MAR.getOpt(isBorrowerInEncompass_rv, `en_ssns.${ssn}`,"");
if (bc === "") {
return {
status : -2,
statusMsg : "applicant not synched"
};
return;
}
return new Promise(function(resolve, reject) {
let url = `/api/encompass/appHelpers/has_anything_changed?appid=${appid}&type=borrower-${bc}.AS`;
$.get(url, function(rv){
if (rv.diffs.length > 0) {
resolve({
status : 0,
tf : rv.tf,
diffs : rv.diffs
});
}
});
});
}
function ui_display_lomenu() {
let $menu = $("#lo-hamburger");
let $icon = $("#lo-hamburger span");
$icon.addClass("animated");
$icon.css("color" , "unset");
$menu.removeClass("x-hide");
}
function are_there_changes() {
let $icon = $("#lo-hamburger span");
return ($icon.hasClass("animated"));
}
function ui_hide_lomenu() {
let $menu = $("#lo-hamburger");
let $icon = $("#lo-hamburger span");
$icon.removeClass("animated");
$icon.css("color" , "#00000033");
//animated
$menu.removeClass("x-hide");
// $menu.addClass("x-hide");
}
function ui_update_lomenu() {
let $menu = $("#lo-hamburger");
let are_diffs = false;
for (let x in current.borrowers) {
let b = current.borrowers[x];
if (typeof b !== "object") continue;
if (b === null) continue;
let diffs = MAR.getOpt(b,"diffs",[]);
if (diffs.length > 0) are_diffs = true;
}
if (are_diffs) {
ui_display_lomenu();
} else {
ui_hide_lomenu();
}
}
function ui_onebutton() {
$(".swal-modal").removeClass("middleInfoPopup");
$(".swal-modal").addClass("midelinfopopupOneButton");
$(".swal-footer .swal-button-container")[1].style.setProperty('display', 'none', 'important');
}
function ui_dualbutton() {
$(".swal-modal").addClass("middleInfoPopup");
$(".swal-modal").removeClass("midelinfopopupOneButton");
$($(".swal-footer .swal-button-container")[1]).css("display", "unset");
}
function ui_lomenu_click() {
let $chks = $(".x-sync-del-chk");
let chks = [];
for (let i=0; i < $chks.length; i++) {
let $chk = $($chks[i]);
if ($chk.prop("checked")) {
chks.push($chk);
$chk.parent().parent().css("opacity", "0.5")
} else {
$chk.parent().parent().css("opacity", "1.0")
}
if (chks.length > 0) {
$(".swal-button.swal-button--call").html("Delete");
} else {
$(".swal-button.swal-button--call").html("Upload");
}
}
return chks;
}
let tfs = [];
let urls = [];
let xs = [];
async function ui_lomenu_reload_fn() {
let enp = $(".swal-modal #en-progress");
let enc = $(".swal-modal #en-content");
let $but = $(".swal-button.swal-button--call");
$but.addClass("x-hide");
ui_onebutton();
enp.html("Rechecking synch");
enc.html("
");
let h = "";
urls = [];
tfs = [];
xs = [];
let unproc = false;
current.borrowers = {};
for (let i=0; i < MAR.applicants.count(); i++) {
let rv = await app_check_diffs_borrower_profileSync(mar.ID, i, { deferred : false});
}
for (let x in current.borrowers) {
let b = current.borrowers[x];
if (typeof b !== "object") continue;
if (b === null) continue;
let diffs = MAR.getOpt(b,"diffs",[]);
let tf = MAR.getOpt(b,"tf","");
let _unproc = MAR.getOpt(b,"unproc",false);
if (_unproc) unproc = true;
if (diffs.length === 0) continue;
tfs.push(tf);
urls.push(b.url);
xs.push(x);
let borrower_label = ((x.endsWith("B")) ? "Borrower" : "Co borrower") + " " +(num(x.substring(0,1))+1);
h += `
${borrower_label} `;
let G = false;
let U = false;
for (let i=0; i < diffs.length; i++) {
if (typeof diff === "string") {
let diff = diffs[i];
diff = diff.split(" ");
diff.shift();
diff = diff.join(" ").split("-");
let key = diff.shift();
h += `
${key} S|${diff.join("-").trim()} `;
} else {
let diff = diffs[i].t;
let g = MAR.getOpt(diffs[i], "g", G);
if (g !== G) {
G = g;
U = false;
h += `
Group: ${G} `;
}
let u = MAR.getOpt(diffs[i], "u", U);
let hk = MAR.getOpt(diffs[i], "h", false);
if (u !== U) {
U = u;
// h += `
-- UID: ${U} `;
}
let r = MAR.getOpt(diffs[i], "r", false);
let chk = (typeof r === "string") ? `
` : "";
if (hk) {
h += `
${diff} `;
} else {
h += `
${diff} ${chk} `;
}
}
}
}
if (unproc) {
enp.html("")
enc.html("There are changes coming from Encompass that are not downloaded yet, you'll have to try again in a few minutes");
ui_onebutton();
}
else if (h === "") {
enp.html("")
enc.html("There are no changes to upload");
ui_onebutton();
} else {
let revealbut = `
Show hidden elements `;
h = `
`;
enp.html("There are changes in Elaine that need to be uploaded for this borrower. Can I proceed to upload?");
enc.html(h);
$but.html("Upload")
$but.removeClass("x-hide");
ui_dualbutton();
}
}
let ui_lomenu_obj = {};
async function ui_lomenu_fn(obj) {
let logo = `
`;
if (MAR.appnav.loanWasImportedAndNotVerified() === true) {
_swal({
msg : `${logo}
This application was created as a download from Encompass but you have not yet gone through the whole app. Until then you cannot upload the changes to Encompass.
`,
ok : "",
okfn : false,
cancel : "Cancel",
cancelfn : function() {
}
});
return;
}
ui_lomenu_obj = (obj) ? obj : {};
_swal({
msg : `${logo}
`,
ok : "Upload",
okfn : MAR.encompass.ui_lomenu_continue,
cancel : (MAR.getOpt(ui_lomenu_obj, "from","") === "close") ? "Cancel and exit" : "Cancel",
cancelfn : function() {
if (MAR.getOpt(ui_lomenu_obj, "from","") === "close" && parent) {
var data = {
from : "app",
action : "encompass_cancel"
};
parent.postMessage(data, "*");
}
}
});
elaineui.waitForElementToDisplay(".swal-modal #en-progress",100,function(){
MAR.encompass.ui_lomenu_reload_fn();
});
}
//
//
// h = `
`;
// msg : `
There are changes in Elaine that need to be uploaded for this borrower, can I proceed to upload?
${h}`,
//
// if (h === "") {
// _swal({
// msg : `There are no changes to upload.`,
// });
//
// } else {
// h = `
`;
// _swal({
// msg : `
There are changes in Elaine that need to be uploaded for this borrower, can I proceed to upload?
${h}`,
// ok : "Upload",
// okfn : MAR.encompass.ui_lomenu_continue,
// cancelfn : function() {
// alert("not smart");
// }
// });
//
// }
//
//
// }
async function ui_lomenu_continue() {
// set assets 3a8cf29f-6ba6-4121-91f4-dcdc3d8e5737/0 __enc_balance 1500
// del assets fe33ea39-e131-4d94-a6fd-7e98ca716d43/0
console.warn("C L I C K");
let $enp = $("#en-progress");
let $ent = $("#en-table");
let $but = $(".swal-button.swal-button--call");
let chks = MAR.encompass.ui_lomenu_click();
if (chks.length > 0) {
$but.text("working");
for (let i=0; i < chks.length; i++) {
let $inp = $(chks[i]);
$inp.LoadingOverlay("show");
}
await waitSync(1000);
for (let i=0; i < chks.length; i++) {
let $inp = $(chks[i]);
let r = $inp.data("r");
if (r.startsWith("del")) {
let rs = r.split(" ");
rs.shift();
let ty = rs.shift();
if (ty === "assets") {
let u = rs.shift();
await waitSync(10);
$inp.LoadingOverlay("hide",true);
await waitSync(10);
console.warn(`D E L E T E [${u}]`);
MAR.assets.deleteByENCID(u);
$inp.replaceWith("X");
continue;
}
}
if (r.startsWith("set")) {
let rs = r.split(" ");
rs.shift();
let ty = rs.shift();
if (ty === "assets") {
let u = rs.shift();
await waitSync(10);
let item = MAR.assets.getByENCID(u);
if (item !== false) {
let k = rs.shift();
let v = rs.join(" ");
item.data[k] = v;
}
$inp.LoadingOverlay("hide",true);
await waitSync(10);
$inp.replaceWith("X");
continue;
}
}
await waitSync(1000);
$inp.LoadingOverlay("hide",true);
continue;
}
$but.text("rechecking");
// $but.click(MAR.encompass.ui_lomenu_continue);
mar.fakesave(function(){
// for (let i=0; i < MAR.applicants.count(); i++) {
// $but.text(`rechecking ${i}`);
// let rv = await app_check_diffs_borrower_profileSync(mar.ID, i, { deferred : false});
// }
$but.text("rechecked");
$but.removeClass("swal-button--loading");
// $but.click(MAR.encompass.ui_lomenu_continue);
// recheck all
// swal.close();
setTimeout(function(){
MAR.encompass.ui_lomenu_reload_fn();
$but.click(MAR.encompass.ui_lomenu_continue);
if (typeof mar.pg.copilot_custom_listener === "function") {
mar.pg.copilot_custom_listener("assets-list-reload");
}
if (MAR.getOpt(ui_lomenu_obj, "from","") === "close" && parent) {
var data = {
from : "app",
action : "encompass_cancel"
};
parent.postMessage(data, "*");
}
// MAR.encompass.ui_lomenu_fn();
},1000);
});
return;
}
$but.click(function(){
setTimeout(function(){
swal.close();
},10);
return;
})
$but.text("ok");
$enp.addClass("xx-done");
$ent.html("");
for (let i=0; i < tfs.length; i++) {
$enp.html(`Uploading changes for ${xs[i]}`)
let uploadrv = await uploadNewBorrowerToEncompassTfSync(mar.ID, tfs[i]);
$enp.html(`Uploading changes for ${xs[i]}, processing return`)
if (uploadrv.status !== 0) {
$enp.html(`Error : ${uploadrv.upl.statusMsg}`);
$but.removeClass("swal-button--loading");
return;
}
else if (uploadrv.upd.status === 0) {
current.borrowers[xs[i]] = false;
continue;
// nothing
} else if (uploadrv.upd.status < 0) {
$enp.html(`Error : ${uploadrv.upd.statusMsg}`);
$but.removeClass("swal-button--loading");
return;
} else {
$enp.html(`Error : ${uploadrv.upd.rvstatus}`);
$but.removeClass("swal-button--loading");
return;
}
}
ui_update_lomenu();
$enp.html(`Upload complete!`)
$ent.html("");
$but.removeClass("swal-button--loading");
}
async function app_check_diffs_borrower_profileSync(appid, applicantid, opts) {
if (typeof appid === "undefined") appid = mar.ID;
if (typeof applicantid === "undefined") applicantid = 0;
let immediate = MAR.getOpt(opts, "immediate", false);
let deferred = MAR.getOpt(opts, "deferred", true);
if (MAR.appnav.loanWasImportedAndNotVerified() === true) {
return;
}
if (immediate === true) deferred = false;
if (deferred === true) immediate = false;
let isSynchedObj = await MAR.encompass.isSynchedSync(appid)
if (isSynchedObj.synched === false) {
return false;
}
if (isBorrowerInEncompass_rv === false) {
await isBorrowerInEncompass(appid);
}
console.log(isBorrowerInEncompass_rv);
let ssn = MAR.digits(getApplicant_sn(applicantid));
let bc = MAR.getOpt(isBorrowerInEncompass_rv, `en_ssns.${ssn}`,"");
if (bc === "") return false;
let url = `/api/encompass/appHelpers/has_anything_changed?appid=${appid}&type=borrower-${bc}.PH.P1.P2.SC.DE.CR.AS.RE.LO.EM`;
// let url = `/api/encompass/appHelpers/has_anything_changed?appid=${appid}&type=borrower-${bc}.PH.P1.P2.SC.DE.CR.AS.RE.LO`;
return new Promise(function(resolve, reject) {
$.get(url, function(rv){
current.borrowers[bc] = {
url : url,
tf : rv.tf,
unproc : rv.unproc,
diffs : rv.diffs
};
ui_update_lomenu();
if (rv.diffs.length > 0 && immediate === true) {
_swal({
msg : `There are changes in Elaine that need to be uploaded for this borrower, can I proceed to upload?
${rv.diffs.join(" ")} `,
okfn : async function() {
let uploadrv = await uploadNewBorrowerToEncompass(mar.ID, `${bc}.PH.P1.P2.SC.DE.CR`)
if (uploadrv.status !== 0) {
_swal({
msg : uploadrv.upl.statusMsg
});
}
else if (uploadrv.upd.status === 0) {
current[bc] = false;
swal.close();
// nothing
} else if (uploadrv.upd.status < 0) {
_swal({
msg : uploadrv.upd.statusMsg
});
} else {
_swal({
msg : uploadrv.upd.rvstatus
});
}
},
cancelfn : function() {
alert("not smart");
}
})
};
resolve(rv);
});
});
}
function app_check_diffs_borrower_profile_swal(appid, applicantid, rv, resolve) {
if (MAR.appnav.loanWasImportedAndNotVerified() === true) {
return;
}
_swal({
msg : `There are changes in Elaine that need to be uploaded for borrower ${applicantid+1}, can I proceed to upload?
${rv.diffs.join(" ")} `,
okfn : async function() {
let uploadrv = await uploadNewBorrowerToEncompass(mar.ID, `${rv.bc}.PH.P1.P2.SC.DE.CR`)
if (uploadrv.status !== 0) {
_swal({
msg : uploadrv.upl.statusMsg
});
resolve(false);
}
else if (uploadrv.upd.status === 0) {
swal.close();
resolve(true);
// nothing
} else if (uploadrv.upd.status < 0) {
_swal({
msg : uploadrv.upd.statusMsg
});
resolve(false);
} else {
_swal({
msg : uploadrv.upd.rvstatus
});
resolve(false);
}
},
cancelfn : function() {
resolve(false);
}
})
}
async function app_check_diffs_borrower_profileTickSync(appid, applicantid) {
if (typeof appid === "undefined") appid = mar.ID;
if (typeof applicantid === "undefined") applicantid = 0;
if (isBorrowerInEncompass_rv === false) {
await isBorrowerInEncompass(appid);
}
let ssn = MAR.digits(getApplicant_sn(applicantid));
let bc = MAR.getOpt(isBorrowerInEncompass_rv, `en_ssns.${ssn}`,"");
return app_check_diffs_borrower_profileTickSync(appid, applicantid, { deferred : true })
// if (bc === "") return false;
// let url = `/api/encompass/appHelpers/has_anything_changed?appid=${appid}&type=borrower-${bc}.PH.P1.P2.SC.DE.CR`;
//
// return new Promise(function(resolve, reject) {
// $.get(url, function(rv){
// resolve(rv);
// });
// });
}
async function app_check_upload_borrowerSync(appid) {
if (typeof appid === "undefined") appid = mar.ID;
if (MAR.appnav.loanWasImportedAndNotVerified() === true) {
return;
}
needs_app_check_upload_borrowerSync = 2;
let isSynchedObj = await MAR.encompass.isSynchedSync(appid)
if (isSynchedObj.synched === true) {
let bie = await MAR.encompass.isBorrowerInEncompass(appid);
if (bie.dirty.length > 0) {
needs_app_check_upload_borrowerSync = 1;
return;
}
if (bie.new_cnt === 0) {
needs_app_check_upload_borrowerSync = 0;
return;
}
// _swal({
// msg : "One of the borrowers needs to be uploaded, Would you like to upload to encompass NOW?",
// okfn : async function() {
// alert("ok, lets do it");
// let uploadrv = await uploadNewBorrowerToEncompass(mar.ID, bie.new_in_app_str)
// if (uploadrv.status !== 0) {
// needs_app_check_upload_borrowerSync = 1;
// _swal({
// msg : uploadrv.upl.statusMsg
// });
// }
// else if (uploadrv.upd.status === 0) {
// needs_app_check_upload_borrowerSync = 0;
// } else if (uploadrv.upd.status < 0) {
// needs_app_check_upload_borrowerSync = 1;
// _swal({
// msg : uploadrv.upd.statusMsg
// });
// } else {
// needs_app_check_upload_borrowerSync = 1;
// _swal({
// msg : uploadrv.upd.rvstatus
// });
// }
// },
// cancelfn : function() {
// alert("not smart");
// needs_app_check_upload_borrowerSync = -1;
// }
// })
}
}
async function app_check_upload_borrowerTickSync(appid, resolve) {
if (typeof appid === "undefined") appid = mar.ID;
if (MAR.appnav.loanWasImportedAndNotVerified() === true) {
return;
}
let bie = await MAR.encompass.isBorrowerInEncompass(appid);
if (bie.dirty.length > 0) {
resolve(false, {});
return;
}
if (bie.new_cnt === 0) {
current.is_new_borrower = false;
resolve(true, {
new_cnt : 0
});
return;
}
current.is_new_borrower = true;
return;
// _swal({
// msg : "One of the borrowers needs to be uploaded, Would you like to upload to encompass NOW?",
// okfn : async function() {
// let uploadrv = await uploadNewBorrowerToEncompass(mar.ID, bie.new_in_app_str)
// if (uploadrv.status !== 0) {
// _swal({
// msg : uploadrv.upl.statusMsg
// });
// resolve(false, {});
// }
// else if (uploadrv.upd.status === 0) {
// resolve(true, {
// new_cnt : 0
// });
// } else if (uploadrv.upd.status < 0) {
// _swal({
// msg : uploadrv.upd.statusMsg
// });
// resolve(false, {});
// } else {
// _swal({
// msg : uploadrv.upd.rvstatus
// });
// resolve(false, {});
// }
// },
// cancelfn : function() {
// resolve(true, {
// new_cnt : bie.new_cnt
// });
// }
// })
}
let needs_app_check_synched = 1;
let needs_app_check_upload_borrowerSync = 1;
function init() {
needs_app_check_synched = 1;
needs_app_check_upload_borrowerSync = 1;
}
function registers() {
return {
needs_app_check_upload_borrowerSync : needs_app_check_upload_borrowerSync
}
}
async function checkSync() {
if (needs_app_check_synched === 1) {
let isSynchedObj = await MAR.encompass.isSynchedSync()
needs_app_check_synched = (isSynchedObj.synched === true) ? 0 : -1;
}
if (needs_app_check_synched !== 0) {
return;
}
if (needs_app_check_upload_borrowerSync === 1 || needs_app_check_upload_borrowerSync === -1) {
await app_check_upload_borrowerSync(mar.ID);
}
return registers();
}
let NOSTATUS = 0;
let LOCKED = 1;
let FAIL = 2;
let SUCCESS = 9;
let NOW = function() {
return new Date().getTime();
};
function task({ Expiry, fn, expirefn, RetryDelay}) {
let state = NOSTATUS;
let expiry = (typeof Expiry === "number") ? Expiry : -1;
let retryDelay = (typeof RetryDelay === "number") ? RetryDelay : 1000;
let _fn = fn;
let fail_time = false;
let succ_time = false;
let fire_time = false;
let _rv = {};
function resolve(status, vals) {
if (status === true) {
state = SUCCESS;
succ_time = NOW();
if (typeof vals === "object") {
_rv = vals;
}
} else {
state = FAIL;
fail_time = NOW();
if (typeof vals === "object") {
_rv = vals;
}
}
}
function fire() {
if (state === LOCKED) {
return state;
}
state = NOSTATUS;
tick();
}
function rv() {
return _rv;
}
function tick() {
if (state == NOSTATUS) {
state = LOCKED;
fire_time = NOW();
fn(resolve);
return state;
}
if (state === LOCKED) {
if ((fire_time + (30*1000)) < NOW()) {
state = NOSTATUS;
}
return state;
}
if (state === FAIL) {
if ((fail_time + (retryDelay*1000)) < NOW()) {
state = NOSTATUS;
}
}
if (state === SUCCESS) {
if (expiry > 0 && (succ_time + (expiry*1000)) < NOW()) {
if (typeof expirefn === "function") expirefn();
state = NOSTATUS;
}
}
}
return {
tick : tick,
fire : fire,
rv : rv,
getState : function() { return state; }
}
};
let test_task = task({
Expiry : 120,
RetryDelay : 5,
fn : function(resolve) {
if (NOW()%5 === 0) {
console.error(`test task FAIL @ ${NOW()}`)
resolve(false);
} else {
console.error(`test task SUCCESS @ ${NOW()}`)
resolve(true);
}
}
});
let is_synched_task = task({
Expiry : 5*60, // every 5 mins
RetryDelay : 5,
fn : function(resolve) {
(async function checkSync() {
let isSynchedObj = await MAR.encompass.isSynchedSync();
resolve(true, {
isSynched : isSynchedObj.synched
})
})();
},
expirefn : function() {
//console.error(`synched task EXPIRED @ ${NOW()}`)
}
});
let is_new_borrower_task = task({
Expiry : 5*60, // every 5 mins
RetryDelay : 5,
fn : function(resolve) {
(async function checkSync() {
let rv = await app_check_upload_borrowerTickSync(mar.ID, resolve);
})();
},
expirefn : function() {
console.error(`newborrower task EXPIRED @ ${NOW()}`)
}
});
let is_change_of_data_task = task({
Expiry : 20*60, // every 5 mins
RetryDelay : 5,
fn : function(resolve) {
(async function checkSync() {
current.borrowers = {};
for (let i=0; i < MAR.applicants.count(); i++) {
let rv = await app_check_diffs_borrower_profileSync(mar.ID, i, { deferred : true});
}
resolve(false, {})
return;
// let rv = await app_check_upload_borrowerTickSync(mar.ID, resolve);
let ob = {
applicants : []
};
for (let i=0; i < MAR.applicants.count(); i++) {
let rv = await app_check_diffs_borrower_profileTickSync(mar.ID, i);
ob.applicants.push(rv);
}
current.applicantdiffs = ob;
for (let i=0; i < MAR.applicants.count(); i++) {
let rv = ob.applicants[i];
if (rv.diffs.length > 0 && rv.dirty.length === 0) {
// not yet!
// app_check_diffs_borrower_profile_swal(mar.ID, i, rv, function(res){
//
// })
return;
}
}
resolve(true, ob);
})();
},
expirefn : function() {
// console.error(`newborrower task EXPIRED @ ${NOW()}`)
}
});
let tasks = {};
tasks.test_task = test_task;
tasks.is_synched_task = is_synched_task,
tasks.is_new_borrower_task = is_new_borrower_task;
tasks.is_change_of_data_task = is_change_of_data_task;
function interrupt() {
test_task.tick();
if (mar.WE_ARE_FROM_LOI !== true) return;
is_synched_task.tick();
if (is_synched_task.getState() !== 9) { // if not success
/**
* nothing more to see!
*/
//console.error(`synched task STATUS NOT 9 @ ${NOW()}`)
return;
}
if (is_synched_task.rv().isSynched !== true) { // if success but not synched
/**
* nothing more to see!
*/
//console.error(`synched task RV NOT SYNCHED @ ${NOW()}`,is_synched_task.rv())
return;
}
//console.error(`synched task RV IS SYNCHED @ ${NOW()}`)
is_new_borrower_task.tick();
if (is_new_borrower_task.getState() !== 9) { // if not success
/**
* nothing more to see!
*/
//console.error(`newborrower task STATUS NOT 9 @ ${NOW()}`)
return;
}
if (is_new_borrower_task.rv().new_cnt !== 0) { // if success but not synched
/**
* nothing more to see!
*/
//console.error(`newborrower task RV new_cnt not 0 @ ${NOW()}`,is_new_borrower_task.rv())
return;
}
is_change_of_data_task.tick();
if (is_change_of_data_task.getState() !== 9) return;
//console.error(`changeofdata task state ${is_change_of_data_task.getState()}`)
}
function deleted_by_encompass(type, uuid) {
if (typeof mar.answers.v2.delbyencompass !== "object") {
mar.answers.v2.delbyencompass = {};
}
if (typeof mar.answers.v2.delbyencompass[type] !== "object") {
mar.answers.v2.delbyencompass[type] = {};
}
let NOW = new Date().getTime();
mar.answers.v2.delbyencompass[type].ts = NOW;
mar.answers.v2.delbyencompass[type][uuid] = NOW;
}
function updated_by_encompass(type, uuid) {
if (typeof mar.answers.v2.updbyencompass !== "object") {
mar.answers.v2.updbyencompass = {};
}
if (typeof mar.answers.v2.updbyencompass[type] !== "object") {
mar.answers.v2.updbyencompass[type] = {};
}
let NOW = new Date().getTime();
mar.answers.v2.updbyencompass[type].ts = NOW;
mar.answers.v2.updbyencompass[type][uuid] = NOW;
}
function getCurrent() {
return current;
}
function menu_check(){
MAR.encompass.tasks.is_change_of_data_task.fire();
_swal({ msg : `
sync_problem A check on the encompass data has been scheduled - `+
`if an upload is necessary you will see thie above icon `+
` at the top of the page. Click it to proceed with synchronizing data with Encompass`});
}
function get_encompass_data_url(type, obj) {
if (type === "asset") {
if (typeof obj === "number") obj = MAR.assets.get(false, obj);
if (typeof obj !== "object") return false;
let encid = MAR.getOpt(obj, "enc_id", false);
if (typeof encid === "number") encid = `${MAR.getOpt(obj, "gid","")}/0`; /* repair some strange numeric value */
if (typeof encid !== "string") return false;
let type = MAR.getOpt(obj, "type", "");
let whose_name = MAR.getOpt(obj, "whose_name", "");
if (type === "cash") whose_name = "0";
if (type === "emd") whose_name = "0";
if (type === "gifts") whose_name = "0";
if (type === "gift") whose_name = "0";
if (type === "nprf") whose_name = "0";
if (typeof whose_name === "string") whose_name = whose_name.split(",");
if (whose_name.length === 0) return false;
let _applicant = getApplicantsNames_v2(num(whose_name[0]));
let ssn = MAR.digits(MAR.getOpt(_applicant, "sn", ""));
return {
ssn : ssn,
encid : encid
};
}
if (type === "reo") {
if (typeof obj !== "object") return false;
let encid = MAR.getOpt(obj, "uuid", false);
let whose_name = MAR.getOpt(obj, "whosname", "0");
let _applicant = getApplicantsNames_v2(num(whose_name.split(",")[0]));
let ssn = MAR.digits(MAR.getOpt(_applicant, "sn", ""));
return {
ssn : ssn,
encid : encid
};
}
if (type === "income") {
if (typeof obj !== "object") return false;
let encid = MAR.getOpt(obj, "uuid", false);
let type = MAR.getOpt(obj, "type", "");
// let whose_name = MAR.getOpt(obj, "whose_name", "");
// whose_name = "0";
// let _applicant = getApplicantsNames_v2(num(whose_name));
let aid = MAR.getOpt(obj, "aid", "0");
let _applicant = getApplicantsNames_v2(num(aid));
let ssn = MAR.digits(MAR.getOpt(_applicant, "sn", ""));
return {
ssn : ssn,
encid : encid
};
}
if (type === "pd") {
let _applicant = obj;
let ssn = MAR.digits(MAR.getOpt(_applicant, "sn", ""));
return {
ssn : ssn,
encid : ""
};
}
if (type === "addr") {
let _applicant = obj;
let ssn = MAR.digits(MAR.getOpt(_applicant, "sn", ""));
return {
ssn : ssn,
encid : ""
};
}
}
var transformations = {};
transformations.date = (function(){
function elm2enc(S) {
return `${S}`.split("T")[0]+`T00:00:00Z`;
}
function elaine(S) {
return `${S}`.split("T")[0];
}
return {
elm2enc : elm2enc,
elaine : elaine,
___id : "trans"
}
})();
transformations.address = (function(){
function elm2arr(S) {
var adr = MAR.addressFromString(S);
return [
adr.address,
adr.unit_type,
adr.unit_number,
adr.city,
adr.state,
adr.zip
];
}
function elm2enc(S) {
var adr = MAR.addressFromString(S);
return [
adr.enc.addressLine1,
adr.enc.unit_type,
adr.enc.unit_num,
adr.city,
adr.state,
adr.zip
];
}
function elaine(S) {
return S;
}
function elmid(S) {
return [
`${S}_address`,
`${S}_unit_type`,
`${S}_unit_number`,
`${S}_city`,
`${S}_state`,
`${S}_zip`
].join("|");
}
return {
elm2enc : elm2enc,
elm2arr : elm2enc,
elaine : elaine,
elmid : elmid,
___id : "trans"
}
})();
function transform(dir, trans, val) {
if (trans in transformations && typeof transformations[trans][dir] === "function") {
return transformations[trans][dir](val)
}
return val;
}
function loi_update_window(elm, type, encidObj, fieldname, fieldlabel,appid, opts) {
let $elm = $(elm);
$elm.addClass("x-enc-link");
$elm.data("encid" , encidObj.encid);
$elm.data("ssn" , encidObj.ssn);
$elm.data("enc_type" , type);
$elm.data("enc_fieldname" , fieldname);
$elm.data("enc_fieldlabel" , fieldlabel);
$elm.data("appid" , appid);
$elm.data("elmid" , $elm[0].id);
$elm.data("enc_data_type" , MAR.getOpt(opts, "type", "string"));
$elm.data("enc_transform" , MAR.getOpt(opts, "transform", ""));
$elm.css("border", "1px solid red");
mar.tmp_loi_update_window_transform = transform;
mar.tmp_loi_update_window = async function(){
let $panel2 = $(".x-clearing-encompass-panel");
mar.tmp_loi_update_enc_vals_success = -1;
if (mar.tmp_loi_update_enc_vals_checkvals() === 0) {
if ($panel2.length > 0) {
mar.tmp_loi_update_enc_vals_cnt = 1;
mar.tmp_loi_update_enc_vals_success = true;
return;
}
mar.tmp_loi_update_enc_vals_cnt = 1;
mar.tmp_loi_update_enc_vals_success = true;
swal.close();
await waitSync(500);
mar._clearfn("cleared-anyway");
return;
}
let $elms = $("#loi_ud_win .x-loi_ud_win_val");
let script = [];
let appid = false;
for (let i=0; i < $elms.length; i++) {
let $elm0 = $($elms[i]);
let elmid = $elm0.data("elmid");
let $elm = $(`#${elmid}`);
let enc_update = $elm0.data("enc_update");
if (enc_update === "N") {
continue;
}
let encid = $elm0.data("encid");
let ssn = $elm0.data("ssn");
let enc_type = $elm0.data("enc_type");
let enc_fieldname = $elm0.data("enc_fieldname");
let fieldlabel = $elm.data("enc_fieldlabel");
let enc_data_type = $elm0.data("enc_data_type");
let enc_transform = $elm0.data("enc_transform");
appid = $elm0.data("appid");
let val = $elm0.val();
let valT = transform("elm2enc", enc_transform,$elm0.val());
if (enc_data_type === "b64") {
valT = Base64.encode(valT);
}
if (enc_type === "asset") {
script.push(`applicant ${ssn}`);
script.push(`set asset ${encid} ${enc_fieldname} ${enc_data_type} ${valT}`);
}
if (enc_type === "reo") {
script.push(`applicant ${ssn}`);
script.push(`set reo ${encid} ${enc_fieldname} ${enc_data_type} ${valT}`);
}
if (enc_type === "income") {
script.push(`applicant ${ssn}`);
script.push(`set job ${encid} ${enc_fieldname} ${enc_data_type} ${valT}`);
}
if (enc_type === "pd") {
script.push(`applicant ${ssn}`);
script.push(`set borrower ${enc_fieldname} ${enc_data_type} ${valT}`);
}
if (enc_type === "res_main") {
script.push(`applicant ${ssn}`);
script.push(`set res_main ${enc_fieldname} ${enc_data_type} ${valT}`);
}
}
script.push(`save`);
// let script = [
// `applicant ${ssn}`,
// `set asset ${encid} ${enc_fieldname} ${enc_data_type} ${val}`,
// `save`
// ];
let $fb = $("#loi_ud_win_fb");
let $top = $("#loi_ud_win_top");
$top.addClass("x-hide");
$fb.html("
Preparing Upload
");
await waitSync(10);
// $fb.html(`
${script.join("\n")} `);
// await waitSync(1000);
// $(".swal-button.swal-button--send.swal-button--loading").removeClass("swal-button--loading").click(mar.tmp_loi_update_window);
// await waitSync(1000);
// return;
$fb.html("
Uploading data to Encompass
");
console.warn("app-execute-encompass-script", script);
let rv = await mar.socket.send_and_receiveSync("app-execute-encompass-script", {appid:appid, script:script.join("\n")});
console.warn("app-execute-encompass-script-rv", rv);
await waitSync(10);
$fb.html("
Done
");
await waitSync(10);
if (rv.status < 0) {
$top.removeClass("x-hide");
$fb.html(`
! ${rv.statusMsg} `);
$(".swal-button.swal-button--send.swal-button--loading").removeClass("swal-button--loading").click(mar.tmp_loi_update_window);
mar.tmp_loi_update_enc_vals_success = -2;
} else {
$fb.html(`
The value is successfully updated in encompass and also in Elaine. `);
for (let i=0; i < $elms.length; i++) {
let $elm0 = $($elms[i]);
let elmid = $elm0.data("elmid");
let $elm = $(`#${elmid}`);
let val = $elm0.val();
$elm.val(val);
}
await waitSync(2000);
mar.tmp_loi_update_enc_vals_cnt = 1;
mar.tmp_loi_update_enc_vals_success = true;
if ($panel2.length > 0) {
return;
}
swal.close();
await waitSync(500);
mar._clearfn("cleared-anyway");
}
};
mar.tmp_loi_update_enc_vals_checkvals = function() {
if (mar.tmp_loi_update_enc_disabled) {
return 0;
}
let $elms = $(".x-loi_ud_win_val");
let diffcnt = 0;
for (let i=0; i < $elms.length; i++) {
let $elm = $($elms[i]);
let val = $elm.val();
let tmpid = $elm.data("tmpid");
let enc_val = mar.tmp_loi_update_enc_vals_encvals[tmpid];
if (enc_val !== val) diffcnt++;
/**
* put the value back in the original form
*/
let elmid = $elm.data("elmid");
let $elm1 = $(`#${elmid}`);
$elm1.val(val).change();
}
let $but = $(".swal-modal .swal-button.swal-button--send");
if (diffcnt > 0) {
$but.html("Update");
} else {
$but.html("Continue");
}
return diffcnt;
}
mar.tmp_loi_update_enc_vals_encvals = {};
mar.tmp_loi_update_enc_vals_cnt = 0;
mar.tmp_loi_update_enc_disabled = false;
mar.tmp_loi_update_enc_vals = async function(fn){
if (mar.tmp_loi_update_enc_disabled) {
if (fn) fn();
return false;
}
let $panel2 = $(".x-clearing-encompass-panel");
if ($panel2.length > 0) {
$panel2.html("");
}
if (mar.tmp_loi_update_enc_vals_cnt > 0) {
mar.tmp_loi_update_enc_vals_cnt = 0; /* don't do it a 2nd time */
if (fn) fn();
return false;
}
mar.tmp_loi_update_enc_vals_encvals = {};
let h = "";
let $elms = $(".x-enc-link");
h += ``;
h += ``; // right align the popup
h += `
`;
h += `
`;
h += `
`;
h += `
`;
h += `
`;
h += `
This field is linked direct to encompass so changing this value will send the information to encompass. You must have the loan closed for this to work. `;
h += `
`;
let getLowerOrUpper = function(da, fieldname, DEF) {
let val = MAR.getOpt(da, fieldname, null);
if (val !== null) return val;
let val1 = MAR.getOpt(da, fieldname[0].toLowerCase()+fieldname.substring(1), null);
if (val1 !== null) return val1;
return DEF;
}
let geturl = function(_url) {
return new Promise(function(resolve, reject) {
$.get(_url, function(da) {
if (da.status === 0 && "obj" in da && typeof da.obj === "object") {
resolve(da.obj);
} else {
resolve(false);
}
})
});
}
let _hh = "";
for (let i=0; i < $elms.length; i++) {
let $elm = $($elms[i]);
if ($elm.is(':visible') === false) continue; /* element is not visible */
let currentvalue = $elm.val();
let startvalue = $elm.data("startvalue");
//if (`${currentvalue}`.trim() === `${startvalue}`.trim()) continue; /* nothing changed */
let _fieldname = $elm.data("enc_fieldname");
let _fieldlabel = $elm.data("enc_fieldlabel");
let _encid = $elm.data("encid");
let _ssn = $elm.data("ssn");
let _enc_type = $elm.data("enc_type");
let _enc_fieldname = $elm.data("enc_fieldname");
let _enc_fieldlabel = $elm.data("enc_fieldlabel");
let _enc_data_type = $elm.data("enc_data_type");
let _enc_transform = $elm.data("enc_transform");
let _appid = $elm.data("appid");
let _val = $elm.val().trim();
let _tval = transform("elm2enc", _enc_transform,_val);
let currentvalueT = transform("elm2enc", _enc_transform,_val);
let currentvalueS = transform("elm2arr", _enc_transform,_val);
let elmid = transform("elmid", _enc_transform,$elm[0].id);
let url = `/api/encompass/getObjectFromEncompass?appid=${_appid}&ssn=${_ssn}&type=${_enc_type}&encid=${_encid}`;
let da = await geturl(url);
let _enc_fieldnames = _enc_fieldname.split("|");
let _enc_fieldlabels = _enc_fieldlabel.split("|");
if (typeof currentvalueT !== "object") {
currentvalueT = currentvalueT.split("|");
}
if (typeof currentvalueS !== "object") {
currentvalueS = currentvalueS.split("|");
}
let _enc_data_types = _enc_data_type.split("|");
let elmids = elmid.split("|");
for (let j=0; j < _enc_fieldnames.length; j++) {
if (typeof currentvalueT[j] === "string") {
currentvalueT[j] = currentvalueT[j].trim();
}
let _tmpid = `x-tmpval-${i}-${j}`;
let enc_update = "";
let html_val = "";
if (da !== false) {
let enc_val = getLowerOrUpper(da, _enc_fieldnames[j], null);
// _h += `
Encompass data : "${enc_val}" "${currentvalueT[j]}" (${_enc_fieldnames[j]})
`;
if (enc_val !== null && `${enc_val}` === `${currentvalueT[j]}`) {
$elm.data("enc_update", "N");
enc_update = "N";
mar.tmp_loi_update_enc_vals_encvals[_tmpid] = `${enc_val}`;
} else if (enc_val === null && currentvalueT[j].trim().length === 0) {
$elm.data("enc_update", "N");
enc_update = "N";
mar.tmp_loi_update_enc_vals_encvals[_tmpid] = "";
} else if (enc_val === null) {
$elm.data("enc_update", "Y");
enc_update = "Y";
mar.tmp_loi_update_enc_vals_encvals[_tmpid] = "";
} else {
$elm.data("enc_update", "Y");
enc_update = "Y";
html_val = `
Encompass data : "${enc_val}"
`;
mar.tmp_loi_update_enc_vals_encvals[_tmpid] = `${enc_val}`;
}
}
let _h = "";
let _del = `
delete `;
_h += `
`;
_h += `
${_enc_fieldlabels[j]} `;
_h += `
${_del}
`;
_h += `
`;
_h += html_val;
if (enc_update === "N") {
_h = "";
}
_hh += _h;
}
}
if (_hh === "") {
let h = "";
h += ``;
h += ``; // right align the popup
h += `
`;
h += `
`;
h += `
`;
h += `
`;
h += `
`;
h += `
None of the Encompass Linked fields have changed. You can go ahead and clear this document witout needing to upload to encompass. `;
h += `
`;
$panel2.html(h);
if (fn) fn();
return false;
}
h += _hh;
h += `
`;
// h += `
Save
`;
h += `
`;
h += `
`;
h += `
`;
h += `
`;
if ($panel2.length > 0) {
h += `
Update `;
$panel2.html(h);
if (fn) fn();
return true;
}
elaineui.swalprompt({
// title : "Encompass Linked field",
txt : h,
ok : "Update",
okfn : function(opts) {
mar.tmp_loi_update_window();
opts.preventclose = true;
},
cancel : "back",
cls : "",
cancelfn : function() {
mar.tmp_loi_update_enc_vals_cnt = 1;
mar._clearfn("cleared");
},
opts : {
closeOnClickOutside : false,
closeOnEsc : false
},
reverse : true
});
if (fn) fn();
return true;
}
//$elm.prop("readonly", true);
//$elm.on("click",);
}
return {
swal : _swal,
deleted_by_encompass : deleted_by_encompass,
updated_by_encompass : updated_by_encompass,
//
get_encompass_data_url : get_encompass_data_url,
loi_update_window : loi_update_window,
//
init : init,
interrupt : interrupt,
waitSync : waitSync,
tasks : tasks,
current : getCurrent,
menu_check : menu_check,
checkSync : checkSync,
//
are_there_changes : are_there_changes,
lomenu_fn : ui_lomenu_fn,
ui_lomenu_reload_fn : ui_lomenu_reload_fn,
ui_lomenu_click : ui_lomenu_click,
ui_lomenu_continue : ui_lomenu_continue,
ui_onebutton : ui_onebutton,
ui_dualbutton : ui_dualbutton,
//
isSynchedSync : isSynchedSync, // are we synced
isBorrowerInEncompass : isBorrowerInEncompass, // is this borrower in encompass
app_check_upload_borrowerSync : app_check_upload_borrowerSync,
app_check_upload_borrowerTickSync : app_check_upload_borrowerTickSync,
app_check_diffs_assetsSync : app_check_diffs_assetsSync,
app_check_diffs_borrower_profileSync : app_check_diffs_borrower_profileSync,
app_check_diffs_borrower_profileTickSync : app_check_diffs_borrower_profileTickSync,
app_check_diffs_borrower_profile_swal : app_check_diffs_borrower_profile_swal,
uploadNewBorrowerToEncompassTfSync : uploadNewBorrowerToEncompassTfSync,
//
___id : "encompass object"
}
})();
/**
* cf
* @namespace MAR.realtor
*/
var realtorObj = (function(){
function getRealtor(){
let have_own_realtor = getScenario_data("have_own_realtor","N");
if (have_own_realtor !== "Y") return {};
return {
name : getName().str,
tel : getScenario_data("realtor_phone"),
email : getScenario_data("realtor_email"),
office : getScenario_data("realtor_office")
}
}
function getName(NA) {
if (arguments.length == 0) {
NA = getScenario_data("realtor_name","");
}
let retval = {
fn : "",
ln : "",
str : ""
}
if (NA.trim().length == 0) return retval;
let _NA = NA.split("|");
if (_NA.length === 1 && NA.trim().indexOf(" ") > -1) {
let __NA = NA.split(" ");
_NA[0] = __NA.shift();
_NA[1] = __NA.join(" ");
}
retval.fn = _NA[0];
retval.ln = (_NA.length > 1) ? _NA[1] : "";
retval.str = [retval.fn,retval.ln].join(" ");
return retval;
}
function setName(A,B) { // obj , or name or fn , ln
let NA = false;
if (arguments.length == 2) {
NA = [A,B].join("|");
}
if (arguments.length == 1 && typeof A === "string") {
if (A.indexOf("|") > -1) {
NA = A;
} else {
let _NA = A.split(" ");
NA = _NA.shift();
if (_NA.length > 0) {
NA += "|";
NA += _NA.join(" ");
}
}
}
if (arguments.length == 1 && typeof A === "object") {
let _NA = [];
if ("fn" in A) _NA.push(A.fn);
if ("ln" in A) _NA.push(A.ln);
NA = _NA.join("|");
}
if (NA !== false) {
setScenario_data("realtor_name",NA);
}
}
function getPermissions() {
return {
share_calcs : getScenario_data("realtor_permission_loan_calcs_and_docs",""),
share_docs : getScenario_data("realtor_permission_loan_calcs_and_docs",""),
share_underwriting : getScenario_data("realtor_permission_direct_underwriting_report",""),
share_appraisal : getScenario_data("realtor_permission_appraisal_information","")
}
}
function set(k,v) {
setOpt(mar.answers, `_cf.${k}`, v)
}
return {
setName : setName,
getName : getName,
getRealtor : getRealtor,
getPermissions : getPermissions,
______id : "custom fields"
}
})()
/**
* cf
* @namespace MAR.declarations
*/
var customfieldsObj = (function(){
function set(k,v) {
// if diff
// then activity object litte brown mouse
if (setOpt(mar.answers, `_cf.${k}`, v)) {
MAR.activity_log.mod("customfield", `_cf.${k}`);
}
}
return {
set : set, // set a value in cutomfields
______id : "custom fields"
}
})()
/**
* application
* @namespace MAR.app
*/
var applicationObj = (function(){
function purchase_to_refi(index_of_subject_property) {
/**
* set the indef of the subject property to reo index 0 if undefined
*/
if (typeof index_of_subject_property === "undefined") index_of_subject_property = 0;
/**
* set the loan type
*/
mar.answers.loan_type = "refinance";
mar.answers.v2.loan_type = "refinance";
mar.answers.v2.scenario.loan_type = "refinance";
/**
* set the subject property
*/
if (typeof mar.answers.v2.reo[index_of_subject_property] !== "undefined") {
mar.answers.v2.reo[index_of_subject_property].is_subject_property = "Y";
}
/**
* set the subject property from REO
*/
if (typeof mar.answers.v2.reo[index_of_subject_property] !== "undefined") {
MAR.reo.makePropertyTheSubjectUnverified();
}
}
function refi_to_purchase() {
mar.answers.loan_type = "purchase";
mar.answers.v2.loan_type = "purchase";
mar.answers.v2.scenario.loan_type = "purchase";
/**
* set that there is no subject property
*/
let sp = MAR.reo.getSubjectProperty();
if (sp !== false) sp.data.is_subject_property = "N";
/**
* remove the subject property
*/
mar.answers.v2.scenario.property_details = {}
}
function update_borrower(answers, applicantnum, {FN, MN, LN, GE, PH, DB, EM, MS, SR, DR}) {
if ("v2" in answers == false) return; // incomplete answers string
if ("applicants" in answers.v2 == false) return; // no applicants object
if (applicantnum >= answers.v2.applicants.length) return; // no borrower in array
if ("bucketid" in answers.v2.applicants[applicantnum] == false) return; // no borrower bucket
let bucketid = answers.v2.applicants[applicantnum].bucketid
let bucket = answers.v2.buckets[bucketid];
if (FN) bucket.fn = FN;
if (MN) bucket.mn = MN;
if (LN) bucket.ln = LN;
if (GE) bucket.ge = GE;
if (PH) bucket.ph = PH;
if (DB) bucket.db = DB;
if (EM) bucket.em = EM;
if (MS) bucket.ms = MS;
if (SR) bucket.sr = SR;
if (DR) bucket.dr = DR;
MAR.activity_log.mod("borrower", bucket.sn);
// sn : "",
// em : "",
// ms : "",
// de : 0,
// age1 : 0,
// age2 : 0,
// age3 : 0,
// age4 : 0,
// age5 : 0,
// age6 : 0,
// h1 : "",
// h2 : "",
// h2s1 : "",
// h2s1_txt : "",
// h3 : "",
// h31_txt : "",
// h3s1 : "",
// h3s1_txt : "",
// h3s2 : "",
// h3s2_txt : "",
// h4 : ""
}
function empty(V) {
if (!V) return true;
if (typeof V == "string" && V.trim().length == 0) return true;
return false;
}
function getBorrower(N) {
}
function nu(S) {
if (typeof S == "undefined") return false;
return true;
}
function setBorrowerCustom(answers, applicantnum, KV) {
if ("v2" in answers == false) return; // incomplete answers string
if ("applicants" in answers.v2 == false) answers.v2.applicants = [];
while (applicantnum >= answers.v2.applicants.length) answers.v2.applicants.push({}); // make aplicants
if ("bucketid" in answers.v2.applicants[applicantnum] == false) {
answers.v2.applicants[applicantnum].bucketid = `/applicants/data/${applicantnum}/${uuidv4()}`
}
if ("buckets" in answers.v2 == false) answers.v2.buckets = {};
let ap = answers.v2.applicants[applicantnum];
let bucketid = answers.v2.applicants[applicantnum].bucketid
if (bucketid in answers.v2.buckets == false) answers.v2.buckets[bucketid] = {};
let bucket = answers.v2.buckets[bucketid];
for (let x in KV) {
bucket[x] = KV[x];
}
}
function setBorrower(answers, applicantnum, {FN, MN, LN, GE, PH, DB, EM, MS, SN, ED, DE, TY, AGE1, AGE2, AGE3, AGE4, AGE5, AGE6,H1,H2,H3,H4,H2S1,H2S1T,H3S1,H3S1T,H3S2,H3S2T,SR,DR,DC}, dbg) {
let updated = false;
if (typeof dbg !== "object") dbg = [];
if ("v2" in answers == false) return updated; // incomplete answers string
if ("applicants" in answers.v2 == false) answers.v2.applicants = [];
while (applicantnum >= answers.v2.applicants.length) answers.v2.applicants.push({}); // make aplicants
if ("bucketid" in answers.v2.applicants[applicantnum] == false) {
answers.v2.applicants[applicantnum].bucketid = `/applicants/data/${applicantnum}/${uuidv4()}`
}
if ("buckets" in answers.v2 == false) answers.v2.buckets = {};
let ap = answers.v2.applicants[applicantnum];
let bucketid = answers.v2.applicants[applicantnum].bucketid
if (bucketid in answers.v2.buckets == false) answers.v2.buckets[bucketid] = {};
let bucket = answers.v2.buckets[bucketid];
let bucket_original = JSON.stringify(bucket);
bucket.bucketid = bucketid;
bucket.uuid = bucketid.split("/").pop()
if (nu(FN)) bucket.fn = FN;
if (nu(MN)) bucket.mn = MN;
if (nu(LN)) bucket.ln = LN;
if (nu(GE)) bucket.ge = GE;
if (nu(PH)) bucket.ph = PH;
if (nu(DB)) bucket.db = DB;
if (nu(EM)) bucket.em = EM;
if (nu(MS)) bucket.ms = MS;
if (nu(SR)) bucket.sr = SR;
if (nu(DR)) bucket.dr = DR;
if (nu(DC)) bucket.dc = DC;
if (nu(SN)) bucket.sn = SN;
if (nu(ED)) bucket.ed = ED;
if (nu(TY)) bucket.ty = TY;
if (nu(DE)) bucket.de = DE;
if (nu(AGE1)) bucket.age1 = AGE1;
if (nu(AGE2)) bucket.age2 = AGE2;
if (nu(AGE3)) bucket.age3 = AGE3
if (nu(AGE4)) bucket.age4 = AGE4;
if (nu(AGE5)) bucket.age5 = AGE5;
if (nu(AGE6)) bucket.age6 = AGE6;
if (nu(H1)) bucket.h1 = H1;
if (nu(H2)) bucket.h2 = H2;
if (nu(H2S1)) bucket.h2s1 = H2S1;
if (nu(H2S1T)) bucket.h2s1t = H2S1T;
if (nu(H3)) bucket.h3 = H3;
if (nu(H3S1)) bucket.h3s1 = H3S1;
if (nu(H3S1T)) bucket.h3s1t = H3S1T;
if (nu(H3S2)) bucket.h3s2 = H3S2;
if (nu(H3S2T)) bucket.h3s2t = H3S2T;
if (nu(H4)) bucket.h4 = H4;
let bucket_final = JSON.stringify(bucket);
if (bucket_original !== bucket_final) { dbg.push("UPDATED SB 1"); updated = true;}
if (FN) {
if (applicantnum == 0) {
if (setScenario_data("applicant1_name",FN)) { dbg.push("UPDATED SB 2"); updated = true;}
}
if (applicantnum == 1) {
if (setScenario_data("applicant2_name",FN)) { dbg.push("UPDATED SB 3"); updated = true;}
if (setScenario_data("is_there_a_second_borrower","Y")) { dbg.push("UPDATED SB 4"); updated = true;}
}
if (applicantnum == 2) {
if (setScenario_data("applicant3_name",FN)) { dbg.push("UPDATED SB 1"); updated = true;}
if (setScenario_data("is_there_a_third_borrower","Y")) { dbg.push("UPDATED SB 5"); updated = true;}
}
if (applicantnum > 2) {
if (setScenario_data(`applicant${(applicantnum+1)}_name`,FN)) { dbg.push("UPDATED SB 6"); updated = true;}
if (setScenario_data(`is_there_a_${MAR.th(applicantnum+1)}_borrower`,"Y")) { dbg.push("UPDATED SB 7"); updated = true;}
}
}
if (updated) {
MAR.activity_log.mod("borrower", bucket.sn);
}
return updated;
}
function setBorrowerVerification(N, VAL) {
let applicantNum = (N+1);
setScenario_data("scenario_applicant"+applicantNum+"_verification",VAL);
}
function getBorrowerVerification(N) {
let applicantNum = (N+1);
return getScenario_data("scenario_applicant"+applicantNum+"_verification","");
}
function setCitizenship(N, {USC, GCH, VISA, CNTRY}) {
let applicantNum = (N+1);
let updated = false;
if (USC && setScenario_data("scenario_applicant"+applicantNum+"_usc",USC)) updated = true;
if (GCH && setScenario_data("scenario_applicant"+applicantNum+"_gch",GCH)) updated = true;
if (VISA && setScenario_data("scenario_applicant"+applicantNum+"_visa_type",VISA)) updated = true;
if (CNTRY && setScenario_data("scenario_applicant"+applicantNum+"_cntry",CNTRY)) updated = true;
if (USC && setScenario_data("__scenario_legalstatus_"+N+"_passed","Y")) updated = true;
if (updated) {
MAR.activity_log.mod("citizenship", N);
}
return updated;
}
function setVeteranFromEncompass(N, {IS_VA_ACTIVE, IS_VA_ACTIVE_ED}) {
let applicantNum = (N+1);
let updated = false;
if (typeof IS_VA_ACTIVE === "string") {
if (IS_VA_ACTIVE === "") {
if (setScenario_data("scenario_applicant"+applicantNum+"_served","N")) updated = true;
if (setScenario_data("scenario_applicant"+applicantNum+"_served_in_us_forces","N")) updated = true;
if (setScenario_data("va_active"+applicantNum,"N")) updated = true;
if (setScenario_data("va_active_ed"+applicantNum,"")) updated = true;
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
}
if (IS_VA_ACTIVE === "A") {
if (setScenario_data("scenario_applicant"+applicantNum+"_served","Y")) updated = true;
if (setScenario_data("scenario_applicant"+applicantNum+"_served_in_us_forces","Y")) updated = true;
if (setScenario_data("va_active"+applicantNum,"A")) updated = true;
if (setScenario_data("va_active_ed"+applicantNum,"")) updated = true;
if (typeof IS_VA_ACTIVE_ED === "string") {
if (setScenario_data("va_active_ed"+applicantNum,IS_VA_ACTIVE_ED)) updated = true;
}
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
}
if (IS_VA_ACTIVE === "D") {
if (setScenario_data("scenario_applicant"+applicantNum+"_served","Y")) updated = true;
if (setScenario_data("scenario_applicant"+applicantNum+"_served_in_us_forces","Y")) updated = true;
if (setScenario_data("va_active"+applicantNum,"D")) updated = true;
if (setScenario_data("va_active_ed"+applicantNum,"")) updated = true;
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
}
if (IS_VA_ACTIVE === "R") {
if (setScenario_data("scenario_applicant"+applicantNum+"_served","Y")) updated = true;
if (setScenario_data("scenario_applicant"+applicantNum+"_served_in_us_forces","Y")) updated = true;
if (setScenario_data("va_active"+applicantNum,"R")) updated = true;
if (setScenario_data("va_active_ed"+applicantNum,"")) updated = true;
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
}
if (IS_VA_ACTIVE === "S") {
if (setScenario_data("scenario_applicant"+applicantNum+"_served","Y")) updated = true;
if (setScenario_data("scenario_applicant"+applicantNum+"_served_in_us_forces","Y")) updated = true;
if (setScenario_data("va_active"+applicantNum,"S")) updated = true;
if (setScenario_data("va_active_ed"+applicantNum,"")) updated = true;
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
}
}
return updated;
}
function setVeteran(N, {served, eligible, employment, firsttime, disabled, disabled_percentage, coe, nofee}) {
let applicantNum = (N+1);
let updated = false;
if (served && setScenario_data("scenario_applicant"+applicantNum+"_served",served)) updated = true;
if (served && setScenario_data("has_applicant"+applicantNum+"_served_in_us_forces",eligible)) updated = true;
if (served && setScenario_data("va_employment"+applicantNum+"",employment)) updated = true;
if (served && setScenario_data("vafirst_time_use"+applicantNum+"",firsttime)) updated = true;
if (served && setScenario_data("va_disabled"+applicantNum+"",disabled)) updated = true;
if (served && setScenario_data("va_disabled"+applicantNum+"_percentage",disabled_percentage)) updated = true;
if (served && setScenario_data("va_coe"+applicantNum+"",coe)) updated = true;
if (nofee && setScenario_data("va_nofee"+applicantNum+"",nofee)) updated = true;
if (setScenario_data("__scenario_veteran_"+N+"_passed","Y")) updated = true;
if (updated) {
MAR.activity_log.mod("veteran", N);
}
}
// here I am little brown mouse
function setSSN(N , V) {
setBorrower(mar.answers, N, { SN : V});
}
function setTimeFrame(S) {
// if field 11 is TDB or blank then not under contact
// field 763 has a date , work it out
if (S === false) {
setScenario_data("visited_timeframe","");
setScenario_data("visited_timeframe","N");
setScenario_data("__scenario_timeframe_passed","N");
return;
}
if (!S || S === "") S = "one_month";
setScenario_data("visited_timeframe","Y");
setScenario_data("loan_type_purchase_options",S);
setScenario_data("__scenario_timeframe_passed","Y");
}
function setCreditScore(N,V) {
if (empty(V)) return;
setScenario_data("applicant"+(N+1)+"_cscore",V);
setScenario_data("__scenario_creditscore_"+N+"_passed","Y");
MAR.setLowestCreditScore(mar.answers);
}
function setCreditReferenceNumber(N,NUM) {
if (NUM === false) {
setScenario_data("applicant"+(N+1)+"_cscore_ref","");
} else {
setScenario_data("applicant"+(N+1)+"_cscore_ref",NUM);
}
}
function setCreditReferenceNumberEncompass(N,NUM) {
if (NUM === false) {
setScenario_data("applicant"+(N+1)+"_cscore_ref_enc","");
} else {
setScenario_data("applicant"+(N+1)+"_cscore_ref_enc",NUM);
}
}
function getCreditReferenceNumber(N) {
return getScenario_data("applicant"+(N+1)+"_cscore_ref","");
}
function getHousingBudget(N) { // returns ```,.stable (bool),.same (bool),.enough (bool),.warn (bool)```,,Where warn is *true* when **either** of the answers if *N*
let applicantNum = (N+1);
let retval = {};
retval.same = getScenario_data("applicant"+applicantNum+"_samelineofwork","");
retval.stable = getScenario_data("applicant"+applicantNum+"_stableincome","");
retval.enough = getScenario_data("applicant"+applicantNum+"_enoughincome","");
retval.warn = (retval.same === "N" || retval.stable === "N" || retval.enough === "N");
return retval;
}
function setHousingBudget(N,same,stable,enough) {
let applicantNum = (N+1);
setScenario_data("applicant"+applicantNum+"_samelineofwork",same);
setScenario_data("applicant"+applicantNum+"_stableincome",stable);
setScenario_data("applicant"+applicantNum+"_enoughincome",enough);
setScenario_data("__scenario_housingbudget_"+N+"_passed","Y");
}
function setHousingBudgetElement(N,key, val) {
let applicantNum = (N+1);
if (key === "same") setScenario_data("applicant"+applicantNum+"_samelineofwork",val);
if (key === "stable") setScenario_data("applicant"+applicantNum+"_stableincome",val);
if (key === "enough") setScenario_data("applicant"+applicantNum+"_enoughincome",val);
if (key === "high") setScenario_data("goals_target_budget_low",val);
if (key === "low") setScenario_data("goals_target_budget_high",val);
}
function setFTHB(N,{ owned,otype,ohow,owns}) {
let applicantNum = (N+1);
let updated = false;
if (owned && setScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years",owned)) updated = true;
if (typeof otype !== "undefined") {
if (otype.toLowerCase().indexOf("prima") > -1) otype = "1";
if (otype.toLowerCase().indexOf("second") > -1) otype = "2";
if (otype.toLowerCase().indexOf("invest") > -1) otype = "D";
if (otype && setScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_type",otype)) updated = true;
}
if (typeof ohow !== "undefined") {
if (ohow === "Sole") ohow = "01";
if (ohow === "JointWithSpouse") ohow = "25";
if (ohow === "JointWithOtherThanSpouse") ohow = "26";
if (ohow && setScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_how",ohow)) updated = true;
}
if (owns && setScenario_data("does_applicant"+applicantNum+"_own_property",owns)) updated = true;
if (setScenario_data("__scenario_pastproperty_"+N+"_passed","Y")) updated = true;
return updated;
}
function setLocation(loc) {
setScenario_data("property_county",loc);
setScenario_data("__scenario_location_passed","Y");
}
function setProperty(prop) {
setScenario_data("property_details",prop);
setScenario_data("__scenario_location_passed","Y");
}
function setPropertyData(K,V) {
if ("property_details" in mar.answers.v2.scenario === false) {
setScenario_data("property_details",{});
}
let rv_changed = (`${mar.answers.v2.scenario.property_details[K]}` !== `${V}`);
mar.answers.v2.scenario.property_details[K] = V;
return rv_changed;
}
function getProperty(prop, def) {
let obj = getScenario_data("property_details",{});
if (typeof prop === "string") {
return MAR.getOpt(obj, prop, def);
}
return obj;
}
function isRefi() {
if (getScenario_data("loan_type" ,"purchase") === "purchase") return false;
return true;
}
function isPurchase() {
if (getScenario_data("loan_type" ,"purchase") === "purchase") return true;
return false;
}
function is_nodoc() {
if (getScenario_data("is_nodoc" ,"") === "Y") return true;
return false;
}
function is_dscr() {
if (getScenario_data("is_nodoc" ,"") === "Y") return true;
return false;
}
function setOccupancy(loc) {
setScenario_data("occupancy_type",loc);
setScenario_data("__scenario_occupancy_passed","Y");
if (isRefi()) {
let applicantNum = "1";
setScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years","Y");
setScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_type",loc);
setScenario_data("does_applicant"+applicantNum+"_own_property","Y");
}
}
function setPropertyType(property_type) {
if (property_type.indexOf("|") > -1) {
setScenario_data("timeframe_other",property_type.split("|")[1]);
setScenario_data("property_type_other",property_type.split("|")[1]);
property_type = property_type.split("|")[0];
}
setScenario_data("property_type",property_type);
// setScenario_data("property_type_other",property_type_other);
// setScenario_data("monthly_rent",monthly_rent);
setScenario_data("__scenario_property_passed","Y");
}
function update_encompass(answers, applicantnum, {milestones}) {
if ("__db" in answers == false) answers.__db = {};
answers.__db.encompass = {
milestones
}
}
function Y() {
return MAR.getOpt(mar.answers, "Y", ""); // 21
}
function M() {
return MAR.getOpt(mar.answers, "M", ""); // 9
}
function TP() {
return MAR.getOpt(mar.answers, "TP", ""); // _TP.21.9
}
return {
update_borrower : update_borrower,
update_encompass : update_encompass,
/**
* Year and month
*/
Y : Y,
M : M,
TP : TP,
/**
* set things
*/
setTimeFrame : setTimeFrame, // timeframe timeframe
setCreditScore : setCreditScore, // credit score N score
setCreditReferenceNumber : setCreditReferenceNumber, // reference number N ref num/false
setCreditReferenceNumberEncompass : setCreditReferenceNumberEncompass, // set the encompass c ref num
getCreditReferenceNumber : getCreditReferenceNumber, // ref num N
setHousingBudget : setHousingBudget, // housing budget N same,stable,enough
setHousingBudgetElement : setHousingBudgetElement,
getHousingBudget : getHousingBudget, // housing budget N same,stable,enough
setFTHB : setFTHB, // FTHB N owned,otype,ohow,owns
setCitizenship : setCitizenship,
setBorrowerVerification : setBorrowerVerification,
getBorrowerVerification : getBorrowerVerification,
setVeteran : setVeteran,
setVeteranFromEncompass : setVeteranFromEncompass,
setBorrower : setBorrower,
setBorrowerCustom : setBorrowerCustom,
setSSN : setSSN,
setLocation : setLocation,
getProperty : getProperty,
setProperty : setProperty,
setPropertyData : setPropertyData,
setOccupancy : setOccupancy,
setPropertyType : setPropertyType,
/**
* get things
*/
isPurchase : isPurchase,
is_purchase : isPurchase,
isRefi : isRefi,
is_refi : isRefi,
is_nodoc : is_nodoc,
is_dscr : is_dscr,
/**
* refi purchase switch
*/
refi_to_purchase : refi_to_purchase,
purchase_to_refi : purchase_to_refi,
/**
* end
*/
____id : "application object"
}
})()
/**
* applicants
* @namespace applicants
*/
var applicantsObj = (function(){
function count() {
let _scenario = getScenario_v2();
let _names = getApplicantsNames_v2();
let _applicantcount = _names.length;
return _applicantcount;
}
function getNames() {
let _scenario = getScenario_v2();
let _names = getApplicantsNames_v2();
return _names;
}
function getSSN(n = false) {
let _names = getApplicantsNames_v2();
if (n === false) {
let rv = [];
for (let i=0; i < _names.length; i++) {
let sn = MAR.getOpt(_names[i], "sn", false);
if (sn === false) {
rv.push(false);
} else {
rv.push(MAR.digits(sn));
}
}
return rv;
}
let sn = MAR.getOpt(_names[n], "sn", false);
if (sn !== false) {
return MAR.digits(sn);
}
return false;
}
function getBySSN(ssn) {
let _names = getApplicantsNames_v2();
for (let i=0; i < _names.length; i++) {
let sn = MAR.getOpt(_names[i], "sn", false);
if (sn === false) continue;
if (MAR.digits(ssn) === MAR.digits(sn)) {
return i;
}
}
return false;
}
let numberedVars_state = [
"_page_creditscore.2_verified"
]
let numberedVars_data = [
"has_applicant(9)_owned_property_in_last_3_years",
"has_applicant(9)_owned_property_in_last_3_years_type",
"has_applicant(9)_owned_property_in_last_3_years_how",
"does_applicant(9)_own_property",
//
"scenario_applicant(9)_usc",
"scenario_applicant(9)_gch",
"scenario_applicant(9)_visa_type",
"scenario_applicant(9)_cntry",
//
"applicant_(9)_name",
//
"applicant(9)_cscore",
//
"applicant(9)_samelineofwork",
"applicant(9)_stableincome",
"applicant(9)_enoughincome",
//
"scenario_applicant(9)_served",
"has_applicant(9)_served_in_us_forces",
"va_employment(9)",
"vafirst_time_use(9)",
"va_disabled(9)",
"va_disabled(9)_percentage",
"va_coe(9)",
"va_nofee(9)",
//
"__income_passed_(9)"
]
function clear(TO) {
setScenario_data("__xx9","Y");
if (TO == 0) {
}
if (TO == 1) {
setScenario_data("applicant2_name","");
setScenario_data("second_applicant","");
setScenario_data("is_there_a_second_borrower","N");
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
if (x.startsWith("__scenario") && x.indexOf("_2_") > -1) {
setScenario_data(x , "");
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace("(9)","2") , "");
}
}
if (TO == 2) {
setScenario_data("applicant3_name","");
setScenario_data("third_applicant","");
setScenario_data("is_there_a_third_borrower","N");
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
if (x.startsWith("__scenario") && x.indexOf("_3_") > -1) {
setScenario_data(x , "");
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace("(9)","3") , "");
}
}
if (TO > 2) {
let NN = num(TO)+1;
setScenario_data(`applicant${NN}_name`,``);
setScenario_data(`${MAR.th(NN)}_applicant`,``);
setScenario_data(`is_there_a_${MAR.th(NN)}_borrower`,`N`);
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
if (x.startsWith(`__scenario`) && x.indexOf(`_${NN}_`) > -1) {
setScenario_data(x , ``);
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace(`(9)`,`${NN}`) , ``);
}
}
}
function shuffle(_TO) {
for (let i=_TO; i < (MAR.MAXBORROWERS-1); i++) {
let TO = i;
let NN = num(TO)+1;
let NNN = num(TO)+2;
let NNd = MAR.th(NN);
let NNNd = MAR.th(NNN);
setScenario_data(`applicant${NN}_name` , getScenario_data(`applicant${NNN}_name`,``) );
setScenario_data(`applicant${NNN}_name`,``);
setScenario_data(`${NNd}_applicant` , getScenario_data(`${NNNd}_applicant`,``) );
setScenario_data(`${NNNd}_applicant`,``);
setScenario_data(`is_there_a_${NNd}_borrower` , getScenario_data(`is_there_a_${NNNd}_borrower`,``) );
setScenario_data(`is_there_a_${NNNd}_borrower`,`N`);
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
// `__scenario_pastproperty_2_passed`,
if (x.startsWith(`__scenario`) && x.indexOf(`_${NN}_`) > -1) {
setScenario_data(x , getScenario_data(x.replace(`_${NN}_`,`_${NNN}_`),``) );
setScenario_data(x.replace(`_${NN}_`,`_${NNN}_`) , ``);
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace(`(9)`,`${NN}`) , getScenario_data(nv.replace(`(9)`,`${NNN}`),``) );
setScenario_data(nv.replace(`(9)`,`${NNN}`) , ``);
}
}
clear(MAR.MAXBORROWERS-1)
return;
if (TO == 0) { // applicant 1 to 2
setScenario_data("applicant1_name" , getScenario_data("applicant2_name","") );
setScenario_data("applicant2_name","");
setScenario_data("second_applicant","");
setScenario_data("is_there_a_second_borrower","");
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
// "__scenario_pastproperty_2_passed",
if (x.startsWith("__scenario") && x.indexOf("_1_") > -1) {
setScenario_data(x , getScenario_data(x.replace("_1_","_2_"),"") );
setScenario_data(x.replace("_1_","_2_") , "");
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace("(9)","1") , getScenario_data(nv.replace("(9)","2"),"") );
setScenario_data(nv.replace("(9)","2") , "");
}
}
if (TO == 1) { //applicant 3 to 2
setScenario_data("applicant2_name" , getScenario_data("applicant3_name","") );
setScenario_data("applicant3_name","");
setScenario_data("second_applicant" , getScenario_data("third_applicant","") );
setScenario_data("third_applicant","");
setScenario_data("is_there_a_second_borrower" , getScenario_data("is_there_a_third_borrower","") );
setScenario_data("is_there_a_third_borrower","N");
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
// "__scenario_pastproperty_2_passed",
if (x.startsWith("__scenario") && x.indexOf("_2_") > -1) {
setScenario_data(x , getScenario_data(x.replace("_2_","_3_"),"") );
setScenario_data(x.replace("_2_","_3_") , "");
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace("(9)","2") , getScenario_data(nv.replace("(9)","3"),"") );
setScenario_data(nv.replace("(9)","3") , "");
}
}
if (TO > 1) { //applicant (n) to (n-1)
let NN = num(TO)+1;
let NNN = num(TO)+2;
let NNd = MAR.th(NN);
let NNNd = MAR.th(NNN);
setScenario_data(`applicant${NN}_name` , getScenario_data(`applicant${NNN}_name`,``) );
setScenario_data(`applicant${NNN}_name`,``);
setScenario_data(`${NNd}_applicant` , getScenario_data(`${NNNd}_applicant`,``) );
setScenario_data(`${NNNd}_applicant`,``);
setScenario_data(`is_there_a_${NNd}_borrower` , getScenario_data(`is_there_a_${NNNd}_borrower`,``) );
setScenario_data(`is_there_a_${NNNd}_borrower`,`N`);
let _scen = mar.answers.v2.scenario;
for (let x in _scen) {
// `__scenario_pastproperty_2_passed`,
if (x.startsWith(`__scenario`) && x.indexOf(`_${NN}_`) > -1) {
setScenario_data(x , getScenario_data(x.replace(`_${NN}_`,`_${NNN}_`),``) );
setScenario_data(x.replace(`_${NN}_`,`_${NNN}_`) , ``);
}
}
for (let i=0; i < numberedVars_data.length; i++) {
let nv = numberedVars_data[i]
setScenario_data(nv.replace(`(9)`,`${NN}`) , getScenario_data(nv.replace(`(9)`,`${NNN}`),``) );
setScenario_data(nv.replace(`(9)`,`${NNN}`) , ``);
}
}
}
function incrementNextApplicantCounter() {
let current_max_number = getScenario_data("max_applicant_number",2);
current_max_number = num(current_max_number);
if (current_max_number < 2) current_max_number = 2;
current_max_number++;
setScenario_data("max_applicant_number",current_max_number);
return current_max_number;
}
function getId(n) {
if (typeof n === "string" && n.startsWith("_")) return num(n.substring(1));
if (typeof n === "string" && n.startsWith("-")) return 0;
let counters = getScenario_data("applicant_counters","0,1,2,3,4,5,6,7,8").split(",");
return counters.indexOf(`${n}`);
}
function getVid(n) {
if (typeof n === "string" && n.startsWith("-")) n = 0;
let counters = getScenario_data("applicant_counters","0,1,2,3,4,5,6,7,8").split(",");
if (n < 0 || n > (counters.length+1)) {
return num(counters[0])
}
return num(counters[n])
}
function removeApplicantCounter(n) {
let counters = getScenario_data("applicant_counters","0,1,2,3,4,5,6,7,8").split(",");
counters[n] = null;
counters = counters.filter(function(item) {
return item !== null
})
let next_number = incrementNextApplicantCounter();
counters.push(next_number);
setScenario_data("applicant_counters", counters.join(","));
}
function clear_scenario_passed(max) {
let scen = mar.answers.v2.scenario;
for (let x in scen) {
if (x.endsWith(`_passed`)) {
let borrower = x.slice(-8,-7);
if (num(borrower) > max) {
scen[x] = ``;
}
}
}
}
function remove(n) {
let v2 = mar.answers.v2;
if (n == 0 && v2.applicants.length > 1) {
let shuffle_down_higher_borrowers = (v2.applicants.length > 1);
v2.applicants[0] = null;
v2.applicants = v2.applicants.filter(function(item) {
return item !== null
})
// income
v2.income[0] = null;
v2.income = v2.income.filter(function(item) {
return item !== null
})
// assets
v2.assets.items = v2.assets.items.filter(function(item) {
if (item.whose_name == "0") return false;
if (item.whose_name == "0,99") return false;
if (item.whose_name.indexOf("0") > -1) {
if (item.whose_name.indexOf("99") < 0) {
item.whose_name = item.whose_name.replace(/0/g,"99")
} else {
litem.whose_name = item.whose_name.split(",").filter(function(itm) { return itm != "0"; }).join(",");
}
}
return true;
})
// liabilities
v2.liabilities = v2.liabilities.filter(function(item) {
if (item.inomask == 1) return false;
if (item.inomask == (1+128)) return false;
return true;
})
// declarations
v2.declarations[0] = null;
v2.declarations = v2.declarations.filter(function(item) {
return item !== null
})
// reo
v2.reo = v2.reo.filter(function(item) {
if (item.whosname == "0") return false;
if (item.whosname == "0,99") return false;
if (item.whosname.indexOf("0") > -1) {
if (item.whosname.indexOf("99") < 0) {
item.whosname = item.whose_name.replace(/0/g,"99")
} else {
litem.whosname = item.whosname.split(",").filter(function(itm) { return itm != "0"; }).join(",");
}
}
return true;
})
// references -- mainly in needslist
removeApplicantCounter(0);
if (shuffle_down_higher_borrowers) {
shuffle(0);
setScenario_data("flow_new_main_applicant_action","verify");
setScenario_data("flow_new_main_applicant_invitation","todo");
clear_scenario_passed(v2.applicants.length-1);
} else {
clear(1);
clear_scenario_passed(v2.applicants.length-1);
}
}
if (n == 1 && v2.applicants.length > 1) {
let shuffle_down_higher_borrowers = (v2.applicants.length > 2);
v2.applicants[1] = null;
v2.applicants = v2.applicants.filter(function(item) {
return item !== null
})
// income
v2.income[1] = null;
v2.income = v2.income.filter(function(item) {
return item !== null
})
// assets
v2.assets.items = v2.assets.items.filter(function(item) {
if (item.whose_name == "1") return false;
if (item.whose_name == "1,99") return false;
if (item.whose_name.indexOf("1") > -1) {
if (item.whose_name.indexOf("99") < 0) {
item.whose_name = item.whose_name.replace(/1/g,"99")
} else {
litem.whose_name = item.whose_name.split(",").filter(function(itm) { return itm != "1"; }).join(",");
}
}
return true;
})
// liabilities
v2.liabilities = v2.liabilities.filter(function(item) {
if (item.inomask == 2) return false;
if (item.inomask == (2+128)) return false;
return true;
})
// declarations
v2.declarations[1] = null;
v2.declarations = v2.declarations.filter(function(item) {
return item !== null
})
// reo
v2.reo = v2.reo.filter(function(item) {
if (item.whosname == "1") return false;
if (item.whosname == "1,99") return false;
if (item.whosname.indexOf("1") > -1) {
if (item.whosname.indexOf("99") < 0) {
item.whosname = item.whose_name.replace(/1/g,"99")
} else {
litem.whosname = item.whosname.split(",").filter(function(itm) { return itm != "1"; }).join(",");
}
}
return true;
})
// references -- mainly in needslist
removeApplicantCounter(1);
if (shuffle_down_higher_borrowers) {
shuffle(1)
clear_scenario_passed(v2.applicants.length-1);
} else {
clear(1);
clear_scenario_passed(v2.applicants.length-1);
}
}
if (n > 1 && v2.applicants.length > n) { // this is delete of #3
let shuffle_down_higher_borrowers = (v2.applicants.length > (n+1));
// applicants
v2.applicants[n] = null;
v2.applicants = v2.applicants.filter(function(item) {
return item !== null
})
// income
v2.income[n] = null;
v2.income = v2.income.filter(function(item) {
return item !== null
})
// assets
v2.assets.items = v2.assets.items.filter(function(item) {
if (item.whose_name == `${n}`) return false;
if (item.whose_name == `${n},99`) return false;
if (item.whose_name.indexOf(`${n}`) > -1) {
if (item.whose_name.indexOf("99") < 0) {
item.whose_name = item.whose_name.replace(`${n}`,"99")
} else {
litem.whose_name = item.whose_name.split(",").filter(function(itm) { return itm != `${n}`; }).join(",");
}
}
return true;
})
let inom = [1,2,3,8,16,32,64,128,256,512];
// liabilities
v2.liabilities = v2.liabilities.filter(function(item) {
if (item.inomask == inom[n]) return false;
if (item.inomask == (inom[n]+128)) return false;
return true;
})
// declarations
v2.declarations[n] = null;
v2.declarations = v2.declarations.filter(function(item) {
return item !== null
})
// reo
v2.reo = v2.reo.filter(function(item) {
if (item.whosname == `${n}`) return false;
if (item.whosname == `${n},99`) return false;
if (item.whosname.indexOf(`${n}`) > -1) {
if (item.whosname.indexOf("99") < 0) {
item.whosname = item.whose_name.replace(`${n}`,"99")
} else {
litem.whosname = item.whosname.split(",").filter(function(itm) { return itm != `${n}`; }).join(",");
}
}
return true;
})
removeApplicantCounter(n);
if (shuffle_down_higher_borrowers) {
shuffle(n)
clear_scenario_passed(v2.applicants.length-1);
} else {
clear(n)
clear_scenario_passed(v2.applicants.length-1);
}
}
/**
* this is in there to squish up any gaps in the borrower pair numbering if they have been set using the "bp" variable as part of the applicants array
*/
MAR.getBorrowerPairs();
}
/**
* set the borrower pair
* n = index of applicant 0,1,2,
* pair_code_eg_1B = coding e.g. 1C 0B
*
*/
function set_borrower_pair(n, pair_code_eg_1B) {
let v2 = mar.answers.v2;
if (n > v2.applicants.length) return;
v2.applicants[n].bp = pair_code_eg_1B;
}
function add(n, name, relationship, ssn) {
let v2 = mar.answers.v2;
if (n > 2 && (v2.applicants.length < (n+1) || getScenario_data(`is_there_a_${MAR.th(n+1)}_borrower`,"") !== "Y") ) {
// applicants
v2.applicants.push({})
setScenario_data(`applicant${n+1}_name`,name);
setScenario_data(`${MAR.th(n+1)}_applicant`,relationship);
setScenario_data(`is_there_a_${MAR.th(n+1)}_borrower`,"Y");
getScenario_v2(); // will create the
MAR.activity_log.add("applicant", n, ssn);
// declarations
// wishlist
// references -- mainly in needslist
return 2;
}
if (n == 2 && (v2.applicants.length < 3 || getScenario_data("is_there_a_third_borrower","") !== "Y") ) {
// applicants
v2.applicants.push({})
setScenario_data("applicant3_name",name);
setScenario_data("third_applicant",relationship);
setScenario_data("is_there_a_third_borrower","Y");
getScenario_v2(); // will create the
MAR.activity_log.add("applicant", n, ssn);
// declarations
// wishlist
// references -- mainly in needslist
return 2;
}
if (n == 1 && (v2.applicants.length < 2 || getScenario_data("is_there_a_second_borrower","") !== "Y") ) {
// applicants
v2.applicants.push({})
setScenario_data("applicant2_name",name);
setScenario_data("second_applicant",relationship);
setScenario_data("is_there_a_second_borrower","Y");
getScenario_v2(); // will create the
MAR.activity_log.add("applicant", n, ssn);
// declarations
// wishlist
// references -- mainly in needslist
return 1;
}
if (n == 0 && v2.applicants.length < 1) {
// applicants
v2.applicants.push({})
setScenario_data("applicant1_name",name);
getScenario_v2(); // will create the
// declarations
MAR.activity_log.add("applicant", n, ssn);
// wishlist
// references -- mainly in needslist
return 0;
}
}
function set_relationship(answers, applicantnum, relationship) {
if ("v2" in answers == false) return; // incomplete answers string
if ("applicants" in answers.v2 == false) answers.v2.applicants = [];
while (applicantnum >= answers.v2.applicants.length) answers.v2.applicants.push({}); // make aplicants
if (relationship === false) {
if (applicantnum == 1) {
setScenario_data("is_there_a_second_borrower","");
setScenario_data("second_applicant","");
}
if (applicantnum == 2) {
setScenario_data("is_there_a_third_borrower","");
setScenario_data("third_applicant","");
}
if (applicantnum > 2) {
setScenario_data(`is_there_a_${MAR.th(applicantnum+1)}_borrower`,"");
setScenario_data(`${MAR.th(applicantnum+1)}_applicant`,"");
}
} else if (relationship !== "") {
if (applicantnum == 1) {
setScenario_data("is_there_a_second_borrower","Y");
setScenario_data("second_applicant",relationship);
}
if (applicantnum == 2) {
setScenario_data("is_there_a_third_borrower","Y");
setScenario_data("third_applicant",relationship);
}
if (applicantnum > 2) {
setScenario_data(`is_there_a_${MAR.th(applicantnum+1)}_borrower`,"Y");
setScenario_data(`${MAR.th(applicantnum+1)}_applicant`,relationship);
}
}
}
function is_there_a_property_ownership_missmatch(answers, applicantnum) {
let scenario_says_own = scenario_owns_primary(answers, applicantnum);
let scenario_says_owned = scenario_has_owned_property(answers, applicantnum);
let refi = (getScenario_data("loan_type","purchase") !== "purchase");
if (refi) scenario_says_own = true;
let reo_properties = MAR.reo.getPropertiesByApplicant(applicantnum);
let address_hist = getApplicantAddresses(applicantnum);
let address_own = (function() {
for (let i=0; i < address_hist.length; i++) {
let addr = address_hist[i];
if (MAR.getOpt(addr, "type","") === "current") {
if (MAR.getOpt(addr, "use","") === "own") {
return i;
}
}
}
return false;
})();
let address_owned = (function() {
for (let i=0; i < address_hist.length; i++) {
let addr = address_hist[i];
if (MAR.getOpt(addr, "use","") === "own") {
return true;
}
}
return false;
})();
let missmatch = false;
if (scenario_says_own === false && address_own !== false) {
missmatch = {
type : `adhist`,
txt : `Scenario says you do not own property but in the address history you say you own your current property`
};
}
else if (scenario_says_owned === false && address_owned === true) {
missmatch = {
type : `adhist1`,
txt : `Scenario says you have not owned property in the last 3 years but your address history differs`
};
}
else if (scenario_says_own === false && reo_properties.length > 0) {
missmatch = {
type : `reo`,
txt : `Scenario says you do not own property but in the reo section you are listed as an owner of a property`
};
}
return {
scenario_says_own : scenario_says_own,
reo_properties_len : reo_properties.length,
address_hist : address_hist,
address_own : address_own,
missmatch : missmatch
}
}
function scenario_owns_primary(answers, applicantnum) {
let applicantNum = applicantnum+1;
var loan_type = getScenario_data("loan_type","purchase");
var owned = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years","");
var otype = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_type","");
var ohow = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_how","");
var owns = getScenario_data("does_applicant"+applicantNum+"_own_property","");
let refi = (loan_type !== "purchase");
if (owned === "Y" && otype === "1" && owns === "Y") {
return true;
}
return false;
}
function scenario_has_owned_property(answers, applicantnum) {
let applicantNum = applicantnum+1;
var loan_type = getScenario_data("loan_type","purchase");
var owned = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years","");
var otype = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_type","");
var ohow = getScenario_data("has_applicant"+applicantNum+"_owned_property_in_last_3_years_how","");
var owns = getScenario_data("does_applicant"+applicantNum+"_own_property","");
let refi = (loan_type !== "purchase");
if (owned === "Y" || owns === "Y") {
return true;
}
return false;
}
return {
/**
* basics
*/
count : count,
getNames : getNames,
getBySSN : getBySSN,
//
id : getId,
getId : getId,
getSSN : getSSN,
getVid : getVid,
vid : getVid,
/**
* mutations
*/
remove : remove,
add : add,
set_borrower_pair : set_borrower_pair,
set_relationship : set_relationship,
clear_scenario_passed : clear_scenario_passed,
/**
* scenario helpers
*/
scenario_owns_primary : scenario_owns_primary,
scenario_has_owned_property : scenario_has_owned_property,
is_there_a_property_ownership_missmatch
: is_there_a_property_ownership_missmatch,
/**
* ID
*/
____id : "applicants object"
}
})();
/**
* declarations
* @namespace MAR.declarations
*/
var declarationsObj = (function(){
/**
* @memberof MAR.declarations
*/
function init() {
}
/**
* @memberof MAR.declarations
*/
function summary() {
}
/**
* @memberof MAR.declarations
*/
function get(applicant, type, def) {
if (arguments.length < 3) def = "";
if ("answers" in mar == false) return def;
if ("v2" in mar.answers == false) return def;
if ("declarations" in mar.answers.v2 == false) return def;
if (arguments.length == 0) { // return the whole array
return mar.answers.v2.declarations;
}
if (typeof applicant == "string") applicant = parseInt(applicant,10);
if (applicant >= mar.answers.v2.declarations.length) return def;
if (arguments.length == 1) { // return the array for one applicant
return mar.answers.v2.declarations[applicant];
}
if (type in mar.answers.v2.declarations[applicant] == true) {
return mar.answers.v2.declarations[applicant][type]
}
return def;
}
/**
* @memberof MAR.declarations
*/
function set(applicant, type, data) {
let updated = false;
if (arguments.length == 3) { // return the whole array
if (data === null) return updated;
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("declarations" in mar.answers.v2 == false) mar.answers.v2.declarations = [];
while (mar.answers.v2.declarations.length <= applicant) {
mar.answers.v2.declarations.push({
});
}
if (type in mar.answers.v2.declarations[applicant] === false) updated = true;
if (mar.answers.v2.declarations[applicant][type] != data) updated = true;
if (updated) MAR.activity_log.mod("declaration", applicant, type);
mar.answers.v2.declarations[applicant][type] = data
}
return updated;
}
return {
/**
* utility functions
*/
init : init, // initialize
/**
* getters and setters
*/
get : get, // get (applicant, type, num)
set : set, // get (applicant, type, num)
/**
* report sand summary
*/
summary : summary,
/**
* object id
*/
__id : "income"
}
})();
/**
* income
* @namespace MAR.income
*
*/
var incomeObj = (function(){
/**
* @memberof MAR.income
*/
function init(applicant){ //This initialises _mar.answers.v2.income[n]_ if it does not exist already,,`applicant` is a _number_
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("income" in mar.answers.v2 == false) mar.answers.v2.income = [];
while (mar.answers.v2.income.length <= applicant) {
mar.answers.v2.income.push({
items : []
});
}
if ("items" in mar.answers.v2.income[applicant] == false) {
mar.answers.v2.income[applicant].items = []
}
}
/**
* @memberof MAR.assets
* To cater for either
* abc_1 = abc
* abc = abc
* _abc_1 = _abc
* _abc = _abc
*/
function matchingPart(S) {
if (typeof S !== "string") return S;
if (S.startsWith("_")) {
return `_${S.substring(1).split("_")[0]}`
}
return S.split("_")[0];
}
/**
* is this an other?
*/
function isOther(itm) {
let incometypes = ["w2","DD1099","llc","k1"];
let other_incometypes = ["pension","ssec","dis","child","alimony","rental","other"];
let type = (typeof itm === "string") ? itm : MAR.getOpt(itm, "type", "");
let other = (other_incometypes.indexOf(type) > -1);
return other;
}
/**
* recalculate income summaries
*/
function recalculate() { //Empty!
}
/**
* @memberof MAR.income
*/
function summary() { //Empty!
}
/**
* @memberof _add need overview
*/
function _over_addneed(needid,__prog,__n,__uuid,__obj) {
/*
NEED iD
application 220
section reo
subsection monthly_includes_taxes
identifier 4fd1e812-13f9-4644-8aa6-9045e9818757
NEED TYPE
sup-doc supporting documentation
personal-id personal identification
tac-
sup-desc supporting description
sup-data supporting data
address-list address history
w1-list employment history
llc-list business history
k1-list k1 business history
ssc-list sec list
alimony-list alimony list
dis-list disability list
child-list child list
bank-list list of bank accounts
K401-list list of 401k accounts
gifts-list list of gifts
stock-list list of stock accounts
nprf-list list of nprf sources
emd-list list of end payments
NEED ID EXAMPLES
220/reo/monthly_includes_taxes/4fd1e812-13f9-4644-8aa6-9045e9818757
220/liability/-/4fd1e812-13f9-4644-8aa6-9045e9818757
220/assets/bank/-
** 220/assets/bank/{uuid}
220/applicants/-/0,1,2
** 220/applicants/id/{uuid}
** 220/applicants/address/{uuid}
220/declaration/credit_has_judgements/0,1,2
220/income/w2/0,1,2
** 220/income/w2/{uuid}
220/scenario/property_county/
220/scenario/hoa_estimate/
NEED
*/
if (arguments.length < 5 || !__obj) {
__obj = {};
}
__obj.n = __n;
__obj.vn = MAR.applicants.vid(__n),
__obj.vn0 = MAR.applicants.vid(0),
__obj.vn1 = MAR.applicants.vid(1),
__obj.vn2 = MAR.applicants.vid(2),
__obj.uuid = __uuid;
__obj.prog = __prog;
needid = Mustache.render(needid , __obj);
if ("needslist" in mar == false) mar.needslist = [];
var needindex = -1;
for (var i=0; i < mar.needslist.length; i++) {
if (mar.needslist[i].needid == needid ) {
needindex = i;
break;
}
}
if (needindex > -1) {
} else {
mar.needslist.push({
needid : needid
});
// console.warn(`_over_addneed ${needid}`)
}
}
/**
* @memberof _add need overview
*/
function _noop_addneed(needid,__prog,__n,__uuid,__obj) {
// console.warn(`NOOP _addneed ${needid}`)
}
/**
* @memberof MAR.income
*/
function getIncome_v2(PROG,QI) { // returns ABC
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
if (!QI) QI = {};
/**
* this supercedes the old schema
*/
var retval = {
total : 0,
base : [0,0,0,0,0,0,0,0,0],
bonus : [0,0,0,0,0,0,0,0,0],
overtime : [0,0,0,0,0,0,0,0,0],
commission : [0,0,0,0,0,0,0,0,0],
other : [0,0,0,0,0,0,0,0,0],
years_hist : [0,0,0,0,0,0,0,0,0],
qi_total : 0,
sug_total : 0,
has_unverified_items : false,
is_empty : true,
detailmatrix : [],
warnings : {}
};
//var js = fs.readFileSync('data-tables/rules/rules.js').toString();
//eval(js);
let no_income_docs = (MAR.getOpt(mar, "answers.v2.scenario.is_interestonly","") === "Y") || (MAR.getOpt(mar, "answers.v2.scenario.is_nodoc","") === "Y");
var _addneed = (no_income_docs) ? _noop_addneed : _over_addneed;
/**
* clear all the warnings for assets
*/
rules.clearwarnings("income")
retval.detailmatrix.push(["TYPE","APPLICANT","BASE","2016","2015","CALCULATED BASE","CALCULATED BONUS","TOTAL","MONTHLY","OVER","CLEARED","UUID"]);
var forApplicant = "0";
var starttotal = 0;
for (var n=0; n < mar.answers.v2.income.length; n++) {
forApplicant = ""+n
let taxyear_c = MAR.getApplicantLastTaxYear(n);
let taxyear_p = MAR.getApplicantLastTaxYear(n)-1;
let taxyear_pp = MAR.getApplicantLastTaxYear(n)-2;
let year_c = MAR.getCurrentYear();
let year_p = MAR.getCurrentYear()-1;
let year_pp = MAR.getCurrentYear()-2;
var taxdetails = (function(){
// 1040SC 2018 aa-bb-cc-dd
let arr = [];
function add(itm) {
arr.push(itm);
}
function get() {
return arr;
}
function get_string_year(yr) {
let rv = []
let ar = get_year(yr);
// rv.push(JSON.stringify(ar));
for (let i=0; i < ar.length; i++) {
let a = ar[i];
if (a[0] === "1040") {
}
else if (a[0] === "1040SC") {
try {
let uuid = a[2];
let item = MAR.income.getByUUID(uuid);
let name = item.name || item.name_k1 || item.name_llc;
let total = MAR.format.format("cur",item.total);
let obj = MAR.xsd.inc_w2(item);
if (obj.isPrevious()) {
rv.push(`Schedule C for ${obj.name()} previous job`)
} else {
rv.push(`Schedule C for ${obj.name()} showing ${total}`)
}
} catch(E) {
rv.push(`Schedule C ${E}`)
}
}
else if (a[0] === "1040E") {
rv.push(`Schedule E showing rental income`)
}
else if (a[0] === "1120") {
// rv.push(`1120 for ...`)
}
else if (a[0] === "1120S") {
// rv.push(`1120S for ...`)
}
else if (a[0] === "1065") {
// try {
// let uuid = a[2];
// let item = MAR.income.getByUUID(uuid);
// let name = item.name || item.name_k1 || item.name_llc;
// let total = MAR.format.format("cur",item.total);
// rv.push(`1065 for ${name} showing ${total}`)
//
// } catch(E) {
// rv.push(`1065`)
// }
}
else {
// rv.push(`${a[0]} ${a[1]}`);
}
}
/**
* override
*
*/
return "include all schedules";
if (rv.length === 0) {
return "include all schedules";
}
return "including "+rv.join(", ");
}
function get_string() {
return JSON.stringify({
y2017 : is_year_1040(2017),
y2018 : is_year_1040(2018),
y2019 : is_year_1040(2019),
arr : arr
});
}
function is_year_type(yr, type) {
for (let i=0; i < arr.length; i++) {
let a = arr[i].split(" ");
if (a.length !== 3) continue;
let a_type = a[0];
let a_yr = num(a[1]);
if (a_yr !== num(yr) && a_type === type) {
return true;
}
}
return false;
}
function is_year_1040(yr) {
for (let i=0; i < arr.length; i++) {
let a = arr[i].split(" ");
if (a.length !== 3) continue;
let a_type = a[0];
let a_yr = num(a[1]);
if (a_yr === num(yr) && a_type.startsWith("1040") === true) {
return true;
}
}
return false;
}
function is_year(yr) {
for (let i=0; i < arr.length; i++) {
let a = arr[i].split(" ");
if (a.length !== 3) continue;
let a_yr = num(a[1]);
if (a_yr === num(yr)) return tru;
}
return false;
}
function get_year(yr) {
let rv = [];
for (let i=0; i < arr.length; i++) {
let a = arr[i].split(" ");
if (a.length !== 3) continue;
let a_yr = num(a[1]);
if (a_yr === num(yr)) rv.push(a)
}
return rv
}
return {
add : add,
get : get,
get_string : get_string,
get_string_year : get_string_year,
is_year : is_year,
is_year_1040 : is_year_1040,
is_year_type : is_year_type,
___id : "tax details"
}
})();
if (MAR.getOpt(mar.answers.v2.income[n], `items`, []).length === 0 ) {
retval.detailmatrix.push(["
Applicant "+(n+1)+" - Income missing "]);
} else {
retval.detailmatrix.push(["
Applicant "+(n+1)+" "]);
}
let incometypes = ["w2","DD1099","llc","k1","pension","ssec","dis","child","alimony","rental","other"]
if ("items" in mar.answers.v2.income[n]) {
/**
* make sure there are no empty income types
*/
for (let i=0; i < incometypes.length; i++) {
let _incometype = incometypes[i];
if (_incometype in mar.answers.v2.income[n] == false || mar.answers.v2.income[n][_incometype] == false) {
mar.answers.v2.income[n][_incometype] = {
total : 0
}
} else {
mar.answers.v2.income[n][_incometype].total = 0;
}
}
let int = function(N) {
return Math.floor(N);
}
let dbl = function(N) {
let n = N.toFixed(2);
n = parseFloat(n);
return n;
return parseFloat(N.toFixed(2),10);
return Math.round( N * 100 + Number.EPSILON ) / 100
return +(Math.round(N + "e+2") + "e-2");
return ~~(N);
return ~~(N * 100) / 100;
}
for (let i=0; i < mar.answers.v2.income[n].items.length; i++) {
let inc = mar.answers.v2.income[n].items[i];
retval.is_empty = false;
// console.log(`INCOME ${inc.type}`)
let __isverified = true;
if (inc.type == "") {
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
__isverified = false;
if ("current" in inc == false || inc.current.toLowerCase() != "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
}
}
}
if (__isverified) {
retval.years_hist[n] = 2;
}
inc.start_date = "";
inc.end_date = "";
inc._M = MAR.application.M();
inc._Y = MAR.application.Y();
inc._TP = MAR.application.TP();
(function(){
let cd = MAR.getOpt(mar.answers, "cleared_dates", {});
for (let x in cd) {
if (x.startsWith("/income/") && x.indexOf(inc.uuid) > -1) {
inc._cleared_dates = cd[x];
return;
}
}
inc._cleared_dates = false;
})();
if (inc.type == "w2") {
// console.log("INC",inc);
var salary_frequency = ("salary_choice" in inc) ? inc.salary_choice : "";
var salary_base = ("income_w2_base" in inc) ? num(inc.income_w2_base) : 0;
var salary_2yearquestion = ("salary_3yearquestion" in inc) ? inc.salary_3yearquestion : "";
var salary_overtime = ("salary_overtime" in inc) ? inc.salary_overtime : 0;
var salary_bonus = ("salary_bonus" in inc) ? inc.salary_bonus : 0;
var salary_other = ("salary_other" in inc) ? inc.salary_other : 0;
var salary_commission = ("salary_commission" in inc) ? inc.salary_commission : 0;
if (salary_overtime != "Y") {
inc[`income_w2_overtime_${year_c}`] = 0;
inc[`income_w2_overtime_${year_p}`] = 0;
inc[`income_w2_overtime_${year_pp}`] = 0;
}
if (salary_bonus != "Y") {
inc[`income_w2_bonus_${year_c}`] = 0;
inc[`income_w2_bonus_${year_p}`] = 0;
inc[`income_w2_bonus_${year_pp}`] = 0;
}
if (salary_other != "Y") {
inc[`income_w2_other_${year_c}`] = 0;
inc[`income_w2_other_${year_p}`] = 0;
inc[`income_w2_other_${year_pp}`] = 0;
}
if (salary_commission != "Y") {
inc[`income_w2_commission_${year_c}`] = 0;
inc[`income_w2_commission_${year_p}`] = 0;
inc[`income_w2_commission_${year_pp}`] = 0;
}
if (salary_frequency == mar.SALARY_FREQUENCY_WEEKLY) {
salary_base = ((num(salary_base) * 52)/12);
} else if (salary_frequency == mar.SALARY_FREQUENCY_BIWEEKLY) {
salary_base = ((num(salary_base) * 26)/12);
} else if (salary_frequency == mar.SALARY_FREQUENCY_SEMIMONTHLY) {
salary_base = (num(salary_base) * 2);
} else if (salary_frequency == mar.SALARY_FREQUENCY_HOURLY) {
salary_base = ((num(salary_base) * 40 * 52) / 12);
} else if (salary_frequency == mar.SALARY_FREQUENCY_MONTHLY) {
/* nothing */
} else if (salary_frequency == mar.SALARY_FREQUENCY_YEARLY) {
salary_base = (num(salary_base) / 12);
} else {
salary_base = 0;
}
var lastyear = (`income_w2_bonus_${year_c}` in inc) ? num(inc[`income_w2_bonus_${year_c}`]) : 0;
var prevyear = (`income_w2_bonus_${year_c}` in inc) ? num(inc[`income_w2_bonus_${year_p}`]) : 0;
var Prevyear = (`income_w2_bonus_${year_c}` in inc) ? num(inc[`income_w2_bonus_${year_pp}`]) : 0;
if (new Date().getMonth() < 3) {
lastyear = prevyear;
prevyear = Prevyear;
Prevyear = 0;
}
var base = num(salary_base);
var bonus = ((num(lastyear) + num(prevyear))/24);
var lastyearc = (`income_w2_commission_${year_c}` in inc) ? num(inc[`income_w2_commission_${year_c}`]) : 0;
var prevyearc = (`income_w2_commission_${year_c}` in inc) ? num(inc[`income_w2_commission_${year_p}`]) : 0;
var Prevyearc = (`income_w2_commission_${year_c}` in inc) ? num(inc[`income_w2_commission_${year_pp}`]) : 0;
var commission = 0;
var lowest_commission = 0;
if (new Date().getMonth() < 3) {
lastyearc = prevyearc;
prevyearc = Prevyearc;
Prevyearc = 0;
commission = ((num(lastyearc) + num(prevyearc))/24);
} else {
let ytd_2y = ((num(lastyearc) + num(prevyearc) + num(Prevyearc))/36);
let ytd_1y = ((num(lastyearc) + num(prevyearc))/24);
let ytd_0y = ((num(lastyearc))/12);
commission = MAR.math.lowest(ytd_2y, ytd_1y, ytd_0y);
}
lowest_commission = commission;
var lastyeart = (`income_w2_other_${year_c}` in inc) ? num(inc[`income_w2_other_${year_c}`]) : 0;
var prevyeart = (`income_w2_other_${year_c}` in inc) ? num(inc[`income_w2_other_${year_p}`]) : 0;
var Prevyeart = (`income_w2_other_${year_c}` in inc) ? num(inc[`income_w2_other_${year_pp}`]) : 0;
if (new Date().getMonth() < 3) {
lastyeart = prevyeart;
prevyeart = Prevyeart;
Prevyeart = 0;
}
var other = ((num(lastyeart) + num(prevyeart))/24);
var lastyearo = (`income_w2_overtime_${year_c}` in inc) ? num(inc[`income_w2_overtime_${year_c}`]) : 0;
var prevyearo = (`income_w2_overtime_${year_c}` in inc) ? num(inc[`income_w2_overtime_${year_p}`]) : 0;
var Prevyearo = (`income_w2_overtime_${year_c}` in inc) ? num(inc[`income_w2_overtime_${year_pp}`]) : 0;
if (new Date().getMonth() < 3) {
lastyearo = prevyearo;
prevyearo = Prevyearo;
Prevyearo = 0;
}
var overtime = ((num(lastyearo) + num(prevyearo))/24);
var val = num(salary_base) + bonus + commission + overtime + other;
if ("current" in inc === false) {
if (MAR.getOpt(inc, "previous_type","") === "") {
inc.current = "Y";
} else {
inc.current = "N";
}
}
if (MAR.getOpt(inc, "current","Y") === "N") {
if (MAR.getOpt(inc, "previous_type","") === "work") {
inc.start_date = MAR.getOpt(inc, "fromd", "");
inc.end_date = MAR.getOpt(inc, "tod", "");
}
if (MAR.getOpt(inc, "previous_type","") === "study") {
inc.start_date = MAR.getOpt(inc, "education_start", "");
inc.end_date = MAR.getOpt(inc, "education_end", "");
}
if (MAR.getOpt(inc, "previous_type","") === "neither") {
inc.start_date = MAR.getOpt(inc, "fromd", "");
inc.end_date = MAR.getOpt(inc, "tod", "");
}
} else {
inc.start_date = MAR.getOpt(inc, "fromd", "");
inc.end_date = "";
}
if (MAR.getOpt(inc, "current","Y") === "N") {
salary_base = 0;
lastyear = 0;
prevyear = 0;
Prevyear = 0;
base = 0;
bonus = 0;
lastyearc = 0;
prevyearc = 0;
Prevyearc = 0;
commission = 0;
lastyeart = 0;
prevyeart = 0;
Prevyeart = 0;
other = 0;
lastyearo = 0;
prevyearo = 0;
Prevyearo = 0;
overtime = 0;
val = 0;
}
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
lastyear = 0;
prevyear = 0;
Prevyear = 0;
salary_base = 0;
base = 0;
bonus = 0;
lastyearc = 0;
prevyearc = 0;
Prevyearc = 0;
commission = 0;
lastyeart = 0;
prevyeart = 0;
Prevyeart = 0;
other = 0;
lastyearo = 0;
prevyearo = 0;
Prevyearo = 0;
overtime = 0;
val = 0;
}
var rules_val = val;
inc.iws = {
enc : {
base : base,
bonus : bonus,
overtime : num(overtime)/12,
commission : num(commission)/12,
other : other
},
current : {
base : base,
bonus : lastyear,
overtime : num(lastyearo)/12,
commission : num(lastyearc)/12,
other : other,
rate : salary_base,
freq : salary_frequency
},
last : {
bonus : prevyear,
overtime : num(prevyearo)/12,
commission : num(prevyearc)/12,
other : other,
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
inc.taxyear_pp = taxyear_pp;
inc.year_c = year_c;
inc.year_p = year_p;
inc.year_pp = year_pp;
inc.rules_val = rules_val;
/* rules */
inc.warnings=[];
let warning_type = "income_w2";
// if (val > 0 || "parent" in inc) { // also run for previous employments
if (val !== 0 || "parent" in inc) { // also run for previous employments
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
employer : ("name" in inc) ? inc.name : "employer",
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
/**
* we have an over ridden value set
*/
if (MAR.getOpt(inc, "over", "") === "Y") {
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
bonus = int(num(MAR.getOpt(inc, "over_bonus" , "0")));
overtime = int(num(MAR.getOpt(inc, "over_overtime" , "0")));
commission = int(num(MAR.getOpt(inc, "over_commission" , "0")));
other = int(num(MAR.getOpt(inc, "over_other" , "0")));
base = val - (bonus + commission + overtime);
}
bonus = int(bonus);
commission = int(commission);
overtime = int(overtime);
other = int(other);
bonus = int(bonus);
base = int(base);
val = int(val);
////
inc.iws.enc.base = val - (bonus + commission + overtime + other);
inc.iws.enc.baseval = val;
inc.iws.enc.bonus = bonus;
inc.iws.enc.overtime = overtime;
inc.iws.enc.commission = commission;
inc.iws.enc.other = other;
inc.total = val;
retval.total += val;
retval.base[n] += inc.iws.enc.base;
retval.bonus[n] += inc.iws.enc.bonus;
retval.overtime[n] += inc.iws.enc.overtime;
retval.commission[n] += inc.iws.enc.commission;
retval.other[n] += inc.iws.enc.other;
mar.answers.v2.income[n].w2.total += val;
mar.answers.v2.income[n].w2.active = (salary_base > 0);
if ("displayName" in inc == false || inc.displayName.trim().length == 0) {
inc.displayName = inc.name;
}
if (val !== 0) {
retval.detailmatrix.push([`${inc.name} (W2)`,forApplicant,
salary_base.toFixed(0),
(lastyear+lastyearo+lastyearc).toFixed(0),
(prevyear+prevyearo+prevyearc).toFixed(0),
salary_base.toFixed(0),
bonus.toFixed(0),
val.toFixed(0),
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "DD1099") {
// itm.type = "DD1099";
// itm.name = "1099 Self Employed";
// itm.last_year_filed = radio("last_year_filed");
// itm.profit_DD1099_2017 = txt("#profit_DD1099_2017");
// itm.profit_DD1099_2016 = txt("#profit_DD1099_2016");
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
(function(){
inc.pnlyear_ytd = year_c;
for (let _i=1; _i < 4; _i++) {
let _yc = year_c - _i;
if (_yc > taxyear_c) {
inc[`pnlyear_m${_i}`] = _yc;
} else {
inc[`pnlyear_m${_i}`] = "-";
}
}
})();
var lastyear = num(inc[`profit_DD1099_${inc.taxyear_c}`]);
var prevyear = num(inc[`profit_DD1099_${inc.taxyear_p}`]);
// var lastyear = num(inc.profit_DD1099_2017);
// var prevyear = num(inc.profit_DD1099_2016);
/**
* rule:the basic calc is to average out the last 2 years
*/
var val = (((lastyear + prevyear)/2)/12);
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
lastyear = 0;
prevyear = 0;
val = 0;
}
inc.warnings=[];
// if (val > 0) {
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_DD1099";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
}
if (MAR.getOpt(inc, "over", "") === "Y") {
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
bonus = int(num(MAR.getOpt(inc, "over_bonus" , "0")));
overtime = int(num(MAR.getOpt(inc, "over_overtime" , "0")));
commission = int(num(MAR.getOpt(inc, "over_commission" , "0")));
other = int(num(MAR.getOpt(inc, "over_other" , "0")));
base = int(num(MAR.getOpt(inc, "over_base" , "0")));
}
inc.total = val;
retval.total += val;
retval.base[n] += val;
inc.iws = {
enc : {
other : val
}
}
mar.answers.v2.income[n].DD1099.total += val;
mar.answers.v2.income[n].DD1099.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["income from 1099",forApplicant,
"",
lastyear,
prevyear,
((lastyear + prevyear)/2),
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "llc") {
inc.name = inc.name_llc;
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
(function(){
inc.pnlyear_ytd = year_c;
for (let _i=1; _i < 4; _i++) {
let _yc = year_c - _i;
if (_yc > taxyear_c) {
inc[`pnlyear_m${_i}`] = _yc;
} else {
inc[`pnlyear_m${_i}`] = "-";
}
}
})();
var lastyear = num(inc[`income_llc_${inc.taxyear_c}`]);
var prevyear = num(inc[`income_llc_${inc.taxyear_p}`]);
// var lastyear = num(inc.income_llc_2017);
// var prevyear = num(inc.income_llc_2016);
/**
* rule:the basic calc is to average out the last 2 years
*/
var val = (((lastyear + prevyear)/2)/12);
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
lastyear = 0;
prevyear = 0;
val = 0;
}
inc.warnings=[];
// if (val > 0) {
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_llc";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
}
if (MAR.getOpt(inc, "over", "") === "Y") {
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
bonus = int(num(MAR.getOpt(inc, "over_bonus" , "0")));
overtime = int(num(MAR.getOpt(inc, "over_overtime" , "0")));
commission = int(num(MAR.getOpt(inc, "over_commission" , "0")));
other = int(num(MAR.getOpt(inc, "over_other" , "0")));
base = int(num(MAR.getOpt(inc, "over_base" , "0")));
}
inc.total = val;
retval.total += val;
retval.base[n] += val;
inc.iws = {
enc : {
other : val
}
}
mar.answers.v2.income[n].llc.total += val;
mar.answers.v2.income[n].llc.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["income from LLC",forApplicant,
"",
lastyear,
prevyear,
((lastyear + prevyear)/2),
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "k1") {
if ("ctype" in inc == false) inc.ctype = "c";
if (inc.ctype == "") inc.ctype = "c";
inc.taxyear_c = num(inc.k1_last_year_filed);
inc.taxyear_p = (inc.taxyear_c-1);
if (ctype == "c" || ctype == "p") {
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
}
(function(){
inc.pnlyear_ytd = year_c;
for (let _i=1; _i < 4; _i++) {
let _yc = year_c - _i;
if (_yc > inc.taxyear_c) {
inc[`pnlyear_m${_i}`] = _yc;
} else {
inc[`pnlyear_m${_i}`] = "-";
}
}
})();
var lastyear = num(inc[`income_corp_${inc.taxyear_c}`]);
var prevyear = num(inc[`income_corp_${inc.taxyear_p}`]);
if (inc.ctype == "s") {
var lastyear = num(inc[`income_corp_c`]);
var prevyear = num(inc[`income_corp_p`]);
}
var more5years = MAR.getOpt(inc, "income_corp_greater_5_years", "Y");
var ctype = inc.ctype;
inc.jc = `1 ${lastyear} ${prevyear}`;
var val = (((lastyear + prevyear)/2)/12);
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
lastyear = 0;
prevyear = 0;
val = 0;
}
// if (val > 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_k1";
// if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
// }
// }
if (MAR.getOpt(inc, "over", "") === "Y") {
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
bonus = int(num(MAR.getOpt(inc, "over_bonus" , "0")));
overtime = int(num(MAR.getOpt(inc, "over_overtime" , "0")));
commission = int(num(MAR.getOpt(inc, "over_commission" , "0")));
other = int(num(MAR.getOpt(inc, "over_other" , "0")));
base = int(num(MAR.getOpt(inc, "over_base" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws = {
enc : {
other : val
}
}
mar.answers.v2.income[n].k1.total += val;
mar.answers.v2.income[n].k1.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push([`${inc.name_k1} (K1)`,forApplicant,
"",
lastyear,
prevyear,
((lastyear + prevyear)/24),
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "pension") {
var income = num(inc.pension_income);
var original = income;
var notax = inc.pension_dont_pay_taxes;
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax
}
}
var val = income;
// if (val > 0) {
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_pension";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
/*
if (notax === mar.YES) {
income = income * 1.15;
}
*/
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].pension.total += val;
mar.answers.v2.income[n].pension.active = (salary_base > 0);
inc.displayName = "Pension " + inc.pension_former_employer;
if (val !== 0) {
retval.detailmatrix.push(["Pension",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "ssec") {
var income = num(inc.ssec_income);
var original = income;
var notax = inc.ssec_dont_pay_taxes;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
var val = income;
if (val !== 0) {
inc.warnings=[];
let warning_type = "income_ssec";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
// inc.iws = {
// enc : {
// other : val
// }
// }
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].ssec.total += val;
mar.answers.v2.income[n].ssec.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["Social security",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "dis") {
var income = num(inc.dis_income);
var original = income;
var notax = inc.dis_dont_pay_taxes;
var more3y = inc.dis_more_3_years;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax,
more3y : more3y
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
var val = income;
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_dis";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
var val = income;
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].dis.total += val;
mar.answers.v2.income[n].dis.active = (salary_base > 0);
if ("displayName" in inc == false || inc.displayName.trim().length == 0) {
inc.displayName = "Disability";
}
if (val !== 0) {
retval.detailmatrix.push(["Disability",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "child") {
var income = num(inc.child_income);
var original = income;
var notax = inc.child_dont_pay_taxes;
var more3y = inc.child_more_3_years;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax,
more3y : more3y
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
var val = income;
/* rules */
if (val !== 0) {
inc.warnings=[];
let warning_type = "income_child";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
employer : ("name" in inc) ? inc.name : "employer",
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
/*
if (notax === mar.YES) {
income = num(income) * 1.15;
}
if (more3y === mar.NO) {
income = 0;
}
*/
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].child.total += val;
mar.answers.v2.income[n].child.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["Child Support",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "alimony") {
var income = num(inc.alimony_income);
var original = income;
var notax = inc.alimony_dont_pay_taxes;
var more3y = inc.alimony_more_3_years;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax,
more3y : more3y
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
var val = income;
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_alimony";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
employer : ("name" in inc) ? inc.name : "employer",
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].alimony.total += val;
mar.answers.v2.income[n].alimony.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["Alimony",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
if (inc.type == "rental") {
}
if (inc.type == "other") {
var income = num(inc.other_income);
var original = income;
var notax = inc.other_dont_pay_taxes;
if ("verified" in inc && inc.verified.toLowerCase() == "n") {
if ("sug_total" in inc) retval.sug_total += num(inc.sug_total);
retval.has_unverified_items = true;
income = 0;
}
inc.iws = {
current : {
ubertype : "ssec",
income : income,
notax : notax
}
}
inc.taxyear_c = taxyear_c;
inc.taxyear_p = taxyear_p;
var val = income;
if (val !== 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_other";
if (val !== 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
employer : ("name" in inc) ? inc.name : "employer",
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
income = val;
}
/*
if (notax === mar.YES) {
income = income * 1.15;
}
*/
if (MAR.getOpt(inc, "over", "") === "Y") {
income = int(num(MAR.getOpt(inc, "over_total" , "0")));
val = int(num(MAR.getOpt(inc, "over_total" , "0")));
original = int(num(MAR.getOpt(inc, "over_total" , "0")));
}
inc.total = val;
retval.total += val;
retval.other[n] += val;
inc.iws.enc = {
other : val
}
mar.answers.v2.income[n].other.total += val;
mar.answers.v2.income[n].other.active = (salary_base > 0);
if (val !== 0) {
retval.detailmatrix.push(["Other",forApplicant,
original,
"",
"",
income,
"",
val,
MAR.getOpt(inc,"over",""),
MAR.getOpt(inc,"cleared",""),
MAR.getOpt(inc,"uuid","")
]);
}
}
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
/**
* add in rental from elsewhere
*/
var val = 0;
var _reo = {};
let scenario_rent = 0;
if (n == 0) {
/** this is a quick fix , the proper way is to ask the income */
_reo = getReo_v2(PROG);
val = (_reo && "income" in _reo) ? float(_reo.income) : 0;
if (MAR.applicationNav.hasEnteredReoEver(mar.answers) === false) {
// if REO not passed
var _sc = getScenario_v2(PROG);
if (_sc.monthly_rent) {
/**
* take 75% of the expected future income from rental of an investment property
*/
scenario_rent += (0.75 * float(_sc.monthly_rent));
val += scenario_rent;
}
} else if (MAR.application.isPurchase()) {
var _sc = getScenario_v2(PROG);
if (_sc.monthly_rent) {
/**
* take 75% of the expected future income from rental of an investment property
*/
scenario_rent += (0.75 * float(_sc.monthly_rent));
val += scenario_rent;
}
}
}
var lastyear = val;
var prevyear = val;
mar.answers.v2.income[n].rental.reorental = _reo.rental;
mar.answers.v2.income[n].rental.reorentalval = val;
mar.answers.v2.income[n].rental.scenario_rent_75 = scenario_rent;
mar.answers.v2.income[n].rental.total = val;
if (val !== 0) {
/* rules */
rules.get("income_rental").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n, {
});
_fn = null;
});
}
mar.answers.v2.income[n].rental.total = val;
mar.answers.v2.income[n].rental.active = true;
retval.total += mar.answers.v2.income[n].rental.total;
if ( mar.answers.v2.income[n].rental.total > 0) {
retval.detailmatrix.push(["Rental income",forApplicant,
"",
lastyear,
prevyear,
((lastyear + prevyear)/2),
"",
val,
"",
"",
""
]);
}
mar.answers.v2.income[n].total = (retval.total - starttotal);
starttotal = retval.total;
/* rules */
rules.get("income_applicantsummary").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
taxdetails : {
obj : taxdetails,
str : taxdetails.get_string(),
str2015 : taxdetails.get_string_year(2015),
str2016 : taxdetails.get_string_year(2016),
str2017 : taxdetails.get_string_year(2017),
str2018 : taxdetails.get_string_year(2018),
str2019 : taxdetails.get_string_year(2019),
str2020 : taxdetails.get_string_year(2020),
str2021 : taxdetails.get_string_year(2021),
str2022 : taxdetails.get_string_year(2022)
},
item : mar.answers.v2.income[n]
});
_fn = null;
});
} else {
}
}
/* rules */
rules.get("income_summary").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(),
items : mar.answers.v2.income,
retval : retval
});
_fn = null;
});
retval.total = num(retval.total).toFixed(0);
retval.detailmatrix.push(["","","","","","","total:",retval.total,"",""]);
// console.log("ENDINCOME",mar.answers.v2.income);
if(retval.is_empty == false && retval.has_unverified_items == true) {
retval.combined_total = num(retval.total) + num(retval.sug_total)
} else {
retval.combined_total = num(retval.total);
}
return retval;
}
/**
* @memberof MAR.income
*/
function getByUUID(uuid, returnindex) { //Get the income by its uuid,,>`uuid` is a *string*,,>`returnindex` is a *Bool*,,If returnindex is set then it returns an *Object* of,``` appl : i, ids : j, data : item```,, Otherwise it returns the item
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("items" in _array[i]) {
for (let j=0; j < _array[i].items.length; j++) {
if ("uuid" in _array[i].items[j] && _array[i].items[j].uuid == matchingPart(uuid)) {
_array[i].items[j].aid = i;
_array[i].items[j].jid = j;
if (arguments.length > 1 && returnindex === true) {
return {
appl : i,
idx : j,
data : _array[i].items[j]
}
}
return _array[i].items[j];
}
}
}
}
return false;
}
/**
* @memberof MAR.income
*/
function setByUUID(uuid, obj) {
let ob = getByUUID(uuid);
if (ob !== false) {
for (let x in obj) {
if (x === "address" && MAR.getOpt(ob,"type","") === "w2") {
let b = MAR.getOpt(mar.answers.v2.buckets, `/income/address/${matchingPart(uuid)}`,false);
if (b === false) {
b = {};
mar.answers.v2.buckets[`/income/address/${matchingPart(uuid)}`] = b;
}
b.address = obj[x];
} else {
ob[x] = obj[x]
}
}
}
}
/**
* @memberof MAR.income
*/
function getByParentUUID(uuid) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("items" in _array[i]) {
for (let j=0; j < _array[i].items.length; j++) {
if ("parent" in _array[i].items[j] && _array[i].items[j].parent == matchingPart(uuid)) {
_array[i].items[j].aid = i;
_array[i].items[j].jid = j;
return _array[i].items[j];
}
}
}
}
return false;
}
/**
* @memberof income
*/
function getNextUnverifiedItem() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("items" in _array[i]) {
for (let j=0; j < _array[i].items.length; j++) {
if ("verified" in _array[i].items[j] && _array[i].items[j].verified === "N") {
return {
a : i,
i : j,
uuid : _array[i].items[j].uuid
}
}
}
}
}
return false;
}
/**
* @memberof MAR.income
*/
function has_w2_with_ownership(applicant) {
init(applicant);
getIncome_v2();
let items = get(applicant);
let retval = [];
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.type === "w2" && MAR.getOpt(item, "current","Y") !== "N" && MAR.getOpt(item, "own_all_or_part","N") === "Y") {
retval.push(item);
}
}
return (retval.length === 0) ? false : retval;
}
/**
* @memberof MAR.income
*/
function has_business_that_generates_w2(applicant) {
init(applicant);
getIncome_v2();
let items = get(applicant);
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.type === "llc" ) return true;
if (item.type === "k1" ) return true;
}
return false;
}
/**
* @memberof MAR.income
*/
function has_w2_with_ownership_first_name(applicant) {
let w2s = has_w2_with_ownership(applicant);
if (w2s === false) return "";
return w2s[0].name;
}
/**
* @memberof MAR.income
*/
function isPrevious(inc) {
if (typeof inc !== "object") return false;
let type = MAR.getOpt(inc, "previous_type", "");
if (type === "") return false;
return true;
}
/**
* @memberof MAR.income
*/
function isBreak(inc) {
if (typeof inc !== "object") return false;
let type = MAR.getOpt(inc, "previous_type", "");
if (type === "neither") return true;
return false;
}
/**
* @memberof MAR.income
*/
function have2Years(applicant) {
init(applicant);
getIncome_v2();
if (typeof applicant == "string") applicant = parseInt(applicant,10);
let items = get(applicant);
if (items.length === 0) return -1; // no income at all
let is_this_w2 = false;
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.type === "w2" && MAR.getOpt(item, "current","Y") !== "N") {
is_this_w2 = true;
}
}
if (is_this_w2 == false) return 0; // all ok
let oldest_start_date = "";
let oldest_uuid = "";
/**
* moment with range
*/
let Moment = (typeof context === "object") ? context.global.moment : moment;
let MomentRange = (typeof context === "object") ? context.global.momentrange : window['moment-range'];
let _moment = MomentRange.extendMoment(Moment);
let ranges = [];
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.type === "w2" && item.current === "Y") {
let ed = moment();
let sd = moment(item.start_date);
ranges.push(moment.range(sd, ed));
}
if (item.type === "w2" && item.current !== "Y") {
if (item.previous_type === "neither") continue; // dont include sabaticals
oldest_start_date = item.start_date;
oldest_uuid = item.uuid;
let ed = moment(item.end_date);
let sd = moment(item.start_date);
ranges.push(moment.range(sd, ed));
}
}
if (ranges.length > 0) {
let _mr = [ranges[0]];
for (let i=1; i < ranges.length; i++) {
let fnd = false;
for (let j=0; j < _mr.length; j++) {
if (_mr[j].overlaps(ranges[i], { adjacent: true })) {
_mr[j] = _mr[j].add(ranges[i], { adjacent: true });
fnd = true;
break;
}
}
if (fnd === false) {
_mr.push(ranges[i]);
}
}
let total_duration = 0;
for (let i=0; i < _mr.length; i++) {
total_duration += _mr[i].duration("months",true); // e.g. 5.23 (true uses parts of month)
}
console.log(total_duration,_mr,ranges);
if (total_duration < 24) return `${oldest_start_date}|${oldest_uuid}|${total_duration}`;
return 0;
}
let m_now = moment();
let m_this_fromd = moment(oldest_start_date);
let diff = m_this_fromd.diff(m_now,'months');
if (diff > -24) return `${oldest_start_date}|${oldest_uuid}`;
return 0;
}
// let range_az = moment.range(moment(startdate), moment(enddate));
// let deductions = [];
// for (let i=0; i < array_of_start_and_end_dates.length; i++) {
// let __s = moment(array_of_start_and_end_dates[i][0]).subtract(1,'day');
// let __e = moment(array_of_start_and_end_dates[i][1]).add(1,'day');
// deductions.push(moment.range(__s, __e));
// }
// dbg.push(["SD",startdate]);
// dbg.push(["ed",enddate]);
// dbg.push(range_az);
// dbg.push(deductions);
//
// let mr = [range_az]
//
// for (let i=0; i < deductions.length; i++) {
// let _mr = [];
// for (let j=0; j < mr.length; j++) {
// let newrange = mr[j].subtract(deductions[i]);
// for (let k=0; k < newrange.length; k++) {
// _mr.push(newrange[k]);
// }
// }
// mr = _mr;
// }
//
// return mr;
/**
* @memberof MAR.income
*/
function get(applicant, type, number) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("income" in mar.answers.v2 == false) return false;
if (arguments.length == 0) { // return the whole array
return mar.answers.v2.income;
}
if (typeof applicant == "string") applicant = parseInt(applicant,10);
if (applicant >= mar.answers.v2.income.length) return false;
if ("items" in mar.answers.v2.income[applicant] == false) mar.answers.v2.income[number].items = []
if (arguments.length == 1) { // return the array for one applicant
return mar.answers.v2.income[applicant].items;
}
if (arguments.length == 2) { // return the array for one applicant
let retval = [];
for (let i=0; i < mar.answers.v2.income[applicant].items.length; i++) {
if (mar.answers.v2.income[applicant].items[i].type == type) {
retval.push(mar.answers.v2.income[applicant].items[i])
}
}
return retval;
}
if (typeof number == "string") number = parseInt(number,10);
if (number < mar.answers.v2.income[applicant].items.length) {
return mar.answers.v2.income[applicant].items[number];
}
return false;
}
function getNextIncomeEncId(){
if ("state" in mar.answers.v2 == false) mar.answers.v2.state = {};
if ("income_encid" in mar.answers.v2.state == false) mar.answers.v2.state.income_encid = 1;
let retval = mar.answers.v2.state.income_encid;
mar.answers.v2.state.income_encid++;
return retval;
}
/**
* @memberof MAR.income
*/
function set(applicant, type, number, data) {
if (applicant < 0) return 0; // in case there is a negative applicant
if (arguments.length >= 4) { // return the whole array
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("income" in mar.answers.v2 == false) mar.answers.v2.income = [];
while (mar.answers.v2.income.length <= applicant) {
mar.answers.v2.income.push({
items : []
});
}
if ("items" in mar.answers.v2.income[applicant] == false) {
mar.answers.v2.income[applicant].items = []
}
if (number === false) {
if ("__pre_uuid" in data == true) {
data.uuid = data.__pre_uuid;
delete data.__pre_uuid;
}
if ("uuid" in data == false) data.uuid = uuidv4();
data.enc_id = getNextIncomeEncId();
mar.answers.v2.income[applicant].items.push(data);
MAR.activity_log.add("income", data.uuid);
return (mar.answers.v2.income[applicant].items.length -1);
} else {
if (typeof number == "string") number = parseInt(number,10);
if (mar.answers.v2.income[applicant].items.length > number) {
if ("uuid" in mar.answers.v2.income[applicant].items[number] == false) {
if ("__pre_uuid" in data == true) {
data.uuid = data.__pre_uuid;
delete data.__pre_uuid;
}
if ("uuid" in data == false) data.uuid = uuidv4();
data.enc_id = getNextIncomeEncId();
}
if ("uuid" in mar.answers.v2.income[applicant].items[number] == false) {
if ("enc_id" in data == false) data.enc_id = getNextIncomeEncId()
}
// mar.answers.v2.income[applicant].items[number] = data;
for (x in data) {
/**
* update only , don't overwrite!
*/
if (x.startsWith("__")) continue;
mar.answers.v2.income[applicant].items[number][x] = data[x];
if (data[x] === null) {
delete mar.answers.v2.income[applicant].items[number][x];
}
// here do the iws
// if (x === "iws") {
// if ("iws" in ob === false) {
// ob.iws = {};
// }
// for (let y in obj[x]) {
// if (y in ob.iws === false) {
// ob.iws[y] = {};
// }
// if (y === "en") {
// for (let z in obj[x][y]) {
// ob.iws[y][z] = obj[x][y][zo];
// }
// }
// }
// } else {
// ob[x] = obj[x]
// }
}
MAR.activity_log.mod("income", mar.answers.v2.income[applicant].items[number].uuid);
return number;
}
}
}
return false;
}
/**
* @memberof MAR.income
*/
function delByUUID(applicant, uuid) {
let obj = getByUUID(uuid, true);
if (obj === false) return false;
return del(obj.appl, obj.idx);
}
/**
* @memberof MAR.income
*/
function del(applicant, number) {
if (arguments.length != 2) return false;
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("income" in mar.answers.v2 == false) return false;
if (mar.answers.v2.income.length <= applicant) return false;
if ("items" in mar.answers.v2.income[applicant] == false) return false;
if (mar.answers.v2.income[applicant].items.length <= number) return false;
MAR.activity_log.del("income", mar.answers.v2.income[applicant].items.uuid);
mar.answers.v2.income[applicant].items.splice(number, 1);
return true;
}
function explode(inc,QI,PROG) {
if (!PROG) PROG = "web";
if (!QI) QI = {};
if (inc.type == "llc") {
var lastyear = num(inc.income_llc_2017);
var prevyear = num(inc.income_llc_2016);
inc.name = inc.name_llc;
/**
* rule:the basic calc is to average out the last 2 years
*/
var val = (((lastyear + prevyear)/2)/12);
inc.warnings=[];
if (val > 0) {
/* rules */
inc.warnings=[];
let warning_type = "income_llc";
if (val > 0) {
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : inc
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
inc.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
}
inc.total = val;
// retval.total += val;
// retval.base[n] += val;
inc.iws = {
enc : {
base : val
}
}
// mar.answers.v2.income[n].llc.total += val;
// mar.answers.v2.income[n].llc.active = (salary_base > 0);
if (inc.uuid in QI) {
let qi_total = QI[inc.uuid];
inc.qi_total = qi_total;
retval.qi_total += qi_total;
} else {
inc.qi_total = false;
retval.qi_total += val;
}
}
}
let othertypes = [
{
"value": "AccessoryUnitIncome",
"text": "Accessory Unit Income"
},
{
"value": "AlimonyChildSupport",
"text": "Alimony/Child Support"
},
{
"value": "AutomobileExpenseAccount",
"text": "Automobile/Expense Account"
},
{
"value": "CapitalGains",
"text": "Capital Gains"
},
{
"value": "EmploymentRelatedAssets",
"text": "Employment Related Assets"
},
{
"value": "FNMBoarderIncome",
"text": "FNM Boarder Income"
},
{
"value": "FNMGovernmentMortgageCreditCertificate",
"text": "FNM Government Mortgage Credit Certificate"
},
{
"value": "ForeignIncome",
"text": "Foreign Income"
},
{
"value": "FosterCare",
"text": "Foster Care"
},
{
"value": "Section8",
"text": "Housing Choice Voucher Program (Section 8)"
},
{
"value": "MilitaryBasePay",
"text": "Military Base Pay"
},
{
"value": "MilitaryClothesAllowance",
"text": "Military Clothes Allowance"
},
{
"value": "MilitaryCombatPay",
"text": "Military Combat Pay"
},
{
"value": "MilitaryFlightPay",
"text": "Military Flight Pay"
},
{
"value": "MilitaryHazardPay",
"text": "Military Hazard Pay"
},
{
"value": "MilitaryOverseasPay",
"text": "Military Overseas Pay"
},
{
"value": "MilitaryPropPay",
"text": "Military Prop Pay"
},
{
"value": "MilitaryQuartersAllowance",
"text": "Military Quarters Allowance"
},
{
"value": "MilitaryRationsAllowance",
"text": "Military Rations Allowance"
},
{
"value": "MilitaryVariableHousingAllowance",
"text": "Military Variable Housing Allowance"
},
{
"value": "Non-borrowerHouseholdIncome",
"text": "Non-borrower Household Income"
},
{
"value": "NotesReceivableInstallment",
"text": "Notes Receivable/Installment"
},
{
"value": "OtherIncome",
"text": "Other Types Of Income"
},
{
"value": "Pension",
"text": "Pension/Retirement Income"
},
{
"value": "MortgageDifferential",
"text": "Real Estate/Mortgage Differential"
},
{
"value": "RoyaltyPayment",
"text": "Royalty Payment"
},
{
"value": "SeasonalIncome",
"text": "Seasonal Income"
},
{
"value": "SocialSecurity",
"text": "Social Security/iility Income"
},
{
"value": "TemporaryLeave",
"text": "Temporary Leave"
},
{
"value": "TipIncome",
"text": "Tip Income"
},
{
"value": "Trust",
"text": "Trust Income"
},
{
"value": "Unemployment",
"text": "Unemployment/Public Assistance"
},
{
"value": "VABenefitsNonEducational",
"text": "VA Benefits NonEducational"
}
];
function getOtherTypeByVal(val, def) {
for (let i=0; i < othertypes.length;i++) {
if (othertypes[i].value == val) return othertypes[i].text;
}
return def;
}
function getOtherTypeByText(val, def) {
for (let i=0; i < othertypes.length;i++) {
if (othertypes[i].text == val) return othertypes[i].value;
}
return def;
}
let getOtherTypesAsArray = function() {
let retval = [];
for (let i=0; i < othertypes.length;i++) {
retval.push(othertypes[i].text)
}
return retval;
}
let name = function(itm, def = "") {
return MAR.getOpt(itm, ["name_k1","name_llc","name_d1099","name"],def);
}
let balance = function(itm) {
return MAR.getOpt(itm, ["name_k1","name_llc","name_d1099","name"],"");
}
return {
/**
* utility functions
*/
init : init, // initialize
recalculate : recalculate,
explode : explode,
/**
* type conversion
*/
getOtherTypeByVal : getOtherTypeByVal,
getOtherTypeByText : getOtherTypeByText,
getOtherTypesAsArray : getOtherTypesAsArray,
isOther : isOther,
/**
* getters and setters
*/
get : get, // get (applicant, type, num)
set : set, // set (applicant, type, num, data)
del : del, // del (applicant, num)
delByUUID : delByUUID, // del (applicant , uuid)
getByUUID : getByUUID, // get by UUID
setByUUID : setByUUID, // set by UUID
getByParentUUID : getByParentUUID, //
getIncome_v2 : getIncome_v2, // link to genIncomeV2
/**
* properties
*/
isPrevious : isPrevious,
isBreak : isBreak,
name : name,
/**
* report and summary
*/
summary : summary,
have2Years : have2Years,
has_w2_with_ownership : has_w2_with_ownership,
has_business_that_generates_w2
: has_business_that_generates_w2,
has_w2_with_ownership_first_name
: has_w2_with_ownership_first_name,
getNextUnverifiedItem : getNextUnverifiedItem,
/**
* object id
*/
__id : "income"
}
})()
/**
* rqObj
* @namespace MAR.rq_obj
*/
var rqObj = (function(){
function breakdown(febe) {
// let febe = mar.tmp_febe_breakdown_obj;
let h = ``;
let lin = function(x,y) {
return `
`;
}
let lin_head = function(x,y) {
return `
`;
}
let lin_sub = function(x,y, lnk = ``) {
let onc = (lnk === ``) ? `` : `onClick="${lnk}"`;
let cls = (lnk === ``) ? `` : `handy`;
return `
`;
}
let lin_tot = function(x,y, lnk = ``) {
return ((lnk === ``) ? `
` : `
`;
}
h += lin_head('
Income ',``);
if (MAR.getOptNum(febe, "reo_inc",0) > 0) {
h += lin_sub('- from work',elaineui.format("cur",(febe.inc - febe.reo_inc)));
h += lin_sub('- from REO',elaineui.format("cur",febe.reo_inc));
}
if (MAR.getOpt(febe, "inc_src","") === "calculated") {
let dm = MAR.getOpt(febe, "inc_details.detailmatrix", []);
if (dm.length > 2) {
for (let i=1; i < (dm.length -1); i++) {
let itm = dm[i];
if (itm.length === 1) {
h += lin(`${itm[0]}`,``);
}
if (itm.length > 1) {
if (MAR.getOpt(itm, `10`,``) === ``) {
h += lin_sub(`${itm[0]}`,elaineui.format("cur",itm[7]));
} else {
h += lin_sub(`${itm[0]}`,elaineui.format("cur",itm[7]),`mar.tmp_open_febe_link('#income-edit.${itm[10]}')`);
}
}
}
h += lin_tot('URLA income',elaineui.format("cur",febe.inc));
h += `
`;
} else {
h += lin_tot('URLA income',elaineui.format("cur",febe.inc));
}
}
else if (MAR.getOpt(febe, "inc_src","") === "scenario") {
h += lin_tot('Quick income',elaineui.format("cur",febe.inc));
}
else {
h += lin_tot('Income not entered',elaineui.format("cur",febe.inc));
}
h += lin_head('
Liabilities ',``);
if (MAR.getOpt(febe, "lia_src","") === "answers") {
h += lin_tot('Quick liailities',elaineui.format("cur",febe.lia));
}
else if (MAR.getOpt(febe, "lia_src","") === "scenario") {
h += lin('Quick liailities',elaineui.format("cur",febe.lia));
}
else if (MAR.getOpt(febe, "lia_src","") === "calculated") {
let dm = MAR.getOpt(febe, "lia_list", []);
if (dm.length > 2) {
for (let i=1; i < (dm.length -1); i++) {
let itm = dm[i];
if (itm.length === 1) {
h += lin(`${itm[0]}`,``);
}
if (itm.length > 1 && itm[0].startsWith("mortga") === false && itm[0].indexOf("") < 0) {
let itm_desc = MAR.liabilities.helper_make_shorter_name(itm[0]);
// let itms = itm[0].split(`:`);
// let type = itms.shift();
//
// let itm_desc = (function() {
// if (type === `child`) return `${itms.join(":")}`;
// if (type === `irstax`) return `${itms.join(":")}`;
// if (itms.length > 0) {
// for (let j=0; j < itms.length; j++) {
// let itm_str = itms[j];
// if (itm_str.startsWith(`Account`) && itm_str.length > 7) {
// itms[j] = `Acc #..${itm_str.substring(7).slice(-4)}`;
// }
// }
// }
// return `${mar._txt(type)} - ${itms.join(":")}`;
//
// })();
if (MAR.getOpt(itm, `17`,``) !== ``) {
h += lin_sub(`${itm_desc}`,elaineui.format("cur",itm[6]), `mar.tmp_open_febe_link('#liabilities-item.0.${itm[17]}')`);
} else {
h += lin_sub(`${itm_desc}`,elaineui.format("cur",itm[6]));
}
}
}
// let _reo_liab_ex_prim = MAR.getOptNum(febe, "_reo._reo_liab_ex_prim", 0);
h += lin_tot('URLA liailities',elaineui.format("cur",febe.lia), `mar.tmp_open_credit()`);
h += `
`;
} else {
h += lin_tot('URLA liailities',elaineui.format("cur",febe.lia), `mar.tmp_open_credit()`);
}
}
else {
h += lin_tot('Liailities not entered',elaineui.format("cur",febe.lia));
}
h += lin_head('
Housing Expenses ',``);
for (let x in febe.monthly_febe) {
let lbl = mar._txt(`rq_lbl_${x}`)
h += lin_sub(`- ${lbl}`,elaineui.format("cur",(febe.monthly_febe[x])));
}
h += lin_tot('Monthly',elaineui.format("cur",febe.monthly_total_febe));
h += `
`;
h += lin_head('
Ratios ',``);
h += `
`;
h += `
FE
`;
h += `
=
`;
h += `
${elaineui.format("cur",febe.monthly_total_febe)}
${elaineui.format("cur",febe.inc)}
`;
h += `
=
`;
h += `
${elaineui.format("perc3",febe.__fe)}
`;
h += `
`;
h += `
`;
h += `
BE
`;
h += `
=
`;
h += `
${elaineui.format("cur",febe.monthly_total_febe)} + ${elaineui.format("cur",febe.lia)}
${elaineui.format("cur",febe.inc)}
`;
h += `
=
`;
h += `
${elaineui.format("perc3",febe.__be)}
`;
h += `
`;
// h += `
${JSON.stringify(febe,null,4)} `;
let $popupelm = $(`.ratequote_popup .topgrid`);
if ($popupelm.length > 0) {
mar.tmp_febe_breakdown_close = function() {
$(`.ratequote_popup .topgrid-details`).html(``)
$(`.ratequote_popup .topgrid-details`).addClass(`x-hide-imp`)
}
h = `
`+
`
FE / BE Breakdown
`+
`${h}`+
`
Close
`+
`
`;
$(`.ratequote_popup .topgrid-details`).html(h)
$(`.ratequote_popup .topgrid-details`).removeClass(`x-hide-imp`)
return;
}
else {
elaineui.swalprompt({
title : "FEBE",
txt : ``,
ok : `ok`
});
}
}
let _defaults = {
Item203KSupplementalOriginationFee:{qm:`Y`,apr:`Y`},
AmortizationFee:{qm:``,apr:`Y`},
ApplicationFee:{qm:`Y`,apr:`Y`},
AutomatedUnderwritingFee:{qm:``,apr:`Y`},
BankruptcyMonitoringFee:{qm:``,apr:``},
BondFee:{qm:``,apr:``},
BondReviewFee:{qm:``,apr:``},
CertificationFee:{qm:``,apr:``},
ChosenInterestRateCreditOrChargeTotal:{qm:`Y`,apr:`Y`},
CommitmentFee:{qm:`Y`,apr:`Y`},
LoanLevelPriceAdjustment:{qm:`Y`,apr:`Y`},
LoanOriginatorCompensation:{qm:`Y`,apr:`Y`},
ManualUnderwritingFee:{qm:`Y`,apr:`Y`},
MortgageBrokerFee:{qm:`Y`,apr:`Y`},
MortgageSurchargeCountyOrParish:{qm:``,apr:``},
MortgageSurchargeMunicipal:{qm:``,apr:``},
MortgageSurchargeState:{qm:``,apr:``},
NewLoanAdministrationFee:{qm:`Y`,apr:`Y`},
OurOriginationChargeTotal:{qm:`Y`,apr:`Y`},
PreclosingVerificationControlFee:{qm:``,apr:``},
ProcessingFee:{qm:`Y`,apr:`Y`},
RateLockFee:{qm:`Y`,apr:`Y`},
RedrawFee:{qm:``,apr:``},
TemporaryBuydownAdministrationFee:{qm:``,apr:`Y`},
UnderwritingFee:{qm:`Y`,apr:`Y`},
TemporaryBuydownPoints:{qm:``,apr:`Y`},
LifeOfLoan:{qm:``,apr:``},
LoanAmountDiscountPoints:{qm:`Y`,apr:`Y`},
//
Item203KArchitecturalAndEngineeringFee:{qm:``,apr:`N`},
Item203KConsultantFee:{qm:``,apr:`Y`},
Item203KDiscountOnRepairs:{qm:``,apr:``},
Item203KTitleUpdate:{qm:`N`,apr:`Y`},
AttorneyFee:{qm:``,apr:`Y`},
CourierFee:{qm:``,apr:`Y`},
CreditDisabilityInsurancePremium:{qm:``,apr:`N`},
CreditLifeInsurancePremium:{qm:``,apr:`N`},
CreditPropertyInsurancePremium:{qm:``,apr:`N`},
CreditUnemploymentInsurancePremium:{qm:``,apr:`N`},
DebtCancellationInsurancePremium:{qm:``,apr:`N`},
DeedPreparationFee:{qm:``,apr:`N`},
DocumentaryStampFee:{qm:``,apr:``},
DocumentPreparationFee:{qm:``,apr:`N`},
ElectronicDocumentDeliveryFee:{qm:`N`,apr:`Y`},
EscrowServiceFee:{qm:``,apr:``},
FilingFee:{qm:`N`,apr:`Y`},
GeneralCounselFee:{qm:``,apr:``},
HighCostMortgageCounselingFee:{qm:``,apr:``},
LendersAttorneyFee:{qm:``,apr:``},
NotaryFee:{qm:`N`,apr:`Y`},
PowerOfAttorneyPreparationFee:{qm:``,apr:`N`},
RecordingFeeForAssignment:{qm:`N`,apr:`Y`},
SigningAgentFee:{qm:`N`,apr:`Y`},
StateTitleInsuranceFee:{qm:``,apr:`N`},
SurveyFee:{qm:``,apr:`N`},
TaxRelatedServiceFee:{qm:`N`,apr:`Y`},
TitleCertificationFee:{qm:`N`,apr:`Y`},
TitleClosingFee:{qm:`N`,apr:`Y`},
TitleClosingProtectionLetterFee:{qm:`N`,apr:`Y`},
TitleDocumentPreparationFee:{qm:``,apr:`N`},
TitleEndorsementFee:{qm:``,apr:`N`},
TitleExaminationFee:{qm:``,apr:`N`},
TitleFinalPolicyShortFormFee:{qm:``,apr:`N`},
TitleInsuranceBinderFee:{qm:``,apr:`N`},
TitleInsuranceFee:{qm:``,apr:`N`},
TitleNotaryFee:{qm:``,apr:`N`},
TitleOwnersCoveragePremium:{qm:``,apr:`N`},
TitleServicesFeeTotal:{qm:``,apr:``},
TitleServicesSalesTax:{qm:``,apr:``},
TitleUnderwritingIssueResolutionFee:{qm:``,apr:``},
//
Item203KArchitecturalAndEngineeringFee:{qm:``,apr:`N`},
Item203KConsultantFee:{qm:``,apr:`Y`},
Item203KDiscountOnRepairs:{qm:``,apr:``},
Item203KInspectionFee:{qm:``,apr:`Y`},
Item203KPermits:{qm:``,apr:`N`},
AppraisalDeskReviewFee:{qm:``,apr:`N`},
AppraisalFieldReviewFee:{qm:``,apr:`N`},
AppraisalManagementCompanyFee:{qm:`N`,apr:`Y`},
AutomatedUnderwritingFee:{qm:`Y`,apr:`Y`},
AVMFee:{qm:``,apr:`N`},
CLOAccessFee:{qm:`N`,apr:`Y`},
FloodCertification:{qm:`N`,apr:`Y`},
MERSRegistrationFee:{qm:`N`,apr:`Y`},
PreclosingVerificationControlFee:{qm:``,apr:``},
PropertyTaxStatusResearchFee:{qm:`N`,apr:`Y`},
RedrawFee:{qm:``,apr:`N`},
ReinspectionFee:{qm:``,apr:``},
TaxRelatedServiceFee:{qm:`N`,apr:`Y`},
VerificationOfAssetsFee:{qm:``,apr:`Y`},
VerificationOfEmploymentFee:{qm:``,apr:`Y`},
VerificationOfIncomeFee:{qm:``,apr:`Y`},
VerificationOfResidencyStatusFee:{qm:``,apr:`Y`},
VerificationOfTaxpayerIdentificationFee:{qm:``,apr:`Y`},
VerificationOfTaxReturnFee:{qm:``,apr:`Y`},
//
TaxStampForCityDeed:{qm:``,apr:`N`},
TaxStampForCityMortgage:{qm:``,apr:`N`},
RecordingFeeForAssignment:{qm:``,apr:`N`},
RecordingFeeForMunicipalLienCertificate:{qm:``,apr:`N`},
RecordingFeeForSubordination:{qm:``,apr:`N`},
PowerOfAttorneyRecordingFee:{qm:``,apr:`N`},
RecordingFeeForDeed:{qm:``,apr:`N`},
RecordingFeeForMortgage:{qm:``,apr:`N`},
TaxStampForCountyDeed:{qm:``,apr:`N`},
TaxStampForCountyMortgage:{qm:``,apr:`N`},
TaxStampForStateDeed:{qm:``,apr:`N`},
TaxStampForStateMortgage:{qm:``,apr:`N`},
Other:{qm:``,apr:``},
//
Item203KPermits:{qm:``,apr:`Y`},
AsbestosInspectionFee:{qm:``,apr:`N`},
CondominiumAssociationDues:{qm:``,apr:`N`},
CondominiumAssociationSpecialAssessment:{qm:``,apr:`N`},
CooperativeAssociationDues:{qm:``,apr:`N`},
CooperativeAssociationSpecialAssessment:{qm:``,apr:`N`},
CreditDisabilityInsurancePremium:{qm:``,apr:`N`},
CreditLifeInsurancePremium:{qm:``,apr:`N`},
CreditPropertyInsurancePremium:{qm:``,apr:`N`},
CreditUnemploymentInsurancePremium:{qm:``,apr:`N`},
DebtCancellationInsurancePremium:{qm:``,apr:`N`},
DryWallInspectionFee:{qm:``,apr:`N`},
ElectricalInspectionFee:{qm:``,apr:`N`},
EnvironmentalInspectionFee:{qm:``,apr:`N`},
HeatingCoolingInspectionFee:{qm:``,apr:`N`},
HomeInspectionFee:{qm:``,apr:`N`},
HomeownersAssociationDues:{qm:``,apr:`N`},
HomeownersAssociationSpecialAssessment:{qm:``,apr:`N`},
HomeWarrantyFee:{qm:``,apr:`N`},
LeadInspectionFee:{qm:``,apr:`N`},
PestInspectionFee:{qm:``,apr:`N`},
PlumbingInspectionFee:{qm:``,apr:`N`},
RadonInspectionFee:{qm:``,apr:`N`},
RealEstateCommissionBuyersBroker:{qm:``,apr:`N`},
RealEstateCommissionSellersBroker:{qm:``,apr:`N`},
RepairsFee:{qm:``,apr:`N`},
RoofInspectionFee:{qm:``,apr:`N`},
SepticInspectionFee:{qm:``,apr:`N`},
SmokeDetectorInspectionFee:{qm:``,apr:`N`},
WaterTestingFee:{qm:``,apr:`N`},
WellInspectionFee:{qm:``,apr:`N`}
};
function default_qm_apr_custom_costs(cost) {
return MAR.getOpt(_defaults, cost, {qm:``,apr:``});
}
return {
breakdown : breakdown,
//
default_qm_apr_custom_costs : default_qm_apr_custom_costs,
//
___id : `rq_obj`
}
})();
/**
* contract
* @namespace MAR.contract
*/
var lockObj = (function(){
function explode_app(app) {
}
return {
___id : `lock object`
}
})();
/**
* contract
* @namespace MAR.contract
*/
var contractObj = function(){
let lockObj = {};
let contractObj = {};
let lockObj_base = {};
let contractObj_base = {};
/**
* set from the db object
*/
function load_from_obj(obj) {
if (typeof obj === "string") {
obj = jsn.parse(obj, {});
}
lockObj = MAR.getOpt(obj, "lock",{});
contractObj = MAR.getOpt(obj, "contract",{});
}
function baseline(){
lockObj_base = JSON.parse(JSON.stringify(lockObj));
contractObj_base = JSON.parse(JSON.stringify(contractObj));
}
/**
* set
*/
function set_lock(k,v) {
lockObj[k] = v;
}
function set_lock_from_encompass(en_pipeline) {
}
function set_lock_from_manual(obj) {
}
function set_lock_from_other(obj) {
}
function get_lock_string_for_pipeline() {
}
function is_different_from_baseline(){
}
function set_contract(k,v) {
contractObj[k] = v;
}
/**
* clear
*/
function clear() {
lockObj = {};
contractObj = {};
}
/**
* get_combined
*/
function get_combined(){
return {
lock : lockObj,
contract : contractObj
}
}
/**
* init
*/
function init() {
//createOpt
MAR.createObt(lockObj, `price` , 0);
MAR.createObt(lockObj, `status` , ``);
MAR.createObt(lockObj, `date` , ``);
MAR.createObt(lockObj, `date_expire` , ``);
MAR.createObt(lockObj, `rate` , 0);
MAR.createObt(lockObj, `days` , 0);
MAR.createObt(lockObj, `prog` , ``);
MAR.createObt(lockObj, `compensation_type` , ``);
MAR.createObt(lockObj, `compensation_factor` , ``);
MAR.createObt(lockObj, `compensation_value` , 0);
MAR.createObt(lockObj, `compensation_in_lo_fee` , `N`);
MAR.createObt(lockObj, `buyout_fee_yn` , `N`);
MAR.createObt(lockObj, `buyout_fee_value` , 0);
MAR.createObt(lockObj, `note` , ``);
}
let lock_statuses = {
none : { txt : `None` },
registered : { txt : `Registered` },
locked : { txt : `Locked` },
expired : { txt : `Expired` },
cancelled : { txt : `Cencelled` },
withdrawn : { txt : `Withdrawn` },
float : { txt : `Float` },
pending : { txt : `Lock Pending` },
registered_man : { txt : `Registered Manual` },
pending_man : { txt : `Lock Pending Manual` },
locked_man : { txt : `Locked Manual` }
}
return {
get_lockObj : function() { return lockObj; }, // get only the lock object
get_Lock : function() { return lockObj; }, // get only the lock object
get_contractObj : function() { return contractObj; }, // get only the contract object
get_Contract : function() { return contractObj; }, // get only the contract object
get_lock_statuses : function() { return lock_statuses; },
get_combined : get_combined, // get combined for saving
//
clear : clear, // empty the contents
init : init, // make any missing data
//
load_from_obj : load_from_obj, // populate from object
set_lock : set_lock, // set key in the lock object
set_l : set_lock,
set_contract : set_contract, // set a key in the contract object
set_c : set_contract,
//
set_lock_from_encompass : set_lock_from_encompass, // set from the encompass data
set_lock_from_manual : set_lock_from_manual, // manual
set_lock_from_other : set_lock_from_other, // other
//
baseline : baseline, // baseline
get_lock_string_for_pipeline : get_lock_string_for_pipeline, // get string summary
//
___id : `Contract object`
}
}
/**
* cpull
* @namespace MAR.cpull
*/
var cpullObj = (function(){
function is_too_old(date) {
if (date === null) return false;
if (date === "") return false;
let dat_diff = (new Date().getTime() - new Date(date).getTime());
dat_diff = dat_diff/1000; // secs
dat_diff = dat_diff/60; // mins
dat_diff = dat_diff/60; // hours
dat_diff = ~~(dat_diff/24); // days
if (dat_diff > 90) {
return true;
}
}
return {
is_too_old : is_too_old,
___id : `cpull object`
}
})();
/**
* liabilities
* @namespace MAR.liabilities
*/
var liabilitiesObj = (function(){
/**
* @memberof MAR.liabilities
*/
function init() {
}
/**
* @memberof MAR.liabilities
*/
function delByUUID(uuid) {
let idx = getByUUID(uuid,true);
if (idx !== false) {
del(idx);
}
}
/**
* @memberof MAR.liabilities
*/
function setByUUID(uuid, obj) {
let idx = getByUUID(uuid,true);
if (idx !== false) {
for (let x in obj) {
mar.answers.v2.liabilities[idx][x] = obj[x];
}
}
}
/**
* @memberof MAR.liabilities
*/
function getByUUID(uuid, returnindex) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("uuid" in _array[i] && _array[i].uuid == uuid) {
if (arguments.length > 1 && returnindex === true) return i;
return _array[i];
}
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function getBySIG(sig) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("sig" in _array[i] && _array[i].sig == sig) return _array[i];
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function getByEncId(enc_uuid) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("enc_uuid" in _array[i] && _array[i].enc_uuid == enc_uuid) return {
i : i,
data : _array[i]
}
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function setLoanLinkByUUID(loanlink , _REO_uuid) {
let loanlinks = loanlink.split(",");
loanlinks.filter(function(ll){
let index = getByUUID(ll, true);
if (typeof index === "number") mar.answers.v2.liabilities[index].reolink = _REO_uuid;
})
}
/**
* @memberof MAR.liabilities
*/
function repair_uuids() {
let _array = get();
let rv = false;
for (let i=0; i < _array.length; i++) {
if ("uuid" in _array[i] === false) {
_array[i].uuid = uuidv4();
rv = true;
}
}
return rv;
}
/**
* @memberof MAR.liabilities
*/
function repair() {
let _array = get();
let rv = false;
for (let i=0; i < _array.length; i++) {
if ("enc_id" in _array[i] === false) {
_array[i].enc_id = getNextLiabilityEncId();
rv = true;
}
}
return rv;
}
/**
* @memberof MAR.liabilities
*/
function is_verified_item(applicantnum, type) {
let vapplicantnum = MAR.applicants.vid(applicantnum);
let items = get(type);
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.verified !== `Y`) continue;
return item;
}
return false
}
/**
* @memberof MAR.liabilities
*/
function getFirstAssignment(ino) {
for (var i=0; i < 8; i++) {
if ((ino & Math.pow(2,i)) == Math.pow(2,i)) return (i);
}
return -1;
}
/**
* @memberof MAR.liabilities
*/
function create(type, applicant, name){
let retval = {};
retval.type = type;
retval.name = name;
retval.inomask = Math.pow(2,applicant);
retval.balance = 0;
retval.monthly = 0;
retval.verified = "N";
return retval;
}
/**
* @memberof MAR.liabilities
*/
function ino_isin(ino, applicant) {
return (ino & Math.pow(2,applicant) == Math.pow(2,applicant))
}
/**
* @memberof MAR.liabilities
*/
function add_unverified_from_declarations() {
let number_of_applicants = MAR.applicants.count();
let opt = "";
for (let i= 0; i < number_of_applicants; i++) {
opt = MAR.declarations.get(i, "credit_obligated_to_pay_alimony_or_child", "");
if (opt === "Y") {
let _array = get("child");
let _found = false;
for (let j=0; j < _array.length; j++) {
let _item = _array[j];
if (ino_isin(_item.inomask, i)) _found = true;
}
if (_found == false) {
let item = create("child", i, "Child/Alimony from declarations");
item._auto_created = "Y";
MAR.liabilities.set("child", false, item);
}
// let follow = MAR.declarations.get(i, "credit_obligated_to_pay_alimony_or_child_followup", "");
// if (follow == "alimony" || follow == "both") {
// let _array = get("alimony");
// let _found = false;
// for (let j=0; j < _array.length; j++) {
// let _item = _array[j];
// if (ino_isin(_item.inomask, i)) _found = true;
// }
// if (_found == false) {
// let item = create("alimony", i, "Alimony from declarations");
// MAR.liabilities.set("alimony", false, item);
//
// }
// }
// if (follow == "child" || follow == "both") {
// let _array = get("child");
// let _found = false;
// for (let j=0; j < _array.length; j++) {
// let _item = _array[j];
// if (ino_isin(_item.inomask, i)) _found = true;
// }
// if (_found == false) {
// let item = create("child", i, "Child from declarations");
// MAR.liabilities.set("child", false, item);
//
// }
// }
}
opt = MAR.declarations.get(i, "credit_delinquent_on_federal_debt", "");
if (opt === "Y") {
let follow = MAR.declarations.get(i, "credit_delinquent_on_federal_debt_type", "");
if (follow == "tax" || follow == "both") {
let _array = get("irstax");
let _found = false;
for (let j=0; j < _array.length; j++) {
let _item = _array[j];
if (ino_isin(_item.inomask, i)) _found = true;
}
if (_found == false) {
let item = create("irstax", i, "IRS Debt");
item.verified = "N";
item._auto_created = "Y";
MAR.liabilities.set("irstax", false, item);
}
}
}
opt = MAR.declarations.get(i, "credit_irs_plan", "");
if (opt === "Y") {
let _array = get("irstax");
let _found = false;
for (let j=0; j < _array.length; j++) {
let _item = _array[j];
if (ino_isin(_item.inomask, i)) _found = true;
}
if (_found == false) {
let item = create("irstax", i, "IRS Debt");
item.verified = "N";
item._auto_created = "Y";
MAR.liabilities.set("irstax", false, item);
}
}
opt = MAR.declarations.get(i, "credit_downpayment_borrowed", "");
if (opt === "Y") {
let _array = get("instalmentloan");
let _found = false;
for (let j=0; j < _array.length; j++) {
let _item = _array[j];
if (ino_isin(_item.inomask, i)) {
if (MAR.getOpt(_item, "_auto_bor_dp","") === "Y") {
_found = true;
}
}
}
if (_found == false) {
let item = create("instalmentloan", i, "Loan for borrowed ");
item.institution = `Borrowed downpayment`;
item.verified = "N";
item._auto_bor_dp = "Y";
item.balance = MAR.declarations.get(i, "credit_downpayment_borrowed_value", "");
MAR.liabilities.set("instalmentloan", false, item);
}
}
opt = MAR.declarations.get(i, "additional_loan", "");
if (opt === "Y") {
let _array = get();
let _found = false;
for (let j=0; j < _array.length; j++) {
let _item = _array[j];
if (ino_isin(_item.inomask, i)) {
if (MAR.getOpt(_item, "_auto_newloan","") === "Y") {
_found = true;
}
}
}
if (_found == false) {
let item = create("instalmentloan", i, "New Loan");
item.institution = `New Loan`;
item.verified = "N";
item._auto_newloan = "Y";
MAR.liabilities.set("instalmentloan", false, item);
}
}
}
}
let is_mortgage_attached = function(item) {
if (MAR.getOpt(item,"reolink","") === "") {
return false
}
return true;
}
let is_mortgage_manual = function(item) {
if (MAR.getOpt(item,"sig","") === "") {
return true;
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function get_unattached_mortgages() {
let _array = get();
let rv = [];
for (let i=0; i < _array.length; i++) {
if (_array[i].type !== "mortgage" && _array[i].type !== "heloc") continue;
let is_attached = is_mortgage_attached(_array[i]);
if (is_attached === false) {
rv.push({
i : i,
item : _array[i]
});
}
}
return rv;
}
/**
* @memberof MAR.liabilities
*/
function get_manual_mortgages() {
let _array = get();
let rv = [];
for (let i=0; i < _array.length; i++) {
if (_array[i].type !== "mortgage") continue;
let is_manual = is_mortgage_manual(_array[i]);
if (is_manual === true) {
rv.push({
i : i,
item : _array[i]
});
}
}
return rv;
}
/**
* @memberof MAR.liabilities
*/
function get_replacement_manual_mortgages_advice() {
let unattached_mortgages = get_unattached_mortgages();
let manual_mortgages = get_manual_mortgages();
let rv = {};
rv.unattached_mortgages = unattached_mortgages;
rv.manual_mortgages = manual_mortgages;
rv.suggestions = [];
if (unattached_mortgages.length === 0) {
rv.status = 0;
return rv;
}
if (manual_mortgages.length === 0) {
rv.status = 0;
return rv;
}
for (let i=0; i < manual_mortgages.length; i++) {
let mm = manual_mortgages[i];
for (let j=0; j < unattached_mortgages.length; j++) {
let um = unattached_mortgages[i];
let mm_bal = num(mm.item.balance);
let um_bal = num(um.item.balance);
if (mm_bal === 0) continue;
if (um_bal === 0) continue;
let diff_perc = Math.abs(((mm_bal/ um_bal) -1)*100);
if (diff_perc > 10) continue;
rv.suggestions.push({
um : um,
mm : mm,
diff_perc : diff_perc
});
}
}
return rv;
}
/**
* @memberof MAR.liabilities
*/
function has_unverified_items() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("verified" in _array[i] == true && _array[i].verified === "N") return true;
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function has_unverified_items_except_mortgages() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if (_array[i].type === "mortgage") continue;
if (_array[i].type === "heloc") continue;
if ("verified" in _array[i] == true && _array[i].verified === "N") return true;
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function getNextUnverifiedItem() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("verified" in _array[i] == true && _array[i].verified === "N") {
return {
i : i,
uuid : _array[i].uuid
}
}
}
return false;
}
let pagenames = {
mortgage : "mortgage",
heloc : "heloc",
alimony : "alimony",
child : "child",
studentloan : "studentloan",
carloan : "carloan",
carlease : "carlease",
instalmentloan : "instalmentloan",
creditcard : "creditcard"
}
function make_link(item, i) {
let type = MAR.getOpt(item, `type`,``);
let pagename = MAR.getOpt(pagenames, type, ``);
if (pagename === ``) {
return false;
}
return `#liabilities-${pagename}.0.${i}`;
}
/**
* @memberof MAR.liabilities
*/
function getNextUnverifiedItem_except_mortgages() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if (_array[i].type === "mortgage") continue;
if (_array[i].type === "heloc") continue;
if ("verified" in _array[i] == true && _array[i].verified === "N") {
return {
i : i,
uuid : _array[i].uuid,
link : make_link(_array[i],i)
}
}
}
return false;
}
/**
* @memberof MAR.liabilities
*/
function get(type, number) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("liabilities" in mar.answers.v2 == false) return false;
if (arguments.length == 0) { // return the array for one applicant
return mar.answers.v2.liabilities;
}
if (arguments.length == 1) { // return the array for one applicant
let retval = [];
for (let i=0; i < mar.answers.v2.liabilities.length; i++) {
if (mar.answers.v2.liabilities[i].type == type) {
mar.answers.v2.liabilities[i]._i = i;
retval.push(mar.answers.v2.liabilities[i])
}
}
return retval;
}
if (typeof number == "string") number = parseInt(number,10);
if (number < mar.answers.v2.liabilities.length) {
return mar.answers.v2.liabilities[number];
}
return false;
}
function getNextLiabilityEncId(){
if ("state" in mar.answers.v2 == false) mar.answers.v2.state = {};
if ("liability_encid" in mar.answers.v2.state == false) mar.answers.v2.state.liability_encid = 3;
if (num(mar.answers.v2.state.liability_encid) < 30) mar.answers.v2.state.liability_encid = 30;
let retval = mar.answers.v2.state.liability_encid;
mar.answers.v2.state.liability_encid++;
return retval;
}
/**
* @memberof MAR.liabilities
*/
function set_from_object(obj) {
let uuid = MAR.getOpt(obj, "uuid", "");
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("liabilities" in mar.answers.v2 == false) mar.answers.v2.liabilities = [];
if (Array.isArray(mar.answers.v2.liabilities) == false) mar.answers.v2.liabilities = [];
let itm = getByUUID(uuid);
if (itm === false) return;
for (let x in obj) {
itm[x] = obj[x];
}
}
/**
* @memberof MAR.liabilities
*/
function set(type, number, data) {
if (arguments.length >= 3) { // return the whole array
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("liabilities" in mar.answers.v2 == false) mar.answers.v2.liabilities = [];
if (Array.isArray(mar.answers.v2.liabilities) == false) mar.answers.v2.liabilities = [];
if (number === false) {
if ("uuid" in data == false) data.uuid = uuidv4();
data.enc_id = getNextLiabilityEncId();
mar.answers.v2.liabilities.push(data);
MAR.activity_log.add("liabilities", data.uuid);
return (mar.answers.v2.liabilities.length -1);
} else {
if (typeof number == "string") number = parseInt(number,10);
if (mar.answers.v2.liabilities.length > number) {
if ("uuid" in mar.answers.v2.liabilities[number] == false) {
if ("uuid" in data == false) data.uuid = uuidv4();
data.enc_id = getNextLiabilityEncId();
// } else {
// data.uuid = mar.answers.v2.assets.items[number].uuid;
}
if ("enc_id" in mar.answers.v2.liabilities[number] == false) {
if ("enc_id" in data == false) data.enc_id = getNextLiabilityEncId()
}
if ("enc_uuid" in mar.answers.v2.liabilities[number] == false) {
if ("enc_uuid" in data == false) data.enc_uuid = data.uuid;
}
for (x in data) {
/**
* update only , don't overwrite!
*/
mar.answers.v2.liabilities[number][x] = data[x];
}
MAR.activity_log.mod("liabilities", mar.answers.v2.liabilities[number].uuid);
// mar.answers.v2.assets.items[number] = data;
return number;
}
}
}
}
/**
* @memberof MAR.liabilities
*/
function del(number) {
if (arguments.length < 0) return false;
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("liabilities" in mar.answers.v2 == false) return false;
if (number >= mar.answers.v2.liabilities.length) return false;
MAR.activity_log.del("liabilities", mar.answers.v2.liabilities[number].uuid);
mar.answers.v2.liabilities.splice(number, 1);
return true;
}
/**
* @memberof MAR.liabilities
*/
function getShortDescription(type) {
if (type === "child") return "Alimony/Child";
return type;
}
let liabilities_reccomendation = (function(liabilities){
let _l = liabilities;
let _objs = [];
function init(){
_objs = [];
if (!_l) return;
for (let i=0; i < _l.length; i++) {
_objs.push({
i : i,
obj : MAR.xsd.lia_factory(_l[i])
});
}
}
function getForApplicant(n) {
return _objs.filter(function(item) {
return (item.obj.assigned().indexOf(n) > -1)
})
}
function getForApplicantType(n, t) {
return _objs.filter(function(item) {
return (item.obj.assigned().indexOf(n) > -1) && (item.obj.raw().type === t)
})
}
function getForApplicantTypeUnverified(n, t) {
return _objs.filter(function(item) {
return (item.obj.assigned().indexOf(n) > -1) && (item.obj.raw().type === t) && (MAR.getOpt(item.obj.raw(), "verified", "Y") === "N")
})
}
function getForApplicantTypeUnverifiedAndNotOmitted(n, t) {
return _objs.filter(function(item) {
if (item.obj.assigned().indexOf(n) === -1) return false;
if (item.obj.raw().type !== t) return false;
if (MAR.getOpt(item.obj.raw(), "_auto_created", "") === "Y") return false;
if (MAR.getOpt(item.obj.raw(), "_auto_bor_dp", "") === "Y") return false;
if (MAR.getOpt(item.obj.raw(), "_auto_newloan", "") === "Y") return false;
if (MAR.getOpt(item.obj.raw(), "verified", "") === "Y") return false;
if (MAR.getOpt(item.obj.raw(), "omit", "") === "Y") return false;
if (MAR.getOpt(item.obj.raw(), "cstatus", "") === "tofillin") return false;
return true;
})
}
function applicantHasAlimony(n) {
let items = getForApplicant(n);
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.obj.raw().type === "child") {
if (item.obj.alimony() > 0) return item;
}
}
return false;
}
function applicantHasChild(n) {
let items = getForApplicant(n);
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.obj.raw().type === "child") {
if (item.obj.child() > 0) return item;
}
}
return false;
}
function applicantHasIrs(n) {
let items = getForApplicant(n);
for (let i=0; i < items.length; i++) {
let item = items[i];
if (item.obj.raw().type === "irsdebt") {
if (item.obj.monthly() > 0) return item;
}
if (item.obj.raw().type === "jsr") {
if (item.obj.raw.name.toLowerCase().indexOf("tax") > -1) {
if (item.obj.monthly() > 0) return item;
}
}
}
return false;
}
let _r = {}
function reccommend() {
let number_of_applicants = MAR.applicants.count();
let opt = "";
let r = [];
let q = [];
let c = [];
_r.number_of_applicants = number_of_applicants;
_r.r = r;
_r.q = q;
_r.c = c;
for (let i= 0; i < number_of_applicants; i++) {
opt = MAR.declarations.get(i, "credit_obligated_to_pay_alimony_or_child", "");
if (opt === "Y") {
let follow = MAR.declarations.get(i, "credit_obligated_to_pay_alimony_or_child_followup", "");
if (follow == "alimony" || follow == "both") {
let hasLiability = applicantHasAlimony(i);
if (hasLiability === false) {
r.push("The client says that they have to pay alimony but there is no alimony in their credit")
}
}
if (follow == "child" || follow == "both") {
let hasLiability = applicantHasChild(i);
if (hasLiability === false) {
r.push("The client says that they have to pay child support but there is no alimony in their credit")
}
}
}
opt = MAR.declarations.get(i, "credit_irs_plan", "");
if (opt === "Y") {
let hasLiability = applicantHasIrs(i);
if (hasLiability === false) {
r.push("The client says that they have an IRS payment plan but there is none in their credit")
}
}
let ccard = getForApplicantTypeUnverifiedAndNotOmitted(i,"creditcard");
if (ccard.length > 0) {
// r.push("The client should be asked if they are not paying any of their creditcards")
q.push(["ask-creditcards",ccard,i]);
}
let carloan = getForApplicantTypeUnverifiedAndNotOmitted(i,"carloan");
if (carloan.length > 0) {
// r.push("The client should be asked if they are not paying any of their carloans")
q.push(["ask-carloans",carloan,i]);
}
let studentloan = getForApplicantTypeUnverifiedAndNotOmitted(i,"instalmentloan");
if (studentloan.length > 0) {
// r.push("The client should be asked if any of the instalment loans are student loans")
q.push(["ask-studentloans",studentloan,i]);
}
(function(){
let items = getForApplicantTypeUnverifiedAndNotOmitted(i,"instalmentloan");
if (items.length > 0) {
// r.push("The client should be asked if they are not paying any of their carloans")
q.push(["ask-instalmentloans",items,i]);
}
})();
let studentloan2 = getForApplicantType(i,"studentloan").filter(function(item){
return (item.obj.raw().cstatus === "tofillin")
})
if (studentloan2.length > 0) {
r.push("The client should be asked to fill in information about these student loans")
q.push(["ask-studentloan",studentloan2,i]);
}
(function(){
let studentloan3 = getForApplicantType(i,"studentloan").filter(function(item){
return (item.obj.raw().cstatus !== "tofillin")
})
for (let j=0; j < studentloan3.length; j++) {
let jj = studentloan3[j].i;
let paytype = studentloan3[j].obj.raw().paytype;
let monthly = studentloan3[j].obj.monthly();
let name = studentloan3[j].obj.raw().name;
r.push(`The client has indicated that liability ${jj} ${name} \$${monthly} pm is a student loan with the type "${paytype}" `)
}
})();
(function(){
let items = getForApplicantType(i,"child").filter(function(item){
let raw = item.obj.raw() ;
return (MAR.getOpt(item.obj.raw(), "cstatus", "") === "")
})
if (items.length > 0) {
// r.push("The client should be asked to fill in information about these Alimon/child suport")
q.push(["ask-child",items,i]);
}
})();
(function(){
let items = getForApplicantType(i,"irstax").filter(function(item){
return (MAR.getOpt(item.obj.raw(), "cstatus", "") === "")
})
if (items.length > 0) {
// r.push("The client should be asked to fill in information about these IRS debts")
q.push(["ask-irs",items,i]);
}
})();
(function(){
let items = getForApplicant(i);
for (let j=0; j < items.length; j++) {
let item = items[j].obj.raw();
if (MAR.getOpt(item, "verified","") !== "Y") {
if (MAR.getOpt(item, "_auto_newloan","") === "Y") q.push(["ask-newloan",[items[j]],i]);
if (MAR.getOpt(item, "_auto_bor_dp","") === "Y") q.push(["ask-borrowed",[items[j]],i]);
}
}
})();
(function(){
let items = getForApplicantType(i,"creditcard").filter(function(item){
return (item.obj.raw().cstatus === "coborrower")
})
for (let j=0; j < items.length; j++) {
let jj = items[j].i;
let paytype = items[j].obj.raw().paytype;
let monthly = items[j].obj.monthly();
let name = items[j].obj.raw().name;
r.push(`The client has indicated that on creditcard "${name}" \$${monthly} pm they are a co-signer, you may be able to exclude this liability `)
}
})();
(function(){
let items = getForApplicantType(i,"instalmentloan").filter(function(item){
return (item.obj.raw().cstatus === "coborrower")
})
for (let j=0; j < items.length; j++) {
let jj = items[j].i;
let paytype = items[j].obj.raw().paytype;
let monthly = items[j].obj.monthly();
let name = items[j].obj.raw().name;
r.push(`The client has indicated that on instalment loan "${name}" \$${monthly} pm they are a co-signer, you may be able to exclude this liability `)
}
})();
(function(){
let items = getForApplicantType(i,"child").filter(function(item){
return (item.obj.raw().cstatus === "ok")
})
for (let j=0; j < items.length; j++) {
let jj = items[j].i;
let monthly = items[j].obj.monthly();
let name = items[j].obj.raw().name;
let ch = items[j].obj.child();
let al = items[j].obj.alimony();
r.push(`The client has indicated that liability "${name}" \$${monthly} pm is a An alimony/child support with the folllowing split child \$${ch}, alimony \$${al}" `)
}
})();
(function(){
let items = getForApplicantType(i,"irstax").filter(function(item){
return (item.obj.raw().cstatus === "ok")
})
for (let j=0; j < items.length; j++) {
let jj = items[j].i;
let monthly = items[j].obj.monthly();
let name = items[j].obj.raw().name;
r.push(`The client has indicated that liability "${name}" \$${monthly} pm is a An IRS plan" `)
}
})();
// (function(){
// let items = getForApplicantType(i,"child").filter(function(item){
// return ("cstatus" in item.obj.raw() === false)
// })
// for (let j=0; j < items.length; j++) {
// let jj = items[j].i;
// let paytype = items[j].obj.raw().paytype;
// let monthly = items[j].obj.monthly();
// let name = items[j].obj.raw().name;
// r.push(`The client has indicated that on creditcard ${jj} ${name} \$${monthly} pm they are a co-signer, you may be able to exclude this liability `)
// }
//
// })();
}
}
return {
init : init,
getForApplicant : getForApplicant,
getForApplicantType : getForApplicantType,
getForApplicantTypeUnverified : getForApplicantTypeUnverified,
getForApplicantTypeUnverifiedAndNotOmitted : getForApplicantTypeUnverifiedAndNotOmitted,
applicantHasChild : applicantHasChild,
applicantHasAlimony : applicantHasAlimony,
applicantHasIrs : applicantHasIrs,
reccommend : reccommend,
reccommendations : _r,
___id : "liabilities reccomendations"
}
});
function get_payoff_omit_action(itm, def = "") {
if (!itm) return def;
let omit = MAR.getOpt(itm, "omit","");
let omit_opt = MAR.getOpt(itm, "omit_opt","");
let payoff = MAR.getOpt(itm, "payoff",false);
let paytype = MAR.getOpt(itm, "paytype","");
if (omit_opt !== "") {
if (omit_opt === "payoff") return `payoff`;
if (omit_opt === "less10pmts") return `omit_less10pmts`;
if (omit_opt === "notpaying") return `omit_notpaying`;
if (omit_opt === "before") return `payoff_before`;
if (omit_opt === "andclose") return `payoff_andclose`;
if (omit_opt === "and-cancel") return `payoff_and-cancel`;
if (omit_opt === "down-to-omit") return `payoff_down-to-omit`;
}
if (omit === "Y" && omit_opt !== "") {
return `omit_${omit_opt}`;
}
if (payoff === true && omit_opt === "") {
return `payoff`;
}
if (payoff === true && omit_opt !== "") {
return `payoff_${omit_opt}`;
}
if (omit === "Y") {
return `omit_notpaying`;
}
if (paytype === "def") {
return "stu_5pc";
}
if (paytype === "ibr") {
return "stu_5pc";
}
return def;
}
function set_payoff_omit_from_action(itm, act) {
if (act === "omit") {
itm.omit = "Y";
itm.omit_opt = "";
itm.payoff = false;
return;
}
if (act === "payoff") {
itm.omit = "N";
itm.omit_opt = "";
itm.payoff = true;
return;
}
if (act === "omit_less10pmts") {
itm.omit = "Y";
itm.omit_opt = "less10pmts";
itm.payoff = false;
return;
}
if (act === "omit_notpaying") {
itm.omit = "Y";
itm.omit_opt = "notpaying";
itm.payoff = false;
return;
}
if (act === "payoff_before") {
itm.omit = "Y";
itm.omit_opt = "before";
itm.payoff = false;
}
if (act === "payoff_andclose") {
itm.omit = "N";
itm.omit_opt = "andclose";
itm.payoff = true;
return;
}
if (act === "payoff_and-cancel") {
itm.omit = "Y";
itm.omit_opt = "and-cancel";
itm.payoff = false;
return;
}
if (act === "payoff_down-to-omit") {
itm.omit = "Y";
itm.omit_opt = "down-to-omit";
itm.payoff = false;
return;
}
if (act === "" || act === "keep") {
itm.omit = "N";
itm.omit_opt = "";
itm.payoff = false;
itm.paytype = "";
}
if (act === "stu_5pc") {
itm.paytype = "def";
itm.omit = "N";
itm.omit_opt = "";
itm.payoff = false;
return
}
}
function redflag_description(s) {
if (s === "l90") return "There have been 90 day late payments on this account";
if (s === "l60") return "There have been 60 day late payments on this account";
if (s === "l30") return "There have been 30 day late payments on this account";
if (s === "pattern") return "There have issued detectedin the last 12 months";
// AsAgreed : Account is being paid on time and according to terms of the credit agreement.
if (s === "BankruptcyOrWageEarnerPlan") return "The exact type could not be determined.";
if (s === "ChargeOff") return "The account was not paid on a timely basis and the debt is being written off as uncollectible by the creditor.";
if (s === "Collection") return "Account has not been paid on a timely basis and is been turned over to an attorney or agency for collection.";
if (s === "CollectionOrChargeOff") return "The exact type could not be determined.";
if (s === "Foreclosure") return "Legal proceedings have been initiated to sell property to settle debt on an unpaid balance.";
if (s === "ForeclosureOrRepossession") return "The exact type could not be determined.";
if (s === "Late30Days") return "Account is between 30 and 59 days past due.";
if (s === "Late60Days") return "Account is between 60 and 89 days past due.";
if (s === "Late90Days") return "Account is betwen 90 and 119 days past due.";
if (s === "LateOver120Days") return "Account is 120 days or more past due.";
if (s === "NoDataAvailable") return "Status of the account is not known.";
if (s === "Repossession") return "Account has not been paid on a timely basis and proceedings have been initiated to repossess collateral property to partially of fully satisfy the debt.";
if (s === "TooNew") return "Account has been recently established and is too new to rate payment history.";
if (s === "WageEarnerPlan") return "Past due debt on an account is being paid according to terms established by a court or agreement with the creditor.";
return s;
}
function helper_make_shorter_name(itm_array /* from getbackend etccc */) {
let itms = itm_array.split(`:`);
let type = itms.shift();
let itm_desc = (function() {
if (type === `child`) return `${itms.join(":")}`;
if (type === `irstax`) return `${itms.join(":")}`;
if (itms.length > 0) {
for (let j=0; j < itms.length; j++) {
let itm_str = itms[j];
if (itm_str.startsWith(`Account`) && itm_str.length > 7) {
itms[j] = `Acc #..${itm_str.substring(7).slice(-4)}`;
}
}
}
return `${mar._txt(type)} - ${itms.join(":")}`;
})();
return itm_desc;
}
function helper_make_shorter_name_for_mismo(itm_str) {
let itms = itm_str.split(`:`);
let itm_desc = (function() {
if (itms.length > 0) {
for (let j=0; j < itms.length; j++) {
let itm_str = itms[j];
if (itm_str.startsWith(`Account`) && itm_str.length > 7) {
itms[j] = `Acc #..${itm_str.substring(7).slice(-4)}`;
}
}
}
return `${itms.join(":")}`;
})();
return itm_desc;
}
return {
init : init,
getByUUID : getByUUID,
delByUUID : delByUUID,
setByUUID : setByUUID,
setLoanLinkByUUID : setLoanLinkByUUID,
//
redflag_description : redflag_description,
//
has_unverified_items : has_unverified_items,
has_unverified_items_except_mortgages : has_unverified_items_except_mortgages,
//
get_unattached_mortgages : get_unattached_mortgages,
get_manual_mortgages : get_manual_mortgages,
get_replacement_manual_mortgages_advice : get_replacement_manual_mortgages_advice,
//
getNextUnverifiedItem : getNextUnverifiedItem,
getNextUnverifiedItem_except_mortgages : getNextUnverifiedItem_except_mortgages,
add_unverified_from_declarations : add_unverified_from_declarations,
//
getByEncId : getByEncId,
//
liabilities_reccomendation : liabilities_reccomendation,
//
getShortDescription : getShortDescription,
//
repair : repair,
repair_uuids : repair_uuids,
//
helper_make_shorter_name : helper_make_shorter_name,
helper_make_shorter_name_for_mismo : helper_make_shorter_name_for_mismo,
//
create : create,
//
pagenames : pagenames,
//
set_payoff_omit_from_action : set_payoff_omit_from_action,
get_payoff_omit_action : get_payoff_omit_action,
//
get : get,
set : set,
set_from_object : set_from_object,
del : del,
//
is_verified_item : is_verified_item, /* (applicantnum , type) */
//
___id : "liabilitiesObj"
}
})()
/**
* reo
* @namespace MAR.scenario
*/
var scenarioObj = (function(){
function cashout_ref_warning(LTV) {
if (MAR.is_refi() === false) return "";
let goal = getScenario_data("refi_goal" , false);
let value = getScenario_data("refi_current_value" , false);
let debt = getScenario_data("refi_current_debt" , false);
let options = getScenario_data("refi_options" , false);
let ltv = (LTV) ? LTV : 0.85
if (goal === false) return "";
if (value === false) return "";
if (debt === false) return "";
if (ltv === false) return "";
if (options !== "cashout") return "";
let max = num(value) * num(ltv) - num(debt);
if (num(goal) > num(max) ) {
return `You need more equity in the property to reach this goal, the max you can reach is ${MAR.format.format("cur",max)}`;
}
return "";
}
function assets_declared_too_low() {
if (MAR.is_refi() === true) return false;
let purchase_target = getScenario_data("purchase_target" , false);
let goals_target_downpayment_perc = getScenario_data("goals_target_downpayment_perc" , false);
let hb_liquid_assets = getScenario_data("hb_liquid_assets" , false);
if (purchase_target === false) return false;
if (goals_target_downpayment_perc === false) return false;
if (hb_liquid_assets === false) return false;
if (purchase_target > 0) {
let actualval = Math.round(num(purchase_target) * (num(goals_target_downpayment_perc)/100));
if (hb_liquid_assets < actualval) {
return true;
}
}
return false;
}
function check_is_cleared_mortgage_out_of_date() {
let da = getScenario_data(`cleared_mortgage_payoff_da`,``);
if (da === ``) return false;
let dat = moment(new Date(da));
let now = moment();
let diff_da = dat.diff(now, "days",true);
if (diff_da < 0) return diff_da;
return false;
}
function set_mortgage_payoff_cleared_value(val, da = false) {
/* -- put this in scenario -- */
setScenario_data(`refi_current_debt`,num(val));
setScenario_data(`cleared_mortgage_payoff_val`,num(val));
if (da !== false && da.trim().length > 0) {
setScenario_data(`cleared_mortgage_payoff_da`,da);
}
setScenario_data(`cleared_mortgage_payoff_ts`,new Date().getTime());
/* -- if refi , ignore -- */
if (MAR.is_refi() !== true) return false;
/* -- if there is no subject property return false -- */
let sp = MAR.reo.getSubjectProperty();
if (sp === false) return false;
/* -- if there is no linked loan , return -- */
if (sp.data.loanlinkA.length === 0) return false;
/* -- get the linked loan -- */
let loan = MAR.liabilities.getByUUID(sp.data.loanlinkA[0]);
if (loan === false || loan === null) return false;
if (num(loan.balance) !== num(val)) {
loan.balance_pre_cleared = loan.balance;
loan.balance = val;
return true;
}
return false;
}
return {
cashout_ref_warning : cashout_ref_warning,
assets_declared_too_low : assets_declared_too_low,
//
set_mortgage_payoff_cleared_value : set_mortgage_payoff_cleared_value,
check_is_cleared_mortgage_out_of_date : check_is_cleared_mortgage_out_of_date,
//
___id : "scenario obj"
}
})();
/**
* reo
* @namespace MAR.reo
*/
var reoObj = (function(){
/**
* @memberof MAR.reo
*/
function init() {
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("reo" in mar.answers.v2 == false) mar.answers.v2.reo = [];
}
/**
* @memberof MAR.reo
*/
function explode_property_address(uuid) {
let property = getByUUID(uuid);
if (property === false) return false;
let zip = MAR.getOpt(addressFromString(property.address), "zip","");
if (zip === "") return false;
let da = MAR.zip2county_full(zip);
property.co_code = da.code;
property.co_name = da.name;
property.area = da.area;
return property;
}
/**
* @memberof MAR.reo
*/
function explode_property(property) {
let zip = MAR.getOpt(addressFromString(property.address), "zip","");
if (zip === "") return false;
let da = MAR.zip2county_full(zip);
property.co_code = da.code;
property.co_name = da.name;
property.area = da.area;
return property;
}
/**
* @memberof MAR.reo
*/
function explode_address(address) {
let property = {
address : address
};
let zip = MAR.getOpt(addressFromString(property.address), "zip","");
if (zip === "") return false;
let da = MAR.zip2county_full(zip);
property.co_code = da.code;
property.co_name = da.name;
property.area = da.area;
return property;
}
/**
* @memberof MAR.reo
*/
function set_scenario_county_from_address(uuid) {
let prop = explode_property_address(uuid);
if (prop === false) return;
let co_name_full = MAR.getOpt(prop, "co_name", "");
if (co_name_full === "") return;
setScenario_data("property_county", co_name_full);
}
/**
* @memberof MAR.reo
*/
function makePropertyTheSubjectUnverifiedSync() {
return new Promise(function(resolve, reject) {
makePropertyTheSubjectUnverified(function(rv){
resolve(rv);
})
});
}
/**
* @memberof MAR.reo
*/
function makePropertyTheSubjectUnverified(fn) {
let sp = getSubjectProperty();
if (sp === false) return;
if (typeof fs === "undefined") {
/**
* we are in the browser
*/
let adr = sp.data;
let _ad = addressFromString(adr.address);
mar.socket.send_and_receive("zip2county",{
zip : _ad.zip
}, function(retval){
let co_code = retval.data.code;
let co_name_full = retval.data.name;
let co_name = MAR.county_name(co_name_full);
let area = retval.data.area;
setScenario_data("property_county", co_name_full);
/**
* do not replace the property type for reverse webhook applications
*/
if (MAR.appnav.loanWasImportedAndNotVerified() !== true || getScenario_data("property_type","") === "") {
if (MAR.getOpt(adr, "property_type","") === "") {
setScenario_data("property_type", adr.property_type);
}
}
setScenario_data("property_details", {
streetAddress : _ad.address,
city : _ad.city,
state : _ad.state,
zip : _ad.zip,
countycode : co_code,
county : co_name
});
if (fn) fn();
});
return;
}
let adr = explode_property_address(sp.data.uuid);
let _ad = addressFromString(adr.address);
let co_code = adr.co_code;
let co_name_full = adr.co_name;
let co_name = MAR.county_name(co_name_full);
let area = adr.area;
setScenario_data("property_county", co_name_full);
if (MAR.getOpt(adr, "property_type","") === "") {
setScenario_data("property_type", adr.property_type);
}
setScenario_data("property_details", {
streetAddress : _ad.address,
city : _ad.city,
state : _ad.state,
zip : _ad.zip,
countycode : co_code,
county : co_name
});
if (fn) fn();
}
/**
* @memberof MAR.reo
*/
function makePropertyTheSubject() {
let sp = getSubjectProperty();
if (sp === false) return;
let adr = sp.data;
let verified = MAR.getOpt(adr, "verified","Y");
if (verified === "N") return;
if (MAR.getOpt(adr, "property_type","") === "") return;
if (MAR.getOpt(adr, "co_code","") === "") return;
if (MAR.getOpt(adr, "co_name","") === "") return;
let _ad = addressFromString(adr.address);
let co_code = adr.co_code;
let co_name_full = adr.co_name;
let co_name = MAR.county_name(co_name_full);
let area = adr.area;
console.log(adr);
debugger;
setScenario_data("property_county", co_name_full);
setScenario_data("property_type", adr.property_type);
// setScenarioData("build_period", "?");
// setScenarioData("property_type_community_options", "?");
// units getPropertyUnits_v2
// area
setScenario_data("property_details", {
streetAddress : _ad.address,
city : _ad.city,
state : _ad.state,
zip : _ad.zip,
countycode : co_code,
county : co_name
});
}
/**
* @memberof MAR.reo
*/
function getByUUID(uuid,ALSOID) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("uuid" in _array[i] && _array[i].uuid == uuid) {
if (arguments.length > 1 && ALSOID === true) {
return {
i : i,
data : _array[i]
}
} else {
_array[i]._i = i;
return _array[i];
}
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function setByUUID(uuid, obj) {
let ob = getByUUID(uuid);
if (ob !== false) {
for (let x in obj) {
ob[x] = obj[x]
}
MAR.activity_log.mod("reo", uuid);
}
}
/**
* @memberof MAR.reo
*/
function getBySIG(sig) {
let _array = this.get();
for (let i=0; i < _array.length; i++) {
if ("sig" in _array[i] && _array[i].sig == sig) return _array[i];
}
return false;
}
/**
* @memberof MAR.reo
*/
function getByREOID(reoid, ALSOID) {
let _array = this.get();
for (let i=0; i < _array.length; i++) {
if ("enc_reoid" in _array[i] && _array[i].enc_reoid == reoid) {
if (arguments.length > 1 && ALSOID === true) {
return {
i : i,
data : _array[i]
}
} else {
return _array[i];
}
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function getByIndex(number) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("reo" in mar.answers.v2 == false) return false;
return mar.answers.v2.reo[number];
}
/**
* @memberof MAR.reo
*/
function get(number) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("reo" in mar.answers.v2 == false) return false;
if (arguments.length == 0) { // return the array for one applicant
return mar.answers.v2.reo;
}
if (typeof number == "string") number = parseInt(number,10);
if (number < mar.answers.v2.reo.length) {
return mar.answers.v2.reo[number];
}
return false;
}
/**
* @memberof MAR.reo
*/
function set(number, data) {
if (arguments.length >= 2) { // return the whole array
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("reo" in mar.answers.v2 == false) mar.answers.v2.assets = {};
if (number === false) {
if ("uuid" in data == false) data.uuid = uuidv4();
mar.answers.v2.reo.push(data);
MAR.activity_log.add("reo", data.uuid);
return (mar.answers.v2.reo.length -1);
} else {
if (typeof number == "string") number = parseInt(number,10);
if (mar.answers.v2.reo.length > number) {
if ("uuid" in mar.answers.v2.reo[number] == false) {
if ("uuid" in data == false) data.uuid = uuidv4();
// } else {
// data.uuid = mar.answers.v2.assets.items[number].uuid;
}
for (x in data) {
/**
* update only , don't overwrite!
*/
mar.answers.v2.reo[number][x] = data[x];
}
MAR.activity_log.mod("reo", mar.answers.v2.reo[number].uuid);
// mar.answers.v2.assets.items[number] = data;
return number;
}
}
}
}
/**
* @memberof MAR.reo
*/
function del(number) {
if (arguments.length < 0) return false;
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("reo" in mar.answers.v2 == false) return false;
if (number >= mar.answers.v2.reo.length) return false;
MAR.activity_log.del("reo", mar.answers.v2.reo[number].uuid);
mar.answers.v2.reo.splice(number, 1);
return true;
}
/**
* @memberof MAR.reo
*/
function getPropertiesByApplicant(n) {
init();
let reolist = mar.answers.v2.reo;
let reo_primary_index = false;
let rvlist = [];
for (let i=0; i < reolist.length; i++) {
if (MAR.getOpt(reolist[i],"whosname","").indexOf(`${n}`) > -1) {
reo_primary_index = i;
rvlist.push({
i : i,
data : reolist[i]
});
}
}
return rvlist;
}
/**
* @memberof MAR.reo
*/
function getCurrentPrimary(n) {
init();
let reolist = mar.answers.v2.reo;
let reo_primary_index = false;
for (let i=0; i < reolist.length; i++) {
if (MAR.getOpt(reolist[i],"reo_use","") == "primary") {
if (MAR.getOpt(reolist[i],"whosname","").indexOf(`${n}`) > -1) {
reo_primary_index = i;
return {
i : i,
data : reolist[i]
}
}
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function _set_reo_property_as_subject_if_matches_property_address() {
if (MAR.is_refi()) {
(function() {
let prop_addr_obj = MAR.getOpt(mar.answers, "v2.scenario.property_details", false);
if (prop_addr_obj === false) return; // no property in scenario
if (MAR.getOpt(prop_addr_obj,"zip", "") === "") return; // unlikely a proper addres if there is no ZIP code
let prop_addr_str = [
MAR.getOpt(prop_addr_obj,"streetAddress","").trim(),
MAR.getOpt(prop_addr_obj,"city","").trim(),
MAR.getOpt(prop_addr_obj,"state","").trim(),
MAR.getOpt(prop_addr_obj,"zip","").trim(),
MAR.getOpt(prop_addr_obj,"unit","").trim()
].join("|");
let reolist = mar.answers.v2.reo;
for (let i=0; i < reolist.length; i++) {
let item = reolist[i];
let addr_str = item.address;
if (typeof addr_str !== "string" || addr_str.trim().length === 0) continue; // exclude empty reo items
if (compareAddresses(addr_str,prop_addr_str)=== true) {
item.is_subject_property = "Y";
}
}
})();
}
}
/**
* @memberof MAR.reo
*/
function getOrCreateSubjectProperty(n) {
_set_reo_property_as_subject_if_matches_property_address();
let sp = MAR.reo.getSubjectProperty();
// ensure there is a subject property
let refi = (getV2_data("loan_type","purchase") !== "purchase");
if (sp === false && refi === true) {
let reolist = mar.answers.v2.reo;
if (reolist.length > 0) {
sp = reolist[0];
sp.is_subject_property = "Y";
} else {
sp = MAR.reo.create({});
sp.is_subject_property = "Y";
MAR.reo.set(false, sp);
}
sp = MAR.reo.getSubjectProperty();
}
return sp;
}
/**
* @memberof MAR.reo
*/
function getSubjectProperty(n) {
init();
let reolist = mar.answers.v2.reo;
for (let i=0; i < reolist.length; i++) {
if (MAR.getOpt(reolist[i],"is_subject_property","") == "Y") {
return {
i : i,
uuid : reolist[i].uuid,
data : reolist[i]
}
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function isSubjectProperty(uuid) {
let sp = getSubjectProperty();
if (sp === false) return false;
if (uuid === sp.uuid) return true;
return false;
}
/**
* @memberof MAR.reo
*/
function getNextUnverifiedItem() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("verified" in _array[i] == true && _array[i].verified === "N") {
return {
i : i,
uuid : _array[i].uuid
}
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function isAnythingVerified() {
let _array = get();
for (let i=0; i < _array.length; i++) {
if ("verified" in _array[i] == true && _array[i].verified === "Y") {
return true;
}
}
return false;
}
/**
* @memberof MAR.reo
*/
function create(obj /*type, address, owner, verified */) {
let _newreo = {};
if ("address" in obj) {
if (typeof obj.address === "string") {
_newreo.address = obj.address;
} else {
_newreo.address = `${MAR.getOpt(obj.address,"address","")}|`+
`${MAR.getOpt(obj.address,"city","")}|`+
`${MAR.getOpt(obj.address,"state","")}|`+
`${MAR.getOpt(obj.address,"zip","")}|`+
``;
}
}
_newreo.reo_use = MAR.getOpt(obj , "type" , "primary");
_newreo.verified = MAR.getOpt(obj , "verified" , "N");
_newreo.whosname = `${MAR.getOpt(obj , "owner" ,"0")}`;
return _newreo;
}
/**
* @memberof MAR.reo
*/
function prop(n , data, def) {
init();
let reolist = mar.answers.v2.reo;
if (reolist.length <= n) return def
let item = reolist[n];
if (data == "tax") return num(MAR.getOpt(item, "loan_tax", def));
if (data == "hoi") return num(MAR.getOpt(item, "loan_insurance", def));
if (data == "hoa") {
if (MAR.getOpt(item, "loan_hoa", false) === false) {
return def;
}
let loan_hoa_freq = num(MAR.getOpt(item, "loan_hoa_freq", "1"));
let loan_hoa = num(MAR.getOpt(item, "loan_hoa", 0));
return (loan_hoa/loan_hoa_freq);
}
return def;
}
function will_display_list_item(item){
if (MAR.getOpt(item, "whosname","") === "") {
item.verified2 = "N";
item.syncnote = `Can you check the ownership on this property please.`;
item.syncsecs = "0";
}
if ("enc_maintenance_C" in item && "enc_maintenance_A" in item) {
if (typeof item.enc_maintenance_C !== "undefined") { // first time through B is undefined
if (num(item.enc_maintenance_A) != num(item.enc_maintenance_C)) {
item.verified2 = "N";
item.syncnote = `Can you check whether the hoa, insurance or tax are correct please.`;
item.syncsecs = "1";
}
}
}
}
function will_display_list(){
if ("reo" in mar.answers.v2 === false) mar.answers.v2.reo = []; // empty REO
let reolist = mar.answers.v2.reo;
for (let i=0; i < reolist.length; i++) {
let item = reolist[i];
will_display_list_item(item);
}
}
function reo_primary_index_fn(i) {
if ("reo" in mar.answers.v2 === false) mar.answers.v2.reo = []; // empty REO
let reolist = mar.answers.v2.reo;
let reo_primary_index = false;
let property_index = false;
for (let j=0; j < reolist.length; j++) {
if (MAR.getOpt(reolist[j],"reo_use","") == "primary") {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${i}`) > -1) {
reo_primary_index = j;
property_index = j;
}
} else {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${i}`) > -1) {
property_index = j;
}
}
}
console.warn(`reo_primary_index ${reo_primary_index}`);
console.warn(`MAR.ownsProperty(${i}) ${MAR.ownsProperty(0)}`);
return reo_primary_index;
}
function normalizeAddress(ad){
if (typeof ad !== "string") return "";
let parts = ad.split("|");
for (let i=0; i < parts.length; i++) {
parts[i] = parts[i].trim().toLowerCase()
}
while (parts.length < 5) {
parts.push("");
}
while (parts.length > 5) {
parts.pop();
}
return parts.join("|");
}
function compareAddresses(ad1,ad2) {
return (normalizeAddress(ad1) === normalizeAddress(ad2));
}
/* -- appnum is the applicant number ad it returns the uuid of the liability containing the mortgage */
function suggest_unconnected_mortgage(appnum) {
let sug = suggest();
for (let i=0; i < sug.length; i++) {
let _sug = sug[i];
if (MAR.getOpt(_sug, `applicant`, -1) !== appnum) continue; /* not the same applicant */
if (MAR.getOpt(_sug, `suggestion`, ``) !== `unconnectedmortgage`) continue; /* not an unconnected mortgage */
let mortgages = MAR.getOpt(_sug, `mortgages`,false); /* abc-123 : { ... json data ... } */
for (let x in mortgages) {
return x;
}
}
return false;
}
function suggest() {
/**
* returns ::
* borrower 0,
* sugestedprimary "address"
*/
let retval = [];
tidyUpReoMortgageLinks();
if ("reo" in mar.answers.v2 === false) mar.answers.v2.reo = []; // empty REO
let reolist = mar.answers.v2.reo;
// for (let j=0; j < reolist.length; j++) {
// let whosname = MAR.getOpt(reolist[j],"whosname","");
// if (whosname === "") {
// let ad = reolist[j].address;
// retval.push({
// applicant : 0,
// suggestion : "propertywithnoowner",
// ad : ad
// })
// }
// }
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
/**
* determine if there is a primary and end up with
*
* reo_primary_index - index of primary property
* property_index - same index but of any type of property
*/
let reo_primary_index = false;
let property_index = false;
let spouse = MAR.getApplicantsSpouse(i);
for (let j=0; j < reolist.length; j++) {
if (MAR.getOpt(reolist[j],"reo_use","") == "primary") {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${i}`) > -1) {
reo_primary_index = j;
property_index = j;
} else if (spouse !== false) {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${spouse}`) > -1) {
reo_primary_index = j;
property_index = j;
}
}
} else {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${i}`) > -1) {
property_index = j;
} else if (spouse !== false) {
if (MAR.getOpt(reolist[j],"whosname","").indexOf(`${spouse}`) > -1) {
property_index = j;
}
}
}
}
// here also check for the spouse
//MAR.getApplicants_JointApplicant
console.warn(`reo_primary_index ${reo_primary_index}`);
console.warn(`MAR.ownsProperty(${i}) ${MAR.ownsProperty(0)}`);
if (reo_primary_index === false) { // we did not find a primary REO property
if (MAR.ownsPrimary(i) == true) { // if we current own realestate , create a new REO block
let a_current = MAR.getApplicantAddressCurrent(i);
if (a_current && a_current.length > 0) {
// retval.push({
// applicant : i,
// suggestion : "add",
// address : a_current[0].address
// })
(function add_to_reo(){
/**
* check for duplicates
*/
let address_to_add = a_current[0].address;
for (let j=0; j < reolist.length; j++) {
let item_address = MAR.getOpt(reolist[j], "address",false);
if (typeof item_address !== "string") {
item_address = MAR.getOpt(reolist[j], "address.address","");
}
if (item_address === address_to_add) {
address_to_add = false;
property_index = j;
break;
}
}
if (address_to_add === false) { /* this is a duplicate */
return;
}
/**
* Add property
*/
let newproperty = MAR.reo.create({
type : "primary",
owner : i,
address : {
address : a_current[0].address
},
verified : "N"
});
if (MAR.is_refi()) {
newproperty.reo_use = "primary";
newproperty.reo_use2 = "primary";
newproperty.property_type = mar.answers.v2.scenario.property_type;
newproperty.value = mar.answers.v2.scenario.refi_current_value;
newproperty.is_subject_property = (MAR.reo.getSubjectProperty() === false) ? "Y" : "N";
}
property_index = MAR.reo.set(false, newproperty);
})()
}
}
} else /* we have a primary */ {
if (MAR.ownsPrimary(i) == false) { // if we current own realestate
let a_current = MAR.getApplicantAddressCurrent(i);
if (a_current && a_current.length > 0) {
let ad1 = a_current[0].address;
let ad2 = reolist[reo_primary_index].address;
retval.push({
applicant : i,
suggestion : "check2",
ad1 : ad1,
ad2 : ad2,
reo_primary_index : reo_primary_index
})
}
} else {
let a_current = MAR.getApplicantAddressCurrent(i);
if (a_current && a_current.length > 0) {
let ad1 = a_current[0].address;
let ad2 = reolist[reo_primary_index].address;
if (compareAddresses(ad1,ad2) === false) {
retval.push({
applicant : i,
suggestion : "check",
ad1 : ad1,
ad2 : ad2,
reo_primary_index : reo_primary_index
})
}
}
}
/**
* now check is the primary is to sell and if this matched NPRF
*/
if (MAR.getOpt(reolist[reo_primary_index], "reo_use2","") === "sell") {
let asset = MAR.assets.get("nprf");
if (asset.length === MAR.zero("no assets")) {
if (MAR.getOpt(reolist[reo_primary_index], "reo_override_nprf","") !== "Y") {
let calculated_nprf = num(MAR.getOpt(reolist[reo_primary_index], "CALC_NPRF",0));
retval.push({
applicant : i,
suggestion : "no_nprf",
ad : reolist[reo_primary_index].address,
calculated_nprf : calculated_nprf,
reo_primary_index : reo_primary_index
})
}
}
if (asset.length > MAR.zero("we have assets")) {
if (MAR.getOpt(reolist[reo_primary_index], "reo_override_nprf","") !== "Y") {
let calculated_nprf = num(MAR.getOpt(reolist[reo_primary_index], "CALC_NPRF",0));
let entered_nprf = num(asset[0].val);
if (calculated_nprf != entered_nprf) {
let ad2 = reolist[reo_primary_index].address;
retval.push({
applicant : i,
suggestion : "diff_nprf",
ad : reolist[reo_primary_index].address,
salesprice : reolist[reo_primary_index].reo_expected_salesprice,
salesperc : reolist[reo_primary_index].reo_expected_salesperc,
loanbalance : reolist[reo_primary_index].LOANBALANCE,
calculated_nprf : calculated_nprf,
entered_nprf : entered_nprf,
assetIndex : asset[0]._i,
reo_primary_index : reo_primary_index
})
}
}
}
}
}
if (property_index === false) {
if (MAR.ownsProperty(i) == true) {
retval.push({
applicant : i,
suggestion : "noproperty"
})
}
}
}
if (MAR.getOpt(mar.answers.v2, "liabilities", null) === null) {
mar.answers.v2.liabilities = [];
}
mar.answers.v2.liabilities.filter(function(item){
if (item.type === "mortgage" || item.type === "heloc") {
if (MAR.getOpt(item,"reolink","") === "") {
if (MAR.getOpt(item, "attached_llc", "") === "Y") return;
let mi = {};
mi[item.uuid] = item;
retval.push({
applicant : 0,
suggestion : "unconnectedmortgage",
mortgages : mi
})
}
}
})
let sp = MAR.reo.getSubjectProperty();
if (sp !== false) {
let spd = sp.data;
if (MAR.getOpt(spd, "verified", "") === "N") {
if (MAR.is_refi()) {
MAR.ifOpt(mar, "answers.v2.scenario.refi_taxes", function(v){
MAR.reo.setByUUID(sp.uuid, { monthly_includes_taxes : MAR.getOpt(mar, "answers.v2.scenario.refi_current_pmt_includes","N")});
MAR.reo.setByUUID(sp.uuid, { loan_tax : num(v) });
});
MAR.ifOpt(mar, "answers.v2.scenario.refi_current_value", function(v){
MAR.reo.setByUUID(sp.uuid, { value : num(v) });
// MAR.reo.setByUUID(sp.uuid, { purchase_price : num(v) });
});
MAR.ifOpt(mar, "answers.v2.scenario.monthly_rent", function(v){
MAR.reo.setByUUID(sp.uuid, { reo_expected_rental : num(v) });
MAR.reo.setByUUID(sp.uuid, { reo_rental_pm : num(v) });
});
MAR.ifOpt(mar, "answers.v2.scenario.property_type", function(v){
MAR.reo.setByUUID(sp.uuid, { property_type : v });
});
MAR.ifOpt(mar, "answers.v2.scenario.hoa_estimate", function(v){
if (num(v) > 0) {
MAR.reo.setByUUID(sp.uuid, { loan_hoa : num(v)*12 });
MAR.reo.setByUUID(sp.uuid, { has_hoa : `Y` });
} else {
MAR.reo.setByUUID(sp.uuid, { has_hoa : `N` });
}
});
MAR.ifOpt(mar, "answers.v2.scenario.refi_home_insurance_cost", function(v){
MAR.reo.setByUUID(sp.uuid, { has_insurance : `Y` });
MAR.reo.setByUUID(sp.uuid, { monthly_includes_insurance : MAR.getOpt(mar, "answers.v2.scenario.refi_current_pmt_includes_ins","N") });
MAR.reo.setByUUID(sp.uuid, { loan_insurance : num(v) });
});
MAR.ifOpt(mar, "answers.v2.scenario.refi_current_debt_mdate", function(v){
MAR.reo.setByUUID(sp.uuid, { purchasedate : v });
});
// let refi_current_debt = getScenario_data("refi_current_debt","");
// let refi_current_value = getScenario_data("refi_current_value","");
// let refi_liquid_assets = getScenario_data("refi_liquid_assets","");
// let goals_target_budget = getScenario_data("goals_target_budget_old","");
// let refi_current_escrow = getScenario_data("refi_current_escrow","");
// let refi_current_debt_mdate = getScenario_data("refi_current_debt_mdate","");
// let refi_taxes = getScenario_data("refi_taxes","");
// let refi_home_insurance_cost= getScenario_data("refi_home_insurance_cost","");
// let hoa_estimate = getScenario_data("hoa_estimate","");
}
}
}
// let mortgagesIndexed = {};
//
// let mortgages = mar.answers.v2.liabilities.filter(function(item){
// if (item.type === "mortgage") {
// mortgagesIndexed[item.uuid] = item;
// return true;
// }
// return false;
// })
// for (let i=0; i < reolist.length; i++) {
// let loanlink = MAR.getOpt(reolist[i],"loanlink","");
// if (loanlink !== "") {
// if (loanlink in mortgagesIndexed) {
// delete mortgagesIndexed[loanlink];
// }
// }
// }
// if (Object.keys(mortgagesIndexed).length > 0) {
// retval.push({
// applicant : 0,
// suggestion : "unconnectedmortgage",
// mortgages : mortgagesIndexed
// })
// }
return retval;
}
function setMortgageOptionsFromReoLinks() {
function getReoByUUID(ID) {
let reolist = MAR.getOpt(mar, "answers.v2.reo", []);
for (let i=0; i < reolist.length; i++) {
let item = reolist[i];
if (item.uuid === ID) return item;
}
}
let reo_array = {};
for (var i=0; i < mar.answers.v2.liabilities.length; i++) {
var item = mar.answers.v2.liabilities[i];
if (!item || item == null) continue;
if (item.type == "mortgage" || item.type == "heloc") {
if ("reolink" in item && item.reolink !== "") {
if (item.reolink in reo_array === false) {
reo_array[item.reolink] = [];
}
reo_array[item.reolink].push(item.uuid);
}
}
}
for (let x in reo_array) {
let R = getReoByUUID(x);
R.mortgageoptions = reoarray[x].join(",");
}
}
function tidyUpReoMortgageLinks() {
function getReoByLoanId(ID) {
let reolist = MAR.getOpt(mar, "answers.v2.reo", []);
for (let i=0; i < reolist.length; i++) {
let item = reolist[i];
if ("mortgageoptions" in item) {
if (typeof item.mortgageoptions === "string" && item.mortgageoptions !== "" && item.mortgageoptions !== "free" && item.mortgageoptions !== "nl") {
let mo = item.mortgageoptions.split(",");
item.loanlink = item.mortgageoptions;
item.loanlinkA = mo;
if (mo.indexOf(ID) > -1) return item.uuid;
} else {
item.loanlink = "";
item.loanlinkA = [];
}
}
}
return false;
}
if (MAR.getOpt(mar, "answers.v2.liabilities", null) === null) return;
for (var i=0; i < mar.answers.v2.liabilities.length; i++) {
var item = mar.answers.v2.liabilities[i];
if (!item || item == null) continue;
if (item.type == "mortgage" || item.type == "heloc") {
let reoitem = getReoByLoanId(item.uuid);
if (reoitem === false) {
MAR.delOpt(item, "reolink");
} else {
item.reolink = reoitem;
}
}
}
}
/**
* @memberof MAR.reo
*/
function is_rent_roll_analysis_needed() {
let _array = get();
for (let i=0; i < _array.length; i++) {
let _reoitem = _array[i];
if ((MAR.getOpt(_reoitem,"skip_nodoc")===false) && (MAR.getOpt(_reoitem, "reo_rental_future_contract", "") === "N") && (MAR.getOpt(_reoitem, "reo_rental_future_contract_rentroll", "") ==="Y")) {
return true;
}
}
return false;
}
return {
init : init,
getByUUID : getByUUID,
getByREOID : getByREOID,
getByIndex : getByIndex,
setMortgageOptionsFromReoLinks : setMortgageOptionsFromReoLinks,
setByUUID : setByUUID,
tidyUpReoMortgageLinks : tidyUpReoMortgageLinks,
makePropertyTheSubject : makePropertyTheSubject,
makePropertyTheSubjectUnverified : makePropertyTheSubjectUnverified,
makePropertyTheSubjectUnverifiedSync : makePropertyTheSubjectUnverifiedSync,
//
explode_property_address : explode_property_address,
explode_property : explode_property,
explode_address : explode_address,
set_scenario_county_from_address : set_scenario_county_from_address,
//
compareAddresses : compareAddresses,
//
get : get,
set : set,
del : del,
suggest : suggest,
reo_primary_index_fn : reo_primary_index_fn,
will_display_list : will_display_list,
will_display_list_item : will_display_list_item,
create : create,
getCurrentPrimary : getCurrentPrimary,
getPropertiesByApplicant : getPropertiesByApplicant,
getSubjectProperty : getSubjectProperty,
getOrCreateSubjectProperty : getOrCreateSubjectProperty,
isSubjectProperty : isSubjectProperty,
getNextUnverifiedItem : getNextUnverifiedItem,
isAnythingVerified : isAnythingVerified,
is_rent_roll_analysis_needed : is_rent_roll_analysis_needed,
prop : prop,
//
// Helper for conditions
//
suggest_unconnected_mortgage : suggest_unconnected_mortgage,
//
___id : "reoObj"
}
})()
var permissionsObj = (function(){
let xsd = {
realtor_permission_loan_calcs_and_docs : "realtor_permission_loan_calcs_and_docs",
realtor_permission_direct_underwriting_report : "realtor_permission_direct_underwriting_report",
realtor_permission_appraisal_information : "realtor_permission_appraisal_information",
}
let pms = {};
let pm = "";
pm = "realtor_permission_loan_calcs_and_docs";
pms[pm] = {};
pms[pm].desc = {
Y : "The client GAVE permission to share calculations and loan documentation with the realtor ",
N : "The client DECLINED to give permissiont o share calculations and loan documentation with the realtor"
};
pm = "realtor_permission_direct_underwriting_report";
pms[pm] = {};
pms[pm].desc = {
Y : "The client GAVE permission to share direct underwriting reports with the realtor ",
N : "The client DECLINED to direct underwriting reports with the realtor"
};
pm = "realtor_permission_appraisal_information";
pms[pm] = {};
pms[pm].desc = {
Y : "The client GAVE permission to share appraisal information with the realtor ",
N : "The client DECLINEDm1 to give permission to share appraisal information with the realtor"
};
function _get(p,val) {
return MAR.getOpt(pms, `${p}.desc.${val}`,false)
}
function makePermsForSummary(ans) {
let perms = [];
let _plcd = MAR.getOpt(ans, "v2.scenario.realtor_permission_loan_calcs_and_docs","");
let _pdur = MAR.getOpt(ans, "v2.scenario.realtor_permission_direct_underwriting_report","");
let _pai = MAR.getOpt(ans, "v2.scenario.realtor_permission_appraisal_information","");
if (_plcd !== "") {
perms.push(MAR.perms.get("realtor_permission_loan_calcs_and_docs",_plcd));
}
if (_pdur !== "") {
perms.push(MAR.perms.get("realtor_permission_direct_underwriting_report",_pdur));
}
if (_pai !== "") {
perms.push(MAR.perms.get("realtor_permission_appraisal_information",_pai));
}
if (perms.length == 0) {
return "";
}
return "Realtor permissons :
";
}
return {
pms : pms,
xsd : xsd,
get : _get,
makePermsForSummary : makePermsForSummary,
___id : "permission"
}
})()
/**
* addresshist
* @namespace addresshist
*/
var addressObj = (function(){
/**
* @memberof addresshist
*/
function init(){
}
function set(i, item) {
console.log(`ADDRESSHIST_SET i[${i}] item[${JSON.stringify(item)}]`);
if (i < 0) return false;
if ("__pre_uuid" in item == true) {
item.uuid = item.__pre_uuid;
let bucketid = `/applicants/address/${i}/${item.uuid}`
item.bucketid = bucketid;
delete item.__pre_uuid;
}
if ("uuid" in item === false) {
let uuid = uuidv4();
let bucketid = `/applicants/address/${i}/${uuid}`
item.uuid = uuid;
item.bucketid = bucketid;
}
if ("addresses" in mar.answers.v2.applicants[i] === false) mar.answers.v2.applicants[i].addresses = [];
let idx = mar.answers.v2.applicants[i].addresses.indexOf(item.bucketid);
if (idx < 0) {
mar.answers.v2.applicants[i].addresses.push(item.bucketid);
}
if (item.bucketid in mar.answers.v2.buckets === false) mar.answers.v2.buckets[item.bucketid] = {};
let bucket = mar.answers.v2.buckets[item.bucketid];
for (x in item) {
bucket[x] = item[x];
}
return item;
}
function getByUUID(uuid) {
for (x in mar.answers.v2.buckets) {
// `/applicants/address/${i}/${uuid}`
if (x.startsWith(`/applicants/address/`) && x.endsWith(`/${uuid}`)) return mar.answers.v2.buckets[x]
}
return false;
}
function delByUUID(uuid) {
for (x in mar.answers.v2.buckets) {
// `/applicants/address/${i}/${uuid}`
if (x.startsWith(`/applicants/address/`) && x.endsWith(`/${uuid}`)) {
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
let adresses = MAR.getOpt(mar.answers.v2.applicants[i], "addresses",[]);
let idx = adresses.indexOf(x);
if (idx > -1) mar.answers.v2.applicants[i].addresses.splice(idx,1);
}
}
}
}
return {
init : init,
set : set,
getByUUID : getByUUID,
delByUUID : delByUUID,
____id : "address object"
}
})()
/**
* assets
* @namespace MAR.assets
*/
var activity_logObj = (function(){
function add(type, uuid, e1, e2, e3) {
let role = (typeof __ROLE === "string") ? __ROLE : "norole";
if (role.length === 0) role = "norole";
if (arguments.length > 2) uuid = `${uuid} ${e1}`;
if (arguments.length > 3) uuid = `${uuid} ${e2}`;
if (arguments.length > 4) uuid = `${uuid} ${e3}`;
MAR.pushOpt(mar.answers, "_activity_log", `${role} ${type} add ${uuid}`);
}
function del(type, uuid, e1, e2, e3) {
let role = (typeof __ROLE === "string") ? __ROLE : "norole";
if (role.length === 0) role = "norole";
if (arguments.length > 2) uuid = `${uuid} ${e1}`;
if (arguments.length > 3) uuid = `${uuid} ${e2}`;
if (arguments.length > 4) uuid = `${uuid} ${e3}`;
MAR.pushOpt(mar.answers, "_activity_log", `${role} ${type} delete ${uuid}`);
}
function mod(type, uuid, e1, e2, e3) {
let role = (typeof __ROLE === "string") ? __ROLE : "norole";
if (role.length === 0) role = "norole";
if (arguments.length > 2) uuid = `${uuid} ${e1}`;
if (arguments.length > 3) uuid = `${uuid} ${e2}`;
if (arguments.length > 4) uuid = `${uuid} ${e3}`;
MAR.pushOpt(mar.answers, "_activity_log", `${role} ${type} modify ${uuid}`);
}
return {
add : add,
del : del,
mod : mod,
modify : mod,
update : mod,
___id : "activity log"
}
})();
/**
* supdata
* @namespace MAR.supdata
*/
var supdataObj = (function(){
function tp_from_code(code) {
if (code.indexOf("_TP.") > -1) {
let TP = code.substring(code.indexOf("_TP.")).split(" ")[0].split("/")[0];
if (TP !== "") {
return TP;
}
}
return "";
}
function Y(tp) {
if (typeof tp !== "string") return false;
let tps = tp.split(".");
if (tps.length < 3) return false;
return tps[1];
}
function M(tp) {
if (typeof tp !== "string") return false;
let tps = tp.split(".");
if (tps.length < 3) return false;
return tps[2];
}
function range(tp, days=30 , period_end_day = 31, PERIOD = "monthly") {
let y = Y(tp);
let m = M(tp);
if (y === false || m === false) {
return false;
}
let dp2 = function(n) {
if (n < 10) return `0${n}`;
return `${n}`;
}
let dom = new Date().getDate(); // todays day of month
let rv = {};
let decrement = 0;
if (num(period_end_day) > dom) {
decrement = 1;
}
let end_m = num(m) - decrement;
let end_y = num(y);
if (end_m < 1) {
end_y--;
end_m+=12;
}
if (PERIOD === "quarterly") {
if (num(m) % 3 !== 1) {
end_m = Math.floor((num(m)-1)/3)*3;
if (end_m < 1) {
end_y--;
end_m+=12;
}
}
}
let dec_m = (~~(days/30));
if (dec_m === 0) dec_m = 1;
if (PERIOD === "quarterly") {
dec_m = 3;
period_end_day = 31;
}
let start_m = num(end_m) - dec_m;
let start_y = num(end_y);
if (start_m < 1) {
start_y--;
start_m+=12;
}
let _period_end_day = function(m , d) {
let rv = d;
if (num(d) > 31) rv = 31;
if (num(m) === 4 && rv > 30) return 30;
if (num(m) === 6 && rv > 30) return 30;
if (num(m) === 9 && rv > 30) return 30;
if (num(m) === 11 && rv > 30) return 30;
if (num(m) === 2 && rv > 28) return 28;
return rv;
}
rv.decr = decrement;
rv.period_end_day = period_end_day;
rv.dom = dom;
rv.y = y;
rv.m = m;
rv.dec_m = dec_m;
rv.sd = `20${start_y}-${dp2(start_m)}-${dp2(num(_period_end_day(start_m,period_end_day)))}`;
rv.sd = moment(rv.sd).add(1,"day").format("YYYY-MM-DD"); /* add 1 day */
rv.ed = `20${end_y}-${dp2(end_m)}-${dp2(num(_period_end_day(end_m,period_end_day)))}`;
return rv;
}
function tp_disp_from_code_hidden(code) {
let rv = tp_disp_from_code(code);
if (rv !== "") {
return ``;
} else {
return ``;
}
}
function tp_disp_from_code(code) {
if (code.indexOf("_TP.") > -1) {
let YM = code.substring(code.indexOf("_TP.")+2).split("_")[0].split(".");
var Y = (YM.length > 1) ? YM[1] : "";
var M = (YM.length > 2) ? YM[2] : "";
if (Y !== "") {
return ` Up to ${Y}-${M}`;
}
}
return "";
}
let months = [
`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`
];
function tp_disp_from_code_short(code,prefix = "") {
if (code.indexOf("_TP.") > -1) {
let YM = code.substring(code.indexOf("_TP.")+2).split("_")[0].split(".");
var Y = (YM.length > 1) ? YM[1] : "";
var M = (YM.length > 2) ? YM[2] : "";
if (Y !== "") {
return `${prefix}${months[num(M)-1]}`;
}
}
return "";
}
let tputils = (function(){
/**
* is this condition cleared based on the cleared data
*/
let isCleared = function(tp, cleared_items, stars) {
for (let i=0; i < cleared_items.length; i++) {
if (arguments.length === 2) {
if (cleared_items[i].full_id.endsWith(`${tp}`)) {
return true;
}
} else {
if (cleared_items[i].full_id.endsWith(`${tp}/${stars}`)) {
return true;
}
}
}
return false;
}
/**
* make a map range with
* ** : 0
* *** : 1
* **** : 2
* ***** : 3
*/
function map_range_to_cleared_data(tp, cleared_items) {
let map_range = {};
let map_i = 0;
for (let i=0; i < 5; i++) {
let k = "*******".substring(0,i+2); /* ** or *** or **** */
if (isCleared(tp, cleared_items, k)) continue;
map_range[k] = map_i;
map_i++;
}
return map_range;
}
return {
isCleared : isCleared,
//
map_range_to_cleared_data : map_range_to_cleared_data,
//
___id : "clear data utils"
}
})();
let clearingutils = (function() {
// thanks to https://stackoverflow.com/questions/39113692/moment-js-how-do-you-get-the-current-quarter-and-previous-three-quarters-along-w?rq=1
function lastq_end() {
return moment().quarter(moment().quarter()).subtract(1, 'Q').endOf('quarter').format("YYYY-MM-DD");
}
function lastq_start() {
return moment().quarter(moment().quarter()).subtract(1, 'Q').startOf('quarter').format("YYYY-MM-DD");
}
// months
function lastm_1_end() {
return moment().month(moment().month()).subtract(1, 'months').endOf('month').format("YYYY-MM-DD");
}
function lastm_1_start() {
return moment().month(moment().month()).subtract(1, 'months').startOf('month').format("YYYY-MM-DD");
}
function lastm_2_end() {
return moment().month(moment().month()).subtract(2, 'months').endOf('month').format("YYYY-MM-DD");
}
function lastm_2_start() {
return moment().month(moment().month()).subtract(2, 'months').startOf('month').format("YYYY-MM-DD");
}
return {
// quarters
lastq_start : lastq_start,
lastq_end : lastq_end,
// weeks
lastm_start : lastm_1_start,
lastm_end : lastm_1_end,
lastm_1_start : lastm_1_start,
lastm_1_end : lastm_1_end,
lastm_2_start : lastm_2_start,
lastm_2_end : lastm_2_end
}
})();
let utils = (function(){
let aname = function(needsidArray,n){
if (getApplicantsNames_v2().length < 2) return "";
var applicantid = (typeof needsidArray === "number") ? needsidArray : MAR.applicants.id(needsidArray[n]);
var applicant_name = getApplicantsNames_v2(Number(applicantid)).Names;
return applicant_name;
}
let AAname = function(needsidArray,n){
var applicantid = (typeof needsidArray === "number") ? needsidArray : MAR.applicants.id(needsidArray[n]);
var applicant_name = getApplicantsNames_v2(Number(applicantid)).Name;
return applicant_name;
}
let Aname = function(needsidArray,n){
if (getApplicantsNames_v2().length < 2) return "";
var applicantid = (typeof needsidArray === "number") ? needsidArray : MAR.applicants.id(needsidArray[n]);
var applicant_name = getApplicantsNames_v2(Number(applicantid)).Name;
return applicant_name;
}
let aname6 = function(needsidArray,n){
if (getApplicantsNames_v2().length < 2) return "";
var applicantid = (typeof needsidArray === "number") ? needsidArray : MAR.applicants.id(needsidArray[n]);
var applicant_name = getApplicantsNames_v2(Number(applicantid)).Name;
return C6(applicant_name);
}
let bname = function(needsidArray,n){
if (getApplicantsNames_v2().length < 2) return "";
var applicantid = (typeof needsidArray === "number") ? needsidArray : MAR.applicants.id(needsidArray[n]);
var applicant_name = getApplicantsNames_v2(Number(applicantid)).Name;
return applicant_name;
}
let _aname = function(needsidArray,n){
return dash(aname(needsidArray,n));
}
let _Aname = function(needsidArray,n){
return dash(Aname(needsidArray,n));
}
let Aname_ = function(needsidArray,n){
return dash_end(Aname(needsidArray,n));
}
let _aname6 = function(needsidArray,n){
return dash(aname6(needsidArray,n));
}
let aname6_ = function(needsidArray,n){
return dash_end(aname6(needsidArray,n));
}
let _bname = function(needsidArray,n){
return dash(bname(needsidArray,n));
}
let bname_ = function(needsidArray,n){
return dash_end(bname(needsidArray,n));
}
let dash = function(S) {
if (!S || S.trim().length === 0) return "";
return `${S.capitalize()} - `;
return ` - ${S}`;
}
let dash_end = function(S) {
if (!S || S.trim().length === 0) return "";
return `${S.capitalize()} - `;
}
let comma = function(S,S1,S2,S3) {
if (arguments.length < 4) S3 = "";
if (!S || S.trim().length === 0) return `${S2}${S3}`;
return `${S}${S1}${S3}`;
}
return {
aname : aname,
//
AAname : AAname,
Aname : Aname,
//
aname6 : aname6,
_aname6 : _aname6,
aname6_ : aname6_,
//
bname : bname,
_bname : _bname,
bname_ : bname_,
//
_aname : _aname,
_Aname : _Aname,
Aname_ : Aname_,
//
dash : dash,
dash_end : dash_end,
comma : comma,
//
___id : "supdata utils"
}
})();
return {
tp_from_code : tp_from_code,
tp_disp_from_code : tp_disp_from_code,
tp_disp_from_code_short : tp_disp_from_code_short,
tp_disp_from_code_hidden : tp_disp_from_code_hidden,
Y : Y,
M : M,
range : range,
//
tputils : tputils,
cleardatautils : tputils,
//
clearingutils : clearingutils,
//
utils : utils,
___id : "supdata"
}
})();
/**
* devops
* @namespace MAR.devops
*/
var devopsObj = (function(){
let errorcodes = {
"cpull-noresponse" : {
client : `There is no response from the credit agency - chck that the SSN is valid`
},
"cpull-locked" : {
client : `File is locked at the request of the client`
},
"cpull-frozenbc" : {
client : `File is frozen at the request of the client`
},
"cpull-frozen" : {
client : `File is frozen, no report is available`
},
"cpull-invalidssn" : {
client : `One of the SSNs is invalid or missing`
},
"cpull-loginerror" : {
client : `There is a log error pulling credit, check your password in the sttings menu (top right)`
}
}
function errorcode(code) {
if (arguments.length === 0) {
return errocodes;
}
let rv = MAR.getOpt(errorcodes, code, false);
return rv;
}
return {
errorcode : errorcode,
___id : "devops obj"
}
})();
/**
* assets
* @namespace MAR.assets
*/
var assetsObj = (function(){
/**
* @memberof MAR.assets
*/
function init(){
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("assets" in mar.answers.v2 == false) mar.answers.v2.assets = {};
if ("items" in mar.answers.v2.assets == false) {
mar.answers.v2.assets.items = []
}
}
/**
* @memberof MAR.assets
*/
function type_to_editor(TYP) {
if (TYP =="checking") TYP = "bank";
if (TYP =="savings") TYP = "savings";
if (TYP =="proceedsfromsale") TYP = "nprf";
return TYP;
}
/**
* @memberof MAR.assets
*/
function recalculate() {
}
/**
* @memberof MAR.assets
*/
function summary() {
}
/**
* @memberof MAR.assets
*/
function getLast4sItems() {
let _array = get();
let retval = [];
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if (_array[i].type == "emd") continue;
if (_array[i].type != "bank" && _array[i].type != "savings") continue;
retval.push({
uuid : _array[i].uuid,
type : _array[i].type,
bank : _array[i].institution_name,
balance : _array[i].balance,
last4digits : MAR.getOpt(_array[i], "last4digits",""),
item : _array[i]
})
}
return retval;
}
/**
* @memberof MAR.assets
*/
function getLast4s() {
let _array = get();
let retval = [];
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if (_array[i].type == "emd") continue;
if ("last4digits" in _array[i]) {
let last4digits = _array[i].last4digits;
if (last4digits.trim().length > 0) {
if (retval.indexOf(last4digits) < 0) {
retval.push(last4digits)
}
}
}
}
return retval;
}
/**
* @memberof MAR.assets
* To cater for either
* abc_1 = abc
* abc = abc
* _abc_1 = _abc
* _abc = _abc
*/
function matchingPart(S) {
if (typeof S !== "string") return S;
if (S.startsWith("_")) {
return `_${S.substring(1).split("_")[0]}`
}
return S.split("_")[0];
}
/**
* @memberof MAR.assets
*/
function getByUUID(uuid,ALSOID) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("uuid" in _array[i] && _array[i].uuid == matchingPart(uuid)) {
if (arguments.length > 1 && ALSOID === true) {
return {
i : i,
data : _array[i]
}
} else {
return _array[i];
}
}
}
return false;
}
/**
* @memberof MAR.assets
*/
function getByUUID_full(uuid,ALSOID) {
let _array = get();
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("uuid" in _array[i] && _array[i].uuid == uuid) {
if (arguments.length > 1 && ALSOID === true) {
return {
i : i,
data : _array[i]
}
} else {
return _array[i];
}
}
}
return false;
}
/**
* @memberof MAR.assets
*/
function getByGID(gid) {
let _array = get();
let _items = [];
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("gid" in _array[i] && _array[i].gid === matchingPart(gid)) {
_items.push(_array[i]);
}
}
return _items;
}
/**
* @memberof MAR.assets
*/
function setAnyEmptyBankStatements() {
let _array = get();
let _items = [];
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if (_array[i] === false) continue;
if ("gid" in _array[i] && _array[i].gid !== "") {
let bs = ("bank_statement" in _array[i]) ? _array[i].bank_statement : "";
let ba = ("business_account" in _array[i]) ? _array[i].business_account : "";
let wn = ("whose_name" in _array[i]) ? _array[i].whose_name : "";
let key = "auto";
key += (ba === "Y") ? "-BUS-" : "-PRI-";
console.log(`FOCUS wn ${wn} ${typeof wn}`)
key += `${wn}`.split(",").join("-")
if (bs === "" || bs.startsWith("auto")) {
_array[i].bank_statement = key;
}
}
}
}
/**
* @memberof MAR.assets
*/
function getByGIDandStatement(gid) {
let _array = get();
let _items = [];
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if (_array[i] === false) continue;
if ("gid" in _array[i] && _array[i].gid == matchingPart(gid)) {
let bs = ("bank_statement" in _array[i]) ? _array[i].bank_statement : "";
if (gid.substring(1).split("_").length === 1 && bs === "") {
_array[i].__editi = i;
_items.push(_array[i]);
} else if (bs === gid.substring(1).split("_")[1]) {
_array[i].__editi = i;
_items.push(_array[i]);
}
}
}
return _items;
}
/**
* @memberof MAR.assets
*/
function setByUUID(uuid, obj) {
let ob = getByUUID(uuid);
if (ob !== false) {
for (let x in obj) {
if (obj[x] === null) {
MAR.delOpt(ob, x)
} else {
ob[x] = obj[x];
}
MAR.activity_log.modify("assets", uuid);
}
}
}
/**
* @memberof MAR.assets
*/
let bank_account_types = ["bank", "savings"];
/**
* @memberof MAR.assets
*/
function getBankAccounts() {
let _array = get();
let _items = {};
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
let gid = MAR.getOpt(_array[i], "gid", false);
let type = MAR.getOpt(_array[i], "type", false);
let name = MAR.getOpt(_array[i], "institution_name", false);
if (gid === false || gid === "") continue;
if (type === false || type === "") continue;
if (name === false || name === "") continue;
if (bank_account_types.indexOf(type) < 0) continue;
if (gid in _items === true) continue;
_items[gid] = { name : name, type : type };
}
return _items;
}
/**
* @memberof MAR.assets
*/
function getByENCID(encid) {
let _encid = encid.split("/");
let gid = _encid[0];
let gidindex = _encid[1];
let _array = get();
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("gid" in _array[i] && _array[i].gid == gid) {
if ("gidindex" in _array[i] && num(_array[i].gidindex) == num(gidindex)) {
return {
i : i,
data : _array[i]
};
}
}
}
return false;
}
/**
* @memberof MAR.assets
* get all the logins for automaticly linked assets
*/
function getNextUnverifiedItem() {
let _array = this.get();
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("verified" in _array[i] && _array[i].verified === "N") {
return {
i : i,
uuid : _array[i].uuid
}
}
}
return false;
}
/**
* @memberof MAR.assets
* get all the logins for automaticly linked assets
*/
function getLogins() {
let retval = [];
let _array = this.get();
for (let i=0; i < _array.length; i++) {
if (MAR.getOpt(_array[i], "__deleted", "") === "Y") continue;
if ("sys" in _array[i] && _array[i].sys && typeof _array[i].sys == "string" && _array[i].sys.trim().length > 0) {
retval.push({
i : i,
uuid : _array[i].uuid,
sys : _array[i].sys
})
}
}
return retval;
}
/**
* @memberof MAR.assets
*/
function addGidsToItems(items) {
let gids = {}
for (let i=0; i < items.length; i++) {
if (MAR.getOpt(items[i], "__deleted", "") === "Y") continue;
if (items[i] === false) continue;
if ("gid" in items[i] == false) {
items[i].gid = items[i].uuid;
}
if (items[i].gid in gids == false) {
gids[items[i].gid] = [items[i].uuid]
} else {
gids[items[i].gid].push(items[i].uuid);
}
}
for (let i=0; i < items.length; i++) {
items[i].gids = gids[items[i].gid]
}
}
/**
* @memberof MAR.assets
*/
function isThereAGift() {
let items = get("gift");
if (items == false) return false;
if (items.length > 0) return true;
return false;
}
/**
* @memberof MAR.assets
*/
function get(type, number) {
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("assets" in mar.answers.v2 == false) return false;
if ("items" in mar.answers.v2.assets == false) mar.answers.v2.assets.items = []
addGidsToItems(mar.answers.v2.assets.items);
if (arguments.length == 0) { // return the array for one applicant
return mar.answers.v2.assets.items;
}
if (arguments.length == 1) { // return the array for one applicant
let retval = [];
for (let i=0; i < mar.answers.v2.assets.items.length; i++) {
let ass = mar.answers.v2.assets.items[i];
if (MAR.getOpt(ass, "__deleted", "") === "Y") continue;
if (mar.answers.v2.assets.items[i].type == type) {
mar.answers.v2.assets.items[i]._i = i;
retval.push(mar.answers.v2.assets.items[i])
}
}
return retval;
}
if (typeof number == "string") number = parseInt(number,10);
if (number < mar.answers.v2.assets.items.length) {
return mar.answers.v2.assets.items[number];
}
return false;
}
function getNextAssetEncId(){
if ("state" in mar.answers.v2 == false) mar.answers.v2.state = {};
if ("asset_encid" in mar.answers.v2.state == false) mar.answers.v2.state.asset_encid = 18;
let retval = mar.answers.v2.state.asset_encid;
mar.answers.v2.state.asset_encid++;
return retval;
}
function repairGroups2() {
let itms = mar.answers.v2.assets.items;
for (let i=0; i < itms.length; i++) {
let itm = itms[i];
if (MAR.getOpt(itm, "__deleted", "") === "Y") continue;
// if ("gids" in itm && "gid" in itm && itm.gid !== itm.uuid && "gidindex" in itm && itm.gidindex == 0) {
// itm.gidindex = itm.gids.indexOf(itm.uuid);
// }
if (itm === false) continue;
if ("gids" in itm && "gid" in itm && itm.gid !== itm.uuid && "gidindex" in itm && itm.gidindex !== itm.gids.indexOf(itm.uuid)) {
itm.gidindex = itm.gids.indexOf(itm.uuid);
}
if ("gids" in itm && "gid" in itm && itm.gid !== itm.uuid && "gidindex" in itm && "enc_id" in itm && typeof itm.enc_id === "string" && itm.enc_id.endsWith(`/${itm.gidindex}`) === false) {
itm.enc_id = itm.enc_id.split("/")[0] + `/${itm.gidindex}`
}
}
}
function repairGroups() {
let itms = mar.answers.v2.assets.items;
let gids = {};
for (let i=0; i < itms.length; i++) {
let itm = itms[i];
if (MAR.getOpt(itm, "__deleted", "") === "Y") continue;
if ("gid" in itm) {
if (itm.gid in gids == false) {
gids[itm.gid] = [false,false,false,false,false,false,false,false];
}
if ("gidindex" in itm === true) {
gids[itm.gid][itm.gidindex] = itm.uuid;
}
}
}
for (let i=0; i < itms.length; i++) {
let itm = itms[i];
if (MAR.getOpt(itm, "__deleted", "") === "Y") continue;
if ("gidindex" in itm === false) {
for (let j=0; j < gids[itm.gid].length; j++) {
if (gids[itm.gid][j] === false) {
gids[itm.gid][j] = itm.uuid;
itm.gidindex = j;
break;
}
}
}
}
}
/**
* @memberof MAR.assets
*/
function set(type, number, data) {
if (arguments.length >= 3) { // return the whole array
if ("answers" in mar == false) mar.answers = {};
if ("v2" in mar.answers == false) mar.answers.v2 = {};
if ("assets" in mar.answers.v2 == false) mar.answers.v2.assets = {};
if ("items" in mar.answers.v2.assets == false) {
mar.answers.v2.assets.items = []
}
if (number === false) {
if ("__pre_uuid" in data == true) {
data.uuid = data.__pre_uuid;
delete data.__pre_uuid;
}
if ("uuid" in data == false) data.uuid = uuidv4();
if ("gid" in data == false) {
data.gid = data.uuid;
if ("gidindex" in data == false) {
data.gidindex = 0;
}
}
data.enc_id = getNextAssetEncId() // non mutable encompass id number
mar.answers.v2.assets.items.push(data);
MAR.activity_log.add("assets", data.uuid);
repairGroups();
repairGroups2();
return (mar.answers.v2.assets.items.length -1);
} else {
if (typeof number == "string") number = parseInt(number,10);
if (mar.answers.v2.assets.items.length > number) {
if ("uuid" in mar.answers.v2.assets.items[number] == false) {
if ("__pre_uuid" in data == true) {
data.uuid = data.__pre_uuid;
delete data.__pre_uuid;
}
if ("uuid" in data == false) data.uuid = uuidv4();
data.enc_id = getNextAssetEncId()
}
if ("gid" in mar.answers.v2.assets.items[number] == false) {
if ("gid" in data == false) {
data.gid = data.uuid;
if ("gidindex" in data == false) {
data.gidindex = 0;
}
}
}
if ("enc_id" in mar.answers.v2.assets.items[number] == false) {
if ("enc_id" in data == false) data.enc_id = getNextAssetEncId()
}
for (x in data) {
/**
* update only , don't overwrite!
*/
if (x.startsWith("__")) continue;
mar.answers.v2.assets.items[number][x] = data[x];
if (data[x] === null) {
delete mar.answers.v2.assets.items[number][x];
}
}
MAR.activity_log.modify("assets", mar.answers.v2.assets.items[number].uuid);
// mar.answers.v2.assets.items[number] = data;
repairGroups();
repairGroups2();
return number;
}
}
}
}
/**
* @memberof MAR.assets
*/
function deleteByUUID(uuid) {
console.log(`DELETING asset uuid [${uuid}]`);
let index = getByUUID(uuid,true);
console.log(`DELETING asset index`,index);
if (index !== false) {
console.log(`DELETING asset index .i ${index.i}`);
let dr = del(index.i)
console.log(`DELETED asset index .i ${index.i} dr ${dr}`);
}
}
/**
* @memberof MAR.assets
*/
function deleteByENCID(uuid) {
console.log(`DELETING asset uuid [${uuid}]`);
let index = getByENCID(uuid,true);
console.log(`DELETING asset index`,index);
if (index !== false) {
console.log(`DELETING asset index .i ${index.i}`);
let dr = del(index.i)
console.log(`DELETED asset index .i ${index.i} dr ${dr}`);
}
}
/**
* @memberof MAR.assets
*/
function del(number) {
if (arguments.length < 0) return false;
if ("answers" in mar == false) return false;
if ("v2" in mar.answers == false) return false;
if ("assets" in mar.answers.v2 == false) return false;
if ("items" in mar.answers.v2.assets == false) return false;
console.log(`DELETED asset number ${number}, arr length [${mar.answers.v2.assets.items.length}] `);
if (number >= mar.answers.v2.assets.items.length) return false;
console.log(`DELETED asset number ${number} PRE`);
MAR.activity_log.del("assets",mar.answers.v2.assets.items[number].uuid);
mar.answers.v2.assets.items[number].__deleted = "Y";
// mar.answers.v2.assets.items.splice(number, 1);
console.log(`DELETED asset number ${number} POST`);
return true;
}
/**
* @memberof MAR.assets
*/
let othertypes = [
{
"value": "MutualFund",
"text": "Mutual Funds"
},
{
"value": "CertificateOfDepositTimeDeposit",
"text": "Certificate Of Deposit"
},
{
"value": "OtherLiquidAssets",
"text": "Other Liquid Assets"
},
{
"value": "OtherNonLiquidAssets",
"text": "Other Non Liquid Assets"
},
{
"value": "MoneyMarketFund",
"text": "Money Market Fund"
},
{
"value": "TrustAccount",
"text": "Trust Account"
},
{
"value": "GiftOfEquity",
"text": "Gift Of Equity"
},
{
"value": "CashOnHand",
"text": "Cash On Hand"
},
{
"value": "LotEquity",
"text": "Lot Equity"
},
{
"value": "BridgeLoanNotDeposited",
"text": "Bridge Loan Not Deposited"
},
{
"value": "SecuredBorrowedFundsNotDeposited",
"text": "Secured Borrowed Funds Not Deposited"
},
{
"value": "CashDepositOnSalesContract",
"text": "Cash Deposit On Sales Contract"
},
{
"value": "NetWorthOfBusinessOwned",
"text": "Net Worth Of Business Owned"
},
{
"value": "NetEquity",
"text": "Net Equity"
},
{
"value": "Other",
"text": "Other"
},
{
"value": "StockOptions",
"text": "Stock Options"
},
{
"value": "Bond",
"text": "Bond"
},
{
"value": "IndividualDevelopmentAccount",
"text": "Individual Development Account"
},
{
"value": "LifeInsurance",
"text": "Life Insurance"
},
{
"value": "Annuity",
"text": "Annuity"
},
{
"value": "Automobile",
"text": "Automobile"
},
{
"value": "Boat",
"text": "Boat"
},
{
"value": "BorrowerPrimaryHome",
"text": "Borrower Primary Home"
},
{
"value": "EmployerAssistedHousing",
"text": "Employer Assisted Housing"
},
{
"value": "LeasePurchaseFund",
"text": "Lease Purchase Fund"
},
{
"value": "ProceedsFromSecuredLoan",
"text": "Proceeds From Secured Loan"
},
{
"value": "ProceedsFromUnsecuredLoan",
"text": "Proceeds From Unsecured Loan"
},
{
"value": "PendingNetSaleProceedsFromRealEstateAssets",
"text": "Pending Net Sale Proceeds From Real Estate Assets"
},
{
"value": "ProceedsFromSaleOfNonRealEstateAsset",
"text": "Proceeds From Sale Of Non Real Estate Asset"
},
{
"value": "LeasePurchaseCredit",
"text": "Lease Purchase Credit"
},
{
"value": "RecreationalVehicle",
"text": "Recreational Vehicle"
},
{
"value": "RelocationFunds",
"text": "Relocation Funds"
},
{
"value": "SavingsBond",
"text": "Savings Bond (FHA/VA)"
},
{
"value": "SeverancePackage",
"text": "Severance Package"
},
{
"value": "SweatEquity",
"text": "Sweat Equity"
},
{
"value": "TradeEquityFromPropertySwap",
"text": "TradeEquity From Property Swap"
}
];
function getOtherTypeByVal(val, def) {
for (let i=0; i < othertypes.length;i++) {
if (othertypes[i].value == val) return othertypes[i].text;
}
return def;
}
function getOtherTypeByText(val, def) {
for (let i=0; i < othertypes.length;i++) {
if (othertypes[i].text == val) return othertypes[i].value;
}
return def;
}
let getOtherTypesAsArray = function() {
let retval = [];
for (let i=0; i < othertypes.length;i++) {
retval.push(othertypes[i].text)
}
return retval;
}
function suggest() {
/**
* returns ::
* borrower 0,
* sugestedprimary "address"
*/
let retval = [];
let itms = mar.answers.v2.assets.items;
for (let i=0; i < itms.length; i++) {
let itm = itms[i];
if (MAR.getOpt(itm, "__deleted", "") === "Y") continue;
if (itm.type ==="tbd") {
retval.push({
applicant : 0,
suggestion : "notype",
index : i,
item : itm
})
}
}
return retval;
}
let fields = {
uuid : "uuid",
institution_name : "Text",
can_take_freely : "Y/N",
dont_pay_taxes : "Y/N",
whose_name : "[0,1] array",
balance : "dollars"
};
return {
/**
* utility functions
*/
init : init, // initialize
recalculate : recalculate,
repairGroups : repairGroups, // repair gidindexes
repairGroups2 : repairGroups2, // repair gidindexes
/**
* fields
*/
FIELDS : fields,
/**
* type conversion
*/
getOtherTypeByVal : getOtherTypeByVal,
getOtherTypeByText : getOtherTypeByText,
getOtherTypesAsArray : getOtherTypesAsArray,
/**
* getters and setters
*/
addGidsToItems : addGidsToItems, // addGidsToItems
get : get, // get (applicant, type, num)
getByUUID : getByUUID, // get by uuid
getByUUID_full : getByUUID_full, // get by uuid including _1
deleteByUUID : deleteByUUID, // delete by uuid
deleteByENCID : deleteByENCID, // delete by encompass id
getByGID : getByGID, // get item(s) by gid
getByGIDandStatement
: getByGIDandStatement, // get by gid_statement
setAnyEmptyBankStatements
: setAnyEmptyBankStatements,
getByENCID : getByENCID, // get by encid with is gid/0,1,2,3
getBankAccounts : getBankAccounts, // get all bank accounts
set : set, // set (applicant, type, num)
setByUUID : setByUUID, // partial set by uuid
del : del, // del (num)
/**
* misc
*/
suggest : suggest, // suggest
/**
* UI
*/
type_to_editor : type_to_editor, // editor types
/**
* report sand summary
*/
getLast4s : getLast4s, // get an array of the last4 digits
getLast4sItems : getLast4sItems, // as above but with the details o the items
summary : summary,
getLogins : getLogins, // get the list of "sys" logins on assets
getNextUnverifiedItem
: getNextUnverifiedItem, // get next un-verified item
isThereAGift : isThereAGift, // is there a gift as an asset
/**
* object id
*/
__id : "income"
}
})()
let testObj = (function(){
function lia_scenario1() {
for (let i=0; i < mar.answers.v2.liabilities.length; i++) {
let lia = mar.answers.v2.liabilities[i];
lia.verified = "N";
lia.cstatus = "";
if (lia.type === "studentloan") {
lia.type = "instalmentloan";
}
}
}
return {
lia_scenario1 : lia_scenario1, /* rest all to unverified, and studentloans to instalmentloans */
___id : "Test object"
}
})();
/**
* @namespace MAR.master_router
*/
var master_router = (function(){
/**
* @memberof MAR.master_router
*/
let routes = {
"0100" : false,
"0200" : false,
"0300" : false,
"0400" : false,
"0500" : false,
"0600" : false,
"0700" : false,
"0800" : false,
"1000" : false,
"1100" : false,
"1200" : false,
"1300" : false,
"2000" : false,
"2100" : false,
"2200" : false,
"2300" : false,
"2150" : false,
"2350" : false,
"3000" : false,
"3100" : false,
"3200" : false,
"3300" : false,
"4000" : false,
"4100" : false,
"4200" : false,
"5000" : false,
"5100" : false,
"5200" : false,
"6000" : false,
"6100" : false,
"6200" : false,
"7000" : false,
"7100" : false,
"9999" : false
}
/**
* @memberof MAR.master_router
*/
let states = {
NO : 0,
REACHED : 1,
PASSED : 2
}
/**
* @memberof MAR.master_router
*/
function addroutestoapp(ans) {
if ("v2" in ans == false) return false;
if ("scenario" in ans.v2 == false) return false;
let retval = false;
/**
* create routes id not there
*/
if ("routes" in ans.v2.scenario == false) {
ans.v2.scenario.routes = {};
retval = true;
}
/**
* fill in any empty items
*/
for (x in routes) {
if (x in ans.v2.scenario.routes == false) {
ans.v2.scenario.routes[x] = states.NO;
retval = true;
}
}
return retval;
}
/**
* @memberof MAR.master_router
*/
function passed(ans, sec, val) {
if (arguments.length == 2) {
if (sec in ans.v2.scenario.routes) {
return ans.v2.scenario.routes[sec];
}
return false;
}
if (arguments.length == 3) {
if (sec in ans.v2.scenario.routes) {
if (ans.v2.scenario.routes[sec] != val) {
ans.v2.scenario.routes[sec] = val;
return true;
}
} else {
ans.v2.scenario.routes[sec] = val;
return true;
}
return false;
}
}
/**
* @memberof MAR.master_router
*/
function wherearewe() {
}
/**
* @memberof MAR.master_router
*/
function decision_pt1() {
}
let pages = (function(){
let pgobj = {
"scenario_nav": "",
"scenario-loantype": "Loan Tyope",
"scenario-timeframe": "Timeframe",
"scenario-location": "Location",
"scenario-creditscore": "Credit score",
"scenario-property": "Property type",
"scenario-mcc": "MCC",
"scenario-occupancy1": "Occupancy",
"scenario-occupancy": "Occupancy",
"scenario-summary": "",
"scenario-borrowers": "Borrowers",
"scenario-borrower": "Borrower",
"scenario-legalstatus": "Legal Status",
"scenario-veteran": "Veteran",
"scenario-ratequote": "Rate quote",
"scenario-pastproperty": "Past ownership",
"scenario-hoi": "HOI",
"scenario-hoa": "HOA",
"scenario-tax": "TAX",
"makepopup": "",
"scenario-mortgageyes3": "Mortgage",
"scenario-mortgage": "Mortgage",
"scenario-magic2": "",
"scenario-magic3": "",
"scenario-magic1": "",
"scenario-crossroads": "",
"calcs": "",
"scenario-housingbudget": "Housing budget",
"upmy": "",
"scenario-c2c": "",
"scenario-purchaseprice": "",
"scenario-budget": "",
"scenario-budget1": "",
"lox-thanks": "",
"lox": "Homework",
"income-how": "",
"income-summary": "",
"income-w2": "Income - W2",
"income-w2manual": "Income - W2",
"income-DD1099": "Income 1099",
"income-w2-previous": "Income previous",
"income-employer": "Income employer",
"income-llc": "Income LLC",
"income-k1": "Income K1",
"income-rental": "Income Rental",
"income-disability": "Income Disability",
"income-child-support": "Income Child support",
"income-alimony": "Income Alimony",
"income-social-security": "Income Social Security",
"income-pension": "Income Pension",
"income-other": "Income Other",
"assets-choice": "",
"assets-suggestion": "",
"assets-checkings": "Assets Bank",
"assets-bankconnect": "",
"assets-importedaccounts": "",
"assets-bank": "Assets Bank",
"assets-savings": "Assets Savings",
"assets-k401": "Assets 401k",
"assets-ira": "Assets IRA",
"assets-stock": "Assets Stock",
"assets-cash": "Assets Cash",
"assets-gifts": "Assets Gifts",
"assets-emd": "Assets EMD",
"assets-nprf": "Assets NPRF",
"assets-other": "Assets Other",
"assets-summary": "Assets Summary",
"assets-bankOld": "",
"scenario-personaldata": "Personal Data",
"scenario-personaldata1": "Personal Data P2",
"scenario-personaldata2": "Personal Data P3",
"scenario-addresshistory": "Address History",
"scenario-checkpersonaldatac1": "",
"authorizations-credit-ed": "",
"liabilities-home-old": "",
"liabilities-home": "Liabilities - Home",
"liabilities-item": "Liabilities - item",
"liabilities-choice": "Liabilities - Choice",
"liabilities-report": "Liabilities - Report",
"liabilities-child": "Liabilities - Child",
"liabilities-jre": "Liabilities - JRE",
"liabilities-irstax": "Liabilities - IRS Tax",
"liabilities-creditcard": "Liabilities - Creditcard",
"liabilities-studentloan": "Liabilities - StudentLoan",
"liabilities-carloan": "Liabilities - Car Loan",
"liabilities-carlease": "Liabilities - Car Lease",
"liabilities-instalmentloan": "Liabilities - instalment Loan",
"liabilities-installmentloan": "Liabilities - installment Loan",
"liabilities-childsupport": "Liabilities - Child Support",
"liabilities-alimony": "Liabilities - Alimony",
"liabilities-irstax1": "Liabilities - IRS Tax 1",
"liabilities-other": "Liabilities - Other",
"liabilities-summary": "Liabilities - Summary",
"up-next-employmentinfo": "",
"up-next": "",
"up-next-wishlist": "",
"up-next-income-inbetween": "",
"up-next-income": "",
"up-next-liabilities": "",
"up-next-homework": "",
"up-next-prescan": "",
"up-next-personalinfo": "",
"up-next-personalinfonext": "",
"up-next-expect": "",
"up-next-assets": "",
"up-next-lox": "",
"logged-out": "",
"declarations-p1": "Declarations 1",
"declarations-p2": "Declarations 2",
"declarations-p3": "Declarations 3",
"scenario-realtor": "Realtor",
"scenario-realtorinfo": "realtor Info",
"videointro2": "",
"licenses": "",
"privacy": "",
"legal": "",
"nmls": "",
"scenario-end": "",
"evaluate-section": "",
"ext-checkings": "",
"review": "",
"scenario-mortgageyes": "",
"scenario-mortgageyes2": "",
"makeNewpopup": "",
"makeC2Cpopup": "",
"loanofficer": "Loan Officer",
"realtor": "Realtor",
"intro-2fa": "",
"scenario-whatsapp": "Whatsapp",
"loanproposal-home": "",
"general-aboutus": "",
"general-route": "",
"general-comments": "",
"general-faq": "",
"general-comms": "",
"reo-home": "REO Home",
"reo-suggestion": "",
"reo-property": "REO property",
"reo-property-connectedloan": "",
"import-encompass-intro": "",
"import-encompass-upnext-submit": "",
"submit": "",
"import-encompass-unverfied-income-change": "",
"import-encompass": "",
"update-encompass": "",
"flow-confirmtakeover": "",
"flow-reconfirm": "",
"flow-reconfirm-assets": "",
"flow-reconfirm-personaldata": "",
"flow-reconfirm-income": "",
"flow-reconfirm-applicnatconfirmed": "",
"flow-test": "",
"flow-flex": "",
"scenario-subjectproperty": "Subject Property",
"copilot_custom_listener": ""
};
function name(code) {
if (code.startsWith("#")) code = code.substring(1);
let i = -1;
for (let x in pgobj) {
i++;
if (code.startsWith(`${x}`)) {
let txt = pgobj[x];
if (txt.length === 0) return {i : i, txt : code};
return {i : i, txt : txt};
}
}
return {i : -1, txt : code};
}
return {
name : name,
___id : "pages object"
};
})();
return {
routes : routes,
addroutestoapp : addroutestoapp, // add route to answers, returns true if any changes were made
addroutestoanswers : addroutestoapp,
passed : passed,
states : states,
pages : pages,
___id : "master_routes"
}
})();
function resetroute(R) {
if (arguments.length == 0 || R == "income") {
delScenario_data("__income_passed");
delScenario_data("__income_passed_0");
delScenario_data("__income_passed_1");
delScenario_data("__income_passed_2");
delScenario_data("__income_unin_passed_0");
delScenario_data("__income_unin_passed_1");
delScenario_data("__income_unin_passed_2");
}
}
/**
* @namespace MAR.loxBuilder
*/
var loxBuilder = (function() {
/**
* @memberof MAR.loxBuilder
*/
var lox = {};
/**
* @memberof MAR.loxBuilder
*/
function init() {
lox = {
questions : []
};
}
/**
* @memberof MAR.loxBuilder
*/
function setTo(email, tel, name) {
let _sendarray = [];
if (email) _sendarray.push("e:"+email);
if (tel) _sendarray.push("t:"+tel);
if (name) _sendarray.push("n:"+name);
lox.sendto = _sendarray.join(",");
}
/**
* @memberof MAR.loxBuilder
*/
function setSign(email, tel, name) {
let _sendarray = [];
if (email) _sendarray.push("e:"+email);
if (tel) _sendarray.push("t:"+tel);
if (name) _sendarray.push("n:"+name);
lox.signby = _sendarray.join(",");
}
/**
* @memberof MAR.loxBuilder
*/
function setNeed(s) {
lox.need = s;
}
/**
* @memberof MAR.loxBuilder
*/
function setFilename(s) {
lox.filename = s;
}
/**
* @memberof MAR.loxBuilder
*/
function setAppid(s) {
lox.appid = s;
}
/**
* @memberof MAR.loxBuilder
*/
function addQuestion(type,merge,data,name,question,html,admin,hide) {
let q = {};
q.type = (type) ? type : "text";
q.merge = (merge) ? merge : "";
q.data = (data) ? data : "";
q.name = (name) ? name : "";
q.question = (question) ? question : "";
if (q.type == "text") {
"
"
} else {
"
"
}
q.admin = (admin) ? admin : "N";
q.hide = (hide) ? hide : "N";
lox.questions.push(q);
}
/**
* @memberof MAR.loxBuilder
*/
function addQuestionSimple(q,a) {
lox.questions.push({
question : q,
answerset : "simple",
data : a
})
}
/**
* @memberof MAR.loxBuilder
*/
function render() {
if ("signby" in lox == false) {
lox.signby = lox.sendto
}
if ("ids" in lox == false) lox.ids = "";
if ("type" in lox == false) lox.type = "";
return lox;
}
/**
* @memberof MAR.loxBuilder
*/
function renderRequest() {
/**
* ids : id number of fragments to combine
*
* appid : application id
*
* send_to : list of people to send to in the format
* e:email,t:smsnumber,n:Jonathan Carter
*
* Sign_by : list of people to sign the evential doc
* e:email,n:J carter|e:email,n:S Carter
*
* filename : the filename to put this into for signing
*
* type : the type (t4506 , fragment, econsent)
*
* questions : if there are questions then the ids are not necessary and this is one time submit
*
*/
return {
ids : "",
appid : lox.appid,
send_to : lox.sendto,
sign_by : ("signby" in lox) ? lox.signby : lox.sendto,
filename : lox.filename,
type : ("type" in lox) ? lox.signby : "fragment",
questions : questions
}
}
return {
init : init,
setTo : setTo,
setSign : setSign,
setNeed : setNeed,
setAppid : setAppid,
setFilename : setFilename,
addQuestion : addQuestion,
addQuestionSimple : addQuestionSimple,
render : render,
renderRequest : renderRequest,
___id : "lox builder"
}
})();
let mortgageNavigator = (function() {
function ic_getMortgagesFromRates(ic_rates) {
let retval = [];
let cnt_total = 0;
let cnt_total1 = [];
let cnt_matched = 0;
for (let i=0; i < ic_rates.length; i++) {
let rate = ic_rates[i];
let xrate = rate.rate; // 3.75
let xrow = rate.row; // r0
if ("master" in rate == false) continue;
if ("MI" in rate.master == false) continue;
for (x in rate.master.MI) {
let addMortgage = function(xmortgage,alt,key) {
if (xmortgage == false) return;
cnt_total += xmortgage.total_loans_calculated;
if (xmortgage.filters._qmpass == false) return;
//if (xmortgage.filters.apr > (xmortgage.pricing_apor + 1.5)) return;
if (xmortgage.filters.rate > (xmortgage.pricing_apor + 1.5)) return;
// rebuttleable consumption
//xmortgage.filters.__apr = `${xmortgage.pricing_apor} - ${xmortgage.filters.apr} = ${xmortgage.pricing_apor - xmortgage.filters.apr}`;
let uuid = `${xrow}_${x}_${key}`;
xmortgage.filters.uuid = uuid;
xmortgage.filters.programme = xmortgage.input_scenario.scenario.programme;
xmortgage.filters.MI = x;
xmortgage.filters.mmi = xmortgage.final_mi;
xmortgage.filters.mmip = xmortgage.final_mi_py;
xmortgage.filters.ufmip = xmortgage.final_ufmi_py;
xmortgage.filters.abdr = xmortgage.bd_price_inc_llpa;
xmortgage.filters.mi_audit = xmortgage.mi_audit;
xmortgage.filters.m_pay = xmortgage.final_monthly_payment;
xmortgage.filters.m_tax = xmortgage.final_monthly_tax;
xmortgage.filters.m_hoa = xmortgage.final_hoa;
xmortgage.filters.m_hoi = xmortgage.final_hoi;
xmortgage.filters.m_flood = xmortgage.final_flood;
// h += mar._txt(mortgage.input_scenario.v2.programme);
// h += elaineui.format("cur", mortgage.filters.downpayment);
// h += elaineui.format("cur", mortgage.filters.max_loan);
// h += elaineui.format("perc2", mortgage.final_ltv);
// h += mortgage.credit_score;
// h += elaineui.format("perc2",mortgage.final_ufmi_py);
// h += elaineui.format("cur",mortgage.final_ufmi);
cnt_matched++;
retval.push({
uuid : uuid,
master_type : xmortgage.master_type,
rate : xrate,
frate : xmortgage.filters.rate,
xrate : xmortgage.filters.xrate,
//loitab : xmortgage.loitab,
alt : alt,
row : xrow,
mi : x,
mortgage : xmortgage,
filters : xmortgage.filters
});
}
let xxmortgage = ("master_return" in rate.master.MI[x] != false) ? rate.master.MI[x].master_return : false;
addMortgage(xxmortgage,false,"max");
if ("master_return_scenario" in rate.master.MI[x]) {
addMortgage(rate.master.MI[x].master_return_scenario,false,"sce");
}
if ("master_return_alt" in rate.master.MI[x]) {
for (let j=0; j < rate.master.MI[x].master_return_alt.length; j++) {
addMortgage(rate.master.MI[x].master_return_alt[j],true,`alt${j}`);
}
}
if ("master_return_alt1" in rate.master.MI[x]) {
for (let j=0; j < rate.master.MI[x].master_return_alt1.length; j++) {
addMortgage(rate.master.MI[x].master_return_alt1[j],true,`alt_1_${j}`);
}
}
}
}
return {
items : retval,
cnt_total1 : cnt_total1,
cnt_total : cnt_total,
cnt_matched : cnt_matched
}
}
function ic_getMortgages(ic) {
if (!ic) return [];
if ("mar" in ic == false) return [];
if ("rates" in ic.mar == false) return [];
let mgs = ic_getMortgagesFromRates(ic_rates);
return mgs.items;
}
function list(ic) {
let mgs = ic_getMortgagesFromRates(ic_rates);
let list = mgs.items;
return list;
}
function list_from_rates(ic_rates) {
let mgs = ic_getMortgagesFromRates(ic_rates);
let list = mgs.items;
return list;
}
function tonear10(N) {
return Math.round(N/10) *10
}
function tonear100(N) {
return Math.round(N/100) *100
}
function tonear1000(N) {
return Math.round(N/100) *1000
}
function mortgage_from_rates(ic_rates, n) {
let mgs = ic_getMortgagesFromRates(ic_rates);
let list = mgs.items;
return list[n].mortgage;
}
function filters_from_rates(ic_rates) {
let mgs = ic_getMortgagesFromRates(ic_rates);
let list = mgs.items;
let _l = list.length;
let xl = ` len ${_l}`;
let aprs = [];
let pps = [];
let c2cs = [];
let budgets = [];
let buydowns = [];
for (let i=0; i < list.length; i++) {
delete list[i].mortgage;
aprs.push( { apr : list[i].filters.apr, i : i});
pps.push( { pp : list[i].filters.purchase_price, i : i, apr : list[i].filters.apr });
c2cs.push( { c2c : list[i].filters.c2c, i : i, apr : list[i].filters.apr });
budgets.push({ budget : list[i].filters.budget, i : i, apr : list[i].filters.apr });
buydowns.push({ buydown : Math.abs(list[i].filters.buydown), i : i, apr : list[i].filters.apr });
}
aprs.sort(function(a, b) {
return a.apr < b.apr ? -1 : 1;
});
pps.sort(function(a, b) {
if (tonear1000(a.pp) == tonear1000(b.pp)) {
return a.apr < b.apr ? -1 : 1;
}
return a.pp > b.pp ? -1 : 1;
});
c2cs.sort(function(a, b) {
if (tonear100(a.c2c) == tonear100(b.c2c)) {
return a.apr < b.apr ? -1 : 1;
}
return a.c2c < b.c2c ? -1 : 1;
});
budgets.sort(function(a, b) {
if (tonear10(a.budget) == tonear10(b.budget)) {
return a.apr < b.apr ? -1 : 1;
}
return a.budget < b.budget ? -1 : 1;
});
buydowns.sort(function(a, b) {
if (a.buydown == b.buydown) {
return a.apr < b.apr ? -1 : 1;
}
return a.buydown < b.buydown ? -1 : 1;
});
return {
xl : xl,
apr : aprs,
pp : pps,
c2c : c2cs,
budget : budgets,
buydown : buydowns,
cnt_total : mgs.cnt_total,
cnt_total1 : mgs.cnt_total1,
cnt_matched : mgs.cnt_matched,
list : list
}
}
function filters_from_rates_full(ic_rates) {
let mgs = ic_getMortgagesFromRates(ic_rates);
let list = mgs.items;
let _l = list.length;
let xl = ` len ${_l}`;
let aprs = [];
let pps = [];
let c2cs = [];
let budgets = [];
let buydowns = [];
for (let i=0; i < list.length; i++) {
aprs.push( { apr : list[i].filters.apr, i : i});
pps.push( { pp : list[i].filters.purchase_price, i : i, apr : list[i].filters.apr });
c2cs.push( { c2c : list[i].filters.c2c, i : i, apr : list[i].filters.apr });
budgets.push({ budget : list[i].filters.budget, i : i, apr : list[i].filters.apr });
buydowns.push({ buydown : Math.abs(list[i].filters.buydown), i : i, apr : list[i].filters.apr });
}
aprs.sort(function(a, b) {
return a.apr < b.apr ? -1 : 1;
});
pps.sort(function(a, b) {
if (tonear1000(a.pp) == tonear1000(b.pp)) {
return a.apr < b.apr ? -1 : 1;
}
return a.pp > b.pp ? -1 : 1;
});
c2cs.sort(function(a, b) {
if (tonear100(a.c2c) == tonear100(b.c2c)) {
return a.apr < b.apr ? -1 : 1;
}
return a.c2c < b.c2c ? -1 : 1;
});
budgets.sort(function(a, b) {
if (tonear10(a.budget) == tonear10(b.budget)) {
return a.apr < b.apr ? -1 : 1;
}
return a.budget < b.budget ? -1 : 1;
});
buydowns.sort(function(a, b) {
if (a.buydown == b.buydown) {
return a.apr < b.apr ? -1 : 1;
}
return a.buydown < b.buydown ? -1 : 1;
});
return {
xl : xl,
apr : aprs,
pp : pps,
c2c : c2cs,
budget : budgets,
buydown : buydowns,
cnt_total : mgs.cnt_total,
cnt_total1 : mgs.cnt_total1,
cnt_matched : mgs.cnt_matched,
list : list
}
}
return {
list : list,
list_from_rates : list_from_rates,
filters_from_rates : filters_from_rates,
filters_from_rates_full : filters_from_rates_full,
mortgage_from_rates : mortgage_from_rates,
___id : "mortgagenav"
}
})();
let abbreviateAddress = function(S) {
try {
let parts = S.split(" ");
for (let i=0; i < parts.length; i++) {
let p = parts[i].toLowerCase();
if (p === "drive") parts[i] = "Dr";
if (p === "lane") parts[i] = "Ln";
if (p === "road") parts[i] = "Rd";
if (p === "place") parts[i] = "Pl";
if (p === "terrace") parts[i] = "Ter";
if (p === "court") parts[i] = "Crt";
if (p === "boulevard") parts[i] = "Blvd";
if (p === "avenue") parts[i] = "Av";
if (p === "causeway") parts[i] = "CSW";
if (p === "southwest") parts[i] = "SW";
if (p === "southeast") parts[i] = "SE";
if (p === "northwest") parts[i] = "NW";
if (p === "northeast") parts[i] = "NE";
if (p === "plaza") parts[i] = "Plz";
if (p === "highway") parts[i] = "Hwy";
if (p === "interstate") parts[i] = "I";
if (p === "turnpike") parts[i] = "Tpke";
if (p === "freeway") parts[i] = "Fwy";
if (p === "parkway") parts[i] = "Pkwy";
if (p === "beltway") parts[i] = "Bltwy";
if (p === "crescent") parts[i] = "Cres";
if (p === "alley") parts[i] = "Aly";
if (p === "esplanade") parts[i] = "Esp";
}
return parts.join(" ");
} catch(E) {
return S;
}
}
let xsd = (function(){
function reo(itm) {
let _itm = itm;
function addr1() {
return abbreviateAddress(MAR.getOpt(_itm, "address", "").split("|")[0])+", "+ MAR.getOpt(_itm, "address", "").split("|")[1];
}
function addr1_raw() {
return MAR.getOpt(_itm, "address", "").split("|")[0];
}
function addr() {
return MAR.getOpt(_itm, "address", "");
}
function addr1_html() {
var ad = MAR.getOpt(_itm, "address", "");
var rv = "
"+addressToString(ad)+"
";
return rv;
}
function ins() {
return MAR.getOpt(_itm, "loan_insurance", "");
}
function subject_property() {
return MAR.getOpt(_itm, "is_subject_property", "");
}
function mortgages(n) {
let item = _itm;
if (item.mortgageoptions == "free") {
return [];
}
let mos = (typeof item.mortgageoptions === "string") ? item.mortgageoptions.split(",") : [];
mos.filter(function(mo,idx){
let loan = MAR.liabilities.getByUUID(mo);
mos[idx] = {
mo : mo,
loan : loan
};
if (loan === false) return;
mos[idx].name = loan.name;
mos[idx].balance = loan.balance;
mos[idx].monthly = loan.monthly;
mos[idx].balanceF = MAR.format.format("cur",loan.balance);
mos[idx].monthlyF = MAR.format.format("cur",loan.monthly);
mos[idx].typeF = "Mortgage";
if (loan.m_type === "heloc") {
mos[idx].typeF = "HELOC";
}
});
if (typeof n !== "number") return mos;
if (n < mos.length) return mos[n];
return false;
}
function summary() {
let item = _itm;
let h = "";
if (item.verified2 === "N") {
h += `Needs Verfification !`;
} else {
if (item.mortgageoptions == "free") {
h += "Mortgage free";
} else {
h += "Property is mortgaged";
let bal = 0;
let mth = 0;
// console.log("item",item)
// console.log("item.mortgageoptions",item.mortgageoptions)
// console.log("item.mortgageoptions type",typeof item.mortgageoptions)
let mos = (typeof item.mortgageoptions === "string") ? item.mortgageoptions.split(",") : [];
mos.filter(function(mo){
let loan = MAR.liabilities.getByUUID(mo);
if (loan === false) return;
bal += loan.balance;
mth += loan.monthly;
});
h += `, Bal: ${MAR.format.format("cur",bal)}, Pmt: ${MAR.format.format("cur",mth)}`;
}
if (item.mortgageoptions !== "free" && item.loantype === "fha") {
h += `, FHA : Yes`;
}
if (MAR.getOpt(item, "is_subject_property","") === "Y") {
let new_monthly = getScenario_data(`goals_target_budget_high`,false);
let new_loanvalue = getScenario_data(`off_loanvalue`,false);
if (new_monthly !== false) {
h += `, subject property - New loan values are pmt:${MAR.format.format("cur",new_monthly)} bal:${MAR.format.format("cur",new_loanvalue)}.`;
} else {
h += `, subject property - the loan values will replace any current mortgage amounts.`;
}
}
// if (item.mortgageoptions == "free") {
// if (num(txt("#reo_free_loan_tax")) > 0) {
// h += "
Tax:"+elaineui.format("cur",txt("#reo_free_loan_tax"))+" p.a.
";
// }
// if (num(txt("#reo_free_loan_insurance")) > 0) {
// h += "
Ins:"+elaineui.format("cur",txt("#reo_free_loan_insurance"))+" p.a.
";
// }
// if (num(txt("#reo_loan_hoa")) > 0) {
// h += "
HOA:"+elaineui.format("cur",Math.floor(num(txt("#reo_loan_hoa"))))+" p.m.
";
// }
// } else {
// if (num(txt("#reo_loan_tax")) > 0) {
// h += "
Tax:"+elaineui.format("cur",txt("#reo_loan_tax"))+" p.a.
";
// }
// if (num(txt("#reo_loan_insurance")) > 0) {
// h += "
Ins:"+elaineui.format("cur",txt("#reo_loan_insurance"))+" p.a.
";
// }
// if (num(txt("#reo_loan_hoa")) > 0) {
// h += "
HOA:"+elaineui.format("cur",Math.floor(num(txt("#reo_loan_hoa"))))+" p.m.
";
// }
// }
if (item.property_type != "") h += ", Type: "+mar._txt(item.property_type);
if (item.reo_use != "") h += ", Use: "+mar._txt(item.reo_use);
if (item.purchasedate != "") h += ", Purchased : "+moment(item.purchasedate).format("MM/YYYY")
h += ", Price : "+MAR.format.format("cur",item.purchase_price)
h += ", Value : "+MAR.format.format("cur",item.value)
if (num(item.reo_rental_pm) !== 0) {
h += ", Rental income : "+MAR.format.format("cur",item.reo_rental_pm)
}
else if (num(item.reo_expected_rental) > 0) {
h += ", Rent entered:"+MAR.format.format("cur",item.reo_expected_rental);;
}
if (item.reo_use2 != "" && item.reo_use2 != "yes") {
h += ", future use:"+mar._txt(`use2_${item.reo_use2}`);
}
if (num(item.reo_expected_salesprice) > 0) {
h += ", Exp. value:"+MAR.format.format("cur",item.reo_expected_salesprice);
}
if (num(item.reo_expected_salesperc) > 0) {
h += ", Closing cost:"+MAR.format.format("perc",item.reo_expected_salesperc);
}
}
// var reo2 = "";
//
// if (item.mortgageoptions == "free") {
// if (num(txt("#reo_free_loan_tax")) > 0) {
// reo2 += "
Tax:"+elaineui.format("cur",txt("#reo_free_loan_tax"))+" p.a.
";
// }
// if (num(txt("#reo_free_loan_insurance")) > 0) {
// reo2 += "
Ins:"+elaineui.format("cur",txt("#reo_free_loan_insurance"))+" p.a.
";
// }
// if (num(txt("#reo_loan_hoa")) > 0) {
// reo2 += "
HOA:"+elaineui.format("cur",Math.floor(num(txt("#reo_loan_hoa"))))+" p.m.
";
// }
// } else {
// if (num(txt("#reo_loan_tax")) > 0) {
// reo2 += "
Tax:"+elaineui.format("cur",txt("#reo_loan_tax"))+" p.a.
";
// }
// if (num(txt("#reo_loan_insurance")) > 0) {
// reo2 += "
Ins:"+elaineui.format("cur",txt("#reo_loan_insurance"))+" p.a.
";
// }
// if (num(txt("#reo_loan_hoa")) > 0) {
// reo2 += "
HOA:"+elaineui.format("cur",Math.floor(num(txt("#reo_loan_hoa"))))+" p.m.
";
// }
// }
// if (reo2 === "") {
// reo2 = "
None
";
// }
//
//
//
//
// var reo6 = "";
// if (item.reo_use2 != "") reo6 += mar._txt(`use2_${item.reo_use2}`);
//
//
// if (num(txt("#reo_expected_rental")) > 0) {
// reo6 += "
Rent:"+elaineui.format("cur",txt("#reo_expected_rental"));
// }
// if (num(txt("#reo_expected_salesprice")) > 0) {
// reo6 += "
Exp. value:"+elaineui.format("cur",txt("#reo_expected_salesprice"));
// }
// if (num(txt("#reo_expected_salesperc")) > 0) {
// reo6 += "
Closing cost:"+elaineui.format("perc",txt("#reo_expected_salesperc"));
// }
//
//
//
// $("#_sc_reo6").html(reo6);
///
return h;
}
function tax() {
return MAR.getOpt(_itm, "loan_tax", "");
}
function hoa() {
return MAR.getOpt(_itm, "loan_hoa", "");
}
function closing_date() {
return MAR.getOpt(_itm, "closing_date", "");
}
function expected_rent() {
return MAR.getOptNum(_itm, "reo_rental_pm", 0);
}
function payoff() {
return MAR.getOptNum(_itm, "LOANBALANCE", 0);
}
function jsn() {
return JSON.stringify(_itm);
}
function getitm() {
return _itm;
}
return {
addr1 : addr1,
addr1_html : addr1_html,
addr : addr,
tax : tax,
hoa : hoa,
entered_hoa : hoa,
payoff : payoff,
subject_property : subject_property,
expected_rent : expected_rent,
ins : ins,
closing_date : closing_date,
itm : getitm,
summary : summary,
mortgages : mortgages,
jsn : jsn,
___id : "xsd reo"
}
}
function lia_factory(itm) {
if (`lia_${itm.type}` in MAR.xsd) {
return MAR.xsd[`lia_${itm.type}`](itm)
} else {
return MAR.xsd.lia_(itm)
}
}
function lia_(itm) {
let _itm = itm;
function monthly() {
return num(MAR.getOpt(_itm, "monthly",0));
}
function balance() {
return num(MAR.getOpt(_itm, "balance",0));
}
function inomask() {
return num(MAR.getOpt(_itm, "inomask",0));
}
function assigned() {
return getLiabilityAssignments(inomask())
}
function data() {
return _itm;
}
function prop(p, def) {
return MAR.getOpt(_itm, p, def);
}
return {
monthly : monthly,
inomask : inomask,
assigned : assigned,
balance : balance,
raw : data,
prop : prop,
data : data,
___id : "xsd lia"
}
}
function lia_child(itm) {
let _itm = itm;
function alimony() {
return num(MAR.getOpt(_itm, "alimony_monthly",0));
}
function payment() {
return num(MAR.getOpt(_itm, "payment",0));
}
function payment_enc() {
return num(MAR.getOpt(_itm, "payment_enc",0));
}
function alimony_will_dropoff() {
return MAR.getOpt(_itm, "alimony_dropoff","N");
}
function alimony_will_dropoff_date() {
return MAR.getOpt(_itm, "alimony_date","N");
}
function child() {
return num(MAR.getOpt(_itm, "child_monthly",0))
}
function child_will_dropoff() {
return MAR.getOpt(_itm, "child_dropoff","N");
}
function child_will_dropoff_count() {
return num(MAR.getOpt(_itm, "child_dropoff_count","0"));
}
function child_will_dropoff_details(i) {
if (child_will_dropoff_count() > 0) {
return {
name : MAR.getOpt(_itm, `child_dropoff_name_${i}` ,""),
dob : MAR.getOpt(_itm, `child_dropoff_dob_${i}` ,""),
val : num(MAR.getOpt(_itm, `child_dropoff_val_${i}` ,0))
}
}
return false;
}
function monthly() {
return alimony() + child();
}
function enc_monthly() {
return num(MAR.getOpt(_itm, "enc_monthly",0));
}
function inomask() {
return num(MAR.getOpt(_itm, "inomask",0));
}
function assigned() {
return getLiabilityAssignments(inomask())
}
function data() {
return _itm;
}
function prop(p, def) {
return MAR.getOpt(_itm, p, def);
}
return {
alimony : alimony,
payment : payment,
payment_enc : payment_enc,
monthly : monthly,
enc_monthly : enc_monthly,
alimony_will_dropoff : alimony_will_dropoff,
alimony_will_dropoff_date : alimony_will_dropoff_date,
child_will_dropoff : child_will_dropoff,
child_will_dropoff_count : child_will_dropoff_count,
child_will_dropoff_details : child_will_dropoff_details,
child : child,
inomask : inomask,
assigned : assigned,
raw : data,
prop : prop,
data : data,
___id : "xsd lia child"
}
}
function inc_w2(itm) {
let _itm = itm;
function is_less_3_months() {
let fromd = MAR.getOpt(itm, "fromd", "");
if (fromd === "") return false;
let m_now = new Date().getTime();
let m_fromd = MAR.Date(fromd).getTime();
let diff = (m_now - m_fromd) / (1000 * 3600 * 24)
if (diff < 95) return true;
return false;
}
function name(DEFAULT) {
if (isPrevious()) {
return MAR.getOpt(_itm, "displayName","")
}
if (DEFAULT === "Dis") return "Disability";
let rv = _itm.name || _itm.name_k1 || _itm.name_llc || _itm.pension_former_employer;
if (typeof rv !== "string" && typeof DEFAULT === "string") return DEFAULT;
return rv;
}
function isPrevious_W2() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "N") {
return true;
}
return false;
}
function isPrevious_1099() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "Y" && MAR.getOpt(_itm, "selfemployed_type", "") == "D1099") {
return true;
}
return false;
}
function isPrevious_partnership() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "Y" && MAR.getOpt(_itm, "selfemployed_type", "") == "Partnership") {
return true;
}
return false;
}
function isPrevious_llc() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "Y" && MAR.getOpt(_itm, "selfemployed_type", "") == "LLC") {
return true;
}
return false;
}
function isPrevious_scorp() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "Y" && MAR.getOpt(_itm, "selfemployed_type", "") == "S-Corp") {
return true;
}
return false;
}
function isPrevious_ccorp() {
if (isPrevious() === true && MAR.getOpt(_itm, "selfemployed", "") === "Y" && MAR.getOpt(_itm, "selfemployed_type", "") == "C-Corp") {
return true;
}
return false;
}
function isPartTime() {
let income_full_or_part = MAR.getOpt(_itm, "income_full_or_part", "");
if (income_full_or_part === "parttime") return true;
return false;
}
function isFullTime() {
let income_full_or_part = MAR.getOpt(_itm, "income_full_or_part", "fulltime");
if (income_full_or_part === "fulltime") return true;
return false;
}
function isPrevious() {
return (MAR.getOpt(_itm, "previous_type","") !== "");
}
function is_last_year() {
let fromd = MAR.getOpt(_itm, "fromd", "");
let tod = MAR.getOpt(_itm, "tod", "");
if (fromd === "") return true;
let m_now = new Date().getFullYear();
let m_fromd = MAR.Date(fromd).getFullYear();
if (tod !== "") {
let m_tod = MAR.Date(tod).getFullYear();
if (m_tod < m_now-1) return false;
}
if (m_fromd < m_now) return true;
return false;
}
function is_more_1_year() {
let fromd = MAR.getOpt(_itm, "fromd", "");
if (fromd === "") return true;
let m_now = new Date().getTime();
let m_fromd = MAR.Date(fromd).getTime();
let diff = (m_now - m_fromd) / (1000 * 3600 * 24)
if (diff > 365) return true;
return false;
}
function is_more_2_year() {
let fromd = MAR.getOpt(_itm, "fromd", "");
if (fromd === "") return true;
let m_now = new Date().getFullYear();
let m_fromd = MAR.Date(fromd.split("-")).getFullYear();
if (m_fromd < (m_now-1)) return true;
// let m_now = new Date().getTime();
// let m_fromd = MAR.Date(fromd).getTime();
// let diff = (m_now - m_fromd) / (1000 * 3600 * 24)
//
// if (diff > 365) return true;
return false;
}
// if ( MAR.getOpt(_itm, "current","Y") !== "N");
//
// if (MAR.getOpt(inc, "previous_type","") === "work") {
// inc.start_date = MAR.getOpt(inc, "fromd", "");
// inc.end_date = MAR.getOpt(inc, "tod", "");
// }
// if (MAR.getOpt(inc, "previous_type","") === "study") {
// inc.start_date = MAR.getOpt(inc, "education_start", "");
// inc.end_date = MAR.getOpt(inc, "education_end", "");
// }
// } else {
// inc.start_date = MAR.getOpt(inc, "fromd", "");
// inc.end_date = "";
// }
return {
is_less_3_months : is_less_3_months,
is_more_1_year : is_more_1_year,
is_more_2_year : is_more_2_year,
is_last_year : is_last_year,
isPartTime : isPartTime,
isFullTime : isFullTime,
name : name,
isPrevious : isPrevious,
isPrevious_W2 : isPrevious_W2,
isPrevious_1099 : isPrevious_1099,
isPrevious_partnership : isPrevious_partnership,
isPrevious_llc : isPrevious_llc,
isPrevious_scorp : isPrevious_scorp,
isPrevious_ccorp : isPrevious_ccorp,
___id : "income w2"
}
}
function obj_from_need_array(needsidArray) {
/**
* e.g.
* [0] [1] [2] [3] [4] [5]
* reo / ? / 1 / sup_doc / reo-home-hoa / 111-222-333-444
*/
if (!needsidArray || needsidArray.length < 6) {
return false;
}
if (needsidArray[0] === "reo") {
let uuid = needsidArray[5];
let itm = MAR.reo.getByUUID(uuid);
if (itm !== false) {
itm._tmpyear = (needsidArray.length > 6) ? needsidArray[6] : "";
}
return itm;
}
if (needsidArray[0] === "liabilities") {
let uuid = needsidArray[5];
let itm = MAR.liabilities.getByUUID(uuid);
if (itm !== false) {
itm._tmpyear = (needsidArray.length > 6) ? needsidArray[6] : "";
}
return itm;
}
if (needsidArray[0] === "income") {
let uuid = needsidArray[5];
let itm = MAR.income.getByUUID(uuid);
if (itm !== false) {
if ("name" in itm) itm.namef = itm.name;
else if ("name_k1" in itm) itm.namef = itm.name_k1;
else if ("name_llc" in itm) itm.namef = itm.name_llc;
itm._tmpyear = (needsidArray.length > 6) ? needsidArray[6] : "";
}
return itm;
}
return false;
}
return {
reo : reo,
lia_child : lia_child,
lia_ : lia_,
lia_factory : lia_factory,
inc_w2 : inc_w2,
obj_from_need_array : obj_from_need_array,
___id : "xsd"
}
})()
let conditionsObj = (function(){
let code2cat = {}
code2cat.ASS = "assets";
code2cat.INC = "income";
code2cat.ID = "personal";
code2cat.REO = "reo";
code2cat.PROP = "property";
code2cat.LIA = "credit";
code2cat.GEN = "miscelaneous";
code2cat.LOI = "Compliance";
let code2enc = {}
code2enc.ASS = "assets";
code2enc.INC = "income";
code2enc.ID = "misc";
code2enc.REO = "misc";
code2enc.PROP = "assets";
code2enc.LIA = "liabilities";
code2enc.GEN = "misc";
code2enc.LOI = "misc";
let cat2code = {}
cat2code.assets = "ASS";
cat2code.income = "INC";
cat2code.personal = "ID";
cat2code.reo = "REO";
cat2code.property = "PROP";
cat2code.liabilities = "LIA";
cat2code.credit = "LIA";
cat2code.miscelaneous = "GEN";
cat2code.loi = "LOI";
function getEncNoteSec(S) {
if (S in cat2code) {
S = cat2code[S]; // change to code
}
return MAR.getOpt(code2enc, S, "misc");
}
function getCode(S) {
if (S in code2cat) return S; // if you send ASS then return ASS
return MAR.getOpt(cat2code, S, S);
}
function getCat(S) {
if (S in cat2code) {
S = cat2code[S]; // change to code
}
return MAR.getOpt(code2cat, S, S);
}
function isDate(S){
if (S.length !== 10) return false;
var regEx = /^\d{4}-\d{2}-\d{2}$/;
if(S.match(regEx)) return true; // valid format
return false;
}
function extra_format(S){
/**
* is it 2 dates?
*/
let parts = S.trim().split(" ");
if (parts.length === 2) {
if (isDate(parts[0]) && isDate(parts[1])) { /* is 2011-01-01 2011-01-01*/
return `for the period ${parts[0]} to ${parts[1]}`;
}
}
return S;
}
function extract_date_range(S){
/**
* is it 2 dates?
*/
let parts = S.trim().split(" ");
if (parts.length === 2) {
if (isDate(parts[0]) && isDate(parts[1])) { /* is 2011-01-01 2011-01-01*/
return {
sdate : parts[0],
edate : parts[1]
};
}
}
return false;
}
return {
cat2code : cat2code,
code2cat : code2cat,
getEncNoteSec : getEncNoteSec,
getCode : getCode,
getCat : getCat,
extra_format : extra_format,
extract_date_range : extract_date_range,
___id : "conditions"
}
})();
let adminusersObj = (function(){
function roles_is_lo(permission) {
if ((permission & mar.approles.assignedto.mask) > 0) return true;
return false;
}
function roles_is_re(permission) {
if ((permission & mar.approles.realtor.mask) > 0) return true;
return false;
}
function image_src(uid) {
return `/cfc/adminuserspublic/${uid}/image`;
}
function user_firstname(user) {
let name = MAR.getOpt(user, `name`,``).split(` `)[0];
if (name.endsWith(`s`)) return `${name}'`;
return `${name}'s`;
}
return {
is_lo : roles_is_lo,
is_re : roles_is_re,
image_src : image_src,
//
user_firstname : user_firstname,
//
____id : "adminusers obj"
}
})();
let format = (function(){
let MAXC = 12;
let MAXCEMP = 20;
function first(str, spacer) {
if (typeof spacer !== "string") spacer = "";
if (typeof str === "string") return spacer+str.trim().split(" ")[0].slice(0,MAXC);
return "";
}
function emp(str,spacer) {
if (typeof spacer !== "string") spacer = "";
if (typeof str === "string") return spacer+str.trim().slice(0,MAXCEMP).trim();
return "";
}
function cur(str,units) {
if (typeof units !== "string") {
units = "";
} else {
units = ` ${units}`;
}
if (typeof str === "string") str = num(str);
if (typeof str === "number") return `\$${str.toFixed(0)}${units}`;
return "";
}
function cur2(str,units) {
if (typeof units !== "string") {
units = "";
} else {
units = ` ${units}`;
}
if (typeof str === "string") str = num(str);
if (typeof str === "number") return `\$${str.toFixed(2)}${units}`;
return "";
}
let month_names = {
"1" : "Jan",
"01" : "Jan",
"2" : "Feb",
"02" : "Feb",
"3" : "Mar",
"03" : "Mar",
"4" : "Apr",
"04" : "Apr",
"5" : "May",
"05" : "May",
"6" : "Jun",
"06" : "Jun",
"7" : "Jul",
"07" : "Jul",
"8" : "Aug",
"08" : "Aug",
"9" : "Sep",
"09" : "Sep",
"10" : "Oct",
"11" : "Nov",
"12" : "Dec",
};
function month_name(n) {
return MAR.getOpt(month_names, `${n}`, "");
}
function dat(str) {
if (typeof str === "string" && str.trim().length === 10) {
let strs = str.split("-");
return {
y : strs[0],
m : month_names[strs[1]],
d : num(strs[2])
};
}
return "";
}
function range(str, str2) {
str = dat(str);
str2 = dat(str2);
if (typeof str === "object" && typeof str2 === "object") {
return `${str.m} ${str.d} - ${str2.m} ${str2.d} ${str2.y}`;
}
return "";
}
function month(str) {
str = dat(str);
if (typeof str === "object") {
return `${str.m} ${str.y}`;
}
return "";
}
function str2usd_docnaming(str) {
if (typeof str !== "string") return str;
let dates = str.match(/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/g);
if (dates !== null) {
for (let i=0; i < dates.length; i++) {
let _da = dates[i];
let _das = _da.split("-");
let _usda = month_names[_das[1]]+"-"+_das[2]+"-"+_das[0]
str = `${month_names[_das[1]]} ${parseInt(_das[2],10)}, ${_das[0]}`;
}
}
dates = str.match(/[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]/g);
if (dates !== null) {
for (let i=0; i < dates.length; i++) {
let _da = dates[i];
let _das = _da.split("-");
let _usda = month_names[_das[1]]+"-"+_das[0]+"-"+_das[2]
str = `${month_names[_das[1]]} ${parseInt(_das[0],10)}, ${_das[2]}`;
}
}
return str;
}
function _format(type, val) {
let rval = val;
if (type == "int") {
if (val != "") rval = parseInt(val,10);
}
if (type == "t_usd1") {
if (val != "") {
let vals = val.split("-");
if (vals.length > 2) {
return `${vals[1]}/${vals[2]}/${vals[0]}`;
}
}
}
else if (type == "da") {
return str2usd_docnaming(val);
}
else if (type == "cal") {
if (val != "") return moment(val).utcOffset(-5*60).calendar();
}
else if (type == "ad1") {
if (val != "") return val.split("|")[0];
}
else if (type == "cur") {
if (val != "") rval = parseInt(val,10).toLocaleString('en-US');;
rval = "$"+rval+"";
}
else if (type == "curK") {
if (val != "") rval = Math.round(parseInt(val,10)/1000);
rval = "$"+rval+"k";
}
else if (type == "cur_space") {
if (val != "") rval = parseInt(val,10).toLocaleString('en-US');;
rval = "$ "+rval+"";
}
else if (type == "cur_just") {
if (typeof val === "number") rval = parseInt(`${val}`,10).toLocaleString('en-US');
else if (typeof val === "string") rval = parseInt(val,10).toLocaleString('en-US');
else rval = "";
rval = "
$ "+rval+"";
}
else if (type == "cur2") {
if (val != "") rval = parseFloat(val,10).toFixed(2).toLocaleString('en-US');;
rval = "$"+rval+"";
}
else if (type == "dec") {
if (val != "") rval = parseFloat(val,10).toFixed(2);
}
else if (type == "perc") {
if (val != "") rval = parseFloat(val,10).toFixed(2)+"%";
}
else if (type == "perc0") {
if (val != "") rval = parseFloat(val,10).toFixed(0)+"%";
}
else if (type == "perc1") {
if (val != "") rval = parseFloat(val,10).toFixed(1)+"%";
}
else if (type == "perc2") {
if (val != "") rval = parseFloat(val,10).toFixed(2)+"%";
if (rval == "0") rval = "0.00%";
}
else if (type == "perc3") {
if (val != "") rval = parseFloat(val,10).toFixed(3)+"%";
if (rval == "0") rval = "0.000%";
}
else if (type == "perc3opt") {
if (val != "") {
rval = parseFloat(val,10).toFixed(3)+"%";
if (rval.endsWith("000%")) {
rval = rval.substring(0,rval.length-5)+"%";
}
else if (rval.endsWith("00%")) {
rval = rval.substring(0,rval.length-3)+"%";
}
else if (rval.endsWith("0%")) {
rval = rval.substring(0,rval.length-2)+"%";
}
}
if (rval == "0") rval = "0.0%";
}
// else if (type == "tel") {
// rval = telF(val,val);
// }
else if (type == "usd") {
rval = str2usd(val);
}
else {
}
return rval;
}
return {
str2usd_docnaming : str2usd_docnaming,
format : _format,
first : first, /* first name */
emp : emp, /* employer name */
dat : dat,
range : range,
month : month,
cur : cur,
month_name : month_name,
cur2 : cur2,
____if : "formatting"
}
})();
function zero(label) {
return 0;
}
function val(v,label) {
return v;
}
function boolean_get(str, posn, def) {
if (typeof str !== "string") {
str = "";
}
if (typeof posn === "number") {
// this is a get
if (posn
= str.length) {
str = (`${str}---------------------------------------}`).substring(0,posn+1);
}
if (typeof val === "string" && val.length > 0) {
str = str.split("");
str[posn] = val[0];
str = str.join("");
}
}
return str;
}
function digits(s) {
if (!s || typeof s !== "string") return "";
return s.replace(/[^0-9]/g,'');
}
function is_timestamp_string(S) {
if (typeof S !== "string") return false;
if (S.length < 12) return false;
if (`${digits(S)}` !== S) return false;
return true;
}
function str(s) {
if (typeof s === "string") return s;
if (typeof s === "object") return JSON.stringify(s);
return `${s}`;
}
function cr2br(S) {
if (typeof S !== "string") return "";
return S.replace(/\n/g, " ");
}
function searchArray(arr, key, val, nth_occurrence) {
if (typeof nth_occurrence !== "number") nth_occurrence = 0;
if (typeof arr !== "object") return false;
for (let i=0; i < arr.length; i++) {
if (key in arr[i] && arr[i][key] === val) {
if (nth_occurrence === 0) {
return arr[i];
} else {
nth_occurrence--;
}
}
}
return false;
}
function DateObj(S) {
// see https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results
if (arguments.length === 0) return new Date();
if (typeof S === "string") {
let parts = S.split("-");
if (parts.length === 3) {
return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
}
return new Date(S);
}
let emailObj = (function(){
function strip_reply(s) {
if (typeof s !== "string") return s;
let lines = s.split("\n");
let rv = [];
for (let i=0; i < lines.length; i++) {
let lin = lines[i].toLowerCase().trim();
if (lin.startsWith("email:")) break;
if (lin.startsWith("phone:")) break;
if (lin.startsWith("[cid")) continue;
if (lin.startsWith("[")) continue;
if (lin.startsWith("from:")) break;
if (lin.startsWith("sent:")) break;
if (lin.startsWith("to:")) break;
if (lin.startsWith("----")) break;
if (lin.indexOf("----") > -1) break;
rv.push(lines[i])
}
return rv.join("\n");
}
return {
strip_reply : strip_reply,
___id : "Email helpers"
}
})();
function confluence(link) {
return `https://confluence.durunner.ai/display/EL/${link}`;
}
/**
* Apply a model to an object
*/
function applymodel(model, da) {
for (let x in model) {
let mandatory = MAR.getOpt(model[x], "mandatory", false);
let name = MAR.getOpt(model[x], "name", x);
let type = MAR.getOpt(model[x], "type", false);
let def = MAR.getOpt(model[x], "def", null);
if (mandatory && x in da === false) {
return `${name} is mandatory`;
}
if (x in da === false) {
if (def !== null) {
da[x] = def;
}
}
let val = da[x];
if (type) {
if (typeof val !== type) {
return `${name} is not a ${type} but a ${typeof val}`;
}
}
}
return true;
}
let apiObj = {}
apiObj.lookup_address_details = function(address,fn) {
$.ajax({
url: `/api/chatbot/getaddressinfo`,
type: 'POST',
data : {
address : address
},
success: function(da) {
if (da.status === 201) {
fn({
error : false,
sug : MAR.getOpt(da, "data.sug",[]),
sug_cnt : MAR.getOpt(da, "data.sug_cnt",0)
})
return;
}
if (da.status === 202) {
fn({
error : false,
sug : MAR.getOpt(da, "data.sug",[]),
sug_cnt : MAR.getOpt(da, "data.sug_cnt",0)
})
return;
}
if (da.status !== 0 && da.status !== 204) {
fn(false);
return;
}
fn(MAR.getOpt(da, "data.eldata",{}), da);
// fn(MAR.getOpt(da, "data.rv.data.data",{}), da);
},
error: function(da){
fn({
error : true,
err : da
});
return;
},
timeout : 10000
})
};
apiObj.lookup_address_detailsSync = function(address) {
return new Promise(function(resolve, reject) {
apiObj.lookup_address_details(address, function(rv) {
resolve(rv);
});
});
};
apiObj.getSync = function(url) {
return new Promise(function(resolve, reject) {
$.get(url, function(rv){
resolve(rv);
})
});
};
apiObj.postSync = function(url, data) {
return new Promise(function(resolve, reject) {
$.post(url, data, function(rv){
resolve(rv);
})
});
};
apiObj.sleepSync = function(n) {
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve(true);
},n);
});
};
function setLowestCreditScore(ans) {
console.log(`setLowestCreditScore 0`)
/* chck type */
if (typeof ans !== "object") return;
/* get the scenario */
let sc = MAR.getOpt(ans, "v2.scenario", false);
if (sc === false) return;
console.log(`setLowestCreditScore 1`)
let cs = false;
for (let i=0; i < 8; i++) {
let _cs = MAR.getOpt(sc, `applicant${i+1}_cscore`, 0);
if (_cs && _cs > 0 && (cs === false || _cs < cs)) {
cs = _cs;
}
}
if (cs === false) return;
console.log(`setLowestCreditScore 2 ${cs}`);
MAR.setOpt(ans, "v2.cscore" , cs);
}
function isString(s) {
return (typeof s === "string");
}
function isDefined(s) {
return (typeof s !== "undefined");
}
function isUndefined(s) {
return (typeof s === "undefined");
}
function ifDefined(s, def) {
if (isDefined(s)) return s;
return def;
}
function clone(obj, DEF) {
if (typeof obj === "string") return obj;
if (typeof obj === "number") return obj;
if (typeof obj === "boolean") return obj;
if (typeof obj === "object") return JSON.parse(JSON.stringify(obj));
if (isDefined(DEF)) {
if (typeof obj === "undefined") return DEF;
if (obj === null) return DEF
}
return obj;
}
function areDifferences(obj1, obj2, fields_arr) {
let rv = [];
for (let i=0; i < fields_arr.length; i++) {
let x = fields_arr[i];
if (MAR.getOpt(obj1,x,null) !== MAR.getOpt(obj2,x,null)) rv.push(x);
}
return (rv)
}
let jsn = (function(){
function parse(JSN,DEFAULT) {
try {
if (typeof JSN == "string") {
if (JSN.trim().length === 0) return DEFAULT;
return JSON.parse(JSN);
} else {
console.warn("jsn parse NON STRING INPUT ",JSON.stringify(JSN.null,4))
if (typeof JSN == "undefined") {
return DEFAULT
}
return JSN;
}
} catch(E) {
console.error("jsn parse error ERRORMESSAGE",E)
console.error("jsn parse error JSON",JSN)
if (arguments.length > 1) {
return DEFAULT
}
return {}
}
}
function stringify(OBJ) {
if (!OBJ || OBJ === null) return "{}";
if (typeof OBJ === "string") return OBJ;
return JSON.stringify(OBJ);
}
return {
parse : parse,
stringify : stringify,
____id : "jsn functions"
}
})();
function constant(v,lbl) {
return v;
}
function ans_skeleton() {
var answers = {
v2: {
state: {
},
scenario : {
},
},
applicants: [],
declarations : [],
income : [],
liabilities : [],
assets : [],
question_number: 0
};
return answers;
}
let icn = {};
icn.tick = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAM5JREFUOE+l061uAlEQBeBvBe/Vd6jhp6YCgQHbYLqo2lbUVPQBapBICKZIHgGJq0Q0oc0kdxOgZdkbRk7OOffMzLmFK6tI/BKPmVoTlJXAD6KRU/FgcSoQTppU5Thb4AaLsJ5GzhJ4wsPBqFkjvGCINTpon3PwgVeM8ZmW8YY+Vom8qRshOGFtiwFucYc5uqkfmNodjPCMb7QwQw9fB+e5uMR7vGOayLuT214UCHycbIn9P8FoJFAXqNhTiPzJQZMUVpijHFz9mXJePsL+AqxdPBGbz/tcAAAAAElFTkSuQmCC`;
icn.tick_green = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAASBJREFUOE+lk79KA0EQxr/ZRWwsRfFP8AXu8gy+g40xNhYWguy1kiZnZWHhGRTBwgewsbRUbGIZuGAtiJd0lhZJ7pM9OUhiNLdmy2HmNzPfNyuY8Ymt995NKIK6C4vEcXutEWYAPzG0AReAbRivNmQEYIlFIPnEzgDv7XCzXbp4/BfAT8wJgKN8VacVyklwTtAI0CLSCqm2JwKoeKuIS2hdi5ej5rfAwTXAfRDPWqlKayV6/XUFW5DZKeiC6gBItwDsiuChr+d3XpZOu8O2TxSxnJiAQARBD8QcwHv0+tV44+ojd2iqiH7H7IG4AXC3MNDVZunsc9jeqYBsTGvZ+uITJEzHb6MQ4K+D8jqmLkT4Q4MiV5jnjNg482dy6Tye+wWEeccR7OTbOgAAAABJRU5ErkJggg==`;
icn.box = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAFpJREFUOE9jZKAQMEL1NzAwMNSTaFYjAwNDA8yA/wwMDKsZGBiuMTAwgNgwcVxmajEwMISC1CEbADaRSFfAXDxqwGggglIuddMBLCkTkxgxkjLFmYkYW7GqAQDTbykRWLpf1AAAAABJRU5ErkJggg==`;
return {
/**
* String functions
* @ignore
*/
capitalizeFirstLetter : capitalizeFirstLetter, // capitalize 1st leter
capitalizeFirstLetters : capitalizeFirstLetters, // all words
getOpt : getOpt, // optional get from JSON object
getOptS : getOptS, // getOption Safe
getOptNum : getOptNum, // getOption Safe
getOptEmptyString : getOptEmptyString, // get Optional but cannot be an empty string
nullIf : nullIf, // return null is matches any of the array params
getOptString : getOptString, // get Option type string
setOpt : setOpt, // set an item with a dit syntax
createOpt : createOpt, // create if not present
pushOpt : pushOpt, // push Optional
isEmpty : isEmpty, // is an object empty
isEmptyString : isEmptyString, // is an empty string
isNonEmptyString : isNonEmptyString, // is a string and non empty
delOpt : delOpt, // delete optionally
notNull : notNull, // not null
createIfNotExist : createIfNotExist, // create if not exist
ifOpt : ifOpt,
ifOpts : ifOpts,
ifOptNum : ifOptNum,
ifNotOpt : ifNotOpt,
extend_replace : extend_replace, // extend / replace an object
numberArray : numberArray, // make sure the array has only numeric values
array_to_kv : array_to_kv, // array to KV object
th : th, // 1 = first, etc..
rd : rd, // 1 = 1st, etc..
numName : numName, // 1 = one, etc...
equalsIgnoreCase : equalsIgnoreCase, // like java
strCmp : strCmp, //compare as string
contains_string : contains_string,
contains_string_ignore_case : contains_string_ignore_case,
MAXBORROWERS : MAXBORROWERS, // MAX BORROWERS
isString : isString,
isDefined : isDefined,
isUndefined : isUndefined,
ifDefined : ifDefined,
clone : clone, // clone a number , string, boolean or object
areDifferences : areDifferences, // are their differences in the values
/**
* helpers
*/
xsd : xsd, // objects
is_refi : is_refi, // is refi
is_refi_limited_cashout : is_refi_limited_cashout, // is limited cash out refi
is_refi_cashout : is_refi_cashout, // is cashout refi
is_refi_rat : is_refi_rat, // is rate and term refi
is_purchase : is_purchase, // is purchase
is_phase_rq : is_phase_rq, // are we in the ratequote phase
is_phase_rq_password : is_phase_rq_password, // in phase rq password
confluence : confluence, // confluence link
setLowestCreditScore : setLowestCreditScore, // set the lowest credit score
ans_skeleton : ans_skeleton, // skeleton answers
icn : icn, // icons
/**
* Movie helpers
*/
movieLinkToPlayer : movieLinkToPlayer,
/**
* County
* @ignore
*/
county_display : county_display, // county display
county_number : county_number, // county number
county_name : county_name, // county name
county2zip : county2zip, // county to zip
zip2county : zip2county, // county to zip
countynum2text : countynum2text,
countynum2Full : countynum2Full,
county_formatted : county_formatted, // formated as buncome, NC
county_state : county_state, // NC
stateCode : stateCode,
zip2county_full : zip2county_full,
state_boundaries : state_boundaries,
/**
* address functions
* @ignore
*/
getTBDaddress : getTBDaddress,
getBorrowerPairs : getBorrowerPairs, // get encompass borrower pairs
get_ssns : get_ssns, // get the ssns of the borrowers
getApplicantsSpouse : getApplicantsSpouse, // get the spouse of (N)
getApplicants_JointApplicant : getApplicants_JointApplicant, // do we have a joint person
getApplicantsShareAddress : getApplicantsShareAddress,
getApplicantsAreJoint : getApplicantsAreJoint, // get if applicant 0 and 1 are joint
getApplicantsAreJointDbg : getApplicantsAreJointDbg, // get if applicant 0 and 1 are joint
safe_sn : safe_sn, // make a safe version of the ssn
getApplicantAddresses4506t : getApplicantAddresses4506t, // get up to 2 addresses , current and previous only if necessary
getApplicantsCurrentRent : getApplicantsCurrentRent, // get the total rent paid
is_current_address_rented_and_will_continue
: is_current_address_rented_and_will_continue, // will rent continue
getApplicantHMDA : getApplicantHMDA, // get HMDA in format (n,"html");
getApplicantLastTaxYear : getApplicantLastTaxYear, // get the Applicant's last tax year , or last year otherwise.
getCurrentYear : getCurrentYear, // get the current year
getCurrentYearForTax : getCurrentYearForTax, // get current year you could file taxes
getCurrentYearForIncome : getCurrentYearForIncome, // get current year you could have an income statement for
getCurrentYearForReoRental : getCurrentYearForReoRental,
getEmails : getEmails, // get All Emails used
getNames : getNames, // get all names
getTels : getTels, // get all tels
getApplicantDoesOwnRealestate : getApplicantDoesOwnRealestate, // get whether an applicant answered that they do own realestate
getApplicantsDoOwnRealestate : getApplicantsDoOwnRealestate, // get whether ayn applicant answered that they do own realestate
getApplicantAddressDL : getApplicantAddressCurrent, // get up to 1 addresses , current
getApplicantAddressCurrent : getApplicantAddressCurrent, // get up to 1 addresses , current
getApplicantEmail : getApplicantEmail,
getApplicantPhone : getApplicantPhone,
removeBorrower : removeBorrower, // remove apps
addressToString : addressToString, // address to string
addressUnitToString : addressUnitToString, // address unit to string
addressToVal : addressToVal, // address to value for storage
addressToPlainString : addressToPlainString, // address to plain string
getUsedAddressList : getUsedAddressList , // get used address list from 'bucket' and 'reo' in answers.v2,
addressFromString : addressFromString, // get address from string
createElaineUnit_from_encompassUnits
: createElaineUnit_from_encompassUnits,
addAddressBucket : addAddressBucket, // add an address to a bucket
/**
* Scenario getters
* @ignore
*/
getPropertyType_v2 : getPropertyType_v2, // get property type (optionsl scenario)
getPropertyType : getPropertyType_v2, // get property type (optionsl scenario)
getLoanType_v2 : getLoanType_v2, // loan type (scenario)
getLoanType : getLoanType_v2, // loan type (scenario)
getRefi_v2 : getRefi_v2, // refi options (scenario)
getRefi : getRefi_v2, // refi options (scenario)
getScenario_data : _getScenario_data, // get scenario data
/**
* General utility functions
* @ignore
*/
getBucket : getBucket, // get data from a bucket
getBuckets : getBuckets, // get all buckets
getBucketByUUID : getBucketByUUID, // get bucket by uuid
setBucket : setBucket, // set bucket
/**
* State functions
* @ignore
*/
isReadyFor4506tStatus : isReadyFor4506tStatus, // is this ready for the 4506T
/**
* applicant functions
* @ignore
*/
setApplicantName : setApplicantName, // set the applicant name in the scenario and bucket
/**
* first time buyer and mcc variables
* @ignore
*/
isMccEligible : isMccEligible, // if this application eligible for MCC
isVaEligible : isVaEligible, // if this application eligible for VA
rec_prog : rec_prog, // rec_prog
rec_progs : rec_progs, // rec_progs
rec_min_dp : rec_min_dp,
set_target_va : set_target_va, // set vac
isFirstTimeBuyer : isFirstTimeBuyer, // does this application have any non first time buyers
fixFirstTimeBuyer : fixFirstTimeBuyer, // fix up the "first time buyer" based on other data
ownsProperty : ownsProperty, // does (n) own property
ownsPropertyUnanswered : ownsPropertyUnanswered, // property is an un-answered question at the moment
ownsPrimary : ownsPrimary, // does (n) own primary residence
/**
* summary display functions
* @ignore
*/
getSummary : getSummary, // get a one line summary
getSummaryHoa : getSummaryHoa, // get an HTML summary of the HOA options
getSummaryHoi : getSummaryHoi, // get an HTML summary of the HOI fees
/**
* calculation functions
* @ignore
*/
getApproximateClosingCosts : getApproximateClosingCosts, // get te approx cloxing cost (max loon , ufmi)
get_estimated_closing_date : get_estimated_closing_date, // get est closing date
getRatesheet : getRatesheet, // get rate sheet setop and defaults
getNiceMIname : getNiceMIname, // nice name for
/**
* Scenario
* @ignore
*/
isUnderContract : isUnderContract, // Is the file under contract "L"
isOffering : isOffering, // Is "O" or "L"
isLive : isLive, // Is Live via the pipeline
realtor_options : realtor_options, // realtor options
/**
* Consent
* @ignore
*/
getConsents : getConsents, // get the consents
/**
* Scenario
* @ignore
*/
scenario : scenarioObj, // scenario
/**
* Income
* @ignore
*/
income : incomeObj, // income
/**
* Declarations
* @ignore
*/
declarations : declarationsObj, // declarations
/**
* Application
* @ignore
*/
applicants : applicantsObj, // applicants functions [x]
/**
* Application
* @ignore
*/
application : applicationObj, // application functions
app : applicationObj, // application functions
/**
* Realtor
* @ignore
*/
realtor : realtorObj, // realtor [x]
/**
* encompass
* @ignore
*/
encompass : encompassObj, // encompass [x]
/**
* Custom fields
* @ignore
*/
customfields : customfieldsObj, // customfields functionsx
cf : customfieldsObj, // customfields functions
/**
* Application Navigation
* @ignore
*/
applicationNav : applicationNavObj, // application navigation functions
applicationnav : applicationNavObj, // application navigation functions
appnav : applicationNavObj, // application navigation functions
/**
* Assets
* @ignore
*/
assets : assetsObj, // assets
/**
* DevOps
* @ignore
*/
devops : devopsObj, // dev ops
/**
* Tests
* @ignore
*/
test : testObj, // testing
/**
* Supdata
*/
supdata : supdataObj, // supdata
sd : supdataObj,
/**
* Activity Log
* @ignore
*/
activity_log : activity_logObj, // activity log
/**
* REO
* @ignore
*/
reo : reoObj, // REO
/**
* Permissions
* @ignore
*/
perms : permissionsObj, // Permissions object [x]
/**
* Assets
* @ignore
*/
addresshist : addressObj, // assets [x]
/**
* Liabilities
* @ignore
*/
liabilities : liabilitiesObj, // liabilities
/**
* cpull
* @ignore
*/
cpull : cpullObj, // credit pull
/**
* contract
* @ignore
*/
contract : contractObj, // contract and Lock information
/**
* lock
* @ignore
*/
lock : lockObj, // contract and Lock information
/**
* rq_obj
* @ignore
*/
rq_obj : rqObj, // contract and Lock information
/**
* Conditions
* @ignore
*/
conditions : conditionsObj, // conditions
/**
* adminusers
*/
adminusers : adminusersObj, // dmin users
/**
* Routing of the app
* @ignore
*/
master_router : master_router, // the master routing in the app
/**
* LOX
* @ignore
*/
loxBuilder : loxBuilder, // building an LOX or an LOX request
/**
* MORTGAGE NAVIGATION
* @ignore
*/
mortgageNavigator : mortgageNavigator,
/**
* APIS
* @ignore
*/
api : apiObj,
/**
* utils
* @ignore
*/
math : math, // math functions
zero : zero,
val : val,
resetroute : resetroute,
digits : digits,
cr2br : cr2br,
is_timestamp_string : is_timestamp_string, // is this a timestamp in a string
str : str,
searchArray : searchArray,
format : format,
applymodel : applymodel,
Date : DateObj,
emailObj : emailObj,
boolean_get : boolean_get,
boolean_set : boolean_set,
jsn : jsn,
constant : constant,
Const : constant,
/**
* telephone number functions
* @ignore
*/
telF : telF,
__name : "MAR"
}
})()
/**
* @namespace MAR_depreciated
*/
/**
* @memberof MAR_depreciated
*/
function getApplicantsAreJoint() {
return true;
return MAR.getApplicantsAreJoint();
}
/**
* @memberof MAR_depreciated
*/
function getApplicantAddresses4506t(n) {
return MAR.getApplicantAddresses4506t(n);
}
/**
* @memberof MAR_depreciated
*/
function getBucket(bucketid) {
return MAR.getBucket(bucketid);
}
/**
* @memberof MAR_depreciated
*/
function getBuckets() {
return MAR.getBuckets();
}
/**
* @memberof MAR_depreciated
*/
function addressToString(ad) {
return MAR.addressToString(ad);
}
/**
* @memberof MAR_depreciated
*/
function addressToPlainString(ad) {
return MAR.addressToPlainString(ad);
}
/**
*
*/
function addressFromString(ad) {
return MAR.addressFromString(ad);
}
/**
*
*/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
/**
*
*/
String.prototype.isempty = function() {
if (!this) return true;
if (this === null) return true
if (this == "") return true
return false;
}
/**
* get applicant names
*
* SPOUSE : "spouse",
* COBORROWER : "coborrower",
* COBORROWER_NON_RESIDENT : "coborrower_nonresident"
*
* returns
* {
* name : "borrower",
* Name : "Borrower",
* prefix : "Your",
* PREFIX : "YOUR"
* }
*
*
*/
var getApplicantsNames_v2_lastscenario = (function(){
let state = {}
function get() {
if ("sc" in state == false) return gs();
if ("apl" in state == false) return gs();
if (JSON.stringify(mar.answers.v2.applicants) !== state.apl) return gs();
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
if (`b${i}` in state == false) return gs();
if (JSON.stringify(getApplicantBucket(i)) !== state[`b${i}`]) return gs();
}
return state.sc;
}
function gs() {
state.sc = getScenario_v2();
state.apl = JSON.stringify(mar.answers.v2.applicants);
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
state[`b${i}`] = JSON.stringify(getApplicantBucket(i))
}
return state.sc;
}
function set() {
}
return {
get : get,
___id : "applicant v2 cache"
}
})()
function getApplicantsNames_v2(n) {
return (function(){
if (!mar.STATIC) setStaticVars();
let retval = [];
//let _sc = getScenario_v2();
if (!mar.answers.v2.applicants) {
let obj = {
name : "borrower",
Name : "Borrower",
names : "borrower's",
Names : "Borrower's",
ino : "Yours",
prefix : "Your",
PREFIX : "YOUR",
tel : "",
email : "",
found : false,
finished : false,
cscore : getScenario_data("applicant1_cscore",0),
dbg : "no applicant data ",
sn : ""
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = 0;
retval.push(obj);
} else {
let _scenario = getApplicantsNames_v2_lastscenario.get();
// let _scenario = getScenario_v2();
let pluralise = function(Str,S) {
if (typeof Str !== "string") return "";
if (Str.endsWith("S") || Str.endsWith("s")) return `${Str}'`;
return `${Str.trim()}'${S}`;
}
let trim = function(Str) {
if (typeof Str !== "string") return "";
return Str.trim();
}
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
let item = mar.answers.v2.applicants[i];
let bucket = getApplicantBucket(i);
if (bucket !== null && "fn" in bucket && bucket.fn != "") {
let obj = {
name : trim(bucket.fn),
Name : trim(bucket.fn).capitalize(),
names : pluralise(bucket.fn,"s"),
Names : pluralise(bucket.fn.capitalize(),"s"),
ino : trim(bucket.fn),
prefix : pluralise(bucket.fn.capitalize(),"s"),
PREFIX : pluralise(bucket.fn.toUpperCase(),"S"),
Fullname: trim(bucket.fn).capitalize() + " " + trim(bucket.ln).capitalize(),
filename: trim(bucket.ln).capitalize() + ", " + trim(bucket.fn).capitalize(),
fn : trim(bucket.fn).capitalize(),
ln : trim(bucket.ln).capitalize(),
data : bucket,
email : trim(bucket.em),
tel : trim(bucket.ph),
sn : bucket.sn,
found : true,
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
finished: (bucket.fn != "" && bucket.ln != "")
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
}
else if ("applicant"+(i+1)+"_name" in _scenario && _scenario["applicant"+(i+1)+"_name"] != "") {
let _name = _scenario["applicant"+(i+1)+"_name"];
let obj = {
name : trim(_name),
Name : trim(_name).capitalize(),
names : pluralise(_name,"s"),
Names : pluralise( _name.capitalize(),"s"),
ino : trim(_name),
prefix : pluralise(_name.capitalize(),"s"),
PREFIX : pluralise(_name.toUpperCase(),"S"),
Fullname : "",
tel : "",
email : MAR.getOpt(bucket,"em",""),
sn : "",
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
found : true,
finished : false
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
}
else if (i == 0) {
let obj = {
name : "borrower",
Name : "Borrower",
names : "borrower's",
Names : "Borrower's",
ino : "Yours",
prefix : "Your",
PREFIX : "YOUR",
Fullname : "",
tel : "",
email : "",
sn : "",
found : false,
finished : false,
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
dbg : "no bucket, no app_name"
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
} else {
if (item.type == mar.APPLICANT_TYPE.SPOUSE) {
let obj = {
name : "spouse",
Name : "Spouse",
names : "spouse's",
Names : "Spouse's",
ino : "Your spouse",
prefix : "Spouse's",
PREFIX : "SPOUSE'S",
Fullname : "",
tel : "",
email : "",
sn : "",
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
found : false,
finished : false
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
} else if (item.type == mar.APPLICANT_TYPE.COBORROWER) {
let obj = {
name : "co-borrower",
Name : "Co-borrower",
names : "Co-borrower's",
Names : "CO-BORROWER'S",
ino : "Your co-borrower",
prefix : "Co-borrower's",
PREFIX : "CO-BORROWER'S",
Fullname : "",
tel : "",
email : "",
sn : "",
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
found : false,
finished : false
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
} else if (item.type == mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT) {
let obj = {
name : "nr co-borrower",
Name : "Nr Co-borrower",
names : "nr co-borrower's",
Names : "Nr Co-borrower's",
ino : "Your co-borrower",
prefix : "Nr Co-borrower's",
PREFIX : "NR CO-BORROWER'S",
Fullname : "",
tel : "",
email : "",
sn : "",
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
found : false,
finished : false
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
} else {
let obj = {
name : "co-applicant",
Name : "Co-applicant",
names : "co-applicant's",
Names : "Co-Applicant's",
ino : "Your co-applicant",
prefix : "Co-applicant's",
PREFIX : "CO-APPLICANT'S",
Fullname : "",
tel : "",
email : "",
sn : "",
cscore : getScenario_data("applicant"+(i+1)+"_cscore",0),
found : false,
finished : false
}
obj.Name_b64 = Base64.encode(obj.Name);
obj.n = i;
retval.push(obj);
}
}
}
}
//console.log(`APPLICANT LENGTH BEG [${mar.answers.v2.applicants.length}] / [${getApplicants_v2().length}] ]`)
if (!mar.isEmpty(n)) return retval[n];
return retval;
})()
}
/**
* back end liabailities
*/
function getBackEndLiabilities_v2_raw(PROG) {
return getBackEndLiabilities_v2_2("raw",PROG);
}
function getBackEndLiabilities_v2(PROG) {
return getBackEndLiabilities_v2_2("",PROG);
}
function getBackEndLiabilities_v2_2(TYPE, PROG) {
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
if (!TYPE) TYPE = "";
var retval = {
oweing : 0,
monthly : 0,
monthly_ex_mort : 0,
monthly_ex_mort_ex_primary : 0,
ccard : 0,
ccard_cnt : 0,
carpayments_cnt : 0,
carpayments : 0,
instalmentloan : 0,
studentloan : 0,
childsupport : 0,
alimoney : 0,
irstax : 0,
jre : 0,
otherloan : 0,
jobrelated : 0,
mortgage_enteredbyclient : 0,
mortgage : 0,
cash2close : 0,
cash2close_outside_closing : 0,
per_applicant_m : [0,0,0,0,0,0,0,0],
debug : [],
detailmatrix : []
};
retval.detailmatrix.push(["TYPE","APPLICANT","OWING","MIN MONTHLY","OPTION","C2C","MONTHLY","NOTE","OPTIONVAR","KEEP","PAYOFF"]);
/**
* clear all the warnings for assets
*/
rules.clearwarnings("liabilities");
var forApplicant = "1";
if ("liabilities" in mar.answers.v2 == false) {
return retval;
}
for (var i=0; i < mar.answers.v2.liabilities.length; i++) {
var item = mar.answers.v2.liabilities[i];
//console.log("item",item);
retval.debug.push(item);
if (item == null) continue;
let _inomask = item.inomask;
let _firstApplicant = getLiabilityFirstAssignment(_inomask);
forApplicant = `${_firstApplicant}`;
item.applicantnum = num(forApplicant);
item.vapplicantnum = MAR.applicants.vid(num(item.applicantnum));
/* rules */
/* var val = __v; */
item.q_balance = item.balance;
item.q_monthly = item.monthly;
item.c2c = 0;
var itemObj = (item.type === "child") ? MAR.xsd.lia_child(item) : MAR.xsd.lia_factory(item);
rules.get("liabilities_"+item.type).forEach(function(xitem){
eval("var _fn = "+xitem+";");
_fn(PROG,"",{
a : getApplicantsNames_v2(item.applicantnum),
item : item
});
_fn = null;
});
/* __v = val; */
// var __m = num(item.q_monthly);
// var __b = num(item.q_balance);
var __m = num(item.monthly);
var __b = num(item.balance);
var __ratio = "";
try {
__ratio = ((__m/__b) * 100).toFixed(1)+"%";
} catch (E) {
__ratio = "";
}
/**
* we need to know if the tax is auto or overriden
*/
var increase_factor = 200 * 0.75;
/*
WTF!!!!
var increase_factor = 200 * 0.75;
if (mar.answers["override_tax_cost"]) {
if (mar.answers["override_tax_cost"].val) {
var __prop_tax_pm = num(mar.answers["override_tax_cost"].val);
if (__prop_tax_pm > 0) {
increase_factor = 200;
}
}
}
*/
var __impact = "";
try {
__impact = ((__m * increase_factor)/1000).toFixed(1)+"k";
} catch (E) {
__impact = "";
}
var __impact_dollars = "";
try {
/**
* if tax is fixes then * 200
* if taxes auto , about 75%
* if reached max of programme
*/
__impact_dollars = (__m * increase_factor).toFixed(0);
} catch (E) {
__impact_dollars = "";
}
/*
if (item.type == "mortgage" || item.type == "heloc") {
retval.mortgage += num(item.monthly);
}
if (item.type == "alimony") retval.alimoney += num(monthly);
if (item.type == "child") retval.childsupport += num(monthly);
if (item.type == "studentloan") {
if (item.paytype == "ibr") {
monthly = num(balance) * 0.01;
balance = 0;
} else if (item.paytype == "def") {
monthly = num(balance) * 0.01;
balance = 0;
} else {
balance = 0;
}
retval.studentloan += num(monthly);
}
if (item.type == "carloan") retval.carpayments += num(monthly);
if (item.type == "carlease") retval.carpayments += num(monthly);
if (item.type == "instalmentloan") retval.carpayments += num(monthly);
if (item.type == "creditcard") retval.ccard += num(monthly);
*/
var _allow_payoff = "N";
if (["creditcard","mortgage","heloc","studentloan","carloan","otherloan","irstax","instalmentloan"].indexOf(item.type) > -1) {
_allow_payoff = "Y";
}
let itemname = item.name;
MAR.ifOpt(item, "_auto_newloan", function(v) {
if (v === "Y") itemname += ` (new line of credit)`;
});
MAR.ifOpt(item, "_auto_bor_dp", function(v) {
if (v === "Y") itemname += ` (borrowed downpayment)`;
});
if (item.omit && item.omit == "Y" ) {
/**
* varius payoff at the closing table things
*/
if (MAR.getOpt(item, "omit_opt","") === "less10pmts") {
retval.cash2close_outside_closing += num(item.balance);
}
if (MAR.getOpt(item, "omit_opt","") === "down-to-omit") {
retval.cash2close_outside_closing += num(item.balance);
}
if (MAR.getOpt(item, "omit_opt","") === "before") {
retval.cash2close_outside_closing += num(item.balance);
}
if (MAR.getOpt(item, "omit_opt","") === "and-cancel") {
retval.cash2close_outside_closing += num(item.balance);
}
if (MAR.getOpt(item, "omit_opt","") === "andclose") {
retval.cash2close_outside_closing += num(item.balance);
}
retval.detailmatrix.push([item.type+":"+itemname,
forApplicant,
num(item.balance), /* oweing */
num(item.monthly), /* min monthly */
"omitted", /* options */
num(item.balance), /* actual c2c */
0, /* actual monthly */
" ratio : " + __ratio + " impact : " + __impact, // + `,qm:${item.q_monthly},qb:${item.q_balance},m:${item.monthly},b:${item.balance}`,
"Estimated increase in loan",
__impact_dollars,
"",
"OMIT",
"",
"",
_allow_payoff,
i,
MAR.getOpt(item, "signer",""),
MAR.getOpt(item, `uuid`,``)
]);
retval.debug.push("n "+i+" "+item.name+" not used as it is marked to pay off");
retval.per_applicant_m[_firstApplicant] += 0;
} else if (item.payoff && item.payoff == true ) {
retval.cash2close += num(item.balance)
retval.detailmatrix.push([item.type+":"+itemname,
forApplicant,
num(item.balance), /* oweing */
num(item.monthly), /* min monthly */
item.payoff, /* options */
num(item.balance), /* actual c2c */
0, /* actual monthly */
" ratio : " + __ratio + " impact : " + __impact, // + `,qm:${item.q_monthly},qb:${item.q_balance},m:${item.monthly},b:${item.balance}`,
"Estimated increase in loan",
__impact_dollars,
"",
"payoff",
"",
"",
_allow_payoff,
i,
MAR.getOpt(item, "signer",""),
MAR.getOpt(item, `uuid`,``)
]);
retval.debug.push("card "+i+" "+item.name+" not used as it is marked to pay off");
retval.per_applicant_m[_firstApplicant] += 0;
} else {
if (item.type == "mortgage" || item.type == "heloc") {
retval.mortgage_enteredbyclient += item.q_monthly;
}
if (item.type == "mortgage") {
// if (TYPE != "raw") continue;
}
var balance = item.q_balance;
var monthly = item.q_monthly;
if (item.type == "mortgage" || item.type == "heloc") {
retval.mortgage += num(monthly);
}
if (item.type == "alimony") retval.alimoney += num(monthly);
if (item.type == "child") retval.childsupport += num(monthly);
// if (item.type == "studentloan") {
// if (item.paytype == "ibr") {
// monthly = num(balance) * 0.01;
// balance = 0;
// } else if (item.paytype == "def") {
// monthly = num(balance) * 0.01;
// balance = 0;
// } else {
// balance = 0;
// }
// retval.studentloan += num(monthly);
// }
if (item.type == "studentloan") retval.studentloan += num(monthly);
if (item.type == "carloan") retval.carpayments += num(monthly);
if (item.type == "carlease") retval.carpayments += num(monthly);
if (item.type == "instalmentloan") retval.carpayments += num(monthly);
if (item.type == "creditcard") retval.ccard += num(monthly);
retval.oweing += num(balance);
retval.monthly += num(monthly);
if (item.type !== "mortgage" && item.type !== "heloc") {
retval.monthly_ex_mort += num(monthly);
}
if (item.type !== "mortgage" && item.type !== "heloc" && item.type.indexOf(``) < 0) {
retval.monthly_ex_mort_ex_primary += num(monthly);
}
//retval.ccard_cnt++;
retval.detailmatrix.push([item.type+":"+itemname,
forApplicant,
num(item.balance), /* oweing */
num(item.monthly), /* min monthly */
"", /* options */
0, /* actual c2c */
num(monthly), /* actual monthly */
" ratio : " + __ratio + " impact : " + __impact + `qm(${item.q_monthly})`, // + `,qm:${item.q_monthly},qb:${item.q_balance},m:${item.monthly},b:${item.balance}`,
"Estimated increase in loan",
__impact_dollars,
"",
"keep",
"",
"",
_allow_payoff,
i,
MAR.getOpt(item, "signer",""),
MAR.getOpt(item, `uuid`,``)
]);
retval.per_applicant_m[_firstApplicant] += num(monthly);
}
}
var _reo = getReo_v2(PROG);
var _reo_liab = (_reo && "liability" in _reo) ? float(_reo.liability) : 0;
retval._reo_liab_ex_prim = (_reo && "liability_ex_primary" in _reo) ? float(_reo.liability_ex_primary) : 0;
retval._reo_liab_prim = (_reo && "liability_primary" in _reo) ? float(_reo.liability_primary) : 0;
if (retval._reo_liab_ex_prim !== 0) {
retval.monthly_ex_mort_ex_primary += float(retval._reo_liab_ex_prim);
if (TYPE != "raw") {
retval.monthly += float(retval._reo_liab_ex_prim);
retval.detailmatrix.push(["liabilities from REO non primary",
"0",
"0",
num(retval._reo_liab_ex_prim).toFixed(2), /* min monthly */
"", /* options */
0, /* actual c2c */
num(retval._reo_liab_ex_prim).toFixed(2), /* actual monthly */
" ",
"",
"",
"",
"",
""
]);
}
}
if (retval._reo_liab_prim !== 0) {
if (TYPE != "raw") {
retval.monthly += float(retval._reo_liab_prim);
retval.detailmatrix.push(["liabilities from REO primary",
"0",
"0",
num(retval._reo_liab_prim).toFixed(2), /* min monthly */
"", /* options */
0, /* actual c2c */
num(retval._reo_liab_prim).toFixed(2), /* actual monthly */
" ",
"",
"",
"",
"",
""
]);
}
}
/**
* add in here
*/
retval.detailmatrix.push([" TOTAL :",
"",
retval.oweing,
"",
"",
retval.cash2close,
retval.monthly,
"",
"",
"",
"",
"",
"",
""
]);
/**
*
* missing - instalment loan
* (similar to a car payment, but not for a payment)
* *8 ask another question
*
* missing - does the person have to pay child support or alimoney
* if they have less than 10 months then it does not have tobe inluded
* ask per month and how many more months
*
* student loans are broken into 2 parts
* student loans and deferred student loans
* -1- if they are paying income based repayments(ibr) (ususlly less 1%) then take 1%
* -2- or in deferment (i.e. they are not paying capital) - within 1%, then take 1%
* -3- paying normally then treat as normal and take the actual payment amount
* therefore always 1% or higher
* -*- this changes often // and is per plan i.e. VA , FHA, etc..
* PARAMETERISE THIS
*
*
*
* note - sometimes different loan programmes have include different liabilities
*
*/
return retval;
}
function application_get_realtor(){
if (!mar.STATIC) setStaticVars();
if ("answers" in mar == false) return {};
if ("v2" in mar.answers == false) return {};
if ("scenario" in mar.answers.v2 == false) return {};
if ("realtor_bucketid" in mar.answers.v2.scenario == false) return {};
let realtorbucket = getBucket(mar.answers.v2.scenario.realtor_bucketid);
if (realtorbucket === null) return {};
return realtorbucket;
}
function getReoSummary(item) {
var retval = {
_sc_reo1 : ""
};
if (item == null) return retval;
if (item.mortgageoptions == mar.MORTGAGEFREE) {
retval._sc_reo1 = "Mortgage free";
} else {
retval._sc_reo1 = "Mortgaged";
}
return retval;
}
/**
* get reo details
*/
function getReoItem(n) {
if (!mar.STATIC) setStaticVars();
var item = null;
if ("reo" in mar.answers.v2) {
item = mar.answers.v2[n];
}
var retval = getReoSummary(item);
return retval;
}
function float(N) {
var retval = parseFloat(N,10);
return (isNaN(retval)) ? 0 : retval;
}
/**
* get reo related questions
*/
function getReo_v2(PROG, dbg = []) {
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
var retval = {
total : 0,
PROG : PROG,
rental : 0,
current_rental : 0,
expected_rental : 0,
income : 0,
income_be : 0,
liability : 0,
liability_be : 0,
liability_ex_primary : 0,
liability_primary : 0,
be_liab : 0,
asset : 0,
items : [],
obj : [],
detailmatrix : [],
breakdown : {
mortgage : 0,
insurance : 0,
tax : 0,
hoa : 0,
monthly : 0
},
currentPrimaryIndex : false,
breakdown_primary : {
mortgage : 0,
insurance : 0,
tax : 0,
hoa : 0,
monthly : 0
}
};
retval.detailmatrix.push([
"NAME", // 0
"USE",
"USE2",
" ",
"AN_TAX",
"AN_HOI", // 5
"M PandI",
"M includes",
"AN_HOA",
"D/N",
"U", // 10
"i",
"VALUE",
"rental", // 13
"cur r",
"exp r", // 15 - exected rental income
"ADDRESS", // 16
"ASS?LIA",
"LIABILITY",
"ASSET",
"PROG", // 20
"SUB", // 21
"ver",
"ver2",
"is_subject",
"exp r NET" // 25 expected rental (net)
]);
/*
var reo_mortgageoptions = $("input:radio[name ='reo_mortgageoptions']:checked").val();
_reo.mortgageoptions = reo_mortgageoptions
_reo.loanlink = txt("#reo_loan_link"); // link to loan
_reo.loanamount = txt("#reo_loan_amount"); //
_reo.monthly = txt("#reo_monthly");
_reo.loantype = radio("reo_type");
_reo.monthly_includes_taxes = yn("#reo_monthly_includes_taxes");
_reo.loan_tax = txt("#reo_loan_tax");
_reo.has_insurance = yn("#reo_has_insurance");
_reo.monthly_includes_insurance = yn("#reo_monthly_includes_insurance");
_reo.loan_tax = txt("#reo_loan_tax");
_reo.loan_insurance = txt("#reo_loan_insurance");
_reo.has_hoa = yn("#reo_has_hoa");
_reo.loan_hoa = txt("#reo_loan_hoa"); //??
_reo.loan_hoa_freq = txt("#reo_loan_hoa_freq"); //??
_reo.property_type = radio("reo_property_type");
_reo.purchasedate = txt("#reo_purchasedate");
_reo.ttype = txt("#ttype"); //??
_reo.ttype2 = txt("#ttype2"); //??
_reo.ttype2 = txt("#ttype2"); //??
_reo.purchase_price = txt("#reo_purchase_price"); //??
_reo.value = txt("#reo_value"); //??
_reo.reo_rental_2015 = txt("#reo_rental_2015"); //??
_reo.reo_rental_2016 = txt("#reo_rental_2016"); //??
_reo.reo_expected_rental = txt(#reo_expected_rental");
reo_rental_income_on_tax_returns
reo_rental_income_continuous_for_2_years
_reo.reo_use = radio("reo_use");
_reo.reo_use2 = radio("reo_use2");
_reo.ad = txt("#ad");
_reo.ad2 = txt("#ad2");
_reo.c1 = txt("#ci");
_reo.zi = txt("#zi");
{
"uuid": "4696894f-e4cd-4671-a9cd-60a1c93a63fc",
"mortgageoptions": "free",
"loanlink": "",
"loanamount": "",
"monthly": "",
"loantype": "",
"monthly_includes_taxes": "Y",
"loan_tax": "1299",
"has_insurance": "Y",
"loan_insurance": "",
"monthly_includes_insurance": "Y",
"has_hoa": "N",
"loan_hoa": "",
"property_type": "sfr",
"purchasedate": "2015-02-20",
"ttype": "purchase",
"ttype2": "primary",
"purchase_price": "11111",
"value": "22222",
"reo_use": "primary",
"reo_use2": "sell",
"ad": "",
"ad2": "",
"c1": "",
"zi": ""
},
*/
retval.items = ("reo" in mar.answers.v2) ? mar.answers.v2.reo : [];
try {
retval.ttype = mar.answers.v2.loan_type;
retval.ttype2 = "primary";
if (mar.answers.v2.scenario.occupancy_type == "occupancy_secondhom") retval.ttype2 = "secondhome";
if (mar.answers.v2.scenario.occupancy_type == "occupancy_investment") retval.ttype2 = "investment";
} catch (e) {
retval.e = e;
}
MAR.reo.tidyUpReoMortgageLinks();
let experience_1y = false;
let experience_2y = false;
for (var i=0; i < retval.items.length; i++) {
var item = retval.items[i];
if (item == null) continue;
item.experience_1y = false;
item.experience_2y = false;
if (item.reo_use == "investment") {
if (MAR.getOpt(item, "reo_rental_income_on_tax_returns","") === mar.YES) {
item.experience_1y = true;
experience_1y = true;
}
if (MAR.getOpt(item, "reo_rental_income_continuous_for_2_years","") === mar.YES) {
item.experience_2y = true;
experience_2y = true;
}
}
}
/**
* loop through all REO items
*/
for (var i=0; i < retval.items.length; i++) {
var item = retval.items[i];
if (item == null) continue;
item.experience_1y_i = false;
item.experience_2y_i = false;
if (item.reo_use == "investment") {
if (MAR.getOpt(item, "reo_rental_income_on_tax_returns","") === mar.YES) {
item.experience_1y_i = true;
}
if (MAR.getOpt(item, "reo_rental_income_continuous_for_2_years","") === mar.YES) {
item.experience_2y_i = true;
}
}
var D = "";
var U = item.reo_use+">"+item.reo_use2
var N = "";
var loantype = item.loantype;
var reo_more_double_fha_death = item.reo_more_double_fha_death;
var reo_more_double_fha_divorce = item.reo_more_double_fha_divorce;
var reo_more_double_fha_100m = item.reo_more_double_fha_100m;
item.taxyear_c = MAR.getApplicantLastTaxYear(0);
item.taxyear_p = MAR.getApplicantLastTaxYear(0)-1;
item.taxyear_pp = MAR.getApplicantLastTaxYear(0)-2;
N += "loantype fha :"+loantype+"
";
if (loantype == "fha") {
N += "double fha death :"+reo_more_double_fha_death+"
";
N += "double fha divorce :"+reo_more_double_fha_divorce+"
";
N += "double fha 100m :"+reo_more_double_fha_100m+"
";
}
if (item.mortgageoptions == mar.MORTGAGEFREE) {
D = "mortgage free";
}
var monthly_mortgage = 0;
item.LOANMONTHLY = 0;
item.LOAN = [];
item.LOAN2 = "N";
item.LOANBALANCE = 0;
item.LOANNAMES = "";
item.CALC_NPRF = 0;
if ("loanlink" in item && item.loanlink != "") {
try {
// var loanitem = mar.answers.v2.liabilities[num(item.loanlink)]; /* LLINK, change to UUID */
let loanlinkA = item.loanlink.split(",")
D = "mortgage "+item.loanlink;
for (let ii=0; ii < loanlinkA.length; ii++) {
var loanitem = MAR.liabilities.getByUUID(loanlinkA[ii]);
monthly_mortgage = (loanitem) ? loanitem.monthly : 0;
item.LOANMONTHLY += num(loanitem.monthly);
item.LOANBALANCE += num(loanitem.balance);
item.LOANNAMES += MAR.getOpt(loanitem, "name","")+" ";
item.LOAN.push(loanitem);
if (loanitem) item.LOAN2 = "Y";
}
} catch (E) {
console.error("cfc-link",E)
}
}
item._use_rq_for_monthly = false;
if (MAR.getOpt(item,"is_subject_property","") === "Y" && MAR.getOpt(item,"is_current_primary",false) === false) {
/**
* subject property is not the primary
* Therefore replace the LOAN with the offer
*/
let rq_base = getScenario_data(`_ratequote_base`, false);
let rq_monthly_total = getScenario_data(`goals_target_budget_high`);
if (rq_base !== false) {
item._use_rq_for_monthly = true;
item.RQ_LOANMONTHLY = rq_monthly_total;
item.RQ_BASE = rq_base;
}
}
item.rental = 0;
item.current_rental = 0;
item.expected_rental = 0;
item.rent_dec_reason = "";
item.rent_dec_reasons = [];
item.rent_dec_perc = 0;
monthly_mortgage = item.LOANMONTHLY;
item.monthly_mortgage = monthly_mortgage;
/**
* make sure we have the entered values for ins tax etc..
*/
var ins = 0;
var tax = 0;
var hoa = 0;
var enc_ins = 0;
var enc_tax = 0;
var enc_hoa = 0;
item.o_monthly_mortgage = monthly_mortgage;
item.o_tax = 0;
item.o_ins = 0;
N += "[COSTS : mortgage:"+monthly_mortgage;
if (item.mortgageoptions == mar.MORTGAGEFREE || item.monthly_includes_taxes !== mar.YES) {
tax = Math.floor(float(item.loan_tax)/12);
item.o_tax = tax;
N += " tax:"+tax;
} else if (item.monthly_includes_taxes === mar.YES) {
tax = Math.floor(float(item.loan_tax)/12);
item.o_tax = `Included`;
monthly_mortgage -= tax;
N += " tax:"+tax;
} else {
N += " tax Included";
}
if (item.monthly_includes_taxes !== mar.YES) {
enc_tax = tax;
}
if (item.mortgageoptions == mar.MORTGAGEFREE || item.monthly_includes_insurance !== mar.YES) {
if (item.has_insurance == mar.YES) {
ins = Math.floor(float(item.loan_insurance)/12);
item.o_ins = ins;
N += ",ins:"+ins;
}
} else if (item.monthly_includes_insurance === mar.YES) {
if (item.has_insurance == mar.YES) {
ins = Math.floor(float(item.loan_insurance)/12);
item.o_ins = `Included`;
monthly_mortgage -= ins;
N += ",ins:"+ins;
}
} else {
N += " ins Included";
}
if (item.monthly_includes_taxes !== mar.YES) {
enc_ins = ins;
}
if (item.has_hoa == mar.YES) {
hoa = float(item.loan_hoa);
var freq = float(item.loan_hoa_freq);
hoa = hoa / freq;
N += ",hoa:"+hoa;
} else {
N += " noHOA";
}
var monthly = (float(monthly_mortgage) + float(ins) + float(tax) + float(hoa));
N += " monthly:"+monthly;
N += "]";
if (item._use_rq_for_monthly === true) {
/* -- FEBE RULE 2 -- */
monthly = num(item.RQ_LOANMONTHLY);
N += ` monthly from offer:${monthly}]`;
}
item.monthlybreakdown = {
mortgage : float(monthly_mortgage),
insurance : float(ins),
tax : float(tax),
hoa : float(hoa),
monthly : monthly,
o_mortgage : item.o_monthly_mortgage,
o_tax : item.o_tax,
o_ins : item.o_ins
};
item.enc_maintenance_A = float(enc_ins) + float(enc_tax) + float(hoa);
item.enc_maintenance_C = float(enc_ins) + float(enc_tax) + float(hoa);
/**
* Accumulate
* retval -> breakdown -> [mortgage, insurance, tax, hoa, monthly]
*/
for (let x in item.monthlybreakdown) {
retval.breakdown[x] += item.monthlybreakdown[x];
}
/**
* If this is the primary Accumulate
* retval -> breakdown_primary -> [mortgage, insurance, tax, hoa, monthly]
*/
item.is_current_primary = false;
if (item.reo_use == "primary" && MAR.getOpt(item, "whosname","").includes("0") && retval.currentPrimaryIndex === false) {
retval.currentPrimaryIndex = i;
item.is_current_primary = true;
for (let x in item.monthlybreakdown) {
retval.breakdown_primary[x] += item.monthlybreakdown[x];
}
}
item.rentalA = item.rental;
item.rentalC = false;
item.rentalE = false;
item.rentalF = false;
item.gross_rental = false;
item.rental_income_capped_zero = false;
if (item.reo_use == "investment") {
var last = ("reo_rental_2015" in item) ? float(item.reo_rental_2015,10) : 0;
var prev = ("reo_rental_2016" in item) ? float(item.reo_rental_2016,10) : 0;
var pm = ("reo_rental_pm" in item) ? float(item.reo_rental_pm,10) : false;
var reo_rental_future_contract = MAR.getOpt(item, "reo_rental_future_contract" , "N");
if (pm !== false) {
item.rental = pm
} else {
item.rental = (((prev+last)/2)/12);
}
if (PROG === "va" && item.expereince_2y === false) {
item.rental = 0;
item.rent_dec_reason = "0% VA not on tax for 2 years";
item.rent_dec_reasons = ["Zero usable rent because the program is VA and it is not on the tax returns for at least 2 years"];
item.rent_dec_reasons = ["Rental income not on taxes. Elaine expects 0% of rent to be allowed as income."]
}
if (PROG === "fha" && item.expereince_1y === false) {
item.rental = 0;
item.rent_dec_reason = "0% FHA not on tax for 1 year";
item.rent_dec_reasons = ["Zero usable rent because the program is FHA and it is not on the tax returns for at least 1 years"];
item.rent_dec_reasons = ["Rental income not on taxes. Elaine expects 0% of rent to be allowed as income."]
}
item.rentalB = item.rental;
var deduction = false;
// var reo_rental_income_continuous_for_2_years = item.reo_rental_income_continuous_for_2_years;
// if (reo_rental_income_continuous_for_2_years == mar.NO) {
// if (!deduction) {
// item.rental = float(item.rental) * 0.75;
// item.rentalB = item.rental;
// N += "[CUR non continuous - deduct 25%:"+item.rental;
//
// deduction = true;
// }
//
// var reo_rental_start_date = item.reo_rental_start_date;
// var reo_rental_start_date_D = new Date(reo_rental_start_date);
//
// N += " " + reo_rental_start_date;
// N += " " + reo_rental_start_date_D;
//
// }
item.rentalC = false;
var reo_rental_income_on_tax_returns = item.reo_rental_income_on_tax_returns;
let reo_rental_future_contract_rentroll = MAR.getOpt(item,`reo_rental_future_contract_rentroll`,``);
if (reo_rental_income_on_tax_returns == mar.NO) {
if (reo_rental_future_contract !== "Y" && reo_rental_future_contract_rentroll !== "Y") {
if (!deduction) {
// item.rental = float(item.rental) * 0.75;
// item.rentalC = item.rental;
//
// N += "[CUR not on tax returns - deduct 25%:"+item.rental;
//
// deduction = true;
item.rental = 0;
item.rentalC = item.rental;
N += "[CUR not on tax returns - deduct 100%:"+item.rental;
deduction = true;
item.rent_dec_reason = "0% Inv->not on tax->No future contract";
item.rent_dec_reasons = ["Zero usable rent because this Investment property does not appear on tax returns and has no future contract or rent roll analysis"];
}
} else {
item.rental = float(item.rental) * 0.75;
item.rentalC = item.rental;
N += "[CUR not on tax retunns with 12 month contract - deduct 25%:"+item.rental;
deduction = true;
item.rent_dec_reason = "75% Inv->not on tax->Has future contract";
if (reo_rental_future_contract === "Y") {
item.rent_dec_reasons = ["Rental income not on taxes. Elaine expects 75% of rental contract"];
} else {
item.rent_dec_reasons = ["Rental income not on taxes. Elaine expects 75% of rent roll analysis"];
}
}
} else {
// var reo_rental_income_on_tax_returns_100 = item.reo_rental_income_on_tax_returns_100;
// if (reo_rental_income_on_tax_returns_100 == mar.NO) {
//
// if (!deduction) {
// item.rental = float(item.rental) * 0.75;
// item.rentalD = item.rental;
//
// N += "[CUR not on tax 100 returns - deduct 25%:"+item.rental;
// deduction = true;
// }
// }
}
if (item.rental > 0 && experience_1y === false) {
item.rental_income_capped_zero = true;
item.rent_dec_reason += "Capped at zero (no experience)";
item.rent_dec_reasons.push(", however never more than $ 0 income, due to lack of experience.");
}
N += ` invchk2 : rent_dec_reason ${item.rent_dec_reason}`;
var reo_rental_future_contract = item.reo_rental_future_contract;
if (item.rental > 0 && item.rent_dec_reason === "") {
item.rent_dec_reason = "100% rental income";
item.rent_dec_reasons = [];
}
if (PROG == "other" && item.rent_dec_reasons.length > 0) {
item.rent_dec_reasons.push(". Elaine expects the Rental income partially usable in NonQM according to lender guidelines. Check guidelines.");
} else {
item.rent_dec_reasons.push(". Elaine expects the Rental income usable according to lender guidelines. Check guidelines.");
}
N += "[CUR rental:"+item.rental;
item.rentalE = item.rental;
item.rental -= monthly;
item.rentalF = item.rental;
N += " net-rental:"+item.rental;
N += "]";
item.current_rental = item.rental;
}
var loan_hoa = float(item.loan_hoa,10);
var loan_hoa_freq = ("loan_hoa_freq" in item) ? float(item.loan_hoa,10) : 12; // per 1 , 3 , 12 months
loan_hoa = loan_hoa / loan_hoa_freq;
item.expected_rentalA = item.expected_rental;
if (item.reo_use == "primary") {
/**
* primary -> investment
*/
if (item.reo_use2 == "investment") {
item.expected_rental = 0;
item.expected_rentalB = item.expected_rental;
if ("reo_expected_rental" in item) {
item.expected_rental = float(item.reo_expected_rental);
N += "[EXP rental:"+item.expected_rental;
item.expected_rentalC = item.expected_rental;
}
if ("reo_expected_rental_have_contract" in item && item.reo_expected_rental_have_contract != mar.YES) {
expected_rental = 0;
item.expected_rentalD = item.expected_rental;
N += " We cant use it because there is no contract";
N += " net-rental:"+item.expected_rental;
item.rent_dec_reason = "0% No Contract";
item.rent_dec_reasons = ["Zero usable rent because this Investment property does not have a contract for the expected rental"];
}
/**
* fha does not allow any expected income from the conversion of a property
*/
if (PROG == "fha" && item.expected_rental > 0) {
var reo_type = item.loantype; /* this is the loan type e.g. fha */
var reo_more_100_miles = item.reo_more_100_miles; /* is fha more than 100 miles away */
if (reo_more_100_miles == mar.YES) {
N += " fha more that 100 miles ";
N += " fha deduction: 0 ";
N += " net-rental:"+item.expected_rental;
} else {
item.expected_rental = 0;
N += " fha deduction: 100% ";
N += " net-rental:"+item.expected_rental;
item.rent_dec_reason = "0% FHA 100 mi";
item.rent_dec_reasons = ["Zero usable rent because this Investment property is less than 100 miles away and this is not allowed under FHA rules"];
}
}
if (PROG == "va" && item.expected_rental > 0) { // of the vacating property //
expected_rental = 0;
item.expected_rentalD = item.expected_rental;
item.rent_dec_reason = "0% VA";
item.rent_dec_reasons = ["Zero usable rent because this Investment property is not allowed under VA rules"];
}
N += ` invchk :${float(item.expected_rental)} ${(float(item.expected_rental) > 0)}`;
N += ` invchk : rent_dec_reason ${item.rent_dec_reason}`;
if (num(item.expected_rental) > 0) {
item.gross_rental = item.expected_rental;
item.expected_rental = float(item.expected_rental * 0.75);
item.expected_rentalE = item.expected_rental;
N += " less 25% :"+item.expected_rental;
item.rent_dec_reason = "x75% Prim -> invest";
item.rent_dec_reasons = ["75% usable rent because this Investment property is flipping from a primary"];
}
N += ` invchk1 : rent_dec_reason ${item.rent_dec_reason}`;
if (item.expected_rental > 0 && experience_1y === false) {
item.rental_income_capped_zero = true;
item.rent_dec_reason += "Capped at zero (no experience)";
item.rent_dec_reasons.push(", however never more than $ 0 income, due to lack of experience.");
// item.rent_dec_reasons.push("Rent is capped at zero due to lack of experience");
}
N += ` invchk2 : rent_dec_reason ${item.rent_dec_reason}`;
if (PROG == "other" && item.rent_dec_reasons.length > 0) {
item.rent_dec_reasons.push(". Elaine expects the Rental income partially usable in NonQM according to lender guidelines. Check guidelines.");
} else {
item.rent_dec_reasons.push(". Elaine expects the Rental income usable in NonQM according to lender guidelines. Check guidelines.");
}
//item.expected_rental -= float(monthly);
item.expected_rentalF = item.expected_rental;
N += " less costs of:"+monthly;
N += " net-rental:"+item.expected_rental;
N += "]";
item.rental += item.expected_rental
item.rental0A = item.rental;
}
}
if (item.reo_use == "investment" || item.reo_use2 == "investment") {
if (MAR.is_current_address_rented_and_will_continue() !== false) {
if (PROG == "other") {
item.rent_dec_reasons.push("** Check QM guidelines if buying or refinancing an Investment Property is allowed when no primary property is owned.
");
}
}
}
if (item.reo_use != "investment") {
/**
* primary or secondary, deduct the monthly from the rent
*/
item.rental -= monthly;
item.rental0B = item.rental;
} else {
/**
* investment say that the expected rent is the rent
*/
item.expected_rental = item.rental;
}
if (item.gross_rental === false) {
item.gross_rental = item.expected_rental;
}
item.DBG = N;
if (item.reo_use2 == "sell") {
/**
* If we are going to sell the property , calculate the NPRF on the sales price
*/
item.rental = 0;
item.CALC_NPRF = Math.round(num(item.reo_expected_salesprice) - item.LOANBALANCE - ((num(item.reo_expected_salesprice) * num(item.reo_expected_salesperc)) / 100) );
}
let _reoitem = retval.items[i];
/**
* warnings
*/
if (MAR.getOpt(_reoitem, "verified", "") !== "N") {
/**
* check for warnings only on Verified items
*/
item.skip_nodoc = false;
if (MAR.app.is_dscr() === true && MAR.getOpt(item,"is_subject_property","") !== "Y") {
item.skip_nodoc = true;
}
dbg.push(`reo item start`);
_reoitem.warnings=[];
let warning_type = "reo_item";
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i,{
name : D,
item : _reoitem
});
_fn = null;
});
dbg.push(`reo item end`);
dbg.push(`reo item start1`);
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
_reoitem.warnings.push(mar.warnings[warning_type][_wc])
}
}
dbg.push(`reo item end`);
}
retval.obj.push({
i : i,
reo_property_name : "reo_property "+i,
reo_use_of_property : item.reo_use,
reo_eventual_use_of_property : item.reo_use2,
reo_other_monthly_rent : item.rental, //
reo_annual_tax_bill : item.loan_tax, //
reo_annual_hoi_tax_bill : item.loan_insurance, //
reo_monthly_mortgage_payment : monthly_mortgage, //
reo_monthly_mortgage_payment_includes : 'Y',
reo_annual_hoa_fees : loan_hoa
});
/**
* calculate a value to use in BE liabilities
*/
item.be_liab = item.rental;
if (retval.ttype === "purchase") {
/**
* purchase
*/
if (item.reo_use2 == "sell") {
/**
* purchase + sell property - wipe out the value from BE liabilities
*/
item.be_liab = 0;
}
} else {
/**
* refi
*/
// if (MAR.getOpt(item,"is_subject_property","") === "Y") {
if (MAR.getOpt(item,"is_current_primary",false) === true) {
/**
* refi and subject property - wipe out income / liability from the be value
*/
item.be_liab = 0;
}
}
if (item.rental_income_capped_zero === true && item.rental > 0) {
item.rental = 0;
item.be_liab = 0;
}
N += ` invchkE : rent_dec_reason ${item.rent_dec_reason}`;
retval.detailmatrix.push([
D, // name
item.reo_use, /* 01 - e.g. primary */
item.reo_use2, /* 02 - e.g. sell */
0, // rent
item.loan_tax, /* 04 - tax monthly */
item.loan_insurance, /* 05 - hoi */
monthly_mortgage, // mortgage /* 06 - monthly mortgage */
'Y', // includes
loan_hoa, /* 08 - annual hoa fees */
D+N, // description
U, /* 10 */
i, /* 11 - the index */
item.value,
item.rental.toFixed(2), /* 13 --- dont know why but this seems to be the overall asset/liability value*/
item.current_rental.toFixed(2),
item.expected_rental.toFixed(2), /* 15 - expected rental */
(item.address) ? item.address : "tbd||||", /* 16 - address */
(item.rental < 0) ? "LIABILITY" : "ASSET", /* 17 - liabilty or asset*/
(item.rental < 0) ? item.rental.toFixed(2) : "", /* 18 - Liability value */
(item.rental < 0) ? "" : item.rental.toFixed(2), /* 19 - asset value */
PROG, /* 20 */
item.uuid, /* 21 - UUID */
MAR.getOpt(item,"verified",""),
MAR.getOpt(item,"verified2",""),
MAR.getOpt(item,"is_subject_property",""), /* 24 - is the subject property? */
item.gross_rental, /* 25 - gross rental */
item.reo_rental_pm, /* 26 - entered rental */
item.reo_expected_rental, /* 27 - expected rentl */
item.be_liab, /* 28 - value to use in back end liabilities / income */
item.rent_dec_reason, /* 29 - the reason that the rent was reduced */
((item.reo_use === "investment") ? item.rentalE : item.expected_rental), /* 30 - income */
((item.reo_use === "investment") ? num(item.reo_rental_pm) : num(item.reo_expected_rental)), /* 31 - net rental */
item.whosname, /* 32 - whos name "1" "0" "0,99" */
item.rent_dec_reasons /* 33 - reasons array */
]);
if (MAR.getOpt(item,"verified","") === "Y") {
retval.rental += float(item.rental);
retval.current_rental += float(item.current_rental);
retval.expected_rental += float(item.expected_rental);
if (float(item.rental) < 0) {
retval.liability += float(item.rental)*-1;
} else {
retval.asset += float(item.rental);
retval.income += float(item.rental);
}
if (float(item.be_liab) < 0) {
retval.liability_be += float(item.be_liab)*-1;
} else {
retval.asset_be += float(item.be_liab);
retval.income_be += float(item.be_liab);
}
if (float(item.be_liab) < 0) {
if (item.is_current_primary === false) {
retval.liability_ex_primary += float(item.be_liab)*-1;
} else {
retval.liability_primary += float(item.be_liab)*-1;
}
}
}
}
retval.detailmatrix.push([
"","","","","","","","","","","","","","","","","","TOTAL",
retval.liability.toFixed(2),
retval.income.toFixed(2),
PROG
]);
return retval;
}
/**
* get County
*/
function getProgramme_v2() {
if (!mar.STATIC) setStaticVars();
if (mar.answers.v2.scenario.programme && mar.answers.v2.scenario.programme != "") {
return mar.answers.v2.scenario.programme;
}
return mar.PROGRAMME_CONVENTIONAL;
}
/**
* get County "37021|NORTH CAROLINA : BUNCOMBE (37021)"
*/
function getCounty_v2(cnty) {
if (arguments.length > 0 && cnty != null && cnty != "" && cnty.indexOf("|") > -1) {
var retval = cnty.split("|")[0]; //val;
return retval;
}
if (!mar.STATIC) setStaticVars();
var retval = mar.answers.v2.scenario.property_county.split("|")[0]; //val;
return retval;
}
/**
* get loan actually rquired
*/
function getLoanRequired_v2() {
if (!mar.STATIC) setStaticVars();
if (mar.answers.v2.scenario.loan_type_refinance_house_value) {
return num(mar.answers.v2.scenario.loan_type_refinance_house_value);
}
if (mar.answers.v2.scenario.override_required_loan) {
return num(mar.answers.v2.scenario.override_required_loan);
}
return 0; /* 0 is no limit , go for max */
}
/**
* translate the loan duration into a number of years
*/
function getLoanDuration_v2() {
if (!mar.STATIC) setStaticVars();
//console.log("mar.answers.v2.scenario.term_of_loan "+mar.answers.v2.scenario.term_of_loan+" , mar.LOAN_TERM_30" + mar.LOAN_TERM_30);
if (mar.answers.v2.scenario.term_of_loan == mar.LOAN_TERM_30) {
return 30;
}
if (mar.answers.v2.scenario.term_of_loan == mar.LOAN_TERM_20) {
return 20;
}
if (mar.answers.v2.scenario.term_of_loan == mar.LOAN_TERM_15) {
return 15;
}
if (mar.answers.v2.scenario.term_of_loan == mar.LOAN_TERM_10) {
return 10;
}
return 30;
}
/**
* refinance options
*/
function getRefi_v2() {
return MAR.getRefi_v2()
if (!mar.STATIC) setStaticVars(mar.answers.v2.scenario);
var retval = {
loan_type_refinance_takehome_value : 0,
refi_home_insurance_cost : 0,
flood_estimate : 0
}
if (getLoanType() && getLoanType() == mar.LOAN_TYPE_REFINANCE) {
retval = {
loan_type_refinance_takehome_value : num(mar.answers.v2.scenario.loan_type_refinance_takehome_value),
refi_home_insurance_cost : num(mar.answers.v2.scenario.refi_home_insurance_cost),
flood_estimate : num(mar.answers.v2.scenario.flood_estimate)
};
}
return retval;
}
/**
* get Property type
*/
function getPropertyType_v2(_sc) {
/**
* type of property
*/
if (!mar.STATIC) setStaticVars();
if (arguments.length == 0 || !_sc) {
_sc = mar.answers.v2.scenario;
}
return MAR.getPropertyType_v2(_sc);
// var retval = "";
//
// if (_sc.property_type == mar.PROPERTY_TYPE_SFR) retval = "sfr";
// if (_sc.property_type == mar.PROPERTY_TYPE_CONDO) retval = "condo";
// if (_sc.property_type == mar.PROPERTY_TYPE_DUPLEX) retval = "2unit";
// if (_sc.property_type == mar.PROPERTY_TYPE_TRIPLEX) retval = "3unit";
// if (_sc.property_type == mar.PROPERTY_TYPE_FOURPLEX) retval = "4unit";
// if (_sc.property_type == mar.PROPERTY_TYPE_OTHER) retval = "Other";
// return retval;
}
/**
* get Property type
*/
function getPropertyUnits_v2(TYPE) {
/**
* type of property
*/
if (!mar.STATIC) setStaticVars();
var retval = "";
if (arguments.length == 0) {
TYPE = mar.answers.v2.scenario.property_type;
}
if (TYPE == mar.PROPERTY_TYPE_SFR) retval = "1";
if (TYPE == mar.PROPERTY_TYPE_CONDO) retval = "1";
if (TYPE == mar.PROPERTY_TYPE_DUPLEX) retval = "2";
if (TYPE == mar.PROPERTY_TYPE_TRIPLEX) retval = "3";
if (TYPE == mar.PROPERTY_TYPE_FOURPLEX) retval = "4";
if (TYPE == mar.PROPERTY_TYPE_OTHER) retval = "1";
return retval;
}
/**
* get the type of loan
*/
function getLoanType_v2() {
return MAR.getLoanType_v2(mar.answers.v2.scenario);
}
function getDoOwnRealestate() {
var _d = getDeclarations_v2();
//console.log("getDoOwnRealestate",_d);
for (var i=0; i < _d.length; i++) {
if (_d[i] && _d[i].credit_currently_own_realestate == mar.YES) return true;
if ( MAR.ownsProperty(i)) return true;
if ( MAR.ownsPrimary(i)) return true;
}
return false;
}
function getUsedAddressList() {
return MAR.getUsedAddressList();
}
function addScenario_data(retval,VAR,DEF) {
retval[VAR] = getScenario_data(VAR,DEF)
}
function getScenario_data(VAR,DEF,ANS) {
if (!mar.STATIC) setStaticVars();
// with APP
if (arguments.length > 2) {
if (!("v2" in ANS)) return DEF;
if (!("scenario" in ANS.v2)) return DEF;
if (VAR in ANS.v2.scenario) return ANS.v2.scenario[VAR];
return DEF;
}
// with mar.answers
if (!("scenario" in mar.answers.v2)) {
if (arguments.length > 1) return DEF;
return {};
}
if (arguments.length == 0) return mar.answers.v2.scenario;
if (VAR in mar.answers.v2.scenario && typeof mar.answers.v2.scenario[VAR] !== "undefined") return mar.answers.v2.scenario[VAR];
if (arguments.length > 1) return DEF;
return "";
}
function getScenario_data_int(VAR,DEF,ANS) {
if (!mar.STATIC) setStaticVars();
// with APP
if (arguments.length > 2) {
if (!("v2" in ANS)) return DEF;
if (!("scenario" in ANS.v2)) return DEF;
if (VAR in ANS.v2.scenario) return num(ANS.v2.scenario[VAR]);
return DEF;
}
// with mar.answers
if (!("scenario" in mar.answers.v2)) {
if (arguments.length > 1) return DEF;
return 0;
}
if (arguments.length == 0) return mar.answers.v2.scenario;
if (VAR in mar.answers.v2.scenario && typeof mar.answers.v2.scenario[VAR] !== "undefined") return num(mar.answers.v2.scenario[VAR]);
if (arguments.length > 1) return DEF;
return 0;
}
function delScenario_data(VAR) {
if (!mar.STATIC) setStaticVars();
if (!("scenario" in mar.answers.v2)) {
return false;
}
if (VAR in mar.answers.v2.scenario) delete mar.answers.v2.scenario[VAR];
return true;
}
var replay = [];
function setScenario_data(VAR,VAL) {
// replay.push(`setScenario_data("${VAR}",JSON.parse("${JSON.stringify(VAL)}"));`)
let retval = false;
if (!mar.STATIC) setStaticVars();
if (!("v2" in mar.answers)) mar.answers.v2 = {};
if (!("scenario" in mar.answers.v2)) mar.answers.v2.scenario = {};
// e.g. __enc_incomechange_1594703676446 = "{"592-05-8244":{"base":9718,"baseD":-5282}}"
if (VAR.startsWith("__enc_incomechange_")) {
for (let x in mar.answers.v2.scenario) {
if (x.startsWith("__enc_incomechange_")) {
let x_val = mar.answers.v2.scenario[x];
if (x_val === VAL) {
return false;
}
}
}
}
if (VAR in mar.answers.v2.scenario == false) retval = true;
if (mar.answers.v2.scenario[VAR] != VAL) {
retval = true;
mar.answers.v2.scenario[VAR] = VAL
MAR.activity_log.mod("scenario", VAR, Base64.encode(`${VAL}`));
}
/**
* applicant 1 creditscore becomes the main creditscore
*/
if (VAR == "applicant1_cscore" ||
VAR == "applicant2_cscore" ||
VAR == "applicant3_cscore") {
/**
* credit scores
*/
MAR.setLowestCreditScore(mar.answers);
// var cscore = mar.answers.v2.scenario.applicant1_cscore;
//
// if (mar.answers.v2.scenario.applicant2_cscore
// && mar.answers.v2.scenario.applicant2_cscore > 0
// && mar.answers.v2.scenario.applicant2_cscore < cscore) {
// cscore = mar.answers.v2.scenario.applicant2_cscore;
// }
// if (mar.answers.v2.scenario.applicant3_cscore
// && mar.answers.v2.scenario.applicant3_cscore > 0
// && mar.answers.v2.scenario.applicant3_cscore < cscore) {
// cscore = mar.answers.v2.scenario.applicant3_cscore;
// }
// mar.answers.v2.cscore = cscore
}
/**
* set the has ANY applicant owned property
*/
if (typeof VAR === "string" && VAR.startsWith("has_applicant") && VAR.endsWith("_owned_property_in_last_3_years")) {
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years = "N";
for (i=1; i < MAR.MAXBORROWERS; i++) {
var __property = "has_applicant"+i+"_owned_property_in_last_3_years";
if (__property in mar.answers.v2.scenario && mar.answers.v2.scenario[__property] == "Y"){
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years = "Y";
}
}
}
return retval;
}
function getV2_data(VAR,DEF) {
if (!mar.STATIC) setStaticVars();
if (arguments.length == 0) return mar.answers.v2;
if (VAR in mar.answers.v2) return mar.answers.v2[VAR];
if (arguments.length > 1) return DEF;
return "";
}
function setV2_data(VAR,VAL) {
if (!mar.STATIC) setStaticVars();
if (!("v2" in mar.answers)) mar.answers.v2 = {};
mar.answers.v2[VAR] = VAL;
}
var ______inc = 0;
/**
* get the scenario
*/
function getScenario_v2(PROG) {
______inc = new Date().getTime();
let tims = [];
let stime = false;
let ltime = false;
let _now = function() {
if (typeof "context" !== "undefined") {
return Math.floor(context.global.process.hrtime()/1000)
}
return new Date().getTime()
}
let timer = function(lbl) {
let now = new Date().getTime();
if (stime == false) {
tims.push(` ${lbl} .. START `);
stime = now;
} else {
tims.push(` ${lbl} .. ${now - stime} ..(${(now-ltime)})`);
}
ltime = now;
}
try {
if (context) {
timer = function(lbl) {
let now = context.global.process.hrtime();
if (stime == false) {
tims.push(` ${lbl} .. START`);
stime = now;
} else {
let dif1 = Math.floor(context.global.process.hrtime(stime)[1]/1000);
let dif2 = Math.floor(context.global.process.hrtime(ltime)[1]/1000);
tims.push(` ${lbl} .. ${dif1} ..(${dif2})`);
}
ltime = now;
}
}
} catch(E){}
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
if (typeof mar.warnings == "undefined") mar.warnings = {};
if (!("scenario" in mar.answers.v2)) return {};
if ("loan_type" in mar.answers.v2.scenario === false && typeof mar.answers.v2.loan_type === "string" ) {
mar.answers.v2.scenario.loan_type = mar.answers.v2.loan_type;
}
timer("start");
var retval = {
tims : tims,
property_type : mar.answers.v2.scenario.property_type,
occupancy_type : mar.answers.v2.scenario.occupancy_type,
mortgage_options : mar.answers.v2.scenario.mortgage_options,
term_of_loan : mar.answers.v2.scenario.term_of_loan,
not_first_time_buyer : mar.answers.v2.scenario.not_first_time_buyer,
property_near_to_water : mar.answers.v2.scenario.property_near_to_water,
square_foot : num(mar.answers.v2.scenario.square_foot), // val
build_period : num(MAR.getOpt(mar.answers.v2.scenario,"build_period","1900")), // val
property_type_community_options
: mar.answers.v2.scenario.property_type_community_options,
loan_type : (mar.answers.v2.scenario.loan_type) ? mar.answers.v2.scenario.loan_type : mar.answers.loan_type,
loan_type_refinance_house_value
: num(mar.answers.v2.scenario.loan_type_refinance_house_value), //val
override_mi_cost : num(mar.answers.v2.scenario.override_mi_cost), //val
override_home_insurance_cost
: num(mar.answers.v2.scenario.override_home_insurance_cost), // val
override_home_owners_association_cost
: num(mar.answers.v2.scenario.override_home_owners_association_cost), // val
override_tax_cost : num(mar.answers.v2.scenario.override_tax_cost), // val
override_prop_tax_percentage_pm : num(mar.answers.v2.scenario.override_prop_tax_percentage_pm),
override_downpayment : num(mar.answers.v2.scenario.override_downpayment), // val
override_qual_inc_pm : num(mar.answers.v2.scenario.override_qual_inc_pm), // val
override_max_budget : num(mar.answers.v2.scenario.override_max_budget), // val
mybudget : num(mar.answers.v2.scenario.mybudget) // val
}
retval.dbg = [];
retval.refi = (retval.loan_type !== "purchase");
retval.use_whatsapp = (MAR.getOpt(mar.answers.v2.scenario,"use_whatsapp","") !== "N");
let sc_int_only = MAR.getOpt(mar.answers.v2.scenario, "is_interestonly","");
let sc_int_only_over = MAR.getOpt(mar.answers.v2.scenario, "is_interestonly_over","");
if (sc_int_only_over === "Y") {
mar.answers.v2.scenario.is_interestonly = "Y";
}
retval.is_nodoc = MAR.getOpt(mar.answers.v2.scenario, "is_nodoc","");
retval.loan_type_purchase_options
= mar.answers.v2.scenario.loan_type_purchase_options; /* timeframe */
retval.property_county = mar.answers.v2.scenario.property_county; /* county */
retval.monthly_rent = num(mar.answers.v2.scenario.monthly_rent); /* monthly rent */
//contains_string_ignore_case
retval.is_primary = MAR.contains_string_ignore_case(retval.occupancy_type, "by_me");
if (retval.is_primary === true) {
if (["duplex","triplex","fourplex"].indexOf(retval.property_type) < 0) { /* cant rent out a sfr */
retval.monthly_rent = 0;
}
}
retval.monthly_rent_occupancy_rate = (retval.monthly_rent > 0) ? MAR.getOpt(mar.answers.v2.scenario, "monthly_rent_occupancy_rate_raw", 75) : 0;
retval.scenario_i_know_my_insurance
= mar.answers.v2.scenario.scenario_i_know_my_insurance /* I know my insurance */
retval.refi_home_insurance_cost
= num(mar.answers.v2.scenario.refi_home_insurance_cost)
retval.hoi_estimate = mar.answers.v2.scenario.hoi_estimate; // this is an object
/*
* hoi_estimate : {
* ins_estimate
* flood_estimate
* hoa_estimate
* prop_tax_percentage_pm
* }
*/
retval.flood_estimate = num(mar.answers.v2.scenario.flood_estimate);
retval.hoa_estimate = mar.answers.v2.scenario.hoa_estimate;
retval.state = {
applicants_phase : 0, // 0 = initial , 1 = subsequent
applicants : 1, // 1 , 2 , 3
currentapplicant : 1 // 1 , 2 , 3
};
if ("state" in mar.answers.v2.scenario) {
if ("applicants_phase" in mar.answers.v2.scenario.state) {
retval.state.applicants_phase = num(mar.answers.v2.scenario.state.applicants_phase);
}
if ("applicants" in mar.answers.v2.scenario.state) {
retval.state.applicants = num(mar.answers.v2.scenario.state.applicants);
}
if ("currentapplicant" in mar.answers.v2.scenario.state) {
retval.state.currentapplicant = num(mar.answers.v2.scenario.state.currentapplicant);
}
}
timer("start p1");
let apvars = [
"applicant(9)_name",
"applicant(9)_cscore:#0",
"applicant(9)_cscore_ref",
"applicant(9)_cscore_ref_enc",
// "#",
// "# citizenship",
// "#",
"scenario_applicant(9)_usc",
"scenario_applicant(9)_gch",
"scenario_applicant(9)_visa_type",
"scenario_applicant(9)_cntry",
// "#",
// "# property",
// "#",
"has_applicant(9)_owned_property_in_last_3_years",
"has_applicant(9)_owned_property_in_last_3_years_type",
"has_applicant(9)_owned_property_in_last_3_years_how",
"does_applicant(9)_own_property",
// "#",
// "# VA",
// "#",
"has_applicant(9)_served_in_us_forces",
"scenario_applicant(9)_served",
"va_active(9)",
"va_active_ed(9)",
"va_coe(9)",
"va_nofee(9)",
"va_employment(9)",
"va_disabled(9)",
"vafirst_time_use(9)",
// "#",
// "# non applicant 1 variables",
"",
"is_there_a_(9th)_borrower",
"(9th)_applicant"
];
timer("start emaxloop");
for (let i=0; i < MAR.MAXBORROWERS; i++) {
let NN = (i+1);
let Nd = MAR.th(NN);
for (let j=0; j < apvars.length; j++) {
let apvar = apvars[j].split(":");
let apvar0 = apvar[0];
if (apvar0.startsWith("#")) continue;
if (apvar0 == "" && i == 0) break;
apvar0 = apvar0.replace("(9)",`${NN}`)
apvar0 = apvar0.replace("(9th)",`${Nd}`)
let apvar_def = (apvar.length < 2) ? "" : apvar[1];
if (apvar_def.startsWith("#")) apvar_def = num(apvar_def.substring(1));
retval[apvar0] = MAR.getOpt(mar.answers.v2.scenario , apvar0 , apvar_def);
//console.log(`appvar i[${i}] // j[${j}] // vars(j)[${apvars[j]}] // varo[${apvar0}] // endvalue[${retval[apvar0]}]`)
}
}
timer("after emaxloop");
// retval.is_there_a_second_borrower = mar.answers.v2.scenario.is_there_a_second_borrower;
// retval.second_applicant = mar.answers.v2.scenario.second_applicant;
// retval.is_there_a_third_borrower = mar.answers.v2.scenario.is_there_a_third_borrower;
// retval.third_applicant = mar.answers.v2.scenario.third_applicant;
// retval.applicant1_name = mar.answers.v2.scenario.applicant1_name;
// retval.applicant2_name = mar.answers.v2.scenario.applicant2_name;
// retval.applicant3_name = mar.answers.v2.scenario.applicant3_name;
// retval.scenario_applicant1_usc = mar.answers.v2.scenario.scenario_applicant1_usc;
// retval.scenario_applicant2_usc = mar.answers.v2.scenario.scenario_applicant2_usc;
// retval.scenario_applicant3_usc = mar.answers.v2.scenario.scenario_applicant3_usc;
//
// retval.scenario_applicant1_gch = mar.answers.v2.scenario.scenario_applicant1_gch;
// retval.scenario_applicant2_gch = mar.answers.v2.scenario.scenario_applicant2_gch;
// retval.scenario_applicant3_gch = mar.answers.v2.scenario.scenario_applicant3_gch;
//
// retval.scenario_applicant1_visa_type = mar.answers.v2.scenario.scenario_applicant1_visa_type;
// retval.scenario_applicant2_visa_type = mar.answers.v2.scenario.scenario_applicant2_visa_type;
// retval.scenario_applicant3_visa_type = mar.answers.v2.scenario.scenario_applicant3_visa_type;
//
// retval.has_applicant1_owned_property_in_last_3_years =
// mar.answers.v2.scenario.has_applicant1_owned_property_in_last_3_years;
// retval.has_applicant2_owned_property_in_last_3_years =
// mar.answers.v2.scenario.has_applicant2_owned_property_in_last_3_years;
// retval.has_applicant3_owned_property_in_last_3_years =
// mar.answers.v2.scenario.has_applicant3_owned_property_in_last_3_years;
//
// retval.has_applicant1_owned_property_in_last_3_years_type =
// mar.answers.v2.scenario.has_applicant1_owned_property_in_last_3_years_type;
// retval.has_applicant2_owned_property_in_last_3_years_type =
// mar.answers.v2.scenario.has_applicant2_owned_property_in_last_3_years_type;
// retval.has_applicant3_owned_property_in_last_3_years_type =
// mar.answers.v2.scenario.has_applicant3_owned_property_in_last_3_years_type;
//
// retval.has_applicant1_owned_property_in_last_3_years_how =
// mar.answers.v2.scenario.has_applicant1_owned_property_in_last_3_years_how;
// retval.has_applicant2_owned_property_in_last_3_years_how =
// mar.answers.v2.scenario.has_applicant2_owned_property_in_last_3_years_how;
// retval.has_applicant3_owned_property_in_last_3_years_how =
// mar.answers.v2.scenario.has_applicant3_owned_property_in_last_3_years_how;
//
//
//
// retval.does_applicant1_own_property =
// mar.answers.v2.scenario.does_applicant1_own_property;
// retval.does_applicant2_own_property =
// mar.answers.v2.scenario.does_applicant2_own_property;
// retval.does_applicant3_own_property =
// mar.answers.v2.scenario.does_applicant3_own_property;
//
// retval.has_applicant1_served_in_us_forces =
// mar.answers.v2.scenario.has_applicant1_served_in_us_forces;
// retval.has_applicant2_served_in_us_forces =
// mar.answers.v2.scenario.has_applicant2_served_in_us_forces;
// retval.has_applicant3_served_in_us_forces =
// mar.answers.v2.scenario.has_applicant3_served_in_us_forces;
// retval.scenario_applicant1_served = mar.answers.v2.scenario.scenario_applicant1_served;
// retval.scenario_applicant2_served = mar.answers.v2.scenario.scenario_applicant2_served;
// retval.scenario_applicant3_served = mar.answers.v2.scenario.scenario_applicant3_served;
//
// retval.va_coe1 = mar.answers.v2.scenario.va_coe1;
// retval.va_coe2 = mar.answers.v2.scenario.va_coe2;
// retval.va_coe3 = mar.answers.v2.scenario.va_coe3;
//
//
//
// retval.va_employment1 = mar.answers.v2.scenario.va_employment1;
// retval.va_employment1 = mar.answers.v2.scenario.va_employment1;
// retval.va_employment1 = mar.answers.v2.scenario.va_employment1;
//
// retval.va_disabled1 = mar.answers.v2.scenario.va_disabled1;
// retval.va_disabled2 = mar.answers.v2.scenario.va_disabled2;
// retval.va_disabled3 = mar.answers.v2.scenario.va_disabled3;
//
// retval.vafirst_time_use1 = mar.answers.v2.scenario.vafirst_time_use1;
// retval.vafirst_time_use2 = mar.answers.v2.scenario.vafirst_time_use2;
// retval.vafirst_time_use3 = mar.answers.v2.scenario.vafirst_time_use3;
retval.goals_target_value = mar.answers.v2.scenario.goals_target_value;
retval.goals_target_downpayment = mar.answers.v2.scenario.goals_target_downpayment;
retval.override_dti_max_front_end = mar.answers.v2.scenario.override_dti_max_front_end;
retval.override_dti_max_back_end = mar.answers.v2.scenario.override_dti_max_back_end;
retval.override_sellconsession = mar.answers.v2.scenario.override_sellconsession;
retval.override_mcc = mar.answers.v2.scenario.override_mcc;
retval.householdsize = mar.answers.v2.scenario.householdsize;
retval.householdincome = mar.answers.v2.scenario.householdincome;
retval.mcc_household = mar.answers.v2.scenario.mcc_household;
retval.mcc_lowincome = mar.answers.v2.scenario.mcc_lowincome;
if ("householdincome" in mar.answers.v2.scenario) {
retval.mcc_lowincome = retval.householdincome;
}
// setScenario_data("householdsize",householdsize);
// setScenario_data("householdincome",householdincome);
retval.scenario_i_know_my_tax = ("scenario_i_know_my_tax" in mar.answers.v2.scenario ) ? mar.answers.v2.scenario.scenario_i_know_my_tax : "N";
retval.scenario_tax = mar.answers.v2.scenario.scenario_tax;
retval.scenario_hoa = mar.answers.v2.scenario.scenario_hoa;
retval.scenario_flood = mar.answers.v2.scenario.scenario_flood;
/**
* have the owned property i.e. first time buyer
*/
retval.has_any_applicant_owned_property_in_last_3_years =
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years;
if (!mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years) {
mar.answers.v2.scenario.has_any_applicant_owned_property_in_last_3_years = "N"
}
/**
* have anybody served?
*/
retval.has_any_applicant_served_in_us_forces =
mar.answers.v2.scenario.has_any_applicant_served_in_us_forces;
if (!mar.answers.v2.scenario.has_any_applicant_served_in_us_forces) {
mar.answers.v2.scenario.has_any_applicant_served_in_us_forces = "N"
}
retval.va_employment = mar.answers.v2.scenario.va_employment;
retval.va_disabled = mar.answers.v2.scenario.va_disabled;
retval.vafirst_time_use = mar.answers.v2.scenario.vafirst_time_use;
if(!retval.va_employment) retval.va_employment = "regular";
if(!retval.va_disabled) retval.va_disabled = "N";
if(!retval.vafirst_time_use) retval.vafirst_time_use = "Y";
/**
* credit score
*/
// retval.applicant1_cscore = mar.answers.v2.scenario.applicant1_cscore;
// retval.applicant2_cscore = mar.answers.v2.scenario.applicant2_cscore;
// retval.applicant3_cscore = mar.answers.v2.scenario.applicant3_cscore;
//
// if (!retval.applicant1_cscore) retval.applicant1_cscore = 0;
// if (!retval.applicant2_cscore) retval.applicant2_cscore = 0;
// if (!retval.applicant3_cscore) retval.applicant3_cscore = 0;
let notNull = function(VAR, DEF) {
if (typeof VAR === "undefined") return DEF;
if (VAR === null) return DEF;
if (typeof VAR === "number") return VAR;
if (typeof VAR === "string") return VAR;
if (!VAR) return DEF;
return VAR;
}
let notNullOptString = function(OBJ, VAR, DEF, MINLEN) {
OBJ[VAR] = notNull(OBJ[VAR], DEF);
if (arguments.length < 4) return;
if (MINLEN === false) return;
if (OBJ[VAR].length < MINLEN) {
OBJ[VAR] = DEF;
}
}
let notNullOptNumeric = function(OBJ, VAR, DEF) {
OBJ[VAR] = num(notNull(OBJ[VAR], DEF));
}
let NOAPPLICANT = false;
for (let i=0; i < MAR.MAXBORROWERS; i++) {
let NN = (i+1); // 1
let Nd = MAR.th(NN); // second;
notNullOptNumeric( retval, `applicant${NN}_cscore` , 0 );
notNullOptString( retval, `applicant${NN}_name` , "" ,1 );
notNullOptString( retval, `applicant${NN}_usc` , "" ,1 );
notNullOptString( retval, `applicant${NN}_gch` , "Y" ,1 );
notNullOptString( retval, `applicant${NN}_visa_type` , "" ,1 );
notNullOptString( retval, `applicant${NN}_cntry` , "" ,1 );
if (i == 0) continue;
notNullOptString( retval, `${Nd}_applicant` , "" ,1 );
if (MAR.getOpt(retval, `is_there_a_${Nd}_borrower`, "") === "") {
let NdApplicant = MAR.getOpt(retval,`${Nd}_applicant`, "");
if (!NdApplicant || NdApplicant === "" || NdApplicant === "none") {
retval[`is_there_a_${Nd}_borrower`] = "N";
} else {
retval[`is_there_a_${Nd}_borrower`] = "Y";
}
}
if (NOAPPLICANT == true) {
retval[`${Nd}_applicant`] = "none";
retval[`is_there_a_${Nd}_borrower`] = "N";
} else {
let NdApplicant = MAR.getOpt(retval, `${Nd}_applicant` , ""); // second applicant
let NdApplicant_is = MAR.getOpt(retval, `is_there_a_${Nd}_borrower` , ""); // is there a second_applicant
if (NdApplicant_is !== "Y") {
retval[`${Nd}_applicant`] = "";
NOAPPLICANT = true;
}
}
// if (retval.second_applicant == "" || retval.second_applicant == "none") {
// retval.is_there_a_third_borrower = "N";
// retval.third_applicant = "";
// }
// if (retval.is_there_a_third_borrower !== "Y") {
// retval.third_applicant = "none"
// }
// if (retval.is_there_a_second_borrower !== "Y") {
// retval.second_applicant = "none"
// }
}
timer("after emaxloop2");
// if (!retval.is_there_a_second_borrower) {
// if (!retval.second_applicant || retval.second_applicant == "" || retval.second_applicant == "none") {
// retval.is_there_a_second_borrower = "N";
// } else {
// retval.is_there_a_second_borrower = "Y";
// }
// }
// if (!retval.is_there_a_third_borrower) retval.is_there_a_third_borrower = "N";
// if (!retval.second_applicant) retval.second_applicant = "";
// if (!retval.third_applicant) retval.third_applicant = "";
// if (!retval.applicant1_name) retval.applicant1_name = "";
// if (!retval.applicant2_name) retval.applicant2_name = "";
// if (!retval.applicant3_name) retval.applicant3_name = "";
// if (!retval.scenario_applicant1_usc) retval.scenario_applicant1_usc = "";
// if (!retval.scenario_applicant2_usc) retval.scenario_applicant2_usc = "";
// if (!retval.scenario_applicant3_usc) retval.scenario_applicant3_usc = "";
// if (!retval.scenario_applicant1_gch) retval.scenario_applicant1_gch = "Y";
// if (!retval.scenario_applicant2_gch) retval.scenario_applicant2_gch = "Y";
// if (!retval.scenario_applicant3_gch) retval.scenario_applicant3_gch = "Y";
// if (!retval.scenario_applicant1_visa_type) retval.scenario_applicant1_visa_type = "";
// if (!retval.scenario_applicant2_visa_type) retval.scenario_applicant2_visa_type = "";
// if (!retval.scenario_applicant3_visa_type) retval.scenario_applicant3_visa_type = "";
// if (retval.second_applicant == "" || retval.second_applicant == "none") {
// retval.is_there_a_third_borrower = "N";
// retval.third_applicant = "";
// }
// if (retval.is_there_a_third_borrower !== "Y") {
// retval.third_applicant = "none"
// }
// if (retval.is_there_a_second_borrower !== "Y") {
// retval.second_applicant = "none"
// }
/**
* set up the applicants
*/
if ("applicants" in mar.answers.v2 === false || mar.answers.v2.applicants.length == 0) {
mar.answers.v2.applicants=[{
fn : retval.applicant1_name
}];
}
/**
* and the declarations
*/
if ("declarations" in mar.answers.v2 === false || mar.answers.v2.declarations.length == 0) {
mar.answers.v2.declarations=[{}];
}
/**
* and the income
*/
if ("income" in mar.answers.v2 === false || mar.answers.v2.income.length == 0) {
mar.answers.v2.income=[{}];
}
retval.cscore = retval.applicant1_cscore;
retval.applicants_cnt = 1;
for (let i=1; i < MAR.MAXBORROWERS; i++) {
let NN = (i+1); // 1
let Nd = MAR.th(NN); // second;
if (retval[`is_there_a_${Nd}_borrower`] == "Y") {
if (mar.answers.v2.applicants.length == i) {
mar.answers.v2.applicants.push({
fn : retval[`applicant${NN}_name`]
});
}
if (mar.answers.v2.declarations.length == i) {
mar.answers.v2.declarations.push({});
}
retval.applicants_cnt = num(NN);
if (retval[`applicant${NN}_cscore`] > 0 && retval[`applicant${NN}_cscore`] < retval.cscore) {
retval.cscore = retval[`applicant${NN}_cscore`];
}
} else {
if (mar.answers.v2.applicants.length > i) {
mar.answers.v2.applicants = mar.answers.v2.applicants.splice(0,i);
}
}
}
// if (retval.is_there_a_second_borrower == "Y") {
// if (mar.answers.v2.applicants.length == 1) {
// mar.answers.v2.applicants.push({
// fn : retval.applicant2_name
// });
// }
// if (mar.answers.v2.declarations.length == 1) {
// mar.answers.v2.declarations.push({});
// }
// retval.applicants_cnt = 2;
// if (retval.applicant2_cscore > 0 && retval.applicant2_cscore < retval.cscore) {
// retval.cscore = retval.applicant2_cscore;
// }
//
// } else {
// if (mar.answers.v2.applicants.length > 1) {
// mar.answers.v2.applicants = [mar.answers.v2.applicants[0]]
// }
// }
//
// if (retval.is_there_a_third_borrower == "Y") {
// if (mar.answers.v2.applicants.length == 2) {
// mar.answers.v2.applicants.push({
// fn : retval.applicant3_name
// });
// }
// if (mar.answers.v2.declarations.length == 2) {
// mar.answers.v2.declarations.push({});
// }
// retval.applicants_cnt = 3;
// if (retval.applicant3_cscore > 0 && retval.applicant3_cscore < retval.cscore) {
// retval.cscore = retval.applicant3_cscore;
// }
// } else {
// if (mar.answers.v2.applicants.length > 2) {
// mar.answers.v2.applicants = [mar.answers.v2.applicants[0],mar.answers.v2.applicants[1]]
// }
// }
/**
* correct if there are too many items in the array
*/
let EMPTY_APPLICANT_FOUND = false;
for (let i=1; i < MAR.MAXBORROWERS; i++) {
let NN = (i+1); // 1
let Nd = MAR.th(NN); // second;
let NthApplicant = retval[`${Nd}_applicant`];
if (EMPTY_APPLICANT_FOUND === true) {
retval[`${Nd}_applicant`] = "none";
}
if (NthApplicant == "none") {
if (mar.answers.v2.applicants.length > i) {
mar.answers.v2.applicants = mar.answers.v2.applicants.splice(0,i);
}
EMPTY_APPLICANT_FOUND = true;
} else if (NthApplicant == "spouse") {
if (mar.answers.v2.applicants.length == i) {
mar.answers.v2.applicants.push({
src : "1"
});
}
mar.answers.v2.applicants[i].type = mar.APPLICANT_TYPE.SPOUSE;
} else if (NthApplicant == "coborrower") {
if (mar.answers.v2.applicants.length == i) {
mar.answers.v2.applicants.push({
src : "2"
});
}
mar.answers.v2.applicants[i].type = mar.APPLICANT_TYPE.COBORROWER;
} else if (NthApplicant == "coborrower_nonresident") {
if (mar.answers.v2.applicants.length == i) {
mar.answers.v2.applicants.push({
src : "2A"
});
}
mar.answers.v2.applicants[i].type = mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT;
}
}
timer("after emaxloop 3");
// if (retval.second_applicant == "none") {
// if (mar.answers.v2.applicants.length > 1) {
// mar.answers.v2.applicants = [mar.answers.v2.applicants[0]];
// }
// } else if (retval.second_applicant == "spouse") {
//
// if (mar.answers.v2.applicants.length == 1) {
// mar.answers.v2.applicants.push({
// src : "1"
// });
// }
//
// mar.answers.v2.applicants[1].type = mar.APPLICANT_TYPE.SPOUSE;
//
// } else if (retval.second_applicant == "coborrower") {
//
// if (mar.answers.v2.applicants.length == 1) {
// mar.answers.v2.applicants.push({
// src : "2"
// });
// }
// mar.answers.v2.applicants[1].type = mar.APPLICANT_TYPE.COBORROWER;
//
// } else if (retval.second_applicant == "coborrower_nonresident") {
// if (mar.answers.v2.applicants.length == 1) {
// mar.answers.v2.applicants.push({
// src : "2A"
// });
// }
// mar.answers.v2.applicants[1].type = mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT;
// }
//
//
// retval.dbg.push(`RV 3RD APP [${retval.third_applicant}]`)
//
// if (retval.third_applicant == "" || retval.third_applicant == "none" ) {
// retval.dbg.push(`RV 3RD APP [cutting applicants down to size]`)
// if (mar.answers.v2.applicants.length > 2) {
// mar.answers.v2.applicants = [mar.answers.v2.applicants[0],mar.answers.v2.applicants[1]];
// }
// if (mar.answers.v2.income.length > 2) {
// mar.answers.v2.income = [mar.answers.v2.income[0],mar.answers.v2.income[1]];
// }
// if (mar.answers.v2.declarations.length > 2) {
// mar.answers.v2.declarations = [mar.answers.v2.declarations[0],mar.answers.v2.declarations[1]];
// }
// retval.dbg.push(`RV 3RD APP [Length = ${mar.answers.v2.applicants.length}]`)
//
// } else if (retval.third_applicant == "spouse") {
//
// if (mar.answers.v2.applicants.length == 2) {
// mar.answers.v2.applicants.push({
// src : "3"
// });
// }
//
// mar.answers.v2.applicants[2].type = mar.APPLICANT_TYPE.SPOUSE;
//
// } else if (retval.third_applicant == "coborrower") {
//
// if (mar.answers.v2.applicants.length == 2) {
// mar.answers.v2.applicants.push({
// src : "4"
// });
// }
// mar.answers.v2.applicants[2].type = mar.APPLICANT_TYPE.COBORROWER;
//
// } else if (retval.third_applicant == "coborrower_nonresident") {
// if (mar.answers.v2.applicants.length == 2) {
// mar.answers.v2.applicants.push({
// src : "5"
// });
// }
// mar.answers.v2.applicants[2].type = mar.APPLICANT_TYPE.COBORROWER_NON_RESIDENT;
// }
// make all the arrays the correct length
while (mar.answers.v2.applicants.length > mar.answers.v2.income.length) {
mar.answers.v2.income.push({});
}
while (mar.answers.v2.applicants.length > mar.answers.v2.declarations.length) {
mar.answers.v2.declarations.push({});
}
retval.final_tax = 0
retval.final_hoi = 0;
retval.final_hoa = 0;
retval.final_fld = 0;
retval.final_ltv = 0;
if ("scenario_i_know_my_tax" in retval && retval.scenario_i_know_my_tax == mar.YES) {
retval.known_tax = Math.floor(num(retval.scenario_tax)/12);
retval.final_tax = retval.known_tax;
} else {
retval.known_tax = 0;
if (retval.hoi_estimate && "prop_tax_percentage_pm" in retval.hoi_estimate && retval.hoi_estimate.prop_tax_percentage_pm && retval.hoi_estimate.prop_tax_percentage_pm != 0) {
var ptp = retval.hoi_estimate.prop_tax_percentage_pm;
if (retval.goals_target_value && retval.goals_target_value > 0) {
retval.final_tax = Math.floor((retval.goals_target_value * mar.answers.v2.scenario.hoi_estimate.prop_tax_percentage_pm)/12)
}
}
}
/**
* retval.known_hoi is the overriden home owners insurance cost
*/
if ("scenario_i_know_my_insurance" in retval && retval.scenario_i_know_my_insurance == mar.YES) {
retval.known_hoi = num(retval.refi_home_insurance_cost)/12;
retval.final_hoi = retval.known_hoi;
} else {
retval.known_hoi = 0;
if (retval.hoi_estimate && "ins_estimate" in retval.hoi_estimate && retval.hoi_estimate.ins_estimate && retval.hoi_estimate.ins_estimate != 0) {
retval.final_hoi = retval.hoi_estimate.ins_estimate
}
}
if ("flood_estimate" in retval && num(retval.flood_estimate) > 0) {
retval.known_flood = num(retval.flood_estimate);
retval.final_fld = retval.known_flood;
} else {
retval.known_flood = 0;
if (retval.hoi_estimate && "flood_estimate" in retval.hoi_estimate && retval.hoi_estimate.flood_estimate && retval.hoi_estimate.flood_estimate != 0) {
retval.final_fld = retval.hoi_estimate.flood_estimate
}
}
/**
* retval known_hoa is for if we knoow the hoa
*/
retval.hoa = 0;
retval.known_hoa = 0;
retval.hoa_option = mar.answers.v2.scenario.property_type_community_options;
if ("scenario_i_know_my_hoa" in retval && retval.scenario_i_know_my_hoa == mar.YES) {
retval.hoa = num(mar.answers.v2.scenario.hoa_estimate);
retval.known_hoa = num(mar.answers.v2.scenario.hoa_estimate);
retval.final_hoa = retval.known_hoa;
}
else if (mar.answers.v2.scenario.property_type_community_options == "cknow") {
retval.hoa = num(mar.answers.v2.scenario.hoa_estimate);
retval.known_hoa = num(mar.answers.v2.scenario.hoa_estimate);
retval.final_hoa = retval.known_hoa;
}
else if (mar.answers.v2.scenario.property_type_community_options == "non") {
retval.hoa = 0;
retval.final_hoa = retval.hoa;
} else {
if ("hoi_estimate" in mar.answers.v2.scenario) {
if ("hoa_estimate" in mar.answers.v2.scenario.hoi_estimate) {
retval.hoa = num(mar.answers.v2.scenario.hoi_estimate.hoa_estimate);
retval.final_hoa = retval.hoa;
}
}
}
/**
* realtor
*/
retval.have_own_realtor = getScenario_data("have_own_realtor","");
retval.realtor_name = getScenario_data("realtor_name","");
retval.realtor_name_fn = MAR.realtor.getName(getScenario_data("realtor_name","")).fn;
retval.realtor_name_ln = MAR.realtor.getName(getScenario_data("realtor_name","")).ln;
retval.realtor_name_str = MAR.realtor.getName(getScenario_data("realtor_name","")).str;
retval.realtor_email = getScenario_data("realtor_email","");
retval.realtor_office = getScenario_data("realtor_office","");
retval.realtor_permission_loan_calcs_and_docs = getScenario_data("realtor_permission_loan_calcs_and_docs","");
retval.realtor_permission_direct_underwriting_report = getScenario_data("realtor_permission_direct_underwriting_report","");
retval.realtor_permission_appraisal_information = getScenario_data("realtor_permission_appraisal_information","");
// if no realtor then send "" values
if (retval.have_own_realtor != mar.YES) {
retval.realtor_name = "";
retval.realtor_name_fn = "";
retval.realtor_name_ln = "";
retval.realtor_name_str = "";
retval.realtor_email = "";
retval.realtor_office = "";
retval.realtor_permission_direct_underwriting_report = "";
retval.realtor_permission_direct_underwriting_report = "";
retval.realtor_permission_appraisal_information = "";
}
retval.calc_additional_lender_credits = getScenario_data("calc_additional_lender_credits","0");
retval.calc_additional_seller_credits = getScenario_data("calc_additional_seller_credits","0");
retval.calc_additional_realtor_credits = getScenario_data("calc_additional_realtor_credits","0");
retval.loan_type_refinance_takehome_value = getScenario_data("loan_type_refinance_takehome_value","");
/**
* new REFI values
*/
retval.loan_type_refinance_takehome_value = getScenario_data("refi_goal","0");
retval.refi_goal = getScenario_data("refi_goal","0");
retval.loan_type_refinance_house_value = getScenario_data("refi_current_value","0");
retval.refi_current_value = getScenario_data("refi_current_value","0");
retval.refi_current_debt = getScenario_data("refi_current_debt","0");
retval.refi_options = getScenario_data("refi_options","0");
/**
* end new REFI values
*/
retval.pdu_selected_programmes = getScenario_data("pdu_selected_programmes","all");
retval.pdu_selected_rates = getScenario_data("pdu_selected_rates","all");
retval.pdu_selected_rates_fha = getScenario_data("pdu_selected_rates_fha","all");
retval.pdu_selected_rates_conv = getScenario_data("pdu_selected_rates_conv","all");
retval.pdu_selected_rates_va = getScenario_data("pdu_selected_rates_va","all");
retval.pdu_selected_rates_hr = getScenario_data("pdu_selected_rates_hr","all");
retval.pdu_selected_rates_jumbo = getScenario_data("pdu_selected_rates_jumbo","all");
retval.calc_additional_lender_credits_fha = getScenario_data("calc_additional_lender_credits_fha","0");
retval.calc_additional_lender_credits_conv = getScenario_data("calc_additional_lender_credits_conv","0");
retval.calc_additional_lender_credits_va = getScenario_data("calc_additional_lender_credits_va","0");
retval.calc_additional_lender_credits_hr = getScenario_data("calc_additional_lender_credits_hr","0");
retval.calc_additional_lender_credits_jumbo = getScenario_data("calc_additional_lender_credits_jumbo","0");
retval.calc_additional_lender_credits_jumbo = getScenario_data("calc_additional_lender_credits_jumbo","0");
retval.calc_additional_lender_credits_jumbo = getScenario_data("calc_additional_lender_credits_jumbo","0");
retval.calc_additional_lender_credits_jumbo = getScenario_data("calc_additional_lender_credits_jumbo","0");
retval.calc_additional_lender_credits_jumbo = getScenario_data("calc_additional_lender_credits_jumbo","0");
/**
* co-ordinate REO and calculations
*/
/* these finals will have come from the input of the mortgage application */
// retval.final_tax = 0
// retval.final_hoi = 0;
// retval.final_hoa = 0;
// retval.final_fld = 0;
// retval.final_ltv = 0;
if ("reo" in mar.answers.v2 === false) mar.answers.v2.reo = []; // empty REO
let reolist = mar.answers.v2.reo;
// let reo_primary_index = false;
// for (let i=0; i < reolist.length; i++) {
// if (MAR.getOpt(reolist[i],"reo_use","") == "primary") {
// if (MAR.getOpt(reolist[i],"whosname","").indexOf("0") > -1) {
// reo_primary_index = i;
// }
// }
// }
//
// console.warn(`reo_primary_index ${reo_primary_index}`);
// console.warn(`MAR.ownsProperty(0) ${MAR.ownsProperty(0)}`);
//
//
// if (reo_primary_index === false) { // we did not find a primary REO property
// if (MAR.ownsProperty(0) == true) { // if we current own realestate , create a new REO block
// let newproperty = MAR.reo.create({
// type : "primary",
// owner : "0",
// address : {
// address : `tbd - current primary ${______inc}`
// },
// verified : "N"
// });
// MAR.reo.set(false, newproperty);
// }
// } else {
// if (MAR.ownsProperty(0) == false) { // if we current own realestate
// setScenario_data("does_applicant1_own_property","Y");
// }
// }
//
// for (let i=0; i < reolist.length; i++) {
// let reoitem = reolist[i];
//
// if ("address" in reoitem) {
// console.log("reoitem", i, reoitem.address, reoitem)
// let adr = reoitem.address;
// console.log("reoitem", i, reoitem.address, adr.startsWith("tbd"), reoitem)
//
// if (adr.startsWith("tbd")) {
// if ("verified" in reoitem && reoitem.verified === "N") {
// let a_current = MAR.getApplicantAddressCurrent(0);
// if (a_current && a_current.length > 0) {
// console.log("reoitem", "a_current", a_current[0].address, "", a_current)
// reolist[i].address = a_current[0].address;
// }
// }
// }
// }
//
//// if (MAR.getOpt(reolist[i],"address","").startsWith("tbd") && MAR.getOpt(reolist[i],"verified","") === "N") {
//// let a_current = MAR.getApplicantAddressCurrent(0);
//// if (a_current) {
//// reolist[i].address = a_current.address;
//// }
//// }
//
//
// }
retval.currentHousingExpenses = {
}
retval.downpayment_type = getScenario_data("downpayment_type","CheckingSavings");
if (MAR.assets.isThereAGift() == true) {
retval.downpayment_type = "GiftFunds"; // global override!
}
/*
* encompass Synch fields
*/
retval.est_closing_date_src = getScenario_data("est_closing_date_src","");
retval.est_closing_date_set = getScenario_data("est_closing_date_set","");
retval.est_closing_date = getScenario_data("est_closing_date","");
retval.property_details = getScenario_data("property_details","");
addScenario_data(retval,"__application_imported_from_encompass_A2B_mortgage","");
addScenario_data(retval,"__application_imported_from_encompass_B2A_mortgage","");
addScenario_data(retval,"__application_imported_from_encompass","");
addScenario_data(retval,"__application_imported_from_encompass_purpose","");
addScenario_data(retval,"__application_imported_from_encompass_needs_verification","");
addScenario_data(retval,"__application_imported_from_encompass_needs_verification_incomechange","");
retval.appdata = [];
retval.encompass_warnings = {};
try {
if (typeof rules !== 'undefined') {
rules.clearwarnings("scenario");
rules.clearwarnings("scenario_all");
rules.clearwarnings("scenario_applicant");
/* rules */
rules.get("scenario_all").forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,0);
_fn = null;
});
(function(){
for (let x in mar.answers.v2.scenario) {
if (x.startsWith("__enc_app_ssn_error")) {
if (mar.answers.v2.scenario[x] === "Y") {
let itm = {
type : "app",
data : mar.answers.v2.scenario[x]
};
_addneed(`/misc/encompass/0/sup-doc/encompass-change/ssn`,"",0,"", itm);
retval[x] = itm.data;
retval.encompass_warnings[x] = itm;
}
}
if (x.startsWith("__enc_income_missmatch")) {
if (mar.answers.v2.scenario[x] !== false) {
let uuid = x.substring("__enc_income_missmatch_".length);
let itm = {
uuid : uuid,
type : "income",
data : JSON.parse(mar.answers.v2.scenario[x])
};
_addneed(`/income/encompass/0/sup-doc/encompass-income-missmatch/${uuid}`,"",0,itm.uuid, itm);
retval[x] = itm.data;
retval.encompass_warnings[x] = itm;
}
}
// {"000-00-0019":{"base":[7361,5231.07],"overtime":[6000,191],"bonus":[0,911],"commission":[0,111],"other":[null,211]},"121-22-1112":{"base":[0,0],"overtime":[0,0],"bonus":[0,0],"commission":[0,0],"other":[null,null]}}
if (x.startsWith("__enc_incomediff")) {
if (mar.answers.v2.scenario[x] !== false) {
let data = JSON.parse(mar.answers.v2.scenario[x]);
for (let d in data) {
let ssn = d;
let is_a_diff = false;
for (let d1 in data[d]) {
let _el_val = num(data[d][d1][0]);
let _en_val = num(data[d][d1][1]);
if (`__enc_over_${MAR.digits(d)}_${d1}` in mar.answers.v2.scenario) {
_el_val = num(mar.answers.v2.scenario[`__enc_over_${MAR.digits(d)}_${d1}`]);
}
if (Math.floor(_el_val*100) !== Math.floor(_en_val*100)) {
is_a_diff = true;
}
}
if (is_a_diff) {
let itm = {
ssn : d,
type : "income",
data : data[d]
};
_addneed(`/income/encompass/0/sup-doc/encompass-income-diff/${d}`,"",0,itm.ssn, itm);
retval[`${x}_${ssn}`] = itm.data;
retval.encompass_warnings[`${x}_${ssn}`] = itm;
}
}
}
}
if (x.startsWith("__enc_incomechange")) {
if (mar.answers.v2.scenario[x] !== false) {
let uuid = x.substring("__enc_incomechange_".length);
let itm = {
uuid : uuid,
type : "income",
data :JSON.parse(mar.answers.v2.scenario[x])
};
_addneed(`/income/encompass/0/sup-doc/encompass-income-change`,"",0,itm.uuid, itm);
retval[x] = itm.data;
retval.encompass_warnings[x] = itm;
}
}
if (x.startsWith("__enc_over")) {
retval[x] = mar.answers.v2.scenario[x];
}
}
})();
// let apvars = [
// "applicant(9)_name",
// "applicant(9)_cscore:#0",
// "#",
// "# citizenship",
// "#",
// "scenario_applicant(9)_usc",
// "scenario_applicant(9)_gch",
// "scenario_applicant(9)_visa_type",
// "#",
// "# property",
// "#",
// "has_applicant(9)_owned_property_in_last_3_years",
// "has_applicant(9)_owned_property_in_last_3_years_type",
// "has_applicant(9)_owned_property_in_last_3_years_how",
// "does_applicant(9)_own_property",
// "#",
// "# VA",
// "#",
// "has_applicant(9)_served_in_us_forces",
// "scenario_applicant(9)_served",
// "va_coe(9)",
// "va_employment(9)",
// "va_disabled(9)",
// "vafirst_time_use(9)",
// "#",
// "# non applicant 1 variables",
// "",
// "is_there_a_(9th)_borrower",
// "(9th)_applicant"
// ]
for (let i=0; i < mar.answers.v2.applicants.length; i++) {
let NN = (i+1);
let Nd = MAR.th(NN);
let Nitem = {};
let applicantData = {};
for (let j=0; j < apvars.length; j++) {
let apvar = apvars[j].split(":");
let apvar0 = apvar[0];
if (apvar0.startsWith("#")) continue;
if (apvar0 == "") break;
apvar_normalized = apvar0.replace("(9)", "N"); // applicantN_name
apvar0 = apvar0.replace("(9)",`${NN}`) // applicant1_name
Nitem[apvar_normalized] = retval[apvar0]
}
retval.appdata.push(Nitem);
Nitem.warnings=[];
let warning_type = "scenario_applicant";
/* rules */
// let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,i,{
});
_fn = null;
});
// if (warning_type in mar.warnings) {
// for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
// inc.warnings.push(mar.warnings[warning_type][_wc])
// }
// }
}
}
} catch (E) {
console.warn(E);
}
timer("after rules");
retval.dbg.push(`RV END [Length = ${mar.answers.v2.applicants.length}]`)
timer("end");
//console.log("scenario tims",tims);
return retval;
}
function capitalizeFirstLetter(string) {
return MAR.capitalizeFirstLetter(string);
}
function county_display(T) {
return MAR.county_display(T);
}
function county_number(T) {
return MAR.county_number(T);
}
function getScenarioSummary(rv) {
if (!rv) return {};
var retval = {};
retval.loantype = [1,"Loan type" ,
rv.loan_type,
rv.loan_type
];
/* timeframe */
retval.timeframe =[1,"Time Frame" ,
mar._txt(rv.loan_type_purchase_options),
rv.loan_type_purchase_options
];
/* location */
retval.location = [1,"Location" ,
county_display(rv.property_county),
rv.property_county
];
/* occupancy */
retval.occupancy = [1,"Occupancy" ,
mar._txt(rv.occupancy_type),
rv.occupancy_type
];
/* property type and potential rental */
retval.propertytype = [1,"Property type" ,
mar._txt(rv.property_type),
rv.property_type
];
//_monthly_rent_display
var _monthly_rent_display = "";
if ((rv.property_type != "" && rv.property_type != "sfr" && rv.property_type != "condo") || rv.occupancy_type == "investment") {
var _monthly_rent = num($("#monthly_rent").val());
if (rv.monthly_rent != 0) {
_monthly_rent_display = "Est rent : $"+rv.monthly_rent+"";
}
}
if (_monthly_rent_display != "") {
retval.property_type_monthlyrent = [2," - monthly rent Est." ,
_monthly_rent_display,
rv.monthly_rent
];
}
/* insurances */
/**
* insurance
*/
var insurance_disp = "";
var scenario_i_know_my_insurance = rv.scenario_i_know_my_insurance;
if (scenario_i_know_my_insurance == "Y") {
retval.hoi_line = [0,"HOI" ,"",""];
retval.hoi_line0 = [1,"I know my insurance" ,
"Yes , I do ",
"Y"
];
retval.hoi_line1 = [2,"- I estimate it at" ,
"$"+rv.refi_home_insurance_cost,
rv.refi_home_insurance_cost
];
retval.hoi_line2 = [2,"- The property is near to water?" ,
(rv.property_near_to_water == "Y") ? "Yes it is" : "No it is not",
rv.property_near_to_water
];
} else {
retval.hoi_line = [0,"HOI" ,"",""];
retval.hoi_line0 = [1,"I know my insurance" ,
"NO - please Estimate for me",
"N"
];
retval.hoi_line1 = [2,"- Square footage" ,
rv.square_foot+" sq. ft",
rv.square_foot
];
retval.hoi_line2 = [2,"- Build Period" ,
"c. "+rv.build_period+"",
rv.build_period
];
retval.hoi_line3 = [2,"- The property is near to water?" ,
(rv.property_near_to_water == "Y") ? "Yes it is" : "No it is not",
rv.property_near_to_water
];
if (rv.hoi_estimate) {
retval.hoi_line4 = [2,"- Ins Est" ,
"$ "+rv.hoi_estimate.ins_estimate+"",
rv.hoi_estimate.ins_estimate
];
retval.hoi_line5 = [2,"- Flood Est" ,
"$ "+rv.hoi_estimate.flood_estimate+"",
rv.hoi_estimate.flood_estimate
];
} else {
retval.hoi_line4 = [2,"- Ins Est" ,
"$ -",
0
];
retval.hoi_line5 = [2,"- Flood Est" ,
"$ -",
0
];
}
}
/**
* HOA
*/
var hoa_disp = "";
if (rv.property_type_community_options == "cknow") {
retval.hoa_line = [0,"HOA" ,"",""];
retval.hoa_line0 = [1,"I know my HOA fees" ,
"Yes , I do ",
"Y"
];
retval.hoa_line1 = [1,"- I estimate it at" ,
"$"+num(rv.hoa_estimate),
num(rv.hoa_estimate)
];
} else {
retval.hoa_line = [0,"HOA" ,"",""];
retval.hoa_line0 = [1,"I know my HOA fees" ,
"No , Estimate them for me ",
"N"
];
retval.hoa_line1 = [2,"- Square footage" ,
rv.square_foot+" sq. ft",
rv.square_foot
];
if (rv.hoi_estimate && rv.hoi_estimate.hoa_estimate) {
retval.hoa_line2 = [2,"- HOA Est" ,
"$ "+rv.hoi_estimate.hoa_estimate+"",
rv.hoi_estimate.hoa_estimate
];
} else {
retval.hoa_line2 = [2,"- HOA Est" ,
"$ -",
0
];
}
}
return retval;
}
function getPersonalData(PROG) {
if (!mar.STATIC) setStaticVars();
if (!PROG) PROG = "web";
let applicantLength = getApplicants_v2().length;
for (var n=0; n < applicantLength; n++) {
let ads = getApplicantAddresses(n);
for (var a=0; a < ads.length; a++) {
let itm = ads[a];
itm.warnings=[];
// address: "2493 Leisure Lane|San Matias|CA|93405-2255|"
// appears_on_drivers_license: "Y"
// appears_on_tax_returns: "Y"
// bucketid: "/applicants/address/0/161de3c3-b35c-4004-8e6b-98213b5811ec"
// months: "0"
// reason_dl_different: ""
// type: "current"
// use: "rent"
// uuid: "161de3c3-b35c-4004-8e6b-98213b5811ec"
// years: "8"
let warning_type = "personaldata_addressitem";
/* rules */
let _warningcount = (warning_type in mar.warnings) ? mar.warnings[warning_type].length : 0;
rules.get(warning_type).forEach(function(item){
eval("var _fn = "+item+";");
_fn(PROG,n,{
a : getApplicantsNames_v2(n),
item : itm
});
_fn = null;
});
if (warning_type in mar.warnings) {
for (let _wc = _warningcount; _wc < mar.warnings[warning_type].length; _wc++) {
itm.warnings.push(mar.warnings[warning_type][_wc])
}
}
}
}
}
function make_needs_list_v2(){
var _needs = [];
try {
rules.clearwarnings("");
getScenario_v2();
getIncome_v2();
getDeclarations_with_rules_v2();
getAssets_v2();
getPersonalData();
getReo_v2();
getBackEndLiabilities_v2();
var applicants = getApplicants_v2();
_needs = rules.getAllNeeds("");
//console.log("_needs",_needs);
// var __needs = [];
// _needs.forEach(function(n){
// __needs.push(n.split(" ")[0]);
// });
} catch (E) {
console.warn(E)
}
return _needs;
}
function get_answers_with_additional_needs_v2(r) {
if ("answers" in r == false) return false;
try {
var answers = JSON.parse(r.answers);
} catch (E) {
console.warn(E);
return false;
}
answers.v2.additional_needs = [];
if (r.additional_needs_obj) {
answers.v2.additional_needs = r.additional_needs_obj;
} else {
if ("additional_needs" in r && r.additional_needs != null && r.additional_needs != "") {
try {
answers.v2.additional_needs = JSON.parse(r.additional_needs);
} catch (E) {
answers.v2.additional_needs = [];
console.warn(E);
}
}
}
return answers;
}
var elainesdk = (function(){
function uuidv4() {
if (typeof el_uuid === "undefined") {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
} else {
return el_uuid.gen();
}
}
var customCostBuilder = (function(){
/*
mar.customcalcs = {
remove : {
"re_inspection_fee" : 0
},
adjust : {
"endorsements" : 1201
},
rename : {
"re_inspection_fee" : "after inspection fee"
},
add : {
"_aiusdfhsaisfuhd" : {
title : "a i u d s",
value : 802,
section : 800,
qmapr : true,
csection : sections[800].cat
},
"_aiusdffhsaisfuhd" : {
title : "aff i u d s",
value : 1211,
section : 1200,
qmapr : false,
csection : sections[1200].cat
}
}
}
*
*/
var localvar = {};
var sections = {
"800" : { title : "Items Payable in Connection with Loa" , cat : 0 },
"900" : { title : "Items required by Lender to be Paid in Advance" , cat : 3 },
"1000" : { title : "Reserves Deposited with Lender" , cat : 3 },
"1100" : { title : "Title Charges" , cat : 1 },
"1200" : { title : "Government recording and Transfer Charges" , cat : 2 },
"1300" : { title : "Additional Settlement Charges" , cat : 2 }
};
function set(LV) {
localvar = LV
}
function get() {
return localvar;
}
function init() {
if ("remove" in localvar == false) localvar.remove = {};
if ("adjust" in localvar == false) localvar.adjust = {};
if ("add" in localvar == false) localvar.add = {};
if ("rename" in localvar == false) localvar.rename = {};
}
function build() {
}
function newline(section,name,qmapr) {
init();
let newlineid = "_"+uuidv4(); // has to be an underscore
let newlinecode = (Math.floor(section/100) * 100) + 90;
localvar.add[newlineid] = {
title : name,
value : 0,
code : newlinecode,
section : section,
qmapr : 1,
csection : sections[section].cat
}
log();
return [newlineid,newlinecode];
}
function adjustValue(code,val) {
init();
if (code.indexOf("_") === 0) {
if (val == false) {
if (code in localvar.add) delete localvar.add[code]
}
localvar.add[code].value = val;
} else {
if (val == false) {
if (code in localvar.adjust) delete localvar.adjust[code]
}
localvar.adjust[code] = val;
}
log();
}
function adjustApr(code,val) {
init();
if (code.indexOf("_") === 0) {
localvar.add[code].qmapr = val;
}
log();
}
function adjustName(code,val) {
init();
if (code.indexOf("_") === 0) {
if (val == false) {
if (code in localvar.add) delete localvar.add[code]
}
localvar.add[code].name = val;
} else {
if (val == false) {
if (code in localvar.rename) delete localvar.rename[code]
}
localvar.rename[code] = val;
}
log();
}
function log(){
console.warn(localvar);
}
return {
adjustValue : adjustValue, // adjust a line item number
adjustName : adjustName, // adjust a line item name
adjustApr : adjustApr, // adjust the QM APR
newline : newline, // add new line
sections : sections, // list of sections
/**
* general functions
*/
log : log, // log to console
build : build, // build the scenario
set : set, // set the scenario object
get : get // get the scenario object
}
})();
return {
// custom cost builder
customCostBuilder : customCostBuilder,
// uuid functions
uuid : uuidv4,
uuidv4 : uuidv4
}
})();
function mar_tmp_docn(completionarray=[]) {
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function formalParameterList(fn) {
var fnText,argDecl;
var args=[];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
if (argDecl === null) return [];
if ("1" in argDecl === false) return [];
var r = argDecl[1].split(FN_ARG_SPLIT);
for(var a in r){
var arg = r[a];
arg.replace(FN_ARG, function(all, underscore, name){
args.push(name);
});
}
return args;
}
let docu = function(obj, path){
for (let x in obj) {
let elm = obj[x];
if (typeof elm === "function") {
//console.error(`${path}.${x}()`);
let args = formalParameterList(elm);
completionarray.push([`${path}.${x}()`,`${path}.${x}(${args.join(",")})`])
}
if (typeof elm === "string") {
completionarray.push([`${path}.${x}="${elm}"`,`${x}`])
}
if (typeof elm === "object") {
// console.error(`${path}.${x}()`);
docu(elm, `${path}.${x}`);
}
}
}
docu(MAR, "MAR")
}
//console.log("endfn");
/*
missing
cs_payment
al_payment
*/
var marclient = {};
marclient.ip = '3.22.181.81';
marclient.ts = '1715322491763';