fsanyoto commited on
Commit
2d0fa4f
·
verified ·
1 Parent(s): d2e4b91

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "9af9bb21f",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "c62a7e496",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 9af9bb21f
 
1
+ c62a7e496
api/app_guide.py CHANGED
@@ -30,7 +30,8 @@ def _skill_directory():
30
  path = Path(__file__).resolve().parents[2] / "platform" / "model" / "skills" / "apps"
31
  if not path.is_dir():
32
  import core
33
- path = Path(core.__file__).resolve().parent.parent / "model" / "skills" / "apps"
 
34
  return path
35
 
36
 
 
30
  path = Path(__file__).resolve().parents[2] / "platform" / "model" / "skills" / "apps"
31
  if not path.is_dir():
32
  import core
33
+ # core is a namespace package in the Space image, so it has no __file__.
34
+ path = Path(next(iter(core.__path__))).resolve().parent / "model" / "skills" / "apps"
35
  return path
36
 
37
 
api/app_rules.py CHANGED
@@ -109,9 +109,9 @@ def _catalog_templates():
109
  # Root-level platform JSON is in the deploy set; platform/model JSON is not.
110
  path = Path(__file__).resolve().parents[2] / "platform" / "catalog_templates.json"
111
  if not path.is_file():
112
- # The Space serves api/ beside the platform packages rather than the repo tree.
113
  import core
114
- path = Path(core.__file__).resolve().parent.parent / "catalog_templates.json"
115
  with path.open(encoding="utf-8") as handle:
116
  return json.load(handle)
117
 
@@ -522,7 +522,7 @@ def _catalog_selftest():
522
  ("title is bounded", {**base, "bindings": {"title": "x" * 121}}, []),
523
  ("body is bounded", {**base, "bindings": {"body": "x" * 2001}}, []),
524
  ("product keys are bounded", {**base, "bindings": {"products": ["x" * 257]}}, []),
525
- ("long dashes are refused", {**base, "bindings": {"body": "Bad\u2014copy"}}, []),
526
  ("control characters are refused", {**base, "bindings": {"body": "Bad\x00copy"}}, []),
527
  ("binding expressions are refused", {**base, "bindings": {"expr": "1+1"}}, []),
528
  ("carrier cannot enable expressions", {**base, "bindings": {"expr": "1+1", "legacy": {"expr": "1+1"}}}, []),
@@ -612,7 +612,7 @@ def _catalog_selftest():
612
  else:
613
  raise AssertionError("Malformed display passed")
614
  check("source rows remain unchanged", rt.get("product_table_workspace__shared") == source)
615
- check("public library has no long dashes", not re.search("[\u2013\u2014]", json.dumps(catalog_templates(), ensure_ascii=False)))
616
  print(json.dumps({"kinds": len(CATALOG_KINDS), "templates": len(pages),
617
  "checks": len(passed), "failed": 0, "tenant": "offline fake store"}, sort_keys=True))
618
 
 
109
  # Root-level platform JSON is in the deploy set; platform/model JSON is not.
110
  path = Path(__file__).resolve().parents[2] / "platform" / "catalog_templates.json"
111
  if not path.is_file():
112
+ # The Space serves api/ beside platform/, where core is a namespace package (no __file__).
113
  import core
114
+ path = Path(next(iter(core.__path__))).resolve().parent / "catalog_templates.json"
115
  with path.open(encoding="utf-8") as handle:
116
  return json.load(handle)
117
 
 
522
  ("title is bounded", {**base, "bindings": {"title": "x" * 121}}, []),
523
  ("body is bounded", {**base, "bindings": {"body": "x" * 2001}}, []),
524
  ("product keys are bounded", {**base, "bindings": {"products": ["x" * 257]}}, []),
525
+ ("long dashes are refused", {**base, "bindings": {"body": "Bad" + chr(0x2014) + "copy"}}, []),
526
  ("control characters are refused", {**base, "bindings": {"body": "Bad\x00copy"}}, []),
527
  ("binding expressions are refused", {**base, "bindings": {"expr": "1+1"}}, []),
528
  ("carrier cannot enable expressions", {**base, "bindings": {"expr": "1+1", "legacy": {"expr": "1+1"}}}, []),
 
612
  else:
613
  raise AssertionError("Malformed display passed")
614
  check("source rows remain unchanged", rt.get("product_table_workspace__shared") == source)
615
+ check("public library has no long dashes", not re.search("[" + chr(0x2013) + chr(0x2014) + "]", json.dumps(catalog_templates(), ensure_ascii=False)))
616
  print(json.dumps({"kinds": len(CATALOG_KINDS), "templates": len(pages),
617
  "checks": len(passed), "failed": 0, "tenant": "offline fake store"}, sort_keys=True))
618
 
api/routes_customers.py CHANGED
@@ -1351,9 +1351,29 @@ def _route_application(session, application, *, write=False):
1351
  source = app.get("sourceDatabase")
1352
  if source not in (MODULE, "ut_odoo_customers") and MODULE not in (app.get("compatibleDatabases") or ()):
1353
  raise err(409, "route_application_source", "this Routing App does not use the customers database")
 
1354
  return application
1355
 
1356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1357
  def _route_application_body(raw, application):
1358
  if "application" in raw and raw["application"] != application:
1359
  raise err(400, "route_application_mismatch", "the body must name the same Routing App as the query")
 
1351
  source = app.get("sourceDatabase")
1352
  if source not in (MODULE, "ut_odoo_customers") and MODULE not in (app.get("compatibleDatabases") or ()):
1353
  raise err(409, "route_application_source", "this Routing App does not use the customers database")
1354
+ _ensure_route_migration(session)
1355
  return application
1356
 
1357
 
1358
+ #: Tenants whose Route store already carries the R20 receipt in this process.
1359
+ _ROUTE_MIGRATED_TENANTS: set = set()
1360
+
1361
+
1362
+ def _ensure_route_migration(session):
1363
+ """R20: copy legacy Routes into every existing Routing App before the first App-scoped read."""
1364
+ from core import route_system
1365
+ tenant = str(getattr(session, "tenant", "") or "")
1366
+ if tenant in _ROUTE_MIGRATED_TENANTS:
1367
+ return
1368
+ try:
1369
+ if route_system.APPLICATION_MIGRATION not in route_system._store(session.runtime):
1370
+ migrate_routing_app_routes(session.runtime, tenant)
1371
+ except Exception:
1372
+ raise err(503, "route_migration_unavailable",
1373
+ "Existing Routes could not be copied into this Routing App. Try again")
1374
+ _ROUTE_MIGRATED_TENANTS.add(tenant)
1375
+
1376
+
1377
  def _route_application_body(raw, application):
1378
  if "application" in raw and raw["application"] != application:
1379
  raise err(400, "route_application_mismatch", "the body must name the same Routing App as the query")
api/routes_external.py CHANGED
@@ -3231,7 +3231,10 @@ def _plan_database_write(session, args):
3231
  g = routes_tables.ut_write_ctx(session, database)
3232
  rows = table.get("rows") or {}
3233
  if action == "record_create":
3234
- values = _database_value_plan(session, database, None, args.get("values"), g["fields"])
 
 
 
3235
  record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1)
3236
  before, after = None, values
3237
  else:
@@ -3258,6 +3261,20 @@ def _plan_database_write(session, args):
3258
  if action == "record_delete":
3259
  (target.get("rows") or {}).pop(record_id, None)
3260
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3261
  target.setdefault("rows", {})[record_id] = copy.deepcopy(after)
3262
  # This is part of the UI row writer's durable result, not an optional callback.
3263
  # Include newly encountered select values in the preview and the one guarded commit.
 
3231
  g = routes_tables.ut_write_ctx(session, database)
3232
  rows = table.get("rows") or {}
3233
  if action == "record_create":
3234
+ raw_values = args.get("values")
3235
+ # An empty object is a valid create when field defaults fill it (checked below).
3236
+ values = ({} if isinstance(raw_values, dict) and not raw_values else
3237
+ _database_value_plan(session, database, None, raw_values, g["fields"]))
3238
  record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1)
3239
  before, after = None, values
3240
  else:
 
3261
  if action == "record_delete":
3262
  (target.get("rows") or {}).pop(record_id, None)
3263
  else:
3264
+ try:
3265
+ if action == "record_create":
3266
+ # The grid's core insert rules: defaults, server-owned numbers, creation order.
3267
+ after = user_tables._new_row_values(target.get("fields") or [], after)
3268
+ if after is None:
3269
+ raise err(400, "bad_value", "A field default is not valid for its field.")
3270
+ if not after:
3271
+ raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
3272
+ user_tables.allocate_autonumbers(target, after)
3273
+ user_tables._stamp_row_creation(target, record_id)
3274
+ user_tables._validate_link_selection_values(
3275
+ target.get("fields") or [], values, bucket_after)
3276
+ except ValueError as exc:
3277
+ raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300])
3278
  target.setdefault("rows", {})[record_id] = copy.deepcopy(after)
3279
  # This is part of the UI row writer's durable result, not an optional callback.
3280
  # Include newly encountered select values in the preview and the one guarded commit.
api/routes_grid.py CHANGED
@@ -1792,7 +1792,8 @@ def _materialise_recurrence_cells(session, scope, events, results, fields):
1792
  updates.setdefault(rid, {})[key] = value
1793
  if not updates:
1794
  return 0
1795
- return user_tables.patch_many_cells(scope, updates, st=st)
 
1796
 
1797
 
1798
  # ── ⭐⭐ W47-T27 (owner instruction 13 / ruling R2): THE STORED DATE ROLLS FORWARD ON ITS OWN ──
 
1792
  updates.setdefault(rid, {})[key] = value
1793
  if not updates:
1794
  return 0
1795
+ # S76-T32: a person's grid write stamps that person as the modifier, never ''.
1796
+ return user_tables.patch_many_cells(scope, updates, st=st, by=getattr(session, "uname", None))
1797
 
1798
 
1799
  # ── ⭐⭐ W47-T27 (owner instruction 13 / ruling R2): THE STORED DATE ROLLS FORWARD ON ITS OWN ──
api/routes_tables.py CHANGED
@@ -2960,6 +2960,9 @@ def add_row(table_key: str, body: dict = Body(default=None),
2960
  try:
2961
  rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
2962
  rid=(body or {}).get("rid"), via=via)
 
 
 
2963
  except Exception:
2964
  raise err(503, "store_unavailable", "the row was not saved. The store refused")
2965
  if rid is None:
@@ -3596,6 +3599,9 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
3596
  except grid_events.StoreUnavailable:
3597
  raise err(503, "store_unavailable",
3598
  "the tenant store is unavailable. Your change was not saved")
 
 
 
3599
  # ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT.
3600
  #
3601
  # ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH
 
2960
  try:
2961
  rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
2962
  rid=(body or {}).get("rid"), via=via)
2963
+ except ValueError as exc:
2964
+ # A core value rule (negative policy, link condition, server-owned cell) names its reason.
2965
+ raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the row was refused")
2966
  except Exception:
2967
  raise err(503, "store_unavailable", "the row was not saved. The store refused")
2968
  if rid is None:
 
3599
  except grid_events.StoreUnavailable:
3600
  raise err(503, "store_unavailable",
3601
  "the tenant store is unavailable. Your change was not saved")
3602
+ except ValueError as exc:
3603
+ # A core value rule refused the cell before anything was stored. Name its reason (C4).
3604
+ raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the edit was refused")
3605
  # ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT.
3606
  #
3607
  # ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH
platform/core/user_tables.py CHANGED
@@ -6137,7 +6137,7 @@ def selftest_default_values():
6137
  assert set_fields(key, definitions, st=st)
6138
  assert get_one(key, st)['rows'] == before['rows']
6139
  for field in definitions:
6140
- saved = {**field, 'key': 'custom_' + field['key'], 'source': 'overlay'}
6141
  shared_overlay.put_field('default_fixture', saved['key'], saved, st=st)
6142
  saved = shared_overlay.fields('default_fixture', st=st)
6143
  projected = aios_grid.fields_from_workspace({'fields': saved}, fields_base=[])
 
6137
  assert set_fields(key, definitions, st=st)
6138
  assert get_one(key, st)['rows'] == before['rows']
6139
  for field in definitions:
6140
+ saved = {**field, 'key': 'custom_' + field['key'], 'source': 'overlay', 'createdBy': 'fixture'}
6141
  shared_overlay.put_field('default_fixture', saved['key'], saved, st=st)
6142
  saved = shared_overlay.fields('default_fixture', st=st)
6143
  projected = aios_grid.fields_from_workspace({'fields': saved}, fields_base=[])
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 321992a227d8bf4af6cfc6bf87218a7272a665960f3f6dfb3c9325a4afe9ffec
 
1
+ c74685c49d4ce77b91dc61a28e613852c53a073f7ea508c21fc682ad16a509a8
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -71,7 +71,7 @@ import { defaultViewConfig, headerMarksFor, useGridColumns } from "./useGridColu
71
  // group-safe slicer; the cap is retired, so the grid takes the pipeline's whole result. The
72
  // function is still exported from `useVisibleRows.ts` and still covered by `gridUx.test.ts` —
73
  // neither file is this ticket's to edit, and an unused export costs nothing. See the handoff.
74
- import { activeMeasureRuleIds, pendingMeasures, runPipeline,
75
  unresolvedConditions, useVisibleRows } from "./useVisibleRows";
76
  import { cleanPercent, computeAggNumbers, computeAggs, formatServerAgg, formatShare,
77
  resolveSummary, sharesTheTotal } from "./aggregations";
@@ -237,7 +237,7 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
237
  /* ⭐⭐ W41-T42 (owner instruction 23) — the pivot's whole vocabulary is DECLARED in `types.ts`
238
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
239
  same feature through other doors and neither of them may edit `types.ts`. */
240
- import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
241
  pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types";
242
  import type {
243
  ApplicationType,
@@ -1141,6 +1141,8 @@ interface FieldBuildExtra {
1141
  * `retypeField` (which emits `choice_rename`) and ignored by every create path: a field
1142
  * being CREATED has no values to migrate. */
1143
  renames?: { from: string; to: string }[];
 
 
1144
  }
1145
 
1146
  /**
@@ -1273,6 +1275,8 @@ function buildOverlayField(
1273
  : {}),
1274
  ...(type === "multiselect" ? { multi: true } : {}),
1275
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
 
 
1276
  };
1277
  }
1278
 
@@ -2077,6 +2081,8 @@ interface CustomerGridProps {
2077
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
2078
  /** Source record withheld from an editable picker over its own database. */
2079
  embeddedExcludeRecordId?: number;
 
 
2080
  /**
2081
  * ⭐⭐ W51-T06 · RULING R5 · CONTRACT C6 — **THE THIRD MODE.**
2082
  *
@@ -2170,6 +2176,8 @@ interface LinkGridModalProps {
2170
  editable?: boolean;
2171
  single?: boolean;
2172
  excludeRecordId?: number;
 
 
2173
  /** W56-T24: render the body as the Data module's own grid, with its display modes. */
2174
  cellView?: boolean;
2175
  /** W56-T25: the Sheet cell's own filter, shown in the grid's standard filter control. */
@@ -2194,7 +2202,7 @@ interface LinkGridModalProps {
2194
  // the two surfaces cannot drift into two popups that behave almost alike. W56-T24 adds optional
2195
  // chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact.
2196
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
2197
- excludeRecordId, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
2198
  headerActions, footer, initialPage, idsPending = false,
2199
  onOpenRecord, onSave, onClose }: LinkGridModalProps) {
2200
  const panelRef = useRef<HTMLDivElement>(null);
@@ -2267,6 +2275,7 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
2267
  embeddedIdsPending={!editable && idsPending}
2268
  onEmbeddedTotalChange={editable ? undefined : reportTotal}
2269
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
 
2270
  embeddedSelectable={editable}
2271
  embeddedSelectedIds={selectedIds}
2272
  onEmbeddedSelectionChange={changeSelectedIds}
@@ -2536,6 +2545,7 @@ function CustomerGridSurface({
2536
  embeddedSelectedIds = [],
2537
  onEmbeddedSelectionChange,
2538
  embeddedExcludeRecordId,
 
2539
  related,
2540
  cellView = false,
2541
  cellFilter,
@@ -2733,11 +2743,18 @@ function CustomerGridSurface({
2733
  * merge of values — the server's row wins outright, because by then it IS this row.
2734
  */
2735
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
 
 
2736
  const rawRows = useMemo(() => {
2737
  if (isCatalogApplication) return catalogData?.rows ?? [];
2738
- const base = embeddedExcludeRecordId !== undefined
2739
  ? fetchedRows.filter((row) => row.pid !== embeddedExcludeRecordId)
2740
  : fetchedRows;
 
 
 
 
 
2741
  const audit = payload?.workspace?.auditTimestamps ?? {};
2742
  const stamped: Row[] = base.map((row): Row => ({
2743
  ...row,
@@ -2747,8 +2764,8 @@ function CustomerGridSurface({
2747
  const known = new Set(stamped.map((r) => r.pid));
2748
  const extra = pendingRows.filter((r) => !known.has(r.pid));
2749
  return extra.length ? [...stamped, ...extra] : stamped;
2750
- }, [fetchedRows, embeddedExcludeRecordId, pendingRows, payload?.workspace?.auditTimestamps,
2751
- isCatalogApplication, catalogData]);
2752
  useEffect(() => {
2753
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
2754
  // pending rows, so it can never report that one has been absorbed. Pruning against the
@@ -4077,7 +4094,13 @@ function CustomerGridSurface({
4077
  if (!canMutateRecords) return undefined;
4078
  const seeded = seedValues();
4079
  const minted = mintRid();
4080
- const optimistic: Row = { ...seeded, pid: minted };
 
 
 
 
 
 
4081
  setPendingRows((cur) => [...cur, optimistic]);
4082
  setNewRowPid(minted);
4083
  const made = await addTableRow(scope, seeded, minted);
@@ -4114,7 +4137,7 @@ function CustomerGridSurface({
4114
  // `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the
4115
  // rows glide knew about when the gesture started, which is the row BEFORE this one.
4116
  return undefined;
4117
- }, [canMutateRecords, scope, seedValues, mintRid]);
4118
 
4119
  /* wave20 item 2 — measure key + window -> the columns that display it. Built ONCE per field
4120
  list and handed to every consumer of "which column is this rule about", so the tint
@@ -6177,8 +6200,13 @@ function CustomerGridSurface({
6177
  // readers racing one counter, which is how two rows end up sharing an id.
6178
  let any = false;
6179
  let moved = 0;
 
 
 
6180
  for (const r of op.rows) {
6181
- const made = await addTableRow(op.table, r.values as Record<string, unknown>, r.rid);
 
 
6182
  any = any || !!made; // a refusal already said why, in the server's words
6183
  // ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1`
6184
  // when the one it was asked for is no longer free — which happens if anything created
@@ -6218,7 +6246,7 @@ function CustomerGridSurface({
6218
  }
6219
  signal(TOAST_EVENT, describe(entry, dir));
6220
  },
6221
- [patchOverlay, withdrawPending, emitHostEvent]
6222
  );
6223
 
6224
  /**
@@ -9404,6 +9432,7 @@ function CustomerGridSurface({
9404
  per surface. Fixing the validator and the offer left the SEND still broken. */
9405
  ...(extra?.geocode ? { geocode: extra.geocode } : {}),
9406
  ...(field.agg ? { agg: field.agg } : {}),
 
9407
  }).then((made) => {
9408
  const reconcile = (current: Field[]) => {
9409
  const without = current.filter((item) => item.key !== field.key && item.key !== made?.key);
@@ -13637,6 +13666,7 @@ function CustomerGridSurface({
13637
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
13638
  single={linkField.link?.single === true}
13639
  excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
 
13640
  onSave={(ids) => patchAndRecord(
13641
  linkAt.pid,
13642
  { [linkField.key]: ids.join(",") },
 
71
  // group-safe slicer; the cap is retired, so the grid takes the pipeline's whole result. The
72
  // function is still exported from `useVisibleRows.ts` and still covered by `gridUx.test.ts` —
73
  // neither file is this ticket's to edit, and an unused export costs nothing. See the handoff.
74
+ import { activeMeasureRuleIds, matchFilterTree, pendingMeasures, runPipeline,
75
  unresolvedConditions, useVisibleRows } from "./useVisibleRows";
76
  import { cleanPercent, computeAggNumbers, computeAggs, formatServerAgg, formatShare,
77
  resolveSummary, sharesTheTotal } from "./aggregations";
 
237
  /* ⭐⭐ W41-T42 (owner instruction 23) — the pivot's whole vocabulary is DECLARED in `types.ts`
238
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
239
  same feature through other doors and neither of them may edit `types.ts`. */
240
+ import { AUDIT_FIELD_TYPES, buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
241
  pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types";
242
  import type {
243
  ApplicationType,
 
1141
  * `retypeField` (which emits `choice_rename`) and ignored by every create path: a field
1142
  * being CREATED has no values to migrate. */
1143
  renames?: { from: string; to: string }[];
1144
+ /** S76-T28: the value a new record takes when its creator leaves this field empty. */
1145
+ defaultValue?: Field["defaultValue"] | null;
1146
  }
1147
 
1148
  /**
 
1275
  : {}),
1276
  ...(type === "multiselect" ? { multi: true } : {}),
1277
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
1278
+ ...(extra?.defaultValue !== undefined && extra.defaultValue !== null
1279
+ ? { defaultValue: extra.defaultValue } : {}),
1280
  };
1281
  }
1282
 
 
2081
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
2082
  /** Source record withheld from an editable picker over its own database. */
2083
  embeddedExcludeRecordId?: number;
2084
+ /** S76-T33: an immutable candidate restriction for an editable link picker. */
2085
+ embeddedSelectionFilter?: FilterTree;
2086
  /**
2087
  * ⭐⭐ W51-T06 · RULING R5 · CONTRACT C6 — **THE THIRD MODE.**
2088
  *
 
2176
  editable?: boolean;
2177
  single?: boolean;
2178
  excludeRecordId?: number;
2179
+ /** S76-T33: the link field's condition. An editable picker offers only matching records. */
2180
+ selectionFilter?: FilterTree;
2181
  /** W56-T24: render the body as the Data module's own grid, with its display modes. */
2182
  cellView?: boolean;
2183
  /** W56-T25: the Sheet cell's own filter, shown in the grid's standard filter control. */
 
2202
  // the two surfaces cannot drift into two popups that behave almost alike. W56-T24 adds optional
2203
  // chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact.
2204
  export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
2205
+ excludeRecordId, selectionFilter, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
2206
  headerActions, footer, initialPage, idsPending = false,
2207
  onOpenRecord, onSave, onClose }: LinkGridModalProps) {
2208
  const panelRef = useRef<HTMLDivElement>(null);
 
2275
  embeddedIdsPending={!editable && idsPending}
2276
  onEmbeddedTotalChange={editable ? undefined : reportTotal}
2277
  embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
2278
+ embeddedSelectionFilter={editable ? selectionFilter : undefined}
2279
  embeddedSelectable={editable}
2280
  embeddedSelectedIds={selectedIds}
2281
  onEmbeddedSelectionChange={changeSelectedIds}
 
2545
  embeddedSelectedIds = [],
2546
  onEmbeddedSelectionChange,
2547
  embeddedExcludeRecordId,
2548
+ embeddedSelectionFilter,
2549
  related,
2550
  cellView = false,
2551
  cellFilter,
 
2743
  * merge of values — the server's row wins outright, because by then it IS this row.
2744
  */
2745
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
2746
+ const selectionFieldByKey = useMemo(() => new Map((payload?.fields ?? []).map(
2747
+ (field): [string, Field] => [field.key, field])), [payload?.fields]);
2748
  const rawRows = useMemo(() => {
2749
  if (isCatalogApplication) return catalogData?.rows ?? [];
2750
+ const unrestricted = embeddedExcludeRecordId !== undefined
2751
  ? fetchedRows.filter((row) => row.pid !== embeddedExcludeRecordId)
2752
  : fetchedRows;
2753
+ // S76-T33: the link's condition narrows candidates before counts; the server refuses the rest.
2754
+ const base = embeddedSelectionFilter?.nodes?.length
2755
+ ? unrestricted.filter((row) => matchFilterTree(embeddedSelectionFilter.nodes,
2756
+ embeddedSelectionFilter.conj ?? "and", row, selectionFieldByKey))
2757
+ : unrestricted;
2758
  const audit = payload?.workspace?.auditTimestamps ?? {};
2759
  const stamped: Row[] = base.map((row): Row => ({
2760
  ...row,
 
2764
  const known = new Set(stamped.map((r) => r.pid));
2765
  const extra = pendingRows.filter((r) => !known.has(r.pid));
2766
  return extra.length ? [...stamped, ...extra] : stamped;
2767
+ }, [fetchedRows, embeddedExcludeRecordId, embeddedSelectionFilter, selectionFieldByKey, pendingRows,
2768
+ payload?.workspace?.auditTimestamps, isCatalogApplication, catalogData]);
2769
  useEffect(() => {
2770
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
2771
  // pending rows, so it can never report that one has been absorbed. Pruning against the
 
4094
  if (!canMutateRecords) return undefined;
4095
  const seeded = seedValues();
4096
  const minted = mintRid();
4097
+ // S76-T28: paint the server's defaults at once. Core stores a boolean as Python's str().
4098
+ const defaults: Record<string, string> = Object.fromEntries(fields
4099
+ .filter((field) => field.defaultValue !== undefined && field.defaultValue !== null
4100
+ && !(field.key in seeded))
4101
+ .map((field) => [field.key, typeof field.defaultValue === "boolean"
4102
+ ? (field.defaultValue ? "True" : "False") : String(field.defaultValue)]));
4103
+ const optimistic: Row = { ...defaults, ...seeded, pid: minted };
4104
  setPendingRows((cur) => [...cur, optimistic]);
4105
  setNewRowPid(minted);
4106
  const made = await addTableRow(scope, seeded, minted);
 
4137
  // `undefined` is returned rather than glide's "bottom": "bottom" is resolved against the
4138
  // rows glide knew about when the gesture started, which is the row BEFORE this one.
4139
  return undefined;
4140
+ }, [canMutateRecords, scope, seedValues, mintRid, fields]);
4141
 
4142
  /* wave20 item 2 — measure key + window -> the columns that display it. Built ONCE per field
4143
  list and handed to every consumer of "which column is this rule about", so the tint
 
6200
  // readers racing one counter, which is how two rows end up sharing an id.
6201
  let any = false;
6202
  let moved = 0;
6203
+ // S76-T31/T32: the server assigns autonumber and audit cells and refuses them as input.
6204
+ const generated = new Set(fields.filter((field) => field.type === "autonumber"
6205
+ || AUDIT_FIELD_TYPES.includes(field.type)).map((field) => field.key));
6206
  for (const r of op.rows) {
6207
+ const values = Object.fromEntries(Object.entries(r.values as Record<string, unknown>)
6208
+ .filter(([key]) => !generated.has(key)));
6209
+ const made = await addTableRow(op.table, values, r.rid);
6210
  any = any || !!made; // a refusal already said why, in the server's words
6211
  // ⚠ THE ID IS PART OF WHAT IS BEING UNDONE, and `add_row` falls back to `max(id)+1`
6212
  // when the one it was asked for is no longer free — which happens if anything created
 
6246
  }
6247
  signal(TOAST_EVENT, describe(entry, dir));
6248
  },
6249
+ [patchOverlay, withdrawPending, emitHostEvent, fields]
6250
  );
6251
 
6252
  /**
 
9432
  per surface. Fixing the validator and the offer left the SEND still broken. */
9433
  ...(extra?.geocode ? { geocode: extra.geocode } : {}),
9434
  ...(field.agg ? { agg: field.agg } : {}),
9435
+ ...(field.defaultValue !== undefined ? { defaultValue: field.defaultValue } : {}),
9436
  }).then((made) => {
9437
  const reconcile = (current: Field[]) => {
9438
  const without = current.filter((item) => item.key !== field.key && item.key !== made?.key);
 
13666
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
13667
  single={linkField.link?.single === true}
13668
  excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
13669
+ selectionFilter={linkField.link?.selectionFilter}
13670
  onSave={(ids) => patchAndRecord(
13671
  linkAt.pid,
13672
  { [linkField.key]: ids.join(",") },
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -3430,6 +3430,7 @@ export default function RecordDetail({
3430
  editable={!frame && mayEditField(openLinkField, viewer) && !openLinkField.link.on}
3431
  single={openLinkField.link.single === true}
3432
  excludeRecordId={openLinkField.link.table === recordTable ? Number(record.pid) : undefined}
 
3433
  onSave={(ids) => onNotesCommit(openLinkField.key, ids.join(","))}
3434
  onOpenRecord={(pid, table, row, rowFields) => {
3435
  pushFrame(pid, table, row, rowFields, openLinkField);
 
3430
  editable={!frame && mayEditField(openLinkField, viewer) && !openLinkField.link.on}
3431
  single={openLinkField.link.single === true}
3432
  excludeRecordId={openLinkField.link.table === recordTable ? Number(record.pid) : undefined}
3433
+ selectionFilter={openLinkField.link.selectionFilter}
3434
  onSave={(ids) => onNotesCommit(openLinkField.key, ids.join(","))}
3435
  onOpenRecord={(pid, table, row, rowFields) => {
3436
  pushFrame(pid, table, row, rowFields, openLinkField);
web/src/customer-grid/aggregations.ts CHANGED
@@ -474,7 +474,8 @@ function wearColumnUnit(field: Field, clean: number): string {
474
  //
475
  // `numberText` is the single implementation `display.ts::valueText` uses for the cells, so the
476
  // fold now wears the column's real unit by CALLING it rather than by resembling it.
477
- return field.type === "currency" ? "$" + numberText(clean, field.format)
 
478
  : field.type === "pct" ? numberText(clean, field.format) + "%"
479
  : numberText(clean, field.format);
480
  }
 
474
  //
475
  // `numberText` is the single implementation `display.ts::valueText` uses for the cells, so the
476
  // fold now wears the column's real unit by CALLING it rather than by resembling it.
477
+ // S76-T29: the field's own symbol, once; `$` only when a currency field names none.
478
+ return field.type === "currency" ? numberText(clean, field.format, "$")
479
  : field.type === "pct" ? numberText(clean, field.format) + "%"
480
  : numberText(clean, field.format);
481
  }
web/src/customer-grid/export.ts CHANGED
@@ -424,10 +424,12 @@ function numFmtCode(f: Field): string | null {
424
  // decimal precision. Abbreviated fields export the full summable number.
425
  const numeric = d != null ? `${grouped ? "#,##0" : "0"}${dec(d)}`
426
  : grouped ? "#,##0.###" : "General";
427
- if (f.type === "currency") return `"$"${numeric}`;
428
  // The stored magnitude already uses percent units. Quote the suffix so Excel cannot
429
  // multiply it by 100; Field decimals and grouping still apply to the numeric portion.
430
  if (f.type === "pct") return `${numeric}"%"`;
 
 
 
431
  return numeric === "General" ? null : numeric;
432
  }
433
 
 
424
  // decimal precision. Abbreviated fields export the full summable number.
425
  const numeric = d != null ? `${grouped ? "#,##0" : "0"}${dec(d)}`
426
  : grouped ? "#,##0.###" : "General";
 
427
  // The stored magnitude already uses percent units. Quote the suffix so Excel cannot
428
  // multiply it by 100; Field decimals and grouping still apply to the numeric portion.
429
  if (f.type === "pct") return `${numeric}"%"`;
430
+ // S76-T29: the same symbol `numberText` paints, `$` only for a currency field naming none.
431
+ const symbol = fmt?.currencySymbol ?? (f.type === "currency" ? "$" : "");
432
+ if (symbol) return `"${symbol}${symbol === "$" ? "" : " "}"${numeric}`;
433
  return numeric === "General" ? null : numeric;
434
  }
435
 
web/src/viz/seriesData.ts CHANGED
@@ -28,6 +28,8 @@ export interface WireField {
28
  export const VIZ_FIELD_TYPES: ReadonlySet<string> = new Set([
29
  "text", "status", "currency", "int", "date", "pct", "select", "user",
30
  "multiselect", "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
 
 
31
  // Wave 18 C5 ④b — the RUNTIME copy of the vocabulary. A `Set` is not a `Record`: the
32
  // compiler stays green when this goes stale and `asFields` silently downgrades the column
33
  // to text. When a `FieldType` joins the union, this line moves WITH the batch.
 
28
  export const VIZ_FIELD_TYPES: ReadonlySet<string> = new Set([
29
  "text", "status", "currency", "int", "date", "pct", "select", "user",
30
  "multiselect", "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
31
+ // S76-T30 to T32: the five new kinds keep their own type in a chart, never a text downgrade.
32
+ "long_text", "autonumber", "created_by", "last_modified_time", "last_modified_by",
33
  // Wave 18 C5 ④b — the RUNTIME copy of the vocabulary. A `Set` is not a `Record`: the
34
  // compiler stays green when this goes stale and `asFields` silently downgrades the column
35
  // to text. When a `FieldType` joins the union, this line moves WITH the batch.