Deploy AIOS web (React glide grid + FastAPI slice)
Browse files- RELEASES.json +1 -1
- VERSION +1 -1
- api/routes_amazon_projects.py +49 -3
- platform/modules/amazon_profit.py +123 -13
- web/public/AIOS_DEPLOY_RECEIPT +1 -1
- web/src/apps/amazon-profit/AccountView.tsx +4 -10
- web/src/apps/amazon-profit/AmazonPeriodPicker.tsx +13 -126
- web/src/apps/amazon-profit/ProjectsList.tsx +2 -9
RELEASES.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": []
|
| 4 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "7aaf8b12c2",
|
| 3 |
"releases": []
|
| 4 |
}
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
7aaf8b12c2
|
api/routes_amazon_projects.py
CHANGED
|
@@ -8,6 +8,7 @@ repaints the `projects` and `projects_label` cells of only the Command Center ro
|
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
from contextlib import contextmanager
|
|
|
|
| 11 |
from pathlib import Path
|
| 12 |
import sys
|
| 13 |
from typing import Any
|
|
@@ -505,6 +506,45 @@ def _series_economics_total(con, key, bounds, skus, available):
|
|
| 505 |
return {"value": None, "reason": str(exc)}
|
| 506 |
|
| 507 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
@router.get("")
|
| 509 |
def row_projects(grain: str | None = None, key: str | None = None,
|
| 510 |
session: Session = Depends(require_session)):
|
|
@@ -664,6 +704,8 @@ def project_result_series(project_id: str, start: str | None = Query(None, alias
|
|
| 664 |
"key": key} for key in selected["keys"]] if selected else [])
|
| 665 |
available = _result_sources(session, targets + selected_targets)
|
| 666 |
con = routes_sku_actions._results_mirror(runtime)
|
|
|
|
|
|
|
| 667 |
reason = None
|
| 668 |
sku_count_reason = None
|
| 669 |
try:
|
|
@@ -674,7 +716,7 @@ def project_result_series(project_id: str, start: str | None = Query(None, alias
|
|
| 674 |
if not skus:
|
| 675 |
reason = "No project targets match the selected scope."
|
| 676 |
elif not bounds["days"]:
|
| 677 |
-
reason = "Today is incomplete. No completed days are available in this range."
|
| 678 |
except projects.MirrorUnreadable as exc:
|
| 679 |
skus, reason = [], str(exc)
|
| 680 |
sku_count_reason = reason
|
|
@@ -686,11 +728,15 @@ def project_result_series(project_id: str, start: str | None = Query(None, alias
|
|
| 686 |
metric = "sales" if key == "sales_yoy" else key
|
| 687 |
if metric not in _SERIES_UNAVAILABLE and metric not in figures:
|
| 688 |
figures[metric] = _result_figure(con, {"metric": metric}, bounds, skus, available)
|
| 689 |
-
|
|
|
|
|
|
|
|
|
|
| 690 |
|
| 691 |
answer = project_results.series(record, bounds=bounds, read=read,
|
| 692 |
independent=lambda key: _series_economics_total(con, key, bounds, skus, available))
|
| 693 |
-
return {**answer, "
|
|
|
|
| 694 |
"skuCountReason": sku_count_reason}
|
| 695 |
except HTTPException:
|
| 696 |
raise
|
|
|
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
from contextlib import contextmanager
|
| 11 |
+
from datetime import timedelta
|
| 12 |
from pathlib import Path
|
| 13 |
import sys
|
| 14 |
from typing import Any
|
|
|
|
| 506 |
return {"value": None, "reason": str(exc)}
|
| 507 |
|
| 508 |
|
| 509 |
+
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _last_reported_economics_day(con):
|
| 513 |
+
"""Return the newest fully reported economics day, or None when no day qualifies."""
|
| 514 |
+
# Amazon writes an all-zero row per SKU for a day it has not reported, so a full row count alone lies.
|
| 515 |
+
day = sku_action_results._day("start_date")
|
| 516 |
+
try:
|
| 517 |
+
rows = con.execute(
|
| 518 |
+
'SELECT d, count(*), SUM(v) FROM (SELECT ' + day + ' AS d, '
|
| 519 |
+
'TRY_CAST("sales_net_product_sales_amount" AS DOUBLE) AS v FROM amzn_economics) daily '
|
| 520 |
+
'WHERE d IS NOT NULL GROUP BY d ORDER BY d').fetchall()
|
| 521 |
+
except Exception: # noqa: BLE001
|
| 522 |
+
return None
|
| 523 |
+
for index in range(len(rows) - 1, -1, -1):
|
| 524 |
+
when, count, total = rows[index]
|
| 525 |
+
peak = max((n for other, n, _ in rows[max(0, index - 14):index] if other >= when - timedelta(days=14)),
|
| 526 |
+
default=0)
|
| 527 |
+
if count >= 0.95 * peak and project_results._finite(total) and total > 0:
|
| 528 |
+
return when
|
| 529 |
+
return None
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def _reported_series_bounds(record, bounds, reported):
|
| 533 |
+
"""Stop aggregation after the last reported economics day and keep the requested dates."""
|
| 534 |
+
if reported is None or bounds["current"][1] <= reported + timedelta(days=1):
|
| 535 |
+
return bounds, None
|
| 536 |
+
first = bounds["current"][0]
|
| 537 |
+
if reported < first:
|
| 538 |
+
return {**bounds, "days": 0, "current": (first, first)}, reported
|
| 539 |
+
cut = project_results.series_window(record, bounds["from"], reported.isoformat(),
|
| 540 |
+
today=reported + timedelta(days=1))
|
| 541 |
+
return {**cut, "from": bounds["from"], "to": bounds["to"]}, reported
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def _reported_reason(reported):
|
| 545 |
+
return f"Amazon has reported economics through {reported.day} {_MONTHS[reported.month - 1]}."
|
| 546 |
+
|
| 547 |
+
|
| 548 |
@router.get("")
|
| 549 |
def row_projects(grain: str | None = None, key: str | None = None,
|
| 550 |
session: Session = Depends(require_session)):
|
|
|
|
| 704 |
"key": key} for key in selected["keys"]] if selected else [])
|
| 705 |
available = _result_sources(session, targets + selected_targets)
|
| 706 |
con = routes_sku_actions._results_mirror(runtime)
|
| 707 |
+
bounds, reported = _reported_series_bounds(record, bounds, _last_reported_economics_day(con))
|
| 708 |
+
cut_reason = _reported_reason(reported) if reported else None
|
| 709 |
reason = None
|
| 710 |
sku_count_reason = None
|
| 711 |
try:
|
|
|
|
| 716 |
if not skus:
|
| 717 |
reason = "No project targets match the selected scope."
|
| 718 |
elif not bounds["days"]:
|
| 719 |
+
reason = cut_reason or "Today is incomplete. No completed days are available in this range."
|
| 720 |
except projects.MirrorUnreadable as exc:
|
| 721 |
skus, reason = [], str(exc)
|
| 722 |
sku_count_reason = reason
|
|
|
|
| 728 |
metric = "sales" if key == "sales_yoy" else key
|
| 729 |
if metric not in _SERIES_UNAVAILABLE and metric not in figures:
|
| 730 |
figures[metric] = _result_figure(con, {"metric": metric}, bounds, skus, available)
|
| 731 |
+
measured = _series_figure(key, figures.get(metric, {}), bounds)
|
| 732 |
+
if cut_reason and measured.get("total") is not None:
|
| 733 |
+
measured = {**measured, "reason": cut_reason}
|
| 734 |
+
return measured
|
| 735 |
|
| 736 |
answer = project_results.series(record, bounds=bounds, read=read,
|
| 737 |
independent=lambda key: _series_economics_total(con, key, bounds, skus, available))
|
| 738 |
+
return {**answer, "reportedThrough": reported.isoformat() if reported else None,
|
| 739 |
+
"skuCount": len(skus) if sku_count_reason is None else None,
|
| 740 |
"skuCountReason": sku_count_reason}
|
| 741 |
except HTTPException:
|
| 742 |
raise
|
platform/modules/amazon_profit.py
CHANGED
|
@@ -85,6 +85,8 @@ PROJECT_HEALTH = ("On track", "Due this week", "Overdue", "Done")
|
|
| 85 |
DUE_SOON_DAYS = 7
|
| 86 |
PICKER_MONTHS = 12
|
| 87 |
SETTLEMENT_TOLERANCE = 0.02
|
|
|
|
|
|
|
| 88 |
|
| 89 |
ECONOMICS = "amzn_economics"
|
| 90 |
SETTLEMENTS = "amzn_settlements"
|
|
@@ -235,6 +237,20 @@ _UNVERIFIED_KEYS = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_pro
|
|
| 235 |
k for k in ("tacos", "profit_health", "score", "priority", "units_30d", "net_sales_30d", "ad_spend",
|
| 236 |
"ad_spend_30d")
|
| 237 |
if k in METRIC_KEYS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
#: A metric check that fails blanks these on every table. The ids and the notes stay.
|
| 239 |
_METRIC_VALUE_KEYS = tuple(k for k in METRIC_KEYS if k not in ("parent_asin",) + M.NOTE_KEYS)
|
| 240 |
#: Cost reasons (R5, D-11172 sibling): a blank COGS, profit or margin names what is missing.
|
|
@@ -712,10 +728,11 @@ def _source_drill(con, sql, params, expected):
|
|
| 712 |
def settlement_components(con, start, end, currency=None, *, drill=False):
|
| 713 |
"""Tie purchase-date order charges, service-month storage and daily ads to independent sources."""
|
| 714 |
month = dt.date.fromisoformat(start).strftime("%B %Y")
|
| 715 |
-
parts, problems, drills = [], [], []
|
| 716 |
|
| 717 |
def problem(component, reason):
|
| 718 |
problems.append(f"Not verified: {component} in {month}: {reason}.")
|
|
|
|
| 719 |
|
| 720 |
def tie(component, ours, source, *, reason=None):
|
| 721 |
ours = float(ours)
|
|
@@ -910,6 +927,7 @@ def settlement_components(con, start, end, currency=None, *, drill=False):
|
|
| 910 |
- float(ad_total)) if ad_total is not None else None
|
| 911 |
return {"total": target, "parts": parts, "reason": problems[0] if problems else None,
|
| 912 |
**({"drills": drills, "problems": problems} if drill else {}),
|
|
|
|
| 913 |
"rows": sum(row[2] for row in groups),
|
| 914 |
"excluded": {k: float(amounts[k]) for k in ("shipping and promotions", "ads billing") if k in amounts}}
|
| 915 |
|
|
@@ -993,6 +1011,50 @@ def _coverage_words(out):
|
|
| 993 |
return dict(out, label=label, sentence=sentence)
|
| 994 |
|
| 995 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 996 |
# ---------------------------------------------------------------- Odoo cost (read only)
|
| 997 |
|
| 998 |
def odoo_costs(codes):
|
|
@@ -2277,6 +2339,43 @@ def refusal(checks, month):
|
|
| 2277 |
return None
|
| 2278 |
|
| 2279 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2280 |
def refusal_line(sentence, covered):
|
| 2281 |
"""The 409 line: the refusal, plus the day the rest settles when the settlement cycle gives one."""
|
| 2282 |
clear = (covered or {}).get("clear")
|
|
@@ -2285,18 +2384,18 @@ def refusal_line(sentence, covered):
|
|
| 2285 |
return f"{sentence} The rest settles about {_day_label(dt.date.fromisoformat(clear))}."
|
| 2286 |
|
| 2287 |
|
| 2288 |
-
def keep_figures(st, *, line, period, month, covered, by=""):
|
| 2289 |
"""A refused refresh: the stored rows, period and verified range stay; only the refusal note is written.
|
| 2290 |
|
| 2291 |
Saving the refused period here would label the kept figures with a period they do not cover."""
|
| 2292 |
stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
| 2293 |
write_settings(st, lastRefusal={"line": line, "period": period, "month": month, "at": stamp,
|
| 2294 |
-
"by": by or WRITER})
|
| 2295 |
settings = read_settings(st)
|
| 2296 |
return {"tableKey": TABLE_KEY, "kept": True, "refusal": line, "refusedPeriod": period,
|
| 2297 |
"refusedAt": stamp, "verifiedMonth": month, "verified": None, "verifiedRange": covered,
|
| 2298 |
"period": period_bounds(settings["period"]), "skus": settings.get("skus"),
|
| 2299 |
-
"linked": settings.get("linked")}
|
| 2300 |
|
| 2301 |
|
| 2302 |
def apply_owned(st, bands, *, today, owner=None, skus=None):
|
|
@@ -2935,21 +3034,27 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
|
|
| 2935 |
tenant=TENANT_ZERO, validator=None):
|
| 2936 |
"""Recompute every SKU for the period and store it; owned cells stay. Returns the report.
|
| 2937 |
|
| 2938 |
-
It runs validate() first for `verification_month`
|
| 2939 |
-
A failed
|
|
|
|
| 2940 |
settings = read_settings(st)
|
| 2941 |
period = str(period or settings["period"]).strip().lower()
|
| 2942 |
period_bounds(period, today)
|
| 2943 |
thin = settings["thin"] if thin is None else clean_thin(thin)
|
| 2944 |
day = today or _today()
|
| 2945 |
-
month = verification_month(period, day)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2946 |
checks = (validator or (lambda c, m: validate(month=m, con=c)))(con, month)
|
| 2947 |
sentence = refusal(checks, month)
|
| 2948 |
covered = next((c["covered"] for c in checks if isinstance(c.get("covered"), dict)), None)
|
| 2949 |
-
|
|
|
|
| 2950 |
with _LOCK:
|
| 2951 |
return keep_figures(st, line=refusal_line(sentence, covered), period=period, month=month,
|
| 2952 |
-
covered=covered, by=by)
|
| 2953 |
verified = covered.get("sentence") if covered else None
|
| 2954 |
with _LOCK:
|
| 2955 |
ensure_table(st, by)
|
|
@@ -2992,7 +3097,7 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
|
|
| 2992 |
metrics = M.sku_metrics(con, start=bounds["start"], end=bounds["end"], skus=list(computed), today=day)
|
| 2993 |
except _metric_problem_types() as exc:
|
| 2994 |
metric_problem = str(exc)
|
| 2995 |
-
computed = merge_metrics(computed, metrics)
|
| 2996 |
metric_checks = [] if metric_problem else list(
|
| 2997 |
M.validate_metrics(con, start=bounds["start"], end=bounds["end"], computed=metrics) or [])
|
| 2998 |
metric_refusal = metric_problem or next(
|
|
@@ -3017,6 +3122,7 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
|
|
| 3017 |
report["pictures"] = dict(grain_pictures(by_grain, refs), stored=len(refs),
|
| 3018 |
sku=sum(1 for values in computed.values() if values.get("picture")))
|
| 3019 |
for key, cells_by_key in list(by_grain.items()):
|
|
|
|
| 3020 |
if metric_refusal:
|
| 3021 |
cells_by_key = {k: _explain(_blank(v, _METRIC_VALUE_KEYS), _METRIC_VALUE_KEYS, metric_refusal)
|
| 3022 |
for k, v in cells_by_key.items()}
|
|
@@ -3043,9 +3149,10 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
|
|
| 3043 |
write_settings(st, period=period, thin=thin, refreshedAt=stamp, refreshedBy=by or WRITER,
|
| 3044 |
lastPeriod=report["period"], skus=report["skus"], linked=report["linked"],
|
| 3045 |
verifiedMonth=month, refusal=None, verified=verified, verifiedRange=covered,
|
| 3046 |
-
lastRefusal=None)
|
| 3047 |
report.update(tableKey=TABLE_KEY, refreshedAt=stamp, verifiedMonth=month, refusal=None,
|
| 3048 |
-
verified=verified, verifiedRange=covered, defaultOwner=owner
|
|
|
|
| 3049 |
try:
|
| 3050 |
report["projectCells"] = paint_project_cells(st, con)
|
| 3051 |
except Exception as exc:
|
|
@@ -3116,6 +3223,7 @@ def recompute_sku(st, con, sku, *, by="", cost_reader=None, today=None):
|
|
| 3116 |
inputs = {k: raw_value(_FIELD_BY_KEY.get(k), before.get(k)) for k in METRIC_KEYS if k in before}
|
| 3117 |
values = merge_metrics({sku: values}, {sku: inputs})[sku]
|
| 3118 |
values = {k: v for k, v in values.items() if k not in _IDENTITY_KEYS or k == "title"}
|
|
|
|
| 3119 |
after = {}
|
| 3120 |
|
| 3121 |
def _set(cur):
|
|
@@ -3146,7 +3254,8 @@ def _recompute_stored_grains(st, changed, settings, con=None):
|
|
| 3146 |
return
|
| 3147 |
source = {rid: row for rid, row in table_rows(st).items() if row.get("period") == period_label}
|
| 3148 |
rows = [_raw_row(row) for row in source.values()]
|
| 3149 |
-
plans = {grain: grain_rows(rows, grain, thin=settings["thin"], period_label=period_label,
|
|
|
|
| 3150 |
for grain, fields in (("asin", ASIN_FIELDS), ("parent_asin", PARENT_FIELDS))}
|
| 3151 |
checks = rollup_checks({rid: row for rid, row in source.items()}, plans)
|
| 3152 |
if not all(check["ok"] for check in checks):
|
|
@@ -3372,6 +3481,7 @@ def validate(pre=None, month=None, con=None, *, cost_usage=None, cost_history=No
|
|
| 3372 |
"ok": ok and not aligned["reason"], "a": round(proceeds, 2),
|
| 3373 |
"b": None if target is None else round(target, 2), "reason": aligned["reason"],
|
| 3374 |
"components": aligned["parts"], "excluded": aligned.get("excluded", {}),
|
|
|
|
| 3375 |
"gap": round(gap, 4), "covered": covered, "tolerance": SETTLEMENT_TOLERANCE})
|
| 3376 |
dropped = net_proceeds_total(con, lo, hi, drop_fees=True)
|
| 3377 |
control_ok, control_gap = _tie(dropped, target) if target is not None else (False, math.inf)
|
|
|
|
| 85 |
DUE_SOON_DAYS = 7
|
| 86 |
PICKER_MONTHS = 12
|
| 87 |
SETTLEMENT_TOLERANCE = 0.02
|
| 88 |
+
#: Amazon releases funds about 7 days after delivery, so a month settles about two weeks after it ends.
|
| 89 |
+
SETTLEMENT_DEFERRAL_DAYS = 14
|
| 90 |
|
| 91 |
ECONOMICS = "amzn_economics"
|
| 92 |
SETTLEMENTS = "amzn_settlements"
|
|
|
|
| 237 |
k for k in ("tacos", "profit_health", "score", "priority", "units_30d", "net_sales_30d", "ad_spend",
|
| 238 |
"ad_spend_30d")
|
| 239 |
if k in METRIC_KEYS)
|
| 240 |
+
#: What a failed settlement component withholds (`withheld_parts`). Any failure also withholds profit.
|
| 241 |
+
_WITHHELD_BY_PART = {
|
| 242 |
+
"product sales": tuple(k for k in ("net_sales", "units_sold", "net_sales_30d", "units_30d", "tacos")
|
| 243 |
+
if k in ("net_sales", "units_sold") or k in METRIC_KEYS),
|
| 244 |
+
"order fees": ("fees",),
|
| 245 |
+
# Published fees is fees_total_amount, which carries the storage, reimbursement and account accruals.
|
| 246 |
+
"monthly storage": ("fees",),
|
| 247 |
+
"reimbursements": ("fees",),
|
| 248 |
+
"account fees": ("fees",),
|
| 249 |
+
"ads": tuple(k for k in ("sponsored_ads", "ad_spend", "ad_spend_30d", "tacos")
|
| 250 |
+
if k == "sponsored_ads" or k in METRIC_KEYS),
|
| 251 |
+
}
|
| 252 |
+
_WITHHELD_PROFIT = ("net_proceeds", "cogs_total", "net_profit", "margin", "band") + tuple(
|
| 253 |
+
k for k in ("profit_health", "score", "priority") if k in METRIC_KEYS)
|
| 254 |
#: A metric check that fails blanks these on every table. The ids and the notes stay.
|
| 255 |
_METRIC_VALUE_KEYS = tuple(k for k in METRIC_KEYS if k not in ("parent_asin",) + M.NOTE_KEYS)
|
| 256 |
#: Cost reasons (R5, D-11172 sibling): a blank COGS, profit or margin names what is missing.
|
|
|
|
| 728 |
def settlement_components(con, start, end, currency=None, *, drill=False):
|
| 729 |
"""Tie purchase-date order charges, service-month storage and daily ads to independent sources."""
|
| 730 |
month = dt.date.fromisoformat(start).strftime("%B %Y")
|
| 731 |
+
parts, problems, drills, named = [], [], [], []
|
| 732 |
|
| 733 |
def problem(component, reason):
|
| 734 |
problems.append(f"Not verified: {component} in {month}: {reason}.")
|
| 735 |
+
named.append(component)
|
| 736 |
|
| 737 |
def tie(component, ours, source, *, reason=None):
|
| 738 |
ours = float(ours)
|
|
|
|
| 927 |
- float(ad_total)) if ad_total is not None else None
|
| 928 |
return {"total": target, "parts": parts, "reason": problems[0] if problems else None,
|
| 929 |
**({"drills": drills, "problems": problems} if drill else {}),
|
| 930 |
+
"failedComponents": list(dict.fromkeys(named)),
|
| 931 |
"rows": sum(row[2] for row in groups),
|
| 932 |
"excluded": {k: float(amounts[k]) for k in ("shipping and promotions", "ads billing") if k in amounts}}
|
| 933 |
|
|
|
|
| 1011 |
return dict(out, label=label, sentence=sentence)
|
| 1012 |
|
| 1013 |
|
| 1014 |
+
def _newest_close(con, currency=None):
|
| 1015 |
+
"""The newest issued settlement close in `currency`, or None without settlement header dates."""
|
| 1016 |
+
cols = _columns(con, SETTLEMENTS)
|
| 1017 |
+
if not set(_COVERAGE_REQUIRED) <= cols:
|
| 1018 |
+
return None
|
| 1019 |
+
scoped = currency is not None and "currency" in cols
|
| 1020 |
+
close = con.execute(
|
| 1021 |
+
f"SELECT max({_moment_sql('settlement_end_date')}) FROM {SETTLEMENTS} WHERE total_amount IS NOT NULL"
|
| 1022 |
+
+ (" AND trim(CAST(currency AS VARCHAR)) = ?" if scoped else ""),
|
| 1023 |
+
[currency] if scoped else []).fetchone()[0]
|
| 1024 |
+
return close if isinstance(close, dt.datetime) else None
|
| 1025 |
+
|
| 1026 |
+
|
| 1027 |
+
def _month_end(month):
|
| 1028 |
+
first = dt.date.fromisoformat(f"{month}-01")
|
| 1029 |
+
return (first.replace(day=28) + dt.timedelta(days=4)).replace(day=1) - dt.timedelta(days=1)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def settled_month(con, month, currency=None):
|
| 1033 |
+
"""`(month, settling)`: `month` stepped back, at most twice, while Amazon still holds its funds.
|
| 1034 |
+
|
| 1035 |
+
A month is settling while the newest close is before its last day plus SETTLEMENT_DEFERRAL_DAYS.
|
| 1036 |
+
`settling` is None when `month` is settled or the mirror has no settlement header dates."""
|
| 1037 |
+
close = _newest_close(con, currency)
|
| 1038 |
+
if close is None:
|
| 1039 |
+
return month, None
|
| 1040 |
+
asked = month
|
| 1041 |
+
for _ in range(2):
|
| 1042 |
+
if close.date() >= _month_end(month) + dt.timedelta(days=SETTLEMENT_DEFERRAL_DAYS):
|
| 1043 |
+
break
|
| 1044 |
+
month = (dt.date.fromisoformat(f"{month}-01") - dt.timedelta(days=1)).strftime("%Y-%m")
|
| 1045 |
+
if month == asked:
|
| 1046 |
+
return month, None
|
| 1047 |
+
end = _month_end(asked)
|
| 1048 |
+
due = end + dt.timedelta(days=SETTLEMENT_DEFERRAL_DAYS)
|
| 1049 |
+
clear = settlement_coverage(con, f"{asked}-01", end.isoformat(), currency).get("clear")
|
| 1050 |
+
if clear and dt.date.fromisoformat(clear) > due:
|
| 1051 |
+
due = dt.date.fromisoformat(clear)
|
| 1052 |
+
words = {m: dt.date.fromisoformat(f"{m}-01").strftime("%B %Y") for m in (asked, month)}
|
| 1053 |
+
line = (f"{words[asked]} is still settling, so the figures tie to {words[month]}. "
|
| 1054 |
+
f"{words[asked]} settles about {_day_label(due)}.")
|
| 1055 |
+
return month, {"month": asked, "verifiedMonth": month, "clear": due.isoformat(), "line": line}
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
# ---------------------------------------------------------------- Odoo cost (read only)
|
| 1059 |
|
| 1060 |
def odoo_costs(codes):
|
|
|
|
| 2339 |
return None
|
| 2340 |
|
| 2341 |
|
| 2342 |
+
def _and(names):
|
| 2343 |
+
return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
|
| 2344 |
+
|
| 2345 |
+
|
| 2346 |
+
def withheld_parts(checks, month):
|
| 2347 |
+
"""`{line, components, keys, month}` when only the settlement tie failed and sales or fees tied, else None.
|
| 2348 |
+
|
| 2349 |
+
Each failed component blanks its own figures and every profit figure; the tied figures publish."""
|
| 2350 |
+
if not checks or checks[0].get("ok") or not all(c.get("ok") for c in checks[1:]):
|
| 2351 |
+
return None
|
| 2352 |
+
first = checks[0]
|
| 2353 |
+
if "covered" in first and (first.get("covered") or {}).get("start") is None:
|
| 2354 |
+
return None
|
| 2355 |
+
parts = {p.get("component"): bool(p.get("ok")) for p in first.get("components") or ()}
|
| 2356 |
+
if not (parts.get("product sales") or parts.get("order fees")):
|
| 2357 |
+
return None
|
| 2358 |
+
failed = list(dict.fromkeys([name for name, ok in parts.items() if not ok]
|
| 2359 |
+
+ list(first.get("failedComponents") or ())))
|
| 2360 |
+
keys = []
|
| 2361 |
+
for part, figures in _WITHHELD_BY_PART.items(): # an absent sales or order fee part counts as failed
|
| 2362 |
+
if not parts.get(part, part not in ("product sales", "order fees")) or part in failed:
|
| 2363 |
+
keys.extend(figures)
|
| 2364 |
+
keys = tuple(dict.fromkeys(keys + list(_WITHHELD_PROFIT)))
|
| 2365 |
+
label = dt.date.fromisoformat(f"{month}-01").strftime("%B %Y")
|
| 2366 |
+
line = (f"Not verified: {_and(failed)} in {label} {'does' if len(failed) == 1 else 'do'} not tie to "
|
| 2367 |
+
"Amazon settlements." if failed else refusal(checks, month))
|
| 2368 |
+
return {"line": line, "components": failed, "keys": keys, "month": month}
|
| 2369 |
+
|
| 2370 |
+
|
| 2371 |
+
def _withhold(cells_by_key, withheld):
|
| 2372 |
+
"""Rows with the figures `withheld` names blanked and explained by its line."""
|
| 2373 |
+
if not withheld:
|
| 2374 |
+
return cells_by_key
|
| 2375 |
+
keys = withheld["keys"]
|
| 2376 |
+
return {k: _explain(_blank(v, keys), keys, withheld["line"]) for k, v in cells_by_key.items()}
|
| 2377 |
+
|
| 2378 |
+
|
| 2379 |
def refusal_line(sentence, covered):
|
| 2380 |
"""The 409 line: the refusal, plus the day the rest settles when the settlement cycle gives one."""
|
| 2381 |
clear = (covered or {}).get("clear")
|
|
|
|
| 2384 |
return f"{sentence} The rest settles about {_day_label(dt.date.fromisoformat(clear))}."
|
| 2385 |
|
| 2386 |
|
| 2387 |
+
def keep_figures(st, *, line, period, month, covered, by="", settling=None):
|
| 2388 |
"""A refused refresh: the stored rows, period and verified range stay; only the refusal note is written.
|
| 2389 |
|
| 2390 |
Saving the refused period here would label the kept figures with a period they do not cover."""
|
| 2391 |
stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
| 2392 |
write_settings(st, lastRefusal={"line": line, "period": period, "month": month, "at": stamp,
|
| 2393 |
+
"by": by or WRITER, "settling": settling})
|
| 2394 |
settings = read_settings(st)
|
| 2395 |
return {"tableKey": TABLE_KEY, "kept": True, "refusal": line, "refusedPeriod": period,
|
| 2396 |
"refusedAt": stamp, "verifiedMonth": month, "verified": None, "verifiedRange": covered,
|
| 2397 |
"period": period_bounds(settings["period"]), "skus": settings.get("skus"),
|
| 2398 |
+
"linked": settings.get("linked"), "settling": settling}
|
| 2399 |
|
| 2400 |
|
| 2401 |
def apply_owned(st, bands, *, today, owner=None, skus=None):
|
|
|
|
| 3034 |
tenant=TENANT_ZERO, validator=None):
|
| 3035 |
"""Recompute every SKU for the period and store it; owned cells stay. Returns the report.
|
| 3036 |
|
| 3037 |
+
It runs validate() first for `verification_month`, stepped back by `settled_month` while it settles.
|
| 3038 |
+
A failed settlement component publishes the tied figures and withholds the rest (`withheld_parts`).
|
| 3039 |
+
Any other failed tie writes no rows and no period (`keep_figures`): the report carries `refusal`."""
|
| 3040 |
settings = read_settings(st)
|
| 3041 |
period = str(period or settings["period"]).strip().lower()
|
| 3042 |
period_bounds(period, today)
|
| 3043 |
thin = settings["thin"] if thin is None else clean_thin(thin)
|
| 3044 |
day = today or _today()
|
| 3045 |
+
month, settling = verification_month(period, day), None
|
| 3046 |
+
try:
|
| 3047 |
+
month, settling = settled_month(con, month, economics_currency(con))
|
| 3048 |
+
except SourceUnavailable:
|
| 3049 |
+
pass # validate() names the missing source
|
| 3050 |
checks = (validator or (lambda c, m: validate(month=m, con=c)))(con, month)
|
| 3051 |
sentence = refusal(checks, month)
|
| 3052 |
covered = next((c["covered"] for c in checks if isinstance(c.get("covered"), dict)), None)
|
| 3053 |
+
partial = withheld_parts(checks, month)
|
| 3054 |
+
if sentence and partial is None: # the settlement check runs before every write
|
| 3055 |
with _LOCK:
|
| 3056 |
return keep_figures(st, line=refusal_line(sentence, covered), period=period, month=month,
|
| 3057 |
+
covered=covered, by=by, settling=settling)
|
| 3058 |
verified = covered.get("sentence") if covered else None
|
| 3059 |
with _LOCK:
|
| 3060 |
ensure_table(st, by)
|
|
|
|
| 3097 |
metrics = M.sku_metrics(con, start=bounds["start"], end=bounds["end"], skus=list(computed), today=day)
|
| 3098 |
except _metric_problem_types() as exc:
|
| 3099 |
metric_problem = str(exc)
|
| 3100 |
+
computed = _withhold(merge_metrics(computed, metrics), partial)
|
| 3101 |
metric_checks = [] if metric_problem else list(
|
| 3102 |
M.validate_metrics(con, start=bounds["start"], end=bounds["end"], computed=metrics) or [])
|
| 3103 |
metric_refusal = metric_problem or next(
|
|
|
|
| 3122 |
report["pictures"] = dict(grain_pictures(by_grain, refs), stored=len(refs),
|
| 3123 |
sku=sum(1 for values in computed.values() if values.get("picture")))
|
| 3124 |
for key, cells_by_key in list(by_grain.items()):
|
| 3125 |
+
cells_by_key = _withhold(cells_by_key, partial)
|
| 3126 |
if metric_refusal:
|
| 3127 |
cells_by_key = {k: _explain(_blank(v, _METRIC_VALUE_KEYS), _METRIC_VALUE_KEYS, metric_refusal)
|
| 3128 |
for k, v in cells_by_key.items()}
|
|
|
|
| 3149 |
write_settings(st, period=period, thin=thin, refreshedAt=stamp, refreshedBy=by or WRITER,
|
| 3150 |
lastPeriod=report["period"], skus=report["skus"], linked=report["linked"],
|
| 3151 |
verifiedMonth=month, refusal=None, verified=verified, verifiedRange=covered,
|
| 3152 |
+
lastRefusal=None, withheld=partial, settling=settling)
|
| 3153 |
report.update(tableKey=TABLE_KEY, refreshedAt=stamp, verifiedMonth=month, refusal=None,
|
| 3154 |
+
verified=verified, verifiedRange=covered, defaultOwner=owner,
|
| 3155 |
+
withheld=partial, settling=settling)
|
| 3156 |
try:
|
| 3157 |
report["projectCells"] = paint_project_cells(st, con)
|
| 3158 |
except Exception as exc:
|
|
|
|
| 3223 |
inputs = {k: raw_value(_FIELD_BY_KEY.get(k), before.get(k)) for k in METRIC_KEYS if k in before}
|
| 3224 |
values = merge_metrics({sku: values}, {sku: inputs})[sku]
|
| 3225 |
values = {k: v for k, v in values.items() if k not in _IDENTITY_KEYS or k == "title"}
|
| 3226 |
+
values = _withhold({sku: values}, settings.get("withheld"))[sku]
|
| 3227 |
after = {}
|
| 3228 |
|
| 3229 |
def _set(cur):
|
|
|
|
| 3254 |
return
|
| 3255 |
source = {rid: row for rid, row in table_rows(st).items() if row.get("period") == period_label}
|
| 3256 |
rows = [_raw_row(row) for row in source.values()]
|
| 3257 |
+
plans = {grain: _withhold(grain_rows(rows, grain, thin=settings["thin"], period_label=period_label,
|
| 3258 |
+
fields=fields), settings.get("withheld"))
|
| 3259 |
for grain, fields in (("asin", ASIN_FIELDS), ("parent_asin", PARENT_FIELDS))}
|
| 3260 |
checks = rollup_checks({rid: row for rid, row in source.items()}, plans)
|
| 3261 |
if not all(check["ok"] for check in checks):
|
|
|
|
| 3481 |
"ok": ok and not aligned["reason"], "a": round(proceeds, 2),
|
| 3482 |
"b": None if target is None else round(target, 2), "reason": aligned["reason"],
|
| 3483 |
"components": aligned["parts"], "excluded": aligned.get("excluded", {}),
|
| 3484 |
+
"failedComponents": aligned.get("failedComponents", []),
|
| 3485 |
"gap": round(gap, 4), "covered": covered, "tolerance": SETTLEMENT_TOLERANCE})
|
| 3486 |
dropped = net_proceeds_total(con, lo, hi, drop_fees=True)
|
| 3487 |
control_ok, control_gap = _tie(dropped, target) if target is not None else (False, math.inf)
|
web/public/AIOS_DEPLOY_RECEIPT
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
9289947cb4215581bb120c57efd62f49fb9ccf4e95e74d88ff2bba1b6edbd9c1
|
web/src/apps/amazon-profit/AccountView.tsx
CHANGED
|
@@ -285,13 +285,14 @@ type Load = { key: string; phase: "loading" }
|
|
| 285 |
| { key: string; phase: "error" | "denied"; message: string };
|
| 286 |
|
| 287 |
export type AccountViewProps = {
|
| 288 |
-
|
|
|
|
| 289 |
components?: AccountDashboardComponents;
|
| 290 |
onSelectSku?: (selection: AccountSkuSelection) => void;
|
| 291 |
};
|
| 292 |
|
| 293 |
-
export default function AccountView({ initialPeriod,
|
| 294 |
-
const [period
|
| 295 |
const [comparison, setComparison] = useState<AccountComparison>("prior");
|
| 296 |
const [monthlyMetric, setMonthlyMetric] = useState<MetricKey>("netSales");
|
| 297 |
const [search, setSearch] = useState("");
|
|
@@ -338,7 +339,6 @@ export default function AccountView({ initialPeriod, periods = [], components: s
|
|
| 338 |
|
| 339 |
const retry = () => { setSelectedSku(null); setRevision((value) => value + 1); };
|
| 340 |
const pending = load.key !== key || load.phase === "loading";
|
| 341 |
-
const choices = periods.some((choice) => choice.key === period) ? periods : [{ key: period, label: period }, ...periods];
|
| 342 |
const id = useId();
|
| 343 |
const content = () => {
|
| 344 |
if (pending) return <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>;
|
|
@@ -403,12 +403,6 @@ export default function AccountView({ initialPeriod, periods = [], components: s
|
|
| 403 |
return <div className="ap-account" data-testid="amazon-profit-account" data-period={period} data-comparison={comparison}
|
| 404 |
role="tabpanel" aria-label="Dashboard" aria-busy={pending}>
|
| 405 |
<header className="ap-account-head"><h2>Account profit</h2>
|
| 406 |
-
<label className="ap-control" htmlFor={`${id}-period`}>Period
|
| 407 |
-
<select id={`${id}-period`} aria-label="Dashboard period" className="ap-select" value={period}
|
| 408 |
-
onChange={(event) => { setSelectedSku(null); setPeriod(event.target.value); }}>
|
| 409 |
-
{choices.map((choice) => <option key={choice.key} value={choice.key}>{choice.label}</option>)}
|
| 410 |
-
</select>
|
| 411 |
-
</label>
|
| 412 |
<label className="ap-control" htmlFor={`${id}-comparison`}>Compare
|
| 413 |
<select id={`${id}-comparison`} className="ap-select" value={comparison}
|
| 414 |
onChange={(event) => { setSelectedSku(null); setComparison(event.target.value as AccountComparison); }}>
|
|
|
|
| 285 |
| { key: string; phase: "error" | "denied"; message: string };
|
| 286 |
|
| 287 |
export type AccountViewProps = {
|
| 288 |
+
/** The stored table period. The Dashboard has no Period control of its own. */
|
| 289 |
+
initialPeriod?: string;
|
| 290 |
components?: AccountDashboardComponents;
|
| 291 |
onSelectSku?: (selection: AccountSkuSelection) => void;
|
| 292 |
};
|
| 293 |
|
| 294 |
+
export default function AccountView({ initialPeriod, components: supplied, onSelectSku }: AccountViewProps) {
|
| 295 |
+
const [period] = useState<string>(() => initialPeriod || lastMonth());
|
| 296 |
const [comparison, setComparison] = useState<AccountComparison>("prior");
|
| 297 |
const [monthlyMetric, setMonthlyMetric] = useState<MetricKey>("netSales");
|
| 298 |
const [search, setSearch] = useState("");
|
|
|
|
| 339 |
|
| 340 |
const retry = () => { setSelectedSku(null); setRevision((value) => value + 1); };
|
| 341 |
const pending = load.key !== key || load.phase === "loading";
|
|
|
|
| 342 |
const id = useId();
|
| 343 |
const content = () => {
|
| 344 |
if (pending) return <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>;
|
|
|
|
| 403 |
return <div className="ap-account" data-testid="amazon-profit-account" data-period={period} data-comparison={comparison}
|
| 404 |
role="tabpanel" aria-label="Dashboard" aria-busy={pending}>
|
| 405 |
<header className="ap-account-head"><h2>Account profit</h2>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
<label className="ap-control" htmlFor={`${id}-comparison`}>Compare
|
| 407 |
<select id={`${id}-comparison`} className="ap-select" value={comparison}
|
| 408 |
onChange={(event) => { setSelectedSku(null); setComparison(event.target.value as AccountComparison); }}>
|
web/src/apps/amazon-profit/AmazonPeriodPicker.tsx
CHANGED
|
@@ -3,8 +3,8 @@ import type { MutableRefObject } from "react";
|
|
| 3 |
import { createPortal } from "react-dom";
|
| 4 |
import { Barcode, ChartBar, Kanban, NotePencil, Tag, TreeStructure } from "@phosphor-icons/react";
|
| 5 |
import type { Icon } from "@phosphor-icons/react";
|
| 6 |
-
import { API_V1, CREDENTIALS
|
| 7 |
-
import {
|
| 8 |
import AccountView, { AccountTabs, useAccountDashboardComponents } from "./AccountView";
|
| 9 |
import type { AccountDashboardComponents, AccountSkuSelection, AccountTab } from "./AccountView";
|
| 10 |
export { DashboardPeriodPicker } from "../../customer-grid/seam";
|
|
@@ -25,9 +25,6 @@ export const COMMAND_CENTER_TABLES: Record<string, CommandCenterGrain> = {
|
|
| 25 |
};
|
| 26 |
const GRAIN_TABLE: Record<CommandCenterGrain, string> = Object.fromEntries(
|
| 27 |
Object.entries(COMMAND_CENTER_TABLES).map(([table, grain]) => [grain, table])) as Record<CommandCenterGrain, string>;
|
| 28 |
-
/** The period POST rewrites these three tables. Projects and Data Entry have no period. */
|
| 29 |
-
const PERIOD_TABLES = [AMAZON_PROFIT_TABLE, "ut_amazon_asin_profit", "ut_amazon_parent_profit"];
|
| 30 |
-
const hasPeriod = (grain: CommandCenterGrain | undefined) => !!grain && grain !== "projects" && grain !== "data_entry";
|
| 31 |
const COMMAND_CENTER_TABS: Array<{ id: AccountTab; label: string; icon: Icon }> = [
|
| 32 |
{ id: "sku", label: "SKU", icon: Barcode }, { id: "asin", label: "Child ASIN", icon: Tag },
|
| 33 |
{ id: "parent", label: "Parent ASIN", icon: TreeStructure },
|
|
@@ -44,111 +41,8 @@ function openCommandCenterTable(table: string) {
|
|
| 44 |
window.location.hash = dataPathHash({ database: table });
|
| 45 |
}
|
| 46 |
|
| 47 |
-
|
| 48 |
-
type ProfitStatus = {
|
| 49 |
-
period: { key: string; label: string };
|
| 50 |
-
periods: PeriodChoice[];
|
| 51 |
-
canEdit: boolean;
|
| 52 |
-
refusal: string | null;
|
| 53 |
-
verified?: string | null;
|
| 54 |
-
};
|
| 55 |
-
|
| 56 |
-
/** A refused period POST retains the stored period and rows cache. */
|
| 57 |
-
export function usePeriodChoice(load: () => Promise<void>) {
|
| 58 |
-
const [busy, setBusy] = useState(false);
|
| 59 |
-
const [pending, setPending] = useState<string | null>(null);
|
| 60 |
-
const [message, setMessage] = useState<string | null>(null);
|
| 61 |
-
const choose = useCallback(async (key: string) => {
|
| 62 |
-
setBusy(true);
|
| 63 |
-
setPending(key);
|
| 64 |
-
setMessage(null);
|
| 65 |
-
try {
|
| 66 |
-
const res = await fetch(`${API_V1}/amazon-profit/period`, {
|
| 67 |
-
method: "POST", credentials: CREDENTIALS,
|
| 68 |
-
headers: { "Content-Type": "application/json" },
|
| 69 |
-
body: JSON.stringify({ period: key }),
|
| 70 |
-
});
|
| 71 |
-
if (!res.ok) {
|
| 72 |
-
const body: unknown = await res.json().catch(() => null);
|
| 73 |
-
setMessage(refusalMessage(body, res.status, "The period did not change. Try again."));
|
| 74 |
-
await load().catch(() => undefined);
|
| 75 |
-
return;
|
| 76 |
-
}
|
| 77 |
-
for (const table of PERIOD_TABLES) {
|
| 78 |
-
clearTopicRowsCache(`tables/${table}/rows`);
|
| 79 |
-
dropTableRowsCache(table);
|
| 80 |
-
}
|
| 81 |
-
signal(ROWS_STALE_EVENT);
|
| 82 |
-
await load();
|
| 83 |
-
} catch {
|
| 84 |
-
setMessage("The period did not change. Try again.");
|
| 85 |
-
} finally {
|
| 86 |
-
setPending(null);
|
| 87 |
-
setBusy(false);
|
| 88 |
-
}
|
| 89 |
-
}, [load]);
|
| 90 |
-
return { busy, pending, message, setMessage, choose };
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
/** The Period select. `pending` holds the choice in flight, so a refusal reverts it. */
|
| 94 |
-
function PeriodSelectField({ status, pending, busy, choose, notesHost }: {
|
| 95 |
-
status: ProfitStatus; pending: string | null; busy: boolean;
|
| 96 |
-
choose: (key: string) => Promise<void>; notesHost?: HTMLElement | null }) {
|
| 97 |
-
const choices = status.periods.some((p) => p.key === status.period.key)
|
| 98 |
-
? status.periods : [{ key: status.period.key, label: status.period.label }, ...status.periods];
|
| 99 |
-
const notes = busy ? <span className="cg-period-busy">Updating</span> : null;
|
| 100 |
-
return (
|
| 101 |
-
<div className="cg-period-picker" data-testid="amazon-period-picker">
|
| 102 |
-
<label>
|
| 103 |
-
<span>Period</span>
|
| 104 |
-
<select
|
| 105 |
-
className="cg-select"
|
| 106 |
-
aria-label="Period"
|
| 107 |
-
value={pending ?? status.period.key}
|
| 108 |
-
disabled={!status.canEdit || busy}
|
| 109 |
-
title={status.canEdit ? undefined : "Only an editor can change the period."}
|
| 110 |
-
onChange={(event) => void choose(event.target.value)}
|
| 111 |
-
>
|
| 112 |
-
{choices.map((p) => <option key={p.key} value={p.key}>{p.label}</option>)}
|
| 113 |
-
</select>
|
| 114 |
-
</label>
|
| 115 |
-
{notes && (notesHost ? createPortal(<span className="cg-period-notes">{notes}</span>, notesHost) : notes)}
|
| 116 |
-
</div>
|
| 117 |
-
);
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
/** The App owns the Period select in the grid's toolbar slot. */
|
| 121 |
-
export function AmazonPeriodSelect({ database }: { database: string }) {
|
| 122 |
-
const grain: CommandCenterGrain | undefined = COMMAND_CENTER_TABLES[database];
|
| 123 |
-
const [status, setStatus] = useState<ProfitStatus | null>(null);
|
| 124 |
-
const anchor = useRef<HTMLSpanElement>(null);
|
| 125 |
-
const [notesHost, setNotesHost] = useState<HTMLElement | null>(null);
|
| 126 |
-
const load = useCallback(async (abortSignal?: AbortSignal) => {
|
| 127 |
-
const res = await fetch(`${API_V1}/amazon-profit`, { credentials: CREDENTIALS,
|
| 128 |
-
signal: abortSignal ?? AbortSignal.timeout(20000) });
|
| 129 |
-
if (!res.ok) return;
|
| 130 |
-
setStatus((await res.json()) as ProfitStatus);
|
| 131 |
-
}, []);
|
| 132 |
-
const { busy, pending, message, setMessage, choose } = usePeriodChoice(load);
|
| 133 |
-
useEffect(() => {
|
| 134 |
-
if (!hasPeriod(grain)) return;
|
| 135 |
-
const controller = new AbortController();
|
| 136 |
-
const timeout = window.setTimeout(() => controller.abort(), 20000);
|
| 137 |
-
void load(controller.signal).catch(() => {
|
| 138 |
-
if (!controller.signal.aborted) setMessage("The period could not be loaded.");
|
| 139 |
-
}).finally(() => window.clearTimeout(timeout));
|
| 140 |
-
return () => { window.clearTimeout(timeout); controller.abort(); };
|
| 141 |
-
}, [grain, load, setMessage]);
|
| 142 |
-
useLayoutEffect(() => {
|
| 143 |
-
setNotesHost(anchor.current?.closest(".cg-main")?.querySelector<HTMLElement>(".ap-table-switcher") ?? null);
|
| 144 |
-
}, [status, message]);
|
| 145 |
-
if (!hasPeriod(grain)) return null;
|
| 146 |
-
return <span className="cc-toolbar-period" ref={anchor}>
|
| 147 |
-
{status ? <PeriodSelectField status={status} pending={pending} busy={busy}
|
| 148 |
-
choose={choose} notesHost={notesHost} />
|
| 149 |
-
: null}
|
| 150 |
-
</span>;
|
| 151 |
-
}
|
| 152 |
|
| 153 |
/** Set by the Command Center App: a tab switches the hosted table, never the hash. */
|
| 154 |
export const CommandCenterTableContext = createContext<((table: string) => void) | null>(null);
|
|
@@ -179,15 +73,12 @@ export function CommandCenterTabStrip({ database, onOpenTable }: {
|
|
| 179 |
type Props = { database: string; dashboardComponents?: AccountDashboardComponents;
|
| 180 |
onSelectSku?: (selection: AccountSkuSelection) => void };
|
| 181 |
|
| 182 |
-
/** The App's one toolbar slot: the
|
| 183 |
export function AmazonToolbar({ database }: { database: string }) {
|
| 184 |
-
return <>
|
| 185 |
-
<AmazonPeriodSelect database={database} />
|
| 186 |
-
<AmazonPeriodPicker database={database} />
|
| 187 |
-
</>;
|
| 188 |
}
|
| 189 |
|
| 190 |
-
/**
|
| 191 |
export default function AmazonPeriodPicker(props: Props) {
|
| 192 |
const mainRef = useRef<HTMLElement | null>(null);
|
| 193 |
// Mounted from the toolbar slot, the tab strip still draws in the toolbar's own row group.
|
|
@@ -209,10 +100,10 @@ export default function AmazonPeriodPicker(props: Props) {
|
|
| 209 |
}, []);
|
| 210 |
if (!grain) return null;
|
| 211 |
return <><span ref={toolbarAnchor} hidden />{tabHost && createPortal(
|
| 212 |
-
<
|
| 213 |
}
|
| 214 |
|
| 215 |
-
function
|
| 216 |
grain: CommandCenterGrain; mainRef: MutableRefObject<HTMLElement | null> }) {
|
| 217 |
const onOpenTable = useContext(CommandCenterTableContext);
|
| 218 |
const [status, setStatus] = useState<ProfitStatus | null>(null);
|
|
@@ -236,17 +127,17 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef, gr
|
|
| 236 |
if (!res.ok) return;
|
| 237 |
setStatus((await res.json()) as ProfitStatus);
|
| 238 |
}, []);
|
| 239 |
-
const { busy, pending, setMessage, choose } = usePeriodChoice(load);
|
| 240 |
|
| 241 |
useEffect(() => {
|
| 242 |
if (grain === "data_entry") { setLoading(false); return; }
|
| 243 |
let current = true;
|
| 244 |
const controller = new AbortController();
|
| 245 |
const timeout = window.setTimeout(() => controller.abort(), 20000);
|
| 246 |
-
|
|
|
|
| 247 |
.finally(() => { window.clearTimeout(timeout); if (current) setLoading(false); });
|
| 248 |
return () => { current = false; window.clearTimeout(timeout); controller.abort(); };
|
| 249 |
-
}, [grain, load
|
| 250 |
|
| 251 |
useLayoutEffect(() => {
|
| 252 |
const main = anchor.current?.closest<HTMLElement>(".cg-main");
|
|
@@ -305,8 +196,6 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef, gr
|
|
| 305 |
openTable(AMAZON_PROFIT_TABLE);
|
| 306 |
};
|
| 307 |
|
| 308 |
-
// The Command Center App draws the Period select in its toolbar (AmazonPeriodSelect).
|
| 309 |
-
const showPeriod = !onOpenTable && !dashboardOn && hasPeriod(grain);
|
| 310 |
if (embedded) return <div className="ap-table-switcher" ref={anchor} hidden />;
|
| 311 |
return (
|
| 312 |
<div className="ap-table-switcher" ref={anchor}>
|
|
@@ -314,11 +203,9 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef, gr
|
|
| 314 |
activeTab={tab} onTabChange={chooseTab} components={shared.components} />
|
| 315 |
{tab === "dashboard" && slot && createPortal(loading
|
| 316 |
? <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>
|
| 317 |
-
: <AccountView initialPeriod={status?.period.key}
|
| 318 |
components={shared.components} onSelectSku={onSelectSku} />, slot)}
|
| 319 |
{tab === "dashboard" && !slot && <p role="status">Dashboard unavailable</p>}
|
| 320 |
-
{showPeriod && status && <PeriodSelectField status={status} pending={pending} busy={busy}
|
| 321 |
-
choose={choose} />}
|
| 322 |
</div>
|
| 323 |
);
|
| 324 |
}
|
|
|
|
| 3 |
import { createPortal } from "react-dom";
|
| 4 |
import { Barcode, ChartBar, Kanban, NotePencil, Tag, TreeStructure } from "@phosphor-icons/react";
|
| 5 |
import type { Icon } from "@phosphor-icons/react";
|
| 6 |
+
import { API_V1, CREDENTIALS } from "../../apiContract";
|
| 7 |
+
import { dataPathHash } from "../../customer-grid/seam";
|
| 8 |
import AccountView, { AccountTabs, useAccountDashboardComponents } from "./AccountView";
|
| 9 |
import type { AccountDashboardComponents, AccountSkuSelection, AccountTab } from "./AccountView";
|
| 10 |
export { DashboardPeriodPicker } from "../../customer-grid/seam";
|
|
|
|
| 25 |
};
|
| 26 |
const GRAIN_TABLE: Record<CommandCenterGrain, string> = Object.fromEntries(
|
| 27 |
Object.entries(COMMAND_CENTER_TABLES).map(([table, grain]) => [grain, table])) as Record<CommandCenterGrain, string>;
|
|
|
|
|
|
|
|
|
|
| 28 |
const COMMAND_CENTER_TABS: Array<{ id: AccountTab; label: string; icon: Icon }> = [
|
| 29 |
{ id: "sku", label: "SKU", icon: Barcode }, { id: "asin", label: "Child ASIN", icon: Tag },
|
| 30 |
{ id: "parent", label: "Parent ASIN", icon: TreeStructure },
|
|
|
|
| 41 |
window.location.hash = dataPathHash({ database: table });
|
| 42 |
}
|
| 43 |
|
| 44 |
+
/** The stored table period. The Dashboard reads its figures for this period. */
|
| 45 |
+
type ProfitStatus = { period: { key: string; label: string } };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
/** Set by the Command Center App: a tab switches the hosted table, never the hash. */
|
| 48 |
export const CommandCenterTableContext = createContext<((table: string) => void) | null>(null);
|
|
|
|
| 73 |
type Props = { database: string; dashboardComponents?: AccountDashboardComponents;
|
| 74 |
onSelectSku?: (selection: AccountSkuSelection) => void };
|
| 75 |
|
| 76 |
+
/** The App's one toolbar slot: the tab strip it draws above the grid. It has no Period control. */
|
| 77 |
export function AmazonToolbar({ database }: { database: string }) {
|
| 78 |
+
return <AmazonPeriodPicker database={database} />;
|
|
|
|
|
|
|
|
|
|
| 79 |
}
|
| 80 |
|
| 81 |
+
/** The Command Center tab strip and Dashboard panel for one hosted table. */
|
| 82 |
export default function AmazonPeriodPicker(props: Props) {
|
| 83 |
const mainRef = useRef<HTMLElement | null>(null);
|
| 84 |
// Mounted from the toolbar slot, the tab strip still draws in the toolbar's own row group.
|
|
|
|
| 100 |
}, []);
|
| 101 |
if (!grain) return null;
|
| 102 |
return <><span ref={toolbarAnchor} hidden />{tabHost && createPortal(
|
| 103 |
+
<ProfitTableTabs {...props} grain={grain} mainRef={mainRef} />, tabHost)}</>;
|
| 104 |
}
|
| 105 |
|
| 106 |
+
function ProfitTableTabs({ dashboardComponents, onSelectSku, mainRef, grain }: Props & {
|
| 107 |
grain: CommandCenterGrain; mainRef: MutableRefObject<HTMLElement | null> }) {
|
| 108 |
const onOpenTable = useContext(CommandCenterTableContext);
|
| 109 |
const [status, setStatus] = useState<ProfitStatus | null>(null);
|
|
|
|
| 127 |
if (!res.ok) return;
|
| 128 |
setStatus((await res.json()) as ProfitStatus);
|
| 129 |
}, []);
|
|
|
|
| 130 |
|
| 131 |
useEffect(() => {
|
| 132 |
if (grain === "data_entry") { setLoading(false); return; }
|
| 133 |
let current = true;
|
| 134 |
const controller = new AbortController();
|
| 135 |
const timeout = window.setTimeout(() => controller.abort(), 20000);
|
| 136 |
+
// A failed read leaves the Dashboard on its default period.
|
| 137 |
+
void load(controller.signal).catch(() => undefined)
|
| 138 |
.finally(() => { window.clearTimeout(timeout); if (current) setLoading(false); });
|
| 139 |
return () => { current = false; window.clearTimeout(timeout); controller.abort(); };
|
| 140 |
+
}, [grain, load]);
|
| 141 |
|
| 142 |
useLayoutEffect(() => {
|
| 143 |
const main = anchor.current?.closest<HTMLElement>(".cg-main");
|
|
|
|
| 196 |
openTable(AMAZON_PROFIT_TABLE);
|
| 197 |
};
|
| 198 |
|
|
|
|
|
|
|
| 199 |
if (embedded) return <div className="ap-table-switcher" ref={anchor} hidden />;
|
| 200 |
return (
|
| 201 |
<div className="ap-table-switcher" ref={anchor}>
|
|
|
|
| 203 |
activeTab={tab} onTabChange={chooseTab} components={shared.components} />
|
| 204 |
{tab === "dashboard" && slot && createPortal(loading
|
| 205 |
? <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>
|
| 206 |
+
: <AccountView initialPeriod={status?.period.key}
|
| 207 |
components={shared.components} onSelectSku={onSelectSku} />, slot)}
|
| 208 |
{tab === "dashboard" && !slot && <p role="status">Dashboard unavailable</p>}
|
|
|
|
|
|
|
| 209 |
</div>
|
| 210 |
);
|
| 211 |
}
|
web/src/apps/amazon-profit/ProjectsList.tsx
CHANGED
|
@@ -30,19 +30,12 @@ const money = (value: number | null | undefined) => value == null ? "Unknown" :
|
|
| 30 |
value.toLocaleString("en-US", { style: "currency", currency: "USD" });
|
| 31 |
const units = (value: number | null | undefined) => value == null ? "Unknown" : value.toLocaleString("en-US");
|
| 32 |
|
| 33 |
-
function projectPeriodLabel(period: string | null | undefined) {
|
| 34 |
-
if (period === "90d") return "90 days";
|
| 35 |
-
if (period === "30d") return "30 days";
|
| 36 |
-
return period || "Period";
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
function ProjectFigures({ project, compact = false }: { project: Project; compact?: boolean }) {
|
| 40 |
const { rollup, impact } = project;
|
| 41 |
if (!rollup && !impact) return null;
|
| 42 |
-
const period = projectPeriodLabel(rollup?.period);
|
| 43 |
if (compact) return <div className="lp-proj-row-figures">
|
| 44 |
<div title={rollup?.asOf}>
|
| 45 |
-
<span>
|
| 46 |
<span>Profit {money(rollup?.netProfit)}</span><span>Units {units(rollup?.units)}</span>
|
| 47 |
</div>
|
| 48 |
{project.status === "Completed" && project.completedOn ? <div title="Compared with the same days one year earlier">
|
|
@@ -52,7 +45,7 @@ function ProjectFigures({ project, compact = false }: { project: Project; compac
|
|
| 52 |
</div> : null}
|
| 53 |
</div>;
|
| 54 |
return <section className="lp-proj-section" aria-label="Project figures" style={{ fontVariantNumeric: "tabular-nums" }}>
|
| 55 |
-
<h4 className="lp-proj-section-title" title={rollup?.asOf}>
|
| 56 |
<dl className="lp-proj-facts">
|
| 57 |
<div><dt>Net sales</dt><dd>{money(rollup?.netSales)}</dd></div>
|
| 58 |
<div><dt>Net profit</dt><dd>{money(rollup?.netProfit)}</dd></div>
|
|
|
|
| 30 |
value.toLocaleString("en-US", { style: "currency", currency: "USD" });
|
| 31 |
const units = (value: number | null | undefined) => value == null ? "Unknown" : value.toLocaleString("en-US");
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
function ProjectFigures({ project, compact = false }: { project: Project; compact?: boolean }) {
|
| 34 |
const { rollup, impact } = project;
|
| 35 |
if (!rollup && !impact) return null;
|
|
|
|
| 36 |
if (compact) return <div className="lp-proj-row-figures">
|
| 37 |
<div title={rollup?.asOf}>
|
| 38 |
+
<span>Sales {money(rollup?.netSales)}</span>
|
| 39 |
<span>Profit {money(rollup?.netProfit)}</span><span>Units {units(rollup?.units)}</span>
|
| 40 |
</div>
|
| 41 |
{project.status === "Completed" && project.completedOn ? <div title="Compared with the same days one year earlier">
|
|
|
|
| 45 |
</div> : null}
|
| 46 |
</div>;
|
| 47 |
return <section className="lp-proj-section" aria-label="Project figures" style={{ fontVariantNumeric: "tabular-nums" }}>
|
| 48 |
+
<h4 className="lp-proj-section-title" title={rollup?.asOf}>Totals</h4>
|
| 49 |
<dl className="lp-proj-facts">
|
| 50 |
<div><dt>Net sales</dt><dd>{money(rollup?.netSales)}</dd></div>
|
| 51 |
<div><dt>Net profit</dt><dd>{money(rollup?.netProfit)}</dd></div>
|