GFS NETSUITE MASTER SYSTEM GUIDE

Global Food Solutions, Inc. · Account 4656898 · ai-globalfoodsolutions.co
CHECKING...
--
2026 YTD Revenue
--
Open AR
--
Open Sales Orders
--
D1 Rows (live)
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

Infra Dashboard

Live API health checks

Executive Dashboard

KPIs · revenue · AR

API Health (live)

Raw JSON from Worker

D1 Console

CF dashboard · query D1 directly

D1 Database — gfs-netsuite · 185K rows · 18 tables 100% SYNCED → Full Wiki

Entities

customers283
vendors484
items1,265
contacts490
employees116

Transactions

transactions102,367
invoice_lines28,528
so_lines29,098
vb_lines21,317

Financial

gl_accounts152
customer_pricing1,264
sync_log59+

Reference (6)

ref_terms18
ref_departments14 (brands)
ref_locations17
ref_categories / classes / shipping14 / 6 / 7

Transaction Types (20)

TypeNameCountValueEntityLines
CustInvcInvoice12,542$169.8M✓ 100%28,528
SalesOrdSales Order12,862$177.4M✓ 100%29,098
VendBillVendor Bill22,916$145.0M✓ 100%21,317
PurchOrdPurchase Order11,566$131.0M✓ 100%
CustPymtPayment8,195$163.2M✓ 100%
VendPymtVendor Payment9,603$144.0M✓ 100%
ItemShipFulfillment12,375
CheckCheck5,493$29.1M
ItemRcptReceipt3,491$51.7M
CustCredCredit Memo932$2.7M
+ 10 more2,392$59.1MInvAdjst, 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'.

REST API — 20 Endpoints ALL LIVE → Full Docs

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

StatusResponseCause
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)

Business Workflows → Full SVG Diagrams

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

Jan
$2,617,390
Feb
$2,447,971
Mar
$2,550,474
Apr
$2,355,274
May*
$1,301,067
YTD: $11,272,176 · Pace: ~$29.4M

Top 5 Customers (67.4%)

Driscoll
$4,107,918
Operative
$1,745,114
Mivila
$617,441
SYSCO LI
$569,354
T. Nichols
$555,527
Concentration: Driscoll = 36.4%

Infrastructure & Services → Standalone Page

NetSuite

Account4656898 PRODUCTION
SuiteAPI #2948RESTlet
SuiteQL #2947Suitelet
Toolkit #2949Suitelet
SuiteAttachRESTlet
MCP ServerClaude ↔ NS
N/llmCohere (0 gov units)

Local

Chartstone Prolocalhost API
launchd syncevery 900s
launchd report7pm daily
Wranglerv4.90.1 (OAuth)
sync.shChartstone→D1
daily-report.shKPI markdown
NetSuite Admin Links — Account 4656898 (24 links)

Core

Dashboard
Users/Roles
Features
Periods
Scripts
Workflows
Custom Fields
File Cabinet

Records

Customers
Vendors
Items
Invoices
Sales Orders
Purchase Orders
Vendor Bills
Saved Searches

Reports & API

Financial Reports
AR Aging
Records Catalog
Integrations
APM
Execution Logs
System Status
CSV Import

DNS & Credentials

DNS Records

CNAME apigfs-platform.mikelevine.workers.dev (proxied)
CNAME wwwai-globalfoodsolutions.co (proxied)
MXroute1/2/3.mx.cloudflare.net
TXT SPFv=spf1 include:_spf.mx.cloudflare.net ~all
NSchance + leanna.ns.cloudflare.com

Credential Locations

CF OAuth~/.wrangler/ (managed)
CHARTSTONE_SECRETenv var (see admin)
API_KEYCF secret store (wrangler secret put)
CF Account ID[REDACTED]
Cloudflare Admin Links (9 links)

Dashboard

Workers & Pages
D1 Databases
R2 / KV

Domain

DNS Records
SSL/TLS
Email Routing

Worker

gfs-platform
Live Logs
Cron Triggers

Operations Runbook

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

SymptomLikely CauseFixVerify
API returns 500D1 query error or Worker crashCheck CF Worker Logs → fix query → wrangler deploycurl .../api/health
API returns 401API key missing or wrongwrangler secret put API_KEYTest with Bearer header
D1 data stalesync.sh failed or Chartstone downCheck sync-stderr.log · Restart Chartstone · bash sync.shCheck .last_sync timestamp
sync.sh "Operation not permitted"macOS Sequoia com.apple.provenanceSystem 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 respondingApp closed or port changedOpen Chartstone · Check port · Update sync.sh PORTcurl localhost:PORT/health
Pages site downDeploy failed or CF outageRe-deploy: wrangler pages deploy · Check status.cloudflare.comVisit pages.dev URL
Custom domain not workingLocal 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 errorScript exceeded 10K unitsCheck NS Execution Logs · Optimize queries · Use Map/ReduceAPM dashboard
Credential compromisedAPI key or token leakedRotate immediately: wrangler secret put API_KEY · Revoke NS tokens · Change CHARTSTONE_SECRETTest 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

IntegrationDirectionAuthWhat Breaks If DownOwner
Chartstone ProNS → localhostBearer tokenALL sync stops — D1 goes staleMichael
CF WorkerD1 → HTTPAPI keyAll dashboards + API go downMichael
ECOBNS ↔ ECOBWorkflowSO shipment status stops updatingOps
Zoho MailNS → emailSMTPAll NS emails stop (confirmations, dunning)IT
DropboxNS → filesURL linksPricing file links break on customer recordsSales
Google APINS → GoogleAPI keyDistance calculations fail on SOsOps
MCP (Claude)Claude ↔ NSOAuthAI can't query NetSuiteMichael
SuiteAttachExternal → NSTBA token 11File uploads failMichael
AirtableNS → AirtableREVOKEDWO sync (already suspended)
ZapierNS → ZapierREVOKEDWO 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
Orphaned lines: 0
Entity backfill: 78,616 (100%)
GL accounts: 152/152
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
!
KV/R2: bound but unused

Users, Roles & Organization

Key Personnel

Mitchell LevinePresident & Owner
Michael LevineAdministrator
Richard GalloVP Operations
Martin BakerVP Sales
Elena MisoulisVP Nutrition & Compliance
Amanda SwerdlowDirector Finance
Thomas KurzaDirector K-12 Sales East
Sal BrunoDirector Supply Chain
James MuldowneyDirector Purchasing
Danielle ScibelliDirector Customer Service
+ ~45 production/warehouse (Delta Pak) · 17 consultants · 3 system accounts (Mike Bot, Dunning Manager, Zapier)

GFS Custom Roles (27 of 97)

GFS - SalesSales Center
GFS - Sales & Ops ManagerSales Center
GFS - BuyerAccount Center
GFS - Supply Chain ManagerShipping Center
GFS - Inventory ManagerShipping Center
GFS - Warehouse OperationsShipping Center
GFS - ControllerAccount Center
GFS - Senior ExecutiveExecutive Center
GFS - Dunning Director/ManagerCustom Center
GFS - Food Safety ManagerAccount Center
+ Customer Center, Vendor Center, Employee Center portals · ~20-25 full user licenses

Deployed Scripts & Suitelets

Total deployments393
GFS custom scripts43
Scripts in TESTING5
Unused international24+
Custom Suitelets24
Broker portals8
Product program portals7
Ops dashboards6
Active workflows28 released
Dunning workflows14
Saved searches968
Active bundles15
SECURITY: 48 Suitelets publicly accessible (isonline=T) including internal ops portal and all broker portals

System Health & Data Quality 8 ISSUES

A
GL Accounts
B+
Customers
F
Vendors (93% no terms)
F
Items (78% no GTIN)

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

ECOBSO shipment + BOL
Zoho MailEmail delivery
DropboxPricing file links
Google APIDistance calculation
SuiteAttachFile upload RESTlet
Analytics WarehouseNS 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 productsFrozen breakfast, cheese, pantry items
BrandsRight Start · Power Up · Bentley's · Alfresco · Cornerstone
Key marketsK-12 school districts, distributors, food service
Top customerDriscoll Foods (36.4% of revenue)
Top vendorEcho Lake Foods (co-packer)
Cheese pricingBongards: CME trailing week avg + 35% moisture premium
USDA programsBarrel cheddar FIFO drawdown, commodity cheese allocation
Rebate programGood 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 Parts976 (85%)
Assembly70 (6%)
Service49 (4%)
Frozen48% · Dry 26% · Refrigerated 5%
Top brandsRight 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 procedure226 of 283 (80%)
Actively dunned32 customers
Level 5 (final)6 (incl Good Eats)
Level 4 (critical)2 (incl Mivila)
Level 2-320
Issue: Dual dunning (day-based + level-based) both active simultaneously

NS Edition & Features

EditionMid-Market
Subsidiary1 (no OneWorld)
Currencies4 configured, USD only used
Active bundles15
Unused bundles6 (intl tax)
API tokens2 active, 9 revoked
Custom fields414 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)

!
Custom domain SSL
!
SuiteAPI live sync (Worker cron → RESTlet)
!
Email daily report (CF Email)
!
KV cache for hot KPIs
!
USDA price feed cron
!
Anomaly detection cron
Workers AI (NL → D1 queries)
GFS Hub Suitelet (SuiteFrame)
6 Suitelet views (see below)
5 MCP Custom Tools
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
Test all 20 GFS queries

Sprint 3-4: Hub Shell

GFS Hub Suitelet (SuiteFrame)
GET routing to views
Attio CSS + mobile responsive
Center Tab in NS nav
Export CSV + Print

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

Test N/llm availability
Prompt Studio templates
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
Morning email summary

Sprint 11-12: MCP + Polish

5 Custom Tool scripts
Connect to Claude Code
Dark mode toggle
UAT with all roles

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)

ToolInputOutput
gfs_get_customer_360customer nameAR, revenue, margin, rebate, last order
gfs_get_pricescommoditybarrel/block price, spread, trend, AI summary
gfs_query_salesdate range, customerrevenue, order count, top items
gfs_check_rebatecustomer, order linestier, progress, projected date
gfs_run_querySQL stringresults (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

Glossary

TermDefinition
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.tsWorker (20 eps)
schema.sql18 tables
sql/45 loader files
docs/9 research docs
guide/System guide
*.shsync + report

Template Review 2026/

Data-Exports/134 files (40MB)
Email-Templates/53 templates
PDF-HTML-Templates/54 XML
PDF/HTML Layouts29 layouts
Reference/24 files
Schema-Browser/24 schemas

NetSuite Tools

Chartstone Prolocalhost
SuiteQL #2947Suitelet
SuiteAPI #2948RESTlet
Toolkit #2949Suitelet
SuiteAttachRESTlet
60+ toolspages.dev

Cloudflare

Workergfs-platform
D1gfs-netsuite
KV + R2CACHE + gfs-files
Pages16 projects
Domainai-globalfoodsolutions.co
Crons2 active

Sitemap & Project Map

Deployed Pages (gfs-system-guide.pages.dev)

/Master Guide (69KB)
/databaseDB Wiki (29KB)
/apiAPI Docs (14KB)
/workflowsFlowcharts (32KB)
/infrastructureInfra (14KB)
/master12-Tab Guide (46KB)
/infrastructure-dashboardLive Health (20KB)
/executive-dashboardKPI Dashboard (19KB)
/docs/04-Power-Tools60+ Tools (51KB)
/diagrams/system-architectureArchify Dataflow (51KB)
/diagrams/order-to-cashArchify O2C (43KB)
/styles.cssShared 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
API Health · Pages · CF Dashboard · NetSuite