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

Say so once when a role opens nothing (#274)

Bernt Christian Egeland 2 месяцев назад
Родитель
Сommit
3a08ae1f4d

+ 3 - 1
messages/de/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Diese Werkstatt hat noch keine Rollen, außer Admin gibt es also nichts zu vergeben. Legen Sie die Standardrollen an und schränken Sie die Rechte später ein.",
     "noRoleDescription": "Überhaupt keine Rechte. Sie können sich anmelden, aber jeder Bildschirm weist sie ab, bis Sie ihnen unten eine Rolle geben.",
     "cannotUseApp": "Diese Rolle kann keine Aufträge bearbeiten. Geben Sie ihr zuerst Techniker oder eine Rolle mit denselben Rechten.",
-    "revokeTechnicianDone": "{name} wurde aus der App abgemeldet"
+    "revokeTechnicianDone": "{name} wurde aus der App abgemeldet",
+    "noAccessTitle": "Noch kein Zugriff",
+    "noAccessBody": "Ihr Konto gehört zu {workshop}, hat aber noch keine Rolle, deshalb gibt es hier nichts zu öffnen. Bitten Sie einen Inhaber oder Administrator Ihrer Werkstatt um eine Rolle."
   },
   "invoice": {
     "title": "Rechnungslayout",

+ 3 - 1
messages/en/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "This workshop has no roles yet, so there is nothing to give them beyond Admin. Create the standard ones and narrow the permissions later.",
     "noRoleDescription": "No permissions at all. They can sign in and every screen will refuse them until you give them a role below.",
     "cannotUseApp": "Their role cannot work on jobs. Give them Technician, or a role with the same permissions, first.",
-    "revokeTechnicianDone": "{name} has been signed out of the app"
+    "revokeTechnicianDone": "{name} has been signed out of the app",
+    "noAccessTitle": "No access yet",
+    "noAccessBody": "Your account is part of {workshop}, but it has not been given a role, so there is nothing here you can open yet. Ask an owner or an admin at your workshop to give you one."
   },
   "invoice": {
     "title": "Invoice & Quotes",

+ 3 - 1
messages/es/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Este taller aún no tiene roles, así que no hay nada que darle aparte de Admin. Cree los estándar y ajuste los permisos después.",
     "noRoleDescription": "Sin permisos. Puede iniciar sesión, pero todas las pantallas lo rechazarán hasta que le dé un rol de los de abajo.",
     "cannotUseApp": "Su rol no puede trabajar en los trabajos. Déle primero Técnico, o un rol con los mismos permisos.",
-    "revokeTechnicianDone": "{name} ha salido de la aplicación"
+    "revokeTechnicianDone": "{name} ha salido de la aplicación",
+    "noAccessTitle": "Sin acceso todavía",
+    "noAccessBody": "Su cuenta pertenece a {workshop}, pero no tiene un rol asignado, así que aquí no hay nada que pueda abrir. Pida un rol a un propietario o administrador de su taller."
   },
   "invoice": {
     "title": "Diseño de factura",

+ 3 - 1
messages/fr/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Cet atelier n’a encore aucun rôle, il n’y a donc rien à leur donner en dehors d’Admin. Créez les rôles standard et affinez les permissions plus tard.",
     "noRoleDescription": "Aucune permission. La personne peut se connecter, mais chaque écran la refusera tant que vous ne lui aurez pas donné un rôle ci-dessous.",
     "cannotUseApp": "Son rôle ne permet pas de travailler sur les travaux. Donnez-lui d’abord Technicien, ou un rôle ayant les mêmes permissions.",
-    "revokeTechnicianDone": "{name} a été déconnecté de l’application"
+    "revokeTechnicianDone": "{name} a été déconnecté de l’application",
+    "noAccessTitle": "Pas encore d’accès",
+    "noAccessBody": "Votre compte fait partie de {workshop}, mais aucun rôle ne lui a été attribué, donc il n’y a rien à ouvrir ici. Demandez un rôle à un propriétaire ou un administrateur de votre atelier."
   },
   "invoice": {
     "title": "Mise en page de facture",

+ 3 - 1
messages/it/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Questa officina non ha ancora ruoli, quindi non c’è nulla da assegnare oltre ad Admin. Crea quelli standard e restringi i permessi dopo.",
     "noRoleDescription": "Nessun permesso. Può accedere, ma ogni schermata lo rifiuta finché non gli assegni un ruolo qui sotto.",
     "cannotUseApp": "Il suo ruolo non può lavorare sui lavori. Assegnagli prima Tecnico, o un ruolo con gli stessi permessi.",
-    "revokeTechnicianDone": "{name} è stato disconnesso dall’app"
+    "revokeTechnicianDone": "{name} è stato disconnesso dall’app",
+    "noAccessTitle": "Ancora nessun accesso",
+    "noAccessBody": "Il tuo account fa parte di {workshop}, ma non ha ancora un ruolo, quindi qui non c’è nulla da aprire. Chiedi un ruolo a un titolare o a un amministratore della tua officina."
   },
   "invoice": {
     "title": "Layout fattura",

+ 3 - 1
messages/lt/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Šios dirbtuvės dar neturi rolių, todėl, be administratoriaus, nėra ko suteikti. Sukurkite standartines ir teises patikslinkite vėliau.",
     "noRoleDescription": "Jokių teisių. Gali prisijungti, bet kiekvienas ekranas jį atmes, kol nesuteiksite rolės žemiau.",
     "cannotUseApp": "Jo rolė neleidžia dirbti su užsakymais. Pirma suteikite meistro rolę arba rolę su tomis pačiomis teisėmis.",
-    "revokeTechnicianDone": "{name} atjungtas nuo programėlės"
+    "revokeTechnicianDone": "{name} atjungtas nuo programėlės",
+    "noAccessTitle": "Prieigos kol kas nėra",
+    "noAccessBody": "Jūsų paskyra priklauso {workshop}, bet jai dar nesuteikta rolė, todėl čia nėra ką atidaryti. Paprašykite dirbtuvių savininko arba administratoriaus suteikti jums rolę."
   },
   "invoice": {
     "title": "Sąskaitos ir pasiūlymai",

+ 3 - 1
messages/nb/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Dette verkstedet har ingen roller ennå, så det finnes ingenting å gi dem utover Admin. Opprett standardrollene og juster tillatelsene senere.",
     "noRoleDescription": "Ingen tillatelser i det hele tatt. De kan logge inn, men hver skjerm avviser dem til du gir dem en rolle nedenfor.",
     "cannotUseApp": "Rollen deres kan ikke jobbe på jobber. Gi dem Tekniker, eller en rolle med de samme tillatelsene, først.",
-    "revokeTechnicianDone": "{name} er logget ut av appen"
+    "revokeTechnicianDone": "{name} er logget ut av appen",
+    "noAccessTitle": "Ingen tilgang ennå",
+    "noAccessBody": "Kontoen din tilhører {workshop}, men den har ikke fått en rolle ennå, så det er ingenting her du kan åpne. Be en eier eller administrator på verkstedet om å gi deg en."
   },
   "invoice": {
     "title": "Faktura og tilbud",

+ 3 - 1
messages/nl/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Deze werkplaats heeft nog geen rollen, dus er valt niets te geven behalve Admin. Maak de standaardrollen aan en verfijn de rechten later.",
     "noRoleDescription": "Geen rechten. Ze kunnen inloggen, maar elk scherm weigert ze tot u hieronder een rol toekent.",
     "cannotUseApp": "Hun rol kan niet aan klussen werken. Geef ze eerst Monteur, of een rol met dezelfde rechten.",
-    "revokeTechnicianDone": "{name} is uitgelogd uit de app"
+    "revokeTechnicianDone": "{name} is uitgelogd uit de app",
+    "noAccessTitle": "Nog geen toegang",
+    "noAccessBody": "Uw account hoort bij {workshop}, maar heeft nog geen rol, dus er is hier niets te openen. Vraag een eigenaar of beheerder van uw werkplaats om een rol."
   },
   "invoice": {
     "title": "Factuurindeling",

+ 3 - 1
messages/pl/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Ten warsztat nie ma jeszcze żadnych ról, więc poza Adminem nie ma czego przydzielić. Utwórz standardowe i dopracuj uprawnienia później.",
     "noRoleDescription": "Brak jakichkolwiek uprawnień. Może się zalogować, ale każdy ekran go odrzuci, dopóki nie nadasz mu roli poniżej.",
     "cannotUseApp": "Ta rola nie może pracować przy zleceniach. Nadaj najpierw rolę Technik lub inną z tymi samymi uprawnieniami.",
-    "revokeTechnicianDone": "{name} został wylogowany z aplikacji"
+    "revokeTechnicianDone": "{name} został wylogowany z aplikacji",
+    "noAccessTitle": "Brak dostępu",
+    "noAccessBody": "Twoje konto należy do {workshop}, ale nie ma jeszcze przypisanej roli, więc nie ma tu nic, co możesz otworzyć. Poproś właściciela lub administratora warsztatu o rolę."
   },
   "invoice": {
     "title": "Układ faktury",

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

@@ -493,7 +493,9 @@
     "noRolesYet": "Esta oficina ainda não tem funções, então não há o que dar além de Admin. Crie as padrão e ajuste as permissões depois.",
     "noRoleDescription": "Nenhuma permissão. A pessoa consegue entrar, mas todas as telas a recusam até você dar uma função abaixo.",
     "cannotUseApp": "A função dela não permite trabalhar em serviços. Dê primeiro Técnico, ou uma função com as mesmas permissões.",
-    "revokeTechnicianDone": "{name} foi desconectado do aplicativo"
+    "revokeTechnicianDone": "{name} foi desconectado do aplicativo",
+    "noAccessTitle": "Ainda sem acesso",
+    "noAccessBody": "Sua conta faz parte da {workshop}, mas ainda não recebeu uma função, então não há nada aqui que você possa abrir. Peça uma função ao proprietário ou a um administrador da sua oficina."
   },
   "invoice": {
     "title": "Layout da fatura",

+ 3 - 1
messages/ru/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "В этой мастерской пока нет ролей, поэтому дать нечего, кроме роли администратора. Создайте стандартные и настройте права позже.",
     "noRoleDescription": "Никаких прав. Такой человек может войти, но каждый экран будет ему отказывать, пока вы не назначите роль ниже.",
     "cannotUseApp": "Его роль не позволяет работать с заказ-нарядами. Сначала назначьте роль механика или роль с теми же правами.",
-    "revokeTechnicianDone": "{name} вышел из приложения"
+    "revokeTechnicianDone": "{name} вышел из приложения",
+    "noAccessTitle": "Доступа пока нет",
+    "noAccessBody": "Ваша учётная запись относится к {workshop}, но ей ещё не назначена роль, поэтому открыть здесь нечего. Попросите владельца или администратора мастерской назначить вам роль."
   },
   "invoice": {
     "title": "Счета и предложения",

+ 3 - 1
messages/tr/settings.json

@@ -493,7 +493,9 @@
     "noRolesYet": "Bu atölyede henüz rol yok, bu yüzden Yönetici dışında verilecek bir şey bulunmuyor. Standart rolleri oluşturup izinleri sonra daraltın.",
     "noRoleDescription": "Hiçbir izni yok. Giriş yapabilir ama aşağıdan bir rol verene kadar her ekran onu reddeder.",
     "cannotUseApp": "Rolü işler üzerinde çalışmaya izin vermiyor. Önce Teknisyen ya da aynı izinlere sahip bir rol verin.",
-    "revokeTechnicianDone": "{name} uygulamadan çıkarıldı"
+    "revokeTechnicianDone": "{name} uygulamadan çıkarıldı",
+    "noAccessTitle": "Henüz erişim yok",
+    "noAccessBody": "Hesabınız {workshop} atölyesine ait, ancak henüz bir rol verilmemiş; bu yüzden burada açabileceğiniz bir şey yok. Atölyenizdeki bir sahip ya da yöneticiden rol isteyin."
   },
   "invoice": {
     "title": "Fatura Düzeni",

+ 19 - 0
src/app/(authenticated)/layout.tsx

@@ -1,4 +1,5 @@
 import { redirect } from 'next/navigation'
+import { NoAccess } from './no-access'
 import { AppSidebar } from '@/components/app-sidebar'
 import { FeatureHintProvider } from '@/components/feature-hint'
 import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
@@ -79,6 +80,16 @@ export default async function DashboardLayout({ children }: { children: React.Re
   const allSubjects = Object.values(PermissionSubject)
   let visibleSubjects: string[] = allSubjects
 
+  /**
+   * Whether this account can reach anything at all.
+   *
+   * Kept separate from what the sidebar shows, because the two answer
+   * different questions and conflating them is what made a roleless account
+   * look like a broken product: the nav offered every screen and every screen
+   * refused, one at a time.
+   */
+  let hasAnyAccess = true
+
   if (!isOwnerOrAdmin) {
     const membership = await getCachedMembership(data.userId)
     // Members without a custom role have full access
@@ -90,9 +101,17 @@ export default async function DashboardLayout({ children }: { children: React.Re
           subject: subject as PermissionSubject,
         })
       )
+      // A role that grants nothing readable. Every page behind the nav would
+      // answer "Your role does not allow this", so say it once instead.
+      hasAnyAccess = visibleSubjects.length > 0
     }
   }
 
+  if (!hasAnyAccess) {
+    const org = data.organizations.find((o) => o.id === data.organizationId)
+    return <NoAccess organizationName={org?.name ?? ''} />
+  }
+
   // Check license expiry (only for admin/owner with white-label)
   let daysUntilExpiry: number | null = null
   let licenseExpiryDismissed = false

+ 25 - 0
src/app/(authenticated)/no-access-actions.tsx

@@ -0,0 +1,25 @@
+'use client'
+
+import { useRouter } from 'next/navigation'
+import { useTranslations } from 'next-intl'
+import { Button } from '@/components/ui/button'
+import { signOut } from '@/lib/auth-client'
+
+/** The one thing this account can still do. */
+export function NoAccessSignOut() {
+  const router = useRouter()
+  const t = useTranslations('navigation.sidebar')
+
+  return (
+    <Button
+      type="button"
+      variant="outline"
+      onClick={async () => {
+        await signOut()
+        router.push('/auth/sign-in')
+      }}
+    >
+      {t('signOut')}
+    </Button>
+  )
+}

+ 40 - 0
src/app/(authenticated)/no-access.tsx

@@ -0,0 +1,40 @@
+import { ShieldOff } from 'lucide-react'
+import { getTranslations } from 'next-intl/server'
+import { NoAccessSignOut } from './no-access-actions'
+
+/**
+ * What somebody sees when their role grants them nothing.
+ *
+ * They used to see the whole application: a full sidebar, and every page
+ * behind it answering "Your role does not allow this". An account that can
+ * reach no screen at all should say so once, plainly, rather than let somebody
+ * discover it one refusal at a time.
+ *
+ * Deliberately names who fixes it. The person reading this cannot: only an
+ * owner or admin of their workshop can give them a role, and without that
+ * sentence the obvious conclusion is that the product is broken.
+ */
+export async function NoAccess({ organizationName }: { organizationName: string }) {
+  const t = await getTranslations('settings.team')
+
+  return (
+    <div className="flex min-h-svh items-center justify-center bg-background p-6">
+      <div className="w-full max-w-md space-y-4 rounded-lg border bg-card p-6 text-center">
+        <div className="mx-auto flex h-11 w-11 items-center justify-center rounded-full bg-muted">
+          <ShieldOff className="h-5 w-5 text-muted-foreground" />
+        </div>
+
+        <div className="space-y-2">
+          <h1 className="font-semibold text-lg">{t('noAccessTitle')}</h1>
+          <p className="text-muted-foreground text-sm">
+            {t('noAccessBody', { workshop: organizationName })}
+          </p>
+        </div>
+
+        <div className="pt-2">
+          <NoAccessSignOut />
+        </div>
+      </div>
+    </div>
+  )
+}