Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-06-09 10:33:14 +08:00
commit a3a01592f4
103 files changed
+17448 -349

No files matched your search

+50 -2
View File
@@ -8,12 +8,14 @@ set -euo pipefail
# 4: 前端是否有变更(true/false)
# 5: 后端是否有变更(true/false)
# 6: 部署配置是否有变更(true/false)
# 7: 是否跳过 flask db upgrade(true/false;镜像回滚时应为 true)
ENV_NAME="${1:-default}"
FRONTEND_IMAGE="${2:-}"
BACKEND_IMAGE="${3:-}"
FRONTEND_CHANGED="${4:-false}"
BACKEND_CHANGED="${5:-false}"
DEPLOY_CONFIG_CHANGED="${6:-false}"
SKIP_DB_MIGRATE="${7:-false}"
# 统一使用仓库根目录下的 compose 和环境文件
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -82,6 +84,40 @@ check_backend_build_inputs() {
fi
}
verify_prebuilt_image() {
local image="$1"
if [[ -z "${image}" ]]; then
echo "Prebuilt mode requires an image reference for the service being deployed."
exit 1
fi
if ! docker image inspect "${image}" >/dev/null 2>&1; then
echo "Prebuilt image not found: ${image}"
echo "List available tags on this host: docker images 'hxops-*' --format '{{.Repository}}:{{.Tag}}'"
exit 1
fi
}
tag_built_images() {
local commit_sha="${GIT_COMMIT:-}"
if [[ -z "${commit_sha}" ]]; then
echo "GIT_COMMIT is empty, skipping version image tags."
return 0
fi
local short_sha="${commit_sha:0:8}"
local version_tag="${ENV_NAME}-${short_sha}"
# 对当前 :local 镜像打版本 tag(含增量部署),便于回滚时前后端 tag 成对存在
if docker image inspect hxops-frontend:local >/dev/null 2>&1; then
docker tag hxops-frontend:local "hxops-frontend:${version_tag}"
echo "Tagged hxops-frontend:${version_tag}"
fi
if docker image inspect hxops-backend:local >/dev/null 2>&1; then
docker tag hxops-backend:local "hxops-backend:${version_tag}"
echo "Tagged hxops-backend:${version_tag}"
fi
}
# 基础文件检查:compose 文件必须存在
if [[ ! -f "${COMPOSE_FILE}" ]]; then
echo "Missing compose file: ${COMPOSE_FILE}"
@@ -159,6 +195,7 @@ fi
echo "Deploying environment: ${ENV_NAME}"
echo "Services: ${services[*]}"
echo "Prebuilt image mode: ${PREBUILT_MODE}"
echo "Skip DB migrate: ${SKIP_DB_MIGRATE}"
if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then
echo "Checking Oracle Instant Client directory..."
@@ -173,18 +210,29 @@ fi
# 预构建镜像模式:只启动,不构建
# 非预构建镜像模式:在目标机本地构建并启动
if [[ "${PREBUILT_MODE}" == "true" ]]; then
if printf '%s\n' "${services[@]}" | grep -qx "hxops-frontend"; then
verify_prebuilt_image "${FRONTEND_IMAGE}"
fi
if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then
verify_prebuilt_image "${BACKEND_IMAGE}"
fi
"${DC_CMD[@]}" "${compose_args[@]}" up -d --no-build "${services[@]}"
else
# Dockerfile 使用 apt/pip cache mount,需启用 BuildKit
export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1
"${DC_CMD[@]}" "${compose_args[@]}" up -d --build "${services[@]}"
tag_built_images
fi
# Keep DB schema aligned with backend code after deployment.
if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then
echo "Running database migrations (flask db upgrade)..."
"${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend flask --app manage.py db upgrade
if [[ "${SKIP_DB_MIGRATE}" == "true" ]]; then
echo "SKIP_DB_MIGRATE=true, skipping flask db upgrade."
else
echo "Running database migrations (flask db upgrade)..."
"${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend flask --app manage.py db upgrade
fi
fi
"${ROOT_DIR}/scripts/healthcheck.sh" "${ENV_NAME}" "${COMPOSE_FILE}" "${ENV_FILE}"
+37
View File
@@ -0,0 +1,37 @@
# 货代 RPA PoC
Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 脚本在 Windows 货代终端上运行(或由本 PoC worker 在开发环境模拟)。
## 目录约定
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json`,RPA 读取后导库存 |
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
## 开发环境 Mock
1. 在 `.env.dev` 配置目录与 Tool Key(见 `docs/shipping_notice_runbook.md`)。
2. 启动后端。
3. 另开终端运行 PoC worker:
```powershell
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>"
$env:FREIGHT_RPA_MOCK = "true"
# 四个 FREIGHT_* 目录与 backend 相同
python scripts/rpa/freight_rpa_worker.py
```
4. 在 Chat 中走 `ensure_inventory` / `upload_to_freight`,worker 会自动回调 `/api/shipping-notice/rpa/*`。
## 生产 RPA
`FREIGHT_RPA_MOCK=false` 时 worker **不会**自动处理触发文件,需业务按 SOP 用 UiPath / Power Automate 等:
1. 监听 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 新 JSON → 登录货代 UI 导出库存 → 保存到 `FREIGHT_INVENTORY_DROP_DIR` → POST `inventory-ready`。
2. 监听 `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` → 读取 `file_path` 在货代 UI 上传 → POST `upload-complete`。
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
+211
View File
@@ -0,0 +1,211 @@
"""
Freight RPA worker (PoC).
Polls trigger JSON files written by hxops and reports results back via Tool API callbacks.
Set FREIGHT_RPA_MOCK=true to simulate export/upload without a real freight UI.
Usage:
python scripts/rpa/freight_rpa_worker.py
Required env (same as backend):
HXOPS_API_BASE e.g. http://127.0.0.1:5052
SHIPPING_NOTICE_TOOL_API_KEY
FREIGHT_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR
Optional:
FREIGHT_RPA_MOCK=true
FREIGHT_RPA_POLL_SECONDS=3
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
try:
from openpyxl import Workbook
except ImportError:
Workbook = None # type: ignore
def _env(name: str, default: str = "") -> str:
return str(os.getenv(name) or default).strip()
def _require_path(name: str) -> Path:
value = _env(name)
if not value:
raise SystemExit(f"Missing env: {name}")
backend_dir = Path(__file__).resolve().parents[2] / "backend"
path = Path(value)
if not path.is_absolute():
normalized = value.replace("\\", "/")
if normalized.startswith("backend/"):
path = backend_dir / normalized[len("backend/") :]
else:
path = backend_dir / value
path = path.resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def _post_callback(path: str, payload: dict) -> None:
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
key = _env("SHIPPING_NOTICE_TOOL_API_KEY") or _env("INTEGRATION_API_KEY")
if not key:
raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY")
url = f"{base}{path}"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={
"Content-Type": "application/json",
"X-Shipping-Tool-Key": key,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
body = resp.read().decode("utf-8")
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
print(f"[callback] {path} HTTP {exc.code}: {err[:300]}", file=sys.stderr)
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
dest = drop_dir / Path(sample).name
shutil.copy2(sample, dest)
return dest
if Workbook is None:
raise RuntimeError("openpyxl required to generate mock inventory")
dest = drop_dir / f"inventory_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
wb = Workbook()
ws = wb.active
ws.title = "Inventory"
ws.append(["料号", "可用数量"])
ws.append(["A001", 100])
ws.append(["A002", 50])
wb.save(dest)
return dest
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
if not task_no:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[inventory] real RPA not implemented; trigger kept: {trigger_path.name}")
return
try:
out_file = _write_sample_inventory(drop_dir, task_no)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"success": True,
"file_path": str(out_file),
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[inventory] mock export done for {task_no} -> {out_file.name}")
except Exception as exc:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"success": False,
"error_message": str(exc),
})
trigger_path.unlink(missing_ok=True)
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
file_path = str(body.get("file_path") or "").strip()
if not task_no:
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
return
if file_path and not Path(file_path).is_file():
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"success": False,
"error_message": f"queue file missing: {file_path}",
})
trigger_path.unlink(missing_ok=True)
return
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"success": True,
"freight_ref_no": ref,
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[upload] mock upload done for {task_no} ref={ref}")
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
if not trigger_dir.is_dir():
return
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
def main() -> None:
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3"))
inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed"
print("[freight_rpa_worker] started")
print(f" mock={_env('FREIGHT_RPA_MOCK', 'true')}")
print(f" inventory_triggers={inv_trigger_dir}")
print(f" upload_triggers={upload_trigger_dir}")
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
while True:
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)
if __name__ == "__main__":
main()