Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Deploy AIOS web (React glide grid + FastAPI slice)
Browse filesFiles changed (34)
- RELEASES.json+2-519
- VERSION+1-1
- api/amazon_relational.py+21-6
- api/app_templates.py+2-2
- api/application_registry.py+20-12
- api/main.py+6-4
- api/odoo_relational.py+1-1
- api/registry_source.py+6-4
- api/routes_competitor_watch.py+5-13
- api/routes_grid.py+4-2
- platform/aios_grid.py+8
- platform/core/grid_events.py+8-3
- platform/core/received_changes.py+327-82
- platform/core/registry.py+1-1
- platform/core/shared_overlay.py+11
- platform/core/table_store.py+56-7
- platform/harness/amazon_client.py+3-1
- platform/harness/amazon_store.py+181-16
- platform/harness/datastore.py+20-4
- platform/modules/amazon_profit.py+112-4
- platform/modules/competitor_watch.py+185-108
- platform/modules/product_data.py+8-3
- web/public/AIOS_DEPLOY_RECEIPT+1-1
- web/src/apps/amazon-profit/AppView.tsx+7-1
- web/src/apps/amazon-profit/ProjectsList.tsx+1-1
- web/src/customer-grid/CustomerGrid.tsx+29-38
- web/src/customer-grid/Toolbar.tsx+1
- web/src/customer-grid/appHostTypes.ts+2
- web/src/customer-grid/seam.ts+4-3
- web/src/customer-grid/types.ts+2
- web/src/customer-grid/useGridColumns.ts+33-16
- web/src/customer-grid/viewOps.ts+25-10
- web/src/filter-kit/FieldsHidePanel.tsx+14-5
- web/src/shell/Shell.tsx+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521{"current": "caef761dd5af969155c5c31f930259757738efe4 (caef761dd5af9)","releases": [{"version": "v87","sha": "288b6b8793041","date": "2026-11-12","subject": "release(sdlc85): release lessons and log line"},{"version": "v86","sha": "108bd7510dcd2","date": "2026-10-27","subject": "release v86: SDLC 80 (owner override, 3 booked FAILs to SDLC 81)"},{"version": "v85","sha": "b36dd4992153e","date": "2026-10-25","subject": "Merge remote-tracking branch 'origin/master' into hfstage/sdlc79-release"},{"version": "v84","sha": "7bb3a2e09e138","date": "2026-10-24","subject": "release(sdlc78): v84 QA records the staging build change and what v84 excludes"},{"version": "v83","sha": "9b7471968e79d","date": "2026-10-21","subject": "release v83"},{"version": "v82","sha": "9c61b1ee94d0c","date": "2026-10-17","subject": "release v82"},{"version": "v81","sha": "e141ccc85ef0c","date": "2026-10-15","subject": "release v81"},{"version": "v80","sha": "869b8fcc62ac7","date": "2026-10-13","subject": "release v80"},{"version": "v79","sha": "406417b8ded0e","date": "2026-10-13","subject": "release v79"},{"version": "v78","sha": "aad6561d63e6c","date": "2026-10-09","subject": "release v78: SDLC 71 with the D-7536 and D-7537 repairs"},{"version": "v77","sha": "e741e5ca604d4","date": "2026-10-05","subject": "release v77"},{"version": "v76","sha": "7990f03e02544","date": "2026-10-01","subject": "release v76"},{"version": "v75","sha": "2c5146981ccfb","date": "2026-09-19","subject": "release v75"},{"version": "v74","sha": "40dceba9262ec","date": "2026-09-14","subject": "release v74: waves 58+59 incl. the Amazon credential door (W59-T21/22/23) and sync producer (W59-T42); hotfix promote so"},{"version": "v73","sha": "bb94de5665e62","date": "2026-09-13","subject": "release v73"},{"version": "v71","sha": "96143dc6fb656","date": "2026-09-04","subject": "release v71 - wave 51, QA'd 24 PASS / 6 FAIL / 5 UNPROVEN"},{"version": "v70","sha": "eedfb6a00163c","date": "2026-09-03","subject": "release v70 - wave 50 (grid analytics, the Sheet as a spreadsheet, view trash and audit)"},{"version": "v69","sha": "8598f56293a00","date": "2026-09-02","subject": "release v69: wave48-continuation validated + hotfixes v67/v68/d4e3e31 + go-live QA repairs (Supplier option limit, optio"},{"version": "v68","sha": "62b065a2610a4","date": "2026-09-01","subject": "release v68: unified holiday date offsets"},{"version": "v67","sha": "3b2241982cf73","date": "2026-09-01","subject": "release v67"},{"version": "v66","sha": "73c94f0767404","date": "2026-08-31","subject": "release v66"},{"version": "v65","sha": "9f6cfedb8a43a","date": "2026-08-31","subject": "release v65"},{"version": "v64","sha": "bb8985c6e73e1","date": "2026-08-31","subject": "release v64"},{"version": "v63","sha": "ec75cb8f34129","date": "2026-08-31","subject": "release v63"},{"version": "v62","sha": "2c8f702c964fd","date": "2026-08-31","subject": "release v62"},{"version": "v61","sha": "bbc4c0760ab52","date": "2026-08-30","subject": "v61 - wave 46 hotfix: D-590 schema overlay reaches the grid read (all three assemblies), D-599 route to zone association"},{"version": "v60","sha": "dd1b0620210e4","date": "2026-08-30","subject": "v60 - wave 46"},{"version": "v59","sha": "3cb73ce8021ed","date": "2026-08-29","subject": "release v59"},{"version": "v58","sha": "c526cede82f92","date": "2026-08-29","subject": "release v58"},{"version": "v57","sha": "4859c035e6a7d","date": "2026-08-29","subject": "release v57"},{"version": "v56","sha": "2970b729e8f04","date": "2026-08-28","subject": "release v56"},{"version": "v55","sha": "b766b904b8fa5","date": "2026-08-28","subject": "release v55"},{"version": "v54","sha": "6a8e99a064d99","date": "2026-08-27","subject": "release v54"},{"version": "v53","sha": "89ed2cb867da5","date": "2026-08-24","subject": "release v53"},{"version": "v52","sha": "8263493762416","date": "2026-08-23","subject": "release v52"},{"version": "v51","sha": "5740d20fa585e","date": "2026-08-23","subject": "release v51"},{"version": "v50","sha": "8027c83d1da69","date": "2026-08-23","subject": "release v50"},{"version": "v49","sha": "9a14c01a48a40","date": "2026-08-23","subject": "release v49"},{"version": "v48","sha": "3c69fd93da7c4","date": "2026-08-23","subject": "release v48"},{"version": "v47","sha": "917f9a0eb5097","date": "2026-08-23","subject": "release v47"},{"version": "v46","sha": "a8dc531b5078e","date": "2026-08-23","subject": "release v46"},{"version": "v45","sha": "0b2b5010d86f0","date": "2026-08-23","subject": "release v45"},{"version": "v44","sha": "a7877aaf20ffd","date": "2026-08-23","subject": "Hotfix: allow renaming the active Map view"},{"version": "v43","sha": "e2ba4616fa0fd","date": "2026-08-23","subject": "release v43"},{"version": "v42","sha": "25b885e6373a7","date": "2026-08-23","subject": "release v42"},{"version": "v41","sha": "1d6adcc3c3ac5","date": "2026-08-22","subject": "v41 vertical route navigation"},{"version": "v40","sha": "1451837168f3c","date": "2026-08-22","subject": "release v40 route UI correction"},{"version": "v39","sha": "a78bdf00e38e5","date": "2026-08-21","subject": "W39 clean stale migration targets"},{"version": "v38","sha": "a556631cf979d","date": "2026-08-21","subject": "W39 reversible Live store cutover"},{"version": "v37","sha": "1ddd8cf82379b","date": "2026-08-21","subject": "W39: coalesce derived workspace reads"},{"version": "v36","sha": "51db3b7fee2ce","date": "2026-08-21","subject": "W39 share-field oid repair"},{"version": "v35","sha": "0f642129c8f77","date": "2026-08-21","subject": "W39 visual QA fixture"},{"version": "v34","sha": "cb4caa188e05a","date": "2026-08-21","subject": "W39 Staging PostgreSQL egress controls"},{"version": "v33","sha": "2b115e573d6ab","date": "2026-08-21","subject": "W39: stop nonproduction Postgres background egress"},{"version": "v32","sha": "b47b27ca7b2ae","date": "2026-08-21","subject": "W39: repair Staging Postgres projection"},{"version": "v31","sha": "8880a49a244ee","date": "2026-08-21","subject": "v31: Wave 39 staging candidate"},{"version": "v30","sha": "71776ca6c8dfa","date": "2026-08-20","subject": "v30: W39-T29 Member-owned View first-share hotfix"},{"version": "v29","sha": "55ced5018ff26","date": "2026-08-18","subject": "v29: the build staging has been running since 2026-08-18 (55ced50)."},{"version": "v28","sha": "2793e4ba53dc1","date": "2026-08-18","subject": "release v28"},{"version": "v27","sha": "c05a794837fc2","date": "2026-08-18","subject": "release v27"},{"version": "v25","sha": "bc248295ed660","date": "2026-08-14","subject": "v25 - wave 32's LIVE build (deployed 2026-08-13, bc24829)"},{"version": "v26","sha": "6a642e139cfaa","date": "2026-08-14","subject": "v26 - wave 33's build (deployed 2026-08-14, 6a642e1)"},{"version": "v24","sha": "514d8292ce734","date": "2026-08-09","subject": "release v24"},{"version": "v23","sha": "44cc28380fca6","date": "2026-08-09","subject": "release v23"},{"version": "v22","sha": "f14e199ff32f4","date": "2026-08-09","subject": "release v22"},{"version": "v21","sha": "5fdffce8b5586","date": "2026-08-09","subject": "release v21"},{"version": "v20","sha": "442e4a1430a77","date": "2026-08-09","subject": "release v20"},{"version": "v19","sha": "94cb4a4dfdfef","date": "2026-08-09","subject": "release v19"},{"version": "v18","sha": "0106ef9498056","date": "2026-08-09","subject": "release v18"},{"version": "v17","sha": "308240cc75e87","date": "2026-08-09","subject": "release v17"},{"version": "v16","sha": "a804df54430f2","date": "2026-08-09","subject": "release v16"},{"version": "v15","sha": "6b84d7264c81e","date": "2026-08-09","subject": "release v15"},{"version": "v14","sha": "bee5eaf5b5cbd","date": "2026-08-07","subject": "release v14"},{"version": "v13","sha": "314c0e368b1d2","date": "2026-08-06","subject": "release v13"},{"version": "v12","sha": "4908f399785d2","date": "2026-08-06","subject": "release v12"},{"version": "v11","sha": "312661712b980","date": "2026-08-05","subject": "release v11"},{"version": "v10","sha": "43f8042874969","date": "2026-08-05","subject": "release v10"},{"version": "v9","sha": "2e26f57396b19","date": "2026-08-05","subject": "release v9"},{"version": "v8","sha": "8073b3ecbac3d","date": "2026-08-05","subject": "release v8"},{"version": "v7","sha": "b1c5a7e9b8486","date": "2026-08-05","subject": "release v7"},{"version": "v6","sha": "a344020f114ac","date": "2026-08-05","subject": "release v6"},{"version": "v5","sha": "c0b0fbb40a7b5","date": "2026-08-05","subject": "release v5"},{"version": "v4","sha": "de5037ff1c8fd","date": "2026-08-05","subject": "release v4"},{"version": "v3","sha": "6b9fa62d93e87","date": "2026-08-05","subject": "release v3"},{"version": "v2","sha": "fd05861998586","date": "2026-08-04","subject": "release v2"},{"version": "v1","sha": "5b4e2c4bc3f3c","date": "2026-08-04","subject": "release v1"}]}1234{"current": "a5862e8a70bdc59e7f25ddaafd72fd83e13b2b55 (a5862e8a70)","releases": []}
1caef761dd5af969155c5c31f930259757738efe4 (caef761dd5af9)1a5862e8a70bdc59e7f25ddaafd72fd83e13b2b55 (a5862e8a70)
871 unmodified lines87287387487587687716 unmodified lines89489589689789889990090190290390490590690717 unmodified lines92592692792892993093193293346 unmodified lines980981982983984985871 unmodified linesf'WHERE "_identity_rowid" = {source}.rowid)')def _grid_identity(cur, key, names, prepared, is_view):table = key.removeprefix(PREFIX)identity_names = names | prepared16 unmodified linescomplete = " AND ".join(f"{value(name)} IS NOT NULL" for name in keys)fallback = sorted(set((*keys, *_fallback_columns(table))))partition = ", ".join(value(name, peer) for name in fallback)if is_view:if legacy:partition += f', ({peer}."_connection_id" = {legacy})'ranks.append(f'row_number() OVER (PARTITION BY {partition} 'f'ORDER BY {peer}."_amazon_publication_order") - 1 AS {_quoted(label)}')occurrence = f'CAST({source}.{_quoted(label)} AS VARCHAR)'else:peer_complete = " AND ".join(f"{value(name, peer)} IS NOT NULL" for name in keys)predicate = f'{peer}."_connection_id" = {legacy} AND ' if legacy else ''occurrence = _missing_occurrence(source, partition, peer_complete, predicate)if not legacy and amazon_schema.IDENTITY_OCCURRENCE in prepared:17 unmodified linesident = f'CASE WHEN {source}."_connection_id"={literal} THEN {old_ident} ELSE {ident} END'spec = {'id': ident}if ranks:spec['from_sql'] = (f'(SELECT *, {", ".join(ranks)} FROM 'f'(SELECT *, row_number() OVER () - 1 AS "_amazon_publication_order" 'f'FROM {source}) AS {peer}) AS {source}')if not is_view and table not in amazon_store.DERIVED_TABLES:spec['page_key'] = f'{source}.rowid'return spec46 unmodified linesif schema is None:continuespec = grid_source(cur, key, allow_lookups=False, status=None, schema=schema)if amazon_schema.CONNECTION_ID in dict(schema[0]):spec['cols'][amazon_schema.CONNECTION_ID] = ('"_connection_id"', _text)result[key] = spec871 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389416 unmodified lines91191291391491591691791891992092192292317 unmodified lines94194294394494594694746 unmodified lines9949959969979989991000871 unmodified linesf'WHERE "_identity_rowid" = {source}.rowid)')def _occurrence_view(source, peer, ranks):"""Number equal-key occurrences over incomplete-key rows only, in publication order.A complete key never shares a partition with an incomplete one, so the narrow window overincomplete rows yields the same occurrence a whole-table window would."""order = '"_amazon_publication_order"'numbered = f'(SELECT *, row_number() OVER () - 1 AS {order} FROM {source})'joins = "".join(f' LEFT JOIN (SELECT {order}, row_number() OVER (PARTITION BY {partition} 'f'ORDER BY {peer}.{order}) - 1 AS {_quoted(label)} FROM {numbered} AS {peer} 'f'WHERE NOT ({complete})) AS "_amazon_rank_{index}" USING ({order})'for index, (label, partition, complete) in enumerate(ranks))labels = ", ".join(f'"_amazon_rank_{index}".{_quoted(label)}' for index, (label, _p, _c) in enumerate(ranks))return f'(SELECT {peer}.*, {labels} FROM {numbered} AS {peer}{joins}) AS {source}'def _grid_identity(cur, key, names, prepared, is_view):table = key.removeprefix(PREFIX)identity_names = names | prepared16 unmodified linescomplete = " AND ".join(f"{value(name)} IS NOT NULL" for name in keys)fallback = sorted(set((*keys, *_fallback_columns(table))))partition = ", ".join(value(name, peer) for name in fallback)peer_complete = " AND ".join(f"{value(name, peer)} IS NOT NULL" for name in keys)if is_view:if legacy:partition += f', ({peer}."_connection_id" = {legacy})'ranks.append((label, partition, peer_complete))occurrence = f'CAST({source}.{_quoted(label)} AS VARCHAR)'else:predicate = f'{peer}."_connection_id" = {legacy} AND ' if legacy else ''occurrence = _missing_occurrence(source, partition, peer_complete, predicate)if not legacy and amazon_schema.IDENTITY_OCCURRENCE in prepared:17 unmodified linesident = f'CASE WHEN {source}."_connection_id"={literal} THEN {old_ident} ELSE {ident} END'spec = {'id': ident}if ranks:spec['from_sql'] = _occurrence_view(source, peer, ranks)if not is_view and table not in amazon_store.DERIVED_TABLES:spec['page_key'] = f'{source}.rowid'return spec46 unmodified linesif schema is None:continuespec = grid_source(cur, key, allow_lookups=False, status=None, schema=schema)spec['observation_tables'] = [SOURCE[key]]if amazon_schema.CONNECTION_ID in dict(schema[0]):spec['cols'][amazon_schema.CONNECTION_ID] = ('"_connection_id"', _text)result[key] = spec
123 unmodified lines124125126127128129130131132123 unmodified lines"ut_amzn_fba_shipped_sales", "ut_amzn_mfn_returns", "ut_amzn_settlements","ut_amzn_transactions", "ut_amzn_ads_sp_campaigns", "ut_amzn_ads_sb_campaigns","ut_amzn_ads_sd_campaigns"), optional_sources=("product_data",), proposes=False),# Project management reads its own module tables (ut_amazon_*), so it declares no# source: a cold mirror must not refuse an App whose rows live in the store._amazon("amazon_profit", "Project management", "See profit, ads and stock for every SKU.","Create value", (),optional_sources=("ut_amzn_search_query_performance", "ut_amzn_order_items","ut_amzn_brand_analytics", "ut_amzn_listings", "ut_amzn_catalog_items",123 unmodified lines124125126127128129130131132123 unmodified lines"ut_amzn_fba_shipped_sales", "ut_amzn_mfn_returns", "ut_amzn_settlements","ut_amzn_transactions", "ut_amzn_ads_sp_campaigns", "ut_amzn_ads_sb_campaigns","ut_amzn_ads_sd_campaigns"), optional_sources=("product_data",), proposes=False),# Project manager reads its own module tables (ut_amazon_*), so it declares no# source: a cold mirror must not refuse an App whose rows live in the store._amazon("amazon_profit", "Project manager", "See profit, ads and stock for every SKU.","Create value", (),optional_sources=("ut_amzn_search_query_performance", "ut_amzn_order_items","ut_amzn_brand_analytics", "ut_amzn_listings", "ut_amzn_catalog_items",
1437 unmodified lines1438143914401441144214431444597 unmodified lines2042204320442045204620472048204920502051205220532054205520567 unmodified lines20642065206620672068206920702071207220732074207540 unmodified lines21162117211821192120212121227 unmodified lines213021312132213321342135213642 unmodified lines21792180218121822183218421851 unmodified line21872188218921902191219221931437 unmodified linesdef _nav_placement(app, index):"""Put default Project management entries first without rewriting stored placements."""placement = app.get("navPlacement")# Every install stores the template default {"section": "app", "order": 0}, so order 0 is the# default here, not a choice; any other stored placement wins.597 unmodified lines#: Marker of the Command Center seed. Once written, a deleted Command Center App is never seeded again.COMMAND_CENTER_MARKER = "commandCenterApplication"def _migrate_project_management_names(runtime):"""Rename only the two original defaults in each tenant-bound App document."""def original(app):return (isinstance(app, dict) and app.get("tenant") == runtime.keyand app.get("templateKind") == "amazon_profit"and app.get("createdBy") == "loopable" and app.get("revision") == 1and app.get("name") in ("Command Center", "Amazon Command Center"))documents = {_KEY: _clean_doc(_read_strict(runtime, _KEY)), **_record_documents(runtime)}count = 07 unmodified linesdoc = _clean_doc(raw)for app in doc["applications"].values():if original(app):app["name"] = "Project management"changed.append(app["id"])return docif _update_document(runtime, apply, key=key) is False:raise ApplicationError("The Project management name was not saved.")count += len(changed)return count40 unmodified linesreturn tablesif runtime.update(user_tables.STORE_KEY, apply, flush="sync") is False:raise ApplicationError("The Project management field order was not saved.")return len(changed)7 unmodified linesdef ensure_command_center_application(runtime, tenant):"""Reconcile Project management defaults and seed one shared App when its table exists.A tenant without the table gets no marker, so a later boot seeds it once the table exists."""42 unmodified linesreturn rawapp = _build_application(tenant, "loopable",{"name": "Project management", "templateKind": "amazon_profit","navPlacement": {"section": "app", "order": 0}})app["share"] = {"mode": "tenant", "users": []}doc["applications"][app["id"]] = app1 unmodified linemigrations[COMMAND_CENTER_MARKER] = {"at": write_execution.utcnow().isoformat(), **result}return docif _update_document(runtime, apply) is False:raise ApplicationError("The Project management App was not saved.")return result1437 unmodified lines1438143914401441144214431444597 unmodified lines204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320647 unmodified lines20722073207420752076207720782079208020812082208340 unmodified lines21242125212621272128212921307 unmodified lines213821392140214121422143214442 unmodified lines21872188218921902191219221931 unmodified line21952196219721982199220022011437 unmodified linesdef _nav_placement(app, index):"""Put default Project manager entries first without rewriting stored placements."""placement = app.get("navPlacement")# Every install stores the template default {"section": "app", "order": 0}, so order 0 is the# default here, not a choice; any other stored placement wins.597 unmodified lines#: Marker of the Command Center seed. Once written, a deleted Command Center App is never seeded again.COMMAND_CENTER_MARKER = "commandCenterApplication"#: The amazon_profit App's default name, and the earlier defaults the boot migration replaces.PROJECT_APP_NAME = _app_templates.BY_KIND["amazon_profit"]["label"]_PROJECT_APP_PRIOR_NAME = "Project management"_PROJECT_APP_SEED_NAMES = ("Command Center", "Amazon Command Center")def _migrate_project_management_names(runtime):"""Rename only earlier default names in each tenant-bound App document; a user's name stays."""def original(app):if not (isinstance(app, dict) and app.get("tenant") == runtime.keyand app.get("templateKind") == "amazon_profit"):return False# An editor save bumps revision, so the prior default name alone marks a default.if app.get("name") == _PROJECT_APP_PRIOR_NAME:return Truereturn (app.get("createdBy") == "loopable" and app.get("revision") == 1and app.get("name") in _PROJECT_APP_SEED_NAMES)documents = {_KEY: _clean_doc(_read_strict(runtime, _KEY)), **_record_documents(runtime)}count = 07 unmodified linesdoc = _clean_doc(raw)for app in doc["applications"].values():if original(app):app["name"] = PROJECT_APP_NAMEchanged.append(app["id"])return docif _update_document(runtime, apply, key=key) is False:raise ApplicationError("The Project manager name was not saved.")count += len(changed)return count40 unmodified linesreturn tablesif runtime.update(user_tables.STORE_KEY, apply, flush="sync") is False:raise ApplicationError("The Project manager field order was not saved.")return len(changed)7 unmodified linesdef ensure_command_center_application(runtime, tenant):"""Reconcile Project manager defaults and seed one shared App when its table exists.A tenant without the table gets no marker, so a later boot seeds it once the table exists."""42 unmodified linesreturn rawapp = _build_application(tenant, "loopable",{"name": PROJECT_APP_NAME, "templateKind": "amazon_profit","navPlacement": {"section": "app", "order": 0}})app["share"] = {"mode": "tenant", "users": []}doc["applications"][app["id"]] = app1 unmodified linemigrations[COMMAND_CENTER_MARKER] = {"at": write_execution.utcnow().isoformat(), **result}return docif _update_document(runtime, apply) is False:raise ApplicationError("The Project manager App was not saved.")return result
4581 unmodified lines45824583458445854586458745884589459045914592459345944595459645974598459946004581 unmodified linesif (data_binding.gate_process() or process_role.role() not in ("web", "all")or os.environ.get("AIOS_BOOT_APP_MIGRATIONS") == "0"or not (os.environ.get("SPACE_ID") or os.environ.get("AIOS_BOOT_APP_MIGRATIONS") == "1")or _freeze_holds("Project management defaults")):returnimport application_registryimport tenant_scanfrom harness import runtime# This startup barrier changes metadata only. Heavy migrations keep their worker owner.for slug, rt in tenant_scan.live_tenants(runtime):try:result = application_registry.reconcile_project_management_defaults(rt, slug)print(f"[aios-api] Project management defaults {slug}: "f"names={result['renamed']} fields={result['reordered']}")except Exception as exc:print(f"[aios-api] Project management defaults {slug}: {type(exc).__name__}")@app.on_event("startup")4581 unmodified lines4582458345844585458645874588458945904591459245934594459545964597459845994600460146024581 unmodified linesif (data_binding.gate_process() or process_role.role() not in ("web", "all")or os.environ.get("AIOS_BOOT_APP_MIGRATIONS") == "0"or not (os.environ.get("SPACE_ID") or os.environ.get("AIOS_BOOT_APP_MIGRATIONS") == "1")or _freeze_holds("Project manager defaults")):returnimport application_registryimport tenant_scanfrom harness import runtimefrom modules import amazon_profit# This startup barrier changes metadata only. Heavy migrations keep their worker owner.for slug, rt in tenant_scan.live_tenants(runtime):try:result = application_registry.reconcile_project_management_defaults(rt, slug)views = amazon_profit.reconcile_views(rt)print(f"[aios-api] Project manager defaults {slug}: "f"names={result['renamed']} fields={result['reordered']} views={views}")except Exception as exc:print(f"[aios-api] Project manager defaults {slug}: {type(exc).__name__}")@app.on_event("startup")
7471 unmodified lines74727473747474757476747774787471 unmodified linesif type(after) is not int or count != total or after != total:raise Refused("Odoo returned an incomplete or changed population. The prior database was preserved.")save("live")datastore._save_state(con, source, "live", last, None)con, _path = datastore._mirror_connection(rt.key, rt)try:spec = dynamic_model_source(con, key, tenant_key=rt.key)7471 unmodified lines74727473747474757476747774787471 unmodified linesif type(after) is not int or count != total or after != total:raise Refused("Odoo returned an incomplete or changed population. The prior database was preserved.")save("live")datastore._save_populated_state(con, source, last)con, _path = datastore._mirror_connection(rt.key, rt)try:spec = dynamic_model_source(con, key, tenant_key=rt.key)
557 unmodified lines5585595605615625635645655665673 unmodified lines571572573574575576577578557 unmodified lines[self.uname, key, 'members'], self.row_ids, source_limit=cohort.MAX_MEMBERS * 2))for key, meta in definitions.items() if isinstance(meta, dict)}}elif name == 'loopable_route_system':meta_key = ('route_definitions', name)if meta_key not in self.metadata or fresh:base = object_values(self._runtime, name, omit=('routes', 'zones'))base['routes'] = [(index, route) for batch in array_values(self._runtime, name,['routes'], drop=('stops',)) for index, route in batch]base['zones'] = [meta for batch in array_values(self._runtime, name, ['zones'], drop=('memberPids', 'member_pids', 'memberships', 'legacyMembershipEvidence')) for _, meta in batch]3 unmodified linesvalue['routes'], value['zones'] = [], []for index, route in saved['routes']:if isinstance(route, dict):# A stop names a customer pid, so a product batch reads no stop membership.route = dict(route, stops=[] if self.table_key == 'product_data' else self._selected_json(name, ['routes', index, 'stops'], array=True, id_key='customerPid'))value['routes'].append(route)value['zones'] = copy.deepcopy(saved['zones'])557 unmodified lines5585595605615625635645655665675685695703 unmodified lines574575576577578579580557 unmodified lines[self.uname, key, 'members'], self.row_ids, source_limit=cohort.MAX_MEMBERS * 2))for key, meta in definitions.items() if isinstance(meta, dict)}}elif name == 'loopable_route_system':# The product shape omits routes, so the cached definitions are keyed by that shape.meta_key = ('route_definitions', name, self.table_key == 'product_data')if meta_key not in self.metadata or fresh:base = object_values(self._runtime, name, omit=('routes', 'zones'))# A Route stops at customers, so a product batch reads only the Zone definitions.base['routes'] = [] if self.table_key == 'product_data' else [(index, route) for batch in array_values(self._runtime, name,['routes'], drop=('stops',)) for index, route in batch]base['zones'] = [meta for batch in array_values(self._runtime, name, ['zones'], drop=('memberPids', 'member_pids', 'memberships', 'legacyMembershipEvidence')) for _, meta in batch]3 unmodified linesvalue['routes'], value['zones'] = [], []for index, route in saved['routes']:if isinstance(route, dict):route = dict(route, stops=self._selected_json(name, ['routes', index, 'stops'], array=True, id_key='customerPid'))value['routes'].append(route)value['zones'] = copy.deepcopy(saved['zones'])
216 unmodified lines21721821922022122222322422522622722822923023123223323423523623777 unmodified lines315316317318319320216 unmodified linesreturn cw.NOT_READYdef _term_rows(cw, tenant, st, page):"""Read dated-week counts for this server page without loading its ranking history."""terms = page["terms"]counts = {}if terms:try:with cw._reader(tenant, st) as cur:cols = cw._ba_columns(cur)if {"search_term", "_period_start", "_period_end"} <= cols:key = cw._term_sql("search_term")rows = cur.execute(f'SELECT {key}, COUNT(DISTINCT CAST("_period_start" AS DATE)) 'f'FROM {cw.BA_TABLE} WHERE {key} IN (' + ','.join('?' for _ in terms) + ') 'f'AND ({cw._weekly_period_sql()}) GROUP BY {key}', terms).fetchall()counts = dict(rows)except Exception as exc: # noqa: BLE001cause = str(exc) if isinstance(exc, cw._ReadFailed) else type(exc).__name__raise cw.SourceNotReady(cause, page=page) from exc77 unmodified linespage = _call(cw.term_page, tenant, st=session.runtime, search=q, offset=offset,limit=limit, selected=term, tracked=tracked, termOrder=termOrder)terms, picked = page["terms"], page["term"]page = {**page, "termRows": _call(_term_rows, cw, tenant, session.runtime, page)}detail = _call(cw.term_detail, tenant, picked, st=session.runtime) if picked else {}return screen_payload(cw, detail, terms, picked, _may_edit(session, record), page=page)216 unmodified lines21721821922022122222322422522622722822977 unmodified lines307308309310311312216 unmodified linesreturn cw.NOT_READYdef _term_rows(cw, tenant, st, page, counts=None):"""Read dated-week counts for this server page without loading its ranking history."""terms = page["terms"]if counts is None:try:with cw._reader(tenant, st) as cur:counts, _history = cw._page_history(cur, terms, None)except Exception as exc: # noqa: BLE001cause = str(exc) if isinstance(exc, cw._ReadFailed) else type(exc).__name__raise cw.SourceNotReady(cause, page=page) from exc77 unmodified linespage = _call(cw.term_page, tenant, st=session.runtime, search=q, offset=offset,limit=limit, selected=term, tracked=tracked, termOrder=termOrder)terms, picked = page["terms"], page["term"]counts, detail = _call(cw.term_page_history, tenant, page, st=session.runtime)page = {**page, "termRows": _term_rows(cw, tenant, session.runtime, page, counts)}return screen_payload(cw, detail, terms, picked, _may_edit(session, record), page=page)
422 unmodified lines4234244254264274284298 unmodified lines438439440441442443444422 unmodified linesimport aios_gridworkspace = dict(workspace)field_keys = {field['key'] for field in fields}valid_keys = field_keys | {measure['key'] for measure in measures}cohort_ids = {str(entry['id']) for entry in workspace.get('lists') or () if entry.get('id')}view_ids = {str(view['id']) for view in workspace.get('views') or () if view.get('id')}8 unmodified linescfg['filters'] = aios_grid.clean_filter_tree(cfg.get('filters'), valid_keys, cohort_ids=cohort_ids,visible_view_ids=view_ids, report=reports)prune_view_field_members(view, live_keys=field_keys, prune_filters=False)removals = []for report in [*(view.get('filterRemovals') or ()), *reports]:if (isinstance(report, dict) and report.get('colId') not in hidden422 unmodified lines4234244254264274284294304318 unmodified lines440441442443444445446422 unmodified linesimport aios_gridworkspace = dict(workspace)workspace['layoutFields'] = aios_grid.audit_layout_fields(fields, hidden)layout_keys = {field['key'] for field in workspace['layoutFields']}field_keys = {field['key'] for field in fields} - set(hidden or ())valid_keys = field_keys | {measure['key'] for measure in measures}cohort_ids = {str(entry['id']) for entry in workspace.get('lists') or () if entry.get('id')}view_ids = {str(view['id']) for view in workspace.get('views') or () if view.get('id')}8 unmodified linescfg['filters'] = aios_grid.clean_filter_tree(cfg.get('filters'), valid_keys, cohort_ids=cohort_ids,visible_view_ids=view_ids, report=reports)prune_view_field_members(view, live_keys=field_keys, prune_filters=False, layout_keys=layout_keys)removals = []for report in [*(view.get('filterRemovals') or ()), *reports]:if (isinstance(report, dict) and report.get('colId') not in hidden
32 unmodified lines33343536373832 unmodified lines_HERE = Path(__file__).resolve().parent# Where the inlined single-file build lives. FIRST match wins:# 1. the shipped copy in this dir (what deploy_hf.py uploads to the Space)# 2. the raw build output in the sibling aios-web tree (local dev, pre-copy)32 unmodified lines333435363738394041424344454632 unmodified lines_HERE = Path(__file__).resolve().parentdef audit_layout_fields(fields=(), hidden=()):"""Publish the audit presentation column without granting cell or schema authority."""if '_updated' in hidden or any(field.get('key') == '_updated' for field in fields):return []return [{'key': '_updated', 'label': 'Last updated', 'type': 'date', 'source': 'odoo','derived': True, 'origin': 'system', 'valueAuthority': 'derived'}]# Where the inlined single-file build lives. FIRST match wins:# 1. the shipped copy in this dir (what deploy_hf.py uploads to the Space)# 2. the raw build output in the sibling aios-web tree (local dev, pre-copy)
1116 unmodified lines1117111811191120112111221123112 unmodified lines123612371238123912401241124222 unmodified lines12651266126712681269127012711116 unmodified linesor (family in (*field_families, 'filter', 'memberPid') and not separator)or (family in scalar_families and separator and family != 'filterConj')):return refuse('unknown_member', 'Choose a supported View setting.')valid_keys = {item['key'] for item in ctx.fields}if family in field_families:key = _view_field_key(key, valid_keys)if key not in valid_keys:112 unmodified linescleaned, refusal = clean_view_member(member, value, cleaner_ctx, prior)return default if refusal else cleanedvalid_keys = {item['key'] for item in ctx.fields}config = {'filters': [], 'filterConj': clean('filterConj', cfg.get('filterConj', 'and'), 'and'),'important': clean('important', cfg.get('important', False), False),22 unmodified linesconfig['order'] = list(dict.fromkeys(_view_field_key(key, valid_keys) for key in orderif isinstance(key, str) and _view_field_key(key, valid_keys) in valid_keys))config['order'] += [item['key'] for item in ctx.fields if item['key'] not in config['order']]visible = cfg.get('visible') if isinstance(cfg.get('visible'), list) else []for key in dict.fromkeys(_view_field_key(key, valid_keys) for key in visible if isinstance(key, str)):hidden = clean('hidden:' + key, False)1116 unmodified lines1117111811191120112111221123112411251126112 unmodified lines12391240124112421243124412451246124722 unmodified lines12701271127212731274127512761116 unmodified linesor (family in (*field_families, 'filter', 'memberPid') and not separator)or (family in scalar_families and separator and family != 'filterConj')):return refuse('unknown_member', 'Choose a supported View setting.')valid_keys = {item['key'] for item in ctx.fields} - set(ctx.hidden_keys or ())if family in ('hidden', 'width', 'position'):import aios_grid as _agvalid_keys |= {item['key'] for item in _ag.audit_layout_fields(ctx.fields, ctx.hidden_keys or ())}if family in field_families:key = _view_field_key(key, valid_keys)if key not in valid_keys:112 unmodified linescleaned, refusal = clean_view_member(member, value, cleaner_ctx, prior)return default if refusal else cleanedlayout_fields = [item for item in ctx.fields if item['key'] not in (ctx.hidden_keys or ())]layout_fields += _ag.audit_layout_fields(ctx.fields, ctx.hidden_keys or ())valid_keys = {item['key'] for item in layout_fields}config = {'filters': [], 'filterConj': clean('filterConj', cfg.get('filterConj', 'and'), 'and'),'important': clean('important', cfg.get('important', False), False),22 unmodified linesconfig['order'] = list(dict.fromkeys(_view_field_key(key, valid_keys) for key in orderif isinstance(key, str) and _view_field_key(key, valid_keys) in valid_keys))config['order'] += [item['key'] for item in layout_fields if item['key'] not in config['order']]visible = cfg.get('visible') if isinstance(cfg.get('visible'), list) else []for key in dict.fromkeys(_view_field_key(key, valid_keys) for key in visible if isinstance(key, str)):hidden = clean('hidden:' + key, False)
19 unmodified lines2021222324252627265 unmodified lines2932942952962972982993003012 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573581 unmodified line36036136236336436536636736836937037137237337437537637737813 unmodified lines3923933943953963973981 unmodified line40040140240340440540640740840912 unmodified lines42242342442542642742842943043143243343443543643743843944018 unmodified lines45946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651721 unmodified lines53954054154254354454554654754854955055155255355455555655755855956056156256319 unmodified linesBASELINE_LOCK_SECONDS = 300BASELINE_CHUNK_BYTES = 8 * 1024 * 1024PROJECTION_VERSION = 1_LISTENERS = []_PROJECTIONS = {}_LOCK = threading.RLock()_LOG = logging.getLogger(__name__)265 unmodified linesreturn f"{STORE_KEY}/observations/{identity}/{kind}/{digest}"def _read_blob(rt, path, digest, size):from core import blob_envelope as beraw = rt.download_bytes(path)if raw is None or len(raw) > BASELINE_CHUNK_BYTES:raise BaselineUnavailable("A required observation blob is missing or oversized.")data = be.open(rt.key, path, raw) if be.is_sealed(raw) else bytes(raw)2 unmodified linesreturn datadef _write_blob(rt, path, data):"""Reuse immutable content and verify persistence before publishing its reference."""from core import blob_envelope as bedigest, size = _digest(data), len(data)if rt.download_bytes(path) is None:stored = be.seal(rt.key, path, data)if len(stored) > BASELINE_CHUNK_BYTES:raise BaselineUnavailable("The observation blob exceeds the store chunk size.")rt.upload_bytes(path, stored)_read_blob(rt, path, digest, size)return {"sha256": digest, "bytes": size}def _persist_baseline(rt, identity, binding, path, snapshot, stamp):from core import blob_envelope as beparts, content, size = [], hashlib.sha256(), 0with path.open("rb") as handle:while chunk := handle.read(BASELINE_CHUNK_BYTES - len(be.HEADER) - 28):parts.append(_write_blob(rt, _blob_path(identity, "chunks", _digest(chunk)), chunk))content.update(chunk)size += len(chunk)manifest = {**binding, "snapshot": snapshot, "at": stamp, "parts": parts,"sha256": content.hexdigest(), "bytes": size}data = _json_bytes(manifest)return _write_blob(rt, _blob_path(identity, "manifests", _digest(data)), data)def _restore_baseline(rt, identity, binding, reference, path, con):try:data = _read_blob(rt, _blob_path(identity, "manifests", reference["sha256"]),reference["sha256"], reference["bytes"])manifest = json.loads(data)if (any(manifest.get(key) != value for key, value in binding.items())or not isinstance(manifest.get("snapshot"), str) or not manifest["snapshot"]or not isinstance(manifest.get("parts"), list) or not manifest["parts"]or not manifest.get("at")):raise BaselineUnavailable("The observation manifest has a different identity or shape.")_at(manifest["at"])content, size = hashlib.sha256(), 0with path.open("wb") as handle:for part in manifest["parts"]:chunk = _read_blob(rt, _blob_path(identity, "chunks", part["sha256"]),part["sha256"], part["bytes"])handle.write(chunk)content.update(chunk)size += len(chunk)if content.hexdigest() != manifest["sha256"] or size != manifest["bytes"]:raise BaselineUnavailable("The observation snapshot failed content verification.")_validate_projection(con, path)return manifestexcept BaselineUnavailable:raise1 unmodified lineraise BaselineUnavailable("The required observation could not be verified.") from excdef _validate_projection(con, path):schema = con.execute("DESCRIBE SELECT * FROM read_parquet(?)", [str(path)]).fetchall()if [(row[0], row[1]) for row in schema] != [("row_id", "VARCHAR"), ("image", "VARCHAR")]:raise BaselineUnavailable("The observation projection has an invalid schema.")invalid = con.execute("SELECT count(*) != count(DISTINCT row_id) OR ""count(*) != count(row_id) OR count(*) != count(image) ""FROM read_parquet(?)", [str(path)]).fetchone()[0]if invalid:raise BaselineUnavailable("A received-change projection requires unique non-null row IDs and images.")def _observation_state(rt, identity):document = _document(rt, rt.get(STORE_KEY, fresh=True))states = document.get("observations", {})if not isinstance(states, dict):raise BaselineUnavailable("The observation index is invalid.")13 unmodified linesreturn state, documentdef _move_baseline(rt, identity, expected, updated):"""Serialize replica transitions in the existing tenant journal's update boundary."""def move(raw):document = _document(rt, raw)1 unmodified lineif states.get(identity) != expected:raise BaselineUnavailable("The observation changed on another replica. Retry publication.")states[identity] = updatedreturn documentresult = rt.update(STORE_KEY, move, flush="sync")if result is None or result is False:raise BaselineUnavailable("The observation reference was not saved.")@contextmanager12 unmodified linesdef _compare_baseline(rt, source, database, spec, con, baseline, current, snapshot, deadline=None):diff = ("FROM read_parquet(?) b FULL OUTER JOIN read_parquet(?) a ""USING (row_id) WHERE b.image IS DISTINCT FROM a.image")count = con.execute("SELECT count(*) " + diff, [str(baseline), str(current)]).fetchone()[0]# A diff wider than the retained window cannot be replayed, so it is recorded as one bulk change.if count > MAX_EVENTS:print(f"[received-changes] {database}: {count} changed rows exceed the journal's "f"{MAX_EVENTS}-event window; recorded as a bulk change, rows not journaled", flush=True)returncursor, done = con.cursor(), 0try:with _query_watchdog(cursor, deadline):cursor.execute("SELECT coalesce(b.row_id, a.row_id), b.image, a.image " + diff+ " ORDER BY coalesce(b.row_id, a.row_id)", [str(baseline), str(current)])while batch := cursor.fetchmany(256):for row_id, before_json, after_json in batch:# Stop and commit: a rerun cannot resume, since each journaled receipt still costs a store write.18 unmodified linescursor.close()def _snapshot(rt, source, database, spec, con, root, manifest, deadline=None):"""Compare verified durable observations in batches, recovering interrupted comparisons first."""if not spec.get("cols"):returnif _uncommitted():raise BaselineUnavailable("Connector observations require a completed publication transaction.")identity = hashlib.sha256(json.dumps([_tenant(rt), source, database]).encode()).hexdigest()binding = {"version": PROJECTION_VERSION, "tenant": _tenant(rt), "source": source,"database": database, "projection": _projection_shape(spec)}snapshot, stamp = str(manifest["snapshot_id"]), manifest.get("completed_at")if not stamp:raise BaselineUnavailable("Connector observations require a completed publication time.")stamp = _at(stamp)state, document = _observation_state(rt, identity)if state is None and (any((root / (identity + suffix)).exists() for suffix in (".parquet", ".json"))or any(event["source"] == source and event["database"] == databasefor event in document["events"])):raise BaselineUnavailable("A legacy observation requires verified migration before comparison.")with tempfile.TemporaryDirectory(dir=root, prefix="projection-") as directory:baseline, current = Path(directory) / "baseline.parquet", Path(directory) / "current.parquet"def complete(pending):observed = _restore_baseline(rt, identity, binding, pending["pending"], current, con)if pending["current"]:_restore_baseline(rt, identity, binding, pending["current"], baseline, con)_compare_baseline(rt, source, database, spec, con, baseline, current, observed["snapshot"],deadline)committed = {"current": pending["pending"], "pending": None}_move_baseline(rt, identity, pending, committed)return committedif state and state["pending"]:state = complete(state)if state:prior = _restore_baseline(rt, identity, binding, state["current"], baseline, con)prior_at = dt.datetime.fromisoformat(prior["at"].replace("Z", "+00:00"))incoming_at = dt.datetime.fromisoformat(stamp.replace("Z", "+00:00"))if prior["snapshot"] == snapshot or incoming_at < prior_at:returnif incoming_at == prior_at:raise BaselineUnavailable("Distinct connector snapshots have ambiguous publication order.")expressions = ", ".join(f"{_quoted(key)} := {value[0]}" for key, value in spec["cols"].items())where = " WHERE " + spec["where"] if spec.get("where") else ""query = (f"SELECT CAST(({spec['id']}) AS VARCHAR) AS row_id, "f"CAST(to_json(struct_pack({expressions})) AS VARCHAR) AS image "f"FROM {spec.get('from_sql') or spec['table']}{where}")current.unlink(missing_ok=True)con.execute(f"COPY ({query}) TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(current)])_validate_projection(con, current)reference = _persist_baseline(rt, identity, binding, current, snapshot, stamp)pending = {"current": state["current"] if state else None, "pending": reference}_move_baseline(rt, identity, state, pending)complete(pending)def mirror_hook(connector, tenant_key, manifest, _state_rows, paths):21 unmodified linesstarted = time.monotonic()specs = resolver(rt, con)resolution_seconds = time.monotonic() - startedsnapshots_started = time.monotonic()completed = deferred = skipped = 0for database, spec in specs.items():# A skipped database keeps its stored baseline for the next publication.if time.monotonic() >= deadline[0]:skipped += 1print(f"[received-changes] {database}: skipped, journal deadline passed", flush=True)continuetry:_snapshot(rt, connector, str(database), spec, con, root, manifest, deadline)completed += 1except Exception as exc:deferred += 1_LOG.warning("Received-change projection deferred for %s: %s",database, type(exc).__name__)print(f'[received-changes] publication connector={connector} tables={len(specs)} 'f'completed={completed} deferred={deferred} skipped={skipped} 'f'resolution={resolution_seconds:.3f}s snapshots={time.monotonic() - snapshots_started:.3f}s',flush=True)finally:con.close()19 unmodified lines2021222324252627282930265 unmodified lines2962972982993003013023032 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214221 unmodified line42442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647713 unmodified lines4914924934944954964971 unmodified line49950050150250350450550650750850951051112 unmodified lines52452552652752852953053153253353453553653753853954054154254354454554654754854918 unmodified lines56856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176221 unmodified lines78478578678778878979079179279379479579679779879980080180280380480580680780819 unmodified linesBASELINE_LOCK_SECONDS = 300BASELINE_CHUNK_BYTES = 8 * 1024 * 1024PROJECTION_VERSION = 1# A 128-bit digest of each image: the compare join carries it, never the image itself.IMAGE_DIGEST = "md5_number(image)"_LISTENERS = []_PROJECTIONS = {}_VERIFIED_BASELINES = {}_LOCK = threading.RLock()_LOG = logging.getLogger(__name__)265 unmodified linesreturn f"{STORE_KEY}/observations/{identity}/{kind}/{digest}"def _open_blob(rt, path, raw, digest, size):from core import blob_envelope as beif raw is None or len(raw) > BASELINE_CHUNK_BYTES:raise BaselineUnavailable("A required observation blob is missing or oversized.")data = be.open(rt.key, path, raw) if be.is_sealed(raw) else bytes(raw)2 unmodified linesreturn datadef _read_blob(rt, path, digest, size):return _open_blob(rt, path, rt.download_bytes(path), digest, size)def _write_blob(rt, path, data):"""Reuse immutable content and verify persistence before publishing its reference."""from core import blob_envelope as bedigest, size = _digest(data), len(data)if _insert_blob(rt, path, data):return {"sha256": digest, "bytes": size}raw = rt.download_bytes(path)if raw is None:stored = be.seal(rt.key, path, data)if len(stored) > BASELINE_CHUNK_BYTES:raise BaselineUnavailable("The observation blob exceeds the store chunk size.")rt.upload_bytes(path, stored)raw = rt.download_bytes(path)_open_blob(rt, path, raw, digest, size)return {"sha256": digest, "bytes": size}def _insert_blob(rt, path, data):"""Verify a new Postgres blob in its insert transaction without transferring it back."""from core import blob_envelope as be, store_pgbackend = rt._document_store() if hasattr(rt, "_document_store") else rtif not isinstance(backend, store_pg.PgStore):return Falseif backend.tenant_slug != _tenant(rt):raise BaselineUnavailable("The observation store belongs to another tenant.")store_pg._effective_slug(backend.tenant_slug)store_pg.check_write(backend.tenant_slug, "write received-change observation")stored = be.seal(rt.key, path, data)if len(stored) > BASELINE_CHUNK_BYTES:raise BaselineUnavailable("The observation blob exceeds the store chunk size.")name = rt.store_key(path) if hasattr(rt, "store_key") else pathwith store_pg._pool().connection() as con:row = con.execute(store_pg._q("INSERT INTO {tbl} (path, bytes) VALUES (%s, %s) ON CONFLICT (path) DO NOTHING ""RETURNING octet_length(bytes), encode(sha256(bytes), 'hex')","store_blobs", backend.tenant_slug), [name, stored]).fetchone()if row is not None and tuple(row) != (len(stored), _digest(stored)):raise BaselineUnavailable("The observation upload failed content verification.")return row is not Nonedef _persist_baseline(rt, identity, binding, path, snapshot, stamp, prior=None, **metadata):from core import blob_envelope as beparts, content, size = [], hashlib.sha256(), 0verified = {(part["sha256"], part["bytes"]) for part in (prior or {}).get("parts", [])}with path.open("rb") as handle:while chunk := handle.read(BASELINE_CHUNK_BYTES - len(be.HEADER) - 28):digest = _digest(chunk)parts.append({"sha256": digest, "bytes": len(chunk)} if (digest, len(chunk)) in verified else_write_blob(rt, _blob_path(identity, "chunks", digest), chunk))content.update(chunk)size += len(chunk)manifest = {**binding, **metadata, "snapshot": snapshot, "at": stamp, "parts": parts,"sha256": content.hexdigest(), "bytes": size}data = _json_bytes(manifest)return _write_blob(rt, _blob_path(identity, "manifests", _digest(data)), data), manifestdef _cached_baseline(cache, identity, reference):return cache / f"{identity}-{reference['sha256']}.parquet"def _cache_baseline(cache, identity, reference, path):"""Keep the committed observation on local disk so the next pass skips its download."""cache.mkdir(parents=True, exist_ok=True)for stale in cache.glob(identity + "-*.parquet"):stale.unlink(missing_ok=True)os.replace(path, _cached_baseline(cache, identity, reference))_VERIFIED_BASELINES[(str(cache), identity)] = reference["sha256"]def _restore_baseline(rt, identity, binding, reference, path, con, cache):try:data = _read_blob(rt, _blob_path(identity, "manifests", reference["sha256"]),reference["sha256"], reference["bytes"])manifest = json.loads(data)if (any(manifest.get(key) != value for key, value in binding.items() if key != "projection")or not isinstance(manifest.get("projection"), str)or not isinstance(manifest.get("snapshot"), str) or not manifest["snapshot"]or not isinstance(manifest.get("parts"), list) or not manifest["parts"]or not manifest.get("at")):raise BaselineUnavailable("The observation manifest has a different identity or shape.")_blob_path(identity, "projections", manifest["projection"])for part in manifest["parts"]:if (set(part) != {"sha256", "bytes"} or type(part["bytes"]) is not intor not 0 < part["bytes"] <= BASELINE_CHUNK_BYTES):raise BaselineUnavailable("The observation chunk reference is invalid.")_blob_path(identity, "chunks", part["sha256"])if (type(manifest.get("bytes")) is not int or manifest["bytes"] <= 0or sum(part["bytes"] for part in manifest["parts"]) != manifest["bytes"]):raise BaselineUnavailable("The observation content length is invalid.")_at(manifest["at"])cached = _cached_baseline(cache, identity, reference)if cached.exists():with cached.open("rb") as source:chunks = iter(lambda: source.read(BASELINE_CHUNK_BYTES), b"")content, size = _write_chunks(path, chunks)if content != manifest["sha256"] or size != manifest["bytes"]:cached.unlink(missing_ok=True)if not cached.exists():content, size = _write_chunks(path, (_read_blob(rt, _blob_path(identity, "chunks", part["sha256"]), part["sha256"], part["bytes"])for part in manifest["parts"]))if content != manifest["sha256"] or size != manifest["bytes"]:raise BaselineUnavailable("The observation snapshot failed content verification.")if _VERIFIED_BASELINES.get((str(cache), identity)) != reference["sha256"]:_validate_projection(con, path)return manifestexcept BaselineUnavailable:raise1 unmodified lineraise BaselineUnavailable("The required observation could not be verified.") from excdef _write_chunks(path, chunks):content, size = hashlib.sha256(), 0with path.open("wb") as handle:for chunk in chunks:handle.write(chunk)content.update(chunk)size += len(chunk)return content.hexdigest(), sizedef _projection_issues(con, path):"""Return (shared row IDs, rows sharing them, any null) for a projection of valid schema."""schema = con.execute("DESCRIBE SELECT * FROM read_parquet(?)", [str(path)]).fetchall()if [(row[0], row[1]) for row in schema] != [("row_id", "VARCHAR"), ("image", "VARCHAR")]:raise BaselineUnavailable("The observation projection has an invalid schema.")return con.execute("SELECT count(*) FILTER (WHERE n > 1), coalesce(sum(n) FILTER (WHERE n > 1), 0), ""coalesce(bool_or(row_id IS NULL OR missing > 0), false) FROM (SELECT row_id, ""count(*) AS n, count(*) - count(image) AS missing FROM read_parquet(?) GROUP BY row_id)",[str(path)]).fetchone()def _validate_projection(con, path):shared, _rows, missing = _projection_issues(con, path)if shared or missing:raise BaselineUnavailable("A received-change projection requires unique non-null row IDs and images.")def _project(con, query, path, database):"""Write the projection, leaving out row IDs the connector identity gives to several rows."""raw = path.with_name("projection.parquet")con.execute(f"COPY ({query}) TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(raw)])shared, rows, missing = _projection_issues(con, raw)if missing:raise BaselineUnavailable("A received-change projection requires non-null row IDs and images.")if not shared:os.replace(raw, path)return# An ID shared by several rows names no single record, so it cannot carry a change event.print(f"[received-changes] {database}: {rows} rows share {shared} row IDs; ""those IDs are not observed until the connector identity separates them", flush=True)con.execute("COPY (SELECT * FROM read_parquet($1) WHERE row_id NOT IN (SELECT row_id FROM read_parquet($1) ""GROUP BY row_id HAVING count(*) > 1)) TO $2 (FORMAT PARQUET, COMPRESSION ZSTD)",[str(raw), str(path)])raw.unlink()def _observation_state(rt, identity, document=None):document = _document(rt, rt.get(STORE_KEY, fresh=True)) if document is None else documentstates = document.get("observations", {})if not isinstance(states, dict):raise BaselineUnavailable("The observation index is invalid.")13 unmodified linesreturn state, documentdef _move_baseline(rt, identity, expected, updated, observed_at=None):"""Serialize replica transitions in the existing tenant journal's update boundary."""def move(raw):document = _document(rt, raw)1 unmodified lineif states.get(identity) != expected:raise BaselineUnavailable("The observation changed on another replica. Retry publication.")states[identity] = updatedif observed_at:document.setdefault("observed", {})[identity] = observed_atreturn documentresult = rt.update(STORE_KEY, move, flush="sync")if result is None or result is False:raise BaselineUnavailable("The observation reference was not saved.")return result@contextmanager12 unmodified linesdef _compare_baseline(rt, source, database, spec, con, baseline, current, snapshot, deadline=None):digests = f"(SELECT row_id, {IMAGE_DIGEST} AS image FROM read_parquet({{}}))"changed = (f"SELECT coalesce(b.row_id, a.row_id) FROM {digests.format('$1')} b FULL OUTER JOIN "f"{digests.format('$2')} a USING (row_id) WHERE b.image IS DISTINCT FROM a.image")files = [str(baseline), str(current)]rows = con.execute(f"SELECT count(*) OVER (), * FROM ({changed}) LIMIT {MAX_EVENTS + 1}", files).fetchall()count, ids = (rows[0][0] if rows else 0), [row[1] for row in rows]# A diff wider than the retained window cannot be replayed, so it is recorded as one bulk change.if count > MAX_EVENTS:print(f"[received-changes] {database}: {count} changed rows exceed the journal's "f"{MAX_EVENTS}-event window; recorded as a bulk change, rows not journaled", flush=True)returnif not ids:returncursor, done = con.cursor(), 0try:with _query_watchdog(cursor, deadline):picked = "(SELECT * FROM read_parquet({}) WHERE row_id IN (SELECT unnest($3::VARCHAR[])))"cursor.execute(f"SELECT coalesce(b.row_id, a.row_id), b.image, a.image FROM {picked.format('$1')} b "f"FULL OUTER JOIN {picked.format('$2')} a USING (row_id) ""ORDER BY coalesce(b.row_id, a.row_id)", [*files, ids])while batch := cursor.fetchmany(256):for row_id, before_json, after_json in batch:# Stop and commit: a rerun cannot resume, since each journaled receipt still costs a store write.18 unmodified linescursor.close()def _observation_identity(rt, source, database):return hashlib.sha256(json.dumps([_tenant(rt), source, database]).encode()).hexdigest()def _complete_baseline(rt, identity, state, current, baseline, con, cache,source, database, spec, deadline, observed, expected, unchanged=False, reset=False):if state["current"] and not unchanged:_compare_baseline(rt, source, database, spec, con, baseline, current, observed, deadline)committed = {"current": state["pending"], "pending": None}document = _move_baseline(rt, identity, expected, committed, observed_at=_at())_cache_baseline(cache, identity, state["pending"], current)if reset:print(f"[received-changes] {database}: projection binding changed; new baseline, no events", flush=True)return committed, documentdef _prior_observations(rt, identity, binding, state, baseline, current, con, cache):"""Verify both references before recovering or replacing a changed projection."""held = {}for key, path in (("current", baseline), ("pending", current)):if state and state[key]:held[key] = _restore_baseline(rt, identity, binding, state[key], path, con, cache)if len(held) == 2:before, after = held["current"], held["pending"]if dt.datetime.fromisoformat(after["at"].replace("Z", "+00:00")) <= dt.datetime.fromisoformat(before["at"].replace("Z", "+00:00")):raise BaselineUnavailable("The pending observation has invalid publication order.")return helddef _refresh_observation(rt, identity, binding, state, prior, snapshot, stamp):"""Advance an identical input's publication order while retaining its verified content."""data = _json_bytes({**prior, **binding, "snapshot": snapshot, "at": stamp})reference = _write_blob(rt, _blob_path(identity, "manifests", _digest(data)), data)return _move_baseline(rt, identity, state, {"current": reference, "pending": None}, observed_at=_at())def _snapshot(rt, source, database, spec, con, root, manifest, deadline=None, publication=None):"""Compare verified durable observations in batches, recovering interrupted comparisons first."""if not spec.get("cols"):returnif _uncommitted():raise BaselineUnavailable("Connector observations require a completed publication transaction.")identity = _observation_identity(rt, source, database)binding = {"version": PROJECTION_VERSION, "tenant": _tenant(rt), "source": source,"database": database, "projection": _projection_shape(spec)}snapshot, stamp = str(manifest["snapshot_id"]), manifest.get("completed_at")if not stamp:raise BaselineUnavailable("Connector observations require a completed publication time.")stamp = _at(stamp)state, document = _observation_state(rt, identity, publication.document if publication else None)if state is None and (any((root / (identity + suffix)).exists() for suffix in (".parquet", ".json"))or any(event["source"] == source and event["database"] == databasefor event in document["events"])):raise BaselineUnavailable("A legacy observation requires verified migration before comparison.")cache = root / "baselines"with tempfile.TemporaryDirectory(dir=root, prefix="projection-") as directory:baseline, current = Path(directory) / "baseline.parquet", Path(directory) / "current.parquet"restoring = time.monotonic()held = _prior_observations(rt, identity, binding, state, baseline, current, con, cache)print(f"[received-changes] {database}: restore_verify={time.monotonic() - restoring:.3f}s", flush=True)reset = any(prior["projection"] != binding["projection"] for prior in held.values())prior = held.get("pending") or held.get("current")if state and state["pending"] and not reset:state, document = _complete_baseline(rt, identity, state, current, baseline, con,cache, source, database, spec, deadline, prior["snapshot"],expected=state,reset=bool(prior.get("reset_from")) and not state["current"])# The recovered pending file became the cache, and is the next comparison's baseline.baseline.unlink(missing_ok=True)baseline.hardlink_to(_cached_baseline(cache, identity, state["current"]))if prior:prior_at = dt.datetime.fromisoformat(prior["at"].replace("Z", "+00:00"))incoming_at = dt.datetime.fromisoformat(stamp.replace("Z", "+00:00"))if incoming_at < prior_at:if publication:publication.document = documentreturnif incoming_at == prior_at and prior["snapshot"] != snapshot:raise BaselineUnavailable("Distinct connector snapshots have ambiguous publication order.")if prior and not reset and prior["snapshot"] == snapshot:if publication:publication.document = documentreturnif prior and not reset and spec.get("input_digest") == prior.get("input") and spec.get("input_digest"):document = _refresh_observation(rt, identity, binding, state, prior, snapshot, stamp)_cache_baseline(cache, identity, document["observations"][identity]["current"], baseline)else:document = _new_observation(rt, identity, binding, state, spec, con, current, baseline,cache, source, database, snapshot, stamp, deadline, reset, prior)if publication:publication.document = documentdef _new_observation(rt, identity, binding, state, spec, con, current, baseline, cache,source, database, snapshot, stamp, deadline, reset, prior):expressions = ", ".join(f"{_quoted(key)} := {value[0]}" for key, value in spec["cols"].items())where = " WHERE " + spec["where"] if spec.get("where") else ""query = (f"SELECT CAST(({spec['id']}) AS VARCHAR) AS row_id, "f"CAST(to_json(struct_pack({expressions})) AS VARCHAR) AS image "f"FROM {spec.get('from_sql') or spec['table']}{where}")current.unlink(missing_ok=True)started = time.monotonic()_project(con, query, current, database)projected = time.monotonic()reference, observed = _persist_baseline(rt, identity, binding, current, snapshot, stamp,prior=prior, input=spec.get("input_digest"), reset_from=prior["projection"] if reset else None)persisted = time.monotonic()pending = {"current": state["current"] if state and not reset else None, "pending": reference}unchanged = bool(prior and prior["sha256"] == observed["sha256"])expected = state# Only a comparison that can emit events needs a durable pending checkpoint.if pending["current"] and not unchanged:_move_baseline(rt, identity, state, pending)expected = pending_committed, document = _complete_baseline(rt, identity, pending, current, baseline,con, cache, source, database, spec, deadline, snapshot, expected=expected,unchanged=unchanged, reset=reset)print(f"[received-changes] {database}: project={projected - started:.3f}s "f"persist={persisted - projected:.3f}s compare_commit={time.monotonic() - persisted:.3f}s", flush=True)return documentclass _ObservationPublication:"""Share one authoritative journal read and ordered input digests across a publication."""def __init__(self, rt, paths):started = time.monotonic()self.document = _document(rt, rt.get(STORE_KEY, fresh=True))self.paths, self.digests = paths, {}print(f"[received-changes] journal_read={time.monotonic() - started:.3f}s", flush=True)def input_digest(self, spec, deadline):tables = spec.get("observation_tables", sorted(self.paths))parts = []for table in tables:files = self.paths.get(table)if not files:return Nonefor path in files:name = str(path)if name not in self.digests:content = hashlib.sha256()with open(path, "rb") as handle:while chunk := handle.read(BASELINE_CHUNK_BYTES):if time.monotonic() >= deadline[0]:raise BaselineUnavailable("The observation input deadline passed.")content.update(chunk)self.digests[name] = content.hexdigest()parts.append([table, self.digests[name]])return _digest(_json_bytes(parts))def _publication_order(rt, connector, specs, paths, document=None):"""Least recently observed databases first, then the smallest, so a deadline defers in rotation."""document = _document(rt, rt.get(STORE_KEY, fresh=True)) if document is None else documentobserved = document.get("observed") or {}def priority(item):database, spec = itemfiles = paths.get(spec.get("table"), ()) if isinstance(spec, dict) else ()return (str(observed.get(_observation_identity(rt, connector, str(database))) or ""),sum(os.path.getsize(path) for path in files if os.path.exists(path)))return sorted(specs.items(), key=priority)def _project_database(rt, connector, database, spec, con, root, manifest, deadline, publication=None):"""Return None when the database committed, else the named reason it was deferred."""import duckdbfrom core import request_timingstarted = time.monotonic()try:with _query_watchdog(con, deadline):if publication:spec = {**spec, "input_digest": publication.input_digest(spec, deadline)}print(f"[received-changes] {database}: input_hash={time.monotonic() - started:.3f}s", flush=True)_snapshot(rt, connector, database, spec, con, root, manifest, deadline, publication)except request_timing.RequestDeadlineExceeded as exc:# The watchdog raises on exit after a clean body too; no cause means the database committed.return None if exc.__cause__ is None else "journal deadline passed"except BaselineUnavailable as exc:return f"BaselineUnavailable: {exc}"except duckdb.Error as exc:# One database's failed query defers it alone; its stored baseline stays for the next pass.return type(exc).__name__finally:print(f"[received-changes] {database}: total={time.monotonic() - started:.3f}s", flush=True)return Nonedef mirror_hook(connector, tenant_key, manifest, _state_rows, paths):21 unmodified linesstarted = time.monotonic()specs = resolver(rt, con)resolution_seconds = time.monotonic() - startedsnapshots_started = time.monotonic()completed = deferred = skipped = 0publication = _ObservationPublication(rt, paths)for database, spec in _publication_order(rt, connector, specs, paths, publication.document):# A skipped database keeps its stored baseline and leads the next publication.if time.monotonic() >= deadline[0]:skipped += 1print(f"[received-changes] {database}: skipped, journal deadline passed", flush=True)continuereason = _project_database(rt, connector, str(database), spec, con, root, manifest, deadline, publication)if reason is None:completed += 1continuedeferred += 1_LOG.warning("Received-change projection deferred for %s: %s", database, reason)print(f'[received-changes] publication connector={connector} tables={len(specs)} 'f'completed={completed} deferred={deferred} skipped={skipped} 'f'resolution={resolution_seconds:.3f}s snapshots={time.monotonic() - snapshots_started:.3f}s',flush=True)finally:con.close()
224 unmodified lines225226227228229230231224 unmodified lines{'key': 'customer_card', 'label': 'Customer Card', 'brand': True, 'hq': False, 'validate': True,'validate_only': True, 'nav': False, 'source': 'Odoo','note': 'Template App customer receivables independently tied to res.partner.credit.'},{'key': 'amazon_profit', 'label': 'Command Center', 'brand': False, 'hq': True,'validate': True, 'validate_only': True, 'nav': False, 'source': 'Amazon','note': 'Per SKU Amazon net profit, margin and band in the module table ''ut_amazon_sku_profit (Odoo cost times units). The row keeps validate.py tying '224 unmodified lines225226227228229230231224 unmodified lines{'key': 'customer_card', 'label': 'Customer Card', 'brand': True, 'hq': False, 'validate': True,'validate_only': True, 'nav': False, 'source': 'Odoo','note': 'Template App customer receivables independently tied to res.partner.credit.'},{'key': 'amazon_profit', 'label': 'Project manager', 'brand': False, 'hq': True,'validate': True, 'validate_only': True, 'nav': False, 'source': 'Amazon','note': 'Per SKU Amazon net profit, margin and band in the module table ''ut_amazon_sku_profit (Odoo cost times units). The row keeps validate.py tying '
860 unmodified lines86186286386486586611 unmodified lines878879880881882883860 unmodified linesreturn hit[0]def prune(table_key, live_pids, st=None, *, pass_id=None, validate_source=None):"""Drop shared cells for rows that no longer exist. Returns how many rows were dropped.11 unmodified lineskeep = {_pid(p) for p in live_pids}if not keep:return 0dropped = []completed = False860 unmodified lines86186286386486586686786886987087187287387487511 unmodified lines887888889890891892893894860 unmodified linesreturn hit[0]def _stored_prune_pass(table_key, st):"""The committed prune marker read by path on a native store, else None (the write decides)."""native = _cell_backend(table_key, st)reader = getattr(native[0], 'get_json_paths', None) if native is not None else Noneif not callable(reader):return Nonereturn (reader(native[1], [['_prune_pass']]) or [None])[0]def prune(table_key, live_pids, st=None, *, pass_id=None, validate_source=None):"""Drop shared cells for rows that no longer exist. Returns how many rows were dropped.11 unmodified lineskeep = {_pid(p) for p in live_pids}if not keep:return 0if pass_id is not None and _stored_prune_pass(table_key, st) == pass_id:return 0dropped = []completed = False
106 unmodified lines10710810911011111218 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521681 unmodified lines183418351836183718381839184039 unmodified lines1880188118821883188418851886188718881889130 unmodified lines20202021202220232024202575 unmodified lines210121022103210421052106106 unmodified lines_VIEW_OP_FAMILIES = frozenset(('hidden', 'sort', 'filter', 'width', 'position', 'summary', 'memberPid'))_VIEW_OP_POSITION = re.compile(r'[0-9A-Za-z]{1,64}\Z')def _view_member_identity(member):"""Use one receipt and last-writer identity for equivalent record ids."""18 unmodified linesyield from _view_filter_nodes(node['children'], node.get('id'))def prune_view_field_members(view, *, live_keys=None, removed_keys=(), prune_filters=True):"""Drop dead field references from a mutable View without changing live member values."""cfg = view.get('config') if isinstance(view, dict) else Noneif not isinstance(cfg, dict):returnremoved = set(removed_keys)def keep(key):return key not in removed and (live_keys is None or key in live_keys)for name in ('visible', 'order'):if isinstance(cfg.get(name), list):cfg[name] = [key for key in cfg[name] if keep(key)]for name in ('widths', 'positions', 'summary'):if isinstance(cfg.get(name), dict):cfg[name] = {key: value for key, value in cfg[name].items() if keep(key)}if isinstance(cfg.get('sorts'), list):cfg['sorts'] = [rule for rule in cfg['sorts']if isinstance(rule, dict) and keep(rule.get('colId'))]1681 unmodified linesdef save_assigned_presentation(self, recipient, assignment_id, presentation):"""Persist presentation only; predicate-shaped keys are rejected, never merged."""blocked = {'filters', 'filterConj', 'memberPids'}clean = {k: v for k, v in dict(presentation or {}).items() if k not in blocked}who, aid = str(recipient or '').strip().lower(), str(assignment_id or '').strip()if not who or not aid:raise ValueError('assignment id and recipient are required')39 unmodified linesown = workspace.get('fields') or {}if view_settings_rows.supports(self.table_key):from core import user_tablesdefinition = user_tables.get_definition(self._shared_stratum_key(), st=self._st) or {}return ({field['key'] for field in definition.get('fields', [])}| {key for key in own if key.startswith(('custom_', 'measure_'))}| self._tenant_wide_keys())# The event adapter checks built-in fields against its scoped field contract.return None130 unmodified linesdenied = admit(view, candidate, member)if denied:return refuse(denied['reason'], denied['message'])if family == 'name':names = ([name for who, vid, name in data.view_index() if vid != view_id]if isinstance(data, view_settings_rows.ScopedDocument) else75 unmodified linesif username in RESERVED_MEMBERS:raise ValueError('reserved username')requested = dict(view)# A Saved View never embeds a second access model. Historical documents are handled by# the fail-closed migration above; an incoming legacy-shaped write is refused rather than# silently normalized into a protocol the API no longer accepts.106 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515618 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961681 unmodified lines187818791880188118821883188439 unmodified lines192419251926192719281929193019311932193319341935130 unmodified lines206620672068206920702071207275 unmodified lines21482149215021512152215321542155106 unmodified lines_VIEW_OP_FAMILIES = frozenset(('hidden', 'sort', 'filter', 'width', 'position', 'summary', 'memberPid'))_VIEW_OP_POSITION = re.compile(r'[0-9A-Za-z]{1,64}\Z')#: `{table_key: (after_key, keys)}`: columns an App keeps in every stored View of its table._VIEW_KEEP = {}def register_view_keep(table_key, keys, *, after):"""Keep `keys` in every View of `table_key`, in order right after `after`, whatever a save sends."""_VIEW_KEEP[str(table_key)] = (str(after), tuple(str(key) for key in keys))def unregister_view_keep(table_key):"""Drop a table's kept columns; returns the entry that was registered, or None."""return _VIEW_KEEP.pop(str(table_key), None)def _view_keep(table_key):# A TableStore holds the workspace key; an App registers the table key.key = str(table_key or '')return _VIEW_KEEP.get(key) or _VIEW_KEEP.get(key.removesuffix('_table_workspace'))def kept_config(table_key, config):"""`config` with the table's kept columns in its `visible` and `order` lists; the same object if nothing moves."""entry = _view_keep(table_key)if entry is None or not isinstance(config, dict):return configafter, keys = entryout = Nonefor part in ('visible', 'order'):columns = config.get(part)if not isinstance(columns, list):continuerest = [column for column in columns if column not in keys]at = rest.index(after) + 1 if after in rest else 0want = rest[:at] + list(keys) + rest[at:]if want != columns:out = dict(config) if out is None else outout[part] = wantif out is None:return config# The browser refuses saved positions that disagree with `order`, so a moved key loses its own.if isinstance(out.get('positions'), dict):out['positions'] = {key: value for key, value in out['positions'].items() if key not in keys}return outdef _view_member_identity(member):"""Use one receipt and last-writer identity for equivalent record ids."""18 unmodified linesyield from _view_filter_nodes(node['children'], node.get('id'))def prune_view_field_members(view, *, live_keys=None, removed_keys=(), prune_filters=True, layout_keys=()):"""Drop dead field references from a mutable View without changing live member values."""cfg = view.get('config') if isinstance(view, dict) else Noneif not isinstance(cfg, dict):returnremoved = set(removed_keys)def keep(key, layout=False):return key not in removed and (live_keys is None or key in live_keys or (layout and key in layout_keys))for name in ('visible', 'order'):if isinstance(cfg.get(name), list):cfg[name] = [key for key in cfg[name] if keep(key, layout=True)]for name in ('widths', 'positions', 'summary'):if isinstance(cfg.get(name), dict):cfg[name] = {key: value for key, value in cfg[name].items() if keep(key, layout=name != 'summary')}if isinstance(cfg.get('sorts'), list):cfg['sorts'] = [rule for rule in cfg['sorts']if isinstance(rule, dict) and keep(rule.get('colId'))]1681 unmodified linesdef save_assigned_presentation(self, recipient, assignment_id, presentation):"""Persist presentation only; predicate-shaped keys are rejected, never merged."""blocked = {'filters', 'filterConj', 'memberPids'}clean = kept_config(self.table_key, {k: v for k, v in dict(presentation or {}).items() if k not in blocked})who, aid = str(recipient or '').strip().lower(), str(assignment_id or '').strip()if not who or not aid:raise ValueError('assignment id and recipient are required')39 unmodified linesown = workspace.get('fields') or {}if view_settings_rows.supports(self.table_key):from core import user_tablesfrom aios_grid import audit_layout_fieldsdefinition = user_tables.get_definition(self._shared_stratum_key(), st=self._st) or {}return ({field['key'] for field in definition.get('fields', [])}| {key for key in own if key.startswith(('custom_', 'measure_'))}| self._tenant_wide_keys()| {field['key'] for field in audit_layout_fields()})# The event adapter checks built-in fields against its scoped field contract.return None130 unmodified linesdenied = admit(view, candidate, member)if denied:return refuse(denied['reason'], denied['message'])candidate['config'] = kept_config(self.table_key, candidate['config'])if family == 'name':names = ([name for who, vid, name in data.view_index() if vid != view_id]if isinstance(data, view_settings_rows.ScopedDocument) else75 unmodified linesif username in RESERVED_MEMBERS:raise ValueError('reserved username')requested = dict(view)if 'config' in requested:requested['config'] = kept_config(self.table_key, requested['config'])# A Saved View never embeds a second access model. Historical documents are handled by# the fail-closed migration above; an incoming legacy-shaped write is refused rather than# silently normalized into a protocol the API no longer accepts.
364 unmodified lines365366367368369370371364 unmodified lines"report": "GET_LEDGER_SUMMARY_VIEW_DATA","snapshot": True,"dated_snapshot": True,"options": {"aggregateByTimePeriod": "DAILY", "aggregateByLocation": "COUNTRY"},"entity_read": "AWD v2024-05-09 listInventory (all 200-row pages)","validates_against": "FBA ledger summary vs detail and AWD API items vs stored AWD rows","role": "Amazon Fulfillment / Amazon Warehousing and Distribution",364 unmodified lines365366367368369370371372373364 unmodified lines"report": "GET_LEDGER_SUMMARY_VIEW_DATA","snapshot": True,"dated_snapshot": True,# D-18058: Amazon names it aggregatedByTimePeriod. A misspelt key falls back to MONTHLY,# which returns an empty document for any window shorter than a whole month."options": {"aggregatedByTimePeriod": "DAILY", "aggregateByLocation": "COUNTRY"},"entity_read": "AWD v2024-05-09 listInventory (all 200-row pages)","validates_against": "FBA ledger summary vs detail and AWD API items vs stored AWD rows","role": "Amazon Fulfillment / Amazon Warehousing and Distribution",
7576 unmodified lines757775787579758075817582758375847585758675877588285 unmodified lines78747875787678777878787969 unmodified lines79497950795179527953795479551 unmodified line79577958795979607961796219 unmodified lines798279837984798579867987798879897990799179927993799479957996799779989 unmodified lines80088009801080118012801380141082 unmodified lines90979098909991009101910291039104910526 unmodified lines91329133913491359136913791382737 unmodified lines11876118771187811879118801188175 unmodified lines119571195811959119601196111962119631196431 unmodified lines1199611997119981199912000120011200212003120041200550 unmodified lines120561205712058120591206012061261 unmodified lines12323123241232512326123271232812329123307576 unmodified linesand task[2] <= end and _history_task_period(task) == period)def _record_reconciliation(con, table, marker):"""Keep the most recent landed period, even while backfill travels backwards."""key = entity_key("reconcile_" + table)previous = _read_state(con, key)old = json.loads(previous["detail"]) if previous and previous.get("detail") else {}if marker["end"] >= old.get("end", ""):_record_state(con, key, "done", detail=json.dumps(marker, separators=(",", ":")))285 unmodified linesreturn sum(bool(raw) and not (len(raw) == 1 and not str(raw[0]).strip()) for raw in reader)def _ledger_date(value):"""The DAILY ledger uses US dates; normalize dates without inventing a report date."""value = str(value or "").strip()69 unmodified linesreturn identitydef _replace_legacy_snapshot(con, table, columns, rows, meta, source_count):"""Replace the whole FBA snapshot with one parsed document, preserving the separate AWD leg.Listings is a catalogue as of the vendor's data/creation date. The ledger is a DAILY1 unmodified lineDuplicate source identities refuse the whole document rather than silently dropping rows.S67-T32 (D-3031): one copy. The document's dates replace every earlier date, so the tableholds exactly one pull, the row count a fresh first load would store."""stamp = meta.get("dataEndTime") or meta.get("dataStartTime") or meta.get("createdTime")if not stamp and (table == "listings" or not rows):19 unmodified linestotal += 1if total != source_count:raise ValueError(f"Amazon {table} snapshot row count differs from its document")if not counts:counts[_utc(stamp).date().isoformat()] = 0columns = sorted(set(columns) | {"_snapshot_date"}| (rows.keys() if lazy else {k for row in rows for k in row}))if table == "inventory":columns = sorted(set(columns) | {"inventory_source"})mirror = table_name(table)types = _ensure(con, mirror, columns, rows, preserve_rows=True)dates = sorted(counts)marker = {"start": dates[0], "end": dates[-1], "column": "_snapshot_date","count": source_count, "dates": counts, "document": meta.get("reportDocumentId")}marker.update({key: meta[key] for key in ("reportId", "processingStatus") if meta.get(key)})if table == "inventory" and meta.get("cancelled") is True and meta.get("processingStatus") == "CANCELLED":marker["cancelled"] = True9 unmodified lines# The ledger keeps every daily snapshot as changes, oldest date first.for day in dates if history else ():_history_merge(con, table, day, f"({predicate}) AND CAST(_snapshot_date AS VARCHAR) = ?", [day])_record_reconciliation(con, table, marker)con.execute("COMMIT")return countexcept Exception:1082 unmodified linesreturn countkwargs = {} if spec.get("snapshot") else {"start": _iso(w0), "end": _iso(w1 - timedelta(seconds=1))}if spec.get("dated_snapshot"):day_end = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)kwargs = {"start": _iso(day_end - timedelta(days=1)), "end": _iso(day_end - timedelta(seconds=1))}options = dict(spec.get("options") or {})if spec.get("period"):options["reportPeriod"] = spec["period"]26 unmodified linescolumns, rows = parse_flat_file(text, **parser_args)rows = normalise_app_dates(table, rows)if table in LEGACY_SNAPSHOT_TABLES:return _replace_legacy_snapshot(con, table, columns, rows, meta, document_row_count(text))if spec.get("snapshot"):stamp = meta.get("dataEndTime") or meta.get("dataStartTime") or meta.get("createdTime")if not stamp:2737 unmodified linesreturn len(failures)def snapshot_selftest(log=print, check=None):"""S66-T47: real sync with in-memory storage and fixture-only vendor transports."""from unittest.mock import patch75 unmodified lineslen(calls) == 1 and (("start" in calls[0] and "end" in calls[0]) if table == "inventory"else ("start" not in calls[0] and "end" not in calls[0]))and result["state"] == "done" and result["remaining"] == 0)ck(table + " all document rows reconcile", lambda:count() == (2 if table == "listings" else 4) and valid()["state"] == "ok")ck(table + " real sync publishes attributed rows and a durable snapshot", lambda:bool(datastore._publication(con, "amazon").get("snapshot_id"))and bool(rt.blobs.get(MIRROR_PREFIX + _MANIFEST_KEY))31 unmodified lines"ORDER BY 1, 2").fetchall() == [("2026-09-26", "A", 9)]and valid()["state"] == "ok")else:ck("ledger keeps one row per data date, SKU, disposition and location", lambda:con.execute("SELECT COUNT(*), COUNT(DISTINCT (date, msku, disposition, location)), ""COUNT(DISTINCT _snapshot_date) FROM amzn_inventory").fetchone() == (4, 4, 2)and calls[0].get("options", {}).get("aggregateByTimePeriod") == "DAILY")payload[0] = ledger_header + "09/24/2026\tA\tFA\tAA\tSELLABLE\tUS\t9\n"sync(rt.key, tables=[table], since=start, rt=rt, log=lambda *_a: None)# S67-T32 (D-3031, reversed): the next document replaces every earlier FBA date.50 unmodified lines"WHERE inventory_source='FBA'").fetchall() == [(9,)])con.close()ck("inventory request retention and empty-source controls", lambda: inventory_status_selftest(log, check) == 0)ck("S67-T32 saved mirror: one copy, content keys, kill-safe checkpoint, full purge",lambda: mirror_selftest(log, check) == 0)return len(failures)261 unmodified linesand Counter(table for table, _kwargs in resync_calls if table in ("orders", "transactions"))== {"orders": 3, "transactions": 3})ck("snapshot transports use no backfill window except the declared ledger day", lambda:all((kwargs.get("start") == _iso(Clock.instant.replace(hour=0) - timedelta(days=1))and kwargs.get("end") == _iso(Clock.instant.replace(hour=0) - timedelta(seconds=1)))if cx.REPORT_TYPES[table].get("dated_snapshot") elsekwargs.get("start") is None and kwargs.get("end") is Nonefor table, kwargs in resync_calls if table in snapshots))7576 unmodified lines757775787579758075817582758375847585758675877588758975907591285 unmodified lines78777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792169 unmodified lines79917992799379947995799679971 unmodified line79998000800180028003800480058006800719 unmodified lines8027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880599 unmodified lines806980708071807280738074807580761082 unmodified lines915991609161916291639164916591669167916826 unmodified lines919591969197919891999200920192022737 unmodified lines119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204375 unmodified lines12119121201212112122121231212412125121261212731 unmodified lines121591216012161121621216312164121651216612167121681216950 unmodified lines1222012221122221222312224122251222612227261 unmodified lines124891249012491124921249312494124957576 unmodified linesand task[2] <= end and _history_task_period(task) == period)def _record_reconciliation(con, table, marker, replace=False):"""Keep the most recent landed period, even while backfill travels backwards.`replace`: the table now holds only this marker's rows, so its proof always wins."""key = entity_key("reconcile_" + table)previous = _read_state(con, key)old = json.loads(previous["detail"]) if previous and previous.get("detail") else {}if replace or marker["end"] >= old.get("end", ""):_record_state(con, key, "done", detail=json.dumps(marker, separators=(",", ":")))285 unmodified linesreturn sum(bool(raw) and not (len(raw) == 1 and not str(raw[0]).strip()) for raw in reader)#: D-18058: a ledger date is a US Pacific day, and Amazon returns no summary rows for an open day.LEDGER_TIMEZONE = "America/Los_Angeles"#: Closed Pacific days one summary request covers, so a day Amazon has not finished falls back a day.LEDGER_LOOKBACK_DAYS = 3def _ledger_days(now):"""`(first, newest)` closed Pacific ledger dates as of `now`."""from zoneinfo import ZoneInfo # noqa: PLC0415newest = now.astimezone(ZoneInfo(LEDGER_TIMEZONE)).date() - timedelta(days=1)return newest - timedelta(days=LEDGER_LOOKBACK_DAYS - 1), newestdef _ledger_window(now):"""The summary request for the newest closed Pacific ledger days, never the open day."""first, newest = _ledger_days(now)return {"start": f"{first.isoformat()}T00:00:00Z", "end": f"{newest.isoformat()}T23:59:59Z"}def _ledger_detail_rows(con, first, last):"""Ledger detail rows dated `first` to `last`, or None when no detail mirror exists."""mirror = table_name("inventory_ledger_detail")if "date" not in _columns_of(con, mirror):return Nonereturn int(con.execute(f"SELECT COUNT(*) FROM {mirror} WHERE CAST(\"date\" AS VARCHAR) BETWEEN ? AND ?",[first, last]).fetchone()[0])def _fba_summary_units(con):"""Units the FBA inventory API summaries hold now, or None when that mirror is absent."""mirror = table_name("fba_inventory")if "total_quantity" not in _columns_of(con, mirror):return Nonereturn int(con.execute(f"SELECT COALESCE(SUM(GREATEST(TRY_CAST(total_quantity AS BIGINT), 0)), 0) FROM {mirror}").fetchone()[0])def _ledger_date(value):"""The DAILY ledger uses US dates; normalize dates without inventing a report date."""value = str(value or "").strip()69 unmodified linesreturn identitydef _replace_legacy_snapshot(con, table, columns, rows, meta, source_count, window=None):"""Replace the whole FBA snapshot with one parsed document, preserving the separate AWD leg.Listings is a catalogue as of the vendor's data/creation date. The ledger is a DAILY1 unmodified lineDuplicate source identities refuse the whole document rather than silently dropping rows.S67-T32 (D-3031): one copy. The document's dates replace every earlier date, so the tableholds exactly one pull, the row count a fresh first load would store.D-18058: a multi-day ledger document keeps only its newest date. `window` is the requested`(first, last)` ledger dates: an empty summary while the ledger detail holds rows for themrefuses, so the last published rows stay."""stamp = meta.get("dataEndTime") or meta.get("dataStartTime") or meta.get("createdTime")if not stamp and (table == "listings" or not rows):19 unmodified linestotal += 1if total != source_count:raise ValueError(f"Amazon {table} snapshot row count differs from its document")if table == "inventory" and not total and window:detail, units = _ledger_detail_rows(con, *window), _fba_summary_units(con)if detail or units:evidence = (f"the ledger detail holds {detail} rows for those days" if detailelse f"the FBA inventory summaries hold {units} units")raise ValueError(f"Amazon returned no FBA ledger summary rows for {window[0]} to {window[1]} while "f"{evidence}, so the last inventory rows are kept. ""Retry Amazon sync after Amazon finishes those days")if not counts:counts[_utc(stamp).date().isoformat()] = 0kept = max(counts) if table == "inventory" and len(counts) > 1 else Noneif kept:rows = (rows.pipe(lambda found: (row for row in found if row["_snapshot_date"] == kept)) if lazyelse [row for row in rows if row["_snapshot_date"] == kept])columns = sorted(set(columns) | {"_snapshot_date"}| (rows.keys() if lazy else {k for row in rows for k in row}))if table == "inventory":columns = sorted(set(columns) | {"inventory_source"})mirror = table_name(table)types = _ensure(con, mirror, columns, rows, preserve_rows=True)dates = [kept] if kept else sorted(counts)marker = {"start": dates[0], "end": dates[-1], "column": "_snapshot_date","count": counts[kept] if kept else source_count,"dates": {kept: counts[kept]} if kept else counts, "document": meta.get("reportDocumentId")}if kept:marker.update(documentCount=source_count, documentDates=counts)marker.update({key: meta[key] for key in ("reportId", "processingStatus") if meta.get(key)})if table == "inventory" and meta.get("cancelled") is True and meta.get("processingStatus") == "CANCELLED":marker["cancelled"] = True9 unmodified lines# The ledger keeps every daily snapshot as changes, oldest date first.for day in dates if history else ():_history_merge(con, table, day, f"({predicate}) AND CAST(_snapshot_date AS VARCHAR) = ?", [day])# D-18058: a closed Pacific day can be older than the last open-day empty proof._record_reconciliation(con, table, marker, replace=True)con.execute("COMMIT")return countexcept Exception:1082 unmodified linesreturn countkwargs = {} if spec.get("snapshot") else {"start": _iso(w0), "end": _iso(w1 - timedelta(seconds=1))}ledger_window = Noneif spec.get("dated_snapshot"):kwargs = _ledger_window(datetime.now(timezone.utc))ledger_window = (kwargs["start"][:10], kwargs["end"][:10])options = dict(spec.get("options") or {})if spec.get("period"):options["reportPeriod"] = spec["period"]26 unmodified linescolumns, rows = parse_flat_file(text, **parser_args)rows = normalise_app_dates(table, rows)if table in LEGACY_SNAPSHOT_TABLES:return _replace_legacy_snapshot(con, table, columns, rows, meta, document_row_count(text),window=ledger_window)if spec.get("snapshot"):stamp = meta.get("dataEndTime") or meta.get("dataStartTime") or meta.get("createdTime")if not stamp:2737 unmodified linesreturn len(failures)def ledger_window_selftest(log=print, check=None):"""D-18058: the ledger summary window, newest-date keep, and the empty-summary guard."""import duckdbfailures = []def ck(name, ok):if check:check("[ledger window] " + name, bool(ok))else:log(f" {'ok' if ok else 'FAIL'} {name}")if not ok:failures.append(name)def at(stamp):return datetime.fromisoformat(stamp.replace("Z", "+00:00"))days = {stamp: tuple(day.isoformat() for day in _ledger_days(at(stamp))) for stamp in ("2026-11-27T00:54:23Z", "2026-11-27T08:30:00Z", "2026-03-08T09:30:00Z","2026-03-08T10:30:00Z", "2026-07-01T06:30:00Z", "2026-07-01T07:30:00Z")}ck("00:54Z asks closed Pacific days, never the open 11-26",days["2026-11-27T00:54:23Z"] == ("2026-11-23", "2026-11-25"))ck("after Pacific midnight the closed day joins", days["2026-11-27T08:30:00Z"] == ("2026-11-24", "2026-11-26"))ck("the spring DST change reads Pacific standard and daylight time",days["2026-03-08T09:30:00Z"][1] == "2026-03-07" and days["2026-03-08T10:30:00Z"][1] == "2026-03-07")ck("summer reads Pacific daylight time",days["2026-07-01T06:30:00Z"][1] == "2026-06-29" and days["2026-07-01T07:30:00Z"][1] == "2026-06-30")options = _client().REPORT_TYPES["inventory"].get("options") or {}ck("the summary asks DAILY rows under Amazon's own option name",options.get("aggregatedByTimePeriod") == "DAILY" and "aggregateByTimePeriod" not in options)window = _ledger_window(at("2026-11-27T00:54:23Z"))ck("the request spans whole closed days",window == {"start": "2026-11-23T00:00:00Z", "end": "2026-11-25T23:59:59Z"})header = "date\tmsku\tfnsku\tdisposition\tlocation\tending-warehouse-balance\n"def landed(con, body, document, ledger=("2026-11-23", "2026-11-25")):columns, records = parse_flat_file(header + body, document_id=document,report_type="GET_LEDGER_SUMMARY_VIEW_DATA")meta = {"reportId": document, "processingStatus": "DONE", "reportDocumentId": document,"dataEndTime": "2026-11-25T23:59:59Z"}return _replace_legacy_snapshot(con, "inventory", columns, records, meta,document_row_count(header + body), window=ledger)con = duckdb.connect(":memory:")try:con.execute("CREATE TABLE _sync_state (entity VARCHAR PRIMARY KEY, phase VARCHAR, ""last_id BIGINT, cursor_wd VARCHAR, rows BIGINT, updated_at VARCHAR)")# The old code's last proof: an empty open day dated after the closed day kept below._record_state(con, "amzn_reconcile_inventory", "done", detail=json.dumps({"start": "2026-11-26", "end": "2026-11-26", "column": "_snapshot_date", "count": 0,"dates": {"2026-11-26": 0}, "document": "ledger-open-day"}))body = "".join(f"{day}\tS{i}\tF{i}\tSELLABLE\tUS\t{i + 1}\n"for day in ("11/23/2026", "11/24/2026", "11/25/2026") for i in range(3))landed(con, body, "ledger-three-days")rows = con.execute("SELECT CAST(_snapshot_date AS VARCHAR), COUNT(*) FROM amzn_inventory ""GROUP BY 1 ORDER BY 1").fetchall()marker = json.loads(_read_state(con, "amzn_reconcile_inventory")["detail"])ck("a three-day document keeps only its newest date", rows == [("2026-11-25", 3)])ck("the proof names the kept date and the whole document",marker["start"] == marker["end"] == "2026-11-25" and marker["count"] == 3and marker["documentCount"] == 9 and len(marker["documentDates"]) == 3)ck("the kept snapshot reconciles to its document",_validate_report_snapshot(con, "inventory", marker)["state"] == "ok")con.execute("CREATE TABLE amzn_inventory_ledger_detail (date VARCHAR, msku VARCHAR)")con.execute("INSERT INTO amzn_inventory_ledger_detail VALUES ('2026-11-24', 'S1'), ('2026-11-01', 'S2')")try:landed(con, "", "ledger-empty-with-detail")refused = ""except ValueError as exc:refused = str(exc)ck("an empty summary refuses while the ledger detail shows those days","ledger detail holds 1 rows" in refused and "last inventory rows are kept" in refused)ck("the refused empty summary keeps the last rows",con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 3)con.execute("DELETE FROM amzn_inventory_ledger_detail WHERE date >= '2026-11-23'")con.execute("CREATE TABLE amzn_fba_inventory (seller_sku VARCHAR, total_quantity BIGINT)")con.execute("INSERT INTO amzn_fba_inventory VALUES ('S1', 0), ('S2', 7)")try:landed(con, "", "ledger-empty-with-fba-stock")refused = ""except ValueError as exc:refused = str(exc)ck("an empty summary refuses while the FBA summaries hold stock and the detail lags","FBA inventory summaries hold 7 units" in refusedand con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 3)con.execute("UPDATE amzn_fba_inventory SET total_quantity = 0")landed(con, "", "ledger-truly-empty")marker = json.loads(_read_state(con, "amzn_reconcile_inventory")["detail"])ck("a truly empty seller still lands its empty proof",con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 0and marker["count"] == 0 and marker["dates"] == {"2026-11-25": 0})finally:con.close()return len(failures)def snapshot_selftest(log=print, check=None):"""S66-T47: real sync with in-memory storage and fixture-only vendor transports."""from unittest.mock import patch75 unmodified lineslen(calls) == 1 and (("start" in calls[0] and "end" in calls[0]) if table == "inventory"else ("start" not in calls[0] and "end" not in calls[0]))and result["state"] == "done" and result["remaining"] == 0)# D-18058: a multi-date ledger document stores its newest date (3 of 4 fixture rows).ck(table + " all document rows reconcile", lambda:count() == (2 if table == "listings" else 3) and valid()["state"] == "ok")ck(table + " real sync publishes attributed rows and a durable snapshot", lambda:bool(datastore._publication(con, "amazon").get("snapshot_id"))and bool(rt.blobs.get(MIRROR_PREFIX + _MANIFEST_KEY))31 unmodified lines"ORDER BY 1, 2").fetchall() == [("2026-09-26", "A", 9)]and valid()["state"] == "ok")else:ck("ledger keeps its newest data date, one row per SKU, disposition and location", lambda:con.execute("SELECT COUNT(*), COUNT(DISTINCT (date, msku, disposition, location)), ""COUNT(DISTINCT _snapshot_date), MIN(CAST(_snapshot_date AS VARCHAR)) ""FROM amzn_inventory").fetchone() == (3, 3, 1, "2026-09-24")and calls[0].get("options", {}).get("aggregatedByTimePeriod") == "DAILY")payload[0] = ledger_header + "09/24/2026\tA\tFA\tAA\tSELLABLE\tUS\t9\n"sync(rt.key, tables=[table], since=start, rt=rt, log=lambda *_a: None)# S67-T32 (D-3031, reversed): the next document replaces every earlier FBA date.50 unmodified lines"WHERE inventory_source='FBA'").fetchall() == [(9,)])con.close()ck("inventory request retention and empty-source controls", lambda: inventory_status_selftest(log, check) == 0)ck("D-18058 ledger summary asks closed Pacific days and an empty answer keeps rows",lambda: ledger_window_selftest(log, check) == 0)ck("S67-T32 saved mirror: one copy, content keys, kill-safe checkpoint, full purge",lambda: mirror_selftest(log, check) == 0)return len(failures)261 unmodified linesand Counter(table for table, _kwargs in resync_calls if table in ("orders", "transactions"))== {"orders": 3, "transactions": 3})ck("snapshot transports use no backfill window except the declared ledger day", lambda:all({"start": kwargs.get("start"), "end": kwargs.get("end")} == _ledger_window(Clock.instant)if cx.REPORT_TYPES[table].get("dated_snapshot") elsekwargs.get("start") is None and kwargs.get("end") is Nonefor table, kwargs in resync_calls if table in snapshots))
3457 unmodified lines345834593460346134623463551 unmodified lines4015401640174018401940208 unmodified lines402940304031403240334034403547 unmodified lines4083408440854086408740884089409086 unmodified lines41774178417941804181418241833457 unmodified linesif not (prefix == key + "." and name.startswith(key + ".connection."))]def _flatten(rec, fields, m2m=(), *, named_m2m=None, analytic_names=None, named_m2m_names=None,list_fields=()):out = {"id": rec["id"]}551 unmodified lines[_connection_state_key(key), phase, last_id, cursor_wd, n, time.strftime("%Y-%m-%d %H:%M:%S")])def _base_domain(spec):return list(spec.get("domain") or ()) + ([("active", "in", [True, False])] if spec["archivable"] else [])8 unmodified lines# A recurring refresh may report changed pages to a bespoke cursor, but a# tenant pass cannot claim completion until those private pages finish too.pending = _connection_pending(candidate["con"], key)if phase == "live" and any(row[1] != "done" for row in pending if not row[0].endswith(".pass")):phase = "backfill"return phase, pulledrt = _resident_odoo_runtime()47 unmodified lineslimit=batch, order="id asc")if not recs:# backfill complete → switch to live mode anchored at max write_date seenwd = con.execute(f"SELECT max(write_date) FROM {key} WHERE {_connection_where()}").fetchone()[0]_save_state(con, key, "live", last_id, wd or "1970-01-01 00:00:00")log(f" {key}: BACKFILL COMPLETE ({st['rows'] + pulled:,} rows) -> live mode")return ("live" if columns_ready else "backfill"), pulled_upsert(con, key, spec, recs)86 unmodified linespending = _connection_pending(con, key)# Recurring refreshes have their own bounded cycle, separate from schema# readiness. The public source wrapper also requires that cycle to finish.columns_ready = columns_ready and all(phase == "done" for marker, phase in pendingif not marker.startswith(_connection_state_key(key + ".refresh.")))return ("live" if columns_ready and delta_complete else "backfill"), pulled + refreshedfinally:3457 unmodified lines345834593460346134623463346434653466346734683469551 unmodified lines4021402240234024402540264027402840294030403140324033403440358 unmodified lines4044404540464047404840494050405147 unmodified lines409941004101410241034104410586 unmodified lines419241934194419541964197419841993457 unmodified linesif not (prefix == key + "." and name.startswith(key + ".connection."))]def _connection_marker_complete(key, marker, phase):"""Population markers finish live, while migration and refresh markers finish done."""dynamic = marker.startswith(_connection_state_key(key + ".dynamic."))return phase == ("live" if dynamic else "done")def _flatten(rec, fields, m2m=(), *, named_m2m=None, analytic_names=None, named_m2m_names=None,list_fields=()):out = {"id": rec["id"]}551 unmodified lines[_connection_state_key(key), phase, last_id, cursor_wd, n, time.strftime("%Y-%m-%d %H:%M:%S")])def _save_populated_state(con, key, last_id):"""Anchor static deltas to populated dates and leave dynamic population cursors unassigned."""cursor = Noneif key in ENTITIES:cursor = con.execute(f"SELECT max(write_date) FROM {key} WHERE {_connection_where()}").fetchone()[0]cursor = cursor or "1970-01-01 00:00:00"_save_state(con, key, "live", last_id, cursor)def _base_domain(spec):return list(spec.get("domain") or ()) + ([("active", "in", [True, False])] if spec["archivable"] else [])8 unmodified lines# A recurring refresh may report changed pages to a bespoke cursor, but a# tenant pass cannot claim completion until those private pages finish too.pending = _connection_pending(candidate["con"], key)if phase == "live" and any(not _connection_marker_complete(key, marker, state)for marker, state in pending if not marker.endswith(".pass")):phase = "backfill"return phase, pulledrt = _resident_odoo_runtime()47 unmodified lineslimit=batch, order="id asc")if not recs:# backfill complete → switch to live mode anchored at max write_date seen_save_populated_state(con, key, last_id)log(f" {key}: BACKFILL COMPLETE ({st['rows'] + pulled:,} rows) -> live mode")return ("live" if columns_ready else "backfill"), pulled_upsert(con, key, spec, recs)86 unmodified linespending = _connection_pending(con, key)# Recurring refreshes have their own bounded cycle, separate from schema# readiness. The public source wrapper also requires that cycle to finish.columns_ready = columns_ready and all(_connection_marker_complete(key, marker, phase)for marker, phase in pendingif not marker.startswith(_connection_state_key(key + ".refresh.")))return ("live" if columns_ready and delta_complete else "backfill"), pulled + refreshedfinally:
40 unmodified lines414243444546471757 unmodified lines18051806180718081809181059 unmodified lines18701871187218731874187518761877187818791880188166 unmodified lines1948194919501951195219535 unmodified lines19591960196119621963196419651966329 unmodified lines229622972298229923002301941 unmodified lines32433244324532463247324840 unmodified linesfrom core import amazon_rivals as _rivalsTABLE_KEY = "ut_amazon_sku_profit"TABLE_LABEL = "Project management"PROJECTS_KEY = "ut_amazon_projects"PROJECTS_LABEL = "Projects"ASIN_KEY = "ut_amazon_asin_profit"1757 unmodified lines"suggesting on the rows already stored.")with _LOCK:ensure_table(st, WRITER)report["decisions"] = apply_decisions(st)if catalogue is None:with _odoo_binding(st):59 unmodified linesreturn outdef _project_field_order(keys):"""Pin App fields in schema defaults and keep companions last, without changing saved layouts."""keys = list(keys)if not keys or keys[0] not in ("sku", "asin", "parent_asin"):return keyspinned = ASIN_APP_KEYS if keys[0] == "asin" else (keys[0], "projects", "history")companions = (("projects_label",) + tuple(f["key"] for f in _ASIN_COMPANIONS)if keys[0] == "asin" else ())return ([key for key in pinned if key in keys]66 unmodified linesrows[rid]["match_state"] = LEGACY_MATCH_STATES[rows[rid]["match_state"]]#: The core helper's field placement, kept under this name for its gate._insert_missing = module_tables._insert_missing5 unmodified linesFormat, grain word, cost description and Link status (`_relabel`) repairs stay here."""if table_key is None:# module_tables persists only `fieldLimit`; user_tables.field_limit reads that key.specs = [{"key": s["key"], "label": s["label"], "fields": _definition_fields(s["fields"], s["owned"]),"fieldLimit": PROFIT_MAX_FIELDS}for s in table_specs()]else:specs = [{"key": table_key, "label": label or table_key, "fields": _definition_fields(fields, owned_keys)}]329 unmodified linesreturn out# ---------------------------------------------------------------- refreshdef build_rows(con, period, row_links, thin=THIN_DEFAULT, cost_reader=None, today=None,941 unmodified linesowner, owner_label = default_owner(st, tenant)for spec in table_specs():ensure_views(st, owner or by, table_key=spec["key"], template_key=spec["template"])row_links = links(table_rows(st))receipts, history, cost_problem = None, [], Noneif cost_reader is None:40 unmodified lines4142434445464748491757 unmodified lines180718081809181018111812181359 unmodified lines1873187418751876187718781879188018811882188318841885188618871888188966 unmodified lines1956195719581959196019611962196319641965196619671968196919705 unmodified lines19761977197819791980198119821983329 unmodified lines231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408941 unmodified lines335033513352335333543355335640 unmodified linesfrom core import amazon_rivals as _rivalsTABLE_KEY = "ut_amazon_sku_profit"TABLE_LABEL = "Project manager"#: Earlier module labels of the SKU table. Only these are renamed; a label a person chose stays._PRIOR_TABLE_LABELS = ("Project management", "Command Center", "Amazon SKU profit")PROJECTS_KEY = "ut_amazon_projects"PROJECTS_LABEL = "Projects"ASIN_KEY = "ut_amazon_asin_profit"1757 unmodified lines"suggesting on the rows already stored.")with _LOCK:ensure_table(st, WRITER)reconcile_views(st)report["decisions"] = apply_decisions(st)if catalogue is None:with _odoo_binding(st):59 unmodified linesreturn outdef _pinned_keys(grain):"""The App's pinned columns of one grain table, grain key first."""return ASIN_APP_KEYS if grain == "asin" else (grain, "projects", "history")def _project_field_order(keys):"""Pin App fields in schema defaults and keep companions last, without changing saved layouts."""keys = list(keys)if not keys or keys[0] not in ("sku", "asin", "parent_asin"):return keyspinned = _pinned_keys(keys[0])companions = (("projects_label",) + tuple(f["key"] for f in _ASIN_COMPANIONS)if keys[0] == "asin" else ())return ([key for key in pinned if key in keys]66 unmodified linesrows[rid]["match_state"] = LEGACY_MATCH_STATES[rows[rid]["match_state"]]def _kept_label(st, table_key, label):"""The SKU table label to store: `label` over an earlier module label, else the stored one."""if table_key != TABLE_KEY:return labelimport core.user_tables as utstored = (ut.get_definition(table_key, st=st) or {}).get("label")return label if not stored or stored in _PRIOR_TABLE_LABELS else stored#: The core helper's field placement, kept under this name for its gate._insert_missing = module_tables._insert_missing5 unmodified linesFormat, grain word, cost description and Link status (`_relabel`) repairs stay here."""if table_key is None:# module_tables persists only `fieldLimit`; user_tables.field_limit reads that key.specs = [{"key": s["key"], "label": _kept_label(st, s["key"], s["label"]),"fields": _definition_fields(s["fields"], s["owned"]), "fieldLimit": PROFIT_MAX_FIELDS}for s in table_specs()]else:specs = [{"key": table_key, "label": label or table_key, "fields": _definition_fields(fields, owned_keys)}]329 unmodified linesreturn out#: Grain key of each App table.GRAIN_KEYS = {TABLE_KEY: "sku", ASIN_KEY: "asin", PARENT_KEY: "parent_asin"}#: Columns every stored View of a table keeps, in this order, right after its grain key.VIEW_KEEP = {TABLE_KEY: ("projects",), ASIN_KEY: ("projects", "pdp_update"), PARENT_KEY: ("projects",)}#: Settings member holding `table:owner:view:key` marks, one per pinned key a View was given.VIEW_PINS_KEY = "viewPinsAdded"def register_view_keep():"""Register the kept columns of every App table with the View store."""from core import table_storefor table_key, keys in VIEW_KEEP.items():table_store.register_view_keep(table_key, keys, after=GRAIN_KEYS[table_key])register_view_keep()def pin_mark(table_key, owner, view_id, key):return f"{table_key}:{owner}:{view_id}:{key}"def pinned_view_config(table_key, owner, view_id, config, fields, marks):"""`(config, new marks)`: the kept keys, then each unmarked pinned key that is a stored field, added once."""from core import table_storepins = _pinned_keys(GRAIN_KEYS[table_key])config, made = dict(table_store.kept_config(table_key, config)), set()if not any(isinstance(config.get(part), list) for part in ("visible", "order")):return config, madefor index, key in enumerate(pins[1:], 1):mark = pin_mark(table_key, owner, view_id, key)if key not in fields or mark in marks:continuefor part in ("visible", "order"):columns = config.get(part)if isinstance(columns, list) and key not in columns:before = next((pin for pin in reversed(pins[:index]) if pin in columns), None)config[part] = _insert_after(columns, before, key) if before else [key, *columns]made.add(mark)return config, madedef _stored_views(st, table_key):"""`[(owner, view_id, view, recipient)]` for every personal View and every assigned View of one table."""from core import dependentsfrom core.table_store import ASSIGNED_KEYout = [(owner, view_id, view, None) for owner, view_id, view in dependents.walk_views(st, table_key)]assigned = (dependents._table_doc(st, table_key, assignments=True).get(ASSIGNED_KEY) or {})for recipient, rows in ((assigned.get("views") or {}) if isinstance(assigned, dict) else {}).items():for view_id, row in (rows.items() if isinstance(rows, dict) else ()):if isinstance(row, dict) and isinstance(row.get("presentation"), dict):out.append((f"{ASSIGNED_KEY}/{recipient}", str(view_id),{"config": row["presentation"]}, str(recipient)))return outdef reconcile_views(st, table_keys=None):"""Give every stored View of the App tables its pinned and kept columns. Returns the Views saved.A pinned key is added once per View: a person who hides it later keeps it hidden. A second runwrites nothing."""import core.user_tables as utfrom core import view_templates as vtfrom core.table_store import TableStoremarks = set(read_settings(st).get(VIEW_PINS_KEY) or ())made, saved = set(), 0for table_key in table_keys or GRAIN_KEYS:definition = ut.get_definition(table_key, st=st)if not isinstance(definition, dict):continuefields = {f.get("key") for f in definition.get("fields") or () if isinstance(f, dict)}ops = TableStore(vt.workspace_key(table_key), st)for owner, view_id, view, recipient in _stored_views(st, table_key):# save_view refuses these legacy shapes; nothing reads them as Views now.if view_id.startswith("sv_") or "permissions" in view or not isinstance(view.get("config"), dict):continueconfig, new = pinned_view_config(table_key, owner, view_id, view["config"], fields, marks)made |= newif config == view["config"]:continueif recipient is not None:ops.save_assigned_presentation(recipient, view_id, config)else:ops.save_view(owner, dict(view, id=view_id, config=config), actor=WRITER, origin={"client": VIA})saved += 1if made:write_settings(st, **{VIEW_PINS_KEY: sorted(marks | made)})return saved# ---------------------------------------------------------------- refreshdef build_rows(con, period, row_links, thin=THIN_DEFAULT, cost_reader=None, today=None,941 unmodified linesowner, owner_label = default_owner(st, tenant)for spec in table_specs():ensure_views(st, owner or by, table_key=spec["key"], template_key=spec["template"])reconcile_views(st)row_links = links(table_rows(st))receipts, history, cost_problem = None, [], Noneif cost_reader is None:
45 unmodified lines464748495051177 unmodified lines22923023123223323423523623723823924022 unmodified lines263264265266267268269270271272273274275166 unmodified lines44244344444544644744810 unmodified lines45946046146246346446558 unmodified lines5245255265275285295305315325335345355365375385395404 unmodified lines54554654754854955055155255355437 unmodified lines59259359459559659759859960030 unmodified lines6316326336346356366376383 unmodified lines642643644645646647648649650651652653654655656657658659660661662663117 unmodified lines781782783784785786787246 unmodified lines10341035103610371038103917 unmodified lines105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611572 unmodified lines1160116111621163116411651166116711681169117011711172204 unmodified lines1377137813791380138113821383138413851386138713881389139013911392139313941395139645 unmodified lines"and the next Amazon sync will retry.")BA_DATES_MISSING = "Brand Analytics report dates are missing"BA_WEEKLY_MISSING = "Brand Analytics has no dated weekly reports"LIMIT = "Alerts and checks use separate store rows and server pages, with no row cap."KEY_SETTINGS = "competitor_watch_settings"177 unmodified linesself._put_meta(con, meta)def _insert(self, con, rows):if not rows:returnstatement = self.term_sql("INSERT INTO {terms} (tenant, term, label, active, starred) ""VALUES (%s, %s, %s, %s, %s) ON CONFLICT (tenant, term) DO NOTHING")with con.cursor() as cur:cur.executemany(statement, rows)def seed(self, found, legacy, *, ours=None, tracking_error=None):with self._locked(prepare=True) as (con, meta):22 unmodified linesself._insert(con, [(self.slug, t, display_term(t), True, False) for t in found if t])# Only a checked ownership result may replace membership, including a valid empty set.if ours is not None:con.execute(self.term_sql("UPDATE {terms} SET ours = FALSE WHERE tenant = %s AND ours = TRUE"),[self.slug])self._insert(con, [(self.slug, t, display_term(t), True, False) for t in ours])if ours:with con.cursor() as cur:cur.executemany(self.term_sql("UPDATE {terms} SET ours = TRUE WHERE tenant = %s AND term = %s"),[(self.slug, t) for t in ours])if tracking_error:meta.update(trackingReady=False, trackingCause=tracking_error)elif ours is not None:166 unmodified linesdef _ba_columns(cur):"""Check weekly readiness with metadata and scalar existence checks, without loading source rows."""cols = _columns(cur, BA_TABLE) if cur is not None else set()if cols and not {"_period_start", "_period_end"} <= cols:try:populated = cur.execute(f"SELECT EXISTS(SELECT 1 FROM {BA_TABLE})").fetchone()[0]10 unmodified linesraise _ReadFailed(type(exc).__name__) from excif populated and not weekly:raise SourceNotReady(BA_WEEKLY_MISSING)return colsdef _sqp(cur, term=None):58 unmodified linesreturn {}cs = 'TRY_CAST("click_share" AS DOUBLE)' if "click_share" in cols else "NULL"cv = 'TRY_CAST("conversion_share" AS DOUBLE)' if "conversion_share" in cols else "NULL"pe = 'CAST("_period_end" AS VARCHAR)' if "_period_end" in cols else "''"wanted = None if terms is None else sorted({_norm(t) for t in terms})if wanted == []:return {}where = (f' AND {_term_sql("search_term")} IN (' + ','.join('?' for _ in wanted) + ')'if wanted is not None else '')rows = cur.execute(f'SELECT "search_term", CAST("_period_start" AS VARCHAR), {pe}, "clicked_asin", 'f'TRY_CAST("click_share_rank" AS INTEGER), {cs}, {cv} FROM {BA_TABLE} 'f'WHERE TRY_CAST("click_share_rank" AS INTEGER) BETWEEN 1 AND 3 'f'AND ({_weekly_period_sql()}){where}', wanted or []).fetchall()out = {}for term, start, end, asin, rank, share, conv in rows:key = _norm(term)4 unmodified linesreturn outdef _periods(cur):if not {"_period_start", "_period_end"} <= _ba_columns(cur):return []rows = cur.execute(f'SELECT DISTINCT CAST("_period_start" AS VARCHAR) FROM {BA_TABLE} 'f'WHERE {_weekly_period_sql()}').fetchall()return sorted((str(r[0]) for r in rows if r[0] is not None), reverse=True)37 unmodified linesdef _brand_source_sql(cur):"""Share one dated BA/listings join between membership and bulk click-share readers."""need = {"search_term", "clicked_asin", "click_share_rank", "_period_start", "_period_end"}if cur is None or not need <= _ba_columns(cur) or "asin1" not in _columns(cur, LISTINGS_TABLE):raise SourceNotReady("Tracked terms need dated Brand Analytics and listing ASINs.")if not cur.execute(f"SELECT EXISTS(SELECT 1 FROM {BA_TABLE} WHERE {_weekly_period_sql()})").fetchone()[0]:raise SourceNotReady(BA_WEEKLY_MISSING)return (f"WITH weekly AS (SELECT * FROM {BA_TABLE} WHERE {_weekly_period_sql()}), "f"own_asins AS (SELECT DISTINCT trim(asin1) AS asin FROM {LISTINGS_TABLE} "30 unmodified linesyield from batchdef seed_terms(tenant_key, *, st=None, cur=None):"""Add every distinct SQP search query to the seeded set. A removed term stays removed."""st = _rt(tenant_key, st)index = _term_index(tenant_key, st)3 unmodified linescause = str(exc) if isinstance(exc, _ReadFailed) else type(exc).__name__return f"Tracked terms could not be checked ({cause}). The next Amazon sync will retry."def distinct(reader):if reader is None or "search_query_data_search_query" not in _columns(reader, SQP_TABLE):if reader is not None and _columns(reader, BA_TABLE):return set()raise TermsNotReady(TERMS_NOT_READY)return {r[0] for r in reader.execute(f'SELECT DISTINCT {_term_sql("search_query_data_search_query")} 'f'AS term FROM {SQP_TABLE} WHERE {_term_sql("search_query_data_search_query")} <> \'\'').fetchall()}def source(reader):try:found = distinct(reader)except Exception: # noqa: BLE001if index is None:raise# Discovery only adds retention rows, so a failed read must keep its existing list.found = set()try:ours = _tracked_terms_source(reader)except Exception as exc: # noqa: BLE001117 unmodified linessource_error = Nonetry:with _reader(tenant_key, st) as cur:_ba_columns(cur)except SourceNotReady as exc:source_error = exccause = READ_FAILED.format(cause=exc)246 unmodified linescompare(tenant, ("daily_quotes",), st=st, quote_asins=changed)def compare(tenant_key, synced_tables=("brand_analytics",), *, st=None, now=None, quote_asins=None):"""Compare the newest held week with the week before and raise owned alerts. Returns a summary."""st = _rt(tenant_key, st)17 unmodified linesterms = _comparison_terms(tenant_key, st)held = _top3(cur, terms)ours = _listing_asins(cur)weeks = _doc(st, KEY_WEEKS)newest = periods[0]if daily and weeks.get("last_compared") != newest:return {"state": "awaits_weekly_pull", "period": newest}retry = set(weeks.get("pending_quotes") or ()) & set(quote_asins or ()) if daily else Noneif daily and not retry:return {"state": "already_compared", "period": newest}if not daily and weeks.get("last_compared") == newest:return {"state": "already_compared", "period": newest}previous = periods[1] if len(periods) > 1 else Noneconf = settings(tenant_key, st=st)our_for = {t: _comparison_asin((held.get(t) or {}).get(newest), ours) for t in terms}want = set()for term in terms:want |= set(((held.get(term) or {}).get(newest) or {}).get("rows", {}))if our_for.get(term):want.add(our_for[term])quotes, quote_cause = _daily_quotes(tenant_key, st, want)current = (weeks.get("metrics") or {}).get(newest) or {}metrics = {a: current[a] if daily and a not in retry and a in current else_quote_metric(quotes.get(a), a in ours, quote_cause) for a in sorted(want)}prior = ((weeks.get("metrics") or {}).get(previous) or {}) if previous else {}raised, checks = [], []for asin, metric in metrics.items():parts = list(dict.fromkeys(c for c in (metric.get("priceCause"), metric.get("rankCause")) if c))if metric.get("price") is not None:parts.insert(0, f"Price {metric['price']:,.2f} {metric.get('currency') or ''}.".strip())checks.append({"term": "", "asin": asin, "trigger": "Daily price", "periodStart": newest,"detail": metric, "cause": " ".join(parts)})if previous is not None:undercut = conf["undercut_pct"] / 100.0surge = conf["rank_surge_pct"] / 100.0for term in terms:now_week = (held.get(term) or {}).get(newest)was_week = (held.get(term) or {}).get(previous)if not now_week or not was_week:continuetop_now, top_was = now_week["rows"], was_week["rows"]end = now_week["end"]def found(asin, key, detail, cause=None):raised.append({"term": term, "asin": asin, "trigger": key, "periodStart": newest,"periodEnd": end, "previousPeriodStart": previous, "detail": detail,"cause": cause})def asin_cause(asin):m = metrics.get(asin) or {}return " ".join(c for c in (m.get("priceCause"), m.get("rankCause")) if c) or Nonefor asin in sorted(set(top_now) - set(top_was)) if not daily else ():found(asin, "new_asin", {"rank": top_now[asin][0]}, asin_cause(asin))for asin in sorted((set(top_was) - set(top_now)) & ours) if not daily else ():found(asin, "lost_spot", {"previousRank": top_was[asin][0]})mine = our_for.get(term)mine_m = metrics.get(mine) or {}if mine is None and set(top_now) - ours:checks.append({"term": term, "asin": None, "trigger": TRIGGERS["undercut"],"periodStart": newest,"cause": "None of our listing ASINs is in this term's top 3, so there is ""no price of ours to compare."})for asin in sorted(set(top_now) - ours):m = metrics.get(asin) or {}if mine is None:passelif mine_m.get("price") is None or m.get("price") is None:cause = " ".join(c for c in (mine_m.get("priceCause") and f"Our price: {mine_m['priceCause']}",m.get("priceCause")) if c)checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["undercut"],"periodStart": newest, "cause": cause or "No price was read."})elif m["price"] <= mine_m["price"] * (1 - undercut) and (not daily or asin in retry or mine in retry):found(asin, "undercut", {"ourAsin": mine, "ourPrice": mine_m["price"],"price": m["price"],"percentUnder": round(100 * (1 - m["price"] / mine_m["price"]), 2)},asin_cause(asin))old = (prior.get(asin) or {})if m.get("rank") is None:checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],"periodStart": newest, "cause": m.get("rankCause") or "No sales rank was read."})elif old.get("rank") is None:if old.get("rankCause"):checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],"periodStart": newest,"cause": f"The week before: {old['rankCause']}"})elif m["rank"] <= old["rank"] * (1 - surge) and (not daily or asin in retry):found(asin, "rank_surge", {"rank": m["rank"], "previousRank": old["rank"]},asin_cause(asin))created = _alert_index(tenant_key, st).record(raised, checks, newest, conf["defaultOwner"], now)ready = previous is not Nonedef _weeks(doc):doc = doc if isinstance(doc, dict) else {}doc.setdefault("metrics", {})[newest] = metricsdoc["pending_quotes"] = [asin for asin, metric in metrics.items()if metric.get("price") is None or metric.get("rank") is None]2 unmodified lines"periodStart": newest, "previousPeriodStart": previous,"comparedAt": _stamp(now), "alertsRaised": len(created),"checks": len(checks)}doc.pop("last_error", None)return docst.update(KEY_WEEKS, _weeks)return {"state": "compared" if ready else "waiting", "period": newest, "previous": previous,"created": created, "checks": checks}# --------------------------------------------------------------------------- alertsclass _AlertIndex(_DocumentIndex):204 unmodified lines# --------------------------------------------------------------------------- term detaildef term_detail(tenant_key, term, *, st=None):"""One term's held periods, the newest top 3 with week-over-week change, and the click share trend."""st = _rt(tenant_key, st)key = _norm(term)with _reader(tenant_key, st) as cur:sqp = _sqp(cur, key) if cur is not None else []weeks_held = _top3(cur, [key]).get(key, {})candidates = {a for week in weeks_held.values() for a in week["rows"]}ours = _our_asins(cur, sqp, candidates) if cur is not None else set()periods = sorted(weeks_held, reverse=True)metric_asins = sorted(weeks_held[periods[0]]["rows"]) if periods else []state, *values = _paths(tenant_key, st, KEY_WEEKS, [("comparison",)] +[("metrics", periods[0], asin) for asin in metric_asins])metric = dict(zip(metric_asins, values))top3 = []if periods:newest = weeks_held[periods[0]]["rows"]45 unmodified lines4647484950515253177 unmodified lines23123223323423523623723823924024122 unmodified lines264265266267268269270271272166 unmodified lines43944044144244344444544644744844945045110 unmodified lines46246346446546646746858 unmodified lines5275285295305315325335345355365375385395405415425435445455465474 unmodified lines55255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260337 unmodified lines64164264364464564664764864965030 unmodified lines6816826836846856866876886896906916926936946956966976986997007017027033 unmodified lines707708709710711712713714715716717718719117 unmodified lines837838839840841842843844845246 unmodified lines10921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111817 unmodified lines11361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411752 unmodified lines1178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247204 unmodified lines145214531454145514561457145814591460146114621463146414651466146714681469147014711472147345 unmodified lines"and the next Amazon sync will retry.")BA_DATES_MISSING = "Brand Analytics report dates are missing"BA_WEEKLY_MISSING = "Brand Analytics has no dated weekly reports"#: Stored sync failures that a live probe finding a dated weekly report proves superseded.SUPERSEDED_BY_WEEKLY = frozenset(READ_FAILED.format(cause=cause) for cause in (BA_DATES_MISSING, BA_WEEKLY_MISSING))LIMIT = "Alerts and checks use separate store rows and server pages, with no row cap."KEY_SETTINGS = "competitor_watch_settings"177 unmodified linesself._put_meta(con, meta)def _insert(self, con, rows):statement = self.term_sql("INSERT INTO {terms} (tenant, term, label, active, starred) ""SELECT * FROM unnest(%s::text[], %s::text[], %s::text[], %s::boolean[], %s::boolean[]) ""ON CONFLICT (tenant, term) DO NOTHING")for start in range(0, len(rows), 1000):con.execute(statement, [list(values) for values in zip(*rows[start:start + 1000])])def seed(self, found, legacy, *, ours=None, tracking_error=None):with self._locked(prepare=True) as (con, meta):22 unmodified linesself._insert(con, [(self.slug, t, display_term(t), True, False) for t in found if t])# Only a checked ownership result may replace membership, including a valid empty set.if ours is not None:self._insert(con, [(self.slug, t, display_term(t), True, False) for t in ours])con.execute(self.term_sql("UPDATE {terms} SET ours = (term = ANY(%s)) WHERE tenant = %s ""AND ours IS DISTINCT FROM (term = ANY(%s))"), [list(ours), self.slug, list(ours)])if tracking_error:meta.update(trackingReady=False, trackingCause=tracking_error)elif ours is not None:166 unmodified linesdef _ba_columns(cur):"""Check weekly readiness with metadata and scalar existence checks, without loading source rows."""return _ba_source(cur)[0]def _ba_source(cur):"""The Brand Analytics columns and whether a dated weekly report exists. Unready sources raise."""cols = _columns(cur, BA_TABLE) if cur is not None else set()weekly = Falseif cols and not {"_period_start", "_period_end"} <= cols:try:populated = cur.execute(f"SELECT EXISTS(SELECT 1 FROM {BA_TABLE})").fetchone()[0]10 unmodified linesraise _ReadFailed(type(exc).__name__) from excif populated and not weekly:raise SourceNotReady(BA_WEEKLY_MISSING)return cols, bool(weekly)def _sqp(cur, term=None):58 unmodified linesreturn {}cs = 'TRY_CAST("click_share" AS DOUBLE)' if "click_share" in cols else "NULL"cv = 'TRY_CAST("conversion_share" AS DOUBLE)' if "conversion_share" in cols else "NULL"pe = 'CAST(TRY_CAST("_period_end" AS DATE) AS VARCHAR)'wanted = None if terms is None else sorted({_norm(t) for t in terms})if wanted == []:return {}where = (f' AND {_term_sql("search_term")} IN (SELECT unnest(?::VARCHAR[]))'if wanted is not None else '')rows = cur.execute(f'SELECT "search_term", CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR), {pe}, "clicked_asin", 'f'TRY_CAST("click_share_rank" AS INTEGER), {cs}, {cv} FROM {BA_TABLE} 'f'WHERE TRY_CAST("click_share_rank" AS INTEGER) BETWEEN 1 AND 3 'f'AND ({_weekly_period_sql()}){where}', [wanted] if wanted is not None else []).fetchall()return _ranked_history(rows, wanted)def _ranked_history(rows, wanted=None):out = {}for term, start, end, asin, rank, share, conv in rows:key = _norm(term)4 unmodified linesreturn outdef _page_history(cur, terms, selected):"""Read page week counts and the selected term's ranks in one source scan."""cols = _ba_columns(cur)wanted = sorted(set(terms) | ({selected} if selected else set()))if not wanted or not {"search_term", "_period_start", "_period_end"} <= cols:return {}, {}optional = {name: f'TRY_CAST("{name}" AS {kind})' if name in cols else f'NULL::{kind}'for name, kind in (("clicked_asin", "VARCHAR"), ("click_share_rank", "INTEGER"),("click_share", "DOUBLE"), ("conversion_share", "DOUBLE"))}query = (f'WITH held AS MATERIALIZED (SELECT {_term_sql("search_term")} AS term, ''CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR) AS start, ''CAST(TRY_CAST("_period_end" AS DATE) AS VARCHAR) AS stop, '+ ', '.join(f'{expr} AS "{name}"' for name, expr in optional.items()) +f' FROM {BA_TABLE} WHERE {_weekly_period_sql()} 'f'AND {_term_sql("search_term")} IN (SELECT unnest(?::VARCHAR[]))) ''SELECT term, COUNT(DISTINCT start) AS weeks, NULL AS start, NULL AS stop, ''NULL AS asin, NULL::INTEGER AS rank, NULL::DOUBLE AS share, NULL::DOUBLE AS conversion ''FROM held GROUP BY term UNION ALL ''SELECT term, NULL, start, stop, clicked_asin, click_share_rank, click_share, conversion_share ''FROM held WHERE term = ? AND click_share_rank BETWEEN 1 AND 3')rows = cur.execute(query, [wanted, selected]).fetchall()counts = {term: weeks for term, weeks, *_rest in rows if weeks is not None}history = _ranked_history([(term, *values) for term, weeks, *values in rows if weeks is None])return counts, history.get(selected, {})def term_page_history(tenant_key, page, *, st=None):"""Share the page's weekly scan with selected-term detail without preparing stored state."""st = _rt(tenant_key, st)selected = page["term"]if not page["terms"] and not selected:return {}, {}try:with _reader(tenant_key, st) as cur:counts, history = _page_history(cur, page["terms"], selected)detail = term_detail(tenant_key, selected, st=st, reader=cur, history=history) if selected else {}except Exception as exc:cause = str(exc) if isinstance(exc, _ReadFailed) else type(exc).__name__raise SourceNotReady(cause, page=page) from excreturn counts, detaildef _periods(cur):if not {"_period_start", "_period_end"} <= _ba_columns(cur):return []rows = cur.execute(f'SELECT DISTINCT CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR) FROM {BA_TABLE} 'f'WHERE {_weekly_period_sql()}').fetchall()return sorted((str(r[0]) for r in rows if r[0] is not None), reverse=True)37 unmodified linesdef _brand_source_sql(cur):"""Share one dated BA/listings join between membership and bulk click-share readers."""need = {"search_term", "clicked_asin", "click_share_rank", "_period_start", "_period_end"}cols, weekly = _ba_source(cur)if cur is None or not need <= cols or "asin1" not in _columns(cur, LISTINGS_TABLE):raise SourceNotReady("Tracked terms need dated Brand Analytics and listing ASINs.")if not weekly:raise SourceNotReady(BA_WEEKLY_MISSING)return (f"WITH weekly AS (SELECT * FROM {BA_TABLE} WHERE {_weekly_period_sql()}), "f"own_asins AS (SELECT DISTINCT trim(asin1) AS asin FROM {LISTINGS_TABLE} "30 unmodified linesyield from batchdef _discover_terms(reader):"""Union the two source vocabularies without treating SQP coverage as BA membership."""if reader is None:raise TermsNotReady(TERMS_NOT_READY)sources = []if "search_query_data_search_query" in _columns(reader, SQP_TABLE):sources.append(f'SELECT {_term_sql("search_query_data_search_query")} AS term FROM {SQP_TABLE}')if {"search_term", "_period_start", "_period_end"} <= _columns(reader, BA_TABLE):sources.append(f'SELECT {_term_sql("search_term")} AS term FROM {BA_TABLE} WHERE {_weekly_period_sql()}')if not sources:raise TermsNotReady(TERMS_NOT_READY)return {row[0] for row in reader.execute('SELECT DISTINCT term FROM (' + ' UNION ALL '.join(sources) + ") WHERE term <> ''").fetchall()}def seed_terms(tenant_key, *, st=None, cur=None):"""Discover SQP queries and held weekly BA terms while preserving authored membership."""st = _rt(tenant_key, st)index = _term_index(tenant_key, st)3 unmodified linescause = str(exc) if isinstance(exc, _ReadFailed) else type(exc).__name__return f"Tracked terms could not be checked ({cause}). The next Amazon sync will retry."def source(reader):try:found = _discover_terms(reader)except Exception as exc:if index is None:raisereturn set(), None, failure_cause(exc)try:ours = _tracked_terms_source(reader)except Exception as exc: # noqa: BLE001117 unmodified linessource_error = Nonetry:with _reader(tenant_key, st) as cur:weekly = _ba_source(cur)[1]if weekly:problems = [problem for problem in problems if problem not in SUPERSEDED_BY_WEEKLY]except SourceNotReady as exc:source_error = exccause = READ_FAILED.format(cause=exc)246 unmodified linescompare(tenant, ("daily_quotes",), st=st, quote_asins=changed)def _clear_error(doc):doc = doc if isinstance(doc, dict) else {}doc.pop("last_error", None)return docdef _weekly_state(doc):"""Normalize legacy timestamp week keys before comparing with connector date keys."""out = dict(doc)if out.get("last_compared"):out["last_compared"] = dt.date.fromisoformat(str(out["last_compared"])[:10]).isoformat()metrics = {}for key, value in (out.get("metrics") or {}).items():day = dt.date.fromisoformat(str(key)[:10]).isoformat()if day in metrics and metrics[day] != value:raise SourceNotReady("Stored weekly metrics disagree for one week.")metrics[day] = valueout["metrics"] = metricsreturn outdef compare(tenant_key, synced_tables=("brand_analytics",), *, st=None, now=None, quote_asins=None):"""Compare the newest held week with the week before and raise owned alerts. Returns a summary."""st = _rt(tenant_key, st)17 unmodified linesterms = _comparison_terms(tenant_key, st)held = _top3(cur, terms)ours = _listing_asins(cur)weeks = _weekly_state(_doc(st, KEY_WEEKS))newest = periods[0]if daily and weeks.get("last_compared") != newest:return {"state": "awaits_weekly_pull", "period": newest}retry = set(weeks.get("pending_quotes") or ()) & set(quote_asins or ()) if daily else Noneif daily and not retry:return {"state": "already_compared", "period": newest}if not daily and weeks.get("last_compared") == newest and not weeks.get("last_error"):return {"state": "already_compared", "period": newest}previous = periods[1] if len(periods) > 1 else Noneconf = settings(tenant_key, st=st)want = {asin for term in terms for asin in ((held.get(term) or {}).get(newest) or {}).get("rows", {})}quotes, quote_cause = _daily_quotes(tenant_key, st, want)current = (weeks.get("metrics") or {}).get(newest) or {}metrics = {a: current[a] if daily and a not in retry and a in current else_quote_metric(quotes.get(a), a in ours, quote_cause) for a in sorted(want)}prior = ((weeks.get("metrics") or {}).get(previous) or {}) if previous else {}raised, term_checks = _term_signals(terms, held, periods, ours, metrics, prior, conf, retry)checks = []for asin, metric in metrics.items():parts = list(dict.fromkeys(c for c in (metric.get("priceCause"), metric.get("rankCause")) if c))if metric.get("price") is not None:parts.insert(0, f"Price {metric['price']:,.2f} {metric.get('currency') or ''}.".strip())checks.append({"term": "", "asin": asin, "trigger": "Daily price", "periodStart": newest,"detail": metric, "cause": " ".join(parts)})checks.extend(term_checks)created = _alert_index(tenant_key, st).record(raised, checks, newest, conf["defaultOwner"], now)ready = previous is not Nonedef _weeks(doc):doc = _weekly_state(doc if isinstance(doc, dict) else {})doc.setdefault("metrics", {})[newest] = metricsdoc["pending_quotes"] = [asin for asin, metric in metrics.items()if metric.get("price") is None or metric.get("rank") is None]2 unmodified lines"periodStart": newest, "previousPeriodStart": previous,"comparedAt": _stamp(now), "alertsRaised": len(created),"checks": len(checks)}return _clear_error(doc)st.update(KEY_WEEKS, _weeks)return {"state": "compared" if ready else "waiting", "period": newest, "previous": previous,"created": created, "checks": checks}def _term_signals(terms, held, periods, ours, metrics, prior, conf, retry):"""Derive weekly and quote-retry signals without changing alert state."""raised, checks = [], []if len(periods) < 2:return raised, checksnewest, previous = periods[:2]daily = retry is not Noneundercut, surge = conf["undercut_pct"] / 100.0, conf["rank_surge_pct"] / 100.0for term in terms:now_week = (held.get(term) or {}).get(newest)was_week = (held.get(term) or {}).get(previous)if not now_week or not was_week:continuetop_now, top_was = now_week["rows"], was_week["rows"]def found(asin, key, detail, cause=None):raised.append({"term": term, "asin": asin, "trigger": key, "periodStart": newest,"periodEnd": now_week["end"], "previousPeriodStart": previous,"detail": detail, "cause": cause})def asin_cause(asin):m = metrics.get(asin) or {}return " ".join(c for c in (m.get("priceCause"), m.get("rankCause")) if c) or Nonefor asin in sorted(set(top_now) - set(top_was)) if not daily else ():found(asin, "new_asin", {"rank": top_now[asin][0]}, asin_cause(asin))for asin in sorted((set(top_was) - set(top_now)) & ours) if not daily else ():found(asin, "lost_spot", {"previousRank": top_was[asin][0]})mine = _comparison_asin(now_week, ours)mine_m = metrics.get(mine) or {}if mine is None and set(top_now) - ours:checks.append({"term": term, "asin": None, "trigger": TRIGGERS["undercut"], "periodStart": newest,"cause": "None of our listing ASINs is in this term's top 3, so there is ""no price of ours to compare."})for asin in sorted(set(top_now) - ours):m = metrics.get(asin) or {}if mine is not None:if mine_m.get("price") is None or m.get("price") is None:cause = " ".join(c for c in (mine_m.get("priceCause") and f"Our price: {mine_m['priceCause']}",m.get("priceCause")) if c)checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["undercut"],"periodStart": newest, "cause": cause or "No price was read."})elif m["price"] <= mine_m["price"] * (1 - undercut) and (not daily or asin in retry or mine in retry):found(asin, "undercut", {"ourAsin": mine, "ourPrice": mine_m["price"], "price": m["price"],"percentUnder": round(100 * (1 - m["price"] / mine_m["price"]), 2)}, asin_cause(asin))old = prior.get(asin) or {}if m.get("rank") is None:checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],"periodStart": newest, "cause": m.get("rankCause") or "No sales rank was read."})elif old.get("rank") is None:if old.get("rankCause"):checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],"periodStart": newest, "cause": f"The week before: {old['rankCause']}"})elif m["rank"] <= old["rank"] * (1 - surge) and (not daily or asin in retry):found(asin, "rank_surge", {"rank": m["rank"], "previousRank": old["rank"]}, asin_cause(asin))return raised, checks# --------------------------------------------------------------------------- alertsclass _AlertIndex(_DocumentIndex):204 unmodified lines# --------------------------------------------------------------------------- term detaildef term_detail(tenant_key, term, *, st=None, reader=None, history=None):"""One term's held periods, the newest top 3 with week-over-week change, and the click share trend."""st = _rt(tenant_key, st)key = _norm(term)with contextlib.nullcontext(reader) if reader is not None else _reader(tenant_key, st) as cur:sqp = _sqp(cur, key) if cur is not None else []weeks_held = _top3(cur, [key]).get(key, {}) if history is None else historycandidates = {a for week in weeks_held.values() for a in week["rows"]}ours = _our_asins(cur, sqp, candidates) if cur is not None else set()periods = sorted(weeks_held, reverse=True)metric_asins = sorted(weeks_held[periods[0]]["rows"]) if periods else []variants = (periods[0], periods[0] + "T00:00:00Z", periods[0] + " 00:00:00") if periods else ()state, *values = _paths(tenant_key, st, KEY_WEEKS, [("comparison",)] +[("metrics", week, asin) for asin in metric_asins for week in variants])metric = {asin: next((value for value in values[i * 3:i * 3 + 3] if value is not None), None)for i, asin in enumerate(metric_asins)}top3 = []if periods:newest = weeks_held[periods[0]]["rows"]
748 unmodified lines74975075175275375475598 unmodified lines8548558568578588598604 unmodified lines865866867868869870320 unmodified lines1191119211931194119511961197748 unmodified lineswith bounded(cur, 'product', [code for _, code in codes], st):rows = ([{'pid': pid, 'code': code} for pid, code in codes]if needed is not None and not needed elsepool(team_id=team_id, raw_fields=raw_fields, needed=needed))yield rowsrows.clear()codes.clear()98 unmodified linesreturn out, reportdef pool(team_id=None, t=None, raw_fields=(), *, needed=None):"""One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.CATALOGUE-FIRST, REVENUE LEFT-JOINED (R12 — see decision 4 in the module header). The row set4 unmodified linespasses it into `_sku_rev`), which is why `core.perm_scope.derive_pool_scope` must keepdriving it rather than a post-filter deciding the BU. It does NOT shape the row set: acatalogue has no team."""from harness import canonical_source, datastoresource = canonical_source.active()320 unmodified lines# nothing sold".rows.sort(key=lambda r: -(r["rev_ytd"] or 0.0))_assert_no_pid_collision(rows)_prune_product_overlay(rows, source, prune_generation)return rows748 unmodified lines74975075175275375475575698 unmodified lines8558568578588598608614 unmodified lines866867868869870871872873874320 unmodified lines11951196119711981199120012011202748 unmodified lineswith bounded(cur, 'product', [code for _, code in codes], st):rows = ([{'pid': pid, 'code': code} for pid, code in codes]if needed is not None and not needed elsepool(team_id=team_id, raw_fields=raw_fields, needed=needed,prune_overlay=ids is None))yield rowsrows.clear()codes.clear()98 unmodified linesreturn out, reportdef pool(team_id=None, t=None, raw_fields=(), *, needed=None, prune_overlay=True):"""One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.CATALOGUE-FIRST, REVENUE LEFT-JOINED (R12 — see decision 4 in the module header). The row set4 unmodified linespasses it into `_sku_rev`), which is why `core.perm_scope.derive_pool_scope` must keepdriving it rather than a post-filter deciding the BU. It does NOT shape the row set: acatalogue has no team.`prune_overlay=False` is a page read: the whole-catalogue overlay prune is a store write thatbelongs to whole-catalogue reads, never to a request that hydrates a few selected rows."""from harness import canonical_source, datastoresource = canonical_source.active()320 unmodified lines# nothing sold".rows.sort(key=lambda r: -(r["rev_ytd"] or 0.0))_assert_no_pid_collision(rows)if prune_overlay:_prune_product_overlay(rows, source, prune_generation)return rows
18c86af445a651c7ecbd3085c9d8b5afa5671a13f052ac92abb0ba0d5a78119911d6960eaba5705f228a28044fd45e3716243779a7cdcb2fd007038d4262a56d1c
26 unmodified lines272829303132145 unmodified lines17817918018118218318426 unmodified linesconst ASIN_COLUMNS = { rowHeight: 56, headerTone: { projects: "primary", pdp_update: "primary", history: "primary" },widths: { asin: 150, projects: 210, pdp_update: 170, trend_score: 150, search_trend: 210,market_share_trend: 240, click_share_trend: 240, exposure: 190, funnel_score: 150, history: 150 } } as const;const noReport = (reasonKey: string) => ({ reasonKey, equals: "No search report", text: "No search report" });const signalTrend = (key: string, share: boolean): AppCellDraw => ({ kind: "trend", seriesKey: key + "_series",valueKey: key + "_now", changeKey: key, format: share ? "percent" : "number", showValue: share,145 unmodified lines<AppTableGrid key={`${table}:${gridRevision}`}data={{ database: table, append: COMMAND_CENTER_TABLES[table] === "projects" }}columns={table === "ut_amazon_asin_profit" ? ASIN_COLUMNS : COMMAND_CENTER_COLUMNS} cellRenderers={cellRenderers}history={false} filterPanel={table === "ut_amazon_asin_profit" ? props => <GridFilter {...props} /> : undefined}sortChoices={table === "ut_amazon_asin_profit" ? SIGNAL_SORTS : undefined}toolbar={<AmazonToolbar database={table} />} />}{picture && <PicturePopup pictureRef={picture.ref} label={picture.label}26 unmodified lines272829303132333435363738145 unmodified lines18418518618718818919026 unmodified linesconst ASIN_COLUMNS = { rowHeight: 56, headerTone: { projects: "primary", pdp_update: "primary", history: "primary" },widths: { asin: 150, projects: 210, pdp_update: 170, trend_score: 150, search_trend: 210,market_share_trend: 240, click_share_trend: 240, exposure: 190, funnel_score: 150, history: 150 } } as const;/** Columns no reader may hide, in the order they sit after the grain key. */const ALWAYS_VISIBLE: Readonly<Record<string, readonly string[]>> = {ut_amazon_asin_profit: ["projects", "pdp_update"],[AMAZON_PROFIT_TABLE]: ["projects"],ut_amazon_parent_profit: ["projects"],};const noReport = (reasonKey: string) => ({ reasonKey, equals: "No search report", text: "No search report" });const signalTrend = (key: string, share: boolean): AppCellDraw => ({ kind: "trend", seriesKey: key + "_series",valueKey: key + "_now", changeKey: key, format: share ? "percent" : "number", showValue: share,145 unmodified lines<AppTableGrid key={`${table}:${gridRevision}`}data={{ database: table, append: COMMAND_CENTER_TABLES[table] === "projects" }}columns={table === "ut_amazon_asin_profit" ? ASIN_COLUMNS : COMMAND_CENTER_COLUMNS} cellRenderers={cellRenderers}history={false} alwaysVisible={ALWAYS_VISIBLE[table]} filterPanel={table === "ut_amazon_asin_profit" ? props => <GridFilter {...props} /> : undefined}sortChoices={table === "ut_amazon_asin_profit" ? SIGNAL_SORTS : undefined}toolbar={<AmazonToolbar database={table} />} />}{picture && <PicturePopup pictureRef={picture.ref} label={picture.label}
861 unmodified lines862863864865866867868861 unmodified linesconst term = query.trim().toLowerCase();const choices = (all ?? []).filter((project) => !exclude.has(project.id) && (!term || project.name.toLowerCase().includes(term)));if (!canEdit) return <p className="lp-proj-muted" role="status">Only an editor of Project management can change projects.</p>;return <div className="lp-proj-search"><div className="lp-proj-search-bar">861 unmodified lines862863864865866867868861 unmodified linesconst term = query.trim().toLowerCase();const choices = (all ?? []).filter((project) => !exclude.has(project.id) && (!term || project.name.toLowerCase().includes(term)));if (!canEdit) return <p className="lp-proj-muted" role="status">Only an editor of Project manager can change projects.</p>;return <div className="lp-proj-search"><div className="lp-proj-search-bar">
181 unmodified lines182183184185186187188671 unmodified lines86086186286386486533 unmodified lines8999009019029039049059069079089099109119129139149151900 unmodified lines2816281728182819282028212822282328242825282628272828508 unmodified lines333733383339334033413342334333443345334622 unmodified lines336933703371337233733374337533763377337815 unmodified lines339433953396339733983399340096 unmodified lines349734983499350035013502249 unmodified lines37523753375437553756375737589 unmodified lines3768376937703771377237733774377537763777377837793780378137823783378437853786378742 unmodified lines3830383138323833383438353836156 unmodified lines39933994399539963997399895 unmodified lines409440954096409740984099208 unmodified lines430843094310431143124313431413 unmodified lines43284329433043314332433343347079 unmodified lines114141141511416114171141811419114201834 unmodified lines1325513256132571325813259132601326185 unmodified lines13347133481334913350133511335213353181 unmodified linesimport type { Tombstones } from "./liveWorkspace";import type { CustomersPayload, GridFolder, VisibleRow } from "./types";import type { ShowAs, SummaryChoice, SummaryMap } from "./types";import { fieldClassOf, mayDeleteField as mayDeleteFieldRight } from "../filter-kit/fieldClass";import type { FieldStamps } from "./optimism";import { orderFormulas, parseFormula } from "./formulaEngine";import type { FormulaAst } from "./formulaEngine";671 unmodified linesorder: string[];visible: Set<string>;lockedKey: string;fieldByKey: Map<string, Field>;isUserTable: boolean;scope: SurfaceScope;33 unmodified linesexport function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors {const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope,rowsPath, setFields, stampFieldDelete, viewer } = deps;const emitHostEvent = useMemo(() => bindHostEvent(scope), [scope]);const onSetFieldsHidden = useCallback((keys: string[], hidden: boolean) => {const next = new Set(visible);for (const key of keys) {if (hidden) {if (key !== lockedKey) next.delete(key);} else next.add(key);}updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] });}, [config, lockedKey, updateConfig, visible]);const onDeleteFields = useCallback((keys: string[]) => {const overlay: string[] = [];1900 unmodified linesonEmbeddedRecordsMutableChange?.(embeddedRecordsMutable);}, [onEmbeddedRecordsMutableChange, embeddedRecordsMutable]);const payloadFields = useMemo(() => {if (!payload?.workspace?.auditTimestamps || payloadFieldsRaw.some((field) => field.key === "_updated"))return payloadFieldsRaw;return [...payloadFieldsRaw, {key: "_updated", label: "Last updated", type: "date", source: "odoo",derived: true, origin: "system", valueAuthority: "derived",} satisfies Field];}, [payloadFieldsRaw, payload?.workspace?.auditTimestamps]);/*** ⭐ WAVE 27 · OWNER ITEM 2 (contract C2) — **ROWS THIS BROWSER JUST CREATED**, held locally* until the server's own copy comes back.508 unmodified linesentry.op.view_id === before.id && entry.status !== "refused" &&(entry.status !== "acked" || entry.readAfter === undefined ||workspaceReadOrder(payload?.workspace) < entry.readAfter)).map((entry) => entry.paint);const canonical = { ...stored, config: normalizeMemberConfig(stored.config) };const previous = { ...canonical, ...applyPendingOps(canonical, pending) };const base = { ...before, config: normalizeMemberConfig(before.config) };const next = { ...after, config: normalizeMemberConfig(after.config, base.config) };const intent = diffViewOps(base, next);const merged = { ...previous, ...applyPendingOps(previous, intent) };const ops = diffViewOps(previous, merged);22 unmodified lines}}return painted;}, [scope, emitHostEvent, payload?.workspace]);const overlayNativeView = useCallback((view: SavedView) => {const ledger = nativeViewLedger.current;const server = { ...view, config: normalizeMemberConfig(view.config) };for (const edit of editOutbox.snapshot().pending) {const event = edit.payload as Extract<HostEvent, { type: "view_op" }>;if (edit.scope !== scope || edit.kind !== "event" || event.type !== "view_op" || event.view_id !== view.id) continue;15 unmodified lines}const restored = { ...server, ...applyPendingOps(server, paints) };return restored;}, [scope, payload?.workspace]);useEffect(() => {if (embedded || queryBinding || hostOwnsLayout) return;return editOutbox.subscribeReceipts((edit, receipt) => {96 unmodified lines: surfaceStorageKey.startsWith(LOCAL_KEY_PREFIX)? `${LOCAL_KEY_PREFIX}${embedStorageKey(surfaceStorageKey.slice(LOCAL_KEY_PREFIX.length), true)}`: embedStorageKey(surfaceStorageKey, true);// A parent may rebuild an equivalent tree on every render. Depend on its value, not its identity,// so the initialization effect cannot re-seed over an edit still settling in this surface.const cellFilterKey = useMemo(() => JSON.stringify(cellFilter ?? null), [cellFilter]);249 unmodified linesuseEffect(() => {// `hostWorkspace`: this adopts views out of `payload.workspace`, which a Query surface never// fetches. Keyed on `embedded` it would read a workspace that is not there.if (!workspaceReady || !hostWorkspace) return;if (workspaceError) {// S72-T57: a failed refresh keeps the last rail; writes stay withheld by `readOnly`.if (workspaceRefreshFailed) return;9 unmodified linesreturn;}const now = Date.now();/*** ⭐⭐ W36-T02 (owner item 1) — CORRECT, THEN ADOPT. The two steps answer two questions and* this effect used to ask only the second one.** ⛔ THE DEFECT, reproduced in `_test/gridUx.test.ts` T01/D before it was fixed: both merges* below are add-only, and add-only was implemented as "skip any id I already hold" — which* also means CANNOT CORRECT. So an edit made on the owner's machine reached this browser (the* change-token poller notices and `reread()` fetches it) and was then thrown away, leaving a* pre-edit filter tree and a pre-edit `agg` in place until a remount. Measured* `{rows: 2, totals: false}` against a reload's `{rows: 4, totals: true, sum: "$4,000"}` off* the SAME server state — the owner's *"only when I refresh it works"*, both symptoms, one* cause. ⚠ The PRD blamed an init RACE; that one is real but self-healing, because* `storageKey` is derived from the workspace and re-arms the guard. See mailbox/B.md B-1.*/const heldFields = reconcileHeldFields(fields, payloadFields, fieldStampsRef.current, now);const nextFields = adoptNewFields(heldFields, payloadFields, fieldStampsRef.current.deleted, now42 unmodified lines// ⚠ TERMINATION IS THE IDENTITY CONTRACT, not a flag: once corrected, both merges return// their input by reference and `nextViews === views`, so the next pass sets nothing and the// effect stops. That is why `views` can be a dependency at all.}, [workspaceReady, hostWorkspaceViews, payloadFields, fields, views, activeViewId,hostWorkspace, workspaceError, workspaceRefreshFailed, scope, payload?.workspace,overlayNativeView, saveStatus]);156 unmodified linesorder,visible,lockedKey,onColumnResize,onColumnMoved,onColumnProposeMove,95 unmodified linesorder,visible,lockedKey,fieldByKey,isUserTable,scope,208 unmodified linespersonalLayoutInitialized, storageKey, viewAsReadOnly]);useEffect(() => {if (viewAsReadOnly || !workspaceReady || embedded || hostOwnsLayout) return;const active = views.find((view) => view.id === activeViewId);if (!active || retiredHostViewIds.has(active.id) ||!canSaveViewDisplay(active.config.display, config.display) || sameConfig(active.config, config)) return;13 unmodified lineselse if (routed.channel === "query")void routed.result.then((result) => { if (!result.ok) signal(TOAST_EVENT, result.message); });}}, [workspaceReady, activeViewId, config, views, embedded, queryBinding, scope, hostOwnsLayout,emitHostEvent, retiredHostViewIds, sendNativeViewOps, viewAsReadOnly]);// Loading can replace the grid node without changing workspace readiness.7079 unmodified linesonColumnsVisible={(keys) =>updateConfig({...config,visible: [...new Set([lockedKey, ...keys])],})}// Owner item 23 — the Hide-fields panel lists and reorders COLUMN order, so it is1834 unmodified lines}}onClose={() => setColumnMenu(null)}onHide={() => {setColumnVisible(menuField.key, false);setColumnMenu(null);}}onSort={(dir) => {85 unmodified lines*/onNote={(note) => saveField({ ...menuField, note })}onHide={() => {setColumnVisible(menuField.key, false);setColumnMenu(null);}}onCreate={createField}181 unmodified lines182183184185186187188671 unmodified lines86086186286386486586686733 unmodified lines9019029039049059069079089099109119129139149159169171900 unmodified lines2818281928202821282228232824282528262827508 unmodified lines333633373338333933403341334233433344334522 unmodified lines336833693370337133723373337433753376337715 unmodified lines339333943395339633973398339996 unmodified lines34963497349834993500350135023503249 unmodified lines37533754375537563757375837599 unmodified lines37693770377137723773377442 unmodified lines3817381838193820382138223823156 unmodified lines398039813982398339843985398695 unmodified lines4082408340844085408640874088208 unmodified lines429742984299430043014302430313 unmodified lines43174318431943204321432243237079 unmodified lines114031140411405114061140711408114091834 unmodified lines132441324513246132471324813249132501325185 unmodified lines1333713338133391334013341133421334313344181 unmodified linesimport type { Tombstones } from "./liveWorkspace";import type { CustomersPayload, GridFolder, VisibleRow } from "./types";import type { ShowAs, SummaryChoice, SummaryMap } from "./types";import { fieldClassOf, LOCKED_HIDE_REFUSAL, mayDeleteField as mayDeleteFieldRight } from "../filter-kit/fieldClass";import type { FieldStamps } from "./optimism";import { orderFormulas, parseFormula } from "./formulaEngine";import type { FormulaAst } from "./formulaEngine";671 unmodified linesorder: string[];visible: Set<string>;lockedKey: string;/** Columns a hide leaves shown, beside the first column. */alwaysVisible?: readonly string[];fieldByKey: Map<string, Field>;isUserTable: boolean;scope: SurfaceScope;33 unmodified linesexport function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors {const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope,rowsPath, setFields, stampFieldDelete, viewer, alwaysVisible } = deps;const emitHostEvent = useMemo(() => bindHostEvent(scope), [scope]);const onSetFieldsHidden = useCallback((keys: string[], hidden: boolean) => {const next = new Set(visible);for (const key of keys) {if (hidden) {if (key !== lockedKey && !alwaysVisible?.includes(key)) next.delete(key);} else next.add(key);}updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] });}, [alwaysVisible, config, lockedKey, updateConfig, visible]);const onDeleteFields = useCallback((keys: string[]) => {const overlay: string[] = [];1900 unmodified linesonEmbeddedRecordsMutableChange?.(embeddedRecordsMutable);}, [onEmbeddedRecordsMutableChange, embeddedRecordsMutable]);const payloadFields = useMemo(() => {const layout = (payload?.workspace?.layoutFields ?? []).filter((field) => !payloadFieldsRaw.some((existing) => existing.key === field.key));return layout.length ? [...payloadFieldsRaw, ...layout] : payloadFieldsRaw;}, [payloadFieldsRaw, payload?.workspace?.layoutFields]);/*** ⭐ WAVE 27 · OWNER ITEM 2 (contract C2) — **ROWS THIS BROWSER JUST CREATED**, held locally* until the server's own copy comes back.508 unmodified linesentry.op.view_id === before.id && entry.status !== "refused" &&(entry.status !== "acked" || entry.readAfter === undefined ||workspaceReadOrder(payload?.workspace) < entry.readAfter)).map((entry) => entry.paint);const canonical = { ...stored, config: normalizeMemberConfig(normalizeConfig(stored.config, fields)) };const previous = { ...canonical, ...applyPendingOps(canonical, pending) };const base = { ...before, config: normalizeMemberConfig(normalizeConfig(before.config, fields)) };const next = { ...after, config: normalizeMemberConfig(normalizeConfig(after.config, fields), base.config) };const intent = diffViewOps(base, next);const merged = { ...previous, ...applyPendingOps(previous, intent) };const ops = diffViewOps(previous, merged);22 unmodified lines}}return painted;}, [scope, emitHostEvent, payload?.workspace, fields]);const overlayNativeView = useCallback((view: SavedView) => {const ledger = nativeViewLedger.current;const server = { ...view, config: normalizeMemberConfig(normalizeConfig(view.config, fields)) };for (const edit of editOutbox.snapshot().pending) {const event = edit.payload as Extract<HostEvent, { type: "view_op" }>;if (edit.scope !== scope || edit.kind !== "event" || event.type !== "view_op" || event.view_id !== view.id) continue;15 unmodified lines}const restored = { ...server, ...applyPendingOps(server, paints) };return restored;}, [scope, payload?.workspace, fields]);useEffect(() => {if (embedded || queryBinding || hostOwnsLayout) return;return editOutbox.subscribeReceipts((edit, receipt) => {96 unmodified lines: surfaceStorageKey.startsWith(LOCAL_KEY_PREFIX)? `${LOCAL_KEY_PREFIX}${embedStorageKey(surfaceStorageKey.slice(LOCAL_KEY_PREFIX.length), true)}`: embedStorageKey(surfaceStorageKey, true);// Effects may use only the workspace state admitted by their render, before initialization queues its replacement.const workspaceInitialized = workspaceReady && initializedKey.current === storageKey;// A parent may rebuild an equivalent tree on every render. Depend on its value, not its identity,// so the initialization effect cannot re-seed over an edit still settling in this surface.const cellFilterKey = useMemo(() => JSON.stringify(cellFilter ?? null), [cellFilter]);249 unmodified linesuseEffect(() => {// `hostWorkspace`: this adopts views out of `payload.workspace`, which a Query surface never// fetches. Keyed on `embedded` it would read a workspace that is not there.if (!workspaceInitialized || !hostWorkspace) return;if (workspaceError) {// S72-T57: a failed refresh keeps the last rail; writes stay withheld by `readOnly`.if (workspaceRefreshFailed) return;9 unmodified linesreturn;}const now = Date.now();const heldFields = reconcileHeldFields(fields, payloadFields, fieldStampsRef.current, now);const nextFields = adoptNewFields(heldFields, payloadFields, fieldStampsRef.current.deleted, now42 unmodified lines// ⚠ TERMINATION IS THE IDENTITY CONTRACT, not a flag: once corrected, both merges return// their input by reference and `nextViews === views`, so the next pass sets nothing and the// effect stops. That is why `views` can be a dependency at all.}, [workspaceInitialized, hostWorkspaceViews, payloadFields, fields, views, activeViewId,hostWorkspace, workspaceError, workspaceRefreshFailed, scope, payload?.workspace,overlayNativeView, saveStatus]);156 unmodified linesorder,visible,lockedKey,alwaysVisible,onColumnResize,onColumnMoved,onColumnProposeMove,95 unmodified linesorder,visible,lockedKey,alwaysVisible,fieldByKey,isUserTable,scope,208 unmodified linespersonalLayoutInitialized, storageKey, viewAsReadOnly]);useEffect(() => {if (viewAsReadOnly || !workspaceInitialized || embedded || hostOwnsLayout) return;const active = views.find((view) => view.id === activeViewId);if (!active || retiredHostViewIds.has(active.id) ||!canSaveViewDisplay(active.config.display, config.display) || sameConfig(active.config, config)) return;13 unmodified lineselse if (routed.channel === "query")void routed.result.then((result) => { if (!result.ok) signal(TOAST_EVENT, result.message); });}}, [workspaceInitialized, activeViewId, config, views, embedded, queryBinding, scope, hostOwnsLayout,emitHostEvent, retiredHostViewIds, sendNativeViewOps, viewAsReadOnly]);// Loading can replace the grid node without changing workspace readiness.7079 unmodified linesonColumnsVisible={(keys) =>updateConfig({...config,visible: [...new Set([lockedKey, ...alwaysVisible, ...keys])],})}// Owner item 23 — the Hide-fields panel lists and reorders COLUMN order, so it is1834 unmodified lines}}onClose={() => setColumnMenu(null)}onHide={() => {if (alwaysVisible.includes(menuField.key)) signal(TOAST_EVENT, LOCKED_HIDE_REFUSAL);else setColumnVisible(menuField.key, false);setColumnMenu(null);}}onSort={(dir) => {85 unmodified lines*/onNote={(note) => saveField({ ...menuField, note })}onHide={() => {if (alwaysVisible.includes(menuField.key)) signal(TOAST_EVENT, LOCKED_HIDE_REFUSAL);else setColumnVisible(menuField.key, false);setColumnMenu(null);}}onCreate={createField}
1018 unmodified lines1019102010211022102310241018 unmodified linesonShowAll={() => onColumnsVisible(fields.map((field) => field.key))}onHideAll={() => onColumnsVisible([lockedKey])}lockedKey={lockedKey}onFieldOrder={onFieldOrder}deletableKeys={deletableKeys}onDeleteField={onDeleteField}1018 unmodified lines10191020102110221023102410251018 unmodified linesonShowAll={() => onColumnsVisible(fields.map((field) => field.key))}onHideAll={() => onColumnsVisible([lockedKey])}lockedKey={lockedKey}alwaysVisibleKeys={appHost?.alwaysVisible}onFieldOrder={onFieldOrder}deletableKeys={deletableKeys}onDeleteField={onDeleteField}
83 unmodified lines84858687888983 unmodified lines/** Drawn in the toolbar's mode slot, beside the grid's History. */toolbar?: ReactNode;history?: boolean;filterPanel?: (props: AppFilterPanelProps) => ReactNode;sortChoices?: readonly AppSortChoice[];}83 unmodified lines848586878889909183 unmodified lines/** Drawn in the toolbar's mode slot, beside the grid's History. */toolbar?: ReactNode;history?: boolean;/** Columns no hide door may hide, kept in this order right after the first column. */alwaysVisible?: readonly string[];filterPanel?: (props: AppFilterPanelProps) => ReactNode;sortChoices?: readonly AppSortChoice[];}
61 unmodified lines62636465666768697071727374757661 unmodified lines}, [database, refusal]);const pickedMode = heightPick?.key === heightKey ? heightPick.mode : undefined;const { data, columns: hostColumns, cellRenderers, toolbar, history, filterPanel, sortChoices } = appHost;const host = useMemo<AppTableHost>(() => ({ data, cellRenderers, toolbar, history, filterPanel, sortChoices,columns: { ...hostColumns,rowHeightMode: hostColumns?.rowHeightMode ?? pickedMode,onRowHeightModeChange: (mode) => {setHeightPick({ key: heightKey, mode });try { localStorage.setItem(heightKey, mode); } catch { /* The pick lasts for this mount. */ }hostColumns?.onRowHeightModeChange?.(mode);} } }), [data, cellRenderers, toolbar, history, filterPanel, sortChoices, hostColumns, pickedMode, heightKey]);const current = admission?.database === database ? admission : null;const message = refusal || current?.refusal;61 unmodified lines6263646566676869707172737475767761 unmodified lines}, [database, refusal]);const pickedMode = heightPick?.key === heightKey ? heightPick.mode : undefined;const { data, columns: hostColumns, cellRenderers, toolbar, history, filterPanel, sortChoices, alwaysVisible } = appHost;const host = useMemo<AppTableHost>(() => ({ data, cellRenderers, toolbar, history, filterPanel, sortChoices, alwaysVisible,columns: { ...hostColumns,rowHeightMode: hostColumns?.rowHeightMode ?? pickedMode,onRowHeightModeChange: (mode) => {setHeightPick({ key: heightKey, mode });try { localStorage.setItem(heightKey, mode); } catch { /* The pick lasts for this mount. */ }hostColumns?.onRowHeightModeChange?.(mode);} } }), [data, cellRenderers, toolbar, history, filterPanel, sortChoices, alwaysVisible, hostColumns, pickedMode,heightKey]);const current = admission?.database === database ? admission : null;const message = refusal || current?.refusal;
5225 unmodified lines5226522752285229523052315225 unmodified linesfields?: Field[];/** W48-T10: scoped record/field audit values, never bucket metadata. */auditTimestamps?: Record<string, { record: string; fields: Record<string, string> }>;/** C4 — the view rail's folders. Absent = no folders, the pre-wave-8 shape. */folders?: GridFolder[];/** C4 — the cohort rail's folders (the cohort page's workspace). */5225 unmodified lines522652275228522952305231523252335225 unmodified linesfields?: Field[];/** W48-T10: scoped record/field audit values, never bucket metadata. */auditTimestamps?: Record<string, { record: string; fields: Record<string, string> }>;/** Server-owned presentation fields with no cell or schema write authority. */layoutFields?: Field[];/** C4 — the view rail's folders. Absent = no folders, the pre-wave-8 shape. */folders?: GridFolder[];/** C4 — the cohort rail's folders (the cohort page's workspace). */
285 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931025 unmodified lines33633733833934034122 unmodified lines36436536636736836937037137237337474 unmodified lines44945045145245345445511 unmodified lines46746846947047147247347447547647747847948048148248348448548648748848914 unmodified lines504505506507508509285 unmodified lines};}function reconcileOrder(order: string[], fields: Field[]): string[] {const valid = new Set(fields.map((field) => field.key));const kept = order.filter((key, index) => valid.has(key) && order.indexOf(key) === index);for (const field of fields) if (!kept.includes(field.key)) kept.push(field.key);const locked = fields.find((field) => field.pinned)?.key ?? fields[0]?.key;if (locked && kept[0] !== locked) {const without = kept.filter((key) => key !== locked);return [locked, ...without];}return kept;}function reconcileVisible(visible: string[], fields: Field[], lockedKey: string): Set<string> {const valid = new Set(fields.map((field) => field.key));const out = new Set(visible.filter((key) => valid.has(key)));if (out.size === 0) {for (const field of fields) if (isDefaultVisible(field)) out.add(field.key);}if (lockedKey) out.add(lockedKey);return out;}25 unmodified linesvisible: Set<string>;widths: Record<string, number>;lockedKey: string;onColumnResize: (col: GridColumn, newSize: number) => void;onColumnMoved: (from: number, to: number) => void;onColumnProposeMove: (from: number, to: number) => boolean;22 unmodified lines() => fields.find((field) => field.pinned)?.key ?? fields[0]?.key ?? "",[fields]);const order = useMemo(() => reconcileOrder(config.order, fields), [config.order, fields]);const visible = useMemo(() => reconcileVisible(config.visible, fields, lockedKey),[config.visible, fields, lockedKey]);// Item 22 — recomputed only when the three controls move, not on every width drag.// Wave-20 item 2 adds `fields`: a measure condition can only be resolved to the column that74 unmodified linesconst onColumnMoved = useCallback((from: number, to: number) => {if (from === 0 || to === 0) return;const visibleKeys = order.filter((key) => visible.has(key));if (from < 0 ||11 unmodified lines);onConfig({ ...config, order: nextOrder });},[config, onConfig, order, visible]);const onColumnProposeMove = useCallback((from: number, to: number) => from !== 0 && to !== 0,[]);const setColumnVisible = useCallback((key: string, show: boolean) => {if (!show && key === lockedKey) return;const next = new Set(visible);if (show) next.add(key);else next.delete(key);onConfig({ ...config, visible: [...next] });},[config, lockedKey, onConfig, visible]);const insertColumn = useCallback(14 unmodified linesvisible,widths: config.widths,lockedKey,onColumnResize,onColumnMoved,onColumnProposeMove,285 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231325 unmodified lines33934034134234334434534622 unmodified lines36937037137237337437537637737837938038138238338438538638738838939074 unmodified lines46546646746846947047111 unmodified lines48348448548648748848949049149249349449549649749849950050150250350450514 unmodified lines520521522523524525526285 unmodified lines};}// Defaults stay inline literals: verify_grid_ux runs these functions extracted from the module.function reconcileOrder(order: string[], fields: Field[], alwaysVisible: readonly string[] = []): string[] {const valid = new Set(fields.map((field) => field.key));const kept = order.filter((key, index) => valid.has(key) && order.indexOf(key) === index);for (const field of fields) if (!kept.includes(field.key)) kept.push(field.key);const locked = fields.find((field) => field.pinned)?.key ?? fields[0]?.key;const head = [locked ?? "", ...alwaysVisible].filter((key, index, all) =>valid.has(key) && all.indexOf(key) === index);if (head.every((key, index) => kept[index] === key)) return kept;return [...head, ...kept.filter((key) => !head.includes(key))];}function reconcileVisible(visible: string[], fields: Field[], lockedKey: string, alwaysVisible: readonly string[] = []): Set<string> {const valid = new Set(fields.map((field) => field.key));const out = new Set(visible.filter((key) => valid.has(key)));if (out.size === 0) {for (const field of fields) if (isDefaultVisible(field)) out.add(field.key);}if (lockedKey) out.add(lockedKey);for (const key of alwaysVisible) if (valid.has(key)) out.add(key);return out;}25 unmodified linesvisible: Set<string>;widths: Record<string, number>;lockedKey: string;/** The host's unhideable columns that this table has, in the host's order. */alwaysVisible: readonly string[];onColumnResize: (col: GridColumn, newSize: number) => void;onColumnMoved: (from: number, to: number) => void;onColumnProposeMove: (from: number, to: number) => boolean;22 unmodified lines() => fields.find((field) => field.pinned)?.key ?? fields[0]?.key ?? "",[fields]);const hostAlwaysVisible = appHost?.alwaysVisible;const alwaysVisible = useMemo(() => (hostAlwaysVisible ?? []).filter((key, index, all) =>key !== lockedKey && fieldByKey.has(key) && all.indexOf(key) === index),[hostAlwaysVisible, lockedKey, fieldByKey]);const order = useMemo(() => reconcileOrder(config.order, fields, alwaysVisible),[config.order, fields, alwaysVisible]);const visible = useMemo(() => reconcileVisible(config.visible, fields, lockedKey, alwaysVisible),[config.visible, fields, lockedKey, alwaysVisible]);// The first column and the unhideable ones after it hold their slots.const fixedSpan = 1 + alwaysVisible.length;// Item 22 — recomputed only when the three controls move, not on every width drag.// Wave-20 item 2 adds `fields`: a measure condition can only be resolved to the column that74 unmodified linesconst onColumnMoved = useCallback((from: number, to: number) => {if (from < fixedSpan || to < fixedSpan) return;const visibleKeys = order.filter((key) => visible.has(key));if (from < 0 ||11 unmodified lines);onConfig({ ...config, order: nextOrder });},[config, fixedSpan, onConfig, order, visible]);const onColumnProposeMove = useCallback((from: number, to: number) => !(from >= 0 && from < fixedSpan) && !(to >= 0 && to < fixedSpan),[fixedSpan]);const setColumnVisible = useCallback((key: string, show: boolean) => {if (!show && (key === lockedKey || alwaysVisible.includes(key))) return;const next = new Set(visible);if (show) next.add(key);else next.delete(key);onConfig({ ...config, visible: [...next] });},[alwaysVisible, config, lockedKey, onConfig, visible]);const insertColumn = useCallback(14 unmodified linesvisible,widths: config.widths,lockedKey,alwaysVisible,onColumnResize,onColumnMoved,onColumnProposeMove,
123430 unmodified lines35363738394089 unmodified lines1301311321331341352 unmodified lines13813914014114214314469 unmodified lines21421521621721821922022122222322422511 unmodified lines23723823924024124224324497 unmodified lines342343344345346347348import { isFilterGroup, mintFilterNodeId } from "./types";import type { DisplaySpec, FilterNode, SavedView, SortRule, ViewConfig, ViewMember,ViewMemberFamily, ViewMemberOp } from "./types";export type { ViewMember, ViewMemberOp } from "./types";30 unmodified linesconst POSITION = /^[0-9A-Za-z]{1,64}$/;const scalars = ["colorBy", "rowHeightMode", "frozenCount", "important", "secondaryView","application", "fullscreen"] as const;type Snapshot = Pick<SavedView, "id" | "config"> & Partial<Pick<SavedView, "name" | "note" | "locked">>;type Input = Snapshot | ViewConfig;type FilterValue = { node: FilterNode; parent: string | null };89 unmodified linesexplicit: Record<string, string> = {}): Record<string, string> {const moved = new Set(after.filter((key) => explicit[key] !== undefined && explicit[key] !== old[key]));const stable = stationaryKeys(before.filter((key) => !moved.has(key)), after.filter((key) => !moved.has(key)));const result: Record<string, string> = {};after.forEach((key, i) => {if (explicit[key] !== undefined && explicit[key] !== old[key]) {2 unmodified lines} else if (stable.has(key)) result[key] = old[key];else {const next = after.slice(i + 1).find((candidate) => stable.has(candidate));result[key] = fractionalPositionBetween(i ? result[after[i - 1]] : null, next ? old[next] : null);}});return result;69 unmodified linesfor (const [key, value] of Object.entries(positions)) out.set(`position:${key}`, value);for (const [key, value] of Object.entries(c.summary ?? {})) out.set(`summary:${key}`, value);for (const pid of c.memberPids ?? []) out.set(`memberPid:${pid}`, true);out.set("group", c.groupBy);if (c.display !== undefined || c.groupSummary !== undefined) out.set("display", {...(c.display ?? { mode: "grid" }), ...(c.groupSummary === undefined ? {} : { groupSummary: c.groupSummary }),});for (const key of scalars) if (c[key] !== undefined) out.set(key, c[key]);for (const key of ["name", "note", "locked"] as const) if (view[key] !== undefined) out.set(key, view[key]);return out;}11 unmodified linesconst positions = seedPositions(ac.order, ac.positions);const sorts = seedPositions(sortKeys(ac), savedSortPositions(ac));const old = members({ ...a, config: ac }, fields, positions, sorts);const next = members({ ...b, config: bc }, fields,nextPositions(ac.order, bc.order, positions, bc.positions),nextPositions(sortKeys(ac), sortKeys(bc), sorts, savedSortPositions(bc)));const result: ViewMemberOp[] = [];const emit = (member: ViewMember, op: "set" | "remove", value: unknown): void => {97 unmodified linesc.memberPids = [...pids];} else if (family === "group") c.groupBy = remove ? null : value as string | null;else if (family === "display") {if (remove) { delete c.display; delete c.groupSummary; }else {c.display = value as DisplaySpec;if (c.display.groupSummary !== undefined) c.groupSummary = c.display.groupSummary;123430 unmodified lines353637383940414289 unmodified lines1321331341351361371382 unmodified lines14114214314414514614714814915015169 unmodified lines22122222322422522622722822923023123223323423523623711 unmodified lines24925025125225325425525625725825997 unmodified lines357358359360361362363import { DEFAULT_ROW_HEIGHT_MODE, isFilterGroup, mintFilterNodeId } from "./types";import type { DisplaySpec, FilterNode, SavedView, SortRule, ViewConfig, ViewMember,ViewMemberFamily, ViewMemberOp } from "./types";export type { ViewMember, ViewMemberOp } from "./types";30 unmodified linesconst POSITION = /^[0-9A-Za-z]{1,64}$/;const scalars = ["colorBy", "rowHeightMode", "frozenCount", "important", "secondaryView","application", "fullscreen"] as const;const scalarDefaults = { colorBy: null, rowHeightMode: DEFAULT_ROW_HEIGHT_MODE, frozenCount: 1,important: false, secondaryView: null, application: null, fullscreen: false };type Snapshot = Pick<SavedView, "id" | "config"> & Partial<Pick<SavedView, "name" | "note" | "locked">>;type Input = Snapshot | ViewConfig;type FilterValue = { node: FilterNode; parent: string | null };89 unmodified linesexplicit: Record<string, string> = {}): Record<string, string> {const moved = new Set(after.filter((key) => explicit[key] !== undefined && explicit[key] !== old[key]));const stable = stationaryKeys(before.filter((key) => !moved.has(key)), after.filter((key) => !moved.has(key)));const occupied = new Set([...Object.values(old), ...Object.values(explicit)]);const result: Record<string, string> = {};after.forEach((key, i) => {if (explicit[key] !== undefined && explicit[key] !== old[key]) {2 unmodified lines} else if (stable.has(key)) result[key] = old[key];else {const next = after.slice(i + 1).find((candidate) => stable.has(candidate));const upper = next ? old[next] : null;let position = fractionalPositionBetween(i ? result[after[i - 1]] : null, upper);// Each member applies separately, so another moving key still occupies its old position.while (occupied.has(position)) position = fractionalPositionBetween(position, upper);result[key] = position;}});return result;69 unmodified linesfor (const [key, value] of Object.entries(positions)) out.set(`position:${key}`, value);for (const [key, value] of Object.entries(c.summary ?? {})) out.set(`summary:${key}`, value);for (const pid of c.memberPids ?? []) out.set(`memberPid:${pid}`, true);out.set("group", c.groupBy ?? null);const display = {...(c.display ?? { mode: "grid" }), ...(c.groupSummary === undefined ? {} : { groupSummary: c.groupSummary }),};if (display.groupSummary === false) delete display.groupSummary;out.set("display", display.mode === "grid" && !display.groupSummary &&Object.keys(display).every((key) => key === "mode" || key === "groupSummary") ? null : display);for (const key of scalars) out.set(key, c[key] ?? scalarDefaults[key]);if (view.name !== undefined) out.set("name", view.name);out.set("note", view.note ?? "");out.set("locked", view.locked ?? false);return out;}11 unmodified linesconst positions = seedPositions(ac.order, ac.positions);const sorts = seedPositions(sortKeys(ac), savedSortPositions(ac));const old = members({ ...a, config: ac }, fields, positions, sorts);// Rendered orders omit unavailable columns. Their canonical positions remain untouched.const nextColumnPositions = nextPositions(ac.order, bc.order, positions, bc.positions);for (const [key, position] of Object.entries(positions))if (nextColumnPositions[key] === undefined) nextColumnPositions[key] = position;const next = members({ ...b, config: bc }, fields, nextColumnPositions,nextPositions(sortKeys(ac), sortKeys(bc), sorts, savedSortPositions(bc)));const result: ViewMemberOp[] = [];const emit = (member: ViewMember, op: "set" | "remove", value: unknown): void => {97 unmodified linesc.memberPids = [...pids];} else if (family === "group") c.groupBy = remove ? null : value as string | null;else if (family === "display") {if (remove || value === null) { delete c.display; delete c.groupSummary; }else {c.display = value as DisplaySpec;if (c.display.groupSummary !== undefined) c.groupSummary = c.display.groupSummary;
102 unmodified lines103104105106107108329 unmodified lines438439440441442443176 unmodified lines62062162262362462562674 unmodified lines701702703704705706139 unmodified lines846847848849850851852209 unmodified lines106210631064106510661067106810691 unmodified line10711072107310741075107610771078200 unmodified lines1279128012811282128312841285102 unmodified lines* locked, which is the right default for a module whose identity column is not this* panel's business. */lockedKey?: string;/** Owner item 23 — the whole new order, keys only. The panel owns the arithmetic because it* owns the list the user is pointing at; the caller just persists it. */onFieldOrder?: (keys: string[]) => void;329 unmodified linesonHideAll,onShowAll,lockedKey,onFieldOrder,deletableKeys,onDeleteField,176 unmodified lines(!rightsKnown || mayDeleteField(fc, viewer));const removable = !!removeFromMine && canRemove;/** The identity column is pinned visible by the host; hiding it is refused, not ignored. */const hideable = !(lockedKey !== undefined && f.key === lockedKey);return { fc, presetRefusal, canRemove, deletable, removable, hideable };};const q = query.trim().toLowerCase();74 unmodified lines// The identity column is pinned first by `reconcileOrder` regardless, so a drag involving// it would appear to work and then silently snap back. Refuse it at the door instead.if (key === lockedKey || target === lockedKey) return null;const keys = fields.map((f) => f.key);const from = keys.indexOf(key);const to = keys.indexOf(target);139 unmodified lines<div key={section.key} className="cg-fields-section">{section.title && <div className="cg-fields-section-title">{section.title}</div>}{section.fields.map((f) => {const locked = lockedKey !== undefined && f.key === lockedKey;const on = !hidden.has(f.key);const armed = confirmKey === f.key;/**209 unmodified linesdisabled={readOnly}draggable={canReorder && !locked}aria-label={locked? `${rowLabel(f)} is always first`: canReorder? `Reorder ${rowLabel(f)}: drag, or use the arrow keys`: `Reorder ${rowLabel(f)} (clear the search first)`1 unmodified linetitle={canReorder && !locked? "Drag to reorder, or use the arrow keys": locked? "This column is always first": "Clear the search to reorder"}onDragStart={(e) => {200 unmodified lines</span>)}{/* Wave-6 item 9c — a cohort-scoped field says so (contract: "label it"). */}{locked && <FieldMetaIcon kind="lock" detail="Always visible and fixed first" />}{/* ⭐⭐ W41-T29 (R6(a)) - A PRE-SET SAYS IT CANNOT BE DELETED. The row used toanswer by simply not having a button, which is indistinguishable from awiring accident; this is the refusal, stated.102 unmodified lines103104105106107108109110329 unmodified lines440441442443444445446176 unmodified lines62362462562662762862974 unmodified lines704705706707708709710139 unmodified lines850851852853854855856857209 unmodified lines10671068106910701071107210731074107510761 unmodified line1078107910801081108210831084108510861087200 unmodified lines1288128912901291129212931294102 unmodified lines* locked, which is the right default for a module whose identity column is not this* panel's business. */lockedKey?: string;/** Rows that stay shown and hold their place beside `lockedKey`. Absent = none. */alwaysVisibleKeys?: readonly string[];/** Owner item 23 — the whole new order, keys only. The panel owns the arithmetic because it* owns the list the user is pointing at; the caller just persists it. */onFieldOrder?: (keys: string[]) => void;329 unmodified linesonHideAll,onShowAll,lockedKey,alwaysVisibleKeys,onFieldOrder,deletableKeys,onDeleteField,176 unmodified lines(!rightsKnown || mayDeleteField(fc, viewer));const removable = !!removeFromMine && canRemove;/** The identity column is pinned visible by the host; hiding it is refused, not ignored. */const hideable = !(lockedKey !== undefined && f.key === lockedKey) && !alwaysVisibleKeys?.includes(f.key);return { fc, presetRefusal, canRemove, deletable, removable, hideable };};const q = query.trim().toLowerCase();74 unmodified lines// The identity column is pinned first by `reconcileOrder` regardless, so a drag involving// it would appear to work and then silently snap back. Refuse it at the door instead.if (key === lockedKey || target === lockedKey) return null;if (alwaysVisibleKeys?.includes(key) || alwaysVisibleKeys?.includes(target)) return null;const keys = fields.map((f) => f.key);const from = keys.indexOf(key);const to = keys.indexOf(target);139 unmodified lines<div key={section.key} className="cg-fields-section">{section.title && <div className="cg-fields-section-title">{section.title}</div>}{section.fields.map((f) => {const first = lockedKey !== undefined && f.key === lockedKey;const locked = first || !!alwaysVisibleKeys?.includes(f.key);const on = !hidden.has(f.key);const armed = confirmKey === f.key;/**209 unmodified linesdisabled={readOnly}draggable={canReorder && !locked}aria-label={first? `${rowLabel(f)} is always first`: locked? `${rowLabel(f)} keeps its place`: canReorder? `Reorder ${rowLabel(f)}: drag, or use the arrow keys`: `Reorder ${rowLabel(f)} (clear the search first)`1 unmodified linetitle={canReorder && !locked? "Drag to reorder, or use the arrow keys": first? "This column is always first": locked? "This column keeps its place": "Clear the search to reorder"}onDragStart={(e) => {200 unmodified lines</span>)}{/* Wave-6 item 9c — a cohort-scoped field says so (contract: "label it"). */}{locked && <FieldMetaIcon kind="lock" detail={first ? "Always visible and fixed first" : "Always visible"} />}{/* ⭐⭐ W41-T29 (R6(a)) - A PRE-SET SAYS IT CANNOT BE DELETED. The row used toanswer by simply not having a button, which is indistinguishable from awiring accident; this is the refusal, stated.
138 unmodified lines1391401411421431441659 unmodified lines180418051806180718081809138 unmodified linesimport { useEscapeClose } from "../ui/useEscapeClose";import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay";import { BodyPortal } from "../customer-grid/OverlaySurface";import { OPEN_APP_TEMPLATE_EVENT } from "../sheet/templates/templatesApi";import { AppMark } from "../apps/templateMarks";import type { TemplateModule } from "../sheet/templates/templatesApi";1659 unmodified linesviewEmitCancel.current?.();viewEmitCancel.current = retryEmit(() => {signal(VIEW_OPEN_EVENT, { topic: gridScopeFor(database), viewId });},undefined,138 unmodified lines1391401411421431441451659 unmodified lines1805180618071808180918101811181218131814138 unmodified linesimport { useEscapeClose } from "../ui/useEscapeClose";import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay";import { BodyPortal } from "../customer-grid/OverlaySurface";import { ALL_VIEW_ID } from "../customer-grid/types";import { OPEN_APP_TEMPLATE_EVENT } from "../sheet/templates/templatesApi";import { AppMark } from "../apps/templateMarks";import type { TemplateModule } from "../sheet/templates/templatesApi";1659 unmodified linesviewEmitCancel.current?.();viewEmitCancel.current = retryEmit(() => {const address = readDataAddress(window.location.hash);// A later Table choice ends this opening request, including its remaining retries.if (address.database !== database|| (address.view || ALL_VIEW_ID) !== (viewId || ALL_VIEW_ID)) return true;signal(VIEW_OPEN_EVENT, { topic: gridScopeFor(database), viewId });},undefined,
RELEASES.json+2-519
VERSION+1-1
api/amazon_relational.py+21-6
api/app_templates.py+2-2
api/application_registry.py+20-12
api/main.py+6-4
api/odoo_relational.py+1-1
api/registry_source.py+6-4
api/routes_competitor_watch.py+5-13
api/routes_grid.py+4-2
platform/aios_grid.py+8
platform/core/grid_events.py+8-3
platform/core/received_changes.py+327-82
platform/core/registry.py+1-1
platform/core/shared_overlay.py+11
platform/core/table_store.py+56-7
platform/harness/amazon_client.py+3-1
platform/harness/amazon_store.py+181-16
platform/harness/datastore.py+20-4
platform/modules/amazon_profit.py+112-4
platform/modules/competitor_watch.py+185-108
platform/modules/product_data.py+8-3
web/public/AIOS_DEPLOY_RECEIPT+1-1
web/src/apps/amazon-profit/AppView.tsx+7-1
web/src/apps/amazon-profit/ProjectsList.tsx+1-1
web/src/customer-grid/CustomerGrid.tsx+29-38
web/src/customer-grid/Toolbar.tsx+1
web/src/customer-grid/appHostTypes.ts+2
web/src/customer-grid/seam.ts+4-3
web/src/customer-grid/types.ts+2
web/src/customer-grid/useGridColumns.ts+33-16
web/src/customer-grid/viewOps.ts+25-10
web/src/filter-kit/FieldsHidePanel.tsx+14-5
web/src/shell/Shell.tsx+5