✕
185K+ D1 Rows · 20 API Endpoints · 18 Tables · 102K Transactions · 280K Research Words · 82 Pitfalls · 60+ Tools · 329 Templates
System Architecture (Source → Extract → Store → Serve → Consume)
GFS Platform Architecture — Source to Delivery
Source
Extract & Sync
Store
Serve
Consume
NetSuite
4656898 · 102K txns
SuiteAPI #2948
RESTlet gateway
MCP Server
Claude ↔ NS
N/llm Module
0 gov units
#2947
SuiteQL
#2949
Toolkit
Chartstone Pro
localhost API · Pro
sync.sh (launchd)
every 15 min · delta SuiteQL
wrangler d1 execute
INSERT OR REPLACE
Worker Crons
*/15 sync · 19:00 report
D1 Database
185K rows · 18 tables
29.6 MB · ENAM/EWR
KV Cache
READY (unused)
R2 Storage
READY (unused)
CF Worker
20 REST endpoints
Auth · CORS · CSP
Custom Domain
api.ai-globalfoodsolutions.co
CF Pages (16)
CDN edge hosting
SuiteAttach
File upload RESTlet
System Guide
pages.dev
Dashboards
Infra + Executive
Power Tools
60+ NS tools
Workers AI
Phase 4
Mobile
All pages responsive
Quick Links
D1 Database — gfs-netsuite · 185K rows · 18 tables 100% SYNCED → Full Wiki
Entities
customers 283
vendors 484
items 1,265
contacts 490
employees 116
Transactions
transactions 102,367
invoice_lines 28,528
so_lines 29,098
vb_lines 21,317
Financial
gl_accounts 152
customer_pricing 1,264
sync_log 59+
Reference (6)
ref_terms 18
ref_departments 14 (brands)
ref_locations 17
ref_categories / classes / shipping 14 / 6 / 7
Transaction Types (20)
Type Name Count Value Entity Lines
CustInvcInvoice 12,542 $169.8M ✓ 100% 28,528
SalesOrdSales Order 12,862 $177.4M ✓ 100% 29,098
VendBillVendor Bill 22,916 $145.0M ✓ 100% 21,317
PurchOrdPurchase Order 11,566 $131.0M ✓ 100% —
CustPymtPayment 8,195 $163.2M ✓ 100% —
VendPymtVendor Payment 9,603 $144.0M ✓ 100% —
ItemShipFulfillment 12,375 — — —
CheckCheck 5,493 $29.1M ✓ —
ItemRcptReceipt 3,491 $51.7M — —
CustCredCredit Memo 932 $2.7M ✓ —
+ 10 more 2,392 $59.1M InvAdjst, WorkOrd, InvWksht, Deposit, VendCred, Build, Journal, InvTrnfr, Unbuild, CustRfnd
Example Queries (D1 SQLite)
Revenue & Sales
-- Top 10 customers by 2026 revenue
SELECT entity_name, COUNT(*) as invs,
ROUND(SUM(foreigntotal),2) as revenue
FROM transactions WHERE type='CustInvc' AND year=2026
GROUP BY entity_name ORDER BY revenue DESC LIMIT 10
-- Monthly revenue trend
SELECT year, CAST(SUBSTR(trandate,1,INSTR(trandate,'/')-1) AS INT) as month,
COUNT(*) as cnt, ROUND(SUM(foreigntotal),2) as rev
FROM transactions WHERE type='CustInvc' AND year>=2024
GROUP BY year, month ORDER BY year, month
AR & Purchasing
-- Open AR by customer
SELECT entity_name, COUNT(*) as cnt,
ROUND(SUM(foreigntotal),2) as open_ar
FROM transactions WHERE type='CustInvc' AND status='A'
GROUP BY entity_name ORDER BY open_ar DESC
-- Vendor spend 2026
SELECT entity_name, COUNT(*) as bills,
ROUND(SUM(ABS(foreigntotal)),2) as spend
FROM transactions WHERE type='VendBill' AND year=2026
GROUP BY entity_name ORDER BY spend DESC LIMIT 10
Foreign Key Relationships
customers.terms → ref_terms.id vendors.terms → ref_terms.id
customers.salesrep → employees.id items.class → ref_classes.id
customers.category → ref_categories.id items.department → ref_departments.id (= brand)
contacts.company → customers|vendors employees.supervisor → employees.id (self)
transactions.entity → customers|vendors (78,616 backfilled, 100%)
invoice_lines.txn_id → transactions.id invoice_lines.item → items.id
so_lines.txn_id → transactions.id vb_lines.txn_id → transactions.id
customer_pricing.customer_id → customers.id customer_pricing.item_id → items.id
Date format: M/D/YYYY throughout. transactions.year is GENERATED STORED from SUBSTR(trandate,-4). All booleans TEXT 'T'/'F'.
Quick Start
# Health (no auth)
curl -s https://gfs-platform.mikelevine.workers.dev/api/health
# KPIs
curl -s -H "Authorization: Bearer YOUR_KEY" https://gfs-platform.mikelevine.workers.dev/api/kpis
# Search customers
curl -s -H "Authorization: Bearer YOUR_KEY" "https://gfs-platform.mikelevine.workers.dev/api/customers?q=driscoll"
# AR aging
curl -s -H "Authorization: Bearer YOUR_KEY" https://gfs-platform.mikelevine.workers.dev/api/ar/aging
Pagination: limit (1-200, default 50) + offset (0-100K). Auth: Authorization: Bearer <API_KEY>
Allowlists:
allergen: milk, eggs, peanuts, soybeans, wheat, fish, tree_nuts, crustacean, celery, lupin, molluscs, mustard, sesame, sulphur_dioxide (14)
type (txn): CustInvc, SalesOrd, PurchOrd, VendBill, CustPymt, VendPymt, Check, ItemShip, CustCred, ItemRcpt, InvAdjst, InvWksht, Deposit, Journal, WorkOrd, Build (16 — Unbuild/InvTrnfr/VendCred/CustRfnd not queryable via API)
type (item): InvtPart, Assembly, Kit, NonInvtPart (4)
CORS: https://ai-globalfoodsolutions.co · https://www.ai-globalfoodsolutions.co · http://localhost:3000 · http://localhost:8787
Core Data
/ PUB root status
/api/health PUB DB counts
/api/kpis AUTH revenue, AR, AP, SOs
/api/briefing AUTH morning briefing
/api/customers AUTH search + paginate
/api/customers/:id AUTH detail + contacts + pricing
/api/customers/:id/history AUTH yearly + items
/api/customers/ranking AUTH top 50 by year
/api/items AUTH type + allergen filter
/api/items/:id AUTH revenue + cost + custs
/api/items/performance AUTH top 50 by year
/api/items/:id/customers AUTH who buys this
Analytics & Financial
/api/transactions AUTH any type + year
/api/vendors AUTH active list
/api/vendors/spend AUTH top 50 by year
/api/ar/aging AUTH current/30/60/90+
/api/financials/summary AUTH rev vs COGS by year
/api/financials/monthly AUTH monthly by type
/api/revenue/trend AUTH monthly 2024+
/api/gl/accounts AUTH chart of accounts
/api/search AUTH cross-entity search
Error Responses
Status Response Cause
401 {"error":"Unauthorized","hint":"..."}Missing/invalid Bearer token
400 {"error":"Invalid item type"}Type/allergen not in allowlist
404 {"error":"Not found","endpoints":[...]}Unknown path — returns endpoint list
405 {"error":"Method not allowed"}Non-GET request
500 {"error":"Internal server error"}Unhandled exception (logged)
Order-to-Cash · $177.4M
SalesOrd 12,862 · B→D→F→G→H
ItemShip 12,375 (96.2% fill)
CustInvc 12,542 · 98.3% paid · 216 open ($2.3M)
CustPymt 8,195 · 99.97% deposited
+ CustCred (932 · $2.7M) + CustRfnd (2)
Procure-to-Pay · $145.0M
PurchOrd 11,566 · B→D→E→F→G→H
ItemRcpt 3,491 · $51.7M
VendBill 22,916 · 99.6% paid · 1.98/PO avg
VendPymt 9,603 · $144.0M + 5,493 Checks ($29.1M)
+ VendCred (116 · $254K)
Manufacturing WorkOrd (547) → Build (98 · $107K) → Unbuild (13). 2020-2025.
Inventory InvAdjst (848 · $5.95M) · InvWksht (457 · $43.5M) · InvTrnfr (44)
Financial Check (5,493 · $29.1M) · Deposit (220 · $9.25M) · Journal (47)
2026 Business Snapshot Static data as of May 19, 2026 · Live dashboard →
Monthly Revenue
YTD: $11,272,176 · Pace: ~$29.4M
Top 5 Customers (67.4%)
Concentration: Driscoll = 36.4%
NetSuite
Account 4656898 PRODUCTION
SuiteAPI #2948 RESTlet
SuiteQL #2947 Suitelet
Toolkit #2949 Suitelet
SuiteAttach RESTlet
MCP Server Claude ↔ NS
N/llm Cohere (0 gov units)
Local
Chartstone Pro localhost API
launchd sync every 900s
launchd report 7pm daily
Wrangler v4.90.1 (OAuth)
sync.sh Chartstone→D1
daily-report.sh KPI markdown
NetSuite Admin Links — Account 4656898 (24 links)
DNS & Credentials
DNS Records
CNAME api gfs-platform.mikelevine.workers.dev (proxied)
CNAME www ai-globalfoodsolutions.co (proxied)
MX route1/2/3.mx.cloudflare.net
TXT SPF v=spf1 include:_spf.mx.cloudflare.net ~all
NS chance + leanna.ns.cloudflare.com
Credential Locations
CF OAuth ~/.wrangler/ (managed)
CHARTSTONE_SECRET env var (see admin)
API_KEY CF secret store (wrangler secret put)
CF Account ID [REDACTED]
Cloudflare Admin Links (9 links)
Deploy Worker cd ~/Desktop/gfs-platform
wrangler deploy
curl -s .../api/health
Deploy Guide cd ~/Desktop/gfs-platform
# rebuild /tmp/gfs-deploy
wrangler pages deploy /tmp/gfs-deploy --project-name gfs-system-guide
Load D1 Data wrangler d1 execute gfs-netsuite --remote --file=sql/01_customers.sql
wrangler d1 execute gfs-netsuite --remote --command="SELECT ..."
wrangler d1 execute gfs-netsuite --remote --json --command="..."
Sync Troubleshooting # Check: cat sync-stderr.log
# launchctl list | grep globalfood
# Fix quarantine: xattr -d com.apple.provenance sync.sh
# Chartstone port changed? Check app, update sync.sh
# Manual: bash sync.sh
Secret Rotation # API key: wrangler secret put API_KEY
# Chartstone: ~/.zshenv CHARTSTONE_SECRET
# CF OAuth: wrangler login
D1 Capacity # Current: 29.6 MB / 185K rows
# Limit: 10 GB / 10M rows (paid)
# Headroom: ~98% free
# Growth: ~30 txns/day = decades of room
Incident Response
Symptom Likely Cause Fix Verify
API returns 500 D1 query error or Worker crash Check CF Worker Logs → fix query → wrangler deploy curl .../api/health
API returns 401 API key missing or wrong wrangler secret put API_KEYTest with Bearer header
D1 data stale sync.sh failed or Chartstone down Check sync-stderr.log · Restart Chartstone · bash sync.sh Check .last_sync timestamp
sync.sh "Operation not permitted" macOS Sequoia com.apple.provenance System Settings → Privacy & Security → Full Disk Access → add Terminal.app (xattr removal doesn't work on Sequoia)Reload: launchctl unload/load then check stderr
Chartstone not responding App closed or port changed Open Chartstone · Check port · Update sync.sh PORT curl localhost:PORT/health
Pages site down Deploy failed or CF outage Re-deploy: wrangler pages deploy · Check status.cloudflare.com Visit pages.dev URL
Custom domain not working Local firewall/VPN blocking TLS to CF proxy IPs (nc connects but curl/openssl fail with "Bad file descriptor") Check System Settings → Network → Firewall. Try from different device/network. CF route is deployed correctly. Test from phone or different network
NS script governance error Script exceeded 10K units Check NS Execution Logs · Optimize queries · Use Map/Reduce APM dashboard
Credential compromised API key or token leaked Rotate immediately: wrangler secret put API_KEY · Revoke NS tokens · Change CHARTSTONE_SECRET Test all endpoints
Escalation: Michael Levine (admin, all access) → Richard Gallo (ops) → Amanda Swerdlow (finance). CF support: dash.cloudflare.com. NS support: Oracle support portal.
Risk Register
Chartstone SPOF
Entire sync pipeline depends on Chartstone Pro running on a single Mac. If machine is off/asleep/broken, D1 stops updating. No monitoring, no alerting, no failover.
Mitigation: Move to Worker-based sync via SuiteAPI RESTlet (eliminates localhost dependency)
Single Admin
Only Michael Levine can deploy Workers, manage D1, rotate secrets, and access all CF/NS admin. Bus factor = 1.
Mitigation: Document all procedures (done in runbook). Cross-train second admin. Share CF access.
No Backups
No D1 backup strategy, no NS data export schedule, no disaster recovery plan. If CF account compromised, D1 data could be lost.
Mitigation: D1 has point-in-time recovery (paid plan). Schedule regular wrangler d1 export.
48 Public Suitelets
Internal ops portal, all broker portals, and product program portals accessible without NS login. Data exposure risk.
Mitigation: Audit each isonline=T deployment. Restrict internal ops immediately. Broker portals may need to stay public.
Integration Dependencies
Integration Direction Auth What Breaks If Down Owner
Chartstone Pro NS → localhost Bearer token ALL sync stops — D1 goes stale Michael
CF Worker D1 → HTTP API key All dashboards + API go down Michael
ECOB NS ↔ ECOB Workflow SO shipment status stops updating Ops
Zoho Mail NS → email SMTP All NS emails stop (confirmations, dunning) IT
Dropbox NS → files URL links Pricing file links break on customer records Sales
Google API NS → Google API key Distance calculations fail on SOs Ops
MCP (Claude) Claude ↔ NS OAuth AI can't query NetSuite Michael
SuiteAttach External → NS TBA token 11 File uploads fail Michael
Airtable NS → Airtable REVOKED WO sync (already suspended) —
Zapier NS → Zapier REVOKED WO automation (already dead) —
Active tokens: 2 (SuiteAttach #11, Analytics Warehouse #2). Revoked: 9. No rotation schedule in place.
Data Integrity — All Validated
Completeness
✓
Null dates: 0 · Null types: 0
✓
Entity backfill: 78,616 (100%)
✓
All 3 line tables: 100% parity with NS
Security
✓
Bearer auth · CORS (4 origins)
✓
CSP · X-Frame · XSS · Referrer
✓
SQL parameterized · input validated
✓
SPF configured · DKIM: verify CF
Known Issues
!
Custom domain SSL: provisioning
!
Worker sync cron: stub only
Users, Roles & Organization
Key Personnel
Mitchell Levine President & Owner
Michael Levine Administrator
Richard Gallo VP Operations
Martin Baker VP Sales
Elena Misoulis VP Nutrition & Compliance
Amanda Swerdlow Director Finance
Thomas Kurza Director K-12 Sales East
Sal Bruno Director Supply Chain
James Muldowney Director Purchasing
Danielle Scibelli Director Customer Service
+ ~45 production/warehouse (Delta Pak) · 17 consultants · 3 system accounts (Mike Bot, Dunning Manager, Zapier)
GFS Custom Roles (27 of 97)
GFS - Sales Sales Center
GFS - Sales & Ops Manager Sales Center
GFS - Buyer Account Center
GFS - Supply Chain Manager Shipping Center
GFS - Inventory Manager Shipping Center
GFS - Warehouse Operations Shipping Center
GFS - Controller Account Center
GFS - Senior Executive Executive Center
GFS - Dunning Director/Manager Custom Center
GFS - Food Safety Manager Account Center
+ Customer Center, Vendor Center, Employee Center portals · ~20-25 full user licenses
Deployed Scripts & Suitelets
Total deployments 393
GFS custom scripts 43
Scripts in TESTING 5
Unused international 24+
Custom Suitelets 24
Broker portals 8
Product program portals 7
Ops dashboards 6
Active workflows 28 released
Dunning workflows 14
Saved searches 968
Active bundles 15
SECURITY: 48 Suitelets publicly accessible (isonline=T) including internal ops portal and all broker portals
System Health & Data Quality 8 ISSUES
Critical Data Gaps
!
Vendors: 93% no payment terms (451/484) — AP aging unreliable
!
Vendors: 70% no email (341) — can't send PO confirmations
!
Items: 78% no GTIN/UPC — can't print barcodes
!
Items: 71% no case weight — BOL weight calculations fail
!
Items: 75% no storage temp — cold chain documentation incomplete
!
Items: 98% no kosher status — certification missing from labels
!
Items: 70% no shelf life / country of origin — compliance risk
!
All 153 accounting periods OPEN — no period closure ever
!
Dual dunning systems running simultaneously
!
9 Power Up meal kits negative inventory
Active Integrations
ECOB SO shipment + BOL
Zoho Mail Email delivery
Dropbox Pricing file links
Google API Distance calculation
SuiteAttach File upload RESTlet
Analytics Warehouse NS reporting
MCP (Claude) AI ↔ NetSuite
SUSPENDED: Airtable, Zapier, Celigo, Tray.IO (all tokens revoked)
Business Context & Data Maps
About GFS
Global Food Solutions, Inc. — commodity food distribution, co-packing, and private-label manufacturing. Based in NY metro area. NetSuite Mid-Market edition, single subsidiary, US-only.
Revenue pace ~$29M/yr
Primary products Frozen breakfast, cheese, pantry items
Brands Right Start · Power Up · Bentley's · Alfresco · Cornerstone
Key markets K-12 school districts, distributors, food service
Top customer Driscoll Foods (36.4% of revenue)
Top vendor Echo Lake Foods (co-packer)
Cheese pricing Bongards: CME trailing week avg + 35% moisture premium
USDA programs Barrel cheddar FIFO drawdown, commodity cheese allocation
Rebate program Good Eats — tier-based by monthly case volume
Customer Segments (283)
Major Distributors ~50 (Sysco 20, US Foods 16)
School Districts / K-12 ~50 (NYC DOE, Albuquerque)
Food Service / Caterers ~15 (Whitsons, Maschio's)
Manufacturers / Co-Packers ~10 (Operative Cake)
Specialty / Retail ~10 (Stew Leonards, Ace)
Terms: 29% Net 30, 22% Net 14, 21% COD. 80% on dunning. 59% OPEN pricing status.
Item Catalog (1,148 active)
Inventory Parts 976 (85%)
Assembly 70 (6%)
Service 49 (4%)
Frozen 48% · Dry 26% · Refrigerated 5%
Top brands Right Start 169 · Bentley's 165 · Power Up 138
Allergens flagged: Wheat 81, Soybeans 43, Milk 40, Eggs 22. 14 allergen checkboxes per item.
Dunning & Collections
On dunning procedure 226 of 283 (80%)
Actively dunned 32 customers
Level 5 (final) 6 (incl Good Eats)
Level 4 (critical) 2 (incl Mivila)
Level 2-3 20
Issue: Dual dunning (day-based + level-based) both active simultaneously
NS Edition & Features
Edition Mid-Market
Subsidiary 1 (no OneWorld)
Currencies 4 configured, USD only used
Active bundles 15
Unused bundles 6 (intl tax)
API tokens 2 active, 9 revoked
Custom fields 414 mapped
Templates (print) 10 preferred + 43 standard
Templates (email) 20 active
Research Library — 280K Words · 9 Documents
01 Portlets 15K · KPIs, saved search tricks, GFS ideas
02 Suitelets 39K · 3-tier arch, React/Vue, 34 repos, APIs
03 Pitfalls 38K · 82 gotchas, 40+ checklist items
04 Tools 11K+HTML · 60+ tools at pages.dev
05 Missing Angles 20K · N/llm, pipeline, MCP, mobile
06 AI Deep Dive 38K · 8 N/llm uses, RAG, 126 queries
07 Blueprint 36K · 6 views, data pipeline, 12-week plan
08 Automations 21K · 8 alerts, 6 workflows, 10 scripts
Build Plan & Roadmap 25/36
Done (25 items) — click to expand
Completed
✓
D1 database provisioned (18 tables, 185K+ rows, 29.6 MB)
✓
Entity backfill complete (78,616 patched, 100% on all 6 core types)
✓
GL accounts loaded (152, full Chart of Accounts from live NS)
✓
vb_lines gap closed (21,317 lines, 100% of item bills, 2 backfilled)
✓
Worker deployed + hardened (20 endpoints, auth, CORS, CSP, 6 headers)
✓
8 new API endpoints added (AR aging, customer ranking/history, vendor spend, item perf, revenue trend, GL, briefing)
✓
KV + R2 bound · API key secret set
✓
Crons running (launchd sync 15m + Worker cron + 7pm report)
✓
Daily report KPI parsing fixed (--json + python3)
✓
sync.sh quarantine fixed (xattr -d com.apple.provenance)
✓
DNS + domain configured (CNAME, MX, SPF, NS records)
✓
Worker route deployed (api.ai-globalfoodsolutions.co/*)
✓
Security audit closed (C1-C3, M6, H2, H3, all SQL parameterized)
✓
MCP connected (Claude ↔ NetSuite, 4 tools live)
✓
60+ NS tools deployed to gfs-netsuite-tools.pages.dev
✓
Research docs integrated (9 docs, 280K words, copied to gfs-platform/docs/)
✓
Master system guide built (1,099 lines, 16 sections, SVG architecture)
✓
Guide deployed to CF Pages (gfs-system-guide.pages.dev)
✓
Archify diagrams rendered (system architecture dataflow + O2C workflow)
✓
3x audit agents: links, data accuracy (70+ claims), HTML quality
✓
Cross-reference audit: guide vs source code, schema, wrangler, research
✓
Users/roles/org extracted (116 employees, 27 roles, 393 scripts)
✓
System health + data quality grades documented (A to F per record type)
✓
Business maps extracted (customer segments, item catalog, dunning, pricing)
✓
README.md + sitemap footer added
Pending / Next (6 items)
!
SuiteAPI live sync (Worker cron → RESTlet)
!
Email daily report (CF Email)
○
Workers AI (NL → D1 queries)
○
GFS Hub Suitelet (SuiteFrame)
○
6 Suitelet views (see below)
○
SuiteFlow workflows + email alerts
12-Week Sprint Plan (from Blueprint doc 07) — 6 sprints
Sprint 1-2: Foundation
○
Install SuiteQL Tool + 106 queries
○
Create cache custom records
○
USDA price Scheduled Script
○
Chrome extensions installed
Sprint 3-4: Hub Shell
○
GFS Hub Suitelet (SuiteFrame)
○
Attio CSS + mobile responsive
Sprint 5-6: Core Views
○
CME Price Dashboard (Chart.js)
○
AR Command Center (DataTables)
○
Customer 360 (tabbed detail)
○
Email actions + keyboard shortcuts
Sprint 7-8: AI Layer
○
AI insights on dashboards (RAG)
○
Customer 360 AI call prep
Sprint 9-10: Chat + Intel
○
AI Chat (NL → SuiteQL → results)
○
Similar Items (embeddings)
○
Nightly anomaly detection
Sprint 11-12: MCP + Polish
Planned Suitelet Views (from Blueprint doc 07)
CME Price Intelligence Real-time barrel/block prices, Chart.js trends, AI summary, margin calc, email price sheet
Stack: Inline HTML + Chart.js + N/cache + USDA API
AR Command Center Aging by customer, overdue alerts, AI anomaly narratives, send reminder button
Stack: Inline HTML + DataTables + SuiteQL
AI Chat — Ask Your Data Natural language → SuiteQL → results table, quick buttons, SQL preview
Stack: N/llm + N/query + safety guardrails
Rebate Tracker Progress bars per customer, tier thresholds, AI projection, accrual history
Stack: Inline HTML + SuiteQL + Chart.js
Product Intelligence Similar items (embeddings), cross-sell, customer-item matrix
Stack: N/llm embed() + cosine similarity
Customer 360 Revenue, AR, margin, trend, AI call prep, orders, contacts, notes
Stack: RAG + SuiteQL + tabbed layout
SuiteFrame Architecture (Tim Dietrich) Single Suitelet = app initializer + API backend. GET routes → views, POST routes → data/AI/export/email. Templates in File Cabinet. Bootstrap + DataTables + Handlebars. Center Tab puts it in NS nav bar.
gfs.core.suitelet.js → gfs.library.module.js → gfs.ui.*.template.html → gfs.css → gfs.client.js
AI Integration — N/llm + SuiteQL
N/llm Methods
llm.generateText() Prompt → text (0 gov units)
llm.generateTextStreamed() Streaming tokens
llm.embed() Text → vectors (96 inputs max)
llm.createDocument() RAG source doc (0 units)
llm.createPrompt() Reusable template (0 units)
llm.evaluatePrompt() Run stored prompt
Critical: LLM calls do NOT consume governance units
8 GFS Use Cases
○
Price Movement Explainer — AI summarizes USDA barrel/block trends
○
Customer Account Summary — AI call prep from AR + orders + rebates
○
Rebate Eligibility Classifier — AI checks order lines vs program rules
○
PO Description Standardizer — AI normalizes vendor memo fields
○
Vendor Email Summarizer — AI distills comms to 1 sentence
○
Margin Alert Narrative — AI morning alert for low-margin customers
○
Weekly Sales Report — AI 5-line team summary
○
Contract Expiration Warning — AI renew vs renegotiate per customer
5 MCP Custom Tools (for Claude)
Tool Input Output
gfs_get_customer_360customer name AR, revenue, margin, rebate, last order
gfs_get_pricescommodity barrel/block price, spread, trend, AI summary
gfs_query_salesdate range, customer revenue, order count, top items
gfs_check_rebatecustomer, order lines tier, progress, projected date
gfs_run_querySQL string results (SELECT only, 100 row limit)
Automation Plan — 4 Tiers
Tier 1: Zero Code (Today)
○
8 saved search email alerts (overdue AR, PO pending, contracts, inventory, large orders)
○
5 scheduled reports (AR aging, sales, POs, inventory, commissions)
○
Reminders portlet configured
○
Formula fields (margin %, days overdue, contract countdown)
Tier 2: SuiteFlow Workflows
○
PO approval routing (3-tier: <$1K auto, <$10K mgr, ≥$10K director)
○
New customer welcome email + follow-up task
○
SO status change → email notifications
○
Price change alert to sales team
○
Auto-set dept/location/class on SO create
Tier 3: SuiteScript
10 Scheduled · 7 User Event · 5 Map/Reduce · 5 AI-powered
○
USDA Price Refresh (hourly) · KPI Aggregator · AI Price Summary
○
Anomaly Detector · Margin Alert · Contract Watcher (nightly)
○
Morning Briefing Email (7am) · Weekly Report (Fri 4pm)
○
Auto-fill fields on SO/PO · Margin validation · Customer flags
○
Bulk Price Update · Month-End Rebate JE · USDA FIFO Drawdown
Tier 4: Integration
○
USDA price pipeline (Scheduled Script → cache → Suitelet reads)
○
5 MCP Custom Tools for Claude (AR, prices, sales, rebate, query)
○
n8n: NS → Slack, Sheets, email, project management
82 Pitfalls — 10 Categories REFERENCE
Field & Form (11) Field IDs must be custpage_ · Duplicate IDs silently break · FILE fields can't go in tabs · INLINEHTML can't be in sublists · Disabled fields don't POST · Use INLINE not DISABLED
Tabs & Sublists (7) #1 Bug: Tabs break INLINEHTML POSTs · Sublist selections lost on paginate · NS doesn't auto-paginate · STATICLIST loses data on sort
Client Script (8) #2 Bug: External Suitelets skip client scripts · Missing return = silent failure · Use SS 2.0 for client entry points · resolveScript() for all URLs
Deployment (7) Select All = Internal only (2025.1) · Status must be Released · Execute As Role determines perms · External needs Available Without Login
INLINEHTML & CSS (8) CSS conflicts with NS CSS (namespace everything) · External must be HTTPS · iframes for isolation · React/Vue must be single-file · Hash routing required
External API (6) Each https.get = 10 governance units · Timeouts not configurable · CORS irrelevant server-side · Cache aggressively with N/cache
N/cache (5) Critical: Cache deleted ANY time without warning · Values must be strings · Loader errors swallowed · Use Custom Records for persistence
Governance (9) Suitelets = 10K units · record.load in loop = #1 killer · lookupFields = 1 unit vs load = 10 · 15-min timeout absolute · Delegate to Map/Reduce
Upgrades (7) 2025.1: Ext JS REMOVED · getRecordType → getType · "use strict" required SS 2.1 · 2024.2: External URL format changed · Bi-annual mandatory
Architecture (8) Don't build what NS already does · Test with ALL roles · Load data async (not on GET) · Don't mix form submit + AJAX · Never hardcode IDs
Pre-Deploy Checklist (40+ items) All field IDs custpage_ · No FILE in tabs · No disabled POST fields · CS entry points in return · resolveScript for URLs · CSS namespaced · No creds in code · Tested all roles · Tested POST handler · Tested error handling · No Ext JS deps · Only documented APIs ·
→ Full checklist in 12-Tab Guide
Term Definition
SuiteQLNetSuite's SQL dialect (Oracle-style). Queries NS data directly.
RESTletNS custom REST endpoint (SuiteScript). SuiteAPI #2948 is a RESTlet.
SuiteletNS custom web page (SuiteScript). SuiteQL Tool #2947 is a Suitelet.
N/llmNS native AI module. Cohere Command R. 0 governance units per call.
MCPModel Context Protocol. AI agents (Claude) call tools in external systems.
TBAToken-Based Authentication. NS auth via consumer/token key pairs.
D1Cloudflare serverless SQLite on edge. Our mirror of NS data.
KV / R2CF key-value store (CACHE) and S3-compatible storage (gfs-files). Both bound, not yet used.
ChartstoneLocal desktop app. Unlimited localhost API to NetSuite via SuiteQL.
EntityCustomer or vendor ID on transactions. Backfilled 78,616 to 100%.
Department= Brand in GFS (Right Start, Power Up, etc). Maps to ref_departments.
Governance UnitsNS script execution budget. Suitelets: 10K. N/llm: 0. lookupFields: 1.
SuiteFrameTim Dietrich's framework. Single-Suitelet MVC pattern for NS apps.
BongardsPrimary barrel/block cheddar supplier. Pricing: CME trailing week average + 35% moisture premium.
Good EatsRebate program — tier-based by monthly case volume. Currently at dunning Level 5.
USDA LMPRSUSDA Livestock Mandatory Price Reporting. Free API for barrel/block cheddar prices at mpr.datamart.ams.usda.gov
FIFO DrawdownFirst-in-first-out allocation for USDA barrel cheddar inventory across price brackets.
isonlineNS Suitelet deployment flag. T = publicly accessible without login. 48 currently set to T.
custitem_as_*14 allergen flag fields on items (milk, eggs, peanuts, soybeans, wheat, fish, tree_nuts, etc.). TEXT 'T'/'F'.
System Inventory
gfs-platform/
src/index.ts Worker (20 eps)
schema.sql 18 tables
sql/ 45 loader files
docs/ 9 research docs
guide/ System guide
*.sh sync + report
Template Review 2026/
Data-Exports/ 134 files (40MB)
Email-Templates/ 53 templates
PDF-HTML-Templates/ 54 XML
PDF/HTML Layouts 29 layouts
Reference/ 24 files
Schema-Browser/ 24 schemas
NetSuite Tools
Chartstone Pro localhost
SuiteQL #2947 Suitelet
SuiteAPI #2948 RESTlet
Toolkit #2949 Suitelet
SuiteAttach RESTlet
60+ tools pages.dev
Cloudflare
Worker gfs-platform
D1 gfs-netsuite
KV + R2 CACHE + gfs-files
Pages 16 projects
Domain ai-globalfoodsolutions.co
Crons 2 active
Sitemap & Project Map
Deployed Pages (gfs-system-guide.pages.dev)
/styles.css Shared CSS (7KB)
gfs-platform/ (local project)
gfs-platform/
├── src/index.ts Worker (20 endpoints)
├── schema.sql 18 tables
├── wrangler.jsonc D1 + KV + R2 + crons
├── package.json npm scripts
├── tsconfig.json TypeScript config
├── sync.sh Chartstone → D1 sync
├── daily-report.sh 7pm KPI report
├── .last_sync Sync timestamp
├── *.html 3 dashboards
├── guide/
│ ├── index.html THIS PAGE (1,001 lines)
│ ├── database.html Column-level wiki
│ ├── api.html Full API docs
│ ├── workflows.html SVG flowcharts
│ ├── infrastructure.html Extended infra
│ ├── master.html 12-tab guide (tools+skills)
│ ├── styles.css Shared CSS
│ └── diagrams/ 2 archify HTMLs + JSONs
├── docs/ 9 research (280K words)
│ ├── 01-Portlet-Research.md
│ ├── 02-Suitelet-Master-Audit.md
│ ├── 03-Pitfalls-Build-Perfect.md
│ ├── 04-Power-Tools.html + .md
│ ├── 05-Missing-Angles.md
│ ├── 06-AI-Query-Deep-Dive.md
│ ├── 07-AI-Suitelet-Blueprint.md
│ ├── 08-Automation-Powerhouse.md
│ └── README.md
└── sql/ 45 loader files (39MB)
GFS Template Review 2026/ (329 files)
GFS Template Review 2026/
├── 00_TEMPLATE_INDEX.html
├── 00_SYSTEM_ARCHITECTURE.html
├── 00_SYSTEM_CONNECTIONS.html
├── 00_FLOWCHARTS.html
├── 00_ADMIN_ACTION_GUIDE.html
├── 00_BULK_COPY_SESSION.html
├── CLAUDE.md
├── SECURITY_AUDIT_*.md (3 files)
├── PLAN_CLOUDFLARE_PLATFORM.md
├── Data-Exports/ 134 files (40MB)
│ ├── 73 JSON data dumps
│ ├── 54 MD reports
│ └── 5 CSV + 2 TXT
├── Email-Templates/ 53 files
│ ├── 18 customer-facing HTML
│ └── NS-Exports/ (35 raw)
├── PDF-HTML-Templates/ 54 XML
│ ├── 10 active/preferred
│ ├── 16 deprecated
│ └── 27 standard
├── PDF-Layouts/ 19 files
├── HTML-Layouts/ 10 files
├── Reference/ 24 files
│ ├── USERS_ROLES_ORG_MAP.md
│ ├── COMPANY_STRUCTURE.md
│ ├── CUSTOMER/VENDOR/ITEM_MAP.md
│ ├── SAVED_SEARCHES.md (968)
│ ├── SCRIPT_DEPLOYMENTS.md
│ └── 12 more reference docs
└── Schema-Browser/ 24 files
├── 19 MD schemas
└── 5 JSON schemas
GFS NetSuite Master System Guide · Account 4656898 · ai-globalfoodsolutions.co
185,500+ D1 rows · 20 API endpoints · 18 tables · 329 template files · 280K words of research
Built May 19, 2026 · Triple-audited · Cross-referenced against all source files