@cardinali-studio/adminkit 2.2.49 → 2.2.50

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.
Files changed (63) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +67 -1
  3. package/dist/app/delivery.js +7 -7
  4. package/dist/app/guide/TransferGuide.js +1 -1
  5. package/dist/app/lib/deliveries.d.ts +6 -0
  6. package/dist/app/lib/delivery-capabilities.d.ts +31 -0
  7. package/dist/app/lib/delivery-capabilities.js +115 -0
  8. package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
  9. package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
  10. package/dist/app/lib/delivery-finalize.d.ts +21 -0
  11. package/dist/app/lib/delivery-finalize.js +42 -0
  12. package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
  13. package/dist/app/lib/delivery-multipart-large.js +28 -0
  14. package/dist/app/lib/delivery-network.d.ts +7 -1
  15. package/dist/app/lib/delivery-network.js +85 -18
  16. package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
  17. package/dist/app/lib/delivery-part-pipeline.js +270 -0
  18. package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
  19. package/dist/app/lib/delivery-upload-coordinator.js +229 -0
  20. package/dist/app/lib/delivery-upload.d.ts +19 -3
  21. package/dist/app/lib/delivery-upload.js +226 -29
  22. package/dist/app/lib/upload-queue.d.ts +5 -0
  23. package/dist/app/lib/upload-queue.js +54 -29
  24. package/dist/app/routes/Deliveries.d.ts +9 -3
  25. package/dist/app/routes/Deliveries.js +299 -164
  26. package/dist/app/routes/DeliveryDashboard.js +1 -1
  27. package/dist/app/routes/DeliveryEmail.d.ts +8 -1
  28. package/dist/app/routes/DeliveryEmail.js +63 -23
  29. package/dist/app/routes/Overview.js +5 -5
  30. package/dist/app/routes/UploadDock.js +4 -3
  31. package/dist/form/media/MediaGrid.js +1 -1
  32. package/dist/functions/_shared/b2.js +98 -19
  33. package/dist/functions/_shared/delivery-activation.js +98 -0
  34. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  35. package/dist/functions/_shared/delivery-email.js +92 -13
  36. package/dist/functions/_shared/delivery-file-names.js +19 -0
  37. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  38. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  39. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  40. package/dist/functions/_shared/delivery-manifest.js +277 -20
  41. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  42. package/dist/functions/_shared/delivery-request.js +74 -0
  43. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  44. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  45. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  46. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  47. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  48. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  49. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  50. package/dist/functions/api/deliveries.js +58 -17
  51. package/dist/functions/api/delivery/multipart.js +152 -15
  52. package/dist/functions/delivery-public/assets/client.js +59 -54
  53. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  54. package/dist/functions/delivery-public/index.js +43 -15
  55. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  56. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  57. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  58. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  59. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  60. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  61. package/dist/functions/index.js +3 -1
  62. package/dist/theme.css +2 -1
  63. package/package.json +1 -1
@@ -1,34 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { DeliveryEmailConfiguration, DeliveryEmail, saveTransferEmailPreferences } from "./DeliveryEmail";
3
- /* Consegne — l'interfaccia.
4
- *
5
- * UNA schermata sola per un transfer, che sia nuovo o già spedito: prima c'erano due form
6
- * diversi per lo stesso oggetto, con etichette diverse per lo stesso campo e — il peggio —
7
- * default opposti sugli stessi due interruttori. Qui il transfer nuovo è semplicemente questa
8
- * schermata con i campi vuoti.
9
- *
10
- * La forma viene da WeTransfer, allargata allo spazio che abbiamo: a sinistra la colonna del
11
- * lavoro (file, nome, messaggio, link), a destra le opzioni raggruppate. Sotto, a piena
12
- * larghezza, la copertina — che ha bisogno di una griglia di foto e in una colonna stretta non
13
- * ci sta.
14
- *
15
- * Due parole che NON esistono più, e perché:
16
- * «attivazione» non corrispondeva a niente che l'utente volesse fare. Il link funziona da
17
- * quando esiste; lo stato («in preparazione» → «pronto») lo sa già il sistema
18
- * e adesso se lo calcola invece di farselo dire con un pulsante. `activate`
19
- * resta nell'API e lo chiama il salvataggio quando i file sono a posto.
20
- * «pacchetto» nel 95% dei casi ce n'è uno solo: non ha bisogno di un nome proprio. Si
21
- * chiama «file», e l'etichetta la eredita dal nome del transfer.
22
- *
23
- * Il vocabolario completo (e il perché di ogni parola) sta in DELIVERY-REDESIGN.md §2.
24
- */
25
3
  import { useEffect, useRef, useState } from "react";
26
- import { deliverySelectionName, deliverySourceFingerprint, uploadDeliveryHeroObject, preflightDeliverySelection, } from "../lib/delivery-upload";
4
+ import { assertUploadCoordinatorSelection, prepareUploadSession, validateNewUploadNegotiation } from '../lib/delivery-upload-coordinator.js';
5
+ import { deliveryProgressPercent, deliveryRelativeName, deliverySelectionName, deliverySourceFingerprint, uploadDeliveryHeroObject, preflightDeliverySelection, } from "../lib/delivery-upload";
27
6
  import { isBusy, startUpload, uploadFor, useUploadCompletions, useUploads, } from "../lib/upload-queue";
7
+ import { Icon } from "../ui/icons.js";
8
+ import { transferErrorMessage as errorText } from "../lib/delivery-network.js";
28
9
  import { filesFromDrop } from "../lib/delivery-drop";
29
10
  /* ============================================================================================
30
11
  La colonna: elenco dei transfer
31
12
  ========================================================================================== */
13
+ export function DeliveryNavHeading({ settingsOpen, onSettings }) {
14
+ return _jsxs("div", { className: "dl-col-heading", children: [_jsx("span", { className: "col-title", children: "Transfer" }), _jsx("button", { type: "button", className: "dl-settings-shortcut", "aria-label": "Impostazioni Transfer", title: "Impostazioni Transfer", "aria-current": settingsOpen ? "page" : undefined, onClick: onSettings, children: _jsx(Icon.settings, {}) })] });
15
+ }
32
16
  export function NewDeliveryButton({ onCreate, disabled }) {
33
17
  return (_jsx("button", { className: "ak-btn ak-btn-primary", disabled: disabled, onClick: onCreate, children: "Nuovo transfer" }));
34
18
  }
@@ -46,7 +30,7 @@ export function DeliveriesTotal({ rows }) {
46
30
  const bytes = rows.reduce((sum, row) => sum + (row.storedBytes || 0), 0);
47
31
  return (_jsxs("p", { className: "dl-total", children: [rows.length, " transfer \u00B7 ", formatBytes(bytes)] }));
48
32
  }
49
- export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefresh, onReload, onRead, onDeleted, onOpen, onSelected, }) {
33
+ export function DeliveryWorkspace({ delivery: fromServer, defaultHeroes = [], busy, onAction, onRefresh, onReload, onRead, onDeleted, onOpen, onSelected, }) {
50
34
  /* Il transfer «corrente» può venire dal server (l'ho aperto dall'elenco) o essere nato qui
51
35
  dentro al primo file rilasciato. Nel secondo caso resta in questo stato finché non si
52
36
  ricarica l'elenco. */
@@ -57,15 +41,49 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
57
41
  const [heroes, setHeroes] = useState(fromServer?.heroes || []);
58
42
  const [heroesClean, setHeroesClean] = useState(fromServer?.heroes || []);
59
43
  const [saving, setSaving] = useState(false);
44
+ const [activityTarget, setActivityTarget] = useState(null);
60
45
  const [emailPreferences, setEmailPreferences] = useState({ recipientEmail: '', notifyOwner: false, sendRecipient: false });
61
46
  const [emailClean, setEmailClean] = useState({ recipientEmail: '', notifyOwner: false, sendRecipient: false });
62
47
  const emailDirty = JSON.stringify(emailPreferences) !== JSON.stringify(emailClean);
63
48
  const persistEmail = async (id) => {
64
- if (emailDirty || emailPreferences.recipientEmail || emailPreferences.notifyOwner || emailPreferences.sendRecipient) {
49
+ if (emailDirty) {
65
50
  await saveTransferEmailPreferences(id, emailPreferences);
66
51
  setEmailClean({ ...emailPreferences });
67
52
  }
68
53
  };
54
+ const [advanced, setAdvanced] = useState(false);
55
+ const [filesShown, setFilesShown] = useState(12);
56
+ const [selection, setSelection] = useState([]);
57
+ const [coverFiles, setCoverFiles] = useState([]);
58
+ const [preparing, setPreparing] = useState(false);
59
+ const [coverPreview, setCoverPreview] = useState("");
60
+ useEffect(() => {
61
+ const url = coverFiles[0] ? URL.createObjectURL(coverFiles[0]) : "";
62
+ setCoverPreview(url);
63
+ return () => { if (url)
64
+ URL.revokeObjectURL(url); };
65
+ }, [coverFiles]);
66
+ const background = coverPreview || heroes[0]?.previewUrl || defaultHeroes[0];
67
+ const quickFields = useRef(null);
68
+ const fileInputs = useRef(null);
69
+ const optionsTitle = useRef(null);
70
+ const toggleRef = useRef(null);
71
+ useEffect(() => {
72
+ if (!advanced)
73
+ return;
74
+ optionsTitle.current?.focus();
75
+ const dismiss = (event) => {
76
+ if (event.key !== "Escape" || event.defaultPrevented)
77
+ return;
78
+ const workspace = toggleRef.current?.closest(".dl-work");
79
+ if (event.target !== document.body && event.target instanceof Node && !workspace?.contains(event.target))
80
+ return;
81
+ setAdvanced(false);
82
+ toggleRef.current?.focus();
83
+ };
84
+ window.addEventListener("keydown", dismiss);
85
+ return () => window.removeEventListener("keydown", dismiss);
86
+ }, [advanced]);
69
87
  const [jpegEnabled, setJpegEnabled] = useState(false);
70
88
  const [downloadLabelsEnabled, setDownloadLabelsEnabled] = useState(false);
71
89
  useEffect(() => {
@@ -91,8 +109,6 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
91
109
  const [loadingImages, setLoadingImages] = useState(false);
92
110
  const [previewAttempt, setPreviewAttempt] = useState(0);
93
111
  const [copied, setCopied] = useState(null);
94
- const folderRef = useRef(null);
95
- const filesRef = useRef(null);
96
112
  const coverRef = useRef(null);
97
113
  const resumeRef = useRef(null);
98
114
  const startingRef = useRef(false);
@@ -103,7 +119,7 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
103
119
  React, così uscire da questa schermata non lo interrompe. Qui lo si guarda e basta. */
104
120
  const jobs = useUploads();
105
121
  const job = delivery ? uploadFor(delivery.id, jobs) : undefined;
106
- const uploading = isBusy(job) || startingRef.current;
122
+ const uploading = isBusy(job) || preparing;
107
123
  const heroesDirty = !sameHeroes(heroes, heroesClean);
108
124
  const dirty = !same(draft, clean) || heroesDirty || emailDirty;
109
125
  const photos = packages.filter(pkg => pkg.state === "ready").flatMap((pkg) => [...pkg.images, ...(moreImages[pkg.id]?.images || [])].map((image) => ({ pkg, image })));
@@ -132,18 +148,16 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
132
148
  }
133
149
  }
134
150
  useEffect(() => { setMoreImages({}); }, [delivery?.id]);
151
+ const editingSnapshot = useRef(fromServer);
135
152
  useEffect(() => {
136
- if (!fromServer)
153
+ if (!fromServer || fromServer === editingSnapshot.current || dirty)
137
154
  return;
155
+ editingSnapshot.current = fromServer;
138
156
  setDraft(draftOf(fromServer));
139
157
  setClean(draftOf(fromServer));
140
158
  setHeroes(fromServer.heroes);
141
159
  setHeroesClean(fromServer.heroes);
142
- }, [fromServer]);
143
- useEffect(() => {
144
- folderRef.current?.setAttribute("webkitdirectory", "");
145
- folderRef.current?.setAttribute("directory", "");
146
- }, []);
160
+ }, [fromServer, dirty]);
147
161
  /* Quando un caricamento finisce — anche mentre si stava guardando un'altra sezione — questa
148
162
  schermata rilegge il proprio transfer: i file appena chiusi devono comparire senza che
149
163
  nessuno ricarichi niente a mano. */
@@ -163,24 +177,32 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
163
177
  Il caricamento vero, la chiusura del pacchetto e l'attivazione li fa la coda,
164
178
  che non muore quando questa schermata sparisce. */
165
179
  const beginUpload = async (files, resume = null) => {
166
- if (!files.length || startingRef.current)
180
+ if (!files.length || startingRef.current || isBusy(job) || !quickFields.current?.reportValidity())
167
181
  return;
182
+ setPreparing(true);
168
183
  startingRef.current = true;
169
184
  setFailure(null);
170
185
  setNotice(null);
171
186
  let target = delivery;
172
187
  let packageId = resume?.id || "";
188
+ let uploadSession = resume?.uploadSession;
173
189
  let options = resume ? { galleryEnabled: resume.galleryEnabled, webEnabled: resume.webEnabled, webFormat: resume.webFormat || "webp" } : { galleryEnabled: draft.gallery, webEnabled: draft.light, webFormat: draft.light ? draft.webFormat : "webp" };
174
190
  try {
191
+ assertUploadCoordinatorSelection(uploadSession);
175
192
  // Verifica i limiti fisici prima della richiesta delle capacità del sito.
176
- preflightDeliverySelection(files, { ...options, manifestVersion: 2 });
177
- const capabilities = resume ? { manifestVersion: resume.manifestVersion || 1 } :
193
+ const checked = preflightDeliverySelection(files, { ...options, manifestVersion: 2 });
194
+ const capabilities = resume && !uploadSession ? { manifestVersion: resume.manifestVersion || 1 } :
178
195
  await onAction({ action: "capabilities" }, { reload: false });
196
+ if (!resume)
197
+ validateNewUploadNegotiation(capabilities);
179
198
  options.manifestVersion = capabilities.manifestVersion;
180
- const { sourceBytes } = preflightDeliverySelection(files, options);
199
+ const { sourceBytes } = options.manifestVersion === 2 ? checked : preflightDeliverySelection(files, options);
181
200
  /* L'impronta si legge PRIMA di creare qualsiasi cosa: se il browser ha perso il
182
201
  permesso su un file, non resta un transfer a metà né un oggetto orfano. */
183
202
  const fingerprint = await deliverySourceFingerprint(files, options.manifestVersion);
203
+ if (resume && resume.sourceFingerprint !== fingerprint) {
204
+ throw new Error("Questi non sono gli stessi file di prima. Riseleziona la cartella o i file del caricamento interrotto.");
205
+ }
184
206
  const title = draft.title.trim() || deliverySelectionName(files) || "Transfer";
185
207
  if (!target) {
186
208
  change({ title });
@@ -191,55 +213,91 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
191
213
  setMade(target);
192
214
  }
193
215
  await persistEmail(target.id);
194
- { // Save the current delivery details before site-wide ready notifications can be queued.
195
- target = (await onAction({ action: 'update', id: target.id, version: target.version, title,
216
+ // quickCreate already persists title, expiry and download labels.
217
+ const detailsChanged = delivery ? !same(draft, clean) :
218
+ !!(draft.clientName || draft.description || draft.licenseNotes || draft.ctaEnabled);
219
+ if (detailsChanged) {
220
+ target = (await onAction({
221
+ action: "update", id: target.id, version: editingSnapshot.current?.version ?? target.version, title,
196
222
  clientName: draft.clientName, description: draft.description, licenseNotes: draft.licenseNotes,
197
- ctaEnabled: draft.ctaEnabled, ctaLabel: draft.ctaLabel, ctaUrl: draft.ctaUrl, expiresAt: target.expiresAt,
198
- filesExpiresAt: draft.duration === 'keep' ? target.filesExpiresAt : expiryFrom(draft.duration),
223
+ ctaEnabled: draft.ctaEnabled, ctaLabel: draft.ctaLabel, ctaUrl: draft.ctaUrl,
224
+ ...(downloadLabelsEnabled ? { downloadOriginalsLabel: draft.downloadOriginalsLabel, downloadWebLabel: draft.downloadWebLabel } : {}),
225
+ expiresAt: target.expiresAt, filesExpiresAt: draft.duration === "keep" ? target.filesExpiresAt : expiryFrom(draft.duration),
199
226
  }, { reload: false })).delivery;
200
- const currentLink = primaryLink(target);
201
- if (!currentLink)
202
- await onAction({ action: 'createLink', id: target.id, label: 'Link del cliente', pin: draft.pin }, { reload: false });
203
- else if ((currentLink.pin || '') !== draft.pin)
204
- await onAction({ action: 'updateLink', id: target.id, linkId: currentLink.id, label: currentLink.label, pin: draft.pin, expiresAt: currentLink.expiresAt }, { reload: false });
205
227
  }
228
+ const currentLink = primaryLink(target);
229
+ if (!currentLink)
230
+ await onAction({ action: "createLink", id: target.id, label: "Link del cliente", pin: draft.pin }, { reload: false });
231
+ else if ((currentLink.pin || "") !== draft.pin)
232
+ await onAction({ action: "updateLink", id: target.id,
233
+ linkId: currentLink.id, label: currentLink.label, pin: draft.pin, expiresAt: currentLink.expiresAt }, { reload: false });
206
234
  if (resume) {
207
- if (resume.sourceFingerprint !== fingerprint) {
208
- throw new Error("Questi non sono gli stessi file di prima. Riseleziona esattamente la cartella " +
209
- "(o i file) del caricamento interrotto.");
210
- }
211
235
  options = { galleryEnabled: resume.galleryEnabled, webEnabled: resume.webEnabled, webFormat: resume.webFormat || "webp", manifestVersion: resume.manifestVersion || 1 };
212
236
  }
213
237
  else {
214
- const created = await onAction({
215
- action: "createPackage", id: target.id, label: title,
216
- ...options, sourceFingerprint: fingerprint, fileCount: files.length,
217
- sourceBytes,
218
- }, { reload: false });
219
- packageId = created.package.id;
220
- options.webFormat = created.package.webFormat || "webp";
238
+ const session = await prepareUploadSession({ id: target.id, label: title,
239
+ sourceFingerprint: fingerprint, fileCount: files.length, sourceBytes, ...options }, capabilities, { gate: async () => { } });
240
+ if (session) {
241
+ packageId = session.packageId;
242
+ uploadSession = { version: 1, id: packageId, contractHash: session.contractHash };
243
+ }
244
+ else {
245
+ const created = await onAction({
246
+ action: "createPackage", id: target.id, label: title,
247
+ ...options, sourceFingerprint: fingerprint, fileCount: files.length,
248
+ sourceBytes,
249
+ }, { reload: false });
250
+ packageId = created.package.id;
251
+ options.webFormat = created.package.webFormat || "webp";
252
+ }
221
253
  }
222
- const completion = startUpload({ deliveryId: target.id, packageId, title, files, options });
254
+ if (coverFiles.length || heroesDirty) {
255
+ const nextHeroes = coverFiles.length ? [] : heroes;
256
+ for (const file of coverFiles) {
257
+ const uploaded = await uploadDeliveryHeroObject(target.id, packageId, file);
258
+ nextHeroes.push({ ...uploaded, previewUrl: "" });
259
+ }
260
+ target = (await onAction({
261
+ action: "commitHeroes", id: target.id, version: target.version, heroes: nextHeroes,
262
+ }, { reload: false })).delivery;
263
+ setHeroes(target.heroes);
264
+ setHeroesClean(target.heroes);
265
+ setCoverFiles([]);
266
+ }
267
+ // Metadata, link and cover are already saved, including when adding a
268
+ // package to an existing transfer. The next detail read can adopt its version.
269
+ const savedDraft = { ...draft, title, duration: "keep" };
270
+ setDraft(savedDraft);
271
+ setClean(savedDraft);
272
+ setSelection([]);
273
+ resumeRef.current = null;
274
+ const completion = startUpload({ deliveryId: target.id, packageId, title, files, options, uploadSession, sourceFingerprint: fingerprint });
223
275
  try {
224
- await refreshAll(target.id);
276
+ await refreshAll(target.id, true);
225
277
  }
226
278
  finally {
227
- startingRef.current = false;
228
279
  await completion;
280
+ fileInputs.current?.replaceChildren();
229
281
  }
230
282
  }
231
283
  catch (error) {
232
- setFailure(uploadFailure(error) + (packageId
284
+ setFailure(errorText(error) + (packageId
233
285
  ? " Il caricamento resta qui sotto: puoi riprenderlo riselezionando gli stessi file."
234
286
  : ""));
235
- if (target)
287
+ if (target) {
236
288
  await refreshAll(target.id).catch(() => { });
289
+ if (packageId) {
290
+ const fresh = await onRead(target.id);
291
+ resumeRef.current = fresh?.packages.find(pkg => pkg.id === packageId) || resume;
292
+ }
293
+ }
237
294
  }
238
295
  finally {
239
296
  startingRef.current = false;
297
+ setPreparing(false);
240
298
  }
241
299
  };
242
- const refreshAll = async (id) => {
300
+ const refreshAll = async (id, syncDraft = false) => {
243
301
  if (fromServer) {
244
302
  await onRefresh();
245
303
  return;
@@ -252,36 +310,41 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
252
310
  const fresh = await onRead(id);
253
311
  if (fresh) {
254
312
  setMade(fresh);
255
- setClean(draftOf(fresh, draft));
313
+ const saved = draftOf(fresh, draft);
314
+ setClean(saved);
315
+ if (syncDraft)
316
+ setDraft(saved);
256
317
  setHeroesClean(fresh.heroes);
257
318
  }
258
319
  };
259
- const picked = (event) => {
260
- const input = event.currentTarget;
261
- const files = [...(input.files || [])];
262
- const resume = resumeRef.current;
263
- resumeRef.current = null;
264
- /* Safari può revocare i riferimenti File appena si azzera l'input, anche se la FileList
265
- è già stata copiata: si svuota SOLO a lettura finita. */
266
- if (files.length)
267
- void beginUpload(files, resume).finally(() => { input.value = ""; });
320
+ const addFiles = (files) => {
321
+ if (!files.length || startingRef.current)
322
+ return;
323
+ setFailure(null);
324
+ setSelection(current => [...current, ...files]);
268
325
  };
269
- const choose = (input, resume = resumeRef.current) => {
270
- resumeRef.current = resume;
271
- if (input)
272
- input.value = "";
273
- input?.click();
326
+ // Keep each native input alive until the queue has finished reading its files (Safari).
327
+ const choose = (folder) => {
328
+ const input = document.createElement("input");
329
+ input.type = "file";
330
+ input.multiple = true;
331
+ if (folder)
332
+ input.setAttribute("webkitdirectory", "");
333
+ input.onchange = () => addFiles(Array.from(input.files || []));
334
+ input.oncancel = () => input.remove();
335
+ fileInputs.current?.append(input);
336
+ input.click();
274
337
  };
275
338
  /* ---- salvataggio: uno solo, che fa tutto ------------------------------------------- */
276
339
  const save = async () => {
277
- if (!delivery)
340
+ if (!delivery || !quickFields.current?.reportValidity())
278
341
  return;
279
342
  setSaving(true);
280
343
  setFailure(null);
281
344
  setNotice(null);
282
345
  try {
283
346
  const updated = (await onAction({
284
- action: "update", id: delivery.id, version: delivery.version, title: draft.title.trim() || delivery.title,
347
+ action: "update", id: delivery.id, version: editingSnapshot.current?.version ?? delivery.version, title: draft.title.trim() || delivery.title,
285
348
  clientName: draft.clientName, description: draft.description,
286
349
  licenseNotes: draft.licenseNotes, ctaEnabled: draft.ctaEnabled,
287
350
  ctaLabel: draft.ctaLabel, ctaUrl: draft.ctaUrl, syncPackageLabel: true,
@@ -337,11 +400,17 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
337
400
  };
338
401
  const uploadCovers = async (event) => {
339
402
  const input = event.currentTarget;
340
- const files = [...(input.files || [])].filter((f) => /\.(jpe?g|png|webp)$/i.test(f.name)).slice(0, 8);
341
- const pkg = packages.find((item) => item.state === "ready");
342
- if (!files.length || !pkg || !delivery) {
343
- input.value = "";
344
- setFailure(pkg ? "Scegli almeno un'immagine JPEG, PNG o WebP" : "Prima carica i file del transfer");
403
+ const files = Array.from(input.files || []);
404
+ if (!files.length)
405
+ return;
406
+ if (files.length > 8 || files.some(file => !/\.(jpe?g|png|webp)$/i.test(file.name))) {
407
+ setFailure("Scegli fino a otto immagini JPEG, PNG o WebP.");
408
+ return;
409
+ }
410
+ const pkg = packages.find(item => item.state === "ready");
411
+ if (!pkg || !delivery) {
412
+ setCoverFiles(files);
413
+ setFailure(null);
345
414
  return;
346
415
  }
347
416
  setSaving(true);
@@ -402,67 +471,107 @@ export function DeliveryWorkspace({ delivery: fromServer, busy, onAction, onRefr
402
471
  }
403
472
  };
404
473
  const copy = async (value, what) => {
405
- await navigator.clipboard.writeText(value);
474
+ try {
475
+ await navigator.clipboard.writeText(value);
476
+ }
477
+ catch {
478
+ setFailure("Copia non disponibile. Seleziona il link e copialo manualmente.");
479
+ return;
480
+ }
406
481
  setCopied(what);
407
482
  setTimeout(() => setCopied(null), 2000);
408
483
  };
409
484
  const state = delivery ? transferState(delivery) : null;
410
485
  const expiry = draft.duration === "keep"
411
486
  ? delivery?.filesExpiresAt || null : expiryFrom(draft.duration);
412
- return (_jsxs("div", { className: "dl-work", children: [_jsxs("header", { className: "dl-work-head", children: [_jsxs("div", { className: "dl-work-title", children: [state && _jsx("span", { className: "dl-pill is-" + state.kind, children: state.label }), _jsx("h2", { children: draft.title.trim() || (delivery ? delivery.title : "Nuovo transfer") })] }), _jsxs("div", { className: "dl-work-actions", children: [link && (_jsx("a", { className: "ak-btn", href: link.url, target: "_blank", rel: "noreferrer", children: "Guarda come lo vede il cliente" })), link && (_jsx("button", { className: "ak-btn ak-btn-primary", disabled: !dirty || saving || busy, onClick: () => void save(), children: saving ? "Salvo…" : "Salva" }))] })] }), (failure || notice) && (_jsxs("p", { className: failure ? "ak-error dl-feedback" : "dl-feedback is-ok", children: [failure || notice, _jsx("button", { type: "button", "aria-label": "Chiudi", onClick: () => { setFailure(null); setNotice(null); }, children: "\u00D7" })] })), _jsxs("div", { className: "dl-grid", children: [_jsxs("div", { className: "dl-main", children: [_jsx(DeliveryEmail, { id: delivery?.id, value: emailPreferences, onChange: setEmailPreferences, busy: saving || uploading, unsaved: dirty, onState: p => { setEmailPreferences(p); setEmailClean(p); } }), _jsxs(Group, { title: "Opzioni di consegna", note: packages.length
413
- ? "Le opzioni dei file caricati sono bloccate. Per cambiarle, rimuovi e ricarica i file."
414
- : "Scegli prima di aggiungere i file. Gli originali sono sempre inclusi.", children: [_jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.gallery, disabled: !!packages.length, onChange: (e) => change({ gallery: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Galleria" }), _jsx("small", { children: "Mostra le foto in anteprima sulla pagina del transfer." })] })] }), _jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.light, disabled: !!packages.length, onChange: (e) => change({ light: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Aggiungi conversione in bassa risoluzione" }), _jsx("small", { children: "Aggiunge un download per web e social, fino a 2048 px sul lato lungo." })] })] }), draft.light && (_jsxs("label", { className: "dl-field", children: [_jsx("span", { children: "Formato della conversione" }), _jsxs("select", { className: "dl-select", "aria-label": "Formato della conversione", value: draft.webFormat, disabled: !!packages.length || uploading, onChange: (e) => change({ webFormat: e.target.value === "jpg" ? "jpg" : "webp" }), children: [_jsx("option", { value: "webp", children: "WebP \u2014 file pi\u00F9 piccoli" }), _jsx("option", { value: "jpg", disabled: !jpegEnabled && draft.webFormat !== "jpg", children: "JPG \u2014 massima compatibilit\u00E0" })] }), _jsxs("small", { children: ["2048 px sul lato lungo, senza ingrandire le foto pi\u00F9 piccole. Qualit\u00E0 ", draft.webFormat === "jpg" ? "82%" : "80%", "."] })] }))] }), _jsxs("section", { className: "dl-card dl-upload-card", "aria-labelledby": "dl-files-heading", children: [_jsxs("div", { className: "dl-section-head", children: [_jsx("h3", { id: "dl-files-heading", children: "File da consegnare" }), _jsx("p", { children: "Fino a 150 GB per transfer. Il caricamento inizia appena scegli i file." })] }), _jsxs("div", { className: "dl-pick", children: [_jsxs("button", { className: "dl-pick-tile", disabled: uploading, onClick: () => choose(filesRef.current), children: [_jsx(FileIcon, {}), "Aggiungi file"] }), _jsxs("button", { className: "dl-pick-tile", disabled: uploading, onClick: () => choose(folderRef.current), children: [_jsx(FolderIcon, {}), "Aggiungi una cartella"] }), _jsx("input", { ref: folderRef, type: "file", multiple: true, hidden: true, onChange: picked }), _jsx("input", { ref: filesRef, type: "file", multiple: true, hidden: true, onChange: picked })] }), _jsx(DropArea, { disabled: uploading, resuming: !!resumeRef.current, onFiles: (files) => {
415
- const resume = resumeRef.current;
416
- resumeRef.current = null;
417
- void beginUpload(files, resume);
418
- }, onError: (error) => setFailure(errorText(error)) }), job && isBusy(job) && _jsx(Progress, { job: job }), !!packages.length && (_jsx("ul", { className: "dl-files", children: packages.map((pkg) => (_jsxs("li", { className: "dl-file is-" + pkg.state + (confirmPackage === pkg.id ? " is-confirming" : ""), children: [_jsx("span", { className: "dl-file-icon", "aria-hidden": "true", children: pkg.state === "ready" ? "✓" : "…" }), confirmPackage === pkg.id ? (_jsxs(_Fragment, { children: [_jsxs("span", { className: "dl-file-main", children: [_jsxs("strong", { children: ["Rimuovo ", pkg.fileCount || "questi", " file?"] }), _jsx("span", { children: "Spariscono adesso, e non si torna indietro." })] }), _jsxs("span", { className: "dl-file-actions", children: [_jsx("button", { className: "ak-btn", onClick: () => setConfirmPackage(null), children: "Annulla" }), _jsx("button", { className: "ak-btn dl-danger-btn", disabled: uploading, onClick: () => {
419
- setConfirmPackage(null);
420
- void run({ action: "deletePackage", id: delivery?.id, packageId: pkg.id }, "File rimossi");
421
- }, children: "S\u00EC, rimuovi" })] })] })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "dl-file-main", children: [_jsxs("strong", { children: [pkg.fileCount || "—", " file \u00B7 ", formatBytes(pkg.sourceBytes)] }), _jsx("span", { children: pkg.state === "ready"
422
- ? [pkg.galleryEnabled ? "si vedono sulla pagina" : "", pkg.webEnabled ? "versione leggera" : ""]
423
- .filter(Boolean).join(" · ") || "solo originali"
424
- : job?.id === pkg.id && isBusy(job)
425
- ? (job.state === "paused" ? "caricamento in pausa" : "caricamento in corso")
426
- : "caricamento interrotto" })] }), _jsxs("span", { className: "dl-file-actions", children: [pkg.state !== "ready" && !(job?.id === pkg.id && isBusy(job)) && (_jsx("button", { className: "ak-btn", disabled: uploading, onClick: () => { resumeRef.current = pkg; setNotice(resumeHint); }, children: "Riprendi" })), !(job?.id === pkg.id && isBusy(job)) && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: uploading, onClick: () => setConfirmPackage(pkg.id), children: "Rimuovi" }))] })] }))] }, pkg.id))) }))] }), _jsxs("section", { className: "dl-card dl-about", children: [_jsxs("div", { className: "dl-section-head", children: [_jsx("h3", { children: "Dettagli del transfer" }), _jsx("p", { children: "Queste informazioni saranno visibili al destinatario." })] }), _jsx(Field, { label: "Nome del transfer", hint: "Usato anche per il nome del file ZIP.", children: _jsx("input", { value: draft.title, placeholder: "Es. Team building \u2014 Milano", onChange: (e) => change({ title: e.target.value }) }) }), _jsx(Field, { label: "Destinatario", hint: "Nome del cliente o dell\u2019azienda. Facoltativo.", children: _jsx("input", { value: draft.clientName, placeholder: "Es. Azienda Rossi", onChange: (e) => change({ clientName: e.target.value }) }) }), _jsx(Field, { label: "Messaggio", wide: true, hint: "Un messaggio di accompagnamento. Facoltativo.", children: _jsx("textarea", { rows: 3, value: draft.description, onChange: (e) => change({ description: e.target.value }) }) })] }), link ? (_jsxs("section", { className: "dl-card dl-link", children: [_jsxs("div", { className: "dl-link-head", children: [_jsx("span", { className: "dl-step", children: "Il link per il cliente" }), _jsx("code", { children: link.url })] }), _jsxs("div", { className: "dl-link-actions", children: [delivery?.canShortenLinks && link.token.length > 16 && (_jsx("button", { className: "ak-btn", disabled: dirty || saving || busy, title: dirty ? "Salva prima le modifiche del transfer" : "Il vecchio indirizzo continuerà a funzionare", onClick: async () => {
427
- setSaving(true);
428
- try {
429
- await run({ action: "shortenLink", id: delivery.id, linkId: link.id }, "Link accorciato. Anche il vecchio indirizzo resta valido.");
430
- }
431
- finally {
432
- setSaving(false);
433
- }
434
- }, children: "Accorcia link" })), _jsx("button", { className: "ak-btn ak-btn-primary", onClick: () => void copy(link.url, "link"), children: copied === "link" ? "Copiato" : "Copia il link" }), _jsx("button", { className: "ak-btn", onClick: () => void copy(messageFor(draft, link, expiry), "messaggio"), children: copied === "messaggio" ? "Copiato" : "Copia il messaggio" }), _jsx("a", { className: "ak-btn", target: "_blank", rel: "noreferrer", href: `https://wa.me/?text=${encodeURIComponent(messageFor(draft, link, expiry))}`, children: "Apri in WhatsApp" })] }), _jsx("p", { className: "dl-link-stats", children: linkStory(link) }), draft.pin && (_jsxs("p", { className: "dl-link-stats", children: ["Codice di accesso ", _jsx("strong", { children: draft.pin }), " \u2014 \u00E8 gi\u00E0 dentro il messaggio."] }))] })) : (_jsxs("section", { className: "dl-card dl-get", children: [_jsx("button", { className: "ak-btn ak-btn-primary dl-get-btn", disabled: !delivery || saving || busy, onClick: () => void save(), children: saving ? "Preparo…" : "Ottieni il link" }), _jsx("p", { children: delivery
435
- ? "Il link vale già mentre l'upload continua: chi lo apre vede che i file stanno arrivando."
436
- : "Aggiungi i file: il caricamento parte subito e il resto si compila mentre va." })] }))] }), _jsxs("div", { className: "dl-side", children: [_jsxs(Group, { title: "Chi pu\u00F2 aprirlo", children: [_jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !draft.pin, onChange: () => change({ pin: "" }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiunque abbia il link" }), _jsx("small", { children: "Chi riceve il link pu\u00F2 aprire il transfer e condividerlo." })] })] }), _jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !!draft.pin, onChange: () => change({ pin: draft.pin || makeCode() }) }), _jsxs("span", { children: [_jsx("strong", { children: "Link e codice di accesso" }), _jsx("small", { children: "Condividi il codice con il destinatario. Dopo 10 tentativi errati, l\u2019accesso \u00E8 sospeso per un\u2019ora." })] })] }), !!draft.pin && (_jsxs("div", { className: "dl-code", children: [_jsx("input", { "aria-label": "Codice di accesso", value: draft.pin, spellCheck: false, onChange: (e) => change({ pin: e.target.value.toUpperCase() }) }), _jsx("button", { className: "ak-btn", onClick: () => change({ pin: makeCode() }), children: "Rigenera" })] }))] }), downloadLabelsEnabled && (_jsxs(Group, { title: "Testi dei pulsanti di download", note: "Lascia vuoto per usare il testo predefinito. Puoi cambiarli anche dopo l\u2019invio, senza ricaricare i file.", children: [delivery?.status !== "archived" && (_jsx(Field, { label: "Pulsante degli originali", children: _jsx("input", { value: draft.downloadOriginalsLabel, maxLength: 80, placeholder: "Scarica i file", onChange: (e) => change({ downloadOriginalsLabel: e.target.value }) }) })), (packages.length ? packages.some(pkg => pkg.webEnabled) : draft.light) && (_jsx(Field, { label: "Pulsante della versione leggera", children: _jsx("input", { value: draft.downloadWebLabel, maxLength: 80, placeholder: "Versione leggera", onChange: (e) => change({ downloadWebLabel: e.target.value }) }) }))] })), _jsxs(Group, { title: "Scadenza", children: [_jsxs("select", { "aria-label": "Scadenza", className: "dl-select", value: draft.duration, onChange: (e) => change({ duration: e.target.value }), children: [delivery && _jsx("option", { value: "keep", children: delivery.filesExpiresAt
437
- ? `Fino al ${formatDate(delivery.filesExpiresAt)}`
438
- : "Per sempre" }), _jsx("option", { value: "7", children: "7 giorni" }), _jsx("option", { value: "30", children: "30 giorni" }), _jsx("option", { value: "60", children: "60 giorni" }), _jsx("option", { value: "180", children: "6 mesi" }), _jsx("option", { value: "365", children: "1 anno" }), _jsx("option", { value: "forever", children: "Per sempre" })] }), _jsx("p", { className: "dl-note", children: expiry
439
- ? `Dopo il ${formatDate(expiry)} il link continua ad aprirsi, ma i file non si scaricano più.`
440
- : "I file restano finché non li togli tu." })] }), _jsxs(Group, { title: "Alla fine della pagina", children: [_jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.ctaEnabled, onChange: (e) => change({ ctaEnabled: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiedi una recensione" }), _jsx("small", { children: "Un pulsante in fondo, dopo le fotografie." })] })] }), draft.ctaEnabled && (_jsxs(_Fragment, { children: [_jsx(Field, { label: "Testo del pulsante", children: _jsx("input", { value: draft.ctaLabel, onChange: (e) => change({ ctaLabel: e.target.value }) }) }), _jsx(Field, { label: "Indirizzo", hint: "Il link alla tua pagina delle recensioni.", children: _jsx("input", { type: "url", value: draft.ctaUrl, placeholder: "https://\u2026", onChange: (e) => change({ ctaUrl: e.target.value }) }) })] })), _jsx(Field, { label: "Note d'uso", hint: "Cosa pu\u00F2 farci il cliente. Appaiono in fondo alla pagina.", children: _jsx("textarea", { rows: 3, value: draft.licenseNotes, onChange: (e) => change({ licenseNotes: e.target.value }) }) })] }), _jsxs("details", { className: "dl-unavailable", children: [_jsx("summary", { children: "Funzioni aggiuntive non attive" }), _jsxs("div", { children: [" ", _jsxs(Group, { title: "Richiedi pagamento", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-payment-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Sblocca gallery e download al saldo" }), _jsx("small", { id: "dl-payment-description", children: "Potrai impostare l\u2019importo da incassare per questa consegna. Il cliente pagher\u00E0 una sola volta per sbloccare la galleria e scaricare i file." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: il transfer non richiede pagamenti e segue le impostazioni di accesso qui sopra." })] }), _jsxs(Group, { title: "Selezione del cliente", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-selection-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Consenti al cliente di scegliere le foto" }), _jsx("small", { id: "dl-selection-description", children: "Il cliente potr\u00E0 indicare nella galleria quali foto entrano nella sua selezione." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: al momento il cliente pu\u00F2 consultare la galleria, se abilitata, ma non salvare una selezione." })] })] })] })] })] }), !!delivery && (_jsxs("section", { className: "dl-card dl-cover", children: [_jsxs("div", { className: "dl-cover-head", children: [_jsxs("div", { children: [_jsx("span", { className: "dl-step", children: "Copertina" }), _jsxs("p", { children: ["Le foto grandi in cima alla pagina del cliente, fino a otto.", " ", heroes.length
441
- ? `Ne hai scelte ${heroes.length}.`
442
- : "Nessuna scelta: si userà quella predefinita."] }), _jsx("p", { role: "status", children: heroesDirty
443
- ? "Scelta non ancora salvata: premi Salva modifiche per mostrarla al cliente."
444
- : heroes.length
445
- ? "Copertine salvate. Una sola immagine resta fissa; più immagini compongono la sequenza."
446
- : "Scegli le copertine qui: la galleria sotto nella pagina del cliente è separata." })] }), _jsxs("div", { className: "dl-cover-actions", children: [!!photos.length && (_jsx("button", { className: "ak-btn", onClick: () => setPreviewAttempt(value => value + 1), title: "Riprova a caricare le miniature senza cambiare le copertine selezionate", children: "Ricarica anteprime" })), _jsx("button", { className: "ak-btn ak-btn-primary", disabled: !dirty || saving || busy, onClick: () => void save(), children: saving ? "Salvo…" : "Salva modifiche" }), _jsx("button", { className: "ak-btn", disabled: saving || !ready, onClick: () => { if (coverRef.current)
447
- coverRef.current.value = ""; coverRef.current?.click(); }, children: "Carica un'immagine" }), !!heroes.length && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: saving, onClick: () => setHeroes([]), children: "Usa quella predefinita" })), _jsx("input", { ref: coverRef, type: "file", accept: "image/jpeg,image/png,image/webp", multiple: true, hidden: true, onChange: (event) => void uploadCovers(event) })] })] }), packages.some(pkg => (moreImages[pkg.id] ? moreImages[pkg.id].nextCursor : pkg.nextCursor) != null) && (_jsx("button", { className: "ak-btn", disabled: loadingImages, onClick: () => void loadMoreImages(), children: loadingImages ? "Caricamento…" : "Mostra altre foto" })), photos.length ? (_jsx("div", { className: "dl-cover-grid", children: photos.map(({ pkg, image }) => {
448
- const chosen = heroes.some((item) => item.type === "package" && item.packageId === pkg.id && item.index === image.index);
449
- return (_jsxs("button", { type: "button", className: chosen ? "is-chosen" : "", disabled: saving, "aria-pressed": chosen, onClick: () => toggleCover(pkg.id, image.index, image.previewUrl), children: [_jsx("img", { src: previewAttempt ? `${image.previewUrl}&previewRetry=${previewAttempt}` : image.previewUrl, alt: image.name, width: image.width, height: image.height, loading: "lazy" }), chosen && _jsx("em", { "aria-hidden": "true", children: "\u2713" })] }, `${pkg.id}-${image.index}`));
450
- }) })) : (_jsx("p", { className: "dl-note dl-cover-empty", children: heroes.some((item) => item.type === "object")
451
- ? `${heroes.length} immagini caricate a mano.`
452
- : "Questo transfer non ha anteprime da cui scegliere: carica un'immagine, oppure resta quella predefinita." }))] })), !!delivery && (_jsxs("section", { className: "dl-danger", children: [_jsxs("div", { children: [_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void duplicate(), children: "Usa come modello" }), delivery.status === "active" && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void run({ action: "archive", id: delivery.id }, "Originali tolti: recuperabili per sette giorni"), children: "Libera spazio: togli gli originali" }))] }), confirmDelete ? (_jsxs("div", { className: "dl-confirm", children: [_jsxs("p", { children: ["Elimino ", _jsx("strong", { children: delivery.title }), photos.length ? ` (${countPhotos(packages)} file, ${formatBytes(delivery.storedBytes)})` : "", "? Il link smette subito di funzionare. La rimozione dei file e degli upload residui viene completata in background. Non si torna indietro."] }), _jsx("button", { className: "ak-btn", onClick: () => setConfirmDelete(false), children: "Annulla" }), _jsx("button", { className: "ak-btn dl-danger-btn", onClick: () => void remove(), children: "S\u00EC, elimina" })] })) : (_jsx("button", { className: "ak-btn ak-btn-quiet", onClick: () => setConfirmDelete(true), children: "Elimina il transfer" }))] }))] }));
487
+ const accessEdited = !!link && (draft.pin !== (link.pin || "") || draft.duration !== clean.duration);
488
+ const sharingPaused = accessEdited || saving;
489
+ const shareMessage = delivery && link ? messageFor(delivery, link) : "";
490
+ const sharingCard = link && delivery ? (_jsxs("section", { className: "dl-card dl-link", "aria-label": "Condivisione del transfer", children: [_jsxs("div", { className: "dl-link-head", children: [_jsx("span", { className: "dl-step", children: "Il link per il cliente" }), _jsx("code", { children: link.url })] }), _jsxs("div", { className: "dl-link-actions", children: [_jsx("button", { className: "ak-btn ak-btn-primary", disabled: sharingPaused, onClick: () => void copy(link.url, "link"), children: copied === "link" ? "Copiato" : "Copia il link" }), _jsx("button", { className: "ak-btn", disabled: sharingPaused, onClick: () => void copy(shareMessage, "messaggio"), children: copied === "messaggio" ? "Copiato" : "Copia il messaggio" }), sharingPaused
491
+ ? _jsx("button", { className: "ak-btn", disabled: true, children: "Apri in WhatsApp" })
492
+ : _jsx("a", { className: "ak-btn", target: "_blank", rel: "noreferrer", href: `https://wa.me/?text=${encodeURIComponent(shareMessage)}`, children: "Apri in WhatsApp" }), delivery?.canShortenLinks && link.token.length > 16 && (_jsx("button", { className: "ak-btn", disabled: dirty || saving || busy, title: dirty ? "Salva prima le modifiche del transfer" : "Il vecchio indirizzo continuerà a funzionare", onClick: async () => {
493
+ setSaving(true);
494
+ try {
495
+ await run({ action: "shortenLink", id: delivery.id, linkId: link.id }, "Link accorciato. Anche il vecchio indirizzo resta valido.");
496
+ }
497
+ finally {
498
+ setSaving(false);
499
+ }
500
+ }, children: "Accorcia link" }))] }), accessEdited && _jsx("p", { className: "dl-link-stats", role: "status", children: "Salva le modifiche di accesso o scadenza prima di condividere." }), _jsx("p", { className: "dl-link-stats", children: linkStory(link) }), _jsx("div", { ref: setActivityTarget, className: "dl-link-email" }), link.pin && (_jsxs("p", { className: "dl-link-stats", children: ["Codice di accesso ", _jsx("strong", { children: link.pin }), " \u00B7 Incluso nel messaggio."] }))] })) : null;
501
+ return (_jsxs("div", { className: "dl-work", children: [_jsxs("header", { className: "dl-work-head", children: [_jsxs("div", { className: "dl-work-title", children: [state && _jsx("span", { className: "dl-pill is-" + state.kind, children: state.label }), _jsx("h2", { children: draft.title.trim() || (delivery ? delivery.title : "Nuovo transfer") })] }), _jsxs("div", { className: "dl-work-actions", children: [link && (_jsx("a", { className: "ak-btn", href: link.url, target: "_blank", rel: "noreferrer", children: "Guarda come lo vede il cliente" })), link && (_jsx("button", { className: "ak-btn ak-btn-primary", disabled: !dirty || saving || busy || uploading, onClick: () => void save(), children: saving ? "Salvo…" : "Salva" }))] })] }), (failure || notice) && (_jsxs("p", { role: failure ? "alert" : "status", className: failure ? "ak-error dl-feedback" : "dl-feedback is-ok", children: [failure || notice, _jsx("button", { type: "button", "aria-label": "Chiudi", onClick: () => { setFailure(null); setNotice(null); }, children: "\u00D7" })] })), _jsxs("div", { className: "dl-grid dl-compose-grid" + (advanced ? " is-expanded" : "") + (background ? " has-background" : ""), children: [background && _jsx("img", { className: "dl-compose-backdrop", src: background, alt: "" }), _jsxs("div", { className: "dl-main", children: [ready && sharingCard, _jsxs("div", { className: "dl-compose-card", children: [_jsxs("section", { className: "dl-card dl-upload-card", "aria-labelledby": "dl-files-heading", children: [_jsxs("div", { className: "dl-section-head", children: [_jsx("h3", { id: "dl-files-heading", children: "File da consegnare" }), _jsx("p", { children: "Fino a 150 GB per caricamento." })] }), _jsxs("div", { className: "dl-pick", children: [_jsxs("button", { className: "dl-pick-tile", disabled: uploading, onClick: () => choose(false), children: [_jsx(FileIcon, {}), "Aggiungi file"] }), _jsxs("button", { className: "dl-pick-tile", disabled: uploading, onClick: () => choose(true), children: [_jsx(FolderIcon, {}), "Aggiungi una cartella"] }), _jsx("div", { ref: fileInputs, hidden: true })] }), _jsx(DropArea, { disabled: uploading, resuming: !!resumeRef.current, onFiles: addFiles, onError: (error) => setFailure(errorText(error)) }), !!selection.length && _jsxs("div", { className: "dl-selection", "aria-live": "polite", children: [_jsx("strong", { children: selection.length === 1 ? deliveryRelativeName(selection[0]) : selection.length + " file selezionati" }), _jsx("span", { children: formatBytes(selection.reduce((sum, file) => sum + file.size, 0)) }), _jsx("button", { type: "button", className: "ak-btn ak-btn-quiet", disabled: uploading, onClick: () => {
502
+ setSelection([]);
503
+ fileInputs.current?.replaceChildren();
504
+ }, children: "Svuota selezione" }), selection.length > 1 && _jsxs("details", { className: "dl-selected-list", children: [_jsx("summary", { children: "Mostra file" }), _jsx("ul", { children: selection.slice(0, filesShown).map((file, index) => _jsxs("li", { children: [_jsx("span", { children: deliveryRelativeName(file) }), _jsx("button", { className: "ak-btn", type: "button", disabled: uploading, "aria-label": `Rimuovi ${deliveryRelativeName(file)}`, onClick: () => setSelection(files => files.filter((_, i) => i !== index)), children: "\u00D7" })] }, index)) }), filesShown < selection.length && _jsx("button", { className: "ak-btn", type: "button", onClick: () => setFilesShown(count => count + 50), children: "Mostra altri file" })] })] }), job && isBusy(job) && _jsx(Progress, { job: job }), !!packages.length && (_jsx("ul", { className: "dl-files", children: packages.map((pkg) => (_jsxs("li", { className: "dl-file is-" + pkg.state + (confirmPackage === pkg.id ? " is-confirming" : ""), children: [_jsx("span", { className: "dl-file-icon", "aria-hidden": "true", children: pkg.state === "ready" ? "✓" : "…" }), _jsx(PackageContents, { pkg: pkg, confirming: confirmPackage === pkg.id, job: job?.id === pkg.id ? job : undefined, onAction: onAction }), confirmPackage === pkg.id ? (_jsx(_Fragment, { children: _jsxs("span", { className: "dl-file-actions", children: [_jsx("button", { className: "ak-btn", onClick: () => setConfirmPackage(null), children: "Annulla" }), _jsx("button", { className: "ak-btn dl-danger-btn", disabled: uploading, onClick: () => {
505
+ setConfirmPackage(null);
506
+ void run({ action: "deletePackage", id: delivery?.id, packageId: pkg.id }, "File rimossi");
507
+ }, children: "S\u00EC, rimuovi" })] }) })) : (_jsx(_Fragment, { children: _jsxs("span", { className: "dl-file-actions", children: [pkg.state !== "ready" && !(job?.id === pkg.id && isBusy(job)) && (_jsx("button", { className: "ak-btn", disabled: uploading, onClick: () => { resumeRef.current = pkg; setSelection([]); setNotice(resumeHint); }, children: "Riprendi" })), !(job?.id === pkg.id && isBusy(job)) && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: uploading, onClick: () => setConfirmPackage(pkg.id), children: "Rimuovi" }))] }) }))] }, pkg.id))) }))] }), _jsxs("form", { ref: quickFields, className: "dl-card dl-about dl-quick-fields", onSubmit: event => { event.preventDefault(); void beginUpload(selection, resumeRef.current); }, children: [_jsx(DeliveryEmail, { id: delivery?.id, value: emailPreferences, onChange: setEmailPreferences, busy: saving || uploading, unsaved: dirty, activityTarget: activityTarget, canResend: ready, hydratePreferences: !!fromServer, onState: p => { setEmailPreferences(p); setEmailClean(p); } }), _jsx(Field, { label: "Titolo", children: _jsx("input", { disabled: uploading || saving, value: draft.title, placeholder: selection.length ? deliverySelectionName(selection) : "Titolo del transfer", onChange: (e) => change({ title: e.target.value }) }) }), _jsx(Field, { label: "Messaggio", wide: true, children: _jsx("textarea", { disabled: uploading || saving, rows: 3, value: draft.description, onChange: (e) => change({ description: e.target.value }) }) }), _jsxs("div", { className: "dl-compose-actions", children: [_jsx("button", { ref: toggleRef, type: "button", className: "ak-btn dl-options-toggle", "aria-label": "Opzioni del transfer", title: "Opzioni del transfer", "aria-expanded": advanced, "aria-controls": "dl-options", onClick: () => setAdvanced(open => !open), children: "\u2022\u2022\u2022" }), _jsx("button", { className: "ak-btn ak-btn-primary", type: "submit", disabled: !selection.length || uploading || saving || busy, children: preparing ? "Caricamento in corso…" : resumeRef.current ? "Riprendi caricamento" : "Trasferisci" })] })] })] }), !ready && sharingCard, !link && delivery && !uploading && (_jsx("button", { className: "ak-btn", disabled: saving || busy, onClick: () => void save(), children: "Ottieni il link" }))] }), _jsxs("aside", { className: "dl-side", id: "dl-options", "aria-label": "Opzioni del transfer", hidden: !advanced, children: [_jsxs("div", { className: "dl-options-head", children: [_jsx("h3", { tabIndex: -1, ref: optionsTitle, children: "Opzioni del transfer" }), _jsx("button", { type: "button", className: "ak-btn", "aria-label": "Chiudi opzioni", onClick: () => { setAdvanced(false); toggleRef.current?.focus(); }, children: "\u00D7" })] }), _jsxs("fieldset", { className: "dl-option-fields", disabled: uploading || saving, children: [_jsxs(Group, { title: "Opzioni di consegna", note: packages.length
508
+ ? "Le opzioni dei file caricati sono bloccate. Per cambiarle, rimuovi e ricarica i file."
509
+ : "Puoi cambiare queste opzioni prima di premere Trasferisci.", children: [_jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.gallery, disabled: !!packages.length, onChange: (e) => change({ gallery: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Galleria" }), _jsx("small", { children: "Mostra le foto in anteprima sulla pagina del transfer." })] })] }), _jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.light, disabled: !!packages.length, onChange: (e) => change({ light: e.target.checked, webFormat: jpegEnabled ? draft.webFormat : "webp" }) }), _jsxs("span", { children: [_jsx("strong", { children: "Aggiungi conversione in bassa risoluzione" }), _jsx("small", { children: "Chi scarica pu\u00F2 scegliere foto pi\u00F9 leggere per web e social, fino a 2048 px sul lato lungo." })] })] }), draft.light && (_jsxs("label", { className: "dl-field", children: [_jsx("span", { children: "Formato della conversione" }), _jsxs("select", { className: "dl-select", "aria-label": "Formato della conversione", value: draft.webFormat, disabled: !!packages.length || uploading, onChange: (e) => change({ webFormat: e.target.value === "jpg" ? "jpg" : "webp" }), children: [_jsx("option", { value: "webp", children: "WebP \u2014 file pi\u00F9 piccoli" }), _jsx("option", { value: "jpg", disabled: !jpegEnabled && draft.webFormat !== "jpg", children: "JPG \u2014 massima compatibilit\u00E0" })] }), _jsxs("small", { children: ["2048 px sul lato lungo, senza ingrandire le foto pi\u00F9 piccole. Qualit\u00E0 ", draft.webFormat === "jpg" ? "82%" : "80%", "."] })] }))] }), _jsx(Group, { title: "Cliente", children: _jsx(Field, { label: "Destinatario", hint: "Nome del cliente o dell\u2019azienda. Facoltativo.", children: _jsx("input", { value: draft.clientName, placeholder: "Es. Azienda Rossi", onChange: (e) => change({ clientName: e.target.value }) }) }) }), _jsxs(Group, { title: "Chi pu\u00F2 aprirlo", children: [_jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !draft.pin, onChange: () => change({ pin: "" }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiunque abbia il link" }), _jsx("small", { children: "Chi riceve il link pu\u00F2 aprire il transfer e condividerlo." })] })] }), _jsxs("label", { className: "dl-radio", children: [_jsx("input", { type: "radio", name: "dl-access", checked: !!draft.pin, onChange: () => change({ pin: draft.pin || makeCode() }) }), _jsxs("span", { children: [_jsx("strong", { children: "Link e codice di accesso" }), _jsx("small", { children: "Condividi il codice con il destinatario. Dopo 10 tentativi errati, l\u2019accesso \u00E8 sospeso per un\u2019ora." })] })] }), !!draft.pin && (_jsxs("div", { className: "dl-code", children: [_jsx("input", { "aria-label": "Codice di accesso", value: draft.pin, spellCheck: false, onChange: (e) => change({ pin: e.target.value.toUpperCase() }) }), _jsx("button", { className: "ak-btn", onClick: () => change({ pin: makeCode() }), children: "Rigenera" })] }))] }), downloadLabelsEnabled && (_jsxs(Group, { title: "Testi dei pulsanti di download", note: "Lascia vuoto per usare il testo predefinito. Puoi cambiarli anche dopo l\u2019invio, senza ricaricare i file.", children: [delivery?.status !== "archived" && (_jsx(Field, { label: "Pulsante degli originali", children: _jsx("input", { value: draft.downloadOriginalsLabel, maxLength: 80, placeholder: "Scarica i file", onChange: (e) => change({ downloadOriginalsLabel: e.target.value }) }) })), (packages.length ? packages.some(pkg => pkg.webEnabled) : draft.light) && (_jsx(Field, { label: "Pulsante della versione leggera", children: _jsx("input", { value: draft.downloadWebLabel, maxLength: 80, placeholder: "Versione leggera", onChange: (e) => change({ downloadWebLabel: e.target.value }) }) }))] })), _jsxs(Group, { title: "Scadenza", children: [_jsxs("select", { "aria-label": "Scadenza", className: "dl-select", value: draft.duration, onChange: (e) => change({ duration: e.target.value }), children: [delivery && _jsx("option", { value: "keep", children: delivery.filesExpiresAt
510
+ ? `Fino al ${formatDate(delivery.filesExpiresAt)}`
511
+ : "Per sempre" }), _jsx("option", { value: "7", children: "7 giorni" }), _jsx("option", { value: "30", children: "30 giorni" }), _jsx("option", { value: "60", children: "60 giorni" }), _jsx("option", { value: "180", children: "6 mesi" }), _jsx("option", { value: "365", children: "1 anno" }), _jsx("option", { value: "forever", children: "Per sempre" })] }), _jsx("p", { className: "dl-note", children: expiry
512
+ ? `Dopo il ${formatDate(expiry)} il link continua ad aprirsi, ma i file non si scaricano più.`
513
+ : "I file restano finché non li togli tu." })] }), _jsxs(Group, { title: "Alla fine della pagina", children: [_jsxs("label", { className: "dl-check", children: [_jsx("input", { type: "checkbox", checked: draft.ctaEnabled, onChange: (e) => change({ ctaEnabled: e.target.checked }) }), _jsxs("span", { children: [_jsx("strong", { children: "Chiedi una recensione" }), _jsx("small", { children: "Un pulsante in fondo, dopo le fotografie." })] })] }), draft.ctaEnabled && (_jsxs(_Fragment, { children: [_jsx(Field, { label: "Testo del pulsante", children: _jsx("input", { value: draft.ctaLabel, onChange: (e) => change({ ctaLabel: e.target.value }) }) }), _jsx(Field, { label: "Indirizzo", hint: "Il link alla tua pagina delle recensioni.", children: _jsx("input", { type: "url", value: draft.ctaUrl, placeholder: "https://\u2026", onChange: (e) => change({ ctaUrl: e.target.value }) }) })] })), _jsx(Field, { label: "Note d'uso", hint: "Cosa pu\u00F2 farci il cliente. Appaiono in fondo alla pagina.", children: _jsx("textarea", { rows: 3, value: draft.licenseNotes, onChange: (e) => change({ licenseNotes: e.target.value }) }) })] }), _jsxs("details", { className: "dl-unavailable", children: [_jsx("summary", { children: "Funzioni aggiuntive non attive" }), _jsxs("div", { children: [" ", _jsxs(Group, { title: "Richiedi pagamento", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-payment-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Sblocca gallery e download al saldo" }), _jsx("small", { id: "dl-payment-description", children: "Potrai impostare l\u2019importo da incassare per questa consegna. Il cliente pagher\u00E0 una sola volta per sbloccare la galleria e scaricare i file." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: il transfer non richiede pagamenti e segue le impostazioni di accesso qui sopra." })] }), _jsxs(Group, { title: "Selezione del cliente", children: [_jsx("span", { className: "dl-payment-status", children: "Chiedi di attivare la funzione" }), _jsxs("label", { className: "dl-check dl-payment-disabled", children: [_jsx("input", { type: "checkbox", checked: false, disabled: true, "aria-describedby": "dl-selection-description" }), _jsxs("span", { children: [_jsx("strong", { children: "Consenti al cliente di scegliere le foto" }), _jsx("small", { id: "dl-selection-description", children: "Il cliente potr\u00E0 indicare nella galleria quali foto entrano nella sua selezione." })] })] }), _jsx("p", { className: "dl-note", children: "Questa opzione non \u00E8 ancora disponibile: al momento il cliente pu\u00F2 consultare la galleria, se abilitata, ma non salvare una selezione." })] })] })] }), _jsxs("section", { className: "dl-card dl-cover", children: [_jsxs("div", { className: "dl-cover-head", children: [_jsxs("div", { children: [_jsx("span", { className: "dl-step", children: "Copertina" }), _jsxs("p", { children: ["Fino a otto sfondi per la pagina del destinatario.", " ", coverFiles.length ? coverFiles.map(file => file.name).join(", ") : heroes.length
514
+ ? `Ne hai scelte ${heroes.length}.`
515
+ : "Nessuna scelta: si userà quella predefinita."] }), _jsx("p", { role: "status", children: !delivery ? "Puoi scegliere uno sfondo per questo transfer prima di inviarlo." : heroesDirty
516
+ ? "Scelta non ancora salvata: premi Salva modifiche per mostrarla al cliente."
517
+ : heroes.length
518
+ ? "Copertine salvate. Una sola immagine resta fissa; più immagini compongono la sequenza."
519
+ : "Scegli le copertine qui: la galleria sotto nella pagina del cliente è separata." })] }), _jsxs("div", { className: "dl-cover-actions", children: [!!photos.length && (_jsx("button", { className: "ak-btn", onClick: () => setPreviewAttempt(value => value + 1), title: "Riprova a caricare le miniature senza cambiare le copertine selezionate", children: "Ricarica anteprime" })), delivery && _jsx("button", { className: "ak-btn ak-btn-primary", disabled: !dirty || saving || busy || uploading, onClick: () => void save(), children: saving ? "Salvo…" : "Salva modifiche" }), _jsx("button", { className: "ak-btn", disabled: saving || uploading, onClick: () => { if (coverRef.current)
520
+ coverRef.current.value = ""; coverRef.current?.click(); }, children: "Carica un'immagine" }), (!!heroes.length || !!coverFiles.length) && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: saving, onClick: () => { setHeroes([]); setCoverFiles([]); }, children: "Usa quella predefinita" })), _jsx("input", { ref: coverRef, type: "file", accept: "image/jpeg,image/png,image/webp", multiple: true, hidden: true, onChange: (event) => void uploadCovers(event) })] })] }), packages.some(pkg => (moreImages[pkg.id] ? moreImages[pkg.id].nextCursor : pkg.nextCursor) != null) && (_jsx("button", { className: "ak-btn", disabled: loadingImages, onClick: () => void loadMoreImages(), children: loadingImages ? "Caricamento…" : "Mostra altre foto" })), photos.length ? (_jsx("div", { className: "dl-cover-grid", children: photos.map(({ pkg, image }) => {
521
+ const chosen = heroes.some((item) => item.type === "package" && item.packageId === pkg.id && item.index === image.index);
522
+ return (_jsxs("button", { type: "button", className: chosen ? "is-chosen" : "", disabled: saving, "aria-pressed": chosen, onClick: () => toggleCover(pkg.id, image.index, image.previewUrl), children: [_jsx("img", { src: previewAttempt ? `${image.previewUrl}&previewRetry=${previewAttempt}` : image.previewUrl, alt: image.name, width: image.width, height: image.height, loading: "lazy" }), chosen && _jsx("em", { "aria-hidden": "true", children: "\u2713" })] }, `${pkg.id}-${image.index}`));
523
+ }) })) : ready ? (_jsx("p", { className: "dl-note dl-cover-empty", children: heroes.some((item) => item.type === "object")
524
+ ? `${heroes.length} immagini caricate a mano.`
525
+ : "Questo transfer non ha anteprime da cui scegliere: carica un'immagine, oppure resta quella predefinita." })) : null] }), !!delivery && (_jsxs("section", { className: "dl-danger", children: [_jsxs("div", { children: [_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void duplicate(), children: "Usa come modello" }), delivery.status === "active" && (_jsx("button", { className: "ak-btn ak-btn-quiet", disabled: busy, onClick: () => void run({ action: "archive", id: delivery.id }, "Originali tolti: recuperabili per sette giorni"), children: "Libera spazio: togli gli originali" }))] }), confirmDelete ? (_jsxs("div", { className: "dl-confirm", children: [_jsxs("p", { children: ["Elimino ", _jsx("strong", { children: delivery.title }), photos.length ? ` (${countPhotos(packages)} file, ${formatBytes(delivery.storedBytes)})` : "", "? Il link smette subito di funzionare. La rimozione dei file e degli upload residui viene completata in background. Non si torna indietro."] }), _jsx("button", { className: "ak-btn", onClick: () => setConfirmDelete(false), children: "Annulla" }), _jsx("button", { className: "ak-btn dl-danger-btn", onClick: () => void remove(), children: "S\u00EC, elimina" })] })) : (_jsx("button", { className: "ak-btn ak-btn-quiet", onClick: () => setConfirmDelete(true), children: "Elimina il transfer" }))] }))] })] })] })] }));
453
526
  }
454
527
  /* ============================================================================================
455
528
  Impostazioni
456
529
  ========================================================================================== */
457
- export function DeliverySettings({ settings, onAction, pickMedia }) {
530
+ export function DeliverySettings({ settings, onAction, onReload, pickMedia }) {
458
531
  const [covers, setCovers] = useState(settings.defaultHeroes);
459
- const [notice, setNotice] = useState(null);
460
- useEffect(() => setCovers(settings.defaultHeroes), [settings]);
461
- return (_jsxs("div", { className: "dl-work", children: [_jsxs("header", { className: "dl-work-head", children: [_jsx("div", { className: "dl-work-title", children: _jsx("h2", { children: "Impostazioni Transfer" }) }), _jsx("div", { className: "dl-work-actions", children: _jsx("button", { className: "ak-btn ak-btn-primary", onClick: () => void onAction({
462
- action: "saveSettings", defaultHeroes: covers,
463
- }).then(() => setNotice("Salvata")), children: "Salva" }) })] }), notice && _jsx("p", { className: "dl-feedback is-ok", children: notice }), _jsx(DeliveryEmailConfiguration, {}), _jsxs("section", { className: "dl-card dl-cover", children: [_jsxs("div", { className: "dl-cover-head", children: [_jsxs("div", { children: [_jsx("span", { className: "dl-step", children: "Pagina del cliente" }), _jsx("p", { children: "Queste immagini vanno in cima ai transfer per cui non scegli una copertina." })] }), _jsxs("div", { className: "dl-cover-actions", children: [_jsx("button", { className: "ak-btn", onClick: () => void pickMedia({ multiple: true })
464
- .then((chosen) => { if (chosen)
465
- setCovers(chosen.slice(0, 8)); }), children: "Scegli dalla libreria" }), !!covers.length && (_jsx("button", { className: "ak-btn ak-btn-quiet", onClick: () => setCovers([]), children: "Nessuna" }))] })] }), !!covers.length && (_jsx("div", { className: "dl-cover-grid is-static", children: covers.map((url) => _jsx("img", { src: url, alt: "" }, url)) }))] })] }));
532
+ const [saving, setSaving] = useState(false);
533
+ const [notice, setNotice] = useState("");
534
+ const [error, setError] = useState("");
535
+ const dirty = JSON.stringify(covers) !== JSON.stringify(settings.defaultHeroes);
536
+ const savedKey = JSON.stringify(settings.defaultHeroes);
537
+ useEffect(() => { setCovers(JSON.parse(savedKey)); }, [savedKey]);
538
+ const update = (next) => {
539
+ setNotice("");
540
+ setError("");
541
+ if (next.length > 8) {
542
+ setError("Puoi scegliere fino a otto sfondi.");
543
+ return;
544
+ }
545
+ setCovers(next);
546
+ };
547
+ const save = async () => {
548
+ setSaving(true);
549
+ setError("");
550
+ setNotice("");
551
+ try {
552
+ const next = covers.map(url => url.trim()).filter(Boolean);
553
+ await onAction({ action: "saveSettings", defaultHeroes: next }, { reload: false });
554
+ await onReload();
555
+ setCovers(next);
556
+ setNotice("Sfondi predefiniti salvati.");
557
+ }
558
+ catch (err) {
559
+ setError(errorText(err));
560
+ }
561
+ finally {
562
+ setSaving(false);
563
+ }
564
+ };
565
+ return (_jsxs("div", { className: "dl-work", children: [_jsx("header", { className: "dl-work-head", children: _jsx("h2", { children: "Impostazioni Transfer" }) }), _jsxs("section", { className: "dl-card dl-cover", "aria-labelledby": "dl-default-covers", children: [_jsxs("div", { className: "dl-cover-head", children: [_jsxs("div", { children: [_jsx("h3", { id: "dl-default-covers", children: "Sfondi predefiniti" }), _jsx("p", { children: "La pagina del destinatario mostra questi sfondi quando il transfer non ha una copertina propria. Puoi sceglierne fino a otto, nell\u2019ordine di visualizzazione." })] }), _jsxs("div", { className: "dl-cover-actions", children: [pickMedia && _jsx("button", { type: "button", className: "ak-btn", disabled: saving, onClick: async () => {
566
+ try {
567
+ const chosen = await pickMedia({ multiple: true });
568
+ if (chosen?.length)
569
+ update([...new Set([...covers, ...chosen])]);
570
+ }
571
+ catch (err) {
572
+ setError(errorText(err));
573
+ }
574
+ }, children: "Scegli dalla libreria" }), _jsx("button", { type: "button", className: "ak-btn ak-btn-primary", disabled: !dirty || saving, onClick: () => void save(), children: saving ? "Salvo…" : "Salva sfondi" })] })] }), !pickMedia && _jsx(Field, { label: "Percorsi delle immagini", hint: "Un percorso /media/ del sito per riga.", children: _jsx("textarea", { rows: 4, disabled: saving, value: covers.join("\n"), placeholder: "/media/copertine/studio.jpg", onChange: event => update(event.target.value.split("\n")) }) }), !!covers.filter(Boolean).length && _jsx("ol", { className: "dl-default-covers", children: covers.map((url, index) => url.startsWith("/media/") && _jsxs("li", { children: [_jsx("img", { src: url, alt: `Sfondo ${index + 1}`, loading: "lazy" }), _jsx("button", { type: "button", className: "ak-btn", disabled: saving, "aria-label": `Rimuovi sfondo ${index + 1}`, onClick: () => update(covers.filter((_, i) => i !== index)), children: "Rimuovi" })] }, index)) }), error && _jsx("p", { className: "ak-error", role: "alert", children: error }), notice && _jsx("p", { role: "status", children: notice })] }), _jsx(DeliveryEmailConfiguration, {})] }));
466
575
  }
467
576
  /* ============================================================================================
468
577
  Pezzi
@@ -475,6 +584,38 @@ function FileIcon() {
475
584
  function FolderIcon() {
476
585
  return (_jsxs("svg", { viewBox: "0 0 24 24", width: "22", height: "22", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" }), _jsx("path", { d: "M12 11.5v5M9.5 14h5" })] }));
477
586
  }
587
+ function PackageContents({ pkg, confirming, job, onAction }) {
588
+ const [loaded, setLoaded] = useState();
589
+ const [loading, setLoading] = useState(false);
590
+ const [error, setError] = useState(false);
591
+ const files = loaded ?? pkg.fileList;
592
+ const names = files?.names ?? [];
593
+ const count = pkg.fileCount;
594
+ const extra = count === 2 ? " e un altro file" : count > 2 ? ` e altri ${count - 1} file` : "";
595
+ const title = names.length ? names[0] + extra : count ? `${count} file` : "Caricamento";
596
+ const status = pkg.state === "ready"
597
+ ? [pkg.galleryEnabled ? "galleria" : "", pkg.webEnabled ? "versione leggera" : ""].filter(Boolean).join(" · ") || "solo originali"
598
+ : isBusy(job) ? job?.state === "paused" ? "caricamento in pausa" : "caricamento in corso" : "caricamento interrotto";
599
+ async function loadMore() {
600
+ if (loading || files?.nextCursor == null)
601
+ return;
602
+ setLoading(true);
603
+ setError(false);
604
+ try {
605
+ const next = await onAction({
606
+ action: "manifestPage", view: "files", id: pkg.deliveryId, packageId: pkg.id, after: files.nextCursor,
607
+ }, { reload: false });
608
+ setLoaded({ names: [...names, ...next.names], nextCursor: next.nextCursor });
609
+ }
610
+ catch {
611
+ setError(true);
612
+ }
613
+ finally {
614
+ setLoading(false);
615
+ }
616
+ }
617
+ return _jsxs("div", { className: "dl-file-main", children: [_jsx("strong", { children: confirming ? `Rimuovere ${title}?` : title }), _jsx("span", { children: confirming ? "La rimozione è definitiva." : `${formatBytes(pkg.sourceBytes)} · ${status}` }), count > 1 && names.length > 0 && _jsxs("details", { open: confirming || undefined, className: "dl-package-names", children: [_jsx("summary", { children: `Elenco dei ${count} file` }), _jsx("ul", { children: names.map((name, index) => _jsx("li", { children: name }, index)) }), error && _jsx("span", { role: "alert", children: "Impossibile caricare gli altri nomi." }), files?.nextCursor != null && _jsx("button", { className: "ak-btn", type: "button", disabled: loading, onClick: () => void loadMore(), children: loading ? "Caricamento…" : error ? "Riprova" : "Mostra altri file" })] }, confirming ? "confirm" : "view")] });
618
+ }
478
619
  function Group({ title, note, children }) {
479
620
  return (_jsxs("section", { className: "dl-group", children: [_jsx("h3", { children: title }), children, note && _jsx("p", { className: "dl-note", children: note })] }));
480
621
  }
@@ -514,7 +655,6 @@ function Progress({ job }) {
514
655
  if (!progress) {
515
656
  return (_jsxs("div", { className: "dl-progress", children: [_jsx("div", { className: "dl-progress-top", children: _jsx("strong", { children: "Preparo il caricamento\u2026" }) }), _jsx("div", { className: "dl-progress-track", children: _jsx("i", { style: { width: "3%" } }) })] }));
516
657
  }
517
- const done = progress.totalFiles ? Math.min(1, progress.doneFiles / progress.totalFiles) : 0;
518
658
  const phase = job.state === "paused" ? "In pausa"
519
659
  : job.state === "cancelling" ? "Annullamento in corso"
520
660
  : job.waitingForNetwork ? "Attendo la connessione e riprovo…"
@@ -527,7 +667,7 @@ function Progress({ job }) {
527
667
  const left = progress.phase === "originals" && mbps > 0
528
668
  ? Math.max(0, (progress.sourceBytes - progress.uploadedBytes) * 8 / (mbps * 1_000_000))
529
669
  : null;
530
- return (_jsxs("div", { className: "dl-progress", children: [_jsxs("div", { className: "dl-progress-top", children: [_jsx("strong", { children: phase }), _jsxs("span", { children: [progress.doneFiles, " di ", progress.totalFiles, left !== null && left > 5 ? ` · ancora ${formatDuration(left)}` : ""] })] }), _jsx("div", { className: "dl-progress-track", children: _jsx("i", { style: { width: `${Math.max(2, done * 100)}%` } }) }), _jsxs("p", { children: [progress.file || "…", " \u00B7 ", formatBytes(progress.uploadedBytes), mbps > 0 ? ` · ${mbps.toFixed(1)} Mbps` : "", progress.note ? ` · ${progress.note}` : ""] }), _jsx("small", { children: "Puoi andare dove vuoi nel pannello: il caricamento continua e lo ritrovi nel riquadro in basso a destra. Se chiudi il browser si ferma, e lo riprendi da qui." })] }));
670
+ return (_jsxs("div", { className: "dl-progress", children: [_jsxs("div", { className: "dl-progress-top", children: [_jsx("strong", { children: phase }), _jsxs("span", { children: [progress.doneFiles, " di ", progress.totalFiles, left !== null && left > 5 ? ` · ancora ${formatDuration(left)}` : ""] })] }), _jsx("div", { className: "dl-progress-track", children: _jsx("i", { style: { width: `${Math.max(2, deliveryProgressPercent(progress))}%` } }) }), _jsxs("p", { children: [progress.file || "…", " \u00B7 ", formatBytes(progress.uploadedBytes), mbps > 0 ? ` · ${mbps.toFixed(1)} Mbps` : "", progress.note ? ` · ${progress.note}` : ""] }), _jsx("small", { children: "Puoi continuare a usare il pannello. Tieni aperta questa scheda fino alla fine del caricamento." })] }));
531
671
  }
532
672
  /* ============================================================================================
533
673
  Calcoli
@@ -575,7 +715,9 @@ function heroKey(item) {
575
715
  return item.type === "package" ? `p:${item.packageId}:${item.index}` : `o:${item.id}`;
576
716
  }
577
717
  function primaryLink(delivery) {
578
- return delivery?.links.find((item) => !item.revokedAt) || null;
718
+ const links = delivery?.links.filter(item => !item.revokedAt) || [];
719
+ const now = Date.now();
720
+ return links.find(item => !item.expiresAt || Date.parse(item.expiresAt) > now) || links[0] || null;
579
721
  }
580
722
  function transferState(row) {
581
723
  if (row.filesExpiresAt) {
@@ -590,8 +732,9 @@ function transferState(row) {
590
732
  if (row.status === "archived")
591
733
  return { kind: "archived", label: "Originali tolti" };
592
734
  if (row.status === "active") {
593
- return row.downloadCount > 0
594
- ? { kind: "downloaded", label: "Scaricato" }
735
+ // Older backends return the total only in the list, but include counters on each detail link.
736
+ return (row.downloadCount > 0 || row.links?.some(link => link.downloadCount > 0))
737
+ ? { kind: "downloaded", label: "Download richiesto" }
595
738
  : { kind: "ready", label: "Pronto" };
596
739
  }
597
740
  return { kind: "draft", label: "Senza file" };
@@ -606,22 +749,26 @@ function makeCode() {
606
749
  .map((n) => alphabet[n % alphabet.length]).join("");
607
750
  return `${pick()}-${pick()}`;
608
751
  }
609
- function messageFor(draft, link, expiry) {
610
- const who = draft.clientName.trim().split(/\s+/)[0];
752
+ function messageFor(delivery, link) {
753
+ const who = delivery.clientName.trim().split(/\s+/)[0];
754
+ const expiry = [link.expiresAt, delivery.expiresAt, delivery.filesExpiresAt]
755
+ .filter((value) => !!value)
756
+ .sort((a, b) => Date.parse(a) - Date.parse(b))[0];
611
757
  return [
612
- `Ciao${who ? ` ${who}` : ""}, i file di ${draft.title.trim() || "questo lavoro"} sono pronti:`,
758
+ `Ciao${who ? ` ${who}` : ""}, ti condivido il transfer «${delivery.title}».`,
613
759
  link.url,
614
- draft.pin ? `Codice di accesso: ${draft.pin}` : "",
615
- expiry ? `Puoi scaricarle fino al ${formatDate(expiry)}.` : "",
760
+ link.pin ? `Codice di accesso: ${link.pin}` : "",
761
+ expiry && Date.parse(expiry) > Date.now() ? `Puoi scaricare i file fino al ${formatDate(expiry)}.` : "",
616
762
  ].filter(Boolean).join("\n");
617
763
  }
618
764
  function linkStory(link) {
619
- if (!link.openedCount)
620
- return "Non è ancora stato aperto.";
621
- const opened = `Aperto ${link.openedCount === 1 ? "una volta" : `${link.openedCount} volte`}`;
622
- const when = link.lastOpenedAt ? `, l’ultima il ${formatDate(link.lastOpenedAt)}` : "";
623
- const got = link.downloadCount ? "ha scaricato" : "non ha ancora scaricato";
624
- return `${opened}${when} · ${got}.`;
765
+ const opens = link.openedCount === 0 ? "Nessuna apertura"
766
+ : link.openedCount === 1 ? "1 apertura" : `${link.openedCount} aperture`;
767
+ const requests = link.downloadCount === 0 ? "Nessuna richiesta di download"
768
+ : link.downloadCount === 1 ? "1 richiesta di download" : `${link.downloadCount} richieste di download`;
769
+ const lastOpen = link.lastOpenedAt ? ` (${formatDate(link.lastOpenedAt)})` : "";
770
+ const lastRequest = link.lastDownloadAt ? ` (${formatDate(link.lastDownloadAt)})` : "";
771
+ return `${opens}${lastOpen} · ${requests}${lastRequest}`;
625
772
  }
626
773
  function expiryFrom(duration) {
627
774
  if (duration === "forever" || duration === "keep")
@@ -652,15 +799,3 @@ function formatDuration(seconds) {
652
799
  const hours = Math.floor(seconds / 3600);
653
800
  return `${hours} h ${Math.ceil((seconds % 3600) / 60)} min`;
654
801
  }
655
- function errorText(error) {
656
- return error instanceof Error ? error.message : String(error);
657
- }
658
- function uploadFailure(error) {
659
- const raw = errorText(error);
660
- if ((error instanceof DOMException && error.name === "NotReadableError") ||
661
- raw.includes("requested file could not be read")) {
662
- return "Il browser non riesce più a leggere uno dei file scelti. " +
663
- "Riseleziona la stessa cartella e premi «Riprendi».";
664
- }
665
- return raw;
666
- }