Skip to content

Commit 89364b4

Browse files
feat(spec): {current_iso_week} defaults a week-keyed filter to the current ISO week (#35391)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg6v19uPsX6gX42G8tGcvvzb)_ Fixes #34938 Clause-②: yes (widening: the closed filter-placeholder vocabulary gains one token) Metadata-protocol: added Skills-docs: follow-up owed — skills/objectstack-query/rules/filters.md (its "Date Macros" section lists the filter-placeholder vocabulary; it should name `{current_iso_week}` as a period key that is text, not a date) ## 维护者速读 - 用户看到的变化:看板的文本筛选可以把默认值设成「本周」,每次打开自动填入当前周号(如 2026-W47),筛选框里直接显示周号;写死的周号照旧可用。 - 为什么:按周号存数据的应用以前只能写死某一周,下周就过期;按您「加一个固定占位符」的裁定执行。 - 如果判断错:只影响用了这个占位符的筛选;跨年那几天周号若算错,看板会落到相邻的一周。误用在日期字段上会直接被拒绝并提示,不会悄悄给出错误结果。 - 需要您做的:无。 ## What changes - **Spec.** `PERIOD_KEY_TOKENS = ['current_iso_week']`, `isPeriodKeyToken` and `PERIOD_KEY_TOKEN_DESCRIPTIONS` in `data/date-macros.zod.ts`. It is a sibling list, not a member of `DATE_MACRO_TOKENS`, so `isDateMacroPlaceholder`, a date dashboard default and a calendar `initialDate` still refuse it. `classifyFilterToken` answers a new kind, `period-key`; `isKnownFilterToken` knows it. The dashboard `defaultValue` TSDoc and describe name the text-filter use. - **Server.** `resolveFilterTokens` (`@objectstack/core`) resolves it with `bucketDateKey(now, 'week', ctx.timezone)`, the same label the analytics week bucket groups by: ISO-8601, Monday start, the ISO week-numbering year at the year edges, today in the workspace zone. The unknown-token message names it. - **Client.** `resolvePeriodKeyTokens` (`@object-ui/core`) carries the same rule; the client cannot import `@objectstack/core`, so the two copies are held equal by one 16-row parity table that both sides run. `resolveFilterPlaceholders` and `resolveDashboardFilterDefs` call it, so a text (or any non-date) filter opens with the resolved key in the box; a `date` / `dateRange` default is left to its own normalizer and refused there as before. - **Lint.** No logic change: `{current_iso_week}` is a known token, so `filter-token-unknown` no longer flags it. The rule's explanation said "exactly two vocabularies", which this change made false; it now lists the period keys. - **Docs.** A new "Defaulting to the Current ISO Week" section in the dashboards guide (with a type-checked example); the analytics and plugin-view placeholder paragraphs name the token; the date-macros and dashboard reference pages and the `data` api-surface / export-origins shards are regenerated. ## Tests All runs below were at `f3bf7beb08`; the only later commit, `fa840834a0`, edits the changeset text alone, and the families that read it were re-run there. - New pins: the 16-row parity table (year edges 2020-12-31, 2021-01-03/04, 2024-12-30, 2025-12-29, 2026-12-31, 2027-01-01/03/04, and zone rows for Tokyo, New York, Los Angeles and Shanghai) in core `filter-tokens.test.ts` and in ui `date-macros.test.ts`; a sibling of the spec-parity test for `PERIOD_KEY_TOKENS`; the classify / known-token / near-spelling cases in spec; the dashboard schema (date filter refuses, text filter keeps both spellings and a literal key); the lint no-finding cases; the dashboard-filter seeding cases (text, untyped, `${…}`, select, zone, literal key, embedded text, a date filter left raw). - Every test file that reads a touched symbol, per package: spec 10 files / 1046 tests, core 6 / 392, lint 7 / 334, objectql 8 / 222, service-analytics 6 / 326 (+20 skipped), service-automation 1 / 65, driver-memory 2 / 78, driver-sql 2 / 79 (+2 skipped), formula 1 / 52, platform-objects 1 / 18, app-showcase 1 / 3, ui (core, plugin-dashboard, plugin-designer, grid, list, view, react, console, app-shell) 28 / 437 (+6 skipped). All passed. - Typecheck: `@objectstack/spec`, `@objectstack/core`, `@objectstack/lint` `typecheck` and `@object-ui/core` `type-check` (which compiles its tests) all exit 0. <details> <summary>Test run readings</summary> ```text READER spec exit 0 :: Test Files 10 passed (10) Tests 1046 passed (1046) READER core exit 0 :: Test Files 6 passed (6) Tests 392 passed (392) READER lint exit 0 :: Test Files 7 passed (7) Tests 334 passed (334) READER objectql exit 0 :: Test Files 8 passed (8) Tests 222 passed (222) READER analytics exit 0 :: Test Files 6 passed (6) Tests 326 passed | 20 skipped (346) READER automation exit 0 :: Test Files 1 passed (1) Tests 65 passed (65) READER drvmem exit 0 :: Test Files 2 passed (2) Tests 78 passed (78) READER drvsql exit 0 :: Test Files 2 passed (2) Tests 79 passed | 2 skipped (81) READER formula exit 0 :: Test Files 1 passed (1) Tests 52 passed (52) READER platobj exit 0 :: Test Files 1 passed (1) Tests 18 passed (18) READER showcase exit 0 :: Test Files 1 passed (1) Tests 3 passed (3) ui readers: Test Files 28 passed (28) Tests 437 passed | 6 skipped (443) os-verify-lock: VERDICT command-exit 0 (each of the three runs) typecheck: TC spec=0 core=0 lint=0 ; @object-ui/core type-check VERDICT command-exit 0 ``` </details> ## Acceptance notes - **The temporal-comparand door, measured as asked.** The dispatch asked what the door answers when the token meets a date or datetime column. Measured with `engine.find` on the SQL driver (SQLite) and the in-memory driver, which answered the same; now pinned to 2026-11-19. It is **not refused and not read as a date: the key reaches the driver and is compared as text**. Before this change the same query answered `FILTER_TOKEN_UNKNOWN` / 400. - `placed_on` (date) `$eq` gives `[]`, `$gte` gives `[]`, and `$lt` returns every row. - `opened_at` (datetime) answers the same; `opens_at` (time) `$gt` gives `[]`. - The literal `"2026-W47"` on the same columns is refused `INVALID_FILTER` / 400. The door steps around every placeholder as written, and after resolution it judges only `date-macro` kinds. The context tokens (`{current_user_id}` on a date column) already behave this way. Per the dispatch the door was not widened. The docs say to use the token only on fields that store week keys. The fix belongs in the core temporal-comparand step-around: judge period-key and context placeholders as written, and step around only date macros. It is reported to the seat to file. - **compareTo.** A chart's previous-period series (the compare-to shift) does not shift a period key, so the comparison series filters the same week. Not measured in a UI; reported, not changed. - **Placeholders only as the whole value.** The token resolves only as a whole value. `'week {current_iso_week}'` is left as written, like every other placeholder. - **Lint does not read dashboard defaults.** Lint does not walk `globalFilters[].defaultValue`. A typo there, such as `{currentIsoWeek}`, surfaces only at query time, as `FILTER_TOKEN_UNKNOWN` / 400. - **Files outside the claim's surface.** - `packages/lint/src/rule-explanations.ts`: its text became false with this change. - `ui/packages/core/src/utils/filter-tokens.ts`: the client's sibling resolver. - `content/docs/data-modeling/analytics.mdx` and `content/docs/frontend/plugins/plugin-view.mdx`: the other filter-placeholder paragraphs. - No path under `skills/**` changed; no generator wrote there. ## Verification - Derived gate families (`dispatch-gates.mjs --commands`, 120 families) ran locally. 118 exited 0 and 2 are NOT MEASURED; the reconciliation reads `✓ dispatch-gates --ran: 120 derived famil(ies) accounted for — 118 run, 2 NOT-MEASURED`. - `check:skill-examples` first refused with exit 3 because `@objectstack/client-react` had no dist. After building it, the gate exits 0: 346 examples type-check, including the new dashboards example. - NOT MEASURED: `check:dual-build-cjs-loads`. It needs every workspace package's dist, which is a whole-repo build, left to CI. - NOT MEASURED: `vitest run scripts/` (ui). 170 of 171 files passed. The one failure, `unit-registry-absence-collision`, was caused by an unbuilt `@objectstack/client`; after building it, that file passes 15/15. - `check:generated` is green after `gen:api-surface`, `gen:export-origins` and `gen:docs`. ui `check:new-line-citations` reports 0 new citations, and `overlap-check` merges cleanly. - CI runs the full lint farm and the full package suites. <details> <summary>Gate readings</summary> ```text dispatch-gates: gate list derived from the tree of 'objectstack-ai/objectstack' at commit fa84083 Run reconciliation — 120 derived, 118 run, 2 NOT-MEASURED, 0 UNRUN. check:skill-examples (rerun): ✅ 346 prose examples type-check across 3 surface(s) check:dual-build-cjs-loads: PREREQUISITE NOT MET — this gate reads built output, and some package has no dist/. VERDICT new-cross-file-line-citations: 0 new citation(s), enforcement report-only -> exit 0 overlap-check: VERDICT clean exit 0 ``` </details> ## Fix round (contract review 7003932618) Head `6b8fc7b563`. It supersedes the "temporal-comparand door" acceptance note above: the door now refuses the token on temporal columns. - **S1, closed in this PR.** The core predicate `isUninterpretableTemporalComparand` no longer steps around a `period-key` placeholder; it judges it as written. `{current_iso_week}` is not a calendar day, an instant or a wall clock, so on a `date`, `datetime` or `time` column it now gets the same refusal as the literal `"2026-W47"`: `INVALID_FILTER` / 400, before any driver read. - The narrowest correct place is the core predicate, the one rule both callers ask. The engine door (`where`, per-aggregation filter and `having`) and the analytics raw-SQL decline therefore move together; `judgeResolvedToken` gains only a docblock clause. - The record validator's write door already refused every placeholder through its own `readable` gate, so its verdicts do not change. - Date macros, unknown placeholders and the context tokens are still stepped around. The context-token half stays with #35394. - **Docs and changeset.** The dashboards guide, the changeset and the spec module doc now say the key is refused on a date, datetime or time field, and the date-macros reference page is regenerated. They used to say it was compared as text and gave the wrong answer. - **N1.** The changeset now carries the sentence "A consumer that switches exhaustively on `kind` gets a compile error until it handles the new kind." - **N2.** Dropped, as the seat instructed. `flow-value-slot-template.ts` is not touched. - **N3.** The lint `filter-token-unknown` hints and the inline comment now name the week key `{current_iso_week}` and the three vocabularies. Both hint lines stay one line of at most 200 characters (186 and 176). ### Pins - **Core predicate** (`temporal-comparand.test.ts`). The predicate refuses every `PERIOD_KEY_TOKENS` member in both spellings, plus the literal key, on all three kinds. As controls, `{current_week_start}`, `{today}`, `{30_days_ago}` and the unknown `{current_iso_wek}` are still stepped around. - **Engine door, recording driver** (`engine-temporal-comparand-door.test.ts`). - Refused with `INVALID_FILTER` / 400 and no driver read: `$eq` / `$lt` / `$gte` / `$gt`, implicit equality and an `$in` member, on `due_on` (date), `created_date` (datetime) and `opens_at` (time), in both spellings. - Positive controls in the same test: a text `$eq` and an implicit equality return the W47 row; a text `$contains` reaches the driver as `2026-W47`; `{current_week_start}` on a date column resolves to `2026-11-16` and returns the W47 row. - **REST query door over SqlDriver** (`data-temporal-write-real-day-iso.test.ts`). - The SQLite cell always runs; the PostgreSQL cell is a named skip unless `OS_TEST_POSTGRES_URL` is set. - On `placed_on`, `opened_at` and `slot`, `$eq` / `$lt` / `$gte` in both spellings answer 400 `INVALID_FILTER` naming the field, with no read of the object. - As controls, a text `$eq` and `$contains` return the W47 row, and `{current_week_start}` on the date field returns it too. - **InMemoryDriver** has no live pin in this PR. A new test file that imports `@objectstack/driver-memory` needs a census ruling (`scripts/driver-memory-census.ledger.json`), which a dev does not make. The refusal sits in front of every driver, and the recording-driver pin asserts that no driver read happens. The pre-fix reading on InMemoryDriver matched SQLite. <details> <summary>Ablation of the new arm (once): pins red, then restored to the HEAD blob</summary> ```text ablation-replace: anchor "if (placeholder !== null && placeholder.kind !== 'period-key') return false;" x1 (before) ablation-replace: replace "if (placeholder !== null) return false;" x0 -> x1 ablation-replace: blob 7032d83 -> 1d48a87164838ef451874f607946b6ec6ae27b30 pnpm --filter @objectstack/core build; ablation-dist-preflight --absent: marker absent from all 20 built files PIN core exit 1 :: Tests 1 failed | 27 passed (28) date {current_iso_week}: expected false to be true PIN objectql exit 1 :: Tests 1 failed | 14 passed (15) due_on $eq {current_iso_week}: expected null not to be null PIN rest exit 1 :: Tests 1 failed | 6 passed | 7 skipped (14) placed_on $eq {current_iso_week}: expected 200 to be 400 restore: git checkout HEAD -- (absolute path); HEAD blob 7032d83 == disk blob 7032d83; git diff HEAD empty pnpm --filter @objectstack/core build; ablation-dist-preflight: marker present in 2 built files; tree clean against HEAD PIN core exit 0 :: Tests 28 passed (28) PIN objectql exit 0 :: Tests 15 passed (15) PIN rest exit 0 :: Tests 7 passed | 7 skipped (14) os-verify-lock: VERDICT command-exit 0 ``` </details> <details> <summary>Readers and gates at 6b8fc7b</summary> ```text READER core Test Files 3 passed Tests 214 passed READER objectql Test Files 14 passed Tests 297 passed READER rest Test Files 4 passed Tests 26 passed | 18 skipped READER analytics Test Files 10 passed Tests 353 passed | 6 skipped READER lint Test Files 2 passed Tests 45 passed READER spec Test Files 2 passed Tests 56 passed typecheck core / lint / objectql / rest: exit 0 spec check:generated: exit 0 after gen:docs dispatch-gates --ran: 123 derived famil(ies) accounted for — 120 run, 3 NOT-MEASURED NOT-MEASURED check:dual-build-cjs-loads (needs every package dist), check:type-check-debt (its re-measure queues a whole-repo build), ui vitest run scripts/ (no ui file changed this round) overlap-check: VERDICT clean exit 0 ``` </details> --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CbSphdunq2aJq7ktuY --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 338448e commit 89364b4

31 files changed

Lines changed: 931 additions & 52 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/core': patch
4+
'@objectstack/lint': patch
5+
'@object-ui/core': patch
6+
---
7+
8+
feat(spec, core, ui): `{current_iso_week}` defaults a week-keyed filter to the current ISO week
9+
10+
Clause-②: yes (widening: the closed filter-placeholder vocabulary gains one token)
11+
Metadata-protocol: added
12+
13+
A dashboard whose rows carry a text week key (`cost_week: '2026-W47'`) could only default its week filter to a fixed week, which went stale the next Monday. Write the placeholder instead and the filter opens on the current week each time:
14+
15+
```ts
16+
globalFilters: [
17+
{ field: 'cost_week', label: 'Week', type: 'text', defaultValue: '{current_iso_week}' },
18+
],
19+
```
20+
21+
- It resolves to the ISO-8601 week key of today, `YYYY-Www`: Monday-start weeks, week 1 is the week that holds the year's first Thursday, and the year is the ISO week-numbering year, so 2027-01-01 is `2026-W53` and 2025-12-29 is `2026-W01`. "Today" is the day in the workspace time zone, on the server and in the browser alike; the label is the one the analytics week bucket already uses.
22+
- It is a period key, not a date. It lives in its own closed list, `PERIOD_KEY_TOKENS`, beside `DATE_MACRO_TOKENS` and not inside it, so a date filter default and a calendar `initialDate` still refuse it. `classifyFilterToken` answers a new kind, `period-key`, and `isKnownFilterToken` knows it, so lint, flow filter operands and the server resolver accept it wherever a filter placeholder is accepted. A consumer that switches exhaustively on `kind` gets a compile error until it handles the new kind.
23+
- The server resolves it in `resolveFilterTokens`; the browser resolves it in `resolveFilterPlaceholders` and in the dashboard filter defaults (every filter type except `date` and `dateRange`), so the filter box opens showing the resolved key. A literal `2026-W47` default keeps working and stays fixed.
24+
- Every filter and default written before parses and resolves exactly as before. Only the whole value is a placeholder: `'week {current_iso_week}'` is left as written. A near spelling such as `{currentIsoWeek}` is still refused as an unknown token.
25+
- Use it only on a field that stores week keys. On a date, datetime or time field the placeholder is refused (`INVALID_FILTER` / 400), as the literal key is; filter those with the `this_week` preset or `{current_week_start}` / `{current_week_end}`.

‎content/docs/data-modeling/analytics.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,10 @@ sort last in both directions.
255255
A `joined` report orders per block: put `order` on each `blocks[]` entry, not on
256256
the container.
257257

258-
Placeholders inside a `filter` / `runtimeFilter` — `{date-macro}`s and the
259-
session tokens `{current_user_id}` / `{current_org_id}` — are resolved on **both**
258+
Placeholders inside a `filter` / `runtimeFilter` — `{date-macro}`s, the
259+
current ISO week's key `{current_iso_week}` (`2026-W47`, for a text field that
260+
stores week keys) and the session tokens `{current_user_id}` /
261+
`{current_org_id}` — are resolved on **both**
260262
sides: by the renderer before it queries, and by the analytics dataset executor
261263
server-side. The server pass is what makes a widget work at all, since the
262264
native-SQL strategy compiles raw SQL and binds comparands directly without ever

‎content/docs/frontend/plugins/plugin-view.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -328,8 +328,9 @@ Whichever tier wins, its filter goes through `resolveFilterPlaceholders` from
328328
`@object-ui/core` before it leaves `ObjectView` (objectui#10506), on all three
329329
paths: the query a non-grid view issues, the grid, and a host's
330330
`renderListView`. So the spec's context tokens (`{current_user_id}`,
331-
`{current_org_id}`) and the relative-date macros (`{today}`,
332-
`{current_quarter_start}`, …) arrive as real values. The user and organization
331+
`{current_org_id}`), the relative-date macros (`{today}`,
332+
`{current_quarter_start}`, …) and the current ISO week's key
333+
(`{current_iso_week}`, `2026-W47`) arrive as real values. The user and organization
333334
come from the nearest `FilterScopeProvider` (`@object-ui/react`), which the
334335
console shell mounts; with none mounted a context token is left as written and
335336
the resolver warns. The filter is never widened: the ObjectStack server resolves

‎content/docs/references/data/date-macros.mdx‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,44 @@ inside any single UI implementation.
6464
`DATE_MACRO_PARAM_RE`. Units: `minute(s)`, `hour(s)`, `day(s)`,
6565
`week(s)`, `month(s)`, `year(s)`. Directions: `ago`, `from_now`.
6666

67+
## A sibling list: period keys, which are not dates
68+
69+
One more placeholder reads the clock, and resolves to a period KEY rather
70+
than to a day: `{current_iso_week}` → `2026-W47`. It is enumerated by
71+
`PERIOD_KEY_TOKENS`, a list of its own, never a member of
72+
`DATE_MACRO_TOKENS`.
73+
74+
The key is the ISO-8601 week of today, written `YYYY-Www`: weeks start on
75+
Monday, week 1 is the week holding the year's first Thursday, and the
76+
year is the ISO week-numbering year, which differs from the calendar year
77+
on a few days at the year's edges (Friday 2027-01-01 is `2026-W53`,
78+
Monday 2027-01-04 is `2027-W01`). "Today" is the calendar day in the
79+
workspace time zone, as for every date macro. It is the label an
80+
analytics `week` bucket groups by, so a text column that stores the same
81+
key, as weekly master data often does, filters to the current week:
82+
83+
```
84+
{ cost_week: '{current_iso_week}' }
85+
```
86+
87+
The value is TEXT. That is why it is a separate list: everything that
88+
reads `DATE_MACRO_TOKENS` takes its members as dates — a `type: 'date'`
89+
dashboard filter's `defaultValue` and a calendar view's `initialDate`
90+
accept any of them — and a week key is not a date. So
91+
`isDateMacroToken('current_iso_week')` is `false`, and those two surfaces
92+
refuse it; so does the query engine's temporal-comparand door, on a
93+
`date`, `datetime` or `time` column (`INVALID_FILTER` / 400), as it
94+
refuses the literal key. Every door that asks whether a filter placeholder is KNOWN
95+
(`isKnownFilterToken` and `classifyFilterToken` in `./context-tokens.zod.ts`,
96+
which lint, the flow filter operand and the server resolver read) knows
97+
it, with its own `period-key` kind. A dashboard text filter may default to
98+
it: the filter bar shows the resolved key, which the user can then edit.
99+
100+
It is resolved on both sides of the wire like the date macros, by the same
101+
week rule: the server's `bucketDateKey(now, 'week', timezone)` in
102+
`@objectstack/core`, and the client resolver in `@object-ui/core`, which
103+
a shared table of year-edge days holds equal to it.
104+
67105
## Out of scope
68106

69107
- CEL expressions (`cel\`daysAgo(30)\``) run **server-side** in the

‎content/docs/references/ui/dashboard.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const result = DashboardSchema.parse(data);
9999
| **type** | `Enum<'text' \| 'select' \| 'date' \| 'number' \| 'lookup'>` | optional | Filter input type |
100100
| **options** | `{ value: string \| number \| boolean; label: string \| Record<string, string> }[]` | optional | Static filter options |
101101
| **optionsFrom** | `{ object: string; valueField: string; labelField: string; filter?: any }` | optional | Dynamic filter options from object |
102-
| **defaultValue** | `string \| number \| boolean` | optional | Default filter value |
102+
| **defaultValue** | `string \| number \| boolean` | optional | Default filter value. On a date filter: a preset name, an ISO date or a date-macro token. On a text filter keyed by ISO week, `{current_iso_week}` resolves to the current week key (e.g. `2026-W47`) each time the dashboard opens |
103103
| **scope** | `Enum<'dashboard' \| 'widget'>` | optional (default: `"dashboard"`) | Filter application scope |
104104
| **targetWidgets** | `string[]` | optional | Widget IDs to apply this filter to |
105105

@@ -324,7 +324,7 @@ Widget configuration — declared query keys + open renderer extras
324324
| **type** | `Enum<'text' \| 'select' \| 'date' \| 'number' \| 'lookup'>` | optional | Filter input type |
325325
| **options** | `{ value: string \| number \| boolean; label: string \| Record<string, string> }[]` | optional | Static filter options |
326326
| **optionsFrom** | `{ object: string; valueField: string; labelField: string; filter?: any }` | optional | Dynamic filter options from object |
327-
| **defaultValue** | `string \| number \| boolean` | optional | Default filter value |
327+
| **defaultValue** | `string \| number \| boolean` | optional | Default filter value. On a date filter: a preset name, an ISO date or a date-macro token. On a text filter keyed by ISO week, `{current_iso_week}` resolves to the current week key (e.g. `2026-W47`) each time the dashboard opens |
328328
| **scope** | `Enum<'dashboard' \| 'widget'>` | optional (default: `"dashboard"`) | Filter application scope |
329329
| **targetWidgets** | `string[]` | optional | Widget IDs to apply this filter to |
330330

‎content/docs/ui/dashboards.mdx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,42 @@ answers `200 OK` with a zero. Every tile read 0 while the filter bar showed
639639
meaning "open the picker with no preset applied", and a bare filter value gives
640640
it no `from`/`to` to hand over.
641641

642+
### Defaulting to the Current ISO Week
643+
644+
Weekly data is often keyed by an ISO week rather than by a date: a text field
645+
such as `cost_week` holds `2026-W47`. A text filter over that field can default
646+
to the current week with the placeholder `{current_iso_week}`:
647+
648+
{/* os:check */}
649+
```typescript
650+
globalFilters: [
651+
{ field: 'cost_week', label: 'Week', type: 'text', defaultValue: '{current_iso_week}' },
652+
]
653+
```
654+
655+
Each time the dashboard opens, the placeholder resolves to the current week's
656+
key, and the filter box shows that key (`2026-W47`), not the placeholder. The
657+
user can edit it like any typed value, and it filters the field the same way.
658+
659+
- **The week.** The key is the ISO-8601 week, written `YYYY-Www`. Weeks start
660+
on Monday, and week 1 is the week that holds the year's first Thursday. Near
661+
New Year the year in the key can differ from the calendar year: Friday
662+
2027-01-01 is in `2026-W53`, and Monday 2027-01-04 starts `2027-W01`. This is
663+
the same label an analytics `week` bucket groups by.
664+
- **The day.** "Today" is the calendar day in the workspace time zone, the
665+
same day the date macros such as `{today}` read.
666+
- **A fixed week.** A literal key, `defaultValue: '2026-W47'`, stays a fixed
667+
default.
668+
- **Widget filters.** `{current_iso_week}` also works as a value in any
669+
filter condition, such as a widget's `filter: { cost_week: '{current_iso_week}' }`.
670+
It resolves before the query runs, in the browser and on the server.
671+
- **Not a date.** The key is text. A `type: 'date'` filter refuses it as a
672+
default, and so does a calendar view's `initialDate`. To filter a date field
673+
to this week, use the `this_week` preset or `{current_week_start}` /
674+
`{current_week_end}`. In a filter on a date, datetime or time field the
675+
placeholder is refused (`INVALID_FILTER`, 400), as the literal key is: use it
676+
only on fields that store week keys.
677+
642678
### Per-Widget Filter Bindings
643679

644680
By default a filter applies to its own `field` on every widget (the date

‎packages/core/src/utils/filter-tokens.test.ts‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import { describe, it, expect } from 'vitest';
4-
import { ReadableIds, isReadableIds } from '@objectstack/spec/data';
4+
import { PERIOD_KEY_TOKENS, ReadableIds, isReadableIds } from '@objectstack/spec/data';
5+
import { bucketDateKey } from './datetime.js';
56
import {
67
resolveFilterToken,
78
resolveFilterTokens,
@@ -547,3 +548,82 @@ describe('filterTokenContextFrom', () => {
547548
});
548549
});
549550
});
551+
552+
/**
553+
* `{current_iso_week}` — the period key (`PERIOD_KEY_TOKENS`): the ISO-8601
554+
* week of the reference day, the label `bucketDateKey` writes for an analytics
555+
* `week` bucket. The table is the client/server parity pin: the same rows are
556+
* asserted against `@object-ui/core`'s `resolvePeriodKeyTokens` in the
557+
* `resolvePeriodKeyTokens` block of
558+
* `ui/packages/core/src/utils/__tests__/date-macros.test.ts`, which writes the
559+
* same week rule again because it cannot import this package. Change a row in
560+
* one file and change it in the other.
561+
*/
562+
describe('resolveFilterToken — the period key {current_iso_week}', () => {
563+
/** instant · reference timezone (none = UTC) · ISO week key */
564+
const PARITY_TABLE: ReadonlyArray<readonly [string, string | undefined, string]> = [
565+
['2026-11-19T12:00:00Z', undefined, '2026-W47'],
566+
// Year edges: the ISO week-numbering year is the year of the week's Thursday.
567+
['2026-12-31T12:00:00Z', undefined, '2026-W53'],
568+
['2027-01-01T12:00:00Z', undefined, '2026-W53'],
569+
['2027-01-03T12:00:00Z', undefined, '2026-W53'],
570+
['2027-01-04T12:00:00Z', undefined, '2027-W01'],
571+
['2020-12-31T12:00:00Z', undefined, '2020-W53'],
572+
['2021-01-03T12:00:00Z', undefined, '2020-W53'],
573+
['2021-01-04T12:00:00Z', undefined, '2021-W01'],
574+
['2025-12-29T12:00:00Z', undefined, '2026-W01'],
575+
['2024-12-30T12:00:00Z', undefined, '2025-W01'],
576+
// The reference timezone decides the day, and so the week.
577+
['2026-11-22T20:00:00Z', 'Asia/Tokyo', '2026-W48'],
578+
['2026-11-22T20:00:00Z', 'America/New_York', '2026-W47'],
579+
['2026-11-23T03:00:00Z', 'America/Los_Angeles', '2026-W47'],
580+
['2026-11-23T03:00:00Z', undefined, '2026-W48'],
581+
['2027-01-03T23:30:00Z', 'Asia/Shanghai', '2027-W01'],
582+
['2027-01-03T23:30:00Z', undefined, '2026-W53'],
583+
];
584+
585+
it.each(PARITY_TABLE)('%s in %s is %s', (instant, timezone, key) => {
586+
const now = new Date(instant);
587+
expect(resolveFilterToken('current_iso_week', { now, timezone })).toBe(key);
588+
// One week rule: the analytics week bucket labels the same instant the same way.
589+
expect(bucketDateKey(now, 'week', timezone)).toBe(key);
590+
});
591+
592+
it('every token in the spec list resolves to a key, never to a date', () => {
593+
expect(PERIOD_KEY_TOKENS.length).toBeGreaterThan(0);
594+
for (const token of PERIOD_KEY_TOKENS) {
595+
expect(resolveFilterToken(token, { now: NOW }), token).toMatch(/^\d{4}-W\d{2}$/);
596+
}
597+
});
598+
599+
it('resolves through the tree walk, both wrappings, beside the other vocabularies on one instant', () => {
600+
const ctx = filterTokenContextFrom({ userId: 'usr_1', timezone: 'UTC' }, NOW);
601+
expect(resolveFilterTokens({
602+
$and: [
603+
{ cost_week: '{current_iso_week}' },
604+
{ supply_week: { $in: ['${current_iso_week}', '2026-W27'] } },
605+
{ day: { $gte: '{current_week_start}' } },
606+
{ owner: '{current_user_id}' },
607+
{ note: 'plan {current_iso_week}' },
608+
],
609+
}, ctx)).toEqual({
610+
$and: [
611+
{ cost_week: '2026-W29' },
612+
{ supply_week: { $in: ['2026-W29', '2026-W27'] } },
613+
{ day: { $gte: '2026-07-13' } },
614+
{ owner: 'usr_1' },
615+
// A placeholder embedded in a longer string is not one: left as written.
616+
{ note: 'plan {current_iso_week}' },
617+
],
618+
});
619+
});
620+
621+
it('a near spelling is refused as unknown, and the refusal names the period key', () => {
622+
let refusal: unknown;
623+
try { resolveFilterTokens({ cost_week: '{current_week}' }, { now: NOW }); } catch (e) { refusal = e; }
624+
expect(refusal).toBeInstanceOf(UnknownFilterTokenError);
625+
expect((refusal as UnknownFilterTokenError).code).toBe('FILTER_TOKEN_UNKNOWN');
626+
expect((refusal as UnknownFilterTokenError).status).toBe(400);
627+
expect((refusal as Error).message).toContain('{current_iso_week}');
628+
});
629+
});

‎packages/core/src/utils/filter-tokens.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,16 @@
112112
* record" would otherwise come back as "about nobody", or, with the condition
113113
* gone, "about everybody".
114114
*
115+
* # A period key resolves to its key, never to a date
116+
*
117+
* `{current_iso_week}` (`PERIOD_KEY_TOKENS` in `@objectstack/spec`) resolves
118+
* to the ISO-8601 week key of the reference day, `2026-W47`: the label
119+
* {@link bucketDateKey} writes for an analytics `week` bucket, in the
120+
* request's reference timezone, so the two cannot disagree about a week. It
121+
* is text. The temporal-comparand door judges a resolved DATE MACRO's year;
122+
* a period key is not one, and this field-agnostic resolver never decides
123+
* what a column makes of the key.
124+
*
115125
* # A `{ $record }` comparand refuses here by name
116126
*
117127
* [#34199] The `lookupFilters` comparand `{ $record: 'path' }` reads the record
@@ -123,13 +133,15 @@
123133

124134
import {
125135
classifyFilterToken,
136+
isPeriodKeyToken,
126137
isReadableIds,
127138
isRecordContextToken,
128139
parseDateMacroParam,
129140
type DateMacroUnit,
141+
type PeriodKeyToken,
130142
} from '@objectstack/spec/data';
131143
import type { StandardErrorCode } from '@objectstack/spec/api';
132-
import { calendarPartsInTzOrUtc, wallClockToUtcMs } from './datetime.js';
144+
import { bucketDateKey, calendarPartsInTzOrUtc, wallClockToUtcMs } from './datetime.js';
133145
import {
134146
isOutsideTemporalYearRange,
135147
SUPPORTED_TEMPORAL_YEARS,
@@ -185,8 +197,8 @@ export class UnknownFilterTokenError extends Error {
185197
(suggestion
186198
? `Did you mean "{${suggestion}}"? `
187199
: 'Resolvable placeholders are the context tokens ({current_user_id}, ' +
188-
'{current_org_id}) and the date macros ({today}, {current_quarter_start}, ' +
189-
'{30_days_ago}, …). ') +
200+
'{current_org_id}), the date macros ({today}, {current_quarter_start}, ' +
201+
'{30_days_ago}, …) and the ISO week key {current_iso_week}. ') +
190202
'Sending it to the data engine verbatim would compare it as a literal ' +
191203
'string and match nothing, which is indistinguishable from an empty result.',
192204
);
@@ -446,6 +458,20 @@ function dateMacroInstant(
446458
return { at: addUnits(param.unit, today, sign * param.n), spelled: 'day' };
447459
}
448460

461+
/**
462+
* Each period-key token's resolver: the key of the period the reference
463+
* instant falls in, as seen in the reference timezone. `satisfies` keeps it
464+
* exhaustive: a token added to the spec's list without a resolver here fails
465+
* to compile rather than resolving to nothing.
466+
*
467+
* `{current_iso_week}` is {@link bucketDateKey}'s `week` label, the one
468+
* statement of the ISO week rule (Monday-start weeks, the ISO week-numbering
469+
* year at the year edges).
470+
*/
471+
const PERIOD_KEY_RESOLVERS = {
472+
current_iso_week: (now: Date, timezone: string | undefined) => bucketDateKey(now, 'week', timezone),
473+
} satisfies Record<PeriodKeyToken, (now: Date, timezone: string | undefined) => string | null>;
474+
449475
/**
450476
* Resolve one token NAME (the bit inside the braces) to its concrete value.
451477
* Throws {@link UnresolvedFilterTokenError} for a vocabulary token the request
@@ -501,6 +527,13 @@ export function resolveFilterToken(
501527
);
502528
}
503529

530+
// ── Period keys ───────────────────────────────────────────────────────
531+
// A key such as `2026-W47`: text, never a day. `bucketDateKey` answers
532+
// `null` only for an invalid instant, which is no key at all.
533+
if (isPeriodKeyToken(token)) {
534+
return PERIOD_KEY_RESOLVERS[token as PeriodKeyToken](now, ctx.timezone) ?? undefined;
535+
}
536+
504537
// ── Date macros ───────────────────────────────────────────────────────
505538
const macro = dateMacroInstant(token, now, ctx.timezone);
506539
if (macro === undefined) return undefined;

0 commit comments

Comments
 (0)