diff --git a/.dockerignore b/.dockerignore index 2b625989318377914ed464f16c0b5d6c355f5ced..5ea5f6ab099236a216aca06a93dee0ff2fb2462c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,12 +1,19 @@ -node_modules .git -.gitignore -.env -.idea -.DS_Store - -uploads -extracted - -npm-debug.log -pnpm-debug.log +.github +**/node_modules +**/dist +**/.next +**/.open-next +**/.env* +!**/.env.example +**/*.tsbuildinfo +passport-check/.backup +passport-check/.playwright-mcp +passport-check/low +passport-check/samples +passport-check/*.xlsx +passport-check/*.docx +passport-check/tessdata/*.traineddata.gz +!passport-check/tessdata/mrz.traineddata.gz +extractor/uploads +extractor/extracted diff --git a/.env.example b/.env.example index 3d8f675a3378a8ffe289065d02ee35a25b6d2c9f..2154d1f2cb727a6685202e24e3ac0576369786dc 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,61 @@ -# Server Configuration -PORT=3000 +# ===================================================================== +# BACKEND (Hugging Face Space) — đặt trong Settings → Variables and secrets +# ===================================================================== -# File Size Limits (in bytes) -MAX_FILE_SIZE=104857600 -MAX_EXTRACTED_FILE_SIZE=52428800 +# ---------- Bảo mật (bắt buộc) +# Khoá chung giữa Next.js và backend; chỉ server Next.js biết. Tạo: openssl rand -base64 48 +BACKEND_API_KEY= +# Khoá ký token phiên đăng nhập. Tạo: openssl rand -base64 48 (đổi khoá = đăng xuất mọi người) +AUTH_SECRET= +# số ngày phiên đăng nhập còn hiệu lực +AUTH_TOKEN_DAYS=7 -# Session Configuration (in milliseconds) -SESSION_TIMEOUT=3600000 +# ---------- Admin đầu tiên (chỉ dùng khi bảng users còn trống) +ADMIN_EMAIL= +# để trống nếu admin chỉ đăng nhập Google; nếu đặt thì >= 8 ký tự +ADMIN_PASSWORD= +# (tuỳ chọn) email đăng nhập Google lần đầu được tự thêm vào bảng users, cách nhau dấu phẩy; "@congty.vn" = cả tên miền +ALLOWED_EMAILS= -# Rate Limiting -RATE_LIMIT_WINDOW=3600000 -RATE_LIMIT_MAX=10 +# ---------- Firebase (bắt buộc) — Firestore + xác minh đăng nhập Google +# Service account: Firebase Console → Project settings → Service accounts → Generate new private key. +# Dán nguyên JSON (hoặc base64 của JSON) vào secret này. +FIREBASE_SERVICE_ACCOUNT= + +# ---------- Telegram (bắt buộc) — nơi lưu ảnh gốc +TELEGRAM_BOT_TOKEN= +TELEGRAM_CHAT_ID= + +# ---------- Gemini (tuỳ chọn) +GEMINI_API_KEY= +GEMINI_MODEL= +# (tuỳ chọn) luật tính token ảnh (theo kích thước, không gọi API): tile (258/ô, không chặn trần) | low | medium | high | ultra_high (258/ô, chặn trần 280/560/1120/2240) | số token cố định/ảnh +# để trống = tự chọn theo GEMINI_MODEL (gemini-2.x -> tile, còn lại -> tile chặn trần 1120) +GEMINI_IMAGE_TOKENS= +# (tuỳ chọn) đơn giá mặc định cho trang chi phí, USD / 1 triệu token (mặc định 0.25 / 1.5 — Gemini 3.1 Flash-Lite trả phí, tier Standard) +GEMINI_PRICE_INPUT= +GEMINI_PRICE_OUTPUT= + +# ---------- Tuỳ chỉnh (không bắt buộc) +OCR_CONCURRENCY=1 +LLM_CONCURRENCY=2 +OCR_WORKERS=2 +MAX_IMAGE_MB=40 +MAX_ZIP_MB=1024 +MAX_ZIP_ENTRIES=5000 +IMAGE_CACHE_MB=500 +TELEGRAM_MIN_INTERVAL_MS=1100 +RATE_LIMIT=600 + +# ===================================================================== +# FRONTEND (Next.js) — biến môi trường phía server, không gửi cho trình duyệt +# ===================================================================== +# URL Space backend, vd https://ten-ban-passport-check.hf.space +BACKEND_URL=http://localhost:7860 +# giống hệt BACKEND_API_KEY ở trên +# BACKEND_API_KEY= +# Cấu hình Firebase web app (công khai) cho nút Google: +# Project settings → General → Your apps → Web app → SDK setup (Config) +FIREBASE_WEB_CONFIG= +# cookie Secure: mặc định bật khi NODE_ENV=production +# COOKIE_SECURE=true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..ddd581d8e9694651fc22099b0b5088e1b2e8586e --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +passport-check/tessdata/mrz.traineddata.gz filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index f86ccf3588091b79f9dededa3c922fd5fa37e9e1..50459d8fc9cdbad22ee7dae213e4348f88e34030 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,35 @@ -# Dependencies -node_modules/ +node_modules +dist +.next +.open-next +*.tsbuildinfo +.env* +!.env.example +extractor/uploads/ +extractor/extracted/ -# Environment files -.env +# secret triển khai (token HF/Cloudflare, API key) — KHÔNG commit +deploy.txt +*.pem +*.key +.dev.vars +.wrangler/ -# Upload and extraction directories -uploads/ -extracted/ +# dữ liệu / file cục bộ trong thư mục app +passport-check/.backup/ +passport-check/.playwright-mcp/ +passport-check/low/ +passport-check/samples/ +passport-check/FEATURES.docx +passport-check/tessdata/*.traineddata.gz +!passport-check/tessdata/mrz.traineddata.gz -# OS files +# log, cache, coverage, file hệ thống/IDE +*.log +coverage/ +.turbo/ +.cache/ .DS_Store Thumbs.db - -# IDE -.vscode/ .idea/ - -# Logs -*.log -npm-debug.log* +.vscode/ diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000000000000000000000000000000000000..23ceb05e6fb63c1b41023ed15fb4185cdebffeb1 --- /dev/null +++ b/Caddyfile @@ -0,0 +1,32 @@ +# Cổng duy nhất HF mở ra (7860). Chia traffic theo tiền tố; các app chỉ nghe ở 127.0.0.1. +{ + admin off + auto_https off + persist_config off +} + +:7860 { + request_body { + max_size 1100MB + } + + redir /extractor /extractor/ 308 + + # Extractor: bỏ tiền tố /extractor trước khi chuyển vào app + handle_path /extractor/* { + reverse_proxy 127.0.0.1:3001 + } + + # Backend Passport Check (chỉ Cloudflare Worker gọi tới, kèm x-api-key): bỏ tiền tố /passport-check + handle_path /passport-check/* { + reverse_proxy 127.0.0.1:8080 { + flush_interval -1 + } + } + + redir / /extractor/ 302 + + handle { + respond "Không tìm thấy" 404 + } +} diff --git a/Dockerfile b/Dockerfile index cfff98c25d061ba1a59f667daca6f025a822a3f9..6d51be7efaad815a6a1952079adf6a0484af99e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,57 @@ -FROM node:20-slim - +# Space gộp nhiều app trong 1 container, Caddy ở cổng 7860 chia traffic: +# /passport-check/* -> backend Express của Passport Check (passport-check/apps/server, 127.0.0.1:8080) +# /extractor/* -> Archive Extractor (extractor/, 127.0.0.1:3001) +# / -> chuyển sang /extractor/ +# Frontend Passport Check (Next.js) KHÔNG nằm ở đây — deploy riêng lên Cloudflare Worker (xem .github/workflows/deploy-cloudflare.yml) + +# ---------- Build Passport Check (chỉ backend) +FROM node:22-slim AS build-passport WORKDIR /app - -ENV NODE_ENV=production -ENV HOST=0.0.0.0 -ENV PORT=7860 -ENV SESSION_TIMEOUT=3600000 -ENV MAX_FILE_SIZE=104857600 -ENV MAX_EXTRACTED_FILE_SIZE=52428800 -ENV RATE_LIMIT_WINDOW=3600000 -ENV RATE_LIMIT_MAX=10 - -COPY package.json ./ -COPY pnpm-lock.yaml ./ - -RUN corepack enable && corepack prepare pnpm@10.33.4 --activate \ - && pnpm install --frozen-lockfile - -COPY . . - -RUN mkdir -p uploads extracted - +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* +COPY passport-check/package.json passport-check/package-lock.json ./ +COPY passport-check/packages/core/package.json packages/core/ +COPY passport-check/apps/server/package.json apps/server/ +COPY passport-check/apps/web/package.json apps/web/ +RUN npm ci --workspace apps/server --include-workspace-root +COPY passport-check/packages packages +COPY passport-check/apps/server apps/server +COPY passport-check/scripts scripts +COPY passport-check/tessdata tessdata +COPY passport-check/tsconfig.base.json ./ +ENV NEXT_TELEMETRY_DISABLED=1 +RUN npm run tessdata \ + && npm -w apps/server run build \ + && npm prune --omit=dev --workspace apps/server --include-workspace-root + +# ---------- Build Archive Extractor +FROM node:22-slim AS build-extractor +WORKDIR /app/extractor +COPY extractor/package.json extractor/pnpm-lock.yaml ./ +RUN corepack enable && corepack prepare pnpm@10.33.4 --activate && pnpm install --frozen-lockfile --prod +COPY extractor/ ./ + +# ---------- Chạy +FROM node:22-slim +ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 \ + TEMPLATE_DIR=/app/passport-server/apps/server/templates TESSDATA_DIR=/app/passport-server/tessdata \ + SESSION_TIMEOUT=3600000 MAX_FILE_SIZE=104857600 MAX_EXTRACTED_FILE_SIZE=52428800 RATE_LIMIT_WINDOW=3600000 RATE_LIMIT_MAX=10 \ + XDG_DATA_HOME=/tmp/caddy-data XDG_CONFIG_HOME=/tmp/caddy-config +WORKDIR /app +COPY --from=caddy:2 /usr/bin/caddy /usr/local/bin/caddy + +# backend +COPY --from=build-passport --chown=node:node /app/node_modules /app/passport-server/node_modules +COPY --from=build-passport --chown=node:node /app/apps/server/dist /app/passport-server/apps/server/dist +COPY --from=build-passport --chown=node:node /app/apps/server/templates /app/passport-server/apps/server/templates +COPY --from=build-passport --chown=node:node /app/tessdata /app/passport-server/tessdata +COPY --from=build-passport --chown=node:node /app/package.json /app/passport-server/ +# extractor +COPY --from=build-extractor --chown=node:node /app/extractor /app/extractor +RUN mkdir -p /app/extractor/uploads /app/extractor/extracted && chown node:node /app/extractor/uploads /app/extractor/extracted + +COPY --chown=node:node Caddyfile start.sh /app/ + +# HF Spaces chạy với uid 1000 (= user node) +USER node EXPOSE 7860 - -CMD ["pnpm", "start"] +CMD ["/app/start.sh"] diff --git a/README.md b/README.md index 814b428d7492d978cf78141f1a787d65ea6bc643..bef9ba644b4663f20c860216d3bd86a2d3f7651c 100644 --- a/README.md +++ b/README.md @@ -9,194 +9,38 @@ pinned: false license: mit --- -# Archive Extractor -A production-ready web application for uploading, extracting, and managing compressed file archives (ZIP and RAR). Features a modern dark-themed UI with drag-and-drop upload, tree view file explorer, and secure file handling. +# Space: backend Passport Check + Archive Extractor -![Node.js](https://img.shields.io/badge/Node.js-18%2B-green) -![Express.js](https://img.shields.io/badge/Express.js-4.x-blue) -![License](https://img.shields.io/badge/License-MIT-yellow) +Một container, Caddy chia traffic ở cổng 7860: -## Features +| Đường dẫn | App | Nội bộ | +|---|---|---| +| `/passport-check/` | Backend Express của Passport Check (chỉ Cloudflare Worker gọi, cần `x-api-key`) | `127.0.0.1:8080` | +| `/extractor/` | Archive Extractor | `127.0.0.1:3001` | +| `/` | chuyển sang `/extractor/` | | -- 📦 **Multi-format Support**: Extract ZIP and RAR archives -- 🔄 **Nested Archive Handling**: Automatically extracts archives within archives -- 🌲 **Interactive File Tree**: Collapsible tree view with file type icons -- ⬇️ **Flexible Downloads**: Download individual files or entire folders as ZIP -- 🎨 **Modern UI**: Dark theme with glassmorphism effects and animations -- 📱 **Responsive Design**: Works on desktop and mobile devices -- 🔒 **Security First**: Path traversal prevention, magic bytes validation, rate limiting +**Frontend** Passport Check (Next.js) chạy riêng trên **Cloudflare Worker** `passport-check-web`, gọi backend qua +`BACKEND_URL=https://.hf.space/passport-check` + `BACKEND_API_KEY`. -## Prerequisites +## Cấu trúc repo -- Node.js v18 or higher -- npm or yarn - -## Installation - -1. **Clone or download the project** - -2. **Install dependencies** - ```bash - npm install - ``` - -3. **Configure environment** (optional) - ```bash - cp .env.example .env - # Edit .env to customize settings - ``` - -4. **Start the server** - ```bash - npm start - ``` - -5. **Open in browser** - ``` - http://localhost:3000 - ``` - -## Development - -Run with auto-reload on file changes: -```bash -npm run dev -``` - -## Configuration - -All settings are configurable via environment variables: - -| Variable | Default | Description | -|----------|---------|-------------| -| `PORT` | 3000 | Server port | -| `MAX_FILE_SIZE` | 104857600 | Max upload size in bytes (100MB) | -| `MAX_EXTRACTED_FILE_SIZE` | 52428800 | Max extracted file size (50MB) | -| `SESSION_TIMEOUT` | 3600000 | Auto-cleanup timeout in ms (1 hour) | -| `RATE_LIMIT_WINDOW` | 3600000 | Rate limit window in ms (1 hour) | -| `RATE_LIMIT_MAX` | 10 | Max uploads per window per IP | - -## API Endpoints - -### Upload Archive -```http -POST /api/upload -Content-Type: multipart/form-data - -file: -``` - -**Response (200)**: -```json -{ - "success": true, - "sessionId": "uuid-v4", - "filename": "archive.zip", - "stats": { - "totalFiles": 42, - "totalSize": 1048576 - } -} ``` - -### Get File Tree -```http -GET /api/files/:sessionId +extractor/ Archive Extractor (lấy từ Space cũ) +passport-check/ Passport Check (apps/web = frontend, apps/server = backend, packages/core) +Dockerfile image cho Space: backend + extractor + Caddy +Caddyfile start.sh +.github/workflows/deploy-hf.yml build thử image rồi đẩy source lên Space +.github/workflows/deploy-cloudflare.yml build + deploy frontend lên Cloudflare Worker ``` -**Response (200)**: -```json -{ - "success": true, - "sessionId": "uuid-v4", - "tree": { - "name": "root", - "type": "folder", - "path": "/", - "children": [...] - } -} -``` - -### Download File -```http -GET /api/download/:sessionId/file?path=/path/to/file.txt -``` - -### Download Folder as ZIP -```http -GET /api/download/:sessionId/folder?path=/path/to/folder -``` - -### Delete Session -```http -DELETE /api/session/:sessionId -``` - -## Error Responses - -All errors return a consistent format: -```json -{ - "error": true, - "message": "Human-readable description", - "code": "ERROR_CODE" -} -``` - -| Code | HTTP Status | Description | -|------|-------------|-------------| -| `INVALID_FILE_TYPE` | 400 | Unsupported file extension | -| `INVALID_MAGIC_BYTES` | 400 | File content doesn't match extension | -| `FILE_TOO_LARGE` | 400 | File exceeds size limit | -| `INVALID_PATH` | 400 | Path contains traversal or is absolute | -| `SESSION_NOT_FOUND` | 404 | Session expired or doesn't exist | -| `FILE_NOT_FOUND` | 404 | Requested file doesn't exist | -| `PASSWORD_PROTECTED` | 422 | Archive requires a password | -| `CORRUPTED_ARCHIVE` | 422 | Archive is damaged | -| `RATE_LIMIT_EXCEEDED` | 429 | Too many requests | -| `INTERNAL_ERROR` | 500 | Server error | - -## Security Features - -- **Magic Bytes Validation**: Verifies file content matches extension -- **Path Traversal Prevention**: Blocks `..` and absolute paths -- **Filename Sanitization**: Removes special characters -- **Rate Limiting**: 10 uploads per IP per hour -- **Helmet Integration**: HTTP security headers -- **Zip Bomb Protection**: 50MB limit per extracted file -- **Isolated Sessions**: Each upload gets a unique UUID directory -- **Automatic Cleanup**: Sessions expire after 1 hour - -## Project Structure - -``` -/project-root -├── server/ -│ ├── index.js # Express app entry point -│ ├── routes/ -│ │ └── api.js # API route definitions -│ ├── controllers/ -│ │ └── archiveController.js # Request handlers -│ ├── services/ -│ │ └── extractionService.js # ZIP/RAR extraction logic -│ ├── middleware/ -│ │ └── security.js # Validation & security -│ └── utils/ -│ └── fileTree.js # Tree generation utility -├── public/ -│ ├── index.html # Main HTML page -│ ├── styles.css # CSS styling -│ └── app.js # Frontend JavaScript -├── uploads/ # Temporary upload storage -├── extracted/ # Session extraction folders -├── package.json -├── .env.example -└── README.md -``` +## Cấu hình GitHub (Settings → Secrets and variables → Actions) -## License +| Tên | Loại | Dùng cho | +|---|---|---| +| `HF_TOKEN` | secret | token HF quyền ghi | +| `HF_SPACE` | variable | vd `bacteriaqh/extractor` | +| `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | secret | deploy Worker (token cần quyền Workers Scripts: Edit) | +| `BACKEND_URL`, `BACKEND_API_KEY`, `FIREBASE_WEB_CONFIG` | secret | đẩy lên Worker làm secret; `BACKEND_API_KEY` phải trùng với secret của Space | -MIT License - Feel free to use in your projects! -# extract-server +Secrets runtime của backend (`BACKEND_API_KEY`, `AUTH_SECRET`, `FIREBASE_SERVICE_ACCOUNT`, `TELEGRAM_*`, `ADMIN_EMAIL`, `GEMINI_*`...) đặt trong Settings → Variables and secrets của Space — xem `.env.example` và `passport-check/README.md`. diff --git a/extractor/.dockerignore b/extractor/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..2b625989318377914ed464f16c0b5d6c355f5ced --- /dev/null +++ b/extractor/.dockerignore @@ -0,0 +1,12 @@ +node_modules +.git +.gitignore +.env +.idea +.DS_Store + +uploads +extracted + +npm-debug.log +pnpm-debug.log diff --git a/extractor/.env.example b/extractor/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..3d8f675a3378a8ffe289065d02ee35a25b6d2c9f --- /dev/null +++ b/extractor/.env.example @@ -0,0 +1,13 @@ +# Server Configuration +PORT=3000 + +# File Size Limits (in bytes) +MAX_FILE_SIZE=104857600 +MAX_EXTRACTED_FILE_SIZE=52428800 + +# Session Configuration (in milliseconds) +SESSION_TIMEOUT=3600000 + +# Rate Limiting +RATE_LIMIT_WINDOW=3600000 +RATE_LIMIT_MAX=10 diff --git a/extractor/.gitignore b/extractor/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f86ccf3588091b79f9dededa3c922fd5fa37e9e1 --- /dev/null +++ b/extractor/.gitignore @@ -0,0 +1,21 @@ +# Dependencies +node_modules/ + +# Environment files +.env + +# Upload and extraction directories +uploads/ +extracted/ + +# OS files +.DS_Store +Thumbs.db + +# IDE +.vscode/ +.idea/ + +# Logs +*.log +npm-debug.log* diff --git a/extractor/Dockerfile b/extractor/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cfff98c25d061ba1a59f667daca6f025a822a3f9 --- /dev/null +++ b/extractor/Dockerfile @@ -0,0 +1,26 @@ +FROM node:20-slim + +WORKDIR /app + +ENV NODE_ENV=production +ENV HOST=0.0.0.0 +ENV PORT=7860 +ENV SESSION_TIMEOUT=3600000 +ENV MAX_FILE_SIZE=104857600 +ENV MAX_EXTRACTED_FILE_SIZE=52428800 +ENV RATE_LIMIT_WINDOW=3600000 +ENV RATE_LIMIT_MAX=10 + +COPY package.json ./ +COPY pnpm-lock.yaml ./ + +RUN corepack enable && corepack prepare pnpm@10.33.4 --activate \ + && pnpm install --frozen-lockfile + +COPY . . + +RUN mkdir -p uploads extracted + +EXPOSE 7860 + +CMD ["pnpm", "start"] diff --git a/HUGGINGFACE_DEPLOY.md b/extractor/HUGGINGFACE_DEPLOY.md similarity index 100% rename from HUGGINGFACE_DEPLOY.md rename to extractor/HUGGINGFACE_DEPLOY.md diff --git a/extractor/README.md b/extractor/README.md new file mode 100644 index 0000000000000000000000000000000000000000..814b428d7492d978cf78141f1a787d65ea6bc643 --- /dev/null +++ b/extractor/README.md @@ -0,0 +1,202 @@ +--- +title: File Share +emoji: 📤 +colorFrom: indigo +colorTo: purple +sdk: docker +app_port: 7860 +pinned: false +license: mit +--- + +# Archive Extractor + +A production-ready web application for uploading, extracting, and managing compressed file archives (ZIP and RAR). Features a modern dark-themed UI with drag-and-drop upload, tree view file explorer, and secure file handling. + +![Node.js](https://img.shields.io/badge/Node.js-18%2B-green) +![Express.js](https://img.shields.io/badge/Express.js-4.x-blue) +![License](https://img.shields.io/badge/License-MIT-yellow) + +## Features + +- 📦 **Multi-format Support**: Extract ZIP and RAR archives +- 🔄 **Nested Archive Handling**: Automatically extracts archives within archives +- 🌲 **Interactive File Tree**: Collapsible tree view with file type icons +- ⬇️ **Flexible Downloads**: Download individual files or entire folders as ZIP +- 🎨 **Modern UI**: Dark theme with glassmorphism effects and animations +- 📱 **Responsive Design**: Works on desktop and mobile devices +- 🔒 **Security First**: Path traversal prevention, magic bytes validation, rate limiting + +## Prerequisites + +- Node.js v18 or higher +- npm or yarn + +## Installation + +1. **Clone or download the project** + +2. **Install dependencies** + ```bash + npm install + ``` + +3. **Configure environment** (optional) + ```bash + cp .env.example .env + # Edit .env to customize settings + ``` + +4. **Start the server** + ```bash + npm start + ``` + +5. **Open in browser** + ``` + http://localhost:3000 + ``` + +## Development + +Run with auto-reload on file changes: +```bash +npm run dev +``` + +## Configuration + +All settings are configurable via environment variables: + +| Variable | Default | Description | +|----------|---------|-------------| +| `PORT` | 3000 | Server port | +| `MAX_FILE_SIZE` | 104857600 | Max upload size in bytes (100MB) | +| `MAX_EXTRACTED_FILE_SIZE` | 52428800 | Max extracted file size (50MB) | +| `SESSION_TIMEOUT` | 3600000 | Auto-cleanup timeout in ms (1 hour) | +| `RATE_LIMIT_WINDOW` | 3600000 | Rate limit window in ms (1 hour) | +| `RATE_LIMIT_MAX` | 10 | Max uploads per window per IP | + +## API Endpoints + +### Upload Archive +```http +POST /api/upload +Content-Type: multipart/form-data + +file: +``` + +**Response (200)**: +```json +{ + "success": true, + "sessionId": "uuid-v4", + "filename": "archive.zip", + "stats": { + "totalFiles": 42, + "totalSize": 1048576 + } +} +``` + +### Get File Tree +```http +GET /api/files/:sessionId +``` + +**Response (200)**: +```json +{ + "success": true, + "sessionId": "uuid-v4", + "tree": { + "name": "root", + "type": "folder", + "path": "/", + "children": [...] + } +} +``` + +### Download File +```http +GET /api/download/:sessionId/file?path=/path/to/file.txt +``` + +### Download Folder as ZIP +```http +GET /api/download/:sessionId/folder?path=/path/to/folder +``` + +### Delete Session +```http +DELETE /api/session/:sessionId +``` + +## Error Responses + +All errors return a consistent format: +```json +{ + "error": true, + "message": "Human-readable description", + "code": "ERROR_CODE" +} +``` + +| Code | HTTP Status | Description | +|------|-------------|-------------| +| `INVALID_FILE_TYPE` | 400 | Unsupported file extension | +| `INVALID_MAGIC_BYTES` | 400 | File content doesn't match extension | +| `FILE_TOO_LARGE` | 400 | File exceeds size limit | +| `INVALID_PATH` | 400 | Path contains traversal or is absolute | +| `SESSION_NOT_FOUND` | 404 | Session expired or doesn't exist | +| `FILE_NOT_FOUND` | 404 | Requested file doesn't exist | +| `PASSWORD_PROTECTED` | 422 | Archive requires a password | +| `CORRUPTED_ARCHIVE` | 422 | Archive is damaged | +| `RATE_LIMIT_EXCEEDED` | 429 | Too many requests | +| `INTERNAL_ERROR` | 500 | Server error | + +## Security Features + +- **Magic Bytes Validation**: Verifies file content matches extension +- **Path Traversal Prevention**: Blocks `..` and absolute paths +- **Filename Sanitization**: Removes special characters +- **Rate Limiting**: 10 uploads per IP per hour +- **Helmet Integration**: HTTP security headers +- **Zip Bomb Protection**: 50MB limit per extracted file +- **Isolated Sessions**: Each upload gets a unique UUID directory +- **Automatic Cleanup**: Sessions expire after 1 hour + +## Project Structure + +``` +/project-root +├── server/ +│ ├── index.js # Express app entry point +│ ├── routes/ +│ │ └── api.js # API route definitions +│ ├── controllers/ +│ │ └── archiveController.js # Request handlers +│ ├── services/ +│ │ └── extractionService.js # ZIP/RAR extraction logic +│ ├── middleware/ +│ │ └── security.js # Validation & security +│ └── utils/ +│ └── fileTree.js # Tree generation utility +├── public/ +│ ├── index.html # Main HTML page +│ ├── styles.css # CSS styling +│ └── app.js # Frontend JavaScript +├── uploads/ # Temporary upload storage +├── extracted/ # Session extraction folders +├── package.json +├── .env.example +└── README.md +``` + +## License + +MIT License - Feel free to use in your projects! +# extract-server diff --git a/package.json b/extractor/package.json similarity index 100% rename from package.json rename to extractor/package.json diff --git a/pnpm-lock.yaml b/extractor/pnpm-lock.yaml similarity index 100% rename from pnpm-lock.yaml rename to extractor/pnpm-lock.yaml diff --git a/public/app.js b/extractor/public/app.js similarity index 97% rename from public/app.js rename to extractor/public/app.js index b06f0be4b3e480c44daa4f111f218e898d6896a4..bcb8787f62c95723831a2caf33e23c4c02ae2b36 100644 --- a/public/app.js +++ b/extractor/public/app.js @@ -403,7 +403,7 @@ async function uploadFiles(files) { state.uploadInProgress = false; }); - xhr.open('POST', '/api/upload'); + xhr.open('POST', 'api/upload'); xhr.send(formData); } @@ -455,7 +455,7 @@ function hideProgress() { */ async function loadFileTree(sessionId, filename, stats, accessCode = sessionId, sessionMeta = {}) { try { - const response = await fetch(`/api/files/${sessionId}`); + const response = await fetch(`api/files/${sessionId}`); const data = await response.json(); if (!response.ok) { @@ -587,8 +587,8 @@ function downloadItem(path, type) { const relativePath = path.startsWith('/') ? path.slice(1) : path; const endpoint = type === 'folder' - ? `/api/download/${state.currentSessionId}/folder?path=${encodeURIComponent(relativePath)}` - : `/api/download/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`; + ? `api/download/${state.currentSessionId}/folder?path=${encodeURIComponent(relativePath)}` + : `api/download/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`; // Create temporary link and click it const link = document.createElement('a'); @@ -612,7 +612,7 @@ function viewItem(path) { } const relativePath = path.startsWith('/') ? path.slice(1) : path; - const endpoint = `/api/view/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`; + const endpoint = `api/view/${state.currentSessionId}/file?path=${encodeURIComponent(relativePath)}`; window.open(endpoint, '_blank', 'noopener,noreferrer'); } @@ -632,7 +632,7 @@ function resetToUpload(options = {}) { // Clean up current session if (!skipDelete && state.currentSessionId) { - fetch(`/api/session/${state.currentSessionId}`, { method: 'DELETE' }) + fetch(`api/session/${state.currentSessionId}`, { method: 'DELETE' }) .catch(console.error); } @@ -699,7 +699,7 @@ elements.accessCodeForm.addEventListener('submit', async (e) => { try { elements.openAccessCodeBtn.disabled = true; elements.openAccessCodeBtn.textContent = 'Opening...'; - const response = await fetch(`/api/files/${accessCode}`); + const response = await fetch(`api/files/${accessCode}`); const data = await response.json(); if (!response.ok) { throw new Error(data.message || 'Unable to open this code'); diff --git a/public/index.html b/extractor/public/index.html similarity index 100% rename from public/index.html rename to extractor/public/index.html diff --git a/public/styles.css b/extractor/public/styles.css similarity index 100% rename from public/styles.css rename to extractor/public/styles.css diff --git a/server/controllers/archiveController.js b/extractor/server/controllers/archiveController.js similarity index 100% rename from server/controllers/archiveController.js rename to extractor/server/controllers/archiveController.js diff --git a/server/index.js b/extractor/server/index.js similarity index 100% rename from server/index.js rename to extractor/server/index.js diff --git a/server/middleware/security.js b/extractor/server/middleware/security.js similarity index 100% rename from server/middleware/security.js rename to extractor/server/middleware/security.js diff --git a/server/routes/api.js b/extractor/server/routes/api.js similarity index 100% rename from server/routes/api.js rename to extractor/server/routes/api.js diff --git a/server/services/extractionService.js b/extractor/server/services/extractionService.js similarity index 100% rename from server/services/extractionService.js rename to extractor/server/services/extractionService.js diff --git a/server/utils/fileTree.js b/extractor/server/utils/fileTree.js similarity index 100% rename from server/utils/fileTree.js rename to extractor/server/utils/fileTree.js diff --git a/passport-check/.dockerignore b/passport-check/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..bf39f4695a097226502009acf546107059d94d26 --- /dev/null +++ b/passport-check/.dockerignore @@ -0,0 +1,11 @@ +node_modules +**/node_modules +**/dist +**/.next +samples +.playwright-mcp +.backup +.env +**/.env* +tessdata/eng.traineddata.gz +tessdata/vie.traineddata.gz diff --git a/passport-check/.env.example b/passport-check/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..6b2469c565003fc80f2c1e2ad77a39008b307856 --- /dev/null +++ b/passport-check/.env.example @@ -0,0 +1,61 @@ +# ===================================================================== +# BACKEND (Hugging Face Space) — đặt trong Settings → Variables and secrets +# ===================================================================== + +# ---------- Bảo mật (bắt buộc) +# Khoá chung giữa Next.js và backend; chỉ server Next.js biết. Tạo: openssl rand -base64 48 +BACKEND_API_KEY= +# Khoá ký token phiên đăng nhập. Tạo: openssl rand -base64 48 (đổi khoá = đăng xuất mọi người) +AUTH_SECRET= +# số ngày phiên đăng nhập còn hiệu lực +AUTH_TOKEN_DAYS=7 + +# ---------- Admin đầu tiên (chỉ dùng khi bảng users còn trống) +ADMIN_EMAIL= +# để trống nếu admin chỉ đăng nhập Google; nếu đặt thì >= 8 ký tự +ADMIN_PASSWORD= +# (tuỳ chọn) email đăng nhập Google lần đầu được tự thêm vào bảng users, cách nhau dấu phẩy; "@congty.vn" = cả tên miền +ALLOWED_EMAILS= + +# ---------- Firebase (bắt buộc) — Firestore + xác minh đăng nhập Google +# Service account: Firebase Console → Project settings → Service accounts → Generate new private key. +# Dán nguyên JSON (hoặc base64 của JSON) vào secret này. +FIREBASE_SERVICE_ACCOUNT= + +# ---------- Telegram (bắt buộc) — nơi lưu ảnh gốc +TELEGRAM_BOT_TOKEN= +TELEGRAM_CHAT_ID= + +# ---------- Gemini (tuỳ chọn) +GEMINI_API_KEY= +GEMINI_MODEL= +# (tuỳ chọn) luật tính token ảnh (theo kích thước, không gọi API): tile (258/ô, không chặn trần) | low | medium | high | ultra_high (258/ô, chặn trần 280/560/1120/2240) | số token cố định/ảnh +# để trống = tự chọn theo GEMINI_MODEL (gemini-2.x -> tile, còn lại -> tile chặn trần 1120) +GEMINI_IMAGE_TOKENS= +# (tuỳ chọn) đơn giá mặc định cho trang chi phí, USD / 1 triệu token (mặc định 0.25 / 1.5 — Gemini 3.1 Flash-Lite trả phí, tier Standard) +GEMINI_PRICE_INPUT= +GEMINI_PRICE_OUTPUT= + +# ---------- Tuỳ chỉnh (không bắt buộc) +OCR_CONCURRENCY=1 +LLM_CONCURRENCY=2 +OCR_WORKERS=2 +MAX_IMAGE_MB=50 +MAX_ZIP_MB=50 +MAX_ZIP_ENTRIES=5000 +IMAGE_CACHE_MB=500 +TELEGRAM_MIN_INTERVAL_MS=1100 +RATE_LIMIT=600 + +# ===================================================================== +# FRONTEND (Next.js) — biến môi trường phía server, không gửi cho trình duyệt +# ===================================================================== +# URL Space backend, vd https://ten-ban-passport-check.hf.space +BACKEND_URL=http://localhost:7860 +# giống hệt BACKEND_API_KEY ở trên +# BACKEND_API_KEY= +# Cấu hình Firebase web app (công khai) cho nút Google: +# Project settings → General → Your apps → Web app → SDK setup (Config) +FIREBASE_WEB_CONFIG= +# cookie Secure: mặc định bật khi NODE_ENV=production +# COOKIE_SECURE=true diff --git a/passport-check/.github/workflows/deploy.yml b/passport-check/.github/workflows/deploy.yml new file mode 100644 index 0000000000000000000000000000000000000000..60aeffea7b38b17f6a3e6d4f626490cf32de4d67 --- /dev/null +++ b/passport-check/.github/workflows/deploy.yml @@ -0,0 +1,32 @@ +name: Deploy to OCI + +on: + push: + branches: [main] + workflow_dispatch: + +concurrency: + group: deploy + cancel-in-progress: false + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Cấu hình SSH + env: + OCI_SSH_KEY: ${{ secrets.OCI_SSH_KEY }} + OCI_HOST: ${{ secrets.OCI_HOST }} + run: | + install -m 700 -d ~/.ssh + printf '%s\n' "$OCI_SSH_KEY" > ~/.ssh/id_deploy + chmod 600 ~/.ssh/id_deploy + ssh-keyscan -H "$OCI_HOST" >> ~/.ssh/known_hosts + + - name: Pull và build lại trên VM + env: + OCI_HOST: ${{ secrets.OCI_HOST }} + OCI_USER: ${{ secrets.OCI_USER }} + run: | + ssh -i ~/.ssh/id_deploy "$OCI_USER@$OCI_HOST" \ + 'set -e; cd ~/passport-check && git pull --ff-only && docker compose up -d --build && docker image prune -f' diff --git a/passport-check/.gitignore b/passport-check/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..42e1e9877966da57d5306d17be080aba4c9132e5 --- /dev/null +++ b/passport-check/.gitignore @@ -0,0 +1,42 @@ +node_modules +dist +# model ngôn ngữ tải bằng `npm run tessdata`; mrz.traineddata.gz (bản int đã chuyển đổi) được commit +tessdata/*.traineddata.gz +!tessdata/mrz.traineddata.gz +samples/ +*.traineddata +.env +.env*.local +# khoá Firebase / log emulator — KHÔNG commit +*firebase-adminsdk*.json +service-account*.json +.firebase/ +*-debug.log +# file Excel mẫu gốc chứa dữ liệu khách thật — chỉ dùng để sinh template, KHÔNG commit +/*.xlsx +.next +next-env.d.ts +*.tsbuildinfo +.backup/ + +# secret triển khai / dữ liệu thật — KHÔNG commit +.env* +!.env.example +low/ +.playwright-mcp/ +FEATURES.docx + +# build Cloudflare/OpenNext, log, cache, file hệ thống/IDE +.open-next +.wrangler/ +.dev.vars +*.log +coverage/ +.turbo/ +.cache/ +.DS_Store +Thumbs.db +.idea/ +.vscode/ +*.pem +*.key diff --git a/passport-check/Caddyfile b/passport-check/Caddyfile new file mode 100644 index 0000000000000000000000000000000000000000..259274b0221a5a542227bea19356c3ffa344c46d --- /dev/null +++ b/passport-check/Caddyfile @@ -0,0 +1,6 @@ +{$SITE_DOMAIN} { + request_body { + max_size 500MB + } + reverse_proxy web:3000 +} diff --git a/passport-check/Dockerfile b/passport-check/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..218786c5efe4abe0152bc81d9026742062dc4479 --- /dev/null +++ b/passport-check/Dockerfile @@ -0,0 +1,30 @@ +# Backend — Hugging Face Spaces (Docker SDK), 1 container Node ở port 7860. +# Frontend Next.js deploy riêng (xem apps/web/Dockerfile); trình duyệt không gọi thẳng vào Space này. +FROM node:22-slim AS build +WORKDIR /app +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* +COPY package.json package-lock.json ./ +COPY packages/core/package.json packages/core/ +COPY apps/server/package.json apps/server/ +COPY apps/web/package.json apps/web/ +RUN npm ci --workspace apps/server --include-workspace-root +COPY packages packages +COPY apps/server apps/server +COPY scripts scripts +COPY tessdata tessdata +COPY tsconfig.base.json ./ +RUN npm run tessdata && npm -w apps/server run build && npm prune --omit=dev --workspace apps/server --include-workspace-root + +FROM node:22-slim +ENV NODE_ENV=production PORT=7860 \ + TEMPLATE_DIR=/app/apps/server/templates TESSDATA_DIR=/app/tessdata +WORKDIR /app +COPY --from=build --chown=node:node /app/node_modules ./node_modules +COPY --from=build --chown=node:node /app/apps/server/dist ./apps/server/dist +COPY --from=build --chown=node:node /app/apps/server/templates ./apps/server/templates +COPY --from=build --chown=node:node /app/tessdata ./tessdata +COPY --from=build --chown=node:node /app/package.json ./ +# HF Spaces chạy với uid 1000 (= user node) +USER node +EXPOSE 7860 +CMD ["node", "apps/server/dist/server.js"] diff --git a/passport-check/FEATURES.md b/passport-check/FEATURES.md new file mode 100644 index 0000000000000000000000000000000000000000..d2d54ebdc189df8162699e0a39707667e65bbe8c --- /dev/null +++ b/passport-check/FEATURES.md @@ -0,0 +1,120 @@ +# Tính năng & tiến độ — Passport Check + +> Cập nhật: 09/11/2026 · Trạng thái chung: **MVP hoàn thành, sẵn sàng chạy thử trên HF Spaces** +> +> Kiểm tra lúc cập nhật: `npm test` 27/27 pass · `npm run typecheck` sạch · không còn TODO/FIXME trong code. + +Chú thích: ✅ xong · 🟡 xong một phần / có giới hạn · ⬜ chưa làm + +--- + +## 1. Tổng quan tiến độ + +| Mảng | Trạng thái | Ghi chú | +|---|---|---| +| Đăng nhập & phân quyền | ✅ | Firebase Auth, whitelist email/tên miền | +| Upload ảnh / thư mục / zip | ✅ | Chống trùng theo SHA-256 | +| Lưu ảnh gốc (Telegram) | ✅ | Có xếp hàng, chờ theo `retry_after` | +| OCR + kiểm chứng MRZ | ✅ | 2 engine, ~60 ngôn ngữ VIZ, 2 lượt nhanh/kỹ | +| Gemini hỗ trợ ảnh khó | ✅ | Tuỳ chọn theo lô, kết quả vẫn kiểm checksum | +| Duyệt / sửa kết quả | ✅ | | +| Hồ sơ thị thực theo đoàn | ✅ | Thông tin đoàn, ghi đè riêng từng khách | +| Danh sách khách (gộp đoàn) | ✅ | Lọc, tìm, chọn nhanh, xoá nhiều, phân trang | +| Xuất Excel theo mẫu (DVC, Biên phòng) + CSV | ✅ | Giữ dropdown, định dạng mẫu | +| Khôi phục job khi restart | ✅ | Ảnh chưa lên Telegram phải upload lại | +| Triển khai (Docker / HF Spaces) | ✅ | 1 instance | +| Kiểm thử tự động | 🟡 | Có unit test core; chưa có test server/web | +| Mở rộng nhiều instance | ⬜ | Thiết kế hiện tại giữ state trong RAM | + +--- + +## 2. Chi tiết tính năng + +### 2.1 Xác thực & bảo mật +- ✅ Đăng nhập Google hoặc email/mật khẩu (đã xác minh) qua Firebase Auth. +- ✅ Chỉ email trong `ALLOWED_EMAILS` được dùng; hỗ trợ cả tên miền (`@congty.vn`). +- ✅ `firestore.rules` chặn toàn bộ truy cập Firestore trực tiếp từ trình duyệt; chỉ server (Admin SDK) đọc/ghi. +- ✅ Rate limit API (`RATE_LIMIT`, mặc định 600 req/phút). +- ✅ Bot token Telegram không bao giờ tới trình duyệt; ảnh đi qua server và yêu cầu đăng nhập. +- 🟡 Ảnh trên Telegram lưu nguyên bản, **không mã hoá**: an toàn phụ thuộc vào việc giữ kênh riêng tư. + +### 2.2 Upload & lưu trữ +- ✅ Upload ảnh lẻ, cả thư mục hoặc `.zip` (JPG, PNG, WebP, HEIC, TIFF…). +- ✅ Mỗi lần upload là một **lô** (= một đoàn); upload chia nhóm, có thanh tiến độ. +- ✅ Chống trùng: trùng trong lô thì bỏ qua; trùng với lô khác thì dùng lại file và kết quả cũ. +- ✅ Lưu ảnh gốc dạng document (không nén) lên kênh Telegram; ảnh > 19,5MB được nén trước khi gửi. +- ✅ Chuẩn hoá ảnh, sinh thumbnail, cache ảnh trên ổ tạm (`IMAGE_CACHE_MB`). +- ✅ Giới hạn kích thước cấu hình được: `MAX_IMAGE_MB`, `MAX_ZIP_MB`, `MAX_ZIP_ENTRIES`. + +### 2.3 OCR & kiểm chứng +- ✅ Tự xoay, chỉnh nghiêng, cắt vùng MRZ; đọc bằng 2 engine độc lập (model MRZ chuyên dụng + `eng`). +- ✅ Parse MRZ TD3 / TD2 / TD1 / visa; kiểm 5 check digit theo ICAO 9303. +- ✅ Sửa lỗi OCR theo loại ô (O↔0, I↔1…). +- ✅ Đọc vùng chữ (VIZ) bằng model ngôn ngữ của nước cấp (~60 ngôn ngữ, bảng trong `packages/core/src/langs.ts`). +- ✅ Đối chiếu tên MRZ với chữ in, kiểm logic ngày, chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`. +- ✅ Lượt nhanh trước, chỉ ảnh chưa đạt `Cao` mới chạy lượt kỹ. +- ✅ Chạy lại OCR cho từng ảnh (`rerun`). +- ✅ Gemini tuỳ chọn theo lô: không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả. + +### 2.4 Duyệt & quản lý dữ liệu +- ✅ Trang lô: xem tiến độ OCR thời gian thực (chỉ tải ảnh vừa thay đổi, 3 giây/lần). +- ✅ Bảng kết quả, panel duyệt/sửa tay, đánh dấu đã duyệt, xoá ảnh. +- ✅ Link xem lại ảnh `/b//i/<ảnh>` (yêu cầu đăng nhập). +- ✅ Kết quả lưu Firestore; server giữ toàn bộ dữ liệu trong RAM, chỉ đọc Firestore 1 lần khi khởi động. + +### 2.5 Hồ sơ thị thực theo đoàn +- ✅ **Thông tin đoàn** điền một lần: mã đoàn, ngày nhập cảnh, số ngày lưu trú, nhập cảnh nhiều lần, cách nhận/nơi nhận visa, mục đích, VIP, khẩn, cơ quan cấp, hướng hành trình. +- ✅ Sửa riêng từng khách; ô ghi đè hiển thị nhãn "riêng". +- ✅ Tự tính ngày xuất cảnh = ngày nhập cảnh + số ngày lưu trú − 1. +- ✅ Tự gán nghề nghiệp theo tuổi tại ngày nhập cảnh (≥ 60 tuổi: "Hưu trí", còn lại "Nhân viên"). +- ✅ Cảnh báo hộ chiếu còn hạn < 6 tháng (ở danh sách, form chi tiết và khi xuất). + +### 2.6 Danh sách khách (`/khach`) +- ✅ Gộp khách của mọi đoàn. +- ✅ Lọc theo cột, tìm kiếm, lọc nhanh (hộ chiếu < 6 tháng / cần duyệt / khẩn). +- ✅ Chọn nhanh theo đoàn, xoá nhiều dòng, phân trang 100 dòng. + +### 2.7 Xuất file +- ✅ *Thông tin hộ chiếu (nộp DVC)*: sheet `INF_NHAN_SU`, tên file `ThongTinHoChieu--.xlsx`. +- ✅ *Công văn biên phòng*: sheet `BP`, giá trị dạng `nhãn|mã`, tên file sửa được trước khi tải. +- ✅ Điền vào file mẫu, giữ dropdown, sheet danh mục ẩn và định dạng có điều kiện; xếp Nam trước, Nữ sau. +- ✅ Kiểm tra trước khi xuất (`/export/check`) và cảnh báo thiếu dữ liệu / hộ chiếu sắp hết hạn. +- ✅ Xuất CSV; Excel có cột link xem ảnh. +- ✅ Script `scripts/make-templates.ts` sinh lại file mẫu + danh mục khi cơ quan đổi mẫu. + +### 2.8 Vận hành & triển khai +- ✅ Dockerfile multi-stage cho HF Spaces (port 7860, user `node`). +- ✅ Hàng đợi job, khôi phục khi Space khởi động lại (lấy lại ảnh từ Telegram để OCR tiếp). +- ✅ Chạy local với Firebase Emulator. +- 🟡 Chỉ đúng khi chạy **1 instance** (state nằm trong RAM). + +### 2.9 Kiểm thử & đo chất lượng +- ✅ Unit test `packages/core`: MRZ, chọn ngôn ngữ, logic visa (3 file, 27 test). +- ✅ `npm run samples`: sinh 8 ảnh hộ chiếu tổng hợp + `ground_truth.csv`. +- ✅ `npm run eval`: đo độ chính xác OCR (lượt nhanh / kỹ). +- ⬜ Chưa có test cho `apps/server` (API, upload, jobs) và `apps/web`. +- ⬜ Chưa có CI chạy test/typecheck tự động. + +--- + +## 3. Việc còn lại / đề xuất + +Các mục dưới đây là đề xuất dựa trên giới hạn hiện tại, chưa phải cam kết. + +| Ưu tiên | Việc | Lý do | +|---|---|---| +| Cao | Thêm CI (test + typecheck) | Hiện chỉ kiểm tra thủ công | +| Cao | Test tích hợp cho API server (upload, export, phân quyền) | Phần quan trọng nhất chưa có test | +| Trung bình | Ghi lại kết quả `npm run eval` làm mốc độ chính xác | Để theo dõi khi chỉnh pipeline OCR | +| Trung bình | Mã hoá ảnh trước khi gửi Telegram | Ảnh hộ chiếu đang lưu nguyên bản | +| Trung bình | Bổ sung bộ ảnh mẫu thực tế (đã ẩn danh) cho eval | 8 ảnh tổng hợp chưa đại diện hết ca khó | +| Thấp | Hỗ trợ nhiều instance (đồng bộ state qua Firestore listener / Redis) | Chỉ cần khi vượt sức 1 Space | +| Thấp | Theo dõi quota Firestore (50k đọc / 20k ghi mỗi ngày gói Spark) | Tránh chạm giới hạn khi xử lý lô lớn | + +--- + +## 4. Lịch sử cập nhật + +| Ngày | Nội dung | +|---|---| +| 09/11/2026 | Tạo tài liệu; MVP đủ các mảng 2.1 – 2.8 | diff --git a/passport-check/README.md b/passport-check/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e193c8a41afe3d6b19f5597c95deef9700902b17 --- /dev/null +++ b/passport-check/README.md @@ -0,0 +1,204 @@ +--- +title: Passport Check +emoji: 🛂 +colorFrom: blue +colorTo: gray +sdk: docker +app_port: 7860 +pinned: false +--- + +# Passport Check + +Web app trích xuất thông tin hộ chiếu hàng loạt từ một thư mục ảnh, kiểm chứng bằng **check digit MRZ (ICAO 9303)**. + +## Kiến trúc + +``` +Trình duyệt ──cookie httpOnly──▶ Next.js (apps/web) ──x-api-key + token phiên──▶ Backend Express trên HF Space (apps/server) + · trang render ở server · Firestore, Telegram, OCR, Gemini + · /api/* = proxy phía server · bảng users, cấp token phiên +``` + +- Trình duyệt **chỉ gọi Next.js** (`/api/...` cùng tên miền). Next.js mới gọi backend, kèm `BACKEND_API_KEY` và token phiên lấy từ cookie httpOnly. Trình duyệt không biết URL backend, API key hay token. +- Backend từ chối mọi request không có `BACKEND_API_KEY`, nên URL Space công khai cũng không gọi thẳng được. +- Upload ảnh/zip, tải ảnh, tải file Excel đều được stream qua Next.js (không giữ cả file trong RAM). + +## Đăng nhập & người dùng + +- **Google**: trình duyệt mở popup Google (Firebase Auth), gửi ID token **một lần** cho Next.js (`/api/auth/google`); backend xác minh bằng firebase-admin, rồi khớp email với **bảng `users`** (Firestore). Sau đó trình duyệt đăng xuất Firebase; phiên thật nằm trong cookie của Next.js. +- **Email / mật khẩu**: chỉ dùng được cho tài khoản mà admin đã đặt mật khẩu (băm scrypt). Không có đăng ký tự do. +- Bảng `users`: `email`, `name`, `role` (`admin` | `user`), `disabled`, `passwordHash` (tuỳ chọn), `tokenVersion`, `lastLoginAt`… + Admin quản lý ở trang **Người dùng** (`/nguoi-dung`): thêm, đổi quyền, khoá, đặt/bỏ mật khẩu, xoá. Khoá / đổi mật khẩu / hạ quyền sẽ huỷ ngay mọi phiên đang mở của người đó. +- Admin đầu tiên: khi bảng trống, backend tự tạo từ `ADMIN_EMAIL` (+ `ADMIN_PASSWORD` nếu muốn đăng nhập bằng mật khẩu). +- `ALLOWED_EMAILS` (tuỳ chọn): email Google khớp danh sách này mà chưa có trong bảng sẽ được **tự thêm** với quyền `user` khi đăng nhập lần đầu. +- Mỗi người tự đặt / đổi mật khẩu ở trang **Tài khoản** (`/tai-khoan`). + +## Cách hoạt động + +1. **Đăng nhập** bằng Google hoặc email/mật khẩu (xem trên). +2. **Upload** ảnh, cả thư mục, hoặc file `.zip` (JPG, PNG, WebP, HEIC, TIFF…). Mỗi lần upload tạo một **lô**. Ảnh trùng (cùng nội dung) trong lô bị bỏ qua; ảnh đã có ở lô khác thì dùng lại file và kết quả cũ. +3. **Lưu ảnh gốc lên Telegram**: server gửi file (dạng document, không nén) vào kênh / nhóm riêng qua bot, lưu `file_id`. HF Spaces free không có ổ đĩa bền, nên Telegram là nơi giữ ảnh lâu dài. +4. **OCR trên server** (tesseract.js + sharp, model chuyên MRZ + tiếng Anh): + - Tự xoay, tự chỉnh nghiêng, cắt vùng MRZ, đọc bằng 2 engine độc lập. + - Sau khi biết nước cấp, đọc thêm vùng chữ bằng model ngôn ngữ của nước đó (VNM→`vie`, FRA→`fra`, BEL→`nld+fra`, CHN→`chi_sim`…, khoảng 60 ngôn ngữ, bảng trong `packages/core/src/langs.ts`). + - Chạy lượt nhanh trước; ảnh chưa đạt độ tin cậy `Cao` mới chạy lượt kỹ. +5. **Kiểm chứng**: + - Parse MRZ (TD3/TD2/TD1/visa), kiểm 5 check digit, sửa lỗi OCR theo loại ô (O/0, I/1…). + - Đối chiếu tên với chữ in trên trang, kiểm logic ngày. + - Chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`. +6. **Gemini (tuỳ chọn)**: chọn cho từng lô khi nào hỏi Gemini (không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả). Kết quả Gemini cũng bị kiểm checksum lại. Gemini chạy ở hàng đợi riêng (`LLM_CONCURRENCY`, mặc định 2), nên trong lúc chờ Gemini server vẫn OCR ảnh khác. +7. **Kết quả lưu Firestore**: xem, sửa tay, duyệt, xuất **Excel** / **CSV**. File Excel có cột link xem ảnh. +8. **Link xem lại ảnh**: `/b//i/<ảnh>`. Người mở phải đăng nhập; server tải ảnh từ Telegram rồi trả về, bot token không bao giờ tới trình duyệt. + +## Hồ sơ thị thực theo đoàn + +- **Mỗi lô upload là một đoàn.** Trong trang của lô, điền **Thông tin đoàn** một lần cho cả đoàn: + - phân tách khách hàng (mã đoàn), ngày nhập cảnh, số ngày lưu trú; + - nhập cảnh nhiều lần, cách nhận thị thực, nơi nhận visa, mục đích; + - VIP, khẩn, cơ quan cấp, hướng hành trình. +- Trên form chi tiết từng khách vẫn sửa riêng được; ô nào sửa riêng có chữ "riêng". +- **Ngày xuất cảnh** = ngày nhập cảnh + số ngày lưu trú − 1. +- **Nghề nghiệp**: tự theo tuổi tại ngày nhập cảnh (từ 60 tuổi là "Hưu trí", còn lại "Nhân viên"); sửa riêng được. +- **Cảnh báo hộ chiếu còn hạn dưới 6 tháng** tính từ ngày nhập cảnh (chưa có ngày thì tính từ hôm nay). Cảnh báo hiện ở danh sách, ở form chi tiết và khi xuất file. +- **Danh sách khách** (`/khach`): gộp mọi đoàn. + - Lọc theo từng cột, tìm kiếm, lọc nhanh (hộ chiếu dưới 6 tháng / cần duyệt / khẩn). + - "Chọn nhanh" theo đoàn, xoá nhiều dòng, phân trang 100 dòng. + - "Xuất ra excel" xuất các dòng đã chọn, nếu chưa chọn thì xuất toàn bộ theo bộ lọc. +- **Hai file xuất**, điền vào file mẫu nên giữ nguyên dropdown, sheet danh mục ẩn và định dạng có điều kiện. Cả hai **xếp toàn bộ Nam lên trên, Nữ xuống dưới**: + - *Thông tin hộ chiếu (nộp DVC)*: sheet `INF_NHAN_SU`, tên file `ThongTinHoChieu--.xlsx`. + - *Công văn biên phòng*: sheet `BP`, giá trị dạng `nhãn|mã`; tên file sửa được trước khi tải. + +File mẫu nằm ở `apps/server/templates/`, sinh từ 2 file Excel thật bằng: + +```bash +npx tsx scripts/make-templates.ts ThongTinHoChieu-....xlsx "XE 1 CV ....xlsx" +``` + +Script xoá toàn bộ dữ liệu khách khỏi file mẫu và sinh lại danh mục `packages/core/src/visa-lists.ts`. Các file `.xlsx` gốc ở thư mục gốc đã bị chặn commit qua `.gitignore` vì chứa dữ liệu khách thật. Khi cơ quan đổi mẫu, chạy lại script với file mẫu mới. + +Dữ liệu Firestore: + +| Collection | Nội dung | +|---|---| +| `batches/{id}` | Lô upload: tên, người tạo, cấu hình Gemini, bộ đếm kết quả | +| `batches/{id}/items/{id}` | Từng ảnh: trạng thái, thumbnail, tham chiếu Telegram, kết quả trích xuất | +| `hashes/{sha256}` | Chống trùng: ảnh đã lưu Telegram + số item đang dùng | + +Server giữ toàn bộ lô và khách trong RAM: chỉ đọc Firestore 1 lần lúc khởi động, sau đó mọi danh sách, bộ lọc và phân trang chạy trên RAM, nên không tốn lượt đọc. Cách này chỉ đúng khi chạy **1 instance** (như HF Space). Không chạy nhiều bản server cùng lúc trên cùng project Firebase. + +Khi Space khởi động lại giữa chừng: +- Ảnh **đã lên Telegram** được OCR tiếp, ảnh lấy lại từ Telegram. +- Ảnh **chưa kịp lên Telegram** (chỉ nằm trên ổ tạm) báo lỗi "hãy upload lại". + +## Cài đặt + +### 1. Firebase + +1. Tạo project ở [console.firebase.google.com](https://console.firebase.google.com). +2. **Authentication** → Sign-in method: bật **Google** (không cần Email/Password — mật khẩu do backend tự quản lý). +3. Authentication → Settings → **Authorized domains**: thêm tên miền của **frontend Next.js** (VD `passport.congty.vn`). +4. **Firestore Database** → tạo database (production mode). +5. Tab **Rules** → dán nội dung file `firestore.rules`: chặn mọi truy cập trực tiếp từ trình duyệt; chỉ server (Admin SDK) đọc/ghi. Hoặc chạy `firebase deploy --only firestore:rules`. +6. Project settings → **Service accounts** → *Generate new private key*, dùng làm `FIREBASE_SERVICE_ACCOUNT`. +7. Project settings → General → thêm **Web app**, copy object cấu hình làm `FIREBASE_WEB_CONFIG` (đặt ở **frontend**). + +Gói free (Spark): mỗi ngày 50.000 lượt đọc, 20.000 lượt ghi. Mỗi ảnh tốn khoảng 5 lượt ghi, nên dùng được khoảng 4.000 ảnh/ngày. Trang lô đang chạy chỉ tải những ảnh vừa thay đổi (20 giây/lần). + +### 2. Telegram + +1. Tạo bot với [@BotFather](https://t.me/BotFather), lấy token làm `TELEGRAM_BOT_TOKEN`. +2. Tạo **kênh hoặc nhóm riêng tư**, thêm bot làm admin (quyền đăng tin và xoá tin). +3. Lấy ID chat, dạng `-100…`: đăng 1 tin trong kênh rồi mở `https://api.telegram.org/bot/getUpdates`, xem `chat.id`. Dùng giá trị này làm `TELEGRAM_CHAT_ID`. + +Giới hạn của bot: +- Gửi file tối đa 50MB, tải về tối đa 20MB (ảnh lớn hơn 19,5MB được server nén lại trước khi gửi). +- Khoảng 20 tin/phút với nhóm. Server tự xếp hàng và chờ theo `retry_after` khi bị giới hạn. + +> ⚠ Ảnh lưu **nguyên bản, không mã hoá** trên Telegram. Ai vào được kênh/nhóm đều xem được ảnh hộ chiếu. Giữ kênh riêng tư, chỉ có bot và người cần thiết. + +### 3. Backend — Hugging Face Spaces (free) + +1. Tạo Space mới, SDK **Docker** (dùng `Dockerfile` ở thư mục gốc, chỉ build backend). Space để Public cũng được vì mọi API đòi `BACKEND_API_KEY`. +2. Settings → Variables and secrets. Bắt buộc: + - `BACKEND_API_KEY`, `AUTH_SECRET` — mỗi cái tạo bằng `openssl rand -base64 48` + - `FIREBASE_SERVICE_ACCOUNT` + - `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` + - `ADMIN_EMAIL` (lần chạy đầu), tuỳ chọn `ADMIN_PASSWORD` + + Tuỳ chọn: `ALLOWED_EMAILS`, `GEMINI_API_KEY`, `AUTH_TOKEN_DAYS`. +3. Push repo này lên Space (`git push` tới `https://huggingface.co/spaces//`). + +### 4. Frontend — Next.js + +Chạy ở bất cứ đâu có Node 22 (VPS, Docker, Cloud Run, Render…). Biến môi trường (phía server): + +- `BACKEND_URL` = `https://-.hf.space` +- `BACKEND_API_KEY` = giống backend +- `FIREBASE_WEB_CONFIG` = cấu hình web app Firebase (bỏ trống thì ẩn nút Google) + +Docker: `docker build -f apps/web/Dockerfile -t passport-check-web . && docker run -p 3000:3000 --env-file .env passport-check-web` + +> ⚠ Upload đi xuyên qua Next.js nên nền tảng chạy frontend phải cho phép request body lớn và request chạy lâu. **Vercel** (giới hạn body ~4,5MB/request) **không hợp** cho upload zip; nên dùng VPS / Docker / Cloud Run. + +> Gemini API gói miễn phí có thể dùng dữ liệu gửi lên để cải thiện sản phẩm của Google. Với hộ chiếu thật nên dùng API key có bật billing, hoặc tắt Gemini cho lô đó. + +## Chạy local + +```bash +npm install +npm run tessdata # tải eng + ~60 model ngôn ngữ (~110MB); hoặc: npm run tessdata -- vie fra +# tạo .env (backend) + apps/web/.env.local (Next.js), tự sinh BACKEND_API_KEY / AUTH_SECRET, +# chuyển file service account JSON thành base64 trong FIREBASE_SERVICE_ACCOUNT (app không đọc file JSON) +npm run setup:env -- --sa ~/path/to/xxx-firebase-adminsdk.json [--web firebase-web-config.json] +# rồi điền tay vào .env: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, ADMIN_EMAIL (+ ADMIN_PASSWORD nếu muốn) +npm run dev:server # backend http://localhost:7860 (đọc .env) +npm run dev:web # Next.js http://localhost:3000 (đọc apps/web/.env.local) +# production: npm run build && npm start (backend) và npm run start:web (frontend) +``` + +Chạy với Firebase Emulator (không cần project thật): + +```bash +npx firebase-tools emulators:start --only auth,firestore --project demo-passport-check +# backend (firebase.json của emulator đặt firestore 8085, auth 9099) +FIRESTORE_EMULATOR_HOST=127.0.0.1:8085 FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099 GCLOUD_PROJECT=demo-passport-check \ + BACKEND_API_KEY=<>=32 ký tự> AUTH_SECRET=<>=32 ký tự> ADMIN_EMAIL=admin@example.com ADMIN_PASSWORD=adminpass123 \ + ALLOWED_EMAILS=@example.com TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=... npm start +# frontend: nút Google dùng Auth emulator +BACKEND_URL=http://127.0.0.1:7860 BACKEND_API_KEY= FIREBASE_AUTH_EMULATOR_PUBLIC_URL=http://127.0.0.1:9099 \ + GCLOUD_PROJECT=demo-passport-check npm run start:web +``` + +Docker backend: `docker build -t passport-check . && docker run -p 7860:7860 --env-file .env passport-check` + +## Kiểm thử + +```bash +npm test # unit test MRZ / VIZ / reconcile +npm run samples # sinh 8 ảnh hộ chiếu tổng hợp (nhân vật hư cấu) + ground_truth.csv +npm run eval -- samples fast # đo độ chính xác OCR (fast = lượt nhanh, thorough = lượt kỹ) +``` + +Model MRZ (`tessdata/mrz.traineddata.gz`) là bản integer chuyển đổi từ [DoubangoTelecom/tesseractMRZ](https://github.com/DoubangoTelecom/tesseractMRZ) vì bản float gốc không chạy trên tesseract.js (WASM). Tạo lại: `scripts/convert-mrz-model.sh` (cần Docker). + +## Cấu trúc + +- `packages/core` — parse MRZ, sửa lỗi, VIZ, pipeline OCR, chọn ngôn ngữ theo nước, đối chiếu & chấm điểm, kiểu dữ liệu Firestore +- `apps/web` — Next.js (App Router): + - `src/app/(app)/*` — các trang; layout server kiểm tra phiên + cấu hình backend + - `src/app/api/[...path]` — proxy phía server sang backend (stream upload / ảnh / xlsx) + - `src/app/api/auth/*`, `api/me/password` — đăng nhập Google / mật khẩu, đăng xuất, đổi mật khẩu (đặt cookie) + - `src/lib/server/backend.ts` — gọi backend, cookie phiên (chỉ chạy trên server) + - `src/components` — upload (chia nhóm, có tiến độ), danh sách lô, duyệt/sửa, xuất Excel, quản lý người dùng +- `apps/server` — Express (backend trên HF Space): + - `auth.ts` — kiểm `BACKEND_API_KEY` + token phiên, phân quyền admin + - `users.ts` — bảng users, đăng nhập Google / mật khẩu, token phiên + - `firebase.ts` — Firestore + firebase-admin + - `templates/` — file Excel mẫu để xuất hồ sơ + - `telegram.ts` — lưu / tải ảnh + - `upload.ts` — multipart + zip + - `media.ts` — chuẩn hoá ảnh, thumbnail, cache + - `jobs.ts` — hàng đợi, khôi phục khi khởi động lại + - `ocr.ts`, `gemini.ts` +- `firestore.rules` — chặn truy cập Firestore trực tiếp từ trình duyệt diff --git a/passport-check/apps/server/build.mjs b/passport-check/apps/server/build.mjs new file mode 100644 index 0000000000000000000000000000000000000000..83520d3b696733c46a4e804c9902c316045daf7e --- /dev/null +++ b/passport-check/apps/server/build.mjs @@ -0,0 +1,13 @@ +import { build } from 'esbuild'; +await build({ + entryPoints: ['src/index.ts'], + bundle: true, + platform: 'node', + format: 'esm', + target: 'node22', + outfile: 'dist/server.js', + // native / worker-based packages giữ ngoài bundle + external: ['sharp', 'tesseract.js', '@google/genai', 'express', 'express-rate-limit', 'firebase-admin', 'busboy', 'yauzl', 'heic-convert'], + banner: { js: "import { createRequire as __pcCreateRequire } from 'module'; const require = __pcCreateRequire(import.meta.url);" }, + logLevel: 'info', +}); diff --git a/passport-check/apps/server/package.json b/passport-check/apps/server/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3797f2b5d29ea64f6da4fca86db6e85cb7d651ff --- /dev/null +++ b/passport-check/apps/server/package.json @@ -0,0 +1,29 @@ +{ + "name": "@pc/server", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "node --watch --env-file-if-exists=../../.env --import tsx src/index.ts", + "build": "node build.mjs" + }, + "dependencies": { + "@google/genai": "^3.0.0", + "@pc/core": "*", + "busboy": "^1.6.0", + "express": "^5.3.0", + "express-rate-limit": "^8.7.3", + "firebase-admin": "^14.5.0", + "heic-convert": "^2.1.0", + "sharp": "^0.35.5", + "tesseract.js": "^7.0.0", + "yauzl": "^3.4.0" + }, + "devDependencies": { + "@types/busboy": "^1.5.5", + "@types/express": "^5", + "@types/yauzl": "^3.4.0", + "esbuild": "^0.28.2", + "tsx": "^4.23.15" + } +} diff --git a/passport-check/apps/server/src/auth.ts b/passport-check/apps/server/src/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee825a4959754197146ed75562a074a0e9e191b7 --- /dev/null +++ b/passport-check/apps/server/src/auth.ts @@ -0,0 +1,54 @@ +/** + * Xác thực request vào backend: + * 1. `x-api-key` = BACKEND_API_KEY — chỉ server Next.js biết khoá này, nên trình duyệt / người ngoài không gọi thẳng + * được backend (kể cả khi URL Space công khai). + * 2. `Authorization: Bearer ` — token do /api/auth/login cấp, Next.js giữ trong cookie httpOnly. + */ +import crypto from 'node:crypto'; +import type { NextFunction, Request, Response } from 'express'; +import { hasCostAccess, userFromToken, type Role } from './users.ts'; + +export interface User { uid: string; email: string; name?: string; role: Role; costAccess: boolean } +declare module 'express-serve-static-core' { + interface Request { user?: User } +} + +const API_KEY = process.env.BACKEND_API_KEY ?? ''; +export const apiKeyConfigured = () => API_KEY.length >= 32; + +function keyOk(got: string | undefined): boolean { + if (!got || !apiKeyConfigured()) return false; + const a = crypto.createHash('sha256').update(got).digest(); + const b = crypto.createHash('sha256').update(API_KEY).digest(); + return crypto.timingSafeEqual(a, b); +} + +/** Chỉ cho server Next.js (có BACKEND_API_KEY) gọi vào */ +export function requireApiKey(req: Request, res: Response, next: NextFunction) { + if (!apiKeyConfigured()) return void res.status(503).json({ error: 'Backend chưa cấu hình BACKEND_API_KEY (>= 32 ký tự)' }); + if (!keyOk(req.get('x-api-key'))) return void res.status(401).json({ error: 'Sai API key', code: 'bad_api_key' }); + next(); +} + +/** IP thật của người dùng (Next.js chuyển tiếp qua `x-client-ip`; chỉ tin vì request đã qua API key) */ +export const clientIp = (req: Request) => req.get('x-client-ip') || req.ip || ''; + +export function requireUser(req: Request, res: Response, next: NextFunction) { + const token = /^Bearer (.+)$/.exec(req.get('authorization') ?? '')?.[1]; + if (!token) return void res.status(401).json({ error: 'Chưa đăng nhập', code: 'unauthenticated' }); + const u = userFromToken(token); + if (!u) return void res.status(401).json({ error: 'Phiên đăng nhập hết hạn, hãy đăng nhập lại', code: 'unauthenticated' }); + req.user = { uid: u.id, email: u.email, name: u.name || undefined, role: u.role, costAccess: hasCostAccess(u) }; + next(); +} + +export function requireAdmin(req: Request, res: Response, next: NextFunction) { + if (req.user?.role !== 'admin') return void res.status(403).json({ error: 'Chỉ admin mới làm được việc này', code: 'forbidden' }); + next(); +} + +/** Trang Chi phí Gemini: admin hoặc user được cấp quyền */ +export function requireCostAccess(req: Request, res: Response, next: NextFunction) { + if (!req.user?.costAccess) return void res.status(403).json({ error: 'Bạn chưa được cấp quyền xem chi phí', code: 'forbidden' }); + next(); +} diff --git a/passport-check/apps/server/src/cost-settings.ts b/passport-check/apps/server/src/cost-settings.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d7956509deb89dbefa5af449ae67ffbf084f9cb --- /dev/null +++ b/passport-check/apps/server/src/cost-settings.ts @@ -0,0 +1,59 @@ +/** + * Đơn giá & cách tính trên trang Chi phí Gemini — dùng chung cho mọi người (Firestore `settings/cost`). + * Ai có quyền xem trang chi phí đều đọc được; chỉ admin sửa được. + * Chưa ai lưu -> null, trang chi phí dùng giá mặc định của model. + */ +import { db } from './firebase.ts'; + +export type CostBasis = 'all' | 'sent'; +export interface CostSettings { + input: number; + output: number; + thinking: number; + rate: number; + basis: CostBasis; + updatedAt: number; + updatedBy: string; +} + +const ref = () => db().collection('settings').doc('cost'); +let cache: CostSettings | null | undefined; + +export async function getCostSettings(): Promise { + if (cache === undefined) { + const snap = await ref().get(); + cache = snap.exists ? (snap.data() as CostSettings) : null; + } + return cache; +} + +const httpError = (message: string) => Object.assign(new Error(message), { status: 400 }); + +function num(x: unknown, label: string, max: number): number { + if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > max) throw httpError(`${label} không hợp lệ (0 – ${max.toLocaleString('vi-VN')})`); + return x; +} + +/** body = null -> xoá, về giá mặc định */ +export async function saveCostSettings(body: unknown, by: string): Promise { + if (body === null) { + await ref().delete(); + cache = null; + return null; + } + if (!body || typeof body !== 'object') throw httpError('Dữ liệu không hợp lệ'); + const o = body as Record; + if (o.basis !== 'all' && o.basis !== 'sent') throw httpError('Cách tính không hợp lệ'); + const s: CostSettings = { + input: num(o.input, 'Giá input', 10_000), + output: num(o.output, 'Giá output', 10_000), + thinking: Math.round(num(o.thinking, 'Token thinking', 1_000_000)), + rate: num(o.rate, 'Tỷ giá', 1_000_000), + basis: o.basis, + updatedAt: Date.now(), + updatedBy: by, + }; + await ref().set(s); + cache = s; + return s; +} diff --git a/passport-check/apps/server/src/firebase.ts b/passport-check/apps/server/src/firebase.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ebe8038a2c6f722a11609ffe4d7a35ef4cd7e4d --- /dev/null +++ b/passport-check/apps/server/src/firebase.ts @@ -0,0 +1,43 @@ +/** + * Firebase Admin: Firestore (lô, khách, người dùng) + xác minh ID token đăng nhập Google (Firebase Auth). + * Phiên đăng nhập do backend tự cấp — xem users.ts. + * + * Biến môi trường: + * - FIREBASE_SERVICE_ACCOUNT: JSON service account (nguyên văn hoặc base64) + * - Chạy emulator: FIRESTORE_EMULATOR_HOST, FIREBASE_AUTH_EMULATOR_HOST, GCLOUD_PROJECT + */ +import { cert, initializeApp, type App } from 'firebase-admin/app'; +import { getFirestore, type Firestore } from 'firebase-admin/firestore'; + +let app: App | null = null; +let firestore: Firestore | null = null; + +function parseJson(raw: string): Record { + const s = raw.trim(); + return JSON.parse(s.startsWith('{') ? s : Buffer.from(s, 'base64').toString('utf8')); +} + +const emulator = !!process.env.FIRESTORE_EMULATOR_HOST; + +export function firebaseConfigured(): boolean { + return emulator || !!process.env.FIREBASE_SERVICE_ACCOUNT; +} + +export function fbApp(): App { + if (app) return app; + if (emulator) { + app = initializeApp({ projectId: process.env.GCLOUD_PROJECT ?? 'demo-passport-check' }); + } else { + if (!process.env.FIREBASE_SERVICE_ACCOUNT) throw new Error('Chưa cấu hình FIREBASE_SERVICE_ACCOUNT'); + app = initializeApp({ credential: cert(parseJson(process.env.FIREBASE_SERVICE_ACCOUNT) as never) }); + } + return app; +} + +export function db(): Firestore { + if (!firestore) { + firestore = getFirestore(fbApp()); + firestore.settings({ ignoreUndefinedProperties: true }); + } + return firestore; +} diff --git a/passport-check/apps/server/src/gemini.ts b/passport-check/apps/server/src/gemini.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf27f4f08250682e038f944279d36893427d4d74 --- /dev/null +++ b/passport-check/apps/server/src/gemini.ts @@ -0,0 +1,98 @@ +/** + * Tầng leo thang LLM: gửi ảnh cho Gemini, ép đầu ra theo JSON schema. + * Kết quả KHÔNG được tin trực tiếp — client/core sẽ kiểm checksum MRZ và đối chiếu lại. + */ +import { GoogleGenAI } from '@google/genai'; +import type { LlmOutput } from '@pc/core'; + +const MODEL = process.env.GEMINI_MODEL || 'gemini-3.1-flash-lite'; +let client: GoogleGenAI | null = null; + +export function llmAvailable() { + return !!process.env.GEMINI_API_KEY; +} +export function llmModel() { + return MODEL; +} + +function ai() { + if (!client) client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); + return client; +} + +const str = (description: string) => ({ type: 'string', description }); + +export const SCHEMA = { + type: 'object', + properties: { + isPassport: { type: 'boolean', description: 'true nếu ảnh là trang thông tin của hộ chiếu / giấy tờ có MRZ' }, + mrzLines: { + type: 'array', items: { type: 'string' }, + description: 'Các dòng MRZ chép CHÍNH XÁC từng ký tự như in trên ảnh (mỗi dòng 44 ký tự với hộ chiếu), giữ nguyên ký tự <. Không tự sửa. Mảng rỗng nếu không thấy MRZ.', + }, + documentCode: str('Loại giấy tờ in ở ô Type trên vùng chữ, VD P, PP, PD'), + issuingState: str('Mã quốc gia cấp 3 chữ cái (ICAO)'), + surname: str('Họ, theo chữ Latin như in trên trang'), + givenNames: str('Tên, theo chữ Latin như in trên trang'), + fullNameNative: str('Họ tên đầy đủ như in trên vùng chữ, GIỮ NGUYÊN dấu / chữ gốc (VD: NGUYỄN VĂN AN). Rỗng nếu không có.'), + documentNumber: str('Số hộ chiếu in trên vùng chữ'), + nationality: str('Quốc tịch, mã 3 chữ cái nếu có, nếu không thì như in'), + birthDate: str('Ngày sinh dạng YYYY-MM-DD'), + sex: str('M, F hoặc X'), + placeOfBirth: str('Nơi sinh như in trên trang (giữ dấu). Nếu in song ngữ "bản địa/Latin" (VD 江苏/JIANGSU) thì chỉ lấy phần Latin'), + placeOfIssue: str('Nơi cấp như in trên trang (nếu có). Nếu in song ngữ thì chỉ lấy phần Latin'), + issueDate: str('Ngày cấp dạng YYYY-MM-DD'), + expiryDate: str('Ngày hết hạn dạng YYYY-MM-DD'), + authority: str('Cơ quan cấp như in trên trang'), + personalNumber: str('Số cá nhân / số định danh nếu có'), + notes: str('Ghi chú ngắn nếu ảnh mờ, bị che, hoặc trường nào không chắc chắn'), + }, + required: ['isPassport', 'mrzLines'], +}; + +const PROMPT = `Bạn là hệ thống trích xuất dữ liệu hộ chiếu. Đọc ảnh và trả JSON theo schema. +Quy tắc: +- Chỉ ghi những gì THẤY rõ trên ảnh. Trường không đọc được thì để chuỗi rỗng. Tuyệt đối không đoán hay bịa. +- MRZ: chép nguyên văn từng ký tự, kể cả ký tự '<'. Không sửa cho khớp check digit. +- Phân biệt kỹ 0/O, 1/I, 5/S, 8/B, 2/Z trong MRZ: trong số hộ chiếu, ngày tháng và check digit hầu như là chữ số. +- Ngày tháng chuyển về YYYY-MM-DD (lưu ý định dạng ngày/tháng/năm và tên tháng nhiều ngôn ngữ). +- Ảnh có thể bị xoay, nghiêng, chói hoặc chụp kèm trang khác — hãy tìm trang thông tin cá nhân.`; + +export const promptText = (hint?: string) => (hint ? `${PROMPT}\n\nGợi ý từ OCR local (có thể sai): ${hint}` : PROMPT); +const GEN_CONFIG = { temperature: 0, responseMimeType: 'application/json', responseJsonSchema: SCHEMA }; + +/** Nội dung gửi Gemini — dùng chung cho trích xuất và đếm token để số đếm khớp request thật */ +function contents(image: Buffer | null, mimeType: string, hint?: string) { + return [{ + role: 'user', + parts: [ + ...(image ? [{ inlineData: { mimeType, data: image.toString('base64') } }] : []), + { text: promptText(hint) }, + ], + }]; +} + +/** Gọi Gemini, tự thử lại khi 429 / 5xx */ +async function withRetry(fn: () => Promise): Promise { + let lastErr: unknown; + for (let attempt = 0; attempt < 4; attempt++) { + try { + return await fn(); + } catch (e: any) { + lastErr = e; + const status = e?.status ?? e?.code; + // 429 (hết quota free) / 5xx -> chờ rồi thử lại + if (status === 429 || (status >= 500 && status < 600)) { + await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt)); + continue; + } + throw e; + } + } + throw lastErr; +} + +export async function geminiExtract(image: Buffer, mimeType: string, hint?: string): Promise { + const res = await withRetry(() => ai().models.generateContent({ model: MODEL, contents: contents(image, mimeType, hint), config: GEN_CONFIG })); + return JSON.parse(res.text ?? '') as LlmOutput; +} diff --git a/passport-check/apps/server/src/heic-convert.d.ts b/passport-check/apps/server/src/heic-convert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..659200add475b5222c84a4e3e109ec3e20ca4969 --- /dev/null +++ b/passport-check/apps/server/src/heic-convert.d.ts @@ -0,0 +1,4 @@ +declare module 'heic-convert' { + function convert(opts: { buffer: ArrayBuffer | Uint8Array; format: 'JPEG' | 'PNG'; quality?: number }): Promise; + export default convert; +} diff --git a/passport-check/apps/server/src/index.ts b/passport-check/apps/server/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a536cad593ff43544d21a4f02d7b5fd1f8f9b6d --- /dev/null +++ b/passport-check/apps/server/src/index.ts @@ -0,0 +1,413 @@ +import path from 'node:path'; +import fs from 'node:fs'; +import express, { type NextFunction, type Request, type Response } from 'express'; +import rateLimit from 'express-rate-limit'; +import { + bpFileName, bpRows, customerRow, dvcFileName, dvcRows, effectiveTrip, fillTemplate, sortMaleFirst, vnDate, + type BatchSettings, type CustomerRow, type ExportEntry, type ExtractionResult, type LlmPolicy, type TripInfo, +} from '@pc/core'; +import { llmAvailable, llmModel } from './gemini.ts'; +import { shutdownOcr } from './ocr.ts'; +import { firebaseConfigured } from './firebase.ts'; +import { apiKeyConfigured, clientIp, requireAdmin, requireApiKey, requireCostAccess, requireUser } from './auth.ts'; +import { getCostSettings, saveCostSettings } from './cost-settings.ts'; +import { authConfigured, changeOwnPassword, createUser, deleteUser, listUsers, loadUsers, login, loginGoogle, updateUser, usersReady } from './users.ts'; +import { telegramConfigured } from './telegram.ts'; +import { batchTokens, currentRule, fixedTokens, formulaInfo, itemTokens, usageReport } from './tokens.ts'; +import { receiveUpload } from './upload.ts'; +import { + allItems, batchById, cacheReady, createBatch, deleteItem, getBatch, getItem, ingest, listBatches, listItems, liveStatus, loadOriginal, recover, + knownHashes, rerun, rerunMany, saveEdit, updateBatchInfo, +} from './jobs.ts'; + +const PORT = Number(process.env.PORT ?? 7860); +const here = path.dirname(new URL(import.meta.url).pathname); +const TEMPLATE_DIR = process.env.TEMPLATE_DIR ?? path.resolve(here, '../templates'); +const missing = [ + !firebaseConfigured() && 'FIREBASE_SERVICE_ACCOUNT', + !telegramConfigured() && 'TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID', + !authConfigured() && 'AUTH_SECRET (>= 32 ký tự)', + !apiKeyConfigured() && 'BACKEND_API_KEY (>= 32 ký tự)', +].filter((x): x is string => !!x); +const ready = !missing.length; + +const app = express(); +app.disable('x-powered-by'); +app.set('trust proxy', 1); // HF Spaces đứng sau reverse proxy + +// mọi request đều đi qua server Next.js -> đếm theo IP thật của người dùng do Next chuyển tiếp +const limiter = rateLimit({ + windowMs: 60_000, limit: Number(process.env.RATE_LIMIT ?? 600), standardHeaders: 'draft-8', legacyHeaders: false, + keyGenerator: (req) => clientIp(req), validate: { keyGeneratorIpFallback: false }, +}); +// chống dò mật khẩu: 10 lần / 15 phút cho mỗi cặp IP + email +const loginLimiter = rateLimit({ + windowMs: 15 * 60_000, limit: 10, standardHeaders: 'draft-8', legacyHeaders: false, skipSuccessfulRequests: true, + keyGenerator: (req) => `${clientIp(req)}|${String(req.body?.email ?? '').toLowerCase()}`, validate: { keyGeneratorIpFallback: false }, + message: { error: 'Đăng nhập sai quá nhiều lần, hãy thử lại sau 15 phút' }, +}); +const json = express.json({ limit: '2mb' }); + +/** bọc handler async: lỗi có `status` -> trả đúng mã, còn lại 500 (không lộ chi tiết nội bộ) */ +const h = (fn: (req: Request, res: Response) => Promise) => (req: Request, res: Response, next: NextFunction) => + fn(req, res).catch((e) => { + if (e?.status && e.status < 500) return void res.status(e.status).json({ error: e.message, code: e.code }); + console.error(req.method, req.path, e?.message ?? e); + if (!res.headersSent) res.status(500).json({ error: 'Lỗi server' }); + else next(e); + }); + +function notReady(_req: Request, res: Response, next: NextFunction) { + if (!ready) return void res.status(503).json({ error: `Backend chưa cấu hình: ${missing.join(', ')}` }); + const loading = cacheReady(); + if (!loading) return void res.status(503).json({ error: 'Server đang khởi động, thử lại sau giây lát' }); + // lần đọc bảng user trước lỗi (mạng / Firestore) -> thử đọc lại + const users = usersReady() ?? loadUsers(); + Promise.all([loading, users]).then(() => next(), () => res.status(503).json({ error: 'Server không đọc được dữ liệu Firebase' })); +} + +/** Kiểm tra thông tin chuyến đi gửi lên; ô có giá trị sai -> lỗi 400 (không lặng lẽ bỏ qua) */ +function parseTrip(x: unknown): TripInfo | undefined { + if (x === undefined || x === null) return undefined; + if (typeof x !== 'object') throw Object.assign(new Error('Thông tin chuyến đi không hợp lệ'), { status: 400 }); + const o = x as Record; + const errors: string[] = []; + const has = (k: string) => o[k] !== undefined && o[k] !== null; + const str = (k: string, label: string, max = 200) => { + if (!has(k)) return undefined; + if (typeof o[k] !== 'string') { errors.push(label); return undefined; } + return (o[k] as string).trim().slice(0, max); + }; + const bool = (k: string, label: string) => { + if (!has(k)) return undefined; + if (typeof o[k] !== 'boolean') { errors.push(label); return undefined; } + return o[k] as boolean; + }; + const entryDate = str('entryDate', 'Ngày nhập cảnh', 10); + if (entryDate && !/^\d{4}-\d{2}-\d{2}$/.test(entryDate)) errors.push('Ngày nhập cảnh (cần YYYY-MM-DD)'); + let stayDays: number | undefined; + if (has('stayDays')) { + if (typeof o.stayDays === 'number' && Number.isInteger(o.stayDays) && o.stayDays >= 1 && o.stayDays <= 365) stayDays = o.stayDays; + else errors.push('Số ngày lưu trú (1–365)'); + } + const t: TripInfo = { + groupCode: str('groupCode', 'Phân tách khách hàng', 60), entryDate, stayDays, multipleEntry: bool('multipleEntry', 'Nhập cảnh nhiều lần'), + visaType: str('visaType', 'Cách nhận thị thực'), receivePlace: str('receivePlace', 'Nơi nhận visa'), purpose: str('purpose', 'Mục đích'), + vip: bool('vip', 'Vào cửa VIP'), urgent: bool('urgent', 'Khẩn'), authority: str('authority', 'Cơ quan cấp'), + direction: str('direction', 'Hướng hành trình'), occupation: str('occupation', 'Nghề nghiệp', 60), + }; + if (errors.length) throw Object.assign(new Error(`Giá trị không hợp lệ: ${errors.join(', ')}`), { status: 400 }); + return t; +} + +const LLM_POLICIES: LlmPolicy[] = ['off', 'low', 'review', 'all']; + +// health check cho HF Space (không lộ thông tin gì) +app.get('/', (_req, res) => void res.type('text').send('passport-check backend')); +app.get(['/health', '/healthz'], (_req, res) => void res.json({ ok: true, ready, uptime: Math.round(process.uptime()) })); + +const pub = express.Router(); + +pub.get('/config', (_req, res) => { + res.json({ ready, missing, llmAvailable: llmAvailable(), model: llmModel() }); +}); + +pub.post('/auth/login', json, notReady, loginLimiter, h(async (req, res) => { + res.json(await login(req.body?.email, req.body?.password)); +})); +pub.post('/auth/google', json, notReady, h(async (req, res) => { + res.json(await loginGoogle(req.body?.idToken)); +})); + +const api = express.Router(); +api.use(notReady, requireUser); + +api.get('/me', (req, res) => res.json(req.user)); + +/** Tự đổi mật khẩu -> token mới (phiên ở thiết bị khác bị đăng xuất) */ +api.post('/me/password', json, h(async (req, res) => { + res.json(await changeOwnPassword(req.user!.uid, req.body?.current, req.body?.password)); +})); + +/* ---------------------------------------------------------- quản lý người dùng (admin) */ + +api.get('/users', requireAdmin, (_req, res) => void res.json(listUsers())); +api.post('/users', requireAdmin, json, h(async (req, res) => { + res.json(await createUser(req.body ?? {}, req.user!.email)); +})); +api.patch('/users/:uid', requireAdmin, json, h(async (req, res) => { + const uid = String(req.params.uid); + // tự khoá / tự hạ quyền mình dễ gây mất quyền admin -> chặn + if (uid === req.user!.uid && (req.body?.disabled === true || req.body?.role === 'user')) { + return void res.status(400).json({ error: 'Không thể tự khoá hoặc tự hạ quyền tài khoản của mình' }); + } + res.json(await updateUser(uid, req.body ?? {})); +})); +api.delete('/users/:uid', requireAdmin, h(async (req, res) => { + await deleteUser(String(req.params.uid), req.user!.uid); + res.json({ ok: true }); +})); + +api.get('/batches', h(async (_req, res) => res.json(await listBatches()))); + +api.post('/batches', json, h(async (req, res) => { + const name = String(req.body?.name ?? '').trim().slice(0, 120) || `Lô ${new Date().toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' })}`; + const llm = LLM_POLICIES.includes(req.body?.settings?.llm) ? req.body.settings.llm : 'low'; + const settings: BatchSettings = { llm }; + res.json(await createBatch(name, settings, { uid: req.user!.uid, email: req.user!.email })); +})); + +async function batchOr404(id: string) { + const b = await getBatch(id); + if (!b) throw Object.assign(new Error('Không tìm thấy lô'), { status: 404 }); + return b; +} + +api.patch('/batches/:bid', json, h(async (req, res) => { + const name = typeof req.body?.name === 'string' ? req.body.name.trim().slice(0, 120) : undefined; + const trip = parseTrip(req.body?.trip); + res.json(await updateBatchInfo(String(req.params.bid), { ...(name ? { name } : {}), ...(trip ? { trip } : {}) })); +})); + +api.get('/batches/:bid', h(async (req, res) => { + res.json({ batch: await batchOr404(String(req.params.bid)), live: liveStatus(String(req.params.bid)) }); +})); + +// Upload ảnh / zip (multipart). Có thể gọi nhiều lần cho cùng 1 lô. +api.post('/batches/:bid/files', h(async (req, res) => { + const bid = String(req.params.bid); + await batchOr404(bid); + const stats = { added: 0, reused: 0, duplicates: [] as string[], again: [] as string[] }; + const reocr = req.query.reocr === '1'; // ảnh trùng đã có kết quả: OCR lại thay vì dùng kết quả cũ + const up = await receiveUpload(req, async (files) => { + const r = await ingest(bid, req.user!.email, files, reocr); + stats.added += r.added; + stats.reused += r.reused; + stats.duplicates.push(...r.duplicates); + stats.again.push(...r.again); + }); + res.json({ ...stats, skipped: up.skipped }); +})); + +api.get('/batches/:bid/items', h(async (req, res) => { + const since = Number(req.query.since ?? 0) || 0; + const now = Date.now(); + // trả kèm mốc thời gian server để client hỏi tiếp từ đó (trừ lùi 2s phòng lệch giờ ghi) + res.json({ items: await listItems(String(req.params.bid), since), next: now - 2000, live: liveStatus(String(req.params.bid)) }); +})); + +async function itemOr404(bid: string, iid: string) { + const it = await getItem(bid, iid); + if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); + return it; +} + +api.get('/batches/:bid/items/:iid', h(async (req, res) => res.json(await itemOr404(String(req.params.bid), String(req.params.iid))))); + +api.get('/batches/:bid/items/:iid/image', h(async (req, res) => { + const it = await itemOr404(String(req.params.bid), String(req.params.iid)); + const buf = await loadOriginal(it); + res.set({ 'content-type': it.mime, 'cache-control': 'private, max-age=86400', 'content-disposition': `inline; filename*=UTF-8''${encodeURIComponent(path.basename(it.name))}` }); + res.send(buf); +})); + +api.patch('/batches/:bid/items/:iid', json, h(async (req, res) => { + const result = req.body?.result as ExtractionResult | undefined; + if (result && (!result.record || !['HIGH', 'MEDIUM', 'LOW'].includes(result.confidence))) return void res.status(400).json({ error: 'Dữ liệu không hợp lệ' }); + const trip = parseTrip(req.body?.trip); + res.json(await saveEdit(String(req.params.bid), String(req.params.iid), { result, trip }, req.user!.email)); +})); + +api.post('/batches/:bid/items/:iid/rerun', json, h(async (req, res) => { + const force = req.body?.mode === 'llm' ? 'llm' : 'ocr'; + if (force === 'llm' && !llmAvailable()) return void res.status(501).json({ error: 'Server chưa cấu hình GEMINI_API_KEY' }); + await rerun(String(req.params.bid), String(req.params.iid), force); + res.json({ ok: true }); +})); + +// Kiểm tra trước khi upload: ảnh nào (theo sha256) đã có kết quả -> hỏi người dùng có OCR lại không +api.post('/batches/:bid/known', json, h(async (req, res) => { + const bid = String(req.params.bid); + await batchOr404(bid); + const list = Array.isArray(req.body?.hashes) ? (req.body.hashes as unknown[]).filter((x): x is string => typeof x === 'string').slice(0, 5000) : []; + res.json({ known: await knownHashes(bid, list) }); +})); + +// OCR lại hàng loạt (VD: ảnh trùng vừa upload mà người dùng muốn xử lý lại) +api.post('/batches/:bid/rerun', json, h(async (req, res) => { + const bid = String(req.params.bid); + await batchOr404(bid); + const ids = Array.isArray(req.body?.ids) ? [...new Set((req.body.ids as unknown[]).filter((x): x is string => typeof x === 'string'))].slice(0, 5000) : []; + res.json(await rerunMany(bid, ids)); +})); + +/* ---------------------------------------------------------- ước lượng token Gemini (tự tính theo kích thước ảnh, không gọi API) */ + +// Mọi lô, gộp theo ngày upload (giờ VN) + theo lô; trang chi phí tự gộp tuần / tháng / quý / năm và nhân đơn giá +api.get('/tokens/usage', requireCostAccess, h(async (_req, res) => res.json(await usageReport(allItems(), batchById)))); + +// Đơn giá & cách tính dùng chung: ai xem được trang chi phí thì đọc, chỉ admin sửa (body null = về mặc định) +api.get('/cost-settings', requireCostAccess, h(async (_req, res) => res.json({ settings: await getCostSettings() }))); +api.put('/cost-settings', requireAdmin, json, h(async (req, res) => { + res.json({ settings: await saveCostSettings(req.body?.settings, req.user!.email) }); +})); + +// Theo lô: tổng + chi tiết từng ảnh +api.get('/batches/:bid/tokens', h(async (req, res) => { + const bid = String(req.params.bid); + const batch = await batchOr404(bid); + res.json({ batchId: bid, batchName: batch.name, ...(await batchTokens(await listItems(bid))) }); +})); + +// Chi tiết 1 ảnh (kèm JSON đầu ra dùng để đếm) +api.get('/batches/:bid/items/:iid/tokens', h(async (req, res) => { + const it = await itemOr404(String(req.params.bid), String(req.params.iid)); + const rule = currentRule(); + res.json({ formula: formulaInfo(rule), ...(await itemTokens(it, rule, await fixedTokens(), true)) }); +})); + +api.delete('/batches/:bid/items/:iid', h(async (req, res) => { + await deleteItem(String(req.params.bid), String(req.params.iid)); + res.json({ ok: true }); +})); + +/* ---------------------------------------------------------- danh sách khách mọi đoàn */ + +const customerRows = (): CustomerRow[] => allItems().map((it) => customerRow(it, batchById(it.batchId))); + +const norm = (s: string) => s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/đ/g, 'd'); +const DISPLAY: Partial string>> = { + birthDate: (r) => vnDate(r.birthDate), entryDate: (r) => vnDate(r.entryDate), exitDate: (r) => vnDate(r.exitDate), + expiryDate: (r) => vnDate(r.expiryDate), issueDate: (r) => vnDate(r.issueDate), + createdAt: (r) => new Date(r.createdAt).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' }), + sex: (r) => (r.sex === 'M' ? 'Nam' : r.sex === 'F' ? 'Nữ' : r.sex), urgent: (r) => (r.urgent ? 'Có' : 'Không'), + vip: (r) => (r.vip ? 'Có' : 'Không'), multipleEntry: (r) => (r.multipleEntry ? 'Nhiều lần' : 'Một lần'), +}; +const display = (r: CustomerRow, k: keyof CustomerRow) => (DISPLAY[k] ? DISPLAY[k]!(r) : String(r[k] ?? '')); + +/** Lọc theo query: q (tìm chung), f.=chuỗi con, flag=warn|review|urgent */ +function filterRows(rows: CustomerRow[], q: Record): CustomerRow[] { + const text = typeof q.q === 'string' ? norm(q.q.trim()) : ''; + const cols = Object.entries(q).filter(([k, v]) => k.startsWith('f.') && typeof v === 'string' && v.trim()) + .map(([k, v]) => [k.slice(2) as keyof CustomerRow, norm(String(v).trim())] as const); + const flag = String(q.flag ?? ''); + return rows.filter((r) => { + if (flag === 'warn' && !r.under6Months) return false; + if (flag === 'review' && !(r.needsReview || r.status === 'error' || r.missing.length)) return false; + if (flag === 'urgent' && !r.urgent) return false; + if (text && !norm(`${r.name} ${r.documentNumber} ${r.groupCode} ${r.batchName} ${r.file}`).includes(text)) return false; + return cols.every(([k, v]) => norm(display(r, k)).includes(v)); + }); +} + +api.get('/customers', h(async (req, res) => { + let rows = filterRows(customerRows(), req.query as Record); + const sort = String(req.query.sort ?? 'createdAt') as keyof CustomerRow; + const dir = req.query.dir === 'asc' ? 1 : -1; + rows = rows.sort((a, b) => { + const x = a[sort] ?? ''; + const y = b[sort] ?? ''; + return (x < y ? -1 : x > y ? 1 : 0) * dir || (b.createdAt - a.createdAt); + }); + const size = Math.min(500, Math.max(10, Number(req.query.size ?? 100) || 100)); + const pages = Math.max(1, Math.ceil(rows.length / size)); + const page = Math.min(pages, Math.max(1, Number(req.query.page ?? 1) || 1)); + const groups = [...new Set(customerRows().map((r) => r.groupCode).filter(Boolean))].sort(); + res.json({ + rows: rows.slice((page - 1) * size, page * size), total: rows.length, page, pages, size, groups, + // id của toàn bộ dòng khớp bộ lọc (để "chọn tất cả theo bộ lọc") + allIds: req.query.ids === '1' ? rows.map((r) => r.id) : undefined, + }); +})); + +/** Xoá nhiều khách */ +api.post('/customers/delete', json, h(async (req, res) => { + const ids: string[] = Array.isArray(req.body?.ids) ? req.body.ids.filter((x: unknown) => typeof x === 'string').slice(0, 2000) : []; + const byId = new Map(allItems().map((i) => [i.id, i])); + const failed: string[] = []; + for (const id of ids) { + const it = byId.get(id); + if (!it) continue; + try { await deleteItem(it.batchId, id); } catch (e) { failed.push(`${it.result?.record.documentNumber || it.name}: ${(e as Error).message}`); } + } + res.json({ deleted: ids.length - failed.length, failed }); +})); + +/* ---------------------------------------------------------- xuất file nộp hồ sơ */ + +function template(name: string): Buffer { + const f = path.join(TEMPLATE_DIR, name); + if (!fs.existsSync(f)) throw new Error(`Thiếu file mẫu ${name}`); + return fs.readFileSync(f); +} + +function exportEntries(ids: unknown): { entries: ExportEntry[]; skipped: string[] } { + const list: string[] = Array.isArray(ids) ? ids.filter((x): x is string => typeof x === 'string').slice(0, 5000) : []; + const byId = new Map(allItems().map((i) => [i.id, i])); + const entries: ExportEntry[] = []; + const skipped: string[] = []; + for (const id of list) { + const it = byId.get(id); + if (!it) continue; + const rec = it.result?.record; + if (it.status !== 'done' || !rec) { skipped.push(it.name); continue; } + entries.push({ item: it, rec, trip: effectiveTrip(batchById(it.batchId), it) }); + } + // thứ tự ổn định theo thời gian upload trước khi xếp Nam/Nữ + entries.sort((a, b) => a.item.createdAt - b.item.createdAt || a.item.name.localeCompare(b.item.name)); + return { entries, skipped }; +} + +/** Kiểm tra trước khi xuất: thiếu trường bắt buộc, hộ chiếu còn hạn dưới 6 tháng, ảnh chưa xử lý xong */ +api.post('/export/check', json, h(async (req, res) => { + const { entries, skipped } = exportEntries(req.body?.ids); + const rows = entries.map((e) => customerRow(e.item, batchById(e.item.batchId))); + res.json({ + count: entries.length, + male: entries.filter((e) => e.rec.sex === 'M').length, + female: entries.filter((e) => e.rec.sex === 'F').length, + skipped, + missing: rows.filter((r) => r.missing.length).map((r) => ({ id: r.id, batchId: r.batchId, name: r.name || r.file, fields: r.missing })), + under6: rows.filter((r) => r.under6Months).map((r) => ({ id: r.id, batchId: r.batchId, name: r.name, expiryDate: r.expiryDate, entryDate: r.entryDate, expired: r.expired })), + groupCodes: [...new Set(entries.map((e) => e.trip.groupCode).filter(Boolean))], + entryDates: [...new Set(entries.map((e) => e.trip.entryDate).filter(Boolean))], + dvcName: dvcFileName(entries[0]?.trip.groupCode ?? '', entries.length), + bpName: bpFileName(entries[0]?.trip.groupCode ?? '', entries.length, entries[0]?.trip.entryDate), + }); +})); +api.post('/export/:kind', json, h(async (req, res) => { + const kind = String(req.params.kind); + if (kind !== 'dvc' && kind !== 'bp') return void res.status(404).json({ error: 'Không có loại file này' }); + const { entries } = exportEntries(req.body?.ids); + if (!entries.length) return void res.status(400).json({ error: 'Không có khách nào đã xử lý xong để xuất' }); + const sorted = sortMaleFirst(entries); + const bytes = kind === 'dvc' + ? fillTemplate(template('thong-tin-ho-chieu.xlsx'), 'INF_NHAN_SU', dvcRows(sorted)) + : fillTemplate(template('cong-van-bp.xlsx'), 'BP', bpRows(sorted)); + const fallback = kind === 'dvc' ? dvcFileName(entries[0].trip.groupCode ?? '', entries.length) : bpFileName(entries[0].trip.groupCode ?? '', entries.length, entries[0].trip.entryDate); + let name = typeof req.body?.filename === 'string' && req.body.filename.trim() ? req.body.filename.trim().replace(/[\\/:*?"<>|]+/g, '').slice(0, 120) : fallback; + if (!/\.xlsx$/i.test(name)) name += '.xlsx'; + res.set({ + 'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`, + 'cache-control': 'no-store', + }); + res.send(Buffer.from(bytes)); +})); + +app.use('/api', requireApiKey, limiter, pub, api); +app.use((_req, res) => void res.status(404).json({ error: 'Không có API này' })); + +const server = app.listen(PORT, () => { + console.log(`passport-check backend listening on :${PORT}${ready ? '' : ` (thiếu cấu hình: ${missing.join(', ')})`}`); + if (ready) { + loadUsers().catch((e) => console.error('load users error', e?.message ?? e)); + recover().catch((e) => console.error('recover error', e?.message ?? e)); + } +}); +for (const sig of ['SIGINT', 'SIGTERM'] as const) { + process.on(sig, () => { + server.close(); + shutdownOcr().finally(() => process.exit(0)); + }); +} diff --git a/passport-check/apps/server/src/jobs.ts b/passport-check/apps/server/src/jobs.ts new file mode 100644 index 0000000000000000000000000000000000000000..65882908dc335168b4e200e9505792cb58e69fbd --- /dev/null +++ b/passport-check/apps/server/src/jobs.ts @@ -0,0 +1,531 @@ +/** + * Hàng đợi xử lý phía server, trạng thái bền nằm trong Firestore: + * nhận file -> (ổ tạm) -> lưu Telegram [pending -> stored] -> OCR -> (hàng đợi Gemini) [stored -> done] + * Gemini chạy ở hàng đợi riêng: trong lúc chờ Gemini trả lời, worker OCR đã chuyển sang ảnh khác. + * Space khởi động lại: item `stored` được OCR tiếp (ảnh lấy lại từ Telegram); + * item `pending` mất file tạm -> báo lỗi để người dùng upload lại. + * + * Firestore: + * batches/{batchId} lô upload, có bộ đếm kết quả + * batches/{batchId}/items/{itemId} từng ảnh + * hashes/{sha256} chống trùng: ảnh đã lưu Telegram thì dùng lại + * + * Server là nơi DUY NHẤT ghi dữ liệu (trình duyệt bị chặn bởi firestore.rules), nên toàn bộ lô + khách được + * giữ trong RAM: đọc Firestore 1 lần lúc khởi động, sau đó mọi truy vấn / lọc / phân trang chạy trên cache, + * mọi thay đổi ghi Firestore rồi cập nhật cache. Chỉ chạy 1 instance (HF Space) nên cache luôn khớp. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { FieldValue } from 'firebase-admin/firestore'; +import { + EMPTY_COUNTS, itemCounts, mergeResults, reconcile, runPipeline, + type Batch, type BatchSettings, type ExtractionResult, type StoredItem, type TripInfo, +} from '@pc/core'; +import { db } from './firebase.ts'; +import { sendDocument, downloadFile, deleteMessage, type TelegramRef } from './telegram.ts'; +import { INBOX, cacheGet, cachePut, type NormalizedImage } from './media.ts'; +import { loadImage, sharpOps, tessEngine } from './ocr.ts'; +import { geminiExtract, llmAvailable } from './gemini.ts'; + +const OCR_CONCURRENCY = Number(process.env.OCR_CONCURRENCY ?? 1); +/** số lời gọi Gemini chạy cùng lúc (chủ yếu là chờ mạng, không tốn CPU) */ +const LLM_CONCURRENCY = Number(process.env.LLM_CONCURRENCY ?? 2); + +const batches = () => db().collection('batches'); +const items = (batchId: string) => batches().doc(batchId).collection('items'); +const hashes = () => db().collection('hashes'); + +export const newId = () => crypto.randomBytes(10).toString('base64url'); +const inboxPath = (itemId: string) => path.join(INBOX, itemId); + +/* ------------------------------------------------------------------ cache dữ liệu */ + +const batchCache = new Map(); +const itemCache = new Map(); +let loaded: Promise | null = null; + +/** Đọc toàn bộ lô + khách vào RAM (1 lần lúc khởi động) */ +export function loadCache(): Promise { + loaded ??= (async () => { + const t0 = Date.now(); + const [bs, its] = await Promise.all([batches().get(), db().collectionGroup('items').get()]); + for (const d of bs.docs) batchCache.set(d.id, d.data() as Batch); + for (const d of its.docs) itemCache.set(d.id, d.data() as StoredItem); + console.log(`cache: ${batchCache.size} lô, ${itemCache.size} khách (${Date.now() - t0}ms)`); + })().catch((e) => { loaded = null; throw e; }); + return loaded; +} +export const cacheReady = () => loaded; + +/** Ghi thay đổi lô lên Firestore + cache. `inc` = cộng/trừ bộ đếm */ +async function patchBatch(batchId: string, patch: Partial, inc: Partial> = {}) { + const b = batchCache.get(batchId); + const now = Date.now(); + const data: Record = { ...clean(patch), updatedAt: now }; + for (const [k, v] of Object.entries(inc)) if (v) data[`counts.${k}`] = FieldValue.increment(v); + await batches().doc(batchId).update(data); + if (b) { + const counts = { ...b.counts }; + for (const [k, v] of Object.entries(inc)) counts[k as keyof typeof counts] += v ?? 0; + batchCache.set(batchId, { ...b, ...clean(patch), counts, updatedAt: now }); + } +} + +/* ------------------------------------------------------------------ trạng thái trong RAM */ + +type OcrTask = { batchId: string; itemId: string; force?: 'ocr' | 'llm' }; +const tgQueue: { batchId: string; itemId: string }[] = []; +const ocrQueue: OcrTask[] = []; +/** ảnh đã OCR xong, chờ hỏi Gemini (giữ kết quả OCR để gộp) */ +type LlmTask = { batchId: string; itemId: string; result: ExtractionResult; rotation: number; t0: number }; +const llmQueue: LlmTask[] = []; +/** việc còn dở của từng lô (để biết lúc nào lô xong) */ +const outstanding = new Map(); +/** item đang xử lý: bước hiện tại (không ghi Firestore để tiết kiệm quota) */ +const live = new Map(); + +function addOutstanding(batchId: string, n: number) { + outstanding.set(batchId, (outstanding.get(batchId) ?? 0) + n); +} + +async function finishOne(batchId: string) { + const n = (outstanding.get(batchId) ?? 1) - 1; + if (n > 0) return void outstanding.set(batchId, n); + outstanding.delete(batchId); + await patchBatch(batchId, { status: 'done' }).catch(() => undefined); +} + +export function liveStatus(batchId: string) { + const processing = [...live.entries()].filter(([, v]) => v.batchId === batchId).map(([id, v]) => ({ id, step: v.step })); + return { + processing, + waitingTelegram: tgQueue.filter((t) => t.batchId === batchId).length, + waitingOcr: ocrQueue.filter((t) => t.batchId === batchId).length, + waitingLlm: llmQueue.filter((t) => t.batchId === batchId).length, + }; +} + +/* ------------------------------------------------------------------ Firestore helpers */ + +/** Cập nhật item + cộng/trừ bộ đếm của lô theo trạng thái cũ -> mới (ghi nguyên tử 1 batch write) */ +async function updateItem(batchId: string, itemId: string, patch: Partial) { + const old = itemCache.get(itemId); + if (!old) return; + const now = Date.now(); + const p = clean(patch); + const next = { ...old, ...p, updatedAt: now }; + const a = itemCounts(old); + const b = itemCounts(next); + const inc: Record = {}; + for (const k of Object.keys(a) as (keyof typeof a)[]) if (a[k] !== b[k]) inc[k] = b[k] - a[k]; + const wb = db().batch(); + wb.update(items(batchId).doc(itemId), { ...p, updatedAt: now }); + const binc: Record = { updatedAt: now }; + for (const [k, v] of Object.entries(inc)) binc[`counts.${k}`] = FieldValue.increment(v); + wb.update(batches().doc(batchId), binc); + await wb.commit(); + itemCache.set(itemId, next); + const bt = batchCache.get(batchId); + if (bt) { + const counts = { ...bt.counts }; + for (const [k, v] of Object.entries(inc)) counts[k as keyof typeof counts] += v; + batchCache.set(batchId, { ...bt, counts, updatedAt: now }); + } +} + +/** Firestore không nhận undefined lồng sâu / class -> chuyển qua JSON */ +function clean(v: T): T { + return JSON.parse(JSON.stringify(v)); +} + +export async function createBatch(name: string, settings: BatchSettings, user: { uid: string; email: string }): Promise { + const now = Date.now(); + const b: Batch = { id: newId(), name, settings, createdBy: user, createdAt: now, updatedAt: now, status: 'done', counts: { ...EMPTY_COUNTS } }; + await batches().doc(b.id).set(clean(b)); + batchCache.set(b.id, b); + return b; +} + +export async function getBatch(id: string): Promise { + return batchCache.get(id) ?? null; +} + +export async function listBatches(limit = 200): Promise { + return [...batchCache.values()].sort((a, b) => b.createdAt - a.createdAt).slice(0, limit); +} + +/** Item của lô thay đổi sau thời điểm `since` (ms) */ +export async function listItems(batchId: string, since = 0): Promise { + return [...itemCache.values()].filter((i) => i.batchId === batchId && i.updatedAt > since); +} + +export async function getItem(batchId: string, itemId: string): Promise { + const it = itemCache.get(itemId); + return it && it.batchId === batchId ? it : null; +} + +/** Đọc lô từ cache (đồng bộ) */ +export function batchById(id: string): Batch | null { + return batchCache.get(id) ?? null; +} + +/** Toàn bộ khách mọi đoàn (cho trang Danh sách khách) */ +export function allItems(): StoredItem[] { + return [...itemCache.values()]; +} + +/** Sửa thông tin đoàn (tên, mã, chuyến đi) */ +export async function updateBatchInfo(batchId: string, patch: { name?: string; trip?: TripInfo }) { + if (!batchCache.has(batchId)) throw Object.assign(new Error('Không tìm thấy lô'), { status: 404 }); + await patchBatch(batchId, patch); + return batchCache.get(batchId)!; +} + +/* ------------------------------------------------------------------ nhận ảnh */ + +/** `again`: ảnh trùng đã có kết quả (cùng lô hoặc lấy từ lô trước) — người dùng có thể chọn OCR lại */ +export interface IngestOutcome { added: number; duplicates: string[]; reused: number; again: string[] } + +/** + * Thêm các ảnh đã chuẩn hoá vào lô. Ảnh trùng trong cùng lô bị bỏ qua; + * ảnh đã từng lưu (lô khác) thì dùng lại file Telegram + kết quả cũ. + */ +export async function ingest( + batchId: string, user: string, + files: { name: string; size: number; sha256: string; img: NormalizedImage }[], + reocr = false, +): Promise { + const out: IngestOutcome = { added: 0, duplicates: [], reused: 0, again: [] }; + const now = Date.now(); + const writes: { item: StoredItem; buf?: Buffer }[] = []; + const seen = new Set(); + for (const f of files) { + // trùng trong cùng lô (cùng request, hoặc đã upload trước đó vào lô này) + if (seen.has(f.sha256)) { out.duplicates.push(f.name); continue; } + seen.add(f.sha256); + const same = [...itemCache.values()].find((i) => i.batchId === batchId && i.sha256 === f.sha256); + if (same) { + out.duplicates.push(f.name); + if ((same.status === 'done' || same.status === 'error') && same.telegram && !out.again.includes(same.id)) { + // người dùng đã chọn OCR lại ảnh trùng -> xử lý lại luôn ảnh đã có trong lô + if (reocr) await rerun(batchId, same.id, 'ocr').catch(() => undefined); + else out.again.push(same.id); + } + continue; + } + const h = await hashes().doc(f.sha256).get(); + const prev = h.exists ? (h.data() as { batchId: string; itemId: string; telegram: TelegramRef }) : null; + const item: StoredItem = { + id: newId(), batchId, name: f.name, size: f.size, mime: f.img.mime, sha256: f.sha256, + status: 'pending', thumb: f.img.thumb, width: f.img.width, height: f.img.height, + uploadedBy: user, createdAt: now, updatedAt: now, + }; + if (prev) { + // ảnh đã có trên Telegram: không gửi lại; lấy kết quả cũ nếu đã xử lý xong + const old = await getItem(prev.batchId, prev.itemId); + item.telegram = prev.telegram; + item.duplicateOf = `${prev.batchId}/${prev.itemId}`; + if (!reocr && old?.status === 'done' && old.result) { + Object.assign(item, { status: 'done', result: old.result, confidence: old.confidence, needsReview: old.needsReview, rotation: old.rotation, edited: old.edited }); + out.reused++; + out.again.push(item.id); + } else item.status = 'stored'; + cachePut(prev.telegram.fileUniqueId, f.img.buf); + await hashes().doc(f.sha256).update({ refs: FieldValue.increment(1) }); + } + writes.push({ item, buf: item.status === 'pending' ? f.img.buf : undefined }); + } + if (!writes.length) return out; + + for (const w of writes) if (w.buf) fs.writeFileSync(inboxPath(w.item.id), w.buf); + const counts = { total: 0, done: 0, error: 0, HIGH: 0, MEDIUM: 0, LOW: 0, review: 0 }; + for (let i = 0; i < writes.length; i += 400) { + const wb = db().batch(); + for (const { item } of writes.slice(i, i + 400)) { + wb.set(items(batchId).doc(item.id), clean(item)); + itemCache.set(item.id, clean(item)); + counts.total++; + const c = itemCounts(item); + for (const k of Object.keys(c) as (keyof typeof c)[]) counts[k] += c[k]; + } + await wb.commit(); + } + const work = writes.filter((w) => w.item.status !== 'done'); + await patchBatch(batchId, work.length ? { status: 'running' } : {}, counts); + + for (const { item } of work) { + addOutstanding(batchId, 1); + if (item.status === 'pending') { + tgQueue.push({ batchId, itemId: item.id }); + } else ocrQueue.push({ batchId, itemId: item.id }); + } + out.added = writes.length; + kick(); + return out; +} + +/* ------------------------------------------------------------------ worker */ + +let tgRunning = false; +let ocrRunning = 0; +let llmRunning = 0; + +function kick() { + if (!tgRunning && tgQueue.length) void runTelegram(); + while (ocrRunning < OCR_CONCURRENCY && ocrQueue.length) void runOcr(); + while (llmRunning < LLM_CONCURRENCY && llmQueue.length) void runLlm(); +} + +async function runTelegram() { + tgRunning = true; + try { + while (tgQueue.length) { + const { batchId, itemId } = tgQueue.shift()!; + live.set(itemId, { batchId, step: 'Lưu lên Telegram' }); + try { + const it = await getItem(batchId, itemId); + if (!it) { fs.rmSync(inboxPath(itemId), { force: true }); await finishOne(batchId); continue; } + const buf = fs.readFileSync(inboxPath(itemId)); + const batch = await getBatch(batchId); + const ext = it.mime.split('/')[1]?.replace('jpeg', 'jpg') ?? 'jpg'; + const filename = `${path.basename(it.name).replace(/\.[^.]+$/, '')}.${ext}`; + const ref = await sendDocument(buf, filename, it.mime, `${batch?.name ?? batchId} / ${it.name}\n#${itemId}`); + cachePut(ref.fileUniqueId, buf); + await updateItem(batchId, itemId, { status: 'stored', telegram: ref }); + await hashes().doc(it.sha256).set({ batchId, itemId, telegram: ref, refs: 1, createdAt: Date.now() }); + ocrQueue.push({ batchId, itemId }); + kick(); + } catch (e) { + console.error('telegram error', (e as Error).message); + await updateItem(batchId, itemId, { status: 'error', error: `Không lưu được lên Telegram: ${(e as Error).message}` }).catch(() => undefined); + fs.rmSync(inboxPath(itemId), { force: true }); + await finishOne(batchId); + } finally { + live.delete(itemId); + } + } + } finally { + tgRunning = false; + } +} + +/** Ảnh gốc: ổ tạm -> cache -> tải lại từ Telegram */ +export async function loadOriginal(it: StoredItem): Promise { + try { return fs.readFileSync(inboxPath(it.id)); } catch { /* không có trong inbox */ } + if (!it.telegram) throw new Error('Ảnh chưa được lưu lên Telegram'); + const cached = cacheGet(it.telegram.fileUniqueId); + if (cached) return cached; + const buf = await downloadFile(it.telegram.fileId); + cachePut(it.telegram.fileUniqueId, buf); + return buf; +} + +const LEVEL = { HIGH: 2, MEDIUM: 1, LOW: 0 } as const; +function wantLlm(r: ExtractionResult, policy: BatchSettings['llm']): boolean { + if (!llmAvailable() || policy === 'off') return false; + if (policy === 'all') return true; + if (policy === 'low') return LEVEL[r.confidence] === 0; + return LEVEL[r.confidence] < 2 || r.needsReview; +} + +async function runOcr() { + ocrRunning++; + try { + while (ocrQueue.length) { + const task = ocrQueue.shift()!; + const { batchId, itemId, force } = task; + const step = (s: string) => live.set(itemId, { batchId, step: s }); + step('Chuẩn bị'); + const t0 = Date.now(); + let handedOff = false; + try { + const it = await getItem(batchId, itemId); + if (!it) continue; + const batch = await getBatch(batchId); + const policy = batch?.settings.llm ?? 'low'; + const buf = await loadOriginal(it); + let result: ExtractionResult; + let rotation = it.rotation ?? 0; + const img = await loadImage(buf); + // lượt nhanh trước; chưa chắc chắn mới chạy lượt kỹ (nhiều biến thể ảnh hơn) + const fast = await runPipeline(img, sharpOps, tessEngine, { thorough: false, onStep: step }); + result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] }); + rotation = fast.rotation; + if (result.confidence !== 'HIGH' || force === 'ocr') { + step('OCR kỹ'); + const deep = await runPipeline(img, sharpOps, tessEngine, { thorough: true, onStep: (s) => step(`OCR kỹ · ${s}`) }); + result = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' }); + if (deep.mrz && deep.mrz === result.mrz) rotation = deep.rotation; + } + if (force === 'llm' || (!force && wantLlm(result, policy))) { + // chuyển sang hàng đợi Gemini; worker OCR làm tiếp ảnh khác + llmQueue.push({ batchId, itemId, result, rotation, t0 }); + handedOff = true; + kick(); + continue; + } + await saveResult(batchId, itemId, result, rotation, t0); + } catch (e) { + console.error('ocr error', (e as Error).message); + await updateItem(batchId, itemId, { status: 'error', error: `Xử lý lỗi: ${(e as Error).message}` }).catch(() => undefined); + } finally { + live.delete(itemId); + if (!handedOff) await finishOne(batchId); + } + } + } finally { + ocrRunning--; + } +} + +async function saveResult(batchId: string, itemId: string, result: ExtractionResult, rotation: number, t0: number) { + await updateItem(batchId, itemId, { + status: 'done', error: '', result, confidence: result.confidence, + needsReview: result.needsReview, rotation, ms: Date.now() - t0, edited: false, + }); + fs.rmSync(inboxPath(itemId), { force: true }); +} + +async function runLlm() { + llmRunning++; + try { + while (llmQueue.length) { + const task = llmQueue.shift()!; + const { batchId, itemId, rotation, t0 } = task; + let result = task.result; + live.set(itemId, { batchId, step: 'Gemini' }); + try { + const it = await getItem(batchId, itemId); + if (!it) continue; // ảnh bị xoá trong lúc chờ + const buf = await loadOriginal(it); + try { + const llm = await geminiExtract(buf, it.mime); + result = mergeResults(result, { llm, source: 'llm' }); + } catch (e: any) { + result = { ...result, warnings: [...result.warnings, `Gemini lỗi: ${e?.status === 429 ? 'hết quota' : e?.message ?? e}`] }; + } + await saveResult(batchId, itemId, result, rotation, t0); + } catch (e) { + console.error('gemini error', (e as Error).message); + await updateItem(batchId, itemId, { status: 'error', error: `Xử lý lỗi: ${(e as Error).message}` }).catch(() => undefined); + } finally { + live.delete(itemId); + await finishOne(batchId); + } + } + } finally { + llmRunning--; + } +} + +/* ------------------------------------------------------------------ thao tác của người dùng */ + +export async function rerun(batchId: string, itemId: string, force: 'ocr' | 'llm') { + const it = await getItem(batchId, itemId); + if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); + if (!it.telegram) throw Object.assign(new Error('Ảnh chưa lưu xong lên Telegram'), { status: 409 }); + if (live.has(itemId) || ocrQueue.some((t) => t.itemId === itemId) || llmQueue.some((t) => t.itemId === itemId)) { + throw Object.assign(new Error('Ảnh đang được xử lý'), { status: 409 }); + } + addOutstanding(batchId, 1); + await patchBatch(batchId, { status: 'running' }); + // hỏi lại Gemini: dùng luôn kết quả OCR đã có, không OCR lại + if (force === 'llm' && it.result) llmQueue.push({ batchId, itemId, result: it.result, rotation: it.rotation ?? 0, t0: Date.now() }); + else ocrQueue.push({ batchId, itemId, force }); + kick(); +} + +/** + * Trong các hash (sha256 của file gốc), hash nào đã có kết quả: trong chính lô này, hoặc ở lô trước + * (khi upload sẽ được dùng lại kết quả cũ nếu không chọn OCR lại). + */ +export async function knownHashes(batchId: string, list: string[]): Promise { + const want = [...new Set(list.filter((h) => /^[0-9a-f]{64}$/.test(h)))]; + const found = new Set(); + for (const i of itemCache.values()) { + if (i.batchId === batchId && want.includes(i.sha256) && (i.status === 'done' || i.status === 'error') && i.telegram) found.add(i.sha256); + } + const rest = want.filter((h) => !found.has(h)); + for (let i = 0; i < rest.length; i += 300) { + const docs = await db().getAll(...rest.slice(i, i + 300).map((h) => hashes().doc(h))); + for (const d of docs) { + if (!d.exists) continue; + const prev = d.data() as { batchId: string; itemId: string }; + const old = await getItem(prev.batchId, prev.itemId); + if (old?.status === 'done' && old.result) found.add(d.id); + } + } + return [...found]; +} + +/** OCR lại nhiều ảnh; bỏ qua ảnh đang xử lý / chưa lưu xong */ +export async function rerunMany(batchId: string, ids: string[]): Promise<{ queued: number; failed: number }> { + let queued = 0; + for (const id of ids) { + try { await rerun(batchId, id, 'ocr'); queued++; } catch { /* bỏ qua */ } + } + return { queued, failed: ids.length - queued }; +} + +export async function saveEdit(batchId: string, itemId: string, edit: { result?: ExtractionResult; trip?: TripInfo }, email: string) { + const it = await getItem(batchId, itemId); + if (!it) throw Object.assign(new Error('Không tìm thấy ảnh'), { status: 404 }); + const patch: Partial = {}; + if (edit.result) { + Object.assign(patch, { status: 'done', result: edit.result, confidence: edit.result.confidence, needsReview: edit.result.needsReview, edited: true, reviewedBy: email }); + } + // ghi đè thông tin chuyến đi riêng của khách; giá trị rỗng = dùng lại thông tin đoàn + if (edit.trip) patch.trip = Object.fromEntries(Object.entries(edit.trip).filter(([, v]) => v !== undefined && v !== null && v !== '')) as TripInfo; + if (Object.keys(patch).length) await updateItem(batchId, itemId, patch); + return itemCache.get(itemId)!; +} + +export async function deleteItem(batchId: string, itemId: string) { + const it = await getItem(batchId, itemId); + if (!it) return; + if (live.has(itemId)) throw Object.assign(new Error('Ảnh đang được xử lý'), { status: 409 }); + await updateItem(batchId, itemId, { status: 'pending' }); // trừ bộ đếm kết quả + await items(batchId).doc(itemId).delete(); + itemCache.delete(itemId); + await patchBatch(batchId, {}, { total: -1 }); + const tq = tgQueue.findIndex((t) => t.itemId === itemId); + if (tq >= 0) { tgQueue.splice(tq, 1); await finishOne(batchId); } + const oq = ocrQueue.findIndex((t) => t.itemId === itemId); + if (oq >= 0) { ocrQueue.splice(oq, 1); await finishOne(batchId); } + const lq = llmQueue.findIndex((t) => t.itemId === itemId); + if (lq >= 0) { llmQueue.splice(lq, 1); await finishOne(batchId); } + fs.rmSync(inboxPath(itemId), { force: true }); + // chỉ xoá tin nhắn Telegram khi không còn item nào dùng file này + if (it.telegram) { + const href = hashes().doc(it.sha256); + const orphan = await db().runTransaction(async (tx) => { + const h = await tx.get(href); + if (!h.exists || (h.data() as { telegram: TelegramRef }).telegram.fileUniqueId !== it.telegram!.fileUniqueId) return false; + const refs = ((h.data() as { refs?: number }).refs ?? 1) - 1; + if (refs > 0) { tx.update(href, { refs }); return false; } + tx.delete(href); + return true; + }); + if (orphan) await deleteMessage(it.telegram).catch((e) => console.warn('telegram delete', (e as Error).message)); + } +} + +/* ------------------------------------------------------------------ khởi động lại */ + +export async function recover() { + await loadCache(); + for (const b of [...batchCache.values()].filter((x) => x.status === 'running')) { + const batchId = b.id; + let n = 0; + for (const it of [...itemCache.values()].filter((i) => i.batchId === batchId && (i.status === 'pending' || i.status === 'stored'))) { + if (it.status === 'stored') { ocrQueue.push({ batchId, itemId: it.id }); n++; } + else if (fs.existsSync(inboxPath(it.id))) { tgQueue.push({ batchId, itemId: it.id }); n++; } + else await updateItem(batchId, it.id, { status: 'error', error: 'Server khởi động lại trước khi kịp lưu ảnh lên Telegram — hãy upload lại ảnh này' }); + } + if (n) addOutstanding(batchId, n); + else await patchBatch(batchId, { status: 'done' }); + } + if (tgQueue.length || ocrQueue.length) console.log(`recover: ${tgQueue.length} chờ Telegram, ${ocrQueue.length} chờ OCR`); + kick(); +} diff --git a/passport-check/apps/server/src/media.ts b/passport-check/apps/server/src/media.ts new file mode 100644 index 0000000000000000000000000000000000000000..3748f4c1399a136a5da58fb81348ad648858b15d --- /dev/null +++ b/passport-check/apps/server/src/media.ts @@ -0,0 +1,104 @@ +/** + * Chuẩn hoá ảnh trước khi lưu Telegram, tạo thumbnail, và cache ảnh trên ổ tạm. + * HF Spaces free không có ổ bền: thư mục tạm mất khi Space khởi động lại, nên ảnh gốc luôn nằm ở Telegram; + * ổ tạm chỉ để xử lý và để xem lại nhanh. + */ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import sharp, { type Metadata } from 'sharp'; +import heicConvert from 'heic-convert'; +import { TELEGRAM_MAX_DOWNLOAD } from './telegram.ts'; + +export const WORK_DIR = process.env.WORK_DIR ?? path.join(os.tmpdir(), 'passport-check'); +export const INBOX = path.join(WORK_DIR, 'inbox'); +const CACHE = path.join(WORK_DIR, 'cache'); +const CACHE_MAX = Number(process.env.IMAGE_CACHE_MB ?? 500) * 1024 * 1024; +fs.mkdirSync(INBOX, { recursive: true }); +fs.mkdirSync(CACHE, { recursive: true }); + +export const IMAGE_EXT = /\.(jpe?g|png|webp|heic|heif|tiff?|bmp|gif)$/i; +export const ZIP_EXT = /\.zip$/i; + +export interface NormalizedImage { + buf: Buffer; + mime: string; + ext: string; + width: number; + height: number; + thumb: string; +} + +/** + * Giữ nguyên file gốc nếu là JPEG/PNG/WebP (trình duyệt xem được); HEIC/TIFF/BMP/GIF đổi sang JPEG. + * Ảnh quá 20MB (giới hạn tải về của Telegram bot) được nén lại. + */ +export async function normalizeImage(input: Buffer, name: string): Promise { + let buf = input; + let meta = await sharp(buf, { failOn: 'none' }).metadata().catch(() => null); + if (!meta && /\.(heic|heif)$/i.test(name)) meta = { format: 'heif' } as Metadata; + if (!meta?.format) throw new Error('Không phải file ảnh hợp lệ'); + let format = meta.format; + if (format === 'heif' && meta.compression !== 'av1') { + // sharp bản dựng sẵn không giải mã HEVC -> dùng heic-convert (WASM) + try { + buf = Buffer.from(await heicConvert({ buffer: buf as unknown as ArrayBuffer, format: 'JPEG', quality: 0.92 })); + } catch { + throw new Error('Không đọc được ảnh HEIC'); + } + format = 'jpeg'; + } else if (!['jpeg', 'png', 'webp'].includes(format)) { + buf = await sharp(buf, { failOn: 'none' }).rotate().jpeg({ quality: 92 }).toBuffer(); + format = 'jpeg'; + } + if (buf.length > TELEGRAM_MAX_DOWNLOAD - 512 * 1024) { + buf = await sharp(buf, { failOn: 'none' }).rotate().resize({ width: 5000, height: 5000, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: 90 }).toBuffer(); + format = 'jpeg'; + } + const img = sharp(buf, { failOn: 'none' }).rotate(); + const thumbBuf = await img.clone().resize({ width: 200, height: 200, fit: 'inside' }).webp({ quality: 55 }).toBuffer(); + const { width = 0, height = 0, orientation } = await sharp(buf, { failOn: 'none' }).metadata(); + const swap = (orientation ?? 1) >= 5; + return { + buf, + mime: `image/${format}`, + ext: format === 'jpeg' ? 'jpg' : format, + width: swap ? height : width, + height: swap ? width : height, + thumb: `data:image/webp;base64,${thumbBuf.toString('base64')}`, + }; +} + +/* --------------------------------------------------------------- cache ảnh để xem lại */ + +const cachePath = (key: string) => path.join(CACHE, key.replace(/[^\w-]/g, '_')); + +export function cacheGet(key: string): Buffer | null { + const p = cachePath(key); + try { + const buf = fs.readFileSync(p); + const now = new Date(); + fs.utimesSync(p, now, now); + return buf; + } catch { + return null; + } +} + +export function cachePut(key: string, buf: Buffer) { + try { + fs.writeFileSync(cachePath(key), buf); + const files = fs.readdirSync(CACHE).map((f) => { + const st = fs.statSync(path.join(CACHE, f)); + return { f, size: st.size, t: st.mtimeMs }; + }); + let total = files.reduce((s, x) => s + x.size, 0); + for (const x of files.sort((a, b) => a.t - b.t)) { + if (total <= CACHE_MAX) break; + fs.rmSync(path.join(CACHE, x.f), { force: true }); + total -= x.size; + } + } catch { + /* cache chỉ để tăng tốc */ + } +} diff --git a/passport-check/apps/server/src/ocr.ts b/passport-check/apps/server/src/ocr.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6b33b814cb9f606eaddbd34d94f6446e673746c --- /dev/null +++ b/passport-check/apps/server/src/ocr.ts @@ -0,0 +1,88 @@ +/** + * Tầng leo thang OCR phía server: sharp (nhiều biến thể tiền xử lý) + tesseract.js (pool worker theo ngôn ngữ). + */ +import os from 'node:os'; +import sharp, { type Sharp } from 'sharp'; +import { createWorker, type Worker } from 'tesseract.js'; +import { createWorkerPool, type ImageOps, type OcrEngine, type OcrLine, type OcrOptions } from '@pc/core'; + +export interface Img { data: Buffer; width: number; height: number } + +async function fromSharp(s: Sharp): Promise { + const { data, info } = await s.png({ compressionLevel: 1 }).toBuffer({ resolveWithObject: true }); + return { data, width: info.width, height: info.height }; +} + +export async function loadImage(buf: Buffer): Promise { + // rotate() không tham số = xoay theo EXIF + return fromSharp(sharp(buf, { failOn: 'none' }).rotate().greyscale()); +} + +export const sharpOps: ImageOps = { + size: (i) => ({ width: i.width, height: i.height }), + rotate: (i, deg) => fromSharp(sharp(i.data).rotate(deg)), + rotateFine: (i, deg) => fromSharp(sharp(i.data).rotate(deg, { background: '#ffffff' })), + crop: (i, r) => { + const left = Math.max(0, Math.min(i.width - 1, r.left)); + const top = Math.max(0, Math.min(i.height - 1, r.top)); + return fromSharp(sharp(i.data).extract({ left, top, width: Math.min(r.width, i.width - left), height: Math.min(r.height, i.height - top) })); + }, + resize: (i, width) => fromSharp(sharp(i.data).resize({ width, kernel: 'lanczos3' })), + variants: async (i, thorough) => { + const base = sharp(i.data); + const list: Promise[] = [ + Promise.resolve(i), + fromSharp(base.clone().normalise().sharpen({ sigma: 1 })), + ]; + if (thorough) { + list.push( + fromSharp(base.clone().clahe({ width: 64, height: 64, maxSlope: 3 })), + fromSharp(base.clone().normalise().threshold(140)), + fromSharp(base.clone().median(3).normalise().threshold(110)), + ); + } + return Promise.all(list); + }, +}; + +/* ------------------------------------------------------------ worker pool */ + +const TESSDATA = process.env.TESSDATA_DIR ?? new URL('../../../tessdata', import.meta.url).pathname; +const POOL_SIZE = Number(process.env.OCR_WORKERS ?? Math.max(1, Math.min(2, os.cpus().length))); + +const pool = createWorkerPool({ + size: POOL_SIZE, + maxNative: 3, + create: (lang) => createWorker(lang, 1, { langPath: TESSDATA, gzip: true, cacheMethod: 'none' }), + terminate: (w) => w.terminate(), +}); + +const THRESH = { otsu: '0', adaptive: '1', sauvola: '2' } as const; + +export const tessEngine: OcrEngine = { + async recognize(img, opts: OcrOptions) { + const w = await pool.acquire(opts.lang); + try { + await w.setParameters({ + tessedit_pageseg_mode: opts.psm as never, + tessedit_char_whitelist: opts.whitelist ?? '', + user_defined_dpi: '300', + thresholding_method: THRESH[opts.threshold ?? 'otsu'] as never, + }); + const { data } = await w.recognize(img.data, {}, { text: true, blocks: true }); + const lines: OcrLine[] = []; + for (const b of data.blocks ?? []) for (const p of b.paragraphs) for (const l of p.lines) { + const b = l.baseline; + const angle = b && b.x1 !== b.x0 ? (Math.atan2(b.y1 - b.y0, b.x1 - b.x0) * 180) / Math.PI : undefined; + lines.push({ text: l.text.trim(), bbox: l.bbox, confidence: l.confidence, angle }); + } + return { text: data.text, lines, confidence: data.confidence }; + } finally { + pool.release(opts.lang, w); + } + }, +}; + +export async function shutdownOcr() { + await pool.shutdown(); +} diff --git a/passport-check/apps/server/src/telegram.ts b/passport-check/apps/server/src/telegram.ts new file mode 100644 index 0000000000000000000000000000000000000000..7867e334dcad281b52388fc1861d9d58c91c0552 --- /dev/null +++ b/passport-check/apps/server/src/telegram.ts @@ -0,0 +1,85 @@ +/** + * Lưu ảnh lên Telegram bằng Bot API (gửi dạng document = file gốc, không bị nén). + * - TELEGRAM_BOT_TOKEN: token của bot (BotFather) + * - TELEGRAM_CHAT_ID: id kênh / nhóm / chat riêng để lưu ảnh (bot phải là admin nếu là kênh) + * Giới hạn Bot API: gửi file ≤ 50MB, tải về qua getFile ≤ 20MB; ~20 tin/phút với nhóm -> có hàng đợi + tôn trọng retry_after. + * Bot token không bao giờ gửi cho trình duyệt: server tải ảnh rồi trả lại. + */ +const API = (process.env.TELEGRAM_API_URL ?? 'https://api.telegram.org').replace(/\/$/, ''); +const TOKEN = process.env.TELEGRAM_BOT_TOKEN ?? ''; +const CHAT = process.env.TELEGRAM_CHAT_ID ?? ''; +const MIN_INTERVAL = Number(process.env.TELEGRAM_MIN_INTERVAL_MS ?? 1100); +/** giới hạn tải về của getFile */ +export const TELEGRAM_MAX_DOWNLOAD = 20 * 1024 * 1024; + +export function telegramConfigured() { + return !!TOKEN && !!CHAT; +} + +export interface TelegramRef { chatId: string; messageId: number; fileId: string; fileUniqueId: string } + +class TelegramError extends Error { + constructor(message: string, public retryAfter?: number, public status?: number) { super(message); } +} + +async function call(method: string, body: FormData | Record): Promise { + const isForm = body instanceof FormData; + const res = await fetch(`${API}/bot${TOKEN}/${method}`, { + method: 'POST', + body: isForm ? body : JSON.stringify(body), + headers: isForm ? undefined : { 'content-type': 'application/json' }, + signal: AbortSignal.timeout(120_000), + }); + const json = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: T; description?: string; parameters?: { retry_after?: number } }; + if (!json.ok) throw new TelegramError(json.description ?? `Telegram HTTP ${res.status}`, json.parameters?.retry_after, res.status); + return json.result as T; +} + +// Mọi lệnh gửi đi qua 1 hàng đợi tuần tự để không vượt giới hạn tốc độ +let chain: Promise = Promise.resolve(); +let last = 0; +function throttled(fn: () => Promise): Promise { + const run = async (): Promise => { + for (let attempt = 0; ; attempt++) { + const wait = last + MIN_INTERVAL - Date.now(); + if (wait > 0) await new Promise((r) => setTimeout(r, wait)); + last = Date.now(); + try { + return await fn(); + } catch (e) { + const err = e as TelegramError; + const transient = err.retryAfter !== undefined || (err.status ?? 0) >= 500 || err.name === 'TimeoutError' || err instanceof TypeError; + if (!transient || attempt >= 5) throw e; + await new Promise((r) => setTimeout(r, (err.retryAfter ?? 2 ** attempt) * 1000 + 250)); + } + } + }; + const p = chain.then(run, run); + chain = p.catch(() => undefined); + return p; +} + +export function sendDocument(buf: Buffer, filename: string, mime: string, caption: string): Promise { + return throttled(async () => { + const form = new FormData(); + form.set('chat_id', CHAT); + form.set('caption', caption.slice(0, 1000)); + form.set('disable_content_type_detection', 'true'); + form.set('document', new Blob([new Uint8Array(buf)], { type: mime }), filename); + const msg = await call<{ message_id: number; chat: { id: number }; document?: { file_id: string; file_unique_id: string } }>('sendDocument', form); + if (!msg.document) throw new Error('Telegram không trả về document'); + return { chatId: String(msg.chat.id), messageId: msg.message_id, fileId: msg.document.file_id, fileUniqueId: msg.document.file_unique_id }; + }); +} + +export async function downloadFile(fileId: string): Promise { + const f = await call<{ file_path?: string; file_size?: number }>('getFile', { file_id: fileId }); + if (!f.file_path) throw new Error('Telegram không trả về đường dẫn file'); + const res = await fetch(`${API}/file/bot${TOKEN}/${f.file_path}`, { signal: AbortSignal.timeout(120_000) }); + if (!res.ok) throw new Error(`Tải ảnh từ Telegram lỗi HTTP ${res.status}`); + return Buffer.from(await res.arrayBuffer()); +} + +export async function deleteMessage(ref: TelegramRef): Promise { + await throttled(() => call('deleteMessage', { chat_id: ref.chatId, message_id: ref.messageId })); +} diff --git a/passport-check/apps/server/src/tokens.ts b/passport-check/apps/server/src/tokens.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ba8593f9f0798cebb539278c16295743a35b0f6 --- /dev/null +++ b/passport-check/apps/server/src/tokens.ts @@ -0,0 +1,219 @@ +/** + * Ước lượng token Gemini cho từng ảnh / cả lô, tự tính tại server (không gọi API, không tốn quota). + * + * input = token ảnh (theo kích thước từng ảnh, công thức @pc/core imageTokens) + token prompt + token JSON schema + * output = token của chuỗi JSON đầu ra + * + * Token text được đếm bằng tokenizer Gemini chạy local (gemma3 SentencePiece — cùng bộ token của Gemini 2.x/3.x). + * Lần đầu tokenizer tải file model (~4MB, kiểm SHA-256) rồi cache ở thư mục tạm; nếu không tải được thì + * dùng công thức xấp xỉ theo số byte UTF-8 và đánh dấu exact=false. + */ +import { LocalTokenizer } from '@google/genai/tokenizer'; +import { + addTokenSum, base64Size, emptyTokenSum, GEMINI_TOKEN_DOCS, imageTokenRule, imageTokens, vnDay, type Batch, type ImageTokenRule, type ItemTokens, + type LlmOutput, type StoredItem, type TokenFormula, type TokenPrices, type TokenSum, type TokenUsageReport, type UsageBatch, type UsageDay, +} from '@pc/core'; +import { llmModel, promptText, SCHEMA } from './gemini.ts'; + +/* ------------------------------------------------------------------ đếm token text */ + +let tokenizer: LocalTokenizer | null = null; +let tokenizerFailed = 0; + +/** Xấp xỉ khi không có tokenizer: hiệu chỉnh trên JSON hộ chiếu / prompt tiếng Việt ≈ 2.3–3 byte / token */ +const approxTokens = (text: string) => Math.ceil(Buffer.byteLength(text, 'utf8') / 2.5); + +const textCache = new Map(); + +export async function countTextTokens(text: string): Promise<{ tokens: number; exact: boolean }> { + if (!text) return { tokens: 0, exact: true }; + const hit = textCache.get(text); + if (hit !== undefined) return { tokens: hit, exact: true }; + // tải lỗi -> 5 phút sau mới thử lại, tránh làm chậm mọi request + if (!tokenizerFailed || Date.now() - tokenizerFailed > 5 * 60_000) { + try { + tokenizer ??= new LocalTokenizer('gemini-2.5-flash'); // tên model chỉ để chọn bộ token gemma3 + const r = await tokenizer.countTokens([{ role: 'user', parts: [{ text }] }]); + const n = r.totalTokens ?? 0; + if (textCache.size > 5000) textCache.clear(); + textCache.set(text, n); + tokenizerFailed = 0; + return { tokens: n, exact: true }; + } catch (e) { + tokenizer = null; + tokenizerFailed = Date.now(); + console.error('tokenizer local lỗi, dùng công thức xấp xỉ:', (e as Error).message); + } + } + return { tokens: approxTokens(text), exact: false }; +} + +/* ------------------------------------------------------------------ token từng ảnh */ + +/** JSON đầu ra: lấy đúng JSON Gemini đã trả nếu ảnh từng qua Gemini, nếu không thì dựng từ kết quả OCR theo schema */ +export function outputJson(it: StoredItem): { json: LlmOutput | null; source: 'llm' | 'ocr' | 'none' } { + const r = it.result; + if (!r) return { json: null, source: 'none' }; + if (r.llm) return { json: r.llm as LlmOutput, source: 'llm' }; + const rec = r.record; + return { + source: 'ocr', + json: { + isPassport: true, + mrzLines: r.mrz?.lines ?? (rec.mrz ? rec.mrz.split('\n') : []), + documentCode: rec.documentCode, issuingState: rec.issuingState, surname: rec.surname, givenNames: rec.givenNames, + fullNameNative: rec.fullName, documentNumber: rec.documentNumber, nationality: rec.nationality, birthDate: rec.birthDate, + sex: rec.sex, placeOfBirth: rec.placeOfBirth, placeOfIssue: rec.placeOfIssue, issueDate: rec.issueDate, + expiryDate: rec.expiryDate, authority: rec.authority, personalNumber: rec.personalNumber, notes: '', + } as LlmOutput, + }; +} + +export interface Fixed { prompt: number; schema: number; exact: boolean } + +/** Phần cố định mỗi request: prompt + schema (giống nhau cho mọi ảnh) */ +export async function fixedTokens(): Promise { + const [p, s] = await Promise.all([countTextTokens(promptText()), countTextTokens(JSON.stringify(SCHEMA))]); + return { prompt: p.tokens, schema: s.tokens, exact: p.exact && s.exact }; +} + +export async function itemTokens(it: StoredItem, rule: ImageTokenRule, fixed: Fixed, withJson = false): Promise { + const w = it.width ?? 0; + const h = it.height ?? 0; + const img = imageTokens(w, h, rule); + const out = outputJson(it); + const text = out.json ? JSON.stringify(out.json) : ''; + const o = await countTextTokens(text); + const input = img.tokens + fixed.prompt + fixed.schema; + return { + id: it.id, + name: it.name, + status: it.status, + sentToLlm: !!it.result?.sources.includes('llm'), + image: { bytes: it.size, base64Bytes: base64Size(it.size), width: w, height: h, megapixels: +((w * h) / 1e6).toFixed(2), mime: it.mime }, + input: { image: img, prompt: fixed.prompt, schema: fixed.schema, total: input }, + output: { source: out.source, jsonChars: text.length, jsonBytes: Buffer.byteLength(text, 'utf8'), tokens: o.tokens, ...(withJson ? { json: out.json } : {}) }, + total: input + o.tokens, + exact: fixed.exact && o.exact, + }; +} + +/* ------------------------------------------------------------------ cả lô */ + +export function currentRule() { + return imageTokenRule(llmModel(), process.env.GEMINI_IMAGE_TOKENS); +} + +export function formulaInfo(rule: ImageTokenRule): TokenFormula { + const image = rule.kind === 'fixed' + ? `${rule.tokensPerImage} token / ảnh (cố định theo cấu hình GEMINI_IMAGE_TOKENS)` + : 'tính theo kích thước từng ảnh: ≤ 384px cả 2 chiều = 258; còn lại ô = clamp(⌊min(w,h)/1.5⌋, 256, 768), số ô = ⌈w/ô⌉ × ⌈h/ô⌉, token = số ô × 258' + + (rule.cap !== undefined ? `; Gemini 3+ chặn tối đa ${rule.cap} token / ảnh (media_resolution)` : ''); + return { + model: llmModel(), + imageRule: rule.label, + input: 'token ảnh + token prompt + token JSON schema', + image, + output: 'token của chuỗi JSON đầu ra (đếm bằng tokenizer Gemini local); chưa gồm token "thinking" nếu model bật suy nghĩ', + note: 'Dung lượng file (KB/MB) không ảnh hưởng số token — Google tính trên số pixel; dung lượng chỉ làm request nặng hơn (base64 ≈ 4/3).', + docs: GEMINI_TOKEN_DOCS, + }; +} + +const emptySum = emptyTokenSum; +function add(s: TokenSum, x: ItemTokens) { + s.images++; + s.bytes += x.image.bytes; + s.imageTokens += x.input.image.tokens; + s.inputTokens += x.input.total; + s.outputTokens += x.output.tokens; + s.totalTokens += x.total; +} + +export async function batchTokens(items: StoredItem[]) { + const rule = currentRule(); + const fixed = await fixedTokens(); + const rows: ItemTokens[] = []; + for (const it of [...items].sort((a, b) => a.createdAt - b.createdAt || a.name.localeCompare(b.name))) { + rows.push(await itemTokens(it, rule, fixed)); + } + /** nếu gửi MỌI ảnh cho Gemini */ + const all = emptySum(); + /** chỉ các ảnh đã thực sự qua Gemini (chi phí đã phát sinh) */ + const sent = emptySum(); + for (const r of rows) { + add(all, r); + if (r.sentToLlm) add(sent, r); + } + const avg = (n: number) => (all.images ? Math.round(n / all.images) : 0); + return { + formula: formulaInfo(rule), + prices: tokenPrices(), + fixedPerRequest: fixed, + total: { all, sentToLlm: sent, avgPerImage: { input: avg(all.inputTokens), output: avg(all.outputTokens), total: avg(all.totalTokens) } }, + exact: rows.every((r) => r.exact) && fixed.exact, + items: rows, + }; +} + +/* ------------------------------------------------------------------ theo thời gian (mọi lô) */ + +/** Đơn giá mặc định: Gemini 3.1 Flash-Lite gói trả phí, tier Standard (USD / 1M token), đổi bằng GEMINI_PRICE_INPUT / GEMINI_PRICE_OUTPUT */ +export function tokenPrices(): TokenPrices { + const n = (v: string | undefined, d: number) => (v && Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d); + return { + input: n(process.env.GEMINI_PRICE_INPUT, 0.25), + output: n(process.env.GEMINI_PRICE_OUTPUT, 1.5), + note: 'Bảng giá Gemini 3.1 Flash-Lite (gói trả phí, Standard): input 0,25 USD (text/ảnh/video), output 1,5 USD (gồm token thinking) / 1M token. Gói miễn phí thì chi phí = 0.', + }; +} + +/** cache kết quả từng ảnh: chỉ tính lại khi ảnh đổi hoặc luật tính đổi */ +const memo = new Map(); + +export async function usageReport(items: StoredItem[], batchOf: (id: string) => Batch | null | undefined): Promise { + const rule = currentRule(); + const fixed = await fixedTokens(); + const ruleKey = `${rule.label}|${fixed.prompt}|${fixed.schema}`; + const days = new Map(); + const batches = new Map(); + let exact = fixed.exact; + const live = new Set(); + for (const it of items) { + live.add(it.id); + const key = `${ruleKey}|${it.updatedAt}`; + let row = memo.get(it.id)?.key === key ? memo.get(it.id)!.row : null; + if (!row) { + row = await itemTokens(it, rule, fixed); + memo.set(it.id, { key, row }); + } + exact &&= row.exact; + const one: TokenSum = { + images: 1, bytes: row.image.bytes, imageTokens: row.input.image.tokens, + inputTokens: row.input.total, outputTokens: row.output.tokens, totalTokens: row.total, + }; + const date = vnDay(it.createdAt); + const dk = `${date}|${it.batchId}`; + const d = days.get(dk) ?? { date, batchId: it.batchId, all: emptySum(), sent: emptySum() }; + addTokenSum(d.all, one); + if (row.sentToLlm) addTokenSum(d.sent, one); + days.set(dk, d); + let b = batches.get(it.batchId); + if (!b) { + const meta = batchOf(it.batchId); + b = { id: it.batchId, name: meta?.name ?? it.batchId, createdAt: meta?.createdAt ?? it.createdAt, all: emptySum(), sent: emptySum() }; + batches.set(it.batchId, b); + } + addTokenSum(b.all, one); + if (row.sentToLlm) addTokenSum(b.sent, one); + } + for (const id of memo.keys()) if (!live.has(id)) memo.delete(id); + return { + formula: formulaInfo(rule), + fixedPerRequest: fixed, + prices: tokenPrices(), + exact, + days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)), + batches: [...batches.values()].sort((a, b) => b.createdAt - a.createdAt), + }; +} diff --git a/passport-check/apps/server/src/upload.ts b/passport-check/apps/server/src/upload.ts new file mode 100644 index 0000000000000000000000000000000000000000..9977b1aba45c3b69f144fe1809d3de7dfd75e858 --- /dev/null +++ b/passport-check/apps/server/src/upload.ts @@ -0,0 +1,159 @@ +/** + * Nhận upload multipart (ảnh và file .zip), ghi tạm ra đĩa theo luồng (không giữ cả file lớn trong RAM), + * giải nén zip, chuẩn hoá từng ảnh. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { pipeline } from 'node:stream/promises'; +import { Transform } from 'node:stream'; +import type { Request } from 'express'; +import busboy from 'busboy'; +import yauzl from 'yauzl'; +import { IMAGE_EXT, WORK_DIR, ZIP_EXT, normalizeImage, type NormalizedImage } from './media.ts'; + +const MB = 1024 * 1024; +const MAX_IMAGE = Number(process.env.MAX_IMAGE_MB ?? 50) * MB; +const MAX_ZIP = Number(process.env.MAX_ZIP_MB ?? 50) * MB; +const MAX_ZIP_ENTRIES = Number(process.env.MAX_ZIP_ENTRIES ?? 5000); +const MAX_ZIP_TOTAL = Number(process.env.MAX_ZIP_UNCOMPRESSED_MB ?? 4096) * MB; +const UPLOADS = path.join(WORK_DIR, 'uploads'); +fs.mkdirSync(UPLOADS, { recursive: true }); + +export interface Accepted { name: string; size: number; sha256: string; img: NormalizedImage } +export interface UploadResult { accepted: number; skipped: { name: string; reason: string }[] } +type Sink = { out: UploadResult; buf: Accepted[]; flush: (a: Accepted[]) => Promise; chain: Promise }; + +/** Gom ảnh đã chuẩn hoá, mỗi 20 ảnh đẩy sang hàng đợi (ghi đĩa) để không giữ cả lô trong RAM */ +function push(sink: Sink, a: Accepted): Promise { + sink.buf.push(a); + sink.out.accepted++; + if (sink.buf.length < 20) return sink.chain; + return drain(sink); +} +function drain(sink: Sink): Promise { + const take = sink.buf.splice(0); + if (take.length) sink.chain = sink.chain.then(() => sink.flush(take)); + return sink.chain; +} + +class LimitError extends Error {} + +/** Đếm byte + giới hạn kích thước khi ghi luồng */ +function limiter(max: number, what: string) { + let n = 0; + return new Transform({ + transform(chunk: Buffer, _enc, cb) { + n += chunk.length; + if (n > max) cb(new LimitError(`${what} vượt quá ${Math.round(max / MB)}MB`)); + else cb(null, chunk); + }, + }); +} + +const sha256 = (b: Buffer) => crypto.createHash('sha256').update(b).digest('hex'); + +async function acceptImage(buf: Buffer, name: string, sink: Sink) { + let img: NormalizedImage; + try { + img = await normalizeImage(buf, name); + } catch (e) { + sink.out.skipped.push({ name, reason: (e as Error).message }); + return; + } + await push(sink, { name, size: buf.length, sha256: sha256(buf), img }); +} + +/** Bỏ file rác của macOS / Windows trong zip */ +const junk = (p: string) => /(^|\/)(__MACOSX|\.DS_Store|Thumbs\.db)(\/|$)|(^|\/)\._/.test(p); + +async function extractZip(file: string, zipName: string, sink: Sink) { + const out = sink.out; + const zip = await new Promise((res, rej) => + yauzl.open(file, { lazyEntries: true, autoClose: true }, (e, z) => (e ? rej(e) : res(z!))), + ); + let entries = 0; + let total = 0; + const prefix = zipName.replace(ZIP_EXT, ''); + await new Promise((resolve, reject) => { + zip.on('error', reject); + zip.on('end', resolve); + zip.on('entry', async (entry: yauzl.Entry) => { + try { + const p = entry.fileName; + if (p.endsWith('/') || junk(p)) return zip.readEntry(); + const name = `${prefix}/${p}`; + if (!IMAGE_EXT.test(p)) { + out.skipped.push({ name, reason: ZIP_EXT.test(p) ? 'Không hỗ trợ zip lồng nhau' : 'Không phải ảnh' }); + return zip.readEntry(); + } + if (++entries > MAX_ZIP_ENTRIES) throw new LimitError(`File zip có quá ${MAX_ZIP_ENTRIES} ảnh`); + if (entry.uncompressedSize > MAX_IMAGE) { + out.skipped.push({ name, reason: `Ảnh vượt quá ${MAX_IMAGE / MB}MB` }); + return zip.readEntry(); + } + total += entry.uncompressedSize; + if (total > MAX_ZIP_TOTAL) throw new LimitError(`Dung lượng giải nén vượt quá ${MAX_ZIP_TOTAL / MB}MB`); + const stream = await new Promise((res, rej) => zip.openReadStream(entry, (e, s) => (e ? rej(e) : res(s!)))); + const chunks: Buffer[] = []; + // không tin uncompressedSize khai trong zip: giới hạn lại khi đọc + await pipeline(stream, limiter(MAX_IMAGE, name), async function* (src) { + for await (const c of src) chunks.push(c as Buffer); + }); + await acceptImage(Buffer.concat(chunks), name, sink); + zip.readEntry(); + } catch (e) { + zip.close(); + reject(e); + } + }); + zip.readEntry(); + }); +} + +/** Đọc request multipart. Trường `path` (tuỳ chọn) đứng trước mỗi file = đường dẫn tương đối trong thư mục. */ +export async function receiveUpload(req: Request, flush: (a: Accepted[]) => Promise): Promise { + const out: UploadResult = { accepted: 0, skipped: [] }; + const sink: Sink = { out, buf: [], flush, chain: Promise.resolve() }; + const work: Promise[] = []; + const temps: string[] = []; + const paths: string[] = []; + try { + await new Promise((resolve, reject) => { + const bb = busboy({ headers: req.headers, limits: { files: 500, fileSize: Math.max(MAX_ZIP, MAX_IMAGE) + 1, fields: 600 } }); + bb.on('field', (name, val) => { if (name === 'path') paths.push(val.slice(0, 500)); }); + bb.on('file', (_field, stream, info) => { + const rel = (paths.shift() || info.filename || 'image').replace(/\\/g, '/').replace(/^\/+/, ''); + const isZip = ZIP_EXT.test(rel) || /zip/.test(info.mimeType); + if (!isZip && !IMAGE_EXT.test(rel) && !info.mimeType.startsWith('image/')) { + out.skipped.push({ name: rel, reason: 'Không phải ảnh hoặc file .zip' }); + return void stream.resume(); + } + const tmp = path.join(UPLOADS, crypto.randomBytes(12).toString('hex')); + temps.push(tmp); + const max = isZip ? MAX_ZIP : MAX_IMAGE; + const written = pipeline(stream, limiter(max, rel), fs.createWriteStream(tmp)); + work.push( + written + .then(async () => { + if (isZip) await extractZip(tmp, rel, sink); + else await acceptImage(fs.readFileSync(tmp), rel, sink); + }) + .catch((e) => { + stream.resume(); + out.skipped.push({ name: rel, reason: e instanceof LimitError ? e.message : `Lỗi đọc file: ${(e as Error).message}` }); + }), + ); + }); + bb.on('error', reject); + bb.on('close', resolve); + req.on('aborted', () => reject(new Error('Upload bị huỷ'))); + req.pipe(bb); + }); + await Promise.all(work); + await drain(sink); + } finally { + for (const t of temps) fs.rmSync(t, { force: true }); + } + return out; +} diff --git a/passport-check/apps/server/src/users.ts b/passport-check/apps/server/src/users.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b3cb8139c03b13293fe806cbda89fc5ffe7e06f --- /dev/null +++ b/passport-check/apps/server/src/users.ts @@ -0,0 +1,273 @@ +/** + * Bảng người dùng (Firestore `users/{id}`) + đăng nhập. + * + * Hai cách đăng nhập, đều phải có tên trong bảng users (bảng này thay cho danh sách cho phép): + * - Google: trình duyệt đăng nhập Google qua Firebase Auth, gửi ID token cho server Next.js -> backend xác minh + * bằng firebase-admin, khớp email với bảng users. Email thuộc ALLOWED_EMAILS mà chưa có trong bảng -> tự tạo (quyền user). + * - Email / mật khẩu: chỉ cho tài khoản được admin đặt mật khẩu (mật khẩu băm scrypt, salt riêng từng người). + * - Đăng nhập thành công -> token phiên ký HMAC (AUTH_SECRET). Frontend Next.js giữ token trong cookie httpOnly, + * trình duyệt không bao giờ thấy token hay gọi thẳng backend. + * - Token mang `v` = tokenVersion của user: đổi mật khẩu / khoá tài khoản -> tăng version -> mọi phiên cũ hết hiệu lực. + * - Toàn bộ bảng user giữ trong RAM (ít bản ghi, chỉ 1 instance ghi) giống cache lô / khách. + * - Bảng trống + có ADMIN_EMAIL (ADMIN_PASSWORD tuỳ chọn) -> tự tạo tài khoản admin đầu tiên lúc khởi động. + */ +import crypto from 'node:crypto'; +import { promisify } from 'node:util'; +import { getAuth } from 'firebase-admin/auth'; +import { db, fbApp } from './firebase.ts'; + +export type Role = 'admin' | 'user'; + +export interface UserDoc { + id: string; + email: string; + name: string; + role: Role; + disabled: boolean; + /** được xem trang Chi phí Gemini (admin luôn được) */ + costAccess?: boolean; + /** không có = chỉ đăng nhập bằng Google */ + passwordHash?: string; + tokenVersion: number; + createdAt: number; + updatedAt: number; + createdBy?: string; + lastLoginAt?: number; +} + +/** Dữ liệu user trả ra ngoài (không có hash) */ +export type PublicUser = Omit & { hasPassword: boolean }; + +const users = () => db().collection('users'); +const cache = new Map(); +let loaded: Promise | null = null; + +const httpError = (status: number, message: string, code?: string) => Object.assign(new Error(message), { status, code }); +export const publicUser = ({ passwordHash, tokenVersion: _v, ...u }: UserDoc): PublicUser => ({ ...u, hasPassword: !!passwordHash }); +const normEmail = (e: unknown) => (typeof e === 'string' ? e.trim().toLowerCase() : ''); +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +/** Tên đăng nhập (không phải email): 3-50 ký tự chữ, số, . _ - */ +const USERNAME_RE = /^[a-z0-9][a-z0-9._-]{2,49}$/; +export const MIN_PASSWORD = 8; + +/* ------------------------------------------------------------------ mật khẩu */ + +const scrypt = promisify(crypto.scrypt) as (pw: string, salt: Buffer, len: number, opt: crypto.ScryptOptions) => Promise; +const SCRYPT = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }; + +async function hashPassword(pw: string): Promise { + const salt = crypto.randomBytes(16); + const key = await scrypt(pw, salt, 32, SCRYPT); + return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString('base64url')}$${key.toString('base64url')}`; +} + +async function verifyPassword(pw: string, stored: string | undefined): Promise { + if (!stored) return false; + const [algo, n, r, p, salt, hash] = stored.split('$'); + if (algo !== 'scrypt' || !salt || !hash) return false; + const expected = Buffer.from(hash, 'base64url'); + const key = await scrypt(pw, Buffer.from(salt, 'base64url'), expected.length, { N: +n, r: +r, p: +p, maxmem: SCRYPT.maxmem }); + return crypto.timingSafeEqual(key, expected); +} + +function checkPassword(pw: unknown): string { + if (typeof pw !== 'string' || pw.length < MIN_PASSWORD) throw httpError(400, `Mật khẩu cần ít nhất ${MIN_PASSWORD} ký tự`); + if (pw.length > 200) throw httpError(400, 'Mật khẩu quá dài'); + return pw; +} + +/* ------------------------------------------------------------------ token phiên */ + +const TOKEN_TTL = Number(process.env.AUTH_TOKEN_DAYS ?? 7) * 86_400_000; + +function secret(): Buffer { + const s = process.env.AUTH_SECRET; + if (!s || s.length < 32) throw new Error('AUTH_SECRET cần ít nhất 32 ký tự'); + return Buffer.from(s); +} +export const authConfigured = () => (process.env.AUTH_SECRET ?? '').length >= 32; + +const sign = (body: string) => crypto.createHmac('sha256', secret()).update(body).digest('base64url'); + +function issueToken(u: UserDoc): { token: string; expiresAt: number } { + const expiresAt = Date.now() + TOKEN_TTL; + const body = Buffer.from(JSON.stringify({ uid: u.id, v: u.tokenVersion, exp: expiresAt })).toString('base64url'); + return { token: `${body}.${sign(body)}`, expiresAt }; +} + +/** Token hợp lệ -> user; sai chữ ký / hết hạn / user bị khoá / đã đổi mật khẩu -> null */ +export function userFromToken(token: string): UserDoc | null { + const [body, mac] = token.split('.'); + if (!body || !mac) return null; + const a = Buffer.from(mac); + const b = Buffer.from(sign(body)); + if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null; + try { + const p = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as { uid: string; v: number; exp: number }; + if (!p.exp || p.exp < Date.now()) return null; + const u = cache.get(p.uid); + if (!u || u.disabled || u.tokenVersion !== p.v) return null; + return u; + } catch { + return null; + } +} + +/* ------------------------------------------------------------------ cache + khởi tạo */ + +export function loadUsers(): Promise { + loaded ??= (async () => { + const snap = await users().get(); + for (const d of snap.docs) cache.set(d.id, d.data() as UserDoc); + if (!cache.size) await bootstrapAdmin(); + console.log(`users: ${cache.size} tài khoản`); + })().catch((e) => { loaded = null; throw e; }); + return loaded; +} +export const usersReady = () => loaded; + +async function bootstrapAdmin() { + const email = normEmail(process.env.ADMIN_EMAIL); + const pw = process.env.ADMIN_PASSWORD ?? ''; + if (!email) { + console.warn('Chưa có tài khoản nào: đặt ADMIN_EMAIL (+ ADMIN_PASSWORD nếu muốn đăng nhập mật khẩu) để tạo admin đầu tiên'); + return; + } + // không có ADMIN_PASSWORD -> admin đăng nhập bằng Google + await createUser({ email, password: pw || undefined, name: 'Admin', role: 'admin' }, 'bootstrap'); + console.log(`đã tạo admin đầu tiên: ${email}`); +} + +const byEmail = (email: string) => [...cache.values()].find((u) => u.email === email); + +async function save(u: UserDoc) { + await users().doc(u.id).set(JSON.parse(JSON.stringify(u))); + cache.set(u.id, u); +} + +/* ------------------------------------------------------------------ nghiệp vụ */ + +// hash giả để so khi email không tồn tại -> thời gian phản hồi như nhau (không dò được email) +let dummyHash: Promise | null = null; + +export async function login(emailIn: unknown, pw: unknown): Promise<{ token: string; expiresAt: number; user: PublicUser }> { + const email = normEmail(emailIn); + const password = typeof pw === 'string' ? pw : ''; + const u = byEmail(email); + if (!u) { + await verifyPassword(password, await (dummyHash ??= hashPassword('x'.repeat(16)))); + throw httpError(401, 'Sai tài khoản hoặc mật khẩu', 'bad_credentials'); + } + if (!u.passwordHash) { + await verifyPassword(password, await (dummyHash ??= hashPassword('x'.repeat(16)))); + throw httpError(401, 'Tài khoản này đăng nhập bằng Google', 'google_only'); + } + if (!(await verifyPassword(password, u.passwordHash))) throw httpError(401, 'Sai tài khoản hoặc mật khẩu', 'bad_credentials'); + return startSession(u); +} + +async function startSession(u: UserDoc) { + if (u.disabled) throw httpError(403, 'Tài khoản đã bị khoá', 'disabled'); + const next = { ...u, lastLoginAt: Date.now() }; + await save(next); + return { ...issueToken(next), user: publicUser(next) }; +} + +const ALLOWED = (process.env.ALLOWED_EMAILS ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean); +const autoAllowed = (email: string) => ALLOWED.some((a) => (a.startsWith('@') ? email.endsWith(a) : email === a)); + +/** Đăng nhập Google: xác minh Firebase ID token, khớp email với bảng users */ +export async function loginGoogle(idToken: unknown) { + if (typeof idToken !== 'string' || !idToken) throw httpError(400, 'Thiếu ID token'); + let email = ''; + let name = ''; + try { + const t = await getAuth(fbApp()).verifyIdToken(idToken); + if (!t.email || !t.email_verified) throw new Error('unverified'); + email = t.email.toLowerCase(); + name = typeof t.name === 'string' ? t.name : ''; + } catch { + throw httpError(401, 'Không xác minh được tài khoản Google, hãy thử lại', 'bad_google_token'); + } + let u = byEmail(email); + if (!u && autoAllowed(email)) { + await createUser({ email, name, role: 'user' }, 'ALLOWED_EMAILS'); + u = byEmail(email); + } + if (!u) throw httpError(403, `${email} chưa được cấp quyền — nhờ admin thêm vào danh sách người dùng`, 'not_registered'); + if (!u.name && name) u = { ...u, name }; + return startSession(u); +} + +export function listUsers(): PublicUser[] { + return [...cache.values()].sort((a, b) => a.createdAt - b.createdAt).map(publicUser); +} + +export const hasCostAccess = (u: Pick) => u.role === 'admin' || !!u.costAccess; + +export async function createUser(input: { email?: unknown; password?: unknown; name?: unknown; role?: unknown; costAccess?: unknown }, by: string): Promise { + const email = normEmail(input.email); + if (!(EMAIL_RE.test(email) && email.length <= 200) && !USERNAME_RE.test(email)) throw httpError(400, 'Nhập email hợp lệ hoặc username (3-50 ký tự: chữ, số, . _ -)'); + if (byEmail(email)) throw httpError(409, 'Email / username đã tồn tại'); + const now = Date.now(); + const u: UserDoc = { + id: crypto.randomBytes(10).toString('base64url'), + email, + name: typeof input.name === 'string' ? input.name.trim().slice(0, 100) : '', + role: input.role === 'admin' ? 'admin' : 'user', + disabled: false, + costAccess: input.costAccess === true, + // bỏ trống mật khẩu = chỉ đăng nhập bằng Google + passwordHash: input.password === undefined || input.password === '' ? undefined : await hashPassword(checkPassword(input.password)), + tokenVersion: 1, + createdAt: now, + updatedAt: now, + createdBy: by, + }; + await save(u); + return publicUser(u); +} + +const activeAdmins = (except?: string) => [...cache.values()].filter((u) => u.role === 'admin' && !u.disabled && u.id !== except).length; + +/** Admin sửa user: tên, quyền, quyền xem chi phí, khoá / mở khoá, đặt lại mật khẩu */ +export async function updateUser(id: string, patch: { name?: unknown; role?: unknown; disabled?: unknown; password?: unknown; costAccess?: unknown }): Promise { + const u = cache.get(id); + if (!u) throw httpError(404, 'Không tìm thấy người dùng'); + const next: UserDoc = { ...u, updatedAt: Date.now() }; + if (typeof patch.name === 'string') next.name = patch.name.trim().slice(0, 100); + if (patch.role === 'admin' || patch.role === 'user') next.role = patch.role; + if (typeof patch.disabled === 'boolean') next.disabled = patch.disabled; + if (typeof patch.costAccess === 'boolean') next.costAccess = patch.costAccess; + // password: chuỗi = đặt mật khẩu mới, null = bỏ mật khẩu (chỉ đăng nhập Google) + if (patch.password === null) delete next.passwordHash; + else if (patch.password !== undefined) next.passwordHash = await hashPassword(checkPassword(patch.password)); + // luôn phải còn ít nhất 1 admin hoạt động + if (u.role === 'admin' && !u.disabled && (next.role !== 'admin' || next.disabled) && !activeAdmins(id)) { + throw httpError(400, 'Phải còn ít nhất 1 admin đang hoạt động'); + } + // đổi mật khẩu / khoá / hạ quyền -> đăng xuất mọi phiên của user đó + if (patch.password !== undefined || next.disabled !== u.disabled || next.role !== u.role) next.tokenVersion = u.tokenVersion + 1; + await save(next); + return publicUser(next); +} + +export async function deleteUser(id: string, by: string) { + const u = cache.get(id); + if (!u) throw httpError(404, 'Không tìm thấy người dùng'); + if (id === by) throw httpError(400, 'Không thể tự xoá tài khoản của mình'); + if (u.role === 'admin' && !u.disabled && !activeAdmins(id)) throw httpError(400, 'Phải còn ít nhất 1 admin đang hoạt động'); + await users().doc(id).delete(); + cache.delete(id); +} + +/** Người dùng tự đổi mật khẩu -> trả token mới (các phiên khác bị đăng xuất) */ +export async function changeOwnPassword(id: string, current: unknown, nextPw: unknown) { + const u = cache.get(id); + if (!u) throw httpError(404, 'Không tìm thấy người dùng'); + // chưa có mật khẩu (tài khoản Google) -> được đặt mật khẩu lần đầu không cần mật khẩu cũ + if (u.passwordHash && (typeof current !== 'string' || !(await verifyPassword(current, u.passwordHash)))) throw httpError(400, 'Mật khẩu hiện tại không đúng'); + const next: UserDoc = { ...u, passwordHash: await hashPassword(checkPassword(nextPw)), tokenVersion: u.tokenVersion + 1, updatedAt: Date.now() }; + await save(next); + return { ...issueToken(next), user: publicUser(next) }; +} diff --git a/passport-check/apps/server/templates/cong-van-bp.xlsx b/passport-check/apps/server/templates/cong-van-bp.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..fb33090bf7e83791b334dee8b3a60ab39106a311 Binary files /dev/null and b/passport-check/apps/server/templates/cong-van-bp.xlsx differ diff --git a/passport-check/apps/server/templates/thong-tin-ho-chieu.xlsx b/passport-check/apps/server/templates/thong-tin-ho-chieu.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81333564b5cf109dea3494f22cf9cd634f5e19e1 Binary files /dev/null and b/passport-check/apps/server/templates/thong-tin-ho-chieu.xlsx differ diff --git a/passport-check/apps/server/tsconfig.json b/passport-check/apps/server/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..5c48d24bf4fa39d7fcfe479baf9214e00fd8f5da --- /dev/null +++ b/passport-check/apps/server/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../tsconfig.base.json", "compilerOptions": { "lib": ["ES2022"], "types": ["node"] }, "include": ["src"] } diff --git a/passport-check/apps/web/.gitignore b/passport-check/apps/web/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fb1c98aaf157646573587ed85fa879c494e331dd --- /dev/null +++ b/passport-check/apps/web/.gitignore @@ -0,0 +1,3 @@ +.open-next +.dev.vars +.wrangler diff --git a/passport-check/apps/web/AGENTS.md b/passport-check/apps/web/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..af3b7c84114bafeee578bf1adff2ef74af2cc6a2 --- /dev/null +++ b/passport-check/apps/web/AGENTS.md @@ -0,0 +1,9 @@ + + +## This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/passport-check/apps/web/Dockerfile b/passport-check/apps/web/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db6a385b0ec33aaff631e51bc022fbd2ac19a9e1 --- /dev/null +++ b/passport-check/apps/web/Dockerfile @@ -0,0 +1,24 @@ +# Frontend Next.js. Build từ thư mục gốc repo: +# docker build -f apps/web/Dockerfile -t passport-check-web . +# docker run -p 3000:3000 -e BACKEND_URL=... -e BACKEND_API_KEY=... -e FIREBASE_WEB_CONFIG=... passport-check-web +FROM node:22-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +COPY packages/core/package.json packages/core/ +COPY apps/server/package.json apps/server/ +COPY apps/web/package.json apps/web/ +RUN npm ci --workspace apps/web --include-workspace-root +COPY packages packages +COPY apps/web apps/web +COPY tsconfig.base.json ./ +ENV NEXT_TELEMETRY_DISABLED=1 NEXT_STANDALONE=1 +RUN npm -w apps/web run build + +FROM node:22-slim +ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 NEXT_TELEMETRY_DISABLED=1 +WORKDIR /app +COPY --from=build --chown=node:node /app/apps/web/.next/standalone ./ +COPY --from=build --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static +USER node +EXPOSE 3000 +CMD ["node", "apps/web/server.js"] diff --git a/passport-check/apps/web/next.config.ts b/passport-check/apps/web/next.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..abd56193228b7cf277b65430bb9bb6dc9ac3bb32 --- /dev/null +++ b/passport-check/apps/web/next.config.ts @@ -0,0 +1,21 @@ +import path from 'node:path'; +import type { NextConfig } from 'next'; + +// Chạy dưới sub-path (vd /passport) khi gộp chung 1 Space: đặt NEXT_BASE_PATH=/passport lúc build +const basePath = process.env.NEXT_BASE_PATH || ''; + +const config: NextConfig = { + basePath: basePath || undefined, + env: { NEXT_PUBLIC_BASE_PATH: basePath }, + // @pc/core là source TypeScript trong monorepo + transpilePackages: ['@pc/core'], + // Docker: build gọn, chạy bằng node .next/standalone/apps/web/server.js (Dockerfile đặt NEXT_STANDALONE=1) + output: process.env.NEXT_STANDALONE ? 'standalone' : undefined, + outputFileTracingRoot: path.join(import.meta.dirname, '../..'), + turbopack: { root: path.join(import.meta.dirname, '../..') }, + poweredByHeader: false, + async headers() { + return [{ source: '/:path*', headers: [{ key: 'X-Robots-Tag', value: 'noindex' }, { key: 'X-Frame-Options', value: 'DENY' }, { key: 'Referrer-Policy', value: 'same-origin' }] }]; + }, +}; +export default config; diff --git a/passport-check/apps/web/open-next.config.ts b/passport-check/apps/web/open-next.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a3d17172639d491312e829dbd1ffbf24eef3008 --- /dev/null +++ b/passport-check/apps/web/open-next.config.ts @@ -0,0 +1,3 @@ +import { defineCloudflareConfig } from '@opennextjs/cloudflare'; + +export default defineCloudflareConfig(); diff --git a/passport-check/apps/web/package.json b/passport-check/apps/web/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ac77f637fb3d36e3a1543d126f2e9603b361918e --- /dev/null +++ b/passport-check/apps/web/package.json @@ -0,0 +1,29 @@ +{ + "name": "@pc/web", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "next dev -p 3000", + "build": "next build", + "start": "next start -p 3000", + "cf:build": "opennextjs-cloudflare build", + "cf:preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview", + "cf:deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy" + }, + "dependencies": { + "@opennextjs/cloudflare": "^1.20.17", + "@pc/core": "*", + "exceljs": "^4.4.0", + "firebase": "^13.2.0", + "next": "^16.4.6", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "server-only": "^0.0.1" + }, + "devDependencies": { + "@types/react": "^19", + "@types/react-dom": "^19", + "wrangler": "^4.161.0" + } +} diff --git a/passport-check/apps/web/src/app/(app)/b/[batchId]/i/[itemId]/page.tsx b/passport-check/apps/web/src/app/(app)/b/[batchId]/i/[itemId]/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0a0232df8d7dde90bcd010ba30487c905b2ca65f --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/b/[batchId]/i/[itemId]/page.tsx @@ -0,0 +1,6 @@ +import { ItemRoute } from '@/components/Pages'; + +export default async function Page({ params }: { params: Promise<{ batchId: string; itemId: string }> }) { + const { batchId, itemId } = await params; + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/b/[batchId]/page.tsx b/passport-check/apps/web/src/app/(app)/b/[batchId]/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b02213e92227b0dd0b339e5c98ebf4dab8716cb1 --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/b/[batchId]/page.tsx @@ -0,0 +1,6 @@ +import { BatchPage } from '@/components/Pages'; + +export default async function Page({ params }: { params: Promise<{ batchId: string }> }) { + const { batchId } = await params; + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/chi-phi/page.tsx b/passport-check/apps/web/src/app/(app)/chi-phi/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8414c596c131c9ef31ff8e38adbdadcfed982bc8 --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/chi-phi/page.tsx @@ -0,0 +1,8 @@ +import { notFound } from 'next/navigation'; +import { CostPage } from '@/components/Pages'; +import { currentUser } from '@/lib/server/backend'; + +export default async function Page() { + if (!(await currentUser())?.costAccess) notFound(); + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/khach/page.tsx b/passport-check/apps/web/src/app/(app)/khach/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..258d49cf7fc6df68e7c330ee9eefd65533f05c7f --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/khach/page.tsx @@ -0,0 +1,5 @@ +import { CustomersPage } from '@/components/Pages'; + +export default function Page() { + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/layout.tsx b/passport-check/apps/web/src/app/(app)/layout.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3b4f964437f943bc258964448b88793380e164ce --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/layout.tsx @@ -0,0 +1,28 @@ +import { redirect } from 'next/navigation'; +import { Shell } from '@/components/Shell'; +import { currentUser, serverConfig, type Me, type ServerConfig } from '@/lib/server/backend'; + +export const dynamic = 'force-dynamic'; + +/** Mọi trang trong app: kiểm tra phiên + đọc cấu hình backend ngay trên server */ +export default async function AppLayout({ children }: { children: React.ReactNode }) { + let user: Me | null; + let cfg: ServerConfig; + try { + [user, cfg] = await Promise.all([currentUser(), serverConfig()]); + } catch (e) { + return ( +
+
+
{(e as Error).message}
+

Backend trên Hugging Face có thể đang ngủ / khởi động — đợi một lát rồi tải lại trang.

+
+
+ ); + } + if (!user) redirect('/login'); + if (!cfg.ready) { + return
Backend chưa được cấu hình đủ. Thiếu: {cfg.missing.join(', ')}
; + } + return {children}; +} diff --git a/passport-check/apps/web/src/app/(app)/nguoi-dung/page.tsx b/passport-check/apps/web/src/app/(app)/nguoi-dung/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c65968a5fcd89c5dd84ca38aedfa6db5fdd7959a --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/nguoi-dung/page.tsx @@ -0,0 +1,8 @@ +import { notFound } from 'next/navigation'; +import { Users } from '@/components/Users'; +import { currentUser } from '@/lib/server/backend'; + +export default async function Page() { + if ((await currentUser())?.role !== 'admin') notFound(); + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/page.tsx b/passport-check/apps/web/src/app/(app)/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..77ffcad9586be88945b716663c2890ba147786d9 --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/page.tsx @@ -0,0 +1,5 @@ +import { HomePage } from '@/components/Pages'; + +export default function Page() { + return ; +} diff --git a/passport-check/apps/web/src/app/(app)/tai-khoan/page.tsx b/passport-check/apps/web/src/app/(app)/tai-khoan/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2060979087d3e8256f9a780456c3be30c25c4efb --- /dev/null +++ b/passport-check/apps/web/src/app/(app)/tai-khoan/page.tsx @@ -0,0 +1,5 @@ +import { Account } from '@/components/Account'; + +export default function Page() { + return ; +} diff --git a/passport-check/apps/web/src/app/api/[...path]/route.ts b/passport-check/apps/web/src/app/api/[...path]/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..78c889ba96818eb7ea71022800a4b4b0d3f21f5e --- /dev/null +++ b/passport-check/apps/web/src/app/api/[...path]/route.ts @@ -0,0 +1,49 @@ +/** + * Proxy phía server: trình duyệt gọi /api/... của Next.js, Next.js gọi backend (HF Space) kèm API key + token phiên. + * Stream cả 2 chiều nên upload zip lớn / tải ảnh / tải xlsx không phải giữ hết trong RAM. + */ +import { NextResponse, type NextRequest } from 'next/server'; +import { BackendError, SESSION_COOKIE, backendStream, clientIpFrom, sameOrigin } from '@/lib/server/backend'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; +export const maxDuration = 800; + +const REQ_HEADERS = ['content-type', 'content-length', 'accept']; +const RES_HEADERS = ['content-type', 'content-length', 'content-disposition', 'cache-control', 'retry-after', 'ratelimit', 'ratelimit-policy']; +// các đường dẫn chỉ được gọi qua route riêng (cần đặt cookie) hoặc chỉ dùng phía server +const BLOCKED = /^(auth\/|me\/password$|config$)/; + +async function handle(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { + const { path } = await ctx.params; + const sub = path.map(encodeURIComponent).join('/'); + if (BLOCKED.test(sub)) return NextResponse.json({ error: 'Không có API này' }, { status: 404 }); + if (!sameOrigin(req)) return NextResponse.json({ error: 'Yêu cầu không hợp lệ (khác nguồn)' }, { status: 403 }); + const token = req.cookies.get(SESSION_COOKIE)?.value; + if (!token) return NextResponse.json({ error: 'Chưa đăng nhập', code: 'unauthenticated' }, { status: 401 }); + + const headers: Record = {}; + for (const k of REQ_HEADERS) { + const v = req.headers.get(k); + if (v) headers[k] = v; + } + try { + const r = await backendStream(`/api/${sub}${req.nextUrl.search}`, { + method: req.method, headers, body: req.body, signal: req.signal, token, ip: clientIpFrom(req.headers), + }); + const out = new Headers(); + for (const k of RES_HEADERS) { + const v = r.headers[k]; + if (typeof v === 'string') out.set(k, v); + } + const res = new NextResponse(r.body, { status: r.status, headers: out }); + // phiên hết hạn / bị thu hồi -> xoá cookie để trình duyệt về trang đăng nhập + if (r.status === 401) res.cookies.delete(SESSION_COOKIE); + return res; + } catch (e) { + const err = e instanceof BackendError ? e : new BackendError(502, 'Lỗi kết nối backend'); + return NextResponse.json({ error: err.message }, { status: err.status }); + } +} + +export { handle as GET, handle as POST, handle as PATCH, handle as PUT, handle as DELETE }; diff --git a/passport-check/apps/web/src/app/api/auth/google/route.ts b/passport-check/apps/web/src/app/api/auth/google/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..17e91a0ef820f0e18a3b840c9cddb90c01cac0a4 --- /dev/null +++ b/passport-check/apps/web/src/app/api/auth/google/route.ts @@ -0,0 +1,20 @@ +import { NextResponse, type NextRequest } from 'next/server'; +import { BackendError, backendJson, clientIpFrom, sameOrigin, setSession, type Me } from '@/lib/server/backend'; + +export const runtime = 'nodejs'; + +/** Đăng nhập (google) -> backend cấp token phiên -> lưu trong cookie httpOnly (trình duyệt không đọc được) */ +export async function POST(req: NextRequest) { + if (!sameOrigin(req)) return NextResponse.json({ error: 'Yêu cầu không hợp lệ (khác nguồn)' }, { status: 403 }); + const body = await req.json().catch(() => ({})); + try { + const r = await backendJson<{ token: string; expiresAt: number; user: Me }>('/api/auth/google', { + method: 'POST', body: { idToken: body?.idToken }, ip: clientIpFrom(req.headers), + }); + await setSession(r.token, r.expiresAt); + return NextResponse.json({ user: r.user }); + } catch (e) { + const err = e instanceof BackendError ? e : new BackendError(500, 'Lỗi đăng nhập'); + return NextResponse.json({ error: err.message, code: err.code }, { status: err.status }); + } +} diff --git a/passport-check/apps/web/src/app/api/auth/login/route.ts b/passport-check/apps/web/src/app/api/auth/login/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..6207ef593ba0aa987fdadcd14cfc628d54878040 --- /dev/null +++ b/passport-check/apps/web/src/app/api/auth/login/route.ts @@ -0,0 +1,20 @@ +import { NextResponse, type NextRequest } from 'next/server'; +import { BackendError, backendJson, clientIpFrom, sameOrigin, setSession, type Me } from '@/lib/server/backend'; + +export const runtime = 'nodejs'; + +/** Đăng nhập (login) -> backend cấp token phiên -> lưu trong cookie httpOnly (trình duyệt không đọc được) */ +export async function POST(req: NextRequest) { + if (!sameOrigin(req)) return NextResponse.json({ error: 'Yêu cầu không hợp lệ (khác nguồn)' }, { status: 403 }); + const body = await req.json().catch(() => ({})); + try { + const r = await backendJson<{ token: string; expiresAt: number; user: Me }>('/api/auth/login', { + method: 'POST', body: { email: body?.email, password: body?.password }, ip: clientIpFrom(req.headers), + }); + await setSession(r.token, r.expiresAt); + return NextResponse.json({ user: r.user }); + } catch (e) { + const err = e instanceof BackendError ? e : new BackendError(500, 'Lỗi đăng nhập'); + return NextResponse.json({ error: err.message, code: err.code }, { status: err.status }); + } +} diff --git a/passport-check/apps/web/src/app/api/auth/logout/route.ts b/passport-check/apps/web/src/app/api/auth/logout/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..6540fa9ea582b71e8bf4f69b7a3a224764f3ff11 --- /dev/null +++ b/passport-check/apps/web/src/app/api/auth/logout/route.ts @@ -0,0 +1,8 @@ +import { NextResponse, type NextRequest } from 'next/server'; +import { clearSession, sameOrigin } from '@/lib/server/backend'; + +export async function POST(req: NextRequest) { + if (!sameOrigin(req)) return NextResponse.json({ error: 'Yêu cầu không hợp lệ (khác nguồn)' }, { status: 403 }); + await clearSession(); + return NextResponse.json({ ok: true }); +} diff --git a/passport-check/apps/web/src/app/api/me/password/route.ts b/passport-check/apps/web/src/app/api/me/password/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8e2581c712c34d0e89bd48d79cc311e1c1115cd --- /dev/null +++ b/passport-check/apps/web/src/app/api/me/password/route.ts @@ -0,0 +1,22 @@ +import { NextResponse, type NextRequest } from 'next/server'; +import { BackendError, backendJson, clientIpFrom, sameOrigin, sessionToken, setSession } from '@/lib/server/backend'; + +export const runtime = 'nodejs'; + +/** Đổi mật khẩu: backend trả token mới (phiên ở thiết bị khác bị đăng xuất) -> cập nhật cookie */ +export async function POST(req: NextRequest) { + if (!sameOrigin(req)) return NextResponse.json({ error: 'Yêu cầu không hợp lệ (khác nguồn)' }, { status: 403 }); + const token = await sessionToken(); + if (!token) return NextResponse.json({ error: 'Chưa đăng nhập', code: 'unauthenticated' }, { status: 401 }); + const body = await req.json().catch(() => ({})); + try { + const r = await backendJson<{ token: string; expiresAt: number }>('/api/me/password', { + method: 'POST', token, ip: clientIpFrom(req.headers), body: { current: body?.current, password: body?.password }, + }); + await setSession(r.token, r.expiresAt); + return NextResponse.json({ ok: true }); + } catch (e) { + const err = e instanceof BackendError ? e : new BackendError(500, 'Lỗi đổi mật khẩu'); + return NextResponse.json({ error: err.message, code: err.code }, { status: err.status }); + } +} diff --git a/passport-check/apps/web/src/app/icon.svg b/passport-check/apps/web/src/app/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..579fde417789642c0015143e4702319cd697df34 --- /dev/null +++ b/passport-check/apps/web/src/app/icon.svg @@ -0,0 +1 @@ + diff --git a/passport-check/apps/web/src/app/layout.tsx b/passport-check/apps/web/src/app/layout.tsx new file mode 100644 index 0000000000000000000000000000000000000000..35495b15939fd5acad66d3221b6301e32459a14a --- /dev/null +++ b/passport-check/apps/web/src/app/layout.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from 'next'; +import '../styles.css'; + +export const metadata: Metadata = { + title: 'Passport Check', + robots: { index: false, follow: false }, +}; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} diff --git a/passport-check/apps/web/src/app/login/page.tsx b/passport-check/apps/web/src/app/login/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c6267d9d42a3b8bd40644f97f4b1a5528b1244b0 --- /dev/null +++ b/passport-check/apps/web/src/app/login/page.tsx @@ -0,0 +1,28 @@ +import { redirect } from 'next/navigation'; +import { Login } from '@/components/Login'; +import { currentUser } from '@/lib/server/backend'; +import { firebaseWebConfig } from '@/lib/server/firebase-web'; + +export const dynamic = 'force-dynamic'; + +/** chỉ cho chuyển về đường dẫn nội bộ (tránh open redirect) */ +const safeNext = (n: unknown) => (typeof n === 'string' && n.startsWith('/') && !n.startsWith('//') && !n.startsWith('/login') ? n : '/'); + +export default async function LoginPage({ searchParams }: { searchParams: Promise> }) { + const next = safeNext((await searchParams).next); + let error = ''; + try { + if (await currentUser()) redirect(next); + } catch (e) { + if ((e as { digest?: string })?.digest?.startsWith('NEXT_REDIRECT')) throw e; + error = (e as Error).message; + } + return ( +
+
+ {error &&
{error}
} + +
+
+ ); +} diff --git a/passport-check/apps/web/src/components/Account.tsx b/passport-check/apps/web/src/components/Account.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b756cfcb6857890039739fe320e19487463ae05b --- /dev/null +++ b/passport-check/apps/web/src/components/Account.tsx @@ -0,0 +1,43 @@ +'use client'; +import { useState } from 'react'; +import { changePassword } from '../lib/api'; +import { useSession } from '../lib/session'; + +export function Account() { + const { user } = useSession(); + const [cur, setCur] = useState(''); + const [pw, setPw] = useState(''); + const [pw2, setPw2] = useState(''); + const [msg, setMsg] = useState<{ ok?: boolean; text: string } | null>(null); + const [busy, setBusy] = useState(false); + + return ( +
+

Tài khoản

+

{user.email}{user.name ? ` · ${user.name}` : ''} · {user.role === 'admin' ? 'Admin' : 'Người dùng'}

+
{ + e.preventDefault(); + if (pw !== pw2) return setMsg({ text: 'Mật khẩu nhập lại không khớp' }); + setBusy(true); + setMsg(null); + try { + await changePassword(cur, pw); + setCur(''); setPw(''); setPw2(''); + setMsg({ ok: true, text: 'Đã đổi mật khẩu. Phiên đăng nhập ở thiết bị khác đã bị đăng xuất.' }); + } catch (err) { + setMsg({ text: (err as Error).message }); + } finally { + setBusy(false); + } + }}> +

Đặt / đổi mật khẩu

+

Tài khoản Google chưa có mật khẩu thì để trống ô mật khẩu hiện tại.

+ + + +
+ {msg &&

{msg.text}

} +
+
+ ); +} diff --git a/passport-check/apps/web/src/components/BatchView.tsx b/passport-check/apps/web/src/components/BatchView.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3bd71c766e2b2b4ad4dce4ad4550f42635a77fa1 --- /dev/null +++ b/passport-check/apps/web/src/components/BatchView.tsx @@ -0,0 +1,176 @@ +'use client'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { passportValidity, type Batch } from '@pc/core'; +import { deleteItem, getBatch, listItems, rerunItem, saveItem, updateBatch, type Live } from '../lib/api'; +import { startUpload, type UploadJob } from '../lib/uploader'; +import { useRouter } from 'next/navigation'; +import { exportCsv, exportXlsx } from '../lib/export'; +import type { Item } from '../lib/types'; +import { useSession } from '../lib/session'; +import { ResultsTable, type Filter } from './ResultsTable'; +import { ReviewPanel, type SaveEdit } from './ReviewPanel'; +import { TripForm } from './TripForm'; +import { ExportDialog } from './ExportDialog'; +import { TokenDialog } from './TokenDialog'; +import { Dropzone } from './Dropzone'; + +const isUnder180 = (i: Item, batch: Batch | null) => + i.status === 'done' && !!i.result?.record.expiryDate && !!passportValidity(i.result.record.expiryDate, batch?.trip ?? {})?.under180Days; + +const EMPTY_LIVE: Live = { processing: [], waitingTelegram: 0, waitingOcr: 0, waitingLlm: 0 }; + +export function BatchView({ batchId, llmAvailable, uploads }: { batchId: string; llmAvailable: boolean; uploads: UploadJob[] }) { + const router = useRouter(); + const isAdmin = useSession().user.role === 'admin'; + const [batch, setBatch] = useState(null); + const [items, setItems] = useState>(new Map()); + const [live, setLive] = useState(EMPTY_LIVE); + const [filter, setFilter] = useState('all'); + const [reviewId, setReviewId] = useState(null); + const [err, setErr] = useState(''); + const [exportIds, setExportIds] = useState(null); + const [showTokens, setShowTokens] = useState(false); + const since = useRef(0); + const uploading = uploads.some((u) => u.batchId === batchId && u.state === 'uploading'); + + const refresh = useCallback(async () => { + try { + const [b, r] = await Promise.all([getBatch(batchId), listItems(batchId, since.current)]); + setBatch(b.batch); + setLive(r.live); + since.current = r.next; + if (r.items.length) { + setItems((prev) => { + const m = new Map(prev); + for (const it of r.items) m.set(it.id, it); + return m; + }); + } + setErr(''); + } catch (e) { + setErr((e as Error).message); + } + }, [batchId]); + + // hỏi server định kỳ khi lô đang chạy; chỉ tải các ảnh vừa thay đổi + const active = uploading || batch?.status === 'running' || live.processing.length > 0; + useEffect(() => { + refresh(); + const t = setInterval(() => { if (!document.hidden) refresh(); }, active ? 20000 : 30000); + return () => clearInterval(t); + }, [refresh, active]); + + const list = useMemo(() => [...items.values()].sort((a, b) => a.createdAt - b.createdAt || a.name.localeCompare(b.name)), [items]); + const steps = useMemo(() => new Map(live.processing.map((p) => [p.id, p.step])), [live]); + + const counts = useMemo(() => { + const c: Record = { all: list.length, review: 0, HIGH: 0, MEDIUM: 0, LOW: 0, pending: 0, under180: 0 }; + for (const i of list) { + if (i.status === 'pending' || i.status === 'stored') c.pending++; + if (i.status === 'error' || (i.status === 'done' && i.needsReview)) c.review++; + if (i.status === 'done' && i.confidence) c[i.confidence]++; + if (isUnder180(i, batch)) c.under180++; + } + return c; + }, [list, batch]); + + const visible = useMemo(() => list.filter((i) => { + if (filter === 'all') return true; + if (filter === 'pending') return i.status === 'pending' || i.status === 'stored'; + if (filter === 'under180') return isUnder180(i, batch); + if (filter === 'review') return i.status === 'error' || (i.status === 'done' && !!i.needsReview); + return i.status === 'done' && i.confidence === filter; + }), [list, filter, batch]); + + const upsert = (id: string, p: Partial) => setItems((prev) => { + const cur = prev.get(id); + if (!cur) return prev; + const m = new Map(prev); + m.set(id, { ...cur, ...p }); + return m; + }); + + const onSave = async (id: string, edit: SaveEdit) => { + const it = await saveItem(batchId, id, edit); + upsert(id, it); + }; + const onRerun = async (id: string, mode: 'ocr' | 'llm') => { + await rerunItem(batchId, id, mode); + setLive((l) => ({ ...l, processing: [...l.processing, { id, step: 'Chờ xử lý lại' }] })); + setBatch((b) => (b ? { ...b, status: 'running' } : b)); + }; + const onDelete = async (id: string) => { + await deleteItem(batchId, id); + setItems((prev) => { const m = new Map(prev); m.delete(id); return m; }); + setReviewId(null); + }; + + const done = list.filter((i) => i.status === 'done'); + const errors = list.filter((i) => i.status === 'error').length; + const total = batch?.counts.total ?? list.length; + const reviewIdx = visible.findIndex((i) => i.id === reviewId); + const reviewItem = reviewId ? items.get(reviewId) : undefined; + const pct = (n: number) => `${total ? (n / total) * 100 : 0}%`; + + return ( + <> +
+ +

{batch?.name ?? '…'}

+ {batch && {new Date(batch.createdAt).toLocaleString('vi-VN')} · {batch.createdBy.email}} +
+ {err &&
{err}
} + + {batch && { setBatch(await updateBatch(batchId, { trip })); }} />} + +
+
+
+
+ {done.length + errors}/{total} ảnh xong{errors > 0 && · {errors} lỗi} + {(live.waitingTelegram > 0 || live.waitingOcr > 0 || (live.waitingLlm ?? 0) > 0 || live.processing.length > 0) && ( + isAdmin + ? · đang xử lý {live.processing.length}, chờ OCR {live.waitingOcr}{(live.waitingLlm ?? 0) > 0 && <>, chờ Gemini {live.waitingLlm}}, chờ lưu Telegram {live.waitingTelegram} + : · đang xử lý… + )} +
+
+ + + +
+
+
+ + + + +
+
+ +
+ + { startUpload(batchId, f, refresh); }} /> + + {exportIds && setExportIds(null)} onOpen={(r) => { setExportIds(null); setReviewId(r.id); }} />} + + {showTokens && setShowTokens(false)} onOpen={(id) => { setShowTokens(false); setReviewId(id); }} />} + + {reviewItem && ( + setReviewId(null)} + onSave={onSave} + onRerun={onRerun} + onDelete={onDelete} + onPrev={reviewIdx > 0 ? () => setReviewId(visible[reviewIdx - 1].id) : undefined} + onNext={reviewIdx >= 0 && reviewIdx < visible.length - 1 ? () => setReviewId(visible[reviewIdx + 1].id) : undefined} + /> + )} + + ); +} diff --git a/passport-check/apps/web/src/components/CostView.tsx b/passport-check/apps/web/src/components/CostView.tsx new file mode 100644 index 0000000000000000000000000000000000000000..876c4c3704212dab0051781f7162939dd8d2cd95 --- /dev/null +++ b/passport-check/apps/web/src/components/CostView.tsx @@ -0,0 +1,272 @@ +'use client'; +import { useEffect, useMemo, useState } from 'react'; +import Link from 'next/link'; +import { + addTokenSum, emptyTokenSum, periodKey, PERIOD_DAYS, tokenCost, vnDay, + type TokenSum, type TokenUsageReport, type UsagePeriod, +} from '@pc/core'; +import { getCostSettings, saveCostSettings, tokenUsage, type CostSettings } from '../lib/api'; +import { useSession } from '../lib/session'; +import { TokenDialog, TokenDocs } from './TokenDialog'; + +type Basis = CostSettings['basis']; +type Settings = Pick; + +const DEFAULT_RATE = 26000; +const pick = ({ input, output, thinking, rate, basis }: Settings): Settings => ({ input, output, thinking, rate, basis }); +const same = (a: Settings, b: Settings) => JSON.stringify(pick(a)) === JSON.stringify(pick(b)); + +const num = (n: number) => Math.round(n).toLocaleString('vi-VN'); +const usd = (n: number) => `$${n.toLocaleString('en-US', { minimumFractionDigits: n > 0 && n < 1 ? 4 : 2, maximumFractionDigits: n > 0 && n < 1 ? 4 : 2 })}`; +const vnd = (n: number) => `${Math.round(n).toLocaleString('vi-VN')} ₫`; +function size(b: number) { + if (b >= 1024 ** 3) return `${(b / 1024 ** 3).toLocaleString('vi-VN', { maximumFractionDigits: 2 })} GB`; + return `${(b / 1024 ** 2).toLocaleString('vi-VN', { maximumFractionDigits: 1 })} MB`; +} + +const PERIODS: { id: UsagePeriod; label: string }[] = [ + { id: 'day', label: 'Ngày' }, { id: 'week', label: 'Tuần' }, { id: 'month', label: 'Tháng' }, { id: 'quarter', label: 'Quý' }, { id: 'year', label: 'Năm' }, +]; +const FORECAST: { id: keyof typeof PERIOD_DAYS; label: string }[] = [ + { id: 'week', label: '1 tuần' }, { id: 'month', label: '1 tháng' }, { id: 'quarter', label: '1 quý' }, { id: 'year', label: '1 năm' }, +]; + +function NumberField({ label, value, onChange, step = 'any', suffix, hint, disabled }: { + label: string; value: number; onChange: (n: number) => void; step?: string; suffix?: string; hint?: string; disabled?: boolean; +}) { + return ( + + ); +} + +/** Trang ước lượng token + chi phí Gemini: thực tế theo kỳ, dự báo tuần / tháng / quý / năm, theo lô */ +export function CostView() { + const isAdmin = useSession().user.role === 'admin'; + const [r, setR] = useState(null); + const [err, setErr] = useState(''); + // s = đang hiển thị (admin sửa nháp ở đây), saved = bản đã lưu trên server, dùng chung cho mọi người + const [s, setS] = useState(null); + const [saved, setSaved] = useState(null); + const [saving, setSaving] = useState(false); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + const [period, setPeriod] = useState('month'); + const [perDay, setPerDay] = useState(null); + const [ratio, setRatio] = useState(null); + const [detail, setDetail] = useState(null); + + useEffect(() => { + Promise.all([tokenUsage(), getCostSettings()]).then(([rep, cs]) => { + setR(rep); + setSaved(cs.settings); + setS(cs.settings ? pick(cs.settings) : defaults(rep)); + }).catch((e) => setErr(e.message)); + }, []); + const set = (p: Partial) => { if (isAdmin) setS((cur) => (cur ? { ...cur, ...p } : cur)); }; + const defaults = (rep: TokenUsageReport): Settings => ({ input: rep.prices.input, output: rep.prices.output, thinking: 0, rate: DEFAULT_RATE, basis: 'all' }); + + const save = async (next: Settings | null) => { + setSaving(true); + setMsg(null); + try { + const res = await saveCostSettings(next); + setSaved(res.settings); + setS(res.settings ? pick(res.settings) : defaults(r!)); + setRatio(null); + setMsg({ ok: true, text: next ? 'Đã lưu, áp dụng cho mọi người' : 'Đã về giá mặc định cho mọi người' }); + } catch (e) { + setMsg({ ok: false, text: (e as Error).message }); + } finally { + setSaving(false); + } + }; + + const totals = useMemo(() => { + const all = emptyTokenSum(); + const sent = emptyTokenSum(); + for (const d of r?.days ?? []) { addTokenSum(all, d.all); addTokenSum(sent, d.sent); } + return { all, sent }; + }, [r]); + + // khối lượng lịch sử: số ảnh / ngày tính từ ngày upload đầu tiên đến hôm nay + const history = useMemo(() => { + if (!r?.days.length) return { from: '', days: 1, perDay: 0, ratio: 1 }; + const from = r.days[0].date; + const days = Math.max(1, Math.round((Date.parse(vnDay(Date.now())) - Date.parse(from)) / 86400_000) + 1); + return { from, days, perDay: totals.all.images / days, ratio: totals.all.images ? totals.sent.images / totals.all.images : 0 }; + }, [r, totals]); + + const rows = useMemo(() => { + const m = new Map; sum: TokenSum }>(); + for (const d of r?.days ?? []) { + const sum = s?.basis === 'sent' ? d.sent : d.all; + if (!sum.images) continue; + const k = periodKey(d.date, period); + const g = m.get(k.key) ?? { ...k, batches: new Set(), sum: emptyTokenSum() }; + g.batches.add(d.batchId); + addTokenSum(g.sum, sum); + m.set(k.key, g); + } + return [...m.values()].sort((a, b) => b.key.localeCompare(a.key)); + }, [r, s?.basis, period]); + + if (err) return
{err}
; + if (!r || !s) return

Đang tính…

; + + const dirty = !same(s, saved ?? defaults(r)); + const prices = { input: s.input, output: s.output }; + const cost = (x: TokenSum) => tokenCost(x, prices, s.thinking); + const basisSum = s.basis === 'sent' ? totals.sent : totals.all; + const avgIn = totals.all.images ? totals.all.inputTokens / totals.all.images : 0; + const avgOut = totals.all.images ? totals.all.outputTokens / totals.all.images : 0; + const avgCost = (avgIn * s.input + (avgOut + s.thinking) * s.output) / 1e6; + const vol = perDay ?? Math.round(history.perDay * 10) / 10; + const pct = ratio ?? Math.round((s.basis === 'sent' ? history.ratio : 1) * 100); + const histSum = rows.reduce((acc, g) => addTokenSum(acc, g.sum), emptyTokenSum()); + + return ( +
+

Chi phí Gemini (ước lượng)

Server tự tính theo kích thước từng ảnh, không gọi Gemini · model {r.formula.model}
+ + {/* đơn giá & cách tính: chỉ admin thấy và sửa; người khác chỉ thấy số đã tính theo bản admin lưu */} + {isAdmin && ( +
+

Đơn giá & cách tính

+
+ {dirty && } + + +
+
+
+ set({ input: v })} /> + set({ output: v })} /> + set({ thinking: v })} step="1" hint="0 nếu tắt thinking" /> + set({ rate: v })} step="1" /> + +
+

+ {saved?.updatedAt ? `Cập nhật ${new Date(saved.updatedAt).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' })}${saved.updatedBy ? ` bởi ${saved.updatedBy}` : ''} · ` : 'Đang dùng giá mặc định · '} + {dirty ? 'Có thay đổi chưa lưu — số liệu bên dưới đang tính theo bản nháp.' : 'Đơn giá áp dụng cho mọi người.'} +

+ {msg &&

{msg.text}

} +

{r.prices.note}

+
+ Công thức +
    +
  • Input / ảnh = {r.formula.input} — prompt {r.fixedPerRequest.prompt} + schema {r.fixedPerRequest.schema} token cố định
  • +
  • Token ảnh: {r.formula.image}
  • +
  • Output / ảnh = {r.formula.output}
  • +
  • Chi phí = input × giá input + (output + thinking) × giá output, chia 1.000.000
  • +
  • {r.formula.note}{!r.exact && ' Một phần text đang đếm xấp xỉ (tokenizer chưa tải được).'}
  • + +
+
+
+ )} + +
+

Dự báo theo kỳ

+
+ + setRatio(Math.min(100, v))} step="1" hint={`lịch sử: ${Math.round(history.ratio * 100)}% ảnh đã qua Gemini`} /> +
+ Trung bình 1 ảnh + {num(avgIn)} in + {num(avgOut + s.thinking)} out + {usd(avgCost)} ≈ {vnd(avgCost * s.rate)} +
+
+
+ + + + {FORECAST.map((f) => { + const n = vol * PERIOD_DAYS[f.id] * (pct / 100); + const c = n * avgCost; + return ( + + + + + ); + })} + +
KỳẢnh gửi GeminiInputOutputTổng tokenUSDVND
{f.label}{num(n)}{num(n * avgIn)}{num(n * (avgOut + s.thinking))}{num(n * (avgIn + avgOut + s.thinking))}{usd(c)}{vnd(c * s.rate)}
+
+
+ +
+
+

Thực tế theo {PERIODS.find((p) => p.id === period)!.label.toLowerCase()}

+
+ {PERIODS.map((p) => )} +
+
+

Theo ngày upload ảnh (giờ Việt Nam) · {s.basis === 'sent' ? 'chỉ ảnh đã gửi Gemini' : 'mọi ảnh, giả sử đều gửi Gemini'}

+
+ + + + {rows.map((g) => ( + + + + + + ))} + {!rows.length && } + + {rows.length > 1 && ( + + + + + + + + )} +
KỳSố lôẢnhDung lượngInputOutputTổng tokenUSDVND
{g.label}{g.batches.size}{num(g.sum.images)}{size(g.sum.bytes)}{num(g.sum.inputTokens)}{num(g.sum.outputTokens + s.thinking * g.sum.images)}{num(g.sum.totalTokens + s.thinking * g.sum.images)}{usd(cost(g.sum))}{vnd(cost(g.sum) * s.rate)}
Chưa có dữ liệu
Tổng{num(histSum.images)}{size(histSum.bytes)}{num(histSum.inputTokens)}{num(histSum.outputTokens + s.thinking * histSum.images)}{num(histSum.totalTokens + s.thinking * histSum.images)}{usd(cost(histSum))}{vnd(cost(histSum) * s.rate)}
+
+
+ +
+

Theo lô

+
+ + + + {r.batches.map((b) => { + const x = s.basis === 'sent' ? b.sent : b.all; + return ( + setDetail(b.id)} title="Bấm để xem chi tiết từng ảnh"> + + + + + + + ); + })} + {!r.batches.length && } + +
LôNgày tạoẢnhĐã gửi GeminiTổng tokenUSDVND
e.stopPropagation()}>{b.name}{new Date(b.createdAt).toLocaleDateString('vi-VN')}{num(b.all.images)}{num(b.sent.images)}{num(x.totalTokens + s.thinking * x.images)}{usd(cost(x))}{vnd(cost(x) * s.rate)}
Chưa có lô nào
+
+

Tổng {s.basis === 'sent' ? 'đã gửi Gemini' : 'mọi ảnh'}: {num(basisSum.images)} ảnh · {usd(cost(basisSum))} ≈ {vnd(cost(basisSum) * s.rate)}

+
+ + {detail && setDetail(null)} />} +
+ ); +} diff --git a/passport-check/apps/web/src/components/CustomerList.tsx b/passport-check/apps/web/src/components/CustomerList.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ee7d7950a099a42c23e68615d448b9734d3c24d5 --- /dev/null +++ b/passport-check/apps/web/src/components/CustomerList.tsx @@ -0,0 +1,225 @@ +'use client'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { vnDate, type Batch, type CustomerRow } from '@pc/core'; +import { deleteCustomers, getBatch, getItem, listCustomers, rerunItem, saveItem, type CustomerPage } from '../lib/api'; +import type { Item } from '../lib/types'; +import { ExportDialog } from './ExportDialog'; +import { ReviewPanel } from './ReviewPanel'; + +type Col = { key: keyof CustomerRow; label: string; w?: number; render?: (r: CustomerRow) => React.ReactNode; filter?: boolean }; + +const yesNo = (v: boolean) => {v ? 'Có' : 'Không'}; +const COLS: Col[] = [ + { key: 'createdAt', label: 'Ngày tạo', w: 150, render: (r) => new Date(r.createdAt).toLocaleString('vi-VN') }, + { key: 'name', label: 'Tên khách hàng', w: 170 }, + { key: 'groupCode', label: 'Phân tách khách hàng', w: 170 }, + { key: 'birthDate', label: 'Ngày sinh', w: 100, render: (r) => vnDate(r.birthDate) }, + { key: 'sex', label: 'Giới tính', w: 80, render: (r) => (r.sex === 'M' ? 'Nam' : r.sex === 'F' ? 'Nữ' : r.sex) }, + { key: 'documentNumber', label: 'Số hộ chiếu', w: 110 }, + { key: 'nationality', label: 'Quốc tịch', w: 80 }, + { key: 'expiryDate', label: 'Hết hạn HC', w: 110, render: (r) => {vnDate(r.expiryDate)}{r.under6Months ? ' ⚠' : ''} }, + { key: 'urgent', label: 'Khẩn', w: 80, render: (r) => yesNo(r.urgent) }, + { key: 'multipleEntry', label: 'Giá trị thị thực', w: 110, render: (r) => {r.multipleEntry ? 'Nhiều lần' : 'Một lần'} }, + { key: 'stayDays', label: 'Số ngày lưu trú', w: 90 }, + { key: 'entryDate', label: 'Ngày nhập cảnh', w: 110, render: (r) => vnDate(r.entryDate) }, + { key: 'exitDate', label: 'Ngày xuất cảnh', w: 110, render: (r) => vnDate(r.exitDate) }, + { key: 'receivePlace', label: 'Nơi nhận visa', w: 150 }, + { key: 'occupation', label: 'Nghề nghiệp', w: 100 }, + { key: 'confidence', label: 'Đọc HC', w: 90, filter: false, render: (r) => statusBadge(r) }, +]; + +function statusBadge(r: CustomerRow) { + if (r.status === 'pending' || r.status === 'stored') return Đang xử lý; + if (r.status === 'error') return Lỗi; + if (r.missing.length) return Thiếu; + if (r.needsReview && !r.edited) return Cần duyệt; + return {r.edited ? 'Đã duyệt' : 'OK'}; +} + +const FLAGS = [ + { id: '', label: 'Tất cả' }, + { id: 'warn', label: 'HC dưới 6 tháng' }, + { id: 'review', label: 'Cần duyệt / thiếu' }, + { id: 'urgent', label: 'Khẩn' }, +]; + +export function CustomerList({ llmAvailable }: { llmAvailable: boolean }) { + const [data, setData] = useState(null); + const [err, setErr] = useState(''); + const [page, setPage] = useState(1); + const [q, setQ] = useState(''); + const [flag, setFlag] = useState(''); + const [filters, setFilters] = useState>({}); + const [sort, setSort] = useState<{ key: keyof CustomerRow; dir: 'asc' | 'desc' }>({ key: 'createdAt', dir: 'desc' }); + const [selected, setSelected] = useState>(new Set()); + const [exportIds, setExportIds] = useState(null); + const [open, setOpen] = useState<{ item: Item; batch: Batch | null } | null>(null); + const [busy, setBusy] = useState(false); + const debounce = useRef>(undefined); + const [applied, setApplied] = useState({ q: '', filters: {} as Record }); + + // gõ lọc -> đợi 300ms mới gọi server + useEffect(() => { + clearTimeout(debounce.current); + debounce.current = setTimeout(() => { setApplied({ q, filters }); setPage(1); }, 300); + return () => clearTimeout(debounce.current); + }, [q, filters]); + + const params = useCallback((extra: Record = {}) => ({ + page, size: 100, q: applied.q, flag, sort: sort.key, dir: sort.dir, + ...Object.fromEntries(Object.entries(applied.filters).map(([k, v]) => [`f.${k}`, v])), + ...extra, + }), [page, applied, flag, sort]); + + const load = useCallback(async () => { + try { + setData(await listCustomers(params())); + setErr(''); + } catch (e) { + setErr((e as Error).message); + } + }, [params]); + useEffect(() => { load(); }, [load]); + useEffect(() => { setPage(1); }, [flag]); + + const rows = data?.rows ?? []; + const allOnPage = rows.length > 0 && rows.every((r) => selected.has(r.id)); + const toggle = (id: string) => setSelected((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; }); + + /** chọn toàn bộ dòng khớp bộ lọc hiện tại (mọi trang) */ + const selectAllFiltered = async (group?: string) => { + const extra: Record = { ids: 1, size: 10, page: 1 }; + if (group !== undefined) extra['f.groupCode'] = group; + const res = await listCustomers({ ...params(extra), ...(group !== undefined ? { q: '', flag: '' } : {}) }); + setSelected(new Set(res.allIds ?? [])); + }; + + const removeSelected = async () => { + if (!selected.size || !confirm(`Xoá ${selected.size} khách đã chọn? Ảnh gốc cũng bị xoá nếu không lô nào khác dùng.`)) return; + setBusy(true); + try { + const r = await deleteCustomers([...selected]); + if (r.failed.length) alert(`Không xoá được ${r.failed.length} khách:\n${r.failed.join('\n')}`); + setSelected(new Set()); + await load(); + } catch (e) { + setErr((e as Error).message); + } finally { + setBusy(false); + } + }; + + const openItem = async (r: Pick) => { + try { + const [item, b] = await Promise.all([getItem(r.batchId, r.id), getBatch(r.batchId)]); + setOpen({ item, batch: b.batch }); + } catch (e) { + setErr((e as Error).message); + } + }; + const openIdx = open ? rows.findIndex((r) => r.id === open.item.id) : -1; + + const exportList = useMemo(() => (selected.size ? [...selected] : null), [selected]); + const startExport = async () => { + if (exportList) return setExportIds(exportList); + // chưa chọn dòng nào -> xuất toàn bộ theo bộ lọc + const res = await listCustomers(params({ ids: 1, size: 10, page: 1 })); + setExportIds(res.allIds ?? []); + }; + + const hasFilter = !!(q || flag || Object.values(filters).some(Boolean)); + + return ( +
+
+

Danh sách khách

+ {data ? `${data.total} khách` : ''} +
+
+ + + setQ(e.target.value)} /> + + + + + +
+ {err &&
{err}
} + +
+ + + + + + {COLS.map((c) => ( + + ))} + + + + ))} + + + + {rows.map((r) => ( + + + + {COLS.map((c) => )} + + ))} + {data && !rows.length && } + +
setSelected((s) => { + const n = new Set(s); + if (allOnPage) rows.forEach((r) => n.delete(r.id)); else rows.forEach((r) => n.add(r.id)); + return n; + })} aria-label="Chọn cả trang" />Ảnh + +
+ {COLS.map((c) => ( + {c.filter !== false && ( + setFilters((f) => ({ ...f, [c.key]: e.target.value }))} /> + )}
toggle(r.id)} aria-label={`Chọn ${r.name}`} />{c.render ? c.render(r) : String(r[c.key] ?? '')}
Không có khách nào
+
+ {data && ( +
+ {data.total ? `${(data.page - 1) * data.size + 1} to ${Math.min(data.page * data.size, data.total)} of ${data.total}` : '0'} + + + Page {data.page} of {data.pages} + + +
+ )} + + {exportIds && setExportIds(null)} onOpen={(r) => { setExportIds(null); openItem(r); }} />} + {open && ( + { setOpen(null); load(); }} + onSave={async (id, edit) => { const it = await saveItem(open.item.batchId, id, edit); setOpen((o) => (o ? { ...o, item: it } : o)); }} + onRerun={async (id, mode) => { await rerunItem(open.item.batchId, id, mode); }} + onDelete={async (id) => { await deleteCustomers([id]); setOpen(null); await load(); }} + onPrev={openIdx > 0 ? () => openItem(rows[openIdx - 1]) : undefined} + onNext={openIdx >= 0 && openIdx < rows.length - 1 ? () => openItem(rows[openIdx + 1]) : undefined} + /> + )} +
+ ); +} diff --git a/passport-check/apps/web/src/components/Dropzone.tsx b/passport-check/apps/web/src/components/Dropzone.tsx new file mode 100644 index 0000000000000000000000000000000000000000..728093dcd03c5610fa0f2fa16c41059314d14276 --- /dev/null +++ b/passport-check/apps/web/src/components/Dropzone.tsx @@ -0,0 +1,45 @@ +'use client'; +import { useRef, useState } from 'react'; +import { ACCEPT, filesFromDataTransfer } from '../lib/files'; +import { useSession } from '../lib/session'; + +export function Dropzone({ onFiles, compact, disabled }: { onFiles: (f: File[]) => void; compact?: boolean; disabled?: boolean }) { + const isAdmin = useSession().user.role === 'admin'; + const [over, setOver] = useState(false); + const dirRef = useRef(null); + const fileRef = useRef(null); + return ( +
{ e.preventDefault(); if (!disabled) setOver(true); }} + onDragLeave={() => setOver(false)} + onDrop={async (e) => { + e.preventDefault(); + setOver(false); + if (!disabled) onFiles(await filesFromDataTransfer(e.dataTransfer)); + }} + > + {!compact && ( +
+ +
+ )} +

{compact ? 'Thêm ảnh vào lô này' : 'Kéo thả thư mục, ảnh hoặc file .zip vào đây'}

+ {!compact &&

JPG, PNG, HEIC, WebP, TIFF · file .zip chứa ảnh{isAdmin ? ' · ảnh được lưu lên Telegram và xử lý trên server' : ''}

} +
+ + +
+ )} + onChange={(e) => { onFiles([...(e.target.files ?? [])]); e.target.value = ''; }} + /> + { onFiles([...(e.target.files ?? [])]); e.target.value = ''; }} + /> +
+ ); +} diff --git a/passport-check/apps/web/src/components/ExportDialog.tsx b/passport-check/apps/web/src/components/ExportDialog.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2b36e9d98e2a4bf484026dcab5af77237ae4bdc1 --- /dev/null +++ b/passport-check/apps/web/src/components/ExportDialog.tsx @@ -0,0 +1,71 @@ +'use client'; +import { useEffect, useState } from 'react'; +import { vnDate } from '@pc/core'; +import { downloadExport, exportCheck, type ExportCheck } from '../lib/api'; + +/** Kiểm tra rồi xuất 2 loại file nộp hồ sơ cho danh sách khách đã chọn */ +export function ExportDialog({ ids, onClose, onOpen }: { ids: string[]; onClose: () => void; onOpen?: (r: { id: string; batchId: string }) => void }) { + const [chk, setChk] = useState(null); + const [err, setErr] = useState(''); + const [dvcName, setDvcName] = useState(''); + const [bpName, setBpName] = useState(''); + const [busy, setBusy] = useState<'' | 'dvc' | 'bp'>(''); + useEffect(() => { + exportCheck(ids).then((c) => { setChk(c); setDvcName(c.dvcName); setBpName(c.bpName); }).catch((e) => setErr(e.message)); + }, [ids]); + useEffect(() => { + const k = (e: KeyboardEvent) => e.key === 'Escape' && onClose(); + window.addEventListener('keydown', k); + return () => window.removeEventListener('keydown', k); + }, [onClose]); + + const dl = async (kind: 'dvc' | 'bp') => { + setBusy(kind); + setErr(''); + try { await downloadExport(kind, ids, kind === 'dvc' ? dvcName : bpName); } catch (e) { setErr((e as Error).message); } finally { setBusy(''); } + }; + + return ( +
+
e.stopPropagation()}> +

Xuất file nộp hồ sơ

+ {!chk && !err &&

Đang kiểm tra {ids.length} khách…

} + {err &&

{err}

} + {chk && ( + <> +

+ {chk.count} khách sẽ được xuất — {chk.male} Nam xếp trên, {chk.female} Nữ xếp dưới. + {chk.skipped.length > 0 && Bỏ qua {chk.skipped.length} ảnh chưa xử lý xong.} +

+ {chk.groupCodes.length > 1 &&

⚠ Danh sách gồm nhiều đoàn: {chk.groupCodes.join(', ')}

} + {chk.entryDates.length > 1 &&

⚠ Có nhiều ngày nhập cảnh khác nhau: {chk.entryDates.map(vnDate).join(', ')}

} + {chk.under6.length > 0 && ( +
+ ⚠ {chk.under6.length} hộ chiếu còn hạn dưới 6 tháng tính từ ngày nhập cảnh +
    {chk.under6.map((u) => ( +
  • — hết hạn {vnDate(u.expiryDate)}{u.expired ? ' (đã hết hạn)' : ''}
  • + ))}
+
+ )} + {chk.missing.length > 0 && ( +
+ {chk.missing.length} khách thiếu thông tin bắt buộc +
    {chk.missing.slice(0, 50).map((m) => ( +
  • : {m.fields.join(', ')}
  • + ))}
+
+ )} +
+ + +
+
+ + +
+ + )} +
+
+ ); +} diff --git a/passport-check/apps/web/src/components/Home.tsx b/passport-check/apps/web/src/components/Home.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b207f6b683cd8f624a272a3099a139a45b9e0530 --- /dev/null +++ b/passport-check/apps/web/src/components/Home.tsx @@ -0,0 +1,107 @@ +'use client'; +import { useEffect, useState } from 'react'; +import type { Batch, LlmPolicy } from '@pc/core'; +import { createBatch, listBatches } from '../lib/api'; +import { startUpload } from '../lib/uploader'; +import { useRouter } from 'next/navigation'; +import { Dropzone } from './Dropzone'; + +const POLICIES: { id: LlmPolicy; label: string }[] = [ + { id: 'off', label: 'Không dùng Gemini' }, + { id: 'low', label: 'Chỉ ảnh độ tin cậy thấp' }, + { id: 'review', label: 'Mọi ảnh chưa chắc chắn' }, + { id: 'all', label: 'Tất cả ảnh' }, +]; + +const POLICY_KEY = 'pc.llmPolicy'; + +export function Home({ llmAvailable, isAdmin }: { llmAvailable: boolean; isAdmin: boolean }) { + const router = useRouter(); + const [batches, setBatches] = useState(null); + const [name, setName] = useState(''); + const [policy, setPolicy] = useState('low'); + const [policyLoaded, setPolicyLoaded] = useState(false); + const [err, setErr] = useState(''); + const [busy, setBusy] = useState(false); + + useEffect(() => { listBatches().then(setBatches).catch((e) => setErr(e.message)); }, []); + // đọc lựa chọn đã lưu sau khi mount (SSR không có localStorage) + useEffect(() => { + try { const v = localStorage.getItem(POLICY_KEY) as LlmPolicy | null; if (v) setPolicy(v); } catch { /* bỏ qua */ } + setPolicyLoaded(true); + }, []); + useEffect(() => { if (policyLoaded) try { localStorage.setItem(POLICY_KEY, policy); } catch { /* bỏ qua */ } }, [policy, policyLoaded]); + + const onFiles = async (files: File[]) => { + if (!files.length) return; + setBusy(true); + setErr(''); + try { + const b = await createBatch(name, { llm: llmAvailable ? policy : 'off' }); + const { ignored } = startUpload(b.id, files); + if (ignored === files.length) return setErr('Không có file ảnh hoặc .zip nào'); + router.push(`/b/${b.id}`); + } catch (e) { + setErr((e as Error).message); + } finally { + setBusy(false); + } + }; + + return ( + <> +
+ +
+

Lô mới

+ + {isAdmin && ( + <> + + {!llmAvailable &&

Server chưa cấu hình GEMINI_API_KEY.

} + + )} +

+ {isAdmin && <>Ảnh được lưu nguyên bản lên kênh Telegram đã cấu hình{llmAvailable && policy !== 'off' ? ' và gửi cho Google Gemini khi cần' : ''}; kết quả lưu trên Firebase.{' '}} + Mọi người dùng được cấp quyền đều xem được các lô. +

+ {err &&

{err}

} +
+
+ +
+

Các lô đã upload

+ {!batches && !err &&

Đang tải…

} + {batches?.length === 0 &&

Chưa có lô nào.

} + {batches && batches.length > 0 && ( +
+ + + + {batches.map((b) => ( + router.push(`/b/${b.id}`)} onKeyDown={(e) => e.key === 'Enter' && router.push(`/b/${b.id}`)}> + + + + + + + + ))} + +
Tên lôNgày tạoNgười tạoẢnhKết quảTrạng thái
{b.name}{new Date(b.createdAt).toLocaleString('vi-VN')}{b.createdBy.email}{b.counts.done + b.counts.error}/{b.counts.total} + {b.counts.HIGH} cao · {b.counts.MEDIUM} TB · {b.counts.LOW + b.counts.error} thấp/lỗi + {b.counts.review > 0 && · {b.counts.review} cần duyệt} + {b.status === 'running' ? Đang xử lý : Xong}
+
+ )} +
+ + ); +} diff --git a/passport-check/apps/web/src/components/ItemPage.tsx b/passport-check/apps/web/src/components/ItemPage.tsx new file mode 100644 index 0000000000000000000000000000000000000000..03aafbe3ab8717aa2d62c813efae3c80e70de689 --- /dev/null +++ b/passport-check/apps/web/src/components/ItemPage.tsx @@ -0,0 +1,56 @@ +'use client'; +import { useCallback, useEffect, useState } from 'react'; +import type { Batch } from '@pc/core'; +import { getBatch, getItem, rerunItem, saveItem } from '../lib/api'; +import { useRouter } from 'next/navigation'; +import type { Item } from '../lib/types'; +import { ReviewPanel } from './ReviewPanel'; + +/** Trang mở từ link /b/:batchId/i/:itemId — chỉ đọc đúng 1 ảnh */ +export function ItemPage({ batchId, itemId, llmAvailable }: { batchId: string; itemId: string; llmAvailable: boolean }) { + const router = useRouter(); + const [item, setItem] = useState(null); + const [batch, setBatch] = useState(null); + const [step, setStep] = useState(); + const [err, setErr] = useState(''); + + const load = useCallback(async () => { + try { + const [it, b] = await Promise.all([getItem(batchId, itemId), getBatch(batchId)]); + setItem(it); + setBatch(b.batch); + setStep(b.live.processing.find((p) => p.id === itemId)?.step); + } catch (e) { + setErr((e as Error).message); + } + }, [batchId, itemId]); + + useEffect(() => { load(); }, [load]); + // đang xử lý -> cập nhật định kỳ + const working = !!step || item?.status === 'pending' || item?.status === 'stored'; + useEffect(() => { + if (!working) return; + const t = setInterval(load, 20000); + return () => clearInterval(t); + }, [working, load]); + + if (err) return
{err}
; + if (!item) return

Đang tải…

; + return ( + <> +
+ +
+ router.push(`/b/${batchId}`)} + onSave={async (id, edit) => { setItem(await saveItem(batchId, id, edit)); }} + onRerun={async (id, mode) => { await rerunItem(batchId, id, mode); setStep('Chờ xử lý lại'); }} + /> + + ); +} diff --git a/passport-check/apps/web/src/components/Login.tsx b/passport-check/apps/web/src/components/Login.tsx new file mode 100644 index 0000000000000000000000000000000000000000..79c7c6a2a3dd63420af8f4b5ed91fab523b9c633 --- /dev/null +++ b/passport-check/apps/web/src/components/Login.tsx @@ -0,0 +1,62 @@ +'use client'; +import { useState } from 'react'; +import { authMessage, googleIdToken } from '../lib/firebase'; +import { withBase } from '../lib/base'; + +async function post(url: string, body: unknown) { + const res = await fetch(withBase(url), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + if (!res.ok) throw new Error((await res.json().catch(() => null))?.error ?? `Lỗi HTTP ${res.status}`); +} + +/** Đăng nhập: Google (Firebase popup -> đổi ID token lấy cookie) hoặc email / mật khẩu do admin cấp */ +export function Login({ firebase, next, notice }: { firebase: Record | null; next: string; notice?: string }) { + const [email, setEmail] = useState(''); + const [pw, setPw] = useState(''); + const [msg, setMsg] = useState(''); + const [busy, setBusy] = useState(false); + const [showPw, setShowPw] = useState(!firebase); + + const run = async (fn: () => Promise) => { + setBusy(true); + setMsg(''); + try { + await fn(); + // tải lại hẳn để layout server đọc cookie mới + location.href = withBase(next); + } catch (e) { + setMsg(authMessage(e)); + setBusy(false); + } + }; + + return ( +
+
+

Đăng nhập

+

Chỉ tài khoản có trong danh sách người dùng mới dùng được app.

+ {notice &&

{notice}

} + {firebase && ( + + )} + {firebase && !showPw && ( + + )} + {showPw && ( + <> + {firebase &&
hoặc tài khoản
} +
{ e.preventDefault(); run(() => post('/api/auth/login', { email, password: pw })); }}> + + + +
+

Quên mật khẩu: nhờ admin đặt lại.

+ + )} + {msg &&

{msg}

} +
+
+ ); +} diff --git a/passport-check/apps/web/src/components/Pages.tsx b/passport-check/apps/web/src/components/Pages.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ff82a818bc97d8f7097f9951b3ceb18bc4b45ea4 --- /dev/null +++ b/passport-check/apps/web/src/components/Pages.tsx @@ -0,0 +1,27 @@ +'use client'; +/** Bọc các màn hình cũ: lấy cấu hình từ phiên + hàng đợi upload */ +import { useSession } from '../lib/session'; +import { useUploads } from '../lib/uploader'; +import { Home } from './Home'; +import { BatchView } from './BatchView'; +import { ItemPage } from './ItemPage'; +import { CustomerList } from './CustomerList'; +import { CostView } from './CostView'; + +export function HomePage() { + const s = useSession(); + return ; +} +export function CustomersPage() { + return ; +} +export function BatchPage({ batchId }: { batchId: string }) { + const { llmAvailable } = useSession(); + return ; +} +export function ItemRoute({ batchId, itemId }: { batchId: string; itemId: string }) { + return ; +} +export function CostPage() { + return ; +} diff --git a/passport-check/apps/web/src/components/ResultsTable.tsx b/passport-check/apps/web/src/components/ResultsTable.tsx new file mode 100644 index 0000000000000000000000000000000000000000..32ccd531e3dd3dc94d246d36a475f22f65882087 --- /dev/null +++ b/passport-check/apps/web/src/components/ResultsTable.tsx @@ -0,0 +1,96 @@ +'use client'; +import { countryName, customerRow, vnDate, type Batch } from '@pc/core'; +import type { Item } from '../lib/types'; +import { useSession } from '../lib/session'; + +export type Filter = 'all' | 'review' | 'HIGH' | 'MEDIUM' | 'LOW' | 'pending' | 'under180'; +const CONF = { HIGH: 'Cao', MEDIUM: 'TB', LOW: 'Thấp' } as const; +const SRC: Record = { local: 'OCR', 'server-ocr': 'OCR kỹ', llm: 'Gemini', manual: 'Sửa tay' }; + +export function ConfBadge({ item, step }: { item: Item; step?: string }) { + if (step) return {step}; + if (item.status === 'pending') return Chờ lưu; + if (item.status === 'stored') return Chờ OCR; + if (item.status === 'error') return Lỗi; + const c = item.result?.confidence ?? 'LOW'; + return {CONF[c]}; +} + +export function ResultsTable({ items, batch, steps, filter, onFilter, counts, onOpen }: { + items: Item[]; + batch: Batch | null; + steps: Map; + filter: Filter; + onFilter: (f: Filter) => void; + counts: Record; + onOpen: (id: string) => void; +}) { + // cột Nguồn (OCR / Gemini / sửa tay) chỉ admin xem + const showSource = useSession().user.role === 'admin'; + const tabs: [Filter, string][] = [ + ['all', 'Tất cả'], ['review', 'Cần duyệt'], ['HIGH', 'Cao'], ['MEDIUM', 'Trung bình'], ['LOW', 'Thấp'], ['pending', 'Đang xử lý'], ['under180', 'Hạn < 180 ngày'], + ]; + return ( + <> +
+ {tabs.map(([id, label]) => ( + + ))} +
+
+ + + + + + + + + + + + + + + {showSource && } + + + + {items.map((it) => { + const r = it.result?.record; + const c = customerRow(it, batch); + return ( + onOpen(it.id)} data-review={!!it.needsReview} tabIndex={0} + onKeyDown={(e) => e.key === 'Enter' && onOpen(it.id)}> + + + + + + + + + + + + + {showSource && } + + ); + })} + {!items.length && } + +
+ FileHọ tênSố hộ chiếuQuốc tịchNgày sinhGTHết hạn HCNhập cảnhXuất cảnhNghề nghiệpTin cậyNguồn
{it.thumb ? :
}
{it.name}{[r?.surname, r?.givenNames].filter(Boolean).join(' ') || r?.fullName}{r?.documentNumber}{r?.nationality}{vnDate(r?.birthDate)}{r?.sex === 'M' ? 'Nam' : r?.sex === 'F' ? 'Nữ' : r?.sex} + {vnDate(r?.expiryDate)}{c.under6Months ? ' ⚠' : ''} + {vnDate(c.entryDate)}{vnDate(c.exitDate)}{c.occupation} + + {it.result && it.result.warnings.length > 0 && !} + {it.edited && ✎} + {it.result?.sources.map((s) => SRC[s] ?? s).join(' → ')}
Không có ảnh nào trong mục này
+
+ + ); +} diff --git a/passport-check/apps/web/src/components/ReviewPanel.tsx b/passport-check/apps/web/src/components/ReviewPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9e6f77418c5f43fe11c92095ac4619f86dd4f68a --- /dev/null +++ b/passport-check/apps/web/src/components/ReviewPanel.tsx @@ -0,0 +1,247 @@ +'use client'; +import { useSession } from '../lib/session'; +import { useEffect, useMemo, useState } from 'react'; +import { + BP_LISTS, DVC_NOI_NHAN, countryName, effectiveTrip, emptyRecord, exitDate, occupationFor, parseMrz, passportValidity, + validityText, vnDate, type Batch, type ExtractionResult, type PassportRecord, type TripInfo, +} from '@pc/core'; +import { imageUrl } from '../lib/api'; +import { itemLink, type Item } from '../lib/types'; +import { ConfBadge } from './ResultsTable'; +import { DateInput, Field, Select, YesNo } from './fields'; + +export interface SaveEdit { result?: ExtractionResult; trip?: TripInfo } + +/** Màn hình chi tiết 1 khách: ảnh hộ chiếu + thông tin khách hàng (sửa được) */ +export function ReviewPanel({ item, batch, step, llmAvailable, onClose, onSave, onRerun, onDelete, onPrev, onNext, standalone }: { + item: Item; + batch: Batch | null; + step?: string; + llmAvailable: boolean; + onClose: () => void; + onSave: (id: string, edit: SaveEdit) => Promise; + onRerun: (id: string, mode: 'ocr' | 'llm') => Promise; + onDelete?: (id: string) => Promise; + onPrev?: () => void; + onNext?: () => void; + /** mở từ link: hiển thị như trang, không phải hộp thoại */ + standalone?: boolean; +}) { + const isAdmin = useSession().user.role === 'admin'; + const [url, setUrl] = useState(''); + const [imgErr, setImgErr] = useState(''); + const [rec, setRec] = useState(item.result?.record ?? emptyRecord()); + const [own, setOwn] = useState(item.trip ?? {}); + const [rot, setRot] = useState(item.rotation ?? 0); + const [zoom, setZoom] = useState(1); + const [tools, setTools] = useState(false); + const [more, setMore] = useState(false); + const [msg, setMsg] = useState<{ ok?: boolean; text: string } | null>(null); + const [busy, setBusy] = useState(false); + useEffect(() => setRec(item.result?.record ?? emptyRecord()), [item.result]); + useEffect(() => setOwn(item.trip ?? {}), [item.trip]); + + // ảnh gốc lấy qua server (lưu trên Telegram), cần đăng nhập + useEffect(() => { + if (!item.telegram && item.status !== 'pending') return; + let u = ''; + let alive = true; + imageUrl(item.batchId, item.id).then((x) => { u = x; if (alive) setUrl(x); else URL.revokeObjectURL(x); }).catch((e) => alive && setImgErr(e.message)); + return () => { alive = false; if (u) URL.revokeObjectURL(u); }; + }, [item.batchId, item.id, item.telegram?.fileUniqueId, item.status]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const tag = (e.target as HTMLElement).tagName; + if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return; + if (e.key === 'Escape' && !standalone) onClose(); + if (e.key === 'ArrowLeft' && onPrev) onPrev(); + if (e.key === 'ArrowRight' && onNext) onNext(); + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [onClose, onPrev, onNext, standalone]); + + const r = item.result; + const working = !!step || item.status === 'pending' || item.status === 'stored'; + const trip = effectiveTrip(batch, { trip: own }); + const groupTrip = effectiveTrip(batch, null); + const setTrip = (p: Partial) => { setOwn((o) => ({ ...o, ...p })); setMsg(null); }; + const setR = (p: Partial) => { setRec((x) => ({ ...x, ...p })); setMsg(null); }; + const validity = passportValidity(rec.expiryDate, trip); + const vText = validityText(validity); + const mrzCheck = useMemo(() => (rec.mrz ? parseMrz(rec.mrz.split('\n')) : null), [rec.mrz]); + const overridden = Object.keys(own).filter((k) => own[k as keyof TripInfo] !== undefined && own[k as keyof TripInfo] !== ''); + /** gợi ý khi giá trị khác thông tin đoàn */ + const differs = (k: keyof TripInfo) => own[k] !== undefined && own[k] !== '' && own[k] !== groupTrip[k] ? 'riêng' : undefined; + + const act = async (fn: () => Promise, ok?: string) => { + setBusy(true); + setMsg(null); + try { + await fn(); + if (ok) setMsg({ ok: true, text: ok }); + return true; + } catch (e) { + setMsg({ text: (e as Error).message }); + return false; + } finally { + setBusy(false); + } + }; + + const save = async (approve: boolean) => { + const base = r ?? { record: rec, confidence: 'LOW' as const, sources: [], checksumOk: false, mrzFound: false, needsReview: true, warnings: [], mrz: null, viz: {} }; + // chỉ lưu các ô khác thông tin đoàn + const tripOwn = Object.fromEntries(Object.entries(own).filter(([k, v]) => v !== undefined && v !== '' && v !== groupTrip[k as keyof TripInfo])) as TripInfo; + const ok = await act(() => onSave(item.id, { + result: { + ...base, + record: { ...rec, fullName: rec.fullName || [rec.surname, rec.givenNames].filter(Boolean).join(' ') }, + sources: [...new Set([...base.sources, 'manual' as const])], + needsReview: approve ? false : base.needsReview, + confidence: approve ? 'HIGH' : base.confidence, + }, + trip: tripOwn, + }), approve ? 'Đã gửi hộ chiếu' : 'Đã lưu'); + if (ok && approve && onNext) onNext(); + }; + + const copyLink = () => act(() => navigator.clipboard.writeText(itemLink(item)), 'Đã sao chép link (người mở cần đăng nhập)'); + + const body = ( +
e.stopPropagation()} role={standalone ? undefined : 'dialog'} aria-label={`Khách ${rec.surname} ${rec.givenNames}`}> +
+
+ + {[rec.surname, rec.givenNames].filter(Boolean).join(' ') || item.name} + {item.name} +
+
+ + {!standalone && } + {!standalone && } + +
+
+
+ {/* ---------------- 1. Ảnh hộ chiếu */} +
+
+ {tools && ( +
+ + + + + {url && Tải ảnh gốc} +
+ )} +
+ {url ? Ảnh hộ chiếu + : imgErr ?

{imgErr}

+ : item.thumb ? : null} +
+
+
+ + + {isAdmin && } +
+
+ + {/* ---------------- 2. Thông tin khách hàng */} +
+

Thông tin khách hàng

+

Kiểm tra thông tin lấy từ hộ chiếu và nhập các thông tin cần thiết.

+
Chú ý Kiểm tra lại thông tin lấy từ hộ chiếu, nếu sai thông tin vui lòng sửa lại
+
Chú ý Vui lòng kiểm tra thời hạn hiệu lực trên hộ chiếu của khách hàng
+ {vText &&
⚠ {vText}
} + {item.error &&
{item.error}
} + {working && !r &&

Ảnh đang chờ xử lý…

} + {r && r.warnings.length > 0 && ( +
+ {r.warnings.length} cảnh báo khi đọc hộ chiếu ({r.confidence === 'HIGH' ? 'độ tin cậy cao' : r.confidence === 'MEDIUM' ? 'độ tin cậy trung bình' : 'độ tin cậy thấp'}) +
    {r.warnings.map((w, i) =>
  • {w}
  • )}
+
+ )} + +
+ setR({ surname: e.target.value.toUpperCase() })} /> + setR({ givenNames: e.target.value.toUpperCase() })} /> + setR({ birthDate: v })} /> + + setR({ nationality: e.target.value.toUpperCase() })} /> + + setR({ documentNumber: e.target.value.toUpperCase().replace(/\s/g, '') })} /> + setR({ issueDate: v })} /> + + setR({ expiryDate: v })} /> + + setTrip({ entryDate: v })} /> + + setTrip({ stayDays: Number(e.target.value) || undefined })} /> + + + setTrip({ multipleEntry: v })} /> +
+
+ setTrip({ receivePlace: v })} /> + setTrip({ groupCode: e.target.value.toUpperCase() })} /> +
+
+ setTrip({ vip: v })} /> + setTrip({ urgent: v })} /> + + setTrip({ occupation: e.target.value })} /> + + setR({ documentCode: e.target.value.toUpperCase() })} /> +
+ + + {more && ( +
+ setR({ fullName: e.target.value })} /> + setR({ placeOfBirth: e.target.value })} /> + setR({ placeOfIssue: e.target.value })} /> + setR({ issuingState: e.target.value.toUpperCase() })} /> + setR({ authority: e.target.value })} /> + setR({ personalNumber: e.target.value })} /> + +