diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10ff9cc..5f4eb83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,4 +28,4 @@ jobs: run: npm run typecheck - name: Run Test Suites - run: npm test -- --passWithNoTests + run: npm test -- --runInBand --passWithNoTests diff --git a/.gitignore b/.gitignore index 22d5de4..1d9a913 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ expo-env.d.ts .env.* *.keystore scratch/ +test-artifacts/ diff --git a/README.md b/README.md index 1a386dd..f35abf1 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Billframe ⚑ -> **The Local-First, Zero-Subscription, AI-Powered Invoice & Statutory Business Operating System** -> *The modern, 100% free & open-source alternative to Zoho Books, Zoho Invoice, and QuickBooks.* +> **The Local-First, Open-Source Invoice & Financial Document App for Android & Web** +> *Offline-capable, deterministic financial document generation with Bring-Your-Own-Key (BYOK) AI assistance.*

Billframe Logo @@ -10,51 +10,54 @@

License: MIT Local First SQLite - Zero Fees - 446 Statutory Documents - Cross Platform + Free and Open Source + 40+ Document Archetypes + Android and Web

--- ## 🌟 Overview -**Billframe** is an enterprise-grade, local-first business operating system designed for freelancers, entrepreneurs, SMBs, and modern enterprises. While traditional SaaS giants lock your financial records behind expensive recurring paywalls, sell your accounting metadata, and grind to a halt during cloud outages, **Billframe runs 100% on your own device with zero subscriptions, zero trackers, and complete data sovereignty.** +**Billframe** is an open-source, local-first billing and document generation application designed for freelancers, independent contractors, tradespeople, and micro-businesses. -Equipped with an **Autonomous AI Copilot**, Billframe understands natural language and statutory regulations. It autonomously reasons, calculates, and compiles compliant business documentsβ€”from CBIC GST Tax Invoices and Delivery Challans to Salary Slips, Commercial Quotations, and ATS-optimized Resumes. +Unlike subscription cloud SaaS tools that require continuous internet connectivity, store financial records on third-party servers, and enforce recurring monthly fees, **Billframe runs directly on your device**. All customer directories, catalog items, and document records are stored locally in an embedded SQLite database, giving you complete data privacy with zero trackers and zero mandatory cloud services. + +### Core Engineering Priorities +- **Deterministic Minor-Unit Arithmetic**: All monetary balances, taxes, and item sums are computed in integer minor units (`BigInt` paisa/cents), preventing floating-point rounding errors. +- **Offline Autonomy**: Core invoicing, estimates, challans, receipts, local queries, and printing work without network connectivity. +- **Privacy & Security by Default**: Client records and financial history never leave your hardware unless you configure your own sync backend. User credentials are kept in the hardware-backed keystore (`expo-secure-store`). +- **Opt-in AI with BYOK**: Conversational drafting uses Bring-Your-Own-Key (BYOK) or deterministic local heuristics. No centralized developer API keys are bundled into the app. --- -## βš”οΈ Why Billframe vs. Zoho & QuickBooks? - -| Feature | **Billframe (Open Source)** | **Zoho Invoice / Books** | **QuickBooks Online** | -| :--- | :--- | :--- | :--- | -| **Pricing & Licensing** | **100% Free & Open Source (MIT)** | $15 to $240 / month per user | $30 to $200 / month | -| **Data Ownership** | **100% Local-First (On-Device SQLite)** | Cloud vendor locked | Cloud vendor locked | -| **Offline Reliability** | **Instantaneous offline execution** | Unusable without internet | Unusable without internet | -| **AI Copilot** | **Autonomous CoT Reasoning + 446 Docs** | None / Rigid rule scripts | Rudimentary categorization | -| **Data Elicitation** | **Interactive in-chatbox MCQ builder** | Static multi-page manual forms | Static multi-page manual forms | -| **Statutory Standards** | **CBIC GST 01–05, Rule 46/55, Sec 10(13A)** | Regional add-on fees | Regional add-on fees | -| **Financial Arithmetic** | **Deterministic BigInt Minor Units** | Floating-point rounding risk | Floating-point rounding risk | -| **POS & Thermal Printing** | **Built-in 80mm ESC/POS + Direct Print** | Requires third-party drivers | Requires expensive hardware bundles | -| **Privacy & Security** | **Zero trackers, Local biometric PIN** | Third-party analytics tracking | Telemetry & ad tracking | -| **Custom Templates** | **Visual Template Studio + Gold Masters** | Limited CSS customization | Restrictive templates | +## βš–οΈ Architectural Philosophy & Comparison + +| Dimension | Billframe (Local-First Open Source) | Full-Suite Cloud SaaS (Zoho / QuickBooks) | +| :--- | :--- | :--- | +| **Data Storage** | **100% On-Device SQLite** (User controls local database) | Multi-tenant cloud database | +| **Offline Execution** | **Full offline capability** for all core operations | Requires continuous internet access | +| **Pricing Model** | **Free & Open Source (MIT)** | Recurring monthly or annual subscription | +| **Telemetry & Privacy** | **Zero telemetry, zero trackers** | Product analytics and telemetry | +| **Arithmetic Precision** | **Deterministic `BigInt` minor units** | Platform-managed decimal engines | +| **AI Integration** | **Client-side BYOK** (Groq/Gemini/OpenAI) + local heuristic fallback | Cloud-managed AI add-ons | +| **Application Scope** | Focused billing, GST compliance, quotes, salary slips, receipts | Full double-entry bookkeeping, payroll tax filing, bank feeds | --- ## πŸš€ Key Features -### 1. πŸ€– Autonomous AI Document Copilot -- **446 Statutory Document Archetypes**: Covers 25 industry families including Commercial Billing, Logistics & Transport, HR & Payroll, Real Estate, Legal & Institutional, and Engineering Dossiers. -- **Cognitive Step-by-Step Reasoning**: Features a transparent, Claude-style thinking accordion (`Thought for 3s ⌡`) that shows intent classification, legal rule grounding, and mathematical derivations. -- **Interactive In-Chatbox MCQ Elicitation**: When statutory fields are missing, the AI smoothly slides up interactive multiple-choice cards in the chatbox (with options `[A]`, `[B]`, `[C]` and `[Other ✎]`), eliminating dummy placeholder data without tedious form filling. -- **Multi-Turn Context Memory**: References previous turns to seamlessly extract counterparties, candidate names, and line items. -- **Bring Your Own Key (BYOK) & Universal Free Trial**: - - **Universal Trial Key Out-of-the-Box**: Runs instantly with deep reasoning on Groq LPU (GPT-OSS 120B) with a built-in preview limit of **7 documents**. - - **Unlimited Free BYOK**: Plug in your free personal Groq API key in **AI Settings** for unlimited, ultra-fast generation ([Get Free Key at console.groq.com/keys](https://console.groq.com/keys) β€” zero cost, no credit card required). - - **100% Offline Heuristic Fallback**: Zero-network on-device policy engine with BigInt arithmetic precision. - -### 2. 🧾 Complete CBIC GST & Statutory Invoicing Suite +### 1. πŸ€– AI Document Assistant (BYOK & Offline Heuristics) +- **40+ Implemented Statutory & Commercial Archetypes**: Covers core billing and operational instruments including B2B GST Invoices, Delivery Challans, Purchase Orders, Quotations, Salary Slips, and Rent Receipts, supported by an extensible taxonomy schema. +- **Transparent Reasoning Flow**: Displays structured intent extraction, statutory rule grounding, and calculation traces. +- **Interactive In-Chatbox MCQ Elicitation**: When required statutory fields are missing, interactive option chips appear directly in the chat to clarify details without tedious form navigation. +- **Multi-Turn Context**: References previous conversation turns to carry over counterparty data, candidate profiles, and line items. +- **Bring Your Own Key (BYOK) & True Offline Architecture**: + - **100% Zero-Network Offline Engine**: Billframe functions completely out of the box without requiring any API keys or network connection. Its on-device deterministic policy engine performs statutory calculations, document structuring, and BigInt balance verifications locally. + - **Secure Bring-Your-Own-Key (BYOK)**: To enable deep neural reasoning on cloud models (Groq, Google Gemini, or OpenAI), users can configure their personal API keys in **AI Settings**. Free personal keys can be generated at [console.groq.com/keys](https://console.groq.com/keys) (zero cost, no credit card required). + - **Hardware-Backed Credential Isolation**: User-configured credentials are stored directly in the device's secure enclave (`Android Keystore` and `iOS Keychain` via `expo-secure-store`) and never touch Billframe servers. Zero developer-owned API keys are embedded in application code. + +### 2. 🧾 CBIC GST & Statutory Invoicing Suite - **Rule 46 B2B Tax Invoices**: Full GSTIN, PAN, HSN/SAC codes, reverse charge flags, and dual-state tax reconciliations. - **Intra-State vs Inter-State Tax Engine**: Automatically splits tax into CGST + SGST or Integrated IGST based on the customer's Place of Supply. - **Rule 55 Delivery Challans**: Formatted for goods transportation, job work, and supply on approval with transit valuations. @@ -70,21 +73,21 @@ Equipped with an **Autonomous AI Copilot**, Billframe understands natural langua ### 3. πŸ’Ό HR, Payroll & Operations - **Statutory Salary Slips**: Compliant with the *Payment of Wages Act 1936*, featuring itemized Gross Earnings and statutory deductions (EPF 12%, ESI, Professional Tax). - **House Rent Receipts**: Fully formatted under *Section 10(13A) of the Income Tax Act 1961* for HRA tax exemption claims with Landlord PAN tracking. -- **ATS-Optimized Resumes & Dossiers**: Generates 98% ATS-scoring single-column resumes with structured skill matrices, quantified impact metrics, and zero parsing traps. +- **ATS-Friendly Resumes & Dossiers**: Clean, single-column resume and dossier templates designed for clear structural parsing with structured skill matrices and quantified project summaries. - **Field Engineering Work Orders**: Operational task lists, milestone deliverables, and authorized engineer sign-offs. ### 4. ⚑ Local-First SQLite & BigInt Math Engine - **Deterministic Minor Units**: All monetary calculations are performed in integer minor units (paisa, cents) using `BigInt`, eliminating IEEE-754 floating-point rounding errors. - **100% Local SQLite Database**: Powered by `expo-sqlite`, storing customers, catalog items, ledger balances, and documents locally on your device. -- **Optional Supabase Cloud Sync**: Encrypted peer-to-peer cloud sync for cross-device backup when you want it. +- **Optional Supabase Cloud Sync**: Encrypted peer-to-peer cloud sync for cross-device backup when configured by the user. ### 5. πŸ–¨οΈ Hardware & Thermal POS Printing - **80mm POS Thermal Receipts**: Instant itemized receipts for grocery stores, retail counters, and quick-service shops. -- **Zero-Blocker Printing**: Bulletproof cross-platform printing for web, Android, and iOS. -- **Vector UPI QR Codes**: Dynamic on-invoice QR codes for instant UPI / SEPA / bank wire settlements. +- **Cross-Platform Printing**: Standard printing via native Android print service (`expo-print`) and browser print dialog. +- **Vector UPI QR Codes**: Dynamic on-invoice QR codes for instant UPI / bank wire settlements. ### 6. 🎨 Arctic Aurora Monochrome Design System -- Neutral-first, distraction-free executive interface (`#0D0E10` dark canvas, `#18191D` surfaces, `#F5F5F6` crisp typography). +- Neutral-first, distraction-free interface (`#0D0E10` dark canvas, `#18191D` surfaces, `#F5F5F6` crisp typography). - Responsive on mobile smartphones, tablets, and widescreen desktop monitors with split-pane live document preview. - Fluid token cadence animations without bulky, congested container nesting. @@ -196,6 +199,21 @@ We welcome contributions from developers, accountants, tax consultants, and open --- +## πŸ”’ Security, Privacy & Reliability Hardening + +Billframe follows rigorous security best practices to protect sensitive financial records: + +- **Zero Hardcoded Secrets**: Client bundles contain zero developer-owned inference keys or cloud credentials. Automated CI checks enforce secret scanning across source and cloud functions. +- **Hardware-Backed Device PIN**: Protected by high-entropy CSPRNG salts (32 bytes / 64 hex characters) and salted SHA-256 digests. Features constant-time hash verification and automated 30-second lockout after 5 consecutive failed attempts. +- **Multi-Tenant Cloud Isolation**: Cloud synchronization strictly requires authenticated user session JWTs, disallowing anonymous bearer tokens and enforcing PostgreSQL Row Level Security (`auth.uid() = user_id`). +- **SQL Injection Defense**: Network delta synchronization payloads are filtered against strict per-table column allowlists before local SQLite persistence. +- **Safe LWW Concurrency**: Uses timestamp-based Last-Write-Wins upserts that preserve foreign key constraints and relational integrity rather than destructive replacement. +- **Payment Webhook Atomicity**: Server-side HMAC-SHA256 signature verification and database-level idempotency (`ON CONFLICT (event_id) DO NOTHING`) defend against webhook replay attacks and race conditions. + +For full architectural details, see [`SECURITY.md`](SECURITY.md). + +--- + ## πŸ“„ License Distributed under the **MIT License**. Free for personal, commercial, and enterprise usage without restrictions. See [`LICENSE`](LICENSE) for details. diff --git a/SECURITY.md b/SECURITY.md index 4ab90e9..24b9a42 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security Policy +# Security Policy & Architecture Guide ## Supported Versions @@ -8,12 +8,42 @@ --- -## Local-First Privacy Invariant +## Security Model & Trust Boundaries -Billframe is built from the ground up on a **Local-First Architecture**: -- All accounting databases, customer records, line items, and ledger balances are stored strictly on-device in SQLite. -- No telemetry, analytics, or third-party trackers are bundled in the application. -- AI features operate either via local deterministic heuristics (zero network traffic) or via encrypted user-configured endpoints (BYOK) with zero permanent retention. +Billframe is built from the ground up on an **Offline-First, Zero-Trust Architecture**. + +### 1. Zero Built-In Cloud Credentials & BYOK Model +- **No Embedded Provider Keys**: The Billframe client codebase and bundled binaries contain zero developer-owned API keys, private tokens, or payment secrets. +- **Bring-Your-Own-Key (BYOK)**: Users who choose to enable cloud inference configure their personal API keys (Groq, Google Gemini, OpenAI). +- **Hardware-Backed Storage**: On native mobile platforms (Android and iOS), API credentials and security tokens are stored using OS-backed secure enclaves (`Android Keystore` and `iOS Keychain` via `expo-secure-store`). +- **Web Storage Clarification**: On Web deployments, credentials reside in browser origin storage (`localStorage`), which does not provide hardware enclave isolation. Users on public or shared terminals should use offline heuristic mode or clear credentials upon completing their session. +- **Automated Regression Guard**: Automated secret scanning (`tests/security/credential_exposure.test.ts`) executes in CI to prevent accidental commits of API keys or provider tokens. + +### 2. Device Master PIN Protection & Cryptographic Defense +- **CSPRNG Salt Generation**: Salts are generated using cryptographically secure pseudorandom number generators (`Crypto.getRandomValues` / Web Crypto API), producing 32 bytes (64 hex characters) of high-entropy randomness. Math.random() is never used for security artifacts. +- **Salted SHA-256 Digest**: Master PINs are hashed with unique per-device CSPRNG salts. Raw PINs are never persisted or logged. +- **Constant-Time Verification**: Verification employs constant-time string comparison (`constantTimeEqual`) to defend against side-channel timing analysis. +- **Brute-Force Rate Limiting**: The system tracks consecutive failed attempts. After 5 consecutive failed entries, verification is locked out for 30 seconds to prevent automated dictionary attacks. + +### 3. Multi-Tenant Cloud Synchronization & Isolation Boundary +- **Authenticated JWT Requirement**: Mobile clients must authenticate with a valid user session JWT. Anonymous keys are strictly prohibited as user bearer tokens, and static fallback user IDs are rejected. +- **Row Level Security (RLS)**: PostgreSQL tables in the cloud control plane (`cloud_business_profiles`, `cloud_customers`, `cloud_documents`, etc.) enforce strict RLS policies: + `USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id)`. +- **Column Allowlist Sanitization**: Remote delta payloads are validated against strict table column allowlists before persistence into local SQLite, preventing SQL injection and schema corruption from untrusted network inputs. +- **Safe LWW Upserts**: Synchronization uses timestamp-based Last-Write-Wins updates rather than destructive `INSERT OR REPLACE`, preserving relational integrity and foreign keys. + +### 4. Payment Gateway Webhook Reliability & Atomicity +- **Server-Side HMAC-SHA256 Verification**: Webhooks are verified using server-held secrets that never touch mobile devices. Signatures are verified via constant-time comparison. +- **Database-Level Deduplication**: Concurrency and replay attacks are prevented via database unique constraints (`ON CONFLICT (event_id) DO NOTHING`). +- **Atomic State Transitions**: Webhook event logging and payment request state transitions execute within an atomic transaction boundary (`process_payment_webhook`), ensuring payment requests are never marked paid unless the event is durably committed. + +--- + +## Credential Incident Advisory + +Any credential previously exposed in public git commits must be treated as compromised. If you deployed a previous fork containing developer test keys: +1. Immediately revoke and regenerate your keys at [Groq Console](https://console.groq.com/keys) or respective provider portals. +2. Ensure your client application uses personal BYOK keys via the in-app AI Engine settings modal. --- diff --git a/cloud/functions/razorpay-webhook/index.ts b/cloud/functions/razorpay-webhook/index.ts index 74eeb8f..f4f5b81 100644 --- a/cloud/functions/razorpay-webhook/index.ts +++ b/cloud/functions/razorpay-webhook/index.ts @@ -149,25 +149,66 @@ serve(async (req: Request) => { paymentLinkId = payment?.notes?.payment_link_id || null; } - // 5. Atomic transaction log in payment_events - await supabase.from('payment_events').insert({ - business_id: businessId, - event_id: eventId, - event_type: eventType, - provider: 'razorpay', - provider_payment_id: providerPaymentId, - amount_minor: amountMinor, - currency, - payload, - signature: signatureHeader, - is_verified: true, - processed_status: 'processed', - processed_at: new Date().toISOString(), + // 5. Atomic persistence: first attempt database-level atomic stored procedure + const { data: rpcData, error: rpcError } = await supabase.rpc('process_payment_webhook', { + p_event_id: eventId, + p_event_type: eventType, + p_provider: 'razorpay', + p_provider_payment_id: providerPaymentId, + p_amount_minor: amountMinor, + p_currency: currency, + p_payload: payload, + p_signature: signatureHeader, + p_payment_link_id: paymentLinkId, + p_business_id: businessId, }); - // 6. Update payment_request status if linked + if (!rpcError && rpcData) { + if (rpcData.status === 'already_processed') { + return new Response(JSON.stringify({ message: 'Event already processed', eventId }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + return new Response(JSON.stringify({ success: true, eventId, status: rpcData.status }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + + // Fallback: If stored procedure is unavailable, perform atomic ON CONFLICT insert with explicit error boundary + const { error: insertError } = await supabase + .from('payment_events') + .insert({ + business_id: businessId, + event_id: eventId, + event_type: eventType, + provider: 'razorpay', + provider_payment_id: providerPaymentId, + amount_minor: amountMinor, + currency, + payload, + signature: signatureHeader, + is_verified: true, + processed_status: 'processed', + processed_at: new Date().toISOString(), + }); + + if (insertError) { + // Postgres error code 23505 indicates unique_violation on event_id + if (insertError.code === '23505' || insertError.message?.includes('duplicate key') || insertError.message?.includes('already exists')) { + return new Response(JSON.stringify({ message: 'Event already processed', eventId }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + console.error(`Database error inserting payment_event ${eventId}:`, insertError); + throw insertError; + } + + // 6. Update payment_request status if linked with explicit error checking if (paymentLinkId) { - await supabase + const { error: updateError } = await supabase .from('payment_requests') .update({ status: 'paid', @@ -178,6 +219,11 @@ serve(async (req: Request) => { }, }) .eq('provider_reference_id', paymentLinkId); + + if (updateError) { + console.error(`Failed to update payment_request status for link ${paymentLinkId}:`, updateError); + throw updateError; + } } return new Response(JSON.stringify({ success: true, eventId }), { diff --git a/cloud/schema.sql b/cloud/schema.sql index 106c7c7..fcf0d00 100644 --- a/cloud/schema.sql +++ b/cloud/schema.sql @@ -137,3 +137,166 @@ CREATE POLICY tax_packs_read_all ON tax_packs CREATE POLICY tax_pack_updates_read_all ON tax_pack_updates FOR SELECT USING (true); + +-- ============================================================================== +-- ATOMIC TRANSACTION STORED PROCEDURES +-- ============================================================================== + +-- Atomic Webhook Processor: Idempotently ingests webhook event and updates payment ledger in a single transaction +CREATE OR REPLACE FUNCTION process_payment_webhook( + p_event_id TEXT, + p_event_type TEXT, + p_provider VARCHAR(20), + p_provider_payment_id TEXT, + p_amount_minor BIGINT, + p_currency VARCHAR(3), + p_payload JSONB, + p_signature TEXT, + p_payment_link_id TEXT, + p_business_id UUID DEFAULT NULL +) RETURNS JSONB AS $$ +DECLARE + v_event_inserted_id UUID; +BEGIN + -- 1. Atomic insertion with unique conflict handling (defends against race conditions & replay attacks) + INSERT INTO payment_events ( + business_id, event_id, event_type, provider, provider_payment_id, + amount_minor, currency, payload, signature, is_verified, processed_status, processed_at + ) VALUES ( + p_business_id, p_event_id, p_event_type, p_provider, p_provider_payment_id, + p_amount_minor, p_currency, p_payload, p_signature, TRUE, 'processed', NOW() + ) + ON CONFLICT (event_id) DO NOTHING + RETURNING id INTO v_event_inserted_id; + + -- If no row was inserted, event_id already exists (concurrent retry or duplicate delivery) + IF v_event_inserted_id IS NULL THEN + RETURN jsonb_build_object('success', TRUE, 'status', 'already_processed', 'event_id', p_event_id); + END IF; + + -- 2. Atomic state transition for the matching payment request + IF p_payment_link_id IS NOT NULL THEN + UPDATE payment_requests + SET status = 'paid', + updated_at = NOW(), + metadata = jsonb_build_object( + 'providerPaymentId', p_provider_payment_id, + 'paidAt', NOW() + ) + WHERE provider_reference_id = p_payment_link_id; + END IF; + + RETURN jsonb_build_object('success', TRUE, 'status', 'processed', 'event_id', p_event_id); +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +-- ============================================================================== +-- MULTI-TENANT DELTA SYNCHRONIZATION TABLES WITH ROW LEVEL SECURITY +-- ============================================================================== + +-- 1. Business Profiles Sync +CREATE TABLE IF NOT EXISTS cloud_business_profiles ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_business_profiles ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_profiles_tenant_isolation ON cloud_business_profiles + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 2. Customers Sync +CREATE TABLE IF NOT EXISTS cloud_customers ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_customers ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_customers_tenant_isolation ON cloud_customers + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 3. Catalog Items Sync +CREATE TABLE IF NOT EXISTS cloud_catalog_items ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_catalog_items ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_catalog_items_tenant_isolation ON cloud_catalog_items + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 4. Documents Sync +CREATE TABLE IF NOT EXISTS cloud_documents ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_documents ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_documents_tenant_isolation ON cloud_documents + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 5. Document Items Sync +CREATE TABLE IF NOT EXISTS cloud_document_items ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_document_items ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_document_items_tenant_isolation ON cloud_document_items + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 6. Payments Sync +CREATE TABLE IF NOT EXISTS cloud_payments ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_payments ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_payments_tenant_isolation ON cloud_payments + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + +-- 7. Universal Documents Sync +CREATE TABLE IF NOT EXISTS cloud_universal_documents ( + id TEXT NOT NULL, + user_id UUID NOT NULL, + data JSONB NOT NULL, + client_updated_at BIGINT NOT NULL, + server_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + device_id TEXT, + PRIMARY KEY (user_id, id) +); +ALTER TABLE cloud_universal_documents ENABLE ROW LEVEL SECURITY; +CREATE POLICY cloud_universal_documents_tenant_isolation ON cloud_universal_documents + FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); + + diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index cc8db19..64b80a7 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -113,6 +113,7 @@ function RootLayoutInner() { + diff --git a/src/app/ai/assistant.tsx b/src/app/ai/assistant.tsx index bad2ce3..1b0b001 100644 --- a/src/app/ai/assistant.tsx +++ b/src/app/ai/assistant.tsx @@ -57,10 +57,16 @@ import { Check, Maximize2, RotateCcw, + Plus, + Menu, + Pencil, + Mic, + ArrowUp, + Square, } from 'lucide-react-native'; import { useTheme } from '../../design/ThemeContext'; import { colors, radii, spacing, typography } from '../../design/tokens'; -import { AiConfigService, AiConfig, AiProvider, DEFAULT_GROQ_KEY, MAX_UNIVERSAL_KEY_DOCS } from '../../services/ai/AiConfigService'; +import { AiConfigService, AiConfig, AiProvider } from '../../services/ai/AiConfigService'; import { AiDocumentAgent, AgentChatMessage, ParsedDocumentDraft } from '../../services/ai/AiDocumentAgent'; import { AiTemplateBridge, DocumentTemplateOption } from '../../services/ai/AiTemplateBridge'; import { createMoney, formatMoney } from '../../domain/money/Money'; @@ -71,11 +77,16 @@ import { ActionApprovalSheet } from '../../components/ai/ActionApprovalSheet'; import { RecommendationEngine, RecommendationItem } from '../../services/ai/RecommendationEngine'; import { BusinessProfile } from '../../domain/profile/types'; import { ClaudeThinkingIndicator } from '../../components/animations/ClaudeThinkingIndicator'; +import { AuraWavesVisualizer } from '../../components/animations/AuraWavesVisualizer'; +import { CopilotActionSheet } from '../../components/ai/CopilotActionSheet'; import { IntelligentMessageRenderer } from '../../components/ai/IntelligentMessageRenderer'; import { FluidStreamingText } from '../../components/ai/FluidStreamingText'; import { AnimatedArtifactTile } from '../../components/ai/AnimatedArtifactTile'; import { ChatQuestionOption } from '../../services/ai/DocumentQuestionElicitor'; import { ChatboxAnimatedMcq } from '../../components/ai/ChatboxAnimatedMcq'; +import { AuraSparkle } from '../../components/ai/AuraSparkle'; +import { PulsingDots } from '../../components/ai/PulsingDots'; +import { AmbientBottomGlow } from '../../components/animations/AmbientBottomGlow'; /** * Transforms raw neural reasoning thoughts into clean, high-elegance cognitive steps. @@ -295,19 +306,39 @@ export default function AiAssistantScreen() { const isDesktop = windowWidth >= 960; // Chat State - const [messages, setMessages] = useState([ - { - id: 'welcome_msg', - role: 'assistant', - content: - 'What would you like to draft today?\n\nTell me what document you need in plain words, or tap a quick starter below.', - timestamp: Date.now(), - }, - ]); + const [messages, setMessages] = useState([]); const [inputText, setInputText] = useState(''); const [isProcessing, setIsProcessing] = useState(false); const [activeDraft, setActiveDraft] = useState(null); const [activeDrafts, setActiveDrafts] = useState([]); + const [showActionSheet, setShowActionSheet] = useState(false); + const [businessProfile, setBusinessProfile] = useState(null); + + useEffect(() => { + BusinessProfileRepository.getActiveProfile() + .then((p) => { + if (p) setBusinessProfile(p); + }) + .catch(() => {}); + }, []); + + const firstName = useMemo(() => { + const raw = businessProfile?.name || businessProfile?.legal_name || ''; + if (!raw) return ''; + const parts = raw.trim().split(/\s+/); + return parts[0] || ''; + }, [businessProfile]); + + const hasUserMessages = useMemo(() => { + return messages.some((m) => m.role === 'user'); + }, [messages]); + + const handleStopGeneration = () => { + setIsProcessing(false); + setMessages((prev) => + prev.map((m) => (m.isThinking || m.isStreaming ? { ...m, isThinking: false, isStreaming: false } : m)) + ); + }; // Codex Real-Time Streaming & Thinking State const [elapsedSeconds, setElapsedSeconds] = useState(0); @@ -321,9 +352,9 @@ export default function AiAssistantScreen() { const [showConfigModal, setShowConfigModal] = useState(false); const [config, setConfig] = useState({ provider: 'groq', - apiKey: DEFAULT_GROQ_KEY, + apiKey: '', model: 'openai/gpt-oss-120b', - isReady: true, + isReady: false, }); const [universalStatus, setUniversalStatus] = useState<{ isLimited: boolean; @@ -333,10 +364,10 @@ export default function AiAssistantScreen() { }>({ isLimited: false, count: 0, - max: MAX_UNIVERSAL_KEY_DOCS, - isUniversalKey: true, + max: 7, + isUniversalKey: false, }); - const [tempApiKey, setTempApiKey] = useState(DEFAULT_GROQ_KEY); + const [tempApiKey, setTempApiKey] = useState(''); const [tempProvider, setTempProvider] = useState('groq'); const [isTestingKey, setIsTestingKey] = useState(false); const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null); @@ -363,6 +394,16 @@ export default function AiAssistantScreen() { const scrollViewRef = useRef(null); const textInputRef = useRef(null); + const lastScrollTime = useRef(0); + + const handleContentSizeChange = () => { + const now = Date.now(); + // Throttle animated scroll to eliminate micro-jitter and shaking + if (now - lastScrollTime.current > 140) { + lastScrollTime.current = now; + scrollViewRef.current?.scrollToEnd({ animated: true }); + } + }; // Hydrate persistent AI session and recommendations from SQLite on Mount useEffect(() => { @@ -375,7 +416,10 @@ export default function AiAssistantScreen() { } const saved = await AgentSessionRepository.getMessages(session.id); if (saved && saved.length > 0) { - setMessages(saved); + const nonWelcome = saved.filter((m) => !m.id.startsWith('welcome_')); + if (nonWelcome.length > 0) { + setMessages(nonWelcome); + } } const recs = await RecommendationEngine.evaluateRecommendations(); setRecommendations(recs); @@ -389,18 +433,10 @@ export default function AiAssistantScreen() { // Load Config on Mount useEffect(() => { async function initConfig() { - let current = await AiConfigService.getConfig(); - if (current.provider === 'offline_heuristic' && !current.apiKey) { - await AiConfigService.saveConfig({ - provider: 'groq', - apiKey: DEFAULT_GROQ_KEY, - model: 'openai/gpt-oss-120b', - }); - current = await AiConfigService.getConfig(); - } + const current = await AiConfigService.getConfig(); setConfig(current); setTempProvider(current.provider); - setTempApiKey(current.apiKey || (current.provider === 'groq' ? DEFAULT_GROQ_KEY : '')); + setTempApiKey(current.apiKey || ''); const limit = await AiConfigService.checkUniversalLimit(); setUniversalStatus(limit); } @@ -533,15 +569,7 @@ export default function AiAssistantScreen() { await AgentSessionRepository.clearSession().catch(() => {}); setActiveDraft(null); setActiveDrafts([]); - setMessages([ - { - id: `welcome_${Date.now()}`, - role: 'assistant', - content: - 'What would you like to draft today?\n\nTell me what document you need in plain words, or tap a quick starter below.', - timestamp: Date.now(), - }, - ]); + setMessages([]); } // Handle Send Message with Real-Time Codex Streaming Animation @@ -844,356 +872,315 @@ export default function AiAssistantScreen() { } return ( - + {/* Top Header Bar */} - - - router.back()} - style={styles.backButton} - hitSlop={8} - accessibilityRole="button" - accessibilityLabel="Go back" - > - - - - - - Billframe AI Agent - - - {config.provider === 'offline_heuristic' - ? 'Offline Engine' - : config.isReady - ? 'AI Agent Β· Ready' - : 'Offline Engine'} - - - - - - setShowConfigModal(true)} - style={[ - styles.byokBadge, - { - backgroundColor: universalStatus.isUniversalKey - ? (universalStatus.isLimited ? '#3f1a1a' : '#142938') - : config.provider === 'offline_heuristic' - ? '#1f2024' - : '#132e22', - borderColor: universalStatus.isUniversalKey - ? (universalStatus.isLimited ? '#f87171' : '#38BDF8') - : config.provider === 'offline_heuristic' - ? '#35363B' - : '#10B981', - }, - ]} - accessibilityRole="button" - accessibilityLabel="AI Engine and BYOK Key Status" - > - - {universalStatus.isUniversalKey - ? (universalStatus.isLimited ? '⚑ Limit: 7/7 Β· BYOK β†—' : `⚑ Free: ${universalStatus.count}/7 Β· BYOK β†—`) - : config.provider === 'offline_heuristic' - ? 'πŸ”’ Offline' - : 'πŸ”‘ BYOK Active'} - - + + router.back()} + style={styles.headerIconButton} + hitSlop={8} + accessibilityRole="button" + accessibilityLabel="Go back" + > + + + + setShowConfigModal(true)} + style={styles.modelSwitcherPill} + hitSlop={8} + accessibilityRole="button" + accessibilityLabel="Model switcher" + > + + {config.provider === 'offline_heuristic' ? 'Billframe 4.0' : 'Billframe Copilot'} + + + + - + setShowConfigModal(true)} - style={[styles.settingsButton, { backgroundColor: theme.surfaceSecondary, borderColor: theme.borderSubtle }]} + style={styles.avatarButton} hitSlop={8} accessibilityRole="button" - accessibilityLabel="Open AI Settings" + accessibilityLabel="User profile" > - + + {firstName ? firstName.charAt(0).toUpperCase() : 'A'} + + {/* Main Responsive Dual-Pane Layout */} - + {/* Left Column: Conversational AI Copilot */} - scrollViewRef.current?.scrollToEnd({ animated: true })} - > - {messages.map((msg) => { - const isUser = msg.role === 'user'; + {/* Ambient Holographic Aura Waves Upper Side (Active during inference/streaming) */} + - if (isUser) { - return ( - - - - {msg.content} - - - - ); - } + {/* Ambient Deep Atmospheric Glow at Bottom */} + - return ( - - - {/* Claude Intelligent Thinking Indicator (Flat, Inline, Organic) */} - {(msg.isThinking || msg.reasoningTrace || (msg.taskSteps && msg.taskSteps.length > 0)) && ( - - toggleThought(msg.id)} - textColor={theme.textPrimary} - textSecondaryColor={theme.textMuted} - /> - - )} + {!hasUserMessages ? ( + + + + {firstName ? `What's next, ${firstName}?` : 'Where should we start?'} + + + ) : ( + + {messages.map((msg) => { + const isUser = msg.role === 'user'; + + if (isUser) { + return ( + + + + {msg.content} + + + + ); + } + + return ( + + + {/* Claude Intelligent Thinking Indicator (Flat, Inline, Organic) */} + {(msg.isThinking || msg.reasoningTrace || (msg.taskSteps && msg.taskSteps.length > 0)) && ( + + toggleThought(msg.id)} + textColor="#F4F4F5" + textSecondaryColor="#8E8E93" + /> + + )} + + {/* 3 Glowing Pulsing Dots while waiting for first tokens */} + {msg.isThinking && !msg.content && ( + + )} - {/* Conversational Reply Text & Materialized Artifacts with Claude-Style Motion */} - {(msg.content || msg.interactiveQuestion || (msg.documentDrafts && msg.documentDrafts.length > 0) || msg.documentDraft) && !msg.isThinking ? ( - - {msg.content ? ( + {/* Conversational Reply Text & Materialized Artifacts with Claude-Style Motion */} + {(msg.content || msg.interactiveQuestion || (msg.documentDrafts && msg.documentDrafts.length > 0) || msg.documentDraft) && !msg.isThinking ? ( + + {msg.content ? ( + + + + ) : null} + + {/* ── Claude-Style Materialized Artifact Tiles ── */} + {(() => { + const draftsToRender = (msg.documentDrafts && msg.documentDrafts.length > 0) + ? msg.documentDrafts + : (msg.documentDraft ? [msg.documentDraft] : []); + if (draftsToRender.length === 0) return null; + + return ( + + {draftsToRender.map((draft, dIdx) => { + const isSelected = activeDraft?.documentId === draft.documentId || activeDraft?.documentNumber === draft.documentNumber; + + return ( + { + setActiveDraft(draft); + if (!isDesktop) handleOpenPreview(draft); + }} + onPrint={() => handlePrintDocument(draft)} + onExportHtml={() => handleDownloadHtml(draft)} + onEditForm={() => router.push(`/document/edit?id=${draft.documentId}` as any)} + /> + ); + })} + + ); + })()} + + {/* ── Subtle In-Message Question Status (Prompted in Chatbox below) ── */} + {msg.interactiveQuestion && !msg.interactiveQuestion.isAnswered && ( + + + + Guided Field: {msg.interactiveQuestion.question} (Choose in chat box below) + + + )} + + {msg.interactiveQuestion?.isAnswered && msg.interactiveQuestion.selectedValue && ( + + + + Answered: {msg.interactiveQuestion.selectedValue} + + + )} + + ) : (msg.isStreaming && !msg.isThinking) ? ( ) : null} + + + ); + })} + + )} - {/* Initial Welcome Quick Suggestions */} - {msg.id === 'welcome_msg' && ( - - handleSendMessage('What is my current business overview and total receivables?')} - > - πŸ“Š Business Overview - Live balance, receivables, and ledger summary - - - handleSendMessage('List all overdue invoices and unpaid customer balances')} - > - ⏰ Check Overdue - Find unpaid invoices and outstanding payments - - - handleSendMessage('Draft a GST Tax Invoice for Acme Corp with 18% GST')} - > - ✦ GST Tax Invoice - Compliant B2B invoice with CBIC tax calculations - + {/* Context-Aware Smart Workflow Chips (Hidden when question active or no active draft) */} + {hasUserMessages && activeDraft && !activeQuestion && ( + + + {getSmartWorkflowChips(activeDraft).map((chip, idx) => ( + { + if (chip.label.startsWith('βŽ™')) { + if (activeDraft) handlePrintDocument(activeDraft); + } else { + handleSendMessage(chip.prompt); + } + }} + > + {chip.label} + + ))} + + + )} - handleSendMessage('build me complete highest ats scoring resume for farhan noor for ai engineer')} - > - πŸ“„ ATS Resume (Farhan Noor) - ATS-optimized curriculum vitae with 98% score - - - )} + {/* Floating Input Bar & In-Chatbox Question Elicitor */} + + {/* Animated Guided MCQ Question Card Rises Up Animately in Chatbox */} + {activeQuestion && ( + + )} - {/* ── Claude-Style Materialized Artifact Tiles ── */} - {(() => { - const draftsToRender = (msg.documentDrafts && msg.documentDrafts.length > 0) - ? msg.documentDrafts - : (msg.documentDraft ? [msg.documentDraft] : []); - if (draftsToRender.length === 0) return null; - - return ( - - {draftsToRender.map((draft, dIdx) => { - const isSelected = activeDraft?.documentId === draft.documentId || activeDraft?.documentNumber === draft.documentNumber; - - return ( - { - setActiveDraft(draft); - if (!isDesktop) handleOpenPreview(draft); - }} - onPrint={() => handlePrintDocument(draft)} - onExportHtml={() => handleDownloadHtml(draft)} - onEditForm={() => router.push(`/document/edit?id=${draft.documentId}` as any)} - /> - ); - })} - - ); - })()} - - {/* ── Subtle In-Message Question Status (Prompted in Chatbox below) ── */} - {msg.interactiveQuestion && !msg.interactiveQuestion.isAnswered && ( - - - - Guided Field: {msg.interactiveQuestion.question} (Choose in chat box below) - - - )} + + setShowActionSheet(true)} + hitSlop={8} + accessibilityRole="button" + accessibilityLabel="Open document action menu" + > + + - {msg.interactiveQuestion?.isAnswered && msg.interactiveQuestion.selectedValue && ( - - - - Answered: {msg.interactiveQuestion.selectedValue} - - - )} - - ) : (msg.isStreaming && !msg.isThinking) ? ( - - - - ) : null} - - - ); - })} - - - {/* Context-Aware Smart Workflow Chips (Hidden when question active) */} - {!activeQuestion && ( - - - {getSmartWorkflowChips(activeDraft).map((chip, idx) => ( + handleSendMessage()} + returnKeyType="send" + editable={!isProcessing} + /> + + {inputText.trim().length > 0 ? ( { - if (chip.label.startsWith('βŽ™')) { - if (activeDraft) handlePrintDocument(activeDraft); - } else { - handleSendMessage(chip.prompt); - } - }} + style={styles.sendCircleBtn} + onPress={() => handleSendMessage()} + disabled={isProcessing} + accessibilityRole="button" + accessibilityLabel="Send message" > - {chip.label} + + + ) : isProcessing ? ( + + - ))} - - - )} - - {/* Floating Input Bar & In-Chatbox Question Elicitor */} - - {/* Animated Guided MCQ Question Card Rises Up Animately in Chatbox */} - {activeQuestion && ( - - )} - - - handleSendMessage()} - returnKeyType="send" - editable={!isProcessing} - /> - handleSendMessage()} - disabled={!inputText.trim() || isProcessing} - accessibilityRole="button" - accessibilityLabel="Send message" - > - {isProcessing ? ( - ) : ( - + + handleSendMessage('Draft a GST Tax Invoice for Acme Corp with 18% GST')} + accessibilityRole="button" + accessibilityLabel="Voice input" + > + + + + setShowActionSheet(true)} + accessibilityRole="button" + accessibilityLabel="Audio assistant" + > + + + + + )} - + - - + {/* Right Column: Live Document Artifact Canvas (Desktop Wide Screen) */} {isDesktop && ( @@ -1380,6 +1367,7 @@ export default function AiAssistantScreen() {