Skip to content

Commit 722fbcd

Browse files
authored
Merge pull request #4 from rogerdemello/fix/workflow-bugs
Fix broken workflows, close security holes, demo-readiness polish
2 parents c53a5d5 + 89ba1fb commit 722fbcd

33 files changed

Lines changed: 815 additions & 276 deletions

‎.env.example‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
11
# Database Configuration
2-
# PostgreSQL connection string for Supabase or your own PostgreSQL instance
2+
# Used ONLY by `npx prisma db push` and `npm run seed`. The running app reaches
3+
# Supabase over REST (SUPABASE_URL + SUPABASE_ANON_KEY) and never opens this
4+
# connection, so the app still works if this is stale.
5+
#
6+
# On Supabase, use the SESSION-mode pooler on port 5432:
7+
# postgresql://postgres.<project-ref>:<password>@aws-<n>-<region>.pooler.supabase.com:5432/postgres?sslmode=require
8+
# Not the direct `db.<project-ref>.supabase.co` host — Supabase has retired it for
9+
# restored projects — and not the transaction pooler on 6543, which Prisma
10+
# migrations cannot use. Copy the exact string from
11+
# Supabase Dashboard → Settings → Database → Connection string → Session pooler.
312
DATABASE_URL="postgresql://postgres:password@localhost:5432/dealsentry"
413

514
# Supabase Configuration
615
# Get these from your Supabase project settings: https://app.supabase.com
716
SUPABASE_URL="https://your-project.supabase.co"
817
SUPABASE_ANON_KEY="your-supabase-anon-key-here"
18+
# Optional but recommended: the server prefers this key when set, so the API
19+
# keeps working after you enable Row Level Security on the tables.
20+
# Server-side only — never ship it to the browser.
21+
# SUPABASE_SERVICE_ROLE_KEY="your-supabase-service-role-key"
922

1023
# Azure OpenAI Configuration (for AI-powered features)
1124
# Required for proposal analysis and AI generation

‎ARCHITECTURE.md‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# DealSentry Architecture
2+
3+
DealSentry is an AI-assisted proposal compliance and risk review system. This
4+
document explains how the pieces fit together and, more importantly, *why* —
5+
including the trade-offs that were made deliberately.
6+
7+
## System overview
8+
9+
```mermaid
10+
flowchart LR
11+
subgraph Browser
12+
SPA["React 18 SPA<br/>(Vite, Tailwind, shadcn/ui,<br/>TanStack Query)"]
13+
end
14+
15+
subgraph "Express API (Node 20, tsx)"
16+
API["REST routers<br/>/api/proposals /rules /analyze<br/>/files /integrations /oauth ..."]
17+
MW["Middleware<br/>helmet · CORS allowlist ·<br/>rate limits · session resolver"]
18+
PDF["PDF export<br/>(Puppeteer / headless Chrome)"]
19+
end
20+
21+
subgraph Supabase
22+
PG[("PostgreSQL<br/>+ pgvector")]
23+
REST["PostgREST API"]
24+
STORE["Storage<br/>(proposal-files bucket)"]
25+
end
26+
27+
subgraph Azure["Azure OpenAI"]
28+
GPT["gpt-4o<br/>(analysis + generation)"]
29+
EMB["text-embedding-ada-002<br/>(semantic search)"]
30+
end
31+
32+
CRM["Salesforce · HubSpot · Gmail<br/>(OAuth 2.0, demo mode available)"]
33+
34+
SPA -- "/api/* (same-origin,<br/>Vite proxy in dev)" --> MW --> API
35+
API -- "supabase-js (REST)" --> REST --> PG
36+
API --> STORE
37+
API --> GPT
38+
API --> EMB
39+
API <--> CRM
40+
PDF --> API
41+
```
42+
43+
## Key design decisions
44+
45+
### 1. Two database access paths, on purpose
46+
47+
- **Runtime**: the Express API talks to Supabase over **PostgREST**
48+
(`supabase-js`). No connection pool to manage, works on serverless-ish free
49+
tiers, and survives the API host and database being in different regions.
50+
- **Schema & seeds**: **Prisma** is used *only* for `db push`, `db execute`
51+
(the manual SQL in `prisma/manual/`) and `npm run seed`, over the Supabase
52+
**session-mode pooler** (port 5432 — Prisma migrations cannot run over the
53+
transaction pooler on 6543).
54+
55+
The trade-off: no compile-time query types at runtime (PostgREST returns
56+
untyped JSON). That's the price of running well on a free tier; the routers
57+
type their own row interfaces at the boundary instead.
58+
59+
### 2. Demo-first authentication
60+
61+
There is deliberately **no login screen**: every request is served as a default
62+
user (`DEMO_USER_EMAIL`, falling back to the first ADMIN). The full JWT +
63+
bcrypt stack still exists (`/api/auth/login`, `/register`,
64+
`/change-password`) and valid bearer tokens win over the default identity, so
65+
real multi-user auth can be re-enabled by rendering the login page again.
66+
67+
### 3. AI with guardrails, not AI instead of rules
68+
69+
`/api/analyze` sends the proposal *content* (source of truth) plus the active
70+
compliance rules to gpt-4o and asks for structured findings. Hard limits
71+
(max 25% discount, 90-day payment terms, mandatory legal clauses, $10k minimum
72+
deal) are enforced twice: stated in the prompt *and* re-checked/capped in
73+
code after generation (`/api/proposals/generate` clamps the discount range).
74+
Results are normalized (`normalizeAnalysis`) before they become a RiskReport.
75+
76+
### 4. Semantic search via pgvector
77+
78+
Every proposal gets a 1536-dim embedding on create (best-effort — failures
79+
never block the write). Search calls the `match_proposals` SQL function
80+
(cosine distance, ivfflat index). If the extension/function is missing the API
81+
answers `available: false` and the client falls back to substring search —
82+
the feature degrades, it doesn't break.
83+
84+
Setup lives in `prisma/manual/semantic_search.sql`; backfill with
85+
`npm run backfill:embeddings`.
86+
87+
### 5. Integrations with a real demo mode
88+
89+
Salesforce/HubSpot/Gmail connect over standard OAuth 2.0. With
90+
`*_DEMO_MODE=true`, connect stores `{demo: true}` credentials and **sync
91+
imports canned deals as proposals**, so the connect → sync → analyze → approve
92+
story is demonstrable without any external accounts. Real-mode sync handles
93+
token refresh and dedupes on the CRM record id.
94+
95+
### 6. Deployment (Render, Docker)
96+
97+
One container serves both the API and the built SPA (Express serves `dist/` in
98+
production, so CORS is a non-issue for same-origin traffic). The runtime image
99+
installs system Chromium for PDF export (`PUPPETEER_EXECUTABLE_PATH`), because
100+
the free tier's 512 MB can't afford Puppeteer's bundled download at build time.
101+
`render.yaml` is a full Blueprint — secrets are dashboard-only (`sync: false`).
102+
103+
## Security model (current state and roadmap)
104+
105+
| Area | Today | Next step |
106+
| --- | --- | --- |
107+
| API auth | Default-user demo mode; JWT honored when present | Re-enable login UI for multi-user |
108+
| DB access | Server-side key via supabase-js; anon key works, service-role preferred when set | Enable RLS per table; drop anon write policies |
109+
| Secrets | `.env` git-ignored; Render dashboard for prod | Rotate any key that was ever committed |
110+
| Responses | Password hashes stripped from every user payload; mutations admin-gated | Field-level DTOs |
111+
112+
## Repository map
113+
114+
```
115+
server.ts Express bootstrap, static SPA serving, error handling
116+
src/api/ One router per resource + middleware/ + lib/
117+
src/lib/ API client (frontend), supabase client (backend), utils
118+
src/pages/ components/ React SPA
119+
prisma/ schema.prisma, seed.ts, manual/*.sql (pgvector, storage)
120+
scripts/ backfill-embeddings, cleanup-integrations, migrate-auth
121+
tests/ Vitest + Supertest API tests
122+
```

‎CREDENTIALS.md‎

Lines changed: 0 additions & 68 deletions
This file was deleted.

‎README.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,21 @@ Typical development time was about 2 to 4 focused hours per day during active im
4949
```bash
5050
npm install
5151
npx prisma generate
52-
npx prisma migrate deploy
52+
npx prisma db push # sync the schema (this repo has no migration files)
5353
npm run seed
5454
```
5555

56+
Then apply the one-time manual SQL (idempotent, safe to re-run):
57+
58+
```bash
59+
# pgvector + semantic search function (required for proposal search)
60+
npx prisma db execute --file prisma/manual/semantic_search.sql
61+
npm run backfill:embeddings
62+
63+
# Storage bucket + policies (required for document upload)
64+
npx prisma db execute --file prisma/manual/storage_bucket.sql
65+
```
66+
5667
### Run
5768

5869
```bash
@@ -63,6 +74,8 @@ On Windows, you can also use `start.bat` to launch the backend and frontend toge
6374

6475
## Documentation
6576

77+
- [ARCHITECTURE.md](ARCHITECTURE.md) — system design and trade-offs
78+
- [docs/DEMO_SCRIPT.md](docs/DEMO_SCRIPT.md) — rehearsed demo storyline
6679
- [SETUP.md](SETUP.md)
6780
- [COMPLIANCE_RULES.md](COMPLIANCE_RULES.md)
6881
- [docs/SERVER_STABILITY.md](docs/SERVER_STABILITY.md)

‎docs/DEMO_SCRIPT.md‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# DealSentry — 7-minute demo script
2+
3+
A rehearsed storyline that shows every major capability without dead ends.
4+
Practice it twice before presenting; every step below is verified working.
5+
6+
> **Before the demo (2 min):** open the deployed URL once to wake the Render
7+
> free-tier instance (cold start ≈ 30s), and keep a second tab on the
8+
> Dashboard. Locally: `npm run dev:full`, then http://localhost:8080.
9+
10+
## 1. The problem (30s)
11+
12+
"Sales teams send out proposals with pricing and legal problems — discounts
13+
nobody approved, missing indemnification clauses, 120-day payment terms.
14+
DealSentry catches these before the proposal leaves the building."
15+
16+
## 2. Dashboard tour (30s)
17+
18+
- Point at the analytics: status breakdown, average readiness score,
19+
needs-attention count — all computed from live data.
20+
21+
## 3. AI generation (90s) — *the wow moment*
22+
23+
- New Proposal → AI generate, type:
24+
*"Proposal for TechNova Inc, $75,000 data platform modernization, 10%
25+
discount, net 60 payment, healthcare industry"*
26+
- Show the generated document: full sections, all five mandatory legal
27+
clauses. Point out that the generator **enforces** policy (caps discounts at
28+
25%, payment terms at 90 days) — AI with guardrails, not instead of them.
29+
30+
## 4. Catching a risky proposal (2 min) — *the core story*
31+
32+
- Upload `sample_proposal/` docx (or create one) with deliberate violations:
33+
35% discount, Net 120 payment terms, no legal clauses.
34+
- Run analysis → walk through the risk report:
35+
- **CRITICAL — Discount violation** (35% > 25% policy)
36+
- **HIGH — Payment terms** (120 > 90 days)
37+
- **HIGH — Missing legal clauses**
38+
- Readiness score + legal/pricing/structural risk breakdown.
39+
- Show the AI recommendations, then **Reject** it. Open the Audit page —
40+
every action is logged with actor and before/after.
41+
42+
## 5. Semantic search (45s)
43+
44+
- Search "cloud migration" — results rank by *meaning* (pgvector cosine
45+
similarity over Azure OpenAI embeddings), not keywords. Mention the graceful
46+
fallback to substring search when embeddings are unavailable.
47+
48+
## 6. CRM integration (45s)
49+
50+
- Integrations → Connect Salesforce (demo mode) → Sync.
51+
- Three deals import as proposals instantly; each can now be analyzed.
52+
Mention: real mode is the same OAuth flow with token refresh.
53+
54+
## 7. Boardroom-ready output (30s)
55+
56+
- Open an analyzed proposal → Export PDF. Show the cover page, compliance
57+
appendix with the quality scores, and page numbering. (Headless Chrome
58+
server-side.)
59+
60+
## 8. Close (30s)
61+
62+
"React + Express + Supabase + Azure OpenAI, deployed on Render from a Docker
63+
blueprint, CI-tested, with policy enforced in code and AI explaining the why.
64+
Everything you saw is in the repo — including the architecture doc."
65+
66+
## Q&A cheat sheet
67+
68+
- **Why no login?** Demo mode by design; the JWT/bcrypt stack is live and
69+
honored when a token is present (`docs/AUTH_QUICKSTART.md`).
70+
- **What stops the AI hallucinating compliance?** Deterministic re-checks in
71+
code: discounts clamped, thresholds hardcoded, findings normalized.
72+
- **How would you scale it?** Enable RLS + service-role key (already
73+
supported), move PDF export to a worker, add Redis for rate limits.
74+
- **Weakest point?** Schema drift between Prisma schema and the live DB —
75+
known, documented in ARCHITECTURE.md, and contained because runtime access
76+
goes through PostgREST.

‎eslint.config.mjs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,12 @@ export default tseslint.config(
4343
"no-useless-escape": "warn",
4444
},
4545
},
46+
{
47+
// shadcn/ui generated components export variants/hooks alongside the
48+
// component by design; fast-refresh purity doesn't apply to them.
49+
files: ["src/components/ui/**/*.{ts,tsx}"],
50+
rules: {
51+
"react-refresh/only-export-components": "off",
52+
},
53+
},
4654
);

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"server": "tsx --watch server.ts",
1111
"start": "npm run build && npx tsx server.ts",
1212
"dev:full": "concurrently --kill-others \"npm run server\" \"wait-on http://localhost:3001/api/health && npm run dev\"",
13-
"lint": "eslint .",
13+
"lint": "eslint . --max-warnings 0",
1414
"test": "vitest run",
1515
"test:watch": "vitest",
1616
"test:coverage": "vitest run --coverage",

‎prisma/manual/semantic_search.sql‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ create extension if not exists vector;
1111
-- 2. Embedding column on Proposal (text-embedding-ada-002 => 1536 dims)
1212
alter table "Proposal" add column if not exists embedding vector(1536);
1313

14+
-- 2b. Tenant column referenced by match_proposals below. The API writes it
15+
-- conditionally (only for users with a companyId), so it must exist even
16+
-- on databases that predate company scoping.
17+
alter table "Proposal" add column if not exists company_id text;
18+
1419
-- 3. Approximate-nearest-neighbour index (cosine distance).
1520
-- Tune `lists` upward as the table grows (≈ rows/1000).
1621
create index if not exists proposal_embedding_idx

‎prisma/manual/storage_bucket.sql‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-- Storage setup for document upload (/api/files). Run ONCE against your
2+
-- Supabase Postgres (Supabase Studio → SQL editor, or:
3+
-- npx prisma db execute --file prisma/manual/storage_bucket.sql
4+
-- ). Idempotent / safe to re-run.
5+
6+
-- 1. The bucket the API uploads proposal documents into.
7+
insert into storage.buckets (id, name, public)
8+
values ('proposal-files', 'proposal-files', true)
9+
on conflict (id) do nothing;
10+
11+
-- 2. The app talks to Storage with the anon key, so anon needs object access
12+
-- scoped to this bucket. (If you later move to a service-role key
13+
-- server-side, these policies can be dropped.)
14+
drop policy if exists "proposal-files anon read" on storage.objects;
15+
create policy "proposal-files anon read" on storage.objects
16+
for select to anon using (bucket_id = 'proposal-files');
17+
18+
drop policy if exists "proposal-files anon insert" on storage.objects;
19+
create policy "proposal-files anon insert" on storage.objects
20+
for insert to anon with check (bucket_id = 'proposal-files');
21+
22+
drop policy if exists "proposal-files anon delete" on storage.objects;
23+
create policy "proposal-files anon delete" on storage.objects
24+
for delete to anon using (bucket_id = 'proposal-files');

‎prisma/schema.prisma‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ model Proposal {
5454
renewalDate DateTime?
5555
autoRenew Boolean @default(false)
5656
57+
// Tenant scoping column used by the API's company checks. Nullable: rows
58+
// created in single-tenant/demo mode have no company. Added by
59+
// prisma/manual/semantic_search.sql on databases that predate it — kept here
60+
// so `prisma db push` doesn't try to drop it.
61+
companyId String? @map("company_id")
62+
5763
// Semantic search embedding (pgvector). Added via prisma/manual/semantic_search.sql;
5864
// populated best-effort on create and by scripts/backfill-embeddings.ts.
5965
embedding Unsupported("vector(1536)")?

0 commit comments

Comments
 (0)