Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-08-11 14:33:56 +08:00
commit 472b530be3
397 files changed
+46450 -34171

No files matched your search

+12 -10
View File
@@ -32,7 +32,7 @@ ENV_FILE="${ROOT_DIR}/.env.${ENV_NAME}"
SHARED_ENV_FILE="${ROOT_DIR}/.env.shared"
ORACLE_CLIENT_DIR="${ROOT_DIR}/oracle_client"
BACKEND_DOCKERFILE="${ROOT_DIR}/backend/Dockerfile"
SCHEMA_DOC_PATH="${ROOT_DIR}/docs/(表+字段).md"
SCHEMA_DOC_PATH="${ROOT_DIR}/docs/integrations/erp/text2sql_schema.md"
ROOT_DOCKERIGNORE="${ROOT_DIR}/.dockerignore"
check_oracle_client() {
@@ -63,7 +63,7 @@ check_backend_build_inputs() {
if [[ ! -f "${SCHEMA_DOC_PATH}" ]]; then
echo "Missing Text2SQL schema doc: ${SCHEMA_DOC_PATH}"
echo "Please ensure docs/(表+字段).md exists in the repository root before building hxops-backend."
echo "Please ensure docs/integrations/erp/text2sql_schema.md exists before building hxops-backend."
exit 1
fi
@@ -75,18 +75,20 @@ check_backend_build_inputs() {
exit 1
fi
if ! grep -Fq 'COPY docs/(表+字段).md /app/docs/(表+字段).md' "${BACKEND_DOCKERFILE}"; then
if ! grep -Fq 'COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md' "${BACKEND_DOCKERFILE}"; then
echo "Invalid backend Dockerfile: schema doc is not copied into the image."
echo "Expected line:"
echo " COPY docs/(表+字段).md /app/docs/(表+字段).md"
echo " COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md"
exit 1
fi
if [[ -f "${ROOT_DOCKERIGNORE}" ]] && grep -Eq '^(docs|docs/\*)$' "${ROOT_DOCKERIGNORE}"; then
if ! grep -Fxq '!docs/(表+字段).md' "${ROOT_DOCKERIGNORE}"; then
echo "Invalid .dockerignore: docs is excluded but docs/(表+字段).md is not re-included."
if ! grep -Fxq '!docs/integrations/erp/text2sql_schema.md' "${ROOT_DOCKERIGNORE}"; then
echo "Invalid .dockerignore: docs is excluded but the Text2SQL schema is not re-included."
echo "Please add the following line to ${ROOT_DOCKERIGNORE}:"
echo " !docs/(表+字段).md"
echo " !docs/integrations/"
echo " !docs/integrations/erp/"
echo " !docs/integrations/erp/text2sql_schema.md"
exit 1
fi
fi
@@ -246,13 +248,13 @@ if [[ "${FRONTEND_CHANGED}" == "true" ]]; then
services+=("hxops-frontend")
fi
if [[ "${BACKEND_CHANGED}" == "true" ]]; then
# 后台 worker 与 backend 共用镜像;仅重建 backend 时 worker 会继续跑旧容器/旧代码
services+=("hxops-backend" "hxops-kb-worker" "hxops-shipping-worker")
# 后端与 worker 共用镜像;后端变更时同步更新,避免 worker 继续运行旧代码。
services+=("hxops-backend" "hxops-kb-worker" "hxops-schedule-worker")
fi
# 如果只是部署配置变更(如 compose/env/脚本),但前后端代码未改,则两边都更新
if [[ ${#services[@]} -eq 0 && "${DEPLOY_CONFIG_CHANGED}" == "true" ]]; then
services=("hxops-frontend" "hxops-backend" "hxops-kb-worker" "hxops-shipping-worker")
services=("hxops-frontend" "hxops-backend" "hxops-kb-worker" "hxops-schedule-worker")
fi
# 无变更则直接跳过,避免无意义重启
+110
View File
@@ -0,0 +1,110 @@
# -*- coding: utf-8 -*-
"""
scripts/fill_overtime_form.py
用途:按模板批量生成指定日期区间的加班申请单 .xls。
依赖:xlrd、xlutils.copy、xlwt。
逻辑:读取模板 ABCD 列固定信息;工作日在前、周六在后,跳过周日。
"""
from datetime import date, timedelta
import xlrd
from xlutils.copy import copy
SRC = r"e:\流程\加班\加班申请单模板_202601_原.xls"
OUT = r"e:\流程\加班\加班申请单_20260721-20260820.xls"
def _date_str(d: date) -> str:
"""将 date 格式化为模板使用的 YYYY-MM-DD 字符串。"""
return d.strftime("%Y-%m-%d")
def _overtime_hours(is_weekday: bool) -> str:
"""
按时间段计算加班时数。
核心逻辑:工作日 18:00–22:30 为 4.5 小时;周六 08:00–20:00 扣午休后为 10 小时。
"""
return "4.5" if is_weekday else "10"
def build_ordered_dates(start: date, end: date) -> tuple[list[date], list[date], list[date]]:
"""
遍历日期区间:工作日(周一~周五)在前,周六在后,跳过周日。
Returns:
(ordered_dates, weekdays, saturdays)
"""
weekdays: list[date] = []
saturdays: list[date] = []
current = start
while current <= end:
wd = current.weekday()
if wd < 5:
weekdays.append(current)
elif wd == 5:
saturdays.append(current)
# 周日 (wd == 6) 跳过
current += timedelta(days=1)
return weekdays + saturdays, weekdays, saturdays
def fill_overtime_workbook(src_path: str, out_path: str, start: date, end: date) -> None:
"""
复制模板并填入加班明细。
核心逻辑:保留表头与 ABCD;工作日类型 026 / 18:00–22:30,周六类型 027 / 08:00–20:00。
"""
rb = xlrd.open_workbook(src_path, formatting_info=True)
rs = rb.sheet_by_index(0)
wb = copy(rb)
ws = wb.get_sheet(0)
dept = rs.cell_value(1, 1)
emp_no = rs.cell_value(1, 2)
name = rs.cell_value(1, 3)
ordered_dates, weekdays, saturdays = build_ordered_dates(start, end)
# [STEP 1] 清除模板旧数据行
for row_idx in range(1, rs.nrows):
for col_idx in range(rs.ncols):
ws.write(row_idx, col_idx, "")
# [STEP 2] 写入新明细
for idx, day in enumerate(ordered_dates, start=1):
is_weekday = day.weekday() < 5
ot_type = "026" if is_weekday else "027"
start_time = "18:00" if is_weekday else "08:00"
end_time = "22:30" if is_weekday else "20:00"
ds = _date_str(day)
row = idx
ws.write(row, 0, str(idx))
ws.write(row, 1, dept)
ws.write(row, 2, emp_no)
ws.write(row, 3, name)
ws.write(row, 4, ot_type)
ws.write(row, 5, ds)
ws.write(row, 6, ds)
ws.write(row, 7, start_time)
ws.write(row, 8, ds)
ws.write(row, 9, end_time)
ws.write(row, 10, _overtime_hours(is_weekday))
ws.write(row, 11, "")
wb.save(out_path)
print(f"Saved: {out_path}")
print(
f"Rows: {len(ordered_dates)} "
f"(weekdays {len(weekdays)} + saturdays {len(saturdays)})"
)
if __name__ == "__main__":
fill_overtime_workbook(
SRC,
OUT,
date(2026, 7, 21),
date(2026, 8, 20),
)
+17 -111
View File
@@ -1,10 +1,9 @@
#!/usr/bin/env bash
#
# scripts/healthcheck.sh
# 用途:部署后健康检查——核心服务运行中,并校验 shipping-worker 可感知 Process Gate 配置。
# 依赖:docker compose、docker-compose.yml、可选 .env 文件。
# 逻辑:由 deploy_compose.sh 在 compose up 后调用;失败则阻断发布继续。
#
# 用途:部署后确认 Web 与后台 Worker 服务均处于 running。
# 依赖:docker compose、docker-compose.yml、目标环境 env 文件。
# 逻辑:逐个检查核心服务,避免仅按容器数量判断而漏掉 schedule/KB worker 启动失败。
set -euo pipefail
ENV_NAME="${1:-default}"
@@ -27,118 +26,25 @@ fi
max_attempts=20
sleep_seconds=3
required_services=(hxops-backend hxops-shipping-worker)
required_services=(hxops-backend hxops-frontend hxops-kb-worker hxops-schedule-worker)
for ((i=1; i<=max_attempts; i++)); do
running=$("${DC_CMD[@]}" "${compose_args[@]}" ps --status running --services || true)
missing=()
for svc in "${required_services[@]}"; do
if ! grep -qx "${svc}" <<<"${running}"; then
missing+=("${svc}")
mapfile -t running_services < <("${DC_CMD[@]}" "${compose_args[@]}" ps --status running --services)
missing_services=()
for service in "${required_services[@]}"; do
if ! printf '%s\n' "${running_services[@]}" | grep -qx "${service}"; then
missing_services+=("${service}")
fi
done
if [[ ${#missing[@]} -eq 0 ]]; then
echo "Core services running for ${ENV_NAME}."
break
if [[ ${#missing_services[@]} -eq 0 ]]; then
echo "Healthcheck passed for ${ENV_NAME} environment."
exit 0
fi
if [[ "${i}" -eq "${max_attempts}" ]]; then
echo "Healthcheck failed for ${ENV_NAME}: missing ${missing[*]}"
"${DC_CMD[@]}" "${compose_args[@]}" ps
exit 1
fi
echo "Healthcheck waiting (${i}/${max_attempts}): missing ${missing[*]}..."
echo "Healthcheck waiting (${i}/${max_attempts}); missing: ${missing_services[*]}"
sleep "${sleep_seconds}"
done
# [STEP] Process Gate:确认 shipping-worker 注入了租约/心跳环境变量(领取 Job 的前提配置)。
gate_env=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-shipping-worker \
sh -c 'printf "%s" "${SHIPPING_PROCESS_GATE_LEASE_SECONDS:-}"' 2>/dev/null || true)
if [[ -z "${gate_env}" ]]; then
echo "Healthcheck failed: hxops-shipping-worker missing SHIPPING_PROCESS_GATE_LEASE_SECONDS"
exit 1
fi
echo "Process Gate worker env OK (LEASE_SECONDS=${gate_env})."
# [STEP] 迁移门禁:确认门禁表已存在(Alembic upgrade 后应有 shipping_process_executions)。
table_check=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend \
python - <<'PY' 2>/dev/null || true
from app import create_app, db
from sqlalchemy import inspect
app = create_app()
with app.app_context():
names = set(inspect(db.engine).get_table_names())
need = {
'shipping_process_executions',
'shipping_process_gates',
'shipping_process_gate_attempts',
}
missing = sorted(need - names)
print('ok' if not missing else 'missing:' + ','.join(missing))
PY
)
if [[ "${table_check}" != "ok" ]]; then
echo "Healthcheck failed: Process Gate tables not ready (${table_check:-empty})"
exit 1
fi
echo "Process Gate migration tables OK."
# [STEP] 领取能力:确认 JobType 已注册且 shipping_process_gate handler 可导入。
handler_check=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-shipping-worker \
python - <<'PY' 2>/dev/null || true
from app.jobs.types import JobType
from app.jobs.registry import get_handler
import app.jobs.handlers # noqa: F401 # 注册全部 handler
handler = get_handler(JobType.SHIPPING_PROCESS_GATE)
print('ok' if callable(handler) else 'missing_handler')
PY
)
if [[ "${handler_check}" != "ok" ]]; then
echo "Healthcheck failed: shipping_process_gate handler not claimable (${handler_check:-empty})"
exit 1
fi
echo "Process Gate job handler OK."
# [STEP] 真实领取:入队探针 Job,等待 shipping-worker 将其推进到终态。
probe_check=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend \
python - <<'PY' 2>/dev/null || true
import time
from app import create_app, db
from app.models import Job
from app.services.shipping_notice.process_gate_job_service import enqueue_process_gate_healthcheck_probe
app = create_app()
with app.app_context():
job_id = enqueue_process_gate_healthcheck_probe()
deadline = time.time() + 45
while time.time() < deadline:
db.session.expire_all()
job = db.session.get(Job, int(job_id))
if job is None:
print('missing_job')
raise SystemExit(0)
status = str(job.status or '')
# [STEP] 仅 succeeded 证明 Handler 跑通 finish_job;failed/cancelled 为假阳性。
if status == 'succeeded':
print('ok:succeeded')
raise SystemExit(0)
if status in {'failed', 'cancelled'}:
print('fail:' + status)
raise SystemExit(0)
time.sleep(1.5)
# 超时前若仍 running,说明已领取但未完成——视为领取能力通过(探针应几乎立即 succeeded)。
db.session.expire_all()
job = db.session.get(Job, int(job_id))
if job is not None and str(job.status or '') == 'running':
print('ok:running')
raise SystemExit(0)
print('timeout:' + str(getattr(job, 'status', None) or 'queued'))
PY
)
if [[ "${probe_check}" != ok:* ]]; then
echo "Healthcheck failed: Process Gate worker probe not healthy (${probe_check:-empty})"
exit 1
fi
echo "Process Gate worker probe OK (${probe_check})."
echo "Healthcheck passed for ${ENV_NAME} environment."
exit 0
echo "Healthcheck failed for ${ENV_NAME} environment."
"${DC_CMD[@]}" "${compose_args[@]}" ps
exit 1
-38
View File
@@ -1,38 +0,0 @@
#!/bin/bash
set -e
# Configuration
SERVER_USER="ai30"
SERVER_IP="192.168.100.230"
REMOTE_DIR="/data/ai-platform/hxops"
BACKEND_CONTAINER="hxops-backend"
echo "=== Starting Remote Server Initialization ==="
echo "Target: $SERVER_USER@$SERVER_IP"
# 1. Check local files exist
if [ ! -f "backend/init_db.py" ] || [ ! -f "backend/seed_production.py" ]; then
echo "Error: Required files not found locally (backend/init_db.py or backend/seed_production.py)"
exit 1
fi
# 2. Upload updated scripts to server
echo ">>> Uploading initialization scripts..."
scp backend/init_db.py $SERVER_USER@$SERVER_IP:$REMOTE_DIR/backend/
scp backend/seed_production.py $SERVER_USER@$SERVER_IP:$REMOTE_DIR/backend/
# 3. Execute remote commands
echo ">>> Executing remote initialization..."
ssh $SERVER_USER@$SERVER_IP "cd $REMOTE_DIR && \
echo '--- 1. Initializing Database (Create DB if missing) ---' && \
docker-compose exec -T $BACKEND_CONTAINER python3 init_db.py && \
echo '--- 2. Running Migrations (Create Tables) ---' && \
docker-compose exec -T $BACKEND_CONTAINER flask db upgrade && \
echo '--- 3. Seeding Data (Admin User & Languages) ---' && \
docker-compose exec -T $BACKEND_CONTAINER python3 seed_production.py"
echo "=== Initialization Complete! ==="
echo "You can now login with:"
echo " Username: admin"
echo " Password: admin"
echo "Please change the password immediately after login."
+82
View File
@@ -0,0 +1,82 @@
"""
scripts/seed_fire_extinguisher_faq.py
用途:为“人事规章”Agent 写入灭火器常见问题的本地 FAQ 兜底。
依赖:Flask 应用、PostgreSQL quick_questions 表。
逻辑:按 Agent 名称和标准问题幂等查找;不存在则创建,存在则补齐同义问法与标准答案。
执行:在仓库根目录运行 `python scripts/seed_fire_extinguisher_faq.py`。
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'backend'))
from app import create_app, db # noqa: E402
from app.models import Agent, QuickQuestion # noqa: E402
FAQ_ITEMS = [
{
'title': '水型灭火器适用场合',
'question': '水型灭火器适用场合',
'aliases': [
'水型灭火器适用于什么火灾',
'水基灭火器能灭什么火',
'水型灭火器适用范围',
'A类火灾用什么灭火器',
],
'answer': (
'水型灭火器主要适用于 A 类火灾,即木材、纸张、棉麻等固体可燃物火灾。'
'不适用于油类、汽油等 B 类液体火灾,也不适用于带电设备火灾;具体以现场灭火器标识和公司安全制度为准。'
),
},
{
'title': '不同类型灭火器怎么使用',
'question': '不同类型灭火器怎么使用',
'aliases': [
'灭火器使用方法',
'灭火器适用场合和使用注意事项',
'各种灭火器分别适合什么火灾',
],
'answer': (
'使用灭火器前先确认火灾类型并站在上风口。水型灭火器主要用于 A 类固体火灾;'
'干粉灭火器适用范围较广,但仍需按瓶身标识选择;二氧化碳灭火器常用于电气设备和精密仪器。'
'油类、电气等场景不要盲目使用水型灭火器,应先断电并按现场安全制度处置。'
),
},
]
def main() -> None:
app = create_app()
with app.app_context():
agent = db.session.query(Agent).filter(Agent.name == '人事规章').first()
if not agent:
raise RuntimeError('未找到“人事规章”Agent,请先确认 Agent 已初始化。')
for item in FAQ_ITEMS:
faq = db.session.query(QuickQuestion).filter(
QuickQuestion.user_id.is_(None),
QuickQuestion.agent_id == agent.id,
QuickQuestion.question == item['question'],
).first()
if faq is None:
faq = QuickQuestion(user_id=None, agent_id=agent.id, sort_order=10)
db.session.add(faq)
faq.title = item['title']
faq.question = item['question']
faq.aliases = item['aliases']
faq.answer = item['answer']
faq.cache_enabled = True
faq.is_enabled = True
faq.stale_at = None
faq.stale_reason = None
db.session.commit()
print(f'已为 Agent={agent.id} 写入 {len(FAQ_ITEMS)} 条灭火器 FAQ。')
if __name__ == '__main__':
main()
+45 -151
View File
@@ -2,20 +2,15 @@
scripts/start_local.ps1
用途:本地一键启动 HXOPS 前后端与后台 worker。
依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口 → 执行 DB 迁移(flask db upgrade)→ 再分别在新 PowerShell 窗口启动各服务。
Worker 使用 backend/ 根目录的并发入口(worker_kb.py / worker_shipping.py),内部通过 multiprocessing 自分叉子进程池;并发数由 -KbConcurrency / -ShippingConcurrency 透传到环境变量。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。
#>
param(
[ValidateSet("sqlite", "postgres")]
[string]$DbMode = "sqlite",
[string]$DatabaseUrl = "",
[int]$KbConcurrency = 1,
[int]$ShippingConcurrency = 1,
[switch]$SkipInstall,
[switch]$SkipMigrate,
[switch]$SkipWorker,
[switch]$IncludeRpaWorker,
[switch]$NoHotReload
[switch]$SkipRpaWorker
)
$ErrorActionPreference = "Stop"
@@ -66,17 +61,11 @@ function Stop-StaleHxopsPythonProcesses {
$patterns = @(
[regex]::Escape((Join-Path $BackendPath "run.py")),
[regex]::Escape((Join-Path $BackendPath "worker.py")),
[regex]::Escape((Join-Path $BackendPath "worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "worker_shipping.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py"))
)
# 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。
# 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。
# 清理阶段必须全部覆盖,避免历史残留进程导致的「多实例重复领取 job / 端口占用」。
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
@@ -226,32 +215,6 @@ function Ensure-Backend {
}
}
function Invoke-DbMigrate {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan
Set-Location $BackendPath
$venvPy = Join-Path $BackendPath "venv\Scripts\python.exe"
$env:FLASK_APP = "run.py"
$env:FLASK_ENV = "development"
$env:ENV_NAME = "dev"
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$env:DATABASE_URL = $DbUrl
}
& $venvPy -m flask db upgrade
if ($LASTEXITCODE -ne 0) {
throw "[db-migrate] flask db upgrade failed with exit code $LASTEXITCODE"
}
Write-Host "[db-migrate] migration completed." -ForegroundColor Green
}
function Ensure-Frontend {
param(
[string]$FrontendPath,
@@ -275,8 +238,7 @@ function Start-BackendWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl,
[bool]$DisableHotReload = $false
[string]$DbUrl
)
$dbExport = ""
@@ -285,13 +247,7 @@ function Start-BackendWindow {
$dbExport = "`$env:DATABASE_URL='$escaped'; "
}
if ($DisableHotReload) {
$reloaderEnv = "`$env:WERKZEUG_RUN_MAIN='true'; "
} else {
$reloaderEnv = ""
}
$cmd = "$dbExport$reloaderEnv Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
@@ -308,34 +264,6 @@ function Get-DatabaseUrlExport {
return ""
}
function Import-DotEnvFilesToCurrentShell {
param([string[]]$Paths)
foreach ($path in $Paths) {
if (-not (Test-Path $path)) {
Write-Host "[env] skip (not found): $path" -ForegroundColor DarkGray
continue
}
Write-Host "[env] loading: $path" -ForegroundColor Cyan
foreach ($line in Get-Content $path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') {
continue
}
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
)) {
$value = $value.Substring(1, $value.Length - 2)
}
Set-Item -Path "env:$name" -Value $value -ErrorAction SilentlyContinue
}
}
}
}
function Get-DotEnvExportPrefix {
param([string[]]$Paths)
@@ -383,17 +311,13 @@ function Start-KbWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl,
[int]$Concurrency = 1
[string]$DbUrl
)
$envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl
$envPrefix += " `$env:ENV_NAME='dev'; `$env:KB_WORKER_CONCURRENCY='$Concurrency';"
Start-WorkerWindow `
-Title "kb-worker (concurrency=$Concurrency)" `
-Title "kb-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix $envPrefix `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\worker_kb.py"
}
@@ -401,18 +325,28 @@ function Start-ShippingWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl,
[int]$Concurrency = 1
[string]$DbUrl
)
$envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl
$envPrefix += " `$env:ENV_NAME='dev'; `$env:SHIPPING_NOTICE_WORKER_CONCURRENCY='$Concurrency';"
Start-WorkerWindow `
-Title "shipping-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\workers\worker_shipping_notice.py"
}
function Start-ScheduleWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
Start-WorkerWindow `
-Title "shipping-worker (concurrency=$Concurrency)" `
-Title "schedule-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix $envPrefix `
-Command ".\venv\Scripts\python.exe .\worker_shipping.py"
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\workers\worker_scheduler.py"
}
function Start-FreightRpaWorkerWindow {
@@ -423,7 +357,7 @@ function Start-FreightRpaWorkerWindow {
)
$envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles
$envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:SHIPPING_NOTICE_RPA_WORKER_MOCK='true';"
$envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:FREIGHT_RPA_MOCK='true';"
Start-WorkerWindow `
-Title "freight-rpa-worker" `
@@ -433,16 +367,8 @@ function Start-FreightRpaWorkerWindow {
}
function Start-FrontendWindow {
param(
[string]$FrontendPath,
[bool]$DisableHotReload = $false
)
if ($DisableHotReload) {
$envArg = "`$env:VITE_HMR='false'; "
} else {
$envArg = ""
}
$cmd = "$envArg Set-Location '$FrontendPath'; npm run dev"
param([string]$FrontendPath)
$cmd = "Set-Location '$FrontendPath'; npm run dev"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
@@ -453,61 +379,31 @@ $frontendDir = Join-Path $repoRoot "frontend"
if (-not (Test-Path $backendDir)) { throw "backend directory not found: $backendDir" }
if (-not (Test-Path $frontendDir)) { throw "frontend directory not found: $frontendDir" }
$pythonCmd = Get-PythonCommand
$doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$envFiles = @(
(Join-Path $repoRoot ".env.shared"),
(Join-Path $repoRoot ".env.dev"),
(Join-Path $repoRoot ".env.local")
)
# 优先级加载:.env.shared → .env.dev → .env.local(后者覆盖前者)
# 显式传参 -DatabaseUrl 的优先级最高,最后覆盖。
Import-DotEnvFilesToCurrentShell -Paths $envFiles
$effectiveDbUrl = $DatabaseUrl
if ([string]::IsNullOrWhiteSpace($effectiveDbUrl)) {
$effectiveDbUrl = $env:DATABASE_URL
}
if (-not [string]::IsNullOrWhiteSpace($DatabaseUrl)) {
$env:DATABASE_URL = $DatabaseUrl
Write-Host "[env] DATABASE_URL overridden from -DatabaseUrl parameter." -ForegroundColor DarkGray
}
$pythonCmd = Get-PythonCommand
$doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Write-Host "kb concurrency: $KbConcurrency | shipping concurrency: $ShippingConcurrency" -ForegroundColor Green
}
if ($DbMode -eq "postgres") {
if (-not [string]::IsNullOrWhiteSpace($effectiveDbUrl)) {
$masked = $effectiveDbUrl -replace '(?<=://[^:]+:)[^@]+', '******'
Write-Host "postgres DATABASE_URL: $masked" -ForegroundColor DarkGray
}
else {
Write-Warning "DbMode=postgres but no DATABASE_URL found in env files or -DatabaseUrl parameter. Relying on app default."
}
}
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $effectiveDbUrl -DoInstall $doInstall
if (-not $SkipMigrate.IsPresent) {
Invoke-DbMigrate -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl
}
else {
Write-Host "[db-migrate] skipped (-SkipMigrate)." -ForegroundColor DarkGray
}
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$windowCount = 2
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $KbConcurrency
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $ShippingConcurrency
$windowCount += 2
if ($IncludeRpaWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Start-ScheduleWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
$windowCount += 3
if (-not $SkipRpaWorker.IsPresent) {
Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles
$windowCount += 1
}
@@ -518,9 +414,7 @@ $windowCount += 1
Write-Host ""
Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Write-Host "Workers: kb-worker(x$KbConcurrency), shipping-worker(x$ShippingConcurrency)$(if ($IncludeRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
Write-Host "(Worker 进程由 master 进程内部通过 multiprocessing fork,每个 Worker 窗口只需要一个 master。)" -ForegroundColor DarkGray
Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray
Write-Host "Workers: kb-worker, shipping-worker, schedule-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
}
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
Write-Host "Backend URL: http://127.0.0.1:5052" -ForegroundColor Green