KarthiEz commited on
Commit
8850939
·
verified ·
1 Parent(s): f657d46

Upload 56 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +31 -0
  2. .env +6 -0
  3. .gitignore +14 -0
  4. .huggingfaceignore +38 -0
  5. Dockerfile +50 -0
  6. README.md +158 -10
  7. README_HF.md +60 -0
  8. ap_agent1/__init__.py +11 -0
  9. ap_agent1/__pycache__/__init__.cpython-310.pyc +0 -0
  10. ap_agent1/__pycache__/ai_agent.cpython-310.pyc +0 -0
  11. ap_agent1/__pycache__/config.cpython-310.pyc +0 -0
  12. ap_agent1/__pycache__/db.cpython-310.pyc +0 -0
  13. ap_agent1/__pycache__/document.cpython-310.pyc +0 -0
  14. ap_agent1/__pycache__/invoice.cpython-310.pyc +0 -0
  15. ap_agent1/__pycache__/po.cpython-310.pyc +0 -0
  16. ap_agent1/__pycache__/suppliers.cpython-310.pyc +0 -0
  17. ap_agent1/__pycache__/utils.cpython-310.pyc +0 -0
  18. ap_agent1/ai_agent.py +581 -0
  19. ap_agent1/config.py +23 -0
  20. ap_agent1/db.py +464 -0
  21. ap_agent1/document.py +159 -0
  22. ap_agent1/invoice.py +157 -0
  23. ap_agent1/po.py +168 -0
  24. ap_agent1/suppliers.py +37 -0
  25. ap_agent1/utils.py +47 -0
  26. app.py +17 -0
  27. backend1/__pycache__/main.cpython-310.pyc +0 -0
  28. backend1/main.py +1045 -0
  29. debug.log +4 -0
  30. frontend/dist/assets/index-CUicmmlc.js +0 -0
  31. frontend/dist/assets/index-Lye-aeXV.css +1 -0
  32. frontend/dist/index.html +15 -0
  33. frontend/index.html +14 -0
  34. frontend/package-lock.json +2667 -0
  35. frontend/package.json +28 -0
  36. frontend/postcss.config.js +8 -0
  37. frontend/src/App.tsx +1687 -0
  38. frontend/src/api.ts +220 -0
  39. frontend/src/components/Badge.tsx +27 -0
  40. frontend/src/components/BadgeButton.tsx +31 -0
  41. frontend/src/components/BookLoader.tsx +85 -0
  42. frontend/src/components/Card.tsx +36 -0
  43. frontend/src/components/FileDrop.tsx +78 -0
  44. frontend/src/components/FilePreview.tsx +274 -0
  45. frontend/src/components/LogoMark.tsx +57 -0
  46. frontend/src/components/MultiFileDrop.tsx +119 -0
  47. frontend/src/components/ShareButton.tsx +76 -0
  48. frontend/src/components/StepBar.tsx +77 -0
  49. frontend/src/main.tsx +12 -0
  50. frontend/src/styles.css +77 -0
.dockerignore ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .Python
6
+ *.so
7
+ *.egg
8
+ *.egg-info
9
+ dist
10
+ build
11
+ .venv
12
+ venv
13
+ env
14
+ ENV
15
+ node_modules
16
+ frontend/node_modules
17
+ frontend/dist
18
+ .git
19
+ .gitignore
20
+ *.log
21
+ .DS_Store
22
+ .vscode
23
+ .idea
24
+ *.swp
25
+ *.swo
26
+ *~
27
+ .env
28
+ .env.local
29
+ data/*.sqlite3
30
+ *.db
31
+
.env ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ AZURE_OPENAI_ENDPOINT=https://ezofisai.cognitiveservices.azure.com
2
+ AZURE_OPENAI_API_KEY=DkCha4tDjyRZx1jROCBh05Iqr8d4T6HrITndWloNSu29t96kre7aJQQJ99BEACYeBjFXJ3w3AAAAACOGzHIR
3
+ AZURE_OPENAI_DEPLOYMENT=gpt-4.1
4
+ AZURE_OPENAI_API_VERSION=2025-01-01-preview
5
+
6
+
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # secrets
2
+ .env
3
+ *.env
4
+
5
+ # local db/artifacts
6
+ data/*.sqlite3
7
+ data/*.db
8
+
9
+ # python
10
+ __pycache__/
11
+ *.pyc
12
+ .venv/
13
+
14
+
.huggingfaceignore ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Files to ignore when uploading to Hugging Face
2
+ node_modules/
3
+ __pycache__/
4
+ *.pyc
5
+ *.pyo
6
+ *.pyd
7
+ .Python
8
+ *.so
9
+ *.egg
10
+ *.egg-info
11
+ dist/
12
+ build/
13
+ .venv/
14
+ venv/
15
+ env/
16
+ ENV/
17
+ .git/
18
+ .gitignore
19
+ *.log
20
+ .DS_Store
21
+ .vscode/
22
+ .idea/
23
+ *.swp
24
+ *.swo
25
+ *~
26
+ .env
27
+ .env.local
28
+ data/*.sqlite3
29
+ *.db
30
+ frontend/node_modules/
31
+ frontend/dist/
32
+ frontend/.vite/
33
+ *.csv
34
+ samples/
35
+ scripts/
36
+ debug.log
37
+ MSP SAMPLE MASTER Export.csv
38
+
Dockerfile ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-stage build for Hugging Face Spaces
2
+ FROM node:18-alpine AS frontend-builder
3
+
4
+ WORKDIR /app/frontend
5
+
6
+ # Copy frontend files
7
+ COPY frontend/package*.json ./
8
+ RUN npm ci
9
+
10
+ COPY frontend/ ./
11
+ RUN npm run build
12
+
13
+ # Python backend stage
14
+ FROM python:3.11-slim
15
+
16
+ WORKDIR /app
17
+
18
+ # Install system dependencies
19
+ RUN apt-get update && apt-get install -y \
20
+ build-essential \
21
+ && rm -rf /var/lib/apt/lists/*
22
+
23
+ # Copy requirements and install Python dependencies
24
+ COPY requirements.txt .
25
+ RUN pip install --no-cache-dir -r requirements.txt
26
+
27
+ # Copy backend code
28
+ COPY backend1/ ./backend1/
29
+ COPY ap_agent1/ ./ap_agent1/
30
+ COPY data/ ./data/
31
+
32
+ # Copy built frontend from builder stage
33
+ COPY --from=frontend-builder /app/frontend/dist ./frontend/dist
34
+
35
+ # Copy any additional files needed
36
+ COPY scripts/ ./scripts/ 2>/dev/null || true
37
+
38
+ # Create data directory if it doesn't exist
39
+ RUN mkdir -p data
40
+
41
+ # Expose port (Hugging Face Spaces uses port 7860 by default)
42
+ EXPOSE 7860
43
+
44
+ # Set environment variables
45
+ ENV PYTHONUNBUFFERED=1
46
+ ENV PORT=7860
47
+
48
+ # Run the FastAPI app
49
+ CMD ["python", "-m", "uvicorn", "backend1.main:app", "--host", "0.0.0.0", "--port", "7860"]
50
+
README.md CHANGED
@@ -1,10 +1,158 @@
1
- ---
2
- title: APAgent Demo
3
- emoji: 📊
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AP Agent Demo (Invoice ↔ PO Matching)
2
+
3
+ User-friendly web app for Accounts Payable processing:
4
+ - Upload **Invoice document** (PDF/DOCX/TXT) + **PO CSV**
5
+ - Auto checks: **Invoice–PO match**, **back-order detection**, **duplicate invoice detection**, **supplier validation**
6
+ - Persists **history** in local SQLite
7
+
8
+ ## Quickstart (FastAPI backend + React frontend)
9
+
10
+ This repo uses:
11
+ - **Backend API**: FastAPI (`backend1/main.py`)
12
+ - **Frontend**: React + Tailwind + Framer Motion (`frontend/`)
13
+
14
+ ### One-command (Windows) ⭐
15
+
16
+ If you're on Windows and want the easiest way to start everything:
17
+
18
+ ```powershell
19
+ .\run-dev.ps1
20
+ ```
21
+
22
+ This script starts:
23
+ - the backend on the first free port from `8000, 8010, 8020, ...`
24
+ - the frontend on `http://localhost:5173` with the correct API proxy target
25
+
26
+ ### Backend
27
+
28
+ Set env vars:
29
+ - `AZURE_OPENAI_ENDPOINT`
30
+ - `AZURE_OPENAI_API_KEY`
31
+ - `AZURE_OPENAI_DEPLOYMENT`
32
+ - (optional) `AZURE_OPENAI_API_VERSION`
33
+
34
+ Optional (real OCR for scanned invoices):
35
+ - `AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT`
36
+ - `AZURE_DOCUMENT_INTELLIGENCE_KEY`
37
+ - (optional) `AZURE_DOCUMENT_INTELLIGENCE_API_VERSION`
38
+
39
+ Troubleshooting (common):
40
+ - Make sure your frontend is talking to the **backend1** server (health shows `"service":"backend1"`). Old servers on `8010` may respond with just `{"ok":true}`.
41
+ - If your backend is on port `8020`, run frontend with: `VITE_API_PROXY_TARGET=http://127.0.0.1:8020`
42
+
43
+ Run:
44
+
45
+ ```bash
46
+ python -m pip install -r requirements.txt
47
+ python -m uvicorn backend1.main:app --reload --port 8010
48
+ ```
49
+
50
+ > If you **can't use port 8000** on your machine: it's usually because another app/service is already listening on it.
51
+ > In our environment we found a Windows service `EZ Capture OCREngineV1` (NSSM) running `uvicorn main:app --port 8000`.
52
+
53
+ ### Frontend
54
+
55
+ In a new terminal:
56
+
57
+ ```bash
58
+ cd frontend
59
+ npm install
60
+ npm run dev
61
+ ```
62
+
63
+ Optional: point the frontend at a different API URL:
64
+ - set `VITE_API_BASE_URL` (defaults to `http://127.0.0.1:8010` in dev; in production it uses relative `/api/*`)
65
+ - or set `VITE_API_PROXY_TARGET` (controls the Vite dev-server proxy for `/api/*`)
66
+
67
+ > Note: If port `8010` is taken on your machine, use any free port (e.g. `8020`) and set `VITE_API_BASE_URL` / `VITE_API_PROXY_TARGET` accordingly.
68
+
69
+ ## Single app (one server, one URL) ✅
70
+
71
+ For a single "real web app" (frontend + backend served together):
72
+
73
+ 1) Build the frontend once:
74
+
75
+ ```bash
76
+ cd frontend
77
+ npm install
78
+ npm run build
79
+ cd ..
80
+ ```
81
+
82
+ 2) Run the server:
83
+
84
+ ```bash
85
+ python -m pip install -r requirements.txt
86
+ python -m uvicorn backend1.main:app --reload --port 8010
87
+ ```
88
+
89
+ Open: `http://localhost:8010`
90
+
91
+ ## Hugging Face Spaces Deployment
92
+
93
+ This app can be deployed to Hugging Face Spaces using Docker.
94
+
95
+ ### Setup
96
+
97
+ 1. Create a new Space on Hugging Face
98
+ 2. Select "Docker" as the SDK
99
+ 3. Push this repository to the Space
100
+ 4. Set environment variables in Space settings:
101
+ - `AZURE_OPENAI_ENDPOINT`
102
+ - `AZURE_OPENAI_API_KEY`
103
+ - `AZURE_OPENAI_DEPLOYMENT`
104
+ - `AZURE_OPENAI_API_VERSION` (optional)
105
+
106
+ The Dockerfile will:
107
+ - Build the React frontend
108
+ - Install Python dependencies
109
+ - Serve the app on port 7860
110
+
111
+ ## AI Agent (recommended)
112
+
113
+ This demo supports an **AI-powered agent** mode for:
114
+ - Better invoice field/line-item extraction
115
+ - A model-driven final settlement decision (with rationale) using PO/history/supplier evidence
116
+
117
+ ### Enable
118
+
119
+ - **UI**: Expand "AI Agent settings", toggle it on, choose **Azure OpenAI** or **OpenAI**, then type **YES** to allow model calls.
120
+ - **Env var (OpenAI)**: set `OPENAI_API_KEY` before running the app
121
+ - **Env var (Azure OpenAI)**: set `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY` (optional: `AZURE_OPENAI_API_VERSION`)
122
+
123
+ ### Local .env (optional)
124
+
125
+ Create a `.env` in the project root (optional) and fill in:
126
+ - `AZURE_OPENAI_ENDPOINT`
127
+ - `AZURE_OPENAI_API_KEY`
128
+ - `AZURE_OPENAI_DEPLOYMENT`
129
+
130
+ The app will fall back to rules-only mode if no API key is provided.
131
+
132
+ ## Feature rollout (only when you say YES)
133
+
134
+ This demo is structured so capabilities can be enabled incrementally.
135
+
136
+ Implemented now:
137
+ - **Item 1**: Detailed match insights (line-level mismatch reasons + optional AI explanation)
138
+ - **Item 2**: Backorder detection + monitoring (history-based remaining quantities + optional AI summary)
139
+
140
+ ## Data formats
141
+
142
+ ### PO CSV
143
+ Expected columns (case-insensitive; extra columns are OK):
144
+ - `po_number` (required)
145
+ - `sku` (recommended)
146
+ - `description` (required if `sku` missing)
147
+ - `qty_ordered` (required)
148
+ - `unit_price` (optional)
149
+
150
+ The AI agent can handle **any column names** dynamically - it will intelligently identify PO number, SKU, description, quantity, etc. from your CSV structure.
151
+
152
+ ### Invoice
153
+ Supported formats:
154
+ - PDF (text extraction + optional OCR)
155
+ - DOCX
156
+ - TXT
157
+
158
+ The AI agent extracts invoice fields and line items dynamically from any invoice format.
README_HF.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AP Agent Demo
3
+ emoji: 📄
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ ---
10
+
11
+ # AP Agent Demo - Invoice ↔ PO Matching
12
+
13
+ AI-powered Accounts Payable processing application that automatically matches invoices to purchase orders, detects backorders, validates suppliers, and identifies duplicates.
14
+
15
+ ## Features
16
+
17
+ - 🤖 **AI-Powered Matching**: Uses Azure OpenAI to dynamically match invoice lines to PO lines, handling any column names
18
+ - 📊 **Backorder Tracking**: Automatically calculates remaining quantities per PO line
19
+ - ✅ **Supplier Validation**: Validates suppliers against approved supplier lists
20
+ - 🔍 **Duplicate Detection**: Detects duplicate invoices by file hash and business key
21
+ - 📈 **History & Analytics**: Tracks processing history with search and filter capabilities
22
+ - 🎨 **Modern UI**: Beautiful React frontend with real-time processing feedback
23
+
24
+ ## How to Use
25
+
26
+ 1. **Upload Invoice**: Upload a PDF, DOCX, or TXT invoice file
27
+ 2. **Upload PO File**: Upload a CSV or Excel file containing purchase order data
28
+ 3. **Review Results**: The AI agent will:
29
+ - Extract invoice fields and line items
30
+ - Match invoice lines to PO lines dynamically
31
+ - Calculate backorders
32
+ - Validate supplier
33
+ - Detect duplicates
34
+ - Provide approval decision (Approved/Partially Approved/Rejected)
35
+
36
+ ## Environment Variables
37
+
38
+ Set these in your Hugging Face Space settings:
39
+
40
+ - `AZURE_OPENAI_ENDPOINT`: Your Azure OpenAI endpoint
41
+ - `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key
42
+ - `AZURE_OPENAI_DEPLOYMENT`: Your Azure OpenAI deployment name
43
+ - `AZURE_OPENAI_API_VERSION`: (Optional) API version, defaults to 2024-10-21
44
+
45
+ Optional (for real OCR on scanned invoices):
46
+ - `AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT`: Azure Document Intelligence endpoint
47
+ - `AZURE_DOCUMENT_INTELLIGENCE_KEY`: Azure Document Intelligence key
48
+
49
+ ## Technical Details
50
+
51
+ - **Backend**: FastAPI (Python)
52
+ - **Frontend**: React + TypeScript + Tailwind CSS
53
+ - **AI**: Azure OpenAI (GPT-4)
54
+ - **Database**: SQLite (persistent storage)
55
+ - **Deployment**: Docker on Hugging Face Spaces
56
+
57
+ ## License
58
+
59
+ MIT
60
+
ap_agent1/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AP Agent demo package.
3
+
4
+ Core capabilities:
5
+ - Parse invoice documents (PDF/DOCX/TXT) into text + best-effort structured fields/lines
6
+ - Normalize PO CSV into a canonical schema
7
+ - Compare invoice ↔ PO for settlement recommendation
8
+ - Track backorders and detect duplicates via local SQLite history
9
+ """
10
+
11
+
ap_agent1/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (476 Bytes). View file
 
ap_agent1/__pycache__/ai_agent.cpython-310.pyc ADDED
Binary file (18.4 kB). View file
 
ap_agent1/__pycache__/config.cpython-310.pyc ADDED
Binary file (651 Bytes). View file
 
ap_agent1/__pycache__/db.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
ap_agent1/__pycache__/document.cpython-310.pyc ADDED
Binary file (4.45 kB). View file
 
ap_agent1/__pycache__/invoice.cpython-310.pyc ADDED
Binary file (4.58 kB). View file
 
ap_agent1/__pycache__/po.cpython-310.pyc ADDED
Binary file (5.94 kB). View file
 
ap_agent1/__pycache__/suppliers.cpython-310.pyc ADDED
Binary file (1.24 kB). View file
 
ap_agent1/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
ap_agent1/ai_agent.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from typing import Any
6
+
7
+ from ap_agent1.utils import norm_space, to_float
8
+ from ap_agent1.config import MAX_HISTORY_INVOICES, MAX_INVOICE_TEXT_CHARS, MAX_PO_LINES
9
+ from ap_agent1.document import png_bytes_to_data_url
10
+
11
+
12
+ def _get_openai_client(*, provider: str, api_key: str | None, azure_endpoint: str | None, azure_api_version: str | None):
13
+ """
14
+ Lazy import so the app still runs without OpenAI installed (rules-only mode).
15
+ """
16
+ provider = (provider or "openai").strip().lower()
17
+ api_key = (api_key or os.environ.get("OPENAI_API_KEY") or "").strip()
18
+
19
+ if provider == "azure":
20
+ from openai import AzureOpenAI # type: ignore
21
+
22
+ endpoint = (azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") or "").strip()
23
+ api_version = (azure_api_version or os.environ.get("AZURE_OPENAI_API_VERSION") or "2024-10-21").strip()
24
+ if not endpoint:
25
+ raise ValueError("Azure OpenAI endpoint is required (AZURE_OPENAI_ENDPOINT).")
26
+ if not api_key:
27
+ raise ValueError("Azure OpenAI API key is required (AZURE_OPENAI_API_KEY).")
28
+ return AzureOpenAI(api_key=api_key, azure_endpoint=endpoint, api_version=api_version)
29
+
30
+ from openai import OpenAI # type: ignore
31
+
32
+ return OpenAI(api_key=api_key)
33
+
34
+
35
+ def _chat_json(
36
+ *,
37
+ client,
38
+ model: str,
39
+ prompt: str,
40
+ image_png_bytes: list[bytes] | None = None,
41
+ ) -> dict[str, Any]:
42
+ """
43
+ Call Chat Completions in JSON mode, with a compatibility fallback if response_format is unsupported.
44
+ """
45
+ content_parts: list[dict[str, Any]] = [{"type": "text", "text": prompt}]
46
+ for b in (image_png_bytes or [])[:3]:
47
+ content_parts.append({"type": "image_url", "image_url": {"url": png_bytes_to_data_url(b)}})
48
+
49
+ try:
50
+ resp = client.chat.completions.create(
51
+ model=model,
52
+ messages=[{"role": "user", "content": content_parts}],
53
+ response_format={"type": "json_object"},
54
+ temperature=0,
55
+ )
56
+ except TypeError:
57
+ # Some environments/SDK variants may not support response_format; rely on prompt-only JSON constraint.
58
+ resp = client.chat.completions.create(
59
+ model=model,
60
+ messages=[{"role": "user", "content": content_parts}],
61
+ temperature=0,
62
+ )
63
+
64
+ content = (resp.choices[0].message.content or "").strip()
65
+ return json.loads(content)
66
+
67
+
68
+ def ai_enabled(*, provider: str, api_key: str | None = None, azure_endpoint: str | None = None) -> bool:
69
+ provider = (provider or "openai").strip().lower()
70
+ if provider == "azure":
71
+ k = (api_key or os.environ.get("AZURE_OPENAI_API_KEY") or "").strip()
72
+ ep = (azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT") or "").strip()
73
+ return bool(k and ep)
74
+ k = (api_key or os.environ.get("OPENAI_API_KEY") or "").strip()
75
+ return bool(k)
76
+
77
+
78
+ def ai_extract_invoice(
79
+ *,
80
+ raw_text: str,
81
+ image_png_bytes: list[bytes] | None = None,
82
+ file_name: str | None,
83
+ model: str,
84
+ api_key: str | None = None,
85
+ provider: str = "openai",
86
+ azure_endpoint: str | None = None,
87
+ azure_api_version: str | None = None,
88
+ ) -> dict[str, Any]:
89
+ """
90
+ Uses an LLM to extract invoice header fields + line items from plain text and/or invoice images (vision).
91
+ Returns a dict with keys:
92
+ invoice_number, supplier, po_number, total_amount, currency, line_items[]
93
+ """
94
+ if provider.strip().lower() == "azure":
95
+ # AzureOpenAI uses AZURE_OPENAI_API_KEY by convention for env-based usage.
96
+ if api_key:
97
+ os.environ["AZURE_OPENAI_API_KEY"] = api_key
98
+ else:
99
+ if api_key:
100
+ os.environ["OPENAI_API_KEY"] = api_key
101
+
102
+ client = _get_openai_client(provider=provider, api_key=api_key, azure_endpoint=azure_endpoint, azure_api_version=azure_api_version)
103
+ text = (raw_text or "").strip()
104
+ if not text and not (image_png_bytes or []):
105
+ return {"invoice_number": "", "supplier": "", "po_number": "", "total_amount": "", "currency": "", "line_items": []}
106
+
107
+ prompt = f"""
108
+ You are an Accounts Payable (AP) extraction agent.
109
+ Extract structured fields from the invoice text below.
110
+
111
+ Return ONLY valid JSON with this schema:
112
+ {{
113
+ "invoice_number": string,
114
+ "supplier": string,
115
+ "po_number": string,
116
+ "total_amount": string,
117
+ "currency": string,
118
+ "line_items": [
119
+ {{
120
+ "sku": string,
121
+ "description": string,
122
+ "qty": number|null,
123
+ "unit_price": number|null,
124
+ "line_total": number|null
125
+ }}
126
+ ]
127
+ }}
128
+
129
+ Rules:
130
+ - If a field is not present, use empty string (or null for numbers).
131
+ - Normalize whitespace (no newlines inside fields).
132
+ - Keep sku/description short and human-readable.
133
+ - Do not invent items; only extract what is present.
134
+ - Prefer the PO number that appears near 'PO', 'Purchase Order', etc.
135
+ - For amounts, remove currency symbols and commas.
136
+
137
+ Invoice filename: {file_name or ""}
138
+
139
+ INVOICE TEXT (may be empty for scanned docs):
140
+ \"\"\"{text[:12000]}\"\"\"
141
+ """.strip()
142
+
143
+ data = _chat_json(client=client, model=model, prompt=prompt, image_png_bytes=list(image_png_bytes or []))
144
+
145
+ # light normalization
146
+ data["invoice_number"] = norm_space(str(data.get("invoice_number", "")))
147
+ data["supplier"] = norm_space(str(data.get("supplier", "")))
148
+ data["po_number"] = norm_space(str(data.get("po_number", "")))
149
+ data["total_amount"] = norm_space(str(data.get("total_amount", "")))
150
+ data["currency"] = norm_space(str(data.get("currency", "")))
151
+ items = data.get("line_items") or []
152
+ out_items = []
153
+ for it in items:
154
+ out_items.append(
155
+ {
156
+ "sku": norm_space(str(it.get("sku", "")))[:64],
157
+ "description": norm_space(str(it.get("description", "")))[:240],
158
+ "qty": to_float(it.get("qty")),
159
+ "unit_price": to_float(it.get("unit_price")),
160
+ "line_total": to_float(it.get("line_total")),
161
+ }
162
+ )
163
+ data["line_items"] = out_items[:80]
164
+ return data
165
+
166
+
167
+ def ai_decide(
168
+ *,
169
+ model: str,
170
+ api_key: str | None,
171
+ evidence: dict[str, Any],
172
+ provider: str = "openai",
173
+ azure_endpoint: str | None = None,
174
+ azure_api_version: str | None = None,
175
+ ) -> dict[str, Any]:
176
+ """
177
+ Uses an LLM to make the final AP decision using evidence computed by tools.
178
+ Returns:
179
+ match_status: Matched|Review|Unmatched
180
+ duplicate: bool
181
+ supplier_status: Validated|Review|Unknown|Missing
182
+ alerts: [{level, message}]
183
+ rationale: string
184
+ """
185
+ if provider.strip().lower() == "azure":
186
+ if api_key:
187
+ os.environ["AZURE_OPENAI_API_KEY"] = api_key
188
+ else:
189
+ if api_key:
190
+ os.environ["OPENAI_API_KEY"] = api_key
191
+
192
+ client = _get_openai_client(provider=provider, api_key=api_key, azure_endpoint=azure_endpoint, azure_api_version=azure_api_version)
193
+
194
+ prompt = f"""
195
+ You are an Accounts Payable (AP) settlement agent.
196
+ Your job: decide whether the invoice matches the PO for payment settlement, detect duplicates, validate supplier confidence, and flag backorders.
197
+
198
+ You are given EVIDENCE computed by the system (PO rows, matching results, duplicate checks, supplier fuzzy match, and backorder summary).
199
+
200
+ Return ONLY valid JSON with this schema:
201
+ {{
202
+ "match_status": "Matched" | "Review" | "Unmatched",
203
+ "duplicate": boolean,
204
+ "supplier_status": "Validated" | "Review" | "Unknown" | "Missing",
205
+ "alerts": [{{"level":"info"|"warning"|"error","message":string}}],
206
+ "rationale": string
207
+ }}
208
+
209
+ Decision guidance:
210
+ - If duplicate is true: match_status should be "Review" (do not settle).
211
+ - If any invoice lines are unmatched to PO: "Unmatched" unless there is very strong evidence it's a formatting/extraction issue → then "Review".
212
+ - If quantities exceed remaining PO quantities or price variance is material (>2%): "Review".
213
+ - If supplier_status is Unknown/Missing: at least "Review".
214
+ - If everything aligns within tolerance: "Matched".
215
+
216
+ EVIDENCE (JSON):
217
+ {json.dumps(evidence, ensure_ascii=False)[:12000]}
218
+ """.strip()
219
+
220
+ data = _chat_json(client=client, model=model, prompt=prompt)
221
+
222
+ # harden outputs
223
+ ms = str(data.get("match_status", "Review"))
224
+ if ms not in ("Matched", "Review", "Unmatched"):
225
+ ms = "Review"
226
+ ss = str(data.get("supplier_status", "Unknown"))
227
+ if ss not in ("Validated", "Review", "Unknown", "Missing"):
228
+ ss = "Unknown"
229
+ alerts = data.get("alerts") or []
230
+ safe_alerts = []
231
+ for a in alerts[:15]:
232
+ lvl = str(a.get("level", "info"))
233
+ if lvl not in ("info", "warning", "error"):
234
+ lvl = "info"
235
+ safe_alerts.append({"level": lvl, "message": norm_space(str(a.get("message", "")))[:240]})
236
+
237
+ return {
238
+ "match_status": ms,
239
+ "duplicate": bool(data.get("duplicate", False)),
240
+ "supplier_status": ss,
241
+ "alerts": safe_alerts,
242
+ "rationale": norm_space(str(data.get("rationale", "")))[:1200],
243
+ }
244
+
245
+
246
+ def ai_match_insights(
247
+ *,
248
+ model: str,
249
+ api_key: str | None,
250
+ provider: str,
251
+ azure_endpoint: str | None,
252
+ azure_api_version: str | None,
253
+ evidence: dict[str, Any],
254
+ ) -> dict[str, Any]:
255
+ """
256
+ Produces short, user-facing insights about mismatches/backorders.
257
+ Returns JSON:
258
+ { "summary": string, "key_issues": [string], "suggested_action": string }
259
+ """
260
+ client = _get_openai_client(provider=provider, api_key=api_key, azure_endpoint=azure_endpoint, azure_api_version=azure_api_version)
261
+ prompt = f"""
262
+ You are an AP agent assisting a human AP clerk.
263
+ Given EVIDENCE (invoice↔PO comparison + backorders), generate a concise explanation.
264
+
265
+ Return ONLY valid JSON with schema:
266
+ {{
267
+ "summary": string,
268
+ "key_issues": [string],
269
+ "suggested_action": string
270
+ }}
271
+
272
+ Rules:
273
+ - Keep it short and specific.
274
+ - Only use evidence; do not invent.
275
+ - If matched: suggest proceeding to payment.
276
+ - If review/unmatched: suggest what to verify (qty/price/PO number/supplier/backorder).
277
+
278
+ EVIDENCE (JSON):
279
+ {json.dumps(evidence, ensure_ascii=False)[:12000]}
280
+ """.strip()
281
+ data = _chat_json(client=client, model=model, prompt=prompt)
282
+ summary = norm_space(str(data.get("summary", "")))[:400]
283
+ issues = [norm_space(str(x))[:160] for x in (data.get("key_issues") or [])][:8]
284
+ action = norm_space(str(data.get("suggested_action", "")))[:200]
285
+ return {"summary": summary, "key_issues": issues, "suggested_action": action}
286
+
287
+
288
+ def ai_ap_agent_process(
289
+ *,
290
+ deployment: str,
291
+ api_key: str,
292
+ azure_endpoint: str,
293
+ azure_api_version: str,
294
+ invoice_text: str,
295
+ invoice_images: list[bytes] | None = None,
296
+ file_name: str | None,
297
+ file_sha256: str | None,
298
+ po_rows: list[dict[str, Any]],
299
+ po_source_text: str | None = None,
300
+ supplier_master: list[dict[str, Any]],
301
+ history: dict[str, Any],
302
+ user_overrides: dict[str, Any] | None = None,
303
+ ) -> dict[str, Any]:
304
+ """
305
+ Single authoritative agent call for:
306
+ - Invoice extraction (header + line items)
307
+ - Invoice↔PO matching with detailed mismatch insights
308
+ - Backorder computation based on PO qty and historical receipts
309
+ - Duplicate invoice detection based on history (invoice number/supplier/file hash)
310
+ - Supplier validation against supplier_master
311
+
312
+ Returns a JSON object used directly by the UI and persisted to history.
313
+ """
314
+ client = _get_openai_client(
315
+ provider="azure",
316
+ api_key=api_key,
317
+ azure_endpoint=azure_endpoint,
318
+ azure_api_version=azure_api_version,
319
+ )
320
+
321
+ invoice_text = (invoice_text or "")[:MAX_INVOICE_TEXT_CHARS]
322
+ po_rows = (po_rows or [])[:MAX_PO_LINES]
323
+ po_source_text = (po_source_text or "")[:8000]
324
+ hist = history or {}
325
+ hist_invoices = (hist.get("invoices") or [])[:MAX_HISTORY_INVOICES]
326
+ hist_lines = hist.get("lines") or []
327
+
328
+ overrides = user_overrides or {}
329
+
330
+ prompt = f"""
331
+ You are an autonomous Accounts Payable (AP) agent.
332
+ You MUST do the entire processing based only on the evidence provided.
333
+
334
+ Goals:
335
+ 1) Extract invoice header + line items from the invoice.
336
+ 2) Match invoice lines to the PO file’s line items (if provided) to support a payment decision.
337
+ 3) Detect duplicates using previously processed invoices (invoice number/supplier and file hash).
338
+ 4) Validate the supplier using the approved supplier list.
339
+ 5) Detect/compute backorders using PO ordered quantities vs quantities received in previous invoices.
340
+
341
+ Return ONLY valid JSON with this schema:
342
+ {{
343
+ "invoice": {{
344
+ "invoice_number": string,
345
+ "supplier": string,
346
+ "po_number": string,
347
+ "total_amount": string,
348
+ "currency": string
349
+ }},
350
+ "confidence_score": number|null,
351
+ "approval_decision": "Approved"|"Partially Approved"|"Rejected",
352
+ "supplier_validation": {{
353
+ "supplier_status": "Validated"|"Review"|"Unknown"|"Missing",
354
+ "supplier_validated": string,
355
+ "supplier_match_score": number|null,
356
+ "notes": string
357
+ }},
358
+ "duplicate": boolean,
359
+ "match_status": "Matched"|"Review"|"Unmatched",
360
+ "rationale": string,
361
+ "suggested_action": string,
362
+ "alerts": [{{"level":"info"|"warning"|"error","message":string}}],
363
+ "line_results": [
364
+ {{
365
+ "invoice_sku": string,
366
+ "invoice_description": string,
367
+ "invoice_qty": number|null,
368
+ "invoice_unit_price": number|null,
369
+ "invoice_line_total": number|null,
370
+ "po_sku": string,
371
+ "po_description": string,
372
+ "po_qty_ordered": number|null,
373
+ "po_unit_price": number|null,
374
+ "remaining_before": number|null,
375
+ "match_score": number|null,
376
+ "line_status": "Matched"|"Review"|"Unmatched",
377
+ "mismatch_reasons": string
378
+ }}
379
+ ],
380
+ "open_backorders": [
381
+ {{
382
+ "sku": string,
383
+ "description": string,
384
+ "qty_ordered": number,
385
+ "received_before": number,
386
+ "received_after": number,
387
+ "remaining": number
388
+ }}
389
+ ]
390
+ }}
391
+
392
+ Hard rules:
393
+ - If you are not confident: use "Review" (not "Matched").
394
+ - If duplicate=true: match_status must be "Review" and include an error alert.
395
+ - Do NOT invent PO line items; only match against the PO line items provided.
396
+ - If a line can't be matched: line_status="Unmatched" with mismatch_reasons.
397
+ - Keep responses concise; no markdown; no extra keys.
398
+
399
+ Decision rules:
400
+ - You MUST set confidence_score as a float from 0.0 to 1.0 (or null if impossible).
401
+ - You MUST set approval_decision to one of: Approved, Partially Approved, Rejected.
402
+ - approval_decision MUST be consistent with confidence_score and the evidence:
403
+ - If match_status="Unmatched" → approval_decision MUST be "Rejected"
404
+ - If match_status="Matched" and confidence_score is high → "Approved"
405
+ - Otherwise → "Partially Approved" or "Rejected" depending on confidence_score and issues found.
406
+
407
+ User-facing language rules (important):
408
+ - You MUST NOT mention internal system words/keys in any user-facing fields (rationale, suggested_action, alerts.message, mismatch_reasons).
409
+ Do NOT use these terms: "PO_ROWS", "PO_SOURCE_TEXT", "SUPPLIER_MASTER", "HISTORY_LINES", "HISTORY_INVOICES", "USER_OVERRIDES".
410
+ - Use plain AP language instead, e.g.:
411
+ - "approved supplier list" (instead of SUPPLIER_MASTER)
412
+ - "PO file" / "PO details" (instead of PO_ROWS/PO_SOURCE_TEXT)
413
+ - "previous invoices" (instead of HISTORY_*)
414
+
415
+ Strict approval rules:
416
+ - You MUST NOT return match_status="Matched" unless ALL are true:
417
+ 1) invoice.invoice_number is present (non-empty)
418
+ 2) invoice.po_number is present AND matches the PO number represented by the uploaded PO file
419
+ 3) supplier_validation.supplier_status == "Validated"
420
+ 4) PO provides item line items (descriptions/SKUs and quantities)
421
+ 5) Every invoice line is matched to a PO line with consistent qty and unit price within tolerance
422
+ - If the uploaded PO is a **PO summary only** (no item lines), you MUST set match_status="Review"
423
+ and include a warning alert explaining that PO line items are required to approve.
424
+
425
+ INPUTS:
426
+ - FILE_NAME: {file_name or ""}
427
+ - FILE_SHA256: {file_sha256 or ""}
428
+ - PO line items (JSON): {json.dumps(po_rows, ensure_ascii=False)[:12000]}
429
+ - PO file preview (text snippet): {po_source_text}
430
+ - Approved supplier list (JSON): {json.dumps(supplier_master, ensure_ascii=False)[:8000]}
431
+ - Previous invoices (JSON): {json.dumps(hist_invoices, ensure_ascii=False)[:8000]}
432
+ - Previous invoice line items (JSON): {json.dumps(hist_lines, ensure_ascii=False)[:8000]}
433
+ - User edits (JSON): {json.dumps(overrides, ensure_ascii=False)[:8000]}
434
+
435
+ INVOICE_TEXT:
436
+ \"\"\"{invoice_text}\"\"\"
437
+ """.strip()
438
+
439
+ data = _chat_json(client=client, model=deployment, prompt=prompt, image_png_bytes=list(invoice_images or []))
440
+
441
+ # Minimal normalization (not decision logic).
442
+ inv = data.get("invoice") or {}
443
+ inv_out = {
444
+ "invoice_number": norm_space(str(inv.get("invoice_number", "")))[:80],
445
+ "supplier": norm_space(str(inv.get("supplier", "")))[:120],
446
+ "po_number": norm_space(str(inv.get("po_number", "")))[:60],
447
+ "total_amount": norm_space(str(inv.get("total_amount", "")))[:40],
448
+ "currency": norm_space(str(inv.get("currency", "")))[:10],
449
+ }
450
+ data["invoice"] = inv_out
451
+
452
+ sv = data.get("supplier_validation") or {}
453
+ data["supplier_validation"] = {
454
+ "supplier_status": norm_space(str(sv.get("supplier_status", "Unknown"))),
455
+ "supplier_validated": norm_space(str(sv.get("supplier_validated", "")))[:120],
456
+ "supplier_match_score": to_float(sv.get("supplier_match_score")),
457
+ "notes": norm_space(str(sv.get("notes", "")))[:240],
458
+ }
459
+ data["confidence_score"] = to_float(data.get("confidence_score"))
460
+ # keep model's label but sanitize length
461
+ data["approval_decision"] = norm_space(str(data.get("approval_decision", "")))[:40]
462
+ data["rationale"] = norm_space(str(data.get("rationale", "")))[:1200]
463
+ data["suggested_action"] = norm_space(str(data.get("suggested_action", "")))[:240]
464
+ return data
465
+
466
+
467
+ def ai_normalize_po_csv(
468
+ *,
469
+ deployment: str,
470
+ api_key: str,
471
+ azure_endpoint: str,
472
+ azure_api_version: str,
473
+ po_csv_text: str,
474
+ ) -> dict[str, Any]:
475
+ """
476
+ Agent-normalizes an arbitrary PO CSV (any columns) into a canonical schema we can store and match against.
477
+
478
+ Returns JSON:
479
+ {
480
+ "po_numbers": [string],
481
+ "po_header": {
482
+ "po_number": string,
483
+ "supplier": string,
484
+ "po_amount": number|null,
485
+ "currency": string
486
+ },
487
+ "po_lines": [
488
+ {"po_number": string, "sku": string, "description": string, "qty_ordered": number, "unit_price": number|null, "supplier": string|null}
489
+ ]
490
+ }
491
+ """
492
+ client = _get_openai_client(
493
+ provider="azure",
494
+ api_key=api_key,
495
+ azure_endpoint=azure_endpoint,
496
+ azure_api_version=azure_api_version,
497
+ )
498
+
499
+ text = (po_csv_text or "").strip()
500
+ # Keep it bounded: header + first ~200 lines is usually enough.
501
+ lines = text.splitlines()
502
+ text = "\n".join(lines[:201])[:12000]
503
+
504
+ prompt = f"""
505
+ You are an AP agent. Normalize a Purchase Order (PO) table export into a canonical line-item format.
506
+ The input may come from a CSV or from an Excel file with multiple sheets (sheet separators may be present).
507
+ Columns can have ANY names. You must infer which columns represent:
508
+ - PO number
509
+ - Item identifier (SKU/material/part) and/or description
510
+ - Quantity ordered
511
+ - Unit price (optional)
512
+ - Supplier (optional)
513
+
514
+ Return ONLY valid JSON with this schema:
515
+ {{
516
+ "po_numbers": [string],
517
+ "po_header": {{
518
+ "po_number": string,
519
+ "supplier": string,
520
+ "po_amount": number|null,
521
+ "currency": string
522
+ }},
523
+ "po_lines": [
524
+ {{
525
+ "po_number": string,
526
+ "sku": string,
527
+ "description": string,
528
+ "qty_ordered": number,
529
+ "unit_price": number|null,
530
+ "supplier": string|null
531
+ }}
532
+ ]
533
+ }}
534
+
535
+ Rules:
536
+ - If SKU is missing, keep it empty string and rely on description.
537
+ - qty_ordered must be numeric for PO_LINES; if missing/invalid, omit that line (do not invent).
538
+ - Do NOT invent data that isn't present.
539
+ - If there are multiple PO numbers, include them all.
540
+ - Keep description short (<= 240 chars).
541
+
542
+ PO CSV (sample/truncated):
543
+ \"\"\"{text}\"\"\"
544
+ """.strip()
545
+
546
+ data = _chat_json(client=client, model=deployment, prompt=prompt)
547
+
548
+ po_numbers = [norm_space(str(x)) for x in (data.get("po_numbers") or []) if str(x).strip()]
549
+ po_header = data.get("po_header") or {}
550
+ po_lines_in = data.get("po_lines") or []
551
+ po_lines_out = []
552
+ for r in po_lines_in:
553
+ po_lines_out.append(
554
+ {
555
+ "po_number": norm_space(str(r.get("po_number", "")))[:60],
556
+ "sku": norm_space(str(r.get("sku", "")))[:64],
557
+ "description": norm_space(str(r.get("description", "")))[:240],
558
+ "qty_ordered": to_float(r.get("qty_ordered")) or 0.0,
559
+ "unit_price": to_float(r.get("unit_price")),
560
+ "supplier": (norm_space(str(r.get("supplier", "")))[:120] or None),
561
+ }
562
+ )
563
+
564
+ # Drop invalid / missing PO number / qty <= 0
565
+ po_lines_out = [r for r in po_lines_out if r["po_number"] and (r["qty_ordered"] is not None) and float(r["qty_ordered"]) > 0]
566
+ if not po_numbers:
567
+ po_numbers = sorted({r["po_number"] for r in po_lines_out})
568
+
569
+ header_out = {
570
+ "po_number": norm_space(str(po_header.get("po_number", "")))[:60],
571
+ "supplier": norm_space(str(po_header.get("supplier", "")))[:120],
572
+ "po_amount": to_float(po_header.get("po_amount")),
573
+ "currency": norm_space(str(po_header.get("currency", "")))[:10],
574
+ }
575
+ # If header po_number exists, include it.
576
+ if header_out["po_number"] and header_out["po_number"] not in po_numbers:
577
+ po_numbers = [header_out["po_number"]] + po_numbers
578
+
579
+ return {"po_numbers": po_numbers, "po_header": header_out, "po_lines": po_lines_out}
580
+
581
+
ap_agent1/config.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Central configuration for the AP Agent demo.
3
+
4
+ User requirement:
5
+ - Model/deployment name must live in code (not user input).
6
+ - AP decisions should be agent-driven (no rule-based decision engine).
7
+
8
+ Azure OpenAI settings:
9
+ - Credentials and endpoint should be provided via env vars or UI fields.
10
+ """
11
+
12
+ # Azure OpenAI deployment name (this is the "model" identifier for Azure).
13
+ AZURE_OPENAI_DEPLOYMENT = "gpt-4o-mini"
14
+
15
+ # Default API version for Azure OpenAI
16
+ AZURE_OPENAI_API_VERSION = "2024-10-21"
17
+
18
+ # Safety limit: trim long inputs to keep requests reasonable.
19
+ MAX_INVOICE_TEXT_CHARS = 12000
20
+ MAX_HISTORY_INVOICES = 25
21
+ MAX_PO_LINES = 200
22
+
23
+
ap_agent1/db.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sqlite3
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from uuid import uuid4
9
+
10
+
11
+ DB_PATH = "data/ap_agent.sqlite3"
12
+
13
+
14
+ def _utc_now_iso() -> str:
15
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
16
+
17
+
18
+ def init_db(db_path: str = DB_PATH) -> None:
19
+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)
20
+ conn = sqlite3.connect(db_path)
21
+ conn.execute("PRAGMA foreign_keys = ON;")
22
+
23
+ conn.executescript(
24
+ """
25
+ CREATE TABLE IF NOT EXISTS invoices (
26
+ id TEXT PRIMARY KEY,
27
+ processed_at TEXT NOT NULL,
28
+ invoice_number TEXT,
29
+ supplier TEXT,
30
+ supplier_validated TEXT,
31
+ supplier_match_score REAL,
32
+ supplier_status TEXT,
33
+ po_number TEXT,
34
+ invoice_total REAL,
35
+ currency TEXT,
36
+ match_status TEXT NOT NULL,
37
+ match_score REAL,
38
+ processing_ms INTEGER,
39
+ extractions_count INTEGER,
40
+ approval_decision TEXT,
41
+ rule_match_status TEXT,
42
+ rule_match_score REAL,
43
+ decision_engine TEXT,
44
+ ai_model TEXT,
45
+ ai_rationale TEXT,
46
+ override_reason TEXT,
47
+ open_backorders_count INTEGER NOT NULL DEFAULT 0,
48
+ duplicate_flag INTEGER NOT NULL DEFAULT 0,
49
+ file_name TEXT,
50
+ file_sha256 TEXT,
51
+ raw_text TEXT
52
+ );
53
+
54
+ CREATE TABLE IF NOT EXISTS invoice_lines (
55
+ id TEXT PRIMARY KEY,
56
+ invoice_id TEXT NOT NULL,
57
+ sku TEXT,
58
+ description TEXT,
59
+ qty REAL,
60
+ unit_price REAL,
61
+ line_total REAL,
62
+ matched_po_line_id TEXT,
63
+ match_score REAL,
64
+ FOREIGN KEY(invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
65
+ );
66
+
67
+ CREATE TABLE IF NOT EXISTS po_lines (
68
+ id TEXT PRIMARY KEY,
69
+ po_number TEXT NOT NULL,
70
+ sku TEXT,
71
+ description TEXT,
72
+ qty_ordered REAL NOT NULL,
73
+ unit_price REAL,
74
+ supplier TEXT,
75
+ source_hash TEXT
76
+ );
77
+
78
+ CREATE INDEX IF NOT EXISTS idx_invoices_invoice_number ON invoices(invoice_number);
79
+ CREATE INDEX IF NOT EXISTS idx_invoices_po_number ON invoices(po_number);
80
+ CREATE INDEX IF NOT EXISTS idx_invoice_lines_invoice_id ON invoice_lines(invoice_id);
81
+ CREATE INDEX IF NOT EXISTS idx_po_lines_po_number ON po_lines(po_number);
82
+ -- NOTE: do not enforce uniqueness on file_sha256; duplicates are agent-detected and recorded for audit.
83
+ """
84
+ )
85
+
86
+ _migrate(conn)
87
+ conn.commit()
88
+ conn.close()
89
+
90
+
91
+ def get_conn(db_path: str = DB_PATH) -> sqlite3.Connection:
92
+ conn = sqlite3.connect(db_path, check_same_thread=False)
93
+ conn.row_factory = sqlite3.Row
94
+ conn.execute("PRAGMA foreign_keys = ON;")
95
+ return conn
96
+
97
+
98
+ def _col_exists(conn: sqlite3.Connection, table: str, col: str) -> bool:
99
+ rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
100
+ return any(r[1] == col for r in rows)
101
+
102
+
103
+ def _migrate(conn: sqlite3.Connection) -> None:
104
+ """
105
+ Best-effort additive migrations for existing local DBs.
106
+ """
107
+ # invoices
108
+ for col, ddl in [
109
+ ("rule_match_status", "ALTER TABLE invoices ADD COLUMN rule_match_status TEXT"),
110
+ ("rule_match_score", "ALTER TABLE invoices ADD COLUMN rule_match_score REAL"),
111
+ ("decision_engine", "ALTER TABLE invoices ADD COLUMN decision_engine TEXT"),
112
+ ("ai_model", "ALTER TABLE invoices ADD COLUMN ai_model TEXT"),
113
+ ("ai_rationale", "ALTER TABLE invoices ADD COLUMN ai_rationale TEXT"),
114
+ ("override_reason", "ALTER TABLE invoices ADD COLUMN override_reason TEXT"),
115
+ ("processing_ms", "ALTER TABLE invoices ADD COLUMN processing_ms INTEGER"),
116
+ ("extractions_count", "ALTER TABLE invoices ADD COLUMN extractions_count INTEGER"),
117
+ ("approval_decision", "ALTER TABLE invoices ADD COLUMN approval_decision TEXT"),
118
+ ]:
119
+ if not _col_exists(conn, "invoices", col):
120
+ conn.execute(ddl)
121
+
122
+ # Drop legacy unique index on file_sha256 if present (agent decides duplicates).
123
+ conn.execute("DROP INDEX IF EXISTS idx_invoices_file_sha256")
124
+
125
+
126
+ def _new_id(prefix: str = "") -> str:
127
+ return f"{prefix}{uuid4().hex[:12]}"
128
+
129
+
130
+ def clear_all(conn: sqlite3.Connection) -> None:
131
+ conn.executescript(
132
+ """
133
+ DELETE FROM invoice_lines;
134
+ DELETE FROM invoices;
135
+ DELETE FROM po_lines;
136
+ """
137
+ )
138
+ conn.commit()
139
+
140
+
141
+ def invoice_exists_by_sha(conn: sqlite3.Connection, file_sha256: str | None) -> bool:
142
+ if not file_sha256:
143
+ return False
144
+ row = conn.execute("SELECT 1 FROM invoices WHERE file_sha256 = ? LIMIT 1", (file_sha256,)).fetchone()
145
+ return row is not None
146
+
147
+
148
+ def invoice_exists_by_business_key(conn: sqlite3.Connection, invoice_number: str | None, supplier: str | None) -> bool:
149
+ if not invoice_number:
150
+ return False
151
+ row = conn.execute(
152
+ "SELECT 1 FROM invoices WHERE lower(invoice_number)=lower(?) AND lower(coalesce(supplier,''))=lower(coalesce(?,'')) LIMIT 1",
153
+ (invoice_number, supplier),
154
+ ).fetchone()
155
+ return row is not None
156
+
157
+
158
+ def insert_invoice_run(
159
+ conn: sqlite3.Connection,
160
+ *,
161
+ invoice_number: str | None,
162
+ supplier: str | None,
163
+ supplier_validated: str | None,
164
+ supplier_match_score: float | None,
165
+ supplier_status: str,
166
+ po_number: str,
167
+ invoice_total: float | None,
168
+ currency: str | None,
169
+ match_status: str,
170
+ match_score: float | None,
171
+ processing_ms: int | None,
172
+ extractions_count: int | None,
173
+ approval_decision: str | None,
174
+ rule_match_status: str | None = None,
175
+ rule_match_score: float | None = None,
176
+ decision_engine: str | None = None,
177
+ ai_model: str | None = None,
178
+ ai_rationale: str | None = None,
179
+ override_reason: str | None = None,
180
+ open_backorders_count: int,
181
+ duplicate_flag: bool,
182
+ file_name: str | None,
183
+ file_sha256: str | None,
184
+ raw_text: str | None,
185
+ invoice_lines: list[dict[str, Any]],
186
+ ) -> str:
187
+ invoice_id = _new_id("inv_")
188
+ conn.execute(
189
+ """
190
+ INSERT INTO invoices(
191
+ id, processed_at, invoice_number, supplier, supplier_validated, supplier_match_score, supplier_status,
192
+ po_number, invoice_total, currency, match_status, match_score,
193
+ processing_ms, extractions_count,
194
+ approval_decision,
195
+ rule_match_status, rule_match_score, decision_engine, ai_model, ai_rationale,
196
+ override_reason,
197
+ open_backorders_count, duplicate_flag,
198
+ file_name, file_sha256, raw_text
199
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
200
+ """,
201
+ (
202
+ invoice_id,
203
+ _utc_now_iso(),
204
+ invoice_number,
205
+ supplier,
206
+ supplier_validated,
207
+ supplier_match_score,
208
+ supplier_status,
209
+ po_number,
210
+ invoice_total,
211
+ currency,
212
+ match_status,
213
+ match_score,
214
+ processing_ms,
215
+ extractions_count,
216
+ approval_decision,
217
+ rule_match_status,
218
+ rule_match_score,
219
+ decision_engine,
220
+ ai_model,
221
+ ai_rationale,
222
+ override_reason,
223
+ int(open_backorders_count),
224
+ 1 if duplicate_flag else 0,
225
+ file_name,
226
+ file_sha256,
227
+ raw_text,
228
+ ),
229
+ )
230
+
231
+ for line in invoice_lines:
232
+ conn.execute(
233
+ """
234
+ INSERT INTO invoice_lines(
235
+ id, invoice_id, sku, description, qty, unit_price, line_total, matched_po_line_id, match_score
236
+ ) VALUES (?,?,?,?,?,?,?,?,?)
237
+ """,
238
+ (
239
+ _new_id("line_"),
240
+ invoice_id,
241
+ line.get("sku") or None,
242
+ line.get("description") or None,
243
+ line.get("qty"),
244
+ line.get("unit_price"),
245
+ line.get("line_total"),
246
+ line.get("matched_po_line_id"),
247
+ line.get("match_score"),
248
+ ),
249
+ )
250
+
251
+ conn.commit()
252
+ return invoice_id
253
+
254
+
255
+ def list_invoices(conn: sqlite3.Connection) -> list[dict[str, Any]]:
256
+ rows = conn.execute(
257
+ """
258
+ SELECT
259
+ id,
260
+ processed_at,
261
+ invoice_number,
262
+ supplier,
263
+ supplier_status,
264
+ po_number,
265
+ match_status,
266
+ match_score,
267
+ processing_ms,
268
+ extractions_count,
269
+ approval_decision,
270
+ open_backorders_count,
271
+ duplicate_flag,
272
+ decision_engine,
273
+ ai_model,
274
+ override_reason,
275
+ file_name
276
+ FROM invoices
277
+ ORDER BY processed_at DESC
278
+ """
279
+ ).fetchall()
280
+ return [dict(r) for r in rows]
281
+
282
+
283
+ def load_invoice_detail(conn: sqlite3.Connection, invoice_id: str) -> dict[str, Any]:
284
+ inv = conn.execute("SELECT * FROM invoices WHERE id = ?", (invoice_id,)).fetchone()
285
+ lines = conn.execute("SELECT * FROM invoice_lines WHERE invoice_id = ? ORDER BY id", (invoice_id,)).fetchall()
286
+ return {"invoice": dict(inv) if inv else {}, "lines": [dict(r) for r in lines]}
287
+
288
+
289
+ def search_invoices(
290
+ conn: sqlite3.Connection,
291
+ *,
292
+ limit: int = 100,
293
+ invoice_number: str | None = None,
294
+ supplier: str | None = None,
295
+ po_number: str | None = None,
296
+ match_status: str | None = None,
297
+ duplicate_flag: int | None = None,
298
+ date_from: str | None = None, # ISO prefix accepted
299
+ date_to: str | None = None,
300
+ ) -> list[dict[str, Any]]:
301
+ where = []
302
+ params: list[Any] = []
303
+
304
+ if invoice_number:
305
+ where.append("lower(coalesce(invoice_number,'')) LIKE lower(?)")
306
+ params.append(f"%{invoice_number.strip()}%")
307
+ if supplier:
308
+ where.append("lower(coalesce(supplier,'')) LIKE lower(?)")
309
+ params.append(f"%{supplier.strip()}%")
310
+ if po_number:
311
+ where.append("lower(coalesce(po_number,'')) LIKE lower(?)")
312
+ params.append(f"%{po_number.strip()}%")
313
+ if match_status:
314
+ where.append("match_status = ?")
315
+ params.append(match_status.strip())
316
+ if duplicate_flag is not None:
317
+ where.append("duplicate_flag = ?")
318
+ params.append(int(duplicate_flag))
319
+ if date_from:
320
+ where.append("processed_at >= ?")
321
+ params.append(date_from.strip())
322
+ if date_to:
323
+ where.append("processed_at <= ?")
324
+ params.append(date_to.strip())
325
+
326
+ where_sql = ("WHERE " + " AND ".join(where)) if where else ""
327
+ rows = conn.execute(
328
+ f"""
329
+ SELECT
330
+ id,
331
+ processed_at,
332
+ invoice_number,
333
+ supplier,
334
+ po_number,
335
+ invoice_total,
336
+ currency,
337
+ supplier_status,
338
+ match_status,
339
+ match_score,
340
+ processing_ms,
341
+ extractions_count,
342
+ approval_decision,
343
+ open_backorders_count,
344
+ duplicate_flag,
345
+ decision_engine,
346
+ ai_model,
347
+ override_reason,
348
+ file_name
349
+ FROM invoices
350
+ {where_sql}
351
+ ORDER BY processed_at DESC
352
+ LIMIT ?
353
+ """,
354
+ (*params, int(limit)),
355
+ ).fetchall()
356
+ return [dict(r) for r in rows]
357
+
358
+
359
+ def get_po_lines(conn: sqlite3.Connection, po_number: str) -> list[dict[str, Any]]:
360
+ rows = conn.execute(
361
+ """
362
+ SELECT id, po_number, sku, description, qty_ordered, unit_price, supplier
363
+ FROM po_lines
364
+ WHERE po_number = ?
365
+ ORDER BY id
366
+ """,
367
+ (po_number,),
368
+ ).fetchall()
369
+ return [dict(r) for r in rows]
370
+
371
+
372
+ def get_received_qty_by_po(conn: sqlite3.Connection, po_number: str) -> dict[tuple[str, str], float]:
373
+ """
374
+ Returns map[(po_number, sku_norm_or_desc_norm)] -> received_qty summed across all saved invoices.
375
+ """
376
+ rows = conn.execute(
377
+ """
378
+ SELECT
379
+ i.po_number AS po_number,
380
+ lower(coalesce(l.sku,'')) AS sku_l,
381
+ lower(coalesce(l.description,'')) AS desc_l,
382
+ sum(coalesce(l.qty, 0)) AS received_qty
383
+ FROM invoices i
384
+ JOIN invoice_lines l ON l.invoice_id = i.id
385
+ WHERE i.po_number = ?
386
+ AND i.duplicate_flag = 0
387
+ GROUP BY i.po_number, sku_l, desc_l
388
+ """,
389
+ (po_number,),
390
+ ).fetchall()
391
+ out: dict[tuple[str, str], float] = {}
392
+ for r in rows:
393
+ key = (r["po_number"], r["sku_l"] or r["desc_l"])
394
+ out[key] = float(r["received_qty"] or 0.0)
395
+ return out
396
+
397
+
398
+ def get_received_qty_by_po_line_id(conn: sqlite3.Connection, po_number: str) -> dict[str, float]:
399
+ """
400
+ Returns map[po_line_id] -> received_qty summed across all saved invoices for a PO.
401
+ Prefers deterministic matching via invoice_lines.matched_po_line_id.
402
+ Excludes duplicates (invoices.duplicate_flag=1).
403
+ """
404
+ rows = conn.execute(
405
+ """
406
+ SELECT
407
+ l.matched_po_line_id AS po_line_id,
408
+ sum(coalesce(l.qty, 0)) AS received_qty
409
+ FROM invoices i
410
+ JOIN invoice_lines l ON l.invoice_id = i.id
411
+ WHERE i.po_number = ?
412
+ AND i.duplicate_flag = 0
413
+ AND l.matched_po_line_id IS NOT NULL
414
+ AND l.matched_po_line_id != ''
415
+ GROUP BY l.matched_po_line_id
416
+ """,
417
+ (po_number,),
418
+ ).fetchall()
419
+ out: dict[str, float] = {}
420
+ for r in rows:
421
+ out[str(r["po_line_id"])] = float(r["received_qty"] or 0.0)
422
+ return out
423
+
424
+
425
+ def get_history_context(conn: sqlite3.Connection, *, po_number: str, supplier: str | None = None, limit: int = 25) -> dict[str, Any]:
426
+ """
427
+ Fetches prior invoices + their lines for agent context.
428
+ This function does NOT make any decisions; it only provides evidence.
429
+ """
430
+ where = "po_number = ?"
431
+ params: list[Any] = [po_number]
432
+ if supplier:
433
+ where += " AND lower(coalesce(supplier,'')) = lower(?)"
434
+ params.append(supplier)
435
+
436
+ inv_rows = conn.execute(
437
+ f"""
438
+ SELECT id, processed_at, invoice_number, supplier, po_number, invoice_total, file_sha256, match_status, decision_engine
439
+ FROM invoices
440
+ WHERE {where}
441
+ ORDER BY processed_at DESC
442
+ LIMIT ?
443
+ """,
444
+ (*params, int(limit)),
445
+ ).fetchall()
446
+ invoices = [dict(r) for r in inv_rows]
447
+
448
+ inv_ids = [r["id"] for r in invoices]
449
+ lines: list[dict[str, Any]] = []
450
+ if inv_ids:
451
+ q_marks = ",".join(["?"] * len(inv_ids))
452
+ line_rows = conn.execute(
453
+ f"""
454
+ SELECT invoice_id, sku, description, qty, unit_price, line_total, matched_po_line_id
455
+ FROM invoice_lines
456
+ WHERE invoice_id IN ({q_marks})
457
+ """,
458
+ inv_ids,
459
+ ).fetchall()
460
+ lines = [dict(r) for r in line_rows]
461
+
462
+ return {"invoices": invoices, "lines": lines}
463
+
464
+
ap_agent1/document.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ import os
6
+ import time
7
+ from typing import Any
8
+
9
+ import fitz # PyMuPDF
10
+ import requests
11
+ from pdfminer.high_level import extract_text
12
+
13
+ from ap_agent1.config import MAX_INVOICE_TEXT_CHARS
14
+ from ap_agent1.utils import norm_space
15
+
16
+
17
+ def _pdf_to_png_pages(pdf_bytes: bytes, *, max_pages: int = 3, zoom: float = 2.0) -> list[bytes]:
18
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
19
+ out: list[bytes] = []
20
+ for i in range(min(max_pages, doc.page_count)):
21
+ page = doc.load_page(i)
22
+ mat = fitz.Matrix(zoom, zoom)
23
+ pix = page.get_pixmap(matrix=mat, alpha=False)
24
+ out.append(pix.tobytes("png"))
25
+ doc.close()
26
+ return out
27
+
28
+
29
+ def _azure_di_read(*, data: bytes, file_name: str) -> dict[str, Any] | None:
30
+ """
31
+ OCR via Azure Document Intelligence (prebuilt-read).
32
+
33
+ Requires:
34
+ AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
35
+ AZURE_DOCUMENT_INTELLIGENCE_KEY
36
+
37
+ Returns:
38
+ {
39
+ "provider": "azure_document_intelligence",
40
+ "model": "prebuilt-read",
41
+ "text": "...",
42
+ "result": {...raw analyzeResult...}
43
+ }
44
+ """
45
+ endpoint = (os.environ.get("AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT") or "").strip().rstrip("/")
46
+ key = (os.environ.get("AZURE_DOCUMENT_INTELLIGENCE_KEY") or "").strip()
47
+ if not endpoint or not key:
48
+ return None
49
+
50
+ # NOTE: API versions change; this is a commonly supported recent version for the /documentintelligence path.
51
+ api_version = (os.environ.get("AZURE_DOCUMENT_INTELLIGENCE_API_VERSION") or "2024-11-30").strip()
52
+
53
+ url = f"{endpoint}/documentintelligence/documentModels/prebuilt-read:analyze?api-version={api_version}"
54
+ headers = {
55
+ "Ocp-Apim-Subscription-Key": key,
56
+ # service will infer from bytes; keep it generic
57
+ "Content-Type": "application/octet-stream",
58
+ }
59
+
60
+ resp = requests.post(url, headers=headers, data=data, timeout=30)
61
+ if resp.status_code not in (202, 200):
62
+ # Return a small error payload for UI/debug (do not throw).
63
+ return {
64
+ "provider": "azure_document_intelligence",
65
+ "model": "prebuilt-read",
66
+ "error": f"OCR request failed ({resp.status_code})",
67
+ "error_body": (resp.text or "")[:400],
68
+ }
69
+
70
+ # Synchronous responses may include JSON directly; async uses Operation-Location.
71
+ if resp.status_code == 200:
72
+ payload = resp.json()
73
+ analyze = payload.get("analyzeResult") or payload
74
+ content = analyze.get("content") or ""
75
+ return {"provider": "azure_document_intelligence", "model": "prebuilt-read", "text": norm_space(str(content)), "result": analyze}
76
+
77
+ op_url = resp.headers.get("operation-location") or resp.headers.get("Operation-Location") or ""
78
+ if not op_url:
79
+ return {"provider": "azure_document_intelligence", "model": "prebuilt-read", "error": "Missing Operation-Location header"}
80
+
81
+ # Poll until completion (bounded).
82
+ deadline = time.time() + 25.0
83
+ while time.time() < deadline:
84
+ r2 = requests.get(op_url, headers={"Ocp-Apim-Subscription-Key": key}, timeout=15)
85
+ try:
86
+ j = r2.json()
87
+ except Exception:
88
+ j = {}
89
+ status = str(j.get("status") or "").lower()
90
+ if status in ("succeeded", "failed"):
91
+ if status == "failed":
92
+ return {
93
+ "provider": "azure_document_intelligence",
94
+ "model": "prebuilt-read",
95
+ "error": "OCR failed",
96
+ "result": j,
97
+ }
98
+ analyze = j.get("analyzeResult") or {}
99
+ content = analyze.get("content") or ""
100
+ return {"provider": "azure_document_intelligence", "model": "prebuilt-read", "text": norm_space(str(content)), "result": analyze}
101
+ time.sleep(0.6)
102
+
103
+ return {"provider": "azure_document_intelligence", "model": "prebuilt-read", "error": "OCR timeout"}
104
+
105
+
106
+ def extract_invoice_inputs(file_name: str, data: bytes) -> dict[str, Any]:
107
+ """
108
+ Produces agent-ready inputs:
109
+ - invoice_text: best-effort extracted text (may be empty for scanned docs)
110
+ - invoice_images: list of PNG bytes for vision grounding (PDF pages or the image itself)
111
+ """
112
+ name = (file_name or "").lower()
113
+
114
+ # Images: pass through directly + OCR if configured.
115
+ if name.endswith((".png", ".jpg", ".jpeg", ".webp")):
116
+ ocr = _azure_di_read(data=data, file_name=file_name) or None
117
+ txt = norm_space(str((ocr or {}).get("text") or ""))[:MAX_INVOICE_TEXT_CHARS]
118
+ return {"invoice_text": txt, "invoice_images": [data], "ocr": ocr}
119
+
120
+ # PDF: extract embedded text + also render pages to images; if embedded text is weak, OCR.
121
+ if name.endswith(".pdf"):
122
+ # Reduce latency by limiting number of rendered pages / zoom; configurable via env.
123
+ try:
124
+ max_pages = int((os.environ.get("AP_INVOICE_IMAGE_PAGES") or "2").strip())
125
+ except Exception:
126
+ max_pages = 2
127
+ try:
128
+ zoom = float((os.environ.get("AP_INVOICE_IMAGE_ZOOM") or "1.6").strip())
129
+ except Exception:
130
+ zoom = 1.6
131
+
132
+ try:
133
+ txt = extract_text(io.BytesIO(data)) or ""
134
+ except Exception:
135
+ txt = ""
136
+ txt = norm_space(txt)[:MAX_INVOICE_TEXT_CHARS]
137
+
138
+ # If text is tiny, it's likely scanned → rely on images.
139
+ pages = _pdf_to_png_pages(data, max_pages=max_pages, zoom=zoom)
140
+ ocr: dict[str, Any] | None = None
141
+ if len(txt) < 200:
142
+ # Prefer real OCR for scanned docs (if configured).
143
+ ocr = _azure_di_read(data=data, file_name=file_name) or None
144
+ ocr_txt = norm_space(str((ocr or {}).get("text") or ""))[:MAX_INVOICE_TEXT_CHARS]
145
+ if ocr_txt:
146
+ txt = ocr_txt
147
+ else:
148
+ txt = ""
149
+ return {"invoice_text": txt, "invoice_images": pages, "ocr": ocr}
150
+
151
+ # DOCX/TXT (optional): keep existing behavior via text-only.
152
+ return {"invoice_text": "", "invoice_images": [], "ocr": None}
153
+
154
+
155
+ def png_bytes_to_data_url(png_bytes: bytes) -> str:
156
+ b64 = base64.b64encode(png_bytes).decode("ascii")
157
+ return f"data:image/png;base64,{b64}"
158
+
159
+
ap_agent1/invoice.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from docx import Document
9
+ from pdfminer.high_level import extract_text
10
+
11
+ from ap_agent1.utils import norm_space, to_float
12
+
13
+
14
+ _RE_INV_NO = re.compile(r"(invoice\s*(number|no|#)\s*[:\-]?\s*)(?P<val>[A-Z0-9][A-Z0-9\-\/]{2,})", re.IGNORECASE)
15
+ _RE_PO_NO = re.compile(r"(po|p\.o\.|purchase\s*order)\s*(number|no|#)?\s*[:\-]?\s*(?P<val>[A-Z0-9][A-Z0-9\-\/]{2,})", re.IGNORECASE)
16
+ _RE_TOTAL = re.compile(
17
+ r"(?:(total\s*(amount)?|amount\s*due|grand\s*total)\s*[:\-]?\s*)(?P<val>\$?\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?)",
18
+ re.IGNORECASE,
19
+ )
20
+
21
+
22
+ def extract_invoice_text(file_name: str, data: bytes) -> str:
23
+ name = (file_name or "").lower()
24
+ if name.endswith(".pdf"):
25
+ return norm_space(extract_text(io.BytesIO(data)))
26
+ if name.endswith(".docx"):
27
+ doc = Document(io.BytesIO(data))
28
+ text = "\n".join(p.text for p in doc.paragraphs)
29
+ return norm_space(text)
30
+ # txt fallback
31
+ try:
32
+ return norm_space(data.decode("utf-8", errors="ignore"))
33
+ except Exception:
34
+ return norm_space(data.decode(errors="ignore"))
35
+
36
+
37
+ def _guess_supplier(text: str) -> str:
38
+ # Heuristic: first non-trivial line, excluding common headers.
39
+ lines = [l.strip() for l in text.splitlines() if l.strip()]
40
+ for l in lines[:12]:
41
+ if len(l) < 3:
42
+ continue
43
+ if re.search(r"\b(invoice|bill\s*to|ship\s*to|purchase\s*order|po\s*#|amount\s*due)\b", l, re.IGNORECASE):
44
+ continue
45
+ # Avoid lines that are mostly numbers.
46
+ if sum(ch.isdigit() for ch in l) > max(3, len(l) // 2):
47
+ continue
48
+ return l[:120]
49
+ return ""
50
+
51
+
52
+ def parse_invoice_fields(text: str) -> dict[str, str]:
53
+ text_n = text or ""
54
+ inv = ""
55
+ m = _RE_INV_NO.search(text_n)
56
+ if m:
57
+ inv = m.group("val").strip()
58
+
59
+ po = ""
60
+ m = _RE_PO_NO.search(text_n)
61
+ if m:
62
+ po = m.group("val").strip()
63
+
64
+ total = ""
65
+ m = _RE_TOTAL.search(text_n)
66
+ if m:
67
+ total = m.group("val").strip()
68
+
69
+ currency = "USD" if "$" in total else ""
70
+ supplier = _guess_supplier(text_n)
71
+
72
+ return {
73
+ "invoice_number": inv,
74
+ "po_number": po,
75
+ "total_amount": total,
76
+ "currency": currency,
77
+ "supplier": supplier,
78
+ }
79
+
80
+
81
+ def _parse_line_by_trailing_numbers(line: str) -> dict[str, Any] | None:
82
+ """
83
+ Best-effort extractor for common invoice line formats.
84
+
85
+ We look for at least 2 numeric tokens at the end: qty and unit_price/total.
86
+ """
87
+ raw = line.strip()
88
+ if len(raw) < 6:
89
+ return None
90
+
91
+ # Strip currency symbols and commas for numeric detection.
92
+ clean = raw.replace("$", "").replace("₹", "").replace(",", "")
93
+ tokens = clean.split()
94
+
95
+ num_idx = []
96
+ for i, t in enumerate(tokens):
97
+ if re.fullmatch(r"\d+(?:\.\d+)?", t):
98
+ num_idx.append(i)
99
+
100
+ if len(num_idx) < 2:
101
+ return None
102
+
103
+ # Take last numeric tokens as qty/unit/total candidates.
104
+ last_nums = num_idx[-3:] if len(num_idx) >= 3 else num_idx[-2:]
105
+ nums = [tokens[i] for i in last_nums]
106
+
107
+ qty = to_float(nums[0]) if len(nums) == 3 else to_float(nums[0])
108
+ unit_price = to_float(nums[1]) if len(nums) == 3 else None
109
+ line_total = to_float(nums[2]) if len(nums) == 3 else to_float(nums[1])
110
+
111
+ if qty is None or qty <= 0:
112
+ return None
113
+
114
+ # Build sku/desc from non-numeric prefix.
115
+ prefix_end = last_nums[0]
116
+ prefix_tokens = raw.split()[:prefix_end]
117
+ if not prefix_tokens:
118
+ return None
119
+
120
+ sku = prefix_tokens[0]
121
+ desc = " ".join(prefix_tokens[1:]).strip()
122
+ if not desc:
123
+ desc = sku
124
+
125
+ # Reject header lines.
126
+ if re.search(r"\b(qty|quantity|amount|total|unit\s*price|price)\b", raw, re.IGNORECASE):
127
+ if re.search(r"\bsku\b", raw, re.IGNORECASE):
128
+ return None
129
+
130
+ return {"sku": sku[:64], "description": desc[:240], "qty": qty, "unit_price": unit_price, "line_total": line_total}
131
+
132
+
133
+ def parse_invoice_lines(text: str) -> list[dict[str, Any]]:
134
+ lines = []
135
+ for raw_line in (text or "").splitlines():
136
+ l = raw_line.strip()
137
+ if not l:
138
+ continue
139
+ if len(l) > 300:
140
+ continue
141
+ parsed = _parse_line_by_trailing_numbers(l)
142
+ if parsed:
143
+ lines.append(parsed)
144
+
145
+ # De-dup identical lines (common in PDF extraction).
146
+ seen = set()
147
+ out = []
148
+ for r in lines:
149
+ key = (r.get("sku"), r.get("description"), r.get("qty"), r.get("unit_price"), r.get("line_total"))
150
+ if key in seen:
151
+ continue
152
+ seen.add(key)
153
+ out.append(r)
154
+
155
+ return out[:50]
156
+
157
+
ap_agent1/po.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from typing import Any
5
+
6
+ import pandas as pd
7
+
8
+ from ap_agent1.db import get_conn
9
+ from ap_agent1.utils import norm_key, to_float
10
+
11
+
12
+ _COL_SYNONYMS: dict[str, list[str]] = {
13
+ "po_number": ["po_number", "po", "purchase_order", "purchase_order_number", "po_no", "ponumber"],
14
+ "sku": ["sku", "item", "item_code", "material", "material_code", "part", "part_number", "product_code"],
15
+ "description": ["description", "item_description", "material_description", "desc", "product_description"],
16
+ "qty_ordered": ["qty_ordered", "quantity", "qty", "ordered_qty", "order_qty", "po_qty"],
17
+ "unit_price": ["unit_price", "price", "unitcost", "unit_cost", "rate"],
18
+ "supplier": ["supplier", "vendor", "supplier_name", "vendor_name"],
19
+ }
20
+
21
+
22
+ def _find_col(cols: list[str], candidates: list[str]) -> str | None:
23
+ norm = {norm_key(c): c for c in cols}
24
+ for cand in candidates:
25
+ k = norm_key(cand)
26
+ if k in norm:
27
+ return norm[k]
28
+ return None
29
+
30
+
31
+ def load_po_csv(file_like: io.BytesIO) -> tuple[pd.DataFrame, str | None]:
32
+ df = pd.read_csv(file_like)
33
+ cols = list(df.columns)
34
+
35
+ mapping: dict[str, str] = {}
36
+ for canonical, synonyms in _COL_SYNONYMS.items():
37
+ found = _find_col(cols, synonyms)
38
+ if found:
39
+ mapping[canonical] = found
40
+
41
+ if "po_number" not in mapping:
42
+ raise ValueError("PO CSV missing required column: po_number (or synonym).")
43
+ if "qty_ordered" not in mapping:
44
+ raise ValueError("PO CSV missing required column: qty_ordered (or synonym).")
45
+ if "sku" not in mapping and "description" not in mapping:
46
+ raise ValueError("PO CSV must include sku or description (or synonyms).")
47
+
48
+ out = pd.DataFrame()
49
+ out["po_number"] = df[mapping["po_number"]].astype(str).str.strip()
50
+ out["sku"] = df[mapping["sku"]].astype(str).str.strip() if "sku" in mapping else ""
51
+ out["description"] = df[mapping["description"]].astype(str).str.strip() if "description" in mapping else ""
52
+ out["qty_ordered"] = df[mapping["qty_ordered"]].apply(to_float)
53
+ out["unit_price"] = df[mapping["unit_price"]].apply(to_float) if "unit_price" in mapping else None
54
+ out["supplier"] = df[mapping["supplier"]].astype(str).str.strip() if "supplier" in mapping else ""
55
+
56
+ out = out.dropna(subset=["po_number", "qty_ordered"])
57
+ out = out[out["po_number"].astype(str).str.len() > 0]
58
+ out["qty_ordered"] = out["qty_ordered"].fillna(0.0)
59
+
60
+ # Pick a hint (first PO number) for auto-filling UI.
61
+ po_hint = None
62
+ if not out.empty:
63
+ po_hint = str(out["po_number"].iloc[0])
64
+
65
+ return out, po_hint
66
+
67
+
68
+ def upsert_po_lines(conn, po_df: pd.DataFrame, source_hash: str) -> None:
69
+ """
70
+ For demo simplicity: delete existing rows for the PO(s) in the upload, then insert fresh.
71
+ """
72
+ po_numbers = sorted(set(po_df["po_number"].astype(str).tolist()))
73
+ for po_number in po_numbers:
74
+ conn.execute("DELETE FROM po_lines WHERE po_number = ?", (po_number,))
75
+
76
+ rows: list[dict[str, Any]] = po_df.to_dict(orient="records")
77
+ for r in rows:
78
+ conn.execute(
79
+ """
80
+ INSERT INTO po_lines(id, po_number, sku, description, qty_ordered, unit_price, supplier, source_hash)
81
+ VALUES(?,?,?,?,?,?,?,?)
82
+ """,
83
+ (
84
+ f"po_{source_hash[:10]}_{len(r.get('sku',''))}_{abs(hash((r.get('po_number'), r.get('sku'), r.get('description'))))%10_000_000}",
85
+ str(r.get("po_number") or "").strip(),
86
+ (r.get("sku") or "").strip() or None,
87
+ (r.get("description") or "").strip() or None,
88
+ float(r.get("qty_ordered") or 0.0),
89
+ r.get("unit_price"),
90
+ (r.get("supplier") or "").strip() or None,
91
+ source_hash,
92
+ ),
93
+ )
94
+ conn.commit()
95
+
96
+
97
+ def read_csv_text(file_like: io.BytesIO) -> str:
98
+ """
99
+ Reads uploaded CSV bytes into text for the agent (best-effort encoding).
100
+ """
101
+ raw = file_like.getvalue() if hasattr(file_like, "getvalue") else file_like.read()
102
+ for enc in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):
103
+ try:
104
+ return raw.decode(enc)
105
+ except Exception:
106
+ continue
107
+ return raw.decode(errors="ignore")
108
+
109
+
110
+ def read_tabular_text(file_name: str, data: bytes) -> str:
111
+ """
112
+ Reads CSV or Excel (XLSX/XLS) into a single text payload for the agent.
113
+ For Excel, includes multiple sheets with clear separators.
114
+ """
115
+ name = (file_name or "").lower()
116
+ if name.endswith(".csv"):
117
+ return read_csv_text(io.BytesIO(data))
118
+
119
+ if name.endswith((".xlsx", ".xls")):
120
+ # Read all sheets
121
+ bio = io.BytesIO(data)
122
+ try:
123
+ sheets = pd.read_excel(bio, sheet_name=None) # engine auto
124
+ except Exception:
125
+ # Retry with common engines
126
+ bio.seek(0)
127
+ engine = "openpyxl" if name.endswith(".xlsx") else "xlrd"
128
+ sheets = pd.read_excel(bio, sheet_name=None, engine=engine)
129
+
130
+ def _clean_sheet(df: pd.DataFrame) -> pd.DataFrame:
131
+ # Drop fully empty rows/cols
132
+ df = df.dropna(axis=0, how="all").dropna(axis=1, how="all")
133
+ if df.empty:
134
+ return df
135
+ # If columns are mostly Unnamed and first row looks like headers, promote it.
136
+ unnamed = sum(str(c).lower().startswith("unnamed") for c in df.columns)
137
+ if unnamed >= max(1, int(len(df.columns) * 0.5)) and len(df) >= 2:
138
+ first = df.iloc[0].tolist()
139
+ # Heuristic: header row has many non-numeric strings
140
+ non_empty = [x for x in first if str(x).strip() and str(x).strip().lower() != "nan"]
141
+ if len(non_empty) >= max(2, int(len(df.columns) * 0.4)):
142
+ df2 = df.copy()
143
+ df2.columns = [str(x).strip() for x in first]
144
+ df2 = df2.iloc[1:].reset_index(drop=True)
145
+ df2 = df2.dropna(axis=0, how="all").dropna(axis=1, how="all")
146
+ return df2
147
+ return df.reset_index(drop=True)
148
+
149
+ parts: list[str] = []
150
+ for sheet_name, df in sheets.items():
151
+ if df is None:
152
+ continue
153
+ df = _clean_sheet(df)
154
+ if df.empty:
155
+ continue
156
+ # Bound size: header + first 200 rows
157
+ df2 = df.head(300).copy()
158
+ parts.append(f"--- SHEET: {sheet_name} ---")
159
+ parts.append(df2.to_csv(index=False))
160
+ return "\n".join(parts).strip()
161
+
162
+ # Unknown: try decode as text
163
+ try:
164
+ return data.decode("utf-8", errors="ignore")
165
+ except Exception:
166
+ return ""
167
+
168
+
ap_agent1/suppliers.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pandas as pd
6
+
7
+ from ap_agent1.utils import norm_space
8
+
9
+
10
+ SUPPLIERS_CSV = "data/suppliers.csv"
11
+
12
+
13
+ def ensure_default_suppliers() -> None:
14
+ p = Path(SUPPLIERS_CSV)
15
+ p.parent.mkdir(parents=True, exist_ok=True)
16
+ if p.exists():
17
+ return
18
+ p.write_text(
19
+ "supplier_id,supplier_name,tax_id\n"
20
+ "SUP-001,Acme Industrial Supplies,TX-ACME-001\n"
21
+ "SUP-002,Northwind Traders,TX-NW-002\n"
22
+ "SUP-003,Contoso Components,TX-CON-003\n"
23
+ "SUP-004,Fabrikam Manufacturing,TX-FAB-004\n"
24
+ "SUP-005,Global Office Supplies Ltd.,TX-GOS-005\n",
25
+ encoding="utf-8",
26
+ )
27
+
28
+
29
+ def load_suppliers() -> pd.DataFrame:
30
+ ensure_default_suppliers()
31
+ df = pd.read_csv(SUPPLIERS_CSV)
32
+ if "supplier_name" not in df.columns:
33
+ raise ValueError("Suppliers CSV must contain 'supplier_name' column.")
34
+ df["supplier_name"] = df["supplier_name"].astype(str).map(norm_space)
35
+ return df
36
+
37
+
ap_agent1/utils.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import re
5
+ from typing import Any
6
+
7
+
8
+ def sha256_bytes(data: bytes) -> str:
9
+ return hashlib.sha256(data).hexdigest()
10
+
11
+
12
+ def norm_space(s: str) -> str:
13
+ return re.sub(r"\s+", " ", (s or "").strip())
14
+
15
+
16
+ def norm_key(s: str) -> str:
17
+ s = norm_space(s).lower()
18
+ s = re.sub(r"[^a-z0-9]+", "_", s)
19
+ return s.strip("_")
20
+
21
+
22
+ def to_float(v: Any) -> float | None:
23
+ if v is None:
24
+ return None
25
+ if isinstance(v, (int, float)):
26
+ return float(v)
27
+ s = str(v).strip()
28
+ if not s:
29
+ return None
30
+ s = s.replace(",", "")
31
+ try:
32
+ return float(s)
33
+ except ValueError:
34
+ # Try extracting the first numeric token (handles values like "6 EA", "$3099.59", etc.)
35
+ m = re.search(r"-?\d+(?:\.\d+)?", s)
36
+ if not m:
37
+ return None
38
+ try:
39
+ return float(m.group(0))
40
+ except ValueError:
41
+ return None
42
+
43
+
44
+ def clamp01(x: float) -> float:
45
+ return 0.0 if x < 0 else 1.0 if x > 1 else x
46
+
47
+
app.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Spaces entry point.
3
+ This file is required for Hugging Face Spaces to recognize the app.
4
+ The actual app is in backend1/main.py
5
+ """
6
+ import os
7
+ import sys
8
+
9
+ # Add the current directory to Python path
10
+ sys.path.insert(0, os.path.dirname(__file__))
11
+
12
+ # Import and run the FastAPI app
13
+ from backend1.main import app
14
+
15
+ # Hugging Face Spaces expects the app to be available as 'app'
16
+ __all__ = ["app"]
17
+
backend1/__pycache__/main.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
backend1/main.py ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import json
4
+ import re
5
+ import logging
6
+ import time
7
+ from collections import Counter
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import pandas as pd
12
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.responses import FileResponse, HTMLResponse
15
+ from fastapi.staticfiles import StaticFiles
16
+
17
+ try:
18
+ # Load local .env for dev convenience (production should use real environment variables)
19
+ from dotenv import load_dotenv # type: ignore
20
+
21
+ load_dotenv()
22
+ except Exception:
23
+ pass
24
+
25
+ from ap_agent1.ai_agent import ai_ap_agent_process, ai_enabled, ai_normalize_po_csv
26
+ from ap_agent1.db import (
27
+ clear_all,
28
+ get_conn,
29
+ get_history_context,
30
+ get_po_lines,
31
+ get_received_qty_by_po_line_id,
32
+ init_db,
33
+ invoice_exists_by_business_key,
34
+ invoice_exists_by_sha,
35
+ insert_invoice_run,
36
+ load_invoice_detail,
37
+ search_invoices,
38
+ )
39
+ from ap_agent1.document import extract_invoice_inputs, png_bytes_to_data_url
40
+ from ap_agent1.invoice import parse_invoice_fields
41
+ from ap_agent1.po import read_tabular_text
42
+ from ap_agent1.suppliers import load_suppliers
43
+ from ap_agent1.utils import sha256_bytes, to_float
44
+
45
+
46
+ logger = logging.getLogger("apdemo.backend1")
47
+ if not logger.handlers:
48
+ logging.basicConfig(level=logging.INFO)
49
+
50
+ BUILD_ID = f"backend1-{int(Path(__file__).stat().st_mtime)}"
51
+
52
+ def _norm_po(s: str | None) -> str:
53
+ """
54
+ Normalize PO identifiers to a stable format like `PO-1008`.
55
+ Handles common variants: `po 1008`, `PO_1008`, `po-1008`, etc.
56
+ """
57
+ v = (s or "").strip().upper()
58
+ if not v:
59
+ return ""
60
+ v = v.replace("_", "-").replace(" ", "-")
61
+ # normalize "PO--1008" or "PO---1008"
62
+ v = re.sub(r"-{2,}", "-", v)
63
+ # normalize "PO1008" -> "PO-1008"
64
+ v = re.sub(r"^PO(\d+)$", r"PO-\1", v)
65
+ # normalize "PO- 1008" etc (after space->- above)
66
+ v = re.sub(r"^PO-(\d+)$", r"PO-\1", v)
67
+ return v
68
+
69
+ def _norm_name(s: str | None) -> str:
70
+ return (s or "").strip()
71
+
72
+
73
+ def _norm_key(s: str | None) -> str:
74
+ return (s or "").strip().lower()
75
+
76
+ def _normalize_score(v: Any) -> float | None:
77
+ """
78
+ Normalize score to 0..1. Accepts either 0..1 or 0..100 style values.
79
+ """
80
+ f = to_float(v)
81
+ if f is None:
82
+ return None
83
+ # Handle % style scores
84
+ if f > 1.0 and f <= 100.0:
85
+ f = f / 100.0
86
+ # Clamp
87
+ if f < 0:
88
+ return 0.0
89
+ if f > 1.0:
90
+ return 1.0
91
+ return float(f)
92
+
93
+ def _confidence_score(*, supplier_match_score: Any, line_results: list[dict[str, Any]]) -> float | None:
94
+ """
95
+ Best-effort overall confidence for UI visibility (0..1).
96
+ Combines supplier validation confidence + average line match confidence when available.
97
+ """
98
+ s = _normalize_score(supplier_match_score)
99
+ scores: list[float] = []
100
+ for r in line_results or []:
101
+ v = _normalize_score(r.get("match_score"))
102
+ if v is not None:
103
+ scores.append(v)
104
+ line_avg = (sum(scores) / len(scores)) if scores else None
105
+ if line_avg is not None and s is not None:
106
+ return 0.7 * line_avg + 0.3 * s
107
+ return line_avg if line_avg is not None else s
108
+
109
+ def _extractions_count(*, invoice_fields: dict[str, Any], line_results: list[dict[str, Any]]) -> int:
110
+ """
111
+ Count extracted units (header fields present + extracted line items).
112
+ """
113
+ header_count = 0
114
+ for k in ["invoice_number", "supplier", "po_number", "total_amount", "currency"]:
115
+ if str((invoice_fields or {}).get(k) or "").strip():
116
+ header_count += 1
117
+ return int(header_count + len(line_results or []))
118
+
119
+
120
+ def _compute_backorders(
121
+ *,
122
+ po_db_lines: list[dict[str, Any]],
123
+ received_before: dict[str, float],
124
+ current_invoice_qty_by_po_line_id: dict[str, float] | None = None,
125
+ ) -> list[dict[str, Any]]:
126
+ """
127
+ Deterministic backorder breakdown per PO line.
128
+ remaining is computed AFTER applying the current invoice quantities (if provided).
129
+ """
130
+ cur = current_invoice_qty_by_po_line_id or {}
131
+ out: list[dict[str, Any]] = []
132
+ for pl in po_db_lines or []:
133
+ po_line_id = str(pl.get("id") or "")
134
+ qty_ordered = to_float(pl.get("qty_ordered")) or 0.0
135
+ rb = float(received_before.get(po_line_id, 0.0) or 0.0)
136
+ ra = rb + float(cur.get(po_line_id, 0.0) or 0.0)
137
+ remaining = qty_ordered - ra
138
+ if remaining > 1e-9:
139
+ out.append(
140
+ {
141
+ "po_line_id": po_line_id,
142
+ "sku": pl.get("sku") or "",
143
+ "description": pl.get("description") or "",
144
+ "qty_ordered": qty_ordered,
145
+ "received_before": rb,
146
+ "received_after": ra,
147
+ "remaining": remaining,
148
+ }
149
+ )
150
+ # stable ordering: most remaining first
151
+ out.sort(key=lambda r: float(r.get("remaining") or 0.0), reverse=True)
152
+ return out
153
+
154
+
155
+ def _guess_po(*, invoice_text: str, file_name: str | None) -> str | None:
156
+ """
157
+ Best-effort PO number extraction from invoice text and/or filename.
158
+ We prefer filename as a fallback because some PDFs don't have clean text extraction.
159
+ """
160
+ candidates: list[str] = []
161
+
162
+ def collect(s: str) -> None:
163
+ s = (s or "").strip()
164
+ if not s:
165
+ return
166
+ # Normalize "PO 1008" -> "PO-1008"
167
+ s = re.sub(r"\bPO\s+(\d+)\b", r"PO-\1", s, flags=re.IGNORECASE)
168
+ # Normalize casing
169
+ s = s.upper()
170
+ candidates.append(s)
171
+
172
+ t = (invoice_text or "").strip()
173
+ if t:
174
+ for pat in [
175
+ r"\bPO[-\s]*\d{3,}\b",
176
+ r"\bPURCHASE\s+ORDER[:\s]*([A-Z0-9-]{4,})\b",
177
+ ]:
178
+ m = re.search(pat, t, flags=re.IGNORECASE)
179
+ if not m:
180
+ continue
181
+ s = m.group(0) if m.lastindex is None else m.group(1)
182
+ collect(s)
183
+
184
+ fn = (file_name or "").strip()
185
+ if fn:
186
+ # Common pattern in filenames: "...PO-1008..." or "...PO_1008..."
187
+ # NOTE: avoid \b here because underscores are "word characters" and can prevent word boundaries.
188
+ m = re.search(r"PO[-_ ]?\d{3,}", fn, flags=re.IGNORECASE)
189
+ if m:
190
+ collect(m.group(0).replace("_", "-").replace(" ", "-"))
191
+
192
+ if not candidates:
193
+ return None
194
+
195
+ # Prefer earliest occurrence (stable) rather than lexical order.
196
+ # If multiple candidates are found, return the first one collected.
197
+ return candidates[0]
198
+
199
+
200
+ def _po_from_filename(file_name: str | None) -> str | None:
201
+ """
202
+ Strong signal: if the user-provided filename contains PO-xxxx, trust it.
203
+ This avoids cases where PDF text extraction contains other PO-like strings.
204
+ """
205
+ fn = (file_name or "").strip()
206
+ if not fn:
207
+ return None
208
+ m = re.search(r"PO[-_ ]?\d{3,}", fn, flags=re.IGNORECASE)
209
+ if not m:
210
+ return None
211
+ s = m.group(0).replace("_", "-").replace(" ", "-").strip().upper()
212
+ s = re.sub(r"\bPO\s+(\d+)\b", r"PO-\1", s, flags=re.IGNORECASE).upper()
213
+ return s
214
+
215
+
216
+ def _po_rows_for_invoice(po_rows: list[dict[str, Any]], invoice_po: str | None) -> list[dict[str, Any]]:
217
+ inv_po = _norm_po(invoice_po)
218
+ if not inv_po:
219
+ return po_rows
220
+ filtered = [r for r in po_rows if _norm_po(str(r.get("po_number", ""))) == inv_po]
221
+ return filtered or po_rows
222
+
223
+
224
+ def _single_po_number(po_lines: list[dict[str, Any]]) -> str | None:
225
+ vals = []
226
+ for r in po_lines or []:
227
+ v = _norm_po(str(r.get("po_number", "")))
228
+ if v:
229
+ vals.append(v)
230
+ uniq = sorted(set(vals))
231
+ return uniq[0] if len(uniq) == 1 else None
232
+
233
+
234
+ def _pick_po_number_ctx(
235
+ *,
236
+ po_lines: list[dict[str, Any]],
237
+ po_header: dict[str, Any],
238
+ po_number_candidates: list[Any],
239
+ invoice_po_hint: str | None,
240
+ po_file_name: str | None,
241
+ ) -> str:
242
+ """
243
+ Choose the PO number we should use for matching / storage.
244
+ Priority:
245
+ 1) If PO file has a single PO → trust it
246
+ 2) If PO filename contains PO-#### → trust it (when present in the uploaded PO)
247
+ 3) PO header PO number (when present in the uploaded PO)
248
+ 4) Invoice hint if it matches a PO in the uploaded file
249
+ 5) Most-common PO number in uploaded file
250
+ 6) Fallback to first candidate
251
+ """
252
+ only_po = _single_po_number(po_lines)
253
+ if only_po:
254
+ return only_po
255
+
256
+ vals = [_norm_po(str(r.get("po_number", ""))) for r in (po_lines or [])]
257
+ vals = [v for v in vals if v]
258
+ uniq = set(vals)
259
+
260
+ po_file_hint = _po_from_filename(po_file_name)
261
+ if po_file_hint and (not uniq or po_file_hint in uniq):
262
+ return po_file_hint
263
+
264
+ hdr = _norm_po(str((po_header or {}).get("po_number") or ""))
265
+ if hdr and (not uniq or hdr in uniq):
266
+ return hdr
267
+
268
+ inv = _norm_po(invoice_po_hint)
269
+ if inv and inv in uniq:
270
+ return inv
271
+
272
+ if vals:
273
+ return Counter(vals).most_common(1)[0][0]
274
+
275
+ # last resort: candidate list
276
+ for c in po_number_candidates or []:
277
+ v = _norm_po(str(c))
278
+ if v:
279
+ return v
280
+ return ""
281
+
282
+ def _supplier_master_from_po(po_lines: list[dict[str, Any]], po_header: dict[str, Any]) -> list[dict[str, Any]]:
283
+ """
284
+ Build an "approved supplier list" from the uploaded PO itself (Vendor Name / Supplier).
285
+ This avoids requiring a pre-maintained data/suppliers.csv for demo usage.
286
+ """
287
+ names: list[str] = []
288
+ header_supplier = _norm_name(str(po_header.get("supplier") or ""))
289
+ if header_supplier:
290
+ names.append(header_supplier)
291
+ for r in po_lines or []:
292
+ s = _norm_name(str(r.get("supplier") or ""))
293
+ if s:
294
+ names.append(s)
295
+ # dedupe while preserving order
296
+ seen: set[str] = set()
297
+ uniq: list[str] = []
298
+ for n in names:
299
+ key = n.lower()
300
+ if key in seen:
301
+ continue
302
+ seen.add(key)
303
+ uniq.append(n)
304
+ return [{"supplier_name": n} for n in uniq]
305
+
306
+
307
+ def _extract_po_lines_from_embedded_json(po_bytes: bytes) -> list[dict[str, Any]]:
308
+ """
309
+ Fallback parser for exports like:
310
+ 56,PO-1008,Global Office Supplies Ltd.,2025-09-01,3099.59,"[{...}]"
311
+
312
+ Many such files have **no header row**, so we parse by position:
313
+ col1 = po_number, col2 = supplier/vendor, last col = JSON items
314
+ """
315
+ out: list[dict[str, Any]] = []
316
+
317
+ # 1) Try headerless read (most common for your sample)
318
+ try:
319
+ df0 = pd.read_csv(io.BytesIO(po_bytes), header=None, engine="python", on_bad_lines="skip")
320
+ if df0.shape[1] >= 3:
321
+ for _, row in df0.iterrows():
322
+ po_number = str(row.iloc[1] if len(row) > 1 else "").strip()
323
+ if not po_number:
324
+ continue
325
+ supplier = str(row.iloc[2] if len(row) > 2 else "").strip()
326
+ raw_items = row.iloc[-1] if len(row) > 0 else None
327
+ if raw_items is None:
328
+ continue
329
+ s = str(raw_items).strip()
330
+ if not (s.startswith("[") and s.endswith("]")):
331
+ continue
332
+ try:
333
+ items = json.loads(s)
334
+ except Exception:
335
+ continue
336
+ if not isinstance(items, list):
337
+ continue
338
+ for it in items:
339
+ if not isinstance(it, dict):
340
+ continue
341
+ keys = {str(k).strip().lower(): v for k, v in it.items()}
342
+ sku = str(keys.get("part number") or keys.get("part") or keys.get("sku") or "").strip()
343
+ desc = str(keys.get("description") or keys.get("desc") or "").strip()
344
+ qty = to_float(keys.get("quantity") or keys.get("qty"))
345
+ unit_price = to_float(keys.get("unit cost") or keys.get("unit_price") or keys.get("unit price"))
346
+ if qty is None:
347
+ continue
348
+ out.append(
349
+ {
350
+ "po_number": po_number,
351
+ "sku": sku[:64],
352
+ "description": desc[:240],
353
+ "qty_ordered": float(qty),
354
+ "unit_price": unit_price,
355
+ "supplier": supplier or None,
356
+ }
357
+ )
358
+ except Exception:
359
+ pass
360
+
361
+ if out:
362
+ return out
363
+
364
+ # 2) Try headered read (if file actually has headers)
365
+ try:
366
+ df = pd.read_csv(io.BytesIO(po_bytes), engine="python", on_bad_lines="skip")
367
+ except Exception:
368
+ return []
369
+
370
+ cols = [c for c in df.columns]
371
+
372
+ def pick_col(pred):
373
+ for c in cols:
374
+ if pred(str(c)):
375
+ return c
376
+ return None
377
+
378
+ po_col = pick_col(lambda c: "po" in c.lower() and "number" in c.lower()) or pick_col(lambda c: c.lower().strip() in {"po", "po_number"})
379
+ supplier_col = pick_col(lambda c: "vendor" in c.lower() or "supplier" in c.lower() or "vendor name" in c.lower())
380
+ items_col = pick_col(lambda c: "item" in c.lower())
381
+ if not po_col or not items_col:
382
+ return []
383
+
384
+ for _, row in df.iterrows():
385
+ po_number = str(row.get(po_col, "")).strip()
386
+ if not po_number:
387
+ continue
388
+ supplier = str(row.get(supplier_col, "")).strip() if supplier_col else ""
389
+ raw_items = row.get(items_col)
390
+ if raw_items is None:
391
+ continue
392
+ s = str(raw_items).strip()
393
+ if not (s.startswith("[") and s.endswith("]")):
394
+ continue
395
+ try:
396
+ items = json.loads(s)
397
+ except Exception:
398
+ continue
399
+ if not isinstance(items, list):
400
+ continue
401
+ for it in items:
402
+ if not isinstance(it, dict):
403
+ continue
404
+ keys = {str(k).strip().lower(): v for k, v in it.items()}
405
+ sku = str(keys.get("part number") or keys.get("part") or keys.get("sku") or "").strip()
406
+ desc = str(keys.get("description") or keys.get("desc") or "").strip()
407
+ qty = to_float(keys.get("quantity") or keys.get("qty"))
408
+ unit_price = to_float(keys.get("unit cost") or keys.get("unit_price") or keys.get("unit price"))
409
+ if qty is None:
410
+ continue
411
+ out.append(
412
+ {
413
+ "po_number": po_number,
414
+ "sku": sku[:64],
415
+ "description": desc[:240],
416
+ "qty_ordered": float(qty),
417
+ "unit_price": unit_price,
418
+ "supplier": supplier or None,
419
+ }
420
+ )
421
+ return out
422
+
423
+
424
+ def _cfg() -> dict[str, str]:
425
+ endpoint = (os.environ.get("AZURE_OPENAI_ENDPOINT") or "").strip()
426
+ key = (os.environ.get("AZURE_OPENAI_API_KEY") or "").strip()
427
+ deployment = (os.environ.get("AZURE_OPENAI_DEPLOYMENT") or "").strip()
428
+ api_version = (os.environ.get("AZURE_OPENAI_API_VERSION") or "2024-10-21").strip()
429
+ if not ai_enabled(provider="azure", api_key=key, azure_endpoint=endpoint):
430
+ raise RuntimeError("Azure OpenAI is not configured. Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY.")
431
+ if not deployment:
432
+ raise RuntimeError("Azure OpenAI deployment is not configured. Set AZURE_OPENAI_DEPLOYMENT.")
433
+ return {"endpoint": endpoint, "key": key, "deployment": deployment, "api_version": api_version}
434
+
435
+
436
+ app = FastAPI(title="AP Agent API", version="0.1.0")
437
+ app.add_middleware(
438
+ CORSMiddleware,
439
+ allow_origins=["*"],
440
+ allow_credentials=True,
441
+ allow_methods=["*"],
442
+ allow_headers=["*"],
443
+ )
444
+
445
+
446
+ @app.on_event("startup")
447
+ def _startup() -> None:
448
+ init_db()
449
+
450
+
451
+ # Serve the built React app (single-server deployment)
452
+ # IMPORTANT: SPA routes are registered at the bottom of the file (after /api/*),
453
+ # otherwise the catch-all will swallow API calls and return HTML instead of JSON.
454
+ FRONTEND_DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
455
+ if FRONTEND_DIST.exists():
456
+ app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIST / "assets")), name="assets")
457
+
458
+
459
+ @app.get("/api/health")
460
+ def health() -> dict[str, Any]:
461
+ try:
462
+ _ = _cfg()
463
+ return {"ok": True, "service": "backend1", "build": BUILD_ID}
464
+ except Exception as e:
465
+ return {"ok": False, "error": str(e), "service": "backend1", "build": BUILD_ID}
466
+
467
+
468
+ @app.post("/api/clear")
469
+ def api_clear() -> dict[str, Any]:
470
+ conn = get_conn()
471
+ clear_all(conn)
472
+ conn.close()
473
+ return {"ok": True}
474
+
475
+
476
+ @app.get("/api/history")
477
+ def api_history(
478
+ limit: int = 50,
479
+ invoice_number: str | None = None,
480
+ supplier: str | None = None,
481
+ po_number: str | None = None,
482
+ match_status: str | None = None,
483
+ duplicate_flag: int | None = None,
484
+ date_from: str | None = None,
485
+ date_to: str | None = None,
486
+ ) -> dict[str, Any]:
487
+ conn = get_conn()
488
+ rows = search_invoices(
489
+ conn,
490
+ limit=int(limit),
491
+ invoice_number=invoice_number,
492
+ supplier=supplier,
493
+ po_number=po_number,
494
+ match_status=match_status,
495
+ duplicate_flag=duplicate_flag,
496
+ date_from=date_from,
497
+ date_to=date_to,
498
+ )
499
+ conn.close()
500
+ return {"items": rows}
501
+
502
+
503
+ @app.get("/api/history/{invoice_id}")
504
+ def api_history_detail(invoice_id: str) -> dict[str, Any]:
505
+ conn = get_conn()
506
+ detail = load_invoice_detail(conn, invoice_id)
507
+ if not detail.get("invoice"):
508
+ conn.close()
509
+ raise HTTPException(status_code=404, detail="Not found")
510
+ # Reconstruct extracted invoice JSON (for History view) from persisted DB rows.
511
+ try:
512
+ inv = detail.get("invoice") or {}
513
+ lines = detail.get("lines") or []
514
+ po_number = str(inv.get("po_number") or "")
515
+ extracted_invoice = {
516
+ "invoice": {
517
+ "invoice_number": inv.get("invoice_number") or "",
518
+ "supplier": inv.get("supplier") or "",
519
+ "po_number": inv.get("po_number") or "",
520
+ "total_amount": str(inv.get("invoice_total") if inv.get("invoice_total") is not None else ""),
521
+ "currency": inv.get("currency") or "",
522
+ },
523
+ "line_items": [
524
+ {
525
+ "sku": l.get("sku") or "",
526
+ "description": l.get("description") or "",
527
+ "qty": l.get("qty"),
528
+ "unit_price": l.get("unit_price"),
529
+ "line_total": l.get("line_total"),
530
+ }
531
+ for l in lines
532
+ ],
533
+ }
534
+ detail["extracted_invoice"] = extracted_invoice
535
+ # Current backorder state for this PO (based on all non-duplicate invoices stored so far).
536
+ po_db_lines = get_po_lines(conn, po_number) if po_number else []
537
+ received = get_received_qty_by_po_line_id(conn, po_number) if po_number else {}
538
+ backorders = _compute_backorders(po_db_lines=po_db_lines, received_before=received, current_invoice_qty_by_po_line_id=None)
539
+ detail["backorders"] = {"items": backorders, "count": len(backorders)}
540
+ except Exception:
541
+ detail["extracted_invoice"] = None
542
+ detail["backorders"] = {"items": [], "count": 0}
543
+ conn.close()
544
+ return detail
545
+
546
+
547
+ @app.post("/api/analyze")
548
+ async def api_analyze(
549
+ invoice: UploadFile = File(...),
550
+ po_file: UploadFile = File(...),
551
+ duplicate_override: bool = Form(default=False),
552
+ override_reason: str = Form(default=""),
553
+ ) -> dict[str, Any]:
554
+ try:
555
+ cfg = _cfg()
556
+ except Exception as e:
557
+ raise HTTPException(status_code=500, detail=str(e))
558
+
559
+ t0 = time.perf_counter()
560
+ inv_bytes = await invoice.read()
561
+ po_bytes = await po_file.read()
562
+ if not inv_bytes or not po_bytes:
563
+ raise HTTPException(status_code=400, detail="Both invoice and PO file are required.")
564
+
565
+ inv_sha = sha256_bytes(inv_bytes)
566
+ po_sha = sha256_bytes(po_bytes)
567
+
568
+ po_csv_text = read_tabular_text(po_file.filename or "po", po_bytes)
569
+ # Fast path: many of your PO exports embed JSON line items in a cell. Parse deterministically and
570
+ # skip the LLM normalization call (big latency win).
571
+ fallback_po_lines = _extract_po_lines_from_embedded_json(po_bytes)
572
+ if fallback_po_lines:
573
+ po_lines = fallback_po_lines
574
+ # best-effort header from lines
575
+ po_header = {
576
+ "po_number": _single_po_number(po_lines) or (po_lines[0].get("po_number") if po_lines else ""),
577
+ "supplier": po_lines[0].get("supplier") if po_lines else "",
578
+ "po_amount": None,
579
+ "currency": "",
580
+ }
581
+ po_number_candidates = sorted({str(r.get("po_number") or "").strip() for r in po_lines if str(r.get("po_number") or "").strip()})
582
+ else:
583
+ po_norm = ai_normalize_po_csv(
584
+ deployment=cfg["deployment"],
585
+ api_key=cfg["key"],
586
+ azure_endpoint=cfg["endpoint"],
587
+ azure_api_version=cfg["api_version"],
588
+ po_csv_text=po_csv_text,
589
+ )
590
+ po_lines = po_norm.get("po_lines") or []
591
+ po_header = po_norm.get("po_header") or {}
592
+ po_number_candidates = po_norm.get("po_numbers") or []
593
+ if not po_number_candidates and po_header.get("po_number"):
594
+ po_number_candidates = [po_header.get("po_number")]
595
+
596
+ conn = get_conn()
597
+ # Deterministic duplicate detection (do not rely on the model).
598
+ dup_by_sha = invoice_exists_by_sha(conn, inv_sha)
599
+ if not po_number_candidates:
600
+ raise HTTPException(status_code=400, detail="Could not identify a PO number from the CSV.")
601
+ po_number = str(po_number_candidates[0])
602
+
603
+ inv_inputs = extract_invoice_inputs(invoice.filename or "invoice", inv_bytes)
604
+ invoice_text = inv_inputs.get("invoice_text", "")
605
+ invoice_images = inv_inputs.get("invoice_images", [])
606
+ ocr_payload = inv_inputs.get("ocr") or None
607
+ # OCR payload for frontend debug/inspection (real OCR when configured; otherwise embedded PDF text).
608
+ # Keep response size sane: include only the first page image (if present).
609
+ ocr_json: dict[str, Any] = {
610
+ "file_name": invoice.filename or "",
611
+ "file_sha256": inv_sha,
612
+ # If Azure DI isn't used, we still run the agent with vision images for PDFs.
613
+ # Use agent_vision as the primary "OCR" provider so the UI consistently shows extracted JSON for ALL PDFs.
614
+ "provider": (ocr_payload or {}).get("provider") or ("agent_vision" if (invoice_images or []) else ("pdf_text" if invoice_text else "none")),
615
+ "text": invoice_text,
616
+ "text_chars": len(invoice_text or ""),
617
+ "pdf_text_present": bool(invoice_text),
618
+ "images_count": len(invoice_images or []),
619
+ "images_preview": [png_bytes_to_data_url(invoice_images[0])] if invoice_images else [],
620
+ # OCR service raw output (bounded; UI can expand it)
621
+ "result": (ocr_payload or {}).get("result") or None,
622
+ "error": (ocr_payload or {}).get("error") or None,
623
+ }
624
+ # Prefer invoice parser output (most reliable for "PO Number: ...") and fall back to heuristic/filename.
625
+ inv_fields = parse_invoice_fields(invoice_text or "")
626
+ file_po = _po_from_filename(invoice.filename)
627
+ invoice_po_hint = file_po or (inv_fields.get("po_number") or "").strip() or _guess_po(invoice_text=invoice_text, file_name=invoice.filename)
628
+ if invoice_po_hint:
629
+ # normalize common variants
630
+ invoice_po_hint = re.sub(r"\bPO\s+(\d+)\b", r"PO-\1", invoice_po_hint, flags=re.IGNORECASE).upper()
631
+
632
+ if po_lines:
633
+ po_df = pd.DataFrame(po_lines)
634
+ from ap_agent1.po import upsert_po_lines
635
+
636
+ upsert_po_lines(conn, po_df, source_hash=po_sha)
637
+ # AGENT-FIRST: Don't pre-select PO number. Let agent extract PO from invoice and match dynamically.
638
+ # Pass ALL PO lines from the file, not filtered by a pre-selected PO number.
639
+ # The agent will extract the invoice PO number and match against all available PO lines.
640
+ po_rows_all = po_lines # Pass all PO lines, let agent filter by invoice PO number
641
+ # We still need po_number_ctx for DB operations (history, backorders), but we'll use agent's extracted PO after it runs
642
+ po_number_ctx_temp = _pick_po_number_ctx(
643
+ po_lines=po_lines,
644
+ po_header=po_header,
645
+ po_number_candidates=po_number_candidates,
646
+ invoice_po_hint=invoice_po_hint,
647
+ po_file_name=po_file.filename,
648
+ )
649
+ po_rows = po_rows_all # Use all lines, not filtered
650
+ else:
651
+ po_rows = []
652
+ po_number_ctx_temp = invoice_po_hint or _norm_po(po_number)
653
+
654
+ try:
655
+ uniq_po = sorted({str(r.get("po_number", "")).strip() for r in (po_lines or []) if str(r.get("po_number", "")).strip()})[:10]
656
+ logger.info(
657
+ "analyze debug: filename=%s file_po=%s inv_po=%s csv_po=%s only_po=%s po_number_ctx_temp=%s po_lines=%d po_rows=%d uniq_pos=%s",
658
+ invoice.filename,
659
+ file_po,
660
+ (inv_fields.get("po_number") or "").strip(),
661
+ po_number,
662
+ _single_po_number(po_lines),
663
+ po_number_ctx_temp,
664
+ len(po_lines or []),
665
+ len(po_rows or []),
666
+ uniq_po,
667
+ )
668
+ except Exception:
669
+ pass
670
+
671
+ supplier_master = load_suppliers().to_dict(orient="records")
672
+ # Use PO vendor/supplier as the approved supplier list (instead of relying on suppliers.csv).
673
+ supplier_master = _supplier_master_from_po(po_lines=po_lines, po_header=po_header)
674
+ # Use temporary PO number for history lookup (will be refined after agent extracts the correct PO)
675
+ history = get_history_context(conn, po_number=po_number_ctx_temp, limit=25)
676
+
677
+ agent_out = ai_ap_agent_process(
678
+ deployment=cfg["deployment"],
679
+ api_key=cfg["key"],
680
+ azure_endpoint=cfg["endpoint"],
681
+ azure_api_version=cfg["api_version"],
682
+ invoice_text=invoice_text,
683
+ invoice_images=invoice_images,
684
+ file_name=invoice.filename,
685
+ file_sha256=inv_sha,
686
+ po_rows=po_rows,
687
+ po_source_text=po_csv_text,
688
+ supplier_master=supplier_master,
689
+ history=history,
690
+ user_overrides=None,
691
+ )
692
+
693
+ inv = agent_out.get("invoice") or {}
694
+ sv = agent_out.get("supplier_validation") or {}
695
+ invoice_number = (inv.get("invoice_number") or "") or None
696
+ supplier = (inv.get("supplier") or "") or None
697
+ currency = (inv.get("currency") or "") or None
698
+ invoice_total_f = to_float(inv.get("total_amount"))
699
+ # AGENT-FIRST: Use the agent's extracted PO number (the source of truth)
700
+ agent_po_number = _norm_po(inv.get("po_number") or "")
701
+ # Use agent's PO number for DB operations (backorders, history, etc.)
702
+ po_number_ctx = agent_po_number if agent_po_number else po_number_ctx_temp
703
+ # Attach agent-extracted invoice structure to OCR JSON (no extra model call).
704
+ try:
705
+ line_items = []
706
+ for r in (agent_out.get("line_results") or [])[:200]:
707
+ line_items.append(
708
+ {
709
+ "sku": r.get("invoice_sku") or "",
710
+ "description": r.get("invoice_description") or "",
711
+ "qty": r.get("invoice_qty"),
712
+ "unit_price": r.get("invoice_unit_price"),
713
+ "line_total": r.get("invoice_line_total"),
714
+ }
715
+ )
716
+ ocr_json["extracted_invoice"] = {
717
+ "invoice": inv,
718
+ "line_items": line_items,
719
+ }
720
+ # Print to backend console so you can verify locally even before the UI.
721
+ try:
722
+ logger.info("ocr extracted_invoice: %s", json.dumps(ocr_json["extracted_invoice"], ensure_ascii=False)[:2000])
723
+ except Exception:
724
+ logger.info("ocr extracted_invoice: <unprintable>")
725
+ except Exception:
726
+ pass
727
+
728
+ evaluation = {
729
+ "match_status": agent_out.get("match_status", "Review"),
730
+ # Start with model output, but we'll override below with deterministic DB checks.
731
+ "duplicate": bool(agent_out.get("duplicate", False)),
732
+ "supplier_status": sv.get("supplier_status", "Unknown"),
733
+ "rationale": agent_out.get("rationale", ""),
734
+ "suggested_action": agent_out.get("suggested_action", ""),
735
+ "alerts": agent_out.get("alerts") or [],
736
+ "line_results": agent_out.get("line_results") or [],
737
+ "open_backorders": agent_out.get("open_backorders") or [],
738
+ }
739
+
740
+ # Enforce deterministic duplicate detection (SHA strongest, business key fallback).
741
+ dup_by_business = invoice_exists_by_business_key(conn, invoice_number, supplier)
742
+ is_dup = bool(dup_by_sha or dup_by_business)
743
+ if is_dup:
744
+ evaluation["duplicate"] = True
745
+ # Duplicates should never be auto-approved.
746
+ evaluation["match_status"] = "Review"
747
+ alerts = list(evaluation.get("alerts") or [])
748
+ alerts.insert(
749
+ 0,
750
+ {
751
+ "level": "warning",
752
+ "message": "Duplicate detected: this invoice appears to have been processed already.",
753
+ },
754
+ )
755
+ evaluation["alerts"] = alerts
756
+
757
+ # Metrics for UI visibility
758
+ model_conf = _normalize_score(agent_out.get("confidence_score"))
759
+ confidence = model_conf if model_conf is not None else _confidence_score(supplier_match_score=sv.get("supplier_match_score"), line_results=evaluation["line_results"])
760
+ approval_decision = (agent_out.get("approval_decision") or "").strip() or None
761
+ if approval_decision not in {"Approved", "Partially Approved", "Rejected"}:
762
+ approval_decision = None
763
+ evaluation["confidence_score"] = confidence
764
+ evaluation["approval_decision"] = approval_decision
765
+ extractions_count = _extractions_count(invoice_fields=inv, line_results=evaluation["line_results"])
766
+ processing_ms = int((time.perf_counter() - t0) * 1000)
767
+
768
+ # Duplicate evidence (for UI): find previously processed records that likely match
769
+ dup_matches: list[dict[str, Any]] = []
770
+ if evaluation["duplicate"]:
771
+ # Prefer sha match; fallback to invoice_number+supplier match
772
+ rows = conn.execute(
773
+ """
774
+ SELECT id, processed_at, invoice_number, supplier, po_number, match_status, duplicate_flag
775
+ FROM invoices
776
+ WHERE (file_sha256 = ? AND ? != '')
777
+ OR (lower(coalesce(invoice_number,'')) = lower(?) AND lower(coalesce(supplier,'')) = lower(?))
778
+ ORDER BY processed_at DESC
779
+ LIMIT 5
780
+ """,
781
+ (inv_sha, inv_sha, inv.get("invoice_number") or "", inv.get("supplier") or ""),
782
+ ).fetchall()
783
+ dup_matches = [dict(r) for r in rows]
784
+
785
+ # Persist
786
+ # Map matched PO line IDs so history can support future backorder reasoning.
787
+ po_db_lines = get_po_lines(conn, po_number_ctx) if po_number_ctx else []
788
+ po_by_sku: dict[str, str] = {}
789
+ po_by_desc: dict[str, str] = {}
790
+ # Build a map of (sku_norm, desc_norm) -> po_line_id for more robust matching
791
+ po_by_sku_desc: dict[tuple[str, str], str] = {}
792
+ for pl in po_db_lines:
793
+ sku_norm = _norm_key(str(pl.get("sku") or ""))
794
+ desc_norm = _norm_key(str(pl.get("description") or ""))
795
+ po_line_id_str = str(pl.get("id"))
796
+
797
+ if sku_norm:
798
+ po_by_sku.setdefault(sku_norm, po_line_id_str)
799
+ if desc_norm:
800
+ po_by_desc.setdefault(desc_norm, po_line_id_str)
801
+ # Combined key for more precise matching
802
+ if sku_norm and desc_norm:
803
+ po_by_sku_desc[(sku_norm, desc_norm)] = po_line_id_str
804
+
805
+ to_save: list[dict[str, Any]] = []
806
+ for r in evaluation["line_results"]:
807
+ po_line_id: str | None = None
808
+
809
+ # Get normalized values from agent's output
810
+ agent_po_sku = _norm_key(r.get("po_sku") or "")
811
+ agent_po_desc = _norm_key(r.get("po_description") or "")
812
+ invoice_sku = _norm_key(r.get("invoice_sku") or "")
813
+ invoice_desc = _norm_key(r.get("invoice_description") or "")
814
+
815
+ # Try matching in order of preference:
816
+ # 1) Agent's po_sku + po_description (most reliable - agent already matched)
817
+ if agent_po_sku and agent_po_desc:
818
+ po_line_id = po_by_sku_desc.get((agent_po_sku, agent_po_desc))
819
+
820
+ # 2) Agent's po_description only (since SKU might be generic like "Goods")
821
+ if not po_line_id and agent_po_desc:
822
+ po_line_id = po_by_desc.get(agent_po_desc)
823
+
824
+ # 3) Invoice description (fallback if agent didn't provide po_description)
825
+ if not po_line_id and invoice_desc:
826
+ po_line_id = po_by_desc.get(invoice_desc)
827
+
828
+ # 4) Agent's po_sku only (least reliable since it might be generic)
829
+ if not po_line_id and agent_po_sku:
830
+ po_line_id = po_by_sku.get(agent_po_sku)
831
+
832
+ # 5) Invoice sku as last resort (should rarely be needed)
833
+ if not po_line_id and invoice_sku:
834
+ po_line_id = po_by_sku.get(invoice_sku)
835
+
836
+ # Log matching attempt (for debugging)
837
+ if not po_line_id:
838
+ logger.warning(
839
+ "Could not match invoice line to PO line: invoice_sku=%s invoice_desc=%s agent_po_sku=%s agent_po_desc=%s po_db_lines_count=%d",
840
+ invoice_sku,
841
+ invoice_desc,
842
+ agent_po_sku,
843
+ agent_po_desc,
844
+ len(po_db_lines),
845
+ )
846
+ # Log available PO lines for debugging
847
+ if po_db_lines:
848
+ logger.info("Available PO lines: %s", [(pl.get("id"), _norm_key(str(pl.get("sku") or "")), _norm_key(str(pl.get("description") or ""))) for pl in po_db_lines[:5]])
849
+ else:
850
+ logger.debug(
851
+ "Matched invoice line: invoice_desc=%s -> po_line_id=%s",
852
+ invoice_desc,
853
+ po_line_id,
854
+ )
855
+
856
+ qty = to_float(r.get("invoice_qty"))
857
+ to_save.append(
858
+ {
859
+ "sku": r.get("invoice_sku") or None,
860
+ "description": r.get("invoice_description") or None,
861
+ "qty": qty,
862
+ "unit_price": to_float(r.get("invoice_unit_price")),
863
+ "line_total": to_float(r.get("invoice_line_total")),
864
+ "matched_po_line_id": po_line_id,
865
+ "match_score": r.get("match_score"),
866
+ }
867
+ )
868
+
869
+ # Deterministic backorder breakdown from DB (more reliable than model text).
870
+ received_before_by_line = get_received_qty_by_po_line_id(conn, po_number_ctx) if po_number_ctx else {}
871
+ current_qty_by_line: dict[str, float] = {}
872
+ unmatched_count = 0
873
+ for l in to_save:
874
+ po_line_id = str(l.get("matched_po_line_id") or "")
875
+ if not po_line_id:
876
+ unmatched_count += 1
877
+ logger.warning(
878
+ "Invoice line not matched to PO line ID: sku=%s desc=%s qty=%s",
879
+ l.get("sku"),
880
+ l.get("description"),
881
+ l.get("qty"),
882
+ )
883
+ continue
884
+ q = to_float(l.get("qty")) or 0.0
885
+ current_qty_by_line[po_line_id] = float(current_qty_by_line.get(po_line_id, 0.0)) + float(q)
886
+
887
+ # Log backorder calculation inputs
888
+ logger.info(
889
+ "Backorder calc: po_number_ctx=%s po_db_lines=%d received_before=%d lines current_qty=%d lines unmatched=%d",
890
+ po_number_ctx,
891
+ len(po_db_lines),
892
+ len(received_before_by_line),
893
+ len(current_qty_by_line),
894
+ unmatched_count,
895
+ )
896
+
897
+ backorders = _compute_backorders(
898
+ po_db_lines=po_db_lines,
899
+ received_before=received_before_by_line,
900
+ current_invoice_qty_by_po_line_id=current_qty_by_line,
901
+ )
902
+
903
+ # If we have unmatched lines, prefer agent's backorder calculation (it did the matching)
904
+ if unmatched_count > 0:
905
+ agent_backorders = agent_out.get("open_backorders") or []
906
+ logger.warning(
907
+ "Some invoice lines unmatched (%d). Agent backorders: %d items, Deterministic backorders: %d items. Using agent's calculation.",
908
+ unmatched_count,
909
+ len(agent_backorders),
910
+ len(backorders),
911
+ )
912
+ # Use agent's backorder calculation when matching fails (agent did semantic matching)
913
+ if agent_backorders:
914
+ # Convert agent's format to our format
915
+ backorders_agent = []
916
+ for ab in agent_backorders:
917
+ # Find matching PO line ID by description
918
+ desc_match = _norm_key(str(ab.get("description") or ""))
919
+ po_line_id_match = None
920
+ for pl in po_db_lines:
921
+ if _norm_key(str(pl.get("description") or "")) == desc_match:
922
+ po_line_id_match = str(pl.get("id"))
923
+ break
924
+ backorders_agent.append({
925
+ "po_line_id": po_line_id_match or "",
926
+ "sku": ab.get("sku") or "",
927
+ "description": ab.get("description") or "",
928
+ "qty_ordered": float(ab.get("qty_ordered") or 0),
929
+ "received_before": float(ab.get("received_before") or 0),
930
+ "received_after": float(ab.get("received_after") or 0),
931
+ "remaining": float(ab.get("remaining") or 0),
932
+ })
933
+ if backorders_agent:
934
+ backorders = backorders_agent
935
+ logger.info("Using agent's backorder calculation due to unmatched lines")
936
+
937
+ evaluation["open_backorders"] = backorders
938
+
939
+ inv_id = insert_invoice_run(
940
+ conn,
941
+ invoice_number=invoice_number,
942
+ supplier=supplier,
943
+ supplier_validated=sv.get("supplier_validated") or None,
944
+ supplier_match_score=sv.get("supplier_match_score"),
945
+ supplier_status=sv.get("supplier_status") or "Unknown",
946
+ po_number=po_number_ctx, # Use agent's extracted PO number, not the pre-selected one
947
+ invoice_total=invoice_total_f,
948
+ currency=currency,
949
+ match_status=evaluation["match_status"],
950
+ match_score=confidence,
951
+ processing_ms=processing_ms,
952
+ extractions_count=extractions_count,
953
+ approval_decision=approval_decision,
954
+ rule_match_status=None,
955
+ rule_match_score=None,
956
+ decision_engine="agent",
957
+ ai_model=cfg["deployment"],
958
+ ai_rationale=agent_out.get("rationale"),
959
+ override_reason=override_reason.strip() or None,
960
+ open_backorders_count=len(backorders),
961
+ duplicate_flag=bool(evaluation["duplicate"]),
962
+ file_name=invoice.filename,
963
+ file_sha256=inv_sha,
964
+ raw_text=invoice_text,
965
+ invoice_lines=to_save,
966
+ )
967
+ conn.close()
968
+
969
+ return {
970
+ "invoice_id": inv_id,
971
+ "po_number": agent_po_number or po_number_ctx, # Prefer agent's extracted PO number
972
+ "evaluation": evaluation,
973
+ "details": {
974
+ "metrics": {
975
+ "confidence_score": confidence,
976
+ "processing_ms": processing_ms,
977
+ "extractions_count": extractions_count,
978
+ },
979
+ "approval_decision": approval_decision,
980
+ "backorders": {
981
+ "items": backorders,
982
+ "count": len(backorders),
983
+ },
984
+ "invoice": {
985
+ "invoice_number": inv.get("invoice_number") or "",
986
+ "supplier": inv.get("supplier") or "",
987
+ "po_number": inv.get("po_number") or "",
988
+ "total_amount": inv.get("total_amount") or "",
989
+ "currency": inv.get("currency") or "",
990
+ "file_name": invoice.filename or "",
991
+ },
992
+ "po": {
993
+ "po_number": agent_po_number or po_number_ctx, # Use agent's extracted PO number
994
+ "supplier": po_header.get("supplier") or "",
995
+ "po_amount": po_header.get("po_amount"),
996
+ "currency": po_header.get("currency") or "",
997
+ "line_items_count": len(po_rows),
998
+ "source_filename": po_file.filename or "",
999
+ },
1000
+ "supplier_validation": {
1001
+ "status": sv.get("supplier_status", "Unknown"),
1002
+ "best_match": sv.get("supplier_validated") or "",
1003
+ "match_score": sv.get("supplier_match_score"),
1004
+ "notes": sv.get("notes") or "",
1005
+ },
1006
+ "ocr": ocr_json,
1007
+ },
1008
+ "duplicate_matches": dup_matches,
1009
+ "blocked": False,
1010
+ }
1011
+
1012
+
1013
+ # -------------------------
1014
+ # SPA routes (must be last)
1015
+ # -------------------------
1016
+ @app.get("/", include_in_schema=False)
1017
+ def spa_index():
1018
+ if FRONTEND_DIST.exists():
1019
+ return FileResponse(str(FRONTEND_DIST / "index.html"))
1020
+ return HTMLResponse(
1021
+ """
1022
+ <html><body style="font-family:system-ui;padding:24px">
1023
+ <h2>AP Agent</h2>
1024
+ <p>Frontend is not built yet.</p>
1025
+ <pre>cd frontend\nnpm install\nnpm run build</pre>
1026
+ <p>Then run the server again.</p>
1027
+ </body></html>
1028
+ """.strip(),
1029
+ status_code=200,
1030
+ )
1031
+
1032
+
1033
+ @app.get("/{full_path:path}", include_in_schema=False)
1034
+ def spa_fallback(full_path: str):
1035
+ # SPA fallback for client-side routing; must not swallow /api/*
1036
+ if full_path.startswith("api/") or full_path == "api":
1037
+ return HTMLResponse("Not found", status_code=404)
1038
+ if FRONTEND_DIST.exists():
1039
+ p = FRONTEND_DIST / full_path
1040
+ if p.exists() and p.is_file():
1041
+ return FileResponse(str(p))
1042
+ return FileResponse(str(FRONTEND_DIST / "index.html"))
1043
+ return HTMLResponse("Not found", status_code=404)
1044
+
1045
+
debug.log ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [0102/135446.143:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: The system cannot find the file specified. (0x2)
2
+ [0102/141610.439:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: The system cannot find the file specified. (0x2)
3
+ [0102/160659.061:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: The system cannot find the file specified. (0x2)
4
+ [0102/160724.764:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: The system cannot find the file specified. (0x2)
frontend/dist/assets/index-CUicmmlc.js ADDED
The diff for this file is too large to render. See raw diff
 
frontend/dist/assets/index-Lye-aeXV.css ADDED
@@ -0,0 +1 @@
 
 
1
+ *,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-6{bottom:1.5rem}.right-6{right:1.5rem}.top-0{top:0}.top-6{top:1.5rem}.z-50{z-index:50}.z-\[60\]{z-index:60}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.ml-2{margin-left:.5rem}.ml-auto{margin-left:auto}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-12{height:3rem}.h-9{height:2.25rem}.h-\[420px\]{height:420px}.max-h-\[38vh\]{max-height:38vh}.max-h-\[420px\]{max-height:420px}.max-h-\[70vh\]{max-height:70vh}.max-h-\[75vh\]{max-height:75vh}.max-h-\[calc\(100vh-6\.5rem\)\]{max-height:calc(100vh - 6.5rem)}.min-h-screen{min-height:100vh}.w-12{width:3rem}.w-9{width:2.25rem}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-full{min-width:100%}.max-w-3xl{max-width:48rem}.max-w-5xl{max-width:64rem}.max-w-\[1280px\]{max-width:1280px}.max-w-\[520px\]{max-width:520px}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-amber-600\/20{border-color:#d9770633}.border-amber-600\/25{border-color:#d9770640}.border-brand{--tw-border-opacity: 1;border-color:rgb(79 70 229 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-600\/25{border-color:#05966940}.border-rose-600\/20{border-color:#e11d4833}.border-rose-600\/25{border-color:#e11d4840}.border-stroke{border-color:#0f172a1a}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-bg{--tw-bg-opacity: 1;background-color:rgb(246 247 251 / var(--tw-bg-opacity, 1))}.bg-black\/0{background-color:#0000}.bg-black\/40{background-color:#0006}.bg-brand{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-brand\/10{background-color:#4f46e51a}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/10{background-color:#10b9811a}.bg-panel{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-rose-500\/10{background-color:#f43f5e1a}.bg-stroke{background-color:#0f172a1a}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.object-contain{-o-object-fit:contain;object-fit:contain}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-4{padding-bottom:1rem}.pr-1{padding-right:.25rem}.pr-4{padding-right:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-brand{--tw-text-opacity: 1;color:rgb(79 70 229 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-ink{--tw-text-opacity: 1;color:rgb(15 23 42 / var(--tw-text-opacity, 1))}.text-ink\/70{color:#0f172ab3}.text-ink\/80{color:#0f172acc}.text-muted{color:#0f172aa6}.text-rose-700{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.text-rose-700\/90{color:#be123ce6}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow-glow{--tw-shadow: 0 0 0 1px rgba(15,23,42,.06), 0 18px 40px rgba(15,23,42,.08);--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color), 0 18px 40px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-soft{--tw-shadow: 0 1px 0 rgba(15,23,42,.04), 0 10px 24px rgba(15,23,42,.06);--tw-shadow-colored: 0 1px 0 var(--tw-shadow-color), 0 10px 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-brand\/15{--tw-ring-color: rgb(79 70 229 / .15)}.ring-brand\/20{--tw-ring-color: rgb(79 70 229 / .2)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}:root{color-scheme:light}html,body{height:100%;background:#f6f7fb}.bg-clean{background:radial-gradient(900px 500px at 15% 0%,rgba(79,70,229,.1),transparent 60%),radial-gradient(700px 450px at 85% 0%,rgba(16,185,129,.08),transparent 60%),linear-gradient(#f6f7fb,#f6f7fb)}@keyframes floaty{0%{transform:translateZ(0) scale(1);opacity:.65}50%{transform:translate3d(18px,-14px,0) scale(1.06);opacity:.8}to{transform:translate3d(-10px,10px,0) scale(1.02);opacity:.7}}.aurora{position:absolute;top:0;right:0;bottom:0;left:0;pointer-events:none;overflow:hidden}.aurora-blob{position:absolute;filter:blur(30px);border-radius:9999px;mix-blend-mode:multiply;animation:floaty 12s ease-in-out infinite}.aurora-blob.b1{width:520px;height:520px;left:-160px;top:-180px;background:#4f46e524;animation-duration:14s}.aurora-blob.b2{width:440px;height:440px;right:-160px;top:-140px;background:#10b9811f;animation-duration:16s}.aurora-blob.b3{width:520px;height:520px;left:25%;bottom:-220px;background:#6366f11a;animation-duration:18s}*::-webkit-scrollbar{height:10px;width:10px}*::-webkit-scrollbar-thumb{background:#0f172a26;border-radius:999px}*::-webkit-scrollbar-track{background:transparent}.placeholder\:text-muted::-moz-placeholder{color:#0f172aa6}.placeholder\:text-muted::placeholder{color:#0f172aa6}.hover\:bg-bg:hover{--tw-bg-opacity: 1;background-color:rgb(246 247 251 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/70:hover{background-color:#ffffffb3}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-brand\/15:hover{--tw-shadow-color: rgb(79 70 229 / .15);--tw-shadow: var(--tw-shadow-colored)}.hover\:brightness-105:hover{--tw-brightness: brightness(1.05);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.disabled\:opacity-40:disabled{opacity:.4}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width: 640px){.sm\:inline{display:inline}}@media (min-width: 768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:sticky{position:sticky}.lg\:top-0{top:0}.lg\:col-span-12{grid-column:span 12 / span 12}.lg\:h-screen{height:100vh}.lg\:grid-cols-12{grid-template-columns:repeat(12,minmax(0,1fr))}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:border-b-0{border-bottom-width:0px}.lg\:border-r{border-right-width:1px}}
frontend/dist/index.html ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>AP Agent Demo</title>
7
+ <script type="module" crossorigin src="/assets/index-CUicmmlc.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-Lye-aeXV.css">
9
+ </head>
10
+ <body class="bg-bg text-ink">
11
+ <div id="root"></div>
12
+ </body>
13
+ </html>
14
+
15
+
frontend/index.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>AP Agent Demo</title>
7
+ </head>
8
+ <body class="bg-bg text-ink">
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/main.tsx"></script>
11
+ </body>
12
+ </html>
13
+
14
+
frontend/package-lock.json ADDED
@@ -0,0 +1,2667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ap-agent-frontend",
3
+ "version": "0.1.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "ap-agent-frontend",
9
+ "version": "0.1.0",
10
+ "dependencies": {
11
+ "framer-motion": "^11.0.0",
12
+ "react": "^18.3.1",
13
+ "react-dom": "^18.3.1"
14
+ },
15
+ "devDependencies": {
16
+ "@types/react": "^18.3.12",
17
+ "@types/react-dom": "^18.3.1",
18
+ "@vitejs/plugin-react": "^4.3.4",
19
+ "autoprefixer": "^10.4.20",
20
+ "postcss": "^8.4.49",
21
+ "tailwindcss": "^3.4.16",
22
+ "typescript": "^5.6.3",
23
+ "vite": "^5.4.11"
24
+ }
25
+ },
26
+ "node_modules/@alloc/quick-lru": {
27
+ "version": "5.2.0",
28
+ "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
29
+ "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",
30
+ "dev": true,
31
+ "license": "MIT",
32
+ "engines": {
33
+ "node": ">=10"
34
+ },
35
+ "funding": {
36
+ "url": "https://github.com/sponsors/sindresorhus"
37
+ }
38
+ },
39
+ "node_modules/@babel/code-frame": {
40
+ "version": "7.27.1",
41
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
42
+ "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==",
43
+ "dev": true,
44
+ "license": "MIT",
45
+ "dependencies": {
46
+ "@babel/helper-validator-identifier": "^7.27.1",
47
+ "js-tokens": "^4.0.0",
48
+ "picocolors": "^1.1.1"
49
+ },
50
+ "engines": {
51
+ "node": ">=6.9.0"
52
+ }
53
+ },
54
+ "node_modules/@babel/compat-data": {
55
+ "version": "7.28.5",
56
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz",
57
+ "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==",
58
+ "dev": true,
59
+ "license": "MIT",
60
+ "engines": {
61
+ "node": ">=6.9.0"
62
+ }
63
+ },
64
+ "node_modules/@babel/core": {
65
+ "version": "7.28.5",
66
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz",
67
+ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
68
+ "dev": true,
69
+ "license": "MIT",
70
+ "dependencies": {
71
+ "@babel/code-frame": "^7.27.1",
72
+ "@babel/generator": "^7.28.5",
73
+ "@babel/helper-compilation-targets": "^7.27.2",
74
+ "@babel/helper-module-transforms": "^7.28.3",
75
+ "@babel/helpers": "^7.28.4",
76
+ "@babel/parser": "^7.28.5",
77
+ "@babel/template": "^7.27.2",
78
+ "@babel/traverse": "^7.28.5",
79
+ "@babel/types": "^7.28.5",
80
+ "@jridgewell/remapping": "^2.3.5",
81
+ "convert-source-map": "^2.0.0",
82
+ "debug": "^4.1.0",
83
+ "gensync": "^1.0.0-beta.2",
84
+ "json5": "^2.2.3",
85
+ "semver": "^6.3.1"
86
+ },
87
+ "engines": {
88
+ "node": ">=6.9.0"
89
+ },
90
+ "funding": {
91
+ "type": "opencollective",
92
+ "url": "https://opencollective.com/babel"
93
+ }
94
+ },
95
+ "node_modules/@babel/generator": {
96
+ "version": "7.28.5",
97
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz",
98
+ "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==",
99
+ "dev": true,
100
+ "license": "MIT",
101
+ "dependencies": {
102
+ "@babel/parser": "^7.28.5",
103
+ "@babel/types": "^7.28.5",
104
+ "@jridgewell/gen-mapping": "^0.3.12",
105
+ "@jridgewell/trace-mapping": "^0.3.28",
106
+ "jsesc": "^3.0.2"
107
+ },
108
+ "engines": {
109
+ "node": ">=6.9.0"
110
+ }
111
+ },
112
+ "node_modules/@babel/helper-compilation-targets": {
113
+ "version": "7.27.2",
114
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz",
115
+ "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==",
116
+ "dev": true,
117
+ "license": "MIT",
118
+ "dependencies": {
119
+ "@babel/compat-data": "^7.27.2",
120
+ "@babel/helper-validator-option": "^7.27.1",
121
+ "browserslist": "^4.24.0",
122
+ "lru-cache": "^5.1.1",
123
+ "semver": "^6.3.1"
124
+ },
125
+ "engines": {
126
+ "node": ">=6.9.0"
127
+ }
128
+ },
129
+ "node_modules/@babel/helper-globals": {
130
+ "version": "7.28.0",
131
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
132
+ "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
133
+ "dev": true,
134
+ "license": "MIT",
135
+ "engines": {
136
+ "node": ">=6.9.0"
137
+ }
138
+ },
139
+ "node_modules/@babel/helper-module-imports": {
140
+ "version": "7.27.1",
141
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz",
142
+ "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==",
143
+ "dev": true,
144
+ "license": "MIT",
145
+ "dependencies": {
146
+ "@babel/traverse": "^7.27.1",
147
+ "@babel/types": "^7.27.1"
148
+ },
149
+ "engines": {
150
+ "node": ">=6.9.0"
151
+ }
152
+ },
153
+ "node_modules/@babel/helper-module-transforms": {
154
+ "version": "7.28.3",
155
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz",
156
+ "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==",
157
+ "dev": true,
158
+ "license": "MIT",
159
+ "dependencies": {
160
+ "@babel/helper-module-imports": "^7.27.1",
161
+ "@babel/helper-validator-identifier": "^7.27.1",
162
+ "@babel/traverse": "^7.28.3"
163
+ },
164
+ "engines": {
165
+ "node": ">=6.9.0"
166
+ },
167
+ "peerDependencies": {
168
+ "@babel/core": "^7.0.0"
169
+ }
170
+ },
171
+ "node_modules/@babel/helper-plugin-utils": {
172
+ "version": "7.27.1",
173
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz",
174
+ "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==",
175
+ "dev": true,
176
+ "license": "MIT",
177
+ "engines": {
178
+ "node": ">=6.9.0"
179
+ }
180
+ },
181
+ "node_modules/@babel/helper-string-parser": {
182
+ "version": "7.27.1",
183
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
184
+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
185
+ "dev": true,
186
+ "license": "MIT",
187
+ "engines": {
188
+ "node": ">=6.9.0"
189
+ }
190
+ },
191
+ "node_modules/@babel/helper-validator-identifier": {
192
+ "version": "7.28.5",
193
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
194
+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
195
+ "dev": true,
196
+ "license": "MIT",
197
+ "engines": {
198
+ "node": ">=6.9.0"
199
+ }
200
+ },
201
+ "node_modules/@babel/helper-validator-option": {
202
+ "version": "7.27.1",
203
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
204
+ "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
205
+ "dev": true,
206
+ "license": "MIT",
207
+ "engines": {
208
+ "node": ">=6.9.0"
209
+ }
210
+ },
211
+ "node_modules/@babel/helpers": {
212
+ "version": "7.28.4",
213
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz",
214
+ "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==",
215
+ "dev": true,
216
+ "license": "MIT",
217
+ "dependencies": {
218
+ "@babel/template": "^7.27.2",
219
+ "@babel/types": "^7.28.4"
220
+ },
221
+ "engines": {
222
+ "node": ">=6.9.0"
223
+ }
224
+ },
225
+ "node_modules/@babel/parser": {
226
+ "version": "7.28.5",
227
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz",
228
+ "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==",
229
+ "dev": true,
230
+ "license": "MIT",
231
+ "dependencies": {
232
+ "@babel/types": "^7.28.5"
233
+ },
234
+ "bin": {
235
+ "parser": "bin/babel-parser.js"
236
+ },
237
+ "engines": {
238
+ "node": ">=6.0.0"
239
+ }
240
+ },
241
+ "node_modules/@babel/plugin-transform-react-jsx-self": {
242
+ "version": "7.27.1",
243
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz",
244
+ "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==",
245
+ "dev": true,
246
+ "license": "MIT",
247
+ "dependencies": {
248
+ "@babel/helper-plugin-utils": "^7.27.1"
249
+ },
250
+ "engines": {
251
+ "node": ">=6.9.0"
252
+ },
253
+ "peerDependencies": {
254
+ "@babel/core": "^7.0.0-0"
255
+ }
256
+ },
257
+ "node_modules/@babel/plugin-transform-react-jsx-source": {
258
+ "version": "7.27.1",
259
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz",
260
+ "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==",
261
+ "dev": true,
262
+ "license": "MIT",
263
+ "dependencies": {
264
+ "@babel/helper-plugin-utils": "^7.27.1"
265
+ },
266
+ "engines": {
267
+ "node": ">=6.9.0"
268
+ },
269
+ "peerDependencies": {
270
+ "@babel/core": "^7.0.0-0"
271
+ }
272
+ },
273
+ "node_modules/@babel/template": {
274
+ "version": "7.27.2",
275
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
276
+ "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==",
277
+ "dev": true,
278
+ "license": "MIT",
279
+ "dependencies": {
280
+ "@babel/code-frame": "^7.27.1",
281
+ "@babel/parser": "^7.27.2",
282
+ "@babel/types": "^7.27.1"
283
+ },
284
+ "engines": {
285
+ "node": ">=6.9.0"
286
+ }
287
+ },
288
+ "node_modules/@babel/traverse": {
289
+ "version": "7.28.5",
290
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz",
291
+ "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==",
292
+ "dev": true,
293
+ "license": "MIT",
294
+ "dependencies": {
295
+ "@babel/code-frame": "^7.27.1",
296
+ "@babel/generator": "^7.28.5",
297
+ "@babel/helper-globals": "^7.28.0",
298
+ "@babel/parser": "^7.28.5",
299
+ "@babel/template": "^7.27.2",
300
+ "@babel/types": "^7.28.5",
301
+ "debug": "^4.3.1"
302
+ },
303
+ "engines": {
304
+ "node": ">=6.9.0"
305
+ }
306
+ },
307
+ "node_modules/@babel/types": {
308
+ "version": "7.28.5",
309
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz",
310
+ "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==",
311
+ "dev": true,
312
+ "license": "MIT",
313
+ "dependencies": {
314
+ "@babel/helper-string-parser": "^7.27.1",
315
+ "@babel/helper-validator-identifier": "^7.28.5"
316
+ },
317
+ "engines": {
318
+ "node": ">=6.9.0"
319
+ }
320
+ },
321
+ "node_modules/@esbuild/aix-ppc64": {
322
+ "version": "0.21.5",
323
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
324
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
325
+ "cpu": [
326
+ "ppc64"
327
+ ],
328
+ "dev": true,
329
+ "license": "MIT",
330
+ "optional": true,
331
+ "os": [
332
+ "aix"
333
+ ],
334
+ "engines": {
335
+ "node": ">=12"
336
+ }
337
+ },
338
+ "node_modules/@esbuild/android-arm": {
339
+ "version": "0.21.5",
340
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
341
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
342
+ "cpu": [
343
+ "arm"
344
+ ],
345
+ "dev": true,
346
+ "license": "MIT",
347
+ "optional": true,
348
+ "os": [
349
+ "android"
350
+ ],
351
+ "engines": {
352
+ "node": ">=12"
353
+ }
354
+ },
355
+ "node_modules/@esbuild/android-arm64": {
356
+ "version": "0.21.5",
357
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
358
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
359
+ "cpu": [
360
+ "arm64"
361
+ ],
362
+ "dev": true,
363
+ "license": "MIT",
364
+ "optional": true,
365
+ "os": [
366
+ "android"
367
+ ],
368
+ "engines": {
369
+ "node": ">=12"
370
+ }
371
+ },
372
+ "node_modules/@esbuild/android-x64": {
373
+ "version": "0.21.5",
374
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
375
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
376
+ "cpu": [
377
+ "x64"
378
+ ],
379
+ "dev": true,
380
+ "license": "MIT",
381
+ "optional": true,
382
+ "os": [
383
+ "android"
384
+ ],
385
+ "engines": {
386
+ "node": ">=12"
387
+ }
388
+ },
389
+ "node_modules/@esbuild/darwin-arm64": {
390
+ "version": "0.21.5",
391
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
392
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
393
+ "cpu": [
394
+ "arm64"
395
+ ],
396
+ "dev": true,
397
+ "license": "MIT",
398
+ "optional": true,
399
+ "os": [
400
+ "darwin"
401
+ ],
402
+ "engines": {
403
+ "node": ">=12"
404
+ }
405
+ },
406
+ "node_modules/@esbuild/darwin-x64": {
407
+ "version": "0.21.5",
408
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
409
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
410
+ "cpu": [
411
+ "x64"
412
+ ],
413
+ "dev": true,
414
+ "license": "MIT",
415
+ "optional": true,
416
+ "os": [
417
+ "darwin"
418
+ ],
419
+ "engines": {
420
+ "node": ">=12"
421
+ }
422
+ },
423
+ "node_modules/@esbuild/freebsd-arm64": {
424
+ "version": "0.21.5",
425
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
426
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
427
+ "cpu": [
428
+ "arm64"
429
+ ],
430
+ "dev": true,
431
+ "license": "MIT",
432
+ "optional": true,
433
+ "os": [
434
+ "freebsd"
435
+ ],
436
+ "engines": {
437
+ "node": ">=12"
438
+ }
439
+ },
440
+ "node_modules/@esbuild/freebsd-x64": {
441
+ "version": "0.21.5",
442
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
443
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
444
+ "cpu": [
445
+ "x64"
446
+ ],
447
+ "dev": true,
448
+ "license": "MIT",
449
+ "optional": true,
450
+ "os": [
451
+ "freebsd"
452
+ ],
453
+ "engines": {
454
+ "node": ">=12"
455
+ }
456
+ },
457
+ "node_modules/@esbuild/linux-arm": {
458
+ "version": "0.21.5",
459
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
460
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
461
+ "cpu": [
462
+ "arm"
463
+ ],
464
+ "dev": true,
465
+ "license": "MIT",
466
+ "optional": true,
467
+ "os": [
468
+ "linux"
469
+ ],
470
+ "engines": {
471
+ "node": ">=12"
472
+ }
473
+ },
474
+ "node_modules/@esbuild/linux-arm64": {
475
+ "version": "0.21.5",
476
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
477
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
478
+ "cpu": [
479
+ "arm64"
480
+ ],
481
+ "dev": true,
482
+ "license": "MIT",
483
+ "optional": true,
484
+ "os": [
485
+ "linux"
486
+ ],
487
+ "engines": {
488
+ "node": ">=12"
489
+ }
490
+ },
491
+ "node_modules/@esbuild/linux-ia32": {
492
+ "version": "0.21.5",
493
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
494
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
495
+ "cpu": [
496
+ "ia32"
497
+ ],
498
+ "dev": true,
499
+ "license": "MIT",
500
+ "optional": true,
501
+ "os": [
502
+ "linux"
503
+ ],
504
+ "engines": {
505
+ "node": ">=12"
506
+ }
507
+ },
508
+ "node_modules/@esbuild/linux-loong64": {
509
+ "version": "0.21.5",
510
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
511
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
512
+ "cpu": [
513
+ "loong64"
514
+ ],
515
+ "dev": true,
516
+ "license": "MIT",
517
+ "optional": true,
518
+ "os": [
519
+ "linux"
520
+ ],
521
+ "engines": {
522
+ "node": ">=12"
523
+ }
524
+ },
525
+ "node_modules/@esbuild/linux-mips64el": {
526
+ "version": "0.21.5",
527
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
528
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
529
+ "cpu": [
530
+ "mips64el"
531
+ ],
532
+ "dev": true,
533
+ "license": "MIT",
534
+ "optional": true,
535
+ "os": [
536
+ "linux"
537
+ ],
538
+ "engines": {
539
+ "node": ">=12"
540
+ }
541
+ },
542
+ "node_modules/@esbuild/linux-ppc64": {
543
+ "version": "0.21.5",
544
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
545
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
546
+ "cpu": [
547
+ "ppc64"
548
+ ],
549
+ "dev": true,
550
+ "license": "MIT",
551
+ "optional": true,
552
+ "os": [
553
+ "linux"
554
+ ],
555
+ "engines": {
556
+ "node": ">=12"
557
+ }
558
+ },
559
+ "node_modules/@esbuild/linux-riscv64": {
560
+ "version": "0.21.5",
561
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
562
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
563
+ "cpu": [
564
+ "riscv64"
565
+ ],
566
+ "dev": true,
567
+ "license": "MIT",
568
+ "optional": true,
569
+ "os": [
570
+ "linux"
571
+ ],
572
+ "engines": {
573
+ "node": ">=12"
574
+ }
575
+ },
576
+ "node_modules/@esbuild/linux-s390x": {
577
+ "version": "0.21.5",
578
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
579
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
580
+ "cpu": [
581
+ "s390x"
582
+ ],
583
+ "dev": true,
584
+ "license": "MIT",
585
+ "optional": true,
586
+ "os": [
587
+ "linux"
588
+ ],
589
+ "engines": {
590
+ "node": ">=12"
591
+ }
592
+ },
593
+ "node_modules/@esbuild/linux-x64": {
594
+ "version": "0.21.5",
595
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
596
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
597
+ "cpu": [
598
+ "x64"
599
+ ],
600
+ "dev": true,
601
+ "license": "MIT",
602
+ "optional": true,
603
+ "os": [
604
+ "linux"
605
+ ],
606
+ "engines": {
607
+ "node": ">=12"
608
+ }
609
+ },
610
+ "node_modules/@esbuild/netbsd-x64": {
611
+ "version": "0.21.5",
612
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
613
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
614
+ "cpu": [
615
+ "x64"
616
+ ],
617
+ "dev": true,
618
+ "license": "MIT",
619
+ "optional": true,
620
+ "os": [
621
+ "netbsd"
622
+ ],
623
+ "engines": {
624
+ "node": ">=12"
625
+ }
626
+ },
627
+ "node_modules/@esbuild/openbsd-x64": {
628
+ "version": "0.21.5",
629
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
630
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
631
+ "cpu": [
632
+ "x64"
633
+ ],
634
+ "dev": true,
635
+ "license": "MIT",
636
+ "optional": true,
637
+ "os": [
638
+ "openbsd"
639
+ ],
640
+ "engines": {
641
+ "node": ">=12"
642
+ }
643
+ },
644
+ "node_modules/@esbuild/sunos-x64": {
645
+ "version": "0.21.5",
646
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
647
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
648
+ "cpu": [
649
+ "x64"
650
+ ],
651
+ "dev": true,
652
+ "license": "MIT",
653
+ "optional": true,
654
+ "os": [
655
+ "sunos"
656
+ ],
657
+ "engines": {
658
+ "node": ">=12"
659
+ }
660
+ },
661
+ "node_modules/@esbuild/win32-arm64": {
662
+ "version": "0.21.5",
663
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
664
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
665
+ "cpu": [
666
+ "arm64"
667
+ ],
668
+ "dev": true,
669
+ "license": "MIT",
670
+ "optional": true,
671
+ "os": [
672
+ "win32"
673
+ ],
674
+ "engines": {
675
+ "node": ">=12"
676
+ }
677
+ },
678
+ "node_modules/@esbuild/win32-ia32": {
679
+ "version": "0.21.5",
680
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
681
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
682
+ "cpu": [
683
+ "ia32"
684
+ ],
685
+ "dev": true,
686
+ "license": "MIT",
687
+ "optional": true,
688
+ "os": [
689
+ "win32"
690
+ ],
691
+ "engines": {
692
+ "node": ">=12"
693
+ }
694
+ },
695
+ "node_modules/@esbuild/win32-x64": {
696
+ "version": "0.21.5",
697
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
698
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
699
+ "cpu": [
700
+ "x64"
701
+ ],
702
+ "dev": true,
703
+ "license": "MIT",
704
+ "optional": true,
705
+ "os": [
706
+ "win32"
707
+ ],
708
+ "engines": {
709
+ "node": ">=12"
710
+ }
711
+ },
712
+ "node_modules/@jridgewell/gen-mapping": {
713
+ "version": "0.3.13",
714
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
715
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
716
+ "dev": true,
717
+ "license": "MIT",
718
+ "dependencies": {
719
+ "@jridgewell/sourcemap-codec": "^1.5.0",
720
+ "@jridgewell/trace-mapping": "^0.3.24"
721
+ }
722
+ },
723
+ "node_modules/@jridgewell/remapping": {
724
+ "version": "2.3.5",
725
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
726
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
727
+ "dev": true,
728
+ "license": "MIT",
729
+ "dependencies": {
730
+ "@jridgewell/gen-mapping": "^0.3.5",
731
+ "@jridgewell/trace-mapping": "^0.3.24"
732
+ }
733
+ },
734
+ "node_modules/@jridgewell/resolve-uri": {
735
+ "version": "3.1.2",
736
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
737
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
738
+ "dev": true,
739
+ "license": "MIT",
740
+ "engines": {
741
+ "node": ">=6.0.0"
742
+ }
743
+ },
744
+ "node_modules/@jridgewell/sourcemap-codec": {
745
+ "version": "1.5.5",
746
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
747
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
748
+ "dev": true,
749
+ "license": "MIT"
750
+ },
751
+ "node_modules/@jridgewell/trace-mapping": {
752
+ "version": "0.3.31",
753
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
754
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
755
+ "dev": true,
756
+ "license": "MIT",
757
+ "dependencies": {
758
+ "@jridgewell/resolve-uri": "^3.1.0",
759
+ "@jridgewell/sourcemap-codec": "^1.4.14"
760
+ }
761
+ },
762
+ "node_modules/@nodelib/fs.scandir": {
763
+ "version": "2.1.5",
764
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
765
+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
766
+ "dev": true,
767
+ "license": "MIT",
768
+ "dependencies": {
769
+ "@nodelib/fs.stat": "2.0.5",
770
+ "run-parallel": "^1.1.9"
771
+ },
772
+ "engines": {
773
+ "node": ">= 8"
774
+ }
775
+ },
776
+ "node_modules/@nodelib/fs.stat": {
777
+ "version": "2.0.5",
778
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
779
+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
780
+ "dev": true,
781
+ "license": "MIT",
782
+ "engines": {
783
+ "node": ">= 8"
784
+ }
785
+ },
786
+ "node_modules/@nodelib/fs.walk": {
787
+ "version": "1.2.8",
788
+ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
789
+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
790
+ "dev": true,
791
+ "license": "MIT",
792
+ "dependencies": {
793
+ "@nodelib/fs.scandir": "2.1.5",
794
+ "fastq": "^1.6.0"
795
+ },
796
+ "engines": {
797
+ "node": ">= 8"
798
+ }
799
+ },
800
+ "node_modules/@rolldown/pluginutils": {
801
+ "version": "1.0.0-beta.27",
802
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
803
+ "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
804
+ "dev": true,
805
+ "license": "MIT"
806
+ },
807
+ "node_modules/@rollup/rollup-android-arm-eabi": {
808
+ "version": "4.54.0",
809
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.54.0.tgz",
810
+ "integrity": "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==",
811
+ "cpu": [
812
+ "arm"
813
+ ],
814
+ "dev": true,
815
+ "license": "MIT",
816
+ "optional": true,
817
+ "os": [
818
+ "android"
819
+ ]
820
+ },
821
+ "node_modules/@rollup/rollup-android-arm64": {
822
+ "version": "4.54.0",
823
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.54.0.tgz",
824
+ "integrity": "sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==",
825
+ "cpu": [
826
+ "arm64"
827
+ ],
828
+ "dev": true,
829
+ "license": "MIT",
830
+ "optional": true,
831
+ "os": [
832
+ "android"
833
+ ]
834
+ },
835
+ "node_modules/@rollup/rollup-darwin-arm64": {
836
+ "version": "4.54.0",
837
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.54.0.tgz",
838
+ "integrity": "sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw==",
839
+ "cpu": [
840
+ "arm64"
841
+ ],
842
+ "dev": true,
843
+ "license": "MIT",
844
+ "optional": true,
845
+ "os": [
846
+ "darwin"
847
+ ]
848
+ },
849
+ "node_modules/@rollup/rollup-darwin-x64": {
850
+ "version": "4.54.0",
851
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.54.0.tgz",
852
+ "integrity": "sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==",
853
+ "cpu": [
854
+ "x64"
855
+ ],
856
+ "dev": true,
857
+ "license": "MIT",
858
+ "optional": true,
859
+ "os": [
860
+ "darwin"
861
+ ]
862
+ },
863
+ "node_modules/@rollup/rollup-freebsd-arm64": {
864
+ "version": "4.54.0",
865
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.54.0.tgz",
866
+ "integrity": "sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==",
867
+ "cpu": [
868
+ "arm64"
869
+ ],
870
+ "dev": true,
871
+ "license": "MIT",
872
+ "optional": true,
873
+ "os": [
874
+ "freebsd"
875
+ ]
876
+ },
877
+ "node_modules/@rollup/rollup-freebsd-x64": {
878
+ "version": "4.54.0",
879
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.54.0.tgz",
880
+ "integrity": "sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==",
881
+ "cpu": [
882
+ "x64"
883
+ ],
884
+ "dev": true,
885
+ "license": "MIT",
886
+ "optional": true,
887
+ "os": [
888
+ "freebsd"
889
+ ]
890
+ },
891
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
892
+ "version": "4.54.0",
893
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.54.0.tgz",
894
+ "integrity": "sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==",
895
+ "cpu": [
896
+ "arm"
897
+ ],
898
+ "dev": true,
899
+ "license": "MIT",
900
+ "optional": true,
901
+ "os": [
902
+ "linux"
903
+ ]
904
+ },
905
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
906
+ "version": "4.54.0",
907
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.54.0.tgz",
908
+ "integrity": "sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==",
909
+ "cpu": [
910
+ "arm"
911
+ ],
912
+ "dev": true,
913
+ "license": "MIT",
914
+ "optional": true,
915
+ "os": [
916
+ "linux"
917
+ ]
918
+ },
919
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
920
+ "version": "4.54.0",
921
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.54.0.tgz",
922
+ "integrity": "sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==",
923
+ "cpu": [
924
+ "arm64"
925
+ ],
926
+ "dev": true,
927
+ "license": "MIT",
928
+ "optional": true,
929
+ "os": [
930
+ "linux"
931
+ ]
932
+ },
933
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
934
+ "version": "4.54.0",
935
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.54.0.tgz",
936
+ "integrity": "sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==",
937
+ "cpu": [
938
+ "arm64"
939
+ ],
940
+ "dev": true,
941
+ "license": "MIT",
942
+ "optional": true,
943
+ "os": [
944
+ "linux"
945
+ ]
946
+ },
947
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
948
+ "version": "4.54.0",
949
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.54.0.tgz",
950
+ "integrity": "sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==",
951
+ "cpu": [
952
+ "loong64"
953
+ ],
954
+ "dev": true,
955
+ "license": "MIT",
956
+ "optional": true,
957
+ "os": [
958
+ "linux"
959
+ ]
960
+ },
961
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
962
+ "version": "4.54.0",
963
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.54.0.tgz",
964
+ "integrity": "sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==",
965
+ "cpu": [
966
+ "ppc64"
967
+ ],
968
+ "dev": true,
969
+ "license": "MIT",
970
+ "optional": true,
971
+ "os": [
972
+ "linux"
973
+ ]
974
+ },
975
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
976
+ "version": "4.54.0",
977
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.54.0.tgz",
978
+ "integrity": "sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==",
979
+ "cpu": [
980
+ "riscv64"
981
+ ],
982
+ "dev": true,
983
+ "license": "MIT",
984
+ "optional": true,
985
+ "os": [
986
+ "linux"
987
+ ]
988
+ },
989
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
990
+ "version": "4.54.0",
991
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.54.0.tgz",
992
+ "integrity": "sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==",
993
+ "cpu": [
994
+ "riscv64"
995
+ ],
996
+ "dev": true,
997
+ "license": "MIT",
998
+ "optional": true,
999
+ "os": [
1000
+ "linux"
1001
+ ]
1002
+ },
1003
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
1004
+ "version": "4.54.0",
1005
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.54.0.tgz",
1006
+ "integrity": "sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==",
1007
+ "cpu": [
1008
+ "s390x"
1009
+ ],
1010
+ "dev": true,
1011
+ "license": "MIT",
1012
+ "optional": true,
1013
+ "os": [
1014
+ "linux"
1015
+ ]
1016
+ },
1017
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
1018
+ "version": "4.54.0",
1019
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.54.0.tgz",
1020
+ "integrity": "sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==",
1021
+ "cpu": [
1022
+ "x64"
1023
+ ],
1024
+ "dev": true,
1025
+ "license": "MIT",
1026
+ "optional": true,
1027
+ "os": [
1028
+ "linux"
1029
+ ]
1030
+ },
1031
+ "node_modules/@rollup/rollup-linux-x64-musl": {
1032
+ "version": "4.54.0",
1033
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.54.0.tgz",
1034
+ "integrity": "sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==",
1035
+ "cpu": [
1036
+ "x64"
1037
+ ],
1038
+ "dev": true,
1039
+ "license": "MIT",
1040
+ "optional": true,
1041
+ "os": [
1042
+ "linux"
1043
+ ]
1044
+ },
1045
+ "node_modules/@rollup/rollup-openharmony-arm64": {
1046
+ "version": "4.54.0",
1047
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.54.0.tgz",
1048
+ "integrity": "sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==",
1049
+ "cpu": [
1050
+ "arm64"
1051
+ ],
1052
+ "dev": true,
1053
+ "license": "MIT",
1054
+ "optional": true,
1055
+ "os": [
1056
+ "openharmony"
1057
+ ]
1058
+ },
1059
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
1060
+ "version": "4.54.0",
1061
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.54.0.tgz",
1062
+ "integrity": "sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==",
1063
+ "cpu": [
1064
+ "arm64"
1065
+ ],
1066
+ "dev": true,
1067
+ "license": "MIT",
1068
+ "optional": true,
1069
+ "os": [
1070
+ "win32"
1071
+ ]
1072
+ },
1073
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
1074
+ "version": "4.54.0",
1075
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.54.0.tgz",
1076
+ "integrity": "sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==",
1077
+ "cpu": [
1078
+ "ia32"
1079
+ ],
1080
+ "dev": true,
1081
+ "license": "MIT",
1082
+ "optional": true,
1083
+ "os": [
1084
+ "win32"
1085
+ ]
1086
+ },
1087
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
1088
+ "version": "4.54.0",
1089
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.54.0.tgz",
1090
+ "integrity": "sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==",
1091
+ "cpu": [
1092
+ "x64"
1093
+ ],
1094
+ "dev": true,
1095
+ "license": "MIT",
1096
+ "optional": true,
1097
+ "os": [
1098
+ "win32"
1099
+ ]
1100
+ },
1101
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
1102
+ "version": "4.54.0",
1103
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.54.0.tgz",
1104
+ "integrity": "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==",
1105
+ "cpu": [
1106
+ "x64"
1107
+ ],
1108
+ "dev": true,
1109
+ "license": "MIT",
1110
+ "optional": true,
1111
+ "os": [
1112
+ "win32"
1113
+ ]
1114
+ },
1115
+ "node_modules/@types/babel__core": {
1116
+ "version": "7.20.5",
1117
+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
1118
+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
1119
+ "dev": true,
1120
+ "license": "MIT",
1121
+ "dependencies": {
1122
+ "@babel/parser": "^7.20.7",
1123
+ "@babel/types": "^7.20.7",
1124
+ "@types/babel__generator": "*",
1125
+ "@types/babel__template": "*",
1126
+ "@types/babel__traverse": "*"
1127
+ }
1128
+ },
1129
+ "node_modules/@types/babel__generator": {
1130
+ "version": "7.27.0",
1131
+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
1132
+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
1133
+ "dev": true,
1134
+ "license": "MIT",
1135
+ "dependencies": {
1136
+ "@babel/types": "^7.0.0"
1137
+ }
1138
+ },
1139
+ "node_modules/@types/babel__template": {
1140
+ "version": "7.4.4",
1141
+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
1142
+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
1143
+ "dev": true,
1144
+ "license": "MIT",
1145
+ "dependencies": {
1146
+ "@babel/parser": "^7.1.0",
1147
+ "@babel/types": "^7.0.0"
1148
+ }
1149
+ },
1150
+ "node_modules/@types/babel__traverse": {
1151
+ "version": "7.28.0",
1152
+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
1153
+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
1154
+ "dev": true,
1155
+ "license": "MIT",
1156
+ "dependencies": {
1157
+ "@babel/types": "^7.28.2"
1158
+ }
1159
+ },
1160
+ "node_modules/@types/estree": {
1161
+ "version": "1.0.8",
1162
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
1163
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
1164
+ "dev": true,
1165
+ "license": "MIT"
1166
+ },
1167
+ "node_modules/@types/prop-types": {
1168
+ "version": "15.7.15",
1169
+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
1170
+ "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
1171
+ "dev": true,
1172
+ "license": "MIT"
1173
+ },
1174
+ "node_modules/@types/react": {
1175
+ "version": "18.3.27",
1176
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
1177
+ "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
1178
+ "dev": true,
1179
+ "license": "MIT",
1180
+ "dependencies": {
1181
+ "@types/prop-types": "*",
1182
+ "csstype": "^3.2.2"
1183
+ }
1184
+ },
1185
+ "node_modules/@types/react-dom": {
1186
+ "version": "18.3.7",
1187
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
1188
+ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
1189
+ "dev": true,
1190
+ "license": "MIT",
1191
+ "peerDependencies": {
1192
+ "@types/react": "^18.0.0"
1193
+ }
1194
+ },
1195
+ "node_modules/@vitejs/plugin-react": {
1196
+ "version": "4.7.0",
1197
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
1198
+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
1199
+ "dev": true,
1200
+ "license": "MIT",
1201
+ "dependencies": {
1202
+ "@babel/core": "^7.28.0",
1203
+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",
1204
+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",
1205
+ "@rolldown/pluginutils": "1.0.0-beta.27",
1206
+ "@types/babel__core": "^7.20.5",
1207
+ "react-refresh": "^0.17.0"
1208
+ },
1209
+ "engines": {
1210
+ "node": "^14.18.0 || >=16.0.0"
1211
+ },
1212
+ "peerDependencies": {
1213
+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
1214
+ }
1215
+ },
1216
+ "node_modules/any-promise": {
1217
+ "version": "1.3.0",
1218
+ "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
1219
+ "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
1220
+ "dev": true,
1221
+ "license": "MIT"
1222
+ },
1223
+ "node_modules/anymatch": {
1224
+ "version": "3.1.3",
1225
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
1226
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
1227
+ "dev": true,
1228
+ "license": "ISC",
1229
+ "dependencies": {
1230
+ "normalize-path": "^3.0.0",
1231
+ "picomatch": "^2.0.4"
1232
+ },
1233
+ "engines": {
1234
+ "node": ">= 8"
1235
+ }
1236
+ },
1237
+ "node_modules/arg": {
1238
+ "version": "5.0.2",
1239
+ "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
1240
+ "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
1241
+ "dev": true,
1242
+ "license": "MIT"
1243
+ },
1244
+ "node_modules/autoprefixer": {
1245
+ "version": "10.4.23",
1246
+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz",
1247
+ "integrity": "sha512-YYTXSFulfwytnjAPlw8QHncHJmlvFKtczb8InXaAx9Q0LbfDnfEYDE55omerIJKihhmU61Ft+cAOSzQVaBUmeA==",
1248
+ "dev": true,
1249
+ "funding": [
1250
+ {
1251
+ "type": "opencollective",
1252
+ "url": "https://opencollective.com/postcss/"
1253
+ },
1254
+ {
1255
+ "type": "tidelift",
1256
+ "url": "https://tidelift.com/funding/github/npm/autoprefixer"
1257
+ },
1258
+ {
1259
+ "type": "github",
1260
+ "url": "https://github.com/sponsors/ai"
1261
+ }
1262
+ ],
1263
+ "license": "MIT",
1264
+ "dependencies": {
1265
+ "browserslist": "^4.28.1",
1266
+ "caniuse-lite": "^1.0.30001760",
1267
+ "fraction.js": "^5.3.4",
1268
+ "picocolors": "^1.1.1",
1269
+ "postcss-value-parser": "^4.2.0"
1270
+ },
1271
+ "bin": {
1272
+ "autoprefixer": "bin/autoprefixer"
1273
+ },
1274
+ "engines": {
1275
+ "node": "^10 || ^12 || >=14"
1276
+ },
1277
+ "peerDependencies": {
1278
+ "postcss": "^8.1.0"
1279
+ }
1280
+ },
1281
+ "node_modules/baseline-browser-mapping": {
1282
+ "version": "2.9.11",
1283
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
1284
+ "integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==",
1285
+ "dev": true,
1286
+ "license": "Apache-2.0",
1287
+ "bin": {
1288
+ "baseline-browser-mapping": "dist/cli.js"
1289
+ }
1290
+ },
1291
+ "node_modules/binary-extensions": {
1292
+ "version": "2.3.0",
1293
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
1294
+ "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
1295
+ "dev": true,
1296
+ "license": "MIT",
1297
+ "engines": {
1298
+ "node": ">=8"
1299
+ },
1300
+ "funding": {
1301
+ "url": "https://github.com/sponsors/sindresorhus"
1302
+ }
1303
+ },
1304
+ "node_modules/braces": {
1305
+ "version": "3.0.3",
1306
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
1307
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
1308
+ "dev": true,
1309
+ "license": "MIT",
1310
+ "dependencies": {
1311
+ "fill-range": "^7.1.1"
1312
+ },
1313
+ "engines": {
1314
+ "node": ">=8"
1315
+ }
1316
+ },
1317
+ "node_modules/browserslist": {
1318
+ "version": "4.28.1",
1319
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",
1320
+ "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",
1321
+ "dev": true,
1322
+ "funding": [
1323
+ {
1324
+ "type": "opencollective",
1325
+ "url": "https://opencollective.com/browserslist"
1326
+ },
1327
+ {
1328
+ "type": "tidelift",
1329
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
1330
+ },
1331
+ {
1332
+ "type": "github",
1333
+ "url": "https://github.com/sponsors/ai"
1334
+ }
1335
+ ],
1336
+ "license": "MIT",
1337
+ "dependencies": {
1338
+ "baseline-browser-mapping": "^2.9.0",
1339
+ "caniuse-lite": "^1.0.30001759",
1340
+ "electron-to-chromium": "^1.5.263",
1341
+ "node-releases": "^2.0.27",
1342
+ "update-browserslist-db": "^1.2.0"
1343
+ },
1344
+ "bin": {
1345
+ "browserslist": "cli.js"
1346
+ },
1347
+ "engines": {
1348
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
1349
+ }
1350
+ },
1351
+ "node_modules/camelcase-css": {
1352
+ "version": "2.0.1",
1353
+ "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
1354
+ "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",
1355
+ "dev": true,
1356
+ "license": "MIT",
1357
+ "engines": {
1358
+ "node": ">= 6"
1359
+ }
1360
+ },
1361
+ "node_modules/caniuse-lite": {
1362
+ "version": "1.0.30001761",
1363
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
1364
+ "integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
1365
+ "dev": true,
1366
+ "funding": [
1367
+ {
1368
+ "type": "opencollective",
1369
+ "url": "https://opencollective.com/browserslist"
1370
+ },
1371
+ {
1372
+ "type": "tidelift",
1373
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
1374
+ },
1375
+ {
1376
+ "type": "github",
1377
+ "url": "https://github.com/sponsors/ai"
1378
+ }
1379
+ ],
1380
+ "license": "CC-BY-4.0"
1381
+ },
1382
+ "node_modules/chokidar": {
1383
+ "version": "3.6.0",
1384
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
1385
+ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
1386
+ "dev": true,
1387
+ "license": "MIT",
1388
+ "dependencies": {
1389
+ "anymatch": "~3.1.2",
1390
+ "braces": "~3.0.2",
1391
+ "glob-parent": "~5.1.2",
1392
+ "is-binary-path": "~2.1.0",
1393
+ "is-glob": "~4.0.1",
1394
+ "normalize-path": "~3.0.0",
1395
+ "readdirp": "~3.6.0"
1396
+ },
1397
+ "engines": {
1398
+ "node": ">= 8.10.0"
1399
+ },
1400
+ "funding": {
1401
+ "url": "https://paulmillr.com/funding/"
1402
+ },
1403
+ "optionalDependencies": {
1404
+ "fsevents": "~2.3.2"
1405
+ }
1406
+ },
1407
+ "node_modules/chokidar/node_modules/glob-parent": {
1408
+ "version": "5.1.2",
1409
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
1410
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
1411
+ "dev": true,
1412
+ "license": "ISC",
1413
+ "dependencies": {
1414
+ "is-glob": "^4.0.1"
1415
+ },
1416
+ "engines": {
1417
+ "node": ">= 6"
1418
+ }
1419
+ },
1420
+ "node_modules/commander": {
1421
+ "version": "4.1.1",
1422
+ "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
1423
+ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
1424
+ "dev": true,
1425
+ "license": "MIT",
1426
+ "engines": {
1427
+ "node": ">= 6"
1428
+ }
1429
+ },
1430
+ "node_modules/convert-source-map": {
1431
+ "version": "2.0.0",
1432
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
1433
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
1434
+ "dev": true,
1435
+ "license": "MIT"
1436
+ },
1437
+ "node_modules/cssesc": {
1438
+ "version": "3.0.0",
1439
+ "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
1440
+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
1441
+ "dev": true,
1442
+ "license": "MIT",
1443
+ "bin": {
1444
+ "cssesc": "bin/cssesc"
1445
+ },
1446
+ "engines": {
1447
+ "node": ">=4"
1448
+ }
1449
+ },
1450
+ "node_modules/csstype": {
1451
+ "version": "3.2.3",
1452
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
1453
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
1454
+ "dev": true,
1455
+ "license": "MIT"
1456
+ },
1457
+ "node_modules/debug": {
1458
+ "version": "4.4.3",
1459
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
1460
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
1461
+ "dev": true,
1462
+ "license": "MIT",
1463
+ "dependencies": {
1464
+ "ms": "^2.1.3"
1465
+ },
1466
+ "engines": {
1467
+ "node": ">=6.0"
1468
+ },
1469
+ "peerDependenciesMeta": {
1470
+ "supports-color": {
1471
+ "optional": true
1472
+ }
1473
+ }
1474
+ },
1475
+ "node_modules/didyoumean": {
1476
+ "version": "1.2.2",
1477
+ "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
1478
+ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
1479
+ "dev": true,
1480
+ "license": "Apache-2.0"
1481
+ },
1482
+ "node_modules/dlv": {
1483
+ "version": "1.1.3",
1484
+ "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
1485
+ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
1486
+ "dev": true,
1487
+ "license": "MIT"
1488
+ },
1489
+ "node_modules/electron-to-chromium": {
1490
+ "version": "1.5.267",
1491
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz",
1492
+ "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==",
1493
+ "dev": true,
1494
+ "license": "ISC"
1495
+ },
1496
+ "node_modules/esbuild": {
1497
+ "version": "0.21.5",
1498
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
1499
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
1500
+ "dev": true,
1501
+ "hasInstallScript": true,
1502
+ "license": "MIT",
1503
+ "bin": {
1504
+ "esbuild": "bin/esbuild"
1505
+ },
1506
+ "engines": {
1507
+ "node": ">=12"
1508
+ },
1509
+ "optionalDependencies": {
1510
+ "@esbuild/aix-ppc64": "0.21.5",
1511
+ "@esbuild/android-arm": "0.21.5",
1512
+ "@esbuild/android-arm64": "0.21.5",
1513
+ "@esbuild/android-x64": "0.21.5",
1514
+ "@esbuild/darwin-arm64": "0.21.5",
1515
+ "@esbuild/darwin-x64": "0.21.5",
1516
+ "@esbuild/freebsd-arm64": "0.21.5",
1517
+ "@esbuild/freebsd-x64": "0.21.5",
1518
+ "@esbuild/linux-arm": "0.21.5",
1519
+ "@esbuild/linux-arm64": "0.21.5",
1520
+ "@esbuild/linux-ia32": "0.21.5",
1521
+ "@esbuild/linux-loong64": "0.21.5",
1522
+ "@esbuild/linux-mips64el": "0.21.5",
1523
+ "@esbuild/linux-ppc64": "0.21.5",
1524
+ "@esbuild/linux-riscv64": "0.21.5",
1525
+ "@esbuild/linux-s390x": "0.21.5",
1526
+ "@esbuild/linux-x64": "0.21.5",
1527
+ "@esbuild/netbsd-x64": "0.21.5",
1528
+ "@esbuild/openbsd-x64": "0.21.5",
1529
+ "@esbuild/sunos-x64": "0.21.5",
1530
+ "@esbuild/win32-arm64": "0.21.5",
1531
+ "@esbuild/win32-ia32": "0.21.5",
1532
+ "@esbuild/win32-x64": "0.21.5"
1533
+ }
1534
+ },
1535
+ "node_modules/escalade": {
1536
+ "version": "3.2.0",
1537
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
1538
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
1539
+ "dev": true,
1540
+ "license": "MIT",
1541
+ "engines": {
1542
+ "node": ">=6"
1543
+ }
1544
+ },
1545
+ "node_modules/fast-glob": {
1546
+ "version": "3.3.3",
1547
+ "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
1548
+ "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
1549
+ "dev": true,
1550
+ "license": "MIT",
1551
+ "dependencies": {
1552
+ "@nodelib/fs.stat": "^2.0.2",
1553
+ "@nodelib/fs.walk": "^1.2.3",
1554
+ "glob-parent": "^5.1.2",
1555
+ "merge2": "^1.3.0",
1556
+ "micromatch": "^4.0.8"
1557
+ },
1558
+ "engines": {
1559
+ "node": ">=8.6.0"
1560
+ }
1561
+ },
1562
+ "node_modules/fast-glob/node_modules/glob-parent": {
1563
+ "version": "5.1.2",
1564
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
1565
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
1566
+ "dev": true,
1567
+ "license": "ISC",
1568
+ "dependencies": {
1569
+ "is-glob": "^4.0.1"
1570
+ },
1571
+ "engines": {
1572
+ "node": ">= 6"
1573
+ }
1574
+ },
1575
+ "node_modules/fastq": {
1576
+ "version": "1.19.1",
1577
+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
1578
+ "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
1579
+ "dev": true,
1580
+ "license": "ISC",
1581
+ "dependencies": {
1582
+ "reusify": "^1.0.4"
1583
+ }
1584
+ },
1585
+ "node_modules/fill-range": {
1586
+ "version": "7.1.1",
1587
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
1588
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
1589
+ "dev": true,
1590
+ "license": "MIT",
1591
+ "dependencies": {
1592
+ "to-regex-range": "^5.0.1"
1593
+ },
1594
+ "engines": {
1595
+ "node": ">=8"
1596
+ }
1597
+ },
1598
+ "node_modules/fraction.js": {
1599
+ "version": "5.3.4",
1600
+ "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
1601
+ "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",
1602
+ "dev": true,
1603
+ "license": "MIT",
1604
+ "engines": {
1605
+ "node": "*"
1606
+ },
1607
+ "funding": {
1608
+ "type": "github",
1609
+ "url": "https://github.com/sponsors/rawify"
1610
+ }
1611
+ },
1612
+ "node_modules/framer-motion": {
1613
+ "version": "11.18.2",
1614
+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.18.2.tgz",
1615
+ "integrity": "sha512-5F5Och7wrvtLVElIpclDT0CBzMVg3dL22B64aZwHtsIY8RB4mXICLrkajK4G9R+ieSAGcgrLeae2SeUTg2pr6w==",
1616
+ "license": "MIT",
1617
+ "dependencies": {
1618
+ "motion-dom": "^11.18.1",
1619
+ "motion-utils": "^11.18.1",
1620
+ "tslib": "^2.4.0"
1621
+ },
1622
+ "peerDependencies": {
1623
+ "@emotion/is-prop-valid": "*",
1624
+ "react": "^18.0.0 || ^19.0.0",
1625
+ "react-dom": "^18.0.0 || ^19.0.0"
1626
+ },
1627
+ "peerDependenciesMeta": {
1628
+ "@emotion/is-prop-valid": {
1629
+ "optional": true
1630
+ },
1631
+ "react": {
1632
+ "optional": true
1633
+ },
1634
+ "react-dom": {
1635
+ "optional": true
1636
+ }
1637
+ }
1638
+ },
1639
+ "node_modules/fsevents": {
1640
+ "version": "2.3.3",
1641
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
1642
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
1643
+ "dev": true,
1644
+ "hasInstallScript": true,
1645
+ "license": "MIT",
1646
+ "optional": true,
1647
+ "os": [
1648
+ "darwin"
1649
+ ],
1650
+ "engines": {
1651
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
1652
+ }
1653
+ },
1654
+ "node_modules/function-bind": {
1655
+ "version": "1.1.2",
1656
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
1657
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
1658
+ "dev": true,
1659
+ "license": "MIT",
1660
+ "funding": {
1661
+ "url": "https://github.com/sponsors/ljharb"
1662
+ }
1663
+ },
1664
+ "node_modules/gensync": {
1665
+ "version": "1.0.0-beta.2",
1666
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
1667
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
1668
+ "dev": true,
1669
+ "license": "MIT",
1670
+ "engines": {
1671
+ "node": ">=6.9.0"
1672
+ }
1673
+ },
1674
+ "node_modules/glob-parent": {
1675
+ "version": "6.0.2",
1676
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
1677
+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
1678
+ "dev": true,
1679
+ "license": "ISC",
1680
+ "dependencies": {
1681
+ "is-glob": "^4.0.3"
1682
+ },
1683
+ "engines": {
1684
+ "node": ">=10.13.0"
1685
+ }
1686
+ },
1687
+ "node_modules/hasown": {
1688
+ "version": "2.0.2",
1689
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
1690
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
1691
+ "dev": true,
1692
+ "license": "MIT",
1693
+ "dependencies": {
1694
+ "function-bind": "^1.1.2"
1695
+ },
1696
+ "engines": {
1697
+ "node": ">= 0.4"
1698
+ }
1699
+ },
1700
+ "node_modules/is-binary-path": {
1701
+ "version": "2.1.0",
1702
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
1703
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
1704
+ "dev": true,
1705
+ "license": "MIT",
1706
+ "dependencies": {
1707
+ "binary-extensions": "^2.0.0"
1708
+ },
1709
+ "engines": {
1710
+ "node": ">=8"
1711
+ }
1712
+ },
1713
+ "node_modules/is-core-module": {
1714
+ "version": "2.16.1",
1715
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
1716
+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
1717
+ "dev": true,
1718
+ "license": "MIT",
1719
+ "dependencies": {
1720
+ "hasown": "^2.0.2"
1721
+ },
1722
+ "engines": {
1723
+ "node": ">= 0.4"
1724
+ },
1725
+ "funding": {
1726
+ "url": "https://github.com/sponsors/ljharb"
1727
+ }
1728
+ },
1729
+ "node_modules/is-extglob": {
1730
+ "version": "2.1.1",
1731
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
1732
+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
1733
+ "dev": true,
1734
+ "license": "MIT",
1735
+ "engines": {
1736
+ "node": ">=0.10.0"
1737
+ }
1738
+ },
1739
+ "node_modules/is-glob": {
1740
+ "version": "4.0.3",
1741
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
1742
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
1743
+ "dev": true,
1744
+ "license": "MIT",
1745
+ "dependencies": {
1746
+ "is-extglob": "^2.1.1"
1747
+ },
1748
+ "engines": {
1749
+ "node": ">=0.10.0"
1750
+ }
1751
+ },
1752
+ "node_modules/is-number": {
1753
+ "version": "7.0.0",
1754
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
1755
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
1756
+ "dev": true,
1757
+ "license": "MIT",
1758
+ "engines": {
1759
+ "node": ">=0.12.0"
1760
+ }
1761
+ },
1762
+ "node_modules/jiti": {
1763
+ "version": "1.21.7",
1764
+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",
1765
+ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
1766
+ "dev": true,
1767
+ "license": "MIT",
1768
+ "bin": {
1769
+ "jiti": "bin/jiti.js"
1770
+ }
1771
+ },
1772
+ "node_modules/js-tokens": {
1773
+ "version": "4.0.0",
1774
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
1775
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
1776
+ "license": "MIT"
1777
+ },
1778
+ "node_modules/jsesc": {
1779
+ "version": "3.1.0",
1780
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
1781
+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
1782
+ "dev": true,
1783
+ "license": "MIT",
1784
+ "bin": {
1785
+ "jsesc": "bin/jsesc"
1786
+ },
1787
+ "engines": {
1788
+ "node": ">=6"
1789
+ }
1790
+ },
1791
+ "node_modules/json5": {
1792
+ "version": "2.2.3",
1793
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
1794
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
1795
+ "dev": true,
1796
+ "license": "MIT",
1797
+ "bin": {
1798
+ "json5": "lib/cli.js"
1799
+ },
1800
+ "engines": {
1801
+ "node": ">=6"
1802
+ }
1803
+ },
1804
+ "node_modules/lilconfig": {
1805
+ "version": "3.1.3",
1806
+ "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
1807
+ "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
1808
+ "dev": true,
1809
+ "license": "MIT",
1810
+ "engines": {
1811
+ "node": ">=14"
1812
+ },
1813
+ "funding": {
1814
+ "url": "https://github.com/sponsors/antonk52"
1815
+ }
1816
+ },
1817
+ "node_modules/lines-and-columns": {
1818
+ "version": "1.2.4",
1819
+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
1820
+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
1821
+ "dev": true,
1822
+ "license": "MIT"
1823
+ },
1824
+ "node_modules/loose-envify": {
1825
+ "version": "1.4.0",
1826
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
1827
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
1828
+ "license": "MIT",
1829
+ "dependencies": {
1830
+ "js-tokens": "^3.0.0 || ^4.0.0"
1831
+ },
1832
+ "bin": {
1833
+ "loose-envify": "cli.js"
1834
+ }
1835
+ },
1836
+ "node_modules/lru-cache": {
1837
+ "version": "5.1.1",
1838
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
1839
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
1840
+ "dev": true,
1841
+ "license": "ISC",
1842
+ "dependencies": {
1843
+ "yallist": "^3.0.2"
1844
+ }
1845
+ },
1846
+ "node_modules/merge2": {
1847
+ "version": "1.4.1",
1848
+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
1849
+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
1850
+ "dev": true,
1851
+ "license": "MIT",
1852
+ "engines": {
1853
+ "node": ">= 8"
1854
+ }
1855
+ },
1856
+ "node_modules/micromatch": {
1857
+ "version": "4.0.8",
1858
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
1859
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
1860
+ "dev": true,
1861
+ "license": "MIT",
1862
+ "dependencies": {
1863
+ "braces": "^3.0.3",
1864
+ "picomatch": "^2.3.1"
1865
+ },
1866
+ "engines": {
1867
+ "node": ">=8.6"
1868
+ }
1869
+ },
1870
+ "node_modules/motion-dom": {
1871
+ "version": "11.18.1",
1872
+ "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-11.18.1.tgz",
1873
+ "integrity": "sha512-g76KvA001z+atjfxczdRtw/RXOM3OMSdd1f4DL77qCTF/+avrRJiawSG4yDibEQ215sr9kpinSlX2pCTJ9zbhw==",
1874
+ "license": "MIT",
1875
+ "dependencies": {
1876
+ "motion-utils": "^11.18.1"
1877
+ }
1878
+ },
1879
+ "node_modules/motion-utils": {
1880
+ "version": "11.18.1",
1881
+ "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-11.18.1.tgz",
1882
+ "integrity": "sha512-49Kt+HKjtbJKLtgO/LKj9Ld+6vw9BjH5d9sc40R/kVyH8GLAXgT42M2NnuPcJNuA3s9ZfZBUcwIgpmZWGEE+hA==",
1883
+ "license": "MIT"
1884
+ },
1885
+ "node_modules/ms": {
1886
+ "version": "2.1.3",
1887
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1888
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1889
+ "dev": true,
1890
+ "license": "MIT"
1891
+ },
1892
+ "node_modules/mz": {
1893
+ "version": "2.7.0",
1894
+ "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
1895
+ "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
1896
+ "dev": true,
1897
+ "license": "MIT",
1898
+ "dependencies": {
1899
+ "any-promise": "^1.0.0",
1900
+ "object-assign": "^4.0.1",
1901
+ "thenify-all": "^1.0.0"
1902
+ }
1903
+ },
1904
+ "node_modules/nanoid": {
1905
+ "version": "3.3.11",
1906
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
1907
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
1908
+ "dev": true,
1909
+ "funding": [
1910
+ {
1911
+ "type": "github",
1912
+ "url": "https://github.com/sponsors/ai"
1913
+ }
1914
+ ],
1915
+ "license": "MIT",
1916
+ "bin": {
1917
+ "nanoid": "bin/nanoid.cjs"
1918
+ },
1919
+ "engines": {
1920
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
1921
+ }
1922
+ },
1923
+ "node_modules/node-releases": {
1924
+ "version": "2.0.27",
1925
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
1926
+ "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",
1927
+ "dev": true,
1928
+ "license": "MIT"
1929
+ },
1930
+ "node_modules/normalize-path": {
1931
+ "version": "3.0.0",
1932
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
1933
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
1934
+ "dev": true,
1935
+ "license": "MIT",
1936
+ "engines": {
1937
+ "node": ">=0.10.0"
1938
+ }
1939
+ },
1940
+ "node_modules/object-assign": {
1941
+ "version": "4.1.1",
1942
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
1943
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
1944
+ "dev": true,
1945
+ "license": "MIT",
1946
+ "engines": {
1947
+ "node": ">=0.10.0"
1948
+ }
1949
+ },
1950
+ "node_modules/object-hash": {
1951
+ "version": "3.0.0",
1952
+ "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
1953
+ "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
1954
+ "dev": true,
1955
+ "license": "MIT",
1956
+ "engines": {
1957
+ "node": ">= 6"
1958
+ }
1959
+ },
1960
+ "node_modules/path-parse": {
1961
+ "version": "1.0.7",
1962
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
1963
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
1964
+ "dev": true,
1965
+ "license": "MIT"
1966
+ },
1967
+ "node_modules/picocolors": {
1968
+ "version": "1.1.1",
1969
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
1970
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
1971
+ "dev": true,
1972
+ "license": "ISC"
1973
+ },
1974
+ "node_modules/picomatch": {
1975
+ "version": "2.3.1",
1976
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
1977
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
1978
+ "dev": true,
1979
+ "license": "MIT",
1980
+ "engines": {
1981
+ "node": ">=8.6"
1982
+ },
1983
+ "funding": {
1984
+ "url": "https://github.com/sponsors/jonschlinkert"
1985
+ }
1986
+ },
1987
+ "node_modules/pify": {
1988
+ "version": "2.3.0",
1989
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
1990
+ "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
1991
+ "dev": true,
1992
+ "license": "MIT",
1993
+ "engines": {
1994
+ "node": ">=0.10.0"
1995
+ }
1996
+ },
1997
+ "node_modules/pirates": {
1998
+ "version": "4.0.7",
1999
+ "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
2000
+ "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
2001
+ "dev": true,
2002
+ "license": "MIT",
2003
+ "engines": {
2004
+ "node": ">= 6"
2005
+ }
2006
+ },
2007
+ "node_modules/postcss": {
2008
+ "version": "8.5.6",
2009
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
2010
+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
2011
+ "dev": true,
2012
+ "funding": [
2013
+ {
2014
+ "type": "opencollective",
2015
+ "url": "https://opencollective.com/postcss/"
2016
+ },
2017
+ {
2018
+ "type": "tidelift",
2019
+ "url": "https://tidelift.com/funding/github/npm/postcss"
2020
+ },
2021
+ {
2022
+ "type": "github",
2023
+ "url": "https://github.com/sponsors/ai"
2024
+ }
2025
+ ],
2026
+ "license": "MIT",
2027
+ "dependencies": {
2028
+ "nanoid": "^3.3.11",
2029
+ "picocolors": "^1.1.1",
2030
+ "source-map-js": "^1.2.1"
2031
+ },
2032
+ "engines": {
2033
+ "node": "^10 || ^12 || >=14"
2034
+ }
2035
+ },
2036
+ "node_modules/postcss-import": {
2037
+ "version": "15.1.0",
2038
+ "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz",
2039
+ "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",
2040
+ "dev": true,
2041
+ "license": "MIT",
2042
+ "dependencies": {
2043
+ "postcss-value-parser": "^4.0.0",
2044
+ "read-cache": "^1.0.0",
2045
+ "resolve": "^1.1.7"
2046
+ },
2047
+ "engines": {
2048
+ "node": ">=14.0.0"
2049
+ },
2050
+ "peerDependencies": {
2051
+ "postcss": "^8.0.0"
2052
+ }
2053
+ },
2054
+ "node_modules/postcss-js": {
2055
+ "version": "4.1.0",
2056
+ "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz",
2057
+ "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",
2058
+ "dev": true,
2059
+ "funding": [
2060
+ {
2061
+ "type": "opencollective",
2062
+ "url": "https://opencollective.com/postcss/"
2063
+ },
2064
+ {
2065
+ "type": "github",
2066
+ "url": "https://github.com/sponsors/ai"
2067
+ }
2068
+ ],
2069
+ "license": "MIT",
2070
+ "dependencies": {
2071
+ "camelcase-css": "^2.0.1"
2072
+ },
2073
+ "engines": {
2074
+ "node": "^12 || ^14 || >= 16"
2075
+ },
2076
+ "peerDependencies": {
2077
+ "postcss": "^8.4.21"
2078
+ }
2079
+ },
2080
+ "node_modules/postcss-load-config": {
2081
+ "version": "6.0.1",
2082
+ "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
2083
+ "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
2084
+ "dev": true,
2085
+ "funding": [
2086
+ {
2087
+ "type": "opencollective",
2088
+ "url": "https://opencollective.com/postcss/"
2089
+ },
2090
+ {
2091
+ "type": "github",
2092
+ "url": "https://github.com/sponsors/ai"
2093
+ }
2094
+ ],
2095
+ "license": "MIT",
2096
+ "dependencies": {
2097
+ "lilconfig": "^3.1.1"
2098
+ },
2099
+ "engines": {
2100
+ "node": ">= 18"
2101
+ },
2102
+ "peerDependencies": {
2103
+ "jiti": ">=1.21.0",
2104
+ "postcss": ">=8.0.9",
2105
+ "tsx": "^4.8.1",
2106
+ "yaml": "^2.4.2"
2107
+ },
2108
+ "peerDependenciesMeta": {
2109
+ "jiti": {
2110
+ "optional": true
2111
+ },
2112
+ "postcss": {
2113
+ "optional": true
2114
+ },
2115
+ "tsx": {
2116
+ "optional": true
2117
+ },
2118
+ "yaml": {
2119
+ "optional": true
2120
+ }
2121
+ }
2122
+ },
2123
+ "node_modules/postcss-nested": {
2124
+ "version": "6.2.0",
2125
+ "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",
2126
+ "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",
2127
+ "dev": true,
2128
+ "funding": [
2129
+ {
2130
+ "type": "opencollective",
2131
+ "url": "https://opencollective.com/postcss/"
2132
+ },
2133
+ {
2134
+ "type": "github",
2135
+ "url": "https://github.com/sponsors/ai"
2136
+ }
2137
+ ],
2138
+ "license": "MIT",
2139
+ "dependencies": {
2140
+ "postcss-selector-parser": "^6.1.1"
2141
+ },
2142
+ "engines": {
2143
+ "node": ">=12.0"
2144
+ },
2145
+ "peerDependencies": {
2146
+ "postcss": "^8.2.14"
2147
+ }
2148
+ },
2149
+ "node_modules/postcss-selector-parser": {
2150
+ "version": "6.1.2",
2151
+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
2152
+ "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
2153
+ "dev": true,
2154
+ "license": "MIT",
2155
+ "dependencies": {
2156
+ "cssesc": "^3.0.0",
2157
+ "util-deprecate": "^1.0.2"
2158
+ },
2159
+ "engines": {
2160
+ "node": ">=4"
2161
+ }
2162
+ },
2163
+ "node_modules/postcss-value-parser": {
2164
+ "version": "4.2.0",
2165
+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
2166
+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
2167
+ "dev": true,
2168
+ "license": "MIT"
2169
+ },
2170
+ "node_modules/queue-microtask": {
2171
+ "version": "1.2.3",
2172
+ "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
2173
+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
2174
+ "dev": true,
2175
+ "funding": [
2176
+ {
2177
+ "type": "github",
2178
+ "url": "https://github.com/sponsors/feross"
2179
+ },
2180
+ {
2181
+ "type": "patreon",
2182
+ "url": "https://www.patreon.com/feross"
2183
+ },
2184
+ {
2185
+ "type": "consulting",
2186
+ "url": "https://feross.org/support"
2187
+ }
2188
+ ],
2189
+ "license": "MIT"
2190
+ },
2191
+ "node_modules/react": {
2192
+ "version": "18.3.1",
2193
+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
2194
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
2195
+ "license": "MIT",
2196
+ "dependencies": {
2197
+ "loose-envify": "^1.1.0"
2198
+ },
2199
+ "engines": {
2200
+ "node": ">=0.10.0"
2201
+ }
2202
+ },
2203
+ "node_modules/react-dom": {
2204
+ "version": "18.3.1",
2205
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
2206
+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
2207
+ "license": "MIT",
2208
+ "dependencies": {
2209
+ "loose-envify": "^1.1.0",
2210
+ "scheduler": "^0.23.2"
2211
+ },
2212
+ "peerDependencies": {
2213
+ "react": "^18.3.1"
2214
+ }
2215
+ },
2216
+ "node_modules/react-refresh": {
2217
+ "version": "0.17.0",
2218
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
2219
+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
2220
+ "dev": true,
2221
+ "license": "MIT",
2222
+ "engines": {
2223
+ "node": ">=0.10.0"
2224
+ }
2225
+ },
2226
+ "node_modules/read-cache": {
2227
+ "version": "1.0.0",
2228
+ "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
2229
+ "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",
2230
+ "dev": true,
2231
+ "license": "MIT",
2232
+ "dependencies": {
2233
+ "pify": "^2.3.0"
2234
+ }
2235
+ },
2236
+ "node_modules/readdirp": {
2237
+ "version": "3.6.0",
2238
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
2239
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
2240
+ "dev": true,
2241
+ "license": "MIT",
2242
+ "dependencies": {
2243
+ "picomatch": "^2.2.1"
2244
+ },
2245
+ "engines": {
2246
+ "node": ">=8.10.0"
2247
+ }
2248
+ },
2249
+ "node_modules/resolve": {
2250
+ "version": "1.22.11",
2251
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
2252
+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",
2253
+ "dev": true,
2254
+ "license": "MIT",
2255
+ "dependencies": {
2256
+ "is-core-module": "^2.16.1",
2257
+ "path-parse": "^1.0.7",
2258
+ "supports-preserve-symlinks-flag": "^1.0.0"
2259
+ },
2260
+ "bin": {
2261
+ "resolve": "bin/resolve"
2262
+ },
2263
+ "engines": {
2264
+ "node": ">= 0.4"
2265
+ },
2266
+ "funding": {
2267
+ "url": "https://github.com/sponsors/ljharb"
2268
+ }
2269
+ },
2270
+ "node_modules/reusify": {
2271
+ "version": "1.1.0",
2272
+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
2273
+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
2274
+ "dev": true,
2275
+ "license": "MIT",
2276
+ "engines": {
2277
+ "iojs": ">=1.0.0",
2278
+ "node": ">=0.10.0"
2279
+ }
2280
+ },
2281
+ "node_modules/rollup": {
2282
+ "version": "4.54.0",
2283
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.54.0.tgz",
2284
+ "integrity": "sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw==",
2285
+ "dev": true,
2286
+ "license": "MIT",
2287
+ "dependencies": {
2288
+ "@types/estree": "1.0.8"
2289
+ },
2290
+ "bin": {
2291
+ "rollup": "dist/bin/rollup"
2292
+ },
2293
+ "engines": {
2294
+ "node": ">=18.0.0",
2295
+ "npm": ">=8.0.0"
2296
+ },
2297
+ "optionalDependencies": {
2298
+ "@rollup/rollup-android-arm-eabi": "4.54.0",
2299
+ "@rollup/rollup-android-arm64": "4.54.0",
2300
+ "@rollup/rollup-darwin-arm64": "4.54.0",
2301
+ "@rollup/rollup-darwin-x64": "4.54.0",
2302
+ "@rollup/rollup-freebsd-arm64": "4.54.0",
2303
+ "@rollup/rollup-freebsd-x64": "4.54.0",
2304
+ "@rollup/rollup-linux-arm-gnueabihf": "4.54.0",
2305
+ "@rollup/rollup-linux-arm-musleabihf": "4.54.0",
2306
+ "@rollup/rollup-linux-arm64-gnu": "4.54.0",
2307
+ "@rollup/rollup-linux-arm64-musl": "4.54.0",
2308
+ "@rollup/rollup-linux-loong64-gnu": "4.54.0",
2309
+ "@rollup/rollup-linux-ppc64-gnu": "4.54.0",
2310
+ "@rollup/rollup-linux-riscv64-gnu": "4.54.0",
2311
+ "@rollup/rollup-linux-riscv64-musl": "4.54.0",
2312
+ "@rollup/rollup-linux-s390x-gnu": "4.54.0",
2313
+ "@rollup/rollup-linux-x64-gnu": "4.54.0",
2314
+ "@rollup/rollup-linux-x64-musl": "4.54.0",
2315
+ "@rollup/rollup-openharmony-arm64": "4.54.0",
2316
+ "@rollup/rollup-win32-arm64-msvc": "4.54.0",
2317
+ "@rollup/rollup-win32-ia32-msvc": "4.54.0",
2318
+ "@rollup/rollup-win32-x64-gnu": "4.54.0",
2319
+ "@rollup/rollup-win32-x64-msvc": "4.54.0",
2320
+ "fsevents": "~2.3.2"
2321
+ }
2322
+ },
2323
+ "node_modules/run-parallel": {
2324
+ "version": "1.2.0",
2325
+ "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
2326
+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
2327
+ "dev": true,
2328
+ "funding": [
2329
+ {
2330
+ "type": "github",
2331
+ "url": "https://github.com/sponsors/feross"
2332
+ },
2333
+ {
2334
+ "type": "patreon",
2335
+ "url": "https://www.patreon.com/feross"
2336
+ },
2337
+ {
2338
+ "type": "consulting",
2339
+ "url": "https://feross.org/support"
2340
+ }
2341
+ ],
2342
+ "license": "MIT",
2343
+ "dependencies": {
2344
+ "queue-microtask": "^1.2.2"
2345
+ }
2346
+ },
2347
+ "node_modules/scheduler": {
2348
+ "version": "0.23.2",
2349
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
2350
+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
2351
+ "license": "MIT",
2352
+ "dependencies": {
2353
+ "loose-envify": "^1.1.0"
2354
+ }
2355
+ },
2356
+ "node_modules/semver": {
2357
+ "version": "6.3.1",
2358
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
2359
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
2360
+ "dev": true,
2361
+ "license": "ISC",
2362
+ "bin": {
2363
+ "semver": "bin/semver.js"
2364
+ }
2365
+ },
2366
+ "node_modules/source-map-js": {
2367
+ "version": "1.2.1",
2368
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
2369
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
2370
+ "dev": true,
2371
+ "license": "BSD-3-Clause",
2372
+ "engines": {
2373
+ "node": ">=0.10.0"
2374
+ }
2375
+ },
2376
+ "node_modules/sucrase": {
2377
+ "version": "3.35.1",
2378
+ "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
2379
+ "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
2380
+ "dev": true,
2381
+ "license": "MIT",
2382
+ "dependencies": {
2383
+ "@jridgewell/gen-mapping": "^0.3.2",
2384
+ "commander": "^4.0.0",
2385
+ "lines-and-columns": "^1.1.6",
2386
+ "mz": "^2.7.0",
2387
+ "pirates": "^4.0.1",
2388
+ "tinyglobby": "^0.2.11",
2389
+ "ts-interface-checker": "^0.1.9"
2390
+ },
2391
+ "bin": {
2392
+ "sucrase": "bin/sucrase",
2393
+ "sucrase-node": "bin/sucrase-node"
2394
+ },
2395
+ "engines": {
2396
+ "node": ">=16 || 14 >=14.17"
2397
+ }
2398
+ },
2399
+ "node_modules/supports-preserve-symlinks-flag": {
2400
+ "version": "1.0.0",
2401
+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
2402
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
2403
+ "dev": true,
2404
+ "license": "MIT",
2405
+ "engines": {
2406
+ "node": ">= 0.4"
2407
+ },
2408
+ "funding": {
2409
+ "url": "https://github.com/sponsors/ljharb"
2410
+ }
2411
+ },
2412
+ "node_modules/tailwindcss": {
2413
+ "version": "3.4.19",
2414
+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",
2415
+ "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==",
2416
+ "dev": true,
2417
+ "license": "MIT",
2418
+ "dependencies": {
2419
+ "@alloc/quick-lru": "^5.2.0",
2420
+ "arg": "^5.0.2",
2421
+ "chokidar": "^3.6.0",
2422
+ "didyoumean": "^1.2.2",
2423
+ "dlv": "^1.1.3",
2424
+ "fast-glob": "^3.3.2",
2425
+ "glob-parent": "^6.0.2",
2426
+ "is-glob": "^4.0.3",
2427
+ "jiti": "^1.21.7",
2428
+ "lilconfig": "^3.1.3",
2429
+ "micromatch": "^4.0.8",
2430
+ "normalize-path": "^3.0.0",
2431
+ "object-hash": "^3.0.0",
2432
+ "picocolors": "^1.1.1",
2433
+ "postcss": "^8.4.47",
2434
+ "postcss-import": "^15.1.0",
2435
+ "postcss-js": "^4.0.1",
2436
+ "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0",
2437
+ "postcss-nested": "^6.2.0",
2438
+ "postcss-selector-parser": "^6.1.2",
2439
+ "resolve": "^1.22.8",
2440
+ "sucrase": "^3.35.0"
2441
+ },
2442
+ "bin": {
2443
+ "tailwind": "lib/cli.js",
2444
+ "tailwindcss": "lib/cli.js"
2445
+ },
2446
+ "engines": {
2447
+ "node": ">=14.0.0"
2448
+ }
2449
+ },
2450
+ "node_modules/thenify": {
2451
+ "version": "3.3.1",
2452
+ "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
2453
+ "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
2454
+ "dev": true,
2455
+ "license": "MIT",
2456
+ "dependencies": {
2457
+ "any-promise": "^1.0.0"
2458
+ }
2459
+ },
2460
+ "node_modules/thenify-all": {
2461
+ "version": "1.6.0",
2462
+ "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
2463
+ "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
2464
+ "dev": true,
2465
+ "license": "MIT",
2466
+ "dependencies": {
2467
+ "thenify": ">= 3.1.0 < 4"
2468
+ },
2469
+ "engines": {
2470
+ "node": ">=0.8"
2471
+ }
2472
+ },
2473
+ "node_modules/tinyglobby": {
2474
+ "version": "0.2.15",
2475
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
2476
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
2477
+ "dev": true,
2478
+ "license": "MIT",
2479
+ "dependencies": {
2480
+ "fdir": "^6.5.0",
2481
+ "picomatch": "^4.0.3"
2482
+ },
2483
+ "engines": {
2484
+ "node": ">=12.0.0"
2485
+ },
2486
+ "funding": {
2487
+ "url": "https://github.com/sponsors/SuperchupuDev"
2488
+ }
2489
+ },
2490
+ "node_modules/tinyglobby/node_modules/fdir": {
2491
+ "version": "6.5.0",
2492
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
2493
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
2494
+ "dev": true,
2495
+ "license": "MIT",
2496
+ "engines": {
2497
+ "node": ">=12.0.0"
2498
+ },
2499
+ "peerDependencies": {
2500
+ "picomatch": "^3 || ^4"
2501
+ },
2502
+ "peerDependenciesMeta": {
2503
+ "picomatch": {
2504
+ "optional": true
2505
+ }
2506
+ }
2507
+ },
2508
+ "node_modules/tinyglobby/node_modules/picomatch": {
2509
+ "version": "4.0.3",
2510
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
2511
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
2512
+ "dev": true,
2513
+ "license": "MIT",
2514
+ "engines": {
2515
+ "node": ">=12"
2516
+ },
2517
+ "funding": {
2518
+ "url": "https://github.com/sponsors/jonschlinkert"
2519
+ }
2520
+ },
2521
+ "node_modules/to-regex-range": {
2522
+ "version": "5.0.1",
2523
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
2524
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
2525
+ "dev": true,
2526
+ "license": "MIT",
2527
+ "dependencies": {
2528
+ "is-number": "^7.0.0"
2529
+ },
2530
+ "engines": {
2531
+ "node": ">=8.0"
2532
+ }
2533
+ },
2534
+ "node_modules/ts-interface-checker": {
2535
+ "version": "0.1.13",
2536
+ "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
2537
+ "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
2538
+ "dev": true,
2539
+ "license": "Apache-2.0"
2540
+ },
2541
+ "node_modules/tslib": {
2542
+ "version": "2.8.1",
2543
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
2544
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
2545
+ "license": "0BSD"
2546
+ },
2547
+ "node_modules/typescript": {
2548
+ "version": "5.9.3",
2549
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
2550
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
2551
+ "dev": true,
2552
+ "license": "Apache-2.0",
2553
+ "bin": {
2554
+ "tsc": "bin/tsc",
2555
+ "tsserver": "bin/tsserver"
2556
+ },
2557
+ "engines": {
2558
+ "node": ">=14.17"
2559
+ }
2560
+ },
2561
+ "node_modules/update-browserslist-db": {
2562
+ "version": "1.2.3",
2563
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
2564
+ "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",
2565
+ "dev": true,
2566
+ "funding": [
2567
+ {
2568
+ "type": "opencollective",
2569
+ "url": "https://opencollective.com/browserslist"
2570
+ },
2571
+ {
2572
+ "type": "tidelift",
2573
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
2574
+ },
2575
+ {
2576
+ "type": "github",
2577
+ "url": "https://github.com/sponsors/ai"
2578
+ }
2579
+ ],
2580
+ "license": "MIT",
2581
+ "dependencies": {
2582
+ "escalade": "^3.2.0",
2583
+ "picocolors": "^1.1.1"
2584
+ },
2585
+ "bin": {
2586
+ "update-browserslist-db": "cli.js"
2587
+ },
2588
+ "peerDependencies": {
2589
+ "browserslist": ">= 4.21.0"
2590
+ }
2591
+ },
2592
+ "node_modules/util-deprecate": {
2593
+ "version": "1.0.2",
2594
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
2595
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
2596
+ "dev": true,
2597
+ "license": "MIT"
2598
+ },
2599
+ "node_modules/vite": {
2600
+ "version": "5.4.21",
2601
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
2602
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
2603
+ "dev": true,
2604
+ "license": "MIT",
2605
+ "dependencies": {
2606
+ "esbuild": "^0.21.3",
2607
+ "postcss": "^8.4.43",
2608
+ "rollup": "^4.20.0"
2609
+ },
2610
+ "bin": {
2611
+ "vite": "bin/vite.js"
2612
+ },
2613
+ "engines": {
2614
+ "node": "^18.0.0 || >=20.0.0"
2615
+ },
2616
+ "funding": {
2617
+ "url": "https://github.com/vitejs/vite?sponsor=1"
2618
+ },
2619
+ "optionalDependencies": {
2620
+ "fsevents": "~2.3.3"
2621
+ },
2622
+ "peerDependencies": {
2623
+ "@types/node": "^18.0.0 || >=20.0.0",
2624
+ "less": "*",
2625
+ "lightningcss": "^1.21.0",
2626
+ "sass": "*",
2627
+ "sass-embedded": "*",
2628
+ "stylus": "*",
2629
+ "sugarss": "*",
2630
+ "terser": "^5.4.0"
2631
+ },
2632
+ "peerDependenciesMeta": {
2633
+ "@types/node": {
2634
+ "optional": true
2635
+ },
2636
+ "less": {
2637
+ "optional": true
2638
+ },
2639
+ "lightningcss": {
2640
+ "optional": true
2641
+ },
2642
+ "sass": {
2643
+ "optional": true
2644
+ },
2645
+ "sass-embedded": {
2646
+ "optional": true
2647
+ },
2648
+ "stylus": {
2649
+ "optional": true
2650
+ },
2651
+ "sugarss": {
2652
+ "optional": true
2653
+ },
2654
+ "terser": {
2655
+ "optional": true
2656
+ }
2657
+ }
2658
+ },
2659
+ "node_modules/yallist": {
2660
+ "version": "3.1.1",
2661
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
2662
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
2663
+ "dev": true,
2664
+ "license": "ISC"
2665
+ }
2666
+ }
2667
+ }
frontend/package.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ap-agent-frontend",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "framer-motion": "^11.0.0",
13
+ "react": "^18.3.1",
14
+ "react-dom": "^18.3.1"
15
+ },
16
+ "devDependencies": {
17
+ "@types/react": "^18.3.12",
18
+ "@types/react-dom": "^18.3.1",
19
+ "@vitejs/plugin-react": "^4.3.4",
20
+ "autoprefixer": "^10.4.20",
21
+ "postcss": "^8.4.49",
22
+ "tailwindcss": "^3.4.16",
23
+ "typescript": "^5.6.3",
24
+ "vite": "^5.4.11"
25
+ }
26
+ }
27
+
28
+
frontend/postcss.config.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {}
5
+ }
6
+ };
7
+
8
+
frontend/src/App.tsx ADDED
@@ -0,0 +1,1687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import { AnimatePresence, motion } from "framer-motion";
3
+ import { analyze, AnalyzeResponse, clearDb, getHistory, getHistoryDetail, health, HistoryItem, InvoiceDetail } from "./api";
4
+ import { Card } from "./components/Card";
5
+ import { FileDrop } from "./components/FileDrop";
6
+ import { MultiFileDrop } from "./components/MultiFileDrop";
7
+ import { Badge } from "./components/Badge";
8
+ import { BadgeButton } from "./components/BadgeButton";
9
+ import { StepBar, StepState } from "./components/StepBar";
10
+ import { InvoiceCarouselPreview, PoPreview } from "./components/FilePreview";
11
+ import { LogoMark } from "./components/LogoMark";
12
+ import { ShareButton } from "./components/ShareButton";
13
+ import { BookLoader } from "./components/BookLoader";
14
+
15
+ function IconGrid() {
16
+ return (
17
+ <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
18
+ <path
19
+ d="M3 3h6v6H3V3Zm8 0h6v6h-6V3ZM3 11h6v6H3v-6Zm8 0h6v6h-6v-6Z"
20
+ fill="currentColor"
21
+ opacity="0.9"
22
+ />
23
+ </svg>
24
+ );
25
+ }
26
+
27
+ function IconClock() {
28
+ return (
29
+ <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
30
+ <path
31
+ d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm0-13a1 1 0 0 1 1 1v3.6l2.3 1.3a1 1 0 1 1-1 1.7l-2.8-1.6A1 1 0 0 1 9 10V6a1 1 0 0 1 1-1Z"
32
+ fill="currentColor"
33
+ opacity="0.9"
34
+ />
35
+ </svg>
36
+ );
37
+ }
38
+
39
+ function IconChevron({ dir }: { dir: "left" | "right" }) {
40
+ return (
41
+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
42
+ {dir === "left" ? (
43
+ <path d="M12.5 4.5 7 10l5.5 5.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
44
+ ) : (
45
+ <path d="M7.5 4.5 13 10l-5.5 5.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
46
+ )}
47
+ </svg>
48
+ );
49
+ }
50
+
51
+ function IconSearch() {
52
+ return (
53
+ <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
54
+ <path
55
+ d="M9 16a7 7 0 1 1 0-14 7 7 0 0 1 0 14Zm6.2 1.6-3.1-3.1"
56
+ stroke="currentColor"
57
+ strokeWidth="2"
58
+ strokeLinecap="round"
59
+ />
60
+ </svg>
61
+ );
62
+ }
63
+
64
+ function IconFilter() {
65
+ return (
66
+ <svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden="true">
67
+ <path
68
+ d="M3 4h14l-5.5 6v5l-3 1v-6L3 4Z"
69
+ stroke="currentColor"
70
+ strokeWidth="2"
71
+ strokeLinejoin="round"
72
+ />
73
+ </svg>
74
+ );
75
+ }
76
+
77
+ function IconFile() {
78
+ return (
79
+ <svg width="22" height="22" viewBox="0 0 20 20" fill="none" aria-hidden="true">
80
+ <path
81
+ d="M6 2h5l3 3v13H6V2Z"
82
+ stroke="currentColor"
83
+ strokeWidth="1.6"
84
+ strokeLinejoin="round"
85
+ />
86
+ <path d="M11 2v3h3" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
87
+ <path d="M7.5 10h5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
88
+ <path d="M7.5 13h5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
89
+ </svg>
90
+ );
91
+ }
92
+
93
+ function toneForStatus(status: string): "ok" | "warn" | "bad" | "neutral" {
94
+ if (status === "Matched") return "ok";
95
+ if (status === "Review") return "warn";
96
+ if (status === "Unmatched") return "bad";
97
+ return "neutral";
98
+ }
99
+
100
+ function toneForApprovalDecision(label?: string | null): "ok" | "warn" | "bad" | "neutral" {
101
+ const v = String(label || "");
102
+ if (v === "Approved") return "ok";
103
+ if (v === "Partially Approved") return "warn";
104
+ if (v === "Rejected") return "bad";
105
+ return "neutral";
106
+ }
107
+
108
+ function fmtDate(s?: string) {
109
+ if (!s) return "—";
110
+ // ISO string from backend (UTC). Keep it readable without heavy libs.
111
+ return s.replace("T", " ").replace("Z", "");
112
+ }
113
+
114
+ function fmtPct01(v?: number | null) {
115
+ if (v === null || v === undefined) return "—";
116
+ const n = Number(v);
117
+ if (!Number.isFinite(n)) return "—";
118
+ const x = n > 1 && n <= 100 ? n / 100 : n; // tolerate percent-style values
119
+ return `${Math.round(Math.max(0, Math.min(1, x)) * 100)}%`;
120
+ }
121
+
122
+ function fmtMs(v?: number | null) {
123
+ if (v === null || v === undefined) return "—";
124
+ const n = Number(v);
125
+ if (!Number.isFinite(n)) return "—";
126
+ if (n < 1000) return `${Math.round(n)} ms`;
127
+ return `${(n / 1000).toFixed(2)} s`;
128
+ }
129
+
130
+ function poFromFilename(fileName?: string | null): string | null {
131
+ const fn = (fileName || "").trim();
132
+ if (!fn) return null;
133
+ const m = fn.match(/PO[-_ ]?\d{3,}/i);
134
+ if (!m) return null;
135
+ const raw = m[0].replace("_", "-").replace(" ", "-").toUpperCase();
136
+ return raw.replace(/PO-(\d+)/i, "PO-$1");
137
+ }
138
+
139
+ function poDisplay(po?: string | null, fileName?: string | null): string {
140
+ return poFromFilename(fileName) || (po || "").trim() || "—";
141
+ }
142
+
143
+ function fmtSecCompact(v?: number | null) {
144
+ if (v === null || v === undefined) return "—";
145
+ const n = Number(v);
146
+ if (!Number.isFinite(n)) return "—";
147
+ const sec = n / 1000;
148
+ if (sec < 1) return `${Math.round(n)}ms`;
149
+ return `${sec.toFixed(sec < 10 ? 2 : 1)}s`;
150
+ }
151
+
152
+ function MetricPill({ label, value }: { label: string; value: string }) {
153
+ return (
154
+ <span className="inline-flex items-center gap-1 rounded-full border border-stroke bg-white px-2.5 py-1 text-[11px] font-semibold text-ink/80">
155
+ <span className="text-muted">{label}:</span>
156
+ <span className="text-ink/80">{value}</span>
157
+ </span>
158
+ );
159
+ }
160
+
161
+ function fmtNum(v: any) {
162
+ const n = Number(v);
163
+ if (!Number.isFinite(n)) return "—";
164
+ return n % 1 === 0 ? String(n) : n.toFixed(2);
165
+ }
166
+
167
+ function poKey(po?: string | null) {
168
+ const v = (po || "").trim();
169
+ return v || "(no PO)";
170
+ }
171
+
172
+ async function copyToClipboard(text: string): Promise<boolean> {
173
+ try {
174
+ if (navigator?.clipboard?.writeText) {
175
+ await navigator.clipboard.writeText(text);
176
+ return true;
177
+ }
178
+ } catch {
179
+ // ignore and fall back
180
+ }
181
+ try {
182
+ const ta = document.createElement("textarea");
183
+ ta.value = text;
184
+ ta.style.position = "fixed";
185
+ ta.style.left = "-9999px";
186
+ ta.style.top = "-9999px";
187
+ document.body.appendChild(ta);
188
+ ta.focus();
189
+ ta.select();
190
+ const ok = document.execCommand("copy");
191
+ document.body.removeChild(ta);
192
+ return ok;
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
197
+
198
+ function downloadTextFile(filename: string, content: string, mime: string) {
199
+ const blob = new Blob([content], { type: mime });
200
+ const url = URL.createObjectURL(blob);
201
+ const a = document.createElement("a");
202
+ a.href = url;
203
+ a.download = filename;
204
+ document.body.appendChild(a);
205
+ a.click();
206
+ document.body.removeChild(a);
207
+ window.setTimeout(() => URL.revokeObjectURL(url), 2000);
208
+ }
209
+
210
+ function escapeXml(s: string) {
211
+ return (s ?? "")
212
+ .replace(/&/g, "&amp;")
213
+ .replace(/</g, "&lt;")
214
+ .replace(/>/g, "&gt;")
215
+ .replace(/\"/g, "&quot;")
216
+ .replace(/'/g, "&apos;");
217
+ }
218
+
219
+ function jsonToXml(value: any, tagName = "root"): string {
220
+ const tag = escapeXml(tagName || "root");
221
+ if (value === null || value === undefined) return `<${tag}/>`;
222
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
223
+ return `<${tag}>${escapeXml(String(value))}</${tag}>`;
224
+ }
225
+ if (Array.isArray(value)) {
226
+ return `<${tag}>${value.map((v) => jsonToXml(v, "item")).join("")}</${tag}>`;
227
+ }
228
+ if (typeof value === "object") {
229
+ const inner = Object.entries(value)
230
+ .map(([k, v]) => jsonToXml(v, k))
231
+ .join("");
232
+ return `<${tag}>${inner}</${tag}>`;
233
+ }
234
+ return `<${tag}>${escapeXml(String(value))}</${tag}>`;
235
+ }
236
+
237
+ export default function App() {
238
+ const [page, setPage] = useState<"dashboard" | "history">("dashboard");
239
+ const [stage, setStage] = useState<"upload" | "preview" | "analyzing" | "result">("upload");
240
+ const [invoices, setInvoices] = useState<File[]>([]);
241
+ const [activeInvoiceIdx, setActiveInvoiceIdx] = useState(0);
242
+ const [po, setPo] = useState<File | null>(null);
243
+ const [loading, setLoading] = useState(false);
244
+ const [error, setError] = useState<string | null>(null);
245
+ const [analysisRuns, setAnalysisRuns] = useState<{ file: File; result?: AnalyzeResponse; error?: string }[]>([]);
246
+ const [activeResultIdx, setActiveResultIdx] = useState(0);
247
+ const [analyzingIdx, setAnalyzingIdx] = useState<number | null>(null);
248
+ const [toast, setToast] = useState<string | null>(null);
249
+ const [ocrOpen, setOcrOpen] = useState(false);
250
+ const [historyJsonOpen, setHistoryJsonOpen] = useState(false);
251
+
252
+ // History state
253
+ const [historyLoading, setHistoryLoading] = useState(false);
254
+ const [historyError, setHistoryError] = useState<string | null>(null);
255
+ const [historyItems, setHistoryItems] = useState<HistoryItem[]>([]);
256
+ const [historySearch, setHistorySearch] = useState<string>("");
257
+ const [historyStatusFilter, setHistoryStatusFilter] = useState<string>("");
258
+ const [selectedHistoryId, setSelectedHistoryId] = useState<string | null>(null);
259
+ const [historyDetailLoading, setHistoryDetailLoading] = useState(false);
260
+ const [historyDetail, setHistoryDetail] = useState<InvoiceDetail | null>(null);
261
+ const [historyDetailsOpen, setHistoryDetailsOpen] = useState(false);
262
+ const [sidebarCollapsed, setSidebarCollapsed] = useState<boolean>(() => {
263
+ try {
264
+ const v = localStorage.getItem("apdemo.sidebarCollapsed");
265
+ return v === null ? false : v === "true";
266
+ } catch {
267
+ return false;
268
+ }
269
+ });
270
+
271
+ const activeInvoice = invoices[activeInvoiceIdx] || null;
272
+ const activeRun = analysisRuns[activeResultIdx] || null;
273
+ const activeAnalysis = activeRun?.result || null;
274
+ const hasOcr = Boolean(activeAnalysis?.details?.ocr);
275
+ const hasHistoryExtracted = Boolean(historyDetail?.extracted_invoice);
276
+ const canNext = Boolean(invoices.length > 0 && po && !loading && stage === "upload");
277
+ const canStartAnalyze = Boolean(invoices.length > 0 && po && !loading && stage === "preview");
278
+ const showResultsPanel = stage !== "upload";
279
+ const hasUploads = Boolean(invoices.length > 0 && po);
280
+
281
+ // Keep active index valid as files are added/removed.
282
+ useEffect(() => {
283
+ setActiveInvoiceIdx((cur) => Math.max(0, Math.min(cur, Math.max(0, invoices.length - 1))));
284
+ }, [invoices.length]);
285
+
286
+ useEffect(() => {
287
+ try {
288
+ localStorage.setItem("apdemo.sidebarCollapsed", String(sidebarCollapsed));
289
+ } catch {
290
+ // ignore
291
+ }
292
+ }, [sidebarCollapsed]);
293
+
294
+ useEffect(() => {
295
+ if (!toast) return;
296
+ const t = window.setTimeout(() => setToast(null), 1800);
297
+ return () => window.clearTimeout(t);
298
+ }, [toast]);
299
+
300
+ // Load history when switching to the History tab.
301
+ useEffect(() => {
302
+ if (page !== "history") return;
303
+ let cancelled = false;
304
+
305
+ (async () => {
306
+ setHistoryError(null);
307
+ setHistoryLoading(true);
308
+ try {
309
+ const r = await getHistory({ limit: 200 });
310
+ if (cancelled) return;
311
+ setHistoryItems(r.items || []);
312
+ } catch (e: any) {
313
+ if (cancelled) return;
314
+ setHistoryItems([]);
315
+ setHistoryError(e?.message || String(e));
316
+ } finally {
317
+ if (!cancelled) setHistoryLoading(false);
318
+ }
319
+ })();
320
+
321
+ return () => {
322
+ cancelled = true;
323
+ };
324
+ }, [page]);
325
+
326
+ // Load selected history detail
327
+ useEffect(() => {
328
+ if (page !== "history") return;
329
+ if (!selectedHistoryId) {
330
+ setHistoryDetail(null);
331
+ return;
332
+ }
333
+ let cancelled = false;
334
+ (async () => {
335
+ setHistoryDetailLoading(true);
336
+ try {
337
+ const d = await getHistoryDetail(selectedHistoryId);
338
+ if (cancelled) return;
339
+ setHistoryDetail(d);
340
+ } catch (e: any) {
341
+ if (cancelled) return;
342
+ setHistoryDetail(null);
343
+ setHistoryError(e?.message || String(e));
344
+ } finally {
345
+ if (!cancelled) setHistoryDetailLoading(false);
346
+ }
347
+ })();
348
+ return () => {
349
+ cancelled = true;
350
+ };
351
+ }, [page, selectedHistoryId]);
352
+
353
+ const stepState = useMemo(() => {
354
+ const upload: StepState = stage === "upload" ? "active" : "done";
355
+ // Keep the 3-step bar, but make it unambiguous:
356
+ // - Upload: active only on upload screen
357
+ // - Analyze: active only while analyzing (not while previewing)
358
+ // - Complete: done only when results are shown
359
+ const analyze: StepState = stage === "analyzing" ? "active" : stage === "result" ? "done" : "todo";
360
+ const complete: StepState = stage === "result" ? "done" : "todo";
361
+ return { upload, analyze, complete };
362
+ }, [stage]);
363
+
364
+ const loadingSteps = [
365
+ "Understanding PO CSV…",
366
+ "Reading invoice…",
367
+ "Matching headers and items…",
368
+ "Generating explanation…"
369
+ ];
370
+
371
+ const kpis = useMemo(() => {
372
+ if (!activeAnalysis) return null;
373
+ const e = activeAnalysis.evaluation;
374
+ const decisionLabel =
375
+ (activeAnalysis.details as any)?.approval_decision ||
376
+ (e as any)?.approval_decision ||
377
+ "";
378
+ const decisionTone = toneForApprovalDecision(decisionLabel) || toneForStatus(e.match_status);
379
+ return [
380
+ { label: "Decision", value: decisionLabel || e.match_status, badge: decisionLabel ? decisionTone : toneForStatus(e.match_status) },
381
+ { label: "Duplicate", value: e.duplicate ? "Yes" : "No", badge: e.duplicate ? "bad" : "ok" },
382
+ { label: "Supplier", value: e.supplier_status || "—", badge: e.supplier_status === "Validated" ? "ok" : "warn" },
383
+ { label: "Backorders", value: String(e.open_backorders?.length ?? 0), badge: (e.open_backorders?.length ?? 0) > 0 ? "warn" : "ok" }
384
+ ] as const;
385
+ }, [activeAnalysis]);
386
+
387
+ const filteredHistoryItems = useMemo(() => {
388
+ const q = historySearch.trim().toLowerCase();
389
+ const s = (historyStatusFilter || "").trim();
390
+ return (historyItems || []).filter((it) => {
391
+ if (s) {
392
+ const label = String((it as any).approval_decision || "");
393
+ if ((label || "").trim() !== s) return false;
394
+ }
395
+ if (!q) return true;
396
+ const hay = [
397
+ it.file_name,
398
+ it.invoice_number,
399
+ it.supplier,
400
+ it.po_number,
401
+ it.id,
402
+ ]
403
+ .filter(Boolean)
404
+ .join(" ")
405
+ .toLowerCase();
406
+ return hay.includes(q);
407
+ });
408
+ }, [historyItems, historySearch, historyStatusFilter]);
409
+
410
+ const historySummary = useMemo(() => {
411
+ const items = filteredHistoryItems || [];
412
+ const total = items.length;
413
+ const successes = items.filter((it) => String((it as any).approval_decision || "") === "Approved").length;
414
+ const successRate = total > 0 ? successes / total : 0;
415
+ const ms = items.map((it) => Number(it.processing_ms)).filter((n) => Number.isFinite(n)) as number[];
416
+ const avgMs = ms.length ? ms.reduce((a, b) => a + b, 0) / ms.length : null;
417
+ const fieldsTotal = items
418
+ .map((it) => Number(it.extractions_count))
419
+ .filter((n) => Number.isFinite(n))
420
+ .reduce((a, b) => a + b, 0);
421
+ return { total, successes, successRate, avgMs, fieldsTotal };
422
+ }, [filteredHistoryItems]);
423
+
424
+ function onNext() {
425
+ if (!invoices.length || !po) return;
426
+ setError(null);
427
+ setAnalysisRuns([]);
428
+ setActiveResultIdx(0);
429
+ setStage("preview");
430
+ }
431
+
432
+ async function onStartAnalyze() {
433
+ if (!invoices.length || !po) return;
434
+ setError(null);
435
+ setAnalysisRuns([]);
436
+ setActiveResultIdx(0);
437
+ setStage("analyzing");
438
+ setLoading(true);
439
+ setAnalyzingIdx(0);
440
+ try {
441
+ // quick preflight to surface config issues
442
+ const h = await health();
443
+ if (!h.ok) throw new Error(h.error || "Backend not ready");
444
+
445
+ const runs: { file: File; result?: AnalyzeResponse; error?: string }[] = [];
446
+ for (let i = 0; i < invoices.length; i++) {
447
+ const inv = invoices[i];
448
+ setAnalyzingIdx(i);
449
+ try {
450
+ const r = await analyze(inv, po);
451
+ runs.push({ file: inv, result: r });
452
+ } catch (e: any) {
453
+ runs.push({ file: inv, error: e?.message || String(e) });
454
+ }
455
+ // keep UI responsive while analyzing multiple invoices
456
+ setAnalysisRuns([...runs]);
457
+ }
458
+ setActiveResultIdx(0);
459
+ setStage("result");
460
+ } catch (e: any) {
461
+ setAnalysisRuns([]);
462
+ setError(e?.message || String(e));
463
+ setStage("preview");
464
+ } finally {
465
+ setLoading(false);
466
+ setAnalyzingIdx(null);
467
+ }
468
+ }
469
+
470
+ async function onClear() {
471
+ setError(null);
472
+ setLoading(true);
473
+ try {
474
+ await clearDb();
475
+ setAnalysisRuns([]);
476
+ setActiveResultIdx(0);
477
+ setStage("upload");
478
+ } catch (e: any) {
479
+ setError(e?.message || String(e));
480
+ } finally {
481
+ setLoading(false);
482
+ }
483
+ }
484
+
485
+ return (
486
+ <div className="min-h-screen bg-clean">
487
+ <div className="aurora">
488
+ <div className="aurora-blob b1" />
489
+ <div className="aurora-blob b2" />
490
+ <div className="aurora-blob b3" />
491
+ </div>
492
+ <div className="flex min-h-screen">
493
+ {/* Sidebar (anchored left, full height) */}
494
+ <motion.aside
495
+ className="w-full border-b border-stroke bg-white lg:sticky lg:top-0 lg:h-screen lg:border-b-0 lg:border-r"
496
+ animate={{ width: sidebarCollapsed ? 80 : 288 }}
497
+ transition={{ type: "spring", stiffness: 260, damping: 26 }}
498
+ >
499
+ <div className="flex items-center justify-between gap-2 px-4 py-4">
500
+ <div className="flex items-center gap-3">
501
+ <LogoMark size={26} />
502
+ {!sidebarCollapsed && (
503
+ <motion.div initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }} className="min-w-0">
504
+ <div className="truncate text-sm font-semibold text-ink">AP Demo</div>
505
+ <div className="truncate text-[11px] text-muted">Agent-powered</div>
506
+ </motion.div>
507
+ )}
508
+ </div>
509
+ <button
510
+ type="button"
511
+ onClick={() => setSidebarCollapsed((v) => !v)}
512
+ className="ml-auto inline-flex items-center justify-center rounded-lg border border-stroke bg-white p-2 text-ink hover:bg-bg"
513
+ aria-label={sidebarCollapsed ? "Expand sidebar" : "Collapse sidebar"}
514
+ title={sidebarCollapsed ? "Expand" : "Collapse"}
515
+ >
516
+ <IconChevron dir={sidebarCollapsed ? "right" : "left"} />
517
+ </button>
518
+ </div>
519
+
520
+ <div className="px-3 pb-4">
521
+ <motion.button
522
+ whileHover={{ x: 2 }}
523
+ whileTap={{ scale: 0.98 }}
524
+ className={`flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left text-sm font-semibold ${
525
+ page === "dashboard" ? "bg-bg text-ink" : "text-muted hover:bg-bg"
526
+ }`}
527
+ onClick={() => setPage("dashboard")}
528
+ title="Dashboard"
529
+ >
530
+ <span className="text-ink/80">
531
+ <IconGrid />
532
+ </span>
533
+ {!sidebarCollapsed && <span>Dashboard</span>}
534
+ </motion.button>
535
+ <motion.button
536
+ whileHover={{ x: 2 }}
537
+ whileTap={{ scale: 0.98 }}
538
+ className={`mt-1 flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left text-sm font-semibold ${
539
+ page === "history" ? "bg-bg text-ink" : "text-muted hover:bg-bg"
540
+ }`}
541
+ onClick={() => setPage("history")}
542
+ title="History"
543
+ >
544
+ <span className="text-ink/80">
545
+ <IconClock />
546
+ </span>
547
+ {!sidebarCollapsed && <span>History</span>}
548
+ </motion.button>
549
+ </div>
550
+ </motion.aside>
551
+
552
+ {/* Main */}
553
+ <main className="min-w-0 flex-1">
554
+ <div className="mx-auto w-full max-w-[1280px] px-6 py-6">
555
+ <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
556
+ {page === "dashboard" ? (
557
+ <>
558
+ <div className="flex items-start gap-3">
559
+ <motion.div initial={{ opacity: 0, scale: 0.98 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.25 }}>
560
+ <LogoMark size={34} />
561
+ </motion.div>
562
+ <div>
563
+ <motion.div
564
+ initial={{ opacity: 0, y: 8 }}
565
+ animate={{ opacity: 1, y: 0 }}
566
+ transition={{ duration: 0.25, ease: "easeOut" }}
567
+ className="text-xl font-bold text-ink"
568
+ >
569
+ Accounts Payable Agent
570
+ </motion.div>
571
+ <div className="mt-1 text-sm text-muted">
572
+ Upload an invoice and PO data. The agent returns a clear decision: <b>Approved</b> (Matched), <b>Review</b>, or <b>Unmatched</b>.
573
+ </div>
574
+ <div className="mt-2 text-xs text-muted">AP Demo · Agent-powered</div>
575
+ </div>
576
+ </div>
577
+ <div className="flex items-center gap-2">
578
+ <ShareButton
579
+ title="Accounts Payable Agent"
580
+ text="Open this AP Agent demo"
581
+ url={window.location.href}
582
+ onToast={(m) => setToast(m)}
583
+ />
584
+ </div>
585
+ </>
586
+ ) : (
587
+ <div>
588
+ <div className="text-xl font-bold text-ink">Extraction History</div>
589
+ <div className="mt-1 text-sm text-muted">View detailed reports and performance metrics for all extractions</div>
590
+ </div>
591
+ )}
592
+ </div>
593
+
594
+ <AnimatePresence>
595
+ {toast && (
596
+ <motion.div
597
+ initial={{ opacity: 0, y: 10 }}
598
+ animate={{ opacity: 1, y: 0 }}
599
+ exit={{ opacity: 0, y: 10 }}
600
+ className="fixed bottom-6 right-6 z-50 rounded-xl border border-stroke bg-white px-4 py-3 text-sm font-semibold text-ink shadow-glow"
601
+ >
602
+ {toast}
603
+ </motion.div>
604
+ )}
605
+ </AnimatePresence>
606
+
607
+ {/* OCR JSON modal */}
608
+ <AnimatePresence>
609
+ {ocrOpen && (
610
+ <motion.div
611
+ key="ocr-modal"
612
+ initial={{ opacity: 0 }}
613
+ animate={{ opacity: 1 }}
614
+ exit={{ opacity: 0 }}
615
+ className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4"
616
+ onMouseDown={(e) => {
617
+ if (e.target === e.currentTarget) setOcrOpen(false);
618
+ }}
619
+ >
620
+ <motion.div
621
+ initial={{ opacity: 0, y: 10, scale: 0.98 }}
622
+ animate={{ opacity: 1, y: 0, scale: 1 }}
623
+ exit={{ opacity: 0, y: 10, scale: 0.98 }}
624
+ transition={{ duration: 0.18, ease: "easeOut" }}
625
+ className="w-full max-w-3xl rounded-2xl border border-stroke bg-white shadow-glow"
626
+ >
627
+ <div className="flex items-center justify-between gap-3 border-b border-stroke px-5 py-4">
628
+ <div>
629
+ <div className="text-sm font-semibold text-ink">Extracted JSON</div>
630
+ <div className="mt-0.5 text-xs text-muted">
631
+ {activeRun?.file?.name || "Invoice"} · provider: {String(activeAnalysis?.details?.ocr?.provider || "unknown")}
632
+ </div>
633
+ </div>
634
+ <div className="flex items-center gap-2">
635
+ <button
636
+ type="button"
637
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
638
+ onClick={async () => {
639
+ const extracted = activeAnalysis?.details?.ocr?.extracted_invoice || {};
640
+ const payload = JSON.stringify(extracted, null, 2);
641
+ const ok = await copyToClipboard(payload);
642
+ setToast(ok ? "Copied extracted JSON" : "Copy failed (try Download)");
643
+ }}
644
+ disabled={!hasOcr}
645
+ >
646
+ Copy JSON
647
+ </button>
648
+ <button
649
+ type="button"
650
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
651
+ onClick={() => {
652
+ const base = (activeRun?.file?.name || "invoice").replace(/\.[^.]+$/, "");
653
+ const extracted = activeAnalysis?.details?.ocr?.extracted_invoice || {};
654
+ downloadTextFile(`${base}.json`, JSON.stringify(extracted, null, 2), "application/json;charset=utf-8");
655
+ setToast("Downloaded .json");
656
+ }}
657
+ disabled={!hasOcr}
658
+ >
659
+ JSON
660
+ </button>
661
+ <button
662
+ type="button"
663
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
664
+ onClick={() => {
665
+ const base = (activeRun?.file?.name || "invoice").replace(/\.[^.]+$/, "");
666
+ const extracted = activeAnalysis?.details?.ocr?.extracted_invoice || {};
667
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>\n${jsonToXml(extracted, "invoice")}\n`;
668
+ downloadTextFile(`${base}.xml`, xml, "application/xml;charset=utf-8");
669
+ setToast("Downloaded .xml");
670
+ }}
671
+ disabled={!hasOcr}
672
+ >
673
+ XML
674
+ </button>
675
+ <button
676
+ type="button"
677
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
678
+ onClick={() => {
679
+ const base = (activeRun?.file?.name || "invoice").replace(/\.[^.]+$/, "");
680
+ const ocrText = String(activeAnalysis?.details?.ocr?.text || "");
681
+ const extracted = activeAnalysis?.details?.ocr?.extracted_invoice || {};
682
+ const txt = `${ocrText}\n\n---\nEXTRACTED_JSON\n---\n${JSON.stringify(extracted, null, 2)}\n`;
683
+ downloadTextFile(`${base}.txt`, txt, "text/plain;charset=utf-8");
684
+ setToast("Downloaded .txt");
685
+ }}
686
+ disabled={!hasOcr}
687
+ >
688
+ TXT
689
+ </button>
690
+ <button
691
+ type="button"
692
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg"
693
+ onClick={() => setOcrOpen(false)}
694
+ >
695
+ Close
696
+ </button>
697
+ </div>
698
+ </div>
699
+ <div className="px-5 py-4">
700
+ {!hasOcr ? (
701
+ <div className="text-sm text-muted">No OCR payload available for this result.</div>
702
+ ) : (
703
+ <div className="space-y-3">
704
+ <div className="rounded-lg border border-stroke bg-bg p-3">
705
+ <div className="text-xs font-semibold text-ink/80">Extracted invoice JSON</div>
706
+ <pre className="mt-2 max-h-[38vh] overflow-auto text-[11px] text-ink/80">
707
+ {JSON.stringify(activeAnalysis?.details?.ocr?.extracted_invoice || {}, null, 2)}
708
+ </pre>
709
+ </div>
710
+ <details>
711
+ <summary className="cursor-pointer text-xs font-semibold text-ink/80">Show full OCR payload</summary>
712
+ <pre className="mt-2 max-h-[38vh] overflow-auto rounded-lg border border-stroke bg-bg p-3 text-[11px] text-ink/80">
713
+ {JSON.stringify(activeAnalysis?.details?.ocr || {}, null, 2)}
714
+ </pre>
715
+ </details>
716
+ </div>
717
+ )}
718
+ </div>
719
+ </motion.div>
720
+ </motion.div>
721
+ )}
722
+ </AnimatePresence>
723
+
724
+ {/* History extracted JSON modal */}
725
+ <AnimatePresence>
726
+ {historyJsonOpen && (
727
+ <motion.div
728
+ key="history-json-modal"
729
+ initial={{ opacity: 0 }}
730
+ animate={{ opacity: 1 }}
731
+ exit={{ opacity: 0 }}
732
+ className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4"
733
+ onMouseDown={(e) => {
734
+ if (e.target === e.currentTarget) setHistoryJsonOpen(false);
735
+ }}
736
+ >
737
+ <motion.div
738
+ initial={{ opacity: 0, y: 10, scale: 0.98 }}
739
+ animate={{ opacity: 1, y: 0, scale: 1 }}
740
+ exit={{ opacity: 0, y: 10, scale: 0.98 }}
741
+ transition={{ duration: 0.18, ease: "easeOut" }}
742
+ className="w-full max-w-3xl rounded-2xl border border-stroke bg-white shadow-glow"
743
+ >
744
+ <div className="flex items-center justify-between gap-3 border-b border-stroke px-5 py-4">
745
+ <div>
746
+ <div className="text-sm font-semibold text-ink">Extracted JSON (History)</div>
747
+ <div className="mt-0.5 text-xs text-muted">{selectedHistoryId ? `Invoice ID: ${selectedHistoryId}` : ""}</div>
748
+ </div>
749
+ <div className="flex items-center gap-2">
750
+ <button
751
+ type="button"
752
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
753
+ onClick={async () => {
754
+ const payload = JSON.stringify(historyDetail?.extracted_invoice || {}, null, 2);
755
+ const ok = await copyToClipboard(payload);
756
+ setToast(ok ? "Copied extracted JSON" : "Copy failed (try Download)");
757
+ }}
758
+ disabled={!hasHistoryExtracted}
759
+ >
760
+ Copy JSON
761
+ </button>
762
+ <button
763
+ type="button"
764
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
765
+ onClick={() => {
766
+ const base = (historyDetail?.invoice?.file_name || selectedHistoryId || "invoice").replace(/\.[^.]+$/, "");
767
+ downloadTextFile(`${base}.json`, JSON.stringify(historyDetail?.extracted_invoice || {}, null, 2), "application/json;charset=utf-8");
768
+ setToast("Downloaded .json");
769
+ }}
770
+ disabled={!hasHistoryExtracted}
771
+ >
772
+ JSON
773
+ </button>
774
+ <button
775
+ type="button"
776
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
777
+ onClick={() => {
778
+ const base = (historyDetail?.invoice?.file_name || selectedHistoryId || "invoice").replace(/\.[^.]+$/, "");
779
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>\n${jsonToXml(historyDetail?.extracted_invoice || {}, "invoice")}\n`;
780
+ downloadTextFile(`${base}.xml`, xml, "application/xml;charset=utf-8");
781
+ setToast("Downloaded .xml");
782
+ }}
783
+ disabled={!hasHistoryExtracted}
784
+ >
785
+ XML
786
+ </button>
787
+ <button
788
+ type="button"
789
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
790
+ onClick={() => {
791
+ const base = (historyDetail?.invoice?.file_name || selectedHistoryId || "invoice").replace(/\.[^.]+$/, "");
792
+ const txt = `${JSON.stringify(historyDetail?.extracted_invoice || {}, null, 2)}\n`;
793
+ downloadTextFile(`${base}.txt`, txt, "text/plain;charset=utf-8");
794
+ setToast("Downloaded .txt");
795
+ }}
796
+ disabled={!hasHistoryExtracted}
797
+ >
798
+ TXT
799
+ </button>
800
+ <button
801
+ type="button"
802
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg"
803
+ onClick={() => setHistoryJsonOpen(false)}
804
+ >
805
+ Close
806
+ </button>
807
+ </div>
808
+ </div>
809
+ <div className="px-5 py-4">
810
+ {!hasHistoryExtracted ? (
811
+ <div className="text-sm text-muted">No extracted JSON available for this history item.</div>
812
+ ) : (
813
+ <pre className="max-h-[70vh] overflow-auto rounded-lg border border-stroke bg-bg p-3 text-[11px] text-ink/80">
814
+ {JSON.stringify(historyDetail?.extracted_invoice || {}, null, 2)}
815
+ </pre>
816
+ )}
817
+ </div>
818
+ </motion.div>
819
+ </motion.div>
820
+ )}
821
+ </AnimatePresence>
822
+
823
+ {/* History details modal */}
824
+ <AnimatePresence>
825
+ {historyDetailsOpen && (
826
+ <motion.div
827
+ key="history-details-modal"
828
+ initial={{ opacity: 0 }}
829
+ animate={{ opacity: 1 }}
830
+ exit={{ opacity: 0 }}
831
+ className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4"
832
+ onMouseDown={(e) => {
833
+ if (e.target === e.currentTarget) setHistoryDetailsOpen(false);
834
+ }}
835
+ >
836
+ <motion.div
837
+ initial={{ opacity: 0, y: 10, scale: 0.98 }}
838
+ animate={{ opacity: 1, y: 0, scale: 1 }}
839
+ exit={{ opacity: 0, y: 10, scale: 0.98 }}
840
+ transition={{ duration: 0.18, ease: "easeOut" }}
841
+ className="w-full max-w-5xl rounded-2xl border border-stroke bg-white shadow-glow"
842
+ >
843
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b border-stroke px-5 py-4">
844
+ <div className="min-w-0">
845
+ <div className="truncate text-sm font-semibold text-ink">Details</div>
846
+ <div className="mt-0.5 truncate text-xs text-muted">
847
+ {selectedHistoryId ? `Invoice ID: ${selectedHistoryId}` : "—"}
848
+ </div>
849
+ </div>
850
+ <div className="flex flex-wrap items-center justify-end gap-2">
851
+ {historyDetailLoading ? <Badge tone="neutral" text="Loading…" /> : null}
852
+ {selectedHistoryId && historyDetail && (
853
+ <>
854
+ <MetricPill label="Confidence" value={fmtPct01(historyDetail.invoice?.match_score ?? null)} />
855
+ <MetricPill label="Time" value={fmtMs(historyDetail.invoice?.processing_ms ?? null)} />
856
+ <MetricPill label="Extractions" value={String(historyDetail.invoice?.extractions_count ?? "—")} />
857
+ <BadgeButton
858
+ tone="ok"
859
+ text="Extracted JSON"
860
+ onClick={() => setHistoryJsonOpen(true)}
861
+ disabled={!hasHistoryExtracted}
862
+ title={hasHistoryExtracted ? "View extracted JSON" : "No extracted JSON stored for this invoice"}
863
+ />
864
+ </>
865
+ )}
866
+ <button
867
+ type="button"
868
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg"
869
+ onClick={() => setHistoryDetailsOpen(false)}
870
+ >
871
+ Close
872
+ </button>
873
+ </div>
874
+ </div>
875
+
876
+ <div className="max-h-[75vh] overflow-auto px-5 py-4">
877
+ {!selectedHistoryId && <div className="text-sm text-muted">Select an item from the list.</div>}
878
+
879
+ {selectedHistoryId && historyDetail && (
880
+ <div className="space-y-4">
881
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
882
+ <div className="rounded-xl border border-stroke bg-white p-3">
883
+ <div className="text-xs text-muted">PO</div>
884
+ <div className="mt-1 text-sm font-semibold text-ink">
885
+ {poDisplay(historyDetail.invoice?.po_number ?? null, historyDetail.invoice?.file_name ?? null)}
886
+ </div>
887
+ </div>
888
+ <div className="rounded-xl border border-stroke bg-white p-3">
889
+ <div className="text-xs text-muted">Invoice #</div>
890
+ <div className="mt-1 text-sm font-semibold text-ink">{historyDetail.invoice?.invoice_number || "—"}</div>
891
+ </div>
892
+ <div className="rounded-xl border border-stroke bg-white p-3">
893
+ <div className="text-xs text-muted">Supplier</div>
894
+ <div className="mt-1 text-sm font-semibold text-ink">{historyDetail.invoice?.supplier || "—"}</div>
895
+ </div>
896
+ <div className="rounded-xl border border-stroke bg-white p-3">
897
+ <div className="text-xs text-muted">Decision</div>
898
+ <div className="mt-1">
899
+ {(() => {
900
+ const label = String((historyDetail.invoice as any)?.approval_decision || historyDetail.invoice?.match_status || "—");
901
+ const tone = toneForApprovalDecision(label) || toneForStatus(String(historyDetail.invoice?.match_status || ""));
902
+ return <Badge tone={tone} text={label} />;
903
+ })()}
904
+ </div>
905
+ </div>
906
+ </div>
907
+
908
+ <div className="rounded-xl border border-stroke bg-white p-4">
909
+ <div className="text-sm font-semibold text-ink">Invoice record</div>
910
+ <div className="mt-2 grid grid-cols-1 gap-2 text-xs text-ink/80 md:grid-cols-2">
911
+ <div>
912
+ <span className="font-semibold text-ink/70">Processed:</span> {fmtDate(historyDetail.invoice?.processed_at)}
913
+ </div>
914
+ <div>
915
+ <span className="font-semibold text-ink/70">Duplicate:</span> {historyDetail.invoice?.duplicate_flag ? "Yes" : "No"}
916
+ </div>
917
+ <div>
918
+ <span className="font-semibold text-ink/70">Backorders:</span>{" "}
919
+ {String(historyDetail.backorders?.count ?? historyDetail.invoice?.open_backorders_count ?? 0)}
920
+ </div>
921
+ <div>
922
+ <span className="font-semibold text-ink/70">Supplier status:</span> {historyDetail.invoice?.supplier_status || "—"}
923
+ </div>
924
+ {historyDetail.invoice?.override_reason ? (
925
+ <div className="md:col-span-2">
926
+ <span className="font-semibold text-ink/70">Override reason:</span> {historyDetail.invoice?.override_reason}
927
+ </div>
928
+ ) : null}
929
+ </div>
930
+ </div>
931
+
932
+ {(historyDetail.backorders?.items || []).length > 0 && (
933
+ <div className="rounded-xl border border-stroke bg-white p-4">
934
+ <div className="flex items-center justify-between gap-2">
935
+ <div className="text-sm font-semibold text-ink">Backorder remaining</div>
936
+ <div className="text-xs text-muted">{historyDetail.backorders?.count ?? historyDetail.backorders?.items?.length} item(s) still pending</div>
937
+ </div>
938
+ <div className="mt-2 overflow-auto rounded-lg border border-stroke">
939
+ <table className="min-w-full text-left text-xs text-ink/80">
940
+ <thead className="bg-white text-[11px] uppercase text-muted">
941
+ <tr>
942
+ <th className="px-3 py-2">SKU</th>
943
+ <th className="px-3 py-2">Description</th>
944
+ <th className="px-3 py-2">Ordered</th>
945
+ <th className="px-3 py-2">Received</th>
946
+ <th className="px-3 py-2">Remaining</th>
947
+ </tr>
948
+ </thead>
949
+ <tbody>
950
+ {(historyDetail.backorders?.items || []).map((b: any, idx: number) => (
951
+ <tr key={b.po_line_id || idx} className="border-t border-stroke">
952
+ <td className="px-3 py-2">{b.sku || "—"}</td>
953
+ <td className="px-3 py-2">{b.description || "—"}</td>
954
+ <td className="px-3 py-2">{fmtNum(b.qty_ordered)}</td>
955
+ <td className="px-3 py-2">{fmtNum(b.received_after ?? b.received_before)}</td>
956
+ <td className="px-3 py-2 font-semibold text-amber-800">{fmtNum(b.remaining)}</td>
957
+ </tr>
958
+ ))}
959
+ </tbody>
960
+ </table>
961
+ </div>
962
+ </div>
963
+ )}
964
+
965
+ <div className="rounded-xl border border-stroke bg-white p-4">
966
+ <div className="text-sm font-semibold text-ink">Line items</div>
967
+ <div className="mt-2 overflow-auto rounded-lg border border-stroke">
968
+ <table className="min-w-full text-left text-xs text-ink/80">
969
+ <thead className="bg-white text-[11px] uppercase text-muted">
970
+ <tr>
971
+ <th className="px-3 py-2">SKU</th>
972
+ <th className="px-3 py-2">Description</th>
973
+ <th className="px-3 py-2">Qty</th>
974
+ <th className="px-3 py-2">Unit price</th>
975
+ <th className="px-3 py-2">Line total</th>
976
+ </tr>
977
+ </thead>
978
+ <tbody>
979
+ {(historyDetail.lines || []).map((l: any) => (
980
+ <tr key={l.id || `${l.sku}-${l.description}`} className="border-t border-stroke">
981
+ <td className="px-3 py-2">{l.sku || "—"}</td>
982
+ <td className="px-3 py-2">{l.description || "—"}</td>
983
+ <td className="px-3 py-2">{l.qty ?? "—"}</td>
984
+ <td className="px-3 py-2">{l.unit_price ?? "—"}</td>
985
+ <td className="px-3 py-2">{l.line_total ?? "—"}</td>
986
+ </tr>
987
+ ))}
988
+ {(historyDetail.lines || []).length === 0 && (
989
+ <tr>
990
+ <td colSpan={5} className="px-3 py-6 text-center text-sm text-muted">
991
+ No line items stored for this invoice.
992
+ </td>
993
+ </tr>
994
+ )}
995
+ </tbody>
996
+ </table>
997
+ </div>
998
+ </div>
999
+ </div>
1000
+ )}
1001
+ </div>
1002
+ </motion.div>
1003
+ </motion.div>
1004
+ )}
1005
+ </AnimatePresence>
1006
+
1007
+ {page === "dashboard" && (
1008
+ <AnimatePresence mode="wait">
1009
+ <motion.div
1010
+ key="dashboard"
1011
+ initial={{ opacity: 0, y: 10 }}
1012
+ animate={{ opacity: 1, y: 0 }}
1013
+ exit={{ opacity: 0, y: 8 }}
1014
+ transition={{ duration: 0.25, ease: "easeOut" }}
1015
+ className="grid grid-cols-1 gap-6 lg:grid-cols-12"
1016
+ >
1017
+ <div className="lg:col-span-12">
1018
+ <StepBar
1019
+ steps={[
1020
+ { key: "upload", label: "Upload", state: stepState.upload },
1021
+ { key: "analyze", label: "Analyze", state: stepState.analyze },
1022
+ { key: "complete", label: "Complete", state: stepState.complete }
1023
+ ]}
1024
+ />
1025
+ <div className="mt-2 text-xs text-muted">
1026
+ {stage === "upload"
1027
+ ? "Step 1/4 — Upload files"
1028
+ : stage === "preview"
1029
+ ? "Step 2/4 — Preview & confirm, then start analyze"
1030
+ : stage === "analyzing"
1031
+ ? "Step 3/4 — Analyzing"
1032
+ : "Step 4/4 — Results"}
1033
+ {invoices.length > 0 && (
1034
+ <span className="ml-2">
1035
+ {" "}
1036
+ ·{" "}
1037
+ {stage === "result" && analysisRuns.length > 0 ? (
1038
+ <>
1039
+ <span className="font-semibold text-ink/80">Viewing:</span>{" "}
1040
+ <span className="text-ink/70">
1041
+ Invoice {activeResultIdx + 1}/{analysisRuns.length} — {analysisRuns[activeResultIdx]?.file?.name}
1042
+ </span>
1043
+ </>
1044
+ ) : stage === "analyzing" && analyzingIdx !== null ? (
1045
+ <>
1046
+ <span className="font-semibold text-ink/80">Analyzing:</span>{" "}
1047
+ <span className="text-ink/70">
1048
+ Invoice {analyzingIdx + 1}/{invoices.length} — {invoices[analyzingIdx]?.name}
1049
+ </span>
1050
+ </>
1051
+ ) : invoices.length === 1 ? (
1052
+ <>
1053
+ <span className="font-semibold text-ink/80">Selected invoice:</span>{" "}
1054
+ <span className="text-ink/70">{invoices[0].name}</span>
1055
+ </>
1056
+ ) : (
1057
+ <>
1058
+ <span className="font-semibold text-ink/80">Selected invoices:</span>{" "}
1059
+ <span className="text-ink/70">
1060
+ {invoices
1061
+ .slice(0, 2)
1062
+ .map((f) => f.name)
1063
+ .join(", ")}
1064
+ {invoices.length > 2 ? <span className="text-muted"> (+{invoices.length - 2} more)</span> : null}
1065
+ <span className="text-muted"> ({invoices.length} total)</span>
1066
+ </span>
1067
+ </>
1068
+ )}
1069
+ </span>
1070
+ )}
1071
+ </div>
1072
+ </div>
1073
+ {/* Upload (only before analysis) */}
1074
+ {!showResultsPanel && (
1075
+ <div className="lg:col-span-12">
1076
+ <Card title="Upload" subtitle="Invoice + PO CSV → decision">
1077
+ <div className="space-y-3">
1078
+ <MultiFileDrop
1079
+ label="Invoice (multiple)"
1080
+ accept=".pdf,.png,.jpg,.jpeg,.webp"
1081
+ files={invoices}
1082
+ onChange={(next) => setInvoices(next)}
1083
+ hint="PDF or image (scanned is OK). You can upload multiple invoices."
1084
+ />
1085
+ <FileDrop
1086
+ label="PO CSV"
1087
+ accept=".csv,.xlsx,.xls"
1088
+ file={po}
1089
+ onPick={setPo}
1090
+ hint="CSV or Excel (multiple sheets supported). Any columns accepted."
1091
+ />
1092
+
1093
+ <button
1094
+ onClick={onNext}
1095
+ disabled={!canNext}
1096
+ className="w-full rounded-xl bg-brand px-4 py-3 text-sm font-bold text-white shadow-md hover:brightness-105 disabled:opacity-40"
1097
+ >
1098
+ Next
1099
+ </button>
1100
+ <button
1101
+ onClick={onClear}
1102
+ disabled={loading}
1103
+ className="w-full rounded-xl border border-stroke bg-white px-4 py-3 text-sm font-semibold text-ink hover:bg-bg disabled:opacity-40"
1104
+ >
1105
+ Clear history
1106
+ </button>
1107
+
1108
+ <AnimatePresence>
1109
+ {error && (
1110
+ <motion.div
1111
+ initial={{ opacity: 0, y: 6 }}
1112
+ animate={{ opacity: 1, y: 0 }}
1113
+ exit={{ opacity: 0, y: 6 }}
1114
+ className="rounded-xl border border-rose-600/20 bg-rose-500/10 p-3 text-sm text-rose-700"
1115
+ >
1116
+ {error}
1117
+ </motion.div>
1118
+ )}
1119
+ </AnimatePresence>
1120
+ </div>
1121
+ </Card>
1122
+ </div>
1123
+ )}
1124
+
1125
+ {/* Results (only after Analyze is triggered) */}
1126
+ {showResultsPanel && (
1127
+ <div className="lg:col-span-12">
1128
+ <div className="sticky top-6 max-h-[calc(100vh-6.5rem)] overflow-auto pr-1">
1129
+ <Card
1130
+ title="Decision"
1131
+ subtitle={
1132
+ stage === "preview"
1133
+ ? "Ready to analyze"
1134
+ : stage === "analyzing"
1135
+ ? analysisRuns.length > 0 && activeRun
1136
+ ? `Viewing ${activeResultIdx + 1}/${analysisRuns.length} completed · ${activeRun.file.name} · ${
1137
+ activeAnalysis ? `PO: ${poDisplay(activeAnalysis.po_number, activeRun.file.name)}` : "Failed"
1138
+ }`
1139
+ : "Analyzing…"
1140
+ : stage === "result" && activeRun
1141
+ ? `Invoice ${activeResultIdx + 1}/${analysisRuns.length} · ${activeRun.file.name} · ${
1142
+ activeAnalysis ? `PO: ${poDisplay(activeAnalysis.po_number, activeRun.file.name)}` : "Failed"
1143
+ }`
1144
+ : ""
1145
+ }
1146
+ right={
1147
+ (stage === "result" || stage === "analyzing") && activeRun ? (
1148
+ <div className="flex flex-col items-end gap-2">
1149
+ <div className="flex items-center gap-2">
1150
+ {analysisRuns.length > 1 && (
1151
+ <>
1152
+ <button
1153
+ type="button"
1154
+ onClick={() => setActiveResultIdx((i) => Math.max(0, i - 1))}
1155
+ disabled={activeResultIdx <= 0}
1156
+ className="inline-flex items-center justify-center rounded-lg border border-stroke bg-white p-2 text-ink hover:bg-bg disabled:opacity-40"
1157
+ title="Previous invoice"
1158
+ aria-label="Previous invoice"
1159
+ >
1160
+ <IconChevron dir="left" />
1161
+ </button>
1162
+ <button
1163
+ type="button"
1164
+ onClick={() => setActiveResultIdx((i) => Math.min(analysisRuns.length - 1, i + 1))}
1165
+ disabled={activeResultIdx >= analysisRuns.length - 1}
1166
+ className="inline-flex items-center justify-center rounded-lg border border-stroke bg-white p-2 text-ink hover:bg-bg disabled:opacity-40"
1167
+ title="Next invoice"
1168
+ aria-label="Next invoice"
1169
+ >
1170
+ <IconChevron dir="right" />
1171
+ </button>
1172
+ </>
1173
+ )}
1174
+ {activeAnalysis ? (() => {
1175
+ const label =
1176
+ (activeAnalysis.details as any)?.approval_decision ||
1177
+ (activeAnalysis.evaluation as any)?.approval_decision ||
1178
+ activeAnalysis.evaluation.match_status ||
1179
+ "—";
1180
+ const tone = toneForApprovalDecision(label) || toneForStatus(activeAnalysis.evaluation.match_status);
1181
+ return <Badge tone={tone} text={label} />;
1182
+ })() : (
1183
+ <Badge tone="bad" text="Error" />
1184
+ )}
1185
+ </div>
1186
+ {activeAnalysis && (
1187
+ <div className="flex flex-wrap items-center justify-end gap-2">
1188
+ <MetricPill
1189
+ label="Confidence"
1190
+ value={fmtPct01(activeAnalysis?.details?.metrics?.confidence_score ?? null)}
1191
+ />
1192
+ <MetricPill label="Time" value={fmtMs(activeAnalysis?.details?.metrics?.processing_ms ?? null)} />
1193
+ <MetricPill
1194
+ label="Extractions"
1195
+ value={String(activeAnalysis?.details?.metrics?.extractions_count ?? "—")}
1196
+ />
1197
+ </div>
1198
+ )}
1199
+ </div>
1200
+ ) : undefined
1201
+ }
1202
+ >
1203
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
1204
+ <div className="text-xs text-muted">
1205
+ {stage === "preview"
1206
+ ? "Review the files below, then click “Start analyze”."
1207
+ : stage === "analyzing"
1208
+ ? "Analyzing your files…"
1209
+ : "Decision details"}
1210
+ </div>
1211
+ <div className="flex items-center gap-2">
1212
+ {stage === "preview" && (
1213
+ <>
1214
+ <button
1215
+ type="button"
1216
+ onClick={() => {
1217
+ if (loading) return;
1218
+ setError(null);
1219
+ setAnalysisRuns([]);
1220
+ setActiveResultIdx(0);
1221
+ setStage("upload");
1222
+ }}
1223
+ disabled={loading}
1224
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
1225
+ >
1226
+ Back
1227
+ </button>
1228
+ <button
1229
+ type="button"
1230
+ onClick={onStartAnalyze}
1231
+ disabled={!canStartAnalyze}
1232
+ className="rounded-lg bg-brand px-3 py-2 text-xs font-bold text-white shadow-md hover:brightness-105 disabled:opacity-40"
1233
+ >
1234
+ Start analyze
1235
+ </button>
1236
+ </>
1237
+ )}
1238
+ {stage !== "preview" && (
1239
+ <button
1240
+ type="button"
1241
+ onClick={() => {
1242
+ if (loading) return;
1243
+ setError(null);
1244
+ setAnalysisRuns([]);
1245
+ setActiveResultIdx(0);
1246
+ setStage("upload");
1247
+ }}
1248
+ disabled={loading}
1249
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
1250
+ >
1251
+ Change files
1252
+ </button>
1253
+ )}
1254
+ <BadgeButton
1255
+ tone="ok"
1256
+ text="Extracted JSON"
1257
+ onClick={() => setOcrOpen(true)}
1258
+ disabled={!hasOcr}
1259
+ title={hasOcr ? "View extracted JSON" : "Extracted JSON not available for this result"}
1260
+ />
1261
+ <button
1262
+ type="button"
1263
+ onClick={onClear}
1264
+ disabled={loading}
1265
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
1266
+ >
1267
+ Clear history
1268
+ </button>
1269
+ </div>
1270
+ </div>
1271
+
1272
+ <AnimatePresence>
1273
+ {error && (
1274
+ <motion.div
1275
+ initial={{ opacity: 0, y: 6 }}
1276
+ animate={{ opacity: 1, y: 0 }}
1277
+ exit={{ opacity: 0, y: 6 }}
1278
+ className="mb-4 rounded-xl border border-rose-600/20 bg-rose-500/10 p-3 text-sm text-rose-700"
1279
+ >
1280
+ {error}
1281
+ </motion.div>
1282
+ )}
1283
+ </AnimatePresence>
1284
+
1285
+ {stage === "preview" && (activeInvoice || po) && (
1286
+ <div className="mb-4 grid grid-cols-1 gap-3 lg:grid-cols-2">
1287
+ <InvoiceCarouselPreview
1288
+ files={invoices}
1289
+ activeIndex={activeInvoiceIdx}
1290
+ onChangeIndex={(idx) => setActiveInvoiceIdx(idx)}
1291
+ />
1292
+ <PoPreview file={po} />
1293
+ </div>
1294
+ )}
1295
+ <AnimatePresence>
1296
+ {stage === "analyzing" && loading && (
1297
+ <motion.div
1298
+ initial={{ opacity: 0 }}
1299
+ animate={{ opacity: 1 }}
1300
+ exit={{ opacity: 0 }}
1301
+ className="mb-4 rounded-xl border border-stroke bg-white p-4 shadow-sm"
1302
+ >
1303
+ <div className="text-sm font-semibold text-ink">Line matching</div>
1304
+ <div className="mt-2 overflow-auto">
1305
+ <table className="min-w-full text-left text-xs text-ink/80">
1306
+ <thead className="text-[11px] uppercase text-muted">
1307
+ <tr>
1308
+ <th className="py-2 pr-4">Status</th>
1309
+ <th className="py-2 pr-4">Item</th>
1310
+ <th className="py-2 pr-4">Qty</th>
1311
+ <th className="py-2 pr-4">PO Item</th>
1312
+ <th className="py-2 pr-4">Reason</th>
1313
+ </tr>
1314
+ </thead>
1315
+ <tbody>
1316
+ <tr className="border-t border-stroke">
1317
+ <td colSpan={5} className="py-10">
1318
+ <div className="flex w-full items-center justify-center">
1319
+ <div className="flex flex-col items-center text-center">
1320
+ <motion.div
1321
+ className="inline-flex items-center justify-center"
1322
+ aria-hidden="true"
1323
+ >
1324
+ <BookLoader size={64} />
1325
+ </motion.div>
1326
+ <div className="mt-3 text-base font-semibold text-ink">
1327
+ Analyzing {analyzingIdx === null ? "…" : `invoice ${analyzingIdx + 1}/${invoices.length}`}
1328
+ </div>
1329
+ <div className="mt-1 text-sm text-muted">
1330
+ {analyzingIdx !== null ? invoices[analyzingIdx]?.name : "Matching invoice lines to PO lines"}
1331
+ </div>
1332
+ </div>
1333
+ </div>
1334
+ </td>
1335
+ </tr>
1336
+ </tbody>
1337
+ </table>
1338
+ </div>
1339
+ </motion.div>
1340
+ )}
1341
+ </AnimatePresence>
1342
+
1343
+ {(stage === "result" || (stage === "analyzing" && analysisRuns.length > 0)) && activeRun && (
1344
+ <div className="space-y-4">
1345
+ {stage === "analyzing" && (
1346
+ <div className="rounded-xl border border-stroke bg-white p-3 text-xs text-muted">
1347
+ Showing completed results while processing the next invoice…{" "}
1348
+ <span className="font-semibold text-ink/70">
1349
+ {analysisRuns.length}/{invoices.length} completed
1350
+ </span>
1351
+ {analyzingIdx !== null ? (
1352
+ <span>
1353
+ {" "}
1354
+ · currently processing invoice{" "}
1355
+ <span className="font-semibold text-ink/70">
1356
+ {analyzingIdx + 1}/{invoices.length}
1357
+ </span>
1358
+ </span>
1359
+ ) : null}
1360
+ </div>
1361
+ )}
1362
+ {!activeAnalysis && activeRun.error && (
1363
+ <div className="rounded-xl border border-rose-600/20 bg-rose-500/10 p-4 text-sm text-rose-700">
1364
+ <div className="font-semibold">Failed to analyze invoice</div>
1365
+ <div className="mt-1 text-sm text-rose-700/90">{activeRun.file.name}</div>
1366
+ <div className="mt-2 whitespace-pre-wrap text-sm text-rose-700/90">{activeRun.error}</div>
1367
+ </div>
1368
+ )}
1369
+
1370
+ {activeAnalysis && (
1371
+ <>
1372
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
1373
+ {kpis?.map((k) => (
1374
+ <div key={k.label} className="rounded-xl border border-stroke bg-white p-3 shadow-sm">
1375
+ <div className="text-xs text-muted">{k.label}</div>
1376
+ <div className="mt-1 flex items-center justify-between gap-2">
1377
+ <div className="text-sm font-semibold text-ink">{k.value}</div>
1378
+ <Badge tone={k.badge} text={k.badge === "ok" ? "OK" : k.badge === "bad" ? "Issue" : "Review"} />
1379
+ </div>
1380
+ </div>
1381
+ ))}
1382
+ </div>
1383
+
1384
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
1385
+ <div className="text-sm font-semibold text-ink">Why this decision?</div>
1386
+ <div className="mt-2 whitespace-pre-wrap text-sm text-ink/80">{activeAnalysis.evaluation.rationale || "—"}</div>
1387
+ {activeAnalysis.evaluation.suggested_action && (
1388
+ <>
1389
+ <div className="mt-3 text-sm font-semibold text-ink">Suggested next step</div>
1390
+ <div className="mt-1 text-sm text-ink/80">{activeAnalysis.evaluation.suggested_action}</div>
1391
+ </>
1392
+ )}
1393
+ </div>
1394
+
1395
+ {activeAnalysis.evaluation.alerts?.length > 0 && (
1396
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
1397
+ <div className="text-sm font-semibold text-ink">Alerts</div>
1398
+ <div className="mt-2 space-y-2">
1399
+ {activeAnalysis.evaluation.alerts.map((a, idx) => (
1400
+ <div
1401
+ key={idx}
1402
+ className={`rounded-lg border px-3 py-2 text-sm ${
1403
+ a.level === "error"
1404
+ ? "border-rose-600/20 bg-rose-500/10 text-rose-700"
1405
+ : a.level === "warning"
1406
+ ? "border-amber-600/20 bg-amber-500/10 text-amber-800"
1407
+ : "border-stroke bg-bg text-ink/80"
1408
+ }`}
1409
+ >
1410
+ {a.message}
1411
+ </div>
1412
+ ))}
1413
+ </div>
1414
+ </div>
1415
+ )}
1416
+
1417
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
1418
+ <div className="text-sm font-semibold text-ink">Line matching</div>
1419
+ <div className="mt-2 overflow-auto">
1420
+ <table className="min-w-full text-left text-xs text-ink/80">
1421
+ <thead className="text-[11px] uppercase text-muted">
1422
+ <tr>
1423
+ <th className="py-2 pr-4">Status</th>
1424
+ <th className="py-2 pr-4">Item</th>
1425
+ <th className="py-2 pr-4">Qty</th>
1426
+ <th className="py-2 pr-4">PO Item</th>
1427
+ <th className="py-2 pr-4">Reason</th>
1428
+ </tr>
1429
+ </thead>
1430
+ <tbody>
1431
+ {activeAnalysis.evaluation.line_results?.map((r: any, i: number) => (
1432
+ <tr key={i} className="border-t border-stroke">
1433
+ <td className="py-2 pr-4">
1434
+ <Badge tone={toneForStatus(r.line_status)} text={r.line_status} />
1435
+ </td>
1436
+ <td className="py-2 pr-4">{r.invoice_sku || r.invoice_description || "—"}</td>
1437
+ <td className="py-2 pr-4">{r.invoice_qty ?? "—"}</td>
1438
+ <td className="py-2 pr-4">{r.po_sku || r.po_description || "—"}</td>
1439
+ <td className="py-2 pr-4">{r.mismatch_reasons || "—"}</td>
1440
+ </tr>
1441
+ ))}
1442
+ </tbody>
1443
+ </table>
1444
+ </div>
1445
+ </div>
1446
+
1447
+ {((activeAnalysis.details as any)?.backorders?.items || activeAnalysis.evaluation.open_backorders || []).length > 0 && (
1448
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
1449
+ <div className="flex items-center justify-between gap-2">
1450
+ <div className="text-sm font-semibold text-ink">Backorder remaining</div>
1451
+ <div className="text-xs text-muted">
1452
+ {((activeAnalysis.details as any)?.backorders?.count ??
1453
+ ((activeAnalysis.details as any)?.backorders?.items || activeAnalysis.evaluation.open_backorders || []).length) || 0}{" "}
1454
+ item(s) still pending
1455
+ </div>
1456
+ </div>
1457
+ <div className="mt-2 overflow-auto rounded-lg border border-stroke">
1458
+ <table className="min-w-full text-left text-xs text-ink/80">
1459
+ <thead className="bg-white text-[11px] uppercase text-muted">
1460
+ <tr>
1461
+ <th className="px-3 py-2">SKU</th>
1462
+ <th className="px-3 py-2">Description</th>
1463
+ <th className="px-3 py-2">Ordered</th>
1464
+ <th className="px-3 py-2">Received</th>
1465
+ <th className="px-3 py-2">Remaining</th>
1466
+ </tr>
1467
+ </thead>
1468
+ <tbody>
1469
+ {(((activeAnalysis.details as any)?.backorders?.items ||
1470
+ activeAnalysis.evaluation.open_backorders ||
1471
+ []) as any[]).map((b: any, idx: number) => (
1472
+ <tr key={b.po_line_id || idx} className="border-t border-stroke">
1473
+ <td className="px-3 py-2">{b.sku || "—"}</td>
1474
+ <td className="px-3 py-2">{b.description || "—"}</td>
1475
+ <td className="px-3 py-2">{fmtNum(b.qty_ordered)}</td>
1476
+ <td className="px-3 py-2">{fmtNum(b.received_after ?? b.received_before)}</td>
1477
+ <td className="px-3 py-2 font-semibold text-amber-800">{fmtNum(b.remaining)}</td>
1478
+ </tr>
1479
+ ))}
1480
+ </tbody>
1481
+ </table>
1482
+ </div>
1483
+ </div>
1484
+ )}
1485
+ </>
1486
+ )}
1487
+ </div>
1488
+ )}
1489
+ </Card>
1490
+ </div>
1491
+ </div>
1492
+ )}
1493
+ </motion.div>
1494
+ </AnimatePresence>
1495
+ )}
1496
+
1497
+ {page === "history" && (
1498
+ <AnimatePresence mode="wait">
1499
+ <motion.div
1500
+ key="history"
1501
+ initial={{ opacity: 0, y: 10 }}
1502
+ animate={{ opacity: 1, y: 0 }}
1503
+ exit={{ opacity: 0, y: 8 }}
1504
+ transition={{ duration: 0.25, ease: "easeOut" }}
1505
+ >
1506
+ <div className="space-y-6">
1507
+ <div className="flex flex-wrap items-center gap-3">
1508
+ <div className="flex w-full max-w-[520px] items-center gap-2 rounded-xl border border-stroke bg-white px-3 py-2">
1509
+ <span className="text-muted">
1510
+ <IconSearch />
1511
+ </span>
1512
+ <input
1513
+ value={historySearch}
1514
+ onChange={(e) => {
1515
+ setSelectedHistoryId(null);
1516
+ setHistorySearch(e.target.value);
1517
+ }}
1518
+ placeholder="Search by file name, invoice, supplier…"
1519
+ className="w-full bg-transparent text-sm font-semibold text-ink outline-none placeholder:text-muted"
1520
+ />
1521
+ </div>
1522
+
1523
+ <div className="flex items-center gap-2 rounded-xl border border-stroke bg-white px-3 py-2">
1524
+ <span className="text-muted">
1525
+ <IconFilter />
1526
+ </span>
1527
+ <select
1528
+ value={historyStatusFilter}
1529
+ onChange={(e) => {
1530
+ setSelectedHistoryId(null);
1531
+ setHistoryStatusFilter(e.target.value);
1532
+ }}
1533
+ className="bg-transparent text-sm font-semibold text-ink outline-none"
1534
+ title="Status"
1535
+ >
1536
+ <option value="">Status</option>
1537
+ <option value="Approved">Approved</option>
1538
+ <option value="Partially Approved">Partially Approved</option>
1539
+ <option value="Rejected">Rejected</option>
1540
+ </select>
1541
+ </div>
1542
+
1543
+ <button
1544
+ type="button"
1545
+ className="ml-auto rounded-xl bg-brand px-4 py-2.5 text-sm font-bold text-white shadow-md hover:brightness-105"
1546
+ onClick={() => {
1547
+ const payload = {
1548
+ exported_at: new Date().toISOString(),
1549
+ total: filteredHistoryItems.length,
1550
+ items: filteredHistoryItems,
1551
+ };
1552
+ downloadTextFile(`history_export_${Date.now()}.json`, JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
1553
+ setToast("Exported history (.json)");
1554
+ }}
1555
+ disabled={historyLoading || filteredHistoryItems.length === 0}
1556
+ >
1557
+ Export All
1558
+ </button>
1559
+ </div>
1560
+
1561
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-4">
1562
+ <div className="rounded-2xl border border-stroke bg-white p-4 shadow-soft">
1563
+ <div className="text-xs font-semibold text-muted">Total Extractions</div>
1564
+ <div className="mt-1 text-2xl font-bold text-ink">{historySummary.total}</div>
1565
+ </div>
1566
+ <div className="rounded-2xl border border-stroke bg-white p-4 shadow-soft">
1567
+ <div className="text-xs font-semibold text-muted">Success Rate</div>
1568
+ <div className="mt-1 text-2xl font-bold text-ink">{Math.round(historySummary.successRate * 1000) / 10}%</div>
1569
+ <div className="mt-0.5 text-xs font-semibold text-emerald-700">
1570
+ {historySummary.successes}/{historySummary.total || 0} successful
1571
+ </div>
1572
+ </div>
1573
+ <div className="rounded-2xl border border-stroke bg-white p-4 shadow-soft">
1574
+ <div className="text-xs font-semibold text-muted">Avg. Processing Time</div>
1575
+ <div className="mt-1 text-2xl font-bold text-ink">{fmtSecCompact(historySummary.avgMs)}</div>
1576
+ </div>
1577
+ <div className="rounded-2xl border border-stroke bg-white p-4 shadow-soft">
1578
+ <div className="text-xs font-semibold text-muted">Fields Extracted</div>
1579
+ <div className="mt-1 text-2xl font-bold text-ink">{historySummary.fieldsTotal}</div>
1580
+ </div>
1581
+ </div>
1582
+
1583
+ <AnimatePresence>
1584
+ {historyError && (
1585
+ <motion.div
1586
+ initial={{ opacity: 0, y: 6 }}
1587
+ animate={{ opacity: 1, y: 0 }}
1588
+ exit={{ opacity: 0, y: 6 }}
1589
+ className="rounded-xl border border-rose-600/20 bg-rose-500/10 p-3 text-sm text-rose-700"
1590
+ >
1591
+ {historyError}
1592
+ </motion.div>
1593
+ )}
1594
+ </AnimatePresence>
1595
+
1596
+ {!historyLoading && historyItems.length === 0 && !historyError && (
1597
+ <div className="rounded-2xl border border-stroke bg-white p-6 text-sm text-muted">
1598
+ No history yet. Run an analysis to create entries.
1599
+ </div>
1600
+ )}
1601
+
1602
+ <div className="space-y-3">
1603
+ {(filteredHistoryItems || []).map((it) => {
1604
+ const label = String((it as any).approval_decision || it.match_status || "—");
1605
+ const tone = toneForApprovalDecision(label) || toneForStatus(String(it.match_status || ""));
1606
+ return (
1607
+ <motion.button
1608
+ key={it.id}
1609
+ type="button"
1610
+ whileHover={{ y: -1 }}
1611
+ whileTap={{ scale: 0.995 }}
1612
+ onClick={() => {
1613
+ setSelectedHistoryId(it.id);
1614
+ setHistoryDetailsOpen(true);
1615
+ }}
1616
+ className={`w-full rounded-2xl border border-stroke bg-white p-5 text-left shadow-soft hover:bg-bg ${
1617
+ selectedHistoryId === it.id ? "ring-2 ring-brand/20" : ""
1618
+ }`}
1619
+ >
1620
+ <div className="flex flex-wrap items-center justify-between gap-4">
1621
+ <div className="flex min-w-0 items-center gap-4">
1622
+ <div className="inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-brand/10 text-brand">
1623
+ <IconFile />
1624
+ </div>
1625
+ <div className="min-w-0">
1626
+ <div className="flex min-w-0 items-center gap-2">
1627
+ <div className="truncate text-sm font-bold text-ink">{it.file_name || it.invoice_number || it.id}</div>
1628
+ {it.duplicate_flag ? (
1629
+ <span className="shrink-0 rounded-full border border-rose-600/25 bg-rose-500/10 px-2 py-0.5 text-[11px] font-semibold text-rose-700">
1630
+ Duplicate
1631
+ </span>
1632
+ ) : null}
1633
+ </div>
1634
+ <div className="mt-1 flex flex-wrap items-center gap-3 text-xs text-muted">
1635
+ <span>{poFromFilename(it.file_name) || (it.po_number || "").trim() || "—"}</span>
1636
+ <span>·</span>
1637
+ <span>{fmtDate(it.processed_at)}</span>
1638
+ </div>
1639
+ </div>
1640
+ </div>
1641
+
1642
+ <div className="flex items-center gap-8">
1643
+ <div className="text-right">
1644
+ <div className="text-xs text-muted">Time</div>
1645
+ <div className="mt-1 text-sm font-bold text-ink">{fmtSecCompact(it.processing_ms ?? null)}</div>
1646
+ </div>
1647
+ <div className="text-right">
1648
+ <div className="text-xs text-muted">Fields</div>
1649
+ <div className="mt-1 text-sm font-bold text-ink">{it.extractions_count ?? "—"}</div>
1650
+ </div>
1651
+ <div className="text-right">
1652
+ <div className="text-xs text-muted">Confidence</div>
1653
+ <div className="mt-1 text-sm font-bold text-emerald-700">{fmtPct01(it.match_score ?? null)}</div>
1654
+ </div>
1655
+
1656
+ <div className="flex items-center gap-3">
1657
+ <Badge tone={tone} text={label} />
1658
+ <div className="text-muted">
1659
+ <IconChevron dir="right" />
1660
+ </div>
1661
+ </div>
1662
+ </div>
1663
+ </div>
1664
+ </motion.button>
1665
+ );
1666
+ })}
1667
+
1668
+ {!historyLoading && filteredHistoryItems.length === 0 && historyItems.length > 0 && (
1669
+ <div className="rounded-2xl border border-stroke bg-white p-6 text-sm text-muted">
1670
+ No results match your filters.
1671
+ </div>
1672
+ )}
1673
+ </div>
1674
+
1675
+ </div>
1676
+ </motion.div>
1677
+ </AnimatePresence>
1678
+ )}
1679
+ </div>
1680
+ </main>
1681
+ </div>
1682
+ </div>
1683
+ );
1684
+ }
1685
+
1686
+
1687
+
frontend/src/api.ts ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type Alert = { level: "info" | "warning" | "error"; message: string };
2
+
3
+ export type Evaluation = {
4
+ match_status: "Matched" | "Review" | "Unmatched" | string;
5
+ duplicate: boolean;
6
+ supplier_status: string;
7
+ confidence_score?: number | null;
8
+ approval_decision?: "Approved" | "Partially Approved" | "Rejected" | string;
9
+ rationale?: string;
10
+ suggested_action?: string;
11
+ alerts: Alert[];
12
+ line_results: any[];
13
+ open_backorders: any[];
14
+ };
15
+
16
+ export type DuplicateMatch = {
17
+ id: string;
18
+ processed_at?: string;
19
+ invoice_number?: string;
20
+ supplier?: string;
21
+ po_number?: string;
22
+ match_status?: string;
23
+ duplicate_flag?: number;
24
+ };
25
+
26
+ export type AnalyzeDetails = {
27
+ metrics?: {
28
+ confidence_score?: number | null;
29
+ processing_ms?: number | null;
30
+ extractions_count?: number | null;
31
+ };
32
+ approval_decision?: "Approved" | "Partially Approved" | "Rejected" | string | null;
33
+ backorders?: {
34
+ count?: number;
35
+ items?: Array<{
36
+ po_line_id?: string;
37
+ sku?: string;
38
+ description?: string;
39
+ qty_ordered?: number;
40
+ received_before?: number;
41
+ received_after?: number;
42
+ remaining?: number;
43
+ }>;
44
+ };
45
+ ocr?: {
46
+ file_name?: string;
47
+ file_sha256?: string;
48
+ provider?: string;
49
+ text?: string;
50
+ text_chars?: number;
51
+ images_count?: number;
52
+ images_preview?: string[];
53
+ result?: any;
54
+ error?: string;
55
+ extracted_invoice?: any;
56
+ };
57
+ invoice?: {
58
+ invoice_number?: string;
59
+ supplier?: string;
60
+ po_number?: string;
61
+ total_amount?: string;
62
+ currency?: string;
63
+ file_name?: string;
64
+ };
65
+ po?: {
66
+ po_number?: string;
67
+ supplier?: string;
68
+ po_amount?: any;
69
+ currency?: string;
70
+ line_items_count?: number;
71
+ source_filename?: string;
72
+ };
73
+ supplier_validation?: {
74
+ status?: string;
75
+ best_match?: string;
76
+ match_score?: number;
77
+ notes?: string;
78
+ };
79
+ };
80
+
81
+ export type AnalyzeResponse = {
82
+ invoice_id: string | null;
83
+ po_number: string;
84
+ evaluation: Evaluation;
85
+ details?: AnalyzeDetails;
86
+ duplicate_matches?: DuplicateMatch[];
87
+ blocked?: boolean;
88
+ };
89
+
90
+ export type HistoryItem = {
91
+ id: string;
92
+ processed_at?: string;
93
+ invoice_number?: string;
94
+ supplier?: string;
95
+ po_number?: string;
96
+ invoice_total?: number | null;
97
+ currency?: string | null;
98
+ match_status?: string;
99
+ match_score?: number | null;
100
+ processing_ms?: number | null;
101
+ extractions_count?: number | null;
102
+ approval_decision?: "Approved" | "Partially Approved" | "Rejected" | string | null;
103
+ open_backorders_count?: number;
104
+ duplicate_flag?: number;
105
+ decision_engine?: string | null;
106
+ ai_model?: string | null;
107
+ supplier_status?: string | null;
108
+ override_reason?: string | null;
109
+ file_name?: string | null;
110
+ };
111
+
112
+ export type HistoryResponse = { items: HistoryItem[] };
113
+
114
+ export type InvoiceDetail = {
115
+ invoice: Record<string, any>;
116
+ lines: Record<string, any>[];
117
+ extracted_invoice?: any;
118
+ backorders?: { count?: number; items?: any[] };
119
+ };
120
+
121
+ const CONFIGURED_API_BASE = (import.meta.env.VITE_API_BASE_URL || "").trim();
122
+ // Use relative /api by default so Vite can proxy in dev and the backend can serve in prod.
123
+ // If you need an absolute URL, set VITE_API_BASE_URL.
124
+ const API_BASE = (CONFIGURED_API_BASE || "").replace(/\/$/, "");
125
+ const api = (path: string) => (API_BASE ? `${API_BASE}${path}` : path);
126
+
127
+ function safeJsonParse<T = any>(text: string): T | null {
128
+ try {
129
+ return JSON.parse(text) as T;
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ async function readJsonOrThrow<T>(res: Response): Promise<T> {
136
+ const text = await res.text();
137
+ const ct = (res.headers.get("content-type") || "").toLowerCase();
138
+
139
+ // FastAPI errors often return JSON, but a misrouted request returns HTML (doctype).
140
+ const maybeJson = safeJsonParse<T>(text);
141
+ if (maybeJson !== null) return maybeJson;
142
+
143
+ const preview = text.slice(0, 200).replace(/\s+/g, " ").trim();
144
+ throw new Error(`Expected JSON but got ${ct || "unknown content-type"} (${res.status}). Response: ${preview}`);
145
+ }
146
+
147
+ export async function analyze(invoice: File, poCsv: File) {
148
+ const fd = new FormData();
149
+ fd.append("invoice", invoice);
150
+ fd.append("po_file", poCsv);
151
+
152
+ const res = await fetch(api("/api/analyze"), { method: "POST", body: fd });
153
+ const data = await readJsonOrThrow<AnalyzeResponse & { detail?: string }>(res);
154
+ if (!res.ok) throw new Error((data as any).detail || `Analyze failed (${res.status})`);
155
+ return data as AnalyzeResponse;
156
+ }
157
+
158
+ export async function analyzeWithOverride(
159
+ invoice: File,
160
+ poCsv: File,
161
+ opts: { duplicate_override: boolean; override_reason?: string }
162
+ ) {
163
+ const fd = new FormData();
164
+ fd.append("invoice", invoice);
165
+ fd.append("po_file", poCsv);
166
+ fd.append("duplicate_override", String(Boolean(opts.duplicate_override)));
167
+ fd.append("override_reason", (opts.override_reason || "").trim());
168
+
169
+ const res = await fetch(api("/api/analyze"), { method: "POST", body: fd });
170
+ const data = await readJsonOrThrow<AnalyzeResponse & { detail?: string }>(res);
171
+ if (!res.ok) throw new Error((data as any).detail || `Analyze failed (${res.status})`);
172
+ return data as AnalyzeResponse;
173
+ }
174
+
175
+ export async function clearDb() {
176
+ const res = await fetch(api("/api/clear"), { method: "POST" });
177
+ const data = await readJsonOrThrow<{ ok?: boolean; detail?: string }>(res);
178
+ if (!res.ok) throw new Error(data.detail || `Clear failed (${res.status})`);
179
+ return data;
180
+ }
181
+
182
+ export async function health() {
183
+ const res = await fetch(api("/api/health"));
184
+ return readJsonOrThrow<{ ok: boolean; error?: string }>(res);
185
+ }
186
+
187
+ export async function getHistory(params?: {
188
+ limit?: number;
189
+ invoice_number?: string;
190
+ supplier?: string;
191
+ po_number?: string;
192
+ match_status?: string;
193
+ duplicate_flag?: number;
194
+ date_from?: string;
195
+ date_to?: string;
196
+ }) {
197
+ const qs = new URLSearchParams();
198
+ if (params?.limit != null) qs.set("limit", String(params.limit));
199
+ if (params?.invoice_number) qs.set("invoice_number", params.invoice_number);
200
+ if (params?.supplier) qs.set("supplier", params.supplier);
201
+ if (params?.po_number) qs.set("po_number", params.po_number);
202
+ if (params?.match_status) qs.set("match_status", params.match_status);
203
+ if (params?.duplicate_flag != null) qs.set("duplicate_flag", String(params.duplicate_flag));
204
+ if (params?.date_from) qs.set("date_from", params.date_from);
205
+ if (params?.date_to) qs.set("date_to", params.date_to);
206
+
207
+ const res = await fetch(api(`/api/history${qs.toString() ? `?${qs.toString()}` : ""}`));
208
+ const data = await readJsonOrThrow<HistoryResponse & { detail?: string }>(res);
209
+ if (!res.ok) throw new Error((data as any).detail || `History failed (${res.status})`);
210
+ return data as HistoryResponse;
211
+ }
212
+
213
+ export async function getHistoryDetail(invoiceId: string) {
214
+ const res = await fetch(api(`/api/history/${encodeURIComponent(invoiceId)}`));
215
+ const data = await readJsonOrThrow<InvoiceDetail & { detail?: string }>(res);
216
+ if (!res.ok) throw new Error((data as any).detail || `History detail failed (${res.status})`);
217
+ return data as InvoiceDetail;
218
+ }
219
+
220
+
frontend/src/components/Badge.tsx ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+
3
+ export function badgeToneClass(tone: "ok" | "warn" | "bad" | "neutral") {
4
+ return tone === "ok"
5
+ ? "border-emerald-600/25 bg-emerald-500/10 text-emerald-700"
6
+ : tone === "warn"
7
+ ? "border-amber-600/25 bg-amber-500/10 text-amber-800"
8
+ : tone === "bad"
9
+ ? "border-rose-600/25 bg-rose-500/10 text-rose-700"
10
+ : "border-stroke bg-black/0 text-muted";
11
+ }
12
+
13
+ export function Badge({ tone, text }: { tone: "ok" | "warn" | "bad" | "neutral"; text: string }) {
14
+ const cls = badgeToneClass(tone);
15
+ return (
16
+ <motion.span
17
+ initial={{ opacity: 0, scale: 0.98 }}
18
+ animate={{ opacity: 1, scale: 1 }}
19
+ transition={{ duration: 0.18, ease: "easeOut" }}
20
+ className={`inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold ${cls}`}
21
+ >
22
+ {text}
23
+ </motion.span>
24
+ );
25
+ }
26
+
27
+
frontend/src/components/BadgeButton.tsx ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+ import { badgeToneClass } from "./Badge";
3
+
4
+ export function BadgeButton(props: {
5
+ tone: "ok" | "warn" | "bad" | "neutral";
6
+ text: string;
7
+ onClick?: () => void;
8
+ disabled?: boolean;
9
+ title?: string;
10
+ className?: string;
11
+ }) {
12
+ const cls = badgeToneClass(props.tone);
13
+ return (
14
+ <motion.button
15
+ type="button"
16
+ initial={{ opacity: 0, scale: 0.98 }}
17
+ animate={{ opacity: 1, scale: 1 }}
18
+ transition={{ duration: 0.18, ease: "easeOut" }}
19
+ onClick={props.onClick}
20
+ disabled={props.disabled}
21
+ title={props.title}
22
+ className={`inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold ${cls} transition-shadow hover:brightness-105 hover:shadow-md hover:shadow-brand/15 disabled:opacity-40 ${
23
+ props.className || ""
24
+ }`}
25
+ >
26
+ {props.text}
27
+ </motion.button>
28
+ );
29
+ }
30
+
31
+
frontend/src/components/BookLoader.tsx ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+
3
+ export function BookLoader({ size = 56 }: { size?: number }) {
4
+ const w = size;
5
+ const h = Math.round(size * 0.75);
6
+ const r = Math.max(10, Math.round(size * 0.18));
7
+
8
+ return (
9
+ <motion.svg
10
+ width={w}
11
+ height={h}
12
+ viewBox="0 0 120 90"
13
+ fill="none"
14
+ xmlns="http://www.w3.org/2000/svg"
15
+ aria-hidden="true"
16
+ >
17
+ <defs>
18
+ <linearGradient id="bk" x1="15" y1="15" x2="105" y2="75" gradientUnits="userSpaceOnUse">
19
+ <stop stopColor="#4F46E5" />
20
+ <stop offset="1" stopColor="#10B981" />
21
+ </linearGradient>
22
+ </defs>
23
+
24
+ {/* Shadow */}
25
+ <motion.ellipse
26
+ cx="60"
27
+ cy="80"
28
+ rx="40"
29
+ ry="7"
30
+ fill="rgba(15,23,42,0.10)"
31
+ animate={{ scaleX: [0.95, 1.05, 0.95], opacity: [0.22, 0.30, 0.22] }}
32
+ transition={{ repeat: Infinity, duration: 1.6, ease: "easeInOut" }}
33
+ />
34
+
35
+ {/* Left cover */}
36
+ <motion.path
37
+ d={`M16 18c0-6 5-11 11-11h33c7 0 12 5 12 12v55c0 2-2 4-4 3-11-3-22-4-34-4H28c-6 0-12-5-12-11V18Z`}
38
+ fill="url(#bk)"
39
+ opacity="0.92"
40
+ initial={false}
41
+ animate={{ rotate: [-10, -2, -10], y: [0, -1, 0] }}
42
+ style={{ transformOrigin: "60px 45px" }}
43
+ transition={{ repeat: Infinity, duration: 1.8, ease: "easeInOut" }}
44
+ />
45
+
46
+ {/* Right cover */}
47
+ <motion.path
48
+ d={`M104 18c0-6-5-11-11-11H60c-7 0-12 5-12 12v55c0 2 2 4 4 3 11-3 22-4 34-4h8c6 0 12-5 12-11V18Z`}
49
+ fill="url(#bk)"
50
+ opacity="0.86"
51
+ initial={false}
52
+ animate={{ rotate: [10, 2, 10], y: [0, -1, 0] }}
53
+ style={{ transformOrigin: "60px 45px" }}
54
+ transition={{ repeat: Infinity, duration: 1.8, ease: "easeInOut" }}
55
+ />
56
+
57
+ {/* Spine */}
58
+ <rect x="56" y="10" width="8" height="68" rx={r} fill="rgba(255,255,255,0.65)" />
59
+
60
+ {/* Pages (flipping) */}
61
+ <motion.path
62
+ d="M60 18c-10 0-20 2-30 5v45c10-3 20-4 30-4V18Z"
63
+ fill="rgba(255,255,255,0.88)"
64
+ animate={{ opacity: [0.55, 0.95, 0.55] }}
65
+ transition={{ repeat: Infinity, duration: 1.2, ease: "easeInOut" }}
66
+ />
67
+ <motion.path
68
+ d="M60 18c10 0 20 2 30 5v45c-10-3-20-4-30-4V18Z"
69
+ fill="rgba(255,255,255,0.82)"
70
+ animate={{ opacity: [0.45, 0.90, 0.45] }}
71
+ transition={{ repeat: Infinity, duration: 1.2, ease: "easeInOut", delay: 0.2 }}
72
+ />
73
+
74
+ {/* Page flip highlight */}
75
+ <motion.path
76
+ d="M60 22c9 1 18 3 26 5v5c-8-2-17-4-26-5v-5Z"
77
+ fill="rgba(255,255,255,0.55)"
78
+ animate={{ x: [0, 2, 0], opacity: [0.2, 0.55, 0.2] }}
79
+ transition={{ repeat: Infinity, duration: 0.9, ease: "easeInOut" }}
80
+ />
81
+ </motion.svg>
82
+ );
83
+ }
84
+
85
+
frontend/src/components/Card.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ReactNode } from "react";
2
+ import { motion } from "framer-motion";
3
+
4
+ export function Card({
5
+ title,
6
+ subtitle,
7
+ right,
8
+ children
9
+ }: {
10
+ title?: string;
11
+ subtitle?: string;
12
+ right?: ReactNode;
13
+ children: ReactNode;
14
+ }) {
15
+ return (
16
+ <motion.div
17
+ whileHover={{ y: -2 }}
18
+ transition={{ type: "spring", stiffness: 320, damping: 22 }}
19
+ className="group relative rounded-2xl border border-stroke bg-panel shadow-soft"
20
+ >
21
+ {(title || subtitle || right) && (
22
+ <div className="flex items-start justify-between gap-4 border-b border-stroke px-5 py-4">
23
+ <div>
24
+ {title && <div className="text-sm font-semibold text-ink">{title}</div>}
25
+ {subtitle && <div className="mt-0.5 text-xs text-muted">{subtitle}</div>}
26
+ </div>
27
+ {right}
28
+ </div>
29
+ )}
30
+ <div className="px-5 py-4">{children}</div>
31
+ <div className="pointer-events-none absolute inset-0 rounded-2xl opacity-0 ring-1 ring-brand/15 transition-opacity duration-300 group-hover:opacity-100" />
32
+ </motion.div>
33
+ );
34
+ }
35
+
36
+
frontend/src/components/FileDrop.tsx ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useRef } from "react";
2
+ import { motion } from "framer-motion";
3
+
4
+ export function FileDrop({
5
+ label,
6
+ accept,
7
+ file,
8
+ onPick,
9
+ hint
10
+ }: {
11
+ label: string;
12
+ accept: string;
13
+ file: File | null;
14
+ onPick: (f: File) => void;
15
+ hint?: string;
16
+ }) {
17
+ const inputRef = useRef<HTMLInputElement | null>(null);
18
+
19
+ const onDrop = useCallback(
20
+ (e: React.DragEvent) => {
21
+ e.preventDefault();
22
+ const f = e.dataTransfer.files?.[0];
23
+ if (f) onPick(f);
24
+ },
25
+ [onPick]
26
+ );
27
+
28
+ return (
29
+ <motion.div
30
+ whileHover={{ y: -1 }}
31
+ className="rounded-xl border border-stroke bg-white p-4"
32
+ onDragOver={(e) => e.preventDefault()}
33
+ onDrop={onDrop}
34
+ >
35
+ <div className="flex items-start justify-between gap-3">
36
+ <div>
37
+ <div className="text-sm font-semibold text-ink">{label}</div>
38
+ <div className="mt-1 text-xs text-muted">{hint || "Drag & drop or browse"}</div>
39
+ <div className="mt-1 text-[11px] text-muted">Accepted: {accept.replace(/\./g, "").toUpperCase()}</div>
40
+ </div>
41
+ {file ? (
42
+ <div className="shrink-0 rounded-full border border-emerald-600/25 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-700">
43
+ ✓ Added
44
+ </div>
45
+ ) : null}
46
+ </div>
47
+
48
+ <div className="mt-3 flex items-center justify-between gap-3">
49
+ <div className="min-w-0">
50
+ {file ? (
51
+ <div className="truncate text-sm text-ink/80">{file.name}</div>
52
+ ) : (
53
+ <div className="text-sm text-muted">No file selected</div>
54
+ )}
55
+ </div>
56
+ <button
57
+ type="button"
58
+ onClick={() => inputRef.current?.click()}
59
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg"
60
+ >
61
+ Browse
62
+ </button>
63
+ <input
64
+ ref={inputRef}
65
+ type="file"
66
+ accept={accept}
67
+ className="hidden"
68
+ onChange={(e) => {
69
+ const f = e.target.files?.[0];
70
+ if (f) onPick(f);
71
+ }}
72
+ />
73
+ </div>
74
+ </motion.div>
75
+ );
76
+ }
77
+
78
+
frontend/src/components/FilePreview.tsx ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import { AnimatePresence, motion } from "framer-motion";
3
+
4
+ function useObjectUrl(file: File | null) {
5
+ const [url, setUrl] = useState<string | null>(null);
6
+ useEffect(() => {
7
+ if (!file) {
8
+ setUrl(null);
9
+ return;
10
+ }
11
+ const u = URL.createObjectURL(file);
12
+ setUrl(u);
13
+ return () => URL.revokeObjectURL(u);
14
+ }, [file]);
15
+ return url;
16
+ }
17
+
18
+ function looksLikePdf(file: File) {
19
+ return file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf");
20
+ }
21
+
22
+ function looksLikeImage(file: File) {
23
+ return file.type.startsWith("image/");
24
+ }
25
+
26
+ function looksLikeCsv(file: File) {
27
+ const n = file.name.toLowerCase();
28
+ return file.type.includes("csv") || n.endsWith(".csv");
29
+ }
30
+
31
+ function parseCsvLine(line: string): string[] {
32
+ const out: string[] = [];
33
+ let cur = "";
34
+ let inQuotes = false;
35
+ for (let i = 0; i < line.length; i++) {
36
+ const ch = line[i];
37
+ if (inQuotes) {
38
+ if (ch === '"') {
39
+ const next = line[i + 1];
40
+ if (next === '"') {
41
+ cur += '"';
42
+ i++;
43
+ } else {
44
+ inQuotes = false;
45
+ }
46
+ } else {
47
+ cur += ch;
48
+ }
49
+ } else {
50
+ if (ch === ",") {
51
+ out.push(cur);
52
+ cur = "";
53
+ } else if (ch === '"') {
54
+ inQuotes = true;
55
+ } else {
56
+ cur += ch;
57
+ }
58
+ }
59
+ }
60
+ out.push(cur);
61
+ return out.map((s) => s.trim());
62
+ }
63
+
64
+ function InvoicePreviewBody({ file }: { file: File | null }) {
65
+ const url = useObjectUrl(file);
66
+ if (!file) return null;
67
+
68
+ return (
69
+ <div className="overflow-hidden rounded-lg border border-stroke bg-bg">
70
+ {looksLikeImage(file) && url && <img src={url} alt="Invoice preview" className="max-h-[420px] w-full object-contain" />}
71
+
72
+ {looksLikePdf(file) && url && (
73
+ <object data={url} type="application/pdf" className="h-[420px] w-full">
74
+ <div className="p-4 text-sm text-muted">
75
+ PDF preview isn’t available in this browser view.{" "}
76
+ <a className="font-semibold text-brand underline" href={url} target="_blank" rel="noreferrer">
77
+ Open PDF in a new tab
78
+ </a>
79
+ .
80
+ </div>
81
+ </object>
82
+ )}
83
+
84
+ {!looksLikeImage(file) && !looksLikePdf(file) && (
85
+ <div className="p-4 text-sm text-muted">Preview not available for this file type.</div>
86
+ )}
87
+ </div>
88
+ );
89
+ }
90
+
91
+ export function InvoicePreview({ file }: { file: File | null }) {
92
+ if (!file) return null;
93
+ return (
94
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
95
+ <div className="mb-2 flex items-center justify-between gap-3">
96
+ <div className="text-sm font-semibold text-ink">Invoice preview</div>
97
+ <div className="truncate text-xs text-muted">{file.name}</div>
98
+ </div>
99
+ <InvoicePreviewBody file={file} />
100
+ </div>
101
+ );
102
+ }
103
+
104
+ export function InvoiceCarouselPreview({
105
+ files,
106
+ activeIndex,
107
+ onChangeIndex
108
+ }: {
109
+ files: File[];
110
+ activeIndex: number;
111
+ onChangeIndex: (idx: number) => void;
112
+ }) {
113
+ const total = files.length;
114
+ if (total === 0) return null;
115
+ const idx = Math.max(0, Math.min(activeIndex, total - 1));
116
+ const f = files[idx] || null;
117
+
118
+ const canPrev = idx > 0;
119
+ const canNext = idx < total - 1;
120
+
121
+ return (
122
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
123
+ <div className="mb-2 flex items-center justify-between gap-3">
124
+ <div className="min-w-0">
125
+ <div className="text-sm font-semibold text-ink">Invoice preview</div>
126
+ <div className="mt-0.5 truncate text-xs text-muted">
127
+ {f?.name || "—"} {total > 1 ? `(${idx + 1}/${total})` : ""}
128
+ </div>
129
+ </div>
130
+
131
+ {total > 1 && (
132
+ <div className="flex items-center gap-2">
133
+ <button
134
+ type="button"
135
+ onClick={() => canPrev && onChangeIndex(idx - 1)}
136
+ disabled={!canPrev}
137
+ className="rounded-lg border border-stroke bg-white px-2.5 py-1.5 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
138
+ aria-label="Previous invoice"
139
+ title="Previous"
140
+ >
141
+ {"<"}
142
+ </button>
143
+ <button
144
+ type="button"
145
+ onClick={() => canNext && onChangeIndex(idx + 1)}
146
+ disabled={!canNext}
147
+ className="rounded-lg border border-stroke bg-white px-2.5 py-1.5 text-xs font-semibold text-ink hover:bg-bg disabled:opacity-40"
148
+ aria-label="Next invoice"
149
+ title="Next"
150
+ >
151
+ {">"}
152
+ </button>
153
+ </div>
154
+ )}
155
+ </div>
156
+
157
+ <InvoicePreviewBody file={f} />
158
+ </div>
159
+ );
160
+ }
161
+
162
+ export function PoPreview({ file }: { file: File | null }) {
163
+ const [csvText, setCsvText] = useState<string>("");
164
+ const [csvErr, setCsvErr] = useState<string | null>(null);
165
+
166
+ useEffect(() => {
167
+ let cancelled = false;
168
+ async function run() {
169
+ setCsvText("");
170
+ setCsvErr(null);
171
+ if (!file) return;
172
+ if (!looksLikeCsv(file)) return;
173
+ try {
174
+ const t = await file.text();
175
+ if (cancelled) return;
176
+ setCsvText(t);
177
+ } catch (e: any) {
178
+ if (cancelled) return;
179
+ setCsvErr(e?.message || String(e));
180
+ }
181
+ }
182
+ run();
183
+ return () => {
184
+ cancelled = true;
185
+ };
186
+ }, [file]);
187
+
188
+ const preview = useMemo(() => {
189
+ if (!csvText) return null;
190
+ const lines = csvText
191
+ .split(/\r?\n/)
192
+ .map((l) => l.trimEnd())
193
+ .filter((l) => l.length > 0)
194
+ .slice(0, 21); // header + 20 rows
195
+ if (lines.length === 0) return null;
196
+ const rows = lines.map(parseCsvLine);
197
+ const header = rows[0] || [];
198
+ const body = rows.slice(1);
199
+ return { header, body };
200
+ }, [csvText]);
201
+
202
+ if (!file) return null;
203
+
204
+ const isCsv = looksLikeCsv(file);
205
+ const isExcel =
206
+ file.name.toLowerCase().endsWith(".xlsx") ||
207
+ file.name.toLowerCase().endsWith(".xls") ||
208
+ file.type.includes("spreadsheet");
209
+
210
+ return (
211
+ <div className="rounded-xl border border-stroke bg-white p-4 shadow-sm">
212
+ <div className="mb-2 flex items-center justify-between gap-3">
213
+ <div className="text-sm font-semibold text-ink">PO preview</div>
214
+ <div className="truncate text-xs text-muted">{file.name}</div>
215
+ </div>
216
+
217
+ <AnimatePresence>
218
+ {csvErr && (
219
+ <motion.div
220
+ initial={{ opacity: 0, y: 6 }}
221
+ animate={{ opacity: 1, y: 0 }}
222
+ exit={{ opacity: 0, y: 6 }}
223
+ className="rounded-lg border border-rose-600/20 bg-rose-500/10 p-3 text-sm text-rose-700"
224
+ >
225
+ {csvErr}
226
+ </motion.div>
227
+ )}
228
+ </AnimatePresence>
229
+
230
+ {!isCsv && isExcel && (
231
+ <div className="rounded-lg border border-stroke bg-bg p-3 text-sm text-muted">
232
+ Excel preview isn’t enabled yet. If you want, I can add Excel preview support (it requires adding an `xlsx` dependency).
233
+ </div>
234
+ )}
235
+
236
+ {!isCsv && !isExcel && (
237
+ <div className="rounded-lg border border-stroke bg-bg p-3 text-sm text-muted">Preview not available for this file type.</div>
238
+ )}
239
+
240
+ {isCsv && !preview && !csvErr && (
241
+ <div className="rounded-lg border border-stroke bg-bg p-3 text-sm text-muted">Loading CSV preview…</div>
242
+ )}
243
+
244
+ {isCsv && preview && (
245
+ <div className="overflow-auto rounded-lg border border-stroke">
246
+ <table className="min-w-full text-left text-xs text-ink/80">
247
+ <thead className="sticky top-0 bg-white text-[11px] uppercase text-muted">
248
+ <tr>
249
+ {preview.header.map((h, i) => (
250
+ <th key={i} className="whitespace-nowrap border-b border-stroke px-3 py-2">
251
+ {h || `col_${i + 1}`}
252
+ </th>
253
+ ))}
254
+ </tr>
255
+ </thead>
256
+ <tbody>
257
+ {preview.body.map((row, rIdx) => (
258
+ <tr key={rIdx} className="border-t border-stroke">
259
+ {preview.header.map((_, cIdx) => (
260
+ <td key={cIdx} className="whitespace-nowrap px-3 py-2">
261
+ {row[cIdx] ?? ""}
262
+ </td>
263
+ ))}
264
+ </tr>
265
+ ))}
266
+ </tbody>
267
+ </table>
268
+ </div>
269
+ )}
270
+ </div>
271
+ );
272
+ }
273
+
274
+
frontend/src/components/LogoMark.tsx ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+
3
+ export function LogoMark({ size = 28 }: { size?: number }) {
4
+ return (
5
+ <motion.svg
6
+ width={size}
7
+ height={size}
8
+ viewBox="0 0 48 48"
9
+ fill="none"
10
+ xmlns="http://www.w3.org/2000/svg"
11
+ aria-hidden="true"
12
+ >
13
+ <defs>
14
+ <linearGradient id="g1" x1="8" y1="8" x2="40" y2="40" gradientUnits="userSpaceOnUse">
15
+ <stop stopColor="#4F46E5" />
16
+ <stop offset="1" stopColor="#10B981" />
17
+ </linearGradient>
18
+ </defs>
19
+
20
+ <motion.circle
21
+ cx="24"
22
+ cy="24"
23
+ r="18"
24
+ stroke="url(#g1)"
25
+ strokeWidth="3"
26
+ animate={{ rotate: 360 }}
27
+ transform-origin="24px 24px"
28
+ transition={{ repeat: Infinity, duration: 9, ease: "linear" }}
29
+ opacity="0.9"
30
+ />
31
+
32
+ <motion.path
33
+ d="M16 25.5c5.5-7.5 10.5-7.5 16 0"
34
+ stroke="url(#g1)"
35
+ strokeWidth="3"
36
+ strokeLinecap="round"
37
+ strokeLinejoin="round"
38
+ initial={{ pathLength: 0.1, opacity: 0.6 }}
39
+ animate={{ pathLength: [0.2, 1, 0.2], opacity: [0.6, 1, 0.6] }}
40
+ transition={{ repeat: Infinity, duration: 2.6, ease: "easeInOut" }}
41
+ />
42
+
43
+ <motion.circle
44
+ cx="24"
45
+ cy="24"
46
+ r="7"
47
+ fill="url(#g1)"
48
+ initial={{ scale: 0.95 }}
49
+ animate={{ scale: [0.95, 1.05, 0.95] }}
50
+ transition={{ repeat: Infinity, duration: 2.4, ease: "easeInOut" }}
51
+ opacity="0.95"
52
+ />
53
+ </motion.svg>
54
+ );
55
+ }
56
+
57
+
frontend/src/components/MultiFileDrop.tsx ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useRef } from "react";
2
+ import { motion } from "framer-motion";
3
+
4
+ function uniqKey(f: File) {
5
+ return `${f.name}::${f.size}::${f.lastModified}`;
6
+ }
7
+
8
+ export function MultiFileDrop({
9
+ label,
10
+ accept,
11
+ files,
12
+ onChange,
13
+ hint
14
+ }: {
15
+ label: string;
16
+ accept: string;
17
+ files: File[];
18
+ onChange: (nextFiles: File[]) => void;
19
+ hint?: string;
20
+ }) {
21
+ const inputRef = useRef<HTMLInputElement | null>(null);
22
+
23
+ const addFiles = useCallback(
24
+ (incoming: File[]) => {
25
+ if (!incoming.length) return;
26
+ const seen = new Set(files.map(uniqKey));
27
+ const merged = [...files];
28
+ for (const f of incoming) {
29
+ const k = uniqKey(f);
30
+ if (seen.has(k)) continue;
31
+ seen.add(k);
32
+ merged.push(f);
33
+ }
34
+ onChange(merged);
35
+ },
36
+ [files, onChange]
37
+ );
38
+
39
+ const onDrop = useCallback(
40
+ (e: React.DragEvent) => {
41
+ e.preventDefault();
42
+ const incoming = Array.from(e.dataTransfer.files || []);
43
+ addFiles(incoming);
44
+ },
45
+ [addFiles]
46
+ );
47
+
48
+ const removeAt = (idx: number) => {
49
+ const next = files.filter((_, i) => i !== idx);
50
+ onChange(next);
51
+ };
52
+
53
+ return (
54
+ <motion.div
55
+ whileHover={{ y: -1 }}
56
+ className="rounded-xl border border-stroke bg-white p-4"
57
+ onDragOver={(e) => e.preventDefault()}
58
+ onDrop={onDrop}
59
+ >
60
+ <div className="flex items-start justify-between gap-3">
61
+ <div>
62
+ <div className="text-sm font-semibold text-ink">{label}</div>
63
+ <div className="mt-1 text-xs text-muted">{hint || "Drag & drop or browse"}</div>
64
+ <div className="mt-1 text-[11px] text-muted">Accepted: {accept.replace(/\./g, "").toUpperCase()}</div>
65
+ </div>
66
+ {files.length > 0 ? (
67
+ <div className="shrink-0 rounded-full border border-emerald-600/25 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-700">
68
+ ✓ Added {files.length}
69
+ </div>
70
+ ) : null}
71
+ </div>
72
+
73
+ <div className="mt-3 flex items-center justify-between gap-3">
74
+ <div className="min-w-0 text-sm text-muted">{files.length ? "Selected invoices:" : "No file selected"}</div>
75
+ <button
76
+ type="button"
77
+ onClick={() => inputRef.current?.click()}
78
+ className="rounded-lg border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink hover:bg-bg"
79
+ >
80
+ Browse
81
+ </button>
82
+ <input
83
+ ref={inputRef}
84
+ type="file"
85
+ accept={accept}
86
+ multiple
87
+ className="hidden"
88
+ onChange={(e) => {
89
+ const incoming = Array.from(e.target.files || []);
90
+ addFiles(incoming);
91
+ e.currentTarget.value = "";
92
+ }}
93
+ />
94
+ </div>
95
+
96
+ {files.length > 0 && (
97
+ <div className="mt-3 space-y-2">
98
+ {files.map((f, idx) => (
99
+ <div key={uniqKey(f)} className="flex items-center justify-between gap-3 rounded-lg border border-stroke bg-bg px-3 py-2">
100
+ <div className="min-w-0 flex-1">
101
+ <div className="truncate text-sm text-ink/80">{f.name}</div>
102
+ </div>
103
+ <button
104
+ type="button"
105
+ onClick={() => removeAt(idx)}
106
+ className="rounded-lg border border-stroke bg-white px-2.5 py-1.5 text-xs font-semibold text-ink hover:bg-white/70"
107
+ >
108
+ Remove
109
+ </button>
110
+ </div>
111
+ ))}
112
+ <div className="text-[11px] text-muted">Tip: you can preview invoices using the &lt; / &gt; buttons in the next step.</div>
113
+ </div>
114
+ )}
115
+ </motion.div>
116
+ );
117
+ }
118
+
119
+
frontend/src/components/ShareButton.tsx ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+
3
+ async function copyToClipboard(text: string) {
4
+ if (navigator.clipboard?.writeText) {
5
+ await navigator.clipboard.writeText(text);
6
+ return;
7
+ }
8
+ // Fallback for older browsers
9
+ const ta = document.createElement("textarea");
10
+ ta.value = text;
11
+ ta.setAttribute("readonly", "true");
12
+ ta.style.position = "fixed";
13
+ ta.style.left = "-9999px";
14
+ document.body.appendChild(ta);
15
+ ta.select();
16
+ document.execCommand("copy");
17
+ document.body.removeChild(ta);
18
+ }
19
+
20
+ export function ShareButton({
21
+ title,
22
+ text,
23
+ url,
24
+ onToast
25
+ }: {
26
+ title: string;
27
+ text: string;
28
+ url: string;
29
+ onToast?: (msg: string) => void;
30
+ }) {
31
+ return (
32
+ <motion.button
33
+ whileHover={{ y: -1 }}
34
+ whileTap={{ scale: 0.98 }}
35
+ type="button"
36
+ className="inline-flex items-center gap-2 rounded-xl border border-stroke bg-white px-3 py-2 text-xs font-semibold text-ink shadow-soft hover:bg-bg"
37
+ onClick={async () => {
38
+ try {
39
+ // Prefer native share sheet when available
40
+ const navAny: any = navigator as any;
41
+ if (typeof navAny.share === "function") {
42
+ await navAny.share({ title, text, url });
43
+ onToast?.("Shared");
44
+ return;
45
+ }
46
+ await copyToClipboard(url);
47
+ onToast?.("Link copied");
48
+ } catch (e: any) {
49
+ // User can cancel share sheet; don't show error for AbortError.
50
+ if (e?.name === "AbortError") return;
51
+ onToast?.("Could not share");
52
+ }
53
+ }}
54
+ aria-label="Share"
55
+ title="Share"
56
+ >
57
+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
58
+ <path
59
+ d="M12.5 6.5a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM5.5 12a2 2 0 1 0 0-4 2 2 0 0 0 0 4Zm7 5.5a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z"
60
+ fill="currentColor"
61
+ opacity="0.9"
62
+ />
63
+ <path
64
+ d="M7.2 9.2l3.6-2.0M7.2 10.8l3.6 2.0"
65
+ stroke="currentColor"
66
+ strokeWidth="1.6"
67
+ strokeLinecap="round"
68
+ opacity="0.9"
69
+ />
70
+ </svg>
71
+ <span className="hidden sm:inline">Share</span>
72
+ </motion.button>
73
+ );
74
+ }
75
+
76
+
frontend/src/components/StepBar.tsx ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { motion } from "framer-motion";
2
+
3
+ export type StepState = "todo" | "active" | "done";
4
+
5
+ type Step = {
6
+ key: string;
7
+ label: string;
8
+ state: StepState;
9
+ };
10
+
11
+ function tone(state: StepState) {
12
+ if (state === "done") return "bg-emerald-500 text-white border-emerald-500";
13
+ if (state === "active") return "bg-brand text-white border-brand";
14
+ return "bg-white text-muted border-stroke";
15
+ }
16
+
17
+ function lineTone(state: StepState) {
18
+ if (state === "done") return "bg-emerald-500";
19
+ if (state === "active") return "bg-brand";
20
+ return "bg-stroke";
21
+ }
22
+
23
+ function icon(state: StepState) {
24
+ if (state === "done") return "✓";
25
+ if (state === "active") return "•";
26
+ return "";
27
+ }
28
+
29
+ export function StepBar({ steps }: { steps: Step[] }) {
30
+ return (
31
+ <div className="rounded-2xl border border-stroke bg-white p-4 shadow-soft">
32
+ <div className="flex items-center justify-between gap-3">
33
+ {steps.map((s, idx) => {
34
+ const isLast = idx === steps.length - 1;
35
+ return (
36
+ <div key={s.key} className={`flex min-w-0 flex-1 items-center ${isLast ? "" : "gap-3"}`}>
37
+ <div className="flex min-w-0 items-center gap-3">
38
+ <motion.div
39
+ className={`flex h-9 w-9 items-center justify-center rounded-full border text-sm font-bold ${tone(s.state)}`}
40
+ animate={
41
+ s.state === "active"
42
+ ? { scale: [1, 1.08, 1] }
43
+ : { scale: 1 }
44
+ }
45
+ transition={s.state === "active" ? { repeat: Infinity, duration: 1.3, ease: "easeInOut" } : { duration: 0.2 }}
46
+ >
47
+ {icon(s.state)}
48
+ </motion.div>
49
+ <div className="min-w-0">
50
+ <div className="truncate text-sm font-semibold text-ink">{s.label}</div>
51
+ <div className="text-[11px] text-muted">
52
+ {s.state === "done" ? "Done" : s.state === "active" ? "In progress" : "Pending"}
53
+ </div>
54
+ </div>
55
+ </div>
56
+
57
+ {!isLast && (
58
+ <div className="mx-2 flex-1">
59
+ <div className="h-1 w-full rounded-full bg-stroke">
60
+ <motion.div
61
+ className={`h-1 rounded-full ${lineTone(s.state)}`}
62
+ initial={false}
63
+ animate={{ width: s.state === "todo" ? "0%" : "100%" }}
64
+ transition={{ duration: 0.6, ease: "easeInOut" }}
65
+ />
66
+ </div>
67
+ </div>
68
+ )}
69
+ </div>
70
+ );
71
+ })}
72
+ </div>
73
+ </div>
74
+ );
75
+ }
76
+
77
+
frontend/src/main.tsx ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from "react";
2
+ import ReactDOM from "react-dom/client";
3
+ import App from "./App";
4
+ import "./styles.css";
5
+
6
+ ReactDOM.createRoot(document.getElementById("root")!).render(
7
+ <React.StrictMode>
8
+ <App />
9
+ </React.StrictMode>
10
+ );
11
+
12
+
frontend/src/styles.css ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ :root {
6
+ color-scheme: light;
7
+ }
8
+
9
+ html, body {
10
+ height: 100%;
11
+ background: #F6F7FB;
12
+ }
13
+
14
+ /* clean background */
15
+ .bg-clean {
16
+ background:
17
+ radial-gradient(900px 500px at 15% 0%, rgba(79, 70, 229, 0.10), transparent 60%),
18
+ radial-gradient(700px 450px at 85% 0%, rgba(16, 185, 129, 0.08), transparent 60%),
19
+ linear-gradient(#F6F7FB, #F6F7FB);
20
+ }
21
+
22
+ /* aurora blobs (subtle, modern) */
23
+ @keyframes floaty {
24
+ 0% { transform: translate3d(0, 0, 0) scale(1); opacity: 0.65; }
25
+ 50% { transform: translate3d(18px, -14px, 0) scale(1.06); opacity: 0.8; }
26
+ 100% { transform: translate3d(-10px, 10px, 0) scale(1.02); opacity: 0.7; }
27
+ }
28
+
29
+ .aurora {
30
+ position: absolute;
31
+ inset: 0;
32
+ pointer-events: none;
33
+ overflow: hidden;
34
+ }
35
+
36
+ .aurora-blob {
37
+ position: absolute;
38
+ filter: blur(30px);
39
+ border-radius: 9999px;
40
+ mix-blend-mode: multiply;
41
+ animation: floaty 12s ease-in-out infinite;
42
+ }
43
+
44
+ .aurora-blob.b1 {
45
+ width: 520px;
46
+ height: 520px;
47
+ left: -160px;
48
+ top: -180px;
49
+ background: rgba(79, 70, 229, 0.14);
50
+ animation-duration: 14s;
51
+ }
52
+
53
+ .aurora-blob.b2 {
54
+ width: 440px;
55
+ height: 440px;
56
+ right: -160px;
57
+ top: -140px;
58
+ background: rgba(16, 185, 129, 0.12);
59
+ animation-duration: 16s;
60
+ }
61
+
62
+ .aurora-blob.b3 {
63
+ width: 520px;
64
+ height: 520px;
65
+ left: 25%;
66
+ bottom: -220px;
67
+ background: rgba(99, 102, 241, 0.10);
68
+ animation-duration: 18s;
69
+ }
70
+
71
+ /* nicer scrollbars */
72
+ *::-webkit-scrollbar { height: 10px; width: 10px; }
73
+ *::-webkit-scrollbar-thumb { background: rgba(15,23,42,.15); border-radius: 999px; }
74
+ *::-webkit-scrollbar-track { background: transparent; }
75
+
76
+ /* (intentionally left open for future UI utilities) */
77
+