Prune files not in the deploy set (stale build context)
Browse files- api/routes_returns_repeat.py +0 -161
- platform/modules/returns_repeat.py +0 -1212
- web/src/apps/returns-repeat/AppView.tsx +0 -784
api/routes_returns_repeat.py
DELETED
|
@@ -1,161 +0,0 @@
|
|
| 1 |
-
"""Returns and repeat App routes (C3): summary, SKU segments, SKU detail, owned items and settings.
|
| 2 |
-
|
| 3 |
-
Every endpoint names the App in its path. A caller who cannot read that App gets 404. Item writes
|
| 4 |
-
need a non-viewer account that may read FBA returns. Settings writes need an editor of the App.
|
| 5 |
-
"""
|
| 6 |
-
from fastapi import APIRouter, Body, Depends, Path, Query
|
| 7 |
-
|
| 8 |
-
from deps import Session, err, require_session
|
| 9 |
-
|
| 10 |
-
TEMPLATE_KIND = "returns_repeat"
|
| 11 |
-
router = APIRouter(prefix=f"/api/v1/app-kinds/{TEMPLATE_KIND}", tags=["returns-repeat"])
|
| 12 |
-
SOURCE = "ut_amzn_fba_customer_returns"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def _module():
|
| 16 |
-
from modules import returns_repeat
|
| 17 |
-
return returns_repeat
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def _tenant(session):
|
| 21 |
-
return str(getattr(session.runtime, "key", "") or session.tenant)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def _call(fn, *args, **kwargs):
|
| 25 |
-
try:
|
| 26 |
-
return fn(*args, **kwargs)
|
| 27 |
-
except PermissionError as exc:
|
| 28 |
-
raise err(403, "returns_repeat_read_only", str(exc)) from exc
|
| 29 |
-
except ValueError as exc:
|
| 30 |
-
raise err(400, "returns_repeat_invalid", str(exc)) from exc
|
| 31 |
-
except KeyError as exc:
|
| 32 |
-
raise err(404, "returns_repeat_not_found", "That SKU or item does not exist.") from exc
|
| 33 |
-
except Exception as exc: # noqa: BLE001
|
| 34 |
-
raise err(503, "returns_repeat_unavailable", "Returns and repeat could not be read. Try again shortly.") from exc
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _app(session, app_id):
|
| 38 |
-
"""The Returns and repeat App this request names, readable by the caller (404 otherwise)."""
|
| 39 |
-
import application_registry
|
| 40 |
-
try:
|
| 41 |
-
app = application_registry.load(session.runtime)["applications"].get(str(app_id or ""))
|
| 42 |
-
except Exception as exc: # noqa: BLE001
|
| 43 |
-
raise err(503, "returns_repeat_unavailable", "The App could not be read. Try again shortly.") from exc
|
| 44 |
-
if (not isinstance(app, dict) or app.get("templateKind") != TEMPLATE_KIND or app.get("retired") is True
|
| 45 |
-
or not application_registry.may_read(app, session.uname, is_admin=session.admin)):
|
| 46 |
-
raise err(404, "returns_repeat_app_not_found", "That Returns and repeat App does not exist.")
|
| 47 |
-
return app
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def _viewer(session):
|
| 51 |
-
return str(session.user.get("role") or "user").strip().lower() == "viewer"
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def _may_edit_app(session, app):
|
| 55 |
-
import application_registry
|
| 56 |
-
return not _viewer(session) and application_registry.may_edit(app, session.uname, is_admin=session.admin)
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def _can_edit_items(session):
|
| 60 |
-
return _module().may_edit(session.runtime, session.user)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _app_reader(app_id: str = Path(..., min_length=1), session: Session = Depends(require_session)) -> Session:
|
| 64 |
-
"""A read names the App, and the caller must read that App and the FBA returns database."""
|
| 65 |
-
_app(session, app_id)
|
| 66 |
-
from core import perm_scope
|
| 67 |
-
if not perm_scope.may_read(session.user, SOURCE, st=session.runtime):
|
| 68 |
-
raise err(403, "returns_repeat_forbidden", "Your account cannot read Amazon FBA returns.")
|
| 69 |
-
return session
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def _item_writer(session: Session = Depends(_app_reader)) -> Session:
|
| 73 |
-
"""An item write also refuses a viewer."""
|
| 74 |
-
if _viewer(session) or not _can_edit_items(session):
|
| 75 |
-
raise err(403, "returns_repeat_read_only", "You can view this App but not change its items.")
|
| 76 |
-
return session
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def _settings_writer(app_id: str = Path(..., min_length=1), session: Session = Depends(_app_reader)) -> Session:
|
| 80 |
-
"""A settings write needs an editor of the App."""
|
| 81 |
-
if not _may_edit_app(session, _app(session, app_id)):
|
| 82 |
-
raise err(403, "returns_repeat_read_only", "You can view this App but not change its settings.")
|
| 83 |
-
return session
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
@router.get("/{app_id}/summary")
|
| 87 |
-
def read_summary(start: str | None = Query(None), end: str | None = Query(None),
|
| 88 |
-
cursor: str | None = Query(None), limit: int = Query(24, ge=1),
|
| 89 |
-
session: Session = Depends(_app_reader)):
|
| 90 |
-
rr = _module()
|
| 91 |
-
out = _call(rr.summary, _tenant(session), start=start, end=end, cursor=cursor, limit=limit, st=session.runtime)
|
| 92 |
-
return {**out, "canEdit": _can_edit_items(session) and not _viewer(session)}
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
@router.get("/{app_id}/skus")
|
| 96 |
-
def list_skus(segment: str = Query("highest"), start: str | None = Query(None), end: str | None = Query(None),
|
| 97 |
-
cursor: str | None = Query(None), limit: int = Query(100, ge=1), q: str | None = Query(None),
|
| 98 |
-
session: Session = Depends(_app_reader)):
|
| 99 |
-
rr = _module()
|
| 100 |
-
return _call(rr.skus, _tenant(session), segment=segment, start=start, end=end, cursor=cursor,
|
| 101 |
-
limit=limit, q=q, st=session.runtime)
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
@router.get("/{app_id}/sku")
|
| 105 |
-
def sku_detail(key: str = Query(..., min_length=1), start: str | None = Query(None),
|
| 106 |
-
end: str | None = Query(None), cursor: str | None = Query(None), limit: int = Query(25, ge=1),
|
| 107 |
-
session: Session = Depends(_app_reader)):
|
| 108 |
-
rr = _module()
|
| 109 |
-
return _call(rr.detail, _tenant(session), key, start=start, end=end, cursor=cursor, limit=limit, st=session.runtime)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def owners(session):
|
| 113 |
-
"""People who may own an item: active, non-service, non-viewer accounts of this tenant, by display name."""
|
| 114 |
-
rr = _module()
|
| 115 |
-
try:
|
| 116 |
-
users = session.runtime.get("users")
|
| 117 |
-
except Exception: # noqa: BLE001
|
| 118 |
-
users = None
|
| 119 |
-
want = _tenant(session).strip().lower()
|
| 120 |
-
names = set()
|
| 121 |
-
for name, rec in (users.items() if isinstance(users, dict) else ()):
|
| 122 |
-
if (not isinstance(rec, dict) or not rec.get("active", True) or rr._is_service(name, rec)
|
| 123 |
-
or str(rec.get("role") or "").strip().lower() == "viewer"
|
| 124 |
-
or (want and str(rec.get("tenant") or "royal-imports").strip().lower() != want)):
|
| 125 |
-
continue
|
| 126 |
-
names.add(str(rec.get("name") or name).strip())
|
| 127 |
-
return sorted((n for n in names if n), key=str.lower)
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
@router.get("/{app_id}/items")
|
| 131 |
-
def list_items(status: str | None = Query(None), cursor: str | None = Query(None),
|
| 132 |
-
limit: int = Query(100, ge=1), session: Session = Depends(_app_reader)):
|
| 133 |
-
rr = _module()
|
| 134 |
-
listed = _call(rr.items, _tenant(session), session.user, status=status, cursor=cursor, limit=limit,
|
| 135 |
-
st=session.runtime)
|
| 136 |
-
return {**listed, "statuses": list(rr.STATUSES), "owners": owners(session),
|
| 137 |
-
"canEdit": _can_edit_items(session) and not _viewer(session)}
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
@router.patch("/{app_id}/items/{item_id}")
|
| 141 |
-
def patch_item(item_id: str, owner: str | None = Body(None), status: str | None = Body(None),
|
| 142 |
-
due: str | None = Body(None), note: str | None = Body(None),
|
| 143 |
-
session: Session = Depends(_item_writer)):
|
| 144 |
-
rr = _module()
|
| 145 |
-
return _call(rr.update_item, _tenant(session), session.user, item_id, owner=owner, status=status,
|
| 146 |
-
due=due, note=note, st=session.runtime)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@router.get("/{app_id}/settings")
|
| 150 |
-
def read_settings(app_id: str, session: Session = Depends(_app_reader)):
|
| 151 |
-
rr = _module()
|
| 152 |
-
out = _call(rr.settings, _tenant(session), st=session.runtime)
|
| 153 |
-
return {**out, "canEdit": _may_edit_app(session, _app(session, app_id))}
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
@router.put("/{app_id}/settings")
|
| 157 |
-
def write_settings(risingRatio: float | None = Body(None), risingMinPct: float | None = Body(None),
|
| 158 |
-
defaultOwner: str | None = Body(None), session: Session = Depends(_settings_writer)):
|
| 159 |
-
rr = _module()
|
| 160 |
-
return _call(rr.set_settings, _tenant(session), rising_ratio=risingRatio, rising_min_pct=risingMinPct,
|
| 161 |
-
default_owner=defaultOwner, st=session.runtime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
platform/modules/returns_repeat.py
DELETED
|
@@ -1,1212 +0,0 @@
|
|
| 1 |
-
"""Returns and repeat App: return rate per SKU, top return reasons, rising-returns items, repeat buyers.
|
| 2 |
-
|
| 3 |
-
Sources (tenant mirror, read-only, never written): `amzn_fba_customer_returns`, `amzn_fba_shipped_sales`,
|
| 4 |
-
`amzn_repeat_purchase`, `amzn_market_basket` (Data-page keys `ut_amzn_*`). Nothing here calls Amazon or Odoo.
|
| 5 |
-
|
| 6 |
-
Store documents (tenant runtime store, App owned, never a connector table):
|
| 7 |
-
returns_repeat_settings {rising_ratio, rising_min_pct, default_owner}
|
| 8 |
-
returns_repeat_items {seq, items: {id: item}}
|
| 9 |
-
returns_repeat_history {snapshots: {date: {sku: [rate30, rate90, ret30, ship30, ret90, ship90]}}, last_run}
|
| 10 |
-
|
| 11 |
-
Deleting this module and its three documents leaves every `amzn_*` table intact (rule 13).
|
| 12 |
-
|
| 13 |
-
Limit (rule 1): each document is one JSON value, and the Postgres store refuses a document over
|
| 14 |
-
`core.store_pg.DOCUMENT_CEILING_BYTES` (128 MB). The history keeps one snapshot a day at about 60
|
| 15 |
-
bytes a SKU, so 1,000 SKUs reach the ceiling after about 2,000 days. At about 700 bytes an item, the
|
| 16 |
-
items document reaches it near 180,000 items. Nothing here caps SKUs, items or rows. The fix when a
|
| 17 |
-
document nears the ceiling: split it by year.
|
| 18 |
-
"""
|
| 19 |
-
import contextlib
|
| 20 |
-
import datetime as dt
|
| 21 |
-
import json
|
| 22 |
-
import logging
|
| 23 |
-
import time
|
| 24 |
-
from pathlib import Path
|
| 25 |
-
|
| 26 |
-
LOG = logging.getLogger(__name__)
|
| 27 |
-
|
| 28 |
-
SOURCE_KIND = "returns_repeat"
|
| 29 |
-
#: The Data-page key a person must be able to read before the App lets them change an item.
|
| 30 |
-
SOURCE = "ut_amzn_fba_customer_returns"
|
| 31 |
-
RETURNS_TABLE = "amzn_fba_customer_returns"
|
| 32 |
-
SHIPPED_TABLE = "amzn_fba_shipped_sales"
|
| 33 |
-
REPEAT_TABLE = "amzn_repeat_purchase"
|
| 34 |
-
BASKET_TABLE = "amzn_market_basket"
|
| 35 |
-
TABLES = (RETURNS_TABLE, SHIPPED_TABLE, REPEAT_TABLE, BASKET_TABLE)
|
| 36 |
-
|
| 37 |
-
STATUSES = ("Open", "Approved", "Investigating", "Listing fixed", "Watching", "Resolved", "Dismissed")
|
| 38 |
-
#: A SKU with an item in one of these statuses raises no second item.
|
| 39 |
-
HOLDING = ("Open", "Approved", "Investigating", "Watching", "Dismissed")
|
| 40 |
-
DECISIONS = {"approved": "Approved", "dismissed": "Dismissed"}
|
| 41 |
-
#: P11 defaults (R49): rising when the 30 day rate is at least 1.5 times the 90 day rate and at least 5%.
|
| 42 |
-
DEFAULTS = {"rising_ratio": 1.5, "rising_min_pct": 5.0}
|
| 43 |
-
DUE_DAYS = 7
|
| 44 |
-
PERIOD_DAYS = 90
|
| 45 |
-
SEGMENTS = {"highest": "Highest return rate", "rising": "Rising returns", "repeat": "Repeat buyers"}
|
| 46 |
-
EMPTY = "No returns in this period"
|
| 47 |
-
NO_SKU = "No SKU"
|
| 48 |
-
ACTION = "Check Voice of the Customer for {target} and fix the listing problem it names."
|
| 49 |
-
LIMIT = ("Each Returns and repeat document is limited to 128 MB by the store. About 2,000 daily "
|
| 50 |
-
"snapshots of 1,000 SKUs, or 180,000 items, fit in one. Split the document by year when it "
|
| 51 |
-
"nears that size.")
|
| 52 |
-
|
| 53 |
-
#: Amazon return codes whose plain word reading is wrong. Every other code reads as sentence case.
|
| 54 |
-
REASON_LABELS = {"DAMAGED_BY_FC": "Damaged at the fulfillment center",
|
| 55 |
-
"UNDELIVERABLE_UNKNOWN": "Undeliverable",
|
| 56 |
-
"SWITCHEROO": "Different item returned"}
|
| 57 |
-
TREND_DAYS = 7
|
| 58 |
-
MAX_PAGE_SIZE = 100
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def reason_label(code):
|
| 62 |
-
"""The words a person reads for an Amazon return code: never the code, never all caps."""
|
| 63 |
-
text = _clean(code)
|
| 64 |
-
if not text:
|
| 65 |
-
return "No reason given"
|
| 66 |
-
if text.upper() in REASON_LABELS:
|
| 67 |
-
return REASON_LABELS[text.upper()]
|
| 68 |
-
if text != text.upper():
|
| 69 |
-
return text
|
| 70 |
-
words = " ".join(text.replace("_", " ").replace("-", " ").split()).lower()
|
| 71 |
-
return words[:1].upper() + words[1:] if words else "No reason given"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
KEY_SETTINGS = "returns_repeat_settings"
|
| 75 |
-
KEY_ITEMS = "returns_repeat_items"
|
| 76 |
-
KEY_HISTORY = "returns_repeat_history"
|
| 77 |
-
OWN_KEYS = (KEY_SETTINGS, KEY_ITEMS, KEY_HISTORY)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def _now():
|
| 81 |
-
return dt.datetime.now(dt.timezone.utc)
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def _stamp(at):
|
| 85 |
-
return at.strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def _rt(tenant_key, st=None):
|
| 89 |
-
"""The tenant runtime store handle (get and update), or raise when it cannot be resolved."""
|
| 90 |
-
if st is not None:
|
| 91 |
-
return st
|
| 92 |
-
from harness import amazon_store
|
| 93 |
-
rt = amazon_store._runtime_for(tenant_key)
|
| 94 |
-
if rt is None:
|
| 95 |
-
raise RuntimeError(f"The store for tenant {tenant_key!r} could not be opened.")
|
| 96 |
-
return rt
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def _doc(st, key):
|
| 100 |
-
value = st.get(key)
|
| 101 |
-
return value if isinstance(value, dict) else {}
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
# --------------------------------------------------------------------------- mirror reads
|
| 105 |
-
|
| 106 |
-
def _mirror_path(tenant_key, st):
|
| 107 |
-
from harness import amazon_store
|
| 108 |
-
rt = st if hasattr(st, "datastore_path") else None
|
| 109 |
-
return amazon_store._tenant_mirror_path(tenant_key, rt)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
@contextlib.contextmanager
|
| 113 |
-
def _reader(tenant_key, st):
|
| 114 |
-
"""A read-only cursor on the tenant mirror, or None when the mirror file does not exist."""
|
| 115 |
-
path = Path(_mirror_path(tenant_key, st))
|
| 116 |
-
if not path.exists():
|
| 117 |
-
yield None
|
| 118 |
-
return
|
| 119 |
-
from harness import datastore
|
| 120 |
-
try:
|
| 121 |
-
shared = Path(datastore.DB_PATH).resolve() == path.resolve()
|
| 122 |
-
except Exception: # noqa: BLE001
|
| 123 |
-
shared = False
|
| 124 |
-
# The process holds one writer on its own mirror: a separate read-only connect would refuse.
|
| 125 |
-
if shared:
|
| 126 |
-
cur = datastore.ro_cursor()
|
| 127 |
-
try:
|
| 128 |
-
yield cur
|
| 129 |
-
finally:
|
| 130 |
-
cur.close()
|
| 131 |
-
return
|
| 132 |
-
import duckdb
|
| 133 |
-
con = duckdb.connect(str(path), read_only=True)
|
| 134 |
-
try:
|
| 135 |
-
yield con
|
| 136 |
-
finally:
|
| 137 |
-
con.close()
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def _columns(cur, table):
|
| 141 |
-
try:
|
| 142 |
-
return {r[0] for r in cur.execute(
|
| 143 |
-
"SELECT column_name FROM information_schema.columns WHERE table_name = ?", [table]).fetchall()}
|
| 144 |
-
except Exception: # noqa: BLE001
|
| 145 |
-
return set()
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
def _text(cols, name):
|
| 149 |
-
return f'CAST("{name}" AS VARCHAR)' if name in cols else "NULL"
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
def _num(cols, name):
|
| 153 |
-
return f'TRY_CAST("{name}" AS DOUBLE)' if name in cols else "NULL"
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def _first(cols, *names):
|
| 157 |
-
return next((n for n in names if n in cols), None)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def _day(value):
|
| 161 |
-
"""A date from mirror text (F36: Amazon dates may arrive as text in several shapes), or None."""
|
| 162 |
-
if value is None:
|
| 163 |
-
return None
|
| 164 |
-
if isinstance(value, dt.datetime):
|
| 165 |
-
return value.date()
|
| 166 |
-
if isinstance(value, dt.date):
|
| 167 |
-
return value
|
| 168 |
-
text = str(value).strip()
|
| 169 |
-
if not text:
|
| 170 |
-
return None
|
| 171 |
-
try:
|
| 172 |
-
return dt.date.fromisoformat(text[:10])
|
| 173 |
-
except ValueError:
|
| 174 |
-
pass
|
| 175 |
-
for fmt in ("%m/%d/%Y", "%Y/%m/%d", "%d-%b-%Y", "%b %d, %Y"):
|
| 176 |
-
try:
|
| 177 |
-
return dt.datetime.strptime(text.split(" ")[0] if "/" in text else text, fmt).date()
|
| 178 |
-
except ValueError:
|
| 179 |
-
continue
|
| 180 |
-
return None
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
def _clean(value):
|
| 184 |
-
return str(value).strip() if value is not None else ""
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
def _returns(cur):
|
| 188 |
-
"""Return rows grouped as (sku, asin, day, reason, units, rows). Uncapped."""
|
| 189 |
-
cols = _columns(cur, RETURNS_TABLE) if cur is not None else set()
|
| 190 |
-
if not cols & {"sku", "asin"}:
|
| 191 |
-
return []
|
| 192 |
-
qty = _num(cols, "quantity") if "quantity" in cols else "1"
|
| 193 |
-
rows = cur.execute(
|
| 194 |
-
f'SELECT {_text(cols, "sku")}, {_text(cols, "asin")}, {_text(cols, "return_date")}, '
|
| 195 |
-
f'{_text(cols, "reason")}, SUM(COALESCE({qty}, 0)), COUNT(*) FROM {RETURNS_TABLE} '
|
| 196 |
-
f'GROUP BY 1, 2, 3, 4').fetchall()
|
| 197 |
-
return [(_clean(s), _clean(a), _day(d), _clean(r), float(u or 0), int(n or 0)) for s, a, d, r, u, n in rows]
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
def _shipped(cur):
|
| 201 |
-
"""Shipment rows grouped as (sku, asin, day, units). Uncapped."""
|
| 202 |
-
cols = _columns(cur, SHIPPED_TABLE) if cur is not None else set()
|
| 203 |
-
if not cols & {"sku", "asin"}:
|
| 204 |
-
return []
|
| 205 |
-
qty = _num(cols, "quantity") if "quantity" in cols else "1"
|
| 206 |
-
rows = cur.execute(
|
| 207 |
-
f'SELECT {_text(cols, "sku")}, {_text(cols, "asin")}, {_text(cols, "shipment_date")}, '
|
| 208 |
-
f'SUM(COALESCE({qty}, 0)) FROM {SHIPPED_TABLE} GROUP BY 1, 2, 3').fetchall()
|
| 209 |
-
return [(_clean(s), _clean(a), _day(d), float(u or 0)) for s, a, d, u in rows]
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
def _repeat(cur):
|
| 213 |
-
"""Repeat purchase rows (Brand Analytics, one per ASIN and month) as dicts."""
|
| 214 |
-
cols = _columns(cur, REPEAT_TABLE) if cur is not None else set()
|
| 215 |
-
if "asin" not in cols:
|
| 216 |
-
return []
|
| 217 |
-
start = _first(cols, "start_date", "_period_start")
|
| 218 |
-
end = _first(cols, "end_date", "_period_end")
|
| 219 |
-
rows = cur.execute(
|
| 220 |
-
f'SELECT CAST("asin" AS VARCHAR), {_text(cols, start or "")}, {_text(cols, end or "")}, '
|
| 221 |
-
f'{_num(cols, "orders")}, {_num(cols, "unique_customers")}, {_num(cols, "repeat_customers_pct_total")}, '
|
| 222 |
-
f'{_num(cols, "repeat_purchase_revenue_amount")}, {_text(cols, "repeat_purchase_revenue_currency_code")}, '
|
| 223 |
-
f'{_num(cols, "repeat_purchase_revenue_pct_total")} FROM {REPEAT_TABLE}').fetchall()
|
| 224 |
-
out = []
|
| 225 |
-
for asin, s, e, orders, customers, pct, revenue, currency, rev_pct in rows:
|
| 226 |
-
if not _clean(asin):
|
| 227 |
-
continue
|
| 228 |
-
s, e = _day(s), _day(e)
|
| 229 |
-
out.append({"asin": _clean(asin), "start": s, "end": e or s, "orders": orders,
|
| 230 |
-
"customers": customers, "pct": pct, "revenue": revenue,
|
| 231 |
-
"currency": _clean(currency) or None, "revenuePct": rev_pct})
|
| 232 |
-
return out
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def _basket(cur):
|
| 236 |
-
"""Market basket rows as dicts: which ASINs a buyer bought together with ours."""
|
| 237 |
-
cols = _columns(cur, BASKET_TABLE) if cur is not None else set()
|
| 238 |
-
if not {"asin", "purchased_with_asin"} <= cols:
|
| 239 |
-
return []
|
| 240 |
-
start = _first(cols, "start_date", "_period_start")
|
| 241 |
-
rank = 'TRY_CAST("purchased_with_rank" AS INTEGER)' if "purchased_with_rank" in cols else "NULL"
|
| 242 |
-
rows = cur.execute(
|
| 243 |
-
f'SELECT CAST("asin" AS VARCHAR), CAST("purchased_with_asin" AS VARCHAR), {rank}, '
|
| 244 |
-
f'{_num(cols, "combination_pct")}, {_text(cols, start or "")} FROM {BASKET_TABLE}').fetchall()
|
| 245 |
-
return [{"asin": _clean(a), "with": _clean(w), "rank": r, "pct": p, "start": _day(s)}
|
| 246 |
-
for a, w, r, p, s in rows if _clean(a) and _clean(w)]
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
def _load(tenant_key, st):
|
| 250 |
-
with _reader(tenant_key, st) as cur:
|
| 251 |
-
if cur is None:
|
| 252 |
-
return {"mirror": False, "returns": [], "shipped": [], "repeat": [], "basket": []}
|
| 253 |
-
return {"mirror": True, "returns": _returns(cur), "shipped": _shipped(cur),
|
| 254 |
-
"repeat": _repeat(cur), "basket": _basket(cur)}
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
# --------------------------------------------------------------------------- settings and owner
|
| 258 |
-
|
| 259 |
-
#: Accounts that sign in for a process, never a person who can own an item (same list as amazon_profit).
|
| 260 |
-
SERVICE_ACCOUNTS = ("admin", "automation", "scheduler", "qa-runner", "leadership")
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
def _is_service(name, rec):
|
| 264 |
-
name = str(name or "").strip().lower()
|
| 265 |
-
return (not name or name.startswith("qa") or name in SERVICE_ACCOUNTS
|
| 266 |
-
or name.endswith("-admin") or bool(rec.get("platform_admin")))
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
def owner_account(st, tenant_key=None):
|
| 270 |
-
"""P22 (SDLC 78 R31): the tenant's earliest active person Administrator by display name.
|
| 271 |
-
|
| 272 |
-
A tenant with no person Administrator falls back to its `admin` account, else its first Administrator."""
|
| 273 |
-
try:
|
| 274 |
-
users = st.get("users")
|
| 275 |
-
except Exception: # noqa: BLE001
|
| 276 |
-
users = None
|
| 277 |
-
want = str(tenant_key or "").strip().lower()
|
| 278 |
-
admins = [(str(name), rec) for name, rec in (users or {}).items()
|
| 279 |
-
if isinstance(rec, dict) and rec.get("active", True)
|
| 280 |
-
and str(rec.get("role") or "").lower() == "admin"
|
| 281 |
-
and (not want or str(rec.get("tenant") or "royal-imports").strip().lower() == want)]
|
| 282 |
-
people = sorted(((n, r) for n, r in admins if not _is_service(n, r)),
|
| 283 |
-
key=lambda item: ("@" not in item[0], not item[1].get("password_changed_at"),
|
| 284 |
-
str(item[1].get("password_changed_at") or ""), item[0]))
|
| 285 |
-
if people:
|
| 286 |
-
return str(people[0][1].get("name") or people[0][0])
|
| 287 |
-
names = sorted(n for n, _r in admins)
|
| 288 |
-
return "admin" if "admin" in names or not names else names[0]
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
def settings(tenant_key, *, st=None):
|
| 292 |
-
"""Rising thresholds and the default owner, with defaults filled in."""
|
| 293 |
-
st = _rt(tenant_key, st)
|
| 294 |
-
doc = _doc(st, KEY_SETTINGS)
|
| 295 |
-
out = {"risingRatio": float(doc.get("rising_ratio", DEFAULTS["rising_ratio"])),
|
| 296 |
-
"risingMinPct": float(doc.get("rising_min_pct", DEFAULTS["rising_min_pct"]))}
|
| 297 |
-
out["defaultOwnerSetting"] = doc.get("default_owner") or None
|
| 298 |
-
out["defaultOwner"] = out["defaultOwnerSetting"] or owner_account(st, tenant_key)
|
| 299 |
-
out["statuses"] = list(STATUSES)
|
| 300 |
-
out["limit"] = LIMIT
|
| 301 |
-
return out
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
def set_settings(tenant_key, *, rising_ratio=None, rising_min_pct=None, default_owner=None, st=None):
|
| 305 |
-
"""Set the rising ratio (1 to 100), the minimum rate (above 0, below 100 percent) or the default owner."""
|
| 306 |
-
st = _rt(tenant_key, st)
|
| 307 |
-
changes = {}
|
| 308 |
-
for name, value, low, label in (("rising_ratio", rising_ratio, 1.0, "The rising ratio"),
|
| 309 |
-
("rising_min_pct", rising_min_pct, 0.0, "The minimum return rate")):
|
| 310 |
-
if value is None:
|
| 311 |
-
continue
|
| 312 |
-
try:
|
| 313 |
-
number = float(value)
|
| 314 |
-
except (TypeError, ValueError):
|
| 315 |
-
raise ValueError(f"{label} must be a number.") from None
|
| 316 |
-
if not (low <= number < 100 if low else 0 < number < 100):
|
| 317 |
-
raise ValueError(f"{label} must be at least 1 and below 100." if low
|
| 318 |
-
else f"{label} must be above 0 and below 100 percent.")
|
| 319 |
-
changes[name] = number
|
| 320 |
-
|
| 321 |
-
def _apply(doc):
|
| 322 |
-
doc = doc if isinstance(doc, dict) else {}
|
| 323 |
-
doc.update(changes)
|
| 324 |
-
if default_owner is not None:
|
| 325 |
-
doc["default_owner"] = str(default_owner).strip() or None
|
| 326 |
-
return doc
|
| 327 |
-
st.update(KEY_SETTINGS, _apply)
|
| 328 |
-
return settings(tenant_key, st=st)
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
# --------------------------------------------------------------------------- the model
|
| 332 |
-
|
| 333 |
-
def _period(start=None, end=None, now=None):
|
| 334 |
-
"""(start, end) dates, inclusive. The default is the 90 days ending today."""
|
| 335 |
-
def parse(value, label):
|
| 336 |
-
if value in (None, ""):
|
| 337 |
-
return None
|
| 338 |
-
if isinstance(value, dt.date):
|
| 339 |
-
return value
|
| 340 |
-
try:
|
| 341 |
-
return dt.date.fromisoformat(str(value)[:10])
|
| 342 |
-
except ValueError:
|
| 343 |
-
raise ValueError(f"{label} must be a date such as 2026-10-01.") from None
|
| 344 |
-
e = parse(end, "End") or (now or _now()).date()
|
| 345 |
-
s = parse(start, "Start") or e - dt.timedelta(days=PERIOD_DAYS - 1)
|
| 346 |
-
if s > e:
|
| 347 |
-
raise ValueError("Start must be on or before End.")
|
| 348 |
-
return s, e
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
def _key(sku, asin):
|
| 352 |
-
return sku or asin or NO_SKU
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
def _rate(returned, shipped):
|
| 356 |
-
return round(100.0 * returned / shipped, 4) if shipped > 0 else None
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
def _scale(values):
|
| 360 |
-
"""Unknown: whether Amazon sends shares as fractions or percent. All values at or under 1 read as fractions."""
|
| 361 |
-
nums = [abs(v) for v in values if isinstance(v, (int, float))]
|
| 362 |
-
return 100.0 if nums and max(nums) <= 1 else 1.0
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
def _repeat_by_asin(data, start, end):
|
| 366 |
-
"""{asin: repeat facts} over the months that overlap the period; a month outside it never stands in."""
|
| 367 |
-
rows = data["repeat"]
|
| 368 |
-
used = [r for r in rows if r["start"] and r["start"] <= end and (r["end"] or r["start"]) >= start]
|
| 369 |
-
scale = _scale([r["pct"] for r in rows])
|
| 370 |
-
rev_scale = _scale([r["revenuePct"] for r in rows])
|
| 371 |
-
out = {}
|
| 372 |
-
for r in used:
|
| 373 |
-
agg = out.setdefault(r["asin"], {"orders": 0.0, "customers": 0.0, "weighted": 0.0, "plain": [],
|
| 374 |
-
"revenue": 0.0, "hasRevenue": False, "currency": None,
|
| 375 |
-
"revenuePct": [], "months": set()})
|
| 376 |
-
agg["orders"] += r["orders"] or 0
|
| 377 |
-
if isinstance(r["pct"], (int, float)):
|
| 378 |
-
agg["plain"].append(r["pct"] * scale)
|
| 379 |
-
if r["customers"]:
|
| 380 |
-
agg["customers"] += r["customers"]
|
| 381 |
-
agg["weighted"] += r["customers"] * r["pct"] * scale
|
| 382 |
-
if isinstance(r["revenue"], (int, float)):
|
| 383 |
-
agg["revenue"] += r["revenue"]
|
| 384 |
-
agg["hasRevenue"] = True
|
| 385 |
-
if isinstance(r["revenuePct"], (int, float)):
|
| 386 |
-
agg["revenuePct"].append(r["revenuePct"] * rev_scale)
|
| 387 |
-
agg["currency"] = agg["currency"] or r["currency"]
|
| 388 |
-
if r["start"]:
|
| 389 |
-
agg["months"].add(r["start"].isoformat())
|
| 390 |
-
facts = {}
|
| 391 |
-
for asin, agg in out.items():
|
| 392 |
-
share = (agg["weighted"] / agg["customers"] if agg["customers"]
|
| 393 |
-
else (sum(agg["plain"]) / len(agg["plain"]) if agg["plain"] else None))
|
| 394 |
-
facts[asin] = {"asin": asin, "repeatShare": None if share is None else round(share, 4),
|
| 395 |
-
"repeatRevenue": round(agg["revenue"], 2) if agg["hasRevenue"] else None,
|
| 396 |
-
"repeatRevenueShare": (round(sum(agg["revenuePct"]) / len(agg["revenuePct"]), 4)
|
| 397 |
-
if agg["revenuePct"] else None),
|
| 398 |
-
"currency": agg["currency"], "orders": agg["orders"],
|
| 399 |
-
"uniqueCustomers": agg["customers"] or None, "months": sorted(agg["months"]),
|
| 400 |
-
"_weighted": agg["weighted"], "_customers": agg["customers"]}
|
| 401 |
-
return facts
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
def _bought_with(data, asin):
|
| 405 |
-
"""The newest month's frequently-bought-with ASINs for one ASIN, by Amazon's rank."""
|
| 406 |
-
rows = [r for r in data["basket"] if r["asin"] == asin]
|
| 407 |
-
if not rows:
|
| 408 |
-
return []
|
| 409 |
-
newest = max((r["start"] for r in rows if r["start"]), default=None)
|
| 410 |
-
rows = [r for r in rows if r["start"] == newest]
|
| 411 |
-
scale = _scale([r["pct"] for r in data["basket"]])
|
| 412 |
-
rows.sort(key=lambda r: (r["rank"] is None, r["rank"] or 0, r["with"]))
|
| 413 |
-
return [{"asin": r["with"], "rank": r["rank"],
|
| 414 |
-
"combinationPct": None if r["pct"] is None else round(r["pct"] * scale, 4)} for r in rows]
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
def _model(data, start, end, conf):
|
| 418 |
-
"""{key: per-SKU facts} for every SKU the returns or shipments tables hold, plus the windows."""
|
| 419 |
-
w30 = end - dt.timedelta(days=29)
|
| 420 |
-
w90 = end - dt.timedelta(days=89)
|
| 421 |
-
skus = {}
|
| 422 |
-
|
| 423 |
-
def entry(sku, asin):
|
| 424 |
-
k = _key(sku, asin)
|
| 425 |
-
e = skus.get(k)
|
| 426 |
-
if e is None:
|
| 427 |
-
e = skus[k] = {"key": k, "sku": sku or None, "asins": set(), "returned": 0.0, "returnRows": 0,
|
| 428 |
-
"shipped": 0.0, "reasons": {}, "r30": 0.0, "s30": 0.0, "r90": 0.0, "s90": 0.0}
|
| 429 |
-
if asin:
|
| 430 |
-
e["asins"].add(asin)
|
| 431 |
-
return e
|
| 432 |
-
|
| 433 |
-
for sku, asin, day, reason, units, rows in data["returns"]:
|
| 434 |
-
e = entry(sku, asin)
|
| 435 |
-
if day is None:
|
| 436 |
-
continue
|
| 437 |
-
if start <= day <= end:
|
| 438 |
-
e["returned"] += units
|
| 439 |
-
e["returnRows"] += rows
|
| 440 |
-
got = e["reasons"].setdefault(reason or "No reason given", [0.0, 0])
|
| 441 |
-
got[0] += units
|
| 442 |
-
got[1] += rows
|
| 443 |
-
if w30 <= day <= end:
|
| 444 |
-
e["r30"] += units
|
| 445 |
-
if w90 <= day <= end:
|
| 446 |
-
e["r90"] += units
|
| 447 |
-
for sku, asin, day, units in data["shipped"]:
|
| 448 |
-
e = entry(sku, asin)
|
| 449 |
-
if day is None:
|
| 450 |
-
continue
|
| 451 |
-
if start <= day <= end:
|
| 452 |
-
e["shipped"] += units
|
| 453 |
-
if w30 <= day <= end:
|
| 454 |
-
e["s30"] += units
|
| 455 |
-
if w90 <= day <= end:
|
| 456 |
-
e["s90"] += units
|
| 457 |
-
ratio, floor = conf["risingRatio"], conf["risingMinPct"]
|
| 458 |
-
for e in skus.values():
|
| 459 |
-
e["returnRate"] = _rate(e["returned"], e["shipped"])
|
| 460 |
-
e["rate30"] = _rate(e["r30"], e["s30"])
|
| 461 |
-
e["rate90"] = _rate(e["r90"], e["s90"])
|
| 462 |
-
e["rising"] = (e["rate30"] is not None and e["rate90"] is not None
|
| 463 |
-
and e["rate30"] >= ratio * e["rate90"] and e["rate30"] >= floor)
|
| 464 |
-
e["asin"] = sorted(e["asins"])[0] if e["asins"] else None
|
| 465 |
-
reasons = sorted(e["reasons"].items(), key=lambda kv: (-kv[1][0], -kv[1][1], kv[0]))
|
| 466 |
-
e["reasonList"] = [{"reason": r, "label": reason_label(r), "units": u, "count": n}
|
| 467 |
-
for r, (u, n) in reasons]
|
| 468 |
-
return skus
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
def _row(e, repeat=None, item=None):
|
| 472 |
-
rep = (repeat or {}).get(e["asin"]) if e["asin"] else None
|
| 473 |
-
return {"key": e["key"], "sku": e["sku"], "asin": e["asin"], "asins": sorted(e["asins"]),
|
| 474 |
-
"returnedUnits": e["returned"], "shippedUnits": e["shipped"], "returnRate": e["returnRate"],
|
| 475 |
-
"rate30": e["rate30"], "rate90": e["rate90"], "rising": e["rising"],
|
| 476 |
-
"topReason": e["reasonList"][0]["reason"] if e["reasonList"] else None,
|
| 477 |
-
"topReasonLabel": e["reasonList"][0]["label"] if e["reasonList"] else None,
|
| 478 |
-
"repeatShare": rep["repeatShare"] if rep else None,
|
| 479 |
-
"repeatRevenue": rep["repeatRevenue"] if rep else None,
|
| 480 |
-
"itemId": (item or {}).get("id"), "itemStatus": (item or {}).get("status")}
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
def _items_by_sku(st):
|
| 484 |
-
latest = {}
|
| 485 |
-
for item in sorted((_doc(st, KEY_ITEMS).get("items") or {}).values(), key=_seq):
|
| 486 |
-
latest[item.get("sku")] = item
|
| 487 |
-
return latest
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
def _seq(item):
|
| 491 |
-
try:
|
| 492 |
-
return int(str(item.get("id", "r0"))[1:] or 0)
|
| 493 |
-
except ValueError:
|
| 494 |
-
return 0
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
def _page(rows, cursor, limit):
|
| 498 |
-
"""One page of rows and the cursor of the next page (None on the last). No cap on the total."""
|
| 499 |
-
try:
|
| 500 |
-
offset = int(cursor) if cursor not in (None, "") else 0
|
| 501 |
-
except (TypeError, ValueError):
|
| 502 |
-
raise ValueError("The cursor is not valid. Start again from the first page.") from None
|
| 503 |
-
try:
|
| 504 |
-
size = int(limit) if limit is not None else len(rows) or 1
|
| 505 |
-
except (TypeError, ValueError):
|
| 506 |
-
raise ValueError("The page size must be a number.") from None
|
| 507 |
-
if offset < 0 or size < 1:
|
| 508 |
-
raise ValueError("The cursor is not valid. Start again from the first page.")
|
| 509 |
-
nxt = offset + size
|
| 510 |
-
return rows[offset:nxt], (str(nxt) if nxt < len(rows) else None)
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
# --------------------------------------------------------------------------- read surfaces
|
| 514 |
-
|
| 515 |
-
def _share(repeat):
|
| 516 |
-
"""The customer-weighted repeat purchase share over {asin: facts}, else the plain mean, else None."""
|
| 517 |
-
customers = sum(f["_customers"] for f in repeat.values())
|
| 518 |
-
plain = [f["repeatShare"] for f in repeat.values() if f["repeatShare"] is not None]
|
| 519 |
-
return (round(sum(f["_weighted"] for f in repeat.values()) / customers, 4) if customers
|
| 520 |
-
else (round(sum(plain) / len(plain), 4) if plain else None))
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
def _trend(data, start, end):
|
| 524 |
-
"""Weekly buckets from `start`, the last one cut at `end`: [{start, end, returnRate}]."""
|
| 525 |
-
count = (end - start).days // TREND_DAYS + 1
|
| 526 |
-
sums = [[0.0, 0.0] for _ in range(count)]
|
| 527 |
-
for _sku, _asin, day, _reason, units, _rows in data["returns"]:
|
| 528 |
-
if day is not None and start <= day <= end:
|
| 529 |
-
sums[(day - start).days // TREND_DAYS][0] += units
|
| 530 |
-
for _sku, _asin, day, units in data["shipped"]:
|
| 531 |
-
if day is not None and start <= day <= end:
|
| 532 |
-
sums[(day - start).days // TREND_DAYS][1] += units
|
| 533 |
-
out = []
|
| 534 |
-
for i, (returned, shipped) in enumerate(sums):
|
| 535 |
-
b0 = start + dt.timedelta(days=i * TREND_DAYS)
|
| 536 |
-
b1 = min(end, b0 + dt.timedelta(days=TREND_DAYS - 1))
|
| 537 |
-
out.append({"start": b0.isoformat(), "end": b1.isoformat(), "returnRate": _rate(returned, shipped)})
|
| 538 |
-
return out
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
def _previous(data, start, end, conf):
|
| 542 |
-
"""The KPIs of the period of equal length ending the day before `start`. No month fallback."""
|
| 543 |
-
p1 = start - dt.timedelta(days=1)
|
| 544 |
-
p0 = p1 - (end - start)
|
| 545 |
-
model = _model(data, p0, p1, conf)
|
| 546 |
-
returned = sum(x["returned"] for x in model.values())
|
| 547 |
-
shipped = sum(x["shipped"] for x in model.values())
|
| 548 |
-
return {"start": p0.isoformat(), "end": p1.isoformat(), "returnRate": _rate(returned, shipped),
|
| 549 |
-
"repeatShare": _share(_repeat_by_asin(data, p0, p1))}
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
def _page_size(value):
|
| 553 |
-
"""Bound transport without capping the source."""
|
| 554 |
-
try:
|
| 555 |
-
size = int(value)
|
| 556 |
-
except (TypeError, ValueError, OverflowError):
|
| 557 |
-
raise ValueError("The page size must be a whole number.") from None
|
| 558 |
-
if size < 1:
|
| 559 |
-
raise ValueError("The page size must be at least 1.")
|
| 560 |
-
return min(size, MAX_PAGE_SIZE)
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
def _offset(cursor):
|
| 564 |
-
try:
|
| 565 |
-
offset = int(cursor) if cursor not in (None, "") else 0
|
| 566 |
-
except (TypeError, ValueError, OverflowError):
|
| 567 |
-
raise ValueError("The cursor is not valid. Start again from the first page.") from None
|
| 568 |
-
if offset < 0:
|
| 569 |
-
raise ValueError("The cursor is not valid. Start again from the first page.")
|
| 570 |
-
return offset
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
def _navigation(offset, limit, total):
|
| 574 |
-
return {"offset": offset, "limit": limit, "total": total,
|
| 575 |
-
"cursor": str(offset + limit) if offset + limit < total else None,
|
| 576 |
-
"previousCursor": str(max(0, offset - limit)) if offset else None}
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
def _sql_scope(st):
|
| 580 |
-
"""Resolve the tenant-bound Postgres document namespace."""
|
| 581 |
-
from core import store_pg
|
| 582 |
-
backend = st._document_store() if callable(getattr(st, "_document_store", None)) else st
|
| 583 |
-
if not isinstance(backend, store_pg.PgStore):
|
| 584 |
-
raise RuntimeError("The returns screen requires a store with server paging.")
|
| 585 |
-
tenant = backend.tenant_slug
|
| 586 |
-
if getattr(st, "key", tenant) != tenant:
|
| 587 |
-
raise PermissionError("The returns store belongs to another tenant.")
|
| 588 |
-
return store_pg, tenant, getattr(st, "store_key", str)
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
def _store_select(st, sql, params):
|
| 592 |
-
"""Transfer one aggregate or bounded page from the tenant document store."""
|
| 593 |
-
from core import request_timing
|
| 594 |
-
pg, tenant, key = _sql_scope(st)
|
| 595 |
-
started = time.perf_counter()
|
| 596 |
-
with pg._pool().connection() as con:
|
| 597 |
-
row = con.execute(pg._q(sql, "store_kv", tenant), params(key)).fetchone()
|
| 598 |
-
value = row[0] if row else None
|
| 599 |
-
value = json.loads(value) if isinstance(value, str) else value
|
| 600 |
-
request_timing.record_store("returns_repeat_page", key(KEY_ITEMS), bytes_read=len(json.dumps(value).encode()),
|
| 601 |
-
milliseconds=(time.perf_counter() - started) * 1000)
|
| 602 |
-
return value
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
ITEM_PAGE_SQL = """
|
| 606 |
-
WITH doc AS (SELECT value FROM {tbl} WHERE key=%s), picked AS MATERIALIZED (
|
| 607 |
-
SELECT e.value AS v FROM doc, LATERAL jsonb_each(COALESCE(value->'items', '{{}}'::jsonb)) e
|
| 608 |
-
WHERE (%s::text IS NULL OR (e.value->>'status')=%s) AND (%s::text IS NULL OR (e.value->>'sku')=%s)
|
| 609 |
-
), page AS (SELECT v FROM picked ORDER BY CAST(substring(v->>'id' FROM 2) AS bigint) DESC
|
| 610 |
-
LIMIT %s OFFSET %s)
|
| 611 |
-
SELECT jsonb_build_object('total', (SELECT count(*) FROM picked),
|
| 612 |
-
'items', (SELECT jsonb_agg(v - 'history' ORDER BY CAST(substring(v->>'id' FROM 2) AS bigint) DESC) FROM page))
|
| 613 |
-
"""
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
def _item_page(st, *, status=None, sku=None, offset=0, limit=100):
|
| 617 |
-
out = _store_select(st, ITEM_PAGE_SQL, lambda key: (key(KEY_ITEMS), status, status, sku, sku, limit, offset))
|
| 618 |
-
return {"items": [_public(item) for item in out.get("items") or []],
|
| 619 |
-
**_navigation(offset, limit, int(out["total"]))}
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
HISTORY_SQL = """
|
| 623 |
-
WITH points AS MATERIALIZED (
|
| 624 |
-
SELECT e.key AS day, e.value->%s::text AS point FROM {tbl} kv,
|
| 625 |
-
LATERAL jsonb_each(COALESCE(kv.value->'snapshots', '{{}}'::jsonb)) e
|
| 626 |
-
WHERE kv.key=%s AND jsonb_typeof(e.value->%s::text)='array' AND jsonb_array_length(e.value->%s::text)>=2
|
| 627 |
-
), page AS (SELECT day, point FROM points ORDER BY day LIMIT %s OFFSET %s)
|
| 628 |
-
SELECT jsonb_build_object('total', (SELECT count(*) FROM points), 'rows',
|
| 629 |
-
(SELECT jsonb_agg(jsonb_build_object('date', day, 'rate30', point->0, 'rate90', point->1) ORDER BY day) FROM page))
|
| 630 |
-
"""
|
| 631 |
-
EVENTS_SQL = """
|
| 632 |
-
WITH latest AS (
|
| 633 |
-
SELECT e.value AS v FROM {tbl} kv, LATERAL jsonb_each(COALESCE(kv.value->'items', '{{}}'::jsonb)) e
|
| 634 |
-
WHERE kv.key=%s AND (e.value->>'sku')=%s
|
| 635 |
-
ORDER BY CAST(substring(e.value->>'id' FROM 2) AS bigint) DESC LIMIT 1
|
| 636 |
-
), points AS MATERIALIZED (
|
| 637 |
-
SELECT a.value AS point, a.n FROM latest,
|
| 638 |
-
LATERAL jsonb_array_elements(COALESCE(v->'history', '[]'::jsonb)) WITH ORDINALITY a(value,n)
|
| 639 |
-
), page AS (SELECT point,n FROM points ORDER BY n LIMIT %s OFFSET %s)
|
| 640 |
-
SELECT jsonb_build_object('total', (SELECT count(*) FROM points),
|
| 641 |
-
'rows', (SELECT jsonb_agg(point ORDER BY n) FROM page))
|
| 642 |
-
"""
|
| 643 |
-
ITEM_LOOKUP_SQL = """
|
| 644 |
-
WITH ranked AS (
|
| 645 |
-
SELECT e.value AS v, row_number() OVER (PARTITION BY e.value->>'sku'
|
| 646 |
-
ORDER BY CAST(substring(e.value->>'id' FROM 2) AS bigint) DESC) AS n
|
| 647 |
-
FROM {tbl} kv, LATERAL jsonb_each(COALESCE(kv.value->'items', '{{}}'::jsonb)) e
|
| 648 |
-
WHERE kv.key=%s AND (e.value->>'sku')=ANY(%s::text[])
|
| 649 |
-
)
|
| 650 |
-
SELECT COALESCE(jsonb_object_agg(v->>'sku', v - 'history'), '{{}}'::jsonb) FROM ranked WHERE n=1
|
| 651 |
-
"""
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
def _sql_day(expr):
|
| 655 |
-
return (f"COALESCE(TRY_CAST(SUBSTR({expr}, 1, 10) AS DATE), "
|
| 656 |
-
f"CAST(TRY_STRPTIME(split_part({expr}, ' ', 1), ['%m/%d/%Y', '%Y/%m/%d']) AS DATE), "
|
| 657 |
-
f"CAST(TRY_STRPTIME({expr}, ['%m/%d/%Y', '%Y/%m/%d', '%d-%b-%Y', '%b %d, %Y']) AS DATE))")
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
def _relations(cur, start, end, conf):
|
| 661 |
-
"""SQL relations retain source rows and grouped metrics inside the mirror."""
|
| 662 |
-
def source(table, fields):
|
| 663 |
-
cols = _columns(cur, table)
|
| 664 |
-
values = []
|
| 665 |
-
for alias, names, kind in fields:
|
| 666 |
-
name = _first(cols, *names)
|
| 667 |
-
expr = _num(cols, name) if kind == "num" else _text(cols, name)
|
| 668 |
-
if kind == "day":
|
| 669 |
-
expr = _sql_day(expr)
|
| 670 |
-
elif kind == "text":
|
| 671 |
-
expr = f"NULLIF(trim({expr}), '')"
|
| 672 |
-
if alias == "units":
|
| 673 |
-
expr = f"COALESCE({expr}, 0)" if name else "CAST(1 AS DOUBLE)"
|
| 674 |
-
values.append(f"{expr} AS {alias}")
|
| 675 |
-
invalid_identity = table in (RETURNS_TABLE, SHIPPED_TABLE) and not cols & {"sku", "asin"}
|
| 676 |
-
return "SELECT " + ", ".join(values) + (f" FROM {table}" if cols else "") + (
|
| 677 |
-
" WHERE false" if not cols or invalid_identity else "")
|
| 678 |
-
|
| 679 |
-
identity = [("sku", ("sku",), "text"), ("asin", ("asin",), "text")]
|
| 680 |
-
r = source(RETURNS_TABLE, identity + [("day", ("return_date",), "day"),
|
| 681 |
-
("reason", ("reason",), "text"), ("units", ("quantity",), "num")])
|
| 682 |
-
sh = source(SHIPPED_TABLE, identity + [("day", ("shipment_date",), "day"), ("units", ("quantity",), "num")])
|
| 683 |
-
p = source(REPEAT_TABLE, [("asin", ("asin",), "text"), ("start", ("start_date", "_period_start"), "day"),
|
| 684 |
-
("finish", ("end_date", "_period_end"), "day"), ("orders", ("orders",), "num"),
|
| 685 |
-
("customers", ("unique_customers",), "num"), ("pct", ("repeat_customers_pct_total",), "num"),
|
| 686 |
-
("revenue", ("repeat_purchase_revenue_amount",), "num"),
|
| 687 |
-
("currency", ("repeat_purchase_revenue_currency_code",), "text"),
|
| 688 |
-
("rev_pct", ("repeat_purchase_revenue_pct_total",), "num")])
|
| 689 |
-
b = source(BASKET_TABLE, [("asin", ("asin",), "text"), ("partner", ("purchased_with_asin",), "text"),
|
| 690 |
-
("rank", ("purchased_with_rank",), "num"), ("pct", ("combination_pct",), "num"),
|
| 691 |
-
("start", ("start_date", "_period_start"), "day")])
|
| 692 |
-
s, e = start.isoformat(), end.isoformat()
|
| 693 |
-
w30, w90 = (end - dt.timedelta(days=29)).isoformat(), (end - dt.timedelta(days=89)).isoformat()
|
| 694 |
-
ratio, floor = float(conf["risingRatio"]), float(conf["risingMinPct"])
|
| 695 |
-
return f"""WITH r0 AS ({r}), s0 AS ({sh}), p_raw AS ({p}), b_raw AS ({b}),
|
| 696 |
-
p0 AS (SELECT * FROM p_raw WHERE asin IS NOT NULL),
|
| 697 |
-
b0 AS (SELECT * FROM b_raw WHERE asin IS NOT NULL AND partner IS NOT NULL),
|
| 698 |
-
events AS (
|
| 699 |
-
SELECT COALESCE(sku, asin, '{NO_SKU}') AS key, sku, asin, day, units AS ret, 0.0 AS ship FROM r0
|
| 700 |
-
UNION ALL SELECT COALESCE(sku, asin, '{NO_SKU}'), sku, asin, day, 0.0, units FROM s0
|
| 701 |
-
), links AS (SELECT DISTINCT key, asin FROM events WHERE asin IS NOT NULL),
|
| 702 |
-
sums AS (SELECT key, MIN(sku) AS sku, MIN(asin) AS asin,
|
| 703 |
-
COALESCE(SUM(ret) FILTER (WHERE day BETWEEN DATE '{s}' AND DATE '{e}'), 0) AS returned,
|
| 704 |
-
COALESCE(SUM(ship) FILTER (WHERE day BETWEEN DATE '{s}' AND DATE '{e}'), 0) AS shipped,
|
| 705 |
-
COALESCE(SUM(ret) FILTER (WHERE day BETWEEN DATE '{w30}' AND DATE '{e}'), 0) AS r30,
|
| 706 |
-
COALESCE(SUM(ship) FILTER (WHERE day BETWEEN DATE '{w30}' AND DATE '{e}'), 0) AS s30,
|
| 707 |
-
COALESCE(SUM(ret) FILTER (WHERE day BETWEEN DATE '{w90}' AND DATE '{e}'), 0) AS r90,
|
| 708 |
-
COALESCE(SUM(ship) FILTER (WHERE day BETWEEN DATE '{w90}' AND DATE '{e}'), 0) AS s90
|
| 709 |
-
FROM events GROUP BY key),
|
| 710 |
-
rates AS (SELECT *, round(100.0*returned/NULLIF(shipped,0),4) AS return_rate,
|
| 711 |
-
round(100.0*r30/NULLIF(s30,0),4) AS rate30, round(100.0*r90/NULLIF(s90,0),4) AS rate90 FROM sums),
|
| 712 |
-
model AS (SELECT *, COALESCE(rate30>={ratio}*rate90 AND rate30>={floor},false) AS rising FROM rates),
|
| 713 |
-
scales AS (SELECT CASE WHEN MAX(abs(pct))<=1 THEN 100.0 ELSE 1.0 END AS pct_scale,
|
| 714 |
-
CASE WHEN MAX(abs(rev_pct))<=1 THEN 100.0 ELSE 1.0 END AS rev_scale FROM p0),
|
| 715 |
-
used_repeat AS (SELECT p0.* FROM p0 WHERE asin IS NOT NULL
|
| 716 |
-
AND start<=DATE '{e}' AND COALESCE(finish,start)>=DATE '{s}'),
|
| 717 |
-
rep_sums AS (SELECT asin, SUM(COALESCE(orders,0)) AS orders,
|
| 718 |
-
SUM(CASE WHEN pct IS NOT NULL THEN COALESCE(customers,0) ELSE 0 END) AS customers,
|
| 719 |
-
SUM(COALESCE(customers*pct*pct_scale,0)) AS weighted, AVG(pct*pct_scale) AS plain,
|
| 720 |
-
SUM(revenue) AS revenue, AVG(rev_pct*rev_scale) AS revenue_share,
|
| 721 |
-
first(currency ORDER BY start, finish, currency) FILTER (WHERE currency IS NOT NULL) AS currency
|
| 722 |
-
FROM used_repeat CROSS JOIN scales GROUP BY asin),
|
| 723 |
-
repeats AS (SELECT *, round(CASE WHEN customers<>0 THEN weighted/customers ELSE plain END,4) AS share
|
| 724 |
-
FROM rep_sums),
|
| 725 |
-
reason_totals AS (SELECT COALESCE(sku,asin,'{NO_SKU}') AS key, COALESCE(reason,'No reason given') AS reason,
|
| 726 |
-
SUM(units) AS units, count(*) AS n FROM r0 WHERE day BETWEEN DATE '{s}' AND DATE '{e}' GROUP BY 1,2),
|
| 727 |
-
reason_rank AS (SELECT *, row_number() OVER (PARTITION BY key ORDER BY units DESC,n DESC,reason) AS pos
|
| 728 |
-
FROM reason_totals),
|
| 729 |
-
sku_facts AS (SELECT model.*, reason_rank.reason AS top_reason, repeats.share AS repeat_share,
|
| 730 |
-
round(repeats.revenue,2) AS repeat_revenue FROM model
|
| 731 |
-
LEFT JOIN reason_rank ON model.key=reason_rank.key AND reason_rank.pos=1
|
| 732 |
-
LEFT JOIN repeats ON model.asin=repeats.asin)
|
| 733 |
-
"""
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
@contextlib.contextmanager
|
| 737 |
-
def _screen_reader(tenant_key, st):
|
| 738 |
-
with _reader(tenant_key, st) as cur:
|
| 739 |
-
if cur is not None:
|
| 740 |
-
yield cur, True
|
| 741 |
-
else:
|
| 742 |
-
import duckdb
|
| 743 |
-
con = duckdb.connect()
|
| 744 |
-
try:
|
| 745 |
-
yield con, False
|
| 746 |
-
finally:
|
| 747 |
-
con.close()
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
def _mirror_one(cur, sql, params=()):
|
| 751 |
-
result = cur.execute(sql, params)
|
| 752 |
-
names = [field[0] for field in result.description]
|
| 753 |
-
row = result.fetchone()
|
| 754 |
-
return dict(zip(names, row)) if row else None
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
def _mirror_page(cur, sql, params, offset, limit):
|
| 758 |
-
result = cur.execute(sql + " LIMIT ? OFFSET ?", [*params, limit, offset])
|
| 759 |
-
names = [field[0] for field in result.description]
|
| 760 |
-
return [dict(zip(names, row)) for row in result.fetchmany(limit)]
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
def _collection(cur, base, query, params, offset, limit):
|
| 764 |
-
total = int(_mirror_one(cur, base + "SELECT count(*) AS n FROM (" + query + ") counted", params)["n"])
|
| 765 |
-
return _mirror_page(cur, base + query, params, offset, limit), total
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
def _sku_row(row, item=None):
|
| 769 |
-
reason = row["top_reason"]
|
| 770 |
-
return {"key": row["key"], "sku": row["sku"], "asin": row["asin"],
|
| 771 |
-
"returnedUnits": row["returned"], "shippedUnits": row["shipped"], "returnRate": row["return_rate"],
|
| 772 |
-
"rate30": row["rate30"], "rate90": row["rate90"], "rising": row["rising"],
|
| 773 |
-
"topReason": reason, "topReasonLabel": reason_label(reason) if reason else None,
|
| 774 |
-
"repeatShare": row["repeat_share"], "repeatRevenue": row["repeat_revenue"],
|
| 775 |
-
"itemId": (item or {}).get("id"), "itemStatus": (item or {}).get("status")}
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
def _aggregate(cur, base):
|
| 779 |
-
metrics = _mirror_one(cur, base + "SELECT COALESCE(SUM(returned),0) AS returned, "
|
| 780 |
-
"COALESCE(SUM(shipped),0) AS shipped, count(*) AS highest, count(*) FILTER (WHERE rising) AS rising FROM model")
|
| 781 |
-
rep = _mirror_one(cur, base + "SELECT count(*) AS n, round(CASE WHEN SUM(customers)<>0 "
|
| 782 |
-
"THEN SUM(weighted)/SUM(customers) ELSE AVG(share) END,4) AS share, round(SUM(revenue),2) AS revenue FROM repeats")
|
| 783 |
-
return {"returnedUnits": metrics["returned"], "shippedUnits": metrics["shipped"],
|
| 784 |
-
"returnRate": _rate(metrics["returned"], metrics["shipped"]), "repeatShare": rep["share"],
|
| 785 |
-
"repeatRevenue": rep["revenue"], "counts": {"highest": metrics["highest"],
|
| 786 |
-
"rising": metrics["rising"], "repeat": rep["n"]}}
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
def summary(tenant_key, *, start=None, end=None, cursor=None, limit=24, st=None, now=None):
|
| 790 |
-
"""Return complete SQL totals and one bounded page of weekly buckets and repeat months."""
|
| 791 |
-
st = _rt(tenant_key, st)
|
| 792 |
-
s, e = _period(start, end, now)
|
| 793 |
-
offset, limit = _offset(cursor), _page_size(limit)
|
| 794 |
-
conf = settings(tenant_key, st=st)
|
| 795 |
-
with _screen_reader(tenant_key, st) as (cur, present):
|
| 796 |
-
base = _relations(cur, s, e, conf)
|
| 797 |
-
out = _aggregate(cur, base)
|
| 798 |
-
p1 = s - dt.timedelta(days=1)
|
| 799 |
-
p0 = p1 - (e - s)
|
| 800 |
-
previous = _aggregate(cur, _relations(cur, p0, p1, conf))
|
| 801 |
-
months, month_total = _collection(cur, base, "SELECT DISTINCT start FROM used_repeat ORDER BY start", [], offset, limit)
|
| 802 |
-
trend_total = (e - s).days // TREND_DAYS + 1
|
| 803 |
-
buckets = ("SELECT CAST(? AS DATE) + CAST(i*7 AS INTEGER) AS start, "
|
| 804 |
-
"LEAST(CAST(? AS DATE), CAST(? AS DATE) + CAST(i*7+6 AS INTEGER)) AS finish "
|
| 805 |
-
"FROM range(?) t(i) ORDER BY i LIMIT ? OFFSET ?")
|
| 806 |
-
trend = _mirror_page(cur, base + "SELECT start, finish AS end, "
|
| 807 |
-
"round(100.0*(SELECT COALESCE(SUM(units),0) FROM r0 WHERE day BETWEEN buckets.start AND buckets.finish)/"
|
| 808 |
-
"NULLIF((SELECT SUM(units) FROM s0 WHERE day BETWEEN buckets.start AND buckets.finish),0),4) AS rate "
|
| 809 |
-
"FROM (" + buckets + ") buckets ORDER BY start", [s, e, s, trend_total, limit, offset], 0, limit)
|
| 810 |
-
out.update({"repeatMonths": [m["start"].isoformat() for m in months],
|
| 811 |
-
"trend": [{"start": p["start"].isoformat(), "end": p["end"].isoformat(),
|
| 812 |
-
"returnRate": p["rate"]} for p in trend]})
|
| 813 |
-
return {**out, **_navigation(offset, limit, max(trend_total, month_total)),
|
| 814 |
-
"collectionTotals": {"trend": trend_total, "repeatMonths": month_total},
|
| 815 |
-
"period": {"start": s.isoformat(), "end": e.isoformat()}, "mirror": present,
|
| 816 |
-
"empty": out["returnedUnits"] == 0, "emptyMessage": EMPTY if out["returnedUnits"] == 0 else None,
|
| 817 |
-
"openItems": _item_page(st, status="Open", limit=1)["total"], "segments": dict(SEGMENTS),
|
| 818 |
-
"previous": {"start": p0.isoformat(), "end": p1.isoformat(),
|
| 819 |
-
"returnRate": previous["returnRate"], "repeatShare": previous["repeatShare"]}}
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
def skus(tenant_key, *, segment="highest", start=None, end=None, cursor=None, limit=100, q=None, st=None, now=None):
|
| 823 |
-
"""Search and select one page in SQL without loading source rows or child arrays."""
|
| 824 |
-
if segment not in SEGMENTS:
|
| 825 |
-
raise ValueError("Segment must be one of: " + ", ".join(SEGMENTS) + ".")
|
| 826 |
-
st = _rt(tenant_key, st)
|
| 827 |
-
s, e = _period(start, end, now)
|
| 828 |
-
offset, limit = _offset(cursor), _page_size(limit)
|
| 829 |
-
needle = " ".join(str(q or "").split()).lower()
|
| 830 |
-
with _screen_reader(tenant_key, st) as (cur, _present):
|
| 831 |
-
base = _relations(cur, s, e, settings(tenant_key, st=st))
|
| 832 |
-
if segment == "repeat":
|
| 833 |
-
query = ("SELECT asin AS key, asin, share AS \"repeatShare\", round(revenue,2) AS \"repeatRevenue\", "
|
| 834 |
-
"currency, orders, NULLIF(customers,0) AS \"uniqueCustomers\", "
|
| 835 |
-
"(SELECT count(*) FROM links WHERE links.asin=repeats.asin) AS \"skuCount\" FROM repeats "
|
| 836 |
-
"WHERE (?='' OR contains(lower(asin),?) OR EXISTS "
|
| 837 |
-
"(SELECT 1 FROM links WHERE links.asin=repeats.asin AND contains(lower(key),?))) "
|
| 838 |
-
"ORDER BY share DESC NULLS LAST, asin")
|
| 839 |
-
else:
|
| 840 |
-
query = ("SELECT * FROM sku_facts WHERE (?='' OR contains(lower(key),?) OR EXISTS "
|
| 841 |
-
"(SELECT 1 FROM links WHERE links.key=sku_facts.key AND contains(lower(asin),?))) "
|
| 842 |
-
+ ("AND rising " if segment == "rising" else "")
|
| 843 |
-
+ ("ORDER BY rate30 DESC, key" if segment == "rising"
|
| 844 |
-
else "ORDER BY return_rate DESC NULLS LAST, returned DESC, key"))
|
| 845 |
-
rows, total = _collection(cur, base, query, [needle, needle, needle], offset, limit)
|
| 846 |
-
if segment != "repeat":
|
| 847 |
-
keys = [row["key"] for row in rows]
|
| 848 |
-
owned = _store_select(st, ITEM_LOOKUP_SQL, lambda key: (key(KEY_ITEMS), keys)) if keys else {}
|
| 849 |
-
rows = [_sku_row(row, owned.get(row["key"])) for row in rows]
|
| 850 |
-
return {"segment": segment, "label": SEGMENTS[segment], "period": {"start": s.isoformat(), "end": e.isoformat()},
|
| 851 |
-
"q": needle or None, "rows": rows, **_navigation(offset, limit, total)}
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
def detail(tenant_key, key, *, start=None, end=None, cursor=None, limit=25, st=None, now=None):
|
| 855 |
-
"""Read scalar SKU facts and bounded pages of every nested collection."""
|
| 856 |
-
want = _clean(key)
|
| 857 |
-
if not want:
|
| 858 |
-
raise ValueError("Name a SKU or an ASIN.")
|
| 859 |
-
st = _rt(tenant_key, st)
|
| 860 |
-
s, e = _period(start, end, now)
|
| 861 |
-
offset, limit = _offset(cursor), _page_size(limit)
|
| 862 |
-
with _screen_reader(tenant_key, st) as (cur, _present):
|
| 863 |
-
base = _relations(cur, s, e, settings(tenant_key, st=st))
|
| 864 |
-
found = _mirror_one(cur, base + "SELECT * FROM model WHERE key=? OR EXISTS "
|
| 865 |
-
"(SELECT 1 FROM links WHERE links.key=model.key AND asin=?) ORDER BY (key=?) DESC, key LIMIT 1",
|
| 866 |
-
[want, want, want])
|
| 867 |
-
sku = found["key"] if found else None
|
| 868 |
-
direct = _mirror_one(cur, base + "SELECT 1 AS n FROM links WHERE key=? AND asin=? LIMIT 1", [sku, want])
|
| 869 |
-
asin = want if not found or direct else found["asin"]
|
| 870 |
-
rep = _mirror_one(cur, base + 'SELECT asin, share AS "repeatShare", round(revenue,2) AS "repeatRevenue", '
|
| 871 |
-
'round(revenue_share,4) AS "repeatRevenueShare", currency, orders, NULLIF(customers,0) AS "uniqueCustomers" '
|
| 872 |
-
"FROM repeats WHERE asin=?", [asin])
|
| 873 |
-
basket = _mirror_one(cur, base + "SELECT 1 AS n FROM b0 WHERE asin=? LIMIT 1", [want])
|
| 874 |
-
if not found and not rep and not basket:
|
| 875 |
-
raise KeyError(want)
|
| 876 |
-
out, totals = {}, {}
|
| 877 |
-
queries = {
|
| 878 |
-
"reasons": ("SELECT COALESCE(reason,'No reason given') AS reason, SUM(units) AS units, count(*) AS count "
|
| 879 |
-
"FROM r0 WHERE COALESCE(sku,asin,?)=? AND day BETWEEN ? AND ? GROUP BY reason "
|
| 880 |
-
"ORDER BY units DESC, count DESC, reason", [NO_SKU, sku, s, e]),
|
| 881 |
-
"skus": ("SELECT key FROM links WHERE asin=? ORDER BY key", [asin]),
|
| 882 |
-
"asins": ("SELECT asin FROM links WHERE key=? ORDER BY asin", [sku]),
|
| 883 |
-
"repeatMonths": ("SELECT DISTINCT start FROM used_repeat WHERE asin=? ORDER BY start", [asin]),
|
| 884 |
-
"boughtWith": ("SELECT partner AS asin, rank, round(pct*(SELECT CASE WHEN MAX(abs(pct))<=1 "
|
| 885 |
-
"THEN 100.0 ELSE 1.0 END FROM b0),4) AS \"combinationPct\" FROM b0 WHERE asin=? "
|
| 886 |
-
"AND partner IS NOT NULL AND start IS NOT DISTINCT FROM (SELECT MAX(start) FROM b0 WHERE asin=?) "
|
| 887 |
-
"ORDER BY rank NULLS LAST, partner", [asin, asin]),
|
| 888 |
-
}
|
| 889 |
-
for name, (query, params) in queries.items():
|
| 890 |
-
out[name], totals[name] = _collection(cur, base, query, params, offset, limit)
|
| 891 |
-
out["reasons"] = [{**r, "label": reason_label(r["reason"])} for r in out["reasons"]]
|
| 892 |
-
out["skus"] = [r["key"] for r in out["skus"]]
|
| 893 |
-
out["asins"] = [r["asin"] for r in out["asins"]]
|
| 894 |
-
out["repeatMonths"] = [r["start"].isoformat() for r in out["repeatMonths"]]
|
| 895 |
-
for name, sql, args in (
|
| 896 |
-
("history", HISTORY_SQL, lambda key: (sku, key(KEY_HISTORY), sku, sku, limit, offset)),
|
| 897 |
-
("itemHistory", EVENTS_SQL, lambda key: (key(KEY_ITEMS), sku, limit, offset))):
|
| 898 |
-
page = _store_select(st, sql, args)
|
| 899 |
-
out[name], totals[name] = page.get("rows") or [], int(page["total"])
|
| 900 |
-
item = _item_page(st, sku=sku, limit=1)["items"] if sku else []
|
| 901 |
-
return {**out, **_navigation(offset, limit, max(totals.values())), "collectionTotals": totals,
|
| 902 |
-
"key": want, "sku": found["sku"] if found else None, "asin": asin,
|
| 903 |
-
"period": {"start": s.isoformat(), "end": e.isoformat()},
|
| 904 |
-
"returnedUnits": found["returned"] if found else 0.0,
|
| 905 |
-
"shippedUnits": found["shipped"] if found else 0.0,
|
| 906 |
-
"returnRate": found["return_rate"] if found else None,
|
| 907 |
-
"rate30": found["rate30"] if found else None, "rate90": found["rate90"] if found else None,
|
| 908 |
-
"rising": bool(found and found["rising"]), "repeat": rep,
|
| 909 |
-
"repeatShare": rep["repeatShare"] if rep else None,
|
| 910 |
-
"repeatRevenue": rep["repeatRevenue"] if rep else None,
|
| 911 |
-
"item": item[0] if item else None, "emptyMessage": EMPTY if not found or not found["returned"] else None}
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
# --------------------------------------------------------------------------- the after-sync recompute
|
| 915 |
-
|
| 916 |
-
def _table_name(name):
|
| 917 |
-
text = str(name or "").strip().lower()
|
| 918 |
-
for prefix in ("ut_", "amzn_"):
|
| 919 |
-
if text.startswith(prefix):
|
| 920 |
-
text = text[len(prefix):]
|
| 921 |
-
return "amzn_" + text
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
def on_amazon_sync(tenant_key, synced_tables):
|
| 925 |
-
"""Contract C5 callback: recompute after any of the four tables synced. Never raises."""
|
| 926 |
-
try:
|
| 927 |
-
if not {_table_name(t) for t in synced_tables or ()} & set(TABLES):
|
| 928 |
-
return {"state": "skipped"}
|
| 929 |
-
return recompute(tenant_key)
|
| 930 |
-
except Exception as exc: # noqa: BLE001
|
| 931 |
-
LOG.warning("returns_repeat: the after-sync recompute failed for %s (%s): %s",
|
| 932 |
-
tenant_key, type(exc).__name__, exc)
|
| 933 |
-
return {"state": "failed"}
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
def recompute(tenant_key, *, st=None, now=None):
|
| 937 |
-
"""Refresh snapshots and rising items from bounded SQL batches after a background sync."""
|
| 938 |
-
st = _rt(tenant_key, st)
|
| 939 |
-
now = now or _now()
|
| 940 |
-
conf = settings(tenant_key, st=st)
|
| 941 |
-
today = now.date()
|
| 942 |
-
created, rising = [], []
|
| 943 |
-
count = created_count = rising_count = 0
|
| 944 |
-
with _screen_reader(tenant_key, st) as (cur, present):
|
| 945 |
-
if not present:
|
| 946 |
-
return {"state": "no_mirror", "created": []}
|
| 947 |
-
base = _relations(cur, today - dt.timedelta(days=PERIOD_DAYS - 1), today, conf)
|
| 948 |
-
while True:
|
| 949 |
-
rows = _mirror_page(cur, base + "SELECT * FROM sku_facts ORDER BY key", [], count, MAX_PAGE_SIZE)
|
| 950 |
-
ids = _refresh_batch(st, rows, now, conf["defaultOwner"], reset=count == 0)
|
| 951 |
-
created_count += len(ids)
|
| 952 |
-
created.extend(ids[:MAX_PAGE_SIZE - len(created)])
|
| 953 |
-
keys = [row["key"] for row in rows if row["rising"]]
|
| 954 |
-
rising_count += len(keys)
|
| 955 |
-
rising.extend(keys[:MAX_PAGE_SIZE - len(rising)])
|
| 956 |
-
count += len(rows)
|
| 957 |
-
if len(rows) < MAX_PAGE_SIZE:
|
| 958 |
-
break
|
| 959 |
-
return {"state": "computed", "date": today.isoformat(), "skus": count, "rising": rising,
|
| 960 |
-
"created": created, "risingCount": rising_count, "createdCount": created_count,
|
| 961 |
-
"previewLimit": MAX_PAGE_SIZE}
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
def _refresh_batch(st, rows, now, owner, *, reset=False):
|
| 965 |
-
"""Merge a bounded snapshot and new items without transferring either containing document."""
|
| 966 |
-
pg, tenant, key = _sql_scope(st)
|
| 967 |
-
names = [key(KEY_ITEMS), key(KEY_HISTORY)]
|
| 968 |
-
for name in names:
|
| 969 |
-
pg.check_write(tenant, f"refresh {name}")
|
| 970 |
-
created = {}
|
| 971 |
-
try:
|
| 972 |
-
with pg._pool().connection() as con, con.transaction():
|
| 973 |
-
con.execute("SELECT set_config('lock_timeout', %s, true)", (f"{int(pg._lock_timeout_s()*1000)}ms",))
|
| 974 |
-
for name, initial in zip(names, ({"seq": 0, "items": {}}, {"snapshots": {}})):
|
| 975 |
-
con.execute(pg._q("INSERT INTO {tbl} (key,value) VALUES (%s,%s::jsonb) ON CONFLICT (key) DO NOTHING",
|
| 976 |
-
"store_kv", tenant), (name, json.dumps(initial)))
|
| 977 |
-
lengths = {}
|
| 978 |
-
for name in sorted(names):
|
| 979 |
-
row = con.execute(pg._q("SELECT COALESCE((value->>'seq')::bigint,0), octet_length(value::text) "
|
| 980 |
-
"FROM {tbl} WHERE key=%s FOR UPDATE", "store_kv", tenant), (name,)).fetchone()
|
| 981 |
-
lengths[name] = row[1]
|
| 982 |
-
if name == names[0]:
|
| 983 |
-
seq = int(row[0])
|
| 984 |
-
selected = [row["key"] for row in rows if row["rising"]]
|
| 985 |
-
latest = con.execute(pg._q(ITEM_LOOKUP_SQL, "store_kv", tenant), (names[0], selected)).fetchone()[0]
|
| 986 |
-
latest = json.loads(latest) if isinstance(latest, str) else latest
|
| 987 |
-
for row in rows:
|
| 988 |
-
if not row["rising"] or (latest.get(row["key"]) or {}).get("status") in HOLDING:
|
| 989 |
-
continue
|
| 990 |
-
seq += 1
|
| 991 |
-
iid = f"r{seq}"
|
| 992 |
-
times = row["rate30"] / row["rate90"] if row["rate90"] else None
|
| 993 |
-
reason = (f"30 day return rate {row['rate30']:.1f}% is {times:.1f} times the 90 day rate "
|
| 994 |
-
f"{row['rate90']:.1f}%." if times else f"30 day return rate {row['rate30']:.1f}%.")
|
| 995 |
-
created[iid] = {"id": iid, "title": f"Return rate rising on {row['key']}", "status": "Open",
|
| 996 |
-
"owner": owner, "due": (now.date() + dt.timedelta(days=DUE_DAYS)).isoformat(),
|
| 997 |
-
"reason": reason, "sku": row["key"], "asin": row["asin"], "rate30": row["rate30"],
|
| 998 |
-
"rate90": row["rate90"], "topReason": row["top_reason"], "createdAt": _stamp(now),
|
| 999 |
-
"updatedAt": _stamp(now), "updatedBy": "system",
|
| 1000 |
-
"history": [{"at": _stamp(now), "by": "system", "event": "created"}]}
|
| 1001 |
-
snapshot = {row["key"]: [row[name] for name in ("rate30", "rate90", "r30", "s30", "r90", "s90")]
|
| 1002 |
-
for row in rows}
|
| 1003 |
-
day = now.date().isoformat()
|
| 1004 |
-
saved = con.execute(pg._q("UPDATE {tbl} SET value=value || jsonb_build_object('snapshots', "
|
| 1005 |
-
"COALESCE(value->'snapshots', '{{}}'::jsonb) || jsonb_build_object(%s::text, "
|
| 1006 |
-
"CASE WHEN %s THEN '{{}}'::jsonb ELSE COALESCE(value #> %s::text[], '{{}}'::jsonb) END || %s::jsonb), "
|
| 1007 |
-
"'last_run', %s::text), rev=rev+1, updated_at=now() WHERE key=%s RETURNING octet_length(value::text)",
|
| 1008 |
-
"store_kv", tenant), (day, reset, ["snapshots", day], json.dumps(snapshot), _stamp(now), names[1])).fetchone()
|
| 1009 |
-
if saved[0] > pg.DOCUMENT_CEILING_BYTES and saved[0] > lengths[names[1]]:
|
| 1010 |
-
raise pg.StoreDocumentTooLarge(names[1], saved[0])
|
| 1011 |
-
if created:
|
| 1012 |
-
saved = con.execute(pg._q("UPDATE {tbl} SET value=value || jsonb_build_object('seq', %s::bigint, "
|
| 1013 |
-
"'items', COALESCE(value->'items', '{{}}'::jsonb) || %s::jsonb), rev=rev+1, updated_at=now() "
|
| 1014 |
-
"WHERE key=%s RETURNING octet_length(value::text)", "store_kv", tenant),
|
| 1015 |
-
(seq, json.dumps(created), names[0])).fetchone()
|
| 1016 |
-
if saved[0] > pg.DOCUMENT_CEILING_BYTES and saved[0] > lengths[names[0]]:
|
| 1017 |
-
raise pg.StoreDocumentTooLarge(names[0], saved[0])
|
| 1018 |
-
finally:
|
| 1019 |
-
for name in names:
|
| 1020 |
-
pg._bump_write_generation(name, tenant)
|
| 1021 |
-
return list(created)
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
# --------------------------------------------------------------------------- C4 item protocol
|
| 1025 |
-
|
| 1026 |
-
def _public(item):
|
| 1027 |
-
return {"id": item.get("id"), "title": item.get("title"), "status": item.get("status"),
|
| 1028 |
-
"owner": item.get("owner"), "due": item.get("due"), "reason": item.get("reason"),
|
| 1029 |
-
"sku": item.get("sku"), "asin": item.get("asin"), "rate30": item.get("rate30"),
|
| 1030 |
-
"rate90": item.get("rate90"), "topReason": item.get("topReason"),
|
| 1031 |
-
"note": item.get("note"), "updatedAt": item.get("updatedAt"), "updatedBy": item.get("updatedBy")}
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
def _user_record(st, user):
|
| 1035 |
-
if isinstance(user, dict):
|
| 1036 |
-
return user
|
| 1037 |
-
name = str(user or "").strip()
|
| 1038 |
-
if not name:
|
| 1039 |
-
return None
|
| 1040 |
-
try:
|
| 1041 |
-
rec = (st.get("users") or {}).get(name)
|
| 1042 |
-
except Exception: # noqa: BLE001
|
| 1043 |
-
rec = None
|
| 1044 |
-
return {**rec, "username": rec.get("username") or name} if isinstance(rec, dict) else None
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
def _may_read_source(st, rec):
|
| 1048 |
-
try:
|
| 1049 |
-
from core import perm_scope
|
| 1050 |
-
return bool(perm_scope.may_read(rec, SOURCE, st=st))
|
| 1051 |
-
except Exception: # noqa: BLE001
|
| 1052 |
-
return False
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
def may_edit(st, user):
|
| 1056 |
-
"""An edit grant: an account that is not a viewer and may read the FBA returns database."""
|
| 1057 |
-
rec = _user_record(st, user)
|
| 1058 |
-
if not rec or str(rec.get("role") or "user").strip().lower() == "viewer":
|
| 1059 |
-
return False
|
| 1060 |
-
return _may_read_source(st, rec)
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
def items(tenant_key, user, *, status=None, cursor=None, limit=100, st=None):
|
| 1064 |
-
"""Every item, newest first, paged by cursor. No cap on the total (rule 1)."""
|
| 1065 |
-
st = _rt(tenant_key, st)
|
| 1066 |
-
if user is not None:
|
| 1067 |
-
rec = _user_record(st, user)
|
| 1068 |
-
if not rec or not _may_read_source(st, rec):
|
| 1069 |
-
raise PermissionError("Your account cannot read Amazon FBA returns.")
|
| 1070 |
-
return _item_page(st, status=status or None, offset=_offset(cursor), limit=_page_size(limit))
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
def _status(value):
|
| 1074 |
-
text = str(value or "").strip().lower()
|
| 1075 |
-
for name in STATUSES:
|
| 1076 |
-
if name.lower() == text:
|
| 1077 |
-
return name
|
| 1078 |
-
raise ValueError("Status must be one of: " + ", ".join(STATUSES) + ".")
|
| 1079 |
-
|
| 1080 |
-
|
| 1081 |
-
def update_item(tenant_key, user, item_id, *, owner=None, status=None, due=None, note=None, st=None):
|
| 1082 |
-
"""Reassign, move status, move the due date or add a note on one item. Returns the item."""
|
| 1083 |
-
st = _rt(tenant_key, st)
|
| 1084 |
-
if not may_edit(st, user):
|
| 1085 |
-
raise PermissionError("Your account can view this App but not change its items.")
|
| 1086 |
-
if status is not None:
|
| 1087 |
-
status = _status(status)
|
| 1088 |
-
if due is not None:
|
| 1089 |
-
try:
|
| 1090 |
-
due = dt.date.fromisoformat(str(due)).isoformat()
|
| 1091 |
-
except ValueError:
|
| 1092 |
-
raise ValueError("Due must be a date such as 2026-10-27.") from None
|
| 1093 |
-
if owner is not None and not str(owner).strip():
|
| 1094 |
-
raise ValueError("Owner cannot be empty.")
|
| 1095 |
-
rec = _user_record(st, user) or {}
|
| 1096 |
-
by = str(rec.get("username") or rec.get("name") or user or "unknown")
|
| 1097 |
-
return _apply_item(st, item_id, by, owner=owner, status=status, due=due, note=note)
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
def _apply_item(st, item_id, by, *, owner=None, status=None, due=None, note=None, event=None):
|
| 1101 |
-
pg, tenant, key = _sql_scope(st)
|
| 1102 |
-
name, path = key(KEY_ITEMS), ["items", str(item_id)]
|
| 1103 |
-
pg.check_write(tenant, "update returns item")
|
| 1104 |
-
at = _stamp(_now())
|
| 1105 |
-
change = {"at": at, "by": by, **(event or {})}
|
| 1106 |
-
payload = {"updatedAt": at, "updatedBy": by}
|
| 1107 |
-
for field, value in (("owner", owner), ("status", status), ("due", due), ("note", note)):
|
| 1108 |
-
if value is not None and (field != "note" or str(value).strip()):
|
| 1109 |
-
payload[field] = change[field] = str(value).strip()
|
| 1110 |
-
try:
|
| 1111 |
-
with pg._pool().connection() as con, con.transaction():
|
| 1112 |
-
con.execute("SELECT set_config('lock_timeout', %s, true)", (f"{int(pg._lock_timeout_s()*1000)}ms",))
|
| 1113 |
-
row = con.execute(pg._q("SELECT (value #> %s::text[]) - 'history', octet_length(value::text) "
|
| 1114 |
-
"FROM {tbl} WHERE key=%s FOR UPDATE", "store_kv", tenant), (path, name)).fetchone()
|
| 1115 |
-
item = row[0] if row else None
|
| 1116 |
-
if not item:
|
| 1117 |
-
raise KeyError(item_id)
|
| 1118 |
-
item = json.loads(item) if isinstance(item, str) else item
|
| 1119 |
-
saved = con.execute(pg._q("UPDATE {tbl} SET value=jsonb_set(value,%s::text[], "
|
| 1120 |
-
"(value #> %s::text[]) || %s::jsonb || jsonb_build_object('history', "
|
| 1121 |
-
"COALESCE(value #> %s::text[], '[]'::jsonb) || %s::jsonb)), rev=rev+1, updated_at=now() "
|
| 1122 |
-
"WHERE key=%s RETURNING octet_length(value::text)", "store_kv", tenant),
|
| 1123 |
-
(path, path, json.dumps(payload), path + ["history"], json.dumps([change]), name)).fetchone()
|
| 1124 |
-
if saved[0] > pg.DOCUMENT_CEILING_BYTES and saved[0] > row[1]:
|
| 1125 |
-
raise pg.StoreDocumentTooLarge(name, saved[0])
|
| 1126 |
-
finally:
|
| 1127 |
-
pg._bump_write_generation(name, tenant)
|
| 1128 |
-
return _public({**item, **payload})
|
| 1129 |
-
|
| 1130 |
-
|
| 1131 |
-
def set_status(tenant_key, user, item_id, status, *, note=None, st=None):
|
| 1132 |
-
"""C4: move one item to a status. PermissionError without an edit grant, ValueError on an unknown status."""
|
| 1133 |
-
st = _rt(tenant_key, st)
|
| 1134 |
-
if not may_edit(st, user):
|
| 1135 |
-
raise PermissionError("Your account can view this App but not change its items.")
|
| 1136 |
-
return update_item(tenant_key, user, item_id, status=_status(status), note=note, st=st)
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
def proposals(tenant_key, *, st=None):
|
| 1140 |
-
"""C7: each open rising-returns item once, with an action in Amazon's own tools (R20)."""
|
| 1141 |
-
st = _rt(tenant_key, st)
|
| 1142 |
-
out, seen = [], set()
|
| 1143 |
-
for item in sorted((_doc(st, KEY_ITEMS).get("items") or {}).values(), key=_seq):
|
| 1144 |
-
if item.get("status") != "Open" or item.get("id") in seen:
|
| 1145 |
-
continue
|
| 1146 |
-
seen.add(item.get("id"))
|
| 1147 |
-
out.append({"source_kind": SOURCE_KIND, "item_id": item.get("id"), "sku": item.get("sku"),
|
| 1148 |
-
"action": ACTION.format(target=item.get("asin") or item.get("sku")),
|
| 1149 |
-
"reason": item.get("reason")})
|
| 1150 |
-
return out
|
| 1151 |
-
|
| 1152 |
-
|
| 1153 |
-
def on_decision(tenant_key, item_id, decision, reason, *, st=None):
|
| 1154 |
-
"""C7: an operator decision (approved or dismissed) moves the item's status."""
|
| 1155 |
-
status = DECISIONS.get(str(decision or "").strip().lower())
|
| 1156 |
-
if status is None:
|
| 1157 |
-
raise ValueError("Decision must be approved or dismissed.")
|
| 1158 |
-
st = _rt(tenant_key, st)
|
| 1159 |
-
return _apply_item(st, item_id, "operator", status=status, note=reason,
|
| 1160 |
-
event={"decision": str(decision).strip().lower()})
|
| 1161 |
-
|
| 1162 |
-
|
| 1163 |
-
# --------------------------------------------------------------------------- validate and removal
|
| 1164 |
-
|
| 1165 |
-
def validate(tenant_key, *, start=None, end=None, st=None, now=None, **_period_kw):
|
| 1166 |
-
"""The App's returned units for the period tie to an independent SUM(quantity) over FBA returns."""
|
| 1167 |
-
st = _rt(tenant_key, st)
|
| 1168 |
-
s, e = _period(start or _period_kw.get("period_start"), end or _period_kw.get("period_end"), now)
|
| 1169 |
-
conf = settings(tenant_key, st=st)
|
| 1170 |
-
with _screen_reader(tenant_key, st) as (cur, _present):
|
| 1171 |
-
app_total = _aggregate(cur, _relations(cur, s, e, conf))["returnedUnits"]
|
| 1172 |
-
independent = None
|
| 1173 |
-
with _reader(tenant_key, st) as cur:
|
| 1174 |
-
cols = _columns(cur, RETURNS_TABLE) if cur is not None else set()
|
| 1175 |
-
if {"quantity", "return_date"} <= cols:
|
| 1176 |
-
day = ('COALESCE(TRY_CAST(SUBSTR(CAST("return_date" AS VARCHAR), 1, 10) AS DATE), '
|
| 1177 |
-
'CAST(TRY_STRPTIME(CAST("return_date" AS VARCHAR), \'%m/%d/%Y\') AS DATE))')
|
| 1178 |
-
got = cur.execute(
|
| 1179 |
-
f'SELECT COALESCE(SUM(TRY_CAST("quantity" AS DOUBLE)), 0) FROM {RETURNS_TABLE} '
|
| 1180 |
-
f'WHERE {day} BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)',
|
| 1181 |
-
[s.isoformat(), e.isoformat()]).fetchone()
|
| 1182 |
-
independent = float(got[0] or 0)
|
| 1183 |
-
elif cur is not None and not cols:
|
| 1184 |
-
independent = 0.0
|
| 1185 |
-
if independent is None:
|
| 1186 |
-
return {"ok": False, "app_total": app_total, "independent_total": None,
|
| 1187 |
-
"detail": "The FBA returns table has no quantity or return date column to sum."}
|
| 1188 |
-
ok = abs(app_total - independent) < 1e-6
|
| 1189 |
-
return {"ok": ok, "app_total": app_total, "independent_total": independent,
|
| 1190 |
-
"detail": (f"Returned units {s.isoformat()} to {e.isoformat()}: App {app_total:g}, "
|
| 1191 |
-
f"{RETURNS_TABLE} {independent:g}.")}
|
| 1192 |
-
|
| 1193 |
-
|
| 1194 |
-
def on_app_removed(tenant_key, *, st=None):
|
| 1195 |
-
"""Rule 13: delete every document this App owns. No `amzn_*` table is touched."""
|
| 1196 |
-
st = _rt(tenant_key, st)
|
| 1197 |
-
removed, errors = [], []
|
| 1198 |
-
for key in OWN_KEYS:
|
| 1199 |
-
try:
|
| 1200 |
-
present = bool(st.get(key))
|
| 1201 |
-
except Exception: # noqa: BLE001
|
| 1202 |
-
present = True
|
| 1203 |
-
try:
|
| 1204 |
-
if hasattr(st, "delete_document"):
|
| 1205 |
-
st.delete_document(key)
|
| 1206 |
-
else:
|
| 1207 |
-
st.update(key, lambda _doc: None)
|
| 1208 |
-
removed.append(key)
|
| 1209 |
-
except Exception as exc: # noqa: BLE001
|
| 1210 |
-
if present:
|
| 1211 |
-
errors.append(f"{key}: {type(exc).__name__}: {exc}")
|
| 1212 |
-
return {"removed": removed, "errors": errors}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
web/src/apps/returns-repeat/AppView.tsx
DELETED
|
@@ -1,784 +0,0 @@
|
|
| 1 |
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 2 |
-
import { API_V1, CREDENTIALS } from "../../apiContract";
|
| 3 |
-
import { useEscapeClose } from "../../ui/useEscapeClose";
|
| 4 |
-
import "../../styles/sdlc79/returns-repeat.css";
|
| 5 |
-
|
| 6 |
-
// S79-T31 (C2, C4, R20): the Returns and repeat App screen. The dispatcher draws the App frame, so this view
|
| 7 |
-
// draws only the period control, the KPI strip, the segment tabs, one list and the SKU drawer. No chat panel (R18).
|
| 8 |
-
|
| 9 |
-
/** C2: the App as the dispatcher passes it. Structurally equal to lane A's TemplateApplication. */
|
| 10 |
-
interface ReturnsApplication {
|
| 11 |
-
id: string;
|
| 12 |
-
name: string;
|
| 13 |
-
templateKind?: string;
|
| 14 |
-
templateView?: string;
|
| 15 |
-
templateMark?: string;
|
| 16 |
-
templateConnector?: string;
|
| 17 |
-
capabilities?: Record<string, boolean>;
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
interface ReturnsAppViewProps { application: ReturnsApplication; canEdit: boolean }
|
| 21 |
-
|
| 22 |
-
type Segment = "highest" | "rising" | "repeat";
|
| 23 |
-
|
| 24 |
-
interface TrendPoint { start: string; end: string; returnRate: number | null }
|
| 25 |
-
interface Navigation { total: number; offset: number; limit: number; cursor: string | null; previousCursor: string | null }
|
| 26 |
-
interface Summary extends Navigation {
|
| 27 |
-
returnedUnits: number | null;
|
| 28 |
-
shippedUnits: number | null;
|
| 29 |
-
returnRate: number | null;
|
| 30 |
-
repeatShare: number | null;
|
| 31 |
-
empty: boolean;
|
| 32 |
-
emptyMessage: string;
|
| 33 |
-
counts: Record<Segment, number>;
|
| 34 |
-
previous: { returnRate: number | null; repeatShare: number | null };
|
| 35 |
-
trend: TrendPoint[];
|
| 36 |
-
repeatMonths: string[];
|
| 37 |
-
canEdit: boolean;
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
/** One row of the Highest return rate or Rising returns list. */
|
| 41 |
-
interface SkuRow {
|
| 42 |
-
key: string;
|
| 43 |
-
sku: string;
|
| 44 |
-
asin: string;
|
| 45 |
-
returnedUnits: number | null;
|
| 46 |
-
shippedUnits: number | null;
|
| 47 |
-
returnRate: number | null;
|
| 48 |
-
rate30: number | null;
|
| 49 |
-
rate90: number | null;
|
| 50 |
-
topReason: string;
|
| 51 |
-
itemStatus: string;
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
/** One row of the Repeat buyers list. */
|
| 55 |
-
interface RepeatRow {
|
| 56 |
-
key: string;
|
| 57 |
-
asin: string;
|
| 58 |
-
skuCount: number;
|
| 59 |
-
repeatShare: number | null;
|
| 60 |
-
repeatRevenue: number | null;
|
| 61 |
-
currency: string;
|
| 62 |
-
orders: number | null;
|
| 63 |
-
uniqueCustomers: number | null;
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
interface SkuPage extends Navigation { rows: SkuRow[]; repeat: RepeatRow[] }
|
| 67 |
-
|
| 68 |
-
interface Reason { label: string; units: number | null; count: number | null }
|
| 69 |
-
interface BoughtWith { asin: string; rank: number | null; combinationPct: number | null }
|
| 70 |
-
interface Item { id: string; title: string; status: string; owner: string; due: string; reason: string }
|
| 71 |
-
interface Detail extends Navigation {
|
| 72 |
-
key: string;
|
| 73 |
-
sku: string;
|
| 74 |
-
asin: string;
|
| 75 |
-
returnedUnits: number | null;
|
| 76 |
-
shippedUnits: number | null;
|
| 77 |
-
returnRate: number | null;
|
| 78 |
-
rate30: number | null;
|
| 79 |
-
rate90: number | null;
|
| 80 |
-
reasons: Reason[];
|
| 81 |
-
repeatShare: number | null;
|
| 82 |
-
repeatRevenue: number | null;
|
| 83 |
-
currency: string;
|
| 84 |
-
boughtWith: BoughtWith[];
|
| 85 |
-
skus: string[];
|
| 86 |
-
asins: string[];
|
| 87 |
-
repeatMonths: string[];
|
| 88 |
-
history: { date: string; rate30: number | null; rate90: number | null }[];
|
| 89 |
-
itemHistory: { at: string; by: string; event: string; status: string; owner: string; due: string; decision: string; note: string }[];
|
| 90 |
-
collectionTotals: Record<string, number>;
|
| 91 |
-
item: Item | null;
|
| 92 |
-
emptyMessage: string;
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
/** The item rules: statuses, the people who may own an item, and whether this account may change one. */
|
| 96 |
-
interface ItemMeta { statuses: string[]; owners: string[]; canEdit: boolean }
|
| 97 |
-
|
| 98 |
-
type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T };
|
| 99 |
-
|
| 100 |
-
const SEGMENTS: [Segment, string][] = [
|
| 101 |
-
["highest", "Highest return rate"], ["rising", "Rising returns"], ["repeat", "Repeat buyers"],
|
| 102 |
-
];
|
| 103 |
-
const PERIODS = [30, 90] as const;
|
| 104 |
-
const DEFAULT_DAYS = 90;
|
| 105 |
-
const PAGE = 100;
|
| 106 |
-
const SEARCH_DELAY_MS = 250;
|
| 107 |
-
const SEARCH_LABEL = "Search SKU or ASIN";
|
| 108 |
-
const NO_MATCH = "No SKU or ASIN matches your search";
|
| 109 |
-
const EMPTY_PERIOD = "No returns in this period";
|
| 110 |
-
const EMPTY_SEGMENT: Record<Segment, string> = {
|
| 111 |
-
highest: "No SKU shipped or returned in this period",
|
| 112 |
-
rising: "No SKU has rising returns",
|
| 113 |
-
repeat: "No repeat purchase data for this period",
|
| 114 |
-
};
|
| 115 |
-
const STATUSES = ["Open", "Approved", "Investigating", "Listing fixed", "Watching", "Resolved", "Dismissed"];
|
| 116 |
-
|
| 117 |
-
const text = (value: unknown) => (typeof value === "string" ? value : "");
|
| 118 |
-
const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
|
| 119 |
-
const list = (value: unknown) => (Array.isArray(value) ? value : []);
|
| 120 |
-
const words = (value: unknown) => list(value).map(text).filter(Boolean);
|
| 121 |
-
const record = (value: unknown) => (value && typeof value === "object" ? value : {}) as Record<string, unknown>;
|
| 122 |
-
|
| 123 |
-
function parseNavigation(body: Record<string, unknown>): Navigation {
|
| 124 |
-
return { total: num(body.total) ?? 0, offset: num(body.offset) ?? 0, limit: num(body.limit) ?? PAGE,
|
| 125 |
-
cursor: text(body.cursor) || null, previousCursor: text(body.previousCursor) || null };
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
async function readJson(response: Response, fallback: string): Promise<unknown> {
|
| 129 |
-
const body: unknown = await response.json().catch(() => null);
|
| 130 |
-
if (response.ok) return body;
|
| 131 |
-
// The server sends a refusal as top-level {error}; a bare router sends it under {detail: {error}}.
|
| 132 |
-
const shaped = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown } } } | null;
|
| 133 |
-
throw new Error(text(shaped?.error?.message) || text(shaped?.detail?.error?.message) || fallback);
|
| 134 |
-
}
|
| 135 |
-
|
| 136 |
-
const failure = (reason: unknown, fallback: string) => (reason instanceof Error && reason.message
|
| 137 |
-
? reason.message : fallback);
|
| 138 |
-
|
| 139 |
-
/** An ISO calendar day, `days` back from `iso`, read in UTC. */
|
| 140 |
-
function shift(iso: string, days: number) {
|
| 141 |
-
const date = new Date(iso + "T00:00:00Z");
|
| 142 |
-
date.setUTCDate(date.getUTCDate() - days);
|
| 143 |
-
return date.toISOString().slice(0, 10);
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
function parseSummary(raw: unknown): Summary {
|
| 147 |
-
const body = record(raw);
|
| 148 |
-
const counts = record(body.counts);
|
| 149 |
-
const previous = record(body.previous);
|
| 150 |
-
return {
|
| 151 |
-
...parseNavigation(body), repeatMonths: words(body.repeatMonths),
|
| 152 |
-
returnedUnits: num(body.returnedUnits), shippedUnits: num(body.shippedUnits), returnRate: num(body.returnRate),
|
| 153 |
-
repeatShare: num(body.repeatShare), empty: body.empty === true, emptyMessage: text(body.emptyMessage),
|
| 154 |
-
counts: { highest: num(counts.highest) ?? 0, rising: num(counts.rising) ?? 0, repeat: num(counts.repeat) ?? 0 },
|
| 155 |
-
previous: { returnRate: num(previous.returnRate), repeatShare: num(previous.repeatShare) },
|
| 156 |
-
trend: list(body.trend).map((entry) => {
|
| 157 |
-
const row = record(entry);
|
| 158 |
-
return { start: text(row.start), end: text(row.end), returnRate: num(row.returnRate) };
|
| 159 |
-
}),
|
| 160 |
-
canEdit: body.canEdit === true,
|
| 161 |
-
};
|
| 162 |
-
}
|
| 163 |
-
|
| 164 |
-
function parsePage(raw: unknown, segment: Segment): SkuPage {
|
| 165 |
-
const body = record(raw);
|
| 166 |
-
const raws = list(body.rows).map(record);
|
| 167 |
-
const rows = segment === "repeat" ? [] : raws.map((row) => ({
|
| 168 |
-
key: text(row.key), sku: text(row.sku), asin: text(row.asin), returnedUnits: num(row.returnedUnits),
|
| 169 |
-
shippedUnits: num(row.shippedUnits), returnRate: num(row.returnRate), rate30: num(row.rate30),
|
| 170 |
-
rate90: num(row.rate90), topReason: text(row.topReasonLabel), itemStatus: text(row.itemStatus),
|
| 171 |
-
})).filter((row) => row.key);
|
| 172 |
-
const repeat = segment !== "repeat" ? [] : raws.map((row) => ({
|
| 173 |
-
key: text(row.key), asin: text(row.asin), skuCount: num(row.skuCount) ?? 0, repeatShare: num(row.repeatShare),
|
| 174 |
-
repeatRevenue: num(row.repeatRevenue), currency: text(row.currency), orders: num(row.orders),
|
| 175 |
-
uniqueCustomers: num(row.uniqueCustomers),
|
| 176 |
-
})).filter((row) => row.key);
|
| 177 |
-
return { rows, repeat, ...parseNavigation(body) };
|
| 178 |
-
}
|
| 179 |
-
|
| 180 |
-
function parseItem(raw: unknown): Item | null {
|
| 181 |
-
const row = record(raw);
|
| 182 |
-
const id = text(row.id);
|
| 183 |
-
if (!id) return null;
|
| 184 |
-
return { id, title: text(row.title), status: text(row.status), owner: text(row.owner), due: text(row.due),
|
| 185 |
-
reason: text(row.reason) };
|
| 186 |
-
}
|
| 187 |
-
|
| 188 |
-
function parseDetail(raw: unknown): Detail {
|
| 189 |
-
const body = record(raw);
|
| 190 |
-
const repeat = record(body.repeat);
|
| 191 |
-
return {
|
| 192 |
-
...parseNavigation(body),
|
| 193 |
-
key: text(body.key), sku: text(body.sku), asin: text(body.asin), returnedUnits: num(body.returnedUnits),
|
| 194 |
-
shippedUnits: num(body.shippedUnits), returnRate: num(body.returnRate), rate30: num(body.rate30),
|
| 195 |
-
rate90: num(body.rate90),
|
| 196 |
-
reasons: list(body.reasons).map((entry) => {
|
| 197 |
-
const row = record(entry);
|
| 198 |
-
return { label: text(row.label) || "No reason given", units: num(row.units), count: num(row.count) };
|
| 199 |
-
}),
|
| 200 |
-
repeatShare: num(body.repeatShare), repeatRevenue: num(body.repeatRevenue), currency: text(repeat.currency),
|
| 201 |
-
boughtWith: list(body.boughtWith).map((entry) => {
|
| 202 |
-
const row = record(entry);
|
| 203 |
-
return { asin: text(row.asin), rank: num(row.rank), combinationPct: num(row.combinationPct) };
|
| 204 |
-
}).filter((row) => row.asin),
|
| 205 |
-
skus: words(body.skus), asins: words(body.asins), repeatMonths: words(body.repeatMonths),
|
| 206 |
-
history: list(body.history).map((entry) => {
|
| 207 |
-
const row = record(entry);
|
| 208 |
-
return { date: text(row.date), rate30: num(row.rate30), rate90: num(row.rate90) };
|
| 209 |
-
}),
|
| 210 |
-
itemHistory: list(body.itemHistory).map((entry) => {
|
| 211 |
-
const row = record(entry);
|
| 212 |
-
return { at: text(row.at), by: text(row.by), event: text(row.event), status: text(row.status),
|
| 213 |
-
owner: text(row.owner), due: text(row.due), decision: text(row.decision), note: text(row.note) };
|
| 214 |
-
}),
|
| 215 |
-
collectionTotals: Object.fromEntries(Object.entries(record(body.collectionTotals)).map(([key, value]) => [key, num(value) ?? 0])),
|
| 216 |
-
item: parseItem(body.item), emptyMessage: text(body.emptyMessage),
|
| 217 |
-
};
|
| 218 |
-
}
|
| 219 |
-
|
| 220 |
-
function parseMeta(raw: unknown): ItemMeta {
|
| 221 |
-
const body = record(raw);
|
| 222 |
-
const statuses = words(body.statuses);
|
| 223 |
-
return { statuses: statuses.length ? statuses : STATUSES, owners: words(body.owners), canEdit: body.canEdit === true };
|
| 224 |
-
}
|
| 225 |
-
|
| 226 |
-
/** A count with at most one decimal, or nothing when the source does not know it. */
|
| 227 |
-
const qty = (value: number | null) => (value === null ? ""
|
| 228 |
-
: value.toLocaleString(undefined, { maximumFractionDigits: 1 }));
|
| 229 |
-
|
| 230 |
-
/** A percent with one decimal. The server sends percent, never a fraction. */
|
| 231 |
-
const pct = (value: number | null) => (value === null ? ""
|
| 232 |
-
: `${value.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })}%`);
|
| 233 |
-
|
| 234 |
-
function money(value: number | null, currency: string) {
|
| 235 |
-
if (value === null) return "";
|
| 236 |
-
try {
|
| 237 |
-
if (currency) return value.toLocaleString(undefined, { style: "currency", currency, maximumFractionDigits: 0 });
|
| 238 |
-
} catch {
|
| 239 |
-
// An unknown currency code reads as a plain amount.
|
| 240 |
-
}
|
| 241 |
-
return value.toLocaleString(undefined, { maximumFractionDigits: 0 });
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
-
/** "Oct 24" from an ISO day. A calendar day is read in UTC. */
|
| 245 |
-
function day(iso: string) {
|
| 246 |
-
if (!iso) return "";
|
| 247 |
-
const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso);
|
| 248 |
-
return Number.isNaN(date.getTime()) ? iso
|
| 249 |
-
: date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
|
| 250 |
-
}
|
| 251 |
-
|
| 252 |
-
const statusTone = (status: string) => status.toLowerCase().replace(/[^a-z]+/g, "-");
|
| 253 |
-
|
| 254 |
-
function Skeleton({ rows = 4 }: { rows?: number }) {
|
| 255 |
-
return <div className="rr-skeleton-rows" aria-busy="true" aria-label="Loading">
|
| 256 |
-
{Array.from({ length: rows }, (_v, index) => <div key={index} className="rr-skeleton" />)}
|
| 257 |
-
</div>;
|
| 258 |
-
}
|
| 259 |
-
|
| 260 |
-
function Failed({ what, message, onRetry }: { what: string; message: string; onRetry: () => void }) {
|
| 261 |
-
return <p className="rr-error" role="alert">{what} {message}{" "}
|
| 262 |
-
<button type="button" className="rr-link" onClick={onRetry}>Retry</button></p>;
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
function StatusPill({ status }: { status: string }) {
|
| 266 |
-
return status ? <span className={`rr-pill is-${statusTone(status)}`}>{status}</span> : null;
|
| 267 |
-
}
|
| 268 |
-
|
| 269 |
-
function Fact({ label, value, numeric = false }: { label: string; value: string; numeric?: boolean }) {
|
| 270 |
-
return <div className="rr-fact">
|
| 271 |
-
<dt>{label}</dt><dd className={numeric ? "is-num" : undefined}>{value || "Not known"}</dd>
|
| 272 |
-
</div>;
|
| 273 |
-
}
|
| 274 |
-
|
| 275 |
-
function Pager({ page, busy, onPage, label }: {
|
| 276 |
-
page: Navigation; busy?: boolean; onPage: (cursor: string | null) => void; label: string;
|
| 277 |
-
}) {
|
| 278 |
-
if (!page.previousCursor && !page.cursor) return null;
|
| 279 |
-
const unavailable = (blocked: boolean) => blocked ? { opacity: "var(--lp-home-disabled-opacity)", cursor: "default" } : undefined;
|
| 280 |
-
return <nav className="rr-more" aria-label={label} aria-busy={busy}>
|
| 281 |
-
<button type="button" className="rr-button" aria-disabled={busy || !page.previousCursor}
|
| 282 |
-
style={unavailable(!!busy || !page.previousCursor)}
|
| 283 |
-
onClick={() => { if (!busy && page.previousCursor) onPage(page.previousCursor); }}>Previous</button>{" "}
|
| 284 |
-
<span className="rr-muted rr-num" aria-live="polite">
|
| 285 |
-
{qty(page.offset + 1)} to {qty(Math.min(page.total, page.offset + page.limit))} of {qty(page.total)}
|
| 286 |
-
</span>{" "}
|
| 287 |
-
<button type="button" className="rr-button" aria-disabled={busy || !page.cursor}
|
| 288 |
-
style={unavailable(!!busy || !page.cursor)}
|
| 289 |
-
onClick={() => { if (!busy && page.cursor) onPage(page.cursor); }}>Next</button>
|
| 290 |
-
</nav>;
|
| 291 |
-
}
|
| 292 |
-
|
| 293 |
-
/** A small inline line of the weekly return rate. Weeks with no shipments leave a gap in the scale only. */
|
| 294 |
-
function Sparkline({ points }: { points: TrendPoint[] }) {
|
| 295 |
-
const known = points.map((point, index) => ({ index, value: point.returnRate }))
|
| 296 |
-
.filter((point): point is { index: number; value: number } => point.value !== null);
|
| 297 |
-
if (known.length < 2) return null;
|
| 298 |
-
const width = 96;
|
| 299 |
-
const height = 28;
|
| 300 |
-
const top = Math.max(...known.map((point) => point.value));
|
| 301 |
-
const low = Math.min(...known.map((point) => point.value));
|
| 302 |
-
const span = top - low || 1;
|
| 303 |
-
const x = (index: number) => (points.length > 1 ? (index / (points.length - 1)) * (width - 4) + 2 : width / 2);
|
| 304 |
-
const y = (value: number) => height - 2 - ((value - low) / span) * (height - 4);
|
| 305 |
-
const path = known.map((point) => `${x(point.index).toFixed(1)},${y(point.value).toFixed(1)}`).join(" ");
|
| 306 |
-
const last = known[known.length - 1];
|
| 307 |
-
return <svg className="rr-spark" viewBox={`0 0 ${width} ${height}`} width={width} height={height} role="img"
|
| 308 |
-
aria-label={`Weekly return rate over ${points.length} weeks, from ${pct(known[0].value)} to ${pct(last.value)}`}>
|
| 309 |
-
<polyline className="rr-spark-line" points={path} fill="none" />
|
| 310 |
-
<circle className="rr-spark-dot" cx={x(last.index)} cy={y(last.value)} r={2} />
|
| 311 |
-
</svg>;
|
| 312 |
-
}
|
| 313 |
-
|
| 314 |
-
/** A KPI card: micro-label, tabular value, delta and period. The delta is tinted by sign (DESIGN.md §3). */
|
| 315 |
-
function KpiCard({ label, value, previous, days, trend, kpi }: {
|
| 316 |
-
label: string; value: number | null; previous: number | null; days: number;
|
| 317 |
-
trend?: TrendPoint[]; kpi: string;
|
| 318 |
-
}) {
|
| 319 |
-
const delta = value !== null && previous !== null ? Math.round((value - previous) * 10) / 10 : null;
|
| 320 |
-
const tone = delta === null || delta === 0 ? "is-flat" : delta > 0 ? "is-up" : "is-down";
|
| 321 |
-
const deltaText = delta === null ? "" : `${delta > 0 ? "+" : delta < 0 ? "−" : ""}${Math.abs(delta)
|
| 322 |
-
.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} pts`;
|
| 323 |
-
return <div className="rr-kpi" data-kpi={kpi}>
|
| 324 |
-
<span className="rr-kpi-label">{label}</span>
|
| 325 |
-
<div className="rr-kpi-main">
|
| 326 |
-
<span className="rr-kpi-value">{value === null ? "Not known" : pct(value)}</span>
|
| 327 |
-
{trend && <Sparkline points={trend} />}
|
| 328 |
-
</div>
|
| 329 |
-
<span className="rr-kpi-foot">
|
| 330 |
-
{deltaText && <span className={`rr-kpi-delta ${tone}`}>{deltaText}</span>}
|
| 331 |
-
<span className="rr-kpi-period">{deltaText ? `vs previous ${days} days` : `Last ${days} days`}</span>
|
| 332 |
-
</span>
|
| 333 |
-
</div>;
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
interface DrawerProps {
|
| 337 |
-
rowKey: string;
|
| 338 |
-
title: string;
|
| 339 |
-
editable: boolean;
|
| 340 |
-
meta: ItemMeta | null;
|
| 341 |
-
url: (path: string, params?: Record<string, string>) => string;
|
| 342 |
-
onSaved: (key: string, item: Item) => void;
|
| 343 |
-
onClose: () => void;
|
| 344 |
-
}
|
| 345 |
-
|
| 346 |
-
function Drawer({ rowKey, title, editable, meta, url, onSaved, onClose }: DrawerProps) {
|
| 347 |
-
const panel = useRef<HTMLElement | null>(null);
|
| 348 |
-
const close = useRef<HTMLButtonElement | null>(null);
|
| 349 |
-
const [detail, setDetail] = useState<Load<Detail>>({ phase: "loading" });
|
| 350 |
-
const [attempt, setAttempt] = useState(0);
|
| 351 |
-
const [cursor, setCursor] = useState<string | null>(null);
|
| 352 |
-
const [busy, setBusy] = useState(false);
|
| 353 |
-
const write = useRef<AbortController | null>(null);
|
| 354 |
-
const [saving, setSaving] = useState(false);
|
| 355 |
-
const [saveError, setSaveError] = useState("");
|
| 356 |
-
useEscapeClose(true, onClose, { container: () => panel.current });
|
| 357 |
-
useEffect(() => { close.current?.focus(); }, [rowKey]);
|
| 358 |
-
useEffect(() => () => { write.current?.abort(); }, []);
|
| 359 |
-
const params: Record<string, string> = { key: rowKey, limit: "25" };
|
| 360 |
-
if (cursor) params.cursor = cursor;
|
| 361 |
-
const detailUrl = url("/sku", params);
|
| 362 |
-
const latestDetail = useRef(detailUrl);
|
| 363 |
-
latestDetail.current = detailUrl;
|
| 364 |
-
|
| 365 |
-
useEffect(() => {
|
| 366 |
-
const controller = new AbortController();
|
| 367 |
-
setBusy(true);
|
| 368 |
-
void fetch(detailUrl, { credentials: CREDENTIALS, signal: controller.signal })
|
| 369 |
-
.then((response) => readJson(response, "The server gave no reason."))
|
| 370 |
-
.then((body) => { if (!controller.signal.aborted && latestDetail.current === detailUrl)
|
| 371 |
-
setDetail({ phase: "ready", value: parseDetail(body) }); })
|
| 372 |
-
.catch((reason: unknown) => {
|
| 373 |
-
if (!controller.signal.aborted && latestDetail.current === detailUrl)
|
| 374 |
-
setDetail({ phase: "error", message: failure(reason, "The server gave no reason.") });
|
| 375 |
-
}).finally(() => { if (!controller.signal.aborted && latestDetail.current === detailUrl) setBusy(false); });
|
| 376 |
-
return () => controller.abort();
|
| 377 |
-
}, [detailUrl, attempt]);
|
| 378 |
-
|
| 379 |
-
/** Store one change, then show the value the server answered. */
|
| 380 |
-
const save = async (itemId: string, change: { owner?: string; status?: string }) => {
|
| 381 |
-
setSaving(true);
|
| 382 |
-
setSaveError("");
|
| 383 |
-
const controller = new AbortController();
|
| 384 |
-
write.current = controller;
|
| 385 |
-
try {
|
| 386 |
-
const response = await fetch(url(`/items/${encodeURIComponent(itemId)}`), {
|
| 387 |
-
method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 388 |
-
body: JSON.stringify(change),
|
| 389 |
-
signal: controller.signal,
|
| 390 |
-
});
|
| 391 |
-
const stored = parseItem(await readJson(response, "The change was not saved."));
|
| 392 |
-
if (!stored) throw new Error("The change was not saved.");
|
| 393 |
-
if (controller.signal.aborted) return;
|
| 394 |
-
setDetail((current) => current.phase !== "ready" ? current
|
| 395 |
-
: { phase: "ready", value: { ...current.value, item: stored } });
|
| 396 |
-
onSaved(rowKey, stored);
|
| 397 |
-
setAttempt((count) => count + 1);
|
| 398 |
-
} catch (reason) {
|
| 399 |
-
if (!controller.signal.aborted) setSaveError(failure(reason, "The change was not saved."));
|
| 400 |
-
} finally {
|
| 401 |
-
if (!controller.signal.aborted) setSaving(false);
|
| 402 |
-
}
|
| 403 |
-
};
|
| 404 |
-
|
| 405 |
-
const value = detail.phase === "ready" ? detail.value : null;
|
| 406 |
-
const item = value?.item ?? null;
|
| 407 |
-
const statuses = meta?.statuses ?? STATUSES;
|
| 408 |
-
const owners = meta?.owners ?? [];
|
| 409 |
-
const ownerOptions = item?.owner && !owners.includes(item.owner) ? [item.owner, ...owners] : owners;
|
| 410 |
-
const reasonUnits = value?.returnedUnits ?? 0;
|
| 411 |
-
const heading = value?.sku || value?.asin || title;
|
| 412 |
-
const sub = value?.sku && value.asin ? value.asin : "";
|
| 413 |
-
return <aside ref={panel} className="rr-drawer" role="dialog" aria-label={heading}>
|
| 414 |
-
<div className="rr-drawer-head">
|
| 415 |
-
<div className="rr-drawer-titles">
|
| 416 |
-
<h2 className="rr-drawer-title">{heading}</h2>
|
| 417 |
-
{sub && <span className="rr-drawer-sub">{sub}</span>}
|
| 418 |
-
</div>
|
| 419 |
-
<button ref={close} type="button" className="rr-button is-quiet" onClick={onClose}>Close</button>
|
| 420 |
-
</div>
|
| 421 |
-
|
| 422 |
-
{detail.phase === "loading" && <Skeleton rows={5} />}
|
| 423 |
-
{detail.phase === "error" && <Failed what="This SKU did not load." message={detail.message}
|
| 424 |
-
onRetry={() => setAttempt((count) => count + 1)} />}
|
| 425 |
-
{value && <>
|
| 426 |
-
{item && <section className="rr-section rr-item" aria-label="Rising returns item">
|
| 427 |
-
<h3 className="rr-heading">{item.title || "Rising returns"}</h3>
|
| 428 |
-
{item.reason && <p className="rr-reason">{item.reason}</p>}
|
| 429 |
-
<div className="rr-controls">
|
| 430 |
-
<label className="rr-field">
|
| 431 |
-
<span className="rr-field-label">Status</span>
|
| 432 |
-
{editable
|
| 433 |
-
? <select className="rr-select" value={item.status} disabled={saving}
|
| 434 |
-
onChange={(event) => void save(item.id, { status: event.target.value })}>
|
| 435 |
-
{(statuses.includes(item.status) || !item.status ? statuses : [item.status, ...statuses])
|
| 436 |
-
.map((status) => <option key={status} value={status}>{status}</option>)}
|
| 437 |
-
</select>
|
| 438 |
-
: <StatusPill status={item.status} />}
|
| 439 |
-
</label>
|
| 440 |
-
<label className="rr-field">
|
| 441 |
-
<span className="rr-field-label">Owner</span>
|
| 442 |
-
{editable
|
| 443 |
-
? <select className="rr-select" value={item.owner} disabled={saving}
|
| 444 |
-
onChange={(event) => void save(item.id, { owner: event.target.value })}>
|
| 445 |
-
{ownerOptions.map((owner) => <option key={owner} value={owner}>{owner}</option>)}
|
| 446 |
-
</select>
|
| 447 |
-
: <span className="rr-field-value">{item.owner || "Nobody"}</span>}
|
| 448 |
-
</label>
|
| 449 |
-
{item.due && <div className="rr-field">
|
| 450 |
-
<span className="rr-field-label">Due</span><span className="rr-field-value rr-num">{day(item.due)}</span>
|
| 451 |
-
</div>}
|
| 452 |
-
{saveError && <p className="rr-error" role="alert">{saveError}</p>}
|
| 453 |
-
</div>
|
| 454 |
-
</section>}
|
| 455 |
-
|
| 456 |
-
<dl className="rr-facts">
|
| 457 |
-
<Fact label="Return rate" value={pct(value.returnRate)} numeric />
|
| 458 |
-
<Fact label="Returns" value={qty(value.returnedUnits)} numeric />
|
| 459 |
-
<Fact label="Units shipped" value={qty(value.shippedUnits)} numeric />
|
| 460 |
-
<Fact label="30 day return rate" value={pct(value.rate30)} numeric />
|
| 461 |
-
<Fact label="90 day return rate" value={pct(value.rate90)} numeric />
|
| 462 |
-
<Fact label="Repeat purchase share" value={pct(value.repeatShare)} numeric />
|
| 463 |
-
<Fact label="Repeat revenue" value={money(value.repeatRevenue, value.currency)} numeric />
|
| 464 |
-
</dl>
|
| 465 |
-
|
| 466 |
-
<section className="rr-section" aria-label="Return reasons">
|
| 467 |
-
<h3 className="rr-heading">Return reasons{value.collectionTotals.reasons > 0 && ` (${qty(value.collectionTotals.reasons)})`}</h3>
|
| 468 |
-
{value.reasons.length === 0
|
| 469 |
-
? <p className="rr-muted">{value.collectionTotals.reasons > 0 ? "No entries on this page" : value.emptyMessage || EMPTY_PERIOD}</p>
|
| 470 |
-
: <table className="rr-mini rr-reasons">
|
| 471 |
-
<thead><tr><th scope="col">Reason</th><th scope="col" className="is-num">Units</th>
|
| 472 |
-
<th scope="col" className="is-num">Share</th></tr></thead>
|
| 473 |
-
<tbody>{value.reasons.map((reason) => <tr key={reason.label}>
|
| 474 |
-
<td>{reason.label}</td>
|
| 475 |
-
<td className="is-num">{qty(reason.units)}</td>
|
| 476 |
-
<td className="is-num">{reasonUnits > 0 && reason.units !== null
|
| 477 |
-
? pct((reason.units / reasonUnits) * 100) : ""}</td>
|
| 478 |
-
</tr>)}</tbody>
|
| 479 |
-
</table>}
|
| 480 |
-
</section>
|
| 481 |
-
|
| 482 |
-
<section className="rr-section" aria-label="Frequently bought with">
|
| 483 |
-
<h3 className="rr-heading">Frequently bought with{value.collectionTotals.boughtWith > 0 && ` (${qty(value.collectionTotals.boughtWith)})`}</h3>
|
| 484 |
-
{value.boughtWith.length === 0
|
| 485 |
-
? <p className="rr-muted">{value.collectionTotals.boughtWith > 0 ? "No entries on this page" : "No basket data"}</p>
|
| 486 |
-
: <table className="rr-mini rr-basket">
|
| 487 |
-
<thead><tr><th scope="col" className="is-num">Rank</th><th scope="col">ASIN</th>
|
| 488 |
-
<th scope="col" className="is-num">Bought together</th></tr></thead>
|
| 489 |
-
<tbody>{value.boughtWith.map((row) => <tr key={row.asin}>
|
| 490 |
-
<td className="is-num">{qty(row.rank)}</td>
|
| 491 |
-
<td>{row.asin}</td>
|
| 492 |
-
<td className="is-num">{pct(row.combinationPct)}</td>
|
| 493 |
-
</tr>)}</tbody>
|
| 494 |
-
</table>}
|
| 495 |
-
</section>
|
| 496 |
-
{([['skus', 'SKUs', value.skus], ['asins', 'ASINs', value.asins],
|
| 497 |
-
['repeatMonths', 'Repeat months', value.repeatMonths]] as const).map(([field, label, members]) =>
|
| 498 |
-
value.collectionTotals[field] > 0 && <section key={field} className="rr-section" aria-label={label}>
|
| 499 |
-
<h3 className="rr-heading">{label} ({qty(value.collectionTotals[field])})</h3>
|
| 500 |
-
<ul className="rr-muted">{members.map((member) => <li key={member}>{member}</li>)}</ul>
|
| 501 |
-
</section>)}
|
| 502 |
-
{value.collectionTotals.history > 0 && <section className="rr-section" aria-label="Rate history">
|
| 503 |
-
<h3 className="rr-heading">Rate history ({qty(value.collectionTotals.history)})</h3>
|
| 504 |
-
<table className="rr-mini"><thead><tr><th scope="col">Date</th><th scope="col" className="is-num">30 day rate</th>
|
| 505 |
-
<th scope="col" className="is-num">90 day rate</th></tr></thead>
|
| 506 |
-
<tbody>{value.history.map((point) => <tr key={point.date}><td>{day(point.date)}</td>
|
| 507 |
-
<td className="is-num">{pct(point.rate30)}</td><td className="is-num">{pct(point.rate90)}</td></tr>)}</tbody>
|
| 508 |
-
</table>
|
| 509 |
-
</section>}
|
| 510 |
-
{value.collectionTotals.itemHistory > 0 && <section className="rr-section" aria-label="Item history">
|
| 511 |
-
<h3 className="rr-heading">Item history ({qty(value.collectionTotals.itemHistory)})</h3>
|
| 512 |
-
<ul className="rr-muted">{value.itemHistory.map((event, index) => <li key={`${event.at}:${index}`}>
|
| 513 |
-
{day(event.at)} {event.by} {event.event} {event.status} {event.owner} {day(event.due)} {event.decision} {event.note}
|
| 514 |
-
</li>)}</ul>
|
| 515 |
-
</section>}
|
| 516 |
-
<Pager page={value} busy={busy || saving} onPage={setCursor} label="Detail pages" />
|
| 517 |
-
</>}
|
| 518 |
-
</aside>;
|
| 519 |
-
}
|
| 520 |
-
|
| 521 |
-
function SkuTable({ rows, rising, onOpen }: { rows: SkuRow[]; rising: boolean; onOpen: (key: string, title: string) => void }) {
|
| 522 |
-
return <div className="rr-table-wrap">
|
| 523 |
-
<table className={rising ? "rr-table is-rising" : "rr-table"}>
|
| 524 |
-
<thead>
|
| 525 |
-
<tr>
|
| 526 |
-
<th scope="col" className="rr-h-product">Product</th>
|
| 527 |
-
<th scope="col" className="is-num">Units shipped</th>
|
| 528 |
-
<th scope="col" className="is-num">Returns</th>
|
| 529 |
-
<th scope="col" className="is-num">Return rate</th>
|
| 530 |
-
{rising && <th scope="col" className="is-num">30 day rate</th>}
|
| 531 |
-
{rising && <th scope="col" className="is-num">90 day rate</th>}
|
| 532 |
-
<th scope="col" className="rr-h-reason">Top reason</th>
|
| 533 |
-
<th scope="col" className="rr-h-status">Status</th>
|
| 534 |
-
</tr>
|
| 535 |
-
</thead>
|
| 536 |
-
<tbody>
|
| 537 |
-
{rows.map((row) => <tr key={row.key} className="rr-row">
|
| 538 |
-
<td className="rr-c-product">
|
| 539 |
-
<button type="button" className="rr-open" data-key={row.key}
|
| 540 |
-
onClick={() => onOpen(row.key, row.sku || row.asin || row.key)}>{row.sku || row.key}</button>
|
| 541 |
-
{row.asin && <span className="rr-sub">{row.asin}</span>}
|
| 542 |
-
</td>
|
| 543 |
-
<td className="is-num" data-label="Units shipped">{qty(row.shippedUnits)}</td>
|
| 544 |
-
<td className="is-num" data-label="Returns">{qty(row.returnedUnits)}</td>
|
| 545 |
-
<td className="is-num rr-rate" data-label="Return rate">{pct(row.returnRate)}</td>
|
| 546 |
-
{rising && <td className="is-num" data-label="30 day rate">{pct(row.rate30)}</td>}
|
| 547 |
-
{rising && <td className="is-num" data-label="90 day rate">{pct(row.rate90)}</td>}
|
| 548 |
-
<td className="rr-c-reason" data-label="Top reason">{row.topReason}</td>
|
| 549 |
-
<td className="rr-c-status"><StatusPill status={row.itemStatus} /></td>
|
| 550 |
-
</tr>)}
|
| 551 |
-
</tbody>
|
| 552 |
-
</table>
|
| 553 |
-
</div>;
|
| 554 |
-
}
|
| 555 |
-
|
| 556 |
-
function RepeatTable({ rows, onOpen }: { rows: RepeatRow[]; onOpen: (key: string, title: string) => void }) {
|
| 557 |
-
return <div className="rr-table-wrap">
|
| 558 |
-
<table className="rr-table is-repeat">
|
| 559 |
-
<thead>
|
| 560 |
-
<tr>
|
| 561 |
-
<th scope="col" className="rr-h-product">ASIN</th>
|
| 562 |
-
<th scope="col" className="rr-h-skus">SKUs</th>
|
| 563 |
-
<th scope="col" className="is-num">Repeat purchase share</th>
|
| 564 |
-
<th scope="col" className="is-num">Repeat revenue</th>
|
| 565 |
-
<th scope="col" className="is-num">Orders</th>
|
| 566 |
-
<th scope="col" className="is-num">Customers</th>
|
| 567 |
-
</tr>
|
| 568 |
-
</thead>
|
| 569 |
-
<tbody>
|
| 570 |
-
{rows.map((row) => <tr key={row.key} className="rr-row">
|
| 571 |
-
<td className="rr-c-product">
|
| 572 |
-
<button type="button" className="rr-open" data-key={row.key}
|
| 573 |
-
onClick={() => onOpen(row.key, row.asin || row.key)}>{row.asin || row.key}</button>
|
| 574 |
-
</td>
|
| 575 |
-
<td className="rr-c-skus" data-label="SKUs">{qty(row.skuCount)}</td>
|
| 576 |
-
<td className="is-num rr-rate" data-label="Repeat purchase share">{pct(row.repeatShare)}</td>
|
| 577 |
-
<td className="is-num" data-label="Repeat revenue">{money(row.repeatRevenue, row.currency)}</td>
|
| 578 |
-
<td className="is-num" data-label="Orders">{qty(row.orders)}</td>
|
| 579 |
-
<td className="is-num" data-label="Customers">{qty(row.uniqueCustomers)}</td>
|
| 580 |
-
</tr>)}
|
| 581 |
-
</tbody>
|
| 582 |
-
</table>
|
| 583 |
-
</div>;
|
| 584 |
-
}
|
| 585 |
-
|
| 586 |
-
export default function ReturnsRepeatView({ application, canEdit }: ReturnsAppViewProps) {
|
| 587 |
-
const appId = application.id;
|
| 588 |
-
const [days, setDays] = useState<number>(DEFAULT_DAYS);
|
| 589 |
-
const period = useMemo(() => {
|
| 590 |
-
const end = new Date().toISOString().slice(0, 10);
|
| 591 |
-
return { start: shift(end, days - 1), end };
|
| 592 |
-
}, [days]);
|
| 593 |
-
const base = useCallback((path: string, params: Record<string, string> = {}) => {
|
| 594 |
-
const query = new URLSearchParams({ app: appId, ...params });
|
| 595 |
-
return `${API_V1}/app-kinds/returns_repeat/${encodeURIComponent(appId)}${path}?${query.toString()}`;
|
| 596 |
-
}, [appId]);
|
| 597 |
-
/** A read inside the chosen period. An item write and the item rules take no period. */
|
| 598 |
-
const url = useCallback((path: string, params: Record<string, string> = {}) => (path.startsWith("/items")
|
| 599 |
-
? base(path, params) : base(path, { start: period.start, end: period.end, ...params })), [base, period]);
|
| 600 |
-
|
| 601 |
-
const [segment, setSegment] = useState<Segment>("highest");
|
| 602 |
-
const [search, setSearch] = useState("");
|
| 603 |
-
const [q, setQ] = useState("");
|
| 604 |
-
const [navigation, setNavigation] = useState<{ scope: string; cursor: string | null }>({ scope: "", cursor: null });
|
| 605 |
-
const [summaryNavigation, setSummaryNavigation] = useState<{ scope: string; cursor: string | null }>({ scope: "", cursor: null });
|
| 606 |
-
const [opened, setOpened] = useState<{ key: string; title: string } | null>(null);
|
| 607 |
-
const trimmedSearch = search.trim();
|
| 608 |
-
// The server matches SKU and ASIN, so a search covers every row, not only the loaded page.
|
| 609 |
-
useEffect(() => {
|
| 610 |
-
if (trimmedSearch === q) return;
|
| 611 |
-
const timer = window.setTimeout(() => {
|
| 612 |
-
setQ(trimmedSearch);
|
| 613 |
-
setNavigation({ scope: "", cursor: null });
|
| 614 |
-
setOpened(null);
|
| 615 |
-
}, SEARCH_DELAY_MS);
|
| 616 |
-
return () => window.clearTimeout(timer);
|
| 617 |
-
}, [trimmedSearch, q]);
|
| 618 |
-
const [summary, setSummary] = useState<Load<Summary>>({ phase: "loading" });
|
| 619 |
-
const [summaryAttempt, setSummaryAttempt] = useState(0);
|
| 620 |
-
const [page, setPage] = useState<Load<SkuPage>>({ phase: "loading" });
|
| 621 |
-
const [pageAttempt, setPageAttempt] = useState(0);
|
| 622 |
-
const [meta, setMeta] = useState<ItemMeta | null>(null);
|
| 623 |
-
const [pageBusy, setPageBusy] = useState(false);
|
| 624 |
-
const [summaryBusy, setSummaryBusy] = useState(false);
|
| 625 |
-
const opener = useRef<HTMLElement | null>(null);
|
| 626 |
-
const scope = `${appId}:${period.start}:${period.end}:${segment}:${q}`;
|
| 627 |
-
const cursor = navigation.scope === scope ? navigation.cursor : null;
|
| 628 |
-
const summaryScope = url("/summary");
|
| 629 |
-
const summaryCursor = summaryNavigation.scope === summaryScope ? summaryNavigation.cursor : null;
|
| 630 |
-
const previousSummaryScope = useRef("");
|
| 631 |
-
const summaryRequest = url("/summary", summaryCursor ? { cursor: summaryCursor } : {});
|
| 632 |
-
const latestSummary = useRef(summaryRequest);
|
| 633 |
-
latestSummary.current = summaryRequest;
|
| 634 |
-
|
| 635 |
-
useEffect(() => {
|
| 636 |
-
const controller = new AbortController();
|
| 637 |
-
if (previousSummaryScope.current !== summaryScope) setSummary({ phase: "loading" });
|
| 638 |
-
previousSummaryScope.current = summaryScope;
|
| 639 |
-
setSummaryBusy(true);
|
| 640 |
-
void fetch(summaryRequest, { credentials: CREDENTIALS, signal: controller.signal })
|
| 641 |
-
.then((response) => readJson(response, "The server gave no reason."))
|
| 642 |
-
.then((body) => { if (!controller.signal.aborted && latestSummary.current === summaryRequest)
|
| 643 |
-
setSummary({ phase: "ready", value: parseSummary(body) }); })
|
| 644 |
-
.catch((reason: unknown) => {
|
| 645 |
-
if (!controller.signal.aborted && latestSummary.current === summaryRequest)
|
| 646 |
-
setSummary({ phase: "error", message: failure(reason, "The server gave no reason.") });
|
| 647 |
-
}).finally(() => { if (!controller.signal.aborted && latestSummary.current === summaryRequest) setSummaryBusy(false); });
|
| 648 |
-
return () => controller.abort();
|
| 649 |
-
}, [summaryRequest, summaryScope, summaryAttempt]);
|
| 650 |
-
|
| 651 |
-
// The item rules (statuses, owners, edit grant) do not depend on the period: read them once.
|
| 652 |
-
useEffect(() => {
|
| 653 |
-
const controller = new AbortController();
|
| 654 |
-
void fetch(base("/items", { limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal })
|
| 655 |
-
.then((response) => readJson(response, ""))
|
| 656 |
-
.then((body) => { if (!controller.signal.aborted) setMeta(parseMeta(body)); })
|
| 657 |
-
.catch(() => { if (!controller.signal.aborted) setMeta(null); });
|
| 658 |
-
return () => controller.abort();
|
| 659 |
-
}, [base]);
|
| 660 |
-
|
| 661 |
-
const listUrl = useCallback((pageCursor: string | null) => {
|
| 662 |
-
const params: Record<string, string> = { segment, limit: String(PAGE) };
|
| 663 |
-
if (pageCursor) params.cursor = pageCursor;
|
| 664 |
-
if (q) params.q = q;
|
| 665 |
-
return url("/skus", params);
|
| 666 |
-
}, [url, segment, q]);
|
| 667 |
-
const requestUrl = listUrl(cursor);
|
| 668 |
-
const latestRequest = useRef(requestUrl);
|
| 669 |
-
latestRequest.current = requestUrl;
|
| 670 |
-
const previousScope = useRef("");
|
| 671 |
-
|
| 672 |
-
useEffect(() => {
|
| 673 |
-
const controller = new AbortController();
|
| 674 |
-
if (previousScope.current !== scope) setPage({ phase: "loading" });
|
| 675 |
-
previousScope.current = scope;
|
| 676 |
-
setPageBusy(true);
|
| 677 |
-
const want = segment;
|
| 678 |
-
void fetch(requestUrl, { credentials: CREDENTIALS, signal: controller.signal })
|
| 679 |
-
.then((response) => readJson(response, "The server gave no reason."))
|
| 680 |
-
.then((body) => { if (!controller.signal.aborted && latestRequest.current === requestUrl)
|
| 681 |
-
setPage({ phase: "ready", value: parsePage(body, want) }); })
|
| 682 |
-
.catch((reason: unknown) => {
|
| 683 |
-
if (!controller.signal.aborted && latestRequest.current === requestUrl)
|
| 684 |
-
setPage({ phase: "error", message: failure(reason, "The server gave no reason.") });
|
| 685 |
-
}).finally(() => { if (!controller.signal.aborted && latestRequest.current === requestUrl) setPageBusy(false); });
|
| 686 |
-
return () => controller.abort();
|
| 687 |
-
}, [requestUrl, segment, scope, pageAttempt]);
|
| 688 |
-
|
| 689 |
-
const screen = page.phase === "ready" ? page.value : null;
|
| 690 |
-
const kpis = summary.phase === "ready" ? summary.value : null;
|
| 691 |
-
const editable = canEdit === true && kpis?.canEdit === true && meta?.canEdit === true;
|
| 692 |
-
|
| 693 |
-
const openRow = (key: string, title: string) => {
|
| 694 |
-
opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
| 695 |
-
setOpened({ key, title });
|
| 696 |
-
};
|
| 697 |
-
const closeRow = useCallback(() => {
|
| 698 |
-
setOpened(null);
|
| 699 |
-
opener.current?.focus();
|
| 700 |
-
}, []);
|
| 701 |
-
const saved = useCallback((key: string, item: Item) => {
|
| 702 |
-
setPage((current) => current.phase !== "ready" ? current : { phase: "ready", value: {
|
| 703 |
-
...current.value, rows: current.value.rows.map((row) => (row.key === key ? { ...row, itemStatus: item.status } : row)),
|
| 704 |
-
} });
|
| 705 |
-
}, []);
|
| 706 |
-
|
| 707 |
-
const pickSegment = (next: Segment) => {
|
| 708 |
-
setSegment(next);
|
| 709 |
-
setOpened(null);
|
| 710 |
-
};
|
| 711 |
-
const pickDays = (next: number) => {
|
| 712 |
-
setDays(next);
|
| 713 |
-
setOpened(null);
|
| 714 |
-
};
|
| 715 |
-
|
| 716 |
-
const rowsShown = screen ? (segment === "repeat" ? screen.repeat.length : screen.rows.length) : 0;
|
| 717 |
-
const label = SEGMENTS.find(([key]) => key === segment)?.[1] ?? "";
|
| 718 |
-
return <div className="rr-app">
|
| 719 |
-
<div className="rr-scroll">
|
| 720 |
-
<div className="rr-bar">
|
| 721 |
-
<div className="rr-period" role="group" aria-label="Period">
|
| 722 |
-
{PERIODS.map((value) => <button key={value} type="button" aria-pressed={days === value}
|
| 723 |
-
className={days === value ? "rr-period-option is-active" : "rr-period-option"}
|
| 724 |
-
onClick={() => pickDays(value)}>Last {value} days</button>)}
|
| 725 |
-
</div>
|
| 726 |
-
<span className="rr-muted rr-nowrap rr-range">{day(period.start)} to {day(period.end)}</span>
|
| 727 |
-
</div>
|
| 728 |
-
|
| 729 |
-
<section className="rr-kpis" aria-label="Key figures">
|
| 730 |
-
{summary.phase === "loading" && <>
|
| 731 |
-
<div className="rr-kpi is-skeleton" aria-busy="true" aria-label="Loading" />
|
| 732 |
-
<div className="rr-kpi is-skeleton" aria-busy="true" aria-label="Loading" />
|
| 733 |
-
</>}
|
| 734 |
-
{kpis && <>
|
| 735 |
-
<KpiCard kpi="return-rate" label="Return rate" value={kpis.returnRate} previous={kpis.previous.returnRate}
|
| 736 |
-
days={days} trend={kpis.trend} />
|
| 737 |
-
<KpiCard kpi="repeat-share" label="Repeat purchase share" value={kpis.repeatShare}
|
| 738 |
-
previous={kpis.previous.repeatShare} days={days} />
|
| 739 |
-
</>}
|
| 740 |
-
</section>
|
| 741 |
-
{kpis && <>
|
| 742 |
-
<Pager page={kpis} busy={summaryBusy} label="Summary pages"
|
| 743 |
-
onPage={(next) => setSummaryNavigation({ scope: summaryScope, cursor: next })} />
|
| 744 |
-
{(kpis.cursor || kpis.previousCursor) && kpis.repeatMonths.length > 0
|
| 745 |
-
&& <p className="rr-muted">Repeat months: {kpis.repeatMonths.join(", ")}</p>}
|
| 746 |
-
</>}
|
| 747 |
-
{summary.phase === "error" && <Failed what="The summary did not load." message={summary.message}
|
| 748 |
-
onRetry={() => setSummaryAttempt((count) => count + 1)} />}
|
| 749 |
-
{kpis?.empty && <p className="rr-empty-period" role="status">{kpis.emptyMessage || EMPTY_PERIOD}</p>}
|
| 750 |
-
|
| 751 |
-
<div className="rr-tabs" role="tablist" aria-label="Segments">
|
| 752 |
-
{SEGMENTS.map(([key, name]) => <button key={key} type="button" role="tab" aria-selected={segment === key}
|
| 753 |
-
data-segment={key} className={segment === key ? "rr-tab is-active" : "rr-tab"} onClick={() => pickSegment(key)}>
|
| 754 |
-
{name}{kpis && <span className="rr-count">{qty(kpis.counts[key])}</span>}
|
| 755 |
-
</button>)}
|
| 756 |
-
</div>
|
| 757 |
-
|
| 758 |
-
<div className="rr-body" role="tabpanel" aria-label={label}>
|
| 759 |
-
{page.phase === "loading" && <Skeleton />}
|
| 760 |
-
{page.phase === "error" && <Failed what={`The ${label.toLowerCase()} list did not load.`} message={page.message}
|
| 761 |
-
onRetry={() => setPageAttempt((count) => count + 1)} />}
|
| 762 |
-
{/* One empty sentence: an empty period already says so above the tabs. */}
|
| 763 |
-
<div className="rr-tools">
|
| 764 |
-
<input type="search" className="rr-input rr-search" value={search} aria-label={SEARCH_LABEL}
|
| 765 |
-
placeholder={SEARCH_LABEL} onChange={(event) => setSearch(event.target.value)} />
|
| 766 |
-
</div>
|
| 767 |
-
{screen && rowsShown === 0 && q && <p className="rr-empty" role="status">{NO_MATCH}</p>}
|
| 768 |
-
{screen && rowsShown === 0 && !q && !(kpis?.empty && segment !== "repeat")
|
| 769 |
-
&& <p className="rr-empty" role="status">{EMPTY_SEGMENT[segment]}</p>}
|
| 770 |
-
{screen && rowsShown > 0 && <span className="rr-muted rr-result">
|
| 771 |
-
{`${qty(screen.offset + 1)} to ${qty(screen.offset + rowsShown)} of ${qty(screen.total)}`}
|
| 772 |
-
{screen.total === 1 ? (segment === "repeat" ? " ASIN" : " SKU") : (segment === "repeat" ? " ASINs" : " SKUs")}
|
| 773 |
-
</span>}
|
| 774 |
-
{screen && rowsShown > 0 && segment !== "repeat"
|
| 775 |
-
&& <SkuTable rows={screen.rows} rising={segment === "rising"} onOpen={openRow} />}
|
| 776 |
-
{screen && rowsShown > 0 && segment === "repeat" && <RepeatTable rows={screen.repeat} onOpen={openRow} />}
|
| 777 |
-
{screen && <Pager page={screen} busy={pageBusy} label="SKU pages"
|
| 778 |
-
onPage={(next) => { setNavigation({ scope, cursor: next }); setOpened(null); }} />}
|
| 779 |
-
</div>
|
| 780 |
-
</div>
|
| 781 |
-
{opened && <Drawer key={`${opened.key}:${period.start}`} rowKey={opened.key} title={opened.title} editable={editable}
|
| 782 |
-
meta={meta} url={url} onSaved={saved} onClose={closeRow} />}
|
| 783 |
-
</div>;
|
| 784 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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