<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[avyay.dev]]></title><description><![CDATA[Documenting the journey of turning complex ideas into functional, production-ready software. I write about backend architecture, and the reality of shipping pro]]></description><link>https://avyay-dev.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6aa18b46d587e89d6325ee1e/716e470a-a867-458d-8e9a-2226ce16bda9.png</url><title>avyay.dev</title><link>https://avyay-dev.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 20 Sep 2026 22:39:59 GMT</lastBuildDate><atom:link href="https://avyay-dev.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building PrismQTC: How I Built an Autonomous B2B Quote-to-Cash & Pricing Governance Platform
]]></title><description><![CDATA[Most B2B software treats sales as a sequence of isolated, static records: a quotation generated as an un-editable PDF, followed by disconnected email chains, manual margin approvals in spreadsheets, d]]></description><link>https://avyay-dev.hashnode.dev/prismqtc</link><guid isPermaLink="true">https://avyay-dev.hashnode.dev/prismqtc</guid><category><![CDATA[System Architecture]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Developer]]></category><category><![CDATA[DevOps Journey]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[nodeJS Developer]]></category><category><![CDATA[React]]></category><category><![CDATA[nginx ingress]]></category><category><![CDATA[Grafana]]></category><category><![CDATA[#prometheus]]></category><category><![CDATA[loki]]></category><dc:creator><![CDATA[Avyay Kachhia]]></dc:creator><pubDate>Fri, 18 Sep 2026 19:45:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aa18b46d587e89d6325ee1e/1192fd07-0f3f-494d-80ec-098a35f8d692.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>Most B2B software treats sales as a sequence of isolated, static records: a quotation generated as an un-editable PDF, followed by disconnected email chains, manual margin approvals in spreadsheets, detached warehouse inventory lookups, and un-reconciled billing runs.</p>
<p>When high-velocity B2B sales teams run into real-world operational turbulence—such as complex multi-tier discount limits, stock dispersed across three different regional warehouses, mid-contract subscription proration, and external buyers demanding interactive negotiation—traditional ERP setups like Odoo, Salesforce CPQ, or NetSuite generate immense operational friction.</p>
<p>To solve this, I designed and built <strong>PrismQTC</strong> (formerly DealFlow 360): a self-governing, multi-tenant B2B Sales Operations, Quote-to-Cash (QTC), and Deal Execution Platform.</p>
<p>In this comprehensive post, I am breaking down <strong>everything</strong> under the hood:</p>
<ul>
<li><p>Why I rejected traditional ORMs in favor of PostgreSQL Row-Level Security (<code>SET LOCAL</code>) and Column-Level Access Control (CLAC).</p>
</li>
<li><p>How PL/pgSQL reactive triggers mathematically enforce discount ceilings and calculate blended risk scores.</p>
</li>
<li><p>How line items are dynamically split across regional warehouses with automatic backorders.</p>
</li>
<li><p>How bidirectional WebSockets power live customer counter-offers and quote locking.</p>
</li>
<li><p>How client-side vector PDF and Word (<code>.docx</code>) engines eliminate document generation server load.</p>
</li>
<li><p>The complete DevOps orchestration spanning Nginx, Redis Stack, BullMQ, Prometheus, Loki, and Grafana.</p>
</li>
</ul>
<hr />
<h2>📑 Table of Contents &amp; Full Content Modules</h2>
<p>Every single module, architectural diagram, code block, and formula is contained directly inside the sections below:</p>
<hr />
<details>
<summary><h3>1. High-Level System Topology &amp; Architecture</h3></summary>
<p>The platform is designed around a decoupled, high-throughput micro-modular topology:</p>
<pre><code class="language-text">┌──────────────────────────────────────────────────────────┐
│                      FRONTEND LAYER                      │
│  React 19 (SPA)  │  TypeScript 5.8  │  Vite 6            │
│  Tailwind CSS v4 │  Socket.IO       │  Motion + Lucide   │
│  SWR Cache       │  Axios Client    │  jsPDF + docx      │
└────────────────────────────┬─────────────────────────────┘
                             │ HTTP / WebSocket (Port 80)
                             ▼
┌──────────────────────────────────────────────────────────┐
│                 GATEWAY &amp; REVERSE PROXY                  │
│  Nginx (Alpine) — Routing, Assets, Caching, WS Upgrade   │
└────────────────────────────┬─────────────────────────────┘
                             │
              ┌──────────────┴──────────────┐
              ▼                             ▼
┌───────────────────────────┐ ┌────────────────────────────┐
│        BACKEND API        │ │   ASYNC WORKERS &amp; CACHE    │
│ Node.js (ESM) + Express   │ │ Redis Stack 7 (Broker/AOF) │
│ Socket.IO Real-Time Hub   │ │ BullMQ Job Queue Workers   │
│ Argon2 + Dual JWT Auth    │ │ node-cron Schedule Engine  │
│ Raw pg (withTenantContext)│ │ RedisInsight Web Dashboard │
└─────────────┬─────────────┘ └──────────────┬─────────────┘
              │                              │
              └──────────────┬───────────────┘
                             ▼
┌──────────────────────────────────────────────────────────┐
│                      DATABASE LAYER                      │
│  PostgreSQL 16 Alpine                                    │
│  ├─ Row-Level Security (RLS) &amp; Column Grants (CLAC)      │
│  ├─ PL/pgSQL Reactive Triggers (Margin &amp; Risk Math)      │
│  └─ Stored Procedures (Atomic Orders, Stalled Sweeps)    │
└────────────────────────────┬─────────────────────────────┘
                             │ Metrics &amp; Log Streams
                             ▼
┌──────────────────────────────────────────────────────────┐
│                OBSERVABILITY &amp; MONITORING                │
│  Prometheus v2.52 (Metrics) │ Loki v3.0 (Log Streams)    │
│  Grafana v11.0 (Pre-Provisioned Unified Dashboards)      │
└──────────────────────────────────────────────────────────┘
</code></pre>
<h4>Complete Technology Stack Matrix</h4>
<table>
<thead>
<tr>
<th>Component</th>
<th>Technology</th>
<th>Role in PrismQTC</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Frontend</strong></td>
<td>React 19 + TS 5.8</td>
<td>Concurrent rendering, deal builder</td>
</tr>
<tr>
<td><strong>Build Tool</strong></td>
<td>Vite 6</td>
<td>Lightning-fast HMR, ESM bundles</td>
</tr>
<tr>
<td><strong>Styling</strong></td>
<td>Tailwind v4 + Tokens</td>
<td>Pure CSS tokens, zero runtime</td>
</tr>
<tr>
<td><strong>Animation</strong></td>
<td>Motion (<code>motion</code>)</td>
<td>Spring physics, fluid drawers</td>
</tr>
<tr>
<td><strong>Data Fetch</strong></td>
<td>Axios + SWR</td>
<td>Optimistic cache revalidation</td>
</tr>
<tr>
<td><strong>Real-Time</strong></td>
<td>Socket.IO</td>
<td>Bidirectional room negotiation</td>
</tr>
<tr>
<td><strong>Backend API</strong></td>
<td>Node.js + Express</td>
<td>RESTful services, security guards</td>
</tr>
<tr>
<td><strong>Database</strong></td>
<td>PostgreSQL 16</td>
<td>Primary datastore, RLS, triggers</td>
</tr>
<tr>
<td><strong>Queue</strong></td>
<td>BullMQ + Redis</td>
<td>Background jobs, rate limiting</td>
</tr>
<tr>
<td><strong>Auth</strong></td>
<td>Argon2 + Dual JWT</td>
<td>HttpOnly role-isolated cookies</td>
</tr>
<tr>
<td><strong>Payments</strong></td>
<td>Razorpay SDK</td>
<td>Cryptographic webhook capture</td>
</tr>
<tr>
<td><strong>Gateway</strong></td>
<td>Nginx Alpine</td>
<td>SSL, reverse proxy, WS upgrade</td>
</tr>
<tr>
<td><strong>Telemetry</strong></td>
<td>Prometheus + Loki</td>
<td>Scrapes /metrics, log ingestion</td>
</tr>
<tr>
<td><strong>Dashboard</strong></td>
<td>Grafana 11</td>
<td>Unified metrics &amp; log viewer</td>
</tr>
</tbody>
</table>
</details>

<hr />
<details>
<summary><h3>2. Database Architecture &amp; Zero-Trust Multi-Tenancy</h3></summary>
<h4>Why I Ditched ORMs for Native PostgreSQL Drivers</h4>
<p>Most enterprise applications implement multi-tenancy by appending <code>WHERE tenant_id = ?</code> to every query via an ORM middleware. A single developer omission, an un-scoped raw query, or an ORM bug can cause cross-tenant data leaks.</p>
<p>In <strong>PrismQTC</strong>, multi-tenancy is enforced directly by PostgreSQL using <strong>Row-Level Security (RLS)</strong> with <strong>transaction-scoped configuration settings</strong>:</p>
<pre><code class="language-sql">BEGIN;
  -- Scoped strictly to this transaction block
  SET LOCAL app.current_tenant_id = 'a1b2c3d4-e5f6...';
  SET LOCAL app.current_actor_type = 'staff';
  SET LOCAL app.current_user_id = 'f9e8d7c6-b5a4...';
  SET LOCAL app.current_role = 'sales_rep';
  SET LOCAL ROLE app_role_staff;
  -- The kernel guarantees no other tenant rows can be read
  SELECT id, quote_number, total_amount 
  FROM quotations 
  WHERE id = $1;
COMMIT;
</code></pre>
<h4>Why <code>SET LOCAL</code> is Crucial</h4>
<p><code>SET LOCAL</code> guarantees that session configuration variables vanish automatically on <code>COMMIT</code> or <code>ROLLBACK</code>. When connections return to the <code>node-postgres</code> pool, no cross-tenant parameters linger.</p>
<p>All operational tables declare:</p>
<pre><code class="language-sql">ALTER TABLE quotations ENABLE ROW LEVEL SECURITY;
ALTER TABLE quotations FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON quotations
    FOR ALL
    USING (
      tenant_id = current_setting('app.current_tenant_id', true)::UUID
    );
</code></pre>
<h4>Column-Level Access Control (CLAC)</h4>
<p>RLS restricts <strong>rows</strong>, not <strong>columns</strong>. To stop external customers from seeing sensitive columns like <code>unit_cost</code>, <code>total_cost</code>, <code>line_margin_pct</code>, or <code>blended_risk_score</code>, PrismQTC establishes two database roles:</p>
<ol>
<li><code>app_role_staff</code>: Full read/write access to all table columns.</li>
<li><code>app_role_customer_portal</code>: Strict column whitelist:</li>
</ol>
<pre><code class="language-sql">GRANT SELECT (
    id, tenant_id, quote_number, status, 
    subtotal_amount, tax_amount, total_amount, 
    currency, customer_notes, created_at
) ON quotations TO app_role_customer_portal;
-- Customer portal role CANNOT select unit_cost or line_margin_pct
-- Attempting to query them triggers an instant database error
</code></pre>
<h4>Complete Schema Entity Map (18 Tables)</h4>
<ul>
<li><code>tenants</code>: Multi-tenant organization boundaries, subdomains, currencies.</li>
<li><code>users</code>: Internal staff members (Admins, Sales Managers, Reps, Finance).</li>
<li><code>customers</code>: Client organizations assigned to tiers (<code>Bronze</code> to <code>Platinum</code>).</li>
<li><code>customer_portal_users</code>: External customer contacts authenticated via magic links.</li>
<li><code>product_categories</code>: Category discount ceilings (e.g., Hardware 10%, Services 15%).</li>
<li><code>products</code>: Base catalog items, inventory levels, cost vs retail, tax rates.</li>
<li><code>product_variants</code>: Attribute variations with price deltas.</li>
<li><code>price_lists</code> &amp; <code>price_list_items</code>: Tier-specific price overrides per currency.</li>
<li><code>upsell_rules</code>: Product recommendation triggers based on margin thresholds.</li>
<li><code>quotation_requests</code> &amp; <code>items</code>: Inbound customer RFQs from the portal.</li>
<li><code>tier_discount_ceilings</code>: Category-level discount thresholds per customer tier.</li>
<li><code>quotations</code> &amp; <code>quotation_lines</code>: The core living transaction document.</li>
<li><code>approval_audit_logs</code>: Immutable ledger of manager/finance approval decisions.</li>
<li><code>quotation_negotiation_threads</code>: Real-time chat threads and counter-offers.</li>
<li><code>shipments</code> &amp; <code>shipment_items</code>: Split-warehouse dispatch tracking and backorders.</li>
<li><code>invoices</code> &amp; <code>invoice_lines</code>: Reconciled billing statements with delivery matching.</li>
<li><code>subscriptions</code>: Contract recurrence schedules and seat proration parameters.</li>
<li><code>deal_health_alerts</code>: Proactive anomaly flags (stalled deals, margin breaches).</li>
</ul>
</details>

<hr />
<details>
<summary><h3>3. The Pricing Governance &amp; Blended Risk Engine</h3></summary>
<p>In high-volume B2B sales, reps often slash prices to hit quotas, eroding margins. PrismQTC automates pricing discipline directly inside the PostgreSQL database engine.</p>
<h4>The Blended Risk Score Formula</h4>
<p>The platform computes a mathematically weighted <strong>Blended Risk Score</strong> ($0 - 10$ scale) for every quotation:</p>
\text{Blended Risk Score} = \sum_{i=1}^{n} \left( \frac{\text{Line Total}<em>i}{\text{Quote Total}} \times \text{Risk}<em>i \right) + \Delta</em>{\text{Margin}} + \Delta</em>{\text{Rep}}
<p>Where:</p>
<ul>
<li>\(\text{Line Discount} \le \text{Tier Ceiling} \implies \text{Risk} = 0\)</li>
<li>\(\text{Line Discount} &gt; \text{Tier Ceiling} \implies \text{Risk} = \left(\frac{\text{Discount} - \text{Ceiling}}{\text{Ceiling}}\right) \times 10\)</li>
<li>\(\Delta_{\text{Margin}}\) triggers if Gross Margin drops below the company floor ($18%$).</li>
<li>\(\Delta_{\text{Rep}}\) factors in the rep's trailing discount history.</li>
</ul>
<h4>Visual Risk Thresholds</h4>
<ul>
<li><strong>🟢 Score $&lt; 5.0$ (Low Risk):</strong> Complies with ceilings; instant client dispatch permitted.</li>
<li><strong>🟡 Score \(= 5.0\) (Moderate Risk):</strong> Max ceiling reached; advisory review suggested.</li>
<li><strong>🔴 Score \(&gt; 5.0\) (Critical Risk):</strong> Threshold breached; auto-routed to approval queue.</li>
</ul>
<h4>Reactive PL/pgSQL Trigger Engine</h4>
<p>Calculations are executed instantly by PostgreSQL triggers:</p>
<pre><code class="language-sql">CREATE OR REPLACE FUNCTION trg_calculate_quote_line_financials()
RETURNS TRIGGER AS $$
DECLARE
    v_unit_cost NUMERIC(12, 2);
BEGIN
    SELECT unit_cost INTO v_unit_cost 
    FROM products WHERE id = NEW.product_id;
<pre><code>NEW.line_subtotal := NEW.quantity * NEW.unit_price;
NEW.line_discount_amount := NEW.line_subtotal * 
    (NEW.applied_discount_pct / 100.0);
NEW.line_total := NEW.line_subtotal - 
    NEW.line_discount_amount;
NEW.line_cost_subtotal := NEW.quantity * v_unit_cost;
<p>IF NEW.line_total &gt; 0 THEN
NEW.line_margin_pct := ((NEW.line_total -
NEW.line_cost_subtotal) / NEW.line_total) * 100.0;
ELSE
NEW.line_margin_pct := 0.0;
END IF;</p>
</code><p><code>RETURN NEW;
</code></p></pre><p></p>
<p>END;
$$ LANGUAGE plpgsql;</p>
</code><p><code class="language-sql">CREATE TRIGGER trg_quote_lines_calc
BEFORE INSERT OR UPDATE ON quotation_lines
FOR EACH ROW
EXECUTE FUNCTION trg_calculate_quote_line_financials();
</code></p></pre><p></p>
<h4>Multi-Tier Approval Chain Automation</h4>
<p>When a quote breaches risk limits:</p>
<ol>
<li><strong>Manager Tier (\(&gt;10%\) Discount):</strong> Moves to <code>pending_manager</code>.</li>
<li><strong>Finance Tier (\(&gt;15%\) Discount or Gross Margin $&lt; 20%$):</strong> Moves to <code>pending_finance</code>.</li>
<li>Every decision writes an immutable log to <code>approval_audit_logs</code>.</li>
</ol>
</details>

<hr />
<details>
<summary><h3>4. Smart Split-Warehouse Fulfillment &amp; Backorders</h3></summary>
<p>When inventory is dispersed across regional facilities, PrismQTC dynamically splits line items across depots:</p>
<pre><code class="language-text">               [ PRISMQTC ORDER #PQ-9281 ]
                            |
                +-----------+-----------+
                |                       |
          [ MAIN WAREHOUSE ]      [ EAST DEPOT ]
          * 85 Units In-Stock     * 15 Units In-Stock
          * Lowest Zone Rate      * Regional Express
                |                       |
          [ SHIPMENT #01 ]        [ SHIPMENT #02 ]
                \                       /
                 +----------+----------+
                            |
                [ BACKORDER CONSOLIDATED ]
                [ TRANSIT COST MINIMIZED ]
</code></pre>
<h4>Split Shipment Execution Flow</h4>
<ol>
<li>Evaluates inventory for each line item in real-time.</li>
<li>If Warehouse A has partial stock, it creates <strong>Shipment #01</strong> and assigns a tracking number.</li>
<li>The remaining quantity routes to Warehouse B (<strong>Shipment #02</strong>) or an <strong>Automated Backorder</strong>.</li>
<li>Invoices map directly to <code>shipment_id</code> records, ensuring buyers are billed only for delivered inventory.</li>
</ol>
</details>

<hr />
<details>
<summary><h3>5. Real-Time Customer Portal &amp; Living Contract Negotiation</h3></summary>
<p>PrismQTC replaces static email PDFs with a synchronized <strong>Customer Portal</strong> (<code>/portal</code>).</p>
<h4>Dual-Token Authentication</h4>
<ul>
<li>Internal staff authenticate via <code>/api/auth/login</code> and receive a staff JWT in an <code>httpOnly</code> cookie.</li>
<li>External buyers authenticate via <code>/api/portal/auth/login</code> or magic links, receiving a scoped customer portal token.</li>
</ul>
<h4>Bidirectional WebSocket Negotiation</h4>
<p>Powered by Socket.IO:</p>
<pre><code class="language-typescript">const socket = io({ path: '/socket.io' });
useEffect(() =&gt; {
  socket.emit('join:quote_negotiation', { quoteId });
  socket.on('quote:counter_offer_received', (data) =&gt; {
    toast.info(`Counter-offer submitted: ₹${data.newTotal}`);
    mutate(); // Optimistic SWR refresh
  });
  socket.on('quote:locked_by_staff', () =&gt; {
    setIsLocked(true);
    toast.warning('Quote is under management review.');
  });
  return () =&gt; {
    socket.emit('leave:quote_negotiation', { quoteId });
  };
}, [quoteId]);
</code></pre>
<h4>Atomic Confirmation via Stored Procedure</h4>
<p>Accepting a proposal executes an atomic PostgreSQL stored procedure:</p>
<pre><code class="language-sql">CREATE OR REPLACE PROCEDURE sp_customer_confirm_quotation(
    p_quotation_id UUID,
    p_customer_id UUID,
    p_portal_user_id UUID
)
LANGUAGE plpgsql
AS $$
BEGIN
    PERFORM 1 FROM quotations 
    WHERE id = p_quotation_id 
      AND customer_id = p_customer_id 
      AND status IN ('sent', 'under_negotiation')
    FOR UPDATE;
    IF NOT FOUND THEN
        RAISE EXCEPTION 'Quotation cannot be confirmed in current state.';
    END IF;
    UPDATE quotations 
    SET status = 'confirmed',
        confirmed_at = NOW(),
        confirmed_by_portal_user_id = p_portal_user_id
    WHERE id = p_quotation_id;
    PERFORM fn_allocate_split_warehouse_shipments(p_quotation_id);
END;
$$;
</code></pre>
</details>

<hr />
<details>
<summary><h3>6. Hybrid Contract Billing, Invoicing &amp; Razorpay Settlement</h3></summary>
<p>Deals bundle one-off hardware, professional services, and recurring subscriptions into a single contract schedule.</p>
<h4>Hybrid Order Proration</h4>
<p>Subscriptions compute day-precise seat proration when licenses are added mid-billing cycle:</p>
\text{Prorated Charge} = \frac{\text{Days Remaining in Cycle}}{\text{Total Days in Cycle}} \times (\text{Seat Count} \times \text{Seat Price})
<h4>4-Stage Invoicing Stepper</h4>
<pre><code class="language-text">[ Order Confirmed ] ──▶ [ Shipped ] ──▶ [ Invoiced ] ──▶ [ Paid ]
</code></pre>
<h4>Razorpay Integration</h4>
<ol>
<li>Backend creates an order via Razorpay SDK (<code>razorpay.orders.create</code>).</li>
<li>Client mounts checkout modal with brand accents (<code>#ff3b30</code>).</li>
<li>Backend cryptographically verifies the payment signature (<code>crypto.createHmac('sha256', secret)</code>) before marking the invoice as <code>PAID</code>.</li>
</ol>
</details>

<hr />
<details>
<summary><h3>7. Deal Health, Telemetry &amp; Autonomous Anomaly Detection</h3></summary>
<p>The <strong>Deal Health Dashboard</strong> (<code>/dealhealth</code>) monitors three automated anomaly sweeps:</p>
<pre><code class="language-text">┌──────────────────────────────────────────────────────────┐
│                    DEAL HEALTH RADAR                     │
├──────────────────────────────────────────────────────────┤
│ [STALLED]   Quote #QT-4401 | 14 Days Inactive | Action   │
│ [MARGIN]    Quote #QT-9920 | Rep: R. Rep (-6.2% vs Avg)  │
│ [SLIPPAGE]  Depot East Shortfall on SKU: SRV-2U-PRO      │
└──────────────────────────────────────────────────────────┘
</code></pre>
<ol>
<li><strong>Stalled Deals:</strong> Flags quotations idling past expected closing dates.</li>
<li><strong>Discount Anomalies:</strong> Rolling z-score analysis flags quotes where discounts exceed a rep's 90-day baseline.</li>
<li><strong>Delivery Slippage:</strong> Detects backorders threatening customer delivery SLAs.</li>
<li><strong>Autonomous Sweeper:</strong> <code>governanceSweeper.js</code> executes <code>sp_flag_stalled_deals()</code> hourly via <code>node-cron</code>.</li>
</ol>
</details>

<hr />
<details>
<summary><h3>8. Frontend Engineering: React 19, Vite &amp; Design Token System</h3></summary>
<h4>Modern React 19 Architecture</h4>
<ul>
<li><strong>Zero Heavy UI Kits:</strong> Built with native Tailwind CSS v4 and a unified token system.</li>
<li><strong>SWR Caching:</strong> Real-time optimistic mutations across tables, modals, and badges.</li>
<li><strong>Role-Based Routing:</strong> Guards enforce route access by user role (<code>admin</code>, <code>sales_manager</code>, <code>sales_rep</code>, <code>finance</code>, <code>customer</code>).</li>
</ul>
<h4>Global CSS Design System (<code>frontend/src/global css/</code>)</h4>
<ul>
<li><code>tokens.css</code>: Color ramps, semantic states (<code>--app-brand-red: #ff3b30</code>), border radiuses.</li>
<li><code>tables.css</code>: High-density ledger styling with sticky headers and numeric alignments.</li>
<li><code>cards.css</code>: Clean, border-accented containers with subtle elevation.</li>
<li><code>badges.css</code>: High-contrast WCAG AAA compliant workflow badges.</li>
<li><code>modals.css</code>: Fluid backdrop blurs and focus traps.</li>
</ul>
<h4>The Landing Page Experience</h4>
<ul>
<li><strong>Kinetic Scramble CTA Buttons:</strong> Characters scramble on hover using monospace text manipulation.</li>
<li><strong>Word-by-Word Scroll Darkening:</strong> <code>ManifestoScrollSection.tsx</code> darkens words as the user scrolls.</li>
<li><strong>Crosshairs &amp; Target Glyphs:</strong> Blueprint design accents (<code>RedCrosshair.tsx</code>).</li>
<li><strong>Terminal ASCII Art:</strong> High-contrast system topologies rendered in pure text.</li>
</ul>
</details>

<hr />
<details>
<summary><h3>9. Zero-Server Document Engine: Vector PDF &amp; Native Word .DOCX</h3></summary>
<p>PrismQTC performs <strong>100% of document assembly client-side in the browser</strong>, saving significant server memory.</p>
<h4>Vector PDF via <code>jspdf</code> &amp; <code>jspdf-autotable</code></h4>
<p>Renders high-DPI vector PDFs directly in memory with branded headers and itemized financial tables:</p>
<pre><code class="language-typescript">export async function exportInvoicePDF(invoice: any) {
  const doc = new jsPDF();
<p>doc.setFillColor(15, 23, 42);
doc.rect(0, 0, 210, 32, 'F');</p>
<p>doc.setTextColor(255, 255, 255);
doc.setFontSize(18);
doc.setFont('helvetica', 'bold');
doc.text('PRISMQTC', 14, 16);</p>
<p>autoTable(doc, {
startY: 45,
head: [['#', 'SKU / Item', 'Qty', 'Unit Price', 'Total']],
body: invoice.lines.map((l: any, i: number) =&gt; [
i + 1, l.name, l.quantity, <code>₹${l.unit_price}</code>, <code>₹${l.total}</code>
]),
theme: 'grid',
headStyles: { fillColor: [15, 23, 42] },
});</p>
</code><p><code class="language-typescript">doc.save(<code>Invoice_${invoice.invoice_number}.pdf</code>);
}
</code></p></pre><p></p>
<h4>Native Word (<code>.docx</code>) via <code>docx</code></h4>
<p>Builds real Microsoft Word <code>.docx</code> documents with native paragraph runs, table shading, and styling, dispatched directly via <code>file-saver</code>.</p>
</details>

<hr />
<details>
<summary><h3>10. DevOps, Observability &amp; Container Topology</h3></summary>
<p>The entire stack is containerized with Docker and Docker Compose (<code>docker-compose.yml</code>):</p>
<pre><code class="language-bash">docker compose up -d
</code></pre>
<h4>Infrastructure Container Fleet</h4>
<table>
<thead>
<tr>
<th>Service</th>
<th>Image</th>
<th>Port</th>
<th>Responsibility</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Nginx</strong></td>
<td><code>nginx:alpine</code></td>
<td>80</td>
<td>Gateway &amp; reverse proxy</td>
</tr>
<tr>
<td><strong>Postgres</strong></td>
<td><code>postgres:16</code></td>
<td>5432</td>
<td>Primary RLS database</td>
</tr>
<tr>
<td><strong>Redis</strong></td>
<td><code>redis-stack</code></td>
<td>6379</td>
<td>Cache, queues &amp; GUI</td>
</tr>
<tr>
<td><strong>Prometheus</strong></td>
<td><code>prometheus</code></td>
<td>9090</td>
<td>Metric scraper</td>
</tr>
<tr>
<td><strong>Loki</strong></td>
<td><code>loki:3.0</code></td>
<td>3100</td>
<td>Log aggregator</td>
</tr>
<tr>
<td><strong>Grafana</strong></td>
<td><code>grafana:11</code></td>
<td>3001</td>
<td>Observability dashboards</td>
</tr>
</tbody>
</table>
<h4>Real-Time Observability</h4>
<ul>
<li><strong>Prometheus Metrics:</strong> Backend exposes <code>/metrics</code> measuring response latencies, status codes, and connection pool saturation.</li>
<li><strong>Loki Log Ingestion:</strong> Structured JSON application logging with request trace IDs.</li>
<li><strong>RedisInsight:</strong> GUI exposed on port <code>8001</code> for real-time queue inspection and key-space debugging.</li>
</ul>
<h4>Distributed Rate Limiting &amp; Brute-Force Defense</h4>
<p>To safeguard authentication and financial endpoints across multi-tenant deployments, PrismQTC integrates distributed rate limiting:</p>
<ul>
<li><strong>Redis-Backed State Store:</strong> Uses <code>express-rate-limit</code> paired with <code>rate-limit-redis</code>, synchronizing rate limit counters across all backend instances via Redis key prefix <code>rl:auth:</code>.</li>
<li><strong>Targeted Sliding Window:</strong> Enforces a 15-minute window permitting up to 50 attempts per IP address (<code>windowMs: 15 * 60 * 1000, max: 50</code>).</li>
<li><strong>Selective POST Filtering:</strong> Selectively targets credential submissions (<code>skip: (req) =&gt; req.method !== 'POST'</code>), preventing unnecessary throttling on read traffic.</li>
<li><strong>Fail-Open Resilience:</strong> Configured with <code>passOnStoreError: true</code>, ensuring enterprise users are never blocked during brief Redis reconnections.</li>
</ul>
<h4>Async Worker Queues, Schedulers &amp; Transactional SMTP</h4>
<ul>
<li><strong>BullMQ Task Queues:</strong> Decouples heavy background operations (audit logs, alerts) from the HTTP cycle with Redis Stack as the message broker.</li>
<li><strong>Autonomous Node-Cron Sweepers:</strong> Runs scheduled background tasks hourly, calling <code>sp_flag_stalled_deals()</code> to flag inactive deals and notify account owners.</li>
<li><strong>Nodemailer Transactional SMTP:</strong> Automatically fires email dispatches when approvals are submitted, counter-offers arrive, or deals are confirmed.</li>
</ul>
</details>

<hr />
<details>
<summary><h3>11. Architectural Tradeoffs, Lessons Learned &amp; What's Next</h3></summary>
<h4>💡 Key Lessons</h4>
<ol>
<li><strong>Push calculations to the database kernel:</strong> Offloading margin math and risk thresholds to PL/pgSQL triggers eliminated race conditions and made discount rules tamper-proof.</li>
<li><strong>Client-side document compilation is an enterprise superpower:</strong> Generating PDFs and DOCX files entirely in the client saved significant server memory and eliminated a major infrastructure bottleneck.</li>
<li><strong>Multi-tenancy belongs in the database, not in application logic:</strong> Using transaction-scoped PostgreSQL session variables (<code>SET LOCAL</code>) provided true zero-trust isolation without the maintenance burden of manually appending tenant IDs across hundreds of queries.</li>
</ol>
<h4>🔮 Future Roadmap</h4>
<ul>
<li><strong>Autonomous AI RFP Parsing:</strong> Ingesting messy PDF RFQs directly into structured quote lines using Gemini Flash.</li>
<li><strong>Dynamic Currency Hedging:</strong> Automatic real-time foreign exchange adjustments on multi-currency quotations.</li>
<li><strong>EDI 850 / 810 Connectors:</strong> Native electronic data interchange integration for enterprise supply chain partners.</li>
</ul>
<h4>🏁 Summary</h4>
<p>PrismQTC demonstrates that high-velocity B2B sales operations don't need to suffer under the weight of slow, rigid enterprise software. By pairing <strong>PostgreSQL's native security kernel</strong> with a <strong>modern React 19 real-time client</strong>, we can build sales systems that are self-governing, mathematically sound, and a pleasure to use.</p>
<hr />
<p><em>Built with React 19, TypeScript, Node.js, PostgreSQL 16, Redis Stack, and Docker.</em></p>
</details>

<hr />
<h2>System Topology &amp; Architecture</h2>
<p>The platform is designed around a decoupled, high-throughput micro-modular topology:</p>
<pre><code class="language-text">┌──────────────────────────────────────────────────────────┐
│                      FRONTEND LAYER                      │
│  React 19 (SPA)  │  TypeScript 5.8  │  Vite 6            │
│  Tailwind CSS v4 │  Socket.IO       │  Motion + Lucide   │
│  SWR Cache       │  Axios Client    │  jsPDF + docx      │
└────────────────────────────┬─────────────────────────────┘
                             │ HTTP / WebSocket (Port 80)
                             ▼
┌──────────────────────────────────────────────────────────┐
│                 GATEWAY &amp; REVERSE PROXY                  │
│  Nginx (Alpine) — Routing, Assets, Caching, WS Upgrade   │
└────────────────────────────┬─────────────────────────────┘
                             │
              ┌──────────────┴──────────────┐
              ▼                             ▼
┌───────────────────────────┐ ┌────────────────────────────┐
│        BACKEND API        │ │   ASYNC WORKERS &amp; CACHE    │
│ Node.js (ESM) + Express   │ │ Redis Stack 7 (Broker/AOF) │
│ Socket.IO Real-Time Hub   │ │ BullMQ Job Queue Workers   │
│ Argon2 + Dual JWT Auth    │ │ node-cron Schedule Engine  │
│ Raw pg (withTenantContext)│ │ RedisInsight Web Dashboard │
└─────────────┬─────────────┘ └──────────────┬─────────────┘
              │                              │
              └──────────────┬───────────────┘
                             ▼
┌──────────────────────────────────────────────────────────┐
│                      DATABASE LAYER                      │
│  PostgreSQL 16 Alpine                                    │
│  ├─ Row-Level Security (RLS) &amp; Column Grants (CLAC)      │
│  ├─ PL/pgSQL Reactive Triggers (Margin &amp; Risk Math)      │
│  └─ Stored Procedures (Atomic Orders, Stalled Sweeps)    │
└────────────────────────────┬─────────────────────────────┘
                             │ Metrics &amp; Log Streams
                             ▼
┌──────────────────────────────────────────────────────────┐
│                OBSERVABILITY &amp; MONITORING                │
│  Prometheus v2.52 (Metrics) │ Loki v3.0 (Log Streams)    │
│  Grafana v11.0 (Pre-Provisioned Unified Dashboards)      │
└──────────────────────────────────────────────────────────┘
</code></pre>
<h3>Visual Workflow Analogy: The End-to-End Deal Lifecycle</h3>
<p>To understand how PrismQTC functions as a cohesive whole, here is the complete end-to-end operational flow from initial deal inception to cash collection and telemetry:</p>
<pre><code class="language-text">┌──────────────────────────────────────────────────────────┐
│                 PRISMQTC DEAL LIFECYCLE                  │
│       End-to-End Autonomous Quote-to-Cash Workflow       │
└────────────────────────────┬─────────────────────────────┘
                             │
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 1: DEAL CREATION &amp; PRICING                         │
│  • Sales Rep crafts Quote or Buyer submits Portal RFQ    │
│  • Contextual Upsell Engine suggests high-margin add-ons │
│  • Instant PL/pgSQL triggers calculate margins &amp; totals  │
└────────────────────────────┬─────────────────────────────┘
                             │
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 2: BLENDED RISK GATE &amp; GOVERNANCE                  │
│  • Compares line discounts against Customer Tier Caps    │
│  • Calculates Blended Risk Score (0 - 10 scale)          │
│    ├─ Risk &lt; 5.0  ──▶ Instant Customer Dispatch          │
│    └─ Risk ≥ 5.0  ──▶ Multi-Tier Approval Chain          │
│                       (Sales Manager ➔ Finance Director) │
└────────────────────────────┬─────────────────────────────┘
                             │ Approved &amp; Dispatched
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 3: LIVE PORTAL &amp; BIDIRECTIONAL NEGOTIATION         │
│  • Buyer logs in via Magic Link or Portal Password       │
│  • Real-Time WebSockets sync live chat &amp; counter-offers  │
│  • Buyer clicks Accept ➔ sp_customer_confirm_quotation  │
└────────────────────────────┬─────────────────────────────┘
                             │ Atomic Deal Confirmation
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 4: SMART SPLIT-WAREHOUSE FULFILLMENT               │
│  • Algorithm checks stock across 3 regional depots       │
│  • Auto-splits order: Shipment #1 (Central) + #2 (East)  │
│  • Auto-generates Backorder records for stock deficits   │
└────────────────────────────┬─────────────────────────────┘
                             │ Dispatches Verified
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 5: HYBRID RECONCILED BILLING &amp; SETTLEMENT          │
│  • Invoices generated strictly matching delivered stock  │
│  • Daily proration calculated for recurring licenses     │
│  • Buyer settles payment online via Razorpay Gateway     │
└────────────────────────────┬─────────────────────────────┘
                             │ Payment Verified (PAID)
                             ▼
┌──────────────────────────────────────────────────────────┐
│  STEP 6: EXECUTIVE TELEMETRY &amp; AUDIT LEDGER              │
│  • Deal Health Radar tracks margin velocity &amp; win-rate   │
│  • Background cron sweeper flags stalled deal anomalies  │
│  • Immutable ledger sealed in approval_audit_logs        │
└──────────────────────────────────────────────────────────┘
</code></pre>
<h4>✈️ The Mental Analogy: The Airport Flight Control System</h4>
<p>Think of PrismQTC like an <strong>autonomous international airport</strong>:</p>
<ol>
<li><p><strong>The Flight Plan (Step 1 — Quotation Builder):</strong> The sales rep plans the route, selecting hardware and subscription seats. The catalog automatically suggests fuel-efficient flight corridors (upsell add-ons).</p>
</li>
<li><p><strong>Air Traffic Control Clearance (Step 2 — Blended Risk Gate):</strong> Before takeoff, the flight plan is checked against strict airspace rules. Standard flights (discounts $&lt; 5.0$) get immediate takeoff clearance. High-risk flights (discounts \(\ge 5.0\)) are held on the runway until approved by the Tower Supervisor (Sales Manager) and Airfield Director (Finance).</p>
</li>
<li><p><strong>The Passenger Boarding Gate (Step 3 — Customer Portal):</strong> The passenger (buyer) steps into the live terminal. If they request a seat upgrade or price adjustment, the ground crew and passenger negotiate in real time over radio (WebSockets). Once both agree, the boarding door seals atomically (<code>sp_customer_confirm_quotation</code>).</p>
</li>
<li><p><strong>Baggage Routing Across Terminals (Step 4 — Split-Warehouse Fulfillment):</strong> Heavy cargo is split intelligently across whichever regional cargo terminals currently have space, without stalling the passenger flight. Missing bags are automatically assigned tracking numbers as priority backorders.</p>
</li>
<li><p><strong>Customs &amp; Duty Settlement (Step 5 — Invoices &amp; Razorpay):</strong> Charges are billed strictly for cargo that has actually arrived at the gate, recurring tickets are prorated to the day, and duty is paid at the instant payment kiosk (Razorpay).</p>
</li>
<li><p><strong>The Black Box Flight Recorder (Step 6 — Deal Health &amp; Telemetry):</strong> Every telemetry reading, altitude change, and approval decision is permanently etched into the flight recorder (<code>approval_audit_logs</code>), while radar sweeps detect stalled aircraft before any collisions occur.</p>
</li>
</ol>
]]></content:encoded></item></channel></rss>