add editable menu items for companies
This commit is contained in:
@@ -4,6 +4,7 @@ import { parseBody, parseQuery, parseParams } from '../../http/validate'
|
||||
import { ok, created } from '../../http/respond'
|
||||
import * as service from './admin.service'
|
||||
import * as subService from '../subscriptions/subscription.service'
|
||||
import * as menuService from '../menu/menu.service'
|
||||
import { presentAdminUser } from './admin.presenter'
|
||||
import {
|
||||
loginSchema, forgotPasswordSchema, resetPasswordSchema, totpVerifySchema,
|
||||
@@ -16,6 +17,8 @@ import {
|
||||
promotionCreateSchema, promotionUpdateSchema, promotionIdParamSchema,
|
||||
billingAccountUpdateSchema, createBillingInvoiceSchema, payBillingInvoiceSchema,
|
||||
retryBillingInvoiceSchema, billingReasonSchema, billingCreditNoteSchema, billingRefundSchema,
|
||||
menuItemSchema, menuItemStatusSchema, menuPlanAssignmentsSchema, menuCompanyAssignmentsSchema,
|
||||
menuPreviewSchema, menuAuditLogQuerySchema, menuPlanParamSchema, menuCompanyParamSchema,
|
||||
} from './admin.schemas'
|
||||
import { z } from 'zod'
|
||||
|
||||
@@ -127,6 +130,92 @@ router.post('/companies/:id/impersonate', requireAdminAuth, requireAdminRole('AD
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
// ─── Menu management ──────────────────────────────────────────
|
||||
|
||||
router.get('/menu-items', requireAdminAuth, requireAdminRole('SUPPORT'), async (_req, res, next) => {
|
||||
try {
|
||||
ok(res, await menuService.listMenuItems())
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.post('/menu-items', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
created(res, { data: await menuService.createMenuItem(parseBody(menuItemSchema, req), req.admin) })
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.get('/menu-items/:id', requireAdminAuth, requireAdminRole('SUPPORT'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
ok(res, await menuService.getMenuItem(id))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.put('/menu-items/:id', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
ok(res, await menuService.updateMenuItem(id, parseBody(menuItemSchema, req), req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.patch('/menu-items/:id/status', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
const { isActive } = parseBody(menuItemStatusSchema, req)
|
||||
ok(res, await menuService.setMenuItemStatus(id, isActive, req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.delete('/menu-items/:id', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
await menuService.deleteMenuItem(id, req.admin)
|
||||
ok(res, { success: true })
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.post('/menu-items/:id/subscriptions', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
const { assignments } = parseBody(menuPlanAssignmentsSchema, req)
|
||||
ok(res, await menuService.assignMenuItemToPlans(id, assignments, req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.delete('/menu-items/:id/subscriptions/:plan', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id, plan } = parseParams(menuPlanParamSchema, req)
|
||||
ok(res, await menuService.removeMenuItemFromPlan(id, plan, req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.post('/menu-items/:id/companies', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id } = parseParams(idParamSchema, req)
|
||||
const { assignments } = parseBody(menuCompanyAssignmentsSchema, req)
|
||||
ok(res, await menuService.assignMenuItemToCompanies(id, assignments, req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.delete('/menu-items/:id/companies/:companyId', requireAdminAuth, requireAdminRole('ADMIN'), async (req, res, next) => {
|
||||
try {
|
||||
const { id, companyId } = parseParams(menuCompanyParamSchema, req)
|
||||
ok(res, await menuService.removeMenuItemFromCompany(id, companyId, req.admin))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.post('/menu-preview', requireAdminAuth, requireAdminRole('SUPPORT'), async (req, res, next) => {
|
||||
try {
|
||||
ok(res, await menuService.previewCompanyMenu(parseBody(menuPreviewSchema, req)))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.get('/menu-audit-logs', requireAdminAuth, requireAdminRole('SUPPORT'), async (req, res, next) => {
|
||||
try {
|
||||
ok(res, await menuService.listMenuAuditLogs(parseQuery(menuAuditLogQuerySchema, req)))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
// ─── Renters ───────────────────────────────────────────────────
|
||||
|
||||
router.get('/renters', requireAdminAuth, async (req, res, next) => {
|
||||
|
||||
@@ -332,3 +332,75 @@ export const promotionUpdateSchema = promotionCreateSchema.partial()
|
||||
|
||||
export const planFeatureIdParamSchema = z.object({ featureId: z.string().min(1) })
|
||||
export const promotionIdParamSchema = z.object({ promotionId: z.string().min(1) })
|
||||
|
||||
const employeeRoleSchema = z.enum(['OWNER', 'MANAGER', 'AGENT'])
|
||||
const planSchema = z.enum(['STARTER', 'GROWTH', 'PRO'])
|
||||
const menuItemTypeSchema = z.enum(['INTERNAL_PAGE', 'EXTERNAL_LINK', 'PARENT_MENU', 'SECTION_LABEL', 'DIVIDER'])
|
||||
|
||||
export const menuItemSchema = z.object({
|
||||
systemKey: z.string().trim().min(1).max(120).optional().nullable(),
|
||||
label: z.string().trim().min(1).max(120),
|
||||
itemType: menuItemTypeSchema,
|
||||
routeOrUrl: z.string().trim().max(400).optional().nullable(),
|
||||
icon: z.string().trim().max(120).optional().nullable(),
|
||||
parentId: z.string().trim().min(1).optional().nullable(),
|
||||
displayOrder: z.number().int().min(0).default(0),
|
||||
openInNewTab: z.boolean().default(false),
|
||||
isRequired: z.boolean().default(false),
|
||||
isActive: z.boolean().default(true),
|
||||
roles: z.array(employeeRoleSchema).default([]),
|
||||
subscriptionPlans: z.array(z.object({
|
||||
plan: planSchema,
|
||||
displayOrder: z.number().int().min(0).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
})).default([]),
|
||||
companyAssignments: z.array(z.object({
|
||||
companyId: z.string().trim().min(1),
|
||||
displayOrder: z.number().int().min(0).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
})).default([]),
|
||||
})
|
||||
|
||||
export const menuItemStatusSchema = z.object({
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
export const menuPlanAssignmentsSchema = z.object({
|
||||
assignments: z.array(z.object({
|
||||
plan: planSchema,
|
||||
displayOrder: z.number().int().min(0).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
})).min(1),
|
||||
})
|
||||
|
||||
export const menuCompanyAssignmentsSchema = z.object({
|
||||
assignments: z.array(z.object({
|
||||
companyId: z.string().trim().min(1),
|
||||
displayOrder: z.number().int().min(0).optional(),
|
||||
isActive: z.boolean().optional(),
|
||||
})).min(1),
|
||||
})
|
||||
|
||||
export const menuPreviewSchema = z.object({
|
||||
companyId: z.string().trim().min(1),
|
||||
role: employeeRoleSchema,
|
||||
})
|
||||
|
||||
export const menuAuditLogQuerySchema = z.object({
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
pageSize: z.coerce.number().int().min(1).max(100).default(20),
|
||||
})
|
||||
|
||||
export const menuItemIdParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
})
|
||||
|
||||
export const menuPlanParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
plan: planSchema,
|
||||
})
|
||||
|
||||
export const menuCompanyParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
companyId: z.string().min(1),
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Router } from 'express'
|
||||
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
|
||||
import { parseBody } from '../../http/validate'
|
||||
import { ok } from '../../http/respond'
|
||||
import { getEmployeeMenu } from '../menu/menu.service'
|
||||
import {
|
||||
employeeForgotPasswordSchema,
|
||||
employeeLanguageSchema,
|
||||
@@ -18,6 +19,12 @@ router.get('/me', requireCompanyAuth, async (req, res, next) => {
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.get('/menu', requireCompanyAuth, async (req, res, next) => {
|
||||
try {
|
||||
ok(res, await getEmployeeMenu(req.employee.id))
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
router.post('/login', async (req, res, next) => {
|
||||
try {
|
||||
const body = parseBody(employeeLoginSchema, req)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../../lib/prisma', () => ({
|
||||
prisma: {
|
||||
menuItem: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
employee: {
|
||||
findUniqueOrThrow: vi.fn(),
|
||||
},
|
||||
company: {
|
||||
findUniqueOrThrow: vi.fn(),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { prisma } from '../../lib/prisma'
|
||||
import { getEmployeeMenu, previewCompanyMenu } from './menu.service'
|
||||
|
||||
describe('menu.service', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('builds the employee menu from subscription defaults and company overrides', async () => {
|
||||
vi.mocked(prisma.employee.findUniqueOrThrow).mockResolvedValue({
|
||||
id: 'employee_1',
|
||||
role: 'MANAGER',
|
||||
isActive: true,
|
||||
companyId: 'company_1',
|
||||
} as never)
|
||||
|
||||
vi.mocked(prisma.company.findUniqueOrThrow).mockResolvedValue({
|
||||
id: 'company_1',
|
||||
name: 'Atlas Cars',
|
||||
status: 'ACTIVE',
|
||||
subscription: { plan: 'GROWTH', status: 'ACTIVE' },
|
||||
} as never)
|
||||
|
||||
vi.mocked(prisma.menuItem.findMany).mockResolvedValue([
|
||||
{
|
||||
id: 'item_dashboard',
|
||||
systemKey: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
routeOrUrl: '/',
|
||||
icon: 'LayoutDashboard',
|
||||
parentId: null,
|
||||
openInNewTab: false,
|
||||
isRequired: true,
|
||||
isActive: true,
|
||||
displayOrder: 1,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [],
|
||||
companyAssignments: [],
|
||||
},
|
||||
{
|
||||
id: 'item_reports',
|
||||
systemKey: 'reports',
|
||||
label: 'Reports',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
routeOrUrl: '/reports',
|
||||
icon: 'BarChart2',
|
||||
parentId: null,
|
||||
openInNewTab: false,
|
||||
isRequired: false,
|
||||
isActive: true,
|
||||
displayOrder: 80,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [{ plan: 'GROWTH', displayOrder: 80, isActive: true }],
|
||||
companyAssignments: [],
|
||||
},
|
||||
{
|
||||
id: 'item_finance',
|
||||
systemKey: null,
|
||||
label: 'Finance Portal',
|
||||
itemType: 'EXTERNAL_LINK',
|
||||
routeOrUrl: 'https://finance.example.com',
|
||||
icon: null,
|
||||
parentId: null,
|
||||
openInNewTab: true,
|
||||
isRequired: false,
|
||||
isActive: true,
|
||||
displayOrder: 200,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [],
|
||||
companyAssignments: [{ companyId: 'company_1', displayOrder: 5, isActive: true }],
|
||||
},
|
||||
{
|
||||
id: 'item_owner_only',
|
||||
systemKey: 'settings',
|
||||
label: 'Settings',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
routeOrUrl: '/settings',
|
||||
icon: 'Settings',
|
||||
parentId: null,
|
||||
openInNewTab: false,
|
||||
isRequired: false,
|
||||
isActive: true,
|
||||
displayOrder: 150,
|
||||
roleVisibilities: [{ role: 'OWNER' }],
|
||||
subscriptionAssignments: [{ plan: 'GROWTH', displayOrder: 150, isActive: true }],
|
||||
companyAssignments: [],
|
||||
},
|
||||
] as never)
|
||||
|
||||
const result = await getEmployeeMenu('employee_1')
|
||||
|
||||
expect(result.items).toHaveLength(3)
|
||||
expect(result.items.map((item) => item.label)).toEqual(['Dashboard', 'Finance Portal', 'Reports'])
|
||||
expect(result.items[0]).toMatchObject({
|
||||
label: 'Dashboard',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
})
|
||||
expect(result.items[1]).toMatchObject({
|
||||
label: 'Finance Portal',
|
||||
itemType: 'EXTERNAL_LINK',
|
||||
openInNewTab: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('explains hidden items in preview results', async () => {
|
||||
vi.mocked(prisma.company.findUniqueOrThrow).mockResolvedValue({
|
||||
id: 'company_1',
|
||||
name: 'Atlas Cars',
|
||||
status: 'ACTIVE',
|
||||
subscription: { plan: 'STARTER', status: 'ACTIVE' },
|
||||
} as never)
|
||||
|
||||
vi.mocked(prisma.menuItem.findMany).mockResolvedValue([
|
||||
{
|
||||
id: 'item_dashboard',
|
||||
systemKey: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
routeOrUrl: '/',
|
||||
icon: 'LayoutDashboard',
|
||||
parentId: null,
|
||||
openInNewTab: false,
|
||||
isRequired: true,
|
||||
isActive: true,
|
||||
displayOrder: 1,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [],
|
||||
companyAssignments: [],
|
||||
},
|
||||
{
|
||||
id: 'item_reports',
|
||||
systemKey: 'reports',
|
||||
label: 'Reports',
|
||||
itemType: 'INTERNAL_PAGE',
|
||||
routeOrUrl: '/reports',
|
||||
icon: 'BarChart2',
|
||||
parentId: null,
|
||||
openInNewTab: false,
|
||||
isRequired: false,
|
||||
isActive: true,
|
||||
displayOrder: 80,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [{ plan: 'GROWTH', displayOrder: 80, isActive: true }],
|
||||
companyAssignments: [],
|
||||
},
|
||||
{
|
||||
id: 'item_direct',
|
||||
systemKey: null,
|
||||
label: 'Finance Portal',
|
||||
itemType: 'EXTERNAL_LINK',
|
||||
routeOrUrl: 'https://finance.example.com',
|
||||
icon: null,
|
||||
parentId: null,
|
||||
openInNewTab: true,
|
||||
isRequired: false,
|
||||
isActive: true,
|
||||
displayOrder: 20,
|
||||
roleVisibilities: [{ role: 'MANAGER' }],
|
||||
subscriptionAssignments: [],
|
||||
companyAssignments: [{ companyId: 'company_1', displayOrder: 10, isActive: true }],
|
||||
},
|
||||
] as never)
|
||||
|
||||
const result = await previewCompanyMenu({ companyId: 'company_1', role: 'MANAGER' })
|
||||
|
||||
expect(result.items.find((item) => item.label === 'Dashboard')).toMatchObject({
|
||||
visible: true,
|
||||
source: 'subscription',
|
||||
})
|
||||
expect(result.items.find((item) => item.label === 'Dashboard')?.reasons.join(' ')).toContain('defaults to all subscription plans')
|
||||
expect(result.items.find((item) => item.label === 'Finance Portal')).toMatchObject({
|
||||
visible: true,
|
||||
source: 'company',
|
||||
})
|
||||
expect(result.items.find((item) => item.label === 'Reports')).toMatchObject({
|
||||
visible: false,
|
||||
})
|
||||
expect(result.items.find((item) => item.label === 'Reports')?.reasons.join(' ')).toContain('STARTER does not include this menu item')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,642 @@
|
||||
import { AppError } from '../../http/errors'
|
||||
import { prisma } from '../../lib/prisma'
|
||||
|
||||
type EmployeeRole = 'OWNER' | 'MANAGER' | 'AGENT'
|
||||
type Plan = 'STARTER' | 'GROWTH' | 'PRO'
|
||||
type MenuItemType = 'INTERNAL_PAGE' | 'EXTERNAL_LINK' | 'PARENT_MENU' | 'SECTION_LABEL' | 'DIVIDER'
|
||||
|
||||
type AdminActor = {
|
||||
id: string
|
||||
role: string
|
||||
}
|
||||
|
||||
type MenuItemInput = {
|
||||
systemKey?: string | null
|
||||
label: string
|
||||
itemType: MenuItemType
|
||||
routeOrUrl?: string | null
|
||||
icon?: string | null
|
||||
parentId?: string | null
|
||||
displayOrder?: number
|
||||
openInNewTab?: boolean
|
||||
isRequired?: boolean
|
||||
isActive?: boolean
|
||||
roles?: EmployeeRole[]
|
||||
subscriptionPlans?: Array<{
|
||||
plan: Plan
|
||||
displayOrder?: number
|
||||
isActive?: boolean
|
||||
}>
|
||||
companyAssignments?: Array<{
|
||||
companyId: string
|
||||
displayOrder?: number
|
||||
isActive?: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
type MenuPreviewInput = {
|
||||
companyId: string
|
||||
role: EmployeeRole
|
||||
}
|
||||
|
||||
type MenuAuditQuery = {
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
const EMPLOYEE_ROLES: EmployeeRole[] = ['OWNER', 'MANAGER', 'AGENT']
|
||||
const MENU_AUDIT_RESOURCES = ['MenuItem', 'MenuSubscriptionAssignment', 'MenuCompanyAssignment', 'MenuRoleVisibility']
|
||||
const MENU_ITEM_TYPES_WITHOUT_ROUTE = new Set([
|
||||
'PARENT_MENU',
|
||||
'SECTION_LABEL',
|
||||
'DIVIDER',
|
||||
])
|
||||
|
||||
function normalizeNullableString(value?: string | null) {
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
return trimmed.length > 0 ? trimmed : null
|
||||
}
|
||||
|
||||
function sortByDisplayOrder<T extends { displayOrder: number; label?: string | null }>(items: T[]) {
|
||||
return [...items].sort((a, b) => {
|
||||
if (a.displayOrder !== b.displayOrder) return a.displayOrder - b.displayOrder
|
||||
return (a.label ?? '').localeCompare(b.label ?? '')
|
||||
})
|
||||
}
|
||||
|
||||
function toPlanValue(plan: Plan) {
|
||||
return plan
|
||||
}
|
||||
|
||||
function toItemTypeValue(itemType: MenuItemType) {
|
||||
return itemType
|
||||
}
|
||||
|
||||
function describeEntitlement(
|
||||
plan: Plan | null,
|
||||
hasSubscriptionAssignment: boolean,
|
||||
hasCompanyAssignment: boolean,
|
||||
defaultsToAllSubscriptions: boolean,
|
||||
) {
|
||||
if (hasCompanyAssignment) return 'Visible because it is assigned directly to this company.'
|
||||
if (defaultsToAllSubscriptions) return 'Visible because this menu item defaults to all subscription plans.'
|
||||
if (hasSubscriptionAssignment && plan) return `Visible because ${plan} includes this menu item.`
|
||||
if (plan) return `Hidden because ${plan} does not include this menu item.`
|
||||
return 'Hidden because the company does not have an active subscription assignment for this item.'
|
||||
}
|
||||
|
||||
async function createAuditLog(admin: AdminActor, action: string, resource: string, resourceId: string | null, before?: unknown, after?: unknown) {
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
adminUserId: admin.id,
|
||||
action,
|
||||
resource,
|
||||
resourceId,
|
||||
before: before === undefined ? undefined : JSON.parse(JSON.stringify(before)),
|
||||
after: after === undefined ? undefined : JSON.parse(JSON.stringify(after)),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function assertMenuItemPayload(input: MenuItemInput, menuItemId?: string) {
|
||||
const label = input.label.trim()
|
||||
if (!label) throw new AppError('Menu label is required.', 400, 'validation_error')
|
||||
|
||||
const itemType = toItemTypeValue(input.itemType)
|
||||
const routeOrUrl = normalizeNullableString(input.routeOrUrl)
|
||||
const parentId = normalizeNullableString(input.parentId)
|
||||
|
||||
if (MENU_ITEM_TYPES_WITHOUT_ROUTE.has(itemType)) {
|
||||
if (routeOrUrl) {
|
||||
throw new AppError('This menu item type cannot define a route or URL.', 400, 'validation_error')
|
||||
}
|
||||
} else if (!routeOrUrl) {
|
||||
throw new AppError('Route or URL is required for this menu item type.', 400, 'validation_error')
|
||||
}
|
||||
|
||||
if (routeOrUrl && itemType === 'EXTERNAL_LINK') {
|
||||
if (!routeOrUrl.startsWith('https://')) {
|
||||
throw new AppError('External links must use HTTPS.', 400, 'validation_error')
|
||||
}
|
||||
}
|
||||
|
||||
if (routeOrUrl && itemType === 'INTERNAL_PAGE' && !routeOrUrl.startsWith('/')) {
|
||||
throw new AppError('Internal page routes must start with "/".', 400, 'validation_error')
|
||||
}
|
||||
|
||||
if (parentId) {
|
||||
if (menuItemId && parentId === menuItemId) {
|
||||
throw new AppError('A menu item cannot be its own parent.', 400, 'validation_error')
|
||||
}
|
||||
|
||||
const parent = await prisma.menuItem.findUnique({ where: { id: parentId } })
|
||||
if (!parent) throw new AppError('Parent menu item was not found.', 400, 'validation_error')
|
||||
if (parent.itemType !== 'PARENT_MENU') {
|
||||
throw new AppError('Only parent menu items can contain children.', 400, 'validation_error')
|
||||
}
|
||||
}
|
||||
|
||||
if (routeOrUrl && !MENU_ITEM_TYPES_WITHOUT_ROUTE.has(itemType)) {
|
||||
const duplicate = await prisma.menuItem.findFirst({
|
||||
where: {
|
||||
routeOrUrl,
|
||||
parentId,
|
||||
...(menuItemId ? { id: { not: menuItemId } } : {}),
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (duplicate) {
|
||||
throw new AppError('Duplicate route under the same parent is not allowed.', 409, 'duplicate_menu_route')
|
||||
}
|
||||
}
|
||||
|
||||
const roles = Array.from(new Set(input.roles ?? []))
|
||||
if (roles.some((role) => !EMPLOYEE_ROLES.includes(role))) {
|
||||
throw new AppError('One or more role visibility values are invalid.', 400, 'validation_error')
|
||||
}
|
||||
|
||||
const companyIds = Array.from(new Set((input.companyAssignments ?? []).map((assignment) => assignment.companyId)))
|
||||
if (companyIds.length > 0) {
|
||||
const companies = await prisma.company.findMany({
|
||||
where: { id: { in: companyIds }, status: { not: 'CANCELLED' } },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (companies.length !== companyIds.length) {
|
||||
throw new AppError('Menu items can only be assigned to active companies.', 400, 'validation_error')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function syncMenuAssignments(
|
||||
tx: Omit<typeof prisma, '$connect' | '$disconnect' | '$on' | '$transaction' | '$use' | '$extends'>,
|
||||
menuItemId: string,
|
||||
input: MenuItemInput,
|
||||
) {
|
||||
await tx.menuItemRoleVisibility.deleteMany({ where: { menuItemId } })
|
||||
if ((input.roles ?? []).length > 0) {
|
||||
await tx.menuItemRoleVisibility.createMany({
|
||||
data: Array.from(new Set(input.roles)).map((role) => ({ menuItemId, role })),
|
||||
})
|
||||
}
|
||||
|
||||
await tx.subscriptionMenuItem.deleteMany({ where: { menuItemId } })
|
||||
if ((input.subscriptionPlans ?? []).length > 0) {
|
||||
await tx.subscriptionMenuItem.createMany({
|
||||
data: input.subscriptionPlans!.map((assignment) => ({
|
||||
menuItemId,
|
||||
plan: toPlanValue(assignment.plan),
|
||||
displayOrder: assignment.displayOrder ?? input.displayOrder ?? 0,
|
||||
isActive: assignment.isActive ?? true,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
await tx.companyMenuItem.deleteMany({ where: { menuItemId } })
|
||||
if ((input.companyAssignments ?? []).length > 0) {
|
||||
await tx.companyMenuItem.createMany({
|
||||
data: input.companyAssignments!.map((assignment) => ({
|
||||
menuItemId,
|
||||
companyId: assignment.companyId,
|
||||
displayOrder: assignment.displayOrder ?? input.displayOrder ?? 0,
|
||||
isActive: assignment.isActive ?? true,
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMenuItemDetail(id: string) {
|
||||
return prisma.menuItem.findUniqueOrThrow({
|
||||
where: { id },
|
||||
include: {
|
||||
parent: { select: { id: true, label: true } },
|
||||
children: { select: { id: true, label: true } },
|
||||
roleVisibilities: { orderBy: { role: 'asc' } },
|
||||
subscriptionAssignments: { orderBy: [{ plan: 'asc' }, { displayOrder: 'asc' }] },
|
||||
companyAssignments: {
|
||||
include: { company: { select: { id: true, name: true } } },
|
||||
orderBy: [{ displayOrder: 'asc' }, { companyId: 'asc' }],
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function listMenuItems() {
|
||||
return prisma.menuItem.findMany({
|
||||
include: {
|
||||
parent: { select: { id: true, label: true } },
|
||||
roleVisibilities: { orderBy: { role: 'asc' } },
|
||||
subscriptionAssignments: { orderBy: [{ plan: 'asc' }, { displayOrder: 'asc' }] },
|
||||
companyAssignments: {
|
||||
include: { company: { select: { id: true, name: true } } },
|
||||
orderBy: [{ displayOrder: 'asc' }, { companyId: 'asc' }],
|
||||
},
|
||||
},
|
||||
orderBy: [{ displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
}
|
||||
|
||||
export async function getMenuItem(id: string) {
|
||||
return loadMenuItemDetail(id)
|
||||
}
|
||||
|
||||
export async function createMenuItem(input: MenuItemInput, admin: AdminActor) {
|
||||
await assertMenuItemPayload(input)
|
||||
|
||||
const created = await prisma.$transaction(async (tx) => {
|
||||
const menuItem = await tx.menuItem.create({
|
||||
data: {
|
||||
systemKey: normalizeNullableString(input.systemKey) ?? undefined,
|
||||
label: input.label.trim(),
|
||||
itemType: toItemTypeValue(input.itemType),
|
||||
routeOrUrl: normalizeNullableString(input.routeOrUrl) ?? undefined,
|
||||
icon: normalizeNullableString(input.icon) ?? undefined,
|
||||
parentId: normalizeNullableString(input.parentId) ?? undefined,
|
||||
displayOrder: input.displayOrder ?? 0,
|
||||
openInNewTab: input.openInNewTab ?? false,
|
||||
isRequired: input.isRequired ?? false,
|
||||
isActive: input.isActive ?? true,
|
||||
createdBy: admin.id,
|
||||
updatedBy: admin.id,
|
||||
},
|
||||
})
|
||||
|
||||
await syncMenuAssignments(tx as any, menuItem.id, input)
|
||||
return menuItem
|
||||
})
|
||||
|
||||
const detail = await loadMenuItemDetail(created.id)
|
||||
await createAuditLog(admin, 'CREATE_MENU_ITEM', 'MenuItem', created.id, undefined, detail)
|
||||
return detail
|
||||
}
|
||||
|
||||
export async function updateMenuItem(id: string, input: MenuItemInput, admin: AdminActor) {
|
||||
const before = await loadMenuItemDetail(id)
|
||||
await assertMenuItemPayload(input, id)
|
||||
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
const menuItem = await tx.menuItem.update({
|
||||
where: { id },
|
||||
data: {
|
||||
systemKey: normalizeNullableString(input.systemKey) ?? undefined,
|
||||
label: input.label.trim(),
|
||||
itemType: toItemTypeValue(input.itemType),
|
||||
routeOrUrl: normalizeNullableString(input.routeOrUrl) ?? undefined,
|
||||
icon: normalizeNullableString(input.icon) ?? undefined,
|
||||
parentId: normalizeNullableString(input.parentId) ?? undefined,
|
||||
displayOrder: input.displayOrder ?? 0,
|
||||
openInNewTab: input.openInNewTab ?? false,
|
||||
isRequired: input.isRequired ?? false,
|
||||
isActive: input.isActive ?? true,
|
||||
updatedBy: admin.id,
|
||||
},
|
||||
})
|
||||
|
||||
await syncMenuAssignments(tx as any, id, input)
|
||||
return menuItem
|
||||
})
|
||||
|
||||
const detail = await loadMenuItemDetail(updated.id)
|
||||
await createAuditLog(admin, 'UPDATE_MENU_ITEM', 'MenuItem', id, before, detail)
|
||||
return detail
|
||||
}
|
||||
|
||||
export async function setMenuItemStatus(id: string, isActive: boolean, admin: AdminActor) {
|
||||
const before = await prisma.menuItem.findUniqueOrThrow({ where: { id } })
|
||||
if (!isActive && before.isRequired && admin.role !== 'SUPER_ADMIN') {
|
||||
throw new AppError('Required system items can only be disabled by a Super Admin.', 403, 'forbidden')
|
||||
}
|
||||
|
||||
const updated = await prisma.menuItem.update({
|
||||
where: { id },
|
||||
data: { isActive, updatedBy: admin.id },
|
||||
})
|
||||
|
||||
await createAuditLog(
|
||||
admin,
|
||||
isActive ? 'ENABLE_MENU_ITEM' : 'DISABLE_MENU_ITEM',
|
||||
'MenuItem',
|
||||
id,
|
||||
{ isActive: before.isActive },
|
||||
{ isActive: updated.isActive },
|
||||
)
|
||||
|
||||
return updated
|
||||
}
|
||||
|
||||
export async function deleteMenuItem(id: string, admin: AdminActor) {
|
||||
const before = await loadMenuItemDetail(id)
|
||||
if (before.isRequired && admin.role !== 'SUPER_ADMIN') {
|
||||
throw new AppError('Required system items can only be deleted by a Super Admin.', 403, 'forbidden')
|
||||
}
|
||||
|
||||
await prisma.menuItem.delete({ where: { id } })
|
||||
await createAuditLog(admin, 'DELETE_MENU_ITEM', 'MenuItem', id, before, undefined)
|
||||
}
|
||||
|
||||
export async function assignMenuItemToPlans(
|
||||
id: string,
|
||||
assignments: Array<{ plan: Plan; displayOrder?: number; isActive?: boolean }>,
|
||||
admin: AdminActor,
|
||||
) {
|
||||
await prisma.menuItem.findUniqueOrThrow({ where: { id } })
|
||||
|
||||
const payload = assignments.map((assignment) => ({
|
||||
menuItemId: id,
|
||||
plan: toPlanValue(assignment.plan),
|
||||
displayOrder: assignment.displayOrder ?? 0,
|
||||
isActive: assignment.isActive ?? true,
|
||||
}))
|
||||
|
||||
await prisma.subscriptionMenuItem.deleteMany({
|
||||
where: { menuItemId: id, plan: { in: payload.map((assignment) => assignment.plan) } },
|
||||
})
|
||||
|
||||
if (payload.length > 0) {
|
||||
await prisma.subscriptionMenuItem.createMany({ data: payload })
|
||||
}
|
||||
|
||||
await createAuditLog(admin, 'ASSIGN_MENU_ITEM_TO_SUBSCRIPTIONS', 'MenuSubscriptionAssignment', id, undefined, payload)
|
||||
return loadMenuItemDetail(id)
|
||||
}
|
||||
|
||||
export async function removeMenuItemFromPlan(id: string, plan: Plan, admin: AdminActor) {
|
||||
await prisma.subscriptionMenuItem.deleteMany({
|
||||
where: {
|
||||
menuItemId: id,
|
||||
plan: toPlanValue(plan),
|
||||
},
|
||||
})
|
||||
|
||||
await createAuditLog(admin, 'REMOVE_MENU_ITEM_FROM_SUBSCRIPTION', 'MenuSubscriptionAssignment', id, { plan }, undefined)
|
||||
return loadMenuItemDetail(id)
|
||||
}
|
||||
|
||||
export async function assignMenuItemToCompanies(
|
||||
id: string,
|
||||
assignments: Array<{ companyId: string; displayOrder?: number; isActive?: boolean }>,
|
||||
admin: AdminActor,
|
||||
) {
|
||||
await prisma.menuItem.findUniqueOrThrow({ where: { id } })
|
||||
const companyIds = assignments.map((assignment) => assignment.companyId)
|
||||
const companies = await prisma.company.findMany({
|
||||
where: { id: { in: companyIds }, status: { not: 'CANCELLED' } },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (companies.length !== new Set(companyIds).size) {
|
||||
throw new AppError('Menu items can only be assigned to active companies.', 400, 'validation_error')
|
||||
}
|
||||
|
||||
await prisma.companyMenuItem.deleteMany({
|
||||
where: {
|
||||
menuItemId: id,
|
||||
companyId: { in: companyIds },
|
||||
},
|
||||
})
|
||||
|
||||
if (assignments.length > 0) {
|
||||
await prisma.companyMenuItem.createMany({
|
||||
data: assignments.map((assignment) => ({
|
||||
menuItemId: id,
|
||||
companyId: assignment.companyId,
|
||||
displayOrder: assignment.displayOrder ?? 0,
|
||||
isActive: assignment.isActive ?? true,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
await createAuditLog(admin, 'ASSIGN_MENU_ITEM_TO_COMPANIES', 'MenuCompanyAssignment', id, undefined, assignments)
|
||||
return loadMenuItemDetail(id)
|
||||
}
|
||||
|
||||
export async function removeMenuItemFromCompany(id: string, companyId: string, admin: AdminActor) {
|
||||
await prisma.companyMenuItem.deleteMany({
|
||||
where: { menuItemId: id, companyId },
|
||||
})
|
||||
|
||||
await createAuditLog(admin, 'REMOVE_MENU_ITEM_FROM_COMPANY', 'MenuCompanyAssignment', id, { companyId }, undefined)
|
||||
return loadMenuItemDetail(id)
|
||||
}
|
||||
|
||||
async function getMenuEvaluationContext(companyId: string, role: EmployeeRole, employeeIsActive = true) {
|
||||
const company = await prisma.company.findUniqueOrThrow({
|
||||
where: { id: companyId },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
subscription: {
|
||||
select: {
|
||||
plan: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const menuItems = await prisma.menuItem.findMany({
|
||||
include: {
|
||||
roleVisibilities: true,
|
||||
subscriptionAssignments: true,
|
||||
companyAssignments: {
|
||||
where: { companyId },
|
||||
},
|
||||
},
|
||||
orderBy: [{ displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
|
||||
const currentPlan = company.subscription?.plan ?? null
|
||||
const currentPlanName = currentPlan as Plan | null
|
||||
|
||||
const evaluated = menuItems.map((item) => {
|
||||
const defaultsToAllSubscriptions = item.subscriptionAssignments.length === 0
|
||||
const subscriptionAssignment = item.subscriptionAssignments.find(
|
||||
(assignment) => assignment.isActive && (!currentPlan || assignment.plan === currentPlan),
|
||||
)
|
||||
const companyAssignment = item.companyAssignments.find((assignment) => assignment.isActive)
|
||||
const roleAllowed = item.roleVisibilities.length === 0 || item.roleVisibilities.some((visibility) => visibility.role === role)
|
||||
const subscriptionEntitled = Boolean(subscriptionAssignment || (defaultsToAllSubscriptions && currentPlan))
|
||||
const entitled = Boolean(subscriptionEntitled || companyAssignment)
|
||||
const visible = Boolean(item.isActive && entitled && roleAllowed && employeeIsActive)
|
||||
const displayOrder = companyAssignment?.displayOrder ?? subscriptionAssignment?.displayOrder ?? item.displayOrder
|
||||
|
||||
const reasons: string[] = []
|
||||
if (!item.isActive) reasons.push('Hidden because the menu item is inactive.')
|
||||
if (!employeeIsActive) reasons.push('Hidden because the user account is inactive.')
|
||||
if (!entitled) reasons.push(describeEntitlement(currentPlanName, false, false, false))
|
||||
if (entitled) {
|
||||
reasons.push(
|
||||
describeEntitlement(
|
||||
currentPlanName,
|
||||
Boolean(subscriptionAssignment),
|
||||
Boolean(companyAssignment),
|
||||
Boolean(defaultsToAllSubscriptions && !companyAssignment),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (!roleAllowed) reasons.push(`Hidden because the ${role} role is not allowed to see this item.`)
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
systemKey: item.systemKey,
|
||||
label: item.label,
|
||||
itemType: item.itemType,
|
||||
routeOrUrl: item.routeOrUrl,
|
||||
icon: item.icon,
|
||||
parentId: item.parentId,
|
||||
openInNewTab: item.openInNewTab,
|
||||
isRequired: item.isRequired,
|
||||
isActive: item.isActive,
|
||||
displayOrder,
|
||||
source: companyAssignment ? 'company' : subscriptionEntitled ? 'subscription' : 'none',
|
||||
visible,
|
||||
reasons,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
company,
|
||||
role,
|
||||
currentPlan: currentPlanName,
|
||||
items: sortByDisplayOrder(evaluated),
|
||||
}
|
||||
}
|
||||
|
||||
function buildMenuTree(items: Array<{
|
||||
id: string
|
||||
systemKey: string | null
|
||||
label: string
|
||||
itemType: MenuItemType
|
||||
routeOrUrl: string | null
|
||||
icon: string | null
|
||||
parentId: string | null
|
||||
openInNewTab: boolean
|
||||
displayOrder: number
|
||||
}>) {
|
||||
const byId = new Map<string, any>()
|
||||
const roots: any[] = []
|
||||
|
||||
for (const item of items) {
|
||||
byId.set(item.id, {
|
||||
id: item.id,
|
||||
systemKey: item.systemKey,
|
||||
label: item.label,
|
||||
itemType: item.itemType,
|
||||
routeOrUrl: item.routeOrUrl,
|
||||
icon: item.icon,
|
||||
parentId: item.parentId,
|
||||
openInNewTab: item.openInNewTab,
|
||||
displayOrder: item.displayOrder,
|
||||
children: [],
|
||||
})
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
const node = byId.get(item.id)
|
||||
if (item.parentId && byId.has(item.parentId)) {
|
||||
byId.get(item.parentId).children.push(node)
|
||||
} else {
|
||||
roots.push(node)
|
||||
}
|
||||
}
|
||||
|
||||
const sortTree = (nodes: any[]) => {
|
||||
nodes.sort((a, b) => {
|
||||
if (a.displayOrder !== b.displayOrder) return a.displayOrder - b.displayOrder
|
||||
return a.label.localeCompare(b.label)
|
||||
})
|
||||
nodes.forEach((node) => sortTree(node.children))
|
||||
}
|
||||
|
||||
sortTree(roots)
|
||||
return roots
|
||||
}
|
||||
|
||||
export async function previewCompanyMenu(input: MenuPreviewInput) {
|
||||
const context = await getMenuEvaluationContext(input.companyId, input.role)
|
||||
return {
|
||||
company: context.company,
|
||||
role: context.role,
|
||||
subscriptionPlan: context.currentPlan,
|
||||
items: context.items,
|
||||
finalMenu: buildMenuTree(
|
||||
context.items
|
||||
.filter((item) => item.visible)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
systemKey: item.systemKey,
|
||||
label: item.label,
|
||||
itemType: item.itemType,
|
||||
routeOrUrl: item.routeOrUrl,
|
||||
icon: item.icon,
|
||||
parentId: item.parentId,
|
||||
openInNewTab: item.openInNewTab,
|
||||
displayOrder: item.displayOrder,
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEmployeeMenu(employeeId: string) {
|
||||
const employee = await prisma.employee.findUniqueOrThrow({
|
||||
where: { id: employeeId },
|
||||
select: {
|
||||
id: true,
|
||||
role: true,
|
||||
isActive: true,
|
||||
companyId: true,
|
||||
},
|
||||
})
|
||||
|
||||
const context = await getMenuEvaluationContext(employee.companyId, employee.role, employee.isActive)
|
||||
const visibleItems = context.items.filter((item) => item.visible)
|
||||
|
||||
return {
|
||||
companyId: employee.companyId,
|
||||
role: employee.role,
|
||||
subscriptionPlan: context.currentPlan,
|
||||
items: buildMenuTree(
|
||||
visibleItems.map((item) => ({
|
||||
id: item.id,
|
||||
systemKey: item.systemKey,
|
||||
label: item.label,
|
||||
itemType: item.itemType,
|
||||
routeOrUrl: item.routeOrUrl,
|
||||
icon: item.icon,
|
||||
parentId: item.parentId,
|
||||
openInNewTab: item.openInNewTab,
|
||||
displayOrder: item.displayOrder,
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export async function listMenuAuditLogs(query: MenuAuditQuery) {
|
||||
const where = {
|
||||
resource: {
|
||||
in: MENU_AUDIT_RESOURCES,
|
||||
},
|
||||
} as const
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
prisma.auditLog.findMany({
|
||||
where,
|
||||
include: { adminUser: { select: { firstName: true, lastName: true, email: true } } },
|
||||
skip: (query.page - 1) * query.pageSize,
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
prisma.auditLog.count({ where }),
|
||||
])
|
||||
|
||||
return {
|
||||
data,
|
||||
total,
|
||||
page: query.page,
|
||||
pageSize: query.pageSize,
|
||||
totalPages: Math.ceil(total / query.pageSize),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user