fsanyoto commited on
Commit
cdb06e5
·
verified ·
1 Parent(s): 4a51aa3

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "340e8a3363",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "2bc6edf7a",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 340e8a3363
 
1
+ 2bc6edf7a
api/main.py CHANGED
@@ -703,7 +703,7 @@ app.include_router(routes_geo.router) # R14 / A11 — D's router, A's
703
  app.include_router(routes_external.router)
704
  import app_routes
705
  _mount_router("routes_security") # W59-T43: lane F declares the router; keep before static mount.
706
- _mount_router("routes_amazon_profit") # S78-T03: the Amazon SKU profit refresh and settings doors.
707
  _mount_router("routes_odoo_attachments") # S78-T14 (lane G, C5): delivery photo doors; before static mount.
708
  _mount_router("routes_sku_actions")
709
  _mount_router("notify_destinations")
 
703
  app.include_router(routes_external.router)
704
  import app_routes
705
  _mount_router("routes_security") # W59-T43: lane F declares the router; keep before static mount.
706
+ _mount_router("routes_amazon_profit") # S78-T03: the Command Center refresh and settings doors.
707
  _mount_router("routes_odoo_attachments") # S78-T14 (lane G, C5): delivery photo doors; before static mount.
708
  _mount_router("routes_sku_actions")
709
  _mount_router("notify_destinations")
api/routes_amazon_profit.py CHANGED
@@ -1,5 +1,5 @@
1
- """Amazon SKU profit doors: read the settings, switch the period, recompute, set the owner,
2
- and confirm or reject a suggested Odoo match.
3
 
4
  The table itself (`ut_amazon_sku_profit`) is read and edited through the ordinary table doors.
5
  A refresh rewrites only computed columns, so owner, status and due date survive a period switch.
@@ -19,7 +19,7 @@ router = APIRouter(prefix="/api/v1")
19
 
20
  def _admin(session):
21
  if not session.admin:
22
- raise err(403, "forbidden", "Only an Administrator can refresh Amazon SKU profit.")
23
 
24
 
25
  def _may_edit(session):
@@ -118,7 +118,7 @@ def profit_account(period: str | None = None, session: Session = Depends(require
118
  except ValueError as exc:
119
  raise err(400, "invalid_setting", str(exc)) from None
120
  if definition is None:
121
- return {"empty": True, "validated": False, "reason": "Refresh Amazon SKU profit first",
122
  "tableKey": amazon_profit.TABLE_KEY}
123
  con = _mirror(session.runtime)
124
  try:
@@ -142,7 +142,7 @@ def profit_what_if(sku: str, price: float | None = None, landed_cost: float | No
142
  """Read a period-matched SKU model through the account permission wall without refreshing."""
143
  definition = _account_access(session, amazon_profit_account.WHAT_IF_FIELDS)
144
  if definition is None:
145
- return {"sku": sku, "label": "Model", "available": False, "reason": "Refresh Amazon SKU profit first."}
146
  con = _mirror(session.runtime)
147
  try:
148
  settings = amazon_profit.read_settings(session.runtime)
@@ -199,7 +199,7 @@ def profit_refresh(body: Any = Body(default=None), session: Session = Depends(re
199
  def profit_period(body: Any = Body(default=None), session: Session = Depends(require_session)):
200
  """Switch the table to another period and recompute every row; owned cells stay."""
201
  if not _may_edit(session):
202
- raise err(403, "forbidden", "Only an editor of Amazon SKU profit can change its period.")
203
  body = body if isinstance(body, dict) else {}
204
  period = body.get("period")
205
  if not period:
@@ -207,11 +207,21 @@ def profit_period(body: Any = Body(default=None), session: Session = Depends(req
207
  return _recompute(session, period)
208
 
209
 
 
 
 
 
 
 
 
 
 
 
210
  @router.put("/amazon-profit/settings")
211
  def profit_settings(body: Any = Body(default=None), session: Session = Depends(require_session)):
212
  """Administrator settings: the default owner of new items and the thin margin."""
213
  if not session.admin:
214
- raise err(403, "forbidden", "Only an Administrator can change Amazon SKU profit settings.")
215
  body = body if isinstance(body, dict) else {}
216
  try:
217
  if "defaultOwner" in body:
@@ -237,12 +247,12 @@ def profit_match(sku: str, decision: str, session: Session = Depends(require_ses
237
  if decision not in states:
238
  raise err(404, "not_found", "Choose confirm or reject.")
239
  if not _may_edit(session):
240
- raise err(403, "forbidden", "Only an editor of Amazon SKU profit can confirm or reject a match.")
241
  sku = str(sku or "").strip()
242
  rows = [r for r in amazon_profit.table_rows(session.runtime).values()
243
  if str(r.get("sku") or "").strip() == sku]
244
  if ut.get_one(amazon_profit.TABLE_KEY, session.runtime) is None or not rows:
245
- raise err(404, "not_found", "This SKU is not in Amazon SKU profit.")
246
  row = rows[0]
247
  if str(row.get("odoo_product") or "").strip():
248
  raise err(409, "already_linked", "This SKU already has an Odoo product.")
 
1
+ """Command Center doors: read the settings, switch the period, recompute, set the owner,
2
+ confirm or reject a suggested Odoo match, and relink projects.
3
 
4
  The table itself (`ut_amazon_sku_profit`) is read and edited through the ordinary table doors.
5
  A refresh rewrites only computed columns, so owner, status and due date survive a period switch.
 
19
 
20
  def _admin(session):
21
  if not session.admin:
22
+ raise err(403, "forbidden", "Only an Administrator can refresh Command Center.")
23
 
24
 
25
  def _may_edit(session):
 
118
  except ValueError as exc:
119
  raise err(400, "invalid_setting", str(exc)) from None
120
  if definition is None:
121
+ return {"empty": True, "validated": False, "reason": "Refresh Command Center first",
122
  "tableKey": amazon_profit.TABLE_KEY}
123
  con = _mirror(session.runtime)
124
  try:
 
142
  """Read a period-matched SKU model through the account permission wall without refreshing."""
143
  definition = _account_access(session, amazon_profit_account.WHAT_IF_FIELDS)
144
  if definition is None:
145
+ return {"sku": sku, "label": "Model", "available": False, "reason": "Refresh Command Center first."}
146
  con = _mirror(session.runtime)
147
  try:
148
  settings = amazon_profit.read_settings(session.runtime)
 
199
  def profit_period(body: Any = Body(default=None), session: Session = Depends(require_session)):
200
  """Switch the table to another period and recompute every row; owned cells stay."""
201
  if not _may_edit(session):
202
+ raise err(403, "forbidden", "Only an editor of Command Center can change its period.")
203
  body = body if isinstance(body, dict) else {}
204
  period = body.get("period")
205
  if not period:
 
207
  return _recompute(session, period)
208
 
209
 
210
+ @router.post("/amazon-profit/projects/relink")
211
+ def projects_relink(session: Session = Depends(require_session)):
212
+ """Write every project's row id onto its SKU, ASIN and parent ASIN rows; editors only."""
213
+ if not _may_edit(session):
214
+ raise err(403, "forbidden", "Only an editor of Command Center can relink projects.")
215
+ with amazon_profit._LOCK:
216
+ linked = amazon_profit.relink_projects(session.runtime)
217
+ return {"ok": True, "linked": linked}
218
+
219
+
220
  @router.put("/amazon-profit/settings")
221
  def profit_settings(body: Any = Body(default=None), session: Session = Depends(require_session)):
222
  """Administrator settings: the default owner of new items and the thin margin."""
223
  if not session.admin:
224
+ raise err(403, "forbidden", "Only an Administrator can change Command Center settings.")
225
  body = body if isinstance(body, dict) else {}
226
  try:
227
  if "defaultOwner" in body:
 
247
  if decision not in states:
248
  raise err(404, "not_found", "Choose confirm or reject.")
249
  if not _may_edit(session):
250
+ raise err(403, "forbidden", "Only an editor of Command Center can confirm or reject a match.")
251
  sku = str(sku or "").strip()
252
  rows = [r for r in amazon_profit.table_rows(session.runtime).values()
253
  if str(r.get("sku") or "").strip() == sku]
254
  if ut.get_one(amazon_profit.TABLE_KEY, session.runtime) is None or not rows:
255
+ raise err(404, "not_found", "This SKU is not in Command Center.")
256
  row = rows[0]
257
  if str(row.get("odoo_product") or "").strip():
258
  raise err(409, "already_linked", "This SKU already has an Odoo product.")
platform/aios_grid.py CHANGED
@@ -169,7 +169,7 @@ def _round2(v):
169
  CUSTOM_FIELD_TYPES = {"text", "long_text", "select", "multiselect", "user", "int", "currency", "pct", "date",
170
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
171
  "automation", "image", "json", "link", "rollup", "code", "ai_enrich", "if", "autonumber",
172
- "created_by", "last_modified_time", "last_modified_by"}
173
 
174
  #: ⭐ WAVE-27 item 13 (owner ruling R13) — the `code` field's LANGUAGES.
175
  #:
@@ -213,7 +213,7 @@ def _clean_code(raw):
213
  #: Emitted with the cohort column's read-only mechanism — `source: 'odoo'` + `derived` — so
214
  #: the client never offers an editor and the host never accepts a cell write for them.
215
  READONLY_CUSTOM_TYPES = {"created_time", "formula", "if", "autonumber",
216
- "created_by", "last_modified_time", "last_modified_by"}
217
  # Mirrored server persistence ceiling. ``core.route_system.MAX_OPTIONS`` owns what is published
218
  # to clients; the focused contract gate keeps this import-free helper equal to that value.
219
  MAX_FIELD_OPTIONS = 200
 
169
  CUSTOM_FIELD_TYPES = {"text", "long_text", "select", "multiselect", "user", "int", "currency", "pct", "date",
170
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
171
  "automation", "image", "json", "link", "rollup", "code", "ai_enrich", "if", "autonumber",
172
+ "created_by", "last_modified_time", "last_modified_by", "chart"}
173
 
174
  #: ⭐ WAVE-27 item 13 (owner ruling R13) — the `code` field's LANGUAGES.
175
  #:
 
213
  #: Emitted with the cohort column's read-only mechanism — `source: 'odoo'` + `derived` — so
214
  #: the client never offers an editor and the host never accepts a cell write for them.
215
  READONLY_CUSTOM_TYPES = {"created_time", "formula", "if", "autonumber",
216
+ "created_by", "last_modified_time", "last_modified_by", "chart"}
217
  # Mirrored server persistence ceiling. ``core.route_system.MAX_OPTIONS`` owns what is published
218
  # to clients; the focused contract gate keeps this import-free helper equal to that value.
219
  MAX_FIELD_OPTIONS = 200
platform/core/registry.py CHANGED
@@ -225,7 +225,7 @@ REGISTRY = [
225
  {'key': 'customer_card', 'label': 'Customer Card', 'brand': True, 'hq': False, 'validate': True,
226
  'validate_only': True, 'nav': False, 'source': 'Odoo',
227
  'note': 'Template App customer receivables independently tied to res.partner.credit.'},
228
- {'key': 'amazon_profit', 'label': 'Amazon SKU profit', 'brand': False, 'hq': True,
229
  'validate': True, 'validate_only': True, 'nav': False, 'source': 'Amazon',
230
  'note': 'Per SKU Amazon net profit, margin and band in the module table '
231
  'ut_amazon_sku_profit (Odoo cost times units). The row keeps validate.py tying '
 
225
  {'key': 'customer_card', 'label': 'Customer Card', 'brand': True, 'hq': False, 'validate': True,
226
  'validate_only': True, 'nav': False, 'source': 'Odoo',
227
  'note': 'Template App customer receivables independently tied to res.partner.credit.'},
228
+ {'key': 'amazon_profit', 'label': 'Command Center', 'brand': False, 'hq': True,
229
  'validate': True, 'validate_only': True, 'nav': False, 'source': 'Amazon',
230
  'note': 'Per SKU Amazon net profit, margin and band in the module table '
231
  'ut_amazon_sku_profit (Odoo cost times units). The row keeps validate.py tying '
platform/core/user_tables.py CHANGED
@@ -308,11 +308,24 @@ def counts_toward_table_cap(table_key, definition=None):
308
  spawn's updater holds the raw document rather than a store.
309
  """
310
  key = str(table_key or '').strip()
311
- if key in _CONNECTED:
312
  return False
313
  return not _connected_definition(key, definition if isinstance(definition, dict) else {})
314
 
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  def capped_table_count(tables):
317
  """How many `MAX_TABLES` slots `{key: definition}` uses. Connector databases take none."""
318
  return sum(1 for k, d in (tables or {}).items() if counts_toward_table_cap(k, d))
@@ -814,7 +827,8 @@ def purge_credential_tables(entry_type, connection_id, rt=None, st=None):
814
  return out
815
 
816
 
817
- MAX_FIELDS = 60
 
818
  #: the badge the nav paints for a table with no connector behind it
819
  BLANK_SOURCE = 'Blank'
820
  #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
@@ -971,7 +985,7 @@ def records_mutable(table_key, st=None):
971
  UT_FIELD_TYPES = {'text', 'long_text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
972
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
973
  'link', 'rollup', 'code', 'image', 'formula', 'ai_enrich', 'if', 'autonumber',
974
- 'created_by', 'last_modified_time', 'last_modified_by'}
975
  AUDIT_FIELD_TYPES = frozenset({'created_by', 'last_modified_time', 'last_modified_by'})
976
  FIELD_ORIGINS = {'odoo', 'loopable', 'system', 'user', 'automation'}
977
  FIELD_AUTHORITIES = {'source', 'derived', 'user-entered', 'computed'}
@@ -1646,9 +1660,38 @@ def _clean_format(raw):
1646
  tz = str(raw.get('tz') or '').strip().lower()
1647
  if tz in FORMAT_TZ:
1648
  out['tz'] = tz
 
 
 
 
 
 
 
 
 
1649
  return out or None
1650
 
1651
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1652
  def _default_value_valid(field, value):
1653
  """Validate a scalar default with the field's existing cell rules."""
1654
  return (field.get('type') in ('text', 'int', 'currency', 'pct', 'select', 'date',
 
308
  spawn's updater holds the raw document rather than a store.
309
  """
310
  key = str(table_key or '').strip()
311
+ if key in _CONNECTED or key in _MODULE_OWNED:
312
  return False
313
  return not _connected_definition(key, definition if isinstance(definition, dict) else {})
314
 
315
 
316
+ #: A module's own databases (Command Center's four) are not what people create: no cap slot either.
317
+ _MODULE_OWNED = set()
318
+
319
+
320
+ def register_module_tables(*keys):
321
+ """Declare table keys a module creates and writes itself. Idempotent; -> the registered set."""
322
+ for k in keys:
323
+ for one in (k if isinstance(k, (set, frozenset, list, tuple)) else (k,)):
324
+ if str(one or '').strip():
325
+ _MODULE_OWNED.add(str(one).strip())
326
+ return frozenset(_MODULE_OWNED)
327
+
328
+
329
  def capped_table_count(tables):
330
  """How many `MAX_TABLES` slots `{key: definition}` uses. Connector databases take none."""
331
  return sum(1 for k, d in (tables or {}).items() if counts_toward_table_cap(k, d))
 
827
  return out
828
 
829
 
830
+ #: Command Center's SKU table carries 64 module columns, and a person must still be able to add a field.
831
+ MAX_FIELDS = 100
832
  #: the badge the nav paints for a table with no connector behind it
833
  BLANK_SOURCE = 'Blank'
834
  #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
 
985
  UT_FIELD_TYPES = {'text', 'long_text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
986
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
987
  'link', 'rollup', 'code', 'image', 'formula', 'ai_enrich', 'if', 'autonumber',
988
+ 'created_by', 'last_modified_time', 'last_modified_by', 'chart'}
989
  AUDIT_FIELD_TYPES = frozenset({'created_by', 'last_modified_time', 'last_modified_by'})
990
  FIELD_ORIGINS = {'odoo', 'loopable', 'system', 'user', 'automation'}
991
  FIELD_AUTHORITIES = {'source', 'derived', 'user-entered', 'computed'}
 
1660
  tz = str(raw.get('tz') or '').strip().lower()
1661
  if tz in FORMAT_TZ:
1662
  out['tz'] = tz
1663
+ # Module display keys: a score bar, a health dot, a named link count and its popup add recipe.
1664
+ if raw.get('display') in ('bar', 'dot'):
1665
+ out['display'] = raw['display']
1666
+ for key in ('linkLabel', 'addLabel'):
1667
+ if isinstance(raw.get(key), str) and 1 <= len(raw[key]) <= 40:
1668
+ out[key] = raw[key]
1669
+ seed = _clean_link_seed(raw.get('seed'))
1670
+ if seed:
1671
+ out['seed'] = seed
1672
  return out or None
1673
 
1674
 
1675
+ def _clean_link_seed(raw):
1676
+ """A link popup's add recipe in the stored shape, or None when any part is malformed."""
1677
+ if not isinstance(raw, dict):
1678
+ return None
1679
+ out = {}
1680
+ for key in ('keyFrom', 'keyField', 'titleField', 'relink'):
1681
+ value = raw.get(key)
1682
+ if not isinstance(value, str) or not 1 <= len(value) <= 80:
1683
+ return None
1684
+ out[key] = value
1685
+ if not out['relink'].startswith('/'):
1686
+ return None
1687
+ values = raw.get('values')
1688
+ if not isinstance(values, dict) or not all(
1689
+ isinstance(k, str) and isinstance(v, str) for k, v in values.items()):
1690
+ return None
1691
+ out['values'] = dict(values)
1692
+ return out
1693
+
1694
+
1695
  def _default_value_valid(field, value):
1696
  """Validate a scalar default with the field's existing cell rules."""
1697
  return (field.get('type') in ('text', 'int', 'currency', 'pct', 'select', 'date',
platform/core/view_templates.py CHANGED
@@ -110,6 +110,13 @@ def _view(view_id, name, note, visible, *, mode='grid', stack_field=None, sorts=
110
  # that MATTERS runs at apply time, against the target the user actually picked, because a
111
  # contract can move and a ut_ table's columns are whatever its owner made.
112
 
 
 
 
 
 
 
 
113
  TEMPLATES = [
114
  {
115
  'key': 'collections_focus',
@@ -240,10 +247,24 @@ TEMPLATES = [
240
  # SDLC 78 (R7, R12). `modules/amazon_profit.py` writes these onto its own table when it
241
  # creates or adopts it and grants them to everyone who can open it, so nobody applies them.
242
  'key': 'amazon_sku_profit',
243
- 'label': 'Amazon money losers',
244
- 'desc': 'Amazon SKUs that lose money, run thin, or have no cost to measure.',
 
245
  'source': 'amazon',
246
  'views': [
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  _view(
248
  'tpl_amazon_sku_profit_losing', 'Losing',
249
  'SKUs whose net profit is below 0 in this period, worst first.',
@@ -274,9 +295,83 @@ TEMPLATES = [
274
  ),
275
  ],
276
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  ]
278
 
279
 
 
280
  def get(key):
281
  """One template by key, or None."""
282
  return next((t for t in TEMPLATES if t['key'] == str(key)), None)
 
110
  # that MATTERS runs at apply time, against the target the user actually picked, because a
111
  # contract can move and a ut_ table's columns are whatever its owner made.
112
 
113
+ #: Command Center columns every grain view shows after its ids, score first.
114
+ _CC_HEALTH = ['score', 'priority', 'stock_health', 'profit_health', 'ads_health', 'listing_health',
115
+ 'units_sold', 'net_sales', 'net_profit', 'margin', 'ctr', 'acos', 'tacos', 'days_of_cover',
116
+ 'return_rate']
117
+ _CC_PROJECT = ['title', 'grain', 'key', 'owner', 'status', 'health', 'start_on', 'deadline_on',
118
+ 'completed_on', 'impact', 'net_sales_since', 'net_sales_prior', 'impact_units', 'impact_state']
119
+
120
  TEMPLATES = [
121
  {
122
  'key': 'collections_focus',
 
247
  # SDLC 78 (R7, R12). `modules/amazon_profit.py` writes these onto its own table when it
248
  # creates or adopts it and grants them to everyone who can open it, so nobody applies them.
249
  'key': 'amazon_sku_profit',
250
+ 'label': 'Command Center: SKU',
251
+ 'desc': 'Every Amazon SKU ranked by health score, plus the ones that lose money, run thin, '
252
+ 'or have no cost to measure.',
253
  'source': 'amazon',
254
  'views': [
255
+ _view(
256
+ 'tpl_amazon_sku_profit_all_skus', 'All SKUs',
257
+ 'Every SKU with the columns that matter first, lowest score first.',
258
+ ['sku', 'asin', 'parent_asin', 'title'] + _CC_HEALTH + ['projects'],
259
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
260
+ ),
261
+ _view(
262
+ 'tpl_amazon_sku_profit_priority_high', 'Priority High',
263
+ 'SKUs that need attention first, lowest score first.',
264
+ ['sku', 'asin', 'parent_asin', 'title'] + _CC_HEALTH + ['projects'],
265
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
266
+ filters=[{'colId': 'priority', 'op': 'eq', 'value': 'High'}],
267
+ ),
268
  _view(
269
  'tpl_amazon_sku_profit_losing', 'Losing',
270
  'SKUs whose net profit is below 0 in this period, worst first.',
 
295
  ),
296
  ],
297
  },
298
+ {
299
+ # `modules/amazon_profit.py` writes these onto `ut_amazon_asin_profit` on every refresh.
300
+ 'key': 'amazon_asin_profit',
301
+ 'label': 'Command Center: ASIN',
302
+ 'desc': 'Every Amazon ASIN, its SKUs rolled up, ranked by health score.',
303
+ 'source': 'amazon',
304
+ 'views': [
305
+ _view(
306
+ 'tpl_amazon_asin_profit_all_asins', 'All ASINs',
307
+ 'Every ASIN with the columns that matter first, lowest score first.',
308
+ ['asin', 'parent_asin', 'title', 'sku_count'] + _CC_HEALTH + ['projects'],
309
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
310
+ ),
311
+ _view(
312
+ 'tpl_amazon_asin_profit_priority_high', 'Priority High',
313
+ 'ASINs that need attention first, lowest score first.',
314
+ ['asin', 'parent_asin', 'title', 'sku_count'] + _CC_HEALTH + ['projects'],
315
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
316
+ filters=[{'colId': 'priority', 'op': 'eq', 'value': 'High'}],
317
+ ),
318
+ ],
319
+ },
320
+ {
321
+ # `modules/amazon_profit.py` writes these onto `ut_amazon_parent_profit` on every refresh.
322
+ 'key': 'amazon_parent_profit',
323
+ 'label': 'Command Center: Parent ASIN',
324
+ 'desc': 'Every Amazon parent ASIN, its children rolled up, ranked by health score.',
325
+ 'source': 'amazon',
326
+ 'views': [
327
+ _view(
328
+ 'tpl_amazon_parent_profit_all_parents', 'All parents',
329
+ 'Every parent ASIN with the columns that matter first, lowest score first.',
330
+ ['parent_asin', 'title', 'sku_count'] + _CC_HEALTH + ['projects'],
331
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
332
+ ),
333
+ _view(
334
+ 'tpl_amazon_parent_profit_priority_high', 'Priority High',
335
+ 'Parent ASINs that need attention first, lowest score first.',
336
+ ['parent_asin', 'title', 'sku_count'] + _CC_HEALTH + ['projects'],
337
+ sorts=[{'colId': 'score', 'dir': 'asc'}],
338
+ filters=[{'colId': 'priority', 'op': 'eq', 'value': 'High'}],
339
+ ),
340
+ ],
341
+ },
342
+ {
343
+ # `modules/amazon_profit.py` writes these onto `ut_amazon_projects` on every refresh.
344
+ 'key': 'amazon_projects',
345
+ 'label': 'Command Center: Projects',
346
+ 'desc': 'Projects on Amazon SKUs, ASINs and parent ASINs, with their deadline and impact.',
347
+ 'source': 'amazon',
348
+ 'views': [
349
+ _view(
350
+ 'tpl_amazon_projects_open', 'Open',
351
+ 'Projects still running, nearest deadline first.',
352
+ _CC_PROJECT,
353
+ sorts=[{'colId': 'deadline_on', 'dir': 'asc'}],
354
+ filters=[{'colId': 'status', 'op': 'eq', 'value': 'Open'}],
355
+ ),
356
+ _view(
357
+ 'tpl_amazon_projects_done', 'Done',
358
+ 'Finished projects with their impact, newest first.',
359
+ _CC_PROJECT,
360
+ sorts=[{'colId': 'completed_on', 'dir': 'desc'}],
361
+ filters=[{'colId': 'status', 'op': 'eq', 'value': 'Done'}],
362
+ ),
363
+ _view(
364
+ 'tpl_amazon_projects_all_projects', 'All projects',
365
+ 'Every project, nearest deadline first.',
366
+ _CC_PROJECT,
367
+ sorts=[{'colId': 'deadline_on', 'dir': 'asc'}],
368
+ ),
369
+ ],
370
+ },
371
  ]
372
 
373
 
374
+
375
  def get(key):
376
  """One template by key, or None."""
377
  return next((t for t in TEMPLATES if t['key'] == str(key)), None)
platform/model/metrics/amazon_profit.yml CHANGED
@@ -1,9 +1,9 @@
1
- # Amazon SKU profit. The module (platform/modules/amazon_profit.py) owns the per SKU table
2
  # ut_amazon_sku_profit and registers the amazon_sku_net_profit validator when it loads.
3
  # harness/semantic.py imports that validator, so the topic declares its measure at model load.
4
  topics:
5
  - key: amazon_sku_profit
6
- label: "Amazon SKU profit"
7
  entity: amazon.sku_profit
8
  grain: "one row per Amazon seller SKU for the chosen period"
9
  semantic:
@@ -48,7 +48,7 @@ metrics:
48
  COGS is the linked Odoo product cost times units per SKU times net units sold.
49
  A SKU with no Odoo link has a blank net profit and belongs in the COGS missing view; never treat it as zero.
50
  Losing means net profit below zero. Thin means margin below the thin threshold, 10% of net sales by default.
51
- Read the figures from the Amazon SKU profit database.
52
  validate:
53
  method: amazon_sku_net_profit
54
  independent: >
 
1
+ # Command Center. The module (platform/modules/amazon_profit.py) owns the per SKU table
2
  # ut_amazon_sku_profit and registers the amazon_sku_net_profit validator when it loads.
3
  # harness/semantic.py imports that validator, so the topic declares its measure at model load.
4
  topics:
5
  - key: amazon_sku_profit
6
+ label: "Command Center"
7
  entity: amazon.sku_profit
8
  grain: "one row per Amazon seller SKU for the chosen period"
9
  semantic:
 
48
  COGS is the linked Odoo product cost times units per SKU times net units sold.
49
  A SKU with no Odoo link has a blank net profit and belongs in the COGS missing view; never treat it as zero.
50
  Losing means net profit below zero. Thin means margin below the thin threshold, 10% of net sales by default.
51
+ Read the figures from the Command Center database.
52
  validate:
53
  method: amazon_sku_net_profit
54
  independent: >
platform/modules/amazon_operator.py CHANGED
@@ -102,9 +102,9 @@ TIME_BASELINE = {"low": 10, "high": 20, "unit": "hours per week", "source": "R13
102
  BAR = {"ads_hours_per_week_under": 3, "profit_after_cogs": "level or up", "days": 60, "source": "R15, R52"}
103
  BASELINE_BASIS = ("Ad sales minus ad cost minus ad orders times COGS per unit, for linked SKUs only. "
104
  "Ad orders stand in for units. Unlinked SKUs are left out and counted.")
105
- NO_COGS = "No COGS yet. Link this SKU in Amazon SKU profit."
106
- NO_SKU = "No SKU on this ad. Its ASIN matches no SKU in Amazon SKU profit or inventory planning."
107
- NO_PROFIT = "No profit after COGS yet. Refresh Amazon SKU profit."
108
  NO_COVER = "No cover yet. Inventory planning has no days of supply for this SKU."
109
  NO_CLICKS = "No clicks in the lookback, so there is no bid to raise."
110
  LIMIT = ("Each Amazon operator document is limited to 128 MB by the store. About 120,000 proposals "
@@ -317,7 +317,7 @@ def _cover(cur):
317
 
318
 
319
  def _profit(st):
320
- """{sku: {"linked", "cogs_per_unit", "net_profit", "asin"}} from the Amazon SKU profit table."""
321
  import core.user_tables as ut
322
  rows = (ut.get_one(PROFIT_TABLE, st) or {}).get("rows") or {}
323
  out = {}
@@ -1194,7 +1194,7 @@ def _result_window(tenant_key, st, cur, prop, start, end, *, spend_only=False):
1194
  if sales <= 0:
1195
  reasons.append("ACOS is unavailable because ad sales are zero or negative.")
1196
  if unlinked or out["rows_without_sku"] or not linked:
1197
- reasons.append("Profit excludes rows without linked COGS. Link the missing SKUs in Amazon SKU profit.")
1198
  if out["ad_profit_after_cogs"] is None or out["acos"] is None or unlinked or out["rows_without_sku"]:
1199
  out["state"] = "partial"
1200
  out["reason"] = " ".join(reasons) or None
 
102
  BAR = {"ads_hours_per_week_under": 3, "profit_after_cogs": "level or up", "days": 60, "source": "R15, R52"}
103
  BASELINE_BASIS = ("Ad sales minus ad cost minus ad orders times COGS per unit, for linked SKUs only. "
104
  "Ad orders stand in for units. Unlinked SKUs are left out and counted.")
105
+ NO_COGS = "No COGS yet. Link this SKU in Command Center."
106
+ NO_SKU = "No SKU on this ad. Its ASIN matches no SKU in Command Center or inventory planning."
107
+ NO_PROFIT = "No profit after COGS yet. Refresh Command Center."
108
  NO_COVER = "No cover yet. Inventory planning has no days of supply for this SKU."
109
  NO_CLICKS = "No clicks in the lookback, so there is no bid to raise."
110
  LIMIT = ("Each Amazon operator document is limited to 128 MB by the store. About 120,000 proposals "
 
317
 
318
 
319
  def _profit(st):
320
+ """{sku: {"linked", "cogs_per_unit", "net_profit", "asin"}} from the Command Center table."""
321
  import core.user_tables as ut
322
  rows = (ut.get_one(PROFIT_TABLE, st) or {}).get("rows") or {}
323
  out = {}
 
1194
  if sales <= 0:
1195
  reasons.append("ACOS is unavailable because ad sales are zero or negative.")
1196
  if unlinked or out["rows_without_sku"] or not linked:
1197
+ reasons.append("Profit excludes rows without linked COGS. Link the missing SKUs in Command Center.")
1198
  if out["ad_profit_after_cogs"] is None or out["acos"] is None or unlinked or out["rows_without_sku"]:
1199
  out["state"] = "partial"
1200
  out["reason"] = " ".join(reasons) or None
platform/modules/amazon_profit.py CHANGED
@@ -1,4 +1,4 @@
1
- """Amazon SKU profit: one row per Amazon SKU with Odoo cost, net profit, margin and band.
2
 
3
  Net proceeds = net sales minus fees minus sponsored ads, from the `amzn_economics` mirror.
4
  COGS follows incoming receipt valuations and posted landed costs through FIFO.
@@ -7,6 +7,11 @@ edit the owned columns (Odoo product, units per SKU, owner, status, due date). A
7
  rewrites only the computed columns, keyed by SKU, so owned cells belong to the SKU and
8
  survive every period switch.
9
 
 
 
 
 
 
10
  `validate()` ties a month's net proceeds to Amazon settlements within 2%, excluding loan
11
  repayments and withheld tax, and proves a negative control that drops fees goes red.
12
  A refresh runs it for the last complete month and writes no figures when it fails.
@@ -29,8 +34,19 @@ import tempfile
29
  import threading
30
  from pathlib import Path
31
 
 
 
 
32
  TABLE_KEY = "ut_amazon_sku_profit"
33
- TABLE_LABEL = "Amazon SKU profit"
 
 
 
 
 
 
 
 
34
  SETTINGS_KEY = "amazon_profit_settings"
35
  COST_HISTORY_KEY = "amazon_profit_cost_history"
36
  VIA = "amazon_profit"
@@ -49,6 +65,13 @@ MATCH_STATES = (NEEDS_REVIEW, CONFIRMED, REJECTED)
49
  DUE_DAYS = 14
50
  REOPEN_DAYS = 30
51
  TEMPLATE_KEY = "amazon_sku_profit"
 
 
 
 
 
 
 
52
  PICKER_MONTHS = 12
53
  SETTLEMENT_TOLERANCE = 0.02
54
 
@@ -83,8 +106,24 @@ def _field(key, label, ftype, description, *, computed, **extra):
83
  return out
84
 
85
 
86
- #: Computed columns: a refresh owns them and the pre-set lock keeps people out of them.
87
- COMPUTED_FIELDS = (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  _field("sku", "SKU", "text", "Amazon seller SKU.", computed=True),
89
  _field("asin", "ASIN", "text", "Amazon product id.", computed=True),
90
  _field("title", "Title", "text", "Listing title.", computed=True),
@@ -115,6 +154,10 @@ COMPUTED_FIELDS = (
115
  computed=True),
116
  _field("odoo_margin_source", "Odoo margin source", "text", "Scope or missing Odoo margin data.", computed=True),
117
  )
 
 
 
 
118
  #: Owned columns: people edit them and a refresh never writes them.
119
  OWNED_FIELDS = (
120
  _field("odoo_product", "Odoo product", "text", "Odoo internal reference.", computed=False),
@@ -144,10 +187,90 @@ OWNED_KEYS = tuple(f["key"] for f in OWNED_FIELDS)
144
  TRACK_KEYS = tuple(f["key"] for f in TRACK_FIELDS)
145
  ALL_KEYS = COMPUTED_KEYS + OWNED_KEYS + TRACK_KEYS
146
  SUGGESTION_KEYS = ("suggested_product", "suggested_units", "match_rule")
 
147
  #: A settlement refusal blanks Amazon totals while independent receipt observations remain visible.
 
 
148
  _UNVERIFIED_KEYS = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds",
149
- "cogs_total", "net_profit", "margin", "band")
150
- _PERIOD_KEYS = tuple(k for k in COMPUTED_KEYS if k not in ("sku", "asin", "title"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
 
153
  # ---------------------------------------------------------------- period and threshold
@@ -262,8 +385,9 @@ def compute_row(econ, cost=None, units_per_sku=1, thin=THIN_DEFAULT):
262
  def cells(row, period_label=""):
263
  """Computed cells as stored strings; None means the cell is blank."""
264
  out = {}
265
- for key in COMPUTED_KEYS:
266
  value = period_label if key == "period" else row.get(key)
 
267
  if value is None or value == "":
268
  out[key] = None
269
  elif key in ("margin", "odoo_channel_margin"):
@@ -1158,19 +1282,27 @@ def on_amazon_sync(tenant_key, synced_tables):
1158
 
1159
  # ---------------------------------------------------------------- module-owned table
1160
 
1161
- def _definition_fields():
 
1162
  import core.user_tables as ut
1163
- cleaned = ut.clean_fields([dict(f) for f in COMPUTED_FIELDS + OWNED_FIELDS + TRACK_FIELDS])
1164
- by_key = {f["key"]: f for f in cleaned}
1165
- if set(by_key) != set(ALL_KEYS):
1166
- raise TableRefused("The profit columns failed the table field check.")
 
 
 
 
 
 
 
1167
  out = []
1168
- for key in ALL_KEYS:
1169
  field = dict(by_key[key])
1170
  # editRole governs the column definition only. Cell values on owned columns follow the
1171
  # database edit grant (`may_edit_database`), so editors edit them and viewers cannot.
1172
  field["editRole"] = "admins"
1173
- if key not in OWNED_KEYS:
1174
  field["automation"] = {"preset": True, "flowId": VIA}
1175
  out.append(field)
1176
  return out
@@ -1183,53 +1315,67 @@ def _format_repairs(fields, wanted):
1183
  if isinstance(f, dict) and f.get("key") in want and not f.get("format")}
1184
 
1185
 
1186
- def ensure_table(st, username):
1187
- """Create or adopt the module table; add missing columns, never retype one. Returns its key."""
 
 
 
1188
  import core.user_tables as ut
1189
- wanted = _definition_fields()
1190
- have = ut.get_one(TABLE_KEY, st)
1191
- cost_description = next(field["description"] for field in wanted if field["key"] == "cogs_per_unit")
1192
- old_description = any(field.get("key") == "cogs_per_unit" and field.get("description") != cost_description
1193
- for field in (have or {}).get("fields", []))
1194
- if (have is not None and {f["key"] for f in wanted} <= {f.get("key") for f in have.get("fields") or []}
1195
- and not _format_repairs(have.get("fields"), wanted) and not old_description):
1196
- return TABLE_KEY
 
 
 
 
 
 
 
 
 
 
 
 
 
1197
  created = dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
1198
- refused = []
1199
 
1200
  def _up(cur):
1201
  cur = cur if isinstance(cur, dict) else {}
1202
- table = cur.get(TABLE_KEY)
1203
- if table is None:
1204
- if ut.capped_table_count(cur) >= ut.MAX_TABLES:
1205
- refused.append("cap")
1206
- return cur
1207
- cur[TABLE_KEY] = {"key": TABLE_KEY, "label": TABLE_LABEL, "source": ut.AUTOMATION_SOURCE,
1208
- "createdBy": username or WRITER, "created": created,
1209
- "fields": [dict(f) for f in wanted], "rows": {}}
1210
- return cur
1211
- present = {f.get("key") for f in table.get("fields") or []}
1212
- repairs = _format_repairs(table.get("fields"), wanted)
1213
- for field in table.get("fields") or []:
1214
- if field.get("key") in repairs:
1215
- field["format"] = dict(repairs[field["key"]])
1216
- if field.get("key") == "cogs_per_unit":
1217
- field["description"] = cost_description
1218
- table.setdefault("fields", []).extend(dict(f) for f in wanted if f["key"] not in present)
 
1219
  return cur
1220
 
1221
  st.update(ut.STORE_KEY, _up, flush="sync")
1222
- if refused:
1223
- raise TableRefused(f"This workspace already holds {ut.MAX_TABLES} databases, so "
1224
- f"{TABLE_LABEL} cannot be created. Delete an unused database, then refresh.")
1225
- if ut.get_one(TABLE_KEY, st) is None:
1226
- raise TableRefused(f"The store did not keep {TABLE_LABEL}. Refresh again.")
1227
- return TABLE_KEY
1228
 
1229
 
1230
- def table_rows(st):
1231
  import core.user_tables as ut
1232
- return dict((ut.get_one(TABLE_KEY, st) or {}).get("rows") or {})
1233
 
1234
 
1235
  def links(rows):
@@ -1289,37 +1435,39 @@ def merge_duplicates(st):
1289
  return len(dropped)
1290
 
1291
 
1292
- def write_rows(st, computed):
1293
- """Upsert computed cells by SKU in two store writes; owned cells are never touched."""
 
1294
  import core.user_tables as ut
1295
- existing = table_rows(st)
1296
- seen = {str(r.get("sku") or "").strip() for r in existing.values()}
 
1297
  new = [{k: v for k, v in values.items() if v is not None}
1298
- for sku, values in computed.items() if sku not in seen]
1299
- limit = ut.row_limit(TABLE_KEY, st)
1300
  if limit and len(existing) + len(new) > limit:
1301
  raise TableRefused(
1302
- f"{TABLE_LABEL} holds at most {limit:,} rows and Amazon has "
1303
- f"{len(existing) + len(new):,} SKUs. Cause: a user database is capped at {limit:,} "
1304
  "rows. Fix: read this table through the mirror instead of storing rows.")
1305
  created = 0
1306
  if new:
1307
- made = ut.add_rows(TABLE_KEY, new, username=WRITER, st=st, by=WRITER, via=VIA)
1308
  if made is None:
1309
- raise TableRefused(f"The store refused new rows for {TABLE_LABEL}.")
1310
  created = len(made)
1311
  updated = []
1312
 
1313
  def _set(cur):
1314
  updated.clear()
1315
- table = cur.get(TABLE_KEY)
1316
  if table is None:
1317
  return cur
1318
  for rid, row in (table.get("rows") or {}).items():
1319
- sku = str(row.get("sku") or "").strip()
1320
- values = computed.get(sku)
1321
  if values is None:
1322
- values = {k: None for k in _PERIOD_KEYS}
1323
  changed = False
1324
  for key, value in values.items():
1325
  if value is None:
@@ -1331,7 +1479,7 @@ def write_rows(st, computed):
1331
  updated.append(rid)
1332
  return cur
1333
 
1334
- ut.update_with_activity(TABLE_KEY, _set, st=st, by=WRITER, via=VIA, row_ids=None)
1335
  return {"created": created, "updated": len(updated)}
1336
 
1337
 
@@ -1425,12 +1573,12 @@ def default_owner(st, tenant=TENANT_ZERO):
1425
 
1426
  # ---------------------------------------------------------------- seeded views
1427
 
1428
- def seeded_views():
1429
  from core import view_templates as vt
1430
- return list((vt.get(TEMPLATE_KEY) or {}).get("views") or ())
1431
 
1432
 
1433
- def ensure_views(st, owner):
1434
  """Write the seeded views once, owned by `owner`, granted to everyone who can open the table.
1435
 
1436
  A view lives in one personal stratum and reaches others through a `*` view grant, the same
@@ -1440,10 +1588,11 @@ def ensure_views(st, owner):
1440
  from core import view_templates as vt
1441
  from core.table_store import TableStore
1442
  done = set(read_settings(st).get("viewsSeeded") or ())
1443
- ops = TableStore(vt.workspace_key(TABLE_KEY), st)
1444
  owner = str(owner or WRITER).strip().lower()
1445
  made = []
1446
- for view in seeded_views():
 
1447
  if view["id"] in done:
1448
  continue
1449
  found = ops.find_view(view["id"])
@@ -1597,6 +1746,287 @@ def apply_owned(st, bands, *, today, owner=None):
1597
  return dict(counts)
1598
 
1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1600
  def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=None,
1601
  tenant=TENANT_ZERO, validator=None):
1602
  """Recompute every SKU for the period and store it; owned cells stay. Returns the report.
@@ -1616,7 +2046,8 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
1616
  merged = merge_duplicates(st)
1617
  decisions = apply_decisions(st, by=by or WRITER)
1618
  owner, owner_label = default_owner(st, tenant)
1619
- ensure_views(st, owner or by)
 
1620
  row_links = links(table_rows(st))
1621
  receipts, history, cost_problem = None, [], None
1622
  if cost_reader is None:
@@ -1639,12 +2070,50 @@ def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=N
1639
  sentence = sentence or "Not verified: receipt costs do not tie to Odoo landed cost lines."
1640
  computed = {sku: dict(values, cogs_per_unit=None, cost_source="Receipt cost not verified")
1641
  for sku, values in computed.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
1642
  if sentence:
1643
  computed = unverified(computed, sentence)
1644
  report.update(write_rows(st, computed), merged=merged,
1645
  decisions={k: decisions[k] for k in ("confirmed", "rejected")})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1646
  bands = {sku: values.get("band") for sku, values in computed.items()}
1647
  report["owned"] = apply_owned(st, bands, today=day, owner=owner_label)
 
1648
  stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
1649
  write_settings(st, period=period, thin=thin, refreshedAt=stamp, refreshedBy=by or WRITER,
1650
  lastPeriod=report["period"], skus=report["skus"], linked=report["linked"],
 
1
+ """Command Center: one row per Amazon SKU with Odoo cost, profit, ads, stock, returns, health and score.
2
 
3
  Net proceeds = net sales minus fees minus sponsored ads, from the `amzn_economics` mirror.
4
  COGS follows incoming receipt valuations and posted landed costs through FIFO.
 
7
  rewrites only the computed columns, keyed by SKU, so owned cells belong to the SKU and
8
  survive every period switch.
9
 
10
+ It also owns three more tables. `ut_amazon_asin_profit` and `ut_amazon_parent_profit` roll the
11
+ SKU rows up by ASIN and parent ASIN on every refresh. `ut_amazon_projects` holds the projects
12
+ people add. A refresh writes their health and impact, and `relink_projects` writes each
13
+ project's row id into the `projects` link cell of its SKU, ASIN and parent rows.
14
+
15
  `validate()` ties a month's net proceeds to Amazon settlements within 2%, excluding loan
16
  repayments and withheld tax, and proves a negative control that drops fees goes red.
17
  A refresh runs it for the last complete month and writes no figures when it fails.
 
34
  import threading
35
  from pathlib import Path
36
 
37
+ from modules import amazon_sku_metrics as M
38
+ import core.user_tables as _registry
39
+
40
  TABLE_KEY = "ut_amazon_sku_profit"
41
+ TABLE_LABEL = "Command Center"
42
+ PROJECTS_KEY = "ut_amazon_projects"
43
+ PROJECTS_LABEL = "Command Center Projects"
44
+ ASIN_KEY = "ut_amazon_asin_profit"
45
+ ASIN_LABEL = "Command Center ASIN"
46
+ PARENT_KEY = "ut_amazon_parent_profit"
47
+ PARENT_LABEL = "Command Center Parent ASIN"
48
+ # The four tables are the module's, not a person's: they take no MAX_TABLES slot (D-3284 spirit).
49
+ _registry.register_module_tables(TABLE_KEY, PROJECTS_KEY, ASIN_KEY, PARENT_KEY)
50
  SETTINGS_KEY = "amazon_profit_settings"
51
  COST_HISTORY_KEY = "amazon_profit_cost_history"
52
  VIA = "amazon_profit"
 
65
  DUE_DAYS = 14
66
  REOPEN_DAYS = 30
67
  TEMPLATE_KEY = "amazon_sku_profit"
68
+ ASIN_TEMPLATE_KEY = "amazon_asin_profit"
69
+ PARENT_TEMPLATE_KEY = "amazon_parent_profit"
70
+ PROJECTS_TEMPLATE_KEY = "amazon_projects"
71
+ RELINK_PATH = "/amazon-profit/projects/relink"
72
+ PROJECT_STATUSES = ("Open", "Done")
73
+ PROJECT_HEALTH = ("On track", "Due this week", "Overdue", "Done")
74
+ DUE_SOON_DAYS = 7
75
  PICKER_MONTHS = 12
76
  SETTLEMENT_TOLERANCE = 0.02
77
 
 
106
  return out
107
 
108
 
109
+ def _projects_field(grain, key_from, description):
110
+ """The `projects` link column; its seed tells the popup how to add a project on this row."""
111
+ return _field("projects", "Projects", "link", description, computed=True,
112
+ link={"table": PROJECTS_KEY},
113
+ format={"linkLabel": "Projects", "addLabel": "Add project",
114
+ "seed": {"keyFrom": key_from, "keyField": "key",
115
+ "values": {"grain": grain, "status": "Open"},
116
+ "titleField": "title", "relink": RELINK_PATH}})
117
+
118
+
119
+ def _metric_fields(skip=()):
120
+ """The sibling metric module's columns, as computed fields of this module."""
121
+ return tuple(_field(key, label, ftype, description, computed=True, **dict(extra or {}))
122
+ for key, label, ftype, description, extra in M.METRIC_COLUMNS if key not in skip)
123
+
124
+
125
+ #: The profit columns: figures from the economics mirror and Odoo cost, written by `cells`.
126
+ _ECON_FIELDS = (
127
  _field("sku", "SKU", "text", "Amazon seller SKU.", computed=True),
128
  _field("asin", "ASIN", "text", "Amazon product id.", computed=True),
129
  _field("title", "Title", "text", "Listing title.", computed=True),
 
154
  computed=True),
155
  _field("odoo_margin_source", "Odoo margin source", "text", "Scope or missing Odoo margin data.", computed=True),
156
  )
157
+ _ECON_KEYS = tuple(f["key"] for f in _ECON_FIELDS)
158
+ #: Computed columns: a refresh owns them and the pre-set lock keeps people out of them.
159
+ COMPUTED_FIELDS = _ECON_FIELDS + _metric_fields() + (
160
+ _projects_field("sku", "sku", "Projects on this SKU, its ASIN or its parent ASIN. Click to open them."),)
161
  #: Owned columns: people edit them and a refresh never writes them.
162
  OWNED_FIELDS = (
163
  _field("odoo_product", "Odoo product", "text", "Odoo internal reference.", computed=False),
 
187
  TRACK_KEYS = tuple(f["key"] for f in TRACK_FIELDS)
188
  ALL_KEYS = COMPUTED_KEYS + OWNED_KEYS + TRACK_KEYS
189
  SUGGESTION_KEYS = ("suggested_product", "suggested_units", "match_rule")
190
+ METRIC_KEYS = tuple(column[0] for column in M.METRIC_COLUMNS)
191
  #: A settlement refusal blanks Amazon totals while independent receipt observations remain visible.
192
+ #: Metrics built from economics figures blank with them. Ads, stock, returns and listing
193
+ #: metrics come from their own mirror tables, so they stay.
194
  _UNVERIFIED_KEYS = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds",
195
+ "cogs_total", "net_profit", "margin", "band") + tuple(
196
+ k for k in ("tacos", "profit_health", "score", "priority", "units_30d", "net_sales_30d")
197
+ if k in METRIC_KEYS)
198
+ #: A metric check that fails blanks these on every table. The ids and the note stay.
199
+ _METRIC_VALUE_KEYS = tuple(k for k in METRIC_KEYS if k not in ("parent_asin", "ads_note"))
200
+ _IDENTITY_KEYS = ("sku", "asin", "parent_asin", "title", "projects")
201
+ _PERIOD_KEYS = tuple(k for k in COMPUTED_KEYS if k not in _IDENTITY_KEYS)
202
+
203
+ #: The profit block a rollup table carries; `_ECON_ADDITIVE` sums, margin and band recompute.
204
+ _ECON_ADDITIVE = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds", "cogs_total",
205
+ "net_profit")
206
+ _ROLLUP_ECON = ("period",) + _ECON_ADDITIVE + ("margin", "band")
207
+
208
+
209
+ def _grain_fields(key_column, grain):
210
+ """ASIN or parent ASIN table columns: ids, SKU count, the profit block, metrics, projects."""
211
+ econ = {f["key"]: f for f in _ECON_FIELDS}
212
+ metric = {f["key"]: f for f in _metric_fields()}
213
+ rollup = tuple(_field(key, label, ftype, description, computed=True, **dict(extra or {}))
214
+ for key, label, ftype, description, extra in M.ROLLUP_COLUMNS)
215
+ ids = (econ["asin"], metric["parent_asin"]) if key_column == "asin" else (metric["parent_asin"],)
216
+ where = "this ASIN or its parent ASIN" if key_column == "asin" else "this parent ASIN"
217
+ return (ids + (econ["title"],) + rollup + tuple(econ[k] for k in _ROLLUP_ECON)
218
+ + _metric_fields(skip=("parent_asin",))
219
+ + (_projects_field(grain, key_column, f"Projects on {where}. Click to open them."),))
220
+
221
+
222
+ ASIN_FIELDS = _grain_fields("asin", "asin")
223
+ PARENT_FIELDS = _grain_fields("parent_asin", "parent_asin")
224
+ _ROAS = next((c for c in M.METRIC_COLUMNS if c[0] == "roas"), ("roas", "ROAS", "int", "", {}))
225
+ #: Project columns people write: rows are added in the Grid and from the Projects popup.
226
+ PROJECT_USER_FIELDS = (
227
+ _field("title", "Title", "text", "What the project changes.", computed=False),
228
+ _field("grain", "Grain", "select", "SKU, ASIN or parent ASIN.", computed=False, options=list(M.GRAINS)),
229
+ _field("key", "Key", "text", "The SKU, ASIN or parent ASIN it works on.", computed=False),
230
+ _field("owner", "Owner", "user", "Who runs the project.", computed=False),
231
+ _field("start_on", "Start", "date", "When the work starts.", computed=False),
232
+ _field("deadline_on", "Deadline", "date", "When the work is due.", computed=False),
233
+ _field("completed_on", "Completed", "date", "When the work was done. Impact counts from this day.",
234
+ computed=False),
235
+ _field("status", "Status", "select", "Open or Done.", computed=False, options=list(PROJECT_STATUSES)),
236
+ )
237
+ #: Project columns a refresh writes.
238
+ PROJECT_COMPUTED_FIELDS = (
239
+ _field("health", "Health", "select", "On track, due this week, overdue or done, from the deadline.",
240
+ computed=True, options=list(PROJECT_HEALTH), format={"display": "dot"}),
241
+ _field("impact", "Impact", "currency", "Net sales since completion minus the same days one year earlier.",
242
+ computed=True),
243
+ _field("net_sales_since", "Net sales since", "currency", "Net sales from completion to yesterday.",
244
+ computed=True),
245
+ _field("net_sales_prior", "Net sales prior", "currency", "Net sales over the same days one year earlier.",
246
+ computed=True),
247
+ _field("units_since", "Units since", "int", "Units from completion to yesterday.", computed=True),
248
+ _field("units_prior", "Units prior", "int", "Units over the same days one year earlier.", computed=True),
249
+ _field("impact_units", "Impact units", "int", "Units since completion minus the same days one year earlier.",
250
+ computed=True),
251
+ _field("roas_since", "ROAS since", _ROAS[2], "Return on ad spend from completion to yesterday.",
252
+ computed=True, **dict(_ROAS[4] or {})),
253
+ _field("roas_prior", "ROAS prior", _ROAS[2], "Return on ad spend over the same days one year earlier.",
254
+ computed=True, **dict(_ROAS[4] or {})),
255
+ _field("impact_state", "Impact state", "text", "Why impact is blank.", computed=True),
256
+ )
257
+ PROJECT_FIELDS = PROJECT_USER_FIELDS + PROJECT_COMPUTED_FIELDS
258
+ PROJECT_USER_KEYS = tuple(f["key"] for f in PROJECT_USER_FIELDS)
259
+ PROJECT_COMPUTED_KEYS = tuple(f["key"] for f in PROJECT_COMPUTED_FIELDS)
260
+
261
+
262
+ def table_specs():
263
+ """Every module table in creation order. Projects comes first: the others link to it."""
264
+ return (
265
+ {"key": PROJECTS_KEY, "label": PROJECTS_LABEL, "fields": PROJECT_FIELDS,
266
+ "owned": PROJECT_USER_KEYS, "keyColumn": None, "template": PROJECTS_TEMPLATE_KEY},
267
+ {"key": TABLE_KEY, "label": TABLE_LABEL, "fields": COMPUTED_FIELDS + OWNED_FIELDS + TRACK_FIELDS,
268
+ "owned": OWNED_KEYS, "keyColumn": "sku", "template": TEMPLATE_KEY},
269
+ {"key": ASIN_KEY, "label": ASIN_LABEL, "fields": ASIN_FIELDS, "owned": (),
270
+ "keyColumn": "asin", "template": ASIN_TEMPLATE_KEY},
271
+ {"key": PARENT_KEY, "label": PARENT_LABEL, "fields": PARENT_FIELDS, "owned": (),
272
+ "keyColumn": "parent_asin", "template": PARENT_TEMPLATE_KEY},
273
+ )
274
 
275
 
276
  # ---------------------------------------------------------------- period and threshold
 
385
  def cells(row, period_label=""):
386
  """Computed cells as stored strings; None means the cell is blank."""
387
  out = {}
388
+ for key in _ECON_KEYS:
389
  value = period_label if key == "period" else row.get(key)
390
+
391
  if value is None or value == "":
392
  out[key] = None
393
  elif key in ("margin", "odoo_channel_margin"):
 
1282
 
1283
  # ---------------------------------------------------------------- module-owned table
1284
 
1285
+ def _definition_fields(fields=None, owned_keys=None):
1286
+ """Stored field definitions for one module table; the SKU table by default."""
1287
  import core.user_tables as ut
1288
+ fields = tuple(COMPUTED_FIELDS + OWNED_FIELDS + TRACK_FIELDS if fields is None else fields)
1289
+ owned = set(OWNED_KEYS if owned_keys is None else owned_keys)
1290
+ keys = [f["key"] for f in fields]
1291
+ by_key = {}
1292
+ # One field per call: `clean_fields` slices a list at `MAX_FIELDS`.
1293
+ for raw in fields:
1294
+ for field in ut.clean_fields([dict(raw)]) or ():
1295
+ by_key[field["key"]] = field
1296
+ missing = [key for key in keys if key not in by_key]
1297
+ if missing:
1298
+ raise TableRefused(f"The Command Center columns failed the table field check: {', '.join(missing)}.")
1299
  out = []
1300
+ for key in keys:
1301
  field = dict(by_key[key])
1302
  # editRole governs the column definition only. Cell values on owned columns follow the
1303
  # database edit grant (`may_edit_database`), so editors edit them and viewers cannot.
1304
  field["editRole"] = "admins"
1305
+ if key not in owned:
1306
  field["automation"] = {"preset": True, "flowId": VIA}
1307
  out.append(field)
1308
  return out
 
1315
  if isinstance(f, dict) and f.get("key") in want and not f.get("format")}
1316
 
1317
 
1318
+ def ensure_table(st, username, *, table_key=None, label=None, fields=None, owned_keys=None):
1319
+ """Create or adopt module tables; add missing columns, never retype one. Returns the key.
1320
+
1321
+ With no `table_key` it ensures every table in `table_specs` order and returns `TABLE_KEY`.
1322
+ A stored label that differs is rewritten, so a renamed module renames its tables."""
1323
  import core.user_tables as ut
1324
+ if table_key is None:
1325
+ specs = [(s["key"], s["label"], _definition_fields(s["fields"], s["owned"])) for s in table_specs()]
1326
+ else:
1327
+ specs = [(table_key, label or table_key, _definition_fields(fields, owned_keys))]
1328
+ cost_description = next((field["description"] for field in _ECON_FIELDS if field["key"] == "cogs_per_unit"))
1329
+
1330
+ def _stale(key, want_label, wanted):
1331
+ have = ut.get_one(key, st)
1332
+ if have is None or have.get("label") != want_label:
1333
+ return True
1334
+ if not {f["key"] for f in wanted} <= {f.get("key") for f in have.get("fields") or []}:
1335
+ return True
1336
+ if _format_repairs(have.get("fields"), wanted):
1337
+ return True
1338
+ return key == TABLE_KEY and any(f.get("key") == "cogs_per_unit" and f.get("description") != cost_description
1339
+ for f in have.get("fields") or [])
1340
+
1341
+ todo = [spec for spec in specs if _stale(*spec)]
1342
+ result = specs[0][0] if table_key is not None else TABLE_KEY
1343
+ if not todo:
1344
+ return result
1345
  created = dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
 
1346
 
1347
  def _up(cur):
1348
  cur = cur if isinstance(cur, dict) else {}
1349
+ for key, want_label, wanted in todo:
1350
+ table = cur.get(key)
1351
+ if table is None:
1352
+ # A module table takes no cap slot (register_module_tables), so nothing refuses here.
1353
+ cur[key] = {"key": key, "label": want_label, "source": ut.AUTOMATION_SOURCE,
1354
+ "createdBy": username or WRITER, "created": created,
1355
+ "fields": [dict(f) for f in wanted], "rows": {}}
1356
+ continue
1357
+ if table.get("label") != want_label:
1358
+ table["label"] = want_label
1359
+ present = {f.get("key") for f in table.get("fields") or []}
1360
+ repairs = _format_repairs(table.get("fields"), wanted)
1361
+ for field in table.get("fields") or []:
1362
+ if field.get("key") in repairs:
1363
+ field["format"] = dict(repairs[field["key"]])
1364
+ if key == TABLE_KEY and field.get("key") == "cogs_per_unit":
1365
+ field["description"] = cost_description
1366
+ table.setdefault("fields", []).extend(dict(f) for f in wanted if f["key"] not in present)
1367
  return cur
1368
 
1369
  st.update(ut.STORE_KEY, _up, flush="sync")
1370
+ for key, want_label, _wanted in todo:
1371
+ if ut.get_one(key, st) is None:
1372
+ raise TableRefused(f"The store did not keep {want_label}. Refresh again.")
1373
+ return result
 
 
1374
 
1375
 
1376
+ def table_rows(st, table_key=TABLE_KEY):
1377
  import core.user_tables as ut
1378
+ return dict((ut.get_one(table_key, st) or {}).get("rows") or {})
1379
 
1380
 
1381
  def links(rows):
 
1435
  return len(dropped)
1436
 
1437
 
1438
+ def write_rows(st, computed, *, table_key=TABLE_KEY, key_column="sku", label=TABLE_LABEL, period_keys=None):
1439
+ """Upsert computed cells by the key column in two store writes; owned cells are never touched.
1440
+ A stored row absent from `computed` keeps its row and loses its period figures."""
1441
  import core.user_tables as ut
1442
+ period_keys = _PERIOD_KEYS if period_keys is None else tuple(period_keys)
1443
+ existing = table_rows(st, table_key)
1444
+ seen = {str(r.get(key_column) or "").strip() for r in existing.values()}
1445
  new = [{k: v for k, v in values.items() if v is not None}
1446
+ for key, values in computed.items() if key not in seen]
1447
+ limit = ut.row_limit(table_key, st)
1448
  if limit and len(existing) + len(new) > limit:
1449
  raise TableRefused(
1450
+ f"{label} holds at most {limit:,} rows and Amazon has "
1451
+ f"{len(existing) + len(new):,} of them. Cause: a user database is capped at {limit:,} "
1452
  "rows. Fix: read this table through the mirror instead of storing rows.")
1453
  created = 0
1454
  if new:
1455
+ made = ut.add_rows(table_key, new, username=WRITER, st=st, by=WRITER, via=VIA)
1456
  if made is None:
1457
+ raise TableRefused(f"The store refused new rows for {label}.")
1458
  created = len(made)
1459
  updated = []
1460
 
1461
  def _set(cur):
1462
  updated.clear()
1463
+ table = cur.get(table_key)
1464
  if table is None:
1465
  return cur
1466
  for rid, row in (table.get("rows") or {}).items():
1467
+ key = str(row.get(key_column) or "").strip()
1468
+ values = computed.get(key)
1469
  if values is None:
1470
+ values = {k: None for k in period_keys}
1471
  changed = False
1472
  for key, value in values.items():
1473
  if value is None:
 
1479
  updated.append(rid)
1480
  return cur
1481
 
1482
+ ut.update_with_activity(table_key, _set, st=st, by=WRITER, via=VIA, row_ids=None)
1483
  return {"created": created, "updated": len(updated)}
1484
 
1485
 
 
1573
 
1574
  # ---------------------------------------------------------------- seeded views
1575
 
1576
+ def seeded_views(template_key=TEMPLATE_KEY):
1577
  from core import view_templates as vt
1578
+ return list((vt.get(template_key) or {}).get("views") or ())
1579
 
1580
 
1581
+ def ensure_views(st, owner, *, table_key=TABLE_KEY, template_key=TEMPLATE_KEY):
1582
  """Write the seeded views once, owned by `owner`, granted to everyone who can open the table.
1583
 
1584
  A view lives in one personal stratum and reaches others through a `*` view grant, the same
 
1588
  from core import view_templates as vt
1589
  from core.table_store import TableStore
1590
  done = set(read_settings(st).get("viewsSeeded") or ())
1591
+ ops = TableStore(vt.workspace_key(table_key), st)
1592
  owner = str(owner or WRITER).strip().lower()
1593
  made = []
1594
+ for view in seeded_views(template_key):
1595
+
1596
  if view["id"] in done:
1597
  continue
1598
  found = ops.find_view(view["id"])
 
1746
  return dict(counts)
1747
 
1748
 
1749
+ # ---------------------------------------------------------------- metrics, rollups, projects
1750
+
1751
+ _FIELD_BY_KEY = {f["key"]: f for f in COMPUTED_FIELDS + ASIN_FIELDS + PARENT_FIELDS + PROJECT_FIELDS}
1752
+
1753
+
1754
+ def _decimals(field):
1755
+ return (field.get("format") or {}).get("decimals")
1756
+
1757
+
1758
+ def stored_cell(field, value):
1759
+ """A raw value as the stored cell string for its field type; None means blank."""
1760
+ if value is None or value == "" or field is None:
1761
+ return None if value in (None, "") else str(value)
1762
+ ftype = field.get("type")
1763
+ if ftype == "chart":
1764
+ return value if isinstance(value, str) else json.dumps(value, separators=(",", ":"))
1765
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
1766
+ return str(value)
1767
+ if not math.isfinite(float(value)):
1768
+ return None
1769
+ if ftype == "pct":
1770
+ return f"{value * 100:.2f}"
1771
+ if ftype == "int":
1772
+ places = _decimals(field)
1773
+ return f"{float(value):.{places}f}" if places else str(int(round(value)))
1774
+ if ftype == "currency" or isinstance(value, float):
1775
+ return f"{float(value):.2f}"
1776
+ return str(value)
1777
+
1778
+
1779
+ def raw_value(field, cell):
1780
+ """The raw value a stored cell holds: numbers as numbers, pct as a fraction."""
1781
+ if cell is None or cell == "":
1782
+ return None
1783
+ ftype = (field or {}).get("type")
1784
+ if ftype == "chart":
1785
+ try:
1786
+ return json.loads(cell) if isinstance(cell, str) else cell
1787
+ except ValueError:
1788
+ return None
1789
+ if ftype in ("pct", "int", "currency"):
1790
+ try:
1791
+ number = float(cell)
1792
+ except (TypeError, ValueError):
1793
+ return None
1794
+ if not math.isfinite(number):
1795
+ return None
1796
+ if ftype == "pct":
1797
+ return number / 100.0
1798
+ if ftype == "int" and not _decimals(field or {}) and number.is_integer():
1799
+ return int(number)
1800
+ return number
1801
+ return cell
1802
+
1803
+
1804
+ def _raw_row(cells_by_key):
1805
+ return {key: raw_value(_FIELD_BY_KEY.get(key), value) for key, value in cells_by_key.items()}
1806
+
1807
+
1808
+ def _metric_problem_types():
1809
+ own = getattr(M, "SourceUnavailable", None)
1810
+ return (SourceUnavailable,) + ((own,) if isinstance(own, type) and issubclass(own, Exception) else ())
1811
+
1812
+
1813
+ def merge_metrics(computed, metrics):
1814
+ """SKU cells with the metric and score cells added; `metrics` holds raw values by SKU."""
1815
+ out = {}
1816
+ for sku, values in computed.items():
1817
+ raw = _raw_row(values)
1818
+ raw.update({k: v for k, v in (metrics.get(sku) or {}).items() if k in METRIC_KEYS})
1819
+ if not raw.get("asin") and (metrics.get(sku) or {}).get("asin"):
1820
+ raw["asin"] = metrics[sku]["asin"]
1821
+ raw.update(M.score_row(raw))
1822
+ merged = dict(values)
1823
+ for key in METRIC_KEYS + ("asin",):
1824
+ if key in raw:
1825
+ merged[key] = stored_cell(_FIELD_BY_KEY.get(key), raw[key])
1826
+ out[sku] = merged
1827
+ return out
1828
+
1829
+
1830
+ def _blank(cells_by_key, keys, period=None):
1831
+ out = {**cells_by_key, **{k: None for k in keys if k in cells_by_key or k in _FIELD_BY_KEY}}
1832
+ if period is not None:
1833
+ out["period"] = period
1834
+ return out
1835
+
1836
+
1837
+ def _flatten(item):
1838
+ flat = {}
1839
+ for key, value in (item or {}).items():
1840
+ if key in ("sums", "ratios") and isinstance(value, dict):
1841
+ flat.update(value)
1842
+ else:
1843
+ flat[key] = value
1844
+ return flat
1845
+
1846
+
1847
+ def grain_rows(rows, key, *, thin=THIN_DEFAULT, period_label="", fields=()):
1848
+ """`{asin or parent: cells}` from `M.rollup`, which sums first and recomputes every ratio.
1849
+ Band follows the rollup's margin and the period cell names the period."""
1850
+ keys = [f["key"] for f in fields]
1851
+ out = {}
1852
+ for item in M.rollup(rows, key=key):
1853
+ flat = _flatten(item)
1854
+ value = str(flat.get(key) or flat.get("key") or "").strip()
1855
+ if not value:
1856
+ continue
1857
+ flat[key] = value
1858
+ flat["band"] = band_for(flat.get("net_profit"), flat.get("margin"), thin)
1859
+ flat["period"] = period_label
1860
+ out[value] = {k: stored_cell(_FIELD_BY_KEY.get(k), flat.get(k)) for k in keys if k != "projects"}
1861
+ return out
1862
+
1863
+
1864
+ def rollup_checks(computed, by_grain):
1865
+ """Each rollup table's units sold equal the SKU units sold, and it holds every distinct key."""
1866
+ checks = []
1867
+ for key, label, cells_by_key in (("asin", "ASIN", by_grain.get("asin") or {}),
1868
+ ("parent_asin", "parent ASIN", by_grain.get("parent_asin") or {})):
1869
+ grouped = [values for values in computed.values() if str(values.get(key) or "").strip()]
1870
+ skus = sum(int(_num(values.get("units_sold"))) for values in grouped)
1871
+ grains = sum(int(_num(values.get("units_sold"))) for values in cells_by_key.values())
1872
+ distinct = len({str(values.get(key)).strip() for values in grouped})
1873
+ checks.append({"check": f"amazon_profit: {label} table units sold equal the SKU table units sold",
1874
+ "ok": skus == grains, "a": grains, "b": skus, "gap": abs(grains - skus)})
1875
+ checks.append({"check": f"amazon_profit: {label} table holds every distinct {label}, no cap",
1876
+ "ok": len(cells_by_key) == distinct, "a": len(cells_by_key), "b": distinct,
1877
+ "gap": abs(len(cells_by_key) - distinct)})
1878
+ return checks
1879
+
1880
+
1881
+ def _grain_period_keys(fields, key_column):
1882
+ return tuple(f["key"] for f in fields if f["key"] not in (key_column, "parent_asin", "title", "projects"))
1883
+
1884
+
1885
+ def _date(value):
1886
+ try:
1887
+ return dt.date.fromisoformat(str(value or "").strip()[:10])
1888
+ except ValueError:
1889
+ return None
1890
+
1891
+
1892
+ def project_health(row, today):
1893
+ """Done, Overdue, Due this week or On track, from status and the deadline."""
1894
+ if str(row.get("status") or "").strip() == "Done":
1895
+ return "Done"
1896
+ deadline = _date(row.get("deadline_on"))
1897
+ if deadline is None:
1898
+ return "On track"
1899
+ if deadline < today:
1900
+ return "Overdue"
1901
+ return "Due this week" if (deadline - today).days <= DUE_SOON_DAYS else "On track"
1902
+
1903
+
1904
+ def _figure(result, metric):
1905
+ found = next((f for f in result.get("figures") or () if f.get("id") == metric), None) or {}
1906
+ return (found.get("current") or {}).get("value"), (found.get("comparison") or {}).get("value"), found
1907
+
1908
+
1909
+ #: `impact_state` reaches a screen, so a results token reads as words. Unknown tokens pass through.
1910
+ IMPACT_STATE_WORDS = {
1911
+ "missing_grain_or_key": "Needs a grain and a key",
1912
+ "not_verified": "Not verified: the source totals did not tie",
1913
+ "unavailable": "Source unavailable. Sync Amazon.",
1914
+ "waiting_for_completion": "Completes first",
1915
+ "waiting_for_completed_day": "Waits for the first full day after completion",
1916
+ "no_prior_data": "No sales one year earlier to compare against",
1917
+ "partial_data": "Only part of the window has data",
1918
+ }
1919
+
1920
+
1921
+ def project_cells(rid, row, con, today):
1922
+ """Computed cells for one project; impact only for a Done project with a completion date."""
1923
+ from modules import sku_action_results as SR
1924
+ out = {k: None for k in PROJECT_COMPUTED_KEYS}
1925
+ out["health"] = project_health(row, today)
1926
+ completed = str(row.get("completed_on") or "").strip()[:10]
1927
+ if str(row.get("status") or "").strip() != "Done" or not completed:
1928
+ return out
1929
+ grain, key = str(row.get("grain") or "").strip(), str(row.get("key") or "").strip()
1930
+ if grain not in M.GRAINS or not key:
1931
+ out["impact_state"] = IMPACT_STATE_WORDS["missing_grain_or_key"]
1932
+ return out
1933
+ action = {"id": str(rid), "grain": grain, "key": key, "status": "done", "completed_on": completed}
1934
+ try:
1935
+ result = SR.results(con, action, today=today)
1936
+ except SR.ValidationFailed:
1937
+ out["impact_state"] = IMPACT_STATE_WORDS["not_verified"]
1938
+ return out
1939
+ except (SR.SourceUnavailable, ValueError):
1940
+ out["impact_state"] = IMPACT_STATE_WORDS["unavailable"]
1941
+ return out
1942
+ except Exception as exc: # noqa: BLE001
1943
+ # One project that cannot be measured must not stop the refresh of every table.
1944
+ _log(f"project {rid}: impact unavailable ({type(exc).__name__}: {exc})")
1945
+ out["impact_state"] = IMPACT_STATE_WORDS["unavailable"]
1946
+ return out
1947
+
1948
+ sales_now, sales_prior, sales = _figure(result, "sales")
1949
+ units_now, units_prior, _units = _figure(result, "units")
1950
+ roas_now, roas_prior, _roas = _figure(result, "roas")
1951
+ raw = {"net_sales_since": sales_now, "net_sales_prior": sales_prior, "units_since": units_now,
1952
+ "units_prior": units_prior, "roas_since": roas_now, "roas_prior": roas_prior,
1953
+ "impact": None if sales_now is None or sales_prior is None else sales_now - sales_prior,
1954
+ "impact_units": None if units_now is None or units_prior is None else units_now - units_prior}
1955
+ out.update({k: stored_cell(_FIELD_BY_KEY[k], v) for k, v in raw.items()})
1956
+ if out["impact"] is None:
1957
+ state = result.get("state") or "unavailable"
1958
+ if state == "ready":
1959
+ state = (sales.get("comparison") or {}).get("status") or (sales.get("current") or {}).get("status") \
1960
+ or "unavailable"
1961
+ out["impact_state"] = state
1962
+ out["impact_state"] = IMPACT_STATE_WORDS.get(out["impact_state"], out["impact_state"])
1963
+ return out
1964
+
1965
+
1966
+ def update_projects(st, con, *, today):
1967
+ """Write health and impact on every project in one store write. Returns counts."""
1968
+ import core.user_tables as ut
1969
+ wanted = {str(rid): project_cells(rid, row, con, today) for rid, row in table_rows(st, PROJECTS_KEY).items()}
1970
+ counts = {"projects": len(wanted), "measured": sum(1 for v in wanted.values() if v.get("impact") is not None)}
1971
+ if not wanted:
1972
+ return counts
1973
+
1974
+ def _set(cur):
1975
+ table = cur.get(PROJECTS_KEY)
1976
+ if table is None:
1977
+ return cur
1978
+ for rid, row in (table.get("rows") or {}).items():
1979
+ values = wanted.get(str(rid))
1980
+ if values is not None:
1981
+ _apply_cells(row, {k: v for k, v in values.items() if v != row.get(k)})
1982
+ return cur
1983
+
1984
+ ut.update_with_activity(PROJECTS_KEY, _set, st=st, by=WRITER, via=VIA, row_ids=None)
1985
+ return counts
1986
+
1987
+
1988
+ #: Which project grains link onto each table's rows, by that row's own id cells.
1989
+ _LINK_GRAINS = ((TABLE_KEY, ("sku", "asin", "parent_asin")), (ASIN_KEY, ("asin", "parent_asin")),
1990
+ (PARENT_KEY, ("parent_asin",)))
1991
+
1992
+
1993
+ def relink_projects(st):
1994
+ """Write each project's row id into the `projects` cell of its SKU, ASIN and parent rows.
1995
+ A cell holds comma separated project row ids, "" when none. Returns rows with an id."""
1996
+ import core.user_tables as ut
1997
+ by_target = {}
1998
+ for rid, row in sorted(table_rows(st, PROJECTS_KEY).items(), key=lambda item: _rid_order(item[0])):
1999
+ grain, key = str(row.get("grain") or "").strip(), str(row.get("key") or "").strip()
2000
+ if grain in M.GRAINS and key:
2001
+ by_target.setdefault((grain, key), []).append(str(rid))
2002
+ linked = [0]
2003
+ for table_key, grains in _LINK_GRAINS:
2004
+ hits = []
2005
+
2006
+ def _set(cur, grains=grains, table_key=table_key, hits=hits):
2007
+ hits.clear()
2008
+ table = cur.get(table_key)
2009
+ if table is None:
2010
+ return cur
2011
+ for row in (table.get("rows") or {}).values():
2012
+ ids = []
2013
+ for grain in grains:
2014
+ for pid in by_target.get((grain, str(row.get(grain) or "").strip()), ()):
2015
+ if pid not in ids:
2016
+ ids.append(pid)
2017
+ value = ",".join(ids)
2018
+ if ids:
2019
+ hits.append(1)
2020
+ if row.get("projects") != value:
2021
+ row["projects"] = value
2022
+ return cur
2023
+
2024
+ if ut.get_one(table_key, st) is not None:
2025
+ ut.update_with_activity(table_key, _set, st=st, by=WRITER, via=VIA, row_ids=None)
2026
+ linked[0] += len(hits)
2027
+ return linked[0]
2028
+
2029
+
2030
  def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=None,
2031
  tenant=TENANT_ZERO, validator=None):
2032
  """Recompute every SKU for the period and store it; owned cells stay. Returns the report.
 
2046
  merged = merge_duplicates(st)
2047
  decisions = apply_decisions(st, by=by or WRITER)
2048
  owner, owner_label = default_owner(st, tenant)
2049
+ for spec in table_specs():
2050
+ ensure_views(st, owner or by, table_key=spec["key"], template_key=spec["template"])
2051
  row_links = links(table_rows(st))
2052
  receipts, history, cost_problem = None, [], None
2053
  if cost_reader is None:
 
2070
  sentence = sentence or "Not verified: receipt costs do not tie to Odoo landed cost lines."
2071
  computed = {sku: dict(values, cogs_per_unit=None, cost_source="Receipt cost not verified")
2072
  for sku, values in computed.items()}
2073
+ bounds = report["period"]
2074
+ metrics, metric_problem = {}, None
2075
+ try:
2076
+ metrics = M.sku_metrics(con, start=bounds["start"], end=bounds["end"], skus=list(computed), today=day)
2077
+ except _metric_problem_types() as exc:
2078
+ metric_problem = str(exc)
2079
+ computed = merge_metrics(computed, metrics)
2080
+ metric_checks = [] if metric_problem else list(
2081
+ M.validate_metrics(con, start=bounds["start"], end=bounds["end"], computed=metrics) or [])
2082
+ metric_refusal = metric_problem or next(
2083
+ (f"Not verified: {c.get('check')}." for c in metric_checks if not c.get("ok")), None)
2084
+ if metric_refusal:
2085
+ computed = {sku: _blank(values, _METRIC_VALUE_KEYS) for sku, values in computed.items()}
2086
  if sentence:
2087
  computed = unverified(computed, sentence)
2088
  report.update(write_rows(st, computed), merged=merged,
2089
  decisions={k: decisions[k] for k in ("confirmed", "rejected")})
2090
+ rows = [dict(_raw_row(values), sku=sku, velocity_30d=(metrics.get(sku) or {}).get("velocity_30d"))
2091
+ for sku, values in computed.items()]
2092
+
2093
+ by_grain = {}
2094
+ for key, fields in (("asin", ASIN_FIELDS), ("parent_asin", PARENT_FIELDS)):
2095
+ cells_by_key = grain_rows(rows, key, thin=thin, period_label=bounds["label"], fields=fields)
2096
+ if metric_refusal:
2097
+ cells_by_key = {k: _blank(v, _METRIC_VALUE_KEYS) for k, v in cells_by_key.items()}
2098
+ if sentence:
2099
+ cells_by_key = {k: _blank(v, _UNVERIFIED_KEYS, sentence) for k, v in cells_by_key.items()}
2100
+ by_grain[key] = cells_by_key
2101
+ tie = rollup_checks(computed, by_grain)
2102
+ if not all(check["ok"] for check in tie):
2103
+ failed = "Not verified: the rollup totals do not add up to the SKU totals."
2104
+ by_grain = {key: {k: _blank(v, _UNVERIFIED_KEYS, failed) for k, v in cells_by_key.items()}
2105
+ for key, cells_by_key in by_grain.items()}
2106
+ report["metricValidation"] = metric_checks + tie
2107
+ report["metricRefusal"] = metric_refusal
2108
+ report["asin"] = write_rows(st, by_grain["asin"], table_key=ASIN_KEY, key_column="asin",
2109
+ label=ASIN_LABEL, period_keys=_grain_period_keys(ASIN_FIELDS, "asin"))
2110
+ report["parent"] = write_rows(st, by_grain["parent_asin"], table_key=PARENT_KEY,
2111
+ key_column="parent_asin", label=PARENT_LABEL,
2112
+ period_keys=_grain_period_keys(PARENT_FIELDS, "parent_asin"))
2113
+ report["projects"] = update_projects(st, con, today=day)
2114
  bands = {sku: values.get("band") for sku, values in computed.items()}
2115
  report["owned"] = apply_owned(st, bands, today=day, owner=owner_label)
2116
+ report["projects"]["linked"] = relink_projects(st)
2117
  stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
2118
  write_settings(st, period=period, thin=thin, refreshedAt=stamp, refreshedBy=by or WRITER,
2119
  lastPeriod=report["period"], skus=report["skus"], linked=report["linked"],
platform/modules/amazon_profit_account.py CHANGED
@@ -102,13 +102,13 @@ def what_if(sku, price=None, landed_cost=None, tacos=None, units=None, *, con, s
102
  return {**out, "reason": reason}
103
  row = stored.get(sku)
104
  if not row:
105
- return unavailable("This SKU is not in Amazon SKU profit. Refresh the table first.")
106
  if not profit.links({"baseline": row}).get(sku, {}).get("code"):
107
  return unavailable("Link this SKU to an Odoo product first.")
108
  if snapshot_missing and configured["key"] in profit.PERIOD_DAYS:
109
- return unavailable("Receipt cost snapshot dates unavailable. Refresh Amazon SKU profit for this period.")
110
  if (saved["start"], saved["end"]) != (selected["start"], selected["end"]):
111
- return unavailable("Receipt cost unavailable for selected window. Refresh Amazon SKU profit for this period.")
112
  problem = _ready(con, ECONOMICS)
113
  if problem:
114
  return unavailable(problem)
@@ -147,13 +147,13 @@ def what_if(sku, price=None, landed_cost=None, tacos=None, units=None, *, con, s
147
  return unavailable("Current unit economics cannot be represented. Positive net sales and units with TACoS at most 100% are required.")
148
  unit_cost = total_cost / sold
149
  if _cents(unit_cost) != _cents(displayed_cost) or cost != _cents(total_cost):
150
- return unavailable("Stored unit cost does not match receipt COGS. Refresh Amazon SKU profit.")
151
  actual = profit.compute_row(item, float(unit_cost), 1)
152
  if (_cents(actual["net_profit"]) != _cents(row.get("net_profit"))
153
  or _cents(Decimal(str(actual["margin"])) * 100) != _cents(stored_margin)):
154
- return unavailable("Current margin does not reconcile. Refresh Amazon SKU profit.")
155
  except (ValueError, InvalidOperation, TypeError, OverflowError):
156
- return unavailable("Current unit economics unavailable. Refresh Amazon SKU profit.")
157
  baseline = {"price": sales / sold, "amazon_fees_per_unit": fees / sold,
158
  "landed_cost": unit_cost, "tacos": spend / sales}
159
  modeled_price = supplied.get("price", baseline["price"])
@@ -195,7 +195,7 @@ def _ready(con, table):
195
 
196
  def _cost(item, row, bounds, settings, today):
197
  """Use T31's FIFO snapshot only for its exact window and unchanged economics inputs."""
198
- reason = "Receipt cost unavailable for selected window. Refresh Amazon SKU profit for this period."
199
  if not row or settings.get("refusal"):
200
  return None, reason
201
  saved = profit.period_bounds(settings.get("period"), today)
@@ -206,7 +206,7 @@ def _cost(item, row, bounds, settings, today):
206
  if any(_cents(value) is None for value in expected.values()):
207
  return None, "Economics amounts unavailable"
208
  if any(_cents(row.get(key)) != _cents(value) for key, value in expected.items()):
209
- return None, "Receipt cost snapshot no longer matches the mirror. Refresh Amazon SKU profit."
210
  try:
211
  units_match = Decimal(str(row.get("units_sold"))) == Decimal(str(item["units"]))
212
  except (InvalidOperation, ValueError, TypeError):
@@ -218,7 +218,7 @@ def _cost(item, row, bounds, settings, today):
218
  if not units_match or cost is None or not valid_source:
219
  return None, source or reason
220
  if _cents(row.get("net_profit")) != _cents(expected["net_proceeds"]) - cost:
221
- return None, "Receipt cost snapshot profit does not reconcile. Refresh Amazon SKU profit."
222
  return cost, None
223
 
224
 
 
102
  return {**out, "reason": reason}
103
  row = stored.get(sku)
104
  if not row:
105
+ return unavailable("This SKU is not in Command Center. Refresh the table first.")
106
  if not profit.links({"baseline": row}).get(sku, {}).get("code"):
107
  return unavailable("Link this SKU to an Odoo product first.")
108
  if snapshot_missing and configured["key"] in profit.PERIOD_DAYS:
109
+ return unavailable("Receipt cost snapshot dates unavailable. Refresh Command Center for this period.")
110
  if (saved["start"], saved["end"]) != (selected["start"], selected["end"]):
111
+ return unavailable("Receipt cost unavailable for selected window. Refresh Command Center for this period.")
112
  problem = _ready(con, ECONOMICS)
113
  if problem:
114
  return unavailable(problem)
 
147
  return unavailable("Current unit economics cannot be represented. Positive net sales and units with TACoS at most 100% are required.")
148
  unit_cost = total_cost / sold
149
  if _cents(unit_cost) != _cents(displayed_cost) or cost != _cents(total_cost):
150
+ return unavailable("Stored unit cost does not match receipt COGS. Refresh Command Center.")
151
  actual = profit.compute_row(item, float(unit_cost), 1)
152
  if (_cents(actual["net_profit"]) != _cents(row.get("net_profit"))
153
  or _cents(Decimal(str(actual["margin"])) * 100) != _cents(stored_margin)):
154
+ return unavailable("Current margin does not reconcile. Refresh Command Center.")
155
  except (ValueError, InvalidOperation, TypeError, OverflowError):
156
+ return unavailable("Current unit economics unavailable. Refresh Command Center.")
157
  baseline = {"price": sales / sold, "amazon_fees_per_unit": fees / sold,
158
  "landed_cost": unit_cost, "tacos": spend / sales}
159
  modeled_price = supplied.get("price", baseline["price"])
 
195
 
196
  def _cost(item, row, bounds, settings, today):
197
  """Use T31's FIFO snapshot only for its exact window and unchanged economics inputs."""
198
+ reason = "Receipt cost unavailable for selected window. Refresh Command Center for this period."
199
  if not row or settings.get("refusal"):
200
  return None, reason
201
  saved = profit.period_bounds(settings.get("period"), today)
 
206
  if any(_cents(value) is None for value in expected.values()):
207
  return None, "Economics amounts unavailable"
208
  if any(_cents(row.get(key)) != _cents(value) for key, value in expected.items()):
209
+ return None, "Receipt cost snapshot no longer matches the mirror. Refresh Command Center."
210
  try:
211
  units_match = Decimal(str(row.get("units_sold"))) == Decimal(str(item["units"]))
212
  except (InvalidOperation, ValueError, TypeError):
 
218
  if not units_match or cost is None or not valid_source:
219
  return None, source or reason
220
  if _cents(row.get("net_profit")) != _cents(expected["net_proceeds"]) - cost:
221
+ return None, "Receipt cost snapshot profit does not reconcile. Refresh Command Center."
222
  return cost, None
223
 
224
 
platform/modules/amazon_sku_metrics.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per Amazon seller SKU ads, stock, returns and listing metrics, four health labels, a score and a priority.
2
+
3
+ Every ratio is a fraction (0.15 means 15%), the scale `amazon_profit.compute_row` stores `margin` in.
4
+ `rollup` builds the ASIN and Parent ASIN grains from SKU rows. It sums first, then recomputes every
5
+ ratio from the sums. `validate_metrics` ties ad spend, stock and returns to independent mirror
6
+ totals (rule 8). No source read carries a LIMIT (rule 1).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ import json
12
+ import math
13
+
14
+ # Data-layer readers of the Amazon mirror, shared on purpose so the stock and listing SQL is not forked.
15
+ from modules import ranking_diagnostic, restock_planner
16
+
17
+ #: Cut-offs and weights (owner ruling). Ratios are fractions: 0.005 is 0.5%.
18
+ BENCHMARKS = {
19
+ "ctr_strong": 0.005, # CTR at least 0.5% is Strong
20
+ "ctr_weak": 0.003, # CTR under 0.3% is Weak
21
+ "acos_strong": 0.25, # ACOS at most 25% is Strong
22
+ "acos_weak": 0.40, # ACOS over 40% is Weak
23
+ "tacos_strong": 0.10, # TACOS at most 10% is Strong
24
+ "tacos_weak": 0.20, # TACOS over 20% is Weak
25
+ "cvr_strong": 0.10, # CVR at least 10% is Strong
26
+ "cvr_weak": 0.05, # CVR under 5% is Weak
27
+ "margin_strong": 0.15, # margin at least 15% is Strong
28
+ "margin_weak": 0.05, # margin under 5% is Weak
29
+ "cover_strong_min": 30, # days of cover 30 to 90 is Strong
30
+ "cover_strong_max": 90,
31
+ "cover_weak_under": 14, # days of cover under 14 is Weak
32
+ "cover_weak_over": 180, # days of cover over 180 is Weak
33
+ "return_rate_strong": 0.03, # return rate at most 3% is Strong
34
+ "return_rate_weak": 0.08, # return rate over 8% is Weak
35
+ "listing_cvr_strong": 0.10, # unit session percentage at least 10%: mirrors the CVR ruling
36
+ "listing_cvr_weak": 0.05, # unit session percentage under 5%: mirrors the CVR ruling
37
+ "points_strong": 25, # each of the four dimensions is worth 25 points
38
+ "points_fair": 12.5, # Fair scores half points
39
+ "points_weak": 0,
40
+ "points_no_data": 12.5, # No data scores neutral, half points, never zero
41
+ "priority_high_under": 40, # score under 40 is High priority
42
+ "priority_low_over": 70, # score over 70 is Low priority; 40 to 70 inclusive is Medium
43
+ }
44
+ GRAINS = ("sku", "asin", "parent_asin")
45
+ HEALTH_OPTIONS = ("Strong", "Fair", "Weak", "No data")
46
+ PRIORITY_OPTIONS = ("High", "Medium", "Low")
47
+ NO_ADS_NOTE = "No ads data yet"
48
+ NO_STOCK_NOTE = "No inventory planning data yet"
49
+ NO_RETURNS_NOTE = "No returns data yet"
50
+ SERIES_DAYS = 30
51
+ #: Ad spend per advertised product may trail the campaign report by a few cents per day.
52
+ ADS_TIE_TOLERANCE = 0.02
53
+ COUNT_TIE_TOLERANCE = 0.01
54
+
55
+ ECONOMICS = "amzn_economics"
56
+ PLANNING = "amzn_inventory_planning"
57
+ FBA_RETURNS = "amzn_fba_customer_returns"
58
+ MFN_RETURNS = "amzn_mfn_returns"
59
+ AD_TYPES = ("sp", "sb", "sd")
60
+ ADS_PRODUCTS = tuple(f"amzn_ads_{kind}_advertised_products" for kind in AD_TYPES)
61
+ ADS_CAMPAIGNS = tuple(f"amzn_ads_{kind}_campaigns" for kind in AD_TYPES)
62
+
63
+ _HEALTH = {"options": list(HEALTH_OPTIONS), "format": {"display": "dot"}}
64
+
65
+ #: (key, label, type, description, extra) in display order. H1b wraps each with `amazon_profit._field`.
66
+ METRIC_COLUMNS = (
67
+ ("parent_asin", "Parent ASIN", "text", "Variation family. An ASIN with no parent is its own.", {}),
68
+ ("ad_impressions", "Ad impressions", "int", "Sponsored ad impressions in the period.", {}),
69
+ ("ad_clicks", "Ad clicks", "int", "Sponsored ad clicks in the period.", {}),
70
+ ("ad_spend", "Ad spend", "currency", "Sponsored ad cost in the period.", {}),
71
+ ("ad_sales", "Ad sales", "currency", "Sales Amazon credits to the ads.", {}),
72
+ ("ad_orders", "Ad orders", "int", "Orders Amazon credits to the ads.", {}),
73
+ ("ctr", "CTR", "pct", "Ad clicks over ad impressions.", {}),
74
+ ("cvr", "CVR", "pct", "Ad orders over ad clicks.", {}),
75
+ ("cpc", "CPC", "currency", "Ad spend over ad clicks.", {}),
76
+ ("acos", "ACOS", "pct", "Ad spend over ad sales.", {}),
77
+ ("tacos", "TACOS", "pct", "Sponsored ad charges over net sales.", {}),
78
+ ("roas", "ROAS", "int", "Ad sales over ad spend.", {"format": {"decimals": 2}}),
79
+ ("fba_on_hand", "FBA on hand", "int", "Units available at Amazon in the newest snapshot.", {}),
80
+ ("inbound_units", "Inbound units", "int", "Units on the way to Amazon.", {}),
81
+ ("days_of_cover", "Days of cover", "int", "Days the FBA stock lasts at the 30 day sales pace.", {}),
82
+ ("return_units", "Returned units", "int", "Customer returns in the period.", {}),
83
+ ("return_rate", "Return rate", "pct", "Returned units over units sold.", {}),
84
+ ("sessions", "Sessions", "int",
85
+ "Product page sessions of the ASIN from the newest traffic report. Not aligned to the period.", {}),
86
+ ("unit_session_pct", "Unit session percentage", "pct", "Units sold over sessions.", {}),
87
+ ("buy_box_pct", "Buy Box", "pct", "Share of sessions that showed your offer.", {}),
88
+ ("stock_health", "Stock health", "select", "Days of cover against the benchmark.", _HEALTH),
89
+ ("profit_health", "Profit health", "select", "Margin against the benchmark.", _HEALTH),
90
+ ("ads_health", "Ads health", "select", "CTR, ACOS, TACOS and CVR against the benchmarks.", _HEALTH),
91
+ ("listing_health", "Listing health", "select", "Unit session percentage and return rate.", _HEALTH),
92
+ ("score", "Score", "int", "Health score from 0 to 100.", {"format": {"display": "bar"}}),
93
+ ("priority", "Priority", "select", "High needs attention first.",
94
+ {"options": list(PRIORITY_OPTIONS), "format": {"display": "dot"}}),
95
+ ("ads_note", "Ads note", "text", "Why ads figures are blank.", {}),
96
+ ("units_30d", "Units trend", "chart", "Units sold per day, last 30 days.", {}),
97
+ ("net_sales_30d", "Net sales trend", "chart", "Net sales per day, last 30 days.", {}),
98
+ ("ad_spend_30d", "Ad spend trend", "chart", "Ad spend per day, last 30 days.", {}),
99
+ )
100
+ ROLLUP_COLUMNS = (
101
+ ("sku_count", "SKUs", "int", "Seller SKUs in this row.", {}),
102
+ ("skus", "SKU list", "text", "Seller SKUs in this row, comma separated.", {}),
103
+ )
104
+ ADDITIVE_KEYS = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds", "cogs_total",
105
+ "net_profit", "ad_impressions", "ad_clicks", "ad_spend", "ad_sales", "ad_orders",
106
+ "fba_on_hand", "inbound_units", "return_units", "velocity_30d")
107
+ SERIES_KEYS = ("units_30d", "net_sales_30d", "ad_spend_30d")
108
+ _INT_KEYS = frozenset(("units_sold", "ad_impressions", "ad_clicks", "ad_orders", "fba_on_hand",
109
+ "inbound_units", "return_units"))
110
+ #: A sum over a partly unlinked group is not a profit: one costless active child blanks it.
111
+ _STRICT_KEYS = frozenset(("cogs_total", "net_profit"))
112
+ _SCORED = ("tacos", "return_rate", "stock_health", "profit_health", "ads_health", "listing_health",
113
+ "score", "priority")
114
+
115
+ #: What the last `rollup` call grouped and skipped. Updated in place.
116
+ last_report: dict = {}
117
+
118
+
119
+ # ---------------------------------------------------------------- pure arithmetic
120
+
121
+ def _f(value):
122
+ try:
123
+ number = float(value)
124
+ except (TypeError, ValueError):
125
+ return None
126
+ return number if math.isfinite(number) else None
127
+
128
+
129
+ def _ratio(num, den):
130
+ """num / den, or None when either is missing or the denominator is not positive."""
131
+ num, den = _f(num), _f(den)
132
+ if num is None or den is None or den <= 0:
133
+ return None
134
+ return num / den
135
+
136
+
137
+ def _half_up(value):
138
+ return int(math.floor(value + 0.5))
139
+
140
+
141
+ def _text(value):
142
+ return str(value).strip() if value is not None and str(value).strip() else None
143
+
144
+
145
+ def band(metric, value):
146
+ """Strong, Fair or Weak for one ratio against BENCHMARKS; None when the value is None."""
147
+ value = _f(value)
148
+ if value is None:
149
+ return None
150
+ if metric == "days_of_cover":
151
+ return cover_band(value)
152
+ name = "listing_cvr" if metric == "unit_session_pct" else metric
153
+ strong, weak = BENCHMARKS[f"{name}_strong"], BENCHMARKS[f"{name}_weak"]
154
+ value = round(value, 9)
155
+ if name in ("acos", "tacos", "return_rate"):
156
+ return "Strong" if value <= strong else "Weak" if value > weak else "Fair"
157
+ return "Strong" if value >= strong else "Weak" if value < weak else "Fair"
158
+
159
+
160
+ def cover_band(days):
161
+ """Strong for 30 to 90 days, Weak under 14 or over 180, else Fair; None when unknown."""
162
+ days = _f(days)
163
+ if days is None:
164
+ return None
165
+ if BENCHMARKS["cover_strong_min"] <= days <= BENCHMARKS["cover_strong_max"]:
166
+ return "Strong"
167
+ if days < BENCHMARKS["cover_weak_under"] or days > BENCHMARKS["cover_weak_over"]:
168
+ return "Weak"
169
+ return "Fair"
170
+
171
+
172
+ def combine(labels):
173
+ """Weak if any is Weak, Strong if all available are Strong, else Fair; No data when none is available."""
174
+ found = [label for label in labels if label]
175
+ if not found:
176
+ return "No data"
177
+ if "Weak" in found:
178
+ return "Weak"
179
+ return "Strong" if all(label == "Strong" for label in found) else "Fair"
180
+
181
+
182
+ def points(label):
183
+ return BENCHMARKS[{"Strong": "points_strong", "Fair": "points_fair", "Weak": "points_weak"}
184
+ .get(label, "points_no_data")]
185
+
186
+
187
+ def priority_for(score):
188
+ if score < BENCHMARKS["priority_high_under"]:
189
+ return "High"
190
+ return "Low" if score > BENCHMARKS["priority_low_over"] else "Medium"
191
+
192
+
193
+ def score_row(row: dict) -> dict:
194
+ """Health labels, score and priority for one row that already carries the economics and metric keys."""
195
+ net_sales = _f(row.get("net_sales"))
196
+ sponsored = _f(row.get("sponsored_ads"))
197
+ tacos = _ratio(sponsored, net_sales) if sponsored and sponsored > 0 else None
198
+ return_rate = _ratio(row.get("return_units"), row.get("units_sold"))
199
+ stock = combine([cover_band(row.get("days_of_cover"))])
200
+ profit = combine([band("margin", row.get("margin"))]) if net_sales else "No data"
201
+ ads = combine([band("ctr", row.get("ctr")), band("acos", row.get("acos")),
202
+ band("tacos", tacos), band("cvr", row.get("cvr"))])
203
+ listing = combine([band("unit_session_pct", row.get("unit_session_pct")),
204
+ band("return_rate", return_rate)])
205
+ score = _half_up(sum(points(label) for label in (stock, profit, ads, listing)))
206
+ return {"tacos": tacos, "return_rate": return_rate, "stock_health": stock, "profit_health": profit,
207
+ "ads_health": ads, "listing_health": listing, "score": score, "priority": priority_for(score)}
208
+
209
+
210
+ # ---------------------------------------------------------------- mirror reads
211
+
212
+ def _columns(con, table):
213
+ return {r[0] for r in con.execute(
214
+ "SELECT column_name FROM information_schema.columns WHERE table_name = ?", [table]).fetchall()}
215
+
216
+
217
+ def _q(name):
218
+ return '"' + str(name).replace('"', '""') + '"'
219
+
220
+
221
+ def _day(column):
222
+ """A DATE from an ISO text or timestamp prefix, or from MM/DD/YYYY."""
223
+ text = f"CAST({_q(column)} AS VARCHAR)"
224
+ return (f"COALESCE(TRY_CAST(substr({text}, 1, 10) AS DATE), "
225
+ f"CAST(try_strptime({text}, '%m/%d/%Y') AS DATE))")
226
+
227
+
228
+ def _pick(cols, *choices):
229
+ return next((c for c in choices if c in cols), None)
230
+
231
+
232
+ def _num_sql(cols, name):
233
+ return f"TRY_CAST({_q(name)} AS DOUBLE)" if name in cols else "NULL"
234
+
235
+
236
+ def _sku_sql(column):
237
+ return f"TRIM(CAST({_q(column)} AS VARCHAR))"
238
+
239
+
240
+ def _all_skus(con):
241
+ if "msku" not in _columns(con, ECONOMICS):
242
+ return []
243
+ return [r[0] for r in con.execute(
244
+ f"SELECT DISTINCT {_sku_sql('msku')} FROM {ECONOMICS} WHERE NULLIF(TRIM(CAST(msku AS VARCHAR)), '') "
245
+ "IS NOT NULL ORDER BY 1").fetchall()]
246
+
247
+
248
+ def _economics(con, start, end, skus):
249
+ """{sku: {asin, units}}: newest child ASIN and net units sold in [start, end]."""
250
+ cols = _columns(con, ECONOMICS)
251
+ if not {"msku", "start_date"} <= cols:
252
+ return {}
253
+ day = _day("start_date")
254
+ asin = (f"arg_max(NULLIF(TRIM(CAST(child_asin AS VARCHAR)), ''), {day})"
255
+ if "child_asin" in cols else "NULL")
256
+ units = (f"SUM(TRY_CAST(sales_net_units_sold AS DOUBLE)) FILTER (WHERE {day} BETWEEN "
257
+ "CAST(? AS DATE) AND CAST(? AS DATE))" if "sales_net_units_sold" in cols else "NULL")
258
+ args = [start, end] if "sales_net_units_sold" in cols else []
259
+ rows = con.execute(f"SELECT {_sku_sql('msku')}, {asin}, {units} FROM {ECONOMICS} "
260
+ f"WHERE {_sku_sql('msku')} IN (SELECT unnest(?)) GROUP BY 1",
261
+ [*args, skus]).fetchall()
262
+ return {r[0]: {"asin": r[1], "units": r[2]} for r in rows}
263
+
264
+
265
+ def _ads_parts(con):
266
+ """SELECT sku, day, impressions, clicks, cost, sales, orders over every present ads product table."""
267
+ parts = []
268
+ for table in ADS_PRODUCTS:
269
+ cols = _columns(con, table)
270
+ if not {"advertised_sku", "date"} <= cols:
271
+ continue
272
+ metrics = ", ".join(f"{_num_sql(cols, c)} AS {c}"
273
+ for c in ("impressions", "clicks", "cost", "sales", "orders"))
274
+ parts.append(f"SELECT {_sku_sql('advertised_sku')} AS sku, {_day('date')} AS day, {metrics} "
275
+ f"FROM {table}")
276
+ return " UNION ALL ".join(parts) or None
277
+
278
+
279
+ def _ads(con, start, end, skus):
280
+ """{sku: summed ad figures} in [start, end]; None when no ads table is mirrored."""
281
+ union = _ads_parts(con)
282
+ if union is None:
283
+ return None
284
+ rows = con.execute(
285
+ f"SELECT sku, SUM(impressions), SUM(clicks), SUM(cost), SUM(sales), SUM(orders), COUNT(*) "
286
+ f"FROM ({union}) a WHERE day BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) "
287
+ "AND sku IN (SELECT unnest(?)) GROUP BY 1", [start, end, skus]).fetchall()
288
+ return {r[0]: {"impressions": r[1], "clicks": r[2], "cost": r[3], "sales": r[4], "orders": r[5]}
289
+ for r in rows if r[6]}
290
+
291
+
292
+ def _returns_parts(con):
293
+ """SELECT sku, day, units over the FBA and MFN customer returns tables that are present."""
294
+ parts = []
295
+ for table, skus, days, qty in ((FBA_RETURNS, ("sku",), ("return_date",), ("quantity",)),
296
+ (MFN_RETURNS, ("merchant_sku", "sku"),
297
+ ("return_request_date", "return_date"), ("return_quantity", "quantity"))):
298
+ cols = _columns(con, table)
299
+ sku, day, units = _pick(cols, *skus), _pick(cols, *days), _pick(cols, *qty)
300
+ if sku is None or day is None:
301
+ continue
302
+ # A row without a quantity is one returned unit.
303
+ amount = f"COALESCE(TRY_CAST({_q(units)} AS DOUBLE), 1)" if units else "1"
304
+ parts.append(f"SELECT {_sku_sql(sku)} AS sku, {_day(day)} AS day, {amount} AS units FROM {table}")
305
+ return " UNION ALL ".join(parts) or None
306
+
307
+
308
+ def _returns(con, start, end, skus):
309
+ """{sku: returned units} in [start, end]; None when no returns table is mirrored."""
310
+ union = _returns_parts(con)
311
+ if union is None:
312
+ return None
313
+ rows = con.execute(f"SELECT sku, SUM(units) FROM ({union}) r WHERE day BETWEEN CAST(? AS DATE) "
314
+ "AND CAST(? AS DATE) AND sku IN (SELECT unnest(?)) GROUP BY 1",
315
+ [start, end, skus]).fetchall()
316
+ return {r[0]: r[1] for r in rows}
317
+
318
+
319
+ def _daily(con, first, last, skus):
320
+ """{sku: {day: [units, net_sales, ad_spend]}} for the series window."""
321
+ out = {}
322
+
323
+ def add(rows, index):
324
+ for sku, day, value in rows:
325
+ if day is not None and value is not None:
326
+ out.setdefault(sku, {}).setdefault(day.isoformat(), [0.0, 0.0, 0.0])[index] += value
327
+
328
+ cols = _columns(con, ECONOMICS)
329
+ if {"msku", "start_date"} <= cols:
330
+ for index, column in ((0, "sales_net_units_sold"), (1, "sales_net_product_sales_amount")):
331
+ if column in cols:
332
+ add(con.execute(
333
+ f"SELECT {_sku_sql('msku')}, {_day('start_date')} AS d, SUM(TRY_CAST({column} AS DOUBLE)) "
334
+ f"FROM {ECONOMICS} WHERE {_day('start_date')} BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) "
335
+ f"AND {_sku_sql('msku')} IN (SELECT unnest(?)) GROUP BY 1, 2",
336
+ [first, last, skus]).fetchall(), index)
337
+ union = _ads_parts(con)
338
+ if union is not None:
339
+ add(con.execute(f"SELECT sku, day, SUM(cost) FROM ({union}) a WHERE day BETWEEN CAST(? AS DATE) "
340
+ "AND CAST(? AS DATE) AND sku IN (SELECT unnest(?)) GROUP BY 1, 2",
341
+ [first, last, skus]).fetchall(), 2)
342
+ return out
343
+
344
+
345
+ def _parent_map(con):
346
+ """child ASIN -> parent ASIN from the mirror: economics first, then pricing."""
347
+ from harness import amazon_store
348
+ out = dict(amazon_store._pricing_parent_map(con))
349
+ out.update(amazon_store._economics_parent_map(con))
350
+ return out
351
+
352
+
353
+ def _out(value):
354
+ value = round(float(value), 2)
355
+ return int(value) if value == int(value) else value
356
+
357
+
358
+ def series_cell(values):
359
+ """The stored chart value: a JSON list of numbers, oldest first."""
360
+ return json.dumps([_out(v) for v in values])
361
+
362
+
363
+ def _series(value):
364
+ if isinstance(value, str):
365
+ try:
366
+ value = json.loads(value)
367
+ except ValueError:
368
+ return None
369
+ if not isinstance(value, (list, tuple)):
370
+ return None
371
+ return [_f(v) or 0.0 for v in value]
372
+
373
+
374
+ def _int(value):
375
+ value = _f(value)
376
+ return None if value is None else _half_up(value)
377
+
378
+
379
+ def sku_metrics(con, *, start, end, skus, today) -> dict[str, dict]:
380
+ """Per SKU metric cells for the period [start, end] (ISO dates), plus internal keys.
381
+
382
+ `skus` None reads every SKU in economics. Series cover the 30 days before `today`.
383
+ """
384
+ wanted = [s for s in dict.fromkeys(_text(s) for s in (_all_skus(con) if skus is None else skus)) if s]
385
+ if not wanted:
386
+ return {}
387
+ if isinstance(today, str):
388
+ today = dt.date.fromisoformat(today[:10])
389
+ days = [(today - dt.timedelta(days=SERIES_DAYS - i)).isoformat() for i in range(SERIES_DAYS)]
390
+ econ = _economics(con, start, end, wanted)
391
+ planning = restock_planner._planning(con, wanted) or {}
392
+ pricing = ranking_diagnostic._pricing(con) or {}
393
+ parents = _parent_map(con)
394
+ ads = _ads(con, start, end, wanted)
395
+ returns = _returns(con, start, end, wanted)
396
+ daily = _daily(con, days[0], days[-1], wanted)
397
+ out = {}
398
+ for sku in wanted:
399
+ e, p = econ.get(sku, {}), planning.get(sku)
400
+ asin = _text(e.get("asin")) or _text((p or {}).get("asin"))
401
+ row = {"asin": asin, "parent_asin": (parents.get(asin) or asin) if asin else None}
402
+ a = (ads or {}).get(sku)
403
+ impressions, clicks = (_f(a["impressions"]), _f(a["clicks"])) if a else (None, None)
404
+ spend, sales, orders = (_f(a["cost"]), _f(a["sales"]), _f(a["orders"])) if a else (None, None, None)
405
+ row.update(ad_impressions=_int(impressions), ad_clicks=_int(clicks), ad_spend=spend, ad_sales=sales,
406
+ ad_orders=_int(orders), ctr=_ratio(clicks, impressions), cvr=_ratio(orders, clicks),
407
+ cpc=_ratio(spend, clicks), acos=_ratio(spend, sales), roas=_ratio(sales, spend),
408
+ ads_note="" if a else NO_ADS_NOTE)
409
+ available = _f(p.get("available")) if p else None
410
+ velocity = _f(p.get("units")) if p else None
411
+ cover = _f(p.get("days")) if p else None
412
+ if cover is None and available is not None:
413
+ cover = _ratio(available * 30, velocity)
414
+ row.update(fba_on_hand=_int(available), inbound_units=_int(p.get("inbound")) if p else None,
415
+ velocity_30d=velocity, days_of_cover=_int(cover))
416
+ row["return_units"] = None if returns is None else _int(returns.get(sku) or 0)
417
+ traffic = pricing.get(asin) if asin else None
418
+ sessions = _int(traffic.get("sessions")) if traffic else None
419
+ box = _f(traffic.get("buyBox")) if traffic else None
420
+ row.update(sessions=sessions, buy_box_pct=None if box is None else box / 100.0,
421
+ unit_session_pct=_ratio(e.get("units"), sessions))
422
+ per_day = daily.get(sku, {})
423
+ for index, key in enumerate(SERIES_KEYS):
424
+ row[key] = series_cell(per_day.get(day, (0.0, 0.0, 0.0))[index] for day in days)
425
+ out[sku] = row
426
+ return out
427
+
428
+
429
+ # ---------------------------------------------------------------- grain rollups
430
+
431
+ def _sum(values):
432
+ found = [v for v in (_f(x) for x in values) if v is not None]
433
+ return sum(found) if found else None
434
+
435
+
436
+ def _active(row):
437
+ return bool(_f(row.get("net_sales")) or _f(row.get("units_sold")))
438
+
439
+
440
+ def rollup(rows: list[dict], *, key: str) -> list[dict]:
441
+ """One row per distinct rows[i][key] (asin or parent_asin): sums, recomputed ratios, then score_row keys."""
442
+ if key not in ("asin", "parent_asin"):
443
+ raise ValueError("Roll up by asin or parent_asin.")
444
+ groups, skipped = {}, []
445
+ for row in rows:
446
+ value = _text(row.get(key))
447
+ if value is None:
448
+ skipped.append(row.get("sku"))
449
+ continue
450
+ groups.setdefault(value, []).append(row)
451
+ last_report.clear()
452
+ last_report.update(key=key, groups=len(groups), skipped=len(skipped),
453
+ skipped_skus=sorted(str(s) for s in skipped if s is not None))
454
+ out = []
455
+ for value in sorted(groups):
456
+ children = sorted(groups[value], key=lambda r: str(r.get("sku") or ""))
457
+ skus = [str(c.get("sku")) for c in children if c.get("sku") is not None]
458
+ row = {key: value, "title": next((c.get("title") for c in children if c.get("title")), None),
459
+ "sku_count": len(children), "skus": ", ".join(skus)}
460
+ row["parent_asin"] = value if key == "parent_asin" else next(
461
+ (_text(c.get("parent_asin")) for c in children if _text(c.get("parent_asin"))), value)
462
+ for k in ADDITIVE_KEYS:
463
+ if k in _STRICT_KEYS and any(c.get(k) is None and _active(c) for c in children):
464
+ row[k] = None
465
+ continue
466
+ total = _sum(c.get(k) for c in children)
467
+ row[k] = _half_up(total) if total is not None and k in _INT_KEYS else total
468
+ for k in SERIES_KEYS:
469
+ total = [0.0] * SERIES_DAYS
470
+ for c in children:
471
+ for i, v in enumerate((_series(c.get(k)) or [])[:SERIES_DAYS]):
472
+ total[i] += v
473
+ row[k] = series_cell(total)
474
+ row.update(ctr=_ratio(row["ad_clicks"], row["ad_impressions"]),
475
+ cvr=_ratio(row["ad_orders"], row["ad_clicks"]), cpc=_ratio(row["ad_spend"], row["ad_clicks"]),
476
+ acos=_ratio(row["ad_spend"], row["ad_sales"]), roas=_ratio(row["ad_sales"], row["ad_spend"]),
477
+ margin=_ratio(row["net_profit"], row["net_sales"]) if row["net_profit"] is not None else None,
478
+ ads_note="" if any(c.get("ads_note") == "" for c in children) else NO_ADS_NOTE)
479
+ velocity = row["velocity_30d"]
480
+ cover = _ratio(row["fba_on_hand"], velocity / 30) if row["fba_on_hand"] is not None and velocity else None
481
+ row["days_of_cover"] = _int(cover)
482
+ # A SKU's sessions are its ASIN's, so they are summed once per distinct ASIN.
483
+ traffic = {}
484
+ for c in children:
485
+ asin = _text(c.get("asin"))
486
+ if asin and asin not in traffic:
487
+ traffic[asin] = (_f(c.get("sessions")), _f(c.get("buy_box_pct")))
488
+ sessions = _sum(s for s, _b in traffic.values())
489
+ boxes = [(b, s or 0.0) for s, b in traffic.values() if b is not None]
490
+ weight = sum(w for _b, w in boxes)
491
+ row["sessions"] = _int(sessions)
492
+ row["buy_box_pct"] = (sum(b * w for b, w in boxes) / weight if weight
493
+ else (sum(b for b, _w in boxes) / len(boxes) if boxes else None))
494
+ row["unit_session_pct"] = _ratio(row["units_sold"], row["sessions"])
495
+ if key == "asin":
496
+ row["asin"] = value
497
+ row.update(score_row(row))
498
+ out.append(row)
499
+ return out
500
+
501
+
502
+ # ---------------------------------------------------------------- validate
503
+
504
+ def _check(name, ok, a, b, gap, note=""):
505
+ return {"check": name, "ok": bool(ok), "a": None if a is None else round(a, 2),
506
+ "b": None if b is None else round(b, 2), "gap": None if gap is None else round(gap, 4),
507
+ "note": note}
508
+
509
+
510
+ def validate_metrics(con, *, start, end, computed: dict[str, dict]) -> list[dict]:
511
+ """Independent ties: [{check, ok, a, b, gap, note}] in amazon_profit.validate's shape."""
512
+ skus = [s for s in (_text(k) for k in computed) if s]
513
+ checks = []
514
+ spend = sum(_f(r.get("ad_spend")) or 0.0 for r in computed.values())
515
+ campaigns = [t for t in ADS_CAMPAIGNS if {"date", "cost"} <= _columns(con, t)]
516
+ if not campaigns and _ads_parts(con) is None:
517
+ checks.append(_check("ads_spend_ties_campaigns", True, 0, 0, 0, NO_ADS_NOTE))
518
+ elif not campaigns:
519
+ checks.append(_check("ads_spend_ties_campaigns", False, spend, None, None,
520
+ "Campaign reports are missing, so ad spend cannot be tied."))
521
+ else:
522
+ union = " UNION ALL ".join(f"SELECT {_day('date')} AS day, TRY_CAST(cost AS DOUBLE) AS cost FROM {t}"
523
+ for t in campaigns)
524
+ total = float(con.execute(f"SELECT COALESCE(SUM(cost), 0) FROM ({union}) c WHERE day BETWEEN "
525
+ "CAST(? AS DATE) AND CAST(? AS DATE)", [start, end]).fetchone()[0])
526
+ gap = abs(spend - total) / abs(total) if total else abs(spend - total)
527
+ checks.append(_check("ads_spend_ties_campaigns", gap <= ADS_TIE_TOLERANCE, spend, total, gap,
528
+ "Advertised product spend against campaign spend, within 2%."))
529
+ on_hand = sum(_f(r.get("fba_on_hand")) or 0.0 for r in computed.values())
530
+ cols = _columns(con, PLANNING)
531
+ if not {"sku", "available"} <= cols:
532
+ checks.append(_check("stock_ties_planning", True, 0, 0, 0, NO_STOCK_NOTE))
533
+ else:
534
+ newest = ('CAST("_snapshot_date" AS VARCHAR) = (SELECT MAX(CAST("_snapshot_date" AS VARCHAR)) '
535
+ f"FROM {PLANNING})" if "_snapshot_date" in cols else "TRUE")
536
+ total = float(con.execute(f"SELECT COALESCE(SUM(TRY_CAST(available AS DOUBLE)), 0) FROM {PLANNING} "
537
+ f"WHERE {newest} AND {_sku_sql('sku')} IN (SELECT unnest(?))",
538
+ [skus or [""]]).fetchone()[0])
539
+ gap = abs(on_hand - total)
540
+ checks.append(_check("stock_ties_planning", gap <= COUNT_TIE_TOLERANCE, on_hand, total, gap,
541
+ "FBA on hand against the newest planning snapshot."))
542
+ returned = sum(_f(r.get("return_units")) or 0.0 for r in computed.values())
543
+ union = _returns_parts(con)
544
+ if union is None:
545
+ checks.append(_check("returns_tie", True, 0, 0, 0, NO_RETURNS_NOTE))
546
+ else:
547
+ total = float(con.execute(f"SELECT COALESCE(SUM(units), 0) FROM ({union}) r WHERE day BETWEEN "
548
+ "CAST(? AS DATE) AND CAST(? AS DATE) AND sku IN (SELECT unnest(?))",
549
+ [start, end, skus or [""]]).fetchone()[0])
550
+ gap = abs(returned - total)
551
+ checks.append(_check("returns_tie", gap <= COUNT_TIE_TOLERANCE, returned, total, gap,
552
+ "Returned units against the returns tables in the period."))
553
+ short = [sku for sku, r in computed.items() for k in SERIES_KEYS
554
+ if len(_series(r.get(k)) or []) != SERIES_DAYS]
555
+ checks.append(_check("trend_length", not short, len(short), 0, len(short),
556
+ f"Every trend has {SERIES_DAYS} days." if not short
557
+ else f"Short trends: {', '.join(sorted(set(map(str, short))))}."))
558
+ return checks
platform/modules/restock_planner.py CHANGED
@@ -376,7 +376,7 @@ def _links(st, *, strict=False):
376
  table = user_tables.get_one(LINK_TABLE, st) or {}
377
  except Exception: # noqa: BLE001
378
  if strict:
379
- raise ValueError("SKU links could not be read. Reload Amazon SKU profit before sending.") from None
380
  table = {}
381
  out = {}
382
  for row in (table.get("rows") or {}).values():
@@ -807,13 +807,13 @@ def _reorder_link(st, sku):
807
  with pg._pool().connection() as con:
808
  count, code, raw_units, variants = con.execute(pg._q(sql, table, tenant), params).fetchone()
809
  if not count or not code:
810
- raise _ReorderUnavailable("This SKU has no Odoo product link.", "Link this SKU in Amazon SKU profit.")
811
  units = _num(raw_units)
812
  if variants != 1:
813
- raise _ReorderUnavailable("This SKU has conflicting links.", "Keep one conversion in Amazon SKU profit.")
814
  if units is None or not math.isfinite(units) or units <= 0:
815
  raise _ReorderUnavailable("This SKU has no valid units_per_sku.",
816
- "Set a positive conversion in Amazon SKU profit.")
817
  return code, units
818
 
819
 
@@ -931,7 +931,7 @@ def _compute_reorder(tenant_key, sku, *, cover_days=None, st=None, now=None, tea
931
  product = cur.execute("SELECT MIN(id), COUNT(*) FROM product_product WHERE trim(default_code)=?",
932
  [code]).fetchone()
933
  if product[1] != 1:
934
- raise ValueError("The linked Odoo product is missing or ambiguous. Fix the link in Amazon SKU profit.")
935
  product_id = int(product[0])
936
  cols = _columns(cur, PLANNING)
937
  snapshot = 'MAX(CAST(_snapshot_date AS VARCHAR))' if "_snapshot_date" in cols else "NULL"
@@ -2289,9 +2289,9 @@ def _inbound_quantities(tenant_key, items, st, *, require_stock_rows=False):
2289
  if not isinstance(sku, str) or not 1 <= len(sku.strip()) <= 255:
2290
  cause = f"{sku}: Amazon requires a SKU of 1 to 255 characters. Fix the SKU link before sending."
2291
  elif not code:
2292
- cause = f"{sku}: no valid SKU link. Link this SKU in Amazon SKU profit before sending."
2293
  elif units is None:
2294
- cause = f"{sku}: units per SKU must be a finite number above zero. Fix its Amazon SKU profit link."
2295
  elif codes is None or len(codes.get(code) or []) != 1:
2296
  cause = f"{sku}: the linked Odoo reference {code} needs exactly one product. Fix the SKU link and sync Odoo."
2297
  else:
 
376
  table = user_tables.get_one(LINK_TABLE, st) or {}
377
  except Exception: # noqa: BLE001
378
  if strict:
379
+ raise ValueError("SKU links could not be read. Reload Command Center before sending.") from None
380
  table = {}
381
  out = {}
382
  for row in (table.get("rows") or {}).values():
 
807
  with pg._pool().connection() as con:
808
  count, code, raw_units, variants = con.execute(pg._q(sql, table, tenant), params).fetchone()
809
  if not count or not code:
810
+ raise _ReorderUnavailable("This SKU has no Odoo product link.", "Link this SKU in Command Center.")
811
  units = _num(raw_units)
812
  if variants != 1:
813
+ raise _ReorderUnavailable("This SKU has conflicting links.", "Keep one conversion in Command Center.")
814
  if units is None or not math.isfinite(units) or units <= 0:
815
  raise _ReorderUnavailable("This SKU has no valid units_per_sku.",
816
+ "Set a positive conversion in Command Center.")
817
  return code, units
818
 
819
 
 
931
  product = cur.execute("SELECT MIN(id), COUNT(*) FROM product_product WHERE trim(default_code)=?",
932
  [code]).fetchone()
933
  if product[1] != 1:
934
+ raise ValueError("The linked Odoo product is missing or ambiguous. Fix the link in Command Center.")
935
  product_id = int(product[0])
936
  cols = _columns(cur, PLANNING)
937
  snapshot = 'MAX(CAST(_snapshot_date AS VARCHAR))' if "_snapshot_date" in cols else "NULL"
 
2289
  if not isinstance(sku, str) or not 1 <= len(sku.strip()) <= 255:
2290
  cause = f"{sku}: Amazon requires a SKU of 1 to 255 characters. Fix the SKU link before sending."
2291
  elif not code:
2292
+ cause = f"{sku}: no valid SKU link. Link this SKU in Command Center before sending."
2293
  elif units is None:
2294
+ cause = f"{sku}: units per SKU must be a finite number above zero. Fix its Command Center link."
2295
  elif codes is None or len(codes.get(code) or []) != 1:
2296
  cause = f"{sku}: the linked Odoo reference {code} needs exactly one product. Fix the SKU link and sync Odoo."
2297
  else:
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 15eadc89193107a27b04d1829ea836b83055d78cb4ad1213cb1bf89156625b71
 
1
+ 997b2217057eb3c8d9d4f307cdab5ab0e0c8df2027bccfcaedf78173b384d8f3
web/src/apps/amazon-profit/AccountView.tsx CHANGED
@@ -45,7 +45,8 @@ export type AccountPayload = ComparedWindow & {
45
  };
46
  type EmptyAccount = { empty: true; reason: string; validated: false };
47
  export type AccountComparison = "prior" | "yearAgo";
48
- export type AccountTab = "dashboard" | "grid";
 
49
  export type AccountSkuSelection = { sku: string; period: string; record: AccountSku };
50
 
51
  // C6 keeps unavailable values null before they reach a shared renderer.
@@ -103,19 +104,13 @@ export function useAccountDashboardComponents(override?: AccountDashboardCompone
103
  return override ? { components: override, pending: false } : result;
104
  }
105
 
 
106
  export function AccountTabs(props: AccountTabsProps & { components?: AccountDashboardComponents }) {
107
  const id = useId();
108
- if (props.components) {
109
- const Tabs = props.components.AppTabs;
110
- return <Tabs tabs={props.tabs} value={props.activeTab} ariaLabel="Amazon SKU profit"
111
- onChange={(value) => {
112
- const tab = props.tabs.find((item) => item.id === value);
113
- if (tab) props.onTabChange(tab.id);
114
- }} />;
115
- }
116
- return <div className="ap-tabs" role="tablist" aria-label="Amazon SKU profit">
117
  {props.tabs.map((tab, index) => <button type="button" role="tab" key={tab.id}
118
- id={`${id}-${tab.id}`} aria-selected={props.activeTab === tab.id}
119
  tabIndex={props.activeTab === tab.id ? 0 : -1}
120
  onClick={() => props.onTabChange(tab.id)}
121
  onKeyDown={(event) => {
 
45
  };
46
  type EmptyAccount = { empty: true; reason: string; validated: false };
47
  export type AccountComparison = "prior" | "yearAgo";
48
+ /** Command Center tabs: one Grid per grain, the Projects Grid, then the SKU dashboard. */
49
+ export type AccountTab = "sku" | "asin" | "parent" | "projects" | "dashboard";
50
  export type AccountSkuSelection = { sku: string; period: string; record: AccountSku };
51
 
52
  // C6 keeps unavailable values null before they reach a shared renderer.
 
104
  return override ? { components: override, pending: false } : result;
105
  }
106
 
107
+ /** One strip in the given order. The shared AppTabs always moves Dashboard first, so it is not used here. */
108
  export function AccountTabs(props: AccountTabsProps & { components?: AccountDashboardComponents }) {
109
  const id = useId();
110
+ return <div className={props.components ? "lp-app-tabs ap-command-tabs" : "ap-tabs ap-command-tabs"}
111
+ role="tablist" aria-label="Command Center">
 
 
 
 
 
 
 
112
  {props.tabs.map((tab, index) => <button type="button" role="tab" key={tab.id}
113
+ id={`${id}-${tab.id}`} data-tab={tab.id} aria-selected={props.activeTab === tab.id}
114
  tabIndex={props.activeTab === tab.id ? 0 : -1}
115
  onClick={() => props.onTabChange(tab.id)}
116
  onKeyDown={(event) => {
web/src/customer-grid/AmazonPeriodPicker.tsx CHANGED
@@ -3,14 +3,43 @@ import type { MutableRefObject } from "react";
3
  import { createPortal } from "react-dom";
4
  import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, signal } from "../apiContract";
5
  import { clearTopicRowsCache, dropTableRowsCache, refusalMessage } from "./apiBridge";
 
6
  import AccountView, { AccountTabs, useAccountDashboardComponents } from "../apps/amazon-profit/AccountView";
7
  import type { AccountDashboardComponents, AccountSkuSelection, AccountTab } from "../apps/amazon-profit/AccountView";
8
  import "./amazonPeriodPicker.css";
9
  export { DashboardPeriodPicker } from "./DashboardPeriodPicker";
10
 
11
- /** The table the period picker belongs to. Every other database renders nothing. */
12
  export const AMAZON_PROFIT_TABLE = "ut_amazon_sku_profit";
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  type PeriodChoice = { key: string; label: string };
15
  type ProfitStatus = {
16
  period: { key: string; label: string };
@@ -25,19 +54,30 @@ type Props = { database: string; dashboardComponents?: AccountDashboardComponent
25
  /** Keep the shared table period separate from each reader's account analysis window. */
26
  export default function AmazonPeriodPicker(props: Props) {
27
  const mainRef = useRef<HTMLElement | null>(null);
28
- const active = props.database === AMAZON_PROFIT_TABLE;
29
  useLayoutEffect(() => {
30
- if (!active && mainRef.current) delete mainRef.current.dataset.amazonProfitTab;
31
- }, [active]);
32
- if (!active) return null;
33
- return <ProfitTablePeriodPicker {...props} mainRef={mainRef} />;
 
 
 
 
 
 
 
34
  }
35
 
36
- function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }: Props & { mainRef: MutableRefObject<HTMLElement | null> }) {
 
37
  const [status, setStatus] = useState<ProfitStatus | null>(null);
38
  const [busy, setBusy] = useState(false);
39
  const [loading, setLoading] = useState(true);
40
- const [tab, setTab] = useState<AccountTab>("dashboard");
 
 
 
41
  const anchor = useRef<HTMLDivElement>(null);
42
  const [slot, setSlot] = useState<HTMLElement | null>(null);
43
  const shared = useAccountDashboardComponents(dashboardComponents);
@@ -63,8 +103,12 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }:
63
  const main = anchor.current?.closest<HTMLElement>(".cg-main");
64
  if (!main) return;
65
  mainRef.current = main;
66
- // The grid can remount this toolbar during its existing row refresh.
67
- if (main.dataset.amazonProfitTab === "grid") setTab("grid");
 
 
 
 
68
  const panel = document.createElement("div");
69
  panel.className = "ap-account-slot";
70
  main.appendChild(panel);
@@ -75,12 +119,37 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }:
75
  useLayoutEffect(() => {
76
  const main = anchor.current?.closest<HTMLElement>(".cg-main");
77
  if (!main || !slot) return;
78
- main.dataset.amazonProfitTab = tab;
79
- main.classList.toggle("ap-profit-dashboard", tab === "dashboard");
80
- slot.hidden = tab !== "dashboard";
 
81
  return () => { main.classList.remove("ap-profit-dashboard"); };
82
- }, [slot, tab]);
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  const choose = async (key: string) => {
86
  setBusy(true);
@@ -96,8 +165,10 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }:
96
  setMessage(refusalMessage(body, res.status, "The period did not change. Try again."));
97
  }
98
  // A refused tie still rewrote the rows (blank figures, the refusal in Period), so re-read.
99
- clearTopicRowsCache(`tables/${AMAZON_PROFIT_TABLE}/rows`);
100
- dropTableRowsCache(AMAZON_PROFIT_TABLE);
 
 
101
  signal(ROWS_STALE_EVENT);
102
  await load();
103
  } catch {
@@ -110,16 +181,17 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }:
110
  const choices = !status ? [] : status.periods.some((p) => p.key === status.period.key)
111
  ? status.periods : [{ key: status.period.key, label: status.period.label }, ...status.periods];
112
  const note = message ?? status?.refusal;
 
113
  return (
114
  <div className="ap-table-switcher" ref={anchor}>
115
- <AccountTabs tabs={[{ id: "dashboard", label: "Dashboard" }, { id: "grid", label: "Grid" }]}
116
- activeTab={tab} onTabChange={setTab} components={shared.components} />
117
  {tab === "dashboard" && slot && createPortal(loading
118
  ? <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>
119
  : <AccountView initialPeriod={status?.period.key} periods={status?.periods}
120
  components={shared.components} onSelectSku={onSelectSku} />, slot)}
121
  {tab === "dashboard" && !slot && <p role="status">Dashboard unavailable</p>}
122
- {tab === "grid" && status && (
123
  <div className="cg-period-picker" data-testid="amazon-period-picker">
124
  <label>
125
  <span>Period</span>
@@ -138,7 +210,7 @@ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef }:
138
  {note && <span className="cg-period-note" role="status">{note}</span>}
139
  </div>
140
  )}
141
- {tab === "grid" && !status && <p role="status">{loading ? "" : message ?? "The period could not be loaded."}</p>}
142
  </div>
143
  );
144
  }
 
3
  import { createPortal } from "react-dom";
4
  import { API_V1, CREDENTIALS, ROWS_STALE_EVENT, signal } from "../apiContract";
5
  import { clearTopicRowsCache, dropTableRowsCache, refusalMessage } from "./apiBridge";
6
+ import { dataPathHash, readDataPath } from "./dataPath";
7
  import AccountView, { AccountTabs, useAccountDashboardComponents } from "../apps/amazon-profit/AccountView";
8
  import type { AccountDashboardComponents, AccountSkuSelection, AccountTab } from "../apps/amazon-profit/AccountView";
9
  import "./amazonPeriodPicker.css";
10
  export { DashboardPeriodPicker } from "./DashboardPeriodPicker";
11
 
12
+ /** The SKU grain table. It owns the period and the dashboard. */
13
  export const AMAZON_PROFIT_TABLE = "ut_amazon_sku_profit";
14
 
15
+ type CommandCenterGrain = "sku" | "asin" | "parent" | "projects";
16
+ /** The Command Center tables. Every other database renders nothing. */
17
+ export const COMMAND_CENTER_TABLES: Record<string, CommandCenterGrain> = {
18
+ [AMAZON_PROFIT_TABLE]: "sku",
19
+ ut_amazon_asin_profit: "asin",
20
+ ut_amazon_parent_profit: "parent",
21
+ ut_amazon_projects: "projects",
22
+ };
23
+ const GRAIN_TABLE: Record<CommandCenterGrain, string> = Object.fromEntries(
24
+ Object.entries(COMMAND_CENTER_TABLES).map(([table, grain]) => [grain, table])) as Record<CommandCenterGrain, string>;
25
+ /** The period POST rewrites these three tables. Projects has no period. */
26
+ const PERIOD_TABLES = [AMAZON_PROFIT_TABLE, "ut_amazon_asin_profit", "ut_amazon_parent_profit"];
27
+ const COMMAND_CENTER_TABS: Array<{ id: AccountTab; label: string }> = [
28
+ { id: "sku", label: "SKU" }, { id: "asin", label: "ASIN" }, { id: "parent", label: "Parent ASIN" },
29
+ { id: "projects", label: "Projects" }, { id: "dashboard", label: "Dashboard" },
30
+ ];
31
+ type Mode = "grid" | "dashboard";
32
+ // A Dashboard click on another table navigates to the SKU table. The grid can remount on that
33
+ // switch, so the request rides here as well as on the `.cg-main` dataset.
34
+ let dashboardRequested = false;
35
+
36
+ /** Open a database's Grid through the same hash the Table rail writes. */
37
+ function openCommandCenterTable(table: string) {
38
+ const current = readDataPath();
39
+ if (current?.database === table) return;
40
+ window.location.hash = dataPathHash({ database: table });
41
+ }
42
+
43
  type PeriodChoice = { key: string; label: string };
44
  type ProfitStatus = {
45
  period: { key: string; label: string };
 
54
  /** Keep the shared table period separate from each reader's account analysis window. */
55
  export default function AmazonPeriodPicker(props: Props) {
56
  const mainRef = useRef<HTMLElement | null>(null);
57
+ const grain: CommandCenterGrain | undefined = COMMAND_CENTER_TABLES[props.database];
58
  useLayoutEffect(() => {
59
+ if (!grain && mainRef.current) delete mainRef.current.dataset.amazonProfitTab;
60
+ }, [grain]);
61
+ useLayoutEffect(() => () => {
62
+ // A toolbar remount mounts a new switcher in the same commit, so clear only when none came back.
63
+ const main = mainRef.current;
64
+ if (main) window.setTimeout(() => {
65
+ if (!main.querySelector(".ap-table-switcher")) delete main.dataset.amazonProfitTab;
66
+ }, 0);
67
+ }, []);
68
+ if (!grain) return null;
69
+ return <ProfitTablePeriodPicker {...props} grain={grain} mainRef={mainRef} />;
70
  }
71
 
72
+ function ProfitTablePeriodPicker({ dashboardComponents, onSelectSku, mainRef, grain }: Props & {
73
+ grain: CommandCenterGrain; mainRef: MutableRefObject<HTMLElement | null> }) {
74
  const [status, setStatus] = useState<ProfitStatus | null>(null);
75
  const [busy, setBusy] = useState(false);
76
  const [loading, setLoading] = useState(true);
77
+ const [mode, setMode] = useState<Mode>("grid");
78
+ const dashboardOn = grain === "sku" && mode === "dashboard";
79
+ const tab: AccountTab = dashboardOn ? "dashboard" : grain;
80
+ const lastGrain = useRef(grain);
81
  const anchor = useRef<HTMLDivElement>(null);
82
  const [slot, setSlot] = useState<HTMLElement | null>(null);
83
  const shared = useAccountDashboardComponents(dashboardComponents);
 
103
  const main = anchor.current?.closest<HTMLElement>(".cg-main");
104
  if (!main) return;
105
  mainRef.current = main;
106
+ // The grid can remount this toolbar during its row refresh or a Command Center table switch.
107
+ const wanted = main.dataset.amazonProfitTab === "dashboard" || dashboardRequested;
108
+ if (lastGrain.current === "sku") {
109
+ setMode(wanted ? "dashboard" : "grid");
110
+ dashboardRequested = false;
111
+ }
112
  const panel = document.createElement("div");
113
  panel.className = "ap-account-slot";
114
  main.appendChild(panel);
 
119
  useLayoutEffect(() => {
120
  const main = anchor.current?.closest<HTMLElement>(".cg-main");
121
  if (!main || !slot) return;
122
+ // A pending Dashboard request from another grain keeps "dashboard" until the SKU table arrives.
123
+ main.dataset.amazonProfitTab = dashboardOn || dashboardRequested ? "dashboard" : "grid";
124
+ main.classList.toggle("ap-profit-dashboard", dashboardOn);
125
+ slot.hidden = !dashboardOn;
126
  return () => { main.classList.remove("ap-profit-dashboard"); };
127
+ }, [slot, dashboardOn]);
128
 
129
+ // Any grain switch, by a tab, the rail or the URL, opens that table's Grid. Only a pending
130
+ // Dashboard request opens the SKU dashboard on arrival.
131
+ useLayoutEffect(() => {
132
+ if (lastGrain.current === grain) return;
133
+ lastGrain.current = grain;
134
+ setMode(grain === "sku" && dashboardRequested ? "dashboard" : "grid");
135
+ if (grain === "sku") dashboardRequested = false;
136
+ }, [grain]);
137
+
138
+ const chooseTab = (next: AccountTab) => {
139
+ if (next !== "dashboard") {
140
+ dashboardRequested = false;
141
+ setMode("grid");
142
+ openCommandCenterTable(GRAIN_TABLE[next]);
143
+ return;
144
+ }
145
+ if (grain === "sku") {
146
+ setMode("dashboard");
147
+ return;
148
+ }
149
+ dashboardRequested = true;
150
+ if (mainRef.current) mainRef.current.dataset.amazonProfitTab = "dashboard";
151
+ openCommandCenterTable(AMAZON_PROFIT_TABLE);
152
+ };
153
 
154
  const choose = async (key: string) => {
155
  setBusy(true);
 
165
  setMessage(refusalMessage(body, res.status, "The period did not change. Try again."));
166
  }
167
  // A refused tie still rewrote the rows (blank figures, the refusal in Period), so re-read.
168
+ for (const table of PERIOD_TABLES) {
169
+ clearTopicRowsCache(`tables/${table}/rows`);
170
+ dropTableRowsCache(table);
171
+ }
172
  signal(ROWS_STALE_EVENT);
173
  await load();
174
  } catch {
 
181
  const choices = !status ? [] : status.periods.some((p) => p.key === status.period.key)
182
  ? status.periods : [{ key: status.period.key, label: status.period.label }, ...status.periods];
183
  const note = message ?? status?.refusal;
184
+ const showPeriod = !dashboardOn && grain !== "projects";
185
  return (
186
  <div className="ap-table-switcher" ref={anchor}>
187
+ <AccountTabs tabs={COMMAND_CENTER_TABS}
188
+ activeTab={tab} onTabChange={chooseTab} components={shared.components} />
189
  {tab === "dashboard" && slot && createPortal(loading
190
  ? <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>
191
  : <AccountView initialPeriod={status?.period.key} periods={status?.periods}
192
  components={shared.components} onSelectSku={onSelectSku} />, slot)}
193
  {tab === "dashboard" && !slot && <p role="status">Dashboard unavailable</p>}
194
+ {showPeriod && status && (
195
  <div className="cg-period-picker" data-testid="amazon-period-picker">
196
  <label>
197
  <span>Period</span>
 
210
  {note && <span className="cg-period-note" role="status">{note}</span>}
211
  </div>
212
  )}
213
+ {showPeriod && !status && <p role="status">{loading ? "" : message ?? "The period could not be loaded."}</p>}
214
  </div>
215
  );
216
  }
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -195,12 +195,13 @@ import { CatalogView } from "./CatalogView";
195
  import { GalleryView, TimelineView } from "./GalleryTimelineViews";
196
  import { foldGridCell } from "./navFold";
197
  import { CATALOG_CODE_FIELD } from "./catalogData";
198
- import type { CatalogSpec } from "./types";
199
  /* ═══ end W18-C CATALOG ═══ */
200
  import { lightTheme, HOVER_NEUTRAL,
201
  ACTIVE_ROW_NEUTRAL, CUSTOM_FIELD_MARK } from "./theme";
202
- import { avatarInitials, formatDisplay, imageCellRenderer, matchChoices, pickerTypeSeed,
203
- ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells";
 
204
  // ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with.
205
  // A second parse here is how a cell painted blank while the total under it counted 1,234.50.
206
  import { actionHref, numberWriteRefusal, numericOrUndefined } from "./display";
@@ -294,7 +295,8 @@ export const GRID_CHAT_OPEN_EVENT = "aios:grid-chat-open";
294
 
295
  // One identity for the life of the module: a new array remounts glide's open cell editor, which
296
  // selects the text typed so far, and the next keystroke replaces it.
297
- const CUSTOM_RENDERERS = [ratingCellRenderer, userCellRenderer, imageCellRenderer];
 
298
 
299
  const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48 };
300
 
@@ -327,6 +329,10 @@ const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48
327
  * redundant, and harmless, because it says exactly the same thing.
328
  */
329
  const ONE_LINE = { whiteSpace: "nowrap" } as const;
 
 
 
 
330
 
331
  function formatHistoryValue(value: unknown): string {
332
  if (value === null || value === "") return "Empty";
@@ -2131,6 +2137,8 @@ interface CustomerGridProps {
2131
  /** A fresh drill is resolving ids; withhold the previous id page during that request. */
2132
  embeddedIdsPending?: boolean;
2133
  onEmbeddedTotalChange?: (total: number | null) => void;
 
 
2134
  /** Selection mode used by an editable ordinary-Link modal. */
2135
  embeddedSelectable?: boolean;
2136
  embeddedSelectedIds?: readonly number[];
@@ -2223,6 +2231,29 @@ export function scopeForLinkTable(table: unknown): SurfaceScope | undefined {
2223
  return table as `ut_${string}`;
2224
  }
2225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2226
  interface LinkGridModalProps {
2227
  label: string;
2228
  table: SurfaceScope;
@@ -2247,6 +2278,8 @@ interface LinkGridModalProps {
2247
  onCellDisplayChange?: (display: CellDisplayChoice) => void;
2248
  /** W56-T24: chrome the caller owns, in the header, right of the title and left of Close. */
2249
  headerActions?: ReactNode;
 
 
2250
  /** W56-T24: a statement under the rows. Only rendered on a non-editable modal. */
2251
  footer?: ReactNode;
2252
  onOpenRecord?: CustomerGridProps["onOpenRecord"];
@@ -2261,7 +2294,7 @@ interface LinkGridModalProps {
2261
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
2262
  excludeRecordId, selectionFilter, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
2263
  headerActions, footer, initialPage, rowSource, idsPending = false,
2264
- onOpenRecord, onSave, onClose }: LinkGridModalProps) {
2265
  const panelRef = useRef<HTMLDivElement>(null);
2266
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
2267
  const countKey = `${table}:${rowSource?.key ?? recordIdsKey(recordIds)}`;
@@ -2332,6 +2365,7 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
2332
  embeddedRowSource={editable ? undefined : rowSource}
2333
  embeddedIdsPending={!editable && idsPending}
2334
  onEmbeddedTotalChange={editable ? undefined : reportTotal}
 
2335
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
2336
  embeddedSelectionFilter={editable ? selectionFilter : undefined}
2337
  embeddedSelectable={editable}
@@ -2631,6 +2665,7 @@ function CustomerGridSurface({
2631
  embeddedRowSource,
2632
  embeddedIdsPending = false,
2633
  onEmbeddedTotalChange,
 
2634
  embeddedSelectable = false,
2635
  embeddedSelectedIds = [],
2636
  onEmbeddedSelectionChange,
@@ -2839,6 +2874,12 @@ function CustomerGridSurface({
2839
  useEffect(() => {
2840
  onEmbeddedTotalChange?.(payload?.counts?.matched ?? null);
2841
  }, [onEmbeddedTotalChange, payload?.counts?.matched]);
 
 
 
 
 
 
2842
  const payloadFields = useMemo(() => {
2843
  if (!payload?.workspace?.auditTimestamps || payloadFieldsRaw.some((field) => field.key === "_updated"))
2844
  return payloadFieldsRaw;
@@ -3236,6 +3277,17 @@ function CustomerGridSurface({
3236
  * This is intentionally distinct from JsonViewer: filters, sorts, search, column visibility,
3237
  * and the standard cell renderers all remain available inside the large modal. */
3238
  const [linkAt, setLinkAt] = useState<{ pid: number; fieldKey: string } | null>(null);
 
 
 
 
 
 
 
 
 
 
 
3239
  const closeLink = useCallback(() => {
3240
  setLinkAt(null);
3241
  requestAnimationFrame(() => gridRef.current?.focus());
@@ -10938,11 +10990,53 @@ function CustomerGridSurface({
10938
  const linkTargetScope = linkField?.type === "link"
10939
  ? scopeForLinkTable(linkField.link?.table)
10940
  : undefined;
10941
- const linkedRecordIds = [...new Set(
10942
- linkValue.split(",").map((part) => Number(part.trim())).filter(
10943
  (pid) => Number.isInteger(pid) && pid > 0
10944
- )
10945
- )];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10946
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
10947
  const dateField = datePicker ? fieldByKey.get(datePicker.fieldKey) : undefined;
10948
  const dateRow = datePicker ? rawRows.find((row) => row.pid === datePicker.pid) : undefined;
@@ -13937,6 +14031,23 @@ function CustomerGridSurface({
13937
  single={linkField.link?.single === true}
13938
  excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
13939
  selectionFilter={linkField.link?.selectionFilter}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13940
  onSave={(ids) => patchAndRecord(
13941
  linkAt.pid,
13942
  { [linkField.key]: ids.join(",") },
 
195
  import { GalleryView, TimelineView } from "./GalleryTimelineViews";
196
  import { foldGridCell } from "./navFold";
197
  import { CATALOG_CODE_FIELD } from "./catalogData";
198
+ import type { CatalogSpec, LinkSeed } from "./types";
199
  /* ═══ end W18-C CATALOG ═══ */
200
  import { lightTheme, HOVER_NEUTRAL,
201
  ACTIVE_ROW_NEUTRAL, CUSTOM_FIELD_MARK } from "./theme";
202
+ import { avatarInitials, barCellRenderer, dotCellRenderer, formatDisplay, imageCellRenderer,
203
+ matchChoices, pickerTypeSeed, ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells";
204
+ import { chartCellRenderer } from "./sparklineCell";
205
  // ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with.
206
  // A second parse here is how a cell painted blank while the total under it counted 1,234.50.
207
  import { actionHref, numberWriteRefusal, numericOrUndefined } from "./display";
 
295
 
296
  // One identity for the life of the module: a new array remounts glide's open cell editor, which
297
  // selects the text typed so far, and the next keystroke replaces it.
298
+ const CUSTOM_RENDERERS = [ratingCellRenderer, userCellRenderer, imageCellRenderer,
299
+ chartCellRenderer, barCellRenderer, dotCellRenderer];
300
 
301
  const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48 };
302
 
 
329
  * redundant, and harmless, because it says exactly the same thing.
330
  */
331
  const ONE_LINE = { whiteSpace: "nowrap" } as const;
332
+ const LINK_ADD_ROW = { display: "flex", alignItems: "center", gap: 8, marginLeft: "auto",
333
+ minWidth: 0 } as const;
334
+ const LINK_ADD_NOTICE = { color: LP_RED_DEEP, whiteSpace: "nowrap", overflow: "hidden",
335
+ textOverflow: "ellipsis", maxWidth: 360 } as const;
336
 
337
  function formatHistoryValue(value: unknown): string {
338
  if (value === null || value === "") return "Empty";
 
2137
  /** A fresh drill is resolving ids; withhold the previous id page during that request. */
2138
  embeddedIdsPending?: boolean;
2139
  onEmbeddedTotalChange?: (total: number | null) => void;
2140
+ /** Reports whether this embedded `ut_*` grid accepts new records (its own `recordsMutable`). */
2141
+ onEmbeddedRecordsMutableChange?: (mutable: boolean) => void;
2142
  /** Selection mode used by an editable ordinary-Link modal. */
2143
  embeddedSelectable?: boolean;
2144
  embeddedSelectedIds?: readonly number[];
 
2231
  return table as `ut_${string}`;
2232
  }
2233
 
2234
+ interface LinkAddState {
2235
+ forKey: string;
2236
+ mutable: boolean;
2237
+ busy: boolean;
2238
+ added: number[];
2239
+ notice: string;
2240
+ }
2241
+ const LINK_ADD_IDLE: LinkAddState = { forKey: "", mutable: false, busy: false, added: [], notice: "" };
2242
+ const LINK_ADD_TITLE = "New project";
2243
+
2244
+ /** A link field's popup add recipe, or undefined when the server sent none or a malformed one. */
2245
+ export function linkSeedOf(field: Field): LinkSeed | undefined {
2246
+ const seed = field.format?.seed;
2247
+ if (!seed || typeof seed !== "object") return undefined;
2248
+ const ok = (s: unknown) => typeof s === "string" && s.trim() !== "";
2249
+ if (!ok(seed.keyFrom) || !ok(seed.keyField) || !ok(seed.titleField)) return undefined;
2250
+ if (typeof seed.relink !== "string") return undefined;
2251
+ const values: Record<string, string> = {};
2252
+ if (seed.values && typeof seed.values === "object")
2253
+ for (const [k, v] of Object.entries(seed.values)) if (typeof v === "string") values[k] = v;
2254
+ return { ...seed, values };
2255
+ }
2256
+
2257
  interface LinkGridModalProps {
2258
  label: string;
2259
  table: SurfaceScope;
 
2278
  onCellDisplayChange?: (display: CellDisplayChoice) => void;
2279
  /** W56-T24: chrome the caller owns, in the header, right of the title and left of Close. */
2280
  headerActions?: ReactNode;
2281
+ /** Forwarded to the embedded grid: whether the target database accepts new records. */
2282
+ onRecordsMutableChange?: (mutable: boolean) => void;
2283
  /** W56-T24: a statement under the rows. Only rendered on a non-editable modal. */
2284
  footer?: ReactNode;
2285
  onOpenRecord?: CustomerGridProps["onOpenRecord"];
 
2294
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
2295
  excludeRecordId, selectionFilter, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
2296
  headerActions, footer, initialPage, rowSource, idsPending = false,
2297
+ onRecordsMutableChange, onOpenRecord, onSave, onClose }: LinkGridModalProps) {
2298
  const panelRef = useRef<HTMLDivElement>(null);
2299
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
2300
  const countKey = `${table}:${rowSource?.key ?? recordIdsKey(recordIds)}`;
 
2365
  embeddedRowSource={editable ? undefined : rowSource}
2366
  embeddedIdsPending={!editable && idsPending}
2367
  onEmbeddedTotalChange={editable ? undefined : reportTotal}
2368
+ onEmbeddedRecordsMutableChange={onRecordsMutableChange}
2369
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
2370
  embeddedSelectionFilter={editable ? selectionFilter : undefined}
2371
  embeddedSelectable={editable}
 
2665
  embeddedRowSource,
2666
  embeddedIdsPending = false,
2667
  onEmbeddedTotalChange,
2668
+ onEmbeddedRecordsMutableChange,
2669
  embeddedSelectable = false,
2670
  embeddedSelectedIds = [],
2671
  onEmbeddedSelectionChange,
 
2874
  useEffect(() => {
2875
  onEmbeddedTotalChange?.(payload?.counts?.matched ?? null);
2876
  }, [onEmbeddedTotalChange, payload?.counts?.matched]);
2877
+ // False until the target's payload arrives, so the popup never offers an add it cannot make.
2878
+ const embeddedRecordsMutable = scope.startsWith("ut_") && !!payload
2879
+ && payload.recordsMutable !== false;
2880
+ useEffect(() => {
2881
+ onEmbeddedRecordsMutableChange?.(embeddedRecordsMutable);
2882
+ }, [onEmbeddedRecordsMutableChange, embeddedRecordsMutable]);
2883
  const payloadFields = useMemo(() => {
2884
  if (!payload?.workspace?.auditTimestamps || payloadFieldsRaw.some((field) => field.key === "_updated"))
2885
  return payloadFieldsRaw;
 
3277
  * This is intentionally distinct from JsonViewer: filters, sorts, search, column visibility,
3278
  * and the standard cell renderers all remain available inside the large modal. */
3279
  const [linkAt, setLinkAt] = useState<{ pid: number; fieldKey: string } | null>(null);
3280
+ // The link popup's "Add project" state, keyed to the open cell so a new popup starts fresh.
3281
+ const [linkAddRaw, setLinkAdd] = useState<LinkAddState>(LINK_ADD_IDLE);
3282
+ const linkAddKey = linkAt ? `${linkAt.pid}:${linkAt.fieldKey}` : "";
3283
+ const linkAdd = linkAddRaw.forKey === linkAddKey ? linkAddRaw : { ...LINK_ADD_IDLE, forKey: linkAddKey };
3284
+ const patchLinkAdd = useCallback((key: string, patch: Partial<LinkAddState>) => {
3285
+ setLinkAdd((current) => ({
3286
+ ...(current.forKey === key ? current : { ...LINK_ADD_IDLE, forKey: key }), ...patch }));
3287
+ }, []);
3288
+ const onLinkTargetMutable = useCallback((mutable: boolean) => {
3289
+ patchLinkAdd(linkAddKey, { mutable });
3290
+ }, [patchLinkAdd, linkAddKey]);
3291
  const closeLink = useCallback(() => {
3292
  setLinkAt(null);
3293
  requestAnimationFrame(() => gridRef.current?.focus());
 
10990
  const linkTargetScope = linkField?.type === "link"
10991
  ? scopeForLinkTable(linkField.link?.table)
10992
  : undefined;
10993
+ const linkedRecordIds = [...new Set([
10994
+ ...linkValue.split(",").map((part) => Number(part.trim())).filter(
10995
  (pid) => Number.isInteger(pid) && pid > 0
10996
+ ),
10997
+ ...linkAdd.added,
10998
+ ])];
10999
+ const linkSeed = linkField?.type === "link" ? linkSeedOf(linkField) : undefined;
11000
+ const linkCanAdd = !!linkSeed && !!linkTargetScope && linkTargetScope.startsWith("ut_")
11001
+ && linkAdd.mutable;
11002
+ const addLinkedSeedRow = async () => {
11003
+ if (!linkAt || !linkSeed || !linkTargetScope || linkAdd.busy) return;
11004
+ const key = linkAddKey;
11005
+ const keyValue = overlayEdits[linkAt.pid]?.[linkSeed.keyFrom]
11006
+ ?? (linkRow ? linkRow[linkSeed.keyFrom] : undefined);
11007
+ if (keyValue == null || String(keyValue).trim() === "") {
11008
+ patchLinkAdd(key, { notice: "This record has nothing to link a new row to." });
11009
+ return;
11010
+ }
11011
+ patchLinkAdd(key, { busy: true, notice: "" });
11012
+ const values = { ...linkSeed.values, [linkSeed.keyField]: String(keyValue),
11013
+ [linkSeed.titleField]: LINK_ADD_TITLE };
11014
+ const made = await addTableRow(linkTargetScope, values);
11015
+ if (!made) {
11016
+ patchLinkAdd(key, { busy: false, notice: "The new row was not added." });
11017
+ return;
11018
+ }
11019
+ let notice = "";
11020
+ if (linkSeed.relink.startsWith("/")) {
11021
+ try {
11022
+ const res = await fetch(`${API_V1}${linkSeed.relink}`, {
11023
+ method: "POST", credentials: CREDENTIALS,
11024
+ headers: { "Content-Type": "application/json" }, body: "{}",
11025
+ });
11026
+ if (!res.ok) {
11027
+ const body: unknown = await res.json().catch(() => null);
11028
+ notice = refusalMessage(body, res.status, "The row was added. The link did not refresh.");
11029
+ }
11030
+ } catch {
11031
+ notice = "The row was added. The link did not refresh.";
11032
+ }
11033
+ }
11034
+ dropTableRowsCache(scope);
11035
+ dropTableRowsCache(linkTargetScope);
11036
+ signal(ROWS_STALE_EVENT);
11037
+ setLinkAdd((current) => current.forKey !== key ? current
11038
+ : { ...current, busy: false, notice, added: [...current.added, made.pid] });
11039
+ };
11040
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
11041
  const dateField = datePicker ? fieldByKey.get(datePicker.fieldKey) : undefined;
11042
  const dateRow = datePicker ? rawRows.find((row) => row.pid === datePicker.pid) : undefined;
 
14031
  single={linkField.link?.single === true}
14032
  excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
14033
  selectionFilter={linkField.link?.selectionFilter}
14034
+ onRecordsMutableChange={linkSeed ? onLinkTargetMutable : undefined}
14035
+ headerActions={linkCanAdd ? (
14036
+ <div style={LINK_ADD_ROW}>
14037
+ {linkAdd.notice && (
14038
+ <span role="status" style={LINK_ADD_NOTICE}>{linkAdd.notice}</span>
14039
+ )}
14040
+ <button
14041
+ type="button"
14042
+ className="cg-btn"
14043
+ style={ONE_LINE}
14044
+ disabled={linkAdd.busy}
14045
+ onClick={() => { void addLinkedSeedRow(); }}
14046
+ >
14047
+ {linkField.format?.addLabel ?? "Add"}
14048
+ </button>
14049
+ </div>
14050
+ ) : undefined}
14051
  onSave={(ids) => patchAndRecord(
14052
  linkAt.pid,
14053
  { [linkField.key]: ids.join(",") },
web/src/customer-grid/cells.ts CHANGED
@@ -35,11 +35,15 @@ import type {
35
  import { assetUrl } from "./catalogData";
36
  import type { Field } from "./types";
37
  import { ratingMax } from "./types";
 
 
38
  import {
39
  LP_BLUE_TEXT,
40
  LP_BLUE_TINT,
41
  LP_GREEN_DEEP,
42
  LP_GREEN_TINT,
 
 
43
  LP_RED_DEEP,
44
  LP_RED_TINT,
45
  LP_YELLOW_DEEP,
@@ -390,6 +394,131 @@ export const ratingCellRenderer: CustomRenderer<RatingCell> = {
390
  },
391
  };
392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  /** Build the cell for one (field, value). `editable` gates overlay + readonly.
394
  *
395
  * ⚠ A BLANK numeric cell renders EMPTY, never "$0" (2026-07-27). `''`/null is how a value that
@@ -445,6 +574,28 @@ function baseCell(
445
  // a fabricated figure on the canvas beside an honest em-dash in the record panel.
446
  const noNumber = numericIsBlank(v);
447
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  switch (field.type) {
449
  case "currency":
450
  return {
@@ -687,6 +838,17 @@ function baseCell(
687
  allowOverlay: false,
688
  };
689
  }
 
 
 
 
 
 
 
 
 
 
 
690
  case "rating": {
691
  const max = ratingMax(field);
692
  const n = Math.max(0, Math.min(max, Math.round(num(v))));
@@ -732,9 +894,13 @@ function baseCell(
732
  // string silently reached the clipboard and then the paste path. A count is not data and
733
  // cannot be pasted back into a relation.
734
  const ids = String(v ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
 
 
 
735
  return {
736
  kind: GridCellKind.Bubble,
737
- data: ids.length ? [ids.length === 1 ? "1 record" : `${ids.length} records`] : [],
 
738
  copyData: String(v ?? ""),
739
  allowOverlay: false,
740
  };
 
35
  import { assetUrl } from "./catalogData";
36
  import type { Field } from "./types";
37
  import { ratingMax } from "./types";
38
+ import { chartValues } from "./sparklineCell";
39
+ import type { ChartCellData } from "./sparklineCell";
40
  import {
41
  LP_BLUE_TEXT,
42
  LP_BLUE_TINT,
43
  LP_GREEN_DEEP,
44
  LP_GREEN_TINT,
45
+ LP_LINE,
46
+ LP_MUTED,
47
  LP_RED_DEEP,
48
  LP_RED_TINT,
49
  LP_YELLOW_DEEP,
 
394
  },
395
  };
396
 
397
+ // --- bar: a 0..100 score as a track plus its number (format.display "bar") --
398
+
399
+ export interface BarCellData {
400
+ kind: "aios-bar";
401
+ /** null = blank, draws nothing. */
402
+ value: number | null;
403
+ }
404
+ export type BarCell = CustomCell<BarCellData>;
405
+
406
+ /** The owner's priority bands: red under 40, yellow from 40 to 70, green over 70. */
407
+ export function barColour(value: number): string {
408
+ if (value < 40) return LP_RED_DEEP;
409
+ if (value <= 70) return LP_YELLOW_DEEP;
410
+ return LP_GREEN_DEEP;
411
+ }
412
+
413
+ /** Draw `text` right aligned at `right` with every digit on one fixed advance (tabular figures). */
414
+ function fillTabular(ctx: CanvasRenderingContext2D, text: string, right: number, y: number): void {
415
+ const digit = ctx.measureText("0").width;
416
+ let x = right;
417
+ ctx.textAlign = "left";
418
+ for (let i = text.length - 1; i >= 0; i -= 1) {
419
+ const ch = text[i];
420
+ const w = ch >= "0" && ch <= "9" ? digit : ctx.measureText(ch).width;
421
+ x -= w;
422
+ ctx.fillText(ch, x + (w - ctx.measureText(ch).width) / 2, y);
423
+ }
424
+ }
425
+
426
+ const BAR_NUMBER_W = 36;
427
+ const BAR_GAP = 8;
428
+ const BAR_TRACK_H = 6;
429
+
430
+ export const barCellRenderer: CustomRenderer<BarCell> = {
431
+ kind: GridCellKind.Custom,
432
+ isMatch: (cell): cell is BarCell =>
433
+ (cell.data as BarCellData | undefined)?.kind === "aios-bar",
434
+ draw: (args, cell) => {
435
+ const { ctx, rect, theme } = args;
436
+ const { value } = cell.data;
437
+ if (value === null || !Number.isFinite(value)) return true;
438
+ const pad = theme.cellHorizontalPadding;
439
+ const right = rect.x + rect.width - pad;
440
+ const cy = rect.y + rect.height / 2;
441
+ ctx.save();
442
+ ctx.font = theme.baseFontFull;
443
+ ctx.fillStyle = theme.textDark;
444
+ ctx.textBaseline = "middle";
445
+ fillTabular(ctx, String(Math.round(value)), right, cy);
446
+ const trackX = rect.x + pad;
447
+ const trackW = right - BAR_NUMBER_W - BAR_GAP - trackX;
448
+ if (trackW > 4) {
449
+ const ty = cy - BAR_TRACK_H / 2;
450
+ const r = BAR_TRACK_H / 2;
451
+ ctx.beginPath();
452
+ ctx.roundRect(trackX, ty, trackW, BAR_TRACK_H, r);
453
+ ctx.fillStyle = LP_LINE;
454
+ ctx.fill();
455
+ const fillW = trackW * Math.max(0, Math.min(1, value / 100));
456
+ if (fillW > 0) {
457
+ ctx.beginPath();
458
+ ctx.roundRect(trackX, ty, Math.max(fillW, BAR_TRACK_H), BAR_TRACK_H, r);
459
+ ctx.fillStyle = barColour(value);
460
+ ctx.fill();
461
+ }
462
+ }
463
+ ctx.restore();
464
+ return true;
465
+ },
466
+ };
467
+
468
+ // --- dot: a select word with a coloured dot and no pill (format.display "dot") --
469
+
470
+ export interface DotCellData {
471
+ kind: "aios-dot";
472
+ value: string;
473
+ colour: string;
474
+ }
475
+ export type DotCell = CustomCell<DotCellData>;
476
+
477
+ const DOT_WORDS: Record<string, string> = {
478
+ "strong": LP_GREEN_DEEP, "low": LP_GREEN_DEEP, "on track": LP_GREEN_DEEP,
479
+ "fair": LP_YELLOW_DEEP, "medium": LP_YELLOW_DEEP, "due this week": LP_YELLOW_DEEP,
480
+ "weak": LP_RED_DEEP, "high": LP_RED_DEEP, "overdue": LP_RED_DEEP,
481
+ "no data": LP_MUTED, "done": LP_MUTED,
482
+ };
483
+
484
+ /** The dot colour for a health or priority word. An unknown word takes the option's deep tint. */
485
+ export function dotColour(field: Field, word: string): string {
486
+ const known = DOT_WORDS[word.trim().toLowerCase()];
487
+ if (known) return known;
488
+ return optionTint(field, word)?.fg ?? LP_MUTED;
489
+ }
490
+
491
+ const DOT_SIZE = 8;
492
+ const DOT_GAP = 6;
493
+
494
+ export const dotCellRenderer: CustomRenderer<DotCell> = {
495
+ kind: GridCellKind.Custom,
496
+ isMatch: (cell): cell is DotCell =>
497
+ (cell.data as DotCellData | undefined)?.kind === "aios-dot",
498
+ draw: (args, cell) => {
499
+ const { ctx, rect, theme } = args;
500
+ const { value, colour } = cell.data;
501
+ if (!value) return true;
502
+ const x = rect.x + theme.cellHorizontalPadding;
503
+ const cy = rect.y + rect.height / 2;
504
+ ctx.save();
505
+ ctx.beginPath();
506
+ ctx.rect(rect.x, rect.y, rect.width, rect.height);
507
+ ctx.clip();
508
+ ctx.beginPath();
509
+ ctx.arc(x + DOT_SIZE / 2, cy, DOT_SIZE / 2, 0, Math.PI * 2);
510
+ ctx.fillStyle = colour;
511
+ ctx.fill();
512
+ ctx.font = theme.baseFontFull;
513
+ ctx.fillStyle = theme.textDark;
514
+ ctx.textBaseline = "middle";
515
+ ctx.textAlign = "left";
516
+ ctx.fillText(value, x + DOT_SIZE + DOT_GAP, cy);
517
+ ctx.restore();
518
+ return true;
519
+ },
520
+ };
521
+
522
  /** Build the cell for one (field, value). `editable` gates overlay + readonly.
523
  *
524
  * ⚠ A BLANK numeric cell renders EMPTY, never "$0" (2026-07-27). `''`/null is how a value that
 
574
  // a fabricated figure on the canvas beside an honest em-dash in the record panel.
575
  const noNumber = numericIsBlank(v);
576
 
577
+ if (field.format?.display === "bar"
578
+ && (field.type === "int" || field.type === "pct" || field.type === "currency")) {
579
+ const n = noNumber ? null : num(v);
580
+ return {
581
+ kind: GridCellKind.Custom,
582
+ data: { kind: "aios-bar", value: n } satisfies BarCellData,
583
+ copyData: n === null ? "" : String(n),
584
+ allowOverlay: false,
585
+ readonly: !editable,
586
+ };
587
+ }
588
+ if (field.format?.display === "dot" && field.type === "select") {
589
+ // Same editing as the select case: the anchored picker opens on click (onCellClicked).
590
+ const s = String(v ?? "");
591
+ return {
592
+ kind: GridCellKind.Custom,
593
+ data: { kind: "aios-dot", value: s, colour: dotColour(field, s) } satisfies DotCellData,
594
+ copyData: s,
595
+ allowOverlay: false,
596
+ };
597
+ }
598
+
599
  switch (field.type) {
600
  case "currency":
601
  return {
 
838
  allowOverlay: false,
839
  };
840
  }
841
+ case "chart": {
842
+ // Module computed and read only. The value is a JSON array, or a real one off the wire.
843
+ const values = chartValues(v as unknown);
844
+ return {
845
+ kind: GridCellKind.Custom,
846
+ data: { kind: "aios-chart", values } satisfies ChartCellData,
847
+ copyData: typeof v === "string" ? v : v == null ? "" : JSON.stringify(v),
848
+ allowOverlay: false,
849
+ readonly: true,
850
+ };
851
+ }
852
  case "rating": {
853
  const max = ratingMax(field);
854
  const n = Math.max(0, Math.min(max, Math.round(num(v))));
 
894
  // string silently reached the clipboard and then the paste path. A count is not data and
895
  // cannot be pasted back into a relation.
896
  const ids = String(v ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
897
+ // `format.linkLabel` names the count ("Projects (0)") and paints at zero, so the cell is clickable.
898
+ const linkLabel = field.format?.linkLabel;
899
+ const named = typeof linkLabel === "string" && linkLabel.trim() !== "";
900
  return {
901
  kind: GridCellKind.Bubble,
902
+ data: named ? [`${linkLabel.trim()} (${ids.length})`]
903
+ : ids.length ? [ids.length === 1 ? "1 record" : `${ids.length} records`] : [],
904
  copyData: String(v ?? ""),
905
  allowOverlay: false,
906
  };
web/src/customer-grid/iconShapes.ts CHANGED
@@ -136,6 +136,8 @@ export const TYPE_SHAPES: Record<FieldType, IconShape[]> = {
136
  { d: "M3.2 3.2v9.6h9.6" },
137
  { d: "M5 10.4l2.4-2.6 1.9 1.5 3.1-3.9" },
138
  ],
 
 
139
  // Wave-23 C7 — TWO BRACES facing each other with a dot between them: the universal mark for
140
  // "a structured document", and the one glyph in this table that draws its own SYNTAX rather
141
  // than a picture of what the value means. Deliberately not a document page (nothing here owns
@@ -756,6 +758,8 @@ export const TYPE_LABELS: Record<FieldType, string> = {
756
  // Wave-22 C7 — spawned by automations (not in CREATABLE_TYPES), so this label mostly shows
757
  // on headers and the field gear, not the create menu.
758
  metric: "Metric",
 
 
759
  // Wave-19 R7 — the picture column.
760
  image: "Image",
761
  // Wave-23 C7 — the structured-document column. "JSON" rather than "Structured data": it is
 
136
  { d: "M3.2 3.2v9.6h9.6" },
137
  { d: "M5 10.4l2.4-2.6 1.9 1.5 3.1-3.9" },
138
  ],
139
+ // A bare series with no axis: the sparkline a chart cell draws.
140
+ chart: [{ d: "M2.8 10.8l2.6-3.2 2.2 1.9 2.6-4.6 3 2.6" }],
141
  // Wave-23 C7 — TWO BRACES facing each other with a dot between them: the universal mark for
142
  // "a structured document", and the one glyph in this table that draws its own SYNTAX rather
143
  // than a picture of what the value means. Deliberately not a document page (nothing here owns
 
758
  // Wave-22 C7 — spawned by automations (not in CREATABLE_TYPES), so this label mostly shows
759
  // on headers and the field gear, not the create menu.
760
  metric: "Metric",
761
+ // Module-computed sparkline; never in the create menu.
762
+ chart: "Trend",
763
  // Wave-19 R7 — the picture column.
764
  image: "Image",
765
  // Wave-23 C7 — the structured-document column. "JSON" rather than "Structured data": it is
web/src/customer-grid/sparklineCell.ts ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * The `chart` field kind: a sparkline drawn from the JSON array of numbers a row carries.
3
+ * The drawing is a port of `sheet/sparkline.ts::drawLine` without the Sheet range plumbing.
4
+ */
5
+ import { GridCellKind } from "@glideapps/glide-data-grid";
6
+ import type { CustomCell, CustomRenderer, Rectangle } from "@glideapps/glide-data-grid";
7
+ import { LP_MUTED, NAVY } from "./theme";
8
+
9
+ /** The margin between the line and the cell's own grid line, in CSS pixels. */
10
+ const INSET = 3;
11
+
12
+ /** Below this a plot box is a smudge, so nothing is drawn. */
13
+ const MIN_SIDE = 6;
14
+
15
+ export interface ChartCellData {
16
+ kind: "aios-chart";
17
+ values: (number | null)[];
18
+ }
19
+ export type ChartCell = CustomCell<ChartCellData>;
20
+
21
+ /** A cell value as a series: a JSON string or a real array. Anything else is an empty series. */
22
+ export function chartValues(raw: unknown): (number | null)[] {
23
+ let parsed: unknown = raw;
24
+ if (typeof raw === "string") {
25
+ const s = raw.trim();
26
+ if (s === "") return [];
27
+ try {
28
+ parsed = JSON.parse(s) as unknown;
29
+ } catch {
30
+ return [];
31
+ }
32
+ }
33
+ if (!Array.isArray(parsed)) return [];
34
+ return parsed.map((v) => {
35
+ if (v === null || v === "" || typeof v === "boolean") return null;
36
+ const n = typeof v === "number" ? v : Number(v);
37
+ return Number.isFinite(n) ? n : null;
38
+ });
39
+ }
40
+
41
+ /** The x centre of reading `i` of `n` across a plot box. One reading sits in the middle. */
42
+ const centreX = (box: Rectangle, i: number, n: number): number =>
43
+ n <= 1 ? box.x + box.width / 2 : box.x + (box.width * i) / (n - 1);
44
+
45
+ /**
46
+ * Draw `values` as a 1.5px line inside `rect` less INSET. A flat series sits on the mid line in
47
+ * LP_MUTED. A null breaks the line. An empty series draws nothing.
48
+ */
49
+ export function drawSparkline(
50
+ ctx: CanvasRenderingContext2D,
51
+ rect: Rectangle,
52
+ values: readonly (number | null)[],
53
+ colour: string = NAVY,
54
+ ): void {
55
+ const box = {
56
+ x: rect.x + INSET,
57
+ y: rect.y + INSET,
58
+ width: rect.width - INSET * 2,
59
+ height: rect.height - INSET * 2,
60
+ };
61
+ if (box.width < MIN_SIDE || box.height < MIN_SIDE) return;
62
+ const present = values.filter((v): v is number => v !== null);
63
+ if (!present.length) return;
64
+ const lo = Math.min(...present);
65
+ const hi = Math.max(...present);
66
+ const span = hi - lo;
67
+ const yOf = (v: number) =>
68
+ span === 0 ? box.y + box.height / 2 : box.y + box.height - ((v - lo) / span) * box.height;
69
+ const stroke = span === 0 ? LP_MUTED : colour;
70
+
71
+ ctx.save();
72
+ ctx.strokeStyle = stroke;
73
+ ctx.lineWidth = 1.5;
74
+ ctx.lineJoin = "round";
75
+ ctx.lineCap = "round";
76
+ ctx.beginPath();
77
+ let open = false;
78
+ values.forEach((v, i) => {
79
+ if (v === null) {
80
+ open = false;
81
+ return;
82
+ }
83
+ const x = centreX(box, i, values.length);
84
+ const y = yOf(v);
85
+ if (open) ctx.lineTo(x, y);
86
+ else ctx.moveTo(x, y);
87
+ open = true;
88
+ });
89
+ ctx.stroke();
90
+
91
+ // A lone reading has no segment to stroke, so it gets a dot.
92
+ if (present.length === 1) {
93
+ const i = values.findIndex((v) => v !== null);
94
+ ctx.fillStyle = stroke;
95
+ ctx.beginPath();
96
+ ctx.arc(centreX(box, i, values.length), yOf(present[0]), 1.5, 0, Math.PI * 2);
97
+ ctx.fill();
98
+ }
99
+ ctx.restore();
100
+ }
101
+
102
+ /** The `chart` cell. Registered once on the DataEditor (customRenderers). */
103
+ export const chartCellRenderer: CustomRenderer<ChartCell> = {
104
+ kind: GridCellKind.Custom,
105
+ isMatch: (cell): cell is ChartCell =>
106
+ (cell.data as ChartCellData | undefined)?.kind === "aios-chart",
107
+ draw: (args, cell) => {
108
+ const { ctx, rect, theme } = args;
109
+ const pad = Math.max(0, theme.cellHorizontalPadding - INSET);
110
+ drawSparkline(
111
+ ctx,
112
+ { x: rect.x + pad, y: rect.y + 4, width: rect.width - pad * 2, height: rect.height - 8 },
113
+ cell.data.values,
114
+ );
115
+ return true;
116
+ },
117
+ };
web/src/customer-grid/types.ts CHANGED
@@ -90,7 +90,10 @@ export type FieldType =
90
  // over it, and doing so permanently protects that cell from every automatic run, so it is
91
  // deliberately NOT in `READONLY_CELL_TYPES`. Its config lives in `Field.aiEnrich`.
92
  | "ai_enrich" | "if" | "autonumber"
93
- | "created_by" | "last_modified_time" | "last_modified_by";
 
 
 
94
 
95
  /**
96
  * ⭐⭐ WAVE-34 (owner ruling R13) — WHOSE VALUE IS IN THIS ENRICHMENT CELL.
@@ -238,6 +241,10 @@ export const CREATABLE_TYPES: readonly FieldType[] = [
238
  // that can ever produce a value here. So `ColumnMenu.canCreate` gates on it, or the create
239
  // button is the "created, named, configured, gone" failure arriving one door earlier.
240
  "ai_enrich",
 
 
 
 
241
  ];
242
 
243
  /**
@@ -317,6 +324,7 @@ export const TYPE_DESCRIPTIONS: Record<
317
  link: "Points at rows of another database, so this row can reach them.",
318
  rollup: "Folds many records into one value: linked rows, or a live topic matched on a column.",
319
  if: "The result of the first matching condition.",
 
320
  measure: "A business number this workspace already publishes, over a period you pick.",
321
  geocode: "Latitude and longitude, read from an address column of this database.",
322
  count: "How many records this row links to. A rollup, with the folding already chosen.",
@@ -330,7 +338,11 @@ export const AUDIT_FIELD_TYPES: readonly FieldType[] = [
330
  "created_by", "last_modified_time", "last_modified_by",
331
  ];
332
 
 
 
 
333
  export function offerableCreateKind(value: string, isUserTable: boolean): boolean {
 
334
  if (value === "autonumber" && !isUserTable) return false;
335
  if (AUDIT_FIELD_TYPES.some((type) => type === value) && !isUserTable) return false;
336
  return !isUserTable || !UT_UNSUPPORTED_CREATE_KINDS.includes(value);
@@ -417,7 +429,7 @@ export const READONLY_CELL_TYPES: ReadonlySet<FieldType> = new Set<FieldType>([
417
  // relation a person builds by picking records. Only a DERIVED link is read-only, which is a
418
  // question about ONE FIELD's bag and not about its type — `mayEditField` asks
419
  // `isDerivedLink` for exactly that reason. A type set cannot express "read-only in one mode".
420
- "formula", "created_time", "automation", "metric", "rollup", "if", "autonumber",
421
  ...AUDIT_FIELD_TYPES,
422
  ]);
423
 
@@ -547,6 +559,23 @@ export interface FieldFormat {
547
  time?: boolean;
548
  /** date/created_time: which clock to display in. Absent = 'local'. */
549
  tz?: "local" | "utc";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  }
551
 
552
  /** The declared choices of a select/multiselect, [] when absent. */
 
90
  // over it, and doing so permanently protects that cell from every automatic run, so it is
91
  // deliberately NOT in `READONLY_CELL_TYPES`. Its config lives in `Field.aiEnrich`.
92
  | "ai_enrich" | "if" | "autonumber"
93
+ | "created_by" | "last_modified_time" | "last_modified_by"
94
+ // `chart` is a module-computed sparkline: the cell holds a JSON array of numbers. Read only,
95
+ // never creatable, not numeric, not groupable. Filter and sort treat it as `json` does.
96
+ | "chart";
97
 
98
  /**
99
  * ⭐⭐ WAVE-34 (owner ruling R13) — WHOSE VALUE IS IN THIS ENRICHMENT CELL.
 
241
  // that can ever produce a value here. So `ColumnMenu.canCreate` gates on it, or the create
242
  // button is the "created, named, configured, gone" failure arriving one door earlier.
243
  "ai_enrich",
244
+ // `chart` is listed only because three gates chain this list to the server's sets
245
+ // (CREATABLE == CUSTOM_FIELD_TYPES, UT_FIELD_TYPES within CUSTOM). It is module computed:
246
+ // `offerableCreateKind` withholds it from the create and retype pickers on every surface.
247
+ "chart",
248
  ];
249
 
250
  /**
 
324
  link: "Points at rows of another database, so this row can reach them.",
325
  rollup: "Folds many records into one value: linked rows, or a live topic matched on a column.",
326
  if: "The result of the first matching condition.",
327
+ chart: "A small trend line, computed for you.",
328
  measure: "A business number this workspace already publishes, over a period you pick.",
329
  geocode: "Latitude and longitude, read from an address column of this database.",
330
  count: "How many records this row links to. A rollup, with the folding already chosen.",
 
338
  "created_by", "last_modified_time", "last_modified_by",
339
  ];
340
 
341
+ /** Kinds a module computes. The server needs them in its sets; no picker ever offers them. */
342
+ export const MODULE_ONLY_KINDS: readonly string[] = ["chart"];
343
+
344
  export function offerableCreateKind(value: string, isUserTable: boolean): boolean {
345
+ if (MODULE_ONLY_KINDS.includes(value)) return false;
346
  if (value === "autonumber" && !isUserTable) return false;
347
  if (AUDIT_FIELD_TYPES.some((type) => type === value) && !isUserTable) return false;
348
  return !isUserTable || !UT_UNSUPPORTED_CREATE_KINDS.includes(value);
 
429
  // relation a person builds by picking records. Only a DERIVED link is read-only, which is a
430
  // question about ONE FIELD's bag and not about its type — `mayEditField` asks
431
  // `isDerivedLink` for exactly that reason. A type set cannot express "read-only in one mode".
432
+ "formula", "created_time", "automation", "metric", "rollup", "if", "autonumber", "chart",
433
  ...AUDIT_FIELD_TYPES,
434
  ]);
435
 
 
559
  time?: boolean;
560
  /** date/created_time: which clock to display in. Absent = 'local'. */
561
  tz?: "local" | "utc";
562
+ /** int/pct/currency: "bar" draws a 0..100 score bar. select: "dot" draws a dot plus the word. */
563
+ display?: "bar" | "dot";
564
+ /** link: the cell reads "<linkLabel> (N)" and stays clickable at N = 0. 1..40 chars. */
565
+ linkLabel?: string;
566
+ /** link: the label of the popup's add button. 1..40 chars, default "Add". */
567
+ addLabel?: string;
568
+ /** link: the row the popup's add button creates in the linked table. Set by the server. */
569
+ seed?: LinkSeed;
570
+ }
571
+
572
+ /** A link popup's add recipe: copy `currentRow[keyFrom]` into `keyField`, then POST `relink`. */
573
+ export interface LinkSeed {
574
+ keyFrom: string;
575
+ keyField: string;
576
+ values: Record<string, string>;
577
+ titleField: string;
578
+ relink: string;
579
  }
580
 
581
  /** The declared choices of a select/multiselect, [] when absent. */
web/src/settings/permsModel.ts CHANGED
@@ -506,6 +506,8 @@ const FIELD_TYPE_TABLE: Record<FieldType, true> = {
506
  ai_enrich: true,
507
  // S74-T23: an If field is granted and hidden like any other computed column.
508
  if: true,
 
 
509
  };
510
 
511
  export const KNOWN_FIELD_TYPES: ReadonlySet<string> = new Set(Object.keys(FIELD_TYPE_TABLE));
 
506
  ai_enrich: true,
507
  // S74-T23: an If field is granted and hidden like any other computed column.
508
  if: true,
509
+ // Module-computed sparkline, granted and hidden like any other column.
510
+ chart: true,
511
  };
512
 
513
  export const KNOWN_FIELD_TYPES: ReadonlySet<string> = new Set(Object.keys(FIELD_TYPE_TABLE));
web/src/viz/types.ts CHANGED
@@ -84,7 +84,9 @@ export type FieldType =
84
  // S74-T23 - the If statement kind, categorical like ai_enrich, so the grid can hand it to charts
85
  | "if"
86
  // S76 combine - the five kinds lane G added to the grid union, so GridFieldFitsViz holds
87
- | "long_text" | "autonumber" | "created_by" | "last_modified_time" | "last_modified_by";
 
 
88
 
89
  export type FieldSource = "odoo" | "overlay";
90
 
 
84
  // S74-T23 - the If statement kind, categorical like ai_enrich, so the grid can hand it to charts
85
  | "if"
86
  // S76 combine - the five kinds lane G added to the grid union, so GridFieldFitsViz holds
87
+ | "long_text" | "autonumber" | "created_by" | "last_modified_time" | "last_modified_by"
88
+ // H3 - the module-computed sparkline kind, categorical, so GridFieldFitsViz holds
89
+ | "chart";
90
 
91
  export type FieldSource = "odoo" | "overlay";
92