@7365admin1/layer-common 4.97.1-staging.694 → 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>
@@ -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.97.1-staging.694",
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
+ }