How We Built a Zero-CASA Competitor Price, Stock & App-Stack Tracker Inside Google Sheets™ (Cloudflare Workers + Pure HTTP)

2026-12-05来源 dev.toEnglish

E-commerce operators, agencies, and merchandising teams almost always end up analyzing competitor pricing and inventory inside spreadsheets. Yet most storefront monitoring tools force a bad trade-off: either export static CSV files that go stale overnight, pay per-seat SaaS fees for a dashboard nobody opens daily, or install legacy Google Workspace add-ons requesting overly broad Google Drive and Gmail OAuth scopes.

When we engineered StorePulse—now live on the Google Workspace Marketplace—we designed around two strict constraints:

  1. Zero-CASA Minimal OAuth Footprint: Never request Gmail™ or Google Drive™ scopes, keep every sync strictly inside the active spreadsheet, and pass Google OAuth + Marketplace review cleanly without invasive permissions.
  2. Pure-HTTP Multi-Platform Extraction at the Edge: Run normalized catalog parsing, 7-type commercial change diffing, and Slack/Discord webhook alerting on Cloudflare Workers with zero headless browsers.

Here is how the architecture works under the hood.

1. Zero-CASA 4-Scope Apps Script Manifest

A common mistake when building Google Sheets™ add-ons is adding Drive-wide or Gmail-send scopes "just in case." Restricted Google scopes trigger expensive annual Tier-2 CASA security assessments and raise immediate red flags for security-conscious B2B teams.

StorePulse intentionally locks its appsscript.json manifest to four narrowly scoped permissions—zero Gmail access and zero Google Drive access:

{ "timeZone": "Etc/UTC", "dependencies": {}, "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.container.ui", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/script.scriptapp" ] } 

On spreadsheet open, onOpen(e) runs safely under AuthMode.NONE (completing in ~0.34s in our automated verification harness) so menu registration never throws authorization errors before the user explicitly opens the sidebar.

Instead of dumping ephemeral data onto one sheet, initializing the workbook creates a 4-tab longitudinal schema:

Tab Role
Tracked Stores Target URLs, platform detection (shopify, woocommerce, generic), last sync UTC timestamp, and active SKU counts
Live Catalog Latest normalized product rows (SKU, handle, price, compare-at price, discount %, stock flag, vendor, product type)
Change Alerts Append-only commercial event feed covering price edits, stockouts, restocks, new arrivals, and storefront app changes
Price History Timestamped UTC snapshots for native Sheets charts, promo tracking, and margin modeling

2. Multi-Platform Pure-HTTP Catalog Router & Stable Product Keys

Merchants rarely monitor just one platform. A single agency workbook frequently mixes Shopify storefronts, WooCommerce shops, and custom independent DTC sites.

Our Cloudflare Worker (storepulse-api) routes each public storefront URL through three pure-HTTP parsers with safe redirect guards:

  • Shopify Engine: Inspects public /products.json catalog endpoints plus storefront HTML fingerprints for installed apps and analytics scripts.
  • WooCommerce Engine: Queries public WooCommerce Store API product payloads alongside theme/plugin markers.
  • Generic JSON-LD Engine: Extracts structured Schema.org Product and Offer JSON-LD blocks from independent storefronts when neither Shopify nor WooCommerce is detected.

To diff snapshots reliably across heterogeneous platforms—even when a merchant omits SKUs or changes URL query parameters—every product passes through buildStableProductKey() and normalizeUnifiedProducts() in engines/router.js:

export function buildStableProductKey(product = {}) { const sku = typeof product.sku === 'string' || typeof product.sku === 'number' ? String(product.sku).trim() : ''; if (sku) return sku.toLowerCase(); const handle = typeof product.handle === 'string' ? product.handle.trim() : ''; if (handle) return handle.toLowerCase(); if (typeof product.url === 'string' && product.url.trim()) { try { const parsed = new URL(product.url.trim()); const cleanPath = parsed.pathname.replace(/\/+$/, '').trim(); if (cleanPath && cleanPath !== '/') { return cleanPath.toLowerCase(); } } catch { // ignore invalid url } } return String(product.title || '').trim().toLowerCase().replace(/\s+/g, ' ') || 'item'; } 

When duplicate keys appear within a single catalog pull (for example, un-SKU'd variants sharing a title), normalizeUnifiedProducts() deterministically suffixes collisions (#2, #3) and validates compareAtPrice > price before calculating discountPct so stale compare-at values never produce negative discounts.

3. Noise-Free 7-Type Commercial Diff Engine

Raw catalog diffs are notoriously noisy. Currency rounding glitches or first-run imports can flood a team's Slack channel with hundreds of useless rows.

In worker/src/diff.js, computeStoreDiff() evaluates exactly 7 structured commercial alert types:

  • PRICE_DROP and PRICE_INCREASE
  • OUT_OF_STOCK and BACK_IN_STOCK
  • NEW_PRODUCT
  • APP_ADDED and APP_REMOVED

Two small guardrails dramatically improve signal-to-noise ratio in production:

  1. First-Run Baseline Safeguard: If previousSnapshot has no product or app baseline yet, the engine returns { alerts: [], baselineInitialized: true } instead of spamming NEW_PRODUCT alerts for every existing SKU.
  2. Minimum Price-Change Threshold: By default, priceChangeMinPct defaults to 0.5%, filtering out trivial FX cent jitter while immediately catching real markdowns, flash sales, and MAP violations.
export function computeStoreDiff(previousSnapshot, currentSnapshot, options = {}) { const minPct = Number.isFinite(Number(options.priceChangeMinPct)) ? Math.max(0, Number(options.priceChangeMinPct)) : 0.5; if (!previousSnapshot || typeof previousSnapshot !== 'object') { return { alerts: [], summary: createEmptySummary(), baselineInitialized: true }; } // Maps previous SKUs by normalized stable key and emits typed price/stock/app events } 

Scheduled refreshes (daily on Starter, every 6 hours on Growth/Agency) compare the latest snapshot against the stored baseline and optionally deliver concise summaries directly to Slack or Discord webhooks.

4. Security Hygiene, Zero-PII Collection & Print-Ready Executive Packets

Running a public storefront checker on Cloudflare Workers requires defensive engineering from day one:

  • SSRF & Redirect Protection: Every outbound fetch validates public HTTP/HTTPS origins and blocks private/loopback/metadata IP ranges across redirect hops.
  • Zero Personal Data Scraping: StorePulse strictly extracts public commercial catalog data (titles, prices, availability, storefront tech tags)—never customer emails, phone numbers, or personal profiles.
  • AUP & Rate Limits: Public instant checks (GET /api/public/check?url=...) enforce per-IP hourly rate limits and deterministic Acceptable Use Policy checks (aup.js) plus 64-character SHA-256 snapshot fingerprints.
  • US Letter & A4 Executive Reports: Agencies can generate zero-CDN, XSS-escaped printable HTML executive assortment reports (POST /api/report/packet) using adaptive @page { size: auto; margin: 12mm; } CSS with custom white-label headers—rendering cleanly on both US Letter and A4 paper without external PDF SaaS dependencies.

Try It Live (Zero Credit Card Required)

If you have built spreadsheet-native monitoring pipelines or hit weird Shopify/WooCommerce catalog edge cases, I would love to hear how you handled SKU key normalization in the comments.

原文:https://www.a8q9.cn/en/article/how-we-built-a-zero-casa-competitor-price-stock-app-stack-tracker-inside-google--228ac9.html

相关文章