@7365admin1/layer-common 4.183.0 → 4.184.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,16 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.184.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d25e96e: Add Site: check the typed site name against other companies' sites and request access from the managing agent instead of creating a duplicate. New `useCustomerSite` calls (name-check, join requests), `utils/site-join-request` helpers and the `SiteAccessRequests` list (approve / reject / cancel).
8
+
9
+ ### Patch Changes
10
+
11
+ - 463259c: Vehicle QR stickers: a blank (not yet linked) sticker printed on a shape with a name tag (heart, star, shield ...) now keeps its sticker number on the sticker itself, under its code, on the print sheet and in Save as image. Before, the number went only to the cut-off strip.
12
+ - 7f86142: Building Management: Block Name is back as an optional field (add and edit). A facility block such as "Barbeque Pit" keeps its own name; leaving it empty still saves "Blk N". Block and unit lists show "Blk 7 - Barbeque Pit" when a block has its own name. Names only need to be unique within a site.
13
+
3
14
  ## 4.183.0
4
15
 
5
16
  ### Minor Changes
@@ -4011,11 +4022,11 @@ Monthly report: a month that had patrols opens the list of that month's patrol r
4011
4022
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
4012
4023
  own rule from two endpoints the console already calls, unprojected:
4013
4024
 
4014
- GET /api/members/user/:user/app/admin the Seven365 staff membership
4015
- GET /api/roles/id/:role that membership's role document
4025
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
4026
+ GET /api/roles/id/:role that membership's role document
4016
4027
 
4017
- owner = member.type === "admin" && role.type === "admin" && role.default === true
4018
- staff = member.type === "admin" && role.type === "admin"
4028
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
4029
+ staff = member.type === "admin" && role.type === "admin"
4019
4030
 
4020
4031
  `role.default` is the marker because it is the only property of a platform
4021
4032
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -19,6 +19,18 @@
19
19
  </v-row>
20
20
  </v-col>
21
21
 
22
+ <v-col cols="12">
23
+ <v-row no-gutters>
24
+ <InputLabel class="text-capitalize font-weight-bold" title="Block Name (optional)" />
25
+ <v-col cols="12">
26
+ <v-text-field v-model="building.name" class="filter-field" density="comfortable" maxlength="60"
27
+ :placeholder="building.block ? `Leave empty for Blk ${building.block}` : 'e.g. Barbeque Pit'"
28
+ hint="Use a name for a facility guards send visitors to, e.g. Barbeque Pit. Empty = Blk + Block No."
29
+ persistent-hint></v-text-field>
30
+ </v-col>
31
+ </v-row>
32
+ </v-col>
33
+
22
34
  <v-col cols="6" class="mt-2">
23
35
  <v-row no-gutters>
24
36
  <InputLabel class="text-capitalize font-weight-bold" title="No. of Levels" required />
@@ -47,6 +59,12 @@
47
59
 
48
60
  <v-expand-transition>
49
61
  <v-row v-if="prop.mode === 'edit'" no-gutters class="px-6">
62
+ <v-col cols="12" class="mb-2">
63
+ <InputLabel class="text-capitalize font-weight-bold" title="Block Name (optional)" />
64
+ <v-text-field v-model="building.name" class="filter-field" density="comfortable" maxlength="60"
65
+ :placeholder="`Leave empty for Blk ${building.block}`"
66
+ hint="Empty = Blk + Block No. Another property may use the same name." persistent-hint></v-text-field>
67
+ </v-col>
50
68
  <template v-for="(level, levelIndex) in building.levels" :key="levelIndex">
51
69
  <v-col cols="12">
52
70
  <v-row no-gutters>
@@ -187,7 +205,7 @@
187
205
 
188
206
  <script setup lang="ts">
189
207
  import InputLabel from './InputLabel.vue';
190
- import { blockLabel, normaliseBlock, BLOCK_NO_MESSAGE } from "../utils/building-block";
208
+ import { blockNameFor, normaliseBlock, BLOCK_NO_MESSAGE } from "../utils/building-block";
191
209
 
192
210
  const prop = defineProps({
193
211
  site: {
@@ -353,7 +371,7 @@ async function submit() {
353
371
  try {
354
372
  if (prop.mode === "add") {
355
373
  const buildingPayload = { ...building.value };
356
- // One block field only: the stored name is derived from the number ("Blk 3").
374
+ // The block's own name if typed (e.g. "Barbeque Pit"), else "Blk 3". Unique within this site only.
357
375
  const blockNo = normaliseBlock(buildingPayload.block);
358
376
  if (blockNo === null) {
359
377
  message.value = BLOCK_NO_MESSAGE;
@@ -364,9 +382,9 @@ async function submit() {
364
382
  message.value = `Block ${blockNo} already exists. Choose a different Block No.`;
365
383
  return;
366
384
  }
367
- const name = blockLabel(blockNo);
385
+ const name = blockNameFor(blockNo, buildingPayload.name);
368
386
  if (prop.blocks.some((b) => b.name?.trim().toLowerCase() === name.toLowerCase() && b.block !== blockNo)) {
369
- message.value = `Another block is already named "${name}". Rename it first, or choose a different Block No.`;
387
+ message.value = `Another block in this site is already named "${name}". Choose a different name.`;
370
388
  return;
371
389
  }
372
390
 
@@ -390,8 +408,13 @@ async function submit() {
390
408
 
391
409
  const newLevels = [...newLevelsArray.value, ...(activeNewLevelInput.value.trim() ? [activeNewLevelInput.value.trim()] : [])];
392
410
 
411
+ const editedName = blockNameFor(building.value.block, building.value.name);
412
+ if (prop.blocks.some((b: any) => b._id !== building.value._id && b.name?.trim().toLowerCase() === editedName.toLowerCase())) {
413
+ message.value = `Another block in this site is already named "${editedName}". Choose a different name.`;
414
+ return;
415
+ }
393
416
  await updateById(building.value._id ?? "", {
394
- name: building.value.name,
417
+ name: editedName,
395
418
  block: building.value.block,
396
419
  // levels: building.value.levels,
397
420
  buildingFiles: (building.value.buildingFiles as string[] || []).map((id) => ({ id, name: buildingFilesNames.value[id] ?? "" })),
@@ -22,7 +22,7 @@
22
22
  <template #prepend-additional>
23
23
  <AppField v-model="searchInput" search compact placeholder="Search" klass="app-toolbar__search" />
24
24
  </template>
25
- <template #item.block="{ value }">{{ value ? blockLabel(value) : "" }}</template>
25
+ <template #item.block="{ value, item }">{{ blockDisplay(value, (item as any)?.name) }}</template>
26
26
  <template #item.createdAt="{ value }">
27
27
  {{ new Date(value).toLocaleDateString() }}
28
28
  </template>
@@ -55,7 +55,7 @@
55
55
  <v-row no-gutters class="mb-4">
56
56
  <v-col cols="12">
57
57
  <strong>Block:</strong>
58
- {{ selectedBuilding?.block ? blockLabel(selectedBuilding.block) : "N/A" }}
58
+ {{ selectedBuilding?.block ? blockDisplay(selectedBuilding.block, selectedBuilding?.name) : "N/A" }}
59
59
  </v-col>
60
60
 
61
61
  <v-col cols="12">
@@ -158,7 +158,7 @@
158
158
  // Relative import, never Nuxt auto-import: this layer's `utils/` are auto-imported
159
159
  // into the consuming apps but not reliably into the layer's own components.
160
160
  import { levelCount } from "../../utils/data";
161
- import { blockLabel } from "../../utils/building-block";
161
+ import { blockDisplay } from "../../utils/building-block";
162
162
 
163
163
 
164
164
  const props = defineProps({
@@ -50,7 +50,7 @@
50
50
  <AppField v-model="searchInput" search compact placeholder="Search" klass="app-toolbar__search" />
51
51
  </template>
52
52
  <template #item.block="{ value, item }">
53
- {{ value ? blockLabel(value) : "" }}
53
+ {{ blockDisplay(value, (item as any)?.buildingName) }}
54
54
  </template>
55
55
  </TableMain>
56
56
 
@@ -174,7 +174,7 @@
174
174
 
175
175
  <script setup lang="ts">
176
176
  import useImportTemplates from "../../composables/useImportTemplates";
177
- import { blockLabel } from "../../utils/building-block";
177
+ import { blockDisplay } from "../../utils/building-block";
178
178
  import { saveBlob } from "../../composables/useInventory";
179
179
  import { useDisplay } from 'vuetify/lib/composables/display.mjs';
180
180
 
@@ -0,0 +1,288 @@
1
+ <template>
2
+ <!--
3
+ Access requests (spec 2026-11-16-site-exists-ma-approval): another company
4
+ typed the name of one of our sites in Add Site and asked to be linked to it
5
+ instead of creating a duplicate. "Requests to approve" is what we answer as
6
+ the site's managing agent; "Our requests" is what we asked of others.
7
+ Same card-per-item layout as ClientInvitations.
8
+ -->
9
+ <div v-if="visibleBoxes.length">
10
+ <div class="screen-card-title mt-6 mb-2" data-test="sites-access-requests-title">Access requests</div>
11
+ <AppCard class="table-card" data-test="site-access-requests">
12
+ <CardToolbar :count="total ? `${total} request${total === 1 ? '' : 's'}` : ''">
13
+ <template #tabs>
14
+ <button
15
+ v-for="t in visibleBoxes"
16
+ :key="t.value"
17
+ type="button"
18
+ role="tab"
19
+ class="app-tab"
20
+ :class="{ 'app-tab--active': box === t.value }"
21
+ :aria-selected="box === t.value"
22
+ :data-test="`site-access-tab-${t.value}`"
23
+ @click="box = t.value"
24
+ >
25
+ {{ t.label }}
26
+ </button>
27
+ </template>
28
+ <template #right>
29
+ <v-select
30
+ v-model="status"
31
+ :items="statuses"
32
+ density="compact"
33
+ variant="outlined"
34
+ aria-label="Request status"
35
+ hide-details
36
+ style="min-width: 150px"
37
+ data-test="site-access-status"
38
+ />
39
+ <AppButton variant="icon" icon="mdi-refresh" aria-label="Refresh" @click="load" />
40
+ <LocalPagination v-if="pages > 1" v-model="page" :length="pages" @update:value="load" />
41
+ </template>
42
+ </CardToolbar>
43
+
44
+ <div class="pa-4 d-flex flex-column ga-3">
45
+ <div v-if="loading" class="screen-hint">Loading…</div>
46
+ <div v-else-if="loadError" class="text-error" role="alert">{{ loadError }}</div>
47
+ <div v-else-if="!items.length" class="screen-hint" data-test="site-access-empty">{{ emptyLine }}</div>
48
+
49
+ <AppCard v-for="item in items" :key="item._id" class="site-access">
50
+ <div class="d-flex align-start ga-3 pa-4">
51
+ <v-avatar color="primary" variant="tonal" size="44">
52
+ <v-icon>mdi-domain-plus</v-icon>
53
+ </v-avatar>
54
+ <div class="flex-grow-1">
55
+ <div class="screen-card-title">
56
+ {{ box === "incoming" ? item.requesterOrgName || "A company" : "You" }}
57
+ asked for access to {{ item.siteName }}
58
+ </div>
59
+ <div class="screen-hint site-access__meta">
60
+ <span v-if="joinRequestRequester(item)">Requested by {{ joinRequestRequester(item) }} · </span>
61
+ <span>Sent {{ day(item.createdAt) }}</span>
62
+ </div>
63
+ </div>
64
+ <StatusChip :status="item.status" :label="joinRequestStatusLabel(item.status)" />
65
+ </div>
66
+
67
+ <div class="px-4 pb-2 site-access__body">{{ joinRequestStateLine(item, box) }}</div>
68
+ <div v-if="item.note" class="px-4 pb-4 site-access__body">
69
+ <span class="font-weight-medium">Note:</span> {{ item.note }}
70
+ </div>
71
+
72
+ <div v-if="item.status === 'pending'" class="d-flex align-center ga-2 px-4 pb-4">
73
+ <template v-if="box === 'incoming'">
74
+ <v-btn variant="flat" class="screen-btn-primary" @click="ask(item, 'approve')">Approve</v-btn>
75
+ <v-btn variant="outlined" class="screen-btn-ghost" @click="ask(item, 'reject')">Reject</v-btn>
76
+ </template>
77
+ <v-btn v-else variant="outlined" class="screen-btn-ghost" @click="ask(item, 'cancel')">
78
+ Cancel request
79
+ </v-btn>
80
+ </div>
81
+ </AppCard>
82
+ </div>
83
+
84
+ <ConfirmDialog v-model="confirmOpen">
85
+ <template #title>{{ confirmTitle }}</template>
86
+ <template #description>
87
+ <p class="mb-3">{{ confirmText }}</p>
88
+ <v-textarea
89
+ v-if="pending?.action === 'reject'"
90
+ v-model="reason"
91
+ label="Reason (optional)"
92
+ variant="outlined"
93
+ rows="2"
94
+ auto-grow
95
+ maxlength="500"
96
+ hide-details
97
+ />
98
+ <div v-if="actionError" class="text-error mt-2" role="alert">{{ actionError }}</div>
99
+ </template>
100
+ <template #footer>
101
+ <v-btn variant="outlined" class="screen-btn-ghost flex-grow-1" :disabled="working" @click="confirmOpen = false">
102
+ Back
103
+ </v-btn>
104
+ <v-btn variant="flat" class="screen-btn-primary flex-grow-1" :loading="working" @click="confirm">
105
+ {{ confirmButton }}
106
+ </v-btn>
107
+ </template>
108
+ </ConfirmDialog>
109
+ </AppCard>
110
+ </div>
111
+ </template>
112
+
113
+ <script setup lang="ts">
114
+ import type { TSiteJoinRequest, TSiteJoinRequestStatus } from "../utils/site-join-request";
115
+
116
+ const props = defineProps({
117
+ /** The organisation on screen. */
118
+ org: { type: String, required: true },
119
+ /** May add sites - only then is there an "Our requests" box to show. */
120
+ canRequest: { type: Boolean, default: true },
121
+ });
122
+
123
+ type Box = "incoming" | "outgoing";
124
+ type Action = "approve" | "reject" | "cancel";
125
+
126
+ const boxes: Array<{ value: Box; label: string }> = [
127
+ { value: "incoming", label: "Requests to approve" },
128
+ { value: "outgoing", label: "Our requests" },
129
+ ];
130
+ const statuses: Array<{ title: string; value: TSiteJoinRequestStatus }> = [
131
+ { title: "Pending", value: "pending" },
132
+ { title: "Approved", value: "approved" },
133
+ { title: "Rejected", value: "rejected" },
134
+ { title: "Cancelled", value: "cancelled" },
135
+ ];
136
+
137
+ const { getJoinRequests, approveJoinRequest, rejectJoinRequest, cancelJoinRequest } = useCustomerSite();
138
+
139
+ const limit = 20;
140
+ const box = ref<Box>("incoming");
141
+ const status = ref<TSiteJoinRequestStatus>("pending");
142
+ const page = ref(1);
143
+ const total = ref(0);
144
+ const pages = computed(() => Math.ceil(total.value / limit));
145
+ const items = ref<TSiteJoinRequest[]>([]);
146
+ const loading = ref(false);
147
+ const loadError = ref("");
148
+
149
+ const emptyLine = computed(() => {
150
+ if (box.value === "incoming") {
151
+ return status.value === "pending"
152
+ ? "No company is waiting for access to your sites."
153
+ : `No ${status.value} requests.`;
154
+ }
155
+ return status.value === "pending"
156
+ ? "You have no requests waiting for an answer."
157
+ : `You have no ${status.value} requests.`;
158
+ });
159
+
160
+ function day(value?: string | null) {
161
+ if (!value) return "";
162
+ const d = new Date(value);
163
+ return Number.isNaN(d.getTime())
164
+ ? ""
165
+ : d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
166
+ }
167
+
168
+ /*
169
+ * Approving is a separate right (provider invites). The server answers the
170
+ * incoming box with `canApprove: false` and no items for someone without it;
171
+ * a 403 on either box is read the same way. Neither is shown as an error -
172
+ * the box just disappears and the other one opens.
173
+ */
174
+ const deniedIncoming = ref(false);
175
+ const deniedOutgoing = ref(false);
176
+ const visibleBoxes = computed(() =>
177
+ boxes.filter((b) => (b.value === "incoming" ? !deniedIncoming.value : props.canRequest && !deniedOutgoing.value))
178
+ );
179
+ watch(
180
+ visibleBoxes,
181
+ (list) => {
182
+ if (list.length && !list.some((b) => b.value === box.value)) box.value = list[0].value;
183
+ },
184
+ { immediate: true }
185
+ );
186
+
187
+ function deny(which: Box) {
188
+ if (which === "incoming") deniedIncoming.value = true;
189
+ else deniedOutgoing.value = true;
190
+ items.value = [];
191
+ total.value = 0;
192
+ }
193
+
194
+ const isForbidden = (err: any) => (err?.statusCode ?? err?.status ?? err?.response?.status) === 403;
195
+
196
+ let loadSeq = 0;
197
+ async function load() {
198
+ if (!visibleBoxes.value.some((b) => b.value === box.value)) return;
199
+ const seq = ++loadSeq; // a slower answer for an earlier tab/filter/page is dropped
200
+ const which = box.value;
201
+ loading.value = true;
202
+ loadError.value = "";
203
+ try {
204
+ const res = await getJoinRequests(props.org, { box: which, status: status.value, page: page.value, limit });
205
+ if (seq !== loadSeq) return;
206
+ if (which === "incoming" && res?.canApprove === false) return deny("incoming");
207
+ items.value = Array.isArray(res?.items) ? res.items : [];
208
+ total.value = Number(res?.total ?? 0);
209
+ } catch (err: any) {
210
+ if (seq !== loadSeq) return;
211
+ if (isForbidden(err)) return deny(which);
212
+ items.value = [];
213
+ total.value = 0;
214
+ loadError.value = err?.data?.message || "Could not load the access requests. Please try again.";
215
+ } finally {
216
+ if (seq === loadSeq) loading.value = false;
217
+ }
218
+ }
219
+
220
+ // Confirm dialog for every action.
221
+ const confirmOpen = ref(false);
222
+ const pending = ref<{ item: TSiteJoinRequest; action: Action } | null>(null);
223
+ const reason = ref("");
224
+ const working = ref(false);
225
+ const actionError = ref("");
226
+
227
+ function ask(item: TSiteJoinRequest, action: Action) {
228
+ pending.value = { item, action };
229
+ reason.value = "";
230
+ actionError.value = "";
231
+ confirmOpen.value = true;
232
+ }
233
+
234
+ const confirmTitle = computed(() => {
235
+ const p = pending.value;
236
+ if (!p) return "";
237
+ return { approve: "Approve access?", reject: "Reject request?", cancel: "Cancel your request?" }[p.action];
238
+ });
239
+ const confirmText = computed(() => {
240
+ const p = pending.value;
241
+ if (!p) return "";
242
+ const who = p.item.requesterOrgName || "This company";
243
+ return {
244
+ approve: `${who} will be linked to ${p.item.siteName} and can provide services there. They will be notified.`,
245
+ reject: `${who} will not be linked to ${p.item.siteName}. They will be notified, with your reason if you give one.`,
246
+ cancel: `Your request for ${p.item.siteName} will be withdrawn.`,
247
+ }[p.action];
248
+ });
249
+ const confirmButton = computed(
250
+ () => ({ approve: "Approve", reject: "Reject", cancel: "Cancel request" })[pending.value?.action ?? "approve"]
251
+ );
252
+
253
+ async function confirm() {
254
+ const p = pending.value;
255
+ if (!p) return;
256
+ working.value = true;
257
+ actionError.value = "";
258
+ try {
259
+ if (p.action === "approve") await approveJoinRequest(p.item._id, props.org);
260
+ else if (p.action === "reject") await rejectJoinRequest(p.item._id, props.org, reason.value);
261
+ else await cancelJoinRequest(p.item._id, props.org);
262
+ confirmOpen.value = false;
263
+ await load();
264
+ } catch (err: any) {
265
+ actionError.value = err?.data?.message || "That did not work. Please try again.";
266
+ } finally {
267
+ working.value = false;
268
+ }
269
+ }
270
+
271
+ watch([box, status], () => {
272
+ page.value = 1;
273
+ load();
274
+ });
275
+ onMounted(load);
276
+ </script>
277
+
278
+ <style scoped>
279
+ .site-access :deep(.screen-card-title) {
280
+ display: block;
281
+ line-height: 1.35;
282
+ }
283
+
284
+ .site-access__meta,
285
+ .site-access__body {
286
+ font-size: var(--fs-cell);
287
+ }
288
+ </style>
@@ -1,3 +1,5 @@
1
+ import type { TSiteJoinRequest, TSiteJoinRequestStatus, TSiteNameMatch } from "../utils/site-join-request";
2
+
1
3
  export default function useCustomerSite() {
2
4
  function add(payload: TCustomerSite) {
3
5
  return useNuxtApp().$api<Record<string, any>>("/api/customer-sites", {
@@ -110,7 +112,55 @@ async function deleteById(id: string) {
110
112
  return useNuxtApp().$api<Record<string, any>>(`/api/customer-sites/provider-changes/${id}/cancel`, { method: "POST" });
111
113
  }
112
114
 
115
+ // Site already exists under another company -> ask its managing agent for
116
+ // access (spec 2026-11-16-site-exists-ma-approval). Types: utils/site-join-request.ts.
117
+ function checkSiteName(org: string, name: string) {
118
+ return useNuxtApp().$api<{ matches: TSiteNameMatch[] }>("/api/customer-sites/name-check", {
119
+ method: "GET",
120
+ query: { org, name },
121
+ });
122
+ }
123
+ function createJoinRequest(org: string, site: string, note?: string) {
124
+ return useNuxtApp().$api<TSiteJoinRequest>("/api/customer-sites/join-requests", {
125
+ method: "POST",
126
+ body: { org, site, ...(note?.trim() ? { note: note.trim() } : {}) },
127
+ });
128
+ }
129
+ function getJoinRequests(
130
+ org: string,
131
+ query: { box: "incoming" | "outgoing"; status?: TSiteJoinRequestStatus; page?: number; limit?: number }
132
+ ) {
133
+ return useNuxtApp().$api<{ items: TSiteJoinRequest[]; total: number; page: number; limit: number; canApprove?: boolean }>(
134
+ "/api/customer-sites/join-requests",
135
+ { method: "GET", query: { org, ...query } }
136
+ );
137
+ }
138
+ function approveJoinRequest(id: string, org: string) {
139
+ return useNuxtApp().$api<TSiteJoinRequest>(`/api/customer-sites/join-requests/${id}/approve`, {
140
+ method: "PUT",
141
+ body: { org },
142
+ });
143
+ }
144
+ function rejectJoinRequest(id: string, org: string, reason?: string) {
145
+ return useNuxtApp().$api<TSiteJoinRequest>(`/api/customer-sites/join-requests/${id}/reject`, {
146
+ method: "PUT",
147
+ body: { org, ...(reason?.trim() ? { reason: reason.trim() } : {}) },
148
+ });
149
+ }
150
+ function cancelJoinRequest(id: string, org: string) {
151
+ return useNuxtApp().$api<TSiteJoinRequest>(`/api/customer-sites/join-requests/${id}/cancel`, {
152
+ method: "PUT",
153
+ body: { org },
154
+ });
155
+ }
156
+
113
157
  return {
158
+ checkSiteName,
159
+ createJoinRequest,
160
+ getJoinRequests,
161
+ approveJoinRequest,
162
+ rejectJoinRequest,
163
+ cancelJoinRequest,
114
164
  previewProviderChange,
115
165
  applyProviderChange,
116
166
  listProviderChanges,
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.183.0",
5
+ "version": "4.184.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.",
@@ -1,6 +1,19 @@
1
- /** The one block label used everywhere: "Blk 3", "Blk 12A". Block names are no longer typed; they come from the number. */
1
+ /** The default block label: "Blk 3", "Blk 12A" - used as the block's name when no name is typed. */
2
2
  export const blockLabel = (block: number | string | null | undefined): string => `Blk ${block}`;
3
3
 
4
+ /** The name a block is saved with: what was typed (e.g. "Barbeque Pit"), or "Blk N" when left empty. */
5
+ export function blockNameFor(block: number | string | null | undefined, typed?: string | null): string {
6
+ return String(typed ?? "").trim() || blockLabel(block);
7
+ }
8
+
9
+ /** How a block shows in lists: "Blk 7", or "Blk 7 - Barbeque Pit" when it has its own name. */
10
+ export function blockDisplay(block: number | string | null | undefined, name?: string | null): string {
11
+ if (block === null || block === undefined || block === "") return String(name ?? "").trim();
12
+ const label = blockLabel(block);
13
+ const own = String(name ?? "").trim();
14
+ return own && own.toLowerCase() !== label.toLowerCase() ? `${label} - ${own}` : label;
15
+ }
16
+
4
17
  export const BLOCK_NO_MESSAGE = "Block No must be a number from 1 to 9999, optionally followed by one letter (for example 12 or 12A).";
5
18
 
6
19
  /**
@@ -0,0 +1,162 @@
1
+ /**
2
+ * "This site already exists" + access requests to the site's managing agent
3
+ * (spec 2026-11-16-site-exists-ma-approval). Pure helpers for the Add Site
4
+ * form and the Access requests list, so the wording and the rules are tested
5
+ * once here instead of living inside the components.
6
+ */
7
+
8
+ /** One row of GET /api/customer-sites/name-check. */
9
+ export type TSiteNameMatch = {
10
+ site: string;
11
+ name: string;
12
+ match: "duplicate" | "near-duplicate";
13
+ sameOrg: boolean;
14
+ managedBy: string[];
15
+ linked: boolean;
16
+ pendingRequest: string | null;
17
+ };
18
+
19
+ export type TSiteJoinRequestStatus = "pending" | "approved" | "rejected" | "cancelled";
20
+
21
+ /** A `site.join-requests` document as the API returns it. */
22
+ export type TSiteJoinRequest = {
23
+ _id: string;
24
+ site: string;
25
+ siteName: string;
26
+ siteOrg?: string;
27
+ requesterOrg: string;
28
+ requesterOrgName?: string;
29
+ requestedBy?: string | { _id?: string; name?: string; email?: string };
30
+ requestedByName?: string;
31
+ approverOrgs?: string[];
32
+ status: TSiteJoinRequestStatus;
33
+ note?: string;
34
+ reason?: string;
35
+ decidedAt?: string | null;
36
+ createdAt?: string;
37
+ };
38
+
39
+ /**
40
+ * What the form does with one match:
41
+ * - `same-org`: one of our own sites - the server's existing message still decides.
42
+ * - `linked`: another company's site we already serve - nothing to request.
43
+ * - `pending`: we already asked; waiting for the managing agent.
44
+ * - `requestable`: same site, another company - Save is blocked, ask for access.
45
+ * - `near`: similar name only - a warning, Save stays allowed.
46
+ */
47
+ export type TSiteMatchState = "same-org" | "linked" | "pending" | "requestable" | "near";
48
+
49
+ export const SITE_NAME_CHECK_MIN = 3;
50
+
51
+ export function shouldCheckSiteName(name?: string | null): boolean {
52
+ return String(name ?? "").trim().length >= SITE_NAME_CHECK_MIN;
53
+ }
54
+
55
+ export function siteMatchState(m: TSiteNameMatch): TSiteMatchState {
56
+ if (m.sameOrg) return "same-org";
57
+ if (m.match !== "duplicate") return "near";
58
+ if (m.linked) return "linked";
59
+ if (m.pendingRequest) return "pending";
60
+ return "requestable";
61
+ }
62
+
63
+ export function managedByText(managedBy?: string[] | null): string {
64
+ const names = (managedBy ?? []).map((n) => String(n ?? "").trim()).filter(Boolean);
65
+ return names.length ? names.join(", ") : "another company";
66
+ }
67
+
68
+ /** "<name> - managed by X" - one line per match in the alert. */
69
+ export function siteMatchLabel(m: TSiteNameMatch): string {
70
+ if (m.sameOrg) return `${m.name} - already one of your sites`;
71
+ return `${m.name} - managed by ${managedByText(m.managedBy)}`;
72
+ }
73
+
74
+ /** The match that stops Save: the same site already run by another company. */
75
+ export function blockingSiteMatch(matches?: TSiteNameMatch[] | null): TSiteNameMatch | null {
76
+ return (matches ?? []).find((m) => !m.sameOrg && m.match === "duplicate") ?? null;
77
+ }
78
+
79
+ export function hasNearSiteMatch(matches?: TSiteNameMatch[] | null): boolean {
80
+ return (matches ?? []).some((m) => siteMatchState(m) === "near");
81
+ }
82
+
83
+ /** Plain sentence under the matches for the blocking match, by state. */
84
+ export function siteMatchMessage(m: TSiteNameMatch): string {
85
+ switch (siteMatchState(m)) {
86
+ case "linked":
87
+ return `Already linked - your company already serves ${m.name}. You can find it on your Sites list.`;
88
+ case "pending":
89
+ return `Request pending - you have already asked ${managedByText(m.managedBy)} for access. You will be notified when they answer.`;
90
+ case "requestable":
91
+ return `${m.name} is already set up by ${managedByText(m.managedBy)}. Instead of adding it again, ask them to give your company access.`;
92
+ case "near":
93
+ return "A site with a similar name already exists. If this is a different property, you can carry on.";
94
+ default:
95
+ return "";
96
+ }
97
+ }
98
+
99
+ /**
100
+ * A 409 `{ code: "SITE_EXISTS" }` from Save (someone created the site while
101
+ * the form was open) turned into the same match the name-check gives, so the
102
+ * form shows the same "Request access" offer. Anything else -> null.
103
+ */
104
+ export function siteExistsFromError(err: any): TSiteNameMatch | null {
105
+ const data = err?.data ?? err?.response?._data;
106
+ if (!data || data.code !== "SITE_EXISTS" || !data.site) return null;
107
+ return {
108
+ site: String(data.site),
109
+ name: String(data.name ?? ""),
110
+ match: "duplicate",
111
+ sameOrg: false,
112
+ managedBy: Array.isArray(data.managedBy) ? data.managedBy.map(String) : [],
113
+ linked: false,
114
+ pendingRequest: null,
115
+ };
116
+ }
117
+
118
+ const STATUS_LABELS: Record<TSiteJoinRequestStatus, string> = {
119
+ pending: "Pending",
120
+ approved: "Approved",
121
+ rejected: "Rejected",
122
+ cancelled: "Cancelled",
123
+ };
124
+
125
+ export function joinRequestStatusLabel(status?: string | null): string {
126
+ return STATUS_LABELS[status as TSiteJoinRequestStatus] ?? "Unknown";
127
+ }
128
+
129
+ /** Who asked: a populated user, a name field, or nothing. */
130
+ export function joinRequestRequester(r: Pick<TSiteJoinRequest, "requestedBy" | "requestedByName">): string {
131
+ if (r.requestedByName) return r.requestedByName;
132
+ const by = r.requestedBy;
133
+ if (by && typeof by === "object") return by.name || by.email || "";
134
+ return "";
135
+ }
136
+
137
+ /** One sentence per card saying where the request stands. */
138
+ export function joinRequestStateLine(r: TSiteJoinRequest, box: "incoming" | "outgoing"): string {
139
+ const who = r.requesterOrgName || "This company";
140
+ if (box === "incoming") {
141
+ switch (r.status) {
142
+ case "pending":
143
+ return `${who} asks to be linked to ${r.siteName}. Approving adds the site to their Sites list; they will not see your other sites.`;
144
+ case "approved":
145
+ return `Approved - ${who} now has ${r.siteName} on their Sites list.`;
146
+ case "rejected":
147
+ return `Rejected - ${who} was told${r.reason ? `: "${r.reason}"` : "."}`;
148
+ default:
149
+ return `${who} cancelled this request.`;
150
+ }
151
+ }
152
+ switch (r.status) {
153
+ case "pending":
154
+ return `Waiting for the managing agent of ${r.siteName} to answer. You will be notified.`;
155
+ case "approved":
156
+ return `Approved - ${r.siteName} is now on your Sites list.`;
157
+ case "rejected":
158
+ return `The managing agent declined this request${r.reason ? `: "${r.reason}"` : "."}`;
159
+ default:
160
+ return "You cancelled this request.";
161
+ }
162
+ }
@@ -391,6 +391,18 @@ function plateSizeMm(plate: string, boxW: number, max = 4.6): number {
391
391
  return Math.round(Math.min(max, (boxW / Math.max(plate.length, 1) - 0.3) / 0.74) * 100) / 100;
392
392
  }
393
393
 
394
+ /**
395
+ * Plate size inside a shape's tag. With the serial printed under it (a blank
396
+ * sticker's two-line code + its number), the plate shrinks so both fit the tag:
397
+ * lines at 1.1 x size, the serial row 1.2 x 5.8 pt, 0.6 mm between.
398
+ */
399
+ export function tagPlateSizeMm(longest: string, tag: { w: number; h: number }, lines: number, withSerial: boolean, k = 1): number {
400
+ const size = plateSizeMm(longest, tag.w, 4.6 * k);
401
+ if (!withSerial || !lines) return size;
402
+ const room = (tag.h - 1.2 * 5.8 * PT - 0.6) / (1.1 * lines);
403
+ return Math.round(Math.max(0.5, Math.min(size, room)) * 100) / 100;
404
+ }
405
+
394
406
  /**
395
407
  * One full HTML document: A4 sheets of stickers. `faceSvgs` is parallel to
396
408
  * `items` (each sticker's frame + QR, already drawn for the chosen design).
@@ -425,14 +437,14 @@ function cardHtml(item: StickerItem, face: string, c: CardContext): string {
425
437
  const longest = lines.reduce((a, l) => (l.length > a.length ? l : a), "");
426
438
  // a two-line code has no room for the words under it inside the tag
427
439
  const label = c.label && !(c.tag && lines.length > 1) ? `<div class="hint">${escapeHtml(c.label)}</div>` : "";
428
- // the serial takes the words' place inside a shape's tag (no room for both)
440
+ // the serial takes the words' place inside a shape's tag; a two-line blank code shrinks to make room for it
429
441
  const serial = serialText ? `<div class="serial">${escapeHtml(serialText)}</div>` : "";
430
- const tagWords = serial && c.tag ? (lines.length > 1 ? "" : serial) : label;
442
+ const tagWords = serial && c.tag ? serial : label;
431
443
  const words = c.shaped && !c.tag
432
444
  ? ""
433
445
  : c.tag
434
446
  ? `<div class="words band" style="left:${c.tag.x}mm;right:auto;top:${c.tag.y}mm;width:${c.tag.w}mm;height:${c.tag.h}mm">` +
435
- (lines.length ? `<div class="plate" style="font-size:${plateSizeMm(longest, c.tag.w, 4.6 * c.k)}mm">${plate}</div>` : "") +
447
+ (lines.length ? `<div class="plate" style="font-size:${tagPlateSizeMm(longest, c.tag, lines.length, !!serial && lines.length > 1, c.k)}mm">${plate}</div>` : "") +
436
448
  tagWords +
437
449
  `</div>`
438
450
  : `<div class="words" style="top:${c.wordsTop}mm${!lines.length && !label ? ";justify-content:center" : ""}">` +
@@ -457,9 +469,8 @@ export function buildStickerDocument(
457
469
  const design = opts.design ?? DEFAULT_STICKER_DESIGN;
458
470
  const n = opts.modules ?? STICKER_QR_MODULES;
459
471
  const c = cardContext(design, opts.siteName, n);
460
- // the strip carries the number when chosen - and when the sticker has no room for it
461
- // (a bare shape, or a two-line blank code filling a shape's tag)
462
- const noRoom = (item: StickerItem) => (c.shaped && !c.tag) || (!!c.tag && shownPlateLines(item, c.hidePlate).length > 1);
472
+ // the strip carries the number when chosen - and when the sticker has no words at all (a bare shape)
473
+ const noRoom = (_item: StickerItem) => c.shaped && !c.tag;
463
474
  const stripSerial = (item: StickerItem) => design.serial === "strip" || design.serial === "both" || (c.serial && noRoom(item));
464
475
  const cells = items.map((item, i) => {
465
476
  const { place, owner } = installerLine(item);
@@ -500,7 +511,7 @@ function cardWordsSvg(item: StickerItem, c: CardContext): string {
500
511
  const longest = lines.reduce((a, l) => (l.length > a.length ? l : a), "");
501
512
  const box = c.tag ?? { x: 3, y: c.wordsTop, w: c.cardW - 6, h: c.layout.cardH - 2 - c.wordsTop };
502
513
  const plateSize = c.tag
503
- ? plateSizeMm(longest, c.tag.w, 4.6 * c.k)
514
+ ? tagPlateSizeMm(longest, c.tag, lines.length, !!serialText && lines.length > 1, c.k)
504
515
  : lines.length > 1 ? plateSizeMm(longest, c.cardW - 6, 4.6) : 13 * PT;
505
516
  const small = 5.8 * PT;
506
517
  type Row = { h: number; draw: (top: number) => string };
@@ -519,7 +530,7 @@ function cardWordsSvg(item: StickerItem, c: CardContext): string {
519
530
  });
520
531
  const label = c.label && !(c.tag && lines.length > 1) ? c.label : "";
521
532
  if (c.tag) {
522
- if (serialText && lines.length === 1) rows.push(word(serialText, true));
533
+ if (serialText) rows.push(word(serialText, true));
523
534
  else if (!serialText && label) rows.push(word(label, false));
524
535
  } else {
525
536
  if (serialText) rows.push(word(serialText, true));