/** @OnlyCurrentDoc */ // Bind to the private Curb Paint Co - TEST Orders spreadsheet. // Cloudflare holds ORDER_EXPORT_TOKEN as a secret. Script Properties holds the same // read-only credential. No payment credentials or customer status tokens are used. const ORDER_HEADERS=['Order ID','Ordered (Pacific)','Customer','Street address','City','ZIP','Email','Phone','Total (USD)','Payment method','Payment status','Job status','Consent','Coupon','Updated (Pacific)','Processor reference','Campaign','Test order','Order notes','My notes']; function onOpen(){SpreadsheetApp.getUi().createMenu('Curb Paint Co TEST').addItem('Connect orders','connectOrders').addItem('Sync now','syncOrders').addItem('Stop automatic sync','stopOrderSync').addToUi();} function connectOrders(){ if(!/TEST/.test(SpreadsheetApp.getActiveSpreadsheet().getName()))throw Error('Use a separate spreadsheet with TEST in its name.'); const ui=SpreadsheetApp.getUi(),r=ui.prompt('Connect orders','Enter the test order-sync key from curbpaintco.com/dev/admin. Do not use the live key.',ui.ButtonSet.OK_CANCEL); if(r.getSelectedButton()!==ui.Button.OK)return; const token=r.getResponseText().trim();if(token.length<32)throw Error('Use the complete order-sync key.'); PropertiesService.getScriptProperties().setProperties({ORDER_EXPORT_TOKEN:token,ORDER_SHEET_ID:SpreadsheetApp.getActiveSpreadsheet().getId()}); syncOrders(); stopOrderSync();ScriptApp.newTrigger('syncOrders').timeBased().everyMinutes(5).create(); SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Orders').getRange('B2').setValue('Connected. Automatic updates every 5 minutes.'); } function stopOrderSync(){for(const trigger of ScriptApp.getProjectTriggers())if(trigger.getHandlerFunction()==='syncOrders')ScriptApp.deleteTrigger(trigger);SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Orders')?.getRange('B2').setValue('Automatic updates stopped. Use Sync now to refresh.');} function literal(value){const s=String(value??'');return /^[=+\-@\t\r\n]/.test(s)?"'"+s:s;} function orderValues(o){ const date=value=>value?Utilities.formatDate(new Date(value),'America/Los_Angeles','yyyy-MM-dd HH:mm:ss'):''; return [o.id,date(o.created_at),o.name,o.street,o.city,o.zip,o.email,o.phone,o.total_cents/100,o.payment_method,o.payment_status,o.job_status,o.consent_status,o.coupon,date(o.updated_at),o.processor_reference,o.campaign,o.test_order?'Yes':'No',o.notes].map((v,i)=>i===8?v:literal(v)); } function syncOrders(){ const lock=LockService.getScriptLock();if(!lock.tryLock(1000))return; let sheet; try{ const props=PropertiesService.getScriptProperties(),token=props.getProperty('ORDER_EXPORT_TOKEN'),id=props.getProperty('ORDER_SHEET_ID'); if(!token||!id)throw Error('Connect orders first.'); const book=SpreadsheetApp.getActiveSpreadsheet();if(!/TEST/.test(book.getName()))throw Error('Use the TEST orders spreadsheet only.');if(book.getId()!==id)throw Error('This script is connected to a different spreadsheet.'); sheet=book.getSheetByName('Orders');if(!sheet)throw Error('Orders tab is missing.'); const headers=sheet.getRange(5,1,1,ORDER_HEADERS.length).getValues()[0]; if(headers.some((x,i)=>x!==ORDER_HEADERS[i]))throw Error('Order column headers changed. Restore the original headers before syncing.'); let cursor=null,snapshot='',orders=[],seen=new Set(); for(let page=0;page<50;page++){ let url='https://curbpaintco.com/dev/api/integrations/orders'; if(snapshot)url+='?snapshot='+encodeURIComponent(snapshot)+'&after_date='+encodeURIComponent(cursor.after_date)+'&after_id='+encodeURIComponent(cursor.after_id); const response=UrlFetchApp.fetch(url,{headers:{Authorization:'Bearer '+token},muteHttpExceptions:true,followRedirects:false}); if(response.getResponseCode()!==200)throw Error('Order connection returned HTTP '+response.getResponseCode()+'. Existing rows have been kept.'); const data=JSON.parse(response.getContentText());if(data.schema_version!==1||!Array.isArray(data.orders)||!data.snapshot)throw Error('Unexpected order response.'); if(snapshot&&snapshot!==data.snapshot)throw Error('Order snapshot changed during synchronization.');snapshot=data.snapshot; for(const o of data.orders){if(o.test_order!==true)throw Error('Live order received by test sync. No rows were changed.');if(!/^CPC-[A-Za-z0-9-]{1,46}$/.test(o.id)||!Number.isSafeInteger(o.total_cents)||seen.has(o.id))throw Error('Order data could not be verified.');seen.add(o.id);orders.push(o);} cursor=data.next_cursor;if(!cursor)break;if(page===49)throw Error('Order list exceeds sync limit. Existing rows have been kept.'); } const count=Math.max(0,sheet.getLastRow()-5),existing=count?sheet.getRange(6,1,count,ORDER_HEADERS.length).getValues():[],rows=new Map(); for(let i=0;irow.slice(0,19))); sheet.getRange(6,9,existing.length,1).setNumberFormat('$0.00'); } const filter=sheet.getFilter(),criteria=[]; if(filter){for(let c=1;c<=ORDER_HEADERS.length;c++)criteria.push(filter.getColumnFilterCriteria(c));filter.remove();} const nextFilter=sheet.getRange(5,1,Math.max(2,existing.length+1),ORDER_HEADERS.length).createFilter(); for(let c=0;ctrigger.getHandlerFunction()==='syncOrders'); sheet.getRange('B2').setValue(automatic?'Connected. Automatic updates every 5 minutes.':'Connected. Manual sync only.'); sheet.getRange('B3').setValue(Utilities.formatDate(new Date(),'America/Los_Angeles','yyyy-MM-dd HH:mm:ss')); }catch(e){if(sheet)sheet.getRange('B2').setValue('Sync needs attention. Existing orders have been kept.');throw e;} finally{lock.releaseLock();} }