refactor(api): extract org unit router support
This commit is contained in:
@@ -0,0 +1,121 @@
|
|||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import {
|
||||||
|
assertOrgUnitParentLevel,
|
||||||
|
buildOrgUnitCreateData,
|
||||||
|
buildOrgUnitListWhere,
|
||||||
|
buildOrgUnitTree,
|
||||||
|
buildOrgUnitUpdateData,
|
||||||
|
findOrgUnitByIdentifier,
|
||||||
|
} from "../router/org-unit-support.js";
|
||||||
|
|
||||||
|
describe("org-unit support", () => {
|
||||||
|
it("builds list filters", () => {
|
||||||
|
expect(buildOrgUnitListWhere({
|
||||||
|
level: 5,
|
||||||
|
parentId: "root",
|
||||||
|
isActive: true,
|
||||||
|
})).toEqual({
|
||||||
|
level: 5,
|
||||||
|
parentId: "root",
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds a sorted org-unit tree", () => {
|
||||||
|
expect(buildOrgUnitTree([
|
||||||
|
{
|
||||||
|
id: "child_b",
|
||||||
|
name: "Beta",
|
||||||
|
shortName: "BET",
|
||||||
|
level: 6,
|
||||||
|
parentId: "root",
|
||||||
|
sortOrder: 20,
|
||||||
|
isActive: true,
|
||||||
|
createdAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
updatedAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "root",
|
||||||
|
name: "Delivery",
|
||||||
|
shortName: "DEL",
|
||||||
|
level: 5,
|
||||||
|
parentId: null,
|
||||||
|
sortOrder: 10,
|
||||||
|
isActive: true,
|
||||||
|
createdAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
updatedAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "child_a",
|
||||||
|
name: "Alpha",
|
||||||
|
shortName: "ALP",
|
||||||
|
level: 6,
|
||||||
|
parentId: "root",
|
||||||
|
sortOrder: 20,
|
||||||
|
isActive: true,
|
||||||
|
createdAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
updatedAt: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
},
|
||||||
|
])).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
id: "root",
|
||||||
|
children: [
|
||||||
|
expect.objectContaining({ id: "child_a", children: [] }),
|
||||||
|
expect.objectContaining({ id: "child_b", children: [] }),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves org units by short name fallback", async () => {
|
||||||
|
const db = {
|
||||||
|
orgUnit: {
|
||||||
|
findUnique: vi.fn().mockResolvedValue(null),
|
||||||
|
findFirst: vi.fn()
|
||||||
|
.mockResolvedValueOnce(null)
|
||||||
|
.mockResolvedValueOnce({ id: "ou_1", shortName: "DEL" }),
|
||||||
|
},
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
const result = await findOrgUnitByIdentifier<{ id: string; shortName: string }>(
|
||||||
|
db,
|
||||||
|
" del ",
|
||||||
|
{ select: { id: true, shortName: true } },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ id: "ou_1", shortName: "DEL" });
|
||||||
|
expect(db.orgUnit.findFirst).toHaveBeenNthCalledWith(2, {
|
||||||
|
where: { shortName: { equals: "del", mode: "insensitive" } },
|
||||||
|
select: { id: true, shortName: true },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects invalid parent/child level combinations", () => {
|
||||||
|
expect(() => assertOrgUnitParentLevel({ level: 6 }, 6)).toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds create and sparse update payloads", () => {
|
||||||
|
expect(buildOrgUnitCreateData({
|
||||||
|
name: "Delivery",
|
||||||
|
shortName: "DEL",
|
||||||
|
level: 5,
|
||||||
|
parentId: "root",
|
||||||
|
sortOrder: 10,
|
||||||
|
})).toEqual({
|
||||||
|
name: "Delivery",
|
||||||
|
shortName: "DEL",
|
||||||
|
level: 5,
|
||||||
|
parentId: "root",
|
||||||
|
sortOrder: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(buildOrgUnitUpdateData({
|
||||||
|
shortName: null,
|
||||||
|
isActive: false,
|
||||||
|
})).toEqual({
|
||||||
|
shortName: null,
|
||||||
|
isActive: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import type { Prisma, PrismaClient } from "@capakraken/db";
|
||||||
|
import { CreateOrgUnitSchema, UpdateOrgUnitSchema, type OrgUnitTree } from "@capakraken/shared";
|
||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
type OrgUnitDb = Pick<PrismaClient, "orgUnit">;
|
||||||
|
|
||||||
|
type OrgUnitListInput = {
|
||||||
|
level?: number | undefined;
|
||||||
|
parentId?: string | undefined;
|
||||||
|
isActive?: boolean | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OrgUnitTreeNode = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
shortName: string | null;
|
||||||
|
level: number;
|
||||||
|
parentId: string | null;
|
||||||
|
sortOrder: number;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ParentOrgUnitRecord = {
|
||||||
|
level: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CreateOrgUnitInput = z.infer<typeof CreateOrgUnitSchema>;
|
||||||
|
type UpdateOrgUnitInput = z.infer<typeof UpdateOrgUnitSchema>;
|
||||||
|
|
||||||
|
export function buildOrgUnitListWhere(
|
||||||
|
input: OrgUnitListInput,
|
||||||
|
): Prisma.OrgUnitWhereInput {
|
||||||
|
return {
|
||||||
|
...(input.level !== undefined ? { level: input.level } : {}),
|
||||||
|
...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
|
||||||
|
...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOrgUnitTree(
|
||||||
|
flatItems: OrgUnitTreeNode[],
|
||||||
|
parentId: string | null = null,
|
||||||
|
): OrgUnitTree[] {
|
||||||
|
return flatItems
|
||||||
|
.filter((item) => item.parentId === parentId)
|
||||||
|
.sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))
|
||||||
|
.map((item) => ({
|
||||||
|
...item,
|
||||||
|
children: buildOrgUnitTree(flatItems, item.id),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findOrgUnitByIdentifier<TOrgUnit>(
|
||||||
|
db: OrgUnitDb,
|
||||||
|
identifier: string,
|
||||||
|
extraArgs: Record<string, unknown>,
|
||||||
|
): Promise<TOrgUnit> {
|
||||||
|
const normalizedIdentifier = identifier.trim();
|
||||||
|
|
||||||
|
let unit = await db.orgUnit.findUnique({
|
||||||
|
where: { id: normalizedIdentifier },
|
||||||
|
...extraArgs,
|
||||||
|
}) as TOrgUnit | null;
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
unit = await db.orgUnit.findFirst({
|
||||||
|
where: { name: { equals: normalizedIdentifier, mode: "insensitive" } },
|
||||||
|
...extraArgs,
|
||||||
|
}) as TOrgUnit | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
unit = await db.orgUnit.findFirst({
|
||||||
|
where: { shortName: { equals: normalizedIdentifier, mode: "insensitive" } },
|
||||||
|
...extraArgs,
|
||||||
|
}) as TOrgUnit | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
unit = await db.orgUnit.findFirst({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ name: { contains: normalizedIdentifier, mode: "insensitive" } },
|
||||||
|
{ shortName: { contains: normalizedIdentifier, mode: "insensitive" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
...extraArgs,
|
||||||
|
}) as TOrgUnit | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!unit) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "NOT_FOUND",
|
||||||
|
message: `Org unit not found: ${normalizedIdentifier}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertOrgUnitParentLevel(
|
||||||
|
parent: ParentOrgUnitRecord,
|
||||||
|
childLevel: number,
|
||||||
|
): void {
|
||||||
|
if (parent.level >= childLevel) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: "BAD_REQUEST",
|
||||||
|
message: `Child level (${childLevel}) must be greater than parent level (${parent.level})`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOrgUnitCreateData(
|
||||||
|
input: CreateOrgUnitInput,
|
||||||
|
): Prisma.OrgUnitUncheckedCreateInput {
|
||||||
|
return {
|
||||||
|
name: input.name,
|
||||||
|
...(input.shortName !== undefined ? { shortName: input.shortName } : {}),
|
||||||
|
level: input.level,
|
||||||
|
...(input.parentId ? { parentId: input.parentId } : {}),
|
||||||
|
sortOrder: input.sortOrder,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOrgUnitUpdateData(
|
||||||
|
input: UpdateOrgUnitInput,
|
||||||
|
): Prisma.OrgUnitUncheckedUpdateInput {
|
||||||
|
return {
|
||||||
|
...(input.name !== undefined ? { name: input.name } : {}),
|
||||||
|
...(input.shortName !== undefined ? { shortName: input.shortName } : {}),
|
||||||
|
...(input.sortOrder !== undefined ? { sortOrder: input.sortOrder } : {}),
|
||||||
|
...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
|
||||||
|
...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { CreateOrgUnitSchema, UpdateOrgUnitSchema } from "@capakraken/shared";
|
import { CreateOrgUnitSchema, UpdateOrgUnitSchema } from "@capakraken/shared";
|
||||||
import { TRPCError } from "@trpc/server";
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||||
import { createAuditEntry } from "../lib/audit.js";
|
import { createAuditEntry } from "../lib/audit.js";
|
||||||
@@ -9,30 +8,30 @@ import {
|
|||||||
protectedProcedure,
|
protectedProcedure,
|
||||||
resourceOverviewProcedure,
|
resourceOverviewProcedure,
|
||||||
} from "../trpc.js";
|
} from "../trpc.js";
|
||||||
|
import {
|
||||||
|
assertOrgUnitParentLevel,
|
||||||
|
buildOrgUnitCreateData,
|
||||||
|
buildOrgUnitListWhere,
|
||||||
|
buildOrgUnitTree,
|
||||||
|
buildOrgUnitUpdateData,
|
||||||
|
findOrgUnitByIdentifier,
|
||||||
|
} from "./org-unit-support.js";
|
||||||
|
|
||||||
import type { OrgUnitTree } from "@capakraken/shared";
|
type OrgUnitIdentifierReadModel = {
|
||||||
|
|
||||||
interface FlatOrgUnit {
|
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
shortName: string | null;
|
shortName: string | null;
|
||||||
level: number;
|
level: number;
|
||||||
|
isActive: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OrgUnitDetailReadModel = OrgUnitIdentifierReadModel & {
|
||||||
parentId: string | null;
|
parentId: string | null;
|
||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
isActive: boolean;
|
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
_count: { resources: number };
|
||||||
|
};
|
||||||
function buildTree(flatItems: FlatOrgUnit[], parentId: string | null = null): OrgUnitTree[] {
|
|
||||||
return flatItems
|
|
||||||
.filter((item) => item.parentId === parentId)
|
|
||||||
.sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))
|
|
||||||
.map((item) => ({
|
|
||||||
...item,
|
|
||||||
children: buildTree(flatItems, item.id),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export const orgUnitRouter = createTRPCRouter({
|
export const orgUnitRouter = createTRPCRouter({
|
||||||
list: resourceOverviewProcedure
|
list: resourceOverviewProcedure
|
||||||
@@ -45,11 +44,7 @@ export const orgUnitRouter = createTRPCRouter({
|
|||||||
)
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
return ctx.db.orgUnit.findMany({
|
return ctx.db.orgUnit.findMany({
|
||||||
where: {
|
where: buildOrgUnitListWhere(input ?? {}),
|
||||||
...(input?.level !== undefined ? { level: input.level } : {}),
|
|
||||||
...(input?.parentId !== undefined ? { parentId: input.parentId } : {}),
|
|
||||||
...(input?.isActive !== undefined ? { isActive: input.isActive } : {}),
|
|
||||||
},
|
|
||||||
orderBy: [{ level: "asc" }, { sortOrder: "asc" }, { name: "asc" }],
|
orderBy: [{ level: "asc" }, { sortOrder: "asc" }, { name: "asc" }],
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -58,12 +53,10 @@ export const orgUnitRouter = createTRPCRouter({
|
|||||||
.input(z.object({ isActive: z.boolean().optional() }).optional())
|
.input(z.object({ isActive: z.boolean().optional() }).optional())
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const all = await ctx.db.orgUnit.findMany({
|
const all = await ctx.db.orgUnit.findMany({
|
||||||
where: {
|
where: buildOrgUnitListWhere({ isActive: input?.isActive }),
|
||||||
...(input?.isActive !== undefined ? { isActive: input.isActive } : {}),
|
|
||||||
},
|
|
||||||
orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
|
orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
|
||||||
});
|
});
|
||||||
return buildTree(all);
|
return buildOrgUnitTree(all);
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getById: resourceOverviewProcedure
|
getById: resourceOverviewProcedure
|
||||||
@@ -86,93 +79,23 @@ export const orgUnitRouter = createTRPCRouter({
|
|||||||
resolveByIdentifier: protectedProcedure
|
resolveByIdentifier: protectedProcedure
|
||||||
.input(z.object({ identifier: z.string().trim().min(1) }))
|
.input(z.object({ identifier: z.string().trim().min(1) }))
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const identifier = input.identifier.trim();
|
return findOrgUnitByIdentifier<OrgUnitIdentifierReadModel>(ctx.db, input.identifier, {
|
||||||
const select = {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
shortName: true,
|
shortName: true,
|
||||||
level: true,
|
level: true,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
} as const;
|
|
||||||
|
|
||||||
let unit = await ctx.db.orgUnit.findUnique({
|
|
||||||
where: { id: identifier },
|
|
||||||
select,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: { name: { equals: identifier, mode: "insensitive" } },
|
|
||||||
select,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: { shortName: { equals: identifier, mode: "insensitive" } },
|
|
||||||
select,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: {
|
|
||||||
OR: [
|
|
||||||
{ name: { contains: identifier, mode: "insensitive" } },
|
|
||||||
{ shortName: { contains: identifier, mode: "insensitive" } },
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
select,
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
throw new TRPCError({ code: "NOT_FOUND", message: `Org unit not found: ${identifier}` });
|
|
||||||
}
|
|
||||||
|
|
||||||
return unit;
|
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getByIdentifier: resourceOverviewProcedure
|
getByIdentifier: resourceOverviewProcedure
|
||||||
.input(z.object({ identifier: z.string().trim().min(1) }))
|
.input(z.object({ identifier: z.string().trim().min(1) }))
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const identifier = input.identifier.trim();
|
return findOrgUnitByIdentifier<OrgUnitDetailReadModel>(ctx.db, input.identifier, {
|
||||||
let unit = await ctx.db.orgUnit.findUnique({
|
|
||||||
where: { id: identifier },
|
|
||||||
include: { _count: { select: { resources: true } } },
|
include: { _count: { select: { resources: true } } },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: { name: { equals: identifier, mode: "insensitive" } },
|
|
||||||
include: { _count: { select: { resources: true } } },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: { shortName: { equals: identifier, mode: "insensitive" } },
|
|
||||||
include: { _count: { select: { resources: true } } },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
unit = await ctx.db.orgUnit.findFirst({
|
|
||||||
where: {
|
|
||||||
OR: [
|
|
||||||
{ name: { contains: identifier, mode: "insensitive" } },
|
|
||||||
{ shortName: { contains: identifier, mode: "insensitive" } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
include: { _count: { select: { resources: true } } },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
throw new TRPCError({ code: "NOT_FOUND", message: `Org unit not found: ${identifier}` });
|
|
||||||
}
|
|
||||||
|
|
||||||
return unit;
|
|
||||||
}),
|
}),
|
||||||
|
|
||||||
create: adminProcedure
|
create: adminProcedure
|
||||||
@@ -183,22 +106,11 @@ export const orgUnitRouter = createTRPCRouter({
|
|||||||
ctx.db.orgUnit.findUnique({ where: { id: input.parentId } }),
|
ctx.db.orgUnit.findUnique({ where: { id: input.parentId } }),
|
||||||
"Parent org unit",
|
"Parent org unit",
|
||||||
);
|
);
|
||||||
if (parent.level >= input.level) {
|
assertOrgUnitParentLevel(parent, input.level);
|
||||||
throw new TRPCError({
|
|
||||||
code: "BAD_REQUEST",
|
|
||||||
message: `Child level (${input.level}) must be greater than parent level (${parent.level})`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const created = await ctx.db.orgUnit.create({
|
const created = await ctx.db.orgUnit.create({
|
||||||
data: {
|
data: buildOrgUnitCreateData(input),
|
||||||
name: input.name,
|
|
||||||
...(input.shortName !== undefined ? { shortName: input.shortName } : {}),
|
|
||||||
level: input.level,
|
|
||||||
...(input.parentId ? { parentId: input.parentId } : {}),
|
|
||||||
sortOrder: input.sortOrder,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
void createAuditEntry({
|
void createAuditEntry({
|
||||||
@@ -227,13 +139,7 @@ export const orgUnitRouter = createTRPCRouter({
|
|||||||
|
|
||||||
const updated = await ctx.db.orgUnit.update({
|
const updated = await ctx.db.orgUnit.update({
|
||||||
where: { id: input.id },
|
where: { id: input.id },
|
||||||
data: {
|
data: buildOrgUnitUpdateData(input.data),
|
||||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
|
||||||
...(input.data.shortName !== undefined ? { shortName: input.data.shortName } : {}),
|
|
||||||
...(input.data.sortOrder !== undefined ? { sortOrder: input.data.sortOrder } : {}),
|
|
||||||
...(input.data.isActive !== undefined ? { isActive: input.data.isActive } : {}),
|
|
||||||
...(input.data.parentId !== undefined ? { parentId: input.data.parentId } : {}),
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
void createAuditEntry({
|
void createAuditEntry({
|
||||||
|
|||||||
Reference in New Issue
Block a user