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

@@ -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" })
}
})