const MAILBOXES=['majorvehicles@gmail.com','greatbusesforsale@gmail.com']; const GMAIL='https://gmail.googleapis.com/gmail/v1/users/me'; function mailbox(){ const me=(Session.getEffectiveUser().getEmail()||'').trim().toLowerCase(); if(!MAILBOXES.includes(me))throw new Error('Sign in to this script as one of the two sales mailboxes.'); return me; } function installMail(){ const me=mailbox(); // Test the connection before installing the trigger. Install time is the start of tracking. bridge(me,'notice',{since:new Date().toISOString(),after:''}); googleApi(GMAIL+'/profile'); if(!properties.getProperty('MAIL_SINCE'))properties.setProperty('MAIL_SINCE',String(Math.floor(Date.now()/1000))); if(!properties.getProperty('NOTICE_SINCE'))properties.setProperty('NOTICE_SINCE',new Date().toISOString()); createTimer('syncMail'); syncMail(); } function emails(text){return (String(text||'').match(/[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi)||[]).map(x=>x.toLowerCase());} function textBody(part) { if(part.mimeType==='text/plain' && part.body && part.body.data) return Utilities.newBlob(Utilities.base64DecodeWebSafe(part.body.data)).getDataAsString('UTF-8').slice(0,32000); for(const child of part.parts||[]){const t=textBody(child);if(t)return t;} return ''; } function alertSales(me) { const active=properties.getProperty('SEND_STAFF_NOTICES')==='yes'; if(!active)return; const response=bridge(me,'notice',{since:properties.getProperty('NOTICE_SINCE'),after:properties.getProperty('NOTICE_ID')||''}); for(const t of response.rows){ // Staff receive their own alert. Reply-To addresses the buyer if the inquiry has an email. const msg={to:me,subject:'[MVE Ticket #'+t.ticket_number+'] '+(t.stock||t.vehicle||'Bus inquiry'),body: [t.name,t.email,t.phone,t.stock,t.vehicle,'',t.question,'',SITE_ORIGIN+'/sales/staff.html'].filter(Boolean).join('\n')}; if(t.email)msg.replyTo=t.email; MailApp.sendEmail(msg); properties.setProperties({NOTICE_SINCE:t.created_at,NOTICE_ID:t.id}); } } function syncMail(){withLock(()=>{ const me=mailbox(); if(!properties.getProperty('MAIL_SINCE'))throw new Error('Run installMail first.'); alertSales(me); // Pin the window while paging so a busy inbox is resumed on the next run. const since=Number(properties.getProperty('MAIL_SINCE')); const end=Number(properties.getProperty('MAIL_UNTIL')||Math.floor(Date.now()/1000)); properties.setProperty('MAIL_UNTIL',String(end)); const params='?maxResults=40&q='+encodeURIComponent('subject:MVE after:'+Math.max(0,since-120)+' before:'+(end+1)); const pageToken=properties.getProperty('MAIL_PAGE'); const page=googleApi(GMAIL+'/messages'+params+(pageToken?'&pageToken='+encodeURIComponent(pageToken):'')); for(const item of page.messages||[]){ const m=googleApi(GMAIL+'/messages/'+encodeURIComponent(item.id)+'?format=full'); if(m.labelIds && (m.labelIds.includes('DRAFT')||m.labelIds.includes('TRASH')||m.labelIds.includes('SPAM')))continue; const headers=Object.fromEntries((m.payload.headers||[]).map(x=>[x.name.toLowerCase(),x.value])); const subject=headers.subject||'', ids=subject.toUpperCase().match(/\b(?:MVE-[0-9A-F]{16}|MVE TICKET #\d+)\b/g)||[]; if(new Set(ids).size!==1||headers['auto-submitted'] && headers['auto-submitted'].toLowerCase()!=='no')continue; const sender=emails(headers.from)[0],recipients=emails([headers.to,headers.cc,headers['delivered-to']].join(',')); if(sender===me && recipients.every(x=>x===me))continue; bridge(me,'import',{ticket:ids[0],message:m.id,rfcId:headers['message-id']||'',subject:subject.slice(0,1000),sender,recipients,body:textBody(m.payload)||m.snippet||'',date:new Date(Number(m.internalDate)).toISOString()}); } if(page.nextPageToken)properties.setProperty('MAIL_PAGE',page.nextPageToken); else{ properties.setProperty('MAIL_SINCE',String(end));properties.deleteProperty('MAIL_PAGE');properties.deleteProperty('MAIL_UNTIL'); bridge(me,'heartbeat',{noticesEnabled:properties.getProperty('SEND_STAFF_NOTICES')==='yes'}); } });}