Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f1c4043d4 | ||
|
|
97ec6ed44b | ||
|
|
f777867749 | ||
|
|
9c9c2c9cd5 | ||
|
|
79fb675af5 | ||
|
|
880a8fb57c | ||
|
|
a9404f01e2 | ||
|
|
f17f355366 | ||
|
|
1a82894b6a | ||
|
|
6181760045 | ||
|
|
80bb27515c | ||
|
|
af7b56b14b | ||
|
|
a80895b75f | ||
|
|
04f94ad665 | ||
|
|
fd1ec32dd6 | ||
|
|
9d07793a57 | ||
|
|
d26f6ecfd3 | ||
|
|
fef233344b | ||
|
|
783f930380 | ||
|
|
888f323b23 | ||
|
|
689d55bcf9 | ||
|
|
eba3a1b562 | ||
|
|
b764fcb33c | ||
|
|
78797d8eca | ||
|
|
b8f6ca586d | ||
|
|
767fca6a79 | ||
|
|
cfd3fb15cc | ||
|
|
1902949f69 | ||
|
|
a415bcdb88 | ||
|
|
8853ea2dfa | ||
|
|
439241dd83 | ||
|
|
147edd042f | ||
|
|
e58dd86d5b | ||
|
|
aacdca6930 | ||
|
|
3f1cee8006 | ||
|
|
99c26a393a | ||
|
|
e051ab2e9b | ||
|
|
6a428bd468 | ||
|
|
ce445d0fb8 | ||
|
|
8444ded971 | ||
|
|
f4e87b0c02 | ||
|
|
1f66307bba | ||
|
|
a081966342 | ||
|
|
cded4238a9 | ||
|
|
3c3d273ee3 | ||
|
|
97162016ee | ||
|
|
167c888718 | ||
|
|
97fc9bec14 | ||
|
|
df688844d3 | ||
|
|
64041893a5 | ||
|
|
06b80803c4 | ||
|
|
27151b3ee5 | ||
|
|
ab5b3580c1 | ||
|
|
805675f8db |
@@ -0,0 +1,31 @@
|
||||
**
|
||||
!Dockerfile
|
||||
!requirements.txt
|
||||
!am.py
|
||||
!rates_extra.py
|
||||
!start.bat
|
||||
!启动.bat
|
||||
!logistics_chat/
|
||||
!logistics_chat/**
|
||||
!templates/
|
||||
!templates/**
|
||||
!static/
|
||||
!static/**
|
||||
!deploy/
|
||||
!deploy/**
|
||||
!scripts/
|
||||
!scripts/**
|
||||
!tests/
|
||||
!tests/**
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/*.db
|
||||
**/*.sqlite3
|
||||
**/runtime.env
|
||||
**/release.env
|
||||
**/*.htpasswd
|
||||
**/*.pem
|
||||
**/*.key
|
||||
**/tls/
|
||||
@@ -0,0 +1,26 @@
|
||||
# Copy this file to .env in the repository root and enter your DeepSeek API key.
|
||||
# The application reads .env at startup. Restart after changing this file.
|
||||
# The process environment takes precedence, including an explicitly empty value.
|
||||
# Keep real credentials in .env; never put them in this example or source files.
|
||||
DEEPSEEK_API_KEY=
|
||||
# Optional fixed tenant scope for the internal order test dataset. Empty = all imported test rows.
|
||||
ORDER_DATA_TENANT_ID=
|
||||
# Default front-end customer account: admin / 123456. It grants no staff access.
|
||||
CUSTOMER_DEMO_ENABLED=true
|
||||
CUSTOMER_DEMO_USERNAME=admin
|
||||
# Bind one explicit tenant, or leave empty to use the current local dataset grants.
|
||||
CUSTOMER_DEMO_TENANT_ID=
|
||||
# On initial association, grant the default account the tenants currently in the local table.
|
||||
CUSTOMER_DEMO_LOCAL_ORDERS=true
|
||||
# Optional password hash used only when creating the default account; not plaintext.
|
||||
# CUSTOMER_DEMO_PASSWORD_HASH=
|
||||
# Short-recording ASR is independent of DEEPSEEK_API_KEY. No credentials = voice input unavailable.
|
||||
ASR_PROVIDER=baidu
|
||||
BAIDU_ASR_API_KEY=
|
||||
BAIDU_ASR_SECRET_KEY=
|
||||
# Optional absolute ffmpeg executable path. Empty = find ffmpeg on PATH. Docker includes it.
|
||||
FFMPEG_BIN=
|
||||
# Optional alternative: ASR_PROVIDER=dashscope, with a separate Alibaba Cloud Model Studio key.
|
||||
ASR_API_KEY=
|
||||
ASR_URL=https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
|
||||
ASR_MODEL=qwen3-asr-flash
|
||||
@@ -0,0 +1,7 @@
|
||||
deploy/*.service text eol=lf
|
||||
deploy/*.sh text eol=lf
|
||||
deploy/*.example text eol=lf
|
||||
deploy/*.yml text eol=lf
|
||||
Jenkinsfile text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
.dockerignore text eol=lf
|
||||
+18
-1
@@ -4,6 +4,10 @@ __pycache__/
|
||||
*.pyo
|
||||
.pytest_cache/
|
||||
|
||||
# 虚拟环境
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# 数据库(含聊天记录,不要提交)
|
||||
*.db
|
||||
*.db-journal
|
||||
@@ -17,11 +21,24 @@ __pycache__/
|
||||
# 环境变量与密钥
|
||||
.env
|
||||
.env.*
|
||||
!.env.example # 配置示例(不含 Key),需要提交
|
||||
# 配置示例(不含 Key),需要提交
|
||||
!.env.example
|
||||
|
||||
# 运行时数据,仅保留上传目录占位文件
|
||||
/logs/
|
||||
/backups/
|
||||
/uploads/*
|
||||
!/uploads/.gitkeep
|
||||
|
||||
# 自签证书与私钥(本地演示用,不要提交)
|
||||
cert.pem
|
||||
key.pem
|
||||
*.pem
|
||||
*.key
|
||||
*.htpasswd
|
||||
runtime.env
|
||||
release.env
|
||||
/work/
|
||||
|
||||
# 系统文件
|
||||
Thumbs.db
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Navigation
|
||||
|
||||
Use `am.py` for CLI/WSGI, `logistics_chat/` for business code, and `static/css/`/`static/js/` for page assets. [Architecture](docs/architecture.md) defines module contracts and extraction rules.
|
||||
|
||||
| Area | Files and search anchors |
|
||||
|---|---|
|
||||
| AI | `logistics_chat/chat_service.py`: `create_chat_stream`; `logistics_chat/ai_client.py`: `post_completion` |
|
||||
| Voice input | `static/js/voice.js`: `ChatVoice.create`; `logistics_chat/speech_service.py`: `transcribe_recording`, `baidu_transcribe`; `logistics_chat/routes/speech.py` |
|
||||
| Guest identity | `static/js/visitor.js`: bootstrap and cookie recovery; `logistics_chat/visitor_service.py`: owner checks; `routes/visitor.py`: customer human support |
|
||||
| Customer login | `logistics_chat/customer_service.py`: sessions, default customer bootstrap, order conversation binding; `routes/customer.py`; `static/js/customer.js`: login and logout |
|
||||
| Order lookup UI | `static/js/order_lookup.js`: `OrderLookup.create`; `chat.js`: `showOrderLookup`, `fillTrackCard`; `support.js`: `copyText` |
|
||||
| Chat drafts | `static/js/drafts.js`: `ChatDrafts.create`; `chat.js`: `flushDraft`, `restoreDraft`, startup recovery |
|
||||
| Knowledge | `logistics_chat/knowledge.py`: `knowledge_list`, `search_knowledge`; `docs/knowledge.md` |
|
||||
| Pricing | `logistics_chat/pricing.py`: `RATES`, `calc_freight`; `quote_intent.py`: `parse_intent`; `quote_service.py`: `answer_quote`; `quote_engine.py`: `quantity`, `render_rates`; `quote_answers.py`, `quote_fees.py`: local business terms and fees |
|
||||
| US quote data | `logistics_chat/quote_workbook.py`: local detail export; `quote_data.py`: versioned SQLite imports; `quote_engine.py`: matching/calculation; `quote_service.py`: conversational reply; `scripts/import_quote_data.py` |
|
||||
| Common customer questions | `logistics_chat/shipping_faq.py`: pre-shipment material; `quote_allocations.py`: per-warehouse weights; `quote_context.py`: chronological edits; `order_explanations.py`: business status, latest actual nodes and operation boundaries |
|
||||
| Reply boundaries / order summaries | `logistics_chat/customer_faq.py`: supported actions; `quote_scope.py`: US-only fallback; `quote_edits.py`: rejected conditions; `quote_material.py`: partial metal chargeable weight; `order_query.py`: bounded filters; `order_listing.py`: scoped five-row summaries and conversation pages; `order_tracking.py`: `current_stage` |
|
||||
| Tracking | `logistics_chat/tracking.py`: `extract_tracking_no`, `build_track`, `CARD_PREFIX` |
|
||||
| Order test data | `logistics_chat/order_data.py`: `lookup_order`, `count_orders`, `answer_query`, `import_records`; `scripts/import_order_test_data.py` |
|
||||
| Persistence | `logistics_chat/db.py`: `init_db`, `save_message`; `logistics_chat/history_service.py` |
|
||||
| Human support | `logistics_chat/human_service.py`: lifecycle, transfer, notes, recall; `logistics_chat/routes/human.py` |
|
||||
| Business / files | `logistics_chat/business_service.py`, `logistics_chat/file_service.py`; `logistics_chat/routes/` |
|
||||
| UI | `templates/`; `static/css/theme.css`: tokens; page CSS; `static/js/chat.js`: `doSend`, `I18N`; `static/js/admin.js`: `poll`, `sendReply`, `setChatView`; `admin_tools.js`: notes, transfer, search; `support.js`: emoji, notifications, rating |
|
||||
| Startup / hooks | `logistics_chat/__init__.py`: `create_app`; `config.py`: `default_config`; `hooks.py`, `runtime.py` in that package |
|
||||
| CLI / tests | `start.bat`: `probe_python`; `scripts/`, `tests/`, `examples/requests/` |
|
||||
| Deployment | `Jenkinsfile`, `Dockerfile`; `deploy/gray_config.py`: `GrayConfig`; publish/activate/TLS scripts; `docs/deployment.md` |
|
||||
|
||||
## Efficient Search & File Boundaries
|
||||
|
||||
Start with mapped files, then follow callers. Prefer symbols over saved line numbers. `rg --files` includes untracked source; respect ignored runtime data.
|
||||
|
||||
```powershell
|
||||
rg --files
|
||||
rg -n -F -e 'calc_freight' -e '/api/human/' logistics_chat static/js
|
||||
```
|
||||
|
||||
Routes adapt HTTP; services compose rules, persistence, and model calls. Keep pure rules independent of Flask. Preserve URL/SSE/storage contracts and update navigation after moves.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
|
||||
Copy-Item .env.example .env # First run only; set DEEPSEEK_API_KEY inside .env.
|
||||
.\.venv\Scripts\python.exe am.py
|
||||
.\.venv\Scripts\python.exe -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
`start.bat` prefers active `VIRTUAL_ENV`; verify with `start.bat --check-python`. No frontend build is required.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
|
||||
Use four-space Python indentation, `snake_case`, `UPPER_SNAKE_CASE` constants, and JavaScript `camelCase`. Preserve Chinese terminology. No formatter/linter is configured.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
Use `tests/test_<feature>.py` and `test_<behavior>`. Mock DeepSeek; configure temporary database/upload/backup/log paths before `create_app`. Pytest: `.\.venv\Scripts\python.exe -m pytest -v`; Linux/macOS: `.venv/bin/python -m pytest -v`.
|
||||
|
||||
Tests run `tests/frontend/admin.test.cjs`, `chat.test.cjs`, `voice.test.cjs`, `visitor.test.cjs`, and `drafts.test.cjs` when Node.js is available; no npm dependencies. Baidu ASR uses FFmpeg on PATH or `FFMPEG_BIN`; provider calls are mocked in tests.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
History uses concise Chinese summaries. Keep commits focused. PRs explain behavior, validation, linked issues, and UI screenshots.
|
||||
|
||||
## Security & Configuration Tips
|
||||
|
||||
Never commit credentials or runtime/customer data. Revoke exposed keys. Keep `uploads/.gitkeep`. Startup reads root `.env`; environment variables override it. Restart after changes. `create_app` initializes storage unless `INITIALIZE_RUNTIME=False`; order and staff tables start empty. The requested default customer account is separate from staff and stores only a password hash. Default HOST is `0.0.0.0`; Linux deployment binds loopback. Staff authentication relies on Nginx: protect staff and unknown routes by default and expose only the owner-checked customer allowlist. Never expose the upstream port publicly. Guest keys authorize public chat history, never customer orders. Order facts and sensitive conversation history require the server-validated customer and tenant; never accept tenant claims from client input. Do not assign unowned legacy records to a new visitor.
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim
|
||||
FROM ${PYTHON_BASE_IMAGE} AS runtime
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
WORKDIR /app
|
||||
COPY requirements.txt ./
|
||||
ARG DEBIAN_MIRROR=https://deb.debian.org
|
||||
RUN case "$DEBIAN_MIRROR" in https://deb.debian.org|https://mirrors.tuna.tsinghua.edu.cn) ;; *) exit 2;; esac \
|
||||
&& sed -i "s|http://deb.debian.org|$DEBIAN_MIRROR|g" /etc/apt/sources.list.d/debian.sources \
|
||||
&& apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=30 update \
|
||||
&& apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=30 install -y --no-install-recommends ffmpeg \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN python -m pip install --no-cache-dir -r requirements.txt \
|
||||
&& groupadd --gid 10001 baiyue \
|
||||
&& useradd --uid 10001 --gid 10001 --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin baiyue \
|
||||
&& mkdir -p /var/lib/baiyue-logistics-chat /var/log/baiyue-logistics-chat \
|
||||
&& chown 10001:10001 /var/lib/baiyue-logistics-chat /var/log/baiyue-logistics-chat
|
||||
COPY am.py rates_extra.py ./
|
||||
COPY logistics_chat/ ./logistics_chat/
|
||||
COPY templates/ ./templates/
|
||||
COPY static/ ./static/
|
||||
COPY deploy/__init__.py deploy/wsgi.py ./deploy/
|
||||
COPY scripts/import_order_test_data.py scripts/import_quote_data.py ./scripts/
|
||||
USER 10001:10001
|
||||
EXPOSE 5000
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=6 \
|
||||
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/healthz', timeout=2).close()"]
|
||||
CMD ["python", "-m", "waitress", "--listen=0.0.0.0:5000", "--threads=8", "--channel-timeout=300", "--max-request-body-size=12582912", "--url-scheme=https", "--trusted-proxy=*", "--trusted-proxy-count=1", "--trusted-proxy-headers=x-forwarded-for", "--call", "deploy.wsgi:create_app"]
|
||||
|
||||
FROM runtime AS test
|
||||
COPY Dockerfile ./
|
||||
COPY deploy/ ./deploy/
|
||||
COPY tests/ ./tests/
|
||||
COPY scripts/ ./scripts/
|
||||
COPY start.bat 启动.bat ./
|
||||
RUN python -m pytest -q -p no:cacheprovider
|
||||
|
||||
FROM ${PYTHON_BASE_IMAGE} AS certbot
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
|
||||
RUN python -m pip install --no-cache-dir certbot==5.8.0
|
||||
ENTRYPOINT ["certbot"]
|
||||
|
||||
FROM runtime AS production
|
||||
Vendored
+98
@@ -0,0 +1,98 @@
|
||||
pipeline {
|
||||
agent { label 'java-builder' }
|
||||
options {
|
||||
timestamps()
|
||||
disableConcurrentBuilds()
|
||||
skipDefaultCheckout(true)
|
||||
timeout(time: 30, unit: 'MINUTES')
|
||||
}
|
||||
stages {
|
||||
stage('Checkout selected gray revision') {
|
||||
steps {
|
||||
script {
|
||||
if (env.JOB_BASE_NAME != 'baiyue-logistics-chat-gray' || params.ENVIRONMENT != 'gray') {
|
||||
error('This pipeline is restricted to the logistics chat gray job')
|
||||
}
|
||||
checkout scm
|
||||
env.SOURCE_COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
|
||||
env.CHAT_IMAGE = "baiyue-logistics-chat-gray:${env.SOURCE_COMMIT.take(12)}-b${env.BUILD_NUMBER}"
|
||||
env.CERTBOT_IMAGE = "baiyue-logistics-chat-certbot:${env.SOURCE_COMMIT.take(12)}-b${env.BUILD_NUMBER}"
|
||||
if (!(params.PYTHON_BASE_IMAGE ==~ /[A-Za-z0-9][A-Za-z0-9._\/:@-]+/)) {
|
||||
error('Invalid Python base image reference')
|
||||
}
|
||||
if (!((params.ASR_PROVIDER ?: '') in ['', 'baidu'])) {
|
||||
error('Gray speech provider must be baidu or disabled')
|
||||
}
|
||||
if (!((params.DEBIAN_MIRROR ?: 'https://deb.debian.org') in ['https://deb.debian.org', 'https://mirrors.tuna.tsinghua.edu.cn'])) {
|
||||
error('Select a supported Debian mirror')
|
||||
}
|
||||
if (params.IMPORT_QUOTE_DATA && !(params.QUOTE_SNAPSHOT_CREDENTIAL_ID ==~ /[A-Za-z0-9_.-]+/)) {
|
||||
error('Select the explicitly supplied private quote snapshot credential')
|
||||
}
|
||||
}
|
||||
sh '''set -eu
|
||||
for file in deploy/*.sh; do bash -n "$file"; done
|
||||
node --test tests/frontend/*.test.cjs
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Build and test image') {
|
||||
steps {
|
||||
withEnv(["PYTHON_BASE_IMAGE=${params.PYTHON_BASE_IMAGE}", "DEBIAN_MIRROR=${params.DEBIAN_MIRROR ?: 'https://deb.debian.org'}"]) {
|
||||
sh '''set -eu
|
||||
docker build --target test --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE" --build-arg DEBIAN_MIRROR="$DEBIAN_MIRROR" -t "$CHAT_IMAGE-test" .
|
||||
docker build --target production --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE" --build-arg DEBIAN_MIRROR="$DEBIAN_MIRROR" \
|
||||
--label "org.opencontainers.image.revision=$SOURCE_COMMIT" -t "$CHAT_IMAGE" .
|
||||
docker build --target certbot --build-arg PYTHON_BASE_IMAGE="$PYTHON_BASE_IMAGE" --build-arg DEBIAN_MIRROR="$DEBIAN_MIRROR" \
|
||||
--label "org.opencontainers.image.revision=$SOURCE_COMMIT" -t "$CERTBOT_IMAGE" .
|
||||
'''
|
||||
}
|
||||
script {
|
||||
env.CHAT_IMAGE_ID = sh(script: 'docker image inspect --format "{{.Id}}" "$CHAT_IMAGE"', returnStdout: true).trim()
|
||||
env.CERTBOT_IMAGE_ID = sh(script: 'docker image inspect --format "{{.Id}}" "$CERTBOT_IMAGE"', returnStdout: true).trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Deploy isolated gray service') {
|
||||
steps {
|
||||
lock(resource: 'baiyue-logistics-chat-gray-release') {
|
||||
withEnv([
|
||||
"PUBLIC_ORIGIN=${params.PUBLIC_ORIGIN}", "HOST_PORT=${params.HOST_PORT}",
|
||||
"GRAY_DEPLOY_DIR=${params.GRAY_DEPLOY_DIR}", "GRAY_PROXY_CONF_DIR=${params.GRAY_PROXY_CONF_DIR}",
|
||||
"GRAY_TLS_CERT_FILE=${params.GRAY_TLS_CERT_FILE}", "GRAY_TLS_KEY_FILE=${params.GRAY_TLS_KEY_FILE}",
|
||||
"ASR_PROVIDER=${params.ASR_PROVIDER ?: ''}"
|
||||
]) {
|
||||
withCredentials([
|
||||
sshUserPrivateKey(credentialsId: params.SSH_CREDENTIAL_ID, keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'),
|
||||
string(credentialsId: params.SSH_HOST_CREDENTIAL_ID, variable: 'TARGET_SSH_HOST'),
|
||||
file(credentialsId: params.SSH_KNOWN_HOSTS_CREDENTIAL_ID, variable: 'TARGET_SSH_KNOWN_HOSTS'),
|
||||
string(credentialsId: params.DEEPSEEK_CREDENTIAL_ID, variable: 'DEEPSEEK_API_KEY'),
|
||||
string(credentialsId: params.BAIDU_ASR_API_KEY_CREDENTIAL_ID, variable: 'BAIDU_ASR_API_KEY'),
|
||||
string(credentialsId: params.BAIDU_ASR_SECRET_KEY_CREDENTIAL_ID, variable: 'BAIDU_ASR_SECRET_KEY'),
|
||||
usernamePassword(credentialsId: params.PREVIEW_AUTH_CREDENTIAL_ID, usernameVariable: 'PREVIEW_USERNAME', passwordVariable: 'PREVIEW_PASSWORD')
|
||||
]) {
|
||||
sh 'bash deploy/publish-gray.sh'
|
||||
script {
|
||||
if (params.IMPORT_QUOTE_DATA) {
|
||||
withCredentials([
|
||||
file(credentialsId: params.QUOTE_SNAPSHOT_CREDENTIAL_ID, variable: 'QUOTE_SNAPSHOT_FILE')
|
||||
]) {
|
||||
sh 'bash deploy/import-gray-quotes.sh'
|
||||
}
|
||||
}
|
||||
if (params.IMPORT_ORDER_SAMPLES) {
|
||||
withCredentials([
|
||||
file(credentialsId: params.ORDER_SNAPSHOT_CREDENTIAL_ID, variable: 'ORDER_SNAPSHOT_FILE'),
|
||||
file(credentialsId: params.TRACKING_SNAPSHOT_CREDENTIAL_ID, variable: 'TRACKING_SNAPSHOT_FILE')
|
||||
]) {
|
||||
sh 'bash deploy/import-gray-order-samples.sh'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# 柏悦智能物流客服系统
|
||||
|
||||
基于 Flask + DeepSeek 的中欧/英国跨境物流智能客服,支持多轮对话、运费试算、运单查询、历史会话管理。
|
||||
基于 Flask + DeepSeek 的跨境物流智能客服,支持美国通用报价、中欧/英国运费试算、多轮对话、运单查询、历史会话管理。
|
||||
|
||||
## 功能
|
||||
|
||||
@@ -8,28 +8,45 @@
|
||||
- **知识库优先**:优先使用本地知识库回答,减少模型编造
|
||||
- **追问兜底**:当前问题没命中关键词时,用上一句提问去检索
|
||||
- **运费试算**:识别重量/尺寸/渠道,按报价表阶梯单价计算并展示完整明细
|
||||
- **运单号查询**:发送 8~20 位运单号,返回时间轴轨迹卡片
|
||||
- **订单查询**:直接输入入仓码查询订单与已有轨迹,卡片主显示入仓码;兼容订单号与 Shipment ID,展示概要、申报重量/体积和业务状态历史,不生成模拟运输轨迹
|
||||
- **历史会话**:会话保存到 SQLite,支持打开、搜索、删除
|
||||
- **交互**:停止生成、复制(纯文本)、重答、多行输入、回到底部
|
||||
- **中英文切换**:右上角「中/EN」按钮或快捷键 `Ctrl + L`
|
||||
- **异常处理**:接口超时、Key 失效、中断时给出明确提示与重试
|
||||
- **会话恢复**:连接中断保留已收到的正文;切换话题取消旧附件,等待建会话时保留新草稿;历史加载失败保留已有列表
|
||||
- **深色模式**:右上角切换,偏好本地保存
|
||||
- **响应式**:窄屏下侧栏自动变为抽屉
|
||||
- **附件预览**:发送前查看文件名或缩略图,可移除待发送附件
|
||||
- **客服工作台**:默认展示会话列表与全高聊天区,统计收在「数据概览」,服务资料按需展开;支持会话搜索、多行回复和切换会话保留草稿,常用回复先填入再发送
|
||||
- **手机客服接待**:会话列表与聊天整屏切换,返回列表保留草稿;回复框固定在聊天底部,可从列表或聊天打开服务资料
|
||||
|
||||
## 报价数据
|
||||
|
||||
运费试算使用 **炜易达 VIP 报价表(2026-10-15 9:00 执行版)** 中的真实数据,覆盖 8 条渠道:
|
||||
美国通用报价通过 `scripts/import_quote_data.py` 将本地 Excel 明细导出为私有快照,再导入运行 SQLite;不读取「快速查询」的外部工作簿,不按文件日期或旧船期停用。原始文件、价格快照及运行数据库均不进入 Git 或镜像。
|
||||
|
||||
| 渠道 | 21KG+ | 101KG+ | 500KG+ | 2000KG+ | 参考时效 |
|
||||
|---|---|---|---|---|---|
|
||||
| 欧洲海运快线 | 12.3 | 10.3 | 10.2 | 10.0 | 开船后 38-45 天 |
|
||||
| 义乌中欧铁路 | 15.5 | 13.5 | — | 13.5(1000+) | 发车后 36-40 天 |
|
||||
| 中欧卡航 | 19.4 | 17.4 | 17.4 | 17.3 | 发车后 16-20 天 |
|
||||
| 欧洲空运 | 39 | 36 | — | 37(71+) | 10-13 天 |
|
||||
| 英国海运 | 12.8 | 10.9 | — | — | 约 40 天 |
|
||||
| 英国铁路 | 18.0 | 16.2 | — | — | 25-30 天 |
|
||||
| 中英卡航 | 21.4 | 19.4 | — | — | 20-22 天 |
|
||||
| 英国空运 | 48(22+) | 42 | — | 44(51+) | 8-10 天 |
|
||||
`quote_books` 保存版本,`quote_rates` 保存线路/交货仓/目的仓或分区/税费方式/重量档位/计费单位,`quote_warehouses` 保留仓码的多种分区,`quote_postcodes` 保存带前导零的邮编及偏远类别,`quote_documents` 保存当前资料中的业务说明。每条价格保留源工作表和单元格。指定 `--activate` 才原子切换美国报价版本,导入不修改订单和客户范围。
|
||||
|
||||
```powershell
|
||||
python scripts/import_quote_data.py --xlsx <本地报价.xlsx> --output <新私有快照.json>
|
||||
python scripts/import_quote_data.py --snapshot <私有快照.json> --db <运行数据库.db> --activate
|
||||
```
|
||||
|
||||
美国报价先由本地规则计算并通过既有 SSE 返回,不等待模型调用。仅给「美国30KG」可先看到不同海派、交货仓和美西/美中/美东的基础价格;提供仓码、邮编、箱数和尺寸后在当前会话继续核算。同一仓码有多种分区时并列展示;更换目的仓或邮编后不重用旧目的地。体积、附加费和承运限制尚不明确时继续补充条件,不编造缺失费率。现有欧洲/英国报价使用下述原有来源。
|
||||
|
||||
代码标注的报价来源为 **炜易达 VIP 报价表(2026-10-15 9:00 执行版)**,覆盖 8 条渠道。以下逐渠道列出代码中的重量档位;按计费重量选择不大于该重量的最高档位:
|
||||
|
||||
报价试算需先确认目的国家或地区;未识别到目的地时先补充信息。英国报价及其连续追问使用英国费率,“海运呢”“空运呢”等短句和重试保留原有条件。美国使用已激活的本地价表;未导入美国价表或其他未覆盖目的地时补充条件或由人工确认。英国按方报价不套用欧洲仓价。没有匹配的国家或仓点时不自动回退到其他仓点。
|
||||
|
||||
| 渠道 | 重量档位 → 基础单价(元/kg) | 参考时效 |
|
||||
|---|---|---|
|
||||
| 欧洲海运快线 | 21KG+ → 12.3;101KG+ → 10.3;500KG+ → 10.2;2000KG+ → 10.0 | 开船后 38-45 天 |
|
||||
| 义乌中欧铁路 | 21KG+ → 15.5;100KG+ → 13.5;1000KG+ → 13.5 | 发车后 36-40 天 |
|
||||
| 中欧卡航 | 21KG+ → 19.4;101KG+ → 17.4;500KG+ → 17.4;2000KG+ → 17.3;4000KG+ → 17.3 | 发车后 16-20 天 |
|
||||
| 欧洲空运 | 21KG+ → 39;45KG+ → 38;71KG+ → 37;101KG+ → 36 | 10-13 天 |
|
||||
| 英国海运 | 21KG+ → 12.8;101KG+ → 10.9;301KG+ → 10.9 | 约 40 天 |
|
||||
| 英国铁路 | 21KG+ → 18.0;101KG+ → 16.2;301KG+ → 16.2 | 25-30 天 |
|
||||
| 中英卡航 | 21KG+ → 21.4;101KG+ → 19.4;301KG+ → 19.4 | 20-22 天 |
|
||||
| 英国空运 | 22KG+ → 48;51KG+ → 44;101KG+ → 42 | 8-10 天 |
|
||||
|
||||
**计费规则**(均来自报价表):
|
||||
|
||||
@@ -39,9 +56,11 @@
|
||||
- 铁路、卡航单件计费重不足 13KG 加收超轻费 5 元/kg;空运单件不足 12KG 按 12KG 计费
|
||||
- 偏远地址 +7 元/kg,单票最低 250 元
|
||||
|
||||
数据定义在 `am.py` 的 `RATES` 字典中,修改价格只需改这里,不需要动计算逻辑。
|
||||
基础报价维护在 `logistics_chat/pricing.py` 的 `RATES` 字典中;修改价格时同步知识资料,避免调整计算逻辑。
|
||||
|
||||
### 扩展数据(rates_extra.py)
|
||||
`calc_freight()` 的 `total` 当前仅为基础运费。超轻费、偏远费及产品附加费以说明或单独结果展示,尚未统一计入 `total`;上述业务规则不能理解为已全部自动结算。
|
||||
|
||||
### 扩展数据(logistics_chat/rates_extra.py)
|
||||
|
||||
从同一份报价表提取、目前已支持:
|
||||
|
||||
@@ -59,162 +78,216 @@
|
||||
|
||||
> ⚠️ 报价表含商业价格与联系人信息,公开发布前请脱敏或替换为示例数据。
|
||||
|
||||
## 运行环境
|
||||
## 运行环境与启动
|
||||
|
||||
- Python 3.9 及以上
|
||||
- Windows / macOS / Linux
|
||||
项目使用 Python、Flask、SQLite 和 DeepSeek API,无需前端构建。建议使用独立虚拟环境;所有应用启动命令均在项目根目录执行。
|
||||
|
||||
## 快速启动(Windows)
|
||||
|
||||
双击 `start.bat` 即可,脚本会自动检查端口占用、API Key 和依赖。
|
||||
|
||||
## 安装与启动
|
||||
|
||||
### 1. 安装依赖
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### 2. 配置 API Key
|
||||
|
||||
Key 不写进代码,通过系统环境变量提供。
|
||||
|
||||
Windows PowerShell:
|
||||
### Windows
|
||||
|
||||
```powershell
|
||||
setx DEEPSEEK_API_KEY "sk-你的key"
|
||||
py -3 -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
|
||||
Copy-Item .env.example .env # 仅首次运行;已有 .env 时跳过
|
||||
# 编辑 .env,填写 DEEPSEEK_API_KEY 后再启动
|
||||
.\.venv\Scripts\python.exe am.py
|
||||
```
|
||||
|
||||
设置后需要**重新打开终端**才生效,可用下面的命令确认:
|
||||
上述命令固定使用项目 `.venv`,不受其他已激活环境影响。可选的一键入口 `start.bat` 按已激活的 `VIRTUAL_ENV`、项目 `.venv`、`py -3`、PATH 中的 `python` 顺序逐个验证 Python 3。使用它之前先退出不需要的旧环境,或检查诊断结果是否指向预期解释器。`启动.bat` 调用同一入口:
|
||||
|
||||
```powershell
|
||||
echo $env:DEEPSEEK_API_KEY
|
||||
.\start.bat
|
||||
```
|
||||
|
||||
Linux / macOS:
|
||||
仅检查并打印选中的解释器,不安装依赖或启动服务:
|
||||
|
||||
```powershell
|
||||
.\start.bat --check-python
|
||||
```
|
||||
|
||||
浏览器访问 http://127.0.0.1:5000;客服登录页为 http://127.0.0.1:5000/admin。
|
||||
|
||||
### Linux / macOS
|
||||
|
||||
```bash
|
||||
export DEEPSEEK_API_KEY="sk-你的key"
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements.txt
|
||||
cp .env.example .env # 仅首次运行;已有 .env 时跳过
|
||||
# 编辑 .env,填写 DEEPSEEK_API_KEY 后再启动
|
||||
.venv/bin/python am.py
|
||||
```
|
||||
|
||||
Key 申请地址:https://platform.deepseek.com/api_keys
|
||||
### 配置说明
|
||||
|
||||
也可以参考项目根目录的 **.env.example**(不含真实 Key 的配置示例文件),其中列出了需要设置的环境变量及说明。
|
||||
手机语音输入:点击输入区上方的麦克风按钮,再按住说话,松开后转文字并发送;上滑或取消触摸不发送,最长 60 秒。微信和手机浏览器使用同一服务端转写链路;页面必须通过 HTTPS 或本机 localhost 打开,并允许麦克风。旧版内置浏览器不支持录音时仍可文字输入。手机订单信息默认折叠,物流轨迹优先展示。
|
||||
|
||||
### 3. 启动服务
|
||||
在根目录 `.env` 配置 `ASR_PROVIDER=baidu`、`BAIDU_ASR_API_KEY` 和 `BAIDU_ASR_SECRET_KEY`,使用已开通短语音识别的百度语音应用凭据,不能混用 OCR 或 DeepSeek 凭据。服务端须安装 FFmpeg 并加入 PATH,也可用 `FFMPEG_BIN` 指定可执行文件绝对路径;Docker 应用镜像已包含 FFmpeg。浏览器 WebM/MP4 录音通过内存管道转为 16 kHz 单声道 PCM,录音不写入上传目录或历史,只发送识别文字。修改后重启服务。可选的 `ASR_PROVIDER=dashscope` 使用 `.env.example` 中独立的 ASR 配置。
|
||||
|
||||
```bash
|
||||
cd E:\wuliu_chat
|
||||
python am.py
|
||||
```
|
||||
- 本地密钥放在项目根目录的 `.env` 中:首次运行复制 [`.env.example`](.env.example),填写 `DEEPSEEK_API_KEY=你的密钥`。`.env` 已被 Git 忽略,示例文件中的值应保持为空。
|
||||
- 应用启动时自动读取根目录 `.env`,不依赖终端的当前目录;`am.py`、Windows 启动脚本和 WSGI 应用工厂均使用同一配置入口。修改密钥后须重启服务。
|
||||
- 配置优先级为:显式传给 `create_app` 的配置 > 进程环境变量 > `.env` > 空值。环境变量即使为空也会覆盖 `.env`;本地填写后仍提示未配置时,请检查并移除旧的空环境变量。
|
||||
- 部署环境仍可注入 `DEEPSEEK_API_KEY`。PowerShell 的 `$env:DEEPSEEK_API_KEY` 只影响当前终端及其子进程,双击启动脚本可直接使用 `.env`,无需配置系统环境变量。
|
||||
- 密钥申请或更换可在 [DeepSeek 平台](https://platform.deepseek.com/api_keys) 完成;不要把密钥写入脚本、提交到 Git,或打印到日志。
|
||||
- 当前服务监听 `0.0.0.0:5000`,局域网设备可能访问。仅供本机开发时,将 `logistics_chat/config.py` 中默认的 `HOST` 设置为 `"127.0.0.1"`。
|
||||
- 历史启动脚本曾提交明文密钥。当前文件已移除该配置,但 Git 历史仍保留旧内容,应在平台作废旧密钥,并在 `.env` 或部署环境中配置新密钥。
|
||||
|
||||
### 4. 打开页面
|
||||
### Jenkins 灰度部署
|
||||
|
||||
浏览器访问 http://127.0.0.1:5000
|
||||
|
||||
## 测试
|
||||
|
||||
### 单元测试
|
||||
|
||||
```bash
|
||||
pytest -v
|
||||
```
|
||||
|
||||
共 **52 个用例**,覆盖运费意图解析、运单号识别、阶梯价计算、卡派按方、附加费识别、岛屿邮编、卡片转换等。
|
||||
测试在临时目录中运行,不会改动 `history.db`。
|
||||
|
||||
### 回答长度控制
|
||||
|
||||
- 中文回答:120~350 字;英文回答:120~700 字
|
||||
- 超过上限时由代码自动压缩一次(保留全部数字),仍超标再压一次
|
||||
- 提示词之外的第二道保险,确保字数可控
|
||||
|
||||
### 场景测试
|
||||
|
||||
`测试记录.md` 记录了 **29 个业务场景**的输入、预期结果、首次结果、修复动作与复测结果,
|
||||
其中 26 项通过或已修复,3 项列为未解决/待验证(超长输入、并发提问、无答案兜底)。
|
||||
现有灰度环境按 [Jenkins 部署指南](docs/deployment.md) 发布:构建和测试镜像,SSH 发送至专用 Compose 服务,Nginx 提供 HTTPS。客户聊天入口免登录,只有明确列出的客户 API 开放;客服后台、搜索、导出和其他未知路径继续使用访问密码。密钥由 Jenkins 注入,数据和证书保存在独立宿主机目录;启动失败时恢复之前的应用和站点。上游端口必须仅绑定回环地址。另附 [Linux 单机参考](docs/deployment-linux.md)。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
wuliu_chat/
|
||||
├── am.py 主程序(路由、知识库、对话逻辑、运单查询、运费试算)
|
||||
├── rates_extra.py 报价表扩展数据(卡派按方、附加费、岛屿邮编)
|
||||
├── test_am.py 单元测试(52 个用例)
|
||||
├── start.bat Windows 一键启动脚本
|
||||
├── requirements.txt 依赖清单
|
||||
├── README.md 说明文档
|
||||
├── knowledge.md 知识资料(由 knowledge_list 导出)
|
||||
├── 测试记录.md 场景测试记录(29 个场景)
|
||||
├── .gitignore Git 忽略规则
|
||||
├── .env.example 配置示例(不含 Key)
|
||||
├── history.db SQLite 数据库(会话与消息)
|
||||
├── static/ 静态资源
|
||||
│ └── fa.jpg 网站图标
|
||||
├── templates/
|
||||
│ └── index.html 前端页面
|
||||
└── .vscode/
|
||||
└── launch.json VS Code 调试配置
|
||||
```text
|
||||
baiyue-logistics-chat/
|
||||
├── am.py CLI/WSGI 兼容入口
|
||||
├── Jenkinsfile 灰度构建、测试及受管发布
|
||||
├── Dockerfile 应用、测试及证书运维镜像
|
||||
├── .dockerignore 显式限制构建上下文
|
||||
├── rates_extra.py 扩展数据旧导入路径的兼容转发
|
||||
├── logistics_chat/
|
||||
│ ├── __init__.py create_app 应用工厂
|
||||
│ ├── config.py .env、环境变量与绝对路径配置
|
||||
│ ├── db.py SQLite、历史持久化、备份
|
||||
│ ├── knowledge.py 知识与关键词检索
|
||||
│ ├── pricing.py 运费解析与计算
|
||||
│ ├── rates_extra.py 扩展报价唯一数据源
|
||||
│ ├── tracking.py 卡片协议与旧演示函数兼容
|
||||
│ ├── order_data.py 本地订单测试表、精确查询与快照导入
|
||||
│ ├── ai_client.py 模型 HTTP、压缩和追问
|
||||
│ ├── chat_service.py 问答与 SSE 编排
|
||||
│ ├── history_service.py 会话 CRUD
|
||||
│ ├── human_service.py 人工会话
|
||||
│ ├── business_service.py 登录、统计、订单、留言、导出
|
||||
│ ├── file_service.py 附件与清理
|
||||
│ ├── hooks.py 限流和缓存头
|
||||
│ ├── runtime.py 服务启动
|
||||
│ └── routes/ HTTP Blueprints
|
||||
├── templates/ 客户、登录、客服工作台 HTML
|
||||
├── static/
|
||||
│ ├── css/ theme.css 共享主题 + chat/admin/admin_login 页面样式
|
||||
│ ├── js/ 对应经典页面脚本
|
||||
│ └── fa.jpg
|
||||
├── scripts/ 人工会话检查/关闭 CLI
|
||||
├── deploy/ 灰度 Compose、发布/回退、证书及单机参考
|
||||
├── tests/ 规则、存储、HTTP/SSE、启动与维护回归
|
||||
├── docs/ architecture.md、knowledge.md
|
||||
├── examples/requests/ 人工接口示例
|
||||
├── uploads/.gitkeep 本地附件不纳入版本控制
|
||||
├── start.bat 可选 Windows 启动检查
|
||||
├── 启动.bat 兼容入口,调用 start.bat
|
||||
├── requirements.txt
|
||||
├── .env.example
|
||||
├── .gitignore
|
||||
├── AGENTS.md
|
||||
└── README.md
|
||||
```
|
||||
|
||||
> `kefu.py`、`SQLite.py` 为早期遗留文件,不影响运行,可安全删除。
|
||||
运行后还会生成 `history.db`、`logs/` 和 `backups/`,这些运行数据以及虚拟环境均由 Git 忽略。已经上传的本地文件在本次目录整理中保留。
|
||||
|
||||
## 测试
|
||||
|
||||
先安装项目依赖,再使用同一个项目虚拟环境运行:
|
||||
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe -m pytest -v
|
||||
```
|
||||
|
||||
也可执行 `.\.venv\Scripts\python.exe -m unittest discover -s tests -v`。Linux/macOS 将解释器替换为 `.venv/bin/python`。纯规则和维护 CLI 本身仅依赖标准库,整套业务测试还需要 Flask 等项目依赖。
|
||||
|
||||
安装 Node.js 后,Python 测试还会运行 `tests/frontend/admin.test.cjs`,验证发送失败保留草稿、重复点击、切换会话、输入法及手机抽屉;也可单独执行 `node --test tests/frontend/admin.test.cjs`,无需安装 npm 依赖。未安装 Node.js 时该项明确跳过。
|
||||
|
||||
覆盖范围包括配置文件加载与优先级、运费边界与单位换算、知识检索、运单识别、旧 SQLite schema 迁移、事务回滚、附件、人工状态、历史、CSV、SSE 压缩/追问/异常/取消,以及 Windows 解释器选择。Windows 启动测试在其他系统上跳过,三个页面的外置资源也由接口测试检查。
|
||||
|
||||
模型请求使用模拟响应,数据库和附件使用临时目录;这不代表完成真实 DeepSeek 或真实物流接口联调。旧文档提及的原始 52 个业务测试和 29 个场景记录未随仓库提供,当前结果以实际测试输出为准。
|
||||
|
||||
## 维护与调试
|
||||
|
||||
在根目录执行:
|
||||
|
||||
```powershell
|
||||
py -3 scripts/inspect_human_sessions.py
|
||||
py -3 scripts/close_active_sessions.py
|
||||
```
|
||||
|
||||
两个脚本默认定位到仓库根目录的 `history.db`,不依赖调用时的工作目录,也可用 `--db "D:\data\history.db"` 指定已有数据库。检查脚本只读;关闭脚本将**所有 active 人工会话**标记为 closed,保留 waiting 会话和聊天消息。数据库不存在时会报错退出,不会误建空库。
|
||||
|
||||
人工客服接口请求示例见 [examples/requests/README.md](examples/requests/README.md)。知识资料见 [docs/knowledge.md](docs/knowledge.md),实际知识内容维护在 `logistics_chat/knowledge.py` 的 `knowledge_list` 中。
|
||||
|
||||
模块定位、文件归属和后续拆分规范见 [docs/architecture.md](docs/architecture.md)。该文档与当前已拆分的目录保持同步。
|
||||
|
||||
## 主要接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/` | 聊天页面 |
|
||||
| GET | `/stream_chat?msg=&conv_id=` | 流式对话(SSE) |
|
||||
| POST | `/api/new_chat` | 新建会话,返回 `{"id": 会话id}` |
|
||||
| GET | `/` | 客户聊天页面 |
|
||||
| GET / POST | `/stream_chat` | SSE 流式对话;POST JSON 接收 `msg`、`conv_id` |
|
||||
| POST | `/api/new_chat` | 新建会话并保存欢迎语,返回 `id`、`welcome` |
|
||||
| GET | `/api/get_history` | 会话列表 |
|
||||
| GET | `/api/get_messages?conv_id=` | 单个会话的全部消息 |
|
||||
| DELETE | `/api/del_history?id=` | 删除会话(级联删消息) |
|
||||
| DELETE | `/api/clear_all` | 清空全部历史 |
|
||||
| GET | `/api/get_messages?conv_id=` | 单个会话的消息 |
|
||||
| DELETE | `/api/del_history?id=` | 删除单个会话和消息 |
|
||||
| DELETE | `/api/clear_all` | 清空聊天历史 |
|
||||
| POST | `/api/upload` | 上传图片、PDF、TXT、CSV,最大 10MB |
|
||||
| POST | `/api/human/request` | 申请人工客服 |
|
||||
| POST | `/api/human/accept` | 客服接待 |
|
||||
| POST | `/api/human/send` | 发送人工消息 |
|
||||
| GET | `/api/human/poll` | 轮询人工消息 |
|
||||
| POST | `/api/human/close` | 关闭人工会话 |
|
||||
| POST | `/api/human/transfer` | 将接待中的会话转回排队列表 |
|
||||
| POST | `/api/human/note` | 保存会话备注 |
|
||||
| POST | `/api/human/recall` | 按 `mid` 撤回客服消息 |
|
||||
| POST | `/api/rate` | 提交人工服务评价(`sid`、1–5 的 `stars`、`comment`) |
|
||||
| GET | `/api/agents/list` | 客服列表,不包含密码 |
|
||||
| GET | `/api/search_chat?q=` | 搜索历史消息,最多返回 50 条 |
|
||||
| GET | `/admin` | 客服登录页面 |
|
||||
| POST | `/admin/login` | 校验客服账号密码 |
|
||||
| GET | `/admin/dashboard` | 客服工作台 |
|
||||
| GET | `/api/export_chat` | 导出 Excel;`?format=csv` 保留 CSV 导出 |
|
||||
|
||||
### 流式事件格式
|
||||
人工客服每天 8:00–22:00 接受新申请,由服务端校验时间;其余时间可提交离线留言。客服工作台保留白色界面,转接后由其他客服在排队列表主动接入。页面的铃铛按钮可开启浏览器通知,页面切到后台时提示排队或新消息;实际通知能力取决于浏览器权限。
|
||||
|
||||
`/stream_chat` 返回 Server-Sent Events,每帧是一条 JSON:
|
||||
SSE 每帧为一条 JSON,主要事件包括:
|
||||
|
||||
```
|
||||
data: {"t": "正文片段"} 正常回答片段
|
||||
data: {"e": "错误提示"} 出错时
|
||||
data: {"card": {...}} 运单轨迹卡片
|
||||
data: {"d": 1} 正常结束
|
||||
```text
|
||||
data: {"t": "正文片段"}
|
||||
data: {"e": "错误提示"}
|
||||
data: {"card": {...}}
|
||||
data: {"replace": "精简后的全文"}
|
||||
data: {"suggest": ["相关追问"]}
|
||||
data: {"d": 1}
|
||||
```
|
||||
|
||||
## 数据库
|
||||
## 数据库与运行数据
|
||||
|
||||
SQLite,文件为 `history.db`,首次启动自动创建。
|
||||
订单数据保存在聊天服务运行时 SQLite 的 `order_test_data` 表中,与灰度业务库独立,可直接通过 SQLite 工具新增或修改;不会自动同步源库,没有管理页面和对外增删改接口。游客咨询无需登录,查询订单时引导客户登录;查询按服务端账号关联的客户范围过滤。`ORDER_DATA_TENANT_ID` 是额外限制,不能代替客户身份。
|
||||
|
||||
- `chat_history`:会话(id、title、ctime、utime)
|
||||
- `messages`:消息(id、conv_id、role、content、ctime)
|
||||
默认前台客户账号为 `admin / 123456`,与受 Nginx 保护的客服后台独立。默认按当前本地数据建立客户范围关联:单客户写入 `customer_users.tenant_id`,多客户写入 `customer_tenant_grants`,查询始终按服务端白名单过滤。首次关联完成后不自动加入新客户范围,同一客户下新增订单可直接查询。`CUSTOMER_DEMO_TENANT_ID` 可指定单个范围;`CUSTOMER_DEMO_LOCAL_ORDERS=false` 关闭多客户自动关联。账号保存在 `customer_users`,密码为 PBKDF2 哈希;已有账号启动时不覆盖,可直接维护哈希、`tenant_id`、`enabled` 及客户范围关联表。`CUSTOMER_DEMO_ENABLED=false` 禁用默认账号及其已有登录;真实客户账号不受该开关影响。`CUSTOMER_DEMO_USERNAME` 与 `CUSTOMER_DEMO_PASSWORD_HASH` 用于首次创建默认账号。
|
||||
|
||||
运单卡片以 `__CARD__{json}` 形式保存在 `messages.content`,前端识别后重新渲染。
|
||||
登录凭据通过独立 HttpOnly Cookie 及服务端 `customer_sessions` 校验,绑定当前访客,8 小时有效;退出后撤销当前登录。登录后自动继续刚才的订单问题;含订单事实的会话在退出后隐藏,只有相同访客重新登录同一客户和范围后才能恢复。真实用户认证接入时替换账号校验/关联层,继续使用内部客户 ID、可信客户范围和已有登录会话契约;MCP 数据查询仍通过 `lookup_order` 的客户范围过滤。
|
||||
|
||||
## 常见问题
|
||||
游客首次访问由浏览器生成 256 位随机 key,保存在当前站点的 localStorage;服务端只保存其哈希作为会话归属,以 HttpOnly、SameSite Cookie 校验请求。刷新或同浏览器再次打开可恢复自己的历史,其他浏览器拥有独立记录;清除站点数据后无法自动找回。存储被禁用时使用 Cookie 维持访客会话。旧版未记录归属的历史不自动分配给首位访客,继续保留给受保护的客服后台。访客只能访问、删除自己的聊天、人工会话和附件,不能凭会话编号或访客 key 查询真实订单。
|
||||
|
||||
**页面报"服务未配置 API Key"**
|
||||
环境变量没读到。确认变量名是 `DEEPSEEK_API_KEY`,并**重新打开终端**后再启动。
|
||||
未发送的文字草稿按游客和会话分别保存在当前浏览器的 localStorage,当前标签页通过 sessionStorage 记录上次打开的会话;切换会话和刷新可恢复对应草稿,发送或删除会话后清理。草稿不跨设备同步,不恢复未发送的附件。浏览器禁止存储或空间不足时只在当前页面暂存,并提示刷新前保留文字;清除站点数据会同时删除草稿。历史加载失败期间禁止发送,重新选择会话或新建对话后再继续。
|
||||
|
||||
**页面报"API Key 无效或已过期"**
|
||||
Key 已作废,去平台重新生成一把,再用 `setx` 覆盖。
|
||||
快照 JSON 放仓库外的私有 artifacts 目录,使用明确路径导入:
|
||||
|
||||
**端口 5000 被占用**
|
||||
```powershell
|
||||
netstat -ano | findstr ":5000 "
|
||||
taskkill /PID <进程号> /F
|
||||
.\.venv\Scripts\python.exe scripts/import_order_test_data.py --snapshot "D:\private\orders.snapshot.json" --db "D:\data\history.db"
|
||||
```
|
||||
确认只有一行 `LISTENING`,避免两个进程同时抢端口。
|
||||
|
||||
**改了 am.py 没生效**
|
||||
Flask 启动时加载代码,改后端必须重启服务;只改 `index.html` 则刷新页面即可。
|
||||
脚本默认保留已有记录,避免覆盖手工调整;确需覆盖时显式加 `--replace`。`order_no` 与 `tenant_id` 组成唯一键;`gross_weight_kg`、`volume_cbm`、`package_count` 是申报汇总,`history_json` 是形如 `[{"time":"2026-10-29 10:00","status":"SUBMITTED"}]` 的业务状态列表。子订单未提供独立货物数据时保持空值。快照、运行数据库和凭据不提交 Git。后续 MCP 接口开放后替换 `order_data.lookup_order`、`count_orders` 的取数实现即可保留聊天契约。
|
||||
|
||||
## 说明
|
||||
登录后可以直接问“我有多少个运单”“我的订单数量”“已完成的订单有多少”。统计每次按当前账号的授权范围查表,返回订单票数和其中已登记入仓码的票数;不要求先提供入仓码,也不沿用上一票订单作为统计范围。支持订单总量和明确的业务状态;其他筛选条件不冒充总量返回,头程订单完成不等于签收。统计会话与订单卡片一样绑定客户和范围,退出后隐藏,重新登录同一身份及范围后恢复。
|
||||
|
||||
- 运单轨迹当前为**模拟数据**(按单号固定生成),接真实接口只需修改 `am.py` 中的 `build_track()`。
|
||||
- 服务使用 Waitress 多线程启动(8 个线程),适合内网小范围使用;面向公网仍需反向代理与 HTTPS。
|
||||
- 默认只监听 `127.0.0.1`,如需局域网访问,把 `am.py` 中的 `HOST` 改为 `"0.0.0.0"`。
|
||||
- 运费计费方式为**阶梯单价 × 计费重量**,价格与时效来自炜易达报价表。报价更新时只需修改 `RATES`;知识库文案在 `knowledge_list` 中,两者建议同步更新。
|
||||
- 材积按 ÷6000 计算(1CBM = 167KG),与部分渠道 ÷5000 的口径不同,修改时注意核对报价表。
|
||||
点击“查入仓码”会打开查询框,填写号码后查询;游客先登录。回复及历史卡片中的入仓码也可点击,自动带入号码,可复制或查询最新轨迹。查询结果接在当前聊天中,草稿和待发送附件保留,人工接待中需要先返回 AI 问答。
|
||||
|
||||
首次启动创建聊天、访客附件、客户登录、人工接待、反馈及订单所需表,并兼容已有数据。默认前台客户账号按上述配置初始化,客服账号和订单数据由管理员配置。本地入口使用根目录 `history.db`,Linux 部署工厂另存至专用数据目录。会话备注保存在 `human_sessions.note`;消息撤回事件通过 `human_messages.recalled_id` 指向原消息,轮询客户端按编号更新。订单卡片以 `__CARD__{json}` 形式保存,前端据此恢复展示。
|
||||
|
||||
普通导入 `am.py` 或 `logistics_chat` 不创建运行数据。显式调用 `create_app()` 或访问 WSGI 兼容入口 `am.app` 时,默认初始化 SQLite、创建正常运行日志、备份数据库,并清理未被聊天记录引用且修改时间超过 7 天的临时上传文件。已发送附件随 AI/人工聊天记录保留;已被删除的旧文件无法恢复,页面会显示附件无法访问的提示。测试须事先配置临时数据库、附件、日志和备份目录;`INITIALIZE_RUNTIME=False` 可禁止自动初始化,此时调用方负责准备 schema。历史会话的自动清理仍已关闭。
|
||||
|
||||
## 当前限制
|
||||
|
||||
- 订单查询使用可编辑测试副本,尚未接入实时承运商物流轨迹或 MCP;旧历史卡片继续兼容展示。
|
||||
- 不预置客服账号;应用内客服登录仍沿用旧账号校验逻辑。客服工作台及接口仍须通过 Nginx 的专用访问密码保护,客户聊天不要求此密码。
|
||||
- 后台登录尚未建立完整会话鉴权,管理页面和接口缺少登录校验。
|
||||
- 运费数字由 Python 计算后交给模型组织说明;附加费是否适用仍需结合具体货物和地址核对。
|
||||
- 回答提示词目标为 120–350 字;代码压缩阈值为中文 800、英文 1400 字符,超过阈值最多尝试压缩两次。
|
||||
- 服务优先使用 Waitress 的 8 个线程;缺少 Waitress 时会回退到 Flask 开发服务器。公网部署前还需完善鉴权及部署配置。
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS agents (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE,
|
||||
password TEXT,
|
||||
name TEXT
|
||||
)''')
|
||||
c.execute("INSERT OR IGNORE INTO agents(username,password,name) VALUES('admin','123','管理员')")
|
||||
c.execute("INSERT OR IGNORE INTO agents(username,password,name) VALUES('agent1','123','客服小王')")
|
||||
c.execute("INSERT OR IGNORE INTO agents(username,password,name) VALUES('agent2','123','客服小李')")
|
||||
c.commit()
|
||||
print("ok")
|
||||
@@ -1,11 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
phone TEXT,
|
||||
track_no TEXT,
|
||||
status TEXT DEFAULT "运输中",
|
||||
created TEXT
|
||||
)''')
|
||||
c.commit()
|
||||
print("ok")
|
||||
@@ -1,7 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
c.execute("INSERT INTO orders(phone, track_no, status, created) VALUES('13800138000','YT20261028001','运输中','2026-10-28')")
|
||||
c.execute("INSERT INTO orders(phone, track_no, status, created) VALUES('13800138000','YT20261028002','派送中','2026-10-27')")
|
||||
c.execute("INSERT INTO orders(phone, track_no, status, created) VALUES('13900139000','YT20261028003','已签收','2026-10-26')")
|
||||
c.commit()
|
||||
print("ok")
|
||||
@@ -1,11 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
content TEXT,
|
||||
phone TEXT,
|
||||
ctime TEXT,
|
||||
status TEXT DEFAULT "pending"
|
||||
)''')
|
||||
c.commit()
|
||||
print("ok")
|
||||
@@ -1,4 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
print("messages:", [d[1] for d in c.execute("PRAGMA table_info(messages)").fetchall()])
|
||||
print("chat_history:", [d[1] for d in c.execute("PRAGMA table_info(chat_history)").fetchall()])
|
||||
@@ -1,5 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
c.execute("UPDATE human_sessions SET status='closed' WHERE status='active'")
|
||||
c.commit()
|
||||
print('ok')
|
||||
@@ -0,0 +1 @@
|
||||
"""Linux acceptance deployment entry points."""
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
root=${1:?}
|
||||
release=${2:?}
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release" == "$root"/releases/* && "$release" != *..* ]] || exit 2
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
|
||||
# Parse a small allowlist of non-secret release fields; never source a credential file.
|
||||
while IFS='=' read -r name value; do
|
||||
case "$name" in
|
||||
CHAT_IMAGE|CHAT_IMAGE_ID|CHAT_CERTBOT_IMAGE|CHAT_CERTBOT_IMAGE_ID|SOURCE_COMMIT|HOST_PORT|CHAT_ROOT|CHAT_RELEASE|CHAT_DATA_DIR|CHAT_LOG_DIR|CHAT_RUNTIME_ENV|CHAT_DOMAIN|CHAT_PROXY_DIR|CHAT_TLS_CERT|CHAT_TLS_KEY|CHAT_AUTH_DIR) ;;
|
||||
*) echo 'Unexpected release setting.' >&2; exit 2 ;;
|
||||
esac
|
||||
[[ "$value" =~ ^[A-Za-z0-9_./:-]+$ ]] || exit 2
|
||||
printf -v "$name" '%s' "$value"
|
||||
done < "$release/release.env"
|
||||
[[ "$CHAT_ROOT" == "$root" && "$CHAT_RELEASE" == "$release" ]] || exit 2
|
||||
[[ "$CHAT_DATA_DIR" == "$root/data" && "$CHAT_LOG_DIR" == "$root/logs" && "$CHAT_RUNTIME_ENV" == "$release/runtime.env" ]] || exit 2
|
||||
[[ "$SOURCE_COMMIT" =~ ^[a-f0-9]{40}$ && "$CHAT_IMAGE_ID" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 2
|
||||
[[ "$CHAT_IMAGE" =~ ^baiyue-logistics-chat-gray:[a-f0-9]{12}-b[0-9]+$ ]] || exit 2
|
||||
[[ "$HOST_PORT" =~ ^[0-9]+$ ]] && ((HOST_PORT >= 1024 && HOST_PORT <= 65535)) || exit 2
|
||||
[[ -d "$CHAT_PROXY_DIR" && -r "$CHAT_TLS_CERT" && -r "$CHAT_TLS_KEY" ]] || exit 2
|
||||
loaded_id=$(awk -F= '$1 == "CHAT_IMAGE_ID" {print $2}' "$release/loaded-image-ids.env")
|
||||
[[ "$loaded_id" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 2
|
||||
[[ "$(docker image inspect --format '{{.Id}}' "$CHAT_IMAGE")" == "$loaded_id" ]] || { echo 'Loaded application image changed.' >&2; exit 2; }
|
||||
[[ "$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$CHAT_IMAGE")" == "$SOURCE_COMMIT" ]] || exit 2
|
||||
openssl x509 -in "$CHAT_TLS_CERT" -checkhost "$CHAT_DOMAIN" -noout >/dev/null
|
||||
|
||||
container=baiyue-logistics-chat-gray
|
||||
if docker container inspect "$container" >/dev/null 2>&1; then
|
||||
[[ "$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$container")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
old_port=$(docker port "$container" 5000/tcp || true)
|
||||
else
|
||||
old_port=''
|
||||
fi
|
||||
if [[ -n "$(ss -H -ltn "sport = :$HOST_PORT")" && "$old_port" != "127.0.0.1:$HOST_PORT" ]]; then
|
||||
echo 'The requested host port belongs to another service.' >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
site="$CHAT_PROXY_DIR/baiyue-logistics-chat-gray.conf"
|
||||
[[ "$CHAT_AUTH_DIR" == /*/baiyue-logistics-chat-gray-proxy && "$CHAT_AUTH_DIR" != *..* ]] || exit 2
|
||||
auth="$CHAT_AUTH_DIR/access.htpasswd"
|
||||
if [[ -f "$site" ]] && ! head -n 1 "$site" | grep -Fq 'Managed for baiyue-logistics-chat-gray'; then
|
||||
echo 'The proxy file is not owned by this application.' >&2
|
||||
exit 2
|
||||
fi
|
||||
for candidate in "$CHAT_PROXY_DIR/"*.conf; do
|
||||
[[ -f "$candidate" && "$candidate" != "$site" ]] || continue
|
||||
if grep -Fq "$CHAT_DOMAIN" "$candidate"; then
|
||||
echo 'The requested domain is already configured by another site.' >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
# The Nginx config directory may be root-only (for example BaoTa). Keep this
|
||||
# application's password hash in a separate worker-readable owned directory.
|
||||
if [[ -e "$CHAT_AUTH_DIR" ]]; then
|
||||
[[ -f "$CHAT_AUTH_DIR/.project" && "$(cat "$CHAT_AUTH_DIR/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
fi
|
||||
install -d -m 755 "$CHAT_AUTH_DIR"
|
||||
printf 'baiyue-logistics-chat-gray\n' > "$CHAT_AUTH_DIR/.project"
|
||||
previous=''
|
||||
if [[ -f "$root/current-release" ]]; then
|
||||
previous=$(cat "$root/current-release")
|
||||
[[ "$previous" == "$root"/releases/* && "$previous" != *..* && -f "$previous/release.env" ]] || exit 2
|
||||
fi
|
||||
[[ ! -f "$site" ]] || cp -p "$site" "$release/previous-site.conf"
|
||||
[[ ! -f "$auth" ]] || cp -p "$auth" "$release/previous-site.htpasswd"
|
||||
chmod 600 "$release/runtime.env"
|
||||
|
||||
compose() { docker compose --env-file "$1/release.env" -f "$1/compose.yml" "${@:2}"; }
|
||||
activated=0
|
||||
proxy_changed=0
|
||||
rollback() {
|
||||
result=$?
|
||||
trap - ERR
|
||||
# ERR is inherited by command substitutions; only the parent may roll back.
|
||||
if ((BASH_SUBSHELL)); then exit "$result"; fi
|
||||
set +e
|
||||
if ((proxy_changed)); then
|
||||
if [[ -f "$release/previous-site.conf" ]]; then cp -p "$release/previous-site.conf" "$site"; else rm -f -- "$site"; fi
|
||||
if [[ -f "$release/previous-site.htpasswd" ]]; then cp -p "$release/previous-site.htpasswd" "$auth"; else rm -f -- "$auth"; fi
|
||||
nginx -t && nginx -s reload
|
||||
fi
|
||||
if ((activated)); then
|
||||
if [[ -n "$previous" ]]; then
|
||||
compose "$previous" up -d --wait --wait-timeout 120
|
||||
else
|
||||
compose "$release" stop chat
|
||||
compose "$release" rm -f chat
|
||||
fi
|
||||
fi
|
||||
echo 'Gray activation failed; previous application/proxy configuration was restored where available. Persistent data was retained.' >&2
|
||||
exit "$result"
|
||||
}
|
||||
trap rollback ERR
|
||||
|
||||
if [[ -f "$root/data/history.db" ]] && docker container inspect "$container" >/dev/null 2>&1; then
|
||||
docker exec "$container" python -c 'import pathlib,sqlite3,sys; p=pathlib.Path("/var/lib/baiyue-logistics-chat/backups");p.mkdir(exist_ok=True); source=sqlite3.connect("/var/lib/baiyue-logistics-chat/history.db"); target=sqlite3.connect(str(p/("pre-release-"+sys.argv[1]+".db"))); source.backup(target);target.close();source.close()' "$(basename "$release")"
|
||||
fi
|
||||
compose "$release" config --quiet
|
||||
activated=1
|
||||
compose "$release" up -d --wait --wait-timeout 120
|
||||
curl --fail --silent --show-error "http://127.0.0.1:$HOST_PORT/healthz" >/dev/null
|
||||
proxy_changed=1
|
||||
install -m 644 "$release/site.htpasswd" "$auth"
|
||||
install -m 644 "$release/site.conf" "$site"
|
||||
nginx -t
|
||||
nginx -s reload
|
||||
for check in /:200 /admin/dashboard:401 /api/export_chat:401 /api/get_history:401 /api/human/queue:401; do
|
||||
path=${check%:*}
|
||||
expected=${check##*:}
|
||||
code=''
|
||||
# A successful reload signal precedes the new workers accepting connections.
|
||||
for attempt in {1..10}; do
|
||||
if code=$(curl --silent --connect-timeout 3 --max-time 8 --resolve "$CHAT_DOMAIN:443:127.0.0.1" -o /dev/null -w '%{http_code}' "https://$CHAT_DOMAIN$path"); then
|
||||
[[ "$code" != "$expected" ]] || break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
[[ "$code" == "$expected" ]] || { echo 'Guest/staff access verification failed.' >&2; false; }
|
||||
done
|
||||
visitor_cookie=$(mktemp "$release/.visitor-smoke.XXXXXX")
|
||||
trap 'rm -f -- "$visitor_cookie"' EXIT
|
||||
code=$(curl --silent --show-error --max-time 10 --resolve "$CHAT_DOMAIN:443:127.0.0.1" \
|
||||
-c "$visitor_cookie" -o /dev/null -w '%{http_code}' -H 'Content-Type: application/json' \
|
||||
-d '{}' "https://$CHAT_DOMAIN/api/visitor/session")
|
||||
[[ "$code" == 200 ]] || { echo 'Guest session bootstrap verification failed.' >&2; false; }
|
||||
code=$(curl --silent --show-error --max-time 10 --resolve "$CHAT_DOMAIN:443:127.0.0.1" \
|
||||
-b "$visitor_cookie" -o /dev/null -w '%{http_code}' "https://$CHAT_DOMAIN/api/get_history")
|
||||
[[ "$code" == 200 ]] || { echo 'Guest history verification failed.' >&2; false; }
|
||||
rm -f -- "$visitor_cookie"
|
||||
trap - EXIT
|
||||
printf '%s\n' "$release" > "$root/.current-release.new"
|
||||
mv -f "$root/.current-release.new" "$root/current-release"
|
||||
trap - ERR
|
||||
printf 'Gray service activated at revision %s.\n' "$SOURCE_COMMIT"
|
||||
@@ -0,0 +1,28 @@
|
||||
[Unit]
|
||||
Description=Baiyue Logistics Chat acceptance service
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=baiyue
|
||||
Group=baiyue
|
||||
WorkingDirectory=/opt/baiyue-logistics-chat
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=PYTHONDONTWRITEBYTECODE=1
|
||||
ExecStart=/opt/baiyue-logistics-chat/.venv/bin/python -m waitress --listen=127.0.0.1:5000 --threads=8 --channel-timeout=300 --max-request-body-size=12582912 --url-scheme=https --trusted-proxy=127.0.0.1 --trusted-proxy-count=1 --trusted-proxy-headers=x-forwarded-for --call deploy.wsgi:create_app
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
TimeoutStopSec=90
|
||||
UMask=0077
|
||||
StateDirectory=baiyue-logistics-chat
|
||||
StateDirectoryMode=0700
|
||||
LogsDirectory=baiyue-logistics-chat
|
||||
LogsDirectoryMode=0700
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,25 @@
|
||||
name: baiyue-logistics-chat-gray
|
||||
services:
|
||||
chat:
|
||||
image: "${CHAT_IMAGE:?CHAT_IMAGE is required}"
|
||||
container_name: baiyue-logistics-chat-gray
|
||||
pull_policy: never
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:?HOST_PORT is required}:5000"
|
||||
env_file:
|
||||
- "${CHAT_RUNTIME_ENV:?CHAT_RUNTIME_ENV is required}"
|
||||
volumes:
|
||||
- "${CHAT_DATA_DIR:?CHAT_DATA_DIR is required}:/var/lib/baiyue-logistics-chat"
|
||||
- "${CHAT_LOG_DIR:?CHAT_LOG_DIR is required}:/var/log/baiyue-logistics-chat"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=64m
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
stop_grace_period: 90s
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Validate gray release inputs and render files without logging credentials."""
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def absolute_path(value):
|
||||
path = PurePosixPath(value)
|
||||
if not re.fullmatch(r'/[A-Za-z0-9_./-]+', value) or '..' in path.parts or str(path) == '/':
|
||||
raise ValueError('A deployment path is invalid')
|
||||
return str(path)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GrayConfig:
|
||||
domain: str
|
||||
port: int
|
||||
root: str
|
||||
release: str
|
||||
proxy_dir: str
|
||||
certificate: str
|
||||
private_key: str
|
||||
commit: str
|
||||
image: str
|
||||
image_id: str
|
||||
certbot_image_id: str
|
||||
auth_dir: str = '/var/lib/baiyue-logistics-chat-gray-proxy'
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls, environment):
|
||||
origin = urlsplit(environment['PUBLIC_ORIGIN'])
|
||||
if (origin.scheme != 'https' or origin.username or origin.password or origin.port not in (None, 443)
|
||||
or origin.path not in ('', '/') or origin.query or origin.fragment
|
||||
or not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?', origin.hostname or '')):
|
||||
raise ValueError('PUBLIC_ORIGIN must be an HTTPS domain without a path')
|
||||
port = int(environment['HOST_PORT'])
|
||||
if not 1024 <= port <= 65535:
|
||||
raise ValueError('HOST_PORT must be an unprivileged TCP port')
|
||||
root = absolute_path(environment['GRAY_DEPLOY_DIR'])
|
||||
if PurePosixPath(root).name != 'gray-logistics-chat':
|
||||
raise ValueError('The deployment must use its dedicated gray-logistics-chat directory')
|
||||
commit = environment['SOURCE_COMMIT']
|
||||
image = environment['CHAT_IMAGE']
|
||||
image_id = environment['CHAT_IMAGE_ID']
|
||||
certbot_image_id = environment['CERTBOT_IMAGE_ID']
|
||||
build = environment['BUILD_NUMBER']
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', commit) or not re.fullmatch(r'[1-9][0-9]*', build):
|
||||
raise ValueError('Source commit or build number is invalid')
|
||||
if image != f'baiyue-logistics-chat-gray:{commit[:12]}-b{build}':
|
||||
raise ValueError('Image coordinates must identify the selected source and build')
|
||||
if any(not re.fullmatch(r'sha256:[0-9a-f]{64}', value) for value in (image_id, certbot_image_id)):
|
||||
raise ValueError('Docker image ID is invalid')
|
||||
return cls(origin.hostname, port, root, f'{root}/releases/{commit[:12]}-b{build}',
|
||||
absolute_path(environment['GRAY_PROXY_CONF_DIR']),
|
||||
absolute_path(environment['GRAY_TLS_CERT_FILE']),
|
||||
absolute_path(environment['GRAY_TLS_KEY_FILE']), commit, image, image_id, certbot_image_id)
|
||||
|
||||
def release_environment(self):
|
||||
fields = {
|
||||
'CHAT_IMAGE': self.image, 'CHAT_IMAGE_ID': self.image_id,
|
||||
'CHAT_CERTBOT_IMAGE': self.image.replace('baiyue-logistics-chat-gray:', 'baiyue-logistics-chat-certbot:'),
|
||||
'CHAT_CERTBOT_IMAGE_ID': self.certbot_image_id,
|
||||
'SOURCE_COMMIT': self.commit, 'HOST_PORT': str(self.port),
|
||||
'CHAT_ROOT': self.root, 'CHAT_RELEASE': self.release,
|
||||
'CHAT_DATA_DIR': self.root + '/data', 'CHAT_LOG_DIR': self.root + '/logs',
|
||||
'CHAT_RUNTIME_ENV': self.release + '/runtime.env',
|
||||
'CHAT_DOMAIN': self.domain, 'CHAT_PROXY_DIR': self.proxy_dir,
|
||||
'CHAT_TLS_CERT': self.certificate, 'CHAT_TLS_KEY': self.private_key,
|
||||
'CHAT_AUTH_DIR': self.auth_dir,
|
||||
}
|
||||
return ''.join(f'{key}={value}\n' for key, value in fields.items())
|
||||
|
||||
def nginx_config(self):
|
||||
return f'''# Managed for baiyue-logistics-chat-gray; guest chat is public and staff routes require authentication.
|
||||
server {{
|
||||
listen 80;
|
||||
server_name {self.domain};
|
||||
location ^~ /.well-known/acme-challenge/ {{
|
||||
root /var/lib/baiyue-logistics-chat-acme;
|
||||
try_files $uri =404;
|
||||
}}
|
||||
location / {{ return 301 https://$host$request_uri; }}
|
||||
}}
|
||||
server {{
|
||||
listen 443 ssl;
|
||||
server_name {self.domain};
|
||||
ssl_certificate {self.certificate};
|
||||
ssl_certificate_key {self.private_key};
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
auth_basic "Baiyue gray acceptance";
|
||||
auth_basic_user_file {self.auth_dir}/access.htpasswd;
|
||||
client_max_body_size 12m;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization "";
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
location = / {{
|
||||
auth_basic off;
|
||||
proxy_pass http://127.0.0.1:{self.port};
|
||||
}}
|
||||
location ^~ /static/ {{
|
||||
auth_basic off;
|
||||
proxy_pass http://127.0.0.1:{self.port};
|
||||
}}
|
||||
location ^~ /uploads/ {{
|
||||
auth_basic off;
|
||||
proxy_pass http://127.0.0.1:{self.port};
|
||||
}}
|
||||
location ~ ^/(?:healthz|stream_chat|api/(?:visitor/(?:session|human/(?:request|poll|send|close))|customer/(?:session|login|logout)|new_chat|get_history|get_messages|del_history|clear_all|upload|ticket|rate|feedback|speech/(?:config|transcribe)))$ {{
|
||||
auth_basic off;
|
||||
proxy_pass http://127.0.0.1:{self.port};
|
||||
}}
|
||||
location / {{
|
||||
proxy_pass http://127.0.0.1:{self.port};
|
||||
}}
|
||||
}}
|
||||
'''
|
||||
|
||||
|
||||
def runtime_environment(key, speech=None):
|
||||
fields = {'DEEPSEEK_API_KEY': key}
|
||||
speech = speech or {}
|
||||
provider = (speech.get('ASR_PROVIDER') or '').strip()
|
||||
if provider:
|
||||
if provider != 'baidu':
|
||||
raise ValueError('Gray speech provider must be baidu or disabled')
|
||||
fields.update(ASR_PROVIDER=provider,
|
||||
BAIDU_ASR_API_KEY=speech.get('BAIDU_ASR_API_KEY', ''),
|
||||
BAIDU_ASR_SECRET_KEY=speech.get('BAIDU_ASR_SECRET_KEY', ''))
|
||||
for value in fields.values():
|
||||
if not isinstance(value, str) or not value.strip() or any(c in value for c in ('\r', '\n', '\x00')):
|
||||
raise ValueError('Runtime credentials must be nonempty single lines')
|
||||
def literal(value):
|
||||
return "'" + value.strip().replace('\\', '\\\\').replace("'", "\\'") + "'"
|
||||
return ''.join(name + '=' + literal(value) + '\n' for name, value in fields.items())
|
||||
|
||||
|
||||
def write_release(directory, config, key, speech=None):
|
||||
runtime = runtime_environment(key, speech)
|
||||
directory.mkdir(parents=True, exist_ok=False)
|
||||
(directory / 'release.env').write_text(config.release_environment(), encoding='utf-8')
|
||||
(directory / 'site.conf').write_text(config.nginx_config(), encoding='utf-8')
|
||||
(directory / 'runtime.env').write_text(runtime, encoding='utf-8')
|
||||
(directory / 'runtime.env').chmod(0o600)
|
||||
source = Path(__file__).resolve().parent
|
||||
shutil.copyfile(source / 'compose.gray.yml', directory / 'compose.yml')
|
||||
shutil.copyfile(source / 'activate-gray.sh', directory / 'activate.sh')
|
||||
shutil.copyfile(source / 'prepare-gray-tls.sh', directory / 'prepare-tls.sh')
|
||||
shutil.copyfile(source / 'renew-gray-tls.sh', directory / 'renew-tls.sh')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directory', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
config = GrayConfig.from_environment(os.environ)
|
||||
write_release(args.directory, config, os.environ['DEEPSEEK_API_KEY'], os.environ)
|
||||
except (KeyError, ValueError) as error:
|
||||
parser.exit(2, 'Gray release configuration is incomplete or invalid.\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
: "${ORDER_SNAPSHOT_FILE:?}" "${TRACKING_SNAPSHOT_FILE:?}"
|
||||
: "${TARGET_SSH_KEY:?}" "${TARGET_SSH_USER:?}" "${TARGET_SSH_HOST:?}" "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||
: "${GRAY_DEPLOY_DIR:?}" "${SOURCE_COMMIT:?}" "${BUILD_NUMBER:?}"
|
||||
[[ "$TARGET_SSH_USER" =~ ^[A-Za-z0-9_.-]+$ && "$TARGET_SSH_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || exit 2
|
||||
[[ "$SOURCE_COMMIT" =~ ^[a-f0-9]{40}$ && "$BUILD_NUMBER" =~ ^[1-9][0-9]*$ ]] || exit 2
|
||||
root=$GRAY_DEPLOY_DIR
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
release_id="${SOURCE_COMMIT:0:12}-b$BUILD_NUMBER"
|
||||
release="$root/releases/$release_id"
|
||||
order_sha=$(sha256sum "$ORDER_SNAPSHOT_FILE" | awk '{print $1}')
|
||||
tracking_sha=$(sha256sum "$TRACKING_SNAPSHOT_FILE" | awk '{print $1}')
|
||||
ssh_options=(-i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes
|
||||
-o "UserKnownHostsFile=$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12)
|
||||
target="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||
|
||||
# Names are fixed; credentials and snapshot contents never enter the shell log.
|
||||
scp "${ssh_options[@]}" "$ORDER_SNAPSHOT_FILE" "$target:$release/order-input.json"
|
||||
scp "${ssh_options[@]}" "$TRACKING_SNAPSHOT_FILE" "$target:$release/tracking-input.json"
|
||||
ssh "${ssh_options[@]}" "$target" bash -s -- "$root" "$release_id" "$SOURCE_COMMIT" "$order_sha" "$tracking_sha" <<'IMPORT'
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
root=$1
|
||||
release_id=$2
|
||||
source_commit=$3
|
||||
order_sha=$4
|
||||
tracking_sha=$5
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release_id" =~ ^[a-f0-9]{12}-b[0-9]+$ && "$source_commit" =~ ^[a-f0-9]{40}$ ]] || exit 2
|
||||
[[ "$order_sha" =~ ^[a-f0-9]{64}$ && "$tracking_sha" =~ ^[a-f0-9]{64}$ ]] || exit 2
|
||||
release="$root/releases/$release_id"
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray && "$(cat "$root/current-release")" == "$release" ]] || exit 2
|
||||
container=baiyue-logistics-chat-gray
|
||||
[[ "$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$container")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
[[ "$(docker inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$container")" == "$source_commit" ]] || exit 2
|
||||
printf '%s %s\n' "$order_sha" "$release/order-input.json" "$tracking_sha" "$release/tracking-input.json" | sha256sum --check --status
|
||||
input="$root/data/imports/$release_id"
|
||||
[[ ! -e "$input" ]] || { echo 'Existing import input requires inspection.' >&2; exit 2; }
|
||||
cleanup() {
|
||||
rm -f -- "$input/orders.json" "$input/tracking.json" "$release/order-input.json" "$release/tracking-input.json"
|
||||
rmdir -- "$input" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
install -d -m 700 -o 10001 -g 10001 "$root/data/imports" "$input"
|
||||
install -m 600 -o 10001 -g 10001 "$release/order-input.json" "$input/orders.json"
|
||||
install -m 600 -o 10001 -g 10001 "$release/tracking-input.json" "$input/tracking.json"
|
||||
docker exec "$container" python -c 'import pathlib,sqlite3,sys; p=pathlib.Path("/var/lib/baiyue-logistics-chat/backups")/("pre-order-import-"+sys.argv[1]+".db"); assert not p.exists(); source=sqlite3.connect("/var/lib/baiyue-logistics-chat/history.db"); target=sqlite3.connect(str(p)); source.backup(target); target.close(); source.close(); print("Chat SQLite backup completed before sample import.")' "$release_id"
|
||||
docker exec "$container" python scripts/import_order_test_data.py \
|
||||
--db /var/lib/baiyue-logistics-chat/history.db --snapshot "/var/lib/baiyue-logistics-chat/imports/$release_id/orders.json"
|
||||
docker exec "$container" python scripts/import_order_test_data.py \
|
||||
--db /var/lib/baiyue-logistics-chat/history.db --snapshot "/var/lib/baiyue-logistics-chat/imports/$release_id/tracking.json" --tracking-only
|
||||
echo 'Private snapshots imported with existing order fields and nonempty tracking preserved.'
|
||||
IMPORT
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
: "${QUOTE_SNAPSHOT_FILE:?}"
|
||||
: "${TARGET_SSH_KEY:?}" "${TARGET_SSH_USER:?}" "${TARGET_SSH_HOST:?}" "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||
: "${GRAY_DEPLOY_DIR:?}" "${SOURCE_COMMIT:?}" "${BUILD_NUMBER:?}"
|
||||
[[ "$TARGET_SSH_USER" =~ ^[A-Za-z0-9_.-]+$ && "$TARGET_SSH_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || exit 2
|
||||
[[ "$SOURCE_COMMIT" =~ ^[a-f0-9]{40}$ && "$BUILD_NUMBER" =~ ^[1-9][0-9]*$ ]] || exit 2
|
||||
root=$GRAY_DEPLOY_DIR
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
release_id="${SOURCE_COMMIT:0:12}-b$BUILD_NUMBER"
|
||||
release="$root/releases/$release_id"
|
||||
quote_sha=$(sha256sum "$QUOTE_SNAPSHOT_FILE" | awk '{print $1}')
|
||||
ssh_options=(-i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes
|
||||
-o "UserKnownHostsFile=$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12)
|
||||
target="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||
scp "${ssh_options[@]}" "$QUOTE_SNAPSHOT_FILE" "$target:$release/quote-input.json"
|
||||
ssh "${ssh_options[@]}" "$target" bash -s -- "$root" "$release_id" "$SOURCE_COMMIT" "$quote_sha" <<'IMPORT'
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
root=$1
|
||||
release_id=$2
|
||||
source_commit=$3
|
||||
quote_sha=$4
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release_id" =~ ^[a-f0-9]{12}-b[0-9]+$ && "$source_commit" =~ ^[a-f0-9]{40}$ ]] || exit 2
|
||||
[[ "$quote_sha" =~ ^[a-f0-9]{64}$ ]] || exit 2
|
||||
release="$root/releases/$release_id"
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
input="$root/data/imports/quotes-$release_id"
|
||||
owned_input=0
|
||||
cleanup() {
|
||||
rm -f -- "$release/quote-input.json"
|
||||
if [[ "$owned_input" == 1 ]]; then
|
||||
rm -f -- "$input/quotes.json"
|
||||
rmdir -- "$input" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
[[ "$(cat "$root/current-release")" == "$release" ]] || exit 2
|
||||
container=baiyue-logistics-chat-gray
|
||||
[[ "$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$container")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
[[ "$(docker inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$container")" == "$source_commit" ]] || exit 2
|
||||
printf '%s %s\n' "$quote_sha" "$release/quote-input.json" | sha256sum --check --status
|
||||
[[ ! -e "$input" ]] || { echo 'Existing quote import input requires inspection.' >&2; exit 2; }
|
||||
install -d -m 700 -o 10001 -g 10001 "$root/data/imports" "$input"
|
||||
owned_input=1
|
||||
install -m 600 -o 10001 -g 10001 "$release/quote-input.json" "$input/quotes.json"
|
||||
docker exec "$container" python -c 'import pathlib,sqlite3,sys; p=pathlib.Path("/var/lib/baiyue-logistics-chat/backups")/("pre-quote-import-"+sys.argv[1]+".db"); p.parent.mkdir(exist_ok=True); assert not p.exists(); source=sqlite3.connect("/var/lib/baiyue-logistics-chat/history.db"); target=sqlite3.connect(str(p)); source.backup(target); target.close(); source.close(); print("Chat SQLite backup completed before quote import.")' "$release_id"
|
||||
docker exec "$container" python scripts/import_quote_data.py \
|
||||
--db /var/lib/baiyue-logistics-chat/history.db --snapshot "/var/lib/baiyue-logistics-chat/imports/quotes-$release_id/quotes.json" --activate
|
||||
echo 'General quote version activated; order data and customer grants preserved.'
|
||||
IMPORT
|
||||
@@ -0,0 +1,16 @@
|
||||
# Replace chat.example.com with your actual domain before installing.
|
||||
# HTTP certificate bootstrap only; the application is not exposed here.
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name chat.example.com;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/letsencrypt;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 404;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# Replace every chat.example.com with your actual domain before installing.
|
||||
# Install only after the certificate and .baiyue-preview.htpasswd exist.
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name chat.example.com;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/letsencrypt;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
server_name chat.example.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/chat.example.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/chat.example.com/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
|
||||
# Staff and unknown routes remain protected; guest APIs check their own visitor owner.
|
||||
auth_basic "Baiyue private acceptance";
|
||||
auth_basic_user_file /etc/nginx/.baiyue-preview.htpasswd;
|
||||
|
||||
# Allow multipart overhead around the application's 10 MiB file limit.
|
||||
client_max_body_size 12m;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Authorization "";
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
|
||||
location = / { auth_basic off; proxy_pass http://127.0.0.1:5000; }
|
||||
location ^~ /static/ { auth_basic off; proxy_pass http://127.0.0.1:5000; }
|
||||
location ^~ /uploads/ { auth_basic off; proxy_pass http://127.0.0.1:5000; }
|
||||
location ~ ^/(?:healthz|stream_chat|api/(?:visitor/(?:session|human/(?:request|poll|send|close))|customer/(?:session|login|logout)|new_chat|get_history|get_messages|del_history|clear_all|upload|ticket|rate|feedback|speech/(?:config|transcribe)))$ {
|
||||
auth_basic off;
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
}
|
||||
location / { proxy_pass http://127.0.0.1:5000; }
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
umask 022
|
||||
root=${1:?}
|
||||
release=${2:?}
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release" == "$root"/releases/* && "$release" != *..* ]] || exit 2
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
while IFS='=' read -r name value; do
|
||||
case "$name" in
|
||||
CHAT_ROOT|CHAT_RELEASE|CHAT_DOMAIN|CHAT_PROXY_DIR|CHAT_TLS_CERT|CHAT_TLS_KEY|CHAT_CERTBOT_IMAGE|CHAT_CERTBOT_IMAGE_ID|SOURCE_COMMIT)
|
||||
[[ "$value" =~ ^[A-Za-z0-9_./:-]+$ ]] || exit 2
|
||||
printf -v "$name" '%s' "$value" ;;
|
||||
esac
|
||||
done < "$release/release.env"
|
||||
[[ "$CHAT_ROOT" == "$root" && "$CHAT_RELEASE" == "$release" ]] || exit 2
|
||||
[[ "$CHAT_TLS_CERT" == "$root/tls/config/live/$CHAT_DOMAIN/fullchain.pem" ]] || exit 2
|
||||
[[ "$CHAT_TLS_KEY" == "$root/tls/config/live/$CHAT_DOMAIN/privkey.pem" ]] || exit 2
|
||||
[[ "$CHAT_CERTBOT_IMAGE" =~ ^baiyue-logistics-chat-certbot:[a-f0-9]{12}-b[0-9]+$ ]] || exit 2
|
||||
loaded_id=$(awk -F= '$1 == "CERTBOT_IMAGE_ID" {print $2}' "$release/loaded-image-ids.env")
|
||||
[[ "$loaded_id" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 2
|
||||
[[ "$(docker image inspect --format '{{.Id}}' "$CHAT_CERTBOT_IMAGE")" == "$loaded_id" ]] || { echo 'Loaded certificate image changed.' >&2; exit 2; }
|
||||
[[ "$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$CHAT_CERTBOT_IMAGE")" == "$SOURCE_COMMIT" ]] || exit 2
|
||||
|
||||
site="$CHAT_PROXY_DIR/baiyue-logistics-chat-gray.conf"
|
||||
if [[ -f "$site" ]]; then
|
||||
head -n 1 "$site" | grep -Fq 'Managed for baiyue-logistics-chat-gray' || exit 2
|
||||
else
|
||||
for candidate in "$CHAT_PROXY_DIR/"*.conf; do
|
||||
[[ -f "$candidate" ]] || continue
|
||||
if grep -Fq "$CHAT_DOMAIN" "$candidate"; then echo 'Domain already belongs to another site.' >&2; exit 2; fi
|
||||
done
|
||||
cat > "$release/bootstrap.conf" <<BOOTSTRAP
|
||||
# Managed for baiyue-logistics-chat-gray; HTTP certificate bootstrap only.
|
||||
server {
|
||||
listen 80;
|
||||
server_name $CHAT_DOMAIN;
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/lib/baiyue-logistics-chat-acme;
|
||||
try_files \$uri =404;
|
||||
}
|
||||
location / { return 404; }
|
||||
}
|
||||
BOOTSTRAP
|
||||
install -m 644 "$release/bootstrap.conf" "$site"
|
||||
if ! nginx -t; then rm -f -- "$site"; exit 2; fi
|
||||
nginx -s reload
|
||||
fi
|
||||
install -d -m 755 /var/lib/baiyue-logistics-chat-acme
|
||||
install -d -m 700 "$root/tls" "$root/tls/config" "$root/tls/work" "$root/tls/logs"
|
||||
if [[ ! -f "$CHAT_TLS_CERT" ]] || ! openssl x509 -in "$CHAT_TLS_CERT" -checkend 604800 -noout >/dev/null; then
|
||||
docker run --rm --name baiyue-logistics-chat-certbot-issue \
|
||||
-v "$root/tls/config:/etc/letsencrypt" -v "$root/tls/work:/var/lib/letsencrypt" \
|
||||
-v "$root/tls/logs:/var/log/letsencrypt" -v /var/lib/baiyue-logistics-chat-acme:/webroot \
|
||||
"$CHAT_CERTBOT_IMAGE" certonly --non-interactive --webroot -w /webroot \
|
||||
--cert-name "$CHAT_DOMAIN" -d "$CHAT_DOMAIN" --agree-tos --register-unsafely-without-email
|
||||
fi
|
||||
openssl x509 -in "$CHAT_TLS_CERT" -checkhost "$CHAT_DOMAIN" -noout >/dev/null
|
||||
|
||||
install -m 700 "$release/renew-tls.sh" "$root/tls/renew.sh"
|
||||
unit=/etc/systemd/system/baiyue-logistics-chat-tls-renew.service
|
||||
timer=/etc/systemd/system/baiyue-logistics-chat-tls-renew.timer
|
||||
for file in "$unit" "$timer"; do
|
||||
if [[ -e "$file" ]]; then head -n 1 "$file" | grep -Fq 'Managed for baiyue-logistics-chat-gray' || exit 2; fi
|
||||
done
|
||||
cat > "$unit" <<UNIT
|
||||
# Managed for baiyue-logistics-chat-gray
|
||||
[Unit]
|
||||
Description=Renew logistics chat gray certificate
|
||||
After=docker.service
|
||||
Requires=docker.service
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/bash $root/tls/renew.sh $root $CHAT_DOMAIN $CHAT_CERTBOT_IMAGE
|
||||
UNIT
|
||||
cat > "$timer" <<TIMER
|
||||
# Managed for baiyue-logistics-chat-gray
|
||||
[Unit]
|
||||
Description=Daily logistics chat gray certificate renewal
|
||||
[Timer]
|
||||
OnCalendar=daily
|
||||
RandomizedDelaySec=6h
|
||||
Persistent=true
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
TIMER
|
||||
chmod 644 "$unit" "$timer"
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now baiyue-logistics-chat-tls-renew.timer
|
||||
printf 'Gray certificate is ready; dedicated renewal timer enabled.\n'
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
: "${TARGET_SSH_KEY:?}" "${TARGET_SSH_USER:?}" "${TARGET_SSH_HOST:?}" "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||
: "${PREVIEW_USERNAME:?}" "${PREVIEW_PASSWORD:?}" "${CHAT_IMAGE:?}" "${CHAT_IMAGE_ID:?}" "${CERTBOT_IMAGE:?}"
|
||||
[[ "$PREVIEW_USERNAME" =~ ^[A-Za-z0-9_.@-]+$ ]] || exit 2
|
||||
[[ "$TARGET_SSH_USER" =~ ^[A-Za-z0-9_.-]+$ ]] || exit 2
|
||||
[[ "$TARGET_SSH_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || exit 2
|
||||
|
||||
temporary=$(mktemp -d)
|
||||
cleanup() { rm -rf -- "$temporary"; }
|
||||
trap cleanup EXIT
|
||||
python3 -m deploy.gray_config "$temporary/release"
|
||||
release=$(awk -F= '$1 == "CHAT_RELEASE" {print $2}' "$temporary/release/release.env")
|
||||
root=$(awk -F= '$1 == "CHAT_ROOT" {print $2}' "$temporary/release/release.env")
|
||||
python3 - <<'TARGET'
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
def addresses(host):
|
||||
return {item[4][0] for item in socket.getaddrinfo(host, 443, socket.AF_INET, socket.SOCK_STREAM)}
|
||||
if not addresses(urlsplit(os.environ['PUBLIC_ORIGIN']).hostname) & addresses(os.environ['TARGET_SSH_HOST']):
|
||||
raise SystemExit('The public domain does not resolve to the managed gray target.')
|
||||
TARGET
|
||||
printf '%s:' "$PREVIEW_USERNAME" > "$temporary/release/site.htpasswd"
|
||||
printf '%s\n' "$PREVIEW_PASSWORD" | openssl passwd -apr1 -stdin >> "$temporary/release/site.htpasswd"
|
||||
|
||||
ssh_options=(-i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes
|
||||
-o "UserKnownHostsFile=$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12)
|
||||
target="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||
run_ssh() { ssh "${ssh_options[@]}" "$target" "$@"; }
|
||||
|
||||
# Only an owned, dedicated directory may receive releases or runtime data.
|
||||
run_ssh bash -s -- "$root" "$release" <<'PREPARE'
|
||||
set -Eeuo pipefail
|
||||
root=$1
|
||||
release=$2
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release" == "$root"/releases/* ]] || exit 2
|
||||
[[ "$(id -u)" == 0 ]] || { echo 'The managed gray deployment account must have the required host permissions.' >&2; exit 2; }
|
||||
for program in docker nginx openssl curl ss systemctl sha256sum; do command -v "$program" >/dev/null; done
|
||||
if [[ -e "$root" && ! -f "$root/.project" ]] && [[ -n "$(find "$root" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then
|
||||
echo 'Refusing to reuse an unowned deployment directory.' >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -f "$root/.project" ]]; then
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
fi
|
||||
install -d -m 700 "$root" "$root/releases" "$root/data" "$root/logs"
|
||||
printf 'baiyue-logistics-chat-gray\n' > "$root/.project"
|
||||
chown 10001:10001 "$root/data" "$root/logs"
|
||||
[[ ! -e "$release" ]] || { echo 'Release directory already exists; inspect its state before retrying.' >&2; exit 2; }
|
||||
install -d -m 700 "$release"
|
||||
PREPARE
|
||||
|
||||
# Verify the exact exported archive before loading. Classic and containerd image
|
||||
# stores can report different IDs for the same archive, so retain target IDs too.
|
||||
docker save "$CHAT_IMAGE" "$CERTBOT_IMAGE" | gzip > "$temporary/images.tar.gz"
|
||||
archive_sha=$(sha256sum "$temporary/images.tar.gz" | awk '{print $1}')
|
||||
scp "${ssh_options[@]}" "$temporary/images.tar.gz" "$target:$release/images.tar.gz"
|
||||
run_ssh bash -s -- "$root" "$release" "$archive_sha" "$CHAT_IMAGE" "$CERTBOT_IMAGE" "$SOURCE_COMMIT" <<'LOAD'
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
root=$1
|
||||
release=$2
|
||||
checksum=$3
|
||||
app_image=$4
|
||||
certbot_image=$5
|
||||
source_commit=$6
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$release" == "$root"/releases/* && "$release" != *..* ]] || exit 2
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
[[ "$checksum" =~ ^[a-f0-9]{64}$ && "$source_commit" =~ ^[a-f0-9]{40}$ ]] || exit 2
|
||||
[[ "$app_image" =~ ^baiyue-logistics-chat-gray:[a-f0-9]{12}-b[0-9]+$ ]] || exit 2
|
||||
[[ "$certbot_image" =~ ^baiyue-logistics-chat-certbot:[a-f0-9]{12}-b[0-9]+$ ]] || exit 2
|
||||
printf '%s %s\n' "$checksum" "$release/images.tar.gz" | sha256sum --check --status
|
||||
gzip -dc "$release/images.tar.gz" | docker load
|
||||
for image in "$app_image" "$certbot_image"; do
|
||||
[[ "$(docker image inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$image")" == "$source_commit" ]] || exit 2
|
||||
done
|
||||
app_id=$(docker image inspect --format '{{.Id}}' "$app_image")
|
||||
certbot_id=$(docker image inspect --format '{{.Id}}' "$certbot_image")
|
||||
[[ "$app_id" =~ ^sha256:[a-f0-9]{64}$ && "$certbot_id" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 2
|
||||
printf 'ARCHIVE_SHA256=%s\nCHAT_IMAGE_ID=%s\nCERTBOT_IMAGE_ID=%s\n' "$checksum" "$app_id" "$certbot_id" > "$release/loaded-image-ids.env"
|
||||
rm -f -- "$release/images.tar.gz"
|
||||
echo 'Image archive checksum and source labels verified; target image IDs recorded.'
|
||||
LOAD
|
||||
scp "${ssh_options[@]}" "$temporary/release/"* "$target:$release/"
|
||||
run_ssh bash "$release/prepare-tls.sh" "$root" "$release"
|
||||
run_ssh bash "$release/activate.sh" "$root" "$release"
|
||||
|
||||
# Verify the public TLS endpoint and the actual acceptance password without putting it in arguments.
|
||||
python3 - <<'VERIFY'
|
||||
import json
|
||||
import os
|
||||
from urllib.request import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener
|
||||
origin = os.environ['PUBLIC_ORIGIN'].rstrip('/')
|
||||
manager = HTTPPasswordMgrWithDefaultRealm()
|
||||
manager.add_password(None, origin, os.environ['PREVIEW_USERNAME'], os.environ['PREVIEW_PASSWORD'])
|
||||
opener = build_opener(HTTPBasicAuthHandler(manager))
|
||||
with opener.open(origin + '/healthz', timeout=30) as response:
|
||||
assert response.status == 200 and json.load(response) == {'status': 'ok'}
|
||||
print('Authenticated gray HTTPS health check passed.')
|
||||
VERIFY
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
/usr/sbin/nginx -t
|
||||
/usr/bin/systemctl reload nginx
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set +x
|
||||
set -Eeuo pipefail
|
||||
root=${1:?}
|
||||
domain=${2:?}
|
||||
image=${3:?}
|
||||
[[ "$root" == /*/gray-logistics-chat && "$root" != *..* ]] || exit 2
|
||||
[[ "$domain" =~ ^[a-z0-9.-]+$ && "$image" =~ ^baiyue-logistics-chat-certbot:[a-f0-9]{12}-b[0-9]+$ ]] || exit 2
|
||||
[[ "$(cat "$root/.project")" == baiyue-logistics-chat-gray ]] || exit 2
|
||||
certificate="$root/tls/config/live/$domain/fullchain.pem"
|
||||
previous=$(sha256sum "$certificate")
|
||||
docker run --rm --name baiyue-logistics-chat-certbot-renew \
|
||||
-v "$root/tls/config:/etc/letsencrypt" -v "$root/tls/work:/var/lib/letsencrypt" \
|
||||
-v "$root/tls/logs:/var/log/letsencrypt" -v /var/lib/baiyue-logistics-chat-acme:/webroot \
|
||||
"$image" renew --non-interactive --cert-name "$domain"
|
||||
if [[ "$(sha256sum "$certificate")" != "$previous" ]]; then nginx -t; nginx -s reload; fi
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Keep Linux service data outside the read-only application checkout."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from logistics_chat import create_app as create_application
|
||||
|
||||
|
||||
DATA_DIR = Path('/var/lib/baiyue-logistics-chat')
|
||||
LOG_DIR = Path('/var/log/baiyue-logistics-chat')
|
||||
|
||||
|
||||
def create_app():
|
||||
return create_application({
|
||||
'DATABASE': DATA_DIR / 'history.db',
|
||||
'UPLOAD_DIR': DATA_DIR / 'uploads',
|
||||
'BACKUP_DIR': DATA_DIR / 'backups',
|
||||
'LOG_DIR': LOG_DIR,
|
||||
'HOST': '127.0.0.1',
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
# 模块导航与拆分规范
|
||||
|
||||
四阶段拆分已落地:`am.py` 保留命令及 WSGI 兼容入口,应用工厂和业务代码位于 `logistics_chat/`,页面样式与脚本位于 `static/`。本文描述当前结构及后续结构调整约定。
|
||||
|
||||
## 先定位,再阅读
|
||||
|
||||
从 [AGENTS.md](../AGENTS.md) 选择文件,以函数、常量、接口为锚点,搜索后只读取相关实现和调用方。模块移动时更新索引,不保存易失效的行号。默认遵守 Git 忽略规则,排除附件、数据库、日志、备份、虚拟环境和工作草稿。
|
||||
|
||||
```powershell
|
||||
rg --files
|
||||
rg -n -F 'calc_freight' logistics_chat/pricing.py
|
||||
rg -n -F '/api/human/' logistics_chat/routes static/js examples
|
||||
rg -n '^(def |class | def )' scripts tests -g '*.py'
|
||||
```
|
||||
|
||||
PowerShell 下把目录和 `-g '*.py'` 分开传给 `rg`。报价字典可能整行很长,搜索时加 `--max-columns 200 --max-columns-preview`,避免输出整份数据。
|
||||
|
||||
## 当前模块索引
|
||||
|
||||
| 业务范围 | 实际文件与搜索锚点 | 联动位置 |
|
||||
|---|---|---|
|
||||
| 应用入口与配置 | `am.py`:`main`、延迟访问的 `app`;`logistics_chat/__init__.py`:`create_app`;`config.py`:`default_config`、`get_setting`;`runtime.py`:`serve_app` | `start.bat`、`.env.example` |
|
||||
| Jenkins 灰度部署 | `Jenkinsfile`、`Dockerfile`;`deploy/gray_config.py`:`GrayConfig`;`publish-gray.sh`、`activate-gray.sh`、`prepare-gray-tls.sh`、`renew-gray-tls.sh` | [部署指南](deployment.md);独立持久化数据、证书和回环端口;`wsgi.py` 提供容器内路径 |
|
||||
| 请求钩子 | `logistics_chat/hooks.py`:`rate_limit`、`no_cache_html` | 工厂注册钩子;限流状态在 `app.extensions['rate_hits']` |
|
||||
| SQLite 与维护 | `logistics_chat/db.py`:`connect`、`close_connections`、`init_db`、`backup_db`、`save_message`、`last_user_question`、`load_context` | 维护 CLI 在 `scripts/`;旧会话自动清理仍未启用 |
|
||||
| 历史接口 | `logistics_chat/history_service.py`:`new_chat`、`get_history`、`get_messages`、`del_history`、`clear_all`;对应 `routes/history.py` | `static/js/chat.js`:`ensureConv`、`loadHistory`、`openConversation` |
|
||||
| 知识检索 | `logistics_chat/knowledge.py`:`knowledge_list`、`search_knowledge` | [knowledge.md](knowledge.md) 与代码同步,程序不读取该文档 |
|
||||
| 运费与附加费 | `logistics_chat/pricing.py`:`RATES`、`parse_shipping_intent`、`dims_to_cm`、`pick_rate`、`calc_freight`、`freight_reply`、`calc_warehouse_card`、`detect_surcharge`、`check_island` | `logistics_chat/rates_extra.py` 为唯一扩展数据源,根目录同名文件仅兼容转发 |
|
||||
| 卡片协议 | `logistics_chat/tracking.py`:`CARD_PREFIX`、`card_to_text`;旧 `extract_tracking_no`、`build_track` 仅兼容旧导入 | `static/js/chat.js`:`fillTrackCard`、`addTrackCard`;新订单卡片由 `order_data.py` 提供,历史卡片保留兼容渲染 |
|
||||
| 订单测试表 | `logistics_chat/order_data.py`:`init_order_table`、`import_records`、`lookup_order`、`count_orders`、`answer_query` | SQLite `order_test_data` 为可编辑快照;按订单号、入仓码、Shipment ID 精确查表。将来 MCP 在取数层替换 `lookup_order`、`count_orders`,不让模型拼 SQL |
|
||||
| 查单交互 | `static/js/order_lookup.js`:`OrderLookup.create`;`chat.js`:`showOrderLookup`、`fillTrackCard`;`support.js`:`copyText` | 快捷入口及当前/历史卡片共用查询框;显式输入后才查单,保留聊天草稿和附件;复制共用安全回退 |
|
||||
| AI 与 SSE | `logistics_chat/chat_service.py`:`create_chat_stream`、`sse`;`ai_client.py`:`post_completion`、`compress_answer`、`gen_followups` | `routes/chat.py`:`stream_chat`;客户端 `doSend`、`renderError`、`renderFollowups` |
|
||||
| 人工会话 | `logistics_chat/human_service.py`:`human_*`(含转接、备注、撤回);对应 `routes/human.py` | 输入状态在 `app.extensions['human_typing']`;客户 `startHumanPoll`;客服 `loadQueue`、`poll`、`sendReply`;人工申请每天 8:00–22:00 |
|
||||
| 附件 | `logistics_chat/file_service.py`:`upload_file`、`cleanup_uploads`;`routes/files.py`:`uploaded_file` | 扩展名/大小/目录由配置提供;客户端 `addMsg`,客服端 `appendMsg` |
|
||||
| 登录、统计、订单、留言、导出 | `logistics_chat/business_service.py`:`admin_login`、`admin_stats`、`my_orders`、`add_ticket`、`list_tickets`、`export_chat` | `routes/admin.py`、`routes/business.py`;登录页 `static/js/admin_login.js` |
|
||||
| 页面 | `templates/index.html`、`templates/admin.html`、`templates/admin_login.html` | 先加载共享 `static/css/theme.css`;客户与客服脚本先加载 `support.js`(表情、通知、评价);客服再加载 `admin_tools.js`(备注、转接、历史搜索),最后加载 `admin.js`;保留全局事件入口 |
|
||||
| 回归 | `tests/test_rules.py`、`test_storage.py`、`test_api.py`、`test_dev_integration.py`、`test_config.py`、`test_deployment.py`、`test_gray_config.py`、`test_gray_activation.py`、`test_startup.py`、`test_maintenance_scripts.py`、`test_frontend.py`;`tests/frontend/admin.test.cjs`、`chat.test.cjs` | Linux 回退模拟基础设施、实际操作临时文件;模型、数据库及上传隔离;Node 验证草稿、异步切换、转接、撤回及评价;浏览器使用临时测试库 |
|
||||
|
||||
除标明的根目录文件外,表内缩写的 Python 文件均相对 `logistics_chat/`。
|
||||
|
||||
## 当前文件布局
|
||||
|
||||
```text
|
||||
am.py # CLI;显式请求 am.app 时创建默认 WSGI 应用
|
||||
rates_extra.py # 旧导入路径的兼容转发
|
||||
logistics_chat/
|
||||
├── __init__.py # create_app 与显式运行时初始化
|
||||
├── config.py # 根目录 .env、环境变量、稳定根路径、服务/资源配置
|
||||
├── db.py # 连接、schema、历史持久化、备份
|
||||
├── knowledge.py # 知识与关键词检索
|
||||
├── pricing.py # 运费规则、解析、换算、附加费说明
|
||||
├── rates_extra.py # 扩展报价数据
|
||||
├── tracking.py # 单号识别、模拟轨迹、卡片协议
|
||||
├── order_data.py # 可编辑订单测试表、精确查询、快照导入与卡片事实
|
||||
├── ai_client.py # 模型 HTTP、压缩与追问
|
||||
├── chat_service.py # 问答编排与 SSE 帧
|
||||
├── history_service.py # 历史会话 CRUD
|
||||
├── human_service.py # 人工状态与消息
|
||||
├── business_service.py # 反馈、评价、统计、登录、订单、留言、历史搜索、Excel/CSV
|
||||
├── file_service.py # 附件校验、保存、清理
|
||||
├── hooks.py # 限流及 HTML/SSE 缓存头
|
||||
├── runtime.py # Waitress / Flask 启动
|
||||
└── routes/
|
||||
├── __init__.py # Blueprint 注册
|
||||
├── chat.py
|
||||
├── history.py
|
||||
├── human.py
|
||||
├── admin.py
|
||||
├── business.py
|
||||
├── files.py
|
||||
└── pages.py
|
||||
templates/ # HTML/Jinja 及原有事件属性
|
||||
static/css/ # theme.css 共享令牌;chat/admin/admin_login 页面样式
|
||||
static/js/ # chat.js、admin.js、admin_login.js,经典脚本
|
||||
scripts/ # 可独立运行的维护 CLI
|
||||
tests/ # 按业务模块组织的回归
|
||||
```
|
||||
|
||||
## 模块边界与依赖方向
|
||||
|
||||
- 路由只解析请求并包装响应;服务组织业务;规则模块提供确定性计算。依赖方向为 `routes → services → rules / db / ai_client`,下层不导入路由或根入口。
|
||||
- `db.py` 统一连接、schema 和历史持久化。人工与管理业务的 SQL 放在所属服务,HTTP 路由不执行 SQL。请求及流式请求结束时关闭连接,未提交事务回滚。
|
||||
- `init_db` 包括客服账号、订单与留言表,首次启动只建空表;不内置账号。重复初始化保留已有数据,业务测试从真实初始化结果插入夹具,不另建缺失表。
|
||||
- 所有模型 HTTP 经 `ai_client.post_completion`。保留流式问答 `(5, 90)`、压缩 `(5, 30)`、追问 `(5, 15)` 三组连接/读取超时;不能因共用客户端而合并期限。流结束或取消时释放 HTTP 响应。
|
||||
- 模块导入不建库、不备份、不清理附件、不访问模型。`create_app` 默认显式初始化运行目录、数据库、备份与旧附件清理;`INITIALIZE_RUNTIME=False` 可禁止这些动作,此时调用方负责提供已有 schema。访问兼容入口 `am.app` 视为显式创建应用。
|
||||
- `config.ROOT_DIR` 指向仓库根目录,模板/静态目录显式提供给 Flask。数据库、上传、备份、日志使用配置中的绝对路径,避免包文件移动改变数据位置。
|
||||
- `default_config` 用 `python-dotenv` 读取根目录 `.env`,不修改 `os.environ`;只读取已支持的 `DEEPSEEK_API_KEY`,不展开 `${...}`。显式工厂配置优先于进程环境(含空值),再使用文件值。配置在应用创建时确定,修改后重启;真实 `.env` 不纳入 Git。
|
||||
- 限流、输入状态由应用实例持有,不能每请求重置或跨测试应用共享。维护 CLI 和纯规则可用标准库加载,包入口延迟导入 Web 依赖。
|
||||
- 单文件围绕一个职责;超过约 300–400 行时检查职责,而非按行数机械拆分。报价数据保持单一来源;兼容转发不复制字典。页面脚本按页面保留既有执行顺序和全局函数,不擅自改为 ES Modules。
|
||||
- 配色、字体基线和通用控件放在 `theme.css`,页面布局放在对应 CSS。客户页通过 `body.dark` 覆盖主题令牌;新增可翻译文案加入 `chat.js` 的 `I18N`,静态文案用 `data-i18n`。调整样式后检查桌面、390px 窄屏、侧栏、聊天卡片和客服空/活动状态。
|
||||
- 客户界面不附加测试/演示声明、底部免责声明、键盘说明、快捷入口副标题或附件准备说明;草稿恢复和发送成功静默处理。加载、录音、人工排队状态及操作失败反馈保留,权限校验继续由服务端执行。
|
||||
- 客户查货以入仓码为主要入口,输入占位、快捷入口与查询追问均优先使用入仓码;订单卡片从 `fields.inbound` 取得主显示号码,内部订单号放在展开详情。`card.no` 仍保存内部订单号以兼容历史协议和上下文关联;未提供入仓码时保留准确的订单号标签,不生成替代入仓码。
|
||||
- 客户附件预览由 `clearAttachment` 管理,轨迹展开由 `fillTrackCard` 管理。客服 `drafts` 按 `sid` 保存草稿,发送成功后只清理已确认发送的内容;常用回复仅填入草稿。`renderList` 只在展示数据变化时重绘。
|
||||
- 客户文字草稿由 `drafts.js` 的 `ChatDrafts.create` 管理,脚本在 `visitor.js` 之后、`chat.js` 之前加载;localStorage 按访客 key 和会话分条存储,sessionStorage 仅记录当前标签页的活动会话。切换前同步保存,输入防抖及页面隐藏时保存;无持久存储时使用页面内存并提示。恢复历史的异步结果受会话版本约束,加载失败禁止继续发送,删除会话同步清除其草稿。草稿不含未发送附件,不跨设备同步。
|
||||
- 人工申请由服务端以 UTC+8 判断每日 08:00–22:00 营业状态,客户手机时区不参与判断。附件清理保留 `messages` 和 `human_messages` 引用的文件,仅删除超过 7 天的未引用临时文件;读取引用失败时停止清理。附件不存在或不属于当前游客均返回相同的私有、不可缓存 404 页面,破图在聊天中显示可读提示。
|
||||
- 客户页 `resetConversation` 统一处理新建、快捷问题和历史切换;人工路由同时绑定 `humanConvId` 与当前会话版本。旧建会话、历史、人工申请和轮询的异步结果不得覆盖新话题。三个业务快捷入口开启独立 AI 对话,联系人工入口才进入人工模式;排队/接待状态常驻输入框上方,可用「返回 AI 问答」结束人工会话。人工消息确认成功后才清空草稿,失败保留输入;服务端校验可选 `conv_id` 并拒绝已关闭会话。
|
||||
- 客服工作台默认只展示会话列表和全高聊天区;统计使用原生 `details` 收在「数据概览」。`setSessionTab` 切换接待/排队列表,`setChatView` 与 `showSessionList` 控制 720px 及以下的整屏导航,不结束当前会话。`setToolsOpen` 控制默认关闭的服务资料:1200px 以上为侧栏,较窄屏为抽屉;列表入口让未选会话的手机用户也能查看留言。
|
||||
|
||||
## 后续结构调整顺序
|
||||
|
||||
| 阶段 | 范围 | 验收要求 |
|
||||
|---|---|---|
|
||||
| 1. 纯规则 | 知识、报价、运费、运单识别 | 边界结果与迁移前一致;固定时钟比较模拟轨迹;导入无运行数据副作用 |
|
||||
| 2. 数据访问 | 配置、SQLite、备份、附件 | 临时目录验证 schema 兼容、事务、保留/清理时机和跨目录 CLI |
|
||||
| 3. 服务/路由 | 模型、聊天、人工、应用工厂、Blueprint | URL/方法/状态/JSON/SSE 不变;保留限流、HTML/SSE 缓存头及根入口 |
|
||||
| 4. 前端 | 模板与 CSS/JS | 仅迁移时对照原资源内容;主动改版时验证语法、资源 URL、加载顺序、响应式和客户/客服页交互 |
|
||||
|
||||
每阶段完成相关验证再推进依赖阶段。鉴权、缺表和计费的业务修复单独说明,避免在结构调整中顺带改行为。
|
||||
|
||||
## 必须保留的接口与数据约定
|
||||
|
||||
- SSE 字段为 `t`、`e`、`card`、`replace`、`suggest`、`d`;客户端兼容 LF/CRLF 和跨字节分段,收到 `d` 才算成功,意外 EOF 保留已收到正文并提供重试。上游缺少结束标记或因长度截断时保存中断状态;压缩、追问、流式 HTTP 响应都要关闭。首段等待 90 秒、整轮 120 秒;会话、历史及人工 JSON 请求 10 秒,上传 15 秒超时可恢复。
|
||||
- `chat_service.create_chat_stream` 的订单查询使用本地 `order_test_data`;忽略附件路径、重量、日期和三维尺寸,保留标识中的后缀,不再调用 `build_track` 生成模拟轨迹。旧模拟函数仅兼容旧导入,不进入聊天查询路径。未知单号、多条匹配和查表失败明确说明,禁止回退模型编造状态。
|
||||
- `CARD_PREFIX` 新增 `kind=order`:仅包含白名单概要、申报货物汇总和订单业务状态历史,不包含姓名、地址、内部备注或操作人。`order_tracking.py` 从 `order_test_data.tracking_json` 的已关联事实生成物流轨迹;存在有效事实时设置 `node_kind=logistics`,`nodes` 仅存实际节点,`estimated_nodes` 单独展示预计节点,`tracking_status` 只按实际节点序号推进。相同货柜/节点按最新观测修正时间,预计事实不覆盖实际事实;多柜独立展示。缺失的节点、地点和签收事实不得补造,提柜、还柜不等于签收。子单不继承父单重量或轨迹;COMPLETED 只表示头程订单完成。没有物流事实时继续展示业务状态历史。页面和模型上下文不附加测试副本声明或导入时间。订单及物流追问只在同一 `conv_id` 内复用最近单号,并重新查表取得修改后的值;新报价或其他话题不会沿用旧订单。
|
||||
- 订单表不提供管理页面或对外增删改接口;表数据在运行时 SQLite 内维护,导入脚本默认保留已有记录,只有显式 `--replace` 覆盖。匿名 HTTP 查单在读取订单前返回登录引导;`g.customer_tenant_id` 由可信客户认证适配器设置,不接受访客 key、请求参数或客户自报 Header。客户范围非空时必须传给 `lookup_order`,并与 `ORDER_DATA_TENANT_ID` 的额外限制取交集。源库连接凭据和快照在仓库外,业务库只读,不随服务查询访问源库。
|
||||
- 登录后的订单数量由 `parse_count_query` / `order_query.parse_query` 识别,汇总、筛选和列表共用 `order_listing.read_orders` 的服务端 `tenant_filter` 交集与同一只读快照;`count_orders` 保留原聚合调用契约。默认给总数、已登记入仓码数及最多5条按来源更新时间排序的摘要;支持业务状态、明确标记的异常和当前实际节点。未指定节点的轨迹统计按订单分组,每票只计一次,多柜不同进度单列,预计节点不推进进度,业务完成不当作签收。未知条件不默认为全部,也不交给模型猜数。内部 `_customer_data` 和 `_order_list_state` 在发送前移除,事实历史绑定客户与范围;无新增公开API。
|
||||
- 客户认证使用独立 `customer_users`、`customer_tenant_grants` 与 `customer_sessions` 表,由 `customer_service.attach_customer` 在访客恢复之后验证并设置 `g.customer`、单客户 `g.customer_tenant_id` 或多客户 `g.customer_tenant_ids`;只保存密码哈希与登录 token 哈希。默认账号首次关联当前本地订单的客户范围,之后不自动扩大,普通账号仍按明确关联过滤;`lookup_order` 的单客户参数及多客户白名单都与环境限制取交集。会话的 `customer_scope` 保存范围指纹。登录 Cookie 为 HttpOnly、SameSite=Lax,在 HTTPS 上为 Secure,绑定当前访客并在 8 小时后失效;退出、账号停用、密码或客户范围改变使旧会话失效。默认客户账号不赋予客服后台权限。
|
||||
- 匿名查单返回 SSE `login_required` 与正文,客户页提供登录按钮;`customer.js` 登录成功后仅在原会话版本未变化时继续原问题,保留期间输入的新草稿。登录过期导致界面清空时,只允许同一客户重新通过历史归属校验后恢复原会话并续查;换账号、访问范围变化、历史加载失败或切换话题均不重放旧问题。侧栏可独立登录/退出,登录状态在窗口恢复焦点时刷新。首次返回订单卡片时,会话绑定客户 ID 和客户范围;历史、人工会话及后续生成同时校验访客、客户和范围。退出立即清除当前可见订单内容和历史标题缓存,重新登录同一身份可恢复;匿名清空历史不删除被登录保护的会话。
|
||||
- 底部及欢迎卡片的查入仓码入口先确认客户登录,再打开 `OrderLookup`,不自动新建会话或发送缺少号码的问题。当前及历史订单卡片的号码也打开该查询框,保留真实的入仓码/订单号标签,支持单独复制和重新查询。提交使用既有 `/stream_chat` 并显示明确的用户问句,结果追加到当前会话;主输入框草稿及已上传附件不清空、不代发。人工接待、未加载历史或其他请求进行中时不抢占路由。切换话题/身份关闭弹窗,迟到的登录/状态/复制结果不得改动新上下文;弹窗跟随手机可视视口并将焦点还给触发按钮。
|
||||
- 节点导出:`scripts/export_order_tracking.py --database-env <显式环境文件> --orders-snapshot <私有订单快照> --output <新私有节点快照>`。仅需离线导出时安装可选 `PyMySQL`;脚本开启源库只读事务,只查询快照订单直接关联的入库完成、已冻结装柜和标准船节点,按客户与源订单 ID 同时匹配。随后运行 `scripts/import_order_test_data.py --snapshot <节点快照> --db <运行数据库> --tracking-only`;只更新已有订单的 `tracking_json`,校验源 ID,不改订单字段,默认保留已有轨迹。`--replace` 才覆盖手工轨迹。快照不随 Git 发布;将来 MCP 接入仍返回同一事实结构,无需改变卡片协议。
|
||||
- 历史卡片以 `__CARD__{json}` 保存;原 SQLite 表、字段、角色值和历史记录继续可读。历史正文和卡片使用存库时间,卡片恢复复制操作。切换话题或历史时取消旧流和待上传附件;等待建会话期间的新草稿不能被旧发送清空。历史刷新失败保留已有列表;删除或清空成功后先同步本地列表,并使先前的刷新失效,刷新失败或迟到均不恢复已删除记录。删除会话同步移除其人工会话及消息,迟到的模型写入不能生成孤立消息。
|
||||
- 人工申请使用 `conv_id`,返回 `session_id`,后续用 `sid`。状态为 `waiting/active/closed`,消息方向为 `customer/agent/system`。转接将 active 改为 waiting,列表只允许主动接入。备注保存在 `human_sessions.note`;撤回将原客服消息改为系统提示并追加带 `recalled_id` 的系统事件,轮询按原消息编号更新,重复撤回不追加事件。
|
||||
- 新建会话保存一条 assistant 欢迎语并返回 `welcome`,前端在首次用户消息之前显示。首次提问判定只统计 user 消息。服务评价用 `ratings` 保存,并汇总到管理统计。Excel 导出依赖 `openpyxl`,原 CSV 可用 `?format=csv` 访问。
|
||||
- 计费档位、单位换算和舍入保持原样。`shipping_intent_with_context` 用 `is_shipping_followup` 识别渠道、重量、尺寸、单独目的地回复及重试,保留报价条件;新订单、另外一票、理赔及新的完整问题形成回溯边界,不继承上一票尺寸。尺寸支持带小数和空格,换算单位后计价。中英混写的 UK/US 按 ASCII 边界识别;目的地未确认时先询问目的国家,不默认给出欧洲报价。英国使用英国渠道和默认比价组合。美国使用已激活的本地通用价表;未导入美国价表或其他未覆盖目的地时不套用欧洲费率,英国按方报价不套用欧洲仓价;指定国家或仓点没有匹配时 `calc_warehouse_card` 返回空。`calc_freight.total` 仅含基础运费;附加费尚未统一并入。知识文档与 `knowledge_list` 同步维护。
|
||||
- 聊天请求的会话编号仅接受 SQLite 整数范围内的 ASCII 十进制整数或空值;字符串转换前限制长度,非法 Unicode 数字和超长数字返回 SSE 输入错误,不进入模型调用。
|
||||
- 上传 URL 保留 `/uploads/`,默认 10MB,扩展名配置保持不变。原附件保留本地、继续忽略,目录迁移不另建一份数据。
|
||||
- 手机语音由 `voice.js` 管理按住、松开、上滑取消、60 秒上限及媒体轨道释放;切换会话、离开页面或权限/转写超时取消录音与待处理请求,迟到结果不能进入新会话,已有草稿不自动提交。`/api/speech/config` 仅返回可用性及限制,`/api/speech/transcribe` 有独立 5MB 请求限制并以 `MemoryAudioRequest` 将音频文件保持在内存中;音频不进入 uploads 或聊天历史。百度适配通过 FFmpeg 管道转换 16 kHz 单声道 PCM,校验真实解码长度后调用百度短语音识别,Token 按应用隔离缓存。可选 DashScope 适配和 DS 文字聊天凭据独立,密钥及上游原始错误不得返回客户端。识别结果走既有 AI/人工消息入口。H5 订单详情默认折叠;可视高度变化保持最新回复可见,阅读旧消息时不强制拉到底部。
|
||||
- `agents`、`orders`、`tickets` 在应用初始化时建空表;兼容已有独立 id 列的 agents 表,不预置账号或演示数据。
|
||||
- 游客由 `visitor.js` 用安全随机数生成本地 key,经 `/api/visitor/session` 换取 HttpOnly、SameSite Cookie,HTTPS 时设置 Secure;浏览器存储不可用时可用 Cookie 恢复。数据库 `chat_history.visitor_id` 仅存 key 的 SHA-256,历史增删查、SSE 上下文和 `visitor_uploads` 附件索引均按归属校验。旧数据归属为空时保留,不自动授予新访客。客户端公共人工接口为 `/api/visitor/human/{request,poll,send,close}`,校验会话归属、只接受 customer 消息并去掉内部备注;原 `/api/human/*` 留给受保护客服。客服附件用 `/api/staff/uploads/`,所有客户 JSON 与附件禁止共享缓存。
|
||||
- Nginx 默认保护客服及未知路径,只有客户首页、静态资源和明确的客户 API 白名单免密码。后台仍依赖代理认证,上游只能绑定回环地址;客户账号登录独立校验,游客身份不能升级为订单权限。
|
||||
|
||||
## 验证与维护
|
||||
|
||||
美国报价由 `quote_workbook.py` 导出当前 Excel 本地明细;`quote_data.py` 管理版本与 SQLite;`quote_intent.py` 解析单位、逐箱明细和业务意图;`quote_engine.py` 负责纯匹配/Decimal 计价;`quote_answers.py` 和 `quote_fees.py` 从当前版本说明读取业务收费;`quote_language.py` 翻译常规英文报价;`quote_service.py` 续接当前会话并通过 `answer_quote` 返回既有 `t`/`d` 事件。分流位置在订单权限检查之后、旧报价/模型分流之前。
|
||||
|
||||
新建库不预置价格;私有快照事务导入、显式激活,读取使用同一事务固定版本,后续查询读取更新后的价格。不访问外部工作簿,不按文件日期或旧船期停用。仓码重复分区并列;邮编存文本;上下文仅来自当前访客拥有的同一会话,新的完整问题、其他国家及订单/理赔话题构成边界。回复不包含原始快照、联系人、文件路径或旧船期,不新增公开导入/管理接口。
|
||||
|
||||
`quote_documents` 保存当前资料说明,复杂业务说明及尚未实现的附加费仍需逐项扩展匹配规则,不代表已全部自动结算。生产镜像必须显式包含 `scripts/import_quote_data.py`。
|
||||
|
||||
已确认口径:同件超重/超尺寸只取最高适用档,其他附加费分别计算;洛杉矶普船海卡体积保留两位、四舍五入;海外进口清关超过5个品名的续页按美元/个。原表大尺寸长度条件有误,不猜测下限,只有其他两条明确条件同时满足时自动应用该档,其余疑似大件转人工确认。报价不把提取时效称为签收时效。金额仍读取激活版本,不把私有费率写入源码。
|
||||
|
||||
订单列表使用与逐单查询相同的服务端租户交集,每次最多展示20票并保护其会话历史;未知筛选条件不默认为全部订单。改址/取消尚无业务写入接口,只明确引导人工,不声称修改成功。输入明确的转人工指令复用现有申请接口,失败保留草稿,不增加SSE事件类型。
|
||||
|
||||
`quote_allocations.py` 只识别明确分配给各仓的重量、箱数及箱规,逐仓计费及计算每箱最低重量;仅给总重和多个仓码时保留比较语义,不擅自分配重量。`quote_context.py` 在当前会话的有效上下文内按时间顺序应用更正,保留已算出的总重:重量纠正会清除旧分箱明细,单改箱数时统一箱重可沿用,混合箱重需重新确认;“总重不变”优先于旧每箱重量,新尺寸不沿用旧体积。按方报价不把按公斤的材质费直接乘CBM,金额未确定时明确单列待核算项。
|
||||
|
||||
`shipping_faq.py` 从激活版本回答交仓、标签、报关资料及查验费用问题;具体船期和计划发货日期需人工核对,不使用旧表日期承诺必达。`order_explanations.py` 只解释授权订单的业务状态和实际节点,不把预计节点当实际位置,不推断逐箱签收或亚马逊上架。文字事实回复与订单卡片同样绑定客户及范围;催单或拦截不声称已提交。本轮不扩展售后理赔规则。
|
||||
|
||||
`customer_faq.py` 在报价分流前处理下单、短信查单、开票、导出及附件读取等能力说明,不生成业务操作成功的假回复。美国常见费用/毛净重/议价/总价追问由当前价表直接回答;`quote_scope.py` 将尚未匹配的美国咨询保留为明确的核对回复,不送入旧欧洲/英国知识库。明确切换其他国家时仍走该地区原有分流,理赔规则未扩展。
|
||||
|
||||
`quote_edits.py` 先移除被明确否定的仓码或交货仓,再解析替换条件。共享尺寸解析支持英寸转换和口语长宽高,“一个箱子”可形成单箱条件;总计立方米不作为尺寸单位“米”。
|
||||
|
||||
`order_listing.py` 负责数量摘要、查看全部和翻页。数量摘要最多5票,直接翻页继续每页5票;明确列出订单或“查看全部”按每页20票。`chat_history.order_list_state` 保存筛选、页码、页大小和成功回复的消息ID,绑定客户与范围;只保存仍为最新消息的状态,迟到回复不能覆盖新话题。中间插问同条件总数保留列表页码,改筛选重置,新话题停止沿用。每次重新查询授权数据,不缓存数量;计数及分页来自同一只读快照,无有效上下文先引导查询,页码有界。
|
||||
|
||||
`order_test_data.exception_reason` 是人工明确登记、允许客户查看的物流异常原因;非空表示该票有异常标记,空值表示未标记,不推断货物正常。取消、审核驳回和无轨迹均不自动标为物流异常。可直接维护此字段,不增加管理页面;旧快照未提供该字段时即使显式覆盖也保留已有原因,显式提供空字符串才清除。后续MCP适配返回相同事实即可。
|
||||
|
||||
共享尺寸解析将单位与长宽高绑定,支持每边单位和混合单位,不受“12英寸显示器”等商品描述影响。报价沿当前会话回溯到最近话题边界,不按10轮截断;其他国家、新一票及订单话题隔离不变。“铁铝部分还是10KG”等口语仅在先前已明确计费重时更新该基数,既不覆盖整票总重,也不把未确认毛重直接当计费重。
|
||||
|
||||
已确认海派计费重保留原小数,不向上取整,每箱最低12KG仍生效。原实重小数原样展示;无限小数的材积结果以“约”展示有限位数,金额计算仍使用原Decimal精度,不把显示近似当作计费进位。
|
||||
|
||||
铁铝附加费只按铁铝货物计费重计算。`quote_material.py` 区分整票铁铝、部分铁铝与未明确材质的金属,并将明确的“铁铝部分计费重”从整票毛重解析中分离。部分货物未提供计费重时不按整票加费;提供明确基数后可将该项人民币费用加到公斤或按方运费中。更改整票重量、箱数或箱规后清除旧的部分计费重,防止沿用过期基数。未明确金属是否属于铁铝时先核实材质,不把所有金属都认作铁铝。
|
||||
|
||||
先按 README 安装项目依赖。Windows 使用 `.\.venv\Scripts\python.exe -m pytest -v` 或同解释器的 `-m unittest discover -s tests -v`;Linux/macOS 使用 `.venv/bin/python`。业务测试依赖 Flask,不能用未安装依赖的全局 Python 运行整套测试。模型请求全部模拟,不代表真实 DeepSeek 联调。
|
||||
|
||||
路径、函数或资产移动后同步更新根 `AGENTS.md`、本文、知识资料和 README 目录树。仅改导航时检查路径、符号、命令;改业务时补充相关成功和失败分支,前端改动检查实际页面。
|
||||
@@ -0,0 +1,154 @@
|
||||
# Linux 单机手动部署参考
|
||||
|
||||
现行灰度环境使用 [Jenkins 部署流程](deployment.md)。本页保留独立主机的安装方法,不用于覆盖已有灰度服务。
|
||||
|
||||
适用场景:Ubuntu / Debian、已有域名。使用系统 Python 3.10+,无需前端构建或 GPU。入口为 HTTPS → Nginx(客户白名单公开,客服及其他路径需密码)→ 本机 Waitress → Flask / SQLite。
|
||||
|
||||
游客历史、人工会话和附件已按访客归属隔离;客户账号登录和订单关联尚未接入,匿名不能查询真实订单。必须沿用示例中的精确公开白名单,保护其余全部路径,包括客服、搜索、导出和原人工接口,不能只保护 `/admin`。上游端口不可对公网开放。
|
||||
|
||||
## 1. 域名与网络
|
||||
|
||||
- 将验收子域名的 A 记录解析到服务器公网 IPv4;只有正确配置服务器 IPv6 后才添加 AAAA。
|
||||
- 服务器安全组和防火墙允许 TCP 80、443,保留实际使用的 SSH 管理端口。不要开放应用端口 5000。
|
||||
- 服务器需要能够出站访问 Python 包源及 `https://api.deepseek.com`。
|
||||
- 下文的 `chat.example.com` 均需替换成真实域名,包括 Nginx 配置内的证书路径。
|
||||
|
||||
## 2. 上传源码并安装依赖
|
||||
|
||||
首次部署使用 `baiyue-logistics-chat-linux-acceptance.tar.gz`。部署包包含本次工作区的部署文件和缺表修复,不含 `.git`、`.env`、虚拟环境、日志、数据库或本机附件。之前 Git 推送因认证失败未完成;若改用 Git 拉取,须先确认远端版本包含这些变更。
|
||||
|
||||
将部署包上传到服务器 `/tmp/`,以下命令均在服务器执行。首次部署假设 `/opt/baiyue-logistics-chat` 尚不存在;已有安装请使用文末更新流程。
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y python3 python3-venv python3-pip nginx apache2-utils certbot
|
||||
python3 --version
|
||||
sudo tar --no-same-owner -xzf /tmp/baiyue-logistics-chat-linux-acceptance.tar.gz -C /opt
|
||||
sudo adduser --system --group --home /nonexistent --no-create-home baiyue
|
||||
sudo chown root:baiyue /opt/baiyue-logistics-chat
|
||||
sudo chmod 750 /opt/baiyue-logistics-chat
|
||||
cd /opt/baiyue-logistics-chat
|
||||
sudo python3 -m venv .venv
|
||||
sudo .venv/bin/python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
若系统已有专用 `baiyue` 用户,跳过 `adduser`。代码与虚拟环境归 root 所有;服务数据另存到 `/var/lib/`,无需让 Web 进程修改源码。
|
||||
|
||||
## 3. 配置 DS 密钥
|
||||
|
||||
仅首次复制配置,已有 `.env` 时跳过复制;不要把本机配置打进部署包。
|
||||
|
||||
```bash
|
||||
sudo install -o root -g baiyue -m 640 .env.example .env
|
||||
sudoedit /opt/baiyue-logistics-chat/.env
|
||||
```
|
||||
|
||||
在编辑器内填写 `DEEPSEEK_API_KEY=你的密钥`,无需加 `export`,不要在终端命令或日志中输出密钥。文件由应用工厂读取;本方案的 systemd 单元不再注入同名环境变量。更换密钥后重启服务。
|
||||
|
||||
## 4. 启动应用服务
|
||||
|
||||
```bash
|
||||
sudo install -m 644 deploy/baiyue-logistics-chat.service /etc/systemd/system/baiyue-logistics-chat.service
|
||||
sudo systemd-analyze verify /etc/systemd/system/baiyue-logistics-chat.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now baiyue-logistics-chat
|
||||
sudo systemctl status baiyue-logistics-chat --no-pager
|
||||
curl -I http://127.0.0.1:5000/
|
||||
```
|
||||
|
||||
本机检查应返回 HTTP 200。服务使用独立系统用户、单进程 8 线程并仅监听 `127.0.0.1:5000`,不走 `am.py` 的 Flask 开发服务器回退。单进程保留当前应用的内存输入状态和限流行为;暂不配置多进程或多个副本。
|
||||
|
||||
systemd 自动创建并授权以下目录,重启与更新源码不会替换其中的数据:
|
||||
|
||||
| 内容 | 服务器路径 |
|
||||
|---|---|
|
||||
| SQLite | `/var/lib/baiyue-logistics-chat/history.db` |
|
||||
| 上传附件 | `/var/lib/baiyue-logistics-chat/uploads/` |
|
||||
| 启动备份 | `/var/lib/baiyue-logistics-chat/backups/` |
|
||||
| 应用日志 | `/var/log/baiyue-logistics-chat/app.log` |
|
||||
| 密钥配置 | `/opt/baiyue-logistics-chat/.env` |
|
||||
|
||||
首次启动创建八张业务表,不插入演示数据、默认客服账号或密码。已有表和记录保持兼容。应用当前仍会在启动时清理超过 7 天的上传文件,并执行启动备份;启动备份不能替代定时备份。
|
||||
|
||||
## 5. 申请 HTTPS 证书
|
||||
|
||||
先安装只提供证书验证路径的 HTTP 配置,此时不会转发到应用:
|
||||
|
||||
```bash
|
||||
sudo install -d -m 755 /var/www/letsencrypt
|
||||
sudo install -m 644 deploy/nginx-bootstrap.conf.example /etc/nginx/sites-available/baiyue-logistics-chat
|
||||
sudoedit /etc/nginx/sites-available/baiyue-logistics-chat
|
||||
sudo ln -s /etc/nginx/sites-available/baiyue-logistics-chat /etc/nginx/sites-enabled/baiyue-logistics-chat
|
||||
sudo nginx -t
|
||||
sudo systemctl enable --now nginx
|
||||
sudo systemctl reload nginx
|
||||
sudo certbot certonly --webroot -w /var/www/letsencrypt --cert-name chat.example.com -d chat.example.com
|
||||
```
|
||||
|
||||
编辑配置时替换域名,申请证书时也替换两处域名;按 Certbot 提示填写邮箱和确认条款。若申请失败,先核对 DNS 和外网 80 端口,保留引导配置排查,暂不安装下一步需要证书的 TLS 配置。
|
||||
|
||||
## 6. 设置访问密码并开放 HTTPS 验收
|
||||
|
||||
创建验收账号 `preview`,密码由命令交互输入,不写入项目配置。`-c` 仅首次创建密码文件时使用;以后修改密码应去掉 `-c`。
|
||||
|
||||
```bash
|
||||
sudo htpasswd -cB /etc/nginx/.baiyue-preview.htpasswd preview
|
||||
sudo chown root:www-data /etc/nginx/.baiyue-preview.htpasswd
|
||||
sudo chmod 640 /etc/nginx/.baiyue-preview.htpasswd
|
||||
sudo install -m 644 deploy/nginx.conf.example /etc/nginx/sites-available/baiyue-logistics-chat
|
||||
sudoedit /etc/nginx/sites-available/baiyue-logistics-chat
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
替换 TLS 配置中所有域名及证书路径;`nginx -t` 失败时先修正,不要继续 reload。模板的访问密码覆盖页面、附件、静态资源和全部 API,后端 5000 端口继续只对本机开放。不能只在导航层隐藏后台页面。
|
||||
|
||||
Nginx 已关闭代理响应缓冲及压缩,并将等待上游数据的超时设为 300 秒,供 AI SSE 分段输出;上传入口允许 12 MiB 请求体以容纳应用 10 MiB 文件上限外的表单开销。
|
||||
|
||||
## 7. 验收和证书续期
|
||||
|
||||
```bash
|
||||
curl -I https://chat.example.com/
|
||||
curl -I https://chat.example.com/api/export_chat
|
||||
curl -u preview -I https://chat.example.com/
|
||||
```
|
||||
|
||||
前两条应返回 401,证明页面和数据接口都受保护;第三条交互输入访问密码后应返回 200。浏览器也会先弹出访问密码:
|
||||
|
||||
- 客户页:`https://chat.example.com/`,发送消息检查 DS 实际回复及流式显示。
|
||||
- 验收工作台:`https://chat.example.com/admin/dashboard`,从客户页申请人工,再检查接待和双向消息。
|
||||
- 当前未预置应用内客服登录账号;Nginx 的 `preview` 是客服及受保护接口的访问账号,不是 `/admin` 页里的客服账号,客户首页无需此账号。
|
||||
|
||||
安装证书续期后的 Nginx 重载钩子,并检查续期定时器:
|
||||
|
||||
```bash
|
||||
sudo install -d -m 755 /etc/letsencrypt/renewal-hooks/deploy
|
||||
sudo install -m 755 deploy/reload-nginx.sh /etc/letsencrypt/renewal-hooks/deploy/baiyue-reload-nginx
|
||||
sudo systemctl enable --now certbot.timer
|
||||
sudo certbot renew --dry-run --run-deploy-hooks
|
||||
```
|
||||
|
||||
最终配置保留 HTTP 的 `/.well-known/acme-challenge/` 路径,供 webroot 续期使用;其他 HTTP 请求跳转到 HTTPS。不要删除验证路径或只对自己的 IP 开放证书验证端口,否则后续续期会失败。
|
||||
|
||||
## 维护、更新和问题定位
|
||||
|
||||
```bash
|
||||
sudo journalctl -u baiyue-logistics-chat -n 100 --no-pager
|
||||
sudo tail -n 100 /var/log/baiyue-logistics-chat/app.log
|
||||
sudo systemctl restart baiyue-logistics-chat
|
||||
sudo nginx -t
|
||||
```
|
||||
|
||||
- **502**:先查应用状态、journal 日志、依赖安装及 5000 端口本机检查。
|
||||
- **一直弹访问密码**:检查 Nginx 密码文件和 `www-data` 读权限;不要用应用内客服密码替代验收密码。
|
||||
- **AI 无回复**:确认服务器 `.env` 已填写并重启,检查服务器能否访问 DS;本机验收成功不代表服务器网络已验证。
|
||||
- **输出集中到最后**:检查实际生效的 Nginx 配置和 CDN 是否重新启用了缓冲。
|
||||
- **429**:目前反向代理后的请求共享应用默认限流桶,适合单人验收;多人开放前需正确配置可信代理和业务限流。
|
||||
|
||||
更新前停止应用并备份 `/var/lib/baiyue-logistics-chat/`,另行保护 `.env`。源码更新只替换项目文件,不复制本机数据库或 `work/`,不覆盖服务器 `.env`;按需重新安装依赖后重启。若修改 systemd 单元,重新安装单元并执行 `daemon-reload`;若修改 Nginx,先检查再 reload。回退源码时仍保留数据副本,本项目尚无数据库降级迁移工具。
|
||||
|
||||
本地已通过应用工厂和全新数据库回归;目标服务器的 `systemd-analyze verify`、`nginx -t`、DNS、证书签发及真实 DS 请求仍需在部署时验证。
|
||||
|
||||
## 参考
|
||||
|
||||
工厂调用与监听参数依据 [Waitress 官方文档](https://docs.pylonsproject.org/projects/waitress/en/stable/runner.html)。流式转发配置依据 [Nginx 代理模块](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering),客服后台密码依据 [Nginx Basic Auth 模块](https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html)。证书和续期使用 [Certbot webroot](https://eff-certbot.readthedocs.io/en/stable/using.html#webroot);服务目录与只读保护依据 [systemd.exec](https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html)。
|
||||
@@ -0,0 +1,115 @@
|
||||
# Jenkins 灰度部署
|
||||
|
||||
现有灰度环境使用 `Jenkinsfile`、`Dockerfile` 和 `deploy/` 发布独立物流聊天服务。流水线构建并测试镜像,通过严格校验主机指纹的 SSH 发送到专用 Docker Compose 服务,Nginx 提供 HTTPS;客户聊天免登录,客服和其他非白名单路径使用访问密码。
|
||||
|
||||
应用使用单个 Waitress 进程、8 个线程和 UID 10001,宿主机端口仅绑定回环地址。运行密钥、聊天数据、附件和证书不进入镜像。游客历史和附件在应用内按归属隔离;客服仍依赖 Nginx 密码保护,不能裸露上游端口。客户登录独立验证账号及订单范围,匿名查单不会读取订单数据。
|
||||
|
||||
限流和登录失败次数按客户端 IP 计算。Nginx 必须用 `$remote_addr` 覆盖 `X-Forwarded-For`;Waitress 只信任这一项代理头和最后一跳地址,不接受代理头里的 Host、协议或更早的地址。容器镜像在仅由本机 Nginx 接入、宿主端口保持回环绑定的前提下使用 `--trusted-proxy=*`,以兼容 Docker 网关地址;systemd 入口只信任 `127.0.0.1`。直接运行 `am.py` 不接受客户端自报的代理 IP。代理规则参见 [Waitress 文档](https://docs.pylonsproject.org/projects/waitress/en/stable/reverse-proxy.html)。
|
||||
|
||||
容器时区设为 `Asia/Shanghai`,营业时间与聊天时间按中国时间计算。
|
||||
|
||||
## Jenkins 任务
|
||||
|
||||
任务名为 `baiyue-logistics-chat-gray`。定义选择 Pipeline script from SCM,本项目 Git 地址为仓库,分支字段为 `${SOURCE_REF}`,脚本路径为 `Jenkinsfile`。公开仓库可匿名读取;转为私有后配置只读 SCM 凭据。
|
||||
|
||||
`java-builder` 标签代理须有 Docker、Bash、Python 3、Node.js 18+、OpenSSL、SSH,并能下载所选 Python 基础镜像和 PyPI 依赖。标签不表示固定物理节点。
|
||||
|
||||
以下参数由私有灰度配置提供,实际地址和凭据值不写入源码:
|
||||
|
||||
| 参数 | 含义 |
|
||||
|---|---|
|
||||
| `ENVIRONMENT` | 单选 `gray`,流水线拒绝其他值 |
|
||||
| `SOURCE_REF` | 本次发布的不可变标签或提交,也可明确选择开发分支 |
|
||||
| `PYTHON_BASE_IMAGE` | 已验证的官方 Python 3.12 基础镜像 |
|
||||
| `DEBIAN_MIRROR` | 默认 `https://deb.debian.org`;国内可选 `https://mirrors.tuna.tsinghua.edu.cn`,保留 Debian 签名校验 |
|
||||
| `PUBLIC_ORIGIN` | 独立 HTTPS 域名,不带子路径 |
|
||||
| `HOST_PORT` | 已确认空闲的宿主机回环端口,如 `29013` |
|
||||
| `GRAY_DEPLOY_DIR` | 专用目录,末级必须为 `gray-logistics-chat` |
|
||||
| `GRAY_PROXY_CONF_DIR` | 宿主机 Nginx 实际加载的站点目录 |
|
||||
| `GRAY_TLS_CERT_FILE` / `GRAY_TLS_KEY_FILE` | 本服务独立证书和私钥路径 |
|
||||
| `SSH_CREDENTIAL_ID` | SSH 用户与私钥凭据引用 |
|
||||
| `SSH_HOST_CREDENTIAL_ID` | SSH 目标的 Secret text 引用 |
|
||||
| `SSH_KNOWN_HOSTS_CREDENTIAL_ID` | 已核实的 known_hosts 文件引用 |
|
||||
| `DEEPSEEK_CREDENTIAL_ID` | 本服务模型密钥的 Secret text 引用 |
|
||||
| `PREVIEW_AUTH_CREDENTIAL_ID` | 专用验收用户名和密码引用 |
|
||||
| `ASR_PROVIDER` | `baidu` 启用语音;空值关闭 |
|
||||
| `BAIDU_ASR_API_KEY_CREDENTIAL_ID` / `BAIDU_ASR_SECRET_KEY_CREDENTIAL_ID` | 本服务百度语音专用 Secret text 引用 |
|
||||
| `IMPORT_ORDER_SAMPLES` | 默认关闭;明确需要补样本时才启用 |
|
||||
| `IMPORT_QUOTE_DATA` | 默认关闭;本次明确导入通用美国报价才启用 |
|
||||
| `QUOTE_SNAPSHOT_CREDENTIAL_ID` | 默认空;本次私有报价快照的临时 Secret file 引用 |
|
||||
| `ORDER_SNAPSHOT_CREDENTIAL_ID` / `TRACKING_SNAPSHOT_CREDENTIAL_ID` | 本次导入的临时 Secret file 引用 |
|
||||
|
||||
运行密钥和验收账号保存在私有灰度配置与 Jenkins 凭据库,供后续发布持续复用;轮换时同步更新。不要将密钥放在构建参数、Git URL、镜像 ARG、日志或示例文件中。
|
||||
|
||||
语音运行配置只注入 `ASR_PROVIDER`、`BAIDU_ASR_API_KEY`、`BAIDU_ASR_SECRET_KEY`,与 DS 密钥一起写入权限 600 的 `runtime.env`。容器使用镜像内的 FFmpeg,不传本机 `FFMPEG_BIN`,也不使用 OCR 凭据。缺少任一百度凭据时拒绝生成发布配置。
|
||||
|
||||
私有订单样本不进入 Git、构建上下文或镜像。可在明确授权后临时上传为 Jenkins Secret file 并启用 `IMPORT_ORDER_SAMPLES`;发布脚本核验快照校验和与实际运行提交,在线备份聊天 SQLite,再调用 `scripts/import_order_test_data.py` 默认导入订单、以 `--tracking-only` 补充轨迹。两步均不使用 `--replace`,保留手工订单字段和已有非空轨迹。临时文件在导入后清除;验收后移除临时 Jenkins 文件凭据并关闭导入开关。此操作只访问聊天服务自己的 SQLite。
|
||||
|
||||
## 发布步骤
|
||||
|
||||
报价导入使用 `IMPORT_QUOTE_DATA` 与临时 Secret file,调用 `deploy/import-gray-quotes.sh`:核对快照 SHA 和运行提交、备份 SQLite,再通过生产镜像中的 `scripts/import_quote_data.py --activate` 事务导入。该开关默认关闭,后续普通发布保留已导入数据;导入不修改订单、轨迹或客户范围。原始 Excel 与快照不进入 Git、Docker 上下文或镜像;导入结束清除临时文件,验收后移除临时 Jenkins 文件凭据。新增参数只追加,不改变既有构建参数及其默认值。
|
||||
|
||||
1. 完成检查并提交代码,创建 `gray-chat-YYYYMMDD-<commit12>` 一类不可变发布标签。不要重写已有标签或强推覆盖远端分支;分支有其他更新时先明确发布基线。
|
||||
2. 推送标签,在任务 `SOURCE_REF` 选择该标签。Jenkins 按此引用加载流水线并检出代码,镜像记录完整提交 SHA。
|
||||
3. 流水线检查 Bash 语法,运行 Node 回归,再构建 `test` 目标执行 Python 回归;通过后构建 `production` 应用镜像及 `certbot` 运维镜像。
|
||||
4. 构建完成后才绑定运行凭据。发布脚本校验路径、域名和源提交,生成私有配置并发送镜像及发布文件。服务器验证镜像归档的 SHA-256 后加载,记录目标主机的镜像 ID。
|
||||
5. 首次签发域名证书,等待应用健康,再安装本服务的 Nginx 配置。已有业务的容器和站点配置不参与本次发布。
|
||||
6. Jenkins 使用验收账号验证公网 HTTPS `/healthz`;之后在浏览器验证 AI 流式回复、上传、转人工和工作台。
|
||||
|
||||
应用镜像必须选择 `production` 构建目标;`certbot` 仅用于证书运维。每个构建生成独立镜像标签,不依赖 `latest`。Docker 的 classic 与 containerd 镜像存储可能返回不同 ID;跨主机以归档校验和与源提交标签核验传输,激活前再与 `loaded-image-ids.env` 中的目标 ID 比较,拒绝加载后被替换的镜像。归档加载后删除,构建机 ID 保留在 `release.env` 供追溯。
|
||||
|
||||
## 数据与失败回退
|
||||
|
||||
`GRAY_DEPLOY_DIR` 如 `/data/services/gray-logistics-chat`,包含:
|
||||
|
||||
| 路径 | 内容 |
|
||||
|---|---|
|
||||
| `.project` | 服务所有权标记,拒绝复用未知目录 |
|
||||
| `data/` | SQLite、附件和备份,跨发布保留 |
|
||||
| `logs/` | 应用日志 |
|
||||
| `releases/<commit12>-b<build>/` | Compose、镜像坐标、私有运行配置和站点候选 |
|
||||
| `current-release` | 已通过应用及入口检查的发布目录 |
|
||||
| `tls/` | 独立 ACME 账号、证书、日志和续期脚本 |
|
||||
|
||||
模型密钥写入权限为 600 的 `runtime.env`,由 Compose 注入进程。验收密码只在 Jenkins 生成 Nginx 哈希,服务器保存哈希文件。
|
||||
|
||||
密码哈希位于独立的 `/var/lib/baiyue-logistics-chat-gray-proxy/access.htpasswd`,目录 755、文件 644,供 Nginx 工作进程读取;不放在可能只有 root 可访问的宝塔站点配置目录,也不放明文密码。该目录有本服务所有权标记,不复用未知目录。
|
||||
|
||||
更新前执行 SQLite 在线备份。应用启动或 Nginx 检查失败时,仅恢复本服务之前的 Compose 和站点配置,保留数据;不自动用旧库覆盖新记录。失败发布目录保留供定位,数据库降级及删除数据需另行处理。
|
||||
|
||||
新环境自动创建业务表,不创建默认客服账号或演示数据。专用访问密码用于客服工作台及受保护接口;Nginx 账号不是应用内客服账号。客户首页无需密码,客户端先自动建立访客会话,再访问自己的历史。
|
||||
|
||||
## HTTPS 及续期
|
||||
|
||||
域名须解析到已核实的灰度入口,公网 80、443 端口可达。其他域名的证书不能直接用于新域名。
|
||||
|
||||
独立 Certbot 镜像通过 HTTP-01 webroot 签发证书;首次只新增本服务的 HTTP 验证站点,业务接口尚不公开。验证目录为 `/var/lib/baiyue-logistics-chat-acme`,最终配置持续保留该 HTTP 路径。
|
||||
|
||||
证书参数须指向:
|
||||
|
||||
```text
|
||||
<GRAY_DEPLOY_DIR>/tls/config/live/<域名>/fullchain.pem
|
||||
<GRAY_DEPLOY_DIR>/tls/config/live/<域名>/privkey.pem
|
||||
```
|
||||
|
||||
ACME 账号和私钥仅保存在服务器私有目录,当前使用无邮箱账号。专用 `baiyue-logistics-chat-tls-renew.timer` 每日检查本服务证书,内容变化后检查并重载 Nginx,不接管其他证书任务。
|
||||
|
||||
## 排查
|
||||
|
||||
先从 Jenkins 构建记录核对阶段及源 SHA。服务器检查:
|
||||
|
||||
```bash
|
||||
docker ps --filter name=baiyue-logistics-chat-gray
|
||||
docker logs --tail 100 baiyue-logistics-chat-gray
|
||||
systemctl status baiyue-logistics-chat-tls-renew.timer --no-pager
|
||||
nginx -t
|
||||
```
|
||||
|
||||
- 构建失败:核对镜像和 PyPI 网络,不跳过测试发布。
|
||||
- SSH 失败:核对受管凭据和 known_hosts,不禁用指纹检查。
|
||||
- 证书失败:核对 DNS 和 HTTP 验证路径,保留本服务的验证站点与私有 ACME 状态。
|
||||
- 容器不健康:检查独立目录的 UID 10001 权限、日志和 `/healthz`;健康检查不计入业务限流。
|
||||
- 客户首页应匿名返回 200,不出现密码弹窗;客服后台、全站搜索和导出匿名返回 401。客户历史 API 在未建立访客会话时由应用返回 JSON 401,自动建立 `/api/visitor/session` 后应返回当前访客的记录。发布激活脚本同时检查这些边界,不能只删除原有密码配置。
|
||||
- 流式显示延迟:检查实际 Nginx 或 CDN 是否重新启用了响应缓冲。
|
||||
|
||||
独立主机安装另见 [Linux 手动参考](deployment-linux.md)。凭据与 API 依据 [Jenkins 官方文档](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/) 和 [Remote API](https://www.jenkins.io/doc/book/using/remote-access-api/),证书验证与续期依据 [Certbot 文档](https://eff-certbot.readthedocs.io/en/stable/using.html#webroot)。
|
||||
@@ -1,8 +1,8 @@
|
||||
# 柏悦智能物流客服系统 · 知识资料
|
||||
|
||||
> 本文件由 `am.py` 的 `knowledge_list` 自动导出,供评审与知识维护使用。
|
||||
> 本文件整理了 [logistics_chat/knowledge.py](../logistics_chat/knowledge.py) 中的 `knowledge_list`,供评审与知识维护使用。
|
||||
> 数据来源:炜易达 VIP 10月15日9点执行报价表。
|
||||
> 修改知识内容请直接编辑 `am.py` 中的 `knowledge_list`,改完后重新导出本文件。
|
||||
> 修改知识内容请编辑 `logistics_chat/knowledge.py` 中的 `knowledge_list`,并同步更新本文件;程序不会直接读取此文档。
|
||||
|
||||
---
|
||||
|
||||
@@ -34,11 +34,11 @@
|
||||
|
||||
### 人工客服、人工、客服、转人工、在线吗、上班、工作时间、营业时间、几点、周六、周日、星期六、星期日、星期天、礼拜、周末、双休、节假日、放假、休息
|
||||
|
||||
人工客服在线时间:**周一至周五 9:00—18:00**。周六、周日及法定节假日人工客服不上班。非工作时间可以先留言或提交需求,业务员会在下一个工作日回复您。
|
||||
人工客服在线时间:**每天北京时间 8:00—22:00**,周末及节假日同样适用。非工作时间可以先留言或提交需求,客服会在工作时间尽快回复您。
|
||||
|
||||
### 电话、联系方式、怎么联系、联系你们、微信
|
||||
|
||||
可以联系您的专属业务员,或在人工客服在线时间(周一至周五 9:00—18:00)通过在线客服咨询。建议提前准备好运单号、货物信息(品名、重量、尺寸、目的国),方便快速处理。
|
||||
可以联系您的专属业务员,或在人工客服在线时间(每天北京时间 8:00—22:00)通过在线客服咨询。建议提前准备好入仓码、货物信息(品名、重量、尺寸、目的国),方便快速处理。
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# 人工客服接口请求示例
|
||||
|
||||
这些 JSON 文件用于本地手动调试。示例中的 `conv_id`、`sid` 均须替换成接口实际返回的 ID。
|
||||
|
||||
| 文件 | 方法与接口 | 用途 |
|
||||
|---|---|---|
|
||||
| `human_request.json` | POST `/api/human/request` | 为已有聊天会话申请人工客服 |
|
||||
| `human_accept.json` | POST `/api/human/accept` | 客服接待排队中的人工会话 |
|
||||
| `human_send.json` | POST `/api/human/send` | 客服向已接待会话发送消息 |
|
||||
| `human_request_invalid.json` | POST `/api/human/request` | `conv_id=0` 的无效请求示例,预期 HTTP 400 |
|
||||
|
||||
在项目根目录执行以下 PowerShell 命令,仅申请人工会话:
|
||||
|
||||
```powershell
|
||||
Invoke-RestMethod -Uri 'http://127.0.0.1:5000/api/human/request' `
|
||||
-Method Post -ContentType 'application/json; charset=utf-8' `
|
||||
-InFile 'examples/requests/human_request.json'
|
||||
```
|
||||
|
||||
先通过 POST `/api/new_chat` 获取 `conv_id`,再申请人工客服取得 `session_id`,后续请求中的 `sid` 使用该值。接口当前没有完整登录鉴权,请仅在受控的开发环境调试。
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"sid": 1
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"conv_id": 1
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"conv_id": 0
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"sid": 1,
|
||||
"side": "agent",
|
||||
"content": "您好,请问需要咨询什么?"
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import sqlite3
|
||||
c = sqlite3.connect('history.db')
|
||||
for u in ['123','456','789']:
|
||||
c.execute("INSERT OR REPLACE INTO agents(username,password,name) VALUES(?,?,?)", (u,'123',u))
|
||||
c.commit()
|
||||
print("ok")
|
||||
@@ -1 +0,0 @@
|
||||
{"conv_id":295}
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Application factory; package imports do not initialize storage or networking."""
|
||||
|
||||
|
||||
def create_app(config=None):
|
||||
from collections import defaultdict
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from .config import ROOT_DIR, default_config
|
||||
from . import customer_service, db, file_service, hooks, visitor_service
|
||||
from .routes import register_routes
|
||||
from .routes.speech import MemoryAudioRequest
|
||||
|
||||
app = Flask(__name__, template_folder=str(ROOT_DIR/'templates'),
|
||||
static_folder=str(ROOT_DIR/'static'))
|
||||
app.request_class = MemoryAudioRequest
|
||||
app.config.update(default_config())
|
||||
if config:
|
||||
app.config.update(config)
|
||||
app.extensions['human_typing'] = {}
|
||||
app.extensions['rate_hits'] = defaultdict(list)
|
||||
app.extensions['customer_login_attempts'] = {}
|
||||
app.extensions['customer_login_lock'] = Lock()
|
||||
app.before_request(hooks.rate_limit)
|
||||
app.before_request(visitor_service.attach_visitor)
|
||||
app.before_request(customer_service.attach_customer)
|
||||
app.after_request(hooks.no_cache_html)
|
||||
app.teardown_appcontext(db.close_connections)
|
||||
register_routes(app)
|
||||
|
||||
if app.config['INITIALIZE_RUNTIME']:
|
||||
if not app.testing:
|
||||
from flask.logging import default_handler
|
||||
log_directory = Path(app.config['LOG_DIR'])
|
||||
log_directory.mkdir(parents=True, exist_ok=True)
|
||||
log_path = str((log_directory/'app.log').resolve())
|
||||
app.logger = logging.getLogger('logistics_chat.' + log_path)
|
||||
app.logger.setLevel(logging.INFO)
|
||||
if default_handler not in app.logger.handlers:
|
||||
app.logger.addHandler(default_handler)
|
||||
if not any(getattr(handler, 'baseFilename', None) == log_path for handler in app.logger.handlers):
|
||||
handler = logging.FileHandler(log_path, encoding='utf-8')
|
||||
handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
|
||||
app.logger.addHandler(handler)
|
||||
with app.app_context():
|
||||
db.init_db()
|
||||
db.backup_db()
|
||||
file_service.cleanup_uploads()
|
||||
return app
|
||||
@@ -0,0 +1,69 @@
|
||||
"""DeepSeek HTTP calls; callers retain their streaming/compression/followup deadlines."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import requests
|
||||
from requests.exceptions import RequestException, Timeout
|
||||
|
||||
from .config import get_setting
|
||||
|
||||
|
||||
def post_completion(body, *, timeout, stream=False):
|
||||
return requests.post(
|
||||
get_setting('MODEL_URL'),
|
||||
headers={'Authorization': f"Bearer {get_setting('DEEPSEEK_API_KEY')}",
|
||||
'Content-Type': 'application/json'},
|
||||
json=body, stream=stream, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
|
||||
EN_COMPRESS_RULE = '原文是英文,压缩后的结果必须仍然使用英文(English),不得翻译成中文。'
|
||||
|
||||
|
||||
def has_chinese(t):
|
||||
return any(('一' <= ch <= '龥' for ch in t))
|
||||
|
||||
|
||||
def compress_answer(text, limit=get_setting('MAX_ANSWER_CHARS')):
|
||||
"""回答超长时,让模型压缩到规定字数内;失败则原样返回"""
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
r = None
|
||||
try:
|
||||
body = {'model': get_setting('MODEL_NAME'), 'messages': [{'role': 'system', 'content': (EN_COMPRESS_RULE if has_chinese(text) is False else '') + f'你是文字精简助手。把用户给的内容压缩到 {limit} 字以内(必须严格满足,超出即为不合格),必须保留所有数字、金额、时效和渠道名称,删除重复表述、客套话和次要说明,结构保持不变。'}, {'role': 'user', 'content': text}], 'stream': False, 'max_tokens': 800}
|
||||
r = post_completion(body, timeout=(5, 30))
|
||||
if r.status_code == 200:
|
||||
short = r.json()['choices'][0]['message']['content'].strip()
|
||||
print(f'[压缩] {len(text)} 字 -> {len(short)} 字')
|
||||
return short
|
||||
print(f'[压缩失败] 状态码 {r.status_code}')
|
||||
except Exception as e:
|
||||
print(f'[压缩异常] {e}')
|
||||
finally:
|
||||
if r is not None:
|
||||
r.close()
|
||||
return text
|
||||
|
||||
|
||||
def gen_followups(user_msg, answer_text):
|
||||
"""根据本轮问答,生成 3 个客户可能接着问的问题(失败返回空列表,不影响主流程)"""
|
||||
if not get_setting('DEEPSEEK_API_KEY'):
|
||||
return []
|
||||
r = None
|
||||
try:
|
||||
body = {'model': get_setting('MODEL_NAME'), 'messages': [{'role': 'system', 'content': '你是物流客服助手。根据用户问题和你的回答,生成3个客户最可能接着问的简短问题(每个不超过20字),只输出JSON字符串数组,不要任何解释。'}, {'role': 'user', 'content': f'用户问:{user_msg}\n你的回答:{answer_text[:500]}\n\n请生成3个追问:'}], 'stream': False, 'max_tokens': 200}
|
||||
r = post_completion(body, timeout=(5, 15))
|
||||
if r.status_code != 200:
|
||||
return []
|
||||
text = r.json()['choices'][0]['message']['content'].strip()
|
||||
m = re.search('\\[.*\\]', text, re.S)
|
||||
if m:
|
||||
arr = json.loads(m.group(0))
|
||||
return [str(x).strip() for x in arr if str(x).strip()][:3]
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if r is not None:
|
||||
r.close()
|
||||
return []
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Feedback, reporting, login, orders and offline tickets."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from .db import connect, now_str
|
||||
from .tracking import card_to_text
|
||||
|
||||
|
||||
def feedback(data):
|
||||
"""收集 👍/👎 反馈,存到 feedback 表"""
|
||||
if not isinstance(data, dict):
|
||||
return {'ok': False, 'error': '评价格式无效。'}, 400
|
||||
raw_vote = data.get('vote')
|
||||
votes = {'up': 1, 'down': -1, '1': 1, '-1': -1}
|
||||
vote = votes.get(raw_vote) if isinstance(raw_vote, str) else raw_vote
|
||||
question, answer = data.get('question', ''), data.get('answer', '')
|
||||
if type(vote) is not int or vote not in (-1, 1) or not isinstance(question, str) or not isinstance(answer, str):
|
||||
return {'ok': False, 'error': '评价内容无效,请重试。'}, 400
|
||||
conn = connect()
|
||||
conn.execute('INSERT INTO feedback(question, answer, vote, ctime) VALUES (?,?,?,?)',
|
||||
(question[:500], answer[:2000], vote, now_str()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def admin_stats():
|
||||
conn = connect()
|
||||
total_conv = conn.execute('SELECT COUNT(*) FROM chat_history').fetchone()[0]
|
||||
total_msg = conn.execute('SELECT COUNT(*) FROM messages').fetchone()[0]
|
||||
good = conn.execute("SELECT COUNT(*) FROM feedback WHERE vote IN ('1', 'up')").fetchone()[0]
|
||||
bad = conn.execute("SELECT COUNT(*) FROM feedback WHERE vote IN ('-1', 'down')").fetchone()[0]
|
||||
today = datetime.now().strftime('%Y-%m-%d')
|
||||
today_conv = conn.execute('SELECT COUNT(*) FROM chat_history WHERE date(ctime)=date(?)', (today,)).fetchone()[0]
|
||||
rating_avg, rating_count = conn.execute('SELECT COALESCE(AVG(stars), 0), COUNT(*) FROM ratings').fetchone()
|
||||
conn.close()
|
||||
return {'total_conv': total_conv, 'total_msg': total_msg, 'good': good, 'bad': bad, 'today_conv': today_conv,
|
||||
'rating_avg': round(rating_avg, 1), 'rating_count': rating_count}
|
||||
|
||||
|
||||
def my_orders(phone):
|
||||
if not phone:
|
||||
return {'orders': []}
|
||||
conn = connect()
|
||||
rows = conn.execute('SELECT track_no, status, created FROM orders WHERE phone=? ORDER BY id DESC', (phone,)).fetchall()
|
||||
conn.close()
|
||||
return {'orders': [{'track_no': r[0], 'status': r[1], 'created': r[2]} for r in rows]}
|
||||
|
||||
|
||||
def add_ticket(data):
|
||||
if not isinstance(data, dict):
|
||||
return {'ok': False, 'error': '留言格式无效。'}, 400
|
||||
content, phone = data.get('content'), data.get('phone', '')
|
||||
if not isinstance(content, str) or not 1 <= len(content.strip()) <= 2000:
|
||||
return {'ok': False, 'error': '请输入 1–2000 字的留言。'}, 400
|
||||
if not isinstance(phone, str) or len(phone.strip()) > 32:
|
||||
return {'ok': False, 'error': '联系电话格式无效。'}, 400
|
||||
conn = connect()
|
||||
conn.execute('INSERT INTO tickets(content, phone, ctime, status) VALUES(?,?,?,?)',
|
||||
(content.strip(), phone.strip(), datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'pending'))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def list_tickets():
|
||||
conn = connect()
|
||||
rows = conn.execute("SELECT id, content, phone, ctime FROM tickets WHERE status='pending' ORDER BY id DESC").fetchall()
|
||||
conn.close()
|
||||
return [{'id': r[0], 'content': r[1], 'phone': r[2], 'ctime': r[3]} for r in rows]
|
||||
|
||||
|
||||
def admin_login(data):
|
||||
u = data.get('username', '')
|
||||
p = data.get('password', '')
|
||||
conn = connect()
|
||||
row = conn.execute('SELECT name FROM agents WHERE username=? AND password=?', (u, p)).fetchone()
|
||||
conn.close()
|
||||
if row:
|
||||
return {'ok': True, 'name': row[0]}
|
||||
return ({'ok': False}, 401)
|
||||
|
||||
|
||||
def agents_list():
|
||||
conn = connect()
|
||||
# rowid also works with the legacy agents table that has an explicit INTEGER id.
|
||||
rows = conn.execute('SELECT rowid, username, name FROM agents ORDER BY rowid').fetchall()
|
||||
conn.close()
|
||||
return [{'id': row[0], 'username': row[1], 'name': row[2]} for row in rows]
|
||||
|
||||
|
||||
def rate_chat(data):
|
||||
sid, stars = data.get('sid'), data.get('stars', 0)
|
||||
comment = data.get('comment', '')
|
||||
if not sid or type(stars) is not int or not 1 <= stars <= 5 or not isinstance(comment, str):
|
||||
return ({'ok': False}, 400)
|
||||
conn = connect()
|
||||
if not conn.execute('SELECT 1 FROM human_sessions WHERE id=?', (sid,)).fetchone():
|
||||
conn.close()
|
||||
return ({'ok': False}, 404)
|
||||
conn.execute('INSERT INTO ratings(sid, stars, comment, ctime) VALUES(?,?,?,?)',
|
||||
(sid, stars, comment, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def search_chat(keyword):
|
||||
if not keyword:
|
||||
return {'results': []}
|
||||
conn = connect()
|
||||
rows = conn.execute('''SELECT h.title, m.role, m.content, m.ctime FROM messages m
|
||||
JOIN chat_history h ON m.conv_id=h.id WHERE m.content LIKE ? ORDER BY m.id DESC LIMIT 50''',
|
||||
('%' + keyword + '%',)).fetchall()
|
||||
conn.close()
|
||||
return [{'title': row[0], 'role': row[1], 'content': card_to_text(row[2]), 'ctime': row[3]} for row in rows]
|
||||
|
||||
|
||||
def export_chat(format='xlsx'):
|
||||
conn = connect()
|
||||
rows = conn.execute('SELECT h.title, m.role, m.content, m.ctime FROM messages m JOIN chat_history h ON m.conv_id=h.id ORDER BY m.id').fetchall()
|
||||
conn.close()
|
||||
import io
|
||||
if format == 'csv':
|
||||
import csv
|
||||
buf = io.StringIO()
|
||||
w = csv.writer(buf)
|
||||
w.writerow(['标题', '角色', '内容', '时间'])
|
||||
for r in rows:
|
||||
w.writerow([r[0], r[1], r[2] or '', r[3]])
|
||||
return buf.getvalue()
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = '聊天记录'
|
||||
sheet.append(['对话标题', '角色', '内容', '时间'])
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True, color='FFFFFF')
|
||||
cell.fill = PatternFill('solid', fgColor='315FD5')
|
||||
cell.alignment = Alignment(horizontal='center')
|
||||
roles = {'user': '客户', 'assistant': '客服', 'system': '系统'}
|
||||
for title, role, content, ctime in rows:
|
||||
sheet.append([title, roles.get(role, role), content or '', ctime])
|
||||
for cell in sheet[sheet.max_row]:
|
||||
cell.data_type = 's'
|
||||
for column, width in zip('ABCD', (20, 8, 80, 20)):
|
||||
sheet.column_dimensions[column].width = width
|
||||
buf = io.BytesIO()
|
||||
workbook.save(buf)
|
||||
return buf.getvalue()
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Compose knowledge, freight and model output into the existing SSE protocol."""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
from . import ai_client
|
||||
from .ai_client import compress_answer, gen_followups, has_chinese
|
||||
from .config import get_setting
|
||||
from .db import connect, last_user_question, load_context, save_message
|
||||
from .knowledge import search_knowledge
|
||||
from .pricing import (parse_shipping_intent, detect_dim_unit, freight_reply,
|
||||
calc_warehouse_card, detect_surcharge, surcharge_reply, check_island,
|
||||
is_shipping_destination_reply)
|
||||
from .tracking import CARD_PREFIX
|
||||
from .order_data import answer_query, extract_reference
|
||||
from .quote_service import answer_quote
|
||||
|
||||
|
||||
|
||||
def sse(payload):
|
||||
"""统一的事件格式:data: {"t":正文} / {"e":错误} / {"card":卡片} / {"d":1结束}
|
||||
JSON 编码可以避免正文里的换行把 SSE 帧撑断。"""
|
||||
return 'data: ' + json.dumps(payload, ensure_ascii=False) + '\n\n'
|
||||
|
||||
|
||||
QUOTE_FOLLOWUP_PREFIX = r'^(?:那(?:么)?|换成|改成|改为|如果|还是|再算|同样)'
|
||||
|
||||
|
||||
def is_shipping_followup(message, intent=None):
|
||||
"""Recognize bounded quote edits without carrying facts across new topics."""
|
||||
if re.search(r'新(?:的)?一(?:票|批)|另(?:一|外一?)(?:票|批)|新(?:的)?(?:货|订单)|换个话题|理赔|赔偿|破损|丢失|签收|退件|退款|投诉', message):
|
||||
return False
|
||||
intent = intent if intent is not None else parse_shipping_intent(message)
|
||||
text = message.strip().strip(',,。.!!??、:: ')
|
||||
prefix = re.match(QUOTE_FOLLOWUP_PREFIX, text)
|
||||
if prefix and any(intent.get(key) is not None for key in ('weight', 'dims', 'channel', 'region')):
|
||||
return True
|
||||
if intent['region'] is not None and is_shipping_destination_reply(text):
|
||||
return True
|
||||
short = re.sub(QUOTE_FOLLOWUP_PREFIX, '', text, count=1).strip()
|
||||
short = re.sub(r'^(?:请问|请|再问一下)', '', short).strip()
|
||||
if re.fullmatch(r'(?:海运|海派|空运|空派|铁路|班列|卡航|卡车|sea(?:\s+freight)?|air(?:\s+freight)?|rail|truck)'
|
||||
r'(?:报价|价格|费用|运费|时效)?(?:呢|怎么样|如何|多少钱|多久|几天)?', short, re.I):
|
||||
return True
|
||||
if re.fullmatch(r'(?:价格|费用|运费|时效)(?:呢|是多少|多少|怎么样|如何|多久|几天)?|多少钱', short):
|
||||
return True
|
||||
if intent['weight'] is not None and re.fullmatch(r'\d+(?:\.\d+)?\s*(?:kg|公斤|千克|吨|lbs?|tons?|kilograms?)(?:呢)?', short, re.I):
|
||||
return True
|
||||
return bool(intent['dims'] and re.fullmatch(r'\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?\s*(?:cm|mm|m|厘米|毫米|米)?(?:呢)?', short, re.I))
|
||||
|
||||
|
||||
def shipping_intent_with_context(message, conv_id):
|
||||
intent = parse_shipping_intent(message)
|
||||
intent['dim_unit'] = detect_dim_unit(message)
|
||||
if conv_id and is_shipping_followup(message, intent):
|
||||
connection = connect()
|
||||
try:
|
||||
recent = connection.execute("SELECT content FROM messages WHERE conv_id=? AND role='user' ORDER BY id DESC LIMIT 6", (conv_id,)).fetchall()
|
||||
finally:
|
||||
connection.close()
|
||||
for (previous,) in recent:
|
||||
if extract_reference(previous):
|
||||
break
|
||||
earlier = parse_shipping_intent(previous)
|
||||
if not any(earlier.get(key) is not None for key in ('weight', 'dims', 'channel', 'region')):
|
||||
if is_shipping_followup(previous, earlier):
|
||||
continue
|
||||
break
|
||||
for key in ('weight', 'channel', 'region'):
|
||||
if intent.get(key) is None:
|
||||
intent[key] = earlier.get(key)
|
||||
if intent['dims'] is None and earlier['dims']:
|
||||
intent['dims'] = earlier['dims']
|
||||
intent['dim_unit'] = detect_dim_unit(previous)
|
||||
if not is_shipping_followup(previous, earlier):
|
||||
break
|
||||
if intent['channel']:
|
||||
base = intent['channel'].removesuffix('_uk')
|
||||
intent['channel'] = base + '_uk' if intent['region'] == 'uk' else base
|
||||
return intent
|
||||
|
||||
|
||||
def create_chat_stream(msg, conv_id):
|
||||
if not msg:
|
||||
return (sse({'e': '问题不能为空'}), {})
|
||||
if conv_id:
|
||||
from .visitor_service import owns_conversation
|
||||
if not owns_conversation(conv_id):
|
||||
from .customer_service import needs_customer_login, order_login_response
|
||||
if needs_customer_login(conv_id):
|
||||
return (sse(order_login_response()) + sse({'d':1}), {})
|
||||
return (sse({'e':'该会话已删除,请新建对话后重试。'}), {})
|
||||
order_answer = answer_query(msg, conv_id)
|
||||
if order_answer is None:
|
||||
from .customer_faq import answer_capability
|
||||
order_answer = answer_capability(msg)
|
||||
if order_answer is None:
|
||||
order_answer = answer_quote(msg, conv_id)
|
||||
if order_answer is None and re.search(r'(?:转|联系|接入|找).*人工|人工客服',msg):
|
||||
order_answer = {'t':'点击“联系人工”可发起人工客服申请;非工作时间可留言。'}
|
||||
if order_answer is None and re.fullmatch(r'\[图片\]/uploads/\S+', msg):
|
||||
order_answer = {'t':'收到您的图片,请描述一下您的问题。'}
|
||||
if order_answer is None:
|
||||
from .quote_scope import answer_us_fallback
|
||||
order_answer = answer_us_fallback(msg,conv_id)
|
||||
ship = shipping_intent_with_context(msg, conv_id) if order_answer is None else None
|
||||
if ship and ship['region'] is None and (ship['weight'] is not None or ship['dims'] or
|
||||
re.search(r'\d+(?:\.\d+)?\s*(?:cbm|方|立方)', msg, re.I) or
|
||||
(ship['channel'] and (is_shipping_followup(msg, ship) or re.search(r'报价|价格|费用|运费|多少钱|\b(?:quote|cost|price)\b', msg, re.I)))):
|
||||
order_answer = {'t':'请提供目的国家或地区、目的仓或邮编,以便匹配对应费率;当前无法确定报价,可联系人工客服确认。'}
|
||||
if ship and ship['region'] == 'unsupported' and (ship['weight'] is not None or ship['dims'] or ship['channel'] or
|
||||
is_shipping_destination_reply(msg) or re.search(r'报价|价格|运费|费用|多少钱', msg)):
|
||||
order_answer = {'t':'当前报价表尚未包含该目的地的费率,请提供目的仓或邮编、货物品名、件数和尺寸,由人工客服确认报价。'}
|
||||
if ship and ship['region'] == 'uk' and re.search(r'\d+(?:\.\d+)?\s*(?:cbm|方|立方)', msg, re.I) and not ship['weight'] and not ship['dims']:
|
||||
order_answer = {'t':'当前报价表未提供该目的地的按方费率,请提供目的仓或邮编、实际重量和尺寸,由人工客服确认报价。'}
|
||||
if order_answer is not None:
|
||||
customer_data = order_answer.pop('_customer_data',False) or 'card' in order_answer
|
||||
order_list_state=order_answer.pop('_order_list_state',None)
|
||||
|
||||
def track_stream():
|
||||
if customer_data:
|
||||
from .customer_service import bind_order_conversation, current_customer_id
|
||||
if current_customer_id() and not bind_order_conversation(conv_id):
|
||||
yield sse({'e':'该会话暂时无法访问,请新建对话后重试。','d':1})
|
||||
return
|
||||
save_message(conv_id, 'user', msg)
|
||||
content = (CARD_PREFIX + json.dumps(order_answer['card'], ensure_ascii=False)
|
||||
if 'card' in order_answer else order_answer['t'])
|
||||
message_id=save_message(conv_id, 'assistant', content)
|
||||
if order_list_state is not None:
|
||||
from .order_listing import save_state
|
||||
save_state(conv_id,order_list_state,message_id)
|
||||
yield sse(order_answer)
|
||||
yield sse({'d': 1})
|
||||
return (track_stream(), {'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
|
||||
if not get_setting('DEEPSEEK_API_KEY'):
|
||||
return (sse({'e': '服务未配置 API Key,请在 .env 或环境变量中设置 DEEPSEEK_API_KEY 后重启服务'}), {})
|
||||
know_text = search_knowledge(msg)
|
||||
freight_text = None
|
||||
if ship['weight'] or ship['dims']:
|
||||
freight_text = freight_reply(ship)
|
||||
if not ship['channel']:
|
||||
freight_text += '\n\n(客户没有指定渠道,上面已同时给出海运和空运,请在回答末尾询问更看重时效还是成本)'
|
||||
extra_parts = []
|
||||
cbm_m = re.search('(\\d+(?:\\.\\d+)?)\\s*(?:cbm|方|立方)', msg, re.I)
|
||||
if cbm_m and ship['region'] != 'uk':
|
||||
cbm = float(cbm_m.group(1))
|
||||
ch = '海运'
|
||||
if re.search('卡航|卡车', msg):
|
||||
ch = '卡航'
|
||||
elif re.search('铁路|班列', msg):
|
||||
ch = '铁路'
|
||||
elif re.search('普卡', msg):
|
||||
ch = '普卡'
|
||||
want = None
|
||||
for kw, ctry in (('德国', 'DE'), ('法国', 'FR'), ('波兰', 'PL'), ('捷克', 'CZ'), ('西班牙', 'ES'), ('马德里', 'ES'), ('中国', '')):
|
||||
if kw in msg:
|
||||
want = ctry
|
||||
break
|
||||
card = calc_warehouse_card(cbm, ch, country=want)
|
||||
if card:
|
||||
store = card['warehouse'].splitlines()[0]
|
||||
extra_parts.append(f"【海外仓卡派 · 按方计费】\n 仓点:{store}\n 计费:{card['note']}\n 渠道:{card['channel']},适用档位 {card['tier']}\n 运费:{card['formula']}\n 说明:单箱实重超 35KG 加收 30 元/箱(封顶 3600 元);不接受仓储,特殊情况 85 元/箱/周")
|
||||
sur = detect_surcharge(msg)
|
||||
if sur:
|
||||
extra_parts.append(surcharge_reply(sur[0], sur[1], ship.get('weight')))
|
||||
pc_m = re.search('(?<![0-9])(\\d{4,5})(?![0-9])', msg)
|
||||
if pc_m and re.search('邮编|postcode|zip|偏远|岛屿', msg, re.I):
|
||||
hit = check_island(pc_m.group(1))
|
||||
if hit:
|
||||
extra_parts.append(f'【偏远判断】邮编 {pc_m.group(1)} 属于{hit[0]}({hit[1]})的岛屿/偏远地区,需加收 DPD 岛屿附加费 35 欧元/件')
|
||||
else:
|
||||
extra_parts.append(f'【偏远判断】邮编 {pc_m.group(1)} 未命中 DPD 岛屿偏远清单;但仍需以 UPS/DPD 官网查询结果为准,偏远费以账单为准')
|
||||
follow_src = None
|
||||
if not know_text:
|
||||
prev_q = last_user_question(conv_id)
|
||||
if prev_q:
|
||||
know_text = search_knowledge(prev_q)
|
||||
if know_text:
|
||||
follow_src = prev_q
|
||||
_c = connect()
|
||||
_msg_count = _c.execute("SELECT COUNT(*) FROM messages WHERE conv_id=? AND role='user'", (conv_id,)).fetchone()[0]
|
||||
_c.close()
|
||||
is_first_turn = _msg_count == 0
|
||||
save_message(conv_id, 'user', msg)
|
||||
LENGTH_RULE = '回答长度要求:全文不少于 120 字、不超过 350 字。内容要完整、信息充分,把关键点讲清楚,可分 2~4 段或用短列表呈现。可以补充相关的说明(例如适用范围、注意事项、下一步建议),让对方看完就能明白。不要寒暄客套,不要重复同一个数字,不要罗列与问题无关的信息。'
|
||||
is_en = bool(re.search('[A-Za-z]{3,}', msg)) and (not re.search('[\\u4e00-\\u9fa5]', msg))
|
||||
if is_en:
|
||||
LANGUAGE_RULE = '【语言要求 · 最高优先级】用户用英文提问,你必须用英文(English)回答全文,包括所有小节标题(如 Conclusion / Calculation / Notes),不要出现任何中文。以下给出的中文结构与参考资料仅用于理解,输出必须翻译成英文。'
|
||||
else:
|
||||
LANGUAGE_RULE = '【语言要求】用户用中文提问,请用中文回答。'
|
||||
if freight_text or extra_parts:
|
||||
blocks = []
|
||||
if freight_text:
|
||||
blocks.append(freight_text)
|
||||
blocks.extend(extra_parts)
|
||||
body = '\n\n'.join(blocks)
|
||||
system_prompt = f'{LANGUAGE_RULE}\n\n你是柏悦物流智能客服。\n下面是根据报价表计算好的结果,请严格按照这些数字向客户说明。\n不要重新计算、不要改动任何数字,但要讲清楚是怎么算出来的。\n\n{body}\n\n请按以下结构输出(用英文回答时请把标题也翻译成英文):\n【结论】先给结论:哪种方式、多少钱、多久到。\n【计算过程】分点列出,最多 5 行,让客户看懂钱花在哪。\n【补充说明】2~3 行:适用范围(如单件重量、尺寸要求)、偏远地区或敏感货附加费、下一步建议(如提供仓点或运单号可进一步核算)。\n\n{LENGTH_RULE}\n客户没指定渠道时,把主要几种渠道(海运/铁路/卡航/空运)列出来对比,并问客户更看重时效还是成本。\n'
|
||||
elif know_text:
|
||||
extra = f'\n(以上资料对应上一句提问:{follow_src})' if follow_src else ''
|
||||
system_prompt = f'{LANGUAGE_RULE}\n\n你是柏悦物流智能客服,严格优先使用下面知识库内容回答,不要自己编造业务信息。\n回答语句通顺自然,分段清晰,让人一眼看清重点。\n要结合上文理解用户的追问(比如"那空运呢""这个多少钱"指的是什么)。\n\n{LENGTH_RULE}\n\n知识库内容(供你理解,输出需按语言要求翻译):{know_text}{extra}\n'
|
||||
else:
|
||||
system_prompt = f'{LANGUAGE_RULE}\n\n你是柏悦物流智能客服。\n物流相关简单问题可以正常回答;不属于物流业务的问题礼貌说明无法解答,并建议联系人工客服。\n回答语句通顺,表述自然。\n\n{LENGTH_RULE}\n如果用户在追问,请结合上文的对话继续回答,不要重复问已经说过的信息。\n'
|
||||
context = load_context(conv_id, msg)
|
||||
|
||||
def generate():
|
||||
body = {'model': get_setting('MODEL_NAME'), 'messages': [{'role': 'system', 'content': system_prompt}] + context, 'stream': True}
|
||||
try:
|
||||
resp = ai_client.post_completion(body, stream=True, timeout=(5, 90))
|
||||
except ai_client.Timeout:
|
||||
yield sse({'e': '模型响应超时,请稍后重试'})
|
||||
return
|
||||
except ai_client.RequestException:
|
||||
yield sse({'e': '无法连接模型服务,请检查网络后重试'})
|
||||
return
|
||||
except Exception:
|
||||
yield sse({'e': '服务异常,请稍后重试'})
|
||||
return
|
||||
if resp.status_code != 200:
|
||||
detail = ''
|
||||
try:
|
||||
detail = (resp.json().get('error') or {}).get('message', '')
|
||||
except Exception:
|
||||
detail = (resp.text or '')[:120]
|
||||
tips = {401: '系统繁忙,请稍后再试', 402: '系统繁忙,请稍后再试', 429: '咨询量较大,请稍后再试'}
|
||||
tip = tips.get(resp.status_code, '系统繁忙,请稍后再试')
|
||||
resp.close()
|
||||
yield sse({'e': tip})
|
||||
return
|
||||
parts = []
|
||||
interrupted = False
|
||||
answer_saved = False
|
||||
try:
|
||||
got_text = False
|
||||
completed = False
|
||||
finish_reason = None
|
||||
for raw in resp.iter_lines():
|
||||
if not raw:
|
||||
continue
|
||||
line = raw.decode('utf-8', errors='ignore')
|
||||
if not line.startswith('data:'):
|
||||
continue
|
||||
data = line[5:].strip()
|
||||
if data == '[DONE]':
|
||||
completed = True
|
||||
break
|
||||
try:
|
||||
j = json.loads(data)
|
||||
choice = j['choices'][0]
|
||||
chunk = choice.get('delta', {}).get('content') or ''
|
||||
finish_reason = choice.get('finish_reason') or finish_reason
|
||||
if finish_reason == 'stop':
|
||||
completed = True
|
||||
except Exception:
|
||||
continue
|
||||
if chunk:
|
||||
got_text = True
|
||||
parts.append(chunk)
|
||||
yield sse({'t': chunk})
|
||||
if not got_text:
|
||||
yield sse({'e': '模型没有返回内容,请重试'})
|
||||
return
|
||||
if not completed or finish_reason not in (None, 'stop'):
|
||||
interrupted = True
|
||||
yield sse({'e': '回答未生成完整,请点击重试'})
|
||||
return
|
||||
full_text = ''.join(parts)
|
||||
limit = get_setting('MAX_ANSWER_CHARS') if has_chinese(full_text) else get_setting('MAX_ANSWER_CHARS_EN')
|
||||
if len(full_text) > limit:
|
||||
short = compress_answer(full_text, limit)
|
||||
if len(short) > limit:
|
||||
short = compress_answer(short, limit - 60)
|
||||
if short != full_text:
|
||||
full_text = short
|
||||
yield sse({'replace': short})
|
||||
save_message(conv_id, 'assistant', full_text)
|
||||
answer_saved = True
|
||||
if is_first_turn:
|
||||
try:
|
||||
fu = gen_followups(msg, full_text)
|
||||
if fu:
|
||||
yield sse({'suggest': fu})
|
||||
except Exception:
|
||||
pass
|
||||
yield sse({'d': 1})
|
||||
except GeneratorExit:
|
||||
interrupted = True
|
||||
raise
|
||||
except Exception:
|
||||
interrupted = True
|
||||
yield sse({'e': '传输中断,请点击重试'})
|
||||
finally:
|
||||
text = ''.join(parts)
|
||||
try:
|
||||
if interrupted and text and not answer_saved:
|
||||
save_message(conv_id, 'assistant', text + '\n\n(回答中断,以上内容未生成完整)')
|
||||
finally:
|
||||
resp.close()
|
||||
return (generate(), {'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Read local configuration without changing the process environment or storage."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parents[1]
|
||||
ALLOWED_EXT = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.pdf', '.txt', '.csv'}
|
||||
MAX_UPLOAD_MB = 10
|
||||
|
||||
|
||||
def default_config():
|
||||
from dotenv import dotenv_values
|
||||
|
||||
local_config = dotenv_values(ROOT_DIR / '.env', encoding='utf-8-sig', interpolate=False)
|
||||
api_key = os.environ.get('DEEPSEEK_API_KEY', local_config.get('DEEPSEEK_API_KEY'))
|
||||
return {
|
||||
'DATABASE': ROOT_DIR / 'history.db',
|
||||
'UPLOAD_DIR': ROOT_DIR / 'uploads',
|
||||
'BACKUP_DIR': ROOT_DIR / 'backups',
|
||||
'LOG_DIR': ROOT_DIR / 'logs',
|
||||
'DEEPSEEK_API_KEY': (api_key or '').strip(),
|
||||
'ASR_API_KEY': str(os.environ.get('ASR_API_KEY', local_config.get('ASR_API_KEY')) or '').strip(),
|
||||
'ASR_PROVIDER': str(os.environ.get('ASR_PROVIDER', local_config.get('ASR_PROVIDER')) or 'baidu').strip().lower(),
|
||||
'BAIDU_ASR_API_KEY': str(os.environ.get('BAIDU_ASR_API_KEY', local_config.get('BAIDU_ASR_API_KEY')) or '').strip(),
|
||||
'BAIDU_ASR_SECRET_KEY': str(os.environ.get('BAIDU_ASR_SECRET_KEY', local_config.get('BAIDU_ASR_SECRET_KEY')) or '').strip(),
|
||||
'FFMPEG_BIN': str(os.environ.get('FFMPEG_BIN', local_config.get('FFMPEG_BIN')) or '').strip(),
|
||||
'ASR_URL': str(os.environ.get('ASR_URL', local_config.get('ASR_URL')) or
|
||||
'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions').strip(),
|
||||
'ASR_MODEL': str(os.environ.get('ASR_MODEL', local_config.get('ASR_MODEL')) or 'qwen3-asr-flash').strip(),
|
||||
'ORDER_DATA_TENANT_ID': str(os.environ.get('ORDER_DATA_TENANT_ID', local_config.get('ORDER_DATA_TENANT_ID')) or '').strip(),
|
||||
'CUSTOMER_DEMO_ENABLED': str(os.environ.get('CUSTOMER_DEMO_ENABLED', local_config.get('CUSTOMER_DEMO_ENABLED', 'true'))).lower() in ('1','true','yes'),
|
||||
'CUSTOMER_DEMO_USERNAME': str(os.environ.get('CUSTOMER_DEMO_USERNAME', local_config.get('CUSTOMER_DEMO_USERNAME', 'admin')) or '').strip(),
|
||||
'CUSTOMER_DEMO_PASSWORD_HASH': str(os.environ.get('CUSTOMER_DEMO_PASSWORD_HASH', local_config.get('CUSTOMER_DEMO_PASSWORD_HASH',
|
||||
'pbkdf2:sha256:600000$vY5fe7GwJQRQbhKV$a4c4eeb96e2bda18bfa6b82d263c0cd61dead2e3f224f694e01fc497152df72f')) or ''),
|
||||
'CUSTOMER_DEMO_TENANT_ID': str(os.environ.get('CUSTOMER_DEMO_TENANT_ID', local_config.get('CUSTOMER_DEMO_TENANT_ID')) or '').strip(),
|
||||
'CUSTOMER_DEMO_LOCAL_ORDERS': str(os.environ.get('CUSTOMER_DEMO_LOCAL_ORDERS', local_config.get('CUSTOMER_DEMO_LOCAL_ORDERS', 'true'))).lower() in ('1','true','yes'),
|
||||
'MODEL_URL': 'https://api.deepseek.com/v1/chat/completions',
|
||||
'MODEL_NAME': 'deepseek-chat',
|
||||
'MAX_CONTEXT': 4,
|
||||
'MAX_ANSWER_CHARS': 800,
|
||||
'MAX_ANSWER_CHARS_EN': 1400,
|
||||
'RATE_LIMIT_PER_MIN': 60,
|
||||
'ALLOWED_EXT': set(ALLOWED_EXT),
|
||||
'MAX_UPLOAD_MB': MAX_UPLOAD_MB,
|
||||
'HOST': '0.0.0.0',
|
||||
'PORT': 5000,
|
||||
'INITIALIZE_RUNTIME': True,
|
||||
}
|
||||
|
||||
|
||||
def get_setting(name):
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
except ImportError:
|
||||
return default_config()[name]
|
||||
if has_app_context():
|
||||
return current_app.config[name]
|
||||
return default_config()[name]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Describe supported customer actions without inventing operational integrations."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def answer_capability(message):
|
||||
if re.search(r'照片|图片',message) and re.search(r'报价|价格|判断|识别|尺寸',message):
|
||||
return {'t':'可以通过输入框旁的“+”上传照片供人工查看。当前聊天不会自动识别图片,请同时用文字提供品名、重量、箱数、尺寸和目的仓码或邮编,再核算报价。'}
|
||||
if re.search(r'(?:手机号|手机号码|电话号码).*(?:查|订单|运单)|(?:查|查询).*手机号',message):
|
||||
return {'t':'当前请使用客户账号登录后,按入仓码查询订单;暂不支持手机号或短信验证码查单。没有入仓码可联系人工核实订单归属。'}
|
||||
if re.search(r'下单(?!号|时间|日期)|订舱|生成订单|创建订单|预约提货|安排提货|\b(?:place|create)\s+(?:an?\s+)?order\b',message,re.I):
|
||||
return {'t':'下单、订舱和安排提货需要联系人工办理。当前可查询报价及已关联订单,尚未创建订单或安排提货;请提供目的仓、品名、箱数、重量和尺寸供人工核对。'}
|
||||
if re.search(r'开(?:发票|票)|发票.*(?:税点|几个点|怎么开|申请)|月结|账期|付款账号|收款账号|银行账号|打款|(?:怎么|如何)付款',message):
|
||||
return {'t':'开票税点、月结资格及付款方式需要由专属业务员确认。请联系人工核对对应订单和结算信息;当前聊天不提供未经确认的税点或收款账号。'}
|
||||
if re.search(r'导出.*(?:订单|运单|Excel)|(?:订单|运单).*导出',message,re.I):
|
||||
return {'t':'当前聊天暂不提供订单Excel导出,可联系人工核对导出需求。可先查看账号内订单列表,或发送入仓码查询单票详情。'}
|
||||
if re.search(r'Excel|表格',message,re.I) and re.search(r'直接读|自动读|读取|识别|读里面',message):
|
||||
return {'t':'当前聊天不会自动读取Excel附件里的箱规。请将每箱重量、长宽高及目的仓码粘贴为文字,我可据此核算;批量表格可交人工整理。'}
|
||||
if re.search(r'换.*手机|换.*设备|跨设备|清除.*(?:浏览器|缓存)',message) and re.search(r'聊天|记录|历史',message):
|
||||
return {'t':'当前聊天记录与原浏览器的访客身份关联,换手机或清除浏览器数据后不会自动同步恢复。请先在原设备查看;客户账号目前用于订单权限校验,尚未提供跨设备聊天同步。'}
|
||||
return None
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Customer authentication and order scope, independent of staff authentication."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from flask import g, has_app_context, jsonify, request
|
||||
from werkzeug.security import check_password_hash
|
||||
|
||||
from .config import get_setting
|
||||
from .db import connect
|
||||
from .visitor_service import valid_key, visitor_id
|
||||
|
||||
COOKIE_NAME = 'baiyue_customer'
|
||||
SESSION_SECONDS = 8 * 3600
|
||||
|
||||
|
||||
def demo_tenant(connection):
|
||||
configured = get_setting('CUSTOMER_DEMO_TENANT_ID') or get_setting('ORDER_DATA_TENANT_ID')
|
||||
if configured:
|
||||
return configured
|
||||
rows = connection.execute("SELECT DISTINCT tenant_id FROM order_test_data WHERE tenant_id<>'' LIMIT 2").fetchall()
|
||||
return rows[0][0] if len(rows) == 1 else ''
|
||||
|
||||
|
||||
def user_tenants(connection, row):
|
||||
if row[4]:
|
||||
return (row[4],)
|
||||
rows = connection.execute('SELECT tenant_id FROM customer_tenant_grants WHERE customer_id=? ORDER BY tenant_id LIMIT 257',
|
||||
(row[0],)).fetchall()
|
||||
return tuple(item[0] for item in rows) if len(rows) <= 256 else ()
|
||||
|
||||
|
||||
def seed_local_grants(connection, row):
|
||||
if not row[6] or connection.execute('SELECT scope_initialized FROM customer_users WHERE id=?',(row[0],)).fetchone()[0]:
|
||||
return
|
||||
if not row[4] and get_setting('CUSTOMER_DEMO_LOCAL_ORDERS') and not user_tenants(connection,row):
|
||||
connection.execute('INSERT OR IGNORE INTO customer_tenant_grants(customer_id,tenant_id) '
|
||||
"SELECT ?,tenant_id FROM order_test_data WHERE tenant_id<>'' GROUP BY tenant_id",(row[0],))
|
||||
if user_tenants(connection,row):
|
||||
connection.execute('UPDATE customer_users SET scope_initialized=1 WHERE id=?',(row[0],))
|
||||
|
||||
|
||||
def scope_key(tenants):
|
||||
return hashlib.sha256(json.dumps(sorted(tenants),ensure_ascii=False).encode()).hexdigest() if tenants else None
|
||||
|
||||
|
||||
def effective_tenants(tenants):
|
||||
configured = get_setting('ORDER_DATA_TENANT_ID')
|
||||
return tuple(value for value in tenants if not configured or value == configured)
|
||||
|
||||
|
||||
def current_scope_key():
|
||||
from .visitor_service import customer_tenant_ids
|
||||
return scope_key(customer_tenant_ids())
|
||||
|
||||
|
||||
def init_customer_tables(connection):
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS customer_users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, display_name TEXT NOT NULL,
|
||||
tenant_id TEXT NOT NULL DEFAULT '', enabled INTEGER NOT NULL DEFAULT 1,
|
||||
is_demo INTEGER NOT NULL DEFAULT 0, scope_initialized INTEGER NOT NULL DEFAULT 0)''')
|
||||
if 'scope_initialized' not in [item[1] for item in connection.execute('PRAGMA table_info(customer_users)')]:
|
||||
connection.execute('ALTER TABLE customer_users ADD COLUMN scope_initialized INTEGER NOT NULL DEFAULT 0')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS customer_sessions (
|
||||
token_hash TEXT PRIMARY KEY, customer_id INTEGER NOT NULL,
|
||||
visitor_id TEXT NOT NULL, auth_stamp TEXT NOT NULL, expires_at INTEGER NOT NULL)''')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS idx_customer_session_expiry ON customer_sessions(expires_at)')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS customer_tenant_grants (
|
||||
customer_id INTEGER NOT NULL, tenant_id TEXT NOT NULL, PRIMARY KEY(customer_id,tenant_id))''')
|
||||
if get_setting('CUSTOMER_DEMO_ENABLED'):
|
||||
connection.execute('''INSERT OR IGNORE INTO customer_users
|
||||
(username,password_hash,display_name,tenant_id,is_demo) VALUES(?,?,?,?,1)''',
|
||||
(get_setting('CUSTOMER_DEMO_USERNAME'), get_setting('CUSTOMER_DEMO_PASSWORD_HASH'),
|
||||
get_setting('CUSTOMER_DEMO_USERNAME'), demo_tenant(connection)))
|
||||
row = connection.execute('SELECT id,username,password_hash,display_name,tenant_id,enabled,is_demo '
|
||||
'FROM customer_users WHERE username=?',(get_setting('CUSTOMER_DEMO_USERNAME'),)).fetchone()
|
||||
seed_local_grants(connection,row)
|
||||
|
||||
|
||||
def auth_stamp(row, tenants):
|
||||
return hashlib.sha256((row[2] + '\n' + (scope_key(effective_tenants(tenants)) or '')).encode()).hexdigest()
|
||||
|
||||
|
||||
def allowed_user(row):
|
||||
return bool(row and row[5] and (not row[6] or (
|
||||
get_setting('CUSTOMER_DEMO_ENABLED') and row[1] == get_setting('CUSTOMER_DEMO_USERNAME'))))
|
||||
|
||||
|
||||
def attach_customer():
|
||||
g.customer = None
|
||||
g.customer_tenant_id = None
|
||||
g.customer_tenant_ids = ()
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
if not visitor_id() or not valid_key(token):
|
||||
return
|
||||
connection = connect()
|
||||
try:
|
||||
session = connection.execute('SELECT customer_id,auth_stamp FROM customer_sessions '
|
||||
'WHERE token_hash=? AND visitor_id=? AND expires_at>?',
|
||||
(hashlib.sha256(token.encode()).hexdigest(), visitor_id(), int(time.time()))).fetchone()
|
||||
if not session:
|
||||
return
|
||||
row = connection.execute('SELECT id,username,password_hash,display_name,tenant_id,enabled,is_demo '
|
||||
'FROM customer_users WHERE id=?', (session[0],)).fetchone()
|
||||
tenants = effective_tenants(user_tenants(connection,row)) if row else ()
|
||||
if allowed_user(row) and secrets.compare_digest(auth_stamp(row,tenants), session[1]):
|
||||
g.customer = {'id':row[0], 'username':row[1], 'name':row[3]}
|
||||
g.customer_tenant_id = tenants[0] if len(tenants) == 1 else None
|
||||
g.customer_tenant_ids = tenants
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def current_customer_id():
|
||||
customer = getattr(g, 'customer', None) if has_app_context() else None
|
||||
return customer['id'] if customer else None
|
||||
|
||||
|
||||
def bind_order_conversation(conv_id):
|
||||
"""A conversation containing order facts also requires its customer login."""
|
||||
if not conv_id:
|
||||
return True
|
||||
connection = connect()
|
||||
try:
|
||||
result = connection.execute('UPDATE chat_history SET customer_id=?,customer_scope=? WHERE id=? AND visitor_id=? '
|
||||
'AND (customer_id IS NULL OR (customer_id=? AND customer_scope=?))',
|
||||
(current_customer_id(),current_scope_key(),conv_id,visitor_id(),current_customer_id(),current_scope_key()))
|
||||
connection.commit()
|
||||
return result.rowcount == 1
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def session_status():
|
||||
return {'ok':True, 'authenticated':bool(g.customer), 'user':g.customer}
|
||||
|
||||
|
||||
def order_login_response():
|
||||
if current_customer_id():
|
||||
return {'t':'当前账号尚未关联订单,请联系人工客服。'}
|
||||
return {'t':'请先使用客户账号登录并关联订单,再查询订单或物流轨迹。','login_required':True}
|
||||
|
||||
|
||||
def needs_customer_login(conv_id):
|
||||
if current_customer_id():
|
||||
return False
|
||||
connection = connect()
|
||||
try:
|
||||
return bool(connection.execute('SELECT 1 FROM chat_history WHERE id=? AND visitor_id=? '
|
||||
'AND customer_id IS NOT NULL',(conv_id,visitor_id())).fetchone())
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def login(data, attempts, lock):
|
||||
if not isinstance(data, dict):
|
||||
return {'ok':False, 'error':'请输入账号和密码。'}, 400
|
||||
username, password = data.get('username'), data.get('password')
|
||||
if not isinstance(username, str) or not isinstance(password, str) or not 1 <= len(username) <= 80 or not 1 <= len(password) <= 256:
|
||||
return {'ok':False, 'error':'请输入有效的账号和密码。'}, 400
|
||||
now = int(time.time())
|
||||
# A separate short failed-login budget supplements the global request limiter.
|
||||
ip = request.remote_addr or 'unknown'
|
||||
with lock:
|
||||
failures = [stamp for stamp in attempts.get(ip, []) if stamp > now - 300]
|
||||
if len(attempts) > 2048:
|
||||
for key in list(attempts):
|
||||
if not attempts[key] or attempts[key][-1] <= now - 300:
|
||||
attempts.pop(key,None)
|
||||
if len(failures) >= 5:
|
||||
return {'ok':False, 'error':'登录尝试过多,请稍后重试。'}, 429
|
||||
attempts[ip] = failures + [now]
|
||||
connection = connect()
|
||||
try:
|
||||
row = connection.execute('SELECT id,username,password_hash,display_name,tenant_id,enabled,is_demo '
|
||||
'FROM customer_users WHERE username=?', (username.strip(),)).fetchone()
|
||||
digest = row[2] if row else get_setting('CUSTOMER_DEMO_PASSWORD_HASH')
|
||||
try:
|
||||
valid = check_password_hash(digest, password)
|
||||
except (ValueError, TypeError):
|
||||
valid = False
|
||||
if not valid or not allowed_user(row):
|
||||
return {'ok':False, 'error':'账号或密码不正确。'}, 403
|
||||
with lock:
|
||||
attempts.pop(ip, None)
|
||||
if row[6] and not row[4] and not user_tenants(connection,row) and not connection.execute(
|
||||
'SELECT scope_initialized FROM customer_users WHERE id=?',(row[0],)).fetchone()[0]:
|
||||
tenant = demo_tenant(connection)
|
||||
if tenant:
|
||||
connection.execute("UPDATE customer_users SET tenant_id=? WHERE id=? AND tenant_id=''", (tenant,row[0]))
|
||||
row = connection.execute('SELECT id,username,password_hash,display_name,tenant_id,enabled,is_demo '
|
||||
'FROM customer_users WHERE id=?', (row[0],)).fetchone()
|
||||
seed_local_grants(connection,row)
|
||||
old_token = request.cookies.get(COOKIE_NAME)
|
||||
if valid_key(old_token):
|
||||
connection.execute('DELETE FROM customer_sessions WHERE token_hash=? AND visitor_id=?',
|
||||
(hashlib.sha256(old_token.encode()).hexdigest(), visitor_id()))
|
||||
token = secrets.token_hex(32)
|
||||
connection.execute('DELETE FROM customer_sessions WHERE expires_at<=?', (now,))
|
||||
connection.execute('INSERT INTO customer_sessions VALUES(?,?,?,?,?)',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),row[0],visitor_id(),auth_stamp(row,user_tenants(connection,row)),now+SESSION_SECONDS))
|
||||
connection.commit()
|
||||
response = jsonify({'ok':True,'authenticated':True,'user':{'id':row[0],'username':row[1],'name':row[3]}})
|
||||
response.set_cookie(COOKIE_NAME,token,max_age=SESSION_SECONDS,httponly=True,secure=request.is_secure,samesite='Lax',path='/')
|
||||
return response
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def logout():
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
if valid_key(token):
|
||||
connection = connect()
|
||||
try:
|
||||
connection.execute('DELETE FROM customer_sessions WHERE token_hash=? AND visitor_id=?',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),visitor_id()))
|
||||
connection.commit()
|
||||
finally:
|
||||
connection.close()
|
||||
response = jsonify({'ok':True,'authenticated':False,'user':None})
|
||||
response.delete_cookie(COOKIE_NAME,path='/',secure=request.is_secure,httponly=True,samesite='Lax')
|
||||
return response
|
||||
@@ -0,0 +1,269 @@
|
||||
"""SQLite schema, history persistence and backups; initialized explicitly by create_app."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .config import get_setting
|
||||
from .tracking import card_to_text
|
||||
|
||||
|
||||
def connect():
|
||||
connection = sqlite3.connect(get_setting('DATABASE'))
|
||||
try:
|
||||
from flask import g, has_app_context
|
||||
except ImportError:
|
||||
return connection
|
||||
if has_app_context():
|
||||
g.setdefault('_database_connections', []).append(connection)
|
||||
return connection
|
||||
|
||||
|
||||
def close_connections(error=None):
|
||||
from flask import g
|
||||
for connection in g.pop('_database_connections', []):
|
||||
connection.close()
|
||||
|
||||
|
||||
|
||||
def now_str():
|
||||
return datetime.now().strftime('%Y-%m-%d %H:%M')
|
||||
|
||||
|
||||
def init_db():
|
||||
Path(get_setting('DATABASE')).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = connect()
|
||||
cur = conn.cursor()
|
||||
# Serialize schema inspection and migration when multiple workers start together.
|
||||
cur.execute('BEGIN IMMEDIATE')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS chat_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
ctime TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
cols = [r[1] for r in cur.execute('PRAGMA table_info(chat_history)').fetchall()]
|
||||
if 'utime' not in cols:
|
||||
cur.execute('ALTER TABLE chat_history ADD COLUMN utime TEXT')
|
||||
cur.execute('UPDATE chat_history SET utime = ctime WHERE utime IS NULL')
|
||||
if 'visitor_id' not in cols:
|
||||
cur.execute('ALTER TABLE chat_history ADD COLUMN visitor_id TEXT')
|
||||
if 'customer_id' not in cols:
|
||||
cur.execute('ALTER TABLE chat_history ADD COLUMN customer_id INTEGER')
|
||||
if 'order_list_state' not in cols:
|
||||
cur.execute('ALTER TABLE chat_history ADD COLUMN order_list_state TEXT')
|
||||
if 'customer_scope' not in cols:
|
||||
cur.execute('ALTER TABLE chat_history ADD COLUMN customer_scope TEXT')
|
||||
if 'customer_tenant_id' in cols:
|
||||
# Preserve conversations created by the earlier local single-tenant login.
|
||||
import hashlib
|
||||
import json
|
||||
for cid, tenant in cur.execute('SELECT id,customer_tenant_id FROM chat_history WHERE customer_id IS NOT NULL').fetchall():
|
||||
scope = hashlib.sha256(json.dumps([tenant],ensure_ascii=False).encode()).hexdigest() if tenant else None
|
||||
cur.execute('UPDATE chat_history SET customer_scope=? WHERE id=?',(scope,cid))
|
||||
cur.execute('CREATE INDEX IF NOT EXISTS idx_chat_visitor ON chat_history(visitor_id, id)')
|
||||
cur.execute('''CREATE TABLE IF NOT EXISTS visitor_uploads (
|
||||
filename TEXT PRIMARY KEY, visitor_id TEXT NOT NULL, ctime TEXT NOT NULL
|
||||
)''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
conv_id INTEGER NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
ctime TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
cur.execute('CREATE INDEX IF NOT EXISTS idx_msg_conv ON messages(conv_id, id)')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS feedback (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
question TEXT,
|
||||
answer TEXT,
|
||||
vote TEXT,
|
||||
ctime TEXT
|
||||
)
|
||||
''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS human_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
conv_id INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'waiting',
|
||||
ctime TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS human_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL,
|
||||
side TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
ctime TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
hm_cols = [r[1] for r in cur.execute('PRAGMA table_info(human_messages)').fetchall()]
|
||||
if 'read_at' not in hm_cols:
|
||||
cur.execute('ALTER TABLE human_messages ADD COLUMN read_at TEXT')
|
||||
if 'recalled_id' not in hm_cols:
|
||||
cur.execute('ALTER TABLE human_messages ADD COLUMN recalled_id INTEGER')
|
||||
hs_cols = [r[1] for r in cur.execute('PRAGMA table_info(human_sessions)').fetchall()]
|
||||
if 'note' not in hs_cols:
|
||||
cur.execute("ALTER TABLE human_sessions ADD COLUMN note TEXT DEFAULT ''")
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS ratings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
sid INTEGER NOT NULL,
|
||||
stars INTEGER NOT NULL,
|
||||
comment TEXT DEFAULT '',
|
||||
ctime TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS agents (
|
||||
username TEXT PRIMARY KEY,
|
||||
password TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
phone TEXT,
|
||||
track_no TEXT,
|
||||
status TEXT,
|
||||
created TEXT
|
||||
)
|
||||
''')
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
content TEXT,
|
||||
phone TEXT,
|
||||
ctime TEXT,
|
||||
status TEXT
|
||||
)
|
||||
''')
|
||||
from .order_data import init_order_table
|
||||
init_order_table(conn)
|
||||
from .customer_service import init_customer_tables
|
||||
init_customer_tables(conn)
|
||||
from .quote_data import init_quote_tables
|
||||
init_quote_tables(conn)
|
||||
old = cur.execute('SELECT id, title FROM chat_history WHERE id NOT IN (SELECT DISTINCT conv_id FROM messages)').fetchall()
|
||||
for cid, title in old:
|
||||
cur.execute('INSERT INTO messages(conv_id, role, content, ctime) VALUES (?,?,?,?)', (cid, 'user', title, now_str()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def backup_db():
|
||||
"""启动时把数据库备份到 backups/,文件名带日期,只保留最近 7 天"""
|
||||
try:
|
||||
bdir = get_setting('BACKUP_DIR')
|
||||
os.makedirs(bdir, exist_ok=True)
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
dst = os.path.join(bdir, f'history_{today}.db')
|
||||
if not os.path.exists(dst):
|
||||
shutil.copy2(get_setting('DATABASE'), dst)
|
||||
cutoff = datetime.now() - timedelta(days=7)
|
||||
for f in os.listdir(bdir):
|
||||
m = re.match('history_(\\d{8})\\.db$', f)
|
||||
if not m:
|
||||
continue
|
||||
try:
|
||||
if datetime.strptime(m.group(1), '%Y%m%d') < cutoff:
|
||||
os.remove(os.path.join(bdir, f))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f'[数据库备份失败] {e}')
|
||||
|
||||
|
||||
def cleanup_old_conversations():
|
||||
"""自动清理 30 天前的旧对话,防止数据库无限膨胀"""
|
||||
try:
|
||||
conn = connect()
|
||||
c = conn.cursor()
|
||||
cutoff = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S')
|
||||
rows = c.execute('SELECT id FROM chat_history WHERE utime < ?', (cutoff,)).fetchall()
|
||||
ids = [r[0] for r in rows]
|
||||
if not ids:
|
||||
return
|
||||
for cid in ids:
|
||||
c.execute('DELETE FROM messages WHERE conv_id=?', (cid,))
|
||||
c.execute(f"DELETE FROM chat_history WHERE id IN ({','.join('?' * len(ids))})", ids)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f'[自动清理] 已删除 {len(ids)} 条 30 天前的旧对话')
|
||||
except Exception as e:
|
||||
print(f'[自动清理失败] {e}')
|
||||
|
||||
|
||||
def make_title(content):
|
||||
"""生成会话标题:优先用文字内容,只有附件时显示附件数量"""
|
||||
lines = [l for l in content.split('\n') if not l.strip().startswith('[附件]')]
|
||||
text = ' '.join(lines).strip()
|
||||
if text and text != '(发送了附件)' and (text != '请帮我看看这个附件'):
|
||||
return text[:24]
|
||||
n = len([l for l in content.split('\n') if l.strip().startswith('[附件]')])
|
||||
if n == 1:
|
||||
return '📎 已上传附件'
|
||||
if n > 1:
|
||||
return f'📎 {n}个附件'
|
||||
return content[:24]
|
||||
|
||||
|
||||
def save_message(conv_id, role, content):
|
||||
"""把一条消息写进会话;用户消息做幂等处理,重试不会重复入库。"""
|
||||
if not conv_id or not content:
|
||||
return
|
||||
conn = connect()
|
||||
cur = conn.cursor()
|
||||
if role == 'user':
|
||||
last = cur.execute('SELECT role, content FROM messages WHERE conv_id=? ORDER BY id DESC LIMIT 1', (conv_id,)).fetchone()
|
||||
if last and last[0] == 'user' and (last[1] == content):
|
||||
conn.close()
|
||||
return 'duplicate'
|
||||
inserted = cur.execute('INSERT INTO messages(conv_id, role, content, ctime) '
|
||||
'SELECT ?,?,?,? WHERE EXISTS(SELECT 1 FROM chat_history WHERE id=?)',
|
||||
(conv_id, role, content, now_str(), conv_id)).rowcount
|
||||
if not inserted:
|
||||
conn.close()
|
||||
return 'deleted'
|
||||
message_id=cur.lastrowid
|
||||
if role == 'user':
|
||||
row = cur.execute('SELECT title FROM chat_history WHERE id=?', (conv_id,)).fetchone()
|
||||
if row and (not row[0] or row[0] == '新对话'):
|
||||
cur.execute('UPDATE chat_history SET title=? WHERE id=?', (make_title(content), conv_id))
|
||||
cur.execute('UPDATE chat_history SET utime=? WHERE id=?', (now_str(), conv_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return message_id
|
||||
|
||||
|
||||
def last_user_question(conv_id):
|
||||
"""上一条用户提问(必须在当前这句入库之前调用)"""
|
||||
if not conv_id:
|
||||
return None
|
||||
conn = connect()
|
||||
row = conn.execute("SELECT content FROM messages WHERE conv_id=? AND role='user' ORDER BY id DESC LIMIT 1", (conv_id,)).fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def load_context(conv_id, msg):
|
||||
"""取最近 MAX_CONTEXT 条消息,拼成模型要的 messages(不含 system)。"""
|
||||
if not conv_id:
|
||||
return [{'role': 'user', 'content': msg}]
|
||||
conn = connect()
|
||||
rows = conn.execute('SELECT role, content FROM messages WHERE conv_id=? ORDER BY id DESC LIMIT ?', (conv_id, get_setting('MAX_CONTEXT'))).fetchall()
|
||||
conn.close()
|
||||
rows.reverse()
|
||||
history = [{'role': r, 'content': card_to_text(c)} for r, c in rows]
|
||||
if not history or history[-1]['role'] != 'user' or history[-1]['content'] != msg:
|
||||
history.append({'role': 'user', 'content': msg})
|
||||
return history
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Attachment validation, storage and retention without request parsing."""
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from urllib.parse import unquote
|
||||
|
||||
from .config import get_setting
|
||||
|
||||
|
||||
|
||||
def cleanup_uploads():
|
||||
"""Keep attachments referenced by chat history; expire unused uploads after 7 days."""
|
||||
try:
|
||||
udir = get_setting('UPLOAD_DIR')
|
||||
if not os.path.isdir(udir):
|
||||
return
|
||||
from .db import connect
|
||||
connection = connect()
|
||||
try:
|
||||
referenced = set()
|
||||
rows = connection.execute("SELECT content FROM messages WHERE content LIKE '%/uploads/%' "
|
||||
"UNION ALL SELECT content FROM human_messages WHERE content LIKE '%/uploads/%'")
|
||||
for (content,) in rows:
|
||||
referenced.update(unquote(name) for name in re.findall(r'/uploads/([A-Za-z0-9_.%-]+)', content or ''))
|
||||
finally:
|
||||
connection.close()
|
||||
cutoff = time.time() - 7 * 86400
|
||||
for f in os.listdir(udir):
|
||||
if f in referenced:
|
||||
continue
|
||||
fp = os.path.join(udir, f)
|
||||
if os.path.isfile(fp) and os.path.getmtime(fp) < cutoff:
|
||||
os.remove(fp)
|
||||
except Exception as e:
|
||||
print(f'[清理上传文件失败] {e}')
|
||||
|
||||
|
||||
def upload_file(files):
|
||||
"""上传附件:保存到 uploads 目录,返回文件名与访问地址"""
|
||||
if 'file' not in files:
|
||||
return ({'ok': False, 'error': '没有文件'}, 400)
|
||||
f = files['file']
|
||||
if not f or not f.filename:
|
||||
return ({'ok': False, 'error': '文件名为空'}, 400)
|
||||
ext = os.path.splitext(f.filename)[1].lower()
|
||||
if ext not in get_setting('ALLOWED_EXT'):
|
||||
return ({'ok': False, 'error': f'不支持的格式 {ext},仅支持图片/PDF/TXT/CSV'}, 400)
|
||||
f.seek(0, os.SEEK_END)
|
||||
size = f.tell()
|
||||
f.seek(0)
|
||||
if size > get_setting('MAX_UPLOAD_MB') * 1024 * 1024:
|
||||
return ({'ok': False, 'error': f"文件超过 {get_setting('MAX_UPLOAD_MB')}MB"}, 400)
|
||||
os.makedirs(get_setting('UPLOAD_DIR'), exist_ok=True)
|
||||
safe_name = secrets.token_hex(16) + ext
|
||||
f.save(os.path.join(get_setting('UPLOAD_DIR'), safe_name))
|
||||
from .db import connect, now_str
|
||||
from .visitor_service import visitor_id
|
||||
owner = visitor_id()
|
||||
if owner:
|
||||
connection = connect()
|
||||
try:
|
||||
with connection:
|
||||
connection.execute('INSERT INTO visitor_uploads(filename,visitor_id,ctime) VALUES(?,?,?)',
|
||||
(safe_name, owner, now_str()))
|
||||
finally:
|
||||
connection.close()
|
||||
is_image = ext in ('.png', '.jpg', '.jpeg', '.gif', '.webp')
|
||||
return {'ok': True, 'name': f.filename, 'url': f'/uploads/{safe_name}', 'is_image': is_image}
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Conversation CRUD with unchanged response data."""
|
||||
|
||||
from .db import connect, now_str
|
||||
from .visitor_service import visitor_id, owns_conversation
|
||||
from .customer_service import current_customer_id, current_scope_key
|
||||
|
||||
|
||||
WELCOME_TEXT = '您好!欢迎咨询柏悦物流智能客服,可以咨询运费、时效或联系人工客服。'
|
||||
|
||||
|
||||
def new_chat():
|
||||
now = now_str()
|
||||
conn = connect()
|
||||
cur = conn.cursor()
|
||||
cur.execute('INSERT INTO chat_history(title, ctime, utime, visitor_id) VALUES (?,?,?,?)',
|
||||
('新对话', now, now, visitor_id()))
|
||||
conv_id = cur.lastrowid
|
||||
cur.execute('INSERT INTO messages(conv_id, role, content, ctime) VALUES (?,?,?,?)',
|
||||
(conv_id, 'assistant', WELCOME_TEXT, now))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'id': conv_id, 'welcome': WELCOME_TEXT}
|
||||
|
||||
|
||||
def get_history():
|
||||
conn = connect()
|
||||
rows = conn.execute('SELECT id, title, ctime, COALESCE(utime, ctime) FROM chat_history WHERE visitor_id=? '
|
||||
'AND (customer_id IS NULL OR (customer_id=? AND customer_scope=?)) '
|
||||
'ORDER BY COALESCE(utime, ctime) DESC, id DESC', (visitor_id(),current_customer_id(),current_scope_key())).fetchall()
|
||||
conn.close()
|
||||
return [{'id': r[0], 'title': r[1], 'ctime': r[2], 'utime': r[3]} for r in rows]
|
||||
|
||||
|
||||
def get_messages(conv_id):
|
||||
if not owns_conversation(conv_id):
|
||||
return []
|
||||
conn = connect()
|
||||
rows = conn.execute('SELECT role, content, ctime FROM messages WHERE conv_id=? ORDER BY id DESC LIMIT 100', (conv_id,)).fetchall()
|
||||
conn.close()
|
||||
rows = rows[::-1]
|
||||
return [{'role': r[0], 'content': r[1], 'ctime': r[2]} for r in rows]
|
||||
|
||||
|
||||
def del_history(hid):
|
||||
if not owns_conversation(hid):
|
||||
return {'ok': False}, 404
|
||||
conn = connect()
|
||||
cur = conn.cursor()
|
||||
cur.execute('DELETE FROM human_messages WHERE session_id IN (SELECT id FROM human_sessions WHERE conv_id=?)', (hid,))
|
||||
cur.execute('DELETE FROM human_sessions WHERE conv_id=?', (hid,))
|
||||
cur.execute('DELETE FROM messages WHERE conv_id=?', (hid,))
|
||||
cur.execute('DELETE FROM chat_history WHERE id=?', (hid,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def clear_all():
|
||||
conn = connect()
|
||||
cur = conn.cursor()
|
||||
owner = visitor_id()
|
||||
owned = 'SELECT id FROM chat_history WHERE visitor_id=? AND (customer_id IS NULL OR (customer_id=? AND customer_scope=?))'
|
||||
scope = (owner,current_customer_id(),current_scope_key())
|
||||
cur.execute('DELETE FROM human_messages WHERE session_id IN (SELECT id FROM human_sessions '
|
||||
'WHERE conv_id IN ('+owned+'))', scope)
|
||||
cur.execute('DELETE FROM human_sessions WHERE conv_id IN ('+owned+')', scope)
|
||||
cur.execute('DELETE FROM messages WHERE conv_id IN ('+owned+')', scope)
|
||||
cur.execute('DELETE FROM chat_history WHERE id IN ('+owned+')', scope)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Request limiting and HTML/SSE cache headers with app-scoped state."""
|
||||
|
||||
import time
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
|
||||
def rate_limit():
|
||||
path = request.path
|
||||
if path in ('/healthz', '/api/visitor/human/poll') or path.startswith('/static') or path.startswith('/api/human/'):
|
||||
return None
|
||||
ip = request.remote_addr or 'unknown'
|
||||
now = time.time()
|
||||
hits = current_app.extensions['rate_hits'][ip]
|
||||
while hits and now - hits[0] > 60:
|
||||
hits.pop(0)
|
||||
if len(hits) >= current_app.config['RATE_LIMIT_PER_MIN']:
|
||||
return jsonify({'e': '请求太频繁,请稍后几秒再试', 'd': 1}), 429
|
||||
hits.append(now)
|
||||
return None
|
||||
|
||||
|
||||
def no_cache_html(response):
|
||||
if response.mimetype in ('text/html', 'text/event-stream') or request.path.startswith('/api/'):
|
||||
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['Expires'] = '0'
|
||||
return response
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Human conversation lifecycle; typing state is supplied by the app."""
|
||||
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from .db import connect
|
||||
|
||||
SERVICE_TIMEZONE = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def human_request(data):
|
||||
conv_id = data.get('conv_id')
|
||||
if not conv_id:
|
||||
return ({'ok': False, 'error': 'no conv'}, 400)
|
||||
service_time = datetime.now(SERVICE_TIMEZONE)
|
||||
if not 8 <= service_time.hour < 22:
|
||||
return {'ok': False, 'closed': True, 'msg': '人工客服工作时间为每天北京时间8:00-22:00,当前为非工作时间,请留言'}
|
||||
now = service_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
conn = connect()
|
||||
conn.execute('BEGIN IMMEDIATE')
|
||||
if not conn.execute('SELECT 1 FROM chat_history WHERE id=?', (conv_id,)).fetchone():
|
||||
conn.close()
|
||||
return ({'ok':False, 'error':'conversation_not_found'}, 404)
|
||||
row = conn.execute("SELECT id FROM human_sessions WHERE conv_id=? AND status!='closed' ORDER BY id DESC LIMIT 1", (conv_id,)).fetchone()
|
||||
if row:
|
||||
sid = row[0]
|
||||
else:
|
||||
cur = conn.execute('INSERT INTO human_sessions(conv_id, status, ctime) VALUES(?,?,?)', (conv_id, 'waiting', now))
|
||||
sid = cur.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True, 'session_id': sid}
|
||||
|
||||
|
||||
def human_poll(sid, after, typing_map):
|
||||
conn = connect()
|
||||
msgs = conn.execute('SELECT id, side, content, ctime, read_at, recalled_id FROM human_messages WHERE session_id=? AND id>? ORDER BY id', (sid, after)).fetchall()
|
||||
st = conn.execute("SELECT status, COALESCE(note, '') FROM human_sessions WHERE id=?", (sid,)).fetchone()
|
||||
conn.close()
|
||||
is_typing = False
|
||||
ts = typing_map.get(str(sid))
|
||||
if ts and time.time() - ts < 5:
|
||||
is_typing = True
|
||||
return {'status': st[0] if st else 'closed', 'note': st[1] if st else '',
|
||||
'typing': is_typing, 'messages': [dict(id=m[0], side=m[1], content=m[2], ctime=m[3],
|
||||
read=bool(m[4]), **({'recalled_id': m[5]} if m[5] else {})) for m in msgs]}
|
||||
|
||||
|
||||
def human_send(data):
|
||||
sid = data.get('sid')
|
||||
side = data.get('side', 'customer')
|
||||
content = data.get('content') or ''
|
||||
if not sid or not isinstance(content, str) or not content.strip() or side not in ('customer', 'agent'):
|
||||
return ({'ok': False}, 400)
|
||||
content = content.strip()
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
conn = connect()
|
||||
conn.execute('BEGIN IMMEDIATE')
|
||||
row = conn.execute('SELECT conv_id, status FROM human_sessions WHERE id=?', (sid,)).fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
return ({'ok': False, 'error': 'session_not_found'}, 404)
|
||||
if row[1] == 'closed' or (data.get('conv_id') is not None and data['conv_id'] != row[0]):
|
||||
conn.close()
|
||||
return ({'ok': False, 'error': 'conversation_changed'}, 409)
|
||||
conn.execute('INSERT INTO human_messages(session_id, side, content, ctime) VALUES(?,?,?,?)', (sid, side, content, now))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_queue():
|
||||
conn = connect()
|
||||
rows = conn.execute("SELECT id, conv_id, status, ctime FROM human_sessions WHERE status='waiting' ORDER BY id").fetchall()
|
||||
conn.close()
|
||||
return [{'id': r[0], 'conv_id': r[1], 'ctime': r[3]} for r in rows]
|
||||
|
||||
|
||||
def human_active():
|
||||
conn = connect()
|
||||
rows = conn.execute("SELECT id, conv_id FROM human_sessions WHERE status='active' ORDER BY id").fetchall()
|
||||
conn.close()
|
||||
return [{'id': r[0], 'conv_id': r[1]} for r in rows]
|
||||
|
||||
|
||||
def human_accept(data):
|
||||
sid = data.get('sid')
|
||||
conn = connect()
|
||||
changed = conn.execute("UPDATE human_sessions SET status='active' WHERE id=? AND status IN ('waiting','active') "
|
||||
'AND EXISTS(SELECT 1 FROM chat_history WHERE id=human_sessions.conv_id)', (sid,)).rowcount
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True} if changed else ({'ok':False, 'error':'session_closed_or_missing'}, 409)
|
||||
|
||||
|
||||
def human_close(data):
|
||||
sid = data.get('sid')
|
||||
conn = connect()
|
||||
conn.execute("UPDATE human_sessions SET status='closed' WHERE id=?", (sid,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_transfer(data, typing_map):
|
||||
sid = data.get('sid')
|
||||
conn = connect()
|
||||
changed = conn.execute("UPDATE human_sessions SET status='waiting' WHERE id=? AND status='active'", (sid,)).rowcount
|
||||
if not changed:
|
||||
conn.close()
|
||||
return ({'ok': False, 'error': '会话当前无法转接'}, 409)
|
||||
conn.execute('INSERT INTO human_messages(session_id, side, content, ctime) VALUES(?,?,?,?)',
|
||||
(sid, 'system', '客服已转接,请其他客服接入', datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
typing_map.pop(str(sid), None)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_note(data):
|
||||
note = data.get('note', '')
|
||||
if not isinstance(note, str):
|
||||
return ({'ok': False}, 400)
|
||||
conn = connect()
|
||||
changed = conn.execute('UPDATE human_sessions SET note=? WHERE id=?', (note, data.get('sid'))).rowcount
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True} if changed else ({'ok': False}, 404)
|
||||
|
||||
|
||||
def human_recall(data):
|
||||
conn = connect()
|
||||
mid = data.get('mid')
|
||||
# Only the first request can change the original message; retries emit no duplicate event.
|
||||
conn.execute('BEGIN IMMEDIATE')
|
||||
row = conn.execute('SELECT session_id, side, content FROM human_messages WHERE id=?', (mid,)).fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
return ({'ok': False}, 404)
|
||||
if row[1] == 'system' and row[2] == '该消息已撤回':
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
if row[1] != 'agent':
|
||||
conn.close()
|
||||
return ({'ok': False}, 400)
|
||||
conn.execute("UPDATE human_messages SET side='system', content='该消息已撤回' WHERE id=?", (mid,))
|
||||
conn.execute('INSERT INTO human_messages(session_id, side, content, ctime, recalled_id) VALUES(?,?,?,?,?)',
|
||||
(row[0], 'system', '该消息已撤回', datetime.now().strftime('%Y-%m-%d %H:%M:%S'), mid))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_typing(data, typing_map):
|
||||
sid = data.get('sid')
|
||||
typing_map[str(sid)] = time.time()
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_stop_typing(data, typing_map):
|
||||
sid = data.get('sid')
|
||||
typing_map.pop(str(sid), None)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
def human_read(data):
|
||||
sid = data.get('sid')
|
||||
conn = connect()
|
||||
conn.execute("UPDATE human_messages SET read_at=? WHERE session_id=? AND side='customer' AND read_at IS NULL", (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), sid))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {'ok': True}
|
||||
@@ -0,0 +1,290 @@
|
||||
"""Extracted knowledge rules with unchanged business behavior."""
|
||||
|
||||
|
||||
knowledge_list = [
|
||||
# ==================== 一、订单 ====================
|
||||
{
|
||||
"keys": ["查询订单", "查订单", "订单查询", "订单在哪里", "我的订单在哪", "帮我查订单", "为什么查不到订单"],
|
||||
"text": (
|
||||
"请提供订单号、入仓号或关联运单号,并核验订单归属。"
|
||||
"查询结果以实际记录为准。查不到时,应核对号码、查询范围和数据同步情况,"
|
||||
"不能直接认定没有发货,也不能编造运输或清关结果。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["订单号和运单号", "订单号是什么", "运单号是什么", "入仓号是什么", "入仓码是什么", "一票多个单号", "主子订单"],
|
||||
"text": (
|
||||
"订单号识别业务订单,入仓号用于收货归集,运单号识别运输任务或包裹。"
|
||||
"一票货可能因分包、分批或阶段换号产生多个编号,"
|
||||
"应根据实际关联记录分别确认,不能把换号当成新增货物。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["付款后没发货", "付款了没发货", "下单后没发货", "下单后多久发货", "修改订单", "订单能修改吗", "取消订单", "订单能取消吗", "更换渠道"],
|
||||
"text": (
|
||||
"下单或付款成功不代表已出运,还需核对收货、审核和运输安排。"
|
||||
"修改、取消或换渠道需根据当前操作阶段确认。"
|
||||
"变更申请不等于执行成功,是否产生费用按适用规则确认。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 二、客户信息 ====================
|
||||
{
|
||||
"keys": ["手机号查订单", "用手机号查", "客户编号查订单", "客户号查订单", "公司名称查订单", "用公司名查", "代客户查询", "帮别人查订单"],
|
||||
"text": (
|
||||
"可按系统支持的方式辅助查找,但必须核验身份、订单归属及代理权限。"
|
||||
"不能仅凭手机号或公司名称披露他人的完整订单、地址和联系方式。"
|
||||
"查询权限与修改权限需要分别确认。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["联系人填错", "联系人写错", "手机号填错", "电话填错", "邮箱填错", "客户资料修改", "客户信息修改"],
|
||||
"text": (
|
||||
"客户账户资料与本票收发货资料需要分别管理。"
|
||||
"修改账户资料不一定同步修改历史和在途订单。"
|
||||
"在途信息变更需确认相关操作方是否接受并生效。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["订单负责人", "谁负责这票", "客户待办", "没收到通知"],
|
||||
"text": (
|
||||
"负责人、客户待办和通知情况应根据实际记录确认。"
|
||||
"待办需说明具体事项、提交渠道及已确认的期限。"
|
||||
"没有联系或送达记录时,不能认定客户已收到通知;"
|
||||
"没有分配记录时,不能编造负责人和反馈时间。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 三、地址 ====================
|
||||
{
|
||||
"keys": ["收货地址怎么填", "地址怎么填写", "地址怎么写", "邮编不对", "邮编错误", "地址不完整", "地址不全", "缺少门牌"],
|
||||
"text": (
|
||||
"国际收货地址通常需要国家、州省、城市、街道、门牌、邮编、收件人及电话。"
|
||||
"缺失或不匹配可能影响派送,具体要求以目的地和承运商为准。"
|
||||
"补交资料后仍需确认是否修改成功。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["最终送到哪里", "最后送到哪里", "收货地址确认", "目的地址是什么", "提货地址和收货地址", "提货地址一样吗"],
|
||||
"text": (
|
||||
"提货、交仓、中转、清关和最终收货地址用途不同。"
|
||||
"最终目的地应查询本票已生效的地址,并按权限展示。"
|
||||
"到达中转仓或清关场所,不代表到达最终收货地址。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["修改收货地址", "改地址", "地址可以修改吗", "可以改地址吗", "更换收件人", "收件人可以改吗", "收件人改地址", "改送其他仓", "换仓地址", "FBA地址确认"],
|
||||
"text": (
|
||||
"改址需要核对货物阶段和执行方处理能力,"
|
||||
"未确认生效前不能告知新地址已启用。"
|
||||
"FBA或海外仓需核对当前货件完整地址及仓代码,"
|
||||
"不能仅按历史仓代码表安排配送。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 四、节点 ====================
|
||||
{
|
||||
"keys": ["节点是什么意思", "什么叫节点", "节点和轨迹", "节点是什么", "已提交是什么意思", "订单已提交", "已接单是什么意思"],
|
||||
"text": (
|
||||
"节点是某一步发生的事件,轨迹是多个运输事件组成的记录。"
|
||||
"已提交、审核通过、已接单属于业务处理状态,"
|
||||
"本身不能证明仓库收到实物或货物已经出运。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["已预报是什么意思", "预报是什么意思", "已入仓是什么意思", "入仓是什么意思", "已装柜是什么意思", "装柜是什么意思", "已出运是什么意思", "出运了吗"],
|
||||
"text": (
|
||||
"已预报通常表示信息已提交,不一定已交实物;"
|
||||
"已入仓表示仓库收货,不一定完成检查;"
|
||||
"已装柜表示完成装载,不代表已经离港。"
|
||||
"已出运需有实际离港、起飞、发车或交运依据。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["到港是什么意思", "到港了吗", "已提取是什么意思", "提取是什么意思", "已交末端是什么意思", "交末端是什么意思", "派送中是什么意思", "开始派送了吗"],
|
||||
"text": (
|
||||
"到港表示到达港口,之后可能仍需清关和交接。"
|
||||
"已提取、已交末端通常表示当地承运商接收货物,需要核对接收方。"
|
||||
"派送中表示进入配送环节,以上均不等于收件人签收。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 五、轨迹 ====================
|
||||
{
|
||||
"keys": ["完整物流轨迹", "物流轨迹怎么查", "运输轨迹怎么查", "有单号没有轨迹", "有单号查不到", "轨迹好几天没更新", "物流几天没更新", "轨迹不更新"],
|
||||
"text": (
|
||||
"轨迹应说明数据来源、覆盖范围及最后有效事件时间。"
|
||||
"暂无记录可能涉及未交接、扫描未回传或查询源异常,需要核实。"
|
||||
"长期没有更新不能直接认定丢失,没有数据的阶段不能自行补齐。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["换单号后怎么查", "单号换了", "新旧单号", "官网轨迹不一样", "轨迹不一致", "节点重复", "节点时间不一致"],
|
||||
"text": (
|
||||
"换号需保留新旧编号关联。"
|
||||
"不同来源或节点时间不一致时,应核对时区、原始事件、回传及更正记录。"
|
||||
"同步时间较新不一定代表事件较新,排查方向不能当作已确认原因。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["实时位置", "货物现在在哪", "预计到达时间", "预计什么时候到", "轨迹能证明签收吗", "轨迹能当到货证明吗", "模拟轨迹"],
|
||||
"text": (
|
||||
"节点地点通常表示某时经过该处,不等于实时定位。"
|
||||
"预计到达时间属于计划,应注明来源和条件。"
|
||||
"签收争议需核对POD等凭证,演示或模拟轨迹不能证明真实运输和交付。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 六、货物状态 ====================
|
||||
{
|
||||
"keys": ["履约中是什么意思", "履约中代表什么", "头程完成是什么意思", "头程完成了吗", "订单完成就是签收吗", "订单完成是不是签收"],
|
||||
"text": (
|
||||
"履约中表示订单正在执行,不能据此判断具体位置或清关阶段。"
|
||||
"当前系统的头程订单已完成,不等于末端已签收,"
|
||||
"也不能直接证明客户已收到货物。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["货物是否完好", "货物完好吗", "有没有少件", "少了几件", "货物受潮", "货物进水", "部分到货", "部分签收", "只到了一部分"],
|
||||
"text": (
|
||||
"货况需依据检查、交接件数和照片等记录确认,运输正常不能证明完好。"
|
||||
"部分到货或签收时,应分别核对总件数及各件进度。"
|
||||
"没有检查依据时说明尚未核实,不能用一件状态代表整票。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["已签收但没收到", "显示签收没收到", "签收人不认识", "谁签收的", "货物异常", "物流异常", "滞留是什么意思", "货物滞留"],
|
||||
"text": (
|
||||
"签收争议应核对签收人、交付地点、代收及POD,必要时调查。"
|
||||
"异常或滞留需明确发生环节和实际原因,不能直接等同海关扣货。"
|
||||
"调查前不能擅自认定货物丢失或客户已经收到。"
|
||||
)
|
||||
},
|
||||
|
||||
# ==================== 七、清关 ====================
|
||||
{
|
||||
"keys": ["清关了吗", "我的货清关了吗", "是否清关", "清关完成没有", "清关完成了吗", "有没有放行", "出口放行就是清关完成吗"],
|
||||
"text": (
|
||||
"查询清关需明确国家、出口或进口环节,并核对有效记录。"
|
||||
"出口放行不代表目的国进口清关完成,到港和已付款也不能证明放行。"
|
||||
"没有可靠数据时应说明暂未取得结果,不能把未知当作已完成或未完成。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["已申报是什么意思", "申报了吗", "清关中是什么意思", "现在清关中吗", "查验是不是没收", "被查验了吗", "清关为什么慢", "清关怎么还没好"],
|
||||
"text": (
|
||||
"申报动作、申报受理和放行需分别核实;"
|
||||
"清关中表示手续正在处理,查验不等于没收。"
|
||||
"具体等待原因以实际反馈为准,"
|
||||
"不能保证统一天数或一定放行,清关状态也不一定按固定顺序变化。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys": ["清关完为什么没派送", "清关了怎么没派送", "整票都清关了吗", "是不是整票放行", "税款交了吗", "税交了吗", "放行证明", "清关证明"],
|
||||
"text": (
|
||||
"资料、税费和放行状态需分别核实,客户付款不一定代表税款已缴。"
|
||||
"放行范围需核对申报单、批次及包裹,不能用一件代表整票。"
|
||||
"放行后可能仍需提货和末端交接;凭证提供需核对关联、授权和脱敏要求。"
|
||||
)
|
||||
},
|
||||
{
|
||||
"keys":["公司","柏悦","柏悦物流","介绍","哪家","哪家货代","你们是哪家","公司地址","办公地址","洛杉矶地址","纽约地址"],
|
||||
"text":"浙江柏悦物流位于义乌,主营中欧跨境物流专线,依托义乌、宁波口岸优势,服务中小跨境卖家。主要渠道:欧洲海运快线、义乌-中欧铁路、中欧卡航、欧洲空运(空派)、英国空运,均支持欧洲、英国双清包税与VAT递延。义乌、泉州、广州、深圳均可交仓,公司地址位于:洛杉矶:10767 7th Street, Rancho Cucamonga, California 91730纽约:Door 13-14,75 Carter Dr Edison, New Jersey 08817义乌:浙江省义乌市福田街道稠州北路 1399 号 8613-8615 室深圳:深圳市南山区粤海街道海珠社区海德三道 1258 号卓越后海金融中心 1101。"
|
||||
},
|
||||
{
|
||||
"keys":["海运","船运","海派","海运快线","樱花快线","欧洲海运价格","海运多少钱","海运多久"],
|
||||
"text":"欧洲海运快线(双清/递延)单价:21KG+ 12.3元/kg,101KG+ 10.3元/kg,500KG+ 10.2元/kg,2000KG+ 10.0元/kg。时效:开船后38-45天提取。可走樱花快线(+0.3元/kg),递延价减1.7元/kg。主派送为UPS/DHL/DPD/CWE统配。"
|
||||
},
|
||||
{
|
||||
"keys":["铁路","中欧班列","班列","义乌铁路","火车","铁路价格","铁路多久","铁路多少钱"],
|
||||
"text":"义乌-中欧铁路专线单价:21KG+ 15.5元/kg,100KG+ 和 1000KG+ 均为13.5元/kg。时效:发车后36-40天提取。VAT递延减1元/kg。只限送义乌仓,义乌装柜经阿拉山口/霍尔果斯出境。"
|
||||
},
|
||||
{
|
||||
"keys":["卡航","卡车","卡派","卡航价格","卡航多久","卡航多少钱"],
|
||||
"text":"中欧卡航单价:21KG+ 19.4元/kg,101KG+ 和 500KG+ 17.4元/kg,2000KG+ 及 4000KG+ 17.3元/kg。时效:发车后欧盟16-20天提取。递延减1.5元/kg,普卡时效18-22天。纯纺织品另加5元/kg。"
|
||||
},
|
||||
{
|
||||
"keys":["空运","空派","航空","欧洲空运","空运价格","空运多久","空运多少钱"],
|
||||
"text":"欧洲空运专线(空派)单价:21KG+ 39元/kg,45KG+ 38元/kg,71KG+ 37元/kg,101KG+ 36元/kg。时效:10-13天左右提取;快线8-13天,直飞快线12-15天。一票多件单件不足12KG按12KG计费。"
|
||||
},
|
||||
{
|
||||
"keys":["英国海运","英国铁路","中英卡航","英国专线"],
|
||||
"text":"英国专线(DPD)双清价格:英国海运21KG+ 12.8元/kg、101KG+/301KG+ 10.9元/kg,时效约40天提取;英国铁路21KG+ 18.0元/kg、101KG+ 16.2元/kg,发车后25-30天提取;中英卡航21KG+ 21.4元/kg、101KG+ 19.4元/kg,发车后20-22天提取。VAT自税/递延价更低(海运10.0/8.1、铁路15/13.2、卡航18.4/16.4)。北极航线英国海运25-28天,价格单询。卡航单件不超30kg、尺寸≤98×68×59cm。"
|
||||
},
|
||||
{
|
||||
"keys":["英国空运","英国空运价格","英国空运多久","英国空运多少钱","英国","UK","伦敦"],
|
||||
"text":"英国空运专线(双清)单价:22KG+ 48元/kg,51KG+ 44元/kg,101KG+ 42元/kg,时效8-10个自然日提取。VAT自税/递延为44/40/38元/kg,带电货47.5/42.5/41.5元/kg。拒收北爱尔兰、苏格兰高地等偏远地址。"
|
||||
},
|
||||
{
|
||||
"keys":["报价","价格","费用","计费","怎么收费","计费重量","计费重量怎么算","材积重","体积重","多少钱","运费","运费怎么算","单价"],
|
||||
"text":"运费计算方式:阶梯单价 × 计费重量。计费重量 = 实重与材积重取大值,材积 = 长×宽×高(cm)÷6000,即1CBM=167KG。各渠道最低起收21KG(英国空运22KG)。单件计费重不足13KG的渠道(铁路、卡航)按5元/kg加收超轻费;空运单件不足12KG按12KG计费。偏远地址加7元/kg,单票最低250元。价格不含税,税点以开出的发票为准。"
|
||||
},
|
||||
{
|
||||
"keys":["时效","运输时效","多久","要几天","多长时间","几天到","什么时候到"],
|
||||
"text":"各渠道时效:欧洲海运快线开船后38-45天提取;中欧铁路发车后36-40天提取;中欧卡航发车后16-20天提取;欧洲空运10-13天提取;英国空运8-10个自然日提取。海关查验、罢工、节假日等不可抗力导致的时间不计入。"
|
||||
},
|
||||
{
|
||||
"keys":["揽收","上门取件","上门收货","可以上门取货吗","交仓","交货","哪里交仓"],
|
||||
"text":"义乌、深圳(龙华观澜、宝安福园)、广州(石井)、泉州均可交仓,义乌仓10:00-21:00收货。欧洲空运交仓义乌+1元/kg,泉州、广州+0.5元/kg;海运、铁路、卡航泉州交货+0.5元/kg。"
|
||||
},
|
||||
{
|
||||
"keys":["入仓","进仓","仓库收货","仓库地址","仓库在哪","义乌仓","深圳仓","广州仓","交仓地址","送仓"],
|
||||
"text":"义乌仓:义乌市稠江街道梦娜袜业德贸路东三门进,李东文 19558263692(10:00-21:00)。深圳龙华:龙华区观澜街道君子布社区张一村路黄背坑路1号B栋,张长印 18688937838。深圳宝安:福园二路九号海亨通物流B区C09-C14。广州:恒河沙仓储石井仓211,潘志红 13789206500。送货需打印交接清单随货交仓。"
|
||||
},
|
||||
{
|
||||
"keys":["理赔","货损","丢件","赔付","破损","压坏","索赔","怎么理赔","丢件怎么赔","理赔多久"],
|
||||
"text":"遗失赔付:未提取上网遗失按申报价值赔偿,最高不超过40元/kg,不退运费;已提取遗失按服务商标准,最高100USD/票。开查时间:交仓后7天未提取可申请开查,开查30天无果走索赔。签收后亚马逊未上架需2周内提出调查,包裹异常需1个月内提出。外包装无损的内件丢失不支持理赔,易碎品损坏不支持理赔。可自购保险,保费为货值千分之三(电池千分之五)。"
|
||||
},
|
||||
{
|
||||
"keys":["超轻费","计费重量不足","最低计费","重量不够怎么收费"],
|
||||
"text":"单件计费重量不得低于13KG(空运12KG),可整票按平均13KG算,不足部分按5元/kg加收超轻费。例:单箱只有12KG,加收5×1=5元超轻费。欧洲热门仓卡派直送要求单件平均计费重12KG,不足按2元/kg加收派送费。"
|
||||
},
|
||||
{
|
||||
"keys":["偏远","偏远费","偏远地址","偏远怎么查","偏远收费"],
|
||||
"text":"偏远地址加收7元/kg(不含燃油),单票偏远费最低消费250元/票。需要自行到UPS/DPD官网查询目的地址是否偏远,我司出货时不另行通知,以账单为准,偏远费6个月内有效。"
|
||||
},
|
||||
{
|
||||
"keys":["超重","超长","超大","尺寸限制","尺寸超了","超尺寸怎么收费"],
|
||||
"text":"欧洲空运最长边≤99cm、次长边≤75cm、实重<24KG。英国DPD单件≤30KG,尺寸100×70×60cm以内,超重或超长各加收330元/件。UPS单边最长≤99cm、次边≤75cm、单件<24KG,超出加收240元+100元。热门仓卡派直送:单件超40KG加收30元/件。"
|
||||
},
|
||||
{
|
||||
"keys":["敏感","敏感货能发吗","带电","电池","液体","粉末","禁品","不能寄","什么不能寄","违禁品","拒收","拒接"],
|
||||
"text":"可接带标准箱100瓦以下非危电池/内电产品(C卡航、海运快线均可),资料齐全加1元/kg,资料不齐加2元/kg;手机、平板电脑加5元/kg。拒接:纯液体、纯粉末、药品、食品、易燃易爆、仿牌侵权、木制品(空运)、陶瓷手表等反倾销品、电子烟、管制刀具、枪支。电池第一个托收400元/件,第二个起100元/件,600元封顶。"
|
||||
},
|
||||
{
|
||||
"keys":["清关","清关资料","清关要什么资料","递延","VAT","VAT递延","双清","双清包税","包税","DDP"],
|
||||
"text":"欧洲、英国渠道均支持双清包税与VAT递延(只付关税,增值税销售后缴纳)。递延需提供法人护照/身份证、欧盟VAT和EORI号及回执、营业执照、4份模板文件原件扫描件PDF。罗马尼亚等欧盟国家有二次清关风险,二次关税由客户自行缴纳。"
|
||||
},
|
||||
{
|
||||
"keys":["报关","怎么报关","单独报关","报关费","报关多少钱"],
|
||||
"text":"单独报关费用:空运350元/票,海运200元/票,铁路250元/票,卡航200元/票,续页费50元/页。一达通报关500元/票。单票品名最多5个,第6个起加收30元/个。报价不含税,税点以开出的发票为准。"
|
||||
},
|
||||
{
|
||||
"keys":["亚马逊","亚马逊仓","FBA","FBA头程","海外仓","仓库配送","卡派直送"],
|
||||
"text":"支持FBA头程送亚马逊仓,热门仓卡派直送(德国WRO5/HAJ1/DTM1/DTM2、法国CDG7/LIL8、意大利TRN3、西班牙BCN8、罗马尼亚EMAG等)。卡派直送优势:超重附加费少、不限尺寸重量、上架快、基本无丢件。法国、意大利、西班牙其他亚马逊仓不能超UPS标准。"
|
||||
},
|
||||
{
|
||||
"keys":["人工客服","人工","客服","转人工","在线吗","上班","工作时间","营业时间","几点","周六","周日","星期六","星期日","星期天","礼拜","周末","双休","节假日","放假","休息"],
|
||||
"text":"人工客服在线时间:每天北京时间 8:00—22:00,周末及节假日同样适用。非工作时间可以先留言或提交需求,客服会在工作时间尽快回复您。"
|
||||
},
|
||||
{
|
||||
"keys":["电话","联系方式","怎么联系","联系你们","微信"],
|
||||
"text":"可以联系您的专属业务员,或在人工客服在线时间(每天北京时间 8:00—22:00)通过在线客服咨询。建议提前准备好入仓码、货物信息(品名、重量、尺寸、目的国),方便快速处理。"
|
||||
},
|
||||
{
|
||||
"keys":["退件","退回","退货","退运","怎么退运"],
|
||||
"text":"海运/铁路为散货拼柜,已装柜不接受退件和扣件。空运国外扣件费200欧/票,收件人改派地址最低200元/票。退回海外仓:德国境内15欧/件,欧盟境内25欧/件,操作费100元/票,5个工作日免仓储,超期1欧/kg/天。重派德国10欧/件、欧盟20欧/件。"
|
||||
}
|
||||
]
|
||||
|
||||
def search_knowledge(question):
|
||||
"""按关键词命中打分:命中的关键词越长越具体,得分越高"""
|
||||
q = question.lower()
|
||||
best, best_score = None, 0
|
||||
for item in knowledge_list:
|
||||
for k in item["keys"]:
|
||||
if k.lower() in q:
|
||||
score = len(k) # 长关键词更具体,优先
|
||||
if score > best_score:
|
||||
best, best_score = item["text"], score
|
||||
return best
|
||||
@@ -0,0 +1,406 @@
|
||||
"""Local, editable order test data. This repository can later be replaced by MCP."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
|
||||
from .config import get_setting
|
||||
from .order_tracking import build_tracking
|
||||
from .visitor_service import customer_tenant_ids
|
||||
from .customer_service import order_login_response
|
||||
|
||||
|
||||
FIELDS = ('source_order_id', 'tenant_id', 'order_no', 'inbound_code', 'shipment_id',
|
||||
'status', 'country_code', 'transport_mode', 'warehouse_code', 'order_role',
|
||||
'parent_order_no', 'package_count', 'gross_weight_kg', 'volume_cbm',
|
||||
'history_json', 'tracking_json', 'exception_reason', 'data_note', 'source_updated_at', 'snapshot_at')
|
||||
STATUS_LABELS = {'DRAFT': '草稿', 'SUBMITTED': '已提交', 'APPROVED': '审核通过',
|
||||
'ACCEPTED': '已接单', 'REJECTED': '审核驳回', 'PROCESSING': '履约中',
|
||||
'COMPLETED': '头程订单已完成', 'CANCELLED': '已取消'}
|
||||
FIELD_LABELS = {'inbound':'入仓码', 'number':'订单号', 'shipment':'Shipment ID', 'country':'目的国',
|
||||
'warehouse':'目的仓', 'transport':'运输方式', 'packages':'件数',
|
||||
'weight':'申报毛重', 'volume':'申报体积', 'role':'订单层级',
|
||||
'parent':'父订单号', 'updated':'来源更新时间'}
|
||||
IDENTIFIER = re.compile(r'(?<![A-Za-z0-9_-])[A-Za-z0-9][A-Za-z0-9_-]{5,63}(?![A-Za-z0-9_-])')
|
||||
ORDER_DETAIL = r'状态|进度|轨迹|异常|到哪|开船|到港|清关|提柜|还柜|签收|预计|什么时候|何时|多久|重量|毛重|体积|件数|箱数|目的地|目的国|目的仓|仓库|父订单|运费|费用|价格|几件|几箱|公斤|千克|多少钱'
|
||||
|
||||
|
||||
class OrderDataUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def init_order_table(connection):
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS order_test_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_order_id TEXT, tenant_id TEXT NOT NULL DEFAULT 'test',
|
||||
order_no TEXT NOT NULL COLLATE NOCASE,
|
||||
inbound_code TEXT COLLATE NOCASE, shipment_id TEXT COLLATE NOCASE,
|
||||
status TEXT NOT NULL, country_code TEXT, transport_mode TEXT, warehouse_code TEXT,
|
||||
order_role TEXT, parent_order_no TEXT,
|
||||
package_count INTEGER, gross_weight_kg TEXT, volume_cbm TEXT,
|
||||
history_json TEXT NOT NULL DEFAULT '[]', tracking_json TEXT NOT NULL DEFAULT '[]', exception_reason TEXT, data_note TEXT,
|
||||
source_updated_at TEXT, snapshot_at TEXT,
|
||||
UNIQUE(tenant_id, order_no)
|
||||
)''')
|
||||
columns = {row[1] for row in connection.execute('PRAGMA table_info(order_test_data)')}
|
||||
if 'tracking_json' not in columns:
|
||||
connection.execute("ALTER TABLE order_test_data ADD COLUMN tracking_json TEXT NOT NULL DEFAULT '[]'")
|
||||
if 'exception_reason' not in columns:
|
||||
connection.execute('ALTER TABLE order_test_data ADD COLUMN exception_reason TEXT')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS idx_order_test_inbound ON order_test_data(inbound_code)')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS idx_order_test_shipment ON order_test_data(shipment_id)')
|
||||
|
||||
|
||||
def import_records(connection, records, replace=False):
|
||||
"""Import an explicitly supplied snapshot; preserve manual edits unless requested."""
|
||||
init_order_table(connection)
|
||||
inserted = skipped = 0
|
||||
for source in records:
|
||||
if not isinstance(source, dict) or not str(source.get('order_no') or '').strip():
|
||||
raise ValueError('Each record requires an order_no')
|
||||
row = {key: source.get(key) for key in FIELDS}
|
||||
row['tenant_id'] = str(row['tenant_id'] or 'test')
|
||||
row['source_order_id'] = str(row['source_order_id']) if row['source_order_id'] is not None else None
|
||||
row['order_no'] = str(row['order_no']).strip()
|
||||
row['status'] = str(row['status'] or 'DRAFT')
|
||||
if row['exception_reason'] is not None:
|
||||
if not isinstance(row['exception_reason'],str) or len(row['exception_reason'])>2000:
|
||||
raise ValueError('exception_reason must be customer-visible text up to 2000 characters')
|
||||
row['exception_reason']=row['exception_reason'].strip() or None
|
||||
history = row['history_json'] or []
|
||||
if isinstance(history, str): history = json.loads(history)
|
||||
if not isinstance(history, list): raise ValueError('history_json must contain a list')
|
||||
row['history_json'] = json.dumps(history, ensure_ascii=False)
|
||||
tracking = row['tracking_json'] or []
|
||||
if isinstance(tracking, str): tracking = json.loads(tracking)
|
||||
if not isinstance(tracking, list): raise ValueError('tracking_json must contain a list')
|
||||
row['tracking_json'] = json.dumps(tracking, ensure_ascii=False)
|
||||
row['snapshot_at'] = row['snapshot_at'] or datetime.now().isoformat(timespec='seconds')
|
||||
exists = connection.execute('SELECT 1 FROM order_test_data WHERE tenant_id=? AND order_no=?',
|
||||
(row['tenant_id'], row['order_no'])).fetchone()
|
||||
if exists and not replace:
|
||||
skipped += 1
|
||||
continue
|
||||
columns = ','.join(FIELDS)
|
||||
placeholders = ','.join('?' for _ in FIELDS)
|
||||
updates = ','.join(key+'=excluded.'+key for key in FIELDS if key not in ('tenant_id', 'order_no')
|
||||
and (key!='exception_reason' or key in source))
|
||||
connection.execute(f'INSERT INTO order_test_data ({columns}) VALUES ({placeholders}) '
|
||||
f'ON CONFLICT(tenant_id,order_no) DO UPDATE SET {updates}', [row[key] for key in FIELDS])
|
||||
inserted += 1
|
||||
return {'imported': inserted, 'preserved': skipped}
|
||||
|
||||
|
||||
def import_tracking_records(connection, records, replace=False):
|
||||
"""Update tracking alone; never replace hand-edited order fields or add unknown orders."""
|
||||
init_order_table(connection)
|
||||
imported = preserved = missing = 0
|
||||
for record in records:
|
||||
if not isinstance(record, dict) or not record.get('tenant_id') or not record.get('order_no'):
|
||||
raise ValueError('Tracking record requires tenant_id and order_no')
|
||||
tracking = record.get('tracking_json')
|
||||
if isinstance(tracking, str): tracking = json.loads(tracking)
|
||||
if not isinstance(tracking, list): raise ValueError('tracking_json must contain a list')
|
||||
row = connection.execute('SELECT id,source_order_id,tracking_json FROM order_test_data '
|
||||
'WHERE tenant_id=? AND order_no=?',
|
||||
(str(record['tenant_id']), record['order_no'])).fetchone()
|
||||
if not row:
|
||||
missing += 1
|
||||
continue
|
||||
if not record.get('source_order_id') or str(record['source_order_id']) != str(row[1]):
|
||||
raise ValueError('Tracking source_order_id does not match local order')
|
||||
if not replace and row[2] not in (None, '', '[]'):
|
||||
preserved += 1
|
||||
continue
|
||||
connection.execute('UPDATE order_test_data SET tracking_json=? WHERE id=?',
|
||||
(json.dumps(tracking, ensure_ascii=False), row[0]))
|
||||
imported += 1
|
||||
return {'imported': imported, 'preserved': preserved, 'missing': missing}
|
||||
|
||||
|
||||
def tenant_filter(tenant_id=None, tenant_ids=None):
|
||||
"""Share the same server-side scope intersection for exact and aggregate reads."""
|
||||
tenant = get_setting('ORDER_DATA_TENANT_ID')
|
||||
if tenant_ids is not None:
|
||||
if not isinstance(tenant_ids,(tuple,list,set)) or not 0 < len(tenant_ids) <= 256:
|
||||
return None
|
||||
allowed = {value for value in tenant_ids if isinstance(value,str) and 0 < len(value.strip()) <= 128}
|
||||
if tenant_id is not None:
|
||||
allowed.intersection_update({str(tenant_id)})
|
||||
if tenant:
|
||||
allowed.intersection_update({str(tenant)})
|
||||
return (' AND tenant_id IN (' + ','.join('?' for _ in allowed) + ')', sorted(allowed)) if allowed else None
|
||||
if tenant_id is not None:
|
||||
if not str(tenant_id).strip() or (tenant and str(tenant_id) != str(tenant)):
|
||||
return None
|
||||
tenant = str(tenant_id)
|
||||
return (' AND tenant_id=?', [str(tenant)]) if tenant else ('', [])
|
||||
|
||||
|
||||
def lookup_order(reference, tenant_id=None, tenant_ids=None):
|
||||
"""Exact, bounded lookup; scope comes from server configuration, never model SQL."""
|
||||
from .db import connect
|
||||
|
||||
scope = tenant_filter(tenant_id, tenant_ids)
|
||||
if scope is None:
|
||||
return []
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
connection.row_factory = sqlite3.Row
|
||||
query = 'SELECT * FROM order_test_data WHERE (order_no=? OR inbound_code=? OR shipment_id=?)' + scope[0]
|
||||
values = [reference] * 3 + scope[1]
|
||||
return [dict(row) for row in connection.execute(query+' ORDER BY id LIMIT 2', values)]
|
||||
except sqlite3.Error:
|
||||
raise OrderDataUnavailable from None
|
||||
finally:
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
|
||||
|
||||
def count_orders(tenant_ids, status=None):
|
||||
"""Fresh totals require an explicit authorized scope; never fall back to all rows."""
|
||||
from .db import connect
|
||||
|
||||
empty = {'total':0, 'with_inbound':0}
|
||||
scope = tenant_filter(tenant_ids=tenant_ids if tenant_ids is not None else ())
|
||||
if scope is None or (status is not None and status not in STATUS_LABELS):
|
||||
return empty
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
query = ("SELECT COUNT(*),COUNT(NULLIF(TRIM(inbound_code,char(9)||char(10)||char(13)||' '),'')) "
|
||||
'FROM order_test_data WHERE 1=1' + scope[0])
|
||||
values = scope[1]
|
||||
if status is not None:
|
||||
query += ' AND status=?'
|
||||
values = values + [status]
|
||||
total, with_inbound = connection.execute(query,values).fetchone()
|
||||
return {'total':total, 'with_inbound':with_inbound}
|
||||
except sqlite3.Error:
|
||||
raise OrderDataUnavailable from None
|
||||
finally:
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
|
||||
|
||||
def parse_count_query(message):
|
||||
if is_lookup_help(message):return None
|
||||
from .order_query import parse_query
|
||||
return parse_query(message)
|
||||
|
||||
|
||||
def answer_count_query(intent, tenants,conv_id=None):
|
||||
from .order_listing import answer_summary
|
||||
return answer_summary(intent,tenants,conv_id)
|
||||
|
||||
|
||||
def answer_list_query(message, tenants, conv_id=None):
|
||||
from .order_listing import answer_list
|
||||
return answer_list(message,tenants,conv_id)
|
||||
|
||||
|
||||
def extract_reference(message):
|
||||
# Explicit postal/monetary fields are not order identifiers, even if invalid.
|
||||
message = re.sub(r'(?:手机号|手机号码|电话号码|联系电话|电话)\s*[::是为]?\s*(?:\+?86[-\s]?)?1[3-9]\d{9}', ' ', message)
|
||||
message = re.sub(r'(?:邮编|zip(?:\s*code)?|post\s*code)\s*[::为是]?\s*[0-9-]+', ' ', message, flags=re.I)
|
||||
message = re.sub(r'(?<![A-Za-z0-9_-])\d+(?:\.\d+)?\s*(?:万)?(?:USD|RMB|CNY|美元|美金|人民币|元)(?![A-Za-z0-9_-])',' ',message,flags=re.I)
|
||||
message = re.sub(r'\[(?:图片|文件)\]/uploads/\S+|https?://\S+', '', message)
|
||||
message = re.sub(r'(?<![A-Za-z0-9_-])\d{4}-\d{1,2}-\d{1,2}'
|
||||
r'(?:[T ]\d{1,2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?'
|
||||
r'(?![A-Za-z0-9_-])', ' ', message)
|
||||
from .pricing import DIMENSION_PATTERNS
|
||||
for pattern in DIMENSION_PATTERNS:
|
||||
def remove_dimensions(match):
|
||||
end=match.start()+len(match[0].rstrip())
|
||||
before=message[match.start()-1:match.start()] if match.start() else ''
|
||||
after=message[end:end+1]
|
||||
return match[0] if re.search(r'[A-Za-z0-9_.-]',before+after) else ' '
|
||||
message=pattern.sub(remove_dimensions,message)
|
||||
message = re.sub(r'(?<![A-Za-z0-9_.-])\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?'
|
||||
r'(?:\s*(?:inches|inch|in|cm|mm|m|英寸|厘米|毫米|米|["″]))?(?![A-Za-z0-9_.-])', ' ', message, flags=re.I)
|
||||
message = re.sub(r'(?<![A-Za-z0-9_-])\d+(?:\.\d+)?\s*'
|
||||
r'(?:kilograms?|kgs?|grams?|g|tons?|lbs?|磅|cbm|cm|mm|公斤|千克|克|吨|立方米|方|m[³3]|箱|件)'
|
||||
r'(?![A-Za-z0-9_])', ' ', message, flags=re.I)
|
||||
references = []
|
||||
for token in IDENTIFIER.findall(message):
|
||||
if (re.fullmatch(r'[A-Za-z]{2,4}[0-9][A-Za-z0-9]{0,2}',token)
|
||||
and re.search(r'美国|报价|海派|海卡|海运|\bquote\b',message,re.I)
|
||||
and not re.search(r'订单|运单|入仓|轨迹|查单|\btrack\b',message,re.I)):
|
||||
continue
|
||||
if sum(character.isdigit() for character in token) < 3:
|
||||
continue
|
||||
if re.fullmatch(r'\d{4}[-_]\d{2}[-_]\d{2}|\d+(?:KG|LBS?|CBM|CM|MM)', token, re.I):
|
||||
continue
|
||||
if token.casefold() not in [value.casefold() for value in references]:
|
||||
references.append(token)
|
||||
return references
|
||||
|
||||
|
||||
def build_card(row):
|
||||
fields = []
|
||||
def field(key, value):
|
||||
if value is not None and str(value).strip(): fields.append({'key': key, 'value': str(value)})
|
||||
field('inbound', row['inbound_code'])
|
||||
if row['inbound_code']:
|
||||
field('number', row['order_no'])
|
||||
field('shipment', row['shipment_id'])
|
||||
field('country', row['country_code'])
|
||||
field('warehouse', row['warehouse_code'])
|
||||
field('transport', {'SEA':'海运', 'AIR':'空运', 'RAIL':'铁路', 'TRUCK':'卡航'}.get(row['transport_mode'], row['transport_mode']))
|
||||
field('packages', row['package_count'])
|
||||
field('weight', str(row['gross_weight_kg'])+' kg' if row['gross_weight_kg'] is not None else None)
|
||||
field('volume', str(row['volume_cbm'])+' m³' if row['volume_cbm'] is not None else None)
|
||||
field('role', {'CHILD':'子订单', 'MASTER':'主订单'}.get(row['order_role']))
|
||||
field('parent', row['parent_order_no'])
|
||||
field('updated', row['source_updated_at'])
|
||||
try:
|
||||
history = json.loads(row['history_json'])
|
||||
except (ValueError, TypeError):
|
||||
history = []
|
||||
nodes = [{'time': str(event.get('time') or ''),
|
||||
'text': STATUS_LABELS.get(str(event.get('status')), str(event.get('status') or '状态更新')), 'place': ''}
|
||||
for event in history[-50:] if isinstance(event, dict)] if isinstance(history, list) else []
|
||||
nodes.reverse()
|
||||
status = STATUS_LABELS.get(row['status'], row['status'])
|
||||
inbound = row['inbound_code']
|
||||
summary = f"入仓码 {inbound},业务状态:{status}。" if inbound else f"订单号 {row['order_no']},业务状态:{status}。"
|
||||
summary += ';'.join(FIELD_LABELS[item['key']]+':'+item['value'] for item in fields if item['key'] != 'inbound')
|
||||
card = {'kind':'order', 'no':row['order_no'], 'status':status, 'fields':fields,
|
||||
'nodes':nodes, 'summary':summary}
|
||||
tracking = build_tracking(row.get('tracking_json'))
|
||||
if tracking:
|
||||
card.update(node_kind='logistics', nodes=tracking['nodes'],
|
||||
estimated_nodes=tracking['estimated_nodes'], tracking_status=tracking['status'])
|
||||
facts = tracking['nodes'][:10] + tracking['estimated_nodes'][:5]
|
||||
card['summary'] += '。物流状态:' + (tracking['status'] or '暂无实际节点') + '。'
|
||||
card['summary'] += ';'.join(f"{node['time']} {node['text']} {node['place']}" for node in facts)
|
||||
return card
|
||||
|
||||
|
||||
def is_lookup_help(message):
|
||||
if re.search(r'是什么意思|指什么|怎么(?:查|操作|使用)|如何(?:查|操作|使用)|怎样(?:查|操作|使用)|'
|
||||
r'\bhow\s+(?:do|can|to)\b', message, re.I):
|
||||
return True
|
||||
if re.fullmatch(r'\s*(?:请问)?(?:物流轨迹|物流状态|订单状态|入仓码|入仓号)是什么[。?!?!\s]*', message):
|
||||
return True
|
||||
return bool(re.search(r'\bwhat\s+(?:is|are)\b', message, re.I) and
|
||||
not re.search(r'\b(?:my|this|that|our)\b', message, re.I))
|
||||
|
||||
|
||||
def is_tracking_request(message):
|
||||
"""Bounded tracking commands also work without an identifier or prior context."""
|
||||
question = re.sub(r'[\s,,。.!!??、::]', '', message)
|
||||
command = (r'(?:请问|请|麻烦)?(?:帮我)?(?:查(?:询|一下|下)?(?:物流(?:轨迹|进度|状态)?|轨迹|进度|货)|'
|
||||
r'(?:物流|轨迹|进度)(?:查询|查一下|查下))')
|
||||
personal = (r'(?:我的|(?:我)?(?:这|那)(?:票|个|单)|该)(?:货物?|包裹|快递|订单|运单)'
|
||||
r'(?:现在|目前)?(?:到哪(?:里)?了?|什么时候(?:能|会)?到|何时能?到|多久能?到|'
|
||||
r'(?:已)?(?:清关|开船|到港|出库|提柜)(?:了)?(?:吗|没|了吗|没有)?|签收了?(?:吗|没)|状态|进度|轨迹)(?:呢|吗|呀|啊)?')
|
||||
english = (r'(?:where\s+(?:is|are)\s+my|track(?:\s+my)?|check(?:\s+my)?)\s+'
|
||||
r'(?:parcels?|packages?|shipments?|orders?)(?:\s+(?:status|progress))?|'
|
||||
r'what\s+is\s+my\s+(?:parcel|package|shipment|order)\s+(?:status|progress)')
|
||||
return bool(re.fullmatch(command+'|'+personal, question) or
|
||||
re.fullmatch(english, message.strip(' \t\r\n.!?'), re.I))
|
||||
|
||||
|
||||
def is_order_followup(message):
|
||||
"""Reuse an order only for an explicit reference or a short detail question."""
|
||||
from .order_explanations import detail_question
|
||||
if detail_question(message) and not re.search(r'报价|价格|多少钱|公斤|\bKG\b|海派|海卡',message,re.I):
|
||||
return True
|
||||
if is_lookup_help(message):
|
||||
return False
|
||||
if is_tracking_request(message):
|
||||
return True
|
||||
if not re.search(ORDER_DETAIL, message):
|
||||
return False
|
||||
if re.search(r'(?:这|那|该)(?:个|票|单|笔)|该订单|刚才|上一(?:票|单|个订单)', message):
|
||||
return True
|
||||
question = re.sub(r'[\s,,。.!!??、::]', '', message)
|
||||
details = (
|
||||
r'(?:(?:(?:物流|运输)?(?:状态|进度|轨迹)|重量|毛重|体积|件数|箱数|目的地|目的国|目的仓|仓库|父订单|运费|费用|价格)'
|
||||
r'(?:(?:是|有|为)?(?:多少|什么|怎么样|怎样|如何|哪个))?|(?:有)?(?:几件|几箱|多少公斤|多少千克|多少钱))'
|
||||
r'(?:呢|吗|呀|啊)?')
|
||||
tracking = (
|
||||
r'(?:(?:到哪(?:里)?|开船|到港|清关|提柜|还柜|签收)(?:了)?(?:呢|吗|没|了吗|没有)?|'
|
||||
r'(?:预计)?(?:什么时候|何时|多久)(?:能|会|可以)?(?:到|到达|到港|到仓|到货|送到)(?:呢|呀|啊)?|还要多久)')
|
||||
return bool(re.fullmatch(
|
||||
r'(?:那|那么|还有|请问|请|查一下|看一下|现在|目前)?(?:它的|订单的)?'
|
||||
r'(?:'+details+'|'+tracking+')', question))
|
||||
|
||||
|
||||
def answer_query(message, conv_id):
|
||||
references = extract_reference(message)
|
||||
tenants = customer_tenant_ids()
|
||||
from .order_explanations import general_explanation, detail_question, explain_order
|
||||
if not references:
|
||||
explanation=general_explanation(message)
|
||||
if explanation:return {'t':explanation}
|
||||
count_intent = parse_count_query(message) if not references else None
|
||||
if count_intent is not None:
|
||||
return answer_count_query(count_intent,tenants,conv_id)
|
||||
if not references:
|
||||
listed=answer_list_query(message,tenants,conv_id)
|
||||
if listed is not None:return listed
|
||||
mutation=bool(re.search(r'改址|改.*(?:收货|收件).*地址|修改.*(?:收件|地址|订单)|(?:收货|收件)地址.*改|(?:取消|删除).*(?:订单|运单)|(?:订单|运单).*取消',message))
|
||||
if references and not tenants:
|
||||
return order_login_response()
|
||||
if len(references) > 1:
|
||||
return {'t':'请一次提供一个入仓码,避免查错订单。'}
|
||||
reference = references[0] if references else None
|
||||
if not reference and conv_id and is_order_followup(message):
|
||||
from .db import connect
|
||||
connection = connect()
|
||||
try:
|
||||
recent = connection.execute('SELECT role,content FROM messages WHERE conv_id=? ORDER BY id DESC LIMIT 12', (conv_id,)).fetchall()
|
||||
finally:
|
||||
connection.close()
|
||||
for role, content in recent:
|
||||
if role == 'user':
|
||||
earlier_references = extract_reference(content)
|
||||
if earlier_references:
|
||||
reference = earlier_references[0] if len(earlier_references) == 1 else None
|
||||
break
|
||||
if not is_order_followup(content):
|
||||
break
|
||||
if role == 'assistant' and content.startswith('__CARD__'):
|
||||
try:
|
||||
previous = json.loads(content[8:])
|
||||
if previous.get('kind') == 'order':
|
||||
reference = previous['no']
|
||||
break
|
||||
except (ValueError, KeyError, TypeError):
|
||||
pass
|
||||
if not reference:
|
||||
if mutation:
|
||||
return order_login_response() if not tenants else {'t':'当前支持查询订单与物流轨迹;改址、取消等操作请联系人工客服办理,尚未修改订单。请提供入仓码。'}
|
||||
if detail_question(message) and not is_lookup_help(message):
|
||||
return order_login_response() if not tenants else {'t':'请提供入仓码,我先核对该票订单的实际物流记录。'}
|
||||
if re.search(r'哪些.*(?:订单|运单)|(?:订单|运单).*(?:筛选|还没开船|未发货|已发货|未签收)',message) and not is_lookup_help(message):
|
||||
return order_login_response() if not tenants else {'t':'暂不支持按这个物流条件批量筛选订单。可按业务状态查看列表,或提供入仓码逐票核对实际物流节点。'}
|
||||
if is_tracking_request(message) or (not is_lookup_help(message) and re.search(r'(?:查|搜|看|找).*(?:订单|运单|物流轨迹|入仓码|入仓号)|(?:入仓码|入仓号).*(?:查|轨迹|状态)|订单状态|物流轨迹|shipment\s*id|'
|
||||
r'(?:列出|搜索|所有|全部|多少|我的).*(?:订单|运单|入仓)|(?:订单|运单).*(?:多少|列表|查询|在哪|到哪|进度)|'
|
||||
r'^\s*(?:查单|查询|查一下|帮我查一下)[。?!?!\s]*$|'
|
||||
r'\b(?:my|find|lookup|track)\s+(?:orders?|shipments?)\b|\b(?:order|shipment)\s+(?:status|tracking|lookup)\b|'
|
||||
r'\b(?:track|lookup|find|search)\b.*\binbound\b|\binbound\s+(?:code|number)\s+(?:lookup|tracking|status)\b', message, re.I)):
|
||||
return order_login_response() if not tenants else {'t':'请提供入仓码查询订单和物流轨迹。'}
|
||||
return None
|
||||
if not tenants:
|
||||
return order_login_response()
|
||||
try:
|
||||
matches = lookup_order(reference,tenant_id=tenants[0]) if len(tenants) == 1 else lookup_order(reference,tenant_ids=tenants)
|
||||
except OrderDataUnavailable:
|
||||
return {'t':'订单信息暂时无法读取,请稍后重试。'}
|
||||
if not matches:
|
||||
return {'t':f'未找到“{reference}”对应的订单。请核对入仓码,或联系人工客服。'}
|
||||
if len(matches) > 1:
|
||||
return {'t':'该标识匹配到多个订单,请提供完整入仓码或联系人工客服确认。'}
|
||||
if mutation:
|
||||
return {'t':f'已查到订单“{reference}”。当前支持查询订单与物流轨迹;改址、取消等操作请联系人工客服办理,尚未修改订单。','_customer_data':True}
|
||||
if re.search(r'运费|费用|多少钱|价格', message):
|
||||
return {'t':'该订单未记录实际运费,请联系人工客服核实。','_customer_data':True}
|
||||
card=build_card(matches[0])
|
||||
explanation=explain_order(message,matches[0],card)
|
||||
if explanation:return {'t':explanation,'_customer_data':True}
|
||||
return {'card':card}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Explain recorded order facts without inferring delivery or operational writes."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def detail_question(message):
|
||||
if re.search(r'报价|运费|海派|海卡|\d+\s*(?:KG|公斤)',message,re.I) and not re.search(r'这票|该订单|我的订单',message):
|
||||
return False
|
||||
return bool(re.search(r'异常原因|为什么异常|什么异常|上架|没更新|未更新|没有更新|不更新|少了?.*(?:箱|件)|到了?几箱|逐箱|每箱.*签收|'
|
||||
r'已完成.*(?:签收|送达)|(?:签收|送达).*已完成|催单|催一下|拦截|改.*(?:收货|收件).*地址|(?:收货|收件)地址.*改|快递单号|付过款|付款状态|'
|
||||
r'(?:这票|该订单|我的货).*(?:发货|发走|出库|开船)',message))
|
||||
|
||||
|
||||
def general_explanation(message):
|
||||
if re.search(r'我的|这票|这单|这个订单|该订单',message):return None
|
||||
if re.search(r'已完成|履约中|上架',message) and re.search(r'是什么意思|是否代表|是不是|等于|有什么区别',message):
|
||||
return '“履约中”“头程订单已完成”属于业务状态;出库、开船、到港等以实际物流节点为准。业务完成不等于收件人签收,签收也不等于亚马逊已上架;上架需以亚马逊入库记录核实。'
|
||||
return None
|
||||
|
||||
|
||||
def explain_order(message,row,card):
|
||||
if not detail_question(message):return None
|
||||
reference=row.get('inbound_code') or row['order_no']
|
||||
lines=[f'入仓码 {reference}。' if row.get('inbound_code') else f'订单号 {reference}。']
|
||||
if re.search(r'异常原因|为什么异常|什么异常',message):
|
||||
reason=(row.get('exception_reason') or '').strip()
|
||||
return lines[0]+('已记录的异常原因:'+reason if reason else '当前未登记异常原因,请联系人工核实。')
|
||||
if re.search(r'催单|催一下|拦截',message):
|
||||
return lines[0]+'催单或拦截需联系人工客服办理;当前仅查询订单,尚未提交催单或拦截申请。'
|
||||
if re.search(r'付过款|付款状态',message):
|
||||
return lines[0]+'当前订单未接入付款状态,不能根据业务状态判断是否付款,请联系人工核对账单。'
|
||||
if '快递单号' in message:
|
||||
return lines[0]+'当前未记录可核实的UPS/FedEx尾程快递单号,入仓码和内部订单号不能直接当作快递单号,请联系人工核对。'
|
||||
lines.append(f'登记的业务状态为“{card["status"]}”。')
|
||||
actual=card.get('nodes',[]) if card.get('node_kind')=='logistics' else []
|
||||
if actual:
|
||||
latest=actual[0]
|
||||
lines.append('最近一条实际物流记录:'+' '.join(str(latest.get(k) or '') for k in ('time','text','place')).strip()+'。')
|
||||
else:lines.append('当前没有已记录的实际物流节点,不能根据业务状态推断货物位置。')
|
||||
if re.search(r'上架|已完成|签收|送达',message):
|
||||
lines.append('头程业务完成不等于收件人签收;当前节点不能用于确认亚马逊上架。上架结果需核对亚马逊入库记录。')
|
||||
if re.search(r'没更新|未更新|没有更新|不更新',message):
|
||||
lines.append('未更新期间的实际位置和原因无法从现有记录确定,可提供入仓码联系人工核查。')
|
||||
if re.search(r'发货|发走|出库|开船',message):
|
||||
lines.append('计划发货或开船安排需联系人工核对,不能根据业务状态承诺未来发货日期。')
|
||||
if re.search(r'少了?.*(?:箱|件)|到了?几箱|逐箱|每箱.*签收',message):
|
||||
if row.get('package_count') is not None:lines.append(f'登记总件数为{row["package_count"]}件。')
|
||||
lines.append('当前没有逐箱签收明细,不能把整票业务状态当作每箱均已送达,请联系人工核实各箱情况。')
|
||||
return '\n'.join(lines)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Scoped summaries, five-row previews and durable conversational list pages."""
|
||||
|
||||
from collections import Counter,deque
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from .db import connect
|
||||
from .order_query import parse_query,filters,STAGE_LABELS
|
||||
from .order_tracking import current_stage
|
||||
|
||||
|
||||
def page_command(message):
|
||||
text=re.sub(r'[\s,,。.!!??]','',message)
|
||||
match=re.fullmatch(r'(?:请)?(?:订单)?第(\d{1,5})页',text)
|
||||
if match:return int(match.group(1))
|
||||
if re.fullmatch(r'(?:请|继续)?(?:下一页|下页|继续显示|接着显示(?:剩下的)?订单)',text):return 'next'
|
||||
if re.fullmatch(r'(?:请)?(?:上一页|上页)',text):return 'previous'
|
||||
return None
|
||||
|
||||
|
||||
def valid_filters(query):
|
||||
from .order_data import STATUS_LABELS
|
||||
return (isinstance(query,dict) and set(query)=={'status','stage','exception'}
|
||||
and (query['status'] is None or query['status'] in STATUS_LABELS)
|
||||
and (query['stage'] is None or query['stage'] in STAGE_LABELS)
|
||||
and isinstance(query['exception'],bool))
|
||||
|
||||
|
||||
def load_state(conv_id):
|
||||
from .customer_service import current_customer_id,current_scope_key
|
||||
from .visitor_service import visitor_id
|
||||
if not conv_id:return None
|
||||
connection=connect()
|
||||
try:
|
||||
row=connection.execute('SELECT order_list_state FROM chat_history WHERE id=? AND visitor_id=? '
|
||||
'AND customer_id=? AND customer_scope=?',
|
||||
(conv_id,visitor_id(),current_customer_id(),current_scope_key())).fetchone()
|
||||
state=json.loads(row[0]) if row and row[0] else None
|
||||
if not isinstance(state,dict) or not valid_filters(state.get('query')):return None
|
||||
if type(state.get('page')) is not int or not 1<=state['page']<=10000:return None
|
||||
if state.get('size') not in (5,20) or type(state.get('message_id')) is not int:return None
|
||||
for (text,) in connection.execute("SELECT content FROM messages WHERE conv_id=? AND role='user' AND id>? ORDER BY id",
|
||||
(conv_id,state['message_id'])):
|
||||
if page_command(text) is None and parse_query(text) is None and text.strip() not in ('查看全部','查看全部订单'):
|
||||
return None
|
||||
return state
|
||||
except (ValueError,TypeError):return None
|
||||
finally:connection.close()
|
||||
|
||||
|
||||
def save_state(conv_id,state,message_id):
|
||||
"""Called only after the reply and customer binding have been persisted."""
|
||||
from .customer_service import current_customer_id,current_scope_key
|
||||
from .visitor_service import visitor_id
|
||||
if not conv_id or type(message_id) is not int:return
|
||||
connection=connect()
|
||||
try:
|
||||
state=dict(state)
|
||||
state['message_id']=message_id
|
||||
connection.execute('UPDATE chat_history SET order_list_state=? WHERE id=? AND visitor_id=? '
|
||||
'AND customer_id=? AND customer_scope=? '
|
||||
'AND NOT EXISTS(SELECT 1 FROM messages WHERE conv_id=? AND id>?)',
|
||||
(json.dumps(state,ensure_ascii=False),conv_id,visitor_id(),current_customer_id(),current_scope_key(),conv_id,message_id))
|
||||
connection.commit()
|
||||
finally:connection.close()
|
||||
|
||||
|
||||
def read_orders(tenants,query,page=1,size=5):
|
||||
"""One scoped snapshot; each order occupies one actual-node bucket."""
|
||||
from .order_data import tenant_filter
|
||||
scope=tenant_filter(tenant_ids=tenants)
|
||||
if scope is None or not valid_filters(query):raise ValueError('Explicit customer scope and filters required')
|
||||
connection=connect()
|
||||
try:
|
||||
connection.row_factory=sqlite3.Row
|
||||
where=' WHERE 1=1'+scope[0];values=scope[1]
|
||||
if query['status']:where+=' AND status=?';values=values+[query['status']]
|
||||
connection.execute('BEGIN')
|
||||
rows=connection.execute('SELECT order_no,inbound_code,status,warehouse_code,tracking_json,exception_reason '
|
||||
'FROM order_test_data'+where+' ORDER BY COALESCE(julianday(source_updated_at),julianday(snapshot_at),0) DESC,id DESC',values)
|
||||
total=with_inbound=0;groups=Counter();selected=[];tail=deque(maxlen=size)
|
||||
for row in rows:
|
||||
item=dict(row)
|
||||
item['exception_reason']=(item['exception_reason'] or '').strip()
|
||||
if query['exception'] and not item['exception_reason']:continue
|
||||
item['stage']=current_stage(item.pop('tracking_json'))
|
||||
if query['stage'] and query['stage']!=item['stage']:continue
|
||||
total+=1;with_inbound+=bool((item['inbound_code'] or '').strip());groups[item['stage']]+=1
|
||||
tail.append(item)
|
||||
if (page-1)*size<total<=page*size:selected.append(item)
|
||||
last=max(1,(total+size-1)//size)
|
||||
if page>last:
|
||||
page=last;selected=list(tail)[-(total-(last-1)*size):] if total else []
|
||||
return {'total':total,'with_inbound':with_inbound,'groups':groups,'rows':selected,'page':page}
|
||||
finally:connection.close()
|
||||
|
||||
|
||||
def row_text(row):
|
||||
from .order_data import STATUS_LABELS
|
||||
def clean(value):return re.sub(r'[\r\n\t]+',' ',str(value or '未登记'))
|
||||
text=f'- 入仓码:{clean(row["inbound_code"])};订单号:{clean(row["order_no"])};业务状态:{STATUS_LABELS.get(row["status"],row["status"])};目的仓:{clean(row["warehouse_code"])};当前节点:{STAGE_LABELS[row["stage"]]}'
|
||||
if row['exception_reason']:text+=';异常原因:'+clean(row['exception_reason'])
|
||||
return text
|
||||
|
||||
|
||||
def unsupported(listing=False):
|
||||
return {'t':f'暂不支持按这个条件{"列出订单" if listing else "统计"}。可以查询订单总数、业务状态、明确标记的异常,或按当前实际物流节点统计;请一次指定一个节点。'}
|
||||
|
||||
|
||||
def answer_summary(intent,tenants,conv_id=None):
|
||||
from .customer_service import order_login_response
|
||||
from .order_data import STATUS_LABELS
|
||||
if not tenants:return order_login_response()
|
||||
if intent['unsupported']:return unsupported()
|
||||
query=filters(intent)
|
||||
try:
|
||||
data=read_orders(tenants,query)
|
||||
total=data['total']
|
||||
if query['stage']:
|
||||
text=f'您当前有 {total} 票当前节点为“{STAGE_LABELS[query["stage"]]}”的订单'
|
||||
elif query['status']:
|
||||
text=f'您当前有 {total} 票业务状态为“{STATUS_LABELS[query["status"]]}”的订单'
|
||||
elif query['exception']:text=f'您当前有 {total} 票明确标记异常的订单'
|
||||
else:text=f'您当前共有 {total} 票订单'
|
||||
if query['exception'] and (query['stage'] or query['status']):text+='(已明确标记异常)'
|
||||
if query['stage'] and query['status']:text+=f'(业务状态:{STATUS_LABELS[query["status"]]})'
|
||||
lines=[text+f',其中 {data["with_inbound"]} 票已登记入仓码。']
|
||||
if intent.get('grouped'):
|
||||
lines.append('按当前实际物流节点分布(每票只计一次):')
|
||||
lines.extend(f'- {label}:{data["groups"][code]}票' for code,label in STAGE_LABELS.items() if data['groups'][code])
|
||||
if data['rows']:
|
||||
lines.append(f'最近更新的{len(data["rows"])}票:')
|
||||
lines.extend(row_text(row) for row in data['rows'])
|
||||
lines.append('回复“查看全部”展开列表,或发送入仓码查询详情。')
|
||||
state={'query':query,'page':1,'size':5}
|
||||
previous=load_state(conv_id)
|
||||
if previous and previous['query']==query:state={key:previous[key] for key in ('query','page','size')}
|
||||
return {'t':'\n'.join(lines),'_customer_data':True,'_order_list_state':state}
|
||||
except sqlite3.Error:return {'t':'订单信息暂时无法读取,请稍后重试。'}
|
||||
|
||||
|
||||
def answer_list(message,tenants,conv_id=None):
|
||||
from .order_data import is_lookup_help,STATUS_LABELS
|
||||
from .customer_service import order_login_response
|
||||
command=page_command(message)
|
||||
expand=message.strip(' ,,。.!!??') in ('查看全部','查看全部订单')
|
||||
initial=(not is_lookup_help(message) and re.search(r'订单|运单|\borders?\b|\bshipments?\b',message,re.I)
|
||||
and re.search(r'列出|列表|全部|所有|\blist\b',message,re.I))
|
||||
if command is None and not initial and not expand:return None
|
||||
if not tenants:return order_login_response()
|
||||
try:
|
||||
previous=load_state(conv_id)
|
||||
if command is not None or expand:
|
||||
if not previous:return {'t':'请先在当前对话中发送“列出我的订单”或查询订单数量,再翻页查看。'}
|
||||
query=previous['query'];size=20 if expand else previous['size']
|
||||
page=1 if expand else int(command) if isinstance(command,int) else max(1,previous['page']+(1 if command=='next' else -1))
|
||||
if not 1<=page<=10000:return {'t':'请提供1至10000之间的有效页码。'}
|
||||
else:
|
||||
intent=parse_query(message,listing=True)
|
||||
if intent is None or intent['unsupported']:return unsupported(True)
|
||||
query=filters(intent);page=1;size=20
|
||||
data=read_orders(tenants,query,page,size);page=data['page'];total=data['total']
|
||||
state={'query':query,'page':page,'size':size}
|
||||
if not total:return {'t':'当前账号下没有符合条件的订单。','_customer_data':True,'_order_list_state':state}
|
||||
label=STATUS_LABELS[query['status']] if query['status'] else '全部'
|
||||
first=f'先列出{size}票;' if page==1 and total>size else ''
|
||||
extra=(';当前节点:'+STAGE_LABELS[query['stage']] if query['stage'] else '')+(';明确标记异常' if query['exception'] else '')
|
||||
lines=[f'您当前的订单列表({first}第{page}页;业务状态:{label}{extra}):',f'共{total}票,当前显示第{(page-1)*size+1}至{(page-1)*size+len(data["rows"])}票。']
|
||||
lines.extend(row_text(row) for row in data['rows'])
|
||||
lines.append('回复“下一页”查看后续订单。' if page*size<total else '当前已是最后一页。')
|
||||
lines.append('发送入仓码可查询该票订单和物流轨迹。')
|
||||
return {'t':'\n'.join(lines),'_customer_data':True,'_order_list_state':state}
|
||||
except sqlite3.Error:return {'t':'订单信息暂时无法读取,请稍后重试。'}
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Recognize explicit, whitelisted order summary and list filters."""
|
||||
|
||||
import re
|
||||
|
||||
from .order_tracking import NODE_LABELS
|
||||
|
||||
|
||||
NODE_PHRASES = (
|
||||
('DOMESTIC_RECEIVED',r'已入国内仓|已入仓'),
|
||||
('LOADING_COMPLETED',r'已完成装柜|已装柜'),
|
||||
('DEPARTED_WAREHOUSE',r'已离开国内仓库|已离仓|已出库'),
|
||||
('AT_ORIGIN_PORT',r'重箱已进入起运港或码头|已到起运港|已进起运港'),
|
||||
('LOADED_ON_VESSEL',r'已装船'),
|
||||
('DEPARTED_ORIGIN_PORT',r'船舶已离开起运港|已开船|开船'),
|
||||
('IN_TRANSIT',r'海运途中|运输中|在途|海上'),
|
||||
('ARRIVED_DESTINATION_PORT',r'船舶已到目的港|已到目的港|已到港|到港'),
|
||||
('DISCHARGED_FROM_VESSEL',r'已卸船、未清关|卸船未清关|已卸船|卸船'),
|
||||
('PICKUP_READY',r'已清关、可提柜|已清关|清关完成|可提柜'),
|
||||
('PICKED_UP',r'已提柜|提柜'),
|
||||
('EMPTY_RETURNED',r'已还柜|还柜'),
|
||||
('NO_ACTUAL',r'没有实际轨迹|暂无实际节点|没有轨迹|无轨迹'),
|
||||
('MIXED',r'多柜进度不一致|多柜进度不同'),
|
||||
)
|
||||
STAGE_LABELS = {code:labels[1] for code,labels in NODE_LABELS.items()}
|
||||
STAGE_LABELS.update(NO_ACTUAL='暂无实际节点',MIXED='多柜进度不同')
|
||||
STATUSES = (('头程订单已完成','COMPLETED'),('已完成','COMPLETED'),('履约中','PROCESSING'),
|
||||
('处理中','PROCESSING'),('已取消','CANCELLED'),('审核通过','APPROVED'),
|
||||
('审核驳回','REJECTED'),('已接单','ACCEPTED'),('已提交','SUBMITTED'),('草稿','DRAFT'))
|
||||
NOUN = r'订单|运单|入仓码|入仓号|\borders?\b|\bshipments?\b'
|
||||
COUNT = r'多少|几(?:个|票|条|张|笔)|总数|数量|总量|统计|数一下|(?:订单|运单)数(?!量)|\bhow\s+many\b|\bcount\b|\bnumber\b|\btotal\b'
|
||||
|
||||
|
||||
def parse_query(message,listing=False):
|
||||
if not re.search(NOUN,message,re.I):return None
|
||||
if not listing and not (re.search(COUNT,message,re.I) or re.search(r'分布|(?:都|分别).*到哪',message)):return None
|
||||
if re.search(r'公斤|千克|\bkg\b|重量|毛重|体积|件数|箱数|运费|费用|价格|多少钱',message,re.I):return None
|
||||
remaining=message
|
||||
statuses=[];nodes=[]
|
||||
# Unknown/negated logistics conditions must never silently become a total.
|
||||
unsupported=bool(re.search(r'未到港|没到港|还没|未开船|未发货|未签收|已签收|已送达|曾经|曾到|到过|正常订单|无异常',remaining))
|
||||
for code,pattern in NODE_PHRASES:
|
||||
if re.search(pattern,remaining):
|
||||
nodes.append(code);remaining=re.sub(pattern,'',remaining)
|
||||
for phrase,status in STATUSES:
|
||||
if phrase in remaining:
|
||||
statuses.append(status);remaining=remaining.replace(phrase,'')
|
||||
exception=bool(re.search(r'异常',remaining))
|
||||
remaining=re.sub(r'物流异常|异常','',remaining)
|
||||
grouped=not nodes and bool(re.search(r'轨迹|节点|阶段|到哪',remaining))
|
||||
remaining=re.sub(r'物流轨迹|物流节点|当前节点|轨迹|节点|阶段|到哪里|到哪|各自|各个|每个|分别|分布|各|都|了', '',remaining)
|
||||
remaining=re.sub(COUNT+'|'+NOUN,'',remaining,flags=re.I)
|
||||
remaining=re.sub(r'当前账号|当前账户|账号下|账户下|名下|可查询|能查到|可以查到|目前|现在|当前|一共|总共|合计|总计|'
|
||||
r'请问|麻烦|帮我|想知道|想查|想看|请|查询|查一下|查下|查查|看一下|看看|看下|一下|下|列出|列表|显示|全部|所有|共有|我的|我|能|有|的|个|票|条|张|笔|呢|吗|呀|啊|共|'
|
||||
r'\b(?:list|what|is|of|do|i|have|are|there|my|in|all|the|currently)\b|[\s,,。.!!??、::]','',remaining,flags=re.I)
|
||||
return {'status':statuses[0] if statuses else None,'stage':nodes[0] if nodes else None,
|
||||
'exception':exception,'grouped':grouped,
|
||||
'unsupported':bool(unsupported or remaining or len(set(statuses))>1 or len(set(nodes))>1)}
|
||||
|
||||
|
||||
def filters(intent):
|
||||
return {key:intent.get(key) for key in ('status','stage','exception')}
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Customer tracking derived from explicit order-linked facts, without inference."""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
# Maritime codes follow the firstleg standard; warehouse facts remain distinct.
|
||||
NODE_LABELS = {
|
||||
'DOMESTIC_RECEIVED': (0, '已入国内仓', '预计入国内仓'),
|
||||
'LOADING_COMPLETED': (5, '已完成装柜', '预计完成装柜'),
|
||||
'DEPARTED_WAREHOUSE': (10, '已离开国内仓库', '预计离开国内仓库'),
|
||||
'AT_ORIGIN_PORT': (20, '重箱已进入起运港或码头', '预计进入起运港或码头'),
|
||||
'LOADED_ON_VESSEL': (30, '已装船', '预计装船'),
|
||||
'DEPARTED_ORIGIN_PORT': (40, '船舶已离开起运港', '预计离开起运港'),
|
||||
'IN_TRANSIT': (50, '海运途中', '预计进入海运阶段'),
|
||||
'ARRIVED_DESTINATION_PORT': (60, '船舶已到目的港', '预计到达目的港'),
|
||||
'DISCHARGED_FROM_VESSEL': (70, '已卸船、未清关', '预计卸船'),
|
||||
'PICKUP_READY': (80, '已清关、可提柜', '预计可提柜'),
|
||||
'PICKED_UP': (90, '已提柜', '预计提柜'),
|
||||
'EMPTY_RETURNED': (100, '已还柜', '预计还柜'),
|
||||
}
|
||||
|
||||
|
||||
def parse_time(value):
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return None
|
||||
try:
|
||||
result = datetime.fromisoformat(value.strip().replace('Z', '+00:00'))
|
||||
if result.tzinfo:
|
||||
result = result.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return result
|
||||
except (ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def tracking_facts(raw):
|
||||
"""Share the same corrections and actual/estimated split with aggregation."""
|
||||
try:
|
||||
facts = json.loads(raw) if isinstance(raw, str) else raw
|
||||
except (ValueError, TypeError):
|
||||
return {},{}
|
||||
if not isinstance(facts, list):
|
||||
return {},{}
|
||||
actual, estimated = {}, {}
|
||||
for index, fact in enumerate(facts):
|
||||
if not isinstance(fact, dict) or not isinstance(fact.get('code'), str) or fact['code'] not in NODE_LABELS:
|
||||
continue
|
||||
shipment = str(fact.get('shipment_key') or '')
|
||||
key = (shipment, fact['code'])
|
||||
observation = parse_time(fact.get('observed_at')) or parse_time(fact.get('created_at')) or datetime.min
|
||||
for field, target in (('actual_at', actual), ('estimated_at', estimated)):
|
||||
when = parse_time(fact.get(field))
|
||||
if when is None:
|
||||
continue
|
||||
candidate = (observation, index, when, fact)
|
||||
if key not in target or candidate[:2] > target[key][:2]:
|
||||
target[key] = candidate
|
||||
return actual,estimated
|
||||
|
||||
|
||||
def current_stage(raw):
|
||||
actual,estimated=tracking_facts(raw)
|
||||
progress={}
|
||||
for (shipment,code) in actual:
|
||||
if shipment not in progress or NODE_LABELS[code][0]>NODE_LABELS[progress[shipment]][0]:
|
||||
progress[shipment]=code
|
||||
shipments={shipment for shipment,_ in actual.keys() | estimated.keys() if shipment}
|
||||
if shipments:
|
||||
if not any(shipment in progress for shipment in shipments) and '' in progress:return progress['']
|
||||
progress={shipment:progress.get(shipment,'NO_ACTUAL') for shipment in shipments}
|
||||
codes=set(progress.values())
|
||||
return next(iter(codes)) if len(codes)==1 else 'MIXED' if codes else 'NO_ACTUAL'
|
||||
|
||||
|
||||
def build_tracking(raw):
|
||||
"""Latest observation corrects a milestone; forecasts never advance progress."""
|
||||
actual,estimated=tracking_facts(raw)
|
||||
if not actual and not estimated:return None
|
||||
|
||||
shipments = sorted({key[0] for key in actual.keys() | estimated.keys()} - {''})
|
||||
multiple = len(shipments) > 1
|
||||
progress = {}
|
||||
for (shipment, code), (_, _, when, fact) in actual.items():
|
||||
sequence = NODE_LABELS[code][0]
|
||||
if shipment not in progress or sequence > progress[shipment][0]:
|
||||
progress[shipment] = (sequence, code, fact)
|
||||
|
||||
def label_shipment(shipment, fact):
|
||||
if not multiple or not shipment:
|
||||
return ''
|
||||
return '货柜 ' + str(fact.get('shipment_no') or (shipments.index(shipment) + 1))
|
||||
|
||||
def node(shipment, code, value, forecast=False):
|
||||
_, _, when, fact = value
|
||||
place = str(fact.get('place') or '')
|
||||
scope = label_shipment(shipment, fact)
|
||||
return {'time': str(fact['estimated_at' if forecast else 'actual_at']),
|
||||
'text': NODE_LABELS[code][2 if forecast else 1],
|
||||
'place': ' · '.join(part for part in (scope, place) if part)}
|
||||
|
||||
nodes = [node(shipment, code, value) for (shipment, code), value in
|
||||
sorted(actual.items(), key=lambda item: (item[1][2], NODE_LABELS[item[0][1]][0]), reverse=True)]
|
||||
forecasts = [node(shipment, code, value, True) for (shipment, code), value in
|
||||
sorted(estimated.items(), key=lambda item: item[1][2])
|
||||
if (shipment, code) not in actual and NODE_LABELS[code][0] > progress.get(shipment, (-1,))[0]]
|
||||
# Multiple containers keep independent progress rather than claiming the whole order advanced.
|
||||
current = [(shipment, value) for shipment, value in sorted(progress.items()) if shipment or not shipments]
|
||||
if not current and '' in progress:
|
||||
current = [('', progress[''])]
|
||||
statuses = [':'.join(part for part in (label_shipment(shipment, value[2]), NODE_LABELS[value[1]][1]) if part)
|
||||
for shipment, value in current]
|
||||
return {'nodes': nodes[:50], 'estimated_nodes': forecasts[:20], 'status': ';'.join(statuses)}
|
||||
@@ -0,0 +1,381 @@
|
||||
"""Extracted pricing rules with unchanged business behavior."""
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
try:
|
||||
from . import rates_extra as RX
|
||||
except Exception:
|
||||
RX = None
|
||||
|
||||
RATES = {
|
||||
"sea": {
|
||||
"name": "欧洲海运快线(双清/递延)",
|
||||
"tiers": [(2000, 10.0), (500, 10.2), (101, 10.3), (21, 12.3)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "开船后 38-45 天提取",
|
||||
"min_pcs_kg": None,
|
||||
"remote": 7,
|
||||
"note": "德国 UPS/DHL/DPD/CWE 统配;欧洲递延 -1.7元/kg;樱花快线 +0.3元/kg;因查验/罢工/节假日顺延",
|
||||
},
|
||||
"rail": {
|
||||
"name": "义乌-中欧铁路专线",
|
||||
"tiers": [(1000, 13.5), (100, 13.5), (21, 15.5)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "发车后 36-40 天提取",
|
||||
"min_pcs_kg": 13,
|
||||
"light_fee": 5,
|
||||
"remote": 7,
|
||||
"note": "义乌装柜;VAT 递延 -1元/kg;单件计费重不足 13kg 按超轻费加收",
|
||||
},
|
||||
"truck": {
|
||||
"name": "中欧卡航",
|
||||
"tiers": [(4000, 17.3), (2000, 17.3), (500, 17.4), (101, 17.4), (21, 19.4)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "发车后欧盟 16-20 天提取",
|
||||
"min_pcs_kg": 13,
|
||||
"light_fee": 5,
|
||||
"remote": 7,
|
||||
"note": "递延 -1.5元/kg;纯纺织品 +5元/kg;普卡时效 18-22 天",
|
||||
},
|
||||
"air": {
|
||||
"name": "欧洲空运专线(空派)",
|
||||
"tiers": [(101, 36), (71, 37), (45, 38), (21, 39)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "10-13 天左右提取",
|
||||
"min_pcs_kg": 12,
|
||||
"light_fee": None,
|
||||
"remote": 7,
|
||||
"note": "一票多件单件不足 12kg 按 12kg 计费;快线 8-13 天;直飞快线 12-15 天",
|
||||
},
|
||||
"sea_uk": {
|
||||
"name": "英国海运(双清)",
|
||||
"tiers": [(301, 10.9), (101, 10.9), (21, 12.8)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "参考时效 40 天提取",
|
||||
"remote": None,
|
||||
"note": "VAT自税/递延 10.0/8.1 元/kg;按KG卡派 12.2/10.3;限时达 13.5/11.6;北极航线 25-28 天(义乌装)",
|
||||
},
|
||||
"rail_uk": {
|
||||
"name": "英国铁路(双清)",
|
||||
"tiers": [(301, 16.2), (101, 16.2), (21, 18.0)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "发车后 25-30 天提取",
|
||||
"remote": None,
|
||||
"note": "VAT自税/递延 15/13.2 元/kg;限时达 19.2/17.4(38天);按KG卡派 17.3/15.5",
|
||||
},
|
||||
"truck_uk": {
|
||||
"name": "中英卡航(双清)",
|
||||
"tiers": [(301, 19.4), (101, 19.4), (21, 21.4)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 21,
|
||||
"time": "发车后 20-22 天提取",
|
||||
"remote": None,
|
||||
"note": "VAT自税/递延 18.4/16.4 元/kg;卡派 20.9/18.9;单件不超30kg,尺寸≤98×68×59cm",
|
||||
},
|
||||
"air_uk": {
|
||||
"name": "英国空运专线(双清)",
|
||||
"tiers": [(101, 42), (51, 44), (22, 48)],
|
||||
"divisor": 6000,
|
||||
"min_kg": 22,
|
||||
"time": "8-10 个自然日提取",
|
||||
"min_pcs_kg": 12,
|
||||
"light_fee": None,
|
||||
"remote": None,
|
||||
"note": "不包税 VAT 自税/递延 44/40/38;带电 47.5/42.5/41.5;拒收北爱尔兰/苏格兰高地偏远地址",
|
||||
},
|
||||
}
|
||||
|
||||
CBM_CHANNELS = ("卡航", "普卡", "铁路", "海运")
|
||||
|
||||
DIMENSION_NUMBER = r'(?<![\d.+-])(\d+(?:\.\d+)?)(?![\d.])'
|
||||
DIMENSION_UNIT = r'\s*(英寸|毫米|厘米|公分|米|(?:inches|inch|in|cm|mm|m)(?=$|[^A-Za-z0-9²³]|[xX])|["″])?\s*'
|
||||
DIMENSION_AXIS = DIMENSION_NUMBER + DIMENSION_UNIT
|
||||
DIMENSION_PATTERNS = tuple(re.compile(pattern,re.I) for pattern in (
|
||||
DIMENSION_AXIS+r'[*xX×]\s*'+DIMENSION_AXIS+r'[*xX×]\s*'+DIMENSION_AXIS,
|
||||
r'长\s*'+DIMENSION_AXIS+r'宽\s*'+DIMENSION_AXIS+r'高\s*'+DIMENSION_AXIS,
|
||||
DIMENSION_AXIS+r'长\s*'+DIMENSION_AXIS+r'宽\s*'+DIMENSION_AXIS+r'高',
|
||||
))
|
||||
|
||||
|
||||
def dimension_measurement(text):
|
||||
"""Keep units attached to the three packaging axes, not product descriptions."""
|
||||
matches=[match for pattern in DIMENSION_PATTERNS if (match:=pattern.search(text))]
|
||||
if not matches:return None
|
||||
match=min(matches,key=lambda item:item.start())
|
||||
parts=match.groups()
|
||||
values=[float(parts[index]) for index in (0,2,4)]
|
||||
aliases={'英寸':'in','inches':'in','inch':'in','"':'in','″':'in',
|
||||
'毫米':'mm','厘米':'cm','公分':'cm','米':'m'}
|
||||
units=[aliases.get(value.lower(),value.lower()) if value else None for value in parts[1::2]]
|
||||
default=next((unit for unit in reversed(units) if unit),'cm')
|
||||
units=[unit or default for unit in units]
|
||||
if len(set(units))==1:return values,units[0]
|
||||
factors={'cm':1,'mm':0.1,'m':100,'in':2.54}
|
||||
return [value*factors[unit] for value,unit in zip(values,units)],'cm'
|
||||
|
||||
|
||||
def parse_dims(t):
|
||||
measurement=dimension_measurement(t)
|
||||
return measurement[0] if measurement else None
|
||||
|
||||
|
||||
SHIPPING_REGION_PATTERNS = tuple((re.compile(pattern, re.I), region) for region, pattern in (
|
||||
('unsupported', r'美国|加拿大|澳大利亚|澳洲|新西兰|日本|韩国|新加坡|马来西亚|泰国|越南|印度|阿联酋|迪拜|沙特|巴西|墨西哥|俄罗斯|'
|
||||
r'(?<![A-Za-z0-9_])(?-i:US)(?=$|[^A-Za-z]|FBA(?![A-Za-z]))|'
|
||||
r'(?<![A-Za-z0-9_])(?:USA|United States|America|Canada|Australia|Japan|Singapore|Russia)(?![A-Za-z])'),
|
||||
('uk', r'英国|伦敦|英格兰|(?<![A-Za-z0-9_])(?:UK|GB)(?=$|[^A-Za-z]|FBA(?![A-Za-z]))|'
|
||||
r'(?<![A-Za-z0-9_])(?:United Kingdom|Britain)(?![A-Za-z])'),
|
||||
('eu', r'欧洲|欧盟|德国|法国|意大利|西班牙|波兰|捷克|荷兰|比利时|奥地利|葡萄牙|瑞典|丹麦|芬兰|爱尔兰|'
|
||||
r'(?<![A-Za-z0-9_])(?:Europe|EU|Germany|France|Italy|Spain|Poland|Netherlands)(?![A-Za-z])|'
|
||||
r'(?<![A-Za-z0-9_])(?-i:DE|FR|PL|CZ|ES|NL)(?=\s*(?:仓|FBA|warehouse))'),
|
||||
('unsupported', r'(?:发(?:往|到)?|寄(?:往|到)?|运往|运到|到|往)\s*us(?=$|[^A-Za-z]|FBA(?![A-Za-z]))|\bto\s+us\b'),
|
||||
))
|
||||
|
||||
|
||||
def shipping_region(text):
|
||||
return next((region for pattern, region in SHIPPING_REGION_PATTERNS if pattern.search(text)), None)
|
||||
|
||||
|
||||
def is_shipping_destination_reply(text):
|
||||
text = text.strip().strip(',,。.!!??、:: ')
|
||||
for pattern, _ in SHIPPING_REGION_PATTERNS:
|
||||
match = pattern.search(text)
|
||||
if not match:
|
||||
continue
|
||||
prefix = re.fullmatch(r'\s*(?:(?:目的地|目的国家|国家)(?:是|为|:|:)?|(?:发|寄|运|送)(?:往|到)?|到|往|去|to)?\s*', text[:match.start()], re.I)
|
||||
suffix = re.fullmatch(r'\s*(?:的)?\s*(?:FBA\s*)?(?:(?:海外)?仓(?:库)?|warehouse)?(?:呢)?\s*', text[match.end():], re.I)
|
||||
if prefix and suffix:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def parse_shipping_intent(text):
|
||||
"""解析重量、渠道、尺寸和费率区域;尺寸单位由调用方识别。"""
|
||||
t = text.replace(" ", "")
|
||||
intent = {"weight": None, "channel": None, "dims": None, "region": shipping_region(text)}
|
||||
|
||||
# 尺寸:在原始文本上解析(空格有助于区分尺寸和后面的重量)
|
||||
intent["dims"] = parse_dims(text)
|
||||
|
||||
# 重量:带单位的数字。去掉空格后在原始文本上匹配,
|
||||
# 但不能把尺寸里的数字(如 120*100*100 的第三个数)当成重量
|
||||
m = re.search(r"(\d+(?:\.\d+)?)\s*(吨|kg|KG|公斤|千克|tons?|kilo(?:grams?)?|lbs?)", text, re.I)
|
||||
if m:
|
||||
before = text[:m.start()].rstrip()
|
||||
adjacent_sep = bool(before) and before[-1] in "*xX×"
|
||||
if not adjacent_sep:
|
||||
n = float(m.group(1))
|
||||
unit_w = m.group(2).lower()
|
||||
if unit_w in ("吨", "ton", "tons"):
|
||||
intent["weight"] = n * 1000
|
||||
elif unit_w.startswith("lb"):
|
||||
intent["weight"] = round(n * 0.4536, 2) # 磅转公斤
|
||||
else:
|
||||
intent["weight"] = n
|
||||
intent["weight_raw"] = m.group(0).replace(" ", "")
|
||||
|
||||
# 渠道:空运 / 铁路 / 卡航 / 海运(按优先级匹配)
|
||||
if re.search(r"空运|空派|航空", t) or re.search(r"\bair\b|air ?freight|air ?cargo", text, re.I):
|
||||
intent["channel"] = "air_uk" if re.search(r"英国|UK|伦敦|英格兰", text, re.I) else "air"
|
||||
elif re.search(r"铁路|班列|火车", t) or re.search(r"\brail\b|train", text, re.I):
|
||||
intent["channel"] = "rail"
|
||||
elif re.search(r"卡航|卡车|卡派", t) or re.search(r"\btruck\b|road", text, re.I):
|
||||
intent["channel"] = "truck"
|
||||
elif re.search(r"海运|海派|船运|快船|海运快线|樱花快线", t) or re.search(r"\bsea\b|ocean|shipping", text, re.I):
|
||||
intent["channel"] = "sea"
|
||||
return intent
|
||||
|
||||
def detect_dim_unit(text):
|
||||
"""Recognize explicit dimensions; aggregate CBM does not imply meters."""
|
||||
measurement=dimension_measurement(text)
|
||||
if measurement:return measurement[1]
|
||||
low = text.lower()
|
||||
if re.search(r'英寸|\binch(?:es)?(?![A-Za-z])|\d\s*in(?![A-Za-z0-9])|\d\s*["″]',low):
|
||||
return 'in'
|
||||
if re.search(r"毫米|\d\s*mm", low):
|
||||
return "mm"
|
||||
if re.search(r"\d\s*cm|\d\s*厘米", low):
|
||||
return "cm"
|
||||
if re.search(r"\d\s*(?:m(?![A-Za-z0-9²³])|米)", low):
|
||||
return "m"
|
||||
return "cm"
|
||||
|
||||
def dims_to_cm(dims, unit):
|
||||
"""统一换算成厘米,体积重公式按 cm 计算"""
|
||||
if unit == 'in':
|
||||
return [d * 2.54 for d in dims]
|
||||
if unit == "m":
|
||||
return [d * 100 for d in dims]
|
||||
if unit == "mm":
|
||||
return [d / 10 for d in dims]
|
||||
return list(dims)
|
||||
|
||||
def pick_rate(weight_kg, tiers):
|
||||
"""从阶梯价里选档:tiers 为 [(最低重量, 单价), ...],从高到低匹配"""
|
||||
for min_w, price in tiers:
|
||||
if weight_kg >= min_w:
|
||||
return price, min_w
|
||||
return tiers[-1][1], tiers[-1][0]
|
||||
|
||||
def calc_warehouse_card(cbm, channel, warehouse_key=None, country=None):
|
||||
"""海外仓卡派:按方(CBM)计费,1CBM+ 和 0.5CBM+ 两档
|
||||
|
||||
country 传入国家代码(DE/FR/PL/CZ/ES)时,仅选择包含该后缀的仓点组;无匹配不报价。
|
||||
"""
|
||||
if not RX or not RX.WAREHOUSE_CARD:
|
||||
return None
|
||||
keys = list(RX.WAREHOUSE_CARD)
|
||||
key = warehouse_key
|
||||
if key and key not in RX.WAREHOUSE_CARD:
|
||||
return None
|
||||
if not key and country:
|
||||
for k in keys:
|
||||
if ("-" + country) in k.upper():
|
||||
key = k
|
||||
break
|
||||
if not key:
|
||||
return None
|
||||
if not key:
|
||||
key = keys[0]
|
||||
row = RX.WAREHOUSE_CARD.get(key) or RX.WAREHOUSE_CARD[keys[0]]
|
||||
p = row.get(channel) or row["海运"]
|
||||
price = p["cbm1"] if cbm >= 1 else p["cbm05"]
|
||||
if price is None:
|
||||
return None
|
||||
tier = "1CBM+" if cbm >= 1 else "0.5CBM+"
|
||||
stores = [s for s in key.splitlines() if s.strip()]
|
||||
if country:
|
||||
stores = [s for s in stores if ("-" + country) in s.upper()]
|
||||
if not stores:
|
||||
return None
|
||||
else:
|
||||
stores = stores[:1]
|
||||
note = "报价表中的仓点分组:" + "、".join(stores)
|
||||
return {
|
||||
"warehouse": "\n".join(stores), "stores": stores,
|
||||
"channel": channel, "cbm": cbm, "note": note,
|
||||
"price_cbm": price, "tier": tier,
|
||||
"total": round(cbm * price, 2),
|
||||
"formula": f"{cbm:g} CBM × {price:,.0f} 元/CBM = {cbm * price:,.0f} 元",
|
||||
}
|
||||
|
||||
def detect_surcharge(text):
|
||||
"""识别产品类型,返回报价表中的附加费条目"""
|
||||
if not RX:
|
||||
return None
|
||||
best = None
|
||||
for product, fee in RX.PRODUCT_SURCHARGES:
|
||||
# 用产品名里的前几个字做匹配(如“手机”“电池”“玩具”)
|
||||
for seg in re.split(r"[,,、\s()()]", product):
|
||||
seg = seg.strip()
|
||||
if len(seg) >= 2 and seg in text:
|
||||
if best is None or len(seg) > len(best[2]):
|
||||
best = (product, fee, seg)
|
||||
if best:
|
||||
return best[0], best[1]
|
||||
return None
|
||||
|
||||
def check_island(postcode):
|
||||
"""按邮编判断是否属于 DPD 岛屿偏远地区(附加费 35 欧/件)"""
|
||||
if not RX:
|
||||
return None
|
||||
pc = re.sub(r"[^0-9]", "", str(postcode))
|
||||
if not pc:
|
||||
return None
|
||||
for country, info in RX.DPD_ISLAND_POSTCODES.items():
|
||||
seg = info["text"]
|
||||
# 直接匹配的 4~5 位邮编
|
||||
for m in re.finditer(r"\d{4,5}", seg):
|
||||
if pc.startswith(m.group(0)):
|
||||
return country, info["code"], m.group(0)
|
||||
# 区间形式 07000–07999
|
||||
for m in re.finditer(r"(\d{4,5})\s*[–\-]\s*(\d{4,5})", seg):
|
||||
lo, hi = int(m.group(1)), int(m.group(2))
|
||||
if len(m.group(1)) == len(pc) and lo <= int(pc) <= hi:
|
||||
return country, info["code"], m.group(0)
|
||||
return None
|
||||
|
||||
def surcharge_reply(product, fee, weight_kg=None):
|
||||
"""附加费说明(能算就给出金额)"""
|
||||
txt = f"【产品附加费】{product}:{fee}"
|
||||
if weight_kg and "/KG" in fee.upper():
|
||||
m = re.search(r"\+?(\d+(?:\.\d+)?)", fee)
|
||||
if m:
|
||||
extra = float(m.group(1)) * weight_kg
|
||||
txt += f"\n 按 {weight_kg:g} kg 计:约 {extra:,.0f} 元(以最终计费重为准)"
|
||||
return txt
|
||||
|
||||
def calc_freight(weight_kg, channel, dims=None, unit="cm"):
|
||||
"""按报价表规则计算运费(数字全部由代码算)
|
||||
|
||||
报价表规则:
|
||||
- 阶梯单价:按总重量落入的档位取价
|
||||
- 材积:长×宽×高(cm) ÷ 6000,与实重取大值作为计费重量
|
||||
- 单件最低计费重 / 超轻费:见 RATES 里的 min_pcs_kg、light_fee
|
||||
- 偏远地址:+7元/kg(不含油),最低 250 元/票
|
||||
"""
|
||||
r = RATES[channel]
|
||||
cm = dims_to_cm(dims, unit) if dims else None
|
||||
divisor = r.get("divisor", 6000)
|
||||
vol = round(cm[0] * cm[1] * cm[2] / divisor, 2) if cm else None
|
||||
real = weight_kg or 0
|
||||
charge = round(max(real, vol) if vol else real, 2) # 实重与体积重取大
|
||||
min_kg = r.get("min_kg") or 0
|
||||
charge = max(charge, min_kg) # 报价表起收档
|
||||
price, tier = pick_rate(charge, r["tiers"])
|
||||
total = round(charge * price, 2)
|
||||
|
||||
unit_note = ""
|
||||
if dims and unit != "cm":
|
||||
unit_note = "(原尺寸 %g×%g×%g %s,已换算为 %g×%g×%g cm)" % (*dims, unit, *cm)
|
||||
return {
|
||||
"channel": channel, "name": r["name"],
|
||||
"real": real, "vol": vol, "charge": charge,
|
||||
"dims": dims, "dims_cm": cm, "unit": unit, "unit_note": unit_note,
|
||||
"dim_rule": ("长×宽×高÷%d = %g×%g×%g÷%d = %g kg" % (divisor, *cm, divisor, vol)) if cm else None,
|
||||
"price": price, "tier": tier,
|
||||
"formula": f"{charge:g} kg × {price} 元/kg = {total:,.0f} 元",
|
||||
"total": total,
|
||||
"time": r["time"],
|
||||
"min_pcs_kg": r.get("min_pcs_kg"),
|
||||
"light_fee": r.get("light_fee"),
|
||||
"remote": r.get("remote"),
|
||||
"note": r.get("note"),
|
||||
}
|
||||
|
||||
def freight_reply(intent):
|
||||
"""根据已知信息拼出可读的计算说明(给模型当参考,也直接展示)"""
|
||||
w = intent["weight"] or 0
|
||||
dims = intent["dims"]
|
||||
unit = intent.get("dim_unit") or "cm"
|
||||
lines = []
|
||||
default_channels = ['sea_uk', 'air_uk'] if intent.get('region') == 'uk' else ['sea', 'air']
|
||||
channels = [intent["channel"]] if intent["channel"] else default_channels
|
||||
for ch in channels:
|
||||
c = calc_freight(w, ch, dims, unit)
|
||||
parts = [f"实重 {w:g} kg" if w else "实重:未提供"]
|
||||
if c["vol"]:
|
||||
parts.append(f"体积重 {c['vol']:g} kg")
|
||||
body = (
|
||||
f"【{c['name']}】按时效 {c['time']},计费方式:阶梯单价 × 计费重量\n"
|
||||
+ (f" 尺寸:{c['unit_note']}\n" if c["unit_note"] else "")
|
||||
+ f" 计费重量 {c['charge']:g} kg(" + ",".join(parts) + ",取较大值)\n"
|
||||
+ (f" 材积算法:{c['dim_rule']}\n" if c["dim_rule"] else "")
|
||||
+ f" 适用档位:{c['tier']}KG+ 档,单价 {c['price']} 元/kg\n"
|
||||
+ f" 运费:{c['formula']}\n"
|
||||
)
|
||||
if c["min_pcs_kg"] and c["charge"] < c["min_pcs_kg"]:
|
||||
body += f" 注意:单件计费重不足 {c['min_pcs_kg']}kg,需按 {c['min_pcs_kg']}kg 起算或加收超轻费 {c['light_fee']} 元/kg\n"
|
||||
if c["remote"]:
|
||||
body += f" 偏远地址:额外 +{c['remote']} 元/kg,单票最低 250 元\n"
|
||||
if c["note"]:
|
||||
body += f" 其他:{c['note']}\n"
|
||||
lines.append(body.rstrip("\n"))
|
||||
return "\n\n".join(lines)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Explicit weight-to-warehouse assignments; unassigned comparisons stay separate."""
|
||||
|
||||
from decimal import Decimal
|
||||
import re
|
||||
|
||||
|
||||
def allocations(text,codes,weight_pattern,to_kg):
|
||||
if len(codes)<2:return None
|
||||
code='('+'|'.join(re.escape(code) for code in sorted(codes,key=len,reverse=True))+r')(?![A-Za-z0-9])'
|
||||
forward=weight_pattern.pattern+r'\s*(?:货物)?\s*(?:发到|发往|送到|发|到|去)?\s*'+code
|
||||
reverse=code+r'\s*(?:[::]|分配|发|重)?\s*'+weight_pattern.pattern
|
||||
entries=[];used=[]
|
||||
for pattern,backwards in ((forward,False),(reverse,True)):
|
||||
for match in re.finditer(pattern,text,re.I):
|
||||
if any(match.start()<end and match.end()>start for start,end in used):continue
|
||||
values=match.groups()
|
||||
destination,value,unit=values if backwards else (values[2],values[0],values[1])
|
||||
piece_weight=to_kg(value,unit)
|
||||
weight_start=match.start(2 if backwards else 1)
|
||||
carton=re.search(r'(第)?(\d+)\s*(?:箱|件)\s*(每(?:箱|件))?\s*$',text[:weight_start])
|
||||
boxes=(1 if carton.group(1) else int(carton.group(2))) if carton else None
|
||||
pieces=([{'count':boxes,'weight':str(piece_weight),'dims':None,'dim_unit':'cm','position':weight_start}]
|
||||
if carton and (boxes==1 or carton.group(3)) else None)
|
||||
weight=piece_weight*boxes if pieces else piece_weight
|
||||
entries.append({'warehouse':destination.upper(),'weight':weight,'boxes':boxes,'packages':pieces})
|
||||
used.append(match.span())
|
||||
if len(entries)<2:return None
|
||||
totals={}
|
||||
for entry in entries:
|
||||
code=entry['warehouse']
|
||||
if code not in totals:
|
||||
totals[code]=entry
|
||||
continue
|
||||
total=totals[code]
|
||||
total['weight']+=entry['weight']
|
||||
total['boxes']=total['boxes']+entry['boxes'] if total['boxes'] is not None and entry['boxes'] is not None else None
|
||||
total['packages']=(total['packages']+entry['packages']) if total['packages'] and entry['packages'] else None
|
||||
return [{**entry,'weight':str(entry['weight'])} for entry in totals.values()]
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Answer business questions from the active local book, without old regional FAQs."""
|
||||
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
import re
|
||||
|
||||
from .quote_fees import document, amount, material_fee, limit_fees
|
||||
|
||||
|
||||
def answer_business(intent,book):
|
||||
from .quote_engine import number,exact_number
|
||||
|
||||
text=intent['text'];mode=intent.get('mode')
|
||||
if mode=='weight_basis':
|
||||
return '运费按计费重量计算,不是只看净重。实重按含包装的毛重,与材积重取较大值;美国海派材积重为长×宽×高(cm)÷6000,每箱不足12KG按12KG计费。海卡包税按对应公斤规则,不包税按方方案以实际体积和毛重÷363取大;请按所选方案核算。'
|
||||
if mode=='rounding':
|
||||
weight=(f'若{exact_number(intent["weight"])}KG已是计费重,就按{exact_number(intent["weight"])}KG计算。' if intent.get('weight') else '')
|
||||
return '美国海派按原小数计费,不向上取整;每箱不足12KG仍按12KG计费。'+weight+'计费重先按各箱实重与材积重取大,再按渠道对应的重量门槛匹配档位。海卡等其他方案的进位方式需另行核对。'
|
||||
if mode=='mixing':
|
||||
return '请分别提供各产品的品名、材质、数量、重量,以及是否带电、带磁、液体或粉末,并说明是否放在同一箱。需先核对各品类的承运与申报要求,再确认混装方案,不能仅凭“两种产品”判断可以混装。'
|
||||
if mode=='metal_scope':
|
||||
from .quote_fees import material_charge
|
||||
from .quote_engine import quantity
|
||||
per_kg=material_fee(book)
|
||||
if per_kg is None:return '铁铝附加费只按铁铝货物的计费重收取,当前未匹配到费率,请联系人工核对。'
|
||||
lines=[f'铁铝附加费为{per_kg:g}元/KG,只按铁铝货物的计费重收取;一票只有部分铁铝货物时,不按整票计费重加收。']
|
||||
unit='cbm' if intent.get('tax')=='excluded' and intent.get('cbm') else 'kg'
|
||||
rate={'kind':'truck' if intent.get('kinds')==['truck'] else 'parcel','unit':unit,'service':''}
|
||||
details=material_charge(intent,quantity(intent,rate),unit,book)
|
||||
lines+=details['items']+details['notes']
|
||||
if intent.get('metal_scope')!='partial' and details['items'] and not intent.get('dims'):
|
||||
lines.append('以上按当前提供的重量条件估算,仍需核对各箱尺寸及材积重。')
|
||||
return '\n'.join(dict.fromkeys(lines))
|
||||
if mode=='currency':
|
||||
return '当前海卡、海派运价中的“元/KG”和“元/CBM”按人民币(RMB/CNY)计;一件代发等资料中标注“$”“USD”“美金”的费用按美元计。不同币种分别列明,未提供结算汇率时不自动换算。'
|
||||
if mode=='insurance':
|
||||
raw=document(book,('保险费','投保金额'))
|
||||
percent=amount(raw,r'百分之\s*(\d+(?:\.\d+)?)')
|
||||
minimum=amount(raw,r'min\s*(\d+(?:\.\d+)?)\s*USD')
|
||||
multiplier=amount(raw,r'货值乘以\s*(\d+(?:\.\d+)?)')
|
||||
if percent is None or minimum is None or multiplier is None:
|
||||
return '当前资料未明确保险的完整计费条件,请提供货值和币种,由人工确认保险费。'
|
||||
lines=[f'当前资料保险费率为保额的{percent:g}%,最低{minimum:g}USD;按货值投保时,投保金额为货值×{multiplier:g}。']
|
||||
money=re.search(r'(-?\d+(?:\.\d+)?)\s*(万)?\s*(美元|美金|USD|人民币|元)',text,re.I)
|
||||
if money and money.group(3).lower() in ('美元','美金','usd'):
|
||||
value=Decimal(money.group(1))*(10000 if money.group(2) else 1)
|
||||
if not 0<value<=1000000000:return '请提供大于0的有效货值或保额及币种。'
|
||||
insured=value if re.search(r'保价|保额',text) and not re.search(r'货值',text) else value*multiplier
|
||||
total=max(insured*percent/100,minimum).quantize(Decimal('.01'),rounding=ROUND_HALF_UP)
|
||||
lines.append(f'按保额{number(insured)}USD计算:max({number(insured)}×{percent:g}%,{minimum:g})={number(total)}USD。')
|
||||
else:
|
||||
lines.append('请提供货值/保额及币种;人民币货值还需确认适用结算汇率。')
|
||||
return '\n'.join(lines)
|
||||
if mode=='fulfillment':
|
||||
tokens=[t for t in ('20GP','40GP','45HQ','散箱','散托','贴标','仓储','仓租','分拣','SKU') if t.lower() in text.lower()]
|
||||
if '仓租' in tokens:tokens.append('仓储')
|
||||
if '卸货' in text and not tokens:tokens=['20GP','40GP','45HQ']
|
||||
rows=[]
|
||||
for d in book['documents']:
|
||||
if d['sheet']!='一件代发收费' or not re.search(r'\$|USD|美金',d['content'],re.I):continue
|
||||
score=sum(t.lower() in d['content'].lower() for t in tokens) if tokens else 1
|
||||
if score:rows.append((score,d['content']))
|
||||
rows=sorted(rows,key=lambda row:(-row[0],-(';' in row[1])))
|
||||
facts=list(dict.fromkeys(row[1] for row in rows))[:4]
|
||||
return '美国仓一件代发收费:\n'+'\n'.join('- '+r for r in facts) if facts else '当前资料中未匹配到该一件代发收费项,请补充服务项目、箱数或体积,由人工核实。'
|
||||
if mode=='customs':
|
||||
if intent.get('services') and '美森加班' in intent['services'] and document(book,('不可接一般贸易',),'美森加班海卡'):
|
||||
return '当前资料中美森加班海卡不可接一般贸易,请由人工确认其他渠道,不能直接按该线路加报关费办理。'
|
||||
if re.search(r'FDA',text,re.I):
|
||||
raw=document(book,('FDA','申报费'))
|
||||
fee=amount(raw,r'申报费[::]?\s*RMB\s*(\d+(?:\.\d+)?)')
|
||||
if fee is not None:return f'当前资料中需做FDA Filing等申报的产品,申报费为{fee:g}人民币/票。请补充具体品名和渠道,确认是否接收及需要的资料。'
|
||||
return '当前资料未匹配到FDA申报费,请提供具体品名和渠道,由人工确认是否接收及费用。'
|
||||
raw=document(book,('海外进口清关','续页'))
|
||||
extra=amount(raw,r'加收USD\s*(\d+(?:\.\d+)?)')
|
||||
lines=[]
|
||||
if re.search(r'续页|品名',text) and extra is not None:
|
||||
lines.append(f'海外进口清关:每票超过5个品名的部分,按{extra:g}美元/个收取。')
|
||||
count=re.search(r'(\d+)\s*个品名',text)
|
||||
if count:lines.append(f'{count.group(1)}个品名的该项费用:max({count.group(1)}−5,0)×{extra:g}={max(int(count.group(1))-5,0)*extra:g}美元。')
|
||||
lines.append('国内出口报关续项与海外进口清关分别收费;国内条款的品名计数方式需按票确认。')
|
||||
raw_fee=document(book,('一般贸易出口报关费',))
|
||||
declaration=amount(raw_fee,r'出口报关费[::]\s*RMB\s*(\d+(?:\.\d+)?)')
|
||||
if declaration is not None:lines.append(f'一般贸易出口报关费为{declaration:g}人民币/票。')
|
||||
if re.search(r'单独报关',text):
|
||||
minimum=document(book,('单独报关货物','300KG'))
|
||||
if minimum:lines.append('单独报关货物最低按300KG计费;还需确认所选渠道是否接受一般贸易。')
|
||||
return '\n'.join(lines) or '请提供具体申报项目、品名数量及渠道,当前资料无法确定该项费用。'
|
||||
if mode=='acceptance':
|
||||
raw=document(book,('禁止运输的货物',))
|
||||
if raw:
|
||||
prohibited=next((t for t in ('纯电池','液体','粉末','食品','医疗用品','仿牌') if t in text),None)
|
||||
if prohibited:return f'当前海派资料将{prohibited}列为不接收/禁止运输的类别,不能按普通货直接报价。若咨询其他渠道,请先由人工核实承运条件。'
|
||||
if re.search(r'带电|电池',text):return '当前海派资料中内置电池需要提供产品图片、MSDS及海运运输鉴定报告后单独确认;纯电池不接收。请补充电池类型和产品信息,确认后再匹配运价。'
|
||||
return '请提供品名、材质、是否带电及所选渠道,先核对承运条件,再计算对应费用。'
|
||||
if mode=='fees':
|
||||
lines=[]
|
||||
if re.search(r'含税|含派送|全包|包不包',text):
|
||||
lines.append('报价行标注“包税”或“不包税”的方案按各自税费方式计算;海派的派送还需核对目的仓/邮编,住宅、商业地址及偏远等附加费不能直接当作已全部包含。')
|
||||
metal=material_fee(book)
|
||||
if metal is not None and re.search(r'铁制|钢制|铝制|铁铝|不锈钢',text):
|
||||
from .quote_fees import material_charge
|
||||
from .quote_engine import quantity
|
||||
unit='cbm' if intent.get('tax')=='excluded' and intent.get('cbm') else 'kg'
|
||||
charge=quantity(intent,{'kind':'truck' if intent.get('kinds')==['truck'] else 'parcel','unit':unit,'service':''})
|
||||
details=material_charge(intent,charge,unit,book)
|
||||
lines.append(f'铁铝附加费为{metal:g}元/KG,只按铁铝货物的计费重收取。')
|
||||
lines+=details['items']+details['notes']
|
||||
if re.search(r'超重|超尺寸|超长',text):
|
||||
raw=document(book,('超重收',))
|
||||
fee=amount(raw,r'超重收\s*[++]?\s*(\d+(?:\.\d+)?)')
|
||||
if fee is not None:lines.append(f'海派明确的普通超重附加费为{fee:g}元/件;同箱同时超重、超尺寸时只收适用的最高一项。')
|
||||
limits=limit_fees(intent,book)
|
||||
lines+=limits['items']+limits['notes']
|
||||
if re.search(r'住宅|私人|商业地址|非亚马逊',text):
|
||||
lines.append('住宅或商业等非亚马逊地址的派送附加费在原表中需单独询价;请提供完整邮编、地址类型和箱规,不能直接当作FBA仓价格。')
|
||||
if not lines or re.search(r'包含|包括|还[要需]|什么费用',text):
|
||||
raw=document(book,('偏远地址加收','超偏远'))
|
||||
remote=amount(raw,r'(?<!超)偏远地址加收\s*(\d+(?:\.\d+)?)元/kg')
|
||||
extended=amount(raw,r'超偏远地址加收\s*(\d+(?:\.\d+)?)元/kg')
|
||||
if remote is not None and extended is not None:
|
||||
lines.append(f'当前美国海派资料:偏远地址加{remote:g}元/KG,超偏远地址加{extended:g}元/KG,遥远地址单询;海派每箱不足12KG按12KG计费。')
|
||||
lines.append('报价中的包税/不包税是不同费率口径;材质、报关申报、偏远及超重超尺寸等按条件单列,不代表所有服务费用都已包含。')
|
||||
if metal is not None:lines.append(f'铁铝制品附加费{metal:g}元/KG,只按铁铝货物计费重收取;多项费用分别列明,同箱超限费用只取最高项。')
|
||||
return '\n'.join(lines)
|
||||
return None
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Apply quote edits in chronological order, including derived carton quantities."""
|
||||
|
||||
from copy import deepcopy
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
QUANTITY_QUESTION='箱数已更改,请确认新的总重或各箱重量,原分箱明细不能直接套用。'
|
||||
|
||||
|
||||
def merge_intent(current,previous):
|
||||
result=deepcopy(current)
|
||||
excluded={'mode','text','errors','dim_unit','quantity_note','quantity_uncertain','preserve_total','metal_weight_update'}
|
||||
if current.get('metal_weight_update') and previous.get('metal_chargeable_weight') is None:
|
||||
result['metal_chargeable_weight']=None
|
||||
result['errors'].append('请确认铁铝部分的计费重,不能把毛重直接当作计费重。')
|
||||
if current.get('warehouse') or current.get('unknown_warehouses'):
|
||||
excluded.update(('postal','zone','zones'))
|
||||
elif current.get('postal'):
|
||||
excluded.update(('warehouse','warehouses','unknown_warehouses','zone','zones'))
|
||||
elif current.get('zone'):
|
||||
excluded.update(('warehouse','warehouses','unknown_warehouses','postal'))
|
||||
if any(current.get(k) for k in ('warehouse','postal','zone')) and not current.get('unknown_warehouses'):
|
||||
excluded.add('unknown_warehouses')
|
||||
if any(current.get(k) for k in ('warehouse','unknown_warehouses','postal','zone')) and not current.get('allocations'):
|
||||
excluded.add('allocations')
|
||||
if current.get('allocations'):excluded.update(('packages','boxes','dims','cbm'))
|
||||
if current['transport'] or current['kinds'] or current['services']:excluded.update(('air_only','air_requested'))
|
||||
if current['air_only'] or current['tax']=='excluded':excluded.add('kinds')
|
||||
if current['weight'] is not None:
|
||||
if not current.get('packages'):excluded.add('packages')
|
||||
if not current.get('allocations'):excluded.add('allocations')
|
||||
if current['dims']:excluded.add('cbm')
|
||||
if current['cbm'] is not None:excluded.add('dims')
|
||||
if any(current.get(k) is not None for k in ('weight','dims','cbm','boxes','packages','allocations','transport','kinds','services','tax')) and current.get('metal_chargeable_weight') is None:
|
||||
excluded.add('metal_chargeable_weight')
|
||||
if current.get('material')=='ordinary':excluded.update(('metal_scope','metal_chargeable_weight'))
|
||||
if current.get('metal_scope')=='all' and current.get('metal_chargeable_weight') is None:
|
||||
excluded.add('metal_chargeable_weight')
|
||||
for key,value in previous.items():
|
||||
if result.get(key) is None and key not in excluded:result[key]=deepcopy(value)
|
||||
if current['dims'] is None and 'dims' not in excluded and previous['dims']:
|
||||
result['dim_unit']=previous['dim_unit']
|
||||
pieces=result.get('packages') or []
|
||||
if current['dims']:
|
||||
for piece in pieces:piece.update(dims=current['dims'],dim_unit=current['dim_unit'])
|
||||
elif current['cbm'] is not None:
|
||||
for piece in pieces:piece.update(dims=None,dim_unit='cm')
|
||||
if previous.get('quantity_uncertain') and current['weight'] is None and not current.get('preserve_total'):
|
||||
result['quantity_uncertain']=True
|
||||
result['errors'].append(QUANTITY_QUESTION)
|
||||
if pieces and result['boxes']!=sum(p['count'] for p in pieces):
|
||||
if current.get('preserve_total'):
|
||||
result['packages']=None
|
||||
elif len(pieces)==1:
|
||||
pieces[0]['count']=result['boxes']
|
||||
result['weight']=str(Decimal(pieces[0]['weight'])*result['boxes'])
|
||||
result['quantity_note']=f'按每箱{pieces[0]["weight"]}KG不变,更新为{result["boxes"]}箱。'
|
||||
else:
|
||||
result['packages']=None
|
||||
result['quantity_uncertain']=True
|
||||
result['errors'].append(QUANTITY_QUESTION)
|
||||
return result
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Versioned, private quote imports and read-only runtime access."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
|
||||
def init_quote_tables(connection):
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS quote_books (
|
||||
id INTEGER PRIMARY KEY, source_sha256 TEXT NOT NULL UNIQUE,
|
||||
source_name TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 0)''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS quote_rates (
|
||||
id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL, service TEXT NOT NULL,
|
||||
kind TEXT NOT NULL, origin TEXT NOT NULL, zone TEXT NOT NULL,
|
||||
unit TEXT NOT NULL, tax TEXT NOT NULL, min_weight TEXT NOT NULL,
|
||||
price TEXT NOT NULL, eta TEXT NOT NULL, destinations_json TEXT NOT NULL,
|
||||
source_sheet TEXT NOT NULL, source_cell TEXT NOT NULL)''')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS idx_quote_rates_book ON quote_rates(book_id)')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS quote_warehouses (
|
||||
id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL, code TEXT NOT NULL,
|
||||
zone TEXT NOT NULL, state TEXT NOT NULL, postal TEXT NOT NULL,
|
||||
address TEXT NOT NULL, source_sheet TEXT NOT NULL, source_cell TEXT NOT NULL)''')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS idx_quote_warehouse_code ON quote_warehouses(book_id,code)')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS quote_postcodes (
|
||||
book_id INTEGER NOT NULL, postal TEXT NOT NULL, severity TEXT NOT NULL,
|
||||
fee TEXT, PRIMARY KEY(book_id,postal))''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS quote_documents (
|
||||
id INTEGER PRIMARY KEY, book_id INTEGER NOT NULL, sheet TEXT NOT NULL,
|
||||
source_cell TEXT NOT NULL, content TEXT NOT NULL)''')
|
||||
|
||||
|
||||
def decimal_text(value, positive=False):
|
||||
try:
|
||||
number = Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
raise ValueError('Invalid quote amount') from None
|
||||
if not number.is_finite() or number < 0 or number > 100000000 or (positive and not number):
|
||||
raise ValueError('Invalid quote amount')
|
||||
return format(number, 'f')
|
||||
|
||||
|
||||
def import_snapshot(connection, snapshot, *, activate=False):
|
||||
"""Validate before writing; replace an active book atomically, never order data."""
|
||||
if not isinstance(snapshot, dict) or snapshot.get('schema') != 1:
|
||||
raise ValueError('Unsupported quote snapshot')
|
||||
digest = snapshot.get('source_sha256', '')
|
||||
if not re.fullmatch('[0-9a-f]{64}', digest):
|
||||
raise ValueError('Invalid quote source checksum')
|
||||
source_name = str(snapshot.get('source_name', ''))[:240]
|
||||
if not source_name:
|
||||
raise ValueError('Missing quote source name')
|
||||
limits = {'rates':10000, 'warehouses':10000, 'postcodes':50000, 'documents':5000}
|
||||
for key, limit in limits.items():
|
||||
if not isinstance(snapshot.get(key), list) or len(snapshot[key]) > limit:
|
||||
raise ValueError('Invalid quote records')
|
||||
rates = []
|
||||
for row in snapshot['rates']:
|
||||
if (row.get('kind') not in ('truck', 'parcel') or row.get('unit') not in ('kg', 'cbm')
|
||||
or row.get('tax') not in ('included', 'excluded') or not row.get('service')
|
||||
or not isinstance(row.get('destinations'), list)
|
||||
or len(row['destinations']) > 200):
|
||||
raise ValueError('Invalid quote rate')
|
||||
rates.append((str(row['service'])[:100], row['kind'], str(row.get('origin', ''))[:40],
|
||||
str(row.get('zone', ''))[:40], row['unit'], row['tax'],
|
||||
decimal_text(row.get('min_weight', 0)), decimal_text(row['price'], positive=True),
|
||||
str(row.get('eta', ''))[:200], json.dumps(row['destinations'], ensure_ascii=False),
|
||||
str(row['source_sheet'])[:100], str(row['source_cell'])[:20]))
|
||||
warehouses = [(str(r.get('code', '')).strip().upper()[:40], str(r.get('zone', ''))[:40],
|
||||
str(r.get('state', ''))[:40], str(r.get('postal', ''))[:20], str(r.get('address', ''))[:1000],
|
||||
str(r['source_sheet'])[:100], str(r['source_cell'])[:20]) for r in snapshot['warehouses']]
|
||||
postcodes = []
|
||||
for row in snapshot['postcodes']:
|
||||
if not re.fullmatch('[0-9]{5}', row.get('postal', '')) or row.get('severity') not in ('remote','extended','extreme'):
|
||||
raise ValueError('Invalid quote postcode')
|
||||
postcodes.append((row['postal'], row['severity'], None if row.get('fee') is None else decimal_text(row['fee'])))
|
||||
documents = [(str(r['sheet'])[:100], str(r['cell'])[:20], str(r['text'])[:16000]) for r in snapshot['documents']]
|
||||
if not rates:
|
||||
raise ValueError('Quote snapshot contains no rates')
|
||||
init_quote_tables(connection)
|
||||
if not connection.in_transaction:
|
||||
connection.execute('BEGIN IMMEDIATE')
|
||||
connection.execute('SAVEPOINT quote_import')
|
||||
try:
|
||||
existing = connection.execute('SELECT id FROM quote_books WHERE source_sha256=?', (digest,)).fetchone()
|
||||
if existing:
|
||||
book_id = existing[0]
|
||||
else:
|
||||
book_id = connection.execute('INSERT INTO quote_books(source_sha256,source_name) VALUES(?,?)',
|
||||
(digest, source_name)).lastrowid
|
||||
connection.executemany('''INSERT INTO quote_rates(book_id,service,kind,origin,zone,unit,tax,
|
||||
min_weight,price,eta,destinations_json,source_sheet,source_cell) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)''',
|
||||
[(book_id, *r) for r in rates])
|
||||
connection.executemany('''INSERT INTO quote_warehouses(book_id,code,zone,state,postal,address,source_sheet,source_cell)
|
||||
VALUES(?,?,?,?,?,?,?,?)''', [(book_id, *r) for r in warehouses])
|
||||
connection.executemany('INSERT INTO quote_postcodes(book_id,postal,severity,fee) VALUES(?,?,?,?)',
|
||||
[(book_id, *r) for r in postcodes])
|
||||
connection.executemany('INSERT INTO quote_documents(book_id,sheet,source_cell,content) VALUES(?,?,?,?)',
|
||||
[(book_id, *r) for r in documents])
|
||||
if activate:
|
||||
connection.execute('UPDATE quote_books SET active=0 WHERE active<>0')
|
||||
connection.execute('UPDATE quote_books SET active=1 WHERE id=?', (book_id,))
|
||||
connection.execute('RELEASE quote_import')
|
||||
except Exception:
|
||||
connection.execute('ROLLBACK TO quote_import')
|
||||
connection.execute('RELEASE quote_import')
|
||||
raise
|
||||
return {'book_id':book_id, 'rates':len(rates), 'warehouses':len(warehouses),
|
||||
'postcodes':len(postcodes), 'documents':len(documents), 'active':bool(activate), 'existing':bool(existing)}
|
||||
|
||||
|
||||
def load_book():
|
||||
"""One read transaction prevents mixed versions during a concurrent import."""
|
||||
from .db import connect
|
||||
|
||||
connection = connect()
|
||||
try:
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute('BEGIN')
|
||||
book = connection.execute('SELECT id FROM quote_books WHERE active=1 ORDER BY id DESC LIMIT 1').fetchone()
|
||||
if not book:
|
||||
return None
|
||||
book_id = book['id']
|
||||
result = {'id':book_id}
|
||||
for table, name in (('quote_rates','rates'), ('quote_warehouses','warehouses'), ('quote_documents','documents')):
|
||||
result[name] = [dict(r) for r in connection.execute(f'SELECT * FROM {table} WHERE book_id=?', (book_id,))]
|
||||
for rate in result['rates']:
|
||||
rate['destinations'] = json.loads(rate.pop('destinations_json'))
|
||||
return result
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def postcode_fee(book_id, postal):
|
||||
from .db import connect
|
||||
|
||||
connection = connect()
|
||||
try:
|
||||
connection.row_factory = sqlite3.Row
|
||||
row = connection.execute('SELECT severity,fee FROM quote_postcodes WHERE book_id=? AND postal=?',
|
||||
(book_id, postal)).fetchone()
|
||||
return dict(row) if row else None
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Discard explicitly rejected quote conditions before parsing their replacements."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def clean_conditions(text):
|
||||
rejected=r'(?:不是|不要|并非|不从)\s*(?:(?:发|寄|运|送)(?:到|往)?|去|到)?\s*'
|
||||
value=(r'(?:[A-Za-z]{2,4}[0-9][A-Za-z0-9]{0,2})(?![A-Za-z0-9])|'
|
||||
r'深圳|华南|东莞|义乌|华东|美西|美中|美东|美国|洛杉矶|纽约|铁制品|钢制品|铝制品|铁铝制品|金属制品')
|
||||
return re.sub(rejected+'(?:'+value+')',' ',text,flags=re.I)
|
||||
|
||||
|
||||
def weight_comparison(text):
|
||||
return bool(re.search(r'会不会按|是不是按|是否按|向上进位|小数公斤|计费.*(?:进位|取整)|公斤.*(?:进位|取整)',text))
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Bounded quote matching and Decimal arithmetic, independent of Flask/models."""
|
||||
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
import re
|
||||
|
||||
from .pricing import dims_to_cm
|
||||
|
||||
|
||||
from .quote_intent import US, QUOTE_WORDS, parse_intent, is_followup
|
||||
|
||||
|
||||
def broad_zone(postal):
|
||||
if not postal:
|
||||
return None
|
||||
if postal.startswith(('8','9')):
|
||||
return '美西'
|
||||
if postal.startswith('46') or postal[0] in '0123':
|
||||
return '美东'
|
||||
return '美中'
|
||||
|
||||
|
||||
def variants(intent, book):
|
||||
if intent.get('allocations'):
|
||||
return [{**destination,'allocation':part} for part in intent['allocations']
|
||||
for destination in variants({**intent,'allocations':None,'warehouse':part['warehouse'],
|
||||
'warehouses':None,'postal':None},book)]
|
||||
if len(intent.get('warehouses') or [])>1:
|
||||
return [variant for warehouse in intent['warehouses'] for variant in
|
||||
variants({**intent,'warehouse':warehouse,'warehouses':None,'postal':None},book)]
|
||||
if not intent['warehouse'] and len(intent.get('zones') or [])>1:
|
||||
return [variant for zone in intent['zones'] for variant in
|
||||
variants({**intent,'zone':zone,'zones':None},book)]
|
||||
warehouse = intent['warehouse']
|
||||
found = [r for r in book['warehouses'] if r['code'] == warehouse] if warehouse else []
|
||||
zoned = [r for r in found if r['zone']]
|
||||
if zoned:
|
||||
unique = {}
|
||||
for row in zoned:
|
||||
postal = intent['postal'] or row['postal'][:5]
|
||||
key = (row['zone'], postal)
|
||||
unique.setdefault(key, {'label':f"{warehouse} · {row['zone']}", 'postal':postal,
|
||||
'zone':broad_zone(postal), 'warehouse':warehouse})
|
||||
return list(unique.values())
|
||||
postal = intent['postal']
|
||||
if not postal and found:
|
||||
match = re.search(r'(?<![0-9])([0-9]{5})(?:-[0-9]{4})?(?![0-9])', found[0]['address'])
|
||||
postal = match.group(1) if match else None
|
||||
zone = intent['zone']
|
||||
if zone and zone[0] in '东中西':
|
||||
zone = {'东':'美东','中':'美中','西':'美西'}[zone[0]]
|
||||
return [{'label':warehouse or postal or zone or '美国', 'postal':postal, 'zone':zone or broad_zone(postal), 'warehouse':warehouse}]
|
||||
|
||||
|
||||
def quantity(intent, rate):
|
||||
real = Decimal(intent['weight'] or '0')
|
||||
volume = Decimal(intent['cbm']) if intent['cbm'] else None
|
||||
if volume is None and intent['dims']:
|
||||
cm = [Decimal(str(value)) for value in dims_to_cm(intent['dims'], intent['dim_unit'])]
|
||||
volume = cm[0]*cm[1]*cm[2]/Decimal(1000000)*(intent['boxes'] or 1)
|
||||
package_charge=Decimal(0)
|
||||
if intent.get('packages'):
|
||||
package_volume=Decimal(0)
|
||||
all_dimensions=True
|
||||
for package in intent['packages']:
|
||||
dims=package.get('dims') or intent['dims']
|
||||
cm=[Decimal(str(value)) for value in dims_to_cm(dims,package.get('dim_unit') or intent['dim_unit'])] if dims else None
|
||||
box_volume=cm[0]*cm[1]*cm[2]/1000000 if cm else Decimal(0)
|
||||
all_dimensions=all_dimensions and bool(cm)
|
||||
package_volume+=box_volume*package['count']
|
||||
piece=max(Decimal(package['weight']),box_volume*1000000/6000 if rate['kind']=='parcel' else box_volume*167)
|
||||
package_charge+=max(piece,Decimal(12) if rate['kind']=='parcel' else Decimal(0))*package['count']
|
||||
if all_dimensions and not intent['cbm']:volume=package_volume
|
||||
if rate['unit'] == 'cbm':
|
||||
if volume is None:
|
||||
return None
|
||||
result=max(volume, real/Decimal(363))
|
||||
if rate['service']=='洛杉矶普船海卡':
|
||||
result=result.quantize(Decimal('.01'),rounding=ROUND_HALF_UP)
|
||||
return result if result>0 else None
|
||||
volume_weight = ((volume or Decimal(0))*1000000/6000 if rate['kind']=='parcel'
|
||||
else (volume or Decimal(0))*167)
|
||||
charge = max(real, volume_weight,package_charge)
|
||||
if rate['kind'] == 'parcel':
|
||||
charge = max(charge, Decimal(12)*(intent['boxes'] or 1))
|
||||
return charge if real or volume else None
|
||||
|
||||
|
||||
def match_rates(intent, book, variant):
|
||||
selected = []
|
||||
kinds = intent['kinds'] or (['truck','parcel'] if variant['warehouse'] else ['parcel'])
|
||||
for rate in book['rates']:
|
||||
if rate['kind'] not in kinds or (intent['origin'] and intent['origin'] != rate['origin']):
|
||||
continue
|
||||
if intent['services'] and not any(name in rate['service'] for name in intent['services']):
|
||||
continue
|
||||
if intent['tax'] and rate['tax'] != intent['tax']:
|
||||
continue
|
||||
if rate['kind'] == 'truck':
|
||||
if not variant['warehouse'] or variant['warehouse'] not in [value.upper() for value in rate['destinations']]:
|
||||
continue
|
||||
elif variant['zone'] and rate['zone'] != variant['zone']:
|
||||
continue
|
||||
selected.append(rate)
|
||||
groups = {}
|
||||
for rate in selected:
|
||||
key = (rate['service'],rate['origin'],rate['zone'],rate['unit'],rate['tax'])
|
||||
charge = quantity(intent,rate)
|
||||
if rate['kind'] == 'parcel' and Decimal(rate['min_weight']) > (charge or Decimal(12)):
|
||||
continue
|
||||
if key not in groups or Decimal(rate['min_weight']) > Decimal(groups[key]['min_weight']):
|
||||
groups[key] = rate
|
||||
return list(groups.values())
|
||||
|
||||
|
||||
def number(value, places=2):
|
||||
return format(Decimal(value).quantize(Decimal(10)**-places, rounding=ROUND_HALF_UP), 'f').rstrip('0').rstrip('.') if places else str(value)
|
||||
|
||||
|
||||
def exact_number(value):
|
||||
text=format(Decimal(value),'f')
|
||||
return text.rstrip('0').rstrip('.') if '.' in text else text
|
||||
|
||||
|
||||
def quantity_number(value,intent):
|
||||
if Decimal(value)==Decimal(intent.get('weight') or '0') or Decimal(value).as_tuple().exponent>=-6:
|
||||
return exact_number(value)
|
||||
return '约'+number(value,6)
|
||||
|
||||
|
||||
def render_rates(intent, book, destinations, remote_fees):
|
||||
from .quote_fees import charge_details
|
||||
from .quote_language import translate_quote
|
||||
|
||||
lines = []
|
||||
if intent.get('mode')=='time':
|
||||
lines.append('美国线路参考时效:')
|
||||
elif intent['weight']:
|
||||
lines.append(f"美国 {exact_number(intent['weight'])}KG 基础运费:")
|
||||
else:
|
||||
lines.append('美国线路报价:')
|
||||
if intent.get('quantity_note'):lines.append(intent['quantity_note'])
|
||||
if intent.get('allocations'):
|
||||
lines.append('按各目的仓分票计算,箱规需逐票核对:')
|
||||
if intent.get('metal_chargeable_weight') is not None:
|
||||
lines.append('请分别提供各目的仓的铁铝货物计费重,整票铁铝基数不能重复套用到每个仓。')
|
||||
elif len(intent.get('warehouses') or [])>1:
|
||||
lines.append('以下按各目的仓分别比较;实际分票请提供每个仓的重量。')
|
||||
if intent.get('air_requested') and not intent.get('air_only'):
|
||||
lines.append('当前资料没有美国空运费率,下面列出海运方案。')
|
||||
for destination, fees in zip(destinations, remote_fees):
|
||||
part=destination.get('allocation')
|
||||
billing=({**intent,'weight':part['weight'],'packages':part.get('packages'),'dims':None,'cbm':None,'boxes':part.get('boxes')}
|
||||
if part else intent)
|
||||
if part and intent.get('metal_chargeable_weight') is not None:
|
||||
billing.update(metal_chargeable_weight=None,metal_scope='partial')
|
||||
rates = match_rates(billing, book, destination)
|
||||
if intent.get('mode') in ('cheapest','fastest') and rates:
|
||||
if intent['mode']=='cheapest':
|
||||
eligible=[r for r in rates if quantity(billing,r) is not None]
|
||||
best={}
|
||||
for rate in eligible:
|
||||
key=(destination['zone'] or rate['zone'],rate['unit'],rate['tax'])
|
||||
value=quantity(billing,rate)*Decimal(rate['price'])+charge_details(billing,rate,fees,book)['cny']
|
||||
best[key]=min(best.get(key,value),value)
|
||||
rates=[r for r in eligible if quantity(billing,r)*Decimal(r['price'])+charge_details(billing,r,fees,book)['cny']==best[(destination['zone'] or r['zone'],r['unit'],r['tax'])]] or rates
|
||||
lines.append('按相同区域、计费单位及税费方式比较的较低价方案:')
|
||||
else:
|
||||
def eta_key(rate):
|
||||
values=[Decimal(v) for v in re.findall(r'\d+(?:\.\d+)?',rate['eta'])]
|
||||
return tuple(values[:2]) if values else (Decimal('Infinity'),)
|
||||
earliest=min(eta_key(r) for r in rates)
|
||||
rates=[r for r in rates if eta_key(r)==earliest]
|
||||
lines.append('按资料中的参考时效,较快方案如下;提取不等于送达或签收:')
|
||||
if not rates:
|
||||
lines.append(f"{destination['label']}:当前资料没有匹配的线路价格,提供目的仓码或邮编可继续查询。")
|
||||
continue
|
||||
if destination['label'] != '美国':
|
||||
lines.append(destination['label']+':')
|
||||
grouped = {}
|
||||
for rate in rates:
|
||||
key = (rate['service'], rate['origin'], rate['unit'], rate['tax'])
|
||||
grouped.setdefault(key, []).append(rate)
|
||||
for (service, origin, unit, tax), rows in grouped.items():
|
||||
if intent.get('mode')=='time':
|
||||
eta=rows[0]['eta'] or '当前资料未列明时效'
|
||||
if rows[0]['kind']=='parcel' and '提取' not in eta:eta+='提取'
|
||||
lines.append(f'- {service} · {origin}:{eta}。提取不等于送达或签收。')
|
||||
continue
|
||||
parts = []
|
||||
for rate in rows:
|
||||
amount = quantity(billing,rate)
|
||||
price = Decimal(rate['price'])
|
||||
rate_text = f"{rate['zone']} " if rate['zone'] and not destination['zone'] else ''
|
||||
rate_text += f"{number(price)}元/{'KG' if unit == 'kg' else 'CBM'}"
|
||||
if amount is not None:
|
||||
total = amount*price
|
||||
details=charge_details(billing,rate,fees,book)
|
||||
total+=details['cny']
|
||||
rate_text += f",{quantity_number(amount,billing)}{'KG' if unit == 'kg' else 'CBM'} = {number(total)}元"
|
||||
if details['items']:rate_text+='('+ ';'.join(details['items'])+')'
|
||||
for note in details['notes']:
|
||||
if note not in lines:lines.append(note)
|
||||
elif intent.get('cbm') and rate['unit']=='cbm':
|
||||
lines.append('计费体积四舍五入后不足0.01CBM,最低计费体积需人工确认,不能按零费用出价。')
|
||||
parts.append(rate_text)
|
||||
eta = re.sub(r'\s*无时效赔偿', '', rows[0]['eta']).strip()
|
||||
if rows[0]['kind']=='parcel' and eta and '提取' not in eta:eta+='提取'
|
||||
elif rows[0]['kind']=='truck' and eta and '船开' not in eta:eta='开船后参考'+eta
|
||||
lines.append(f"- {service} · {origin} · {'包税' if tax=='included' else '不包税'}:"+';'.join(parts)
|
||||
+ (f'({eta})' if eta else ''))
|
||||
if fees:
|
||||
if fees['fee'] is None:
|
||||
lines.append('该邮编属于遥远地址,派送附加费需单独确认。')
|
||||
else:
|
||||
lines.append(f"海派已计入偏远附加费 {number(fees['fee'])}元/KG。")
|
||||
if not any(intent.get(key) for key in ('warehouse','postal')):
|
||||
lines.append('发我目的仓码或邮编,可继续匹配到仓线路。')
|
||||
if intent.get('mode')=='time':
|
||||
pass
|
||||
elif not intent['weight'] and not intent['cbm'] and not intent['dims']:
|
||||
lines.append('货物多少公斤、几箱?')
|
||||
elif not intent['boxes'] or not intent['dims']:
|
||||
lines.append('请补充箱数、每箱重量和尺寸,继续核算计费重及超重超尺寸费用。')
|
||||
if intent.get('mode')=='calculation':
|
||||
lines.append('计算过程:各箱实重与体积重取大;海派每箱不足12KG按12KG计费,再按整票计费重选择重量档位,乘对应单价,并单列已知附加费。')
|
||||
text='\n'.join(lines)
|
||||
return translate_quote(text) if intent.get('english') else text
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Amounts come from the active book; explicit customer-approved fee policies live here."""
|
||||
|
||||
from decimal import Decimal
|
||||
import re
|
||||
|
||||
from .pricing import dims_to_cm
|
||||
|
||||
|
||||
def document(book,required,service=None):
|
||||
rows=[d for d in book['documents'] if (not service or d['sheet'] in (service,'海派'))
|
||||
and all(term in d['content'] for term in required)]
|
||||
return rows[0]['content'] if rows else ''
|
||||
|
||||
|
||||
def amount(text,pattern):
|
||||
match=re.search(pattern,text,re.I)
|
||||
return Decimal(match.group(1)) if match else None
|
||||
|
||||
|
||||
def material_fee(book):
|
||||
text=document(book,('铁铝','附加费'))
|
||||
return amount(text,r'铁铝制品[^\n]*?[¥¥]\s*(\d+(?:\.\d+)?)\s*/KG')
|
||||
|
||||
|
||||
def material_charge(intent,charged,unit,book):
|
||||
result={'cny':Decimal(0),'items':[],'notes':[]}
|
||||
material=intent.get('material')
|
||||
if material not in ('metal','unknown_metal'):return result
|
||||
per_kg=material_fee(book)
|
||||
if per_kg is None:
|
||||
result['notes'].append('铁铝附加费费率尚未明确,当前金额未包含该项,请联系人工确认。')
|
||||
return result
|
||||
if material=='unknown_metal':
|
||||
result['notes'].append('请先确认金属是否属于铁铝制品;铁铝附加费只按铁铝货物的计费重收取,当前金额未包含待核实的材质费用。')
|
||||
return result
|
||||
basis=intent.get('metal_chargeable_weight')
|
||||
if basis is None and intent.get('metal_scope')=='partial':
|
||||
result['notes'].append(f'铁铝附加费{per_kg:g}元/KG只按铁铝货物的计费重收取,不能按整票重量加费;请提供铁铝部分的计费重,当前金额未包含该项。')
|
||||
return result
|
||||
if basis is None and unit!='kg':
|
||||
result['notes'].append(f'铁铝附加费为{per_kg:g}元/KG,当前按方运费未包含该项;需确认铁铝货物计费重量后单列,不能把CBM直接乘公斤附加费。')
|
||||
return result
|
||||
basis=Decimal(basis) if basis is not None else charged
|
||||
if basis is None:return result
|
||||
if unit=='kg' and charged is not None and basis>charged:
|
||||
result['notes'].append('铁铝货物计费重高于当前整票可计算的计费重,请补充各箱实重和尺寸核对;当前金额未包含该项。')
|
||||
return result
|
||||
fee=basis*per_kg
|
||||
result['cny']=fee
|
||||
result['items'].append(f'铁铝附加费{per_kg:g}元/KG×{basis:g}KG={fee:g}元')
|
||||
return result
|
||||
|
||||
|
||||
def specimens(intent):
|
||||
if intent.get('packages'):
|
||||
return [{**p,'dims':p.get('dims') or intent.get('dims'),
|
||||
'dim_unit':p.get('dim_unit') if p.get('dims') else intent.get('dim_unit','cm')} for p in intent['packages']]
|
||||
if intent.get('boxes')==1 and intent.get('weight'):
|
||||
return [{'count':1,'weight':intent['weight'],'dims':intent.get('dims'),'dim_unit':intent.get('dim_unit','cm')}]
|
||||
return []
|
||||
|
||||
|
||||
def limit_fees(intent,book):
|
||||
"""Maximum per-piece limit fee, not the sum of overlapping weight/size charges.
|
||||
|
||||
The malformed 0<length<274 rule does not create a new threshold. Only two
|
||||
independently explicit large-piece conditions can establish that tier.
|
||||
"""
|
||||
normal=document(book,('正常货物',))
|
||||
cleaned=re.sub(r'\s+','',normal).replace('<','<').upper()
|
||||
limits=[amount(cleaned,p) for p in (r'0KG<单件重量<(\d+)KG',r'0CM<最长单边长度<(\d+)CM',
|
||||
r'0CM<第二边<(\d+)CM',r'最长边<(\d+)CM')]
|
||||
normal_fee=amount(document(book,('超重收',)),r'超重收\s*[++]?\s*(\d+(?:\.\d+)?)')
|
||||
size_text=document(book,('普通超尺寸',))
|
||||
size_fee=amount(size_text,r'加收\s*(\d+(?:\.\d+)?)\s*RMB/件')
|
||||
large_text=document(book,('大尺寸货物','任意2个'))
|
||||
large_fee=amount(large_text,r'加收\s*(\d+(?:\.\d+)?)\s*RMB/件')
|
||||
huge=document(book,('超大件货物',))
|
||||
huge_fee=amount(huge,r'加收\s*USD\s*(\d+(?:\.\d+)?)')
|
||||
result={'cny':Decimal(0),'items':[],'notes':[]}
|
||||
if not all(limits) or normal_fee is None:return result
|
||||
max_weight,max_length,max_second,max_girth=limits
|
||||
for piece in specimens(intent):
|
||||
weight=Decimal(piece['weight']);count=piece['count']
|
||||
dims=sorted([Decimal(str(x)) for x in dims_to_cm(piece['dims'],piece['dim_unit'])],reverse=True) if piece['dims'] else []
|
||||
length,second,girth=(dims[0],dims[1],dims[0]+2*(dims[1]+dims[2])) if dims else (None,None,None)
|
||||
if weight>68 or (dims and (length>270 or girth>419)):
|
||||
result['notes'].append('该件可能超出承运尺寸或重量,需人工确认是否接收。'+(f'原表超大件若接收的附加费为{huge_fee:g}USD/件。' if huge_fee else ''))
|
||||
continue
|
||||
candidates=[]
|
||||
if weight>max_weight:candidates.append(normal_fee)
|
||||
if dims and (length>max_length or second>max_second or girth>max_girth) and size_fee is not None:candidates.append(size_fee)
|
||||
if large_fee is not None and max_weight<weight<68 and dims and 330<girth<419:
|
||||
candidates.append(large_fee)
|
||||
elif dims and (length>=243 or girth>=330):
|
||||
result['notes'].append('该件接近大尺寸档,原表有一处长度条件不清,适用档位需人工确认。')
|
||||
if candidates:
|
||||
fee=max(candidates)*count
|
||||
result['cny']+=fee
|
||||
result['items'].append(f'超重/超尺寸按最高项{max(candidates):g}元/件×{count}件={fee:g}元')
|
||||
return result
|
||||
|
||||
|
||||
def charge_details(intent,rate,remote,book):
|
||||
from .quote_engine import quantity
|
||||
|
||||
result={'cny':Decimal(0),'items':[],'notes':[]}
|
||||
charged=quantity(intent,rate)
|
||||
if charged is None:return result
|
||||
if rate['kind']=='parcel' and remote:
|
||||
if remote['fee'] is not None:
|
||||
fee=charged*Decimal(remote['fee']);result['cny']+=fee
|
||||
result['items'].append(f'偏远费{remote["fee"]}元/KG×{charged:g}KG={fee:g}元')
|
||||
else:result['notes'].append('遥远地址的附加费需单独确认,当前金额未包含该项。')
|
||||
metal=material_charge(intent,charged,rate['unit'],book)
|
||||
result['cny']+=metal['cny'];result['items']+=metal['items'];result['notes']+=metal['notes']
|
||||
if rate['kind']=='parcel':
|
||||
limits=limit_fees(intent,book)
|
||||
result['cny']+=limits['cny'];result['items']+=limits['items'];result['notes']+=limits['notes']
|
||||
if intent.get('address_type')=='non_fba':
|
||||
result['notes'].append('非亚马逊地址还需核对住宅/商业派送附加费,原表此项需单独询价。')
|
||||
return result
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Normalize customer wording into bounded quote fields without model inference."""
|
||||
|
||||
from decimal import Decimal
|
||||
import re
|
||||
|
||||
from .pricing import parse_shipping_intent, detect_dim_unit, shipping_region
|
||||
|
||||
US = re.compile(r'美国|美西|美中|美东|洛杉矶|纽约|芝加哥|休斯顿|萨凡纳|'
|
||||
r'(?<![A-Za-z])(?:USA|(?-i:US)|United States|America)(?=$|[^A-Za-z]|FBA(?![A-Za-z]))|'
|
||||
r'(?:发(?:往|到)?|寄(?:往|到)?|运往|运到|到|往|\bto\s+)\s*us(?=$|[^A-Za-z]|FBA(?![A-Za-z]))',re.I)
|
||||
QUOTE_WORDS = re.compile(r'报价|价格|运费|费用|收费|多少钱|计费|包税|海运|空运|海派|海卡|海铁|美森|合德|普船|附加|保险|代发|申报|偏远|超重|超尺寸|币种|\bEXX\b|\b(?:quote|price|cost|freight)\b',re.I)
|
||||
WEIGHT = re.compile(r'(?<![\d.])(-?\d+(?:\.\d+)?)\s*(kilograms?|kgs?|公斤|千克|grams?|克|g|tons?|吨|lbs?|磅)(?![A-Za-z])',re.I)
|
||||
TOPIC_BOUNDARY = re.compile(r'新(?:的)?一(?:票|批)|另外|另一|换个话题|理赔|赔偿|破损|丢失|退件|投诉|查单|轨迹|签收')
|
||||
|
||||
|
||||
def chinese_number(text):
|
||||
digits={c:i for i,c in enumerate('零一二三四五六七八九')};digits.update({'两':2,'〇':0})
|
||||
if all(c in digits for c in text):return ''.join(str(digits[c]) for c in text)
|
||||
if '点' in text:
|
||||
left,right=text.split('点',1)
|
||||
return str(chinese_number(left or '零'))+'.'+''.join(str(digits[c]) for c in right)
|
||||
total=section=number=0
|
||||
for character in text:
|
||||
if character in digits:
|
||||
number=digits[character]
|
||||
elif character=='万':
|
||||
total+=(section+number)*10000;section=number=0
|
||||
else:
|
||||
section+=(number or 1)*{'十':10,'百':100,'千':1000}[character];number=0
|
||||
return str(total+section+number)
|
||||
|
||||
|
||||
def normalize(text):
|
||||
result=re.sub(r'([零〇一二两三四五六七八九十百千万点]+)(?=\s*(?:公斤|千克|克|吨|磅|(?:个)?箱|件|立方米|立方|方|kg|cbm))',
|
||||
lambda m:chinese_number(m.group(1)),text,flags=re.I)
|
||||
return re.sub(r'负(?=\d)','-',result)
|
||||
|
||||
|
||||
def kg(value,unit):
|
||||
value=Decimal(value)
|
||||
unit=unit.lower()
|
||||
if unit in ('克','g','gram','grams'):return value/1000
|
||||
if unit in ('吨','ton','tons'):return value*1000
|
||||
if unit in ('磅','lb','lbs'):return (value*Decimal('0.4536')).quantize(Decimal('.01'))
|
||||
return value
|
||||
|
||||
|
||||
def request_mode(text):
|
||||
# Business topics outrank generic verbs such as “怎么算”.
|
||||
if re.search(r'保险|保价|投保|insured|insurance',text,re.I):return 'insurance'
|
||||
from .quote_edits import weight_comparison
|
||||
if weight_comparison(text):return 'rounding'
|
||||
if re.search(r'毛重|净重|计费重.*(?:什么|区别)|材积重.*(?:什么|区别)',text):return 'weight_basis'
|
||||
if re.search(r'混装|混箱|不同产品.*一箱',text):return 'mixing'
|
||||
if (re.search(r'(?:铁|钢|铝|金属).*(?:附加|加费|加钱|整票)|整票.*(?:铁|钢|铝|金属)',text)
|
||||
and not re.search(r'最终总价|一共多少钱|总共多少钱|合计多少钱|最终价格|最终费用|到门总价',text)):
|
||||
return 'metal_scope'
|
||||
if re.search(r'纯电池|带电|内置电池|液体|粉末|食品|医疗用品|仿牌',text):return 'acceptance'
|
||||
from .shipping_faq import preparation_topic
|
||||
if preparation_topic(text):return 'preparation'
|
||||
if re.search(r'最便宜|便宜的|便宜一?点|优惠|折扣|打折|最省钱|最划算|最低价|cheapest|least expensive',text,re.I):return 'cheapest'
|
||||
if re.search(r'最终总价|一共多少钱|总共多少钱|合计多少钱|最终价格|最终费用|到门总价',text):return 'total'
|
||||
if re.search(r'最快|快的|fastest',text,re.I):return 'fastest'
|
||||
if re.search(r'一件代发|散箱入库|整柜卸货|卸货费|仓租|仓储|贴标费',text):return 'fulfillment'
|
||||
if re.search(r'FDA|申报费|报关|续页|品名',text,re.I):return 'customs'
|
||||
if re.search(r'附加费|含税|含派送|全包|包不包|还.*(?:费|加钱)|(?:额外|其他|其它).*(?:费用|收费)|包含.*费|包税.*(?:包含|包括)|超重费|超尺寸|住宅|私人|商业地址',text):return 'fees'
|
||||
if re.search(r'电池|带电|液体|粉末|食品|医疗|能(?:不能|发|走)|可以.*(?:发|走)',text):return 'acceptance'
|
||||
if re.search(r'人民币|美元|美金|币种|currency|\b(?:RMB|CNY|USD)\b',text,re.I) and not WEIGHT.search(text):return 'currency'
|
||||
if re.search(r'怎么(?:算|计算)|计算(?:过程|出来)|怎么算出来|calculation',text,re.I):return 'calculation'
|
||||
if re.search(r'时效|多久|几天',text) and not WEIGHT.search(text):return 'time'
|
||||
return 'quote'
|
||||
|
||||
|
||||
def parse_intent(message,warehouse_codes):
|
||||
text=normalize(message)
|
||||
from .quote_edits import clean_conditions
|
||||
text=clean_conditions(text)
|
||||
text=re.sub(r'(?:而?不是|并非|不要按|不是按)\s*(?:每[箱件]|单[箱件])?\s*'+WEIGHT.pattern,' ',text,flags=re.I)
|
||||
from .quote_material import material_intent
|
||||
materials=material_intent(text,WEIGHT,kg)
|
||||
quantity_text=materials['quantity_text']
|
||||
parsed=parse_shipping_intent(quantity_text)
|
||||
country='US' if US.search(text) else ('other' if shipping_region(text) is not None else None)
|
||||
candidates=re.findall(r'(?<![A-Za-z0-9])[A-Za-z][A-Za-z0-9]{2,7}(?![A-Za-z0-9])',text.upper())
|
||||
warehouses=list(dict.fromkeys(t for t in candidates if t in warehouse_codes))
|
||||
unknown=[t for t in candidates if t not in warehouse_codes and re.fullmatch(r'[A-Z]{2,4}[0-9][A-Z0-9]{0,2}',t)
|
||||
and not t.startswith(('USD','RMB','CNY'))]
|
||||
errors=materials['errors'][:]
|
||||
from .quote_allocations import allocations
|
||||
assigned=allocations(quantity_text,warehouses,WEIGHT,kg)
|
||||
weights=[m for m in WEIGHT.finditer(quantity_text) if not quantity_text[:m.start()].rstrip().endswith(('x','X','×','*'))]
|
||||
weight=str(kg(*weights[0].groups())) if weights else None
|
||||
boxes=re.search(r'(\d+)\s*(?:个)?(?:箱(?:子)?|件|cartons?|boxes?)',quantity_text,re.I)
|
||||
count=int(boxes.group(1)) if boxes else None
|
||||
packages=[]
|
||||
package_re=re.compile(r'(第)?(\d+)\s*(?:箱|件)\s*(?:[,,]?\s*每(?:箱|件))?\s*'+WEIGHT.pattern.replace(r'(?<![\d.])',''),re.I)
|
||||
matches=list(package_re.finditer(quantity_text))
|
||||
package_dimensions={}
|
||||
for index,match in enumerate(matches):
|
||||
ordinal,n,value,unit=match.groups()
|
||||
segment=quantity_text[match.end():matches[index+1].start() if index+1<len(matches) else len(quantity_text)]
|
||||
dims=parse_shipping_intent(segment)['dims']
|
||||
packages.append({'count':1 if ordinal else int(n),'weight':str(kg(value,unit)),
|
||||
'dims':dims,'dim_unit':detect_dim_unit(segment)})
|
||||
package_dimensions[match.start(3)]={'dims':dims,'dim_unit':detect_dim_unit(segment)}
|
||||
for part in assigned or []:
|
||||
for piece in part.get('packages') or []:
|
||||
piece.update(package_dimensions.get(piece.pop('position'),{}))
|
||||
each=re.search(r'每(?:箱|件)\s*'+WEIGHT.pattern.replace(r'(?<![\d.])',''),quantity_text,re.I)
|
||||
if each and count and not packages:
|
||||
packages=[{'count':count,'weight':str(kg(*each.groups())),'dims':parsed['dims'],'dim_unit':detect_dim_unit(text)}]
|
||||
if packages:
|
||||
package_count=sum(p['count'] for p in packages)
|
||||
aggregate_count=boxes and not any(m.start()<=boxes.start()<m.end() for m in matches)
|
||||
if count and aggregate_count and count!=package_count:
|
||||
errors.append('箱数与分箱明细不一致,请确认总箱数及每箱重量。')
|
||||
count=package_count
|
||||
weight=str(sum(Decimal(p['weight'])*p['count'] for p in packages))
|
||||
total=re.search(r'(?:总重|合计重量|一共重)\s*'+WEIGHT.pattern.replace(r'(?<![\d.])',''),quantity_text,re.I)
|
||||
if total and kg(*total.groups())!=Decimal(weight):errors.append('总重与分箱重量合计不一致,请确认。')
|
||||
# Per-carton dimensions must not spill onto another carton without dimensions.
|
||||
if len(packages)>1:parsed['dims']=None
|
||||
elif assigned:
|
||||
weight=str(sum(Decimal(a['weight']) for a in assigned))
|
||||
if set(a['warehouse'] for a in assigned)!=set(warehouses):errors.append('请分别提供每个目的仓的重量,避免遗漏分票。')
|
||||
total=re.search(r'(?:总重|合计重量)\s*'+WEIGHT.pattern,quantity_text,re.I)
|
||||
if total and kg(*total.groups())!=Decimal(weight):errors.append('总重与各目的仓分配重量不一致,请确认。')
|
||||
elif len(weights)>1 and request_mode(text)!='rounding':
|
||||
errors.append('请明确总重,或分别提供每箱重量,避免把不同重量混在一起。')
|
||||
if assigned and packages and Decimal(weight)!=sum(Decimal(a['weight']) for a in assigned):
|
||||
errors.append('分仓重量与分箱重量不一致,请分别确认每仓的箱数和重量。')
|
||||
if any(kg(*w.groups())<=0 for w in weights):errors.append('重量必须大于 0,请确认有效重量。')
|
||||
labeled=re.search(r'(?:邮编|zip(?:\s*code)?|post\s*code)\s*[::为是]?\s*([0-9-]+)',text,re.I)
|
||||
postal=None
|
||||
if labeled:
|
||||
if re.fullmatch(r'[0-9]{5}(?:-[0-9]{4})?',labeled.group(1)):postal=labeled.group(1)[:5]
|
||||
else:errors.append('美国邮编请提供5位数字,可附加4位扩展码;当前邮编格式不正确。')
|
||||
else:
|
||||
remaining=WEIGHT.sub(' ',text)
|
||||
remaining=re.sub(r'\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?\s*[*xX×]\s*\d+(?:\.\d+)?',' ',remaining)
|
||||
match=re.search(r'(?:^|美国\s*|[,,\s])([0-9]{5})(?:-[0-9]{4})?(?=$|[,,\s])',remaining)
|
||||
if match:postal=match.group(1)
|
||||
cbm=re.search(r'(-?\d+(?:\.\d+)?)\s*(?:cbm|立方米|立方|方)',text,re.I)
|
||||
origin='华南' if re.search(r'华南|深圳|东莞|south china|shenzhen',text,re.I) else ('义乌' if re.search(r'华东|义乌|yiwu',text,re.I) else None)
|
||||
if re.search(r'华南|深圳|东莞',text) and re.search(r'华东|义乌',text):origin=None
|
||||
services=[n for n in ('美森正班','美森加班','EXX','合德','普船') if n.lower() in text.lower()]
|
||||
if '美森' in text and not any(n.startswith('美森') for n in services):services+=['美森正班','美森加班']
|
||||
kinds=[]
|
||||
if re.search(r'海派|快递|UPS|FEDEX',text,re.I):kinds.append('parcel')
|
||||
if re.search(r'海卡|海铁|全卡|卡派|卡车|铁路',text):kinds.append('truck')
|
||||
zones=[z for z in ('美西','美中','美东','东1区','东2区','中1区','中2区','西1区','西2区') if z in text]
|
||||
if not zones and '洛杉矶' in text:zones=['美西']
|
||||
if not zones and re.search(r'纽约|萨凡纳',text):zones=['美东']
|
||||
air=bool(re.search(r'空运|空派|\bair\b',text,re.I))
|
||||
sea=bool(re.search(r'海运|海派|海卡|海铁|\bsea\b',text,re.I))
|
||||
english=not re.search(r'[\u4e00-\u9fff]',message) and bool(re.search(r'[A-Za-z]{3,}\s+[A-Za-z]',message))
|
||||
return {'country':country,'weight':weight,'dims':parsed['dims'],'dim_unit':detect_dim_unit(text),
|
||||
'cbm':cbm.group(1) if cbm else None,'boxes':count,'packages':packages or None,'allocations':assigned,'origin':origin,
|
||||
'services':services or None,'kinds':kinds or None,'transport':parsed['channel'],
|
||||
'air_only':True if air and not sea else None,'air_requested':True if air else None,
|
||||
'warehouse':warehouses[0] if warehouses else None,'warehouses':warehouses or None,
|
||||
'unknown_warehouses':unknown or None,'postal':postal,'zone':zones[0] if zones else None,'zones':zones or None,
|
||||
'tax':'excluded' if re.search(r'不包税|自税|不含税|tax excluded',text,re.I) else ('included' if re.search(r'包税|tax included',text,re.I) else None),
|
||||
'errors':errors,'mode':request_mode(text),'english':True if english else (False if re.search(r'[\u4e00-\u9fff]',message) else None),
|
||||
'material':materials['material'],'metal_scope':materials['metal_scope'],
|
||||
'metal_chargeable_weight':materials['metal_chargeable_weight'],
|
||||
'metal_weight_update':materials['metal_weight_update'],
|
||||
'address_type':('non_fba' if re.search(r'私人|住宅|商业地址|非亚马逊',text) else ('fba' if warehouses else None)),
|
||||
'preserve_total':True if re.search(r'总重不变|重量不变',text) else None,'text':text}
|
||||
|
||||
|
||||
def is_followup(message,intent):
|
||||
if re.search(r'和刚才一样|其他不变|其它不变|每箱不变',message):return True
|
||||
if TOPIC_BOUNDARY.search(message):return False
|
||||
text=message.strip().strip(',,。.!!?? ')
|
||||
if intent.get('errors') and re.search(r'邮编|重量|箱|kg',message,re.I):return True
|
||||
if re.match(r'^(?:那(?:么)?|换成|改成|改为|如果|还是|同样|目的仓改|仓码改|只要|货物是|这个价格|这个费用)',text):return True
|
||||
if intent.get('warehouse') or intent.get('unknown_warehouses'):
|
||||
return not (intent['country'] and intent['weight'])
|
||||
if intent.get('mode')!='quote':return not (intent['country'] and intent['weight'])
|
||||
if re.fullmatch(r'(?:邮编|zip|postcode)?\s*\d{5}(?:-\d{4})?(?:呢)?',text,re.I):return True
|
||||
if re.fullmatch(r'(?:义乌|华东|深圳|华南|美国|美西|美中|美东|东[12]区|西[12]区|中[12]区|不包税|包税)(?:交仓|仓)?(?:呢)?',text):return True
|
||||
return bool(len(text)<=60 and not (intent['country'] and intent['weight']) and any(intent.get(k) is not None for k in ('services','kinds','transport','weight','dims','cbm','tax','origin','zone','material','metal_scope','metal_chargeable_weight')))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""English rendering for deterministic quotes; numerical facts remain unchanged."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def translate_quote(text):
|
||||
replacements=(
|
||||
('美森正班海派','Matson regular sea parcel'),('美森加班海派','Matson extra sea parcel'),
|
||||
('美森正班海卡','Matson regular sea truck'),('美森加班海卡','Matson extra sea truck'),
|
||||
('纽约EXX海铁','New York EXX sea rail'),('洛杉矶普船全卡','Los Angeles regular sea truck direct'),
|
||||
('洛杉矶普船海卡','Los Angeles regular sea truck'),('芝加哥普船海铁','Chicago regular sea rail'),
|
||||
('休斯顿普船海卡','Houston regular sea truck'),('纽约普船海卡','New York regular sea truck'),
|
||||
('萨凡纳普船海卡','Savannah regular sea truck'),('EXX海卡','EXX sea truck'),('合德海卡','Hede sea truck'),
|
||||
('合德海派','Hede sea parcel'),('普船海派','Regular sea parcel'),
|
||||
('请补充箱数、每箱重量和尺寸,继续核算计费重及超重超尺寸费用。','Please provide the carton count, weight and dimensions of each carton to calculate chargeable weight and size surcharges.'),
|
||||
('发我目的仓码或邮编,可继续匹配到仓线路。','Send the destination warehouse code or ZIP code to match the route.'),
|
||||
('货物多少公斤、几箱?','What are the total weight and carton count?'),
|
||||
('当前资料没有美国空运费率,下面列出海运方案。','The current rate sheet has no US air rates. Sea options are listed below.'),
|
||||
('以下按各目的仓分别比较;实际分票请提供每个仓的重量。','Each destination is compared separately; provide the weight assigned to each shipment.'),
|
||||
('按相同区域、计费单位及税费方式比较的较低价方案:','Lower-priced options within the same region, billing unit and tax basis:'),
|
||||
('按资料中的参考时效,较快方案如下;提取不等于送达或签收:','Faster reference options follow. Pickup timing is not a delivery or receipt commitment:'),
|
||||
('该邮编属于遥远地址,派送附加费需单独确认。','This ZIP code is extremely remote; the delivery surcharge requires confirmation.'),
|
||||
('海派已计入偏远附加费','Sea parcel totals include the remote surcharge of '),
|
||||
('当前资料没有匹配的线路价格,提供目的仓码或邮编可继续查询。','No matching route rate was found. Please provide the destination warehouse or ZIP code.'),
|
||||
('美国线路参考时效','US reference transit times'),('美国线路报价','US route rates'),('基础运费','base freight'),('美国','US'),('义乌','Yiwu'),('华南','South China'),
|
||||
('不包税','tax excluded'),('包税','tax included'),('美西','US West'),('美中','US Central'),('美东','US East'),
|
||||
('开船后参考','Reference timing after sailing: '),('船开后','After sailing: '),('开船后','After sailing: '),
|
||||
('若干','several '),
|
||||
('提取',' until pickup'),('天左右',' days approximately'),('天',' days'),('元/KG',' CNY/kg'),('元/CBM',' CNY/CBM'),
|
||||
('元',' CNY'),(':',': '),(';','; '),(',',', '),('(',' ('),(')',')'))
|
||||
for source,target in replacements:text=text.replace(source,target)
|
||||
text=re.sub(r'([东中西])(\d)区',lambda m:{'东':'East','中':'Central','西':'West'}[m[1]]+' zone '+m[2],text)
|
||||
return text
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Separate metal chargeable-weight declarations from the shipment's gross weight."""
|
||||
|
||||
import re
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
def material_intent(text,weight_pattern,to_kg):
|
||||
declarations=re.sub(r'铁铝(?:附加费|加费|费用)','',text)
|
||||
metal=bool(re.search(r'铁制|钢制|铝制|铁铝|不锈钢|(?:铁|钢|铝)(?:件|货|扣|罐|盒|板|管|架|材)',declarations))
|
||||
generic='金属' in text
|
||||
ordinary=bool(re.search(r'普通货|普货|非铁铝',text))
|
||||
partial=bool(re.search(r'只有|部分|其中|有些|只是|一部分',text) or
|
||||
metal and re.search(r'塑料|木制|布料',text))
|
||||
scope='partial' if partial and (metal or generic) else ('all' if re.search(r'全是|全部是|都是|整票是|货物是|换成|改成',text) and metal else None)
|
||||
material=('ordinary' if '非铁铝' in text else 'metal' if metal else 'unknown_metal' if generic
|
||||
else 'ordinary' if ordinary or re.search(r'塑料|木制',text) else None)
|
||||
name=r'(?:铁铝|铁制品|钢制品|铝制品|铁件|钢件|铝件|金属)(?:部分|货物)?(?:的)?'
|
||||
patterns=(name+r'\s*计费重(?:量)?\s*(?:为|是|[::])?\s*'+weight_pattern.pattern,
|
||||
name+r'\s*按\s*'+weight_pattern.pattern+r'\s*计费',
|
||||
r'(?:铁铝|铁制品|钢制品|铝制品|铁件|钢件|铝件|金属)部分(?:的计费重(?:量)?)?\s*'
|
||||
r'(?:还是|仍然是|仍是|改为|改成|换成)\s*'+weight_pattern.pattern)
|
||||
charged=None;cleaned=text;errors=[];oral=False
|
||||
for index,pattern in enumerate(patterns):
|
||||
matches=list(re.finditer(pattern,text,re.I))
|
||||
for match in matches:
|
||||
value=to_kg(*match.groups())
|
||||
if charged is not None and Decimal(charged)!=value:errors.append('铁铝货物的计费重不一致,请确认。')
|
||||
charged=str(value);scope='partial'
|
||||
oral=oral or (index==2 and '计费重' not in match[0])
|
||||
if not 0<value<=1000000:errors.append('请提供大于0的有效铁铝货物计费重。')
|
||||
cleaned=cleaned[:match.start()]+' '*(match.end()-match.start())+cleaned[match.end():]
|
||||
return {'material':material,'metal_scope':scope,'metal_chargeable_weight':charged,
|
||||
'quantity_text':cleaned,'errors':errors,'metal_weight_update':True if oral else None}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Keep unanswered US shipping questions outside legacy regional model knowledge."""
|
||||
|
||||
import re
|
||||
|
||||
from .quote_intent import US
|
||||
from .pricing import shipping_region
|
||||
|
||||
|
||||
def answer_us_fallback(message,conv_id):
|
||||
if re.search(r'理赔|赔偿|索赔|破损|丢失|退件|投诉',message):return None
|
||||
if re.search(r'换个话题|另外问',message):return None
|
||||
from .quote_edits import clean_conditions
|
||||
current=clean_conditions(message)
|
||||
active=bool(US.search(current))
|
||||
if not active and shipping_region(current) is not None:return None
|
||||
if not active and conv_id:
|
||||
from .quote_service import previous_quote_intents
|
||||
active=any(intent['country']=='US' for intent in previous_quote_intents(conv_id,set()))
|
||||
if not active:return None
|
||||
from .quote_data import load_book
|
||||
if not load_book():return {'t':'当前尚未包含可用的美国报价表,请提供目的地仓码或邮编及货物信息,联系人工确认。'}
|
||||
english=not re.search(r'[\u4e00-\u9fff]',message) and bool(re.search(r'[A-Za-z]{3,}',message))
|
||||
if english:
|
||||
return {'t':'Please specify the US route or destination warehouse/ZIP code and the point you want to confirm. Unlisted charges or service conditions require confirmation by customer support.'}
|
||||
return {'t':'请说明您想确认的美国渠道、目的仓码或邮编,以及具体的费用或发货要求;未明确的服务条件需要联系人工核对。'}
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Resolve same-conversation quote edits and return local facts without model I/O."""
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from .db import connect
|
||||
from .quote_data import load_book, postcode_fee
|
||||
from .quote_engine import US, QUOTE_WORDS, parse_intent, is_followup, variants, render_rates
|
||||
|
||||
|
||||
def previous_quote_intents(conv_id,codes):
|
||||
"""Read the current quote back to its topic boundary, without a turn cutoff."""
|
||||
earlier_intents=[]
|
||||
if conv_id:
|
||||
connection=connect()
|
||||
try:
|
||||
recent=connection.execute("SELECT content FROM messages WHERE conv_id=? AND role='user' ORDER BY id DESC",(conv_id,))
|
||||
for (previous,) in recent:
|
||||
if re.search(r'理赔|赔偿|破损|丢失|退件|投诉|查单|轨迹|签收|换个话题|另外问',previous):break
|
||||
earlier=parse_intent(previous,codes)
|
||||
if earlier['country']=='other':break
|
||||
if not (QUOTE_WORDS.search(previous) or US.search(previous) or is_followup(previous,earlier) or
|
||||
any(earlier.get(key) for key in ('weight','dims','cbm','warehouse','postal'))):break
|
||||
earlier_intents.append(earlier)
|
||||
if not is_followup(previous,earlier):break
|
||||
finally:
|
||||
connection.close()
|
||||
return earlier_intents
|
||||
|
||||
|
||||
def intent_with_context(message, conv_id, book):
|
||||
from .quote_context import merge_intent
|
||||
|
||||
codes = {row['code'] for row in book['warehouses']}
|
||||
codes.update(value.upper() for rate in book['rates'] for value in rate['destinations'])
|
||||
intent = parse_intent(message,codes)
|
||||
earlier_intents=previous_quote_intents(conv_id,codes) if is_followup(message,intent) else []
|
||||
if intent.get('metal_weight_update') and not earlier_intents:
|
||||
intent['metal_chargeable_weight']=None
|
||||
intent['errors'].append('请确认铁铝部分的计费重,不能把毛重直接当作计费重。')
|
||||
if earlier_intents:
|
||||
state=earlier_intents[-1]
|
||||
if state.get('metal_weight_update'):state['metal_chargeable_weight']=None
|
||||
for update in list(reversed(earlier_intents[:-1]))+[intent]:
|
||||
state=merge_intent(update,state)
|
||||
intent=state
|
||||
if (intent['warehouse'] or intent.get('unknown_warehouses')) and intent['country'] is None:
|
||||
intent['country']='US'
|
||||
return intent
|
||||
|
||||
|
||||
def answer_quote(message, conv_id):
|
||||
if re.search(r'理赔|赔偿|破损|丢失|退件|投诉|查单|轨迹|签收', message):
|
||||
return None
|
||||
# Avoid a new read for ordinary chat; short followups need their local context.
|
||||
from .shipping_faq import preparation_topic
|
||||
if not (US.search(message) or QUOTE_WORDS.search(message) or preparation_topic(message) or conv_id or
|
||||
re.search(r'(?<![A-Za-z0-9])[A-Za-z]{2,4}[0-9](?![A-Za-z0-9])', message)):
|
||||
return None
|
||||
try:
|
||||
book = load_book()
|
||||
if not book:
|
||||
return None
|
||||
intent = intent_with_context(message, conv_id, book)
|
||||
if intent['country'] != 'US':
|
||||
if intent['country'] is None and intent.get('mode')=='preparation':
|
||||
return {'t':'请先确认目的国家和所选渠道,我再为您核对交仓、标签或发货资料要求。'}
|
||||
return None
|
||||
if intent.get('errors'):
|
||||
return {'t':'\n'.join(intent['errors'])}
|
||||
if intent.get('unknown_warehouses'):
|
||||
return {'t':'未找到目的仓码 '+ '、'.join(intent['unknown_warehouses'])+',请核对仓码,或提供5位美国邮编继续查询。'}
|
||||
if not (QUOTE_WORDS.search(message) or is_followup(message,intent) or
|
||||
any(intent.get(key) for key in ('weight','dims','cbm','warehouse','postal'))):
|
||||
return None
|
||||
for key in ('weight','cbm'):
|
||||
if intent[key] is not None and not (Decimal(0) < Decimal(intent[key]) <= Decimal(1000000)):
|
||||
return {'t':'请提供大于 0 的有效重量或体积。'}
|
||||
if intent['boxes'] is not None and not 0 < intent['boxes'] <= 10000:
|
||||
return {'t':'请提供有效的货物箱数。'}
|
||||
dimensions=[intent['dims']] if intent['dims'] else []
|
||||
dimensions += [piece['dims'] for piece in intent.get('packages') or [] if piece.get('dims')]
|
||||
if any(not 0 < value <= 100000 for dims in dimensions for value in dims):
|
||||
return {'t':'请提供大于 0 的有效长宽高。'}
|
||||
if intent['air_only']:
|
||||
return {'t':'当前美国报价资料包含美森、EXX、合德及普船的海卡、海铁和海派。发我目的仓码或邮编、重量,可以列出这些线路的价格;空运费率当前资料没有列出,空运承运条件也需单独确认。'}
|
||||
from .quote_answers import answer_business
|
||||
preparation=None
|
||||
if intent.get('mode')=='preparation':
|
||||
from .shipping_faq import answer_preparation
|
||||
preparation=answer_preparation(intent,book)
|
||||
if preparation_topic(message)!='schedule' or not re.search(r'\d+\s*(?:KG|公斤|千克|克|吨|方|CBM)',intent['text'],re.I):
|
||||
return {'t':preparation}
|
||||
intent['mode']='cheapest' if re.search(r'最便宜|最划算|最低价',message) else 'quote'
|
||||
business=answer_business(intent,book)
|
||||
if business is not None:return {'t':business}
|
||||
destinations = variants(intent,book)
|
||||
fees = []
|
||||
for destination in destinations:
|
||||
postal = destination['postal']
|
||||
if postal and (postal[:3] in ('006','007','008','009','966','967','968','969','995','996','997','998','999') or postal=='89124'):
|
||||
return {'t':f'当前海派资料不接收邮编 {postal} 的地址,请提供其他目的仓码或联系人工确认可用线路。'}
|
||||
fees.append(postcode_fee(book['id'],postal) if postal else None)
|
||||
reply=render_rates(intent,book,destinations,fees)
|
||||
if intent.get('mode')=='total':
|
||||
reply+='\n以上为已提供条件下可计算的运费,各方案按所列包税/不包税方式分别核算;目的仓、箱规及未确定附加费需核实后才能确认最终应付总价。'
|
||||
if intent.get('mode')=='cheapest' and re.search(r'便宜一?点|折扣|优惠|打折',message):
|
||||
reply+='\n以上按当前价表比较,折扣或合作价格需人工确认,尚未修改单价。'
|
||||
return {'t':reply+('\n'+preparation if preparation else '')}
|
||||
except (sqlite3.Error, ValueError, KeyError, TypeError, InvalidOperation):
|
||||
return {'t':'报价数据暂时无法读取,请稍后重试。'}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Extract only this workbook's local detail cells; never evaluate external links."""
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
from xml.etree import ElementTree as ET
|
||||
from zipfile import ZipFile
|
||||
|
||||
from .quote_data import decimal_text
|
||||
|
||||
|
||||
NS = {'s':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
|
||||
TRUCK_SHEETS = ('美森正班海卡','美森加班海卡','EXX海卡','合德海卡','纽约EXX海铁',
|
||||
'洛杉矶普船海卡','洛杉矶普船全卡','芝加哥普船海铁','休斯顿普船海卡','纽约普船海卡','萨凡纳普船海卡')
|
||||
|
||||
|
||||
def read_sheets(path):
|
||||
path = Path(path)
|
||||
if path.stat().st_size > 20*1024*1024:
|
||||
raise ValueError('Quote workbook is too large')
|
||||
with ZipFile(path) as archive:
|
||||
if sum(info.file_size for info in archive.infolist()) > 100*1024*1024:
|
||||
raise ValueError('Expanded quote workbook is too large')
|
||||
strings = []
|
||||
if 'xl/sharedStrings.xml' in archive.namelist():
|
||||
for entry in ET.fromstring(archive.read('xl/sharedStrings.xml')):
|
||||
strings.append(''.join(t.text or '' for t in entry.findall('.//s:t', NS)))
|
||||
workbook = ET.fromstring(archive.read('xl/workbook.xml'))
|
||||
rels = {r.attrib['Id']:r.attrib['Target'] for r in ET.fromstring(archive.read('xl/_rels/workbook.xml.rels'))}
|
||||
result = {}
|
||||
for sheet in workbook.find('s:sheets', NS):
|
||||
target = rels[sheet.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id']]
|
||||
target = target.lstrip('/') if target.startswith('/') else posixpath.normpath('xl/'+target)
|
||||
rows = {}
|
||||
for cell in ET.fromstring(archive.read(target)).findall('s:sheetData/s:row/s:c', NS):
|
||||
ref = cell.attrib['r']
|
||||
column = re.sub('[0-9]', '', ref)
|
||||
if len(column) != 1 or column > 'Q':
|
||||
continue
|
||||
raw = cell.find('s:v', NS)
|
||||
value = raw.text if raw is not None else ''
|
||||
if cell.attrib.get('t') == 's':
|
||||
value = strings[int(value)]
|
||||
elif cell.attrib.get('t') == 'inlineStr':
|
||||
value = ''.join(t.text or '' for t in cell.findall('.//s:t', NS))
|
||||
formula = cell.find('s:f', NS)
|
||||
if formula is not None and formula.text and re.search(r'\[[0-9]+\]', formula.text):
|
||||
continue
|
||||
if value:
|
||||
rows.setdefault(int(re.sub('[^0-9]', '', ref)), {})[column] = value
|
||||
result[sheet.attrib['name']] = rows
|
||||
return result
|
||||
|
||||
|
||||
def export_snapshot(path):
|
||||
sheets = read_sheets(path)
|
||||
missing = set(TRUCK_SHEETS + ('海派','FBA分区表','亚马逊仓库代码表','UPS&FedEx偏远地区表')) - sheets.keys()
|
||||
if missing:
|
||||
raise ValueError('Quote workbook is missing required local detail sheets')
|
||||
result = {'schema':1, 'source_name':Path(path).name,
|
||||
'source_sha256':hashlib.sha256(Path(path).read_bytes()).hexdigest(),
|
||||
'rates':[], 'warehouses':[], 'postcodes':[], 'documents':[]}
|
||||
for name in TRUCK_SHEETS:
|
||||
rows = sheets[name]
|
||||
destination_col = 'A' if name in TRUCK_SHEETS[:4] else 'B'
|
||||
price_cols = ('B','C','D') if destination_col == 'A' else ('C','D','E')
|
||||
eta_col = 'E' if destination_col == 'A' else 'F'
|
||||
for number, row in rows.items():
|
||||
if number < 6 or not re.fullmatch(r'\d+(?:\.\d+)?', row.get(price_cols[0], '')):
|
||||
continue
|
||||
destinations = [p.strip() for p in re.split(r'[/\n、]+', row.get(destination_col, '')) if p.strip()]
|
||||
if not destinations:
|
||||
raise ValueError('Price row is missing destinations')
|
||||
for column, origin, unit, tax in zip(price_cols, ('义乌','义乌','华南'), ('cbm','kg','kg'), ('excluded','included','included')):
|
||||
result['rates'].append({'service':name, 'kind':'truck', 'origin':origin, 'zone':'',
|
||||
'unit':unit, 'tax':tax, 'min_weight':'0', 'price':decimal_text(row[column], positive=True),
|
||||
'eta':row.get(eta_col, ''), 'destinations':destinations, 'source_sheet':name, 'source_cell':f'{column}{number}'})
|
||||
parcel = sheets['海派']
|
||||
for origin, header, first in (('义乌',4,9), ('华南',13,18)):
|
||||
for start_col in ('C','F','I','L'):
|
||||
for offset, tier in enumerate(('12','51','101')):
|
||||
column = chr(ord(start_col)+offset)
|
||||
for index, zone in enumerate(('美西','美中','美东')):
|
||||
number = first+index
|
||||
result['rates'].append({'service':parcel[header][start_col], 'kind':'parcel', 'origin':origin,
|
||||
'zone':zone, 'unit':'kg', 'tax':'included', 'min_weight':tier,
|
||||
'price':decimal_text(parcel[number][column], positive=True),
|
||||
'eta':parcel[header+2][start_col], 'destinations':[], 'source_sheet':'海派', 'source_cell':f'{column}{number}'})
|
||||
for name, first in (('FBA分区表',3), ('亚马逊仓库代码表',2)):
|
||||
for number, row in sheets[name].items():
|
||||
if number < first or not row.get('A'):
|
||||
continue
|
||||
is_zone = name == 'FBA分区表'
|
||||
result['warehouses'].append({'code':row['A'].strip().upper(),
|
||||
'zone':row.get('B','') if is_zone else '', 'state':row.get('C','') if is_zone else '',
|
||||
'postal':row.get('D','') if is_zone else '', 'address':row.get('B','') if not is_zone else '',
|
||||
'source_sheet':name, 'source_cell':f'A{number}'})
|
||||
for number, row in sheets['UPS&FedEx偏远地区表'].items():
|
||||
if number <= 23:
|
||||
continue
|
||||
for column, severity, fee in (('B','remote','1'), ('F','extended','2'), ('J','extreme',None)):
|
||||
postal = row.get(column, '')
|
||||
if postal:
|
||||
result['postcodes'].append({'postal':postal, 'severity':severity, 'fee':fee})
|
||||
for name, rows in sheets.items():
|
||||
if name in ('快速查询','UPS&FedEx偏远地区表','FBA分区表','亚马逊仓库代码表'):
|
||||
continue
|
||||
for number, row in rows.items():
|
||||
if number <= 1 or (name in TRUCK_SHEETS and number <= 5):
|
||||
continue
|
||||
# Long detail text contains rules; short lookup rows contain service fees.
|
||||
for column, value in row.items():
|
||||
if len(value) >= 20 and not re.search(r'公司地址|TEL:|船名航次|预计开船日期|关税查询网址', value):
|
||||
result['documents'].append({'sheet':name, 'cell':f'{column}{number}', 'text':value})
|
||||
if name in ('一件代发收费','FDA申报清单'):
|
||||
text = ';'.join(row.values())
|
||||
result['documents'].append({'sheet':name,'cell':f'A{number}','text':text})
|
||||
return result
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报价表扩展数据(自动生成,来源:炜易达 VIP 10月15日9点执行报价表)
|
||||
|
||||
包含:海外仓卡派、二级补仓、德国仓亚马逊退货、产品附加费、DPD 岛屿偏远邮编。
|
||||
"""
|
||||
|
||||
# 海外仓卡派:按 kg(21KG+/51KG+)或按方(0.5CBM+/1CBM+)计费
|
||||
# 价格单位:按 kg 为 RMB/kg,按方为 RMB/CBM
|
||||
WAREHOUSE_CARD = {'谷仓法国巴黎1仓-95500-FR\n谷仓法国巴黎2仓-60440-FR\n谷仓法国巴黎4仓-77230-FR': {'卡航': {'kg21': 19.5, 'kg51': 18.5, 'cbm05': 3200.0, 'cbm1': 3020.0}, '普卡': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2920.0}, '铁路': {'kg21': 16.8, 'kg51': 15.8, 'cbm05': 2722.0, 'cbm1': 2542.0}, '海运': {'kg21': 12.5, 'kg51': 11.5, 'cbm05': 1952.0, 'cbm1': 1772.0}}, '4PX-69110-PL\n谷仓-69110-PL\nSLU2-69110-PL': {'卡航': {'kg21': 18.2, 'kg51': 17.2, 'cbm05': 2966.0, 'cbm1': 2786.0}, '普卡': {'kg21': 17.7, 'kg51': 16.7, 'cbm05': 2876.0, 'cbm1': 2686.0}, '铁路': {'kg21': 15.5, 'kg51': 14.5, 'cbm05': 2488.0, 'cbm1': 2308.0}, '海运': {'kg21': 11.1, 'kg51': 10.1, 'cbm05': 1700.0, 'cbm1': 1520.0}}, 'EDAPL-69100-PL': {'卡航': {'kg21': 18.6, 'kg51': 17.6, 'cbm05': 3038.0, 'cbm1': 2858.0}, '普卡': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2948.0, 'cbm1': 2758.0}, '铁路': {'kg21': 15.9, 'kg51': 14.9, 'cbm05': 2560.0, 'cbm1': 2380.0}, '海运': {'kg21': 11.5, 'kg51': 10.5, 'cbm05': 1772.0, 'cbm1': 1592.0}}, '4PX-66340-PL\n菜鸟仓-66340-PL': {'卡航': {'kg21': 18.9, 'kg51': 17.9, 'cbm05': 3092.0, 'cbm1': 2912.0}, '普卡': {'kg21': 18.4, 'kg51': 17.4, 'cbm05': 3002.0, 'cbm1': 2812.0}, '铁路': {'kg21': 16.2, 'kg51': 15.2, 'cbm05': 2614.0, 'cbm1': 2434.0}, '海运': {'kg21': 11.9, 'kg51': 10.9, 'cbm05': 1844.0, 'cbm1': 1664.0}}, '希音-44141-PL\n希音-55040-PL': {'卡航': {'kg21': 19.5, 'kg51': 18.5, 'cbm05': 3200.0, 'cbm1': 3020.0}, '普卡': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2920.0}, '铁路': {'kg21': 16.8, 'kg51': 15.8, 'cbm05': 2722.0, 'cbm1': 2542.0}, '海运': {'kg21': 12.5, 'kg51': 11.5, 'cbm05': 1952.0, 'cbm1': 1772.0}}, '谷仓捷克1仓-25261-CZ\n谷仓捷克2仓-25261-CZ\n谷仓捷克3仓-41002-CZ\n谷仓捷克4仓-25261-CZ\n谷仓捷克5仓-25219-CZ\n谷仓捷克7仓-25301-CZ\n谷仓捷克8仓-41002-CZ': {'卡航': {'kg21': 18.6, 'kg51': 17.6, 'cbm05': 3038.0, 'cbm1': 2858.0}, '普卡': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2948.0, 'cbm1': 2758.0}, '铁路': {'kg21': 15.9, 'kg51': 14.9, 'cbm05': 2560.0, 'cbm1': 2380.0}, '海运': {'kg21': 11.5, 'kg51': 10.5, 'cbm05': 1772.0, 'cbm1': 1592.0}}, '4PX布拉格A仓-25261-CZ': {'卡航': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2930.0}, '普卡': {'kg21': 18.5, 'kg51': 17.5, 'cbm05': 3020.0, 'cbm1': 2830.0}, '铁路': {'kg21': 16.3, 'kg51': 15.3, 'cbm05': 2632.0, 'cbm1': 2452.0}, '海运': {'kg21': 12.0, 'kg51': 11.0, 'cbm05': 1862.0, 'cbm1': 1682.0}}, '4PX马德里A仓-19171-ES': {'卡航': {'kg21': 20.8, 'kg51': 19.8, 'cbm05': 3434.0, 'cbm1': 3254.0}, '普卡': {'kg21': 20.3, 'kg51': 19.3, 'cbm05': 3344.0, 'cbm1': 3154.0}, '铁路': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2956.0, 'cbm1': 2776.0}, '海运': {'kg21': 13.7, 'kg51': 12.7, 'cbm05': 2168.0, 'cbm1': 1988.0}}, '盘古-63150-DE\n新欧达-31628-DE': {'卡航': {'kg21': 19.4, 'kg51': 18.4, 'cbm05': 3182.0, 'cbm1': 3002.0}, '普卡': {'kg21': 18.9, 'kg51': 17.9, 'cbm05': 3092.0, 'cbm1': 2902.0}, '铁路': {'kg21': 16.7, 'kg51': 15.7, 'cbm05': 2704.0, 'cbm1': 2524.0}, '海运': {'kg21': 12.3, 'kg51': 11.3, 'cbm05': 1916.0, 'cbm1': 1736.0}}}
|
||||
|
||||
# 二级补仓(海外仓中转)主要服务费
|
||||
SECONDARY_WAREHOUSE = {'服务': '1.贴标:2张FBA标签,一张快递面单)单件计费重量范围在(0KG<X≤30KG) 2.打板:实际打板数为准(1个板大概1.2方-1.5方) 3.卸货费', '头程单价指示': '欧洲铁路头程单价:欧洲铁路渠道 中欧卡航头程单价:中欧卡航渠道 欧洲海运头程单价:海运快线/海运热门仓卡派直送 英国头程单价:英国专线(DPD)', '二次派送': '1. 欧洲/英国二级补仓无需二次派送费用,可自提单价-1/KG 2. 海外仓在德国,如需发往其他国家补运费差价', '仓储费': '德国:免费存储25天,超过5RMB/方/天,61-180天 7RMB/方/每天,181天以上 15RMB/方/每天 英国:免费存储25天,超过8RMB/方/天,90-120/方/天 9.5RMB/方/天,超120天 15RMB/方/天', '订单处理费': '1:针对一个SKU发往一个地址作为一个订单收取15RMB订单操作费; 2:针对不同票数合并发往一个地址作为一个订单收取15RMB订单操作费; 出货之前都需要填写出货指令', '销毁费': '德国:单询 英国:50英镑/件', '换产品SKU费': '欧洲:针对一个箱里面是一种SKU要换标:开箱关箱费13RMB/箱换SKU:4RMB/个,清点:2RMB/个针对一箱多个SKU换标(费用单询) 英国:针对一个箱里面是一种SKU要换标:开箱关箱费20RMB/箱换SKU:6RMB/个,清点:3RMB/个针对一箱多个SKU换标(费用单询)'}
|
||||
|
||||
# 德国仓亚马逊退货费用(单位:欧元)
|
||||
DE_RETURN_FEES = [
|
||||
{'cat': '2. Outbound 出库', 'item': '2.1.1 Picking 整箱出库', 'sub': 'Single Carton 每箱', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.4 Packing 打包费', 'sub': 'Per Carton 每箱', 'price': 1.5},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.5 Unpacking and Inspection 开箱检验', 'sub': 'Per Carton 每箱', 'price': 1},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.6 Destroy Product without Battery 不带电池产品销毁', 'sub': 'Per 1KG 每公斤', 'price': 1},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.7 Destroy battery 销毁电池', 'sub': 'Per 1KG 每公斤', 'price': 1.5},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.8 Cancel Order 截单费', 'sub': 'Per order 每单', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.9 Claim Fee 认领费', 'sub': 'Every order 每个订单', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.10 Lost Shipping Claim 丢件索赔服务费', 'sub': 'Per order 每单', 'price': 5},
|
||||
]
|
||||
|
||||
# 产品附加费清单
|
||||
PRODUCT_SURCHARGES = [
|
||||
('电池 标准箱100瓦以下非危电池/内电不超100瓦产品。头程参考海运快线快递单价标准', '资料齐全+1/KG 资料不齐全+2/KG'),
|
||||
('手机,平板电脑', '5/KG'),
|
||||
('铝制品', '2元/KG'),
|
||||
('瓷砖', '1元/KG'),
|
||||
('玻璃纤维网格织物、玻璃纤维长丝、聚酯高强力纱', '1元/KG'),
|
||||
('胶合板', '1元/KG'),
|
||||
('铜版纸', '1元/KG'),
|
||||
('钢丝绳和钢缆', '1元/KG'),
|
||||
('包包、U型枕、吊床,普通纺织品', '1元/KG(中欧卡航+2)'),
|
||||
('与接触食品类产品(厨具、榨汁机、擀面杖、杯子等)', '1元/KG'),
|
||||
('LED灯、白炽灯、钨丝灯类、电子温度计', '1元/KG'),
|
||||
('皮革制品', '1元/KG'),
|
||||
('球类', '1元/KG'),
|
||||
('木制品', '1元/KG'),
|
||||
('带磁产品', '1元/KG'),
|
||||
('蓝牙产品 无线产品 数据线', '1元/KG'),
|
||||
('金属及其制品:不锈钢无缝钢管耐腐蚀钢、铸铁产品、可锻铸铁螺纹管和接头、钢铁管配件、钢铁制紧固件、预应力非合金钢丝和钢绞线、活页夹的贱金属附件、铸铁井盖', '1元/KG'),
|
||||
('光伏、晶体硅光伏组件、太阳能板、眼镜', '2元/KG'),
|
||||
('玩具、沐浴盐球、碳包 蜡烛', '2元/KG'),
|
||||
('厨房刀具 (全长不超30CM)', '2元/KG'),
|
||||
('空气净化器', '2元/KG'),
|
||||
('工具箱', '2元/KG'),
|
||||
('眼镜类 笔类', '2元/KG'),
|
||||
('机顶盒 计时器(不包括大的钟表) 电子手环', '2元/KG'),
|
||||
('带陶瓷产品', '2元/KG'),
|
||||
('汽车/摩托车/自行车配件/平衡车/汽车配件', '2元/KG'),
|
||||
('卡客车轮胎、铝合金轮毂 、笔类', '2元/KG'),
|
||||
('投影仪', '2元/KG'),
|
||||
('成人用品、性用品、', '3元/KG'),
|
||||
('服装类(大衣,棉服,风衣,外套,斗篷,运动服饰,毛衫,T恤,衬衫,连体服饰,套装,裙子,骑行服),毛巾类,床上用品,和内衣内裤(海关编码61-65开头)', '3/KG(中欧卡航+5)'),
|
||||
('鞋类(包括塑料拖鞋、鞋垫)不包括鞋带', '3/KG(中欧卡航+5)'),
|
||||
('针织类的帽子、围巾、手套、披肩,窗帘', '3/KG(中欧卡航+5)'),
|
||||
('U盘/内存卡', '3元/个'),
|
||||
('各种码表 手表', '3.5元/个'),
|
||||
('车载DVD/车载显示屏/车载收音机/行车记录仪/行车导航仪', '80元/台'),
|
||||
('投影仪', '35元/台'),
|
||||
('平衡车/平板车(单个15KG以下)(超100瓦安时拒接)', '单询'),
|
||||
('平衡车/平板车(超100瓦安时拒接)', '单询'),
|
||||
('电动滑板车(单个15KG以下)(超100瓦安时拒接)', '单询'),
|
||||
('电动滑板车(超100瓦安时拒接)', '单询'),
|
||||
('平衡车/平板车/滑板车(单个20KG以上)', '单询'),
|
||||
('自行车、电动自行车、', '400/台(计费重超60KG拒收)'),
|
||||
('药物、化学产品及原料', '拒接'),
|
||||
('玩具车、积木类', '不侵权+2/KG'),
|
||||
('管制刀具,弓箭,枪支弹药及配件', '拒接'),
|
||||
('电子打火机、电子烟', '拒接'),
|
||||
('以上表格未列明的产品', '另外询价'),
|
||||
]
|
||||
|
||||
# DPD 欧洲岛屿偏远邮编(附加费 35 欧/件)
|
||||
DPD_ISLAND_POSTCODES = {'丹麦': {'code': 'DK', 'text': '4592, 5960, 5970, 5985, 6720, 7884,8305,8592, 9940, 9950, 9960, Bornholm: 3700, 3720, 3730,3740,3751, 3760, 3770, 3782, 3790'}, '德国': {'code': 'DE', 'text': 'Hiddensee: 18565, NordfriesischeInseln:25849, 25859, 25863, 25869, 25938, 25946, 25980,25992,25996–25999, Ostfries. Inseln: 26465, 26474, 26486,26548,26571, 26579, 26757, Helgoland: 27498,27499,Chiemsee: 83256 Neuwerk:'}, '爱沙尼亚': {'code': 'EE', 'text': '62601, 88001–88005, 91217,91301–91320,92001–92420, 93001–94799, 96027, 96098'}, '芬兰': {'code': 'FI', 'text': 'Aland–Inseln: 22000–22999'}, '法国': {'code': 'FR', 'text': '17111, 17123, 17190, 17310, 17370,17410, 17480,17550, 17580, 17590, 17630, 17670, 17740, 17880,17940,22870, 29242, 29253, 29259, 29990, 56360, 56590,56780,56840, 85330, 85350, Korsika: 20000–20999'}, '希腊': {'code': 'GR', 'text': 'Saronische Inseln: 180xx, 189xx,Ionische Inseln: 28xxx–29xxx, 31xxx, 49xxx, Berg Athos:63086–63087,Kreta: 70xxx–74xxx und Inseln der Ägäis: 80xxx–85xxx'}, '意大利': {'code': 'IT', 'text': 'Pontinische Inseln: 04020, 04027, Sardinien:07000–09999, Lagune von Venedig: 30010, 30012, 30100,30121–30126, 30131–30133, 30135, 30141, Elba mitTyrrhenischeInseln: 57030–57039, 58012–58013, 58018, Tremiti Inseln:71040, Inseln im Golf von Neapel: 80070–80071, 80073–80077, 80079, Inselgruppen um Sizilien: 90010, 91017, 91023,92010, 98050, 98052, 98055Einige PLZ können Gebiete auf Inseln und dem Festlandbetreffen.'}, '克罗地亚': {'code': 'HR', 'text': '20221–20226, 20260–20263, 20264,20270– 20275, 20290, 21220, 21223–21225, 21400,21403–21405,21410, 21412, 21413, 21420, 21423–21426, 21430, 21432,21450, 21454, 21460, 21462–21463, 21465–21467, 21469,21480, 21483, 21485, 22231–22236, 22240–22244, 23212,23234, 23249–23251, 23262–23264, 23271–23275, 23281–23287, 23291–23296, 51280–51281, 51500, 51511–51517,51521–51523, 51550–51552, 51554–51557, 51559, 51561–51562, 51564, 53291, 53294, 53296'}, '荷兰': {'code': 'NL', 'text': '1156AA–1156ZZ, 1791AA–1797ZZ,8881AA– 8884ZZ, 8891AA–8897ZZ, 8899AA–8899ZZ,9161AA–9164ZZ, 9166AA–9166ZZ'}, '葡萄牙': {'code': 'PT', 'text': 'Madeira: 9000–9390, Porto Santo: 9400,Azoren: 9500–9980'}, '瑞典': {'code': 'SE', 'text': '10005, 13025, 13033, 13034, 13036,13038, 13039, 13042, 13043, 13055, 13056, 37022, 43080–43099,45204–45205, 47112–47115, 47500–47599, 62000–62999,74296–74297, 76017–76019, 91803'}, '西班牙': {'code': 'ES', 'text': 'Balearen: 07000–07999'}}
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Blueprint registration, called explicitly by the application factory."""
|
||||
|
||||
|
||||
def register_routes(app):
|
||||
from . import admin, business, chat, customer, files, history, human, pages, speech, visitor
|
||||
for module in (admin, business, chat, customer, files, history, human, pages, speech, visitor):
|
||||
app.register_blueprint(module.bp)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""HTTP adapters for admin; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, Response, render_template, request
|
||||
|
||||
from .. import business_service
|
||||
|
||||
bp = Blueprint('admin', __name__)
|
||||
|
||||
@bp.route('/api/admin/stats')
|
||||
def admin_stats():
|
||||
return business_service.admin_stats()
|
||||
|
||||
|
||||
@bp.route('/admin/login', methods=['POST'])
|
||||
def admin_login():
|
||||
return business_service.admin_login(request.json or {})
|
||||
|
||||
|
||||
@bp.route('/api/export_chat')
|
||||
def export_chat():
|
||||
format = 'csv' if request.args.get('format') == 'csv' else 'xlsx'
|
||||
mimetype = 'text/csv' if format == 'csv' else 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
return Response(business_service.export_chat(format), mimetype=mimetype,
|
||||
headers={'Content-Disposition': 'attachment;filename=chat_export.' + format})
|
||||
|
||||
|
||||
@bp.route('/api/agents/list')
|
||||
def agents_list():
|
||||
return business_service.agents_list()
|
||||
|
||||
|
||||
@bp.route('/api/search_chat')
|
||||
def search_chat():
|
||||
return business_service.search_chat(request.args.get('q', '').strip())
|
||||
|
||||
|
||||
@bp.route('/admin')
|
||||
def admin():
|
||||
return render_template('admin_login.html')
|
||||
|
||||
|
||||
@bp.route('/admin/dashboard')
|
||||
def admin_dash():
|
||||
return render_template('admin.html')
|
||||
@@ -0,0 +1,31 @@
|
||||
"""HTTP adapters for business; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from .. import business_service, visitor_service
|
||||
|
||||
bp = Blueprint('business', __name__)
|
||||
|
||||
@bp.route('/api/my_orders')
|
||||
def my_orders():
|
||||
return business_service.my_orders(request.args.get('phone', '').strip())
|
||||
|
||||
|
||||
@bp.route('/api/ticket', methods=['POST'])
|
||||
def add_ticket():
|
||||
return business_service.add_ticket(request.get_json(silent=True))
|
||||
|
||||
|
||||
@bp.route('/api/tickets')
|
||||
def list_tickets():
|
||||
return business_service.list_tickets()
|
||||
|
||||
|
||||
@bp.route('/api/rate', methods=['POST'])
|
||||
def rate_chat():
|
||||
data = request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
return {'ok': False}, 400
|
||||
if not visitor_service.owns_human_session(data.get('sid')):
|
||||
return {'ok': False}, 404
|
||||
return business_service.rate_chat(data)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""HTTP adapters for chat; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, Response, request, stream_with_context
|
||||
|
||||
from .. import business_service, chat_service
|
||||
|
||||
bp = Blueprint('chat', __name__)
|
||||
|
||||
@bp.route('/stream_chat', methods=['GET', 'POST'])
|
||||
def stream_chat():
|
||||
def error(message):
|
||||
return Response(chat_service.sse({'e':message}) + chat_service.sse({'d':1}), mimetype='text/event-stream')
|
||||
|
||||
if request.method == 'POST':
|
||||
data = request.get_json(silent=True)
|
||||
if not isinstance(data, dict):
|
||||
return error('请求格式无效,请重新发送问题。')
|
||||
msg = data.get('msg', '')
|
||||
conv_id = data.get('conv_id')
|
||||
else:
|
||||
msg = request.args.get('msg', '')
|
||||
conv_id = request.args.get('conv_id')
|
||||
if not isinstance(msg, str):
|
||||
return error('问题必须是文本,请重新输入。')
|
||||
msg = msg.strip()
|
||||
if isinstance(conv_id, (bool, float)):
|
||||
return error('会话编号无效,请新建对话后重试。')
|
||||
if conv_id not in (None, '', 0):
|
||||
if not isinstance(conv_id, (str, int)):
|
||||
return error('会话编号无效,请新建对话后重试。')
|
||||
if isinstance(conv_id, str) and (len(conv_id) > 19 or not conv_id.isascii() or not conv_id.isdecimal()):
|
||||
return error('会话编号无效,请新建对话后重试。')
|
||||
try:
|
||||
conv_id = int(conv_id)
|
||||
except (ValueError, TypeError):
|
||||
return error('会话编号无效,请新建对话后重试。')
|
||||
if not 0 < conv_id <= 9223372036854775807:
|
||||
return error('会话编号无效,请新建对话后重试。')
|
||||
else:
|
||||
conv_id = None
|
||||
frames, headers = chat_service.create_chat_stream(msg, conv_id)
|
||||
body = frames if isinstance(frames, str) else stream_with_context(frames)
|
||||
return Response(body, mimetype='text/event-stream', headers=headers)
|
||||
|
||||
|
||||
@bp.route('/api/feedback', methods=['POST'])
|
||||
def feedback():
|
||||
return business_service.feedback(request.get_json(silent=True))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Public, visitor-bound customer login endpoints. No staff privileges."""
|
||||
|
||||
from flask import Blueprint, current_app, request
|
||||
from werkzeug.exceptions import RequestEntityTooLarge
|
||||
from .. import customer_service
|
||||
|
||||
bp = Blueprint('customer', __name__)
|
||||
|
||||
|
||||
@bp.get('/api/customer/session')
|
||||
def session():
|
||||
return customer_service.session_status()
|
||||
|
||||
|
||||
@bp.post('/api/customer/login')
|
||||
def login():
|
||||
request.max_content_length = 2048
|
||||
try:
|
||||
return customer_service.login(request.get_json(silent=True), current_app.extensions['customer_login_attempts'],
|
||||
current_app.extensions['customer_login_lock'])
|
||||
except RequestEntityTooLarge:
|
||||
return {'ok':False,'error':'登录信息过长。'}, 413
|
||||
|
||||
|
||||
@bp.post('/api/customer/logout')
|
||||
def logout():
|
||||
return customer_service.logout()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""HTTP adapters for files; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, render_template, request, send_from_directory
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from .. import file_service, visitor_service
|
||||
from ..config import get_setting
|
||||
|
||||
bp = Blueprint('files', __name__)
|
||||
|
||||
|
||||
def unavailable(staff=False):
|
||||
return render_template('attachment_unavailable.html', staff=staff), 404, {'Cache-Control':'private, no-store'}
|
||||
|
||||
@bp.route('/api/upload', methods=['POST'])
|
||||
def upload_file():
|
||||
return file_service.upload_file(request.files)
|
||||
|
||||
|
||||
@bp.route('/uploads/<path:name>')
|
||||
def uploaded_file(name):
|
||||
if not visitor_service.owns_upload(name):
|
||||
return unavailable()
|
||||
try:
|
||||
response = send_from_directory(get_setting('UPLOAD_DIR'), name)
|
||||
except NotFound:
|
||||
return unavailable()
|
||||
response.headers['Cache-Control'] = 'private, no-store'
|
||||
return response
|
||||
|
||||
|
||||
@bp.route('/api/staff/uploads/<path:name>')
|
||||
def staff_uploaded_file(name):
|
||||
try:
|
||||
response = send_from_directory(get_setting('UPLOAD_DIR'), name)
|
||||
except NotFound:
|
||||
return unavailable(staff=True)
|
||||
response.headers['Cache-Control'] = 'private, no-store'
|
||||
return response
|
||||
@@ -0,0 +1,31 @@
|
||||
"""HTTP adapters for history; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from .. import history_service
|
||||
|
||||
bp = Blueprint('history', __name__)
|
||||
|
||||
@bp.route('/api/new_chat', methods=['POST'])
|
||||
def new_chat():
|
||||
return history_service.new_chat()
|
||||
|
||||
|
||||
@bp.route('/api/get_history')
|
||||
def get_history():
|
||||
return history_service.get_history()
|
||||
|
||||
|
||||
@bp.route('/api/get_messages')
|
||||
def get_messages():
|
||||
return history_service.get_messages(request.args.get('conv_id', type=int))
|
||||
|
||||
|
||||
@bp.route('/api/del_history', methods=['DELETE'])
|
||||
def del_history():
|
||||
return history_service.del_history(request.args.get('id', type=int))
|
||||
|
||||
|
||||
@bp.route('/api/clear_all', methods=['DELETE'])
|
||||
def clear_all():
|
||||
return history_service.clear_all()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""HTTP adapters for human; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, current_app, request
|
||||
|
||||
from .. import human_service
|
||||
|
||||
bp = Blueprint('human', __name__)
|
||||
|
||||
@bp.route('/api/human/request', methods=['POST'])
|
||||
def human_request():
|
||||
return human_service.human_request(request.json)
|
||||
|
||||
|
||||
@bp.route('/api/human/poll')
|
||||
def human_poll():
|
||||
return human_service.human_poll(request.args.get('sid', type=int), request.args.get('after', 0, type=int), current_app.extensions['human_typing'])
|
||||
|
||||
|
||||
@bp.route('/api/human/send', methods=['POST'])
|
||||
def human_send():
|
||||
return human_service.human_send(request.json)
|
||||
|
||||
|
||||
@bp.route('/api/human/queue')
|
||||
def human_queue():
|
||||
return human_service.human_queue()
|
||||
|
||||
|
||||
@bp.route('/api/human/active')
|
||||
def human_active():
|
||||
return human_service.human_active()
|
||||
|
||||
|
||||
@bp.route('/api/human/accept', methods=['POST'])
|
||||
def human_accept():
|
||||
return human_service.human_accept(request.json)
|
||||
|
||||
|
||||
@bp.route('/api/human/close', methods=['POST'])
|
||||
def human_close():
|
||||
return human_service.human_close(request.json)
|
||||
|
||||
|
||||
@bp.route('/api/human/transfer', methods=['POST'])
|
||||
def human_transfer():
|
||||
return human_service.human_transfer(request.json or {}, current_app.extensions['human_typing'])
|
||||
|
||||
|
||||
@bp.route('/api/human/note', methods=['POST'])
|
||||
def human_note():
|
||||
return human_service.human_note(request.json or {})
|
||||
|
||||
|
||||
@bp.route('/api/human/recall', methods=['POST'])
|
||||
def human_recall():
|
||||
return human_service.human_recall(request.json or {})
|
||||
|
||||
|
||||
@bp.route('/api/human/typing', methods=['POST'])
|
||||
def human_typing():
|
||||
return human_service.human_typing(request.json, current_app.extensions['human_typing'])
|
||||
|
||||
|
||||
@bp.route('/api/human/stop_typing', methods=['POST'])
|
||||
def human_stop_typing():
|
||||
return human_service.human_stop_typing(request.json, current_app.extensions['human_typing'])
|
||||
|
||||
|
||||
@bp.route('/api/human/read', methods=['POST'])
|
||||
def human_read():
|
||||
return human_service.human_read(request.json)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""HTTP adapters for pages; business logic lives in services."""
|
||||
|
||||
from flask import Blueprint, render_template
|
||||
|
||||
|
||||
bp = Blueprint('pages', __name__)
|
||||
|
||||
|
||||
@bp.route('/healthz')
|
||||
def health():
|
||||
return {'status': 'ok'}
|
||||
|
||||
@bp.route('/')
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
@@ -0,0 +1,47 @@
|
||||
"""HTTP adapters for short voice input; no audio is stored or added to history."""
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, Request, request
|
||||
from werkzeug.exceptions import RequestEntityTooLarge
|
||||
|
||||
from .. import speech_service
|
||||
|
||||
|
||||
bp = Blueprint('speech', __name__)
|
||||
|
||||
|
||||
class MemoryAudioRequest(Request):
|
||||
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None):
|
||||
if self.path == '/api/speech/transcribe':
|
||||
return BytesIO()
|
||||
return super()._get_file_stream(total_content_length, content_type, filename, content_length)
|
||||
|
||||
|
||||
@bp.after_request
|
||||
def no_cache(response):
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
|
||||
|
||||
@bp.get('/api/speech/config')
|
||||
def speech_config():
|
||||
return {'enabled': speech_service.speech_enabled(), 'max_seconds': speech_service.MAX_DURATION_SECONDS,
|
||||
'max_bytes': speech_service.MAX_AUDIO_BYTES}, {'Cache-Control': 'no-store'}
|
||||
|
||||
|
||||
@bp.post('/api/speech/transcribe')
|
||||
def speech_transcribe():
|
||||
request.max_content_length = speech_service.MAX_AUDIO_BYTES + 64 * 1024
|
||||
if not speech_service.speech_enabled():
|
||||
return {'ok': False, 'error': speech_service.UNAVAILABLE}, 503
|
||||
try:
|
||||
files = request.files
|
||||
try:
|
||||
return speech_service.transcribe_recording(files.get('audio'), request.form.get('duration'),
|
||||
request.form.get('language'))
|
||||
finally:
|
||||
for _, upload in files.items(multi=True):
|
||||
upload.close()
|
||||
except RequestEntityTooLarge:
|
||||
return {'ok': False, 'error': '录音文件过大,请缩短后重试。'}, 413
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Guest bootstrap and owner-checked human support adapters, separate from staff APIs."""
|
||||
|
||||
from flask import Blueprint, current_app, request
|
||||
from werkzeug.exceptions import RequestEntityTooLarge
|
||||
|
||||
from .. import human_service, visitor_service
|
||||
|
||||
|
||||
bp = Blueprint('visitor', __name__)
|
||||
|
||||
|
||||
@bp.post('/api/visitor/session')
|
||||
def visitor_session():
|
||||
request.max_content_length = 1024
|
||||
try:
|
||||
return visitor_service.start_session(request.get_json(silent=True))
|
||||
except RequestEntityTooLarge:
|
||||
return {'ok': False, 'error': '访客会话格式无效。'}, 413
|
||||
|
||||
|
||||
@bp.route('/api/visitor/human/<action>', methods=['GET', 'POST'])
|
||||
def visitor_human(action):
|
||||
methods = {'poll': 'GET', 'request': 'POST', 'send': 'POST', 'close': 'POST'}
|
||||
if action not in methods or request.method != methods[action]:
|
||||
return {'ok': False}, 404
|
||||
data = request.get_json(silent=True) if request.method == 'POST' else {}
|
||||
if not isinstance(data, dict):
|
||||
return {'ok': False}, 400
|
||||
if action == 'request':
|
||||
if not visitor_service.owns_conversation(data.get('conv_id')):
|
||||
return {'ok': False, 'error': 'conversation_not_found'}, 404
|
||||
return human_service.human_request(data)
|
||||
sid = request.args.get('sid', type=int) if action == 'poll' else data.get('sid')
|
||||
if not visitor_service.owns_human_session(sid):
|
||||
return {'ok': False, 'error': 'session_not_found'}, 404
|
||||
if action == 'poll':
|
||||
after = request.args.get('after', 0, type=int)
|
||||
if not 0 <= after <= 9223372036854775807:
|
||||
return {'ok': False}, 400
|
||||
result = human_service.human_poll(sid, after, current_app.extensions['human_typing'])
|
||||
result.pop('note', None)
|
||||
return result
|
||||
if action == 'send':
|
||||
if data.get('side', 'customer') != 'customer':
|
||||
return {'ok': False}, 403
|
||||
return human_service.human_send({**data, 'side': 'customer'})
|
||||
return human_service.human_close(data)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Explicit local serving entry point; importing it starts no server."""
|
||||
|
||||
|
||||
def local_ips():
|
||||
import socket
|
||||
ips = set()
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as connection:
|
||||
connection.connect(('8.8.8.8', 80))
|
||||
ips.add(connection.getsockname()[0])
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
|
||||
ip = info[4][0]
|
||||
if not ip.startswith('127.'):
|
||||
ips.add(ip)
|
||||
except Exception:
|
||||
pass
|
||||
return sorted(ips)
|
||||
|
||||
|
||||
def serve_app(app):
|
||||
host, port = app.config['HOST'], app.config['PORT']
|
||||
print(f'Local: http://127.0.0.1:{port}')
|
||||
for ip in local_ips():
|
||||
print(f'LAN: http://{ip}:{port}')
|
||||
try:
|
||||
from waitress import serve
|
||||
except ImportError:
|
||||
app.run(host=host, port=port, debug=True, use_reloader=False)
|
||||
else:
|
||||
serve(app, host=host, port=port, threads=8)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Pre-shipment answers from the active US book, without live operational claims."""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
def preparation_topic(text):
|
||||
if re.search(r'理赔|赔偿|索赔|货损|丢件|破损',text):return None
|
||||
if re.search(r'截仓|截单|船期|排仓|哪天开船|(?:什么时候|几号).*开船|能.*开船|'
|
||||
r'(?:今天|明天|这周|下周).*(?:发货|发走|开船)|赶得上|来得及|(?:保证|必须|月底).*到',text):return 'schedule'
|
||||
if re.search(r'上门.*(?:提货|取货|收货|揽收)|提货服务|交仓地址|仓库地址|仓.*(?:地址|电话|联系人|几点)|送哪个仓|仓库在哪|收货时间|\bpick\s*up\b|\bpickup\b',text,re.I):return 'delivery'
|
||||
if re.search(r'报关资料|清关资料|报关.*(?:准备|材料)|申报比例|低申报|怎么申报|如何申报|认证资料|熏蒸',text):return 'documents'
|
||||
if re.search(r'查验.*(?:费|承担)|谁.*承担.*查验',text):return 'inspection'
|
||||
if re.search(r'(?:东|西|中)[12](?:区)?.*(?:区别|分区|哪区)|分区.*(?:什么意思|怎么分)',text):return 'zones'
|
||||
if '一件代发' not in text and re.search(r'贴标|FBA标|标签|唛头|产地标|外箱.*贴|贴.*条码|made\s+in\s+china',text,re.I):return 'labels'
|
||||
if re.search(r'哪些渠道|哪些线路|什么渠道|能发哪些仓|支持.*仓|(?:能发|能走|可以发).*美国',text):return 'coverage'
|
||||
return None
|
||||
|
||||
|
||||
def answer_preparation(intent,book):
|
||||
topic=preparation_topic(intent['text'])
|
||||
if topic is None:return None
|
||||
from .quote_fees import document
|
||||
|
||||
if topic=='coverage':
|
||||
services=list(dict.fromkeys(rate['service'] for rate in book['rates']))
|
||||
return '美国可查询的线路:'+ '、'.join(services)+'。请提供目的仓码或邮编、重量及交货仓,我再匹配具体可用线路。'
|
||||
if topic=='zones':
|
||||
return '东1、东2等是报价资料中的不同目的地区域,需要按目的仓码或邮编匹配;同一仓码存在多个分区记录时会分别列出。请提供目的仓码或邮编,我按现有记录核对。'
|
||||
if topic=='schedule':
|
||||
return '请提供计划交仓日期、交货仓和目的仓码。具体截仓、装柜和开船安排需联系人工核对;当前参考时效不能作为月底或指定日期必达的承诺。'
|
||||
if topic=='delivery':
|
||||
raw=document(book,('不提供上门提货服务',))
|
||||
if intent.get('english'):
|
||||
return ('The current US route sheet requires delivery to the designated warehouse and does not offer pickup. ' if raw else '')+'Please confirm the route and Yiwu or South China origin with customer support before delivery; warehouse address, contact and receiving hours need confirmation.'
|
||||
lines=[]
|
||||
if raw:lines.append('当前美国渠道资料要求客户自行送货至对应仓库,不提供上门提货服务。')
|
||||
lines.append('请确认所选渠道及义乌或华南交仓,仓库地址、联系人和收货时间请联系人工核对后再送仓。')
|
||||
return '\n'.join(lines)
|
||||
if topic=='labels':
|
||||
label=document(book,('外箱','入仓条码','唛头'))
|
||||
origin=document(book,('产品上和包装上','产地标识'))
|
||||
lines=[]
|
||||
if label:lines.append(re.sub(r'^\s*\d+[、..]\s*','',label.strip())+'\n代贴标签具体费用需按所选服务确认。')
|
||||
if origin:lines.append('产品和包装还需有“Made in China”产地标识。')
|
||||
return '\n'.join(lines) or '请提供渠道和目的仓码,由人工核对外箱标签及代贴要求。'
|
||||
if topic=='documents':
|
||||
if '熏蒸' in intent['text']:
|
||||
raw=document(book,('熏蒸','备货阶段'))
|
||||
return (raw.strip()+'\n' if raw else '')+'请确认是木制成品还是木质包装,并提供具体品名及渠道,核对是否需要熏蒸及证明材料后再安排发货。'
|
||||
if re.search(r'申报比例|低申报|怎么申报|如何申报',intent['text']):
|
||||
return '请提供品名、材质、用途、实际交易金额及销售链接,由业务核对申报资料。申报价需结合实际交易信息确认,不能按统一比例直接代算。'
|
||||
raw=document(book,('单独报关需提供资料',))
|
||||
if raw:return raw.strip()+'\n请补充具体品名及渠道,涉及商检或认证的资料需逐项核对。'
|
||||
return '请提供具体品名和渠道,由人工核对装箱单、发票及对应报关、认证材料。'
|
||||
raw=document(book,('查验','不包税货物','比例均摊'))
|
||||
if raw:return raw.strip()+'\n具体金额按实际查验费用核算;包税渠道的承担方式需另行确认,不能直接套用不包税条款。'
|
||||
return '查验费用和承担方式需按渠道、税费方式及实际费用确认,当前无法给出固定金额。'
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Bounded, in-memory recording transcription; separate from text chat credentials."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import math
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from .config import get_setting
|
||||
|
||||
|
||||
MAX_AUDIO_BYTES = 5 * 1024 * 1024
|
||||
MAX_DURATION_SECONDS = 60
|
||||
UNAVAILABLE = '语音输入暂不可用,请使用文字输入。'
|
||||
|
||||
|
||||
class SpeechFailure(Exception):
|
||||
def __init__(self, message, status=502):
|
||||
self.message, self.status = message, status
|
||||
|
||||
|
||||
def ffmpeg_binary():
|
||||
configured = get_setting('FFMPEG_BIN')
|
||||
return str(configured) if configured and Path(configured).is_file() else shutil.which('ffmpeg')
|
||||
|
||||
|
||||
def speech_enabled():
|
||||
provider = get_setting('ASR_PROVIDER')
|
||||
if provider == 'baidu':
|
||||
return bool(get_setting('BAIDU_ASR_API_KEY') and get_setting('BAIDU_ASR_SECRET_KEY') and ffmpeg_binary())
|
||||
if provider != 'dashscope':
|
||||
return False
|
||||
try:
|
||||
url = urlsplit(get_setting('ASR_URL'))
|
||||
except ValueError:
|
||||
return False
|
||||
return bool(get_setting('ASR_API_KEY') and get_setting('ASR_MODEL')
|
||||
and url.scheme == 'https' and url.hostname and not url.username and not url.password)
|
||||
|
||||
|
||||
def post_json(url, **options):
|
||||
response = requests.post(url, timeout=(5, 30), stream=True, allow_redirects=False, **options)
|
||||
try:
|
||||
if response.status_code != 200:
|
||||
raise SpeechFailure('语音转文字失败,请稍后重试。')
|
||||
data = bytearray()
|
||||
for chunk in response.iter_content(4096):
|
||||
data.extend(chunk)
|
||||
if len(data) > 64 * 1024:
|
||||
raise SpeechFailure('语音识别结果无效,请重试。')
|
||||
return json.loads(data)
|
||||
finally:
|
||||
response.close()
|
||||
|
||||
|
||||
def baidu_token():
|
||||
key, secret = get_setting('BAIDU_ASR_API_KEY'), get_setting('BAIDU_ASR_SECRET_KEY')
|
||||
identity = hashlib.sha256((key + '\0' + secret).encode()).hexdigest()
|
||||
lock = current_app.extensions.setdefault('speech_token_lock', threading.Lock())
|
||||
with lock:
|
||||
cached = current_app.extensions.get('speech_token')
|
||||
if cached and cached['identity'] == identity and cached['expires'] > time.time():
|
||||
return cached['token']
|
||||
data = post_json('https://aip.baidubce.com/oauth/2.0/token', data={
|
||||
'grant_type':'client_credentials', 'client_id':key, 'client_secret':secret})
|
||||
token = data.get('access_token')
|
||||
if not isinstance(token, str) or not token:
|
||||
raise SpeechFailure(UNAVAILABLE, 503)
|
||||
current_app.extensions['speech_token'] = {'identity':identity, 'token':token,
|
||||
'expires':time.time() + max(0, min(float(data.get('expires_in', 0)), 2592000) - 60)}
|
||||
return token
|
||||
|
||||
|
||||
def to_pcm(content):
|
||||
"""Decode browser WebM/MP4 in pipes to mono 16 kHz, without temporary audio files."""
|
||||
binary = ffmpeg_binary()
|
||||
if not binary:
|
||||
raise SpeechFailure(UNAVAILABLE, 503)
|
||||
result = subprocess.run([binary, '-hide_banner', '-loglevel', 'error', '-protocol_whitelist', 'pipe',
|
||||
'-i', 'pipe:0', '-map', '0:a:0', '-vn', '-sn', '-dn', '-ac', '1', '-ar', '16000',
|
||||
'-t', '61', '-f', 's16le', 'pipe:1'], input=content, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
timeout=10, creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
||||
if result.returncode != 0 or len(result.stdout) < 12800:
|
||||
raise SpeechFailure('录音无法识别,请重新录制。', 422)
|
||||
if len(result.stdout) > 16000 * 2 * MAX_DURATION_SECONDS:
|
||||
raise SpeechFailure('录音超过 60 秒,请缩短后重试。', 400)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def baidu_transcribe(content, language):
|
||||
pcm = to_pcm(content)
|
||||
result = post_json('https://vop.baidu.com/server_api', json={'format':'pcm', 'rate':16000, 'channel':1,
|
||||
'cuid':'baiyue-logistics-chat', 'token':baidu_token(), 'dev_pid':1737 if language == 'en' else 1537,
|
||||
'speech':base64.b64encode(pcm).decode('ascii'), 'len':len(pcm)})
|
||||
code = result.get('err_no')
|
||||
if code == 3301:
|
||||
raise SpeechFailure('没有识别到文字,请靠近麦克风重试。', 422)
|
||||
if code != 0:
|
||||
current_app.logger.warning('Baidu ASR request failed: code=%s', code)
|
||||
raise SpeechFailure(UNAVAILABLE if code == 3302 else '语音转文字失败,请稍后重试。', 503 if code == 3302 else 502)
|
||||
parts = result.get('result')
|
||||
if not isinstance(parts, list) or any(not isinstance(part, str) for part in parts):
|
||||
raise SpeechFailure('语音识别结果无效,请重试。')
|
||||
return ''.join(parts)
|
||||
|
||||
|
||||
def audio_format(content, mime):
|
||||
"""Check container signatures, never trust the uploaded filename."""
|
||||
mime = mime.split(';', 1)[0].lower()
|
||||
if mime == 'audio/webm' and content.startswith(b'\x1aE\xdf\xa3'):
|
||||
return 'audio/webm'
|
||||
if mime in ('audio/mp4', 'audio/x-m4a') and content[4:8] == b'ftyp':
|
||||
return 'audio/mp4'
|
||||
if mime in ('audio/ogg', 'audio/opus') and content.startswith(b'OggS'):
|
||||
return 'audio/ogg'
|
||||
if mime in ('audio/wav', 'audio/x-wav') and content[:4] == b'RIFF' and content[8:12] == b'WAVE':
|
||||
return 'audio/wav'
|
||||
return None
|
||||
|
||||
|
||||
def transcribe_recording(upload, duration, language):
|
||||
if not speech_enabled():
|
||||
return {'ok': False, 'error': UNAVAILABLE}, 503
|
||||
if not upload:
|
||||
return {'ok': False, 'error': '没有收到录音,请重新按住说话。'}, 400
|
||||
try:
|
||||
duration = float(duration)
|
||||
except (TypeError, ValueError):
|
||||
duration = 0
|
||||
if not math.isfinite(duration) or not 0.4 <= duration <= MAX_DURATION_SECONDS + 1:
|
||||
return {'ok': False, 'error': '录音时长无效,请录制 1 至 60 秒语音。'}, 400
|
||||
content = upload.read(MAX_AUDIO_BYTES + 1)
|
||||
if len(content) > MAX_AUDIO_BYTES:
|
||||
return {'ok': False, 'error': '录音文件过大,请缩短后重试。'}, 413
|
||||
mime = audio_format(content, upload.mimetype)
|
||||
if len(content) < 16 or not mime:
|
||||
return {'ok': False, 'error': '录音格式不受支持,请使用文字输入或更换浏览器。'}, 415
|
||||
language = 'en' if language == 'en' else 'zh'
|
||||
try:
|
||||
if get_setting('ASR_PROVIDER') == 'baidu':
|
||||
text = baidu_transcribe(content, language)
|
||||
else:
|
||||
body = {'model': get_setting('ASR_MODEL'), 'stream': False,
|
||||
'messages': [{'role': 'user', 'content': [{'type': 'input_audio', 'input_audio': {
|
||||
'data': 'data:' + mime + ';base64,' + base64.b64encode(content).decode('ascii')}}]}],
|
||||
'asr_options': {'language': language, 'enable_itn': True}}
|
||||
result = post_json(get_setting('ASR_URL'), json=body,
|
||||
headers={'Authorization': 'Bearer ' + get_setting('ASR_API_KEY')})
|
||||
text = result['choices'][0]['message']['content']
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return {'ok': False, 'error': '没有识别到文字,请靠近麦克风重试。'}, 422
|
||||
text = text.strip()
|
||||
if len(text) > 2000:
|
||||
return {'ok': False, 'error': '识别文字过长,请缩短录音后重试。'}, 422
|
||||
return {'ok': True, 'text': text}, 200
|
||||
except requests.Timeout:
|
||||
return {'ok': False, 'error': '语音转文字超时,请重试。'}, 504
|
||||
except SpeechFailure as error:
|
||||
return {'ok': False, 'error': error.message}, error.status
|
||||
except subprocess.TimeoutExpired:
|
||||
return {'ok': False, 'error': '录音处理超时,请缩短后重试。'}, 504
|
||||
except OSError:
|
||||
return {'ok': False, 'error': UNAVAILABLE}, 503
|
||||
except (requests.RequestException, ValueError, KeyError, IndexError, TypeError):
|
||||
return {'ok': False, 'error': '语音转文字失败,请稍后重试。'}, 502
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Extracted tracking rules with unchanged business behavior."""
|
||||
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
CARD_PREFIX = "__CARD__"
|
||||
|
||||
def card_to_text(content):
|
||||
"""把存库的卡片标记转成人话,避免原始 JSON 进入模型上下文"""
|
||||
if not content.startswith(CARD_PREFIX):
|
||||
return content
|
||||
try:
|
||||
card = json.loads(content[len(CARD_PREFIX):])
|
||||
if card.get('kind') == 'order':
|
||||
return card.get('summary', '')
|
||||
return f"(历史演示轨迹,非真实物流信息:单号 {card.get('no', '')},演示状态:{card.get('status', '')})"
|
||||
except Exception:
|
||||
return "(已为该运单查询过轨迹)"
|
||||
|
||||
def is_tracking_no(text):
|
||||
"""判断一句话是不是"整句运单号"
|
||||
|
||||
规则(逐条收紧,避免误判):
|
||||
1. 去掉空格和横杠后,长度 8~20 位,且只能由字母数字组成
|
||||
2. 至少包含 3 个数字(英文句子通常只有 1 个数字)
|
||||
3. 字母数量不能多于数字("i want to go 1t how money" 这类会被排除)
|
||||
纯数字单号(如 15252125)全部满足上述条件。
|
||||
"""
|
||||
# 日期格式(如 2026-10-23、2026/10/23)不算运单号
|
||||
if re.fullmatch(r"\d{4}[-/.]\d{1,2}[-/.]\d{1,2}", text.strip()):
|
||||
return False
|
||||
t = re.sub(r"[\s\-]", "", text)
|
||||
if not (8 <= len(t) <= 20):
|
||||
return False
|
||||
if not re.fullmatch(r"[A-Za-z0-9]+", t):
|
||||
return False
|
||||
digits = sum(c.isdigit() for c in t)
|
||||
letters = sum(c.isalpha() for c in t)
|
||||
if digits < 3:
|
||||
return False
|
||||
if letters > digits:
|
||||
return False
|
||||
return True
|
||||
|
||||
def extract_tracking_no(text):
|
||||
"""从一句话里提取运单号:先看整句是不是,再从句子里找最长的字母数字串"""
|
||||
t = text.strip()
|
||||
if is_tracking_no(t):
|
||||
return t
|
||||
# 找句子里最长的 8~20 位字母数字连续串
|
||||
candidates = re.findall(r"[A-Za-z0-9]{8,20}", t)
|
||||
best = None
|
||||
for c in candidates:
|
||||
if is_tracking_no(c):
|
||||
if best is None or len(c) > len(best):
|
||||
best = c
|
||||
return best
|
||||
|
||||
def build_track(no):
|
||||
"""Legacy demo helper for old imports; chat queries use order_test_data."""
|
||||
rnd = random.Random(no)
|
||||
steps = [
|
||||
("已揽收", "义乌仓"),
|
||||
("出口清关放行", "义乌/宁波口岸"),
|
||||
("已发车", "中欧班列/卡航 · 阿拉山口"),
|
||||
("到达欧洲中转仓", "波兰 · 华沙"),
|
||||
("欧盟清关放行", "德国 · 杜伊斯堡"),
|
||||
("派送中", "收件人所在城市"),
|
||||
]
|
||||
gaps = [rnd.randint(6, 40) for _ in steps] # 相邻节点间隔(小时)
|
||||
t = datetime.now() - timedelta(hours=sum(gaps))
|
||||
nodes = []
|
||||
for (text, place), gap in zip(steps, gaps):
|
||||
t = t + timedelta(hours=gap)
|
||||
nodes.append({"time": t.strftime("%Y-%m-%d %H:%M"),
|
||||
"text": text, "place": place})
|
||||
nodes.reverse() # 最新的排最上面
|
||||
return {"no": no, "status": nodes[0]["text"], "nodes": nodes}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Guest possession tokens isolate chat data; they never identify an order customer."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
|
||||
from flask import g, has_app_context, jsonify, request
|
||||
|
||||
from .db import connect
|
||||
|
||||
|
||||
COOKIE_NAME = 'baiyue_visitor'
|
||||
KEY_PATTERN = re.compile(r'[0-9a-f]{64}\Z')
|
||||
CUSTOMER_PATHS = {
|
||||
'/stream_chat', '/api/new_chat', '/api/get_history', '/api/get_messages', '/api/del_history',
|
||||
'/api/clear_all', '/api/upload', '/api/ticket', '/api/rate', '/api/feedback',
|
||||
'/api/speech/config', '/api/speech/transcribe',
|
||||
'/api/customer/session', '/api/customer/login', '/api/customer/logout',
|
||||
}
|
||||
|
||||
|
||||
def valid_key(value):
|
||||
return isinstance(value, str) and KEY_PATTERN.fullmatch(value) is not None
|
||||
|
||||
|
||||
def visitor_id():
|
||||
return getattr(g, 'visitor_id', None) if has_app_context() else None
|
||||
|
||||
|
||||
def customer_tenant_id():
|
||||
# Set only after validating a server-side customer session.
|
||||
# Visitor cookies, request parameters and headers are deliberately not accepted.
|
||||
value = getattr(g, 'customer_tenant_id', None) if has_app_context() else None
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int)):
|
||||
return None
|
||||
tenant = str(value).strip()
|
||||
return tenant if tenant and len(tenant) <= 128 else None
|
||||
|
||||
|
||||
def customer_tenant_ids():
|
||||
if not has_app_context():
|
||||
return ()
|
||||
# Also retain compatibility with a trusted single-tenant authentication adapter.
|
||||
single = customer_tenant_id()
|
||||
if single:
|
||||
return (single,)
|
||||
values = getattr(g,'customer_tenant_ids',())
|
||||
if not isinstance(values,(list,tuple)) or len(values) > 256:
|
||||
return ()
|
||||
return tuple(sorted(set(value for value in values if isinstance(value,str) and 0 < len(value.strip()) <= 128)))
|
||||
|
||||
|
||||
def attach_visitor():
|
||||
key = request.cookies.get(COOKIE_NAME)
|
||||
g.visitor_id = hashlib.sha256(key.encode('ascii')).hexdigest() if valid_key(key) else None
|
||||
is_customer = request.path in CUSTOMER_PATHS or request.path.startswith('/api/visitor/human/')
|
||||
if is_customer and not visitor_id():
|
||||
return jsonify({'ok': False, 'e': '访客会话已失效,请刷新页面重试。'}), 401
|
||||
if (is_customer or request.path == '/api/visitor/session') and request.method not in ('GET', 'HEAD', 'OPTIONS'):
|
||||
origin = request.headers.get('Origin')
|
||||
if origin and origin.rstrip('/') != request.host_url.rstrip('/'):
|
||||
return jsonify({'ok': False, 'e': '请求来源无效。'}), 403
|
||||
|
||||
|
||||
def start_session(data):
|
||||
if not isinstance(data, dict):
|
||||
return {'ok': False, 'error': '访客会话格式无效。'}, 400
|
||||
key = data.get('key')
|
||||
if key is None:
|
||||
existing = request.cookies.get(COOKIE_NAME)
|
||||
key = existing if valid_key(existing) else secrets.token_hex(32)
|
||||
if not valid_key(key):
|
||||
return {'ok': False, 'error': '访客标识无效。'}, 400
|
||||
response = jsonify({'ok': True, 'key': key})
|
||||
response.set_cookie(COOKIE_NAME, key, max_age=365*24*3600, httponly=True,
|
||||
secure=request.is_secure, samesite='Lax', path='/')
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
|
||||
|
||||
def owns_conversation(conv_id):
|
||||
from .customer_service import current_customer_id, current_scope_key
|
||||
owner = visitor_id()
|
||||
if not owner or not isinstance(conv_id, int) or isinstance(conv_id, bool) or not 0 < conv_id <= 9223372036854775807:
|
||||
return False
|
||||
connection = connect()
|
||||
try:
|
||||
return bool(connection.execute('SELECT 1 FROM chat_history WHERE id=? AND visitor_id=? '
|
||||
'AND (customer_id IS NULL OR (customer_id=? AND customer_scope=?))',
|
||||
(conv_id, owner, current_customer_id(),current_scope_key())).fetchone())
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def owns_human_session(sid):
|
||||
from .customer_service import current_customer_id, current_scope_key
|
||||
owner = visitor_id()
|
||||
if not owner or not isinstance(sid, int) or isinstance(sid, bool) or not 0 < sid <= 9223372036854775807:
|
||||
return False
|
||||
connection = connect()
|
||||
try:
|
||||
return bool(connection.execute('SELECT 1 FROM human_sessions s JOIN chat_history h ON h.id=s.conv_id '
|
||||
'WHERE s.id=? AND h.visitor_id=? AND (h.customer_id IS NULL OR '
|
||||
'(h.customer_id=? AND h.customer_scope=?))',
|
||||
(sid, owner, current_customer_id(),current_scope_key())).fetchone())
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def owns_upload(name):
|
||||
owner = visitor_id()
|
||||
if not owner:
|
||||
return False
|
||||
connection = connect()
|
||||
try:
|
||||
return bool(connection.execute('SELECT 1 FROM visitor_uploads WHERE filename=? AND visitor_id=?',
|
||||
(name, owner)).fetchone())
|
||||
finally:
|
||||
connection.close()
|
||||
+5
-77
@@ -1,78 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报价表扩展数据(自动生成,来源:炜易达 VIP 10月15日9点执行报价表)
|
||||
"""Compatibility exports for the relocated quotation data."""
|
||||
|
||||
包含:海外仓卡派、二级补仓、德国仓亚马逊退货、产品附加费、DPD 岛屿偏远邮编。
|
||||
"""
|
||||
|
||||
# 海外仓卡派:按 kg(21KG+/51KG+)或按方(0.5CBM+/1CBM+)计费
|
||||
# 价格单位:按 kg 为 RMB/kg,按方为 RMB/CBM
|
||||
WAREHOUSE_CARD = {'谷仓法国巴黎1仓-95500-FR\n谷仓法国巴黎2仓-60440-FR\n谷仓法国巴黎4仓-77230-FR': {'卡航': {'kg21': 19.5, 'kg51': 18.5, 'cbm05': 3200.0, 'cbm1': 3020.0}, '普卡': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2920.0}, '铁路': {'kg21': 16.8, 'kg51': 15.8, 'cbm05': 2722.0, 'cbm1': 2542.0}, '海运': {'kg21': 12.5, 'kg51': 11.5, 'cbm05': 1952.0, 'cbm1': 1772.0}}, '4PX-69110-PL\n谷仓-69110-PL\nSLU2-69110-PL': {'卡航': {'kg21': 18.2, 'kg51': 17.2, 'cbm05': 2966.0, 'cbm1': 2786.0}, '普卡': {'kg21': 17.7, 'kg51': 16.7, 'cbm05': 2876.0, 'cbm1': 2686.0}, '铁路': {'kg21': 15.5, 'kg51': 14.5, 'cbm05': 2488.0, 'cbm1': 2308.0}, '海运': {'kg21': 11.1, 'kg51': 10.1, 'cbm05': 1700.0, 'cbm1': 1520.0}}, 'EDAPL-69100-PL': {'卡航': {'kg21': 18.6, 'kg51': 17.6, 'cbm05': 3038.0, 'cbm1': 2858.0}, '普卡': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2948.0, 'cbm1': 2758.0}, '铁路': {'kg21': 15.9, 'kg51': 14.9, 'cbm05': 2560.0, 'cbm1': 2380.0}, '海运': {'kg21': 11.5, 'kg51': 10.5, 'cbm05': 1772.0, 'cbm1': 1592.0}}, '4PX-66340-PL\n菜鸟仓-66340-PL': {'卡航': {'kg21': 18.9, 'kg51': 17.9, 'cbm05': 3092.0, 'cbm1': 2912.0}, '普卡': {'kg21': 18.4, 'kg51': 17.4, 'cbm05': 3002.0, 'cbm1': 2812.0}, '铁路': {'kg21': 16.2, 'kg51': 15.2, 'cbm05': 2614.0, 'cbm1': 2434.0}, '海运': {'kg21': 11.9, 'kg51': 10.9, 'cbm05': 1844.0, 'cbm1': 1664.0}}, '希音-44141-PL\n希音-55040-PL': {'卡航': {'kg21': 19.5, 'kg51': 18.5, 'cbm05': 3200.0, 'cbm1': 3020.0}, '普卡': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2920.0}, '铁路': {'kg21': 16.8, 'kg51': 15.8, 'cbm05': 2722.0, 'cbm1': 2542.0}, '海运': {'kg21': 12.5, 'kg51': 11.5, 'cbm05': 1952.0, 'cbm1': 1772.0}}, '谷仓捷克1仓-25261-CZ\n谷仓捷克2仓-25261-CZ\n谷仓捷克3仓-41002-CZ\n谷仓捷克4仓-25261-CZ\n谷仓捷克5仓-25219-CZ\n谷仓捷克7仓-25301-CZ\n谷仓捷克8仓-41002-CZ': {'卡航': {'kg21': 18.6, 'kg51': 17.6, 'cbm05': 3038.0, 'cbm1': 2858.0}, '普卡': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2948.0, 'cbm1': 2758.0}, '铁路': {'kg21': 15.9, 'kg51': 14.9, 'cbm05': 2560.0, 'cbm1': 2380.0}, '海运': {'kg21': 11.5, 'kg51': 10.5, 'cbm05': 1772.0, 'cbm1': 1592.0}}, '4PX布拉格A仓-25261-CZ': {'卡航': {'kg21': 19.0, 'kg51': 18.0, 'cbm05': 3110.0, 'cbm1': 2930.0}, '普卡': {'kg21': 18.5, 'kg51': 17.5, 'cbm05': 3020.0, 'cbm1': 2830.0}, '铁路': {'kg21': 16.3, 'kg51': 15.3, 'cbm05': 2632.0, 'cbm1': 2452.0}, '海运': {'kg21': 12.0, 'kg51': 11.0, 'cbm05': 1862.0, 'cbm1': 1682.0}}, '4PX马德里A仓-19171-ES': {'卡航': {'kg21': 20.8, 'kg51': 19.8, 'cbm05': 3434.0, 'cbm1': 3254.0}, '普卡': {'kg21': 20.3, 'kg51': 19.3, 'cbm05': 3344.0, 'cbm1': 3154.0}, '铁路': {'kg21': 18.1, 'kg51': 17.1, 'cbm05': 2956.0, 'cbm1': 2776.0}, '海运': {'kg21': 13.7, 'kg51': 12.7, 'cbm05': 2168.0, 'cbm1': 1988.0}}, '盘古-63150-DE\n新欧达-31628-DE': {'卡航': {'kg21': 19.4, 'kg51': 18.4, 'cbm05': 3182.0, 'cbm1': 3002.0}, '普卡': {'kg21': 18.9, 'kg51': 17.9, 'cbm05': 3092.0, 'cbm1': 2902.0}, '铁路': {'kg21': 16.7, 'kg51': 15.7, 'cbm05': 2704.0, 'cbm1': 2524.0}, '海运': {'kg21': 12.3, 'kg51': 11.3, 'cbm05': 1916.0, 'cbm1': 1736.0}}}
|
||||
|
||||
# 二级补仓(海外仓中转)主要服务费
|
||||
SECONDARY_WAREHOUSE = {'服务': '1.贴标:2张FBA标签,一张快递面单)单件计费重量范围在(0KG<X≤30KG) 2.打板:实际打板数为准(1个板大概1.2方-1.5方) 3.卸货费', '头程单价指示': '欧洲铁路头程单价:欧洲铁路渠道 中欧卡航头程单价:中欧卡航渠道 欧洲海运头程单价:海运快线/海运热门仓卡派直送 英国头程单价:英国专线(DPD)', '二次派送': '1. 欧洲/英国二级补仓无需二次派送费用,可自提单价-1/KG 2. 海外仓在德国,如需发往其他国家补运费差价', '仓储费': '德国:免费存储25天,超过5RMB/方/天,61-180天 7RMB/方/每天,181天以上 15RMB/方/每天 英国:免费存储25天,超过8RMB/方/天,90-120/方/天 9.5RMB/方/天,超120天 15RMB/方/天', '订单处理费': '1:针对一个SKU发往一个地址作为一个订单收取15RMB订单操作费; 2:针对不同票数合并发往一个地址作为一个订单收取15RMB订单操作费; 出货之前都需要填写出货指令', '销毁费': '德国:单询 英国:50英镑/件', '换产品SKU费': '欧洲:针对一个箱里面是一种SKU要换标:开箱关箱费13RMB/箱换SKU:4RMB/个,清点:2RMB/个针对一箱多个SKU换标(费用单询) 英国:针对一个箱里面是一种SKU要换标:开箱关箱费20RMB/箱换SKU:6RMB/个,清点:3RMB/个针对一箱多个SKU换标(费用单询)'}
|
||||
|
||||
# 德国仓亚马逊退货费用(单位:欧元)
|
||||
DE_RETURN_FEES = [
|
||||
{'cat': '2. Outbound 出库', 'item': '2.1.1 Picking 整箱出库', 'sub': 'Single Carton 每箱', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.4 Packing 打包费', 'sub': 'Per Carton 每箱', 'price': 1.5},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.5 Unpacking and Inspection 开箱检验', 'sub': 'Per Carton 每箱', 'price': 1},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.6 Destroy Product without Battery 不带电池产品销毁', 'sub': 'Per 1KG 每公斤', 'price': 1},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.7 Destroy battery 销毁电池', 'sub': 'Per 1KG 每公斤', 'price': 1.5},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.8 Cancel Order 截单费', 'sub': 'Per order 每单', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.9 Claim Fee 认领费', 'sub': 'Every order 每个订单', 'price': 2},
|
||||
{'cat': '4. In-House Service 库内服务', 'item': '4.10 Lost Shipping Claim 丢件索赔服务费', 'sub': 'Per order 每单', 'price': 5},
|
||||
]
|
||||
|
||||
# 产品附加费清单
|
||||
PRODUCT_SURCHARGES = [
|
||||
('电池 标准箱100瓦以下非危电池/内电不超100瓦产品。头程参考海运快线快递单价标准', '资料齐全+1/KG 资料不齐全+2/KG'),
|
||||
('手机,平板电脑', '5/KG'),
|
||||
('铝制品', '2元/KG'),
|
||||
('瓷砖', '1元/KG'),
|
||||
('玻璃纤维网格织物、玻璃纤维长丝、聚酯高强力纱', '1元/KG'),
|
||||
('胶合板', '1元/KG'),
|
||||
('铜版纸', '1元/KG'),
|
||||
('钢丝绳和钢缆', '1元/KG'),
|
||||
('包包、U型枕、吊床,普通纺织品', '1元/KG(中欧卡航+2)'),
|
||||
('与接触食品类产品(厨具、榨汁机、擀面杖、杯子等)', '1元/KG'),
|
||||
('LED灯、白炽灯、钨丝灯类、电子温度计', '1元/KG'),
|
||||
('皮革制品', '1元/KG'),
|
||||
('球类', '1元/KG'),
|
||||
('木制品', '1元/KG'),
|
||||
('带磁产品', '1元/KG'),
|
||||
('蓝牙产品 无线产品 数据线', '1元/KG'),
|
||||
('金属及其制品:不锈钢无缝钢管耐腐蚀钢、铸铁产品、可锻铸铁螺纹管和接头、钢铁管配件、钢铁制紧固件、预应力非合金钢丝和钢绞线、活页夹的贱金属附件、铸铁井盖', '1元/KG'),
|
||||
('光伏、晶体硅光伏组件、太阳能板、眼镜', '2元/KG'),
|
||||
('玩具、沐浴盐球、碳包 蜡烛', '2元/KG'),
|
||||
('厨房刀具 (全长不超30CM)', '2元/KG'),
|
||||
('空气净化器', '2元/KG'),
|
||||
('工具箱', '2元/KG'),
|
||||
('眼镜类 笔类', '2元/KG'),
|
||||
('机顶盒 计时器(不包括大的钟表) 电子手环', '2元/KG'),
|
||||
('带陶瓷产品', '2元/KG'),
|
||||
('汽车/摩托车/自行车配件/平衡车/汽车配件', '2元/KG'),
|
||||
('卡客车轮胎、铝合金轮毂 、笔类', '2元/KG'),
|
||||
('投影仪', '2元/KG'),
|
||||
('成人用品、性用品、', '3元/KG'),
|
||||
('服装类(大衣,棉服,风衣,外套,斗篷,运动服饰,毛衫,T恤,衬衫,连体服饰,套装,裙子,骑行服),毛巾类,床上用品,和内衣内裤(海关编码61-65开头)', '3/KG(中欧卡航+5)'),
|
||||
('鞋类(包括塑料拖鞋、鞋垫)不包括鞋带', '3/KG(中欧卡航+5)'),
|
||||
('针织类的帽子、围巾、手套、披肩,窗帘', '3/KG(中欧卡航+5)'),
|
||||
('U盘/内存卡', '3元/个'),
|
||||
('各种码表 手表', '3.5元/个'),
|
||||
('车载DVD/车载显示屏/车载收音机/行车记录仪/行车导航仪', '80元/台'),
|
||||
('投影仪', '35元/台'),
|
||||
('平衡车/平板车(单个15KG以下)(超100瓦安时拒接)', '单询'),
|
||||
('平衡车/平板车(超100瓦安时拒接)', '单询'),
|
||||
('电动滑板车(单个15KG以下)(超100瓦安时拒接)', '单询'),
|
||||
('电动滑板车(超100瓦安时拒接)', '单询'),
|
||||
('平衡车/平板车/滑板车(单个20KG以上)', '单询'),
|
||||
('自行车、电动自行车、', '400/台(计费重超60KG拒收)'),
|
||||
('药物、化学产品及原料', '拒接'),
|
||||
('玩具车、积木类', '不侵权+2/KG'),
|
||||
('管制刀具,弓箭,枪支弹药及配件', '拒接'),
|
||||
('电子打火机、电子烟', '拒接'),
|
||||
('以上表格未列明的产品', '另外询价'),
|
||||
]
|
||||
|
||||
# DPD 欧洲岛屿偏远邮编(附加费 35 欧/件)
|
||||
DPD_ISLAND_POSTCODES = {'丹麦': {'code': 'DK', 'text': '4592, 5960, 5970, 5985, 6720, 7884,8305,8592, 9940, 9950, 9960, Bornholm: 3700, 3720, 3730,3740,3751, 3760, 3770, 3782, 3790'}, '德国': {'code': 'DE', 'text': 'Hiddensee: 18565, NordfriesischeInseln:25849, 25859, 25863, 25869, 25938, 25946, 25980,25992,25996–25999, Ostfries. Inseln: 26465, 26474, 26486,26548,26571, 26579, 26757, Helgoland: 27498,27499,Chiemsee: 83256 Neuwerk:'}, '爱沙尼亚': {'code': 'EE', 'text': '62601, 88001–88005, 91217,91301–91320,92001–92420, 93001–94799, 96027, 96098'}, '芬兰': {'code': 'FI', 'text': 'Aland–Inseln: 22000–22999'}, '法国': {'code': 'FR', 'text': '17111, 17123, 17190, 17310, 17370,17410, 17480,17550, 17580, 17590, 17630, 17670, 17740, 17880,17940,22870, 29242, 29253, 29259, 29990, 56360, 56590,56780,56840, 85330, 85350, Korsika: 20000–20999'}, '希腊': {'code': 'GR', 'text': 'Saronische Inseln: 180xx, 189xx,Ionische Inseln: 28xxx–29xxx, 31xxx, 49xxx, Berg Athos:63086–63087,Kreta: 70xxx–74xxx und Inseln der Ägäis: 80xxx–85xxx'}, '意大利': {'code': 'IT', 'text': 'Pontinische Inseln: 04020, 04027, Sardinien:07000–09999, Lagune von Venedig: 30010, 30012, 30100,30121–30126, 30131–30133, 30135, 30141, Elba mitTyrrhenischeInseln: 57030–57039, 58012–58013, 58018, Tremiti Inseln:71040, Inseln im Golf von Neapel: 80070–80071, 80073–80077, 80079, Inselgruppen um Sizilien: 90010, 91017, 91023,92010, 98050, 98052, 98055Einige PLZ können Gebiete auf Inseln und dem Festlandbetreffen.'}, '克罗地亚': {'code': 'HR', 'text': '20221–20226, 20260–20263, 20264,20270– 20275, 20290, 21220, 21223–21225, 21400,21403–21405,21410, 21412, 21413, 21420, 21423–21426, 21430, 21432,21450, 21454, 21460, 21462–21463, 21465–21467, 21469,21480, 21483, 21485, 22231–22236, 22240–22244, 23212,23234, 23249–23251, 23262–23264, 23271–23275, 23281–23287, 23291–23296, 51280–51281, 51500, 51511–51517,51521–51523, 51550–51552, 51554–51557, 51559, 51561–51562, 51564, 53291, 53294, 53296'}, '荷兰': {'code': 'NL', 'text': '1156AA–1156ZZ, 1791AA–1797ZZ,8881AA– 8884ZZ, 8891AA–8897ZZ, 8899AA–8899ZZ,9161AA–9164ZZ, 9166AA–9166ZZ'}, '葡萄牙': {'code': 'PT', 'text': 'Madeira: 9000–9390, Porto Santo: 9400,Azoren: 9500–9980'}, '瑞典': {'code': 'SE', 'text': '10005, 13025, 13033, 13034, 13036,13038, 13039, 13042, 13043, 13055, 13056, 37022, 43080–43099,45204–45205, 47112–47115, 47500–47599, 62000–62999,74296–74297, 76017–76019, 91803'}, '西班牙': {'code': 'ES', 'text': 'Balearen: 07000–07999'}}
|
||||
from logistics_chat.rates_extra import (
|
||||
WAREHOUSE_CARD, SECONDARY_WAREHOUSE, DE_RETURN_FEES,
|
||||
PRODUCT_SURCHARGES, DPD_ISLAND_POSTCODES,
|
||||
)
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,34 @@
|
||||
"""Close all active human sessions; waiting sessions and messages are preserved."""
|
||||
|
||||
import argparse
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
DEFAULT_DB = Path(__file__).resolve().parents[1] / "history.db"
|
||||
|
||||
|
||||
def close_active_sessions(db_path=None):
|
||||
database = Path(db_path if db_path is not None else DEFAULT_DB).expanduser().resolve()
|
||||
with closing(sqlite3.connect(database.as_uri() + "?mode=rw", uri=True)) as connection:
|
||||
with connection:
|
||||
count = connection.execute(
|
||||
"UPDATE human_sessions SET status='closed' WHERE status='active'"
|
||||
).rowcount
|
||||
return count
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--db", type=Path, default=DEFAULT_DB, help="Existing SQLite database")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
count = close_active_sessions(args.db)
|
||||
except sqlite3.Error as error:
|
||||
parser.exit(1, f"Database error: {error}\n")
|
||||
print(f"Closed {count} active session(s).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Read order-linked warehouse and shipping facts into an explicit private snapshot.
|
||||
|
||||
Requires the optional PyMySQL package. This command never writes to the source DB.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
|
||||
def export_tracking(connection, orders):
|
||||
output = {}
|
||||
for order in orders:
|
||||
key = (str(order.get('tenant_id') or ''), str(order.get('source_order_id') or ''))
|
||||
if not all(value.isdecimal() for value in key) or not order.get('order_no'):
|
||||
raise ValueError('Source snapshot requires numeric tenant_id/source_order_id and order_no')
|
||||
if key in output:
|
||||
raise ValueError('Source snapshot contains duplicate order identities')
|
||||
output[key] = {key_name: order[key_name] for key_name in ('tenant_id', 'source_order_id', 'order_no')}
|
||||
output[key]['tracking_json'] = []
|
||||
ids = sorted({key[1] for key in output})
|
||||
for start in range(0, len(ids), 100):
|
||||
batch = ids[start:start + 100]
|
||||
placeholders = ','.join('%s' for _ in batch)
|
||||
# Every relation uses both source order identity and customer identity.
|
||||
queries = [
|
||||
(f'''SELECT o.tenant_id,o.id AS order_id, i.id AS fact_id,
|
||||
i.inbounded_at AS actual_at,i.updated_at AS observed_at
|
||||
FROM baiyue_order.ord_order o
|
||||
JOIN baiyue_firstleg.fl_inbound_order i ON i.order_id=o.id AND i.tenant_id=o.tenant_id
|
||||
WHERE o.deleted=0 AND i.deleted=0 AND i.inbounded_at IS NOT NULL
|
||||
AND o.id IN ({placeholders}) ORDER BY i.id''', 'inbound'),
|
||||
(f'''SELECT DISTINCT o.tenant_id,o.id AS order_id,i.id AS fact_id,
|
||||
i.frozen_at AS actual_at,i.frozen_at AS observed_at,
|
||||
p.container_booking_id,b.container_no
|
||||
FROM baiyue_order.ord_order o
|
||||
JOIN baiyue_firstleg.fl_loading_plan_item i
|
||||
ON i.order_id=o.id AND i.account_id=o.tenant_id AND i.deleted=0
|
||||
JOIN baiyue_firstleg.fl_loading_plan p ON p.id=i.loading_plan_id AND p.plan_status='COMPLETED'
|
||||
JOIN baiyue_firstleg.fl_container_booking b ON b.id=p.container_booking_id
|
||||
WHERE o.deleted=0 AND i.frozen_at IS NOT NULL
|
||||
AND o.id IN ({placeholders}) ORDER BY i.id''', 'loading'),
|
||||
(f'''SELECT DISTINCT o.tenant_id,o.id AS order_id,n.id AS fact_id,n.standard_node,
|
||||
n.actual_at,n.estimated_at,n.observed_at,n.created_at,n.location_name,
|
||||
n.container_booking_id,b.container_no
|
||||
FROM baiyue_order.ord_order o
|
||||
JOIN baiyue_firstleg.fl_loading_plan_item i
|
||||
ON i.order_id=o.id AND i.account_id=o.tenant_id AND i.deleted=0 AND i.frozen_at IS NOT NULL
|
||||
JOIN baiyue_firstleg.fl_loading_plan p ON p.id=i.loading_plan_id AND p.plan_status='COMPLETED'
|
||||
JOIN baiyue_firstleg.fl_container_booking b ON b.id=p.container_booking_id
|
||||
JOIN baiyue_firstleg.fl_carrier_schedule_node_fact n ON n.container_booking_id=b.id
|
||||
WHERE o.deleted=0 AND o.id IN ({placeholders}) ORDER BY n.id''', 'shipping'),
|
||||
]
|
||||
for sql, source in queries:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(sql, batch)
|
||||
for row in cursor.fetchall():
|
||||
key = (str(row['tenant_id']), str(row['order_id']))
|
||||
if key not in output:
|
||||
continue
|
||||
fact = {'event_id': source + ':' + str(row['fact_id']),
|
||||
'code': {'inbound': 'DOMESTIC_RECEIVED', 'loading': 'LOADING_COMPLETED'}.get(source)
|
||||
or row['standard_node'],
|
||||
'shipment_key': str(row.get('container_booking_id') or ''),
|
||||
'shipment_no': row.get('container_no') or '',
|
||||
'place': row.get('location_name') or ''}
|
||||
for field in ('actual_at', 'estimated_at', 'observed_at', 'created_at'):
|
||||
value = row.get(field)
|
||||
fact[field] = value.isoformat(sep=' ') if value else None
|
||||
output[key]['tracking_json'].append(fact)
|
||||
return list(output.values())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--database-env', type=Path, required=True)
|
||||
parser.add_argument('--orders-snapshot', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.output.exists(): parser.error('Output already exists; choose a new private snapshot path')
|
||||
if not args.output.parent.is_dir(): parser.error('Output parent directory must exist')
|
||||
if not args.orders_snapshot.is_file() or args.orders_snapshot.stat().st_size > 10 * 1024 * 1024:
|
||||
parser.error('Orders snapshot must be an existing JSON file smaller than 10 MB')
|
||||
orders = json.loads(args.orders_snapshot.read_text(encoding='utf-8-sig'))
|
||||
if isinstance(orders, dict): orders = orders.get('orders')
|
||||
if not isinstance(orders, list) or not orders or len(orders) > 3000:
|
||||
parser.error('Orders snapshot must contain 1 to 3000 orders')
|
||||
import pymysql
|
||||
from dotenv import dotenv_values
|
||||
config = dotenv_values(args.database_env, interpolate=False, encoding='utf-8-sig')
|
||||
required = ('CHONGCHONG_DB_HOST', 'CHONGCHONG_DB_PORT', 'CHONGCHONG_DB_USERNAME', 'CHONGCHONG_DB_PASSWORD')
|
||||
if any(not config.get(key) for key in required): parser.error('Database env is missing connection settings')
|
||||
connection = pymysql.connect(host=config[required[0]], port=int(config[required[1]]),
|
||||
user=config[required[2]], password=config[required[3]], cursorclass=pymysql.cursors.DictCursor,
|
||||
connect_timeout=10, read_timeout=30, write_timeout=10, autocommit=False)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute('SET SESSION TRANSACTION READ ONLY')
|
||||
cursor.execute('START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY')
|
||||
records = export_tracking(connection, orders)
|
||||
finally:
|
||||
connection.rollback()
|
||||
connection.close()
|
||||
args.output.write_text(json.dumps({'orders': records}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps({'orders': len(records), 'orders_with_tracking': sum(bool(row['tracking_json']) for row in records),
|
||||
'facts': sum(len(row['tracking_json']) for row in records)}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Import an explicit, private order snapshot into the chat SQLite database."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from logistics_chat.order_data import import_records, import_tracking_records
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--snapshot', type=Path, required=True)
|
||||
parser.add_argument('--db', type=Path, required=True)
|
||||
parser.add_argument('--replace', action='store_true', help='Replace existing rows, including manual edits')
|
||||
parser.add_argument('--tracking-only', action='store_true', help='Update only tracking for matching local orders')
|
||||
args = parser.parse_args()
|
||||
if not args.snapshot.is_file() or args.snapshot.stat().st_size > 10*1024*1024:
|
||||
parser.error('Snapshot must be an existing JSON file smaller than 10 MB')
|
||||
records = json.loads(args.snapshot.read_text(encoding='utf-8-sig'))
|
||||
if isinstance(records, dict): records = records.get('orders')
|
||||
if not isinstance(records, list) or len(records) > 3000:
|
||||
parser.error('Snapshot must contain a list of at most 3000 orders')
|
||||
if not args.db.parent.is_dir(): parser.error('Database parent directory must exist')
|
||||
with sqlite3.connect(args.db) as connection:
|
||||
importer = import_tracking_records if args.tracking_only else import_records
|
||||
result = importer(connection, records, replace=args.replace)
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Export local workbook details or import a private quote snapshot into SQLite."""
|
||||
|
||||
import argparse
|
||||
from contextlib import closing
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from logistics_chat.quote_data import import_snapshot
|
||||
from logistics_chat.quote_workbook import export_snapshot
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
source = parser.add_mutually_exclusive_group(required=True)
|
||||
source.add_argument('--xlsx', type=Path)
|
||||
source.add_argument('--snapshot', type=Path)
|
||||
parser.add_argument('--output', type=Path, help='New private snapshot output for --xlsx')
|
||||
parser.add_argument('--db', type=Path)
|
||||
parser.add_argument('--activate', action='store_true', help='Use this version as general US rates without expiry')
|
||||
args = parser.parse_args()
|
||||
if args.xlsx:
|
||||
if not args.output or args.db or args.output.exists():
|
||||
parser.error('--xlsx requires a new --output path, without --db')
|
||||
snapshot = export_snapshot(args.xlsx)
|
||||
with args.output.open('x', encoding='utf-8') as target:
|
||||
json.dump(snapshot, target, ensure_ascii=False, separators=(',', ':'))
|
||||
print(json.dumps({key:len(snapshot[key]) for key in ('rates','warehouses','postcodes','documents')}))
|
||||
return
|
||||
if not args.db or not args.db.is_file() or not args.snapshot.is_file() or args.snapshot.stat().st_size > 20*1024*1024:
|
||||
parser.error('Import requires an existing database and a private snapshot smaller than 20 MB')
|
||||
snapshot = json.loads(args.snapshot.read_text(encoding='utf-8-sig'))
|
||||
with closing(sqlite3.connect(args.db)) as connection, connection:
|
||||
print(json.dumps(import_snapshot(connection, snapshot, activate=args.activate)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Inspect recent human messages and open sessions without changing the database."""
|
||||
|
||||
import argparse
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
DEFAULT_DB = Path(__file__).resolve().parents[1] / "history.db"
|
||||
|
||||
|
||||
def inspect_sessions(db_path=None):
|
||||
database = Path(db_path if db_path is not None else DEFAULT_DB).expanduser().resolve()
|
||||
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as connection:
|
||||
messages = connection.execute(
|
||||
"SELECT * FROM human_messages ORDER BY id DESC LIMIT 5"
|
||||
).fetchall()
|
||||
sessions = connection.execute(
|
||||
"SELECT id, status FROM human_sessions WHERE status!='closed' ORDER BY id"
|
||||
).fetchall()
|
||||
return messages, sessions
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--db", type=Path, default=DEFAULT_DB, help="Existing SQLite database")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
messages, sessions = inspect_sessions(args.db)
|
||||
except sqlite3.Error as error:
|
||||
parser.exit(1, f"Database error: {error}\n")
|
||||
print(messages)
|
||||
print("---")
|
||||
print(sessions)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,21 +1,46 @@
|
||||
@echo off
|
||||
chcp 936 >nul
|
||||
title Baiyue Logistics AI Customer Service
|
||||
setlocal DisableDelayedExpansion
|
||||
cd /d "%~dp0"
|
||||
|
||||
set "PYTHON_ARGS="
|
||||
if defined VIRTUAL_ENV (
|
||||
set "PYTHON_EXE=%VIRTUAL_ENV%\Scripts\python.exe"
|
||||
call :probe_python
|
||||
if not errorlevel 1 goto python_ready
|
||||
)
|
||||
|
||||
set "PYTHON_EXE=%~dp0.venv\Scripts\python.exe"
|
||||
call :probe_python
|
||||
if not errorlevel 1 goto python_ready
|
||||
|
||||
set "PYTHON_EXE=py.exe"
|
||||
set "PYTHON_ARGS=-3"
|
||||
call :probe_python
|
||||
if not errorlevel 1 goto python_ready
|
||||
|
||||
set "PYTHON_EXE=python.exe"
|
||||
set "PYTHON_ARGS="
|
||||
call :probe_python
|
||||
if not errorlevel 1 goto python_ready
|
||||
|
||||
echo [ERROR] No working Python 3 interpreter found. Install Python or recreate .venv.
|
||||
if /i "%~1"=="--check-python" exit /b 1
|
||||
pause
|
||||
exit /b 1
|
||||
|
||||
:python_ready
|
||||
if /i "%~1"=="--check-python" (
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% -c "import sys; print(sys.executable)"
|
||||
exit /b
|
||||
)
|
||||
|
||||
chcp 936 >nul
|
||||
title Baiyue Logistics AI Customer Service
|
||||
echo ============================================
|
||||
echo Baiyue Logistics AI Customer Service
|
||||
echo ============================================
|
||||
echo.
|
||||
|
||||
where python >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] python not found. Install Python and tick "Add to PATH".
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [1/3] Checking port 5000 ...
|
||||
netstat -ano | findstr "LISTENING" | findstr /C:":5000 " >nul
|
||||
if not errorlevel 1 (
|
||||
@@ -34,23 +59,11 @@ if not errorlevel 1 (
|
||||
)
|
||||
echo OK - port is free.
|
||||
|
||||
echo [2/3] Checking DEEPSEEK_API_KEY ...
|
||||
if "%DEEPSEEK_API_KEY%"=="" (
|
||||
echo.
|
||||
echo [WARN] DEEPSEEK_API_KEY is empty in this window.
|
||||
echo If you just ran setx, reopen this window or restart VS Code.
|
||||
echo setx DEEPSEEK_API_KEY "sk-xxxxxxxx"
|
||||
echo.
|
||||
pause
|
||||
) else (
|
||||
echo OK - key detected.
|
||||
)
|
||||
|
||||
echo [3/3] Checking dependencies ...
|
||||
python -c "import flask, requests" >nul 2>nul
|
||||
echo [2/3] Checking dependencies ...
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% -c "import flask, requests, waitress, dotenv, openpyxl" >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo Missing packages, installing ...
|
||||
python -m pip install -r requirements.txt
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% -m pip install -r requirements.txt
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] pip install failed, check network and retry.
|
||||
pause
|
||||
@@ -59,6 +72,15 @@ if errorlevel 1 (
|
||||
)
|
||||
echo OK - dependencies ready.
|
||||
|
||||
echo [3/3] Checking DeepSeek configuration ...
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% -c "import sys; from logistics_chat.config import default_config; sys.exit(0 if default_config()['DEEPSEEK_API_KEY'] else 1)" >nul
|
||||
if errorlevel 1 (
|
||||
echo [WARN] No DeepSeek API key configured.
|
||||
echo Copy .env.example to .env and set DEEPSEEK_API_KEY, then restart.
|
||||
) else (
|
||||
echo OK - key detected in .env or environment.
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ============================================
|
||||
echo Starting: http://127.0.0.1:5000
|
||||
@@ -67,8 +89,15 @@ echo ============================================
|
||||
echo.
|
||||
|
||||
start "" http://127.0.0.1:5000
|
||||
python am.py
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% am.py
|
||||
set "APP_EXIT_CODE=%ERRORLEVEL%"
|
||||
|
||||
echo.
|
||||
echo Server stopped.
|
||||
pause
|
||||
pause
|
||||
exit /b %APP_EXIT_CODE%
|
||||
|
||||
:probe_python
|
||||
"%PYTHON_EXE%" %PYTHON_ARGS% -c "import sys; sys.exit(0 if sys.version_info.major == 3 else 1)" >nul 2>nul
|
||||
if "%ERRORLEVEL%"=="0" exit /b 0
|
||||
exit /b 1
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
/* A conversation-first console: compact header, session inbox and full-height chat. */
|
||||
body { height: 100dvh; min-height: 0; display: flex; flex-direction: column; overflow: hidden; background: var(--surface); }
|
||||
.topbar { height: 56px; min-height: 56px; display: flex; justify-content: space-between; align-items: center; gap: 20px; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--border); z-index: 30; }
|
||||
.app-identity, .topbar-actions { display: flex; align-items: center; gap: 20px; min-width: 0; }
|
||||
.brand { gap: 10px; }
|
||||
.topbar .brand-mark { width: 30px; height: 30px; border-radius: 8px; }
|
||||
.topbar .brand-mark svg { width: 19px; height: 19px; }
|
||||
.topbar .brand-name { font-size: 15px; white-space: nowrap; }
|
||||
.nav-divider { height: 18px; width: 1px; background: var(--border); }
|
||||
.app-identity h1 { font-size: 14px; font-weight: 500; color: var(--secondary); white-space: nowrap; }
|
||||
.workspace-link { font-size: 12px; color: var(--secondary); text-decoration: none; white-space: nowrap; }
|
||||
.workspace-link:hover { color: var(--brand); }
|
||||
.data-overview { position: relative; }
|
||||
.data-overview summary { display: flex; align-items: center; gap: 7px; padding: 6px 10px; font-size: 12px; color: var(--secondary); cursor: pointer; border-radius: 7px; list-style: none; border: 1px solid var(--border); }
|
||||
.data-overview summary::-webkit-details-marker { display: none; }
|
||||
.data-overview summary svg { width: 15px; height: 15px; }
|
||||
.data-overview[open] summary, .data-overview summary:hover { color: var(--brand); border-color: #bacbf2; background: var(--brand-soft); }
|
||||
.stats { position: absolute; top: calc(100% + 11px); right: 0; width: 310px; padding: 18px; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; border: 1px solid var(--border); border-radius: 11px; background: var(--surface); box-shadow: 0 12px 40px #19263d1a; }
|
||||
.stats h2 { grid-column: 1 / -1; font-size: 13px; font-weight: 600; margin-bottom: 3px; }
|
||||
.stat { display: flex; flex-direction: column; padding: 10px 12px; background: var(--surface-soft); border-radius: 7px; }
|
||||
.stat > span { font-size: 11px; color: var(--secondary); }
|
||||
.stat b { font-size: 23px; font-weight: 600; line-height: 1.5; font-variant-numeric: tabular-nums; }
|
||||
.export-link { display: grid; place-items: center; border: 1px solid var(--border); border-radius: 7px; font-size: 12px; color: var(--brand); text-decoration: none; }
|
||||
.export-link:hover { background: var(--brand-soft); }
|
||||
.sync-status { flex-shrink: 0; background: var(--danger-soft); color: var(--danger); border-bottom: 1px solid #eed0d3; padding: 7px 22px; font-size: 12px; }
|
||||
.layout { flex: 1; min-height: 0; display: grid; grid-template-columns: 300px minmax(0, 1fr); overflow: hidden; }
|
||||
.conv-list { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--surface); border-right: 1px solid var(--border); }
|
||||
.list-heading { padding: 23px 20px 18px; }
|
||||
.list-heading h2 { font-size: 17px; font-weight: 650; }
|
||||
.list-heading p { font-size: 12px; color: var(--muted); margin-top: 4px; }
|
||||
.session-search-wrap { position: relative; margin-top: 17px; }
|
||||
.session-search-wrap svg { position: absolute; top: 12px; left: 11px; width: 15px; height: 15px; color: var(--muted); pointer-events: none; }
|
||||
#session-search { width: 100%; height: 38px; padding: 8px 10px 8px 34px; border: 1px solid transparent; border-radius: 7px; background: var(--surface-soft); color: var(--text); font-size: 13px; }
|
||||
#session-search::placeholder { color: var(--muted); }
|
||||
#session-search:focus { outline: none; border-color: #9ab4ed; background: var(--surface); box-shadow: 0 0 0 3px var(--brand-soft); }
|
||||
.session-tabs { display: flex; gap: 22px; padding: 0 20px; border-bottom: 1px solid var(--border); }
|
||||
.session-tabs button { position: relative; display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 43px; padding: 7px 0 12px; border: 0; background: transparent; color: var(--secondary); font-size: 13px; }
|
||||
.session-tabs button[aria-selected="true"] { color: var(--brand); font-weight: 600; }
|
||||
.session-tabs button[aria-selected="true"]::after { position: absolute; content: ""; height: 2px; background: var(--brand); inset: auto 0 -1px; }
|
||||
.section-count { display: inline-flex; align-items: center; justify-content: center; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 5px; color: var(--muted); background: var(--surface-soft); font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
[aria-selected="true"] .section-count { background: var(--brand-soft); color: var(--brand); }
|
||||
.session-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 10px; }
|
||||
.list-empty { padding: 33px 14px; text-align: center; font-size: 12px; line-height: 1.8; color: var(--muted); }
|
||||
.conv-item { display: flex; align-items: center; gap: 11px; width: 100%; padding: 14px 12px; margin-bottom: 4px; border: 1px solid transparent; border-radius: 8px; text-align: left; background: transparent; }
|
||||
.conv-item:hover { background: var(--surface-soft); }
|
||||
.conv-item.active { background: #edf3ff; border-color: #e3ebfc; }
|
||||
.avatar { flex-shrink: 0; display: grid; place-items: center; width: 39px; height: 39px; border-radius: 11px; color: #60728f; background: #eaf0f7; font-size: 14px; font-weight: 600; }
|
||||
.active .avatar { color: var(--brand); background: #dce7fe; }
|
||||
.conv-item .info { min-width: 0; flex: 1; }
|
||||
.conv-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.conv-item .name { display: block; font-size: 14px; font-weight: 600; color: var(--text); white-space: nowrap; }
|
||||
.conv-time { flex-shrink: 0; color: var(--muted); font-size: 10px; font-weight: 400; }
|
||||
.conv-item .preview { display: block; margin-top: 5px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--secondary); font-size: 12px; }
|
||||
.badge { flex-shrink: 0; padding: 0 5px; border-radius: 5px; background: var(--brand); color: white; font-size: 10px; }
|
||||
.queue-item { border: 1px solid var(--border); border-radius: 8px; padding: 14px; margin-bottom: 8px; background: var(--surface); }
|
||||
.queue-item .qt { font-size: 13px; font-weight: 600; color: var(--text); }
|
||||
.queue-item small { display: block; color: var(--muted); font-size: 11px; font-weight: 400; margin-top: 5px; }
|
||||
.queue-item button { margin-top: 13px; padding: 7px 12px; min-height: 34px; width: 100%; border: 0; border-radius: 6px; background: var(--brand); color: white; font-size: 12px; }
|
||||
.list-footer { flex-shrink: 0; display: flex; align-items: center; gap: 7px; padding: 14px 20px; border-top: 1px solid var(--border); color: var(--muted); font-size: 11px; }
|
||||
.list-footer-mark { width: 6px; height: 6px; border-radius: 50%; background: #91a2bc; }
|
||||
.list-footer > span { display: flex; align-items: center; gap: 7px; }
|
||||
#tools-from-list { display: none; }
|
||||
.chat-area { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: #f5f7fa; }
|
||||
.chat-header { display: flex; flex-shrink: 0; align-items: center; gap: 12px; min-height: 72px; padding: 13px 28px; background: var(--surface); border-bottom: 1px solid var(--border); }
|
||||
.participant-avatar { display: grid; place-items: center; flex-shrink: 0; width: 38px; height: 38px; border-radius: 10px; background: #edf2fa; color: #6a7b96; font-size: 14px; }
|
||||
.participant-copy { flex: 1; min-width: 0; }
|
||||
.participant-copy h2 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 15px; font-weight: 650; }
|
||||
.participant-copy p { margin-top: 2px; color: var(--muted); font-size: 11px; }
|
||||
.has-active-session .participant-copy p { color: #4b796b; }
|
||||
.chat-header-actions { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
|
||||
.tools-toggle, .close { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 33px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; font-size: 12px; background: var(--surface); color: var(--secondary); white-space: nowrap; }
|
||||
.tools-toggle svg { width: 16px; height: 16px; }
|
||||
.tools-toggle[aria-expanded="true"], .tools-toggle:hover { border-color: #bacbf2; color: var(--brand); background: var(--brand-soft); }
|
||||
.close:hover:enabled { border-color: #ecc5ca; background: var(--danger-soft); color: var(--danger); }
|
||||
.close:disabled { cursor: default; opacity: .45; }
|
||||
.has-active-session .participant-avatar { color: var(--brand); background: var(--brand-soft); }
|
||||
body:not(.has-active-session) .close { display: none; }
|
||||
.empty { flex: 1; display: grid; place-items: center; text-align: center; min-height: 0; padding: 30px; }
|
||||
.empty-illustration { display: grid; place-items: center; width: 52px; height: 52px; margin: 0 auto 18px; border: 1px solid #e0e6ee; border-radius: 15px; background: var(--surface); color: #879bb9; }
|
||||
.empty-illustration svg { width: 26px; height: 26px; }
|
||||
.empty h2 { margin-bottom: 8px; font-size: 18px; font-weight: 600; }
|
||||
.empty p { font-size: 13px; line-height: 1.9; color: var(--muted); }
|
||||
.session-panel { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
#chatBox { flex: 1; min-height: 0; overflow-y: auto; padding: 26px clamp(22px, 4vw, 60px); }
|
||||
.msg { display: flex; align-items: flex-start; gap: 10px; max-width: 1040px; margin: 0 auto 24px; }
|
||||
.msg.agent { flex-direction: row-reverse; }
|
||||
.message-avatar { flex-shrink: 0; display: grid; place-items: center; width: 32px; height: 32px; margin-top: 24px; border-radius: 9px; background: #e6ecf4; color: #6e7e97; font-size: 12px; }
|
||||
.message-avatar svg { width: 17px; height: 17px; }
|
||||
.msg.agent .message-avatar { background: var(--brand); color: white; }
|
||||
.message-stack { max-width: min(76%, 720px); min-width: 0; }
|
||||
.meta { margin-bottom: 6px; font-size: 11px; line-height: 1.5; color: var(--muted); }
|
||||
.msg.agent .meta { text-align: right; }
|
||||
.bubble { padding: 12px 16px; border-radius: 3px 10px 10px; border: 1px solid #e4e9f0; background: var(--surface); color: var(--text); font-size: 15px; line-height: 1.8; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.msg.agent .bubble { background: #eaf1ff; border-color: #dce6fb; color: #213858; border-radius: 10px 3px 10px 10px; }
|
||||
.message-image { display: block; max-width: min(240px, 100%); max-height: 320px; object-fit: contain; border-radius: 6px; }
|
||||
.message-file { color: inherit; text-underline-offset: 3px; font-size: 13px; }
|
||||
.agent-composer { flex-shrink: 0; padding: 13px 28px 16px; background: var(--surface); border-top: 1px solid var(--border); }
|
||||
.composer-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; color: var(--secondary); font-size: 12px; }
|
||||
.composer-heading span { color: var(--muted); font-size: 11px; }
|
||||
.input-bar { padding: 10px 12px 9px; border: 1px solid #dce3ed; border-radius: 8px; background: var(--surface); }
|
||||
.input-bar:focus-within { border-color: #8ba8eb; box-shadow: 0 0 0 2px var(--brand-soft); }
|
||||
#replyText { display: block; width: 100%; min-height: 56px; max-height: 180px; padding: 0; border: 0; resize: none; outline: none; background: transparent; color: var(--text); font-size: 14px; line-height: 1.7; }
|
||||
#replyText::placeholder { color: #8b98ab; }
|
||||
.input-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 7px; }
|
||||
.input-actions > span { color: var(--muted); font-size: 11px; }
|
||||
#reply-send { min-width: 78px; min-height: 34px; padding: 6px 20px; border: 0; border-radius: 6px; background: var(--brand); color: white; font-size: 13px; }
|
||||
#reply-send:hover:enabled { background: var(--brand-hover); }
|
||||
.reply-status { font-size: 12px; line-height: 1.6; color: var(--success); padding-top: 7px; }
|
||||
.reply-status.is-error { color: var(--danger); }
|
||||
.system-msg { display: block; text-align: center; color: var(--muted); font-size: 12px; }
|
||||
.recall-button { border: 0; background: transparent; padding: 0 0 0 10px; color: var(--muted); font-size: 11px; }
|
||||
.night-badge { padding: 4px 7px; border-radius: 5px; background: var(--brand-soft); color: var(--secondary); font-size: 11px; }
|
||||
.note-input { width: 100%; padding: 9px; margin-bottom: 9px; border: 1px solid var(--border); border-radius: 7px; background: var(--surface); color: var(--text); resize: vertical; font-size: 13px; }
|
||||
.search-dialog { width: min(660px, calc(100vw - 32px)); max-height: calc(100dvh - 60px); padding: 22px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); }
|
||||
.search-dialog::backdrop { background: #19263d55; }
|
||||
.search-dialog header, .search-dialog form { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 16px; }
|
||||
.search-dialog h2 { font-size: 17px; }
|
||||
.search-dialog input { flex: 1; min-width: 0; padding: 10px; border: 1px solid var(--border); border-radius: 7px; }
|
||||
.search-dialog .quick { width: auto; margin: 0; }
|
||||
.search-result { padding: 14px 0; border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
|
||||
.search-result h3 { font-size: 14px; }
|
||||
.search-result p { margin: 8px 0; white-space: pre-wrap; font-size: 13px; }
|
||||
.search-result small { color: var(--muted); }
|
||||
@media (max-width: 720px) { .night-badge { display: none; } .participant-copy { min-width: 55px; } .chat-header-actions { gap: 4px; } }
|
||||
.side { display: none; min-height: 0; min-width: 0; overflow-y: auto; background: var(--surface); border-left: 1px solid var(--border); }
|
||||
.tools-open .layout { grid-template-columns: 300px minmax(0, 1fr) 310px; }
|
||||
.tools-open .side { display: block; }
|
||||
.side-heading { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px; border-bottom: 1px solid var(--border); background: var(--surface); }
|
||||
.side-heading h2 { font-size: 15px; font-weight: 600; }
|
||||
.side-heading .icon-button { width: 28px; height: 28px; border: 0; font-size: 20px; }
|
||||
.card { padding: 20px 18px; border-bottom: 1px solid var(--border); }
|
||||
.card:last-child { border-bottom: 0; }
|
||||
.card h3 { margin-bottom: 13px; font-size: 13px; font-weight: 600; }
|
||||
.card-caption { color: var(--muted); font-size: 11px; margin: -5px 0 12px; }
|
||||
.info-row { font-size: 12px; line-height: 1.8; color: var(--secondary); }
|
||||
.info-hint { margin-top: 13px; padding: 10px; font-size: 11px; line-height: 1.9; background: var(--surface-soft); color: var(--secondary); border-radius: 6px; }
|
||||
.quick { display: block; width: 100%; margin-bottom: 8px; padding: 10px 12px; border: 1px solid var(--border); border-radius: 6px; text-align: left; background: var(--surface); color: var(--secondary); font-size: 12px; }
|
||||
.quick:hover:enabled { border-color: #a5bdee; color: var(--brand); background: var(--brand-soft); }
|
||||
.quick:disabled { cursor: default; opacity: .5; }
|
||||
.ticket-item { padding: 11px; margin-bottom: 9px; border: 1px solid var(--border); border-radius: 6px; color: var(--secondary); font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; }
|
||||
.ticket-item span { display: block; margin-top: 6px; font-size: 10px; color: var(--muted); }
|
||||
.tools-backdrop, .sessions-back { display: none; }
|
||||
@media (max-width: 1200px) {
|
||||
.layout, .tools-open .layout { grid-template-columns: 280px minmax(0, 1fr); }
|
||||
.side { display: block; position: fixed; top: 0; bottom: 0; right: 0; z-index: 51; width: min(330px, 88vw); border-left: 1px solid var(--border); transform: translateX(105%); visibility: hidden; box-shadow: -10px 0 40px #19263d22; transition: transform .2s; }
|
||||
.tools-open .side { transform: translateX(0); visibility: visible; }
|
||||
.tools-open .tools-backdrop { display: block; position: fixed; inset: 0; z-index: 50; border: 0; background: #19263d55; }
|
||||
.chat-header { padding-left: 22px; padding-right: 22px; }
|
||||
.agent-composer { padding-left: 22px; padding-right: 22px; }
|
||||
}
|
||||
@media (max-width: 900px) and (min-width: 721px) {
|
||||
.layout, .tools-open .layout { grid-template-columns: 248px minmax(0, 1fr); }
|
||||
.list-heading { padding-left: 16px; padding-right: 16px; }
|
||||
.session-tabs { padding-left: 16px; padding-right: 16px; gap: 17px; }
|
||||
.tools-toggle span { display: none; }
|
||||
#chatBox { padding-left: 18px; padding-right: 18px; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.topbar { height: 52px; min-height: 52px; padding: 0 16px; }
|
||||
.app-identity h1, .nav-divider { display: none; }
|
||||
.topbar .brand-name { font-size: 14px; }
|
||||
.topbar-actions { gap: 12px; }
|
||||
.data-overview summary { font-size: 11px; padding: 5px 8px; }
|
||||
.stats { width: min(310px, calc(100vw - 32px)); }
|
||||
.layout, .tools-open .layout { display: flex; flex-direction: column; }
|
||||
.conv-list { flex: 1; min-height: 0; border-right: 0; }
|
||||
.list-footer { justify-content: space-between; }
|
||||
#tools-from-list { display: inline-block; padding: 5px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--secondary); font-size: 11px; }
|
||||
.list-heading { padding: 20px 18px 15px; }
|
||||
.session-tabs { padding-left: 18px; }
|
||||
.list-heading h2 { font-size: 18px; }
|
||||
.conv-item { padding-top: 16px; padding-bottom: 16px; }
|
||||
.chat-area { display: none; flex: 1; min-height: 0; }
|
||||
.chat-view .conv-list { display: none; }
|
||||
.chat-view .chat-area { display: flex; }
|
||||
.sessions-back { display: grid; place-items: center; flex-shrink: 0; width: 30px; height: 34px; padding: 0; border: 0; border-radius: 6px; background: transparent; color: var(--secondary); font-size: 28px; line-height: 1; }
|
||||
.participant-avatar { display: none; }
|
||||
.chat-header { min-height: 65px; padding: 11px 13px 11px 9px; gap: 8px; }
|
||||
.participant-copy h2 { font-size: 14px; }
|
||||
.participant-copy p { font-size: 10px; }
|
||||
.chat-header-actions { gap: 7px; }
|
||||
.tools-toggle { width: 33px; padding: 6px; }
|
||||
.tools-toggle span { display: none; }
|
||||
.close { padding: 6px 8px; font-size: 11px; }
|
||||
#chatBox { padding: 21px 14px; }
|
||||
.msg { gap: 7px; margin-bottom: 20px; }
|
||||
.message-avatar { width: 27px; height: 27px; border-radius: 8px; }
|
||||
.message-stack { max-width: calc(100% - 40px); }
|
||||
.bubble { padding: 10px 12px; font-size: 15px; }
|
||||
.agent-composer { padding: 11px 13px calc(11px + env(safe-area-inset-bottom)); }
|
||||
.composer-heading { margin-bottom: 6px; font-size: 11px; }
|
||||
.composer-heading span { font-size: 10px; }
|
||||
#replyText { font-size: 16px; min-height: 54px; }
|
||||
.input-actions > span { font-size: 10px; max-width: 210px; }
|
||||
#reply-send { min-width: 66px; min-height: 38px; padding: 7px 14px; font-size: 12px; }
|
||||
.reply-status { font-size: 11px; }
|
||||
}
|
||||
@media (max-width: 420px) {
|
||||
.workspace-link { display: none; }
|
||||
.input-actions > span { max-width: 185px; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user