feat(portal): customer-admin surface on real data + Stripe billing + session resilience

Access & navigation
- Gate partner-mode strictly to partner staff so admins/end-users never inherit
  leftover partner-view state; purge stale session entry on hydrate.
- Role-driven admin entry: useMe.isTenantAdmin, Admin/Personal tiles in the app
  launcher, and an /admin route guard in the global middleware (fail closed).
- Drop the duplicate user identity block from the sidebar footer.

Admin pages on real data
- New tenant-scoped, membership-gated endpoints: GET /tenants/:slug/{audit,users,
  invoices}; useTenant composable resolves the active workspace + subscription.
- Dashboard: real seats, spend (cycle-normalized + minor-units), plan, renewal,
  and recent audit; unbacked sections removed.
- Users & groups: real members; Groups/Invitations/Service accounts shown as
  honest "coming soon".
- Subscription & invoices: real plan hero, invoice history, and billing details.

Stripe payment method (Elements + SetupIntent)
- StripeClient: publishable key + getDefaultCard/createSetupIntent/setDefaultCard.
- CustomerBillingController + BillingService methods (ensure-customer on demand).
- Portal: PaymentMethodModal, useStripeJs (CDN load), proxies; hidePostalCode.

Editable billing details & whitelabel branding
- PATCH /tenants/:slug/billing-info (narrow: company/VAT/country/email).
- TenantBranding schema/service + GET/PUT /tenants/:slug/branding: real product
  name, accent colour, and per-tenant email-template overrides.
- Branding preview + sidebar workspace mark wired to real name/plan/seats/colour
  with YIQ auto-contrast (readableOn util).

Session resilience
- Request offline_access so Authentik issues a refresh token (automaticRefresh).
- Silent refresh + single retry on 401 for writes (useApiFetch, incl. partner
  pages) and reads (useMe.fetchMe) — no redirect, no lost input.
- Modal backdrop closes only on press+release on the backdrop (no more
  drag-select-to-close).
This commit is contained in:
Ronni Baslund
2026-05-31 00:19:34 +02:00
parent db26dafc64
commit 3288fde693
44 changed files with 1874 additions and 1237 deletions
+12 -3
View File
@@ -9,6 +9,7 @@ import type { IconName } from './UiIcon.vue'
const launcher = useAppLauncher()
const route = useRoute()
const partnerMode = usePartnerMode()
const { isTenantAdmin } = useMe()
interface Tile {
key: string
@@ -38,8 +39,15 @@ const tiles = computed<Tile[]>(() => {
{ key: 'cal', name: 'Kalender', icon: 'calendar', ext: 'cal.dezky.com' },
{ key: 'contacts', name: 'Kontakter', icon: 'users', ext: 'contacts.dezky.com' },
]
if (isAdmin) {
base.push({ key: 'admin', name: 'Admin', icon: 'shield', ext: 'admin.dezky.com', current: !isPartner })
// Admin tile is the entry point to the workspace-admin surface. Show it to any
// tenant admin/owner (so they can get TO /admin from the personal shell), not
// only when already on the admin section. Marked "HERE" when on /admin. Pair it
// with a Personal tile so the launcher is a clean two-way toggle between the
// admin and personal surfaces — clicking either crosses over, "HERE" shows
// which side you're on.
if (isAdmin || isTenantAdmin.value) {
base.push({ key: 'home', name: 'Personal', icon: 'home', ext: 'app.dezky.com', current: section.value === 'user' })
base.push({ key: 'admin', name: 'Admin', icon: 'shield', ext: 'admin.dezky.com', current: isAdmin && !isPartner })
}
if (isPartner) {
base.push({ key: 'partner', name: 'Partner', icon: 'briefcase', ext: 'partner.nordicmsp.dk', current: true })
@@ -51,6 +59,7 @@ const tiles = computed<Tile[]>(() => {
const toast = useToast()
function open(t: Tile) {
launcher.hide()
if (t.key === 'home') return navigateTo('/')
if (t.key === 'admin') return navigateTo('/admin')
if (t.key === 'partner') return navigateTo('/partner')
toast.info(`Opening ${t.name}`, t.ext)
@@ -73,7 +82,7 @@ onMounted(() => {
<header>
<div class="head-meta">
<Eyebrow>Apps</Eyebrow>
<div class="head-title">Open in new tab</div>
<div class="head-title">Jump to</div>
</div>
<button class="x" @click="launcher.hide" aria-label="Close">
<UiIcon name="x" :size="16" />
+14 -2
View File
@@ -16,6 +16,18 @@ const emit = defineEmits<{ close: [] }>()
const maxWidth = computed(() => ({ sm: 440, md: 600, lg: 880 })[props.size || 'md'])
// Close only when the press AND release both land on the backdrop. Without this,
// drag-selecting text inside an input and releasing on the backdrop fires a
// `click` on the backdrop (the common ancestor) and wrongly dismisses the modal.
const pressedOnBackdrop = ref(false)
function onBackdropMousedown(e: MouseEvent) {
pressedOnBackdrop.value = e.target === e.currentTarget
}
function onBackdropClick() {
if (pressedOnBackdrop.value) emit('close')
pressedOnBackdrop.value = false
}
onMounted(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && props.open) emit('close')
@@ -28,8 +40,8 @@ onMounted(() => {
<template>
<Teleport to="body">
<Transition name="modal">
<div v-if="open" class="backdrop" @click="emit('close')">
<div class="modal" :style="{ maxWidth: maxWidth + 'px' }" @click.stop>
<div v-if="open" class="backdrop" @mousedown="onBackdropMousedown" @click.self="onBackdropClick">
<div class="modal" :style="{ maxWidth: maxWidth + 'px' }">
<header v-if="title || eyebrow || $slots.header">
<div class="lhs">
<Eyebrow v-if="eyebrow">{{ eyebrow }}</Eyebrow>
@@ -0,0 +1,149 @@
<script setup lang="ts">
// Card-on-file update via Stripe Elements + a SetupIntent. The card field is a
// Stripe-hosted iframe (loaded from js.stripe.com) — raw card data never hits
// our origin. Flow: open → POST setup-intent (secret + publishable key) → mount
// Elements → confirmCardSetup client-side → POST the resulting PM as default.
//
// Stripe handles are untyped (`any`) on purpose — we don't bundle @stripe/stripe-js.
import { loadStripeJs } from '~/composables/useStripeJs'
import type { PaymentMethodCard } from '~/types/workspace'
const props = defineProps<{ open: boolean; slug: string }>()
const emit = defineEmits<{ close: []; saved: [card: PaymentMethodCard | null] }>()
const { request } = useApiFetch()
const cardMount = ref<HTMLElement | null>(null)
const status = ref<'idle' | 'loading' | 'ready' | 'submitting'>('idle')
const errorMsg = ref('')
/* eslint-disable @typescript-eslint/no-explicit-any */
let stripe: any = null
let cardEl: any = null
let clientSecret = ''
async function setup() {
status.value = 'loading'
errorMsg.value = ''
try {
const res = await request<{ clientSecret: string; publishableKey: string }>(
`/api/tenants/${props.slug}/payment-method/setup-intent`,
{ method: 'POST' },
)
if (!res.publishableKey) throw new Error('Billing is not configured')
clientSecret = res.clientSecret
const StripeCtor = (await loadStripeJs()) as any
if (!StripeCtor) throw new Error('Could not load Stripe')
stripe = StripeCtor(res.publishableKey)
// Pull theme colours so the iframe text matches light/dark.
const cs = getComputedStyle(document.documentElement)
const color = cs.getPropertyValue('--text').trim() || '#0A0A0A'
const placeholder = cs.getPropertyValue('--text-mute').trim() || '#9b9b9b'
const elements = stripe.elements()
// hidePostalCode: the Card Element's bundled postal field validates against a
// US 5-digit ZIP by default, so a valid 4-digit Danish postcode reads as
// "incomplete". We don't need postal for a SetupIntent, so drop the field.
cardEl = elements.create('card', {
hidePostalCode: true,
style: { base: { fontSize: '14px', color, fontFamily: 'inherit', '::placeholder': { color: placeholder } } },
})
await nextTick()
if (cardMount.value) cardEl.mount(cardMount.value)
cardEl.on('change', (e: any) => { errorMsg.value = e.error?.message ?? '' })
status.value = 'ready'
} catch (e: any) {
errorMsg.value = e?.data?.message || e?.message || 'Could not start card update'
status.value = 'idle'
}
}
function teardown() {
try { cardEl?.destroy() } catch { /* already gone */ }
cardEl = null
stripe = null
clientSecret = ''
status.value = 'idle'
errorMsg.value = ''
}
watch(() => props.open, (open) => (open ? setup() : teardown()))
async function submit() {
if (status.value !== 'ready' || !stripe || !clientSecret) return
status.value = 'submitting'
errorMsg.value = ''
const { error, setupIntent } = await stripe.confirmCardSetup(clientSecret, { payment_method: { card: cardEl } })
if (error) {
errorMsg.value = error.message ?? 'Card could not be saved'
status.value = 'ready'
return
}
try {
const card = await request<PaymentMethodCard | null>(
`/api/tenants/${props.slug}/payment-method/default`,
{ method: 'POST', body: { paymentMethodId: setupIntent.payment_method } },
)
emit('saved', card)
emit('close')
} catch (e: any) {
errorMsg.value = e?.data?.message || 'Card saved, but setting it as default failed'
status.value = 'ready'
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
onBeforeUnmount(teardown)
</script>
<template>
<Modal :open="open" eyebrow="Billing · payment method" title="Update card" size="md" @close="emit('close')">
<div class="pm">
<label class="field">
<Eyebrow>Card details</Eyebrow>
<div ref="cardMount" class="card-input" />
</label>
<div v-if="status === 'loading'"><Mono dim>Loading secure card form</Mono></div>
<div v-if="errorMsg" class="err">{{ errorMsg }}</div>
<div class="trust">
<UiIcon name="shield" :size="14" stroke="var(--ok)" />
<div>Card details go straight to Stripe Dezky never sees your full card number or CVC. PCI DSS Level 1.</div>
</div>
</div>
<template #footer>
<UiButton variant="ghost" @click="emit('close')">Cancel</UiButton>
<UiButton variant="primary" :disabled="status !== 'ready'" @click="submit">
<template #leading><UiIcon name="check" :size="13" /></template>
{{ status === 'submitting' ? 'Saving…' : 'Save card' }}
</UiButton>
</template>
</Modal>
</template>
<style scoped>
.pm { display: flex; flex-direction: column; gap: 14px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.card-input {
min-height: 20px;
padding: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
}
.err { font-size: 12px; color: var(--bad); }
.trust {
padding: 12px;
background: var(--bg);
border-radius: 6px;
border: 1px solid var(--border);
display: flex;
gap: 10px;
align-items: flex-start;
font-size: 12px;
color: var(--text-dim);
line-height: 1.55;
}
</style>
+42 -41
View File
@@ -15,6 +15,7 @@
import type { IconName } from './UiIcon.vue'
import type { PartnerTenantDoc } from '~/types/partner'
import type { TenantUserDoc } from '~/types/workspace'
interface NavItem {
id: string
@@ -156,6 +157,32 @@ const { data: partnerTenants } = await useFetch<PartnerTenantDoc[]>('/api/partne
})
const partnerCustomerCount = computed(() => partnerTenants.value?.length ?? 0)
// The signed-in user's own workspace (for the customer switcher tile). Real
// name, plan and accent come from /api/me.
const { tenant: ownTenant, planLabel, seatLimit } = useTenant()
const ownSlug = computed(() => ownTenant.value?.slug ?? '')
// Seat usage for the switcher sub-line. Gated to non-partner members so the
// global shell never 403s the membership-scoped endpoint; shared key keeps it
// to one request.
const { data: ownUsers } = await useFetch<TenantUserDoc[]>(
() => `/api/tenants/${ownSlug.value}/users`,
{
key: 'sidebar-ws-users',
default: () => [],
immediate: !isPartnerStaff.value && !!ownSlug.value,
watch: [ownSlug],
},
)
const seatsUsed = computed(() => (ownUsers.value ?? []).filter((u) => u.active !== false).length)
// Workspace mark colours. Default to the signal accent when no brandColor is
// saved (matches the Branding preview); readableOn flips the initial light on
// dark accents so it stays legible for any chosen colour.
const DEFAULT_BRAND = '#D4FF3A'
const brandBg = computed(() => ownTenant.value?.brandColor || DEFAULT_BRAND)
const brandFg = computed(() => readableOn(brandBg.value))
// Customer currently being acted-as (partner-in-customer mode), resolved from
// the real tenant list by the _id stored in partner mode.
const activeCustomer = computed(() =>
@@ -167,14 +194,15 @@ const activeCustomer = computed(() =>
<aside class="sidebar" :class="{ collapsed }">
<!-- Workspace switcher -->
<button class="switcher" :title="collapsed ? 'Workspace' : undefined">
<!-- Customer admin: bone tile with node-mark -->
<!-- Customer admin: brand-colour tile with the workspace initial,
matching the Branding live-preview mark. -->
<template v-if="switcherKind === 'customer'">
<span class="ws-tile bone">
<NodeMark :size="28" fg="#0A0A0A" accent="var(--signal)" />
<span class="ws-tile brand" :style="{ background: brandBg, color: brandFg }">
{{ (ownTenant?.name?.[0] || 'a').toLowerCase() }}
</span>
<div v-if="!collapsed" class="ws-text">
<div class="ws-name">baslund</div>
<div class="ws-sub">Business · 11/25</div>
<div class="ws-name">{{ ownTenant?.name || 'Workspace' }}</div>
<div class="ws-sub">{{ planLabel }}{{ seatLimit ? ` · ${seatsUsed}/${seatLimit}` : '' }}</div>
</div>
</template>
@@ -225,18 +253,9 @@ const activeCustomer = computed(() =>
</template>
</nav>
<!-- User footer -->
<!-- Footer: collapse toggle only. The user identity block lives in the
topbar avatar menu no need to duplicate it here. -->
<div class="foot">
<button class="user" :title="collapsed ? 'Anne Hansen' : undefined">
<Avatar name="Anne Hansen" :size="26" />
<div v-if="!collapsed" class="user-text">
<div class="user-name">Anne Hansen</div>
<div class="user-role">
{{ section === 'partner' ? 'partner admin' : section === 'admin' ? 'admin' : 'user' }}
</div>
</div>
<UiIcon v-if="!collapsed" name="chevUpDown" :size="12" stroke="var(--side-mute)" />
</button>
<button class="collapse" @click="toggle" :title="collapsed ? 'Expand · ⌘[' : 'Collapse · ⌘['">
<UiIcon :name="collapsed ? 'chevRight' : 'chevLeft'" :size="11" />
<span v-if="!collapsed">collapse · [</span>
@@ -298,6 +317,13 @@ const activeCustomer = computed(() =>
font-weight: 700;
font-size: 18px;
}
/* Customer workspace mark — brand colour bg + auto-contrast initial (bg + color
set inline; the initial flips light/dark by luminance). */
.ws-tile.brand {
font-family: var(--font-mono);
font-weight: 700;
font-size: 18px;
}
.ws-text { flex: 1; min-width: 0; }
.ws-name {
@@ -397,31 +423,6 @@ nav {
border-top: 1px solid var(--side-border);
padding: 8px;
}
.user {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 8px;
background: transparent;
border: none;
border-radius: 6px;
color: var(--side-dim);
font-family: inherit;
font-size: 13px;
cursor: pointer;
text-align: left;
}
.user:hover { background: var(--side-hover); }
.user-text { flex: 1; min-width: 0; }
.user-name { font-size: 12px; color: var(--side-text); font-weight: 500; }
.user-role {
font-size: 10px;
color: var(--side-mute);
font-family: var(--font-mono);
margin-top: 1px;
}
.sidebar.collapsed .user { justify-content: center; padding: 8px 0; }
/* Collapse toggle */
.collapse {
@@ -7,6 +7,8 @@
defineProps<{ open: boolean }>()
const emit = defineEmits<{ close: []; done: [] }>()
const { request } = useApiFetch()
// 5 steps. Branding was dropped because nothing on the backend persists it
// yet (no Tenant.branding field, no logo upload pipeline) — partners
// configure branding post-provisioning via /partner/branding once that
@@ -214,7 +216,7 @@ async function submit() {
// client so the wizard never sends half-filled admin payloads.
...(adminName && adminEmail && { adminName, adminEmail }),
}
const res = await $fetch<{
const res = await request<{
tenant: { name: string }
adminInvite?: AdminCredentials | { error: string }
}>('/api/partner/tenants', { method: 'POST', body: payload })