// 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('
'))+'
'+ (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()} }