fsanyoto commited on
Commit
f7e34ed
Β·
verified Β·
1 Parent(s): 13e5577

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "caf2c2e",
3
  "releases": [
4
  {
5
  "version": "v29",
 
1
  {
2
+ "current": "4540dfb",
3
  "releases": [
4
  {
5
  "version": "v29",
VERSION CHANGED
@@ -1 +1 @@
1
- caf2c2e
 
1
+ 4540dfb
platform/aios_grid_fields.json CHANGED
@@ -450,12 +450,19 @@
450
  "source": "odoo",
451
  "description": "Units sold in the last twelve months. Consolidated; absent for a BU-scoped caller."
452
  },
 
 
 
 
 
 
 
453
  {
454
  "key": "dos",
455
  "label": "Days of supply",
456
  "type": "int",
457
  "source": "odoo",
458
- "description": "Days of supply at the LTM rate; null means it never sells through. Consolidated; absent for a BU-scoped caller."
459
  },
460
  {
461
  "key": "cover_gap_d",
@@ -463,7 +470,22 @@
463
  "type": "int",
464
  "source": "odoo",
465
  "default": false,
466
- "description": "Days of supply minus lead time. Negative means it runs out before a reorder lands."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  },
468
  {
469
  "key": "stock_bucket",
@@ -472,6 +494,17 @@
472
  "source": "odoo",
473
  "description": "Dead / excess / healthy bucket from the inventory module. Consolidated; absent for a BU-scoped caller."
474
  },
 
 
 
 
 
 
 
 
 
 
 
475
  {
476
  "key": "needs_pricing",
477
  "label": "Needs pricing",
 
450
  "source": "odoo",
451
  "description": "Units sold in the last twelve months. Consolidated; absent for a BU-scoped caller."
452
  },
453
+ {
454
+ "key": "incoming",
455
+ "label": "Inbound units",
456
+ "type": "int",
457
+ "source": "odoo",
458
+ "description": "Units already on order and not yet received, from Odoo's own incoming quantity on the product. In the product's STOCK unit of measure, the same unit as On hand, so the two can be added. Both cover gap columns count this as stock."
459
+ },
460
  {
461
  "key": "dos",
462
  "label": "Days of supply",
463
  "type": "int",
464
  "source": "odoo",
465
+ "description": "Days of supply at the LTM rate, from ON-HAND stock only; null means it never sells through. It deliberately IGNORES inbound units, because dead stock and overstock are questions about what is on the shelf. The cover gap columns are the ones that count inbound. Consolidated; absent for a BU-scoped caller."
466
  },
467
  {
468
  "key": "cover_gap_d",
 
470
  "type": "int",
471
  "source": "odoo",
472
  "default": false,
473
+ "description": "Days of cover minus supplier lead time. Negative means it runs out before a reorder lands. Two things it counts that Days of supply does not (owner, 2026-08-19): INBOUND units count as stock, and the burn rate is the FORWARD 8 month forecast rather than the trailing twelve month average."
474
+ },
475
+ {
476
+ "key": "cover_gap_units",
477
+ "label": "Cover gap (units)",
478
+ "type": "int",
479
+ "source": "odoo",
480
+ "default": false,
481
+ "description": "The recommended reorder quantity: units of forecast demand over the lead time that on-hand plus inbound does not cover. POSITIVE means buy this many; negative is surplus units; blank means we cannot say, because the SKU has no lead time on file or no forecast demand. Rounded AWAY from zero, so a real shortfall never rounds down to nothing."
482
+ },
483
+ {
484
+ "key": "demand_fwd",
485
+ "label": "Forecast units (8 mo)",
486
+ "type": "int",
487
+ "source": "odoo",
488
+ "description": "Units this SKU is expected to sell over the next 8 months, read as the units it actually sold in the same 8 calendar months one year ago. Seasonal on purpose: a flat annual average spreads Valentine's, Mother's Day and Christmas evenly across the year and understates the months buyers actually order for. A SKU too new to appear in that window falls back to its trailing twelve month rate scaled to 8 months. This is the burn rate both cover gap columns divide by, shown so the reorder quantity can be checked."
489
  },
490
  {
491
  "key": "stock_bucket",
 
494
  "source": "odoo",
495
  "description": "Dead / excess / healthy bucket from the inventory module. Consolidated; absent for a BU-scoped caller."
496
  },
497
+ {
498
+ "key": "discontinued",
499
+ "label": "Discontinued",
500
+ "type": "select",
501
+ "source": "odoo",
502
+ "options": [
503
+ "Yes",
504
+ "No"
505
+ ],
506
+ "description": "Whether Odoo carries the Discontinued product tag on this SKU. Every row gets an explicit Yes or No rather than a blank, because a blank reads as an inactive condition in the filter engine and would silently WIDEN any view that filtered on it."
507
+ },
508
  {
509
  "key": "needs_pricing",
510
  "label": "Needs pricing",
platform/core/odoo.py CHANGED
@@ -264,12 +264,34 @@ def excluded_partner_ids():
264
  return res
265
 
266
 
267
- def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, partner_ids=None):
 
268
  """Build a sale.order.line domain in the RI+FFS confirmed-order scope, excluding
269
  the configured house accounts, with optional date window / single team / extra clauses.
270
  partner_ids (a collection, possibly empty) restricts to those customers β€” the carrier for
271
- the Customer module's Agent filter; None = no partner restriction (an empty set matches none)."""
272
- tids = active_team_ids()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  dom = [('state', 'in', ['sale', 'done']), ('product_id', '!=', False)]
274
  if tids:
275
  dom.insert(1, ('order_id.team_id', 'in', tids))
@@ -280,7 +302,7 @@ def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, par
280
  dom.append(('order_id.date_order', '>=', f'{date_from} 00:00:00'))
281
  if date_to:
282
  dom.append(('order_id.date_order', '<=', f'{date_to} 23:59:59'))
283
- ex = excluded_partner_ids()
284
  if ex:
285
  dom.append(('order_partner_id', 'not in', list(ex)))
286
  if partner_ids is not None:
 
264
  return res
265
 
266
 
267
+ def sale_line_domain(date_from=None, date_to=None, team_id=None, extra=None, partner_ids=None,
268
+ all_channels=False):
269
  """Build a sale.order.line domain in the RI+FFS confirmed-order scope, excluding
270
  the configured house accounts, with optional date window / single team / extra clauses.
271
  partner_ids (a collection, possibly empty) restricts to those customers β€” the carrier for
272
+ the Customer module's Agent filter; None = no partner restriction (an empty set matches none).
273
+
274
+ ⭐⭐ `all_channels=True` DROPS THE WHOLESALE FENCE, and exists for exactly one class of
275
+ question: how much stock to BUY. Owner, 2026-08-19: *"for the Cover gap we need to include
276
+ Amazon SKUs as well ... Amazon units sold through Giftware deals client"*. Those units leave
277
+ the same warehouse, so a buy quantity computed without them under-orders every SKU Amazon
278
+ moves. The default fence is right for revenue, margin and customer analysis and is unchanged.
279
+ ⚠ This is not a new policy: the standing scope rule already reads *"inventory/SKU/dead-stock
280
+ analysis uses ALL channels"*. It is the first caller that needed a way to say so in code.
281
+
282
+ β›”β›” IT TAKES **TWO** FENCES DOWN, AND MISSING THE SECOND MAKES THIS FLAG A SILENT NO-OP.
283
+ MEASURED 2026-08-19: dropping only the excluded-partner clause changed the answer by ZERO
284
+ units, because GIFTWARE DEALS is not gated by the partner list at all in practice β€” its orders
285
+ sit on **`crm.team` 7 ('Giftware Deals')** while `active_team_ids()` is `[5 Fisch, 6 Royal]`,
286
+ so the TEAM clause was already excluding them and the partner clause never bit. In the
287
+ forecast window that is **3,794 lines on team 7 against 0 on the active teams**. So this drops
288
+ the team restriction as well.
289
+ ⚠ AN EXPLICIT `team_id` STILL WINS. A BU-scoped caller asked about ONE unit and must keep
290
+ getting that unit; only a consolidated read widens.
291
+ β›” OPT-IN, never the default: flipping the default would silently widen revenue everywhere."""
292
+ # β›” `all_channels` suppresses the ACTIVE-TEAM fence, which is the one that actually excludes
293
+ # the Amazon channel (crm.team 7). An explicit `team_id` below still overrides either way.
294
+ tids = () if all_channels else active_team_ids()
295
  dom = [('state', 'in', ['sale', 'done']), ('product_id', '!=', False)]
296
  if tids:
297
  dom.insert(1, ('order_id.team_id', 'in', tids))
 
302
  dom.append(('order_id.date_order', '>=', f'{date_from} 00:00:00'))
303
  if date_to:
304
  dom.append(('order_id.date_order', '<=', f'{date_to} 23:59:59'))
305
+ ex = () if all_channels else excluded_partner_ids()
306
  if ex:
307
  dom.append(('order_partner_id', 'not in', list(ex)))
308
  if partner_ids is not None:
platform/modules/product_data.py CHANGED
@@ -52,6 +52,7 @@ template and this deliberately mirrors its signature and its row shape.
52
  sources are JOINED rather than merged.
53
  """
54
  import json
 
55
  import zlib
56
  from pathlib import Path
57
 
@@ -392,6 +393,14 @@ def pool(team_id=None, t=None):
392
  sup = supplier_master()
393
  prices, _price_report = _pricelist_by_code()
394
  cat = _catalogue_by_code()
 
 
 
 
 
 
 
 
395
  # The LEFT side of the join, indexed by the same code key. β›” A code here that the catalogue
396
  # does not carry belongs to a product no ACTIVE record claims β€” archived, and R12 keeps those
397
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
@@ -410,6 +419,12 @@ def pool(team_id=None, t=None):
410
  # SKU that is not re-SKUed. `directory()` derives the category identically.
411
  "product": meta.get("product") or code,
412
  "category": meta.get("category") or "(uncategorized)",
 
 
 
 
 
 
413
  # ⭐⭐ W33-T43 (R2 / amendment A2) β€” ODOO'S OWN PRODUCT ID, beside the hashed `pid`.
414
  # R2 retires `ut_odoo_products` onto this key and keeps every data column it had; this
415
  # is that column. β›” NOT DERIVABLE DOWNSTREAM: `pid` is `crc32(default_code)` here,
@@ -484,11 +499,60 @@ def pool(team_id=None, t=None):
484
  # "does the shelf outlast a reorder AT FISCH'S RATE" β€” reading the consolidated figure
485
  # here would print a buy signal computed from both units' velocity beside a days-of-supply
486
  # computed from one, and the two columns would disagree on the same row.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  lead = s.get("lead_days")
488
- if isinstance(dos, (int, float)) and isinstance(lead, (int, float)) and lead > 0:
489
- row["cover_gap_d"] = int(round(dos - lead))
490
- row["buy_now"] = "Buy now" if dos < lead else "OK"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  else:
 
492
  row["cover_gap_d"] = None
493
  row["buy_now"] = None
494
  rows.append(row)
@@ -521,7 +585,19 @@ def pool(team_id=None, t=None):
521
  #: which is the difference between this and a filter engine's `toNum(null) === 0`;
522
  #: Β· `IF` with a non-boolean condition returns BLANK ("no truthiness"), so a blank comparison
523
  #: propagates out as a blank cell rather than taking the false branch.
524
- BUY_SIGNAL_FORMULA = 'IF({lead_days} > 0, IF({dos} < {lead_days}, "Buy now", "OK"), "")'
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
 
527
  def _buy_signal_formula(row):
@@ -533,14 +609,10 @@ def _buy_signal_formula(row):
533
  return None
534
  return v if v == v and v not in (float('inf'), float('-inf')) else None
535
 
536
- lead, dos = num(row.get("lead_days")), num(row.get("dos"))
537
- if lead is None: # `{lead_days} > 0` is blank -> IF(blank, …) is blank
538
  return ""
539
- if not lead > 0:
540
- return "" # the formula's own else-branch
541
- if dos is None: # `{dos} < {lead_days}` is blank -> IF(blank, …) is blank
542
- return ""
543
- return "Buy now" if dos < lead else "OK"
544
 
545
 
546
  def validate(team_id=None, t=None):
@@ -735,12 +807,14 @@ def validate(team_id=None, t=None):
735
  buy = [r for r in rows if r.get("buy_now") == "Buy now"]
736
  ok_rows = [r for r in rows if r.get("buy_now") == "OK"]
737
  blank = [r for r in rows if r.get("buy_now") is None]
738
- mis = sum(1 for r in buy if not (r["dos"] < r["lead_days"]))
739
- mis += sum(1 for r in ok_rows if not (r["dos"] >= r["lead_days"]))
 
 
 
 
740
  # A blank must be UNKNOWN β€” never a row we could have answered and quietly did not.
741
- mis += sum(1 for r in blank
742
- if isinstance(r.get("dos"), (int, float))
743
- and isinstance(r.get("lead_days"), (int, float)) and r["lead_days"] > 0)
744
  checks.append({
745
  "check": "Buy signal partitions the catalogue (buy + ok + unknown == rows, none "
746
  "misclassified)",
@@ -769,36 +843,142 @@ def validate(team_id=None, t=None):
769
  if (r.get("buy_now") or "") != _buy_signal_formula(r))
770
  checks.append({
771
  "check": 'Buy signal as a FORMULA field == the retired preset column, per SKU '
772
- '(IF({lead_days} > 0, IF({dos} < {lead_days}, "Buy now", "OK"), ""))',
773
  "ours": len(rows) - len(disagree), "theirs": len(rows),
774
  "ok": not disagree,
775
  "detail": {"disagreeing_skus": disagree[:10], "n_disagree": len(disagree)},
776
  })
777
- # The other half of "the same figures": the SHARED Buy list view can no longer filter on
778
- # the retired column, and its replacement conditions must select the same SKUs. They are
779
- # `dos isNotEmpty AND lead_days isNotEmpty AND lead_days > 0 AND dos < lead_days`
780
  # (_seed_wave17.views), so this reproduces exactly that conjunction.
781
  #
782
- # β›” THE NEGATIVE CONTROL IS WHY THIS IS NOT `cover_gap_d < 0`, which reads like the
783
- # obvious filter and is WRONG: `cover_gap_d` is `int(round(dos - lead))`, so a genuine
784
- # gap of -0.4 days rounds to 0 and that SKU drops off a buy list it belongs on.
 
 
 
 
 
 
 
 
 
785
  view_rows = {r["code"] for r in rows
786
- if isinstance(r.get("dos"), (int, float))
787
- and isinstance(r.get("lead_days"), (int, float))
788
- and r["lead_days"] > 0 and r["dos"] < r["lead_days"]}
789
- signal_rows = {r["code"] for r in buy}
790
- rounding_would_miss = sorted(
791
- c for c in signal_rows
792
- if next((r for r in rows if r["code"] == c), {}).get("cover_gap_d") == 0)
793
  checks.append({
794
- "check": "Buy list view conditions (dos/lead_days, no retired column) select "
795
- "exactly the Buy-now SKUs",
796
  "ours": len(view_rows), "theirs": len(signal_rows),
797
  "ok": view_rows == signal_rows,
798
  "detail": {"only_in_view": sorted(view_rows - signal_rows)[:10],
799
- "only_in_signal": sorted(signal_rows - view_rows)[:10],
800
- # Reported, not asserted: how many SKUs a `cover_gap_d < 0` filter would
801
- # have silently dropped. 0 today does not make that filter correct.
802
- "cover_gap_rounds_to_zero": len(rounding_would_miss)},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
803
  })
804
  return checks
 
52
  sources are JOINED rather than merged.
53
  """
54
  import json
55
+ import math as _math
56
  import zlib
57
  from pathlib import Path
58
 
 
393
  sup = supplier_master()
394
  prices, _price_report = _pricelist_by_code()
395
  cat = _catalogue_by_code()
396
+ # ⭐ THE BUY LIST'S DEMAND HORIZON (owner ruling 2026-08-19). BU-shaped through `team_id`, the
397
+ # same way the revenue columns are: a Fisch reader's reorder quantity must answer what FISCH
398
+ # will sell. Degrades to `{}` on a read failure, matching every other column source here β€” a
399
+ # blank cover gap is honest, a product grid that will not render is not.
400
+ try:
401
+ fwd_demand, _fwd_report = products.forward_demand_by_code(t=t, team_id=team_id)
402
+ except Exception: # noqa: BLE001
403
+ fwd_demand, _fwd_report = {}, {"error": "forward demand unavailable"}
404
  # The LEFT side of the join, indexed by the same code key. β›” A code here that the catalogue
405
  # does not carry belongs to a product no ACTIVE record claims β€” archived, and R12 keeps those
406
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
 
419
  # SKU that is not re-SKUed. `directory()` derives the category identically.
420
  "product": meta.get("product") or code,
421
  "category": meta.get("category") or "(uncategorized)",
422
+ # ⭐⭐ OWNER 2026-08-19 β€” the Odoo Discontinued tag, surfaced so the buy list can drop
423
+ # them. β›” ALWAYS "Yes" OR "No", NEVER BLANK: an unknown value is an INACTIVE condition
424
+ # in the tri-state filter engine, so a view filtering on a blank column IGNORES the
425
+ # leaf and WIDENS to the whole catalogue. That is the exact failure `_seed_wave17`'s
426
+ # buy-list comment was written about, and a blank here would reintroduce it.
427
+ "discontinued": meta.get("discontinued") or "No",
428
  # ⭐⭐ W33-T43 (R2 / amendment A2) β€” ODOO'S OWN PRODUCT ID, beside the hashed `pid`.
429
  # R2 retires `ut_odoo_products` onto this key and keeps every data column it had; this
430
  # is that column. β›” NOT DERIVABLE DOWNSTREAM: `pid` is `crc32(default_code)` here,
 
499
  # "does the shelf outlast a reorder AT FISCH'S RATE" β€” reading the consolidated figure
500
  # here would print a buy signal computed from both units' velocity beside a days-of-supply
501
  # computed from one, and the two columns would disagree on the same row.
502
+ # ⭐⭐ OWNER 2026-08-19 β€” INBOUND COUNTS AS STOCK FOR THE COVER GAP. Verbatim: *"Cover gap
503
+ # day also should INCLUDE the incoming SKUs so it assumes those as stock even though its
504
+ # inbound"*, and *"we need the 'Cover gap (units)' basically tell us how much to buy"*.
505
+ #
506
+ # β›” `dos` AND `stock_bucket` DELIBERATELY DO NOT MOVE. They answer "what is on the shelf",
507
+ # which is the question dead-stock, excess and overstock are built on; folding inbound into
508
+ # them would change the Inventory module's meaning from a buy-list request. So a row can
509
+ # honestly read `dos 5, lead 30, cover gap +12` when 900 units are on the water, and the
510
+ # two columns' own descriptions say which is which.
511
+ #
512
+ # ⭐⭐ THE VELOCITY BASIS IS FORWARD 8 MONTHS (owner ruling, 2026-08-19). The owner
513
+ # described the cover gap as *"based on the next 8 months Unit sales"*; it was a TRAILING
514
+ # twelve-month rate, and asked to choose, they ruled forward. `products.forward_demand_by_
515
+ # code` is a SEASONAL read (the same 8 calendar months a year ago), which matters for a
516
+ # floral wholesaler whose year is Valentine's, Mother's Day and Christmas: a flat LTM rate
517
+ # spreads those peaks evenly and understates exactly the months a buyer is ordering for.
518
+ #
519
+ # β›” `dos` STILL USES THE LTM RATE, and the difference is deliberate rather than an
520
+ # oversight. `dos` and `stock_bucket` feed dead-stock and overstock, which ask "how long
521
+ # will what is on the shelf last at the rate it has been moving" β€” a backward-looking
522
+ # question. The cover gap asks "will it last until the reorder lands", which is forward.
523
+ # Both columns say which basis they use in their own descriptions.
524
  lead = s.get("lead_days")
525
+ # ⚠ FROM THE CATALOGUE ROW (`meta`), NOT THE INVENTORY ROW (`e`). Both live on this SKU
526
+ # and only one of them was read from Odoo's product record.
527
+ incoming = meta.get("incoming")
528
+ row["incoming"] = incoming
529
+ fwd = fwd_demand.get(code)
530
+ row["demand_fwd"] = round(fwd) if isinstance(fwd, (int, float)) and fwd > 0 else None
531
+ daily = (fwd / float(products.FORWARD_DAYS)) if isinstance(fwd, (int, float)) \
532
+ and fwd > 0 else None
533
+ on_shelf = row["on_hand"]
534
+ effective = ((on_shelf or 0.0) + (incoming or 0.0)
535
+ if isinstance(on_shelf, (int, float)) else None)
536
+ if daily and isinstance(effective, (int, float)) and isinstance(lead, (int, float)) \
537
+ and lead > 0:
538
+ # Units of demand the lead time will consume, less everything we already hold or have
539
+ # bought. POSITIVE is a shortfall to buy; negative is surplus. Signed on purpose: a
540
+ # floor at zero would make the buy-list filter depend on the floor rather than on the
541
+ # measurement, and would flatten "covered by 2 units" into "covered by 400".
542
+ short = daily * lead - effective
543
+ # β›” AWAY FROM ZERO, NEVER `round()`. `cover_gap_d` is `int(round(...))` and the seed's
544
+ # own comment records why that makes it unsafe to SELECT on: a real gap of -0.4 days
545
+ # rounds to 0 and the SKU drops off a list it belongs on. A shortfall of 0.4 units is
546
+ # still a shortfall, so it must land on 1, not 0. `validate()` holds this on the
547
+ # boundary rather than trusting the expression.
548
+ row["cover_gap_units"] = int(_math.ceil(short) if short > 0 else _math.floor(short))
549
+ row["cover_gap_d"] = int(round(effective / daily - lead))
550
+ # ⭐ THE SIGNAL IS NOW A FUNCTION OF THE SAME NUMBER THE COLUMN SHOWS, so the words and
551
+ # the quantity on one row can no longer disagree β€” which they would have the moment
552
+ # the gap started counting inbound and the signal did not.
553
+ row["buy_now"] = "Buy now" if row["cover_gap_units"] > 0 else "OK"
554
  else:
555
+ row["cover_gap_units"] = None
556
  row["cover_gap_d"] = None
557
  row["buy_now"] = None
558
  rows.append(row)
 
585
  #: which is the difference between this and a filter engine's `toNum(null) === 0`;
586
  #: Β· `IF` with a non-boolean condition returns BLANK ("no truthiness"), so a blank comparison
587
  #: propagates out as a blank cell rather than taking the false branch.
588
+ #: ⭐⭐ REPOINTED 2026-08-19 ONTO `cover_gap_units`, AND THE REASON IS THE OWNER'S OWN INSTRUCTION.
589
+ #: The old formula was `IF({lead_days} > 0, IF({dos} < {lead_days}, "Buy now", "OK"), "")`. Once
590
+ #: the cover gap counts inbound stock, `{dos} < {lead_days}` is no longer the same question: it
591
+ #: would keep saying "Buy now" for a SKU whose replenishment is already on the water, which is the
592
+ #: shape of confusion the owner opened this work with. `cover_gap_units` already carries the whole
593
+ #: rule β€” lead time present and positive, velocity known, inbound counted, rounded away from zero
594
+ #: β€” so one reference replaces three and the words cannot disagree with the number beside them.
595
+ #:
596
+ #: ⚠ ONE ENGINE BEHAVIOUR CARRIES THE BLANK CASE, and it is why no `isNotEmpty` guard is needed:
597
+ #: `cmp` returns BLANK unless BOTH sides read as numbers, and `IF` with a non-boolean condition
598
+ #: returns BLANK. So a SKU with no lead time or no sell-through has `cover_gap_units = null`, the
599
+ #: comparison is blank, and the cell is blank β€” never the false branch, and never a coerced 0.
600
+ BUY_SIGNAL_FORMULA = 'IF({cover_gap_units} > 0, "Buy now", "OK")'
601
 
602
 
603
  def _buy_signal_formula(row):
 
609
  return None
610
  return v if v == v and v not in (float('inf'), float('-inf')) else None
611
 
612
+ gap = num(row.get("cover_gap_units"))
613
+ if gap is None: # `{cover_gap_units} > 0` is blank -> IF(blank, …) is blank
614
  return ""
615
+ return "Buy now" if gap > 0 else "OK"
 
 
 
 
616
 
617
 
618
  def validate(team_id=None, t=None):
 
807
  buy = [r for r in rows if r.get("buy_now") == "Buy now"]
808
  ok_rows = [r for r in rows if r.get("buy_now") == "OK"]
809
  blank = [r for r in rows if r.get("buy_now") is None]
810
+ # ⚠ RE-DERIVED FROM `cover_gap_units`, NOT FROM `dos < lead_days`, SINCE 2026-08-19. The
811
+ # signal counts inbound stock now; the old predicate does not, so leaving it here made the
812
+ # check disagree with the column on **796 rows** β€” every SKU with an open purchase order.
813
+ # It was the check that was stale, and it caught the definition move exactly as intended.
814
+ mis = sum(1 for r in buy if not (r["cover_gap_units"] > 0))
815
+ mis += sum(1 for r in ok_rows if not (r["cover_gap_units"] <= 0))
816
  # A blank must be UNKNOWN β€” never a row we could have answered and quietly did not.
817
+ mis += sum(1 for r in blank if isinstance(r.get("cover_gap_units"), (int, float)))
 
 
818
  checks.append({
819
  "check": "Buy signal partitions the catalogue (buy + ok + unknown == rows, none "
820
  "misclassified)",
 
843
  if (r.get("buy_now") or "") != _buy_signal_formula(r))
844
  checks.append({
845
  "check": 'Buy signal as a FORMULA field == the retired preset column, per SKU '
846
+ '(' + BUY_SIGNAL_FORMULA + ')',
847
  "ours": len(rows) - len(disagree), "theirs": len(rows),
848
  "ok": not disagree,
849
  "detail": {"disagreeing_skus": disagree[:10], "n_disagree": len(disagree)},
850
  })
851
+ # The other half of "the same figures": the SHARED Buy list view's conditions must select
852
+ # exactly the Buy-now SKUs. They are `discontinued neq Yes AND cover_gap_units gt 0`
 
853
  # (_seed_wave17.views), so this reproduces exactly that conjunction.
854
  #
855
+ # ⭐⭐ THE FOUR-LEAF CONJUNCTION COLLAPSED TO TWO ON 2026-08-19, and the guard the old
856
+ # leaves provided is now STRUCTURAL rather than spelled out. The two `isNotEmpty` leaves
857
+ # existed because the client filter engine's `toNum(null)` is **0**, so a bare
858
+ # `dos < lead_days` read a SKU with no days-of-supply as `0 < 30` = TRUE and put every
859
+ # never-selling product on the buy list. `cover_gap_units > 0` inverts that accident into
860
+ # a safety: a blank reads as 0, and `0 > 0` is FALSE, so an unknown SKU is EXCLUDED. The
861
+ # filter now fails CLOSED on exactly the rows the old one failed OPEN on.
862
+ #
863
+ # β›” AND THE ROUNDING TRAP IS THE REASON IT IS NOT `cover_gap_d < 0`. That column is
864
+ # `int(round(...))`, so a real gap of -0.4 days rounds to 0 and the SKU silently drops off
865
+ # a list it belongs on. `cover_gap_units` rounds AWAY from zero for that reason, and the
866
+ # boundary control below proves it on the rows where the two disagree.
867
  view_rows = {r["code"] for r in rows
868
+ if (r.get("discontinued") or "") != "Yes"
869
+ and isinstance(r.get("cover_gap_units"), (int, float))
870
+ and r["cover_gap_units"] > 0}
871
+ signal_rows = {r["code"] for r in buy if (r.get("discontinued") or "") != "Yes"}
 
 
 
872
  checks.append({
873
+ "check": "Buy list view conditions (discontinued neq Yes AND cover_gap_units gt 0) "
874
+ "select exactly the Buy-now SKUs that are not discontinued",
875
  "ours": len(view_rows), "theirs": len(signal_rows),
876
  "ok": view_rows == signal_rows,
877
  "detail": {"only_in_view": sorted(view_rows - signal_rows)[:10],
878
+ "only_in_signal": sorted(signal_rows - view_rows)[:10]},
879
+ })
880
+
881
+ # οΏ½οΏ½οΏ½β›” THE BOUNDARY CONTROL, and it is the single check that proves the collapse above did
882
+ # not silently SHRINK the list. It re-derives the rows where `cover_gap_d` rounds to 0 but
883
+ # the true gap is negative β€” precisely the SKUs the old comment warned a `cover_gap_d < 0`
884
+ # filter would lose β€” and asserts every one of them is still selected by the new predicate.
885
+ # A SKU short by 0.4 days of demand must produce `cover_gap_units >= 1`, not 0.
886
+ # ⚠ DISCONTINUED ROWS ARE OUT OF THIS POPULATION, and finding that out is why the control
887
+ # is written as a control. Its first run went RED naming SKU `15001`, which is a genuine
888
+ # sub-one-day shortfall AND carries Odoo's Discontinued tag: correctly absent from the buy
889
+ # list, for the other reason. Counting it as "dropped by rounding" would have made a
890
+ # working exclusion look like a rounding defect on every future run.
891
+ boundary = [r for r in rows
892
+ if r.get("cover_gap_d") == 0
893
+ and (r.get("discontinued") or "") != "Yes"
894
+ and isinstance(r.get("cover_gap_units"), (int, float))
895
+ and r["cover_gap_units"] > 0]
896
+ missed = sorted(r["code"] for r in boundary if r["code"] not in view_rows)
897
+ checks.append({
898
+ "check": "Rounding boundary: every SKU whose cover gap rounds to 0 DAYS but is a real "
899
+ "shortfall in UNITS is still on the buy list",
900
+ "ours": len(boundary) - len(missed), "theirs": len(boundary),
901
+ "ok": not missed,
902
+ "detail": {"dropped_by_rounding": missed[:10],
903
+ # Reported, not asserted: these are the rows a `cover_gap_d < 0` filter
904
+ # would have lost. A 0 here does not make that filter correct.
905
+ "n_saved_by_rounding_away_from_zero": len(boundary)},
906
+ })
907
+
908
+ # ⭐ RULE 8 β€” the Discontinued column against an INDEPENDENT Odoo aggregate.
909
+ # β›” IT RE-RESOLVES THE TAG BY NAME rather than reusing the id the column was built from.
910
+ # Sharing that binding would let the check and the column carry the same bug and agree
911
+ # about it ([[gate-and-nc-must-not-share-a-binding]]).
912
+ tag_id = products.discontinued_tag_id.__wrapped__()
913
+ ours_disc = len([r for r in rows if (r.get("discontinued") or "") == "Yes"])
914
+ theirs_disc = O.get_odoo().search_count(
915
+ 'product.product',
916
+ [('active', '=', True), ('product_tag_ids', 'in', [tag_id])]) if tag_id else -1
917
+ checks.append({
918
+ "check": f"Discontinued SKUs == Odoo products carrying the {products.DISCONTINUED_TAG}"
919
+ f" tag (resolved by name, id {tag_id})",
920
+ "ours": ours_disc, "theirs": theirs_disc,
921
+ # Codes merge variants, so ours may be <= theirs; a tag that resolved to nothing is a
922
+ # hard red, because the column would read "nobody is discontinued" and look fine.
923
+ "ok": tag_id is not None and 0 < ours_disc <= theirs_disc,
924
+ "detail": {"tag_resolved": tag_id is not None,
925
+ "note": "ours counts SKU CODES, theirs counts product RECORDS; variants "
926
+ "sharing a code merge into one row, so ours <= theirs."},
927
+ })
928
+
929
+ # ⭐ RULE 8 β€” inbound units against a SECOND, INDEPENDENTLY DERIVED source (open purchase
930
+ # order lines). β›” SHAPE AND DIRECTION, NOT EQUALITY: the two are in different units of
931
+ # measure on ~107 codes and asserting equality would go red forever on a correct
932
+ # difference. `products.incoming_from_po` documents the measurement.
933
+ po_units, po_report = products.incoming_from_po()
934
+ ours_inc = sum(float(r.get("incoming") or 0.0) for r in rows)
935
+ theirs_inc = sum(po_units.values())
936
+ with_inbound = {r["code"] for r in rows if float(r.get("incoming") or 0.0) > 0}
937
+ po_codes = {c for c, v in po_units.items() if v > 0}
938
+ checks.append({
939
+ "check": "Inbound units (Odoo incoming_qty) reconcile to open purchase order lines",
940
+ "ours": round(ours_inc, 1), "theirs": round(theirs_inc, 1),
941
+ # A truncated PO read makes the oracle itself untrustworthy, so it is a red.
942
+ "ok": (not po_report["truncated"]) and theirs_inc > 0
943
+ and abs(ours_inc - theirs_inc) <= 0.10 * max(ours_inc, theirs_inc)
944
+ and len(with_inbound & po_codes) >= 0.85 * len(po_codes),
945
+ "detail": {"skus_with_inbound_ours": len(with_inbound),
946
+ "skus_with_inbound_po": len(po_codes),
947
+ "in_both": len(with_inbound & po_codes),
948
+ "po_lines": po_report, "uom_note": "purchase uom vs stock uom; the shipped "
949
+ "column is in the STOCK uom so it can be added to On hand."},
950
+ })
951
+
952
+ # ⭐ RULE 8 β€” the FORWARD demand basis against a DIRECT Odoo read_group over the same
953
+ # reference window. β›” The oracle re-reads Odoo itself rather than re-calling
954
+ # `forward_demand_by_code`, which would reconcile the number with itself β€” the self-sealing
955
+ # shape this function already carries a scar for.
956
+ fwd_map, fwd_report = products.forward_demand_by_code(t=t, team_id=team_id)
957
+ _rf, _rt = fwd_report["reference_window"]
958
+ # ⚠ `include_excluded_partners=True` HERE TOO, or the oracle would measure a narrower
959
+ # universe than the column and go red on the Amazon units the owner asked to include.
960
+ direct = O.read_group('sale.order.line',
961
+ O.sale_line_domain(_rf, _rt, team_id, extra=products._NO_SVC,
962
+ all_channels=True),
963
+ ['product_uom_qty:sum'], [], lazy=False)
964
+ theirs_u = float((direct[0] or {}).get('product_uom_qty') or 0.0) if direct else 0.0
965
+ # ⚠ A BRACKET, NOT AN EQUALITY, and the reason is in the number itself: the shipped total
966
+ # is the seasonal rows PLUS the LTM-fallback rows scaled onto the horizon, and the fallback
967
+ # rows are by definition SKUs that window never saw. Asserting equality would go red
968
+ # forever on a difference the design creates on purpose.
969
+ shipped = sum(float(r["demand_fwd"]) for r in rows
970
+ if isinstance(r.get("demand_fwd"), (int, float)))
971
+ checks.append({
972
+ "check": f"Forward {products.FORWARD_MONTHS}-month demand basis: the shipped forecast "
973
+ f"ties to Odoo units over its own reference window {_rf} to {_rt}",
974
+ "ours": round(shipped, 0), "theirs": round(theirs_u, 0),
975
+ # The shipped total is seasonal rows PLUS scaled fallback rows, so it cannot equal the
976
+ # window total exactly; what must hold is that it is a real, bounded fraction of it and
977
+ # that the window itself returned units at all.
978
+ "ok": theirs_u > 0 and 0.5 * theirs_u <= shipped <= 1.5 * theirs_u,
979
+ "detail": {**fwd_report,
980
+ "skus_with_a_forecast": len([r for r in rows if r.get("demand_fwd")]),
981
+ "note": "shipped = seasonal rows + LTM-fallback rows scaled to the "
982
+ "horizon, so it brackets rather than equals the window total."},
983
  })
984
  return checks
platform/modules/products.py CHANGED
@@ -39,10 +39,15 @@ def _code_map():
39
  for p in prods}
40
 
41
 
42
- def _sku_rev(date_from, date_to, team_id=None):
43
  """{sku_code: {'name','rev','qty','orders'}} over a window (services excluded,
44
- duplicate product records merged by SKU code)."""
45
- g = O.read_group('sale.order.line', O.sale_line_domain(date_from, date_to, team_id, extra=_NO_SVC),
 
 
 
 
 
46
  ['price_subtotal:sum', 'product_uom_qty:sum'], ['product_id'], lazy=False)
47
  codes = _code_map()
48
  out = {}
@@ -59,6 +64,73 @@ def _sku_rev(date_from, date_to, team_id=None):
59
  return out
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def yoy_movers(t=None, limit=20, team_id=None):
63
  """Top SKU risers and decliners by YTD-vs-same-period-LY revenue change."""
64
  t = t or P.today()
@@ -167,7 +239,8 @@ def directory(t=None, team_id=None):
167
 
168
 
169
  def catalogue():
170
- """`{sku_code: {'product', 'category', 'id'}}` β€” EVERY ACTIVE product, sold or not.
 
171
 
172
  β›” THIS IS THE CATALOGUE UNIVERSE, AND IT IS DELIBERATELY NOT `directory()`. `directory()`'s
173
  row set IS the union of two revenue `read_group`s over `sale.order.line` (`:155`), so a SKU
@@ -193,7 +266,16 @@ def catalogue():
193
  `modules/backorders.py:161` already uses).
194
  """
195
  dom = [('active', '=', True)]
196
- prods = O.search_read('product.product', dom, ['id', 'default_code', 'display_name', 'name'],
 
 
 
 
 
 
 
 
 
197
  limit=50000)
198
  n = O.get_odoo().search_count('product.product', dom)
199
  if len(prods) != n:
@@ -202,11 +284,19 @@ def catalogue():
202
  f"a search_count of {n}. A short catalogue renders as a plausible smaller grid with "
203
  f"nothing reporting it; raise the limit before shipping this.")
204
  code_cat = _code_category()
 
205
  out = {}
206
  for p in prods:
207
  code = (str(p['default_code']).strip() if p.get('default_code') else f"pid:{p['id']}")
208
- # First record wins, matching `_code_category`'s own convention. MEASURED 2026-08-11: zero
209
- # active products share a code, so this branch is a guard, not a merge policy.
 
 
 
 
 
 
 
210
  # ⭐⭐ W33-T43 (R2 / amendment A2) β€” `id` RIDES THE ROW. Odoo's `product.product` id is
211
  # already in hand (the `pid:{id}` fallback above uses it and then threw it away), and it is
212
  # the ONE column `ut_odoo_products` had that `product_data` lacked. R2 merges onto the
@@ -215,12 +305,90 @@ def catalogue():
215
  # ⚠ A product's grid pid is `crc32(default_code)`, NOT the Odoo id β€” unlike a CUSTOMER row,
216
  # whose pid IS the partner id. That asymmetry is exactly why this cannot be derived
217
  # downstream in `aios_grid.py` and has to be carried from the source read.
218
- out.setdefault(code, {'product': p.get('display_name') or p.get('name') or code,
219
- 'category': code_cat.get(code, '(uncategorized)'),
220
- 'id': p['id']})
 
 
 
 
 
 
 
 
221
  return out
222
 
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  #: ⭐⭐ WAVE 30 / W30-T34 (the carried W29-T52) β€” THE PRICELIST STRATUM, PER LIST.
225
  #:
226
  #: MEASURED LIVE 2026-08-12, and every one of these numbers shaped the design rather than
 
39
  for p in prods}
40
 
41
 
42
+ def _sku_rev(date_from, date_to, team_id=None, all_channels=False):
43
  """{sku_code: {'name','rev','qty','orders'}} over a window (services excluded,
44
+ duplicate product records merged by SKU code).
45
+
46
+ ⚠ `all_channels=True` keeps the excluded house accounts (GIFTWARE DEALS, the Amazon channel)
47
+ IN the read. Only the replenishment caller wants that; see `sale_line_domain`'s own note."""
48
+ g = O.read_group('sale.order.line',
49
+ O.sale_line_domain(date_from, date_to, team_id, extra=_NO_SVC,
50
+ all_channels=all_channels),
51
  ['price_subtotal:sum', 'product_uom_qty:sum'], ['product_id'], lazy=False)
52
  codes = _code_map()
53
  out = {}
 
64
  return out
65
 
66
 
67
+ #: ⭐⭐ THE BUY LIST'S DEMAND HORIZON (owner ruling, 2026-08-19). The owner described the cover gap
68
+ #: as *"based on the next 8 months Unit sales"*; it was in fact a trailing-twelve-month daily rate,
69
+ #: and asked to choose, the owner ruled FORWARD 8 MONTHS. This is that horizon, in days.
70
+ FORWARD_MONTHS = 8
71
+ FORWARD_DAYS = 243 # 8 months of 30.4 days, rounded to whole days
72
+
73
+
74
+ def forward_demand_by_code(t=None, team_id=None):
75
+ """`({code: units}, report)` β€” units this SKU is expected to sell over the NEXT 8 months.
76
+
77
+ ⭐⭐ SEASONAL NAIVE, AND FOR THIS TENANT THAT IS THE POINT RATHER THAN A SHORTCUT. The estimate
78
+ for the next 8 months is **the units the SKU actually sold in the same 8 calendar months one
79
+ year ago**. Royal Imports is a floral-supply wholesaler whose year is Valentine's, Mother's Day
80
+ and Christmas; a flat trailing-twelve-month rate spreads those peaks evenly across the year and
81
+ tells a buyer to hold the same stock in January as in early February. Reading the matching
82
+ window last year keeps the shape of the year in the number.
83
+
84
+ β›” THE FALLBACK IS NOT OPTIONAL AND IT IS NOT SILENT. A SKU introduced since that window has no
85
+ history in it, and a pure seasonal read would estimate ZERO demand and quietly guarantee the
86
+ newest products are never re-ordered β€” a buy list's worst possible blind spot, because nothing
87
+ on screen would look wrong. So a SKU with no reference-window sales but real LTM sales falls
88
+ back to its LTM rate scaled to the horizon, and `report` COUNTS how many rows took each road so
89
+ the mix is visible rather than assumed.
90
+
91
+ ⚠ BU-SHAPED THROUGH `team_id`, exactly as `directory()` is: a Fisch reader's buy quantity must
92
+ answer "what will FISCH sell", and the window reads through the same `sale_line_domain`.
93
+ """
94
+ t = t or P.today()
95
+ # β›” THE WINDOW IS THE NEXT 8 MONTHS SHIFTED BACK A YEAR, NOT THE 8 MONTHS BEFORE THIS DATE
96
+ # LAST YEAR, and the two are easy to swap. Today is the ANCHOR: `t - 365d` is where the
97
+ # forecast period starts and the window runs FORWARD from there. Written the other way round
98
+ # (`ref_to = t - 365d`, counting backwards) the estimate reads the wrong half of the year and
99
+ # is at its most wrong exactly where seasonality is strongest β€” it would price the next
100
+ # Christmas off last spring. Caught on the first run of this function, 2026-08-19.
101
+ ref_from = t - dt.timedelta(days=365)
102
+ ref_to = ref_from + dt.timedelta(days=FORWARD_DAYS)
103
+ # ⭐⭐ ALL CHANNELS, INCLUDING AMAZON (owner, 2026-08-19). Those units ship off the same shelf,
104
+ # so a reorder quantity that omits them under-buys every SKU the Amazon channel moves. This is
105
+ # the ONE demand read in this module that opts in; revenue and margin stay wholesale-scoped.
106
+ seasonal = _sku_rev(ref_from.isoformat(), ref_to.isoformat(), team_id, all_channels=True)
107
+ lf, lt = P.ltm(t)
108
+ ltm = _sku_rev(lf, lt, team_id, all_channels=True)
109
+
110
+ out, from_seasonal, from_ltm = {}, 0, 0
111
+ for code, e in seasonal.items():
112
+ qty = float(e.get('qty') or 0.0)
113
+ if qty > 0:
114
+ out[code] = qty
115
+ from_seasonal += 1
116
+ for code, e in ltm.items():
117
+ if code in out:
118
+ continue
119
+ qty = float(e.get('qty') or 0.0)
120
+ if qty > 0:
121
+ # Scale the trailing rate onto the horizon. Flat by construction: there is no
122
+ # seasonal shape to borrow for a SKU that was not there last year.
123
+ out[code] = qty * (FORWARD_DAYS / 365.0)
124
+ from_ltm += 1
125
+ return out, {
126
+ 'reference_window': [ref_from.isoformat(), ref_to.isoformat()],
127
+ 'horizon_days': FORWARD_DAYS,
128
+ 'codes_from_seasonal': from_seasonal,
129
+ 'codes_from_ltm_fallback': from_ltm,
130
+ 'codes_with_no_demand': 0, # filled by the caller against the catalogue it holds
131
+ }
132
+
133
+
134
  def yoy_movers(t=None, limit=20, team_id=None):
135
  """Top SKU risers and decliners by YTD-vs-same-period-LY revenue change."""
136
  t = t or P.today()
 
239
 
240
 
241
  def catalogue():
242
+ """`{sku_code: {'product', 'category', 'id', 'discontinued', 'incoming'}}` β€” EVERY ACTIVE
243
+ product, sold or not.
244
 
245
  β›” THIS IS THE CATALOGUE UNIVERSE, AND IT IS DELIBERATELY NOT `directory()`. `directory()`'s
246
  row set IS the union of two revenue `read_group`s over `sale.order.line` (`:155`), so a SKU
 
266
  `modules/backorders.py:161` already uses).
267
  """
268
  dom = [('active', '=', True)]
269
+ # ⭐ `product_tag_ids` and `incoming_qty` RIDE THIS READ rather than paying for their own.
270
+ # This function already pulls every active product once; a second full pull for either column
271
+ # costs ~6 s on somebody's first page load for data that is already in flight.
272
+ # ⚠ `incoming_qty` is an UNSTORED computed field. It reads fine per record, but Odoo refuses
273
+ # to aggregate it (`Fault 2: Cannot aggregate field 'incoming_qty'`), so nothing downstream
274
+ # may push a filter or a read_group on it back to Odoo. It is materialised into the pool here
275
+ # and summed on our side; `validate()` reconciles that sum against purchase-order lines.
276
+ prods = O.search_read('product.product', dom,
277
+ ['id', 'default_code', 'display_name', 'name',
278
+ 'product_tag_ids', 'incoming_qty'],
279
  limit=50000)
280
  n = O.get_odoo().search_count('product.product', dom)
281
  if len(prods) != n:
 
284
  f"a search_count of {n}. A short catalogue renders as a plausible smaller grid with "
285
  f"nothing reporting it; raise the limit before shipping this.")
286
  code_cat = _code_category()
287
+ disc_tag = discontinued_tag_id()
288
  out = {}
289
  for p in prods:
290
  code = (str(p['default_code']).strip() if p.get('default_code') else f"pid:{p['id']}")
291
+ # First record wins, matching `_code_category`'s own convention.
292
+ # β›” THE 2026-08-11 MEASUREMENT ("zero active products share a code, so this branch is a
293
+ # guard, not a merge policy") HAS EXPIRED. RE-MEASURED 2026-08-19: **5,873 active products
294
+ # carry 5,872 distinct codes** because `2112-12` is now on two records. So this IS a merge
295
+ # policy today, and it is the standing reason `validate()`'s row-count leg reads 5872
296
+ # against an Odoo `search_count` of 5873, along with all three pricelist legs being short
297
+ # by exactly one. Those reds are this duplicate, not a truncated read.
298
+ # ⚠ Which is also why `incoming` ACCUMULATES below instead of taking the first record's
299
+ # value: a merge policy that keeps one record's name must still sum the other's stock.
300
  # ⭐⭐ W33-T43 (R2 / amendment A2) β€” `id` RIDES THE ROW. Odoo's `product.product` id is
301
  # already in hand (the `pid:{id}` fallback above uses it and then threw it away), and it is
302
  # the ONE column `ut_odoo_products` had that `product_data` lacked. R2 merges onto the
 
305
  # ⚠ A product's grid pid is `crc32(default_code)`, NOT the Odoo id β€” unlike a CUSTOMER row,
306
  # whose pid IS the partner id. That asymmetry is exactly why this cannot be derived
307
  # downstream in `aios_grid.py` and has to be carried from the source read.
308
+ row = out.setdefault(code, {'product': p.get('display_name') or p.get('name') or code,
309
+ 'category': code_cat.get(code, '(uncategorized)'),
310
+ 'id': p['id'],
311
+ 'discontinued': 'No', 'incoming': 0.0})
312
+ # β›” ACROSS EVERY RECORD SHARING THE CODE, not just the first one that won above. A SKU
313
+ # whose variants are separate records carries its inbound on whichever record the PO named,
314
+ # and 'first record wins' would drop the rest β€” a buy list that under-counts what is
315
+ # already on the water tells you to re-order stock you have already bought.
316
+ row['incoming'] += float(p.get('incoming_qty') or 0.0)
317
+ if disc_tag is not None and disc_tag in (p.get('product_tag_ids') or ()):
318
+ row['discontinued'] = 'Yes'
319
  return out
320
 
321
 
322
+ #: ⭐ The Odoo product tag that marks a SKU withdrawn from the line. Owner, 2026-08-19: *"we have
323
+ #: a status Field called discontinued from Odoo. Surface it right now so we can filter correctly."*
324
+ #: MEASURED that day: it is not a FIELD at all β€” `product.product` has no `discontinued` column and
325
+ #: no selection carrying the word. It is `product.tag`, on **497 of 5,873 active products**, every
326
+ #: one of them `active=True` and `sale_ok=True`, so nothing else in Odoo distinguishes them and the
327
+ #: buy list was quoting them as live SKUs.
328
+ DISCONTINUED_TAG = 'Discontinued'
329
+
330
+
331
+ @lru_cache(maxsize=1)
332
+ def discontinued_tag_id():
333
+ """The `product.tag` id for `DISCONTINUED_TAG`, or `None` if the tag is not there.
334
+
335
+ ⚠ RESOLVED BY NAME, NOT BY ID, for the reason `PRICELIST_COLUMNS` gives: an id hard-coded here
336
+ keeps pointing at whatever inherits it if the tag is deleted and re-made, and every product
337
+ would be silently mislabelled. A missing tag yields `None`, which marks the whole catalogue
338
+ `No` β€” so `validate()` reconciles the count against Odoo rather than trusting this, and goes
339
+ RED on the difference instead of shipping a column that quietly says nobody is discontinued.
340
+ """
341
+ rows = O.search_read('product.tag', [('name', '=ilike', DISCONTINUED_TAG)], ['id'], limit=2)
342
+ return rows[0]['id'] if rows else None
343
+
344
+
345
+ def incoming_from_po(prods=None):
346
+ """`({code: open_po_units}, report)` β€” inbound derived from PURCHASE ORDER LINES.
347
+
348
+ β›” THIS IS THE ORACLE, NOT THE SOURCE. The shipped `incoming` column comes from
349
+ `product.product.incoming_qty` (see `catalogue()`); this derives the same quantity a second,
350
+ independent way so `validate()` can hold them against each other rather than reconciling a
351
+ number with itself β€” the self-sealing failure `product_data.validate` already carries a scar
352
+ for ([[gate-and-nc-must-not-share-a-binding]]).
353
+
354
+ β›”β›” AND THE TWO ARE NOT EXPECTED TO BE EQUAL, WHICH IS WHY THE SOURCE IS THE ONE IT IS.
355
+ MEASURED 2026-08-19: totals 179,979 vs 173,775 units, differing on **107 of ~490 codes**, and
356
+ the differences are a UNIT OF MEASURE gap, not an error. `purchase.order.line.product_qty` is
357
+ in the line's PURCHASE uom while `incoming_qty` is in the product's STOCK uom, so the `SP-*`
358
+ family reads exactly 4x apart (400 vs 100, 320 vs 80, 240 vs 60). `on_hand` and `qty_ltm` are
359
+ both in the STOCK uom, so `incoming_qty` is the only one of the two that can be ADDED to a
360
+ shelf quantity. A buy list built on the purchase uom would over-count inbound fourfold on
361
+ those SKUs and tell the team not to re-order stock that is not coming.
362
+
363
+ So the check this feeds asserts SHAPE and DIRECTION (same SKUs carry inbound, totals within a
364
+ stated band) and REPORTS the per-code gap. Asserting equality would go red forever on a
365
+ difference that is correct.
366
+ """
367
+ lines = O.search_read('purchase.order.line', [('state', '=', 'purchase')],
368
+ ['product_id', 'product_qty', 'qty_received'], limit=50000)
369
+ n = O.get_odoo().search_count('purchase.order.line', [('state', '=', 'purchase')])
370
+ by_id = {p['id']: p for p in (prods if prods is not None else [])}
371
+ if not by_id:
372
+ for p in O.search_read('product.product', [('active', '=', True)],
373
+ ['id', 'default_code'], limit=50000):
374
+ by_id[p['id']] = p
375
+ out, off_catalogue = {}, 0.0
376
+ for line in lines:
377
+ pid = (line.get('product_id') or [None])[0]
378
+ open_q = float(line.get('product_qty') or 0.0) - float(line.get('qty_received') or 0.0)
379
+ if open_q <= 0:
380
+ continue
381
+ rec = by_id.get(pid)
382
+ if rec is None: # ordered against an ARCHIVED product: real, but off-grid
383
+ off_catalogue += open_q
384
+ continue
385
+ code = (str(rec['default_code']).strip() if rec.get('default_code') else f"pid:{pid}")
386
+ out[code] = out.get(code, 0.0) + open_q
387
+ return out, {'lines_read': len(lines), 'lines_total': n,
388
+ 'truncated': len(lines) != n,
389
+ 'units_on_archived_products': round(off_catalogue, 1)}
390
+
391
+
392
  #: ⭐⭐ WAVE 30 / W30-T34 (the carried W29-T52) β€” THE PRICELIST STRATUM, PER LIST.
393
  #:
394
  #: MEASURED LIVE 2026-08-12, and every one of these numbers shaped the design rather than
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,568 +1,568 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // Β· nothing is silently hidden β€” the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- import { choiceOptions } from "./types";
30
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
31
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
32
- // loaded here) β€” the same import `RecordComments` takes for the same prop.
33
- import type { SurfaceScope } from "./apiBridge";
34
- import RecordComments from "./RecordComments";
35
- import { Documents } from "./Documents";
36
- import { formatDisplay } from "./cells";
37
- import { actionHref } from "./display";
38
- import { optionTint } from "./choiceColors";
39
- import { ModeIcon } from "./icons";
40
- // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
41
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
42
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
43
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
44
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
45
- import "./SwipeView.css";
46
-
47
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
48
-
49
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
50
- type BindingFault =
51
- | { kind: "unbound" }
52
- | { kind: "field-gone"; fieldKey: string }
53
- | { kind: "not-select"; field: Field }
54
- | { kind: "option-gone"; field: Field; missing: string[] };
55
-
56
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
57
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
58
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
59
- const field = fieldByKey.get(spec.fieldKey);
60
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
61
- // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
62
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
63
- // adds and sometimes overwrites is two gestures wearing one button.
64
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
65
- const options = choiceOptions(field);
66
- const has = new Set(options.map((o) => o.toLowerCase()));
67
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
68
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
69
- return { ok: true, field, spec };
70
- }
71
-
72
- /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
73
- const isUndecided = (row: Row, key: string): boolean =>
74
- String(row[key] ?? "").trim() === "";
75
-
76
- export function SwipeView({
77
- rows,
78
- fields,
79
- fieldByKey,
80
- spec,
81
- cardKeys,
82
- detailKeys,
83
- scope,
84
- viewer,
85
- docs,
86
- docPayload,
87
- onDocAdd,
88
- onDocFetch,
89
- onDocDelete,
90
- titleKey,
91
- canWrite,
92
- readOnlyReason,
93
- canBind,
94
- onSpec,
95
- onSwipe,
96
- onOpen,
97
- }: {
98
- /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
99
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
100
- * patch lands; there is no local cursor to drift out of step with the data. */
101
- rows: Row[];
102
- /** Every field, for the picker's field list. */
103
- fields: Field[];
104
- fieldByKey: Map<string, Field>;
105
- /** The stored binding, or undefined for a deck nobody has configured yet. */
106
- spec: SwipeSpec | undefined;
107
- /** The handful of visible fields the card lists under its title. */
108
- cardKeys: string[];
109
- titleKey: string;
110
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
111
- canWrite: boolean;
112
- /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
113
- readOnlyReason: string | null;
114
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
115
- * view-editing permission and NOT `canWrite` β€” conflating the two is
116
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
117
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
118
- canBind: boolean;
119
- /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
120
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
121
- onSpec: (next: SwipeSpec | undefined) => void;
122
- onSwipe: (pid: number, value: string) => void;
123
- onOpen: (pid: number) => void;
124
- /**
125
- * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
126
- *
127
- * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
128
- * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
129
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
130
- * different amounts. A card must render with none of them rather than throw β€” the standalone
131
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
132
- */
133
- /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
134
- detailKeys?: string[];
135
- /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
136
- * which is the pre-existing precondition `RecordDetail` already carries. */
137
- scope?: SurfaceScope;
138
- viewer?: Viewer;
139
- /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
140
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
141
- * cannot keep). */
142
- /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
143
- * and that shape cannot serve a deck. */
144
- docs?: Record<string, CustomerDoc[]>;
145
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
146
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
147
- * open record. A deck paints many records at once, so a handler bound to a single pid would
148
- * attach every reviewer's upload to whichever card happened to be open. */
149
- onDocAdd?: (
150
- pid: number,
151
- file: { name: string; mime: string; size: number; data_b64: string }
152
- ) => void;
153
- onDocFetch?: (pid: number, docId: string) => void;
154
- onDocDelete?: (pid: number, docId: string) => void;
155
- }) {
156
- // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
157
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
158
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
159
- // state rather than quietly shrinking the deck (rule 8b).
160
- const [later, setLater] = useState<Set<number>>(new Set());
161
- const deckRef = useRef<HTMLDivElement>(null);
162
-
163
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
164
- const boundKey = binding.ok ? binding.field.key : null;
165
-
166
- const undecided = useMemo(
167
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
168
- [rows, boundKey]
169
- );
170
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
171
- const card = deck[0];
172
-
173
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
174
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
175
- useEffect(() => {
176
- setLater((prev) => {
177
- if (prev.size === 0) return prev;
178
- const live = new Set(undecided.map((r) => r.pid));
179
- const next = new Set([...prev].filter((pid) => live.has(pid)));
180
- return next.size === prev.size ? prev : next;
181
- });
182
- }, [undecided]);
183
-
184
- const decide = useCallback(
185
- (value: string) => {
186
- if (!card || !canWrite) return;
187
- onSwipe(card.pid, value);
188
- },
189
- [card, canWrite, onSwipe]
190
- );
191
-
192
- // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
193
- // path: the whole point of the mode is that one hand can clear a queue.
194
- useEffect(() => {
195
- if (!binding.ok || !canWrite || !card) return;
196
- const onKey = (e: KeyboardEvent) => {
197
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
198
- const el = document.activeElement as HTMLElement | null;
199
- // Never steal an arrow key from a text field or a native control the user is inside.
200
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
201
- return;
202
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
203
- e.preventDefault();
204
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
205
- };
206
- window.addEventListener("keydown", onKey);
207
- return () => window.removeEventListener("keydown", onKey);
208
- }, [binding, canWrite, card, decide]);
209
-
210
- if (!binding.ok) {
211
- return (
212
- <div className="cg-swipe" ref={deckRef}>
213
- <SwipeBinder
214
- fault={binding.fault}
215
- fields={fields}
216
- fieldByKey={fieldByKey}
217
- spec={spec}
218
- canBind={canBind}
219
- onSpec={onSpec}
220
- />
221
- </div>
222
- );
223
- }
224
-
225
- const { field } = binding;
226
- const leftTint = optionTint(field, binding.spec.leftOption);
227
- const rightTint = optionTint(field, binding.spec.rightOption);
228
-
229
- return (
230
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
231
- <div className="cg-swipe-bar">
232
- <span className="cg-swipe-bound">
233
- <ModeIcon mode="swipe" />
234
- Sorting into <strong>{field.label}</strong>
235
- </span>
236
- <span className="cg-swipe-left">
237
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
238
- </span>
239
- {canBind && (
240
- <button
241
- type="button"
242
- className="cg-link-btn"
243
- onClick={() => onSpec(undefined)}
244
- title="Choose a different field or different options for this deck"
245
- >
246
- Change
247
- </button>
248
- )}
249
- </div>
250
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
251
- {card ? (
252
- <div className="cg-swipe-deck">
253
- <button
254
- type="button"
255
- className="cg-swipe-side cg-swipe-side--left"
256
- disabled={!canWrite}
257
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
258
- onClick={() => decide(binding.spec.leftOption)}
259
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
260
- >
261
- <span aria-hidden className="cg-swipe-arrow">
262
- <svg width="16" height="16" viewBox="0 0 16 16">
263
- <path
264
- d="M11 3.2 6.2 8l4.8 4.8"
265
- fill="none"
266
- stroke="currentColor"
267
- strokeWidth="1.6"
268
- strokeLinecap="round"
269
- strokeLinejoin="round"
270
- />
271
- </svg>
272
- </span>
273
- {binding.spec.leftOption}
274
- </button>
275
- <article
276
- className="cg-swipe-card"
277
- role="button"
278
- tabIndex={0}
279
- onClick={() => onOpen(card.pid)}
280
- onKeyDown={(e) => {
281
- if (e.key !== "Enter" && e.key !== " ") return;
282
- e.preventDefault();
283
- onOpen(card.pid);
284
- }}
285
- >
286
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
287
- <div className="cg-swipe-cells">
288
- {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
289
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
290
- been widened yet renders exactly what it rendered before. */}
291
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
292
- const f = fieldByKey.get(k);
293
- if (!f) return null;
294
- const text = formatDisplay(f, card[k]);
295
- if (!text) return null;
296
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
297
- // scheme guard β€” and every gesture that reaches it must be stopped from also
298
- // reaching the card, which is a button (the kanban card's note, same trap).
299
- const href = actionHref(f, card[k]);
300
- return (
301
- <div key={k} className="cg-swipe-cell">
302
- <span className="cg-lv-k">{f.label}</span>
303
- {href ? (
304
- <a
305
- className="cg-lv-v"
306
- href={href}
307
- target="_blank"
308
- rel="noopener noreferrer"
309
- title={text}
310
- onClick={(e) => e.stopPropagation()}
311
- onKeyDown={(e) => e.stopPropagation()}
312
- >
313
- {text}
314
- </a>
315
- ) : (
316
- <span className="cg-lv-v">{text}</span>
317
- )}
318
- </div>
319
- );
320
- })}
321
- </div>
322
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
323
- that opens the record, and a click on a comment box or an upload control must not
324
- also open the modal it exists to make unnecessary (the kanban card's link trap,
325
- one surface over). */}
326
- {onDocAdd && onDocFetch && onDocDelete && (
327
- <div
328
- className="cg-swipe-docs"
329
- onClick={(e) => e.stopPropagation()}
330
- onKeyDown={(e) => e.stopPropagation()}
331
- role="presentation"
332
- >
333
- <Documents
334
- pid={Number(card.pid)}
335
- docs={docs?.[String(card.pid)] ?? []}
336
- docPayload={docPayload}
337
- onAdd={(file) => onDocAdd(card.pid, file)}
338
- onFetch={(docId) => onDocFetch(card.pid, docId)}
339
- onDelete={(docId) => onDocDelete(card.pid, docId)}
340
- />
341
- </div>
342
- )}
343
- {scope != null && (
344
- <div
345
- className="cg-swipe-comments"
346
- onClick={(e) => e.stopPropagation()}
347
- onKeyDown={(e) => e.stopPropagation()}
348
- role="presentation"
349
- >
350
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
351
- reuses the mounted instance across a card change and paints one record's
352
- comments under another's name until the fetch returns. */}
353
- <RecordComments
354
- key={`${scope}:${Number(card.pid)}`}
355
- scope={scope}
356
- pid={Number(card.pid)}
357
- viewer={viewer}
358
- />
359
- </div>
360
- )}
361
- {canWrite && (
362
- <button
363
- type="button"
364
- className="cg-link-btn cg-swipe-later"
365
- onClick={(e) => {
366
- e.stopPropagation();
367
- setLater((prev) => new Set(prev).add(card.pid));
368
- }}
369
- >
370
- Decide later
371
- </button>
372
- )}
373
- </article>
374
- <button
375
- type="button"
376
- className="cg-swipe-side cg-swipe-side--right"
377
- disabled={!canWrite}
378
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
379
- onClick={() => decide(binding.spec.rightOption)}
380
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
381
- >
382
- {binding.spec.rightOption}
383
- <span aria-hidden className="cg-swipe-arrow">
384
- <svg width="16" height="16" viewBox="0 0 16 16">
385
- <path
386
- d="M5 3.2 9.8 8 5 12.8"
387
- fill="none"
388
- stroke="currentColor"
389
- strokeWidth="1.6"
390
- strokeLinecap="round"
391
- strokeLinejoin="round"
392
- />
393
- </svg>
394
- </span>
395
- </button>
396
- </div>
397
- ) : (
398
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
399
- // between "the deck is finished" and "the filter hid everything", and the two want
400
- // different next actions. `later` is disclosed rather than quietly subtracted.
401
- <div className="cg-mode-empty cg-swipe-empty">
402
- {later.size > 0 ? (
403
- <>
404
- <p>
405
- {later.size.toLocaleString()}{" "}
406
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
407
- in this view is missing a <strong>{field.label}</strong>.
408
- </p>
409
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
410
- Bring them back
411
- </button>
412
- </>
413
- ) : (
414
- <p>
415
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
416
- view's filters to sort more.
417
- </p>
418
- )}
419
- </div>
420
- )}
421
- </div>
422
- );
423
- }
424
-
425
- /**
426
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
427
- * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
428
- * error screen beside a separate setup screen.
429
- */
430
- function SwipeBinder({
431
- fault,
432
- fields,
433
- fieldByKey,
434
- spec,
435
- canBind,
436
- onSpec,
437
- }: {
438
- fault: BindingFault;
439
- fields: Field[];
440
- fieldByKey: Map<string, Field>;
441
- spec: SwipeSpec | undefined;
442
- canBind: boolean;
443
- onSpec: (next: SwipeSpec | undefined) => void;
444
- }) {
445
- const selects = useMemo(
446
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
447
- [fields]
448
- );
449
- const [fieldKey, setFieldKey] = useState<string>(() => {
450
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
451
- return selects[0]?.key ?? "";
452
- });
453
- const chosen = fieldByKey.get(fieldKey);
454
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
455
- const [left, setLeft] = useState<string>("");
456
- const [right, setRight] = useState<string>("");
457
-
458
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
459
- // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
460
- // previous field would offer a value the new field cannot hold.
461
- useEffect(() => {
462
- setLeft(options[0] ?? "");
463
- setRight(options.find((o) => o !== options[0]) ?? "");
464
- }, [options]);
465
-
466
- const message = ((): string => {
467
- switch (fault.kind) {
468
- case "field-gone":
469
- return "The field this deck sorted into has been deleted. Pick another one.";
470
- case "not-select":
471
- return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
472
- + " sort into. Pick another field.";
473
- case "option-gone":
474
- return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
475
- fault.missing.length === 1 ? "is" : "are"
476
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
477
- fault.field.label
478
- }”. Pick the sides again.`;
479
- default:
480
- return "Sort records one at a time into two options of a single-select field.";
481
- }
482
- })();
483
-
484
- if (!canBind) {
485
- return (
486
- <div className="cg-mode-empty">
487
- <p>{message}</p>
488
- <p>Its creator or an admin can set this view up.</p>
489
- </div>
490
- );
491
- }
492
- if (selects.length === 0) {
493
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
494
- // requirement is what turns a dead end into a next action.
495
- return (
496
- <div className="cg-mode-empty">
497
- <p>
498
- A swipe deck sorts into a single-select field with at least two options. This database
499
- does not have one yet β€” add a single-select column, then come back.
500
- </p>
501
- </div>
502
- );
503
- }
504
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
505
- return (
506
- <div className="cg-swipe-setup">
507
- <p className="cg-swipe-setup-note">{message}</p>
508
- <label className="cg-swipe-setup-row">
509
- <span>Sort into</span>
510
- <select
511
- className="cg-select"
512
- value={fieldKey}
513
- onChange={(e) => setFieldKey(e.target.value)}
514
- >
515
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
516
- renders its FIRST option and reports a choice the user never made
517
- ([[cg-condition-builder-items]]). */}
518
- {selects.map((f) => (
519
- <option key={f.key} value={f.key}>
520
- {f.label}
521
- </option>
522
- ))}
523
- </select>
524
- </label>
525
- <div className="cg-swipe-setup-sides">
526
- <label className="cg-swipe-setup-row">
527
- <span>Swipe left</span>
528
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
529
- {options.map((o) => (
530
- <option key={o} value={o}>
531
- {o}
532
- </option>
533
- ))}
534
- </select>
535
- </label>
536
- <label className="cg-swipe-setup-row">
537
- <span>Swipe right</span>
538
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
539
- {options.map((o) => (
540
- <option key={o} value={o}>
541
- {o}
542
- </option>
543
- ))}
544
- </select>
545
- </label>
546
- </div>
547
- {!ready && left && right && (
548
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
549
- // option, so a Save that looked like it worked would simply not persist.
550
- <p className="cg-swipe-setup-warn">
551
- The two sides must be different options β€” otherwise both gestures do the same thing.
552
- </p>
553
- )}
554
- <button
555
- type="button"
556
- className="cg-btn cg-btn--primary"
557
- disabled={!ready}
558
- onClick={() =>
559
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
560
- }
561
- >
562
- Start sorting
563
- </button>
564
- </div>
565
- );
566
- }
567
-
568
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) β€” the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // Β· the deck holds only the records whose bound field is EMPTY β€” a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // Β· nothing is silently hidden β€” the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker β€” the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ import { choiceOptions } from "./types";
30
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
31
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
32
+ // loaded here) β€” the same import `RecordComments` takes for the same prop.
33
+ import type { SurfaceScope } from "./apiBridge";
34
+ import RecordComments from "./RecordComments";
35
+ import { Documents } from "./Documents";
36
+ import { formatDisplay } from "./cells";
37
+ import { actionHref } from "./display";
38
+ import { optionTint } from "./choiceColors";
39
+ import { ModeIcon } from "./icons";
40
+ // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
41
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
42
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
43
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
44
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
45
+ import "./SwipeView.css";
46
+
47
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
48
+
49
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
50
+ type BindingFault =
51
+ | { kind: "unbound" }
52
+ | { kind: "field-gone"; fieldKey: string }
53
+ | { kind: "not-select"; field: Field }
54
+ | { kind: "option-gone"; field: Field; missing: string[] };
55
+
56
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
57
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
58
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
59
+ const field = fieldByKey.get(spec.fieldKey);
60
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
61
+ // R2 β€” SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
62
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
63
+ // adds and sometimes overwrites is two gestures wearing one button.
64
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
65
+ const options = choiceOptions(field);
66
+ const has = new Set(options.map((o) => o.toLowerCase()));
67
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
68
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
69
+ return { ok: true, field, spec };
70
+ }
71
+
72
+ /** The bound cell is EMPTY β€” the one predicate that decides deck membership (R2). */
73
+ const isUndecided = (row: Row, key: string): boolean =>
74
+ String(row[key] ?? "").trim() === "";
75
+
76
+ export function SwipeView({
77
+ rows,
78
+ fields,
79
+ fieldByKey,
80
+ spec,
81
+ cardKeys,
82
+ detailKeys,
83
+ scope,
84
+ viewer,
85
+ docs,
86
+ docPayload,
87
+ onDocAdd,
88
+ onDocFetch,
89
+ onDocDelete,
90
+ titleKey,
91
+ canWrite,
92
+ readOnlyReason,
93
+ canBind,
94
+ onSpec,
95
+ onSwipe,
96
+ onOpen,
97
+ }: {
98
+ /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the kanban's contract.
99
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
100
+ * patch lands; there is no local cursor to drift out of step with the data. */
101
+ rows: Row[];
102
+ /** Every field, for the picker's field list. */
103
+ fields: Field[];
104
+ fieldByKey: Map<string, Field>;
105
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
106
+ spec: SwipeSpec | undefined;
107
+ /** The handful of visible fields the card lists under its title. */
108
+ cardKeys: string[];
109
+ titleKey: string;
110
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
111
+ canWrite: boolean;
112
+ /** Stated when the deck cannot be decided β€” permissions, or a computed column. */
113
+ readOnlyReason: string | null;
114
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
115
+ * view-editing permission and NOT `canWrite` β€” conflating the two is
116
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
117
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
118
+ canBind: boolean;
119
+ /** `undefined` DELETES the binding β€” absent is the honest unconfigured state, and storing a
120
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
121
+ onSpec: (next: SwipeSpec | undefined) => void;
122
+ onSwipe: (pid: number, value: string) => void;
123
+ onOpen: (pid: number) => void;
124
+ /**
125
+ * ⭐⭐ WAVE-29 T26 (owner R9) β€” WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
126
+ *
127
+ * R9: *"the swipe CARD itself renders the record detail inline β€” fields, comments and
128
+ * attachments β€” so a reviewer decides without leaving the deck."* Everything below is that,
129
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
130
+ * different amounts. A card must render with none of them rather than throw β€” the standalone
131
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
132
+ */
133
+ /** Every field the VIEW shows, in its order β€” not the three-key card summary. */
134
+ detailKeys?: string[];
135
+ /** The surface these records live on. Comments are keyed by it; absent β‡’ no comments section,
136
+ * which is the pre-existing precondition `RecordDetail` already carries. */
137
+ scope?: SurfaceScope;
138
+ viewer?: Viewer;
139
+ /** This record's attachments, and the plumbing. Handlers absent β‡’ the section is not rendered
140
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
141
+ * cannot keep). */
142
+ /** Keyed by pid, because a deck shows many records β€” `RecordDetail` takes ONE record's list
143
+ * and that shape cannot serve a deck. */
144
+ docs?: Record<string, CustomerDoc[]>;
145
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
146
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
147
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
148
+ * attach every reviewer's upload to whichever card happened to be open. */
149
+ onDocAdd?: (
150
+ pid: number,
151
+ file: { name: string; mime: string; size: number; data_b64: string }
152
+ ) => void;
153
+ onDocFetch?: (pid: number, docId: string) => void;
154
+ onDocDelete?: (pid: number, docId: string) => void;
155
+ }) {
156
+ // "Later" β€” session-only, never stored. A deck with no way past a record you cannot decide
157
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
158
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
159
+ // state rather than quietly shrinking the deck (rule 8b).
160
+ const [later, setLater] = useState<Set<number>>(new Set());
161
+ const deckRef = useRef<HTMLDivElement>(null);
162
+
163
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
164
+ const boundKey = binding.ok ? binding.field.key : null;
165
+
166
+ const undecided = useMemo(
167
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
168
+ [rows, boundKey]
169
+ );
170
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
171
+ const card = deck[0];
172
+
173
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β€”
174
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
175
+ useEffect(() => {
176
+ setLater((prev) => {
177
+ if (prev.size === 0) return prev;
178
+ const live = new Set(undecided.map((r) => r.pid));
179
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
180
+ return next.size === prev.size ? prev : next;
181
+ });
182
+ }, [undecided]);
183
+
184
+ const decide = useCallback(
185
+ (value: string) => {
186
+ if (!card || !canWrite) return;
187
+ onSwipe(card.pid, value);
188
+ },
189
+ [card, canWrite, onSwipe]
190
+ );
191
+
192
+ // ← / β†’ decide, and they are the SAME two actions the buttons are rather than a second code
193
+ // path: the whole point of the mode is that one hand can clear a queue.
194
+ useEffect(() => {
195
+ if (!binding.ok || !canWrite || !card) return;
196
+ const onKey = (e: KeyboardEvent) => {
197
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
198
+ const el = document.activeElement as HTMLElement | null;
199
+ // Never steal an arrow key from a text field or a native control the user is inside.
200
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
201
+ return;
202
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
203
+ e.preventDefault();
204
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
205
+ };
206
+ window.addEventListener("keydown", onKey);
207
+ return () => window.removeEventListener("keydown", onKey);
208
+ }, [binding, canWrite, card, decide]);
209
+
210
+ if (!binding.ok) {
211
+ return (
212
+ <div className="cg-swipe" ref={deckRef}>
213
+ <SwipeBinder
214
+ fault={binding.fault}
215
+ fields={fields}
216
+ fieldByKey={fieldByKey}
217
+ spec={spec}
218
+ canBind={canBind}
219
+ onSpec={onSpec}
220
+ />
221
+ </div>
222
+ );
223
+ }
224
+
225
+ const { field } = binding;
226
+ const leftTint = optionTint(field, binding.spec.leftOption);
227
+ const rightTint = optionTint(field, binding.spec.rightOption);
228
+
229
+ return (
230
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
231
+ <div className="cg-swipe-bar">
232
+ <span className="cg-swipe-bound">
233
+ <ModeIcon mode="swipe" />
234
+ Sorting into <strong>{field.label}</strong>
235
+ </span>
236
+ <span className="cg-swipe-left">
237
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
238
+ </span>
239
+ {canBind && (
240
+ <button
241
+ type="button"
242
+ className="cg-link-btn"
243
+ onClick={() => onSpec(undefined)}
244
+ title="Choose a different field or different options for this deck"
245
+ >
246
+ Change
247
+ </button>
248
+ )}
249
+ </div>
250
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
251
+ {card ? (
252
+ <div className="cg-swipe-deck">
253
+ <button
254
+ type="button"
255
+ className="cg-swipe-side cg-swipe-side--left"
256
+ disabled={!canWrite}
257
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
258
+ onClick={() => decide(binding.spec.leftOption)}
259
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
260
+ >
261
+ <span aria-hidden className="cg-swipe-arrow">
262
+ <svg width="16" height="16" viewBox="0 0 16 16">
263
+ <path
264
+ d="M11 3.2 6.2 8l4.8 4.8"
265
+ fill="none"
266
+ stroke="currentColor"
267
+ strokeWidth="1.6"
268
+ strokeLinecap="round"
269
+ strokeLinejoin="round"
270
+ />
271
+ </svg>
272
+ </span>
273
+ {binding.spec.leftOption}
274
+ </button>
275
+ <article
276
+ className="cg-swipe-card"
277
+ role="button"
278
+ tabIndex={0}
279
+ onClick={() => onOpen(card.pid)}
280
+ onKeyDown={(e) => {
281
+ if (e.key !== "Enter" && e.key !== " ") return;
282
+ e.preventDefault();
283
+ onOpen(card.pid);
284
+ }}
285
+ >
286
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
287
+ <div className="cg-swipe-cells">
288
+ {/* ⭐ WAVE-29 T26 (R9) β€” the RECORD's visible fields, not the three-key summary the
289
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
290
+ been widened yet renders exactly what it rendered before. */}
291
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
292
+ const f = fieldByKey.get(k);
293
+ if (!f) return null;
294
+ const text = formatDisplay(f, card[k]);
295
+ if (!text) return null;
296
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
297
+ // scheme guard β€” and every gesture that reaches it must be stopped from also
298
+ // reaching the card, which is a button (the kanban card's note, same trap).
299
+ const href = actionHref(f, card[k]);
300
+ return (
301
+ <div key={k} className="cg-swipe-cell">
302
+ <span className="cg-lv-k">{f.label}</span>
303
+ {href ? (
304
+ <a
305
+ className="cg-lv-v"
306
+ href={href}
307
+ target="_blank"
308
+ rel="noopener noreferrer"
309
+ title={text}
310
+ onClick={(e) => e.stopPropagation()}
311
+ onKeyDown={(e) => e.stopPropagation()}
312
+ >
313
+ {text}
314
+ </a>
315
+ ) : (
316
+ <span className="cg-lv-v">{text}</span>
317
+ )}
318
+ </div>
319
+ );
320
+ })}
321
+ </div>
322
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
323
+ that opens the record, and a click on a comment box or an upload control must not
324
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
325
+ one surface over). */}
326
+ {onDocAdd && onDocFetch && onDocDelete && (
327
+ <div
328
+ className="cg-swipe-docs"
329
+ onClick={(e) => e.stopPropagation()}
330
+ onKeyDown={(e) => e.stopPropagation()}
331
+ role="presentation"
332
+ >
333
+ <Documents
334
+ pid={Number(card.pid)}
335
+ docs={docs?.[String(card.pid)] ?? []}
336
+ docPayload={docPayload}
337
+ onAdd={(file) => onDocAdd(card.pid, file)}
338
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
339
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
340
+ />
341
+ </div>
342
+ )}
343
+ {scope != null && (
344
+ <div
345
+ className="cg-swipe-comments"
346
+ onClick={(e) => e.stopPropagation()}
347
+ onKeyDown={(e) => e.stopPropagation()}
348
+ role="presentation"
349
+ >
350
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
351
+ reuses the mounted instance across a card change and paints one record's
352
+ comments under another's name until the fetch returns. */}
353
+ <RecordComments
354
+ key={`${scope}:${Number(card.pid)}`}
355
+ scope={scope}
356
+ pid={Number(card.pid)}
357
+ viewer={viewer}
358
+ />
359
+ </div>
360
+ )}
361
+ {canWrite && (
362
+ <button
363
+ type="button"
364
+ className="cg-link-btn cg-swipe-later"
365
+ onClick={(e) => {
366
+ e.stopPropagation();
367
+ setLater((prev) => new Set(prev).add(card.pid));
368
+ }}
369
+ >
370
+ Decide later
371
+ </button>
372
+ )}
373
+ </article>
374
+ <button
375
+ type="button"
376
+ className="cg-swipe-side cg-swipe-side--right"
377
+ disabled={!canWrite}
378
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
379
+ onClick={() => decide(binding.spec.rightOption)}
380
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
381
+ >
382
+ {binding.spec.rightOption}
383
+ <span aria-hidden className="cg-swipe-arrow">
384
+ <svg width="16" height="16" viewBox="0 0 16 16">
385
+ <path
386
+ d="M5 3.2 9.8 8 5 12.8"
387
+ fill="none"
388
+ stroke="currentColor"
389
+ strokeWidth="1.6"
390
+ strokeLinecap="round"
391
+ strokeLinejoin="round"
392
+ />
393
+ </svg>
394
+ </span>
395
+ </button>
396
+ </div>
397
+ ) : (
398
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
399
+ // between "the deck is finished" and "the filter hid everything", and the two want
400
+ // different next actions. `later` is disclosed rather than quietly subtracted.
401
+ <div className="cg-mode-empty cg-swipe-empty">
402
+ {later.size > 0 ? (
403
+ <>
404
+ <p>
405
+ {later.size.toLocaleString()}{" "}
406
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
407
+ in this view is missing a <strong>{field.label}</strong>.
408
+ </p>
409
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
410
+ Bring them back
411
+ </button>
412
+ </>
413
+ ) : (
414
+ <p>
415
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
416
+ view's filters to sort more.
417
+ </p>
418
+ )}
419
+ </div>
420
+ )}
421
+ </div>
422
+ );
423
+ }
424
+
425
+ /**
426
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
427
+ * with the loss stated above it β€” one place that answers "what is this deck for", rather than an
428
+ * error screen beside a separate setup screen.
429
+ */
430
+ function SwipeBinder({
431
+ fault,
432
+ fields,
433
+ fieldByKey,
434
+ spec,
435
+ canBind,
436
+ onSpec,
437
+ }: {
438
+ fault: BindingFault;
439
+ fields: Field[];
440
+ fieldByKey: Map<string, Field>;
441
+ spec: SwipeSpec | undefined;
442
+ canBind: boolean;
443
+ onSpec: (next: SwipeSpec | undefined) => void;
444
+ }) {
445
+ const selects = useMemo(
446
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
447
+ [fields]
448
+ );
449
+ const [fieldKey, setFieldKey] = useState<string>(() => {
450
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
451
+ return selects[0]?.key ?? "";
452
+ });
453
+ const chosen = fieldByKey.get(fieldKey);
454
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
455
+ const [left, setLeft] = useState<string>("");
456
+ const [right, setRight] = useState<string>("");
457
+
458
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
459
+ // pick survives re-renders, and reset whenever the field changes β€” carrying an option from the
460
+ // previous field would offer a value the new field cannot hold.
461
+ useEffect(() => {
462
+ setLeft(options[0] ?? "");
463
+ setRight(options.find((o) => o !== options[0]) ?? "");
464
+ }, [options]);
465
+
466
+ const message = ((): string => {
467
+ switch (fault.kind) {
468
+ case "field-gone":
469
+ return "The field this deck sorted into has been deleted. Pick another one.";
470
+ case "not-select":
471
+ return `β€œ${fault.field.label}” is no longer a single-select, so it has no options to`
472
+ + " sort into. Pick another field.";
473
+ case "option-gone":
474
+ return `${fault.missing.map((m) => `β€œ${m}”`).join(" and ")} ${
475
+ fault.missing.length === 1 ? "is" : "are"
476
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on β€œ${
477
+ fault.field.label
478
+ }”. Pick the sides again.`;
479
+ default:
480
+ return "Sort records one at a time into two options of a single-select field.";
481
+ }
482
+ })();
483
+
484
+ if (!canBind) {
485
+ return (
486
+ <div className="cg-mode-empty">
487
+ <p>{message}</p>
488
+ <p>Its creator or an admin can set this view up.</p>
489
+ </div>
490
+ );
491
+ }
492
+ if (selects.length === 0) {
493
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
494
+ // requirement is what turns a dead end into a next action.
495
+ return (
496
+ <div className="cg-mode-empty">
497
+ <p>
498
+ A swipe deck sorts into a single-select field with at least two options. This database
499
+ does not have one yet β€” add a single-select column, then come back.
500
+ </p>
501
+ </div>
502
+ );
503
+ }
504
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
505
+ return (
506
+ <div className="cg-swipe-setup">
507
+ <p className="cg-swipe-setup-note">{message}</p>
508
+ <label className="cg-swipe-setup-row">
509
+ <span>Sort into</span>
510
+ <select
511
+ className="cg-select"
512
+ value={fieldKey}
513
+ onChange={(e) => setFieldKey(e.target.value)}
514
+ >
515
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
516
+ renders its FIRST option and reports a choice the user never made
517
+ ([[cg-condition-builder-items]]). */}
518
+ {selects.map((f) => (
519
+ <option key={f.key} value={f.key}>
520
+ {f.label}
521
+ </option>
522
+ ))}
523
+ </select>
524
+ </label>
525
+ <div className="cg-swipe-setup-sides">
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Swipe left</span>
528
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
529
+ {options.map((o) => (
530
+ <option key={o} value={o}>
531
+ {o}
532
+ </option>
533
+ ))}
534
+ </select>
535
+ </label>
536
+ <label className="cg-swipe-setup-row">
537
+ <span>Swipe right</span>
538
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
539
+ {options.map((o) => (
540
+ <option key={o} value={o}>
541
+ {o}
542
+ </option>
543
+ ))}
544
+ </select>
545
+ </label>
546
+ </div>
547
+ {!ready && left && right && (
548
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
549
+ // option, so a Save that looked like it worked would simply not persist.
550
+ <p className="cg-swipe-setup-warn">
551
+ The two sides must be different options β€” otherwise both gestures do the same thing.
552
+ </p>
553
+ )}
554
+ <button
555
+ type="button"
556
+ className="cg-btn cg-btn--primary"
557
+ disabled={!ready}
558
+ onClick={() =>
559
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
560
+ }
561
+ >
562
+ Start sorting
563
+ </button>
564
+ </div>
565
+ );
566
+ }
567
+
568
+ export default SwipeView;