redone admin

added branches
This commit is contained in:
2026-03-25 14:59:44 +01:00
parent 809a37a410
commit c29494dc0d
26 changed files with 1578 additions and 904 deletions

View File

@@ -9,6 +9,7 @@ import {
authRolePermissions,
} from "../../../db/schema"
import { eq, and, or, isNull } from "drizzle-orm"
import { enrichProfilesWithBranches } from "../../utils/profileBranches"
export default async function meRoutes(server: FastifyInstance) {
server.get("/me", async (req, reply) => {
@@ -89,7 +90,8 @@ export default async function meRoutes(server: FastifyInstance) {
)
.limit(1)
profile = profileResult?.[0] ?? null
const enrichedProfiles = await enrichProfilesWithBranches(server, profileResult)
profile = enrichedProfiles?.[0] ?? null
}
// ----------------------------------------------------

View File

@@ -8,6 +8,7 @@ import {
} from "../../../db/schema"
import {and, eq, inArray} from "drizzle-orm"
import { enrichProfilesWithBranches } from "../../utils/profileBranches"
export default async function tenantRoutesInternal(server: FastifyInstance) {
@@ -53,7 +54,7 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
.where(inArray(authUsers.id, userIds))
// 3) auth_profiles pro Tenant laden
const profiles = await server.db
const profileRows = await server.db
.select()
.from(authProfiles)
.where(
@@ -61,6 +62,7 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
eq(authProfiles.tenant_id, tenantId),
inArray(authProfiles.user_id, userIds)
))
const profiles = await enrichProfilesWithBranches(server, profileRows)
const combined = users.map(u => {
const profile = profiles.find(p => p.user_id === u.id)
@@ -91,12 +93,12 @@ export default async function tenantRoutesInternal(server: FastifyInstance) {
const tenantId = req.params.id
if (!tenantId) return reply.code(401).send({ error: "Unauthorized" })
const data = await server.db
const profileRows = await server.db
.select()
.from(authProfiles)
.where(eq(authProfiles.tenant_id, tenantId))
return data
return await enrichProfilesWithBranches(server, profileRows)
} catch (err) {
console.error("/tenant/profiles ERROR:", err)

View File

@@ -4,6 +4,11 @@ import { eq, and } from "drizzle-orm";
import {
authProfiles,
} from "../../db/schema";
import {
loadProfileWithBranches,
resolveTenantBranchIds,
syncProfileBranches,
} from "../utils/profileBranches";
export default async function authProfilesRoutes(server: FastifyInstance) {
@@ -19,22 +24,13 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
return reply.code(400).send({ error: "No tenant selected" });
}
const rows = await server.db
.select()
.from(authProfiles)
.where(
and(
eq(authProfiles.id, id),
eq(authProfiles.tenant_id, tenantId)
)
)
.limit(1);
const profile = await loadProfileWithBranches(server, id, tenantId)
if (!rows.length) {
if (!profile) {
return reply.code(404).send({ error: "User not found or not in tenant" });
}
return rows[0];
return profile;
} catch (error) {
console.error("GET /profiles/:id ERROR:", error);
@@ -48,7 +44,8 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
// ❌ Systemfelder entfernen
const forbidden = [
"id", "user_id", "tenant_id", "created_at", "updated_at",
"updatedAt", "updatedBy", "old_profile_id", "full_name"
"updatedAt", "updatedBy", "old_profile_id", "full_name",
"branch", "branches", "branch_ids"
]
forbidden.forEach(f => delete cleaned[f])
@@ -89,8 +86,19 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
// Clean + Normalize
body = sanitizeProfileUpdate(body)
const { primaryBranchId, branchIds } = await resolveTenantBranchIds(
server,
tenantId,
[
...(Array.isArray(body.branch_ids) ? body.branch_ids : []),
...(Array.isArray(body.branches) ? body.branches : []),
],
body.branch_id ?? body.branch?.id ?? null
)
const updateData = {
...body,
branch_id: primaryBranchId,
updatedAt: new Date(),
updatedBy: userId
}
@@ -110,10 +118,16 @@ export default async function authProfilesRoutes(server: FastifyInstance) {
return reply.code(404).send({ error: "User not found or not in tenant" })
}
return updated[0]
await syncProfileBranches(server, id, branchIds, userId)
const profile = await loadProfileWithBranches(server, id, tenantId)
return profile || updated[0]
} catch (err) {
console.error("PUT /profiles/:id ERROR:", err)
if (err instanceof Error && ["INVALID_BRANCH_SELECTION", "INVALID_PRIMARY_BRANCH"].includes(err.message)) {
return reply.code(400).send({ error: "Ungültige Niederlassungsauswahl" })
}
return reply.code(500).send({ error: "Internal Server Error" })
}
})

View File

@@ -12,6 +12,7 @@ import {
} from "../../db/schema"
import {and, desc, eq, inArray} from "drizzle-orm"
import { enrichProfilesWithBranches } from "../utils/profileBranches"
export default async function tenantRoutes(server: FastifyInstance) {
@@ -123,7 +124,7 @@ export default async function tenantRoutes(server: FastifyInstance) {
.where(inArray(authUsers.id, userIds))
// 3) auth_profiles pro Tenant laden
const profiles = await server.db
const profileRows = await server.db
.select()
.from(authProfiles)
.where(
@@ -131,6 +132,7 @@ export default async function tenantRoutes(server: FastifyInstance) {
eq(authProfiles.tenant_id, tenantId),
inArray(authProfiles.user_id, userIds)
))
const profiles = await enrichProfilesWithBranches(server, profileRows)
const combined = users.map(u => {
const profile = profiles.find(p => p.user_id === u.id)
@@ -160,11 +162,12 @@ export default async function tenantRoutes(server: FastifyInstance) {
const tenantId = req.user?.tenant_id
if (!tenantId) return reply.code(401).send({ error: "Unauthorized" })
const data = await server.db
const profileRows = await server.db
.select()
.from(authProfiles)
.where(eq(authProfiles.tenant_id, tenantId))
const data = await enrichProfilesWithBranches(server, profileRows)
return { data }
} catch (err) {

View File

@@ -0,0 +1,142 @@
import { and, eq, inArray } from "drizzle-orm"
import { FastifyInstance } from "fastify"
import { authProfileBranches, authProfiles, branches } from "../../db/schema"
function normalizeBranchIds(values: any[]): number[] {
return [...new Set(
values
.map((value) => {
if (typeof value === "number") return value
if (typeof value === "string" && value.trim()) return Number(value)
if (value && typeof value === "object" && "id" in value) return Number(value.id)
return NaN
})
.filter((value) => Number.isFinite(value))
)]
}
export async function enrichProfilesWithBranches(server: FastifyInstance, profiles: any[]) {
if (!profiles.length) return profiles
const profileIds = profiles.map((profile) => profile.id).filter(Boolean)
if (!profileIds.length) return profiles
const profileBranchRows = await server.db
.select()
.from(authProfileBranches)
.where(inArray(authProfileBranches.profile_id, profileIds))
const branchIds = [...new Set(profileBranchRows.map((row) => row.branch_id).filter(Boolean))]
const branchRows = branchIds.length
? await server.db.select().from(branches).where(inArray(branches.id, branchIds))
: []
const branchMap = new Map(branchRows.map((branch) => [branch.id, branch]))
const branchIdsByProfile = new Map<string, number[]>()
for (const row of profileBranchRows) {
const current = branchIdsByProfile.get(row.profile_id) || []
current.push(row.branch_id)
branchIdsByProfile.set(row.profile_id, current)
}
return profiles.map((profile) => {
const assignedBranchIds = [...new Set(branchIdsByProfile.get(profile.id) || [])]
return {
...profile,
branch: profile.branch_id ? branchMap.get(profile.branch_id) || null : null,
branches: assignedBranchIds
.map((branchId) => branchMap.get(branchId))
.filter(Boolean),
branch_ids: assignedBranchIds,
}
})
}
export async function loadProfileWithBranches(server: FastifyInstance, profileId: string, tenantId: number) {
const rows = await server.db
.select()
.from(authProfiles)
.where(
and(
eq(authProfiles.id, profileId),
eq(authProfiles.tenant_id, tenantId)
)
)
.limit(1)
if (!rows.length) return null
const [profile] = await enrichProfilesWithBranches(server, rows)
return profile
}
export async function resolveTenantBranchIds(
server: FastifyInstance,
tenantId: number,
values: any[],
primaryBranchId?: any
) {
const normalizedPrimaryBranchId = primaryBranchId == null || primaryBranchId === ""
? null
: Number(primaryBranchId)
const requestedBranchIds = normalizeBranchIds([
...values,
normalizedPrimaryBranchId,
])
if (!requestedBranchIds.length) {
return {
primaryBranchId: normalizedPrimaryBranchId,
branchIds: [],
}
}
const validBranches = await server.db
.select({ id: branches.id })
.from(branches)
.where(
and(
eq(branches.tenant, tenantId),
inArray(branches.id, requestedBranchIds)
)
)
const validBranchIds = validBranches.map((branch) => branch.id)
if (validBranchIds.length !== requestedBranchIds.length) {
throw new Error("INVALID_BRANCH_SELECTION")
}
if (normalizedPrimaryBranchId != null && !validBranchIds.includes(normalizedPrimaryBranchId)) {
throw new Error("INVALID_PRIMARY_BRANCH")
}
return {
primaryBranchId: normalizedPrimaryBranchId,
branchIds: validBranchIds,
}
}
export async function syncProfileBranches(
server: FastifyInstance,
profileId: string,
branchIds: number[],
userId?: string | null
) {
await server.db
.delete(authProfileBranches)
.where(eq(authProfileBranches.profile_id, profileId))
if (!branchIds.length) return
await server.db
.insert(authProfileBranches)
.values(branchIds.map((branchId) => ({
profile_id: profileId,
branch_id: branchId,
created_by: userId || null,
})))
}

View File

@@ -4,6 +4,7 @@ import {
bankaccounts,
bankrequisitions,
bankstatements,
branches,
entitybankaccounts,
events,
contacts,
@@ -162,7 +163,12 @@ export const resourceConfig = {
costcentres: {
table: costcentres,
searchColumns: ["name","number","description"],
mtoLoad: ["vehicle","project","inventoryitem"],
mtoLoad: ["vehicle","project","inventoryitem","branch"],
numberRangeHolder: "number",
},
branches: {
table: branches,
searchColumns: ["name","number","description"],
numberRangeHolder: "number",
},
tasks: {