@flowselections/e-mail-installatie-techniek 1.0.5 → 1.0.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"WerkbonProposalForm.d.ts","sourceRoot":"","sources":["../../../src/components/mail/WerkbonProposalForm.tsx"],"names":[],"mappings":"AAYA,OAAO,EAQL,KAAK,WAAW,EAChB,KAAK,cAAc,EAEpB,MAAM,uCAAuC,CAAC;AAE/C,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,2BAA2B,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,0BAA0B,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,KAAK,EAAE,WAAW,EAAE,CAAC;CACtB;AAED,UAAU,KAAK;IACb,KAAK,EAAE,gBAAgB,CAAC;IACxB,OAAO,EAAE,cAAc,CAAC;IACxB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;IACrD,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,aAAa,EAAE,MAAM,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAobD,wBAAgB,mBAAmB,CAAC,EAClC,KAAK,EACL,OAAO,EACP,MAAM,EACN,SAAiB,EACjB,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,aAAa,EACb,QAAgB,GACjB,EAAE,KAAK,+BAkjBP"}
1
+ {"version":3,"file":"WerkbonProposalForm.d.ts","sourceRoot":"","sources":["../../../src/components/mail/WerkbonProposalForm.tsx"],"names":[],"mappings":"AAYA,OAAO,EAQL,KAAK,WAAW,EAChB,KAAK,cAAc,EAEpB,MAAM,uCAAuC,CAAC;AAG/C,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,2BAA2B,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,0BAA0B,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,KAAK,EAAE,WAAW,EAAE,CAAC;CACtB;AAED,UAAU,KAAK;IACb,KAAK,EAAE,gBAAgB,CAAC;IACxB,OAAO,EAAE,cAAc,CAAC;IACxB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,KAAK,IAAI,CAAC;IACrD,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,aAAa,EAAE,MAAM,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AA4cD,wBAAgB,mBAAmB,CAAC,EAClC,KAAK,EACL,OAAO,EACP,MAAM,EACN,SAAiB,EACjB,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,aAAa,EACb,QAAgB,GACjB,EAAE,KAAK,+BA+oBP"}
@@ -1,9 +1,10 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useEffect, useMemo, useRef, useState } from "react";
3
3
  import { Check, ChevronsUpDown, Plus, Search, Trash2, UserPlus } from "lucide-react";
4
4
  import { Button, Input, Label, Popover, PopoverContent, PopoverTrigger, Textarea, } from "@flowselections/core";
5
5
  import { useServerFn } from "@tanstack/react-start";
6
6
  import { computeWerkbonTravel, getWerkbonLinesTotal, formatEuroCents, searchArtikelen, getArtikelFotos, } from "../../lib/werkbon-proposals.functions";
7
+ import { getKlantStatus } from "../../lib/klanten.functions";
7
8
  function Section({ title, children }) {
8
9
  return (_jsxs("section", { className: "space-y-3 rounded-md border border-border p-4", children: [_jsx("h3", { className: "text-sm font-semibold", children: title }), children] }));
9
10
  }
@@ -30,13 +31,15 @@ function OptionPicker({ items, value, placeholder, noun, disabled, header, onSel
30
31
  setOpen(next);
31
32
  if (!next)
32
33
  setSearch("");
33
- }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("button", { type: "button", disabled: disabled, className: "flex h-9 w-full items-center justify-between rounded-md border border-input bg-background px-3 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", children: [_jsx("span", { className: selected ? "truncate" : "truncate text-muted-foreground", children: selected ? selected.label : placeholder }), _jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 text-muted-foreground" })] }) }), _jsxs(PopoverContent, { align: "start", className: "z-[200] w-[--radix-popover-trigger-width] min-w-[16rem] p-0", children: [header ? _jsx("div", { className: "border-b border-border p-2", children: header(close) }) : null, _jsxs("div", { className: "flex items-center gap-2 border-b border-border px-3 py-2", children: [_jsx(Search, { className: "h-4 w-4 shrink-0 text-muted-foreground" }), _jsx("input", { value: search, onChange: (e) => setSearch(e.target.value), placeholder: `Zoek in ${safeItems.length} ${noun}…`, className: "h-7 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" })] }), _jsxs("div", { className: "max-h-64 overflow-y-auto p-1", children: [_jsxs("button", { type: "button", onClick: () => {
34
+ }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("button", { type: "button", disabled: disabled, className: "flex h-9 w-full items-center justify-between rounded-md border border-input bg-background px-3 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", children: [_jsx("span", { className: selected
35
+ ? "flex min-w-0 items-center gap-2"
36
+ : "truncate text-muted-foreground", children: selected ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "truncate", children: selected.label }), selected.badge ? (_jsx("span", { className: "shrink-0 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-primary", children: selected.badge })) : null] })) : (placeholder) }), _jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 text-muted-foreground" })] }) }), _jsxs(PopoverContent, { align: "start", className: "z-[200] w-[--radix-popover-trigger-width] min-w-[16rem] p-0", children: [header ? _jsx("div", { className: "border-b border-border p-2", children: header(close) }) : null, _jsxs("div", { className: "flex items-center gap-2 border-b border-border px-3 py-2", children: [_jsx(Search, { className: "h-4 w-4 shrink-0 text-muted-foreground" }), _jsx("input", { value: search, onChange: (e) => setSearch(e.target.value), placeholder: `Zoek in ${safeItems.length} ${noun}…`, className: "h-7 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" })] }), _jsxs("div", { className: "max-h-64 overflow-y-auto p-1", children: [_jsxs("button", { type: "button", onClick: () => {
34
37
  onClear();
35
38
  close();
36
39
  }, className: "flex w-full items-center justify-between gap-2 rounded-sm px-3 py-2 text-left text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground", children: [_jsx("span", { children: "\u2014 Geen koppeling \u2014" }), value == null ? _jsx(Check, { className: "h-4 w-4 shrink-0" }) : null] }), safeItems.length === 0 ? (_jsxs("p", { className: "px-3 py-4 text-center text-sm text-muted-foreground", children: ["Er zijn nog geen ", noun, " ingericht."] })) : filtered.length === 0 ? (_jsxs("p", { className: "px-3 py-4 text-center text-sm text-muted-foreground", children: ["Geen ", noun, " gevonden."] })) : (filtered.map((item) => (_jsxs("button", { type: "button", onClick: () => {
37
40
  onSelect(item.id);
38
41
  close();
39
- }, className: "flex w-full items-center justify-between gap-2 rounded-sm px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground", children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "block truncate", children: item.label }), item.hint ? (_jsx("span", { className: "block truncate text-xs text-muted-foreground", children: item.hint })) : null] }), item.id === value ? _jsx(Check, { className: "h-4 w-4 shrink-0" }) : null] }, item.id))))] })] })] }));
42
+ }, className: "flex w-full items-center justify-between gap-2 rounded-sm px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground", children: [_jsxs("span", { className: "min-w-0", children: [_jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [_jsx("span", { className: "truncate", children: item.label }), item.badge ? (_jsx("span", { className: "shrink-0 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-primary", children: item.badge })) : null] }), item.hint ? (_jsx("span", { className: "block truncate text-xs text-muted-foreground", children: item.hint })) : null] }), item.id === value ? _jsx(Check, { className: "h-4 w-4 shrink-0" }) : null] }, item.id))))] })] })] }));
40
43
  }
41
44
  function CustomerPicker({ customers, value, onSelect, onClear, onNewCustomer, }) {
42
45
  return (_jsx(OptionPicker, { items: customers, value: value, placeholder: "Kies klant\u2026", noun: "klanten", onSelect: onSelect, onClear: onClear, header: (close) => (_jsxs(Button, { type: "button", className: "w-full justify-start gap-2", onClick: () => {
@@ -184,7 +187,7 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
184
187
  // Totaal van pakketten + materialen t.o.v. het mandaat (prijzen uit de database).
185
188
  const fetchTotal = useServerFn(getWerkbonLinesTotal);
186
189
  const [totalCents, setTotalCents] = useState(null);
187
- const linesKey = JSON.stringify(lines.map((l) => [l.line_type, l.package_id, (l.article_number ?? "").trim(), l.quantity]));
190
+ const linesKey = JSON.stringify(lines.map((l) => [l.line_type, l.package_id, (l.article_number ?? "").trim(), l.quantity, l.extra_quarters ?? 0]));
188
191
  useEffect(() => {
189
192
  let cancelled = false;
190
193
  const t = setTimeout(() => {
@@ -204,8 +207,38 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
204
207
  };
205
208
  // eslint-disable-next-line react-hooks/exhaustive-deps
206
209
  }, [linesKey]);
210
+ // Risico- / geblokkeerd-status van de gekozen klant.
211
+ const fetchKlantStatus = useServerFn(getKlantStatus);
212
+ const [klantStatus, setKlantStatus] = useState(null);
213
+ useEffect(() => {
214
+ const id = value.customer_id;
215
+ if (!id) {
216
+ setKlantStatus(null);
217
+ return;
218
+ }
219
+ let cancelled = false;
220
+ fetchKlantStatus({ data: { customer_id: id } })
221
+ .then((r) => {
222
+ if (!cancelled)
223
+ setKlantStatus(r ?? null);
224
+ })
225
+ .catch(() => {
226
+ if (!cancelled)
227
+ setKlantStatus(null);
228
+ });
229
+ return () => {
230
+ cancelled = true;
231
+ };
232
+ // eslint-disable-next-line react-hooks/exhaustive-deps
233
+ }, [value.customer_id]);
234
+ const klantBlocked = klantStatus?.status === "blocked";
235
+ const klantRisk = klantStatus?.status === "risk";
236
+ const klantNotes = (() => {
237
+ const list = [klantStatus?.reason, ...(Array.isArray(klantStatus?.notes) ? klantStatus.notes : [])]
238
+ .filter((n) => !!n);
239
+ return Array.from(new Set(list));
240
+ })();
207
241
  const mandateCents = Number(value.budget_mandate_cents ?? 0) || 0;
208
- const showMandate = mandateCents > 0 && totalCents != null && totalCents >= mandateCents * 0.9;
209
242
  const overMandate = mandateCents > 0 && totalCents != null ? Math.max(0, totalCents - mandateCents) : 0;
210
243
  const pkgList = Array.isArray(options?.packages) ? options.packages : [];
211
244
  // Alleen werktijd telt mee; reistijd uit rijpakketten niet.
@@ -215,11 +248,22 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
215
248
  const p = pkgList.find((x) => x.id === l.package_id);
216
249
  const m = Math.max(0, Number(p?.duration_minutes ?? 0) - Number(p?.travel_minutes ?? 0));
217
250
  const q = l.quantity == null ? 1 : Number(l.quantity);
218
- return sum + (Number.isFinite(m) && Number.isFinite(q) ? m * q : 0);
251
+ const extra = Math.max(0, Number(l.extra_quarters ?? 0) || 0) * 15;
252
+ return sum + (Number.isFinite(m) && Number.isFinite(q) ? m * q : 0) + extra;
219
253
  }, 0);
220
254
  // Reistijd automatisch berekenen en rijpakketten zetten.
221
255
  const computeTravel = useServerFn(computeWerkbonTravel);
222
- const travelPkg = pkgList.find((p) => (p.travel_minutes ?? 0) > 0) ?? null;
256
+ const travelPkg = pkgList.find((p) => (p.travel_minutes ?? 0) > 0 && !p.badge) ?? null;
257
+ // Reistijd die al in basispakketten zit (blijft altijd staan).
258
+ const basisTravel = lines.reduce((sum, l) => {
259
+ if (l.line_type !== "package" || !l.package_id)
260
+ return sum;
261
+ const p = pkgList.find((x) => x.id === l.package_id);
262
+ if (!p?.badge)
263
+ return sum;
264
+ const q = l.quantity == null ? 1 : Number(l.quantity) || 0;
265
+ return sum + (Number(p.travel_minutes ?? 0) || 0) * q;
266
+ }, 0);
223
267
  const [travel, setTravel] = useState(null);
224
268
  const latest = useRef({ lines, onChange });
225
269
  latest.current = { lines, onChange };
@@ -238,35 +282,6 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
238
282
  if (cancelled)
239
283
  return;
240
284
  setTravel(res);
241
- const per = Number(travelPkg?.travel_minutes ?? 0);
242
- if (!res?.round_trip_minutes || !travelPkg || per <= 0)
243
- return;
244
- const qty = Math.ceil(res.round_trip_minutes / per);
245
- const cur = Array.isArray(latest.current.lines) ? latest.current.lines : [];
246
- const idx = cur.findIndex((l) => l.line_type === "package" && l.package_id === travelPkg.id);
247
- if (idx >= 0) {
248
- if (cur[idx].quantity === qty)
249
- return;
250
- latest.current.onChange({
251
- lines: cur.map((l, i) => (i === idx ? { ...l, quantity: qty } : l)),
252
- });
253
- }
254
- else {
255
- latest.current.onChange({
256
- lines: [
257
- ...cur,
258
- {
259
- line_type: "package",
260
- package_id: travelPkg.id,
261
- description: "",
262
- article_number: "",
263
- quantity: qty,
264
- unit: "",
265
- note: "Reistijd (automatisch)",
266
- },
267
- ],
268
- });
269
- }
270
285
  }
271
286
  catch {
272
287
  if (!cancelled)
@@ -279,6 +294,45 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
279
294
  };
280
295
  // eslint-disable-next-line react-hooks/exhaustive-deps
281
296
  }, [address, value.technician_id, readOnly, travelPkg?.id]);
297
+ // Rijpakketten alleen voor de reistijd boven wat de basispakketten al dekken.
298
+ const roundTrip = travel?.round_trip_minutes ?? null;
299
+ useEffect(() => {
300
+ if (readOnly || !roundTrip || !travelPkg)
301
+ return;
302
+ const per = Number(travelPkg.travel_minutes ?? 0);
303
+ if (per <= 0)
304
+ return;
305
+ const qty = Math.ceil(Math.max(0, roundTrip - basisTravel) / per);
306
+ const cur = Array.isArray(latest.current.lines) ? latest.current.lines : [];
307
+ const idx = cur.findIndex((l) => l.line_type === "package" && l.package_id === travelPkg.id);
308
+ if (idx >= 0) {
309
+ if (qty === 0) {
310
+ latest.current.onChange({ lines: cur.filter((_, i) => i !== idx) });
311
+ }
312
+ else if (cur[idx].quantity !== qty) {
313
+ latest.current.onChange({
314
+ lines: cur.map((l, i) => (i === idx ? { ...l, quantity: qty } : l)),
315
+ });
316
+ }
317
+ }
318
+ else if (qty > 0) {
319
+ latest.current.onChange({
320
+ lines: [
321
+ ...cur,
322
+ {
323
+ line_type: "package",
324
+ package_id: travelPkg.id,
325
+ description: "",
326
+ article_number: "",
327
+ quantity: qty,
328
+ unit: "",
329
+ note: "Reistijd (automatisch)",
330
+ },
331
+ ],
332
+ });
333
+ }
334
+ // eslint-disable-next-line react-hooks/exhaustive-deps
335
+ }, [roundTrip, basisTravel, travelPkg?.id, readOnly]);
282
336
  const applyLines = (next) => {
283
337
  const diff = Math.round(packageMinutes(next) - packageMinutes(lines));
284
338
  if (diff === 0) {
@@ -311,6 +365,7 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
311
365
  };
312
366
  const fetchFotos = useServerFn(getArtikelFotos);
313
367
  const [fotos, setFotos] = useState({});
368
+ const [prijzen, setPrijzen] = useState({});
314
369
  const packageLines = lines
315
370
  .map((l, i) => ({ l, i }))
316
371
  .filter(({ l }) => l.line_type === "package");
@@ -360,6 +415,14 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
360
415
  next[c] = got[c] ?? "";
361
416
  return next;
362
417
  });
418
+ const gotP = res?.prijzen && typeof res.prijzen === "object" ? res.prijzen : {};
419
+ setPrijzen((pr) => {
420
+ const next = { ...pr };
421
+ for (const c of missing)
422
+ if (!(c in next))
423
+ next[c] = gotP[c] ?? null;
424
+ return next;
425
+ });
363
426
  })
364
427
  .catch(() => { });
365
428
  return () => {
@@ -367,14 +430,16 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
367
430
  };
368
431
  // eslint-disable-next-line react-hooks/exhaustive-deps
369
432
  }, [materialCodesKey]);
370
- return (_jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "min-h-0 flex-1 space-y-4 overflow-y-auto p-5", children: [_jsx("h2", { className: "text-base font-semibold", children: "Werkbonvoorstel" }), _jsxs(Section, { title: "Klant & locatie", children: [_jsxs(Field, { label: "Klant", required: true, empty: !value.customer_id, children: [_jsx(CustomerPicker, { customers: Array.isArray(options.customers) ? options.customers : [], value: value.customer_id, onSelect: (id) => onChange({ customer_id: id }), onClear: () => onChange({ customer_id: null }), onNewCustomer: onNewCustomer }), !value.customer_id && !readOnly && (_jsxs("div", { className: "mt-1.5 flex items-center justify-between gap-2", children: [_jsx("span", { className: "text-xs font-medium text-destructive", children: "Klant niet bekend" }), _jsxs(Button, { type: "button", size: "sm", variant: "outline", className: "gap-1.5", onClick: onNewCustomer, children: [_jsx(UserPlus, { className: "h-3.5 w-3.5" }), "Nieuwe klant toevoegen"] })] }))] }), _jsx(Field, { label: "Werkadres", children: _jsx(Input, { value: value.work_address ?? "", placeholder: "Straat, postcode, plaats", onChange: (e) => onChange({ work_address: e.target.value || null }) }) }), _jsx(Field, { label: "kamer/ruimte nummer", children: _jsx(Input, { value: value.room_number ?? "", placeholder: "Bijv. 2.14", onChange: (e) => onChange({ room_number: e.target.value || null }) }) })] }), _jsxs(Section, { title: "Project & referentie", children: [_jsx(Field, { label: "Externe referentie", children: _jsx(Input, { value: value.externe_referentie ?? "", placeholder: "Referentie van de klant", onChange: (e) => onChange({ externe_referentie: e.target.value || null }) }) }), _jsx(Field, { label: "Budgetmandaat (\u20AC)", children: _jsx(Input, { inputMode: "decimal", value: value.budget_mandate_cents == null ? "" : String(value.budget_mandate_cents / 100), placeholder: "0", onChange: (e) => {
371
- const n = Number(e.target.value.replace(",", "."));
372
- onChange({
373
- budget_mandate_cents: e.target.value === "" || Number.isNaN(n) ? null : Math.round(n * 100),
374
- });
375
- } }) })] }), _jsxs(Section, { title: "Opdracht", children: [_jsx(Field, { label: "Klacht / melding", children: _jsx(Textarea, { rows: 4, value: value.complaint_description ?? "", placeholder: "Wat is er aan de hand?", onChange: (e) => onChange({ complaint_description: e.target.value || null }) }) }), _jsx(Field, { label: "Omschrijving voor de monteur", children: _jsx(Textarea, { rows: 4, value: value.technician_task_description ?? "", placeholder: "Wat moet er gebeuren?", onChange: (e) => onChange({ technician_task_description: e.target.value || null }) }) })] }), _jsxs(Section, { title: "Pakketten toevoegen", children: [_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { className: "text-xs text-muted-foreground", children: "Werkzaamheden" }), packageLines.length === 0 && (_jsx("p", { className: "text-xs text-muted-foreground", children: "Nog geen werkzaamheden." })), !readOnly && travel && (_jsx("p", { className: travel.error ? "text-xs text-destructive" : "text-xs text-muted-foreground", children: travel.error
433
+ return (_jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [_jsxs("div", { className: "min-h-0 flex-1 space-y-4 overflow-y-auto p-5", children: [_jsx("h2", { className: "text-base font-semibold", children: "Werkbonvoorstel" }), (klantRisk || klantBlocked) && (_jsxs("div", { role: "alert", className: `rounded-md border p-3 text-sm ${klantBlocked
434
+ ? "border-destructive/50 bg-destructive/10 text-destructive"
435
+ : "border-orange-400/60 bg-orange-500/10 text-orange-700 dark:text-orange-300"}`, children: [_jsx("p", { className: "font-semibold", children: klantBlocked ? "Deze klant is geblokkeerd" : "Let op: dit is een risicoklant" }), klantNotes.length > 0 && (_jsx("ul", { className: "mt-1 list-disc space-y-0.5 pl-5", children: klantNotes.map((n, i) => (_jsx("li", { children: n }, i))) }))] })), _jsxs(Section, { title: "Klant & locatie", children: [_jsxs(Field, { label: "Klant", required: true, empty: !value.customer_id, children: [_jsx(CustomerPicker, { customers: Array.isArray(options.customers) ? options.customers : [], value: value.customer_id, onSelect: (id) => onChange({ customer_id: id }), onClear: () => onChange({ customer_id: null }), onNewCustomer: onNewCustomer }), !value.customer_id && !readOnly && (_jsxs("div", { className: "mt-1.5 flex items-center justify-between gap-2", children: [_jsx("span", { className: "text-xs font-medium text-destructive", children: "Klant niet bekend" }), _jsxs(Button, { type: "button", size: "sm", variant: "outline", className: "gap-1.5", onClick: onNewCustomer, children: [_jsx(UserPlus, { className: "h-3.5 w-3.5" }), "Nieuwe klant toevoegen"] })] }))] }), _jsx(Field, { label: "Werkadres", children: _jsx(Input, { value: value.work_address ?? "", placeholder: "Straat, postcode, plaats", onChange: (e) => onChange({ work_address: e.target.value || null }) }) }), _jsx(Field, { label: "kamer/ruimte nummer", children: _jsx(Input, { value: value.room_number ?? "", placeholder: "Bijv. 2.14", onChange: (e) => onChange({ room_number: e.target.value || null }) }) })] }), _jsxs(Section, { title: "Project & referentie", children: [_jsx(Field, { label: "Externe referentie", children: _jsx(Input, { value: value.externe_referentie ?? "", placeholder: "Referentie van de klant", onChange: (e) => onChange({ externe_referentie: e.target.value || null }) }) }), _jsxs(Field, { label: "Budgetmandaat (\u20AC)", children: [_jsx(Input, { inputMode: "decimal", value: value.budget_mandate_cents == null ? "" : String(value.budget_mandate_cents / 100), placeholder: "0", onChange: (e) => {
436
+ const n = Number(e.target.value.replace(",", "."));
437
+ onChange({
438
+ budget_mandate_cents: e.target.value === "" || Number.isNaN(n) ? null : Math.round(n * 100),
439
+ });
440
+ } }), mandateCents > 0 && (_jsx(MandaatBalk, { totalCents: totalCents ?? 0, mandateCents: mandateCents }))] })] }), _jsxs(Section, { title: "Opdracht", children: [_jsx(Field, { label: "Klacht / melding", children: _jsx(Textarea, { rows: 4, value: value.complaint_description ?? "", placeholder: "Wat is er aan de hand?", onChange: (e) => onChange({ complaint_description: e.target.value || null }) }) }), _jsx(Field, { label: "Omschrijving voor de monteur", children: _jsx(Textarea, { rows: 4, value: value.technician_task_description ?? "", placeholder: "Wat moet er gebeuren?", onChange: (e) => onChange({ technician_task_description: e.target.value || null }) }) })] }), _jsxs(Section, { title: "Pakketten toevoegen", children: [_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { className: "text-xs text-muted-foreground", children: "Werkzaamheden" }), packageLines.length === 0 && (_jsx("p", { className: "text-xs text-muted-foreground", children: "Nog geen werkzaamheden." })), !readOnly && travel && (_jsx("p", { className: travel.error ? "text-xs text-destructive" : "text-xs text-muted-foreground", children: travel.error
376
441
  ? travel.error
377
- : `Reistijd: ${fmtMin(travel.one_way_minutes ?? 0)} enkele reis (${fmtMin(travel.round_trip_minutes ?? 0)} heen en terug) vanaf ${travel.origin_label ?? "de zaak"}` })), packageLines.map(({ l, i }) => (_jsxs("div", { className: "grid grid-cols-[minmax(0,1fr)_5rem_auto] gap-2 rounded-md border border-border p-3", children: [_jsxs("div", { className: "min-w-0 space-y-1", children: [_jsx(OptionPicker, { value: l.package_id, items: options.packages, placeholder: "Kies een werkzaamheid\u2026", noun: "werkzaamheden", onSelect: (id) => updateLine(i, { package_id: id, quantity: l.quantity ?? 1 }), onClear: () => updateLine(i, { package_id: null }) }), l.description && !l.package_id && (_jsxs("p", { className: "truncate text-xs text-muted-foreground", children: ["Uit de mail: ", l.description] }))] }), _jsx(Input, { inputMode: "numeric", placeholder: "Aantal", value: l.quantity == null ? "" : String(l.quantity), onChange: (e) => {
442
+ : `Reistijd: ${fmtMin(travel.one_way_minutes ?? 0)} enkele reis (${fmtMin(travel.round_trip_minutes ?? 0)} heen en terug) vanaf ${travel.origin_label ?? "de zaak"}` })), packageLines.map(({ l, i }) => (_jsxs("div", { className: "grid grid-cols-[minmax(0,1fr)_5rem_auto] gap-2 rounded-md border border-border p-3", children: [_jsxs("div", { className: "min-w-0 space-y-1", children: [_jsx(OptionPicker, { value: l.package_id, items: options.packages, placeholder: "Kies een werkzaamheid\u2026", noun: "werkzaamheden", onSelect: (id) => updateLine(i, { package_id: id, quantity: l.quantity ?? 1 }), onClear: () => updateLine(i, { package_id: null }) }), l.description && !l.package_id && (_jsxs("p", { className: "truncate text-xs text-muted-foreground", children: ["Uit de mail: ", l.description] })), _jsx(PackageLineInfo, { line: l, pkg: pkgList.find((x) => x.id === l.package_id) ?? null, readOnly: !!readOnly, onQuarters: (q) => updateLine(i, { extra_quarters: q }) })] }), _jsx(Input, { inputMode: "numeric", placeholder: "Aantal", value: l.quantity == null ? "" : String(l.quantity), onChange: (e) => {
378
443
  const n = Number(e.target.value);
379
444
  updateLine(i, {
380
445
  quantity: e.target.value === "" || Number.isNaN(n) ? null : n,
@@ -387,13 +452,21 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
387
452
  if (photoUrl && a.artikelcode) {
388
453
  setFotos((f) => ({ ...f, [a.artikelcode]: photoUrl }));
389
454
  }
455
+ if (a.artikelcode)
456
+ setPrijzen((pr) => ({ ...pr, [a.artikelcode]: a.prijs_cent ?? null }));
390
457
  updateLine(i, {
391
458
  description: a.naam || a.omschrijving || a.artikelcode,
392
459
  article_number: a.artikelcode,
393
460
  unit: a.eenheid || l.unit,
394
461
  quantity: l.quantity ?? 1,
395
462
  });
396
- }, onFreeText: (t) => updateLine(i, { description: t }) }), l.article_number ? (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsxs("p", { className: "truncate text-xs text-muted-foreground", children: ["Artikelcode: ", l.article_number] }), _jsx(ArtikelFoto, { url: fotos[l.article_number] ?? null, className: "h-8 w-8 shrink-0" })] })) : null] }), _jsx(Input, { inputMode: "numeric", placeholder: "Aantal", value: l.quantity == null ? "" : String(l.quantity), onChange: (e) => {
463
+ }, onFreeText: (t) => updateLine(i, { description: t }) }), l.article_number ? (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsxs("p", { className: "truncate text-xs text-muted-foreground", children: ["Artikelcode: ", l.article_number, " · ", (() => {
464
+ const pc = prijzen[l.article_number];
465
+ if (pc == null)
466
+ return l.article_number in prijzen ? "geen prijs" : "";
467
+ const q = l.quantity == null ? 1 : Number(l.quantity) || 0;
468
+ return `${euro(pc)} × ${q} = ${euro(pc * q)}`;
469
+ })()] }), _jsx(ArtikelFoto, { url: fotos[l.article_number] ?? null, className: "h-8 w-8 shrink-0" })] })) : null] }), _jsx(Input, { inputMode: "numeric", placeholder: "Aantal", value: l.quantity == null ? "" : String(l.quantity), onChange: (e) => {
397
470
  const n = Number(e.target.value);
398
471
  updateLine(i, {
399
472
  quantity: e.target.value === "" || Number.isNaN(n) ? null : n,
@@ -411,12 +484,34 @@ export function WerkbonProposalForm({ value, options, saving, analysing = false,
411
484
  estimated_duration_minutes: combineDuration(e.target.value, durationMinutes(value.estimated_duration_minutes)),
412
485
  }) }), _jsx("span", { className: "text-xs text-muted-foreground", children: "uur" })] }), _jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Input, { inputMode: "numeric", placeholder: "0", "aria-label": "Minuten", value: durationMinutes(value.estimated_duration_minutes), onChange: (e) => onChange({
413
486
  estimated_duration_minutes: combineDuration(durationHours(value.estimated_duration_minutes), e.target.value),
414
- }) }), _jsx("span", { className: "text-xs text-muted-foreground", children: "min" })] })] }) })] }), _jsx(Field, { label: "Monteur", children: _jsx(OptionPicker, { value: value.technician_id, items: options.technicians, placeholder: "Kies een monteur\u2026", noun: "monteurs", onSelect: (id) => onChange({ technician_id: id }), onClear: () => onChange({ technician_id: null }) }) })] }), _jsx(Section, { title: "Interne notities", children: _jsx(Textarea, { rows: 3, value: value.internal_notes ?? "", placeholder: "Alleen zichtbaar voor collega's", onChange: (e) => onChange({ internal_notes: e.target.value || null }) }) })] }), !readOnly && showMandate && (_jsxs("div", { className: `shrink-0 border-t px-4 py-2 text-sm ${overMandate > 0
415
- ? "border-destructive/40 bg-destructive/10 text-destructive"
416
- : "border-border bg-muted/50 text-muted-foreground"}`, children: ["Totaal: ", formatEuroCents(totalCents ?? 0), " van mandaat ", formatEuroCents(mandateCents), overMandate > 0 && (_jsxs("span", { className: "font-semibold", children: [" \u2014 ", formatEuroCents(overMandate), " boven het mandaat"] }))] })), !readOnly && (_jsxs("div", { className: "grid shrink-0 grid-cols-[minmax(0,1fr)_auto] gap-2 border-t border-border p-4", children: [_jsx(Button, { className: "w-full", onClick: onConfirm, disabled: saving ||
487
+ }) }), _jsx("span", { className: "text-xs text-muted-foreground", children: "min" })] })] }) })] }), _jsx(Field, { label: "Monteur", children: _jsx(OptionPicker, { value: value.technician_id, items: options.technicians, placeholder: "Kies een monteur\u2026", noun: "monteurs", onSelect: (id) => onChange({ technician_id: id }), onClear: () => onChange({ technician_id: null }) }) })] }), _jsx(Section, { title: "Interne notities", children: _jsx(Textarea, { rows: 3, value: value.internal_notes ?? "", placeholder: "Alleen zichtbaar voor collega's", onChange: (e) => onChange({ internal_notes: e.target.value || null }) }) })] }), !readOnly && mandateCents > 0 && (_jsx("div", { className: "shrink-0 border-t border-border px-4 py-2", children: _jsx(MandaatBalk, { totalCents: totalCents ?? 0, mandateCents: mandateCents }) })), !readOnly && klantBlocked && (_jsxs("div", { className: "shrink-0 border-t border-destructive/40 bg-destructive/10 px-4 py-2 text-sm text-destructive", children: [_jsx("p", { className: "font-semibold", children: "Hier kan je geen werkbon van aanmaken" }), klantNotes[0] && _jsxs("p", { children: ["Reden: ", klantNotes[0]] })] })), !readOnly && (_jsxs("div", { className: "grid shrink-0 grid-cols-[minmax(0,1fr)_auto] gap-2 border-t border-border p-4", children: [_jsx(Button, { className: "w-full", onClick: onConfirm, disabled: saving ||
417
488
  analysing ||
418
489
  overMandate > 0 ||
490
+ klantBlocked ||
419
491
  !value.customer_id ||
420
492
  value.estimated_duration_minutes == null ||
421
493
  value.estimated_duration_minutes <= 0, children: "Werkbon aanmaken" }), _jsx(Button, { variant: "outline", onClick: onReject, disabled: saving, children: "Afwijzen" })] }))] }));
422
494
  }
495
+ const euro = (cents) => new Intl.NumberFormat("nl-NL", { style: "currency", currency: "EUR" }).format(cents / 100);
496
+ function PackageLineInfo({ line, pkg, readOnly, onQuarters, }) {
497
+ if (!pkg)
498
+ return null;
499
+ const qty = line.quantity == null ? 1 : Number(line.quantity) || 0;
500
+ const price = Number(pkg.price_cents ?? 0) || 0;
501
+ const isBasis = !!pkg.badge;
502
+ const quarters = Math.max(0, Number(line.extra_quarters ?? 0) || 0);
503
+ const qPrice = pkg.extra_quarter_price_cents;
504
+ const quartersCents = quarters * (Number(qPrice ?? 0) || 0);
505
+ const travel = Number(pkg.travel_minutes ?? 0) || 0;
506
+ const lineTotal = price * qty + quartersCents;
507
+ return (_jsxs("div", { className: "space-y-1 pt-1 text-xs text-muted-foreground", children: [_jsxs("p", { children: [euro(price), " \u00D7 ", qty, " = ", _jsx("span", { className: "font-medium text-foreground", children: euro(price * qty) }), travel > 0 ? ` · Reistijd: ${travel * qty} min` : ""] }), isBasis && (_jsxs("div", { className: "space-y-1 rounded-md bg-muted/50 p-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-foreground", children: "Extra kwartieren" }), _jsx(Button, { type: "button", variant: "outline", size: "icon", className: "h-6 w-6", disabled: readOnly || quarters <= 0, onClick: () => onQuarters(quarters - 1 > 0 ? quarters - 1 : null), "aria-label": "Kwartier eraf", children: "\u2212" }), _jsx("span", { className: "w-6 text-center font-medium text-foreground", children: quarters }), _jsx(Button, { type: "button", variant: "outline", size: "icon", className: "h-6 w-6", disabled: readOnly, onClick: () => onQuarters(quarters + 1), "aria-label": "Kwartier erbij", children: "+" })] }), quarters > 0 && (_jsxs("p", { children: [quarters, " \u00D7 15 min = ", quarters * 15, " min \u00B7", " ", qPrice == null
508
+ ? "kwartierprijs niet ingesteld"
509
+ : `${quarters} × ${euro(qPrice)} = ${euro(quartersCents)}`] })), _jsxs("p", { children: ["Regeltotaal: ", _jsx("span", { className: "font-medium text-foreground", children: euro(lineTotal) })] })] }))] }));
510
+ }
511
+ function MandaatBalk({ totalCents, mandateCents }) {
512
+ const pct = mandateCents > 0 ? (totalCents / mandateCents) * 100 : 0;
513
+ const over = Math.max(0, totalCents - mandateCents);
514
+ const bar = pct > 100 ? "bg-destructive" : pct >= 75 ? "bg-orange-500" : "bg-primary";
515
+ const txt = pct > 100 ? "text-destructive" : pct >= 75 ? "text-orange-700" : "text-muted-foreground";
516
+ return (_jsxs("div", { className: "space-y-1 pt-1", children: [_jsxs("p", { className: `text-xs ${txt}`, children: [formatEuroCents(totalCents), " van ", formatEuroCents(mandateCents), " (", Math.round(pct), "%)", over > 0 && _jsxs("span", { className: "font-semibold", children: [" \u2014 ", formatEuroCents(over), " boven het mandaat"] })] }), _jsx("div", { className: "h-2 w-full overflow-hidden rounded-full bg-muted", children: _jsx("div", { className: `h-full ${bar} transition-all`, style: { width: `${Math.min(100, pct)}%` } }) })] }));
517
+ }
@@ -1,6 +1,12 @@
1
- export declare function brokeredPreviewStorage(): Storage | {
2
- getItem: (key: string) => Promise<string | null>;
3
- setItem: (key: string, value: string) => Promise<void>;
4
- removeItem: (key: string) => Promise<undefined>;
5
- } | undefined;
1
+ /** Storage accepted by Supabase's `auth.storage` option; `localStorage` and the editor broker both satisfy it. */
2
+ export interface PreviewAuthStorage {
3
+ getItem: (key: string) => string | null | Promise<string | null>;
4
+ setItem: (key: string, value: string) => void | Promise<void>;
5
+ removeItem: (key: string) => void | Promise<void>;
6
+ }
7
+ /**
8
+ * On a Lovable preview surface, broker the auth session to the editor over
9
+ * postMessage so the project's preview surfaces share one login; else localStorage.
10
+ */
11
+ export declare function brokeredPreviewStorage(): PreviewAuthStorage | undefined;
6
12
  //# sourceMappingURL=previewAuthStorage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"previewAuthStorage.d.ts","sourceRoot":"","sources":["../../../src/integrations/supabase/previewAuthStorage.ts"],"names":[],"mappings":"AAIA,wBAAgB,sBAAsB;mBA2Db,MAAM;mBAeZ,MAAM,SAAS,MAAM;sBASlB,MAAM;cAK3B"}
1
+ {"version":3,"file":"previewAuthStorage.d.ts","sourceRoot":"","sources":["../../../src/integrations/supabase/previewAuthStorage.ts"],"names":[],"mappings":"AAEA,kHAAkH;AAClH,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACjE,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnD;AA6BD;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,kBAAkB,GAAG,SAAS,CAsGvE"}
@@ -1,6 +1,21 @@
1
1
  // This file is automatically generated. Do not edit it directly.
2
- // On a Lovable preview surface, broker the auth session to the editor over
3
- // postMessage so the project's preview surfaces share one login; else localStorage.
2
+ const RESULT = 'lovable-preview-auth:result';
3
+ function readBrokerReply(data, requestId) {
4
+ if (typeof data !== 'object' || data === null)
5
+ return null;
6
+ if (!('type' in data) || data.type !== RESULT)
7
+ return null;
8
+ if (!('requestId' in data) || data.requestId !== requestId)
9
+ return null;
10
+ return {
11
+ ok: 'ok' in data && Boolean(data.ok),
12
+ value: 'value' in data && typeof data.value === 'string' ? data.value : null,
13
+ };
14
+ }
15
+ /**
16
+ * On a Lovable preview surface, broker the auth session to the editor over
17
+ * postMessage so the project's preview surfaces share one login; else localStorage.
18
+ */
4
19
  export function brokeredPreviewStorage() {
5
20
  if (typeof window === 'undefined')
6
21
  return undefined;
@@ -11,10 +26,13 @@ export function brokeredPreviewStorage() {
11
26
  // preview--<name> host can't smuggle another project's id.
12
27
  const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
13
28
  const projectId = onPreviewZone
14
- ? (host.match(new RegExp('^(?:id-preview(?:-[a-z0-9]+)?|project)--(' + UUID + ')(?:-dev)?(?=\\.|$)', 'i'))?.[1]
15
- ?? host.match(new RegExp('^(' + UUID + ')(?=[.-])', 'i'))?.[1])
29
+ ? (new RegExp('^(?:id-preview(?:-[a-z0-9]+)?|project)--(' + UUID + ')(?:-dev)?(?=\\.|$)', 'i').exec(host)?.[1]
30
+ ?? new RegExp('^(' + UUID + ')(?=[.-])', 'i').exec(host)?.[1])
16
31
  : undefined;
17
- const framed = window.parent && window.parent !== window;
32
+ // lib.dom types window.parent and location.ancestorOrigins as always set, but a
33
+ // detached frame has no parent and not every browser implements ancestorOrigins.
34
+ const parentWindow = window.parent;
35
+ const framed = parentWindow !== null && parentWindow !== window;
18
36
  if (!projectId || !framed)
19
37
  return localStorage;
20
38
  // Post only to the real editor ancestor, validated as a Lovable origin, so the
@@ -23,59 +41,75 @@ export function brokeredPreviewStorage() {
23
41
  const EDITOR = dev
24
42
  ? /^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/
25
43
  : /^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/;
26
- const ancestor = (location.ancestorOrigins && location.ancestorOrigins[0]) || (document.referrer ? new URL(document.referrer).origin : '');
44
+ const ancestorOrigins = location.ancestorOrigins;
45
+ const ancestor = ancestorOrigins?.[0] ?? (document.referrer ? new URL(document.referrer).origin : '');
27
46
  const editorOrigins = ancestor && EDITOR.test(ancestor)
28
47
  ? [ancestor]
29
48
  : (dev ? ['https://lovable.dev', 'http://localhost:3000'] : ['https://lovable.dev']);
30
- const RESULT = 'lovable-preview-auth:result';
31
49
  const TIMEOUT = 2000;
32
50
  const newId = () => Math.random().toString(36).slice(2) + Date.now().toString(36);
33
51
  const request = (type, key, value) => new Promise((resolve) => {
34
52
  const requestId = newId();
35
53
  let done = false;
36
- let timer;
37
- const finish = (r) => {
54
+ const finish = (reply) => {
38
55
  if (done)
39
56
  return;
40
57
  done = true;
41
58
  clearTimeout(timer);
42
59
  window.removeEventListener('message', onMessage);
43
- resolve(r);
60
+ resolve(reply);
44
61
  };
45
62
  const onMessage = (e) => {
46
- if (editorOrigins.indexOf(e.origin) < 0)
63
+ if (!editorOrigins.includes(e.origin))
47
64
  return;
48
- const d = e.data;
49
- if (d && d.type === RESULT && d.requestId === requestId)
50
- finish(d);
65
+ const reply = readBrokerReply(e.data, requestId);
66
+ if (reply)
67
+ finish(reply);
51
68
  };
52
69
  window.addEventListener('message', onMessage);
70
+ const timer = setTimeout(() => { finish(null); }, TIMEOUT);
53
71
  const msg = { type, requestId, projectId, key };
54
72
  if (value !== undefined)
55
- msg['value'] = value;
73
+ msg.value = value;
56
74
  // targetOrigin per trusted editor origin, so a session token never reaches an arbitrary embedder.
57
75
  for (const origin of editorOrigins)
58
76
  window.parent.postMessage(msg, origin);
59
- timer = setTimeout(() => finish(null), TIMEOUT);
60
77
  });
61
78
  // The editor may not be listening yet at the first getItem, so retry once.
62
79
  let firstGet = true;
63
80
  const RETRY_DELAY = 250;
81
+ // Blocked third-party storage throws here; seeding must not break broker reads.
82
+ const readLocal = (key) => { try {
83
+ return localStorage.getItem(key);
84
+ }
85
+ catch {
86
+ return undefined;
87
+ } };
64
88
  return {
65
89
  getItem: async (key) => {
66
- let res = await request('lovable-preview-auth:get', key);
90
+ // Sent with GET and REMOVE so an editor that never cached this session can check or revoke it.
91
+ const local = readLocal(key);
92
+ let res = await request('lovable-preview-auth:get', key, local ?? undefined);
67
93
  if (!res && firstGet) {
68
- await new Promise((r) => setTimeout(r, RETRY_DELAY));
69
- res = await request('lovable-preview-auth:get', key);
94
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
95
+ res = await request('lovable-preview-auth:get', key, local ?? undefined);
70
96
  }
71
97
  firstGet = false;
72
98
  // '' is the logout tombstone: clear the local copy too so it can't resurrect if
73
- // the broker later goes silent. A null reply means never-synced -> keep local.
74
- if (res && res.ok && typeof res.value === 'string') {
99
+ // the broker later goes silent. A null value means never-synced -> keep local.
100
+ if (res?.ok && res.value !== null) {
75
101
  if (res.value === '') {
76
- localStorage.removeItem(key);
102
+ if (local !== undefined && readLocal(key) === local)
103
+ localStorage.removeItem(key);
77
104
  return null;
78
105
  }
106
+ // Seed this origin so a new tab, whose editor holds no session, stays signed in.
107
+ if (local === null && readLocal(key) === null) {
108
+ try {
109
+ localStorage.setItem(key, res.value);
110
+ }
111
+ catch { /* storage full: still return the editor's session */ }
112
+ }
79
113
  return res.value;
80
114
  }
81
115
  return localStorage.getItem(key);
@@ -83,7 +117,7 @@ export function brokeredPreviewStorage() {
83
117
  setItem: (key, value) => {
84
118
  localStorage.setItem(key, value);
85
119
  return request('lovable-preview-auth:set', key, value).then((res) => {
86
- if (res && res.ok && typeof res.value === 'string' && localStorage.getItem(key) === value) {
120
+ if (res?.ok && res.value !== null && localStorage.getItem(key) === value) {
87
121
  if (res.value === '')
88
122
  localStorage.removeItem(key);
89
123
  else
@@ -92,8 +126,9 @@ export function brokeredPreviewStorage() {
92
126
  });
93
127
  },
94
128
  removeItem: (key) => {
129
+ const local = readLocal(key);
95
130
  localStorage.removeItem(key);
96
- return request('lovable-preview-auth:remove', key).then(() => undefined);
131
+ return request('lovable-preview-auth:remove', key, local ?? undefined).then(() => { });
97
132
  },
98
133
  };
99
134
  }