settings.py 6.9 KB
"""配置:设置页(数据库 rsk_sys_settings)> config.toml > 内置默认值;密钥/数据库连接只从 .env 读。

按环境部署的项可以写在 .env 里,优先于 config.toml(同一份代码、同一份 config.toml,换 .env 就换环境):
  CLOUD_PORT       → server.port
  PUBLIC_BASE_URL  → server.public_base_url(设置页里改过的仍以设置页为准)
  DMS_MODE         → business.dms_mode(real = 门店取数端连真实 DMS;mock = 模拟 DMS 演示)

用法:from .settings import S;  S.get("im.bot_id")
"""
from __future__ import annotations

import os
import tomllib
from pathlib import Path

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parent.parent          # cloud/
load_dotenv(ROOT / ".env")

DEFAULTS = {
    "server.host": "0.0.0.0", "server.port": 53003, "server.public_base_url": "", "server.data_dir": "data",
    "edge.offline_seconds": 60, "edge.timeout_scan": 300, "edge.timeout_create_po": 300,
    "edge.timeout_screenshot_po": 240, "edge.timeout_sync_stock_full": 3600, "edge.timeout_check": 300,
    "im.enabled": True, "im.api_base": "https://imhub.glsx.com.cn/api", "im.channel": "yjy_ww", "im.bot_id": "",
    "im.contact_id": "", "im.contact_type": "ww_customer", "im.contact_name": "计划员", "im.allow_senders": "",
    "im.bot_name": "", "im.require_at": True, "im.poll_seconds": 3, "im.image_mode": "upload",
    "llm.model": "qwen-plus", "llm.base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
    "llm.temperature": 0.1, "llm.fallback_rules": True,
    "business.warehouses": "GTMC广州,华南GTMC", "business.supplier_code": "APC40", "business.order_type": "S", "business.in_transit_field": "trans_shipped",
    "business.po_remark": "补货Agent自动创建", "business.cutoff": "16:00", "business.dms_mode": "mock",
    "business.seed_expected": "019990A115:用户手册:10,0400007516:卡子:10",
    "web.order_style": "simple",
}

# .env 环境变量 → 配置项(优先于 config.toml)
ENV_KEYS = {"server.port": "CLOUD_PORT", "server.public_base_url": "PUBLIC_BASE_URL", "business.dms_mode": "DMS_MODE"}

# 设置页可修改的项:(键, 说明)
EDITABLE = [
    ("im.enabled", "是否接通企业微信(关掉后只在网页上模拟)"),
    ("im.api_base", "企微网关地址"),
    ("im.channel", "网关通道"),
    ("im.bot_id", "机器人 bot_id"),
    ("im.contact_id", "交互联系人 contact_id"),
    ("im.contact_type", "联系人类型"),
    ("im.contact_name", "联系人称呼"),
    ("im.allow_senders", "只听这些 sender_id(逗号分隔,空=单聊只听联系人本人 / 群聊不限发言人)"),
    ("im.bot_name", "机器人在群里的昵称(群聊判断是否被 @;逗号分隔可写多个别名)"),
    ("im.require_at", "群聊是否必须 @ 机器人才回复 true/false"),
    ("im.poll_seconds", "收消息轮询间隔(秒)"),
    ("im.image_mode", "截图发送方式 upload / url"),
    ("server.public_base_url", "对外地址(单据链接;空=自动局域网 IP)"),
    ("business.warehouses", "只看这些仓(逗号分隔)"),
    ("business.supplier_code", "采购单供应商代码"),
    ("business.order_type", "采购单订单类型(S=SO 库存补充)"),
    ("business.in_transit_field", "在途取哪个字段:trans_shipped 调拨在途 / unreceived 未收货 / max 取大"),
    ("business.po_remark", "采购单备注"),
    ("business.cutoff", "截单时间"),
    ("business.dms_mode", "数据来源标识 mock / real"),
    ("llm.model", "大模型名称"),
    ("llm.base_url", "大模型接口地址"),
    ("llm.fallback_rules", "模型失败时用规则兜底 true/false"),
    ("web.order_style", "补货单页样式 simple 演示版 / full 完整版"),
]


def _flatten(d: dict, prefix: str = "") -> dict:
    out = {}
    for k, v in d.items():
        key = f"{prefix}{k}"
        if isinstance(v, dict):
            out.update(_flatten(v, key + "."))
        else:
            out[key] = v
    return out


def _coerce(like, value: str):
    if isinstance(like, bool):
        return str(value).strip().lower() in ("1", "true", "yes", "on")
    if isinstance(like, int):
        return int(float(value))
    if isinstance(like, float):
        return float(value)
    return str(value)


class Settings:
    def __init__(self) -> None:
        self.config_path = ROOT / ("config.toml" if (ROOT / "config.toml").exists() else "config.example.toml")
        with open(self.config_path, "rb") as f:
            self.file = _flatten(tomllib.load(f))
        self.overrides: dict[str, str] = {}

    def _env(self, key: str):
        name = ENV_KEYS.get(key)
        return os.environ.get(name, "").strip() if name else ""

    def get(self, key: str):
        base = self.file.get(key, DEFAULTS.get(key))
        if self._env(key):
            try:
                base = _coerce(DEFAULTS.get(key, ""), self._env(key))
            except (TypeError, ValueError):
                pass
        if key in self.overrides:
            try:
                return _coerce(base if base is not None else "", self.overrides[key])
            except (TypeError, ValueError):
                return base
        return base

    def source(self, key: str) -> str:
        if key in self.overrides:
            return "设置页"
        if self._env(key):
            return ".env " + ENV_KEYS[key]
        return "config.toml" if key in self.file else "默认值"

    def list(self, key: str) -> list[str]:
        return [x.strip() for x in str(self.get(key) or "").replace(",", ",").split(",") if x.strip()]

    # ---- 密钥(.env)----
    @staticmethod
    def env(name: str, default: str = "") -> str:
        return os.environ.get(name, default)

    @staticmethod
    def env_label() -> str:
        """.env 的 APP_ENV:test → 测试环境,prod → 正式环境;没填就是「未标注环境」。"""
        name = os.environ.get("APP_ENV", "").strip().lower()
        return {"test": "测试环境", "prod": "正式环境", "dev": "开发环境"}.get(name, name or "未标注环境")

    def db_url(self) -> str:
        from urllib.parse import quote_plus
        if os.environ.get("DB_URL"):          # 测试用(如 sqlite:///...),正式环境用下面的 MySQL 配置
            return os.environ["DB_URL"]
        need = ("DB_HOST", "DB_NAME", "DB_USER", "DB_PASSWORD")
        miss = [n for n in need if not os.environ.get(n)]
        if miss:
            raise RuntimeError(f".env 缺少数据库配置:{', '.join(miss)}")
        return "mysql+pymysql://{u}:{p}@{h}:{port}/{db}?charset=utf8mb4".format(
            u=quote_plus(os.environ["DB_USER"]), p=quote_plus(os.environ["DB_PASSWORD"]), h=os.environ["DB_HOST"],
            port=os.environ.get("DB_PORT", "3306"), db=os.environ["DB_NAME"])

    def data_dir(self) -> Path:
        p = Path(str(self.get("server.data_dir")))
        p = p if p.is_absolute() else ROOT / p
        p.mkdir(parents=True, exist_ok=True)
        return p


S = Settings()