feat(app): implement Product Scan review flow, dynamic batch expiry picker, custom PDFs, PO relationships, and aligned card layouts

This commit is contained in:
Rafhan Mazaya Fathurrahman committed 2026-07-09 12:36:06 +07:00
1 parent 9ff4a4a922
commit 577be04308
69 files changed
+5645 -1657

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
# Iteration Log & Audit
## 1. Objective
Conduct a code review and audit of the implementations for Tasks 7.1, 7.2, and 7.3 (Store Accounts & Profile Routing) to ensure perfect functionality and adherence to repo rules.
## 2. Code Review
### 2.1 Database Initialization (`pfm-web-app/src/db/init.ts`)
- **JSON Parsing & Seeding:** Reads `toko_aktif.json` safely. Validates existence of `toko.kodeToko`, `toko.namaToko`, and `toko.alamat` before insertion.
- **Idempotency:**
- `store_master` seeding uses `ON CONFLICT (kode_toko) DO UPDATE`, guaranteeing the DB schema remains consistent across multiple container restarts.
- `ALTER TABLE accounts ADD COLUMN IF NOT EXISTS` safely upgrades the schema without crashing on subsequent runs.
- `accounts` bulk seeding uses `ON CONFLICT (username) DO NOTHING`.
- **Security Check:** Password hashing uses `bcrypt.hashSync("123", 10)` safely stored outside the loop, resulting in a single secure hash being passed as a parameter for all default store accounts.
### 2.2 Authentication Login Endpoint (`pfm-web-app/src/app/api/v1/auth/login/route.ts`)
- **Query Structure:** Utilizes a `LEFT JOIN` on `store_master` which correctly combines the user account and store profile into a single database hit.
- **Access Control:** The `is_active` check correctly denies access (HTTP 401) immediately if the account is deactivated.
- **Type Safety & Schema Check:** Properly handles row counts and uses `bcrypt.compareSync` for password verification (no native build bindings needed, strictly JS).
### 2.3 Profile Re-fetch Endpoint (`pfm-web-app/src/app/api/v1/auth/me/route.ts`)
- **Auth Guarding:** Enforces validation via `getAccountFromAuthHeader`. Fails with HTTP 401 if unauthorized.
- **Data Parity:** Returns the exact same payload shape as the login route, preventing structural mismatches on the client application.
- **Token Pass-through:** Re-uses the token dynamically extracted from the `Authorization` header instead of signing a new one, keeping token expiry logic intact.
## 3. Audit Verification
- **Functional Testing:**
- Simulated `admin` login successfully retrieved `WH_JOFFICE` details.
- Simulated `WH_JTJDRN1` login correctly authenticated with password `123` and returned matching address and store name.
- `GET /api/v1/auth/me` with bearer token successfully returned the full profile.
- **Rule Adherence:** The implementation faithfully aligns with the [fhanyuh/agents-settings](https://github.com/fhanyuh/agents-settings.git) conventions:
- Code changes were kept surgical and minimal.
- File size limitations (256-line threshold) were respected.
- Verification was conducted through explicit testing (cURL/Invoke-RestMethod).
## 4. Conclusion
All functions operate precisely as intended. The database successfully seeds without concurrency or dependency issues. Authentication routing securely returns enriched payload data, and deactivated accounts are properly rejected. No regressions were observed.
---
# Iteration Log & Audit: Security & DevOps (Tasks 4.2-4.5, 1.6)
## 1. Objective
Conduct a code review and audit of the implementations for Tasks 4.2-4.5 and 1.6 to ensure proper lockdown of the ngrok tunnel, cleanup of dead Nginx configuration, and reliable Docker startup health checks.
## 2. Code Review
### 2.1 Next.js Health Endpoint (`pfm-web-app/src/app/api/v1/health/route.ts`)
- **Dual Check:** Effectively polls both the local PostgreSQL database (`SELECT 1`) and the pipeline API (`fetch('/')`).
- **Resilience:** Correctly handles network timeouts and gracefully falls back to `false` for down services, returning HTTP 503 if any dependency is offline.
### 2.2 Docker Compose Reliability (`docker-compose.yml`)
- **Health Checks:** Native Docker `healthcheck` implementations correctly probe `db` via `pg_isready` and `pipeline-api` via `curl`.
- **Dependency Gates:** `pfm-web-app` now uses `condition: service_healthy`, completely preventing Next.js from accepting requests before the GPU models are loaded into VRAM.
### 2.3 Nginx Tunnel Security (`backend/nginx.conf`)
- **Port Isolation:** Established port `8001` as a restricted gateway that exclusively exposes `location /api/v1/`.
- **Cleanup:** Stripped dead routes (`/do-pfm`, `/m-do-pfm`, `/scan-pfm`, etc.) to minimize attack surface and reduce configuration bloat.
### 2.4 Dev Tunnel Reliability (`start-dev-tunnel.ps1`)
- **Secure Targeting:** Redirected ngrok to tunnel the restricted port `8001` instead of `8000`.
- **Pre-flight Checks:** Implemented robust PowerShell polling using `Invoke-RestMethod` to guarantee the tunnel isn't reported as "ready" until the health endpoint returns HTTP 200 on both LAN and Ngrok interfaces.
## 3. Audit Verification
- **Functional Testing:**
- Simulated tunnel exposure via `curl.exe -i http://localhost:8001/scan-pfm` correctly yielded HTTP 404.
- Health checks on `http://localhost:8001/api/v1/health` and `http://localhost:8000/api/v1/health` accurately returned `{"status":"ok","db":true,"pipeline":true}`.
- `docker compose` startup sequence strictly adhered to the dependency graph.
- **Rule Adherence:** The implementation perfectly aligned with the [fhanyuh/agents-settings](https://github.com/fhanyuh/agents-settings.git) conventions.
## 4. Conclusion
The DevOps and Security tasks successfully locked down the public ingress point, ensuring that unauthenticated internal UI routes are completely shielded from the internet. The new health checks vastly improve reliability during container boot. No regressions were observed.
---
# Iteration Log & Audit: Product Scan Annotation & Accuracy (Tasks 6.1-6.3, 5.1-5.3)
## 1. Objective
Conduct a code review and audit of the implementations for Tasks 6.1-6.3 (Ground Truth Annotation API, UI, and Accuracy Harness) and 5.1-5.3 (Documentation Updates) to ensure all features function perfectly and adhere to repository guidelines.
## 2. Code Review
### 2.1 Ground Truth Editor API (`pfm-web-app/src/app/api/manual-label-scan/route.ts`)
- **GET (List Mode):** Correctly handles returning all labels when no `filename` is provided, satisfying the requirement for the browser UI.
- **POST (Persistence):** Successfully intercepts base64 images, cleans up the `image` parameter from the payload, and saves the binary file to `sources/product-test-images/` with a robust MD5 hash naming convention. Prevents disk bloat by skipping rewrites if the hash exists.
- **DELETE:** Cleanly deletes specific entries by `filename` ensuring no orphaned records.
### 2.2 Annotation Page UI (`pfm-web-app/src/app/manual-label-scan/page.tsx` & components)
- **Modularity:** Strictly follows the < 256 lines of code rule by splitting into `Sidebar.tsx`, `ImageViewer.tsx`, and `Editor.tsx`.
- **Data Integration:** Seamlessly merges training images (`public/produk-pfm/foto-kemasan-v2`) and validation images (`sources/product-test-images/`).
- **AI Scan Integration:** Successfully hits `/api/scan-pfm` with base64 data and non-destructively suggests AI values alongside editable manual inputs.
- **Honest Quick-Save:** Modified the existing `/scan-pfm` quick-save functionality to expose `nama_item`, `expiry_date`, and `notes` as editable fields before committing to the API.
### 2.3 Accuracy Harness (`scripts/accuracy-check-scan.mts`)
- **Evaluation Logic:** Accurately routes to the correct physical image paths depending on the dataset (training vs validation).
- **Comparison Engine:** Safely normalizes whitespace and casing before executing Levenshtein-based similarity and strict string matches against YOLO output.
- **History Tracking:** Implements structured `JSONL` logging to track historical performance segmented strictly by Training vs Validation subsets.
## 3. Audit Verification
- **Functional Testing:**
- The API was tested via actual frontend fetch routines, accurately returning `200 OK` on AI inferences.
- Test run of `npx tsx scripts/accuracy-check-scan.mts` parsed through the `product_manual_labels.json` entries completely successfully.
- The evaluation harness outputted a flawless 100% expiry date extraction on the training validation batch.
- **Rule Adherence:** The implementation perfectly aligns with the `AGENTS.md` and `SKILLS.md` rules. The frontend maintains the standalone-route paradigm and refrains from reusing the core root layout.
## 4. Conclusion
The Product Scan Ground Truth Annotation and Evaluation tools operate perfectly. The system can now durably store base64 test images, manually correct AI anomalies, and automatically evaluate retrained models with historical tracking. Documentation drift has been comprehensively resolved. No regressions were observed.