// Paste this file in a standalone Apps Script project owned by the dealership. const properties = PropertiesService.getScriptProperties(); const SITE_ORIGIN = (properties.getProperty('SITE_ORIGIN') || '').trim().replace(/\/$/,''); function bridge(channel, action, data) { if (!/^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::[0-9]{1,5})?$/i.test(SITE_ORIGIN)) { throw new Error('Set SITE_ORIGIN to the dealership’s HTTPS origin without a path.'); } const secret = properties.getProperty('BRIDGE_KEY'); if (!secret || secret.length < 40) throw new Error('Set this channel’s BRIDGE_KEY in Script Properties first.'); const headers = {Authorization: 'Bearer ' + secret, 'X-MVE-Channel': channel}; const response = UrlFetchApp.fetch(SITE_ORIGIN + '/api/google/bridge/' + action,{ method:'post',contentType:'application/json',headers,payload:JSON.stringify(data),muteHttpExceptions:true,followRedirects:false }); const status = response.getResponseCode(); if (status < 200 || status >= 300) throw new Error('CRM '+action+' returned '+status+'. Review account permissions or refresh the ticket before retrying.'); try { return JSON.parse(response.getContentText()); } catch (error) {throw new Error('CRM returned an unexpected response. Confirm SITE_ORIGIN and the bridge route on the dealership server.'); } } function googleApi(url,method,body) { const options={method:method||'get',headers:{Authorization:'Bearer '+ScriptApp.getOAuthToken()},muteHttpExceptions:true,followRedirects:false}; if(body) {options.contentType='application/json';options.payload=JSON.stringify(body);} const response=UrlFetchApp.fetch(url,options); if(response.getResponseCode()<200||response.getResponseCode()>=300)throw new Error('Google API returned '+response.getResponseCode()+'. Check scopes, API enablement and quotas.'); return JSON.parse(response.getContentText()||'{}'); } function createTimer(handler) { if (!ScriptApp.getProjectTriggers().some(t=>t.getHandlerFunction()===handler)) ScriptApp.newTrigger(handler).timeBased().everyMinutes(10).create(); } function withLock(fn) { const lock=LockService.getScriptLock(); if(!lock.tryLock(20000))return; try{return fn();}finally{lock.releaseLock();} }