> ## Documentation Index
> Fetch the complete documentation index at: https://docs.briankimemia.is-a.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# AMO CertVault — Complete Documentation

> Enterprise-grade AI-powered aircraft spares certificate repository for Approved Maintenance Organisations. EASA Form 1, FAA 8130-3, COC, CRS extraction with role-based access, audit trails, and compliance tooling.

<Note>
  **AMO CertVault** is a production-grade certificate management system designed for aviation AMOs. It uses AI to extract, validate, and organise aircraft spares certificates — EASA Form 1, FAA 8130-3, COC, CRS, and more.
</Note>

***

## Introduction

AMO CertVault digitises the certificate management workflow for Aircraft Approved Maintenance Organisations. Upload a PDF certificate, and the AI engine automatically extracts part numbers, serial numbers, suppliers, dates, and certificate types — even from multi-item documents with dozens of line items, including kit/overhaul sub-components.

<Info>
  **Why CertVault?** Aviation AMOs handle hundreds of certificates monthly. Manual data entry is slow, error-prone, and non-auditable. CertVault automates extraction with **92%+ accuracy** using Gemini AI, with a regex fallback ensuring zero data loss.
</Info>

**Built for:**

* **Quality Managers** reviewing incoming spares documentation
* **Store Personnel** receiving and cataloguing parts
* **Auditors** verifying compliance trails
* **Administrators** managing user access and system configuration

***

## Quick Start

<Steps>
  <Step title="Create Your Account">
    Navigate to `/auth` and create an account with your email and password. You will receive a **Visitor** role by default.

    <Tip>Use your company email — administrators can identify and approve your account faster.</Tip>
  </Step>

  <Step title="Await Admin Approval">
    An administrator will review your account and assign an appropriate role (Quality Manager, Store Personnel, or Auditor). You will be redirected to a **Pending Approval** screen until activated.

    <Warning>Do not create multiple accounts — duplicate sign-ups will be flagged and may delay approval.</Warning>
  </Step>

  <Step title="Upload Your First Certificate">
    Go to **Upload Certificate** from the sidebar. Drag and drop a PDF or use the **Camera Scanner** to capture a physical certificate directly from your device.

    <Info>Supported formats: PDF (text-based or scanned). Maximum file size: 10MB per document.</Info>
  </Step>

  <Step title="Review AI Extraction">
    The system will automatically extract certificate data using Gemini AI. Review the extracted fields — part number, serial number, description, supplier, certificate type, and date. Edit any inaccuracies and save.

    <Tip>The **confidence score** (0–100%) indicates extraction reliability. Scores below 70% warrant manual verification.</Tip>
  </Step>

  <Step title="Search and Manage">
    Use the **Certificates** page to search by part number, description, serial number, or supplier. Full-text search is powered by PostgreSQL `tsvector` with trigram fuzzy matching.
  </Step>
</Steps>

***

## Features

<CardGroup cols={3}>
  <Card title="AI-Powered Extraction" icon="robot">
    Gemini 2.5 Flash extracts structured data from PDFs using tool-calling. Supports EASA Form 1, FAA 8130-3, COC, CRS, and 37+ certificate type mappings. Regex fallback ensures zero data loss.
  </Card>

  <Card title="Multi-Item Certificates" icon="layer-group">
    Certificates with multiple line items are parsed into individual records — each with its own part number, serial number, quantity, and condition. Supports 100+ items per certificate.
  </Card>

  <Card title="Kit Sub-Item Extraction" icon="box-open">
    Overhaul kits, gasket sets, and assembly items with sub-components are automatically detected. Sub-items use decimal line numbering (`14.1`, `14.2`) to preserve parent-child relationships.
  </Card>

  <Card title="Role-Based Access (RBAC)" icon="user-shield">
    Five-tier RBAC: Admin, Quality Manager, Store Personnel, Auditor, and Visitor. Row-Level Security (RLS) enforced at the database level — no client-side bypasses possible.
  </Card>

  <Card title="Camera Scanning" icon="camera">
    Capture certificates directly from your device camera with real-time preview, crop overlay, and flash toggle. The image is uploaded and processed through the same AI extraction pipeline.
  </Card>

  <Card title="Batch Upload" icon="upload">
    Upload multiple PDFs simultaneously. Each file is processed independently with live progress tracking, error reporting, and searchable batch history.
  </Card>

  <Card title="Certificate Cart and Bulk Print" icon="cart-shopping">
    Add certificates to a cart from search results or the duplicates page. Bulk print PDFs or export selected certificates as CSV for external reporting and audits.
  </Card>

  <Card title="Duplicate Detection" icon="clone">
    Dedicated duplicate management page groups certificates by part number across the entire system. View, compare, delete, or add duplicates to cart with role-restricted actions.
  </Card>

  <Card title="AI Chat Assistant" icon="message-bot">
    Streaming AI chat assistant for aviation certificate questions. Renders responses with Markdown formatting — headers, tables, code blocks, bold/italic, and clickable links.
  </Card>

  <Card title="PDF Compression" icon="file-zipper">
    Structural PDF compression using pdf-lib's object stream optimisation. Anomaly detection automatically flags suspiciously high compression ratios (below 0.2).
  </Card>

  <Card title="Complete Audit Trail" icon="clipboard-list">
    Every create, update, and delete action is logged with user ID, certificate ID, timestamp, and action details in JSON format. Fully queryable and exportable.
  </Card>

  <Card title="Full-Text Search" icon="magnifying-glass">
    PostgreSQL `tsvector`-based search across certificates and items. Trigram similarity matching handles typos and partial matches. Debounced input for responsive UX.
  </Card>
</CardGroup>

***

## System Architecture

<Info>
  The application is a React SPA backed by Lovable Cloud, providing authentication, PostgreSQL database, file storage, and serverless edge functions — no separate backend to manage.
</Info>

```mermaid theme={null}
graph TB
    subgraph Client["Frontend — React / Vite / PWA"]
        UI["React SPA\nTailwind + shadcn/ui"]
        RQ["TanStack Query\nCache & Mutations"]
        Auth["Auth Context\nSession Management"]
        Cart["Certificate Cart\nReact Context"]
        Router["React Router v6\nProtected Routes"]
    end

    subgraph Cloud["Lovable Cloud"]
        SBAuth["Authentication\nEmail + Password"]
        DB[("PostgreSQL\nRLS Policies")]
        Storage["File Storage\nPDF Originals"]
        EF1["extract-certificate\nAI + Regex Fallback"]
        EF2["compress-certificate\npdf-lib Optimisation"]
        EF3["cert-ai-chat\nStreaming SSE"]
    end

    subgraph AI["AI Gateway"]
        Gemini["Gemini 2.5 Flash\nTool Calling"]
    end

    UI --> RQ
    RQ --> SBAuth
    RQ --> DB
    UI --> Storage
    UI --> EF1
    EF1 --> Gemini
    UI --> EF2
    EF2 --> Storage
    UI --> EF3
    EF3 --> Gemini
    Cart --> DB
    Router --> Auth
    Auth --> SBAuth
```

***

## Certificate Processing

### Extraction Pipeline

<Tip>
  The extraction pipeline is **fully automated** — upload a PDF and the system handles file storage, AI extraction, type normalisation, duplicate checking, and database persistence without manual intervention.
</Tip>

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant ST as Storage
    participant EF as extract-certificate
    participant AI as Gemini AI
    participant DB as Database

    U->>FE: Upload PDF
    FE->>ST: Store original file
    FE->>EF: Invoke extraction (filePath)
    EF->>ST: Download PDF bytes
    EF->>AI: Send PDF + tool schema

    alt AI Extraction Succeeds
        AI-->>EF: Structured certificate JSON
        EF->>EF: Normalize types (37 mappings)
        EF->>EF: Normalize dates to ISO 8601
        EF->>EF: Sort and re-sequence kit sub-items
        EF->>EF: Compute per-item confidence
    else AI Fails or Rate Limited
        EF->>EF: Regex fallback extraction
        EF->>EF: Parse BT/ET text blocks
        EF->>EF: Match 36 aviation patterns
        EF->>EF: Tiered confidence scoring
    end

    EF->>DB: Check for duplicates (part_number)
    EF-->>FE: Return extraction result + duplicates
    FE->>FE: User reviews and edits
    FE->>DB: Save certificate + items
    FE->>DB: Log audit entry
```

### Extraction Algorithm

<Tabs>
  <Tab title="AI Path (Primary)">
    The primary extraction path uses **Gemini 2.5 Flash** with structured tool-calling:

    ```
    1. Download PDF from storage → base64 encode
    2. Call Gemini 2.5 Flash with extraction tool schema
    3. Parse tool_calls response → structured JSON
    4. Normalize certificate_type against 37 pattern mappings
    5. Normalize all dates to ISO 8601 format
    6. Detect kit/overhaul items by keyword matching
    7. Sort kit sub-items by decimal line_number (14.1, 14.2...)
    8. Re-sequence to integer line numbers for storage
    9. Validate part numbers with aviation regex patterns
    10. Compute per-item confidence score (0.0 – 1.0)
    ```

    <Tip>The AI prompt explicitly instructs Gemini to extract unnumbered rows beneath kit/overhaul/set items as sub-components with decimal line numbers.</Tip>
  </Tab>

  <Tab title="Regex Fallback">
    When AI extraction fails (rate limits, malformed PDFs), the system falls back to pattern-based extraction:

    ```
    1. Parse BT/ET (Begin Text / End Text) blocks from raw PDF bytes
    2. Detect aviation keywords against 36 known patterns
    3. Require >= 2 keyword matches to classify as certificate
    4. Extract fields via tiered regex patterns:
       - Part Number:   8 patterns (P/N, PN, Part No., etc.)
       - Serial Number: 6 patterns (S/N, SN, Serial, etc.)
       - Supplier:      7 patterns (MFR, Manufacturer, etc.)
       - Description:   5 patterns (DESC, Item, etc.)
       - Date:          6 patterns with ISO normalisation
    5. Multi-item detection via repeating pattern groups
    6. Tiered confidence: High (>=0.8), Medium (0.5–0.79), Low (<0.5)
    ```

    <Warning>Regex extraction typically achieves **60–75% accuracy** compared to AI's 92%+. Always review regex-extracted certificates manually.</Warning>
  </Tab>
</Tabs>

### Kit Sub-Item Extraction

<Info>
  Kit certificates (overhaul kits, gasket sets, hardware assemblies) contain a **parent item** with multiple **sub-components** listed beneath it. CertVault automatically detects and preserves these relationships.
</Info>

**Detection Keywords:** `kit`, `set`, `overhaul`, `assembly`, `hardware kit`, `gasket set`

**Example Extraction:**

| Line | Part Number | Description                | Type          |
| ---- | ----------- | -------------------------- | ------------- |
| 14   | SL12034-SC  | GASKET SET SINGLE CYLINDER | Kit Parent    |
| 15   | SL66732     | GASKET                     | Sub-component |
| 16   | SL67193     | GASKET                     | Sub-component |
| 17   | SL71481     | RING, OIL SEAL             | Sub-component |

**Visual Display:**

* Kit parent rows — teal gradient background with `KIT` badge pill
* Sub-component rows — indented with teal connector line and junction dot
* Hover highlights the entire kit group

### Certificate Type Mapping

<Accordion title="Supported Certificate Types (37+ input patterns)">
  The system normalises dozens of input variations to standardised types:

  | Input Pattern(s)                                    | Normalised Type | Common Sources                 |
  | --------------------------------------------------- | --------------- | ------------------------------ |
  | EASA Form 1, JAA Form 1, TCCA Form One              | `easa-form-1`   | European / Canadian MROs       |
  | FAA 8130-3, FAA Form 8130-3, Airworthiness Approval | `8130-3`        | FAA-certified facilities       |
  | Certificate of Conformity, COC, C of C              | `coc`           | Manufacturers and distributors |
  | Certificate of Release to Service, CRS              | `crs`           | Maintenance organisations      |
  | Test Report, Inspection Report                      | `test-report`   | Testing laboratories           |
  | Shipping Document, Packing Slip                     | `shipping`      | Logistics and supply chain     |
  | CAAC Form, ANAC Form, DGCA, Serviceable Tag         | `other`         | Other national authorities     |

  <Tip>If a certificate type is not recognised, it defaults to `other`. You can manually update the type in the certificate detail view.</Tip>
</Accordion>

***

## Cart and Bulk Operations

<Steps>
  <Step title="Add to Cart">
    From the **Certificates** page or **Duplicates** page, click the cart icon on any certificate item. The cart state persists via React Context across navigation.

    <Tip>You can add items from multiple certificates — the cart is not limited to a single document.</Tip>
  </Step>

  <Step title="Review Cart">
    Navigate to the **Cart** page to see all selected items with part numbers, descriptions, and source certificate references. Remove unwanted items individually or clear the entire cart.
  </Step>

  <Step title="Bulk Print PDFs">
    Click **Print All** to open all selected certificate PDFs in new tabs for printing. Each PDF links to the original uploaded document in storage.
  </Step>

  <Step title="Export to CSV">
    Click **Export CSV** to download a spreadsheet containing part number, description, serial number, quantity, condition, and source certificate for each selected item.

    <Info>The CSV export is compatible with Excel, Google Sheets, and most ERP/inventory systems.</Info>
  </Step>
</Steps>

```mermaid theme={null}
flowchart LR
    A["Search Certificates"] --> B["Add to Cart"]
    C["Duplicates Page"] --> B
    B --> D["Review Cart"]
    D --> E{"Action?"}
    E -->|Print| F["Bulk Print PDFs"]
    E -->|Export| G["Export CSV"]
    E -->|Remove| H["Remove Items"]
    E -->|Clear| I["Clear Cart"]
```

***

## Duplicate Management

The Duplicates page identifies certificates that share the same part number across different uploads, enabling quick review and cleanup.

<Warning>
  **Destructive Action:** Deleting a duplicate removes the certificate item permanently from the database. This action is restricted to **Admin** and **Quality Manager** roles and is logged in the audit trail with full details.
</Warning>

### Detection Algorithm

```
FUNCTION detectDuplicates():
    groups   <- GROUP certificate_items BY LOWER(part_number)
    duplicates <- FILTER groups WHERE COUNT > 1

    FOR EACH group IN duplicates:
        SORT items BY upload_date DESC
        DISPLAY with certificate metadata:
            - Part number, description, serial number
            - Source certificate ID and type
            - Upload date and uploader
            - Available actions (View, Cart, Delete)

    RETURN duplicates WITH search filtering
```

<Tip>
  Duplicates are matched by **part number only** (case-insensitive). Different serial numbers with the same part number are flagged as duplicates — the same part from different batches should be reviewable together.
</Tip>

***

## AI Chat Assistant

The AI Assistant provides **streaming** responses about aviation certificates and compliance, rendered with full Markdown formatting.

<Info>
  The chat uses the `cert-ai-chat` edge function connecting to **Gemini AI** via the Lovable AI Gateway. No API key configuration is required — it works out of the box.
</Info>

### Capabilities

<CardGroup cols={2}>
  <Card title="Certificate Knowledge" icon="file-certificate">
    FAA Form 8130-3 field explanations, EASA Form 1 block descriptions, certificate status types, traceability requirements.
  </Card>

  <Card title="Compliance Guidance" icon="gavel">
    Regulatory requirements for parts documentation, release-to-service criteria, certificate validity periods.
  </Card>

  <Card title="System Help" icon="circle-question">
    OCR extraction process explanation, batch upload guidance, search tips, role-based access questions.
  </Card>

  <Card title="General Aviation" icon="plane">
    Part number formats, supplier identification, condition codes (NE, OH, SV, AR), quantity and unit conventions.
  </Card>
</CardGroup>

### Response Formatting

The AI assistant renders responses with rich Markdown:

* Headers (`##`, `###`) with teal accent styling
* Bold and italic text for emphasis
* Inline code and fenced code blocks with monospace font
* Tables with borders and header highlighting
* Ordered and unordered lists with proper nesting
* Clickable links to external references

<Tip>Try these starter prompts: *"What fields are on FAA Form 8130-3?"*, *"Explain certificate status types"*, *"How does OCR extraction work?"*</Tip>

***

## User Roles and Permissions

### Permission Matrix

<Tabs>
  <Tab title="Permissions Grid">
    | Permission           | Admin | Quality Manager | Store Personnel | Auditor | Visitor |
    | -------------------- | :---: | :-------------: | :-------------: | :-----: | :-----: |
    | View certificates    |   ✅   |        ✅        |        ✅        |    ✅    |    ❌    |
    | Upload certificates  |   ✅   |        ✅        |        ✅        |    ❌    |    ❌    |
    | Edit certificates    |   ✅   |        ✅        |        ❌        |    ❌    |    ❌    |
    | Delete certificates  |   ✅   |        ✅        |        ❌        |    ❌    |    ❌    |
    | Batch upload         |   ✅   |        ✅        |        ✅        |    ❌    |    ❌    |
    | Camera scanning      |   ✅   |        ✅        |        ✅        |    ❌    |    ❌    |
    | View audit logs      |   ✅   |        ✅        |        ❌        |    ✅    |    ❌    |
    | Manage users         |   ✅   |        ❌        |        ❌        |    ❌    |    ❌    |
    | Certificate cart     |   ✅   |        ✅        |        ✅        |    ✅    |    ❌    |
    | Duplicate management |   ✅   |        ✅        |        ✅        |    ✅    |    ❌    |
    | AI Assistant         |   ✅   |        ✅        |        ✅        |    ✅    |    ❌    |
    | System settings      |   ✅   |        ❌        |        ❌        |    ❌    |    ❌    |

    <Warning>
      **Principle of Least Privilege:** Each role has only the minimum permissions required. The admin dashboard includes an interactive permissions matrix for visual reference. Actual enforcement is at the database level via RLS policies.
    </Warning>
  </Tab>

  <Tab title="Role Lifecycle">
    ```mermaid theme={null}
    graph TD
        A["User Signs Up"] --> B["Visitor Role Assigned"]
        B --> C{"Admin Reviews Account"}
        C -->|Approve| D["Assign Operational Role"]
        C -->|Reject| E["Account Deactivated"]
        D --> F["Quality Manager"]
        D --> G["Store Personnel"]
        D --> H["Auditor"]
        F --> I["Full Upload + Edit + Delete"]
        G --> J["Upload + View Only"]
        H --> K["View + Audit Logs Only"]
        E --> L["Cannot Access System"]
    ```
  </Tab>

  <Tab title="Security Model">
    **Row-Level Security (RLS)** is enforced on every table:

    ```sql theme={null}
    -- Only active, non-visitor users can view certificates
    CREATE POLICY "Authenticated users can view certificates"
    ON public.certificates FOR SELECT TO authenticated
    USING (
      public.has_role(auth.uid(), 'admin') OR
      public.has_role(auth.uid(), 'quality_manager') OR
      public.has_role(auth.uid(), 'store_personnel') OR
      public.has_role(auth.uid(), 'auditor')
    );
    ```

    <Warning>
      The `has_role()` function is defined as `SECURITY DEFINER` to prevent recursive RLS evaluation. Never store roles on the `profiles` table — they are isolated in `user_roles` to prevent privilege escalation.
    </Warning>
  </Tab>
</Tabs>

### User Management Dashboard (Admin)

<CardGroup cols={2}>
  <Card title="Stats Overview" icon="chart-bar">
    Summary cards showing total users, active accounts, pending visitors, and role distribution with animated counters.
  </Card>

  <Card title="Interactive Permissions Matrix" icon="table-cells">
    Visual reference grid with toggle checkboxes showing what each role can do. Labeled as reference-only — actual enforcement is via RLS.
  </Card>

  <Card title="User Table" icon="users">
    Avatar initials, coloured role badges, activation toggle switches, time-ago join dates, and role assignment dropdowns.
  </Card>

  <Card title="Role Summary Cards" icon="id-card">
    Per-role cards with custom icons, colour coding, and permission count — quick overview of the access hierarchy.
  </Card>
</CardGroup>

***

## Data Model

<Info>
  All tables use UUID primary keys, automatic timestamps, and Row-Level Security. The `search_vector` columns enable PostgreSQL full-text search with automatic updates via triggers.
</Info>

```mermaid theme={null}
erDiagram
    certificates ||--o{ certificate_items : "has many"
    certificates ||--o{ audit_logs : "tracked by"
    certificates }o--|| profiles : "uploaded by"
    batch_uploads ||--o{ batch_upload_items : "contains"
    profiles ||--|| user_roles : "has role"

    certificates {
        uuid id PK
        uuid uploaded_by FK
        string part_number
        string description
        string serial_number
        string file_url
        string certificate_type
        string status
        int item_count
        float ocr_confidence
        string compressed_file_url
        float compression_ratio
        tsvector search_vector
        timestamp upload_date
        timestamp updated_at
    }

    certificate_items {
        uuid id PK
        uuid certificate_id FK
        int line_number
        string part_number
        string description
        string serial_number
        string quantity
        string condition
        float confidence
        tsvector search_vector
    }

    profiles {
        uuid id PK
        uuid user_id
        string email
        string full_name
        boolean is_active
        timestamp created_at
    }

    user_roles {
        uuid id PK
        uuid user_id
        string role
    }

    audit_logs {
        uuid id PK
        uuid user_id
        uuid certificate_id FK
        string action
        json details
        timestamp created_at
    }

    batch_uploads {
        uuid id PK
        uuid user_id
        int total_files
        int saved_count
        int error_count
        int skipped_count
        int rejected_count
        string status
        timestamp started_at
        timestamp completed_at
    }

    batch_upload_items {
        uuid id PK
        uuid batch_id FK
        uuid certificate_id FK
        string file_name
        int file_size
        string status
        string part_number
        float confidence
        string error_message
    }
```

***

## API Reference

### Edge Functions

<Accordion title="extract-certificate — AI Certificate Extraction">
  **Method:** `POST`\
  **Authentication:** Bearer token (anon key)

  Extracts structured data from a PDF certificate using Gemini AI with regex fallback.

  **Request Body**

  ```json theme={null}
  {
    "filePath": "userId/timestamp_filename.pdf"
  }
  ```

  **Success Response (200)**

  ```json theme={null}
  {
    "certificate": {
      "part_number": "7A-2841-MFG",
      "description": "Turbine Blade Assembly",
      "serial_number": "SN-2024-8847",
      "certificate_type": "easa-form-1",
      "certificate_date": "2024-03-15",
      "supplier": "Rolls-Royce Aerospace",
      "items": [
        {
          "line_number": 1,
          "part_number": "7A-2841-MFG",
          "description": "Turbine Blade Assembly",
          "serial_number": "SN-2024-8847",
          "quantity": "1 EA",
          "condition": "NE",
          "confidence": 0.95
        }
      ]
    },
    "confidence": 0.92,
    "duplicates": [],
    "method": "ai"
  }
  ```

  **Error Response (500)**

  ```json theme={null}
  {
    "error": "Extraction failed",
    "message": "PDF could not be parsed"
  }
  ```

  <Tip>The `method` field indicates whether `"ai"` or `"regex"` was used. Regex extractions typically have lower confidence scores.</Tip>
</Accordion>

<Accordion title="compress-certificate — PDF Compression">
  **Method:** `POST`\
  **Authentication:** Bearer token (anon key)

  Compresses a PDF certificate using structural optimisation with pdf-lib.

  **Request Body**

  ```json theme={null}
  {
    "filePath": "userId/timestamp_filename.pdf"
  }
  ```

  **Success Response (200)**

  ```json theme={null}
  {
    "compressed_url": "userId/compressed_filename.pdf",
    "original_size": 524288,
    "compressed_size": 312500,
    "ratio": 0.596,
    "flagged": false
  }
  ```

  <Warning>A `flagged: true` response indicates the compression ratio is suspiciously high (below 0.2), meaning 80%+ size reduction. The original is always preserved.</Warning>
</Accordion>

<Accordion title="cert-ai-chat — Streaming AI Chat">
  **Method:** `POST`\
  **Authentication:** Bearer token (anon key)

  Streaming AI chat for aviation certificate questions using Server-Sent Events (SSE).

  **Request Body**

  ```json theme={null}
  {
    "messages": [
      { "role": "user", "content": "What fields are on FAA Form 8130-3?" }
    ]
  }
  ```

  **Response (SSE Stream)**

  ```text theme={null}
  data: {"choices":[{"delta":{"content":"FAA Form 8130-3 contains..."}}]}

  data: {"choices":[{"delta":{"content":" the following blocks:\n\n"}}]}

  data: [DONE]
  ```

  <Info>The response follows the OpenAI-compatible delta streaming format. The frontend uses `ReadableStream` with chunk-by-chunk parsing for real-time display.</Info>
</Accordion>

***

## Application Routes

| Route               | Page                 | Access Level           | Description                                                               |
| ------------------- | -------------------- | ---------------------- | ------------------------------------------------------------------------- |
| `/`                 | Landing / Dashboard  | Public / Authenticated | Marketing page (unauthenticated) or interactive dashboard (authenticated) |
| `/auth`             | Login and Sign Up    | Public                 | Email/password authentication with form validation                        |
| `/pending`          | Pending Approval     | Visitor                | Displayed after sign-up while awaiting admin activation                   |
| `/certificates`     | Certificate List     | Authenticated          | Searchable, paginated list with status filters                            |
| `/certificates/:id` | Certificate Detail   | Authenticated          | Full certificate view with items table and kit indicators                 |
| `/upload`           | Upload Certificate   | Upload roles           | Single PDF upload with AI extraction preview                              |
| `/batch-upload`     | Batch Upload         | Upload roles           | Multi-file upload with progress tracking                                  |
| `/batch-history`    | Batch History        | Authenticated          | Historical batch upload records and item details                          |
| `/scan`             | Camera Scanner       | Upload roles           | Device camera capture with crop overlay                                   |
| `/cart`             | Certificate Cart     | Authenticated          | Selected items for bulk print / CSV export                                |
| `/duplicates`       | Duplicate Management | Authenticated          | Part-number-grouped duplicate review and cleanup                          |
| `/ai-assistant`     | AI Chat              | Authenticated          | Streaming AI assistant for certificate questions                          |
| `/audit-logs`       | Audit Logs           | Admin / QM / Auditor   | Paginated audit trail with action filtering                               |
| `/settings`         | User Settings        | Authenticated          | Profile and preference management                                         |
| `/admin/users`      | User Management      | Admin only             | User activation, role assignment, permissions matrix                      |
| `/privacy-policy`   | Privacy Policy       | Public                 | Data handling and privacy information                                     |

***

## Tech Stack

<CardGroup cols={2}>
  <Card title="Frontend" icon="browser">
    **React 18** + **TypeScript** + **Vite** for fast builds. **Tailwind CSS** + **shadcn/ui** component library. **Framer Motion** for animations.
  </Card>

  <Card title="State Management" icon="database">
    **TanStack Query** for server state with intelligent caching. **React Context** for client-side state (auth, cart).
  </Card>

  <Card title="Backend" icon="cloud">
    **Lovable Cloud** — PostgreSQL, Authentication, File Storage, and Edge Functions. Zero-config serverless deployment.
  </Card>

  <Card title="AI and Processing" icon="microchip">
    **Gemini 2.5 Flash** via Lovable AI Gateway. **pdf-lib** for compression. **react-markdown** + **remark-gfm** for rendering.
  </Card>
</CardGroup>

| Layer        | Technology                                | Purpose                                   |
| ------------ | ----------------------------------------- | ----------------------------------------- |
| Framework    | React 18, TypeScript                      | Component architecture, type safety       |
| Build        | Vite 5                                    | Fast HMR, optimised production builds     |
| Styling      | Tailwind CSS 3, shadcn/ui                 | Utility-first CSS, accessible components  |
| Routing      | React Router v6                           | Client-side routing with protected routes |
| Server State | TanStack Query v5                         | Data fetching, caching, mutations         |
| Backend      | Lovable Cloud (PostgreSQL, Auth, Storage) | Full-stack serverless platform            |
| AI           | Gemini 2.5 Flash                          | Certificate extraction, chat assistant    |
| PDF          | pdf-lib                                   | Structural compression, byte parsing      |
| Charts       | Recharts                                  | Dashboard visualisations                  |
| Markdown     | react-markdown + remark-gfm               | AI chat response formatting               |
| PWA          | vite-plugin-pwa                           | Offline support, installability           |
| Search       | PostgreSQL tsvector + pg\_trgm            | Full-text and fuzzy search                |

***

## Progressive Web App (PWA)

AMO CertVault is a **Progressive Web App** — installable on mobile and desktop with offline caching and a native-like experience.

**Configuration:**

* **Install Prompt:** Automatic on supported browsers (Chrome, Edge, Safari)
* **Icons:** 192×192 and 512×512 PNG (including maskable)
* **Apple Touch Icon:** Configured for iOS home screen
* **Theme Colour:** Teal (`#1a9e8f`)
* **Display:** Standalone (no browser chrome)
* **Orientation:** Portrait-primary
* **Service Worker:** Auto-update strategy via Workbox
* **Viewport:** `width=device-width, initial-scale=1.0, viewport-fit=cover`

<Tip>On iOS, open the app in Safari, tap the **Share** button, and select **Add to Home Screen** to install CertVault as a native-like app.</Tip>

***

## SEO and Performance

<CardGroup cols={2}>
  <Card title="Meta and Structured Data" icon="code">
    OpenGraph tags, Twitter Cards, JSON-LD (SoftwareApplication + Organization), canonical URLs, comprehensive meta descriptions.
  </Card>

  <Card title="Image Optimisation" icon="image">
    `loading="lazy"` on non-critical images, explicit `width`/`height` to prevent CLS, `alt` text on all images, `role="img"` with `aria-label` on SVGs.
  </Card>

  <Card title="Font Performance" icon="font">
    Google Fonts preconnect and preload for JetBrains Mono. `font-display: swap` to prevent FOIT.
  </Card>

  <Card title="Core Web Vitals" icon="gauge-high">
    Minimised CLS via explicit dimensions, optimised LCP via font preloading, efficient FID via code splitting.
  </Card>
</CardGroup>

***

## Troubleshooting

<Accordion title="AI extraction returns no data or low confidence">
  **Possible causes:**

  * PDF is password-protected or image-only without embedded text
  * Document is not a recognised aviation certificate type
  * AI rate limits triggered fallback to regex extraction

  **Solutions:**

  1. Verify the PDF opens normally in a PDF reader
  2. Check that it contains at least 2 aviation keywords (P/N, S/N, EASA, FAA, etc.)
  3. Try re-uploading — temporary rate limits resolve automatically
  4. For image-only PDFs, use the **Camera Scanner** which handles image processing

  <Tip>The `method` field in extraction results indicates whether AI or regex was used. Regex results warrant manual review.</Tip>
</Accordion>

<Accordion title="Duplicate detection shows unexpected results">
  By design, duplicates are matched by **part number only** (case-insensitive):

  * Different serial numbers with the same part number are flagged as duplicates
  * The same part from different certificates is flagged as a duplicate
  * This is intentional for inventory reconciliation

  <Info>Use the Duplicates page to review groups and decide which entries to keep, delete, or export.</Info>
</Accordion>

<Accordion title="User cannot access system after sign-up">
  New accounts receive the **Visitor** role by default and are placed on a **Pending Approval** screen. To resolve:

  1. An **Admin** must navigate to **User Management**
  2. Locate the user in the table
  3. Change their role from `visitor` to an operational role
  4. Ensure the **Active** toggle is enabled

  <Warning>Users with the `visitor` role or `is_active: false` cannot access any protected routes. This is enforced by both frontend route guards and database RLS policies.</Warning>
</Accordion>

<Accordion title="PDF compression flags an anomaly">
  Compression ratios below **0.2** (80%+ size reduction) are flagged as potentially suspicious:

  * May indicate the PDF contains very little actual content
  * May indicate excessive metadata or duplicate objects
  * The **original PDF is always preserved** alongside the compressed version

  <Tip>Flagged compression is informational only — the certificate is still saved and accessible. Review flagged certificates to ensure content integrity.</Tip>
</Accordion>

<Accordion title="Batch upload shows errors for some files">
  Individual files in a batch can fail independently:

  * **Invalid PDF:** Corrupted or non-PDF files are rejected
  * **Extraction failure:** AI and regex both failed to extract meaningful data
  * **Duplicate detected:** A certificate with the same part number already exists (skipped, not error)

  Check **Batch History** for detailed per-file status, error messages, and confidence scores.
</Accordion>

<Accordion title="Camera scanner not working">
  **Browser permissions required:**

  1. Allow camera access when prompted
  2. Ensure HTTPS connection (camera API requires secure context)
  3. On iOS, use **Safari** — other browsers may not support the camera API

  <Warning>Camera scanning is not supported on desktop browsers without a webcam. Use the standard **Upload** page for desktop workflows.</Warning>
</Accordion>

***

## Changelog

| Version | Date          | Highlights                                                                     |
| ------- | ------------- | ------------------------------------------------------------------------------ |
| 2.6     | March 2026    | Enhanced Mintlify documentation, SEO optimisation, deployment fixes            |
| 2.5     | March 2026    | Kit sub-item extraction, parent-child visual indicators, AI markdown rendering |
| 2.4     | March 2026    | Certificate cart, duplicate management page, bulk print and CSV export         |
| 2.3     | March 2026    | AI chat assistant with streaming, batch upload history page                    |
| 2.2     | March 2026    | Dashboard redesign with Recharts, user management permissions matrix           |
| 2.1     | March 2026    | Camera scanning, batch upload, PDF compression with anomaly detection          |
| 2.0     | March 2026    | Multi-item certificate support, full-text search with tsvector + pg\_trgm      |
| 1.0     | February 2026 | Initial release — single-item extraction, RBAC, audit logging                  |

***

## Additional Resources

<CardGroup cols={3}>
  <Card title="EASA Part 21" icon="book" href="https://www.easa.europa.eu/en/document-library/easy-access-rules/easy-access-rules-21">
    EASA Form 1 regulatory requirements and authorised release certificate specifications.
  </Card>

  <Card title="FAA Order 8130.21" icon="book" href="https://www.faa.gov/regulations_policies/orders_notices/index.cfm/go/document.information/documentID/1040745">
    FAA procedures for completion and use of FAA Form 8130-3, Airworthiness Approval Tag.
  </Card>

  <Card title="Source Code" icon="github" href="https://github.com/BrianKN019/skydocs-compliance">
    Open-source repository with full codebase, CI/CD configuration, and contribution guidelines.
  </Card>
</CardGroup>

***

Built by [Brian KN](https://briankimemia.is-a.dev/) ·
