# TFM aInventory - Project Architecture & Requirements

This document is the **Single Source of Truth** for the project's technical architecture, business requirements, and core logic.

## 1. Application Overview
A unified system to maintain an inventory of "items" and their quantities, inclusive of a web administration interface, offline field operations, audit logging, and AI-powered label extraction functionalities.

## 2. Technical Stack
### 2.1 Backend (API & Data)
- **Language:** Python 3.12+ (Optimized for performance and type safety)
- **Framework:** FastAPI (Async ASGI)
- **Database:** SQLite (SQLAlchemy) - Local file-based persistence
- **Validation:** Pydantic v2
- **Auth:** Hybrid LDAP (python-ldap) + PBKDF2 local password hash caching
- **AI Engine:** Google GenAI SDK (Gemini 2.0 Flash) - Location: `backend/ai/`

### 2.2 Frontend (Web & PWA)
- **Architecture:** Next.js 15+ (App Router)
- **Styling:** Tailwind CSS (Readability-first config)
- **Icons:** Lucide Icons (React components)
- **Offline persistence:** Dexie.js (IndexedDB wrapper)
- **Scanner:** `html5-qrcode` (Client-side, offline-only)
- **Sync:** Axios with bulk-sync idempotency (UUID-based)

### 2.3 Operations & Tooling
- **PWA Deployment:** `next-pwa` (Service Workers + Manifest.json)
- **HTTPS Proxy:** `caddy` or `local-ssl-proxy` (Port 8909)
- **Servers:** Frontend (Port 8907), Backend (Port 8906)
- **Configuration:** Centrally managed via root `config/` directory (includes `network_config.env`, `ldap_config.json`, `Caddyfile`).

## 3. Data Models & Entities
- **Item:** Name, Category Group (Structured), Item Type (Specific), Quantity, Barcode, Part Number, Box Label (Association).
- **Category:** Predefined groups for organizational structure.
- **Box/Container:** A generic grouping label (box_label) that links multiple items together for rapid multi-scanning.
- **Audit Log:** Immutable ledger detailing CRUD operations and stock fluctuations, including point-in-time box associations.

## 4. Scanning & Optimization Strategy (Crucial)
### 4.1 AI Usage Policy
- **Routine Operations (Check-in/Out):** Executes entirely on the local device unconditionally using `html5-qrcode` ($0 cost). No AI is allowed here.
- **New Item Onboarding (AI Label OCR):** Uses cloud AI (`gemini-2.0-flash`). The user takes a photo, AI extracts data based on strict templates.
- **AI Box Discovery Mode (v1.6.0):** Supports specialized `mode="box"` prompt that focuses exclusively on prominent container names/hand-written labels, ignoring technical spec noise.
- **Validation Mask:** AI-extracted data is NEVER saved directly. It is presented in a validation UI for human confirmation.

### 4.2 Scanner Technical Specs
- **Hardware Access:** Direct `MediaStreamTrack` access. Zoom cycle: 1x -> 2x -> Max/2 -> Max.
- **Image Pre-processing:** Rescaling (1200px), 60% Center Crop, Grayscale/Contrast filters, JPEG (`0.85` quality).
- **OCR Mode:** Fully automated. Cycles every 4 seconds without user intervention. Visual countdown shown in controls panel.
- **UI Layout:** Camera viewport is always unobstructed. Controls (Zoom + countdown status) are displayed in a dedicated section below the viewport.
- **OCR Matching Engine (`page.tsx`):**
  - Noise Filtering: Ignores `< 3` chars, decimals, and dates.
  - Scoring: Exact S/N (+500), Exact P/N (+200), Token match (+50), Category match (+20).
  - Threshold: Minimum **40 points** for auto-match without user intervention.
- **Targeted Field Scanning (v1.6.0):** UI allows "locking" the scanner focus to a specific input field (e.g., `box_label`). The OCR result is then redirected to state without performing regular item lookup.

### 4.3 Box Labeling & Printing System (v1.5.0)
- **Local OCR Priority:** Before checking individual S/Ns, the matching engine searches for `box_label` tokens. If a box is identified:
  - Single Match: Directly opens stock adjustment.
  - Multi Match: Opens "Box Contents" selection interstitial.
- **Label Generation:** Native SVG-based Code 128 and QR generation (`lib/labels.ts`). Requires ZERO external libraries for maximum offline stability.
- **Printing Modes:**
  - @media print: Hardcoded CSS styles for 62mm x 29mm label dimensions.
  - Mobile Export: Canvas-to-PNG rasterization for sharing with Bluetooth printer roll apps.


## 5. Offline Sync Protocol
To prevent data loss in basements or unstable networks:
- **Offline Engine:** Service Workers cache assets. IndexedDB saves data.
- **UUID Labeling:** Every sync operation generated offline is tagged with a client-side UUID.
- **Idempotent Backend:** The `bulk_sync` endpoint checks UUIDs against `AuditLog` before applying increments, preventing double-counts.

## 6. Automation & Versioning (`scripts/`)
- **`scripts/save_version.py`**: Implements the `save-version` AI Command Shortcut. Increments `VERSION.json` patch version, commits all staged changes, creates a snapshot branch `v.X.Y.Z`, and calls `./export_prod.sh` to generate the production bundle. Always stays on the `dev` branch.


## 7. Security & Hardening (v1.4.0)
To ensure enterprise-grade protection, the following policies are enforced:

### 7.1 Access Control & RBAC
- **Strict Separation:** Operations are divided into `user` and `admin` roles.
- **Admin Only:** Critical operations such as `DELETE /items/`, user management, and DB settings are restricted via the `auth.get_current_admin` dependency.
- **User Role:** Standard users are permitted to perform check-in/out and list inventory, but cannot delete catalog entries.

### 7.2 Brute-Force Protection
- **Rate Limiting:** Implemented via `slowapi`. The `login` endpoint is limited to **5 requests per minute** per IP to mitigate automated credential stuffing.

### 7.3 Data Privacy
- **Information Scrubbing:** Backend logs are configured to intercept and mask sensitive auth tokens or internal secrets (e.g., `JWT_SECRET_KEY`) during debug output.
- **Direct Bind LDAP:** Authentication uses direct user binding to the LDAP server, avoiding the need for a privileged service account with broad search permissions.
- **Cryptographic Credential Caching:** To support offline operations, the system caches a **PBKDF2-HMAC-SHA256 hash** of the user's Enterprise credentials upon successful online login. Plain text passwords are NEVER stored.

### 7.4 PWA Trust & Security
- **HTTPS Enforcement:** The system requires TLS (Port 8909) for camera access and secure token transmission.
- **Manifest Integrity:** A comprehensive `manifest.json` ensures the app is recognized as a trusted PWA on mobile platforms (iOS/Android).
7.5 Git Infrastructure Hardening (v1.7.0)
To ensure deployment stability on macOS environments with potentially broken developer tool links (`xcode-select` errors):
- **Direct Binary Mapping:** The system bypasses path resolution by using a hardcoded direct link to the Git binary in `.git_path` (`/Library/Developer/CommandLineTools/usr/bin/git`).
- **Persistence Mandate:** This path is protected by mandatory AI rules and must never be removed or modified to ensure `save-version` and automated deployment scripts remain functional.
