Field service • Offline-ready

ServicePro

Customer records, appliance information, service orders, estimates, forms, and scheduling in one field-friendly workspace.

Case setup1 of 5
Draft stays on this device when local storage is available.

Select a dashboard area to view or make changes. After saving, you will return to the dashboard automatically.

SB

Manufacturer Service Bulletin Lookup

Search for service bulletins and technical notices using the appliance identity on the active service order.

Verify before relying on a bulletin.

Search results are external references, not confirmed matches. ServicePro prioritizes a known manufacturer domain when available, but does not yet connect to a live bulletin database. Open the source document and verify exact model/serial coverage, revision, and date before using its instructions.

Both searches use the entered model and serial together. The manufacturer search prioritizes an official brand domain when recognized; the broader search can find independent technical references too. Serial ranges and date codes must still be checked in the original bulletin.

Save a bulletin reference to this service order

No search started.
$

Repair estimate

Create a customer-facing estimate tied to this service order. Track customer approval and payments without creating a separate invoice.

Estimate is attached to the active service order. Start a service order to begin.

Enter each part, labor task, fee, or other charge as a separate line. Quantities and unit prices calculate automatically.

Subtotal

$0.00

Tax

$0.00

Discount

−$0.00

Estimated total

$0.00

Requested return visit (dispatcher confirmation required)

A requested time is not a confirmed appointment. Only the owner or dispatcher can publish the schedule.

Capture a fresh signature for this estimate approval. This does not replace the separate service authorization form.

Drafts and saved estimates are stored locally on this device and linked to the service-order number.

Approval protection: once a customer-approved estimate is saved, that version cannot be edited. Use “Create new revision” for any change so the signed scope and price remain intact.

$

Estimates & Payments

Select a saved, customer-approved estimate and track payments received against its approved total.

Payment tracking is linked to a saved, customer-approved estimate. The approved estimate remains the customer-facing document; its saved amounts are preserved even if you create a later revision. Current payment mode: record payments already received. Sensitive payment credentials are never requested or stored. This build does not yet process card payments or move money through a payment gateway.
No estimate selected. Select a saved, approved estimate to track payments.
↻

Parts & return-visit scheduling

When a repair needs an ordered part, record the order and book a return appointment linked to the original service order.

A return appointment is tracked separately from the original visit. Scheduling it does not create a completed service-history entry; the technician records the return work as its own visit when the customer is serviced.
Return visits are stored locally and included in full backups.
★

Customer & service history

Quickly find a customer, update their contact details, or review previous visits on this device.

Customer contact details Editable
Customer profiles and visit history are stored only in this browser. Export backups regularly.
Customer directory Open to view / edit
Service history Read-only records

Saved visits cannot be edited or deleted here. Open a visit to read or print it, or export a backup.

Local-only storage. Cloud sync is not configured. Export backups regularly.

A full backup includes customer profiles, appliance records, read-only service history, editable parts records, and service-order forms with photos and signatures. Restore merges records without replacing existing saved records.

✍

Forms & photo documentation

Every service order gets its own waiver, work authorization, signature, and visit photos.

Forms are attached to the active service order. Create a service order to generate an order number.
Damage waiver & customer acknowledgement New signature each visit

This acknowledgement documents existing conditions and service-related risks. It does not waive the technician’s or company’s responsibility for negligence or improper work.

Pre-existing damage photos Attached to this damage form

Use Take photo on your phone to photograph each existing scratch, dent, crack, stain, or surrounding-area concern. These images are saved specifically as pre-existing damage evidence for this service order and included with the form printout and backup.

Before-service photos Timestamped

Photograph appliance condition, surrounding area, model/serial label, and any pre-existing damage before moving or servicing. Photos are compressed before saving. For reliability, add no more than 8 photos per category and keep each service order’s compressed photos under 3 MB; export backups regularly.

After-service photos Timestamped

Document completed work, replaced parts, final condition, and any remaining concerns. Photos are compressed before saving. For reliability, add no more than 8 photos per category and keep each service order’s compressed photos under 3 MB; export backups regularly.

Customer approval & work authorization Required per visit

Customer may sign with a finger or stylus. Signature is saved with the service-order number, signer name, and timestamp on this device.

Email delivery is not connected in this prototype. A PDF can be printed/saved and emailed manually; automatic delivery requires a configured secure email service.

Saved documents for this service order

No forms saved for this service order yet.

01

Service order details

Enter only what you know. Unknown details are okay.

Entering a serial number loads prior visits for this exact appliance, regardless of customer name.

Prototype scope

This is a local, rules-based demo. Customer profiles, appliance serial-linked visit history, individual service orders, estimates, and estimate approvals are separate linked records. It does not connect to an AI service, manufacturer database, user account, or cloud storage. Your entries stay in this browser if local draft saving is available. Export a JSON copy to keep a case record.

');w.document.close()} $('estimateProceedPayment').addEventListener('click',()=>{const rec=readStore(ESTIMATE_KEY).find(x=>x.id===editingEstimateId&&x.jobNumber===val('jobNumber')&&x.approved===true);if(!rec){alert('Save a customer-approved estimate before proceeding to payment.');return}refreshInvoiceOptions();$('invoiceEstimateSelect').value=rec.id;createInvoice();openWorkspace('invoiceHub');}); $('createInvoiceBtn').addEventListener('click',createInvoice);$('recordPaymentBtn').addEventListener('click',recordInvoicePayment);$('printInvoiceBtn').addEventListener('click',invoicePrint);$('jobNumber').addEventListener('change',()=>{activeInvoiceId=null;refreshInvoiceOptions();renderInvoice(null)});refreshInvoiceOptions(); $('savedEstimateList').addEventListener('click',e=>{const b=e.target.closest('[data-load-estimate]');if(!b)return;const rec=readStore(ESTIMATE_KEY).find(x=>x.id===b.dataset.loadEstimate);if(rec)loadEstimateRecord(rec)});$('newEstimateRevision').addEventListener('click',createEstimateRevision);$('addEstimateLine').addEventListener('click',()=>addEstimateLine());$('estimateLines').addEventListener('input',e=>{const card=e.target.closest('[data-est-line]'),field=e.target.dataset.estField;if(!card||!field)return;const line=estimateLines.find(x=>x.id===card.dataset.estLine);if(!line)return;line[field]=field==='quantity'||field==='unitPrice'?Math.max(0,Number(e.target.value)||0):e.target.value;calcEstimate()});$('estimateLines').addEventListener('change',e=>{const card=e.target.closest('[data-est-line]'),field=e.target.dataset.estField;if(!card||!field)return;const line=estimateLines.find(x=>x.id===card.dataset.estLine);if(line){line[field]=field==='quantity'||field==='unitPrice'?Math.max(0,Number(e.target.value)||0):e.target.value;renderEstimateLines()}});$('estimateLines').addEventListener('click',e=>{const b=e.target.closest('[data-remove-est-line]');if(b){estimateLines=estimateLines.filter(x=>x.id!==b.dataset.removeEstLine);renderEstimateLines()}});['estimateTaxRate','estimateDiscount'].forEach(id=>$(id).addEventListener('input',calcEstimate));$('importEstimateParts').addEventListener('click',importRecordedParts);$('saveEstimate').addEventListener('click',saveEstimate);$('printEstimate').addEventListener('click',printEstimate);$('emailEstimate').addEventListener('click',emailEstimateCopy);estimateSig.addEventListener('pointerdown',e=>{estimateSignatureDrawing=true;estimateSig.setPointerCapture(e.pointerId);const r=estimateSig.getBoundingClientRect();estimateCtx.beginPath();estimateCtx.moveTo(e.clientX-r.left,e.clientY-r.top);estimateSignatureDirty=true});estimateSig.addEventListener('pointermove',e=>{if(!estimateSignatureDrawing)return;const r=estimateSig.getBoundingClientRect();estimateCtx.lineTo(e.clientX-r.left,e.clientY-r.top);estimateCtx.stroke()});['pointerup','pointercancel','lostpointercapture'].forEach(n=>estimateSig.addEventListener(n,()=>estimateSignatureDrawing=false));$('clearEstimateSignature').addEventListener('click',()=>{estimateCtx.clearRect(0,0,estimateSig.width,estimateSig.height);estimateSignatureDirty=false;loadedEstimateSignature=null;loadedEstimateApprovedAt=null});$('jobNumber').addEventListener('change',loadEstimateForOrder);setTimeout(()=>{resizeEstimateSignature();loadEstimateForOrder()},0);window.addEventListener('resize',resizeEstimateSignature); function renderPartsRecords(){const host=$('partsRecordList');if(!host)return;const order=val('jobNumber');const records=readPartsForOrder(order);const locked=partsOrderIsReadOnly(order);$('addPartRecordBtn').disabled=!order||locked;$('partsRecordStatus').textContent=!order?'Start a service order before adding parts.':locked?'This visit is saved to read-only history; its parts records are locked.':'Parts entries are editable until the visit is saved to read-only history.';if(!records.length){host.innerHTML='

No structured parts recorded for this service order yet.

';return}host.innerHTML=records.map(p=>'
').join('')} function addPartRecord(){const order=ensureServiceOrder();if(partsOrderIsReadOnly(order))return;const list=readStore(PARTS_KEY);list.unshift({id:'part_'+Date.now()+'_'+Math.random().toString(36).slice(2,7),jobNumber:order,partNumber:'',description:'',quantity:1,status:'recommended',notes:'',createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(writeStore(PARTS_KEY,list)){renderPartsRecords();$('partsRecordList').querySelector('.part-record input')?.focus()}} function validPartQuantity(raw){const s=String(raw??'').trim();if(!/^[1-9]\d*$/.test(s))return null;const n=Number(s);return Number.isSafeInteger(n)?n:null} function updatePartRecord(id,field,value){const order=val('jobNumber');if(partsOrderIsReadOnly(order))return;const list=readStore(PARTS_KEY),p=list.find(x=>x.id===id&&x.jobNumber===order);if(!p||!['partNumber','description','quantity','status','notes'].includes(field))return;if(field==='quantity'){const quantity=validPartQuantity(value);if(quantity===null){$('partsRecordStatus').textContent='Invalid part quantity. Enter a positive whole number; the saved quantity was not changed.';return}p.quantity=quantity}else if(field==='status'){if(!['recommended','installed','returned'].includes(value)){$('partsRecordStatus').textContent='Invalid part status; the saved status was not changed.';return}p.status=value}else p[field]=String(value||'');p.updatedAt=new Date().toISOString();if(!writeStore(PARTS_KEY,list))return;$('partsRecordStatus').textContent='Parts record updated locally for '+order+'.';} function deletePartRecord(id){const order=val('jobNumber');if(partsOrderIsReadOnly(order))return;const list=readStore(PARTS_KEY).filter(x=>!(x.id===id&&x.jobNumber===order));if(writeStore(PARTS_KEY,list)){renderPartsRecords();$('partsRecordStatus').textContent='Part record removed from this service order.'}} function clearCustomerForm(){activeCustomerId=null;['profileName','profilePhone','profileEmail','profileAddress','profileNotes'].forEach(id=>$(id).value='');$('saveCustomerBtn').textContent='Save customer';$('customerStatus').textContent='Enter details and save a new customer profile.'} function loadCustomer(id){const c=readStore(CUSTOMER_KEY).find(x=>x.id===id);if(!c)return;activeCustomerId=c.id;$('profileName').value=c.name||'';$('profilePhone').value=c.phone||'';$('profileEmail').value=c.email||'';$('profileAddress').value=c.address||'';$('profileNotes').value=c.notes||'';$('customer').value=c.name||'';$('customerStatus').textContent='Loaded customer profile. Edit any field and press Update customer.';$('saveCustomerBtn').textContent='Update customer';saveDraft();renderHub()} function saveCustomer(){const name=val('profileName');if(!name){$('profileName').focus();$('customerStatus').textContent='Enter a customer or site name first.';return}const list=readStore(CUSTOMER_KEY),now=new Date().toISOString();let c=activeCustomerId?list.find(x=>x.id===activeCustomerId):null;if(!c){c={id:'cust_'+Date.now()+'_'+Math.random().toString(36).slice(2,7),createdAt:now};list.unshift(c)}Object.assign(c,{name,phone:val('profilePhone'),email:val('profileEmail'),address:val('profileAddress'),notes:val('profileNotes'),updatedAt:now});if(!writeStore(CUSTOMER_KEY,list))return;activeCustomerId=c.id;$('customer').value=name;$('saveCustomerBtn').textContent='Update customer';$('customerStatus').textContent='Customer profile saved on this device.';saveDraft();renderHub();closeWorkspace()} function saveVisit(){const complaint=val('complaint');if(!complaint){$('complaint').focus();$('customerStatus').textContent='Add the customer complaint before saving this visit.';return}const requestedJob=val('jobNumber');const existingHistory=readStore(HISTORY_KEY);if(requestedJob&&existingHistory.some(h=>String(h.jobNumber||h.caseData?.jobNumber||'')===requestedJob)){$('customerStatus').textContent='This service order has already been saved. Past visits are read-only; start a new case for another visit instead of saving a duplicate.';return}const currentJob=ensureServiceOrder();const list=readStore(HISTORY_KEY);if(list.some(h=>String(h.jobNumber||h.caseData?.jobNumber||'')===currentJob)){$('customerStatus').textContent='This service order has already been saved. Past visits are read-only; start a new case for another visit instead of saving a duplicate.';return}const authorization=readStore(FORMS_KEY).find(x=>x.jobNumber===currentJob);if(!authorization?.signedAt){$('customerStatus').textContent='Visit not finalized. Complete and save a new customer authorization for service order '+currentJob+' in the Forms section before saving this visit.';const formsBubble=document.querySelector('.dash-bubble[data-jump="formsHub"]');if(formsBubble)formsBubble.click();return}const d=collect(true);const returnRows=readStore(RETURN_KEY);const linkedReturn=returnRows.find(r=>r.returnOrderNumber===currentJob&&r.status!=='completed'&&r.status!=='cancelled');if(linkedReturn){d.followUpOfOrder=linkedReturn.originalOrderNumber;d.returnVisitId=linkedReturn.id;d.isReturnVisit=true}const record={id:'visit_'+Date.now()+'_'+Math.random().toString(36).slice(2,7),savedAt:new Date().toISOString(),customerProfileId:activeCustomerId||d.customerProfileId||null,jobNumber:d.jobNumber,customerOrSite:d.customerOrSite,customerPhone:d.customerPhone,customerAddress:d.customerAddress,brand:d.brand,model:d.model,serialNumber:d.serialNumber,applianceKey:d.serialNumber?serialKey(d.serialNumber):null,complaint:d.complaint,caseClosureStatus:d.caseClosureStatus,followUpOfOrder:d.followUpOfOrder||null,returnVisitId:d.returnVisitId||null,summary:summaryText(),caseData:d};const applianceSave=d.serialNumber?upsertApplianceRecord(d,false):{saved:true,reason:'no-serial'};if(!applianceSave.saved){$('customerStatus').textContent='Visit was not saved because the appliance record could not be prepared. No history entry was added.';return}const updates={[HISTORY_KEY]:[record,...list]};if(d.serialNumber)updates[APPLIANCE_KEY]=applianceSave.records;if(linkedReturn){const ri=returnRows.findIndex(r=>r.id===linkedReturn.id);returnRows[ri]={...linkedReturn,status:'completed',completedAt:new Date().toISOString(),completedServiceOrder:currentJob,updatedAt:new Date().toISOString()};updates[RETURN_KEY]=returnRows}const committed=commitStoreTransaction(updates);if(!committed.ok){$('customerStatus').textContent='Visit was not finalized. '+(committed.rollbackOk?'No partial save remains. ':'A storage rollback could not be fully verified; stop editing and export any readable data immediately. ')+(committed.error||'Storage write failed.');return}$('customerStatus').textContent='Visit saved as '+d.jobNumber+'. Service history is read-only; this visit is a separate record.'+(!d.serialNumber?' No serial number was supplied, so this visit is not linked to an appliance history.':'')+(applianceSave.conflicts?.length?' WARNING: serial number matched an existing appliance but '+applianceSave.conflicts.map(x=>x.field+' ('+x.savedValue+' vs '+x.incomingValue+')').join(', ')+' did not match. The original appliance identity was preserved and a review alert was recorded.':'');renderHub();renderSerialHistory();renderPartsRecords();if(linkedReturn){renderReturnVisits();$('returnVisitStatus').textContent='Return visit '+currentJob+' saved and marked completed. It is linked to original service order '+linkedReturn.originalOrderNumber+'.'}closeWorkspace() } function openVisit(id){const h=readStore(HISTORY_KEY).find(x=>x.id===id);if(!h)return;const w=window.open('','_blank');if(!w){alert('Your browser blocked the visit detail window. Use Export history backup to keep a copy.');return}w.document.write('ServicePro Visit

ServicePro — Past Visit

Saved: '+esc(new Date(h.savedAt).toLocaleString())+'

'+esc(h.summary||JSON.stringify(h.caseData,null,2))+'
');w.document.close()} function renderCustomerDetail(){const host=$('customerDetail');if(!activeCustomerId){host.innerHTML='';return}const c=readStore(CUSTOMER_KEY).find(x=>x.id===activeCustomerId);if(!c){host.innerHTML='';return}const visits=readStore(HISTORY_KEY).filter(h=>h.customerProfileId===c.id||(!h.customerProfileId&&String(h.customerOrSite||'').trim().toLowerCase()===String(c.name||'').trim().toLowerCase())).sort((a,b)=>new Date(b.savedAt||0)-new Date(a.savedAt||0));const appliances=new Map();readStore(APPLIANCE_KEY).filter(a=>(a.linkedCustomerIds||[]).includes(c.id)||a.lastCustomerProfileId===c.id).forEach(a=>appliances.set(serialKey(a.serialNumber),{brand:a.brand,model:a.model,serial:a.serialNumber,count:readStore(HISTORY_KEY).filter(h=>serialKey(h.serialNumber||h.caseData?.serialNumber)===serialKey(a.serialNumber)).length,last:a.lastSeenAt}));visits.forEach(h=>{const d=h.caseData||{};const brand=h.brand||d.brand||'Appliance';const model=h.model||d.model||'Model not recorded';const serial=h.serialNumber||d.serialNumber||'';const key=serial?serialKey(serial):(brand+'|'+model).toLowerCase();if(!appliances.has(key))appliances.set(key,{brand,model,serial,count:0,last:h.savedAt});const a=appliances.get(key);a.count++;if(new Date(h.savedAt||0)>new Date(a.last||0))a.last=h.savedAt});const open=visits.filter(h=>{const d=h.caseData||{};const st=h.caseClosureStatus||d.caseClosureStatus||'';return st!=='closed-verified'&&(['open-follow-up-required','follow-up-needed','pending-verification'].includes(st)||Boolean(d.verificationNotes))});const repeated=new Map();visits.forEach(h=>{const complaint=String(h.complaint||h.caseData?.complaint||'').trim();if(complaint){const k=complaint.toLowerCase();if(!repeated.has(k))repeated.set(k,{text:complaint,count:0,latest:h.savedAt});repeated.get(k).count++}});const repeat=[...repeated.values()].filter(x=>x.count>1).sort((a,b)=>b.count-a.count);host.innerHTML='

Customer record: '+esc(c.name)+'

'+esc([c.phone,c.email,c.address].filter(Boolean).join(' • ')||'No contact details saved')+'

'+visits.length+'Saved visits
'+appliances.size+'Appliances
'+open.length+'Follow-ups to review

Appliances on record

'+(appliances.size?[...appliances.values()].map(a=>'
'+esc(a.brand)+' '+esc(a.model)+'
Serial: '+esc(a.serial||'Not recorded')+' · Visits: '+a.count+'
Last visit: '+esc(a.last?new Date(a.last).toLocaleDateString():'Unknown')+'
').join(''):'

No appliances saved yet. Save a service visit linked to this customer to build the appliance list.

')+'

Repeat complaints

'+(repeat.length?repeat.map(x=>'
'+esc(x.text)+'
Recorded '+x.count+' times
').join(''):'

No identical complaint text appears more than once in the saved visits.

')+'

Outstanding follow-ups

'+(open.length?open.map(h=>{const d=h.caseData||{};return '
'+esc(h.brand||d.brand||'Appliance')+' '+esc(h.model||d.model||'')+' · '+esc(h.caseClosureStatus||d.caseClosureStatus||'Needs review')+'
'+esc(d.verificationNotes||'Follow-up details not recorded.')+'
'}).join(''):'

No outstanding follow-ups identified from the saved case statuses.

')+'

All visits for this customer

'+(visits.length?visits.map(h=>{const d=h.caseData||{};return '

'+esc(h.brand||d.brand||'Appliance')+' '+esc(h.model||d.model||'')+'

'+esc(h.jobNumber||d.jobNumber||'No work order')+' · '+esc(h.savedAt?new Date(h.savedAt).toLocaleDateString():'Date unknown')+'

Complaint: '+esc(h.complaint||d.complaint||'Not recorded')+'

Repair: '+esc(d.repairPerformed||'Not recorded')+'

Parts: '+esc(d.partsUsed||'Not recorded')+'

Status: '+esc(h.caseClosureStatus||d.caseClosureStatus||'Not recorded')+'

'}).join(''):'

No saved visits are linked to this profile yet.

')+'
';host.querySelector('#closeCustomerDetail').addEventListener('click',()=>{activeCustomerId=null;host.innerHTML='';renderHub()});host.querySelector('#editProfileFromDetail').addEventListener('click',()=>{loadCustomer(c.id);$('profileName').scrollIntoView({behavior:'smooth',block:'center'})});host.querySelector('#newJobForCustomer').addEventListener('click',()=>{loadCustomer(c.id);$('setup').scrollIntoView({behavior:'smooth'})});host.querySelectorAll('[data-open-visit]').forEach(b=>b.addEventListener('click',()=>openVisit(b.dataset.openVisit)))} function renderHub(){const q=(val('customerSearch')||'').toLowerCase();const customers=readStore(CUSTOMER_KEY).filter(c=>[c.name,c.phone,c.email,c.address,c.notes].join(' ').toLowerCase().includes(q));$('customerList').innerHTML=customers.length?'

Customer profiles ('+customers.length+')

'+customers.map(c=>'
'+esc(c.name)+'

'+esc([c.phone,c.email,c.address].filter(Boolean).join(' • ')||'No contact details saved')+'

').join(''):'

No matching customer profiles yet.

'; const visits=readStore(HISTORY_KEY).filter(h=>[h.customerOrSite,h.customerPhone,h.customerAddress,h.jobNumber,h.brand,h.model,h.serialNumber,h.complaint].join(' ').toLowerCase().includes(q));$('historyList').innerHTML=visits.length?visits.slice(0,30).map(h=>'

'+esc(h.customerOrSite||'Unassigned customer')+' — '+esc(h.brand||'Appliance')+' '+esc(h.model||'')+'

'+esc(new Date(h.savedAt).toLocaleString())+' • Work order: '+esc(h.jobNumber||'not supplied')+'

'+esc(h.complaint||'No complaint entered')+'

Status: '+esc(h.caseClosureStatus||'not recorded')+' • Serial: '+esc(h.serialNumber||'not supplied')+'

').join(''):'

No saved service visits match this search. Save a visit to begin building history.

'; $('customerList').querySelectorAll('[data-load-customer]').forEach(b=>b.addEventListener('click',()=>loadCustomer(b.dataset.loadCustomer)));$('customerList').querySelectorAll('[data-use-customer]').forEach(b=>b.addEventListener('click',()=>{loadCustomer(b.dataset.useCustomer);$('setup').scrollIntoView({behavior:'smooth'});$('customer').value=val('profileName')}));$('historyList').querySelectorAll('[data-open-visit]').forEach(b=>b.addEventListener('click',()=>openVisit(b.dataset.openVisit)));renderCustomerDetail()} async function sha256Hex(text){if(!globalThis.crypto?.subtle)return null;const bytes=new TextEncoder().encode(text),digest=await crypto.subtle.digest('SHA-256',bytes);return [...new Uint8Array(digest)].map(b=>b.toString(16).padStart(2,'0')).join('')} function readArrayStrictForExport(key){const raw=localStorage.getItem(key);if(raw===null)return [];let parsed;try{parsed=JSON.parse(raw)}catch(e){throw new Error('Stored data in '+key+' is not valid JSON. Export stopped to avoid creating an incomplete backup.')}if(!Array.isArray(parsed))throw new Error('Stored data in '+key+' is not a valid record list. Export stopped to avoid creating an incomplete backup.');return parsed} async function exportHistory(){try{const payload={app:'ServicePro local data backup',schemaVersion:7,exportedAt:new Date().toISOString(),customers:readArrayStrictForExport(CUSTOMER_KEY),appliances:readArrayStrictForExport(APPLIANCE_KEY),serviceHistory:readArrayStrictForExport(HISTORY_KEY),partsRecords:readArrayStrictForExport(PARTS_KEY),serviceOrderForms:readArrayStrictForExport(FORMS_KEY),returnVisits:readArrayStrictForExport(RETURN_KEY),estimates:readArrayStrictForExport(ESTIMATE_KEY),invoices:readArrayStrictForExport(INVOICE_KEY),bulletinRecords:readArrayStrictForExport(BULLETIN_KEY)};const canonical=JSON.stringify(payload);const digest=await sha256Hex(canonical);if(digest)payload.integrity={algorithm:'SHA-256',digest};payload.recordCounts={customers:payload.customers.length,appliances:payload.appliances.length,serviceHistory:payload.serviceHistory.length,partsRecords:payload.partsRecords.length,serviceOrderForms:payload.serviceOrderForms.length,returnVisits:payload.returnVisits.length,estimates:payload.estimates.length,invoices:payload.invoices.length,bulletinRecords:payload.bulletinRecords.length};const blob=new Blob([JSON.stringify(payload,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='servicepro-full-backup-'+new Date().toISOString().slice(0,10)+'.json';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),30000);$('customerStatus').textContent='Full backup exported with validated records, nine data groups, counts, and '+(digest?'SHA-256 integrity verification.':'no checksum because Web Crypto is unavailable.');}catch(e){storageNotice('Backup export stopped: '+(e.message||'Stored data could not be validated.'));alert('Backup export stopped: '+(e.message||'Stored data could not be validated.'))}} function readArrayForBackupMerge(key){const raw=localStorage.getItem(key);if(raw===null)return [];const parsed=JSON.parse(raw);if(!Array.isArray(parsed))throw new Error('Local data in '+key+' is not a valid record list. No records were changed.');return parsed} function mergeBackupArray(current,incoming,identity){const next=current.slice(),seen=new Set(next.map(identity).filter(Boolean));let added=0;for(const item of incoming){if(!item||typeof item!=='object'||Array.isArray(item))throw new Error('Backup contains an invalid record. No records were changed.');const id=identity(item);if(!id||seen.has(id))continue;next.push(item);seen.add(id);added++}return {records:next,added}} function prepareBackupMerge(payload){const specs=[{name:'customers',key:CUSTOMER_KEY,input:payload.customers,identity:x=>String(x.id||'')},{name:'appliances',key:APPLIANCE_KEY,input:payload.appliances,identity:x=>serialKey(x.serialNumber)||String(x.id||'')},{name:'visits',key:HISTORY_KEY,input:payload.serviceHistory,identity:x=>String(x.jobNumber||x.caseData?.jobNumber||x.id||'')},{name:'forms',key:FORMS_KEY,input:payload.serviceOrderForms||[],identity:x=>String(x.jobNumber||'')},{name:'parts',key:PARTS_KEY,input:payload.partsRecords||[],identity:x=>String(x.id||'')},{name:'returnVisits',key:RETURN_KEY,input:payload.returnVisits||[],identity:x=>String(x.id||x.returnOrderNumber||'')},{name:'estimates',key:ESTIMATE_KEY,input:payload.estimates||[],identity:x=>String(x.id||x.estimateNumber||'')},{name:'invoices',key:INVOICE_KEY,input:payload.invoices||[],identity:x=>String(x.id||x.invoiceNumber||'')},{name:'bulletinRecords',key:BULLETIN_KEY,input:payload.bulletinRecords||[],identity:x=>String(x.id||'')}];const updates={},counts={};for(const spec of specs){const merged=mergeBackupArray(readArrayForBackupMerge(spec.key),spec.input,spec.identity);updates[spec.key]=merged.records;counts[spec.name]=merged.added}return {updates,counts}} function validateBackupPayload(payload){ if(!payload||typeof payload!=='object'||Array.isArray(payload)||payload.app!=='ServicePro local data backup')throw new Error('This is not a valid ServicePro full backup.'); if(!Number.isInteger(payload.schemaVersion)||payload.schemaVersion<1||payload.schemaVersion>7)throw new Error('Unsupported or missing backup schema version. No records were imported.'); const required=['customers','appliances','serviceHistory']; const optional=['serviceOrderForms','partsRecords','returnVisits','estimates','invoices','bulletinRecords']; for(const key of required){if(!Array.isArray(payload[key]))throw new Error('Backup is missing the required '+key+' record list. No records were imported.');} for(const key of optional){if(payload[key]!==undefined&&!Array.isArray(payload[key]))throw new Error('Backup contains an invalid '+key+' record list. No records were imported.');} const groups=[...required,...optional]; for(const key of groups){for(let i=0;i<(payload[key]||[]).length;i++){const row=payload[key][i];if(!row||typeof row!=='object'||Array.isArray(row))throw new Error('Backup contains an invalid record in '+key+' at position '+(i+1)+'. No records were imported.');}} const requiredIdentity={customers:x=>x.id,appliances:x=>x.serialNumber||x.id,serviceHistory:x=>x.jobNumber||x.caseData?.jobNumber||x.id}; for(const [key,getId] of Object.entries(requiredIdentity)){for(let i=0;ix.jobNumber===val('jobNumber')));$('customerStatus').textContent='Backup merged and verified: '+prepared.counts.customers+' customers, '+prepared.counts.appliances+' appliances, '+prepared.counts.visits+' visits, '+prepared.counts.forms+' form records, '+prepared.counts.parts+' parts records, '+prepared.counts.returnVisits+' return visits, and '+prepared.counts.estimates+' estimates, '+prepared.counts.invoices+' payment records, plus '+prepared.counts.bulletinRecords+' bulletin references added. Existing records were preserved.';}catch(e){alert('Backup restore failed: '+e.message);$('customerStatus').textContent='Backup restore failed. '+e.message;}finally{$('importHistoryFile').value=''}} function restoreDraft(){try{const raw=localStorage.getItem('servicepro_refrigerator_draft_v1');if(!raw)return;const d=JSON.parse(raw);$('jobNumber').value=d.jobNumber||'';$('technician').value=d.technician||'';$('customer').value=d.customerOrSite||'';$('profilePhone').value=d.customerPhone||'';$('profileEmail').value=d.customerEmail||'';$('profileAddress').value=d.customerAddress||'';$('profileNotes').value=d.customerNotes||'';activeCustomerId=d.customerProfileId||null;$('serviceDate').value=d.serviceDate||'';$('brand').value=d.brand||'Whirlpool';$('model').value=d.model||'';$('serial').value=d.serialNumber||'';$('complaint').value=d.complaint||'Runs but is not cooling properly';$('error').value=d.errorCode||'';$('duration').value=d.duration||'unknown';$('fridgeTemp').value=d.temperaturesF?.freshFood||'';$('freezerTemp').value=d.temperaturesF?.freezer||'';setRadio('pattern',d.temperaturePattern);$('tempNotes').value=d.temperatureNotes||'';setRadio('fan',d.evaporatorFan);$('fanNotes').value=d.fanNotes||'';setRadio('air',d.freshFoodAirflow);$('airNotes').value=d.airflowNotes||'';$('frostPattern').value=d.evaporatorFrostPattern||'unknown';$('doorSeal').value=d.doorSealInspection||'unknown';$('testStatus').value=d.testStatus||'not-started';$('testCategory').value=d.testCategory||'none';$('testFinding').value=d.testFinding||'unknown';$('testResultNotes').value=d.testResultNotes||'';$('finalNotes').value=d.technicianNotes||'';$('repairPerformed').value=d.repairPerformed||'';$('partsUsed').value=d.partsUsed||'';$('postFridgeTemp').value=d.postRepairTemperaturesF?.freshFood||'';$('postFreezerTemp').value=d.postRepairTemperaturesF?.freezer||'';$('verificationStatus').value=d.postRepairVerification||'not-verified';$('complaintResolved').value=d.originalComplaintStatus||'unknown';$('verificationNotes').value=d.verificationNotes||'';$('closureStatus').textContent=({'closed-verified':'Case closure: verification recorded and complaint marked resolved.','open-follow-up-required':'Case remains open: verification failed or complaint remains unresolved.','follow-up-needed':'Follow-up needed: results are inconclusive or only partially resolved.','pending-verification':'Case closure: pending verification.'})[closureLabel()];$('savedStatus').textContent='Previous draft restored from this device';}catch(e){}} $('saveReturnVisitBtn').addEventListener('click',saveReturnVisit);$('clearReturnVisitBtn').addEventListener('click',clearReturnVisitForm);renderReturnVisits(); $('protectStorageBtn').addEventListener('click',protectLocalStorage);refreshStorageStatus();$('saveCustomerBtn').addEventListener('click',saveCustomer);$('clearCustomerBtn').addEventListener('click',clearCustomerForm);$('customerSearch').addEventListener('input',renderHub);$('serial').addEventListener('input',renderSerialHistory);$('serial').addEventListener('change',renderSerialHistory);$('saveVisitBtn').addEventListener('click',saveVisit);$('exportHistoryBtn').addEventListener('click',exportHistory);$('importHistoryBtn').addEventListener('click',()=>$('importHistoryFile').click());$('importHistoryFile').addEventListener('change',e=>importHistoryBackup(e.target.files?.[0]));addTestInstructions();$('startBtn').addEventListener('click',begin);$('tempsBtn').addEventListener('click',goFan);$('fanBtn').addEventListener('click',goAir);$('assessmentBtn').addEventListener('click',rank);$('applyTestBtn').addEventListener('click',applyTestEvidence); function applyTestEvidence(){ const status=val('testStatus'),tc=val('testCategory'),tf=val('testFinding'); if(!['pass','fail'].includes(status)){alert('Mark the test as Passed or Failed only after you have performed it. For an unperformed or unclear test, leave it unranked.');return} if(tc==='none'||tf==='unknown'){alert('Choose the test you actually performed and its structured finding before applying evidence.');return} const statusConflict=(tf==='normal'&&status==='fail')||(tf==='abnormal'&&status==='pass')||(tf==='obstruction-found'&&status==='pass')||(tf==='no-obstruction'&&status==='fail'); if(statusConflict){alert('The test status conflicts with the structured finding. Reconcile the status and finding before applying evidence.');return} const findingAllowed={defrost:['normal','abnormal'],fan:['normal','abnormal'],airpath:['obstruction-found','no-obstruction'],cooling:['normal','abnormal']}; if(!findingAllowed[tc]||!findingAllowed[tc].includes(tf)){alert('That finding does not match the selected test category. Choose a compatible structured finding so the engine does not apply misleading evidence.');return} const t=complaintType(); const rec={ defrost:{abnormal:['Verify the recorded abnormal defrost result against the exact model’s service criteria, then isolate the relevant sensing, termination, heater, or control path using the manufacturer procedure.','An abnormal result elevates the defrost-system investigation but does not identify a failed component.'],normal:['If the symptom recurs, document the timing and use verified model-specific diagnostics to investigate intermittent defrost operation and moisture entry.','A normal result lowers support for faults detectable by that test under those conditions, but does not exclude intermittent or out-of-scope faults.']}, fan:{abnormal:['Confirm fan command conditions, then isolate the motor, connector, wiring, and control output using the exact model’s procedure.','An abnormal fan test supports a fan-path investigation; further isolation is needed before naming a failed part.'],normal:['Check physical ice or duct restriction, damper operation, and temperature trend while considering intermittent fan behavior.','A normal fan check shifts attention toward distribution or intermittent issues without excluding every fan fault.']}, airpath:{'obstruction-found':['Document the obstruction, correct it safely using an approved procedure, then re-check airflow and temperature trend.','A directly observed obstruction may contribute to the symptom; confirm the effect of correcting it and investigate why it occurred.'],'no-obstruction':['Check damper movement and fan operation under the correct conditions, then review the evaporator frost pattern using model-specific guidance.','No obstruction was found in the inspected area; this does not establish that every part of the air path is clear.']}, cooling:{abnormal:['Verify operating conditions and follow the exact model’s diagnostic sequence for cooling production before any sealed-system conclusion.','An abnormal cooling check broadens the investigation beyond airflow delivery alone.'],normal:['Track both compartment temperatures through an adequate operating period and re-check airflow distribution, damper behavior, and intermittent conditions.','Normal cooling production under these conditions shifts attention toward delivery, controls, or intermittent issues but does not confirm one.']} }; const entry=rec[tc]?.[tf]; if(!entry){alert('No guidance is available for this test result. The evidence was not applied.');return} if(t==='cooling'){ const adaptive=window.serviceProAdaptiveAnswers||{};const noActivity=/No obvious cooling activity/.test(adaptive.coolingState||'');const tooCold=/Food freezing/.test(adaptive.pattern||''); if(!noActivity&&!adaptive.pattern){alert('Complete the baseline cooling assessment and record the temperature pattern before applying test evidence.');return} if(!noActivity&&!tooCold&&(!adaptive.fan||!adaptive.airflow)){alert('Complete the fan and airflow observations, or explicitly choose Not checked yet, before applying this cooling test evidence.');return} const config=(window.serviceProConfigs||{}).cooling;if(!config){alert('The cooling assessment configuration is unavailable. Re-enter the complaint and begin diagnosis again.');return} rankSpecial(config); }else{ const configs=window.serviceProConfigs||{};const c=configs[t]||configs.general; if(!c){alert('The complaint-specific assessment is not available yet. Re-enter the complaint and begin diagnosis again.');return} rankSpecial(c); } $('nextTestText').textContent=entry[0]; $('resultIntro').textContent='Structured test evidence applied. '+$('resultIntro').textContent; const existing=$('testEvidenceApplied');if(existing)existing.remove(); const article=document.createElement('article');article.id='testEvidenceApplied';article.className='resultitem';article.innerHTML='

EApplied test evidence

'+escapeHTML(entry[1])+'

'; const host=$('resultsContent');host.insertBefore(article,host.firstChild); saveDraft(); } // Service-order-specific customer forms. Signatures are never carried to a new order. // Local multi-key writes use best-effort rollback; browser localStorage is not a cloud database or a true ACID store. const FORMS_KEY='servicepro_forms_v1';let signatureDirty=false,signatureDrawing=false;const sig=$('customerSignature'),sigCtx=sig.getContext('2d'); function activeOrder(){return val('jobNumber')||ensureServiceOrder()} function resizeSignature(){const r=sig.getBoundingClientRect(),ratio=window.devicePixelRatio||1;const old=signatureDirty?sig.toDataURL():null;sig.width=Math.max(1,Math.round(r.width*ratio));sig.height=Math.max(1,Math.round(r.height*ratio));sigCtx.setTransform(ratio,0,0,ratio,0,0);sigCtx.lineWidth=2.2;sigCtx.lineCap='round';sigCtx.lineJoin='round';sigCtx.strokeStyle='#142a43';if(old){const im=new Image();im.onload=()=>sigCtx.drawImage(im,0,0,r.width,r.height);im.src=old}} function sigPoint(e){const r=sig.getBoundingClientRect();return{x:e.clientX-r.left,y:e.clientY-r.top}} sig.addEventListener('pointerdown',e=>{signatureDrawing=true;sig.setPointerCapture(e.pointerId);const p=sigPoint(e);sigCtx.beginPath();sigCtx.moveTo(p.x,p.y);signatureDirty=true});sig.addEventListener('pointermove',e=>{if(!signatureDrawing)return;const p=sigPoint(e);sigCtx.lineTo(p.x,p.y);sigCtx.stroke()});['pointerup','pointercancel','lostpointercapture'].forEach(n=>sig.addEventListener(n,()=>signatureDrawing=false)); $('clearSignature').addEventListener('click',()=>{sigCtx.clearRect(0,0,sig.width,sig.height);signatureDirty=false}); function compressPhoto(file){return new Promise((resolve,reject)=>{if(!file||!/^image\//i.test(file.type||'')){reject(new Error('Not an image'));return}if(file.size>20*1024*1024){reject(new Error('Original image exceeds 20 MB'));return}const rd=new FileReader();rd.onerror=()=>reject(new Error('Could not read image'));rd.onload=()=>{const im=new Image();im.onerror=()=>reject(new Error('Image format could not be decoded'));im.onload=()=>{if(!im.width||!im.height){reject(new Error('Image dimensions are invalid'));return}let scale=Math.min(1,1280/Math.max(im.width,im.height));const c=document.createElement('canvas'),ctx=c.getContext('2d');if(!ctx){reject(new Error('Image compression is unavailable'));return}let data='';for(const edge of [1280,1100,960,800]){scale=Math.min(1,edge/Math.max(im.width,im.height));c.width=Math.max(1,Math.round(im.width*scale));c.height=Math.max(1,Math.round(im.height*scale));ctx.clearRect(0,0,c.width,c.height);ctx.drawImage(im,0,0,c.width,c.height);for(const quality of [.72,.62,.52]){data=c.toDataURL('image/jpeg',quality);if(Math.ceil((data.length-2)*.75)<=650*1024)break}if(Math.ceil((data.length-2)*.75)<=650*1024)break}const bytes=Math.ceil((data.length-2)*.75);if(!data||bytes>650*1024){reject(new Error('Could not compress below 650 KB'));return}resolve({name:file.name,type:'image/jpeg',addedAt:new Date().toISOString(),width:c.width,height:c.height,bytes,data})};im.src=rd.result};rd.readAsDataURL(file)})} function photoBytes(photos){return (photos||[]).reduce((sum,p)=>sum+(Number(p.bytes)||Math.ceil(String(p.data||'').length*.75)),0)} async function handlePhotos(inputId,kind){const input=$(inputId),files=[...(input.files||[])];if(!files.length)return;const order=activeOrder();if(!files.length)return;const original=readStore(FORMS_KEY),records=original.map(r=>({...r,beforePhotos:[...(r.beforePhotos||[])],afterPhotos:[...(r.afterPhotos||[])],damagePhotos:[...(r.damagePhotos||[])]}));let rec=records.find(x=>x.jobNumber===order);if(!rec){rec={jobNumber:order,createdAt:new Date().toISOString(),beforePhotos:[],afterPhotos:[],damagePhotos:[]};records.unshift(rec)}const dest=kind==='before'?'beforePhotos':kind==='damage'?'damagePhotos':'afterPhotos',existing=rec[dest]||[];if(existing.length+files.length>8){$('formDeliveryStatus').textContent='Photo limit: up to 8 '+kind+' photos per service order. Existing photos were not changed.';input.value='';return}let added=0,failed=[];for(const f of files){try{const photo=await compressPhoto(f);if(photoBytes([...rec.beforePhotos,...rec.afterPhotos,...(rec.damagePhotos||[]),photo])>3*1024*1024){failed.push(f.name+' (3 MB service-order photo limit reached)');continue}rec[dest].push(photo);added++}catch(e){failed.push(f.name+' ('+(e?.message||'could not process')+')')}}if(!added){$('formDeliveryStatus').textContent='No photos were added. '+(failed.join('; ')||'Check the selected image files and try again.');input.value='';return}rec.updatedAt=new Date().toISOString();if(!writeStore(FORMS_KEY,records)){$('formDeliveryStatus').textContent='Photo save failed because browser storage may be full. Previously saved photos were preserved. Export a full backup, then retry with fewer or smaller images.';return}input.value='';renderFormRecord(rec);$('formDeliveryStatus').textContent=added+' compressed photo(s) saved to '+order+'. '+(failed.length?'Not added: '+failed.join('; '):'')} $('beforePhotos').addEventListener('change',()=>handlePhotos('beforePhotos','before'));$('damagePhotos').addEventListener('change',()=>handlePhotos('damagePhotos','damage'));$('afterPhotos').addEventListener('change',()=>handlePhotos('afterPhotos','after')); function renderFormRecord(rec){for(const [kind,id] of [['before','beforePhotoPreview'],['damage','damagePhotoPreview'],['after','afterPhotoPreview']]){const arr=rec?.[kind+'Photos']||[];$(id).innerHTML=arr.map(x=>'
'+esc(x.name)+'

'+esc(x.name)+'
Added: '+esc(new Date(x.addedAt||x.takenAt).toLocaleString())+'

').join('')||'

No '+kind+' photos added.

'}const saved=Boolean(rec?.signedAt);$('formsBubblePreview').textContent=saved?'Signed · '+(rec.damagePhotos?.length||0)+' damage / '+(rec.beforePhotos?.length||0)+' before / '+(rec.afterPhotos?.length||0)+' after':'Waiver · photos · approval';$('formsOrderStatus').textContent='Service order: '+(rec?.jobNumber||val('jobNumber')||'Not generated')+(saved?' · Signed '+new Date(rec.signedAt).toLocaleString():' · Awaiting customer signature');$('savedFormsList').innerHTML=saved?'
Customer authorization saved

Order: '+esc(rec.jobNumber)+'

Signed by: '+esc(rec.signerName)+' · '+esc(new Date(rec.signedAt).toLocaleString())+'

Damage photos: '+(rec.damagePhotos?.length||0)+' · Before photos: '+(rec.beforePhotos?.length||0)+' · After photos: '+(rec.afterPhotos?.length||0)+'

Email status: Not sent — email service not configured

':'

No signed forms saved for this service order yet.

'} function loadFormRecord(rec){const d=rec?.signedPayload||rec||{};for(const [id,value] of [['preexistingNotes',d.preexistingNotes||''],['authorizationScope',d.authorizationScope||''],['signerName',d.signerName||''],['signerEmail',d.signerEmail||'']])$(id).value=value;for(const [id,value] of [['ackPreexisting',d.ackPreexisting],['ackMoving',d.ackMoving],['ackCosmetic',d.ackCosmetic],['authorizeWork',d.authorizeWork]])$(id).checked=value===true;sigCtx.clearRect(0,0,sig.width,sig.height);if($('beforePhotos'))$('beforePhotos').value='';if($('damagePhotos'))$('damagePhotos').value='';if($('afterPhotos'))$('afterPhotos').value='';signatureDirty=false;signatureDrawing=false;if(rec?.signature){const expectedOrder=rec.jobNumber||val('jobNumber');const im=new Image();im.onload=()=>{if((val('jobNumber')||null)!==(expectedOrder||null))return;sigCtx.clearRect(0,0,sig.width,sig.height);sigCtx.drawImage(im,0,0,sig.width/(window.devicePixelRatio||1),sig.height/(window.devicePixelRatio||1));signatureDirty=true};im.src=rec.signature}renderFormRecord(rec)} function formPayload(){return {jobNumber:activeOrder(),customer:val('customer')||val('profileName'),brand:val('brand'),model:val('model'),serialNumber:val('serial'),serviceDate:val('serviceDate'),ackPreexisting:$('ackPreexisting').checked,preexistingNotes:val('preexistingNotes'),ackMoving:$('ackMoving').checked,ackCosmetic:$('ackCosmetic').checked,authorizationScope:val('authorizationScope'),authorizeWork:$('authorizeWork').checked,signerName:val('signerName'),signerEmail:val('signerEmail'),signature:signatureDirty?sig.toDataURL('image/png'):null}} function saveSigned(){const d=formPayload();if(!d.ackPreexisting||!d.ackMoving||!d.ackCosmetic){alert('Please complete each customer acknowledgement before signing.');return}if(!d.preexistingNotes){$('preexistingNotes').focus();alert('Record visible pre-existing condition or enter “None observed.”');return}if(!d.authorizationScope||!d.authorizeWork){alert('Enter the authorized work scope and obtain customer approval.');return}if(!d.signerName||!signatureDirty){alert('Customer name and a signature are required.');return}const list=readStore(FORMS_KEY),existing=list.find(x=>x.jobNumber===d.jobNumber);if(existing?.signedAt){alert('This service order already has a signed authorization. Start a new service order for a new visit; do not reuse a prior signature.');return}const rec={...(existing||{}),...d,signedPayload:{...d},signedAt:new Date().toISOString(),beforePhotos:existing?.beforePhotos||[],damagePhotos:existing?.damagePhotos||[],afterPhotos:existing?.afterPhotos||[],emailStatus:'not-configured'};const idx=list.findIndex(x=>x.jobNumber===d.jobNumber);if(idx>=0)list[idx]=rec;else list.unshift(rec);if(!writeStore(FORMS_KEY,list)){alert('Could not save. Browser storage may be full; export/remove photos and retry.');return}renderFormRecord(rec);$('formDeliveryStatus').textContent='Signed authorization saved locally for '+d.jobNumber+'. Automatic email is not available until a secure email service is configured; use Print / save PDF to provide the customer a copy.';closeWorkspace();} $('saveSignedForms').addEventListener('click',saveSigned); function formHTML(){const live=formPayload(),rec=readStore(FORMS_KEY).find(x=>x.jobNumber===live.jobNumber)||{};const d=rec.signedPayload||rec;const signed=rec.signedAt?new Date(rec.signedAt).toLocaleString():'Not signed';const photos=(arr,label)=>(arr||[]).map((x,i)=>'
'+label+' '+(i+1)+' — Added '+new Date(x.addedAt||x.takenAt).toLocaleString()+'
').join('');return '

ServicePro — Customer Authorization

Service order: '+esc(d.jobNumber)+' · Estimate date: '+esc(d.serviceDate||'Not entered')+'

Customer: '+esc(d.customer||'Not entered')+' · Appliance: '+esc([d.brand,d.model].filter(Boolean).join(' ')||'Not entered')+' · Serial: '+esc(d.serialNumber||'Not entered')+'

Damage and condition acknowledgement

Pre-existing condition reviewed: '+(d.ackPreexisting?'Yes':'No')+'. Notes: '+esc(d.preexistingNotes||'None entered')+'

Moving/access risks reviewed: '+(d.ackMoving?'Yes':'No')+'. Cosmetic condition reviewed: '+(d.ackCosmetic?'Yes':'No')+'.

This acknowledgement records conditions and risks discussed. It is not a blanket release of liability or a waiver of responsibility for negligence or improper work.

Work authorization

'+esc(d.authorizationScope||'No scope entered')+'

Customer approval: '+(d.authorizeWork?'Authorized':'Not authorized')+'

Signer: '+esc(d.signerName||'Not entered')+' · Email: '+esc(d.signerEmail||'Not entered')+'

Signature captured: '+esc(signed)+'

'+(rec.signature?'':'')+'

Pre-existing damage photos

'+photos(rec.damagePhotos,'Pre-existing damage')+'

Before-service photos

'+photos(rec.beforePhotos,'Before')+'

After-service photos

'+photos(rec.afterPhotos,'After')+'

Prepared by ServicePro. Keep a copy with this service order.

'} function openFormPrint(){const w=window.open('','_blank');if(!w){alert('Allow pop-ups to preview or print this form.');return}w.document.write('ServicePro Forms'+formHTML()+'

');w.document.close()} $('printForms').addEventListener('click',openFormPrint);$('previewForm').addEventListener('click',openFormPrint); async function emailFormsCopy(){const order=activeOrder(),rec=readStore(FORMS_KEY).find(x=>x.jobNumber===order);if(!rec?.signedAt){alert('Save the customer-signed authorization for this service order before sharing a copy.');return}const recipient=String(rec.signerEmail||val('signerEmail')||val('profileEmail')||'').trim();if(!recipient){alert('Enter the customer email address before sharing the signed authorization.');$('signerEmail').focus();return}const html='ServicePro signed authorization '+esc(order)+''+formHTML()+'';const file=new File([html],'ServicePro-'+order+'-signed-authorization.html',{type:'text/html'});const subject='ServicePro signed work authorization — '+order;const body='Hello '+(rec.signerName||'')+',\n\nAttached is your signed ServicePro work authorization for service order '+order+'.\n\nThank you.';try{if(navigator.share&&navigator.canShare&&navigator.canShare({files:[file]})){await navigator.share({files:[file],title:subject,text:body});$('formDeliveryStatus').textContent='Signed authorization shared. Complete sending in your email app if it has not already been sent.';return}}catch(err){if(err?.name==='AbortError')return}const blob=new Blob([html],{type:'text/html;charset=utf-8'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=file.name;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),30000);window.location.href='mailto:'+encodeURIComponent(recipient)+'?subject='+encodeURIComponent(subject)+'&body='+encodeURIComponent(body+'\n\nThe signed authorization was downloaded separately. Please attach the downloaded HTML file before sending.');$('formDeliveryStatus').textContent='Signed authorization downloaded and email draft opened. Attach the downloaded file before sending.'} $('emailForms').addEventListener('click',emailFormsCopy); function exportFormsPacket(){try{const order=activeOrder(),rec=readArrayStrictForExport(FORMS_KEY).find(x=>x.jobNumber===order);if(!rec){alert('No forms or photos are saved for this service order yet.');return}const blob=new Blob([JSON.stringify({app:'ServicePro Forms Packet',exportedAt:new Date().toISOString(),serviceOrder:order,record:rec},null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='ServicePro-'+order+'-forms-photos.json';document.body.appendChild(a);a.click();a.remove();URL.revokeObjectURL(url)}catch(e){storageNotice('Forms export stopped: '+e.message);alert('Forms export stopped: '+e.message)}} const exportFormsBtn=document.createElement('button');exportFormsBtn.type='button';exportFormsBtn.className='btn ghost';exportFormsBtn.textContent='Export forms & photos';exportFormsBtn.addEventListener('click',exportFormsPacket);$('printForms').parentElement.appendChild(exportFormsBtn); $('jobNumber').addEventListener('change',()=>{const r=readStore(FORMS_KEY).find(x=>x.jobNumber===val('jobNumber'));loadFormRecord(r);renderPartsRecords();loadEstimateForOrder()}); resizeSignature();window.addEventListener('resize',resizeSignature);renderFormRecord(readStore(FORMS_KEY).find(x=>x.jobNumber===val('jobNumber'))); $('addPartRecordBtn').addEventListener('click',addPartRecord);$('partsRecordList').addEventListener('input',e=>{const field=e.target.dataset.partField,card=e.target.closest('[data-part-id]');if(field&&card&&field!=='quantity')updatePartRecord(card.dataset.partId,field,e.target.value)});$('partsRecordList').addEventListener('change',e=>{const field=e.target.dataset.partField,card=e.target.closest('[data-part-id]');if(field&&card)updatePartRecord(card.dataset.partId,field,e.target.value)});$('partsRecordList').addEventListener('click',e=>{const b=e.target.closest('[data-delete-part]');if(b)deletePartRecord(b.dataset.deletePart)});$('summaryBtn').addEventListener('click',makeSummary);$('updateClosureBtn').addEventListener('click',updateClosure);$('verificationStatus').addEventListener('change',updateClosure);$('complaintResolved').addEventListener('change',updateClosure);$('exportBtn').addEventListener('click',exportJSON);$('copyBtn').addEventListener('click',copySummary);document.querySelectorAll('[data-back]').forEach(b=>b.addEventListener('click',()=>show(b.dataset.back)));$('newBtn').addEventListener('click',()=>{if(confirm('Start a new case? This clears the current draft on this device.')){if(!clearDraftForNewCase())return;$('jobNumber').value='';location.reload()}});document.querySelectorAll('input,select,textarea').forEach(el=>{el.addEventListener('change',saveDraft);el.addEventListener('input',saveDraft)});restoreDraft();loadFormRecord(readStore(FORMS_KEY).find(x=>x.jobNumber===val('jobNumber')));renderHub();renderSerialHistory();renderPartsRecords();loadEstimateForOrder();$('progressBar').style.width=((1/ids.length)*100)+'%'; // Dashboard navigation opens incorporated full-screen workspaces; the dashboard itself never scrolls. const workspace=document.createElement('div'); workspace.className='workspace-window'; workspace.id='serviceProWorkspace'; workspace.setAttribute('role','dialog'); workspace.setAttribute('aria-modal','true'); workspace.setAttribute('aria-label','ServicePro work area'); workspace.innerHTML='
Work area
'; document.body.appendChild(workspace); const workspaceContent=workspace.querySelector('#workspaceContent'); const workspaceTitle=workspace.querySelector('#workspaceTitle'); const movedSections=[]; const groupedWorkAreas={ customerHub:[['Customer','customerHub'],['Cloud records','cloudHub']], applianceAnchor:[['Appliance','applianceAnchor'],['Service history','historyList'],['Bulletins','bulletinHub']], results:[['Service order','applianceAnchor'],['Parts','partsRecordsSection']], estimateHub:[['Estimate','estimateHub'],['Payments','invoiceHub']], formsHub:[['Forms & photos','formsHub']], returnVisitHub:[['Return visits','returnVisitHub']] }; let activeGroup=null; const viewDefinitions={ cloudHub:{title:'Cloud Records',ids:['spCloudPanel']}, customerHub:{title:'Customer & Service History',ids:['customerHub']}, applianceAnchor:{title:'Appliance & Service Order',ids:['setup']}, diagnosisAnchor:{title:'Guided Diagnosis',ids:['setup','symptomStep','stepTemps','stepFan','stepAir','results']}, historyList:{title:'Service History',ids:['customerHub']}, partsRecordsSection:{title:'Parts Records',ids:['partsRecordsSection']}, estimateHub:{title:'Repair Estimate',ids:['estimateHub']}, invoiceHub:{title:'Estimates & Payments',ids:['invoiceHub']}, results:{title:'Service Report & Closeout',ids:['results']}, formsHub:{title:'Forms & Photo Documentation',ids:['formsHub']}, returnVisitHub:{title:'Return Visits & Parts Scheduling',ids:['returnVisitHub']}, bulletinHub:{title:'Service Bulletin Lookup',ids:['bulletinHub']} }; function closeWorkspace(){ movedSections.slice().reverse().forEach(item=>{if(item.placeholder.parentNode)item.placeholder.parentNode.insertBefore(item.element,item.placeholder);item.placeholder.remove()}); movedSections.length=0;workspaceContent.replaceChildren();workspace.classList.remove('open');document.body.classList.remove('view-open');workspaceContent.scrollTop=0; document.querySelectorAll('.dash-bubble').forEach(b=>b.removeAttribute('aria-current')); } function openWorkspace(key,button){ const def=viewDefinitions[key];if(!def)return; const group=activeGroup||key; closeWorkspace();activeGroup=group;workspaceTitle.textContent=group==='estimateHub'?'Estimate & Payment':group==='results'?'Service Order':group==='returnVisitHub'?'Schedule':def.title; const tabs=groupedWorkAreas[group]||[[def.title,key]]; if(tabs.length>1){const bar=document.createElement('div');bar.className='servicepro-subnav';bar.setAttribute('aria-label','Related work areas');tabs.forEach(([label,target])=>{const b=document.createElement('button');b.type='button';b.textContent=label;b.setAttribute('aria-pressed',String(target===key));b.addEventListener('click',()=>{activeGroup=group;openWorkspace(target,null)});bar.appendChild(b)});workspaceContent.appendChild(bar)} def.ids.forEach(id=>{const el=document.getElementById(id);if(!el)return;const placeholder=document.createComment('ServicePro workspace return point: '+id);el.parentNode.insertBefore(placeholder,el);movedSections.push({element:el,placeholder});workspaceContent.appendChild(el)}); if(key==='invoiceHub')refreshInvoiceOptions(); if(key==='customerHub'||key==='historyList')renderHub(); if(key==='partsRecordsSection')renderPartsRecords(); workspace.classList.add('open');document.body.classList.add('view-open');workspaceContent.scrollTop=0; if(key==='cloudHub'){const details=document.querySelector('#spCloudPanel details');if(details)details.open=true;} /* Signature canvases are hidden at initial page load. Size them only after their workspace is visible. */ if(key==='estimateHub'){resizeEstimateSignature();loadEstimateForOrder()} if(key==='formsHub'){resizeSignature();loadFormRecord(readStore(FORMS_KEY).find(x=>x.jobNumber===val('jobNumber')))} if(button)button.setAttribute('aria-current','true'); } document.querySelectorAll('.dash-bubble[data-jump]').forEach(btn=>btn.addEventListener('click',()=>{activeGroup=null;openWorkspace(btn.dataset.jump,btn)})); workspace.querySelector('#workspaceBack').addEventListener('click',()=>{activeGroup=null;closeWorkspace()}); function bulletinSearch(kind){ const brand=($('bulletinBrand').value||val('brand')||'').trim(); const model=($('bulletinModel').value||val('model')||'').trim(); const serial=($('bulletinSerial').value||val('serial')||'').trim(); if(!brand&&!model&&!serial){$('bulletinSearchStatus').textContent='Enter a manufacturer, model, or serial number before searching.';return} const officialDomains={whirlpool:'whirlpool.com',maytag:'maytag.com',kitchenaid:'kitchenaid.com',amana:'amana.com',jennair:'jennair.com',ge:'geappliances.com',"general electric":'geappliances.com',frigidaire:'frigidaire.com',electrolux:'electrolux.com',lg:'lg.com',samsung:'samsung.com',bosch:'bosch-home.com',thermador:'thermador.com',miele:'mieleusa.com',"fisher paykel":'fisherpaykel.com',haier:'haierappliances.com'}; const brandKey=brand.toLowerCase().replace(/[^a-z0-9 ]/g,'').trim(); const domain=officialDomains[brandKey]||''; const identity=[brand,model,serial].filter(Boolean).map(x=>'"'+x.replace(/"/g,'')+'"').join(' '); const bulletinTerms='("service bulletin" OR "technical service bulletin" OR "service pointer" OR "service flash")'; const officialQuery=(domain?'site:'+domain+' ':'')+identity+' '+bulletinTerms; const broadQuery=identity+' '+bulletinTerms; const query=kind==='serial'?broadQuery:officialQuery; const url='https://www.google.com/search?q='+encodeURIComponent(query); window.open(url,'_blank','noopener'); const mode=kind==='serial'?'broader web references':(domain?'official '+brand+' domain':'manufacturer-focused web search'); $('bulletinSearchStatus').textContent='Opened '+mode+' using all entered identity details. Results are leads only: ServicePro has not fetched or verified a bulletin. Confirm the exact model/serial range, exclusions, revision, and publication date in the original manufacturer document before marking applicability confirmed.'; } $('bulletinBrand').value=val('brand')||'';$('bulletinModel').value=val('model')||'';$('bulletinSerial').value=val('serial')||''; $('bulletinSearchModel').addEventListener('click',()=>bulletinSearch('model')); $('bulletinSearchSerial').addEventListener('click',()=>bulletinSearch('serial')); $('brand').addEventListener('change',()=>{if(!$('bulletinBrand').value)$('bulletinBrand').value=val('brand')}); $('model').addEventListener('change',()=>{if(!$('bulletinModel').value)$('bulletinModel').value=val('model')}); $('serial').addEventListener('change',()=>{if(!$('bulletinSerial').value)$('bulletinSerial').value=val('serial')}); function renderBulletinRecords(){const host=$('savedBulletinRecords');if(!host)return;const rows=readStore(BULLETIN_KEY).filter(x=>x.jobNumber===val('jobNumber')).sort((a,b)=>String(b.savedAt||'').localeCompare(String(a.savedAt||'')));host.innerHTML=rows.length?'

Saved bulletin references for this order ('+rows.length+')

'+rows.map(r=>'

'+esc(r.bulletinNumber||'Bulletin number not entered')+' · '+esc(r.title||'Untitled reference')+'

'+esc(r.brand||'Manufacturer not entered')+' '+esc(r.model||'')+' · Serial: '+esc(r.serialNumber||'Not entered')+'

Status: '+esc(r.applicabilityLabel||r.applicability)+' · Published/revised: '+esc(r.publicationDate||'Not recorded')+'

Coverage: '+esc(r.coverage||'Not recorded')+'

Notes: '+esc(r.notes||'None')+'

'+(r.sourceUrl?'

Open source document

':'

No source URL saved.

')+'
').join(''):'

No bulletin references saved for this service order yet.

';host.querySelectorAll('[data-delete-bulletin]').forEach(b=>b.addEventListener('click',()=>{if(!confirm('Delete this saved bulletin reference?'))return;const next=readStore(BULLETIN_KEY).filter(x=>x.id!==b.dataset.deleteBulletin);if(writeStore(BULLETIN_KEY,next))renderBulletinRecords()}))} function saveBulletinRecord(){const order=val('jobNumber')||ensureServiceOrder();const source=val('bulletinSource');if(source){try{const u=new URL(source);if(!['http:','https:'].includes(u.protocol))throw new Error('Only HTTP or HTTPS source links are allowed.')}catch(e){$('bulletinSearchStatus').textContent='Enter a valid http(s) source URL or leave it blank.';return}}const applicability=$('bulletinApplicability').value;const labels={unverified:'Unverified reference',possible:'Possible match — verify coverage',confirmed:'Confirmed by technician against manufacturer coverage', 'not-applicable':'Checked — not applicable'};const row={id:'sb_'+Date.now()+'_'+Math.random().toString(36).slice(2,7),jobNumber:order,brand:val('bulletinBrand')||val('brand'),model:val('bulletinModel')||val('model'),serialNumber:val('bulletinSerial')||val('serial'),bulletinNumber:val('bulletinNumber'),title:val('bulletinTitle'),publicationDate:val('bulletinDate'),applicability,applicabilityLabel:labels[applicability],coverage:val('bulletinCoverage'),sourceUrl:source,notes:val('bulletinNotes'),savedAt:new Date().toISOString()};if(!row.bulletinNumber&&!row.title&&!row.sourceUrl){$('bulletinSearchStatus').textContent='Enter a bulletin number, title, or source URL before saving.';return}const rows=readStore(BULLETIN_KEY);rows.unshift(row);if(!writeStore(BULLETIN_KEY,rows))return;$('bulletinSearchStatus').textContent='Bulletin reference saved to service order '+order+'. Its applicability status remains exactly as selected; ServicePro has not independently verified it.';renderBulletinRecords()} $('saveBulletinRecord').addEventListener('click',saveBulletinRecord);$('clearBulletinRecord').addEventListener('click',()=>['bulletinNumber','bulletinTitle','bulletinDate','bulletinCoverage','bulletinSource','bulletinNotes'].forEach(id=>$(id).value=''));renderBulletinRecords();$('jobNumber').addEventListener('change',renderBulletinRecords);
☁ ServicePro Cloud (owner-only beta)

Cloud records are separate from local records. Nothing is synchronized automatically. Use test data first.


Create cloud customer


Create cloud appliance


Create cloud service order


Save cloud draft estimate

Draft only. Cloud draft estimates are separate from local estimates. Customer approval is not synchronized yet.



Signed cloud work authorization (typed signature beta)

One authorization per service order. Review the scope and consent before signing. A typed name is treated as an electronic signature in this beta; do not use for real customers until reviewed.



Cloud payment record (manual bookkeeping only)

Records an externally completed payment; does not charge a card. Never enter card numbers, CVV, or bank details.

Show your tech appreciation for an excellent job.



Serial-linked service history


Not signed in.

Owner's authenticated records only. Session tokens are held in memory (sign in again after reload). Testing build: no technician roles, payment processing, photo sync, or automatic local migration. Signed cloud authorizations are now protected from updates and deletion at the database level.