redone admin
added branches
This commit is contained in:
37
backend/db/migrations/0024_tenant_branches.sql
Normal file
37
backend/db/migrations/0024_tenant_branches.sql
Normal file
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE "branches" (
|
||||
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"tenant" bigint NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"number" text,
|
||||
"description" text,
|
||||
"archived" boolean DEFAULT false NOT NULL,
|
||||
"updated_at" timestamp with time zone,
|
||||
"updated_by" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "branches" ADD CONSTRAINT "branches_tenant_tenants_id_fk" FOREIGN KEY ("tenant") REFERENCES "public"."tenants"("id") ON DELETE no action ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "branches" ADD CONSTRAINT "branches_updated_by_auth_users_id_fk" FOREIGN KEY ("updated_by") REFERENCES "public"."auth_users"("id") ON DELETE no action ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "costcentres" ADD COLUMN "branch" bigint;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "costcentres" ADD CONSTRAINT "costcentres_branch_branches_id_fk" FOREIGN KEY ("branch") REFERENCES "public"."branches"("id") ON DELETE no action ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profiles" ADD COLUMN "branch_id" bigint;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profiles" ADD CONSTRAINT "auth_profiles_branch_id_branches_id_fk" FOREIGN KEY ("branch_id") REFERENCES "public"."branches"("id") ON DELETE no action ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "auth_profile_branches" (
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"profile_id" uuid NOT NULL,
|
||||
"branch_id" bigint NOT NULL,
|
||||
"created_by" uuid,
|
||||
CONSTRAINT "auth_profile_branches_profile_id_branch_id_pk" PRIMARY KEY("profile_id","branch_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profile_branches" ADD CONSTRAINT "auth_profile_branches_profile_id_auth_profiles_id_fk" FOREIGN KEY ("profile_id") REFERENCES "public"."auth_profiles"("id") ON DELETE cascade ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profile_branches" ADD CONSTRAINT "auth_profile_branches_branch_id_branches_id_fk" FOREIGN KEY ("branch_id") REFERENCES "public"."branches"("id") ON DELETE cascade ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "auth_profile_branches" ADD CONSTRAINT "auth_profile_branches_created_by_auth_users_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."auth_users"("id") ON DELETE no action ON UPDATE no action;
|
||||
@@ -162,6 +162,13 @@
|
||||
"when": 1774080000000,
|
||||
"tag": "0023_tax_evaluation_period",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 23,
|
||||
"version": "7",
|
||||
"when": 1774393200000,
|
||||
"tag": "0024_tenant_branches",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
30
backend/db/schema/auth_profile_branches.ts
Normal file
30
backend/db/schema/auth_profile_branches.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { pgTable, uuid, bigint, timestamp } from "drizzle-orm/pg-core"
|
||||
|
||||
import { authProfiles } from "./auth_profiles"
|
||||
import { branches } from "./branches"
|
||||
import { authUsers } from "./auth_users"
|
||||
|
||||
export const authProfileBranches = pgTable(
|
||||
"auth_profile_branches",
|
||||
{
|
||||
created_at: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
|
||||
profile_id: uuid("profile_id")
|
||||
.notNull()
|
||||
.references(() => authProfiles.id, { onDelete: "cascade" }),
|
||||
|
||||
branch_id: bigint("branch_id", { mode: "number" })
|
||||
.notNull()
|
||||
.references(() => branches.id, { onDelete: "cascade" }),
|
||||
|
||||
created_by: uuid("created_by").references(() => authUsers.id),
|
||||
},
|
||||
(table) => ({
|
||||
primaryKey: [table.profile_id, table.branch_id],
|
||||
})
|
||||
)
|
||||
|
||||
export type AuthProfileBranch = typeof authProfileBranches.$inferSelect
|
||||
export type NewAuthProfileBranch = typeof authProfileBranches.$inferInsert
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
jsonb,
|
||||
} from "drizzle-orm/pg-core"
|
||||
import { authUsers } from "./auth_users"
|
||||
import { branches } from "./branches"
|
||||
|
||||
export const authProfiles = pgTable("auth_profiles", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
@@ -18,6 +19,8 @@ export const authProfiles = pgTable("auth_profiles", {
|
||||
|
||||
tenant_id: bigint("tenant_id", { mode: "number" }).notNull(),
|
||||
|
||||
branch_id: bigint("branch_id", { mode: "number" }).references(() => branches.id),
|
||||
|
||||
created_at: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
|
||||
37
backend/db/schema/branches.ts
Normal file
37
backend/db/schema/branches.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
pgTable,
|
||||
bigint,
|
||||
timestamp,
|
||||
text,
|
||||
boolean,
|
||||
uuid,
|
||||
} from "drizzle-orm/pg-core"
|
||||
|
||||
import { tenants } from "./tenants"
|
||||
import { authUsers } from "./auth_users"
|
||||
|
||||
export const branches = pgTable("branches", {
|
||||
id: bigint("id", { mode: "number" })
|
||||
.primaryKey()
|
||||
.generatedByDefaultAsIdentity(),
|
||||
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
|
||||
tenant: bigint("tenant", { mode: "number" })
|
||||
.notNull()
|
||||
.references(() => tenants.id),
|
||||
|
||||
name: text("name").notNull(),
|
||||
number: text("number"),
|
||||
description: text("description"),
|
||||
|
||||
archived: boolean("archived").notNull().default(false),
|
||||
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }),
|
||||
updatedBy: uuid("updated_by").references(() => authUsers.id),
|
||||
})
|
||||
|
||||
export type Branch = typeof branches.$inferSelect
|
||||
export type NewBranch = typeof branches.$inferInsert
|
||||
@@ -13,6 +13,7 @@ import { inventoryitems } from "./inventoryitems"
|
||||
import { projects } from "./projects"
|
||||
import { vehicles } from "./vehicles"
|
||||
import { authUsers } from "./auth_users"
|
||||
import { branches } from "./branches"
|
||||
|
||||
export const costcentres = pgTable("costcentres", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
@@ -32,6 +33,8 @@ export const costcentres = pgTable("costcentres", {
|
||||
|
||||
project: bigint("project", { mode: "number" }).references(() => projects.id),
|
||||
|
||||
branch: bigint("branch", { mode: "number" }).references(() => branches.id),
|
||||
|
||||
inventoryitem: bigint("inventoryitem", { mode: "number" }).references(
|
||||
() => inventoryitems.id
|
||||
),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from "./accounts"
|
||||
export * from "./auth_profiles"
|
||||
export * from "./auth_profile_branches"
|
||||
export * from "./auth_role_permisssions"
|
||||
export * from "./auth_roles"
|
||||
export * from "./auth_tenant_users"
|
||||
@@ -8,6 +9,7 @@ export * from "./auth_users"
|
||||
export * from "./bankaccounts"
|
||||
export * from "./bankrequisitions"
|
||||
export * from "./bankstatements"
|
||||
export * from "./branches"
|
||||
export * from "./checkexecutions"
|
||||
export * from "./checks"
|
||||
export * from "./citys"
|
||||
|
||||
@@ -92,6 +92,7 @@ export const tenants = pgTable(
|
||||
serialInvoice: true,
|
||||
incomingInvoices: true,
|
||||
costcentres: true,
|
||||
branches: true,
|
||||
accounts: true,
|
||||
ownaccounts: true,
|
||||
banking: true,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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" })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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) {
|
||||
|
||||
142
backend/src/utils/profileBranches.ts
Normal file
142
backend/src/utils/profileBranches.ts
Normal 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,
|
||||
})))
|
||||
}
|
||||
@@ -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: {
|
||||
|
||||
Reference in New Issue
Block a user