/** * OTA CHECKER — Google Maps link → OTA listings + prices * Data source: SerpApi Google Hotels engine (https://serpapi.com) * * Sheets used: * Hotels → paste Google Maps links in column A * OTA Detail → one row per OTA per hotel (for filtering and comparisons) * Settings → check-in offset, nights, adults, currency, country */ const SHEET_MAIN ='Hotels'; const SHEET_DETAIL ='OTA Detail'; const SHEET_SETTINGS ='Settings'; const MAX_RUN_MS = 5 * 60 * 1000; // stop before Apps Script's 6-minute limit const MAIN_HEADERS = [ 'Google Maps Link', 'Hotel Name + City (optional override)', 'Status', 'Matched Hotel', 'Rating', 'Reviews', 'No. of OTAs', 'OTAs & Prices (per night)', 'Lowest Price', 'Cheapest On', 'Direct / Official Price', 'Direct vs Lowest', 'Check-in', 'Checked At' ]; const DETAIL_HEADERS = [ 'Matched Hotel', 'Maps Link', 'Source', 'Official Site?', 'Price / Night', 'Before Taxes', 'Check-in', 'Checked At' ]; function onOpen() { SpreadsheetApp.getUi().createMenu('OTA Checker') .addItem('1. Set up sheets', 'setupSheets') .addItem('2. Save SerpApi key', 'saveApiKey') .addSeparator() .addItem('Check new links', 'checkNewRows') .addItem('Re-check selected rows', 'checkSelectedRows') .addItem('Re-check all rows', 'checkAllRows') .addToUi(); } function setupSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const main = ss.getSheetByName(SHEET_MAIN) || ss.insertSheet(SHEET_MAIN); main.getRange(1, 1, 1, MAIN_HEADERS.length).setValues([MAIN_HEADERS]) .setFontWeight('bold').setBackground('#1f3b57').setFontColor('#ffffff'); main.setFrozenRows(1); main.setColumnWidth(1, 260); main.setColumnWidth(2, 220); main.setColumnWidth(8, 380); main.getRange('H:H').setWrap(true); main.getRange('I:I').setNumberFormat('#,##0'); main.getRange('K:K').setNumberFormat('#,##0'); const detail = ss.getSheetByName(SHEET_DETAIL) || ss.insertSheet(SHEET_DETAIL); detail.getRange(1, 1, 1, DETAIL_HEADERS.length).setValues([DETAIL_HEADERS]) .setFontWeight('bold').setBackground('#1f3b57').setFontColor('#ffffff'); detail.setFrozenRows(1); detail.getRange('E:F').setNumberFormat('#,##0'); const settings = ss.getSheetByName(SHEET_SETTINGS) || ss.insertSheet(SHEET_SETTINGS); settings.getRange('A1:B6').setValues([ ['Setting', 'Value'], ['Check-in (days from today)', 1], ['Nights', 1], ['Adults', 2], ['Currency', 'INR'], ['Country code (gl)', 'in'] ]); settings.getRange('A1:B1').setFontWeight('bold'); settings.setColumnWidth(1, 220); SpreadsheetApp.getUi().alert('Sheets are ready. Next: OTA Checker → 2. Save SerpApi key.'); } function saveApiKey() { const ui = SpreadsheetApp.getUi(); const res = ui.prompt('SerpApi key', 'Paste your SerpApi API key:', ui.ButtonSet.OK_CANCEL); if (res.getSelectedButton() !== ui.Button.OK) return; const key = res.getResponseText().trim(); if (!key) return ui.alert('No key entered.'); PropertiesService.getScriptProperties().setProperty('SERPAPI_KEY', key); ui.alert('Key saved. Paste Maps links in the Hotels sheet, then click "Check new links".'); } function checkNewRows() { const sh = getMainSheet_(); const last = sh.getLastRow(); if (last < 2) return toast_('No links found.'); const vals = sh.getRange(2, 1, last - 1, 3).getValues(); const rows = []; vals.forEach((r, i) => { if ((r[0] || r[1]) && !r[2]) rows.push(i + 2); }); runRows_(rows); } function checkSelectedRows() { const sh = getMainSheet_(); const range = sh.getActiveRange(); const rows = []; for (let r = range.getRow(); r < range.getRow() + range.getNumRows(); r++) { if (r >= 2) rows.push(r); } runRows_(rows); } function checkAllRows() { const sh = getMainSheet_(); const rows = []; for (let r = 2; r <= sh.getLastRow(); r++) rows.push(r); runRows_(rows); } function runRows_(rows) { const apiKey = PropertiesService.getScriptProperties().getProperty('SERPAPI_KEY'); if (!apiKey) return SpreadsheetApp.getUi().alert('Save your SerpApi key first (OTA Checker → 2).'); if (!rows.length) return toast_('Nothing to check.'); const sh = getMainSheet_(); const settings = readSettings_(); const start = Date.now(); let done = 0; for (const row of rows) { if (Date.now() - start > MAX_RUN_MS) { toast_('Time limit reached. Run "Check new links" again to continue.'); break; } sh.getRange(row, 3).setValue('Checking…'); SpreadsheetApp.flush(); processRow_(sh, row, settings, apiKey); done++; } toast_('Done: ' + done + ' row(s) checked.'); } function processRow_(sh, row, settings, apiKey) { const link = String(sh.getRange(row, 1).getValue() || '').trim(); const override = String(sh.getRange(row, 2).getValue() || '').trim(); if (!link && !override) return; const dates = getDates_(settings); const now = new Date(); try { const name = override || getNameFromMapsLink_(link); if (!name) throw new Error('Could not read hotel name from link. Type "Hotel Name, City" in column B.'); const baseParams = { q: name, check_in_date: dates.checkIn, check_out_date: dates.checkOut, adults: settings.adults, currency: settings.currency, gl: settings.gl, hl: 'en' }; const prop = findProperty_(baseParams, apiKey); const prices = collectPrices_(prop); const sym = settings.currency ==='INR' ? '₹' : settings.currency + ' '; const priced = prices.filter(p => p.price != null); const lowest = priced.length ? priced[0] : null; const direct = prices.find(p => p.official) || null; let gap ='No direct price on Google'; if (direct && direct.price != null && lowest) { const diff = direct.price - lowest.price; if (diff > 0) gap ='Direct is ' + sym + fmt_(diff) + ' higher than ' + lowest.source; else if (diff === 0) gap ='Direct matches lowest price'; else gap ='Direct is the cheapest'; } else if (direct) { gap ='Direct listed, no price shown'; } const summary = prices.map(p => p.source + (p.official ? ' (Official)' : '') + ': ' + (p.price != null ? sym + fmt_(p.price) : 'price not shown') ).join('\n'); sh.getRange(row, 3, 1, 12).setValues([[ prices.length ? 'OK' : 'Found hotel, but no OTA prices for these dates', prop.name || name, prop.overall_rating || '', prop.reviews || '', prices.length, summary || '—', lowest ? lowest.price : '', lowest ? lowest.source : '', direct && direct.price != null ? direct.price : '', gap, dates.checkIn, now ]]); if (prices.length) { const detail = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_DETAIL); const out = prices.map(p => [ prop.name || name, link, p.source, p.official ? 'Yes' : 'No', p.price != null ? p.price : '', p.beforeTax != null ? p.beforeTax : '', dates.checkIn, now ]); detail.getRange(detail.getLastRow() + 1, 1, out.length, out[0].length).setValues(out); } } catch (e) { sh.getRange(row, 3).setValue('Error: ' + e.message); sh.getRange(row, 14).setValue(now); } } /** Returns a single hotel's details (with prices) from Google Hotels. */ function findProperty_(baseParams, apiKey) { const data = serpSearch_(Object.assign({}, baseParams), apiKey); if (data.name && (data.prices || data.featured_prices)) return data; if (data.properties && data.properties.length) { const top = data.properties[0]; if (top.property_token) { try { const details = serpSearch_(Object.assign({}, baseParams, { property_token: top.property_token }), apiKey); if (details && details.name) return details; } catch (e) { /* fall back to the list result */ } } return top; } throw new Error('Hotel not found on Google Hotels. Try "Hotel Name, City" in column B.'); } /** Merges featured_prices + prices, one entry per source, sorted cheapest first. */ function collectPrices_(prop) { const all = [].concat(prop.featured_prices || [], prop.prices || []); const hotelName = norm_(prop.name || ''); const bySource = {}; all.forEach(x => { if (!x || !x.source) return; const rate = x.rate_per_night || {}; let price = num_(rate.extracted_lowest); let beforeTax = num_(rate.extracted_before_taxes_fees); if (price == null && Array.isArray(x.rooms)) { x.rooms.forEach(room => { const rp = num_((room.rate_per_night || {}).extracted_lowest); if (rp != null && (price == null || rp < price)) price = rp; }); } const official = !!x.official || (hotelName && norm_(x.source) === hotelName); const key = norm_(x.source); const prev = bySource[key]; if (!prev) { bySource[key] = { source: x.source, price: price, beforeTax: beforeTax, official: official }; } else { if (price != null && (prev.price == null || price < prev.price)) { prev.price = price; prev.beforeTax = beforeTax; } prev.official = prev.official || official; } }); return Object.keys(bySource).map(k => bySource[k]).sort((a, b) => { if (a.price == null) return 1; if (b.price == null) return -1; return a.price - b.price; }); } function serpSearch_(params, apiKey) { params.engine ='google_hotels'; params.api_key = apiKey; const qs = Object.keys(params) .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])) .join('&'); const res = UrlFetchApp.fetch('https://serpapi.com/search.json?' + qs, { muteHttpExceptions: true }); let data; try { data = JSON.parse(res.getContentText()); } catch (e) { throw new Error('SerpApi returned an unreadable response (HTTP ' + res.getResponseCode() + ')'); } if (data.error) throw new Error(data.error); return data; } /** Reads the hotel name from a full or short (maps.app.goo.gl) Google Maps link. */ function getNameFromMapsLink_(url) { if (!url) return ''; let current = url; for (let i = 0; i < 6; i++) { if (/\/place\//.test(current)) break; const consent = current.match(/consent\.google\.[^?]+\?.*continue=([^&]+)/); if (consent) { current = decodeURIComponent(consent[1]); continue; } const q = current.match(/[?&]q=([^&]+)/); if (q && !/^-?\d+(\.\d+)?,/.test(decodeURIComponent(q[1]))) break; const res = UrlFetchApp.fetch(current, { followRedirects: false, muteHttpExceptions: true }); const h = res.getAllHeaders(); let loc = h['Location'] || h['location']; if (!loc) break; current = Array.isArray(loc) ? loc[0] : loc; } let m = current.match(/\/place\/([^\/@?]+)/); if (m) return clean_(m[1]); m = current.match(/[?&]q=([^&]+)/); if (m) { const val = clean_(m[1]); if (!/^-?\d+(\.\d+)?,/.test(val)) return val; } return ''; } function readSettings_() { const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_SETTINGS); const v = sh ? sh.getRange('B2:B6').getValues().map(r => r[0]) : []; return { offset: Number(v[0]) >= 0 && v[0] !=='' ? Number(v[0]) : 1, nights: Number(v[1]) || 1, adults: Number(v[2]) || 2, currency: String(v[3] || 'INR').toUpperCase(), gl: String(v[4] || 'in').toLowerCase() }; } function getDates_(s) { const tz = Session.getScriptTimeZone(); const ci = new Date(); ci.setDate(ci.getDate() + s.offset); const co = new Date(ci); co.setDate(co.getDate() + s.nights); return { checkIn: Utilities.formatDate(ci, tz, 'yyyy-MM-dd'), checkOut: Utilities.formatDate(co, tz, 'yyyy-MM-dd') }; } function getMainSheet_() { const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_MAIN); if (!sh) throw new Error('Run "1. Set up sheets" first.'); return sh; } function clean_(s) { return decodeURIComponent(String(s).replace(/\+/g, ' ')).trim(); } function norm_(s) { return String(s).toLowerCase().replace(/[^a-z0-9]/g, ''); } function num_(v) { return (v === undefined || v === null || v ==='' || isNaN(Number(v))) ? null : Number(v); } function fmt_(n) { return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function toast_(msg) { SpreadsheetApp.getActiveSpreadsheet().toast(msg, 'OTA Checker', 6); }