@7365admin1/layer-common 4.35.1-staging.448 → 4.35.1-staging.450

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.
@@ -119,7 +119,7 @@
119
119
  <v-window-item v-if="ctl.tabs.people" value="technicians">
120
120
  <InventoryTechniciansTab :store="store" @changed="refreshCounts" />
121
121
  </v-window-item>
122
- <v-window-item v-if="ctl.tabs.reports" value="reports">
122
+ <v-window-item v-if="ctl.tabs.reports || companyUsage" value="reports">
123
123
  <InventoryReportsTab :store="store" :sites="storeSites" />
124
124
  </v-window-item>
125
125
  <v-window-item v-if="ctl.tabs.suppliers" value="suppliers">
@@ -150,7 +150,7 @@ const props = defineProps({
150
150
 
151
151
  const movedFromEquipment = useRoute().query.moved === "equipment";
152
152
 
153
- const { getStores, createStore: apiCreateStore, getRequests } = useInventory();
153
+ const { getStores, createStore: apiCreateStore, getRequests, getReport } = useInventory();
154
154
  const { getSites } = useSite();
155
155
  const { requiredRule } = useUtils();
156
156
 
@@ -216,6 +216,7 @@ const tabs = computed(() => {
216
216
  ...(ctl.value.tabs.requests ? [{ value: "requests", label: a.canApprove ? "Requests" : "My Requests", badge: a.canApprove ? pendingCount.value : 0 }] : []),
217
217
  ...(ctl.value.tabs.people ? [{ value: "technicians", label: worker.many }] : []),
218
218
  ...(ctl.value.tabs.reports ? [{ value: "reports", label: a.canReports ? "Reports" : "Usage check" }] : []),
219
+ ...(!ctl.value.tabs.reports && companyUsage.value ? [{ value: "reports", label: "Company usage" }] : []),
219
220
  ...(ctl.value.tabs.suppliers ? [{ value: "suppliers", label: "Suppliers" }] : []),
220
221
  ...(ctl.value.tabs.settings ? [{ value: "settings", label: "Settings" }] : []),
221
222
  ];
@@ -239,6 +240,25 @@ async function loadStores() {
239
240
  refreshCounts();
240
241
  }
241
242
 
243
+ /**
244
+ * Another company's supervisor at the main store may track its OWN people's usage (the API answers the usage
245
+ * report for them, scoped). The store's access flags do not say so, so ask once per store.
246
+ * ponytail: one probe request per store switch; add a flag to the store's access if the API grows one.
247
+ */
248
+ const companyUsage = ref(false);
249
+ async function probeCompanyUsage() {
250
+ companyUsage.value = false;
251
+ const s = store.value;
252
+ if (!s || ctl.value.tabs.reports || !s.main || s.owner !== false) return;
253
+ const now = new Date().toISOString();
254
+ try {
255
+ await getReport(s._id, "usage", { from: now, to: now });
256
+ companyUsage.value = true;
257
+ } catch {
258
+ companyUsage.value = false;
259
+ }
260
+ }
261
+
242
262
  async function refreshCounts() {
243
263
  if (!store.value?.access.canApprove) return (pendingCount.value = 0);
244
264
  try {
@@ -277,6 +297,7 @@ async function createStore() {
277
297
  watch(storeId, () => {
278
298
  tab.value = "stock";
279
299
  refreshCounts();
300
+ probeCompanyUsage();
280
301
  });
281
302
  watch(() => props.siteId, loadStores);
282
303
 
@@ -22,6 +22,25 @@
22
22
  <v-btn class="text-none" variant="text" size="small" :loading="acting === h._id + 'c'" @click="cancelHandover(h)">Cancel</v-btn>
23
23
  </AppCard>
24
24
 
25
+ <!-- Usage drafts: before photo saved, job not finished yet. Nothing is taken off the stock until submitted. -->
26
+ <template v-if="drafts.length">
27
+ <div class="text-subtitle-2 mb-2">My drafts — in progress ({{ drafts.length }})</div>
28
+ <AppCard
29
+ v-for="d in drafts"
30
+ :key="d._id"
31
+ class="pa-3 mb-2 d-flex flex-wrap align-center ga-3"
32
+ :style="{ borderLeft: `4px solid rgb(var(--v-theme-${d.stale ? 'error' : 'info'}))` }"
33
+ >
34
+ <InventoryPhotoThumbs :photos="{ before: d.photos?.before ?? [] }" :before-at="d.photosBeforeAt" :size="44" />
35
+ <div class="flex-grow-1" style="min-width: 200px">
36
+ <div class="font-weight-medium">{{ d.itemName }} × {{ d.qty }} {{ d.unit }}<span v-if="d.reference" class="text-medium-emphasis"> · {{ d.reference }}</span></div>
37
+ <div class="text-body-2">{{ draftCardText(d, standardFormatDateTime, staleDays).line }}</div>
38
+ <div v-if="d.stale" class="text-caption text-error">{{ draftCardText(d, standardFormatDateTime, staleDays).warning }}</div>
39
+ </div>
40
+ <v-btn class="text-none screen-btn-primary" variant="flat" size="small" @click="continueDraft(d)">{{ d.photos?.after?.length ? "Review and submit" : "Add after photo" }}</v-btn>
41
+ </AppCard>
42
+ </template>
43
+
25
44
  <v-progress-linear v-if="loading" indeterminate color="primary" />
26
45
  <AppCard v-else-if="!holdings.length" class="pa-6 text-center">
27
46
  <div class="text-body-1 mb-1">You are not holding any stock.</div>
@@ -38,16 +57,22 @@
38
57
  <div class="flex-grow-1">
39
58
  <div class="font-weight-medium">{{ h.itemName }}</div>
40
59
  <div class="text-body-2">{{ h.qty }} {{ h.unit }} left · {{ h.usedThisMonth ?? 0 }} used this month</div>
60
+ <div v-if="h.inDrafts" class="text-caption text-medium-emphasis">{{ h.inDrafts }} in drafts · {{ h.free ?? 0 }} free to use</div>
41
61
  </div>
42
62
  <div class="d-flex flex-column ga-1">
43
- <v-btn v-if="h.qty > 0 && ctl.recordUsage" class="text-none screen-btn-primary" variant="flat" size="small" @click="use(h)">Record usage</v-btn>
63
+ <v-btn v-if="(h.free ?? h.qty) > 0 && ctl.recordUsage" class="text-none screen-btn-primary" variant="flat" size="small" @click="use(h)">Record usage</v-btn>
44
64
  <v-btn v-if="h.qty > 0" class="text-none screen-btn-ghost" variant="outlined" size="small" @click="openGive(h)">Give to colleague</v-btn>
65
+ <v-btn class="text-none" variant="text" size="small" prepend-icon="mdi-history" @click="openHistory(h)">History</v-btn>
45
66
  </div>
46
67
  </AppCard>
47
68
  </v-col>
48
69
  </v-row>
49
70
 
50
- <div class="text-subtitle-2 mt-6 mb-2">My recent activity</div>
71
+ <div class="d-flex align-center mt-6 mb-2">
72
+ <div class="text-subtitle-2">My recent activity</div>
73
+ <v-spacer />
74
+ <v-btn class="text-none" variant="text" size="small" prepend-icon="mdi-map-marker-check-outline" @click="openMyUsage">My usage — where I used my stock</v-btn>
75
+ </div>
51
76
  <v-table density="compact">
52
77
  <thead>
53
78
  <tr>
@@ -76,7 +101,8 @@
76
101
  </tbody>
77
102
  </v-table>
78
103
 
79
- <InventoryUsageDialog v-model="usage.show" :store="store" :site-id="siteId" :holding="usage.holding" :sites="sites" @done="changed" />
104
+ <InventoryUsageDialog v-model="usage.show" :store="store" :site-id="siteId" :holding="usage.holding" :draft="usage.draft" :sites="sites" @done="changed" />
105
+ <InventoryHistoryDialog v-model="history.show" :store="store" :holder="me" :item="history.item" :title="history.title" :usage-only="history.usageOnly" />
80
106
  <v-dialog v-model="give.show" max-width="520" persistent>
81
107
  <v-card class="screen-modal">
82
108
  <v-card-title class="d-flex align-center">
@@ -135,6 +161,7 @@ import useFile from "../composables/useFile";
135
161
  import useUtils from "../composables/useUtils";
136
162
  import useLocalAuth from "../composables/useLocalAuth";
137
163
  import { inventoryControls } from "../utils/inventory-presets";
164
+ import { draftCardText } from "../utils/inventory-usage";
138
165
 
139
166
  const props = defineProps({
140
167
  store: { type: Object as PropType<TInventoryStore>, required: true },
@@ -147,14 +174,41 @@ const emit = defineEmits(["changed"]);
147
174
  const api = useInventory();
148
175
  const { typeLabels } = api;
149
176
  const { getFileUrl } = useFile();
150
- const { standardFormatDate } = useUtils();
177
+ const { standardFormatDate, standardFormatDateTime } = useUtils();
151
178
  const { currentUser } = useLocalAuth();
152
179
 
153
180
  const holdings = ref<TInventoryHolding[]>([]);
154
181
  const activity = ref<TInventoryTransaction[]>([]);
155
182
  const loading = ref(false);
156
183
  const showRequest = ref(false);
157
- const usage = reactive({ show: false, holding: null as TInventoryHolding | null });
184
+ const usage = reactive({ show: false, holding: null as TInventoryHolding | null, draft: null as TInventoryUsageDraft | null });
185
+ const drafts = ref<TInventoryUsageDraft[]>([]);
186
+ const staleDays = ref(3);
187
+ const history = reactive({ show: false, item: "", title: "", usageOnly: false });
188
+
189
+ function openHistory(h: TInventoryHolding) {
190
+ Object.assign(history, { show: true, item: String(h.item), title: `History — ${h.itemName}`, usageOnly: false });
191
+ }
192
+ function openMyUsage() {
193
+ Object.assign(history, { show: true, item: "", title: "My usage", usageOnly: true });
194
+ }
195
+ function continueDraft(d: TInventoryUsageDraft) {
196
+ // The draft's own item in hand (its qty is reserved there); a stand-in if the list has not loaded it.
197
+ const holding =
198
+ holdings.value.find((h) => String(h.item) === String(d.item)) ??
199
+ ({ _id: d._id, item: d.item, itemName: d.itemName, unit: d.unit, photo: "", holder: "", holderName: "", qty: d.qty, inDrafts: d.qty } as TInventoryHolding);
200
+ Object.assign(usage, { show: true, holding, draft: d });
201
+ }
202
+ async function loadDrafts() {
203
+ if (!ctl.value.recordUsage) return;
204
+ try {
205
+ const res = await api.getUsageDrafts(props.store._id);
206
+ drafts.value = res.items;
207
+ staleDays.value = res.staleAfterDays ?? 3;
208
+ } catch {
209
+ drafts.value = [];
210
+ }
211
+ }
158
212
  const notify = inject<(text: string, color?: string) => void>("inventoryNotify", () => {});
159
213
 
160
214
  const handovers = ref<TInventoryHandover[]>([]);
@@ -264,15 +318,16 @@ async function load() {
264
318
  }
265
319
 
266
320
  function use(h: TInventoryHolding) {
267
- Object.assign(usage, { show: true, holding: h });
321
+ Object.assign(usage, { show: true, holding: h, draft: null });
268
322
  }
269
323
 
270
324
  function changed() {
271
325
  load();
272
326
  loadHandovers();
327
+ loadDrafts();
273
328
  emit("changed");
274
329
  }
275
330
 
276
- watch(() => props.store._id, () => (load(), loadHandovers()));
277
- onMounted(() => (load(), loadHandovers()));
331
+ watch(() => props.store._id, () => (load(), loadHandovers(), loadDrafts()));
332
+ onMounted(() => (load(), loadHandovers(), loadDrafts()));
278
333
  </script>
@@ -0,0 +1,67 @@
1
+ <template>
2
+ <div v-if="list.length" class="d-flex flex-wrap ga-1 py-1">
3
+ <button v-for="ph in list" :key="ph.id + ph.label" type="button" class="inventory-thumb" :title="ph.title" :aria-label="`Open ${ph.title}`" @click="open = ph">
4
+ <v-img :src="getFileUrl(ph.id)" :width="size" :height="size" cover class="rounded" :alt="ph.title" />
5
+ <span class="inventory-thumb__tag">{{ ph.label }}</span>
6
+ </button>
7
+ </div>
8
+ <span v-else class="text-medium-emphasis">—</span>
9
+ <v-dialog :model-value="!!open" max-width="820" @update:model-value="open = null">
10
+ <v-card v-if="open" class="screen-modal">
11
+ <v-card-title class="d-flex align-center">
12
+ {{ open.title }}
13
+ <v-spacer />
14
+ <v-btn icon="mdi-close" variant="text" aria-label="Close" @click="open = null" />
15
+ </v-card-title>
16
+ <v-card-text>
17
+ <v-img :src="getFileUrl(open.id)" max-height="70vh" contain />
18
+ <div class="d-flex mt-2">
19
+ <a :href="getFileUrl(open.id)" target="_blank" rel="noopener" class="text-body-2">Open full size</a>
20
+ </div>
21
+ </v-card-text>
22
+ </v-card>
23
+ </v-dialog>
24
+ </template>
25
+
26
+ <script setup lang="ts">
27
+ import useFile from "../composables/useFile";
28
+ import useUtils from "../composables/useUtils";
29
+
30
+ /** Before / after (and other) photos of a usage or hand-over: small thumbnails, click to enlarge with the time taken. */
31
+ const props = defineProps({
32
+ photos: { type: Object as PropType<{ before?: string[]; after?: string[]; other?: string[] } | undefined>, default: undefined },
33
+ beforeAt: { type: String as PropType<string | null | undefined>, default: null },
34
+ afterAt: { type: String as PropType<string | null | undefined>, default: null },
35
+ size: { type: Number, default: 36 },
36
+ });
37
+ const { getFileUrl } = useFile();
38
+ const { standardFormatDateTime } = useUtils();
39
+ const open = ref<{ id: string; label: string; title: string } | null>(null);
40
+ const at = (d?: string | null) => (d ? ` — taken ${standardFormatDateTime(d)}` : "");
41
+ const list = computed(() => [
42
+ ...(props.photos?.before ?? []).map((id) => ({ id, label: "Before", title: `Before photo${at(props.beforeAt)}` })),
43
+ ...(props.photos?.after ?? []).map((id) => ({ id, label: "After", title: `After photo${at(props.afterAt)}` })),
44
+ ...(props.photos?.other ?? []).map((id) => ({ id, label: "Photo", title: "Photo" })),
45
+ ]);
46
+ </script>
47
+
48
+ <style scoped>
49
+ .inventory-thumb {
50
+ position: relative;
51
+ border: 0;
52
+ padding: 0;
53
+ background: none;
54
+ cursor: zoom-in;
55
+ }
56
+ .inventory-thumb__tag {
57
+ position: absolute;
58
+ left: 2px;
59
+ bottom: 2px;
60
+ font-size: 9px;
61
+ line-height: 1;
62
+ padding: 1px 3px;
63
+ border-radius: 3px;
64
+ background: rgba(0, 0, 0, 0.6);
65
+ color: #fff;
66
+ }
67
+ </style>
@@ -6,7 +6,7 @@
6
6
  <v-btn value="usage" class="text-none">Usage</v-btn>
7
7
  <v-btn v-if="ctl.fullReports" value="technicians" class="text-none">{{ worker.many }}</v-btn>
8
8
  <v-btn v-if="ctl.fullReports" value="purchases" class="text-none">Purchases</v-btn>
9
- <v-btn value="handovers" class="text-none">Hand-overs</v-btn>
9
+ <v-btn v-if="ctl.fullReports || ctl.review" value="handovers" class="text-none">Hand-overs</v-btn>
10
10
  </v-btn-toggle>
11
11
  <v-select
12
12
  v-if="report === 'purchases'"
@@ -60,21 +60,36 @@
60
60
  hide-details
61
61
  style="max-width: 260px"
62
62
  />
63
- <v-checkbox v-if="report === 'usage'" v-model="uncheckedOnly" label="Not checked yet" density="compact" hide-details class="flex-grow-0" />
63
+ <v-checkbox v-if="report === 'usage' && canCheck" v-model="uncheckedOnly" label="Not checked yet" density="compact" hide-details class="flex-grow-0" />
64
64
  <v-spacer />
65
- <v-btn v-if="ctl.fullReports" class="text-none screen-btn-ghost" variant="outlined" prepend-icon="mdi-file-excel-outline" :loading="exporting" @click="exportExcel">
65
+ <v-btn v-if="ctl.fullReports || report === 'usage'" class="text-none screen-btn-ghost" variant="outlined" prepend-icon="mdi-file-excel-outline" :loading="exporting" @click="exportExcel">
66
66
  Export Excel
67
67
  </v-btn>
68
68
  </div>
69
69
 
70
+ <!-- Usage tracking (owner 2026-09-29): who used what from this store, where, for which work order, with photos. -->
71
+ <div v-if="report === 'usage'" class="d-flex flex-wrap ga-2 align-center mb-3">
72
+ <v-select v-model="status" :items="USAGE_STATUS_CHOICES" label="Status" density="compact" hide-details style="max-width: 200px" />
73
+ <v-select v-model="person" :items="[{ value: '', title: 'Everyone' }, ...personChoices]" label="Person" density="compact" hide-details style="max-width: 280px" />
74
+ <v-select v-model="itemFilter" :items="[{ value: '', title: 'All items' }, ...itemChoices]" label="Item" density="compact" hide-details style="max-width: 220px" />
75
+ <v-text-field v-model="locationText" label="Where (unit, tenant or area)" density="compact" hide-details clearable style="max-width: 220px" />
76
+ <v-text-field v-model="referenceText" label="Work order / ref" density="compact" hide-details clearable style="max-width: 180px" />
77
+ <v-select v-model="flag" :items="flagChoices" label="Needs a look" density="compact" hide-details style="max-width: 220px" />
78
+ <v-text-field v-model="search" label="Search" prepend-inner-icon="mdi-magnify" density="compact" hide-details clearable style="max-width: 220px" />
79
+ </div>
80
+ <v-alert v-if="report === 'usage' && scope === 'own_company'" type="info" variant="tonal" density="compact" class="mb-2">
81
+ You see your own company's people only. The store's owner sees everyone's.
82
+ </v-alert>
83
+
70
84
  <p class="text-caption text-medium-emphasis mb-2">{{ help[report] }}</p>
71
85
  <p v-if="report === 'movement' && siteName" class="text-caption text-medium-emphasis mb-2">
72
86
  Start, received and end are the whole store's (shared by {{ sites.map((s) => s.name).join(" and ") }}). The last columns show what was issued for {{ siteName }} and used there.
73
87
  </p>
74
88
 
75
- <div v-if="report === 'usage' && rows.length" class="d-flex flex-wrap align-center ga-3 mb-2">
89
+ <div v-if="report === 'usage' && shownRows.length" class="d-flex flex-wrap align-center ga-3 mb-2">
76
90
  <div class="text-body-2 font-weight-medium">
77
- {{ rows.length }} record(s) · {{ totals.qty }} item(s) used · Total cost {{ money(totals.cost) }}
91
+ <template v-if="usageSummary.records">{{ usageSummary.records }} record(s) · {{ usageSummary.qty }} item(s) used · Total cost {{ money(usageSummary.cost) }}</template>
92
+ <template v-if="usageSummary.drafts">{{ usageSummary.records ? " · " : "" }}{{ usageSummary.drafts }} in progress (drafts — not counted as usage until submitted)</template>
78
93
  </div>
79
94
  <v-spacer />
80
95
  <template v-if="canCheck">
@@ -88,6 +103,19 @@
88
103
  </template>
89
104
  </div>
90
105
 
106
+ <v-row v-if="report === 'usage' && usageSummary.records" dense class="mb-2">
107
+ <v-col v-for="box in totalBoxes" :key="box.title" cols="12" md="4">
108
+ <AppCard class="pa-3">
109
+ <div class="text-subtitle-2 mb-2">{{ box.title }}</div>
110
+ <div v-for="t in box.rows.slice(0, 6)" :key="t.label" class="d-flex justify-space-between text-body-2 mb-1 ga-2">
111
+ <span class="text-truncate">{{ t.label }}</span>
112
+ <span class="text-no-wrap">{{ t.records }} × · {{ t.qty }}{{ t.unit ? ` ${t.unit}` : "" }} · {{ money(t.totalCost) }}</span>
113
+ </div>
114
+ <div v-if="box.rows.length > 6" class="text-caption text-medium-emphasis">and {{ box.rows.length - 6 }} more (all in the Excel file)</div>
115
+ </AppCard>
116
+ </v-col>
117
+ </v-row>
118
+
91
119
  <template v-if="report === 'purchases' && rows.length">
92
120
  <div class="text-body-2 font-weight-medium mb-2">Total purchases {{ money(totals.cost) }}</div>
93
121
  <v-row dense class="mb-2">
@@ -121,11 +149,12 @@
121
149
  :items="shownRows"
122
150
  :loading="loading"
123
151
  :show-select="report === 'usage' && canCheck"
152
+ :item-selectable="(r: any) => r.status !== 'draft'"
124
153
  item-value="_id"
125
154
  density="compact"
126
155
  :items-per-page="50"
127
156
  class="border rounded"
128
- no-data-text="Nothing recorded in this period."
157
+ :no-data-text="noDataText"
129
158
  >
130
159
  <template #item.date="{ value }">{{ standardFormatDate(value) }}</template>
131
160
  <template #item.createdAt="{ value }">{{ standardFormatDate(value) }}</template>
@@ -142,14 +171,31 @@
142
171
  <template #item.receivedCost="{ value }">{{ money(value) }}</template>
143
172
  <template #item.usedCost="{ value }">{{ money(value) }}</template>
144
173
  <template #item.siteUsedCost="{ value }">{{ money(value) }}</template>
145
- <!-- The supervisor checks usage against the technician's before/after photos. -->
174
+ <!-- The supervisor checks usage against the technician's before/after photos (click to enlarge, with the time taken). -->
146
175
  <template #item.photos="{ item }">
147
- <div v-if="usagePhotos(item).length" class="d-flex ga-1 py-1">
148
- <a v-for="ph in usagePhotos(item)" :key="ph.id" :href="getFileUrl(ph.id)" target="_blank" rel="noopener" :title="ph.label">
149
- <v-img :src="getFileUrl(ph.id)" width="36" height="36" cover class="rounded" :alt="ph.label" />
150
- </a>
176
+ <InventoryPhotoThumbs :photos="item.photos" :before-at="item.photosBeforeAt" :after-at="item.photosAfterAt" />
177
+ </template>
178
+ <template #item.state="{ item }">
179
+ <v-chip size="x-small" variant="tonal" :color="item.status === 'draft' ? 'info' : 'success'">{{ item.status === "draft" ? "In progress" : "Submitted" }}</v-chip>
180
+ <div v-for="f in item.flags ?? []" :key="f" class="mt-1">
181
+ <v-chip size="x-small" variant="tonal" color="warning">{{ flagWords[f] ?? f }}</v-chip>
151
182
  </div>
152
- <span v-else class="text-medium-emphasis">—</span>
183
+ </template>
184
+ <template #item.technician="{ item }">
185
+ <a href="#" class="text-primary" @click.prevent="openPerson(item)">{{ item.holderLabel || item.technician }}</a>
186
+ </template>
187
+ <template #item.itemName="{ item }">
188
+ <a v-if="report === 'usage' && scope === 'all'" href="#" class="text-primary" @click.prevent="openItem(item)">{{ item.itemName }}</a>
189
+ <span v-else>{{ item.itemName }}</span>
190
+ </template>
191
+ <template #item.times="{ item }">
192
+ <div class="text-caption text-no-wrap">
193
+ <div v-if="item.draftedAt">Draft {{ standardFormatDateTime(item.draftedAt) }}</div>
194
+ <div v-if="item.submittedAt">Submitted {{ standardFormatDateTime(item.submittedAt) }}</div>
195
+ </div>
196
+ </template>
197
+ <template #item.path="{ item }">
198
+ <span class="text-caption">{{ usagePathText(item.path, standardFormatDate) || "—" }}</span>
153
199
  </template>
154
200
  <template #item.checkedByName="{ item }">
155
201
  <v-chip v-if="item.checkedByName" size="x-small" color="success" variant="tonal">{{ item.checkedByName }}</v-chip>
@@ -159,6 +205,7 @@
159
205
  <span :class="item.reorderLevel && item.closing <= item.reorderLevel ? 'text-error font-weight-bold' : 'font-weight-medium'">{{ item.closing }}</span>
160
206
  </template>
161
207
  </v-data-table>
208
+ <InventoryHistoryDialog v-model="drill.show" :store="store" :holder="drill.holder" :item="drill.item" :title="drill.title" />
162
209
  </div>
163
210
  </template>
164
211
 
@@ -166,9 +213,9 @@
166
213
  import useInventory, { saveBlob } from "../composables/useInventory";
167
214
  import useWorkerTerm, { workerAppKey } from "../composables/useWorkerTerm";
168
215
  import useUtils from "../composables/useUtils";
169
- import useFile from "../composables/useFile";
170
216
  import { inventoryControls } from "../utils/inventory-presets";
171
217
  import { USED_BY_FILTERS } from "../utils/inventory-used-by";
218
+ import { USAGE_FLAG_WORDS, USAGE_STATUS_CHOICES, usagePathText, usageQuery, usageTotals } from "../utils/inventory-usage";
172
219
 
173
220
  const props = defineProps({
174
221
  store: { type: Object as PropType<TInventoryStore>, required: true },
@@ -177,12 +224,7 @@ const props = defineProps({
177
224
  const ctl = computed(() => inventoryControls(props.store.access));
178
225
 
179
226
  const api = useInventory();
180
- const { standardFormatDate } = useUtils();
181
- const { getFileUrl } = useFile();
182
- const usagePhotos = (row: any) => [
183
- ...(row.photos?.before ?? []).map((id: string) => ({ id, label: "Before" })),
184
- ...(row.photos?.after ?? []).map((id: string) => ({ id, label: "After" })),
185
- ];
227
+ const { standardFormatDate, standardFormatDateTime } = useUtils();
186
228
  const notify = inject<(text: string, color?: string) => void>("inventoryNotify", () => {});
187
229
 
188
230
  const worker = useWorkerTerm({ providers: true });
@@ -197,6 +239,26 @@ const site = ref("");
197
239
  const locationType = ref("");
198
240
  const uncheckedOnly = ref(false);
199
241
  const usedBy = ref("");
242
+ // Usage tracking filters. Status / place / work order / flag / search go to the server; person and item
243
+ // narrow the loaded rows (their choices come from the rows).
244
+ const status = ref("submitted");
245
+ const person = ref("");
246
+ const itemFilter = ref("");
247
+ const locationText = ref("");
248
+ const referenceText = ref("");
249
+ const flag = ref("");
250
+ const search = ref("");
251
+ const scope = ref<"all" | "own_company">("all");
252
+ const staleDays = ref(3);
253
+ const flagWords = computed(() => ({ ...USAGE_FLAG_WORDS, old_draft: `Draft older than ${staleDays.value} days` }) as Record<string, string>);
254
+ const flagChoices = computed(() => [{ value: "", title: "Everything" }, ...Object.entries(flagWords.value).map(([value, title]) => ({ value, title }))]);
255
+ const drill = reactive({ show: false, holder: "", item: "", title: "" });
256
+ function openPerson(r: any) {
257
+ Object.assign(drill, { show: true, holder: String(r.holder ?? ""), item: "", title: r.holderLabel || r.technician });
258
+ }
259
+ function openItem(r: any) {
260
+ Object.assign(drill, { show: true, holder: "", item: String(r.item ?? ""), title: `${r.itemName} — where it went` });
261
+ }
200
262
  const rows = ref<any[]>([]);
201
263
  const selected = ref<string[]>([]);
202
264
  const purchases = reactive({ byMonth: [] as { month: string; deliveries: number; totalCost: number }[], bySupplier: [] as { supplier: string; deliveries: number; totalCost: number }[] });
@@ -214,7 +276,7 @@ const barWidth = (v: number) => {
214
276
 
215
277
  const help: Record<string, string> = {
216
278
  movement: "For each item: stock at the start of the month, what came in (deliveries and opening stock), what was issued and returned, count differences, and stock at the end.",
217
- usage: "Every recorded usage: where it was used, for which tenant, by whom, and the cost. Use this for tenant billing. Tick records and mark them checked once verified.",
279
+ usage: "Every usage of this store's items, by anyone: who (company and service), where, which work order, before and after photos with their times, and how the stock reached them. Click a person or an item to see its full history. Use it for tenant billing; tick records and mark them checked once verified.",
218
280
  technicians: "For each person: stock they held at the start, took, used, returned, and hold at the end of the month.",
219
281
  purchases: "Every delivery received, and opening stock entered with new items (Type: Opening stock), with totals by month and by supplier.",
220
282
  handovers: "Stock passed from one person to a colleague: who gave it, who received it, and whether they confirmed.",
@@ -228,7 +290,43 @@ const serviceFilter = ref("");
228
290
  const serviceChoices = computed(() =>
229
291
  [...new Set(rows.value.map(companyOf).filter(Boolean))].sort().map((v) => ({ value: v, title: v })),
230
292
  );
231
- const shownRows = computed(() => (serviceFilter.value ? rows.value.filter((r) => companyOf(r) === serviceFilter.value || [r.toCompany, r.toServiceLabel].filter(Boolean).join(" · ") === serviceFilter.value) : rows.value));
293
+ const shownRows = computed(() =>
294
+ rows.value.filter(
295
+ (r) =>
296
+ (!serviceFilter.value || companyOf(r) === serviceFilter.value || [r.toCompany, r.toServiceLabel].filter(Boolean).join(" · ") === serviceFilter.value) &&
297
+ (report.value !== "usage" || ((!person.value || String(r.holder) === person.value) && (!itemFilter.value || String(r.item) === itemFilter.value))),
298
+ ),
299
+ );
300
+ const choices = (key: (r: any) => string, label: (r: any) => string) =>
301
+ report.value !== "usage"
302
+ ? []
303
+ : [...new Map(rows.value.map((r) => [key(r), String(label(r) ?? "")])).entries()].map(([value, title]) => ({ value, title })).sort((a, b) => a.title.localeCompare(b.title));
304
+ const personChoices = computed(() => choices((r) => String(r.holder), (r) => r.holderLabel || r.technician));
305
+ const itemChoices = computed(() => choices((r) => String(r.item), (r) => r.itemName));
306
+ const usageSummary = computed(() => {
307
+ const done = shownRows.value.filter((r) => r.status !== "draft");
308
+ return {
309
+ records: done.length,
310
+ qty: done.reduce((sum, r) => sum + r.qty, 0),
311
+ cost: Math.round(done.reduce((sum, r) => sum + (r.totalCost ?? 0), 0) * 100) / 100,
312
+ drafts: shownRows.value.length - done.length,
313
+ };
314
+ });
315
+ const totalBoxes = computed(() => {
316
+ const t = usageTotals(shownRows.value);
317
+ return [
318
+ { title: "By item", rows: t.byItem },
319
+ { title: "By person", rows: t.byPerson },
320
+ { title: "By company", rows: t.byCompany },
321
+ ];
322
+ });
323
+ const noDataText = computed(() =>
324
+ report.value !== "usage"
325
+ ? "Nothing recorded in this period."
326
+ : status.value === "draft"
327
+ ? "No usage in progress. Drafts appear here once someone saves a before photo."
328
+ : "No usage recorded for these filters in this month.",
329
+ );
232
330
 
233
331
  const headers: Record<string, any[]> = {
234
332
  movement: [
@@ -247,6 +345,7 @@ const headers: Record<string, any[]> = {
247
345
  ],
248
346
  usage: [
249
347
  { title: "Date", key: "date" },
348
+ { title: "Status", key: "state", sortable: false },
250
349
  { title: "Property", key: "siteName" },
251
350
  { title: "Where", key: "locationType" },
252
351
  { title: "Unit / Area", key: "location" },
@@ -255,12 +354,13 @@ const headers: Record<string, any[]> = {
255
354
  { title: "Qty", key: "qty" },
256
355
  { title: "Unit price", key: "unitCost" },
257
356
  { title: "Total", key: "totalCost" },
258
- { title: worker.one, key: "technician" },
259
- { title: "Company", key: "holderCompany" },
260
- { title: "Service", key: "holderServiceLabel" },
261
- { title: "Photos", key: "photos", sortable: false },
262
- { title: "Reference", key: "reference" },
357
+ { title: worker.one, key: "technician", minWidth: "200px" },
358
+ { title: "Photos", key: "photos", sortable: false, minWidth: "124px" },
359
+ { title: "Work order / ref", key: "reference", minWidth: "130px" },
360
+ { title: "Saved / submitted", key: "times", sortable: false },
361
+ { title: "Came from", key: "path", sortable: false, minWidth: "220px" },
263
362
  { title: "Reported by", key: "reportedBy" },
363
+ { title: "Remarks", key: "remarks" },
264
364
  { title: "Checked by", key: "checkedByName" },
265
365
  ],
266
366
  technicians: [
@@ -326,9 +426,27 @@ function period(): TInventoryPeriod & { unchecked?: boolean } {
326
426
  ...(report.value === "usage" && locationType.value ? { locationType: locationType.value } : {}),
327
427
  ...(report.value === "usage" && uncheckedOnly.value ? { unchecked: true } : {}),
328
428
  ...(usedBy.value ? { usedBy: usedBy.value } : {}),
429
+ ...(report.value === "usage"
430
+ ? usageQuery({ status: status.value === "submitted" ? "" : status.value, location: locationText.value, reference: referenceText.value, flag: flag.value, search: search.value })
431
+ : {}),
329
432
  };
330
433
  }
331
434
 
435
+ /** The export carries the person / item / company picked on screen too. */
436
+ function exportFilters() {
437
+ if (report.value !== "usage") return {};
438
+ const pick = rows.value.find((r) => companyOf(r) === serviceFilter.value);
439
+ const base = String(useRuntimeConfig().public.API_DO_STORAGE_ENDPOINT ?? "");
440
+ return usageQuery({
441
+ holder: person.value,
442
+ item: itemFilter.value,
443
+ company: serviceFilter.value ? pick?.holderCompany : "",
444
+ service: serviceFilter.value ? pick?.holderService : "",
445
+ // Photo links in the file open the photo itself.
446
+ photoBase: base.startsWith("https://") ? base : "",
447
+ });
448
+ }
449
+
332
450
  async function load() {
333
451
  if (!month.value) return;
334
452
  loading.value = true;
@@ -338,6 +456,8 @@ async function load() {
338
456
  rows.value = res.rows;
339
457
  totals.qty = res.totalQty ?? 0;
340
458
  totals.cost = res.totalCost ?? 0;
459
+ scope.value = res.scope ?? "all";
460
+ staleDays.value = res.staleAfterDays ?? 3;
341
461
  purchases.byMonth = res.byMonth ?? [];
342
462
  purchases.bySupplier = res.bySupplier ?? [];
343
463
  } catch (error: any) {
@@ -365,7 +485,7 @@ async function setChecked(checked: boolean) {
365
485
  async function exportExcel() {
366
486
  exporting.value = true;
367
487
  try {
368
- const blob = await api.exportReport(props.store._id, report.value, { ...period(), appSlug });
488
+ const blob = await api.exportReport(props.store._id, report.value, { ...period(), ...exportFilters(), appSlug });
369
489
  saveBlob(blob, `${props.store.name} - ${report.value === "technicians" ? worker.many : report.value} - ${month.value}.xlsx`);
370
490
  } catch {
371
491
  notify("Could not export the report.", "error");
@@ -374,7 +494,13 @@ async function exportExcel() {
374
494
  }
375
495
  }
376
496
 
377
- watch([report, month, span, site, locationType, uncheckedOnly, usedBy, () => props.store._id], load);
497
+ watch([report, month, span, site, locationType, uncheckedOnly, usedBy, status, flag, () => props.store._id], load);
498
+ // Typed filters wait until the typing stops.
499
+ let typing: ReturnType<typeof setTimeout> | undefined;
500
+ watch([locationText, referenceText, search], () => {
501
+ clearTimeout(typing);
502
+ typing = setTimeout(load, 400);
503
+ });
378
504
  watch(report, () => (serviceFilter.value = ""));
379
505
  onMounted(load);
380
506
  </script>