Dashboard

`; openModal(mh(`Check #${esc(ck.no)}`)+`
${checkHTML(ck)}
${ck.status==='Issued'?``:''}${DL?'':''}
`,true); $('#ckc').onclick=()=>copyText(doc);if($('#ckd'))$('#ckd').onclick=async()=>{try{await DL.save({filename:`check-${ck.no}.html`,data:doc});toast('Saved – open it and click Print')}catch(e){}}; if($('#ckv'))$('#ckv').onclick=()=>confirmBox(`Void check #${esc(ck.no)}? A reversing entry is posted.`,()=>{ck.status='Void';txn(TODAY,ck.cat,-ck.amount,'CK'+ck.no,'VOID check #'+ck.no);const v=ck.vid&&veh(ck.vid);if(v&&ck.cat==='Reconditioning')v.recon.push({id:uid(),date:TODAY,desc:'Void check #'+ck.no,amount:-ck.amount});save();render();toast('Check voided')})} const CKCSS=`.ckpage{padding:.35in .5in}.ck{border:1.5px solid #94a3b8;border-radius:6px;padding:18px 22px;height:3.3in;background:repeating-linear-gradient(135deg,#f8fafc 0 6px,#f1f5f9 6px 12px)}.ckh{display:flex;justify-content:space-between}.ckno{font-size:16px;font-weight:800} .ckrow{display:flex;align-items:flex-end;gap:12px;margin-top:16px}.ckline{border-bottom:1px solid #111;padding:2px 6px;font-size:14px;font-weight:600;min-height:22px}.ckamt{border:1.5px solid #111;padding:4px 12px;font-weight:800;font-size:15px;background:#fff;min-width:130px;text-align:right} .ckstub{border-top:1.5px dashed #94a3b8;margin-top:.35in;padding-top:.25in;height:3.1in}`; function checkRegister(){const cs=(S.checks||[]).slice().sort((a,b)=>b.date.localeCompare(a.date)||String(b.no).localeCompare(String(a.no)));if(!cs.length)return''; return `
Check register${cs.filter(c=>c.status==='Issued').length} issued · ${$$(cs.filter(c=>c.status==='Issued').reduce((a,c)=>a+c.amount,0))}
${cs.map(c=>``).join('')}
Check #DatePayeeAccountMemoAmountStatus
${esc(c.no)}${fdate(c.date)}${esc(c.payee)}${esc(c.cat)}${esc(c.memo||'')}${$$(c.amount)}${c.status==='Void'?'Void':'Issued'}
`} /* ================= Next-action prompt ================= */ const NEXT_TYPES=[['Call','✆'],['Text','✉'],['Email','@'],['Appointment','📅'],['Test drive','🚗'],['Send info / pictures','📷'],['Credit app follow-up','🏦'],['Visit / walk-in','🤝']]; const LOST_REASONS=['Bought elsewhere','Credit / financing','Price','Not ready / just looking','No response','Wrong number / bad info','Other']; const isLead=c=>c&&['New','Contacted','Appointment'].includes(c.stage); const nxIcon=t=>(NEXT_TYPES.find(x=>x[0]===t)||[,'•'])[1]; const nxTime=t=>{if(!t)return'';const [h,m]=t.split(':').map(Number);return (h%12||12)+(m?':'+pad(m):'')+(h<12?'am':'pm')}; const nxLabel=n=>n?`${nxIcon(n.type)} ${n.type} · ${fdate(n.date)}${n.time?' '+nxTime(n.time):''}`:''; function promptNext(cid){const c=cust(cid);if(S.settings.nextActionPrompt===false||!isLead(c))return;setTimeout(()=>nextActionModal(cid),80)} function nextActionModal(cid){setTimeout(()=>{ui.nxType=''},0);const c=cust(cid);const cur=c.next||{};const lm=lastMsg(cid);const owner=c.ownerId||me()?.id; const quick=[['In 2 hours',0,2],['Tomorrow 10am',1,'10:00'],['In 2 days',2,'10:00'],['Next week',7,'10:00']]; openModal(mh(`What's next for ${esc(c.name)}?`)+`
${lm?`
Just logged: ${lm.channel==='call'?'✆ call – '+esc(lm.outcome):lm.dir==='in'?'✉ their reply':'✉ text sent'}${lm.body?' · “'+esc(lm.body.slice(0,90))+'”':''}
`:''}
${NEXT_TYPES.map((t,i)=>``).join('')}
${quick.map(q=>``).join('')}
Close this lead instead
${LOST_REASONS.map(r=>``).join('')}
`); const f=$('#nxf'); f.querySelectorAll('[data-q]').forEach(b=>b.onclick=()=>{const [d,t]=b.dataset.q.split('|');if(d==='0'){const n=new Date(Date.now()+(+t)*36e5);f.date.value=iso(n);f.time.value=pad(n.getHours())+':'+pad(n.getMinutes())}else{f.date.value=addDays(TODAY,+d);f.time.value=t}f.querySelectorAll('[data-q]').forEach(x=>x.classList.toggle('pri',x===b))}); f.querySelectorAll('[data-lost]').forEach(b=>b.onclick=()=>{c.stage='Lost';c.followUp='';c.next=null;c.notes.push({date:TODAY,by:S.settings.user,text:'Lead closed – '+b.dataset.lost});save();closeModal();render();toast('Lead closed')}); $('#nxskip').onclick=()=>{if(!c.next){c.notes.push({date:TODAY,by:S.settings.user,text:'No next step scheduled'})}save();closeModal();render()}; f.onsubmit=e=>{e.preventDefault();const x=fd(f);c.next={type:x.type,date:x.date,time:x.time,note:x.note,by:S.settings.user,at:nowAt()};c.followUp=x.date;if(x.ownerId)c.ownerId=x.ownerId; if(x.type==='Appointment'||x.type==='Test drive')c.stage='Appointment';else if(c.stage==='New')c.stage='Contacted'; c.notes.push({date:TODAY,by:S.settings.user,text:`Next step: ${x.type} on ${fdate(x.date)}${x.time?' at '+nxTime(x.time):''}${x.note?' – '+x.note:''}${x.ownerId&&x.ownerId!==me()?.id?' (assigned to '+(S.users.find(u=>u.id===x.ownerId)?.name||'')+')':''}`}); save();closeModal();render();toast('Next step scheduled: '+x.type+' '+fdate(x.date))}} function doneNext(cid){const c=cust(cid);if(!c.next)return;planStepDone(cid);const t=c.next.type;c.notes.push({date:TODAY,by:S.settings.user,text:`Completed: ${t}`});c.next=null;save();if(t==='Call')callModal(cid);else if(t==='Text')textModal(cid);else{render();promptNext(cid)}} /* ================= AI customer suggestion ================= */ async function aiCustomer(cid){const c=cust(cid);const o=$('#aicust');if(!o)return;o.innerHTML='
✦ Reviewing this customer…
'; const loans=S.loans.filter(l=>l.customerId===cid),deals=S.deals.filter(d=>d.customerId===cid); try{const r=await ai(`${dealerCtx()} You are a sales coach inside the dealer's CRM. Using ONLY the information below (what the customer has told the dealership and their history here), suggest how the salesperson should move this customer forward. Do not guess personal details that aren't given, and don't make assumptions based on name, age or background. Customer: ${JSON.stringify({first_name:c.name.split(' ')[0],stage:c.stage,source:c.source,created:c.created,interest:c.interest,monthly_income:c.income||null,employer:c.employer||null,preferred_contact:c.prefContact||null,can_text:!canText(c),current_next_step:c.next||null,notes:c.notes.slice(-8).map(n=>n.date+': '+n.text)})} Conversation (latest last): ${JSON.stringify(S.comms.filter(x=>x.customerId===cid).sort((a,b)=>a.at.localeCompare(b.at)).slice(-10).map(x=>(x.channel==='call'?'[call '+x.outcome+'] ':x.dir==='in'?'Customer: ':'Dealer: ')+x.body))} Past deals: ${JSON.stringify(deals.map(d=>({date:d.date,vehicle:vname(veh(d.vehicleId)),type:d.type})))} Loans: ${JSON.stringify(loans.map(l=>({status:l.status,days_late:daysLate(l),paid:paidCount(l)+'/'+l.term})))} Available inventory: ${JSON.stringify(invList().slice(0,40))} Reply with only JSON: {"summary":"2 sentences on where this customer stands","intent":"what they seem to want","temperature":"hot|warm|cold","talking_points":["3 short points"],"vehicles":[{"stock":"S1101","why":"short"}],"next_step":{"type":"Call|Text|Email|Appointment|Test drive|Send info / pictures|Credit app follow-up|Visit / walk-in","in_days":1,"time":"10:00","why":"short"},"message":"a ready-to-send text under 300 characters, or empty if texting isn't allowed"}`,{nocache:true}); ui.custAI={cid,r};const vs=(r.vehicles||[]).map(x=>({...x,v:S.vehicles.find(z=>z.stock===x.stock)})).filter(x=>x.v); o.innerHTML=`
✦ AI suggestion${esc(r.temperature||'')}${esc(r.intent||'')}

${esc(r.summary||'')}

${(r.talking_points||[]).length?`
Talking points
`:''} ${vs.length?`
Cars to show
${vs.map(x=>`
🚗 ${esc(x.v.stock)} ${esc(vname(x.v))} · ${$0(x.v.price)}: ${esc(x.why)}
`).join('')}`:''} ${r.next_step?`
Suggested next step${esc(nxIcon(r.next_step.type))} ${esc(r.next_step.type)} on ${fdate(addDays(TODAY,+r.next_step.in_days||1))}${r.next_step.time?' '+nxTime(r.next_step.time):''}: ${esc(r.next_step.why||'')}
`:''} ${r.message&&!canText(c)?`
Suggested text${esc(r.message)}
`:''}
${r.next_step?``:''}${r.message&&!canText(c)?``:''}
`}catch(e){o.innerHTML=`
${aiErrMsg(e)}
`}} function applyCustAI(){const {cid,r}=ui.custAI;const c=cust(cid),n=r.next_step;const type=NEXT_TYPES.some(t=>t[0]===n.type)?n.type:'Call';const date=addDays(TODAY,Math.max(0,+n.in_days||1)); c.next={type,date,time:/^\d\d:\d\d$/.test(n.time||'')?n.time:'10:00',note:n.why||'',by:'AI suggestion',at:nowAt()};c.followUp=date;if(type==='Appointment'||type==='Test drive')c.stage='Appointment'; c.notes.push({date:TODAY,by:S.settings.user,text:`Next step (AI suggested): ${type} on ${fdate(date)} – ${n.why||''}`});save();render();custModal(cid);toast('Next step scheduled')} /* ================= Vehicle photos ================= */ let ASSETS=null;const IDBURL={}; try{if(window.claude&&window.claude.use)window.claude.use('assets').then(x=>{ASSETS=x}).catch(()=>{})}catch(e){} function idb(){return new Promise((res,rej)=>{try{const r=indexedDB.open(workspaceStorage('lotledger_photos'),1);r.onupgradeneeded=()=>r.result.createObjectStore('p');r.onsuccess=()=>res(r.result);r.onerror=()=>rej(r.error)}catch(e){rej(e)}})} async function idbOp(mode,fn){const db=await idb();return new Promise((res,rej)=>{const tx=db.transaction('p',mode);const st=tx.objectStore('p');const r=fn(st);tx.oncomplete=()=>res(r&&r.result);tx.onerror=()=>rej(tx.error)})} async function loadLocalPhotos(){const ids=[];S.vehicles.forEach(v=>(v.photos||[]).forEach(p=>{if(p.src==='i'&&!IDBURL[p.id])ids.push(p.id)}));if(!ids.length)return; for(const id of ids){try{const b=await idbOp('readonly',st=>st.get(id));if(b)IDBURL[id]=URL.createObjectURL(b)}catch(e){}}render()} let photoURL=p=>p.src==='a'?workspaceMount+'/_blob/'+p.id:(IDBURL[p.id]||''); const mainPhoto=v=>(v.photos||[]).map(photoURL).find(Boolean)||''; function shrink(file,max=1600,q=0.85){return new Promise((res,rej)=>{const img=new Image();const u=URL.createObjectURL(file);img.onload=()=>{const k=Math.min(1,max/Math.max(img.width,img.height));const c=document.createElement('canvas');c.width=Math.round(img.width*k);c.height=Math.round(img.height*k);c.getContext('2d').drawImage(img,0,0,c.width,c.height);URL.revokeObjectURL(u);c.toBlob(b=>b?res(b):rej(new Error('encode')),'image/jpeg',q)};img.onerror=()=>{URL.revokeObjectURL(u);rej(new Error('Not an image'))};img.src=u})} async function addPhotos(vid,files){const v=veh(vid);v.photos=v.photos||[];const list=[...files].filter(f=>/^image\//.test(f.type)).slice(0,40-v.photos.length);if(!list.length)return toast('Choose image files (JPG, PNG, WebP)'); const st=$('#phstat');let n=0;for(const f of list){if(st)st.textContent=`Uploading ${n+1} of ${list.length}…`;try{const b=await shrink(f); if(ASSETS){const r=await ASSETS.upload(b,{type:'image/jpeg'});v.photos.push({id:r.id,src:'a'})}else{const id=uid();await idbOp('readwrite',s=>s.put(b,id));IDBURL[id]=URL.createObjectURL(b);v.photos.push({id,src:'i'})}n++} catch(e){toast(e&&e.code==='quota_or_state'?'Photo storage is full':e&&e.code==='too_large'?'A photo was too large':'A photo failed to upload')}} save();if(st)st.textContent='';drawPhotos(vid);toast(n+' photo(s) added');if(route!=='inventory')render()} async function delPhoto(vid,i){const v=veh(vid),p=v.photos[i];confirmBox('Delete this photo? It will disappear from the website and listings.',async()=>{try{if(p.src==='a'&&ASSETS)await ASSETS.delete(p.id);else if(p.src==='i')await idbOp('readwrite',s=>s.delete(p.id))}catch(e){}v.photos.splice(i,1);save();render();vehModal(vid)})} function movePhoto(vid,i,to){const v=veh(vid);const [p]=v.photos.splice(i,1);v.photos.splice(to,0,p);save();drawPhotos(vid)} function drawPhotos(vid){const box=$('#phgrid');if(!box)return;const v=veh(vid);const ps=v.photos||[]; box.innerHTML=ps.map((p,i)=>`
${i===0?'Main photo':''}
${i?``:''}${i▶`:''}
`).join('')+ ``; let from=null;box.querySelectorAll('.phx').forEach(el=>{el.ondragstart=()=>from=+el.dataset.i;el.ondragover=e=>e.preventDefault();el.ondrop=e=>{e.preventDefault();e.stopPropagation();if(e.dataTransfer.files.length)return addPhotos(vid,e.dataTransfer.files);if(from!=null&&from!==+el.dataset.i)movePhoto(vid,from,+el.dataset.i)}}); const d=$('#phdrop');d.ondragover=e=>{e.preventDefault();d.classList.add('over')};d.ondragleave=()=>d.classList.remove('over');d.ondrop=e=>{e.preventDefault();d.classList.remove('over');addPhotos(vid,e.dataTransfer.files)}} async function photoDataURL(p,max=1000){try{let b;if(p.src==='i')b=await idbOp('readonly',s=>s.get(p.id));else b=await (await fetch(workspaceMount+'/_blob/'+p.id)).blob();if(!b)return'';const sb=await shrink(b,max,0.72);return await new Promise(r=>{const fr=new FileReader();fr.onload=()=>r(fr.result);fr.readAsDataURL(sb)})}catch(e){return''}} /* ================= Dealer websites ================= */ const WTPL={ modern:{n:'Modern Showroom',d:'Dark hero, clean cards, tech-forward',primary:'#2f54eb',accent:'#00c2a8',bg:'#ffffff',ink:'#0b1220',font:"'Inter',sans-serif",head:"'Inter',sans-serif",hero:'dark',radius:16,upper:false}, classic:{n:'Classic Dealer',d:'Warm, trustworthy, family-owned feel',primary:'#1f4d3a',accent:'#c8a24a',bg:'#fbf8f1',ink:'#1f2a24',font:"'Inter',sans-serif",head:"'Playfair Display',serif",hero:'light',radius:4,upper:false}, bold:{n:'Bold Lot',d:'Big type, strong color blocks, high energy',primary:'#e4372b',accent:'#ffb400',bg:'#ffffff',ink:'#111111',font:"'Archivo',sans-serif",head:"'Archivo Black',sans-serif",hero:'color',radius:0,upper:true}, credit:{n:'Easy Credit',d:'Built for buy-here-pay-here, payment-first',primary:'#0e9f6e',accent:'#2563eb',bg:'#f6fbf8',ink:'#0f2a1f',font:"'Inter',sans-serif",head:"'Archivo',sans-serif",hero:'split',radius:14,upper:false,payFirst:true}, minimal:{n:'Minimal',d:'Lots of white space, quietly premium',primary:'#111111',accent:'#8a8a8a',bg:'#ffffff',ink:'#111111',font:"'Inter',sans-serif",head:"'Inter',sans-serif",hero:'plain',radius:2,upper:false}}; function siteCfg(){const st=S.settings;S.site=S.site||{};const d={template:'modern',primary:'',accent:'',headline:'Quality used cars. Honest prices.',subhead:'Hand-picked, inspected vehicles with in-house financing for every credit situation.',about:`${st.dealer} is a locally owned dealership. Every vehicle is inspected and reconditioned before it hits our lot, and our in-house financing team works with all credit situations.`,hours:'Mon–Fri 9am–7pm · Sat 9am–5pm · Sun closed',email:'',showPay:true,secFinance:true,secAbout:true,secTrade:true,disclaimer:'',formEndpoint:'',domain:''};for(const k in d)if(S.site[k]===undefined)S.site[k]=d[k];return S.site} function siteData(){const s=siteCfg(),st=S.settings,T=WTPL[s.template]||WTPL.modern;const ppy=FREQ[st.freq].ppy; const inv=S.vehicles.filter(v=>v.published&&v.status==='Available').map(v=>{const fin=v.price*1.07+ +st.docFee-v.price*0.1;return{stock:v.stock,year:v.year,make:v.make,model:v.model,trim:v.trim||'',color:v.color||'',miles:+v.miles,price:+v.price,vin:v.vin,photos:(v.photos||[]).map(photoURL).filter(Boolean),desc:v.notes&&!/^Price .*AI pricing/m.test(v.notes)?v.notes.split('\n').filter(l=>!/AI pricing|Trade-in from|Repo from/.test(l)).join(' '):'',down:Math.round(v.price*0.1/50)*50,pay:Math.round(pmt(fin,+st.apr,+st.term,ppy)),payLbl:FREQ[st.freq].label.toLowerCase()}}); return{inv,site:s,T:{...T,primary:s.primary||T.primary,accent:s.accent||T.accent},dealer:st.dealer,address:st.address,phone:st.phone,apr:+st.apr,term:+st.term,freq:FREQ[st.freq].label.toLowerCase(),ppy,docFee:+st.docFee,tax:+st.taxRate,year:new Date().getFullYear()}} function carSVG(color){const map={black:'#1f2937',white:'#e5e7eb',silver:'#b8bec7',gray:'#6b7280',grey:'#6b7280',red:'#c0392b',blue:'#2c5ea8',green:'#2f6b4f',yellow:'#e0b100',orange:'#e07a1f',brown:'#7a5230',gold:'#c8a24a',beige:'#d8c7a5',maroon:'#7a1f2b'};const c=map[String(color||'').toLowerCase()]||'#6b7a90'; return ``} function siteHTML(D,forExport){const s=D.site,T=D.T,e=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));const makes=[...new Set(D.inv.map(v=>v.make))].sort(); const css=`:host,.ws{all:initial}.ws{--p:${T.primary};--a:${T.accent};--bg:${T.bg};--ink:${T.ink};--r:${T.radius}px;display:block;font-family:${T.font};color:var(--ink);background:var(--bg);font-size:15px;line-height:1.55} .ws *{box-sizing:border-box}.ws h1,.ws h2,.ws h3{font-family:${T.head};margin:0;line-height:1.1;${T.upper?'text-transform:uppercase;letter-spacing:.5px;':''}}.ws a{color:inherit;text-decoration:none} .ws .wrap{max-width:1180px;margin:0 auto;padding:0 22px} .ws .nav{position:sticky;top:0;z-index:5;background:${T.hero==='dark'?'#0b1220':'var(--bg)'};color:${T.hero==='dark'?'#fff':'var(--ink)'};border-bottom:1px solid ${T.hero==='dark'?'#1e293b':'rgba(0,0,0,.08)'}} .ws .nav .wrap{display:flex;align-items:center;gap:22px;height:68px}.ws .brand{display:flex;align-items:center;gap:10px;font-family:${T.head};font-weight:800;font-size:19px}.ws .mk{width:36px;height:36px;border-radius:calc(var(--r)/1.6);background:var(--p);color:#fff;display:grid;place-items:center;font-size:14px;font-family:${T.font};font-weight:800} .ws .links{display:flex;gap:20px;margin-left:auto;font-weight:600;font-size:14px}.ws .links a{cursor:pointer;opacity:.85}.ws .links a:hover{opacity:1;color:var(--a)} .ws .btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;background:var(--p);color:#fff;border:0;border-radius:var(--r);padding:12px 20px;font-weight:700;font-size:15px;cursor:pointer;font-family:${T.font};${T.upper?'text-transform:uppercase;letter-spacing:.6px;':''}}.ws .btn.alt{background:transparent;color:inherit;box-shadow:inset 0 0 0 2px currentColor}.ws .btn.ac{background:var(--a);color:${T.template==='bold'?'#111':'#fff'}} .ws .hero{position:relative;overflow:hidden;${T.hero==='dark'?'background:radial-gradient(circle at 75% 30%,color-mix(in srgb,var(--p) 55%,transparent),transparent 55%),#0b1220;color:#fff;':T.hero==='color'?'background:var(--p);color:#fff;':T.hero==='split'?'background:linear-gradient(120deg,color-mix(in srgb,var(--p) 14%,#fff),#fff);':'background:var(--bg);'}} .ws .hero .wrap{display:grid;grid-template-columns:1.1fr .9fr;gap:30px;align-items:center;padding-top:70px;padding-bottom:70px}.ws .hero h1{font-size:${T.upper?'54px':'50px'};font-weight:800;letter-spacing:-1px}.ws .hero p{font-size:18px;opacity:.85;margin:16px 0 26px;max-width:520px} .ws .hero .car{filter:drop-shadow(0 20px 30px rgba(0,0,0,.25))}.ws .search{display:flex;gap:8px;flex-wrap:wrap;background:${T.hero==='dark'||T.hero==='color'?'rgba(255,255,255,.1)':'#fff'};padding:10px;border-radius:calc(var(--r) + 4px);box-shadow:0 10px 30px rgba(0,0,0,.08);max-width:560px} .ws select,.ws input,.ws textarea{font-family:${T.font};font-size:14px;padding:11px 12px;border:1.5px solid rgba(0,0,0,.12);border-radius:calc(var(--r)/1.5);background:#fff;color:#111;flex:1;min-width:120px} .ws .badges{display:flex;gap:18px;flex-wrap:wrap;margin-top:22px;font-size:13px;font-weight:600;opacity:.85}.ws .badges span:before{content:'✓ ';color:var(--a)} .ws section{padding:64px 0}.ws .sh{display:flex;align-items:end;gap:16px;margin-bottom:26px;flex-wrap:wrap}.ws .sh h2{font-size:34px}.ws .sh p{margin:0;opacity:.7}.ws .sh .tools{margin-left:auto;display:flex;gap:8px} .ws .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:20px} .ws .card{background:#fff;border-radius:var(--r);overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.08),0 8px 24px rgba(0,0,0,.06);cursor:pointer;transition:.18s;border:1px solid rgba(0,0,0,.06)}.ws .card:hover{transform:translateY(-3px);box-shadow:0 14px 34px rgba(0,0,0,.12)} .ws .ph{background:linear-gradient(160deg,#eef1f5,#dfe4ea);padding:18px 14px 6px;position:relative}.ws .tag{position:absolute;top:10px;left:10px;background:var(--a);color:#fff;font-size:11px;font-weight:800;padding:3px 9px;border-radius:20px;text-transform:uppercase;letter-spacing:.5px} .ws .ph.img{padding:0;background:#e5e7eb}.ws .ph.img img{display:block;width:100%;aspect-ratio:4/3;object-fit:cover}.ws .pcount{position:absolute;right:10px;bottom:10px;background:rgba(0,0,0,.6);color:#fff;font-size:11px;font-weight:700;padding:3px 8px;border-radius:20px}.ws .gal{display:flex;flex-direction:column}.ws .thumbs{display:flex;gap:6px;padding:8px;overflow-x:auto;background:#f4f6f9}.ws .thumbs img{width:72px;height:54px;object-fit:cover;border-radius:6px;cursor:pointer;opacity:.6;aspect-ratio:auto}.ws .thumbs img.on{opacity:1;outline:2px solid var(--p)}.ws .cb{padding:14px 16px 16px}.ws .cb h3{font-size:17px;font-family:${T.font};font-weight:800;text-transform:none;letter-spacing:0}.ws .meta{font-size:13px;opacity:.65;margin:3px 0 10px}.ws .pr{display:flex;align-items:end;justify-content:space-between} .ws .big{font-size:22px;font-weight:800}.ws .pay{text-align:right;font-size:12px;opacity:.75}.ws .pay b{display:block;font-size:17px;color:var(--p);opacity:1} .ws .fin{background:${T.hero==='color'?'#111':'var(--p)'};color:#fff}.ws .fin .wrap{display:grid;grid-template-columns:1fr 1fr;gap:40px;align-items:center}.ws .fin h2{font-size:38px}.ws .fin ul{padding-left:20px;line-height:2} .ws .formcard{background:#fff;color:#111;border-radius:calc(var(--r) + 4px);padding:24px;box-shadow:0 20px 50px rgba(0,0,0,.2)}.ws .formcard h3{font-size:20px;margin-bottom:12px;color:#111}.ws .fg2{display:grid;grid-template-columns:1fr 1fr;gap:10px}.ws .fg2 .w{grid-column:span 2} .ws .about .wrap{display:grid;grid-template-columns:1.2fr 1fr;gap:40px}.ws .info{background:#fff;border-radius:var(--r);padding:22px;border:1px solid rgba(0,0,0,.08)}.ws .info div{padding:8px 0;border-bottom:1px solid rgba(0,0,0,.06)}.ws .info b{display:block;font-size:12px;text-transform:uppercase;letter-spacing:.6px;opacity:.6} .ws footer{background:#0b0f17;color:#cbd2dc;padding:34px 0;font-size:13px}.ws footer .wrap{display:flex;gap:20px;flex-wrap:wrap;justify-content:space-between}.ws .disc{font-size:11px;opacity:.6;margin-top:14px;max-width:900px} .ws .ov{position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;align-items:flex-start;justify-content:center;padding:30px 14px;overflow:auto;z-index:50}.ws .ov.on{display:flex}.ws .vdp{background:#fff;color:#111;border-radius:calc(var(--r) + 4px);max-width:980px;width:100%;overflow:hidden} .ws .vdp .top{display:grid;grid-template-columns:1.2fr 1fr}.ws .vdp .ph{padding:40px 24px}.ws .vdp .side{padding:26px}.ws .x{position:absolute;right:14px;top:10px;font-size:26px;cursor:pointer;background:none;border:0} .ws .specs{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;padding:0 26px 26px}.ws .specs div{background:#f4f6f9;border-radius:calc(var(--r)/1.5);padding:10px 12px;font-size:13px}.ws .specs b{display:block;font-size:11px;opacity:.6;text-transform:uppercase} .ws .calc{background:#f4f6f9;border-radius:var(--r);padding:14px;margin:14px 0}.ws .calc .row{display:flex;justify-content:space-between;margin:4px 0}.ws .thanks{background:color-mix(in srgb,var(--a) 15%,#fff);border-radius:var(--r);padding:16px;font-weight:600} .ws .empty{padding:40px;text-align:center;opacity:.6} .ws.mob .hero .wrap,.ws.mob .fin .wrap,.ws.mob .about .wrap,.ws.mob .vdp .top{grid-template-columns:1fr}.ws.mob .links{display:none}.ws.mob .hero h1{font-size:34px}.ws.mob .specs{grid-template-columns:1fr 1fr}.ws.mob .fg2{grid-template-columns:1fr}.ws.mob .fg2 .w{grid-column:auto} @media (max-width:760px){.ws .hero .wrap,.ws .fin .wrap,.ws .about .wrap,.ws .vdp .top{grid-template-columns:1fr}.ws .links{display:none}.ws .hero h1{font-size:34px}.ws .specs{grid-template-columns:1fr 1fr}}`; const ini=D.dealer.split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase();const hero=D.inv[0]; const finPitch=T.payFirst?'Bad credit? No credit? We finance you right here.':'Financing made simple'; return `

${e(s.headline)}

${e(s.subhead)}

Every car inspectedIn-house financingTrade-ins welcome
${hero?carSVG(hero.color):carSVG('silver')}

${T.payFirst?'Cars you can afford today':'Our inventory'}

${D.inv.length} vehicles in stock

${s.secFinance?`

${e(finPitch)}

Apply in two minutes and our finance team will call you with options. Applying doesn't obligate you to buy.

  • All credit situations welcome
  • Weekly, bi-weekly or monthly payments
  • Low down payment options
  • ${s.secTrade?'
  • Use your trade-in as down payment
  • ':''}

Get pre-qualified

`:''} ${s.secAbout?`

About ${e(D.dealer)}

${e(s.about)}

Send us a message

Visit${e(D.address)}
Call or text${e(D.phone)}
${s.email?`
Email${e(s.email)}
`:''}
Hours${e(s.hours)}
`:''}
`} function siteRuntime(root,D,hooks){const q=s=>root.querySelector(s),qa=s=>[...root.querySelectorAll(s)];const T=D.T;const money=n=>'$'+Math.round(n).toLocaleString(); const svgOf=c=>hooks.svg(c);const T_=(t,d)=>{try{hooks.track&&hooks.track(t,d||{})}catch(e){}};setTimeout(()=>T_('visit',{}),0);const st={make:'',max:'',sort:'new'}; function card(v){return `
${v.miles<60000?'Low miles':''}${v.photos&&v.photos.length?`${v.year} ${v.make} ${v.model}${v.photos.length>1?`📷 ${v.photos.length}`:''}`:svgOf(v.color)}

${v.year} ${v.make} ${v.model}

${v.trim?v.trim+' · ':''}${v.miles.toLocaleString()} mi · ${v.color}
${T.payFirst&&D.site.showPay?`
${money(v.pay)}/${v.payLbl.replace('-','').replace('bi weekly','2 wks')}*
${money(v.down)} down · ${money(v.price)}
`:`
${money(v.price)}
${D.site.showPay?`
est.${money(v.pay)}*${v.payLbl}
`:''}`}
`} function grid(){let l=D.inv.filter(v=>(!st.make||v.make===st.make)&&(!st.max||v.price<=+st.max));l=l.slice().sort((a,b)=>st.sort==='plo'?a.price-b.price:st.sort==='phi'?b.price-a.price:st.sort==='mi'?a.miles-b.miles:0); q('[data-grid]').innerHTML=l.map(card).join('')||'
No vehicles match. Try another search or call us, since new cars arrive every week.
';q('[data-count]').textContent=l.length+' of '+D.inv.length+' vehicles';} function vdp(stock){const v=D.inv.find(x=>x.stock===stock);if(!v)return;T_('view',{stock});const r=D.apr/100/D.ppy; q('[data-vdp]').innerHTML=`
${v.photos&&v.photos.length?`
${v.photos.map((u,i)=>``).join('')}
`:svgOf(v.color)}
Stock ${v.stock}

${v.year} ${v.make} ${v.model} ${v.trim}

${v.miles.toLocaleString()} miles · ${v.color}
${money(v.price)}
${D.site.showPay?`
Estimate your payment
Down payment
Payments${D.term} ${D.freq}
Est. payment*
`:''}
🛒 Buy online: start your deal from home

Not a credit approval or final price. A team member will confirm taxes, fees and financing terms.

Year${v.year}
Make${v.make}
Model${v.model}
Trim${v.trim||'—'}
Mileage${v.miles.toLocaleString()}
VIN${v.vin}
${v.desc?`

${v.desc.replace(/[<>&]/g,'')}

`:''}`; q('[data-ov]').classList.add('on');const calc=()=>{const dn=+(q('[data-cdown]')?.value||0);const fin=v.price*(1+D.tax/100)+D.docFee-dn;const p=r===0?fin/D.term:fin*r/(1-Math.pow(1+r,-D.term));if(q('[data-cpay]'))q('[data-cpay]').textContent=money(Math.max(0,p))+' '+D.freq};calc();const cd=q('[data-cdown]');if(cd)cd.oninput=()=>{calc();if(!cd._t){cd._t=1;T_('calc',{stock:v.stock})}};bindForms()} function bindForms(){qa('form[data-lead]').forEach(f=>{if(f._b)return;f._b=1;f.onsubmit=ev=>{ev.preventDefault();const o=Object.fromEntries(new FormData(f).entries());o.type=f.dataset.lead;try{if(hooks.vid)o.vid=hooks.vid()}catch(e){}T_(/credit/i.test(o.type)?'credit':/trade/i.test(o.type)?'trade':'lead',{stock:o.stock||''});Promise.resolve(hooks.lead(o)).then(()=>{f.innerHTML=`
Thanks${o.name?', '+String(o.name).split(' ')[0].replace(/[<>&]/g,''):''}! We got your request and will reach out shortly. Need us now? Call ${D.phone}.
`})}})} root.addEventListener('click',ev=>{const th=ev.target.closest('[data-thumb]');if(th){const m=q('[data-main]');if(m)m.src=th.src;qa('[data-thumb]').forEach(x=>x.classList.toggle('on',x===th));return}const t=ev.target.closest('[data-go],[data-act],[data-vdp-open],[data-close],[data-ov]');if(!t)return; if(t.dataset.go){ev.preventDefault();const sec=q(`[data-sec="${t.dataset.go}"]`);if(sec)sec.scrollIntoView({behavior:'smooth'})} else if(t.dataset.act==='search'){st.make=q('[data-f="make"]').value;st.max=q('[data-f="max"]').value;grid();q('[data-sec="inv"]').scrollIntoView({behavior:'smooth'})} else if(t.dataset.vdpOpen)vdp(t.dataset.vdpOpen);else if(t.dataset.close!==undefined||(t.dataset.ov!==undefined&&ev.target===t))q('[data-ov]').classList.remove('on')}); const so=q('[data-f="sort"]');so.onchange=()=>{st.sort=so.value;grid()};grid();bindForms()} function siteLeadToCRM(o){if(o.type==='Online deal'){const ex={stock:o.stock,payType:o.payType,down:o.down,term:o.term,income:o.income,employer:o.employer,trade:o.tradeDesc?{desc:o.tradeDesc,miles:o.tradeMiles,payoff:o.tradePayoff}:null};const v=S.vehicles.find(z=>z.stock===o.stock);if(v&&!ex.estPayment&&o.payType!=='cash'){const D=siteData();const fin=v.price*(1+D.tax/100)+D.docFee-(+o.down||0);const r=D.apr/100/12,n=+o.term||D.term;ex.estPayment=Math.max(0,r?fin*r/(1-Math.pow(1+r,-n)):fin/n)} const c=intakeLead({name:o.name,phone:o.phone,email:o.email,source:'Website',type:'Online deal',vehicle:v?vname(v):'',message:'Started an online deal',consent:!!o.consent,extra:ex},'Website');save();setTimeout(()=>{toast('New online deal started on your website');renderNav()},50);return c} const c={id:uid(),created:TODAY,name:o.name||'Website visitor',phone:o.phone||'',email:o.email||'',address:'',source:'Website',stage:'New',employer:'',income:+String(o.income||'').replace(/[^\d.]/g,'')||0,interest:/\(S\d+\)/.test(o.type)?o.type.replace(/^Vehicle inquiry – /,'').replace(/ \(S\d+\)$/,''):'',followUp:TODAY,smsConsent:!!o.consent,optOut:false,dnc:false,notes:[{date:TODAY,by:'Website',text:`${o.type}${o.down?' · down available: '+o.down:''}${o.trade?' · trade: '+o.trade:''}`}]}; S.customers.push(c);logComm({customerId:c.id,channel:'text',dir:'in',body:`[Website – ${o.type}] ${o.msg||''}`.trim()});save();setTimeout(()=>{toast('New website lead: '+c.name);renderNav()},50)} let siteDev='desk'; VIEWS.website=()=>{const s=siteCfg(),D=siteData();const leads=S.customers.filter(c=>c.source==='Website'); return `
${D.inv.length} published vehicles on your site · ${leads.length} website leads in CRM
${DL?``:''}
Template
${Object.entries(WTPL).map(([k,t])=>``).join('')}
Brand & text
Sections
${[['showPay','Show estimated payments'],['secFinance','Financing / credit application'],['secTrade','Trade-in mentions'],['secAbout','About & contact']].map(o=>``).join('')}
Publishing

Inventory comes from cars marked Publish to website and Available, so new arrivals appear and sold cars disappear automatically. Forms in this preview create real leads in your CRM. On the downloaded site, forms send to your form endpoint, or open the visitor's email app if none is set.

${esc(s.domain||'www.'+S.settings.dealer.toLowerCase().replace(/[^a-z0-9]+/g,'')+'.com')}
`}; AFTER.website=()=>{const host=$('#sitehost');if(!host)return;const D=siteData();let sr=host.shadowRoot||host.attachShadow({mode:'open'});sr.innerHTML=siteHTML(D);const ws=sr.querySelector('.ws');if(siteDev==='mob')ws.classList.add('mob'); siteRuntime(sr,D,{svg:carSVG,lead:siteLeadToCRM}); const f=$('#sitef');let tm;f.oninput=f.onchange=()=>{clearTimeout(tm);tm=setTimeout(()=>{const x=fd(f);Object.assign(S.site,{primary:x.primary,accent:x.accent,headline:x.headline,subhead:x.subhead,about:x.about,hours:x.hours,email:x.email,domain:x.domain,formEndpoint:x.formEndpoint,disclaimer:x.disclaimer});['showPay','secFinance','secTrade','secAbout'].forEach(k=>S.site[k]=!!x[k]);save();const el=document.activeElement,nm=el&&el.name,pos=el&&el.selectionStart;render();if(nm){const n=$('#sitef')?.elements[nm];if(n&&n.focus){n.focus();try{n.setSelectionRange(pos,pos)}catch(e){}}}},350)}}; async function siteExportAsync(){const D=siteData();for(const iv of D.inv){const v=S.vehicles.find(x=>x.stock===iv.stock);iv.photos=[];for(const p of (v.photos||[]).slice(0,12)){const u=await photoDataURL(p);if(u)iv.photos.push(u)}}return siteExport(D)} function siteExport(D0){const D=D0||siteData();const s=D.site;const fonts='https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&family=Playfair+Display:wght@700;800&family=Archivo:wght@400;600;800&family=Archivo+Black&display=swap'; const trackUrl=s.tracking===false?'':(s.trackUrl||'');const hooks=`{svg:${carSVG.toString()},vid:function(){try{var k='llv',v=localStorage.getItem(k);if(!v){v=Math.random().toString(36).slice(2)+Date.now().toString(36);localStorage.setItem(k,v)}return v}catch(e){return ''}},track:function(t,d){var u=${JSON.stringify(trackUrl)};if(!u||navigator.globalPrivacyControl||navigator.doNotTrack==='1')return;var b=JSON.stringify(Object.assign({vid:this.vid(),type:t,page:location.pathname,ref:document.referrer,utm:location.search.slice(0,120)},d||{}));try{if(navigator.sendBeacon)navigator.sendBeacon(u,new Blob([b],{type:'text/plain'}));else fetch(u,{method:'POST',body:b,keepalive:true})}catch(e){}},lead:function(o){var ep=${JSON.stringify(s.formEndpoint||'')};if(ep){return fetch(ep,{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json'},body:JSON.stringify(o)}).catch(function(){})}var to=${JSON.stringify(s.email||'')};var body=Object.keys(o).map(function(k){return k+': '+o[k]}).join('\\n');location.href='mailto:'+to+'?subject='+encodeURIComponent('Website lead: '+o.type)+'&body='+encodeURIComponent(body)}}`; return `${esc(D.dealer)} | Used Cars${S.settings.address?' – '+esc(S.settings.address.split(',').slice(-2).join(',').trim()):''}${siteHTML(D,true)} `} async function dlSite(){toast('Building website…');try{await DL.save({filename:'index.html',data:await siteExportAsync()});toast('Website saved. Upload index.html to your web host')}catch(e){if(e.code!=='declined')copyText(siteExport())}} /* ================= Listing feeds (syndication) ================= */ const CHANNELS=[['cars','Cars.com','Inventory feed delivered by FTP/feed provider; set up with your Cars.com rep','std'],['cargurus','CarGurus','Inventory feed via FTP or feed provider; listings are free, featured upgrades paid','std'],['autotrader','Autotrader','Inventory feed via FTP/feed provider set up with Autotrader','std'],['facebook','Facebook Marketplace','Vehicle catalog file uploaded in Meta Commerce Manager (requires eligible dealer account)','fb'],['google','Google Vehicle Ads','Vehicle feed uploaded in Google Merchant Center (vehicle ads program)','google'],['carfax','CARFAX Listings','Inventory feed via your feed provider or CARFAX dealer account','std'],['truecar','TrueCar','Inventory feed for TrueCar dealer network members','std'],['offerup','OfferUp','Dealer inventory via feed partner','std'],['website','Your website','Built in: published cars appear automatically','site']]; function feedCfg(){S.feeds=S.feeds||{};CHANNELS.forEach(c=>{S.feeds[c[0]]=Object.assign({on:['cars','cargurus','facebook','website'].includes(c[0]),acct:'',method:'FTP',host:'',user:'',last:''},S.feeds[c[0]]||{})});return S.feeds} let feedVeh=k=>S.vehicles.filter(v=>v.published&&v.status==='Available'&&!(v.noFeed||[]).includes(k)); const csvq=x=>{x=String(x??'');return /[",\n]/.test(x)?'"'+x.replace(/"/g,'""')+'"':x}; function vDesc(v){return (v.notes||'').split('\n').filter(l=>!/AI pricing|Trade-in from|Repo from/.test(l)).join(' ').trim()||`${vname(v)} with ${(+v.miles).toLocaleString()} miles. In-house financing available. Call ${S.settings.phone}.`} function vUrl(v){const d=(S.site&&S.site.domain)||'';return d?`https://${d.replace(/^https?:\/\//,'').replace(/\/$/,'')}/#${v.stock}`:''} function feedFile(k){if(k==='custom')return customFeedFile();const vs=feedVeh(k),st=S.settings,addr=st.address; if(k==='facebook'){const h=['vehicle_id','title','description','url','make','model','year','mileage.value','mileage.unit','price','vin','state_of_vehicle','exterior_color','trim','body_style','address','image[0].url']; return{name:`facebook-vehicle-catalog-${TODAY}.csv`,data:h.join(',')+'\n'+vs.map(v=>[v.stock,`${v.year} ${v.make} ${v.model}`,vDesc(v),vUrl(v),v.make,v.model,v.year,v.miles,'MI',`${(+v.price).toFixed(2)} USD`,v.vin,'USED',v.color,v.trim,'',addr,''].map(csvq).join(',')).join('\n')}} if(k==='google'){const h=['id','title','description','link','image_link','price','condition','brand','model','year','mileage','vin','color','trim','store_code']; return{name:`google-vehicle-feed-${TODAY}.tsv`,data:h.join('\t')+'\n'+vs.map(v=>[v.stock,`${v.year} ${v.make} ${v.model} ${v.trim||''}`.trim(),vDesc(v),vUrl(v),'',`${(+v.price).toFixed(2)} USD`,'used',v.make,v.model,v.year,`${v.miles} miles`,v.vin,v.color,v.trim,''].map(x=>String(x??'').replace(/[\t\n]/g,' ')).join('\t')).join('\n')}} const h=['dealer_id','dealer_name','dealer_address','dealer_phone','stock_number','vin','year','make','model','trim','exterior_color','mileage','price','condition','description','vehicle_url','photo_urls','date_in_stock']; return{name:`${k}-inventory-${TODAY}.csv`,data:h.join(',')+'\n'+vs.map(v=>[S.feeds[k]?.acct||'',st.dealer,addr,st.phone,v.stock,v.vin,v.year,v.make,v.model,v.trim,v.color,v.miles,v.price,'Used',vDesc(v),vUrl(v),'',v.acquired].map(csvq).join(',')).join('\n')}} async function sendFeed(k){const f=feedFile(k);const c=CHANNELS.find(x=>x[0]===k);if(!feedVeh(k).length)return toast('No published cars for '+c[1]); const done=()=>{S.feeds[k].last=nowAt();save();render()};if(DL){try{await DL.save({filename:f.name,data:f.data});done();toast(c[1]+' feed saved – upload it to the channel')}catch(e){if(e.code!=='declined'){copyText(f.data);done()}}}else{copyText(f.data);done()}} function feedModal(k){const c=CHANNELS.find(x=>x[0]===k),f=S.feeds[k];openModal(mh(`${c[1]} feed settings`)+`

${esc(c[2])}.

Passwords are not stored here. Automatic nightly uploads need the DealerPen server, which keeps credentials securely.
`); $('#fdf').onsubmit=e=>{e.preventDefault();Object.assign(f,fd(e.target));save();closeModal();render();toast('Saved')}} function toggleVehFeed(vid,k,on){const v=veh(vid);v.noFeed=v.noFeed||[];v.noFeed=on?v.noFeed.filter(x=>x!==k):[...new Set([...v.noFeed,k])];save();render()} VIEWS.feeds=()=>{const F_=feedCfg();const on=CHANNELS.filter(c=>F_[c[0]].on);const pub=S.vehicles.filter(v=>v.published&&v.status==='Available');const unpub=S.vehicles.filter(v=>!v.published&&v.status==='Available'); const issues=pub.filter(v=>!(v.photos||[]).length||!v.vin||v.vin.length!==17||!+v.price||!+v.miles||!(v.notes||'').trim()); return `
${kpi('Cars being marketed',pub.length,unpub.length+' available but not published')}${kpi('Active channels',on.length,'of '+CHANNELS.length)}${kpi('Listing issues',issues.length,'missing photos, VIN, price, miles or description')}
${CHANNELS.map(c=>{const f=F_[c[0]],n=c[3]==='site'?pub.length:feedVeh(c[0]).length;return `

${esc(c[1])}

${esc(c[2])}
Vehicles${n}
Last sent${f.last?ftime(f.last):'Never'}
${c[3]==='site'?``:c[3]==='kit'?``:c[3]==='custom'?`
`:`
`}
`}).join('')}
${on.filter(c=>!['site','kit'].includes(c[3])).map(c=>``).join('')}${pub.map(v=>{const miss=[!(v.photos||[]).length?'photos':'',!v.vin||v.vin.length!==17?'VIN':'',!+v.price?'price':'',!+v.miles?'miles':'',!(v.notes||'').trim()?'description':''].filter(Boolean); return `${on.filter(c=>!['site','kit'].includes(c[3])).map(c=>``).join('')}`}).join('')||''}
VehiclePriceListing quality${esc(c[0]==='custom'&&S.feeds.custom.label?S.feeds.custom.label:c[1])}
${v.stock} ${esc(vname(v))}${$0(v.price)}${miss.length?`Missing ${miss.join(', ')}`:'Ready'}${!(v.notes||'').trim()&&aiOn('listing')?` `:''}
No published vehicles. Tick "Publish to website & listing feed" on a vehicle.

DealerPen builds each channel's feed file: a standard inventory CSV, Meta's vehicle catalog format, and a Google vehicle feed. Check each channel's current spec, since requirements change. Marketplaces need photos at public web addresses. Photos uploaded here are private to your DealerPen, so photo links fill in once the server hosts them publicly. Automatic nightly delivery by FTP/API needs the DealerPen server plus a feed agreement with each site.

`}; /* ---- extra channels + custom feed ---- */ CHANNELS.splice(CHANNELS.length-1,0,['ebay','eBay Motors','Dealer listings via eBay Motors dealer tools or a feed partner','std'],['autolist','Autolist','Inventory feed through your feed provider','std'],['edmunds','Edmunds','Dealer inventory feed via Edmunds dealer program','std'],['ksl','KSL Cars','Dealer feed for Utah/Mountain West dealers (KSL dealer account)','std'],['carsoup','CarSoup','Dealer inventory feed (Midwest markets)','std'],['craigslist','Craigslist','No feed: use the post kit (copy-ready text + photos) and post by hand','kit'],['custom','Custom feed','Build your own format for any site, provider or partner: CSV, TSV, JSON or XML','custom']); const CUSTOM_FIELDS=[['stock','Stock #',v=>v.stock],['vin','VIN',v=>v.vin],['year','Year',v=>v.year],['make','Make',v=>v.make],['model','Model',v=>v.model],['trim','Trim',v=>v.trim],['color','Color',v=>v.color],['miles','Mileage',v=>v.miles],['price','Price',v=>v.price],['cost','Cost (internal)',v=>vcost(v)],['days','Days in stock',v=>age(v)],['desc','Description',v=>vDesc(v)],['url','Vehicle URL',v=>vUrl(v)],['photos','Photo count',v=>(v.photos||[]).length],['dealer','Dealer name',()=>S.settings.dealer],['phone','Dealer phone',()=>S.settings.phone],['address','Dealer address',()=>S.settings.address],['condition','Condition',()=>'Used']]; function customFeedFile(){const c=S.feeds.custom;const cols=(c.cols||['stock','vin','year','make','model','trim','miles','price','desc','url']).map(k=>CUSTOM_FIELDS.find(f=>f[0]===k)).filter(Boolean);const vs=feedVeh('custom');const fmt=c.fmt||'csv'; const recs=vs.map(v=>Object.fromEntries(cols.map(f=>[f[0],f[2](v)]))); if(fmt==='json')return{name:`custom-feed-${TODAY}.json`,data:JSON.stringify({dealer:S.settings.dealer,generated:nowAt(),vehicles:recs},null,2)}; if(fmt==='xml'){const x=s=>String(s??'').replace(/[<>&'"]/g,ch=>({'<':'<','>':'>','&':'&',"'":''','"':'"'}[ch]));return{name:`custom-feed-${TODAY}.txt`,data:`\n\n${recs.map(r=>' \n'+Object.entries(r).map(([k,v])=>` <${k}>${x(v)}`).join('\n')+'\n ').join('\n')}\n`}} const sep=fmt==='tsv'?'\t':',';const q=fmt==='tsv'?(v=>String(v??'').replace(/[\t\n]/g,' ')):csvq;return{name:`custom-feed-${TODAY}.${fmt==='tsv'?'tsv':'csv'}`,data:cols.map(f=>f[1]).join(sep)+'\n'+recs.map(r=>Object.values(r).map(q).join(sep)).join('\n')}} function customFeedModal(){const c=S.feeds.custom;const sel=new Set(c.cols||['stock','vin','year','make','model','trim','miles','price','desc','url']);openModal(mh('Custom feed builder')+`
Columns
${CUSTOM_FIELDS.map(f=>``).join('')}

XML downloads with a .txt extension because of a file-type limit here. Rename it to .xml.

`); $('#cff').onsubmit=e=>{e.preventDefault();const x=fd(e.target);Object.assign(c,{label:x.label,fmt:x.fmt,acct:x.acct,cols:CUSTOM_FIELDS.map(f=>f[0]).filter(k=>x['col_'+k])});save();closeModal();render();toast('Custom feed saved')}} /* ---- zip (store) for photo downloads ---- */ const CRCT=(()=>{const t=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;t[n]=c>>>0}return t})(); const crc32=b=>{let c=0xFFFFFFFF;for(let i=0;i>>8);return (c^0xFFFFFFFF)>>>0}; function makeZip(files){const enc=new TextEncoder();const parts=[],cd=[];let off=0;const u16=n=>[n&255,(n>>8)&255],u32=n=>[n&255,(n>>8)&255,(n>>16)&255,(n>>>24)&255]; files.forEach(f=>{const nm=enc.encode(f.name),d=f.data,c=crc32(d);const lh=new Uint8Array([0x50,0x4b,3,4,...u16(20),0,0,0,0,0,0,0,0,...u32(c),...u32(d.length),...u32(d.length),...u16(nm.length),0,0]);parts.push(lh,nm,d); cd.push(new Uint8Array([0x50,0x4b,1,2,...u16(20),...u16(20),0,0,0,0,0,0,0,0,...u32(c),...u32(d.length),...u32(d.length),...u16(nm.length),0,0,0,0,0,0,0,0,0,0,0,0,...u32(off)]),nm);off+=lh.length+nm.length+d.length}); const cdl=cd.reduce((a,x)=>a+x.length,0);const end=new Uint8Array([0x50,0x4b,5,6,0,0,0,0,...u16(files.length),...u16(files.length),...u32(cdl),...u32(off),0,0]);return new Blob([...parts,...cd,end],{type:'application/zip'})} async function photosZip(v){const files=[];let i=1;for(const p of (v.photos||[])){try{let b;if(p.src==='i')b=await idbOp('readonly',s=>s.get(p.id));else b=await (await fetch(workspaceMount+'/_blob/'+p.id)).blob();if(b)files.push({name:`${v.stock}-${String(i++).padStart(2,'0')}.jpg`,data:new Uint8Array(await b.arrayBuffer())})}catch(e){}}return files.length?makeZip(files):null} async function dlPhotos(vid){const v=veh(vid);if(!(v.photos||[]).length)return toast('This vehicle has no photos yet');if(!DL)return toast('Downloads are not available here');toast('Packing photos…');const z=await photosZip(v);if(!z)return toast('Could not read the photos');try{await DL.save({filename:`${v.stock}-photos.zip`,data:z});toast('Photos saved')}catch(e){}} function kitPicker(){const l=S.vehicles.filter(v=>v.published&&v.status==='Available');openModal(mh('Craigslist post kit')+`

Pick a car. You'll get copy-ready text and a photo download, then post it on Craigslist yourself (Craigslist charges dealers per post).

${l.map(v=>``).join('')||''}
${v.stock}${esc(vname(v))}${$0(v.price)}${(v.photos||[]).length} 📷
No published cars
`)} function clKit(vid){const v=veh(vid),k=fbKitText(v);openModal(mh(`Craigslist kit · ${esc(v.stock)}`)+`
${(v.photos||[]).length?``:''}Open Craigslist ↗
`,true)} /* ================= Title Admin (DLRdmv / Vitu / NTX) ================= */ const TPROV=[['dlrdmv','DLRdmv','In-state e-filing in FL (EFS), GA (ETR), MN (EVTR) and WI (EVR), plus DLR50 for out-of-state deals','https://www.dlrdmv.com/',['FL','GA','MN','WI']], ['vitu','Vitu','In-state EVR/ERT in supported states, plus Vitu Interstate for 50-state title & registration','https://vitu.com/',[]], ['ntx','NTX (Vitu)','National Title Exchange: digital title transfers between dealers, lenders and states','https://vitu.com/products/ntx.html',[]], ['manual','Manual / tag agency','Paper packet to your county office, tag agency or runner','',[]]]; const TTYPES=['In-state title & registration','Out-of-state title & registration','E-title transfer (NTX)','Title only (no plates)','Duplicate / corrected title','Lien release / payoff title']; const TXST=['Prepared','Submitted','Needs correction','Approved','Plates / tags issued','Title issued','Complete']; const txPill=s=>`${s}`; const INTITLE=['In hand','E-title (NTX)','Waiting on lender payoff','Waiting on seller / auction','Missing','Branded / problem']; function tpCfg(){S.titleProv=S.titleProv||{};TPROV.forEach(p=>{S.titleProv[p[0]]=Object.assign({on:p[0]==='manual',acct:'',states:p[4].join(', ')},S.titleProv[p[0]]||{})});return S.titleProv} function provFor(state,out){const c=tpCfg();const ok=k=>c[k]&&c[k].on;const inS=k=>(c[k].states||'').toUpperCase().split(/[,\s]+/).includes(state); if(out){if(ok('vitu'))return'vitu';if(ok('dlrdmv'))return'dlrdmv'}else{if(ok('dlrdmv')&&inS('dlrdmv'))return'dlrdmv';if(ok('vitu')&&(inS('vitu')||!c.vitu.states))return'vitu'}return'manual'} function titlePacket(d){const v=veh(d.vehicleId),c=cust(d.customerId),t=dealTitle(d);return{deal_number:d.no,sale_date:d.date,sale_type:d.type,dealer:{name:S.settings.dealer,license:S.settings.dealerLicense||'',address:S.settings.address,phone:S.settings.phone,state:S.settings.state||''}, buyer:{name:c?.name,address:c?.address,phone:c?.phone,email:c?.email},vehicle:{vin:v.vin,year:v.year,make:v.make,model:v.model,trim:v.trim,color:v.color,odometer:+v.miles,odometer_status:'Actual',incoming_title_state:v.titleState||'',incoming_title_number:v.titleNo||''}, sale:{price:+d.price,doc_fee:+d.docFee,trade_allowance:+d.tradeAllow,taxable_amount:d.taxable,tax_rate:+d.taxRate,sales_tax:d.tax,other_fees:+d.otherFees}, lien:d.type==='Cash'?null:{lienholder:d.type==='BHPH'?S.settings.dealer:d.lender||'',address:d.type==='BHPH'?S.settings.address:'',lien_date:d.date,amount:d.financed}, trade:d.tradeDesc?{description:d.tradeDesc,vin:d.tradeVin||'',payoff:+d.tradePayoff}:null,registration:{state:t.state,temp_tag:t.tempTag||'',temp_tag_expires:t.tempExp||''}}} function titleTxModal(dealId){const d=S.deals.find(x=>x.id===dealId),t=dealTitle(d);const c=cust(d.customerId);const st=t.state||S.settings.state||'';const out=st&&S.settings.state&&st!==S.settings.state;const def=provFor(st,out);tpCfg(); openModal(mh(`Title & registration · deal #${d.no} · ${esc(c?.name)}`)+`
`); const f=$('#ttx');const chk=()=>{const pv=f.prov.value,uu=S.users.find(u=>u.id===f.under.value),en=uu&&uu.tEnroll&&uu.tEnroll[pv];const who=S.users.filter(u=>u.tEnroll&&u.tEnroll[pv]&&u.tEnroll[pv].on).map(u=>u.name);$('#enrw').innerHTML=pv==='manual'?'':en&&en.on?`✓ ${esc(uu.name)} is enrolled with ${esc(TPROV.find(p=>p[0]===pv)[1])}${en.user?' as '+esc(en.user):''}`:`
${esc(uu?.name||'')} isn't marked as enrolled with ${esc(TPROV.find(p=>p[0]===pv)[1])}.${who.length?' Enrolled: '+esc(who.join(', ')):' Nobody is marked enrolled yet (Title Admin → Providers).'}
`;const v=veh(d.vehicleId),cu=cust(d.customerId);const items=[[!!(cu?.address&&cu.address.length>8),'Buyer address'],[!!v.vin&&v.vin.length===17,'17-character VIN'],[+v.miles>0,'Odometer reading'],[!!(v.titleStatus==='In hand'||v.titleStatus==='E-title (NTX)'),'Title for this vehicle is in hand ('+(v.titleStatus||'not recorded')+')'],[!!S.settings.dealerLicense,'Dealer license # in Settings'],[d.type==='Cash'||!!(d.type==='BHPH'||d.lender),'Lienholder recorded']]; $('#ttxchk').innerHTML=`
${items.map(i=>`
${i[0]?'✓':'!'}${esc(i[1])}
`).join('')}
`};f.oninput=chk;chk(); f.onsubmit=e=>{e.preventDefault();const x=fd(f);t.state=x.state;S.titleTx=S.titleTx||[];const uu=S.users.find(u=>u.id===x.under);const tx={id:uid(),dealId,prov:x.prov,under:x.under,underUser:uu&&uu.tEnroll&&uu.tEnroll[x.prov]?uu.tEnroll[x.prov].user||'':'',type:x.type,state:x.state,fees:+x.fees||0,plate:x.plate,notes:x.notes,status:'Prepared',ref:'',created:nowAt(),by:S.settings.user,events:[{at:nowAt(),by:S.settings.user,text:`Prepared ${x.type} for ${stateOf(x.state)?.[1]||x.state} via ${TPROV.find(p=>p[0]===x.prov)[1]}${x.prov!=='manual'&&uu?' under '+uu.name+'\'s account':''}`}]};S.titleTx.push(tx);if(t.status==='Not started')t.status='Docs signed';save();closeModal();render();titleTxView(tx.id)}} async function txExport(id){const tx=S.titleTx.find(x=>x.id===id),d=S.deals.find(x=>x.id===tx.dealId);const data=JSON.stringify({provider:tx.prov,transaction_type:tx.type,...titlePacket(d)},null,2); if(DL){try{await DL.save({filename:`title-${d.no}-${tx.prov}.json`,data});toast('Title data saved')}catch(e){if(e.code!=='declined')copyText(data)}}else copyText(data)} function titleTxView(id){const tx=S.titleTx.find(x=>x.id===id),d=S.deals.find(x=>x.id===tx.dealId),p=TPROV.find(x=>x[0]===tx.prov),pk=titlePacket(d);const t=dealTitle(d); const rows=[['Buyer',pk.buyer.name],['Buyer address',pk.buyer.address],['VIN',pk.vehicle.vin],['Year / make / model',`${pk.vehicle.year} ${pk.vehicle.make} ${pk.vehicle.model}`],['Odometer',pk.vehicle.odometer],['Sale date',pk.sale_date],['Sale price',pk.sale.price],['Trade allowance',pk.sale.trade_allowance],['Taxable amount',pk.sale.taxable_amount],['Sales tax',pk.sale.sales_tax],['Lienholder',pk.lien?.lienholder||'None'],['Lien amount',pk.lien?.amount||''],['Incoming title #',pk.vehicle.incoming_title_number],['Dealer license #',pk.dealer.license]]; openModal(mh(`${esc(tx.type)} · deal #${d.no}`)+`
Provider${esc(p[1])}
State${esc(tx.state)}
Status${txPill(tx.status)}
Provider ref #${esc(tx.ref||'—')}
Submitted under${esc(tx.under?uname(tx.under):'—')}${tx.underUser?' ('+esc(tx.underUser)+')':''}
${tx.prov!=='manual'&&S.titleProv[tx.prov]&&!S.titleProv[tx.prov].live?`
DealerPen isn't connected to ${esc(p[1])} yet, so enter this deal in ${esc(p[1])} using the details below (copy each one, or download the data file), then record the reference number and status here.
`:''}
${p[3]?`Open ${esc(p[1])} ↗`:''}
${rows.map(r=>``).join('')}
${esc(r[0])}${esc(r[1]??'')}

History

${tx.events.slice().reverse().map(e=>`
${esc(e.text)}
${ftime(e.at)} · ${esc(e.by)}
`).join('')}
`,true); $('#txsave').onclick=()=>{const ns=$('#txs').value,ref=$('#txr').value.trim(),note=$('#txn').value.trim();const ch=[];if(ns!==tx.status){ch.push('Status → '+ns);tx.status=ns}if(ref!==tx.ref){ch.push('Ref # '+ref);tx.ref=ref}t.plate=$('#txp').value.trim();t.titleNo=$('#txt').value.trim(); if(ns==='Submitted'&&!t.sent)t.sent=TODAY;t.status=ns==='Complete'?'Complete':ns==='Title issued'?'Title received':ns==='Plates / tags issued'?'Plates delivered':['Submitted','Approved','Needs correction'].includes(ns)?'Sent to state':t.status; if(ch.length||note)tx.events.push({at:nowAt(),by:S.settings.user,text:[...ch,note].filter(Boolean).join(' · ')});save();closeModal();render();toast('Title transaction updated')}} function inTitleModal(vid){const v=veh(vid);openModal(mh(`Incoming title · ${esc(v.stock)} ${esc(vname(v))}`)+`

Selling a car before its title is in hand risks delays and unhappy buyers. DealerPen flags those cars in Title Admin.

`); $('#itf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(x.titleStatus==='In hand'&&!x.titleRcvd)x.titleRcvd=TODAY;Object.assign(v,x);save();closeModal();render();toast('Title info saved')}} VIEWS.titleadmin=()=>{tpCfg();const T=ui.taTab||'queue';const tabs=[['queue','Outgoing (sold)'],['incoming','Incoming titles'],['providers','Providers']];const head=`
${tabs.map(t=>``).join('')}
`; const txs=S.titleTx||[];const lastTx=d=>txs.filter(x=>x.dealId===d.id).slice(-1)[0]; const noTitleSold=S.deals.filter(d=>!['In hand','E-title (NTX)'].includes(veh(d.vehicleId)?.titleStatus)&&dealTitle(d).status!=='Complete');const noTitleLot=S.vehicles.filter(v=>['Available','Pending','In Recon'].includes(v.status)&&!['In hand','E-title (NTX)'].includes(v.titleStatus)); const kp=`
${kpi('Open title transactions',txs.filter(x=>x.status!=='Complete').length,txs.filter(x=>x.status==='Needs correction').length+' need correction')}${kpi('Sold, not yet submitted',S.deals.filter(d=>!lastTx(d)&&dealTitle(d).status!=='Complete').length,'deals')}${kpi('Temp tags expiring ≤7d',S.deals.filter(d=>{const t=dealTitle(d);return t.tempExp&&t.status!=='Complete'&&diff(TODAY,t.tempExp)<=7}).length,'')}${kpi('Lot cars without title',noTitleLot.length,'not in hand')}
`; if(T==='providers')return head+`
${TPROV.map(p=>{const c=S.titleProv[p[0]];return `

${esc(p[1])}

${esc(p[2])}
${p[0]!=='manual'?`
Not connectedWebsite ↗
`:'
Print the title packet from Forms and track it here.
'}
`}).join('')}
Who's enrolledTick each person enrolled with a provider and enter their username there. Never enter passwords here.
${TPROV.filter(p=>p[0]!=='manual').map(p=>``).join('')}${S.users.filter(u=>u.active).map(u=>{u.tEnroll=u.tEnroll||{};return `${TPROV.filter(p=>p[0]!=='manual').map(p=>{const e=u.tEnroll[p[0]]||{};return ``}).join('')}`}).join('')}
UserRole${esc(p[1])}
${esc(u.name)}${esc(u.role)}

Connecting live

Your dealership or individual users can be enrolled with each provider. Live submission also needs DealerPen approved as an integration partner, with each enrolled user's API credentials stored on the DealerPen server (never in the browser). Vitu publishes a developer API (developer.vitu.com) covering fee estimates, ready-to-sign state forms and title/registration submissions. DLRdmv and NTX connections are arranged with those companies. Once you have credentials, the DealerPen server will submit deals automatically and pull back status, plate and title numbers. Until then, use each transaction's copy-ready details and data file.
`; if(T==='incoming')return head+kp+`${noTitleSold.length?`
⚠ ${noTitleSold.length} sold vehicle(s) don't have a title in hand. Chase these first: ${noTitleSold.map(d=>``).join(' ')}
`:''}
${S.vehicles.filter(v=>v.status!=='Sold'||noTitleSold.some(d=>d.vehicleId===v.id)).map(v=>``).join('')}
VehicleStatusTitle statusState / #BrandReceivedNotes
${v.stock} ${esc(vname(v))}${statusPill(v.status)}${esc(v.titleStatus||'Not recorded')}${esc([v.titleState,v.titleNo].filter(Boolean).join(' · '))||'—'}${esc(v.titleBrand||'')}${v.titleRcvd?fdate(v.titleRcvd):'—'}${esc(v.titleNotes||'')}
`; return head+kp+`
${S.deals.slice().sort((a,b)=>b.date.localeCompare(a.date)).map(d=>{const t=dealTitle(d),tx=lastTx(d),e=t.tempExp?diff(TODAY,t.tempExp):null;return ``}).join('')||''}
DealCustomerVehicleStateProviderTransactionTemp tagPlate / title
#${d.no}
${fdate(d.date)}
${esc(cust(d.customerId)?.name)}${esc(vname(veh(d.vehicleId)))}${['In hand','E-title (NTX)'].includes(veh(d.vehicleId)?.titleStatus)?'':' no title'}${t.state||'—'}${tx?esc(TPROV.find(p=>p[0]===tx.prov)[1]):'—'}${tx?txPill(tx.status)+(tx.ref?`
#${esc(tx.ref)}
`:''):'Not started'}
${t.tempTag?esc(t.tempTag):'—'}${e!=null&&t.status!=='Complete'?`
${e<0?'expired':e+'d left'}
`:''}
${esc([t.plate,t.titleNo].filter(Boolean).join(' / '))||'—'}${tx?``:``}
No deals yet
`}; /* ================= Custom forms ================= */ const MERGE=[['buyer_name','Buyer name',x=>x.c?.name],['buyer_first','Buyer first name',x=>(x.c?.name||'').split(' ')[0]],['buyer_address','Buyer address',x=>x.c?.address],['buyer_phone','Buyer phone',x=>x.c?.phone],['buyer_email','Buyer email',x=>x.c?.email], ['year','Year',x=>x.v.year],['make','Make',x=>x.v.make],['model','Model',x=>x.v.model],['trim','Trim',x=>x.v.trim],['color','Color',x=>x.v.color],['vin','VIN',x=>x.v.vin],['stock','Stock #',x=>x.v.stock],['miles','Odometer',x=>(+x.v.miles).toLocaleString()], ['deal_no','Deal #',x=>x.d.no],['sale_date','Sale date',x=>fdate(x.d.date)],['sale_price','Sale price',x=>$$(x.d.price)],['doc_fee','Doc fee',x=>$$(x.d.docFee)],['tax','Sales tax',x=>$$(x.d.tax)],['total','Total cash price',x=>$$(x.d.total)],['down','Down payment',x=>$$(x.d.down)],['trade_desc','Trade-in',x=>x.d.tradeDesc||'None'],['trade_allow','Trade allowance',x=>$$(x.d.tradeAllow)],['trade_payoff','Trade payoff',x=>$$(x.d.tradePayoff)], ['financed','Amount financed',x=>$$(x.d.financed)],['apr','APR',x=>(+x.d.apr||0).toFixed(2)+'%'],['payment','Payment',x=>$$(x.d.payment)],['term','# of payments',x=>x.d.term],['frequency','Payment frequency',x=>FREQ[x.d.freq]?.label||''],['first_due','First payment due',x=>x.d.type==='Cash'?'':fdate(addPeriods(x.d.date,x.d.freq,1))],['lender','Lender',x=>x.d.type==='BHPH'?S.settings.dealer:x.d.lender||''],['acct','Account #',x=>x.l?.acct||''], ['dealer','Dealer name',()=>S.settings.dealer],['dealer_address','Dealer address',()=>S.settings.address],['dealer_phone','Dealer phone',()=>S.settings.phone],['dealer_license','Dealer license #',()=>S.settings.dealerLicense||''],['salesperson','Salesperson',x=>uname(x.d.salespersonId)],['today','Today\'s date',()=>fdate(TODAY)]]; const mval=(k,x)=>{const m=MERGE.find(f=>f[0]===k);try{return m?String(m[2](x)??''):'{{'+k+'}}'}catch(e){return''}}; function renderCustomText(cf,x){const fill=t=>esc(t).replace(/\{\{(\w+)\}\}/g,(m,k)=>`${esc(mval(k,x))}`).replace(/\*\*(.+?)\*\*/g,'$1').replace(/\[ \]/g,'☐').replace(/\[x\]/gi,'☒'); const blocks=String(cf.body||'').split(/\n\s*\n/);let out=F.hdr(esc(cf.name),0,cf.sub?esc(cf.sub):`Deal #${x.d.no}`); blocks.forEach(b=>{const lines=b.split('\n');let para=[];const flush=()=>{if(para.length)out+=`

${para.join('
')}

`;para=[]}; lines.forEach(l=>{const t=l.trim();if(!t)return; if(/^#\s/.test(t)){flush();out+=`

${fill(t.slice(2))}

`} else if(/^\[sig:/i.test(t)){flush();out+=F.sig(...t.replace(/^\[sig:\s*/i,'').replace(/\]$/,'').split(',').map(s=>esc(s.trim())))} else if(/^\[note\]/i.test(t)){flush();out+=F.note(fill(t.replace(/^\[note\]\s*/i,'')))} else if(t.includes(' | ')||/^\w[^:]*:\s*\{\{/.test(t)&&/\{\{/.test(t)&&t.split('|').length>1){flush();out+=F.grid([t.split(' | ').map(c=>{const i=c.indexOf(':');return i>0?[esc(c.slice(0,i).trim()),c.slice(i+1).trim().replace(/\{\{(\w+)\}\}/g,(m,k)=>mval(k,x))]:['',c]})])} else if(/^[-•]\s/.test(t)){flush();out+=`
• ${fill(t.slice(2))}
`} else para.push(fill(t))});flush()}); return out} function renderOverlay(cf,x){const src=cf.bgData||(cf.bg?photoURL(cf.bg):'');return `
${(cf.fields||[]).map(f=>`${esc(f.key==='__text'?f.text:mval(f.key,x))}`).join('')}
`} function syncCustomForms(){for(let i=FORMS.length-1;i>=0;i--)if(FORMS[i].custom)FORMS.splice(i,1);(S.customForms||[]).forEach(cf=>FORMS.push({id:'cf_'+cf.id,g:'Custom forms',n:cf.name,need:cf.need||'deal',custom:1,overlay:cf.kind==='overlay',f:x=>cf.kind==='overlay'?renderOverlay(cf,x):renderCustomText(cf,x)}))} const CF_SAMPLE=`# Vehicle condition acknowledgment I, {{buyer_name}}, have inspected the {{year}} {{make}} {{model}} (VIN {{vin}}, stock {{stock}}) and accept it in its present condition. Odometer: {{miles}} | Sale date: {{sale_date}} | Sale price: {{sale_price}} # Items noted at delivery [ ] Spare tire and jack present [ ] Two keys provided [ ] Owner's manual provided [note] Add your own wording here. Use {{field}} to fill in deal details, "Label: {{field}} | Label: {{field}}" for a row of boxes, # for a section, and [sig: Buyer, Dealer] for signature lines. [sig: Buyer, Co-buyer, Dealer representative]`; function customFormsView(){const cfs=S.customForms||[];return `
Make your own forms that fill in from each deal, or upload a form you already use and place the fields on it. Custom forms show up in Print forms and can be added to print packs.
${cfs.map(cf=>`

${cf.kind==='overlay'?'🖼':'📝'} ${esc(cf.name)}

${cf.kind==='overlay'?`Uploaded form · ${(cf.fields||[]).length} fields placed`:'Text template'} · ${({deal:'All deals',fin:'Financed deals',bhph:'BHPH deals'})[cf.need||'deal']} · updated ${fdate(cf.updated)}
`).join('')||'
No custom forms yet
'}
`} function mergePicker(target){return ``} function insertAtCursor(id,t){const el=$('#'+id);const s=el.selectionStart??el.value.length;el.value=el.value.slice(0,s)+t+el.value.slice(el.selectionEnd??s);el.focus();el.selectionStart=el.selectionEnd=s+t.length;el.dispatchEvent(new Event('input'))} function previewCtx(){const d=S.deals.find(x=>x.id===ui.formDeal)||S.deals[0];return d?{d,l:d.loanId?loan(d.loanId):null,v:veh(d.vehicleId),c:cust(d.customerId)}:null} function cfModal(id){S.customForms=S.customForms||[];const cf=id?S.customForms.find(x=>x.id===id):{name:'',kind:'text',need:'deal',sub:'',body:CF_SAMPLE}; openModal(mh(id?'Edit custom form':'Create a custom form')+`
${mergePicker('cfbody')}${aiOn('listing')||aiOn('doccheck')?aiBtn('Draft with AI','cfAI()','cfaib'):''}
Format: # Section · {{field}} · Label: {{field}} | Label: {{field}} (row of boxes) · [ ] checkbox · **bold** · - bullet · [note] text · [sig: Buyer, Dealer]
Live preview with ${previewCtx()?'deal #'+previewCtx().d.no:'sample data'}
`,true); const f=$('#cff2');const pv=()=>{const x=previewCtx();if(!x){$('#cfpv').innerHTML='
Create a deal to preview
';return}const y=fd(f);$('#cfpv').innerHTML=`
${renderCustomText({name:y.name||'Untitled form',sub:y.sub,body:y.body},x)}
`};f.oninput=pv;pv(); f.onsubmit=e=>{e.preventDefault();const x=fd(f);const n=id?cf:{id:uid(),kind:'text'};Object.assign(n,{name:x.name,need:x.need,sub:x.sub,body:x.body,updated:TODAY});if(!id)S.customForms.push(n);syncCustomForms();save();closeModal();render();toast('Form saved')}} async function cfAI(){const want=await new Promise(res=>{const d=document.createElement('div');d.className='aiask';d.innerHTML=`
✦ Describe the form you need
`;$('#cfbody').before(d);const [go,no]=d.querySelectorAll('button');go.onclick=()=>{const v=d.querySelector('textarea').value;d.remove();res(v)};no.onclick=()=>{d.remove();res('')};d.querySelector('textarea').focus()}); if(!want.trim())return;const b=$('#cfaib');b.disabled=true;b.textContent='✦ Drafting…'; try{const t=await ai(`Draft a dealership form for a used-car dealer in this exact plain-text template format: - "# Heading" for sections - {{field}} merge fields, using ONLY these keys: ${MERGE.map(m=>m[0]).join(', ')} - "Label: {{field}} | Label: {{field}}" lines for a row of boxed fields - "[ ]" for checkboxes, "- " for bullets, "**bold**" - "[note] text" for a small notice - "[sig: Buyer, Dealer representative]" for signature lines (end with one) Write clear plain-English wording. Do not claim it satisfies any specific law; add a [note] that the dealer should have counsel review it. The form: ${want} Reply with only the template text.`,{text:true,nocache:true});$('#cfbody').value=t.replace(/^```\w*\n?|```$/g,'').trim();$('#cfbody').dispatchEvent(new Event('input'));if(!$('#cff2').name.value)$('#cff2').name.value=want.slice(0,60)}catch(e){toast(aiErrMsg(e))}b.disabled=false;b.textContent='✦ Draft with AI'} function overlayModal(id){S.customForms=S.customForms||[];const cf=id?JSON.parse(JSON.stringify(S.customForms.find(x=>x.id===id))):{name:'',kind:'overlay',need:'deal',fields:[],bg:null};let cur='buyer_name',size=11; openModal(mh(id?'Edit uploaded form':'Upload your own form')+`
Place:Pick a field, then click on the form where it goes. Drag placed fields to adjust.
${cf.bg?'':'
Upload an image of your form (PDFs: take a screenshot or export the page as an image)
'}
`,true); const draw=()=>{const w=$('#ovwrap');if(!cf.bg)return;const x=previewCtx();w.innerHTML=`${cf.fields.map((f,i)=>`${esc(f.key==='__text'?f.text:(x?mval(f.key,x):'{{'+f.key+'}}')||'{{'+f.key+'}}')}`).join('')}`; $('#ovlist').innerHTML=cf.fields.map((f,i)=>`${esc(f.key==='__text'?'“'+f.text+'”':MERGE.find(m=>m[0]===f.key)?.[1]||f.key)} ✕`).join(' '); $('#ovimg').onclick=e=>{const r=e.target.getBoundingClientRect();const k=$('#ovkey').value;let text='';if(k==='__text'){text=prompt?'':'';const t=window.__ovtext||'';} const add=t=>{cf.fields.push({key:k,text:t,x:+((e.clientX-r.left)/r.width*100).toFixed(2),y:+((e.clientY-r.top)/r.height*100-1).toFixed(2),size:+$('#ovsize').value||11});draw()}; if(k==='__text'){const tx=$('#ovtxt');if(!tx){const i=document.createElement('input');i.id='ovtxt';i.placeholder='Type the fixed text, then click the form again';i.style.cssText='margin-left:8px;padding:6px;border:1.5px solid var(--line);border-radius:8px';$('#ovkey').after(i);i.focus();return}if(!tx.value.trim())return toast('Type the text first');add(tx.value.trim())}else add('')}; w.querySelectorAll('.ovf').forEach(el=>{el.onmousedown=ev=>{ev.preventDefault();const i=+el.dataset.i,r=$('#ovimg').getBoundingClientRect();const mv=m=>{cf.fields[i].x=+((m.clientX-r.left)/r.width*100).toFixed(2);cf.fields[i].y=+((m.clientY-r.top)/r.height*100-1).toFixed(2);el.style.left=cf.fields[i].x+'%';el.style.top=cf.fields[i].y+'%'};const up=()=>{document.removeEventListener('mousemove',mv);document.removeEventListener('mouseup',up)};document.addEventListener('mousemove',mv);document.addEventListener('mouseup',up)}})}; window.ovDel=i=>{cf.fields.splice(i,1);draw()};draw(); $('#ovfile').onchange=async e=>{const f=e.target.files[0];if(!f)return;try{const b=await shrink(f,2200,0.9);if(ASSETS){const r=await ASSETS.upload(b,{type:'image/jpeg'});cf.bg={id:r.id,src:'a'}}else{const pid=uid();await idbOp('readwrite',s=>s.put(b,pid));IDBURL[pid]=URL.createObjectURL(b);cf.bg={id:pid,src:'i'}}if(!$('#ovn').value)$('#ovn').value=f.name.replace(/\.\w+$/,'');draw()}catch(err){toast('Could not read that image')}}; $('#ovsave').onclick=()=>{if(!cf.bg)return toast('Upload the form image first');if(!$('#ovn').value.trim())return toast('Name the form');cf.name=$('#ovn').value.trim();cf.need=$('#ovneed').value;cf.updated=TODAY;if(id){const i=S.customForms.findIndex(x=>x.id===id);S.customForms[i]=cf}else{cf.id=uid();S.customForms.push(cf)}syncCustomForms();save();closeModal();render();toast('Form saved')}} /* ================= E-signatures ================= */ const sigRole=l=>{l=String(l).toLowerCase();if(/co-?buyer|co-?owner|co-?applicant/.test(l))return'cobuyer';if(/buyer|transferee|grantor|customer|applicant/.test(l))return'buyer';if(/dealer|seller|transferor|manager|salesperson|authorized|received by/.test(l))return'dealer';return''}; let CURSIGS=null; async function sha256(t){try{const b=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(t));return [...new Uint8Array(b)].map(x=>x.toString(16).padStart(2,'0')).join('')}catch(e){return''}} const ENV_ST=['Draft','Sent','Viewed','Partially signed','Completed','Declined','Voided']; const envPill=s=>`${s}`; function envForms(env){syncCustomForms();const d=S.deals.find(x=>x.id===env.dealId);const x={d,l:d.loanId?loan(d.loanId):null,v:veh(d.vehicleId),c:cust(d.customerId)};return{x,forms:env.forms.map(FBYID).filter(f=>f&&formOk(f,x))}} function envDocHTML(env,withSigs){const {x,forms}=envForms(env);CURSIGS=withSigs?Object.fromEntries(env.signers.filter(s=>s.sig).map(s=>[s.role,{img:s.sig,at:s.signedAt}])):null;const h=forms.map(f=>fpage(f,x)).join('');CURSIGS=null;return h} function esignStart(dealId){syncCustomForms();const d=S.deals.find(x=>x.id===dealId),c=cust(d.customerId);const x={d,l:d.loanId?loan(d.loanId):null,v:veh(d.vehicleId),c};const pk=defaultPack(x);const ids=pk?pk.items.map(i=>i.id):PACKS[d.type]; openModal(mh(`Send deal #${d.no} for signature`)+`
Signers
Documents
${FORMS.filter(f=>formOk(f,x)).map(f=>``).join('')}
`,true); const f=$('#esf');f.pack.onchange=()=>{const p=S.packs.find(z=>z.id===f.pack.value);if(!p)return;f.querySelectorAll('[name^="f_"]').forEach(cb=>cb.checked=p.items.some(i=>'f_'+i.id===cb.name))}; f.onsubmit=e=>{e.preventDefault();const y=fd(f);const forms=FORMS.filter(fm=>y['f_'+fm.id]).map(fm=>fm.id);if(!forms.length)return toast('Pick at least one document'); const signers=[{role:'buyer',label:'Buyer',name:y.b_name,email:y.b_email,phone:y.b_phone,status:'Pending'}];if(y.co&&y.co_name)signers.push({role:'cobuyer',label:'Co-buyer',name:y.co_name,email:y.co_email,phone:y.co_phone,status:'Pending'});signers.push({role:'dealer',label:'Dealer',name:y.d_name,status:'Pending'}); const env={id:uid(),dealId,provider:y.provider,forms,signers,msg:y.msg,status:'Draft',created:nowAt(),by:S.settings.user,events:[{at:nowAt(),by:S.settings.user,text:'Signing packet created ('+forms.length+' documents)'}]};S.envelopes=S.envelopes||[];S.envelopes.push(env);save();closeModal(); if(y.provider==='inperson')signSession(env.id);else if(y.provider==='esignauto')esaLive(env.id);else esaSend(env.id)}} function signSession(envId){const env=S.envelopes.find(x=>x.id===envId);const next=env.signers.find(s=>s.status!=='Signed');if(!next){finishEnv(env);return} const doc=envDocHTML(env,true); openModal(mh(`Signing: ${esc(next.label)} – ${esc(next.name)}`)+`
${doc}
✕ Sign here
Sign with a finger, stylus or mouse. Your signature will be placed on every signature line for ${esc(next.label.toLowerCase())}.
`,true); const cv=$('#pad'),cx=cv.getContext('2d');cx.lineWidth=3.2;cx.lineCap='round';cx.lineJoin='round';cx.strokeStyle='#0b1f5c';let drawing=false,inked=false; const pt=e=>{const r=cv.getBoundingClientRect(),t=e.touches?e.touches[0]:e;return[(t.clientX-r.left)*cv.width/r.width,(t.clientY-r.top)*cv.height/r.height]}; const st=e=>{e.preventDefault();drawing=true;const [a,b]=pt(e);cx.beginPath();cx.moveTo(a,b)},mv=e=>{if(!drawing)return;e.preventDefault();const [a,b]=pt(e);cx.lineTo(a,b);cx.stroke();inked=true},en=()=>drawing=false; cv.addEventListener('pointerdown',st);cv.addEventListener('pointermove',mv);window.addEventListener('pointerup',en);cv.style.touchAction='none'; $('#pclr').onclick=()=>{cx.clearRect(0,0,cv.width,cv.height);inked=false}; $('#sgdecl').onclick=()=>confirmBox(`Record that ${esc(next.name)} declined to sign?`,()=>{env.status='Declined';env.events.push({at:nowAt(),by:S.settings.user,text:`${next.label} ${next.name} declined to sign`});save();render()}); $('#sgok').onclick=async()=>{if(!$('#sgc').checked)return toast('The signer must agree to sign electronically');if(!inked)return toast('Please sign in the box'); const img=cv.toDataURL('image/png');next.sig=img;next.status='Signed';next.signedAt=nowAt();next.consent=true;next.device=navigator.userAgent.slice(0,120);next.docHash=await sha256(doc); env.events.push({at:next.signedAt,by:next.name,text:`${next.label} agreed to e-sign and signed ${env.forms.length} documents in person (witness: ${S.settings.user}). Document fingerprint ${next.docHash.slice(0,16)}…`});env.status=env.signers.every(s=>s.status==='Signed')?'Completed':'Partially signed';save(); if(env.status==='Completed')finishEnv(env);else{toast(next.label+' signed');signSession(env.id)}}} async function finishEnv(env){env.status='Completed';env.completed=env.completed||nowAt();env.finalHash=await sha256(envDocHTML(env,true));env.events.push({at:nowAt(),by:'DealerPen',text:'All parties signed. Packet completed, fingerprint '+env.finalHash.slice(0,16)+'…'});const d=S.deals.find(x=>x.id===env.dealId);dealTitle(d);if(d.title.status==='Not started')d.title.status='Docs signed';save();render();envView(env.id);toast('All signatures collected 🎉')} function certHTML(env){const d=S.deals.find(x=>x.id===env.dealId);return `
${F.hdr('Signature Certificate',0,'Deal #'+d.no)}${F.grid([[['Packet ID',env.id,2],['Created',env.created.replace('T',' ')],['Completed',(env.completed||'').replace('T',' ')]],[['Method',env.provider==='inperson'?'In-person electronic signature':'eSignAutos',2],['Documents',env.forms.length],['Final fingerprint (SHA-256)',(env.finalHash||'').slice(0,24)+'…']]])}

Signers

${env.signers.map(s=>``).join('')}
RoleNameSignedConsentSignature
${esc(s.label)}${esc(s.name)}${esc((s.signedAt||s.status).replace('T',' '))}${s.consent?'Agreed':''}${s.sig?``:''}

Audit trail

${env.events.map(e=>``).join('')}
WhenByEvent
${esc(e.at.replace('T',' '))}${esc(e.by)}${esc(e.text)}
${F.note('Signatures were captured electronically with each signer\'s consent. The fingerprint is a SHA-256 hash of the signed documents and changes if the documents are altered. Some documents (for example certain title or odometer forms, or lender contracts) may require a wet signature or an approved e-contracting platform. Check your state and lender rules.')}
`} async function envDownload(envId){const env=S.envelopes.find(x=>x.id===envId);const d=S.deals.find(x=>x.id===env.dealId);let body=envDocHTML(env,true)+certHTML(env); const doc=`Signed packet – deal ${d.no}
${env.status==='Completed'?'Signed packet':'Unsigned packet'} · Deal #${d.no}
${await inlineImgs(body)}
`; if(DL){try{await DL.save({filename:`deal-${d.no}-${env.status==='Completed'?'signed':'for-signature'}.html`,data:doc});toast('Saved')}catch(e){if(e.code!=='declined')copyText(doc)}}else copyText(doc);return doc} async function inlineImgs(h){const ids=[...new Set([...h.matchAll(/src="\/_blob\/([\w-]+)"/g)].map(m=>m[1]))];for(const id of ids){const u=await photoDataURL({id,src:'a'},2200);if(u)h=h.split('/_blob/'+id).join(u)}return h} function esaSend(envId){const env=S.envelopes.find(x=>x.id===envId);const d=S.deals.find(x=>x.id===env.dealId); openModal(mh(`Send through E-Sign Auto by hand · deal #${d.no}`)+`
This sends the packet by hand. For live sending (upload, signing links and the signed PDF coming back automatically), choose “E-Sign Auto (live)” when DealerPen is connected to its server.
  1. Download the packet, open it and use Print → Save as PDF.
  2. Open E-Sign Auto and create a new signing request with the PDF.
  3. Add these signers in this order:${env.signers.map(s=>``).join('')}
    ${esc(s.label)}${esc(s.name)}${esc(s.email||'')}${esc(s.phone||'')}
  4. Mark it sent here, then update the status as signers finish. Upload or link the signed PDF when it's complete.
`,true)} function envView(envId){const env=S.envelopes.find(x=>x.id===envId);const d=S.deals.find(x=>x.id===env.dealId); openModal(mh(`Signing packet · deal #${d.no} · ${esc(cust(d.customerId)?.name)}`)+`
Status${envPill(env.status)}
Method${env.provider==='inperson'?'In store':env.provider==='esignauto'?'E-Sign Auto':'E-Sign Auto (by hand)'}
Documents${env.forms.length}
Created${ftime(env.created)}
${env.signers.map((s,i)=>``).join('')}
SignerNameStatusSigned
${esc(s.label)}${esc(s.name)}
${esc(s.email||'')} ${esc(s.phone||'')}
${s.status==='Signed'?'Signed':'Pending'}${s.sig?``:s.signedAt?ftime(s.signedAt):''}${env.provider==='esignautos'&&s.status!=='Signed'&&!['Voided','Declined'].includes(env.status)?``:''}
${env.signedUrl?`

Signed document: open ↗

`:''}

Audit trail

${env.events.slice().reverse().map(e=>`
${esc(e.text)}
${ftime(e.at)} · ${esc(e.by)}
`).join('')}
${!['Completed','Voided'].includes(env.status)?``:''}${env.provider==='esignautos'?``:''}${env.provider==='inperson'&&!['Completed','Voided','Declined'].includes(env.status)?``:''}${env.provider==='esignautos'&&env.status==='Draft'?``:''}${env.esaId?`${env.status!=='Completed'&&env.signers.some(z=>z.signingUrl)?``:''}${env.status==='Draft'?``:''}${env.signedAsset?`📄 Signed PDF`:''}`:``}
`,true); const lb=[...document.querySelectorAll('#modal .mf .btn')].find(b=>b.textContent==='Signed PDF link');if(lb)lb.onclick=()=>{const box=document.createElement('div');box.innerHTML=`
`;$('#modal .mb').appendChild(box);box.querySelector('button').onclick=()=>{const v=$('#sgurl').value.trim();if(v&&!/^https:\/\//.test(v))return toast('Link must start with https://');env.signedUrl=v;env.events.push({at:nowAt(),by:S.settings.user,text:'Signed document link saved'});save();envView(env.id)}}} function esignView(){const es=(S.envelopes||[]).slice().sort((a,b)=>b.created.localeCompare(a.created));return `
${kpi('Out for signature',es.filter(e=>['Sent','Viewed','Partially signed','Draft'].includes(e.status)).length,'')}${kpi('Completed',es.filter(e=>e.status==='Completed').length,'')}${kpi('Declined / voided',es.filter(e=>['Declined','Voided'].includes(e.status)).length,'')}

✍ E-Sign Auto${ui.esaHealth?.ok?(ui.esaHealth.mock?'Connected – test mode':'Connected'):'Server not reachable from here'}

${ui.esaHealth?.ok?'Packets upload as a PDF, signers get private links in order, DealerPen checks progress, and the completed PDF with the audit certificate is saved to the deal.':'Live E-Sign Auto runs through the DealerPen server. Open DealerPen from your server (or set its address in Settings → E-Sign Auto) to send live. Manual sending and in-store signing still work.'}
${(S.envelopes||[]).some(e=>e.esaId&&e.status!=='Completed')?``:''}
${es.map(e=>{const d=S.deals.find(x=>x.id===e.dealId);return ``}).join('')||''}
CreatedDealCustomerMethodSignersStatus
${ftime(e.created)}#${d?.no}${esc(cust(d?.customerId)?.name)}${e.provider==='inperson'?'In store':e.provider==='esignauto'?'E-Sign Auto':'E-Sign Auto (by hand)'}${e.signers.filter(s=>s.status==='Signed').length}/${e.signers.length}${envPill(e.status)}
No signing packets yet. Open a deal and click ✍ E-sign
`} /* ================= Server features: sync, leads, payments, phone, video ================= */ let SRV=null; async function srvFeatures(force){if(!force&&SRV&&Date.now()-SRV.at<60000)return SRV;const r=await esaFetch2('/api/features');SRV=r.ok?{...r.body,at:Date.now(),ok:true}:{ok:false,at:Date.now()};return SRV} async function srvPost(path,body,raw){const h=srvHeaders();if(!raw)h['Content-Type']='application/json';try{const r=await fetch((ESA().server||'').replace(/\/$/,'')+path,{method:'POST',headers:raw?{...h,'Content-Type':raw}:h,body:raw?body:JSON.stringify(body)});const b=await r.json().catch(()=>({}));return{ok:r.ok,status:r.status,body:b}}catch(e){return{ok:false,status:0,body:{error:'DealerPen server not reachable from here'}}}} const custByPhone=p=>{const d=digits(p);return d?S.customers.find(c=>digits(c.phone)===d):null}; function routeOwner(source){const R=S.settings.routing||{};const reps=S.users.filter(u=>u.active&&(R.reps||[]).includes(u.id));const bySrc=(R.bySource||{})[source];if(bySrc&&S.users.some(u=>u.id===bySrc&&u.active))return bySrc;if(!reps.length)return '';R.rr=((R.rr||0)+1)%reps.length;S.settings.routing=R;return reps[R.rr].id} function intakeLead(L,via){const ph=L.phone,em=String(L.email||'').toLowerCase();let c=(ph&&custByPhone(ph))||(em&&S.customers.find(x=>String(x.email||'').toLowerCase()===em));const isNew=!c; if(!c){c={id:uid(),created:TODAY,createdAt:nowAt(),name:L.name||'Unknown lead',phone:L.phone||'',email:L.email||'',address:'',source:L.source||'Website',stage:'New',employer:'',income:0,interest:L.vehicle||'',followUp:TODAY,smsConsent:!!L.consent,optOut:false,dnc:false,notes:[],ownerId:routeOwner(L.source||'Website')};S.customers.push(c)} else if(['Sold','Lost'].includes(c.stage)&&c.stage==='Lost')c.stage='New'; c.notes.push({date:TODAY,by:via||'Lead intake',text:`${isNew?'New':'Repeat'} lead from ${L.source||'unknown'}${L.format?' ('+L.format+')':''}${L.vehicle?' · '+L.vehicle:''}${L.vin?' · VIN '+L.vin:''}${L.type?' · '+L.type:''}`}); if(L.message)logComm({customerId:c.id,channel:'text',dir:'in',body:`[${L.source||'Lead'}] ${L.message}`.slice(0,1500),by:''}); if(L.type&&/online deal/i.test(L.type)&&L.extra)addOnlineDeal(c,L.extra); if(isNew&&(S.settings.planAuto??true)){if(!c.leadType&&typeof leadTypeOf==='function')c.leadType=leadTypeOf(L.source,L.type);const pp=typeof pickPlan==='function'?pickPlan(c,L):(S.plans||[])[0];if(pp)enrollPlan(c.id,pp.id,true)} return c} async function srvSync(show){const f=await srvFeatures();if(!f.ok)return show&&toast('DealerPen server not reachable from here'); const r=await (async()=>{const h=srvHeaders();try{const x=DBM.on?await fetch(srvURL('/api/sync/claim'),{method:'POST',headers:{...h,'Content-Type':'application/json'},body:'{}'}):await fetch((ESA().server||'').replace(/\/$/,'')+'/api/sync?since='+(S.settings.syncSeq||0),{headers:h});return x.ok?await x.json():null}catch(e){return null}})();if(!r)return;let n=0; for(const e of r.events){const d=e.data||{}; if(e.type==='lead'){intakeLead({...d,source:d.source,format:d.format},'Lead intake');n++} else if(e.type==='payment'){const l=S.loans.find(x=>x.id===d.loanId)||S.loans.find(x=>x.acct===d.acct);if(l&&!l.payments.some(p=>(p.memo||'').includes(d.ref))&&l.status==='Active'){const p=postPayment(l,+d.amount,e.at.slice(0,10),d.method||'Online (card)','Online payment '+d.ref);n++;l.notes.push({date:TODAY,by:'Payments portal',text:`Customer paid ${$$(d.amount)} online (receipt #${p.receipt})`})}} else if(e.type==='sms_in'&&!custByPhone(d.from)&&typeof SG==='function'&&SG('comms.newFromSms',true)===false){toast('Text from an unknown number: '+d.from)} else if(e.type==='sms_in'){let c=custByPhone(d.from);if(!c)c=intakeLead({name:'Text from '+d.from,phone:d.from,source:'Text',message:''},'Texting');logComm({customerId:c.id,channel:'text',dir:'in',body:d.body+(d.media?` [${d.media} photo(s)]`:''),sid:d.sid});n++} else if(e.type==='call'){const num=d.dir==='in'?d.from:d.to;let c=d.customerId&&cust(d.customerId)||custByPhone(num);if(!c&&d.dir==='in'&&(typeof SG!=='function'||SG('comms.newFromCall',true)!==false))c=intakeLead({name:'Caller '+num,phone:num,source:'Phone'},'Phone'); if(c&&!S.comms.some(x=>x.cid===d.cid)){logComm({customerId:c.id,loanId:d.loanId||null,channel:'call',dir:d.dir||'out',body:d.dir==='in'?'Inbound call':'Call through DealerPen',outcome:d.status==='completed'||d.status==='answered'?'Answered':d.status==='no-answer'?'No answer':d.status==='busy'?'Busy':(d.status||''),duration:+d.duration||0,cid:d.cid,by:d.user||''});n++}} else if(e.type==='email_unsub'){const c=d.customerId&&cust(d.customerId)||S.customers.find(x=>String(x.email||'').toLowerCase()===d.email);if(c&&!c.emailOptOut){c.emailOptOut=true;c.notes.push({date:TODAY,by:'Email',text:'Unsubscribed from marketing emails'});n++}} else if(e.type==='recording'){const cm=S.comms.find(x=>x.cid===d.cid);if(cm){cm.rec=d.recordingSid;cm.recDur=d.duration}} else if(e.type==='video_view'){const c=cust(d.customerId);if(c){c.notes.push({date:TODAY,by:'Video',text:`👀 Watched the walkaround video: ${d.vehicle||''}`});if(isLead(c)){c.next={type:'Call',date:TODAY,time:'',note:'They just watched your video. Call now',by:'System',at:nowAt()};c.followUp=TODAY}n++}} try{if(typeof engageEvent==='function'&&engageEvent(e))n++}catch(er){} if(e.type==='import_file'&&d.b64){try{const by=Uint8Array.from(atob(d.b64),ch=>ch.charCodeAt(0));impAuto(d.name||'import.csv',by,d.source||'').then(r=>{toast(r.ok?`Automatic import: ${d.name} (${r.res.added} added, ${r.res.updated} updated)`:r.why);render()})}catch(er){}} S.settings.syncSeq=Math.max(S.settings.syncSeq||0,e.seq)} if(r.events.length){save();if(n){toast(`${n} update(s) from the DealerPen server`);render()}}else if(show)toast('Up to date')} async function serverCall(cid,lid){const c=cust(cid),u=me();if(!u.phone){toast('Add your mobile number to your user profile first (Settings → Users)');return} const r=await srvPost('/api/phone/call',{repPhone:u.phone,to:c.phone,customerId:cid,loanId:lid||null,user:u.name});if(!r.ok)return toast(r.body.error||'Call failed');closeModal();toast(r.body.message||'Calling your phone…');setTimeout(()=>srvSync(),20000)} async function serverText(cid,lid,body){const c=cust(cid);const b=canText(c);if(b)return toast(b);const r=await srvPost('/api/phone/sms',{to:c.phone,body});if(!r.ok){toast(r.body.error||'Text failed');return false} logComm({customerId:cid,loanId:lid,channel:'text',dir:'out',body,sid:r.body.sid});save();return true} async function playRec(id,btn){const h=srvHeaders();try{const r=await fetch((ESA().server||'').replace(/\/$/,'')+'/api/phone/recording-link/'+id,{headers:h});const j=await r.json();const a=document.createElement('audio');a.controls=true;a.autoplay=true;a.src=(ESA().server||'').replace(/\/$/,'')+j.url;a.style.cssText='display:block;margin-top:6px;width:260px';btn.replaceWith(a)}catch(e){toast('Recording unavailable')}} async function payLink(lid){const l=loan(lid),c=cust(l.customerId);const f=await srvFeatures();if(!f.ok||!f.payments?.ready)return toast(f.ok?'Payments aren\'t set up on the server yet (Stripe)':'DealerPen server not reachable from here'); const r=await srvPost('/api/pay/link',{loanId:l.id,acct:l.acct,first:c.name.split(' ')[0],vehicle:vname(veh(l.vehicleId)),payment:l.payment,pastDue:pastDue(l)+l.lateFeesDue,suggested:Math.max(l.payment,pastDue(l)+l.lateFeesDue),nextDue:fdate(nextDue(l)),dealer:S.settings.dealer,phone:S.settings.phone}); if(!r.ok)return toast(r.body.error||'Could not create the link');l.payUrl=r.body.url;save(); textModal(c.id,l.id,null,`Hi ${c.name.split(' ')[0]}, you can make your ${S.settings.dealer} payment online anytime here: ${r.body.url}${f.payments.test?' (TEST)':''}`)} async function sendVideo(cid,vid){const f=await srvFeatures();if(!f.ok||!f.video?.ready)return toast(f.ok?'Set PUBLIC_URL on the server to share video links':'Video links need the DealerPen server'); const inp=document.createElement('input');inp.type='file';inp.accept='video/mp4,video/quicktime,video/webm';inp.setAttribute('capture','environment'); inp.onchange=async()=>{const file=inp.files[0];if(!file)return;if(file.size>150*1024*1024)return toast('Video is over 150 MB. Record a shorter one');const c=cust(cid),v=vid?veh(vid):null;toast('Uploading video…'); const type=file.type||'video/mp4';const title=v?`${vname(v)} walkaround`:'Video for you';const q=`?title=${encodeURIComponent(title)}&from=${encodeURIComponent((me()?.name||'')+' · '+S.settings.dealer)}&phone=${encodeURIComponent(S.settings.phone)}&customerId=${cid}`; const r=await srvPost('/api/videos'+q,file,type);if(!r.ok)return toast(r.body.error||'Upload failed');if(v){v.videos=v.videos||[];v.videos.push({url:r.body.url,at:nowAt(),by:me()?.name})}save(); textModal(cid,null,null,`Hi ${c.name.split(' ')[0]}, I made a quick video of the ${v?vname(v):'vehicle'} for you: ${r.body.url} Any questions, just reply! - ${(me()?.name||'').split(' ')[0]}, ${S.settings.dealer}`)};inp.click()} /* ---- local lead parsing (paste a lead email / ADF) ---- */ function parseLeadText(t){if(/((s.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`,'i'))||[])[1]||'').replace(//g,'').trim();const cu=(t.match(//i)||[''])[0],ve=(t.match(//i)||[''])[0]; const nm=k=>((cu.match(new RegExp(`]*part="${k}"[^>]*>([\\s\\S]*?)<\\/name>`,'i'))||[])[1]||'').trim();return{name:(nm('full')||`${nm('first')} ${nm('last')}`).trim(),email:g(cu,'email'),phone:g(cu,'phone'),message:g(cu,'comments'),vehicle:[g(ve,'year'),g(ve,'make'),g(ve,'model'),g(ve,'trim')].filter(Boolean).join(' '),vin:g(ve,'vin'),source:g((t.match(//i)||[''])[0],'name')||'Lead provider',format:'ADF'}} const email=(t.match(/[\w.+-]+@[\w-]+\.[\w.-]+/)||[''])[0],phone=(t.match(/(\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/)||[''])[0];const fld=k=>((t.match(new RegExp(`(?:^|\\n)\\s*(?:${k})\\s*[:\\-]\\s*(.+)`,'i'))||[])[1]||'').trim(); return{name:fld('name|customer|from'),email,phone,vehicle:fld('vehicle|interested in|car'),message:t.slice(0,1500),source:fld('source|provider')||'Email lead',format:'text'}} function pasteLeadModal(){openModal(mh('Add a lead from an email or lead provider')+`

Paste the lead email or the lead provider's ADF/XML. DealerPen reads the name, phone, email and vehicle, assigns a rep and starts the follow-up plan.

`,true); const pv=()=>{const L=parseLeadText($('#plt').value);$('#plp').innerHTML=`${[['Name',L.name],['Phone',L.phone],['Email',L.email],['Vehicle',L.vehicle],['Source',L.source],['Format',L.format]].map(r=>``).join('')}
${r[0]}${esc(r[1]||'—')}
`;return L};$('#plprev').onclick=pv; $('#plgo').onclick=()=>{const L=pv();if(!L.name&&!L.phone&&!L.email)return toast('Couldn\'t find a name, phone or email');const c=intakeLead(L,S.settings.user);save();closeModal();render();toast('Lead added'+(c.ownerId?' and assigned to '+uname(c.ownerId):''))}} /* ---- follow-up plans ---- */ const DEFAULT_PLAN={id:'plan_internet',name:'New internet lead',steps:[ {day:0,min:5,type:'Text',auto:true,label:'Instant thank-you text',body:'Hi {first}, thanks for your interest in the {interest} at {dealer}! I\'m {user}. When is a good time to chat or come see it? Reply STOP to opt out.'}, {day:0,min:10,type:'Call',label:'First call'}, {day:1,type:'Call',label:'Day 1 call + walkaround video'}, {day:2,type:'Text',auto:true,label:'Similar cars text',body:'Hi {first}, in case the {interest} isn\'t quite right, we have a few similar options. Want me to send a couple over? - {user}, {dealer}'}, {day:4,type:'Email',label:'Manager check-in'}, {day:7,type:'Call',label:'Final call + text'}, {day:30,type:'Text',auto:false,label:'Monthly check-in',body:'Hi {first}, {user} from {dealer} checking in. Still looking for a vehicle? New arrivals every week.'}]}; const planOf=id=>(S.plans||[]).find(p=>p.id===id); function enrollPlan(cid,pid,silent){const c=cust(cid),p=planOf(pid);if(!c||!p)return;c.plan={id:p.id,start:new Date().toISOString(),done:[],status:'Active'};c.notes.push({date:TODAY,by:S.settings.user,text:`Started follow-up plan: ${p.name}`});save();if(!silent){render();toast('Follow-up plan started')}} function stepDue(c,s){return new Date(new Date(c.plan.start).getTime()+((s.day||0)*86400+(s.min||0)*60)*1000)} let planBusy=false; async function planTick(){if(planBusy)return;planBusy=true;try{const f=SRV&&SRV.ok&&SRV.phone?.ready;const now=new Date();let changed=false; for(const c of S.customers){const pl=c.plan;if(!pl||pl.status!=='Active')continue;const p=planOf(pl.id);if(!p){pl.status='Stopped';continue}if(p.byStatus)continue; const replied=S.comms.some(x=>x.customerId===c.id&&x.dir==='in'&&x.at>pl.start.slice(0,16)&&!/^\[(Website|Lead|Cars|CarGurus|Autotrader)/.test(x.body||'')); if(replied||['Appointment','Sold','Lost'].includes(c.stage)||c.optOut){pl.status='Stopped';pl.stopReason=replied?'Customer replied':c.optOut?'Opted out':c.stage;c.notes.push({date:TODAY,by:'Follow-up plan',text:`Plan stopped: ${pl.stopReason}`});changed=true;continue} for(let i=0;inow)break; if(s.type==='Text'&&s.auto&&f&&!canText(c)&&!quietHours()){const ok=await serverText(c.id,null,merge(s.body||'',c));if(ok){pl.done.push(i);changed=true;continue}} if(pl.tasked!==i){pl.tasked=i;c.next={type:s.type==='Email'?'Email':s.type==='Text'?'Text':'Call',date:TODAY,time:'',note:`Plan step: ${s.label}${s.body?' – '+merge(s.body,c):''}`,by:'Follow-up plan',at:nowAt(),planStep:i};c.followUp=TODAY;changed=true} break} if(pl.done.length===p.steps.length){pl.status='Completed';changed=true}} if(changed){save();if(['desk','crm'].includes(route))render()}}finally{planBusy=false}} function planStepDone(cid){const c=cust(cid);if(c&&c.plan&&c.next&&c.next.planStep!=null){c.plan.done.push(c.next.planStep);delete c.plan.tasked}} function plansView(){S.plans=S.plans&&S.plans.length?S.plans:[JSON.parse(JSON.stringify(DEFAULT_PLAN))];const act=S.customers.filter(c=>c.plan&&c.plan.status==='Active'); return `
Every new lead is enrolled automatically${(S.settings.planAuto??true)?'':' (off)'}. Plans stop on their own when the customer replies, books an appointment, buys, is marked lost or opts out. Automatic texts send only through the DealerPen phone server, to customers who agreed to texts, and not between 9pm and 8am.
${S.plans.map(p=>`

🔁 ${esc(p.name)}${S.customers.filter(c=>c.plan&&c.plan.id===p.id&&c.plan.status==='Active').length} active

    ${p.steps.map(s=>`
  1. Day ${s.day}${s.min?' +'+s.min+'m':''} · ${esc(s.type)}${s.auto?' auto':''} · ${esc(s.label)}
  2. `).join('')}
`).join('')}
${act.map(c=>{const p=planOf(c.plan.id);const ni=p?p.steps.findIndex((s,i)=>!c.plan.done.includes(i)):-1;return ``}).join('')||''}
LeadPlanProgressNext stepRep
${esc(c.name)}
${esc(c.source)}
${esc(p?.name||'')}${c.plan.done.length}/${p?.steps.length||0}${ni>=0?`${esc(p.steps[ni].label)}
${ftime(stepDue(c,p.steps[ni]).toISOString())}
`:'—'}
${esc(uname(c.ownerId))}
No leads on a plan right now
`} function planModal(id){const p=id?planOf(id):{id:'plan_'+uid(),name:'',steps:[{day:0,min:5,type:'Text',auto:true,label:'Thank-you text',body:'Hi {first}, thanks for reaching out to {dealer}!'}]};let steps=JSON.parse(JSON.stringify(p.steps)); openModal(mh(id?'Edit follow-up plan':'New follow-up plan')+`

Merge fields: {first} {interest} {dealer} {user} {phone}. "Auto" texts send by themselves through the phone server. Every other step becomes a task for the rep on the day it's due.

${id&&S.plans.length>1?'':''}
`,true); const draw=()=>{$('#pls').innerHTML=steps.map((s,i)=>`
${i+1}Day +min ${s.type==='Text'?``:''}${s.type==='Text'||s.type==='Email'?``:''}
`).join(''); $('#pls').querySelectorAll('[data-k]').forEach(el=>el.onchange=()=>{const s=steps[+el.dataset.i];const k=el.dataset.k;s[k]=el.type==='checkbox'?el.checked:['day','min'].includes(k)?+el.value:el.value;if(k==='type')draw()}); $('#pls').querySelectorAll('[data-x]').forEach(b=>b.onclick=()=>{steps.splice(+b.dataset.x,1);draw()})};draw(); $('#pladd').onclick=()=>{const last=steps[steps.length-1];steps.push({day:(last?.day||0)+1,type:'Call',label:'Follow-up call'});draw()}; if($('#pldel'))$('#pldel').onclick=()=>{S.plans=S.plans.filter(x=>x.id!==id);save();closeModal();render()}; $('#plsave').onclick=()=>{if(!$('#pln').value.trim())return toast('Name the plan');if(!steps.length)return toast('Add a step');steps.sort((a,b)=>a.day*1440+(a.min||0)-(b.day*1440+(b.min||0)));const n=id?p:{...p};n.name=$('#pln').value.trim();n.steps=steps;if(!id)S.plans.push(n);save();closeModal();render();toast('Plan saved')}} function leadIntakeView(){const f=SRV;const recent=S.customers.filter(c=>c.createdAt||c.created>=addDays(TODAY,-14)).sort((a,b)=>(b.createdAt||b.created).localeCompare(a.createdAt||a.created)).slice(0,40); const frt=c=>{const t0=c.createdAt?new Date(c.createdAt):null;if(!t0)return null;const first=S.comms.filter(x=>x.customerId===c.id&&x.dir==='out').sort((a,b)=>a.at.localeCompare(b.at))[0];return first?Math.max(0,Math.round((new Date(first.at)-t0)/60000)):null}; const R=S.settings.routing||{};const ts=recent.map(frt).filter(x=>x!=null);const avg=ts.length?Math.round(ts.reduce((a,b)=>a+b,0)/ts.length):null; return `
${kpi('Leads (14 days)',recent.length,'')}${kpi('Avg first response',avg==null?'—':avg<60?avg+' min':(avg/60).toFixed(1)+' hr','goal: under 5 min')}${kpi('Not answered yet',recent.filter(c=>isLead(c)&&frt(c)==null).length,'')}${kpi('Lead feed',f&&f.ok&&f.leads?.ready?'Live':'Off',f&&f.ok?'DealerPen server':'server not reachable')}

📥 Where leads come from

${f&&f.ok&&f.leads?.ready?`Lead providers, your website and email forwarding post to your server's lead address ${esc(f.leads.inboundUrl||'')} (key in LEADS_INBOUND_KEY). New leads appear here within a minute.`:'Set LEADS_INBOUND_KEY and PUBLIC_URL on the DealerPen server to receive leads automatically. Cars.com, CarGurus, Autotrader and most others can send ADF/XML leads to a web address or email. Until then, paste leads here.'}

🔀 Routing

New leads rotate between these reps. You can also send a source to one person.
${S.users.filter(u=>u.active&&['Salesperson','Sales Manager','Owner'].includes(u.role)).map(u=>``).join('')}
${['Cars.com','CarGurus','Autotrader','Facebook','Website','Phone','Text'].map(src=>``).join('')}
${recent.map(c=>{const t=frt(c);return ``}).join('')||''}
ReceivedLeadSourceRepFirst responsePlan
${c.createdAt?ftime(c.createdAt):fdate(c.created)}${esc(c.name)}
${esc(c.interest||'')}
${esc(c.source)}${esc(uname(c.ownerId))}${t==null?(isLead(c)?'Waiting':'—'):`${t<60?t+' min':(t/60).toFixed(1)+' hr'}`}${c.plan?`${esc(c.plan.status)}`:'—'}${cbtn(c.id)}
No recent leads
`} /* ================= Equity mining ================= */ function payoffOf(d){if(d.type==='Cash')return 0;if(d.type==='BHPH'){const l=d.loanId&&loan(d.loanId);return l?(l.status==='Active'?payoff(l):0):0} const n=+d.term||0,ppy=FREQ[d.freq]?.ppy||12;if(!n)return 0;const r=(+d.apr||0)/100/ppy;const k=Math.min(n,Math.floor(Math.max(0,diff(d.date,TODAY))/(365/ppy)));if(r===0)return Math.max(0,d.financed*(1-k/n));const P=d.financed,pm=pmt(P,+d.apr,n,ppy);return Math.max(0,P*Math.pow(1+r,k)-pm*(Math.pow(1+r,k)-1)/r)} function valueNow(d){const v=veh(d.vehicleId);const sm=bookSummary(v);const tr=Object.entries(sm).map(([b,s])=>bkVal(s.e,b==='kbb'?'tig':'ta')).filter(Boolean);if(tr.length)return{val:tr.reduce((a,b)=>a+b,0)/tr.length,src:'Book trade-in'}; const months=Math.max(0,diff(d.date,TODAY)/30.4);return{val:Math.round(+d.price*0.72*Math.pow(1-0.012,months)/25)*25,src:'Estimate'}} function equityRows(){return S.deals.map(d=>{const c=cust(d.customerId),v=veh(d.vehicleId),l=d.loanId&&loan(d.loanId);const po=payoffOf(d),vn=valueNow(d);const eq=vn.val-po;const months=Math.round(diff(d.date,TODAY)/30.4); const good=l?l.status==='Paid Off'||(l.status==='Active'&&daysLate(l)===0&&paidCount(l)/l.term>=0.5):true;return{d,c,v,l,po,vn,eq,months,good,score:Math.round((eq>0?eq/100:0)+(good?30:0)+Math.min(24,months))}}).filter(r=>r.c).sort((a,b)=>b.score-a.score)} VIEWS.equity=()=>{const rows=equityRows();const f=ui.eqF||'pos';const list=rows.filter(r=>f==='all'||(f==='pos'?r.eq>0&&r.good:f==='bhph'?r.d.type==='BHPH'&&r.good:r.months>=12)); return `
${kpi('Customers with positive equity',rows.filter(r=>r.eq>0).length,'')}${kpi('Upgrade-ready',rows.filter(r=>r.eq>0&&r.good).length,'positive equity, paying well')}${kpi('Total equity',$0(rows.filter(r=>r.eq>0).reduce((a,r)=>a+r.eq,0)),'across your customers')}
Values use the newest Black Book / J.D. Power / KBB trade-in on the vehicle when there is one. Otherwise DealerPen estimates (marked) and you can book it for an exact number.${aiOn('bdc')?``:''}
${list.map(r=>``).join('')||''}
CustomerVehicleBoughtEst. valuePayoffEquityStatus
${esc(r.c.name)}
${esc(r.c.phone)}
${esc(vname(r.v))}${fdate(r.d.date)}
${r.months} mo · ${r.d.type}
${$0(r.vn.val)}
${r.vn.src}
${$0(r.po)}${$0(r.eq)}${r.l?r.l.status==='Active'?latePill(daysLate(r.l))+` ${paidCount(r.l)}/${r.l.term}`:statusPill(r.l.status):''+r.d.type+''} ${cbtn(r.c.id)}
Nobody matches this filter
`}; /* ================= Online buying (digital retailing) ================= */ function addOnlineDeal(c,x){S.onlineDeals=S.onlineDeals||[];const v=x.stock?S.vehicles.find(z=>z.stock===x.stock):null;S.onlineDeals.push({id:uid(),at:nowAt(),customerId:c.id,vehicleId:v?.id||null,stock:x.stock||'',type:x.payType==='cash'?'Cash':'BHPH',down:+x.down||0,term:+x.term||0,estPayment:+x.estPayment||0,trade:x.trade||null,income:+x.income||0,employer:x.employer||'',status:'New'}); if(+x.income&&!c.income)c.income=+x.income;if(x.employer&&!c.employer)c.employer=x.employer;if(v&&!c.interest)c.interest=vname(v);c.next={type:'Call',date:TODAY,time:'',note:'Online deal started: call within 5 minutes',by:'Website',at:nowAt()};c.followUp=TODAY} function onlineDealsView(){const od=(S.onlineDeals||[]).slice().sort((a,b)=>b.at.localeCompare(a.at));return `
Deals customers started on your website: payment option, down payment, term, trade-in and pre-qualification. Review and desk them here.
${od.map(o=>{const c=cust(o.customerId),v=veh(o.vehicleId);return ``}).join('')||''}
StartedCustomerVehicleStructureTrade-inIncomeStatus
${ftime(o.at)}${esc(c?.name)}
${esc(c?.phone)}
${v?esc(vname(v)):esc(o.stock||'—')}${o.type==='Cash'?'Cash':`${$0(o.down)} down · ${o.term} mo${o.estPayment?' · est. '+$0(o.estPayment)+'/mo':''}`}${o.trade&&o.trade.desc?esc(o.trade.desc)+(o.trade.miles?' · '+(+o.trade.miles).toLocaleString()+' mi':'')+(o.trade.payoff?' · owes '+$0(o.trade.payoff):''):'—'}${o.income?$0(o.income)+'/mo':'—'}${o.status} ${cbtn(o.customerId)} ${o.trade&&o.trade.desc?` `:''}
No online deals yet. They arrive from the “Buy online” button on your website
`} function deskOnline(id){const o=S.onlineDeals.find(x=>x.id===id);o.status='Desked';save();dealModal(null,o.vehicleId&&['Available','Pending'].includes(veh(o.vehicleId)?.status)?o.vehicleId:null,o.customerId);setTimeout(()=>{const f=$('#df');if(!f)return;f.type.value=o.type;if(o.down)f.down.value=o.down;if(o.term){f.freq.value='monthly';f.term.value=o.term}f.dispatchEvent(new Event('input'))},30)} function tradeFromOnline(id){const o=S.onlineDeals.find(x=>x.id===id),t=o.trade||{};S.appraisals=S.appraisals||[];const parts=String(t.desc||'').split(/\s+/);const a={id:uid(),created:nowAt(),by:S.settings.user,vin:t.vin||'',year:+parts[0]||'',make:+parts[0]?parts[1]||'':parts[0]||'',model:parts.slice(+parts[0]?2:1).join(' '),trim:'',color:'',miles:+t.miles||0,condition:t.condition||'Average',customerId:o.customerId,recon:0,payoff:+t.payoff||0,offer:0,status:'Open',bookouts:[],notes:'From online deal'};S.appraisals.push(a);save();appraisalModal(a.id)} /* ================= Market pricing (comps) ================= */ const mkCfg=()=>Object.assign({target:97,perMile:0.08},S.settings.market||{}); function marketStats(v){const cs=(v.comps||[]).filter(c=>+c.price>0);if(!cs.length)return null;const pm=mkCfg().perMile;const adj=cs.map(c=>+c.price+((+c.miles||+v.miles)-(+v.miles))*pm);const sorted=[...adj].sort((a,b)=>a-b);const avg=adj.reduce((a,b)=>a+b,0)/adj.length;const med=sorted[Math.floor(sorted.length/2)]; const rank=1+adj.filter(p=>p<+v.price).length;return{n:cs.length,avg,med,low:sorted[0],high:sorted[sorted.length-1],ptm:+v.price/avg*100,rank,suggested:Math.round(avg*mkCfg().target/100/100)*100}} function marketModal(vid){const v=veh(vid);v.comps=v.comps||[];const st=marketStats(v);const c=mkCfg(); openModal(mh(`Market pricing · ${esc(v.stock)} ${esc(vname(v))}`)+`
Compare against similar cars for sale near you (same year range, make, model and trim). Prices are adjusted for mileage at ${$$(c.perMile)}/mile.
${st?`
Your price${$0(v.price)}
Market avg (mileage-adj.)${$0(st.avg)}
Price to market${st.ptm.toFixed(1)}%
Rank${st.rank} of ${st.n+1}
Range${$0(st.low)}–${$0(st.high)}
Suggested at ${c.target}%${$0(st.suggested)}
${st.suggested!==+v.price?``:''}
`:''} ${v.comps.map((k,i)=>``).join('')||''}
SourceYear / trimMilesPriceAdj. priceDist.
${k.url?`${esc(k.source||'link')} ↗`:esc(k.source||'')}${esc([k.year,k.trim].filter(Boolean).join(' '))}${k.miles?(+k.miles).toLocaleString():'—'}${$0(k.price)}${$0(+k.price+((+k.miles||+v.miles)-(+v.miles))*c.perMile)}${k.dist?esc(k.dist)+' mi':''}
No comparable listings yet
Paste several listings at once
${[['Cars.com','https://www.cars.com/'],['CarGurus','https://www.cargurus.com/'],['Autotrader','https://www.autotrader.com/'],['Facebook Marketplace','https://www.facebook.com/marketplace/category/vehicles']].map(x=>`Search ${x[0]} ↗`).join('')}
`,true); $('#cmpf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);v.comps.push({source:x.source,year:x.year,trim:x.trim,miles:+x.miles||0,price:+x.price,dist:x.dist,at:TODAY});save();marketModal(vid)}; $('#cmpgo').onclick=async()=>{const t=$('#cmpp').value.trim();if(!t)return;let rows=[]; if(aiOn('pricing')&&SAMPLE){try{rows=await ai(`Extract every vehicle listing from this pasted text. Reply with only a JSON array: [{"source":"site or seller if shown","year":2018,"trim":"","miles":54000,"price":15995,"dist":"","url":""}]. Use numbers without $ or commas; skip listings without a price.\n\n${t.slice(0,20000)}`,{tier:'quick',nocache:true})}catch(e){toast(aiErrMsg(e))}} if(!rows.length)rows=t.split(/\n{2,}|\r?\n(?=\d{4}\s)/).map(b=>({price:+((b.match(/\$\s?([\d,]{4,7})/)||[])[1]||'').replace(/,/g,''),miles:+((b.match(/([\d,]{2,7})\s*(?:mi|miles)/i)||[])[1]||'').replace(/,/g,''),year:(b.match(/\b(19|20)\d{2}\b/)||[''])[0],source:'Pasted'})).filter(r=>r.price>500); if(!rows.length)return toast('Couldn\'t find prices in that text');rows.forEach(r=>v.comps.push({...r,at:TODAY}));save();toast(rows.length+' comps added');marketModal(vid)}} /* ================= Lender programs (rate sheets in desking) ================= */ function lendersView(){S.lenders=S.lenders||[];return `
Enter each lender's current rate sheet: tiers by credit score, rates, terms and limits. Desking then shows only the programs a deal qualifies for, with payments. Update them when lenders send new sheets.
${S.lenders.map(L=>`

🏦 ${esc(L.name)}${esc(L.kind||'')}

Sheet dated ${L.sheetDate?fdate(L.sheetDate):'—'}${L.sheetDate&&diff(L.sheetDate,TODAY)>45?' update?':''}${L.portal?' · via '+esc(L.portal):''}
${(L.programs||[]).map(p=>``).join('')}
TierScoreRateMax termMax LTVVehicle limits
${esc(p.tier)}${p.minScore||0}–${p.maxScore||850}${(+p.rate).toFixed(2)}%${p.maxTerm} mo${p.maxLTV}%${p.minYear?'≥'+p.minYear+' ':''}${p.maxMiles?'≤'+(+p.maxMiles).toLocaleString()+' mi ':''}${p.maxAmount?'≤'+$0(p.maxAmount):''}
`).join('')||'
No lenders yet. Add a lender and type in its rate sheet
'}
`} function lenderModal(id){S.lenders=S.lenders||[];const L=id?S.lenders.find(x=>x.id===id):{name:'',kind:'Credit union',portal:'',sheetDate:TODAY,programs:[{tier:'A',minScore:720,maxScore:850,rate:6.99,maxTerm:72,maxLTV:125,minYear:'',maxMiles:120000,maxAmount:''},{tier:'B',minScore:660,maxScore:719,rate:9.99,maxTerm:72,maxLTV:115,minYear:'',maxMiles:120000,maxAmount:''},{tier:'C',minScore:600,maxScore:659,rate:14.99,maxTerm:60,maxLTV:110,minYear:'',maxMiles:100000,maxAmount:''}]};let ps=JSON.parse(JSON.stringify(L.programs||[])); openModal(mh(id?'Edit lender':'Add lender')+`

The example numbers in a new lender are placeholders. Replace them with the lender's actual rate sheet.

${id?'':''}
`,true); const cols=[['tier','Tier',60],['minScore','Min score',70],['maxScore','Max score',70],['rate','Rate %',70],['maxTerm','Max term',70],['maxLTV','Max LTV %',70],['minYear','Min year',70],['maxMiles','Max miles',90],['maxAmount','Max $',90]]; const draw=()=>{$('#lps').innerHTML=`${cols.map(c=>``).join('')}${ps.map((p,i)=>`${cols.map(c=>``).join('')}`).join('')}
${c[1]}
`; $('#lps').querySelectorAll('input').forEach(el=>el.onchange=()=>{const k=el.dataset.k;ps[+el.dataset.i][k]=k==='tier'?el.value:el.value===''?'':+el.value});$('#lps').querySelectorAll('[data-x]').forEach(b=>b.onclick=()=>{ps.splice(+b.dataset.x,1);draw()})};draw(); $('#lpa').onclick=()=>{ps.push({tier:'',minScore:0,maxScore:850,rate:0,maxTerm:60,maxLTV:100});draw()};if($('#ldel'))$('#ldel').onclick=()=>{S.lenders=S.lenders.filter(x=>x.id!==id);save();closeModal();render()}; $('#lsv').onclick=()=>{if(!$('#lnm').value.trim())return toast('Name the lender');const n=id?L:{id:uid()};Object.assign(n,{name:$('#lnm').value.trim(),kind:$('#lkd').value,portal:$('#lpt').value,sheetDate:$('#lsd').value,programs:ps.filter(p=>p.tier!==''||p.rate)});if(!id)S.lenders.push(n);save();closeModal();render();toast('Lender saved')}} function eligiblePrograms(x,score){const v=veh(x.vehicleId);if(!v)return[];const k=calcDeal({...x,type:'Retail Finance'});const lb=lenderBookValue(v);const out=[]; (S.lenders||[]).forEach(L=>(L.programs||[]).forEach(p=>{const why=[];if(score&&(score<(+p.minScore||0)||score>(+p.maxScore||850)))return;if(p.minYear&&+v.year<+p.minYear)why.push(`year ${v.year} < ${p.minYear}`);if(p.maxMiles&&+v.miles>+p.maxMiles)why.push(`${(+v.miles).toLocaleString()} mi over limit`);if(p.maxAmount&&k.financed>+p.maxAmount)why.push(`amount over ${$0(p.maxAmount)}`); const ltv=lb&&lb.val?k.financed/lb.val*100:null;if(ltv!=null&&p.maxLTV&<v>+p.maxLTV)why.push(`LTV ${ltv.toFixed(0)}% > ${p.maxLTV}%`);const term=+p.maxTerm||60;const pay=pmt(k.financed,+p.rate,term,12);out.push({L,p,term,pay,ltv,why})}));return out.sort((a,b)=>a.why.length-b.why.length||a.pay-b.pay)} function programsHTML(x){const score=+(x.score||0);const el=eligiblePrograms(x,score);if(!(S.lenders||[]).length)return `
No lender rate sheets yet. Add lenders
`; return `
${score?'Programs for a '+score+' score':'Enter a credit score to filter tiers'}${lenderBookValue(veh(x.vehicleId))?'':' · book the car for LTV checks'}
${el.slice(0,8).map(e=>`
${esc(e.L.name)} · tier ${esc(e.p.tier)} ${(+e.p.rate).toFixed(2)}% · ${e.term} mo · ${$$(e.pay)}/mo${e.ltv!=null?` · LTV ${e.ltv.toFixed(0)}%`:''}${e.why.length?`
✕ ${esc(e.why.join(' · '))}
`:`
`}
`).join('')||'
No programs fit this score.
'}`} function applyProgram(o){const f=$('#df');f.type.value='Retail Finance';f.lender.value=o.lender;f.apr.value=o.rate;f.freq.value='monthly';f.term.value=o.term;f.dispatchEvent(new Event('input'));toast('Program applied')} /* ================= Manager desk log (floor traffic) ================= */ const FSTAGES=['Greeted','Test drive','Desking','In finance','Sold','Be-back','Lost']; VIEWS.desklog=()=>{const day=ui.flDay||TODAY;const fl=(S.floor||[]).filter(x=>x.date===day).sort((a,b)=>a.timeIn.localeCompare(b.timeIn));const cnt=s=>fl.filter(x=>x.stage===s).length; return `
Everyone on the lot ${day===TODAY?'today':'on '+fdate(day)}, who's working them and where each deal stands.
${kpi('Ups',fl.length,'')}${kpi('Test drives',fl.filter(x=>['Test drive','Desking','In finance','Sold'].includes(x.stage)).length,'')}${kpi('Sold',cnt('Sold'),fl.length?Math.round(cnt('Sold')/fl.length*100)+'% close':'')}${kpi('Still working',fl.filter(x=>!['Sold','Lost','Be-back'].includes(x.stage)).length,'')}
${fl.map(x=>{const c=cust(x.customerId);return ``}).join('')||''}
InCustomerSourceSalespersonVehicleStageManager notes
${esc(x.timeIn)}
${Math.round((Date.now()-new Date(x.date+'T'+x.timeIn))/60000)>0&&day===TODAY&&!['Sold','Lost','Be-back'].includes(x.stage)?Math.round((Date.now()-new Date(x.date+'T'+x.timeIn))/60000)+' min':''}
${esc(c?.name)}
${esc(c?.phone||'')}
${esc(x.source||'')} ${x.stage==='Desking'||x.stage==='In finance'?``:''}
No ups logged yet

Shared live across computers once DealerPen runs on its server with a shared database. For now each browser keeps its own log.

`}; function floorSet(id,k,v){const x=S.floor.find(f=>f.id===id);x[k]=v;x.updated=nowAt();if(k==='stage'){const c=cust(x.customerId);if(c){if(v==='Sold'&&c.stage!=='Sold')c.notes.push({date:TODAY,by:S.settings.user,text:'Floor: sold'});if(v==='Lost'){c.stage='Lost'}if(v==='Be-back'){c.stage='Appointment';c.next={type:'Call',date:addDays(TODAY,1),time:'10:00',note:'Be-back from the lot',by:S.settings.user,at:nowAt()}}if(['Test drive','Desking'].includes(v)&&c.stage==='New')c.stage='Contacted'}}save();render()} function floorUp(prefill){S.floor=S.floor||[];openModal(mh('New up')+`
`); $('#fuf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);let c=x.cid&&cust(x.cid);if(!c){if(!x.name.trim())return toast('Pick a customer or enter a name');c={id:uid(),created:TODAY,createdAt:nowAt(),name:x.name.trim(),phone:x.phone,email:'',address:prefill?.address||'',source:x.source==='Internet'?'Website':'Walk-in',stage:'New',employer:'',income:0,interest:x.vid?vname(veh(x.vid)):'',followUp:'',smsConsent:false,optOut:false,dnc:false,notes:[],ownerId:x.rep,...(prefill?.extra||{})};S.customers.push(c)} S.floor.push({id:uid(),date:TODAY,timeIn:new Date().toTimeString().slice(0,5),customerId:c.id,repId:x.rep,source:x.source,vehicleId:x.vid,stage:'Greeted'});c.notes.push({date:TODAY,by:S.settings.user,text:`On the lot (${x.source}) with ${uname(x.rep)}`});save();closeModal();ui.flDay=TODAY;if(route!=='desklog')go('desklog');else render()}} /* ================= Driver's license scan (AI vision) ================= */ function takeGuidedPhoto(onPhoto){ const fallback=()=>{ const input=document.createElement('input'); input.type='file';input.accept='image/*';input.setAttribute('capture','environment'); input.onchange=()=>{if(input.files[0])onPhoto(input.files[0])}; input.click(); }; if(!navigator.mediaDevices?.getUserMedia)return fallback(); openModal(mh('Take a photo')+`

Starting camera…

`); const video=$('#scan-preview'), guide=$('#scan-guide'), frame=$('#scan-frame'), shutter=$('#scan-shutter'); let stream,timer,closed=false,nearSamples=0,warning=false; const cleanup=()=>{ closed=true;clearInterval(timer); stream?.getTracks().forEach(track=>track.stop()); video.srcObject=null; window.removeEventListener('pagehide',cleanup); if(stopPhotoPreview===cleanup)stopPhotoPreview=undefined; }; stopPhotoPreview=cleanup; window.addEventListener('pagehide',cleanup); $('#scan-native').onclick=()=>{closeModal();fallback()}; shutter.onclick=()=>{ if(closed||!video.videoWidth)return; shutter.disabled=true; const canvas=document.createElement('canvas'); canvas.width=video.videoWidth;canvas.height=video.videoHeight; canvas.getContext('2d').drawImage(video,0,0); canvas.toBlob(blob=>{ if(closed)return; if(!blob){shutter.disabled=false;guide.textContent='Could not take the photo. Try again.';return} closeModal(); onPhoto(new File([blob],'document.jpg',{type:'image/jpeg'})); },'image/jpeg',0.93); }; navigator.mediaDevices.getUserMedia({audio:false,video:{facingMode:{ideal:'environment'},width:{ideal:1920},height:{ideal:1080}}}).then(async camera=>{ if(closed){camera.getTracks().forEach(track=>track.stop());return} stream=camera;video.srcObject=stream;await video.play(); if(closed)return; shutter.disabled=false; const track=stream.getVideoTracks()[0]; const update=()=>{ const distance=track.getSettings().focusDistance; const near=Number.isFinite(distance)&&distance>0&&distance<(warning?0.19:0.15); nearSamples=near?Math.min(3,nearSamples+1):0; warning=nearSamples>=3||(warning&&near); const message=warning?'Too close. Move back until the whole document fits inside the guide.':'Keep all four corners inside the guide and make sure the text is sharp.'; if(guide.textContent!==message)guide.textContent=message; frame.style.borderColor=warning?'#f59e0b':'white'; guide.style.fontWeight=warning?'700':'400'; }; update();timer=setInterval(update,200); }).catch(()=>{ if(closed)return; stream?.getTracks().forEach(track=>track.stop()); video.srcObject=null; guide.textContent='Preview unavailable. Use the device camera and keep all four corners in view.'; }); } function scanLicense(cid,toFloor){if(!SAMPLE){toast('License scanning uses AI and works when DealerPen is open inside Claude');return} takeGuidedPhoto(async f=>{if(!f)return;toast('Reading license…');try{const img=await shrink(f,1600,0.85); const r=await ai(`This is a photo of the FRONT of a U.S. driver's license or state ID, provided by a car dealership with the customer's permission to fill in their customer record. Read it carefully. Reply with only JSON: {"first":"","middle":"","last":"","address":"street, city, ST zip","dob":"YYYY-MM-DD","dl_number":"","state":"ST","expires":"YYYY-MM-DD","readable":true}. Use empty strings for anything you can't read clearly; never guess.`,{images:[img],tier:'default',nocache:true}); if(!r||r.readable===false)return toast('Couldn\'t read that photo. Try again with better light');const name=[r.first,r.middle?r.middle[0]:'',r.last].filter(Boolean).join(' ');const extra={dlNo:r.dl_number||'',dlState:r.state||'',dob:r.dob||'',dlExp:r.expires||''}; if(r.expires&&r.expires{S.finder=S.finder||{wants:[],found:[],lastRun:''};const F_=S.finder;const st=F_.found.filter(x=>x.status!=='Dismissed').sort((a,b)=>b.score-a.score); return `

🎯 What we're looking for

${F_.wants.map(w=>`
${esc([w.yearMin&&w.yearMin+'+',w.make,w.model].filter(Boolean).join(' ')||'Any vehicle')} ${w.maxPrice?'under '+$0(w.maxPrice):''} ${w.maxMiles?'· ≤'+(+w.maxMiles).toLocaleString()+' mi':''}${w.belowMarket?` · ${w.belowMarket}% below market`:''}
${w.customerId?'For '+esc(cust(w.customerId)?.name):'For inventory'} · added ${fdate(w.at)}
`).join('')||'
Add customer requests (“2016+ Camry under $15k”) and your own buying targets
'}

🔎 Today's sources

Open each source, export or copy the run list or search results, and paste it here. The finder scores every car against your targets and the market.
${[['Manheim','https://www.manheim.com/'],['OPENLANE (ADESA)','https://www.openlane.com/'],['CarMax Auctions','https://www.carmaxauctions.com/'],['Facebook Marketplace','https://www.facebook.com/marketplace/category/vehicles']].map(x=>`${x[0]} ↗`).join('')}
${F_.lastRun?'Last run '+ftime(F_.lastRun):''}
${st.map(x=>``).join('')||''}
ScoreVehicleSourcePrice / bidMarket / MMRMatchesWhy
${x.score}${esc(x.title)}
${x.miles?(+x.miles).toLocaleString()+' mi':''} ${x.vin?'· '+esc(x.vin):''} ${x.location?'· '+esc(x.location):''}
${x.url?`${esc(x.source)} ↗`:esc(x.source)}${x.lane?`
${esc(x.lane)}
`:''}
${x.price?$0(x.price):'—'}${x.market?$0(x.market):'—'}${x.price&&x.market?`
${$0(x.market-x.price)} ${x.price`:''}
${(x.matches||[]).map(m=>`${esc(m)}`).join(' ')}${esc(x.why||'')} ${x.customerId&&cust(x.customerId)?` `:''}
Paste a run list or listings to see matches

A fully automatic daily run needs data access from each source (for example Manheim and OPENLANE developer programs) and the DealerPen server. Facebook Marketplace has no public API, so reps search it by hand and paste results here.

`}; function wantModal(){openModal(mh('What are we looking for?')+`
`); $('#wf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);S.finder.wants.push({id:uid(),at:TODAY,...x});save();closeModal();render()}} async function finderRun(){const t=$('#fdp').value.trim(),src=$('#fds').value;if(!t)return toast('Paste a run list or listings first');if(!SAMPLE)return toast('Scoring uses AI and works when DealerPen is open inside Claude');const b=$('#fdgo');b.disabled=true;b.textContent='✦ Scoring…'; try{const rows=await ai(`You help a used-car dealer find vehicles to buy. Source: ${src}. Our targets: ${JSON.stringify(S.finder.wants.map(w=>({id:w.id,for:w.customerId?'customer '+(cust(w.customerId)?.name||''):'inventory',make:w.make,model:w.model,yearMin:w.yearMin,maxPrice:w.maxPrice,maxMiles:w.maxMiles,belowMarketPct:w.belowMarket,notes:w.notes})))}. Our current inventory (avoid duplicates of what we already have lots of): ${JSON.stringify(S.vehicles.filter(v=>v.status==='Available').map(v=>vname(v)))}. Below is a pasted run list or listings. Extract each vehicle. Use the listing's own market or MMR value if one is shown; otherwise leave market empty (never invent values). Score 0-100 for how good a buy it is for us: matches a target, priced below market when market is known, reasonable miles, condition grade if shown. Reply with only a JSON array: [{"title":"2017 Toyota Camry SE","vin":"","miles":64000,"price":13200,"market":15100,"location":"","lane":"lane/run # if shown","url":"","match_ids":["target id"],"score":82,"why":"one short sentence"}] Data: ${t.slice(0,40000)}`,{nocache:true}); const arr=Array.isArray(rows)?rows:[];arr.forEach(r=>{const matches=(r.match_ids||[]).map(id=>{const w=S.finder.wants.find(x=>x.id===id);return w?(w.customerId?cust(w.customerId)?.name:[w.make,w.model].filter(Boolean).join(' ')||'target'):null}).filter(Boolean); const cid=(r.match_ids||[]).map(id=>S.finder.wants.find(x=>x.id===id)).find(w=>w&&w.customerId)?.customerId||'';S.finder.found.push({id:uid(),at:nowAt(),source:src,title:r.title,vin:r.vin,miles:+r.miles||0,price:+r.price||0,market:+r.market||0,location:r.location,lane:r.lane,url:r.url,score:Math.max(0,Math.min(100,+r.score||0)),why:r.why,matches,customerId:cid,status:'New'})}); S.finder.lastRun=nowAt();save();render();toast(arr.length+' vehicles scored')}catch(e){toast(aiErrMsg(e))}if(b){b.disabled=false;b.textContent='✦ Score these cars'}} /* ================= Bookout (Black Book / J.D. Power / KBB) ================= */ const BOOKS={ bb:{n:'Black Book',c:'#111827',url:'https://www.blackbook.com/',vals:[['wxc','Wholesale – extra clean'],['wc','Wholesale – clean'],['wa','Wholesale – average'],['wr','Wholesale – rough'],['tc','Trade-in – clean'],['ta','Trade-in – average'],['rc','Retail – clean'],['ra','Retail – average']],wholesale:'wa',retail:'rc',loan:'rc'}, jdp:{n:'J.D. Power',c:'#0b4ea2',url:'https://www.jdpowervalues.com/',vals:[['tr','Trade-in – rough'],['ta','Trade-in – average'],['tc','Trade-in – clean'],['loan','Clean loan'],['retail','Clean retail'],['al','Auction – low'],['aa','Auction – average'],['ah','Auction – high']],wholesale:'aa',retail:'retail',loan:'loan'}, kbb:{n:'Kelley Blue Book',c:'#1d5fbf',url:'https://b2b.kbb.com/',vals:[['tif','Trade-in – fair'],['tig','Trade-in – good'],['tivg','Trade-in – very good'],['pp','Private party'],['tlp','Typical listing price'],['fpp','Fair purchase price'],['lend','Lending value'],['auc','Auction value']],wholesale:'auc',retail:'tlp',loan:'lend'}}; const bkCfg=()=>Object.assign({on:{bb:true,jdp:true,kbb:true},lenderBook:'jdp',lenderVal:'loan',advance:110,maxAge:30},S.settings.bookout||{}); const bookouts=v=>(v&&v.bookouts)||[]; const latestBook=(v,b)=>bookouts(v).filter(x=>x.book===b).sort((a,c)=>c.date.localeCompare(a.date))[0]; const bkVal=(e,k)=>e?(+e.vals?.[k]||0)+(+e.adj||0):0; function bookSummary(v){const out={};Object.keys(BOOKS).forEach(b=>{const e=latestBook(v,b);if(e)out[b]={e,whole:bkVal(e,BOOKS[b].wholesale),retail:bkVal(e,BOOKS[b].retail),loan:bkVal(e,BOOKS[b].loan),age:diff(e.date,TODAY)}});return out} function lenderBookValue(v){const c=bkCfg();const e=latestBook(v,c.lenderBook);return e?{val:bkVal(e,c.lenderVal),e,label:`${BOOKS[c.lenderBook].n} ${BOOKS[c.lenderBook].vals.find(x=>x[0]===c.lenderVal)?.[1]||''}`,stale:diff(e.date,TODAY)>c.maxAge}:null} function bookoutModal(target,book,editId){const isApp=target.startsWith('ap:');const v=isApp?S.appraisals.find(a=>a.id===target.slice(3)):veh(target);v.bookouts=v.bookouts||[];const B=BOOKS[book];const e=editId?v.bookouts.find(x=>x.id===editId):{book,date:TODAY,miles:v.miles||'',condition:'Average',region:S.settings.state||'',trim:v.trim||'',vals:{},adj:0,optAdj:0,milesAdj:0}; openModal(mh(`${B.n} bookout · ${esc(vname(v)||'Appraisal')}`)+`
Enter the values from your ${esc(B.n)} subscription. Open ${esc(B.n)} ↗ · VIN ${esc(v.vin||'')}
Pulls values automatically once ${esc(B.n)} is connected to your DealerPen server.
Values (after options & mileage, or base values plus the adjustments above)
${B.vals.map(([k,l])=>``).join('')}
${editId?'':''}
`,true); const f=$('#bkf');const u=()=>{$('#bkadj').value=$$((+f.optAdj.value||0)+(+f.milesAdj.value||0))};f.oninput=u;u(); if(editId)$('#bkdel').onclick=()=>{v.bookouts=v.bookouts.filter(x=>x.id!==editId);save();closeModal();render()}; f.onsubmit=ev=>{ev.preventDefault();const x=fd(f);const vals={};B.vals.forEach(([k])=>{if(x['v_'+k]!=='')vals[k]=+x['v_'+k]});if(!Object.keys(vals).length)return toast('Enter at least one value'); const n=editId?e:{id:uid(),book,by:S.settings.user,at:nowAt()};Object.assign(n,{source:f.dataset.src||n.source||'manual',date:x.date,region:x.region,trim:x.trim,miles:+x.miles||0,condition:x.condition,optAdj:+x.optAdj||0,milesAdj:+x.milesAdj||0,adj:x.baseVals?(+x.optAdj||0)+(+x.milesAdj||0):0,vals,notes:x.notes});if(!editId)v.bookouts.push(n);save();closeModal();render();toast(B.n+' bookout saved');if(isApp)appraisalModal(v.id);else if(route!=='inventory')bookoutView(target)}} function bookCompareHTML(v,opts={}){const sm=bookSummary(v);const c=bkCfg();const books=Object.keys(BOOKS).filter(b=>c.on[b]);const price=+v.price||0,cost=vcost(v); return `
${books.map(b=>{const s=sm[b],B=BOOKS[b];return `
${B.n}${s?`${s.e.source==='test'?'TEST ':s.e.source==='api'?'API ':''}${s.age}d old`:''}
${s?`${B.vals.filter(([k])=>s.e.vals[k]!=null).map(([k,l])=>``).join('')}
${esc(l)}${$0(bkVal(s.e,k))}
${[s.e.condition&&esc(s.e.condition),+s.e.miles?(+s.e.miles).toLocaleString()+' mi':'',fdate(s.e.date),s.e.region&&esc(s.e.region)].filter(Boolean).join(' · ')}
${opts.noEdit?'':`
`}` :`
Not booked
${opts.noEdit?'':``}`}
`}).join('')}
${Object.keys(sm).length&&!opts.noSummary?`
${(()=>{const ws=Object.values(sm).map(s=>s.whole).filter(Boolean),rs=Object.values(sm).map(s=>s.retail).filter(Boolean);const avgW=ws.length?ws.reduce((a,b)=>a+b,0)/ws.length:0,avgR=rs.length?rs.reduce((a,b)=>a+b,0)/rs.length:0;const lb=lenderBookValue(v); return [avgW?`
Avg wholesale${$0(avgW)}
`:'',avgR?`
Avg retail${$0(avgR)}
`:'',price&&avgR?`
Asking vs avg retail${(price/avgR*100).toFixed(0)}%
`:'',cost&&avgW?`
Cost vs avg wholesale${$0(cost-avgW)}
`:'',lb?`
Lender book (${esc(lb.label)})${$0(lb.val)}${lb.stale?' ⚠':''}
`:'',lb&&price?`
Max advance @${c.advance}%${$0(lb.val*c.advance/100)}
`:''].join('')})()}
`:''}`} function bookoutView(vid){const v=veh(vid);openModal(mh(`Bookout · ${esc(v.stock)} ${esc(vname(v))}`)+`
${(+v.miles).toLocaleString()} mi · VIN ${esc(v.vin)} · asking ${$0(v.price)} · cost + recon ${$0(vcost(v))}
${bookCompareHTML(v)}
${Object.entries(BOOKS).filter(([b])=>bkCfg().on[b]).map(([b,B])=>`${esc(B.n)} ↗`).join('')}
${DL?``:''}
`,true)} async function bookSheet(vid,dealId){const v=veh(vid),d=dealId?S.deals.find(x=>x.id===dealId):null;syncCustomForms();const doc=`Bookout – ${esc(v.stock)}
${bookSheetHTML(v,d)}
`; try{await DL.save({filename:`bookout-${v.stock}.html`,data:doc});toast('Saved')}catch(e){if(e.code!=='declined')copyText(doc)}} function bookSheetHTML(v,d){const lb=lenderBookValue(v),c=bkCfg();return F.hdr('Vehicle Bookout Sheet',0,d?`Deal #${d.no}`:`Stock ${v.stock}`)+F.grid([[['Year',v.year],['Make',v.make],['Model',v.model],['Trim',v.trim]],[['VIN',v.vin,2],['Odometer',(+v.miles).toLocaleString()],['Color',v.color]]])+ `

Book values

${bookCompareHTML(v,{noEdit:true,noSummary:true})}`+(d&&d.type!=='Cash'?`

Loan-to-value

`+F.money([['Amount financed',d.financed],[lb?'Lender book value ('+lb.label+')':'Lender book value (not booked)',lb?lb.val:0],['Loan-to-value',lb&&lb.val?(d.financed/lb.val*100).toFixed(1)+'%':'—','tot'],[`Max advance at ${c.advance}%`,lb?lb.val*c.advance/100:0]]):'')+F.note('Values were entered from the dealer\'s Black Book, J.D. Power and/or Kelley Blue Book subscriptions on the dates shown. Lenders may require their own bookout printout.')+F.sig('Prepared by','Manager')} const BKCSS=`.bkgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px}.bkcard{border:1px solid #d6dce6;border-top:4px solid;border-radius:10px;padding:10px 12px;background:#fff}.bkh{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px} .bkt{width:100%;border-collapse:collapse;font-size:12.5px}.bkt td{padding:3px 0;border-bottom:1px solid #eef1f5}.bkt tr.key td{font-weight:800}.bksum{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}.bksum div{background:#f3f5f9;border-radius:10px;padding:8px 12px}.bksum span{display:block;font-size:11px;color:#475569;text-transform:uppercase;letter-spacing:.4px;font-weight:700}.bksum b{font-size:16px}`; async function bookLookup(target,book){const isApp=target.startsWith('ap:');const v=isApp?S.appraisals.find(a=>a.id===target.slice(3)):veh(target);const f=$('#bkf');const btn=$('#bklk'); const vin=String(v.vin||'').toUpperCase();if(vin.length!==17)return toast('This vehicle needs a 17-character VIN first');btn.disabled=true;btn.textContent='Looking up…'; try{const zip=(String(S.settings.address||'').match(/\b\d{5}\b/)||[''])[0];const r=await esaFetch2(`/api/books/${book}/lookup?vin=${vin}&miles=${encodeURIComponent(f.miles.value||v.miles||'')}&zip=${zip}`); if(!r.ok)throw new Error(r.body?.error||`Lookup failed (${r.status})`);const o=r.body;Object.entries(o.vals||{}).forEach(([k,val])=>{if(f['v_'+k])f['v_'+k].value=val});if(o.trim)f.trim.value=o.trim;f.region.value=o.edition||o.region||f.region.value;f.dataset.src=o.test?'test':'api'; $('#bkmsg').innerHTML=o.test?'
TEST DATA from the server\'s test mode. These are not real book values, so don\'t save them on a real vehicle.
':`✓ Values pulled from ${esc(BOOKS[book].n)} ${o.date?'on '+fdate(o.date):''}`} catch(e){$('#bkmsg').innerHTML=`
${esc(String(e.message||'Lookup failed').replace(/\.$/,''))}. You can still type the values in.
`}btn.disabled=false;btn.textContent='⚡ Look up by VIN'} async function esaFetch2(path){const h=srvHeaders();try{const r=await fetch((ESA().server||'').replace(/\/$/,'')+path,{headers:h});const b=await r.json().catch(()=>({}));return{ok:r.ok,status:r.status,body:b}}catch(e){return{ok:false,status:0,body:{error:'DealerPen server not reachable from here'}}}} async function bookStatus(force){if(!force&&ui.bkStat&&Date.now()-ui.bkStat.at<60000)return ui.bkStat;const r=await esaFetch2('/api/books/status');ui.bkStat={at:Date.now(),ok:r.ok,data:r.ok?r.body:{}};return ui.bkStat} const SIGNUPS=[ ['Black Book','Data license (values in DealerPen by VIN)','https://www.blackbook.com/','Call 800-554-1026 and ask for Data Licensing. Say you\'re a dealer using your own DMS and want Black Book values by VIN through its API.'], ['J.D. Power','Web Services API (VIN Precision+ values)','https://www.jdpower.com/business/web-services-api/','Use “Contact us” on that page to request API documentation, sample calls and pricing.'], ['J.D. Power','Values Online subscription (manual lookups)','https://www.jdpowervalues.com/','Dealer subscription for looking values up yourself.'], ['Kelley Blue Book','B2B data license / InfoDriver Web Service','https://b2b.kbb.com/contact/','Request API access as a dealer integrating into your own DMS. Developer docs: developer.kbb.com'], ['Kelley Blue Book','Quick Values (manual lookups)','https://b2b.kbb.com/solutions/quick-values','Self-service dealer values site.'], ['Vitu / NTX','Developer portal: title, registration, NTX','https://api-identity.service.vitu.com/forms/signup','Create a developer account (sandbox right away; company accounts are reviewed).'], ['DLRdmv','DMS integration partner','https://connect.dlrdmv.com/cdg','Or email ContactUs@DLRdmv.com and ask to add DealerPen as a DMS integration.'], ['E-Sign Auto','Developer key','https://esignauto.com/','Ask the E-Sign Auto administrator for a LotLedger-scoped key (plus a separate test key).']]; function connectionsCard(){const st=ui.bkStat?.data||{};const live=k=>st[k]?.connected;return `

🔌 Connections & sign-up links

${SIGNUPS.map(sg=>{const k=sg[0]==='Black Book'?'bb':sg[0]==='J.D. Power'?'jdp':sg[0]==='Kelley Blue Book'?'kbb':sg[0]==='E-Sign Auto'?'esa':'';const ok=k==='esa'?ui.esaHealth?.ok&&ui.esaHealth.keyConfigured:k?live(k):false;const test=k==='esa'?ui.esaHealth?.mock:k?st[k]?.test:false; return ``}).join('')}
ProviderWhat to sign up forStatus
${esc(sg[0])}${esc(sg[1])}
${esc(sg[3])}
${!k||sg[1].includes('manual')?'—':ok?`${test?'Test mode':'Connected'}`:'Not connected'}Sign up ↗

After approval, each provider sends API documentation and credentials. The credentials go on the DealerPen server, never in this page. Black Book, J.D. Power and KBB plug into bookout-adapters.mjs.

`} /* ================= Professional theme (clean, readable) ================= */ const THEME=`:root{--bg:#f5f6f8;--panel:#fff;--ink:#101828;--ink2:#1d2939;--muted:#556070;--line:#e3e6eb;--line2:#eef0f3; --brand:#2558e0;--brand2:#1d47bd;--brandsoft:#eef3ff;--accent:#0e7c74;--red:#c4320a;--redsoft:#fdeee8;--amber:#a15c07;--ambersoft:#fdf4e3;--green:#067647;--greensoft:#e7f6ee;--blue:#1d4ed8;--bluesoft:#eaf0ff; --radius:12px;--shadow:0 1px 2px rgba(16,24,40,.05)} body{font-size:14px;line-height:1.5;letter-spacing:-.006em;font-feature-settings:'cv11','ss01';background:var(--bg)} a{font-weight:600} /* sidebar */ .app{grid-template-columns:240px 1fr} aside{background:#0f1729;border-right:0;padding:18px 12px} .logo{padding:6px 10px 22px;font-size:17px;font-weight:700;letter-spacing:-.2px} .logo .mark{background:var(--brand);box-shadow:none;border-radius:9px;width:32px;height:32px;font-size:13px} .logo small{color:#8a94a6;font-weight:500} nav a{gap:12px;padding:8px 12px;border-radius:8px;color:#b9c1d0;font-weight:500;font-size:13.5px;margin-bottom:1px;position:relative} nav a:hover{background:#1a2438;color:#fff} nav a.on{background:#1e2a42;color:#fff;box-shadow:none;font-weight:600} nav a.on:before{content:'';position:absolute;left:-12px;top:7px;bottom:7px;width:3px;border-radius:0 3px 3px 0;background:#6b93ff} nav .ico{width:18px;height:18px;display:inline-grid;place-items:center;color:#8a94a6;font-size:14px} nav a.on .ico,nav a:hover .ico{color:#fff} nav .ico svg{width:18px;height:18px} nav .sec{font-size:11px;letter-spacing:.08em;color:#6f7a8e;margin:22px 12px 6px;font-weight:600} .badge{background:#e04f1a;font-weight:600;line-height:18px;font-size:11px} .badge.blue{background:#2ea597;color:#fff} /* top bar */ .top{background:#fff;backdrop-filter:none;border-bottom:1px solid var(--line);padding:12px 28px;min-height:64px} .top h1{font-size:19px;font-weight:700;letter-spacing:-.3px} .search input{border:1px solid var(--line);border-radius:8px;background:#f7f8fa;padding:9px 13px;font-weight:400} .search input:focus{background:#fff} .content{padding:24px 28px 72px;max-width:1600px} .top{display:grid;grid-template-columns:minmax(max-content,1fr) minmax(200px,480px) minmax(max-content,1fr);gap:16px;align-items:center}.top .tl,.top .tr{display:flex;align-items:center;gap:12px;min-width:0}.top .tr{justify-content:flex-end}.top .tl h1{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.top .search input{width:100%}.top .sres{left:0;right:auto;width:100%;min-width:360px} @media(max-width:1100px){.top{grid-template-columns:auto minmax(160px,1fr) auto}.top .tl h1{display:none}} /* cards */ .card{border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);padding:20px} .card h3{font-size:15px;font-weight:650;letter-spacing:-.15px;margin-bottom:14px;color:var(--ink)} .grid{gap:16px} /* KPI tiles */ .kpi:before{display:none} .kpi .l{font-size:12px;font-weight:500;letter-spacing:.01em;text-transform:none;color:var(--muted)} .kpi .v{font-size:27px;font-weight:650;letter-spacing:-.6px;margin-top:4px;color:var(--ink)} .kpi .s{font-size:12.5px;font-weight:400;margin-top:2px} /* tables */ th{background:transparent;font-size:12px;font-weight:600;text-transform:none;letter-spacing:0;color:var(--muted);border-bottom:1px solid var(--line);padding:10px 12px} th:first-child,th:last-child{border-radius:0} td{padding:12px;border-bottom:1px solid var(--line2);color:var(--ink2)} td b{color:var(--ink);font-weight:600} tr.click:hover td{background:#f8f9fb} .num{font-weight:500} /* buttons, pills, inputs */ .btn{border:1px solid #d0d5dd;border-radius:8px;padding:8px 14px;font-weight:600;font-size:13.5px;box-shadow:0 1px 2px rgba(16,24,40,.05);color:var(--ink2)} .btn:hover{background:#f9fafb;border-color:#b9c0cb} .btn.pri{background:var(--brand);border-color:var(--brand);box-shadow:0 1px 2px rgba(16,24,40,.08)} .btn.pri:hover{background:var(--brand2);border-color:var(--brand2)} .btn.sm{padding:5px 10px;font-size:12.5px;border-radius:7px} .btn.ai{background:#f4f1ff;border-color:#d9d0fb;color:#4b2fb3} .btn:focus-visible,.tabs button:focus-visible,nav a:focus-visible{outline:3px solid #a9c1ff;outline-offset:2px} .pill{border-radius:999px;font-weight:600;font-size:12px;padding:2px 10px} .p-gray{background:#f0f2f5;color:#344054} .bar input,.bar select,.compose select,.form input,.form select,.form textarea,.compose textarea{border:1px solid #d0d5dd;border-radius:8px;font-weight:400;box-shadow:0 1px 2px rgba(16,24,40,.04)} input:focus,select:focus,textarea:focus{outline:none;border-color:#84a5f5!important;box-shadow:0 0 0 3px #e3ebff!important} .form{grid-template-columns:repeat(4,minmax(0,1fr))} .form label{font-weight:500;font-size:12.5px;color:var(--ink2);min-width:0} .form input,.form select,.form textarea{width:100%;min-width:0}.form input[type=checkbox],.form input[type=radio]{width:auto;box-shadow:none;flex:0 0 auto} /* tabs */ .tabs{border-bottom:1px solid var(--line);gap:2px} .tabs button{font-weight:500;color:var(--muted);padding:10px 14px;border-bottom-width:2px} .tabs button.on{font-weight:600} /* modal */ .modal{border-radius:14px;box-shadow:0 24px 60px rgba(16,24,40,.22);overflow:hidden} .mh{padding:18px 24px}.mh h2{font-size:17px;font-weight:650} .mb{padding:20px 24px}.mf{padding:14px 24px;background:#fafbfc;border-radius:0} .x{background:transparent;border-radius:8px;color:var(--muted)}.x:hover{background:#f2f4f7} .ov{background:rgba(16,24,40,.45);backdrop-filter:blur(2px)} /* misc */ .empty{font-weight:400;color:var(--muted)} .hint{color:var(--muted)} .note{background:#f7f8fa;border-left-color:#9db4f5} .warn{border-radius:8px;font-weight:500} .col{background:#eef0f4;border-radius:12px} .deskhead h2{font-weight:700;font-size:26px} @media(max-width:900px){.app{grid-template-columns:72px 1fr}}`; const NAVICO=(()=>{const p={desk:'',dashboard:'', ai:'',inventory:'', finder:'',recon:'',website:'', feeds:'',fbpost:'',crm:'', equity:'',comms:'',desklog:'', deals:'',finance:'',accounts:'', collections:'',activity:'',titleadmin:'',forms:'', accounting:'',reports:'',settings:''}; const o={};for(const k in p)o[k]=``;return o})(); /* strip decorative emoji from labels, headings and buttons so screens read cleanly */ const EMOJI_RE=/(?:[\u{1F000}-\u{1FAFF}]|[\u{2600}-\u{269F}\u{26A1}-\u{26FF}]|[\u{2B06}\u{2B50}\u{2705}\u{274C}\u{1F1E6}-\u{1F1FF}])[\u{FE0F}\u{200D}]?/gu; const CLEAN_SEL='#nav,.top,.content h1,.content h2,.content h3,.content h4,.content th,.content button,.content .btn,.content .tabs,.content .pill,.content label,.content .empty,.content summary,.content .kpi,#modal h2,#modal h3,#modal h4,#modal button,#modal .btn,#modal label,#modal th,#modal .tabs,#modal summary,#modal .empty,#modal .phhead,.qlmenu,.qlinks'; function cleanEmoji(root){(root||document).querySelectorAll(CLEAN_SEL).forEach(el=>{const w=document.createTreeWalker(el,NodeFilter.SHOW_TEXT);let n;while(n=w.nextNode()){const pe=n.parentElement;if(!pe||/^(TEXTAREA|INPUT|SCRIPT|STYLE|OPTION)$/.test(pe.tagName)||pe.closest('.bub,.msgs,.doc'))continue;const t=n.nodeValue;if(EMOJI_RE.test(t)){EMOJI_RE.lastIndex=0;const c=t.replace(EMOJI_RE,'').replace(/^\s+(?=\S)/,m=>n.previousSibling?' ':'').replace(/\s{2,}/g,' ');n.nodeValue=c}EMOJI_RE.lastIndex=0}})} let _cleanQ=false;function queueClean(){if(_cleanQ)return;_cleanQ=true;(typeof requestAnimationFrame==="function"?requestAnimationFrame:setTimeout)(()=>{_cleanQ=false;try{cleanEmoji()}catch(e){}})} /* ================= Shared database (server) + staff sign-in ================= */ const LOCAL_SETTINGS=['user','syncSeq','esa','requireLogin','curStore']; const DBM={on:false,mode:false,token:'',seq:0,base:{},timer:null,poll:null,busy:false,pending:false,status:null,needRender:false,err:''}; const DBTK=workspaceStorage('lotledger_session'); function srvHeaders(){const h={};if(ESA().token)h['X-LotLedger-Token']=ESA().token;if(DBM.token)h['X-LotLedger-Session']=DBM.token;return h} const srvURL=p=>(ESA().server||'').replace(/\/$/,'')+p; async function dbFetch(p,opt={}){const h={...srvHeaders(),...(opt.body?{'Content-Type':'application/json'}:{})};try{const r=await fetch(srvURL(p),{method:opt.method||(opt.body?'POST':'GET'),headers:h,body:opt.body?JSON.stringify(opt.body):undefined});const b=await r.json().catch(()=>({}));if(r.status===401&&DBM.on&&!p.startsWith('/api/auth/'))dbSignedOut();return{ok:r.ok,status:r.status,body:b}}catch(e){return{ok:false,status:0,body:{error:'DealerPen server not reachable'}}}} const isRecArr=v=>Array.isArray(v)&&v.every(x=>x&&typeof x==='object'&&!Array.isArray(x)&&typeof x.id==='string'&&/^[\w.:-]{1,80}$/.test(x.id)); function dbDoc(c,x){if(c==='users'){const o={...x};delete o.pin;return o}if(c==='_'&&x&&typeof x==='object'&&!Array.isArray(x)&&x===S.settings){const o={...x};LOCAL_SETTINGS.forEach(k=>delete o[k]);return o}return x} function dbDocs(){const out={};for(const k of Object.keys(S)){if(!/^[\w-]{1,40}$/.test(k))continue;const v=S[k];if(v===undefined)continue; if(isRecArr(v)){for(const it of v)out[k+'\u0001'+it.id]=JSON.stringify(dbDoc(k,it))}else out['_\u0001'+k]=JSON.stringify(dbDoc('_',v))}return out} function dbDiff(){const cur=dbDocs(),ch=[];for(const [key,j] of Object.entries(cur))if(DBM.base[key]!==j){const [c,id]=key.split('\u0001');ch.push({c,id,doc:JSON.parse(j),_k:key,_j:j})} for(const key of Object.keys(DBM.base))if(!(key in cur)){const [c,id]=key.split('\u0001');ch.push({c,id,doc:null,_k:key,_j:undefined})}return ch} function dbSchedule(){if(!DBM.on)return;clearTimeout(DBM.timer);DBM.timer=setTimeout(dbPush,500)} async function dbPush(){if(!DBM.on)return;if(DBM.busy){DBM.pending=true;return}const ch=dbDiff();if(!ch.length)return;DBM.busy=true; try{const r=await dbFetch('/api/db/push',{body:{changes:ch.map(({c,id,doc})=>({c,id,doc}))}}); if(r.ok){r.body.results.forEach((res,i)=>{const x=ch[i];if(res.ok){if(x._j===undefined)delete DBM.base[x._k];else DBM.base[x._k]=x._j}else{DBM.err=res.error;delete DBM.base[x._k];dbApplyOne({c:x.c,id:x.id,doc:res.doc===undefined?null:res.doc},true);toast((res.error||'A change was not saved')+' It was undone.');softRender()}});DBM.seq=Math.max(DBM.seq,0);setSyncDot('ok')} else setSyncDot('off')}finally{DBM.busy=false;if(DBM.pending){DBM.pending=false;dbSchedule()}}} function dbApplyOne(ch,force){const key=ch.c+'\u0001'+ch.id;const cur=force?undefined:dbDocs()[key];if(cur!==undefined&&cur!==DBM.base[key]&&DBM.base[key]!==undefined)return false; // local edit waiting to be pushed wins if(ch.c==='_'){if(ch.id==='settings'){const keep={};LOCAL_SETTINGS.forEach(k=>{if(S.settings&&k in S.settings)keep[k]=S.settings[k]});S.settings=Object.assign({},ch.doc||{},keep)}else if(ch.doc===null)delete S[ch.id];else S[ch.id]=ch.doc} else{const a=S[ch.c]=Array.isArray(S[ch.c])?S[ch.c]:[];const i=a.findIndex(x=>x.id===ch.id);if(ch.doc===null){if(i>=0)a.splice(i,1)}else if(i>=0)a[i]=ch.doc;else a.push(ch.doc); if(ch.c==='users'&&ME&&ME.id===ch.id&&ch.doc)ME=a[i>=0?i:a.length-1]} if(ch.doc===null)delete DBM.base[key];else DBM.base[key]=JSON.stringify(dbDoc(ch.c,ch.c==='_'&&ch.id==='settings'?S.settings:ch.doc));return true} async function dbPoll(){if(!DBM.on||DBM.busy)return;const r=await dbFetch('/api/db/changes?since='+DBM.seq);if(!r.ok){setSyncDot('off');return}setSyncDot('ok'); const chs=r.body.changes||[];let n=0;for(const ch of chs){if(dbApplyOne(ch))n++;DBM.seq=Math.max(DBM.seq,ch.v)}DBM.seq=Math.max(DBM.seq,r.body.seq||0); if(n){try{localStorage.setItem(KEY,JSON.stringify(S))}catch(e){}softRender()}} function softRender(){if(route==='workspace'&&!$('#ov').classList.contains('on')){wsRefresh();return}drawTopIcons&&drawTopIcons();const busy=$('#ov').classList.contains('on')||(document.activeElement&&/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName));if(busy)DBM.needRender=true;else render()} function setSyncDot(st){DBM.status=st;const d=$('#syncdot');if(d){d.className='syncdot '+st;d.title=st==='ok'?'Shared database: up to date':'Shared database: can’t reach the server. Changes are kept on this computer and sent when it’s back.'}} async function dbLoadSnapshot(){const r=await dbFetch('/api/db/snapshot');if(!r.ok)throw new Error(r.body.error||'Could not load the shared database');const sn=r.body; const keep={};LOCAL_SETTINGS.forEach(k=>{if(S.settings&&k in S.settings)keep[k]=S.settings[k]});const fresh={}; for(const k of Object.keys(S))if(Array.isArray(S[k])&&isRecArr(S[k]))fresh[k]=[]; // nothing from this browser leaks into the shared copy for(const [c,docs] of Object.entries(sn.colls||{})){if(c==='_')for(const [id,d] of Object.entries(docs))fresh[id]=d;else fresh[c]=Object.values(docs)} if(!sn.empty){S=Object.assign({},fresh);S.settings=Object.assign({},fresh.settings||{},keep);migrate()} DBM.seq=sn.seq||0;DBM.base={};for(const [c,docs] of Object.entries(sn.colls||{}))for(const [id,d] of Object.entries(docs))DBM.base[c+'\u0001'+id]=JSON.stringify(c==='_'&&id==='settings'?dbDoc('_',S.settings):d);return sn} function dbStart(user){DBM.on=true;ME=S.users.find(u=>u.id===user.id)||user;try{if(!ui._logged){ui._logged=1;logAccess(ME,'Email & password')}}catch(e){}S.settings.user=ME.name;try{localStorage.setItem(KEY,JSON.stringify(S))}catch(e){} clearInterval(DBM.poll);DBM.poll=setInterval(dbPoll,4000);$('#login').classList.remove('on');if(!can(route))route=ALLM.find(can)||'dashboard';dbSchedule();render();setSyncDot('ok')} function dbSignedOut(){if(!DBM.on)return;DBM.on=false;clearInterval(DBM.poll);DBM.token='';try{localStorage.removeItem(DBTK)}catch(e){}ME=null;dbLogin()} async function dbBoot(){const r=await dbFetch('/api/auth/status');if(!r.ok||!r.body.dbEnabled)return false;DBM.mode=true;DBM.statusInfo=r.body; let t='';try{t=localStorage.getItem(DBTK)||''}catch(e){} if(t){DBM.token=t;const me_=await dbFetch('/api/auth/me');if(me_.ok){try{await dbLoadSnapshot();dbStart(me_.body.user);return true}catch(e){toast(e.message)}}DBM.token=''} dbLogin();return true} function dbForgotPassword(email){ const box=$('#login'); box.innerHTML=`

Reset your password

`; box.classList.add('on'); const form=$('#forgot-form'); const submit=form.querySelector('[type=submit]'); $('#forgot-back').onclick=()=>dbLogin(); form.elements.email.focus(); form.onsubmit=async event=>{ event.preventDefault(); submit.disabled=true; const result=await dbFetch('/api/auth/forgot-password',{body:{email:form.elements.email.value}}); form.querySelector('[role=status]').textContent=result.ok?'If an account matches that email, we’ll send a reset link. Check your inbox.':'Could not request a reset link. Please try again.'; submit.disabled=false; }; } function dbLogin(err){const st=DBM.statusInfo||{};const L=$('#login'); const head=``; L.innerHTML=st.needsSetup?`
${head}

Set up the owner account

This server has no accounts yet. Create the owner sign-in. Staff accounts are added later in Settings → Users.

${st.setupNeedsCode?'':''}
${esc(err||'')}
` :`
${head}
${esc(err||'')}
`; L.classList.add('on'); const forgot=$('#forgot-password');if(forgot)forgot.onclick=()=>dbForgotPassword($('#dblf').elements.email.value); const lf=$('#dblf');if(lf)lf.onsubmit=async e=>{e.preventDefault();const x=fd(lf);const r=await dbFetch('/api/auth/login',{body:{email:x.email,password:x.password}});if(!r.ok)return dbLogin(r.body.error||'Sign-in failed'); DBM.token=r.body.token;try{localStorage.setItem(DBTK,DBM.token)}catch(e){}try{await dbLoadSnapshot();dbStart(r.body.user);toast('Signed in as '+r.body.user.name)}catch(er){dbLogin(er.message)}}; const sf=$('#dbsf');if(sf)sf.onsubmit=async e=>{e.preventDefault();const x=fd(sf);const own=S.users.find(u=>u.role==='Owner'); const r=await dbFetch('/api/auth/setup',{body:{name:x.name,email:x.email,password:x.password,code:x.code||'',ownerId:x.start==='copy'?own?.id:''}});if(!r.ok)return dbLogin(r.body.error||'Setup failed'); DBM.token=r.body.token;try{localStorage.setItem(DBTK,DBM.token)}catch(e){}DBM.statusInfo.needsSetup=false; if(x.start==='copy'){const o=S.users.find(u=>u.id===r.body.user.id);if(o)Object.assign(o,{email:r.body.user.email,name:r.body.user.name,role:'Owner',active:true});else S.users.push(r.body.user); const all=dbDocs();const changes=Object.entries(all).map(([k,j])=>{const [c,id]=k.split('\u0001');return{c,id,doc:JSON.parse(j)}});const im=await dbFetch('/api/db/import',{body:{changes}});if(!im.ok)toast(im.body.error||'Import failed');else toast(im.body.imported+' records copied to the shared database')} else{const keepS=S.settings;S={...seed(),customers:[],vehicles:[],deals:[],loans:[],txns:[],comms:[]};S.settings=keepS;S.settings.sampleData=false;S.users=[r.body.user];const all=dbDocs();await dbFetch('/api/db/import',{body:{changes:Object.entries(all).map(([k,j])=>{const [c,id]=k.split('\u0001');return{c,id,doc:JSON.parse(j)}})}})} await dbLoadSnapshot();dbStart(r.body.user)}} async function dbSignOut(){await dbFetch('/api/auth/logout',{method:'POST',body:{}});DBM.on=false;clearInterval(DBM.poll);DBM.token='';try{localStorage.removeItem(DBTK)}catch(e){}ME=null;closeModal();dbLogin()} function pwModal(uid_){const self=!uid_||uid_===me()?.id;const u=uid_?S.users.find(x=>x.id===uid_):me(); openModal(mh(self?'Change your password':'Set password for '+esc(u.name))+`
${self&&me()?.role!=='Owner'?'':''} ${self?'':`

${esc(u.name)} signs in with ${esc(u.email||'(add an email first)')}. Setting a password signs them out on other computers.

`}
`); $('#pwf').onsubmit=async e=>{e.preventDefault();const x=fd(e.target);if(x.password!==x.password2)return toast('The passwords don’t match');dbSchedule();await dbPush(); const r=await dbFetch('/api/auth/password',{body:{userId:u.id,password:x.password,current:x.current||''}});if(!r.ok)return toast(r.body.error||'Not saved');closeModal();toast('Password saved')}} function dbCard(){if(!DBM.mode)return `

Shared database & staff sign-in

${storageMsg(1)} When DealerPen runs from the DealerPen server, everyone shares one live database and signs in with their own email and password. Setup steps are in the server README.

`; return `

Shared database & staff sign-in${DBM.status==='ok'?'Connected':'Reconnecting…'}

Signed in as${esc(me()?.name||'')} · ${esc(me()?.email||'')}
ChangesSaved to the server within a second

Staff sign in with the email on their user record. Set each person’s password in Users below. The server checks who is allowed to change users, roles, stores and settings.

`} /* ---- API keys & webhooks (owner) ---- */ async function apiCardLoad(){if(!DBM.on||me()?.role!=='Owner')return;const [k,w]=await Promise.all([dbFetch('/api/admin/keys'),dbFetch('/api/admin/webhooks')]);ui.apiKeys=k.ok?k.body:[];ui.hooks=w.ok?w.body:{events:[],hooks:[]};const el=$('#apicard');if(el)el.outerHTML=apiCard()} function apiCard(){if(me()?.role!=='Owner')return '';if(!DBM.on)return `

API & webhooks

API keys and webhooks let your website and other software read inventory and send leads in. They work when DealerPen runs from the DealerPen server with the shared database (see the server README).

`;const ks=ui.apiKeys,hs=ui.hooks;if(!ks){setTimeout(apiCardLoad,0)} return `

API & webhooksAPI docs ↗

Let your website, lead providers or other software read inventory and customers and send leads in. Keys are shown once when created. Revoke any key you no longer use.

${(ks||[]).filter(k=>!k.revoked).map(k=>``).join('')||''}
KeyAccessCreatedLast used
${esc(k.name)}
${esc(k.prefix)}…
${k.scope==='write'?'Read + send leads':'Read only'}${fdate(k.created.slice(0,10))}${k.lastUsed?ftime(k.lastUsed):'Never'}
No API keys

Webhooks

${((hs||{}).hooks||[]).map(h=>``).join('')||''}
URLEventsLast delivery
${esc(h.url)}${esc(h.events.join(', '))}${h.lastAt?ftime(h.lastAt)+' · '+esc(String(h.lastStatus)):'—'}
No webhooks
${((hs||{}).events||[]).map(e=>``).join('')}
`} async function apiNewKey(f){const x=fd(f);const r=await dbFetch('/api/admin/keys',{body:x});if(!r.ok)return toast(r.body.error||'Not created'); openModal(mh('Copy your new API key')+`

This is the only time the full key is shown. Store it somewhere safe, like your website host’s secret settings.

${esc(r.body.key)}
`)} async function apiRevoke(id){confirmBox('Revoke this key? Anything using it stops working right away.',async()=>{await dbFetch('/api/admin/keys/'+id,{method:'DELETE'});apiCardLoad()})} async function apiNewHook(f){const evs=[...f.querySelectorAll('input[name=ev]:checked')].map(i=>i.value);const r=await dbFetch('/api/admin/webhooks',{body:{url:f.url.value,events:evs}});if(!r.ok)return toast(r.body.error||'Not added'); openModal(mh('Webhook added')+`

Use this secret to check the LotLedger-Signature header on each delivery. It is shown once.

${esc(r.body.secret)}
`)} /* ================= Multi-store ================= */ const STORE_COLLS=['vehicles','deals','loans','floor','txns','onlineDeals','appraisals','creditApps','envelopes']; function stores(){S.stores=Array.isArray(S.stores)&&S.stores.length?S.stores:[{id:'st_main',name:S.settings.dealer||'Main store',address:S.settings.address||'',phone:S.settings.phone||''}];return S.stores} function myStores(){const u=me();const all=stores();return u&&u.role!=='Owner'&&Array.isArray(u.stores)&&u.stores.length?all.filter(s=>u.stores.includes(s.id)):all} function curStore(){const ms=myStores();let c=S.settings.curStore||'';if(ms.length===1)c=ms[0].id;if(c&&!ms.some(s=>s.id===c))c=ms.lengthstores().find(s=>s.id===id)?.name||''; function tagStores(){const st=curStore()||stores()[0].id;for(const k of STORE_COLLS)for(const x of (S[k]||[]))if(x&&!x.storeId)x.storeId=st;for(const c of (S.customers||[]))if(!c.storeId)c.storeId=st} function withStore(fn){const st=curStore();if(!st)return fn();const saved={};for(const k of STORE_COLLS)if(Array.isArray(S[k])){saved[k]=S[k];S[k]=S[k].filter(x=>!x.storeId||x.storeId===st)} try{return fn()}finally{for(const k in saved){const filt=S[k];const orig=saved[k];if(filt!==orig){filt.forEach(x=>{if(!orig.includes(x))orig.push(x)})}S[k]=orig}}} function storePicker(){const ms=myStores();if(stores().length<2)return '';const c=curStore(); return ``} function storesCard(){if(me()?.role!=='Owner')return '';return `

Stores

Each store keeps its own inventory, deals, accounts, desk log and accounting. Customers are shared, so everyone sees a customer’s full history across stores. Pick which stores each user works at in Users.

${stores().map(s=>``).join('')}
StoreAddressPhoneVehiclesDeals
${esc(s.name)}${esc(s.address||'')}${esc(s.phone||'')}${S.vehicles.filter(v=>(v.storeId||stores()[0].id)===s.id).length}${S.deals.filter(d=>(d.storeId||stores()[0].id)===s.id).length}
`} function storeModal(id){const s=id?stores().find(x=>x.id===id):{name:'',address:'',phone:'',dealerLicense:''}; openModal(mh(id?'Edit store':'Add store')+`
${id&&stores().length>1?'':''}
`); if($('#stdel'))$('#stdel').onclick=()=>{if(STORE_COLLS.some(k=>(S[k]||[]).some(x=>x.storeId===id)))return toast('Move or sell this store’s records first');S.stores=stores().filter(x=>x.id!==id);save();closeModal();render()}; $('#stf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(id)Object.assign(s,x);else{stores();S.stores.push({id:'st_'+uid(),...x})}save();closeModal();render();toast('Store saved')}} /* ================= Pay plans + payroll ================= */ function payPlans(){S.payPlans=Array.isArray(S.payPlans)&&S.payPlans.length?S.payPlans:[{id:'pp_std',name:'Standard sales',pct:+S.settings.commPct||25,mini:+S.settings.commMin||150,flat:0,tiers:[{units:10,bonus:500},{units:15,bonus:1000}],draw:0}];return S.payPlans} const planFor=u=>payPlans().find(p=>p.id===u?.payPlanId)||payPlans()[0]; function dealComm(d,p){return Math.max(+p.mini||0,(+d.gross||0)*(+p.pct||0)/100)+(+p.flat||0)} function payrollRows(from,to){const ds=S.deals.filter(d=>d.date>=from&&d.date<=to);const reps=S.users.filter(u=>u.active&&(ds.some(d=>d.salespersonId===u.id)||['Salesperson','Sales Manager','Desking Manager'].includes(u.role))); const adj=(S.payAdj||[]).filter(a=>a.date>=from&&a.date<=to); return reps.map(u=>{const p=planFor(u);const mine=ds.filter(d=>d.salespersonId===u.id);const comm=mine.reduce((a,d)=>a+dealComm(d,p),0);const units=mine.length; const tier=(p.tiers||[]).filter(t=>units>=+t.units).sort((a,b)=>b.units-a.units)[0];const bonus=tier?+tier.bonus:0;const ad=adj.filter(a=>a.userId===u.id);const adjT=ad.reduce((a,x)=>a+(+x.amount||0),0); const total=comm+bonus+adjT;return{u,p,mine,units,gross:mine.reduce((a,d)=>a+d.gross,0),comm,bonus,adj:ad,adjT,draw:+p.draw||0,total,due:total-(+p.draw||0)}})} function payrollView(){const from=ui.payFrom||TODAY.slice(0,7)+'-01',to=ui.payTo||TODAY;const rows=payrollRows(from,to); return `
${rows.map(r=>``).join('')||''}
SalespersonPay planUnitsFront grossCommissionUnit bonusSpiffs / adj.DrawDue
${esc(r.u.name)}
${esc(r.u.role)}
${esc(r.p.name)}${r.units}${$0(r.gross)}${$$(r.comm)}${$$(r.bonus)}${$$(r.adjT)}${r.draw?'−'+$$(r.draw):'—'}${$$(r.due)}
No salespeople
Total due${$$(rows.reduce((a,r)=>a+r.due,0))}

Commission per deal = the larger of the plan’s % of front gross or its minimum, plus any flat amount per unit. Unit bonuses use the highest tier reached in the period. Check totals with your accountant before paying.

`} function payStatement(uid_){const from=ui.payFrom||TODAY.slice(0,7)+'-01',to=ui.payTo||TODAY;const r=payrollRows(from,to).find(x=>x.u.id===uid_); openModal(mh('Commission statement · '+esc(r.u.name))+`
${fdate(from)} – ${fdate(to)} · plan: ${esc(r.p.name)} (${r.p.pct}% of front, ${$0(r.p.mini)} mini${r.p.flat?', +'+$0(r.p.flat)+'/unit':''})
${r.mine.map(d=>``).join('')||''} ${r.adj.map(a=>``).join('')} ${r.draw?``:''}
DealDateCustomerVehicleFront grossCommission
#${d.no}${fdate(d.date)}${esc(cust(d.customerId)?.name)}${esc(vname(veh(d.vehicleId)))}${$$(d.gross)}${$$(dealComm(d,r.p))}
No deals in this period
${esc(a.note||'Adjustment')} · ${fdate(a.date)}${$$(a.amount)}
Unit bonus${$$(r.bonus)}
Less draw−${$$(r.draw)}
Due${$$(r.due)}
`,true)} function payAdjModal(){openModal(mh('Spiff or adjustment')+`
`); $('#paf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);S.payAdj=S.payAdj||[];S.payAdj.push({id:uid(),...x,amount:+x.amount,by:S.settings.user});save();closeModal();render()}} function payPlansModal(){const ps=JSON.parse(JSON.stringify(payPlans())); const draw=()=>{$('#ppl').innerHTML=ps.map((p,i)=>`
${ps.length>1?``:''}
`).join(''); $('#ppl').querySelectorAll('input').forEach(el=>el.onchange=()=>{const p=ps[+el.dataset.i],k=el.dataset.k;if(k==='tiers')p.tiers=el.value.split(',').map(s=>s.split(':').map(Number)).filter(a=>a.length===2&&a[0]>0).map(a=>({units:a[0],bonus:a[1]}));else p[k]=k==='name'?el.value:+el.value}); $('#ppl').querySelectorAll('[data-x]').forEach(b=>b.onclick=()=>{ps.splice(+b.dataset.x,1);draw()})}; openModal(mh('Pay plans')+`

Who is on which plan

${S.users.filter(u=>u.active&&u.role!=='Recon Tech').map(u=>``).join('')}
`,true); draw();$('#ppa').onclick=()=>{ps.push({id:'pp_'+uid(),name:'New plan',pct:20,mini:100,flat:0,tiers:[],draw:0});draw()}; $('#pps').onclick=()=>{ps.forEach(p=>{if(!p.id)p.id='pp_'+uid()});S.payPlans=ps;document.querySelectorAll('[data-u]').forEach(s=>{const u=S.users.find(x=>x.id===s.dataset.u);if(u)u.payPlanId=s.value});save();closeModal();render();toast('Pay plans saved')}} async function payrollExport(){const from=ui.payFrom||TODAY.slice(0,7)+'-01',to=ui.payTo||TODAY;const rows=payrollRows(from,to);const q=v=>'"'+String(v??'').replace(/"/g,'""')+'"'; const csv=['employee,email,period_start,period_end,units,front_gross,commission,unit_bonus,adjustments,draw,amount_due'].concat(rows.map(r=>[q(r.u.name),q(r.u.email||''),from,to,r.units,r.gross.toFixed(2),r.comm.toFixed(2),r.bonus.toFixed(2),r.adjT.toFixed(2),r.draw.toFixed(2),r.due.toFixed(2)].join(','))).join('\n'); if(DL){try{await DL.save({filename:`payroll-${from}-to-${to}.csv`,data:csv});toast('Payroll file saved. Import it into your payroll service or send it to your accountant')}catch(e){if(e.code!=='declined')copyText(csv)}}else copyText(csv)} /* ================= Email campaigns ================= */ const validEmail=e=>/^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$/.test(String(e||'').trim()); async function emailStatus(force){if(!force&&ui.emailSt&&Date.now()-ui.emailSt.at<60000)return ui.emailSt;const r=await dbFetch('/api/email/status');ui.emailSt={at:Date.now(),ok:r.ok,...(r.ok?r.body:{ready:false})};return ui.emailSt} const EAUD={leads:['Open leads (New, Contacted, Appointment)',c=>isLead(c)],sold:['Past customers (bought from us)',c=>c.stage==='Sold'],lost:['Lost leads',c=>c.stage==='Lost'],equity:['Customers with positive equity',c=>equityRows().some(r=>r.c.id===c.id&&r.eq>0)],bhph:['BHPH customers in good standing',c=>S.loans.some(l=>l.customerId===c.id&&l.status==='Active'&&!daysLate(l))],all:['Everyone',()=>true]}; function campAudience(key,src){const f=(EAUD[key]||EAUD.leads)[1];return S.customers.filter(c=>f(c)&&(!src||c.source===src))} function campSendable(list){return list.filter(c=>validEmail(c.email)&&!c.emailOptOut&&!c.emailInvalid)} function emailView(){const st=ui.emailSt;if(!st)emailStatus().then(()=>route==='crm'&&ui.crmView==='email'&&render());const cs=(S.campaigns||[]).slice().reverse(); return `${st&&!st.ready?`
Email sending isn’t set up on the DealerPen server yet${st.missing&&st.missing.length?` (missing: ${esc(st.missing.join(', '))})`:''}. You can still build campaigns and download the audience list.
`:''}
Marketing emails always include your dealership address and an unsubscribe link. People who unsubscribe are never emailed again.
${cs.map(c=>``).join('')||''}
CampaignAudienceStatusSent
${esc(c.name)}
${esc(c.subject)}
${esc((EAUD[c.aud]||EAUD.leads)[0])}${c.src?' · '+esc(c.src):''}${c.sentAt?`Sent ${fdate(c.sentAt.slice(0,10))}`:'Draft'}${c.sent||0}
No campaigns yet
`} function campModal(id){S.campaigns=S.campaigns||[];const c=id?S.campaigns.find(x=>x.id===id):{id:'',name:'',aud:'leads',src:'',subject:'',body:'Hi {first},\n\n\n\nThanks,\n{rep}\n{dealer}'};const sent=!!c.sentAt; openModal(mh(id?esc(c.name):'New email campaign')+`
${aiOn('leads')&&!sent?``:''}
${sent?'':``}
`,true); const f=$('#cmf');const read=()=>({...c,...fd(f)});const cnt=()=>{const x=read();const a=campAudience(x.aud,x.src),ok=campSendable(a);$('#cmcount').innerHTML=sent?`Sent to ${c.sent} people on ${ftime(c.sentAt)}.`:`${ok.length} of ${a.length} people in this audience can be emailed. Skipped: no or invalid email, or unsubscribed.`};f.oninput=cnt;cnt(); const merge_=(t,cu)=>t.replace(/\{first\}/g,(cu.name||'').split(' ')[0]).replace(/\{name\}/g,cu.name||'').replace(/\{vehicle\}/g,cu.interest||'your next vehicle').replace(/\{rep\}/g,uname(cu.ownerId)!=='—'?uname(cu.ownerId):(me()?.name||'')).replace(/\{dealer\}/g,S.settings.dealer||'').replace(/\{phone\}/g,S.settings.phone||''); const keep=()=>{const x=read();if(!x.id){x.id=uid();S.campaigns.push(x)}else Object.assign(S.campaigns.find(z=>z.id===x.id),x);c.id=x.id;save();return S.campaigns.find(z=>z.id===x.id)}; $('#cmcsv').onclick=async()=>{const x=read();const q=v=>'"'+String(v??'').replace(/"/g,'""')+'"';const csv='name,email,phone,stage,source\n'+campSendable(campAudience(x.aud,x.src)).map(cu=>[q(cu.name),q(cu.email),q(cu.phone),q(cu.stage),q(cu.source)].join(',')).join('\n');if(DL){try{await DL.save({filename:'email-audience.csv',data:csv})}catch(e){if(e.code!=='declined')copyText(csv)}}else copyText(csv)}; if(sent)return;$('#cmsave').onclick=()=>{if(!f.reportValidity())return;keep();closeModal();render();toast('Draft saved')}; if($('#cmai'))$('#cmai').onclick=async()=>{const x=read();try{const t=await ai(`Write a short, friendly marketing email from ${S.settings.dealer}, a used-car dealership, to this audience: ${(EAUD[x.aud]||EAUD.leads)[0]}. Topic/notes: ${x.subject||x.name||'monthly specials'}. Use the fill-in {first} for the first name and sign off with {rep} and {dealer}. Plain text, under 120 words, no made-up prices, rates or promises. Reply with JSON {"subject":"","body":""}.`,{nocache:true});f.subject.value=t.subject||f.subject.value;f.body.value=t.body||f.body.value;cnt()}catch(e){toast(aiErrMsg(e))}}; $('#cmtest').onclick=async()=>{const x=read();const u=me();if(!validEmail(u?.email))return toast('Add your email to your user record first');const r=await dbFetch('/api/email/send',{body:{subject:'[Test] '+x.subject,to:[{email:u.email,name:u.name,text:merge_(x.body,{name:u.name,interest:'2019 Honda Accord',ownerId:u.id})}]}});toast(r.ok&&r.body.sent?'Test sent to '+u.email:(r.body.error||r.body.results?.[0]?.error||'Test failed'))}; f.onsubmit=async e=>{e.preventDefault();const x=keep();const list=campSendable(campAudience(x.aud,x.src));if(!list.length)return toast('Nobody in this audience can be emailed'); confirmBox(`Send “${esc(x.subject)}” to ${list.length} people now?`,async()=>{toast('Sending…');const r=await dbFetch('/api/email/send',{body:{subject:x.subject,to:list.map(cu=>({email:cu.email,name:cu.name,customerId:cu.id,text:merge_(x.body,cu)}))}}); if(!r.ok)return toast(r.body.error||'Sending failed');x.sentAt=nowAt();x.sent=r.body.sent;(r.body.results||[]).forEach(res=>{const cu=S.customers.find(z=>z.id===res.customerId);if(!cu)return;if(res.ok)logComm({customerId:cu.id,channel:'email',dir:'out',body:`[Campaign: ${x.name}] ${x.subject}`});else if(res.error==='unsubscribed')cu.emailOptOut=true;else if(res.error==='invalid')cu.emailInvalid=true}); save();closeModal();render();toast(`Sent to ${r.body.sent} people`)})}} function emailModal(cid){const c=cust(cid);if(!validEmail(c.email))return toast('This customer has no valid email');if(c.emailOptOut)return toast(c.name+' unsubscribed from emails'); openModal(mh('Email '+esc(c.name))+`
To ${esc(c.email)}
`); const f=$('#emf');const upd=()=>$('#emo').href=`mailto:${encodeURIComponent(c.email)}?subject=${encodeURIComponent(f.subject.value)}&body=${encodeURIComponent(f.body.value)}`;f.oninput=upd;upd(); $('#emo').addEventListener('click',()=>{logComm({customerId:cid,channel:'email',dir:'out',body:f.subject.value});save();setTimeout(()=>{closeModal();render()},300)}); f.onsubmit=async e=>{e.preventDefault();const st=await emailStatus();if(!st.ready)return toast('Use “Open in my email app”. Email sending isn’t set up on the server yet');const r=await dbFetch('/api/email/send',{body:{subject:f.subject.value,to:[{email:c.email,name:c.name,customerId:cid,text:f.body.value}]}}); if(!r.ok||!r.body.sent)return toast(r.body.error||r.body.results?.[0]?.error||'Not sent');logComm({customerId:cid,channel:'email',dir:'out',body:f.subject.value+'\n'+f.body.value});save();closeModal();render();promptNext(cid);toast('Email sent')}} /* ================= Duplicate finder + merge ================= */ const normPhone=p=>String(p||'').replace(/\D/g,'').slice(-10); const normName=n=>String(n||'').toLowerCase().replace(/[^a-z ]/g,'').replace(/\s+/g,' ').trim(); function dupGroups(only){const map=new Map();const add=(k,c)=>{if(!k)return;if(!map.has(k))map.set(k,new Set());map.get(k).add(c.id)}; for(const c of S.customers){const p=normPhone(c.phone);if(p.length===10)add('p:'+p,c);if(validEmail(c.email))add('e:'+c.email.trim().toLowerCase(),c);const n=normName(c.name);if(n.split(' ').length>1&&c.address)add('n:'+n+'|'+String(c.address).toLowerCase().replace(/\W/g,'').slice(0,12),c)} const groups=[],seen=new Set();for(const [k,set] of map)if(set.size>1){const ids=[...set].sort().join(',');if(seen.has(ids))continue;seen.add(ids);groups.push({why:k[0]==='p'?'Same phone':k[0]==='e'?'Same email':'Same name and address',ids:[...set]})} return only?groups.filter(g=>g.ids.includes(only)):groups} function cleanupView(){const g=dupGroups();const bad=S.customers.filter(c=>c.email&&!validEmail(c.email)&&!c.emailInvalid); return `

Possible duplicates${g.length}

${g.length?`${g.map((x,i)=>``).join('')}
${x.ids.map(id=>`${esc(cust(id)?.name)} ${esc(cust(id)?.phone||cust(id)?.email||'')}`).join('
')}
${x.why}
`:'
No duplicates found
'}

Emails that can’t be delivered${bad.length?``:''}

${bad.length?`${bad.map(c=>``).join('')}
${esc(c.name)}${esc(c.email)}
`:'
All emails look valid
'}
`} function mergeModal(idsCsv){const ids=idsCsv.split(',').filter(id=>cust(id));if(ids.length<2)return toast('Nothing to merge');const F_=['name','phone','email','address','employer','income','source','interest','ownerId']; openModal(mh('Merge duplicate customers')+`

Pick the record to keep. Blank fields on it are filled from the others, and every note, call, text, deal, account and document moves to it. The other records are removed.

${F_.map(f=>``).join('')}${ids.map((id,i)=>{const c=cust(id);return `${F_.map(f=>``).join('')}`}).join('')}
Keep${f==='ownerId'?'Rep':f[0].toUpperCase()+f.slice(1)}Activity
${esc(f==='ownerId'?uname(c[f]):c[f]||'')}${(c.notes||[]).length+S.comms.filter(x=>x.customerId===id).length}
`,true); $('#mgo').onclick=()=>{const keep=document.querySelector('input[name=keep]:checked').value;mergeCustomers(keep,ids.filter(x=>x!==keep));closeModal();if(route==='cust')ui.custId=keep;render();toast('Merged')}} function mergeCustomers(keepId,others){const k=cust(keepId);for(const oid of others){const o=cust(oid);if(!o)continue; for(const f of Object.keys(o))if(k[f]===undefined||k[f]===''||k[f]===null||k[f]===0)k[f]=o[f]; k.notes=[...(k.notes||[]),...(o.notes||[])].sort((a,b)=>String(a.date).localeCompare(String(b.date)));k.files=[...(k.files||[]),...(o.files||[])];k.tasks=[...(k.tasks||[]),...(o.tasks||[])]; for(const key of Object.keys(S)){const arr=S[key];if(!Array.isArray(arr))continue;for(const x of arr)if(x&&typeof x==='object'){if(x.customerId===oid)x.customerId=keepId;if(x.cobuyerId===oid)x.cobuyerId=keepId}} if(S.finder)for(const w of [...(S.finder.wants||[]),...(S.finder.found||[])])if(w.customerId===oid)w.customerId=keepId; S.customers=S.customers.filter(x=>x.id!==oid);k.notes.push({date:TODAY,by:S.settings.user,text:`Merged duplicate record “${o.name}” into this one`})}save()} /* ================= New customer from ID / photo / document ================= */ let PDFJS=null; async function loadPdfJs(){if(PDFJS)return PDFJS;await new Promise((res,rej)=>{const s=document.createElement('script');s.src='https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js';s.onload=res;s.onerror=()=>rej(new Error('Could not load the PDF reader'));document.head.appendChild(s)}); PDFJS=window.pdfjsLib;try{PDFJS.GlobalWorkerOptions.workerSrc='https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'}catch(e){}return PDFJS} async function fileToImages(file){if(/^image\//.test(file.type))return [await shrink(file,1800,0.88)]; if(file.type==='application/pdf'||/\.pdf$/i.test(file.name)){const lib=await loadPdfJs();const pdf=await lib.getDocument({data:await file.arrayBuffer()}).promise;const out=[]; for(let i=1;i<=Math.min(pdf.numPages,3);i++){const pg=await pdf.getPage(i);const vp=pg.getViewport({scale:1.6});const c=document.createElement('canvas');c.width=vp.width;c.height=vp.height;await pg.render({canvasContext:c.getContext('2d'),viewport:vp}).promise;out.push(await new Promise(r=>c.toBlob(r,'image/jpeg',0.85)))}return out} throw new Error('Use a photo (JPG, PNG) or a PDF')} const DOC_PROMPT=`These images were provided by a car dealership, with the customer's permission, to create or update the customer's record. They may show a driver's license or state ID, insurance card, pay stub, utility bill, bank statement, credit application, or business card. Read them carefully. Reply with only JSON: {"docType":"drivers_license|state_id|insurance_card|pay_stub|utility_bill|credit_application|business_card|other","first":"","middle":"","last":"","address":"street, city, ST zip","phone":"","email":"","dob":"YYYY-MM-DD","dl_number":"","dl_state":"","dl_expires":"YYYY-MM-DD","employer":"","monthly_income":0,"insurance_company":"","insurance_policy":"","cobuyer_name":"","readable":true} Use empty strings or 0 for anything not shown or not clearly readable. Never guess. For a pay stub, convert gross pay to a monthly amount only if the pay period is shown.`; async function readCustomerDoc(files){if(!SAMPLE)throw new Error('Reading documents uses AI and works when DealerPen is open inside Claude');const imgs=[];for(const f of [...files].slice(0,3))imgs.push(...await fileToImages(f)); const r=await ai(DOC_PROMPT,{images:imgs.slice(0,4),tier:'default',nocache:true});if(!r||r.readable===false)throw new Error('Couldn\u2019t read that. Try a clearer photo with good light');return{r,imgs}} function docToCustomer(r){const name=[r.first,r.middle?r.middle[0]:'',r.last].filter(Boolean).join(' ');const o={name,address:r.address||'',phone:r.phone||'',email:r.email||'',employer:r.employer||'',income:+r.monthly_income||''}; if(r.dob)o.dob=r.dob;if(r.dl_number)Object.assign(o,{dlNo:r.dl_number,dlState:r.dl_state||'',dlExp:r.dl_expires||''});if(r.insurance_company)Object.assign(o,{insCo:r.insurance_company,insPolicy:r.insurance_policy||''});if(r.cobuyer_name)o.cobuyer={name:r.cobuyer_name};return o} async function storeCustFiles(c,blobs,label){c.files=c.files||[];for(const b of blobs){try{if(ASSETS){const up=await ASSETS.upload(b,{type:b.type||'image/jpeg'});c.files.push({id:up.id,src:'a',name:label,type:b.type||'image/jpeg',at:nowAt(),by:S.settings.user})}else{const id=uid();await idbOp('readwrite',s=>s.put(b,id));IDBURL[id]=URL.createObjectURL(b);c.files.push({id,src:'i',name:label,type:b.type||'image/jpeg',at:nowAt(),by:S.settings.user})}}catch(e){}}} function newCustomerFrom(kind){ const read=async files=>{if(!files.length)return;toast('Reading…');try{const {r,imgs}=await readCustomerDoc(files);const pre=docToCustomer(r);if(r.dl_expires&&r.dl_expires(pre.phone&&normPhone(c.phone)===normPhone(pre.phone))||(validEmail(pre.email)&&c.email&&c.email.toLowerCase()===pre.email.toLowerCase())||(pre.dlNo&&c.dlNo===pre.dlNo)); if(dupe){confirmBox(`${esc(dupe.name)} is already a customer and looks like the same person. Update their record instead of creating a new one?`,async()=>{for(const [k,v] of Object.entries(pre))if(v&&!dupe[k])dupe[k]=v;await storeCustFiles(dupe,imgs,(r.docType||'document').replace(/_/g,' '));dupe.notes.push({date:TODAY,by:S.settings.user,text:'Document scanned: '+(r.docType||'document').replace(/_/g,' ')});save();openCustomer(dupe.id)});return} ui.pendingScan={imgs,label:(r.docType||'document').replace(/_/g,' ')};custModal(null,{...pre,source:'Walk-in',_scanned:r.docType});toast('Details filled in. Please check them')} catch(e){toast(e.code==='images_unavailable'?'Photos aren\u2019t supported here':e.message||aiErrMsg(e))}}; if(kind!=='doc')return takeGuidedPhoto(file=>read([file])); const input=document.createElement('input');input.type='file';input.accept='image/*,application/pdf';input.multiple=true; input.onchange=()=>read(input.files);input.click(); } const scanBar=()=>`
Start from a document:
`; /* ================= Customer workspace (full page) ================= */ const CSTEPS=['New','Contacted','Appointment','Sold','Lost']; function openCustomer(id){if(!cust(id))return;closeModal();ui.custId=id;ui.cTab=ui.cTab||'lead';ui.cSide=ui.cSide||'buyer';if(route==='cust')render();else{ui.custBack=route;go('cust')}} function setCust(id,k,v){const c=cust(id);if(!c)return;const old=c[k];if(String(old??'')===String(v??''))return;c[k]=v;if(['ownerId','bdcId','stage'].includes(k))c.notes.push({date:TODAY,by:S.settings.user,text:`${k==='ownerId'?'Sales rep':k==='bdcId'?'BDC rep':'Stage'} changed${k==='stage'?` ${old} → ${v}`:` to ${uname(v)}`}`});save();if(['stage','ownerId'].includes(k))render()} function setSub(id,sub,k,v){const c=cust(id);c[sub]=c[sub]||{};c[sub][k]=v;save()} function custActivity(c){const items=[];(c.notes||[]).forEach((n,i)=>items.push({t:/^(Stage|Sales rep|BDC rep|Merged|Started follow-up|Reassigned)/.test(n.text)?'log':/^Completed: Appointment|Appointment/.test(n.text)?'appt':'note',at:n.date+(n.time?'T'+n.time:''),by:n.by,title:'Note',body:n.text})); S.comms.filter(x=>x.customerId===c.id).forEach(x=>items.push({t:x.channel==='call'?'call':x.channel==='email'?'email':x.channel==='chat'||x.channel==='social'?'chat':'text',at:x.at,by:x.by||(x.dir==='in'?c.name:''),title:x.channel==='social'?`${x.platform==='instagram'?'Instagram':'Facebook'} message ${x.dir==='in'?'received':'sent'}`:x.channel==='call'?`${x.dir==='in'?'Incoming':'Outgoing'} call${x.outcome?' · '+x.outcome:''}${x.duration?' · '+fdur(x.duration):''}`:x.channel==='email'?(x.dir==='in'?'Email received':'Email sent'):(x.dir==='in'?'Text received':'Text sent'),body:x.body||'',rec:x.rec})); (c.tasks||[]).forEach(tk=>items.push({t:'task',at:tk.due||tk.at,by:tk.by,title:`Task${tk.done?' · done':''}`,body:tk.text,task:tk})); S.deals.filter(d=>d.customerId===c.id).forEach(d=>items.push({t:'log',at:d.date,by:uname(d.salespersonId),title:`Deal #${d.no} · ${d.type}`,body:`${vname(veh(d.vehicleId))} · ${$$(d.price)}`})); return items.sort((a,b)=>String(b.at).localeCompare(String(a.at)))} function interestVeh(c){if(c.vehicleId&&veh(c.vehicleId))return veh(c.vehicleId);const t=String(c.interest||'').toLowerCase();if(!t)return null;return S.vehicles.find(v=>t.includes(String(v.stock).toLowerCase()))||S.vehicles.find(v=>v.status!=='Sold'&&t.includes(`${v.year} ${v.make} ${v.model}`.toLowerCase()))||S.vehicles.find(v=>v.status!=='Sold'&&t.includes(`${v.make} ${v.model}`.toLowerCase()))||null} VIEWS.cust=()=>{const c=cust(ui.custId);if(!c)return `
Customer not found. Back to Leads & CRM
`; const deals=S.deals.filter(d=>d.customerId===c.id),loans=S.loans.filter(l=>l.customerId===c.id),cm=S.comms.filter(x=>x.customerId===c.id).sort((a,b)=>b.at.localeCompare(a.at)); const lastOut=cm.find(x=>x.dir==='out'),lastAny=cm[0];const overdue=(c.tasks||[]).filter(t=>!t.done&&t.due&&t.due!t.done).length+(c.next?1:0); const created=c.created||(c.createdAt||'').slice(0,10)||TODAY;const lastAct=[lastAny?.at?.slice(0,10),...(c.notes||[]).map(n=>n.date)].filter(Boolean).sort().pop()||created; const si=CSTEPS.indexOf(c.stage);const dupes=dupGroups(c.id).length;const v=interestVeh(c);const users=S.users.filter(u=>u.active); const fld=(label,k,type,opts)=>``; const sub=(s,label,k)=>``; const left=ui.cSide==='co'?`${sub('cobuyer','Name','name')}${sub('cobuyer','Cell phone','phone')}${sub('cobuyer','Email','email')}${sub('cobuyer','Address','address')}${sub('cobuyer','Date of birth','dob')}${sub('cobuyer','Employer','employer')}${sub('cobuyer','Monthly income','income')}${sub('cobuyer','Relationship','relationship')}

A co-buyer is added to deals and contracts for this customer.

` :ui.cSide==='ref'?`${sub('referrer','Referred by','name')}${sub('referrer','Phone','phone')}${sub('referrer','Relationship','relationship')}${sub('referrer','Referral reward','reward')}` :`${fld('Name','name')}${fld('Cell phone','phone','tel')}${fld('Home phone','homePhone','tel')}${fld('Work phone','workPhone','tel')}${fld('Email','email','email')}${fld('Address','address')} ${fld('Lead type','leadType','',['Internet','Walk-in','Phone','Referral','Repeat','Service','Social'])}${fld('Lead source','source','',['Walk-in','Website','Phone','Referral','Facebook','Marketplace','Cars.com','CarGurus','Autotrader','Repeat customer','Online deal'])} ${fld('Inquiry type','inquiry','',['Specific vehicle','Shopping','Financing','Trade-in','Pricing'])}${fld('Language','lang','',['English','Spanish','Vietnamese','Chinese','Arabic','Other'])}${fld('Contact by','prefContact','',['Call','Text','Email'])}${fld('Best time','bestTime','',['Morning','Afternoon','Evening','Weekends'])}
${['bdcId:BDC rep','ownerId:Sales rep'].map(x=>{const [k,l]=x.split(':');return ``}).join('')}
`; const tabs=[['lead','Lead'],['engage','Engagement'],['credit','Credit app'],['prequal','Pre-qual'],['vehicle','Vehicle'],['deals','Deals'+(deals.length?` (${deals.length})`:'')],['files','Files'+((c.files||[]).length?` (${c.files.length})`:'')],['compliance','Compliance'],['dupes','Duplicates'+(dupes?` (${dupes})`:'')],['acct','Accounting'+(loans.length?` (${loans.length})`:'')],['logs','Logs']]; return `
${custNavBar(c)}

${esc(c.name)}

${esc(subOf(c))}${heatPill(heat(c))}${c.mgrReview?'Manager review':''}
${ui.cMenu?``:''}
    ${(()=>{const cur=subOf(c),ci=CSUB.findIndex(x=>x[0]===cur);return CSUB.map(([s],i)=>`
  1. `).join('')})()}
${complStrip(c)}
${(()=>{const lastAppt=(c.notes||[]).filter(n=>/Appointment|Checked in/.test(n.text)).map(n=>n.date).sort().pop();const dep=depTotal(c);const pend=deals.filter(d=>!['Funded','Complete','Closed'].includes(d.status||'')).length;const lastAtt=cm.filter(x=>x.dir==='out')[0]; return `
Next appt.${c.next&&/Appointment|Test drive|Visit/.test(c.next.type)?esc(nxLabel(c.next)):'Not scheduled'}Last appt.${lastAppt?fdate(lastAppt):'None'}
Overdue tasks${overdue?overdue+' late':'None'}Pending tasks${pending||'None'}
Deposit${dep?$0(dep)+' · ':''}${dep?'Manage':'Take deposit'}Deals${deals.length?`${deals.length} · ${fdate(deals[deals.length-1].date)}`:'None'}
Last contact attempt${lastAtt?ftime(lastAtt.at):'Never'}Last contacted${lastAny?ftime(lastAny.at):'Never'}
Days old${Math.max(0,diff(created,TODAY))}Days since activity${Math.max(0,diff(lastAct,TODAY))}
`})()}
${[['buyer','Buyer'],['co','Co-buyer'],['ref','Referrer']].map(t=>``).join('')}
${left}
${tabs.map(t=>``).join('')}
${custTab(c,deals,loans)}
${custVehicleCard(c,v)}
`}; function custTab(c,deals,loans){const t=ui.cTab||'lead'; if(t==='lead'){const f=ui.cFeed||'all',q=(ui.cQ||'').toLowerCase();const all=custActivity(c);const list=all.filter(x=>(f==='all'||x.t===f)&&(!q||(x.title+' '+x.body).toLowerCase().includes(q))); const cnt=k=>all.filter(x=>x.t===k).length; return `
Workflow ${c.plan&&c.plan.status==='Active'?esc(planOf(c.plan.id)?.name||'Follow-up plan'):'None'}${c.plan&&c.plan.status==='Active'?'':`Start`}
${c.next?`
Next step: ${esc(nxLabel(c.next))}${c.next.note?`
${esc(c.next.note)}
`:''}
`:isLead(c)?`
No next step is scheduled. Set one
`:''}

Activity (${all.length})

${[['all','All'],['note','Notes'],['appt','Appts'],['call','Calls'],['text','Texts'],['email','Email'],['chat','Chat'],['task','Tasks'],['log','Other']].map(x=>``).join('')}
${list.map(x=>`
${esc(x.title)}${esc(x.by||'')} · ${String(x.at).length>10?ftime(x.at):fdate(x.at)}
${esc(x.body)}
${x.rec?``:''}${x.task&&!x.task.done?``:''}
`).join('')||'
No activity matches
'}
`} if(t==='credit'){const apps=(S.creditApps||[]).filter(a=>a.customerId===c.id);return `
Applications for this customer
${apps.map(a=>``).join('')||''}
DateLenderAmountStatus
${fdate((a.created||'').slice(0,10))}${esc(a.lender||a.portal||'')}${$0(a.amount)}${appPill(a.status)}
No credit applications yet

On file

Employer${esc(c.employer||'—')}
Monthly income${c.income?$0(c.income):'—'}
Date of birth${c.dob?fdate(c.dob):'—'}
Driver\u2019s license${c.dlNo?esc((c.dlState||'')+' ••••'+String(c.dlNo).slice(-4)):'—'}
Insurance${esc(c.insCo||'—')}
`} if(t==='vehicle'){const avail=S.vehicles.filter(v=>v.status==='Available');return `

Vehicle of interest

Other matches in stock

${avail.filter(v=>!c.income||v.price<=c.income*8).slice(0,8).map(v=>``).join('')}
${esc(vname(v))}
${v.stock} · ${(+v.miles).toLocaleString()} mi
${$0(v.price)}
`} if(t==='deals')return `
${deals.length?dealTable(deals):'
No deals yet
'}
${(S.onlineDeals||[]).filter(o=>o.customerId===c.id).length?`

Online deals

${(S.onlineDeals||[]).filter(o=>o.customerId===c.id).map(o=>`
${ftime(o.at)} · ${esc(o.stock||'')} · ${o.type} · ${$0(o.down)} down · ${o.term} mo
`).join('')}
`:''}`; if(t==='files'){const fs_=c.files||[];return `
Driver\u2019s license, insurance, pay stubs, signed paperwork
${fs_.map((f,i)=>{const url=photoURL(f);return `
${/^image\//.test(f.type)&&url?`${esc(f.name)}`:`
PDF
`}
${esc(f.name)}
${ftime(f.at)} · ${esc(f.by||'')}
${url?`Open`:''}
`}).join('')||'
No files yet
'}
`} if(t==='compliance'){const ok=(b,l,h)=>`${b?'Done':'Open'}${l}
${h}
`; return `

Compliance checklist

${ok(c.smsConsent,'Text consent recorded','Needed before automated texts (TCPA). Turn on “OK to text” only with the customer\u2019s permission.')}${ok(!!c.dlNo,'ID verified','Scan the driver\u2019s license (Red Flags Rule identity check).')}${ok(!!c.ofacAt,'OFAC check','Search the Treasury OFAC list, then mark it done.')}${ok(!!c.privacyAt,'Privacy notice given','Required for financed deals (GLBA).')}${ok(!c.dnc||true,'Do-not-call respected',c.dnc?'Customer asked not to be called.':'No do-not-call request on file.')}
Open OFAC search ↗

Adverse action notices are sent from the credit application when a lender declines. This checklist helps your process; it isn\u2019t legal advice.

`} if(t==='dupes'){const g=dupGroups(c.id);return `

Possible duplicates of ${esc(c.name)}

${g.length?g.map(x=>`
${x.ids.filter(i=>i!==c.id).map(i=>`${esc(cust(i)?.name)} ${esc(cust(i)?.phone||'')} ${esc(cust(i)?.email||'')}`).join('
')}
${x.why}
`).join(''):'
No duplicates found for this customer
'}
`} if(t==='acct')return `
${loans.map(l=>``).join('')||''}
AccountVehicleStatusBalancePast due
${l.acct}${esc(vname(veh(l.vehicleId)))}${l.status==='Active'?latePill(daysLate(l)):statusPill(l.status)}${$$(l.balance)}${$$(pastDue(l))}${l.status==='Active'?` `:''}
No financed accounts
`; if(t==='logs'){const logs=custActivity(c).filter(x=>x.t==='log');return `
${logs.map(x=>`
${esc(x.title)}: ${esc(x.body)}
${esc(x.by||'')} · ${fdate(String(x.at).slice(0,10))}
`).join('')||'
No system changes logged
'}
`} return ''} function custVehicleCard(c,v){if(!v)return `

Interested vehicle

${c.interest?esc(c.interest)+'
':''}No vehicle picked
`; const ph=mainPhoto(v);const vin=encodeURIComponent(v.vin||''); return `

Interested vehicle

${ph?`${esc(vname(v))}`:'No photo yet'}
${esc(vname(v))}
Price${$0(v.price)}
Stock #${esc(v.stock)}
Miles${(+v.miles).toLocaleString()}
Days in stock${age(v)}
Color${esc(v.color||'—')}
Status${esc(v.status)}
${esc(v.vin||'')}
${v.status==='Available'?``:''}

Vehicle history reports

Reports need your dealer account with each provider.

`} function noteModal(cid){openModal(mh('Add note')+`
`);$('#ntf').t.focus(); $('#ntf').onsubmit=e=>{e.preventDefault();const c=cust(cid);c.notes.push({date:TODAY,time:new Date().toTimeString().slice(0,5),by:S.settings.user,text:e.target.t.value.trim()});save();closeModal();render();promptNext(cid)}} function taskModal(cid){openModal(mh('Add task')+`
`); $('#tkf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const c=cust(cid);c.tasks=c.tasks||[];c.tasks.push({id:uid(),...x,at:nowAt(),by:S.settings.user,done:false});save();closeModal();render()}} function taskDone(cid,tid){const c=cust(cid);const t=(c.tasks||[]).find(x=>x.id===tid);if(t){t.done=true;t.doneAt=nowAt();c.notes.push({date:TODAY,by:S.settings.user,text:'Task done: '+t.text});save();render()}} function creditAppFor(cid){const c=cust(cid);if(typeof appModal==='function'){appModal(null,cid)}else creditApp()} function privacyNotice(cid){const c=cust(cid);c.privacyAt=nowAt();c.notes.push({date:TODAY,by:S.settings.user,text:'Privacy notice given'});save();toast('Logged. Print it from Forms if you give it on paper');render()} function newDocFor(cid){const inp=document.createElement('input');inp.type='file';inp.accept='image/*,application/pdf';inp.multiple=true;inp.onchange=async()=>{if(!inp.files.length)return;toast('Reading…');try{const {r,imgs}=await readCustomerDoc(inp.files);const c=cust(cid);const pre=docToCustomer(r);const filled=[]; for(const [k,v] of Object.entries(pre)){if(k==='cobuyer'){if(!(c.cobuyer||{}).name){c.cobuyer={...(c.cobuyer||{}),...v};filled.push('co-buyer')}continue}if(v&&!c[k]){c[k]=v;filled.push(k)}} await storeCustFiles(c,imgs,(r.docType||'document').replace(/_/g,' '));c.notes.push({date:TODAY,by:S.settings.user,text:`Document read: ${(r.docType||'document').replace(/_/g,' ')}${filled.length?' · filled '+filled.join(', '):''}`});save();render();toast(filled.length?'Filled in: '+filled.join(', ')+'. Please check them':'Saved to Files. Nothing new to fill in')}catch(e){toast(e.message||aiErrMsg(e))}};inp.click()} async function custUpload(cid,files){const c=cust(cid);const list=[...files].slice(0,10);for(const f of list){if(f.size>15*1024*1024){toast(f.name+' is too large (15 MB max)');continue}const b=/^image\//.test(f.type)?await shrink(f,2200,0.88):f;await storeCustFiles(c,[b],f.name)}save();render();toast(list.length+' file(s) added')} const CWCSS=`.cw-top{display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-bottom:12px}.cw-name{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.cw-name h2{margin:0;font-size:22px;font-weight:700;letter-spacing:-.3px} .cw-steps{display:flex;list-style:none;margin:0 0 0 auto;padding:0;gap:2px;flex-wrap:wrap}.cw-steps button{border:0;background:#eef0f4;color:var(--muted);font:600 12.5px inherit;padding:8px 16px 8px 20px;cursor:pointer;clip-path:polygon(0 0,calc(100% - 10px) 0,100% 50%,calc(100% - 10px) 100%,0 100%,10px 50%)}.cw-steps li:first-child button{clip-path:polygon(0 0,calc(100% - 10px) 0,100% 50%,calc(100% - 10px) 100%,0 100%);padding-left:14px} .cw-steps button.done{background:#dbe6ff;color:#1d47bd}.cw-steps button.on{background:var(--brand);color:#fff}.cw-steps button.lost.on{background:var(--red)}.cw-steps button:focus-visible{outline:3px solid #a9c1ff} .cw-quick{display:flex;gap:8px;flex-wrap:wrap;align-items:center;background:#fff;border:1px solid var(--line);border-radius:12px;padding:10px 12px;margin-bottom:12px}.cw-quick .sp{flex:1} .cw-kpis{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:1px;background:var(--line);border:1px solid var(--line);border-radius:12px;overflow:hidden;margin-bottom:14px}.cw-kpis>div{background:#fff;padding:10px 14px}.cw-kpis span{display:block;font-size:12px;color:var(--muted)}.cw-kpis b{font-size:14px;font-weight:600} .cw-grid{display:grid;grid-template-columns:310px minmax(0,1fr) 300px;gap:14px;align-items:start}.cw-left{padding:14px;position:sticky;top:80px}.cw-left .seg{display:grid;grid-template-columns:repeat(3,1fr);margin-bottom:12px} .seg{display:inline-flex;border:1px solid #d0d5dd;border-radius:8px;overflow:hidden;background:#fff}.seg button{white-space:nowrap;border:0;background:#fff;padding:7px 10px;font:500 13px inherit;color:var(--ink2);cursor:pointer;border-right:1px solid #e3e6eb}.seg button:last-child{border-right:0}.seg button.on{background:var(--brand);color:#fff} .cf-row{display:grid;grid-template-columns:96px minmax(0,1fr);align-items:center;gap:8px;margin-bottom:7px;font-size:12.5px;color:var(--muted)}.cf-row input,.cf-row select{width:100%;min-width:0;padding:7px 9px;border:1px solid #d0d5dd;border-radius:7px;font-size:13.5px;color:var(--ink)} .cf-reps{background:#f5f8ff;border:1px solid #e1e9fb;border-radius:10px;padding:10px;margin:10px 0}.cf-notes{display:flex;flex-direction:column;gap:4px;font-size:12.5px;color:var(--muted)}.cf-notes textarea{border:1px solid #d0d5dd;border-radius:7px;padding:7px;font-size:13.5px} .cf-consent{display:grid;grid-template-columns:1fr 1fr;gap:6px;font-size:12.5px} .cw-actions{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:12px}.cw-feed{padding:16px}.cw-feedhead{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:12px}.cw-feedhead .seg{max-width:100%;overflow-x:auto}.cw-feedhead input{margin-left:auto;padding:7px 10px;border:1px solid #d0d5dd;border-radius:8px;min-width:180px} .cw-item{display:flex;gap:12px;padding:12px;border:1px solid var(--line);border-radius:10px;margin-bottom:8px;background:#fff}.cw-ico{width:30px;height:30px;flex:0 0 30px;border-radius:8px;display:grid;place-items:center;font:700 12px inherit;background:#eef3ff;color:#1d47bd} .t-call .cw-ico{background:#e7f6ee;color:#067647}.t-text .cw-ico{background:#eaf7f6;color:#0e7c74}.t-email .cw-ico{background:#f4f1ff;color:#4b2fb3}.t-task .cw-ico{background:#fdf4e3;color:#a15c07}.t-log .cw-ico{background:#f0f2f5;color:#556070} .cw-ititle{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;justify-content:space-between}.cw-ibody{white-space:pre-wrap;margin:4px 0;color:var(--ink2);overflow-wrap:anywhere} .cw-veh .cw-vimg{height:150px;border-radius:10px;background:#f0f2f5;display:grid;place-items:center;color:var(--muted);overflow:hidden;margin-bottom:10px}.cw-vimg img{width:100%;height:100%;object-fit:cover} .scanbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;background:#f5f8ff;border:1px solid #e1e9fb;border-radius:10px;padding:10px 12px;margin-bottom:14px} .syncdot{width:9px;height:9px;border-radius:50%;display:inline-block;background:#98a2b3}.syncdot.ok{background:#12b76a}.syncdot.off{background:#f79009} @media(max-width:1280px){.cw-grid{grid-template-columns:270px minmax(0,1fr)}.cw-right{grid-column:1/-1}.cw-kpis{grid-template-columns:repeat(3,minmax(0,1fr))}} @media(max-width:820px){.cw-grid{grid-template-columns:1fr}.cw-left{position:static}.cw-steps{margin-left:0}.cw-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Import from Frazer / DealerCenter / spreadsheets ================= */ const IMP_TYPES={ vehicles:{n:'Inventory',f:[['stock','Stock #',/^(stock|stk|stock ?(#|no|num(ber)?))$/],['vin','VIN',/^vin( ?(#|no|number))?$/],['year','Year',/^(year|yr|model ?year)$/],['make','Make',/^make$/],['model','Model',/^model$/],['trim','Trim',/^(trim|series|style)$/],['ymm','Year Make Model (one column)',/^(vehicle|description|year ?make ?model|ymm|unit)$/],['color','Color',/^(color|ext(erior)? ?colou?r)$/],['miles','Mileage',/^(miles|mileage|odometer|odom)$/],['cost','Cost',/^(cost|purchase ?(price|cost)|total ?cost|acv|buy ?price|vehicle ?cost)$/],['price','Asking price',/^(price|asking( ?price)?|retail( ?price)?|internet ?price|list ?price|sticker)$/],['status','Status',/^(status|stock ?status|inv(entory)? ?status)$/],['acquired','Date in stock',/^(date ?in|purchase ?date|inventory ?date|date ?(acquired|purchased|stocked)|in ?stock ?date|received)$/],['lot','Lot / location',/^(lot|location|lot ?location)$/],['notes','Notes',/^(notes?|comments?)$/]]}, customers:{n:'Customers & leads',f:[['name','Full name',/^(name|customer( ?name)?|buyer( ?name)?|full ?name|contact( ?name)?|prospect( ?name)?)$/],['first','First name',/^(first( ?name)?|fname|buyer ?first)$/],['last','Last name',/^(last( ?name)?|lname|surname|buyer ?last)$/],['phone','Cell / main phone',/^(phone|cell|mobile|cell ?phone|mobile ?phone|primary ?phone|phone ?(1|#|number))$/],['homePhone','Home phone',/^home( ?phone)?$/],['workPhone','Work phone',/^(work|business)( ?phone)?$/],['email','Email',/^e-?mail( ?address)?$/],['address','Street address',/^(address|street|address ?1|street ?address|addr)$/],['city','City',/^city$/],['state','State',/^(state|st)$/],['zip','ZIP',/^(zip|zip ?code|postal( ?code)?)$/],['dob','Date of birth',/^(dob|birth ?date|date ?of ?birth|birthday)$/],['employer','Employer',/^(employer|employment|company)$/],['income','Monthly income',/^(income|monthly ?income|gross ?monthly( ?income)?)$/],['source','Lead source',/^(source|lead ?source|referral ?source)$/],['leadType','Lead type',/^lead ?type$/],['inquiry','Inquiry type',/^inquiry ?type$/],['interestMake','Interested vehicle make',/^(interested ?vehicle ?make|vehicle ?of ?interest ?make)$/],['interestModel','Interested vehicle model',/^(interested ?vehicle ?model|vehicle ?of ?interest ?model)$/],['salesperson','Sales rep',/^(sales ?rep|salesperson)$/],['importCreatedBy','Created by',/^created ?by$/],['lastContactAttempt','Last contact attempt',/^last ?contact ?attempt( ?date)?$/],['daysSinceContact','Days since last contact (at export)',/^days? ?since ?last ?contact$/],['stage','Status / stage',/^(status|stage|lead ?status|customer ?status)$/],['created','Date added',/^(created|date ?(added|created|entered)|lead ?date|customer ?created ?date|added)$/],['dlNo','Driver license #',/^(dl|driver'?s? ?licen[cs]e( ?(#|no|number))?|dl ?(#|no|number))$/],['notes','Notes',/^(notes?|comments?)$/]]}, deals:{n:'Sold deals',f:[['no','Deal #',/^(deal|deal ?(#|no|num(ber)?)|sale ?(#|no))$/],['date','Sale date',/^(date|sale ?date|sold ?date|deal ?date|delivery ?date|contract ?date)$/],['name','Buyer name',/^(name|customer( ?name)?|buyer( ?name)?|purchaser)$/],['phone','Buyer phone',/^(phone|cell|mobile|customer ?phone|(cell|mobile|home|buyer|primary) ?phone)$/],['email','Buyer email',/^e-?mail$/],['vin','VIN',/^vin$/],['stock','Stock #',/^(stock|stk|stock ?(#|no))$/],['ymm','Vehicle',/^(vehicle|description|year ?make ?model|unit)$/],['price','Sale price',/^(price|sale ?price|selling ?price|cash ?price|vehicle ?price)$/],['cost','Vehicle cost',/^(cost|total ?cost|vehicle ?cost)$/],['gross','Front gross',/^(gross|front( ?end)? ?gross|profit|front)$/],['type','Deal type',/^(type|deal ?type|sale ?type|finance ?type)$/],['down','Down payment',/^(down|cash ?down|down ?payment|total ?down)$/],['financed','Amount financed',/^(amount ?financed|financed|amt ?financed)$/],['apr','APR',/^(apr|rate|interest ?rate)$/],['term','Term (payments)',/^(term|# ?pmts|number ?of ?payments|months)$/],['payment','Payment',/^(payment|pmt|payment ?amount)$/],['salesperson','Salesperson',/^(salesperson|sales ?(rep|person)|rep|sold ?by)$/],['lender','Lender',/^(lender|bank|finance ?company|lienholder)$/]]}, loans:{n:'BHPH accounts',f:[['acct','Account #',/^(acct|account|account ?(#|no|number)|loan ?(#|no)|contract ?(#|no))$/],['name','Customer name',/^(name|customer( ?name)?|buyer( ?name)?|borrower)$/],['phone','Phone',/^(phone|cell|mobile|(cell|mobile|home|customer|primary) ?phone)$/],['vin','VIN',/^vin$/],['stock','Stock #',/^(stock|stk|stock ?(#|no))$/],['ymm','Vehicle',/^(vehicle|description|year ?make ?model|unit)$/],['startDate','Contract date',/^(contract ?date|sale ?date|start ?date|date|origination ?date|deal ?date)$/],['principal','Amount financed',/^(amount ?financed|financed|original ?(balance|principal)|principal)$/],['balance','Current balance',/^(balance|current ?balance|principal ?balance|payoff|remaining ?balance|outstanding)$/],['payment','Payment amount',/^(payment|pmt|payment ?amount|regular ?payment)$/],['freq','Payment schedule',/^(freq|frequency|schedule|pmt ?freq|payment ?(freq(uency)?|schedule|terms))$/],['apr','APR',/^(apr|rate|interest ?rate)$/],['term','Total payments',/^(term|# ?pmts|number ?of ?payments|total ?payments)$/],['made','Payments made',/^(payments ?made|# ?pmts ?made|pmts ?made|paid ?count|# ?paid)$/],['nextDue','Next due date',/^(next ?due( ?date)?|due ?date|next ?payment( ?date)?)$/],['daysLate','Days past due',/^(days ?(late|past ?due|delinquent)|dpd)$/],['lastPaid','Last payment date',/^(last ?(pay(ment)?|paid)( ?date)?|lpd)$/],['status','Status',/^(status|account ?status)$/]]}}; const normH=h=>String(h||'').toLowerCase().replace(/[_.:]/g,' ').replace(/\s+/g,' ').replace(/[^a-z0-9#' ]/g,'').trim(); const money=v=>{const t=String(v??'').trim();if(!t)return 0;const neg=/^\(.*\)$/.test(t)||/^-/.test(t);const n=parseFloat(t.replace(/[^0-9.]/g,''));return isNaN(n)?0:(neg?-n:n)}; function pdate(v){if(v instanceof Date&&!isNaN(v))return v.toISOString().slice(0,10);const t=String(v??'').trim();if(!t)return '';let m; if(m=t.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/))return `${m[1]}-${m[2].padStart(2,'0')}-${m[3].padStart(2,'0')}`; if(m=t.match(/^(\d{1,2})[\/\-.](\d{1,2})[\/\-.](\d{2,4})/)){let y=+m[3];if(y<100)y+=y>50?1900:2000;return `${y}-${m[1].padStart(2,'0')}-${m[2].padStart(2,'0')}`} if(/^\d{5}(\.\d+)?$/.test(t)){const d=new Date(Date.UTC(1899,11,30)+(+t)*864e5);return d.toISOString().slice(0,10)} const d=new Date(t);return isNaN(d)?'':d.toISOString().slice(0,10)} function impParseCSV(text){const rows=[];let row=[],cell='',q=false;const delim=(text.split('\n')[0].match(/\t/g)||[]).length>(text.split('\n')[0].match(/,/g)||[]).length?'\t':','; for(let i=0;ir.some(c=>String(c).trim()!==''))} let XLSXLIB=null;async function loadXLSX(){if(XLSXLIB)return XLSXLIB;await new Promise((res,rej)=>{const s=document.createElement('script');s.src='https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js';s.onload=res;s.onerror=()=>rej(new Error('Could not load the Excel reader. Save the file as CSV and try again'));document.head.appendChild(s)});XLSXLIB=window.XLSX;return XLSXLIB} async function readSheetFile(file){if(/\.(xlsx|xls)$/i.test(file.name)){const X=await loadXLSX();const wb=X.read(await file.arrayBuffer(),{cellDates:true});const ws=wb.Sheets[wb.SheetNames[0]];return X.utils.sheet_to_json(ws,{header:1,raw:true,defval:''}).filter(r=>r.some(c=>String(c).trim()!==''))} return impParseCSV(await file.text())} function findHeader(rows,type){const F_=IMP_TYPES[type].f;let best=0,bi=0;for(let i=0;iF_.some(f=>f[2].test(normH(h)))).length;if(sc>best){best=sc;bi=i}}return bi} function guessMap(headers,type){const map={};IMP_TYPES[type].f.forEach(([k,,re])=>{const i=headers.findIndex((h,j)=>re.test(normH(h))&&!Object.values(map).includes(j));if(i>=0)map[k]=i});return map} function guessType(headers){let best='customers',bs=-1;for(const t of Object.keys(IMP_TYPES)){const s=Object.keys(guessMap(headers,t)).length+(t==='loans'&&headers.some(h=>/acct|account|balance|next ?due/i.test(h))?3:0)+(t==='vehicles'&&headers.some(h=>/stock|vin/i.test(h))&&!headers.some(h=>/sale ?date|sold|buyer/i.test(h))?2:0)+(t==='deals'&&headers.some(h=>/sale ?date|sold ?date|deal/i.test(h))?3:0);if(s>bs){bs=s;best=t}}return best} function rowObj(r,map){const o={};for(const [k,i] of Object.entries(map))if(i!==''&&i!=null&&i>=0)o[k]=r[i]instanceof Date?r[i]:String(r[i]??'').trim();return o} const splitYMM=t=>{const p=String(t||'').trim().split(/\s+/);const y=/^(19|20)\d{2}$/.test(p[0])?+p.shift():'';return{year:y,make:p.shift()||'',model:p.join(' ')}}; const vStatus=t=>/sold|deliver/i.test(t)?'Sold':/pend|hold|deposit/i.test(t)?'Pending':/recon|shop|service/i.test(t)?'In Recon':/wholesale|auction/i.test(t)?'Wholesale':'Available'; const cStage=t=>/^missed appointment|^dealer visit follow-up/i.test(t)?'Contacted':/sold|customer|deliver|purchas/i.test(t)?'Sold':/lost|dead|inactive|bad/i.test(t)?'Lost':/appt|appointment/i.test(t)?'Appointment':/contact|working|follow/i.test(t)?'Contacted':'New'; const dType=(t,o)=>/bhph|in.?house|buy.?here|lhph|note|owner|seller fin/i.test(t)?'BHPH':/cash/i.test(t)?'Cash':/financ|retail|bank|credit|outside|lender/i.test(t)||o.lender?'Retail Finance':(money(o.financed)>0?'BHPH':'Cash'); const freqOf=t=>/week(?!.*bi)|^w$/i.test(t)&&!/bi/i.test(t)?'weekly':/bi.?week|every 2|biwk|^b$/i.test(t)?'biweekly':/semi/i.test(t)?'semimonthly':'monthly'; function findCust(o){const lf0=String(o.name||'').match(/^([^,]+),\s*(.+)$/);const p=normPhone(o.phone),e=String(o.email||'').toLowerCase(),n=normName(lf0?lf0[2]+' '+lf0[1]:o.name||[o.first,o.last].filter(Boolean).join(' ')); return (p.length===10&&S.customers.find(c=>normPhone(c.phone)===p))||(validEmail(e)&&S.customers.find(c=>String(c.email||'').toLowerCase()===e))||(o.dlNo&&S.customers.find(c=>c.dlNo&&c.dlNo===o.dlNo))||(n&&n.includes(' ')&&!p&&!e&&S.customers.find(c=>normName(c.name)===n))||null} function findVeh(o){const vin=String(o.vin||'').toUpperCase().replace(/\s/g,'');return (vin.length>=11&&S.vehicles.find(v=>String(v.vin||'').toUpperCase()===vin))||(o.stock&&S.vehicles.find(v=>String(v.stock).toLowerCase()===String(o.stock).toLowerCase()))||null} function custFrom(o,src,batch){let name=o.name||[o.first,o.last].filter(Boolean).join(' ').trim();const lf=String(name).match(/^([^,]+),\s*(.+)$/);if(lf)name=(lf[2]+' '+lf[1]).trim();if(!name&&!o.phone&&!o.email)return null; const addr=[o.address,[o.city,[o.state,o.zip].filter(Boolean).join(' ')].filter(Boolean).join(', ')].filter(Boolean).join(', '); return{id:uid(),name:name||'Unknown',phone:o.phone||'',homePhone:o.homePhone||'',workPhone:o.workPhone||'',email:o.email||'',address:addr,dob:pdate(o.dob)||'',employer:o.employer||'',income:money(o.income)||0,source:o.source||src,stage:o.stage?cStage(o.stage):'New',created:pdate(o.created)||TODAY,createdAt:(pdate(o.created)||TODAY)+'T09:00',dlNo:o.dlNo||'',followUp:'',smsConsent:false,optOut:false,dnc:false,interest:'',notes:[{date:TODAY,by:S.settings.user,text:`Imported from ${src}${o.notes?': '+o.notes:''}`}],importBatch:batch}} function vehFrom(o,src,batch,status){const y=o.ymm?splitYMM(o.ymm):{};const s=status||vStatus(o.status||''); return{id:uid(),stock:o.stock||('S'+(++S.seq.stock)),vin:String(o.vin||'').toUpperCase().replace(/\s/g,''),year:+o.year||y.year||'',make:o.make||y.make||'',model:o.model||y.model||'',trim:o.trim||'',color:o.color||'',miles:Math.round(money(o.miles))||0,cost:money(o.cost),price:money(o.price),recon:[],status:s,acquired:pdate(o.acquired)||TODAY,lot:o.lot||'Main Lot',published:s==='Available',notes:o.notes?`${o.notes} (imported from ${src})`:`Imported from ${src}`,importBatch:batch}} function runImport(type,rows,map,opts){const batch='imp_'+uid();const src=opts.source;const res={added:0,updated:0,skipped:0,linked:0,problems:[]};const made={};const mk=(c,x)=>{(made[c]=made[c]||[]).push(x.id)}; const users=S.users||[];const userByName=n=>{const t=normName(n);return t?users.find(u=>normName(u.name)===t||normName(u.name).split(' ')[0]===t.split(' ')[0]):null}; rows.forEach((r,ri)=>{const o=rowObj(r,map);try{ if(type==='vehicles'){if(!o.vin&&!o.stock&&!o.ymm&&!o.make){res.skipped++;return}const ex=findVeh(o);if(ex){impVehUpdate(ex,o,opts,res,src,batch);return}if(opts.onlyUpdate){res.skipped++;return}const v=vehFrom(o,src,batch);impVehExtra(v,o);if(S.vehicles.some(x=>x.stock===v.stock))v.stock=v.stock+'-I';S.vehicles.push(v);mk('vehicles',v);res.added++} else if(type==='customers'){const ex=findCust(o);if(ex){if(opts.dupes==='update'){const n=custFrom(o,src,batch);for(const k of ['phone','homePhone','workPhone','email','address','dob','employer','income','dlNo'])if(n&&n[k]&&!ex[k])ex[k]=n[k];impCustExtra(ex,o,true);res.updated++}else res.skipped++;return}const c=custFrom(o,src,batch);if(!c){res.skipped++;return}impCustExtra(c,o);S.customers.push(c);mk('customers',c);res.added++} else if(type==='deals'){const date=pdate(o.date);if(!date){res.problems.push(`Row ${ri+1}: no sale date`);res.skipped++;return} if(o.no&&S.deals.some(d=>String(d.extNo||'')===String(o.no)&&d.importSource===src)){res.skipped++;return} let c=findCust(o);if(!c){c=custFrom(o,src,batch);if(!c){res.problems.push(`Row ${ri+1}: no buyer`);res.skipped++;return}c.stage='Sold';S.customers.push(c);mk('customers',c)}else{c.stage='Sold';res.linked++} let v=findVeh(o);if(!v){v=vehFrom({...o,status:'Sold',acquired:o.date},src,batch,'Sold');v.price=money(o.price)||v.price;S.vehicles.push(v);mk('vehicles',v)}else{v.status='Sold';res.linked++}v.soldDate=date; const price=money(o.price),cost=money(o.cost)||+v.cost||0;const type_=dType(o.type||'',o);const sp=userByName(o.salesperson); const d={id:uid(),no:++S.seq.deal,extNo:o.no||'',importSource:src,date,customerId:c.id,vehicleId:v.id,type:type_,price,docFee:0,taxRate:0,otherFees:0,tradeAllow:0,tradePayoff:0,down:money(o.down),apr:money(o.apr),term:Math.round(money(o.term))||0,freq:'monthly',financed:money(o.financed)||(type_==='Cash'?0:Math.max(0,price-money(o.down))),payment:money(o.payment),gross:o.gross!==undefined&&o.gross!==''?money(o.gross):(cost?price-cost:0),salespersonId:sp?.id||'',lender:o.lender||'',notes:`Imported from ${src}${o.no?' (deal '+o.no+')':''}${o.salesperson&&!sp?' · salesperson: '+o.salesperson:''}`,importBatch:batch}; impDealExtra(d,o,c);S.deals.push(d);mk('deals',d);res.added++} else if(type==='loans'){const bal=money(o.balance),pmt=money(o.payment);if(!o.acct&&!o.name){res.skipped++;return}if(!pmt||bal<=0&&!/paid|closed/i.test(o.status||'')){res.problems.push(`Row ${ri+1} (${o.acct||o.name}): needs a payment amount and a balance`);res.skipped++;return} if(o.acct&&S.loans.some(l=>String(l.extAcct||l.acct)===String(o.acct))){res.skipped++;return} let c=findCust(o);if(!c){c=custFrom(o,src,batch);c.stage='Sold';S.customers.push(c);mk('customers',c)}else res.linked++; let v=findVeh(o);if(!v){v=vehFrom({...o,status:'Sold'},src,batch,'Sold');S.vehicles.push(v);mk('vehicles',v)}else v.status='Sold'; const freq=freqOf(o.freq||''),ppy=FREQ[freq]?.ppy||12,apr=money(o.apr);const start=pdate(o.startDate)||TODAY;let term=Math.round(money(o.term));const principal=money(o.principal)||bal; if(!term){const r=apr/100/ppy;term=r?Math.ceil(-Math.log(1-principal*r/pmt)/Math.log(1+r)):Math.ceil(principal/pmt);if(!isFinite(term)||term<=0)term=Math.ceil(principal/pmt)} let firstDue=addPeriods(start,freq,1);let made_=Math.round(money(o.made));const nd=pdate(o.nextDue); if(!o.made&&nd){made_=0;while(made_bal+0.5){b=b*(1+r)-pmt;made_++}} made_=Math.max(0,Math.min(term,made_));if(nd&&made_x.id===id);if(!im)return;confirmBox(`Remove everything this import added (${im.res.added} ${esc(IMP_TYPES[im.type].n.toLowerCase())} records${Object.keys(im.made).length>1?' plus linked customers/vehicles':''})? Records you changed since are removed too. Updates to existing records are not undone.`,()=>{ for(const [c,ids] of Object.entries(im.made||{}))S[c]=(S[c]||[]).filter(x=>!ids.includes(x.id));im.undone=nowAt();save();render();toast('Import undone')})} function importCard(){if(!can('settings'))return '';const ims=(S.imports||[]).slice().reverse().slice(0,8); return `

Import from Frazer, DealerCenter or a spreadsheet

Bring over inventory, customers, sold deals and BHPH accounts from reports you export as CSV or Excel. DealerPen matches the columns for you, skips duplicates, and every import can be undone.

${ims.length?`${ims.map(i=>``).join('')}
WhenFromWhatAddedUpdatedSkipped
${ftime(i.at)}${esc(i.source)}
${esc(i.file||'')}
${IMP_TYPES[i.type].n}${i.res.added}${i.res.updated}${i.res.skipped}${i.undone?'Undone':``}
`:''}
`} const IMP_HELP={Frazer:'In Frazer, open the report for what you are moving (inventory list, customer list, sales/deals report, or accounts/receivables list) and export or save it to Excel or CSV. If a report won’t export, ask Frazer support for a data export of your own records.',DealerCenter:'In DealerCenter, open Reports (or the Inventory, Customer or Deal list), click Print/Export and choose “CSV - Raw Data”. Run one report per type: inventory, customers, deals and BHPH accounts.','Other spreadsheet':'Any CSV or Excel file with a header row works.'}; function importWizard(){const st={source:'DealerCenter',file:null,rows:null,type:'',hi:0,map:{},dupes:'skip'}; const step1=()=>{openModal(mh('Import data')+`
${esc(IMP_HELP[st.source])}

Import in this order for the best matching: inventory, then customers, then sold deals, then BHPH accounts. Files stay on this computer; only the records you import are saved.

`,true); $('#imsrc').onchange=e=>{st.source=e.target.value;$('#imhelp').textContent=IMP_HELP[st.source]}; $('#imnext').onclick=async()=>{const f=$('#imfile').files[0];if(!f)return $('#imerr').textContent='Choose a file first';$('#imnext').disabled=true;$('#imnext').textContent='Reading…'; try{const rows=await readSheetFile(f);if(rows.length<2)throw new Error('That file has no data rows');st.file=f.name;st.all=rows;const t0=guessType(rows[findHeader(rows,'customers')]||rows[0]);st.type=t0;st.hi=findHeader(rows,t0);st.map=guessMap(rows[st.hi],t0);step2()} catch(e){$('#imerr').textContent=e.message||'Could not read that file';$('#imnext').disabled=false;$('#imnext').textContent='Next'}}}; const step2=()=>{const H=st.all[st.hi]||[];const data=st.all.slice(st.hi+1);const F_=IMP_TYPES[st.type].f; const prev=data.slice(0,5).map(r=>rowObj(r,st.map));const found=data.map(r=>rowObj(r,st.map)); const dup=st.type==='vehicles'?found.filter(o=>findVeh(o)).length:st.type==='customers'?found.filter(o=>findCust(o)).length:0; const need={vehicles:['vin|stock|ymm|make'],customers:['name|first|last|phone|email'],deals:['date','name|first|phone'],loans:['acct|name','balance','payment'],payments:['acct|name|phone','date','amount'],notes:['name|phone|email|acct','note']}[st.type]||[];const missing=need.filter(g=>!g.split('|').some(k=>st.map[k]!==undefined)); const visible=F_.filter(([k])=>st.map[k]!==undefined || missing.some(group=>group.split('|').includes(k))); const optional=F_.filter(field=>!visible.includes(field)); const mapping=fields=>`
${fields.map(([k,label])=>``).join('')}
`; openModal(mh('Review import')+`
${esc(st.file)}

${esc(st.source)} · ${esc(IMP_TYPES[st.type].n)} · ${data.length.toLocaleString()} rows

File settings
${missing.length?`
Match a column for: ${missing.map(g=>g.split('|').map(k=>F_.find(f=>f[0]===k)?.[1]).join(' or ')).join('; ')}
`:''}

Match columns

Choose which column in your file fills each DealerPen field.

${visible.length?mapping(visible):''} ${optional.length?`
Add optional fields (${optional.length})
${mapping(optional)}
`:''}

Preview (first ${prev.length} rows)

${F_.filter(f=>st.map[f[0]]!==undefined).map(f=>``).join('')}${prev.map(o=>`${F_.filter(f=>st.map[f[0]]!==undefined).map(f=>``).join('')}`).join('')}
${f[1]}
${esc(o[f[0]] instanceof Date?pdate(o[f[0]]):o[f[0]]||'')}
${['vehicles','customers'].includes(st.type)?`
${dup} row(s) look like records you already have.
`:''}
${st.type==='vehicles'?``:''}
${st.type==='payments'?'

Each payment is added to the matching BHPH account (by account #, or by customer and VIN). Import BHPH accounts first. Payments already imported are skipped.

':''}${st.type==='notes'?'

Notes are added to the matching customer, and collection notes also to their BHPH account.

':''}${st.type==='loans'?'

For each account DealerPen keeps the current balance and works out payments made from the next due date (or days late, or the balance). It adds one “opening history” line instead of every past payment. Keep your old payment history report on file.

':''} ${st.type==='deals'?'

Past deals are added to customer history and reports. They don’t post entries to your accounting books.

':''}
`,true); const optionalFields=$('#imoptional'); if(optionalFields)optionalFields.ontoggle=()=>{if(optionalFields.isConnected)st.showOptional=optionalFields.open}; const remember=$('#imrem'),full=$('#imfull'); remember.onchange=()=>{st.remember=remember.checked}; if(full)full.onchange=()=>{st.full=full.checked}; $('#imback').onclick=step1;$('#imtype').onchange=e=>{st.type=e.target.value;st.hi=findHeader(st.all,st.type);st.map=guessMap(st.all[st.hi],st.type);step2()};$('#imhi').onchange=e=>{st.hi=+e.target.value;st.map=guessMap(st.all[st.hi],st.type);step2()}; document.querySelectorAll('#modal [data-k]').forEach(sel=>sel.onchange=()=>{const k=sel.dataset.k;if(sel.value==='')delete st.map[k];else st.map[k]=+sel.value;step2()}); document.querySelectorAll('input[name=imdup]').forEach(r=>r.onchange=()=>{st.dupes=r.value}); $('#imgo').onclick=()=>{const full_=!!($('#imfull')&&$('#imfull').checked),rem_=!!($('#imrem')&&$('#imrem').checked);const res=runImport(st.type,data,st.map,{source:st.source,dupes:st.dupes,file:st.file,full:full_});if(rem_)impRemember(st.source,st.type,st.all[st.hi],st.map,st.hi,full_); openModal(mh('Import finished')+`
Added${res.added}
Updated${res.updated}
Skipped${res.skipped}
Linked to existing${res.linked}
${res.removed!=null?`
Missing from file${res.removed}
`:''}
${res.problems.length?`

Rows that need a look

${res.problems.slice(0,100).map(p=>`
${esc(p)}
`).join('')}
`:''}

Changed your mind? Undo this import in Settings → Import.

`,true)}}; step1()} /* ================= Customer Activity (sold-customer look-up for managers) ================= */ const lastFirst=n=>{const p=String(n||'').trim().split(/\s+/);if(p.length<2)return String(n||'').toUpperCase();const suf=/^(jr|sr|ii|iii|iv)\.?$/i.test(p[p.length-1])?p.pop():'';const last=p.pop();return (last+(suf?' '+suf:'')+', '+p.join(' ')).toUpperCase()}; const shortVeh=v=>v?`${String(v.year||'').slice(-2)} ${String(v.make||'').toUpperCase()} ${String(v.model||'').toUpperCase()}${v.color?'; '+String(v.color).toUpperCase():''}`:''; function activityRows(){return S.deals.map(d=>{const c=cust(d.customerId),v=veh(d.vehicleId),l=d.loanId?loan(d.loanId):S.loans.find(x=>x.dealId===d.id); const bal=l&&l.status==='Active'?l.balance:0;const dpd=l&&l.status==='Active'?daysLate(l):0;const lastPay=l&&l.payments.length?l.payments[l.payments.length-1].date:''; return{d,c,v,l,stock:v?.stock||'',name:c?.name||'',lf:lastFirst(c?.name||''),date:d.date,bal,dpd,dlp:l&&l.status==='Active'&&lastPay?diff(lastPay,TODAY):'',veh:shortVeh(v),type:d.type,rep:d.salespersonId,phones:[c?.phone,c?.homePhone,c?.workPhone,c?.cobuyer?.phone].filter(Boolean).map(normPhone),co:c?.cobuyer?.name||''}}).filter(r=>r.c)} VIEWS.activity=()=>{const by=ui.caBy||'last',q=String(ui.caQ||'').trim().toLowerCase(),bal=ui.caBal||'all',st=ui.caType||'',rep=ui.caRep||''; let rows=activityRows(); if(q){const qd=q.replace(/\D/g,'');rows=rows.filter(r=>by==='last'?r.lf.toLowerCase().startsWith(q):by==='first'?(r.name.toLowerCase().split(' ')[0]||'').startsWith(q):by==='stock'?String(r.stock).toLowerCase().startsWith(q):by==='date'?(r.date.includes(q)||fdate(r.date).toLowerCase().includes(q)):by==='co'?r.co.toLowerCase().includes(q):by==='veh'?(r.veh.toLowerCase().includes(q)||String(r.v?.vin||'').toLowerCase().includes(q)):by==='phone'?(qd.length>=3&&r.phones.some(p=>p.includes(qd))):true)} if(bal==='bal')rows=rows.filter(r=>r.bal>0);if(bal==='late')rows=rows.filter(r=>r.dpd>0);if(st)rows=rows.filter(r=>r.type===st);if(rep)rows=rows.filter(r=>r.rep===rep); rows.sort(by==='stock'?(a,b)=>String(a.stock).localeCompare(String(b.stock)):by==='date'?(a,b)=>b.date.localeCompare(a.date):(a,b)=>a.lf.localeCompare(b.lf)); const modes=[['last','Last name'],['first','First name'],['stock','Stock #'],['date','Sale date'],['co','Co-buyer'],['veh','Vehicle / VIN'],['phone','Phone']]; return `
${modes.map(m=>``).join('')}
${[['all','All customers'],['bal','With a balance'],['late','Past due']].map(x=>``).join('')}
${rows.length} customers
${rows.slice(0,500).map(r=>``).join('')||''}
StockNameSale dateBalanceDPDDLPVehicleSale type
${esc(r.stock)}${esc(r.lf)}${fdate(r.date)}${r.bal?$$(r.bal):'0.00'}${r.dpd||''}${r.dlp===''?'':r.dlp}${esc(r.veh)}${r.type==='Retail Finance'?'Outside':r.type}
No sold customers match

DPD = days past due · DLP = days since last payment. Click a customer (or press Enter on the first match) to open their activity screen.

`}; function activityModal(did){const d=S.deals.find(x=>x.id===did);if(!d)return;const c=cust(d.customerId),v=veh(d.vehicleId),l=d.loanId?loan(d.loanId):S.loans.find(x=>x.dealId===d.id); const act=l&&l.status==='Active';const fin=d.type==='BHPH'?'In-house financing':d.type==='Cash'?'Cash sale':'Outside financing';const due=act?r2(pastDue(l)+l.lateFeesDue):0;const st=storeName(d.storeId); const B=(label,fn,dis)=>``;const noL=act?'':'Only for in-house (BHPH) accounts with a balance'; openModal(mh('Customer activity · '+esc(c?.name||''))+`
Stock #
${esc(v?.stock||'')}
${esc(lastFirst(c?.name))}
${esc(c?.address||'')}
${c?.cobuyer?.name?`
Co-buyer: ${esc(c.cobuyer.name)}
`:''}
Sale date ${fdate(d.date)} · Deal #${d.no}${st&&stores().length>1?' · '+esc(st):''}
${esc(v?`${v.year} ${v.make} ${v.model}${v.trim?' '+v.trim:''}${v.color?'; '+v.color:''}`:'')}
VIN ${esc(v?.vin||'')}
Sold by ${esc(uname(d.salespersonId))}
${fin}
${[['Cell',c?.phone],['Home',c?.homePhone],['Work',c?.workPhone],['Co-buyer',c?.cobuyer?.phone],['Email',c?.email]].map(p=>`
${p[0]}${esc(p[1]||'')}
`).join('')}
${d.type==='Retail Finance'?`
Financed by ${esc(d.lender||'outside lender')} · amount financed ${$$(d.financed)}
`:''}${act?`
Account ${l.acct} · ${$$(l.payment)} ${FREQ[l.freq].label.toLowerCase()} · ${paidCount(l)} of ${l.term} paid · next due ${fdate(nextDue(l))}${daysLate(l)?` · ${daysLate(l)} days late`:''}${l.paused?' · payments paused':''}
`:''}${c?.special?`
Special message: ${esc(c.special)}
`:''}
${act?`
Principal balance${$$(l.balance)}
Amount due today${$$(due)}
Payoff today${$$(payoff(l))}
`:`
Balance${l&&l.status!=='Active'?esc(l.status):'Paid in full'}
`}
${B('Enter a payment',`closeModal();payModal('${l?.id}')`,noL)}${B('Customer page',`openCustomer('${c?.id}')`)}${B('Vehicle information',`closeModal();vehModal('${v?.id}')`,v?'':'No vehicle')} ${B('Payment history',`closeModal();acctModal('${l?.id}')`,l?'':'No financed account')}${B('Contact activity',`openCustomer('${c?.id}');ui.cTab='lead';ui.cFeed='all'`)}${B('Sale recap sheet',`closeModal();dealView('${d.id}')`)} ${B('Early payoff quote',`closeModal();acctModal('${l?.id}');setTimeout(()=>$('#po')&&$('#po').click(),60)`,noL)}${B('Special message',`caSpecial('${c?.id}','${d.id}')`)}${B('Reprint paperwork',`ui.formDeal='${d.id}';ui.formSelFor=null;ui.formTab='print';closeModal();go('forms')`)} ${B('Amount due today',`caDueToday('${l?.id}','${d.id}')`,noL)}${B('Text the customer',`closeModal();textModal('${c?.id}',${act?`'${l.id}'`:'null'})`,c?.phone?'':'No phone')}${B('Title & registration',`closeModal();go('titleadmin')`)} ${B('Payment link (card)',`payLink('${l?.id}')`,noL)}${B(l&&l.paused?'Resume payments':'Pause payments',`caPause('${l?.id}','${d.id}')`,noL)}${B('Audit trail',`openCustomer('${c?.id}');ui.cTab='logs'`)} ${B('Refinance / rewrite',`closeModal();dealModal(null,null,'${c?.id}')`,noL)}${B('Customer documents',`openCustomer('${c?.id}');ui.cTab='files'`)}${B('Credit report',`toast('Credit reports need a credit bureau partner (e.g. 700Credit). See Settings → Connections')`)}
`,true)} function caSpecial(cid,did){const c=cust(cid);openModal(mh('Special message · '+esc(c.name))+`

Shows at the top of this customer’s activity screen and customer page for everyone.

`); $('#css').onclick=()=>{c.special=$('#csm').value.trim();c.notes.push({date:TODAY,by:S.settings.user,text:'Special message updated'});save();activityModal(did)}} function caDueToday(lid,did){const l=loan(lid);const pd=pastDue(l);openModal(mh('Amount due today · '+l.acct)+`
Past-due payments${$$(pd)}
Late fees${$$(l.lateFeesDue)}
Total due today${$$(pd+l.lateFeesDue)}
Next payment${$$(l.payment)} on ${fdate(nextDue(l))}
Days past due${daysLate(l)}
Promise${l.promise?$$(l.promise.amount)+' by '+fdate(l.promise.date):'None'}
`)} function caPause(lid,did){const l=loan(lid);if(l.paused){l.paused=false;l.notes.push({date:TODAY,by:S.settings.user,text:'Payments resumed'});save();toast('Payments resumed');return activityModal(did)} openModal(mh('Pause payments · '+l.acct)+`

Pausing stops reminder texts, automatic follow-ups and collection calls for this account. It does not change the contract or the payment schedule. Use “Refinance / rewrite” to change terms.

`); $('#cpf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);l.paused={until:x.until,why:x.why,by:S.settings.user,at:nowAt()};l.notes.push({date:TODAY,by:S.settings.user,text:`Payments paused until ${fdate(x.until)}: ${x.why}`});save();toast('Payments paused');activityModal(did)}} async function caPrint(did){const d=S.deals.find(x=>x.id===did),c=cust(d.customerId),v=veh(d.vehicleId),l=d.loanId?loan(d.loanId):null; const doc=`Customer summary ${esc(c?.name)}

${esc(S.settings.dealer||'')} · Customer summary

${esc(new Date().toLocaleString())}
${[['Customer',c?.name],['Address',c?.address],['Phone',c?.phone],['Email',c?.email],['Co-buyer',c?.cobuyer?.name],['Deal #',d.no],['Sale date',fdate(d.date)],['Sale type',d.type],['Vehicle',v?`${v.year} ${v.make} ${v.model} ${v.trim||''}`:''],['Stock #',v?.stock],['VIN',v?.vin],['Sale price',$$(d.price)],['Salesperson',uname(d.salespersonId)],...(l?[['Account',l.acct],['Payment',$$(l.payment)+' '+FREQ[l.freq].label.toLowerCase()],['Balance',$$(l.balance)],['Next due',fdate(nextDue(l))],['Days past due',daysLate(l)],['Payoff today',$$(payoff(l))]]:[]),...(d.type==='Retail Finance'?[['Lender',d.lender],['Amount financed',$$(d.financed)]]:[])].map(r=>``).join('')}
${r[0]}${esc(r[1]??'')}
`; if(DL){try{await DL.save({filename:`customer-${(c?.name||'summary').replace(/\W+/g,'-')}.html`,data:doc});toast('Saved. Open it to print')}catch(e){if(e.code!=='declined')copyText(doc)}}else{const w=window.open('','_blank');if(w){w.document.write(doc);w.document.close()}else copyText(doc)}} const CACSS=`.ca-card{padding:16px}.ca-table{max-height:calc(100vh - 290px);overflow:auto;border:1px solid var(--line);border-radius:10px}.ca-table thead th{position:sticky;top:0;background:#f7f8fa;z-index:1}.ca-table td{padding:7px 12px;white-space:nowrap;font-size:13.5px}.ca-table tbody tr:nth-child(even) td{background:#fafbfc}.ca-table tr.ca-row:focus-visible td{background:#eef3ff;outline:none} .ca-top{display:grid;grid-template-columns:1.1fr 1.3fr 1fr;gap:18px;padding-bottom:14px;border-bottom:1px solid var(--line)}.ca-stock{font-size:22px;font-weight:700;color:var(--red);font-family:var(--mono)}.ca-name{font-weight:700;color:#7a271a;font-size:15px}.ca-fin{font-weight:700;color:var(--green);font-size:15px;margin-bottom:6px} .ca-phones>div:not(.ca-fin){display:flex;justify-content:space-between;gap:8px;font-size:13px}.ca-phones span{color:var(--muted)}.ca-mid{padding:12px 0;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:8px}.ca-note{border-left:3px solid var(--brand);background:#f7f8fa;padding:8px 12px;border-radius:0 8px 8px 0} .ca-due{display:flex;gap:28px;justify-content:flex-end;flex-wrap:wrap}.ca-due span{display:block;font-size:12px;color:var(--muted)}.ca-due b{font-size:18px} .ca-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:14px}.ca-btn{justify-content:center;padding:10px}.ca-btn:disabled{opacity:.45;cursor:not-allowed} @media(max-width:800px){.ca-top{grid-template-columns:1fr}.ca-grid{grid-template-columns:1fr 1fr}}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Top-right: announcements, notifications, support center ================= */ const TI={mic:'',chat:'',mega:'',bell:'',head:'', spark:'',msg:'',tool:'',book:'',phone:''}; const tic=(k,s=20)=>``; function seenSet(){const u=me();u&&(u.seen=u.seen||{});return u?u.seen:(S.settings._seen=S.settings._seen||{})} function myNotifs(){const u=me();if(!u)return[];const out=[];const mine=c=>!c.ownerId||c.ownerId===u.id||['Owner','Sales Manager','Desking Manager'].includes(u.role);const mgr=['Owner','Sales Manager','Desking Manager'].includes(u.role); S.customers.filter(c=>isLead(c)&&mine(c)&&c.next&&c.next.dateout.push({id:'od_'+c.id+'_'+c.next.date,kind:'Follow-up overdue',text:`${c.name}: ${nxLabel(c.next)}`,go:`openCustomer('${c.id}')`,at:c.next.date})); S.customers.filter(c=>isLead(c)&&(c.createdAt||c.created||'')>=addDays(TODAY,-2)&&(c.ownerId===u.id||(!c.ownerId&&mgr))).forEach(c=>out.push({id:'nl_'+c.id,kind:c.ownerId?'New lead for you':'New lead (unassigned)',text:`${c.name}${c.source?' · '+c.source:''}`,go:`openCustomer('${c.id}')`,at:c.createdAt||c.created})); if(can('deals'))(S.onlineDeals||[]).filter(o=>o.status==='New').forEach(o=>out.push({id:'odl_'+o.id,kind:'Online deal waiting',text:`${cust(o.customerId)?.name||''} · ${o.stock||''}`,go:`ui.dealTab='online';go('deals')`,at:o.at})); S.customers.forEach(c=>(c.notes||[]).filter(n=>n.by==='Video'&&n.date>=addDays(TODAY,-2)&&mine(c)).forEach((n,i)=>out.push({id:'vv_'+c.id+'_'+n.date+i,kind:'Video watched',text:`${c.name} watched your video`,go:`openCustomer('${c.id}')`,at:n.date}))); if(can('accounts'))S.loans.forEach(l=>(l.payments||[]).filter(p=>p.method==='Online (card)'&&p.date>=addDays(TODAY,-3)).forEach(p=>out.push({id:'pay_'+p.id,kind:'Payment received',text:`${cust(l.customerId)?.name||''} paid ${$$(p.amount)} online`,go:`acctModal('${l.id}')`,at:p.date}))); if(can('comms'))S.customers.filter(mine).forEach(c=>{const t=S.comms.filter(x=>x.customerId===c.id).sort((a,b)=>b.at.localeCompare(a.at))[0];if(t&&t.dir==='in'&&t.at.slice(0,10)>=addDays(TODAY,-2))out.push({id:'in_'+t.id,kind:'New reply',text:`${c.name}: ${String(t.body||'').slice(0,60)}`,go:`ui.commTab='inbox';ui.commCid='${c.id}';go('comms')`,at:t.at})}); (S.customers.flatMap(c=>(c.tasks||[]).filter(t=>!t.done&&t.assignee===u.id&&t.due&&t.due<=TODAY).map(t=>({c,t})))).forEach(({c,t})=>out.push({id:'tk_'+t.id,kind:'Task due',text:`${t.text} · ${c.name}`,go:`openCustomer('${c.id}');ui.cTab='lead';ui.cFeed='task'`,at:t.due})); (S.wsTasks||[]).filter(t=>t.assignee===u.id&&t.status!=='Done'&&t.by!==u.id).forEach(t=>out.push({id:'wt_'+t.id,kind:'Task assigned to you',text:`${t.title}${t.due?' · due '+fdate(t.due):''} (from ${uname(t.by)})`,go:`ui.wsPane='tasks';go('workspace')`,at:t.at})); (S.wsMeet||[]).filter(m=>(m.attendees||[]).includes(u.id)&&m.date>=TODAY&&m.date<=addDays(TODAY,1)).forEach(m=>out.push({id:'wm_'+m.id,kind:'Meeting soon',text:`${m.title} · ${fdate(m.date)} ${m.time}`,go:`ui.wsPane='meet';go('workspace')`,at:m.date+'T'+(m.time||'00:00')})); (S.wsMsgs||[]).filter(m=>m.call&&m.by!==u.id&&m.at>=new Date(Date.now()-15*60000).toISOString().slice(0,16)).forEach(m=>{const r=wsRooms().find(z=>z.id===m.room);if(wsCanSee(r,u))out.push({id:'wc_'+m.id,kind:(m.call.video?'Video':'Audio')+' call',text:`${uname(m.by)} started a call in ${roomName(r)}`,go:`window.open('${m.call.url}','_blank','noopener')`,at:m.at})}); return out.sort((a,b)=>String(b.at).localeCompare(String(a.at))).slice(0,40)} function annList(){return (S.announcements||[]).filter(a=>!a.until||a.until>=TODAY).sort((a,b)=>b.at.localeCompare(a.at))} function topIcons(){const sn=seenSet();const n=myNotifs().filter(x=>!sn[x.id]).length;const a=annList().filter(x=>!sn['ann_'+x.id]).length; const w=wsUnreadAll();return ``} function drawTopIcons(){const el=$('#topicons');if(el)el.innerHTML=topIcons()} function topMenu(which){const el=$('#tmenu');if(el&&el.dataset.w===which){el.remove();return}if(el)el.remove();const box=document.createElement('div');box.id='tmenu';box.dataset.w=which;box.className='tmenu';box.setAttribute('role','dialog'); if(which==='help')box.innerHTML=`
${tic('head',18)} Support Center
${[['spark','AI Assistant','Ask anything about DealerPen or your data',`ui.aiTab='ask';go('ai')`,1],['mega','Dealer Messages','Announcements from your dealership',`topMenu('ann')`],['tool','My Support Cases','Report a problem and track it',`supportCases()`],['book','Training Center','Guides for every screen',`trainingCenter()`],['phone','Contact Us','Phone and email for help',`go('contact')`]].map(x=>``).join('')}`; else if(which==='bell'){const ns=myNotifs();const sn=seenSet();box.innerHTML=`
${tic('bell',18)} Notifications${ns.length?``:''}
${ns.map(x=>``).join('')||'
You’re all caught up
'}
`} else{const as=annList();const sn=seenSet();box.innerHTML=`
${tic('mega',18)} Dealer Messages${me()?.role==='Owner'||me()?.role==='Sales Manager'?``:''}
${as.map(a=>`
${esc(a.title)}
${esc(a.body)}
${esc(a.by)} · ${ftime(a.at)}
`).join('')||'
No messages
'}
`;as.forEach(a=>sn['ann_'+a.id]=1);save();setTimeout(drawTopIcons,0)} document.body.appendChild(box);const b=$('#topicons').getBoundingClientRect?$('#topicons').getBoundingClientRect():{right:innerWidth-20,bottom:60};box.style.top=(b.bottom+8)+'px';box.style.right=Math.max(12,innerWidth-b.right)+'px'; setTimeout(()=>document.addEventListener('click',function off(e){if(!e.target.closest('#tmenu')&&!e.target.closest('#topicons')){const m=$('#tmenu');m&&m.remove();document.removeEventListener('click',off)}}),0)} function annModal(){openModal(mh('Post a dealer message')+`

Everyone sees it under the megaphone icon at the top right.

`); $('#anf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);S.announcements=S.announcements||[];S.announcements.push({id:uid(),...x,by:S.settings.user,at:nowAt()});save();closeModal();drawTopIcons();toast('Posted')}} function supportInfo(){return Object.assign({name:'DealerPen Support',email:'',phone:'',hours:'Mon–Fri 9am–6pm'},S.settings.support||{})} function contactUs(){const s=supportInfo();const own=me()?.role==='Owner'; openModal(mh('Contact us')+`
${s.email||s.phone?`
Support${esc(s.name)}
${s.phone?``:''}${s.email?``:''}
Hours${esc(s.hours)}
`:'

Support contact details haven’t been set up yet.

'} ${own?`
Support details shown to your staff
`:''}
`); if($('#suf'))$('#suf').onsubmit=e=>{e.preventDefault();S.settings.support=fd(e.target);save();contactUs();toast('Saved')}} function supportCases(){const u=me();const all=(S.cases||[]).slice().reverse();const list=u?.role==='Owner'?all:all.filter(c=>c.by===u?.id); openModal(mh('My support cases')+`
${u?.role==='Owner'?'All cases from your staff':'Cases you opened'}
${list.map(c=>``).join('')||''}
#SubjectOpenedStatus
${c.no}${esc(c.subject)}
${esc(uname(c.by))} · ${esc(c.screen||'')}
${ftime(c.at)}${c.status}
No support cases
`,true)} function caseModal(id){S.cases=S.cases||[];const c=id?S.cases.find(x=>x.id===id):null;const s=supportInfo(); openModal(mh(c?`Case #${c.no} · ${esc(c.subject)}`:'New support case')+`
${c?`${(c.thread||[]).map(m=>`
${esc(m.text)}
${esc(uname(m.by)||m.by)} · ${ftime(m.at)}
`).join('')}${me()?.role==='Owner'?``:''}` :`
`}
${s.email?`Also email support`:''}
`,true); const f=$('#csf');if($('#csm')){const upd=()=>{$('#csm').href=`mailto:${encodeURIComponent(s.email)}?subject=${encodeURIComponent('[DealerPen] '+(c?c.subject:(f.subject?.value||'')))}&body=${encodeURIComponent((f.text?.value||'')+'\n\nDealer: '+(S.settings.dealer||'')+'\nUser: '+(me()?.name||''))}`};f.oninput=upd;upd()} f.onsubmit=e=>{e.preventDefault();const x=fd(f);if(c){if(x.text&&x.text.trim())(c.thread=c.thread||[]).push({by:me()?.id,text:x.text.trim(),at:nowAt()});if(x.status)c.status=x.status}else{S.settings.caseSeq=(S.settings.caseSeq||100)+1;S.cases.push({id:uid(),no:S.settings.caseSeq,subject:x.subject,screen:x.screen,pri:x.pri,by:me()?.id,at:nowAt(),status:'Open',thread:[{by:me()?.id,text:x.text,at:nowAt()}]})}save();supportCases();toast(c?'Saved':'Case submitted')}} const GUIDES=[['Getting started','Set up your dealership name, tax and fees in Settings, add users and roles, then add inventory or import it from Frazer or DealerCenter (Settings → Import).'], ['Leads and follow-up','New leads arrive in Leads & CRM. Every call, text or note asks for the next step. Follow-up plans send the first text and remind you to call. Overdue steps turn red on your Sales Rep Dashboard.'], ['The customer page','Click any customer to open their page: details on the left, status bar on top, activity and tabs in the middle, the vehicle they want on the right. Use Scan ID / document to fill details from a license or pay stub.'], ['Desking a deal','Deals & Desking → New deal. Pick the customer and vehicle, choose Cash, Retail finance or BHPH, then enter a credit score to see lender programs that fit. Save, print forms and send for e-signature.'], ['Customer Activity','Managers find any sold customer by last name, stock #, sale date, vehicle or phone, then post payments, reprint paperwork, view the sale recap, give payoff quotes or pause payments.'], ['Taking a payment','Loan Accounts → open the account → Post payment, or use Customer Activity → Enter a payment. Customers can also pay with a texted card link.'], ['Collections','Collections lists past-due accounts with call and text buttons. Log promises to pay; broken promises show up the next day.'], ['Inventory and photos','Inventory → Add vehicle (decode the VIN), add photos, recon costs and book values. Use Market to compare prices with similar cars.'], ['Dashboard','Click Customize dashboard to add, move and resize widgets. Each person has their own layout.'], ['Payroll','Accounting → Payroll & commissions. Set pay plans, add spiffs, print statements and export the payroll file.']]; function trainingCenter(){openModal(mh('Training Center')+`
${GUIDES.map(g=>`
${esc(g[0])}

${esc(g[1])}

`).join('')}

Still stuck? Ask the AI Assistant or open a support case.

`,true)} const TICSS=`#topicons{display:inline-flex;gap:4px;align-items:center}.ticon.ws-btn{width:auto;padding:0 12px;gap:6px;display:inline-flex;align-items:center;background:#eef3ff;color:var(--brand);font-weight:600;font-size:13.5px}.ticon.ws-btn:hover{background:#dbe6ff}@media(max-width:1250px){.ws-lbl{display:none}}.ticon{position:relative;width:38px;height:38px;border-radius:9px;border:0;background:transparent;color:var(--ink2);display:grid;place-items:center;cursor:pointer}.ticon:hover{background:#f2f4f7}.ticon:focus-visible{outline:3px solid #a9c1ff} .tbadge{position:absolute;top:2px;right:1px;min-width:17px;height:17px;padding:0 4px;border-radius:9px;background:#d92d20;color:#fff;font:700 10.5px/17px Inter,sans-serif;text-align:center} .tmenu{position:fixed;z-index:60;width:330px;max-height:70vh;overflow:auto;background:#fff;border:1px solid var(--line);border-radius:12px;box-shadow:0 16px 40px rgba(16,24,40,.18)}.tm-head{display:flex;align-items:center;gap:8px;padding:12px 14px;font-weight:700;background:var(--brand);color:#fff;position:sticky;top:0}.tm-head .btn{color:var(--ink2)} .tm-item{display:flex;gap:12px;align-items:flex-start;width:100%;text-align:left;border:0;background:#fff;padding:11px 14px;cursor:pointer;border-bottom:1px solid var(--line2);font:inherit;color:var(--ink2)}.tm-item:hover{background:#f7f8fa}.tm-item.hl{background:#f4f1ff;color:#4b2fb3}.tm-item span{display:flex;flex-direction:column}.tm-item small{color:var(--muted);font-size:12px}.tm-item.unread{background:#f5f8ff}.tm-item.unread b:before{content:'';display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--brand);margin-right:6px;vertical-align:middle} .tm-ann{padding:12px 14px;border-bottom:1px solid var(--line2)}.tm-ann small{color:var(--muted)}.tm-ann.unread{background:#f5f8ff}.tm-list .empty{padding:24px}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Contact Us page ================= */ const CONTACT_DEFAULT=[ {id:'rep',group:'Key contacts',title:'Your account rep',name:'',phone:'',email:'',icon:'user',action:''}, {id:'support',group:'Key contacts',title:'General support',name:'DealerPen Support',phone:'',email:'',icon:'head',action:'chat',actionUrl:''}, {id:'billing',group:'Key contacts',title:'Billing & accounts',name:'Billing team',phone:'',email:'',icon:'money',action:'pay',actionUrl:''}, {id:'bhph',group:'Platform specialists',title:'BHPH specialist',name:'',phone:'',email:'',icon:'car'}, {id:'crm',group:'Platform specialists',title:'CRM specialist',name:'',phone:'',email:'',icon:'users'}, {id:'web',group:'Platform specialists',title:'Website & marketing specialist',name:'',phone:'',email:'',icon:'globe'}, {id:'title',group:'Platform specialists',title:'Title & compliance specialist',name:'',phone:'',email:'',icon:'doc'}]; const CICO={user:'',head:TI.head,money:'',car:'',users:'',globe:'',doc:'',mail:'',phone:TI.phone,screen:''}; const cic=(k,s=20)=>``; function contacts(){const saved=S.settings.contacts;return Array.isArray(saved)&&saved.length?saved:JSON.parse(JSON.stringify(CONTACT_DEFAULT))} VIEWS.contact=()=>{const cs=contacts();const own=me()?.role==='Owner';const rs=S.settings.remoteUrl||'';const groups=[...new Set(cs.map(c=>c.group))]; return `
${cic('phone',22)}

Contact us

Get in touch with the people who support your dealership
${own?``:''}${rs?`${cic('screen',18)} Remote support session`:own?``:''}
${esc(S.settings.dealer||'DealerPen')} support
${groups.map(g=>`

${cic(g==='Key contacts'?'user':'users',18)} ${esc(g)}

${cs.filter(c=>c.group===g).map(c=>`
${cic(c.icon,22)}
${esc(c.title)}
${esc(c.name||'Not set up yet')}
${own?``:''}
${c.phone?`${cic('phone',15)} ${esc(c.phone)}`:''}${c.email?`${cic('mail',15)} ${esc(c.email)}`:''}${!c.phone&&!c.email?`${own?'Add a phone or email with Edit':'Contact details coming soon'}`:''}
${c.action==='chat'?``:''}${c.action==='pay'&&c.actionUrl?`Payment portal`:''}
`).join('')}
`).join('')}
`}; function contactEdit(id){const cs=contacts();const c=id?cs.find(x=>x.id===id):{id:'c_'+uid(),group:'Platform specialists',title:'',name:'',phone:'',email:'',icon:'user'}; openModal(mh(id?'Edit contact':'Add contact')+`
${id?'':''}
`); if($('#ctdel'))$('#ctdel').onclick=()=>{S.settings.contacts=cs.filter(x=>x.id!==id);save();closeModal();render()}; $('#ctf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(x.actionUrl&&!/^https:\/\//.test(x.actionUrl))return toast('Links must start with https://');Object.assign(c,x);if(!id)cs.push(c);S.settings.contacts=cs;save();closeModal();render();toast('Saved')}} function remoteSetup(){openModal(mh('Remote support session')+`

Paste the link your support team uses for screen sharing (for example a Zoom, Teams, TeamViewer QuickSupport or AnyDesk link). Staff click the button to start a session.

`); $('#rsf').onsubmit=e=>{e.preventDefault();const u=e.target.u.value.trim();if(u&&!/^https:\/\//.test(u))return toast('Links must start with https://');S.settings.remoteUrl=u;save();closeModal();render()}} const CTCSS=`.ct-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:16px}.ct-title{display:flex;gap:12px;align-items:center}.ct-title>svg{background:#eef3ff;color:var(--brand);border-radius:10px;padding:8px;width:40px;height:40px;box-sizing:border-box}.ct-title h2{margin:0;font-size:20px;font-weight:700}.ct-head .sp{flex:1}.ct-head .btn{gap:8px} .card.ct-wrap{padding:0;overflow:hidden}.ct-org{padding:16px 20px;font-weight:700;border-bottom:1px solid var(--line);background:#fafbfc}.ct-group{display:flex;align-items:center;gap:8px;margin:20px 20px 12px;font-size:15px;color:var(--ink)}.ct-group svg{color:var(--brand)} .ct-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;padding:0 20px}.ct-card{border:1px solid var(--line);border-radius:12px;padding:16px;display:flex;flex-direction:column;gap:12px;background:#fff} .ct-top{display:flex;gap:12px;align-items:flex-start}.ct-ico{width:42px;height:42px;border-radius:10px;display:grid;place-items:center;background:#eef3ff;color:var(--brand);flex:0 0 42px}.ic-money{background:#e7f6ee;color:#067647}.ic-car{background:#fdf4e3;color:#a15c07}.ic-globe{background:#fdeee8;color:#c4320a}.ic-doc{background:#f4f1ff;color:#4b2fb3} .ct-lines{display:flex;flex-direction:column;gap:6px}.ct-lines a{display:inline-flex;gap:7px;align-items:center;font-weight:500;text-decoration:none;overflow-wrap:anywhere}.ct-act{justify-content:center;gap:8px;margin-top:auto}.ct-foot{display:flex;gap:8px;padding:20px;border-top:1px solid var(--line);margin-top:20px;flex-wrap:wrap}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Team Workspace: rooms, DMs, voice, tasks, calls, meetings, calendar ================= */ const WS={rec:null,chunks:[],sr:null,transcript:'',start:0,timer:null,mode:'msg'}; const isMgr=u=>u&&['Owner','Sales Manager','Desking Manager'].includes(u.role); function wsRooms(){S.wsRooms=Array.isArray(S.wsRooms)?S.wsRooms:[];if(!S.wsRooms.some(r=>r.id==='general'))S.wsRooms.unshift({id:'general',name:'General',desc:'Everyone at the dealership',members:[],type:'room',by:'',at:nowAt()});return S.wsRooms} const wsCanSee=(r,u)=>r&&u&&(r.type==='dm'?(r.members||[]).includes(u.id):(!r.members||!r.members.length||r.members.includes(u.id)||u.role==='Owner')); function wsMyRooms(){const u=me();return wsRooms().filter(r=>wsCanSee(r,u))} const wsMsgs=room=>(S.wsMsgs||[]).filter(m=>m.room===room).sort((a,b)=>a.at.localeCompare(b.at)); function wsUnread(room){const u=me();if(!u)return 0;const lr=(u.wsRead||{})[room]||'';return (S.wsMsgs||[]).filter(m=>m.room===room&&m.by!==u.id&&m.at>lr).length} function wsUnreadAll(){return wsMyRooms().reduce((a,r)=>a+wsUnread(r.id),0)} function wsMarkRead(room){const u=me();if(!u)return;u.wsRead=u.wsRead||{};const last=wsMsgs(room).slice(-1)[0];if(last&&u.wsRead[room]!==last.at){u.wsRead[room]=last.at;save()}} function dmRoom(otherId){const u=me();const key=[u.id,otherId].sort().join('_');let r=wsRooms().find(x=>x.type==='dm'&&x.key===key);if(!r){r={id:'dm_'+uid(),type:'dm',key,members:[u.id,otherId],name:'',at:nowAt(),by:u.id};S.wsRooms.push(r);save()}return r} const roomName=r=>r.type==='dm'?uname((r.members||[]).find(x=>x!==me()?.id)||''):r.name; function wsPost(room,o){S.wsMsgs=S.wsMsgs||[];const m={id:uid(),room,by:me()?.id||'',at:nowAt(),...o};S.wsMsgs.push(m);if(S.wsMsgs.length>4000)S.wsMsgs=S.wsMsgs.slice(-3500);save();return m} function meetUrl(title){const p=S.settings.meetProvider||'jitsi';if(p==='fixed'&&S.settings.meetFixed)return S.settings.meetFixed;return 'https://meet.jit.si/LotLedger-'+String(S.settings.dealer||'team').replace(/\W+/g,'')+'-'+uid()+uid()} function gcalLink(title,date,time,mins,details){const st=new Date(`${date}T${time||'09:00'}:00`);if(isNaN(st))return '';const en=new Date(st.getTime()+(mins||30)*60000);const f=d=>d.toISOString().replace(/[-:]/g,'').replace(/\.\d+/,''); return `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(title)}&dates=${f(st)}/${f(en)}&details=${encodeURIComponent(details||'')}`} function wsFileURL(v){if(!v)return '';if(v.src==='srv')return srvURL(v.url);return photoURL(v)} VIEWS.workspace=()=>{const u=me();const rooms=wsMyRooms();let cur=ui.wsRoom&&rooms.find(r=>r.id===ui.wsRoom)?ui.wsRoom:'general';ui.wsRoom=cur;const room=rooms.find(r=>r.id===cur);const pane=ui.wsPane||'chat'; const myTasks=(S.wsTasks||[]).filter(t=>t.assignee===u?.id&&t.status!=='Done'); return `
Rooms${isMgr(u)?``:''}
${rooms.filter(r=>r.type!=='dm').map(r=>``).join('')}
Direct messages
${S.users.filter(x=>x.active&&x.id!==u?.id).map(x=>{const r=wsRooms().find(z=>z.type==='dm'&&z.key===[u?.id,x.id].sort().join('_'));const n=r?wsUnread(r.id):0;return ``}).join('')}
Planning
${pane==='tasks'?wsTasksPane():pane==='meet'?wsMeetPane():`
${room.type==='dm'?esc(roomName(room)):'# '+esc(room.name)}
${room.type==='dm'?'Direct message':esc(room.desc||'')+(room.members&&room.members.length?` · ${room.members.length} members`:' · everyone')}
${room.type!=='dm'&&(isMgr(u)&&(room.by===u.id||u.role==='Owner'))&&room.id!=='general'?``:''}
${wsMsgsHTML(room.id)}
`}
`}; function wsMsgsHTML(room){const ms=wsMsgs(room).slice(-300);const u=me();let last=''; return ms.map(m=>{const day=m.at.slice(0,10);const sep=day!==last?`
${fdate(day)}
`:'';last=day;const mine=m.by===u?.id; const t=m.task&&(S.wsTasks||[]).find(x=>x.id===m.task);const mt=m.meet&&(S.wsMeet||[]).find(x=>x.id===m.meet); return sep+`
${esc(ini(uname(m.by)))}
${esc(uname(m.by))} ${new Date(m.at).toLocaleTimeString([], {hour:'numeric',minute:'2-digit'})}
${m.text?`
${esc(m.text).replace(/@([A-Za-z]+)/g,'@$1')}
`:''} ${m.voice?`${m.transcript?`
“${esc(m.transcript)}”
`:''}`:''} ${m.call?`
${m.call.video?'Video':'Audio'} call started
${esc(uname(m.by))} is waiting
Join call
`:''} ${t?`
Task: ${esc(t.title)}
For ${esc(uname(t.assignee))}${t.due?' · due '+fdate(t.due)+(t.time?' '+t.time:''):''} · ${t.status}
${t.status!=='Done'&&(t.assignee===u?.id||isMgr(u))?``:''}${t.due?`Add to Google Calendar`:''}
`:''} ${mt?`
Meeting: ${esc(mt.title)}
${fdate(mt.date)} ${esc(mt.time||'')} · ${mt.dur||30} min
`:''}
`}).join('')||'
No messages yet. Say hello!
'} function wsRefresh(){if(route!=='workspace')return;const box=$('#wsmsgs');if(!box)return render();const atBottom=box.scrollHeight-box.scrollTop-box.clientHeight<60;box.innerHTML=wsMsgsHTML(ui.wsRoom);if(atBottom)box.scrollTop=box.scrollHeight;wsMarkRead(ui.wsRoom);drawTopIcons()} AFTER.workspace=()=>{const b=$('#wsmsgs');if(b){b.scrollTop=b.scrollHeight;wsMarkRead(ui.wsRoom);drawTopIcons()}const t=$('#wstx');if(t){t.focus();t.oninput=()=>{t.style.height='auto';t.style.height=Math.min(140,t.scrollHeight)+'px'}}}; function wsSend(){const t=$('#wstx');const txt=t.value.trim();if(!txt)return;wsPost(ui.wsRoom,{text:txt});t.value='';t.style.height='';wsRefresh()} function wsCall(room,video){const url=meetUrl()+(video?'':'#config.startWithVideoMuted=true');wsPost(room,{call:{url,video}});window.open(url,'_blank','noopener');wsRefresh()} function wsRoomModal(id){const r=id?wsRooms().find(x=>x.id===id):{name:'',desc:'',members:[]}; openModal(mh(id?'Room settings':'New room')+`

Members

${S.users.filter(u=>u.active).map(u=>``).join('')}
${id?'':''}
`); if($('#wrdel'))$('#wrdel').onclick=()=>confirmBox('Delete this room and its messages?',()=>{S.wsRooms=S.wsRooms.filter(x=>x.id!==id);S.wsMsgs=(S.wsMsgs||[]).filter(m=>m.room!==id);ui.wsRoom='general';save();render()}); $('#wrf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const all=$('#wrall').checked;const members=all?[]:S.users.filter(u=>x['m_'+u.id]).map(u=>u.id);if(!all&&me()&&!members.includes(me().id))members.push(me().id); if(id)Object.assign(r,{name:x.name,desc:x.desc,members});else{const nr={id:'r_'+uid(),type:'room',name:x.name,desc:x.desc,members,by:me()?.id,at:nowAt()};S.wsRooms.push(nr);ui.wsRoom=nr.id;wsPost(nr.id,{text:`created #${x.name}`})}save();closeModal();render()}} function wsTaskModal(room,pre){pre=pre||{};const members=(()=>{const r=wsRooms().find(x=>x.id===room);return S.users.filter(u=>u.active&&(!r||wsCanSee(r,u)))})(); openModal(mh('Assign a task')+`
${pre.transcript?`

From your voice note: “${esc(pre.transcript)}”

`:''}
`); $('#wtf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);S.wsTasks=S.wsTasks||[];const t={id:uid(),...x,room,by:me()?.id,at:nowAt(),status:'Open',voice:pre.voice||null};S.wsTasks.push(t);wsPost(room,{task:t.id,text:`@${uname(x.assignee).split(' ')[0]} new task`,voice:pre.voice||undefined,transcript:pre.transcript||undefined});closeModal();ui.wsPane='chat';render();toast('Task assigned to '+uname(x.assignee))}} function wsTaskDone(id){const t=(S.wsTasks||[]).find(x=>x.id===id);if(!t)return;t.status='Done';t.doneAt=nowAt();wsPost(t.room||'general',{text:`completed: ${t.title}`});render()} function wsTasksPane(){const u=me();const all=S.wsTasks||[];const f=ui.wsTF||'mine';const list=all.filter(t=>f==='mine'?t.assignee===u?.id:f==='given'?t.by===u?.id:true).sort((a,b)=>(a.status==='Done')-(b.status==='Done')||String(a.due).localeCompare(String(b.due))); return `
Tasks
${[['mine','Assigned to me'],['given','I assigned'],...(isMgr(u)?[['all','Everyone']]:[])].map(x=>``).join('')}
${list.map(t=>``).join('')||''}
TaskForFromDueStatus
${esc(t.title)}${t.notes?`
${esc(t.notes)}
`:''}${t.voice?``:''}
${esc(uname(t.assignee))}${esc(uname(t.by))}${t.due?fdate(t.due)+(t.time?' '+t.time:''):'—'}${t.status}${t.status!=='Done'?``:''} ${t.due?`Calendar`:''}
No tasks
`} function wsMeetModal(room){openModal(mh('Schedule a meeting')+`

Everyone in the room gets it in chat, in their notifications and on their DealerPen calendar feed.

`); const f=$('#wmf');f.prov.onchange=()=>{$('#wmpl').hidden=f.prov.value!=='paste'}; f.onsubmit=e=>{e.preventDefault();const x=fd(f);if(x.prov==='paste'&&!/^https:\/\//.test(x.link||''))return toast('Paste a full https:// link');const url=x.prov==='paste'?x.link:x.prov==='fixed'?S.settings.meetFixed:meetUrl(); S.wsMeet=S.wsMeet||[];const r=wsRooms().find(z=>z.id===room);const mt={id:uid(),title:x.title,date:x.date,time:x.time,dur:+x.dur||30,url,room,by:me()?.id,at:nowAt(),attendees:r&&r.members&&r.members.length?r.members:S.users.filter(u=>u.active).map(u=>u.id)};S.wsMeet.push(mt);wsPost(room,{meet:mt.id});closeModal();render();toast('Meeting scheduled')}} function wsMeetPane(){const u=me();const list=(S.wsMeet||[]).filter(m=>(m.attendees||[]).includes(u?.id)||m.by===u?.id).sort((a,b)=>(a.date+a.time).localeCompare(b.date+b.time));const up=list.filter(m=>m.date>=TODAY),past=list.filter(m=>m.date`${esc(m.title)}
${esc(roomName(wsRooms().find(r=>r.id===m.room)||{name:''}))} · by ${esc(uname(m.by))}
${fdate(m.date)} ${esc(m.time)}${m.dur} minJoin Add to Google Calendar`; return `
Meetings

Upcoming

${up.map(row).join('')||''}
Nothing scheduled
${past.length?`

Past

${past.map(row).join('')}
`:''} ${isMgr(u)?`
Video meetings use free Jitsi Meet links by default (no account needed). Use your own Zoom, Google Meet or Teams room instead.
`:''}
`} function wsMeetSettings(){openModal(mh('Meeting links')+`
`); $('#wms').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(x.p==='fixed'&&!/^https:\/\//.test(x.u||''))return toast('Paste a full https:// link');S.settings.meetProvider=x.p;S.settings.meetFixed=x.u||'';save();closeModal();render()}} async function wsCalendar(){let feed='';if(DBM.on){const r=await dbFetch('/api/cal/token',{method:'POST',body:{}});if(r.ok)feed=r.body.url} openModal(mh('Connect to Google Calendar')+`
${feed?`

Add your personal DealerPen calendar to Google Calendar once. Your assigned tasks, team meetings and customer appointments then show up automatically and stay updated.

  1. Copy your calendar link:
    ${esc(feed)}
  2. Open Google Calendar → Add calendar → From URL ↗
  3. Paste the link and click Add calendar.

Google refreshes subscribed calendars on its own schedule (usually every few hours). Keep this link private; anyone with it can see your schedule. Make a new link if it leaks.

` :`

Every task and meeting has an Add to Google Calendar button. For a calendar that updates automatically, run DealerPen from the DealerPen server; each person then gets a private calendar link to add to Google Calendar.

`}
${feed?``:''}
`)} /* voice messages + voice-to-task */ async function wsVoice(mode){if(WS.rec){WS.rec.stop();return}if(!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder==='undefined')return toast('Voice recording isn’t supported in this browser'); let stream;try{stream=await navigator.mediaDevices.getUserMedia({audio:true})}catch(e){return toast('Allow microphone access to record')} WS.mode=mode;WS.chunks=[];WS.transcript='';const mt=['audio/webm','audio/mp4','audio/ogg'].find(t=>MediaRecorder.isTypeSupported?.(t))||'';const rec=new MediaRecorder(stream,mt?{mimeType:mt}:{});WS.rec=rec;WS.start=Date.now(); const SR=window.SpeechRecognition||window.webkitSpeechRecognition;if(SR){try{const sr=new SR();sr.continuous=true;sr.interimResults=true;sr.lang='en-US';sr.onresult=e=>{let t='';for(const r of e.results)t+=r[0].transcript;WS.transcript=t;const b=$('#wsrec');if(b)b.querySelector('.ws-live').textContent=t};sr.start();WS.sr=sr}catch(e){}} const box=$('#wsrec');if(box){box.hidden=false;box.innerHTML=`0:00 ${mode==='task'?'Say who, what and when, e.g. “Jake, call Omar about his trade tomorrow at 10”':'Recording…'}`} WS.timer=setInterval(()=>{const s=Math.floor((Date.now()-WS.start)/1000);const c=$('#wsclock');if(c)c.textContent=Math.floor(s/60)+':'+String(s%60).padStart(2,'0');if(s>=300)rec.stop()},500); rec.ondataavailable=e=>{if(e.data.size)WS.chunks.push(e.data)}; rec.onstop=async()=>{clearInterval(WS.timer);stream.getTracks().forEach(t=>t.stop());try{WS.sr&&WS.sr.stop()}catch(e){}WS.sr=null;WS.rec=null;const box2=$('#wsrec');if(box2)box2.hidden=true;if(WS.cancel){WS.cancel=false;return} const blob=new Blob(WS.chunks,{type:rec.mimeType||'audio/webm'});const dur=Math.round((Date.now()-WS.start)/1000);if(dur<1)return;await new Promise(r=>setTimeout(r,400));const transcript=WS.transcript.trim(); let voice=null;try{voice=await wsUpload(blob)}catch(e){toast('Couldn’t save the recording');return}voice.dur=dur; if(WS.mode==='task')return wsTaskFromVoice(voice,transcript);wsPost(ui.wsRoom,{voice,transcript:transcript||undefined});wsRefresh()}; rec.start(1000)} async function wsUpload(blob){if(DBM.on){const h={...srvHeaders(),'Content-Type':blob.type.split(';')[0]};const r=await fetch(srvURL('/api/files'),{method:'POST',headers:h,body:blob});if(!r.ok)throw new Error('upload');const j=await r.json();return{src:'srv',url:j.url,id:j.id}} if(ASSETS){const r=await ASSETS.upload(blob,{type:blob.type.split(';')[0]});return{id:r.id,src:'a'}}const id=uid();await idbOp('readwrite',s=>s.put(blob,id));IDBURL[id]=URL.createObjectURL(blob);return{id,src:'i'}} async function wsTaskFromVoice(voice,transcript){const pre={voice,transcript,title:transcript};const people=S.users.filter(u=>u.active); if(transcript&&SAMPLE){try{const r=await ai(`A dealership manager recorded this voice note to assign a task: "${transcript}". Today is ${TODAY} (${new Date().toLocaleDateString('en-US',{weekday:'long'})}). Staff: ${people.map(u=>u.name+' (id '+u.id+')').join(', ')}. Reply with only JSON {"assignee_id":"","title":"short task in imperative form","due":"YYYY-MM-DD or empty","time":"HH:MM or empty","notes":""}. Use an empty assignee_id if no staff member is clearly named.`,{tier:'quick',nocache:true}); if(r){if(people.some(u=>u.id===r.assignee_id))pre.assignee=r.assignee_id;if(r.title)pre.title=r.title;if(/^\d{4}-\d{2}-\d{2}$/.test(r.due||''))pre.due=r.due;if(/^\d{2}:\d{2}$/.test(r.time||''))pre.time=r.time;pre.notes=r.notes||''}}catch(e){}} if(transcript&&!pre.assignee){const lw=transcript.toLowerCase();const hit=people.find(u=>lw.includes(u.name.toLowerCase().split(' ')[0]));if(hit)pre.assignee=hit.id;if(/tomorrow/.test(lw))pre.due=addDays(TODAY,1);else if(/today|tonight/.test(lw))pre.due=TODAY} if(!transcript)toast('Couldn’t transcribe it here. Type the task; the voice note is attached');wsTaskModal(ui.wsRoom||'general',pre)} const WSCSS=`.ws{display:grid;grid-template-columns:260px minmax(0,1fr);gap:14px;height:calc(100vh - 120px)}.ws-side{padding:10px;overflow:auto}.ws-sec{display:flex;align-items:center;justify-content:space-between;font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin:14px 8px 6px}.ws-sec:first-child{margin-top:4px} .ws-room{display:flex;align-items:center;justify-content:space-between;gap:6px;width:100%;border:0;background:transparent;text-align:left;padding:7px 10px;border-radius:8px;font:500 14px inherit;color:var(--ink2);cursor:pointer}.ws-room:hover{background:#f2f4f7}.ws-room.on{background:#eef3ff;color:var(--brand);font-weight:600} .ws-main{padding:0;display:flex;flex-direction:column;min-height:0;overflow:hidden}.ws-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid var(--line)}.ws-head .sp{flex:1}.ws-head .btn{gap:6px} .ws-msgs{flex:1;overflow:auto;padding:14px 16px}.ws-day{text-align:center;font-size:12px;color:var(--muted);margin:12px 0}.ws-msg{display:flex;gap:10px;margin-bottom:12px}.ws-b{min-width:0;max-width:720px}.ws-meta{font-size:13px}.ws-text{white-space:pre-wrap;overflow-wrap:anywhere;margin-top:2px}.ws-at{color:var(--brand)}.ws-tr{font-style:italic;margin-top:2px}.ws-msg audio{height:36px;margin-top:4px;max-width:100%} .ws-card{border:1px solid var(--line);border-radius:10px;padding:10px 12px;margin-top:6px;background:#fafbfc;display:flex;flex-direction:column;gap:6px}.ws-card .btn{align-self:flex-start} .ws-compose{border-top:1px solid var(--line);padding:10px 12px;display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap}.ws-compose textarea{flex:1;min-width:200px;resize:none;border:1px solid #d0d5dd;border-radius:10px;padding:10px 12px;font:inherit;max-height:140px} .ws-rec{flex-basis:100%;display:flex;align-items:center;gap:10px;background:#fdeee8;border-radius:10px;padding:8px 12px}.ws-live{font-style:italic;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:40%}.ws-dot{width:10px;height:10px;border-radius:50%;background:#d92d20;animation:wsb 1s infinite}@keyframes wsb{50%{opacity:.3}} @media(max-width:820px){.ws{grid-template-columns:1fr;height:auto}.ws-side{max-height:220px}.ws-main{height:70vh}}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Desking worksheet (full page) ================= */ const WSTYPES=[['Cash','Cash sale'],['Retail Finance','Outside financing'],['BHPH','Buy here pay here'],['Wholesale','Wholesale']]; function newSheet(o={}){const st=S.settings;const v=o.vehicleId&&veh(o.vehicleId);const bh=(o.type||'BHPH')==='BHPH'; return Object.assign({id:'wk_'+uid(),status:'Desking',at:nowAt(),by:me()?.id||'',date:TODAY,delivery:TODAY,type:'BHPH',customerId:'',cobuyer:'',vehicleId:'',price:v?+v.price:0,taxable:true,taxRate:+st.taxRate||0,taxLock:false,taxOverride:0, tradeAllow:0,tradePayoff:0,tradeDesc:'',fees:[{n:'Doc fee',a:+st.docFee||0},{n:'Tag & title',a:0}],vsc:0,gap:0,acc:0,deposit:0,down:0,pickup:0,apr:bh?+st.apr||19.9:9.9,buyRate:0,term:bh?+st.term||78:60,freq:bh?st.freq||'biweekly':'monthly',firstDays:bh?14:30, calcBy:'term',payAmt:0,interest:'simple',firstDate:'',stips:[],notes:[],grid:{downs:[0,1000,2000],rows:bh?[[52,+st.apr||19.9],[78,+st.apr||19.9],[104,+st.apr||19.9]]:[[36,7.9],[48,8.9],[60,9.9]]},lender:'',score:''},o)} function sheetCalc(w,downOverride,termOverride,aprOverride){const fees=(w.fees||[]).reduce((a,f)=>a+(+f.a||0),0);const doc=+((w.fees||[]).find(f=>/doc/i.test(f.n))?.a||0);const net=(+w.tradeAllow||0)-(+w.tradePayoff||0); const base=Math.max(0,(+w.price||0)+doc+(+w.acc||0)-(+w.tradeAllow||0));const tax=w.taxLock?+w.taxOverride||0:w.taxable?r2(base*(+w.taxRate||0)/100):0; const products=(+w.vsc||0)+(+w.gap||0)+(+w.acc||0);const cashPrice=r2((+w.price||0)+fees+products+tax-net);const down=downOverride!=null?downOverride:(+w.down||0);const totalDown=r2((+w.deposit||0)+down+(+w.pickup||0)); const fin=w.type==='Retail Finance'||w.type==='BHPH';const financed=fin?Math.max(0,r2(cashPrice-totalDown)):0;const ppy=FREQ[w.freq]?.ppy||12;const term=termOverride!=null?termOverride:+w.term||0,apr=aprOverride!=null?aprOverride:+w.apr||0; let term2=term;if(fin&&w.calcBy==='payment'&&+w.payAmt>0&&termOverride==null){const r=apr/100/ppy,P=+w.payAmt;term2=r?Math.ceil(-Math.log(1-Math.min(.9999,financed*r/P))/Math.log(1+r)):Math.ceil(financed/P);if(!isFinite(term2)||term2<1)term2=0} const payment=fin?(w.calcBy==='payment'&&termOverride==null&&+w.payAmt>0?Math.min(+w.payAmt,r2(pmt(financed,apr,term2,ppy))):r2(pmt(financed,apr,term2,ppy))):0;const tot=r2(payment*term2);const v=veh(w.vehicleId); return{fees,doc,net,tax,products,cashPrice,totalDown,financed,payment,term:term2,apr,ppy,totalPay:tot,financeCharge:fin?Math.max(0,r2(tot-financed)):0,remaining:fin?0:r2(cashPrice-totalDown),gross:v?r2((+w.price||0)-vcost(v)):0,fin}} function curSheet(){S.worksheets=S.worksheets||[];let w=S.worksheets.find(x=>x.id===ui.sheet);if(!w){w=newSheet();S.worksheets.push(w);ui.sheet=w.id}return w} function openSheet(o){S.worksheets=S.worksheets||[];let w=o&&o.id?S.worksheets.find(x=>x.id===o.id):null;if(!w){if(o&&(o.customerId||o.vehicleId)){w=S.worksheets.find(x=>x.status==='Desking'&&x.customerId===o.customerId&&x.vehicleId===o.vehicleId&&o.customerId)}if(!w){w=newSheet(o||{});S.worksheets.push(w)}}ui.sheet=w.id;save();closeModal();if(route==='deskws')render();else go('deskws')} function wset(k,v){const w=curSheet();const num=!['type','freq','customerId','vehicleId','cobuyer','tradeDesc','lender','date','delivery','calcBy','interest','firstDate'].includes(k);w[k]=num?(v===''?0:+v):v; if(k==='vehicleId'){const vv=veh(v);if(vv)w.price=+vv.price||0}if(k==='type'){const bh=v==='BHPH';if(bh){w.freq=S.settings.freq||'biweekly';w.apr=+S.settings.apr||19.9;w.term=+S.settings.term||78;w.grid.rows=[[52,w.apr],[78,w.apr],[104,w.apr]]}else if(v==='Retail Finance'){w.freq='monthly';w.apr=w.apr>15?9.9:w.apr;w.term=60;w.grid.rows=[[36,w.apr],[48,w.apr],[60,w.apr]]}} w.at=nowAt();save();render()} VIEWS.deskws=()=>{const w=curSheet();const k=sheetCalc(w);const v=veh(w.vehicleId),c=cust(w.customerId);const mgr=isMgr(me());const tab=ui.wsTab||'work';const fin=k.fin; const num=(label,key,sign,opt={})=>`
${sign||''}${opt.after||''}
`; const ro=(label,val,cls)=>`
${label}${val}
`; const avail=S.vehicles.filter(x=>['Available','Pending'].includes(x.status)||x.id===w.vehicleId); const head=`
${v?esc(`${v.year} ${v.make} ${v.model} ${v.trim||''}`):'No vehicle selected'}
${v?`Stock # ${esc(v.stock)} · ${(+v.miles).toLocaleString()} mi · ${$0(v.price)} asking`:''}
${c?`${esc(c.name)}`:'No customer chosen'}
${c?esc(c.phone||'')+((S.creditApps||[]).some(a=>a.customerId===c.id)?' · credit app on file':''):''}${w.cobuyer?' · co-buyer: '+esc(w.cobuyer):''}
${c?``:''}
${esc(w.status)} ${WSTYPES.find(t=>t[0]===w.type)?.[1]||''}
${WSTYPES.map(t=>``).join('')}
Sale · Delivery
`; const tabs=`
${[['work','Worksheet'],['offers','Lender offers'],['trade','Trade-in'],['lien','Lien holder'],['stips','Stipulations'+((w.stips||[]).filter(x=>!x.got).length?' ('+(w.stips||[]).filter(x=>!x.got).length+')':'')],['notes','Notes'],['files','Files'],['events','Events'],['costs','Dealer costs']].map(t=>``).join('')}
`; if(tab!=='work')return dkRail(w)+`
`+head+tabs+sheetSubTab(w,k,tab)+'
'; const left=`

Pricing

${num('Vehicle price','price','')}
${ro('Net trade-in',`${$$(k.net)}`,'')} ${(w.fees||[]).map((f,i)=>`
+
`).join('')}
${num('Service contract (VSC)','vsc','+')}${num('GAP / insurance','gap','+')}${num('Accessories','acc','+')}
Taxes+
${ro('Total cash price',$$(k.cashPrice),'dk-total')}
${num('Deposit','deposit','−')}${num('Down payment','down','−')}${num('Pick-up note (deferred down)','pickup','−')}${ro('Total down',$$(k.totalDown),'dk-total')}
${fin?`${ro('Amount financed',$$(k.financed),'dk-big')}
Payment schedule${Object.entries(FREQ).map(([kk,f])=>``).join('')}
Work out the financing by
${num('APR %','apr','')}${w.type==='Retail Finance'?num('Buy rate %','buyRate',''):''} ${w.calcBy==='payment'?num('Payment amount','payAmt','')+ro('Number of payments',k.term||'—',''):num('Number of payments','term','')+ro(FREQ[w.freq].label+' payment',$$(k.payment),'dk-big')}
${ro('Finance charge',$$(k.financeCharge))}${ro('Total of payments',$$(k.totalPay))} ${w.type==='BHPH'?`
How interest is earned
DealerPen accounts use simple interest. Precompute contracts need your state's precompute disclosures; check with your form provider.
`:''}`:ro('Remaining balance',$$(k.remaining),'dk-big')}
`; const g=w.grid;const cellPay=(d,row)=>sheetCalc(w,d,row[0],row[1]).payment; const center=`

Payment options${fin?FREQ[w.freq].label:''}

${fin?`
Down
${g.downs.map((d,i)=>`
`).join('')} ${g.rows.map((row,ri)=>`
pmts · %
${g.downs.map((d,di)=>{const sel=+w.down===d&&+w.term===row[0]&&+w.apr===row[1];return ``}).join('')}`).join('')}

Click a payment to use that down payment, term and rate. Change any box to try other numbers.

`:'
Cash and wholesale deals have no payment options. Switch the type of sale to finance it.
'}
${w.type==='Retail Finance'?``:''}${c?``:''}${fin?'':``}
`; const right=`

Deal summary

${$$(k.totalDown)}down
${fin?k.term:'—'}${fin?'payments':''}
${fin?k.apr+'%':'—'}APR
${fin?$$(k.payment):$$(k.remaining)}${fin?FREQ[w.freq].label.toLowerCase():'due at signing'}
${[['Cash price',$$(k.cashPrice)],['Amount financed',$$(k.financed)],['Finance charge',$$(k.financeCharge)],['Total of payments',$$(k.totalPay)],['Doc fee',$$(k.doc)],['Taxes',$$(k.tax)],['Products',$$(k.products)],['First payment',fin?fdate(w.firstDate||addDays(w.date,+w.firstDays||30)):'—']].map(r=>`
${r[0]}${r[1]}
`).join('')} ${mgr&&v&&ui.dealerView!==false?`
Vehicle cost + recon${$$(vcost(v))}
Front gross${$$(k.gross)}
${w.type==='Retail Finance'&&w.buyRate?`
Rate spread reserve (est.)${$$(Math.max(0,k.totalPay-r2(pmt(k.financed,w.buyRate,k.term,k.ppy)*k.term))*0.75)}
`:''}
`:''}

Book values & credit

${v?``:''}${c?``:''}
`; return dkRail(w)+`
`+head+tabs+`
${left}${center}${right}
`}; function sheetSubTab(w,k,tab){ if(tab==='offers'){if(w.type!=='Retail Finance')return '
Lender offers are for outside financing. Switch the type of sale to Outside financing.
';if(!w.vehicleId)return '
Pick a vehicle first
';const k2=sheetCalc(w);const x={vehicleId:w.vehicleId,price:w.price,docFee:k2.doc,taxRate:w.taxable?w.taxRate:0,tradeAllow:w.tradeAllow,tradePayoff:w.tradePayoff,down:k2.totalDown,otherFees:k2.fees-k2.doc+k2.products,score:w.score}; return `

Lender offers

${programsHTML(x).replace(/applyProgram\(/g,'sheetApply(')}

Submit the application through Dealertrack, RouteOne or CUDL from Finance Apps.

`} if(tab==='stips')return stipsPane(w); if(tab==='notes')return `

Deal notes

${(w.notes||[]).slice().reverse().map(n=>`
${esc(n.text)}
${esc(uname(n.by))} · ${ftime(n.at)}
`).join('')||'
No notes yet
'}
`; if(tab==='files'){const c=cust(w.customerId);if(!c)return '
Pick a customer first
';return `

Files for ${esc(c.name)}

${(c.files||[]).map(f=>{const u=photoURL(f);return `
${esc(f.name)}
${ftime(f.at)}
${u?`Open`:''}
`}).join('')||'
No files yet
'}
`} if(tab==='events'){const ev=[{at:w.at,t:'Worksheet updated by '+uname(w.by)},...(w.notes||[]).map(n=>({at:n.at,t:'Note: '+n.text})),...(w.stips||[]).filter(s=>s.got).map(s=>({at:s.got,t:'Stip received: '+s.n})),...(w.stipSent?[{at:w.stipSent,t:'Stips requested from customer'}]:[]),...(w.dealId?[{at:(S.deals.find(d=>d.id===w.dealId)||{}).date||'',t:'Completed as sale'}]:[])].sort((a,b)=>String(b.at).localeCompare(String(a.at))); return `

Events

${ev.map(e=>`
${esc(e.t)}
${String(e.at).length>10?ftime(e.at):fdate(e.at)}
`).join('')}
`}if(tab==='trade')return `

Trade-in

Net trade (equity)${$$(k.net)}
${k.net<0?'

Negative equity is added to the amount financed.

':''}
`; if(tab==='lien')return `

Lien holder

${w.type==='BHPH'?'On buy-here-pay-here deals your dealership is the lien holder.':'Use Lender programs on the worksheet to see which tiers fit.'}

`; const v=veh(w.vehicleId);if(!isMgr(me())||ui.dealerView===false)return '
Dealer costs are hidden. Managers can show them with “Show dealer view”.
'; return `

Dealer costs

${v?`${[['Purchase cost',$$(+v.cost||0)],['Recon',$$(reconTotal(v))],['Total cost',$$(vcost(v))],['Sale price',$$(w.price)],['Front gross',$$(k.gross)],['Days in stock',age(v)]].map(r=>`
${r[0]}${r[1]}
`).join('')}`:'
Pick a vehicle first
'}
`} function sheetDriveOut(){const w=curSheet();const k=sheetCalc(w);openModal(mh('Adjust to a drive-out price')+`

Enter the total the customer should pay out the door (price, fees, products and tax, less trade). DealerPen works out the vehicle price.

`); $('#dof').onsubmit=e=>{e.preventDefault();const t=+e.target.t.value;const r=w.taxable&&!w.taxLock?(+w.taxRate||0)/100:0;const k0=sheetCalc({...w,price:0});const p=r2((t-k0.cashPrice)/(1+r));if(p<=0)return toast('That drive-out is less than the fees and products');w.price=p;save();closeModal();render();toast('Price set to '+$$(p))}} function sheetPrograms(){const w=curSheet();const k=sheetCalc(w);if(!w.vehicleId)return toast('Pick a vehicle first');const x={vehicleId:w.vehicleId,price:w.price,docFee:k.doc,taxRate:w.taxable?w.taxRate:0,tradeAllow:w.tradeAllow,tradePayoff:w.tradePayoff,down:k.totalDown,otherFees:k.fees-k.doc+k.products,score:w.score}; openModal(mh('Lender programs')+`
${programsHTML(x).replace(/applyProgram\(/g,'sheetApply(')}
`,true)} function sheetApply(o){const w=curSheet();w.lender=o.lender;w.apr=o.rate;w.term=o.term;w.freq='monthly';save();closeModal();render();toast('Program applied')} function sheetQuoteText(w,k){const v=veh(w.vehicleId),c=cust(w.customerId);const g=w.grid; return `${S.settings.dealer||''} · Quote for ${c?.name||'customer'}\n${v?`${v.year} ${v.make} ${v.model} (stock ${v.stock})`:''}\nCash price ${$$(k.cashPrice)}${k.fin?`\n${g.downs.map(d=>`${$$(d)} down: `+g.rows.map(r=>`${r[0]} pmts ${$$(sheetCalc(w,d,r[0],r[1]).payment)}`).join(' / ')).join('\n')}`:''}\nEstimate only. Taxes, fees and approval are confirmed at signing.`} async function sheetQuote(kind){const w=curSheet();const k=sheetCalc(w);const c=cust(w.customerId),v=veh(w.vehicleId);const txt=sheetQuoteText(w,k); if(kind==='text'){if(!c)return toast('Pick a customer first');return textModal(c.id,null,null,txt)} if(kind==='email'){if(!c)return toast('Pick a customer first');emailModal(c.id);setTimeout(()=>{const f=$('#emf');if(f){f.subject.value='Your quote from '+(S.settings.dealer||'');f.body.value=txt;f.dispatchEvent(new Event('input'))}},50);return} const rows=[['Vehicle',v?`${v.year} ${v.make} ${v.model} ${v.trim||''} · stock ${v.stock} · VIN ${v.vin}`:''],['Customer',c?.name||''],['Vehicle price',$$(w.price)],...(w.fees||[]).map(f=>[f.n,$$(f.a)]),['Service contract',$$(w.vsc)],['GAP / insurance',$$(w.gap)],['Accessories',$$(w.acc)],['Taxes',$$(k.tax)],['Net trade-in',$$(k.net)],['Total cash price',$$(k.cashPrice)],['Total down',$$(k.totalDown)],...(k.fin?[['Amount financed',$$(k.financed)],['APR',w.apr+'%'],['Term',w.term+' '+FREQ[w.freq].label.toLowerCase()+' payments'],['Payment',$$(k.payment)],['Finance charge',$$(k.financeCharge)],['Total of payments',$$(k.totalPay)]]:[['Remaining balance',$$(k.remaining)]]),...(kind==='recap'&&isMgr(me())&&v?[['Vehicle cost + recon',$$(vcost(v))],['Front gross',$$(k.gross)]]:[])]; const grid=k.fin?`

Payment options

${w.grid.downs.map(d=>``).join('')}${w.grid.rows.map(r=>`${w.grid.downs.map(d=>``).join('')}`).join('')}
${$$(d)} down
${r[0]} pmts @ ${r[1]}%${$$(sheetCalc(w,d,r[0],r[1]).payment)}
`:''; const doc=`${kind==='recap'?'Pricing recap':'Quote'}

${esc(S.settings.dealer||'')} · ${kind==='recap'?'Pricing recap':'Payment quote'}

${esc(fdate(TODAY))}
${rows.map(r=>``).join('')}
${esc(r[0])}${esc(r[1])}
${grid}

Estimate only, not an offer of credit. Final price, taxes, fees, rate and terms are set in the signed contract.

`; if(DL){try{await DL.save({filename:`${kind==='recap'?'recap':'quote'}-${(c?.name||'customer').replace(/\W+/g,'-')}.html`,data:doc});toast('Saved. Open it to print')}catch(e){if(e.code!=='declined')copyText(doc)}}else{const wn=window.open('','_blank');if(wn){wn.document.write(doc);wn.document.close()}else copyText(doc)}} function sheetList(){const ws=(S.worksheets||[]).slice().reverse();openModal(mh('Saved worksheets')+`
${ws.map(w=>``).join('')||''}
CustomerVehicleTypeUpdatedStatus
${esc(cust(w.customerId)?.name||'—')}${esc(veh(w.vehicleId)?vname(veh(w.vehicleId)):'—')}${esc(w.type)}${ftime(w.at)}${esc(w.status)}
No worksheets
`,true)} function sheetComplete(){const w=curSheet();if(w.dealId&&S.deals.find(d=>d.id===w.dealId))return dealView(w.dealId);const k=sheetCalc(w);ui.pendingSheet=w.id;if(!w.vehicleId||!w.customerId)return toast('Pick the vehicle and customer first');if(w.type==='Wholesale')return toast('Record wholesale sales from the vehicle: set status to Wholesale and log the sale'); const others=r2(k.fees-k.doc+k.products);dealModal(null,w.vehicleId,w.customerId); setTimeout(()=>{const f=$('#df');if(!f)return;const set=(n,v)=>{if(f[n]!==undefined&&f[n]!==null&&'value' in f[n])f[n].value=v};set('type',w.type);set('date',w.date);set('price',w.price);set('docFee',k.doc);set('otherFees',others);set('taxRate',w.taxable&&!w.taxLock?w.taxRate:0);set('tradeAllow',w.tradeAllow);set('tradePayoff',w.tradePayoff);set('tradeDesc',w.tradeDesc);set('down',k.totalDown);set('apr',w.apr);set('term',k.term);set('freq',w.freq);if(w.lender)set('lender',w.lender); f.dispatchEvent(new Event('input'));w.status='Sent to deal';save();toast('Check the deal and finalize it. Fees and products are under Other fees'+(w.taxLock?'. Tax was typed by hand; re-check it':''))},40)} const DKCSS=`.dk-head{display:grid;grid-template-columns:1fr 1.2fr 1fr;gap:12px}.dk-hcard{background:#fff;border:1px solid var(--line);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:6px;min-width:0}.dk-htitle{font-weight:700;font-size:15px}.dk-hcard select{padding:6px 8px;border:1px solid #d0d5dd;border-radius:7px;max-width:100%}.dk-radios{display:grid;grid-template-columns:1fr 1fr;gap:2px 10px;font-size:13px} .dk-wrap{display:grid;grid-template-columns:minmax(330px,1fr) minmax(380px,1.25fr) minmax(280px,.9fr);gap:14px;align-items:start}.dk-col{padding:16px} .dk-row{display:grid;grid-template-columns:minmax(0,1fr) 16px 140px 30px;align-items:center;gap:6px;margin-bottom:6px;font-size:13.5px}.dk-row label,.dk-l{color:var(--ink2)}.dk-row input,.dk-row select,.dk-row output{width:100%;padding:7px 9px;border:1px solid #d0d5dd;border-radius:7px;text-align:right;font:inherit;font-variant-numeric:tabular-nums;box-sizing:border-box}.dk-row select{text-align:left}.dk-row output{border-color:transparent;background:#f5f6f8}.dk-row input:disabled{background:#f5f6f8;color:var(--ink)} .dk-row .chk{grid-column:2/5}.dk-fname{text-align:left!important;border-style:dashed!important}.dk-sign{color:var(--muted);text-align:center}.dk-x{padding:4px 7px!important;font-size:11.5px!important}.dk-row .chk{display:flex;align-items:center;gap:6px;justify-content:flex-end}.dk-row{grid-template-columns:minmax(0,1fr) 16px 140px 52px}.dk-total output{font-weight:700}.dk-big output{font-weight:800;font-size:15px;background:#eef3ff}.dk-box{background:#fafbfc;border:1px solid var(--line);border-radius:10px;padding:8px 8px 2px;margin:8px 0} .dk-grid{display:grid;grid-template-columns:150px repeat(3,minmax(0,1fr));gap:6px}.dk-gh{background:var(--brand);color:#fff;border-radius:8px;padding:6px 4px;display:flex;align-items:center;justify-content:center;font-weight:600}.dk-gh input{width:100%;padding:6px;border-radius:6px;border:0;text-align:right;color:var(--ink);background:#fff}.dk-gt{display:grid;grid-template-columns:1fr 1fr;gap:4px;align-items:center}.dk-gt input{width:100%;padding:6px;border:1px solid #d0d5dd;border-radius:6px;text-align:right;box-sizing:border-box}.dk-gt .hint{grid-column:1/3;font-size:11px;text-align:center} .dk-cell{border:1px solid var(--line);background:#f5f9ff;border-radius:8px;font:700 16px inherit;color:#0e7c74;cursor:pointer;min-height:56px}.dk-cell:hover{border-color:var(--brand)}.dk-cell.on{background:var(--brand);color:#fff;border-color:var(--brand)}.dk-acts{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px} .dk-sumtop{display:grid;grid-template-columns:1fr 1fr;gap:10px;padding-bottom:12px;border-bottom:1px solid var(--line);margin-bottom:10px}.dk-sumtop b{font-size:20px;display:block}.dk-sumtop span{font-size:12px;color:var(--muted)}.dk-sum{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--line2);font-size:13.5px}.dk-mgr{margin-top:12px;background:#fdf4e3;border-radius:10px;padding:4px 10px}.dk-side{display:flex;flex-wrap:wrap;gap:6px} .dk-bottom{display:flex;gap:8px;align-items:center;margin-top:14px;padding:12px 16px;background:#fff;border:1px solid var(--line);border-radius:12px;position:sticky;bottom:12px;box-shadow:0 4px 16px rgba(16,24,40,.08)} @media(max-width:1700px){.dk-wrap{grid-template-columns:minmax(320px,1fr) minmax(360px,1.2fr)}.dk-wrap>.dk-col:last-child{grid-column:1/-1}}@media(max-width:900px){.dk-wrap,.dk-head{grid-template-columns:1fr}}`; document.head.insertAdjacentHTML('beforeend',''); /* deal-screen rail, stipulations, contracting, print window */ function dkRail(w){const d=w.dealId&&S.deals.find(x=>x.id===w.dealId);const l=d&&d.loanId?loan(d.loanId):null;const it=(label,fn,dis)=>``; return ``} const STIP_DEFAULT=['Proof of income (2 recent pay stubs)','Proof of residence (utility bill)','Valid driver’s license','Proof of insurance','6 personal references','Down payment']; function stipsPane(w){if(!(w.stips||[]).length){w.stips=STIP_DEFAULT.map(n=>({n,got:''}))} return `

Stipulations

${w.stips.map((s,i)=>``).join('')}
${esc(s.n)}${s.got?'Received '+ftime(s.got):'Waiting'}

Customers can send photos of their documents by text; save them to the customer’s Files.

`} function stipRequest(){const w=curSheet();const c=cust(w.customerId);if(!c)return toast('Pick a customer first');if(!(w.stips||[]).length)w.stips=STIP_DEFAULT.map(n=>({n,got:''}));const need=w.stips.filter(s=>!s.got).map(s=>'• '+s.n).join('\n');if(!need)return toast('All stipulations are in'); w.stipSent=nowAt();save();textModal(c.id,null,null,`Hi ${(c.name||'').split(' ')[0]}, to finish your paperwork with ${S.settings.dealer||'us'} we still need:\n${need}\nYou can text photos to this number. Thanks!`)} function sheetContract(kind){const w=curSheet();const d=w.dealId&&S.deals.find(x=>x.id===w.dealId);if(!d){toast('Complete the sale first, then print or e-sign the contract');return sheetComplete()}if(kind==='e')return esignStart(d.id);printFormsModal(d.id)} function printFormsModal(dealId){syncCustomForms();const d=S.deals.find(x=>x.id===dealId);if(!d)return;const x={d,l:d.loanId?loan(d.loanId):null,v:veh(d.vehicleId),c:cust(d.customerId)};const st={tab:'lib',q:'',g:'',sel:new Set((defaultPack(x)?.items||[]).map(i=>i.id))}; const draw=()=>{const groups=[...new Set(FORMS.map(f=>f.g))];const list=FORMS.filter(f=>formOk(f,x)&&(!st.g||f.g===st.g)&&(!st.q||f.n.toLowerCase().includes(st.q.toLowerCase())));const packs=(S.packs||[]).filter(p=>p.dealType==='Any'||p.dealType===d.type); openModal(mh('Print forms · deal #'+d.no+' · '+esc(x.c?.name||''))+`
${[['lib','Document library'],['esign','eSign packs'],['packs','Print packs']].map(t=>``).join('')}
${st.tab==='lib'?`
${list.map(f=>``).join('')}
FormCategoryeSignCopies
${esc(f.n)}${esc(f.g)}Yes
${st.sel.size} selected. Don’t see a form? Add your own in Forms → Custom.
` :`${packs.map(p=>``).join('')||''}
PackForms
${esc(p.name)}
${esc(p.dealType)}${p.state?' · '+esc(p.state):''}
${p.items.map(i=>FBYID(i.id)?.n).filter(Boolean).join(', ')}${st.tab==='esign'?``:``}
No packs for this deal type
`}
${st.tab==='lib'?``:''}
`,true); if(st.tab==='packs'){const mount=document.createElement('div');mount.dataset.dealercenterPacks='';document.querySelector('#modal .mb').append(mount);attachDealerCenterPanel(d);} document.querySelectorAll('#modal .tabs [data-t]').forEach(b=>b.onclick=()=>{st.tab=b.dataset.t;draw()}); if(st.tab==='lib'){$('#pfq').oninput=e=>{st.q=e.target.value;const pos=e.target.selectionStart;draw();const n=$('#pfq');n.focus();n.setSelectionRange(pos,pos)};$('#pfg').onchange=e=>{st.g=e.target.value;draw()};$('#pfclr').onclick=()=>{st.sel.clear();draw()}; document.querySelectorAll('#modal [data-f]').forEach(cb=>cb.onchange=()=>{cb.checked?st.sel.add(cb.dataset.f):st.sel.delete(cb.dataset.f);draw()}); document.querySelectorAll('#modal [data-c]').forEach(i=>i.onchange=()=>{ui.formCopies=ui.formCopies||{};ui.formCopies[i.dataset.c]=Math.max(1,+i.value||1)}); const go_=()=>{if(!st.sel.size)return toast('Select at least one form');ui.formDeal=d.id;ui.formSelFor=d.id;ui.formSel=new Set(st.sel);ui.formOrder=FORMS.map(f=>f.id).filter(id=>st.sel.has(id));ui.formPack='';ui.formTab='print';closeModal();go('forms');if(route==='forms')render()}; $('#pfpr').onclick=go_;$('#pfes').onclick=()=>{const ids=[...st.sel];esignStart(d.id);setTimeout(()=>{const f=$('#esf');if(f)f.querySelectorAll('[name^="f_"]').forEach(cb=>cb.checked=ids.includes(cb.name.slice(2)))},60)}; $('#pfmk').onclick=()=>{if(!st.sel.size)return toast('Select some forms first');const name=prompt('Name this print pack',d.type+' pack');if(!name)return;S.packs.push({id:uid(),name,dealType:d.type,state:'',auto:false,items:[...st.sel].map(id=>({id,copies:+(ui.formCopies||{})[id]||1}))});save();toast('Print pack saved');st.tab='packs';draw()}} document.querySelectorAll('#modal [data-pack]').forEach(b=>b.onclick=()=>{const p=S.packs.find(z=>z.id===b.dataset.pack);ui.formDeal=d.id;ui.formSelFor=d.id;applyPack(p,x);ui.formTab='print';closeModal();go('forms');if(route==='forms')render()}); document.querySelectorAll('#modal [data-esign]').forEach(b=>b.onclick=()=>{const p=S.packs.find(z=>z.id===b.dataset.esign);esignStart(d.id);setTimeout(()=>{const f=$('#esf');if(f&&f.pack){f.pack.value=p.id;f.pack.dispatchEvent(new Event('change'))}},60)})}; draw()} const DK2CSS=`.dk-rail{position:fixed;left:240px;top:72px;bottom:0;width:150px;background:#1d2939;padding:8px 0;z-index:3;display:flex;flex-direction:column;overflow:auto}.dk-ri{background:transparent;border:0;border-bottom:1px solid #344054;color:#e4e7ec;text-align:left;padding:12px 14px;font:500 13.5px inherit;cursor:pointer}.dk-ri:hover{background:#344054;color:#fff}.dk-ri:disabled{opacity:.45;cursor:not-allowed}.dk-ri:focus-visible{outline:3px solid #a9c1ff;outline-offset:-3px} .dk-page{margin-left:150px}.dk-fs{border:1px solid var(--line);border-radius:10px;padding:6px 12px 8px;margin:8px 0;display:flex;flex-wrap:wrap;gap:4px 14px;font-size:13px}.dk-fs legend{font-size:12px;color:var(--muted);padding:0 4px}.dk-fs .hint{flex-basis:100%;font-size:11.5px} .dk-big-acts{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:14px}.dk-big-acts .btn{justify-content:center;padding:12px}.dk-big-acts .btn:last-child{grid-column:1/-1} @media(max-width:900px){.dk-rail{position:static;width:auto;flex-direction:row;flex-wrap:wrap;margin-bottom:12px;border-radius:12px}.dk-page{margin-left:0}}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Vehicle workspace (full page inventory record) ================= */ TITLES.veh='Vehicle'; const VSALE=['Retail','Wholesale','BHPH','Rent to own'];const VCOND=['Used','Certified pre-owned','New','As-is'];const VTITLE=['Clean','Rebuilt','Salvage','Flood','Lemon / buyback','Odometer brand','Junk']; const VFEEDS=[['web','Your website'],['fb','Facebook Marketplace'],['cars','Cars.com'],['cg','CarGurus'],['at','Autotrader'],['gg','Google vehicle ads']]; function openVehicle(id){if(!veh(id))return;closeModal();ui.vehId=id;ui.vTab=ui.vTab||'info';ui.vSub=ui.vSub||'summary';if(route==='veh')render();else{ui.vehBack=route==='veh'?'inventory':route;go('veh')}} {const _vm=vehModal;vehModal=function(id){if(id&&!ui.vehEdit&&veh(id))return openVehicle(id);ui.vehEdit=false;return _vm.apply(this,arguments)}} function vlog(v,text){(v.log=v.log||[]).unshift({at:nowAt(),by:S.settings.user,text})} const VLBL={price:'Asking price',advPrice:'Advertising price',specialPrice:'Special price',msrp:'MSRP',minDown:'Minimum down',minDeposit:'Minimum deposit',wholesalePrice:'Wholesale price',cost:'Vehicle cost',packs:'Pack',addlCost:'Additional cost',writeDown:'Write-down',status:'Status',miles:'Odometer',lot:'Location',saleType:'Sale type',titleBrand:'Title brand',titleStatus:'Title status'}; function setVeh(id,k,val){const v=veh(id);if(!v)return;const num=['price','advPrice','specialPrice','msrp','minDown','minDeposit','wholesalePrice','cost','packs','addlCost','writeDown','miles','mpgCity','mpgHwy','keys','floorAmt','purchMiles'].includes(k);if(num)val=val===''?'':+val; const old=v[k];if(String(old??'')===String(val??''))return;v[k]=val; if(VLBL[k])vlog(v,`${VLBL[k]} changed${old!==undefined&&old!==''?` from ${num&&k!=='miles'?$0(old):old}`:''} to ${num&&k!=='miles'?$0(val):val}`); if(k==='price'&&old)v.priceHist=(v.priceHist||[]).concat({date:TODAY,from:+old,to:+val,by:S.settings.user}); if(k==='status'&&val==='In Recon'&&!v.reconStage)sendToRecon(v,true); save();if(['status','price','cost','packs','addlCost','writeDown','saleType','advPrice','specialPrice','wholesalePrice','minDown'].includes(k))render()} function vNumbers(v){const st=S.settings;const fees=[{n:'Doc fee',a:+st.docFee||0},...(st.vehFees||[{n:'Tag & title (est.)',a:0}])].filter(f=>f.a||/doc/i.test(f.n));const feeT=fees.reduce((a,f)=>a+(+f.a||0),0); const recon=reconTotal(v),packs=+v.packs||0,addl=+v.addlCost||0,wd=+v.writeDown||0;const total=(+v.cost||0)+recon+packs+addl-wd; const sale=v.saleType==='Wholesale'?(+v.wholesalePrice||+v.price||0):(+v.specialPrice||+v.price||0);const sm=bookSummary(v); const ws=Object.values(sm).map(s=>s.whole).filter(Boolean),rs=Object.values(sm).map(s=>s.retail).filter(Boolean);const avgW=ws.length?ws.reduce((a,b)=>a+b,0)/ws.length:(+v.mmr||0),avgR=rs.length?rs.reduce((a,b)=>a+b,0)/rs.length:0; return{fees,feeT,recon,packs,addl,wd,total,sale,allIn:sale+feeT,profit:sale-total,avgW,avgR,water:avgW?total-avgW:null,fmv:+v.fmv||Math.round(avgR)||0}} function vLeads(v){return S.customers.filter(c=>c.vehicleId===v.id||interestVeh(c)?.id===v.id)} function vSimilar(v){const same=x=>x.id!==v.id&&x.make===v.make&&x.model===v.model;let l=S.vehicles.filter(same),basis=`${v.make} ${v.model}`;if(l.length<2){l=S.vehicles.filter(x=>x.id!==v.id&&x.make===v.make);basis=v.make} const cur=l.filter(x=>x.status!=='Sold'),sold=l.filter(x=>x.status==='Sold');const avg=(a,f)=>a.length?a.reduce((s,x)=>s+f(x),0)/a.length:0;const gross=x=>{const d=S.deals.find(d=>d.vehicleId===x.id);return d?+d.gross||0:(+x.soldPrice||0)-vcost(x)}; return{basis,cur:{n:cur.length,price:avg(cur,x=>+x.price||0),days:avg(cur,age),miles:avg(cur,x=>+x.miles||0)},sold:{n:sold.length,price:avg(sold,x=>+x.soldPrice||+x.price||0),days:avg(sold,age),gross:avg(sold,gross)},list:l}} VIEWS.veh=()=>{const v=veh(ui.vehId);if(!v)return `
Vehicle not found. Back to inventory
`; const N=vNumbers(v),deal=S.deals.find(d=>d.vehicleId===v.id),leads=vLeads(v),mk=marketStats(v),dIn=Math.max(0,age(v)),ph=mainPhoto(v); const r=(label,k,type,opts,extra)=>``; const left=`
${ph?`${esc(vname(v))}`:carSVG(v.color)}
${v.status==='Sold'?(deal?``:''):``}
${esc(vname(v))}${esc([v.body,v.engine,v.trans,v.drive].filter(Boolean).join(' · ')||'Add body, engine and drivetrain in General info')}
${r('Stock #','stock')}${r('Odometer','miles','number')}${r('Sale type','saleType','',VSALE)}
In stock${fdate(v.acquired)} · ${dIn} day${dIn===1?'':'s'}
${r('Ext. color','color')}${r('Int. color','intColor')}${r('Condition','condition','',VCOND)}${r('Location','lot')} ${r('Title brand','titleBrand','',VTITLE)} `; const tabs=[['info','Vehicle info'],['mkt','Marketing'],['media','Media'+((v.photos||[]).length?` (${v.photos.length})`:'')],['market','Market data'],['purch','Purchase info'],['act','Activities'+(leads.length?` (${leads.length})`:'')],['files','Files'+((v.files||[]).length?` (${v.files.length})`:'')],['acct','Accounting'],['recon','Recon'+(openTasks(v).length?` (${openTasks(v).length})`:'')],['logs','Logs']]; return `
← Back

${esc(vname(v))}

${esc(v.stock)}${statusPill(v.status)}${v.published&&v.status==='Available'?'Online':''}${v.titleBrand&&v.titleBrand!=='Clean'?`${esc(v.titleBrand)} title`:''}${v.titleStatus&&v.titleStatus!=='In hand'&&v.status!=='Sold'?`Title: ${esc(v.titleStatus)}`:''}
${v.status!=='Sold'?``:''}
Days in stock${dIn}
${v.saleType==='Wholesale'?'Wholesale price':'Selling price'}${$0(N.sale)}
Total cost${$0(N.total)}
Potential profit${$0(N.profit)}
Price to market${mk?mk.ptm.toFixed(0)+'%':'Add comps'}
Leads on this car${leads.length}
${left}
${tabs.map(t=>``).join('')}
${vehTab(v,N,deal,leads,mk)}
`}; AFTER.veh=()=>{const v=veh(ui.vehId);if(v&&ui.vTab==='media')drawPhotos(v.id)}; function vMoney(v,k,label,hint){return ``} function vehTab(v,N,deal,leads,mk){const t=ui.vTab||'info'; if(t==='info'){const s=ui.vSub||'summary';const subs=[['summary','Summary'],['general','General info'],['books','Build & books'],['desc','Description']]; const head=`
${subs.map(x=>``).join('')}
`; if(s==='general'){const g=(l,k,type,opts)=>``; return head+`
${g('Year','year','number')}${g('Make','make')}${g('Model','model')}${g('Trim','trim')}${g('Body style','body','',['Sedan','Coupe','SUV','Truck','Van','Minivan','Wagon','Hatchback','Convertible','Motorcycle'])}${g('Engine','engine')}${g('Cylinders','cyl','',['3','4','5','6','8','10','12','Electric'])}${g('Transmission','trans','',['Automatic','Manual','CVT','Dual-clutch'])}${g('Drivetrain','drive','',['FWD','RWD','AWD','4WD'])}${g('Fuel','fuel','',['Gasoline','Diesel','Hybrid','Plug-in hybrid','Electric','Flex fuel'])}${g('Doors','doors','',['2','3','4','5'])}${g('Seats','seats','number')}${g('Ext. color','color')}${g('Int. color','intColor')}${g('Int. material','intMat','',['Cloth','Leather','Leatherette','Vinyl'])}${g('Keys / fobs','keys','number')}${g('Odometer','miles','number')}${g('Odometer status','odoStatus','',['Actual','Exceeds mechanical limits','Not actual (warning)','Exempt'])}${g('Title brand','titleBrand','',VTITLE)}${g('Title state','titleState')}
`} if(s==='books')return head+`
Bookout values from your guide subscriptions. Re-book every ${bkCfg().maxAge} days so lenders see fresh numbers.${DL?``:''}
${bookCompareHTML(v)}
`; if(s==='desc')return head+`
${aiOn('listing')?``:''}${(v.notes||'').trim().split(/\s+/).filter(Boolean).length} words. Shown on your website and sent in listing feeds.
`; // summary const sv=vSimilar(v),sm=bookSummary(v); return head+`

Price info

${['Retail','Wholesale'].map(x=>``).join('')}
${v.saleType==='Wholesale'?vMoney(v,'wholesalePrice','Wholesale price')+vMoney(v,'price','Retail asking price'):vMoney(v,'price','Asking price')+vMoney(v,'advPrice','Advertising price','shown online')+vMoney(v,'specialPrice','Special price','sale price')+vMoney(v,'msrp','MSRP')}
Fair market value${N.fmv?$0(N.fmv):'Book it'}
${vMoney(v,'minDown','Minimum down')}${vMoney(v,'minDeposit','Minimum deposit')}

Cost info

Purchased ${fdate(v.acquired)}
${vMoney(v,'cost','Vehicle cost')}
Cost adds (recon)${(v.recon||[]).length} item${(v.recon||[]).length===1?'':'s'}${$0(N.recon)}
${vMoney(v,'packs','Pack','added to cost for commissions')}${vMoney(v,'addlCost','Additional cost')}${vMoney(v,'writeDown','Write-down','reduces cost')}
Total cost${$0(N.total)}
Vehicle price${$0(N.sale)}
+
Dealer fees${$0(N.feeT)}
=
All-in price${$0(N.allIn)}
Potential profit${$0(N.profit)}
${N.water==null?'Water':N.water>0?'Under water':'Equity vs wholesale'}${N.water==null?'Book to see':$0(Math.abs(N.water))}
Holding cost to date${$0(age(v)*(+S.settings.holdingCost||0))}

Valuation

${Object.entries(BOOKS).map(([b,B])=>{const s=sm[b];return ``}).join('')}
GuideWholesaleRetailAge
${B.n}${s?$0(s.whole):'—'}${s?$0(s.retail):'—'}${s?`${s.age}d`:``}
Manheim MMR${v.mmr?$0(v.mmr):'—'}—${v.mmr?'':``}

Vehicle history reports

${vHistHTML(v)}

Print documents

${[['book','Book sheet','Bookout values for lenders'],['sticker','Window sticker','Price, equipment, MPG'],['hang','Hang tag','Mirror tag with price and stock #'],['guide',"Buyers Guide",'FTC as-is / warranty disclosure']].map(d=>``).join('')}

Similar vehicles

${esc(sv.basis)}

In stock now · ${sv.cur.n}

Avg price
${sv.cur.n?$0(sv.cur.price):'—'}
Avg days
${sv.cur.n?Math.round(sv.cur.days):'—'}
Avg miles
${sv.cur.n?Math.round(sv.cur.miles).toLocaleString():'—'}

Sold · ${sv.sold.n}

Avg sold price
${sv.sold.n?$0(sv.sold.price):'—'}
Avg days to sell
${sv.sold.n?Math.round(sv.sold.days):'—'}
Avg front gross
${sv.sold.n?$0(sv.sold.gross):'—'}
${sv.list.length?``:''}

Options & equipment

${(v.options||[]).length} listed
${(v.options||[]).map((o,i)=>`${esc(o)}`).join('')||'No options listed yet.'}
${VOPTS.filter(o=>!(v.options||[]).includes(o)).map(o=>`

Vehicle description

${esc(v.notes||'No description yet. Add one so your website and listings have something to say.')}

`} if(t==='mkt'){const fd_=v.feeds||{};return `

Online listing

Send to

${VFEEDS.map(([k,l])=>``).join('')}
${!v.published?'Not published':fd_[k]===false?'Off':v.status==='Available'?'Included in next feed':'Waits until Available'}

Price history

${(v.priceHist||[]).length?`${v.priceHist.slice().reverse().map(p=>``).join('')}
${fdate(p.date)}${$0(p.from)} → ${$0(p.to)}${esc(p.by||'')}
`:'
No price changes yet
'}

Shoppers interested

${leads.length?`${leads.map(c=>``).join('')}
${esc(c.name)}
${esc(c.source||'')}
${esc(c.stage)}${esc(uname(c.ownerId))}
`:'
No leads have asked about this car yet
'}
`} if(t==='media')return `
PhotosThe first photo is the main one on your website and listings. Drag to reorder.

Video

`; if(t==='market'){const c=mkCfg();return `

Market data

${mk?`
Your price${$0(v.price)}
Market avg (mileage adj.)${$0(mk.avg)}
Price to market${mk.ptm.toFixed(1)}%
Rank${mk.rank} of ${mk.n+1}
Range${$0(mk.low)}–${$0(mk.high)}
Suggested at ${c.target}%${$0(mk.suggested)}
${(v.comps||[]).filter(k=>+k.price).map(k=>{const a=+k.price+((+k.miles||+v.miles)-(+v.miles))*c.perMile;return ``}).join('')}
${$0(mk.low)}Blue = your price${$0(mk.high)}
` :'
No comparable listings yet. Add a few from Cars.com, CarGurus or Facebook to see where your price sits.
'} ${(v.comps||[]).map(k=>``).join('')}
SourceYear / trimMilesPriceDistance
${k.url?`${esc(k.source||'link')} ↗`:esc(k.source||'')}${esc([k.year,k.trim].filter(Boolean).join(' '))}${k.miles?(+k.miles).toLocaleString():'—'}${$0(k.price)}${k.dist?esc(k.dist)+' mi':''}
`} if(t==='purch'){const p=(l,k,type,opts,cls)=>``; return `

Purchase

${p('Purchase date','acquired','date')}${p('Purchase type','purchType','',['Auction','Trade-in','Street purchase','Wholesaler','Dealer trade','Repossession','Lease return'])}${p('Purchased from','purchFrom')}${p('Auction / sale','auction')}${p('Lane / run #','lane')}${p('Buyer','buyer','',S.users.filter(u=>u.active).map(u=>u.name))}${p('Vehicle cost','cost','number')}${p('Buy fee','buyFee','number')}${p('Transport','transport','number')}${p('Odometer at purchase','purchMiles','number')}${p('Bill of sale #','bosNo')}${p('Payment method','purchPay','',['Check','ACH / wire','Floor plan','Cash','Trade credit'])}

Title

${p('Title received','titleRcvd','date')}${p('Title #','titleNo')}${p('Title state','titleState')}${p('Title in office','titleStatus','',INTITLE)}${p('Title brand','titleBrand','',VTITLE)}${p('Lienholder on title','titleLien','','',' c2')}${p('Title location','titleLoc','',['In office safe','At DMV','With lender','Waiting on seller','Sent to buyer'])}

Floor plan

${p('Floor plan lender','floorLender')}${p('Amount floored','floorAmt','number')}${p('Floored on','floorDate','date')}${p('Curtailment due','floorDue','date')}
${v.floorAmt&&v.floorDate?`

${diff(v.floorDate,TODAY)} days on floor plan${v.floorDue?` · curtailment ${v.floorDuepast due':'due '+fdate(v.floorDue)}`:''}

`:''}
`} if(t==='act'){const items=[];leads.forEach(c=>{items.push({at:c.createdAt||c.created||'',t:'Lead',body:`${c.name} asked about this car (${c.source||'unknown source'})`,c:c.id});(S.comms||[]).filter(x=>x.customerId===c.id).slice(-3).forEach(x=>items.push({at:x.at,t:x.channel==='call'?'Call':x.channel==='email'?'Email':'Text',body:`${c.name}: ${String(x.body||x.outcome||'').slice(0,120)}`,c:c.id}))}); (v.vnotes||[]).forEach(n=>items.push({at:n.at,t:n.kind||'Note',body:n.text,by:n.by}));S.deals.filter(d=>d.vehicleId===v.id).forEach(d=>items.push({at:d.date,t:'Deal',body:`Deal #${d.no} · ${d.type} · ${$$(d.price)} to ${cust(d.customerId)?.name||''}`}));(v.reconLog||[]).forEach(l=>items.push({at:l.date,t:'Recon',body:'Moved to '+l.stage,by:l.by})); items.sort((a,b)=>String(b.at).localeCompare(String(a.at))); return `
${items.map(x=>`
${esc(x.t)}${esc(x.by||'')} ${x.at?'· '+(String(x.at).length>10?ftime(x.at):fdate(x.at)):''}
${esc(x.body)}
${x.c?``:''}
`).join('')||'
No activity on this vehicle yet
'}
`} if(t==='files'){const fs_=v.files||[];return `
Title, bill of sale, auction receipt, inspection, history report
${fs_.map((f,i)=>{const url=photoURL(f);return `
${/^image\//.test(f.type)&&url?`${esc(f.name)}`:`
PDF
`}
${esc(f.name)}
${ftime(f.at)} · ${esc(f.by||'')}
${url?`Open`:''}
`}).join('')||'
No files yet
'}
`} if(t==='acct'){const tx=S.txns.filter(x=>x.ref===v.stock).sort((a,b)=>a.date.localeCompare(b.date));const tot=tx.reduce((a,x)=>a+ +x.amount,0); return `
${kpi('Vehicle cost',$0(v.cost),'purchase')}${kpi('Recon posted',$0(N.recon),(v.recon||[]).length+' entries')}${kpi('Pack + additional',$0(N.packs+N.addl),'not posted to the ledger')}${kpi('Total cost',$0(N.total),N.wd?'after '+$0(N.wd)+' write-down':'')}
${tx.map(x=>``).join('')||''}${tx.length?``:''}
DateAccountDescriptionAmount
${fdate(x.date)}${esc(x.cat)}${esc(x.desc||'')}${$$(x.amount)}
No ledger entries for this stock number
Total posted${$$(tot)}
`} if(t==='recon'){const ts=v.tasks||[];return `
${kpi('Stage',v.status==='In Recon'?esc(v.reconStage):v.reconDone?'Frontline ready':'Not in recon',v.reconStart?reconDays(v)+' days in recon':'')}${kpi('Recon spent',$0(N.recon),'budget '+$0(S.settings.reconBudget))}${kpi('Open tasks',openTasks(v).length,ts.filter(t=>t.status==='Needs Approval').length+' need approval')}
${ts.map(t=>``).join('')||''}
TaskCategoryVendorEst.ActualStatus
${esc(t.desc)}${esc(t.cat)}${esc(vendor(t.vendorId)?.name||'—')}${$0(t.est)}${t.status==='Done'?$$(t.actual):'—'}${taskPill(t.status)}
No recon tasks
${(v.recon||[]).map(x=>``).join('')||''}
DateCost addAmount
${fdate(x.date)}${esc(x.desc)}${$$(x.amount)}
No cost adds
${v.status!=='In Recon'&&v.status!=='Sold'?``:''}
`} if(t==='logs')return `
${(v.log||[]).map(l=>``).join('')||''}
WhenWhoChange
${ftime(l.at)}${esc(l.by||'')}${esc(l.text)}
Changes made on this page are recorded here
`; return ''} const VOPTS=['Backup camera','Bluetooth','Apple CarPlay','Android Auto','Navigation','Sunroof / moonroof','Leather seats','Heated seats','Cooled seats','Third-row seat','Remote start','Keyless entry','Push-button start','Blind spot monitor','Lane keep assist','Adaptive cruise control','Alloy wheels','Tow package','Running boards','Power liftgate','Premium audio','Wireless charging']; function vOpt(id,i,val){const v=veh(id);v.options=v.options||[];if(i>=0){vlog(v,'Removed option '+v.options[i]);v.options.splice(i,1)}else{val=String(val||'').trim();if(!val)return;if(v.options.includes(val))return toast('Already listed');v.options.push(val);vlog(v,'Added option '+val)}save();render();if(i<0)setTimeout(()=>{const n=document.querySelector('.vw-addopt input');n&&n.focus()},0)} function vHistHTML(v){const h=v.hist||{};const vin=encodeURIComponent(v.vin||''); return `
${[['carfax','CARFAX',`https://www.carfaxonline.com/`],['autocheck','AutoCheck',`https://www.autocheck.com/`],['nmvtis','NMVTIS title check','https://vehiclehistory.bja.ojp.gov/nmvtis_vehiclehistory']].map(([k,n,u])=>{const r=h[k];return `
${n}
${r?`Pulled ${fdate(r.date)}${r.owners?` · ${r.owners} owner${r.owners==1?'':'s'}`:''}${r.accidents!=null&&r.accidents!==''?` · ${r.accidents} accident${r.accidents==1?'':'s'}`:''}${r.flags?' · '+esc(r.flags):''}`:'Not pulled yet'}
Open ↗
`}).join('')}

Opening a provider copies the VIN. Record the result here so the team and your website can see it.

`} function vHistModal(id,k,n){const v=veh(id);v.hist=v.hist||{};const r=v.hist[k]||{date:TODAY};openModal(mh(n+' result · '+esc(v.stock))+`
${v.hist[k]?'':''}
`); if($('#vhdel'))$('#vhdel').onclick=()=>{delete v.hist[k];save();closeModal();render()};$('#vhf').onsubmit=e=>{e.preventDefault();v.hist[k]=fd(e.target);vlog(v,n+' report recorded');save();closeModal();render();toast('Saved')}} function vNote(id,kind){const v=veh(id);openModal(mh(kind+' · '+esc(vname(v)))+`
${kind==='Note'?'':``}
`); $('#vnf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const c=x.cid&&cust(x.cid);(v.vnotes=v.vnotes||[]).push({at:nowAt(),by:S.settings.user,kind,text:(c?c.name+': ':'')+x.text});if(c){c.notes.push({date:TODAY,by:S.settings.user,text:`${kind} · ${vname(v)} (${v.stock}): ${x.text}`});if(!c.vehicleId)c.vehicleId=v.id}save();closeModal();render();toast(kind+' saved')}} async function vUpload(id,files){const v=veh(id);const list=[...files].slice(0,10);for(const f of list){if(f.size>15*1024*1024){toast(f.name+' is too large (15 MB max)');continue}const b=/^image\//.test(f.type)?await shrink(f,2200,0.88):f;await storeCustFiles(v,[b],f.name)}vlog(v,list.length+' file(s) uploaded');save();render();toast(list.length+' file(s) added')} function vCostModal(id){const v=veh(id);openModal(mh('Add cost · '+esc(v.stock))+`

Adds to the vehicle's cost adds and posts to Reconditioning in accounting.

`); $('#vcf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);v.recon=v.recon||[];v.recon.push({id:uid(),date:x.date,desc:x.desc,amount:+x.amount});txn(x.date,'Reconditioning',+x.amount,v.stock,x.desc);vlog(v,`Cost added: ${x.desc} ${$$(+x.amount)}`);save();closeModal();render();toast('Cost added')}} function vDecode(id){const v=veh(id);const r=decodeVin(v.vin||'');const m=$('#vdmsg');if(!r.ok){if(m){m.textContent=r.msg;m.style.color='var(--red)'}return}if(r.year&&!v.year)v.year=r.year;if(r.make&&!v.make)v.make=r.make;save();render();setTimeout(()=>{const m2=$('#vdmsg');if(m2){m2.textContent=r.valid?'Check digit valid':'Check digit does not match. Verify the VIN';m2.style.color=r.valid?'var(--green)':'var(--amber)'}},0)} async function vAiDesc(id){const v=veh(id);const b=$('#vdai');if(b){b.disabled=true;b.textContent='✦ Writing…'} try{const t=await ai(`Write a vehicle listing description for a used-car dealer's website and online marketplaces. Vehicle: ${vname(v)}, ${v.color||''}, ${(+v.miles).toLocaleString()} miles, price ${$0(+v.advPrice||+v.price)}. Equipment: ${(v.options||[]).join(', ')||'not listed'}. ${[v.engine,v.trans,v.drive].filter(Boolean).join(', ')}. Existing notes: ${v.notes||'none'}. Dealer: ${S.settings.dealer}, ${S.settings.phone}; in-house financing available. Write 90-140 words: a catchy first line, then the vehicle's strengths, then a call to action. Only state features listed above or standard for this model; don't invent accident history, warranty or certifications. Plain text, no markdown, no emojis.`,{text:true,tier:'quick',nocache:true});v.notes=t.trim();vlog(v,'Description written with AI');save();render();toast('Description written. Review it before publishing')}catch(e){toast(aiErrMsg(e));if(b){b.disabled=false;b.textContent='✦ Write with AI'}}} /* printable vehicle documents */ function vDocHTML(v,kind){const st=S.settings,N=vNumbers(v),price=+v.advPrice||+v.price||0; if(kind==='book')return bookSheetHTML(v); if(kind==='guide')return F.hdr("Buyers Guide",0,'Stock '+esc(v.stock))+`

IMPORTANT: Spoken promises are difficult to enforce. Ask the dealer to put all promises in writing. Keep this form.

`+F.grid([[['Vehicle make',v.make],['Model',v.model],['Year',v.year],['VIN',v.vin]],[['Dealer stock number',v.stock],['Mileage',(+v.miles).toLocaleString()],['Color',v.color],['Price',$0(price)]]])+ `

Warranties for this vehicle

${v.warranty==='warranty'?'☐':'☒'} AS IS – NO DEALER WARRANTY

The dealer does not provide a warranty for any repairs after sale.

${v.warranty==='warranty'?'☒':'☐'} DEALER WARRANTY

☐ FULL WARRANTY   ☐ LIMITED WARRANTY. The dealer will pay ___% of the labor and ___% of the parts for the covered systems that fail during the warranty period.

Systems covered: ______________________   Duration: ______________

`+F.note('Template preview only. Use the official FTC Used Car Rule Buyers Guide (English, and Spanish if the sale is conducted in Spanish) required in your state, displayed on the vehicle while it is offered for sale.'); if(kind==='hang')return `
${esc(st.dealer)}
${esc(v.year)}
${esc(v.make)}
${esc(v.model)}
${esc(v.trim||'')}
${v.noPrice?'Call for price':$0(price)}
Miles${(+v.miles).toLocaleString()}
Stock${esc(v.stock)}
${v.minDown?`
Down from${$0(v.minDown)}
`:''}
${esc(v.vin)}
${esc(st.phone)}
`; // window sticker return F.hdr('Window Sticker',0,'Stock '+esc(v.stock))+`
${esc(vname(v))}
${esc([v.body,v.engine,v.trans,v.drive,v.fuel].filter(Boolean).join(' · '))}
${v.specialPrice?'Special price':'Our price'}${v.noPrice?'Call':$0(+v.specialPrice||price)}${v.specialPrice&&price>v.specialPrice?`${$0(price)}`:''}
`+ F.grid([[['VIN',v.vin,2],['Stock #',v.stock],['Odometer',(+v.miles).toLocaleString()]],[['Exterior',v.color],['Interior',[v.intColor,v.intMat].filter(Boolean).join(' ')],['Condition',v.condition||'Used'],['Title',v.titleBrand||'Clean']]])+ `

Equipment

    ${(v.options||[]).map(o=>`
  • ${esc(o)}
  • `).join('')||'
  • See dealer for equipment list
  • '}
${v.mpgCity||v.mpgHwy?`
${esc(v.mpgCity||'—')}City MPG
${esc(v.mpgHwy||'—')}Highway MPG
`:''}${v.notes?`

About this vehicle

${esc(v.notes)}

`:''}
In-house financing available${v.minDown?` · down payments from ${$0(v.minDown)}`:''}. Plus dealer fees of ${$0(N.feeT)}, tax, title and registration.
`+F.note('This is not the manufacturer’s Monroney label. A Buyers Guide is also displayed on this vehicle.')} const VDCSS=`.vgbox{border:2px solid #111;padding:8px 12px;margin:8px 0;font-size:13px}.vgbox p{margin:4px 0} .vhang{width:3.6in;margin:0 auto;border:2px solid #111;border-radius:14px;padding:18px 18px 22px;text-align:center;font-family:Inter,Arial,sans-serif}.vh-hole{width:1.3in;height:1.3in;border:2px dashed #999;border-radius:50%;margin:0 auto 14px}.vh-d{font-weight:800;font-size:15px;text-transform:uppercase;letter-spacing:.06em;border-bottom:2px solid #111;padding-bottom:8px;margin-bottom:10px}.vh-y{font-size:30px;font-weight:800}.vh-m{font-size:28px;font-weight:800;line-height:1.05;text-transform:uppercase}.vh-t{font-size:15px;margin:4px 0 12px;color:#333}.vh-p{font-size:40px;font-weight:900;background:#111;color:#fff;border-radius:8px;padding:8px;margin:8px 0 12px}.vh-r{display:flex;justify-content:space-between;border-bottom:1px solid #ccc;padding:6px 2px;font-size:15px}.vh-v{font-family:monospace;font-size:13px;margin-top:10px}.vh-f{font-weight:800;font-size:18px;margin-top:8px} .vws-h{display:flex;justify-content:space-between;gap:20px;align-items:flex-start;border-bottom:3px solid #111;padding-bottom:10px;margin-bottom:10px}.vws-n{font-size:24px;font-weight:800}.vws-s{color:#444;font-size:13px}.vws-p{text-align:right}.vws-p span{display:block;font-size:12px;text-transform:uppercase;color:#555}.vws-p b{font-size:34px;font-weight:900}.vws-p s{display:block;color:#777} .vws-g{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:10px;font-size:13px}.vws-g ul{columns:2;margin:0;padding-left:18px}.vws-mpg{display:flex;gap:10px;margin-bottom:10px}.vws-mpg div{flex:1;border:2px solid #111;border-radius:8px;text-align:center;padding:8px}.vws-mpg b{display:block;font-size:28px}.vws-fin{margin-top:10px;background:#f2f4f7;border-radius:8px;padding:10px;font-weight:600}`; function vDoc(id,kind){const v=veh(id);const names={book:'Book sheet',sticker:'Window sticker',hang:'Hang tag',guide:'Buyers Guide'};if(kind==='book'&&!Object.keys(bookSummary(v)).length)toast('No book values yet. The sheet will show empty guides'); const body=vDocHTML(v,kind);const css=fcss()+BKCSS+VDCSS; const doc=`${names[kind]} – ${esc(v.stock)}
${names[kind]} · ${esc(v.stock)}
${body}
`; openModal(mh(names[kind]+' · '+esc(v.stock)+' '+esc(vname(v)))+`
${body}
${kind==='guide'?``:''}${DL?'':''}
`,true); if($('#vgw'))$('#vgw').onchange=e=>{v.warranty=e.target.value;save();vDoc(id,kind)}; $('#vdc').onclick=()=>copyText(doc); $('#vdp').onclick=()=>{try{const f=document.createElement('iframe');f.style.cssText='position:fixed;width:0;height:0;border:0;right:0;bottom:0';document.body.appendChild(f);f.srcdoc=doc;f.onload=()=>{try{f.contentWindow.focus();f.contentWindow.print()}catch(e){toast('Printing is blocked here. Use Download instead')}setTimeout(()=>f.remove(),60000)}}catch(e){toast('Printing is blocked here. Use Download instead')}}; if($('#vdd'))$('#vdd').onclick=async()=>{try{await DL.save({filename:`${kind}-${v.stock}.html`,data:doc});toast('Saved. Open it and click Print')}catch(e){if(e&&e.code!=='declined')copyText(doc)}}; vlog(v,names[kind]+' opened for printing');save()} const VWCSS=`.vw-grid{grid-template-columns:300px minmax(0,1fr)}.vw-topacts{display:flex;gap:8px;margin-left:auto;flex-wrap:wrap} .vw-photo{position:relative;border-radius:10px;overflow:hidden;background:#f0f2f5;aspect-ratio:4/3;display:grid;place-items:center;margin-bottom:10px}.vw-photo img{width:100%;height:100%;object-fit:cover}.vw-photo svg{width:80%;height:auto}.vw-photo .btn{position:absolute;right:8px;bottom:8px;background:rgba(255,255,255,.94)} .vw-status{display:flex;gap:8px;margin-bottom:10px}.vw-status select{flex:1;min-width:0;padding:7px 9px;border:1px solid #d0d5dd;border-radius:7px;font-weight:600} .vw-specs{display:flex;flex-direction:column;gap:2px;padding:10px 0;margin-bottom:8px;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.vw-specs b{font-size:14.5px} .vw-sub{margin-bottom:12px;max-width:100%;overflow-x:auto} .vw-sum{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px}.vw-sum .card{padding:14px 16px}.vw-wide{grid-column:1/-1} .vw-ch{display:flex;align-items:center;gap:8px;justify-content:space-between;margin-bottom:10px}.vw-ch h3{margin:0;font-size:15px} .vw-m{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:5px 0;border-bottom:1px solid #f0f2f5;font-size:13px;color:var(--ink2)}.vw-m span i{display:block;font-style:normal;font-size:11.5px}.vw-m b{font-weight:600;color:var(--ink)}.vw-m.tot{border-bottom:0;border-top:2px solid var(--line);margin-top:4px;padding-top:9px}.vw-m.tot b{font-size:16px} .vw-mi{display:flex;align-items:center;border:1px solid #d0d5dd;border-radius:7px;overflow:hidden;width:130px;flex:0 0 130px}.vw-mi b{padding:0 7px;color:var(--muted);background:#f7f8fa;align-self:stretch;display:grid;place-items:center;font-weight:500}.vw-mi input{border:0;width:100%;padding:6px 8px;text-align:right;font-size:13.5px;color:var(--ink);background:#fff}.vw-mi:focus-within{border-color:var(--brand);box-shadow:0 0 0 3px #dbe6ff} .vw-allin{display:flex;flex-direction:column;gap:12px;justify-content:center}.vw-eq{display:flex;align-items:center;gap:8px;justify-content:space-between}.vw-eq>div{flex:1;text-align:center;background:#f7f8fa;border-radius:10px;padding:10px 6px}.vw-eq>div.hl{background:#eef3ff;color:#1d47bd}.vw-eq span,.vw-eq2 span{display:block;font-size:12px;color:var(--muted)}.vw-eq b{font-size:17px}.vw-eq i{font-style:normal;font-weight:700;color:var(--muted)} .vw-eq2{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.vw-eq2>div{border:1px solid var(--line);border-radius:10px;padding:8px 10px}.vw-eq2 b{font-size:15px} .vw-t{width:100%;font-size:13px}.vw-t th,.vw-t td{padding:6px 4px} .vw-hist{display:flex;flex-direction:column;gap:8px}.vw-hrow{display:flex;align-items:center;gap:8px;padding:8px 10px;border:1px solid var(--line);border-radius:10px}.vw-hrow>div{flex:1;min-width:0} .vw-docs{display:grid;grid-template-columns:1fr 1fr;gap:8px}.vw-doc{text-align:left;border:1px solid var(--line);border-radius:10px;background:#fff;padding:10px 12px;cursor:pointer;font:inherit}.vw-doc:hover{border-color:var(--brand);background:#f5f8ff}.vw-doc b{display:block;font-size:13.5px;color:var(--ink)}.vw-doc span{font-size:12px;color:var(--muted)}.vw-doc:focus-visible{outline:3px solid #a9c1ff} .vw-simg{display:grid;grid-template-columns:1fr 1fr;gap:10px}.vw-simg>div{background:#f7f8fa;border-radius:10px;padding:10px 12px}.vw-simg h4{margin:0 0 6px;font-size:12.5px}.vw-simg dl{display:grid;grid-template-columns:1fr auto;gap:3px 8px;margin:0;font-size:12.5px}.vw-simg dt{color:var(--muted)}.vw-simg dd{margin:0;font-weight:600;text-align:right} .vw-simlist{margin-top:8px;display:flex;flex-direction:column}.vw-simlist a{display:flex;gap:8px;align-items:center;padding:6px 2px;border-bottom:1px solid #f0f2f5;font-size:13px;color:var(--ink);text-decoration:none}.vw-simlist a i{margin-left:auto;font-style:normal}.vw-simlist a:hover{color:var(--brand)} .vw-opts{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}.vw-opt{display:inline-flex;align-items:center;gap:4px;background:#eef3ff;color:#1d47bd;border-radius:999px;padding:4px 6px 4px 11px;font-size:12.5px;font-weight:500}.vw-opt button{border:0;background:transparent;color:inherit;cursor:pointer;font-size:15px;line-height:1;padding:0 4px;border-radius:50%}.vw-opt button:hover{background:#dbe6ff} .vw-addopt{display:flex;gap:6px}.vw-addopt input{flex:1;max-width:340px;padding:7px 9px;border:1px solid #d0d5dd;border-radius:7px} .vw-desc{white-space:pre-wrap;margin:0;color:var(--ink2);line-height:1.6} .vw-range{position:relative;height:34px;margin:16px 6px 4px}.vw-rt{position:absolute;left:0;right:0;top:15px;height:4px;background:#e4e7ec;border-radius:2px}.vw-range i{position:absolute;top:10px;width:14px;height:14px;margin-left:-7px;border-radius:50%;background:#98a2b3;border:2px solid #fff}.vw-range b{position:absolute;top:4px;width:6px;height:26px;margin-left:-3px;border-radius:3px;background:var(--brand)} @media(max-width:1100px){.vw-grid{grid-template-columns:1fr}.vw-grid .cw-left{position:static}}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Customer page: detailed status, compliance strip, check-in, deposit, pre-qual ================= */ const CSUB=[['New','New'],['Contact attempt','New'],['Contacted','Contacted'],['Appt. scheduled','Appointment'],['Working deal','Appointment'],['Missed appt.','Contacted'],['Visit follow-up','Contacted'],['Sold','Sold'],['Lost','Lost']]; const CSUB_DEF={New:'New',Contacted:'Contacted',Appointment:'Appt. scheduled',Sold:'Sold',Lost:'Lost'}; const subOf=c=>{const m=CSUB.find(x=>x[0]===c.sub);return m&&m[1]===c.stage?c.sub:(CSUB_DEF[c.stage]||c.stage)}; const PRIOS=['Hot','Warm','Normal','Cold']; function setCustSub(id,s,note){const c=cust(id);if(!c)return;if(s==='Lost'&&c.stage!=='Lost')return dispModal(id,'Lost');const st=CSUB.find(x=>x[0]===s)[1];const was=subOf(c);c.sub=s; if(c.stage!==st){c.notes.push({date:TODAY,time:new Date().toTimeString().slice(0,5),by:S.settings.user,text:`Stage changed ${c.stage} → ${st}`});c.stage=st} if(was!==s||note)c.notes.push({date:TODAY,time:new Date().toTimeString().slice(0,5),by:S.settings.user,text:`Disposition: ${s}${note?' · '+note:''}`}); save();render();if(s==='Appt. scheduled'&&!(c.next&&/Appointment|Test drive|Visit/.test(c.next.type))){ui.nxType='Appointment';nextActionModal(id)}} function dispModal(id,pre){const c=cust(id);const cur=pre||subOf(c);openModal(mh('Update status · '+esc(c.name))+`
${CSUB.map(([s])=>``).join('')}
Why was it lost?
${LOST_REASONS.map(r=>``).join('')}
`); const f=$('#dpf');f.onchange=()=>{$('#dplost').style.display=fd(f).s==='Lost'?'':'none'}; f.onsubmit=e=>{e.preventDefault();const x=fd(f);if(!x.s)return toast('Pick a status'); if(x.s==='Lost'){if(!x.why)return toast('Pick a reason');c.stage='Lost';c.sub='Lost';c.next=null;c.followUp='';if(c.plan&&c.plan.status==='Active')c.plan.status='Stopped';c.notes.push({date:TODAY,by:S.settings.user,text:'Lead closed – '+x.why+(x.note?' · '+x.note:'')});save();closeModal();render();return toast('Lead closed')} closeModal();setCustSub(id,x.s,x.note)}} function checkIn(id){const c=cust(id);(c.visits=c.visits||[]).push({at:nowAt(),by:S.settings.user});c.notes.push({date:TODAY,time:new Date().toTimeString().slice(0,5),by:S.settings.user,text:'Checked in at the dealership'}); if(c.next&&c.next.date<=TODAY&&/Appointment|Test drive|Visit/.test(c.next.type))c.next=null;if(isLead(c)){c.sub='Working deal';c.stage='Appointment'}save();render();toast(`${c.name} checked in${c.ownerId?'. '+uname(c.ownerId)+' was notified':''}`)} {const _mn=myNotifs;myNotifs=function(){const out=_mn();const u=me();if(!u)return out;S.customers.forEach(c=>(c.visits||[]).filter(v=>v.at.slice(0,10)===TODAY&&(c.ownerId===u.id||(!c.ownerId&&['Owner','Sales Manager','Desking Manager'].includes(u.role)))).forEach(v=>out.push({id:'ci_'+c.id+'_'+v.at,kind:'Customer checked in',text:`${c.name} is at the dealership`,go:`openCustomer('${c.id}')`,at:v.at})));return out}} const depTotal=c=>(c.deposits||[]).filter(d=>!d.refunded).reduce((a,d)=>a+ +d.amount,0); function depositModal(id){const c=cust(id);const v=interestVeh(c);openModal(mh('Take deposit · '+esc(c.name))+`
${(c.deposits||[]).length?`

On file

${c.deposits.map((d,i)=>``).join('')}
${fdate(d.date)}${esc(d.method)}${$$(d.amount)}${d.refunded?'Refunded':``}
`:''}
`); document.querySelectorAll('[data-rf]').forEach(b=>b.onclick=()=>confirmBox('Mark this deposit refunded?',()=>{const d=c.deposits[+b.dataset.rf];d.refunded=TODAY;txn(TODAY,'Customer Deposit',-d.amount,d.stock||c.name,'Deposit refunded – '+c.name);c.notes.push({date:TODAY,by:S.settings.user,text:`Deposit refunded ${$$(d.amount)}`});save();render();toast('Refund recorded')})); $('#dpsf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const amt=+x.amount;if(!(amt>0))return toast('Enter an amount');const vv=x.vehicleId&&veh(x.vehicleId); (c.deposits=c.deposits||[]).push({id:uid(),date:TODAY,amount:amt,method:x.method,ref:x.ref,vehicleId:x.vehicleId||'',stock:vv?vv.stock:'',refundable:!!x.refundable,by:S.settings.user});txn(TODAY,'Customer Deposit',amt,vv?vv.stock:c.name,`Deposit from ${c.name} (${x.method})`); if(vv&&x.hold&&vv.status==='Available'){vv.status='Pending';vlog(vv,`Held with ${$$(amt)} deposit from ${c.name}`)}if(vv&&!c.vehicleId)c.vehicleId=vv.id; c.notes.push({date:TODAY,time:new Date().toTimeString().slice(0,5),by:S.settings.user,text:`Deposit taken ${$$(amt)} (${x.method})${vv?' on '+vv.stock:''}`});save();closeModal();render();toast('Deposit recorded')}} const COMPL=[['credit','Credit report','creditRpt'],['prequal','Pre-qual','prequal'],['id','ID verification','idAt'],['ofac','OFAC','ofacAt'],['adverse','Adverse action','adverseAt'],['csd','Credit score disclosure','csdAt'],['privacy','Privacy notice','privacyAt']]; function complState(c,k){if(k==='id')return !!(c.idAt||c.dlNo);if(k==='prequal')return !!(c.prequal&&c.prequal.at);const f=COMPL.find(x=>x[0]===k)[2];return !!c[f]} function complStrip(c){return `
${COMPL.map(([k,l])=>{const ok=complState(c,k);return ``}).join('')}
`} const COMPL_TXT={credit:'Record the bureau pull. Live pulls need a credit bureau partner (e.g. 700Credit) connected in Settings → Connections. Get the customer’s written permission first (FCRA).', id:'Check the driver’s license against the customer in person (Red Flags Rule). Scan it to fill in their details automatically.',ofac:'Search the customer’s name on the Treasury OFAC SDN list before you sell. Record that there was no match.', adverse:'Required when you deny credit or offer worse terms based on a credit report (ECOA / FCRA). Record when and how the notice was given.',csd:'Give the credit score disclosure (or risk-based pricing notice) when you used a credit score to set terms.',privacy:'Give the GLBA privacy notice on every financed deal.'}; function complModal(id,k){const c=cust(id);if(k==='prequal'){ui.cTab='prequal';return render()}if(k==='privacy'&&!c.privacyAt)return privacyNotice(id);if(k==='id'&&!c.dlNo&&!c.idAt)return newDocFor(id); const l=COMPL.find(x=>x[0]===k)[1],f=COMPL.find(x=>x[0]===k)[2];const cur=c[f];const r=k==='credit'&&cur&&typeof cur==='object'?cur:{}; openModal(mh(l+' · '+esc(c.name))+`

${COMPL_TXT[k]}

${cur?`
Done ${typeof cur==='string'?ftime(cur):fdate(cur.date)}${c[f+'Note']?' · '+esc(c[f+'Note']):''}
`:''}
${k==='credit'?`` :k==='adverse'?`` :``}
${k==='ofac'?'Open OFAC search ↗':''}
${cur?'':''}
`); if($('#cmclr'))$('#cmclr').onclick=()=>{delete c[f];delete c[f+'Note'];save();closeModal();render()}; $('#cmf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(k==='credit'){c.creditRpt={bureau:x.bureau,score:x.score,date:x.date,perm:true};if(x.score)c.score=x.score}else{c[f]=nowAt();if(x.note||x.how)c[f+'Note']=[x.note,x.how].filter(Boolean).join(' · ')} c.notes.push({date:TODAY,by:S.settings.user,text:`${l} done${x.score?' · score '+x.score:''}${x.note?' · '+x.note:''}`});save();closeModal();render();toast(l+' recorded')}} /* pre-qualification */ function pqCalc(c){const st=S.settings,p=Object.assign({income:+c.income||0,other:0,housing:0,debt:0,down:0,pti:+st.pti||20,dti:50,apr:+st.apr||19.9,term:+st.term||78,freq:st.freq||'biweekly'},c.prequal||{}); const inc=(+p.income||0)+(+p.other||0);const ppy=FREQ[p.freq]?.ppy||26;const capPti=inc*(+p.pti)/100,capDti=inc*(+p.dti)/100-(+p.housing||0)-(+p.debt||0);const mo=Math.max(0,Math.min(capPti,capDti));const per=mo*12/ppy; const r=(+p.apr)/100/ppy,n=+p.term;const fin=r?per*(1-Math.pow(1+r,-n))/r:per*n;const tax=(+st.taxRate||0)/100;const maxPrice=Math.max(0,(fin+(+p.down||0)-(+st.docFee||0))/(1+tax)); return{p,inc,mo,per,ppy,fin,maxPrice,limit:capDtiv.status==='Available'&&+v.price<=R.maxPrice&&(!p.down||!v.minDown||+v.minDown<=+p.down)).sort((a,b)=>b.price-a.price).slice(0,8); const fld=(l,k,t,o)=>``; return `

Pre-qualification

${c.prequal&&c.prequal.at?`Saved ${ftime(c.prequal.at)}`:'Not saved yet'}
${fld('Monthly income','income')}${fld('Other income','other')}${fld('Rent / mortgage','housing')}${fld('Other monthly debts','debt')}${fld('Cash down','down')}${fld('Credit score range','score','',[['','Unknown'],['<500','Under 500'],['500-579','500–579'],['580-619','580–619'],['620-679','620–679'],['680+','680+']])}${fld('Max payment-to-income %','pti')}${fld('Max debt-to-income %','dti')}${fld('APR %','apr')}${fld('Term (payments)','term')}${fld('Pay schedule','freq','',Object.entries(FREQ).map(([k,f])=>[k,f.label]))}
Max payment${$0(R.per)}/${FREQ[p.freq]?.label.toLowerCase()||'period'}${$0(R.mo)} a month, limited by ${R.limit}
Max amount financed${$0(R.fin)}${p.term} payments at ${p.apr}%
Shop up to${$0(R.maxPrice)}selling price with ${$0(p.down||0)} down, tax and doc fee
An estimate for shopping, not a credit decision. Lenders decide final terms.

Vehicles that fit · ${fit.length}

${fit.length?`${fit.map(v=>{const f=(+v.price*(1+(+S.settings.taxRate||0)/100)+(+S.settings.docFee||0))-(+p.down||0);const r=(+p.apr)/100/R.ppy;const pay=r?f*r/(1-Math.pow(1+r,-p.term)):f/p.term;return ``}).join('')}
VehiclePriceMilesEst. payment
${esc(vname(v))}
${esc(v.stock)}
${$0(v.price)}${(+v.miles).toLocaleString()}${$0(pay)}
`:'
Nothing in stock fits these numbers. Try more down or a longer term.
'}
`} function pqSave(id){const c=cust(id);c.prequal=Object.assign({},pqCalc(c).p,{at:nowAt(),by:S.settings.user});const R=pqCalc(c);c.notes.push({date:TODAY,by:S.settings.user,text:`Pre-qual saved: shop up to ${$0(R.maxPrice)}, max payment ${$0(R.per)}`});save();render();toast('Pre-qual saved')} document.addEventListener('change',e=>{const k=e.target&&e.target.dataset&&e.target.dataset.pq;if(!k||route!=='cust')return;const c=cust(ui.custId);c.prequal=Object.assign({},c.prequal||{},{[k]:['score','freq'].includes(k)?e.target.value:e.target.value===''?'':+e.target.value});save();render()}); {const _ct=custTab;custTab=function(c,deals,loans){if(ui.cTab==='prequal')return pqTab(c);return _ct.apply(this,arguments)}} /* richer interested-vehicle panel */ {const _cv=custVehicleCard;custVehicleCard=function(c,v){if(!v)return _cv(c,v);const ph=mainPhoto(v),N=vNumbers(v);const f=(l,x)=>`
${l}
${x==null||x===''?'—':esc(x)}
`; return `

Interested vehicle

${ph?`${esc(vname(v))}`:carSVG(v.color)}
${esc(vname(v))}
${statusPill(v.status==='Available'?'Available':v.status)}
${f('Price',$0(+v.advPrice||+v.price))}${f('Stock #',v.stock)}${f('VIN',v.vin)}${f('Mileage',(+v.miles).toLocaleString())}${f('Location',v.lot)}${f('Ext / int',[v.color,v.intColor].filter(Boolean).join(' / '))}${v.minDown?f('Down from',$0(v.minDown)):''}${f('All-in',$0(N.allIn))}
${v.status!=='Sold'?``:''}

Vehicle features

${f('Body',v.body)}${f('Days in stock',age(v))}${f('Transmission',v.trans)}${f('Condition',v.condition||'Used')}${f('Engine',v.engine)}${f('Doors',v.doors)}${f('Fuel',v.fuel)}${f('Drivetrain',v.drive)}${f('Cylinders',v.cyl)}${f('Title brand',v.titleBrand||'Clean')}${f('MPG',v.mpgCity||v.mpgHwy?(v.mpgCity||'—')+' / '+(v.mpgHwy||'—'):'')}${f('Title status',v.titleStatus)}
${(v.options||[]).length?`
${v.options.slice(0,8).map(o=>`${esc(o)}`).join('')}
`:''}

Vehicle history reports

${vHistHTML(v)}
`}} function planPick(cid){const ps=S.plans||[];if(!ps.length)return toast('No follow-up plans yet. Create one in Leads & CRM');openModal(mh('Start a workflow')+`
${ps.map(p=>``).join('')}
${esc(p.name)}
${p.steps.length} steps
`)} function custNavList(){const ids=(ui.custList||[]).filter(id=>cust(id));if(ids.length&&ids.includes(ui.custId))return ids;return S.customers.slice().sort((a,b)=>String(b.createdAt||b.created||'').localeCompare(String(a.createdAt||a.created||''))).map(c=>c.id)} function custNavBar(c){const l=custNavList(),i=l.indexOf(c.id);const back={crm:'Leads & CRM',activity:'Customer Activity',dashboard:'Dashboard',reports:'Reports',deals:'Deals'}[ui.custBack]||TITLES[ui.custBack]||'Leads & CRM'; return `
← Back to ${esc(back)}${i+1} of ${l.length.toLocaleString()}
`} function custStep(d){const l=custNavList(),i=l.indexOf(ui.custId);const n=l[i+d];if(n){ui.custId=n;ui.cMenu=false;render();window.scrollTo(0,0)}} function custSaveNow(){const a=document.activeElement;if(a&&a.blur&&/INPUT|SELECT|TEXTAREA/.test(a.tagName))a.blur();save();toast('All changes saved')} document.addEventListener('click',e=>{if(ui.cMenu&&!e.target.closest('.cw-more')){ui.cMenu=false;if(route==='cust')render()}}); document.addEventListener('keydown',e=>{if(e.key==='Escape'&&ui.cMenu){ui.cMenu=false;render()}}); function custPrint(id){const c=cust(id);const v=interestVeh(c);const body=F.hdr('Customer Summary',0,esc(subOf(c)))+F.grid([[['Name',c.name,2],['Cell',c.phone],['Email',c.email]],[['Address',c.address,2],['Lead source',c.source],['Sales rep',uname(c.ownerId)]],[['Vehicle',v?vname(v)+' · '+v.stock:(c.interest||''),2],['Deposit',depTotal(c)?$$(depTotal(c)):'None'],['Priority',c.priority||'Normal']]])+`

Recent activity

${custActivity(c).slice(0,12).map(x=>``).join('')}
${esc(String(x.at).slice(0,10))}${esc(x.title)}: ${esc(String(x.body).slice(0,160))}
`; openModal(mh('Customer summary · '+esc(c.name))+`
${body}
`,true); $('#cpp').onclick=()=>{const f=document.createElement('iframe');f.style.cssText='position:fixed;width:0;height:0;border:0';document.body.appendChild(f);f.srcdoc=`
${body}
`;f.onload=()=>{try{f.contentWindow.print()}catch(e){toast('Printing is blocked here')}setTimeout(()=>f.remove(),60000)}}} const CW2CSS=`.cw-nav{display:flex;align-items:center;gap:8px;margin:-4px 0 10px;font-size:13px}.cw-nav a{font-weight:600}.cw-nav .sp{flex:1}.cw-nav .btn.ic{width:30px;justify-content:center} .cw-more{position:relative}.cw-more>.btn.ic{width:38px;justify-content:center}.cw-menu{position:absolute;right:0;top:calc(100% + 6px);z-index:40;background:#fff;border:1px solid var(--line);border-radius:10px;box-shadow:0 12px 32px rgba(16,24,40,.16);padding:6px;min-width:220px;display:flex;flex-direction:column}.cw-menu button{border:0;background:transparent;text-align:left;padding:9px 12px;border-radius:7px;font:500 13.5px inherit;color:var(--ink);cursor:pointer}.cw-menu button:hover,.cw-menu button:focus-visible{background:#f5f8ff;outline:0} .cw-comp{flex-wrap:nowrap;overflow-x:auto;gap:2px}.cc{white-space:nowrap;font-size:12.5px;padding:6px 8px} .cw-head{align-items:center}.cw-head .cw-name select{padding:5px 8px;border:1px solid #d0d5dd;border-radius:7px;font-weight:600;font-size:13px}.cw-hacts{display:flex;gap:8px;margin-left:auto;flex-wrap:wrap} .prio-Hot{color:#b42318!important;border-color:#fda29b!important;background:#fef3f2}.prio-Warm{color:#b54708!important;border-color:#fec84b!important;background:#fffaeb}.prio-Cold{color:#175cd3!important;border-color:#b2ccff!important;background:#eff8ff} .cw-flow{display:flex;gap:10px;align-items:center;margin-bottom:12px}.cw-flow .cw-steps{margin:0;flex:1;flex-wrap:nowrap;overflow-x:auto}.cw-flow .cw-steps li{flex:1;min-width:max-content}.cw-flow .cw-steps button{width:100%;padding:9px 14px 9px 20px} .cw-comp{display:flex;align-items:center;gap:6px;flex-wrap:wrap;background:#fff;border:1px solid var(--line);border-radius:12px;padding:8px 10px;margin-bottom:12px}.cw-comp .sp{flex:1} .cc{display:inline-flex;align-items:center;gap:6px;border:1px solid transparent;background:transparent;border-radius:8px;padding:6px 9px;font:600 13px inherit;color:var(--ink2);cursor:pointer}.cc:hover{background:#f5f8ff;border-color:#e1e9fb}.cc i{width:16px;height:16px;border-radius:50%;border:2px solid #98a2b3;display:grid;place-items:center;font-style:normal;font-size:10px;color:#fff;line-height:1}.cc.ok i{background:#12b76a;border-color:#12b76a}.cc:focus-visible{outline:3px solid #a9c1ff} .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)} .cw-kp2{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:1px;background:var(--line);border:1px solid var(--line);border-radius:12px;overflow:hidden;margin-bottom:14px}.cw-kp2>div{background:#fff;padding:9px 14px;display:grid;grid-template-columns:auto 1fr;gap:3px 10px;font-size:12.5px;align-content:center}.cw-kp2 span{color:var(--muted)}.cw-kp2 b{font-weight:600;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cw-kp2 b a{font-weight:600} .cw-wf{margin-left:auto;font-size:13px;color:var(--muted);display:flex;align-items:center;gap:6px}.cw-wf b{color:var(--brand);text-transform:uppercase;letter-spacing:.02em} .dp-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}.dp-opt{display:flex;align-items:center;gap:8px;border:1px solid var(--line);border-radius:8px;padding:8px 10px;cursor:pointer;font-size:13px}.dp-opt:has(input:checked){border-color:var(--brand);background:#f5f8ff;font-weight:600} .pq-out{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:14px}.pq-out>div{background:#f7f8fa;border-radius:10px;padding:12px}.pq-out>div.hl{background:#eef3ff;color:#1d47bd}.pq-out span{display:block;font-size:12px;color:var(--muted)}.pq-out b{font-size:20px;display:block}.pq-out b small{font-size:12px;font-weight:500}.pq-out i{font-style:normal;font-size:12px;color:var(--muted)} .cw-vtop{display:flex;gap:10px;align-items:center;margin-bottom:8px}.cw-vtop .cw-vimg{width:110px;height:78px;flex:0 0 110px;margin:0}.cw-vtop .cw-vimg svg{width:90%}.cw-vname{font-weight:700;font-size:14.5px;color:var(--ink);display:block;margin-bottom:4px} .cw-vdl{display:grid;grid-template-columns:auto 1fr;gap:3px 10px;margin:6px 0 10px;font-size:12.5px}.cw-vdl dt{color:var(--muted)}.cw-vdl dd{margin:0;font-weight:600;text-align:right;overflow-wrap:anywhere}.cw-vdl.two{grid-template-columns:auto 1fr auto 1fr}.cw-vdl.two dd{white-space:nowrap} .cw-vh{margin:14px 0 6px;font-size:13px;padding-top:10px;border-top:1px solid var(--line)} .cw-veh .vw-hrow{flex-wrap:wrap;padding:7px 8px}.cw-veh .vw-hist>p{font-size:11.5px} @media(max-width:1280px){.cw-kp2{grid-template-columns:repeat(3,minmax(0,1fr))}.dp-grid{grid-template-columns:repeat(2,1fr)}} .cw-nav{background:#e8f2fc;border:1px solid #d3e4f7;border-radius:10px;padding:7px 12px;margin:-4px 0 10px} .cw-head{background:#f3f8fe;border:1px solid #d9e7f7;border-radius:12px;padding:10px 12px}.cw-head .cw-name{background:#fdf1cf;border-radius:8px;padding:6px 12px}.cw-head .cw-name h2{font-size:18px}.cw-head .cw-name>.pill{background:transparent;color:#8e2bd6;font-weight:600;padding:0} .cw-hacts .btn:not(.pri){border-color:#2f6fe4;color:#1f5bd1;background:#fff}.cw-hacts .btn:not(.pri):hover{background:#eef4ff} .cw-flow .cw-steps button{background:#eef1f4;color:#475467}.cw-flow .cw-steps button.done{background:#c9efe7;color:#0d5c4f}.cw-flow .cw-steps button.on{background:#14a88a;color:#fff;font-weight:700}.cw-flow .cw-steps button.on.lost{background:#d92d20} .cw-flow>.btn{border-color:#14a88a;color:#0d7a64;background:#e9f8f4} .cc.ok i{background:#14a88a;border-color:#14a88a}.cc{color:#1d2939}.cc:hover{background:#eefaf6;border-color:#c9efe7} .cw-kp2 b a{color:#0d7a64} .cw .cw-main>.tabs{border-bottom:0;gap:4px;flex-wrap:wrap;margin-bottom:12px}.cw .cw-main>.tabs button{background:#e6f0fb;border:1px solid #d3e4f7;border-bottom:0;border-radius:8px 8px 0 0;padding:9px 16px;color:#1d2939;font-weight:500}.cw .cw-main>.tabs button.on{background:#fff;color:#101828;font-weight:700;box-shadow:inset 0 3px 0 #1f5bd1} .cw .cw-actions .btn{background:#1f5bd1;border-color:#1f5bd1;color:#fff}.cw .cw-actions .btn:hover{background:#1a4fb7} .cw-feedhead .seg button.on{background:#1f5bd1} .cw-left .seg{border:0;gap:4px;background:transparent;overflow:visible}.cw-left .seg button{background:#e6f0fb;border:1px solid #d3e4f7!important;border-radius:8px 8px 0 0;color:#1d2939;font-weight:500}.cw-left .seg button.on{background:#fff;color:#101828;font-weight:700;box-shadow:inset 0 3px 0 #1f5bd1} .cw-veh>.vw-ch{background:#eefaf6;margin:-16px -16px 12px;padding:10px 16px;border-bottom:1px solid #d5f0e7;border-radius:12px 12px 0 0}.cw-veh>.vw-ch h3{color:#101828}.cw-veh>.vw-ch .btn{border-color:#14a88a;color:#0d7a64;background:#fff} .cw-veh .vw-hrow .btn{border-color:#14a88a;color:#0d7a64} `; document.head.insertAdjacentHTML('beforeend',''); /* ---- calm layer: one type scale, softer colors, even spacing (loaded last) ---- */ const CALM=`:root{--bg:#f6f7f9;--ink:#1f2937;--ink2:#344054;--muted:#667085;--line:#e6e8ec;--line2:#f0f1f4;--brand:#2f5fd0;--brand2:#2650b5;--brandsoft:#eef3fd;--radius:12px;--shadow:none} html,body{font-family:'Inter',system-ui,-apple-system,'Segoe UI',sans-serif} body{font-size:14px;line-height:1.55;letter-spacing:0;color:var(--ink);background:var(--bg);-webkit-font-smoothing:antialiased} b,strong,td b{font-weight:600}h1,h2,h3,h4{font-weight:600!important;letter-spacing:-.01em!important;color:var(--ink)} a{font-weight:500;color:var(--brand)} /* sidebar: light and quiet */ aside{background:#fff;border-right:1px solid var(--line);padding:18px 12px} .logo{color:var(--ink);font-weight:600;font-size:16px}.logo small{color:var(--muted);font-weight:400} nav a{color:#475467;font-weight:500;font-size:13.5px;padding:8px 12px;border-radius:8px} nav a:hover{background:#f4f6f8;color:var(--ink)}nav a.on{background:var(--brandsoft);color:var(--brand);font-weight:600}nav a.on:before{display:none} nav .ico{color:#98a2b3}nav a:hover .ico{color:#475467}nav a.on .ico{color:var(--brand)} nav .sec{color:#98a2b3;font-size:11px;font-weight:500;letter-spacing:.06em;margin:20px 12px 6px} /* top bar */ .top{min-height:60px;padding:10px 32px;border-bottom:1px solid var(--line);background:#fff} .top h1{font-size:17px;font-weight:600;letter-spacing:-.01em} .search input{background:#f6f7f9;border-color:var(--line);padding:8px 12px} .content{padding:28px 32px 80px} /* surfaces */ .card{border-color:var(--line);box-shadow:none;padding:20px} .card h3{font-size:15px;font-weight:600;margin:0 0 12px} .grid{gap:20px}.bar{gap:10px;margin-bottom:16px} .kpi .l{font-size:12.5px;color:var(--muted)}.kpi .v{font-size:24px;font-weight:600;letter-spacing:-.02em}.kpi .s{font-size:12.5px;color:var(--muted)} /* tables */ th{font-size:12px;font-weight:500;color:var(--muted);padding:10px 14px;border-bottom:1px solid var(--line)} td{padding:11px 14px;border-bottom:1px solid var(--line2);color:var(--ink2)} tr.click:hover td{background:#f8f9fb}.num{font-weight:400;font-variant-numeric:tabular-nums} /* controls */ .btn{font-weight:500;font-size:13.5px;padding:7px 14px;border-radius:8px;border-color:#d5d9e0;box-shadow:none;color:var(--ink2)} .btn:hover{background:#f6f7f9;border-color:#c4c9d2} .btn.pri{background:var(--brand);border-color:var(--brand);color:#fff;box-shadow:none}.btn.pri:hover{background:var(--brand2);border-color:var(--brand2)} .btn.sm{font-size:12.5px;padding:5px 10px} .pill{font-weight:500;font-size:12px;padding:2px 9px} input,select,textarea{font-family:inherit;font-size:13.5px} .bar input,.bar select,.form input,.form select,.form textarea,.cf-row input,.cf-row select,.compose textarea,.compose select{border:1px solid #d5d9e0;border-radius:8px;box-shadow:none;color:var(--ink)} input:focus,select:focus,textarea:focus{border-color:#8eaaf0!important;box-shadow:0 0 0 3px #e8eefc!important} .form{gap:14px 16px}.form label{font-weight:500;font-size:12.5px;color:var(--muted)} .tabs button{font-weight:500;color:var(--muted);padding:10px 14px}.tabs button.on{font-weight:600;color:var(--ink)} .seg button{font-weight:500} .hint{color:var(--muted)}.note{background:#f8f9fb;border-left-color:#b9c9f3} /* modal */ .modal{border-radius:14px;box-shadow:0 20px 50px rgba(16,24,40,.18)}.mh{padding:18px 24px;border-bottom:1px solid var(--line)}.mh h2{font-size:17px;font-weight:600}.mb{padding:20px 24px}.mf{padding:14px 24px;background:#fafbfc;border-top:1px solid var(--line)} .ov{background:rgba(16,24,40,.38);backdrop-filter:none} /* customer + vehicle pages: same colors, gentler */ .cw-nav{background:#f1f6fd;border-color:#e0eaf7} .cw-head{background:#f7faff;border-color:#e3ecf8;padding:10px 14px}.cw-head .cw-name{background:#fdf6e1}.cw-head .cw-name h2{font-size:17px}.cw-head .cw-name>.pill{color:#7e3fc4;font-weight:500} .cw-hacts .btn:not(.pri){border-color:#b9cdf3;color:var(--brand)} .cw-flow .cw-steps button{font-weight:500;font-size:12.5px;background:#f1f3f6;color:#667085}.cw-flow .cw-steps button.done{background:#dcf3ee;color:#155e52}.cw-flow .cw-steps button.on{background:#25a58b;font-weight:600} .cw-flow>.btn{border-color:#a8dfd3;background:#f0faf7;color:#16705f} .cc{font-weight:500;color:var(--ink2)}.cc.ok i{background:#25a58b;border-color:#25a58b} .cw-kpis b,.cw-kp2 b{font-weight:500}.cw-kp2 b a{color:#16705f} .cw .cw-main>.tabs button{background:#f1f6fd;border-color:#e0eaf7;font-weight:500;color:#475467}.cw .cw-main>.tabs button.on{font-weight:600;color:var(--ink);box-shadow:inset 0 2px 0 var(--brand)} .cw .cw-actions .btn{background:var(--brand);border-color:var(--brand);font-weight:500} .cw-left .seg button{background:#f1f6fd;border-color:#e0eaf7!important;color:#475467}.cw-left .seg button.on{box-shadow:inset 0 2px 0 var(--brand)} .cw-veh>.vw-ch{background:#f3fbf8;border-color:#e0f3ec} .cw-item{border-color:var(--line)}.cw-ititle b{font-weight:600}.cw-ibody{color:var(--ink2)} .cf-row{margin-bottom:8px}.vw-m b,.vw-eq b{font-weight:600}.vw-eq b{font-size:16px} .cw-grid{gap:20px}.cw-kpis,.cw-kp2,.cw-comp,.cw-quick{margin-bottom:16px} /* desking boxes: match the light layout */ .dk-rail{background:#fff;border-right:1px solid var(--line);top:69px}.dk-ri{color:var(--ink2);border-bottom:1px solid var(--line2);font-weight:500}.dk-ri:hover{background:#f4f6f8;color:var(--ink)} .dk-htitle{font-weight:600}.dk-hcard,.dk-col{border-color:var(--line)} .dk-gh{background:#eef3fd;color:var(--brand);border:1px solid #dbe5fb}.dk-gh input{border:1px solid #c9d6f5;font-weight:500} .dk-gt input{border:1px solid #d5d9e0!important;box-shadow:none!important} .dk-cell{background:#fff;color:var(--ink);border:1px solid var(--line);font-weight:600;font-size:15px}.dk-cell:hover{background:#f5f8ff;border-color:#9fb6ee}.dk-cell.on{background:var(--brand);border-color:var(--brand);color:#fff} .dk-fname{border-style:solid!important;background:#f8f9fb} .dk-total output,.dk-big output{font-weight:600}.dk-sumtop b{font-weight:600} .dk-bottom{box-shadow:0 2px 10px rgba(16,24,40,.06)} /* always light form fields, even when the computer is in dark mode */ :root,html{color-scheme:light only} input,select,textarea{background-color:#fff;color:var(--ink)} input:disabled,select:disabled,textarea:disabled{background-color:#f6f7f9;color:var(--muted)} input::placeholder,textarea::placeholder{color:#98a2b3} input[type=checkbox],input[type=radio]{accent-color:var(--brand);background-color:#fff} option{background:#fff;color:var(--ink)} @media (prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}}`; /* ---- resizable lists: drag any list taller/shorter, drag column edges wider/narrower ---- */ const RLKEY=workspaceStorage('ll_lists_v1');let RLS={};try{RLS=JSON.parse(localStorage.getItem(RLKEY)||'{}')}catch(e){} const rlSave=()=>{try{localStorage.setItem(RLKEY,JSON.stringify(RLS))}catch(e){}}; const RL_SKIP='.pf,.doc,.wdg,.fg,.bkt,.vw-t,.cw-vdl,.form,.kv,.dkws,.sheet,.th-host,#login'; function rlKey(el,i){const box=el.closest('.card,.modal,.cw-main,.content');const h=box&&box.querySelector('h3,.mh h2,.vw-ch h3');const tab=box&&box.querySelector('.tabs button.on,.seg button.on');return [route,h?h.textContent.trim().slice(0,40):'',tab?tab.textContent.trim().slice(0,24):'',i].join('|')} function rlGrip(scroller,key,natural){const g=document.createElement('div');g.className='rl-grip';g.setAttribute('role','separator');g.setAttribute('aria-orientation','horizontal');g.tabIndex=0;g.title='Drag to make this list longer or shorter. Double-click to show everything';g.innerHTML=''; const set=h=>{if(h==null){scroller.style.maxHeight='';delete RLS[key]}else{h=Math.max(90,Math.round(h));scroller.style.maxHeight=h+'px';RLS[key]=Object.assign(RLS[key]||{},{h})}}; g.onpointerdown=e=>{e.preventDefault();g.setPointerCapture(e.pointerId);const y0=e.clientY,h0=scroller.getBoundingClientRect().height;g.classList.add('on'); const mv=ev=>{const h=h0+ev.clientY-y0;if(h>=scroller.scrollHeight-2){scroller.style.maxHeight='';}else set(h)};const up=()=>{g.classList.remove('on');g.removeEventListener('pointermove',mv);g.removeEventListener('pointerup',up);if(!scroller.style.maxHeight){RLS[key]=Object.assign(RLS[key]||{},{h:0})}rlSave()}; g.addEventListener('pointermove',mv);g.addEventListener('pointerup',up)}; g.ondblclick=()=>{if(scroller.style.maxHeight){scroller.style.maxHeight='';RLS[key]=Object.assign(RLS[key]||{},{h:0})}else set(natural);rlSave()}; g.onkeydown=e=>{if(!['ArrowUp','ArrowDown'].includes(e.key))return;e.preventDefault();const h=scroller.getBoundingClientRect().height+(e.key==='ArrowDown'?60:-60);if(h>=scroller.scrollHeight)scroller.style.maxHeight='',RLS[key]=Object.assign(RLS[key]||{},{h:0});else set(h);rlSave()}; return g} function rlCols(t,key){const ths=[...(t.tHead?t.tHead.rows[0]:t.rows[0]).cells].filter(c=>c.tagName==='TH');if(ths.length<2)return;const saved=(RLS[key]||{}).w||{}; ths.forEach((th,i)=>{if(saved[i])th.style.width=th.style.minWidth=saved[i]+'px';if(i===ths.length-1)return;const r=document.createElement('span');r.className='rl-col';r.title='Drag to resize column';r.onclick=e=>e.stopPropagation();th.appendChild(r); r.onpointerdown=e=>{e.preventDefault();e.stopPropagation();r.setPointerCapture(e.pointerId);const x0=e.clientX,w0=th.getBoundingClientRect().width;r.classList.add('on'); const mv=ev=>{const w=Math.max(48,Math.round(w0+ev.clientX-x0));th.style.width=th.style.minWidth=w+'px';(RLS[key]=RLS[key]||{}).w=Object.assign((RLS[key]||{}).w||{},{[i]:w})};const up=()=>{r.classList.remove('on');r.removeEventListener('pointermove',mv);r.removeEventListener('pointerup',up);rlSave()}; r.addEventListener('pointermove',mv);r.addEventListener('pointerup',up)}; r.ondblclick=e=>{e.stopPropagation();th.style.width=th.style.minWidth='';if(RLS[key]&&RLS[key].w){delete RLS[key].w[i];rlSave()}}})} function enhanceLists(){const seen={}; document.querySelectorAll('table:not([data-rl]),.cw-feed:not([data-rl]),.rl-list:not([data-rl])').forEach(el=>{if(el.closest(RL_SKIP))return;el.dataset.rl='1'; const isT=el.tagName==='TABLE';const rows=isT?el.rows.length-1:el.children.length;const k0=rlKey(el,'');seen[k0]=(seen[k0]||0)+1;const key=k0+seen[k0]; if(isT)rlCols(el,key);if(rows<5)return; let sc;if(isT){const p=el.parentElement;if(p&&p.children.length===1&&!p.classList.contains('card')&&!p.classList.contains('mb')&&getComputedStyle(p).overflow!=='visible'){sc=p}else{sc=document.createElement('div');el.before(sc);sc.appendChild(el)}sc.classList.add('rl-wrap')}else{sc=el;sc.classList.add('rl-wrap')} const natural=Math.min(sc.scrollHeight,520);const st=RLS[key];if(st&&st.h)sc.style.maxHeight=st.h+'px';else if(!st&&rows>14)sc.style.maxHeight='560px'; sc.after(rlGrip(sc,key,natural))}); // kanban boards: one height for every column on the board, handle under the board document.querySelectorAll('.pipeline:not([data-rl]),.rboard:not([data-rl])').forEach(bd=>{bd.dataset.rl='1';const key=route+'|board|'+bd.className.split(' ')[0];const cols=[...bd.children]; const apply=h=>cols.forEach(c=>{c.classList.add('rl-wrap');c.style.maxHeight=h?h+'px':''});const st=RLS[key];if(st&&st.h)apply(st.h); const proxy={get style(){return{set maxHeight(v){apply(parseInt(v)||0)},get maxHeight(){return cols[0]&&cols[0].style.maxHeight}}},getBoundingClientRect:()=>({height:Math.max(...cols.map(c=>c.getBoundingClientRect().height))}),get scrollHeight(){return Math.max(...cols.map(c=>c.scrollHeight))}}; bd.after(rlGrip(proxy,key,520))}); // fixed-height panels (texting inbox): drag to change the panel height document.querySelectorAll('.inbox:not([data-rl])').forEach(el=>{el.dataset.rl='1';const key=route+'|panel|inbox';const st=RLS[key];if(st&&st.h)el.style.height=st.h+'px'; const proxy={get style(){return{set maxHeight(v){el.style.height=v||''},get maxHeight(){return el.style.height}}},getBoundingClientRect:()=>el.getBoundingClientRect(),scrollHeight:4000};el.after(rlGrip(proxy,key,620))})} {const _ce=cleanEmoji;cleanEmoji=function(){_ce.apply(this,arguments);try{enhanceLists()}catch(e){}}} const RLCSS=`.rl-wrap{overflow:auto;position:relative}.rl-wrap>table thead th,.rl-wrap>table tr:first-child>th{position:sticky;top:0;z-index:2;background:#fff} .rl-grip{height:14px;margin:2px 0 0;display:flex;align-items:center;justify-content:center;cursor:ns-resize;border-radius:6px;touch-action:none}.rl-grip span{width:44px;height:4px;border-radius:2px;background:#d5d9e0;transition:background .15s}.rl-grip:hover span,.rl-grip.on span,.rl-grip:focus-visible span{background:var(--brand)}.rl-grip:focus-visible{outline:2px solid #a9c1ff} th{position:relative}.rl-col{position:absolute;top:0;right:-4px;width:8px;height:100%;cursor:col-resize;z-index:3;touch-action:none}.rl-col:after{content:'';position:absolute;top:25%;bottom:25%;left:3px;width:2px;border-radius:1px;background:transparent}th:hover .rl-col:after{background:#d5d9e0}.rl-col:hover:after,.rl-col.on:after{background:var(--brand)}`; document.head.insertAdjacentHTML('beforeend',''); /* ================= Engagement & AI Coach: heat score, combined timeline, social, next best move ================= */ const ENG_CH={web:'Website',email:'Email',video:'Video',social:'Social',phone:'Phone & text',person:'In person',deal:'Desking'}; const ENG_W={visit:3,view:7,calc:12,credit:30,trade:15,lead:22,contact:18,email_open:4,email_click:10,video:20,msg_in:25,comment:8,call_ok:12,call_in:22,text_in:20,checkin:30,testdrive:25,deposit:35,desk:18,social_lead:25}; function engAdd(cid,o){S.engage=S.engage||[];const e=Object.assign({id:uid(),cid,at:nowAt()},o);S.engage.push(e);if(S.engage.length>20000)S.engage=S.engage.slice(-15000);return e} function linkVisitor(c,vid){if(!vid)return;c.webVid=vid;const buf=(S.webVisitors||{})[vid];if(buf&&buf.length){buf.forEach(x=>engAdd(c.id,x));delete S.webVisitors[vid];c.notes.push({date:TODAY,by:'Website',text:`Linked ${buf.length} earlier website visit${buf.length===1?'':'s'} to this customer`})}} {const _il=intakeLead;intakeLead=function(L,via){const c=_il.apply(this,arguments);try{if(c&&L&&L.vid)linkVisitor(c,String(L.vid))}catch(e){}return c}} const custByVid=vid=>vid&&S.customers.find(c=>c.webVid===vid); const custByPsid=(psid,pf)=>psid&&S.customers.find(c=>c.social&&c.social[pf==='instagram'?'ig':'fb']&&c.social[pf==='instagram'?'ig':'fb'].psid===psid); const vehByStock=st=>st&&S.vehicles.find(v=>String(v.stock).toLowerCase()===String(st).toLowerCase()); const PFN=pf=>pf==='instagram'?'Instagram':'Facebook'; /* events from the DealerPen server (website tracking, email opens/clicks, Facebook & Instagram) */ function engageEvent(e){const d=e.data||{},at=e.at||nowAt(); if(e.type==='web'){const o={at,ch:'web',kind:d.type,stock:d.stock||'',detail:d.page||'',ref:d.ref||'',utm:d.utm||''};const c=custByVid(d.vid); if(c){engAdd(c.id,o);return ['credit','trade','calc'].includes(d.type)}S.webVisitors=S.webVisitors||{};(S.webVisitors[d.vid]=S.webVisitors[d.vid]||[]).push(o);if(S.webVisitors[d.vid].length>200)S.webVisitors[d.vid].shift();return false} if(e.type==='email_open'||e.type==='email_click'){const c=cust(d.customerId);if(!c)return false;engAdd(c.id,{at,ch:'email',kind:e.type,detail:d.subject||'',url:d.url||''});return e.type==='email_click'} if(e.type==='video_view'){const c=cust(d.customerId);if(c)engAdd(c.id,{at,ch:'video',kind:'video',detail:d.vehicle||'',pct:+d.pct||0});return false} if(e.type==='meta_msg'){const k=d.platform==='instagram'?'ig':'fb';let c=custByPsid(d.psid,d.platform); if(!c){c=intakeLead({name:d.name||`${PFN(d.platform)} shopper`,source:PFN(d.platform),message:''},PFN(d.platform)+' Messenger');c.social=c.social||{};c.social[k]={psid:d.psid,name:d.name||'',username:d.username||'',linked:at}} if(S.comms.some(x=>x.mid&&x.mid===d.mid))return false;logComm({customerId:c.id,channel:'social',platform:d.platform,dir:'in',body:d.text,mid:d.mid,psid:d.psid});engAdd(c.id,{at,ch:'social',kind:'msg_in',detail:d.text.slice(0,140),platform:d.platform}); if(isLead(c)){c.next={type:'Text',date:TODAY,time:'',note:`Reply to their ${PFN(d.platform)} message`,by:'System',at:nowAt()};c.followUp=TODAY}return true} if(e.type==='meta_lead'){if(S.customers.some(c=>(c.metaLeads||[]).includes(d.leadgenId)))return false;const c=intakeLead({name:d.name,phone:d.phone,email:d.email,vehicle:d.vehicle,message:d.message,source:PFN(d.platform),type:'Lead ad'},PFN(d.platform)+' lead ad'); (c.metaLeads=c.metaLeads||[]).push(d.leadgenId);c.adSource=[d.campaign,d.ad].filter(Boolean).join(' · ');engAdd(c.id,{at,ch:'social',kind:'social_lead',detail:`Lead form${d.ad?' from ad “'+d.ad+'”':''}`,platform:d.platform});return true} if(e.type==='meta_comment'){const c=S.customers.find(x=>x.social&&Object.values(x.social).some(s=>s&&typeof s==='object'&&(s.psid===d.fromId||s.commentId===d.fromId)))||S.customers.find(x=>d.name&&x.name&&x.name.toLowerCase()===String(d.name).toLowerCase()); const o={at,ch:'social',kind:'comment',detail:d.text,platform:d.platform,postId:d.postId};if(c){engAdd(c.id,o);return true}(S.socialInbox=S.socialInbox||[]).unshift({...o,name:d.name,fromId:d.fromId});S.socialInbox=S.socialInbox.slice(0,300);return true} return false} /* everything a customer has done with the dealership, newest first */ function engItems(c){const out=[];const lbl={visit:'Visited your website',view:'Viewed a vehicle online',calc:'Used the payment calculator',credit:'Started a credit application online',trade:'Asked for a trade-in value',lead:'Sent a website form',contact:'Sent a website form',email_open:'Opened your email',email_click:'Clicked a link in your email',video:'Watched your walkaround video',msg_in:'Sent you a message',comment:'Commented on your post',social_lead:'Filled out a lead ad form'}; (S.engage||[]).filter(e=>e.cid===c.id).forEach(e=>{const v=vehByStock(e.stock);out.push({at:e.at,ch:e.ch,kind:e.kind,w:ENG_W[e.kind]||4,title:(e.platform?PFN(e.platform)+': ':'')+(lbl[e.kind]||e.kind),detail:[v?vname(v)+' ('+v.stock+')':e.stock,e.detail].filter(Boolean).join(' · '),stock:e.stock})}); S.comms.filter(x=>x.customerId===c.id).forEach(x=>{const ch=x.channel==='call'?'phone':x.channel==='email'?'email':x.channel==='social'?'social':'phone';const k=x.dir==='in'?(x.channel==='call'?'call_in':x.channel==='social'?'msg_in':x.channel==='email'?'email_in':'text_in'):(x.channel==='call'&&x.outcome==='Answered'?'call_ok':'out'); if(x.channel==='social'&&x.dir==='in'&&(S.engage||[]).some(e=>e.cid===c.id&&e.kind==='msg_in'&&e.at===x.at))return; out.push({at:x.at,ch,kind:k,w:ENG_W[k]||(x.dir==='in'?12:0),dir:x.dir,title:x.channel==='social'?`${PFN(x.platform)} message ${x.dir==='in'?'received':'sent'}`:x.channel==='call'?`${x.dir==='in'?'Incoming':'Outgoing'} call${x.outcome?' · '+x.outcome:''}`:x.channel==='email'?(x.dir==='in'?'Email received':'Email sent'):(x.dir==='in'?'Text received':'Text sent'),detail:String(x.body||'').slice(0,160)})}); (c.visits||[]).forEach(v=>out.push({at:v.at,ch:'person',kind:'checkin',w:ENG_W.checkin,title:'Checked in at the dealership',detail:''})); S.vehicles.forEach(v=>(v.vnotes||[]).filter(n=>n.kind==='Test drive'&&String(n.text).startsWith(c.name+':')).forEach(n=>out.push({at:n.at,ch:'person',kind:'testdrive',w:ENG_W.testdrive,title:'Test drive',detail:vname(v)}))); (c.deposits||[]).filter(d=>!d.refunded).forEach(d=>out.push({at:d.date,ch:'person',kind:'deposit',w:ENG_W.deposit,title:'Left a deposit',detail:$$(d.amount)+(d.stock?' on '+d.stock:'')})); (S.worksheets||[]).filter(w=>w.customerId===c.id).forEach(w=>out.push({at:w.at||w.date,ch:'deal',kind:'desk',w:ENG_W.desk,title:'Deal desked',detail:vname(veh(w.vehicleId))||''})); (c.notes||[]).filter(n=>n.by==='Video').forEach(n=>{if(!(S.engage||[]).some(e=>e.cid===c.id&&e.kind==='video'&&e.at.slice(0,10)===n.date))out.push({at:n.date,ch:'video',kind:'video',w:ENG_W.video,title:'Watched your walkaround video',detail:n.text.replace(/^\W+/,'')})}); return out.filter(x=>x.at).sort((a,b)=>String(b.at).localeCompare(String(a.at)))} const hoursAgo=at=>{const t=Date.parse(String(at).length<=10?at+'T12:00:00':at);return isNaN(t)?9999:(Date.now()-t)/36e5}; function heat(c,items){if(!c||['Sold','Lost'].includes(c.stage))return null;items=items||engItems(c);let s=0;const parts={}; items.forEach(x=>{if(!x.w)return;const h=hoursAgo(x.at);if(h>24*21)return;const v=x.w*Math.pow(.5,h/72);s+=v;parts[x.ch]=(parts[x.ch]||0)+v}); if(c.stage==='Appointment')s+=8;if(c.priority==='Hot')s+=10;if(c.priority==='Cold')s-=10;const sc=Math.max(0,Math.min(100,Math.round(s))); return{score:sc,label:sc>=60?'Hot':sc>=30?'Warm':'Cold',parts}} const heatPill=h=>h?`${h.label} · ${h.score}`:''; /* when and how this customer actually responds */ function bestTime(c){const ins=S.comms.filter(x=>x.customerId===c.id&&x.dir==='in').map(x=>x.at).concat((S.engage||[]).filter(e=>e.cid===c.id&&['msg_in','view','calc','email_open'].includes(e.kind)).map(e=>e.at)).filter(a=>String(a).length>10); const slot=a=>{const d=new Date(a);const h=d.getHours();return h<12?'Morning':h<17?'Afternoon':'Evening'};const cnt={};ins.forEach(a=>{const k=slot(a);cnt[k]=(cnt[k]||0)+1});const top=Object.entries(cnt).sort((a,b)=>b[1]-a[1])[0]; const outs=S.comms.filter(x=>x.customerId===c.id).sort((a,b)=>a.at.localeCompare(b.at));const rt={text:[],call:[],social:[],email:[]};let calls=0,ans=0; outs.forEach((x,i)=>{if(x.channel==='call'&&x.dir==='out'){calls++;if(x.outcome==='Answered')ans++}if(x.dir!=='out')return;const r=outs.slice(i+1).find(y=>y.dir==='in');if(r){const k=x.channel in rt?x.channel:'text';rt[k].push((Date.parse(r.at)-Date.parse(x.at))/6e4)}}); const med=a=>a.length?a.sort((p,q)=>p-q)[Math.floor(a.length/2)]:null;const tx=med(rt.text),sm=med(rt.social); let ch=c.prefContact||'';if(!ch){ch=sm!=null&&(tx==null||sm=2&&ans/calls>=.5?'Call':c.social&&(c.social.fb||c.social.ig)?'Social':c.phone&&c.smsConsent?'Text':c.phone?'Call':c.email?'Email':'Call'} return{when:top?top[0]:(c.bestTime||''),n:ins.length,channel:ch,textMins:tx,socialMins:sm,callRate:calls?Math.round(ans/calls*100):null,calls}} const OBJ=[['price',/too (high|much|expensive)|best price|lowest|cheaper|out the door|otd|negotiat|discount|come down/i,'Price','Show the value and the payment, not just the price. Offer to go over the out-the-door numbers.'], ['credit',/credit|bankrupt|repo|approved|denied|score|no cosigner|cosign/i,'Credit worries','Reassure them: in-house financing works with most credit situations. Offer a quick pre-qualification.'], ['spouse',/wife|husband|spouse|talk (it )?over|partner|my (mom|dad)|girlfriend|boyfriend/i,'Needs to talk to someone','Invite the other person to come with them, or send the details they can share.'], ['payment',/payment|monthly|weekly|bi-?weekly|how much down|down payment/i,'Payment amount','Lead with an exact payment and down payment that fit their budget.'], ['trade',/trade|owe|payoff|upside/i,'Trade-in','Offer a free trade appraisal. Ask for year, make, miles and payoff.'], ['timing',/not ready|few weeks|next month|just looking|later|tax (return|refund)|payday/i,'Not ready yet','Agree on a date to follow up and hold the car with a small deposit if they love it.'], ['shopping',/another dealer|carmax|carvana|other (place|lot)|found (one|another)|cheaper somewhere/i,'Shopping around','Ask what the other car is and compare honestly: miles, warranty, fees and financing.'], ['distance',/far|drive (out|there)|deliver|out of town|no ride|ride there/i,'Getting to the lot','Offer delivery, a pickup, or a video walkaround and paperwork by text.']]; function objections(c){const msgs=S.comms.filter(x=>x.customerId===c.id&&x.dir==='in'&&hoursAgo(x.at)<24*45).map(x=>x.body||'').join(' \n ');return OBJ.filter(o=>o[1].test(msgs)).map(o=>({k:o[0],label:o[2],tip:o[3]}))} function viewedStocks(c){const m={};(S.engage||[]).filter(e=>e.cid===c.id&&e.stock).forEach(e=>{m[e.stock]=(m[e.stock]||0)+(e.kind==='view'?1:2)});return Object.entries(m).sort((a,b)=>b[1]-a[1]).map(x=>({v:vehByStock(x[0]),n:x[1]})).filter(x=>x.v)} function estPay(price,down){const st=S.settings,ppy=FREQ[st.freq]?.ppy||26,n=+st.term||78,r=(+st.apr||19.9)/100/ppy;const f=Math.max(0,+price*(1+(+st.taxRate||0)/100)+(+st.docFee||0)-(+down||0));return r?f*r/(1-Math.pow(1+r,-n)):f/n} function vehMatches(c){const iv=interestVeh(c);const pq=c.prequal&&c.prequal.at?pqCalc(c):null;const viewed=viewedStocks(c).map(x=>x.v);const avail=S.vehicles.filter(v=>v.status==='Available'); const anchor=iv||viewed[0];const cap=pq?pq.maxPrice:anchor?anchor.price*1.2:null;let l=avail.filter(v=>(!cap||+v.price<=cap)&&(!anchor||v.id!==anchor.id)); if(anchor)l.sort((a,b)=>((a.body===anchor.body)?0:1)-((b.body===anchor.body)?0:1)||((a.make===anchor.make)?0:1)-((b.make===anchor.make)?0:1)||Math.abs(a.price-anchor.price)-Math.abs(b.price-anchor.price));else l.sort((a,b)=>a.price-b.price); const first=[iv&&iv.status==='Available'?iv:null,...viewed.filter(v=>v.status==='Available')].filter(Boolean);const seen=new Set();return [...first,...l].filter(v=>!seen.has(v.id)&&seen.add(v.id)).slice(0,3).map(v=>({v,pay:estPay(v.price,(c.prequal&&c.prequal.down)||v.minDown||0),why:v===iv?'Their vehicle':viewed.includes(v)?'Viewed online':pq?'Fits their pre-qual':'Similar, in budget'}))} const quietNow=()=>{const h=new Date().getHours();return h<8||h>=21}; const firstName=c=>String(c.name||'').trim().split(/\s+/)[0]||'there'; /* the AI coach: rules first (always available), AI rewrite optional */ function nextMoves(c){const items=engItems(c),h=heat(c,items),bt=bestTime(c),ob=objections(c),vm=vehMatches(c);const fn=firstName(c),rep=(me()&&me().name||S.settings.user||'').split(' ')[0],dl=S.settings.dealer||'our dealership';const iv=interestVeh(c);const car=iv?`${iv.year} ${iv.make} ${iv.model}`:(vm[0]?`${vm[0].v.year} ${vm[0].v.make} ${vm[0].v.model}`:'the car'); const canTxt=!canText(c),canCall=!!c.phone&&!c.dnc,canMail=!!c.email&&!c.emailOptOut,soc=c.social&&(c.social.fb&&c.social.fb.psid?'facebook':c.social.ig&&c.social.ig.psid?'instagram':''),out=[]; const lastIn=S.comms.filter(x=>x.customerId===c.id&&x.dir==='in').sort((a,b)=>b.at.localeCompare(a.at))[0],lastOut=S.comms.filter(x=>x.customerId===c.id&&x.dir==='out').sort((a,b)=>b.at.localeCompare(a.at))[0]; const pick=pref=>{const order={Social:['social','text','call','email'],Text:['text','call','social','email'],Call:['call','text','social','email'],Email:['email','text','call','social']}[pref]||['call','text','email','social'];return order.find(k=>k==='text'?canTxt:k==='call'?canCall:k==='email'?canMail:!!soc)||''}; const add=(o)=>{if(!o.ch)return;out.push(o)};const why=[]; if(c.stage==='Sold'){const d=S.deals.filter(x=>x.customerId===c.id).sort((a,b)=>b.date.localeCompare(a.date))[0];const days=d?diff(d.date,TODAY):999; if(days<=30)add({k:'review',title:'Ask for a review and a referral',ch:pick('Text'),why:[`Bought ${days} day${days===1?'':'s'} ago, while the experience is fresh`],msg:`Hi ${fn}, it's ${rep} at ${dl}. How are you liking the ${d?vname(veh(d.vehicleId)):'car'}? If we took good care of you, a quick review would mean a lot. And if a friend or family member needs a car, send them my way!`}); else add({k:'checkin',title:'Check in and look for the next sale',ch:pick('Text'),why:['Past customer: stay in touch for service, referrals and their next car'],msg:`Hi ${fn}, ${rep} from ${dl} checking in. How is the car treating you? If anyone you know is shopping, I'd love to help them.`}); return{items,h,bt,ob,vm,moves:out}} if(c.stage==='Lost')return{items,h,bt,ob,vm,moves:[{k:'win',title:'Try to win them back',ch:pick('Text'),why:['Closed as lost. A friendly check-in can reopen the deal'],msg:`Hi ${fn}, it's ${rep} at ${dl}. Are you still looking for a car? We just got some new ones in and I'd be happy to help.`}].filter(o=>o.ch)} const hot=items.filter(x=>hoursAgo(x.at)<3&&['view','calc','credit','trade','video','msg_in','text_in','call_in','email_click'].includes(x.kind)); if(lastIn&&(!lastOut||lastIn.at>lastOut.at)){const ch0=lastIn.channel==='social'?'social':lastIn.channel==='email'?'email':lastIn.channel==='call'?'call':'text';const ch=ch0==='social'&&soc?'social':ch0==='text'&&canTxt?'text':ch0==='email'&&canMail?'email':pick(bt.channel); add({k:'reply',title:`Reply to their ${lastIn.channel==='social'?PFN(lastIn.platform)+' message':lastIn.channel==='call'?'call':lastIn.channel}`,ch,urgent:true,why:[`They wrote ${hoursAgo(lastIn.at)<1?'less than an hour':Math.round(hoursAgo(lastIn.at))<48?Math.round(hoursAgo(lastIn.at))+' hours':Math.round(hoursAgo(lastIn.at)/24)+' days'} ago and haven't heard back`,lastIn.body?`“${String(lastIn.body).slice(0,90)}”`:''].filter(Boolean),msg:ob.length?`Hi ${fn}, thanks for your message! ${ob[0].k==='credit'?"We work with all kinds of credit, and our in-house financing gets most people approved. ":ob[0].k==='price'?`I can go over the full out-the-door numbers on the ${car} with you. `:ob[0].k==='payment'?`On the ${car} payments start around ${$0(vm[0]?vm[0].pay:estPay(iv?iv.price:0,0))} ${FREQ[S.settings.freq]?.label.toLowerCase()||''}. `:''}When's a good time to come by?`:`Hi ${fn}, thanks for reaching out! I'd be glad to help with the ${car}. When works for you to come take a look?`})} if(hot.length){const top=hot[0];const v=vehByStock(top.stock)||iv;why.push(`${top.title}${top.detail?' ('+top.detail+')':''} ${Math.max(1,Math.round(hoursAgo(top.at)*60))<60?Math.max(1,Math.round(hoursAgo(top.at)*60))+' min':Math.round(hoursAgo(top.at))+' h'} ago`); const views=items.filter(x=>x.kind==='view'&&hoursAgo(x.at)<48&&(!v||x.stock===v.stock)).length;if(views>1)why.push(`Viewed ${v?'it':'cars'} ${views} times in 2 days`); add({k:'hot',title:canCall&&bt.channel!=='Text'?'Call now while they’re looking':'Reach out now while they’re looking',ch:canCall&&bt.channel!=='Text'?'call':pick(bt.channel),urgent:true,why:[...why],msg:`Hi ${fn}, it's ${rep} at ${dl}. I saw you were checking out the ${v?v.year+' '+v.make+' '+v.model:car}. It's still available. Want me to hold it for a test drive today?`})} if(c.next&&/Appointment|Test drive|Visit/.test(c.next.type)&&c.next.date>=TODAY&&c.next.date<=addDays(TODAY,1)&&!(c.notes||[]).some(n=>n.date===TODAY&&/confirm/i.test(n.text)))add({k:'confirm',title:`Confirm ${c.next.date===TODAY?'today’s':'tomorrow’s'} appointment`,ch:pick('Text'),why:['Confirmed appointments show up far more often'],msg:`Hi ${fn}, it's ${rep} at ${dl}. Just confirming ${c.next.date===TODAY?'today':'tomorrow'}${c.next.time?' at '+nxTime(c.next.time):''}. The ${car} will be ready for you. Reply C to confirm!`}); if(c.sub==='Missed appt.')add({k:'resched',title:'Reschedule the missed appointment',ch:pick('Text'),why:['Missed the appointment. A no-pressure text gets most people back'],msg:`Hi ${fn}, sorry we missed you! No worries at all. Would later today or tomorrow work better to see the ${car}?`}); ob.forEach(o=>add({k:'obj_'+o.k,title:`Handle the “${o.label.toLowerCase()}” concern`,ch:pick(bt.channel),why:[o.tip],msg:{price:`Hi ${fn}, I put together the out-the-door numbers on the ${car} so there are no surprises. Can I send them over or go through them on a quick call?`,credit:`Hi ${fn}, good news: our in-house financing works with most credit situations, including past repos or bankruptcy. A 2-minute pre-qualification shows your options with no pressure. Want the link?`,spouse:`Hi ${fn}, totally understand. Bring them along! I can set aside time for both of you, or send photos and numbers you can share tonight.`,payment:`Hi ${fn}, on the ${car} you'd be around ${$0(vm[0]?vm[0].pay:0)} ${FREQ[S.settings.freq]?.label.toLowerCase()||''} with ${$0((c.prequal&&c.prequal.down)||(vm[0]&&vm[0].v.minDown)||1000)} down. Want me to work numbers with a different down payment?`,trade:`Hi ${fn}, I can get you a free trade value today. Just send the year, make, miles and a couple of photos, plus your payoff if you have one.`,timing:`Hi ${fn}, no rush at all. When do you think you'll be ready? I'll check back then, and I can hold the ${car} with a small refundable deposit if you love it.`,shopping:`Hi ${fn}, smart to compare! Send me the other car's link and I'll give you an honest side-by-side: miles, warranty, fees and payment.`,distance:`Hi ${fn}, we can make this easy. I can send a video walkaround and do most of the paperwork by text, and we can talk about delivery.`}[o.k]})); const lastTouch=[lastIn&&lastIn.at,lastOut&&lastOut.at].filter(Boolean).sort().pop();const quiet=lastTouch?hoursAgo(lastTouch)/24:diff(c.created||TODAY,TODAY); if(!out.length&&quiet>=7&&(!h||h.score<30))add({k:'breakup',title:'Send a last-chance check-in',ch:pick(bt.channel),why:[`No contact for ${Math.round(quiet)} days and engagement is cold`,'A short “should I close your file?” message gets many replies'],msg:`Hi ${fn}, it's ${rep} at ${dl}. I don't want to bug you. Are you still shopping, or should I close your file for now?`}); if(quiet>=2&&vm.length)add({k:'match',title:'Send vehicles that fit them',ch:pick(bt.channel),why:[`${Math.round(quiet)} day${Math.round(quiet)===1?'':'s'} since the last contact`,vm.map(x=>`${x.v.stock} ${x.v.year} ${x.v.model} · about ${$0(x.pay)} ${FREQ[S.settings.freq]?.label.toLowerCase()||''}`).join('; ')],msg:`Hi ${fn}, ${rep} at ${dl}. A few options I think you'd like: ${vm.map(x=>`${x.v.year} ${x.v.make} ${x.v.model} (about ${$0(x.pay)} ${FREQ[S.settings.freq]?.label.toLowerCase()||''})`).join(', ')}. Want to come see any of them?`}); if(!(c.prequal&&c.prequal.at)&&isLead(c))add({k:'prequal',title:'Get them pre-qualified',ch:pick(bt.channel),why:['Knowing their budget lets you show cars they can actually buy'],msg:`Hi ${fn}, want to see what you qualify for before you come in? It takes 2 minutes and won't hurt your credit. I can text you the link.`}); if(!(c.next&&/Appointment|Test drive|Visit/.test(c.next.type)))add({k:'appt',title:'Set an appointment',ch:pick(bt.channel),why:['No appointment on the calendar yet'],msg:`Hi ${fn}, when would be a good time to come see the ${car}? I have openings ${new Date().getHours()<15?'this afternoon':'tomorrow'}.`}); const risk=quiet>=4&&lastOut&&(!lastIn||lastOut.at>lastIn.at)?`No reply in ${Math.round(quiet)} days${ob.some(o=>o.k==='shopping')?' and they mentioned shopping elsewhere':''}. Change the channel or the offer.`:ob.some(o=>o.k==='shopping')?'They mentioned another dealer. Respond with an honest comparison.':''; const seenK=new Set();return{items,h,bt,ob,vm,risk,moves:out.filter(o=>!seenK.has(o.k)&&seenK.add(o.k)).slice(0,4)}} const CHN={call:'Call',text:'Text',email:'Email',social:'Message on social'}; function aiCard(c){if(c.aiSnooze&&hoursAgo(c.aiSnooze)<4)return `
AI coach snoozed until ${ftime(new Date(Date.parse(c.aiSnooze)+4*36e5).toISOString())}. Show now
`; const R=nextMoves(c);const i=Math.min(+(ui.aiAlt||0),Math.max(0,R.moves.length-1));const m=R.moves[i];const draft=(ui.aiDraft&&ui.aiDraft.cid===c.id&&ui.aiDraft.k===(m&&m.k))?ui.aiDraft.text:m&&m.msg; return `
AI next move${heatPill(R.h)}${R.bt.when?`Best time: ${esc(R.bt.when)} · by ${esc(R.bt.channel.toLowerCase())}`:`Best channel: ${esc(R.bt.channel.toLowerCase())}`}
${m?`

${esc(m.title)}

    ${m.why.map(w=>`
  • ${esc(w)}
  • `).join('')}
${aiAny()?``:''}${R.moves.length>1?``:''}
${quietNow()&&m.ch!=='call'?'
It’s outside 8 AM–9 PM. Texts are best sent in the morning.
':''}` :'
Nothing urgent. Keep the next step on the calendar.
'} ${R.risk?`
${esc(R.risk)}
`:''} ${R.ob.length||R.vm.length?`
${R.ob.length?`
Concerns heard${R.ob.map(o=>`${esc(o.label)}`).join(' ')}
`:''}${R.vm.length?``:''}
`:''}
`} function aiLog(c,k,action,ch){(c.aiLog=c.aiLog||[]).unshift({at:nowAt(),k,action,ch:ch||'',by:S.settings.user});c.aiLog=c.aiLog.slice(0,60)} function aiUse(cid,k,ch){const c=cust(cid);const R=nextMoves(c);const m=R.moves.find(x=>x.k===k);const text=($('#aidraft')&&$('#aidraft').value)||(m&&m.msg)||'';aiLog(c,m?m.title:k,'used',ch);save();ui.aiDraft=null; if(ch==='call')return callModal(cid);if(ch==='text')return textModal(cid,null,null,text);if(ch==='email'){emailModal(cid);setTimeout(()=>{const t=document.querySelector('#modal textarea');if(t&&!t.value)t.value=text},50);return}if(ch==='social')return socialReply(cid,text)} function aiDismiss(cid,k){const c=cust(cid);aiLog(c,k,'dismissed');c.aiSnooze=nowAt();ui.aiAlt=0;save();render()} async function aiRewrite(cid,k){const c=cust(cid);const R=nextMoves(c);const m=R.moves.find(x=>x.k===k);if(!m)return;const b=$('#airw');if(b){b.disabled=true;b.textContent='✦ Writing…'} const recent=S.comms.filter(x=>x.customerId===c.id).sort((a,b)=>b.at.localeCompare(a.at)).slice(0,6).reverse().map(x=>`${x.dir==='in'?'Customer':'Dealer'} (${x.channel}): ${String(x.body||x.outcome||'').slice(0,200)}`).join('\n'); try{const t=await ai(`You help a used-car salesperson write one short ${m.ch==='call'?'set of call talking points':m.ch==='email'?'email':'text message'} to a customer. Goal: ${m.title}. Why now: ${m.why.join('; ')}. Customer first name: ${firstName(c)}. Stage: ${c.stage}. Concerns heard: ${R.ob.map(o=>o.label).join(', ')||'none'}. Vehicles to mention: ${R.vm.map(x=>`${x.v.year} ${x.v.make} ${x.v.model} about ${$0(x.pay)} per ${FREQ[S.settings.freq]?.label.toLowerCase()||'payment'}`).join('; ')||'none'}. Recent conversation:\n${recent||'none'} Dealer: ${S.settings.dealer}. Salesperson: ${(me()&&me().name)||S.settings.user}. Rules: friendly and plain, under ${m.ch==='email'?110:55} words, one clear question at the end, no emojis, no pressure tactics, don't promise approval, rates or prices that aren't given above, and don't mention any information about the customer that they didn't share with the dealership. Reply with the message only.`,{text:true,tier:'quick',nocache:true}); ui.aiDraft={cid,k,text:t.trim()};aiLog(c,m.title,'rewritten');save();render()}catch(e){toast(aiErrMsg(e));if(b){b.disabled=false;b.textContent='✦ Rewrite with AI'}}} async function socialReply(cid,text){const c=cust(cid);const s=c.social||{};const pf=s.fb&&s.fb.psid?'facebook':s.ig&&s.ig.psid?'instagram':'';const link=pf?s[pf==='instagram'?'ig':'fb']:null; if(!link)return toast('This customer hasn’t messaged your Facebook or Instagram page yet'); openModal(mh(`Reply on ${PFN(pf)} · ${esc(c.name)}`)+`

Meta only allows page replies within 24 hours of the customer’s last message.

`); $('#srf').onsubmit=async e=>{e.preventDefault();const t=e.target.t.value.trim();const r=await srvPost('/api/meta/send',{psid:link.psid,platform:pf,text:t});if(!r.ok)return toast(r.body&&r.body.error||'Facebook / Instagram replies work once DealerPen runs on your server with Meta connected'); logComm({customerId:cid,channel:'social',platform:pf,dir:'out',body:t,psid:link.psid});save();closeModal();render();toast('Sent on '+PFN(pf))}} /* Engagement tab */ function engTab(c){const R=nextMoves(c),items=R.items;const f=ui.engF||'all';const list=items.filter(x=>f==='all'||x.ch===f);const since=items.filter(x=>hoursAgo(x.at)<24*30);const cnt=k=>since.filter(x=>x.ch===k).length; const s=c.social||{};const handles=s.handles||{};const vw=viewedStocks(c); return `

Engagement score

${heatPill(R.h)||'Not scored for '+esc(c.stage.toLowerCase())+' customers'}
${R.h?`
${Object.keys(ENG_CH).map(k=>`
${ENG_CH[k]}${cnt(k)}
`).join('')}

Last 30 days. Recent actions count most; the score fades if they go quiet.

`:''}

How to reach them

Best time
${esc(R.bt.when||'Not enough data yet')}
Best channel
${esc(R.bt.channel)}
Text reply time
${R.bt.textMins!=null?(R.bt.textMins<60?Math.round(R.bt.textMins)+' min':Math.round(R.bt.textMins/60)+' h'):'—'}
Calls answered
${R.bt.callRate!=null?R.bt.callRate+'% of '+R.bt.calls:'—'}
OK to text
${c.smsConsent&&!c.optOut?'Yes':'No'}
Emails
${c.emailOptOut?'Unsubscribed':c.email?'Yes':'No email'}

Social profiles

${['fb','ig'].filter(k=>s[k]&&s[k].psid).map(k=>`
${k==='fb'?'Facebook':'Instagram'} MessengerConnected through your page${s[k].username?' · @'+esc(s[k].username):''}
`).join('')}
${[['fb','Facebook profile link'],['ig','Instagram handle'],['tt','TikTok handle']].map(([k,l])=>``).join('')}

Only save handles the customer shares with you. DealerPen never pulls data from personal profiles.

Cars they looked at online

${vw.length?`${vw.slice(0,6).map(x=>``).join('')}
${esc(vname(x.v))}
${esc(x.v.stock)}
${$0(x.v.price)}${x.n} view${x.n===1?'':'s'}${statusPill(x.v.status)}
`:`
${c.webVid?'No vehicle views yet':'Website visits link to a customer once they fill out a form on your site'}
`}

Engagement timeline (${items.length})

${[['all','All'],...Object.entries(ENG_CH)].map(([k,l])=>``).join('')}
${list.slice(0,150).map(x=>`
${esc(x.title)}${ENG_CH[x.ch]||''} · ${String(x.at).length>10?ftime(x.at):fdate(x.at)}
${x.detail?`
${esc(x.detail)}
`:''}
${x.w?`+${x.w}`:''}
`).join('')||'
No engagement yet
'}
${(c.aiLog||[]).length?`

AI suggestions log

${c.aiLog.slice(0,20).map(l=>``).join('')}
${ftime(l.at)}${esc(l.k)}${l.action==='used'?'Used':l.action==='rewritten'?'Rewritten':'Not now'}${l.ch?' '+esc(CHN[l.ch]||l.ch):''}${esc(l.by||'')}
`:''}

Engagement comes only from this customer’s activity with your dealership: your website, your emails and videos, your Facebook and Instagram pages, calls, texts and visits. It is never used for credit decisions or pricing.

`} function engHandle(cid,k,v){const c=cust(cid);c.social=c.social||{};if(k==='consent')c.social.consent=!!v;else{c.social.handles=c.social.handles||{};c.social.handles[k]=String(v).trim().slice(0,200)}save()} /* wire into the customer page */ {const _ct2=custTab;custTab=function(c,deals,loans){if(ui.cTab==='engage')return engTab(c);const h=_ct2.apply(this,arguments);return ui.cTab==='lead'||!ui.cTab?aiCard(c)+h:h}} {const _mn2=myNotifs;myNotifs=function(){const out=_mn2();const u=me();if(!u)return out;const mgr=['Owner','Sales Manager','Desking Manager'].includes(u.role); S.customers.filter(c=>isLead(c)&&(mgr||c.ownerId===u.id)).forEach(c=>{const h=heat(c);if(!h||h.score<60)return;const lastOut=S.comms.filter(x=>x.customerId===c.id&&x.dir==='out').map(x=>x.at).sort().pop();if(lastOut&&hoursAgo(lastOut)<24)return; out.push({id:'hot_'+c.id+'_'+TODAY,kind:mgr&&c.ownerId!==u.id?'Hot lead not worked':'Hot lead: reach out',text:`${c.name} · score ${h.score}${c.ownerId&&mgr?' · '+uname(c.ownerId):''}`,go:`openCustomer('${c.id}')`,at:nowAt()})});return out}} const ENGCSS=`.heat{display:inline-flex;align-items:center;border-radius:999px;padding:2px 9px;font-size:12px;font-weight:600;white-space:nowrap}.h-hot{background:#fdecea;color:#b42318}.h-warm{background:#fef4e2;color:#a15c07}.h-cold{background:#eef2f7;color:#475467} .ai-card{margin-bottom:14px;border-color:#dbe5fb;background:linear-gradient(#fbfcff,#fff)}.ai-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px}.ai-top .sp{flex:1}.ai-badge{background:#eef3fd;color:var(--brand);border-radius:6px;padding:2px 8px;font-size:12px;font-weight:600} .ai-move h3{margin:0 0 4px;font-size:16px}.ai-move.urgent h3:before{content:'';display:inline-block;width:8px;height:8px;border-radius:50%;background:#e04f1a;margin-right:8px;vertical-align:2px}.ai-move ul{margin:0 0 10px;padding-left:18px;color:var(--ink2);font-size:13.5px} .ai-draft{display:flex;flex-direction:column;gap:4px;font-size:12.5px;color:var(--muted)}.ai-draft textarea{border:1px solid #d5d9e0;border-radius:8px;padding:8px 10px;font-size:13.5px;line-height:1.5;resize:vertical} .ai-acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px}.ai-acts .sp{flex:1} .ai-risk{margin-top:10px;background:#fff6ed;border:1px solid #fddcab;color:#93370d;border-radius:8px;padding:8px 10px;font-size:13px} .ai-foot{display:flex;flex-wrap:wrap;gap:14px;margin-top:12px;padding-top:10px;border-top:1px solid var(--line)}.ai-foot>div{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.ai-veh{background:#f6f7f9;border:1px solid var(--line);border-radius:6px;padding:2px 8px;font-size:12.5px;font-weight:500;color:var(--ink2);text-decoration:none}.ai-veh:hover{border-color:var(--brand);color:var(--brand)} .ai-snz{font-size:13px;color:var(--muted);margin-bottom:12px} .eng-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px}.eng-meter{height:8px;background:#eef0f4;border-radius:4px;overflow:hidden;margin:4px 0 12px}.eng-meter i{display:block;height:100%;background:linear-gradient(90deg,#9db4f5,#e04f1a);border-radius:4px} .eng-ch{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}.eng-ch>div{background:#f7f8fa;border-radius:8px;padding:6px 8px}.eng-ch span{display:block;font-size:11.5px;color:var(--muted)}.eng-ch b{font-size:15px;font-weight:600} .eng-soc{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 10px;border:1px solid var(--line);border-radius:8px;margin-bottom:6px}.eng-soc .hint{flex:1} .eng-w{font-size:11.5px;color:#a15c07;background:#fef4e2;border-radius:6px;padding:1px 6px;align-self:flex-start} .eng-web .cw-ico{background:#eef3fd;color:#2f5fd0}.eng-email .cw-ico{background:#f4f1ff;color:#4b2fb3}.eng-video .cw-ico{background:#fdf2fa;color:#a11673}.eng-social .cw-ico{background:#eaf2ff;color:#1b4fbf}.eng-phone .cw-ico{background:#e7f6ee;color:#067647}.eng-person .cw-ico{background:#fef4e2;color:#a15c07}.eng-deal .cw-ico{background:#f0f2f5;color:#475467}`; document.head.insertAdjacentHTML('beforeend',''); {const _sf=srvFeatures;srvFeatures=async function(){const f=await _sf.apply(this,arguments);try{if(f&&f.ok&&f.tracking&&f.tracking.url){S.site=S.site||{};if(S.site.trackUrl!==f.tracking.url){S.site.trackUrl=f.tracking.url;save()}}}catch(e){}return f}} /* ---- affiliate & referral programs (earn on every dealer sign-up) ---- */ const AFF=[ ['vapi','Vapi','AI calling (AI BDC)','Affiliate program. A user on Vapi\'s support forum reports 15%; confirm the rate in the portal.','https://affiliates.vapi.ai/','https://vapi.ai/'], ['retell','Retell AI','AI calling (AI BDC)','Affiliate: 15% of referred revenue for 12 months. Agency Partner Program also available.','https://retellai.com/affiliate','https://www.retellai.com/'], ['synthflow','Synthflow','AI calling (AI BDC)','Affiliate: 20% of each paid referral for 12 months. Separate white-label reseller option.','https://market.partnerstack.com/page/synthflowai','https://synthflow.ai/'], ['elevenlabs','ElevenLabs','AI voices / agents','Creator affiliate: 22% of payments in the referral\'s first year.','https://elevenlabs.io/affiliates','https://elevenlabs.io/'], ['bland','Bland AI','AI calling (AI BDC)','Reseller program with revenue share. Terms set with their sales team.','https://bland.ai/partners','https://bland.ai/'], ['claude','Claude (Anthropic)','AI inside DealerPen','No per-sign-up affiliate program. Referral fees only on Claude for Enterprise deals.','https://www.anthropic.com/referral','https://claude.ai/']]; const affCfg=()=>{S.settings.aff=S.settings.aff||{};return S.settings.aff}; function affLink(k){const a=AFF.find(x=>x[0]===k);const c=affCfg()[k]||{};return (c.link&&/^https:\/\//.test(c.link))?c.link:a?a[5]:'#'} function affOpen(k){const href=affLink(k);S.affClicks=S.affClicks||[];S.affClicks.push({k,at:nowAt(),by:S.settings.user,ref:!!(affCfg()[k]||{}).link});save();window.open(href,'_blank','noopener')} function affSet(k,f,v){const c=affCfg();c[k]=c[k]||{};c[k][f]=v.trim?v.trim():v;if(f==='link'&&v&&!/^https:\/\//.test(v.trim()))toast('Referral links must start with https://');save();render()} function affCard(){const c=affCfg();const clicks=S.affClicks||[];const done=AFF.filter(a=>(c[a[0]]||{}).link).length; return `

💸 Affiliate & referral programs${done} of ${AFF.length} links added

Join each program (it needs your business name, tax form and payout details), then paste your personal referral link here. Every “Create account” button in DealerPen then uses your link, so you get the commission when a dealer signs up. Only the owner sees this.
${AFF.map(a=>{const x=c[a[0]]||{};const n=clicks.filter(k=>k.k===a[0]).length;return ``}).join('')}
ProviderWhat it paysYour statusYour referral linkDealer clicks
${esc(a[1])}
${esc(a[2])}
${esc(a[3])} ${n} Join program ↗

Commissions only count when the dealer opens their own account through your link. For services DealerPen runs on your accounts (texting, calls, AI), you earn by charging dealers more than your cost instead. Check each program's rules before you promote it, since some ban paid ads on their brand name.

`} /* ---- trade appraisals ---- */ function appraisalModal(id){S.appraisals=S.appraisals||[];const a=id?S.appraisals.find(x=>x.id===id):null; if(!a){const n={id:uid(),created:nowAt(),by:S.settings.user,vin:'',year:'',make:'',model:'',trim:'',color:'',miles:'',condition:'Average',customerId:'',recon:0,offer:0,status:'Open',bookouts:[],notes:''};S.appraisals.push(n);save();return appraisalModal(n.id)} const sm=bookSummary(a);const ws=Object.values(sm).map(s=>s.whole).filter(Boolean);const avgW=ws.length?ws.reduce((x,y)=>x+y,0)/ws.length:0;const tr=Object.entries(sm).map(([b,s])=>bkVal(s.e,b==='bb'?'ta':b==='jdp'?'ta':'tig')).filter(Boolean);const avgT=tr.length?tr.reduce((x,y)=>x+y,0)/tr.length:0; openModal(mh(`Trade appraisal${a.year?` · ${esc(a.year+' '+a.make+' '+a.model)}`:''}`)+`
Book values
${a.vin||a.make?bookCompareHTML(a,{target:'ap:'+a.id,noSummary:true}):'
Enter the VIN and save to book this vehicle.
'}
${ws.length?`
Avg wholesale${$0(avgW)}
${avgT?`
Avg trade-in${$0(avgT)}
`:''}
Suggested ACV (avg wholesale − recon − $${bkCfg().pack||500} pack)${$0(Math.max(0,avgW-(+a.recon||0)-(bkCfg().pack||500)))}
`:''}
${a.status!=='Added to inventory'?``:''}
`,true); const f=$('#apf');$('#apdec').onclick=()=>{const r=decodeVin(f.vin.value);if(!r.ok)return toast(r.msg);f.vin.value=r.vin;if(r.year)f.year.value=r.year;if(r.make)f.make.value=r.make;toast(r.valid?'VIN decoded':'Check digit mismatch. Verify the VIN')}; const grab=()=>{const x=fd(f);Object.assign(a,{vin:x.vin.toUpperCase(),miles:+x.miles||0,customerId:x.customerId,year:+x.year||'',make:x.make,model:x.model,trim:x.trim,color:x.color,condition:x.condition,recon:+x.recon||0,payoff:+x.payoff||0,notes:x.notes,offer:+x.offer||0,status:x.status});save()}; f.onsubmit=e=>{e.preventDefault();grab();appraisalModal(a.id);toast('Appraisal saved')}; $('#apdel').onclick=()=>confirmBox('Delete this appraisal?',()=>{S.appraisals=S.appraisals.filter(x=>x.id!==a.id);save();render()}); if($('#apinv'))$('#apinv').onclick=()=>{grab();if(!a.make||!a.offer)return toast('Enter make/model and your offer (ACV) first');const nv={id:uid(),stock:'S'+(++S.seq.stock),vin:a.vin,year:a.year,make:a.make,model:a.model,trim:a.trim,color:a.color,miles:a.miles,cost:a.offer,price:Math.round((avgW||a.offer)*1.25/100)*100,recon:[],status:'Available',acquired:TODAY,lot:'Main Lot',published:false,notes:'From trade appraisal'+(a.notes?': '+a.notes:''),bookouts:JSON.parse(JSON.stringify(a.bookouts||[])),titleStatus:a.payoff?'Waiting on lender payoff':'Waiting on seller / auction'}; S.vehicles.push(nv);txn(TODAY,'Vehicle Purchase',a.offer,nv.stock,'Purchased '+vname(nv)+' (appraisal)');a.status='Added to inventory';a.vehicleId=nv.id;sendToRecon(nv,true);save();closeModal();render();vehModal(nv.id);toast('Added to inventory and sent to recon')}} function appraisalsView(){const as=(S.appraisals||[]).slice().sort((a,b)=>b.created.localeCompare(a.created));return `
Appraise trades and purchases against Black Book, J.D. Power and KBB, then add winners to inventory with their bookouts attached.
${as.map(a=>``).join('')||''}
DateVehicleCustomerMilesBooksOfferStatus
${ftime(a.created)}${esc([a.year,a.make,a.model,a.trim].filter(Boolean).join(' ')||'(no vehicle yet)')}
${esc(a.vin)}
${esc(cust(a.customerId)?.name||'—')}${a.miles?(+a.miles).toLocaleString():'—'}${Object.keys(bookSummary(a)).map(b=>`${BOOKS[b].n.split(' ')[0]}`).join(' ')||'—'}${a.offer?$0(a.offer):'—'}${esc(a.status)}
No appraisals yet
`} function bookoutSettings(){const c=bkCfg();return `

📘 Bookout (Black Book · J.D. Power · KBB)

${Object.entries(BOOKS).map(([k,B])=>``).join('')}

Values are typed in from your own subscriptions. Automatic lookups by VIN need each provider's data license, connected through the DealerPen server.

`} /* ================= E-Sign Auto (live, via DealerPen server) ================= */ const mountedServer = location.pathname === '/dms/' ? location.origin + '/dms' : ''; const ESA=()=>{ const settings=Object.assign({server:'',token:'',mode:'manual'},S.settings.esa||{}); return {...settings,server:workspaceMount ? location.origin + workspaceMount : settings.server||mountedServer}; }; const esaURL=p=>(ESA().server||'').replace(/\/$/,'')+'/api/esign'+p; async function esaFetch(p,opt={}){const h={'Content-Type':'application/json'};if(ESA().token)h['X-LotLedger-Token']=ESA().token; const r=await fetch(esaURL(p),{...opt,headers:{...h,...(opt.headers||{})}});const ct=r.headers.get('content-type')||'';const body=ct.includes('json')?await r.json().catch(()=>({})):await r.blob();return{status:r.status,ok:r.ok,body}} async function esaHealth(force){if(!force&&ui.esaHealth&&Date.now()-ui.esaHealth.at<60000)return ui.esaHealth;let h={ok:false,at:Date.now()};try{const r=await esaFetch('/health');if(r.ok&&r.body&&r.body.ok)h={...r.body,ok:true,at:Date.now()}}catch(e){}ui.esaHealth=h;return h} function loadScript(src){return new Promise((res,rej)=>{if(document.querySelector(`script[src="${src}"]`))return res();const s=document.createElement('script');s.src=src;s.onload=res;s.onerror=()=>rej(new Error('Could not load '+src));document.head.appendChild(s)})} async function pdfLibs(){await loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js');await loadScript('https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js');if(!window.html2canvas||!window.jspdf)throw new Error('PDF tools did not load')} // Render envelope forms to a letter-size PDF and work out where each signature/date line sits. async function buildPacketPDF(env,progress){await pdfLibs();const {x,forms}=envForms(env);if(!forms.length)throw new Error('No documents in this packet'); const host=document.createElement('div');host.style.cssText='position:fixed;left:-10000px;top:0;width:8.5in;background:#fff;z-index:-1'; host.innerHTML=`
${await inlineImgs(forms.map(f=>fpage(f,x)).join(''))}
`;document.body.appendChild(host); try{await document.fonts?.ready;await Promise.all([...host.querySelectorAll('img')].map(i=>i.complete?0:new Promise(r=>{i.onload=i.onerror=r}))); const pages=[...host.querySelectorAll('.page')];if(pages.length>20)throw new Error(`This packet is ${pages.length} pages. E-Sign Auto accepts up to 20 per request. Remove some forms or split into two packets.`); const {jsPDF}=window.jspdf;const pdf=new jsPDF({unit:'pt',format:'letter',compress:true});const W=612,H=792;const fields=[]; for(let i=0;iH){h=H;w=H*cv.width/cv.height}const x0=(W-w)/2;if(i)pdf.addPage('letter');pdf.addImage(img,'JPEG',x0,0,w,h); const fx=(r)=>({x:+((x0+(r.left-pr.left)/pr.width*w)/W).toFixed(4),y:+(((r.top-pr.top)/pr.height*h)/H).toFixed(4),w:+((r.width/pr.width*w)/W).toFixed(4),h:+((r.height/pr.height*h)/H).toFixed(4)}); pg.querySelectorAll('.fsigbox').forEach(sb=>{const lab=sb.querySelector('.fsigl b')?.textContent||'';const role=sigRole(lab);const si=env.signers.findIndex(s=>s.role===role);if(si<0)return; const line=sb.querySelector('.fl').getBoundingClientRect();fields.push({page:i+1,...fx(line),type:'signature',signerIndex:si,label:`${env.signers[si].label} signature – ${lab}`.slice(0,120)}); const dt=sb.querySelector('.fsigl span');if(dt){const r=dt.getBoundingClientRect();fields.push({page:i+1,...fx({left:r.left+30,top:r.top-4,width:Math.max(60,r.width-24),height:r.height+8}),type:'date',signerIndex:si,label:`${env.signers[si].label} date`})}})} // every signer needs at least one signature field env.signers.forEach((s,si)=>{if(!fields.some(f=>f.type==='signature'&&f.signerIndex===si))fields.push({page:pages.length,x:0.1+0.3*(si%3),y:0.9,w:0.25,h:0.04,type:'signature',signerIndex:si,label:`${s.label} signature (added – no signature line found)`,added:true})}); const blob=pdf.output('blob');if(blob.size>10*1024*1024)throw new Error(`This packet PDF is ${(blob.size/1048576).toFixed(1)} MB. E-Sign Auto accepts up to 10 MB. Remove some forms or uploaded-form images.`); return{blob,pages:pages.length,fields:fields.slice(0,300)}}finally{host.remove()}} const b64=blob=>new Promise(r=>{const fr=new FileReader();fr.onload=()=>r(String(fr.result).split(',')[1]);fr.readAsDataURL(blob)}); async function dlPacketPDF(envId){const env=S.envelopes.find(x=>x.id===envId);toast('Building PDF…');try{const p=await buildPacketPDF(env);const d=S.deals.find(x=>x.id===env.dealId);if(DL){await DL.save({filename:`deal-${d.no}-packet.pdf`,data:p.blob});toast('PDF saved')}else toast('Downloads aren\'t available here')}catch(e){if(e&&e.code!=='declined')toast(e.message||'PDF failed')}} function esaStep(env,html,foot){openModal(mh(`E-Sign Auto · deal #${S.deals.find(x=>x.id===env.dealId).no}`)+`
${html}
${foot||''}
`,true)} async function esaLive(envId){const env=S.envelopes.find(x=>x.id===envId);const d=S.deals.find(x=>x.id===env.dealId),c=cust(d.customerId); esaStep(env,`
Checking the DealerPen server…
`);const h=await esaHealth(true); if(!h.ok){esaStep(env,`
DealerPen can't reach its server, so E-Sign Auto isn't connected from this copy of DealerPen. Live sending works when DealerPen is opened from your DealerPen server (Settings → E-Sign Auto). You can still send manually or sign in store.
`,``);return} if(!h.keyConfigured){esaStep(env,`
The DealerPen server is running but has no E-Sign Auto developer key set (ESIGN_DEVELOPER_KEY).
`,``);return} const pr=t=>{const e=$('#esap');if(e)e.textContent=t}; try{let doc; if(!env.esaId){pr('Building the PDF packet…');const pk=await buildPacketPDF(env,pr);env.esaFields=pk.fields;env.esaPages=pk.pages; pr(`Uploading ${pk.pages} pages to E-Sign Auto…`);const mode=ESA().mode==='auto'?'auto':'manual'; const r=await esaFetch('/documents',{method:'POST',body:JSON.stringify({dealId:d.id,envelopeId:env.id,title:`Deal #${d.no} – ${c?.name||''} – ${vname(veh(d.vehicleId))}`.slice(0,200),mode,pdfBase64:await b64(pk.blob)})}); if(r.status!==201)throw new Error(r.body?.error||`Upload failed (${r.status})`);doc=r.body;env.esaId=doc.id;env.provider='esignauto';env.esaAuto=doc.autoPrep||null;env.events.push({at:nowAt(),by:S.settings.user,text:`Uploaded ${doc.pages||pk.pages}-page packet to E-Sign Auto (document ${doc.id})`});save()} await esaReview(env.id)}catch(e){esaStep(env,`
${esc(e.message||'Something went wrong')}
`,``)}} async function esaReview(envId){const env=S.envelopes.find(x=>x.id===envId);const ap=env.esaAuto; if(!env.esaFields)env.esaFields=[];const useAI=env.esaUseAI&&ap&&ap.fields&&ap.fields.length; const fields=useAI?ap.fields.map(f=>({...f,signerIndex:Math.max(0,env.signers.findIndex(s=>sigRole(f.role||f.label||'')===s.role))})):env.esaFields; const per=env.signers.map((s,i)=>[s,fields.filter(f=>f.signerIndex===i)]);let stmt=''; try{const r=await esaFetch(`/documents/${env.esaId}/send?dealId=${encodeURIComponent(env.dealId)}`,{method:'POST',body:JSON.stringify({acknowledged:false})});stmt=r.status===400?r.body.error:'';if(r.status===200&&r.body.signers){return esaSent(env.id,r.body)}}catch(e){} esaStep(env,`
Review before sending

Signers sign in this order. Each gets a private link and doesn't need an E-Sign Auto account.

${per.map(([s,fs],i)=>``).join('')}
${i+1}${esc(s.label)}
${esc(s.name)}
${fs.filter(f=>f.type==='signature').length} signature · ${fs.filter(f=>f.type==='date').length} date${fs.some(f=>f.added)?' 1 added at the bottom of the last page':''}

${fields.length} fields on ${env.esaPages||'?'} pages, placed from DealerPen's own signature lines.${ap&&ap.fields&&ap.fields.length?` E-Sign Auto also suggested ${ap.fields.length} fields${ap.model?'':' (not AI-reviewed)'}. `:''}

E-Sign Auto statement
${esc(stmt||'Could not load the statement. Close and try again.')}
Preview of the uploaded PDF${ESA().token?' (if blank, open it from the DealerPen server; previews need the access token)':''}
`, ``); $('#esgo').onclick=async()=>{if(!$('#esack').checked)return toast('Please review and accept the statement first');$('#esgo').disabled=true;$('#esgo').textContent='Sending…'; const payload={acknowledged:true,signers:env.signers.map(s=>({name:s.name,role:s.label})),fields:fields.map(({page,x,y,w,h,type,signerIndex,label,value})=>({page,x,y,w,h,type,signerIndex,label,...(value!=null?{value}:{})}))}; try{const r=await esaFetch(`/documents/${env.esaId}/send?dealId=${encodeURIComponent(env.dealId)}`,{method:'POST',body:JSON.stringify(payload)});if(!r.ok)throw new Error(r.body?.error||`Send failed (${r.status})`); env.events.push({at:nowAt(),by:S.settings.user,text:`${S.settings.user} accepted the E-Sign Auto statement and sent the packet to ${env.signers.length} signer(s)`});esaSent(env.id,r.body)}catch(e){toast(e.message);$('#esgo').disabled=false;$('#esgo').textContent='Send for signatures'}}} function esaSent(envId,body){const env=S.envelopes.find(x=>x.id===envId);(body.signers||[]).forEach((s,i)=>{if(env.signers[i])env.signers[i].signingUrl=s.signingUrl});if(env.status==='Draft')env.status='Sent';env.sent=env.sent||nowAt();save();render();esaLinks(env.id)} function esaLinks(envId){const env=S.envelopes.find(x=>x.id===envId);const d=S.deals.find(x=>x.id===env.dealId),c=cust(d.customerId); esaStep(env,`

Deliver each private link to its signer. Links work in order: each one opens after the signer before it finishes. Don't forward a link to anyone else.

${env.signers.map((s,i)=>``).join('')}
${i+1}${esc(s.label)}
${esc(s.name)} ${esc(s.phone||'')} ${esc(s.email||'')}
${s.signedAt?'Signed':i===env.signers.findIndex(z=>!z.signedAt)?'Up now':'Waiting'} ${s.signingUrl?` ${s.role==='dealer'?`Open`:`${s.phone&&c&&!canText(c)&&s.role==='buyer'?``:''} ${s.email?`✉ Email`:''}`}`:'no link yet'}

DealerPen checks E-Sign Auto for progress automatically, and the server also checks in the background. When everyone has signed, the completed PDF with E-Sign Auto's audit certificate is saved to this deal.

`, ``)} async function esaRefresh(envId,show){const env=S.envelopes.find(x=>x.id===envId);if(!env||!env.esaId)return; try{const r=await esaFetch(`/documents/${env.esaId}?dealId=${encodeURIComponent(env.dealId)}`);if(!r.ok){if(show)toast(r.body?.error||`Status check failed (${r.status})`);return} const b=r.body;let changed=false;(b.signers||[]).forEach((s,i)=>{const L=env.signers[i];if(L&&s.signedAt&&!L.signedAt){L.signedAt=s.signedAt;L.status='Signed';changed=true;env.events.push({at:nowAt(),by:'E-Sign Auto',text:`${L.label} ${L.name} signed (${s.signedAt.replace('T',' ').slice(0,16)})`})}}); if(b.status==='Completed'&&env.status!=='Completed'){env.status='Completed';env.completed=nowAt();changed=true;env.events.push({at:nowAt(),by:'E-Sign Auto',text:'All signers finished. Packet completed'});const dd=S.deals.find(x=>x.id===env.dealId);dealTitle(dd);if(dd.title.status==='Not started')dd.title.status='Docs signed'} else if(b.status==='Awaiting signatures'){const st=env.signers.some(s=>s.signedAt)?'Partially signed':'Sent';if(env.status!==st){env.status=st;changed=true}} if(env.status==='Completed'&&!env.signedAsset&&!env.signedFetching){env.signedFetching=1;try{const p=await esaFetch(`/documents/${env.esaId}/signed-pdf?dealId=${encodeURIComponent(env.dealId)}`); if(p.ok&&p.body instanceof Blob){const pdfb=p.body.type==='application/pdf'?p.body:new Blob([p.body],{type:'application/pdf'});if(ASSETS){const up=await ASSETS.upload(pdfb,{type:'application/pdf'});env.signedAsset={id:up.id,src:'a'}}else{const id=uid();await idbOp('readwrite',s=>s.put(pdfb,id));IDBURL[id]=URL.createObjectURL(pdfb);env.signedAsset={id,src:'i'}}env.events.push({at:nowAt(),by:'DealerPen',text:'Signed PDF with audit certificate saved to the deal'});changed=true}}catch(e){}delete env.signedFetching} if(changed){save();if(show)toast('Status updated');render()}else if(show)toast('No change yet')}catch(e){if(show)toast('Could not reach the DealerPen server')}} let esaTimer=null;function esaAuto(){clearInterval(esaTimer);esaTimer=setInterval(()=>{(S.envelopes||[]).filter(e=>e.esaId&&!['Completed','Voided','Declined'].includes(e.status)||e.esaId&&e.status==='Completed'&&!e.signedAsset).forEach(e=>esaRefresh(e.id))},120000)} function esaSettings(){const c=ESA();return `

✍ E-Sign Auto${ui.esaHealth?.ok?(ui.esaHealth.mock?'Server connected (test mode)':'Server connected'):'Not connected'}

Live e-signing runs through the DealerPen server, which keeps your E-Sign Auto developer key. The key never goes in this page or in Settings.

`} /* ================= Facebook Marketplace posting (per rep) ================= */ const FBPOSTS=()=>S.fbPosts=S.fbPosts||[]; const fbActive=v=>FBPOSTS().filter(p=>p.vid===v.id&&p.status==='Live'); function fbKitText(v){const pay=pmt(v.price*1.07+ +S.settings.docFee-v.price*0.1,+S.settings.apr,+S.settings.term,FREQ[S.settings.freq].ppy); return{title:`${v.year} ${v.make} ${v.model}${v.trim?' '+v.trim:''}`,price:Math.round(v.price),desc:`${vDesc(v)}\n\n✅ ${(+v.miles).toLocaleString()} miles · ${v.color||''}\n✅ Inspected & reconditioned\n✅ In-house financing – all credit situations welcome\n✅ Trade-ins welcome\n\nStock #${v.stock} · VIN ${v.vin}\n${S.settings.dealer} · ${S.settings.address}\nCall/text ${S.settings.phone}${S.settings.user?' – ask for '+S.settings.user.split(' ')[0]:''}`}} async function fbKit(vid){const v=veh(vid);let k=fbKitText(v);const pc=(v.photos||[]).length; openModal(mh(`Facebook Marketplace post · ${esc(v.stock)}`)+`
1 · Copy the details2 · Download photos3 · Post from your Facebook4 · Paste the link back
${`
${aiBtn(aiOn('listing')?'Write a Marketplace post with AI':'Auto-write post',aiOn('listing')?`fbAI('${vid}')`:`(()=>{const r=fbFallback(veh('${vid}'));$('#fbt').value=r.title;$('#fbd').value=r.description})()`,'fbaib')}Tailored to Marketplace buyers, in your name
`}
${pc?``:'No photos yet. Add some in the vehicle first, since Marketplace needs photos'}Open Facebook Marketplace ↗

Post from your own Facebook profile, by hand. Facebook doesn't allow automated posting tools on personal accounts. Mark the listing sold on Facebook when the car sells, and DealerPen will remind you.

`,true); $('#fbsave').onclick=()=>{const u=$('#fburl').value.trim();if(u&&!/^https:\/\/(www\.|m\.)?facebook\.com\//.test(u))return toast('That doesn\'t look like a Facebook link');FBPOSTS().push({id:uid(),vid,userId:me()?.id,at:nowAt(),url:u,status:'Live',title:$('#fbt').value,price:+$('#fbp').value});save();closeModal();render();toast('Facebook post recorded')}} function fbFallback(v){const st=S.settings,rep=(me()?.name||st.user).split(' ')[0];const d=vDesc(v);const pay=Math.round(pmt(v.price*1.07+ +st.docFee-v.price*0.1,+st.apr,+st.term,FREQ[st.freq].ppy)); return{title:`${v.year} ${v.make} ${v.model}${v.trim?' '+v.trim:''} – ${(+v.miles/1000).toFixed(0)}k miles`.slice(0,60),description:`🚗 ${v.year} ${v.make} ${v.model}${v.trim?' '+v.trim:''} – ${$0(v.price)}\n\n${d}\n\n✅ ${(+v.miles).toLocaleString()} miles${v.color?' · '+v.color:''}\n✅ Inspected & reconditioned\n✅ In-house financing available – all credit situations welcome (around ${$0(pay)} ${FREQ[st.freq].label.toLowerCase()} with 10% down, on approved credit)\n✅ Trade-ins welcome\n\nMessage me here or call/text ${st.phone} and ask for ${rep}.\n${st.dealer} · ${st.address}\nStock #${v.stock}`}} function fbMsg(t,warn){let m=$('#fbmsg');if(!m){m=document.createElement('div');m.id='fbmsg';$('#fbaib').parentElement.after(m)}m.className=warn?'warn amber':'hint';m.style.marginBottom='10px';m.innerHTML=t} async function fbAI(vid){const v=veh(vid),b=$('#fbaib');if(!SAMPLE){const r=fbFallback(v);$('#fbt').value=r.title;$('#fbd').value=r.description;fbMsg('AI writing needs DealerPen open inside Claude. It looks like it\'s open in its own browser tab, so a built-in template wrote the post instead. Review it, then copy.',true);return}b.disabled=true;b.textContent='✦ Writing…';fbMsg('✦ Asking Claude… the first time, Claude may ask you to allow this page to use it.'); try{const r=await ai(`Write a Facebook Marketplace vehicle listing for a salesperson at a used-car dealer. Vehicle: ${vname(v)}, ${(+v.miles).toLocaleString()} miles, ${v.color}, price ${$0(v.price)}, stock ${v.stock}, VIN ${v.vin}. Notes: ${vDesc(v)}. Dealer: ${S.settings.dealer}, ${S.settings.address}, ${S.settings.phone}. Salesperson: ${(me()?.name||S.settings.user)}. In-house financing for all credit situations; trade-ins welcome. Rules: friendly, local, scannable; short paragraphs and a few ✅ bullet lines; only claim features standard for this model/trim or in the notes; no "guaranteed approval" or rate promises; include stock number and how to reach the salesperson; under 900 characters. Title under 60 characters. Reply with only JSON: {"title":"","description":""}`,{tier:'quick',nocache:true});if(r&&r.title)$('#fbt').value=r.title;if(r&&r.description)$('#fbd').value=r.description;fbMsg('✓ AI post ready. Review it, then copy each field into Facebook.')}catch(e){const r=fbFallback(v);$('#fbt').value=r.title;$('#fbd').value=r.description;fbMsg(aiErrMsg(e)+' A built-in template wrote the post instead.',true)}b.disabled=false;b.textContent='✦ Write a Marketplace post with AI'} VIEWS.fbpost=()=>{const u=me();const mine=FBPOSTS().filter(p=>p.userId===u.id);const avail=S.vehicles.filter(v=>v.status==='Available'); const toRemove=FBPOSTS().filter(p=>p.status==='Live'&&veh(p.vid)&&veh(p.vid).status==='Sold');const stale=mine.filter(p=>p.status==='Live'&&diff(p.at.slice(0,10),TODAY)>=7&&veh(p.vid)?.status==='Available'); const reps=S.users.filter(x=>x.active).map(x=>[x,FBPOSTS().filter(p=>p.userId===x.id&&p.status==='Live').length,S.customers.filter(c=>c.source==='Facebook'&&c.ownerId===x.id).length]).filter(r=>r[1]||r[2]); return `
${kpi('My live posts',mine.filter(p=>p.status==='Live').length,'on Facebook Marketplace')}${kpi('Cars not posted by me',avail.filter(v=>!mine.some(p=>p.vid===v.id&&p.status==='Live')).length,'available to post')}${kpi('My Facebook leads',S.customers.filter(c=>c.source==='Facebook'&&c.ownerId===u.id).length,'assigned to you')}${kpi('Needs attention',toRemove.length+stale.length,'sold cars still posted / relists')}
${toRemove.length?`
🚫 These cars are sold but still listed on Facebook. Mark them sold on Facebook, then here: ${toRemove.map(p=>``).join(' ')}
`:''} ${stale.length?`
🔁 Posted 7+ days ago. Renewing or relisting keeps them near the top: ${stale.map(p=>``).join(' ')}
`:''}
Post your inventory from your own Facebook profile. Each rep posts and tracks their own listings. Leads from Facebook go to you: add them with source "Facebook".
${avail.map(v=>{const my=mine.find(p=>p.vid===v.id&&p.status==='Live');const team=fbActive(v).filter(p=>p.userId!==u.id); return ``}).join('')}
VehiclePricePhotosMy postTeam posts
${mainPhoto(v)?``:''}
${esc(vname(v))}
${v.stock} · ${(+v.miles).toLocaleString()} mi
${$0(v.price)}${(v.photos||[]).length||'0'} ${my?`Live · ${diff(my.at.slice(0,10),TODAY)}d${my.url?` view ↗`:''}${my.price&&my.price!==Math.round(v.price)?' price changed – update post':''}`:'Not posted'}${team.map(p=>esc(uname(p.userId).split(' ')[0])).join(', ')||'—'} ${my?` `:``}
${reps.length?`

Team Facebook activity

${reps.map(r=>``).join('')}
RepLive postsFacebook leads
${esc(r[0].name)}${r[1]}${r[2]}
`:''}`}; /* ================= Finance applications (Dealertrack / RouteOne / CUDL) ================= */ const PORTALS=[['dealertrack','Dealertrack','https://www.dealertrack.com/'],['routeone','RouteOne','https://www.routeone.com/'],['cudl','CUDL (credit unions)','https://www.cudl.com/'],['direct','Direct to lender','']]; const APPST=['Draft','Submitted','Approved','Conditioned','Counter-offer','Declined','Funded']; const appPill=s=>`${s}`; const mask=x=>x?'•••-••-'+String(x).replace(/\D/g,'').slice(-4):''; function appModal(id,cid){S.creditApps=S.creditApps||[];const a=id?S.creditApps.find(x=>x.id===id):{customerId:cid||'',vehicleId:'',amount:'',down:'',term:72,status:'Draft',app:{},co:{},decisions:[]};const c=cust(a.customerId)||{};const A=a.app; const fld=(o,k,l,t='text',cls='')=>``; openModal(mh(id?`Credit application · ${esc(c.name||'')}`:'New credit application')+`
Applicant
${fld('app','dob','Date of birth','date')}${fld('app','ssn','SSN (stored masked)','text')}${fld('app','dl',"Driver's license #")}${fld('app','dlState','DL state')} ${fld('app','addr','Current address','text','c2')}${fld('app','yrsAddr','Years at address','number')}${fld('app','housing','Rent / mortgage $','number')} ${fld('app','employer','Employer','text','c2')}${fld('app','title','Job title')}${fld('app','yrsJob','Years on job','number')} ${fld('app','income','Gross monthly income','number')}${fld('app','otherIncome','Other income / mo','number')}${fld('app','prevEmployer','Previous employer (if < 2 yrs)','text','c2')}
Co-applicant (optional)
${fld('co','name','Name','text','c2')}${fld('co','phone','Phone')}${fld('co','income','Monthly income','number')}
Credit applications hold sensitive data. Only the last 4 digits of the SSN are kept in this browser. Full SSN and credit pulls belong in the lender portal or the secure DealerPen server.
`,true); $('#caf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const n=id?a:{id:uid(),created:nowAt(),decisions:[],submissions:[],app:{},co:{}}; Object.assign(n,{customerId:x.customerId,vehicleId:x.vehicleId,amount:+x.amount||0,down:+x.down||0,term:+x.term||0,status:x.status}); Object.keys(x).forEach(k=>{const [o,f]=k.split('.');if(f){if(f==='ssn'){const d=x[k].replace(/\D/g,'');if(d)n[o].ssn4=d.slice(-4);return}n[o][f]=x[k]}});delete n.app.ssn; if(!id)S.creditApps.push(n);save();closeModal();render();toast('Application saved')}} function submitApp(id,portal){const a=S.creditApps.find(x=>x.id===id),p=PORTALS.find(x=>x[0]===portal);const c=cust(a.customerId),v=veh(a.vehicleId); const sheet=`CREDIT APPLICATION – ${c?.name}\nPhone: ${c?.phone} Email: ${c?.email||''}\nAddress: ${a.app.addr||c?.address||''} (${a.app.yrsAddr||'?'} yrs) · Housing ${$0(a.app.housing||0)}/mo\nDOB: ${a.app.dob||''} SSN: ${a.app.ssn4?'xxx-xx-'+a.app.ssn4:''} DL: ${a.app.dl||''} ${a.app.dlState||''}\nEmployer: ${a.app.employer||c?.employer||''} – ${a.app.title||''} (${a.app.yrsJob||'?'} yrs) · Income ${$0(a.app.income||c?.income||0)}/mo + other ${$0(a.app.otherIncome||0)}\n${a.co.name?`Co-applicant: ${a.co.name} ${a.co.phone||''} income ${$0(a.co.income||0)}/mo\n`:''}\nVEHICLE: ${v?vname(v)+' · VIN '+v.vin+' · '+(+v.miles).toLocaleString()+' mi · price '+$0(v.price):''}\nAmount requested ${$0(a.amount)} · Cash down ${$0(a.down)} · Term ${a.term} mo`; openModal(mh(`Send to ${p[1]}`)+`
DealerPen is not yet a certified ${p[1]} integration partner, so applications can't be sent automatically yet. Open ${p[1]}, start the application, and use the summary below to fill it in. Then record the lender decisions back here.
${esc(sheet)}
${p[2]?`Open ${p[1]} ↗`:''}
`); $('#cps').onclick=()=>copyText(sheet);$('#mks').onclick=()=>{a.submissions=a.submissions||[];a.submissions.push({portal,at:nowAt(),by:S.settings.user});if(a.status==='Draft')a.status='Submitted';save();closeModal();render();toast('Marked submitted to '+p[1])}} function decisionModal(id){const a=S.creditApps.find(x=>x.id===id);openModal(mh('Record lender decision')+`
`); $('#dcf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);a.decisions.push({...x,at:nowAt()});const rank={'Approved':3,'Conditioned':2,'Counter-offer':1,'Declined':0};const best=a.decisions.reduce((m,d)=>Math.max(m,rank[d.decision]),0);if(a.status!=='Funded')a.status=['Declined','Counter-offer','Conditioned','Approved'][best];save();closeModal();render();toast('Decision saved')}} function appToDeal(id,di){const a=S.creditApps.find(x=>x.id===id),dz=a.decisions[di];closeModal();dealModal(null,a.vehicleId||null,a.customerId);setTimeout(()=>{const f=$('#df');if(!f)return;f.type.value='Retail Finance';f.lender.value=dz.lender;if(dz.rate)f.apr.value=dz.rate;f.freq.value='monthly';f.term.value=dz.term||a.term;if(a.down)f.down.value=a.down;f.dispatchEvent(new Event('input'))},30)} VIEWS.finance=()=>{const apps=(S.creditApps||[]).slice().sort((a,b)=>b.created.localeCompare(a.created));const cnt=s=>apps.filter(a=>a.status===s).length; const ft=`
${[['apps','Credit applications'],['lenders','Lender programs']].map(t=>``).join('')}
`;if(ui.finTab==='lenders')return ft+lendersView(); return ft+`
${kpi('Open applications',apps.filter(a=>!['Funded','Declined'].includes(a.status)).length,'')}${kpi('Approved / conditioned',cnt('Approved')+cnt('Conditioned'),'')}${kpi('Declined',cnt('Declined'),'')}${kpi('Funded',cnt('Funded'),'')}
${PORTALS.slice(0,3).map(p=>`

🏦 ${p[1]}Not connected

Credit apps go out by hand for now. A live connection needs DealerPen to be certified as a ${p[1]} DMS partner plus your dealer enrollment, after which apps and decisions sync automatically.
`).join('')}
${apps.map(a=>{const c=cust(a.customerId),v=veh(a.vehicleId);return `

${esc(c?.name||'—')} ${appPill(a.status)}${v?esc(vname(v))+' · ':''}${$0(a.amount)} requested · ${$0(a.down)} down · ${a.term} mo

${PORTALS.map(p=>``).join('')}
${(a.submissions||[]).length?`
Submitted: ${a.submissions.map(s=>PORTALS.find(p=>p[0]===s.portal)[1]+' '+ftime(s.at)).join(' · ')}
`:''} ${a.decisions.length?`${a.decisions.map((d,i)=>``).join('')}
LenderDecisionRateMaxTermTierStips
${esc(d.lender)}
${esc(PORTALS.find(p=>p[0]===d.portal)?.[1]||'')} · ${ftime(d.at)}
${appPill(d.decision)}${d.rate?d.rate+'%':'—'}${d.max?$0(d.max):'—'}${esc(d.term||'')}${esc(d.tier||'')}${esc(d.stips||'')}${d.decision!=='Declined'?``:''}
`:''}
`}).join('')||'
No credit applications yet
'}
`}; /* ================= Sales rep desk ================= */ const ownerOf=c=>S.users.find(u=>u.id===c.ownerId); function myId(){return me()?.id} VIEWS.desk=()=>{const real=me();const canAll=['Owner','Sales Manager','Desking Manager'].includes(real.role);const u=canAll&&ui.deskFor?S.users.find(x=>x.id===ui.deskFor)||real:real;const reps=S.users.filter(x=>x.active&&['Salesperson','Sales Manager','Owner'].includes(x.role));const mine=c=>c.ownerId===u.id;const m=TODAY.slice(0,7); const myLeads=S.customers.filter(c=>mine(c)&&['New','Contacted','Appointment'].includes(c.stage));const unassigned=S.customers.filter(c=>!c.ownerId&&['New','Contacted','Appointment'].includes(c.stage)); const tasks=myLeads.filter(c=>(c.next?c.next.date:c.followUp)&&(c.next?c.next.date:c.followUp)<=TODAY||!c.next).sort((a,b)=>((a.next?.date||'0')+(a.next?.time||'')).localeCompare((b.next?.date||'0')+(b.next?.time||'')));const appts=myLeads.filter(c=>c.stage==='Appointment'&&c.followUp>=TODAY).sort((a,b)=>a.followUp.localeCompare(b.followUp)); const myDeals=S.deals.filter(d=>d.salespersonId===u.id&&d.date.slice(0,7)===m);const gross=myDeals.reduce((a,d)=>a+d.gross,0);const st=S.settings;const comm=myDeals.reduce((a,d)=>a+Math.max(+st.commMin||0,d.gross*(+st.commPct||0)/100),0); const goal=+u.goal||+st.unitGoal||10;const board=S.users.filter(x=>x.active&&['Salesperson','Sales Manager'].includes(x.role)).map(x=>{const ds=S.deals.filter(d=>d.salespersonId===x.id&&d.date.slice(0,7)===m);return[x,ds.length,ds.reduce((a,d)=>a+d.gross,0)]}).sort((a,b)=>b[1]-a[1]||b[2]-a[2]); const row=c=>{const lm=lastMsg(c.id);return `${esc(c.name)}
${esc(c.interest||c.source)}
${stagePill(c.stage)}
${c.next?esc(nxLabel(c.next)):'⚠ No next step'}
${c.next&&c.next.note?`
${esc(c.next.note)}
`:''}${lm?(lm.dir==='in'?'💬 ':'')+esc((lm.channel==='call'?'Call: '+lm.outcome:lm.body).slice(0,50)):'No contact yet'}${c.next&&c.next.date<=TODAY?` `:''}${cbtn(c.id)}`}; return `
${u.id===real.id?`Good ${new Date().getHours()<12?'morning':new Date().getHours()<17?'afternoon':'evening'},`:'Sales rep view'}

${esc(u.id===real.id?u.name.split(' ')[0]:u.name)}

${canAll?``:''}
${kpi('My units this month',`${myDeals.length} / ${goal}`,`
`)}${kpi('My front gross',$0(gross),myDeals.length?$0(gross/myDeals.length)+' avg per deal':'')}${kpi('Est. commission',$0(comm),`${st.commPct}% of front gross, ${$0(st.commMin)} min per unit`)}${kpi('Follow-ups due',tasks.length,appts.length+' upcoming appointments')}

📋 Today's follow-ups${tasks.length}

${tasks.length?`${tasks.map(row).join('')}
`:'
All caught up 🎉
'}

📅 Upcoming appointments

${appts.length?`${appts.map(c=>``).join('')}
${esc(c.name)}
${esc(c.interest||'')}
${fdate(c.followUp)}${cbtn(c.id)}${aiOn('leads')?'':''}
`:'
No appointments booked
'}

👥 My pipeline (${myLeads.length})

${myLeads.length?`${myLeads.map(row).join('')}
`:'
No leads assigned to you
'}
${unassigned.length?`

🆕 Up for grabs${unassigned.length}

${unassigned.map(c=>``).join('')}
${esc(c.name)}
${esc(c.source)} · ${fdate(c.created)}
`:''}

🏆 Leaderboard · ${s2d(m+'-01').toLocaleDateString('en-US',{month:'long'})}

${board.map((b,i)=>``).join('')||''}
${['🥇','🥈','🥉'][i]||i+1}${esc(b[0].name)}${b[1]} units${$0(b[2])}
No sales staff

🚗 Fresh inventory

${S.vehicles.filter(v=>v.status==='Available').sort((a,b)=>age(a)-age(b)).slice(0,6).map(v=>``).join('')}
${esc(vname(v))}
${(+v.miles).toLocaleString()} mi · ${age(v)} days
${$0(v.price)}

💵 My deals this month

${myDeals.length?`${myDeals.map(d=>``).join('')}
#${d.no} ${esc(cust(d.customerId)?.name)}${d.type}${$0(d.gross)}
`:'
No deals yet this month. Let\'s go!
'}
`}; /* ================= Users & roles ================= */ const MODS=[['desk','Sales Rep Dashboard'],['dashboard','Dashboard'],['ai','AI Assistant'],['inventory','Inventory'],['finder','Vehicle Finder'],['recon','Recon'],['website','Website'],['feeds','Listing Feeds'],['fbpost','Facebook Posting'],['crm','Leads & CRM'],['equity','Equity Mining'],['comms','Calls & Texts'],['desklog','Desk Log'],['deals','Deals'],['activity','Customer Activity'],['finance','Finance Apps'],['accounts','Loan Accounts'],['collections','Collections'],['titleadmin','Title Admin'],['forms','Forms'],['accounting','Accounting'],['reports','Reports'],['settings','Settings']]; const ALLM=MODS.map(m=>m[0]); const DEFAULT_ROLES={'Owner':ALLM,'Sales Manager':ALLM.filter(m=>m!=='settings'&&m!=='accounting'),'Salesperson':['desk','dashboard','ai','inventory','finder','fbpost','crm','equity','comms','deals','finance','forms'],'Desking Manager':['desk','dashboard','ai','inventory','finder','crm','equity','comms','desklog','deals','activity','finance','titleadmin','forms','reports'],'Office / F&I':['dashboard','ai','crm','comms','deals','activity','finance','accounts','titleadmin','forms','accounting','reports'],'Customer Service':['dashboard','ai','inventory','crm','comms','accounts','titleadmin','forms'],'Collector':['dashboard','ai','crm','comms','accounts','collections'],'Recon Tech':['dashboard','inventory','recon']}; let ME=null; const SKEY=workspaceStorage('lotledger_session'); function me(){if(ME)return ME;if(!S.settings.requireLogin)return S.users.find(u=>u.role==='Owner'&&u.active)||S.users[0];return null} const can=m=>{const u=me();if(!u)return false;if(m==='contact'||m==='workspace'||m==='mailbox')return true;if(m==='cust')m='crm';if(m==='deskws')m='deals';if(m==='veh')m='inventory';if(u.role==='Owner')return true;return (S.roles[u.role]||[]).includes(m)}; function signIn(u){ME=u;try{logAccess(u,'PIN on this computer')}catch(e){}if(u.role==='Salesperson'&&(S.roles[u.role]||[]).includes('desk'))route='desk';u.lastLogin=nowAt();S.settings.user=u.name;try{localStorage.setItem(SKEY,u.id)}catch(e){}save();$('#login').classList.remove('on');if(!can(route))route=ALLM.find(can)||'dashboard';render();toast('Signed in as '+u.name)} function signOut(){ME=null;try{localStorage.removeItem(SKEY)}catch(e){}closeModal();if(S.settings.requireLogin)showLogin();else render()} function restoreSession(){try{const id=localStorage.getItem(SKEY);const u=S.users.find(x=>x.id===id&&x.active);if(u){ME=u;S.settings.user=u.name}}catch(e){}} function showLogin(sel){const L=$('#login');const us=S.users.filter(u=>u.active);const u=sel?S.users.find(x=>x.id===sel):null; L.innerHTML=`
${u?`
${esc(ini(u.name))}
${esc(u.name)}
${esc(u.role)}
` :`

Who's working?

${us.map(x=>``).join('')}
`}
`; L.classList.add('on'); if(u){$('#pin').focus();$('#pinf').onsubmit=e=>{e.preventDefault();if($('#pin').value===String(u.pin))signIn(u);else{$('#pinerr').textContent='Wrong PIN';$('#pin').value=''}}}} const ini=n=>String(n||'?').split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase(); function userChip(){ const user=me(); const chip=$('#uchip'); if(!chip)return; chip.innerHTML=user?`
${esc(ini(user.name))}${esc(user.name)}${esc(user.role)}
${myAccountCard()}${DBM.mode?'':''+ (S.settings.requireLogin?'':'')}
`:''; } document.addEventListener('click',event=>{ const profile=$('.profile-options[open]'); if(profile&&!profile.contains(event.target))profile.open=false; }); document.addEventListener('keydown',event=>{ const profile=$('.profile-options[open]'); if(profile&&event.key==='Escape'){profile.open=false;profile.querySelector('summary').focus();} }); document.addEventListener('click', event => { const toggle = event.target.closest('[data-password-eye]'); if (!toggle) return; const input = toggle.previousElementSibling; const show = input.type === 'password'; input.type = show ? 'text' : 'password'; toggle.setAttribute('aria-label', show ? 'Hide password' : 'Show password'); toggle.querySelector('[data-eye-slash]').style.display = show ? '' : 'none'; }); async function sendWelcome(userId){ const result=await dbFetch('/api/auth/invite',{body:{userId}}); toast(result.ok?'Welcome email sent':result.body.error||'Welcome email could not be sent'); } async function acceptWelcome(){ const params=new URLSearchParams(location.hash.slice(1)); const reset=params.get('reset'); const token=reset||params.get('welcome'); if(!token)return; history.replaceState(null,'',location.pathname); const box=$('#login'); box.innerHTML='

'+(reset?'Reset your password':'Welcome to DealerPen')+'

'; box.classList.add('on'); const form=$('#welcome-form'); form.onsubmit=async event=>{ event.preventDefault(); const response=await dbFetch(reset?'/api/auth/reset-password':'/api/auth/accept-invite',{body:{token,password:form.elements.password.value}}); if(response.ok)dbLogin('Password saved. Sign in with your email.'); else form.querySelector('[role=status]').textContent=response.body.error||'Try again.'; }; } function userModal(id){const u=id?S.users.find(x=>x.id===id):{name:'',email:'',phone:'',role:'Salesperson',pin:'',active:true}; openModal(mh(id?'Edit user':'Add user')+`
${DBM.mode?`${id&&u.active&&u.email?``: ''}`:``} ${stores().length>1?`
Works at
${stores().map(st=>``).join('')}
`:''}
Can open:
${id?'':''}
`); const f=$('#uf');const up=()=>{const r=f.role.value;$('#ucan').textContent=(r==='Owner'?ALLM:(S.roles[r]||[])).map(m=>MODS.find(x=>x[0]===m)[1]).join(', ')};f.role.onchange=up;up(); const owners=()=>S.users.filter(x=>x.role==='Owner'&&x.active); if(id)$('#udel').onclick=()=>{if(u.role==='Owner'&&owners().length<2)return toast('You need at least one active Owner');if(me()&&me().id===id)return toast("You can't remove yourself");confirmBox('Remove '+esc(u.name)+'? Their past notes and activity stay.',()=>{S.users=S.users.filter(x=>x.id!==id);save();render()})}; f.onsubmit=async e=>{e.preventDefault();const x=fd(f);if(!DBM.mode&&!/^\d{4,6}$/.test(x.pin))return toast('PIN must be 4–6 digits');if(DBM.mode&&!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(x.email||''))return toast('Staff sign in with their email, so add one'); if(id&&u.role==='Owner'&&(x.role!=='Owner'||!x.active)&&owners().length<2)return toast('You need at least one active Owner'); const n=id?u:{id:uid(),created:TODAY};Object.assign(n,{name:x.name,email:x.email,phone:x.phone,role:x.role,active:!!x.active,payPlanId:x.payPlanId||n.payPlanId||''});if(!DBM.mode)n.pin=x.pin;if(stores().length>1){const sel=stores().filter(st=>x['st_'+st.id]).map(st=>st.id);n.stores=sel.length===stores().length?[]:sel}if(!id)S.users.push(n);if(ME&&ME.id===n.id)S.settings.user=n.name;save();closeModal();render();if(!id&&DBM.on&&n.active){const saved=await dbFetch('/api/db/push',{body:{changes:[{c:'users',id:n.id,doc:dbDoc('users',n)}]}});if(saved.ok&&saved.body.results?.[0]?.ok){DBM.base['users\u0001'+n.id]=JSON.stringify(dbDoc('users',n));await sendWelcome(n.id);}else toast('User sync is pending. Retry from Edit user.');}else toast('User saved')}} function roleModal(){const roles=Object.keys(S.roles);openModal(mh('New role')+`
`); $('#rf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(S.roles[x.name])return toast('That role exists');S.roles[x.name]=[...(S.roles[x.copy]||[])];save();closeModal();render()}} function toggleRole(r,m,on){const a=new Set(S.roles[r]);on?a.add(m):a.delete(m);S.roles[r]=ALLM.filter(x=>a.has(x));save();if(!can(route))go(ALLM.find(can));else render()} function usersSettings(){const s=S.settings;return `

👥 Users & roles

${S.users.map(u=>``).join('')}
NameRoleEmailMobileLast sign-inStatus
${esc(ini(u.name))}
${esc(u.name)}${me()&&me().id===u.id?' You':''}
${esc(u.role)}${esc(u.email)}${esc(u.phone)}${u.lastLogin?ftime(u.lastLogin):'Never'}${u.active?'Active':'Disabled'}

Role permissions

${MODS.map(m=>``).join('')}${Object.keys(S.roles).map(r=>`${MODS.map(m=>``).join('')}`).join('')}
Role${m[1]}
${esc(r)}${!DEFAULT_ROLES[r]?` `:''}
${DBM.mode?'Staff sign in with their own email and password on any device. The server checks every change, so only the owner can manage users, roles, stores and settings.':'Users, PINs and permissions are stored in this browser only. They keep staff in their own lanes on a shared office computer, but they aren\'t real security. Run DealerPen from the DealerPen server for real staff logins on every device.'}
`} /* ================= AI ================= */ let SAMPLE=null; try{if(window.claude&&window.claude.use)window.claude.use('sample').then(x=>{SAMPLE=x;if(route==='ai')render()}).catch(()=>{})}catch(e){} const AIFEAT=[['collections','Collections assistant','Ranks who to call first and writes a call script and text for each past-due account'],['voice','Voice agent prep','Builds instructions and a daily call list for an AI phone agent (e.g. your Vapi agent)'],['leads','Lead auto-responder','Drafts instant replies to new leads, qualifies them and suggests cars'],['deal','Deal structuring advisor','Suggests vehicle, down payment and term that fit the customer'],['pricing','Pricing & aging advisor','Reviews aging inventory and recommends price cuts or wholesale'],['listing','Listing writer','Writes vehicle descriptions for your website and marketplaces'],['recon','Recon inspection helper','Turns inspection notes and photos into recon tasks with estimates'],['doccheck','Deal document check','Checks each deal for missing or mismatched paperwork before you finalize'],['ask','Ask DealerPen','Answer plain-English questions about your sales, inventory and accounts'],['profile','Customer AI suggestions','Summarizes each customer, suggests cars, talking points, the next step and a text to send'],['bdc','AI BDC calling','Follow-up calling campaigns with Vapi, Retell, Bland, Synthflow, ElevenLabs or Twilio agents']]; const aiOn=k=>S.settings.ai&&S.settings.ai.master&&S.settings.ai[k]; const aiAny=()=>AIFEAT.some(f=>aiOn(f[0])); const busy={}; function aiErrMsg(e){const c=e&&e.code;return c==='not_granted'?'Claude access was not allowed for this page.':c==='rate_limited'?'Too many AI requests right now. Wait a minute and try again.':c==='invalid_json'?'The AI answer came back garbled. Try again.':c==='unavailable'||c==='sampling_disabled'||c==='capability_disabled'?'AI is only available when DealerPen is opened inside Claude.':c==='session_expired'?'Please sign in to Claude again.':'AI request failed. Try again.'} async function ai(prompt,opt={}){if(!SAMPLE)throw{code:'unavailable'};const o={modelTier:opt.tier||'default'};if(opt.images&&opt.images.length)o.images=opt.images;if(opt.nocache)o.cache=false;return opt.text?(await SAMPLE(prompt,o)).text:SAMPLE.json(prompt,o)} const RULES=`You are an assistant inside DealerPen, dealer management software for an independent used-car dealership that also does buy-here-pay-here (in-house) financing. Dealer: ${''}`; const dealerCtx=()=>`Dealer: ${S.settings.dealer}, ${S.settings.address}, phone ${S.settings.phone}. Staff user: ${S.settings.user}. Today is ${TODAY}.`; const aiBtn=(label,on,id)=>``; const aiNote=()=>SAMPLE?'':'
AI features run on Claude and work when DealerPen is opened inside Claude. Everything else still works here.
'; /* --- 1. collections assistant: local risk scoring + AI plan --- */ function risk(l){if(l.status!=='Active')return null;const dl=daysLate(l),pd=pastDue(l),missed=Math.floor(pd/l.payment+0.01),broken=!!(l.promise&&l.promise.datep.fee>0).length;let sc=dl*1.2+missed*8+(broken?20:0)+Math.min(since,90)*0.3+(gap>7&&dl>0?8:0)+feeHist*3+(l.payments.length<4&&dl>0?6:0); const why=[];if(dl)why.push(dl+' days late');if(missed)why.push(missed+' missed payment'+(missed>1?'s':''));if(broken)why.push('broken promise');if(since>30)why.push('no payment in '+since+' days');if(gap>7&&dl>0)why.push(gap>=99?'never contacted':'no contact in '+gap+' days');if(l.payments.length<4&&dl>0)why.push('early-term delinquency');if(soon)why.push('payment due '+fdate(nd)); return{l,score:Math.round(sc),lvl:sc>=70?'Repo risk':sc>=40?'High':sc>=15?'Medium':'Low',why,include:dl>0||soon||broken}} const riskPill=r=>`${r}`; function acctFacts(l){const c=cust(l.customerId),v=veh(l.vehicleId);return{acct:l.acct,first_name:(c?.name||'').split(' ')[0],vehicle:vname(v),payment:l.payment,frequency:FREQ[l.freq].label,days_late:daysLate(l),past_due:pastDue(l),late_fees:l.lateFeesDue,balance:l.balance,payments_made:l.payments.length,term:l.term,last_payment:l.payments.length?{date:l.payments.at(-1).date,amount:l.payments.at(-1).amount}:null,promise:l.promise?{date:l.promise.date,amount:l.promise.amount,broken:l.promise.daten.date+': '+n.text)}} async function aiPlan(){const list=S.loans.map(risk).filter(r=>r&&r.include).sort((a,b)=>b.score-a.score).slice(0,8);if(!list.length)return toast('No accounts need attention'); busy.plan=true;render(); try{const out=await ai(`${dealerCtx()} You are a collections coach for this buy-here-pay-here dealer. For each account below, write a short call plan for the collector. Rules: be respectful and factual; never threaten, harass, shame, or make false or misleading statements; do not discuss the debt with anyone but the customer; only mention that the contract allows repossession for accounts 45+ days late, and only as a fact, not a threat; aim for a specific, realistic promise to pay (date + amount) the customer can keep; texts must be under 300 characters, include the dealer name, and end with "Reply STOP to opt out." Accounts (JSON): ${JSON.stringify(list.map(r=>({...acctFacts(r.l),risk_score:r.score})))} Reply with only a JSON array, one object per account, ordered by who to call first: [{"acct":"A123","priority":1,"risk":"low|medium|high|repo","summary":"one sentence on the situation","approach":"how to handle this customer","opener":"what the collector says first, under 60 words","ask":"the payment arrangement to propose","text":"SMS to send if no answer"}]`); ui.aiPlan=Array.isArray(out)?out:[];ui.aiPlanAt=nowAt()}catch(e){toast(aiErrMsg(e))}busy.plan=false;render()} /* --- 2. voice agent prep --- */ async function aiVoice(){busy.voice=true;render();try{ui.voicePrompt=await ai(`${dealerCtx()} Write the system instructions for an AI phone agent that calls this dealer's buy-here-pay-here customers about upcoming and past-due payments. Include: identity and purpose disclosure at the start of the call; verify you're speaking with the customer before discussing the account (if not, leave only a callback message with no account details); goal of getting a specific promise to pay or taking a payment by transferring to staff; respectful tone, no threats, no false statements; handle hardship (offer to have a manager call back), disputes, wrong numbers, requests to stop calling (honor and log them), and calling hours of 8am-9pm local time; how to log the outcome. Late fee: ${$$(S.settings.lateFee)} after ${S.settings.graceDays} days. Use {{first_name}}, {{acct}}, {{past_due}}, {{payment}}, {{due_date}} as variables. Plain text, under 450 words.`,{text:true,nocache:true})}catch(e){toast(aiErrMsg(e))}busy.voice=false;render()} function voiceList(){return S.loans.map(risk).filter(r=>r&&r.include).sort((a,b)=>b.score-a.score).filter(r=>{const c=cust(r.l.customerId);return c.phone&&!c.optOut})} function voiceCSV(){return 'phone,first_name,name,acct,days_late,past_due,payment,due_date,risk\n'+voiceList().map(r=>{const l=r.l,c=cust(l.customerId);return ['+'+digits(c.phone),c.name.split(' ')[0],'"'+c.name+'"',l.acct,daysLate(l),pastDue(l),l.payment,nextDue(l)||'',r.lvl].join(',')}).join('\n')} async function dlVoice(){const csv=voiceCSV();if(DL){try{await DL.save({filename:`call-list-${TODAY}.csv`,data:csv});toast('Call list saved')}catch(e){if(e.code!=='declined')copyText(csv)}}else copyText(csv)} /* --- 3. lead auto-responder --- */ const invList=()=>S.vehicles.filter(v=>v.status==='Available').map(v=>({stock:v.stock,vehicle:vname(v),miles:+v.miles,price:+v.price})); const isOpenLead=c=>['New','Contacted','Appointment'].includes(c.stage); const lastMsg=cid=>S.comms.filter(x=>x.customerId===cid).sort((a,b)=>b.at.localeCompare(a.at))[0]; const needsReply=c=>{const m=lastMsg(c.id);return !m||m.dir==='in'}; function leadPrompt(cs){return `${dealerCtx()} You answer sales leads by text for this used-car dealer. For each lead, write the next text message to send. Goals: reply warmly and fast, answer what they asked, recommend 1-2 cars from the inventory that fit (never invent cars or prices), ask ONE qualifying question at a time (budget or payment, down payment, trade-in, timeline; mention in-house financing is available for all credit types if relevant), and push toward booking a visit or test drive. Under 320 characters, no emojis overload, sign with the dealer name. Do not promise approval or specific rates. Inventory: ${JSON.stringify(invList())} Leads: ${JSON.stringify(cs.map(c=>({id:c.id,first_name:c.name.split(' ')[0],source:c.source,stage:c.stage,interest:c.interest,monthly_income:c.income||null,notes:c.notes.slice(-3).map(n=>n.text),conversation:S.comms.filter(x=>x.customerId===c.id).sort((a,b)=>a.at.localeCompare(b.at)).slice(-8).map(x=>(x.channel==='call'?'[call '+x.outcome+'] ':x.dir==='in'?'Customer: ':'Dealer: ')+x.body)})))} Reply with only a JSON array: [{"id":"lead id","reply":"text to send","intent":"what the customer wants, a few words","temperature":"hot|warm|cold","qualification":{"budget":"","down_payment":"","trade_in":"","credit":"","timeline":""},"suggested_stock":["S1101"],"next_step":"short action for the salesperson","appointment":"YYYY-MM-DD or empty"}] (use empty strings for unknown qualification fields).`} async function aiLeads(cids){const cs=cids.map(cust).filter(Boolean);if(!cs.length)return toast('No leads waiting for a reply');busy.leads=true;render(); try{const out=await ai(leadPrompt(cs),{nocache:true});(Array.isArray(out)?out:[]).forEach(d=>{if(d&&d.id&&cust(d.id))ui.leadDrafts[d.id]=d})}catch(e){toast(aiErrMsg(e))}busy.leads=false;render()} function newLeadModal(){openModal(mh('New incoming lead')+`

Enter a lead from your website, marketplace or a text. DealerPen saves it and AI drafts the first reply right away.

`); $('#nl').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const c={id:uid(),created:TODAY,name:x.name,phone:x.phone,email:'',address:'',source:x.source,stage:'New',employer:'',income:0,interest:'',followUp:TODAY,smsConsent:!!x.consent,optOut:false,notes:[{date:TODAY,by:S.settings.user,text:'Lead created from '+x.source}]};S.customers.push(c);logComm({customerId:c.id,channel:'text',dir:'in',body:x.msg});save();closeModal();ui.aiTab='leads';ui.leadSel=c.id;if(route!=='ai')go('ai');else render();if(SAMPLE)aiLeads([c.id])}} function leadApply(cid){const d=ui.leadDrafts[cid],c=cust(cid);if(!d)return;const q=d.qualification||{};const parts=Object.entries(q).filter(([k,v])=>v).map(([k,v])=>k.replace('_',' ')+': '+v); c.notes.push({date:TODAY,by:'AI',text:`Lead summary – ${d.intent||''} (${d.temperature||'?'}). ${parts.join('; ')}${d.suggested_stock?.length?'. Suggested: '+d.suggested_stock.join(', '):''}. Next: ${d.next_step||''}`}); if(d.suggested_stock?.[0]){const v=S.vehicles.find(x=>x.stock===d.suggested_stock[0]);if(v&&!c.interest)c.interest=vname(v)} if(d.appointment&&/^\d{4}-\d\d-\d\d$/.test(d.appointment)){c.stage='Appointment';c.followUp=d.appointment}else if(c.stage==='New')c.stage='Contacted';save();render();toast('Saved to lead')} function leadSend(cid){const c=cust(cid);const t=($('#ld_'+cid)||{}).value||'';if(!t.trim())return;if(canText(c))return toast(canText(c));logComm({customerId:cid,channel:'text',dir:'out',body:t.trim()});if(c.stage==='New')c.stage='Contacted';delete ui.leadDrafts[cid];save();render();toast('Reply logged');promptNext(cid)} /* --- 4. deal advisor --- */ async function aiDeal(){const f=$('#df');if(!f)return;const x=fd(f);const c=cust(x.customerId);if(!c)return toast('Pick a customer first');const out=$('#aideal');out.innerHTML='
✦ Thinking…
'; try{const r=await ai(`${dealerCtx()} Suggest how to structure this deal. Customer: ${JSON.stringify({monthly_income:c.income||'unknown',employer:c.employer,stage:c.stage,notes:c.notes.slice(-4).map(n=>n.text)})}. Deal type: ${x.type}. Vehicle currently selected: ${x.vehicleId?JSON.stringify((v=>({stock:v.stock,vehicle:vname(v),price:v.price,cost_with_recon:vcost(v)}))(veh(x.vehicleId))):'none'}. Down payment entered: ${x.down}. Default APR ${S.settings.apr}%, doc fee ${S.settings.docFee}, tax ${S.settings.taxRate}%. Available inventory: ${JSON.stringify(S.vehicles.filter(v=>['Available','Pending'].includes(v.status)).map(v=>({stock:v.stock,vehicle:vname(v),miles:+v.miles,price:+v.price,cost_with_recon:vcost(v)})))} Guidelines for in-house deals: keep the payment at or under 20% of monthly income (monthly-equivalent), prefer at least 10% down, keep term short enough that the loan amount stays below the vehicle's value over time, match pay frequency to how the customer is paid if known, and protect the dealer's profit (price at or above cost_with_recon). Reply with only JSON: {"assessment":"2 sentences","options":[{"stock":"S1101","price":12995,"down":1500,"term":78,"frequency":"weekly|biweekly|semimonthly|monthly","apr":19.9,"why":"one sentence"}],"cautions":["short items"]} with 2-3 options.`); ui.dealAI=r;const opts=(r.options||[]).map(o=>{const v=S.vehicles.find(z=>z.stock===o.stock);if(!v)return'';const fq=FREQ[o.frequency]?o.frequency:'monthly';const k=calcDeal({...x,vehicleId:v.id,price:o.price||v.price,down:o.down,term:o.term,freq:fq,apr:o.apr}); return `
${esc(v.stock)} · ${esc(vname(v))}
${$$(o.price||v.price)} · ${$$(o.down)} down · ${o.term} ${FREQ[fq].label.toLowerCase()} payments of ${$$(k.payment)}${c.income?` · PTI ${(k.payment*k.ppy/12/c.income*100).toFixed(1)}%`:''}
${esc(o.why||'')}
`}).join(''); out.innerHTML=`
✦ AI advice

${esc(r.assessment||'')}

${opts}${(r.cautions||[]).length?`
    ${r.cautions.map(t=>`
  • ${esc(t)}
  • `).join('')}
`:''}
`}catch(e){out.innerHTML=`
${aiErrMsg(e)}
`}} function applyDealOpt(o){const f=$('#df');if(!f.vehicleId.querySelector(`option[value="${o.id}"]`))return;f.vehicleId.value=o.id;f.price.value=o.price;f.down.value=o.down;f.term.value=o.term;f.freq.value=o.freq;if(o.apr!=null)f.apr.value=o.apr;f.dispatchEvent(new Event('input'));toast('Applied')} /* --- 5. pricing advisor --- */ async function aiPricing(){const inv=S.vehicles.filter(v=>v.status==='Available'||v.status==='Pending');busy.pricing=true;render(); try{const out=await ai(`${dealerCtx()} Review this used-car inventory and recommend pricing actions. You have NO live market data; base advice on days in stock, margin, recon spend, mileage, price band and holding cost (${$$(S.settings.holdingCost)}/unit/day). Typical independent-dealer practice: fresh units (<30 days) hold price; 30-60 days consider a modest cut; 60-90 days cut harder; 90+ days consider wholesale/auction. Never recommend a price below cost_with_recon unless recommending wholesale. Note when a unit is a good fit for buy-here-pay-here customers. Inventory: ${JSON.stringify(inv.map(v=>({stock:v.stock,vehicle:vname(v),miles:+v.miles,days_in_stock:age(v),price:+v.price,cost_with_recon:vcost(v),margin:v.price-vcost(v)})))} Reply with only a JSON array: [{"stock":"S1101","action":"hold|reduce|raise|wholesale","new_price":12495,"reason":"one sentence"}]`);ui.priceAI=Array.isArray(out)?out:[]}catch(e){toast(aiErrMsg(e))}busy.pricing=false;render()} function applyPrice(stock,p){const v=S.vehicles.find(x=>x.stock===stock);if(!v)return;const old=v.price;v.price=+p;v.notes=(v.notes?v.notes+'\n':'')+`Price ${$0(old)} → ${$0(p)} on ${fdate(TODAY)} (AI pricing review)`;ui.priceAI=ui.priceAI.filter(x=>x.stock!==stock);save();render();toast(stock+' repriced')} /* --- 6. listing writer --- */ async function aiListing(){const f=$('#vf');const x=fd(f);if(!x.make||!x.model)return toast('Enter year, make and model first');const b=$('#ailist');b.disabled=true;b.textContent='✦ Writing…'; try{const t=await ai(`Write a vehicle listing description for a used-car dealer's website and online marketplaces. Vehicle: ${x.year} ${x.make} ${x.model} ${x.trim}, ${x.color}, ${(+x.miles).toLocaleString()} miles, price ${$0(x.price)}. Existing notes: ${x.notes||'none'}. Dealer: ${S.settings.dealer}, ${S.settings.phone}; in-house financing available. Write 90-140 words: a catchy first line, then the vehicle's strengths, then a call to action. Only state features that are standard for this model/trim or mentioned in the notes; don't invent accident history, warranty or certifications. Plain text, no markdown, no emojis.`,{text:true,tier:'quick',nocache:true});f.notes.value=t.trim();f.notes.rows=6;toast('Description written – review before saving')}catch(e){toast(aiErrMsg(e))}b.disabled=false;b.textContent='✦ Write listing with AI'} /* --- 7. recon helper --- */ async function aiRecon(vid){const v=veh(vid);const notes=$('#ainotes').value.trim();const files=[...($('#aiphotos').files||[])].slice(0,4);if(!notes&&!files.length)return toast('Add inspection notes or photos');const o=$('#aireconout');o.innerHTML='
✦ Reading inspection…
'; try{const r=await ai(`You help a used-car dealer's reconditioning manager. Vehicle: ${vname(v)}, ${(+v.miles).toLocaleString()} miles, asking ${$0(v.price)}. Recon budget ${$0(S.settings.reconBudget)}; already planned: ${JSON.stringify((v.tasks||[]).map(t=>t.desc))}. Turn the inspection notes${files.length?' and attached photos':''} into recon work items with realistic independent-shop cost estimates (parts + labor) in USD. Skip anything already planned. Mark items that are safety-related. Notes: ${notes||'(see photos)'} Categories: ${RCATS.join(', ')}. Reply with only JSON: {"tasks":[{"desc":"short task","cat":"Brakes","est":340,"safety":true,"why":"what was seen"}],"summary":"one sentence"}`,{images:files,nocache:true}); ui.reconAI={vid,tasks:(r.tasks||[]).map((t,i)=>({...t,i,on:true}))}; o.innerHTML=`
✦ ${esc(r.summary||'Suggested tasks')}${ui.reconAI.tasks.map(t=>``).join('')}
${esc(t.desc)}${t.safety?' Safety':''}
${esc(t.why||'')}
${esc(t.cat)}${$0(t.est)}
Estimates are AI guesses – confirm with your shop.
`}catch(e){o.innerHTML=`
${e.code==='images_unavailable'?'Photos aren\'t supported in this view – try notes only.':aiErrMsg(e)}
`}} function addReconAI(){const r=ui.reconAI;const v=veh(r.vid);let n=0;r.tasks.filter(t=>t.on).forEach(t=>{const est=+t.est||0;v.tasks.push({id:uid(),desc:t.desc,cat:RCATS.includes(t.cat)?t.cat:'Other',vendorId:'',est,actual:0,status:est>+S.settings.approvalLimit?'Needs Approval':'Approved',created:TODAY});n++});ui.reconAI=null;save();render();reconModal(v.id);toast(n+' task(s) added')} /* --- 8. deal document check --- */ function dealChecks(d){const v=veh(d.vehicleId),c=cust(d.customerId),l=d.loanId?loan(d.loanId):null,out=[];const add=(ok,t,lvl)=>out.push({ok,t,lvl:ok?'ok':lvl||'warn'}); const vd=decodeVin(v.vin);add(vd.ok&&vd.valid,vd.ok?(vd.valid?'VIN check digit is valid':'VIN check digit does not match – verify the VIN'):'VIN missing or wrong length','bad'); add(!!(c?.address&&c.address.length>8),'Buyer address on file','bad');add(!!c?.phone,'Buyer phone on file');add(+v.miles>0,'Odometer reading recorded','bad'); add(+d.taxRate>0||d.type==='Cash'&&+d.taxRate>0,'Sales tax applied ('+d.taxRate+'%)');add(+d.price>=vcost(v),'Sold at or above cost + recon ('+$0(vcost(v))+')'); if(d.tradeDesc){add(!!d.tradeVin&&d.tradeVin.length===17,'Trade-in VIN recorded','bad');add(+d.tradeAllow>0,'Trade allowance entered')} if(d.type!=='Cash'){add(+d.down>=d.total*0.1,'Down payment is at least 10% ('+$0(d.down)+' of '+$0(d.total)+')');if(c?.income){const pti=d.payment*FREQ[d.freq].ppy/12/c.income;add(pti<=0.2,`Payment-to-income ${(pti*100).toFixed(1)}% (target ≤ 20%)`)}else add(false,'No income on file to check payment-to-income'); if(+S.settings.aprCap>0)add(+d.apr<=+S.settings.aprCap,`APR ${d.apr}% within your state cap of ${S.settings.aprCap}%`,'bad');add(true,'Financed deals: print the Agreement to Provide Insurance and verify coverage before delivery','info');} if(d.type==='Retail Finance')add(!!d.lender,'Lender name recorded'); add(true,"Display the official FTC Buyers Guide and give the buyer a signed copy",'info'); return out} function checksHtml(d){const cs=dealChecks(d);const bad=cs.filter(x=>x.lvl==='bad').length,warn=cs.filter(x=>x.lvl==='warn').length; return `
${bad?`${bad} problem(s) · `:''}${warn?`${warn} warning(s) · `:''}${cs.filter(x=>x.ok&&x.lvl==='ok').length} passed
${cs.map(x=>`
${x.lvl==='ok'?'✓':x.lvl==='info'?'ℹ':x.lvl==='bad'?'✕':'!'}${esc(x.t)}
`).join('')} ${aiOn('doccheck')?`
${aiBtn('AI review of this deal',`aiDealReview('${d.id}')`)}
`:''}
`} async function aiDealReview(id){const d=S.deals.find(x=>x.id===id),v=veh(d.vehicleId),c=cust(d.customerId);const o=$('#aidr');o.innerHTML='
✦ Reviewing…
'; try{const t=await ai(`${dealerCtx()} Act as a careful F&I compliance reviewer for a used-car dealer. Review this deal and list anything that looks risky, inconsistent or missing before the paperwork is signed (math errors, missing info, high payment-to-income, thin down payment, pricing below cost, trade issues, required federal disclosures). Be specific and brief; note that state rules vary. Don't repeat items that are fine. Deal: ${JSON.stringify({type:d.type,date:d.date,price:d.price,doc_fee:d.docFee,tax_rate:d.taxRate,tax:d.tax,other_fees:d.otherFees,trade:d.tradeDesc,trade_vin:d.tradeVin,trade_allow:d.tradeAllow,trade_payoff:d.tradePayoff,down:d.down,total:d.total,amount_financed:d.financed,apr:d.apr,term:d.term,frequency:d.freq,payment:d.payment,finance_charge:d.financeCharge,total_of_payments:d.totalOfPayments,lender:d.lender})} Vehicle: ${JSON.stringify({vehicle:vname(v),vin:v.vin,miles:v.miles,cost_with_recon:vcost(v)})} Buyer: ${JSON.stringify({has_address:!!c?.address,has_phone:!!c?.phone,monthly_income:c?.income||null,employer:c?.employer||''})} Automated checks: ${JSON.stringify(dealChecks(d).map(x=>x.t+(x.ok?' (ok)':' (FAIL)')))} Reply in plain text: a one-line verdict, then up to 6 short bullet points starting with "- ".`,{text:true});o.innerHTML=`
${esc(t)}
`}catch(e){o.innerHTML=`
${aiErrMsg(e)}
`}} /* --- 9. ask DealerPen --- */ function snapshot(){const m={};S.deals.forEach(d=>{const k=d.date.slice(0,7);m[k]=m[k]||{units:0,gross:0};m[k].units++;m[k].gross+=d.gross});const cash={};S.txns.forEach(t=>{const k=t.date.slice(0,7)+' '+t.cat;cash[k]=r2((cash[k]||0)+t.amount)}); return JSON.stringify({today:TODAY,dealer:S.settings.dealer,settings:{tax:S.settings.taxRate,doc_fee:S.settings.docFee,late_fee:S.settings.lateFee,grace_days:S.settings.graceDays,recon_budget:S.settings.reconBudget,recon_target_days:S.settings.reconTarget}, inventory:S.vehicles.map(v=>({stock:v.stock,vehicle:vname(v),status:v.status,miles:+v.miles,price:+v.price,cost:+v.cost,recon:reconTotal(v),days:age(v),recon_stage:v.status==='In Recon'?v.reconStage:undefined,days_in_recon:v.reconStart?reconDays(v):undefined})), deals:S.deals.map(d=>({no:d.no,date:d.date,type:d.type,customer:cust(d.customerId)?.name,vehicle:vname(veh(d.vehicleId)),price:d.price,front_gross:d.gross,doc_fee:d.docFee,financed:d.financed})),sales_by_month:m, bhph_accounts:S.loans.map(l=>({acct:l.acct,customer:cust(l.customerId)?.name,status:l.status,balance:l.balance,payment:l.payment,frequency:l.freq,days_late:daysLate(l),past_due:pastDue(l),late_fees:l.lateFeesDue,payments_made:l.payments.length,term:l.term,promise:l.promise})), customers:S.customers.map(c=>({name:c.name,stage:c.stage,source:c.source,follow_up:c.followUp})),ledger_by_month_and_category:cash, comms_last_30_days:S.comms.filter(x=>x.at.slice(0,10)>=addDays(TODAY,-30)).length})} async function aiAsk(q){q=(q||'').trim();if(!q)return;ui.askLog.push({role:'user',content:q});busy.ask=true;render(); const intro=`${dealerCtx()}\nYou answer the dealer's questions about their own business using ONLY the DealerPen data below. Do the math carefully, show key numbers, say when the data doesn't contain the answer, and keep answers short (bullets are fine). Data (JSON): ${snapshot()}`; const turns=[{role:'user',content:intro},...ui.askLog.slice(-10)];if(turns[1]&&turns[1].role==='assistant')turns.splice(1,1); try{const t=await ai(turns,{text:true,nocache:true});ui.askLog.push({role:'assistant',content:t})}catch(e){ui.askLog.push({role:'assistant',content:'⚠ '+aiErrMsg(e)})}busy.ask=false;render()} /* --- 10. AI BDC: outbound follow-up campaigns across voice providers --- */ const PROVIDERS=[['vapi','Vapi'],['retell','Retell AI'],['bland','Bland AI'],['synthflow','Synthflow'],['elevenlabs','ElevenLabs Agents'],['twilio','Twilio + custom agent'],['other','Other provider']]; const pname=k=>(PROVIDERS.find(p=>p[0]===k)||[,k])[1]; const CTYPES={ lead:['New lead follow-up','Open leads with no contact in 2+ days',()=>S.customers.filter(c=>['New','Contacted'].includes(c.stage)&&(()=>{const m=lastMsg(c.id);return !m||diff(m.at.slice(0,10),TODAY)>=2})()).map(c=>({c}))], unsold:['Unsold / lost lead re-engagement','Contacted or lost leads to win back',()=>S.customers.filter(c=>c.stage==='Lost'||c.stage==='Contacted'&&c.followUp&&c.followUp<=TODAY).map(c=>({c}))], appt:['Appointment confirmation','Appointments in the next 2 days',()=>S.customers.filter(c=>c.stage==='Appointment'&&c.followUp&&c.followUp>=TODAY&&c.followUp<=addDays(TODAY,2)).map(c=>({c}))], noshow:['Missed appointment','Appointment date passed, no sale',()=>S.customers.filter(c=>c.stage==='Appointment'&&c.followUp&&c.followUp({c}))], postsale:['Post-sale check-in','Deals delivered 3–14 days ago',()=>S.deals.filter(d=>{const n=diff(d.date,TODAY);return n>=3&&n<=14}).map(d=>({c:cust(d.customerId),d}))], payrem:['Payment reminder (BHPH)','Payments due in the next 3 days',()=>S.loans.filter(l=>{const n=nextDue(l);return n&&daysLate(l)===0&&n>=TODAY&&n<=addDays(TODAY,3)}).map(l=>({c:cust(l.customerId),l}))], pastdue:['Past-due follow-up (BHPH)','Accounts 1+ days late',()=>S.loans.filter(l=>daysLate(l)>0).map(l=>({c:cust(l.customerId),l}))], rebuy:['Trade-up / repeat buyer','Paid-off or 70%+ paid accounts in good standing',()=>S.loans.filter(l=>l.status==='Paid Off'||l.status==='Active'&&daysLate(l)===0&&paidCount(l)/l.term>=0.7).map(l=>({c:cust(l.customerId),l}))]}; function bdcVars(r){const c=r.c,l=r.l,d=r.d;const v=l?veh(l.vehicleId):d?veh(d.vehicleId):null;return{phone:'+'+digits(c.phone),first_name:c.name.split(' ')[0],full_name:c.name,dealer:S.settings.dealer,dealer_phone:S.settings.phone,vehicle:v?vname(v):(c.interest||''),appointment:c.followUp||'',acct:l?.acct||'',payment:l?l.payment:'',due_date:l?nextDue(l)||'':'',past_due:l?pastDue(l):'',days_late:l?daysLate(l):'',salesperson:S.settings.user}} function bdcAudience(cp){const raw=CTYPES[cp.type][2]().filter(r=>r.c);const ok=[],skip=[];raw.forEach(r=>{const c=r.c;const why=!c.phone?'no phone':c.optOut?'opted out':c.dnc?'do-not-call':!c.smsConsent?'no consent':'';const tries=S.bdc.results.filter(x=>x.campaignId===cp.id&&x.customerId===c.id).length; if(why)skip.push([r,why]);else if(tries>=+cp.attempts)skip.push([r,'max attempts reached']);else ok.push(r)});return{ok,skip}} function bdcCampaignModal(id){const cp=id?S.bdc.campaigns.find(x=>x.id===id):{name:'',type:'lead',provider:'vapi',active:true,days:'Mon–Sat',start:'09:00',end:'19:00',attempts:3,gap:24,voice:'Friendly, upbeat',transfer:S.settings.phone,script:null}; openModal(mh(id?'Edit BDC campaign':'New BDC campaign')+`
Calls only go to customers who agreed to texts and automated calls, haven't opted out and aren't on your do-not-call list. Keep calling hours within 8am–9pm in the customer's time zone. AI voice calls count as artificial-voice calls under federal telemarketing rules, so prior consent is required.
${id?'':''}
`); if(id)$('#bcd').onclick=()=>{S.bdc.campaigns=S.bdc.campaigns.filter(x=>x.id!==id);save();closeModal();render()}; $('#bcf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);const n=id?cp:{id:uid(),created:TODAY,script:null};const typeChanged=id&&cp.type!==x.type;Object.assign(n,x,{active:!!x.active,attempts:+x.attempts||1,gap:+x.gap||24});if(typeChanged)n.script=null;if(!id)S.bdc.campaigns.push(n);ui.bdcSel=n.id;save();closeModal();render();toast('Campaign saved')}} async function aiBdcScript(id){const cp=S.bdc.campaigns.find(x=>x.id===id);busy['bdc'+id]=true;render(); try{const r=await ai(`${dealerCtx()} Write the setup for an outbound AI phone agent used by this used-car dealership's BDC (business development center). Provider: ${pname(cp.provider)}. Campaign: ${CTYPES[cp.type][0]} – ${CTYPES[cp.type][1]}. Voice/tone: ${cp.voice}. Calling window: ${cp.days} ${cp.start}-${cp.end}. Transfer hot or complex calls to ${cp.transfer}. Available per-call variables, written as {{name}}: {{first_name}}, {{full_name}}, {{dealer}}, {{dealer_phone}}, {{vehicle}}, {{appointment}}, {{acct}}, {{payment}}, {{due_date}}, {{past_due}}, {{days_late}}, {{salesperson}}. Requirements: open by saying the agent is an automated assistant calling for the dealer; for account calls verify identity before discussing any balance, otherwise leave a short callback message with no account details; respectful, no pressure tactics, no threats, no false statements; never promise financing approval or rates; honor "stop calling"/"remove me" immediately and mark do_not_call; offer transfer to a person; book appointments with a specific day and time when relevant; keep the call under 3 minutes. Reply with only JSON: {"first_message":"what the agent says when the call connects","system_prompt":"full agent instructions, under 400 words","voicemail":"under 25 seconds","outcomes":["appointment_set","promise_to_pay","callback_requested","not_interested","wrong_number","do_not_call","no_answer","voicemail","transferred"]}`,{nocache:true});cp.script=r;save()}catch(e){toast(aiErrMsg(e))}busy['bdc'+id]=false;render()} function bdcCSV(cp){const a=bdcAudience(cp).ok;const keys=['phone','first_name','full_name','dealer','dealer_phone','vehicle','appointment','acct','payment','due_date','past_due','days_late','salesperson']; return 'campaign_id,'+keys.join(',')+'\n'+a.map(r=>{const v=bdcVars(r);return [cp.id,...keys.map(k=>'"'+String(v[k]??'').replace(/"/g,'""')+'"')].join(',')}).join('\n')} async function bdcExport(id){const cp=S.bdc.campaigns.find(x=>x.id===id);const csv=bdcCSV(cp);if(!bdcAudience(cp).ok.length)return toast('Nobody to call in this campaign right now'); if(DL){try{await DL.save({filename:`bdc-${cp.name.replace(/\W+/g,'-').toLowerCase()||'campaign'}-${TODAY}.csv`,data:csv});toast('Call list saved – upload it to '+pname(cp.provider))}catch(e){if(e.code!=='declined')copyText(csv)}}else copyText(csv)} function bdcApply(cp,rows){let n=0;rows.forEach(r=>{const dg=digits(r.phone);const c=S.customers.find(x=>digits(x.phone)===dg);if(!c)return;const out=String(r.outcome||'').toLowerCase().replace(/\s+/g,'_'); const l=S.loans.find(x=>x.customerId===c.id&&x.status==='Active');const isAcct=['payrem','pastdue'].includes(cp.type); S.bdc.results.push({id:uid(),campaignId:cp.id,customerId:c.id,at:nowAt(),outcome:out,summary:r.summary||'',provider:cp.provider}); logComm({customerId:c.id,loanId:isAcct&&l?l.id:null,channel:'call',dir:'out',body:'[AI BDC – '+pname(cp.provider)+'] '+(r.summary||''),outcome:out.replace(/_/g,' '),duration:+r.duration||0,by:'AI BDC'}); if(/^\d{4}-\d\d-\d\d/.test(r.appointment_date||'')){c.stage='Appointment';c.followUp=r.appointment_date.slice(0,10)} if(isAcct&&l&&/^\d{4}-\d\d-\d\d/.test(r.promise_date||'')&&+r.promise_amount)l.promise={date:r.promise_date.slice(0,10),amount:+r.promise_amount}; if(out==='do_not_call'){c.dnc=true;c.notes.push({date:TODAY,by:'AI BDC',text:'Asked not to be called – marked do-not-call'})} if(out==='callback_requested'&&!isAcct)c.followUp=addDays(TODAY,1);n++});save();return n} function parseCSV(t){const lines=t.trim().split(/\r?\n/);const split=s=>{const o=[];let cur='',q=false;for(const ch of s){if(ch==='"')q=!q;else if(ch===','&&!q){o.push(cur);cur=''}else cur+=ch}o.push(cur);return o.map(x=>x.trim())};const h=split(lines.shift()).map(x=>x.toLowerCase());return lines.filter(Boolean).map(l=>{const v=split(l);return Object.fromEntries(h.map((k,i)=>[k,v[i]||'']))})} function bdcImportModal(id){const cp=S.bdc.campaigns.find(x=>x.id===id);openModal(mh(`Import call results · ${esc(cp.name)}`)+`

Paste the results export from ${esc(pname(cp.provider))}. Either a CSV with columns phone, outcome, summary, appointment_date, promise_date, promise_amount, duration, or the raw export / transcripts and let AI read it.

${aiOn('bdc')?aiBtn('Let AI read it',`bdcAIRead('${id}')`):''}
`); $('#brg').onclick=()=>{try{const rows=parseCSV($('#bri').value);if(!rows.length||!('phone' in rows[0]))throw 0;const n=bdcApply(cp,rows);closeModal();render();toast(n+' result(s) logged')}catch(e){toast('Needs a header row with at least phone and outcome')}}} async function bdcAIRead(id){const cp=S.bdc.campaigns.find(x=>x.id===id);const raw=$('#bri').value.trim();if(!raw)return toast('Paste the results first');$('#brio').innerHTML='
✦ Reading results…
'; try{const rows=await ai(`These are outbound call results or transcripts exported from ${pname(cp.provider)} for a car dealer's "${CTYPES[cp.type][0]}" campaign. Extract one record per call. Outcomes must be one of: appointment_set, promise_to_pay, callback_requested, not_interested, wrong_number, do_not_call, no_answer, voicemail, transferred, other. Today is ${TODAY}; turn relative dates into YYYY-MM-DD. Reply with only a JSON array: [{"phone":"+15551234567","outcome":"","summary":"one sentence","appointment_date":"","promise_date":"","promise_amount":0,"duration":0}] Data: ${raw.slice(0,60000)}`,{tier:'quick',nocache:true});const n=bdcApply(cp,Array.isArray(rows)?rows:[]);closeModal();render();toast(n+' result(s) logged')}catch(e){$('#brio').innerHTML=`
${aiErrMsg(e)}
`}} function bdcView(head){const cs=S.bdc.campaigns;if(!ui.bdcSel&&cs[0])ui.bdcSel=cs[0].id;const cp=cs.find(x=>x.id===ui.bdcSel); const stat=c=>{const rs=S.bdc.results.filter(x=>x.campaignId===c.id);const reach=rs.filter(x=>!['no_answer','voicemail','wrong_number'].includes(x.outcome)).length;return{calls:rs.length,reach,appt:rs.filter(x=>x.outcome==='appointment_set').length,ptp:rs.filter(x=>x.outcome==='promise_to_pay').length}}; const all=S.bdc.results; let body=`
${kpi('Active campaigns',cs.filter(c=>c.active).length,cs.length+' total')}${kpi('AI calls logged',all.length,all.filter(x=>x.at.slice(0,10)===TODAY).length+' today')}${kpi('Contact rate',all.length?Math.round(all.filter(x=>!['no_answer','voicemail','wrong_number'].includes(x.outcome)).length/all.length*100)+'%':'—','reached a person')}${kpi('Appointments set',all.filter(x=>x.outcome==='appointment_set').length,'by AI BDC')}${kpi('Promises to pay',all.filter(x=>x.outcome==='promise_to_pay').length,'by AI BDC')}
Campaigns
${cs.map(c=>{const a=bdcAudience(c).ok.length,s=stat(c);return `
${esc(c.name)}
${esc(pname(c.provider))} · ${a} to call · ${s.calls} logged
${c.active?'':'Off'}
`}).join('')||'
Create your first campaign
'}
`; if(cp){const au=bdcAudience(cp),s=stat(cp),sc=cp.script; body+=`

${esc(cp.name)} ${esc(pname(cp.provider))} ${cp.active?'Active':'Paused'}

${esc(CTYPES[cp.type][0])} – ${esc(CTYPES[cp.type][1])} · ${esc(cp.days)} ${cp.start}–${cp.end} · up to ${cp.attempts} attempts, ${cp.gap}h apart · transfers to ${esc(cp.transfer)}
Ready to call${au.ok.length}
Calls logged${s.calls}
Reached${s.calls?Math.round(s.reach/s.calls*100)+'%':'—'}
${['payrem','pastdue'].includes(cp.type)?'Promises':'Appointments'}${['payrem','pastdue'].includes(cp.type)?s.ptp:s.appt}
1 · Agent script${sc?`
First message: “${esc(sc.first_message)}”
Show full agent instructions
${esc(sc.system_prompt)}
Voicemail: ${esc(sc.voicemail)}
Outcomes: ${esc((sc.outcomes||[]).join(', '))}
${aiOn('bdc')?aiBtn(busy['bdc'+cp.id]?'Writing…':'Rewrite',`aiBdcScript('${cp.id}')`):''}
`:aiOn('bdc')?`
Generate the agent's opening line, instructions and voicemail, written for ${esc(pname(cp.provider))}.
${aiBtn(busy['bdc'+cp.id]?'Writing…':'Write agent script',`aiBdcScript('${cp.id}')`)}
`:'
Turn on AI to generate the script.
'}
2 · Call list
${au.ok.length} customer(s) with every merge field filled in. Upload to ${esc(pname(cp.provider))} as an outbound campaign or batch call.
3 · Results
Bring outcomes back: appointments, promises to pay, call-backs and do-not-call requests update each customer automatically.
${au.ok.map(r=>{const v=bdcVars(r);const t=S.bdc.results.filter(x=>x.campaignId===cp.id&&x.customerId===r.c.id).length;return ``}).join('')}${au.skip.map(([r,why])=>``).join('')||''}${!au.ok.length&&!au.skip.length?'':''}
CustomerPhoneContextAttempts
${esc(r.c.name)}${esc(r.c.phone)}${esc(r.l?`${r.l.acct} · ${daysLate(r.l)?daysLate(r.l)+' days late':'due '+fdate(nextDue(r.l))}`:v.vehicle||r.c.stage)}${t}/${cp.attempts}${cbtn(r.c.id,r.l?.id)}
${esc(r.c.name)}${esc(r.c.phone)}Skipped: ${why}
Nobody matches this campaign right now
${S.bdc.results.filter(x=>x.campaignId===cp.id).length?`
${S.bdc.results.filter(x=>x.campaignId===cp.id).slice().reverse().map(x=>``).join('')}
WhenCustomerOutcomeSummary
${ftime(x.at)}${esc(cust(x.customerId)?.name)}${esc(x.outcome.replace(/_/g,' '))}${esc(x.summary)}
`:''}`} body+=`

DealerPen prepares each campaign for the provider you pick: the agent script, a call list with merge fields, and importing the results. It can't dial from this page. Fully hands-off calling (campaigns launching on schedule, results flowing back live) needs a small server holding your provider API keys, which is part of the backend build.

`; return head+body} /* --- AI hub view --- */ VIEWS.ai=()=>{const tabs=[['bdc','AI BDC'],['collections','Collections'],['leads','Lead responder'],['ask','Ask DealerPen'],['pricing','Pricing review'],['voice','Voice agent']].filter(t=>aiOn(t[0])); if(!tabs.length)return `
All AI features are turned off. Turn them on in Settings → AI features.
`; if(!tabs.some(t=>t[0]===ui.aiTab))ui.aiTab=tabs[0][0]; const head=aiNote()+`
${tabs.map(t=>``).join('')}
`; const T=ui.aiTab; if(T==='bdc')return bdcView(head); if(T==='collections'){const rs=S.loans.map(risk).filter(r=>r&&r.include).sort((a,b)=>b.score-a.score); return head+`
${rs.length} accounts need attention, ranked by risk score (payment history, days late, broken promises, time since last contact).${aiBtn(busy.plan?'Writing call plan…':'Generate AI call plan','aiPlan()')}
${ui.aiPlan&&ui.aiPlan.length?`
${ui.aiPlan.map(p=>{const l=S.loans.find(x=>x.acct===p.acct);if(!l)return'';const c=cust(l.customerId);return `

#${p.priority} ${esc(c.name)} ${l.acct}${riskPill(({repo:'Repo risk',high:'High',medium:'Medium',low:'Low'})[p.risk]||'Medium')}

${esc(p.summary||'')}

Approach${esc(p.approach||'')}
Say“${esc(p.opener||'')}”
Ask for${esc(p.ask||'')}
If no answer, text${esc(p.text||'')}
`}).join('')}

Plan generated ${ftime(ui.aiPlanAt)}. AI suggestions – use your judgment and follow federal and state collection rules.

`:''}
${rs.map((r,i)=>{const c=cust(r.l.customerId);return ``}).join('')||''}
#CustomerRiskScoreWhyPast due
${i+1}${esc(c.name)}
${r.l.acct}
${riskPill(r.lvl)}${r.score}${r.why.map(w=>`${esc(w)}`).join(' ')}${$$(pastDue(r.l))}${cbtn(c.id,r.l.id)}
Nothing to work today 🎉
`} if(T==='leads'){const leads=S.customers.filter(isOpenLead).sort((a,b)=>(lastMsg(b.id)?.at||b.created).localeCompare(lastMsg(a.id)?.at||a.created));const waiting=leads.filter(needsReply); return head+`
${waiting.length} lead(s) waiting for a reply${aiBtn(busy.leads?'Drafting…':'Draft replies for all waiting','aiLeads(S.customers.filter(c=>isOpenLead(c)&&needsReply(c)).map(c=>c.id))')}
${leads.map(c=>{const d=ui.leadDrafts[c.id],m=lastMsg(c.id),blk=canText(c);return `

${esc(c.name)} ${stagePill(c.stage)} ${esc(c.source)} · ${esc(c.phone)}${needsReply(c)?'Needs reply':''}

${m?(m.dir==='in'?'They said: ':'You said: ')+esc(m.channel==='call'?'[call] '+m.outcome:m.body):'No messages yet'}
${d?`
${esc(d.temperature||'')}${esc(d.intent||'')}${Object.entries(d.qualification||{}).filter(([k,v])=>v).map(([k,v])=>`${esc(k.replace('_',' '))}: ${esc(v)}`).join('')}${(d.suggested_stock||[]).map(s=>`${esc(s)}`).join('')}
Next step: ${esc(d.next_step||'')}${d.appointment?' · suggested appointment '+fdate(d.appointment):''}
${blk?`${blk}`:`✉ Open in Messages`}
`:`
${aiBtn(busy.leads?'Drafting…':'Draft reply',`aiLeads(['${c.id}'])`)}
`}
`}).join('')||'
No open leads
'}

Replies are drafted for you to review and send from your phone. Fully automatic replies (answering within seconds, day and night) need a texting provider such as Twilio connected to a server.

`} if(T==='ask'){const sug=['Who should I call first today and why?','What was my total front gross by month?','Which cars have been in stock the longest and what did I spend on them?','How much BHPH principal is past due, and what percent of the portfolio is that?','Which lead sources are converting best?']; return head+`
${ui.askLog.map(m=>`
${esc(m.content)}
`).join('')||`
Ask anything about your inventory, deals, accounts, leads or money.
${sug.map(s=>``).join('')}
`}${busy.ask?'
✦ Thinking…
':''}
${ui.askLog.length?'':''}
`} if(T==='pricing'){const rows=ui.priceAI||[];return head+`
Reviews ${S.vehicles.filter(v=>['Available','Pending'].includes(v.status)).length} units using days in stock, margin, recon and holding cost. It has no live market data, so check comparable listings before big moves.${aiBtn(busy.pricing?'Reviewing…':'Run pricing review','aiPricing()')}
${rows.map(r=>{const v=S.vehicles.find(x=>x.stock===r.stock);if(!v)return'';return ``}).join('')||''}
VehicleDaysCost + reconPriceRecommendationNew priceWhy
${v.stock} ${esc(vname(v))}${ageCell(age(v))}${$0(vcost(v))}${$0(v.price)}${esc(r.action)}${r.new_price?$0(r.new_price):'—'}${esc(r.reason)}${r.action==='wholesale'?``:r.new_price&&+r.new_price!==+v.price?``:''}
Run a review to get recommendations
`} if(T==='voice'){const vl=voiceList();return head+`

Agent instructions${aiBtn(busy.voice?'Writing…':(ui.voicePrompt?'Rewrite':'Write instructions'),'aiVoice()')}

Paste these into your AI phone agent (for example your Vapi assistant's system prompt). It's written around your late fee, grace period and collection rules.

Today's call list

Upload this to your voice agent's outbound campaign. Opted-out customers and those without a phone are left out. Log the agent's results back on each account.

${vl.map(r=>{const c=cust(r.l.customerId);return ``}).join('')||''}
CustomerPhoneRiskPast due
${esc(c.name)}
${r.l.acct}
${esc(c.phone)}${riskPill(r.lvl)}${$$(pastDue(r.l))}
Nobody to call

DealerPen can't place AI calls from this page. A live connection (calls placed automatically, results logged back) needs your voice agent and a small server linking it to DealerPen.

`} return head}; AFTER.ai=()=>{const f=$('#askf');if(f){f.onsubmit=e=>{e.preventDefault();const q=$('#askq').value;aiAsk(q)};const m=$('#askmsgs');if(m)m.scrollTop=m.scrollHeight;if(!busy.ask)$('#askq').focus()}}; /* ---- collections ---- */ const BUCKETS=[['all','All past due',1,1e9],['1-15','1–15 days',1,15],['16-30','16–30',16,30],['31-60','31–60',31,60],['61+','61+',61,1e9]]; VIEWS.collections=()=>{const act=S.loans.filter(l=>l.status==='Active');const late=act.filter(l=>daysLate(l)>0); const b=BUCKETS.find(x=>x[0]===ui.colBucket);const list=late.filter(l=>{const d=daysLate(l);return d>=b[2]&&d<=b[3]}).sort((a,b)=>daysLate(b)-daysLate(a)); const promises=act.filter(l=>l.promise);const dueSoon=act.filter(l=>{const n=nextDue(l);return n&&n>=TODAY&&n<=addDays(TODAY,3)}); return (aiOn('collections')?`
✦ AI call plan: see who to call first today and what to say Open →
`:'')+`
${BUCKETS.map(x=>{const n=late.filter(l=>daysLate(l)>=x[2]&&daysLate(l)<=x[3]).length;return ``}).join('')}
${list.map(l=>{const c=cust(l.customerId);const lp=l.payments[l.payments.length-1];const ln=l.notes[l.notes.length-1];const broken=l.promise&&l.promise.date`}).join('')||''}
AccountCustomerDays latePast dueLate feesLast paymentPromiseLast note
${l.acct}${esc(c?.name)}
${esc(c?.phone)}
${latePill(daysLate(l))}${$$(pastDue(l))}${$$(l.lateFeesDue)}${lp?fdate(lp.date)+'
'+$$(lp.amount)+'
':'—'}
${l.promise?`${broken?'Broken':'Due'} ${fdate(l.promise.date)}`:'—'}${ln?esc(ln.text.slice(0,80)):'—'}${cbtn(l.customerId,l.id)}
No accounts in this bucket

Promises to pay

${promises.length?`${promises.map(l=>``).join('')}
${esc(cust(l.customerId)?.name)}${fdate(l.promise.date)}${$$(l.promise.amount)}${l.promise.dateBroken':'Pending'}
`:'
None
'}

Payment reminders (due in next 3 days)

${dueSoon.length?`${dueSoon.map(l=>``).join('')}
${esc(cust(l.customerId)?.name)}
${esc(cust(l.customerId)?.phone)}
${fdate(nextDue(l))}${$$(l.payment)}${cbtn(l.customerId,l.id)}
`:'
None
'}
`}; function reminder(id){const L=loan(id);return textModal(L.customerId,id,'Payment reminder');const l=loan(id),c=cust(l.customerId);const t=`Hi ${c.name.split(' ')[0]}, this is ${S.settings.dealer}. Friendly reminder your payment of ${$$(l.payment)} on account ${l.acct} is due ${fdate(nextDue(l))}. Questions? Call ${S.settings.phone}.`; openModal(mh('Reminder text')+`
${esc(t)}

Send from your phone or SMS tool. Make sure you have the customer's consent to receive texts.

`);$('#cp').onclick=()=>copyText(t)} /* ---- forms center ---- */ let DL=null; const F={ hdr:(title,ctx,sub)=>{const st=S.settings,ini=st.dealer.split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase();return `
${esc(st.dealer)}
${esc(st.address)}
${esc(st.phone)}
${title}
${sub?`
${sub}
`:''}
`}, grid:(rows)=>`${rows.map(r=>`${r.map(c=>``).join('')}`).join('')}
${c[0]}${c[1]===''||c[1]==null?' ':esc(c[1])}
`, sig:(...who)=>`
${who.map(w=>{const sg=CURSIGS&&CURSIGS[sigRole(w)];return `
${sg?``:'✕'}
${w}Date ${sg?esc(fdate(sg.at.slice(0,10))):''}
`}).join('')}
`, money:(rows)=>`${rows.map(r=>``).join('')}
${r[0]}${typeof r[1]==='number'?$$(r[1]):esc(r[1])}
`, buyer:c=>[['Buyer',c?.name],['Phone',c?.phone],['Address',c?.address,2]], vehicle:v=>[['Year',v.year],['Make',v.make],['Model',v.model+' '+(v.trim||'')],['Color',v.color]], vin:v=>[['VIN',v.vin,2],['Stock #',v.stock],['Odometer',(+v.miles).toLocaleString()+' mi']], note:t=>`
i
${t}
`}; const FORMS=[ {id:'bos',g:'Sale',n:"Buyer's Order / Bill of Sale",need:'deal',f:({d,v,c})=>F.hdr("Buyer's Order & Bill of Sale",0,`Deal #${d.no} · ${fdate(d.date)}`)+F.grid([F.buyer(c),F.vehicle(v),F.vin(v)])+ `
${F.money([['Cash price of vehicle',+d.price],['Documentation fee',+d.docFee],['Other fees (title, registration)',+d.otherFees],['Trade-in allowance',-(+d.tradeAllow)],['Sales tax ('+d.taxRate+'%)',d.tax],['Total cash price',d.total,'tot'],['Payoff owed on trade',+d.tradePayoff],[d.type==='Cash'?'Paid at delivery':'Down payment',d.type==='Cash'?d.cashDue:+d.down],['Unpaid balance',d.type==='Cash'?0:d.financed,'tot']])}
${F.grid([[['Sale type',d.type==='BHPH'?'In-house financing':d.type]],[['Trade-in',d.tradeDesc||'None']],[['Trade VIN',d.tradeVin||'']],[['Lienholder',d.type==='BHPH'?S.settings.dealer:d.type==='Retail Finance'?(d.lender||''):'None']]])} ${F.note('The information on the Buyers Guide displayed on this vehicle is part of this contract and overrides any contrary provisions in the contract of sale. Unless a separate written warranty is provided, this vehicle is sold AS IS. Buyer acknowledges receiving a copy of this agreement.')}
`+F.sig('Buyer','Co-buyer','Dealer representative')}, {id:'bg',g:'Sale',n:'Buyers Guide (data sheet)',need:'deal',f:({v})=>F.hdr('Buyers Guide Information',0,'Used vehicle')+F.grid([F.vehicle(v),F.vin(v)])+ `
WARRANTIES FOR THIS VEHICLE

☐ AS IS – NO DEALER WARRANTY. The dealer does not provide a warranty for any repairs after sale.

☐ DEALER WARRANTY   ☐ Full   ☐ Limited — Dealer pays ____% of labor and ____% of parts for covered systems that fail during the warranty period.

Systems covered: ______________________________________   Duration: ____________________

☐ Manufacturer's warranty still applies   ☐ Service contract available for extra charge

`+ F.note('Important: federal law (FTC Used Car Rule) requires the official Buyers Guide window form to be displayed on every used vehicle offered for sale, and a copy given to the buyer. Use this sheet to fill in the official form; it does not replace it. Spanish version required when the sale is conducted in Spanish.')+F.sig('Buyer acknowledges receipt of the Buyers Guide at closing')}, {id:'odo',g:'Sale',n:'Odometer Disclosure Statement',need:'deal',f:({d,v,c})=>F.hdr('Odometer Disclosure Statement',0,fdate(d.date))+ `

Federal law (and state law, if applicable) requires that you state the mileage upon transfer of ownership. Failure to complete this statement, or providing a false statement, may result in fines and/or imprisonment.

I,  ${esc(S.settings.dealer)} , state that the odometer now reads  ${(+v.miles).toLocaleString()}  miles (no tenths) and to the best of my knowledge it reflects the actual mileage of the vehicle described below, unless one of the following boxes is checked:

☐ The mileage stated is in excess of its mechanical limits.    ☐ The odometer reading is NOT the actual mileage. WARNING – ODOMETER DISCREPANCY.

`+ F.grid([F.vehicle(v),[['VIN',v.vin,2],['Body type',''],['Stock #',v.stock]],[['Transferor (seller)',S.settings.dealer,2],['Seller address',S.settings.address,2]],[['Transferee (buyer)',c?.name,2],['Buyer address',c?.address,2]]])+F.sig('Transferor signature & printed name','Transferee signature & printed name')+F.note('Many states require the odometer disclosure on the title itself or a state form. Check your state requirements.')}, {id:'risc',g:'Finance',n:'Retail Installment Contract (summary)',need:'fin',f:({d,v,c})=>F.hdr('Retail Installment Sale Contract',0,`Deal #${d.no} · ${fdate(d.date)}`)+F.grid([F.buyer(c),[['Seller / Creditor',d.type==='BHPH'?S.settings.dealer:(d.lender||''),2],['Vehicle',vname(v),2]],[['VIN',v.vin,2],['Odometer',(+v.miles).toLocaleString()],['Stock #',v.stock]]])+ `
ANNUAL PERCENTAGE RATEThe cost of your credit as a yearly rate
${(+d.apr).toFixed(2)}%
FINANCE CHARGEThe dollar amount the credit will cost you
${$$(d.financeCharge)}
Amount FinancedThe amount of credit provided to you
${$$(d.financed)}
Total of PaymentsWhat you will have paid after all scheduled payments
${$$(d.totalOfPayments)}
Total Sale PriceTotal cost of your purchase on credit, including down payment
${$$(d.totalOfPayments+ +d.down+ +d.tradeAllow-(+d.tradePayoff))}
`+ F.grid([[['Number of payments',d.term],['Amount of each payment',$$(d.payment)],['Frequency',FREQ[d.freq].label],['First payment due',fdate(addPeriods(d.date,d.freq,1))]],[['Late charge',`${$$(S.settings.lateFee)} if more than ${S.settings.graceDays} days late`,2],['Prepayment','No penalty for paying early',2]],[['Security','You are giving a security interest in the vehicle being purchased.',4]]])+ `

Itemization of amount financed

`+F.money([['Cash price (incl. tax & fees)',d.total],['Less trade-in allowance',-(+d.tradeAllow)],['Plus payoff on trade',+d.tradePayoff],['Less down payment',-(+d.down)],['Amount financed',d.financed,'tot']])+ F.note('Template notice: retail installment contracts are regulated state by state (rate caps, required wording, font sizes, arbitration and repossession terms). Have an attorney approve your contract form, or use your lender\'s or a licensed forms provider\'s contract. This page summarizes the federally required Truth-in-Lending disclosures for the deal.')+F.sig('Buyer','Co-buyer','Seller')}, {id:'ins',g:'Finance',n:'Agreement to Provide Insurance',need:'fin',f:({d,v,c})=>F.hdr('Agreement to Provide Insurance',0,fdate(d.date))+F.grid([F.buyer(c),F.vehicle(v),F.vin(v)])+ `

I agree to keep the vehicle described above insured against physical damage (comprehensive and collision) for as long as any amount is owed on it, with a deductible no higher than $________. The policy must list ${esc(d.type==='BHPH'?S.settings.dealer:(d.lender||'the lienholder'))} as loss payee / lienholder.

${F.grid([[['Insurance company',''],['Policy #',''],['Agent',''],['Agent phone','']],[['Effective date',''],['Expiration',''],['Deductible',''],['Verified by','']]])}

If the insurance lapses, I understand the lienholder may treat it as a default under my contract. I authorize the lienholder to contact my agent to verify coverage.

`+F.sig('Buyer','Co-buyer')}, {id:'sched',g:'Finance',n:'Payment Schedule',need:'bhph',f:({l,c,v})=>F.hdr('Payment Schedule',0,`Account ${l.acct}`)+F.grid([[['Customer',c?.name,2],['Vehicle',vname(v),2]],[['Amount financed',$$(l.principal)],['APR',l.apr+'%'],['Payment',$$(l.payment)+' '+FREQ[l.freq].label.toLowerCase()],['Number of payments',l.term]]])+ `${(()=>{const a=amort(l),h=Math.ceil(a.length/2);let o='';for(let i=0;i${y?``:''}`}return o})()}
#Due dateAmountPaid ✓#Due dateAmountPaid ✓
${x.n}${fdate(x.date)}${$$(x.pay)}${y.n}${fdate(y.date)}${$$(y.pay)}
`+F.note(`Payments may be made in person at ${esc(S.settings.address)}. Always get a receipt. A late charge of ${$$(S.settings.lateFee)} applies after ${S.settings.graceDays} days.`)}, {id:'poa',g:'Sale',n:'Power of Attorney (title)',need:'deal',f:({d,v,c})=>F.hdr('Limited Power of Attorney',0,'Motor vehicle title & registration')+ `

I/we,  ${esc(c?.name)} , of ${esc(c?.address||'')}, appoint ${esc(S.settings.dealer)} and its authorized employees as my attorney-in-fact for the limited purpose of signing any documents needed to apply for title and registration, transfer ownership, record a lien, and make odometer disclosures for the vehicle below.

`+F.grid([F.vehicle(v),F.vin(v)])+ `

This power of attorney is limited to the vehicle described and expires once title and registration are complete.

`+F.sig('Grantor (buyer)','Co-buyer')+`
Notary (if required by your state)

State of ____________ County of ____________ Subscribed and sworn before me on ____________

Notary signature ______________________ My commission expires ____________

`+F.note('Some states require their own power-of-attorney form, especially for odometer disclosures. Check with your state motor vehicle agency.')}, {id:'weowe',g:'Sale',n:'We Owe / Due Bill',need:'deal',f:({d,v,c})=>F.hdr('We Owe',0,`Deal #${d.no} · ${fdate(d.date)}`)+F.grid([F.buyer(c),[['Vehicle',vname(v),2],['Stock #',v.stock],['VIN',v.vin]]])+ `${''.repeat(6)}
Item the dealer agrees to provideEst. costPromised byDone
 

☐ Nothing is owed. Buyer acknowledges no other promises were made unless written above.

`+F.sig('Buyer','Dealer manager')}, {id:'priv',g:'Finance',n:'Privacy Notice',need:'fin',f:({d,c})=>F.hdr('Privacy Notice',0,fdate(d.date))+ `

Why we collect information. When you finance a vehicle with ${esc(S.settings.dealer)}, we collect personal information such as your name, address, phone, Social Security number, income, employment and payment history to process your credit application and service your account.

How we share it. We share information only as permitted by law: with service providers who help us process your transaction and service your account (for example, credit bureaus, payment processors, insurers), with lenders or assignees of your contract, and when required by law. We do not sell your information to outside companies for their marketing.

How we protect it. We use physical, electronic and procedural safeguards, and we limit access to employees who need it to serve you.

Questions? Call ${esc(S.settings.phone)}.

`+F.note('Template only. The federal Gramm-Leach-Bliley Act sets privacy-notice requirements for dealers that offer financing; the FTC publishes a model form. Have your counsel review your notice.')+F.sig('Customer acknowledges receipt: '+esc(c?.name||''))}, {id:'recap',g:'Internal',n:'Deal Recap (internal)',need:'deal',f:({d,v,c})=>F.hdr('Deal Recap',0,`Deal #${d.no} · INTERNAL – do not give to customer`)+F.grid([[['Customer',c?.name,2],['Vehicle',vname(v),2]],[['Stock #',v.stock],['Days in stock',diff(v.acquired,d.date)],['Type',d.type],['Lender',d.type==='BHPH'?'In-house':(d.lender||'—')]]])+ `

Gross

${F.money([['Sale price',+d.price],['Vehicle cost',-(+v.cost)],['Reconditioning',-reconTotal(v)],['Front gross',d.gross,'tot'],['Doc fee',+d.docFee],['Total gross',d.gross+ +d.docFee,'tot']])}

Funding

${F.money([['Down / cash received',d.type==='Cash'?d.cashDue:+d.down],['Amount financed',d.financed],['Sales tax to remit',d.tax],['Trade payoff to send',+d.tradePayoff]])}
`+F.sig('Salesperson','Manager')}, {id:'rcpt',g:'Sale',n:'Down Payment Receipt',need:'deal',f:({d,c,v})=>F.hdr('Receipt',0,`Deal #${d.no} · ${fdate(d.date)}`)+F.grid([[['Received from',c?.name,2],['Amount',$$(d.type==='Cash'?d.cashDue:d.down)],['Method','']],[['For',(d.type==='Cash'?'Payment in full':'Down payment')+' on '+vname(v)+' (stock '+v.stock+')',4]]])+F.sig('Received by')}, {id:'welcome',g:'BHPH letters',n:'Welcome Letter',need:'bhph',f:({l,c,v})=>F.hdr('Welcome',0,fdate(TODAY))+`

${esc(c?.name)}
${esc(c?.address||'')}

Dear ${esc((c?.name||'').split(' ')[0])},

Thank you for buying your ${esc(vname(v))} from ${esc(S.settings.dealer)}. Your account number is ${l.acct}.

Your ${FREQ[l.freq].label.toLowerCase()} payment is ${$$(l.payment)}, and your first payment is due ${fdate(l.firstDue)}. A payment schedule is enclosed. Please keep your receipts.

If you ever expect to be late, call us before the due date at ${esc(S.settings.phone)}. We're glad to work with you.

Sincerely,

${esc(S.settings.user)}
${esc(S.settings.dealer)}

`}, {id:'late',g:'BHPH letters',n:'Past-Due Notice',need:'bhph',f:({l,c,v})=>F.hdr('Past-Due Notice',0,fdate(TODAY))+`

${esc(c?.name)}
${esc(c?.address||'')}

Re: Account ${l.acct} – ${esc(vname(v))}

Dear ${esc((c?.name||'').split(' ')[0])},

Our records show your account is ${daysLate(l)} days past due. The amount needed to bring your account current is:

${F.money([['Past-due payments',pastDue(l)],['Late fees',l.lateFeesDue],['Total due now',pastDue(l)+l.lateFeesDue,'tot']])}

Please pay this amount or call us at ${esc(S.settings.phone)} by ${fdate(addDays(TODAY,10))} to discuss your account. If you have already paid, thank you, and please disregard this notice.

Sincerely,
${esc(S.settings.dealer)}

`+F.note('Collection letters must follow federal and state debt-collection and repossession rules. Review wording with counsel.')}, {id:'payoff',g:'BHPH letters',n:'Payoff Letter',need:'bhph',f:({l,c,v})=>{const g=addDays(TODAY,10);return F.hdr('Payoff Letter',0,fdate(TODAY))+`

${esc(c?.name)}
Re: Account ${l.acct} – ${esc(vname(v))}, VIN ${esc(v.vin)}

`+F.money([['Principal balance',l.balance],['Interest accrued to today',accrued(l)],['Late fees due',l.lateFeesDue],['Payoff as of '+fdate(TODAY),payoff(l),'tot'],['Payoff good through '+fdate(g),payoff(l,g),'tot'],['Daily interest after that',l.balance*l.apr/100/365]])+`

Send certified funds payable to ${esc(S.settings.dealer)}, ${esc(S.settings.address)}. Once paid in full, the lien will be released and title sent to the owner.

`}}, {id:'pif',g:'BHPH letters',n:'Paid-in-Full / Lien Release Letter',need:'bhph',f:({l,c,v})=>F.hdr('Paid in Full',0,fdate(l.closedDate||TODAY))+`

${esc(c?.name)}
${esc(c?.address||'')}

Congratulations! Account ${l.acct} for your ${esc(vname(v))} (VIN ${esc(v.vin)}) ${l.status==='Paid Off'?'has been paid in full':'[not yet paid in full – current balance '+$$(l.balance)+']'}.

${esc(S.settings.dealer)} releases its lien on this vehicle. The signed title / lien release is enclosed or will be filed with the state motor vehicle agency as required.

Thank you for your business. Ready for your next vehicle? Call ${esc(S.settings.phone)}.

`+F.sig('Authorized signature, '+esc(S.settings.dealer))}, {id:'stmt',g:'BHPH letters',n:'Account Statement',need:'bhph',f:({l,c,v})=>F.hdr('Account Statement',0,`Account ${l.acct} · ${fdate(TODAY)}`)+F.grid([[['Customer',c?.name,2],['Vehicle',vname(v),2]],[['Principal balance',$$(l.balance)],['Next due',fdate(nextDue(l))],['Past due',$$(pastDue(l))],['Late fees',$$(l.lateFeesDue)]]])+ `${l.payments.map(p=>``).join('')||''}
DateReceiptAmountFeesInterestPrincipalBalance
${fdate(p.date)}${p.receipt}${$$(p.amount)}${$$(p.fee)}${$$(p.interest)}${$$(p.principal)}${$$(p.balance)}
No payments
`}, {id:'repo',g:'BHPH letters',n:'Notice of Repossession / Intent to Sell',need:'bhph',f:({l,c,v})=>F.hdr('Notice of Our Plan to Sell Property',0,fdate(TODAY))+`

${esc(c?.name)}
${esc(c?.address||'')}

We have your ${esc(vname(v))}, VIN ${esc(v.vin)}, because you broke promises in our agreement (account ${l.acct}).

We will sell it at private sale sometime after ${fdate(addDays(TODAY,15))}. The money we get from the sale (after paying our costs) will reduce the amount you owe. If we get less money than you owe, you will / will not still owe us the difference.

You can get the property back at any time before we sell it by paying us the full amount you owe (not just the past-due payments), including our expenses. To learn the exact amount you must pay, call us at ${esc(S.settings.phone)}.

Personal property found in the vehicle is available for pickup at ${esc(S.settings.address)}.

`+F.note('State-specific: repossession notices (right to cure, redemption, timing, delivery method) vary a lot by state. Have your attorney supply the exact wording before you send this.')}, ]; FORMS.push({id:'bookout',g:'Bookout',n:'Vehicle Bookout Sheet',need:'deal',f:({d,v})=>bookSheetHTML(v,d)}); FORMS.splice(3,0,{id:'titlereg',g:'Title & Registration',n:'Title & Registration Worksheet',need:'deal',f:({d,v,c,l})=>{const t=dealTitle(d),st=stateOf(t.state),sf=sForm(t.state);const lien=d.type==='BHPH'?S.settings.dealer:d.type==='Retail Finance'?(d.lender||''):'None'; return F.hdr('Title & Registration Worksheet',0,`Deal #${d.no} · ${st?st[1]:'State not set'}`)+ `
STATE FORM TO COMPLETE

${st?`${esc(st[2])} – ${esc(st[3])}`:'Set the registration state on this deal (Forms → Title work).'}

${sf.form?`Form: ${esc(sf.form)}${sf.url?' – '+esc(sf.url):''}`:'Form: use your state\'s current dealer title / registration application (save it in Forms → State directory).'}

${sf.notes?`

${esc(sf.notes)}

`:''}
`+ `

Owner / applicant

`+F.grid([[['Owner name',c?.name,2],['Co-owner',''],['Date of birth','']],[['Residence address',c?.address,2],['County',''],['Phone',c?.phone]],[["Driver's license #",''],['DL state',''],['Email',c?.email],['Mailing address (if different)','']]])+ `

Vehicle

`+F.grid([[['Year',v.year],['Make',v.make],['Model',v.model],['Body style','']],[['VIN',v.vin,2],['Color',v.color],['Odometer',(+v.miles).toLocaleString()+' mi']],[['Odometer status','☐ Actual ☐ Exceeds limits ☐ Not actual',2],['Title brand','☐ None ☐ Salvage ☐ Rebuilt ☐ Other',2]],[['Previous title state',''],['Previous title #',''],['Fuel type',''],['Weight / GVWR','']]])+ `

Sale

`+F.grid([[['Date of sale',fdate(d.date)],['Sale price',$$(d.price)],['Trade-in allowance',$$(d.tradeAllow)],['Taxable amount',$$(d.taxable)]],[['Sales tax collected',$$(d.tax)],['Tax rate',d.taxRate+'%'],['Seller (dealer)',S.settings.dealer],['Dealer license #',S.settings.dealerLicense||'']]])+ `

Lien & registration

`+F.grid([[['First lienholder',lien,2],['Lienholder address',d.type==='BHPH'?S.settings.address:'',2]],[['Lien date',d.type==='Cash'?'':fdate(d.date)],['Plate','☐ New ☐ Transfer #________'],['Temp tag #',t.tempTag||''],['Temp tag expires',t.tempExp?fdate(t.tempExp):'']],[['Insurance company',''],['Policy #',''],['Registration term','☐ 1 yr ☐ 2 yr'],['Fees collected',$$(d.otherFees)]]])+ `

Checklist

${['Signed state title application','Odometer disclosure (or on title)','Previous title signed over / MSO','Lien release from prior lienholder (trade-ins)','Proof of insurance','Buyer ID copy','Bill of sale / buyer\'s order','Power of attorney (if signing for buyer)','Emissions / safety inspection (if required)','Sales tax & title fees paid'].map(i=>`
☐ ${i}
`).join('')}
`+ F.note('This worksheet collects the details most state title and registration applications ask for. Copy them onto your state\'s official form, or use it to fill an electronic titling system. Requirements and deadlines vary by state.')}}); const fpage=(f,x,cp)=>`
${f.f(x)}
${esc(f.n)}${cp?' · '+cp:''}${esc(S.settings.dealer)} · Deal #${x.d.no}${x.l?' · Acct '+x.l.acct:''}Buyer initials ______
`; const STATES=[['AL','Alabama','Dept. of Revenue – Motor Vehicle Division','https://www.revenue.alabama.gov/motor-vehicle/'],['AK','Alaska','Division of Motor Vehicles','https://dmv.alaska.gov/'],['AZ','Arizona','ADOT Motor Vehicle Division','https://azdot.gov/mvd'],['AR','Arkansas','DFA Office of Motor Vehicle','https://www.dfa.arkansas.gov/'],['CA','California','Department of Motor Vehicles','https://www.dmv.ca.gov/'],['CO','Colorado','Division of Motor Vehicles','https://dmv.colorado.gov/'],['CT','Connecticut','Department of Motor Vehicles','https://portal.ct.gov/dmv'],['DE','Delaware','Division of Motor Vehicles','https://www.dmv.de.gov/'],['DC','District of Columbia','Department of Motor Vehicles','https://dmv.dc.gov/'],['FL','Florida','Dept. of Highway Safety & Motor Vehicles','https://www.flhsmv.gov/'],['GA','Georgia','Dept. of Revenue – Motor Vehicle Division','https://dor.georgia.gov/motor-vehicles'],['HI','Hawaii','County motor vehicle offices (administered by county)','https://hidot.hawaii.gov/'],['ID','Idaho','ITD Division of Motor Vehicles','https://itd.idaho.gov/dmv/'],['IL','Illinois','Secretary of State – Vehicle Services','https://www.ilsos.gov/'],['IN','Indiana','Bureau of Motor Vehicles','https://www.in.gov/bmv/'],['IA','Iowa','Iowa DOT – Motor Vehicle Division','https://iowadot.gov/mvd'],['KS','Kansas','Dept. of Revenue – Division of Vehicles','https://www.ksrevenue.gov/'],['KY','Kentucky','Transportation Cabinet – Motor Vehicle Licensing','https://drive.ky.gov/'],['LA','Louisiana','Office of Motor Vehicles','https://www.expresslane.org/'],['ME','Maine','Bureau of Motor Vehicles','https://www.maine.gov/sos/bmv/'],['MD','Maryland','Motor Vehicle Administration','https://mva.maryland.gov/'],['MA','Massachusetts','Registry of Motor Vehicles','https://www.mass.gov/orgs/massachusetts-registry-of-motor-vehicles'],['MI','Michigan','Secretary of State','https://www.michigan.gov/sos'],['MN','Minnesota','Driver and Vehicle Services','https://dps.mn.gov/divisions/dvs/'],['MS','Mississippi','Dept. of Revenue – Motor Vehicle Licensing','https://www.dor.ms.gov/'],['MO','Missouri','Dept. of Revenue – Motor Vehicle Bureau','https://dor.mo.gov/motor-vehicle/'],['MT','Montana','DOJ Motor Vehicle Division','https://dojmt.gov/driving/'],['NE','Nebraska','Department of Motor Vehicles','https://dmv.nebraska.gov/'],['NV','Nevada','Department of Motor Vehicles','https://dmv.nv.gov/'],['NH','New Hampshire','Division of Motor Vehicles','https://www.dmv.nh.gov/'],['NJ','New Jersey','Motor Vehicle Commission','https://www.nj.gov/mvc/'],['NM','New Mexico','Motor Vehicle Division','https://www.mvd.newmexico.gov/'],['NY','New York','Department of Motor Vehicles','https://dmv.ny.gov/'],['NC','North Carolina','NCDOT Division of Motor Vehicles','https://www.ncdot.gov/dmv/'],['ND','North Dakota','NDDOT Motor Vehicle Division','https://www.dot.nd.gov/'],['OH','Ohio','Bureau of Motor Vehicles','https://bmv.ohio.gov/'],['OK','Oklahoma','Service Oklahoma','https://oklahoma.gov/service.html'],['OR','Oregon','ODOT Driver & Motor Vehicle Services','https://www.oregon.gov/odot/dmv/'],['PA','Pennsylvania','PennDOT Driver & Vehicle Services','https://www.dmv.pa.gov/'],['RI','Rhode Island','Division of Motor Vehicles','https://dmv.ri.gov/'],['SC','South Carolina','Department of Motor Vehicles','https://www.scdmvonline.com/'],['SD','South Dakota','Dept. of Revenue – Motor Vehicles','https://dor.sd.gov/'],['TN','Tennessee','Dept. of Revenue – Title & Registration','https://www.tn.gov/revenue/title-and-registration.html'],['TX','Texas','Department of Motor Vehicles','https://www.txdmv.gov/'],['UT','Utah','Division of Motor Vehicles','https://dmv.utah.gov/'],['VT','Vermont','Department of Motor Vehicles','https://dmv.vermont.gov/'],['VA','Virginia','Department of Motor Vehicles','https://www.dmv.virginia.gov/'],['WA','Washington','Department of Licensing','https://www.dol.wa.gov/'],['WV','West Virginia','Division of Motor Vehicles','https://transportation.wv.gov/DMV/'],['WI','Wisconsin','WisDOT Division of Motor Vehicles','https://wisconsindot.gov/'],['WY','Wyoming','WYDOT Motor Vehicle Services','https://www.dot.state.wy.us/']]; const stateOf=k=>STATES.find(x=>x[0]===k); const sForm=k=>(S.stateForms||{})[k]||{}; const TSTEPS=['Not started','Docs signed','Temp tag issued','Sent to state','Title received','Plates delivered','Complete']; function dealTitle(d){d.title=d.title||{state:S.settings.state||'',status:'Not started',tempTag:'',tempExp:'',sent:'',plate:'',titleNo:'',notes:''};if(!d.title.state)d.title.state=S.settings.state||'';return d.title} function titleModal(id){const d=S.deals.find(x=>x.id===id),t=dealTitle(d),c=cust(d.customerId),v=veh(d.vehicleId); openModal(mh(`Title & registration · Deal #${d.no}`)+`

${esc(c?.name)} · ${esc(vname(v))} · VIN ${esc(v.vin)}

`); $('#ttf').onsubmit=e=>{e.preventDefault();Object.assign(t,fd(e.target));save();closeModal();render();toast('Title work updated')}} const VIEWS_TITLE=()=>{const rows=S.deals.slice().sort((a,b)=>b.date.localeCompare(a.date)).map(d=>[d,dealTitle(d)]);const open=rows.filter(r=>r[1].status!=='Complete'); const exp=r=>r[1].tempExp&&r[1].status!=='Complete'?diff(TODAY,r[1].tempExp):null; return `
${kpi('Open title work',open.length,'deals not complete')}${kpi('Temp tags expiring',open.filter(r=>exp(r)!=null&&exp(r)<=7).length,'within 7 days')}${kpi('Waiting on state',open.filter(r=>r[1].status==='Sent to state').length,'sent, title not back')}
${rows.map(([d,t])=>{const e=exp([d,t]);return ``}).join('')}
DealCustomerVehicleStateStatusTemp tagSentPlate / title
#${d.no}${esc(cust(d.customerId)?.name)}${esc(vname(veh(d.vehicleId)))}${t.state||'Set state'}${t.status}${t.tempTag?esc(t.tempTag):'—'}${e!=null?`
${e<0?'expired '+(-e)+'d ago':'expires in '+e+'d'}
`:''}
${t.sent?fdate(t.sent):'—'}${esc([t.plate,t.titleNo].filter(Boolean).join(' / '))||'—'}
`}; function stateDir(){const q=(ui.stateQ||'').toLowerCase();const my=S.settings.state; return `
Your dealership state: ${my?stateOf(my)[1]:'not set'} (Settings)
${STATES.filter(s=>!q||(s[0]+' '+s[1]+' '+s[2]).toLowerCase().includes(q)).map(s=>{const f=sForm(s[0]);return ``}).join('')}
StateAgencyYour title / registration formOfficial site
${s[1]} ${s[0]}${s[0]===my?' Your state':''}${esc(s[2])}${f.form?`${esc(f.form)}${f.url?``:''}${f.notes?`
${esc(f.notes)}
`:''}`:'Not saved yet'}
${s[3].replace(/^https?:\/\/(www\.)?/,'').replace(/\/$/,'')} ↗

Agency sites change, so confirm the current form on the official site. Forms you save here show on the Title & Registration Worksheet for deals registered in that state.

`} function stateFormModal(k){const s=stateOf(k),f=sForm(k);openModal(mh(`${s[1]} title & registration form`)+`

Open ${esc(s[2])} ↗, find the current dealer title/registration application, and save its name and link here.

`); $('#sff').onsubmit=e=>{e.preventDefault();const x=fd(e.target);if(x.url&&!/^https?:\/\//.test(x.url))return toast('Link must start with https://');S.stateForms=S.stateForms||{};S.stateForms[k]=x;save();closeModal();render();toast('Saved')}} function formCtx(){const d=ui.formDeal?S.deals.find(x=>x.id===ui.formDeal):null;const l=d&&d.loanId?loan(d.loanId):null;return d?{d,l,v:veh(d.vehicleId),c:cust(d.customerId)}:null} const formOk=(f,x)=>f.need==='deal'||(f.need==='fin'&&x.d.type!=='Cash')||(f.need==='bhph'&&x.l); const PACKS={Cash:['bos','bg','odo','poa','weowe','rcpt','recap'],'Retail Finance':['bos','bg','odo','risc','ins','poa','priv','weowe','rcpt','recap'],BHPH:['bos','bg','odo','risc','ins','sched','poa','priv','weowe','rcpt','welcome','recap']}; const fcss=()=>BKCSS+`.pf{font-family:Inter,'Helvetica Neue',Arial,sans-serif;color:#111827;font-size:11.5px;line-height:1.5;--fa:${S.settings.formColor||'#1e3a8a'};-webkit-print-color-adjust:exact;print-color-adjust:exact} .pf .page{background:#fff;width:8.5in;min-height:11in;padding:.5in .55in .4in;margin:0 auto 22px;box-shadow:0 6px 24px rgba(15,23,42,.18);display:flex;flex-direction:column;border-radius:3px} .pf .fbody{flex:1} .fh{display:flex;align-items:center;gap:14px;padding-bottom:14px;margin-bottom:16px;border-bottom:3px solid var(--fa);position:relative} .fh:after{content:'';position:absolute;left:0;right:0;bottom:-7px;border-bottom:1px solid #d1d5db} .flogo{width:46px;height:46px;border-radius:10px;background:var(--fa);color:#fff;display:grid;place-items:center;font-weight:800;font-size:17px;letter-spacing:.5px;flex-shrink:0} .fdealer{flex:1}.fdn{font-size:16px;font-weight:800;letter-spacing:-.2px;color:#0f172a}.fsm{font-size:10px;color:#4b5563} .ftitle{text-align:right}.ft{font-size:17px;font-weight:800;text-transform:uppercase;letter-spacing:1px;color:var(--fa);line-height:1.15} .fchip{display:inline-block;margin-top:5px;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:20px;padding:2px 10px;font-size:9.5px;font-weight:600;color:#334155} .fg{width:100%;border:1px solid #cbd5e1;border-radius:8px;border-collapse:separate;border-spacing:0;margin:10px 0;overflow:hidden} .fg td{border-right:1px solid #e2e8f0;border-bottom:1px solid #e2e8f0;padding:6px 9px 7px;vertical-align:top;font-size:12px;font-weight:600;color:#0f172a} .fg tr:last-child td{border-bottom:0}.fg td:last-child{border-right:0} .fg td span{display:block;font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:#64748b;margin-bottom:2px} .fm{width:100%;border-collapse:collapse;margin:8px 0;font-size:12px}.fm td{padding:6px 10px;border-bottom:1px solid #eef2f7}.fm td:last-child{text-align:right;font-variant-numeric:tabular-nums;font-weight:600;white-space:nowrap} .fm tr.tot td{font-weight:800;background:#f1f5f9;border-top:2px solid var(--fa);border-bottom:0;font-size:12.5px} .tila{width:100%;border-collapse:separate;border-spacing:6px 0;margin:12px -6px}.tila td{border:2px solid #0f172a;border-radius:8px;padding:9px 10px;vertical-align:top;width:20%} .tila td:nth-child(-n+2){border-color:var(--fa);background:#f8faff}.tila b{font-size:10px;text-transform:uppercase;letter-spacing:.4px}.tila small{display:block;font-size:8.5px;color:#475569;margin-top:3px;line-height:1.3}.tila div{font-size:18px;font-weight:800;margin-top:8px;color:#0f172a} .fsched{width:100%;border-collapse:collapse;margin:10px 0;border:1px solid #cbd5e1}.fsched th{background:var(--fa);color:#fff;font-size:9px;text-transform:uppercase;letter-spacing:.5px;padding:6px 7px;text-align:left}.fsched td{padding:5px 7px;font-size:10.5px;border-bottom:1px solid #e2e8f0}.fsched tr:nth-child(even) td{background:#f8fafc} .fcols{display:grid;grid-template-columns:1fr 1fr;gap:18px} .fbox{background:#f8fafc;border:1px solid #e2e8f0;border-left:4px solid var(--fa);border-radius:8px;padding:10px 14px;margin:12px 0}.fbox p{margin:6px 0}.fbox>b{display:block;font-size:10.5px;letter-spacing:.6px;color:var(--fa);margin-bottom:4px} .fnote{display:flex;gap:9px;font-size:9.5px;color:#475569;background:#fffbeb;border:1px solid #fde68a;border-radius:8px;padding:8px 11px;margin:12px 0;line-height:1.45}.fnote i{font-style:normal;font-weight:800;width:16px;height:16px;border-radius:50%;background:#f59e0b;color:#fff;display:grid;place-items:center;font-size:10px;flex-shrink:0;font-family:Georgia,serif} .pf h4{margin:16px 0 6px;font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--fa);padding:5px 9px;background:#f1f5f9;border-left:3px solid var(--fa);border-radius:0 6px 6px 0} .pf p{margin:8px 0}.pf u{text-decoration:none;border-bottom:1px solid #111;font-weight:700;padding:0 4px} .fsig{display:flex;gap:22px;margin-top:30px}.fsigbox{flex:1}.fsig .fl{border-bottom:1.5px solid #0f172a;height:34px;position:relative}.fsig .fl i{position:absolute;left:0;bottom:3px;font-style:normal;color:#94a3b8;font-size:11px} .fsigl{display:flex;justify-content:space-between;margin-top:4px;font-size:9.5px;color:#475569}.fsigl b{font-weight:700;color:#0f172a}.fsigl span{border-left:1px solid #cbd5e1;padding-left:8px;min-width:80px} .ffoot{display:flex;justify-content:space-between;gap:10px;border-top:1px solid #e2e8f0;margin-top:20px;padding-top:7px;font-size:8.5px;color:#64748b;text-transform:uppercase;letter-spacing:.5px}`; const FBYID=id=>FORMS.find(f=>f.id===id); function defaultPack(x){const st=dealTitle(x.d).state;const ps=(S.packs||[]).filter(p=>p.auto&&(p.dealType==='Any'||p.dealType===x.d.type));return ps.find(p=>p.state&&p.state===st)||ps.find(p=>!p.state)||null} function applyPack(p,x){ui.formPack=p?p.id:'';if(!p){ui.formSel=new Set();ui.formCopies={};ui.formOrder=null;return}ui.formSel=new Set(p.items.map(i=>i.id).filter(id=>FBYID(id)&&formOk(FBYID(id),x)));ui.formCopies=Object.fromEntries(p.items.map(i=>[i.id,+i.copies||1]));ui.formOrder=p.items.map(i=>i.id)} function selForms(x){const sel=FORMS.filter(f=>ui.formSel.has(f.id)&&formOk(f,x));if(ui.formOrder){const o=ui.formOrder;sel.sort((a,b)=>(o.indexOf(a.id)+1||99)-(o.indexOf(b.id)+1||99))}return sel} function packPages(x){return selForms(x).map(f=>{const n=Math.max(1,+(ui.formCopies||{})[f.id]||1);let o='';for(let i=1;i<=n;i++)o+=fpage(f,x,n>1?`Copy ${i} of ${n}`:'');return o}).join('')} const pageCount=x=>selForms(x).reduce((a,f)=>a+Math.max(1,+(ui.formCopies||{})[f.id]||1),0); VIEWS.forms=()=>{syncCustomForms();const tabs=[['print','Print forms'],['packs','Print packs'],['custom','Custom forms'],['esign','E-signatures'],['title','Title work'],['states','State directory']]; const head=`
${tabs.map(t=>``).join('')}
`; if(ui.formTab==='packs')return head+packsView();if(ui.formTab==='custom')return head+customFormsView();if(ui.formTab==='esign'){if(!ui._esaChecked||Date.now()-ui._esaChecked>60000){ui._esaChecked=Date.now();esaHealth().then(h=>{(S.envelopes||[]).filter(e=>e.esaId&&(e.status!=='Completed'||!e.signedAsset)).forEach(e=>esaRefresh(e.id));if(route==='forms')render()})}return head+esignView()}if(ui.formTab==='title')return head+VIEWS_TITLE();if(ui.formTab==='states')return head+stateDir(); const deals=S.deals.slice().sort((a,b)=>b.date.localeCompare(a.date));if(!ui.formDeal&&deals[0])ui.formDeal=deals[0].id;const x=formCtx(); if(!x)return head+'
Finalize a deal first – forms fill in from the deal.
'; if(!ui.formSel||ui.formSelFor!==x.d.id){applyPack(defaultPack(x),x);ui.formSelFor=x.d.id} const groups=[...new Set(FORMS.map(f=>f.g))];const packs=(S.packs||[]).filter(p=>p.dealType==='Any'||p.dealType===x.d.type);const cur=S.packs.find(p=>p.id===ui.formPack); return head+`
${ui.formSel.size} form(s) · ${pageCount(x)} page(s)${DL?``:``}
${cur?`
Using print pack ${esc(cur.name)}. Change the selection on the left for this deal only, or edit the pack.
`:''}
${groups.map(g=>`
${g}
${FORMS.filter(f=>f.g===g).map(f=>{const ok=formOk(f,x),on=ui.formSel.has(f.id);return `
${on?``:''}
`}).join('')}`).join('')}

Forms are DealerPen templates filled in from the deal. Contracts, repossession notices and state title forms vary by state, so have your attorney or state dealer association approve the versions you use.

${packPages(x)||'
Pick forms on the left to preview
'}
`}; const printPackFieldMap = new Map([ [ "buyername", "buyer.name" ], [ "buyerfullname", "buyer.name" ], [ "applicant_fullname", "buyer.name" ], [ "buyeraddrcomplete", "buyer.address" ], [ "applicant_address_streetcitystatezip", "buyer.address" ], [ "buyerhomephone", "buyer.phone" ], [ "applicant_homephone", "buyer.phone" ], [ "buyeremail", "buyer.email" ], [ "applicant_emailaddress", "buyer.email" ], [ "buyerdob", "buyer.dob" ], [ "applicant_birthdate", "buyer.dob" ], [ "buyerdriverslicense", "buyer.dl" ], [ "cobuyername", "cobuyer.name" ], [ "applicant2_fullname", "cobuyer.name" ], [ "cobuyeraddrcomplete", "cobuyer.address" ], [ "applicant2_address_streetcitystatezip", "cobuyer.address" ], [ "sellername", "dealer.name" ], [ "dealername", "dealer.name" ], [ "selleraddrcomplete", "dealer.address" ], [ "seller_fulladdress", "dealer.address" ], [ "sellerphone", "dealer.phone" ], [ "dealerphone", "dealer.phone" ], [ "vehyear", "veh.year" ], [ "vehicle_year", "veh.year" ], [ "vehmake", "veh.make" ], [ "vehicle_make", "veh.make" ], [ "vehmodel", "veh.model" ], [ "vehicle_model", "veh.model" ], [ "vehvin", "veh.vin" ], [ "vehicle_identificationnumber", "veh.vin" ], [ "vehicle_vin", "veh.vin" ], [ "vehmileage", "veh.miles" ], [ "vehicle_odometer", "veh.miles" ], [ "vehstocknumber", "veh.stock" ], [ "vehstocknumbertx", "veh.stock" ], [ "vehicle_stocknumber", "veh.stock" ], [ "vehbodytype", "veh.body" ], [ "vehicle_bodytype", "veh.body" ], [ "vehexteriorcolor", "veh.color" ], [ "vehicle_exteriorcolor", "veh.color" ], [ "vehyearmakemodel", "veh.ymm" ], [ "dealnumber", "deal.no" ], [ "deal_number", "deal.no" ], [ "dealdate", "deal.date" ], [ "deal_date", "deal.date" ], [ "salesperson1", "deal.salesperson" ], [ "cashprice", "deal.price" ], [ "vehicle_cashprice", "deal.price" ], [ "docfee", "deal.docFee" ], [ "documentationfee", "deal.docFee" ], [ "salestax", "deal.tax" ], [ "tradeallowance", "deal.tradeAllow" ], [ "tradepayoff", "deal.tradePayoff" ], [ "tradevin", "deal.tradeVin" ], [ "cashdownpayment", "deal.down" ], [ "amountfinanced", "fin.financed" ], [ "loan_amountfinanced_amount", "fin.financed" ], [ "annualpercentagerate", "fin.apr" ], [ "loan_annualpercentage_rate", "fin.apr" ], [ "financecharge", "fin.financeCharge" ], [ "loan_financecharge_amount", "fin.financeCharge" ], [ "totalofpayments", "fin.totalOfPayments" ], [ "loan_totalofpayments_amount", "fin.totalOfPayments" ], [ "totalsaleprice", "fin.totalSale" ], [ "loan_totalsaleprice_amount", "fin.totalSale" ], [ "loan_payment_amount", "fin.payment" ], [ "loan_payment_due", "fin.firstDue" ], [ "lienholdername", "fin.lienholder" ] ]); function printPackDealData(deal) { const data = lfData(deal); const buyer = cust(deal.customerId) || {}; const coBuyer = buyer.cobuyer || {}; const vehicle = veh(deal.vehicleId) || {}; if (vehicle.miles == null || vehicle.miles === '') delete data['veh.miles']; if (!deal.date) delete data['deal.date']; if (deal.type === 'Cash') { for (const key of Object.keys(data)) if (key.startsWith('fin.')) delete data[key]; } return { ...data, 'BuyerAndCoBuyerName': [data['buyer.name'], data['cobuyer.name']].filter(Boolean).join(' and '), 'BuyerFirstName': buyer.firstName || '', 'BuyerLastName': buyer.lastName || '', 'BuyerCity': buyer.city || '', 'BuyerState': buyer.state || '', 'BuyerZip': buyer.zip || '', 'CoBuyerEmail': coBuyer.email || '', 'CoBuyerHomePhone': coBuyer.phone || '', }; } function fillPrintPackFields(pdf, data, {flatten = false} = {}) { const form = pdf.getForm(); let filled = 0; for (const field of form.getFields()) { if (typeof field.setText !== 'function') continue; const name = field.getName(); const key = printPackFieldMap.get(name.toLowerCase()) || name; if (!Object.hasOwn(data, key)) continue; const value = data[key]; if (value == null || String(value).trim() === '') continue; field.setText(String(value)); filled++; } if (flatten) { for (const field of form.getFields()) { if (field.isChecked?.() === false && field.acroField.getWidgets().some(widget => !widget.getAppearances()?.normal)) form.removeField(field); } form.flatten(); } else if (filled) form.updateFieldAppearances(); return filled; } VIEWS.mailbox = () => `

DealerPen Mail

Sign in with your full mailbox address and mailbox password.

Open in a new tab

SMTP submission
mail.dealerpen.com · 587 · STARTTLS
POP3
mail.dealerpen.com · 995 · TLS
IMAP
mail.dealerpen.com · 993 · TLS
`; function dealerCenterPanel(deal) { const el = document.createElement('details'); el.className = 'card'; el.open = true; el.innerHTML = 'Imported print packs

Loading packs…

'; const endpoint = '/api/print-packs/dealercenter'; async function readPdf(id) { const response = await fetch(srvURL(endpoint + '/' + id), {headers:srvHeaders()}); if (!response.ok) throw new Error('Could not open this form. Sign in and try again.'); return response.arrayBuffer(); } function showPdf(tab, bytes) { const url = URL.createObjectURL(new Blob([bytes], {type:'application/pdf'})); tab.location.replace(url); setTimeout(() => URL.revokeObjectURL(url), 600000); } async function preview(button, ids, combine) { const tab = window.open('', '_blank'); if (!tab) return toast('Allow pop-ups to open the PDF preview.'); tab.opener = null; tab.document.body.textContent = 'Preparing PDF…'; button.disabled = true; try { if (!combine && !deal) return showPdf(tab, await readPdf(ids[0])); const data = deal ? printPackDealData(deal) : {}; let filled = 0; const {PDFDocument} = await loadPdfLib(); const packet = await PDFDocument.create(); for (const id of ids) { const source = await PDFDocument.load(await readPdf(id)); filled += fillPrintPackFields(source, data, {flatten:combine}); if (!combine) { if (!filled) toast('This template has no matching fields for the current deal.'); return showPdf(tab, await source.save({updateFieldAppearances:false})); } const pages = await packet.copyPages(source, source.getPageIndices()); pages.forEach(page => packet.addPage(page)); } showPdf(tab, await packet.save()); if (deal) toast(filled ? filled + ' fields filled. Review the PDF before printing.' : 'This pack has no matching fields for the current deal.'); } catch (error) { tab.document.body.textContent = error.message; toast('Could not prepare the PDF preview.'); } finally { button.disabled = false; } } (async () => { try { const response = await fetch(srvURL(endpoint), {headers:srvHeaders()}); if (!response.ok) throw new Error('Sign in to view imported packs.'); const {documents, packs} = await response.json(); const documentLabel = id => { const form = documents[id]; return esc(form.name) + (form.sample ? ' (SAMPLE)' : ''); }; el.innerHTML = 'Imported print packs

Open or print the supplied PDFs. Select one version when a form has multiple templates.

'; if (deal) { const note = document.createElement('p'); note.className = 'hint'; note.textContent = 'Autofill uses deal #' + deal.no + '. Review each form before printing.'; el.append(note); } for (const group of ['Deal','Inventory']) { const heading = document.createElement('h3'); heading.textContent = group + ' packs'; el.append(heading); for (const pack of packs.filter(pack => pack.group === group)) { const details = document.createElement('details'); details.className = 'st-det'; const available = pack.entries.filter(entry => entry.variants.length).length; details.innerHTML = '' + esc(pack.name) + ' · ' + available + ' of ' + pack.entries.length + ' forms available'; const list = document.createElement('ol'); const selected = []; for (const entry of pack.entries) { const item = document.createElement('li'); item.textContent = entry.name; list.append(item); if (!entry.variants.length) { item.append(' · Template unavailable'); continue; } let current = () => entry.variants[0]; if (entry.variants.length > 1) { const select = document.createElement('select'); select.setAttribute('aria-label',entry.name + ' version'); select.innerHTML = entry.variants.map(id => '').join(''); current = () => select.value; item.append(' ',select); } else if (documents[current()].sample) { item.append(' · SAMPLE'); } selected.push(current); const button = document.createElement('button'); button.className = 'btn sm'; button.textContent = 'Open PDF'; button.onclick = () => preview(button,[current()],false); item.append(' ',button); } const button = document.createElement('button'); button.className = 'btn sm pri'; button.textContent = 'Preview printable pack'; button.disabled = !available; button.onclick = () => preview(button,selected.map(get => get()),true); details.append(list,button); el.append(details); } } } catch (error) { el.querySelector('[role=status]').textContent = error.message; } })(); return el; } function attachDealerCenterPanel(deal) { for (const mount of document.querySelectorAll('[data-dealercenter-packs]:empty')) mount.append(dealerCenterPanel(deal)); } function packsView(){queueMicrotask(()=>attachDealerCenterPanel(formCtx()?.d));const ps=S.packs||[];return `
A print pack is a saved set of forms in order, with copies, for one kind of deal. The matching pack loads automatically when you print a deal, and a state-specific pack beats a general one.
${ps.map(p=>`

📦 ${esc(p.name)}${p.auto?'Auto':''}

${p.dealType==='Any'?'Any deal type':esc(p.dealType)+' deals'}${p.state?' · '+esc(stateOf(p.state)?.[1]||p.state):' · all states'} · ${p.items.reduce((a,i)=>a+(+i.copies||1),0)} pages
    ${p.items.map(i=>`
  1. ${esc(FBYID(i.id)?.n||i.id)}${+i.copies>1?` ×${i.copies}`:''}
  2. `).join('')}
`).join('')||'
No print packs yet
'}
`} function packModal(id){syncCustomForms();const p=id?S.packs.find(x=>x.id===id):{name:'',dealType:'BHPH',state:'',auto:true,items:[]};let items=JSON.parse(JSON.stringify(p.items)); openModal(mh(id?'Edit print pack':'New print pack')+`
In this pack (print order)
Add forms
`,true); const draw=()=>{$('#pkin').innerHTML=items.map((it,i)=>`
${i+1}${esc(FBYID(it.id)?.n||it.id)}
`).join('')||'
Add forms from the right
'; $('#pkout').innerHTML=FORMS.filter(f=>!items.some(i=>i.id===f.id)).map(f=>`
${esc(f.n)} ${esc(f.g)}
`).join(''); $('#pkin').querySelectorAll('[data-c]').forEach(e=>e.onchange=()=>{items[+e.dataset.c].copies=+e.value}); $('#pkin').querySelectorAll('[data-u]').forEach(e=>e.onclick=()=>{const i=+e.dataset.u;[items[i-1],items[i]]=[items[i],items[i-1]];draw()}); $('#pkin').querySelectorAll('[data-d]').forEach(e=>e.onclick=()=>{const i=+e.dataset.d;[items[i+1],items[i]]=[items[i],items[i+1]];draw()}); $('#pkin').querySelectorAll('[data-x]').forEach(e=>e.onclick=()=>{items.splice(+e.dataset.x,1);draw()}); $('#pkout').querySelectorAll('[data-a]').forEach(e=>e.onclick=()=>{items.push({id:e.dataset.a,copies:1});draw()})};draw(); $('#pkf').onsubmit=e=>{e.preventDefault();if(!items.length)return toast('Add at least one form');const x=fd(e.target);const n=id?p:{id:uid()};Object.assign(n,{name:x.name,dealType:x.dealType,state:x.state,auto:!!x.auto,items});if(!id)S.packs.push(n);ui.formSelFor=null;save();closeModal();render();toast('Print pack saved')}} function savePackFromSel(){const x=formCtx();const items=selForms(x).map(f=>({id:f.id,copies:+(ui.formCopies||{})[f.id]||1}));if(!items.length)return toast('Select some forms first');const p={id:uid(),name:x.d.type+' pack '+((S.packs||[]).length+1),dealType:x.d.type,state:'',auto:false,items};S.packs.push(p);save();packModal(p.id)} function formsDoc(){const x=formCtx();const pages=packPages(x); return `Deal ${x.d.no} forms – ${esc(x.c?.name)}
Deal #${x.d.no} · ${esc(x.c?.name)} · ${pageCount(x)} page(s)
${pages}
`} async function dlForms(){if(!ui.formSel.size)return toast('Pick at least one form');const x=formCtx();try{await DL.save({filename:`deal-${x.d.no}-${(x.c?.name||'forms').replace(/\W+/g,'-')}.html`,data:await inlineImgs(formsDoc())});toast('Saved – open the file and click Print')}catch(e){if(e&&e.code!=='declined')toast('Download unavailable here – use Copy instead')}} function copyForms(){if(!ui.formSel.size)return toast('Pick at least one form');copyText(formsDoc())} try{if(window.claude&&window.claude.use)window.claude.use('downloads').then(x=>{DL=x;if(route==='forms')render()}).catch(()=>{})}catch(e){} /* ---- accounting ---- */ VIEWS.accounting=()=>{const m=ui.acctMonth;const tx=S.txns.filter(t=>t.date.slice(0,7)===m).sort((a,b)=>b.date.localeCompare(a.date)); const sum=c=>tx.filter(t=>t.cat===c).reduce((a,t)=>a+t.amount,0); const rev=['Vehicle Sales','Doc Fees','Interest Income','Late Fee Income'],exp=['Cost of Vehicles Sold','Reconditioning']; const tr=rev.reduce((a,c)=>a+sum(c),0),te=exp.reduce((a,c)=>a+sum(c),0); const cin=Object.keys(CATS).filter(c=>CATS[c]==='cashin'),cout=['Vehicle Purchase','Reconditioning','Trade Payoff Owed']; const ti=cin.reduce((a,c)=>a+sum(c),0),to=cout.reduce((a,c)=>a+sum(c),0); const months=[...new Set(S.txns.map(t=>t.date.slice(0,7)))].sort().reverse();if(!months.includes(m))months.unshift(m); return `

Profit & loss

${rev.map(c=>`
${c}${$$(sum(c))}
`).join('')}
Total revenue${$$(tr)}
${exp.map(c=>`
${c}(${$$(sum(c))})
`).join('')}${otherExp(tx)}
Net income${$$(tr-te-oe(tx))}

Cash flow

${cin.map(c=>`
${c}${$$(sum(c))}
`).join('')}
Cash in${$$(ti)}
${cout.map(c=>`
${c==='Trade Payoff Owed'?'Trade payoffs':c}(${$$(sum(c))})
`).join('')}
Operating expenses(${$$(oe(tx))})
Net cash${$$(ti-to-oe(tx))}

Liabilities this month

Sales tax collected (remit to state)${$$(sum('Sales Tax Payable'))}
Trade lien payoffs owed${$$(sum('Trade Payoff Owed'))}

Inventory on hand: ${$0(S.vehicles.filter(v=>v.status!=='Sold').reduce((a,v)=>a+vcost(v),0))} · BHPH notes receivable: ${$0(S.loans.filter(l=>l.status==='Active').reduce((a,l)=>a+l.balance,0))}

${tx.map(t=>``).join('')||''}
DateCategoryRefDescriptionAmount
${fdate(t.date)}${esc(t.cat)}${esc(t.ref)}${esc(t.desc)}${$$(t.amount)}
No transactions this month
`+checkRegister()}; const oe=tx=>tx.filter(t=>!CATS[t.cat]).reduce((a,t)=>a+t.amount,0); const otherExp=tx=>{const g={};tx.filter(t=>!CATS[t.cat]).forEach(t=>g[t.cat]=(g[t.cat]||0)+t.amount);return Object.entries(g).map(([c,a])=>`
${esc(c)}(${$$(a)})
`).join('')}; function expenseModal(){openModal(mh('Record operating expense')+`
`); $('#ef').onsubmit=e=>{e.preventDefault();const x=fd(e.target);txn(x.date,x.cat,+x.amount,x.ref,x.desc||x.cat);save();closeModal();render();toast('Expense recorded')}} function exportTx(){const csv='date,category,ref,description,amount\n'+S.txns.slice().sort((a,b)=>a.date.localeCompare(b.date)).map(t=>[t.date,t.cat,t.ref,'"'+String(t.desc).replace(/"/g,'""')+'"',t.amount].join(',')).join('\n'); openModal(mh('Journal export (CSV)')+`

Paste into your spreadsheet or accounting software.

`);$('#cp').onclick=()=>copyText(csv)} /* ---- reports ---- */ const overviewReports=()=>{ const inv=S.vehicles.filter(v=>v.status==='Available'||v.status==='Pending'); const ib=[['0–30 days',0,30],['31–60',31,60],['61–90',61,90],['90+',91,1e9]].map(b=>{const l=inv.filter(v=>age(v)>=b[1]&&age(v)<=b[2]);return[b[0],l.length,l.reduce((a,v)=>a+vcost(v),0)]}); const act=S.loans.filter(l=>l.status==='Active'); const pb=[['Current',0,0],['1–30',1,30],['31–60',31,60],['61–90',61,90],['90+',91,1e9]].map(b=>{const l=act.filter(x=>daysLate(x)>=b[1]&&daysLate(x)<=b[2]);return[b[0],l.length,l.reduce((a,x)=>a+x.balance,0)]}); const months=[];for(let i=5;i>=0;i--)months.push(addMonths(TODAY.slice(0,7)+'-01',-i).slice(0,7)); const sm=months.map(m=>{const d=S.deals.filter(x=>x.date.slice(0,7)===m);return[s2d(m+'-01').toLocaleDateString('en-US',{month:'short'}),d.length,d.reduce((a,x)=>a+x.gross,0)]}); const cm=months.map(m=>[s2d(m+'-01').toLocaleDateString('en-US',{month:'short'}),S.txns.filter(t=>t.cat==='BHPH Payment'&&t.date.slice(0,7)===m).reduce((a,t)=>a+t.amount,0)]); const src={};S.customers.forEach(c=>{src[c.source]=src[c.source]||[0,0];src[c.source][0]++;if(c.stage==='Sold')src[c.source][1]++}); const bars=(rows,vi,fmt)=>{const mx=Math.max(1,...rows.map(r=>r[vi]));return rows.map(r=>`
${r[0]}
${fmt(r)}
`).join('')}; const tot=act.reduce((a,l)=>a+l.balance,0); return `

Sales by month (units · front gross)

${bars(sm,1,r=>r[1]+' · '+$0(r[2]))}

BHPH collections by month

${bars(cm,1,r=>$0(r[1]))}

Inventory aging

${bars(ib,2,r=>r[1]+' units · '+$0(r[2]))}

Portfolio aging (principal)

${bars(pb,2,r=>r[1]+' · '+$0(r[2]))}

${tot?((tot-pb[0][2])/tot*100).toFixed(1):0}% of principal is past due.

Lead source conversion

${Object.entries(src).map(([s,v])=>``).join('')}
SourceLeadsSoldClose rate
${esc(s)}${v[0]}${v[1]}${(v[1]/v[0]*100).toFixed(0)}%

Deal mix

${['BHPH','Retail Finance','Cash'].map(t=>{const d=S.deals.filter(x=>x.type===t);return ``}).join('')}
TypeDealsAvg priceAvg gross
${t}${d.length}${$0(d.length?d.reduce((a,x)=>a+x.price,0)/d.length:0)}${$0(d.length?d.reduce((a,x)=>a+x.gross,0)/d.length:0)}
`}; /* ---- report library ---- */ const RCATS2=[['inv','🚗','Inventory'],['deal','✎','Sales & Deals'],['cust','👤','Customers & Leads'],['bhph','▤','BHPH & Collections'],['acct','≡','Accounting'],['tax','🏛','Tax & Title'],['recon','🔧','Recon'],['mkt','📣','Marketing'],['admin','⚙','Staff & Admin']]; const inR=(d)=>d&&d>=ui.rep.from&&d<=ui.rep.to; const uname=id=>S.users.find(u=>u.id===id)?.name||'—'; const $c=n=>({v:+n||0,t:$$(n),m:1}); const REPORTS=[ ['inv','active','Active inventory','Every unit not sold, with cost, price and age',0,()=>[['Stock','Vehicle','VIN','Status','Miles','Days','Cost','Recon','Price','Margin'],S.vehicles.filter(v=>v.status!=='Sold').map(v=>[v.stock,vname(v),v.vin,v.status,+v.miles,age(v),$c(v.cost),$c(reconTotal(v)),$c(v.price),$c(v.price-vcost(v))])]], ['inv','aging','Inventory aging','Units grouped into 0–30, 31–60, 61–90 and 90+ day buckets',0,()=>{const b=[['0–30',0,30],['31–60',31,60],['61–90',61,90],['90+',91,1e9]];const l=S.vehicles.filter(v=>['Available','Pending','In Recon'].includes(v.status));return[['Bucket','Units','Total cost','Total price','Avg days'],b.map(x=>{const u=l.filter(v=>age(v)>=x[1]&&age(v)<=x[2]);return[x[0],u.length,$c(u.reduce((a,v)=>a+vcost(v),0)),$c(u.reduce((a,v)=>a+ +v.price,0)),u.length?Math.round(u.reduce((a,v)=>a+age(v),0)/u.length):0]})]}], ['inv','sold','Sold vehicles','Units sold in the date range',1,()=>[['Date','Stock','Vehicle','Customer','Type','Days to sell','Sale price','Front gross'],S.deals.filter(d=>inR(d.date)).map(d=>{const v=veh(d.vehicleId);return[d.date,v.stock,vname(v),cust(d.customerId)?.name,d.type,diff(v.acquired,d.date),$c(d.price),$c(d.gross)]})]], ['inv','value','Inventory value summary','Cost vs. asking price by status',0,()=>{const st=['In Recon','Available','Pending','Wholesale'];return[['Status','Units','Purchase cost','Recon','Total cost','Asking price','Potential gross'],st.map(x=>{const l=S.vehicles.filter(v=>v.status===x);const c=l.reduce((a,v)=>a+ +v.cost,0),r=l.reduce((a,v)=>a+reconTotal(v),0),p=l.reduce((a,v)=>a+ +v.price,0);return[x,l.length,$c(c),$c(r),$c(c+r),$c(p),$c(p-c-r)]})]}], ['inv','pricelog','Price change log','Every recorded price change',0,()=>{const rows=[];S.vehicles.forEach(v=>(v.notes||'').split('\n').forEach(l=>{const m=l.match(/Price \$([\d,]+) → \$([\d,]+) on (.+?) \(/);if(m)rows.push([m[3],v.stock,vname(v),$c(m[1].replace(/,/g,'')),$c(m[2].replace(/,/g,'')),$c(+m[2].replace(/,/g,'')-+m[1].replace(/,/g,''))])}));return[['Date','Stock','Vehicle','Old price','New price','Change'],rows]}], ['inv','vexp','Vehicle expense report','Recon and other costs added to vehicles in the range',1,()=>{const rows=[];S.vehicles.forEach(v=>(v.recon||[]).forEach(r=>{if(inR(r.date))rows.push([r.date,v.stock,vname(v),r.desc,$c(r.amount)])}));return[['Date','Stock','Vehicle','Description','Amount'],rows]}], ['inv','pricebook','Price vs. book','Asking price and cost against each book on file',0,()=>[['Stock','Vehicle','Price','Cost + recon','Black Book retail','J.D. Power retail','KBB listing','Avg wholesale','Price % of retail','Book age (days)'],S.vehicles.filter(v=>['Available','Pending','In Recon'].includes(v.status)).map(v=>{const sm=bookSummary(v);const rs=Object.values(sm).map(s=>s.retail).filter(Boolean),ws=Object.values(sm).map(s=>s.whole).filter(Boolean);const r=rs.length?rs.reduce((a,b)=>a+b,0)/rs.length:0;return[v.stock,vname(v),$c(v.price),$c(vcost(v)),sm.bb?$c(sm.bb.retail):'',sm.jdp?$c(sm.jdp.retail):'',sm.kbb?$c(sm.kbb.retail):'',ws.length?$c(ws.reduce((a,b)=>a+b,0)/ws.length):'',r?Math.round(v.price/r*100)+'%':'Not booked',Object.values(sm).length?Math.max(...Object.values(sm).map(s=>s.age)):'']})]], ['inv','purch','Purchase history','Vehicles acquired in the range',1,()=>[['Acquired','Stock','Vehicle','VIN','Miles','Cost','Source'],S.vehicles.filter(v=>inR(v.acquired)).map(v=>[v.acquired,v.stock,vname(v),v.vin,+v.miles,$c(v.cost),/Trade-in/.test(v.notes||'')?'Trade-in':/Repo/.test(v.notes||'')?'Repossession':'Purchase'])]], ['deal','saleslog','Sales log','Every deal in the range with the main numbers',1,()=>[['Date','Deal #','Customer','Vehicle','Type','Salesperson','Price','Doc fee','Tax','Down','Financed','Front gross'],S.deals.filter(d=>inR(d.date)).map(d=>[d.date,d.no,cust(d.customerId)?.name,vname(veh(d.vehicleId)),d.type,uname(d.salespersonId),$c(d.price),$c(d.docFee),$c(d.tax),$c(d.type==='Cash'?d.cashDue:d.down),$c(d.financed),$c(d.gross)])]], ['deal','byrep','Sales by salesperson','Units, gross and commission by rep',1,()=>{const st=S.settings;const g={};S.deals.filter(d=>inR(d.date)).forEach(d=>{const k=d.salespersonId||'';g[k]=g[k]||[0,0,0];g[k][0]++;g[k][1]+=d.gross;g[k][2]+=Math.max(+st.commMin||0,d.gross*(+st.commPct||0)/100)});return[['Salesperson','Units','Front gross','Avg gross','Est. commission'],Object.entries(g).map(([k,x])=>[uname(k),x[0],$c(x[1]),$c(x[1]/x[0]),$c(x[2])])]}], ['deal','bytype','Sales by deal type','Cash vs. outside finance vs. BHPH',1,()=>[['Type','Units','Total sales','Front gross','Avg down','Total financed'],['Cash','Retail Finance','BHPH'].map(t=>{const l=S.deals.filter(d=>inR(d.date)&&d.type===t);return[t,l.length,$c(l.reduce((a,d)=>a+d.price,0)),$c(l.reduce((a,d)=>a+d.gross,0)),$c(l.length?l.reduce((a,d)=>a+(+d.down||0),0)/l.length:0),$c(l.reduce((a,d)=>a+d.financed,0))]})]], ['deal','trades','Trade-ins taken','Trades on deals in the range',1,()=>[['Date','Deal #','Customer','Trade vehicle','Trade VIN','Allowance','Payoff owed','Equity'],S.deals.filter(d=>inR(d.date)&&d.tradeDesc).map(d=>[d.date,d.no,cust(d.customerId)?.name,d.tradeDesc,d.tradeVin||'',$c(d.tradeAllow),$c(d.tradePayoff),$c(d.tradeAllow-d.tradePayoff)])]], ['deal','payoffs','Trade payoffs owed','Liens to pay off on traded vehicles',0,()=>[['Date','Deal #','Customer','Trade','Payoff'],S.deals.filter(d=>+d.tradePayoff>0).map(d=>[d.date,d.no,cust(d.customerId)?.name,d.tradeDesc,$c(d.tradePayoff)])]], ['deal','lenders','Outside finance by lender','Funded amounts by lender',1,()=>{const g={};S.deals.filter(d=>inR(d.date)&&d.type==='Retail Finance').forEach(d=>{const k=d.lender||'(none)';g[k]=g[k]||[0,0];g[k][0]++;g[k][1]+=d.financed});return[['Lender','Deals','Amount funded'],Object.entries(g).map(([k,x])=>[k,x[0],$c(x[1])])]}], ['cust','leads','Lead list','Leads created in the range',1,()=>[['Created','Name','Phone','Source','Stage','Assigned to','Next step'],S.customers.filter(c=>inR(c.created)).map(c=>[c.created,c.name,c.phone,c.source,c.stage,uname(c.ownerId),c.next?nxLabel(c.next).replace(/^\S+ /,''):''])]], ['cust','conv','Lead source conversion','Leads vs. sales by source',0,()=>{const g={};S.customers.forEach(c=>{g[c.source]=g[c.source]||[0,0];g[c.source][0]++;if(c.stage==='Sold')g[c.source][1]++});return[['Source','Leads','Sold','Close rate'],Object.entries(g).map(([k,x])=>[k,x[0],x[1],Math.round(x[1]/x[0]*100)+'%'])]}], ['cust','nostep','Leads without a next step','Open leads nobody has scheduled',0,()=>[['Name','Phone','Stage','Assigned to','Last contact'],S.customers.filter(c=>isLead(c)&&!c.next).map(c=>{const m=lastMsg(c.id);return[c.name,c.phone,c.stage,uname(c.ownerId),m?m.at.slice(0,10):'Never']})]], ['cust','fu','Follow-ups due','Next steps due today or overdue',0,()=>[['Due','Time','Name','Phone','Action','Assigned to','Plan'],S.customers.filter(c=>c.next&&c.next.date<=TODAY&&isLead(c)).sort((a,b)=>a.next.date.localeCompare(b.next.date)).map(c=>[c.next.date,nxTime(c.next.time),c.name,c.phone,c.next.type,uname(c.ownerId),c.next.note||''])]], ['cust','lost','Lost leads by reason','Why leads were closed',0,()=>{const g={};S.customers.filter(c=>c.stage==='Lost').forEach(c=>{const n=[...c.notes].reverse().find(n=>/Lead closed – /.test(n.text));const k=n?n.text.split('– ')[1]:'Not recorded';g[k]=(g[k]||0)+1});return[['Reason','Leads'],Object.entries(g)]}], ['cust','contacts','Customer contact list','Everyone with contact permissions',0,()=>[['Name','Phone','Email','Stage','Texts/auto calls OK','Opted out','Do not call','Preferred'],S.customers.map(c=>[c.name,c.phone,c.email,c.stage,c.smsConsent?'Yes':'No',c.optOut?'Yes':'',c.dnc?'Yes':'',c.prefContact||''])]], ['cust','activity','Calls & texts log','All contact activity in the range',1,()=>[['When','Customer','Type','Direction','Result','By','Details'],S.comms.filter(x=>inR(x.at.slice(0,10))).sort((a,b)=>b.at.localeCompare(a.at)).map(x=>[x.at.replace('T',' '),cust(x.customerId)?.name,x.channel,x.dir,x.outcome||'',x.by||'',x.body])]], ['bhph','portfolio','Portfolio summary','Active BHPH accounts at a glance',0,()=>{const a=S.loans.filter(l=>l.status==='Active');return[['Measure','Value'],[['Active accounts',a.length],['Principal outstanding',$c(a.reduce((x,l)=>x+l.balance,0))],['Original amount financed',$c(a.reduce((x,l)=>x+l.principal,0))],['Accounts past due',a.filter(l=>daysLate(l)>0).length],['Past-due amount',$c(a.reduce((x,l)=>x+pastDue(l),0))],['Late fees owed',$c(a.reduce((x,l)=>x+l.lateFeesDue,0))],['Weighted avg APR',(a.reduce((x,l)=>x+l.apr*l.balance,0)/Math.max(1,a.reduce((x,l)=>x+l.balance,0))).toFixed(2)+'%'],['Paid off (all time)',S.loans.filter(l=>l.status==='Paid Off').length],['Repossessed',S.loans.filter(l=>l.status==='Repossessed').length],['Charged off',S.loans.filter(l=>l.status==='Charged Off').length]]]}], ['bhph','agingd','Accounts by days late','Every active account with delinquency',0,()=>[['Account','Customer','Phone','Days late','Bucket','Past due','Late fees','Balance','Next due'],S.loans.filter(l=>l.status==='Active').sort((a,b)=>daysLate(b)-daysLate(a)).map(l=>{const d=daysLate(l);return[l.acct,cust(l.customerId)?.name,cust(l.customerId)?.phone,d,d===0?'Current':d<=30?'1–30':d<=60?'31–60':d<=90?'61–90':'90+',$c(pastDue(l)),$c(l.lateFeesDue),$c(l.balance),nextDue(l)||'']})]], ['bhph','payments','Payment history','BHPH payments received in the range',1,()=>{const rows=[];S.loans.forEach(l=>l.payments.forEach(p=>{if(inR(p.date))rows.push([p.date,p.receipt,l.acct,cust(l.customerId)?.name,p.method,$c(p.amount),$c(p.fee),$c(p.interest),$c(p.principal)])}));return[['Date','Receipt','Account','Customer','Method','Amount','Late fee','Interest','Principal'],rows.sort((a,b)=>b[0].localeCompare(a[0]))]}], ['bhph','expected','Expected collections','Scheduled payments due in the range',1,()=>{const rows=[];S.loans.filter(l=>l.status==='Active').forEach(l=>{for(let k=0;kui.rep.to)break;if(inR(d))rows.push([d,l.acct,cust(l.customerId)?.name,FREQ[l.freq].label,$c(l.payment),ka[0].localeCompare(b[0]))]}], ['bhph','promises','Promises to pay','Open and broken promises',0,()=>[['Account','Customer','Promise date','Amount','Status','Days late'],S.loans.filter(l=>l.status==='Active'&&l.promise).map(l=>[l.acct,cust(l.customerId)?.name,l.promise.date,$c(l.promise.amount),l.promise.date[['Account','Customer','Status','Closed','Original','Balance at close','Payments'],S.loans.filter(l=>l.status!=='Active').map(l=>[l.acct,cust(l.customerId)?.name,l.status,l.closedDate||'',$c(l.principal),$c(l.balance),l.payments.length])]], ['acct','pl','Profit & loss','Revenue and expenses in the range',1,()=>{const t=S.txns.filter(x=>inR(x.date));const sum=c=>t.filter(x=>x.cat===c).reduce((a,x)=>a+x.amount,0);const rev=['Vehicle Sales','Doc Fees','Interest Income','Late Fee Income'],exp=['Cost of Vehicles Sold','Reconditioning'];const other=[...new Set(t.filter(x=>!CATS[x.cat]).map(x=>x.cat))];const tr=rev.reduce((a,c)=>a+sum(c),0),te=[...exp,...other].reduce((a,c)=>a+sum(c),0); return[['Line','Amount'],[...rev.map(c=>[c,$c(sum(c))]),['Total revenue',$c(tr)],...[...exp,...other].map(c=>[c,$c(-sum(c))]),['Total expenses',$c(-te)],['Net income',$c(tr-te)]]]}], ['acct','journal','General journal','Every transaction in the range',1,()=>[['Date','Category','Ref','Description','Amount'],S.txns.filter(x=>inR(x.date)).sort((a,b)=>a.date.localeCompare(b.date)).map(x=>[x.date,x.cat,x.ref,x.desc,$c(x.amount)])]], ['acct','expcat','Expenses by category','Spend grouped by account',1,()=>{const g={};S.txns.filter(x=>inR(x.date)&&(CATS[x.cat]==='exp'||CATS[x.cat]==='cashout'||!CATS[x.cat])).forEach(x=>g[x.cat]=(g[x.cat]||0)+x.amount);return[['Category','Amount'],Object.entries(g).sort((a,b)=>b[1]-a[1]).map(([k,v])=>[k,$c(v)])]}], ['acct','receipts','Cash receipts','Money in, by type',1,()=>[['Date','Type','Ref','Description','Amount'],S.txns.filter(x=>inR(x.date)&&CATS[x.cat]==='cashin').sort((a,b)=>a.date.localeCompare(b.date)).map(x=>[x.date,x.cat,x.ref,x.desc,$c(x.amount)])]], ['acct','checks','Check register','Checks written in the range',1,()=>[['Check #','Date','Payee','Account','Memo','Amount','Status'],(S.checks||[]).filter(c=>inR(c.date)).map(c=>[c.no,c.date,c.payee,c.cat,c.memo||'',$c(c.amount),c.status])]], ['tax','salestax','Sales tax collected','Tax by deal, for your state return',1,()=>[['Date','Deal #','Customer','Taxable amount','Rate','Tax collected'],S.deals.filter(d=>inR(d.date)).map(d=>[d.date,d.no,cust(d.customerId)?.name,$c(d.taxable),d.taxRate+'%',$c(d.tax)])]], ['tax','title','Title status report','Where every deal\'s title work stands',0,()=>[['Deal #','Date','Customer','Vehicle','State','Status','Temp tag','Temp expires','Sent','Plate','Title #'],S.deals.map(d=>{const t=dealTitle(d);return[d.no,d.date,cust(d.customerId)?.name,vname(veh(d.vehicleId)),t.state,t.status,t.tempTag,t.tempExp,t.sent,t.plate,t.titleNo]})]], ['tax','temptags','Temp tags expiring','Temp tags expiring in the next 14 days or already expired',0,()=>[['Deal #','Customer','Temp tag','Expires','Days left','Status'],S.deals.map(d=>[d,dealTitle(d)]).filter(([d,t])=>t.tempExp&&t.status!=='Complete'&&diff(TODAY,t.tempExp)<=14).map(([d,t])=>[d.no,cust(d.customerId)?.name,t.tempTag,t.tempExp,diff(TODAY,t.tempExp),t.status])]], ['recon','open','Open recon tasks','Everything not yet done',0,()=>{const rows=[];S.vehicles.forEach(v=>(v.tasks||[]).filter(t=>!['Done','Declined'].includes(t.status)).forEach(t=>rows.push([v.stock,vname(v),t.desc,t.cat,vendor(t.vendorId)?.name||'',t.status,$c(t.est),diff(t.created,TODAY)])));return[['Stock','Vehicle','Task','Category','Vendor','Status','Estimate','Age (days)'],rows]}], ['recon','vendor','Recon spend by vendor','Completed work in the range',1,()=>{const g={};S.vehicles.forEach(v=>(v.tasks||[]).filter(t=>t.status==='Done'&&inR(t.done)).forEach(t=>{const k=vendor(t.vendorId)?.name||'(no vendor)';g[k]=g[k]||[0,0];g[k][0]++;g[k][1]+=+t.actual}));return[['Vendor','Jobs','Spend'],Object.entries(g).map(([k,x])=>[k,x[0],$c(x[1])])]}], ['recon','days','Days in recon','Time each vehicle spent (or is spending) in recon',0,()=>[['Stock','Vehicle','Started','Finished','Days','Stage','Recon $'],S.vehicles.filter(v=>v.reconStart).map(v=>[v.stock,vname(v),v.reconStart,v.reconDone||'',reconDays(v),v.status==='In Recon'?v.reconStage:'Done',$c(reconTotal(v))])]], ['mkt','feedready','Listing readiness','Published cars and what they\'re missing',0,()=>[['Stock','Vehicle','Price','Photos','Description','VIN OK','Days online'],S.vehicles.filter(v=>v.published&&v.status==='Available').map(v=>[v.stock,vname(v),$c(v.price),(v.photos||[]).length,(v.notes||'').trim()?'Yes':'Missing',v.vin&&v.vin.length===17?'Yes':'No',age(v)])]], ['mkt','webleads','Website & marketplace leads','Leads by online source in the range',1,()=>[['Created','Name','Source','Stage','Assigned','Interest'],S.customers.filter(c=>inR(c.created)&&['Website','Marketplace','Facebook'].includes(c.source)).map(c=>[c.created,c.name,c.source,c.stage,uname(c.ownerId),c.interest||''])]], ['admin','comm','Commission report','Commission by deal for payroll',1,()=>{const st=S.settings;return[['Date','Deal #','Salesperson','Customer','Front gross','Commission'],S.deals.filter(d=>inR(d.date)).map(d=>[d.date,d.no,uname(d.salespersonId),cust(d.customerId)?.name,$c(d.gross),$c(Math.max(+st.commMin||0,d.gross*(+st.commPct||0)/100))])]}], ['admin','useract','Activity by user','Calls, texts and notes logged per person',1,()=>{const g={};S.comms.filter(x=>inR(x.at.slice(0,10))&&x.by).forEach(x=>{g[x.by]=g[x.by]||[0,0];g[x.by][x.channel==='call'?0:1]++});return[['User','Calls','Texts'],Object.entries(g).map(([k,x])=>[k,x[0],x[1]])]}], ['admin','users','Users & access','Who can open what',0,()=>[['Name','Role','Status','Last sign-in','Sections'],S.users.map(u=>[u.name,u.role,u.active?'Active':'Disabled',u.lastLogin||'Never',u.role==='Owner'?'All':(S.roles[u.role]||[]).length+' sections'])]], ].map(r=>({cat:r[0],id:r[1],n:r[2],d:r[3],range:!!r[4],run:r[5]})); const cellTxt=c=>c&&typeof c==='object'?c.t:c??'';const cellVal=c=>c&&typeof c==='object'?c.v:c; function repTable(R){const [cols,rows0]=R.run();let rows=rows0.slice();if(ui.rep.sort!=null){const k=ui.rep.sort,dir=ui.rep.dir;rows.sort((a,b)=>{const x=cellVal(a[k]),y=cellVal(b[k]);return (typeof x==='number'&&typeof y==='number'?x-y:String(x??'').localeCompare(String(y??'')))*dir})} const money=cols.map((c,i)=>rows.some(r=>r[i]&&typeof r[i]==='object'&&r[i].m));const tot=cols.map((c,i)=>money[i]?rows.reduce((a,r)=>a+(cellVal(r[i])||0),0):null); return{cols,rows,html:`${cols.map((c,i)=>``).join('')}${rows.map(r=>`${r.map((c,i)=>``).join('')}`).join('')||``}${rows.length&&tot.some(x=>x!=null)?`${cols.map((c,i)=>``).join('')}`:''}
${esc(c)}${ui.rep.sort===i?(ui.rep.dir===1?' ▲':' ▼'):''}
${esc(cellTxt(c))}
No data for this report${R.range?' in this date range':''}
${i===0?'Total ('+rows.length+')':tot[i]!=null?$$(tot[i]):''}
`}} function repCSV(R){const t=repTable(R);return [t.cols,...t.rows.map(r=>r.map(c=>typeof c==='object'&&c?c.v:c))].map(r=>r.map(csvq).join(',')).join('\n')} async function repDownload(id){const R=REPORTS.find(x=>x.id===id);const csv=repCSV(R);if(DL){try{await DL.save({filename:`${R.n.replace(/\W+/g,'-').toLowerCase()}-${TODAY}.csv`,data:csv});toast('Report saved')}catch(e){if(e.code!=='declined')copyText(csv)}}else copyText(csv)} async function repPrint(id){const R=REPORTS.find(x=>x.id===id);const t=repTable(R);const doc=`${esc(R.n)}

${esc(R.n)}

${esc(S.settings.dealer)} · ${R.range?fdate(ui.rep.from)+' – '+fdate(ui.rep.to):'As of '+fdate(TODAY)} · run ${fdate(TODAY)} by ${esc(S.settings.user)}
${t.html.replace(/ onclick="[^"]*"/g,'').replace(/ style="cursor:pointer"/g,'')}`; if(DL){try{await DL.save({filename:`${R.n.replace(/\W+/g,'-').toLowerCase()}-${TODAY}.html`,data:doc});toast('Saved – open it and click Print')}catch(e){if(e.code!=='declined')copyText(doc)}}else copyText(doc)} const RANGES=[['This month',()=>[TODAY.slice(0,8)+'01',TODAY]],['Last month',()=>{const f=addMonths(TODAY.slice(0,8)+'01',-1);return[f,addDays(TODAY.slice(0,8)+'01',-1)]}],['Last 30 days',()=>[addDays(TODAY,-30),TODAY]],['Year to date',()=>[TODAY.slice(0,4)+'-01-01',TODAY]],['Last 12 months',()=>[addMonths(TODAY,-12),TODAY]],['All time',()=>['2000-01-01','2099-12-31']]]; VIEWS.reports=()=>{ui.rep=ui.rep||{cat:'fav',id:null,from:TODAY.slice(0,8)+'01',to:TODAY,sort:null,dir:1,q:''};S.favReports=S.favReports||['saleslog','agingd','active','pl'];const P=ui.rep; const tabs=`
`; if(P.view==='overview')return tabs+overviewReports(); if(P.id){const R=REPORTS.find(x=>x.id===P.id);const t=repTable(R);const fav=S.favReports.includes(R.id); return tabs+`

${esc(R.n)}

${R.range?``:'As of today'}

${esc(R.d)} · ${t.rows.length} row(s) · click a column to sort

${t.html}
`} const q=(P.q||'').toLowerCase();const list=REPORTS.filter(r=>q?(r.n+' '+r.d).toLowerCase().includes(q):P.cat==='fav'?S.favReports.includes(r.id):r.cat===P.cat); return tabs+`
${RCATS2.map(c=>``).join('')}
Scheduled email delivery comes with the server build
${list.map(r=>`
${esc(r.n)}${esc(r.d)}
${esc(RCATS2.find(c=>c[0]===r.cat)[2])}
`).join('')||'
No reports here yet. Star reports to add them to Favorites.
'}
`}; /* ---- settings ---- */ VIEWS.settings=()=>{const s=S.settings;return `
Dealership
Deal defaults
BHPH collections
Sales commission
Reconditioning
BHPH collections
${usersSettings()} ${esaSettings()} ${bookoutSettings()} ${dbCard()}${importCard()}${storesCard()}${affCard()}${apiCard()} ${connectionsCard()}

✦ AI features

AI runs on Claude using the account of whoever is signed in. Turn the master switch off to hide every AI feature, or switch features on and off one by one.

${AIFEAT.map(f=>``).join('')}

Calls & texting

Right now, Call and Text open your own phone or Messages app with the number and message filled in, and DealerPen keeps the history. To send texts and place calls straight from DealerPen, including two-way inbox, automatic payment reminders and call recording, it needs to be connected to a texting and calling provider such as Twilio. That requires a small server, which is the next build step. Only text customers who have agreed to receive texts, honor STOP replies, and keep collection contacts between 8am and 9pm.

Data

${storageMsg()}

`}; AFTER.settings=()=>{$('#sf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);Object.assign(S.settings,x,{taxRate:+x.taxRate,docFee:+x.docFee,apr:+x.apr,term:+x.term,lateFee:+x.lateFee,graceDays:+x.graceDays,reconBudget:+x.reconBudget,reconTarget:+x.reconTarget,approvalLimit:+x.approvalLimit,holdingCost:+x.holdingCost,aprCap:+x.aprCap||0,formColor:x.formColor,state:x.state,nextActionPrompt:!!x.nextActionPrompt,commPct:+x.commPct,commMin:+x.commMin,unitGoal:+x.unitGoal,dealerLicense:x.dealerLicense});save();render();toast('Settings saved')}}; function backup(){const j=JSON.stringify(S);openModal(mh('Backup')+`
`);$('#cp').onclick=()=>copyText(j)} function restore(){openModal(mh('Restore from backup')+`
`); $('#rs').onclick=()=>{try{const o=JSON.parse($('#rj').value);if(!o.vehicles||!o.settings)throw 0;S=o;save();closeModal();render();toast('Restored')}catch(e){toast('That doesn\'t look like a valid backup')}}} /* ---- global search ---- */ $('#q').addEventListener('input',e=>{const q=e.target.value.trim().toLowerCase();const box=$('#sres');if(q.length<2){box.style.display='none';return} const r=[];S.vehicles.forEach(v=>{if([v.stock,v.vin,vname(v)].join(' ').toLowerCase().includes(q))r.push([`🚗 ${v.stock} · ${vname(v)}`,`vehModal('${v.id}')`])}); S.customers.forEach(c=>{if([c.name,c.phone,c.email].join(' ').toLowerCase().includes(q))r.push([`👤 ${c.name} · ${c.phone}`,`custModal('${c.id}')`])}); S.loans.forEach(l=>{if((l.acct+' '+cust(l.customerId)?.name).toLowerCase().includes(q))r.push([`▤ ${l.acct} · ${cust(l.customerId)?.name} · ${$$(l.balance)}`,`acctModal('${l.id}')`])}); S.deals.forEach(d=>{if(('#'+d.no).includes(q))r.push([`✎ Deal #${d.no} · ${cust(d.customerId)?.name}`,`dealView('${d.id}')`])}); box.innerHTML=r.slice(0,12).map(x=>`
${esc(x[0])}
`).join('')||'
No matches
';box.style.display='block'}); document.addEventListener('click',e=>{if(!e.target.closest('.search'))$('#sres').style.display='none'}); /* ---- boot ---- */ /* ================= Settings menu (left navigation) ================= */ const SETMENU=[ ['Dealership',[['general','General'],['stores','Stores'],['go:website','Website'],['go:feeds','Listing feeds']]], ['Admin',[['new:user','+ New user'],['users','Manage users & roles'],['access','User access logs'],['events','Company events'],['security','Sign-in & security']]], ['Sales & deals',[['deal','Deal defaults & commission'],['fn:payPlansModal','Pay plans'],['go:finance:lenders','Lender programs'],['bookout','Book values'],['go:crm:plans','Follow-up plans']]], ['Inventory',[['recon','Reconditioning']]], ['BHPH',[['bhph','Collections & late fees']]], ['Paperwork',[['esign','Forms & e-signature'],['go:forms:packs','Print packs']]], ['Communication',[['phone','Phone, texting & email'],['go:contact','Support contacts']]], ['AI',[['ai','AI features']]], ['Partners',[['connections','Connections & sign-ups'],['affiliate','Affiliate programs'],['api','API & webhooks']]], ['Data',[['import','Import data'],['data','Backup & reset']]], ['My account',[['me','My account']]]]; const SET_CARD_RULES=[['users',/Users\s*&\s*roles/i],['esign',/E-Sign/i],['bookout',/Bookout|Black Book/i],['security',/Shared database/i],['import',/^Import from/i],['stores',/^Stores/i],['affiliate',/Affiliate/i],['api',/API\s*&\s*webhooks/i],['connections',/Connections/i],['ai',/AI features/i],['phone',/Calls\s*&\s*texting/i],['data',/^Data/i],['access',/User access logs/i],['events',/Company events/i],['me',/My account/i]]; const SET_FORM_RULES=[['general_old',/^Dealership/i],['deal',/Deal defaults|Sales commission/i],['bhph',/BHPH/i],['recon',/Reconditioning/i]]; function setGo(id){const [k,a,b]=id.split(':');if(k==='new'){userModal();return}if(k==='fn'){window[a]&&window[a]();return}if(k==='go'){if(a==='finance')ui.finTab=b;if(a==='crm')ui.crmView=b;if(a==='forms')ui.formTab=b;go(a);return}ui.setCat=id;setApply();const m=document.querySelector('.set-body');if(m)m.scrollTop=0;window.scrollTo&&window.scrollTo(0,0)} function setApply(){const cat=ui.setCat||'general';document.querySelectorAll('.set-nav [data-s]').forEach(b=>{b.classList.toggle('on',b.dataset.s===cat);b.setAttribute('aria-current',b.dataset.s===cat?'page':'false')}); const body=document.querySelector('.set-body');if(!body)return;const formCard=$('#sf')?.closest('.card'); [...body.children].forEach(card=>{if(card===formCard)return;const h=(card.querySelector('h3')?.textContent||'').trim();const r=SET_CARD_RULES.find(x=>x[1].test(h));card.style.display=r&&r[0]===cat?'':'none'}); if(formCard){const inForm=SET_FORM_RULES.some(r=>r[0]===cat);formCard.style.display=inForm?'':'none';if(inForm){let curK=null;[...$('#sf .form').children].forEach(el=>{if(el.classList.contains('fsec')){const r=SET_FORM_RULES.find(x=>x[1].test(el.textContent.trim()));curK=r?r[0]:null;const nx=el.nextElementSibling;el.style.display=curK===cat&&nx&&!nx.classList.contains('fsec')?'':'none';return}el.style.display=curK===cat?'':'none'})}} const hd=document.querySelector('.set-title');if(hd){const it=SETMENU.flatMap(g=>g[1]).find(i=>i[0]===cat);hd.textContent=it?it[1]:'Settings'}} function accessCard(){const own=me()?.role==='Owner';if(!own)return '';const log=(S.accessLog||[]).slice().reverse().slice(0,200);return `

User access logs

Sign-ins on this DealerPen${DBM.mode?' server':''}. Newest first.

${log.map(l=>``).join('')||''}
WhenUserRoleHow
${ftime(l.at)}${esc(uname(l.userId))}${esc(S.users.find(u=>u.id===l.userId)?.role||'')}${esc(l.how||'')}
No sign-ins recorded yet

Last sign-in by user

${S.users.map(u=>``).join('')}
${esc(u.name)}${u.lastLogin?ftime(u.lastLogin):'Never'}${u.active?'Active':'Inactive'}
`} function logAccess(u,how){S.accessLog=S.accessLog||[];S.accessLog.push({id:uid(),userId:u.id,at:nowAt(),how});if(S.accessLog.length>600)S.accessLog=S.accessLog.slice(-500);u.lastLogin=nowAt()} function eventsCard(){const ev=(S.companyEvents||[]).slice().sort((a,b)=>(a.date+a.time).localeCompare(b.date+b.time));const up=ev.filter(e=>e.date>=TODAY),past=ev.filter(e=>e.date`${esc(e.title)}${e.notes?`
${esc(e.notes)}
`:''}${fdate(e.date)} ${esc(e.time||'')}Add to Google Calendar${canEdit?` `:''}`; return `

Company events${canEdit?'':''}

Sales events, holidays, closures and meetings for the whole dealership. They also appear on everyone’s DealerPen calendar link.

${up.map(row).join('')||''}
No upcoming events
${past.length?`

Past

${past.map(row).join('')}
`:''}
`} function eventModal(){openModal(mh('Add company event')+`
`); $('#evf').onsubmit=e=>{e.preventDefault();S.companyEvents=S.companyEvents||[];S.companyEvents.push({id:uid(),...fd(e.target),by:me()?.id});save();closeModal();render();toast('Event added')}} function myAccountCard(){const u=me();if(!u)return '';return `

My account

${DBM.mode?``:''}${DBM.mode?``:''}

Ask the owner to change your name, email or role.

`} /* ================= Website theme gallery ================= */ Object.assign(WTPL,{ nightdrive:{n:'Night Drive',d:'Deep navy with electric blue, great for luxury and late models',primary:'#3b82f6',accent:'#22d3ee',bg:'#ffffff',ink:'#0b1220',font:"'Inter',sans-serif",head:"'Inter',sans-serif",hero:'dark',radius:12,upper:false,isNew:1,tier:'pro'}, redline:{n:'Redline',d:'Black and red, made for performance and sport cars',primary:'#d61f26',accent:'#111111',bg:'#ffffff',ink:'#111111',font:"'Archivo',sans-serif",head:"'Archivo Black',sans-serif",hero:'dark',radius:6,upper:true,isNew:1,tier:'pro'}, coastline:{n:'Coastline',d:'Bright, airy blues for a friendly neighborhood lot',primary:'#0284c7',accent:'#f59e0b',bg:'#f8fbff',ink:'#0c2a3f',font:"'Inter',sans-serif",head:"'Archivo',sans-serif",hero:'light',radius:18,upper:false,isNew:1,tier:'plus'}, torque:{n:'Torque',d:'Orange and charcoal, built for trucks and work vehicles',primary:'#ea580c',accent:'#1f2937',bg:'#ffffff',ink:'#1f2937',font:"'Archivo',sans-serif",head:"'Archivo Black',sans-serif",hero:'color',radius:4,upper:true,tier:'plus'}, evergreen:{n:'Evergreen',d:'Calm greens with a payment-first layout for in-house financing',primary:'#15803d',accent:'#0369a1',bg:'#f7fbf8',ink:'#14281d',font:"'Inter',sans-serif",head:"'Inter',sans-serif",hero:'split',radius:12,upper:false,payFirst:true,tier:'plus'}, velocity:{n:'Velocity',d:'Violet and blue gradients for a modern, tech-savvy feel',primary:'#6d28d9',accent:'#2563eb',bg:'#ffffff',ink:'#1e1b4b',font:"'Inter',sans-serif",head:"'Archivo',sans-serif",hero:'color',radius:16,upper:false,tier:'pro'}, heritage:{n:'Heritage',d:'Burgundy and cream, a classic family-owned look',primary:'#7f1d1d',accent:'#b45309',bg:'#fbf7f2',ink:'#2b1d14',font:"'Inter',sans-serif",head:"'Playfair Display',serif",hero:'light',radius:6,upper:false,tier:'plus'}, motogarage:{n:'Moto Garage',d:'Gritty black and red for motorcycles and powersports',primary:'#dc2626',accent:'#f59e0b',bg:'#0f0f10',ink:'#111111',font:"'Archivo',sans-serif",head:"'Archivo Black',sans-serif",hero:'dark',radius:2,upper:true,tier:'moto'}, sunsetlot:{n:'Sunset Lot',d:'Warm amber and plum, inviting and upbeat',primary:'#b45309',accent:'#7c3aed',bg:'#fffaf3',ink:'#2a1a0e',font:"'Inter',sans-serif",head:"'Archivo',sans-serif",hero:'split',radius:14,upper:false,tier:'plus'}}); Object.assign(WTPL.modern,{tier:'pro'});Object.assign(WTPL.bold,{tier:'plus'});Object.assign(WTPL.credit,{tier:'plus'});Object.assign(WTPL.classic,{tier:'plus'});Object.assign(WTPL.minimal,{tier:'pro'}); const TIERS={plus:'Premium Plus',pro:'Premium Pro',moto:'Motorcycles'}; const thPrice=t=>{const p=(S.settings.themePrices||{})[t];return p?`${$$(p)}/month`:'Included'}; const THEME_ORDER=['nightdrive','redline','coastline','modern','credit','evergreen','torque','velocity','bold','heritage','classic','motogarage','sunsetlot','minimal']; function themeData(id){const D=siteData();const T=WTPL[id];return{...D,T:{...T},site:{...D.site,template:id}}} function themeGallery(){const cur=siteCfg().template;const f=ui.thF||'all';const list=THEME_ORDER.filter(id=>WTPL[id]&&(f==='all'||(f==='new'&&WTPL[id].isNew)||(f==='bhph'&&WTPL[id].payFirst)||WTPL[id].tier===f));const ps=S.settings.themePrices||{};const nums=Object.values(ps).map(Number).filter(n=>n>0);const from=nums.length?Math.min(...nums):0;const own=me()?.role==='Owner'; return `

Stunning, mobile-friendly, fully customizable websites${from?` starting at ${$$(from)}/month`:' included with DealerPen'}

${own?``:''}
${[['screen','Mobile optimized','Looks great on any device'],['calc','Built-in payment calculator','Shows estimated payments on every car'],['grid','Large theme collection',WTPLcount()+' designer themes to customize'],['link','Unified online marketing','Leads, listing feeds and CRM in one place']].map(x=>`
${thIco(x[0])}${x[1]}${x[2]}
`).join('')}
${[['all','View all'],['plus','Premium Plus'],['pro','Premium Pro'],['moto','Motorcycles'],['new','New'],['bhph','Payment-first']].map(x=>``).join('')}
${list.map(id=>{const T=WTPL[id];return `
${T.isNew?'NEW':''}
${esc(T.n)}
${esc(T.d)}
${cur===id?'Your current theme':`${TIERS[T.tier]||''} · ${thPrice(T.tier)}`}
${cur===id?``:``}
`}).join('')}
`} function themeRender(host,id,dev){const D=themeData(id);const sr=host.shadowRoot||host.attachShadow({mode:'open'});sr.innerHTML=siteHTML(D);const ws=sr.querySelector('.ws');if(ws&&dev==='mob')ws.classList.add('mob');if(ws&&host.closest('.th-screen,.th-phscreen')){ws.style.display='block';ws.style.width=dev==='mob'?'375px':'1280px'}try{siteRuntime(sr,D,{svg:carSVG,lead:()=>Promise.resolve()})}catch(e){}} function themeDrawAll(){const hosts=[...document.querySelectorAll('.th-host')];let i=0;const step=()=>{const t0=performance.now();while(i{openModal(mh('Live demo · '+esc(T.n))+`
${esc(T.d)}. Shown with your real inventory. Click around; forms here don’t create leads.
${cur?``:``}
`,true); $('#modal').classList.add('xl');themeRender($('#thdemo'),id,dev);$('#thd').onclick=()=>{dev='desk';draw()};$('#thm').onclick=()=>{dev='mob';draw()}};draw()} function useTheme(id){const s=siteCfg();const prev=s.template;S.site.template=id;S.site.primary='';S.site.accent='';save();closeModal();ui.webTab='custom';render();toast(`Theme changed to ${WTPL[id].n}. Your text and settings were kept`); if(prev&&prev!==id)setTimeout(()=>{const t=document.createElement('div');t.className='toast-undo';t.innerHTML=``;t.querySelector('button').onclick=()=>{S.site.template=prev;save();render();t.remove()};document.body.appendChild(t);setTimeout(()=>t.remove(),8000)},50)} {const _web=VIEWS.website,_after=AFTER.website; VIEWS.website=()=>{const tab=ui.webTab||'themes';return `
${[['themes','Themes'],['custom','Customize & publish']].map(t=>``).join('')}
`+(tab==='themes'?themeGallery():_web())}; AFTER.website=()=>{if((ui.webTab||'themes')==='themes')return themeDrawAll();_after&&_after()}} const THCSS=`.th-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:18px}.th-card{background:#fff;border:1px solid var(--line);border-radius:12px;overflow:hidden;box-shadow:var(--shadow);display:flex;flex-direction:column}.th-card.cur{border-color:var(--green);box-shadow:0 0 0 2px var(--greensoft)} .th-prev{position:relative;height:250px;background:linear-gradient(#f7f8fa,#eef0f4);cursor:pointer;overflow:hidden}.th-prev:focus-visible{outline:3px solid #a9c1ff;outline-offset:-3px}.th-new{position:absolute;right:12px;bottom:34px;z-index:3;width:46px;height:46px;border-radius:50%;background:#d61f26;color:#fff;font:800 11px/46px Inter,sans-serif;text-align:center;box-shadow:0 2px 6px rgba(0,0,0,.25)} .th-mon{position:absolute;left:50%;top:16px;transform:translateX(-50%);width:244px}.th-screen{width:244px;height:153px;border:7px solid #1d2939;border-radius:8px 8px 0 0;overflow:hidden;background:#fff;position:relative}.th-stand{height:16px;background:linear-gradient(#d0d5dd,#e4e7ec);border-radius:0 0 6px 6px;width:244px}.th-stand:after{content:'';display:block;width:60px;height:10px;margin:16px auto 0;background:#d0d5dd;border-radius:3px} .th-screen .th-host{display:block;width:1280px;height:802px;transform:scale(.1797);transform-origin:0 0;pointer-events:none}.th-phone{position:absolute;left:calc(50% - 150px);top:70px;width:70px;height:140px;border:4px solid #101828;border-radius:12px;background:#fff;overflow:hidden;box-shadow:0 6px 14px rgba(16,24,40,.25)}.th-phscreen .th-host{display:block;width:375px;height:750px;transform:scale(.1653);transform-origin:0 0;pointer-events:none} .th-dots{position:absolute;bottom:10px;left:0;right:0;display:flex;justify-content:center;gap:5px}.th-dots i{width:7px;height:7px;border-radius:50%;border:1px solid #98a2b3}.th-dots i.on{background:#475467;border-color:#475467} .th-foot{display:flex;gap:10px;align-items:flex-start;justify-content:space-between;padding:12px 14px;background:#fafbfc;border-top:1px solid var(--line);flex:1}.th-desc{font-size:12px;margin:2px 0 4px}.th-price{font-size:13px;color:var(--brand);font-weight:600}.th-btns{display:flex;flex-direction:column;gap:6px;flex:0 0 auto} .modal.xl{max-width:1320px}.th-demo{background:#e4e7ec;padding:16px;display:flex;justify-content:center;max-height:72vh;overflow:auto}.th-demo .th-host{display:block;width:100%;background:#fff;box-shadow:0 4px 16px rgba(16,24,40,.12)}.th-demo.mob .th-host{width:390px;min-height:700px;border:10px solid #101828;border-radius:28px;overflow:hidden} .toast-undo{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:80;background:#101828;padding:8px;border-radius:10px}`; document.head.insertAdjacentHTML('beforeend',''); const WTPLcount=()=>THEME_ORDER.filter(id=>WTPL[id]).length; const THI={screen:'',calc:'',grid:'',link:''}; const thIco=k=>``; function themePricing(){const ps=S.settings.themePrices||{};openModal(mh('Website prices')+`

What you charge dealers each month for a website on each theme tier. Leave a tier blank to show it as included.

${Object.entries(TIERS).map(([k,n])=>``).join('')}
`); $('#tpf').onsubmit=e=>{e.preventDefault();const x=fd(e.target);S.settings.themePrices=Object.fromEntries(Object.entries(x).map(([k,v])=>[k,+v||0]));save();closeModal();render()}} const THCSS2=`.th-hero{background:#fff;border:1px solid var(--line);border-radius:12px;padding:22px;margin-bottom:18px;text-align:center}.th-hero h2{margin:0 0 6px;font-size:21px;font-weight:600;color:var(--ink)}.th-hero h2 b{color:var(--brand);display:block;font-size:26px;margin-top:4px} .th-feats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:18px 0}.th-feat{display:flex;flex-direction:column;align-items:center;gap:4px;color:var(--brand)}.th-feat b{color:var(--ink);font-size:14px}.th-feat span{font-size:12px;color:var(--muted)} .th-pills{display:flex;gap:8px;justify-content:center;flex-wrap:wrap}.th-pills button{border:1.5px solid var(--brand);background:#fff;color:var(--brand);border-radius:8px;padding:7px 14px;font:600 13px inherit;cursor:pointer}.th-pills button.on{background:var(--brand);color:#fff} @media(max-width:800px){.th-feats{grid-template-columns:1fr 1fr}}`; document.head.insertAdjacentHTML('beforeend',''); {const _set=VIEWS.settings;VIEWS.settings=()=>{const own=can('settings');const items=SETMENU; return `

General

${own?_set():''}${accessCard()}${eventsCard()}${myAccountCard()}
`}} {const _after=AFTER.settings;AFTER.settings=()=>{try{_after&&_after()}catch(e){}if(!can('settings')&&(!ui.setCat||ui.setCat==='general'))ui.setCat='me';setApply()}} const SETPAGES={}; /* ================= Settings pages: dealership, website, inventory, customer (leads, assignment, workflows) ================= */ const SG=(path,def)=>{let o=S.settings;for(const k of path.split('.')){if(o==null||typeof o!=='object')return def;o=o[k]}return o===undefined||o===null?def:o}; function SSet(path,val,re){const ks=path.split('.');let o=S.settings;ks.slice(0,-1).forEach(k=>{if(!o[k]||typeof o[k]!=='object')o[k]={};o=o[k]});o[ks[ks.length-1]]=val;save();if(re)setRefresh()} const sid_=()=>'s'+Math.random().toString(36).slice(2,8); const stg=(path,label,hint,def)=>{const i=sid_();return `
`}; const ssel=(path,label,opts,def,hint)=>``; const sinp=(path,label,type,def,hint,ph)=>``; const scard=(title,desc,body,act)=>`

${title}

${act||''}
${desc?`

${desc}

`:''}${body}
`; const slink=(label,fn,hint)=>``; const schoice=(path,opts,def)=>`
${opts.map(([v,l,d])=>``).join('')}
`; const sgrid=(...x)=>`
${x.join('')}
`; const sfld=(path,label,type,def,ph)=>``; function setRefresh(){const x=document.getElementById('setx');if(x&&SETPAGES[ui.setCat]){const y=window.scrollY;x.innerHTML=setPageHTML(ui.setCat);window.scrollTo(0,y)}} function setPageHTML(cat){const g=SETMENU.find(gr=>gr[1].some(i=>i[0]===cat));const it=g&&g[1].find(i=>i[0]===cat);const crumb=cat==='wf_edit'?'Customer › Workflows › Edit':g?`${g[0]} › ${it[1]}`:'';return `
${esc(crumb)}
${SETPAGES[cat]()}`} /* ---------- Dealership › General ---------- */ const DAYS7=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; function nthDow(y,m,dow,n){if(n>0){const d=new Date(y,m,1);const off=(dow-d.getDay()+7)%7;return new Date(y,m,1+off+7*(n-1))}const d=new Date(y,m+1,0);const off=(d.getDay()-dow+7)%7;return new Date(y,m,d.getDate()-off)} function holidays(y){const D=(m,d)=>new Date(y,m,d);const tg=nthDow(y,10,4,4);return [['newyear','New Year’s Day',D(0,1)],['mlk','MLK Day',nthDow(y,0,1,3)],['pres','Presidents’ Day',nthDow(y,1,1,3)],['memorial','Memorial Day',nthDow(y,4,1,-1)],['june','Juneteenth',D(5,19)],['july4','Independence Day',D(6,4)],['labor','Labor Day',nthDow(y,8,1,1)],['columbus','Columbus Day',nthDow(y,9,1,2)],['veterans','Veterans Day',D(10,11)],['thanks','Thanksgiving',tg],['blackfri','Black Friday',new Date(y,10,tg.getDate()+1)],['xmaseve','Christmas Eve',D(11,24)],['xmas','Christmas Day',D(11,25)],['nye','New Year’s Eve',D(11,31)]].map(([k,n,d])=>({k,n,date:iso(d)}))} const HDEF={xmas:'Closed',thanks:'Closed',newyear:'Closed'}; function hoursFor(dateStr){const d=new Date(dateStr+'T12:00:00');const y=d.getFullYear();const hs=SG('hours',{});const sp=(SG('special',{})||{});const hol=holidays(y).find(h=>h.date===dateStr);const cus=(SG('customDays',[])||[]).find(x=>x.date===dateStr); const ov=cus||(hol?Object.assign({status:HDEF[hol.k]||'Open'},sp[hol.k]||{}):null);if(ov&&ov.status==='Closed')return null;if(ov&&ov.status==='Custom')return{open:ov.open||'09:00',close:ov.close||'17:00'}; const w=hs[d.getDay()]||{open:d.getDay()===0?'':'09:00',close:d.getDay()===0?'':'20:30',closed:d.getDay()===0};return w.closed||!w.open?null:{open:w.open,close:w.close}} function storeOpenNow(){const now=new Date();const h=hoursFor(iso(now));if(!h)return false;const t=pad(now.getHours())+':'+pad(now.getMinutes());return t>=h.open&&t{const r=new FileReader();r.onload=()=>{SSet('logo',r.result,1);toast('Logo saved. It now prints on your forms')};r.readAsDataURL(b)})} SETPAGES.dealer=()=>{const hs=SG('hours',{});const y=new Date().getFullYear();const sp=SG('special',{})||{};const cust_=SG('customDays',[])||[]; return scard('Dealer settings','Basic information like licenses, contact info and the dealership address. This prints on your forms and shows on your website.', `
${sgrid(sfld('dealer','Dealership name'),sfld('dealerAlias','Name used on forms (if different)'),sfld('dealerLicense','Dealer license #'),sfld('dealerNo','Dealer #'),sfld('companyId','Company ID'),sfld('salesTaxLicense','Sales tax license'),sfld('ein','EIN / tax ID'),sfld('websiteCode','Website dealer code'))}

Contact info

${sgrid(sfld('phone','Phone','tel'),sfld('fax','Fax','tel'),sfld('dealerEmail','Email','email'),sfld('user','Your name (for notes)'))}

Address

${sgrid(``,sfld('county','County'),``)} ${SG('sameMail',true)?'':sgrid(``)}

Default reminders

${ssel('remindAppt','Appointment reminder',[['0','None'],['15','15 minutes before'],['30','30 minutes before'],['60','1 hour before'],['1440','1 day before']],'15')}${ssel('remindTask','Task reminder',[['0','None'],['15','15 minutes before'],['30','30 minutes before'],['60','1 hour before']],'15')}

Forms

${sgrid(``)}`) +scard('Store hours','When the dealership is open. Used for lead assignment, text quiet hours and your website.',`
${DAYS7.map((d,i)=>{const w=hs[i]||{open:i===0?'':'09:00',close:i===0?'':'20:30',closed:i===0};return `
${w.closed?'Closed':`to`}
`}).join('')}
`) +scard('Special store hours','Holidays and special days override your regular hours.',`${holidays(y).filter(h=>h.date>=addDays(TODAY,-1)).concat(holidays(y+1).filter(h=>h.date{const o=Object.assign({status:HDEF[h.k]||'Open'},sp[h.k]||{});return ``}).join('')}
DateHolidayStatusHours
${fdate(h.date)}${esc(h.n)}${o.status==='Custom'?` – `:'—'}

Custom days

${cust_.map((c,i)=>``).join('')||''}
${fdate(c.date)}${esc(c.name)}${c.status==='Closed'?'Closed':esc(c.open+' – '+c.close)}
No custom days. Add closures or special hours for one-off days.
`) +scard('Consent','',stg('shareConsent','Consent for sharing and use of information','Lets DealerPen use your data to provide the service, as described in your agreement.',true))}; /* ---------- Dealership › Website ---------- */ SETPAGES.webset=()=>{const urls=SG('web.urls',[])||[];return scard('Website URL','Your website addresses, your credit application link and how vehicle pages are linked. Used in listing feeds, texts and emails.', sinp('web.primary','Primary dealer website','url','','','https://www.yourdealership.com')+`
Other website addressesDomains that also point to your site
${urls.length?`
    ${urls.map((u,i)=>`
  • ${esc(u)}
  • `).join('')}
`:''} ${sinp('web.creditUrl','Credit application URL','url','','Only if you use a website other than DealerPen’s','https://…/financing')}${sinp('web.vdpPattern','Vehicle page URL pattern','text','','Use {stock} or {vin}. Leave blank to use your DealerPen website','https://www.example.com/inventory/{stock}')} `)}; {const _vu=vUrl;vUrl=function(v){const p=SG('web.vdpPattern','');if(p)return p.replace('{stock}',encodeURIComponent(v.stock)).replace('{vin}',encodeURIComponent(v.vin||''));const pr=SG('web.primary','');if(pr&&!(S.site&&S.site.domain))return pr.replace(/\/$/,'')+'/#'+v.stock;return _vu(v)}} /* ---------- Inventory › General ---------- */ SETPAGES.inv_general=()=>scard('General','Defaults for vehicles you add, aging alerts and how stock numbers are made.', ssel('inv.defStatus','New vehicles start as',['In Recon','Available'],'In Recon')+stg('inv.toRecon','Send new vehicles to recon automatically','',true)+sinp('inv.prefix','Stock number prefix','text','S','Next number: '+(S.seq.stock+1))+ssel('inv.defLot','Default location',[...new Set(['Main Lot',...S.vehicles.map(v=>v.lot).filter(Boolean)])],'Main Lot')+ssel('inv.defSale','Default sale type',VSALE,'Retail')+ssel('inv.defCond','Default condition',VCOND,'Used')+sinp('inv.ageWarn','Aging warning after (days)','number',45)+sinp('inv.ageAlert','Aging alert after (days)','number',60)+stg('inv.autoPublish','Publish new vehicles online when they’re frontline ready','',true)) +scard('Build and book','Which value guides you use and how bookouts are kept fresh.',stg('inv.showMMR','Show Manheim MMR on vehicle pages','',true)+slink('Book value guides, lender book and refresh days',"setGo('bookout')")) +scard('Vehicle history','Default history report for vehicle pages and listings.',ssel('inv.history','Default report',['CARFAX','AutoCheck','NMVTIS'],'CARFAX')+stg('inv.histOnline','Show the history report link on your website','',true)) +scard('Cost','Costs that are added to every vehicle automatically.',sinp('inv.pack','Default pack per vehicle','number',0,'Added to cost for commission. Applies when a vehicle has no pack of its own')+stg('inv.flooring','Add floor plan interest to cost','Uses the rate below from the day the car is floored',false)+(SG('inv.flooring',false)?sinp('inv.floorRate','Floor plan rate (APR %)','number',8):'')+slink('Recon budget, target days and approvals',"setGo('recon')")) +scard('Vehicle description','A starting description for vehicles that don’t have one. Use {year} {make} {model} {trim} {miles} {color} {dealer} {phone}.',`
`); function invApplyDesc(){const t=SG('inv.descTpl','');const st=S.settings;let n=0;S.vehicles.filter(v=>!(v.notes||'').trim()&&v.status!=='Sold').forEach(v=>{v.notes=t.replace(/\{(\w+)\}/g,(m,k)=>({year:v.year,make:v.make,model:v.model,trim:v.trim||'',miles:(+v.miles).toLocaleString(),color:v.color||'',dealer:st.dealer,phone:st.phone})[k]??m).replace(/\s+/g,' ').trim();n++});save();setRefresh();toast(n+' description'+(n===1?'':'s')+' added')} /* ---------- Inventory › Pricing ---------- */ SETPAGES.inv_pricing=()=>{const fees=SG('vehFees',[{n:'Tag & title (est.)',a:0}]);const docFee=+S.settings.docFee||0;const tot=docFee+fees.reduce((a,f)=>a+(+f.a||0),0); return scard('Pricing configuration','Tell DealerPen whether your vehicle prices include dealer fees. This keeps your website and listing prices accurate and helps with FTC advertising rules.', schoice('pricing.mode',[['exclude','Prices do not include dealer fees','Fees are added on top of the price you enter'],['include','Prices include dealer fees','The price you enter already has the fees in it'],['none','No dealer fees','You don’t charge dealer fees']],'exclude')) +scard('Dealer fees','Fees added to every retail sale. They show as "dealer fees" on vehicle pages and deals.',`${fees.map((f,i)=>``).join('')}
FeeAmount
Doc fee
Total dealer fees${$$(tot)}
`) +scard('Disclaimer text','Shown under prices on your website and in listings.',``) +scard('Deposit settings','Defaults for customer deposits.',sinp('pricing.minDeposit','Minimum deposit','number',500)+sinp('pricing.depositDays','Deposit holds the vehicle for (days)','number',7)+stg('pricing.depositNonRefund','Deposits are non-refundable by default','Check your state’s rules before making deposits non-refundable',false)) +scard('Required down','The default down payment shown on vehicles that don’t have their own.',ssel('pricing.downMode','Required down is',[['pct','A percent of the selling price'],['amt','A dollar amount']],'pct')+sinp('pricing.downVal',SG('pricing.downMode','pct')==='pct'?'Percent of price':'Amount','number',10)+`
`)}; const reqDown=v=>{if(+v.minDown)return +v.minDown;const m=SG('pricing.downMode','pct'),x=+SG('pricing.downVal',10)||0;return m==='pct'?Math.round((+v.price||0)*x/100/50)*50:x}; function invApplyDown(){let n=0;S.vehicles.filter(v=>!+v.minDown&&v.status!=='Sold').forEach(v=>{v.minDown=reqDown(v);n++});save();toast(n+' vehicle'+(n===1?'':'s')+' updated')} /* ---------- Inventory › Media ---------- */ SETPAGES.inv_media=()=>scard('Photo overlay','Add your dealership name and phone across the bottom of vehicle photos in listing feeds and on your website. Your original photos are never changed.', schoice('media.overlay',[['none','None',''],['banner','Dealer banner','Name and phone on a strip'],['price','Price banner','Price, name and phone']],'none')+(SG('media.overlay','none')!=='none'?`
${carSVG('#7b8794')}
${esc(S.settings.dealer)}${SG('media.overlay')==='price'?' · $14,995':''} · ${esc(S.settings.phone)}
`:'')) +scard('Video settings','Turn vehicle photos into a short video for listings and social posts.',stg('media.autoVideo','Make a photo video automatically for each vehicle','Uses the vehicle’s photos in order',false)+`

Intro

${schoice('media.intro',[['none','None'],['logo','Logo and name'],['photo','First photo with title']],'none')}

Outro

${schoice('media.outro',[['none','None'],['cta','Call-to-action with phone']],'cta')}

Background music

${schoice('media.music',[['none','None'],['calm','Calm'],['upbeat','Upbeat']],'none')}

Videos are made on your DealerPen server. Walkaround videos you record are still sent from the customer page.

`) +scard('Coming soon','What shows when a vehicle has no photos yet.',schoice('media.comingSoon',[['none','Car drawing','A simple drawing in the vehicle’s color'],['template','Photos coming soon','A branded “photos coming soon” card']],'template')); /* ---------- Inventory › Import ---------- */ const IMPF=[['price','Price'],['miles','Mileage'],['notes','Description'],['photos','Pictures'],['cost','Cost'],['body','Body style'],['color','Exterior color'],['intColor','Interior color'],['mpgCity','MPG city'],['mpgHwy','MPG highway'],['acquired','Date in stock'],['lot','Location'],['saleType','Sale type'],['titleStatus','Title information']]; SETPAGES.inv_import=()=>scard('Inventory import','Where you manage inventory and how vehicles from another system update DealerPen.', schoice('imp.where',[['lotledger','DealerPen','You add and edit vehicles here'],['other','Another system','Vehicles come in from a file or feed']],'lotledger')+(SG('imp.where','lotledger')==='other'?ssel('imp.source','Inventory source',['Frazer','DealerCenter','vAuto','HomeNet','Dealer Specialties','CSV / Excel file'],'Frazer')+sinp('imp.email','Send inventory files to','email','','Your provider sends files here')+ssel('imp.freq','Import',['Every night','Every 4 hours','Manually'],'Every night')+`
Last imported${SG('imp.last')?ftime(SG('imp.last')):'Never'}
`:'') +`
`) +scard('Does this source send prices that include dealer fees?','',schoice('imp.feesIncluded',[['yes','Yes, prices include dealer fees'],['no','No, prices don’t include dealer fees']],'no')) +scard('Update settings','When a vehicle in the import matches one in DealerPen (by VIN), update these fields.',stg('imp.update','Update vehicles that already exist','',true)+`
${IMPF.map(([k,l])=>``).join('')}

Updating price and cost from an import overwrites changes made in DealerPen. Leave them off if you price cars here.

` +ssel('imp.removed','Vehicles missing from the import become',[['keep','Unchanged'],['Wholesale','Wholesale'],['Sold','Sold'],['unpublish','Hidden from the website']],'unpublish')+stg('imp.skipDeals','Don’t change vehicles that are on a deal','',true)+stg('imp.onlyUpdate','Only update. Don’t add new vehicles','',false)+stg('imp.replacePhotos','Replace photos with the imported ones','',false)); /* ---------- Inventory › Export ---------- */ const WHOLESALE=[['ove','OVE.com (Manheim)'],['acv','ACV Auctions'],['ally','Ally SmartAuction']]; SETPAGES.inv_export=()=>{const F_=feedCfg();const mode=SG('pricing.mode','exclude'); return scard('Export settings','Choose which sites get your inventory, what price they get and when cars come off.',`
Retail sites${stg('export.noDeposit','Don’t post vehicles with an active deposit','',true)+stg('export.retailOnly','Only send vehicles with sale type Retail','',true)}
Pricing: ${mode==='include'?'Prices include dealer fees':mode==='none'?'No dealer fees':'Prices do not include dealer fees'} · Edit pricing
${CHANNELS.map(c=>{const f=F_[c[0]];return ``}).join('')}
SiteSendVehiclesPrice sentCall for priceLast sent
${esc(c[1])}${f.last?ftime(f.last):'—'}
Wholesale sites${stg('export.wholesaleOnly','Only send vehicles with sale type Wholesale','',true)}${WHOLESALE.map(([k,n])=>``).join('')}
SiteSendLast sent
${n}—

Wholesale sites need your account with each auction. Your DealerPen server sends the feed nightly.

`)}; {const _fv=feedVeh;feedVeh=function(k){const f=(S.feeds||{})[k]||{};return _fv(k).filter(v=>(!SG('export.retailOnly',true)||!v.saleType||v.saleType==='Retail'||v.saleType==='BHPH')&&(!SG('export.noDeposit',true)||!S.customers.some(c=>(c.deposits||[]).some(d=>!d.refunded&&d.vehicleId===v.id)))&&(f.scope!=='With photos only'||(v.photos||[]).length)&&(f.scope!=='Over 0 miles only'||+v.miles>0))}} /* ---------- Inventory › Print ---------- */ const BG_TPL=[['asis','As is – no dealer warranty'],['implied','Implied warranties only'],['limited30','30-day limited warranty'],['limited','Limited warranty'],['full','Full warranty']]; SETPAGES.inv_print=()=>scard('Window sticker and hang tag','What prints on window stickers and hang tags.',stg('print.bookValue','Show retail book value','',true)+stg('print.price','Show price','',true)+stg('print.bookIfNoPrice','Use retail book value when there’s no selling price','',true)+stg('print.labelNoPrice','Show “Call for price” when there’s no price or book value','',true)+`

Window sticker

${schoice('print.sticker',[['none','None'],['standard','Standard','Price, equipment, MPG'],['compact','Compact','Price and key specs']],'standard')}

Hang tag

${schoice('print.hang',[['none','None'],['standard','Standard','Big price, miles, stock #']],'standard')}`) +scard('Buyers Guide','The default warranty choice when you print a Buyers Guide.',`${BG_TPL.map(([k,l])=>``).join('')}
DefaultTemplate
${l}

Drop-down lists

${['bgSystems:Systems covered:Engine, Transmission, Drive axle, Brakes, Steering','bgDurations:Durations:30 days or 1,000 miles, 60 days or 3,000 miles, 90 days or 4,000 miles'].map(x=>{const [k,l,d]=x.split(':');return ``}).join('')}`) +scard('Print packs','Groups of forms you print together.',slink('Manage print packs',"setGo('go:forms:packs')",`${(S.packs||[]).length} pack${(S.packs||[]).length===1?'':'s'}`)); /* ---------- Customer › Lead management ---------- */ SETPAGES.lead_mgmt=()=>{const fwd=SG('leads.forward',[])||[];const srcs=[...new Set(S.customers.map(c=>c.source).filter(Boolean))].sort();const costs=SG('leads.costs',{})||{};const f=SRV&&SRV.ok?SRV:null; return scard('Lead generation','How new leads come in, duplicate checking and what each lead source costs.',stg('leads.advDup','Advanced duplicate detection','Matches by phone, email and name to stop duplicate customers',true)+(SG('leads.advDup',true)?stg('leads.dupIgnoreName','Ignore first and last name when matching','Match on phone and email only',false):'')+stg('leads.adfSuffix','Add the lead provider’s name to the lead source','e.g. “CarGurus – Chat”',false) +`
Forward new leads toEach new lead is also emailed to these addresses
${fwd.length?`
    ${fwd.map((e,i)=>`
  • ${esc(e)}
  • `).join('')}
`:''}
Lead provider inboxGive this address or link to your lead providers${f&&f.leads&&f.leads.inboundUrl?esc(f.leads.inboundUrl):'Available when DealerPen runs on your server'}
Lead sources and costs${srcs.map(s=>{const L=S.customers.filter(c=>c.source===s&&(c.created||'')>=addDays(TODAY,-30));const sold=L.filter(c=>c.stage==='Sold').length;const cost=+costs[s]||0;return ``}).join('')}
SourceMonthly costLeads (30d)Sold (30d)Cost per sale
${esc(s)}${L.length}${sold}${cost&&sold?$0(cost/sold):'—'}
Credit application link generator

Make a link that tags every application with the source it came from.

`) +scard('CRM integrations','Bring leads straight in from your ad accounts.',`
Facebook & Instagram Lead Ads${f&&f.meta&&f.meta.ready?(f.meta.test?'Connected in test mode':'Connected'):'Not connected. Add your Meta app details on your DealerPen server (README, section 12)'}${f&&f.meta&&f.meta.ready?'On':'Off'}
`) +scard('Lead statuses','How leads move between statuses when they go quiet or come back.',stg('leads.reactivate','Reopen lost customers when they contact you','',true)+ssel('leads.reactivateTo','Reopened customers start at',['New','Contacted'],'New')+sinp('leads.lostAfter','Mark a lead lost after this many days with no activity','number','','Leave blank to never do this automatically') +`
Check-in actions${stg('leads.ciWorking','Set status to Working deal on check-in','',true)}${stg('leads.ciNotify','Notify the assigned rep','',true)}${stg('leads.ciDesk','Open a desking worksheet','',false)}
Lost reasons
    ${LOST_REASONS.map((r,i)=>`
  • ${esc(r)}
  • `).join('')}
`)}; /* ---------- Customer › Lead assignment ---------- */ const ASSIGN_SEC=[['sales','Sales reps','ownerId',['Salesperson','Sales Manager','Desking Manager']],['bdc','BDC reps','bdcId',['Salesperson','Customer Service','Sales Manager']]]; SETPAGES.lead_assign=()=>scard('Lead assignment','Hand new internet leads to reps in turn, and pass them on if nobody works them in time. Reps only get leads while they’re marked ready.',stg('assign.bdcOn','Use BDC reps too','',false)) +ASSIGN_SEC.filter(s=>s[0]==='sales'||SG('assign.bdcOn',false)).map(([k,title,fld,roles])=>{const P='assign.'+k;const users=SG(P+'.users',[])||[];const pool=S.users.filter(u=>u.active&&!users.some(x=>x.id===u.id)); return scard(title,'',stg(P+'.auto','Assign leads automatically to ready reps','',k==='sales')+stg(P+'.reassign','Pass leads on if they’re not worked','',true)+ssel(P+'.mins','Pass on after',[['10','10 minutes'],['15','15 minutes'],['30','30 minutes'],['60','1 hour'],['240','4 hours']],k==='sales'?'10':'30')+stg(P+'.daily','Reps must mark themselves ready each day','',false)+ssel(P+'.during','Assign leads',[['hours','During store hours'],['always','Any time']],'hours')+stg(P+'.onlyNew','Only leads with status New','',k!=='sales')+sinp(P+'.maxDays','Don’t assign leads older than (days)','number',k==='sales'?60:0) +`${users.map((x,i)=>{const u=S.users.find(y=>y.id===x.id);if(!u)return '';return ``}).join('')||''}
RepReady for leadsLeads per turnPass on after
${esc(u.name)}
${esc(u.role)}
No reps in the rotation yet
${pool.length?`
`:''}

Reps get leads only while “Ready for leads” is on. They can turn it on from their account menu.

`)}).join(''); const repReady=(u,k)=>{const r=(u.ready||{})[k||'sales'];if(!r)return false;return !SG('assign.'+(k||'sales')+'.daily',false)||String(r).slice(0,10)===TODAY}; function setReady(uid_,on,k){const u=S.users.find(x=>x.id===uid_);if(!u)return;u.ready=u.ready||{};u.ready[k||'sales']=on?nowAt():'';save();if(route==='settings')setRefresh();else render();if(uid_===me()?.id)toast(on?'You’re ready for leads':'You won’t get new leads')} function nextRep(k,exclude){const P='assign.'+k;const list=(SG(P+'.users',[])||[]).filter(x=>{const u=S.users.find(y=>y.id===x.id);return u&&u.active&&repReady(u,k)&&x.id!==exclude});if(!list.length)return ''; const st=SG(P+'.rr',{i:0,c:0});let i=st.i%list.length;if(st.c>=(list[i].n||1)){i=(i+1)%list.length;st.c=0}st.i=i;st.c=(st.c||0)+1;SSet(P+'.rr',st);return list[i].id} {const _ro=routeOwner;routeOwner=function(src){if(!SG('assign.sales.auto',true)||!(SG('assign.sales.users',[])||[]).length)return _ro(src);if(SG('assign.sales.during','hours')==='hours'&&!storeOpenNow())return _ro(src);return nextRep('sales')||_ro(src)}} {const _il2=intakeLead;intakeLead=function(L,via){const c=_il2.apply(this,arguments);try{if(c&&c.ownerId&&!c.assignedAt)c.assignedAt=nowAt();if(c&&SG('assign.bdcOn',false)&&SG('assign.bdc.auto',false)&&!c.bdcId){c.bdcId=nextRep('bdc');if(c.bdcId)c.bdcAt=nowAt()}if(c&&!c.leadType)c.leadType=leadTypeOf(L.source,L.type)}catch(e){}return c}} const leadTypeOf=(src,t)=>/text|sms/i.test(src||'')?'SMS':/phone|call/i.test(src||'')?'Phone':/walk/i.test(src||'')?'Walk-in':/facebook|instagram|messenger/i.test(src||'')&&!/lead ad/i.test(t||'')?'Chat':/chat/i.test(t||'')?'Chat':/referral/i.test(src||'')?'Referral':'Internet'; function reassignTick(){let ch=false;ASSIGN_SEC.forEach(([k,title,fld])=>{const P='assign.'+k;if(!SG(P+'.reassign',true)||!(SG(P+'.users',[])||[]).length)return;if(k==='bdc'&&!SG('assign.bdcOn',false))return;if(SG(P+'.during','hours')==='hours'&&!storeOpenNow())return; const maxD=+SG(P+'.maxDays',k==='sales'?60:0)||0;S.customers.forEach(c=>{if(!c[fld]||c.stage!=='New'||(c.sub&&c.sub!=='New'))return;const at=c[k==='sales'?'assignedAt':'bdcAt'];if(!at)return;if(maxD&&diff((c.created||TODAY),TODAY)>maxD)return; const row=(SG(P+'.users',[])||[]).find(x=>x.id===c[fld]);const mins=+(row&&row.mins)||+SG(P+'.mins',k==='sales'?10:30);if(hoursAgo(at)*60x.customerId===c.id&&x.dir==='out'&&x.at>=at)||(c.notes||[]).some(n=>n.date===TODAY&&/Disposition|Stage changed/.test(n.text)))return; const nx=nextRep(k,c[fld]);if(!nx)return;const old=c[fld];c[fld]=nx;c[k==='sales'?'assignedAt':'bdcAt']=nowAt();c.notes.push({date:TODAY,by:'Lead assignment',text:`Not worked in ${mins} minutes. ${k==='sales'?'Sales':'BDC'} rep changed from ${uname(old)} to ${uname(nx)}`});ch=true})});if(ch){save();if(['crm','cust','desk'].includes(route))render()}} setInterval(()=>{try{reassignTick()}catch(e){}},60000); /* ---------- Customer › Workflows ---------- */ const WF_STAT=['New','Contact attempt','Contacted','Appt. scheduled','Working deal','Missed appt.','Visit follow-up']; const WF_TYPES=['Internet','Chat','Phone','Walk-in','SMS','Referral'];const WF_INQ=['Specific vehicle','Shopping','Financing','Trade-in','Pricing']; const WF_ACT=[['Call','Phone call'],['Text','Text message'],['Email','Email'],['Task','Task'],['Appointment','Appointment reminder'],['Video','Video']]; const WFICO={Call:'',Text:'',Email:'',Task:'',Appointment:'',Video:''}; const wfIco=t=>``; const wfWho=s=>!s.assign?'Unassigned':s.assign==='sales'?'Assigned sales rep':s.assign==='bdc'?'Assigned BDC rep':uname(s.assign); const wfDue=s=>{const d=s.due||{mode:s.day||s.min?'days':'now',n:s.day||0,time:''};return d.mode==='now'?'Immediately':d.mode==='hours'?`${d.n} hour${+d.n===1?'':'s'}`:d.mode==='mins'?`${d.n} minutes`:d.mode==='before'?`${d.n} day${+d.n===1?'':'s'} before appointment${d.time?' @ '+nxTime(d.time):''}`:`${d.n} day${+d.n===1?'':'s'}${d.time?' @ '+nxTime(d.time):''}`}; function wfNorm(p){p.crit=p.crit||{types:['Internet','Chat','Phone','Walk-in'],sources:[],inq:[]};if(p.active===undefined)p.active=true;p.steps.forEach(s=>{if(!s.when)s.when='New';if(!s.due)s.due=(s.day||s.min)?(s.day?{mode:'days',n:s.day,time:''}:{mode:'mins',n:s.min}):{mode:'now'}});p.byStatus=true;return p} SETPAGES.workflows=()=>{S.plans=S.plans&&S.plans.length?S.plans:[JSON.parse(JSON.stringify(DEFAULT_PLAN))];const only=ui.wfActive;const list=S.plans.filter(p=>!only||p.active!==false); return scard('Workflows','Automate follow-up for each kind of lead. Each workflow has steps for every customer status: calls, texts, emails and tasks, assigned to the right person at the right time.',`
${list.map(p=>{const c_=p.crit||{};return ``}).join('')}
ActiveWorkflowApplies toStepsOn it now
${esc(p.name)}${p.desc?`
${esc(p.desc)}
`:''}
Type: ${esc((c_.types||[]).join(', ')||'All')}
Source: ${esc((c_.sources||[]).join(', ')||'All')}
Inquiry: ${esc((c_.inq||[]).join(', ')||'All')}
${p.steps.length}${S.customers.filter(c=>c.plan&&c.plan.id===p.id&&c.plan.status==='Active').length}${S.plans.length>1?` `:''}
`)}; function wfEdit(id){const p=id?planOf(id):{id:'plan_'+uid(),name:'',desc:'',active:true,steps:[]};ui.wfDraft=wfNorm(JSON.parse(JSON.stringify(p)));ui.wfIsNew=!id;ui.wfStat='New';ui.wfOpen={New:true};ui.setCat='wf_edit';setApply()} SETPAGES.wf_edit=()=>{const p=ui.wfDraft;if(!p)return '
Nothing to edit
';const c_=p.crit;const srcs=[...new Set(['Website','Walk-in','Phone','Text','Facebook','Instagram','Cars.com','CarGurus','Autotrader','Referral',...S.customers.map(c=>c.source).filter(Boolean)])]; const crit=(k,label,opts)=>`
${label}
    ${(c_[k]||[]).map((o,i)=>`
  • ${esc(o)}
  • `).join('')||'
  • All
  • '}
`; return `
${ui.wfIsNew?'':``}
` +scard(ui.wfIsNew?'New workflow':'Edit workflow','',`

Texts are only sent to customers who agreed to receive them.

`) +scard('Applies to','A new lead gets the first active workflow that matches all three. Leave a list empty to match everything.',`
${crit('types','Lead type',WF_TYPES)}${crit('sources','Lead source',srcs)}${crit('inq','Inquiry type',WF_INQ)}
`) +scard('Steps by status','Steps run while the customer is in that status. Timing starts when they enter the status.',`
${WF_STAT.map(st=>{const steps=p.steps.map((s,i)=>[s,i]).filter(([s])=>s.when===st);const open=!!ui.wfOpen[st];return `
${open?`
${steps.map(([s,i])=>`
`).join('')||'
No steps for this status
'}
`:''}
`}).join('')}`)}; function wfStepModal(i,type){const p=ui.wfDraft;const s=i>=0?p.steps[i]:{type,when:ui.wfStat||'New',label:'',assign:'sales',due:{mode:'now',n:1,time:''},auto:false,body:''};const users=S.users.filter(u=>u.active); openModal(mh(i>=0?'Edit step':'Add step')+`
${['Text','Email'].includes(s.type)?``:''} ${s.type==='Text'?``:''}

Merge fields: {first} {interest} {dealer} {user} {phone}

`); const f=$('#wsf');f.type.onchange=()=>{s.type=f.type.value;Object.assign(s,{label:f.label.value});wfStepModal(i,s.type)}; f.onsubmit=e=>{e.preventDefault();const x=fd(f);const n={type:x.type,when:x.when,label:x.label,assign:x.assign,due:{mode:x.mode,n:+x.n||0,time:x.time},body:x.body||'',auto:!!x.auto};if(i>=0)p.steps[i]=n;else p.steps.push(n);ui.wfOpen[n.when]=true;closeModal();setRefresh()}} function wfSave(){const p=ui.wfDraft;if(!p.name.trim())return toast('Give the workflow a name');S.plans=S.plans||[];const i=S.plans.findIndex(x=>x.id===p.id);if(i>=0)S.plans[i]=p;else S.plans.push(p);save();ui.setCat='workflows';setApply();toast('Workflow saved')} function pickPlan(c,L){const t=c.leadType||leadTypeOf(c.source,L&&L.type);return (S.plans||[]).find(p=>{if(p.active===false)return false;const k=p.crit||{};return (!(k.types||[]).length||k.types.includes(t))&&(!(k.sources||[]).length||k.sources.includes(c.source))&&(!(k.inq||[]).length||k.inq.includes(c.inquiry||''))})} /* status-based workflow runner (old-style plans keep running as before) */ function wfBase(c,st){return c.sub===st&&c.subAt?c.subAt:c.plan.start} function wfDueAt(c,s,base){const d=s.due||{mode:'now'};const b=new Date(base);if(d.mode==='now')return b;if(d.mode==='mins')return new Date(b.getTime()+(+d.n||0)*6e4);if(d.mode==='hours')return new Date(b.getTime()+(+d.n||0)*36e5); if(d.mode==='before'){if(!(c.next&&/Appointment|Test drive|Visit/.test(c.next.type)))return null;const a=new Date(c.next.date+'T'+(d.time||'09:00'));a.setDate(a.getDate()-(+d.n||0));return a} const x=new Date(b);x.setDate(x.getDate()+(+d.n||0));if(d.time){const [h,m]=d.time.split(':');x.setHours(+h,+m,0,0)}return x} async function wfTick(){const f=SRV&&SRV.ok&&SRV.phone?.ready;const now=new Date();let ch=false; for(const c of S.customers){const pl=c.plan;if(!pl||pl.status!=='Active')continue;const p=planOf(pl.id);if(!p||!p.byStatus)continue; if(['Sold','Lost'].includes(c.stage)||c.optOut){pl.status='Stopped';pl.stopReason=c.optOut?'Opted out':c.stage;ch=true;continue} const st=subOf(c),base=wfBase(c,st);for(let i=0;inow)continue; if(s.type==='Text'&&s.auto&&f&&!canText(c)&&!quietHours()){const ok=await serverText(c.id,null,merge(s.body||'',c));if(ok){pl.done.push(key);c.notes.push({date:TODAY,by:'Workflow',text:`Sent: ${s.label}`});ch=true;continue}} const who=s.assign==='sales'?c.ownerId:s.assign==='bdc'?(c.bdcId||c.ownerId):s.assign||'';c.tasks=c.tasks||[];c.tasks.push({id:uid(),text:`${s.type}: ${s.label}${s.body?' – '+merge(s.body,c):''}`,due:iso(due),assignee:who,at:nowAt(),by:'Workflow',done:false,wf:key});pl.done.push(key);ch=true}} if(ch){save();if(['desk','crm','cust'].includes(route))render()}} setInterval(()=>{wfTick().catch(()=>{})},60000);setTimeout(()=>{wfTick().catch(()=>{})},5000); /* remember when the status changed, so status steps time correctly */ {const _scs=setCustSub;setCustSub=function(id,s,note){const c=cust(id);const was=c&&subOf(c);const r=_scs.apply(this,arguments);if(c&&subOf(c)!==was)c.subAt=nowAt();save();return r}} {const _ci=checkIn;checkIn=function(id){const c=cust(id);const was=c&&subOf(c);_ci.apply(this,arguments);if(c){if(subOf(c)!==was)c.subAt=nowAt();if(SG('leads.ciDesk',false))openSheet({customerId:c.id,vehicleId:interestVeh(c)?.id||''})}}} /* lost-after-N-days and lost reasons */ try{const lr=SG('leads.lostReasons',null);if(Array.isArray(lr)&&lr.length){LOST_REASONS.length=0;lr.forEach(x=>LOST_REASONS.push(x))}}catch(e){} function lostTick(){const n=+SG('leads.lostAfter',0);if(!n)return;let ch=false;S.customers.filter(isLead).forEach(c=>{const last=[c.created,...(c.notes||[]).map(x=>x.date),...S.comms.filter(x=>x.customerId===c.id).map(x=>x.at.slice(0,10))].filter(Boolean).sort().pop();if(last&&diff(last,TODAY)>=n){c.stage='Lost';c.sub='Lost';c.next=null;c.notes.push({date:TODAY,by:'Lead statuses',text:`Lead closed – No activity for ${n} days`});ch=true}});if(ch)save()} setTimeout(lostTick,8000); /* ready-for-leads switch in the account menu */ {const _mac=myAccountCard;myAccountCard=function(){const h=_mac();const u=me();if(!u||!h)return h;const inRot=k=>(SG('assign.'+k+'.users',[])||[]).some(x=>x.id===u.id);if(!inRot('sales')&&!inRot('bdc'))return h; return h.replace(/<\/div>$/,`
`)}} /* dealer logo on printed forms */ {const _h=F.hdr;F.hdr=function(title,ctx,sub){const h=_h.apply(this,arguments);const lg=S.settings.logo;return lg?h.replace(/