refactor(dashboard): reconcile approval counts onto the SSOT engine

The dashboard ran a SECOND approval-count engine (getDashboardStats) that
read the dead `user_content_submissions` table for `pendingApprovals` +
`topPendingApproval`, so the "N Freigaben warten" queue item was broken/stale
while the /admin/approvals hub showed the true count from getApprovalCounts().
Workshop proposals, locations and absences never surfaced on the dashboard at
all.

Now the dashboard's approval-type action items derive from the SAME SSOT
engine as the hub: buildActionItems iterates APPROVAL_SOURCES over
getApprovalCounts(), routing each row to its own reviewHref and gating on its
section permission. Adding an approval source makes it appear on both surfaces
automatically — the two can no longer drift.

- getDashboardStats: dropped the dead ucs read + the now-SSOT-owned
  blog/timecard/permission queries (getDashboardStats keeps only non-approval
  items: appointments, listings, IT-Hilfe, tasks, repairer/HR apps, decisions)
- approval-sources: timecard/absence now gate on `timecard-approvals` (the
  review surface) not personal `timecards`
- removed dead code the UnifiedQueue already replaced: ActionItemsSection,
  QuickActionsSection, buildFulfillActions, FulfillAction type
- test: locks SSOT-driven queue (per-source rows, permission gating,
  super-admin-only, staleness→urgent, failed-count skip)

Net -286 lines. typecheck + lint clean; 31 approvals/dashboard/team tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mao NakamotoandClaude Opus 4.8 committed 2026-07-09 15:29:35 +02:00
1 parent 430f515f6c
commit edcebec665
11 files changed
+171 -353

No files matched your search

+14 -7
View File
@@ -45,6 +45,7 @@ import {
import { TeamActivityFeed } from '@/components/admin/dashboard/TeamActivityFeed'
import { SystemHealthBar } from '@/components/admin/dashboard/SystemHealthBar'
import type { DashboardStats } from '@/components/admin/dashboard'
import { getApprovalCounts, type ApprovalCounts } from '@/lib/approvals/counts'
import { OnboardingChecklist } from '@/components/dashboard/OnboardingChecklist'
import { getOnboardingChecklistState } from '@/lib/services/onboarding-state'
import { ROLES, type UserRole } from '@/lib/constants'
@@ -69,15 +70,17 @@ function todayLongLabel(): string {
async function UnifiedQueueSection({
statsPromise,
approvalCountsPromise,
isSuper,
canAccess,
}: {
statsPromise: Promise<DashboardStats>
approvalCountsPromise: Promise<ApprovalCounts>
isSuper: boolean
canAccess: (section: AdminSection) => boolean
}) {
const stats = await statsPromise
const items = buildUnifiedQueue(stats, isSuper, canAccess)
const [stats, approvalCounts] = await Promise.all([statsPromise, approvalCountsPromise])
const items = buildUnifiedQueue(stats, approvalCounts, isSuper, canAccess)
return <UnifiedQueue items={items} />
}
@@ -98,15 +101,15 @@ async function MonatsueberblickSection({
}
async function PermissionRequestsSection({
statsPromise,
approvalCountsPromise,
isSuper,
}: {
statsPromise: Promise<DashboardStats>
approvalCountsPromise: Promise<ApprovalCounts>
isSuper: boolean
}) {
if (!isSuper) return null
const stats = await statsPromise
if (stats.pendingPermissionRequests === 0) return null
const approvalCounts = await approvalCountsPromise
if ((approvalCounts.permission_request?.pending ?? 0) === 0) return null
const t = await getTranslations('admin.dashboard')
return (
<section id="permission-requests" aria-labelledby="dashboard-perm-title">
@@ -131,6 +134,9 @@ export default async function AdminDashboard() {
const isSuper = isSuperAdmin(session.user.email)
const statsPromise = getDashboardStats(isSuper)
// Approval-type counts come from the SSOT engine (same as the /admin/approvals
// hub) — fetched once, shared by the queue and the permission-requests block.
const approvalCountsPromise = getApprovalCounts()
const t = await getTranslations('admin.dashboard')
const userForPermissions = {
@@ -218,6 +224,7 @@ export default async function AdminDashboard() {
<Suspense fallback={<UnifiedQueueSkeleton />}>
<UnifiedQueueSection
statsPromise={statsPromise}
approvalCountsPromise={approvalCountsPromise}
isSuper={isSuper}
canAccess={canAccess}
/>
@@ -228,7 +235,7 @@ export default async function AdminDashboard() {
{/* ZUGRIFFS-ANFRAGEN — super admin only, only when pending */}
<Suspense fallback={null}>
<PermissionRequestsSection statsPromise={statsPromise} isSuper={isSuper} />
<PermissionRequestsSection approvalCountsPromise={approvalCountsPromise} isSuper={isSuper} />
</Suspense>
{/* MONATSÜBERBLICK — collapsed by default except for 'lead' mode */}
@@ -1,74 +0,0 @@
import { Link } from '@/i18n/navigation'
import { Zap, ArrowRight, Check } from 'lucide-react'
import Heading from '@/components/admin/AdminHeading'
import { formatQueueAge } from './format'
import type { ActionItem } from './types'
import { adminInteractive } from '@/lib/admin-ui'
import { URGENCY_TONES } from '@/config/dashboard'
interface ActionItemsSectionProps {
actionItems: ActionItem[]
}
export function ActionItemsSection({ actionItems }: ActionItemsSectionProps) {
const hasNoActionItems = actionItems.length === 0
return (
<div className="bg-surface-base rounded-xl shadow-xs border border-subtle">
<div className="p-4 border-b border-subtle flex items-center gap-2">
<Zap className="w-5 h-5 text-warning-500" aria-hidden="true" />
<Heading level={2} className="font-semibold text-text-primary">
Was gibt es zu tun?
</Heading>
</div>
<div className="p-4">
{hasNoActionItems ? (
<div className="flex items-center gap-3 text-action">
<div className="w-8 h-8 rounded-full bg-action-muted flex items-center justify-center">
<Check className="w-5 h-5" aria-hidden="true" />
</div>
<span className="font-medium">Alles erledigt! Keine offenen Aufgaben.</span>
</div>
) : (
<ul className="space-y-2" role="list">
{actionItems.map((item, index) => {
const urgency = URGENCY_TONES[item.type]
const age = formatQueueAge(item.oldestAt)
return (
<li key={index}>
<Link
href={item.href}
className={`flex items-center justify-between p-3 rounded-lg bg-surface-raised ${adminInteractive.rowHover} transition-colors group`}
aria-label={`${urgency.label}: ${item.label}${age ? ` (${age})` : ''}`}
>
<div className="flex items-start gap-3">
<span
className={`mt-1 w-3 h-3 shrink-0 rounded-full ${urgency.dot}`}
aria-hidden="true"
/>
<div>
<span className="font-medium text-text-primary">
{item.label}
</span>
{age && (
<p className={`text-xs mt-0.5 ${urgency.text}`}>
{age}
</p>
)}
</div>
</div>
<span className="flex items-center gap-1 text-sm text-text-secondary group-hover:text-action dark:group-hover:text-action transition-colors shrink-0 ml-3">
{item.actionLabel}
<ArrowRight className="w-4 h-4" aria-hidden="true" />
</span>
</Link>
</li>
)
})}
</ul>
)}
</div>
</div>
)
}
@@ -1,80 +0,0 @@
import { Link } from '@/i18n/navigation'
import type { QuickAction, FulfillAction } from './types'
import Heading from '@/components/admin/AdminHeading'
interface QuickActionsSectionProps {
quickActions: QuickAction[]
fulfillActions: FulfillAction[]
}
export function QuickActionsSection({ quickActions, fulfillActions }: QuickActionsSectionProps) {
if (quickActions.length === 0 && fulfillActions.length === 0) return null
return (
<div className="bg-surface-base rounded-xl shadow-xs border border-subtle">
<div className="p-4 border-b border-subtle">
<Heading level={2} className="font-semibold text-text-primary">
Schnellaktionen
</Heading>
</div>
<div className="p-4 space-y-5">
{/* Fulfill row — process pending work */}
{fulfillActions.length > 0 && (
<div>
<p className="mb-2.5 text-xs font-medium uppercase tracking-wide text-text-muted">
Erledigen
</p>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
{fulfillActions.map((action) => {
const Icon = action.icon
return (
<Link
key={action.href}
href={action.href}
className="relative flex flex-col items-center gap-2 p-3 rounded-lg bg-action-muted text-action hover:bg-action-muted transition-colors"
>
{/* Badge */}
<span className="absolute -top-1.5 -right-1.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-action px-1 text-xs font-bold text-white">
{action.count > 99 ? '99+' : action.count}
</span>
<Icon className="w-5 h-5" aria-hidden="true" />
<span className="text-xs font-medium text-center leading-tight">
{action.label}
</span>
</Link>
)
})}
</div>
</div>
)}
{/* Create row */}
{quickActions.length > 0 && (
<div>
<p className="mb-2.5 text-xs font-medium uppercase tracking-wide text-text-muted">
Erstellen
</p>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
{quickActions.map((action) => {
const Icon = action.icon
return (
<Link
key={action.href}
href={action.href}
className={`flex flex-col items-center gap-2 p-3 rounded-lg transition-colors ${action.color}`}
>
<Icon className="w-5 h-5" aria-hidden="true" />
<span className="text-xs font-medium text-center leading-tight">
{action.label}
</span>
</Link>
)
})}
</div>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,104 @@
import { buildActionItems } from '../buildActionItems'
import type { DashboardStats } from '../types'
import type { ApprovalCounts } from '@/lib/approvals/counts'
import { APPROVAL_SOURCES } from '@/config/approval-sources'
import type { AdminSection } from '@/lib/permissions'
// A DashboardStats with every NON-approval action item at zero — approval-type
// items now come exclusively from the approvalCounts arg, so these tests can
// isolate the SSOT-driven queue.
const ZERO_STATS: DashboardStats = {
pendingAppointments: 0,
pendingAppointmentsOldest: null,
unverifiedListings: 0,
unverifiedListingsOldest: null,
urgentItHilfe: 0,
urgentItHilfeOldest: null,
pendingRepairerApplications: 0,
pendingRepairerApplicationsOldest: null,
pendingJobApplications: 0,
pendingJobApplicationsOldest: null,
overdueTasks: 0,
overdueTasksOldest: null,
openDecisions: 0,
newUsersThisWeek: 0,
postsPublishedThisWeek: 0,
totalUsers: 0,
totalStaff: 0,
totalTechnicians: 0,
totalListings: 0,
activeListings: 0,
mission: {
devicesProcessedThisMonth: 0,
devicesSoldThisMonth: 0,
itHilfeCompletedThisMonth: 0,
workshopAttendeesThisMonth: 0,
},
delta: { devicesProcessed: 0, devicesSold: 0, itHilfeCompleted: 0, workshopAttendees: 0 },
topUnverifiedListing: null,
topPendingRepairerApp: null,
}
function emptyCounts(): ApprovalCounts {
return Object.fromEntries(
APPROVAL_SOURCES.map(s => [s.key, { pending: 0, oldestAt: null, failed: false }]),
)
}
const allowAll = (_section: AdminSection) => true
const denyAll = (_section: AdminSection) => false
describe('buildActionItems — approval sources are SSOT-driven', () => {
it('emits one queue row per pending approval source, routed to its reviewHref', () => {
const counts = emptyCounts()
counts.blog = { pending: 2, oldestAt: '2026-07-01T00:00:00.000Z', failed: false }
counts.location = { pending: 1, oldestAt: '2026-07-08T00:00:00.000Z', failed: false }
const items = buildActionItems(ZERO_STATS, counts, true, allowAll)
const blogSource = APPROVAL_SOURCES.find(s => s.key === 'blog')!
const blogItem = items.find(i => i.href === blogSource.reviewHref)
expect(blogItem).toBeDefined()
expect(blogItem!.count).toBe(2)
// No hardcoded pluralization in the label — the count lives in the badge.
expect(blogItem!.label).toBe(`${blogSource.label} zur Freigabe`)
expect(items.filter(i => i.count && i.count > 0)).toHaveLength(2)
})
it('does NOT emit a source the viewer lacks permission for', () => {
const counts = emptyCounts()
counts.timecard = { pending: 5, oldestAt: '2026-07-01T00:00:00.000Z', failed: false }
const items = buildActionItems(ZERO_STATS, counts, true, denyAll)
expect(items).toHaveLength(0)
})
it('hides super-admin-only sources (permission requests) from non-supers', () => {
const counts = emptyCounts()
counts.permission_request = { pending: 3, oldestAt: '2026-07-01T00:00:00.000Z', failed: false }
const asSuper = buildActionItems(ZERO_STATS, counts, true, allowAll)
const asStaff = buildActionItems(ZERO_STATS, counts, false, allowAll)
expect(asSuper.some(i => i.count === 3)).toBe(true)
expect(asStaff.some(i => i.count === 3)).toBe(false)
})
it('marks a source urgent once its oldest pending item is >= 7 days old', () => {
const old = new Date(Date.now() - 9 * 86_400_000).toISOString()
const fresh = new Date(Date.now() - 1 * 86_400_000).toISOString()
const counts = emptyCounts()
counts.blog = { pending: 1, oldestAt: old, failed: false }
counts.location = { pending: 1, oldestAt: fresh, failed: false }
const items = buildActionItems(ZERO_STATS, counts, true, allowAll)
const blogSource = APPROVAL_SOURCES.find(s => s.key === 'blog')!
const locSource = APPROVAL_SOURCES.find(s => s.key === 'location')!
expect(items.find(i => i.href === blogSource.reviewHref)!.type).toBe('urgent')
expect(items.find(i => i.href === locSource.reviewHref)!.type).toBe('warning')
})
it('skips sources whose count query failed (never a misleading zero row)', () => {
const counts = emptyCounts()
counts.blog = { pending: 0, oldestAt: null, failed: true }
const items = buildActionItems(ZERO_STATS, counts, true, allowAll)
expect(items).toHaveLength(0)
})
})
@@ -1,35 +1,44 @@
import type { DashboardStats, ActionItem } from './types'
import { SERVICE_APPOINTMENT_ROUTES } from '@/config/service-appointments'
import type { AdminSection } from '@/lib/permissions'
import { APPROVAL_SOURCES } from '@/config/approval-sources'
import type { ApprovalCounts } from '@/lib/approvals/counts'
/** A pending approval older than this reads as urgent (matches the hub hero). */
const APPROVAL_STALE_DAYS = 7
function daysSince(iso: string | null): number | null {
if (!iso) return null
return Math.floor((Date.now() - Date.parse(iso)) / 86_400_000)
}
export function buildActionItems(
stats: DashboardStats,
approvalCounts: ApprovalCounts,
isSuper: boolean,
canAccessSection: (section: AdminSection) => boolean
): ActionItem[] {
const items: ActionItem[] = []
if (stats.pendingApprovals > 0 && canAccessSection('approvals')) {
// Approval sources — ONE count engine (`getApprovalCounts` over the
// APPROVAL_SOURCES SSOT), the SAME one the /admin/approvals hub reads. This
// replaces the former dead `user_content_submissions` read plus the separately
// queried blog/timecard/permission counts, so the dashboard and the hub can no
// longer disagree. Each row routes to its own review surface (`reviewHref`) and
// is gated by its own section permission — add a source and it appears here.
for (const source of APPROVAL_SOURCES) {
const count = approvalCounts[source.key]
if (!count || count.failed || count.pending === 0) continue
if (source.superAdminOnly && !isSuper) continue
if (!canAccessSection(source.permission as AdminSection)) continue
const age = daysSince(count.oldestAt)
items.push({
type: 'urgent',
label: `${stats.pendingApprovals} Freigabe${stats.pendingApprovals > 1 ? 'n' : ''} warten`,
count: stats.pendingApprovals,
href: '/admin/approvals',
actionLabel: 'Jetzt prüfen',
oldestAt: stats.pendingApprovalsOldest,
inlineAction: stats.topPendingApproval
? { itemId: stats.topPendingApproval.id, itemLabel: stats.topPendingApproval.label, actionType: 'approve_blog' }
: undefined,
})
}
if (isSuper && stats.pendingPermissionRequests > 0) {
items.push({
type: 'warning',
label: `${stats.pendingPermissionRequests} Berechtigungsanfrage${stats.pendingPermissionRequests > 1 ? 'n' : ''}`,
count: stats.pendingPermissionRequests,
href: '#permission-requests',
actionLabel: 'Ansehen',
type: age !== null && age >= APPROVAL_STALE_DAYS ? 'urgent' : 'warning',
label: `${source.label} zur Freigabe`,
count: count.pending,
href: source.reviewHref,
actionLabel: 'Prüfen',
oldestAt: count.oldestAt,
})
}
@@ -80,17 +89,6 @@ export function buildActionItems(
})
}
if (stats.pendingBlogSubmissions > 0) {
items.push({
type: 'warning',
label: `${stats.pendingBlogSubmissions} Blog-Einreichung${stats.pendingBlogSubmissions > 1 ? 'en' : ''} ausstehend`,
count: stats.pendingBlogSubmissions,
href: '/admin/approvals',
actionLabel: 'Prüfen',
oldestAt: stats.pendingBlogSubmissionsOldest,
})
}
if (stats.pendingJobApplications > 0 && canAccessSection('hr-applications')) {
items.push({
type: 'warning',
@@ -102,17 +100,6 @@ export function buildActionItems(
})
}
if (stats.pendingTimecardApprovals > 0 && canAccessSection('timecard-approvals')) {
items.push({
type: 'warning',
label: `${stats.pendingTimecardApprovals} Zeitkarte${stats.pendingTimecardApprovals > 1 ? 'n' : ''} zur Freigabe`,
count: stats.pendingTimecardApprovals,
href: '/admin/team/approvals',
actionLabel: 'Freigeben',
oldestAt: stats.pendingTimecardApprovalsOldest,
})
}
if (stats.pendingRepairerApplications > 0) {
items.push({
type: 'warning',
@@ -1,63 +0,0 @@
import {
ClipboardCheck,
FileText,
Zap,
Calendar,
Wrench,
} from 'lucide-react'
import type { DashboardStats, FulfillAction } from './types'
import { SERVICE_APPOINTMENT_ROUTES } from '@/config/service-appointments'
export function buildFulfillActions(
stats: DashboardStats,
canAccessSection: (section: string) => boolean,
): FulfillAction[] {
const actions: FulfillAction[] = []
if (stats.unverifiedListings > 0) {
actions.push({
label: 'Inserate prüfen',
href: '/admin/marketplace',
icon: ClipboardCheck,
count: stats.unverifiedListings,
})
}
if (stats.pendingBlogSubmissions > 0) {
actions.push({
label: 'Blog-Einreichungen',
href: '/admin/approvals',
icon: FileText,
count: stats.pendingBlogSubmissions,
})
}
if (stats.urgentItHilfe > 0 && canAccessSection('it-hilfe-admin')) {
actions.push({
label: 'IT-Hilfe zuweisen',
href: '/admin/it-hilfe',
icon: Zap,
count: stats.urgentItHilfe,
})
}
if (stats.pendingAppointments > 0 && canAccessSection('appointments-admin')) {
actions.push({
label: 'Termine bestätigen',
href: SERVICE_APPOINTMENT_ROUTES.adminList,
icon: Calendar,
count: stats.pendingAppointments,
})
}
if (stats.pendingRepairerApplications > 0) {
actions.push({
label: 'Techniker-Bewerbungen',
href: '/admin/repairer-applications',
icon: Wrench,
count: stats.pendingRepairerApplications,
})
}
return actions
}
@@ -1,5 +1,6 @@
import { buildActionItems } from './buildActionItems'
import type { DashboardStats, UnifiedQueueItem } from './types'
import type { ApprovalCounts } from '@/lib/approvals/counts'
import type { AdminSection } from '@/lib/permissions'
const URGENCY_ORDER = { urgent: 0, warning: 1, success: 2 } as const
@@ -13,10 +14,11 @@ const URGENCY_ORDER = { urgent: 0, warning: 1, success: 2 } as const
*/
export function buildUnifiedQueue(
stats: DashboardStats,
approvalCounts: ApprovalCounts,
isSuper: boolean,
canAccessSection: (section: AdminSection) => boolean,
): UnifiedQueueItem[] {
return buildActionItems(stats, isSuper, canAccessSection).sort(
return buildActionItems(stats, approvalCounts, isSuper, canAccessSection).sort(
(a, b) => URGENCY_ORDER[a.type] - URGENCY_ORDER[b.type]
)
}
@@ -1,21 +1,17 @@
import { db } from '@/db'
import { sql, getTableName } from 'drizzle-orm'
import {
users, userContentSubmissions, staffPermissionRequests,
serviceAppointments, repairerProfiles, listings,
users, serviceAppointments, repairerProfiles, listings,
tasks, decisions, itHilfeRequests, repairerApplications,
inventoryItems, workshopRegistrations,
} from '@/db/schema'
import { jobApplications } from '@/db/schema/hr-vacancies'
import { timecards } from '@/db/schema/timecards'
import { blogPosts, blogSubmissions } from '@/db/schema/content'
import { APPROVAL_STATUS, SUBMISSION_CONTENT_TYPE } from '@/config/approval-status'
import { PERMISSION_REQUEST_STATUS } from '@/config/permission-request-status'
import { blogPosts } from '@/db/schema/content'
import { APPROVAL_STATUS } from '@/config/approval-status'
import { LISTING_STATUS } from '@/config/marketplace'
import { REQUEST_STATUS, URGENCY } from '@/config/it-hilfe'
import { REPAIRER_APPLICATION_STATUS, REPAIRER_PROFILE_TIER } from '@/config/repairer-status'
import { APPLICATION_STATUS } from '@/config/hr-application-status'
import { TIMECARD_STATUSES } from '@/config/timecards'
import { DECISION_STATUS } from '@/config/decisions'
import { INVENTORY_ITEM_STATUS } from '@/config/marketplace-status'
import { logger } from '@/lib/logger'
@@ -23,17 +19,13 @@ import type { DashboardStats } from './types'
// Table name refs
const usersTable = getTableName(users)
const ucsTable = getTableName(userContentSubmissions)
const sprTable = getTableName(staffPermissionRequests)
const saTable = getTableName(serviceAppointments)
const rpTable = getTableName(repairerProfiles)
const blogTable = getTableName(blogPosts)
const listingsTable = getTableName(listings)
const blogSubTable = getTableName(blogSubmissions)
const itHilfeTable = getTableName(itHilfeRequests)
const repairerAppTable = getTableName(repairerApplications)
const jobApplicationsTable = getTableName(jobApplications)
const timecardsTable = getTableName(timecards)
const tasksTable = getTableName(tasks)
const decisionsTable = getTableName(decisions)
const inventoryTable = getTableName(inventoryItems)
@@ -89,14 +81,10 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
usersRes,
staffRes,
techRes,
approvalsRes,
permissionsRes,
appointmentsRes,
blogSubRes,
itHilfeRes,
repairerRes,
jobApplicationsRes,
timecardsRes,
tasksRes,
decisionsRes,
listingsRes,
@@ -110,7 +98,6 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
prevDevicesSoldRes,
prevItHilfeCompletedRes,
prevWorkshopAttendeesRes,
topApprovalRes,
topListingRes,
topRepairerRes,
] = await Promise.allSettled([
@@ -119,30 +106,15 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
db.execute(sql`SELECT COUNT(*) AS count FROM ${sql.raw(usersTable)} WHERE is_staff = true`),
db.execute(sql`SELECT COUNT(*) AS count FROM ${sql.raw(rpTable)} WHERE is_active = true AND profile_tier = ${REPAIRER_PROFILE_TIER.COMMUNITY}`),
// Action items — count + oldest unresolved
db.execute(sql`
SELECT COUNT(*) AS count, MIN(created_at) AS oldest
FROM ${sql.raw(ucsTable)}
WHERE status = ${APPROVAL_STATUS.PENDING}
AND content_type IN (${SUBMISSION_CONTENT_TYPE.WORKSHOP}, ${SUBMISSION_CONTENT_TYPE.BLOG_POST})
`),
isSuper
? db.execute(sql`
SELECT COUNT(*) AS count
FROM ${sql.raw(sprTable)}
WHERE status = ${PERMISSION_REQUEST_STATUS.PENDING}
`)
: Promise.resolve({ rows: [{ count: '0' }] }),
// Action items — count + oldest unresolved. NOTE: approval-type counts
// (blog/workshop proposals/locations/timecards/absences/permission requests)
// are intentionally NOT here — they come from the SSOT `getApprovalCounts()`
// engine so the dashboard and the /admin/approvals hub read ONE source.
db.execute(sql`
SELECT COUNT(*) AS count, MIN(created_at) AS oldest
FROM ${sql.raw(saTable)}
WHERE status = ${APPROVAL_STATUS.PENDING}
`),
db.execute(sql`
SELECT COUNT(*) AS count, MIN(created_at) AS oldest
FROM ${sql.raw(blogSubTable)}
WHERE status = ${APPROVAL_STATUS.PENDING}
`),
db.execute(sql`
SELECT COUNT(*) AS count, MIN(created_at) AS oldest
FROM ${sql.raw(itHilfeTable)}
@@ -158,11 +130,6 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
FROM ${sql.raw(jobApplicationsTable)}
WHERE status = ${APPLICATION_STATUS.NEW}
`),
db.execute(sql`
SELECT COUNT(*) AS count, MIN(submitted_at) AS oldest
FROM ${sql.raw(timecardsTable)}
WHERE status = ${TIMECARD_STATUSES.SUBMITTED}
`),
db.execute(sql`
SELECT COUNT(*) AS count, MIN(due_date) AS oldest
FROM ${sql.raw(tasksTable)}
@@ -239,14 +206,6 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
`),
// Top pending items for inline actions in the dashboard queue
db.execute(sql`
SELECT id, COALESCE(title, content_type, 'Einreichung') AS label
FROM ${sql.raw(ucsTable)}
WHERE status = ${APPROVAL_STATUS.PENDING}
AND content_type IN (${SUBMISSION_CONTENT_TYPE.WORKSHOP}, ${SUBMISSION_CONTENT_TYPE.BLOG_POST})
ORDER BY created_at ASC
LIMIT 1
`),
db.execute(sql`
SELECT id, COALESCE(title, 'Inserat') AS label
FROM ${sql.raw(listingsTable)}
@@ -264,14 +223,12 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
`),
])
// Extract approvals
const approvals = rowCountAndOldest(approvalsRes, 'pendingApprovals')
// Extract non-approval action items (approval-type counts come from the SSOT
// `getApprovalCounts()` engine, not from here).
const appointments = rowCountAndOldest(appointmentsRes, 'pendingAppointments')
const blogSubs = rowCountAndOldest(blogSubRes, 'pendingBlogSubmissions')
const itHilfe = rowCountAndOldest(itHilfeRes, 'urgentItHilfe')
const repairer = rowCountAndOldest(repairerRes, 'pendingRepairerApplications')
const jobApps = rowCountAndOldest(jobApplicationsRes, 'pendingJobApplications')
const timecardApprovals = rowCountAndOldest(timecardsRes, 'pendingTimecardApprovals')
const overdueTasksData = rowCountAndOldest(tasksRes, 'overdueTasks')
// Listings (special shape)
@@ -290,23 +247,16 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
}
return {
pendingApprovals: approvals.count,
pendingApprovalsOldest: approvals.oldest,
pendingPermissionRequests: rowCount(permissionsRes, 'pendingPermissionRequests'),
pendingAppointments: appointments.count,
pendingAppointmentsOldest: appointments.oldest,
unverifiedListings,
unverifiedListingsOldest,
pendingBlogSubmissions: blogSubs.count,
pendingBlogSubmissionsOldest: blogSubs.oldest,
urgentItHilfe: itHilfe.count,
urgentItHilfeOldest: itHilfe.oldest,
pendingRepairerApplications: repairer.count,
pendingRepairerApplicationsOldest: repairer.oldest,
pendingJobApplications: jobApps.count,
pendingJobApplicationsOldest: jobApps.oldest,
pendingTimecardApprovals: timecardApprovals.count,
pendingTimecardApprovalsOldest: timecardApprovals.oldest,
overdueTasks: overdueTasksData.count,
overdueTasksOldest: overdueTasksData.oldest,
openDecisions: rowCount(decisionsRes, 'openDecisions'),
@@ -337,11 +287,6 @@ export async function getDashboardStats(isSuper: boolean): Promise<DashboardStat
rowCount(workshopAttendeesRes, 'workshopAttendeesThisMonth') -
rowCount(prevWorkshopAttendeesRes, 'prevWorkshopAttendees'),
},
topPendingApproval: (() => {
if (topApprovalRes.status !== 'fulfilled') return null
const r = (topApprovalRes.value.rows as Row[])[0]
return r ? { id: String(r.id), label: String(r.label) } : null
})(),
topUnverifiedListing: (() => {
if (topListingRes.status !== 'fulfilled') return null
const r = (topListingRes.value.rows as Row[])[0]
+1 -4
View File
@@ -1,10 +1,7 @@
export { getDashboardStats } from './getDashboardStats'
export { buildActionItems } from './buildActionItems'
export { buildQuickActions } from './buildQuickActions'
export { buildFulfillActions } from './buildFulfillActions'
export { buildUnifiedQueue } from './buildUnifiedQueue'
export { ActionItemsSection } from './ActionItemsSection'
export { QuickActionsSection } from './QuickActionsSection'
export { WeeklyActivitySection } from './WeeklyActivitySection'
export { MissionMetrics } from './MissionMetrics'
export { UnifiedQueue } from './UnifiedQueue'
@@ -14,4 +11,4 @@ export { VotingBanner } from './VotingBanner'
export { PersonalSection } from './PersonalSection'
export { BannerSkeleton, PersonalSectionSkeleton, UnifiedQueueSkeleton } from './skeletons'
export { DashboardModeToggle } from './DashboardModeToggle'
export type { DashboardStats, ActionItem, QuickAction, FulfillAction, MissionStats, MissionDelta, UnifiedQueueItem } from './types'
export type { DashboardStats, ActionItem, QuickAction, MissionStats, MissionDelta, UnifiedQueueItem } from './types'
+7 -16
View File
@@ -15,24 +15,23 @@ export interface MissionDelta {
}
export interface DashboardStats {
// NOTE: approval-type counts (blog, workshop proposals, locations, timecards,
// absences, permission requests) are NOT here — they come from the SSOT
// `getApprovalCounts()` engine (src/lib/approvals/counts.ts), the same one the
// /admin/approvals hub reads, so the two surfaces can't drift. Only
// non-approval action items live in DashboardStats.
// Action items with age of oldest unresolved item
pendingApprovals: number
pendingApprovalsOldest: string | null
pendingPermissionRequests: number
pendingAppointments: number
pendingAppointmentsOldest: string | null
unverifiedListings: number
unverifiedListingsOldest: string | null
pendingBlogSubmissions: number
pendingBlogSubmissionsOldest: string | null
urgentItHilfe: number
urgentItHilfeOldest: string | null
pendingRepairerApplications: number
pendingRepairerApplicationsOldest: string | null
pendingJobApplications: number
pendingJobApplicationsOldest: string | null
pendingTimecardApprovals: number
pendingTimecardApprovalsOldest: string | null
overdueTasks: number
overdueTasksOldest: string | null
openDecisions: number
@@ -55,7 +54,6 @@ export interface DashboardStats {
// Delta vs last month (positive = improvement)
delta: MissionDelta
// Top pending items for inline actions in UnifiedQueue
topPendingApproval: { id: string; label: string } | null
topUnverifiedListing: { id: string; label: string } | null
topPendingRepairerApp: { id: string; label: string } | null
}
@@ -83,13 +81,6 @@ export type QuickAction = {
color: string
}
export type FulfillAction = {
label: string
href: string
icon: typeof Package
count: number
}
// UnifiedQueueItem is an ActionItem — same shape, used in the merged queue
// that replaces the separate ActionItems + FulfillActions sections.
// that replaced the separate ActionItems + FulfillActions sections.
export type UnifiedQueueItem = ActionItem
+4 -2
View File
@@ -71,7 +71,9 @@ export const APPROVAL_SOURCES: readonly ApprovalSourceConfig[] = [
icon: Clock,
reviewMode: 'bulk',
reviewHref: '/admin/team/approvals',
permission: 'timecards',
// Gate on the APPROVAL surface, not personal `timecards` — only reviewers,
// not everyone with their own card, should see this in a queue.
permission: 'timecard-approvals',
},
{
key: 'time_off',
@@ -80,7 +82,7 @@ export const APPROVAL_SOURCES: readonly ApprovalSourceConfig[] = [
icon: CalendarOff,
reviewMode: 'bulk',
reviewHref: '/admin/team/approvals',
permission: 'timecards',
permission: 'timecard-approvals',
},
{
key: 'permission_request',