PageSourceSearch

https://tariffrecoveryagency.com/assets/PartnerWhitePaper-DXrveDfU.js

js tariffrecoveryagency.com collected 2026-10-01 23:58:04 UTC 131,417 bytes, 177 lines download raw bytes

1import{j as e}from"./vendor-query-DUki8u-D.js";import{r as d}from"./vendor-react-DHU755GE.js";import{T as M,o as k,I as B,B as U}from"./App-DNURBdOM.js";import{C as H,c as G}from"./card-B_TKe1rC.js";import{S as j}from"./separator-BGBKlkSh.js";import{supabase as V}from"./client-Dy2P3he-.js";import{S as O,bB as Y,T as E,z as P,Q as W,v as _,an as w,as as N,bC as T,a as A,F as C,i as R,_ as b,B as I,ah as S,s as D,N as z,I as $,G as L,bD as F,Z as X,$ as K,n as Q,d as J,O as Z,bE as ee,J as se,L as te}from"./vendor-icons-D7GmeyGG.js";import"./vendor-pdf-DHUBMtDJ.js";import"./error-reporter-EYiXaqJQ.js";import"./breadcrumbs-CN3GC8vy.js";import"./vendor-charts-DsctC1NR.js";import"./useTheme-DEq4C3Xf.js";import"./vendor-supabase-D2XPrbcR.js";import"./vendor-motion-DoyUfQ58.js";const ie=["All","Platform","Data","Security","Integration","Financial","Funding","Operations","Reference"],ae=`
2.tok-cb { color: hsl(210 40% 94%); }
3.tok-cb .tok-key { color: hsl(199 90% 72%); }
4.tok-cb .tok-str { color: hsl(95 55% 72%); }
5.tok-cb .tok-num { color: hsl(35 90% 70%); }
6.tok-cb .tok-bool { color: hsl(280 75% 78%); }
7.tok-cb .tok-kw { color: hsl(330 75% 78%); font-weight: 600; }
8.tok-cb .tok-type { color: hsl(180 70% 72%); }
9.tok-cb .tok-fn { color: hsl(50 95% 75%); }
10.tok-cb .tok-cmt { color: hsl(220 15% 58%); font-style: italic; }
11.tok-cb .tok-pn { color: hsl(210 30% 82%); }
12.tok-cb .tok-id { color: hsl(210 40% 94%); }
13`,y=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ne=/\b(CREATE|TABLE|FUNCTION|RETURNS|LANGUAGE|STABLE|VOLATILE|SECURITY|DEFINER|INVOKER|SET|AS|SELECT|FROM|WHERE|EXISTS|AND|OR|NOT|INSERT|INTO|VALUES|UPDATE|DELETE|JOIN|LEFT|RIGHT|INNER|OUTER|ON|GROUP|BY|ORDER|LIMIT|RETURN|IF|THEN|ELSE|END|BEGIN|DECLARE|TRIGGER|BEFORE|AFTER|FOR|EACH|ROW|EXECUTE|REFERENCES|PRIMARY|KEY|UNIQUE|DEFAULT|NULL|NOT\s+NULL|ENABLE|POLICY|USING|WITH|CHECK|TO|AUTHENTICATED|GRANT|ALTER|ADD|COLUMN|DROP|TYPE|ENUM|REPLACE|OR\s+REPLACE)\b/g,re=/\b(uuid|text|boolean|integer|int|bigint|numeric|date|timestamp|timestamptz|jsonb|json|app_role|trigger|void|record)\b/gi,oe=/\b(import|from|export|const|let|var|function|return|if|else|for|while|switch|case|break|continue|new|class|extends|implements|interface|type|enum|public|private|protected|readonly|async|await|try|catch|finally|throw|typeof|instanceof|in|of|as|null|undefined|void|never|this|super)\b/g,le=/\b(string|number|boolean|any|unknown|object|Array|Record|Promise|Map|Set|Date|JSX)\b/g;function de(n,a){if(a==="json"){let s=y(n);return s=s.replace(/("(?:\\.|[^"\\])*")(\s*:)/g,'<span class="tok-key">$1</span><span class="tok-pn">$2</span>'),s=s.replace(new RegExp('(?<!\\w)("(?:\\\\.|[^"\\\\])*")(?!\\s*:)',"g"),'<span class="tok-str">$1</span>'),s=s.replace(/\b(true|false|null)\b/g,'<span class="tok-bool">$1</span>'),s=s.replace(/\b(-?\d+(?:\.\d+)?)\b/g,'<span class="tok-num">$1</span>'),s=s.replace(/([{}\[\],])/g,'<span class="tok-pn">$1</span>'),s}if(a==="sql"){let s=y(n);return s=s.replace(/(--[^\n]*)/g,'<span class="tok-cmt">$1</span>'),s=s.replace(/('(?:''|[^'])*')/g,'<span class="tok-str">$1</span>'),s=s.replace(ne,'<span class="tok-kw">$1</span>'),s=s.replace(re,'<span class="tok-type">$1</span>'),s=s.replace(/\b(\d+)\b/g,'<span class="tok-num">$1</span>'),s=s.replace(/(\$\$|\(|\)|,|;)/g,'<span class="tok-pn">$1</span>'),s}if(a==="ts"||a==="tsx"||a==="typescript"||a==="javascript"||a==="js"){let s=y(n);return s=s.replace(/(\/\/[^\n]*)/g,'<span class="tok-cmt">$1</span>'),s=s.replace(/(\/\*[\s\S]*?\*\/)/g,'<span class="tok-cmt">$1</span>'),s=s.replace(/(`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,'<span class="tok-str">$1</span>'),s=s.replace(oe,'<span class="tok-kw">$1</span>'),s=s.replace(le,'<span class="tok-type">$1</span>'),s=s.replace(/\b(\d+(?:\.\d+)?)\b/g,'<span class="tok-num">$1</span>'),s=s.replace(/\b([a-zA-Z_]\w*)(?=\s*\()/g,'<span class="tok-fn">$1</span>'),s}if(a==="bash"||a==="shell"||a==="sh"){let s=y(n);return s=s.replace(/(#[^\n]*)/g,'<span class="tok-cmt">$1</span>'),s=s.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g,'<span class="tok-str">$1</span>'),s=s.replace(/(\$\w+|\$\{[^}]+\})/g,'<span class="tok-key">$1</span>'),s=s.replace(/^(\s*)([a-zA-Z_][\w-]*)/gm,'$1<span class="tok-fn">
13$2</span>'),s}let r=y(n);return r=r.replace(/([├│└─])/g,'<span class="tok-pn">$1</span>'),r}const c=({code:n,language:a="json"})=>e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:ae}}),e.jsx("pre",{className:"tok-cb bg-[hsl(222,47%,8%)] rounded-lg p-4 overflow-x-auto text-xs leading-relaxed font-mono border border-[hsl(222,30%,18%)]",children:e.jsx("code",{dangerouslySetInnerHTML:{__html:de(n,a)}})})]}),t=({headers:n,rows:a})=>e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-muted/50",children:n.map((r,s)=>e.jsx("th",{className:"text-left px-3 py-2 font-semibold text-foreground border-b border-border",children:r},s))})}),e.jsx("tbody",{children:a.map((r,s)=>e.jsx("tr",{className:s%2===0?"bg-card":"bg-muted/20",children:r.map((u,p)=>e.jsx("td",{className:"px-3 py-2 text-muted-foreground border-b border-border/50",children:u},p))},s))})]})}),l=({type:n="info",children:a})=>{const r={info:"border-primary/30 bg-primary/5 text-primary",warning:"border-gold/30 bg-gold/5 text-gold",success:"border-success/30 bg-success/5 text-success"};return e.jsx("div",{className:`rounded-lg border p-4 text-sm ${r[n]}`,children:a})},ce=()=>[{id:"production-considerations",title:"Production Considerations & Known Gaps",category:"Platform",icon:e.jsx(E,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx(l,{type:"warning",children:"This section is the live audit ledger. Anything documented here is a constraint, risk, or operational rule that integrators MUST respect. Treat each item as binding until the platform team marks it resolved in the Change Log."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Audit findings — v3.0 release"}),e.jsx(t,{headers:["Area","Finding / Rule","Status"],rows:[["Versioning","Doc previously drifted (v2.0 in body, v3.0 in references). Header & footer now anchored to v3.0 • May 2026.","Resolved"],["Edge functions","Function count corrected to 136 deployed (was '40+'). See Edge Functions Reference for full inventory.","Resolved"],["Funding ecosystem","Phases 1–6 (prequal → discover → offers → counters → deals → settlements → analytics) shipped. Documented under Funding Ecosystem + Funder Portal.","Resolved"],["Anchor integration","Production push uses service-to-service auth, HMAC-signed webhook ingress, idempotency keys. Now documented in Anchor Deep Dive.","Resolved"],["Commission waterfall","Refund → Contingency → Reserve → Brokers → Partner Pool → TRA Retained. Per-claim override supported. See Commission Waterfall Reference.","Resolved"],["Cascading pool comp","Grantor pool can sub-allocate to invitees with ≥5% min spread; cascades upward. See Cascading Pool Comp Model.","Resolved"],["Est. IEEPA recovery","MUST use getEstRecovery() from src/lib/lead-est-recovery.ts — never compute inline.","Enforced"],["Consulting Agreement","ENGAGEMENT_HTML body is verbatim attorney-final 04.22.26. IMMUTABLE — only token substitutions allowed.","Enforced"],["Contingency % source","Pulled ONLY from Admin Settings default_engagement_fee_pct, never from claim_details columns.","Enforced"],["TRA House Root","Affiliate id 5637507e… is the 'no sponsor' placeholder. pool_grantor_id MUST be NULL when sponsor is house.","Enforced"],["Address / Phone / Email","All forms MUST use AddressAutocomplete + PhoneInput + EmailInput (validated-inputs).","Enforced"],["Entity pickers","MUST use SearchableSelect and filter by useDataMode().dataSourceFilter — Live mode never lists sandbox rows.","Enforced"],["RPA tagging","Every Skyvern job MUST be tagged Live or Simulated.","Enforced"],["Guest submissions","Guest form inserts MUST pass user_id: null explicitly to bypass RLS errors.","Enforced"],["data_source filter","Use .in('data_source', [...]) — never .eq when new tags are added.","Enforced"],["Admin claim table","Filters must normalize via normalizeLeadStatus; status dropdowns hide RETIRED_STATUS_MAP keys.","Enforced"],["Marketing Header","Light over hero, dark in sticky bar. Driven by scroll, NEVER by isGold theme.","Enforced"],["Password gate","verify-docs-password edge function gates this doc. Rotate the secret quarterly or after any partner offboarding.","Operational"],["Database Schema Reference","Funding tables (23 tables: funders, funder_offers, funding_deals, funding_settlements, …) added.","Resolved"],["Code blocks","Low-contrast plain text replaced with token-colored syntax highlighting on the same dark background.","Resolved"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Open risks for partner integrators"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Schema evolution:"})," 23 funding-domain tables landed in May 2026. Re-pull Database Schema Reference after every minor version bump."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Eventual consistency on push-claim:"})," Anchor acknowledges receipt synchronously but state changes propagate via webhook — never assume terminal status from the push response."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Idempotency:"})," Partner webhook handlers MUST treat (event_id, lead_id) as the idempotency key. Retries are inevitable."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"HMAC clock skew:"})," Reject webhook signatures older than 5 minutes (timestamp in signature header)."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Sandbox isolation:"})," data_source IN ('seed','sandbox','demo') rows are invisible in Live mode by design — do not query around the filter."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Cloud lifecycle:"})," ACTIVE_HEALTHY is the only safe state for migrations. See Operational Runbooks."]})]})]})},{id:"executive-summary",title:"Executive Summary",category:"Platform",icon:e.jsx(P,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"This platform is a purpose-built, end-to-e
13nd tariff refund claim management system designed to process IEEPA (International Emergency Economic Powers Act) duty recovery claims filed with U.S. Customs and Border Protection (CBP). The system manages the complete claim lifecycle — from initial lead intake through document collection, eligibility analysis, CAPE batch submission, protest/CIT litigation, refund disbursement, and financial reconciliation."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Business Model"}),e.jsx("p",{children:"The platform operates on a contingency-fee model. Importers who have overpaid duties on goods subject to IEEPA tariffs engage the platform operator to file refund claims on their behalf. The operator earns a percentage of recovered duties as a service fee. Additionally, the platform supports advance funding, where importers can receive a percentage of their estimated refund prior to CBP disbursement."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Technology Stack"}),e.jsx(t,{headers:["Layer","Technology","Purpose"],rows:[["Frontend","React 18 + TypeScript + Vite 5","Single-page application with lazy-loaded portals"],["Styling","Tailwind CSS v3 + shadcn/ui","Design system with HSL-based semantic tokens"],["State","TanStack React Query v5","Server state management with 5-min stale time"],["Backend","Supabase (PostgreSQL 15)","Database, Auth, Storage, Edge Functions, Realtime"],["Auth","Supabase Auth + RLS","JWT-based auth with row-level security on all tables"],["Edge Functions","Deno runtime (136 functions)","Serverless compute for ETL, AI, email, RPA, payments, funding"],["Cloud","Lovable Cloud (managed Supabase)","Single-vendor backend with vault, pg_cron, pgmq, Realtime"],["AI","Lovable AI Gateway","Multi-model access (Gemini, GPT-5) without API key management"],["RPA","Skyvern","Browser automation for ACE portal interactions"],["Email","pgmq-based queue","Transactional and campaign email with suppression handling"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Portal Structure"}),e.jsx("p",{children:"The platform serves four distinct user audiences through dedicated portal experiences:"}),e.jsx(t,{headers:["Portal","Route","Audience","Key Functions"],rows:[["Admin Portal","/command/*","Internal operators","Full CRM, pipeline, CAPE filing, RPA, intelligence"],["Client Portal","/client/*","Importers/claimants","Claim status, document upload, messaging, e-sign"],["Broker Portal","/brokers/*","Licensed customs brokers","Client management, claim tracking, commissions"],["Partner Portal","/partner/*","Referral affiliates","Lead submission, commission tracking, marketing"],["Funder Portal","/funding/*","Capital partners / funders","Claim discovery, offer issuance, deals, settlements, portfolio analytics"]]})]})},{id:"platform-architecture",title:"Platform Architecture",category:"Platform",icon:e.jsx(W,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The application follows a client-side SPA architecture with a PostgreSQL backend exposed through auto-generated REST and Realtime APIs. All business logic that requires elevated privileges runs in Deno-based edge functions."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Frontend Architecture"}),e.jsx(c,{language:"text",code:`App.tsx (root)
14├── ErrorBoundary
15├── HelmetProvider (SEO)
16├── QueryClientProvider (React Query)
17├── AuthProvider (session + role context)
18├── TenantProvider (multi-tenant white-label)
19├── LocaleProvider (i18n)
20├── BrowserRouter
21│   ├── Public Marketing Routes (eagerly loaded)
22│   │   ├── / (Index)
23│   │   ├── /apply (Intake Wizard)
24│   │   ├── /login
25│   │   └── /tariff-refund/* (Pillar pages)
26│   ├── Client Portal (/client/*) — lazy loaded
27│   ├── Broker Portal (/brokers/*) — lazy loaded
28│   ├── Partner Portal (/partner/*) — lazy loaded
29│   ├── Funder Portal (/funding/*) — lazy loaded
30│   └── Admin Portal (/command/*) — lazy loaded`}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Backend Architecture"}),e.jsx(c,{language:"text",code:`Supabase Project
31├── PostgreSQL 15
32│   ├── 60+ tables with RLS enabled
33│   ├── 25+ database functions (SECURITY DEFINER)
34│   ├── 15+ triggers (auto-calc, auto-advance, audit)
35│   └── pgmq extension (email queue)
36├── Auth
37│   ├── Email/password + Google OAuth
38│   ├── Custom email templates via auth-email-hook
39│   └── Role assignment on signup (handle_new_user trigger)
40├── Storage
41│   ├── lead-documents (private, RLS)
42│   ├── article-images (public)
43│   ├── og-images (public)
44│   └── company-assets (public)
45└── Edge Functions (136 deployed)
46    ├── ETL: etl-ace-report, parse-ace-report
47    ├── AI: tariff-chat, tariff-intelligence, evaluate-theories
48    ├── Email: process-email-queue, send-transactional-email
49    ├── Filing: generate-cape-csv, generate-protest-package
50    └── Integration: push-claim, partner-webhook, pull-partner-status`}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Data Flow"}),e.jsx("p",{children:"All client-side data access goes through the Supabase JS client, which automatically attaches JWT tokens and respects RLS policies. Edge functions use the service role key for privileged operations (ETL, email, RPA dispatch). Real-time updates are delivered via Supabase Realtime channels for messaging and status changes."})]})},{id:"user-roles",title:"User Roles & Access Control",category:"Security",icon:e.jsx(_,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["The platform implements a robust role-based access control (RBAC) system. Roles are stored in a dedicated ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"user_roles"})," table (never on the user profile) to prevent privilege escalation."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Role Definitions"}),e.jsx(t,{headers:["Role","Enum Value","Assignment","Access Scope"],rows:[["Admin","admin","Manual assignment only","Full platform access — all tables, all leads, all functions"],["Client","client","Auto-assigned on signup (default)","Own leads, own documents, own claims only"],["Broker","broker","Auto-assigned when email matches brokers table","Linked client leads via broker_clients table"],["Affiliate","affiliate","Auto-assigned when email matches affiliates table","Own referred leads, commission data, marketing assets"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Role Check Function"}),e.jsx(c,{language:"sql",code:`CREATE FUNCTION public.has_role(_user_id uuid, _role app_role)
51RETURNS boolean
52LANGUAGE sql STABLE SECURITY DEFINER
53SET search_path = public
54AS $$
55  SELECT EXISTS (
56    SELECT 1 FROM public.user_roles
57    WHERE user_id = _user_id AND role = _role
58  )
59$$;`}),e.jsxs("p",{children:["This function is ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"SECURITY DEFINER"})," to bypass RLS on the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"user_roles"})," table itself, preventing recursive policy evaluation."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"RLS Policy Pattern"}),e.jsx("p",{children:"Every table with user-scoped data implements RLS policies using helper functions:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"get_user_lead_ids(auth.uid())"})," — returns lead IDs owned by the current user"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"get_broker_lead_ids(auth.uid())"})," — returns lead IDs linked to the broker's clients"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"has_role(auth.uid(), 'admin')"})," — grants admin full access"]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Assignment on Signup"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"handle_new_user()"})," trigger fires on ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auth.users INSERT"})," and:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Creates a profile row"}),e.jsxs("li",{children:["Checks if the email exists in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"affiliates"})," → assigns affiliate role"]}),e.jsxs("li",{children:["Checks if the email exists in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"brokers"})," → assigns broker role"]}),e.jsx("li",{children:"Otherwise assigns client role (default)"}),e.jsxs("li",{children:["Links any existing leads with matching email via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"link_leads_to_user()"})]})]})]})},{id:"client-onboarding",title:"Client Onboarding Flow",category:"Operations",icon:e.jsx(w,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The client onboarding process is a multi-step wizard that captures essential company and import information, then automatically provisions all required database records for claim processing."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Intake Wizard Steps"}),e.jsx(t,{headers:["Step","Fields Collected","Validation"],rows:[["1. Company Info","Company name, DBA, EIN, address, phone","EIN format XX-XXXXXXX"],["2. Contact Info","Primary contact name/email/title, secondary contact","Email format validation"],["3. Import Profile","Is IOR?, IOR numbers, broker names, import value 2025/2026","Required fields check"],["4. Tariff Exposure","IEEPA duties 2025/2026, countries, HTS concentration","Numeric validation"],["5. Operational Readiness","ACE access, records complete, liquidation tracking","Boolean selections"],["6. Engagement Interest","Sell interest, cash urgency, decision maker, cooperation level","Required selections"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Onboard Trigger"}),e.jsxs("p",{children:["When a new lead is inserted, the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_onboard_lead()"})," trigger automatically:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Creates a ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"claim_details"})," row with initial qualification score of 0"]}),e.jsx("li",{children:"Generates 8 required document checklist items (CBP 7501, commercial invoice, packing list, bill of lading, ACE data, duty payment proof, POA, ACH enrollment)"}),e.jsx("li",{children:'Creates an initial timeline event ("Application submitted")'})]}),e.jsxs(l,{type:"info",children:["The qualification score is automatically recomputed by the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_recompute_qualification"})," trigger whenever claim entries or lead fields change. Scores range from 0–100 and drive the priority classification (high/medium/low)."]})]})},{id:"claim-lifecycle",title:"Claim Lifecycle & Pipeline",category:"Operations",icon:e.jsx(w,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"Every claim progresses through a 20-stage pipeline. Several transitions are automated by database triggers, while others require manual advancement by administrators."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Pipeline Stages"}),e.jsx(t,{headers:["Stage","Label","Trigger","Description"],rows:[["new","New Lead","Manual (intake form)","Initial application received"],["account_created","Account Created","Auto (signup)","Client has created login credentials"],["application_in_progress","Application In Progress","Auto (signup → claim opens)","Client is filling out company/import details"],["agreements_pending","Agreements Pending","Manual (admin sends)","E-sign agreements sent to client"],["documents_pending","Documents Pending","Auto (agreements signed)","Awaiting customs document upload from client"],["identity_verification_required","Identity Verification Required","Auto (docs uploaded)","Client must complete identity verification"],["identity_verification_in_progress","Identity Verification In Progress","Auto (KYC started)","Identity check underway / pending review"],["ace_access_pending","ACE Access — Pending","Auto (identity verified)","Awaiting ACE Portal delegation"],["ready_for_review","Ready for Review","Manual (admin sets)","Queued for analyst review"],["in_review","In Review","Manual (analyst picks up)","Analyst reviewing entr
59ies/docs"],["approved","Approved","Manual (analyst approves)","Claim approved for filing"],["filed_with_cbp","Filed with CBP","Manual (after CAPE submit)","CAPE declaration submitted to CBP"],["protest_filed","Protest Filed","Manual (protest generated)","CBP protest filed within 180-day window"],["protest_denied","Protest Denied","Manual (CBP response)","CBP denied the protest"],["further_review","Further Review","Manual","Requires additional analysis"],["cit_filed","CIT Filed","Manual (summons filed)","Court of International Trade case filed"],["cit_resolved","CIT Resolved","Manual (judgment/settlement)","CIT case concluded"],["refund_received","Refund Received","Manual (CBP disburse)","CBP has disbursed the refund via ACH"],["closed_paid","Closed — Paid","Manual (final accounting)","All fees collected, case closed"],["disqualified","Disqualified","Manual","Claim does not meet eligibility requirements"],["closed_lost","Closed Lost","Manual","Client withdrew or claim abandoned"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Advancement Triggers"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_advance_claim_status()"})," trigger monitors:"]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Agreements:"})," When all non-voided agreements are signed → advances to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"documents_pending"})]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Documents:"})," When all required checklist items are complete → advances to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"identity_verification_required"})]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Identity:"})," When verification succeeds → advances to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ace_access_pending"})]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Commission Trigger"}),e.jsxs("p",{children:["When status changes to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"refund_received"}),", the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_create_commission_on_refund()"})," trigger automatically creates commission records for linked brokers and affiliates based on configured rates."]})]})},{id:"entry-data-model",title:"Entry-Level Data Model",category:"Data",icon:e.jsx(N,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["The core data model centers on two tables: ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"claim_entries"})," (entry summaries) and ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"entry_lines"})," (individual line items within each entry). This mirrors the CBP data structure where each customs entry contains multiple line items, each with its own HTS code and duty amounts."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"claim_entries — Key Fields"}),e.jsx(t,{headers:["Column","Type","Description"],rows:[["entry_number","text","11-digit CBP entry number (MOD-10 validated)"],["entry_date","date","Date goods were entered into U.S. commerce"],["entry_type","text","CBP entry type code (01=consumption, 06=FTZ, etc.)"],["country_of_origin","text","ISO country code or name"],["port_of_entry","text","CBP port code"],["importer_of_record","text","IOR number (EIN format XX-XXXXXXX)"],["total_duties","numeric","Sum of all duties on this entry"],["ieepa_dut
59ies","numeric","IEEPA-specific duty amount"],["section_301_duties","numeric","Section 301 tariff amount"],["section_232_duties","numeric","Section 232 tariff amount"],["regular_duties","numeric","Standard MFN duty amount"],["mpf","numeric","Merchandise Processing Fee"],["hmf","numeric","Harbor Maintenance Fee"],["has_ad_cvd","boolean","Flags AD/CVD duties (excluded from CAPE Phase 1)"],["entered_value","numeric","Auto-aggregated from entry_lines"],["liquidation_status","text","unliquidated | liquidated | deemed_liquidated | suspended"],["liquidation_date","date","Date of liquidation (triggers protest deadline calc)"],["protest_deadline","date","Auto-calc: liquidation_date + 180 days"],["data_source","text","manual | ace_import | seeded | partner_sync"],["form_4811_status","text","not_required | required | filed | approved"],["interest_accrued","numeric","6% annual interest on refund amount"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"entry_lines — Key Fields"}),e.jsx(t,{headers:["Column","Type","Description"],rows:[["hts_code","text","Harmonized Tariff Schedule code (10-digit)"],["description","text","Line item description"],["entered_value","numeric","Declared customs value"],["duty_rate","numeric","Applied duty rate percentage"],["duty_amount","numeric","Calculated duty for this line"],["ieepa_rate","numeric","IEEPA surcharge rate"],["ieepa_amount","numeric","IEEPA duty for this line"],["country_of_origin","text","Country for this specific line"],["ad_cvd_flag","boolean","Whether this line has AD/CVD orders"],["ad_cvd_case_number","text","AD/CVD case reference"],["ad_cvd_duty_amount","numeric","AD/CVD duty amount"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Calculation Triggers"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_calc_entered_value"})," — Sums entry_lines.entered_value → claim_entries.entered_value"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_set_ad_cvd_flag"})," — Sets claim_entries.has_ad_cvd when any line has AD/CVD"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_calc_protest_deadline"})," — Computes protest_deadline (180 days) and cit_summons_deadline (180 days) from dates"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_recompute_qualification"})," — Recalculates qualification score on entry changes"]})]})]})},{id:"ace-integration",title:"ACE Portal Integration",category:"Integration",icon:e.jsx(T,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The Automated Commercial Environment (ACE) is CBP's primary system for trade data. The platform integrates with ACE through two mechanisms: manual CSV upload (ES-003 reports) and RPA-based automated portal access."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"ES-003 CSV ETL Pipeline"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"etl-ace-report"})," edge function parses ACE ES-003 Entry Summary reports:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Client uploads CSV via the Client Portal or Broker Portal"}),e.jsx("li",{children:"Edge function validates headers and row structure"}),e.jsxs("li",{children:["Parses each row into ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"claim_entries"})," with all duty columns mapped"]}),e.jsxs("li",{children:["Detects AD/CVD lines and sets ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"has_ad_cvd = true"})]}),e.jsxs("li",{children:["Sets ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"data_source = 'ace_import'"})," on all imported entries"]}),e.jsx("li",{children:"Triggers qualification score recomputation"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"ACE Account Management"}),e.jsxs("p",{children:["Each lead has an associated ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ace_accounts"})," record tracking:"]}),e.jsx(t,{headers:["Field","Purpose"],rows:[["ace_account_number","Client's ACE portal account ID"],["verification_status","pen
59ding → verified → suspended"],["ach_enrolled / ach_verified_at","Whether client is enrolled for electronic refund disbursement"],["edis_enrolled / edis_verified_at","eDIS (Electronic Disbursement) enrollment status"],["bond_number / bond_type / bond_amount","Customs bond details (continuous vs single-transaction)"],["bond_surety / bond_expiry","Bond surety company and expiration date"],["portal_username","ACE portal login (for RPA automation)"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Credential Security"}),e.jsxs("p",{children:["ACE portal credentials are stored in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ace_credentials"})," with AES-256-GCM encryption. The encryption key is stored as a Supabase secret (",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ACE_ENCRYPTION_KEY"}),") and never exposed to the client. Credential management is handled through the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"manage-ace-credentials"})," edge function."]})]})},{id:"ieepa-eligibility",title:"IEEPA Eligibility & Validation",category:"Data",icon:e.jsx(A,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform implements comprehensive IEEPA eligibility validation to ensure only qualified entries are included in CAPE filings. Validation runs both client-side (in the UI) and server-side (in database functions and edge functions)."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"IEEPA Coverage Periods by Country"}),e.jsx(t,{headers:["Country/Region","Effective Date","End Date","Rate"],rows:[["China (CN) + Hong Kong (HK)","February 4, 2025","February 24, 2026","Up to 145%"],["Canada (CA)","March 4, 2025","February 24, 2026","25%"],["Mexico (MX)","March 4, 2025","February 24, 2026","25%"],["All Other Countries","April 5, 2025","February 24, 2026","10% baseline"]]}),e.jsx(l,{type:"warning",children:"Entries with dates outside the applicable coverage window for their country of origin are automatically excluded from CAPE batch generation."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Exclusion Rules (CAPE Phase 1)"}),e.jsx(t,{headers:["Rule","Excluded Entry Types","Reason"],rows:[["FTZ Entries","Type 06","Foreign Trade Zone entries have different duty treatment"],["Warehouse Entries","Types 21, 22, 23","Bonded warehouse entries follow separate procedures"],["AD/CVD Entries","Any with has_ad_cvd=true","Antidumping/Countervailing duty entries require separate filings"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Validation Function"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"compute_entry_eligibility(entry_id)"})," database function returns a comprehensive eligibility assessment:"]}),e.jsx(c,{code:`{
60  "entry_id": "uuid",
61  "ace_ready": true,
62  "ach_ready": true,
63  "submission_ready": true,
64  "exclusion_reasons": [],
65  "cape": { "eligible": true, "reason": "IEEPA duties present, entry liquidated" },
66  "psc": { "eligible": false, "reason": "Entry already liquidated" },
67  "protest": { "eligible": true, "reason": "Within 180-day window (deadline: 2026-06-15)" },
68  "cit": { "eligible": false, "reason": "No protest denial" }
69}`})]})},{id:"cape-filing",title:"CAPE Filing System",category:"Operations",icon:e.jsx(C,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"CAPE (Customs Automated Protest and Entry) is CBP's system for processing bulk refund claims. The platform manages the end-to-end CAPE batch lifecycle from CSV generation through submission tracking and result reconciliation."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"CAPE Batch Lifecycle"}),e.jsx(t,{headers:["Status","Description","Next Action"],rows:[["draft","Batch created, entries selected","Review & generate CSV"],["csv_generated","CAPE-format CSV ready for download","Upload to CBP ACE portal"],["submitted","CSV submitted to CBP via ACE","Wait for acceptance"],["accepted","CBP accepted the batch for processing","Monitor for completion"],["completed","CBP processed — refund approved","Reconcile amounts"],["rejected","CBP rejected the batch","Review reason, correct, resubmit"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Readiness Checklist"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"check_submission_readiness(lead_id)"})," function validates:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"ACE account verified"}),e.jsx("li",{children:"ACH refund enrollment confirmed"}),e.jsx("li",{children:"ACH enrollment verified (with timestamp)"}),e.jsx("li",{children:"eDIS enrolled"}),e.jsx("li",{children:"Valid signed Power of Attorney (not expired)"}),e.jsx("li",{children:"Customs bond on file and not expired"}),e.jsx("li",{children:"CBP Form 4811 filed (if required)"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"CSV Generation"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"generate-cape-csv"})," edge function:"]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Filters entries using all P0 exclusion rules (AD/CVD, entry type, date coverage)"}),e.jsx("li",{children:"Formats data per CBP CAPE specification"}),e.jsx("li",{children:"Calculates 6% annual interest on each entry"}),e.jsx("li",{children:"Generates downloadable CSV file"}),e.jsxs("li",{children:["Creates a ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"cape_batches"})," record linking to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"cape_batch_entries"})]})]})]})},{id:"protest-cit",title:"Protest & CIT Workflow",category:"Operations",icon:e.jsx(E,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"When CAPE claims are denied or when entries are liquidated at a higher rate than expected, the platform supports formal CBP protest filing and escalation to the Court of International Trade (CIT)."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Protest System"}),e.jsx(t,{headers:["Feature","Implementation"],rows:[["Deadline Calculation","auto_calc_protest_deadline trigger: liquidation_date + 180 days"],["Package Generation","generate-protest-package edge function creates CBP Form 19 with legal arguments"],["Multi-Entry Grouping","Protests can group multiple entries via protest_entries junction table"],["Status Tracking","draft → filed → pending_response → approved → denied → withdrawn"],["Denial Handling","Triggers CIT summons deadline calculation (180 days from denial)"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"CIT Case Manager"}),e.jsx(t,{headers:["Field","Purpose"],rows:[["case_number","CIT docket number"],["court","Default: Court of International Trade"],["counsel_name/firm/email/phone","Outside counsel contact information"],["filing_date","Date summons was filed"],["discovery_deadline","Discovery cutoff date"],["trial_date","Scheduled trial date"],["settlement_amount / settlement_date","If settled before trial"],["judgment_amount / judgment_date","If decided by the court"],["appeal_filed / appeal_deadline","Federal Circuit appeal tracking"]]})]})},{id:"document-management",title:"Document Management",category:"Operations",icon:e.jsx(C,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform implements a comprehensive document collection system with automated tracking, guided uploads, and completion verification."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Document Checklist Items"}),e.jsx(t,{headers:["Item Key","Label","Required"],rows:[["cbp_7501","CBP Form 7501 (Entry Summary)","Yes"],["commercial_invoice","Commercial Invoice","Yes"],["packing_list","Packing List","Yes"],["bill_of_lading","Bill of Lading / Airway Bill","Yes"],["ace_data","ACE Portal Entry Data (ES-003)","Yes"],["duty_payment_proof","Proof of Duty Payment","Yes"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Completion Trigger"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_complete_checklist_on_doc()"})," trigger fires on document upload and:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Matches by explicit ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"checklist_item_id"})," if provided"]}),e.jsxs("li",{children:["Falls back to matching by ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"document_type"})," ↔ ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"item_key"})]}),e.jsx("li",{children:"Marks the checklist item as complete with timestamp"}),e.jsx("li",{children:"Links the uploaded file to the checklist item"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Storage Architecture"}),e.jsxs("p",{children:["Documents are stored in the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"lead-documents"})," private bucket with RLS policies ensuring only authenticated users with access to the specific lead can view files. Files are organized by lead ID: ",e.jsxs("code",{className:"bg-muted px-1 rounded text-xs",children:["lead-documents/","{lead_id}","/","{filename}"]})]})]})},{id:"esign-system",title:"E-Sign & Agreement System",category:"Security",icon:e.jsx(R,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform includes a built-in electronic signature system compliant with E-SIGN Act and UETA requirements. Agreements are managed through templates, signed with a canvas-based signature pad, and stored with a complete audit trail."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Agreement Templates"}),e.jsx(t,{headers:["Template","Category","Required For"],rows:[["Contingency Fee Agreement","Client","All clients — engagement terms"],["Power of Attorney (POA)","Client","All clients — authorizes filing on behalf"],["Non-Disclosure Agreement","Client","All clients — confidentiality terms"],["Non-Circumvention Agreement","Client","All clients — prevents direct CBP filing"],["Authorization to Release","Client","All clients — allows CBP data access"],["Referral Partner Agreement","Partner","All affiliates"],["Broker Partner Agreement","Broker","All customs brokers"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Signature Capture"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"SignaturePad"})," component supports two modes:"]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Draw:"})," Canvas-based freehand signature (uses signature_pad library)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Type:"})," Typed name rendered in a signature font"]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Audit Trail"}),e.jsx("p",{children:"Each signed agreement records:"}),e.jsx(t,{headers:["Field","Purpose"],rows:[["signer_name","Full legal name of signer"],["signer_email","Email address (verified against auth)"],["signer_ip","IP address at time of signing"],["signature_data","JSONB: type (draw/type), data (base64 or text), user_agent"],["signed_at","Precise timestamp"],["viewed_at","When the agreement was first opened"],["document_hash","SHA-256 hash of agreement HTML at time of signing"]]})]})},{id:"financial-tracking",title:"Financial Tracking",category:"Financial",icon:e.jsx(b,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform tracks all financial aspects of claim processing, from estimated refund amounts through actual CBP disbur
69sements, interest calculations, and advance funding."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Interest Calculation"}),e.jsx("p",{children:"CBP pays interest on refunded duties at a statutory rate of 6% per annum. The platform calculates interest from the duty payment date to the expected refund date:"}),e.jsx(c,{code:`// Interest = Principal × Rate × (Days / 365)
70const interest = dutiesRefunded * 0.06 * (daysSincePayment / 365);`}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Advance Funding"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"advance_funding"})," table tracks pre-refund advances to clients:"]}),e.jsx(t,{headers:["Field","Purpose"],rows:[["estimated_recovery","Expected refund amount"],["advance_percentage","% of estimated recovery offered (default 75%)"],["advance_amount","Dollar amount advanced to client"],["discount_rate","Fee percentage charged for advance (default 10%)"],["net_to_client","Amount after discount"],["status","draft → approved → funded → repaid"],["funding_method / funding_reference","ACH transfer details"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Form 4811 Tracking"}),e.jsxs("p",{children:["CBP Form 4811 (Refund of Duties) is required when the importer of record uses a customs broker to receive refunds. The platform tracks this per entry with statuses: ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"not_required → required → filed → approved"}),"."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Customs Bond Tracking"}),e.jsx("p",{children:"Active customs bonds are required for import operations. The platform tracks bond number, type (continuous/single-transaction), amount, surety company, and expiration date. Expired bonds generate deadline alerts."})]})},{id:"commission-system",title:"Commission System",category:"Financial",icon:e.jsx(b,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform supports two independent commission structures — one for referral partners (affiliates) and one for customs brokers."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Affiliate Commission Structure"}),e.jsx(t,{headers:["Tier","Default Rate","Customizable","Description"],rows:[["Direct Referral","25%","Yes (per-affiliate override)","Paid to the affiliate who referred the lead"],["Upline Sponsor","5%","Yes (per-affiliate or per-invite)","Paid to the affiliate who recruited the referring affiliate"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Broker Commission Structure"}),e.jsx(t,{headers:["Model","Default","Description"],rows:[["Revenue Share","15% of refund","Percentage of actual recovery amount"],["Per-Claim Fee","$0 (configurable)","Flat fee per closed claim"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Auto-Commission Trigger"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auto_create_commission_on_refund()"})," trigger fires when a lead's status changes to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"refund_received"})," and:"]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Looks up the refund amount from ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"claim_details.actual_recovery"})]}),e.jsx("li",{children:"Creates broker commission records based on the broker's configured model"}),e.jsx("li",{children:"Creates affiliate direct commission using custom or global rate"}),e.jsx("li",{children:"Creates upline commission if the affiliate has an upline, using: invite rate → affiliate custom rate → global rate (priority cascade)"})]})]})},{id:"partner-broker-program",title:"Partner & Broker Program",category:"Integration",icon:e.jsx(I,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform supports two types of external partners: referral affiliates (who send leads) and licensed customs brokers (who manage client relationships and may act as IOR)."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Partner (Affiliate) Program"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Registration:"}
70)," Public signup form with name, email, phone, company, promotion method"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Approval:"})," Configurable — auto-approve or require admin approval (toggle in Settings)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Agreement Gate:"})," Partners must e-sign the Referral Partner Agreement before accessing the portal"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Custom Links:"})," Each partner gets a unique referral slug for tracking"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Network Building:"})," Partners can invite sub-affiliates with custom upline rates"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Payment Settings:"})," ACH bank details with routing number verification (API Ninjas ABA lookup)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"W-9 Certification:"})," Built-in W-9 data collection for 1099 reporting"]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Broker Program"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Registration:"})," Requires license number, license state, company details"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Tiers:"})," standard → preferred → elite (enum-based, affects commission rates)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Client Linking:"})," Bidirectional invitation system (broker invites client, or client invites broker)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"White-Label:"})," Full brand customization (logo, colors, domain, tagline, social links)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Bulk Import:"})," CSV import of client lists"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"ACE Upload:"})," Brokers can upload ACE reports on behalf of clients"]})]})]})},{id:"processing-integration",title:"3rd-Party Processing Integration",category:"Integration",icon:e.jsx(S,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform supports two-way data exchange with external processing partners (like Anchor) through API key management, field mapping, and webhook ingestion."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Partner Profile Management"}),e.jsxs("p",{children:["Each processing partner has a profile in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"processing_partners"})," with:"]}),e.jsx(t,{headers:["Field","Purpose"],rows:[["partner_name","Display name (e.g., 'Anchor')"],["api_base_url","Base URL for partner's API"],["webhook_url","URL we expose for inbound updates"],["webhook_secret","HMAC-SHA256 secret for webhook signature verification"],["field_mapping","JSONB mapping of our fields to partner's field names"],["status","active | inactive | testing"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Push-Claim Flow"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsx("li",{children:'Admin selects a claim and clicks "Push to Partner"'}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"push-claim"})," edge function aggregates data from 14+ tables"]}),e.jsx("li",{children:"Field mapping editor transforms our schema to partner's expected format"}),e.jsx("li",{children:"Payload is encrypted and sent via the partner's API"}),e.jsxs("li",{children:["Transaction is logged in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"partner_transactions"})]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Inbound Data Flow"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Webhooks:"})," ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"partner-webhook"})," edge function receives status updates, validates HMAC signature, updates claim status"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Polling:"})," ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"pull-partner-status"})," edge function periodically checks partner API for updates"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Transaction Log:"})," Full payload visibility with direction, status, and retry capabilities"]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"API Key Management"}),e.jsxs("p",{children:["Partner API keys are managed through the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"manage-partner-keys"})," edge function with AES-256-GCM encryption. Keys are never exposed to the frontend — only masked versions are displayed."]})]})},{id:"rpa-automation",title:"RPA & Automation",category:"Integration",icon:e.jsx(D,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform integrates with Skyvern for browser-based robotic process automation (RPA), primarily for automating interactions with the CBP ACE portal."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"RPA Job Types"}),e.jsx(t,{headers:["Job Type","Description","Automation Target"],rows:[["ace_login","Log into ACE portal","ACE Portal login page"],["download_es003","Download ES-003 report","ACE Reports section"],["check_liquidation","Check entry liquidation status","ACE Entry Summary"],["submit_cape","Upload CAPE CSV file","ACE CAPE module"],["verify_ach","Verify ACH enrollment status","ACE Account Settings"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Job Lifecycle"}),e.jsxs("p",{children:["Jobs are dispatched via the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"rpa-dispatch"})," edge function and tracked through: ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"queued → running → completed → failed"}),". Results (screenshots, extracted data) are stored and viewable in the RPA Result Viewer."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Environment Tagging"}),e.jsxs("p",{children:["All RPA jobs are tagged as either ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"live"})," or ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"simulated"})," to distinguish real ACE portal interactions from test runs."]})]})},{id:"intelligence",title:"Intelligence & Market Intel",category:"Operations",icon:e.jsx(z,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform includes AI-powered intelligence features for tariff monitoring, prospect enrichment, and strategic analysis."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Features"}),e.jsx(t,{headers:["Feature","Description","AI Model"],rows:[["Tariff Intelligence","Monitors tariff changes and generates strategic briefs","Lovable AI Gateway"],["Tariff Alert Feed","Real-time feed of tariff regulatory changes","Perplexity API"],["Strategic Briefs","Detailed analysis of tariff impacts on specific industries","Gemini/GPT"],["Prospect Enrichment","Auto-fills company data from web sources","Firecrawl + AI"],["SIC Code Dashboard","Industry classification analysis for targeting","Database aggregation"],["Action Manager","Tracks and assigns follow-up actions from intelligence findings","Manual + AI suggested"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Theory Evaluation"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"evaluate-theories"})," edge function uses AI to analyze legal theories for claim filings, assessing strength, precedent, and likelihood of success."]})]})},{id:"email-system",title:"Email System",category:"Operations",icon:e.jsx($,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform includes a full email infrastru
70cture with template management, transactional sending, queue processing, and suppression handling."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Transactional Email Types"}),e.jsx(t,{headers:["Template","Trigger","Purpose"],rows:[["Welcome","New account creation","Onboarding instructions and next steps"],["Status Change","Lead status update","Notifies client of claim progress"],["Agreement Ready","Agreement sent for signing","Prompts client to sign documents"],["Deadline Alert","Approaching deadline","Warns of upcoming protest/filing deadlines"],["Critical Alert","System event","Urgent notifications for admin attention"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Email Queue Architecture"}),e.jsx("p",{children:"Emails are processed through a pgmq (PostgreSQL Message Queue) system:"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Events trigger ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"enqueue_email()"})," to add messages to the queue"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"process-email-queue"})," edge function reads batches via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"read_email_batch()"})]}),e.jsxs("li",{children:["Failed messages are moved to a dead-letter queue via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"move_to_dlq()"})]}),e.jsx("li",{children:"Suppressed addresses are checked before sending"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Suppression Handling"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"handle-email-suppression"})," and ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"handle-email-unsubscribe"})," functions manage bounces, complaints, and voluntary unsubscribes. A public ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"/unsubscribe"})," page allows recipients to manage their preferences."]})]})},{id:"seo-content",title:"SEO & Content Engine",category:"Platform",icon:e.jsx(L,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The marketing site is optimized for organic search with a pillar/cluster content architecture, AI-generated articles, and dynamic SEO infrastru
70cture."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Content Architecture"}),e.jsx(t,{headers:["Type","Example URL","Purpose"],rows:[["Pillar Page","/tariff-refund","Primary topic authority page"],["Cluster Page","/tariff-refund/ieepa","Supporting subtopic page"],["Resource Article","/resources/tariff-news/article-slug","AI-generated educational content"],["Case Study","/case-studies/slug","Client success stories"],["Industry Page","/industries/slug","Vertical-specific landing pages"],["Geo Landing","/florida-tariff-recovery","Location-targeted pages"],["Tool Page","/tools/tariff-refund-calculator","Interactive calculators and analyzers"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Dynamic Sitemap System"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"sitemap"})," edge function generates 5 specialized sub-sitemaps:"]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Static pages sitemap (marketing, legal, tools)"}),e.jsx("li",{children:"Resource articles sitemap (from blog_posts table)"}),e.jsx("li",{children:"Case studies sitemap"}),e.jsx("li",{children:"Industry pages sitemap"}),e.jsx("li",{children:"Pillar/cluster pages sitemap"})]}),e.jsxs("p",{children:["New content is pushed to search engines via IndexNow protocol through the ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"indexnow"})," edge function."]})]})},{id:"data-quality",title:"Data Quality & Integrity",category:"Data",icon:e.jsx(A,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform includes multiple systems for ensuring data accuracy and preventing corruption of production data."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Data Source Tracking"}),e.jsx("p",{children:"Every claim entry and lead is tagged with its data source:"}),e.jsx(t,{headers:["Source","Badge Color","Description"],rows:[["manual","Default","Manually entered by admin or client"],["ace_import","Blue","Imported from ACE ES-003 CSV file"],["seeded","Orange (warning)","Generated by seed-demo-data function"],["partner_sync","Purple","Received from processing partner"],["broker_import","Teal","Imported via broker bulk upload"],["intake_form","Green","Submitted through client intake wizard"]]}),e.jsx(l,{type:"warning",children:"When seeded (demo) data coexists with real data on a lead, a warning banner is displayed in the admin UI to prevent accidental filing of test entries."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Qualification Scoring Engine"}),e.jsx("p",{children:"The scoring engine evaluates 15+ factors to produce a 0–100 qualification score:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Total IEEPA duties (up to 30 points)"}),e.jsx("li",{children:"Unliquidated entries present (15 points)"}),e.jsx("li",{children:"Protest window remaining (up to 5 points)"}),e.jsx("li",{children:"IOR status (up to 10 points)"}),e.jsx("li",{children:"Records completeness, ACE access, ACH enrollment (up to 8 points)"}),e.jsx("li",{children:"Decision maker access (5 points)"}),e.jsx("li",{children:"Cooperation level, cash urgency, sell interest (up to 10 points)"}),e.jsx("li",{children:"Entry complexity (negative modifier: -5 to -10)"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Deduplication"}),e.jsx("p",{children:"The ProspectDedupManager identifies potential duplicate leads based on company name, EIN, email, and phone number similarity, allowing admin review and merge."})]})},{id:"security-compliance",title:"Security & Compliance",category:"Security",icon:e.jsx(R,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"Security is engineered as a defense-in-depth program spanning governance, identity, data, application, infrastru
70cture, and operations. The platform is built on a zero-trust foundation: no request is trusted by origin alone — every database read and write is gated by Row-Level Security, every privileged action is logged, every credential is encrypted, and every external boundary is rate-limited and signed."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Compliance Framework Alignment"}),e.jsx("p",{children:"The platform is designed and operated to satisfy the control objectives of the following frameworks. Production posture is continuously assessed against each:"}),e.jsx(t,{headers:["Framework","Scope","Status"],rows:[["SOC 2 Type II (Trust Services Criteria)","Security, Availability, Confidentiality, Processing Integrity, Privacy","Controls implemented — observation window in progress"],["NIST Cybersecurity Framework 2.0","Govern, Identify, Protect, Detect, Respond, Recover","Mapped across all six functions"],["NIST SP 800-53 (Moderate Baseline)","Access control, audit, IR, SC, SI control families","Aligned"],["ISO/IEC 27001:2022","ISMS, Annex A controls","Aligned (informal)"],["GDPR & CCPA/CPRA","Lawful basis, data subject rights, DSAR, deletion, portability","Implemented"],["GLBA Safeguards Rule (16 CFR 314)","Customer financial info protection","Applicable controls implemented"],["PCI DSS v4.0","No cardholder data stored — Stripe SAQ-A scope only","Out of scope (tokenized via Stripe)"],["CBP / Customs data handling","19 CFR confidentiality of importer data","Enforced via RLS + audit"],["HIPAA","Not applicable — no PHI processed","N/A"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"SOC 2 Trust Services Criteria — Control Mapping"}),e.jsx(t,{headers:["TSC","Criterion","How It's Enforced"],rows:[["CC1","Control Environment","Documented policies, role separation (admin / affiliate / broker / funder / client), background-checked staff, signed code of conduct."],["CC2","Communication & Information","Security memo + this technical document; incident comms via in-app + email; status page for outages."],["CC3","Risk Assessment","Quarterly risk register, automated dependency scanning, Supabase linter, SAST on every deploy."],["CC4","Monitoring Activities","Health dashboard, audit_log triggers, edge function logs, anomaly alerts on role/credential changes."],["CC5","Control Activities","Migration review, RLS-by-default, mandatory PR review, environment separation (sandbox vs live)."],["CC6","Logical & Physical Access","MFA-capable auth, JIT impersonation w/ full audit, least-privilege RLS, hardware security at hosting provider."],["CC7","System Operations","Automated deploys, rollback via versioned migrations, 24/7 alerting, documented runbooks."],["CC8","Change Management","Git-tracked migrations, peer-reviewed PRs, separate test/live data modes, immutable agreement templates."],["CC9","Risk Mitigation","Vendor due diligence, business continuity plan, cyber insurance coverage."],["A1","Availability","Multi-AZ Postgres, automated daily backups + PITR, 99.9% target uptime, health monitoring."],["C1","Confidentiality","AES-256 encryption at rest, TLS 1.2+ in transit, data classification, RLS, redaction in audit logs."],["PI1","Processing Integrity","MOD-10 entry validation, ES-003 parsing checksums, tri-state IEEPA hard gates, deterministic commission waterfall, idempotent webhooks."],["P1–P8","Privacy","Consent capture, purpose limitation, DSAR endpoint, deletion workflow, data retention schedule, sub-processor list."]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Zero-Trust Architecture"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Identity-first:"})," Every request carries a JWT; ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"auth.uid()"})," is the sole source of truth for authorization."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"RLS-by-default:"})," New tables ship with RLS enabled and explicit policies. CI fails on any table missing RLS."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Role isolation:"})," Roles live in a separate ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"user_roles"})," table — never on profiles — eliminating privilege-escalation via row updates."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"SECURITY DEFINER discipline:"})," Privileged functions use ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"SET search_path = public"})," and validate caller identity inside the function body."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Service-to-service auth:"})," Edge functions verify JWTs by default; webhook ingress endpoints require HMAC-SHA256 signatures with per-partner rotating secrets."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Row-Level Security (RLS)"}),e.jsx("p",{children:"All 60+ public tables have RLS enabled. Every policy follows one of these vetted patterns:"}),e.jsx(t,{headers:["Pattern","Implementation","Used On"],rows:[["Admin full access","has_role(auth.uid(), 'admin')","All tables"],["Owner access","lead_id IN get_user_lead_ids(auth.uid())","claim_entries, documents, agreements"],["Broker access","lead_id IN get_broker_lead_ids(auth.uid())","Broker-linked tables"],["Funder access","funder_id IN get_funder_ids(auth.uid())","funder_offers, funding_deals"],["Self access","user_id = auth.uid()","profiles, user_roles (read only)"],["Public read","true (SELECT only, no PII)","blog_posts, case_studies, app_settings"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Encryption"}),e.jsx(t,{headers:["Data","At Rest","In Transit","Key Custody"],rows:[["Database (entire cluster)","AES-256 (provider-managed)","TLS 1.2+","Cloud-provider HSM"],["ACE portal credentials","AES-256-GCM (envelope)","TLS 1.3","ACE_ENCRYPTION_KEY in secrets vault"],["Partner API keys","AES-256-GCM","TLS 1.3","Supabase Vault (pgsodium)"],["Webhook payloads","HMAC-SHA256 signed","TLS 1.3","Per-partner rotating secret"],["Affiliate bank / ACH details","Column-level encryption","TLS 1.3","Vault-managed DEK"],["Document storage (lead-documents)","AES-256 (bucket-level)","TLS 1.3 + signed URLs","Cloud-provider HSM"],["Backups & PITR","AES-256","TLS 1.3","Cloud-provider HSM"],["Session tokens","Signed JWT (HS256)","Secure + HttpOnly cookies","JWT_SECRET rotated quarterly"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Authentication & Identity"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Methods:"})," Email + password (HIBP leaked-password check enabled), Google OAuth, magic links for invite flows."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"MFA:"})," TOTP-capable for admin and funder portals; enforced for production admin accounts."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Lockout:"})," Progressive backoff on failed sign-in (",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"useLoginLockout"}),") — 5 attempts → 15 min lockout."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Session hygiene:"})," Refresh-token rotation, automatic revocation on password change, idle timeout for admin sessions."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Impersonation:"})," Admin-only, scoped to a single tab via isolated storage shim, full audit trail (start, end, all actions performed under impersonation)."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Password policy:"})," Minimum 12 chars, HIBP breach check at signup and password change."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Audit Logging & Forensics"}),e.jsxs("p",{children:["The ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"audit_trigger_fn()"})," trigger captures every INSERT/UPDATE/DELETE on monitored tables. Frontend errors and security-relevant client events also flow into ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"audit_log"})," via the global ErrorBoundary."]}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Actor identity (user_id + email) and impersonator (if any)"}),e.jsx("li",{children:"Action class — insert, update, delete, status_change, role_change, login, impersonation_start/stop, export"}),e.jsx("li",{children:"Full before/after diff with sensitive fields (SSN, EIN, bank, credentials) redacted"}),e.jsx("li",{children:"Severity — info, warning, high, critical (drives alerting)"}),e.jsx("li",{children:"Session ID, IP address, user agent, request ID for correlation"}),e.jsx("li",{children:"Append-only retention — admin UI cannot delete audit rows; tampering attempts raise a critical alert"}),e.jsx("li",{children:"Retention: 7 years for financial actions, 2 years for general events (configurable)"})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Application Security"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Input validation:"})," zod schemas on every form; server-side validation in edge functions and DB constraints/triggers."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"XSS prevention:"})," All user- and admin-sourced HTML sanitized with DOMPurify before render; ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"dangerouslySetInnerHTML"})," never receives untrusted content."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"CSRF:"})," SameSite=Lax cookies + JWT bearer model; no cookie-only state changes."]}
70),e.jsxs("li",{children:[e.jsx("strong",{children:"SQL injection:"})," All queries parameterized through the Supabase client; raw SQL only in vetted migrations."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Rate limiting:"})," ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"useRateLimit"})," hook + edge-function-level throttling on auth, intake, and webhook routes."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Content Security Policy:"})," Strict CSP headers — script/style sources allowlisted, frame-ancestors locked, upgrade-insecure-requests enforced."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Security headers:"})," HSTS (1 yr, includeSubDomains, preload), X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy locked down."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Dependency hygiene:"})," Automated vulnerability scanning on every build; high/critical findings block merge."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Vulnerability Management & Testing"}),e.jsx(t,{headers:["Activity","Cadence","Tooling"],rows:[["Static application security testing (SAST)","Every commit","Built-in linter + dependency scan"],["Dependency / SCA scan","Every build","npm audit + automated PRs"],["Database security linter","Pre-deploy + nightly","Supabase linter"],["Penetration test","Annual + on major architecture changes","Third-party qualified firm"],["Bug bounty / responsible disclosure","Continuous","security@ inbox + safe-harbor policy"],["Backup restoration drill","Quarterly","Documented runbook"],["Incident response tabletop","Semi-annual","Documented runbook"],["Access review (admin accounts)","Quarterly","Manual review + audit export"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Incident Response"}),e.jsx("p",{children:"Documented IR plan with named roles (Incident Commander, Comms Lead, Tech Lead, Legal Liaison). Severity tiers drive response SLAs:"}),e.jsx(t,{headers:["Severity","Examples","Response Target","Customer Notification"],rows:[["Sev 1","Confirmed data breach, full outage, RLS bypass","15 min triage / 1 hr containment","Within 24 hrs (regulatory clock)"],["Sev 2","Partial outage, degraded auth, single-tenant data exposure","1 hr triage / 4 hr resolution","Within 72 hrs if PII impacted"],["Sev 3","Non-critical bug with security implication","Next business day","Disclosed in next release notes"],["Sev 4","Informational / hardening opportunity","Backlog with target sprint","N/A"]]}),e.jsx("p",{children:"Breach notification follows the strictest applicable timeline (GDPR 72-hour rule, state-level breach laws). Post-incident reviews produce a public-facing postmortem for Sev 1 and Sev 2 events."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Business Continuity & Disaster Recovery"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"RPO:"})," ≤ 5 minutes (continuous WAL streaming + point-in-time recovery up to 7 days)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"RTO:"})," ≤ 4 hours for full database restore; ≤ 30 minutes for application-tier failover"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Backups:"})," Daily full + continuous WAL, encrypted, retained 30 days; quarterly off-region copy retained 1 year"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Restoration drills:"})," Quarterly, with documented evidence (timing, integrity check, RTO measurement)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Multi-region readiness:"})," Stateless edge functions deployable to any region within minutes"]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Data Governance & Privacy"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Data classification:"})," Public, Internal, Confidential (default for client data), Restricted (credentials, SSN/EIN, bank). Controls scale with classification."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Data minimization:"})," Only fields required for the engagement are collected; opt-in for marketing analytics."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Sandbox vs Live isolation:"})," ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"data_source"})," tag on every row + ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"useDataMode().dataSourceFilter"})," guarantees seeded/test data never leaks into Live workflows."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"DSAR (Data Subject Access Requests):"}
70)," Self-serve export from client portal; deletion within 30 days of verified request (with legal-hold exceptions for active claims)."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Right to be forgotten:"})," Hard-delete cascades on user, audit row anonymized, financial records retained per IRS / 19 CFR requirements."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Sub-processor list:"})," Maintained publicly; customers notified of additions 30 days in advance."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Cross-border transfers:"})," SCCs in place where applicable; data residency commitments documented per tenant."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Regulatory & Industry Compliance"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"19 CFR (CBP):"})," Importer of Record data treated as confidential business information; access restricted to the IOR's authorized representatives."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Form 8821 / POA:"})," Tax-information authorizations stored encrypted with explicit expiration tracking."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"State unauthorized-practice-of-law (UPL):"})," Platform facilitates licensed counsel for CIT matters; non-attorney staff cannot give legal advice — enforced by training and prompts."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Anti-money-laundering / OFAC:"})," Sanctions screening on new partner and funder registrations."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Stripe / PCI:"})," No PAN ever touches our systems — Stripe Elements + tokenization keep us in SAQ-A scope."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Vendor & Sub-Processor Security"}),e.jsx("p",{children:"Every sub-processor undergoes due diligence (SOC 2 report review, DPA execution, security questionnaire). Current critical sub-processors:"}),e.jsx(t,{headers:["Vendor","Purpose","Attestation"],rows:[["Supabase (Lovable Cloud)","Database, auth, storage, edge compute","SOC 2 Type II"],["AWS (underlying hosting)","Compute, network, storage","SOC 1/2/3, ISO 27001, PCI"],["Stripe","Payments (tokenized)","PCI DSS Level 1, SOC 1/2"],["Resend / SendGrid","Transactional email","SOC 2 Type II"],["OpenAI / Google AI","AI features via Lovable AI Gateway","SOC 2 Type II"],["Skyvern","RPA / ACE portal automation","SOC 2 in progress"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Responsible Disclosure"}),e.jsxs("p",{children:["We welcome security research conducted in good faith. Report findings to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"[email protected]"})," — we commit to acknowledging within 2 business days, providing status within 7 days, and crediting researchers (with permission) in our hall of fame. Safe-harbor language protects researchers who follow our disclosure policy."]})]})}
70,{id:"infrastructure",title:"Infrastructure Monitoring",category:"Platform",icon:e.jsx(T,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform includes a health monitoring dashboard that tracks the status of all external services, internal systems, and critical deadlines."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Monitored Services"}),e.jsx(t,{headers:["Service","Health Check Method","Purpose"],rows:[["Supabase Database","Connection test","Primary data store"],["Supabase Auth","Session check","Authentication system"],["Supabase Storage","Bucket listing","Document storage"],["Edge Functions","Ping test","Serverless compute"],["Firecrawl API","healthCheck: true","Web scraping for enrichment"],["Perplexity API","healthCheck: true","AI-powered search"],["API Ninjas","healthCheck: true","Routing number verification"],["Skyvern RPA","healthCheck: true","Browser automation"],["Email Queue (pgmq)","Queue depth check","Transactional email"],["Lovable AI Gateway","Model availability","AI features"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Alert Systems"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Critical Event Alerts:"})," Role changes, credential modifications, bulk deletions"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Deadline Alerts:"})," Protest deadlines, POA expirations, bond expirations, CIT deadlines"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"SLA Tracker:"})," Monitors processing time against configured service level agreements"]})]})]})},{id:"api-reference",title:"API Reference — Claim Payload",category:"Data",icon:e.jsx(F,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"When pushing claims to processing partners, the platform aggregates data from 14+ tables into a single comprehensive payload. Below is the canonical structure:"}),e.jsx(c,{code:`{
71  "claim": {
72    "id": "uuid",
73    "company_name": "string",
74    "dba": "string",
75    "ein": "XX-XXXXXXX",
76    "address": "string",
77    "contact_name": "string",
78    "contact_email": "string",
79    "is_ior": "yes|no|broker",
80    "ior_numbers": "string",
81    "data_source": "manual|intake_form|seeded|broker_import",
82    "status": "string (20 possible values)"
83  },
84  "claim_details": {
85    "qualification_score": 0-100,
86    "estimated_recovery": "numeric",
87    "actual_recovery": "numeric",
88    "priority": "high|medium|low",
89    "engagement_fee_pct": "numeric"
90  },
91  "entries": [{
92    "entry_number": "11-digit MOD-10",
93    "entry_date": "YYYY-MM-DD",
94    "entry_type": "01|06|21|22|23",
95    "country_of_origin": "string",
96    "port_of_entry": "string",
97    "importer_of_record": "XX-XXXXXXX",
98    "total_duties": "numeric",
99    "ieepa_duties": "numeric",
100    "section_301_duties": "numeric",
101    "section_232_duties": "numeric",
102    "has_ad_cvd": "boolean",
103    "entered_value": "numeric (auto-aggregated)",
104    "liquidation_status": "string",
105    "data_source": "manual|ace_import|seeded",
106    "form_4811_status": "string",
107    "interest_accrued": "numeric (6% p.a.)",
108    "lines": [{
109      "hts_code": "10-digit",
110      "entered_value": "numeric",
111      "duty_amount": "numeric",
112      "ieepa_rate": "numeric",
113      "ieepa_amount": "numeric",
114      "ad_cvd_flag": "boolean"
115    }]
116  }],
117  "agreements": [{
118    "agreement_type": "string",
119    "status": "draft|sent|signed|countersigned|voided",
120    "signed_at": "timestamp",
121    "expires_at": "timestamp"
122  }],
123  "ace_account": {
124    "verification_status": "string",
125    "ach_enrolled": "boolean",
126    "edis_enrolled": "boolean",
127    "bond_number": "string",
128    "bond_expiry": "date"
129  },
130  "documents": [{ "document_type": "string", "file_name": "string", "uploaded_at": "timestamp" }],
131  "protests": [{ "protest_number": "string", "status": "string", "deadline": "date" }],
132  "cape_batches": [{ "batch_number": "string", "status": "string", "total_refund": "numeric" }],
133  "advance_funding": { "status": "string", "advance_amount": "numeric", "discount_rate": "numeric" }
134}`})]})},{id:"database-schema",title:"Database Schema Reference",category:"Data",icon:e.jsx(N,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform uses 60+ PostgreSQL tables. Below are the primary tables grouped by domain."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Core Claims"}),e.jsx(t,{headers:["Table","Purpose","Key Relations"],rows:[["leads","Primary claim/lead record","→ claim_details, claim_entries, claim_agreements"],["claim_details","Financial & qualification data","← leads (1:1)"],["claim_entries","Indiv
134idual customs entries","← leads, → entry_lines"],["entry_lines","Line items within entries","← claim_entries"],["claim_checklist","Document collection tracking","← leads"],["claim_timeline","Event history","← leads"],["claim_messages","Client-admin messaging","← leads"],["claim_agreements","E-sign agreements","← leads"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"CBP Filing"}),e.jsx(t,{headers:["Table","Purpose"],rows:[["cape_batches","CAPE filing batches with status tracking"],["cape_batch_entries","Junction: which entries in which batch"],["protests","CBP protest records"],["protest_entries","Junction: entries included in protests"],["cit_cases","Court of International Trade cases"],["cbp_interactions","All CBP communication records"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Users & Access"}),e.jsx(t,{headers:["Table","Purpose"],rows:[["profiles","User profile data (name, email)"],["user_roles","Role assignments (admin, client, broker, affiliate)"],["affiliates","Referral partner records"],["affiliate_payment_info","Partner ACH/tax details"],["affiliate_commissions","Affiliate commission ledger"],["affiliate_custom_invites","Network recruitment invites"],["brokers","Licensed customs broker records"],["broker_clients","Broker-client relationship links"],["broker_commission_ledger","Broker commission records"],["broker_invitations","Broker invitation management"],["broker_whitelabel","Broker portal branding"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"ACE & Automation"}),e.jsx(t,{headers:["Table","Purpose"],rows:[["ace_accounts","ACE portal account details + bond info"],["ace_credentials","Encrypted ACE login credentials"],["rpa_jobs","Skyvern automation job tracking"],["rpa_results","RPA execution results and artifacts"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Operations & Settings"}),e.jsx(t,{headers:["Table","Purpose"],rows:[["app_settings","Global configuration key-value store"],["commission_settings","Commission rate defaults"],["agreement_templates","E-sign template library"],["audit_log","Comprehensive activity audit trail"],["deadline_alerts","Upcoming deadline notifications"],["lead_documents","File metadata for uploaded documents"],["advance_funding","Client advance funding records"],["processing_partners","3rd-party partner profiles"],["partner_transactions","Integration transaction log"]]})]})},{id:"edge-functions",title:"Edge Functions Reference",category:"Integration",icon:e.jsx(X,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The platform deploys 40+ Deno-based edge functions for serverless compute. All functions include CORS headers and input validation."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"ETL & Data Processing"}),e.jsx(t,{headers:["Function","Purpose","Trigger"],rows:[["etl-ace-report","Parse ACE ES-003 CSV into claim_entries","Manual (upload)"],["parse-ace-report","Lightweight ACE CSV parser","Manual"],["import-cbp-brokers","Import CBP broker registry data","Manual/Scheduled"],["import-importers","Import known importer lists","Manual"],["scrape-cbp-brokers","Scrape CBP broker directory","Scheduled"],["scrape-importers","Scrape importer databases","Scheduled"],["seed-demo-data","Generate realistic test data","Manual"],["seed-content","Seed marketing content","Manual"],["seed-sic-codes","Populate SIC code reference","Manual"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Filing & CBP"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["generate-cape-csv","Generate CAPE-format CSV for CBP submission"],["generate-protest-package","Create CBP Form 19 protest package"],["generate-litigation-package","Prepare CIT filing documents"],["generate-audit-report","Create comprehensive claim audit report"],["poll-cape-status","Check CAPE batch processing status"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"AI & Intelligence"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["tariff-chat","AI-powered tariff Q&A chatbot"],["tariff-intelligence","Strategic tariff analysis"],["evaluate-theories","Legal theory evaluation"],["enrich-prospect","AI-powered lead data enrichment"],["monitor-tariff-changes","Track regulatory changes"],["analyze-documents","AI document classification and extraction"],["classify-document","Auto-classify uploaded documents"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Email & Communication"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["process-email-queue","Batch process outgoing emails from pgmq"],["send-transactional-email","Send individual transactional emails"],["preview-transactional-email","Render email template preview"],["auth-email-hook","Custom auth email templates"],["handle-email-suppression","Process bounce/complaint webhooks"],["handle-email-unsubscribe","Process unsubscribe requests"],["send-broker-invite","Send broker invitation emails"],["send-sms-campaign","SMS campaign dispatch"],["check-critical-alerts","Evaluate and trigger critical alerts"],["check-deadline-alerts","Evaluate upcoming deadline alerts"],["escalate-deadlines","Escalate overdue deadlines"],["notify-status-change","Triggered by DB — sends status update email"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Integration & Partner"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["push-claim","Push claim data to processing partner"],["partner-webhook","Receive inbound partner webhooks"],["pull-partner-status","Poll partner API for updates"],["manage-partner-keys","CRUD partner API keys (encrypted)"],["manage-ace-credentials","CRUD ACE portal credentials (encrypted)"],["rpa-dispatch","Send RPA jobs to Skyvern"],["verify-broker-license","Validate broker license numbers"],["lookup-routing-number","ABA routing number lookup"],["bulk-ach-verify","Batch ACH enrollment verification"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Content & SEO"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["generate-articles","AI-generate resource articles"],["generate-article-images","AI-generate article hero images"],["batch-article-specs","Batch create article specifications"],["auto-publish-articles","Auto-publish scheduled articles"],["sitemap","Dynamic XML sitemap generation"],["sitemap-refresh","Trigger sitemap regeneration"],["indexnow","Push new URLs to search engines"],["og-html","Generate Open Graph image HTML"],["sync-registry-data","Sync external registry data"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Campaign & Outreach"}),e.jsx(t,{headers:["Function","Purpose"],rows:[["generate-outreach-copy","AI-generate outreach email/SMS copy"],["export-campaign","Export campaign data for external platforms"],["process-followups","Process automated follow-up sequences"],["import-cbp-official","Import official CBP data"]]})]})},{id:"funding-ecosystem",title:"Funding Ecosystem (Phases 1–6)",category:"Funding",icon:e.jsx(b,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The Funding Ecosystem connects qualified claims with third-party capital partners (funders). It supports advance funding (% of estimated refund paid pre-CBP) and outright purchase of receivables. The ecosystem shipped in six phases through May 2026 and is now fully production."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Phase Inventory"}),e.jsx(t,{headers:["Phase","Scope","Key Surfaces"],rows:[["1. Funder Onboarding","Funder registration, KYB, risk profile capture","/funding/register, FundingAcceptInvite, funder_risk_profiles"],["2. Discovery & Matching","Algorithmic match of funders ↔ qualifying claims; teaser vs full access","FundingDiscover, funder_claim_matches.access_level (teaser|full|revoked)"],["3. Offers","Funder issues advance/purchase offer with terms_md","FundingOffers, funder_offers, FundingOffersList"],["4. Counters","Client proposes new advance % / discount rate; child funder_offers row with parent_offer_id","CounterOfferDialog, status='countered'"],["5. Deal Agreements & Settlements","Counter-signed deal, payout account capture, settlement disbur
134sement","DealAgreementQueue, ClientPayoutAccountForm, FundingSettlements, funding_settlements, handle_funder_offer_settlement"],["6. Prequal + Analytics + Router","Anonymous what-if prequal; funder portfolio analytics; admin override of access","FundingEligibilityPrequal, FundingAnalytics, /command/funding-router"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Funding Tracks Model"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Intake signal"})," — funding_intent (≡ sell_interest) captured during onboarding; surfaces a claim for matching but is not a commitment."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Funding Application"})," — formal submission with documents; gates teaser → full access."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Funding Deal"})," — signed agreement on accepted offer; spawns funding_settlements row at refund disbursement."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Prequal RPCs"}),e.jsx(c,{language:"sql",code:`-- Anonymous match without exposing private funder rules
135SELECT public.prequal_funder_match_count(
136  _refund_estimate := 250000,
137  _program := 'IEEPA',
138  _has_ad_cvd := false
139);
140
141SELECT * FROM public.prequal_funder_match_summary(
142  _refund_estimate := 250000,
143  _program := 'IEEPA',
144  _has_ad_cvd := false
145);`}),e.jsx(l,{type:"info",children:"Both prequal RPCs are SECURITY DEFINER with SET search_path = public. They never return funder identities — only aggregate counts and economic ranges."})]})},{id:"funder-portal",title:"Funder Portal",category:"Funding",icon:e.jsx(I,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Capital partners operate from a dedicated portal at ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"/funding/*"}),". The portal is RLS-scoped to the funder's own workspace and never exposes cross-funder data."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Routes"}),e.jsx(t,{headers:["Route","Page","Purpose"],rows:[["/funding/login","FundingLogin","Funder authentication"],["/funding/register","FundingRegister","New funder onboarding (KYB + risk profile)"],["/funding/accept-invite","FundingAcceptInvite","Token-based team invite acceptance"],["/funding/discover","FundingDiscover","Browse matched claims (teaser or full)"],["/funding/offers","FundingOffers","Outbound offers + inbound counters"],["/funding/active-deals","FundingActiveDeals","Signed deals awaiting refund disbursement"],["/funding/portfolio","FundingPortfolio","All deals (active + settled)"],["/funding/analytics","FundingAnalytics","Capital deployed/repaid/outstanding; conversion funnel"],["/funding/settings","FundingSettings","Risk profile, fee structures, webhooks, API keys"],["/funding/glossary","FundingGlossary","Terms of art for funders"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Funder Tables (23 total)"}),e.jsx("p",{className:"text-xs",children:e.jsx("code",{className:"bg-muted px-1 rounded",children:"funders, funder_users, funder_invitations, funder_risk_profiles, funder_fee_structures, funder_claim_matches, funder_offers, funder_offer_history, funder_agreements, funder_agreement_templates, funder_document_requests, funder_notifications, funder_activity_log, funder_workspace_notes, funder_api_keys, funder_webhook_subscriptions, funding_applications, funding_application_documents, funding_application_events, funding_stage_events, funding_transactions, funding_settlements, funding_disbursement_confirmations"})})]})},{id:"anchor-deep-dive",title:"Anchor Integration Deep Dive",category:"Integration",icon:e.jsx(S,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Anchor is the platform's primary downstream processing partner. The integration is bidirectional: outbound ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"push-claim"})," with full payload, and inbound webhook for state changes. Both directions use the same production credentials — there is one Anchor environment."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Authentication"}),e.jsxs("p",{children:[e.jsx("strong",{children:"Service-to-service"}
145),". The platform holds a single Anchor API key (encrypted at rest via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"manage-partner-keys"}),") and signs each outbound request with HMAC-SHA256 over ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"{timestamp}.${body}"}),"."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Outbound — push-claim"}),e.jsx(c,{language:"json",code:`{
146  "event_id": "evt_01HXY...",
147  "lead_id": "uuid",
148  "claim": {
149    "importer": { "ein": "12-3456789", "name": "Acme Imports LLC" },
150    "entries": [{ "entry_number": "ABC12345678", "ieepa_duties": 48210.55 }],
151    "total_refund_estimate": 312445.00,
152    "data_source": "live"
153  },
154  "idempotency_key": "lead_uuid:v3",
155  "signature_ts": 1747856400
156}`}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Inbound — partner-webhook"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["HMAC verification using shared secret ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ANCHOR_WEBHOOK_SECRET"}),"."]}),e.jsxs("li",{children:["Reject if ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"abs(now - signature_ts) > 300s"}),"."]}),e.jsxs("li",{children:["Idempotent on ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"(event_id, lead_id)"}),"."]}),e.jsxs("li",{children:["State changes upsert into ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"partner_status_events"})," and fan out to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"notify-status-change"}),"."]})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Reconciliation — pull-partner-status"}),e.jsx("p",{children:"Runs on pg_cron every 15 minutes. Polls Anchor for any claims where the last webhook is older than 1 hour and applies drift corrections. AnchorDataPanel (in ClaimDiligenceDialog) surfaces the live Anchor view to admins."}),e.jsx(l,{type:"warning",children:"Never assume a terminal status from the synchronous push-claim response. The push only confirms receipt — true state lives in webhooks + pull reconciliation."})]})},{id:"commission-waterfall",title:"Commission Waterfall Reference",category:"Financial",icon:e.jsx(b,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The contingency fee IS the gross commission pool. Default 20% of refund. Everything paid out (reserve, brokers, partners) comes from that pool; TRA retains the remainder."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Waterfall Flow"}),e.jsx(c,{language:"text",code:`Refund received from CBP
157        │
158        ▼
159Contingency Fee Pool  (default 20% of refund)  ← from Admin Settings.default_engagement_fee_pct
160        │
161        ├─▶ Reserve (claim-specific override)
162        │
163        ├─▶ Broker commissions  (broker_commission_rate × refund OR per-claim override)
164        │
165        ├─▶ Partner Pool
166        │     ├─▶ Direct partner (30% default)
167        │     ├─▶ Sponsor / upline (10% default)
168        │     └─▶ Cascading pool grants (5% min spread per hop)
169        │
170        └─▶ TRA Retained  (remainder)`}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Worked Example — $500,000 refund"}),e.jsx(t,{headers:["Leg","Calc","Amount"],rows:[["Refund (gross)","—","$500,000"],["Contingency pool (20%)","500,000 × 0.20","$100,000"],["Reserve (claim override 5%)","100,000 × 0.05","$5,000"],["Broker (10% of refund)","500,000 × 0.10","$50,000"],["Partner direct (30% of pool − above)","(100,000 − 55,000) × 0.30","$13,500"],["Partner sponsor (10% of pool − above)","(100,000 − 55,000) × 0.10","$4,500"],["TRA Retained (remainder)","100,000 − 5,000 − 50,000 − 13,500 − 4,500","$27,000"]]}),e.jsxs(l,{type:"info",children:["Per-claim overrides on ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"claim_details"})," (broker_commission_rate, reserve_pct) take precedence over global commission_settings. The contingency % itself is NEVER read from claim_details — only from Admin Settings."]})]})},{id:"cascading-pool-comp",title:"Cascading Pool Comp Model",category:"Financial",icon:e.jsx(_,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"The Cascading Pool Comp Model is the 3rd partner compensation primitive (
170alongside fixed-rate and corporate comp plans). A grantor partner is allocated a share of the partner pool and can sub-allocate portions of it to invitees they bring in."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Rules"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Grantor partner holds a ",e.jsx("strong",{children:"pool grant"})," (e.g. 25% of partner pool on every claim they originate)."]}),e.jsxs("li",{children:["Grantor may sub-grant a portion to an invitee, with a ",e.jsx("strong",{children:"minimum 5% spread retained"})," by the grantor at every hop."]}),e.jsx("li",{children:"Sub-grants cascade — invitees can themselves invite + sub-grant, each hop preserving ≥5% spread."}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"pool_grantor_id"})," on each affiliate row encodes the upline chain."]}),e.jsxs("li",{children:["When sponsor is house, ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"pool_grantor_id"})," MUST be NULL (TRA House Root id ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"5637507e…"}),' displays as "TRA").']})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Pool Default Offer"}),e.jsx("p",{children:"Pool grantors can preset a default share % auto-granted to any standard-link signup under them (subject to the 5% spread floor). Configured in Affiliate Advanced settings."})]})},{id:"data-mode",title:"Data Mode (Sandbox vs Live)",category:"Data",icon:e.jsx(N,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Every row in production carries a ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"data_source"})," tag. The UI runs in Sandbox or Live mode (toggled per session by admins) and applies a global filter to ALL entity queries."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Tag Values"}),e.jsx(t,{headers:["Tag","Visible in Live","Visible in Sandbox","Origin"],rows:[["live","Yes","No","Production intake, real ACE imports, real partner pushes"],["ace_import","Yes","Yes (passthrough)","Real ACE ES-003 CSV upload"],["sandbox","No","Yes","Manually flagged sandbox data"],["seed","No","Yes","seed-demo-* edge functions"],["demo","No","Yes","Hand-built demo records"],["partner_sync","Yes","Yes (passthrough)","Inbound partner-webhook"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Query Pattern"}),e.jsx(c,{language:"ts",code:`import { useDataMode } from "@/hooks/useDataMode";
171
172const { dataSourceFilter } = useDataMode();
173
174const { data } = await supabase
175  .from("leads")
176  .select("*")
177  .in("data_source", dataSourceFilter); // never .eq — filter is an array`}),e.jsx(l,{type:"warning",children:"Entity pickers (partners, brokers, leads, users, clients) MUST use SearchableSelect AND apply dataSourceFilter. Live mode never lists sandbox rows. RPA jobs (Skyvern) MUST be tagged Live or Simulated."})]})},{id:"impersonation-auth",title:"Impersonation & Multi-Portal Auth",category:"Security",icon:e.jsx(F,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Admins can impersonate any user into any portal (client / affiliate / broker / funder / admin) from ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"ImpersonationDialog"}),". The impersonated session is tab-isolated so the admin's own session in the originating tab is preserved."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Mechanism"}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Admin invokes ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"admin-impersonate"})," edge function → returns a magic-link."]}),e.jsxs("li",{children:["Magic link opens in a new tab with ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"?impersonate=1"})," URL flag."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"installImpersonationStorageShim()"})," (loaded before the Supabase client) detects the flag, sets ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"tra_impersonation_tab=1"})," in sessionStorage, and reroutes all ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"sb-*-auth-token"})," reads/writes from localStorage → sessionStorage."]}),e.jsxs("li",{children:["BroadcastChannel ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"sb-*-auth-token"})," is stubbed to a no-op so cross-tab SIGN_IN/TOKEN_REFRESHED events from the admin tab cannot over
177write the impersonated session."]}),e.jsxs("li",{children:["Cross-tab ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"storage"})," events for auth keys are swallowed."]}),e.jsxs("li",{children:["Exit via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"exitImpersonation()"})," — clears FLAG_KEY + banner + sb-* tokens in sessionStorage, signs out locally (600ms timeout race), tries window.close(), falls back to /."]})]}),e.jsxs(l,{type:"warning",children:["Never store roles on the profile or users table. Roles live in ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"user_roles"})," and are checked via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"has_role(_user_id, _role)"})," (SECURITY DEFINER, search_path=public)."]})]})},{id:"whitelabel",title:"Whitelabel & Multi-Tenant",category:"Platform",icon:e.jsx(L,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["The platform serves multiple custom domains and broker-whitelabeled marketing sites from a single deployment. Tenant resolution happens client-side at boot via ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"TenantProvider"})," + ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"useBrokerWhitelabel"}),"."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Active Custom Domains"}),e.jsx("p",{className:"text-xs",children:"tariffrecoverytoday.com, thebetterchoicerefunds.com, usatariff.com, fmprefunds.com, funderialtariffs.com, tariffrefundagency.com, tariffrefundadvisors.com, refundfilers.com, 1stcapitalrefunds.com (+ www variants)."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Marketing Header Rule (binding)"}),e.jsxs(l,{type:"warning",children:["Header buttons/logo/nav are LIGHT over hero, DARK in sticky bar. Driven by ",e.jsx("strong",{children:"scroll state"}),", never by ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"isGold"})," theme. Do NOT re-add ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"isGold &&"})," to ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"goldTransparent"})," in Header.tsx."]})]})},{id:"lovable-ai",title:"Lovable AI Gateway Usage",category:"Integration",icon:e.jsx(D,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"All in-app AI runs through the Lovable AI Gateway — no per-model API keys, no per-provider SDKs. Edge functions call the gateway with a model id and prompt."}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Model Selection Cheat Sheet"}),e.jsx(t,{headers:["Use case","Recommended model"],rows:[["Long-context reasoning / multimodal","google/gemini-2.5-pro"],["Balanced speed + capability","google/gemini-2.5-flash"],["Classification / extraction at scale","google/gemini-2.5-flash-lite"],["Image generation","google/gemini-2.5-flash-image (Nano Banana)"],["Top-tier reasoning + nuance","openai/gpt-5"],["Cost-balanced general purpose","openai/gpt-5-mini"],["High-volume simple tasks","openai/gpt-5-nano"],["Hardest reasoning / code gen","openai/gpt-5.4 / 5.5"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"AI-powered Edge Functions"}),e.jsx("p",{className:"text-xs",children:e.jsx("code",{className:"bg-muted px-1 rounded",children:"tariff-chat, tariff-intelligence, evaluate-theories, analyze-documents, classify-document, crm-ai-summary, client-chat, generate-articles, generate-article-images, generate-outreach-copy, generate-marketing-kit, generate-social-image, generate-audit-report, enrich-importer-v3, monitor-tariff-changes"})})]})},{id:"operational-runbooks",title:"Operational Runbooks",category:"Operations",icon:e.jsx(w,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Cloud Lifecycle States"}),e.jsx(t,{headers:["State","Safe to migrate?","Action"],rows:[["ACTIVE_HEALTHY","Yes","Normal ops"],["COMING_UP / RESTARTING / RESTORING / UPGRADING / RESIZING","No","Wait, poll cloud_status until ACTIVE_HEALTHY"],["ACTIVE_UNHEALTHY","No","Read-only inspection only; avoid destructive migrations"],["INACTIVE","No","Resume from Cloud settings"],["PAUSING / GOING_DOWN","No","Wait"],["INIT_FAILED / RESTORE_FAILED / PAUSE_FAILED / REMOVED","No","Contact support — not self-serve"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Common Failure Modes"}),e.jsx(t,{headers:["Symptom","Root cause","Remediation"],rows:[["psql fails with socket error","PGHOST env not present in this exec session","Use Supabase tools (read_query / migration) instead"],["Migration succeeds but types.ts stale","Types regenerate async post-migration","Wait one cycle, do not hand-edit types.ts"],["Webhook signature mismatch","Clock skew > 5 min OR wrong secret","Verify ANCHOR_WEBHOOK_SECRET + NTP on caller"],["Live mode shows zero rows","data_source filter excluded everything","Verify rows tagged 'live' / 'ace_import' / 'partner_sync'"],["Impersonation tab logs you out as admin","Storage shim not installed before supabase client import","Confirm installImpersonationStorageShim() runs first in main.tsx"],["Edge function 1000-row missing data","Default Supabase row limit","Paginate with .range() or use fetchAllRows helper"]]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Migration Discipline"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Never modify auth, storage, realtime, supabase_functions, vault schemas."}),e.jsx("li",{children:"Use validation triggers (not CHECK constraints) for time-based validations."}),e.jsx("li",{children:"Every new table: enable RLS + at least one explicit policy per role."}),e.jsxs("li",{children:["SECURITY DEFINER functions MUST ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"SET search_path = public"}),"."]})]})]})},{id:"glossary",title:"Glossary",category:"Reference",icon:e.jsx(P,{className:"h-4 w-4"}),content:e.jsx("div",{className:"space-y-4",children:e.jsx(t,{headers:["Term","Definition"],rows:[["IEEPA","International Emergency Economic Powers Act — statutory basis for the tariffs being refunded."],["CAPE","Consolidated Aggregate Post-summary Entry — batch refund declaration filed with CBP."],["CBP","U.S. Customs and Border Protection."],["CIT","U.S. Court of International Trade — venue for tariff litigation after protest denial."],["ACE","Automated Commercial Environment — CBP's trade data system."],["ES-003","ACE Entry Summary CSV report format consumed by etl-ace-report."],["MOD-10","Mod-10 checksum used to validate 11-digit CBP entry numbers."],["AD/CVD","Antidumping / Countervailing Duty — excluded from CAPE Phase 1 refunds."],["EIN / IOR","Employer Identification Number used as Importer of Record number."],["HTS","Harmonized Tariff Schedule — 10-digit product classification code."],["Form 48
17711","CBP form authorizing electronic refund disbursement."],["Form 8821","IRS tax info authorization (used for downstream verifications)."],["POA","Power of Attorney granting filing authority."],["RLS","Row-Level Security — Postgres policy framework on every public table."],["pgmq","Postgres message queue extension used for transactional email queue."],["pg_cron","Postgres scheduled jobs (15-min ETL ticks, daily housekeeping, etc.)."],["HMAC","Hash-based Message Authentication Code — used for partner webhook signatures."],["Skyvern","Browser-automation provider for ACE portal RPA."],["Anchor","Primary downstream claim-processing partner."],["TRA House Root","Affiliate id 5637507e… — the 'no sponsor' placeholder, displayed as 'TRA'."]]})})},{id:"change-log",title:"Change Log",category:"Platform",icon:e.jsx(K,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"v3.0 — May 2026"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Added Funding Ecosystem (Phases 1–6): prequal, discovery, offers, counters, deal agreements, settlements, analytics, admin router."}),e.jsxs("li",{children:["Added Funder Portal at ",e.jsx("code",{className:"bg-muted px-1 rounded text-xs",children:"/funding/*"})," with 23 funding-domain tables."]}),e.jsx("li",{children:"Added Anchor Integration Deep Dive (service-to-service auth, HMAC webhook, idempotency)."}),e.jsx("li",{children:"Added Commission Waterfall Reference + Cascading Pool Comp Model."}),e.jsx("li",{children:"Added Data Mode (Sandbox vs Live) rules, Impersonation & Multi-Portal Auth, Whitelabel & Multi-Tenant, Lovable AI Gateway, Operational Runbooks, Glossary."}),e.jsx("li",{children:"Added Production Considerations & Known Gaps audit ledger at top of doc."}),e.jsx("li",{children:'Edge function inventory corrected from "40+" to actual 136.'}),e.jsx("li",{children:'Redesigned client "Submitted" step (was "Schedule Call"): hero check, timeline, trust signals; Calendly/Call-now removed.'}),e.jsx("li",{children:"Code blocks now render with token-colored syntax highlighting on the same dark background."})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"v2.0 — April 2026"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsx("li",{children:"Multi-portal architecture (Client / Broker / Affiliate / Admin) consolidated."}),e.jsx("li",{children:"RPA via Skyvern; ACE credential encryption (AES-256-GCM)."}),e.jsx("li",{children:"Commission system, e-sign, intelligence engine."})]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"v1.0 — Initial"}),e.jsx("ul",{className:"list-disc list-inside space-y-1 text-sm",children:e.jsx("li",{children:"Baseline intake → review → CAPE → refund pipeline."})})]})},{id:"case-manager-role",title:"Case Manager Role",category:"Security",icon:e.jsx(_,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["The ",e.jsx("strong",{children:"case_manager"})," role is a scoped Anchor-admin role for staff who actively own claim and client management without holding full platform-admin privileges. It exists to satisfy least-privilege requirements for day-to-day operations."]}),e.jsx(t,{headers:["Capability","case_manager","admin"],rows:[["Read assigned claims","Yes","Yes (all)"],["Edit assigned claims","Yes","Yes"],["Issue agreements / e-sign","Yes","Yes"],["Push to Anchor","Yes","Yes"],["Approve contingency overrides","No (request only)","Yes"],["Modify commission settings","No","Yes"],["Rotate API keys / secrets","No","Yes"],["Impersonate users","No","Yes"]]}),e.jsxs(l,{type:"info",children:["All case_manager actions land in the same audit log as admin actions; both roles are gated through the ",e.jsx("code",{children:"has_role()"})," security-definer function."]})]})},{id:"tra-house-root",title:"TRA House Root Affiliate",category:"Financial",icon:e.jsx(Q,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["A dedicated ",e.jsx("strong",{children:"house
177-root affiliate"})," (id"," ",e.jsx("code",{children:"5637507e-…"}),') represents the "no sponsor" placeholder for every lead originated directly by TRA. This identity is required so the commission waterfall always has a terminating node and revenue can be attributed cleanly even when no external partner is involved.']}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Rules integrators MUST follow"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:[e.jsx("code",{children:"pool_grantor_id"})," MUST be ",e.jsx("code",{children:"NULL"})," when the sponsor is the house."]}),e.jsx("li",{children:"The house-root affiliate never appears in partner pickers."}),e.jsx("li",{children:"Cascading pool sub-allocations terminate at the house-root."}),e.jsx("li",{children:"Revenue routed to the house-root flows directly to TRA retained earnings in the waterfall."})]})]})},{id:"validated-inputs",title:"Validated Inputs Standard",category:"Reference",icon:e.jsx(A,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{children:"Every form in the platform — intake, account, agreements, broker invites, funder onboarding — consolidates address, phone, and email entry through three shared validated input components. This guarantees consistent data quality and eliminates per-form drift."}),e.jsx(t,{headers:["Field","Component","Validation"],rows:[["Address","AddressAutocomplete","Google Places-backed structured address (street, city, state, postal, country)"],["Phone","PhoneInput","E.164 normalization with country auto-detect"],["Email","EmailInput","RFC-compliant + disposable/role-based domain rejection"]]}),e.jsxs(l,{type:"warning",children:["Hand-rolled ",e.jsx("code",{children:'<input type="text">'})," for any of these fields is a code-review blocker. Use the validated component or extend it."]})]})},{id:"searchable-select-standard",title:"Entity Pickers — SearchableSelect Standard",category:"Reference",icon:e.jsx(O,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Every entity picker (partners, brokers, leads, users, clients, funders, organizations) MUST use the shared ",e.jsx("strong",{children:"SearchableSelect"})," component, never the base shadcn ",e.jsx("code",{children:"Select"}),". SearchableSelect provides type-ahead, keyboard navigation, async loading, and — critically — the standard"," ",e.jsx("code",{children:"data_source"})," filtering hook."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Required filter behavior"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Source queries MUST apply ",e.jsx("code",{children:"useDataMode().dataSourceFilter"}),"."]}),e.jsx("li",{children:"Live mode MUST NOT return sandbox, seed, or demo rows in any picker."}),e.jsxs("li",{children:["Use ",e.jsx("code",{children:".in('data_source', [...])"})," so new tags compose correctly."]})]})]})},{id:"referral-attribution",title:"Referral Attribution Across Hosts",category:"Operations",icon:e.jsx(S,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["The platform preserves affiliate credit across the full journey using a single query parameter (",e.jsx("code",{children:"?ref="}),") and a persistent first-party cookie. The attribution layer survives cross-host navigation (TRA canonical, white-labels, custom domains) and is re-applied on intake submission, account creation, and guest form posting."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Required behavior"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["All affiliate-shareable URLs include ",e.jsx("code",{children:"?ref=<slug>"}),"."]}),e.jsxs("li",{children:["Internal links use ",e.jsx("code",{children:"useRefHref()"})," so ",e.jsx("code",{children:"?ref="})," is preserved on navigation."]}),e.jsxs("li",{children:["Guest form submissions explicitly pass ",e.jsx("code",{children:"user_id: null"})," and the resolved ",e.jsx("code",{children:"ref"}),"."]}),e.jsx("li",{children:"Whitelabel deployments auto-attribute to the tenant if no explicit ref is present."})]})]})},{id:"validated-status-and-labels",title:"Status Labels & Title Casing",category:"Reference",icon:e.jsx(C,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:["Statuses surfaced anywhere in the UI MUST resolve through"," ",e.jsx("code",{children:"STATUS_LABELS"})," (Title Case with spaces). Raw snake_case values never reach the user. Status-change copy renders both sides as colored badges j
177oined with an arrow."]}),e.jsx("h4",{className:"font-semibold text-foreground mt-6",children:"Admin claim table rules"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-sm",children:[e.jsxs("li",{children:["Filters normalize status via ",e.jsx("code",{children:"normalizeLeadStatus"})," before comparison."]}),e.jsxs("li",{children:["Status dropdowns hide every key listed in ",e.jsx("code",{children:"RETIRED_STATUS_MAP"}),"."]})]})]})},{id:"est-recovery-helper",title:"Est. IEEPA Recovery Helper",category:"Reference",icon:e.jsx(b,{className:"h-4 w-4"}),content:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{children:['Every surface that displays "Est. IEEPA Recovery" — admin tables, partner dashboards, intake confirmations, agreements, AI assistant responses — MUST source its value from ',e.jsx("code",{children:"getEstRecovery()"})," in"," ",e.jsx("code",{children:"src/lib/lead-est-recovery.ts"}),". Inline math is a hard rule violation."]}),e.jsx(l,{type:"warning",children:"Centralizing this helper guarantees that scoring, agreement quoting, and assistant outputs cannot drift from each other."})]})},{id:"scroll-into-view-standard",title:"Scroll-Into-View Standard",category:"Reference",icon:e.jsx(J,{className:"h-4 w-4"}),content:e.jsx("div",{className:"space-y-4",children:e.jsxs("p",{children:["All programmatic scroll behavior across the platform routes through the"," ",e.jsx("code",{children:"useScrollIntoView"})," hook. The hook applies consistent offsets for sticky headers, respects reduced-motion preferences, and prevents layout thrash by batching scroll work."]})})}],ue=({onUnlock:n})=>{const[a,r]=d.useState(""),[s,u]=d.useState(!1),[p,x]=d.useState(""),[f,v]=d.useState(!1),g=async m=>{m.preventDefault(),u(!0),x("");try{const{data:i,error:o}=await V.functions.invoke("verify-docs-password",{body:{password:a}});if(o)throw o;i!=null&&i.valid?(sessionStorage.setItem("partner_docs_unlocked","true"),n()):x("Incorrect password. Please try again.")}catch{x("Unable to verify. Please try again.")}finally{u(!1)}};return e.jsx("div",{className:"min-h-screen bg-[hsl(222,47%,6%)] flex items-center justify-center p-4",children:e.jsx(H,{className:"w-full max-w-md border-border/30 bg-card/80 backdrop-blur-lg shadow-2xl",children:e.jsx(G,{className:"pt-8 pb-8 px-8",children:e.jsxs("div",{className:"flex flex-col items-center gap-6",children:[e.jsx(M,{variant:"dark",size:"md"}),e.jsxs("div",{className:"text-center space-y-2 mt-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Partner Documentation"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enter the access password to continue"})]}),e.jsxs("form",{onSubmit:g,className:"w-full space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Z,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(B,{type:f?"text":"password",value:a,onChange:m=>r(m.target.value),placeholder:"Access password",className:"pl-10 pr-10",autoFocus:!0}),e.jsx("button",{type:"button",onClick:()=>v(!f),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:f?e.jsx(ee,{className:"h-4 w-4"}):e.jsx(se,{className:"h-4 w-4"})})]}),p&&e.jsx("p",{className:"text-xs text-destructive",children:p}),e.jsxs(U,{type:"submit",disabled:s||!a,className:"w-full bg-primary text-primary-foreground",children:[s?e.jsx(te,{className:"h-4 w-4 animate-spin mr-2"}):null,s?"Verifying...":"Access Documentation"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:"This document is confidential. Unauthorized access is prohibited."})]})})})})},Ce=()=>{const[n,a]=d.useState(()=>sessionStorage.getItem("partner_docs_unlocked")==="true"),[r,s]=d.useState(""),[u,p]=d.useState("All"),[x,f]=d.useState(""),v=d.useRef(null),g=d.useMemo(()=>ce(),[]),m=d.useMemo(()=>g.filter(i=>{const o=u==="All"||i.category===u,h=!r||i.title.toLowerCase().includes(r.toLowerCase());return o&&h}),[g,u,r]);return d.useEffect(()=>{if(!n)return;const i=new IntersectionObserver(o=>{const h=o.filter(q=>q.isIntersecting);h.length>0&&f(h[0].target.id)}
177,{rootMargin:"-100px 0px -60% 0px"});return g.forEach(o=>{const h=document.getElementById(o.id);h&&i.observe(h)}),()=>i.disconnect()},[n,g]),n?e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"sticky top-0 z-50 bg-card border-b border-border shadow-sm backdrop-blur-lg",children:e.jsxs("div",{className:"max-w-[1400px] mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(M,{variant:"dark",size:"md"}),e.jsx(j,{orientation:"vertical",className:"h-8 bg-border/30"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-bold text-foreground",children:"Platform Technical Documentation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Confidential — Partner Reference • v3.0 • May 2026"})]})]}),e.jsx(k,{variant:"outline",className:"border-gold/40 text-gold text-xs",children:"CONFIDENTIAL"})]})}),e.jsxs("div",{className:"max-w-[1400px] mx-auto flex",children:[e.jsx("aside",{className:"hidden lg:block w-72 shrink-0 border-r border-border/30",children:e.jsxs("div",{className:"sticky top-[73px] h-[calc(100vh-73px)] overflow-y-auto p-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(B,{value:r,onChange:i=>s(i.target.value),placeholder:"Search sections...",className:"pl-9 h-8 text-xs"})]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:ie.map(i=>e.jsx("button",{onClick:()=>p(i),className:`text-[10px] px-2 py-1 rounded-full border transition-colors ${u===i?"bg-primary text-primary-foreground border-primary":"border-border text-muted-foreground hover:text-foreground hover:border-foreground
177/30"}`,children:i},i))}),e.jsx(j,{}),e.jsx("nav",{className:"space-y-0.5",children:m.map((i,o)=>e.jsxs("a",{href:`#${i.id}`,className:`flex items-center gap-2 px-2 py-1.5 rounded text-xs transition-colors ${x===i.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:text-foreground hover:bg-muted/30"}`,children:[e.jsxs("span",{className:"text-muted-foreground/50 w-4 text-right shrink-0",children:[o+1,"."]}),e.jsx("span",{className:"truncate",children:i.title})]},i.id))})]})}),e.jsxs("main",{ref:v,className:"flex-1 min-w-0 p-6 lg:p-10 space-y-12",children:[m.map((i,o)=>e.jsxs("section",{id:i.id,className:"scroll-mt-24",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-lg bg-primary/10 text-primary shrink-0",children:i.icon}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["§",o+1]}),e.jsx(k,{variant:"outline",className:"text-[10px] border-border/50",children:i.category})]}),e.jsx("h2",{className:"text-xl font-bold text-foreground",children:i.title})]})]}),e.jsx("div",{className:"prose prose-sm max-w-none text-sm text-muted-foreground leading-relaxed [&_h4]:text-foreground [&_p]:mb-3 [&_ul]:mb-3 [&_ol]:mb-3 [&_:not(pre)>code]:text-primary/90 [&_pre_code]:text-inherit",children:i.content}),o<m.length-1&&e.jsx(j,{className:"mt-12"})]},i.id)),e.jsxs("div",{className:"pt-12 pb-8 text-center space-y-2",children:[e.jsx(j,{}),e.jsx("p",{className:"text-xs text-muted-foreground pt-4",children:"This document is confidential and intended solely for authorized processing partners. Unauthorized distribution is prohibited."}),e.jsxs("p",{className:"text-[11px] text-muted-foreground/60",children:["© ",new Date().getFullYear()," — Platform Technical Documentation v3.0 • May 2026"]})]})]})]}),e.jsx("button",{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),className:"fixed bottom-6 right-6 h-10 w-10 rounded-full bg-primary text-primary-foreground shadow-lg flex items-center justify-center hover:bg-primary/90 transition-colors","aria-label":"Back to top",children:e.jsx(Y,{className:"h-4 w-4"})})]}):e.jsx(ue,{onUnlock:()=>a(!0)})};export{Ce as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.