// Paramount Home Services: one-way app -> Requests tab. // Set SHEETS_SYNC_SECRET in Project Settings > Script properties. // Deploy as a Web app, execute as Me, access Anyone. Signed POSTs only. // The spreadsheet itself stays private. Do not manually edit Requests. const TRACKER_ID='1L8vIjme0LdjocEDfiLEspKVzSsOZKdcqqOOG0I3K1_A'; const ALERT_EMAIL='phswqmv@gmail.com'; const OWNER_INBOX='https://paramount-home-services-jh.poetic-river-6318.chatgpt.site/#owner'; function authorizeParamount() { const book=SpreadsheetApp.openById(TRACKER_ID); if(!book.getSheetByName('Requests'))throw new Error('Requests tab missing.'); } // Run once after installing this version, before updating the deployment. // Existing synced requests become the baseline; they do not generate old alerts. function enableParamountAlerts(){ MailApp.getRemainingDailyQuota(); // Requests Google's send-mail permission. const lock=LockService.getScriptLock();lock.waitLock(20000); try{ const props=PropertiesService.getScriptProperties(); if(props.getProperty('ALERTS_ENABLED')==='true')return; const sheet=SpreadsheetApp.openById(TRACKER_ID).getSheetByName('Requests'); if(!sheet)throw Error('Requests tab missing'); const entries={};sheet.getRange(2,1,500,1).getValues().forEach(row=>{if(row[0])entries['ALERT_KNOWN_'+row[0]]='1'}); props.setProperties(entries);props.setProperty('ALERTS_ENABLED','true'); }finally{lock.releaseLock()} } function alertStatus_(props,rows){ if(props.getProperty('ALERTS_ENABLED')!=='true')return {status:'disabled',pending:0}; const pending=rows.filter(row=>!props.getProperty('ALERT_KNOWN_'+row[0])); let sent=0,error=false; try{ let quota=MailApp.getRemainingDailyQuota(); for(const row of pending.slice(0,10)){ if(quota<1)break; const name=String(row[3]).replace(/[\r\n]/g,' ').slice(0,120); const body=['A new Paramount service request is ready for review.','', 'Customer: '+name,'Phone: '+row[18],'Email: '+row[19], 'Service address: '+row[5],'Services: '+row[6], 'Preferred visit: '+row[9]+' · '+row[10]+' Central Time', 'Customer notes: '+String(row[17]).slice(0,2000),'', 'Request reference: '+row[0],'Open your owner inbox: '+OWNER_INBOX,'', 'This is a request, not a confirmed appointment. Review the photos in the app.'].join('\n'); MailApp.sendEmail({to:ALERT_EMAIL,subject:'New Paramount service request — '+name,body:body,name:'Paramount Home Services'}); props.setProperty('ALERT_KNOWN_'+row[0],'1');sent++;quota--; } }catch(err){error=true} const remaining=pending.length-sent; return {status:error?'failed':remaining?'pending':'ready',pending:remaining}; } // Customer emails: durable per-job reservation prevents duplicate sends, even // when Google accepts an email but the HTTP response or following write fails. function validReviewUrl_(url){return typeof url==='string'&&url.length<=2000&&/^https:\/\/(g\.page|search\.google\.com|www\.google\.com|google\.com|maps\.google\.com|maps\.app\.goo\.gl)\//i.test(url);} function thanksStatus_(props){ const all=props.getProperties();let sent=0,review=0,skipped=0; Object.keys(all).filter(k=>k.indexOf('THANKS_JOB_')===0).forEach(k=>{if(all[k]==='sent')sent++;else if(all[k]==='reserved'||all[k]==='needs_review')review++;else if(all[k]==='skipped')skipped++}); return {status:props.getProperty('THANKS_ENABLED')==='true'?'enabled':'paused',reviewUrl:props.getProperty('THANKS_REVIEW_URL')||'',sent:sent,needsReview:review,skipped:skipped,pending:Number(props.getProperty('THANKS_PENDING')||0),reviewJobs:Object.keys(all).filter(k=>k.indexOf('THANKS_JOB_')===0&&(all[k]==='reserved'||all[k]==='needs_review')).map(k=>k.slice(11))}; } function validateArchived_(jobs){ if(!Array.isArray(jobs)||jobs.length>500)throw Error('Invalid archived jobs'); const ids=new Set();jobs.forEach(j=>{if(!j||typeof j.id!=='string'||!/^[A-Za-z0-9-]{1,100}$/.test(j.id)||ids.has(j.id)||typeof j.name!=='string'||j.name.length>120||typeof j.email!=='string'||j.email.length>254)throw Error('Invalid archived job');ids.add(j.id)}); } function configureThanks_(props,d){ validateArchived_(d.archived);if(typeof d.enabled!=='boolean'||!validReviewUrl_(d.reviewUrl))throw Error('Invalid customer email settings'); // Every activation skips jobs already archived, including while paused. if(d.enabled&&props.getProperty('THANKS_ENABLED')!=='true'){ MailApp.getRemainingDailyQuota(); const skip={};d.archived.forEach(j=>{const key='THANKS_JOB_'+j.id;if(!props.getProperty(key))skip[key]='skipped'});props.setProperties(skip); } props.setProperty('THANKS_REVIEW_URL',d.reviewUrl);props.setProperty('THANKS_ENABLED',String(d.enabled));props.setProperty('THANKS_PENDING','0');return thanksStatus_(props); } function sendThanks_(props,jobs){ if(props.getProperty('THANKS_ENABLED')!=='true')return thanksStatus_(props); // Older app versions do not provide eligibility. Never infer it from sheet text. if(!Array.isArray(jobs))return thanksStatus_(props); validateArchived_(jobs);const url=props.getProperty('THANKS_REVIEW_URL');if(!validReviewUrl_(url))return {status:'invalid_link'}; const pending=jobs.filter(j=>!props.getProperty('THANKS_JOB_'+j.id));let quota=MailApp.getRemainingDailyQuota(),attempts=0; for(const j of pending){ if(attempts>=10||quota<1)break; const key='THANKS_JOB_'+j.id; if(!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(j.email)){props.setProperty(key,'needs_review');continue} const name=j.name.replace(/[\r\n]/g,' ').trim()||'there'; const body=['Hi '+name+',','','Thank you for choosing Paramount Home Services. I appreciate the opportunity to help with your home. Your job is complete and your final invoice is paid in full.','','If you have a moment, I would appreciate an honest Google review about your experience working with me. Your feedback helps other homeowners get to know Paramount.','','Leave a review: '+url,'','If you have any questions about the work, just reply to this email or call me at 316-210-2520.','','Thanks again,','James Hill','Paramount Home Services','316-210-2520','www.callphsnow.com'].join('\n'); const escape=value=>String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const htmlBody=body.split('\n\n').map(section=>'

'+(section==='Leave a review: '+url?'Google review':section.split('\n').map(line=>line==='www.callphsnow.com'?'www.callphsnow.com':escape(line)).join('
'))+'

').join(''); props.setProperty(key,'reserved');attempts++;quota--; try{MailApp.sendEmail({to:j.email,subject:'Thank you for choosing Paramount Home Services',body:body,htmlBody:htmlBody,name:'James | Paramount Home Services',replyTo:ALERT_EMAIL});props.setProperty(key,'sent')} catch(err){props.setProperty(key,'needs_review')} } props.setProperty('THANKS_PENDING',String(jobs.filter(j=>!props.getProperty('THANKS_JOB_'+j.id)).length));return thanksStatus_(props); } function safeThanks_(props,jobs){try{return sendThanks_(props,jobs)}catch(err){return {status:'failed'}}} function result_(data){return ContentService.createTextOutput(JSON.stringify(data)).setMimeType(ContentService.MimeType.JSON);} function doGet(){return result_({ok:false,error:'Signed POST required.'});} function doPost(e){ let lock; try{ const envelope=JSON.parse(e.postData.contents); const secret=PropertiesService.getScriptProperties().getProperty('SHEETS_SYNC_SECRET'); if(!secret||typeof envelope.payload!=='string'||envelope.payload.length>6000000)throw Error('Unauthorized'); const expected=Utilities.computeHmacSha256Signature(envelope.payload,secret,Utilities.Charset.UTF_8).map(b=>('0'+((b+256)%256).toString(16)).slice(-2)).join(''); let diff=0;const sig=String(envelope.signature||'');if(sig.length!==expected.length)throw Error('Unauthorized'); for(let i=0;i300000)throw Error('Invalid or expired request'); if(d.action==='travel'){ if(typeof d.origin!=='string'||typeof d.destination!=='string'||d.origin.length>300||d.destination.length>300)throw Error('Invalid address'); const directions=Maps.newDirectionFinder().setOrigin(d.origin).setDestination(d.destination).setMode(Maps.DirectionFinder.Mode.DRIVING).setRegion('us').getDirections(); if(directions.status!=='OK'||directions.geocoded_waypoints?.some(x=>x.partial_match))return result_({ok:true,target:TRACKER_ID,status:'pending'}); const legs=directions.routes?.[0]?.legs; if(!legs||legs.length!==1||!Number.isFinite(legs[0].distance?.value))return result_({ok:true,target:TRACKER_ID,status:'pending'}); return result_({ok:true,target:TRACKER_ID,meters:legs[0].distance.value,matchedAddress:legs[0].end_address}); } const book=SpreadsheetApp.openById(TRACKER_ID),sheet=book.getSheetByName('Requests'); if(!sheet)throw Error('Requests tab missing'); if(d.action==='ping')return result_({ok:true,target:TRACKER_ID,customerEmailVersion:1,approvalRemindersEnabled:approvalRemindersEnabled_(),teamMessagesVersion:1,alertsVersion:1,travelVersion:1,thanksVersion:1,thanks:thanksStatus_(PropertiesService.getScriptProperties())}); if(d.action==='customer_email_pdf'){ if(typeof d.html!=='string'||d.html.length>250000)throw Error('Invalid document'); const pdf=Utilities.newBlob(d.html,'text/html','document.html').getAs('application/pdf'); return result_({ok:true,target:TRACKER_ID,pdf:Utilities.base64Encode(pdf.getBytes())}); } if(d.action==='customer_email_send'||d.action==='customer_email_status'){ lock=LockService.getScriptLock();lock.waitLock(20000); return result_(Object.assign({ok:true,target:TRACKER_ID},d.action==='customer_email_send'?customerEmailSend_(book,d):customerEmailStatus_(book,d.id))); } if(d.action==='team_message'){lock=LockService.getScriptLock();lock.waitLock(20000);return result_({ok:true,target:TRACKER_ID,teamMessageStatus:teamMessage_(book,d)});} if(d.action==='configure_thanks'){lock=LockService.getScriptLock();lock.waitLock(20000);return result_({ok:true,target:TRACKER_ID,thanks:configureThanks_(PropertiesService.getScriptProperties(),d)});} if(d.action!=='snapshot'||!Number.isSafeInteger(d.revision)||d.revision<1||!Array.isArray(d.rows)||d.rows.length>500)throw Error('Invalid snapshot'); const ids=new Set(); for(const row of d.rows){if(!Array.isArray(row)||row.length!==20||typeof row[0]!=='string'||!/^[A-Za-z0-9-]{1,100}$/.test(row[0])||ids.has(row[0])||row.some(v=>typeof v!=='string'&&typeof v!=='number'))throw Error('Invalid row');ids.add(row[0]);} lock=LockService.getScriptLock();lock.waitLock(20000); const props=PropertiesService.getScriptProperties(),last=Number(props.getProperty('LAST_REVISION')||0); if(d.revisiontypeof v==='string'&&/^[\s]*[=+@-]/.test(v)?"'"+v:v; const rows=d.rows.map(row=>row.map(safe)); while(rows.length<500)rows.push(Array(20).fill('')); sheet.getRange(2,1,500,20).setValues(rows); const overview=book.getSheetByName('Overview'); if(overview){overview.getRange('A4').setValue('Automatic app → Sheets sync connected. Update requests in the app.');overview.getRange('A18:A24').setValues([['1. Submit requests and manage status, quote, notes, and schedule in the app.'],['2. New submissions and saved changes automatically attempt a sync.'],['3. Check the Google Sheets connection status in the owner inbox.'],['4. If sync fails, changes stay in the app. Use Retry or save another change.'],['5. The app controls Requests. Manual edits here are replaced by the next sync.'],['6. Deleting a request in the app removes it from this tracker on the next sync.'],['7. Capacity: 500 requests. Dates and times are Central Time.']]);} SpreadsheetApp.flush(); props.setProperty('LAST_REVISION',String(d.revision)); return result_({ok:true,target:TRACKER_ID,revision:d.revision,alerts:alertStatus_(props,d.rows),thanks:safeThanks_(props,d.archived)}); }catch(err){return result_({ok:false,error:'Sync failed. Check script settings, permissions, and Requests tab.'});} finally{if(lock&&lock.hasLock())lock.releaseLock();} } // A durable reservation prevents duplicate alerts on connection retries. function teamMessage_(book,d){ if(typeof d.id!=='string'||!/^[a-f0-9-]{36}$/.test(d.id)||typeof d.employee!=='string'||d.employee.length>120||typeof d.customer!=='string'||d.customer.length>200||typeof d.note!=='string'||d.note.length>3000)throw Error('Invalid message'); let log=book.getSheetByName('Team Message Alerts'); if(!log){log=book.insertSheet('Team Message Alerts');log.appendRow(['Message ID','Delivery status','Attempted at']);} const found=log.getRange(1,1,Math.max(log.getLastRow(),1),1).createTextFinder(d.id).matchEntireCell(true).findNext(); if(found)return log.getRange(found.getRow(),2).getValue()==='sent'?'sent':'needs_review'; if(MailApp.getRemainingDailyQuota()<1)return 'pending'; log.appendRow([d.id,'reserved',new Date()]);SpreadsheetApp.flush();const row=log.getLastRow(); try{ MailApp.sendEmail({to:ALERT_EMAIL,subject:'PHS employee message — '+d.employee.replace(/[\r\n]/g,' '),body:[d.employee+' sent you a message.','Job: '+d.customer,'',d.note,d.hasPhoto?'Photo attached — view it securely in the app.':'','Open Employee Messages in your Owners Box: https://callphsnow.com/#owner','Reply in the app so your employee can see it.'].join('\n'),name:'Paramount Home Services'}); log.getRange(row,2).setValue('sent');SpreadsheetApp.flush();return 'sent'; }catch(e){log.getRange(row,2).setValue('needs_review');return 'needs_review';} } // Outbound customer mail: review in the app first; each send ID is reserved once. function enableParamountCustomerEmail(){MailApp.getRemainingDailyQuota();} function customerEmailLog_(book){ let log=book.getSheetByName('Customer Email Log'); if(!log){log=book.insertSheet('Customer Email Log');log.appendRow(['Send ID','Status','Sent at','Payload hash']);SpreadsheetApp.flush();} return log; } function customerEmailStatus_(book,id){ if(typeof id!=='string'||!/^[a-f0-9-]{36}$/.test(id))throw Error('Invalid email ID'); const log=customerEmailLog_(book),found=log.getRange(1,1,Math.max(log.getLastRow(),1),1).createTextFinder(id).matchEntireCell(true).findNext(); if(!found)return {status:'missing'}; return {status:log.getRange(found.getRow(),2).getValue()==='sent'?'sent':'needs_review',sentAt:String(log.getRange(found.getRow(),3).getValue()||'')}; } // Render text safely; apply meaningful labels only to recognized destinations. function phsMailHtml_(body){ const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const re=/(?:https?:\/\/|\bwww\.)[^\s<>"']+/gi; let out='',pos=0,m; while((m=re.exec(body))){ out+=esc(body.slice(pos,m.index));pos=re.lastIndex; let raw=m[0],end='';while(/[.,;:!?)]$/.test(raw)){end=raw.slice(-1)+end;raw=raw.slice(0,-1)} let href=/^www\./i.test(raw)?'https://'+raw:raw; const parts=/^https?:\/\/([a-z\d.-]+)(?=\/|[?#]|$)(.*)$/i.exec(href); if(!parts){out+=esc(raw+end);continue} let host=parts[1].toLowerCase(),path=parts[2],label=host; if(/^(www\.)?callphsnow\.com$/.test(host))label=/^\/approve\.html[#?]/.test(path)?'Review your estimate':/\/#owner/.test(path)?'Owners Box':(!path||path==='/')?'www.callphsnow.com':'Open Paramount Home Services'; else if((host==='g.page'&&/\/review(?:[?#/]|$)/i.test(path))||(host==='search.google.com'&&path.includes('/local/writereview')))label='Google review'; else if(host==='venmo.com'&&/^\/u\/James-Hill-4(?:[/?#]|$)/i.test(path))label='Venmo'; else if(host==='cash.app'&&/^\/\$jdhill108(?:[/?#]|$)/i.test(path))label='Cash App'; else if(host==='us-west-2.protection.sophos.com'&&/[?&]u=aHR0cHM6Ly9nLnBhZ2Uvci9DUkg1Z0FGLXBzZmFFQ0UvcmV2aWV3(?:&|$)/.test(path)){href='https://g.page/r/CRH5gAF-psfaECE/review';label='Google review'} out+=''+esc(label)+''+esc(end); } return '

'+ (out+esc(body.slice(pos))).replace(/\r\n?/g,'\n').split(/\n\n+/).map(s=>s.replace(/\n/g,'
')).join('

')+'

'; } function customerEmailSend_(book,d){ if(typeof d.id!=='string'||!/^[a-f0-9-]{36}$/.test(d.id)||typeof d.to!=='string'||d.to.length>254||!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(d.to)||typeof d.subject!=='string'||!d.subject.trim()||d.subject.length>200||/[\r\n]/.test(d.subject)||typeof d.body!=='string'||!d.body.trim()||d.body.length>10000)throw Error('Invalid customer email'); let attachments=[]; if(d.pdf!==null){if(typeof d.pdf!=='string'||d.pdf.length>4000000||!d.pdf.startsWith('JVBER')||typeof d.filename!=='string'||!/^[a-zA-Z0-9_-]+\.pdf$/.test(d.filename))throw Error('Invalid PDF');attachments=[Utilities.newBlob(Utilities.base64Decode(d.pdf),'application/pdf',d.filename)];} const hash=Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256,JSON.stringify([d.to,d.subject,d.body,d.filename,d.pdf]),Utilities.Charset.UTF_8).map(b=>('0'+((b+256)%256).toString(16)).slice(-2)).join(''); const log=customerEmailLog_(book),found=log.getRange(1,1,Math.max(log.getLastRow(),1),1).createTextFinder(d.id).matchEntireCell(true).findNext(); if(found){if(log.getRange(found.getRow(),4).getValue()!==hash)throw Error('Send ID already belongs to another message');return customerEmailStatus_(book,d.id);} if(MailApp.getRemainingDailyQuota()<1)return {status:'pending'}; log.appendRow([d.id,'reserved','',hash]);SpreadsheetApp.flush();const row=log.getLastRow(); try{ MailApp.sendEmail({to:d.to,subject:d.subject,body:d.body,htmlBody:phsMailHtml_(d.body),name:'James | Paramount Home Services',replyTo:ALERT_EMAIL,attachments:attachments}); const sentAt=new Date().toISOString();log.getRange(row,3).setValue(sentAt);log.getRange(row,2).setValue('sent');SpreadsheetApp.flush();return {status:'sent',sentAt:sentAt}; }catch(err){try{log.getRange(row,2).setValue('needs_review');SpreadsheetApp.flush()}catch(_){}return {status:'needs_review'};} } // One-time setup: time-driven trigger checks active holds even with the app closed. function approvalRemindersEnabled_(){ return PropertiesService.getScriptProperties().getProperty('APPROVAL_REMINDERS_ENABLED')==='true'&&ScriptApp.getProjectTriggers().some(t=>t.getHandlerFunction()==='sendParamountApprovalReminders'); } function enableParamountApprovalReminders(){ MailApp.getRemainingDailyQuota(); // Check the signed connection before enabling a recurring trigger. approvalReminderRequest_({action:'queue'}); const existing=ScriptApp.getProjectTriggers().filter(t=>t.getHandlerFunction()==='sendParamountApprovalReminders'); if(!existing.length)ScriptApp.newTrigger('sendParamountApprovalReminders').timeBased().everyMinutes(15).create(); existing.slice(1).forEach(t=>ScriptApp.deleteTrigger(t)); PropertiesService.getScriptProperties().setProperty('APPROVAL_REMINDERS_ENABLED','true'); } function pauseParamountApprovalReminders(){ PropertiesService.getScriptProperties().setProperty('APPROVAL_REMINDERS_ENABLED','false'); ScriptApp.getProjectTriggers().filter(t=>t.getHandlerFunction()==='sendParamountApprovalReminders').forEach(t=>ScriptApp.deleteTrigger(t)); } function approvalReminderRequest_(data){ const secret=PropertiesService.getScriptProperties().getProperty('SHEETS_SYNC_SECRET');if(!secret)throw Error('Missing SHEETS_SYNC_SECRET'); const payload=JSON.stringify(Object.assign({},data,{target:'phs-approval-reminders',sentAt:Date.now()})); const signature=Utilities.computeHmacSha256Signature(payload,secret,Utilities.Charset.UTF_8).map(b=>('0'+((b+256)%256).toString(16)).slice(-2)).join(''); const response=UrlFetchApp.fetch('https://callphsnow.com/api/approval-reminders',{method:'post',contentType:'application/json',payload:JSON.stringify({payload:payload,signature:signature}),muteHttpExceptions:true}); const result=JSON.parse(response.getContentText());if(response.getResponseCode()!==200||!result.ok)throw Error('Could not connect to Paramount reminder service');return result; } function sendParamountApprovalReminders(){ if(PropertiesService.getScriptProperties().getProperty('APPROVAL_REMINDERS_ENABLED')!=='true')return; const lock=LockService.getScriptLock();if(!lock.tryLock(1000))return; try{ const batch=approvalReminderRequest_({action:'queue'}),book=SpreadsheetApp.openById(TRACKER_ID); for(const mail of batch.emails){ // Recheck eligibility immediately before sending; stop completed/cancelled holds. const fresh=approvalReminderRequest_({action:'queue'});if(!fresh.emails.some(m=>m.id===mail.id))continue; const result=customerEmailSend_(book,mail); approvalReminderRequest_({action:'ack',id:mail.id,status:result.status}); } }finally{lock.releaseLock()} }