Răsfoiți Sursa

Show free workshops their plan and an Upgrade link at the foot of the sidebar (#693)

A plan row above the account menu, on Torqvoice Cloud only, for owners
and admins of a workshop on Free or on a demo without Stripe. Free shows
customers used against the limit; a demo shows the days it has left.
Collapsed to icons it is one icon with the same words in its tooltip.
Clicks are recorded as plan:sidebar_upgrade_click.

The plans page and the row read the subscription through one shared
helper so they cannot disagree.
Bernt Christian Egeland 12 ore în urmă
părinte
comite
b14738af3f

+ 8 - 1
messages/bg/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} текущи инспекции",
       "reminders": "{count} предстоящи напомняния"
     },
-    "faultCodes": "Кодове за грешки"
+    "faultCodes": "Кодове за грешки",
+    "plan": {
+      "free": "Безплатен план",
+      "demo": "{plan} (демо)",
+      "customers": "{used} / {limit, plural, one {# клиент} other {# клиенти}}",
+      "endsIn": "Изтича след {days, plural, =0 {по-малко от ден} one {# ден} other {# дни}}",
+      "upgrade": "Надстрой"
+    }
   }
 }

+ 8 - 1
messages/de/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} laufende Inspektionen",
       "reminders": "{count} fällige Erinnerungen"
     },
-    "faultCodes": "Fehlercodes"
+    "faultCodes": "Fehlercodes",
+    "plan": {
+      "free": "Kostenloser Plan",
+      "demo": "{plan} (Demo)",
+      "customers": "{used} / {limit, plural, one {# Kunde} other {# Kunden}}",
+      "endsIn": "Endet in {days, plural, =0 {weniger als einem Tag} one {# Tag} other {# Tagen}}",
+      "upgrade": "Upgraden"
+    }
   }
 }

+ 8 - 1
messages/en/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} inspections in progress",
       "reminders": "{count} reminders due"
     },
-    "faultCodes": "Fault codes"
+    "faultCodes": "Fault codes",
+    "plan": {
+      "free": "Free plan",
+      "demo": "{plan} demo",
+      "customers": "{used} / {limit, plural, one {# customer} other {# customers}}",
+      "endsIn": "Ends in {days, plural, =0 {less than a day} one {# day} other {# days}}",
+      "upgrade": "Upgrade"
+    }
   }
 }

+ 8 - 1
messages/es/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} inspecciones en curso",
       "reminders": "{count} recordatorios vencidos"
     },
-    "faultCodes": "Códigos de avería"
+    "faultCodes": "Códigos de avería",
+    "plan": {
+      "free": "Plan gratuito",
+      "demo": "Demo de {plan}",
+      "customers": "{used} / {limit, plural, one {# cliente} other {# clientes}}",
+      "endsIn": "Termina en {days, plural, =0 {menos de un día} one {# día} other {# días}}",
+      "upgrade": "Mejorar plan"
+    }
   }
 }

+ 8 - 1
messages/fr/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} inspections en cours",
       "reminders": "{count} rappels à échéance"
     },
-    "faultCodes": "Codes défaut"
+    "faultCodes": "Codes défaut",
+    "plan": {
+      "free": "Plan gratuit",
+      "demo": "Démo {plan}",
+      "customers": "{used} / {limit, plural, one {# client} other {# clients}}",
+      "endsIn": "Se termine dans {days, plural, =0 {moins d'un jour} one {# jour} other {# jours}}",
+      "upgrade": "Améliorer"
+    }
   }
 }

+ 8 - 1
messages/it/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} ispezioni in corso",
       "reminders": "{count} promemoria in scadenza"
     },
-    "faultCodes": "Codici di errore"
+    "faultCodes": "Codici di errore",
+    "plan": {
+      "free": "Piano gratuito",
+      "demo": "Demo di {plan}",
+      "customers": "{used} / {limit, plural, one {# cliente} other {# clienti}}",
+      "endsIn": "Termina tra {days, plural, =0 {meno di un giorno} one {# giorno} other {# giorni}}",
+      "upgrade": "Aggiorna piano"
+    }
   }
 }

+ 8 - 1
messages/lt/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} vykdomos apžiūros",
       "reminders": "{count} priminimai, kurių terminas suėjo"
     },
-    "faultCodes": "Gedimų kodai"
+    "faultCodes": "Gedimų kodai",
+    "plan": {
+      "free": "Nemokamas planas",
+      "demo": "{plan} (demo)",
+      "customers": "{used} iš {limit, plural, one {# kliento} few {# klientų} many {# kliento} other {# klientų}}",
+      "endsIn": "Baigsis po {days, plural, =0 {mažiau nei dienos} one {# dienos} few {# dienų} many {# dienos} other {# dienų}}",
+      "upgrade": "Atnaujinti"
+    }
   }
 }

+ 8 - 1
messages/nb/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} pågående inspeksjoner",
       "reminders": "{count} forfalte påminnelser"
     },
-    "faultCodes": "Feilkoder"
+    "faultCodes": "Feilkoder",
+    "plan": {
+      "free": "Gratisplan",
+      "demo": "{plan}-demo",
+      "customers": "{used} / {limit, plural, one {# kunde} other {# kunder}}",
+      "endsIn": "Utløper om {days, plural, =0 {mindre enn én dag} one {# dag} other {# dager}}",
+      "upgrade": "Oppgrader"
+    }
   }
 }

+ 8 - 1
messages/nl/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} lopende inspecties",
       "reminders": "{count} herinneringen vervallen"
     },
-    "faultCodes": "Foutcodes"
+    "faultCodes": "Foutcodes",
+    "plan": {
+      "free": "Gratis plan",
+      "demo": "{plan}-demo",
+      "customers": "{used} / {limit, plural, one {# klant} other {# klanten}}",
+      "endsIn": "Eindigt over {days, plural, =0 {minder dan een dag} one {# dag} other {# dagen}}",
+      "upgrade": "Upgraden"
+    }
   }
 }

+ 8 - 1
messages/pl/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} przeglądy w toku",
       "reminders": "{count} zaległe przypomnienia"
     },
-    "faultCodes": "Kody usterek"
+    "faultCodes": "Kody usterek",
+    "plan": {
+      "free": "Plan darmowy",
+      "demo": "{plan} (demo)",
+      "customers": "{used} z {limit, plural, one {# klienta} few {# klientów} many {# klientów} other {# klienta}}",
+      "endsIn": "Kończy się za {days, plural, =0 {mniej niż dzień} one {# dzień} few {# dni} many {# dni} other {# dnia}}",
+      "upgrade": "Zmień plan"
+    }
   }
 }

+ 8 - 1
messages/pt-BR/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} inspeções em andamento",
       "reminders": "{count} lembretes vencidos"
     },
-    "faultCodes": "Códigos de falha"
+    "faultCodes": "Códigos de falha",
+    "plan": {
+      "free": "Plano gratuito",
+      "demo": "Demo do {plan}",
+      "customers": "{used} / {limit, plural, one {# cliente} other {# clientes}}",
+      "endsIn": "Termina em {days, plural, =0 {menos de um dia} one {# dia} other {# dias}}",
+      "upgrade": "Atualizar plano"
+    }
   }
 }

+ 8 - 1
messages/pt-PT/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} inspeções em curso",
       "reminders": "{count} lembretes pendentes"
     },
-    "faultCodes": "Códigos de avaria"
+    "faultCodes": "Códigos de avaria",
+    "plan": {
+      "free": "Plano gratuito",
+      "demo": "Demonstração do {plan}",
+      "customers": "{used} / {limit, plural, one {# cliente} other {# clientes}}",
+      "endsIn": "Termina em {days, plural, =0 {menos de um dia} one {# dia} other {# dias}}",
+      "upgrade": "Mudar de plano"
+    }
   }
 }

+ 8 - 1
messages/ru/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} проверок в работе",
       "reminders": "{count} напоминаний просрочено"
     },
-    "faultCodes": "Коды неисправностей"
+    "faultCodes": "Коды неисправностей",
+    "plan": {
+      "free": "Бесплатный тариф",
+      "demo": "{plan} (демо)",
+      "customers": "{used} из {limit, plural, one {# клиента} few {# клиентов} many {# клиентов} other {# клиента}}",
+      "endsIn": "Закончится через {days, plural, =0 {меньше дня} one {# день} few {# дня} many {# дней} other {# дня}}",
+      "upgrade": "Обновить тариф"
+    }
   }
 }

+ 8 - 1
messages/tr/navigation.json

@@ -150,6 +150,13 @@
       "inspections": "{count} devam eden muayene",
       "reminders": "{count} vadesi gelen hatırlatma"
     },
-    "faultCodes": "Arıza kodları"
+    "faultCodes": "Arıza kodları",
+    "plan": {
+      "free": "Ücretsiz plan",
+      "demo": "{plan} demosu",
+      "customers": "{used} / {limit} müşteri",
+      "endsIn": "{days, plural, =0 {Bir günden kısa sürede} other {# gün içinde}} sona erer",
+      "upgrade": "Yükselt"
+    }
   }
 }

+ 122 - 0
src/__tests__/features/subscription/sidebar-plan-server.test.ts

@@ -0,0 +1,122 @@
+/**
+ * Who sees the sidebar's plan row, and with what in it.
+ *
+ * Shown on the same terms as a purchase: the app torqvoice.com bills for, a
+ * workshop the plans page would sell to (free, or a demo without Stripe),
+ * and someone the checkout route lets buy.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const state = vi.hoisted(() => ({
+  demoMode: false,
+  linked: true,
+  ctx: { organizationId: 'org-1', isAdmin: true } as {
+    organizationId: string
+    isAdmin: boolean
+  } | null,
+  subscription: null as unknown,
+  customers: 14,
+}))
+
+vi.mock('@/lib/demo', () => ({
+  get isDemoMode() {
+    return state.demoMode
+  },
+}))
+vi.mock('@/lib/torqvoice-com-link', () => ({ isCloudLinked: vi.fn(async () => state.linked) }))
+vi.mock('@/lib/get-auth-context', () => ({ getAuthContext: vi.fn(async () => state.ctx) }))
+vi.mock('@/lib/customer-limit', () => ({
+  countCustomersTowardLimit: vi.fn(async () => state.customers),
+}))
+vi.mock('@/lib/db', () => ({
+  db: { subscription: { findUnique: vi.fn(async () => state.subscription) } },
+}))
+
+const { getSidebarPlan } = await import('@/features/subscription/Lib/sidebarPlan.server')
+const { getAuthContext } = await import('@/lib/get-auth-context')
+const { db } = await import('@/lib/db')
+
+const DAY = 86_400_000
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  state.demoMode = false
+  state.linked = true
+  state.ctx = { organizationId: 'org-1', isAdmin: true }
+  state.subscription = null
+  state.customers = 14
+})
+
+describe('getSidebarPlan', () => {
+  it('shows a free workshop its customers against the free limit', async () => {
+    expect(await getSidebarPlan()).toEqual({ kind: 'free', customers: 14, customerLimit: 20 })
+  })
+
+  it('treats a canceled subscription as free', async () => {
+    state.subscription = {
+      status: 'canceled',
+      stripeSubscriptionId: 'sub_1',
+      currentPeriodEnd: null,
+      plan: { name: 'Torq Pro (monthly)' },
+    }
+    expect(await getSidebarPlan()).toMatchObject({ kind: 'free' })
+  })
+
+  it('shows nothing to a paying workshop', async () => {
+    state.subscription = {
+      status: 'active',
+      stripeSubscriptionId: 'sub_1',
+      currentPeriodEnd: new Date(Date.now() + 30 * DAY),
+      plan: { name: 'Torq Pro (monthly)' },
+    }
+    expect(await getSidebarPlan()).toBeNull()
+  })
+
+  it('shows a demo without Stripe its plan and days left', async () => {
+    state.subscription = {
+      status: 'trialing',
+      stripeSubscriptionId: null,
+      currentPeriodEnd: new Date(Date.now() + 4.5 * DAY),
+      plan: { name: 'Enterprise (annual)' },
+    }
+    expect(await getSidebarPlan()).toEqual({ kind: 'demo', plan: 'enterprise', daysLeft: 5 })
+  })
+
+  it('shows nothing to a Stripe trial, which is already bought', async () => {
+    state.subscription = {
+      status: 'trialing',
+      stripeSubscriptionId: 'sub_1',
+      currentPeriodEnd: new Date(Date.now() + 4 * DAY),
+      plan: { name: 'Torq Pro (monthly)' },
+    }
+    expect(await getSidebarPlan()).toBeNull()
+  })
+
+  it('shows nothing to someone who cannot buy', async () => {
+    state.ctx = { organizationId: 'org-1', isAdmin: false }
+    expect(await getSidebarPlan()).toBeNull()
+  })
+
+  // TORQVOICE_MODE=cloud is a line anyone can put in an environment file. A
+  // self-hosted install that does so is still not billed by torqvoice.com,
+  // so the plans page sends it away and the sidebar must not point there.
+  it('shows nothing on a self-hosted install that set cloud mode but is not linked', async () => {
+    const before = process.env.TORQVOICE_MODE
+    process.env.TORQVOICE_MODE = 'cloud'
+    state.linked = false
+    try {
+      expect(await getSidebarPlan()).toBeNull()
+      expect(getAuthContext).not.toHaveBeenCalled()
+      expect(db.subscription.findUnique).not.toHaveBeenCalled()
+    } finally {
+      if (before === undefined) delete process.env.TORQVOICE_MODE
+      else process.env.TORQVOICE_MODE = before
+    }
+  })
+
+  it('shows nothing on the public demo, where checkout is refused', async () => {
+    state.demoMode = true
+    expect(await getSidebarPlan()).toBeNull()
+  })
+})

+ 78 - 0
src/__tests__/features/subscription/sidebar-plan.test.tsx

@@ -0,0 +1,78 @@
+/**
+ * The plan row at the foot of the sidebar.
+ *
+ * A free workshop used to learn it was on a plan only when a limit refused
+ * something. The row says which plan it is on, how many of its customers it
+ * has used, and leads to the plans, counted in analytics like the upgrade
+ * dialog's button.
+ */
+
+import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { SidebarProvider } from '@/components/ui/sidebar'
+
+const track = vi.fn()
+vi.mock('@/lib/analytics', () => ({ track: (...args: unknown[]) => track(...args) }))
+
+const { SidebarPlan } = await import('@/features/subscription/Components/SidebarPlan')
+
+beforeAll(() => {
+  window.matchMedia ??= ((query: string) => ({
+    matches: false,
+    media: query,
+    addEventListener: vi.fn(),
+    removeEventListener: vi.fn(),
+  })) as unknown as typeof window.matchMedia
+})
+
+beforeEach(() => track.mockClear())
+
+function renderRow(plan: Parameters<typeof SidebarPlan>[0]['plan']) {
+  return render(
+    <SidebarProvider>
+      <ul>
+        <SidebarPlan plan={plan} />
+      </ul>
+    </SidebarProvider>
+  )
+}
+
+describe('SidebarPlan', () => {
+  it('shows a free workshop its plan and customers used, linking to the plans', () => {
+    renderRow({ kind: 'free', customers: 14, customerLimit: 20 })
+
+    expect(screen.getByText('Free plan')).toBeInTheDocument()
+    expect(screen.getByText('14 / 20 customers')).toBeInTheDocument()
+    const link = screen.getByRole('link', { name: /Upgrade/ })
+    expect(link).toHaveAttribute('href', '/settings/subscription')
+  })
+
+  it('records the click with how much of the plan was used', () => {
+    renderRow({ kind: 'free', customers: 14, customerLimit: 20 })
+
+    fireEvent.click(screen.getByRole('link', { name: /Upgrade/ }))
+
+    expect(track).toHaveBeenCalledWith('plan:sidebar_upgrade_click', {
+      kind: 'free',
+      customers: 14,
+      customer_limit: 20,
+    })
+  })
+
+  it('marks the count once the workshop is over its limit', () => {
+    renderRow({ kind: 'free', customers: 23, customerLimit: 20 })
+
+    expect(screen.getByText('23 / 20 customers')).toHaveClass('text-destructive')
+  })
+
+  it('tells a demo which plan it is trying and how long is left', () => {
+    renderRow({ kind: 'demo', plan: 'pro', daysLeft: 5 })
+
+    expect(screen.getByText('Torq Pro demo')).toBeInTheDocument()
+    expect(screen.getByText('Ends in 5 days')).toBeInTheDocument()
+    expect(screen.queryByText(/customers/)).toBeNull()
+
+    fireEvent.click(screen.getByRole('link', { name: /Upgrade/ }))
+    expect(track).toHaveBeenCalledWith('plan:sidebar_upgrade_click', { kind: 'demo' })
+  })
+})

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

@@ -51,6 +51,7 @@ import { isAiConfigured } from '@/features/integrations/Lib/ai'
 import { WORKSHOP_CHAT_ENABLED } from '@/features/ai/constants'
 import { getManifest, listManifests } from '@/integrations/registry'
 import { isCloudLinked } from '@/lib/torqvoice-com-link'
+import { getSidebarPlan } from '@/features/subscription/Lib/sidebarPlan.server'
 import { PlateLookupProvider } from '@/components/plate-lookup-context'
 import { PlateLookupCommand } from '@/features/vehicles/Components/PlateLookupCommand'
 import { BookingAccessProvider } from '@/components/booking-launcher'
@@ -304,6 +305,9 @@ export default async function DashboardLayout({ children }: { children: React.Re
   // settings pages exist on this install, and the connectors the catalog
   // offers, trimmed to a name and a logo.
   const cloudLinked = await isCloudLinked()
+  // The plan row at the foot of the sidebar: cloud only, free or demo, and
+  // only for someone who can buy.
+  const sidebarPlan = cloudLinked ? await getSidebarPlan() : null
   const ti = await getTranslations('integrations')
   const ta = await getTranslations('common.a11y')
   const searchConnectors = listManifests().map((m) => ({
@@ -477,6 +481,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
                                       counts={sidebarCounts}
                                       isTechnician={technicianIds.length > 0}
                                       supportEnabled={supportEnabled}
+                                      plan={sidebarPlan}
                                     />
                                     <SidebarInset
                                       id="main-content"

+ 4 - 13
src/app/(authenticated)/settings/subscription/page.tsx

@@ -1,12 +1,13 @@
 import { getAuthContext } from '@/lib/get-auth-context'
 import { db } from '@/lib/db'
 import { redirect } from 'next/navigation'
-import { getFeatures, PLAN_FEATURES, type Plan } from '@/lib/features'
+import { getFeatures, PLAN_FEATURES } from '@/lib/features'
 import { isCloudLinked } from '@/lib/torqvoice-com-link'
 import { SubscriptionSettings } from '@/features/subscription/Components/subscription-settings'
 import { countCustomersTowardLimit } from '@/lib/customer-limit'
 import { fetchBillingPrices, isTorqvoiceComBillingConfigured } from '@/lib/torqvoice-com'
 import { settingsPageTitle } from '@/lib/page-title'
+import { currentPlan } from '@/features/subscription/Lib/currentPlan'
 
 export function generateMetadata() {
   return settingsPageTitle('subscription')
@@ -35,18 +36,8 @@ export default async function SubscriptionPage({
     include: { plan: true },
   })
 
-  // Plan rows are named per price ("Torq Pro (monthly)", "Enterprise
-  // (annual)"), so the plan is the word in the name, as getFeatures reads it.
-  const plan: Plan =
-    subscription?.status === 'active' || subscription?.status === 'trialing'
-      ? subscription.plan.name.toLowerCase().includes('enterprise')
-        ? 'enterprise'
-        : 'pro'
-      : 'free'
-
-  // A demo is a trialing subscription not backed by Stripe (granted from the
-  // admin panel). It carries full plan features but expires at currentPeriodEnd.
-  const isDemo = subscription?.status === 'trialing' && !subscription?.stripeSubscriptionId
+  // The same reading the sidebar's plan row makes, so the two cannot disagree.
+  const { plan, isDemo } = currentPlan(subscription)
 
   // The member meter shows the limit that is enforced, which for a workshop
   // with a team size agreed by hand is higher than its plan's.

+ 8 - 0
src/components/app-sidebar.tsx

@@ -101,6 +101,8 @@ import { cn } from '@/lib/utils'
 import { openSupport } from '@/features/support/Lib/supportVisibility'
 import { useTouchScreen } from '@/features/support/Lib/useTouchScreen'
 import { handleGated } from '@/components/upgrade-gate'
+import { SidebarPlan } from '@/features/subscription/Components/SidebarPlan'
+import type { SidebarPlan as SidebarPlanData } from '@/features/subscription/Lib/sidebarPlan.server'
 
 type OrgInfo = { id: string; name: string; role: string }
 
@@ -160,6 +162,7 @@ export function AppSidebar({
   counts,
   isTechnician = false,
   supportEnabled = false,
+  plan = null,
   ...props
 }: React.ComponentProps<typeof Sidebar> & {
   companyLogo?: string
@@ -180,6 +183,8 @@ export function AppSidebar({
   /** Linked to a technician row: the dashboard is their job list even without the figures. */
   isTechnician?: boolean
   supportEnabled?: boolean
+  /** The plan row above the account menu, worked out on the server; null hides it. */
+  plan?: SidebarPlanData | null
 }) {
   const pathname = usePathname()
   const { openHelp: openShortcutsHelp } = useShortcuts()
@@ -668,6 +673,9 @@ export function AppSidebar({
       </SidebarContent>
       <SidebarFooter className="border-t border-sidebar-border p-2">
         <SidebarMenu>
+          {/* At the foot, where it is always in sight but never in the way of
+              the pages above. Only someone who can buy is shown it. */}
+          {plan && <SidebarPlan plan={plan} />}
           <SidebarMenuItem>
             <DropdownMenu>
               <DropdownMenuTrigger asChild>

+ 107 - 0
src/features/subscription/Components/SidebarPlan.tsx

@@ -0,0 +1,107 @@
+'use client'
+
+import Link from 'next/link'
+import { Zap } from 'lucide-react'
+import { useTranslations } from 'next-intl'
+import { SidebarMenuButton, SidebarMenuItem, useSidebar } from '@/components/ui/sidebar'
+import { track } from '@/lib/analytics'
+import { cn } from '@/lib/utils'
+import type { SidebarPlan as SidebarPlanData } from '@/features/subscription/Lib/sidebarPlan.server'
+
+/**
+ * The plan row at the foot of the sidebar: which plan the workshop is on,
+ * how much of it is used, and the way to the plans.
+ *
+ * Until it existed a free workshop only learned it was on a plan at all
+ * when a limit refused something. Kept quiet on purpose: a muted icon and a
+ * thin meter, the way a nav row looks, so it reads as information rather
+ * than an advert. Collapsed to icons it is one icon with the same words in
+ * its tooltip, like every other row.
+ */
+export function SidebarPlan({ plan }: { plan: SidebarPlanData }) {
+  const t = useTranslations('navigation.sidebar.plan')
+  const tSettings = useTranslations('settings.subscription')
+  const { isMobile, setOpenMobile } = useSidebar()
+
+  const label =
+    plan.kind === 'free'
+      ? t('free')
+      : t('demo', {
+          plan: plan.plan === 'enterprise' ? tSettings('planEnterprise') : tSettings('planPro'),
+        })
+
+  const detail =
+    plan.kind === 'free'
+      ? t('customers', { used: plan.customers, limit: plan.customerLimit })
+      : plan.daysLeft !== null
+        ? t('endsIn', { days: plan.daysLeft })
+        : null
+
+  // The plans page's meter, the same arithmetic and the same colours.
+  const over = plan.kind === 'free' && plan.customers > plan.customerLimit
+  const share =
+    plan.kind === 'free' && plan.customerLimit > 0
+      ? Math.min(100, (plan.customers / plan.customerLimit) * 100)
+      : 0
+
+  const handleClick = () => {
+    track(
+      'plan:sidebar_upgrade_click',
+      plan.kind === 'free'
+        ? { kind: 'free', customers: plan.customers, customer_limit: plan.customerLimit }
+        : { kind: 'demo' }
+    )
+    if (isMobile) setOpenMobile(false)
+  }
+
+  return (
+    <SidebarMenuItem>
+      <SidebarMenuButton
+        asChild
+        tooltip={{
+          children: (
+            <span className="grid gap-0.5">
+              <span className="font-medium">{label}</span>
+              {detail && <span>{detail}</span>}
+              <span>{t('upgrade')}</span>
+            </span>
+          ),
+        }}
+        className="h-auto border border-sidebar-border group-data-[collapsible=icon]:border-0"
+      >
+        <Link href="/settings/subscription" onClick={handleClick}>
+          <Zap className="size-4" />
+          <div className="grid min-w-0 flex-1 gap-1 leading-tight group-data-[collapsible=icon]:hidden">
+            <div className="flex items-center justify-between gap-2">
+              <span className="truncate font-medium">{label}</span>
+              <span className="shrink-0 text-xs font-medium underline-offset-4 group-hover/menu-item:underline">
+                {t('upgrade')}
+              </span>
+            </div>
+            {plan.kind === 'free' && (
+              <div aria-hidden className="h-1.5 overflow-hidden rounded-full bg-sidebar-border">
+                <div
+                  className={cn(
+                    'h-full rounded-full',
+                    over ? 'bg-destructive' : 'bg-sidebar-primary'
+                  )}
+                  style={{ width: `${share}%` }}
+                />
+              </div>
+            )}
+            {detail && (
+              <span
+                className={cn(
+                  'truncate text-xs',
+                  over ? 'font-medium text-destructive' : 'text-sidebar-foreground/60'
+                )}
+              >
+                {detail}
+              </span>
+            )}
+          </div>
+        </Link>
+      </SidebarMenuButton>
+    </SidebarMenuItem>
+  )
+}

+ 29 - 0
src/features/subscription/Lib/currentPlan.ts

@@ -0,0 +1,29 @@
+/** The plans torqvoice.com sells to the cloud app. */
+export type CloudPlan = 'free' | 'pro' | 'enterprise'
+
+type SubscriptionRow = {
+  status: string
+  stripeSubscriptionId: string | null
+  plan: { name: string }
+} | null
+
+/**
+ * The plan a workshop's subscription row puts it on, as the plans page shows
+ * it, and whether that is a demo.
+ *
+ * Plan rows are named per price ("Torq Pro (monthly)", "Enterprise
+ * (annual)"), so the plan is the word in the name, as getFeatures reads it.
+ * A demo is a trialing subscription not backed by Stripe (granted from the
+ * admin panel): it carries full plan features but expires at
+ * currentPeriodEnd, and can still be bought.
+ */
+export function currentPlan(subscription: SubscriptionRow): { plan: CloudPlan; isDemo: boolean } {
+  const plan: CloudPlan =
+    subscription?.status === 'active' || subscription?.status === 'trialing'
+      ? subscription.plan.name.toLowerCase().includes('enterprise')
+        ? 'enterprise'
+        : 'pro'
+      : 'free'
+  const isDemo = subscription?.status === 'trialing' && !subscription?.stripeSubscriptionId
+  return { plan, isDemo }
+}

+ 64 - 0
src/features/subscription/Lib/sidebarPlan.server.ts

@@ -0,0 +1,64 @@
+import { db } from '@/lib/db'
+import { isDemoMode } from '@/lib/demo'
+import { PLAN_FEATURES } from '@/lib/features'
+import { getAuthContext } from '@/lib/get-auth-context'
+import { countCustomersTowardLimit } from '@/lib/customer-limit'
+import { isCloudLinked } from '@/lib/torqvoice-com-link'
+import { currentPlan } from './currentPlan'
+
+/**
+ * What the plan row at the foot of the sidebar shows, or nothing.
+ *
+ * A free workshop sees its plan and how many of its customers it has used;
+ * a demo sees which plan it is trying and how long it has left.
+ */
+export type SidebarPlan =
+  | { kind: 'free'; customers: number; customerLimit: number }
+  | { kind: 'demo'; plan: 'pro' | 'enterprise'; daysLeft: number | null }
+
+/**
+ * The sidebar's plan row, for the signed-in account's active workshop.
+ *
+ * Shown on the same terms as a purchase: the app torqvoice.com bills for
+ * (as the plans page decides), a workshop the plans page would offer to
+ * sell to (free, or a demo without Stripe), and someone the checkout route
+ * would let buy (an owner or an admin). A paid workshop, a member, a
+ * self-hosted install and the public demo get nothing.
+ */
+export async function getSidebarPlan(): Promise<SidebarPlan | null> {
+  // The checkout route refuses on the public demo.
+  if (isDemoMode) return null
+  if (!(await isCloudLinked())) return null
+
+  const ctx = await getAuthContext()
+  if (!ctx?.isAdmin) return null
+
+  const subscription = await db.subscription.findUnique({
+    where: { organizationId: ctx.organizationId },
+    select: {
+      status: true,
+      stripeSubscriptionId: true,
+      currentPeriodEnd: true,
+      plan: { select: { name: true } },
+    },
+  })
+  const { plan, isDemo } = currentPlan(subscription)
+
+  if (isDemo && plan !== 'free') {
+    const end = subscription?.currentPeriodEnd
+    return {
+      kind: 'demo',
+      plan,
+      // Whole days left, as the plans page counts them.
+      daysLeft: end ? Math.max(0, Math.ceil((end.getTime() - Date.now()) / 86_400_000)) : null,
+    }
+  }
+
+  if (plan !== 'free') return null
+
+  return {
+    kind: 'free',
+    customers: await countCustomersTowardLimit(ctx.organizationId),
+    customerLimit: PLAN_FEATURES.free.maxCustomers,
+  }
+}

+ 5 - 0
src/lib/analytics.ts

@@ -66,6 +66,11 @@ export type AnalyticsEvent =
   | 'plan:gate_show'
   /** The upgrade dialog's button to the plans. */
   | 'plan:upgrade_click'
+  /**
+   * The plan row at the foot of the sidebar followed to the plans: `kind` free
+   * or demo, and on free how many `customers` of the `customer_limit` were used.
+   */
+  | 'plan:sidebar_upgrade_click'
   /**
    * A fault code opened, on its page or in the sheet beside a job: `kind` obd or make,
    * `make` for a make's own code, and `found`, whether we had a meaning for it. The misses