@7365admin1/layer-common 4.163.6 → 4.164.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.164.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0305d43: CCTV Engine Live: saved camera groups - pick a group to show its cameras; users who manage engines can save the picked cameras as a group or delete one.
8
+
9
+ ## 4.163.7
10
+
11
+ ### Patch Changes
12
+
13
+ - 42c6eed: CCTV Engine: hide "Confidence" on smart detection results (the engine sends no score, so it always read 0%), and show a loading spinner instead of an empty picture while smart detection photos load (a broken-picture icon only when a photo really failed).
14
+ - 33f15ff: Visitor Mgmt: optional "today" default for the date filter
15
+
16
+ VisitorManagement takes a new `defaultDateRange` prop. "last30" (the default)
17
+ keeps iSecure's last 30 days through today, unchanged. "today" opens on today
18
+ to today in Singapore time, stops either picker going past today, ignores dates
19
+ left in the URL on a fresh open, and moves an untouched today to the new day
20
+ when the page is left open past midnight. InputDatePicker gains an optional
21
+ `max`.
22
+
3
23
  ## 4.163.6
4
24
 
5
25
  ### Patch Changes
@@ -3734,11 +3754,11 @@ Monthly report: a month that had patrols opens the list of that month's patrol r
3734
3754
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
3735
3755
  own rule from two endpoints the console already calls, unprojected:
3736
3756
 
3737
- GET /api/members/user/:user/app/admin the Seven365 staff membership
3738
- GET /api/roles/id/:role that membership's role document
3757
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
3758
+ GET /api/roles/id/:role that membership's role document
3739
3759
 
3740
- owner = member.type === "admin" && role.type === "admin" && role.default === true
3741
- staff = member.type === "admin" && role.type === "admin"
3760
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
3761
+ staff = member.type === "admin" && role.type === "admin"
3742
3762
 
3743
3763
  `role.default` is the marker because it is the only property of a platform
3744
3764
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -57,7 +57,8 @@
57
57
  <v-card variant="outlined" :class="{ 'cctv-dd__picked': picked.has(p.file) }">
58
58
  <div class="cctv-dd__thumb" @click="togglePick(p.file)">
59
59
  <img v-if="thumbs[key(p.file)]" :src="thumbs[key(p.file)]" :alt="`Waiting photo from ${when(p.at)}`" />
60
- <v-icon v-else icon="mdi-image-outline" size="28" />
60
+ <v-icon v-else-if="thumbFailed.has(key(p.file))" icon="mdi-image-broken-variant" size="28" />
61
+ <v-progress-circular v-else indeterminate size="24" width="2" aria-label="Loading photo" />
61
62
  <v-checkbox-btn :model-value="picked.has(p.file)" class="cctv-dd__check" density="compact" aria-label="Select photo" @click.stop @update:model-value="togglePick(p.file)" />
62
63
  </div>
63
64
  <div class="pa-2">
@@ -84,7 +85,8 @@
84
85
  <v-col v-for="f in data.sorted[s]" :key="f" cols="4" sm="3" md="2">
85
86
  <div class="cctv-dd__thumb cctv-dd__thumb--sm">
86
87
  <img v-if="thumbs[key(f, s)]" :src="thumbs[key(f, s)]" :alt="`Photo sorted as ${s}`" />
87
- <v-icon v-else icon="mdi-image-outline" size="24" />
88
+ <v-icon v-else-if="thumbFailed.has(key(f, s))" icon="mdi-image-broken-variant" size="24" />
89
+ <v-progress-circular v-else indeterminate size="20" width="2" aria-label="Loading photo" />
88
90
  <v-btn icon="mdi-close" size="x-small" variant="flat" class="cctv-dd__remove" :disabled="busy" :aria-label="`Remove this photo from ${s}`" @click="discard([f], s)" />
89
91
  </div>
90
92
  </v-col>
@@ -122,6 +124,8 @@ const loading = ref(false);
122
124
  const error = ref<unknown>(null);
123
125
  const busy = ref(false);
124
126
  const thumbs = ref<Record<string, string>>({});
127
+ // Photos that could not be fetched (shown as a broken picture instead of a spinner).
128
+ const thumbFailed = ref<Set<string>>(new Set());
125
129
  const picked = ref<Set<string>>(new Set());
126
130
  const alerts = ref<string[]>([]);
127
131
  const confirmDiscard = ref(false);
@@ -158,7 +162,7 @@ async function loadThumbs() {
158
162
  const url = await classifierPhoto(props.engine, props.name, t.file, t.state);
159
163
  thumbs.value = { ...thumbs.value, [t.k]: url };
160
164
  } catch {
161
- /* placeholder stays */
165
+ thumbFailed.value = new Set(thumbFailed.value).add(t.k);
162
166
  }
163
167
  }
164
168
  };
@@ -33,7 +33,8 @@
33
33
  <tr v-if="event.faceName"><th>Face</th><td>{{ event.faceName }}</td></tr>
34
34
  <tr v-if="event.plate"><th>Plate</th><td>{{ event.plate }}</td></tr>
35
35
  <tr v-if="!isClassification"><th>Zones</th><td>{{ (event.zones ?? []).join(", ") || "None" }}<template v-if="(event.enteredZones ?? []).length"> (entered: {{ event.enteredZones.join(" then ") }})</template></td></tr>
36
- <tr><th>Confidence</th><td>{{ scoreText(event.score) }}</td></tr>
36
+ <!-- A smart detection result carries no score from the engine. -->
37
+ <tr v-if="!isClassification"><th>Confidence</th><td>{{ scoreText(event.score) }}</td></tr>
37
38
  <tr v-if="event.incident"><th>Incident</th><td>An incident report was created for this alert.</td></tr>
38
39
  </tbody>
39
40
  </v-table>
@@ -9,6 +9,21 @@
9
9
 
10
10
  <template v-if="engine">
11
11
  <div class="d-flex flex-wrap align-center ga-3 my-3">
12
+ <v-select
13
+ v-if="groups.length"
14
+ :model-value="group"
15
+ :items="groups"
16
+ item-title="name"
17
+ item-value="name"
18
+ label="Camera group"
19
+ density="comfortable"
20
+ hide-details
21
+ clearable
22
+ class="cctv-live__group"
23
+ :max-width="smAndDown ? undefined : 260"
24
+ data-test="camera-group"
25
+ @update:model-value="pickGroup"
26
+ />
12
27
  <v-btn-toggle v-model="tiles" mandatory density="comfortable" divided color="primary" aria-label="Grid size">
13
28
  <v-btn v-for="l in GRID_LAYOUTS" :key="l.key" :value="l.key" size="small">{{ l.key === 1 ? "Single" : l.key }}</v-btn>
14
29
  </v-btn-toggle>
@@ -26,8 +41,16 @@
26
41
  :hint="`Up to ${tiles}. Empty = the first ${tiles} on this engine.`"
27
42
  class="cctv-live__picker"
28
43
  :max-width="smAndDown ? undefined : 420"
44
+ @update:model-value="group = null"
29
45
  />
46
+ <template v-if="canManage && cameras.length">
47
+ <v-btn size="small" variant="tonal" prepend-icon="mdi-content-save-outline" :disabled="!picked.length" @click="openSave">Save as group</v-btn>
48
+ <v-btn v-if="group" size="small" variant="text" color="error" prepend-icon="mdi-delete-outline" @click="removeOpen = true">Delete group</v-btn>
49
+ </template>
30
50
  </div>
51
+ <p v-if="canManage && cameras.length && !groups.length" class="hero-muted mt-n1 mb-2">
52
+ Tip: pick the cameras you watch together, then press Save as group. Everyone on this site can then show them with one choice.
53
+ </p>
31
54
 
32
55
  <v-progress-linear v-if="loading" indeterminate />
33
56
  <CctvEngineNotice v-else-if="error" :error="error" retry @retry="loadCameras" />
@@ -40,36 +63,92 @@
40
63
  <CctvEngineLiveTile v-for="c in shown" :key="`${engine}/${c.name}`" :engine-id="engine" :camera="c.name" />
41
64
  </div>
42
65
  </template>
66
+
67
+ <v-dialog v-model="saveOpen" max-width="460">
68
+ <v-card>
69
+ <v-card-title>Save these cameras as a group</v-card-title>
70
+ <v-card-text>
71
+ <p class="hero-muted">{{ picked.length }} camera{{ picked.length === 1 ? "" : "s" }}: {{ picked.slice(0, MAX_GROUP_CAMERAS).join(", ") }}</p>
72
+ <v-text-field v-model="groupName" label="Group name (e.g. Gate cameras)" density="comfortable" counter="40" maxlength="40" autofocus />
73
+ <p class="hero-muted mb-0">A group with the same name is replaced.</p>
74
+ <CctvEngineNotice v-if="saveError" class="mt-2" :error="saveError" />
75
+ </v-card-text>
76
+ <v-card-actions>
77
+ <v-spacer />
78
+ <v-btn variant="text" @click="saveOpen = false">Cancel</v-btn>
79
+ <v-btn color="primary" :loading="saving" :disabled="!groupName.trim()" @click="saveGroup">Save group</v-btn>
80
+ </v-card-actions>
81
+ </v-card>
82
+ </v-dialog>
83
+
84
+ <v-dialog v-model="removeOpen" max-width="420">
85
+ <v-card>
86
+ <v-card-title>Delete the group "{{ group }}"?</v-card-title>
87
+ <v-card-text>
88
+ Only the saved group is removed. The cameras keep working.
89
+ <CctvEngineNotice v-if="saveError" class="mt-2" :error="saveError" />
90
+ </v-card-text>
91
+ <v-card-actions>
92
+ <v-spacer />
93
+ <v-btn variant="text" @click="removeOpen = false">Keep</v-btn>
94
+ <v-btn color="error" :loading="saving" @click="removeGroup">Delete</v-btn>
95
+ </v-card-actions>
96
+ </v-card>
97
+ </v-dialog>
43
98
  </div>
44
99
  </template>
45
100
 
46
101
  <script setup lang="ts">
47
102
  import { computed, ref, watch } from "vue";
48
103
  import { useDisplay } from "vuetify";
49
- import { GRID_LAYOUTS, gridColumns, pickGridCameras } from "../../utils/cctv-engine";
104
+ import {
105
+ CCTV_PERMISSIONS,
106
+ GRID_LAYOUTS,
107
+ MAX_GROUP_CAMERAS,
108
+ gridColumns,
109
+ groupCameras,
110
+ layoutFor,
111
+ pickGridCameras,
112
+ saveGroupIn,
113
+ type TCameraGroup,
114
+ } from "../../utils/cctv-engine";
50
115
 
51
- defineProps<{ site: string; access?: unknown }>();
116
+ const props = defineProps<{ site: string; access?: { can: (p: any) => boolean } }>();
52
117
 
53
- const { listCameras } = useCctvEngine();
118
+ const { listCameras, updateEngine } = useCctvEngine();
54
119
  const { smAndDown } = useDisplay();
120
+ const canManage = computed(() => props.access?.can(CCTV_PERMISSIONS.manageEngine) ?? false);
55
121
 
56
122
  const engine = ref("");
123
+ const engines = ref<any[]>([]);
57
124
  const tiles = ref<number>(4);
58
125
  const picked = ref<string[]>([]);
126
+ const group = ref<string | null>(null);
59
127
  const cameras = ref<{ name: string }[]>([]);
60
128
  const loading = ref(false);
61
129
  const error = ref<unknown>(null);
62
130
 
131
+ const groups = computed<TCameraGroup[]>(() => engines.value.find((e) => e._id === engine.value)?.cameraGroups ?? []);
63
132
  const shown = computed(() => pickGridCameras(cameras.value, picked.value.slice(0, tiles.value), tiles.value));
64
133
  const columns = computed(() => gridColumns(tiles.value, smAndDown.value));
65
134
 
66
135
  function onEngines(list: any[]) {
136
+ engines.value = list;
67
137
  if (!engine.value && list[0]) engine.value = list[0]._id;
68
138
  }
69
139
 
140
+ function pickGroup(name: string | null) {
141
+ group.value = name;
142
+ if (!name) return;
143
+ const names = groupCameras(groups.value.find((g) => g.name === name), cameras.value);
144
+ picked.value = names;
145
+ tiles.value = layoutFor(names.length);
146
+ }
147
+
70
148
  async function loadCameras() {
71
149
  cameras.value = [];
72
150
  picked.value = [];
151
+ group.value = null;
73
152
  error.value = null;
74
153
  if (!engine.value) return;
75
154
  loading.value = true;
@@ -83,10 +162,53 @@ async function loadCameras() {
83
162
  }
84
163
  }
85
164
 
165
+ // ---- save / delete groups (manage-engine)
166
+ const saveOpen = ref(false);
167
+ const removeOpen = ref(false);
168
+ const groupName = ref("");
169
+ const saving = ref(false);
170
+ const saveError = ref<unknown>(null);
171
+
172
+ function openSave() {
173
+ groupName.value = group.value ?? "";
174
+ saveError.value = null;
175
+ saveOpen.value = true;
176
+ }
177
+
178
+ async function store(next: TCameraGroup[]) {
179
+ saving.value = true;
180
+ saveError.value = null;
181
+ try {
182
+ const res: any = await updateEngine(engine.value, { cameraGroups: next });
183
+ const saved = res?.cameraGroups ?? next;
184
+ engines.value = engines.value.map((e) => (e._id === engine.value ? { ...e, cameraGroups: saved } : e));
185
+ return true;
186
+ } catch (e) {
187
+ saveError.value = e;
188
+ return false;
189
+ } finally {
190
+ saving.value = false;
191
+ }
192
+ }
193
+
194
+ async function saveGroup() {
195
+ const next = saveGroupIn(groups.value, groupName.value, picked.value);
196
+ if (!next || !(await store(next))) return;
197
+ saveOpen.value = false;
198
+ group.value = next.find((g) => g.name.toLowerCase() === groupName.value.trim().toLowerCase())?.name ?? null;
199
+ }
200
+
201
+ async function removeGroup() {
202
+ if (!(await store(groups.value.filter((g) => g.name !== group.value)))) return;
203
+ removeOpen.value = false;
204
+ group.value = null;
205
+ }
206
+
86
207
  watch(engine, loadCameras, { immediate: true });
87
208
  </script>
88
209
 
89
210
  <style scoped>
90
211
  .cctv-live__grid { display: grid; gap: 8px; }
91
212
  .cctv-live__picker { min-width: 220px; flex: 1; }
213
+ .cctv-live__group { min-width: 180px; }
92
214
  </style>
@@ -7,7 +7,7 @@
7
7
  </template>
8
8
  </v-text-field>
9
9
  <div class="w-100 d-flex align-end ga-3 hidden-input">
10
- <input ref="dateInput" type="date" v-model="date" :min="min" />
10
+ <input ref="dateInput" type="date" v-model="date" :min="min" :max="max" />
11
11
  </div>
12
12
  </div>
13
13
  </template>
@@ -26,6 +26,10 @@ const prop = defineProps({
26
26
  min: {
27
27
  type: String,
28
28
  default: undefined
29
+ },
30
+ max: {
31
+ type: String,
32
+ default: undefined
29
33
  }
30
34
  })
31
35
 
@@ -127,8 +127,14 @@
127
127
  v-model="dateFrom"
128
128
  density="compact"
129
129
  hide-details
130
+ :max="todayOnly ? sgToday : undefined"
131
+ />
132
+ <InputDatePicker
133
+ v-model="dateTo"
134
+ density="compact"
135
+ hide-details
136
+ :max="todayOnly ? sgToday : undefined"
130
137
  />
131
- <InputDatePicker v-model="dateTo" density="compact" hide-details />
132
138
  <!-- iSecure: every tab but Unregistered; the Guests tab offers
133
139
  Guest / Contractor, the Visitors tab the eight types. -->
134
140
  <AppSelect
@@ -1883,6 +1889,7 @@ import { isVisitorPassSmsOn } from "../composables/useVisitor";
1883
1889
  import { barrierCameraOf, barrierMessage, barrierOf, VISITOR_ACTION_SUCCESS } from "../utils/visitor-barrier";
1884
1890
  import useVisitorCameraChoices from "../composables/useVisitorCameraChoices";
1885
1891
  import { VISITOR_CAMERA_LABEL } from "../utils/visitor-camera";
1892
+ import { notAfterToday, sgDateOf, type VisitorDateDefault } from "../utils/visitor-date-default";
1886
1893
  import usePassKey from "../composables/usePassKey";
1887
1894
  import {
1888
1895
  VISITOR_SEARCH_DEBOUNCE_MS,
@@ -1894,6 +1901,11 @@ import {
1894
1901
  const { downloadPDF } = usePDFDownload();
1895
1902
 
1896
1903
  const props = defineProps({
1904
+ // The date filter's opening range: "last30" (iSecure) or "today" (Property).
1905
+ defaultDateRange: {
1906
+ type: String as PropType<VisitorDateDefault>,
1907
+ default: "last30",
1908
+ },
1897
1909
  canAddVisitor: {
1898
1910
  type: Boolean,
1899
1911
  default: false,
@@ -2275,8 +2287,15 @@ function daysAgo(days: number) {
2275
2287
  date.setDate(date.getDate() - days);
2276
2288
  return date;
2277
2289
  }
2278
- const defaultDateTo = () => normalizeDateOnly(new Date().toISOString());
2279
- const defaultDateFrom = () => normalizeDateOnly(daysAgo(30).toISOString());
2290
+ // defaultDateRange "today" (Property, DV-0886): both dates are today in
2291
+ // Singapore, nothing after today can be picked, and a fresh open ignores dates
2292
+ // left in the URL. "last30" keeps the lines below exactly as they were.
2293
+ const todayOnly = computed(() => props.defaultDateRange === "today");
2294
+ const sgToday = ref(sgDateOf());
2295
+ const defaultDateTo = () =>
2296
+ todayOnly.value ? sgToday.value : normalizeDateOnly(new Date().toISOString());
2297
+ const defaultDateFrom = () =>
2298
+ todayOnly.value ? sgToday.value : normalizeDateOnly(daysAgo(30).toISOString());
2280
2299
 
2281
2300
  const dateTo = ref(defaultDateTo());
2282
2301
  const dateFrom = ref(defaultDateFrom());
@@ -4263,11 +4282,37 @@ watch(
4263
4282
  // iSecure: the dates cannot be cleared - a cleared one goes back to its default.
4264
4283
  watch(dateFrom, (value) => {
4265
4284
  if (!value) dateFrom.value = defaultDateFrom();
4285
+ else if (todayOnly.value && value > sgToday.value) dateFrom.value = sgToday.value;
4266
4286
  });
4267
4287
  watch(dateTo, (value) => {
4268
4288
  if (!value) dateTo.value = defaultDateTo();
4289
+ else if (todayOnly.value && value > sgToday.value) dateTo.value = sgToday.value;
4269
4290
  });
4270
4291
 
4292
+ // "today" only: a page left open past midnight moves an untouched today to
4293
+ // the new day. A range the user picked is left alone.
4294
+ let sgDayTimer: ReturnType<typeof setInterval> | null = null;
4295
+ onMounted(() => {
4296
+ if (!todayOnly.value) return;
4297
+ sgDayTimer = setInterval(() => {
4298
+ const next = sgDateOf();
4299
+ if (next === sgToday.value) return;
4300
+ const previous = sgToday.value;
4301
+ sgToday.value = next;
4302
+ if (dateFrom.value === previous && dateTo.value === previous) {
4303
+ dateFrom.value = next;
4304
+ dateTo.value = next;
4305
+ }
4306
+ }, 60_000);
4307
+ });
4308
+ onBeforeUnmount(() => {
4309
+ if (sgDayTimer) clearInterval(sgDayTimer);
4310
+ });
4311
+
4312
+ // "today" only: the first read of the route is a fresh open, so dates left in
4313
+ // the URL (bookmark, back navigation, yesterday's tab) do not replace today.
4314
+ let routeDatesSeen = false;
4315
+
4271
4316
  const syncVisitorFiltersFromRoute = () => {
4272
4317
  const requestedTab = (route.query.tab as string) || "registered";
4273
4318
  const nextTab =
@@ -4293,15 +4338,20 @@ const syncVisitorFiltersFromRoute = () => {
4293
4338
  searchQuery.value = nextSearch;
4294
4339
  }
4295
4340
 
4296
- if (route.query.dateFrom) {
4297
- const nextDateFrom = normalizeDateOnly(route.query.dateFrom as string);
4341
+ const skipRouteDates = todayOnly.value && !routeDatesSeen;
4342
+ routeDatesSeen = true;
4343
+ const fromRoute = (value: string) =>
4344
+ todayOnly.value ? notAfterToday(value, sgToday.value) : value;
4345
+
4346
+ if (route.query.dateFrom && !skipRouteDates) {
4347
+ const nextDateFrom = fromRoute(normalizeDateOnly(route.query.dateFrom as string));
4298
4348
  if (dateFrom.value !== nextDateFrom) {
4299
4349
  dateFrom.value = nextDateFrom;
4300
4350
  }
4301
4351
  }
4302
4352
 
4303
- if (route.query.dateTo) {
4304
- const nextDateTo = normalizeDateOnly(route.query.dateTo as string);
4353
+ if (route.query.dateTo && !skipRouteDates) {
4354
+ const nextDateTo = fromRoute(normalizeDateOnly(route.query.dateTo as string));
4305
4355
  if (dateTo.value !== nextDateTo) {
4306
4356
  dateTo.value = nextDateTo;
4307
4357
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.163.6",
5
+ "version": "4.164.0",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -234,6 +234,32 @@ export function pickGridCameras<T extends { name: string }>(all: readonly T[], p
234
234
  return [...chosen, ...rest].slice(0, tiles);
235
235
  }
236
236
 
237
+ // --------------------------------------------------------------------------- saved camera groups
238
+
239
+ export type TCameraGroup = { name: string; cameras: string[] };
240
+ export const MAX_GROUP_CAMERAS = 16;
241
+
242
+ /** The smallest grid that holds `count` cameras (16 at most). */
243
+ export function layoutFor(count: number): number {
244
+ return (GRID_LAYOUTS.find((l) => l.key >= count) ?? GRID_LAYOUTS[GRID_LAYOUTS.length - 1]).key;
245
+ }
246
+
247
+ /** A group's cameras that the engine still has, in the group's order (a removed camera simply drops out). */
248
+ export function groupCameras(group: TCameraGroup | null | undefined, cameras: readonly { name: string }[]): string[] {
249
+ if (!group) return [];
250
+ const have = new Set(cameras.map((c) => c.name));
251
+ return group.cameras.filter((n) => have.has(n));
252
+ }
253
+
254
+ /** Add a group, or replace the one with the same name (any case). Returns a new list; null when the name or cameras are missing. */
255
+ export function saveGroupIn(groups: readonly TCameraGroup[], name: string, cameras: readonly string[]): TCameraGroup[] | null {
256
+ const n = name.trim();
257
+ if (!n || !cameras.length) return null;
258
+ const g = { name: n, cameras: cameras.slice(0, MAX_GROUP_CAMERAS) };
259
+ const i = groups.findIndex((x) => x.name.toLowerCase() === n.toLowerCase());
260
+ return i < 0 ? [...groups, g] : groups.map((x, j) => (j === i ? g : x));
261
+ }
262
+
237
263
  /** Latest-picture fallback: refresh every 2 s. The tick is part of the address so the browser never reuses a stale frame. */
238
264
  export const STILL_REFRESH_MS = 2000;
239
265
 
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The Visitor Mgmt date filter's default range.
3
+ *
4
+ * - "last30" (the default): the last 30 days through today. iSecure (Security
5
+ * web) keeps this; it is the behaviour before DV-0886.
6
+ * - "today": From and To are both today. The Property app asks for this.
7
+ *
8
+ * "Today" is the Singapore date, not the browser's: a browser in another time
9
+ * zone, or with a wrong clock, would otherwise show yesterday or tomorrow.
10
+ * Dates are YYYY-MM-DD strings, so they compare correctly as text.
11
+ */
12
+ export type VisitorDateDefault = "last30" | "today";
13
+
14
+ export const VISITOR_DATE_TIME_ZONE = "Asia/Singapore";
15
+
16
+ /** The Singapore date of `now`, as YYYY-MM-DD. */
17
+ export function sgDateOf(now: Date = new Date()): string {
18
+ return new Intl.DateTimeFormat("en-CA", {
19
+ timeZone: VISITOR_DATE_TIME_ZONE,
20
+ year: "numeric",
21
+ month: "2-digit",
22
+ day: "2-digit",
23
+ }).format(now);
24
+ }
25
+
26
+ /** YYYY-MM-DD `days` before `day`. */
27
+ export function daysBefore(day: string, days: number): string {
28
+ const date = new Date(`${day}T00:00:00Z`);
29
+ date.setUTCDate(date.getUTCDate() - days);
30
+ return date.toISOString().slice(0, 10);
31
+ }
32
+
33
+ /** The [from, to] a fresh page opens with. */
34
+ export function visitorDefaultRange(
35
+ mode: VisitorDateDefault,
36
+ today: string,
37
+ ): { from: string; to: string } {
38
+ return mode === "today"
39
+ ? { from: today, to: today }
40
+ : { from: daysBefore(today, 30), to: today };
41
+ }
42
+
43
+ /** A date after today becomes today; anything else is kept. */
44
+ export function notAfterToday(day: string, today: string): string {
45
+ return day && day > today ? today : day;
46
+ }