编辑代码
数据管理
字段字典
代码管理
服务发布
编辑:dashboard/monthly_archive.py
/home/ubuntu/app/dashboard/monthly_archive.py
"""月度归档:把「非库存」数据按月冻结一份,并把月度销量 + 毛利算成小快照。 为什么需要(用户 2026-11-02 提出): 现在每张表只保存**最新一次抓取**的结果(datasets.rows 被覆盖写)。源表一旦改名、 换月份、被清空或抓取失败,上个月的销量与毛利就跟着消失 —— 历史账对不上。 所以按月留一份,**源表后续怎么变都不影响已归档的月份**。 为什么存在 dashboard_config 而不是新建表: 云库只允许操作既有表(不允许 DDL),所以复用配置表: md_index → 归档索引(每月每表一行元信息,小) md_
_
→ 单表单月的完整内容(base64(gzip(json))) md_snap_
→ 该月的经营快照(销量 / 毛利 / 台数,按门店) 库存为什么不归档: 库存是**时点值**,每月留一份历史库存容易和"当前在库"混淆; 而且库存表每次都是全量快照,本身可重算。按用户要求排除。 写法约定: - 只增不删:同一 (月, 表) 重复归档是覆盖那一格,不会删别的月份; - 任何异常都吞掉:归档失败绝不能影响主流程(数据写入 / 看板渲染)。 """ from __future__ import annotations import base64 import gzip import json from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Tuple CFG_INDEX = "md_index" IDX_PREFIX_DS = "md_" IDX_PREFIX_SNAP = "md_snap_" # 单表原始 JSON 上限:超过就不归档(避免一条配置撑爆接口) MAX_RAW_BYTES = 8 * 1024 * 1024 def _now() -> str: return datetime.now().strftime("%Y-%m-%d %H:%M:%S") def ds_key(month: str, ds_id: str) -> str: return "%s%s_%s" % (IDX_PREFIX_DS, month, ds_id) def snap_key(month: str) -> str: return IDX_PREFIX_SNAP + month def _load(conn, cid: str, default): try: row = conn.execute("SELECT config FROM dashboard_config WHERE id=?", (cid,)).fetchone() except Exception: return default if not row: return default try: raw = row["config"] if hasattr(row, "keys") else row[0] return json.loads(raw or "{}") except Exception: return default def _save(conn, cid: str, obj: Any) -> None: conn.execute( "INSERT OR REPLACE INTO dashboard_config(id, config, updated_at) VALUES(?,?,?)", (cid, json.dumps(obj, ensure_ascii=False), _now()), ) def _pack(obj: Any) -> str: raw = json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode("utf-8") return base64.b64encode(gzip.compress(raw, 6)).decode("ascii") def _unpack(blob: str) -> Any: return json.loads(gzip.decompress(base64.b64decode(blob)).decode("utf-8")) # ==================== 月份推断 ==================== _MONTH_KEYS = ("开票日期", "销售时间", "销售日期", "日期", "创建时间", "到店时间", "入库日期", "订单日期", "成交日期", "时间") def month_of_rows(cols: Iterable[str], rows: List[List[Any]], hint: str = "") -> str: """先看配置月份,再看行内日期(取出现次数最多的月份),最后返回空。""" h = str(hint or "").strip() if len(h) == 7 and h[4] == "-": return h if not rows: return "" cols = [str(c or "") for c in cols] cand = [] for i, c in enumerate(cols): if any(k in c for k in _MONTH_KEYS) or c.endswith("日期") or c.endswith("时间"): cand.append(i) if not cand: return "" counter: Dict[str, int] = {} for r in rows[:800]: for i in cand: if i >= len(r): continue m = _to_month(r[i]) if m: counter[m] = counter.get(m, 0) + 1 if not counter: return "" return max(counter.items(), key=lambda kv: kv[1])[0] def _to_month(v: Any) -> str: """把各种日期写法折成 YYYY-MM。支持 Excel 序列号。""" if v is None: return "" if isinstance(v, (int, float)): # Excel 序列号:1900 历法(25569 = 1970-01-01) try: n = float(v) except Exception: return "" if 20000 <= n <= 80000: from datetime import timedelta d = datetime(1899, 12, 30) + timedelta(days=int(n)) return d.strftime("%Y-%m") return "" s = str(v).strip() if not s: return "" import re m = re.match(r"^(\d{4})[-/年.](\d{1,2})", s) if m: y, mo = int(m.group(1)), int(m.group(2)) if 2000 <= y <= 2100 and 1 <= mo <= 12: return "%04d-%02d" % (y, mo) return "" # ==================== 索引 ==================== def load_index(conn) -> Dict[str, Any]: idx = _load(conn, CFG_INDEX, {}) or {} if not isinstance(idx, dict): idx = {} idx.setdefault("months", {}) return idx def months(conn) -> List[Dict[str, Any]]: idx = load_index(conn) out = [] for m, info in (idx.get("months") or {}).items(): ds = info.get("datasets") or {} out.append({ "month": m, "datasets": len(ds), "rows": sum(int(v.get("rows") or 0) for v in ds.values()), "bytes": sum(int(v.get("bytes") or 0) for v in ds.values()), "at": info.get("at") or "", "has_snapshot": bool(info.get("snapshot")), }) out.sort(key=lambda x: x["month"], reverse=True) return out # ==================== 归档 ==================== def archive_dataset(conn, ds_id: str, month: str, name: str, store_id: str, cols: List[Any], rows: List[Any], fetched_at: str = "") -> Optional[Dict[str, Any]]: """把一张表某一月的内容冻结一份。返回元信息;跳过的返回 None。""" month = str(month or "").strip() if not (len(month) == 7 and month[4] == "-") or not rows: return None payload = {"ds_id": ds_id, "month": month, "name": name, "store_id": store_id or "", "columns": cols, "rows": rows, "fetched_at": fetched_at or "", "archived_at": _now()} raw = len(json.dumps(payload, ensure_ascii=False).encode("utf-8")) if raw > MAX_RAW_BYTES: return None blob = _pack(payload) _save(conn, ds_key(month, ds_id), {"gz_b64": blob}) meta = {"name": name, "store_id": store_id or "", "rows": len(rows), "cols": len(cols), "bytes": len(blob), "raw_bytes": raw, "at": payload["archived_at"], "fetched_at": payload["fetched_at"]} idx = load_index(conn) bucket = idx["months"].setdefault(month, {"datasets": {}, "at": ""}) bucket.setdefault("datasets", {})[ds_id] = meta bucket["at"] = meta["at"] idx["updated_at"] = meta["at"] _save(conn, CFG_INDEX, idx) return meta def get_dataset(conn, month: str, ds_id: str) -> Optional[Dict[str, Any]]: node = _load(conn, ds_key(month, ds_id), None) if not node or not node.get("gz_b64"): return None try: return _unpack(node["gz_b64"]) except Exception: return None def months_of_dataset(conn, ds_id: str) -> List[str]: idx = load_index(conn) out = [m for m, info in (idx.get("months") or {}).items() if ds_id in (info.get("datasets") or {})] return sorted(out, reverse=True) # ==================== 月度经营快照(销量 + 毛利) ==================== def save_summary(conn, month: str, summary: Dict[str, Any]) -> Dict[str, Any]: summary = dict(summary or {}) summary["month"] = month summary["at"] = _now() _save(conn, snap_key(month), summary) idx = load_index(conn) bucket = idx["months"].setdefault(month, {"datasets": {}, "at": ""}) bucket["snapshot"] = {"at": summary["at"], "stores": len(summary.get("stores") or {})} idx["updated_at"] = summary["at"] _save(conn, CFG_INDEX, idx) return summary def get_summary(conn, month: str) -> Optional[Dict[str, Any]]: node = _load(conn, snap_key(month), None) return node if isinstance(node, dict) and node.get("month") else None def summary_months(conn) -> List[str]: idx = load_index(conn) return sorted([m for m, info in (idx.get("months") or {}).items() if info.get("snapshot")], reverse=True)
保存到服务器
取消