@7365admin1/layer-common 4.97.1-staging.693 → 4.97.1-staging.695

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.
@@ -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>
@@ -27,9 +27,21 @@
27
27
  <p v-if="blankSummary" class="text-body-2 font-weight-medium mb-3" data-test="vehicle-qr-blank-summary">
28
28
  {{ blankSummaryText(blankSummary) }}
29
29
  </p>
30
- <v-text-field v-model.number="blankQty" type="number" :min="1" :max="BLANK_MAX_COUNT" label="How many stickers?"
31
- density="compact" variant="outlined" style="max-width: 240px" :hint="`1 to ${BLANK_MAX_COUNT} at a time`"
32
- persistent-hint data-test="vehicle-qr-blank-count" />
30
+ <v-radio-group v-model="blankKind" inline density="compact" hide-details class="mb-3" data-test="vehicle-qr-blank-kind">
31
+ <v-radio value="new" label="Make new stickers" data-test="vehicle-qr-blank-kind-new" />
32
+ <v-radio value="saved" label="Reprint saved stickers (not linked yet)" :disabled="!blankSummary?.available"
33
+ data-test="vehicle-qr-blank-kind-saved" />
34
+ </v-radio-group>
35
+ <v-text-field v-if="blankKind === 'new'" v-model.number="blankQty" type="number" :min="1" :max="BLANK_MAX_COUNT"
36
+ label="How many stickers?" density="compact" variant="outlined" style="max-width: 240px"
37
+ :hint="`1 to ${BLANK_MAX_COUNT} at a time`" persistent-hint data-test="vehicle-qr-blank-count" />
38
+ <template v-else>
39
+ <v-text-field v-model="savedSearch" label="Sticker number or code (optional)" density="compact" variant="outlined"
40
+ style="max-width: 360px" clearable persistent-hint
41
+ hint="Leave empty to see every saved sticker; untick the ones you do not need on the next step."
42
+ data-test="vehicle-qr-blank-saved-search" />
43
+ <p class="text-caption text-medium-emphasis mt-2 mb-0">{{ BLANK_LIST_NOTE }}</p>
44
+ </template>
33
45
  </div>
34
46
  <div v-if="mode === 'vehicles'" class="d-flex flex-wrap align-center ga-2 mb-2">
35
47
  <v-checkbox-btn :model-value="allOnPageTicked" :indeterminate="someOnPageTicked && !allOnPageTicked"
@@ -72,7 +84,8 @@
72
84
  {{ missing.length }} vehicle(s) could not be found and were skipped.
73
85
  </v-alert>
74
86
  <v-alert v-if="dropped" type="info" variant="tonal" density="compact" class="mb-3">
75
- {{ dropped }} more vehicle(s) were over the {{ STICKER_MAX_PER_REQUEST }} limit - print again for the rest.
87
+ <template v-if="isBlank">{{ dropped }} more saved sticker(s) were over the {{ SAVED_REPRINT_MAX }} limit - search by sticker number to print the rest.</template>
88
+ <template v-else>{{ dropped }} more vehicle(s) were over the {{ STICKER_MAX_PER_REQUEST }} limit - print again for the rest.</template>
76
89
  </v-alert>
77
90
  <v-table density="compact" fixed-header height="220">
78
91
  <thead>
@@ -84,7 +97,7 @@
84
97
  <td><v-checkbox-btn :model-value="ticked.includes(it.vehicleId)" :aria-label="`Print ${it.plateNumber}`"
85
98
  @update:model-value="(v: any) => (ticked = setIds(ticked, [it.vehicleId], !!v))" /></td>
86
99
  <template v-if="isBlank">
87
- <td class="font-weight-bold">{{ it.plateNumber }}</td>
100
+ <td class="font-weight-bold">{{ blankRowLabel(it) }}</td>
88
101
  <td class="text-medium-emphasis">{{ BLANK_STRIP_NOTE }}</td>
89
102
  </template>
90
103
  <template v-else>
@@ -210,8 +223,10 @@
210
223
  <v-spacer />
211
224
  <v-btn variant="text" class="text-none" @click="close(false)">Cancel</v-btn>
212
225
  <v-btn v-if="step === 'select'" color="primary" variant="flat" class="text-none"
213
- :disabled="mode === 'blank' ? !blankCount(blankQty) : !selected.length" :loading="loading" @click="goReview">
214
- <template v-if="mode === 'blank'">Preview {{ blankCount(blankQty) }} blank sticker{{ blankCount(blankQty) === 1 ? "" : "s" }}</template>
226
+ :disabled="mode === 'blank' ? (blankKind === 'new' ? !blankCount(blankQty) : !blankSummary?.available) : !selected.length"
227
+ :loading="loading" @click="goReview">
228
+ <template v-if="mode === 'blank' && blankKind === 'saved'">Show saved stickers</template>
229
+ <template v-else-if="mode === 'blank'">Preview {{ blankCount(blankQty) }} blank sticker{{ blankCount(blankQty) === 1 ? "" : "s" }}</template>
215
230
  <template v-else>Preview {{ selected.length }} sticker{{ selected.length === 1 ? "" : "s" }}</template>
216
231
  </v-btn>
217
232
  <template v-if="step === 'review'">
@@ -245,7 +260,7 @@
245
260
  <script lang="ts" setup>
246
261
  import QRCode from "qrcode";
247
262
  import useVehicle from "../composables/useVehicle";
248
- import { BLANK_DEFAULT_COUNT, BLANK_MAX_COUNT, BLANK_STRIP_NOTE, STICKER_NEW_NOTE, STICKER_SAME_NOTE, blankCount, blankStickerItems, blankSummaryText, reprintItems, type BlankSummary } from "../utils/vehicle-qr-blank";
263
+ import { BLANK_DEFAULT_COUNT, BLANK_LIST_NOTE, BLANK_MAX_COUNT, BLANK_STRIP_NOTE, SAVED_REPRINT_MAX, blankRowLabel, savedBlankItems, STICKER_NEW_NOTE, STICKER_SAME_NOTE, blankCount, blankStickerItems, blankSummaryText, reprintItems, type BlankSummary } from "../utils/vehicle-qr-blank";
249
264
  import { errorConverter } from "../utils/data";
250
265
  import { saveFile, stickerBundleName, stickerFileNames, svgToImage, zipFiles, type ImageFormat } from "../utils/vehicle-qr-export";
251
266
  import {
@@ -313,6 +328,9 @@ async function loadBlankSummary() {
313
328
  // "vehicles" = stickers for chosen vehicles; "blank" = codes made in advance, linked to a vehicle later.
314
329
  const mode = ref<"vehicles" | "blank">("vehicles");
315
330
  const blankQty = ref<number | string>(BLANK_DEFAULT_COUNT);
331
+ // "new" = generate a fresh batch; "saved" = print again stickers already made and not linked yet.
332
+ const blankKind = ref<"new" | "saved">("new");
333
+ const savedSearch = ref("");
316
334
  const isBlank = ref(false); // the mode the shown review was made in
317
335
 
318
336
  const step = ref<"select" | "review">("select");
@@ -428,6 +446,8 @@ watch(
428
446
  docHtml.value = "";
429
447
  step.value = "select";
430
448
  mode.value = "vehicles";
449
+ blankKind.value = "new";
450
+ savedSearch.value = "";
431
451
  isBlank.value = false;
432
452
  plates.value = stickerPlateRows(props.rows);
433
453
  selected.value = defaultPlateIds(plates.value);
@@ -466,6 +486,31 @@ async function goReview() {
466
486
  loading.value = true;
467
487
  error.value = "";
468
488
  try {
489
+ if (mode.value === "blank" && blankKind.value === "saved" && !props.vehicleIds.length) {
490
+ const found: Array<Record<string, any>> = [];
491
+ let page = 1;
492
+ let total = 0;
493
+ let name = "";
494
+ do {
495
+ const res = await getAvailableBlankVehicleQr(props.site, { search: savedSearch.value || "", page, limit: 100 });
496
+ found.push(...(res?.items ?? []));
497
+ total = res?.total ?? 0;
498
+ name = String(res?.site?.name ?? name);
499
+ page += 1;
500
+ } while (found.length < total && found.length < SAVED_REPRINT_MAX);
501
+ items.value = savedBlankItems(found);
502
+ if (!items.value.length) {
503
+ error.value = savedSearch.value ? "No saved sticker matches that number or code." : "No saved stickers to reprint.";
504
+ return;
505
+ }
506
+ siteName.value = name;
507
+ missing.value = [];
508
+ dropped.value = Math.max(total - found.length, 0);
509
+ ticked.value = items.value.map((i) => i.vehicleId);
510
+ isBlank.value = true;
511
+ step.value = "review";
512
+ return;
513
+ }
469
514
  if (mode.value === "blank" && !props.vehicleIds.length) {
470
515
  const blank = await getBlankVehicleQrStickers(props.site, blankCount(blankQty.value));
471
516
  items.value = blankStickerItems(blank?.items ?? []);
@@ -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,
@@ -329,13 +329,15 @@ function getSpecificVehicleById(id: string){
329
329
  }
330
330
 
331
331
  // Blank codes saved when printed and still free to link, plus {printed, linked, available}.
332
+ // `search` matches the code or the sticker number; `qr` lets a saved sticker be printed again.
332
333
  function getAvailableBlankVehicleQr(site: string, query: { search?: string; page?: number; limit?: number } = {}) {
333
334
  return useNuxtApp().$api<{
335
+ site?: { _id: string; name: string };
334
336
  summary: { printed: number; linked: number; available: number };
335
337
  total: number;
336
338
  page: number;
337
339
  limit: number;
338
- items: Array<{ token: string; code: string }>;
340
+ items: Array<{ token: string; code: string; qr?: string; serialNo?: number | null; serialLabel?: string | null }>;
339
341
  }>(`/api/vehicles/qr/blank-stickers/site/${site}`, { query });
340
342
  }
341
343
 
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.97.1-staging.693",
5
+ "version": "4.97.1-staging.695",
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.",
@@ -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
+ }
@@ -28,6 +28,23 @@ export function blankStickerItems(items: BlankItem[]): StickerItem[] {
28
28
  return items.map((i) => ({ vehicleId: i.token, qr: i.qr, token: i.token, plateNumber: i.code, status: "active", blank: true, ...(i.serialNo ? { serialNo: i.serialNo, serialLabel: i.serialLabel ?? null } : {}) }));
29
29
  }
30
30
 
31
+ /** Most saved stickers one reprint loads (the list endpoint pages 100 at a time). */
32
+ export const SAVED_REPRINT_MAX = BLANK_MAX_COUNT;
33
+
34
+ /** Saved (unlinked) blank stickers as printable items; a row the server sent without its QR is skipped. */
35
+ export function savedBlankItems(items: Array<Partial<BlankItem> & { serialNo?: number | null }>): StickerItem[] {
36
+ return blankStickerItems(
37
+ items
38
+ .filter((i): i is BlankItem => !!i?.token && !!i?.qr && !!i?.code)
39
+ .map((i) => ({ token: i.token, qr: i.qr, code: i.code, ...(i.serialNo ? { serialNo: i.serialNo, serialLabel: i.serialLabel ?? null } : {}) })),
40
+ );
41
+ }
42
+
43
+ /** The reprint list's code cell: "TLR001 - ABCD-..." when the sticker has a number. */
44
+ export function blankRowLabel(item: { plateNumber?: string; serialLabel?: string | null }): string {
45
+ return item.serialLabel ? `${item.serialLabel} - ${item.plateNumber ?? ""}` : String(item.plateNumber ?? "");
46
+ }
47
+
31
48
  /**
32
49
  * The token a sticker's QR carries: older stickers hold "S365V:<token>", newer
33
50
  * ones a link ".../q/<token>" (a phone camera opens a "no data" page).