Production Architecture • Self-Hosted Hybrid SaaS

Technical Architecture & System Topology

SmartBiz combines instant client BaaS operations with trusted server-side computation, private on-premise AI intelligence, and strict PostgreSQL One-Schema-Per-Tenant isolation—purpose-built to deliver enterprise-grade ERP capabilities to price-sensitive MSMEs at predictable infrastructure costs.

1 Schema
27 Dedicated ERP Tables per Tenant
Dual Engine
Supabase BaaS + CI4 Admin & REST
On-Prem AI
Ollama llama3.2 & gemma4 Cluster
Asia/Manila
Localized DTR, SMTP & Single VPS
Architectural Philosophy

The Power Hybrid Paradigm: Purpose-Built for MSME Scale

SmartBiz avoids the pitfalls of bloated monolithic frameworks and over-engineered microservices. By strategically dividing responsibilities between instant client BaaS operations, a battle-tested server-side transactional engine, and a private on-premise AI cluster, SmartBiz delivers unmatched speed, bank-grade data security, and flat operating costs.

Core Responsibility Division • 3 Architectural Pillars Engineered for Maximum Efficiency

Pillar A: Instant Reactive BaaS (PostgREST + Realtime)

Frontline Speed (<15ms): POS sales, barcode lookup, item/category & supplier editing, multi-type inventory classification (product, raw_material, supply), and loyalty rewards query PostgreSQL directly via PostgREST while Realtime pushes deltas over WebSockets.

Pillar B: Trusted Transactional Engine (CodeIgniter 4 PHP)

Platform Admin, FEFO Manufacturing & GL Sync: Hosts /admin/tenants (AdminAuthFilter), automated provisioning (provision_tenant.sh), atomic FEFO batch inventory & BOM manufacturing (InventoryController, ManufacturingController, AccountingGlService), SMTP digital e-receipts, shift-aware Asia/Manila DTR punches, and async BIR VAT workers (smartbiz-queue.service).

Pillar C: Private On-Premise AI & Biometrics (Ollama + FastAPI)

Zero-Token Privacy: Self-hosted llama3.2:latest, mxbai-embed-large, and gemma4:e2b-it-qat power Executive Daily Briefings rendered in rich client Markdown without exposing financial data, while FastAPI runs 512-D pgvector face matching for tamper-proof DTR.

Operational Domain Executing Engine Protocol & Latency Architectural Rationale
POS Checkout & Multi-Type Catalogs PostgREST (spbase.smartbiz.asia) REST / <15ms Direct database CRUD for products, raw materials, supplies, categories & inline supplier edits without app overhead.
Live Stock & Attendance Feed Supabase Realtime (:4000) WebSocket / Realtime PostgreSQL CDC broadcasts stock deductions, invoices, and DTR punches instantly across web & mobile clients.
Platform Admin & Tenant Provisioning CodeIgniter 4 (AdminController + CLI) Admin UI / CLI CSRF-protected /admin/tenants console runs provision_tenant.sh, Auth owner seeding, php spark migrate:tenants & a PostgREST NOTIFY pgrst, 'reload schema' hot reload.
Paperless Green E-Receipts CI4 ReceiptEmailController + SMTP REST + SMTP TLS Builds XSS-escaped HTML receipts with store branding, dispatches via SMTP, and stamps receipt_email_sent_to & receipt_sent_at.
FEFO Batches, Manufacturing & Traceability CI4 InventoryController + ManufacturingController FOR UPDATE / TX Row-locked FEFO allocation across locations, strict expired-batch blocking, BOM production runs (wastage_pct) & lot recall tracing.
Double-Entry Journals, Valuation & COA PostgreSQL Engine + AccountingGlService ACID / Idempotent Enforces Debit == Credit invariants, auto-posts balanced standard-cost vouchers (1200/2010/5010/5020/6030 via uq_journal_entries_auto_ref), and derives the Trial Balance and period Income Statement (Revenue → Cost of Sales → Gross Profit → Operating Expenses → Net Income) from posted lines.
Shift Scheduling & Employee Sync CodeIgniter 4 REST API + PostgREST REST / <60ms Enforces shift overlaps, weekly auto-copy, credential linking/unlinking, and employee email synchronization.
Async BIR VAT & Monthly Reports CI4 Queue Worker (smartbiz-queue.service) + VatReportPolicy Async Worker / 202 Claims jobs with FOR UPDATE SKIP LOCKED, aggregates VATable vs. exempt sales, output/input tax, net VAT payable & carry-over credit in SQL, writes a JSON export, and returns the summary from /reports/status/{id} for web & mobile (CSV export on web).
Timezone-Safe Face & GPS DTR FastAPI (:8010) + CI4 (Asia/Manila) Loopback / <250ms Combines 512-D pgvector match & GPS radius checks with client_date & overnight clock_out IS NULL resolution.
Executive Daily Briefing Ollama Service (llama3.2:latest) HTTPS / Streaming Synthesizes localized sales, low-stock items, and shift rosters into Markdown JSON insights with 0ms rule-based fallback.
01

One-Schema-Per-Tenant Isolation

Every MSME workspace is assigned an isolated PostgreSQL schema (tenant_<slug>) containing all 27 ERP tables. Ledgers, inventory batches, production runs, and employee rosters are physically segregated in their own namespace—eliminating cross-tenant leakage.

02

Cryptographic JWT Tenant Scoping

During authentication, GoTrue stamps the verified tenant_schema claim into the user's JWT. Both PostgREST and CodeIgniter's TenantSchemaFilter validate this claim and execute SET search_path TO "tenant_<slug>", public, extensions before executing any statement.

03

Zero-Downtime Admin & SaaS Provisioning

Authenticated platform operators (AdminController at /admin/tenants behind AdminAuthFilter) or self-service signups (OnboardingController) run provision_tenant.sh, seed base_erp_template.sql, create GoTrue Owner credentials, and issue NOTIFY pgrst, 'reload schema' so PostgREST exposes the new schema without a restart.

PostgreSQL Search-Path Enforcement
-- 1. Client sends Bearer JWT with app_metadata
-- tenant_schema: "tenant_iloilo_coffee_roasters"
 
-- 2. PgBouncer checks out pooled connection
SET search_path TO "tenant_iloilo_coffee_roasters", public, extensions;
 
-- 3. Invoices query executes strictly in isolated schema
SELECT invoice_number, total_amount, receipt_email_sent_to
FROM invoices
WHERE issue_date = CURRENT_DATE;
 
-- 4. Cross-tenant reads are structurally impossible
-- Schema boundaries enforced at PostgreSQL kernel level
System Topology

Multi-Tier Infrastructure & Network Topology

An end-to-end blueprint illustrating how client devices, cloud edge ingress, dual-backend services, on-premise AI inference nodes, and the PostgreSQL database cluster interact in production.

Tier 1 — Client Ecosystem & Edge Ingress Gateway Cloudflare SSL • Nginx Reverse Proxy

Vue 3 Back-Office Web Portal (smartbiz-web)

Desktop command center using Vue 3, TypeScript, Pinia, Tailwind CSS, and timezone-safe dateUtils.ts. Two-step workspace sign-in. Handles multi-location FEFO inventory, BOM production runs, batch recall trace, consignment reconciliation, Income Statement & Trial Balance, server-verified Monthly VAT Summary, Inventory GL Sync (1200), shift scheduling, HR face purge, printable DTR, Green E-Receipts, and Markdown AI briefings.

GoSmartBiz Mobile App (Flutter, smartbiz_mobile)

Cross-platform Android/iOS app with single-step email sign-in (tenant resolved from the JWT), Riverpod, a dead-lettering SharedPreferences offline outbox, GS1-128 lot scanning, server VAT summaries, mobile BOM production runs & recall trace, location-bound FEFO POS, 🌱 E-Receipts inside print previews, Valuation cards, and shift-aware Staff Time Logs.

Edge Ingress & Platform Admin Landing

Cloudflare TLS proxying to Nginx: routes spbase.smartbiz.asia to the Supabase API gateway and engine.smartbiz.asia to CodeIgniter 4—serving the Platform Admin Sign-In Console on / and tenant provisioning at /admin/tenants.

▼ Dual-Route Dispatch • JWT Bearer Tokens (API) & Hardened Session Cookies (Admin) ▼
Tier 2 — Service Orchestration, AI & Biometric Cluster Ubuntu Linux Production Environment

Self-Hosted Supabase Core (spbase.smartbiz.asia)

Supabase API Gateway (:8000) orchestrating GoTrue Auth (/auth/v1), PostgREST Multi-Schema Engine (/rest/v1), and Realtime WebSockets (/realtime/v1).

CodeIgniter 4 Enterprise Engine (engine.smartbiz.asia)

PHP 8.2 FPM engine running TenantSchemaFilter, CorsFilter, AdminAuthFilter, InventoryController & ManufacturingController (FEFO batches & BOM runs), AccountingGlService, ReceiptEmailController, shift-aware Asia/Manila DTR punches, smartbiz-queue.service, and php spark migrate:tenants.

Private On-Premise AI Cluster (Ollama)

Local LLM server running llama3.2:latest (Briefings), mxbai-embed-large:latest (Embeddings), and gemma4:e2b-it-qat (Vision/OCR) behind an authenticated reverse proxy (X-API-Key).

FastAPI Biometric Engine (127.0.0.1:8010)

Python microservice that runs every punch selfie through Silent-Face-Anti-Spoofing liveness before matching (failing closed with 503 if the detector is unavailable), then crops with MTCNN and embeds with facenet-pytorch InceptionResnetV1 into 512-D vectors for cosine matching. Liveness is server-side; the apps only capture the frame.

▼ Transaction-Mode Connection Pooling via PgBouncer (:6432 • SET search_path) ▼
Tier 3 — Decoupled PostgreSQL Database Cluster PostgreSQL 16 + pgvector • Daily Backups & Point-in-Time Recovery

auth & extensions Schemas

Managed by Supabase GoTrue. Houses encrypted credentials, session tokens, tenant metadata claims (app_metadata.tenant_schema, erp_role: owner, admin, accountant, hr, cashier, warehouse, staff), and vector extensions (pgvector, uuid-ossp).

public Schema

Shared global registries: tenants (subdomains, company names, workspace status), currencies, Philippine tax_types, and the background_jobs queue table.

Dedicated tenant_<slug> Schemas

27 isolated ERP tables per company: items, item_categories, inventory_locations, item_batches, inventory_balances, stock_movements, boms, bom_items, production_orders, production_consumptions, invoices, invoice_items, payments, purchase_orders, purchase_order_items, contacts, chart_of_accounts, journal_entries, journal_lines, employees, shift_templates, employee_shifts, business_events, work_locations, attendance_logs, ai_briefings, and company_settings.

Flow 1 • Direct BaaS

High-Velocity Frontline Reads & Edits

POS checkouts, item/category/supplier updates, and item_type stock queries hit PostgREST with Bearer JWTs. PostgREST sets search_path via PgBouncer and returns results in <15ms.

Flow 2 • CDC Broadcast

Real-Time WebSockets Synchronization

Every sale, purchase order receipt, or DTR punch triggers PostgreSQL WAL notifications to Supabase Realtime, broadcasting instant updates to subscribed Vue 3 and Flutter screens.

Flow 3 • AI Briefing

On-Premise Private LLM Insights

CI4 aggregates localized Asia/Manila sales, low-stock supplies, and shift rosters for Ollama (llama3.2) via X-API-Key, returning Markdown insights (with a 0ms rule-based fallback if offline).

Flow 4 • Vector & GPS DTR

Overnight-Safe Biometric Attendance

Mobile punches send selfies, GPS coordinates (mock locations rejected on-device), and local client_date to CI4 → FastAPI for server-side liveness and 512-D matching. Open-shift lookups resolve cleanly past midnight, and photos auto-purge after 72 hours.

Flow 5 • Admin Provisioning

Admin Console & SaaS Onboarding

Authenticated platform operators at /admin/tenants (guarded by AdminAuthFilter + CSRF) provision new tenant schemas, Auth owner accounts, and live PostgREST reloads in seconds.

Flow 6 • Sustainability

Paperless Green E-Receipt Dispatch

Cashiers tap 🌱 Email Receipt in Web Invoicing or Mobile POS print previews; CI4's ReceiptEmailController renders XSS-escaped HTML receipts over SMTP and logs dispatch timestamps.

Competitive Strengths

Why the SmartBiz Architecture Wins for MSMEs

SmartBiz delivers the security, reliability, and precision of tier-1 enterprise ERP systems without the six-figure licensing fees, fragile cloud sprawl, or data privacy risks.

01

Zero Cross-Tenant Data Leakage by Design

Rather than relying on application developers never forgetting a WHERE tenant_id = ? clause, SmartBiz enforces isolation at the PostgreSQL schema level. Financial records, customer databases, and employee salaries are structurally impossible to query across tenant boundaries.

02

Predictable Single-Host VPS Economics

By combining lightweight Go (Supabase), compiled C (PostgreSQL + PgBouncer), fast PHP 8.2 (CodeIgniter 4), and quantized local AI models, SmartBiz operates smoothly on a cost-effective virtual private server. SaaS operators avoid runaway AWS microservice bills.

03

On-Premise AI Privacy & Zero Token Expenses

Every Executive Daily Briefing is generated locally by quantized llama3.2 models running on our dedicated AI server. Business sales, inventory margins, and customer data never leave the private perimeter, and owners enjoy unlimited daily insights without recurring per-token bills.

04

Frontline Offline Resilience, Paperless Agility & Zero Lock-In

SmartBiz eliminates costly proprietary POS terminals. Cashiers scan GS1-128 & SKU barcodes with standard mobile cameras, email eco-friendly paperless receipts via CI4 SMTP, or print to standard 58mm/80mm Bluetooth thermal printers. When store internet drops, Flutter's local SharedPreferences outbox caches punches and invoices, syncing automatically via idempotent FEFO checkout upon reconnection.

05

ACID Financial Precision & BIR-Ready Accounting

Monetary fields use PostgreSQL NUMERIC(15,2) and quantities NUMERIC(15,3), eliminating floating-point rounding discrepancies. Double-entry general ledger journal transactions are validated with balanced debit/credit invariants, feeding the Trial Balance, Income Statement, and BIR VAT summaries used in financial audits.

Architectural Dimension Legacy Monoliths (SAP / Odoo) Generic Cloud SaaS SmartBiz Hybrid ERP
Tenant Isolation Heavy separate DB instances Shared flat tables with tenant_id One-Schema-Per-Tenant (Dedicated PG Schemas)
Infrastructure Cost Costly dedicated server footprint Sprawling microservices & cloud lock-in Predictable, self-hosted single VPS with PgBouncer
AI Intelligence & Privacy Costly add-ons or none Public cloud APIs (OpenAI token fees & leaks) On-premise Ollama (llama3.2) • 100% private & $0 token fee
Offline Store Continuity Requires local desktop server sync Stops working when WiFi drops Local SharedPreferences outbox + idempotent sync on reconnect
Hardware Requirements Proprietary hardware & barcode guns Web-only browser interface Smartphone cameras, thermal printers & paperless e-receipts
Real-Time Responsiveness Slow server page reloads Client polling or basic WebSockets Direct PostgREST (<15ms) + WAL-driven WebSockets
Financial Integrity Double-entry accounting Often single-entry or loose checks ACID double-entry ledger (exact NUMERIC money) with live Income Statement