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.*
@@ -10,51 +10,54 @@
-
-
-
+
+
+
---
## π 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() {
setPendingProposal(null)}
/>
+
+ {/* Sleek Monochrome Bottom Sheet Overlay (Image 4 Style) */}
+ setShowActionSheet(false)}
+ activeDraft={activeDraft}
+ onPreview={() => activeDraft && handleOpenPreview(activeDraft)}
+ onPrint={() => activeDraft && handlePrintDocument(activeDraft)}
+ onDownloadHtml={() => activeDraft && handleDownloadHtml(activeDraft)}
+ onOpenStudio={() => router.push('/templates/studio' as any)}
+ onSelectPrompt={(p) => handleSendMessage(p)}
+ />
);
}
@@ -1842,14 +1818,82 @@ export default function AiAssistantScreen() {
const styles = StyleSheet.create({
safeArea: {
flex: 1,
+ backgroundColor: '#000000',
},
headerBar: {
- height: 56,
- borderBottomWidth: StyleSheet.hairlineWidth,
+ height: 54,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
+ backgroundColor: '#000000',
+ },
+ headerIconButton: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ modelSwitcherPill: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ paddingHorizontal: 12,
+ paddingVertical: 6,
+ borderRadius: 18,
+ backgroundColor: 'transparent',
+ },
+ modelSwitcherText: {
+ fontSize: 17,
+ fontWeight: '600',
+ color: '#F4F4F5',
+ letterSpacing: -0.2,
+ },
+ headerRightGroup: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ },
+ avatarButton: {
+ width: 32,
+ height: 32,
+ borderRadius: 16,
+ backgroundColor: '#0D9488',
+ alignItems: 'center',
+ justifyContent: 'center',
+ position: 'relative',
+ },
+ avatarText: {
+ fontSize: 14,
+ fontWeight: '700',
+ color: '#FFFFFF',
+ },
+ avatarStatusDot: {
+ position: 'absolute',
+ bottom: -1,
+ right: -1,
+ width: 8,
+ height: 8,
+ borderRadius: 4,
+ backgroundColor: '#10B981',
+ borderWidth: 1.5,
+ borderColor: '#000000',
+ },
+ emptyContainer: {
+ flex: 1,
+ alignItems: 'center',
+ justifyContent: 'center',
+ paddingBottom: 40,
+ paddingHorizontal: 24,
+ zIndex: 1,
+ },
+ emptyTitle: {
+ fontSize: 28,
+ fontWeight: '400',
+ color: '#F1F5F9',
+ textAlign: 'center',
+ letterSpacing: -0.3,
},
headerLeft: {
flexDirection: 'row',
@@ -1914,22 +1958,102 @@ const styles = StyleSheet.create({
justifyContent: 'flex-start',
},
userBubbleContainer: {
- maxWidth: Platform.OS === 'web' ? '78%' : '88%',
- borderRadius: 16,
- borderBottomRightRadius: 4,
- paddingVertical: 10,
- paddingHorizontal: 14,
- borderWidth: 1,
+ maxWidth: Platform.OS === 'web' ? '78%' : '84%',
+ borderRadius: 24,
+ paddingVertical: 14,
+ paddingHorizontal: 20,
+ backgroundColor: '#1E293B',
+ alignSelf: 'flex-end',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
- shadowOpacity: 0.1,
- shadowRadius: 2,
- elevation: 1,
+ shadowOpacity: 0.15,
+ shadowRadius: 3,
+ elevation: 2,
},
userMessageText: {
- fontSize: 14,
- lineHeight: 20,
+ fontSize: 16,
+ lineHeight: 22,
fontWeight: '400',
+ color: '#F8FAFC',
+ },
+ bottomBarWrapper: {
+ paddingHorizontal: 16,
+ paddingBottom: Platform.OS === 'ios' ? 12 : 16,
+ backgroundColor: 'transparent',
+ zIndex: 10,
+ },
+ floatingInputPill: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ height: 58,
+ borderRadius: 29,
+ backgroundColor: '#1C1D21',
+ borderWidth: 1,
+ borderColor: 'rgba(255, 255, 255, 0.08)',
+ paddingHorizontal: 10,
+ },
+ floatingPlusBtn: {
+ width: 38,
+ height: 38,
+ borderRadius: 19,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ floatingTextInputField: {
+ flex: 1,
+ color: '#FFFFFF',
+ fontSize: 16,
+ paddingHorizontal: 10,
+ height: '100%',
+ },
+ sendCircleBtn: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ backgroundColor: '#FFFFFF',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ stopCircleBtn: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ backgroundColor: '#27272A',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ stopSquareIcon: {
+ width: 12,
+ height: 12,
+ borderRadius: 2,
+ backgroundColor: '#FFFFFF',
+ },
+ idleRightGroup: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ },
+ micCircleBtn: {
+ width: 36,
+ height: 36,
+ borderRadius: 18,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ voiceOrbCircleBtn: {
+ width: 40,
+ height: 40,
+ borderRadius: 20,
+ backgroundColor: '#2563EB',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'row',
+ gap: 2.5,
+ },
+ orbWaveBar: {
+ width: 2.5,
+ borderRadius: 1,
+ backgroundColor: '#FFFFFF',
},
messageTimestamp: {
fontSize: 10,
@@ -2073,6 +2197,42 @@ const styles = StyleSheet.create({
borderRadius: 3,
backgroundColor: '#10B981',
},
+ copilotHeroBanner: {
+ paddingVertical: 14,
+ paddingHorizontal: 14,
+ backgroundColor: 'rgba(255, 255, 255, 0.02)',
+ borderWidth: 1,
+ borderColor: 'rgba(255, 255, 255, 0.06)',
+ borderRadius: 16,
+ marginBottom: 12,
+ },
+ copilotHeroBadge: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 5,
+ alignSelf: 'flex-start',
+ backgroundColor: 'rgba(56, 189, 248, 0.12)',
+ paddingHorizontal: 8,
+ paddingVertical: 3,
+ borderRadius: 8,
+ marginBottom: 8,
+ },
+ copilotHeroBadgeText: {
+ fontSize: 10,
+ fontWeight: '800',
+ color: '#38BDF8',
+ letterSpacing: 0.6,
+ },
+ copilotHeroTitle: {
+ fontSize: 16,
+ fontWeight: '700',
+ letterSpacing: -0.2,
+ marginBottom: 4,
+ },
+ copilotHeroSubtitle: {
+ fontSize: 12,
+ lineHeight: 17,
+ },
welcomeGrid: {
marginTop: 12,
gap: 8,
@@ -2550,7 +2710,7 @@ const styles = StyleSheet.create({
alignItems: 'center',
borderRadius: 24,
borderWidth: 1,
- paddingHorizontal: 14,
+ paddingHorizontal: 12,
paddingVertical: 4,
minHeight: 48,
shadowColor: '#000',
@@ -2559,6 +2719,15 @@ const styles = StyleSheet.create({
shadowRadius: 4,
elevation: 2,
},
+ floatingPlusButton: {
+ width: 32,
+ height: 32,
+ borderRadius: 16,
+ backgroundColor: 'rgba(255, 255, 255, 0.08)',
+ alignItems: 'center',
+ justifyContent: 'center',
+ marginRight: 6,
+ },
floatingTextInput: {
flex: 1,
fontSize: 14,
diff --git a/src/app/security-pin.tsx b/src/app/security-pin.tsx
index 441cd10..712f565 100644
--- a/src/app/security-pin.tsx
+++ b/src/app/security-pin.tsx
@@ -85,9 +85,21 @@ export default function SecurityPinScreen() {
const handleDisablePin = async () => {
setErrorMsg('');
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Too many failed attempts. Locked out for ${remainingSec} second(s).`);
+ return;
+ }
+
const isValid = await SecurityService.verifyPin(currentPinToDisable);
if (!isValid) {
- setErrorMsg('Incorrect current PIN.');
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Too many failed attempts. Locked out for ${remainingSec} second(s).`);
+ } else {
+ const attempts = await SecurityService.getFailedAttempts();
+ setErrorMsg(`Incorrect current PIN. (${attempts}/5 attempts used)`);
+ }
return;
}
diff --git a/src/app/templates/studio.tsx b/src/app/templates/studio.tsx
index 2512c88..8f1a99a 100644
--- a/src/app/templates/studio.tsx
+++ b/src/app/templates/studio.tsx
@@ -103,8 +103,10 @@ export default function DocumentStudioScreen() {
}
// Common standard fallbacks
- if (!initial.signatory_name) initial.signatory_name = 'Rahul Mehta';
- if (!initial.signatory_title) initial.signatory_title = 'CEO, Apex Solutions';
+ if (!existingData) {
+ initial.signatory_name ??= 'Rahul Mehta';
+ initial.signatory_title ??= 'CEO, Apex Solutions';
+ }
setFormData(initial);
@@ -125,8 +127,10 @@ export default function DocumentStudioScreen() {
}
// Default reference number format
- const prefix = (s.code || 'DOC').substring(0, 4).toUpperCase();
- setDocNumber(`${prefix}-2026-042`);
+ if (!existingData) {
+ const prefix = (s.code || 'DOC').substring(0, 4).toUpperCase();
+ setDocNumber(`${prefix}-2026-042`);
+ }
}, []);
// Load Business Profile & Custom Schema if any
@@ -152,6 +156,8 @@ export default function DocumentStudioScreen() {
setDocNumber(inst.documentNumber);
setDocStatus(inst.status as any);
if (inst.partyName) setPartyName(inst.partyName);
+ setSignatoryName(inst.content.signatory_name ?? active?.signatory_name ?? '');
+ setSignatoryTitle(inst.content.signatory_title ?? active?.signatory_title ?? '');
if (inst.templateCode) setSelectedLayout(inst.templateCode);
initializeFormDataFromSchema(activeSchema, inst.content);
return;
@@ -260,20 +266,11 @@ export default function DocumentStudioScreen() {
const generatePreview = useCallback((version: number) => {
const dummyBiz: BusinessProfile = businessProfile || {
id: 'biz_default',
- name: 'Apex Solutions',
- legal_name: 'Apex Solutions Pvt Ltd',
- tax_id: '29ABCDE1234F1Z5',
+ name: '',
default_currency: 'INR',
default_document_locale: 'en-IN',
- address_line1: 'Flat 402, Green View Apartments',
- city: 'Bengaluru',
- state: 'Karnataka',
- postal_code: '560038',
country: 'IN',
country_iso2: 'IN',
- phone: '+91 98765 43210',
- email: 'hello@apexsolutions.com',
- website: 'www.apexsolutions.com',
is_active: 1,
created_at: Date.now(),
updated_at: Date.now(),
diff --git a/src/components/ai/AuraSparkle.tsx b/src/components/ai/AuraSparkle.tsx
new file mode 100644
index 0000000..8129ab8
--- /dev/null
+++ b/src/components/ai/AuraSparkle.tsx
@@ -0,0 +1,48 @@
+import React from 'react';
+import { View, StyleSheet, Animated, Easing } from 'react-native';
+import Svg, { Defs, LinearGradient, RadialGradient, Stop, Path } from 'react-native-svg';
+
+export interface AuraSparkleProps {
+ size?: number;
+}
+
+export const AuraSparkle: React.FC = ({ size = 44 }) => {
+ return (
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ justifyContent: 'center',
+ alignItems: 'center',
+ marginBottom: 20,
+ shadowColor: '#38BDF8',
+ shadowOffset: { width: 0, height: 0 },
+ shadowOpacity: 0.5,
+ shadowRadius: 16,
+ elevation: 8,
+ },
+});
diff --git a/src/components/ai/CopilotActionSheet.tsx b/src/components/ai/CopilotActionSheet.tsx
new file mode 100644
index 0000000..b3f7de0
--- /dev/null
+++ b/src/components/ai/CopilotActionSheet.tsx
@@ -0,0 +1,361 @@
+import React from 'react';
+import {
+ StyleSheet,
+ View,
+ Text,
+ Modal,
+ Pressable,
+ ScrollView,
+ Platform,
+} from 'react-native';
+import {
+ Image as ImageIcon,
+ Camera,
+ Paperclip,
+ Layers,
+ FileText,
+ Briefcase,
+ Sparkles,
+ Home,
+ Receipt,
+ Truck,
+ Printer,
+ Sliders,
+ X,
+} from 'lucide-react-native';
+import { ParsedDocumentDraft } from '../../services/ai/AiDocumentAgent';
+
+export interface CopilotActionSheetProps {
+ visible: boolean;
+ onClose: () => void;
+ activeDraft: ParsedDocumentDraft | null;
+ onPreview: () => void;
+ onPrint: () => void;
+ onDownloadHtml: () => void;
+ onOpenStudio: () => void;
+ onSelectPrompt: (prompt: string) => void;
+}
+
+export const CopilotActionSheet: React.FC = ({
+ visible,
+ onClose,
+ activeDraft,
+ onPreview,
+ onPrint,
+ onDownloadHtml,
+ onOpenStudio,
+ onSelectPrompt,
+}) => {
+ return (
+
+
+ e.stopPropagation()}>
+ {/* Center Drag Handle */}
+
+
+
+
+ {/* Top Row: Horizontal Squircles (Photos, Camera, Files, Canvas) */}
+
+ {/* Photos */}
+ [styles.squircleItem, pressed && styles.squirclePressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Upload an invoice photo or receipt image to extract items and GST');
+ }}
+ accessibilityRole="button"
+ accessibilityLabel="Upload Photos"
+ >
+
+
+
+ Photos
+
+
+ {/* Camera */}
+ [styles.squircleItem, pressed && styles.squirclePressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Scan a paper invoice or receipt using camera OCR');
+ }}
+ accessibilityRole="button"
+ accessibilityLabel="Scan Camera"
+ >
+
+
+
+ Camera
+
+
+ {/* Files */}
+ [styles.squircleItem, pressed && styles.squirclePressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Import PDF or CSV file to populate line items and ledger');
+ }}
+ accessibilityRole="button"
+ accessibilityLabel="Attach Files"
+ >
+
+
+
+ Files
+
+
+ {/* Canvas / Studio */}
+ [styles.squircleItem, pressed && styles.squirclePressed]}
+ onPress={() => {
+ onClose();
+ if (activeDraft) {
+ onPreview();
+ } else {
+ onOpenStudio();
+ }
+ }}
+ accessibilityRole="button"
+ accessibilityLabel="Open Document Canvas"
+ >
+
+
+
+ Canvas
+
+
+
+ {/* Vertical Menu Items */}
+
+ {/* Tax Invoice & GST */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Draft a GST Tax Invoice for Acme Corp with 18% GST');
+ }}
+ >
+
+
+
+
+ Tax Invoice & GST
+ CBIC-compliant B2B & B2C invoice with statutory calculations
+
+
+
+ {/* Salary Slip & Payslip */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Create a salary slip for John Doe, Senior Architect, basic 65,000, HRA 25,000, PF 3,600 for October 2026');
+ }}
+ >
+
+
+
+
+ Salary & Payslip
+ Statutory monthly earnings, PF deductions and net pay
+
+
+
+ {/* ATS Resume */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('build me complete highest ats scoring resume for farhan noor for ai engineer');
+ }}
+ >
+
+
+
+
+ ATS Engineering Resume
+ High-impact CV optimized for applicant tracking systems
+
+
+
+ {/* House Rent Receipt */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Generate a House Rent Receipt for tenant Rahul Sharma for 28,000 INR');
+ }}
+ >
+
+
+
+
+ House Rent Receipt
+ HRA tax exemption proof with revenue stamp ledger
+
+
+
+ {/* Commercial Quotation */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Draft a commercial quotation for enterprise software implementation');
+ }}
+ >
+
+
+
+
+ Commercial Quotation
+ Formal sales quotation with payment terms & scope
+
+
+
+ {/* Delivery Challan */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onSelectPrompt('Generate an official delivery challan for 50 commercial display panels');
+ }}
+ >
+
+
+
+
+ Delivery Challan
+ Goods dispatch slip with vehicle number & e-way bill
+
+
+
+ {/* Document Studio Canvas */}
+ [styles.actionRow, pressed && styles.actionRowPressed]}
+ onPress={() => {
+ onClose();
+ onOpenStudio();
+ }}
+ >
+
+
+
+
+ Canvas & Studio
+ Code, write, or design custom financial templates
+
+
+
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ backdrop: {
+ flex: 1,
+ backgroundColor: 'rgba(0, 0, 0, 0.65)',
+ justifyContent: 'flex-end',
+ },
+ sheetContainer: {
+ backgroundColor: '#16171B',
+ borderTopLeftRadius: 28,
+ borderTopRightRadius: 28,
+ paddingTop: 12,
+ paddingBottom: Platform.OS === 'ios' ? 40 : 24,
+ maxHeight: '75%',
+ borderWidth: 1,
+ borderColor: 'rgba(255, 255, 255, 0.08)',
+ },
+ dragHandleContainer: {
+ alignItems: 'center',
+ paddingVertical: 6,
+ marginBottom: 8,
+ },
+ dragHandle: {
+ width: 36,
+ height: 4,
+ borderRadius: 2,
+ backgroundColor: '#52525B',
+ },
+ topSquirclesRow: {
+ flexDirection: 'row',
+ justifyContent: 'space-around',
+ paddingHorizontal: 16,
+ paddingBottom: 20,
+ borderBottomWidth: 1,
+ borderBottomColor: 'rgba(255, 255, 255, 0.06)',
+ },
+ squircleItem: {
+ alignItems: 'center',
+ gap: 8,
+ },
+ squirclePressed: {
+ opacity: 0.7,
+ transform: [{ scale: 0.96 }],
+ },
+ squircleIconBox: {
+ width: 64,
+ height: 64,
+ borderRadius: 22,
+ backgroundColor: '#23242A',
+ justifyContent: 'center',
+ alignItems: 'center',
+ borderWidth: 1,
+ borderColor: 'rgba(255, 255, 255, 0.06)',
+ },
+ squircleLabel: {
+ fontSize: 13,
+ fontWeight: '500',
+ color: '#D4D4D8',
+ },
+ actionList: {
+ marginTop: 8,
+ },
+ actionListContent: {
+ paddingHorizontal: 20,
+ paddingVertical: 8,
+ gap: 4,
+ },
+ actionRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingVertical: 14,
+ paddingHorizontal: 8,
+ borderRadius: 14,
+ gap: 16,
+ },
+ actionRowPressed: {
+ backgroundColor: 'rgba(255, 255, 255, 0.04)',
+ },
+ actionIconCol: {
+ width: 36,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ actionTextCol: {
+ flex: 1,
+ },
+ actionTitle: {
+ fontSize: 16,
+ fontWeight: '500',
+ color: '#F4F4F5',
+ marginBottom: 2,
+ },
+ actionDesc: {
+ fontSize: 13,
+ color: '#9CA3AF',
+ lineHeight: 18,
+ },
+});
diff --git a/src/components/ai/FluidStreamingText.tsx b/src/components/ai/FluidStreamingText.tsx
index 122b361..dc0e634 100644
--- a/src/components/ai/FluidStreamingText.tsx
+++ b/src/components/ai/FluidStreamingText.tsx
@@ -84,15 +84,26 @@ export const FluidStreamingText: React.FC = ({
cursorFade.setValue(1);
}
- // Continue streaming words to completion
+ // Continue streaming words to completion with smooth token cadence
if (displayedLength < content.length) {
const timer = setTimeout(() => {
setDisplayedLength((prev) => {
if (prev >= content.length) return prev;
- // Advance by 1 to 2 words per tick (~8-15 characters)
- const nextSpace = content.indexOf(' ', prev + 6);
- const nextTarget = nextSpace === -1 ? content.length : nextSpace + 1;
- return Math.min(content.length, Math.max(prev + 4, nextTarget));
+ // Advance smoothly to next whitespace or punctuation boundary
+ const nextSpace = content.indexOf(' ', prev + 1);
+ const nextNewline = content.indexOf('\n', prev + 1);
+ let target = -1;
+ if (nextSpace !== -1 && nextNewline !== -1) {
+ target = Math.min(nextSpace, nextNewline);
+ } else if (nextSpace !== -1) {
+ target = nextSpace;
+ } else if (nextNewline !== -1) {
+ target = nextNewline;
+ }
+ if (target === -1 || target > prev + 24) {
+ return Math.min(content.length, prev + 12);
+ }
+ return target + 1;
});
}, speedMs);
@@ -129,11 +140,11 @@ const styles = StyleSheet.create({
position: 'relative',
},
claudeCursor: {
- width: 6,
- height: 16,
- borderRadius: 2,
+ width: 5,
+ height: 14,
+ borderRadius: 1.5,
backgroundColor: '#38BDF8',
- marginTop: 4,
+ marginTop: 2,
marginLeft: 2,
},
});
diff --git a/src/components/ai/PulsingDots.tsx b/src/components/ai/PulsingDots.tsx
new file mode 100644
index 0000000..0f7100f
--- /dev/null
+++ b/src/components/ai/PulsingDots.tsx
@@ -0,0 +1,135 @@
+import React, { useEffect, useRef } from 'react';
+import { View, StyleSheet, Animated, Easing } from 'react-native';
+
+export interface PulsingDotsProps {
+ color?: string;
+ size?: number;
+}
+
+export const PulsingDots: React.FC = ({
+ color = '#38BDF8',
+ size = 5,
+}) => {
+ const dot1 = useRef(new Animated.Value(0.3)).current;
+ const dot2 = useRef(new Animated.Value(0.3)).current;
+ const dot3 = useRef(new Animated.Value(0.3)).current;
+
+ useEffect(() => {
+ const createAnim = (val: Animated.Value, delay: number) => {
+ return Animated.loop(
+ Animated.sequence([
+ Animated.delay(delay),
+ Animated.timing(val, {
+ toValue: 1,
+ duration: 400,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ Animated.timing(val, {
+ toValue: 0.3,
+ duration: 400,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ Animated.delay(800 - delay),
+ ])
+ );
+ };
+
+ const anim1 = createAnim(dot1, 0);
+ const anim2 = createAnim(dot2, 200);
+ const anim3 = createAnim(dot3, 400);
+
+ anim1.start();
+ anim2.start();
+ anim3.start();
+
+ return () => {
+ anim1.stop();
+ anim2.stop();
+ anim3.stop();
+ };
+ }, [dot1, dot2, dot3]);
+
+ return (
+
+
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ paddingVertical: 12,
+ paddingHorizontal: 4,
+ },
+ dot: {
+ shadowColor: '#38BDF8',
+ shadowOffset: { width: 0, height: 0 },
+ shadowOpacity: 0.8,
+ shadowRadius: 6,
+ elevation: 4,
+ },
+});
diff --git a/src/components/animations/AmbientBottomGlow.tsx b/src/components/animations/AmbientBottomGlow.tsx
new file mode 100644
index 0000000..ccdc7d4
--- /dev/null
+++ b/src/components/animations/AmbientBottomGlow.tsx
@@ -0,0 +1,42 @@
+import React from 'react';
+import { StyleSheet, View, useWindowDimensions } from 'react-native';
+import Svg, { Defs, RadialGradient, Stop, Rect } from 'react-native-svg';
+
+export const AmbientBottomGlow: React.FC = () => {
+ const { width } = useWindowDimensions();
+ const height = 360;
+
+ return (
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ position: 'absolute',
+ bottom: 0,
+ left: 0,
+ right: 0,
+ zIndex: 0,
+ },
+});
diff --git a/src/components/animations/AuraWavesVisualizer.tsx b/src/components/animations/AuraWavesVisualizer.tsx
new file mode 100644
index 0000000..4901d20
--- /dev/null
+++ b/src/components/animations/AuraWavesVisualizer.tsx
@@ -0,0 +1,525 @@
+/**
+ * AMBIENT HOLOGRAPHIC AURA WAVES & VISOR VISUALIZER
+ *
+ * Implements the 6-layer cognitive motion architecture:
+ * 1. Ambient Holographic Aura Waves (smooth pulsing cyan/teal radial gradient aura)
+ * 2. Holographic Visor Scanline (thinking/searching sweep animation)
+ * 3. Analytical Lens with Pulsing Focus
+ * 4. Multi-Frequency Wave Equalizer Bars
+ * 5. Microphone Soundwave Pulse Waves
+ * 6. Reasoning Shimmer Wave
+ *
+ * Works seamlessly across iOS, Android, and Web using standard React Native Animated & SVG.
+ */
+
+import React, { useEffect, useRef } from 'react';
+import {
+ StyleSheet,
+ View,
+ Animated,
+ Easing,
+ Platform,
+ useWindowDimensions,
+} from 'react-native';
+import Svg, {
+ Defs,
+ RadialGradient,
+ LinearGradient,
+ Stop,
+ Rect,
+ Circle,
+ Line,
+ G,
+} from 'react-native-svg';
+
+export interface AuraWavesVisualizerProps {
+ isProcessing: boolean;
+ isThinking?: boolean;
+ isStreaming?: boolean;
+ height?: number;
+}
+
+export const AuraWavesVisualizer: React.FC = ({
+ isProcessing,
+ isThinking = false,
+ isStreaming = false,
+ height = 130,
+}) => {
+ const { width: windowWidth } = useWindowDimensions();
+ const activeWidth = Math.min(windowWidth, 900);
+
+ // 1. Ambient Aura Scale and Opacity
+ const auraScale = useRef(new Animated.Value(1.0)).current;
+ const auraOpacity = useRef(new Animated.Value(0.12)).current;
+
+ // 2. Visor Scanline Sweep Y Position
+ const scanlineY = useRef(new Animated.Value(15)).current;
+
+ // 3. Analytical Lens Scale and Opacity
+ const lensScale = useRef(new Animated.Value(0.85)).current;
+ const lensOpacity = useRef(new Animated.Value(0.55)).current;
+
+ // 4. Equalizer Bars Height Interpolations
+ const bar1 = useRef(new Animated.Value(12)).current;
+ const bar2 = useRef(new Animated.Value(24)).current;
+ const bar3 = useRef(new Animated.Value(32)).current;
+ const bar4 = useRef(new Animated.Value(10)).current;
+
+ // 5. Soundwave Pulse Concentric Rings
+ const waveRadius = useRef(new Animated.Value(0)).current;
+ const waveOpacity = useRef(new Animated.Value(0.8)).current;
+
+ // Master visibility fade
+ const containerOpacity = useRef(new Animated.Value(isProcessing ? 1 : 0)).current;
+
+ // Handle processing transition
+ useEffect(() => {
+ Animated.timing(containerOpacity, {
+ toValue: isProcessing ? 1 : 0,
+ duration: 350,
+ easing: Easing.out(Easing.cubic),
+ useNativeDriver: true,
+ }).start();
+ }, [isProcessing, containerOpacity]);
+
+ // Dynamic Aura Waves Loop
+ useEffect(() => {
+ let auraLoop: Animated.CompositeAnimation | null = null;
+ if (isProcessing) {
+ auraLoop = Animated.loop(
+ Animated.parallel([
+ Animated.sequence([
+ Animated.timing(auraScale, {
+ toValue: 1.08,
+ duration: 850,
+ easing: Easing.inOut(Easing.sin),
+ useNativeDriver: true,
+ }),
+ Animated.timing(auraScale, {
+ toValue: 1.0,
+ duration: 850,
+ easing: Easing.inOut(Easing.sin),
+ useNativeDriver: true,
+ }),
+ ]),
+ Animated.sequence([
+ Animated.timing(auraOpacity, {
+ toValue: 0.65,
+ duration: 850,
+ easing: Easing.inOut(Easing.sin),
+ useNativeDriver: true,
+ }),
+ Animated.timing(auraOpacity, {
+ toValue: 0.35,
+ duration: 850,
+ easing: Easing.inOut(Easing.sin),
+ useNativeDriver: true,
+ }),
+ ]),
+ ])
+ );
+ auraLoop.start();
+ } else {
+ auraScale.setValue(1.0);
+ auraOpacity.setValue(0.1);
+ }
+
+ return () => {
+ if (auraLoop) auraLoop.stop();
+ };
+ }, [isProcessing, auraScale, auraOpacity]);
+
+ // Holographic Visor Scanline Sweep Loop
+ useEffect(() => {
+ let scanLoop: Animated.CompositeAnimation | null = null;
+ if (isProcessing) {
+ scanLoop = Animated.loop(
+ Animated.sequence([
+ Animated.timing(scanlineY, {
+ toValue: height - 20,
+ duration: 1900,
+ easing: Easing.linear,
+ useNativeDriver: true,
+ }),
+ Animated.timing(scanlineY, {
+ toValue: 15,
+ duration: 1900,
+ easing: Easing.linear,
+ useNativeDriver: true,
+ }),
+ ])
+ );
+ scanLoop.start();
+ } else {
+ scanlineY.setValue(15);
+ }
+
+ return () => {
+ if (scanLoop) scanLoop.stop();
+ };
+ }, [isProcessing, height, scanlineY]);
+
+ // Analytical Lens Pulsing Focus Loop
+ useEffect(() => {
+ let lensLoop: Animated.CompositeAnimation | null = null;
+ if (isProcessing) {
+ lensLoop = Animated.loop(
+ Animated.parallel([
+ Animated.sequence([
+ Animated.timing(lensScale, {
+ toValue: 1.18,
+ duration: 575,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ Animated.timing(lensScale, {
+ toValue: 0.85,
+ duration: 575,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ ]),
+ Animated.sequence([
+ Animated.timing(lensOpacity, {
+ toValue: 1.0,
+ duration: 575,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ Animated.timing(lensOpacity, {
+ toValue: 0.55,
+ duration: 575,
+ easing: Easing.inOut(Easing.ease),
+ useNativeDriver: true,
+ }),
+ ]),
+ ])
+ );
+ lensLoop.start();
+ } else {
+ lensScale.setValue(1.0);
+ lensOpacity.setValue(0.5);
+ }
+
+ return () => {
+ if (lensLoop) lensLoop.stop();
+ };
+ }, [isProcessing, lensScale, lensOpacity]);
+
+ // Multi-Frequency Equalizer Bars Animation Loop
+ useEffect(() => {
+ let eqLoop: Animated.CompositeAnimation | null = null;
+ if (isProcessing) {
+ eqLoop = Animated.loop(
+ Animated.parallel([
+ Animated.sequence([
+ Animated.timing(bar1, { toValue: 36, duration: 400, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar1, { toValue: 18, duration: 200, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar1, { toValue: 12, duration: 200, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(100),
+ Animated.timing(bar2, { toValue: 48, duration: 375, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar2, { toValue: 28, duration: 175, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar2, { toValue: 24, duration: 200, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(200),
+ Animated.timing(bar3, { toValue: 16, duration: 225, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar3, { toValue: 44, duration: 425, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar3, { toValue: 32, duration: 200, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(300),
+ Animated.timing(bar4, { toValue: 24, duration: 350, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar4, { toValue: 14, duration: 150, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(bar4, { toValue: 10, duration: 200, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ ])
+ );
+ eqLoop.start();
+ } else {
+ bar1.setValue(12);
+ bar2.setValue(24);
+ bar3.setValue(32);
+ bar4.setValue(10);
+ }
+
+ return () => {
+ if (eqLoop) eqLoop.stop();
+ };
+ }, [isProcessing, bar1, bar2, bar3, bar4]);
+
+ // Soundwave Concentric Pulse Loop
+ useEffect(() => {
+ let waveLoop: Animated.CompositeAnimation | null = null;
+ if (isProcessing) {
+ waveLoop = Animated.loop(
+ Animated.parallel([
+ Animated.timing(waveRadius, {
+ toValue: 1,
+ duration: 1700,
+ easing: Easing.out(Easing.ease),
+ useNativeDriver: true,
+ }),
+ Animated.timing(waveOpacity, {
+ toValue: 0,
+ duration: 1700,
+ easing: Easing.out(Easing.ease),
+ useNativeDriver: true,
+ }),
+ ])
+ );
+ waveLoop.start();
+ } else {
+ waveRadius.setValue(0);
+ waveOpacity.setValue(0);
+ }
+
+ return () => {
+ if (waveLoop) waveLoop.stop();
+ };
+ }, [isProcessing, waveRadius, waveOpacity]);
+
+ if (!isProcessing) {
+ return null;
+ }
+
+ const waveScale1 = waveRadius.interpolate({
+ inputRange: [0, 1],
+ outputRange: [1, 2.8],
+ });
+
+ const waveScale2 = waveRadius.interpolate({
+ inputRange: [0, 1],
+ outputRange: [0.8, 2.2],
+ });
+
+ return (
+
+ {/* 1. Ambient Holographic Aura Waves (Radial Gradient Glow) */}
+
+
+
+
+ {/* 2. Holographic Visor Scanline Sweep */}
+
+
+
+
+ {/* 3 & 4. Analytical Lens & Multi-Frequency Wave Equalizer Bars */}
+
+ {/* Analytical Lens with Pulsing Focus */}
+
+
+
+
+
+
+
+
+ {/* Multi-Frequency Wave Equalizer Bars */}
+
+
+
+
+
+
+
+ {/* 5. Concentric Soundwave Pulse Rings */}
+
+
+
+
+
+
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ zIndex: 10,
+ overflow: 'hidden',
+ backgroundColor: 'transparent',
+ },
+ scanlineContainer: {
+ position: 'absolute',
+ left: 0,
+ right: 0,
+ height: 4,
+ shadowColor: '#10B981',
+ shadowOffset: { width: 0, height: 0 },
+ shadowOpacity: 0.8,
+ shadowRadius: 8,
+ },
+ hudOverlayRow: {
+ position: 'absolute',
+ top: 14,
+ right: 20,
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 16,
+ },
+ lensContainer: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ lensOuterRing: {
+ width: 26,
+ height: 26,
+ borderRadius: 8,
+ backgroundColor: 'rgba(255, 255, 255, 0.95)',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ lensInnerDark: {
+ width: 20,
+ height: 20,
+ borderRadius: 6,
+ backgroundColor: '#04120C',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ lensPupil: {
+ width: 8,
+ height: 8,
+ borderRadius: 4,
+ backgroundColor: '#2DD4BF',
+ shadowColor: '#2DD4BF',
+ shadowOffset: { width: 0, height: 0 },
+ shadowOpacity: 0.9,
+ shadowRadius: 6,
+ },
+ equalizerRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ height: 36,
+ gap: 3.5,
+ },
+ eqBar: {
+ width: 3.5,
+ borderRadius: 2,
+ backgroundColor: '#FFFFFF',
+ shadowColor: '#2DD4BF',
+ shadowOffset: { width: 0, height: 0 },
+ shadowOpacity: 0.6,
+ shadowRadius: 4,
+ },
+ micPulseContainer: {
+ width: 28,
+ height: 28,
+ alignItems: 'center',
+ justifyContent: 'center',
+ position: 'relative',
+ },
+ pulseRing: {
+ position: 'absolute',
+ width: 14,
+ height: 14,
+ borderRadius: 7,
+ borderWidth: 1.5,
+ },
+ pulseCoreDot: {
+ width: 6,
+ height: 6,
+ borderRadius: 3,
+ backgroundColor: '#10B981',
+ },
+});
diff --git a/src/components/animations/ClaudeThinkingIndicator.tsx b/src/components/animations/ClaudeThinkingIndicator.tsx
index 2abfcef..18e5e05 100644
--- a/src/components/animations/ClaudeThinkingIndicator.tsx
+++ b/src/components/animations/ClaudeThinkingIndicator.tsx
@@ -60,6 +60,12 @@ export function ClaudeThinkingIndicator({
const wordFadeAnim = useRef(new Animated.Value(1)).current;
const expandAnim = useRef(new Animated.Value(isExpanded ? 1 : 0)).current;
+ // Multi-frequency wave equalizer bars
+ const eqBar1 = useRef(new Animated.Value(5)).current;
+ const eqBar2 = useRef(new Animated.Value(9)).current;
+ const eqBar3 = useRef(new Animated.Value(12)).current;
+ const eqBar4 = useRef(new Animated.Value(4)).current;
+
const [activeWordIndex, setActiveWordIndex] = useState(0);
const [reduceMotion, setReduceMotion] = useState(false);
const [shouldRenderBody, setShouldRenderBody] = useState(isExpanded);
@@ -138,6 +144,45 @@ export function ClaudeThinkingIndicator({
};
}, [isThinking, pulseAnim, scaleAnim, reduceMotion]);
+ // Multi-frequency wave equalizer bars loop
+ useEffect(() => {
+ let eqLoop: Animated.CompositeAnimation | null = null;
+ if (isThinking && !reduceMotion) {
+ eqLoop = Animated.loop(
+ Animated.parallel([
+ Animated.sequence([
+ Animated.timing(eqBar1, { toValue: 12, duration: 400, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(eqBar1, { toValue: 4, duration: 400, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(100),
+ Animated.timing(eqBar2, { toValue: 16, duration: 375, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(eqBar2, { toValue: 6, duration: 375, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(200),
+ Animated.timing(eqBar3, { toValue: 14, duration: 325, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(eqBar3, { toValue: 5, duration: 325, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ Animated.sequence([
+ Animated.delay(150),
+ Animated.timing(eqBar4, { toValue: 10, duration: 425, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ Animated.timing(eqBar4, { toValue: 3, duration: 425, easing: Easing.inOut(Easing.sin), useNativeDriver: false }),
+ ]),
+ ])
+ );
+ eqLoop.start();
+ } else {
+ eqBar1.setValue(5);
+ eqBar2.setValue(9);
+ eqBar3.setValue(12);
+ eqBar4.setValue(4);
+ }
+ return () => {
+ if (eqLoop) eqLoop.stop();
+ };
+ }, [isThinking, eqBar1, eqBar2, eqBar3, eqBar4, reduceMotion]);
+
// Cycle thinking words smoothly
useEffect(() => {
let wordInterval: any = null;
@@ -197,16 +242,25 @@ export function ClaudeThinkingIndicator({
>
{isThinking ? (
- /* Soft Pulsing Amber Dot */
-
+
+ {/* Soft Pulsing Dot */}
+
+ {/* Multi-Frequency Wave Equalizer Bars */}
+
+
+
+
+
+
+
) : null}
{isThinking ? (
@@ -347,6 +401,23 @@ const styles = StyleSheet.create({
alignItems: 'center',
gap: 6,
},
+ thinkingIndicatorGroup: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 5,
+ },
+ miniEqualizerRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ height: 16,
+ gap: 2,
+ marginRight: 2,
+ },
+ miniEqBar: {
+ width: 2.2,
+ borderRadius: 1,
+ backgroundColor: '#2DD4BF',
+ },
thinkingDot: {
width: 7,
height: 7,
diff --git a/src/components/animations/index.ts b/src/components/animations/index.ts
index 160adee..ebee724 100644
--- a/src/components/animations/index.ts
+++ b/src/components/animations/index.ts
@@ -1,3 +1,5 @@
export * from './AnimatedProcessingIcon';
export * from './ExecutiveProcessingModal';
export * from './ShimmerSkeleton';
+export * from './ClaudeThinkingIndicator';
+export * from './AuraWavesVisualizer';
diff --git a/src/components/navigation/SearchableSideDrawer.tsx b/src/components/navigation/SearchableSideDrawer.tsx
index 231bfb6..1750bf7 100644
--- a/src/components/navigation/SearchableSideDrawer.tsx
+++ b/src/components/navigation/SearchableSideDrawer.tsx
@@ -93,7 +93,7 @@ export const DRAWER_GROUPS: DrawerGroup[] = [
items: [
{ id: 'create_doc', label: 'Create Document', route: '/document/templates?type=invoice', icon: FilePlus, keywords: ['new', 'invoice', 'gst', 'bill', 'order', 'document'] },
{ id: 'doc_library', label: 'Document Library', route: '/(tabs)/documents', icon: FolderOpen, keywords: ['all', 'files', 'records', 'history', 'drafts', 'invoices', 'receipts'] },
- { id: 'template_studio', label: 'Template Studio', route: '/document/templates?type=invoice', icon: Palette, badge: 'PRO', keywords: ['design', 'brand', 'rule 46', 'layouts', 'templates', 'studio'] },
+ { id: 'template_studio', label: 'Template Studio', route: '/templates/studio', icon: Palette, keywords: ['design', 'brand', 'rule 46', 'layouts', 'templates', 'studio'] },
{ id: 'custom_docs', label: 'Custom Document Builder', route: '/templates/create-type', icon: Sparkles, keywords: ['builder', 'creator', 'custom', 'schema', 'type'] },
],
},
@@ -109,15 +109,15 @@ export const DRAWER_GROUPS: DrawerGroup[] = [
title: 'BUSINESS WORK',
items: [
{ id: 'inventory_catalog', label: 'Item Catalog & Work', route: '/(tabs)/money', icon: Package, keywords: ['catalog', 'products', 'services', 'hsn', 'rates', 'pricing'] },
- { id: 'expenses', label: 'Expense Records', route: '/expenses/index', icon: Receipt, keywords: ['spending', 'costs', 'bills', 'outflows', 'receipts'] },
+ { id: 'expenses', label: 'Expense Records', route: '/expenses', icon: Receipt, keywords: ['spending', 'costs', 'bills', 'outflows', 'receipts'] },
],
},
{
id: 'finance',
title: 'FINANCE',
items: [
- { id: 'collections', label: 'Collections Hub', route: '/collections/index', icon: Wallet, badge: 'AUTO', keywords: ['overdue', 'aging', 'reminders', 'receivables', 'collections'] },
- { id: 'reports', label: 'Financial Reports & Tax', route: '/reports/index', icon: BarChart3, keywords: ['analytics', 'p&l', 'gst', 'summary', 'cashflow', 'tax'] },
+ { id: 'collections', label: 'Collections Hub', route: '/collections', icon: Wallet, keywords: ['overdue', 'aging', 'reminders', 'receivables', 'collections'] },
+ { id: 'reports', label: 'Financial Reports & Tax', route: '/reports', icon: BarChart3, keywords: ['analytics', 'p&l', 'gst', 'summary', 'cashflow', 'tax'] },
{ id: 'payment_settings', label: 'Payment Gateways & UPI', route: '/settings/payments', icon: QrCode, keywords: ['qr', 'vpa', 'gateway', 'razorpay', 'cashfree', 'upi'] },
],
},
diff --git a/src/components/security/LockChallengeScreen.tsx b/src/components/security/LockChallengeScreen.tsx
index efcbd19..34ebc3b 100644
--- a/src/components/security/LockChallengeScreen.tsx
+++ b/src/components/security/LockChallengeScreen.tsx
@@ -4,7 +4,7 @@
* TalkBack-compliant accessibility and custom numeric keypad.
*/
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
import {
StyleSheet,
View,
@@ -20,6 +20,7 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { Lock, Delete } from 'lucide-react-native';
import { colors, spacing, radii, typography, MIN_TOUCH_TARGET, MAX_CONTENT_WIDTH } from '../../design/tokens';
import { useSecurity } from '../../services/security/SecurityContext';
+import { SecurityService } from '../../services/security/SecurityService';
export function LockChallengeScreen() {
const security = useSecurity();
@@ -30,9 +31,26 @@ export function LockChallengeScreen() {
const [errorMsg, setErrorMsg] = useState('');
const [isVerifying, setIsVerifying] = useState(false);
+ useEffect(() => {
+ async function checkLockout() {
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Too many failed attempts. Locked out for ${remainingSec}s.`);
+ }
+ }
+ checkLockout();
+ }, []);
+
const handleKeyPress = async (digit: string) => {
if (isVerifying || pin.length >= 6) return;
setErrorMsg('');
+
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Locked out. Try again in ${remainingSec}s.`);
+ return;
+ }
+
const newPin = pin + digit;
setPin(newPin);
@@ -41,9 +59,14 @@ export function LockChallengeScreen() {
setIsVerifying(true);
const success = await security.unlockSessionAsync(newPin);
if (!success) {
- if (newPin.length === 6) {
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Locked out for ${remainingSec}s.`);
+ setPin('');
+ } else if (newPin.length === 6) {
Vibration.vibrate(200);
- setErrorMsg('Incorrect Master PIN.');
+ const attempts = await SecurityService.getFailedAttempts();
+ setErrorMsg(`Incorrect Master PIN (${attempts}/5).`);
setPin('');
}
}
@@ -63,11 +86,24 @@ export function LockChallengeScreen() {
setErrorMsg('PIN must be at least 4 digits.');
return;
}
+
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Locked out for ${remainingSec}s.`);
+ return;
+ }
+
setIsVerifying(true);
const success = await security.unlockSessionAsync(pin);
if (!success) {
Vibration.vibrate(200);
- setErrorMsg('Incorrect Master PIN.');
+ if (await SecurityService.isLockedOut()) {
+ const remainingSec = Math.ceil((await SecurityService.getLockoutRemainingMs()) / 1000);
+ setErrorMsg(`Too many failed attempts. Locked out for ${remainingSec}s.`);
+ } else {
+ const attempts = await SecurityService.getFailedAttempts();
+ setErrorMsg(`Incorrect Master PIN (${attempts}/5).`);
+ }
setPin('');
}
setIsVerifying(false);
diff --git a/src/data/repositories/UniversalDocumentRepository.ts b/src/data/repositories/UniversalDocumentRepository.ts
index 27c67c7..3677bda 100644
--- a/src/data/repositories/UniversalDocumentRepository.ts
+++ b/src/data/repositories/UniversalDocumentRepository.ts
@@ -301,7 +301,13 @@ export class UniversalDocumentRepository {
id, business_profile_id, type_id, doc_class, document_number, title,
status, issue_date, party_name, party_details_json, content_json,
template_code, branding_json, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ document_number = excluded.document_number, title = excluded.title,
+ status = excluded.status, issue_date = excluded.issue_date,
+ party_name = excluded.party_name, party_details_json = excluded.party_details_json,
+ content_json = excluded.content_json, template_code = excluded.template_code,
+ branding_json = excluded.branding_json, updated_at = excluded.updated_at;`,
[
id,
savedInstance.businessProfileId,
diff --git a/src/domain/documents/universal/SystemSchemas.ts b/src/domain/documents/universal/SystemSchemas.ts
index e81c7a3..434e48f 100644
--- a/src/domain/documents/universal/SystemSchemas.ts
+++ b/src/domain/documents/universal/SystemSchemas.ts
@@ -3000,5 +3000,29 @@ export const SYSTEM_SCHEMAS: readonly UniversalDocumentSchema[] = [
authorizedSignatoryLabel: "Chief Procurement Officer",
recipientAcceptanceLabel: "Vendor Acceptance & Confirmation"
}
- }
+ },
+ {
+ id: 'schema_resume',
+ code: 'resume',
+ name: 'Resume',
+ docClass: 'class_b_administrative',
+ category: 'hr_employment',
+ description: 'Single-column rΓ©sumΓ© using the candidateβs own work history and skills.',
+ icon: 'file-text',
+ defaultTemplate: 'universal',
+ isSystem: true,
+ footerConfig: { showSignatures: false, showTerms: false, showNotes: false },
+ sections: [
+ { id: 'contact', title: 'Candidate', fields: [
+ { id: 'candidate_name', label: 'Candidate Name', type: 'text', required: true },
+ { id: 'candidate_email', label: 'Email', type: 'text' },
+ { id: 'job_title', label: 'Target Role', type: 'text', required: true },
+ ] },
+ { id: 'qualifications', title: 'Qualifications', fields: [
+ { id: 'experience', label: 'Work Experience or Projects', type: 'textarea', required: true },
+ { id: 'skills', label: 'Skills', type: 'textarea', required: true },
+ { id: 'education', label: 'Education', type: 'textarea' },
+ ] },
+ ],
+ },
];
diff --git a/src/domain/features/FeatureRegistry.ts b/src/domain/features/FeatureRegistry.ts
index 5bd3632..9d72f66 100644
--- a/src/domain/features/FeatureRegistry.ts
+++ b/src/domain/features/FeatureRegistry.ts
@@ -112,7 +112,7 @@ export const FEATURE_REGISTRY: FeatureCapability[] = [
name: 'Customers & Clients',
description: 'Customer directory, balances, contact information, and billing history',
icon: 'customers',
- route: '/(tabs)/customers',
+ route: '/(tabs)/contacts',
availability: 'ready',
businessRelevance: {
freelancer: 95,
diff --git a/src/domain/workspace/WorkspaceResolver.ts b/src/domain/workspace/WorkspaceResolver.ts
index b9ac911..733e53c 100644
--- a/src/domain/workspace/WorkspaceResolver.ts
+++ b/src/domain/workspace/WorkspaceResolver.ts
@@ -196,7 +196,7 @@ export class WorkspaceResolver {
id: 'customers',
name: 'Customers',
icon: 'customers',
- route: '/(tabs)/customers',
+ route: '/(tabs)/contacts',
description: 'Customer directory and history',
});
list.push({
@@ -235,7 +235,7 @@ export class WorkspaceResolver {
id: 'customers',
name: 'Clients',
icon: 'customers',
- route: '/(tabs)/customers',
+ route: '/(tabs)/contacts',
description: 'Client ledger & accounts',
});
return list;
@@ -262,7 +262,7 @@ export class WorkspaceResolver {
id: 'customers',
name: 'Clients & Customers',
icon: 'customers',
- route: '/(tabs)/customers',
+ route: '/(tabs)/contacts',
description: 'Customer balances and history',
});
if (enabledFeatures.includes('expenses')) {
diff --git a/src/services/ai/AiConfigService.ts b/src/services/ai/AiConfigService.ts
index 8fbef2f..8fa1530 100644
--- a/src/services/ai/AiConfigService.ts
+++ b/src/services/ai/AiConfigService.ts
@@ -26,7 +26,7 @@ export interface AiConfig {
isReady: boolean;
}
-export const DEFAULT_GROQ_KEY = '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';
+export const DEFAULT_GROQ_KEY = '';
export const MAX_UNIVERSAL_KEY_DOCS = 7;
export const PROVIDER_MODELS: Record> = {
@@ -144,7 +144,7 @@ export class AiConfigService {
provider,
apiKey,
model,
- isReady: provider === 'offline_heuristic' || Boolean(apiKey.trim()) || (provider === 'groq' && Boolean(DEFAULT_GROQ_KEY)),
+ isReady: provider === 'offline_heuristic' || Boolean(apiKey && apiKey.trim().length > 0),
};
}
@@ -186,10 +186,13 @@ export class AiConfigService {
* Performs live healthcheck probe with the configured key
*/
static async testConnection(apiKey?: string, provider: AiProvider = 'groq'): Promise<{ success: boolean; message: string }> {
- const key = apiKey !== undefined ? apiKey : ((await this.getStorageItem(AI_API_KEY)) || (provider === 'groq' ? DEFAULT_GROQ_KEY : ''));
+ const key = apiKey !== undefined ? apiKey.trim() : ((await this.getStorageItem(AI_API_KEY)) || '');
if (!key && provider !== 'offline_heuristic') {
- return { success: false, message: 'API Key is missing.' };
+ return {
+ success: false,
+ message: 'API Key is missing. Please enter your provider API key (BYOK) or switch to Offline mode.',
+ };
}
if (provider === 'offline_heuristic') {
diff --git a/src/services/ai/AiDocumentAgent.ts b/src/services/ai/AiDocumentAgent.ts
index 4bbaacb..9d69db2 100644
--- a/src/services/ai/AiDocumentAgent.ts
+++ b/src/services/ai/AiDocumentAgent.ts
@@ -12,7 +12,7 @@
* 7. Real-time iterative chat refinement ("change basic to 65000", "add 10% discount").
*/
-import { AiConfigService, DEFAULT_GROQ_KEY, MAX_UNIVERSAL_KEY_DOCS } from './AiConfigService';
+import { AiConfigService } from './AiConfigService';
import { AiLocalSqlContext } from './AiLocalSqlContext';
import { AiRagRegistry } from './AiRagRegistry';
import { DocumentTypeRegistry } from '../../domain/documents/DocumentTypeRegistry';
@@ -23,6 +23,7 @@ import { BusinessProfileRepository } from '../../data/repositories/BusinessProfi
import { DatabaseManager } from '../../data/database/DatabaseManager';
import { DocumentType } from '../../domain/documents/types';
import { createMoney, formatMoney } from '../../domain/money/Money';
+import { UniversalAgentEngine } from './UniversalAgentEngine';
import {
ChatInteractiveQuestion,
ChatQuestionOption,
@@ -787,13 +788,11 @@ export class AiDocumentAgent {
}
}
- const effectiveApiKey = config.apiKey || (config.provider === 'groq' ? DEFAULT_GROQ_KEY : '');
- const isUsingUniversal = config.provider === 'groq' && (!config.apiKey || config.apiKey.trim() === DEFAULT_GROQ_KEY);
- const universalLimit = await AiConfigService.checkUniversalLimit();
- const isOverUniversalLimit = isUsingUniversal && universalLimit.isLimited;
+ const effectiveApiKey = config.apiKey ? config.apiKey.trim() : '';
// 1. Live Cloud Execution on Groq LPU (GPT-OSS 120B Reasoning with Native Tool Calling)
- if (effectiveApiKey && config.provider === 'groq' && !isOverUniversalLimit) {
+ // Strictly requires an explicit user-configured API key (BYOK); never silently sends dummy or hardcoded keys.
+ if (effectiveApiKey && config.provider === 'groq') {
try {
const formattedContext = AiLocalSqlContext.formatContextForSystemPrompt(localContext);
const activeDraftStr = this.serializeDraftForPrompt(activeDraft);
@@ -924,9 +923,6 @@ CORE AGENTIC INVARIANTS:
}
if (allDrafts.length > 0) {
- if (isUsingUniversal) {
- await AiConfigService.incrementUniversalUsage();
- }
const reasoning = this.buildComprehensiveReasoning(allDrafts, combinedReasoning);
const reply =
combinedReply ||
@@ -1250,9 +1246,6 @@ CORE AGENTIC INVARIANTS:
}
if (rawDraft && rawDraft.docType) {
- if (isUsingUniversal) {
- await AiConfigService.incrementUniversalUsage();
- }
const verified = await this.commitAndVerifyDraft(rawDraft, localContext);
const reasoning = this.synthesizeReasoning(userPrompt, verified);
taskSteps[2] = {
@@ -1281,9 +1274,6 @@ CORE AGENTIC INVARIANTS:
/(?:build|draft|create|generate|make|write|in document|ats|dossier)/i.test(userPrompt);
if (isResumeRequest) {
- if (isUsingUniversal) {
- await AiConfigService.incrementUniversalUsage();
- }
const genResume = this.generateDeterministicDraftForArchetype(
'resume',
userPrompt,
@@ -1376,12 +1366,6 @@ CORE AGENTIC INVARIANTS:
verifiedDrafts.push(v);
}
const verified = verifiedDrafts[0] || null;
- if (verifiedDrafts.length > 0 && isUsingUniversal && !isOverUniversalLimit) {
- await AiConfigService.incrementUniversalUsage();
- }
- if (isOverUniversalLimit) {
- heuristicResult.reply += `\n\n> β‘ **Universal Key Free Preview (7/7 docs used)**: You've reached the free trial limit. Add your free personal Groq API key in **AI Settings (BYOK)** to unlock unlimited ultra-fast AI generation with deep step-by-step reasoning, or continue with 100% offline mode.`;
- }
const trace =
heuristicResult.reasoning ||
(verified ? this.synthesizeReasoning(userPrompt, verified) : 'Local assistant processed query.');
@@ -1730,6 +1714,15 @@ ${userPrompt}
}
if (isQuestion) {
+ const universalAnswer = UniversalAgentEngine.answerBusinessQuestion(prompt, context);
+ if (universalAnswer) {
+ return {
+ reply: universalAnswer.reply,
+ reasoning: universalAnswer.reasoning,
+ draft: null as any,
+ };
+ }
+
if (/gst/i.test(prompt)) {
return {
reply: `**Goods and Services Tax (GST) in India** is governed by the CGST Act 2017.\n\nβ’ Standard commercial B2B invoices apply **18% GST** (9% CGST + 9% SGST intra-state, or 18% IGST inter-state).\nβ’ Concessional rates: **0%**, **5%**, and **12%**.\nβ’ Luxury/de-merit goods: **28%**.\n\nYou can ask me to draft a GST invoice anytime with specific items and rates!`,
@@ -1737,6 +1730,7 @@ ${userPrompt}
draft: null as any,
};
}
+
return {
reply: `I am currently operating in **Offline Local Assistant** mode for **${context?.businessProfile?.name || 'your business'}**.\n\nTo ask open-ended questions with deep neural reasoning, connect to Groq in Settings. For document creation, you can ask me to draft an invoice, salary slip, rent receipt, or job offer directly.`,
reasoning: 'Offline transparency: Reported local mode status without generating fictitious records.',
@@ -1948,7 +1942,8 @@ ${userPrompt}
if (context?.matchedCustomers?.length > 0) {
return context.matchedCustomers[0].name;
}
- return fallback;
+ const universalParty = UniversalAgentEngine.extractPartyName(prompt, history, fallback);
+ return universalParty || fallback;
};
// Helper: Extract items and quantities
@@ -1973,6 +1968,21 @@ ${userPrompt}
return items;
}
+ // Universal natural language multi-pattern extraction for freeform queries
+ const parsedUniversal = UniversalAgentEngine.parseLineItems(prompt, defaultCurrency);
+ if (
+ parsedUniversal.length > 0 &&
+ !(parsedUniversal.length === 1 && parsedUniversal[0].description.includes('Statutory & Commercial Deliverable'))
+ ) {
+ return parsedUniversal.map((p) => ({
+ description: p.description,
+ quantityScaled: p.quantityScaled,
+ unitName: p.unitName,
+ unitPriceMinor: p.unitPriceMinor,
+ hsnSac: p.hsnSac || '998314',
+ }));
+ }
+
const qtyMatch = prompt.match(/(\d+)\s+([a-zA-Z\s]{3,30}?)(?:\s+(?:for|to|with|and|\.|$))/i);
if (qtyMatch && !qtyMatch[2].toLowerCase().includes('percent') && !qtyMatch[2].toLowerCase().includes('gst')) {
const qty = parseInt(qtyMatch[1], 10);
diff --git a/src/services/ai/UniversalAgentEngine.ts b/src/services/ai/UniversalAgentEngine.ts
new file mode 100644
index 0000000..5623e7d
--- /dev/null
+++ b/src/services/ai/UniversalAgentEngine.ts
@@ -0,0 +1,361 @@
+/**
+ * UNIVERSAL AGENT ENGINE β BILLFRAME REASONING & COMMON SENSE CORE
+ *
+ * Provides deep, autonomous cognitive capabilities for Billframe:
+ * 1. Multi-pattern natural language item, rate & quantity extraction for ANY industry or service.
+ * 2. Intelligent counterparty and role resolution across complex conversational phrasing.
+ * 3. Authoritative statutory, accounting, GST, payroll, and business knowledge Q&A.
+ * 4. Contextual domain adaptation (e.g. retail, consulting, healthcare, tech, legal, real estate).
+ * 5. Deterministic integer arithmetic validation to eliminate hallucinated totals.
+ */
+
+import { ParsedDocumentDraft } from './AiDocumentAgent';
+import { AgentChatMessage } from './AiDocumentAgent';
+
+export interface ExtractedLineItem {
+ id: string;
+ description: string;
+ quantityScaled: bigint;
+ unitName: string;
+ unitPriceMinor: bigint;
+ hsnSac?: string;
+ totalMinor: bigint;
+}
+
+export interface ExtractedDocumentIntent {
+ archetypeId: string;
+ docTitle: string;
+ partyName: string;
+ partyRole: string;
+ items: ExtractedLineItem[];
+ currency: string;
+ taxRateBp: bigint;
+ taxLabel: string;
+ discountType: 'none' | 'percentage' | 'fixed';
+ discountValue: bigint;
+ notes?: string;
+ terms?: string;
+ metadata?: Record;
+ reasoning: string;
+}
+
+export class UniversalAgentEngine {
+ /**
+ * Universal natural language line item parser
+ * Handles multi-item lists, rates with units, comma/and conjunctions, and freeform text.
+ */
+ static parseLineItems(prompt: string, defaultCurrency: string = 'INR'): ExtractedLineItem[] {
+ const items: ExtractedLineItem[] = [];
+ const cleanPrompt = prompt.trim();
+
+ // Strategy A: Multi-item list with explicit quantities and prices
+ // Examples: "2 MacBooks at 120000 each", "3 lattes @ 250", "40 hours of cloud consulting at $150/hr"
+ const explicitRegex =
+ /(\d+(?:\.\d+)?)\s*(?:units?|pcs?|items?|hours?|hrs?|days?|months?|sets?|boxes?|kgs?)?\s+(?:of\s+)?([A-Za-z0-9\s\-\.\'\/\(\)]+?)\s+(?:at|@|for|rate)\s+(?:[\$βΉΒ£β¬]|rs\.?\s*|usd\s*|inr\s*)?(\d[\d,]*)(?:\s*(?:\/|per|each|\.|$))/gi;
+
+ let match: RegExpExecArray | null;
+ while ((match = explicitRegex.exec(cleanPrompt)) !== null) {
+ const qty = parseFloat(match[1]);
+ let desc = match[2].trim();
+ const price = parseFloat(match[3].replace(/,/g, ''));
+
+ // Filter out leading action verbs and prepositions
+ desc = desc.replace(/^(?:and|plus|\+|,|i\s+sold|sold|bought|bought\s+for|took)\s+/i, '').trim();
+ // Filter out trailing counterparty preposition e.g. "to Rohan", "for Acme"
+ desc = desc.replace(/\s+(?:to|for)\s+[A-Za-z0-9\s]+$/i, '').trim();
+
+ if (
+ desc.length > 1 &&
+ !/^(?:gst|tax|discount|total|invoice|bill|challan|quote)$/i.test(desc) &&
+ price > 0
+ ) {
+ const unitName = this.inferUnitName(cleanPrompt, desc);
+ const hsnSac = this.inferHsnSac(desc);
+ const qtyScaled = BigInt(Math.round(qty * 10000));
+ const unitPriceMinor = BigInt(Math.round(price * 100));
+ const totalMinor = (qtyScaled * unitPriceMinor) / 10000n;
+
+ items.push({
+ id: `item_${items.length + 1}`,
+ description: this.capitalizeTitle(desc),
+ quantityScaled: qtyScaled,
+ unitName,
+ unitPriceMinor,
+ hsnSac,
+ totalMinor,
+ });
+ }
+ }
+
+ if (items.length > 0) return items;
+
+ // Strategy B: Service / item description followed directly by amount without explicit "at"
+ // Examples: "laptop repair 3500 and screen replacement 4500", "gym membership 12000", "web design 25000"
+ const directPairs = cleanPrompt.matchAll(
+ /(?:^|[\n,;]|\band\b|\bwith\b|\bplus\b|\+)\s*([A-Za-z\s\-\/\(\)]{3,40}?)\s+(?:[\$βΉΒ£β¬]|rs\.?\s*)?(\d[\d,]{2,8})(?:\s*(?:each|\/hr|\/month|\/yr|inr|usd)?)/gi
+ );
+
+ for (const pair of directPairs) {
+ let desc = pair[1].trim();
+ const price = parseFloat(pair[2].replace(/,/g, ''));
+
+ // Clean up leading invoice/bill commands and prepositions
+ desc = desc.replace(/^(?:invoice|bill|draft|create|make)\s+(?:for|of)?\s*/i, '').trim();
+ desc = desc.replace(/^(?:for|to|and|plus|with|\+|,)\s+/i, '').trim();
+ // Clean up trailing counterparty preposition e.g. "for Rahul", "to Acme"
+ desc = desc.replace(/\s+(?:for|to)\s+[A-Za-z0-9\s]+$/i, '').trim();
+ desc = desc.replace(/\s+(?:for|to|dated|with|inr|usd)$/i, '').trim();
+
+ if (
+ desc.length > 2 &&
+ !/^(?:gst|tax|discount|percent|total|invoice|quote|bill|payment|balance|due|tenant|client|vendor)$/i.test(desc) &&
+ price >= 10
+ ) {
+ const unitName = this.inferUnitName(cleanPrompt, desc);
+ const hsnSac = this.inferHsnSac(desc);
+ const qtyScaled = 10000n; // 1 unit
+ const unitPriceMinor = BigInt(Math.round(price * 100));
+ const totalMinor = unitPriceMinor;
+
+ items.push({
+ id: `item_${items.length + 1}`,
+ description: this.capitalizeTitle(desc),
+ quantityScaled: qtyScaled,
+ unitName,
+ unitPriceMinor,
+ hsnSac,
+ totalMinor,
+ });
+ }
+ }
+
+ if (items.length > 0) return items;
+
+ // Strategy C: Single price match with intelligent domain context description
+ const singlePriceMatch = cleanPrompt.match(/(?:[\$βΉΒ£β¬]|rs\.?\s*|usd\s*|inr\s*)(\d[\d,]*)/i) ||
+ cleanPrompt.match(/\b(\d[\d,]{3,8})\b/);
+ const amount = singlePriceMatch ? parseFloat(singlePriceMatch[1].replace(/,/g, '')) : 10000;
+
+ const contextualDesc = this.inferContextualDescription(cleanPrompt);
+ const unitName = this.inferUnitName(cleanPrompt, contextualDesc);
+ const hsnSac = this.inferHsnSac(contextualDesc);
+ const qtyScaled = 10000n;
+ const unitPriceMinor = BigInt(Math.round(amount * 100));
+
+ items.push({
+ id: 'item_1',
+ description: contextualDesc,
+ quantityScaled: qtyScaled,
+ unitName,
+ unitPriceMinor,
+ hsnSac,
+ totalMinor: unitPriceMinor,
+ });
+
+ return items;
+ }
+
+ /**
+ * Extracts counterparty name with deep grammar and conversational awareness
+ */
+ static extractPartyName(
+ prompt: string,
+ history: AgentChatMessage[] = [],
+ fallback: string = 'Valued Client'
+ ): string {
+ const cleanPrompt = prompt.trim();
+
+ // Common noise words to never treat as party names
+ const noiseWords = new Set([
+ 'gst', 'invoice', 'bill', 'tax', 'quote', 'quotation', 'challan', 'receipt',
+ 'salary', 'slip', 'po', 'order', 'resume', 'cv', 'dossier', 'application',
+ 'document', 'item', 'items', 'service', 'services', 'him', 'her', 'them',
+ 'client', 'vendor', 'tenant', 'employee', 'candidate', 'applicant', 'customer',
+ 'reliance', 'acme', 'tata', 'infosys', 'wipro', 'google', 'microsoft'
+ ]);
+
+ // 1. Explicit syntax: "for/to "
+ const forMatch = cleanPrompt.match(
+ /\b(?:for|to|client|vendor|consignee|customer|employee|tenant|candidate|applicant)\s+([A-Za-z0-9\s\.\,\'\-]+?)(?:\s+(?:with|at|on|for|basic|salary|amount|buying|having|dated|\$|βΉ|rs|\d|and\b)|$)/i
+ );
+ if (forMatch && forMatch[1]) {
+ const candidate = this.sanitizePartyName(forMatch[1]);
+ if (candidate && candidate.length > 1) return candidate;
+ }
+
+ // 2. Named corporate patterns: e.g. "Acme Corp", "Zenith Infotech Ltd", "Reliance Industries"
+ const corpMatch = cleanPrompt.match(
+ /\b([A-Z][a-zA-Z0-9]+(?:\s+[A-Z][a-zA-Z0-9]+)*\s+(?:Pvt\s+Ltd|Ltd|Limited|LLC|Inc|Corporation|Corp|Enterprises|Technologies|Infotech|Solutions|Studio|Agencies|Agency|Holdings|LLP))\b/
+ );
+ if (corpMatch && corpMatch[1]) {
+ return corpMatch[1].trim();
+ }
+
+ // 3. Multi-turn history lookback
+ if (history && history.length > 0) {
+ for (let i = history.length - 1; i >= 0; i--) {
+ const content = history[i].content || '';
+ const histMatch =
+ content.match(/\b(?:candidate\s+dossier|resume|cv|dossier|application|document)\s+for\s+([A-Za-z\s\.\,\'\-]+?)(?:\s+(?:applying|targeting|for|as|with|roles?|position|basic|salary|amount|\$|βΉ|rs|\d|and\b|\n)|$)/i) ||
+ content.match(/\b(?:for|to|client|employee|tenant)\s+([A-Za-z\s\.\,\'\-]+?)(?:\s+(?:applying|targeting|for|as|with|roles?|position|basic|salary|amount|\$|βΉ|rs|\d|and\b|\n)|$)/i);
+ if (histMatch && histMatch[1]) {
+ const candidate = this.sanitizePartyName(histMatch[1]);
+ if (candidate && candidate.length > 1) return candidate;
+ }
+
+ // Header match like "# Farhan Noor"
+ const nameHeader = content.match(/(?:^|\n)#*\s*([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b/);
+ if (nameHeader && nameHeader[1] && !nameHeader[1].toLowerCase().includes('billframe')) {
+ return nameHeader[1].trim();
+ }
+ }
+ }
+
+ return fallback;
+ }
+
+ /**
+ * Universal business, tax, GST, accounting, and compliance Q&A knowledge base
+ * Provides deep, comprehensive, common-sense answers with statutory references.
+ */
+ static answerBusinessQuestion(prompt: string, context?: any): { reply: string; reasoning: string } | null {
+ const text = prompt.toLowerCase();
+
+ // 1. Reverse Charge Mechanism (RCM)
+ if (text.includes('reverse charge') || text.includes('rcm')) {
+ return {
+ reply: `### Reverse Charge Mechanism (RCM) under GST\n\nUnder **Section 9(3) and 9(4) of the CGST Act 2017**, the Reverse Charge Mechanism shifts the statutory liability to pay GST from the supplier to the **recipient of goods or services**.\n\n#### Key Scenarios Requiring RCM:\n1. **Goods Transport Agency (GTA)**: Freight charges paid to GTAs where 5% GST is payable by the recipient under RCM.\n2. **Legal Services**: Legal representation and advisory services provided by advocates or senior advocates to business entities.\n3. **Import of Services**: Services received by an Indian business from a foreign vendor without an Indian establishment.\n4. **Director Remuneration**: Sitting fees or professional fees paid to company directors.\n5. **Sponsorship & Security Services**: Provided to registered corporate entities.\n\n#### Operational Rules in Billframe:\nβ’ The supplier must clearly declare **"Reverse Charge: YES"** on the tax invoice.\nβ’ The recipient pays GST via Electronic Cash Ledger and can claim Input Tax Credit (ITC) in the same tax period if used for business furtherance.`,
+ reasoning: 'Statutory compliance engine: Cited Sections 9(3) and 9(4) of CGST Act 2017 with practical RCM invocation scenarios.',
+ };
+ }
+
+ // 2. Input Tax Credit (ITC) & Blocked Credits
+ if (text.includes('input tax credit') || text.includes('itc') || text.includes('blocked credit')) {
+ return {
+ reply: `### Input Tax Credit (ITC) Rules under Indian GST\n\n**Section 16 of the CGST Act** empowers registered taxable persons to claim credit for GST paid on inward supplies used in the course or furtherance of business.\n\n#### 4 Mandatory Conditions to Claim ITC (Section 16(2)):\n1. Possession of a valid **Tax Invoice or Debit Note** issued by the supplier.\n2. Inward supply must be reflected in the buyer\'s **GSTR-2B** (invoice uploaded by vendor in GSTR-1).\n3. Actual receipt of goods or services.\n4. Supplier has paid the tax to the Government and filed GSTR-3B.\n\n#### Blocked Credits (Section 17(5)):\nβ’ Motor vehicles for passenger transport (<13 seats), unless used for transport business.\nβ’ Food, beverages, outdoor catering, health club memberships, and health insurance.\nβ’ Construction or works contracts for immovable property (capitalized).\nβ’ Goods lost, stolen, destroyed, written off, or disposed of as free gifts.`,
+ reasoning: 'Accounting compliance engine: Synthesized Section 16 eligibility criteria and Section 17(5) blocked credit exceptions.',
+ };
+ }
+
+ // 3. Difference between Invoice, Quotation, and Proforma
+ if (
+ (text.includes('difference') || text.includes('compare') || text.includes('vs')) &&
+ (text.includes('proforma') || text.includes('quote') || text.includes('quotation') || text.includes('invoice'))
+ ) {
+ return {
+ reply: `### Invoice vs. Quotation vs. Proforma Invoice\n\n| Document Type | Legal Nature | Tax Obligation | When to Issue |\n| :--- | :--- | :--- | :--- |\n| **Quotation / Estimate** | Non-binding offer | No tax liability | At proposal/pitch stage to quote commercial terms and scope. |\n| **Proforma Invoice** | Preliminary commercial intent | No statutory liability | Pre-payment request; helps the buyer arrange funds or import licenses. |\n| **Tax Invoice** | Binding statutory legal document | **Immediate tax liability** | Upon supply of goods or completion of service (Rule 46). |\n\n#### Practical Guidance in Billframe:\nβ’ Use a **Quotation** to pitch pricing with 15-30 day validity.\nβ’ Convert to **Proforma Invoice** when the client accepts and needs an official advance payment reference.\nβ’ Issue the **Tax Invoice** upon project delivery or milestone clearance to legally record revenue and GST.`,
+ reasoning: 'Commercial document logic: Contrast matrix defining statutory obligations between quotation, proforma, and tax invoice.',
+ };
+ }
+
+ // 4. HSN and SAC Code Requirements
+ if (text.includes('hsn') || text.includes('sac') || text.includes('tariff code')) {
+ return {
+ reply: `### HSN & SAC Code Requirements under CBIC GST\n\nβ’ **HSN (Harmonized System of Nomenclature)**: 6 to 8-digit codes classifying physical goods.\nβ’ **SAC (Services Accounting Code)**: 6-digit codes beginning with **99** classifying commercial services.\n\n#### Mandatory Digit Slabs (CBIC Notification 78/2020):\n1. **Annual Turnover up to βΉ5 Crore**: Minimum **4 digits** on B2B invoices (optional on B2C).\n2. **Annual Turnover above βΉ5 Crore**: Minimum **6 digits** on all B2B and B2C invoices.\n3. **Export & Import Shipments**: Mandatory **8 digits** on all shipping bills.\n\n#### Common Tech & Business Codes:\nβ’ **998314**: IT Design and Development Services (Standard 18% GST)\nβ’ **998311**: IT Consulting and Advisory Services\nβ’ **998361**: Advertising & Photography Services\nβ’ **997212**: Commercial Real Estate Leasing\nβ’ **847130**: Laptops, Computers & Digital Processing Units (18% GST)`,
+ reasoning: 'CBIC statutory classification: Cited Notification 78/2020 turnover thresholds and common commercial SAC codes.',
+ };
+ }
+
+ // 5. E-Invoicing & E-Way Bill Thresholds
+ if (text.includes('e-invoicing') || text.includes('irn') || text.includes('e-way bill') || text.includes('eway bill')) {
+ return {
+ reply: `### E-Invoicing (IRN) & E-Way Bill Compliance\n\n#### 1. E-Invoicing (Invoice Registration Portal):\nβ’ **Mandatory Threshold**: All GST-registered businesses with aggregate annual turnover exceeding **βΉ5 Crore** in any preceding financial year since 2017-18.\nβ’ **Requirement**: B2B invoices and Credit/Debit Notes must be validated on the government IRP to receive a unique 64-character **Invoice Reference Number (IRN)** and signed QR code.\nβ’ **Invoices without IRN are legally invalid** and cannot be used by the buyer to claim ITC.\n\n#### 2. E-Way Bill (CBIC Rule 138):\nβ’ Mandatory for physical movement of goods where consignment value exceeds **βΉ50,000** (inter-state or intra-state in most states).\nβ’ Generated via Form GST EWB-01 prior to dispatch.\nβ’ Valid for 1 day per 200 km for regular cargo.`,
+ reasoning: 'Statutory compliance engine: Outlined βΉ5 Cr e-invoicing mandate and Rule 138 βΉ50,000 e-way bill threshold.',
+ };
+ }
+
+ // 6. House Rent Allowance (HRA) & Rent Receipts under Section 10(13A)
+ if (text.includes('rent receipt') || text.includes('hra') || text.includes('10(13a)') || text.includes('house rent')) {
+ return {
+ reply: `### HRA Exemption & Rent Receipts under Section 10(13A)\n\nSalaried employees can claim income tax exemption on House Rent Allowance under **Section 10(13A) read with Rule 2A** of the Income Tax Rules 1962.\n\n#### Minimum of the Following is Tax-Exempt:\n1. Actual HRA received from employer.\n2. **50% of Basic Salary + DA** (if living in Mumbai, Delhi, Kolkata, Chennai) or **40%** (non-metro).\n3. Rent paid in excess of **10% of Basic Salary + DA**.\n\n#### Statutory Documentation Rules:\nβ’ **Landlord PAN is mandatory** if total annual rent exceeds **βΉ1,00,000** (CBDT Circular 08/2013).\nβ’ If monthly rent exceeds βΉ5,000, each receipt must bear a cancelled **βΉ1 Revenue Stamp**.\nβ’ Receipts must specify property address, rental period, landlord signature, and payment mode (e.g. UPI/Bank Transfer).`,
+ reasoning: 'Tax advisory engine: Synthesized Section 10(13A) Rule 2A HRA exemption formula and CBDT PAN mandate.',
+ };
+ }
+
+ // 7. Statutory Salary Slip Components & Deduction Limits
+ if (text.includes('salary slip') || text.includes('payslip') || text.includes('pf calculation') || text.includes('epf deduction')) {
+ return {
+ reply: `### Statutory Indian Salary Slip Architecture\n\nA legally compliant salary slip in India conforms to the **Payment of Wages Act 1936** and the **Code on Wages 2019**.\n\n#### 1. Earnings Slabs:\nβ’ **Basic Salary**: Typically 40% - 50% of Total CTC.\nβ’ **House Rent Allowance (HRA)**: 40% to 50% of Basic.\nβ’ **Special Allowance / Performance Bonus**: Balancing component of gross remuneration.\n\n#### 2. Statutory Deductions:\nβ’ **EPF (Employees Provident Fund)**: 12% of Basic (capped at βΉ1,800/month if opted on the βΉ15,000 statutory wage ceiling, or full 12% of actual basic).\nβ’ **ESI (Employee State Insurance)**: 0.75% of Gross Wages for employees earning $\\le$ βΉ21,000/month.\nβ’ **Professional Tax (PT)**: State-specific levy (e.g. βΉ200/month in Maharashtra and Karnataka, max βΉ2,500/year).\nβ’ **TDS (Tax Deducted at Source)**: Under Section 192 as per applicable income tax slab.`,
+ reasoning: 'HR statutory engine: Detailed Code on Wages salary architecture with EPF, ESI, and PT parameters.',
+ };
+ }
+
+ // 8. General Open-Ended Commercial / Billing Question Fallback
+ const isGeneralBusinessQuestion =
+ text.startsWith('what is') ||
+ text.startsWith('how to') ||
+ text.startsWith('how do') ||
+ text.startsWith('can i') ||
+ text.startsWith('should i') ||
+ text.startsWith('explain') ||
+ text.endsWith('?');
+
+ if (isGeneralBusinessQuestion && !text.includes('draft') && !text.includes('create') && !text.includes('bill')) {
+ return {
+ reply: `### Billframe Business & Financial Advisory\n\nRegarding your inquiry: **"${prompt.trim()}"**\n\nβ’ **Commercial Principle**: In sound business operations, all financial transactions should be supported by statutory documentation (Tax Invoice, Delivery Challan, or Agreement) to establish legal enforceability and support tax audit reconciliation.\nβ’ **Audit Trail**: Under Section 35(1) of the CGST Act, true and correct accounts of production, inward and outward supply, inventory, and taxes paid must be retained for at least **72 months** from the due date of filing the relevant annual return.\nβ’ **Next Step**: Would you like me to draft a compliant document for this workflow, or look up specific records in your database?`,
+ reasoning: 'Grounded financial reasoning: Synthesized commercial accounting principles and Section 35 audit retention standards.',
+ };
+ }
+
+ return null;
+ }
+
+ // ββ Helper Utilities ββ
+
+ private static inferUnitName(prompt: string, desc: string): string {
+ const text = (prompt + ' ' + desc).toLowerCase();
+ if (text.includes('hour') || text.includes('hr') || text.includes('hourly')) return 'Hours';
+ if (text.includes('day') || text.includes('daily')) return 'Days';
+ if (text.includes('month') || text.includes('monthly')) return 'Months';
+ if (text.includes('year') || text.includes('annual')) return 'Year';
+ if (text.includes('kg') || text.includes('kilo')) return 'kg';
+ if (text.includes('box') || text.includes('pack')) return 'Boxes';
+ if (text.includes('license') || text.includes('subscription')) return 'Lic';
+ if (text.includes('session') || text.includes('class')) return 'Sessions';
+ if (text.includes('consulting') || text.includes('audit') || text.includes('service')) return 'Service';
+ return 'Units';
+ }
+
+ private static inferHsnSac(desc: string): string {
+ const d = desc.toLowerCase();
+ if (d.includes('software') || d.includes('cloud') || d.includes('ai') || d.includes('code') || d.includes('tech')) return '998314';
+ if (d.includes('consult') || d.includes('advisory') || d.includes('strategy')) return '998311';
+ if (d.includes('laptop') || d.includes('computer') || d.includes('server') || d.includes('hardware')) return '847130';
+ if (d.includes('photo') || d.includes('video') || d.includes('media') || d.includes('shoot')) return '998361';
+ if (d.includes('repair') || d.includes('maintenance') || d.includes('fix')) return '998713';
+ if (d.includes('health') || d.includes('gym') || d.includes('medical') || d.includes('fitness')) return '999312';
+ if (d.includes('rent') || d.includes('lease') || d.includes('property')) return '997212';
+ if (d.includes('transport') || d.includes('freight') || d.includes('logistics')) return '996511';
+ return '998314';
+ }
+
+ private static inferContextualDescription(prompt: string): string {
+ const p = prompt.toLowerCase();
+ if (p.includes('gym') || p.includes('fitness')) return 'Annual Gym Membership & Fitness Facility Access';
+ if (p.includes('coffee') || p.includes('cafe') || p.includes('latte')) return 'Specialty Coffee & Bakery Refreshments';
+ if (p.includes('photo') || p.includes('headshot')) return 'Corporate Photography & Executive Headshots';
+ if (p.includes('web') || p.includes('website')) return 'Responsive Web Application Design & Front-End Engineering';
+ if (p.includes('cloud') || p.includes('devops')) return 'Enterprise Cloud Infrastructure & DevOps Consulting';
+ if (p.includes('legal') || p.includes('law')) return 'Legal Advisory, Contract Scaffolding & Compliance Review';
+ if (p.includes('tuition') || p.includes('course') || p.includes('class')) return 'Educational Course Tuition & Training Modules';
+ if (p.includes('repair') || p.includes('hardware')) return 'Hardware Diagnostics, Component Replacement & Labor';
+ return 'Professional Statutory & Commercial Deliverable';
+ }
+
+ private static sanitizePartyName(raw: string): string {
+ let clean = raw.trim();
+ if (clean.includes(',')) clean = clean.split(',')[0].trim();
+ clean = clean.replace(/^(?:client|vendor|consignee|customer|employee|tenant|candidate|applicant|dossier)\s+/i, '').trim();
+ clean = clean.replace(/\s+(?:targeting|applying|for|as|with|roles?|position|basic|salary|amount|buying|at|on|dated|\$|βΉ|rs|\d|and\b).*$/i, '').trim();
+ return this.capitalizeTitle(clean);
+ }
+
+ private static capitalizeTitle(str: string): string {
+ return str
+ .toLowerCase()
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
+ .join(' ');
+ }
+}
diff --git a/src/services/image/LogoStorageService.ts b/src/services/image/LogoStorageService.ts
index a1ae70c..ac357be 100644
--- a/src/services/image/LogoStorageService.ts
+++ b/src/services/image/LogoStorageService.ts
@@ -103,10 +103,11 @@ export class LogoStorageService {
}
}
- // Generate immutable durable filename scoped to business profile
+ // Generate immutable durable filename scoped to business profile (sanitized against path traversal)
+ const sanitizedProfileId = profileId.replace(/[^a-zA-Z0-9_-]/g, '_');
const timestamp = Date.now();
const sanitizedExt = detectedExtension.toLowerCase() === 'jpeg' ? 'jpg' : detectedExtension.toLowerCase();
- const filename = `logo_${profileId}_${timestamp}.${sanitizedExt}`;
+ const filename = `logo_${sanitizedProfileId}_${timestamp}.${sanitizedExt}`;
const destinationUri = `${this.BRANDING_DIR}${filename}`;
// Copy file to app-private storage
@@ -210,7 +211,8 @@ export class LogoStorageService {
if (!dirInfo.exists) return;
const files = await FileSystem.readDirectoryAsync(this.BRANDING_DIR);
- const prefix = `logo_${profileId}_`;
+ const sanitizedProfileId = profileId.replace(/[^a-zA-Z0-9_-]/g, '_');
+ const prefix = `logo_${sanitizedProfileId}_`;
for (const file of files) {
if (file.startsWith(prefix) && file !== excludeFilename) {
diff --git a/src/services/pdf/templates/UniversalCustomRenderer.ts b/src/services/pdf/templates/UniversalCustomRenderer.ts
index bbaa903..38a0c66 100644
--- a/src/services/pdf/templates/UniversalCustomRenderer.ts
+++ b/src/services/pdf/templates/UniversalCustomRenderer.ts
@@ -20,8 +20,8 @@ import { UniversalDocumentInstance, UniversalDocumentSchema } from '../../../dom
import { TemplateCustomization } from '../types';
import { resolveDocumentTheme, escapeHtml } from './commonStyles';
-function cleanText(str?: string | null): string {
- if (!str) return '';
+function cleanText(str?: any): string {
+ if (str === null || str === undefined) return '';
return String(str)
.replace(//g, '>');
@@ -596,7 +596,7 @@ export function renderUniversalCustomHtml(
` : ''}
${textareas.map((ta) => {
- const val = content[ta.id] || ta.defaultValue || '';
+ const val = content[ta.id] ?? ta.defaultValue ?? '';
if (!val) return '';
return `
@@ -607,7 +607,7 @@ export function renderUniversalCustomHtml(
${tables.map((tbl) => {
let rows: any[] = Array.isArray(content[tbl.id]) ? content[tbl.id] : [];
- if (rows.length === 0) {
+ if (content[tbl.id] === undefined) {
// Intelligent fallback mock rows for immediate high-fidelity preview
const MOCK_ROWS: Record
= {
equipment_table: [
@@ -792,6 +792,7 @@ export function renderUniversalCustomHtml(
}).join('')}
+ ${schema.footerConfig?.showSignatures === false ? '' : `
ACKNOWLEDGEMENT AND SIGNATURES
@@ -809,6 +810,7 @@ export function renderUniversalCustomHtml(
+ `}