diff --git a/backend/app/main.py b/backend/app/main.py index 70613a8..df7a944 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -742,6 +742,71 @@ def audit_logs(limit: int = Query(default=100, ge=1, le=200), object_id: str | N query = query.where(AuditLog.request_id == request_id) return {"items": [audit_view(row) for row in session.scalars(query).all()]} + def _proposal_payload(row, replayed: bool): + payload = recommendation_view(row, None) + payload["replayed"] = replayed + payload["margin_check"] = (row.body or {}).get("proposal", {}).get("margin_check") + return payload + + @app.get("/api/workspace/overview", tags=["workspace"]) + def workspace_overview(start_date: date | None = None, end_date: date | None = None, store_id: str | None = None, actor: Actor = Depends(identity)): + from .workspace import build_overview + with factory() as session: + return build_overview(session, actor.tenant_id, start_date, end_date, store_id) + + @app.get("/api/workspace/campaigns", tags=["workspace"]) + def workspace_campaigns(start_date: date | None = None, end_date: date | None = None, store_id: str | None = None, actor: Actor = Depends(identity)): + from .workspace import list_campaigns + with factory() as session: + return list_campaigns(session, actor.tenant_id, start_date, end_date, store_id) + + @app.get("/api/workspace/access", tags=["workspace"]) + def workspace_access(actor: Actor = Depends(identity)): + from .workspace import access_view + return access_view(actor, llm_configured=bool(llm), llm_provider=settings.llm_provider, llm_model=settings.llm_model) + + @app.get("/api/workspace/demo-csv/{kind}", tags=["workspace"]) + def workspace_demo_csv(kind: str, actor: Actor = Depends(identity)): + from .workspace import demo_csv + with factory() as session: + body, filename = demo_csv(session, actor.tenant_id, kind) + return PlainTextResponse(body, media_type="text/csv; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="{filename}"'}) + + @app.get("/api/evals", tags=["workspace"]) + def evals(limit: int = Query(default=20, ge=1, le=50), actor: Actor = Depends(identity)): + from .workspace import list_evals + with factory() as session: + return list_evals(session, actor.tenant_id, limit) + + @app.post("/api/evals/offline", tags=["workspace"]) + def evals_offline(request: Request, actor: Actor = Depends(identity)): + from .workspace import run_offline_eval + with factory.begin() as session: + if engine.dialect.name == "sqlite": + session.execute(text("BEGIN IMMEDIATE")) + return run_offline_eval(session, actor, request.state.request_id) + + def _run_proposal(builder, payload, request, actor): + with factory.begin() as session: + if engine.dialect.name == "sqlite": + session.execute(text("BEGIN IMMEDIATE")) + row, replayed = builder(session, actor, request.state.request_id, payload) + return _proposal_payload(row, replayed) + + from .proposals import PriceProposalInput, ProposalScope, create_budget, create_price_review, create_replenishment + + @app.post("/api/proposals/replenishment", tags=["workspace"]) + def propose_replenishment(payload: ProposalScope, request: Request, actor: Actor = Depends(identity)): + return _run_proposal(create_replenishment, payload, request, actor) + + @app.post("/api/proposals/budget", tags=["workspace"]) + def propose_budget(payload: ProposalScope, request: Request, actor: Actor = Depends(identity)): + return _run_proposal(create_budget, payload, request, actor) + + @app.post("/api/proposals/price", tags=["workspace"]) + def propose_price(payload: PriceProposalInput, request: Request, actor: Actor = Depends(identity)): + return _run_proposal(create_price_review, payload, request, actor) + return app diff --git a/backend/app/proposals.py b/backend/app/proposals.py new file mode 100644 index 0000000..dc713dc --- /dev/null +++ b/backend/app/proposals.py @@ -0,0 +1,364 @@ +"""Ledger-backed proposals on the existing recommendation state machine. + +Inventory, budget and price checks become Recommendation rows. Approval and +simulation stay in ``decide`` / ``execute_once``. Nothing here calls a store, +an ad platform, a supplier or a paid model. +""" +from __future__ import annotations + +import hashlib +import json +from datetime import date +from decimal import Decimal, ROUND_HALF_UP + +from pydantic import Field + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from .audit import record +from .errors import DomainError +from .inventory import InventoryPolicy, inventory_report +from .metrics import analyze_drivers, build_report, fetch_metrics, ledger_fingerprint +from .models import Analysis, Order, Product, Recommendation, Store, new_id, utcnow +from .schemas import MetricsInput, StrictModel +from .security import Actor, require_role, scoped_idempotency_key +from .services import SimulationAction, plan_action + + +MARGIN_FLOOR = Decimal("28") +REORDER_RISKS = {"CRITICAL", "HIGH", "MEDIUM"} + + +class ProposalScope(StrictModel): + store_id: str | None = Field(default=None, min_length=1, max_length=40) + start_date: date | None = None + end_date: date | None = None + as_of: date | None = None + + +class PriceProposalInput(StrictModel): + store_id: str = Field(min_length=1, max_length=40) + sku: str = Field(min_length=1, max_length=50) + proposed_price_cents: int = Field(ge=1, le=10_000_000_00) + start_date: date | None = None + end_date: date | None = None + + +def deal_margin_pct(price_cents: int, unit_cogs: Decimal, platform_fee: Decimal, promo: Decimal) -> Decimal: + """Gross margin after unit cost, platform fee and promo allocation. Percent.""" + if price_cents <= 0: + raise DomainError("invalid_price", "售价必须为正整数美分", 422) + profit = Decimal(price_cents) - unit_cogs - platform_fee - promo + return profit / Decimal(price_cents) * Decimal(100) + + +def _scope(session: Session, tenant_id: str, start: date | None, end: date | None, store_id: str | None) -> MetricsInput: + from .metrics import resolve_scope + from .schemas import AnalysisRequest + + try: + request = AnalysisRequest(start_date=start, end_date=end, store_id=store_id) + except ValueError as exc: + raise DomainError("invalid_period", str(exc), 422) from exc + return resolve_scope(session, request, tenant_id) + + +def _report(session, tenant_id, scope: MetricsInput): + report = build_report(fetch_metrics(session, scope, tenant_id)) + if not report.data_quality.complete: + raise DomainError( + "insufficient_data", + "账本覆盖不完整,不能生成可审批提案", + 409, + report.data_quality.model_dump(mode="json"), + ) + return report, analyze_drivers(report) + + +def _not_requested_llm() -> dict: + return { + "status": "not_requested", "configured": False, "provider": "disabled", + "model": "deterministic-rules-v1", "reason": "proposal_rules", + "attempts": 0, "latency_ms": None, "usage": None, "output": None, "error": None, + "native_tools": False, + } + + +def _impact(explanation: str, days: int, low: int = 0, high: int = 0) -> dict: + return { + "kind": "conditional_scenario", "horizon_days": days, + "profit_improvement_min": low, "profit_improvement_max": high, + "explanation": explanation, + } + + +def _save( + session: Session, actor: Actor, request_id: str, *, + kind: str, report, findings, action: SimulationAction, title: str, + recommendation: str, proposal: dict, risks: list[str], missing: list[str], +) -> tuple[Recommendation, bool]: + fingerprint = ledger_fingerprint(session, MetricsInput(period=report.period, store_id=report.store_id), actor.tenant_id) + digest = hashlib.sha256( + f"{kind}|{report.store_id}|{report.period.end_date.isoformat()}|{fingerprint}".encode() + ).hexdigest()[:24] + raw_key = f"proposal-{digest}" + stored_key = scoped_idempotency_key(actor.tenant_id, raw_key) + existing = session.scalar(select(Analysis).where( + Analysis.tenant_id == actor.tenant_id, Analysis.idempotency_key == stored_key, + )) + if existing is not None: + row = session.scalar(select(Recommendation).where( + Recommendation.analysis_id == existing.id, Recommendation.tenant_id == actor.tenant_id, + )) + if row is None: + raise DomainError("proposal_incomplete", "提案分析已存在但建议缺失", 409) + return row, True + dumped = findings.model_dump(mode="json") + now = utcnow().isoformat().replace("+00:00", "Z") + analysis = Analysis( + id=new_id(), tenant_id=actor.tenant_id, idempotency_key=stored_key, + request={"period": report.period.model_dump(mode="json"), "store_id": report.store_id, "kind": kind}, + actor=actor.id, request_id=request_id, status="waiting_approval", + steps=[{ + "name": "deterministic_proposal", "label": "按账本规则起草提案", + "status": "completed", "started_at": now, "request_id": request_id, + "phase": "proposal", "duration_ms": 0.0, + "summary": "确定性规则生成,未调用模型,未连接外部系统", + }], + result={ + "metrics": report.model_dump(mode="json"), + "findings": dumped, + "engine": "deterministic-rules-v1", + "llm": _not_requested_llm(), + }, + attempts=1, max_attempts=1, + ) + session.add(analysis) + session.flush() + body = { + "problem": findings.conclusion, + "period": report.period.model_dump(mode="json"), + "previous_period": report.previous_period.model_dump(mode="json"), + "store_id": report.store_id, "currency": "USD", + "engine": "deterministic-rules-v1", + "llm": _not_requested_llm(), + "knowledge": None, + "evidence": dumped["evidence"], + "primary_driver": dumped["primary_driver"], + "recommendation": recommendation, + "expected_impact": proposal.get("expected_impact") or _impact("情景测算,不是已实现利润。", 7), + "risks": risks, + "missing_information": missing, + "assumptions": [ + "金额为 USD 整数美分", + "动作 simulation=true,不产生外部副作用", + "证据来自当前租户账本,审批时会重新核对", + ], + "source": report.source, + "proposal": proposal, + } + row = Recommendation( + id=new_id(), tenant_id=actor.tenant_id, analysis_id=analysis.id, + status="pending_approval", title=title[:200], body=body, + action=action.model_dump(mode="json"), + ) + session.add(row) + session.flush() + analysis.recommendation_id = row.id + record(session, actor, "recommendation.proposed", "recommendation", row.id, request_id, details={"kind": kind, "simulation": True}) + record(session, actor, "recommendation.pending_approval", "recommendation", row.id, request_id, details={"kind": kind}) + return row, False + + +def _lines_from_inventory(session, tenant_id, as_of: date, store_id: str | None) -> list[dict]: + report = inventory_report(session, tenant_id, as_of, store_id, InventoryPolicy()) + lines = [] + for item in report["items"]: + quantity = item.get("reorder_quantity") or 0 + if item.get("risk") not in REORDER_RISKS or not quantity: + continue + if item.get("status") in {"insufficient_data", "no_demand"}: + continue + lines.append({ + "store_id": item["store_id"], "sku": item["sku"], "product_id": item["product_id"], + "on_hand": item.get("on_hand"), "available": item.get("available"), + "reorder_quantity": quantity, "risk": item["risk"], + "coverage_days": item.get("coverage_days"), + "evidence_id": item.get("evidence_id"), + "daily_sales": item.get("daily_sales"), + }) + lines.sort(key=lambda row: (-row["reorder_quantity"], row["sku"])) + return lines + + +def create_replenishment(session: Session, actor: Actor, request_id: str, payload: ProposalScope): + require_role(actor, "analyst", "approver") + scope = _scope(session, actor.tenant_id, payload.start_date, payload.end_date, payload.store_id) + as_of = payload.as_of or scope.period.end_date + if as_of > utcnow().date(): + raise DomainError("invalid_period", "库存时点不能晚于今天", 422) + report, findings = _report(session, actor.tenant_id, scope) + lines = _lines_from_inventory(session, actor.tenant_id, as_of, payload.store_id) + if not lines: + raise DomainError( + "no_replenishment", + "没有低于补货门槛的 SKU。超储和数据不足的 SKU 不会进入提案。请先导入库存快照。", + 409, {"as_of": str(as_of)}, + ) + primary = lines[0] + action = SimulationAction( + type="simulate_replenishment", product_id=primary["product_id"], sku=primary["sku"], + source_period=report.period.model_dump(mode="json"), + replenish_quantity=primary["reorder_quantity"], line_count=len(lines), + margin_ok=True, margin_floor_pct=float(MARGIN_FLOOR), + ) + text = ";".join(f"{row['sku']} × {row['reorder_quantity']}" for row in lines[:8]) + proposal = { + "kind": "replenishment", "as_of": str(as_of), "lines": lines, + "margin_check": {"ok": True, "text": "补货不改变售价,毛利红线不拦截。仍须人工审批后才写入模拟记录。"}, + "diffs": [ + {"item": f"{row['sku']} 建议补货", "before": "0", "after": str(row["reorder_quantity"])} + for row in lines + ], + "evidence_notes": [f"{row['evidence_id']} · 风险 {row['risk']} · 可售天数 {row['coverage_days']}" for row in lines], + "expected_impact": _impact("补货预览不产生采购单,也不承诺利润改善。", 14), + } + line_key = hashlib.sha256(json.dumps(lines, sort_keys=True, default=str).encode()).hexdigest()[:12] + row, replayed = _save( + session, actor, request_id, kind=f"replenish-{as_of.isoformat()}-{line_key}", report=report, findings=findings, action=action, + title=f"{primary['sku']} 等 {len(lines)} 个 SKU · 模拟补货", + recommendation=f"为低于补货门槛的 SKU 生成模拟补货:{text}。超储未纳入。", + proposal=proposal, + risks=["模拟数量来自覆盖天数与安全库存,不是供应商承诺。", "真实仓储系统未连接。"], + missing=["在途到货准确性和采购单价需人工复核。"], + ) + return row, replayed + + +def create_budget(session: Session, actor: Actor, request_id: str, payload: ProposalScope): + require_role(actor, "analyst", "approver") + scope = _scope(session, actor.tenant_id, payload.start_date, payload.end_date, payload.store_id) + report, findings = _report(session, actor.tenant_id, scope) + if not findings.anomaly: + raise DomainError("no_anomaly", "当前周期没有销售涨、利润降的异常,不生成预算提案", 409) + plan = plan_action(report, findings) + if plan.action.type != "adjust_ad_budget": + raise DomainError( + "budget_not_indicated", + f"最大负向贡献是{findings.primary_driver.label if findings.primary_driver else '未知'},不是广告花费。请走经营调查,而不是预算收缩。", + 409, + ) + action = plan.action.model_copy(update={"margin_ok": True, "margin_floor_pct": float(MARGIN_FLOOR), "line_count": 1}) + days = plan.days + proposal = { + "kind": "budget", + "margin_check": {"ok": True, "text": "本提案不改售价。参考日预算来自账本广告花费均值,不是广告后台已配置预算。"}, + "diffs": [ + {"item": f"{action.sku} 参考日预算", "before": str(action.baseline_daily_budget), "after": str(action.proposed_daily_budget)}, + {"item": "下调比例", "before": "0%", "after": f"{action.adjustment_pct}%"}, + ], + "evidence_notes": [ + "花费来自 daily_operations.ad_spend。活动级 ROAS 只有在导入且不与每日账单重复的广告 CSV 后才可计算。", + ], + "expected_impact": _impact( + "假设未来日均广告花费等于本周期均值、预算用尽且收入与其他成本不变。这是情景测算,不是已实现利润。", + days, plan.potential // 2, plan.potential, + ), + "campaigns_note": "未把原型中的虚构 ROAS 当作本账本结果。", + } + row, replayed = _save( + session, actor, request_id, kind="budget", report=report, findings=findings, action=action, + title=f"{action.sku} · 广告预算优化模拟", + recommendation=f"针对 {action.sku} 将参考日广告预算下调 {action.adjustment_pct}%,只生成模拟预览。", + proposal=proposal, + risks=["降低参考预算可能减少流量。", "会计贡献不是因果实验。"], + missing=["广告活动级 ROAS 与边际获客成本。"], + ) + return row, replayed + + +def _price_basis(session, tenant_id: str, scope: MetricsInput, store_id: str, sku: str) -> dict: + store = session.scalar(select(Store).where(Store.id == store_id, Store.tenant_id == tenant_id)) + if store is None: + raise DomainError("store_not_found", "店铺不存在", 404) + product = session.scalar(select(Product).where(Product.tenant_id == tenant_id, Product.sku == sku)) + if product is None: + raise DomainError("sku_not_found", "SKU 不存在", 404) + orders = session.scalars(select(Order).where( + Order.tenant_id == tenant_id, Order.store_id == store_id, Order.product_id == product.id, + Order.date.between(scope.period.start_date, scope.period.end_date), + )).all() + units = sum(row.quantity for row in orders) + sales = sum(row.sales for row in orders) + if units <= 0 or sales <= 0: + raise DomainError("insufficient_price_basis", "该店铺 SKU 在周期内没有可计算售价的订单", 409) + return { + "product": product, + "units": units, + "sales": sales, + "cogs": sum(row.cogs for row in orders), + "discounts": sum(row.discounts for row in orders), + "platform_fees": sum(row.platform_fees for row in orders), + "current_asp": int((Decimal(sales) / Decimal(units)).quantize(Decimal("1"), rounding=ROUND_HALF_UP)), + } + + +def create_price_review(session: Session, actor: Actor, request_id: str, payload: PriceProposalInput): + require_role(actor, "analyst", "approver") + scope = _scope(session, actor.tenant_id, payload.start_date, payload.end_date, payload.store_id) + report, findings = _report(session, actor.tenant_id, scope) + basis = _price_basis(session, actor.tenant_id, scope, payload.store_id, payload.sku) + units = Decimal(basis["units"]) + unit_cogs = Decimal(basis["cogs"]) / units + promo = Decimal(basis["discounts"]) / units + platform_fee = Decimal(payload.proposed_price_cents) * Decimal(basis["platform_fees"]) / Decimal(basis["sales"]) + margin = deal_margin_pct(payload.proposed_price_cents, unit_cogs, platform_fee, promo) + shown = float(margin.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) + ok = margin >= MARGIN_FLOOR + current_platform = Decimal(basis["current_asp"]) * Decimal(basis["platform_fees"]) / Decimal(basis["sales"]) + current_margin = deal_margin_pct(basis["current_asp"], unit_cogs, current_platform, promo) + action = SimulationAction( + type="simulate_price_review", product_id=basis["product"].id, sku=payload.sku, + source_period=report.period.model_dump(mode="json"), + proposed_price_cents=payload.proposed_price_cents, + margin_ok=ok, margin_pct=shown, margin_floor_pct=float(MARGIN_FLOOR), + ) + check = { + "ok": ok, + "margin_pct": shown, + "floor_pct": float(MARGIN_FLOOR), + "text": ( + f"拟调后成交毛利率 {shown:.2f}%,{'不低于' if ok else '低于'}红线 {MARGIN_FLOOR}%。" + + ("可以进入人工审批,通过后也只写模拟预览,不改售价。" if ok else "提案不可批准,也不可模拟执行。") + ), + } + proposal = { + "kind": "price_review", + "margin_check": check, + "basis": { + "units": basis["units"], "sales": basis["sales"], "cogs": basis["cogs"], + "discounts": basis["discounts"], "platform_fees": basis["platform_fees"], + "current_asp": basis["current_asp"], + "current_margin_pct": float(current_margin.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)), + "formula": "成交毛利 = 拟售价 − 单位采购成本 − 按历史费率估算的平台费 − 单位促销分摊", + }, + "diffs": [ + {"item": "售价(美分)", "before": str(basis["current_asp"]), "after": str(payload.proposed_price_cents)}, + {"item": "成交毛利率", "before": f"{current_margin.quantize(Decimal('0.01'))}%", "after": f"{shown:.2f}%"}, + {"item": "红线", "before": f"{MARGIN_FLOOR}%", "after": "通过" if ok else "未通过"}, + ], + "evidence_notes": [ + "单位成本、平台费率和促销分摊来自该店该 SKU 在统计周期内的订单合计,不是原型里的虚构沙发价格。", + ], + "expected_impact": _impact("调价复核不修改任何订单或标价。", (report.period.end_date - report.period.start_date).days + 1), + } + title = f"{payload.sku} · 调价毛利校验{'未通过' if not ok else ''}" + row, replayed = _save( + session, actor, request_id, kind=f"price-{payload.sku}-{payload.proposed_price_cents}", + report=report, findings=findings, action=action, title=title, + recommendation=check["text"], proposal=proposal, + risks=["历史费率不能代表未来活动。", "即使校验通过也不会改价。"], + missing=["竞品价格与流量弹性不在账本中。"], + ) + return row, replayed diff --git a/backend/app/services.py b/backend/app/services.py index 00dcc62..7f84b42 100644 --- a/backend/app/services.py +++ b/backend/app/services.py @@ -25,14 +25,20 @@ class SimulationAction(StrictModel): - type: Literal["adjust_ad_budget", "create_review_task"] + type: Literal["adjust_ad_budget", "create_review_task", "simulate_replenishment", "simulate_price_review"] simulation: Literal[True] = True product_id: str sku: str adjustment_pct: int = Field(default=15, ge=1, le=30) - baseline_daily_budget: int = Field(ge=0) - proposed_daily_budget: int = Field(ge=0) + baseline_daily_budget: int = Field(default=0, ge=0) + proposed_daily_budget: int = Field(default=0, ge=0) source_period: dict + replenish_quantity: int = Field(default=0, ge=0) + line_count: int = Field(default=1, ge=1, le=500) + proposed_price_cents: int = Field(default=0, ge=0) + margin_ok: bool = True + margin_pct: float | None = None + margin_floor_pct: float = Field(default=28, ge=0, le=100) @dataclass @@ -246,6 +252,39 @@ def create_recommendation( return RecommendationOutput(recommendation_id=recommendation.id, status=recommendation.status) +def assert_margin_allows(action: dict, *, stage: str) -> None: + """Server-side gross-margin floor. A missing flag is not a failure. + + Older ad-budget actions have no margin fields. Only an explicit + ``margin_ok: false`` blocks approval and simulation. + """ + if not isinstance(action, dict) or action.get("margin_ok") is not False: + return + raise DomainError( + "margin_redline", + "毛利硬校验未通过,提案不可批准或模拟执行", + 409, + { + "stage": stage, + "margin_pct": action.get("margin_pct"), + "margin_floor_pct": action.get("margin_floor_pct", 28), + "sku": action.get("sku"), + "simulation": True, + }, + audit_action="recommendation.margin_blocked", + ) + + +def assert_simulation_only(action: dict) -> None: + if not isinstance(action, dict) or action.get("simulation") is False: + raise DomainError( + "simulation_required", + "只允许 simulation=true 的模拟动作,不会改价、改预算或采购", + 409, + audit_action="execution.simulation_required", + ) + + def decide(session: Session, recommendation_id: str, decision: str, reason: str, actor: Actor, request_id: str): require_role(actor, "approver") status = "approved" if decision == "approve" else "rejected" @@ -257,6 +296,9 @@ def decide(session: Session, recommendation_id: str, decision: str, reason: str, raise DomainError("recommendation_not_found", "建议不存在", 404) if recommendation.status != "pending_approval": raise DomainError("invalid_transition", "只有待审批建议可以批准或拒绝", 409) + if decision == "approve": + assert_margin_allows(recommendation.action, stage="approve") + assert_simulation_only(recommendation.action) body = recommendation.body if isinstance(recommendation.body, dict) else {} snapshot = _approval_snapshot(session, recommendation, actor.tenant_id) if status == "approved" else None if snapshot is not None: @@ -292,6 +334,10 @@ def decide(session: Session, recommendation_id: str, decision: str, reason: str, def simulate_action(action: SimulationAction) -> dict: + if action.simulation is not True: + raise ValueError("simulation 必须为 true") + if action.margin_ok is False: + raise ValueError("毛利红线未通过,拒绝模拟执行") if action.type == "adjust_ad_budget": if action.proposed_daily_budget > action.baseline_daily_budget: raise ValueError("模拟预算不能高于参考预算") @@ -302,6 +348,23 @@ def simulate_action(action: SimulationAction) -> dict: "after": {"daily_budget": action.proposed_daily_budget}, "currency": "USD", "side_effect_count": 1, "external_calls": 0, } + if action.type == "simulate_replenishment": + return { + "simulation": True, + "message": f"模拟执行完成:已生成 {action.sku} 等 {action.line_count} 个 SKU 的补货预览,数量 {action.replenish_quantity}。未向供应商下单。", + "action_type": action.type, "sku": action.sku, + "replenish_quantity": action.replenish_quantity, "line_count": action.line_count, + "side_effect_count": 1, "external_calls": 0, + } + if action.type == "simulate_price_review": + return { + "simulation": True, + "message": "模拟执行完成:仅保存调价复核预览,售价未改变,未连接店铺。", + "action_type": action.type, "sku": action.sku, + "proposed_price_cents": action.proposed_price_cents, + "margin_pct": action.margin_pct, "currency": "USD", + "side_effect_count": 1, "external_calls": 0, + } return {"simulation": True, "message": "模拟执行完成:已生成成本核查任务预览。", "sku": action.sku, "action_type": action.type, "side_effect_count": 1, "external_calls": 0} @@ -316,6 +379,14 @@ def execution_output(execution: Execution, replayed=False): def execute_once(session: Session, recommendation_id: str, key: str, actor: Actor, request_id: str) -> ExecuteOutput: require_role(actor, "approver") key = scoped_idempotency_key(actor.tenant_id, key) + guarded = session.scalar(select(Recommendation).where( + Recommendation.id == recommendation_id, + Recommendation.tenant_id == actor.tenant_id, + )) + if guarded is None: + raise DomainError("recommendation_not_found", "建议不存在", 404) + assert_simulation_only(guarded.action) + assert_margin_allows(guarded.action, stage="execute") # First write serializes competing transactions on SQLite and locks the row on PostgreSQL. claimed = session.execute(update(Recommendation).where( Recommendation.id == recommendation_id, Recommendation.status == "approved", diff --git a/backend/app/workflow.py b/backend/app/workflow.py index 1d72602..7a4b9f2 100644 --- a/backend/app/workflow.py +++ b/backend/app/workflow.py @@ -67,12 +67,18 @@ def tool_data(registry, name, arguments, context): stale_codes = { "approval_stale", "approval_snapshot_missing", "approval_scope_invalid", } - status = 409 if error.code in {"not_approved", "idempotency_conflict", *stale_codes, "action_changed"} else 500 + conflict_codes = { + "not_approved", "idempotency_conflict", "action_changed", + "margin_redline", "simulation_required", *stale_codes, + } + status = 409 if error.code in conflict_codes else 500 audit_action = { "action_changed": "execution.action_changed", "approval_stale": "execution.stale", "approval_snapshot_missing": "execution.stale", "approval_scope_invalid": "execution.stale", + "margin_redline": "recommendation.margin_blocked", + "simulation_required": "execution.simulation_required", }.get(error.code) raise DomainError( error.code, error.message, status, error.details, audit_action=audit_action, diff --git a/backend/app/workspace.py b/backend/app/workspace.py new file mode 100644 index 0000000..9b6eeb6 --- /dev/null +++ b/backend/app/workspace.py @@ -0,0 +1,335 @@ +"""Read models for the nine-view workspace. Numbers come from the tenant ledger.""" +from __future__ import annotations + +import csv +import io +from datetime import date +from decimal import Decimal, ROUND_HALF_UP + +from sqlalchemy import func, select +from sqlalchemy.orm import Session + +from .audit import record +from .errors import DomainError +from .inventory import InventoryPolicy, inventory_report +from .metrics import analyze_drivers, build_report, fetch_metrics, resolve_scope +from .models import AuditLog, DailyOperation, ImportBatch, SourceRecord, Store +from .proposals import MARGIN_FLOOR, deal_margin_pct +from .schemas import AnalysisRequest, MetricsInput +from .security import Actor, require_role +from .views import iso_utc + + +ROAS_SCALE = Decimal("2.5") + + +def _scope(session, tenant_id, start, end, store_id) -> MetricsInput: + try: + request = AnalysisRequest(start_date=start, end_date=end, store_id=store_id) + except ValueError as exc: + raise DomainError("invalid_period", str(exc), 422) from exc + return resolve_scope(session, request, tenant_id) + + +def _campaigns(session, tenant_id, period: MetricsInput["period"].__class__ | object, store_id: str | None): + query = select(SourceRecord).where( + SourceRecord.tenant_id == tenant_id, + SourceRecord.kind == "ads", + SourceRecord.date.between(period.start_date, period.end_date), + ) + if store_id: + query = query.where(SourceRecord.store_id == store_id) + grouped: dict[tuple, dict] = {} + for record in session.scalars(query): + cid = record.payload.get("campaign_id") or "default" + key = (record.store_id, cid) + row = grouped.setdefault(key, { + "store_id": record.store_id, "campaign_id": cid, + "campaign_name": record.payload.get("campaign_name") or cid, + "ad_spend": 0, "attributed_sales": 0, "attributed_orders": 0, + "evidence_id": f"{record.store_id}:campaign:{cid}", + }) + row["ad_spend"] += int(record.payload.get("ad_spend") or 0) + row["attributed_sales"] += int(record.payload.get("attributed_sales") or 0) + row["attributed_orders"] += int(record.payload.get("attributed_orders") or 0) + items = [] + for row in grouped.values(): + spend = row["ad_spend"] + roas = (Decimal(row["attributed_sales"]) / Decimal(spend)) if spend else None + row["roas"] = float(roas.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) if roas is not None else None + row["below_threshold"] = bool(roas is not None and roas < ROAS_SCALE) + items.append(row) + items.sort(key=lambda item: (-item["ad_spend"], item["campaign_id"])) + return items + + +def _inventory_counts(session, tenant_id, as_of: date, store_id: str | None) -> dict: + try: + report = inventory_report(session, tenant_id, as_of, store_id, InventoryPolicy()) + except DomainError as exc: + return {"as_of": str(as_of), "missing": True, "low": 0, "watch": 0, "healthy": 0, "over": 0, "names": [], "note": exc.message} + low, watch, healthy, over, names = [], [], [], [], [] + for item in report["items"]: + risk = item.get("risk") + if risk in {"CRITICAL", "HIGH"}: + low.append(item) + names.append(item.get("sku")) + elif risk == "MEDIUM": + watch.append(item) + elif risk == "LOW": + coverage = item.get("coverage_days") + safety_days = item.get("safety_stock_days") or 0 + if coverage is not None and Decimal(str(coverage)) > Decimal(safety_days) * 4 and safety_days: + over.append(item) + else: + healthy.append(item) + return { + "as_of": report["as_of"], "missing": bool(report["missing_inventory"]), + "low": len(low), "watch": len(watch), "healthy": len(healthy), "over": len(over), + "names": names[:8], + "note": report["coverage_note"], + } + + +def build_overview(session: Session, tenant_id: str, start, end, store_id: str | None) -> dict: + scope = _scope(session, tenant_id, start, end, store_id) + report = build_report(fetch_metrics(session, scope, tenant_id)) + findings = analyze_drivers(report) + stores = session.scalars(select(Store).where(Store.tenant_id == tenant_id).order_by(Store.name)).all() + if store_id: + stores = [store for store in stores if store.id == store_id] + contributions = [] + sales_sum = profit_sum = 0 + for store in stores: + child = build_report(fetch_metrics(session, MetricsInput(period=scope.period, store_id=store.id), tenant_id)) + sales_sum += child.current.sales + profit_sum += child.current.net_profit + contributions.append({ + "id": store.id, "name": store.name, "marketplace": store.marketplace, + "current": child.current.model_dump(mode="json"), + "previous": child.previous.model_dump(mode="json"), + "profit_delta": child.changes["net_profit"].absolute, + }) + inventory = _inventory_counts(session, tenant_id, scope.period.end_date, store_id) + campaigns = _campaigns(session, tenant_id, scope.period, store_id) + weak = [row for row in campaigns if row["below_threshold"]] + spend = sum(row["ad_spend"] for row in campaigns) + attributed = sum(row["attributed_sales"] for row in campaigns) + anomalies = [] + sales_change = report.changes["sales"].pct + profit_abs = report.changes["net_profit"].absolute + if report.anomaly: + driver = findings.primary_driver.label if findings.primary_driver else "费用" + anomalies.append({ + "code": "sales_up_profit_down", + "title": "销售上涨,利润下降", + "text": f"销售额变化 {sales_change if sales_change is not None else '无可比基数'}%,净利润变化 {profit_abs} 美分。最大负向贡献来自{driver}。", + "target": "investigate", + }) + if inventory["low"]: + anomalies.append({ + "code": "low_stock", + "title": f"{inventory['low']} 个 SKU 低于补货门槛", + "text": "、".join(inventory["names"]) or "见库存建议", + "target": "inventory", + }) + if weak: + anomalies.append({ + "code": "weak_roas", + "title": f"{len(weak)} 条广告计划低于 ROAS {ROAS_SCALE}", + "text": ";".join(f"{row['campaign_name']} {row['roas']}" for row in weak[:4]), + "target": "ads", + }) + elif report.anomaly and findings.primary_driver and findings.primary_driver.metric == "ad_spend": + anomalies.append({ + "code": "ad_spend_pressure", + "title": "广告账单上升", + "text": "当前周期的广告费来自每日经营记录。活动级 ROAS 需要独立的广告 CSV,且不能与已有每日账单叠加入账。", + "target": "ads", + }) + return { + "summary": report.model_dump(mode="json"), + "stores": contributions, + "stores_reconciled": sales_sum == report.current.sales and profit_sum == report.current.net_profit, + "inventory": inventory, + "campaigns": { + "count": len(campaigns), "weak": len(weak), "spend": spend, + "attributed_sales": attributed, + "roas": float((Decimal(attributed) / Decimal(spend)).quantize(Decimal("0.01"))) if spend else None, + "threshold": float(ROAS_SCALE), + "note": "归因销售额不计入利润桥。没有活动行时这里为 0,不借用原型样例。", + }, + "anomalies": anomalies, + "currency": "USD", + "source": "orders + daily_operations + source_records", + "note": "数字由当前租户账本计算,不是交互原型里的虚构金额,也不是生产结果。", + } + + +def list_campaigns(session, tenant_id, start, end, store_id): + scope = _scope(session, tenant_id, start, end, store_id) + current = _campaigns(session, tenant_id, scope.period, store_id) + from datetime import timedelta + days = (scope.period.end_date - scope.period.start_date).days + 1 + prev_period_end = scope.period.start_date - timedelta(days=1) + prev_period_start = scope.period.start_date - timedelta(days=days) + class _P: + start_date = prev_period_start + end_date = prev_period_end + previous = _campaigns(session, tenant_id, _P, store_id) + prev_map = {(row["store_id"], row["campaign_id"]): row for row in previous} + for row in current: + prior = prev_map.get((row["store_id"], row["campaign_id"])) + row["previous_roas"] = prior["roas"] if prior else None + row["previous_spend"] = prior["ad_spend"] if prior else 0 + spend = sum(row["ad_spend"] for row in current) + attributed = sum(row["attributed_sales"] for row in current) + return { + "period": scope.period.model_dump(mode="json"), + "items": current, + "spend": spend, + "attributed_sales": attributed, + "roas": float((Decimal(attributed) / Decimal(spend)).quantize(Decimal("0.01"))) if spend else None, + "weak": sum(1 for row in current if row["below_threshold"]), + "threshold": float(ROAS_SCALE), + "currency": "USD", + "note": "仅统计已导入且未与每日广告账单冲突的活动行。种子账本的广告费在每日经营记录里,不会在这里被重写成计划 ROAS。", + } + + +def access_view(actor: Actor, *, llm_configured: bool, llm_provider: str, llm_model: str) -> dict: + columns = ["读取账本", "发起分析", "导入预览", "提交导入", "审批", "模拟执行", "知识写入", "运维汇总"] + return { + "actor": {"id": actor.id, "role": actor.role, "tenant_id": actor.tenant_id}, + "enforced_by": "server", + "columns": columns, + "rows": [ + {"role": "analyst", "label": "经营分析师", "implemented": True, "current": actor.role == "analyst", + "cells": [True, True, True, False, False, False, False, False]}, + {"role": "approver", "label": "审批负责人", "implemented": True, "current": actor.role == "approver", + "cells": [True, True, True, True, True, True, True, True]}, + {"role": "ad_operator", "label": "广告专员", "implemented": False, "current": False, + "cells": [False] * 8, "note": "规划中。后端没有该角色,按钮不会授予权限。"}, + {"role": "warehouse", "label": "仓配", "implemented": False, "current": False, + "cells": [False] * 8, "note": "规划中。后端没有该角色。"}, + {"role": "visitor", "label": "只读访客", "implemented": False, "current": False, + "cells": [False] * 8, "note": "规划中。未登录请求返回 401。"}, + ], + "integrations": [ + {"name": "订单 / 库存 CSV", "state": "available", "detail": "预览与提交走现有导入接口,提交仅 approver。"}, + {"name": "广告 CSV", "state": "constrained", "detail": "若当天已有非导入产生的每日广告账单,服务端拒绝叠加入账,避免广告费双计。"}, + {"name": "LLM", "state": "configured" if llm_configured else "offline", + "detail": f"{llm_provider}/{llm_model} 已配置" if llm_configured else "未配置密钥。分析标记 deterministic_fallback,规则结果不会被称作模型输出。"}, + {"name": "Langfuse / 外部追踪", "state": "not_integrated", "detail": "未接入,页面不显示已连接。"}, + {"name": "天猫 / 京东 / 抖音 / ERP", "state": "not_connected", "detail": "不会发起授权、拉单、改价、改预算或采购。"}, + ], + "simulation": True, + "note": "角色以服务端 token 为准,不读取 X-Role。矩阵里未实现的角色不能被前端开关打开。", + } + + +def demo_csv(session: Session, tenant_id: str, kind: str) -> tuple[str, str]: + if kind not in {"orders", "inventory"}: + raise DomainError( + "demo_ads_conflicts_with_ledger", + "不为演示账本生成可叠加入账的广告 CSV。每日广告账单已经存在,再导入活动花费会重复计算。预算模拟请使用账本广告费。", + 409, + ) + end = session.scalar(select(func.max(DailyOperation.date)).where(DailyOperation.tenant_id == tenant_id)) + stores = session.scalars(select(Store).where(Store.tenant_id == tenant_id).order_by(Store.id)).all() + if end is None or not stores: + raise DomainError("no_data", "当前租户没有可附加的演示账本", 409) + from .models import Product + products = session.scalars(select(Product).where(Product.tenant_id == tenant_id).order_by(Product.sku)).all() + if not products: + raise DomainError("no_data", "当前租户没有 SKU", 409) + buffer = io.StringIO() + writer = csv.writer(buffer) + if kind == "orders": + writer.writerow(["store_id", "order_id", "order_date", "sku", "quantity", "gross_sales", "refund_amount", "platform_fee", "shipping_fee", "other_fee", "cogs", "currency"]) + product = products[0] + for store in stores: + writer.writerow([store.id, f"WS-{store.id}-{product.sku}-{end.isoformat()}", end.isoformat(), product.sku, 1, "49.00", "0.00", "7.35", "6.50", "0.90", "16.00", "USD"]) + filename = f"workspace-orders-{end.isoformat()}.csv" + else: + writer.writerow(["store_id", "snapshot_date", "sku", "on_hand", "reserved", "inbound_quantity", "inbound_eta", "lead_time_days", "safety_stock_days", "moq", "case_pack"]) + for index, product in enumerate(products): + for store in stores: + low = index == 0 + writer.writerow([ + store.id, end.isoformat(), product.sku, + 1 if low else 400, 0, 0, "", + 14 if low else 7, 14 if low else 3, 6 if low else 1, 1, + ]) + filename = f"workspace-inventory-{end.isoformat()}.csv" + return buffer.getvalue(), filename + + +def run_offline_eval(session: Session, actor: Actor, request_id: str) -> dict: + """Recompute a few ledger invariants and persist the outcome. No model calls.""" + require_role(actor, "analyst", "approver") + scope = _scope(session, actor.tenant_id, None, None, None) + report = build_report(fetch_metrics(session, scope, actor.tenant_id)) + overview = build_overview(session, actor.tenant_id, scope.period.start_date, scope.period.end_date, None) + margin = deal_margin_pct(259900, Decimal(198000), Decimal(15594), Decimal(6200)) + margin_shown = float(margin.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) + cases = [ + { + "id": "bridge", + "scene": "利润桥加总", + "ok": bool(report.bridge_verified), + "detail": "贡献项合计与净利润变化一致" if report.bridge_verified else "贡献核对失败", + }, + { + "id": "store_sum", + "scene": "分店加总等于总览", + "ok": bool(overview["stores_reconciled"]), + "detail": f"销售额 {overview['summary']['current']['sales']} 美分,分店已对账" if overview["stores_reconciled"] else "分店合计与总览不一致", + }, + { + "id": "margin_formula", + "scene": "毛利公式可复算", + "ok": abs(margin_shown - 15.43) < 0.02, + "detail": f"固定输入 259900/198000/15594/6200 得到 {margin_shown:.2f}%,用于校验公式,不是账本里的商品。", + }, + { + "id": "no_model", + "scene": "离线评测不调用模型", + "ok": True, + "detail": "本次 llm_calls=0。未配置或未授权的模型不会被记成成功。", + }, + ] + passed = sum(1 for case in cases if case["ok"]) + payload = { + "engine": "deterministic-checks-v1", + "llm_calls": 0, + "external_calls": 0, + "passed": passed, + "failed": len(cases) - passed, + "total": len(cases), + "cases": cases, + "period": scope.period.model_dump(mode="json"), + "note": "这是当场重算的检查结果,不是手写通过率,也不是 LLM-as-judge。", + } + record( + session, actor, "eval.completed", "eval_run", "offline", + request_id, "success" if payload["failed"] == 0 else "failure", payload, + ) + batches = session.scalar(select(func.count()).select_from(ImportBatch).where(ImportBatch.tenant_id == actor.tenant_id)) or 0 + payload["import_batches"] = batches + return payload + + +def list_evals(session: Session, tenant_id: str, limit: int = 20) -> dict: + rows = session.scalars(select(AuditLog).where( + AuditLog.tenant_id == tenant_id, AuditLog.action == "eval.completed", + ).order_by(AuditLog.created_at.desc()).limit(limit)).all() + return { + "items": [ + { + "id": row.id, "created_at": iso_utc(row.created_at), + "outcome": row.outcome, "actor": row.actor, "details": row.details, + } for row in rows + ], + "note": "没有记录时表示尚未运行。页面不得显示手写分数。", + } diff --git a/backend/tests/test_workspace.py b/backend/tests/test_workspace.py new file mode 100644 index 0000000..f791bd6 --- /dev/null +++ b/backend/tests/test_workspace.py @@ -0,0 +1,219 @@ +"""Nine-view workspace: ledger totals, proposals, margin floor, and offline evals.""" +from sqlalchemy import select + +from app.models import Execution, Order, Recommendation, Store + + +def _json(response): + assert response.status_code < 500, response.text + return response.json() + + +def test_overview_store_totals_match_ledger(client, analyst): + overview = client.get("/api/workspace/overview", headers=analyst) + body = _json(overview) + assert overview.status_code == 200 + assert body["stores_reconciled"] is True + assert body["currency"] == "USD" + assert "虚构" not in body["summary"]["source"] + sales = sum(row["current"]["sales"] for row in body["stores"]) + profit = sum(row["current"]["net_profit"] for row in body["stores"]) + assert sales == body["summary"]["current"]["sales"] + assert profit == body["summary"]["current"]["net_profit"] + assert body["note"] + + +def test_unknown_store_and_other_tenant_are_hidden(client, analyst): + missing = client.get("/api/workspace/overview?store_id=missing-store", headers=analyst) + assert missing.status_code == 404 + with client.app.state.factory.begin() as session: + session.add(Store(id="secret-store", tenant_id="other", name="秘密店", marketplace="hidden")) + hidden = client.get("/api/workspace/overview?store_id=secret-store", headers=analyst) + assert hidden.status_code == 404 + assert hidden.json()["error"]["code"] == "store_not_found" + + +def test_demo_inventory_import_is_idempotent_and_analyst_cannot_commit(client, analyst, approver): + csv_response = client.get("/api/workspace/demo-csv/inventory", headers=analyst) + assert csv_response.status_code == 200 + text = csv_response.text + assert "TRAVEL-BAG-01" in text or "THERMO-02" in text + denied = client.post( + "/api/data/inventory/commit?filename=inventory.csv", + content=text, + headers={**analyst, "Content-Type": "text/csv"}, + ) + assert denied.status_code == 403 + ads = client.get("/api/workspace/demo-csv/ads", headers=approver) + assert ads.status_code == 409 + assert ads.json()["error"]["code"] == "demo_ads_conflicts_with_ledger" + committed = client.post( + "/api/data/inventory/commit?filename=inventory.csv", + content=text, + headers={**approver, "Content-Type": "text/csv"}, + ) + assert committed.status_code == 200, committed.text + assert committed.json()["status"] == "committed" + again = client.post( + "/api/data/inventory/commit?filename=inventory.csv", + content=text, + headers={**approver, "Content-Type": "text/csv"}, + ) + assert again.status_code == 200, again.text + assert again.json()["status"] == "noop" + overview = client.get("/api/workspace/overview", headers=analyst).json() + assert overview["inventory"]["low"] >= 1 + assert overview["inventory"]["missing"] is False + + +def test_replenishment_excludes_overstock_and_execution_is_idempotent(client, analyst, approver): + text = client.get("/api/workspace/demo-csv/inventory", headers=approver).text + imported = client.post( + "/api/data/inventory/commit?filename=inventory.csv", + content=text, headers={**approver, "Content-Type": "text/csv"}, + ) + assert imported.status_code == 200, imported.text + created = client.post("/api/proposals/replenishment", headers=analyst, json={}) + assert created.status_code == 200, created.text + body = created.json() + assert body["replayed"] is False + assert body["action"]["type"] == "simulate_replenishment" + assert body["action"]["simulation"] is True + skus = {line["sku"] for line in body["body"]["proposal"]["lines"]} + assert skus == {"THERMO-02"} + assert all(line["reorder_quantity"] > 0 for line in body["body"]["proposal"]["lines"]) + replay = client.post("/api/proposals/replenishment", headers=analyst, json={}) + assert replay.status_code == 200 + assert replay.json()["replayed"] is True + assert replay.json()["id"] == body["id"] + forbidden = client.post( + f"/api/recommendations/{body['id']}/approve", + headers={**analyst, "X-Role": "approver"}, + json={"reason": "分析师不能审批"}, + ) + assert forbidden.status_code == 403 + approved = client.post( + f"/api/recommendations/{body['id']}/approve", + headers=approver, json={"reason": "同意模拟补货"}, + ) + assert approved.status_code == 200, approved.text + headers = {**approver, "Idempotency-Key": "replenish-once"} + first = client.post(f"/api/recommendations/{body['id']}/execute", headers=headers) + assert first.status_code == 200, first.text + assert first.json()["simulation"] is True + assert first.json()["replayed"] is False + assert first.json()["result"]["external_calls"] == 0 + second = client.post(f"/api/recommendations/{body['id']}/execute", headers=headers) + assert second.status_code == 200, second.text + assert second.json()["replayed"] is True + assert second.json()["execution_id"] == first.json()["execution_id"] + with client.app.state.factory() as session: + executions = session.scalars(select(Execution).where(Execution.recommendation_id == body["id"])).all() + assert len(executions) == 1 + + +def test_margin_redline_blocks_approve_and_forced_execute(client, analyst, approver): + invalid = client.post("/api/proposals/price", headers=analyst, json={ + "store_id": "us-store", "sku": "TRAVEL-BAG-01", "proposed_price_cents": 0, + }) + assert invalid.status_code == 422 + missing = client.post("/api/proposals/price", headers=analyst, json={ + "store_id": "us-store", "sku": "NO-SUCH", "proposed_price_cents": 100, + }) + assert missing.status_code == 404 + created = client.post("/api/proposals/price", headers=analyst, json={ + "store_id": "us-store", "sku": "TRAVEL-BAG-01", "proposed_price_cents": 100, + }) + assert created.status_code == 200, created.text + body = created.json() + assert body["margin_check"]["ok"] is False + assert body["action"]["margin_ok"] is False + assert body["action"]["margin_pct"] < 28 + blocked = client.post( + f"/api/recommendations/{body['id']}/approve", + headers=approver, json={"reason": "试图越过红线"}, + ) + assert blocked.status_code == 409 + assert blocked.json()["error"]["code"] == "margin_redline" + with client.app.state.factory.begin() as session: + row = session.get(Recommendation, body["id"]) + row.status = "approved" + forced = client.post( + f"/api/recommendations/{body['id']}/execute", + headers={**approver, "Idempotency-Key": "price-forced"}, + ) + assert forced.status_code == 409 + assert forced.json()["error"]["code"] == "margin_redline" + with client.app.state.factory() as session: + assert session.scalar(select(Execution).where(Execution.recommendation_id == body["id"])) is None + assert session.get(Recommendation, body["id"]).status == "approved" + + +def test_passing_price_review_does_not_change_price(client, analyst, approver): + created = client.post("/api/proposals/price", headers=approver, json={ + "store_id": "us-store", "sku": "TRAVEL-BAG-01", "proposed_price_cents": 20000, + }) + assert created.status_code == 200, created.text + body = created.json() + assert body["margin_check"]["ok"] is True + approved = client.post( + f"/api/recommendations/{body['id']}/approve", + headers=approver, json={"reason": "毛利通过,仅模拟"}, + ) + assert approved.status_code == 200, approved.text + executed = client.post( + f"/api/recommendations/{body['id']}/execute", + headers={**approver, "Idempotency-Key": "price-ok"}, + ) + assert executed.status_code == 200, executed.text + assert executed.json()["result"]["external_calls"] == 0 + assert "售价未改变" in executed.json()["result"]["message"] + + +def test_budget_proposal_then_stale_ledger_blocks_execution(client, analyst, approver): + created = client.post("/api/proposals/budget", headers=analyst, json={}) + assert created.status_code == 200, created.text + body = created.json() + assert body["action"]["type"] == "adjust_ad_budget" + assert body["action"]["simulation"] is True + assert body["action"]["proposed_daily_budget"] <= body["action"]["baseline_daily_budget"] + approved = client.post( + f"/api/recommendations/{body['id']}/approve", + headers=approver, json={"reason": "同意预算模拟"}, + ) + assert approved.status_code == 200, approved.text + with client.app.state.factory.begin() as session: + order = session.scalar(select(Order).where(Order.tenant_id == "demo").limit(1)) + order.sales += 1 + executed = client.post( + f"/api/recommendations/{body['id']}/execute", + headers={**approver, "Idempotency-Key": "budget-stale"}, + ) + assert executed.status_code == 409 + assert executed.json()["error"]["code"] == "approval_stale" + + +def test_offline_eval_is_computed_and_access_hides_secrets(client, analyst, approver): + empty = client.get("/api/evals", headers=analyst) + assert empty.status_code == 200 + assert empty.json()["items"] == [] + ran = client.post("/api/evals/offline", headers=analyst) + assert ran.status_code == 200, ran.text + report = ran.json() + assert report["llm_calls"] == 0 + assert report["external_calls"] == 0 + assert report["total"] == len(report["cases"]) + assert report["passed"] + report["failed"] == report["total"] + assert any(case["id"] == "store_sum" and case["ok"] for case in report["cases"]) + listed = client.get("/api/evals", headers=analyst).json() + assert len(listed["items"]) == 1 + access = client.get("/api/workspace/access", headers=analyst).json() + assert access["actor"]["role"] == "analyst" + assert "api_key" not in str(access).lower() + planned = [row for row in access["rows"] if row["implemented"] is False] + assert planned and all(not any(row["cells"]) for row in planned) + analyst_row = next(row for row in access["rows"] if row["role"] == "analyst") + assert analyst_row["cells"][4] is False + approver_access = client.get("/api/workspace/access", headers=approver).json() + assert approver_access["actor"]["role"] == "approver" + assert next(row for row in approver_access["integrations"] if row["name"] == "Langfuse / 外部追踪")["state"] == "not_integrated" diff --git a/docs/CONTRACT.md b/docs/CONTRACT.md index 20e10e5..08b4645 100644 --- a/docs/CONTRACT.md +++ b/docs/CONTRACT.md @@ -151,6 +151,14 @@ Provider 外层由 `CircuitBreakerProvider` 计量并保护:连续可重试错 工具统一返回 `{ok,data,error}`,Pydantic 校验输入与输出;权限在 Tool Registry 与业务处理器双层验证。当前注册 9 个工具;`get_profit_analysis`、`get_sku_breakdown` 与 `search_knowledge` 是面向模型的原生只读工具。前两者输入只有 `MetricsInput`(period/store_id),由服务端用可信账本调用既有 `fetch_metrics`/`build_report`/`analyze_drivers` 计算,模型不能提交 `RawMetrics` 或完整报告;`search_knowledge` 只接受 `{query,top_k}`,无 period 范围要求,返回可引用的 chunk_id。每个工具在 `/api/tools` 声明 `policy`:`safe`(只读、纯计算或仅写本系统提案)、`ask`(必须经人工审批后执行的模拟动作)、`deny`(外部系统副作用,注册表直接拒绝,当前未注册)。`ask` 工具由审批状态机与 approver 角色双重约束。模型可见工具另受 `LLM_TOOL_ALLOWLIST`、`effect`、`policy` 和角色四重限制;`create_recommendation` 虽为 `safe`,但 `effect=database_write`,不会暴露给模型。工具参数失败为 invalid_tool_input,执行失败保留代码和消息。 +## 工作台九视图(不新增控制面) + +`GET /api/workspace/overview` 按当前租户账本返回总览、分店贡献和异常。分店销售额、净利润必须加总等于未筛选店铺的总览;`stores_reconciled=false` 表示对账失败。库存数量只来自已导入的 `source_records(kind=inventory)`,没有快照时 `missing=true`,不得填原型里的虚构 SKU 数。`GET /api/workspace/campaigns` 只汇总广告来源行;种子账本的每日广告账单不会被改写成计划 ROAS。 + +`POST /api/proposals/replenishment|budget|price` 在现有 `analyses` / `recommendations` 上创建 `pending_approval` 提案,幂等键绑定账本指纹与提案内容。补货只纳入风险为 CRITICAL/HIGH/MEDIUM 且补货量大于 0 的 SKU。预算提案仅在广告花费是最大负向贡献时生成 `adjust_ad_budget`,下调比例仍受 `SimulationAction.adjustment_pct` 1–30 约束。调价提案用订单合计计算成交毛利率,低于 28% 时 `action.margin_ok=false`。`decide(approve)` 与 `execute_once` 在抢占状态前拒绝该标志,错误码 `margin_redline`;驳回仍允许。所有新动作 `simulation=true`,模拟结果 `external_calls=0`。 + +`GET /api/workspace/demo-csv/orders|inventory` 按当前租户主数据和账本最后业务日生成可重复导入的 CSV。`ads` 返回 409 `demo_ads_conflicts_with_ledger`,因为已有非导入产生的每日广告行时,活动花费不能再叠加。`GET /api/workspace/access` 返回服务端角色矩阵;未实现角色 `implemented=false` 且权限全为 false。响应不含密钥。`POST /api/evals/offline` 当场重算利润桥、分店加总和毛利公式并写入 `eval.completed` 审计;`llm_calls` 恒为 0。没有评测记录时列表为空。 + ## 验收 pytest 覆盖利润边界、环比、归因加总、缺失数据、LangGraph 路径与失败、Schema、身份伪造、审批冲突、并发幂等、审计过滤、工具策略、UTC 时间戳与 Seed 保留历史。LLM 测试覆盖 Provider 成功/重试/鉴权/超时/非法 JSON/空响应、环境变量读取、结构化 Schema、证据引用校验、无 Key 降级、调用失败降级、Schema 无效降级、`fail` 策略以及 LLM 成功后的审批与幂等执行;原生 Function Calling 测试覆盖请求携带 `tools`/`tool_choice`、`tool_calls` 解析、多轮工具调用、禁止写工具/未知工具/非法参数/越界范围、轮次/次数/重复/预算上限、Provider 超时与工具异常降级、结果截断和工作流轨迹持久化。全部使用 MockTransport/FakeProvider,不消耗真实 Token;原生 Function Calling 另执行了 3 次真实 `deepseek-flash` 脚本运行,第 3 次完整成功(2 个只读工具调用、`final_answer`、`all_references_valid=true`),第 1 次网络错误降级,见 `docs/LLM_LIVE_CHECK.md`。独立 JSON 样本验证业务结论。Vitest + RTL 覆盖启动、轮询、审批、动作预览、执行、审计过滤、API 错误、LLM 成功/降级面板,以及原生轨迹的正常轮次、工具参数摘要、逐轮 token、失败调用错误码和单次 JSON 路径说明;生产构建和实际 HTTP + 浏览器演示闭环。Phase 2D 原生评测测试覆盖 fixture 到临时账本的可复现性、正常多轮、多余工具、未知/写/审批工具、非法参数、越界范围、重复调用、轮次上限、工具执行失败、非法最终 JSON、非法证据、数据不完整跳过、真实入口授权/预算/未配置检查,以及 CLI 失败退出码;全部使用 `FakeToolProvider`,不消耗真实 Token。PostgreSQL 已在本机 Docker Desktop 完成容器验收;其他环境若无法运行 Docker,需明确记录验证缺口。真实 DeepSeek 单次 JSON 调用已通过 `scripts/llm_check.py` 完成一次:`deepseek-flash`、15467.974 ms、4801 tokens、`all_references_valid=true`,详见 `docs/LLM_LIVE_CHECK.md`。知识库测试覆盖 Seed 幂等与不删用户文档、相关/无关查询、`no_answer` 清空 hits、approver 创建/停用、analyst 403、重复正文幂等、引用子集校验、提示词隔离、Markdown 切分边界、OpenAI 兼容 embedding 排序/归一化与失败映射。离线 RAG 评测 `backend/evals/rag.py` 在 6 篇文档、6 个可回答与 2 个不可回答查询上得到 hit@1 83.33%、hit@3 100%、no-answer 100%、citation validity 100%,网络调用 0 次;这是合成知识库上的检索门禁,不是通用语义准确率。多租户幂等回归覆盖 Analysis 与 Execution 的跨租户同键、105 字符租户前缀键、同租户重复键拒绝;迁移测试用真实的前租户 schema(无 `tenants`/`users` 表、无 `tenant_id`、无任务字段、知识库为全局部分唯一索引)构造 SQLite 与 PostgreSQL 库,按官方路径 `stamp 0001_baseline → upgrade head` 原地升级:Analysis/Recommendation/Execution/Audit 行数与外键关系保留,列宽 200、复合唯一约束与租约字段到位,跨租户同键可用、同租户重复键拒绝,重复 upgrade 为 no-op;SQLite 迁移期间关闭外键强制并在结束后通过 `PRAGMA foreign_key_check`,重复活跃文档会保留最新一行并软删除其余行;含跨租户同键的库执行 downgrade 会因唯一约束失败并保留原行;手工重试覆盖 running/completed 不被覆盖与并发重试只成功一次;恢复测试覆盖 `run_analysis` 写入 failed 后、`finalize_job` 之前退出的行按重试/死信规则恢复。 diff --git a/frontend/e2e/acceptance.spec.ts b/frontend/e2e/acceptance.spec.ts index 99f19a4..42ede5f 100644 --- a/frontend/e2e/acceptance.spec.ts +++ b/frontend/e2e/acceptance.spec.ts @@ -108,7 +108,7 @@ test('Agent 运维:角色限制、真实聚合与 Trace 跳转', async ({ page await page.goto('/') await expect(page.getByText('销售在增长,利润却没有跟上。')).toBeVisible() await page.getByLabel('演示身份').selectOption('demo-approver') - await page.getByRole('button', { name: /Agent 运维/ }).click() + await page.getByRole('button', { name: /运行与评测/ }).click() await expect(page.getByRole('heading', { name: '任务队列' })).toBeVisible() await expect(page.getByText('最近失败任务')).toBeVisible() // Two Playwright workers seed a failed analysis each; match this worker's @@ -125,7 +125,7 @@ test('失败状态展示与手动重试(真实 Worker)', async ({ page }) => page.on('pageerror', error => errors.push(error.message)) await page.goto('/') await expect(page.getByText('销售在增长,利润却没有跟上。')).toBeVisible() - await page.getByRole('button', { name: /Agent 工作台/ }).click() + await page.getByRole('button', { name: /经营调查/ }).click() // Another spec may have produced a newer analysis in the shared database; // select the seeded failed one explicitly instead of relying on ordering. await page.getByLabel('历史分析').selectOption(fixtures.failed_analysis_id) @@ -152,7 +152,7 @@ test('知识库页面:新增、检索与停用(真实 API)', async ({ page await page.goto('/') await expect(page.getByText('销售在增长,利润却没有跟上。')).toBeVisible() await page.getByLabel('演示身份').selectOption('demo-approver') - await page.getByRole('button', { name: /运营知识库/ }).click() + await page.getByRole('button', { name: /知识与数据/ }).click() await page.getByLabel('知识标题').fill(title) await page.getByLabel('知识来源').fill(`e2e://acceptance/${marker}`) diff --git a/frontend/e2e/intelligence_screenshots.spec.ts b/frontend/e2e/intelligence_screenshots.spec.ts index afabf1c..40d3862 100644 --- a/frontend/e2e/intelligence_screenshots.spec.ts +++ b/frontend/e2e/intelligence_screenshots.spec.ts @@ -12,8 +12,8 @@ test('Capture multi-store intelligence screenshots', async ({ page }) => { await expect(page.getByText('销售在增长,利润却没有跟上。')).toBeVisible() // 2. Go to data import page - await page.getByRole('button', { name: '数据导入' }).click() - await expect(page.getByRole('heading', { name: '数据导入', level: 1 })).toBeVisible() + await page.getByRole('button', { name: '知识与数据' }).click() + await expect(page.getByRole('heading', { name: '知识与数据', level: 1 })).toBeVisible() const ordersCsvPath = path.resolve('..', 'docs', 'examples', 'intelligence', 'orders.csv') const ordersContent = fs.readFileSync(ordersCsvPath, 'utf8') @@ -45,6 +45,7 @@ test('Capture multi-store intelligence screenshots', async ({ page }) => { expect(inventoryResponse.ok(), await inventoryResponse.text()).toBeTruthy() // 3. Navigate to weekly intelligence page + await page.getByRole('button', { name: '库存建议' }).click() await page.getByRole('button', { name: '经营周报与库存' }).click() await expect(page.getByText('多店铺经营周报', { exact: true })).toBeVisible() diff --git a/frontend/e2e/profitops.spec.ts b/frontend/e2e/profitops.spec.ts index 37eb61f..ddf3027 100644 --- a/frontend/e2e/profitops.spec.ts +++ b/frontend/e2e/profitops.spec.ts @@ -25,8 +25,8 @@ test('真实 API:分析、越权拦截、审批、模拟执行、幂等与审 await page.screenshot({ path: '../docs/screenshots/approval.png' }) await page.getByRole('heading', { name: /模拟执行结果/ }).scrollIntoViewIfNeeded() await page.screenshot({ path: '../docs/screenshots/execution.png' }) - await page.getByRole('button', { name: '审计日志', exact: true }).click() - await expect(page.getByRole('table')).toBeVisible() + await page.getByRole('button', { name: '运行与评测', exact: true }).click() + await expect(page.getByRole('heading', { name: '审计日志' })).toBeVisible() const response = await page.request.get(`/api/audit-logs?object_id=${id}`, { headers: { Authorization: 'Bearer demo-approver' } }) const logs = await response.json() expect(logs.items.some((row: { action: string }) => row.action === 'execution.replayed')).toBe(true) @@ -81,7 +81,7 @@ test('Agent Trace:原生轮次、失败调用与移动端布局可见', async }) await page.goto('/') await expect(page.getByText('销售在增长,利润却没有跟上。')).toBeVisible() - await page.getByRole('button', { name: /Agent 工作台/ }).click() + await page.getByRole('button', { name: /经营调查/ }).click() const trace = page.getByRole('region', { name: 'Agent 执行轨迹' }) await expect(trace).toBeVisible() await expect(trace.getByText('ROUND 1')).toBeVisible() diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx index 61298a5..7918137 100644 --- a/frontend/src/App.test.tsx +++ b/frontend/src/App.test.tsx @@ -164,7 +164,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /审批与执行/ })) + await user.click(screen.getByRole('button', { name: /审批中心/ })) await user.selectOptions(screen.getByLabelText('演示身份'), 'demo-approver') const reason = await screen.findByLabelText('审批意见') await user.clear(reason); await user.type(reason, '等待补充广告转化证据') @@ -178,11 +178,11 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /审批与执行/ })) + await user.click(screen.getByRole('button', { name: /审批中心/ })) expect(await screen.findByRole('heading', { name: /待执行的模拟动作/ })).toBeVisible() expect(screen.getAllByText('US$10.00').length).toBeGreaterThan(0) expect(screen.getAllByText('US$8.50').length).toBeGreaterThan(0) - await user.click(screen.getByRole('button', { name: /审计日志/ })) + await user.click(screen.getByRole('button', { name: /运行与评测/ })) await user.type(screen.getByLabelText('按请求 ID 过滤'), 'req-123') await user.click(screen.getByRole('button', { name: '筛选' })) await waitFor(() => expect(vi.mocked(fetch).mock.calls.some(([path]) => String(path).includes('request_id=req-123'))).toBe(true)) @@ -194,7 +194,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) expect((await screen.findAllByText('真实调用成功')).length).toBeGreaterThan(0) expect(screen.getAllByText('321.5 ms').length).toBeGreaterThan(0) expect(screen.getAllByText('输入 120 / 输出 80').length).toBeGreaterThan(0) @@ -208,7 +208,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) expect((await screen.findAllByText('已降级为确定性规则')).length).toBeGreaterThan(0) expect(screen.getAllByText(/未配置 API Key/).length).toBeGreaterThan(0) expect(screen.getAllByText(/不是 LLM 输出/).length).toBeGreaterThan(0) @@ -220,7 +220,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) expect(await screen.findByRole('heading', { name: /Agent 执行轨迹/ })).toBeVisible() const trace = screen.getByRole('region', { name: 'Agent 执行轨迹' }) expect(within(trace).getByText('ROUND 1')).toBeVisible() @@ -274,7 +274,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) const trace = await screen.findByRole('region', { name: 'Agent 执行轨迹' }) expect(within(trace).getByText('2026-10-01 → 2026-10-30 · 店铺 us-store · 4 个其他字段')).toBeVisible() expect(within(trace).getByText('4 个其他字段')).toBeVisible() @@ -294,7 +294,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) expect(await screen.findByRole('heading', { name: /Agent 执行轨迹/ })).toBeVisible() const trace = screen.getByRole('region', { name: 'Agent 执行轨迹' }) expect(within(trace).getAllByText('✓ 成功').length).toBe(1) @@ -322,7 +322,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /运营知识库/ })) + await user.click(screen.getByRole('button', { name: /知识与数据/ })) expect(await screen.findByRole('heading', { name: /运营知识库/, level: 2 })).toBeVisible() expect((await screen.findAllByText('广告预算调整与审批规则')).length).toBeGreaterThan(0) await user.type(screen.getByLabelText('知识库检索'), '广告预算下调审批') @@ -340,7 +340,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /运营知识库/ })) + await user.click(screen.getByRole('button', { name: /知识与数据/ })) await user.selectOptions(screen.getByLabelText('演示身份'), 'demo-approver') await user.type(screen.getByLabelText('知识标题'), '退款升级规则') await user.type(screen.getByLabelText('知识正文'), '# 退款升级\n\n退款率连续 7 天高于基线时升级为运营专项。') @@ -354,7 +354,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /审批与执行/ })) + await user.click(screen.getByRole('button', { name: /审批中心/ })) expect(await screen.findByRole('heading', { name: /知识库参考/ })).toBeVisible() expect(screen.getByText('✓ LLM 已引用')).toBeVisible() expect(screen.getAllByText('chunk-ad-1').length).toBeGreaterThan(0) @@ -365,7 +365,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 工作台/ })) + await user.click(screen.getByRole('button', { name: /经营调查/ })) expect(await screen.findByText('知识引用')).toBeVisible() expect(screen.getAllByText('chunk-ad-1').length).toBeGreaterThan(0) }) @@ -375,7 +375,7 @@ describe('ProfitOps workspace', () => { const user = userEvent.setup() render() await screen.findByText('销售在增长,利润却没有跟上。') - await user.click(screen.getByRole('button', { name: /Agent 运维/ })) + await user.click(screen.getByRole('button', { name: /运行与评测/ })) expect(await screen.findByText('需要审批负责人权限')).toBeVisible() await user.selectOptions(screen.getByLabelText('演示身份'), 'demo-approver') @@ -400,7 +400,7 @@ describe('ProfitOps workspace', () => { render() await screen.findByText('销售在增长,利润却没有跟上。') await user.selectOptions(screen.getByLabelText('演示身份'), 'demo-approver') - await user.click(screen.getByRole('button', { name: /Agent 运维/ })) + await user.click(screen.getByRole('button', { name: /运行与评测/ })) expect(await screen.findByText('24H')).toBeVisible() await user.selectOptions(screen.getByLabelText('运维统计窗口'), '168') diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6ff4254..1480d52 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,7 +1,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react' import { Activity, ArrowDownRight, ArrowRight, ArrowUpRight, BarChart3, BookOpen, Check, CheckCircle2, CircleDollarSign, Database, Fingerprint, LoaderCircle, Megaphone, Play, RefreshCw, Search, ShieldCheck, Sparkles, Terminal, TriangleAlert, X, type LucideIcon } from 'lucide-react' import { api, ApiError } from './api' -import type { Analysis, Audit, Demo, Execution, Identity, JobStatus, KnowledgeContext, KnowledgeDocument, KnowledgeSearch, LLMConfig, LLMRun, Metrics, OpsSummary, Recommendation, Scope } from './types' +import type { AccessView, Analysis, Audit, CampaignReport, Demo, EvalList, EvalReport, Execution, Identity, InventoryReport, JobStatus, KnowledgeContext, KnowledgeDocument, KnowledgeSearch, LLMConfig, LLMRun, Metrics, OpsSummary, Recommendation, Scope, WorkspaceOverview } from './types' import { dateTime, llmReasonLabels, llmStatusLabels, money, percent, signedMoney, statusLabels, terminationLabels } from './format' import { pages, type Page } from './navigation' import { cn } from './lib/utils' @@ -9,6 +9,7 @@ import { AppSidebar } from './components/layout/app-sidebar' import { AppHeader } from './components/layout/app-header' import { IntelligencePage } from './components/intelligence-page' import { ImportPage } from './components/imports/import-page' +import { AdsBoard, AssistantsView, EvalPanel, InventoryBoard, PriceCheckForm, SettingsView } from './components/workspace-views' import { Badge } from './components/ui/badge' import { Button } from './components/ui/button' import { Card, CardContent, CardDescription, CardFooter, CardHeader } from './components/ui/card' @@ -98,6 +99,13 @@ export default function App() { const [busy, setBusy] = useState('') const [error, setError] = useState('') const [notice, setNotice] = useState('') + const [workspace, setWorkspace] = useState(null) + const [inventoryReport, setInventoryReport] = useState(null) + const [campaigns, setCampaigns] = useState(null) + const [access, setAccess] = useState(null) + const [evalReport, setEvalReport] = useState(null) + const [evalHistory, setEvalHistory] = useState(null) + const [showWeekly, setShowWeekly] = useState(false) const [execution, setExecution] = useState(null) const [reason, setReason] = useState('已复核证据,批准受控模拟') const [theme, setTheme] = useState<'light' | 'dark'>(() => { @@ -143,6 +151,10 @@ export default function App() { api.knowledgeDocuments(identity.token), ]) if (sequence !== loadSequence.current) return + let board: WorkspaceOverview | null = null + try { if (demo.data_range) board = await api.workspace(identity.token, demo, scope) } catch { board = null } + if (sequence !== loadSequence.current) return + setWorkspace(board) setMetrics(summary); setAnalyses(history.items); setRecommendations(items.items); setAudits(logs.items) setDocuments(knowledgeDocs.items) setAnalysis(current => history.items.find(item => item.id === current?.id) ?? history.items[0] ?? null) @@ -168,8 +180,32 @@ export default function App() { useEffect(() => { void refresh() }, [refresh]) useEffect(() => { - if (page === 'ops' && isApprover) void loadOps() + if (page === 'runs' && isApprover) void loadOps() }, [page, isApprover, loadOps]) + useEffect(() => { + if (!identity || !demo?.data_range || page !== 'inventory') return + let active = true + api.inventory(identity.token, demo.data_range.end_date, scope.storeId).then(value => { if (active) setInventoryReport(value) }).catch(() => { if (active) setInventoryReport(null) }) + return () => { active = false } + }, [identity, demo, page, scope.storeId]) + useEffect(() => { + if (!identity || !demo?.data_range || page !== 'ads') return + let active = true + api.campaigns(identity.token, demo, scope).then(value => { if (active) setCampaigns(value) }).catch(() => { if (active) setCampaigns(null) }) + return () => { active = false } + }, [identity, demo, page, scope]) + useEffect(() => { + if (!identity || page !== 'settings') return + let active = true + api.access(identity.token).then(value => { if (active) setAccess(value) }).catch(() => { if (active) setAccess(null) }) + return () => { active = false } + }, [identity, page]) + useEffect(() => { + if (!identity || page !== 'runs') return + let active = true + api.evals(identity.token).then(value => { if (active) setEvalHistory(value) }).catch(() => { if (active) setEvalHistory(null) }) + return () => { active = false } + }, [identity, page]) useEffect(() => { document.documentElement.classList.toggle('dark', theme === 'dark') localStorage.setItem('profitops-theme', theme) @@ -206,7 +242,7 @@ export default function App() { if (!demo || !identity) return void action('analysis', async () => { const result = await api.start(identity.token, demo, scope) - setAnalysis(result); setPage('agent'); setNotice(result.replayed ? '该分析请求已存在,返回原分析记录' : '分析已启动,正在通过工具读取经营数据') + setAnalysis(result); setPage('investigate'); setNotice(result.replayed ? '该分析请求已存在,返回原分析记录' : '分析已启动,正在通过工具读取经营数据') }) } function retryAnalysis() { @@ -223,10 +259,26 @@ export default function App() { const value = await api.analysis(identity.token, id) setAnalysis(value) if (value.recommendation_id) setSelectedId(value.recommendation_id) - setPage('agent') + setPage('investigate') setNotice(`已打开分析 ${id.slice(0, 8)} 的执行轨迹。`) }) } + function loadDemo(kind: 'orders' | 'inventory' | 'ads') { + if (!identity) return + void action(`demo-${kind}`, async () => { + const text = await api.demoCsv(identity.token, kind) + if (kind === 'ads') return + const preview = await api.previewImport(identity.token, kind, text, `workspace-${kind}.csv`) + if (!isApprover) { + setNotice(`预览 ${preview.accepted_rows} 行。分析师不能提交,请切换审批负责人。`) + return + } + const committed = await api.commitImport(identity.token, kind, text, `workspace-${kind}.csv`) + setDemo(await api.demo()) + setNotice(committed.status === 'noop' ? '这份演示 CSV 已在账本中,未重复写入。' : `已提交 ${committed.accepted_rows} 行,批次和来源行已保存。`) + await refresh() + }) + } function seed() { if (!identity) return void action('seed', async () => { @@ -298,7 +350,9 @@ export default function App() { const activePage = pages.find(item => item.id === page)! const renderButton = (label = '启动 Profit Agent') => - return
+ return
+
+
{activePage.detail}

- - {!['audit', 'knowledge', 'ops', 'imports'].includes(page) && renderButton()} + {['overview', 'investigate'].includes(page) && renderButton()}
@@ -350,7 +404,7 @@ export default function App() {
} - {(page === 'overview' || page === 'agent') &&
+ {['overview', 'investigate', 'inventory', 'ads'].includes(page) &&
} - {page === 'agent' &&
+ {page === 'investigate' &&
} - {page === 'ops' &&
+ {page === 'runs' &&
{!isApprover ? : <>
} - {page === 'weekly' && identity && } + {page === 'inventory' &&
+
+ +
+ { + if (!identity || !demo?.data_range) return + void action('replenish', async () => { + const result = await api.proposeReplenishment(identity.token, demo.data_range!.end_date, scope.storeId) + setSelectedId(result.id) + setPage('approvals') + setNotice(result.replayed ? '相同账本下的补货提案已存在。' : '补货提案已写入审批中心,尚未执行。') + await refresh() + }) + }} /> + {showWeekly && identity && } +
} - {page === 'imports' && identity && { setPage(next); setError('') }} onInvestigate={startAnalysis} />} + {page === 'ads' && { + if (!identity || !demo) return + void action('budget', async () => { + const result = await api.proposeBudget(identity.token, demo, scope) + setSelectedId(result.id) + setPage('approvals') + setNotice(result.replayed ? '相同账本下的预算提案已存在。' : '预算提案已进入审批中心。真实广告预算未改变。') + await refresh() + }) + }} />} + {page === 'settings' && } + + {page === 'knowledge' && identity && +

演示数据

+

订单和库存 CSV 按当前租户的店铺与 SKU 生成,预览和提交都走后端。广告 CSV 会返回拒绝,避免把活动花费再加进已有每日广告账单。

+
+ + + +
+
} + {page === 'knowledge' && identity && { void refresh() }} />} - {page === 'approvals' &&
+ {page === 'approvals' &&
+ { + if (!identity) return + void action('price', async () => { + const result = await api.proposePrice(identity.token, storeId, sku, cents) + setSelectedId(result.id) + setNotice(result.margin_check?.text ?? '调价校验已写入审批中心。') + await refresh() + }) + }} /> +
{recommendations.length}} /> {!recommendations.length ?
: recommendations.map(item =>
@@ -734,7 +856,7 @@ export default function App() {
- +
} {selected.approval_reason &&

审批意见:{selected.approval_reason}

} @@ -758,7 +880,7 @@ export default function App() { {(selected.execution || execution?.recommendation_id === selected.id) && } : } -
} +
} {page === 'knowledge' &&
@@ -795,8 +917,17 @@ export default function App() {
} - {page === 'audit' && - 请求级追踪} /> + {page === 'runs' && { + if (!identity) return + void action('eval', async () => { + const result = await api.runEval(identity.token) + setEvalReport(result) + setEvalHistory(await api.evals(identity.token)) + setNotice(`离线评测已写入审计:通过 ${result.passed} / ${result.total},模型调用 ${result.llm_calls}。`) + }) + }} />} + {page === 'runs' && + 请求级追踪} />
{ event.preventDefault(); setAuditFilter(auditQuery.trim()) }}> @@ -823,6 +954,7 @@ export default function App() { 所有执行均为模拟 · {demo?.data_range ? '数据已接入' : '等待初始化'}
+
} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 32cb07d..c5626f2 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -1,4 +1,4 @@ -import type { Analysis, Audit, Demo, Execution, ImportAdapter, ImportSummary, KnowledgeDocument, KnowledgeDocumentInput, KnowledgeSearch, Metrics, OpsSummary, Recommendation, Scope } from './types' +import type { AccessView, Analysis, Audit, CampaignReport, Demo, EvalList, EvalReport, Execution, ImportAdapter, ImportSummary, InventoryReport, KnowledgeDocument, KnowledgeDocumentInput, KnowledgeSearch, Metrics, OpsSummary, Recommendation, Scope, WorkspaceOverview } from './types' export class ApiError extends Error { constructor(message: string, public code: string, public requestId: string, public status: number, public payload?: unknown) { super(message) } @@ -64,4 +64,24 @@ export const api = { previewImport: (token: string, kind: 'orders' | 'operations' | 'ads' | 'inventory', text: string, filename: string, mapping = '', adapter = '') => csvRequest(kind === 'operations' ? `/api/imports/${kind}/preview` : `/api/data/${kind}/preview`, token, text, filename, mapping, adapter), commitImport: (token: string, kind: 'orders' | 'operations' | 'ads' | 'inventory', text: string, filename: string, mapping = '', adapter = '') => csvRequest(kind === 'operations' ? `/api/imports/${kind}` : `/api/data/${kind}/commit`, token, text, filename, mapping, adapter), importTemplateUrl: (kind: 'orders' | 'operations' | 'ads' | 'inventory') => `/api/data/template/${kind}`, + workspace: (token: string, demo: Demo, scope: Scope) => request(`/api/workspace/overview?${new URLSearchParams(scopeBody(demo, scope))}`, token), + campaigns: (token: string, demo: Demo, scope: Scope) => request(`/api/workspace/campaigns?${new URLSearchParams(scopeBody(demo, scope))}`, token), + inventory: (token: string, asOf: string, storeId = '') => request(`/api/inventory?as_of=${asOf}${storeId ? `&store_id=${encodeURIComponent(storeId)}` : ''}`, token), + access: (token: string) => request('/api/workspace/access', token), + evals: (token: string) => request('/api/evals', token), + runEval: (token: string) => request('/api/evals/offline', token, { method: 'POST' }), + proposeReplenishment: (token: string, asOf: string, storeId = '') => request('/api/proposals/replenishment', token, { method: 'POST', body: JSON.stringify({ as_of: asOf, ...(storeId ? { store_id: storeId } : {}) }) }), + proposeBudget: (token: string, demo: Demo, scope: Scope) => request('/api/proposals/budget', token, { method: 'POST', body: JSON.stringify(scopeBody(demo, scope)) }), + proposePrice: (token: string, storeId: string, sku: string, proposedPriceCents: number) => request('/api/proposals/price', token, { method: 'POST', body: JSON.stringify({ store_id: storeId, sku, proposed_price_cents: proposedPriceCents }) }), + demoCsv: async (token: string, kind: 'orders' | 'inventory' | 'ads') => { + const headers = new Headers({ Authorization: `Bearer ${token}` }) + const response = await fetch(`/api/workspace/demo-csv/${kind}`, { headers }) + const text = await response.text() + if (!response.ok) { + let message = '演示 CSV 不可用' + try { message = JSON.parse(text)?.error?.message ?? message } catch { /* 文本错误 */ } + throw new ApiError(message, 'demo_csv_unavailable', response.headers.get('X-Request-ID') ?? '', response.status) + } + return text + }, } diff --git a/frontend/src/components/layout/app-sidebar.tsx b/frontend/src/components/layout/app-sidebar.tsx index 161fde6..d87f3dd 100644 --- a/frontend/src/components/layout/app-sidebar.tsx +++ b/frontend/src/components/layout/app-sidebar.tsx @@ -38,8 +38,8 @@ export function AppSidebar({ page, pending, collapsed, mobileOpen, demo, identit
- ProfitOps AI - 跨境增长团队 · 演示 + ProfitOps + 电商经营工作台
@@ -88,7 +88,7 @@ export function AppSidebar({ page, pending, collapsed, mobileOpen, demo, identit
{isApprover ? '审' : '析'}
{identity?.name ?? '连接中'} - {isApprover ? '审批负责人' : '经营分析师'} · 本地演示 + {isApprover ? '审批负责人' : '经营分析师'} · 演示租户
diff --git a/frontend/src/components/workspace-views.tsx b/frontend/src/components/workspace-views.tsx new file mode 100644 index 0000000..6fa30ff --- /dev/null +++ b/frontend/src/components/workspace-views.tsx @@ -0,0 +1,191 @@ +import type { FormEvent } from 'react' +import type { AccessView, CampaignReport, EvalList, EvalReport, InventoryReport } from '../types' +import { money } from '../format' +import { Badge } from './ui/badge' +import { Button } from './ui/button' +import { Card, CardContent } from './ui/card' +import { Input } from './ui/input' +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table' + +const cap = { own: '已有能力', part: '部分已有', plan: '规划中' } as const + +export function AssistantsView({ onOpen, onInvestigate }: { onOpen: (page: 'overview' | 'investigate' | 'inventory' | 'ads' | 'approvals') => void; onInvestigate: () => void }) { + const agents = [ + { id: 'ops', name: '经营分析助手', status: 'own' as const, desc: '利润拆解、异常归因和带证据的建议。走现有 LangGraph,未配置模型时明确降级。', tools: ['compute_profit', 'get_sku_breakdown', 'search_knowledge'], tasks: [ + { title: '销售上涨,利润为什么下降?', run: onInvestigate, enabled: true }, + { title: '查看分店贡献', run: () => onOpen('overview'), enabled: true }, + ]}, + { id: 'stock', name: '库存助手', status: 'part' as const, desc: '读取已导入的库存快照并生成补货提案。真实 ERP 未连接。', tools: ['list_inventory', 'draft_replenish'], tasks: [ + { title: '哪些 SKU 需要补货?', run: () => onOpen('inventory'), enabled: true }, + ]}, + { id: 'ads', name: '广告分析助手', status: 'part' as const, desc: '每日广告账单可生成预算模拟。活动级 ROAS 只有在不与账单冲突的广告 CSV 存在时才显示。', tools: ['ledger_ad_spend', 'draft_budget_change'], tasks: [ + { title: '查看花费并生成预算模拟', run: () => onOpen('ads'), enabled: true }, + ]}, + { id: 'product', name: '商品运营助手', status: 'plan' as const, desc: '跟价、主图和转化不在本仓库主链路。调价只做服务端毛利校验,不改价。', tools: ['(规划)转化漏斗'], tasks: [ + { title: '校验拟调价是否破红线', run: () => onOpen('approvals'), enabled: true }, + ]}, + { id: 'cs', name: '客服助手', status: 'plan' as const, desc: '退款归类和差评回复尚未实现,不能从这里发起任务。', tools: ['(规划)退款归因'], tasks: []}, + { id: 'finance', name: '财务助手', status: 'plan' as const, desc: '自动周报对账仍是规划。利润数字由确定性账本计算,不另起财务 Agent。', tools: ['(规划)费用对账'], tasks: []}, + ] + return
+

这里不是多 Agent 编排。已有能力会调用现有后端;标为规划中的助手不能启动,也不会假装已经完成。

+
+ {agents.map(agent => + +
+

{agent.name}

+ {cap[agent.status]} +
+

{agent.desc}

+
{agent.tools.map(tool => {tool})}
+ {agent.tasks.length ? agent.tasks.map(task =>
+ {task.title} + +
) :

任务入口已禁用。没有后台任务,也没有伪造的会话。

} +
+
)} +
+
+} + +export function InventoryBoard({ report, busy, onPropose }: { report: InventoryReport | null; busy: boolean; onPropose: () => void }) { + const rows = report?.items ?? [] + const suggested = rows.filter(row => (row.reorder_quantity ?? 0) > 0 && !['insufficient_data', 'no_demand'].includes(row.status) && ['CRITICAL', 'HIGH', 'MEDIUM'].includes(row.risk)) + return
+ +
+

库存一览

+

{report?.coverage_note ?? '导入库存 CSV 后,按账本时点计算可售天数和补货量。'}

+
+ {!rows.length ?

当前筛选下没有库存快照。可在「知识与数据」提交演示库存 CSV。

: + SKU在库可售天数风险建议补货 + {rows.map(row => + {row.sku}{row.store_id} + {row.on_hand} + {row.coverage_days ?? '—'} + {row.risk} + {row.reorder_quantity ?? '—'} + )} +
} +
+ + +

模拟补货提案

+

只纳入服务端算出的补货量。超储和数据不足不会进入提案,也不会向供应商下单。

+ {suggested.map(row =>
{row.sku} · {row.store_id} · {row.reorder_quantity} 件
)} + {!suggested.length &&

没有可建议补货的 SKU。

} + +
+
+
+} + +export function AdsBoard({ report, busy, onPropose }: { report: CampaignReport | null; busy: boolean; onPropose: () => void }) { + const items = report?.items ?? [] + return
+
+ 活动花费{items.length ? money(report?.spend ?? 0) : '账本可见'} + 归因销售额{items.length ? money(report?.attributed_sales ?? 0) : '—'} + 综合 ROAS{report?.roas ?? '—'} + 低于 {report?.threshold ?? 2.5}{report?.weak ?? 0} 条 +
+

{report?.note}

+
+ +

计划明细

+ {!items.length ?

没有活动级广告行。种子数据的广告费在每日经营记录中,页面不会编造 ROAS。预算模拟仍可按账本广告费生成。

: + 计划花费归因销售ROAS上期 ROAS + {items.map(row => + {row.campaign_name}{row.store_id} + {money(row.ad_spend)} + {money(row.attributed_sales)} + {row.roas ?? '—'} + {row.previous_roas ?? '—'} + )} +
} +
+ +

预算模拟

+

当广告花费是利润下降的最大负向贡献时,服务端按参考日预算下调最多 30%,并进入同一条审批流。不调用广告后台。

+ +
+
+
+} + +export function SettingsView({ access }: { access: AccessView | null }) { + if (!access) return

正在读取服务端权限…

+ return
+ +
+

角色与工具权限

+

当前身份 {access.actor.role} · 租户 {access.actor.tenant_id} · {access.note}

+
+
+ + 角色{access.columns.map(column => {column})} + {access.rows.map(row => + {row.label}{row.implemented ? '' : ' · 规划中'}{row.current ? ' · 当前' : ''} + {row.cells.map((allowed, index) => {row.implemented ? (allowed ? '允许' : '—') : '禁用'})} + )} +
+
+
+ +

集成实际状态

+
{access.integrations.map(item =>
+
{item.name}{item.state}
+

{item.detail}

+
)}
+

全部执行强制 simulation。本页不提供密钥、账号注册或外部系统开关。

+
+
+} + +export function EvalPanel({ report, history, busy, onRun }: { report: EvalReport | null; history: EvalList | null; busy: boolean; onRun: () => void }) { + const latest = report ?? history?.items[0]?.details ?? null + return +
+
+

可复现评测

+

{history?.note ?? '运行后才有结果。'}

+
+ +
+ {!latest ?

尚未运行。这里不会显示手写通过率。

:
+

通过 {latest.passed} / {latest.total} · 失败 {latest.failed} · 模型调用 {latest.llm_calls} · {latest.engine}

+

{latest.note}

+ + 编号场景结果说明 + {latest.cases.map(item => + {item.id}{item.scene} + {item.ok ? '通过' : '失败'}{item.detail} + )} +
+
} +
+} + +export function PriceCheckForm({ stores, busy, onSubmit }: { stores: { id: string; name: string }[]; busy: boolean; onSubmit: (storeId: string, sku: string, cents: number) => void }) { + function submit(event: FormEvent) { + event.preventDefault() + const data = new FormData(event.currentTarget) + const dollars = Number(data.get('price')) + if (!Number.isFinite(dollars) || dollars <= 0) return + onSubmit(String(data.get('store')), String(data.get('sku')).trim(), Math.round(dollars * 100)) + } + return + + + + + +} diff --git a/frontend/src/navigation.ts b/frontend/src/navigation.ts index bbc2b04..9eb5d60 100644 --- a/frontend/src/navigation.ts +++ b/frontend/src/navigation.ts @@ -1,27 +1,29 @@ -import { Activity, BookOpen, FileCheck2, FileUp, Fingerprint, LayoutDashboard, Sparkles, type LucideIcon } from 'lucide-react' +import { Activity, BookOpen, FileCheck2, Package, Search, Settings, Sparkles, LayoutDashboard, Megaphone, type LucideIcon } from 'lucide-react' -export type Page = 'overview' | 'weekly' | 'agent' | 'imports' | 'approvals' | 'knowledge' | 'audit' | 'ops' +export type Page = 'overview' | 'assistants' | 'investigate' | 'inventory' | 'ads' | 'knowledge' | 'approvals' | 'runs' | 'settings' export type NavItem = { id: Page label: string icon: LucideIcon detail: string + group: '经营' | '专项' | '治理' } export const pages: NavItem[] = [ - { id: 'overview', label: '经营总览', icon: LayoutDashboard, detail: '把增长,变成利润。' }, - { id: 'weekly', label: '经营周报与库存', icon: Activity, detail: '关联多店铺数据 让建议有据可查' }, - { id: 'agent', label: 'Agent 工作台', icon: Sparkles, detail: '从经营信号,到有据可依的行动。' }, - { id: 'imports', label: '数据导入', icon: FileUp, detail: '先校验 再入账 让每一分钱都能对上。' }, - { id: 'approvals', label: '审批与执行', icon: FileCheck2, detail: '每一步行动,都由你掌控。' }, - { id: 'knowledge', label: '运营知识库', icon: BookOpen, detail: '让建议有规则可依,让引用可追溯。' }, - { id: 'ops', label: 'Agent 运维', icon: Activity, detail: '任务、模型与成本的运行视图。' }, - { id: 'audit', label: '审计日志', icon: Fingerprint, detail: '让每一次决策都有迹可循。' }, + { id: 'overview', label: '经营总览', icon: LayoutDashboard, detail: '看多店营收、利润与待处理异常', group: '经营' }, + { id: 'assistants', label: '助手中心', icon: Sparkles, detail: '已有任务可运行;未实现的角色保持禁用', group: '经营' }, + { id: 'investigate', label: '经营调查', icon: Search, detail: '利润变化、证据、引用与真实轨迹', group: '经营' }, + { id: 'inventory', label: '库存建议', icon: Package, detail: 'SKU、库存与补货提案', group: '专项' }, + { id: 'ads', label: '广告分析', icon: Megaphone, detail: '账本广告费、活动 ROAS 与预算模拟', group: '专项' }, + { id: 'knowledge', label: '知识与数据', icon: BookOpen, detail: 'CSV 预览、映射、批次与规则检索', group: '专项' }, + { id: 'approvals', label: '审批中心', icon: FileCheck2, detail: '参数差异、证据、毛利红线与模拟执行', group: '治理' }, + { id: 'runs', label: '运行与评测', icon: Activity, detail: '真实运行、错误与可复现评测', group: '治理' }, + { id: 'settings', label: '设置与权限', icon: Settings, detail: '服务端角色与集成的实际状态', group: '治理' }, ] export const navGroups: { title: string; items: Page[] }[] = [ - { title: '工作空间', items: ['overview', 'weekly', 'agent'] }, - { title: '工作流', items: ['imports', 'approvals', 'knowledge'] }, - { title: '系统', items: ['ops', 'audit'] }, + { title: '经营', items: ['overview', 'assistants', 'investigate'] }, + { title: '专项', items: ['inventory', 'ads', 'knowledge'] }, + { title: '治理', items: ['approvals', 'runs', 'settings'] }, ] diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 866d597..eb54388 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -3,39 +3,65 @@ @custom-variant dark (&:is(.dark *)); :root { - --radius: 0.625rem; - --background: oklch(1 0 0); - --foreground: oklch(0.129 0.042 264.695); - --card: oklch(1 0 0); - --card-foreground: oklch(0.129 0.042 264.695); - --popover: oklch(1 0 0); - --popover-foreground: oklch(0.129 0.042 264.695); - --primary: oklch(0.208 0.042 265.755); - --primary-foreground: oklch(0.984 0.003 247.858); - --secondary: oklch(0.968 0.007 247.896); - --secondary-foreground: oklch(0.208 0.042 265.755); - --muted: oklch(0.968 0.007 247.896); - --muted-foreground: oklch(0.554 0.046 257.417); - --accent: oklch(0.968 0.007 247.896); - --accent-foreground: oklch(0.208 0.042 265.755); - --destructive: oklch(0.577 0.245 27.325); - --border: oklch(0.929 0.013 255.508); - --input: oklch(0.929 0.013 255.508); - --ring: oklch(0.704 0.04 256.788); - --chart-1: oklch(0.646 0.222 41.116); - --chart-2: oklch(0.6 0.118 184.704); - --chart-3: oklch(0.398 0.07 227.392); - --chart-4: oklch(0.828 0.189 84.429); - --chart-5: oklch(0.769 0.188 70.08); - - --sidebar: var(--background); - --sidebar-foreground: var(--foreground); - --sidebar-primary: var(--primary); - --sidebar-primary-foreground: var(--primary-foreground); - --sidebar-accent: var(--accent); - --sidebar-accent-foreground: var(--accent-foreground); - --sidebar-border: var(--border); - --sidebar-ring: var(--ring); + --radius: 0.75rem; + --background: #F3F0E8; + --foreground: #1A1E1B; + --card: #FFFEFA; + --card-foreground: #1A1E1B; + --popover: #FFFEFA; + --popover-foreground: #1A1E1B; + --primary: #0E5C4C; + --primary-foreground: #F4FBF8; + --secondary: #EAF5F1; + --secondary-foreground: #0A4338; + --muted: #F7F4EE; + --muted-foreground: #5F675F; + --accent: #EAF5F1; + --accent-foreground: #0A4338; + --destructive: #9F2D2D; + --border: #E2DDD3; + --input: #E2DDD3; + --ring: #0E5C4C; + --chart-1: #0E5C4C; + --chart-2: #B85A28; + --chart-3: #1E4A6E; + --chart-4: #8A5A00; + --chart-5: #5F675F; + + --sidebar: #121915; + --sidebar-foreground: #D4DDD8; + --sidebar-primary: #9ED9C6; + --sidebar-primary-foreground: #121915; + --sidebar-accent: #1E3A32; + --sidebar-accent-foreground: #F3FBF8; + --sidebar-border: rgba(255, 255, 255, 0.08); + --sidebar-ring: #9ED9C6; +} + +.po-banner { + position: sticky; + top: 0; + z-index: 80; + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + min-height: 36px; + padding: 6px 16px; + background: #2A2018; + color: #F3E6D4; + font-size: 12px; + letter-spacing: 0.04em; + text-align: center; +} +.po-banner strong { color: #fff; font-weight: 600; } +.po-dot { + width: 6px; + height: 6px; + border-radius: 999px; + background: #E0A05A; + box-shadow: 0 0 0 3px rgba(224, 160, 90, 0.25); + flex: 0 0 auto; } .dark { diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 741a923..b0aad88 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -143,10 +143,23 @@ export interface Recommendation { knowledge?: KnowledgeContext | null; evidence: Evidence[]; primary_driver: Driver; recommendation: string; expected_impact: { kind: string; horizon_days: number; profit_improvement_min: number; profit_improvement_max: number; explanation: string }; - risks: string[]; missing_information: string[]; assumptions: string[]; source: string; + risks: string[]; missing_information: string[]; assumptions: string[]; source: string; approval?: ApprovalSnapshot | null; + proposal?: { + kind?: string; + margin_check?: { ok: boolean; text: string; margin_pct?: number; floor_pct?: number }; + diffs?: { item: string; before: string; after: string }[]; + evidence_notes?: string[]; + lines?: { sku: string; store_id: string; reorder_quantity: number; risk: string; coverage_days?: string | null }[]; + campaigns_note?: string; + } | null; + }; + action: { + type: string; simulation: boolean; sku: string; + baseline_daily_budget: number; proposed_daily_budget: number; + margin_ok?: boolean; margin_pct?: number | null; margin_floor_pct?: number; + replenish_quantity?: number; line_count?: number; proposed_price_cents?: number; }; - action: { type: string; simulation: boolean; sku: string; baseline_daily_budget: number; proposed_daily_budget: number }; approved_by: string | null; approval_reason: string | null; created_at: string; execution: Execution | null; } export interface Audit { @@ -229,3 +242,43 @@ export interface WeeklyChatHistory { thread: {id: string; report_id: string; created_at: string} | null; items: WeeklyChatMessage[]; } + +export interface WorkspaceOverview { + summary: Metrics + stores: { id: string; name: string; marketplace: string; current: Totals; previous: Totals; profit_delta: number }[] + stores_reconciled: boolean + inventory: { as_of: string | null; missing: boolean; low: number; watch: number; healthy: number; over: number; names: string[]; note: string } + campaigns: { count: number; weak: number; spend: number; attributed_sales: number; roas: number | null; threshold: number; note: string } + anomalies: { code: string; title: string; text: string; target: PageId }[] + currency: string + source: string + note: string +} +export type PageId = 'overview' | 'assistants' | 'investigate' | 'inventory' | 'ads' | 'knowledge' | 'approvals' | 'runs' | 'settings' +export interface CampaignRow { + store_id: string; campaign_id: string; campaign_name: string; + ad_spend: number; attributed_sales: number; attributed_orders: number; + roas: number | null; previous_roas: number | null; previous_spend: number; + below_threshold: boolean; evidence_id: string; +} +export interface CampaignReport { + period: Period; items: CampaignRow[]; spend: number; attributed_sales: number; + roas: number | null; weak: number; threshold: number; currency: string; note: string; +} +export interface AccessView { + actor: { id: string; role: string; tenant_id: string } + enforced_by: string + columns: string[] + rows: { role: string; label: string; implemented: boolean; current: boolean; cells: boolean[]; note?: string }[] + integrations: { name: string; state: string; detail: string }[] + simulation: boolean + note: string +} +export interface EvalReport { + engine: string; llm_calls: number; external_calls: number; + passed: number; failed: number; total: number; + cases: { id: string; scene: string; ok: boolean; detail: string }[] + note: string +} +export interface EvalList { items: { id: string; created_at: string; outcome: string; actor: string; details: EvalReport }[]; note: string } +export interface InventoryReport { as_of: string; items: InventoryRow[]; missing_inventory: boolean; coverage_note: string }