Просмотр исходного кода

Show when a share link stops working and replace the 404 for closed links (#617)

Bernt Christian Egeland 1 день назад
Родитель
Сommit
a8b9e18c2e
39 измененных файлов с 789 добавлено и 106 удалено
  1. 1 1
      messages/de/settings.json
  2. 10 0
      messages/de/share.json
  3. 1 1
      messages/en/settings.json
  4. 10 0
      messages/en/share.json
  5. 1 1
      messages/es/settings.json
  6. 10 0
      messages/es/share.json
  7. 1 1
      messages/fr/settings.json
  8. 10 0
      messages/fr/share.json
  9. 1 1
      messages/it/settings.json
  10. 10 0
      messages/it/share.json
  11. 1 1
      messages/lt/settings.json
  12. 10 0
      messages/lt/share.json
  13. 1 1
      messages/nb/settings.json
  14. 10 0
      messages/nb/share.json
  15. 1 1
      messages/nl/settings.json
  16. 10 0
      messages/nl/share.json
  17. 1 1
      messages/pl/settings.json
  18. 10 0
      messages/pl/share.json
  19. 1 1
      messages/pt-BR/settings.json
  20. 10 0
      messages/pt-BR/share.json
  21. 1 1
      messages/pt-PT/settings.json
  22. 10 0
      messages/pt-PT/share.json
  23. 1 1
      messages/ru/settings.json
  24. 10 0
      messages/ru/share.json
  25. 1 1
      messages/tr/settings.json
  26. 10 0
      messages/tr/share.json
  27. 287 0
      src/__tests__/app/share/share-link-pages.test.tsx
  28. 4 0
      src/app/(public)/share/inspection/[orgId]/[token]/inspection-view.tsx
  29. 32 13
      src/app/(public)/share/inspection/[orgId]/[token]/page.tsx
  30. 4 0
      src/app/(public)/share/invoice/[orgId]/[token]/invoice-view.tsx
  31. 28 13
      src/app/(public)/share/invoice/[orgId]/[token]/page.tsx
  32. 28 15
      src/app/(public)/share/quote/[orgId]/[token]/page.tsx
  33. 4 0
      src/app/(public)/share/quote/[orgId]/[token]/quote-view.tsx
  34. 76 32
      src/app/(public)/share/status-report/[orgId]/[token]/page.tsx
  35. 4 0
      src/app/(public)/share/status-report/[orgId]/[token]/status-report-view.tsx
  36. 60 19
      src/components/share-link-expired.tsx
  37. 58 0
      src/components/share-link-open-until.tsx
  38. 23 1
      src/lib/share-expiry.ts
  39. 38 0
      src/lib/share-link.server.ts

+ 1 - 1
messages/de/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Die Einstellungen für Freigabelinks konnten nicht gespeichert werden. Versuchen Sie es erneut.",
     "saveFailed": "Die Einstellungen für Freigabelinks konnten nicht gespeichert werden. Versuchen Sie es erneut.",
     "rules": {
     "rules": {
       "title": "Ablauf von Links",
       "title": "Ablauf von Links",
-      "description": "Wie lange ein Link, den Sie an einen Kunden senden, funktioniert. Danach sieht der Kunde eine Seite, die ihn bittet, sich bei Ihnen zu melden.",
+      "description": "Wie lange ein Link, den Sie an einen Kunden senden, funktioniert. Die Seite nennt dem Kunden den letzten Tag; danach sieht er eine Seite, die ihn bittet, sich bei Ihnen zu melden.",
       "kind": {
       "kind": {
         "invoice": "Rechnungen",
         "invoice": "Rechnungen",
         "quote": "Angebote",
         "quote": "Angebote",

+ 10 - 0
messages/de/share.json

@@ -266,5 +266,15 @@
       "inspection": "Wenden Sie sich an die Werkstatt, um einen neuen Link zu dieser Inspektion zu erhalten.",
       "inspection": "Wenden Sie sich an die Werkstatt, um einen neuen Link zu dieser Inspektion zu erhalten.",
       "statusReport": "Wenden Sie sich an die Werkstatt, um einen neuen Link zu diesem Update zu erhalten."
       "statusReport": "Wenden Sie sich an die Werkstatt, um einen neuen Link zu diesem Update zu erhalten."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link funktioniert nicht",
+    "title": "Dieser Link funktioniert nicht mehr",
+    "body": "Möglicherweise wurde er entfernt oder die Adresse ist unvollständig. Wenden Sie sich an {workshop}, um einen neuen Link zu erhalten.",
+    "bodyNoName": "Möglicherweise wurde er entfernt oder die Adresse ist unvollständig. Wenden Sie sich an die Werkstatt, um einen neuen Link zu erhalten."
+  },
+  "openUntil": {
+    "text": "Dieser Link funktioniert bis einschließlich {date}. Wenden Sie sich danach an {workshop}, um einen neuen zu erhalten.",
+    "textNoName": "Dieser Link funktioniert bis einschließlich {date}. Wenden Sie sich danach an die Werkstatt, um einen neuen zu erhalten."
   }
   }
 }
 }

+ 1 - 1
messages/en/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Couldn't save the share link settings. Try again.",
     "saveFailed": "Couldn't save the share link settings. Try again.",
     "rules": {
     "rules": {
       "title": "Link expiry",
       "title": "Link expiry",
-      "description": "How long a link you send to a customer keeps working. After that the customer sees a page asking them to contact you.",
+      "description": "How long a link you send to a customer keeps working. The page tells the customer the last day; after that they see a page asking them to contact you.",
       "kind": {
       "kind": {
         "invoice": "Invoices",
         "invoice": "Invoices",
         "quote": "Quotes",
         "quote": "Quotes",

+ 10 - 0
messages/en/share.json

@@ -266,5 +266,15 @@
       "inspection": "Contact the workshop to get a new link to this inspection.",
       "inspection": "Contact the workshop to get a new link to this inspection.",
       "statusReport": "Contact the workshop to get a new link to this update."
       "statusReport": "Contact the workshop to get a new link to this update."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link not working",
+    "title": "This link no longer works",
+    "body": "It may have been removed, or the address may be incomplete. Contact {workshop} to get a new link.",
+    "bodyNoName": "It may have been removed, or the address may be incomplete. Contact the workshop to get a new link."
+  },
+  "openUntil": {
+    "text": "This link works until {date}. After that, ask {workshop} for a new one.",
+    "textNoName": "This link works until {date}. After that, ask the workshop for a new one."
   }
   }
 }
 }

+ 1 - 1
messages/es/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "No se pudieron guardar los ajustes de enlaces compartidos. Inténtalo de nuevo.",
     "saveFailed": "No se pudieron guardar los ajustes de enlaces compartidos. Inténtalo de nuevo.",
     "rules": {
     "rules": {
       "title": "Caducidad de enlaces",
       "title": "Caducidad de enlaces",
-      "description": "Cuánto tiempo funciona un enlace que envías a un cliente. Después, el cliente ve una página que le pide que se ponga en contacto contigo.",
+      "description": "Cuánto tiempo funciona un enlace que envías a un cliente. La página le indica al cliente el último día; después, ve una página que le pide que se ponga en contacto contigo.",
       "kind": {
       "kind": {
         "invoice": "Facturas",
         "invoice": "Facturas",
         "quote": "Presupuestos",
         "quote": "Presupuestos",

+ 10 - 0
messages/es/share.json

@@ -266,5 +266,15 @@
       "inspection": "Ponte en contacto con el taller para obtener un nuevo enlace a esta inspección.",
       "inspection": "Ponte en contacto con el taller para obtener un nuevo enlace a esta inspección.",
       "statusReport": "Ponte en contacto con el taller para obtener un nuevo enlace a esta actualización."
       "statusReport": "Ponte en contacto con el taller para obtener un nuevo enlace a esta actualización."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "El enlace no funciona",
+    "title": "Este enlace ya no funciona",
+    "body": "Puede que se haya eliminado o que la dirección esté incompleta. Ponte en contacto con {workshop} para obtener un nuevo enlace.",
+    "bodyNoName": "Puede que se haya eliminado o que la dirección esté incompleta. Ponte en contacto con el taller para obtener un nuevo enlace."
+  },
+  "openUntil": {
+    "text": "Este enlace funciona hasta el {date}. Después, pide uno nuevo a {workshop}.",
+    "textNoName": "Este enlace funciona hasta el {date}. Después, pide uno nuevo al taller."
   }
   }
 }
 }

+ 1 - 1
messages/fr/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Impossible d'enregistrer les réglages des liens de partage. Réessayez.",
     "saveFailed": "Impossible d'enregistrer les réglages des liens de partage. Réessayez.",
     "rules": {
     "rules": {
       "title": "Expiration des liens",
       "title": "Expiration des liens",
-      "description": "Combien de temps un lien envoyé à un client reste valable. Ensuite, le client voit une page qui l'invite à vous contacter.",
+      "description": "Combien de temps un lien envoyé à un client reste valable. La page indique au client le dernier jour. Ensuite, il voit une page qui l'invite à vous contacter.",
       "kind": {
       "kind": {
         "invoice": "Factures",
         "invoice": "Factures",
         "quote": "Devis",
         "quote": "Devis",

+ 10 - 0
messages/fr/share.json

@@ -266,5 +266,15 @@
       "inspection": "Contactez l'atelier pour obtenir un nouveau lien vers cette inspection.",
       "inspection": "Contactez l'atelier pour obtenir un nouveau lien vers cette inspection.",
       "statusReport": "Contactez l'atelier pour obtenir un nouveau lien vers ce point d'avancement."
       "statusReport": "Contactez l'atelier pour obtenir un nouveau lien vers ce point d'avancement."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Lien indisponible",
+    "title": "Ce lien ne fonctionne plus",
+    "body": "Il a peut-être été supprimé, ou l'adresse est incomplète. Contactez {workshop} pour obtenir un nouveau lien.",
+    "bodyNoName": "Il a peut-être été supprimé, ou l'adresse est incomplète. Contactez l'atelier pour obtenir un nouveau lien."
+  },
+  "openUntil": {
+    "text": "Ce lien est valable jusqu'au {date}. Ensuite, demandez-en un nouveau à {workshop}.",
+    "textNoName": "Ce lien est valable jusqu'au {date}. Ensuite, demandez-en un nouveau à l'atelier."
   }
   }
 }
 }

+ 1 - 1
messages/it/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Impossibile salvare le impostazioni dei link condivisi. Riprova.",
     "saveFailed": "Impossibile salvare le impostazioni dei link condivisi. Riprova.",
     "rules": {
     "rules": {
       "title": "Scadenza dei link",
       "title": "Scadenza dei link",
-      "description": "Per quanto tempo funziona un link inviato a un cliente. Dopo, il cliente vede una pagina che gli chiede di contattarti.",
+      "description": "Per quanto tempo funziona un link inviato a un cliente. La pagina indica al cliente l'ultimo giorno; dopo, vede una pagina che gli chiede di contattarti.",
       "kind": {
       "kind": {
         "invoice": "Fatture",
         "invoice": "Fatture",
         "quote": "Preventivi",
         "quote": "Preventivi",

+ 10 - 0
messages/it/share.json

@@ -266,5 +266,15 @@
       "inspection": "Contatta l'officina per ricevere un nuovo link a questa ispezione.",
       "inspection": "Contatta l'officina per ricevere un nuovo link a questa ispezione.",
       "statusReport": "Contatta l'officina per ricevere un nuovo link a questo aggiornamento."
       "statusReport": "Contatta l'officina per ricevere un nuovo link a questo aggiornamento."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link non funzionante",
+    "title": "Questo link non funziona più",
+    "body": "Potrebbe essere stato rimosso o l'indirizzo potrebbe essere incompleto. Contatta {workshop} per ricevere un nuovo link.",
+    "bodyNoName": "Potrebbe essere stato rimosso o l'indirizzo potrebbe essere incompleto. Contatta l'officina per ricevere un nuovo link."
+  },
+  "openUntil": {
+    "text": "Questo link funziona fino al {date}. Dopo, chiedine uno nuovo a {workshop}.",
+    "textNoName": "Questo link funziona fino al {date}. Dopo, chiedine uno nuovo all'officina."
   }
   }
 }
 }

+ 1 - 1
messages/lt/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Nepavyko įrašyti bendrinimo nuorodų nustatymų. Bandykite dar kartą.",
     "saveFailed": "Nepavyko įrašyti bendrinimo nuorodų nustatymų. Bandykite dar kartą.",
     "rules": {
     "rules": {
       "title": "Nuorodų galiojimas",
       "title": "Nuorodų galiojimas",
-      "description": "Kiek laiko veikia klientui išsiųsta nuoroda. Vėliau klientas mato puslapį, kuriame prašoma susisiekti su jumis.",
+      "description": "Kiek laiko veikia klientui išsiųsta nuoroda. Puslapyje klientui nurodoma paskutinė diena; vėliau jis mato puslapį, kuriame prašoma susisiekti su jumis.",
       "kind": {
       "kind": {
         "invoice": "Sąskaitos",
         "invoice": "Sąskaitos",
         "quote": "Pasiūlymai",
         "quote": "Pasiūlymai",

+ 10 - 0
messages/lt/share.json

@@ -266,5 +266,15 @@
       "inspection": "Susisiekite su dirbtuvėmis, kad gautumėte naują nuorodą į šią apžiūrą.",
       "inspection": "Susisiekite su dirbtuvėmis, kad gautumėte naują nuorodą į šią apžiūrą.",
       "statusReport": "Susisiekite su dirbtuvėmis, kad gautumėte naują nuorodą į šią naujieną."
       "statusReport": "Susisiekite su dirbtuvėmis, kad gautumėte naują nuorodą į šią naujieną."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Nuoroda neveikia",
+    "title": "Ši nuoroda nebeveikia",
+    "body": "Galbūt ji buvo pašalinta arba adresas nepilnas. Susisiekite su {workshop}, kad gautumėte naują nuorodą.",
+    "bodyNoName": "Galbūt ji buvo pašalinta arba adresas nepilnas. Susisiekite su dirbtuvėmis, kad gautumėte naują nuorodą."
+  },
+  "openUntil": {
+    "text": "Ši nuoroda veikia iki {date} imtinai. Po to susisiekite su {workshop}, kad gautumėte naują.",
+    "textNoName": "Ši nuoroda veikia iki {date} imtinai. Po to susisiekite su dirbtuvėmis, kad gautumėte naują."
   }
   }
 }
 }

+ 1 - 1
messages/nb/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Kunne ikke lagre innstillingene for delte lenker. Prøv igjen.",
     "saveFailed": "Kunne ikke lagre innstillingene for delte lenker. Prøv igjen.",
     "rules": {
     "rules": {
       "title": "Utløp for lenker",
       "title": "Utløp for lenker",
-      "description": "Hvor lenge en lenke du sender til en kunde virker. Etter det ser kunden en side som ber dem kontakte deg.",
+      "description": "Hvor lenge en lenke du sender til en kunde virker. Siden viser kunden siste dag; etter det ser kunden en side som ber dem kontakte deg.",
       "kind": {
       "kind": {
         "invoice": "Fakturaer",
         "invoice": "Fakturaer",
         "quote": "Tilbud",
         "quote": "Tilbud",

+ 10 - 0
messages/nb/share.json

@@ -266,5 +266,15 @@
       "inspection": "Kontakt verkstedet for å få en ny lenke til denne inspeksjonen.",
       "inspection": "Kontakt verkstedet for å få en ny lenke til denne inspeksjonen.",
       "statusReport": "Kontakt verkstedet for å få en ny lenke til denne oppdateringen."
       "statusReport": "Kontakt verkstedet for å få en ny lenke til denne oppdateringen."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Lenken virker ikke",
+    "title": "Denne lenken virker ikke lenger",
+    "body": "Den kan ha blitt fjernet, eller adressen kan være ufullstendig. Kontakt {workshop} for å få en ny lenke.",
+    "bodyNoName": "Den kan ha blitt fjernet, eller adressen kan være ufullstendig. Kontakt verkstedet for å få en ny lenke."
+  },
+  "openUntil": {
+    "text": "Denne lenken virker til og med {date}. Etter det kan du be {workshop} om en ny.",
+    "textNoName": "Denne lenken virker til og med {date}. Etter det kan du be verkstedet om en ny."
   }
   }
 }
 }

+ 1 - 1
messages/nl/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Kon de instellingen voor deellinks niet opslaan. Probeer het opnieuw.",
     "saveFailed": "Kon de instellingen voor deellinks niet opslaan. Probeer het opnieuw.",
     "rules": {
     "rules": {
       "title": "Verloop van links",
       "title": "Verloop van links",
-      "description": "Hoe lang een link die je naar een klant stuurt blijft werken. Daarna ziet de klant een pagina die vraagt contact met je op te nemen.",
+      "description": "Hoe lang een link die je naar een klant stuurt blijft werken. De pagina toont de klant de laatste dag; daarna ziet de klant een pagina die vraagt contact met je op te nemen.",
       "kind": {
       "kind": {
         "invoice": "Facturen",
         "invoice": "Facturen",
         "quote": "Offertes",
         "quote": "Offertes",

+ 10 - 0
messages/nl/share.json

@@ -266,5 +266,15 @@
       "inspection": "Neem contact op met de werkplaats voor een nieuwe link naar deze inspectie.",
       "inspection": "Neem contact op met de werkplaats voor een nieuwe link naar deze inspectie.",
       "statusReport": "Neem contact op met de werkplaats voor een nieuwe link naar deze update."
       "statusReport": "Neem contact op met de werkplaats voor een nieuwe link naar deze update."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link werkt niet",
+    "title": "Deze link werkt niet meer",
+    "body": "Mogelijk is hij verwijderd, of is het adres onvolledig. Neem contact op met {workshop} voor een nieuwe link.",
+    "bodyNoName": "Mogelijk is hij verwijderd, of is het adres onvolledig. Neem contact op met de werkplaats voor een nieuwe link."
+  },
+  "openUntil": {
+    "text": "Deze link werkt tot en met {date}. Vraag daarna een nieuwe aan {workshop}.",
+    "textNoName": "Deze link werkt tot en met {date}. Vraag daarna een nieuwe aan de werkplaats."
   }
   }
 }
 }

+ 1 - 1
messages/pl/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Nie udało się zapisać ustawień udostępnionych linków. Spróbuj ponownie.",
     "saveFailed": "Nie udało się zapisać ustawień udostępnionych linków. Spróbuj ponownie.",
     "rules": {
     "rules": {
       "title": "Wygasanie linków",
       "title": "Wygasanie linków",
-      "description": "Jak długo działa link wysłany do klienta. Potem klient widzi stronę z prośbą o kontakt z Tobą.",
+      "description": "Jak długo działa link wysłany do klienta. Strona informuje klienta o ostatnim dniu; potem widzi on stronę z prośbą o kontakt z Tobą.",
       "kind": {
       "kind": {
         "invoice": "Faktury",
         "invoice": "Faktury",
         "quote": "Wyceny",
         "quote": "Wyceny",

+ 10 - 0
messages/pl/share.json

@@ -266,5 +266,15 @@
       "inspection": "Skontaktuj się z warsztatem, aby otrzymać nowy link do tej inspekcji.",
       "inspection": "Skontaktuj się z warsztatem, aby otrzymać nowy link do tej inspekcji.",
       "statusReport": "Skontaktuj się z warsztatem, aby otrzymać nowy link do tej aktualizacji."
       "statusReport": "Skontaktuj się z warsztatem, aby otrzymać nowy link do tej aktualizacji."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link nie działa",
+    "title": "Ten link już nie działa",
+    "body": "Mógł zostać usunięty albo adres jest niepełny. Skontaktuj się z {workshop}, aby otrzymać nowy link.",
+    "bodyNoName": "Mógł zostać usunięty albo adres jest niepełny. Skontaktuj się z warsztatem, aby otrzymać nowy link."
+  },
+  "openUntil": {
+    "text": "Ten link działa do {date} włącznie. Potem skontaktuj się z {workshop}, aby otrzymać nowy.",
+    "textNoName": "Ten link działa do {date} włącznie. Potem skontaktuj się z warsztatem, aby otrzymać nowy."
   }
   }
 }
 }

+ 1 - 1
messages/pt-BR/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Não foi possível salvar as configurações de links compartilhados. Tente novamente.",
     "saveFailed": "Não foi possível salvar as configurações de links compartilhados. Tente novamente.",
     "rules": {
     "rules": {
       "title": "Expiração de links",
       "title": "Expiração de links",
-      "description": "Por quanto tempo um link enviado a um cliente continua funcionando. Depois disso, o cliente vê uma página pedindo que entre em contato com você.",
+      "description": "Por quanto tempo um link enviado a um cliente continua funcionando. A página informa ao cliente o último dia; depois disso, ele vê uma página pedindo que entre em contato com você.",
       "kind": {
       "kind": {
         "invoice": "Faturas",
         "invoice": "Faturas",
         "quote": "Orçamentos",
         "quote": "Orçamentos",

+ 10 - 0
messages/pt-BR/share.json

@@ -266,5 +266,15 @@
       "inspection": "Entre em contato com a oficina para receber um novo link para esta inspeção.",
       "inspection": "Entre em contato com a oficina para receber um novo link para esta inspeção.",
       "statusReport": "Entre em contato com a oficina para receber um novo link para esta atualização."
       "statusReport": "Entre em contato com a oficina para receber um novo link para esta atualização."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link indisponível",
+    "title": "Este link não funciona mais",
+    "body": "Ele pode ter sido removido ou o endereço pode estar incompleto. Entre em contato com {workshop} para receber um novo link.",
+    "bodyNoName": "Ele pode ter sido removido ou o endereço pode estar incompleto. Entre em contato com a oficina para receber um novo link."
+  },
+  "openUntil": {
+    "text": "Este link funciona até {date}. Depois disso, entre em contato com {workshop} para receber um novo.",
+    "textNoName": "Este link funciona até {date}. Depois disso, entre em contato com a oficina para receber um novo."
   }
   }
 }
 }

+ 1 - 1
messages/pt-PT/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Não foi possível guardar as definições de links partilhados. Tente novamente.",
     "saveFailed": "Não foi possível guardar as definições de links partilhados. Tente novamente.",
     "rules": {
     "rules": {
       "title": "Expiração de links",
       "title": "Expiração de links",
-      "description": "Durante quanto tempo um link enviado a um cliente continua a funcionar. Depois disso, o cliente vê uma página a pedir que o contacte.",
+      "description": "Durante quanto tempo um link enviado a um cliente continua a funcionar. A página indica ao cliente o último dia; depois disso, vê uma página a pedir que o contacte.",
       "kind": {
       "kind": {
         "invoice": "Faturas",
         "invoice": "Faturas",
         "quote": "Orçamentos",
         "quote": "Orçamentos",

+ 10 - 0
messages/pt-PT/share.json

@@ -266,5 +266,15 @@
       "inspection": "Contacte a oficina para receber um novo link para esta inspeção.",
       "inspection": "Contacte a oficina para receber um novo link para esta inspeção.",
       "statusReport": "Contacte a oficina para receber um novo link para esta atualização."
       "statusReport": "Contacte a oficina para receber um novo link para esta atualização."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Link indisponível",
+    "title": "Este link já não funciona",
+    "body": "Pode ter sido removido ou o endereço pode estar incompleto. Contacte {workshop} para receber um novo link.",
+    "bodyNoName": "Pode ter sido removido ou o endereço pode estar incompleto. Contacte a oficina para receber um novo link."
+  },
+  "openUntil": {
+    "text": "Este link funciona até {date}. Depois disso, contacte {workshop} para receber um novo.",
+    "textNoName": "Este link funciona até {date}. Depois disso, contacte a oficina para receber um novo."
   }
   }
 }
 }

+ 1 - 1
messages/ru/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Не удалось сохранить настройки ссылок. Попробуйте ещё раз.",
     "saveFailed": "Не удалось сохранить настройки ссылок. Попробуйте ещё раз.",
     "rules": {
     "rules": {
       "title": "Срок действия ссылок",
       "title": "Срок действия ссылок",
-      "description": "Сколько работает ссылка, отправленная клиенту. После этого клиент видит страницу с просьбой связаться с вами.",
+      "description": "Сколько работает ссылка, отправленная клиенту. Страница сообщает клиенту последний день; после этого он увидит страницу с просьбой связаться с вами.",
       "kind": {
       "kind": {
         "invoice": "Счета",
         "invoice": "Счета",
         "quote": "Предложения",
         "quote": "Предложения",

+ 10 - 0
messages/ru/share.json

@@ -266,5 +266,15 @@
       "inspection": "Свяжитесь с мастерской, чтобы получить новую ссылку на этот осмотр.",
       "inspection": "Свяжитесь с мастерской, чтобы получить новую ссылку на этот осмотр.",
       "statusReport": "Свяжитесь с мастерской, чтобы получить новую ссылку на это обновление."
       "statusReport": "Свяжитесь с мастерской, чтобы получить новую ссылку на это обновление."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Ссылка не работает",
+    "title": "Эта ссылка больше не работает",
+    "body": "Возможно, её удалили или адрес указан не полностью. Свяжитесь с {workshop}, чтобы получить новую ссылку.",
+    "bodyNoName": "Возможно, её удалили или адрес указан не полностью. Свяжитесь с мастерской, чтобы получить новую ссылку."
+  },
+  "openUntil": {
+    "text": "Эта ссылка действует до {date} включительно. После этого свяжитесь с {workshop}, чтобы получить новую.",
+    "textNoName": "Эта ссылка действует до {date} включительно. После этого свяжитесь с мастерской, чтобы получить новую."
   }
   }
 }
 }

+ 1 - 1
messages/tr/settings.json

@@ -3134,7 +3134,7 @@
     "saveFailed": "Paylaşım bağlantısı ayarları kaydedilemedi. Tekrar deneyin.",
     "saveFailed": "Paylaşım bağlantısı ayarları kaydedilemedi. Tekrar deneyin.",
     "rules": {
     "rules": {
       "title": "Bağlantı süresi",
       "title": "Bağlantı süresi",
-      "description": "Müşteriye gönderdiğiniz bir bağlantının ne kadar süre çalışacağı. Sonrasında müşteri, sizinle iletişime geçmesini isteyen bir sayfa görür.",
+      "description": "Müşteriye gönderdiğiniz bir bağlantının ne kadar süre çalışacağı. Sayfa müşteriye son günü gösterir; sonrasında müşteri, sizinle iletişime geçmesini isteyen bir sayfa görür.",
       "kind": {
       "kind": {
         "invoice": "Faturalar",
         "invoice": "Faturalar",
         "quote": "Teklifler",
         "quote": "Teklifler",

+ 10 - 0
messages/tr/share.json

@@ -266,5 +266,15 @@
       "inspection": "Bu muayeneye yeni bir bağlantı almak için atölyeyle iletişime geçin.",
       "inspection": "Bu muayeneye yeni bir bağlantı almak için atölyeyle iletişime geçin.",
       "statusReport": "Bu güncellemeye yeni bir bağlantı almak için atölyeyle iletişime geçin."
       "statusReport": "Bu güncellemeye yeni bir bağlantı almak için atölyeyle iletişime geçin."
     }
     }
+  },
+  "gone": {
+    "pageTitle": "Bağlantı çalışmıyor",
+    "title": "Bu bağlantı artık çalışmıyor",
+    "body": "Bağlantı kaldırılmış ya da adres eksik olabilir. Yeni bir bağlantı almak için {workshop} ile iletişime geçin.",
+    "bodyNoName": "Bağlantı kaldırılmış ya da adres eksik olabilir. Yeni bir bağlantı almak için atölyeyle iletişime geçin."
+  },
+  "openUntil": {
+    "text": "Bu bağlantı {date} tarihine kadar çalışır. Sonrasında yeni bir bağlantı için {workshop} ile iletişime geçin.",
+    "textNoName": "Bu bağlantı {date} tarihine kadar çalışır. Sonrasında yeni bir bağlantı için atölyeyle iletişime geçin."
   }
   }
 }
 }

+ 287 - 0
src/__tests__/app/share/share-link-pages.test.tsx

@@ -0,0 +1,287 @@
+/**
+ * What a customer sees on a page opened from a share link.
+ *
+ * While the link is open and has a date, one line at the foot of the page
+ * names the last day it works, on the workshop's calendar. When the address
+ * names a real workshop but the token opens nothing, the customer gets a page
+ * telling them who to ask, the same page whatever the reason, and never the
+ * staff 404.
+ */
+import { render, screen } from '@testing-library/react'
+import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('server-only', () => ({}))
+vi.mock('next-intl/server', async () => {
+  const { useTranslations } = await import('next-intl')
+  return {
+    getTranslations: async (arg: string | { namespace: string }) =>
+      useTranslations(typeof arg === 'string' ? arg : arg.namespace),
+  }
+})
+vi.mock('next/headers', () => ({
+  headers: async () => new Headers({ 'accept-language': 'en' }),
+  cookies: async () => ({ get: () => undefined }),
+}))
+
+class NotFound extends Error {}
+vi.mock('next/navigation', () => ({
+  notFound: () => {
+    throw new NotFound()
+  },
+}))
+
+const organization = { findUnique: vi.fn() }
+const appSetting = { findMany: vi.fn() }
+const statusReport = { findUnique: vi.fn(), update: vi.fn() }
+const serviceRecord = { findUnique: vi.fn() }
+const quote = { findFirst: vi.fn() }
+const inspection = { findUnique: vi.fn() }
+vi.mock('@/lib/db', () => ({
+  db: { organization, appSetting, statusReport, serviceRecord, quote, inspection },
+}))
+vi.mock('@/lib/customer-session', () => ({ getCustomerSession: async () => null }))
+vi.mock('@/lib/features', () => ({ getFeatures: async () => ({ brandingRemoved: false }) }))
+vi.mock('@/features/status-reports/Actions/submitFeedback', () => ({
+  submitStatusReportFeedback: vi.fn(),
+}))
+
+const { ShareLinkOpenUntil } = await import('@/components/share-link-open-until')
+const statusReportPage = await import('@/app/(public)/share/status-report/[orgId]/[token]/page')
+const quotePage = await import('@/app/(public)/share/quote/[orgId]/[token]/page')
+
+/** Server components are async functions; run them down to plain elements. */
+async function settle(node: ReactNode): Promise<ReactNode> {
+  if (Array.isArray(node)) return Promise.all(node.map(settle))
+  if (!isValidElement(node)) return node
+  const element = node as ReactElement<Record<string, unknown>>
+  if (typeof element.type === 'function' && element.type.constructor.name === 'AsyncFunction') {
+    return settle(await (element.type as (p: unknown) => Promise<ReactNode>)(element.props))
+  }
+  const props: Record<string, unknown> = {}
+  for (const [key, value] of Object.entries(element.props)) {
+    props[key] = isValidElement(value) || Array.isArray(value) ? await settle(value) : value
+  }
+  return cloneElement(element, props)
+}
+
+async function show(node: ReactNode) {
+  return render(<>{await settle(node)}</>)
+}
+
+const WORKSHOP = { id: 'org1', name: 'Nordvik Motor' }
+
+function workshop(settings: Record<string, string> = {}) {
+  organization.findUnique.mockImplementation(async ({ where }) =>
+    where.id === WORKSHOP.id || where.portalSlug === 'nordvik' ? WORKSHOP : null
+  )
+  const all: Record<string, string> = {
+    'workshop.phone': '+47 22 00 00 00',
+    'workshop.email': 'post@nordvik.example',
+    ...settings,
+  }
+  appSetting.findMany.mockImplementation(async ({ where }) =>
+    Object.entries(all)
+      .filter(([key]) => !where.key?.in || where.key.in.includes(key))
+      .map(([key, value]) => ({ key, value }))
+  )
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(new Date('2026-11-16T12:00:00Z'))
+  workshop()
+  statusReport.findUnique.mockResolvedValue(null)
+  quote.findFirst.mockResolvedValue(null)
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('the line saying when a link closes', () => {
+  const until = (at: string) =>
+    ShareLinkOpenUntil({
+      organizationId: 'org1',
+      expiry: { kind: 'date', at: new Date(at), source: 'workshop' },
+    })
+
+  it('names the last day on the workshop’s calendar, not the server’s', async () => {
+    // The last instant of 16 December in Los Angeles is already the 17th in UTC.
+    workshop({ 'workshop.timezone': 'America/Los_Angeles' })
+    await show(await until('2026-12-17T07:59:59.999Z'))
+    expect(
+      screen.getByText(
+        'This link works until Dec 16, 2026. After that, ask Nordvik Motor for a new one.'
+      )
+    ).toBeInTheDocument()
+  })
+
+  it('does the same east of UTC, where the workshop’s day starts first', async () => {
+    // The last instant of 17 December in Auckland is still the 16th in UTC.
+    workshop({ 'workshop.timezone': 'Pacific/Auckland', 'workshop.dateFormat': 'dd.MM.yyyy' })
+    await show(await until('2026-12-17T10:59:59.999Z'))
+    expect(screen.getByText(/This link works until 17\.12\.2026\./)).toBeInTheDocument()
+  })
+
+  it('promises only the day before when the link closes partway through a day', async () => {
+    // A status report lives 14 days to the minute: this one closes at 10:30
+    // on 1 December in Oslo, so 30 November is the last day it surely works.
+    workshop({ 'workshop.timezone': 'Europe/Oslo' })
+    await show(await until('2026-12-01T09:30:00.000Z'))
+    expect(screen.getByText(/This link works until Nov 30, 2026\./)).toBeInTheDocument()
+  })
+
+  it('is left off the printed page', async () => {
+    workshop({ 'workshop.timezone': 'Europe/Oslo' })
+    await show(await until('2026-12-16T22:59:59.999Z'))
+    expect(screen.getByText(/This link works until/)).toHaveClass('print:hidden')
+  })
+
+  it('says nothing for a link that never expires', async () => {
+    const line = await ShareLinkOpenUntil({
+      organizationId: 'org1',
+      expiry: { kind: 'never', source: 'workshop' },
+    })
+    expect(line).toBeNull()
+  })
+
+  it('says nothing on an unpaid invoice that stays open until it is paid', async () => {
+    const line = await ShareLinkOpenUntil({
+      organizationId: 'org1',
+      expiry: { kind: 'untilPaid', source: 'workshop' },
+    })
+    expect(line).toBeNull()
+  })
+
+  it('says nothing once the day has passed, for a portal customer still reading', async () => {
+    expect(await until('2026-11-01T22:59:59.999Z')).toBeNull()
+  })
+})
+
+describe('a status report link', () => {
+  const open = (orgId: string, token: string) =>
+    statusReportPage.default({ params: Promise.resolve({ orgId, token }) })
+  const title = async (orgId: string, token: string) =>
+    (await statusReportPage.generateMetadata({ params: Promise.resolve({ orgId, token }) })).title
+
+  const report = (over: Record<string, unknown> = {}) => ({
+    id: 'r1',
+    organizationId: 'org1',
+    title: 'Brake pads worn',
+    message: 'Front pads are at 2 mm.',
+    videoUrl: null,
+    videoFileName: null,
+    status: 'published',
+    createdAt: new Date('2026-11-10T09:00:00Z'),
+    expiresAt: new Date('2026-11-24T22:59:59.999Z'),
+    viewedAt: new Date('2026-11-10T10:00:00Z'),
+    customerFeedback: null,
+    feedbackAt: null,
+    serviceRecord: {
+      title: 'Annual service',
+      vehicle: { make: 'Volvo', model: 'V70', year: 2015, licensePlate: 'AB12345' },
+    },
+    inspection: null,
+    technician: { name: 'Ola' },
+    organization: { name: WORKSHOP.name },
+    ...over,
+  })
+
+  it('shows the report and the last day its link works', async () => {
+    workshop({ 'workshop.timezone': 'Europe/Oslo' })
+    statusReport.findUnique.mockResolvedValue(report())
+    await show(await open('org1', 'tok'))
+    expect(screen.getByText('Brake pads worn')).toBeInTheDocument()
+    expect(
+      screen.getByText(
+        'This link works until Nov 24, 2026. After that, ask Nordvik Motor for a new one.'
+      )
+    ).toBeInTheDocument()
+  })
+
+  it('tells the customer who to ask when the report has been cleaned up', async () => {
+    const { container } = await show(await open('org1', 'cleaned-up'))
+    expect(screen.getByRole('heading', { name: 'This link no longer works' })).toBeInTheDocument()
+    expect(
+      screen.getByText(
+        'It may have been removed, or the address may be incomplete. Contact Nordvik Motor to get a new link.'
+      )
+    ).toBeInTheDocument()
+    expect(screen.getByRole('link', { name: '+47 22 00 00 00' })).toHaveAttribute(
+      'href',
+      'tel:+4722000000'
+    )
+    expect(screen.getByRole('link', { name: 'post@nordvik.example' })).toBeInTheDocument()
+    expect(container).not.toHaveTextContent(/Brake|Volvo|404|Dashboard/)
+    expect(await title('org1', 'cleaned-up')).toBe('Link not working')
+  })
+
+  it('shows the very same page for another workshop’s live report', async () => {
+    const gone = (await show(await open('org1', 'nothing'))).container.innerHTML
+    statusReport.findUnique.mockResolvedValue(report({ organizationId: 'org2' }))
+    const foreign = (await show(await open('org1', 'tok'))).container.innerHTML
+    expect(foreign).toBe(gone)
+  })
+
+  it('says the link has expired, and nothing of the report, once its day has passed', async () => {
+    statusReport.findUnique.mockResolvedValue(
+      report({ expiresAt: new Date('2026-11-15T22:59:59.999Z') })
+    )
+    const { container } = await show(await open('org1', 'tok'))
+    expect(screen.getByRole('heading', { name: 'This link has expired' })).toBeInTheDocument()
+    expect(container).not.toHaveTextContent(/Brake|Volvo/)
+    expect(await title('org1', 'tok')).toBe('Link expired')
+  })
+
+  it('stays a plain 404 when no workshop answers to the address', async () => {
+    await expect(open('nobody', 'tok')).rejects.toBeInstanceOf(NotFound)
+  })
+})
+
+describe('a quote link', () => {
+  const open = (orgId: string, token: string) =>
+    quotePage.default({ params: Promise.resolve({ orgId, token }) })
+  const title = async (orgId: string, token: string) =>
+    (await quotePage.generateMetadata({ params: Promise.resolve({ orgId, token }) })).title
+
+  const shared = (over: Record<string, unknown> = {}) => ({
+    id: 'q1',
+    organizationId: 'org1',
+    customerId: 'cust1',
+    sharedAt: new Date('2026-09-01T09:00:00Z'),
+    shareRenewedAt: null,
+    shareExpiresAt: null,
+    shareNeverExpires: false,
+    ...over,
+  })
+
+  it('is the same page whether the link was removed, mistyped or another workshop’s', async () => {
+    const removed = (await show(await open('org1', 'removed'))).container.innerHTML
+    expect(screen.getByRole('heading', { name: 'This link no longer works' })).toBeInTheDocument()
+
+    const mistyped = (await show(await open('nordvik', 'mistypd'))).container.innerHTML
+    quote.findFirst.mockResolvedValue(shared({ organizationId: 'org2' }))
+    const foreign = (await show(await open('org1', 'tok'))).container.innerHTML
+
+    expect(mistyped).toBe(removed)
+    expect(foreign).toBe(removed)
+    expect(removed).not.toMatch(/quote/i)
+    expect(await title('org1', 'removed')).toBe('Link not working')
+  })
+
+  it('says it has expired once the workshop’s days have run out', async () => {
+    quote.findFirst.mockResolvedValue(shared())
+    await show(await open('org1', 'tok'))
+    expect(screen.getByRole('heading', { name: 'This link has expired' })).toBeInTheDocument()
+    expect(
+      screen.getByText('Contact Nordvik Motor to get a new link to this quote.')
+    ).toBeInTheDocument()
+    expect(await title('org1', 'tok')).toBe('Link expired')
+  })
+
+  it('stays a plain 404 when no workshop answers to the address', async () => {
+    await expect(open('nobody', 'tok')).rejects.toBeInstanceOf(NotFound)
+  })
+})

+ 4 - 0
src/app/(public)/share/inspection/[orgId]/[token]/inspection-view.tsx

@@ -109,6 +109,7 @@ export function InspectionView({
   logoUrl,
   logoUrl,
   primaryColor,
   primaryColor,
   showTorqvoiceBranding,
   showTorqvoiceBranding,
+  expiryNote,
   dateFormat,
   dateFormat,
   timezone,
   timezone,
   publicToken,
   publicToken,
@@ -124,6 +125,8 @@ export function InspectionView({
   logoUrl: string
   logoUrl: string
   primaryColor: string
   primaryColor: string
   showTorqvoiceBranding: boolean
   showTorqvoiceBranding: boolean
+  /** The line saying when this link closes. Page chrome, never part of the sheet. */
+  expiryNote?: React.ReactNode
   dateFormat?: string
   dateFormat?: string
   timezone?: string
   timezone?: string
   publicToken: string
   publicToken: string
@@ -727,6 +730,7 @@ export function InspectionView({
             </a>
             </a>
           </p>
           </p>
         )}
         )}
+        {expiryNote}
       </footer>
       </footer>
 
 
       <MediaLightbox
       <MediaLightbox

+ 32 - 13
src/app/(public)/share/inspection/[orgId]/[token]/page.tsx

@@ -1,11 +1,11 @@
 import { getTranslations } from 'next-intl/server'
 import { getTranslations } from 'next-intl/server'
-import { ShareLinkExpired } from '@/components/share-link-expired'
-import { findSharedDocument } from '@/lib/share-link.server'
+import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
+import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { lookUpShareLink } from '@/lib/share-link.server'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { InspectionView } from './inspection-view'
 import { InspectionView } from './inspection-view'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
-import { resolvePortalOrg } from '@/lib/portal-slug'
 import type { Metadata } from 'next'
 import type { Metadata } from 'next'
 import { headers } from 'next/headers'
 import { headers } from 'next/headers'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { getAppBaseUrl } from '@/lib/app-url'
@@ -30,9 +30,20 @@ import { gateTypeKey, typeKeyEnabledIn } from '@/features/vehicles/Lib/typeKeySe
 
 
 export const revalidate = 60
 export const revalidate = 60
 
 
-export async function generateMetadata(): Promise<Metadata> {
+export async function generateMetadata({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>
+}): Promise<Metadata> {
+  const { orgId, token } = await params
+  const link = await lookUpShareLink('inspection', orgId, token)
+  const robots = { index: false, follow: false }
+  // A closed link's tab does not say what the link led to.
+  if (link.status === 'expired' || link.status === 'gone') {
+    return { title: await closedShareLinkTitle(link.organizationId, link.status), robots }
+  }
   const t = await getTranslations('portal.inspectionDetail')
   const t = await getTranslations('portal.inspectionDetail')
-  return { title: t('title'), robots: { index: false, follow: false } }
+  return { title: t('title'), robots }
 }
 }
 
 
 export default async function PublicInspectionPage({
 export default async function PublicInspectionPage({
@@ -42,13 +53,20 @@ export default async function PublicInspectionPage({
 }) {
 }) {
   const { orgId: orgParam, token } = await params
   const { orgId: orgParam, token } = await params
 
 
-  // Resolve slug (e.g. "egelandauto") or UUID to the real org ID
-  const resolvedOrg = await resolvePortalOrg(orgParam)
-  const orgId = resolvedOrg?.id ?? orgParam
-
-  const shared = await findSharedDocument('inspection', token, orgId)
-  if (!shared) notFound()
-  if (!shared.open) return <ShareLinkExpired organizationId={orgId} kind="inspection" />
+  // Only an address with no workshop behind it is the plain 404. A customer
+  // whose link is closed gets a page that tells them who to ask.
+  const link = await lookUpShareLink('inspection', orgParam, token)
+  if (link.status === 'unknownWorkshop') notFound()
+  if (link.status !== 'open') {
+    return (
+      <ShareLinkClosed
+        organizationId={link.organizationId}
+        status={link.status}
+        kind="inspection"
+      />
+    )
+  }
+  const { organizationId: orgId, shared } = link
 
 
   const inspection = await db.inspection.findFirst({
   const inspection = await db.inspection.findFirst({
     where: { publicToken: token, organizationId: orgId },
     where: { publicToken: token, organizationId: orgId },
@@ -96,7 +114,7 @@ export default async function PublicInspectionPage({
   })
   })
 
 
   if (!inspection) {
   if (!inspection) {
-    notFound()
+    return <ShareLinkClosed organizationId={orgId} status="gone" kind="inspection" />
   }
   }
 
 
   // Every setting, as the PDF loads them: the certificate design reads its
   // Every setting, as the PDF loads them: the certificate design reads its
@@ -219,6 +237,7 @@ export default async function PublicInspectionPage({
 
 
   return (
   return (
     <InspectionView
     <InspectionView
+      expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       inspection={publicInspection}
       inspection={publicInspection}
       spec={spec}
       spec={spec}
       workshop={workshop}
       workshop={workshop}

+ 4 - 0
src/app/(public)/share/invoice/[orgId]/[token]/invoice-view.tsx

@@ -238,6 +238,7 @@ export function InvoiceView({
   showLogo = true,
   showLogo = true,
   showCompanyName = true,
   showCompanyName = true,
   showTorqvoiceBranding,
   showTorqvoiceBranding,
+  expiryNote,
   dateFormat,
   dateFormat,
   timezone,
   timezone,
   termsOfSaleUrl,
   termsOfSaleUrl,
@@ -267,6 +268,8 @@ export function InvoiceView({
   showLogo?: boolean
   showLogo?: boolean
   showCompanyName?: boolean
   showCompanyName?: boolean
   showTorqvoiceBranding?: boolean
   showTorqvoiceBranding?: boolean
+  /** The line saying when this link closes. Page chrome, never part of the sheet. */
+  expiryNote?: React.ReactNode
   dateFormat?: string
   dateFormat?: string
   timezone?: string
   timezone?: string
   termsOfSaleUrl?: string
   termsOfSaleUrl?: string
@@ -843,6 +846,7 @@ export function InvoiceView({
           </a>
           </a>
         )}
         )}
       </div>
       </div>
+      {expiryNote}
 
 
       {/* Image Carousel Modal */}
       {/* Image Carousel Modal */}
       {carouselIndex !== null && imageAttachments[carouselIndex] && (
       {carouselIndex !== null && imageAttachments[carouselIndex] && (

+ 28 - 13
src/app/(public)/share/invoice/[orgId]/[token]/page.tsx

@@ -3,7 +3,6 @@ import { resolveCurrencyCode, resolveCurrencyFormat } from '@/lib/currencies'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { InvoiceView } from './invoice-view'
 import { InvoiceView } from './invoice-view'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
-import { resolvePortalOrg } from '@/lib/portal-slug'
 import { buildInvoicePrintSpec } from '@/features/invoice-designer/Pdf/buildInvoicePrint'
 import { buildInvoicePrintSpec } from '@/features/invoice-designer/Pdf/buildInvoicePrint'
 import { loadPrintLabels } from '@/features/invoice-designer/Pdf/printLabels'
 import { loadPrintLabels } from '@/features/invoice-designer/Pdf/printLabels'
 import { visitConditionMapIn } from '@/features/condition-map/Lib/loadMarks.server'
 import { visitConditionMapIn } from '@/features/condition-map/Lib/loadMarks.server'
@@ -16,8 +15,9 @@ import type { Metadata } from 'next'
 import { documentCustomerId, telegramQrForPrint } from '@/features/invoices/Lib/telegramQr'
 import { documentCustomerId, telegramQrForPrint } from '@/features/invoices/Lib/telegramQr'
 import { offeredPaymentProviders } from '@/features/integrations/Lib/payments'
 import { offeredPaymentProviders } from '@/features/integrations/Lib/payments'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { getAppBaseUrl } from '@/lib/app-url'
-import { ShareLinkExpired } from '@/components/share-link-expired'
-import { findSharedDocument } from '@/lib/share-link.server'
+import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
+import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { lookUpShareLink } from '@/lib/share-link.server'
 
 
 /** Rewrites /api/protected/files/[orgId]/[category]/[filename] to /api/public/files/[token]/[category]/[filename] */
 /** Rewrites /api/protected/files/[orgId]/[category]/[filename] to /api/public/files/[token]/[category]/[filename] */
 function toPublicFileUrl(fileUrl: string, token: string): string {
 function toPublicFileUrl(fileUrl: string, token: string): string {
@@ -29,9 +29,20 @@ function toPublicFileUrl(fileUrl: string, token: string): string {
 
 
 export const revalidate = 60
 export const revalidate = 60
 
 
-export async function generateMetadata(): Promise<Metadata> {
+export async function generateMetadata({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>
+}): Promise<Metadata> {
+  const { orgId, token } = await params
+  const link = await lookUpShareLink('invoice', orgId, token)
+  const robots = { index: false, follow: false }
+  // A closed link's tab does not say what the link led to.
+  if (link.status === 'expired' || link.status === 'gone') {
+    return { title: await closedShareLinkTitle(link.organizationId, link.status), robots }
+  }
   const t = await getTranslations('share.invoice')
   const t = await getTranslations('share.invoice')
-  return { title: t('title'), robots: { index: false, follow: false } }
+  return { title: t('title'), robots }
 }
 }
 
 
 export default async function PublicInvoicePage({
 export default async function PublicInvoicePage({
@@ -41,18 +52,21 @@ export default async function PublicInvoicePage({
 }) {
 }) {
   const { orgId: orgParam, token } = await params
   const { orgId: orgParam, token } = await params
 
 
-  // Resolve slug (e.g. "egelandauto") or UUID to the real org ID
-  const resolvedOrg = await resolvePortalOrg(orgParam)
-  const orgId = resolvedOrg?.id ?? orgParam
-
-  const shared = await findSharedDocument('invoice', token, orgId)
-  if (!shared) notFound()
-  if (!shared.open) return <ShareLinkExpired organizationId={orgId} kind="invoice" />
+  // Only an address with no workshop behind it is the plain 404. A customer
+  // whose link is closed gets a page that tells them who to ask.
+  const link = await lookUpShareLink('invoice', orgParam, token)
+  if (link.status === 'unknownWorkshop') notFound()
+  if (link.status !== 'open') {
+    return (
+      <ShareLinkClosed organizationId={link.organizationId} status={link.status} kind="invoice" />
+    )
+  }
+  const { organizationId: orgId, shared } = link
 
 
   // The document as it was issued, or the live draft: one assembler decides,
   // The document as it was issued, or the live draft: one assembler decides,
   // and the page a customer opens is the sheet the PDF prints.
   // and the page a customer opens is the sheet the PDF prints.
   const assembly = await assembleInvoicePrint(shared.id)
   const assembly = await assembleInvoicePrint(shared.id)
-  if (!assembly) notFound()
+  if (!assembly) return <ShareLinkClosed organizationId={orgId} status="gone" kind="invoice" />
   const { record, settingsMap, org } = assembly
   const { record, settingsMap, org } = assembly
 
 
   const features = await getFeatures(orgId)
   const features = await getFeatures(orgId)
@@ -182,6 +196,7 @@ export default async function PublicInvoicePage({
       findings={assembly.data.findings}
       findings={assembly.data.findings}
       serviceType={assembly.serviceType}
       serviceType={assembly.serviceType}
       taxLabel={assembly.taxLabel}
       taxLabel={assembly.taxLabel}
+      expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       certificateUrl={
       certificateUrl={
         certificateInspection
         certificateInspection
           ? `/api/public/share/invoice/${orgParam}/${token}/certificate`
           ? `/api/public/share/invoice/${orgParam}/${token}/certificate`

+ 28 - 15
src/app/(public)/share/quote/[orgId]/[token]/page.tsx

@@ -5,7 +5,6 @@ import { db } from '@/lib/db'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { QuoteView } from './quote-view'
 import { QuoteView } from './quote-view'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
-import { resolvePortalOrg } from '@/lib/portal-slug'
 import { mergeWithDefaults } from '@/features/settings/Schema/invoiceLayoutSchema'
 import { mergeWithDefaults } from '@/features/settings/Schema/invoiceLayoutSchema'
 import { buildQuotePrintSpec } from '@/features/invoice-designer/Pdf/buildQuotePrint'
 import { buildQuotePrintSpec } from '@/features/invoice-designer/Pdf/buildQuotePrint'
 import { loadPrintLabels } from '@/features/invoice-designer/Pdf/printLabels'
 import { loadPrintLabels } from '@/features/invoice-designer/Pdf/printLabels'
@@ -18,17 +17,29 @@ import { headers } from 'next/headers'
 import type { Metadata } from 'next'
 import type { Metadata } from 'next'
 import { getCustomFieldsForPrint } from '@/features/custom-fields/Lib/getCustomFieldsForPrint'
 import { getCustomFieldsForPrint } from '@/features/custom-fields/Lib/getCustomFieldsForPrint'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { getAppBaseUrl } from '@/lib/app-url'
-import { ShareLinkExpired } from '@/components/share-link-expired'
-import { findSharedDocument } from '@/lib/share-link.server'
+import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
+import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { lookUpShareLink } from '@/lib/share-link.server'
 import { documentSigner } from '@/features/signatures/Lib/memberSignature.server'
 import { documentSigner } from '@/features/signatures/Lib/memberSignature.server'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { gateTypeKey, typeKeyEnabledIn } from '@/features/vehicles/Lib/typeKeySetting'
 import { gateTypeKey, typeKeyEnabledIn } from '@/features/vehicles/Lib/typeKeySetting'
 
 
 export const revalidate = 60
 export const revalidate = 60
 
 
-export async function generateMetadata(): Promise<Metadata> {
+export async function generateMetadata({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>
+}): Promise<Metadata> {
+  const { orgId, token } = await params
+  const link = await lookUpShareLink('quote', orgId, token)
+  const robots = { index: false, follow: false }
+  // A closed link's tab does not say what the link led to.
+  if (link.status === 'expired' || link.status === 'gone') {
+    return { title: await closedShareLinkTitle(link.organizationId, link.status), robots }
+  }
   const t = await getTranslations('share.quote')
   const t = await getTranslations('share.quote')
-  return { title: t('title'), robots: { index: false, follow: false } }
+  return { title: t('title'), robots }
 }
 }
 
 
 export default async function PublicQuotePage({
 export default async function PublicQuotePage({
@@ -38,13 +49,16 @@ export default async function PublicQuotePage({
 }) {
 }) {
   const { orgId: orgParam, token } = await params
   const { orgId: orgParam, token } = await params
 
 
-  // Resolve slug (e.g. "egelandauto") or UUID to the real org ID
-  const resolvedOrg = await resolvePortalOrg(orgParam)
-  const orgId = resolvedOrg?.id ?? orgParam
-
-  const shared = await findSharedDocument('quote', token, orgId)
-  if (!shared) notFound()
-  if (!shared.open) return <ShareLinkExpired organizationId={orgId} kind="quote" />
+  // Only an address with no workshop behind it is the plain 404. A customer
+  // whose link is closed gets a page that tells them who to ask.
+  const link = await lookUpShareLink('quote', orgParam, token)
+  if (link.status === 'unknownWorkshop') notFound()
+  if (link.status !== 'open') {
+    return (
+      <ShareLinkClosed organizationId={link.organizationId} status={link.status} kind="quote" />
+    )
+  }
+  const { organizationId: orgId, shared } = link
 
 
   const quote = await db.quote.findFirst({
   const quote = await db.quote.findFirst({
     where: { publicToken: token, organizationId: orgId },
     where: { publicToken: token, organizationId: orgId },
@@ -93,9 +107,7 @@ export default async function PublicQuotePage({
     },
     },
   })
   })
 
 
-  if (!quote) {
-    notFound()
-  }
+  if (!quote) return <ShareLinkClosed organizationId={orgId} status="gone" kind="quote" />
 
 
   const [settings, org, features] = await Promise.all([
   const [settings, org, features] = await Promise.all([
     db.appSetting.findMany({
     db.appSetting.findMany({
@@ -298,6 +310,7 @@ export default async function PublicQuotePage({
       customFields={customFields}
       customFields={customFields}
       serviceType={(settingsMap['workshop.serviceType'] || 'automotive') as 'automotive' | 'marine'}
       serviceType={(settingsMap['workshop.serviceType'] || 'automotive') as 'automotive' | 'marine'}
       taxLabel={settingsMap['workshop.taxLabel']?.trim() || undefined}
       taxLabel={settingsMap['workshop.taxLabel']?.trim() || undefined}
+      expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       certificateUrl={
       certificateUrl={
         certificateInspection
         certificateInspection
           ? `/api/public/share/quote/${orgParam}/${token}/certificate`
           ? `/api/public/share/quote/${orgParam}/${token}/certificate`

+ 4 - 0
src/app/(public)/share/quote/[orgId]/[token]/quote-view.tsx

@@ -173,6 +173,7 @@ export function QuoteView({
   certificateUrl,
   certificateUrl,
   logoUrl,
   logoUrl,
   showTorqvoiceBranding,
   showTorqvoiceBranding,
+  expiryNote,
   dateFormat,
   dateFormat,
   timezone,
   timezone,
   primaryColor = '#d97706',
   primaryColor = '#d97706',
@@ -198,6 +199,8 @@ export function QuoteView({
   certificateUrl?: string
   certificateUrl?: string
   logoUrl?: string
   logoUrl?: string
   showTorqvoiceBranding?: boolean
   showTorqvoiceBranding?: boolean
+  /** The line saying when this link closes. Page chrome, never part of the sheet. */
+  expiryNote?: React.ReactNode
   dateFormat?: string
   dateFormat?: string
   timezone?: string
   timezone?: string
   primaryColor?: string
   primaryColor?: string
@@ -573,6 +576,7 @@ export function QuoteView({
           <p className="text-center text-xs text-gray-400">{shopName}</p>
           <p className="text-center text-xs text-gray-400">{shopName}</p>
         )}
         )}
       </div>
       </div>
+      {expiryNote}
 
 
       {/* Image Carousel Modal */}
       {/* Image Carousel Modal */}
       {carouselIndex !== null && imageAttachments[carouselIndex] && (
       {carouselIndex !== null && imageAttachments[carouselIndex] && (

+ 76 - 32
src/app/(public)/share/status-report/[orgId]/[token]/page.tsx

@@ -1,5 +1,8 @@
 import { getTranslations } from 'next-intl/server'
 import { getTranslations } from 'next-intl/server'
-import { ShareLinkExpired } from '@/components/share-link-expired'
+import { cache } from 'react'
+import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
+import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import type { ShareLinkLookup } from '@/lib/share-link.server'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { StatusReportView } from './status-report-view'
 import { StatusReportView } from './status-report-view'
@@ -15,50 +18,83 @@ function toPublicFileUrl(fileUrl: string, token: string): string {
 
 
 export const revalidate = 0
 export const revalidate = 0
 export const dynamic = 'force-dynamic'
 export const dynamic = 'force-dynamic'
-export async function generateMetadata(): Promise<Metadata> {
-  const t = await getTranslations('statusReport.create')
-  return {
-    title: t('title'),
-    robots: { index: false, follow: false, nocache: true, noarchive: true, nosnippet: true },
-  }
-}
-
-export default async function PublicStatusReportPage({
-  params,
-}: {
-  params: Promise<{ orgId: string; token: string }>
-}) {
-  const { orgId: orgParam, token } = await params
-  const resolvedOrg = await resolvePortalOrg(orgParam)
-  const orgId = resolvedOrg?.id ?? orgParam
 
 
-  // The report and what it is about: a job, or an inspection.
-  const vehicle = { select: { make: true, model: true, year: true, licensePlate: true } }
-  const report = await db.statusReport.findUnique({
+// The report and what it is about: a job, or an inspection.
+const vehicle = { select: { make: true, model: true, year: true, licensePlate: true } }
+function findReport(token: string) {
+  return db.statusReport.findUnique({
     where: { publicToken: token },
     where: { publicToken: token },
     include: {
     include: {
       serviceRecord: { select: { title: true, vehicle } },
       serviceRecord: { select: { title: true, vehicle } },
       inspection: { select: { template: { select: { name: true } }, vehicle } },
       inspection: { select: { template: { select: { name: true } }, vehicle } },
-      technician: {
-        select: { name: true },
-      },
-      organization: {
-        select: { name: true },
-      },
+      technician: { select: { name: true } },
+      organization: { select: { name: true } },
     },
     },
   })
   })
+}
+type Report = NonNullable<Awaited<ReturnType<typeof findReport>>>
+
+/**
+ * The same answers the other share pages give. A report the clean-up has
+ * deleted, a token cut short and one from another workshop are all "gone".
+ */
+const lookUpReport = cache(
+  async (orgParam: string, token: string): Promise<ShareLinkLookup<Report>> => {
+    const org = await resolvePortalOrg(orgParam)
+    if (!org) return { status: 'unknownWorkshop' }
+    const report = await findReport(token)
+    if (!report || report.organizationId !== org.id) {
+      return { status: 'gone', organizationId: org.id }
+    }
+    if (report.expiresAt && report.expiresAt < new Date()) {
+      return { status: 'expired', organizationId: org.id }
+    }
+    return { status: 'open', organizationId: org.id, shared: report }
+  }
+)
 
 
-  if (!report || report.organizationId !== orgId) {
-    notFound()
+export async function generateMetadata({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>
+}): Promise<Metadata> {
+  const { orgId, token } = await params
+  const link = await lookUpReport(orgId, token)
+  const robots = { index: false, follow: false, nocache: true, noarchive: true, nosnippet: true }
+  // A closed link's tab does not say what the link led to.
+  if (link.status === 'expired' || link.status === 'gone') {
+    return { title: await closedShareLinkTitle(link.organizationId, link.status), robots }
   }
   }
+  const t = await getTranslations('statusReport.create')
+  return { title: t('title'), robots }
+}
+
+export default async function PublicStatusReportPage({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>
+}) {
+  const { orgId: orgParam, token } = await params
 
 
-  // Check if expired
-  if (report.expiresAt && report.expiresAt < new Date()) {
-    return <ShareLinkExpired organizationId={orgId} kind="statusReport" />
+  // Only an address with no workshop behind it is the plain 404. A customer
+  // whose link is closed gets a page that tells them who to ask.
+  const link = await lookUpReport(orgParam, token)
+  if (link.status === 'unknownWorkshop') notFound()
+  if (link.status !== 'open') {
+    return (
+      <ShareLinkClosed
+        organizationId={link.organizationId}
+        status={link.status}
+        kind="statusReport"
+      />
+    )
   }
   }
+  const { organizationId: orgId, shared: report } = link
 
 
   const subject = report.serviceRecord ?? report.inspection
   const subject = report.serviceRecord ?? report.inspection
-  if (!subject) notFound()
+  if (!subject) {
+    return <ShareLinkClosed organizationId={orgId} status="gone" kind="statusReport" />
+  }
   const serviceTitle = report.serviceRecord?.title ?? report.inspection?.template.name ?? ''
   const serviceTitle = report.serviceRecord?.title ?? report.inspection?.template.name ?? ''
 
 
   // Mark as viewed on first visit
   // Mark as viewed on first visit
@@ -117,6 +153,14 @@ export default async function PublicStatusReportPage({
       primaryColor={settingsMap['invoice.primaryColor'] || '#3b82f6'}
       primaryColor={settingsMap['invoice.primaryColor'] || '#3b82f6'}
       token={token}
       token={token}
       showBranding={!features.brandingRemoved}
       showBranding={!features.brandingRemoved}
+      expiryNote={
+        report.expiresAt && (
+          <ShareLinkOpenUntil
+            organizationId={orgId}
+            expiry={{ kind: 'date', at: report.expiresAt, source: 'document' }}
+          />
+        )
+      }
     />
     />
   )
   )
 }
 }

+ 4 - 0
src/app/(public)/share/status-report/[orgId]/[token]/status-report-view.tsx

@@ -30,6 +30,8 @@ interface StatusReportViewProps {
   primaryColor: string
   primaryColor: string
   token: string
   token: string
   showBranding: boolean
   showBranding: boolean
+  /** The line saying when this link closes. Page chrome, never part of the sheet. */
+  expiryNote?: React.ReactNode
 }
 }
 
 
 export function StatusReportView({
 export function StatusReportView({
@@ -43,6 +45,7 @@ export function StatusReportView({
   primaryColor,
   primaryColor,
   token,
   token,
   showBranding,
   showBranding,
+  expiryNote,
 }: StatusReportViewProps) {
 }: StatusReportViewProps) {
   const t = useTranslations('statusReport.view')
   const t = useTranslations('statusReport.view')
   const [feedback, setFeedback] = useState('')
   const [feedback, setFeedback] = useState('')
@@ -190,6 +193,7 @@ export function StatusReportView({
         {showBranding && (
         {showBranding && (
           <p className="text-center text-xs text-gray-400 py-4">{t('poweredBy')} Torqvoice</p>
           <p className="text-center text-xs text-gray-400 py-4">{t('poweredBy')} Torqvoice</p>
         )}
         )}
+        {expiryNote}
       </div>
       </div>
     </div>
     </div>
   )
   )

+ 60 - 19
src/components/share-link-expired.tsx

@@ -1,4 +1,4 @@
-import { ClockAlert, Mail, Phone } from 'lucide-react'
+import { ClockAlert, Link2Off, Mail, Phone } from 'lucide-react'
 import { headers } from 'next/headers'
 import { headers } from 'next/headers'
 import { getTranslations } from 'next-intl/server'
 import { getTranslations } from 'next-intl/server'
 import { resolveCustomerLocale } from '@/i18n/locale-from-request'
 import { resolveCustomerLocale } from '@/i18n/locale-from-request'
@@ -6,49 +6,85 @@ import { db } from '@/lib/db'
 
 
 type ExpiredKind = 'invoice' | 'quote' | 'inspection' | 'statusReport'
 type ExpiredKind = 'invoice' | 'quote' | 'inspection' | 'statusReport'
 
 
+/** Written in the reader's language, the way the document itself would be. */
+async function readerLocale(organizationId: string) {
+  const acceptLanguage = (await headers()).get('accept-language')
+  return resolveCustomerLocale(organizationId, acceptLanguage)
+}
+
+/**
+ * The tab title of a page whose link is closed. It never names the kind of
+ * document: a link that opens nothing has no document to name.
+ */
+export async function closedShareLinkTitle(
+  organizationId: string,
+  status: 'expired' | 'gone'
+): Promise<string> {
+  const locale = await readerLocale(organizationId)
+  const t = await getTranslations({ locale, namespace: 'share' })
+  return t(`${status}.pageTitle`)
+}
+
 /**
 /**
- * What a customer sees when the link they were sent has expired: that it
- * has, and how to reach the workshop for a new one. Nothing of the document
- * is on the page, not even its title.
+ * The page for a link that is closed, whichever way it closed.
  *
  *
- * Written in the reader's language, the way the document itself would be.
+ * Expired: the link was real and its date has passed. The page says so and
+ * how to reach the workshop for a new one.
+ *
+ * Gone: the address names a real workshop and a token that opens nothing. A
+ * link the workshop removed, one cut short on its way to the customer and
+ * one that never was all get this same page, so it cannot be used to test a
+ * token.
+ *
+ * Nothing of any document is on either page, not even its title.
  */
  */
-export async function ShareLinkExpired({
+export async function ShareLinkClosed({
   organizationId,
   organizationId,
+  status,
   kind,
   kind,
 }: {
 }: {
   organizationId: string
   organizationId: string
+  status: 'expired' | 'gone'
   kind: ExpiredKind
   kind: ExpiredKind
 }) {
 }) {
-  const [org, rows, acceptLanguage] = await Promise.all([
+  const [org, rows, locale] = await Promise.all([
     db.organization.findUnique({ where: { id: organizationId }, select: { name: true } }),
     db.organization.findUnique({ where: { id: organizationId }, select: { name: true } }),
     db.appSetting.findMany({
     db.appSetting.findMany({
       where: { organizationId, key: { in: ['workshop.phone', 'workshop.email'] } },
       where: { organizationId, key: { in: ['workshop.phone', 'workshop.email'] } },
       select: { key: true, value: true },
       select: { key: true, value: true },
     }),
     }),
-    headers().then((h) => h.get('accept-language')),
+    readerLocale(organizationId),
   ])
   ])
-  const locale = await resolveCustomerLocale(organizationId, acceptLanguage)
-  const t = await getTranslations({ locale, namespace: 'share.expired' })
+  const t = await getTranslations({ locale, namespace: 'share' })
 
 
   const phone = rows.find((r) => r.key === 'workshop.phone')?.value?.trim()
   const phone = rows.find((r) => r.key === 'workshop.phone')?.value?.trim()
   const email = rows.find((r) => r.key === 'workshop.email')?.value?.trim()
   const email = rows.find((r) => r.key === 'workshop.email')?.value?.trim()
   const workshop = org?.name?.trim()
   const workshop = org?.name?.trim()
 
 
+  const expired = status === 'expired'
+  const Icon = expired ? ClockAlert : Link2Off
+  const title = t(`${status}.title`)
+  // Only an expired link says what it led to: the customer held it.
+  const body = expired
+    ? workshop
+      ? t(`expired.body.${kind}`, { workshop })
+      : t(`expired.bodyNoName.${kind}`)
+    : workshop
+      ? t('gone.body', { workshop })
+      : t('gone.bodyNoName')
+
   return (
   return (
     <main className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
     <main className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
-      <div className="w-full max-w-sm rounded-xl border bg-background p-8 text-center shadow-sm">
-        <ClockAlert className="mx-auto h-8 w-8 text-muted-foreground" aria-hidden="true" />
-        <h1 className="mt-4 text-lg font-semibold">{t('title')}</h1>
-        <p className="mt-2 text-sm text-muted-foreground">
-          {workshop ? t(`body.${kind}`, { workshop }) : t(`bodyNoName.${kind}`)}
-        </p>
+      <div className="w-full max-w-sm rounded-xl border bg-background p-8 pb-6 text-center shadow-sm">
+        <Icon className="mx-auto h-8 w-8 text-muted-foreground" aria-hidden="true" />
+        <h1 className="mt-4 text-lg font-semibold">{title}</h1>
+        <p className="mt-2 text-sm text-muted-foreground">{body}</p>
         {(phone || email) && (
         {(phone || email) && (
-          <div className="mt-6 space-y-2 border-t pt-4 text-sm">
+          <div className="mt-6 border-t pt-2 text-sm">
             {phone && (
             {phone && (
               <a
               <a
                 href={`tel:${phone.replace(/\s+/g, '')}`}
                 href={`tel:${phone.replace(/\s+/g, '')}`}
-                className="flex items-center justify-center gap-2 text-foreground hover:underline"
+                className="flex min-h-11 items-center justify-center gap-2 text-foreground hover:underline"
               >
               >
                 <Phone className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                 <Phone className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                 {phone}
                 {phone}
@@ -57,7 +93,7 @@ export async function ShareLinkExpired({
             {email && (
             {email && (
               <a
               <a
                 href={`mailto:${email}`}
                 href={`mailto:${email}`}
-                className="flex items-center justify-center gap-2 text-foreground hover:underline"
+                className="flex min-h-11 items-center justify-center gap-2 text-foreground hover:underline"
               >
               >
                 <Mail className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                 <Mail className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                 {email}
                 {email}
@@ -69,3 +105,8 @@ export async function ShareLinkExpired({
     </main>
     </main>
   )
   )
 }
 }
+
+/** The page for a link past its date. */
+export function ShareLinkExpired(props: { organizationId: string; kind: ExpiredKind }) {
+  return <ShareLinkClosed {...props} status="expired" />
+}

+ 58 - 0
src/components/share-link-open-until.tsx

@@ -0,0 +1,58 @@
+import { headers } from 'next/headers'
+import { getTranslations } from 'next-intl/server'
+import { resolveCustomerLocale } from '@/i18n/locale-from-request'
+import { db } from '@/lib/db'
+import { formatDate } from '@/lib/format'
+import { type ShareExpiry, shareOpenUntilDay } from '@/lib/share-expiry'
+import { resolveWorkshopTimeZone } from '@/lib/timezone'
+
+/**
+ * One quiet line at the foot of a share page saying the day its link stops
+ * working, so the customer is not surprised by a closed link later.
+ *
+ * It belongs to the page, never to the document: the sheet and the PDF are
+ * what was issued, and the day depends on a rule the workshop can change.
+ * Nothing is shown for a link with no date, which includes an unpaid invoice
+ * that stays open until it is paid.
+ *
+ * The day is the workshop's, in the workshop's date format.
+ */
+export async function ShareLinkOpenUntil({
+  organizationId,
+  expiry,
+}: {
+  organizationId: string
+  expiry: ShareExpiry
+}) {
+  if (expiry.kind !== 'date') return null
+
+  const [org, rows, acceptLanguage] = await Promise.all([
+    db.organization.findUnique({ where: { id: organizationId }, select: { name: true } }),
+    db.appSetting.findMany({
+      where: {
+        organizationId,
+        key: { in: ['workshop.timezone', 'workshop.timezoneDetected', 'workshop.dateFormat'] },
+      },
+      select: { key: true, value: true },
+    }),
+    headers().then((h) => h.get('accept-language')),
+  ])
+  const setting = (key: string) => rows.find((r) => r.key === key)?.value
+  const timeZone = resolveWorkshopTimeZone(
+    setting('workshop.timezone'),
+    setting('workshop.timezoneDetected')
+  )
+  const day = shareOpenUntilDay(expiry, timeZone)
+  if (!day) return null
+
+  const locale = await resolveCustomerLocale(organizationId, acceptLanguage)
+  const t = await getTranslations({ locale, namespace: 'share.openUntil' })
+  const date = formatDate(day, setting('workshop.dateFormat') || undefined, timeZone)
+  const workshop = org?.name?.trim()
+
+  return (
+    <p className="mt-3 text-balance text-center text-xs text-muted-foreground print:hidden">
+      {workshop ? t('text', { date, workshop }) : t('textNoName', { date })}
+    </p>
+  )
+}

+ 23 - 1
src/lib/share-expiry.ts

@@ -1,4 +1,4 @@
-import { addZonedDays } from '@/lib/timezone'
+import { addZonedDays, startOfZonedDay } from '@/lib/timezone'
 
 
 /**
 /**
  * When a share link stops working.
  * When a share link stops working.
@@ -169,6 +169,28 @@ export function isShareExpired(expiry: ShareExpiry, now: Date = new Date()): boo
   return expiry.kind === 'date' && expiry.at.getTime() < now.getTime()
   return expiry.kind === 'date' && expiry.at.getTime() < now.getTime()
 }
 }
 
 
+/**
+ * The last day a customer can be told the link works, or null when there is
+ * no such day to name: the link has no date, or the date has passed (a
+ * portal customer still reading their own document).
+ *
+ * A link that closes at the end of a workshop day works for the whole of
+ * that day. One that closes partway through a day (a status report lives 14
+ * days to the minute) is promised only up to the day before, unless that
+ * day is today.
+ */
+export function shareOpenUntilDay(
+  expiry: ShareExpiry,
+  timeZone: string,
+  now: Date = new Date()
+): Date | null {
+  if (expiry.kind !== 'date' || isShareExpired(expiry, now)) return null
+  const dayStart = startOfZonedDay(expiry.at, timeZone)
+  const endsTheDay = addZonedDays(expiry.at, 1, timeZone).getTime() - 1 === expiry.at.getTime()
+  if (endsTheDay || dayStart.getTime() <= now.getTime()) return expiry.at
+  return new Date(dayStart.getTime() - 1)
+}
+
 /**
 /**
  * Whether an invoice is paid in full, and the day it was. Marked paid by hand
  * Whether an invoice is paid in full, and the day it was. Marked paid by hand
  * counts as paid whatever is recorded; otherwise the payments must cover the
  * counts as paid whatever is recorded; otherwise the payments must cover the

+ 38 - 0
src/lib/share-link.server.ts

@@ -1,4 +1,5 @@
 import 'server-only'
 import 'server-only'
+import { cache } from 'react'
 import { getCustomerSession } from '@/lib/customer-session'
 import { getCustomerSession } from '@/lib/customer-session'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import {
 import {
@@ -17,6 +18,7 @@ import {
   type ShareKind,
   type ShareKind,
   type ShareLinkFacts,
   type ShareLinkFacts,
 } from '@/lib/share-expiry'
 } from '@/lib/share-expiry'
+import { resolvePortalOrg } from '@/lib/portal-slug'
 import { resolveWorkshopTimeZone } from '@/lib/timezone'
 import { resolveWorkshopTimeZone } from '@/lib/timezone'
 
 
 /**
 /**
@@ -216,3 +218,39 @@ export async function findSharedDocumentOfAnyKind(
   }
   }
   return null
   return null
 }
 }
+
+/**
+ * What a share page finds at its address.
+ *
+ * - `unknownWorkshop`: nothing answers to the workshop part of the address.
+ * - `gone`: the workshop is real, the token opens nothing. A removed link, a
+ *   mistyped one and one that never existed are the same answer, so the page
+ *   confirms nothing about any token.
+ * - `expired`: the link is real and past its date.
+ * - `open`: the document, for the page to render.
+ */
+export type ShareLinkLookup<T> =
+  | { status: 'unknownWorkshop' }
+  | { status: 'gone'; organizationId: string }
+  | { status: 'expired'; organizationId: string }
+  | { status: 'open'; organizationId: string; shared: T }
+
+/**
+ * A share page's address, read once per request: the page and its tab title
+ * both ask, and get the same answer from one lookup.
+ */
+export const lookUpShareLink = cache(
+  async (
+    kind: ShareKind,
+    orgParam: string,
+    token: string
+  ): Promise<ShareLinkLookup<SharedDocument>> => {
+    // A slug (e.g. "egelandauto") or the organization's id.
+    const org = await resolvePortalOrg(orgParam)
+    if (!org) return { status: 'unknownWorkshop' }
+    const shared = await findSharedDocument(kind, token, org.id)
+    if (!shared) return { status: 'gone', organizationId: org.id }
+    if (!shared.open) return { status: 'expired', organizationId: org.id }
+    return { status: 'open', organizationId: org.id, shared }
+  }
+)