Redone Routes customers,contracts,contacts,vendors

This commit is contained in:
2025-12-06 20:33:27 +01:00
parent 765f3c42c1
commit dff2b05401
4 changed files with 687 additions and 199 deletions

View File

@@ -4,7 +4,10 @@ import {
ilike,
asc,
desc,
and, count, inArray,
and,
count,
inArray,
or,
} from "drizzle-orm"
import {
@@ -17,7 +20,29 @@ import {
statementallocations,
files,
events,
} from "../../../db/schema" // dein zentraler index.ts Export
} from "../../../db/schema"
// -------------------------------------------------------------
// 🔍 Helper für SQL-Suche über mehrere Spalten
// -------------------------------------------------------------
function buildSearchCondition(table: any, columns: string[], search: string) {
if (!search || !columns.length) return null
const term = `%${search.toLowerCase()}%`
const conditions = columns
.map((colName) => table[colName])
.filter(Boolean)
.map((col) => ilike(col, term))
if (conditions.length === 0) return null
// @ts-ignore
return or(...conditions)
}
export default async function customerRoutes(server: FastifyInstance) {
@@ -36,38 +61,38 @@ export default async function customerRoutes(server: FastifyInstance) {
}
// Basisquery
let whereCond: any = eq(customers.tenant, tenantId)
// 🔍 SQL-Suche
if (search) {
const searchCond = buildSearchCondition(
customers,
["name", "customerNumber", "firstname", "lastname", "notes"],
search
)
if (searchCond) {
whereCond = and(whereCond, searchCond)
}
}
let baseQuery = server.db
.select()
.from(customers)
.where(eq(customers.tenant, tenantId))
// Suche
if (search) {
baseQuery = server.db
.select()
.from(customers)
.where(
and(
eq(customers.tenant, tenantId),
ilike(customers.name, `%${search}%`)
)
)
}
.where(whereCond)
// Sortierung
if (sort) {
const field = (customers as any)[sort]
if (field) {
// @ts-ignore
//@ts-ignore
baseQuery = baseQuery.orderBy(
ascQuery === "true" ? asc(field) : desc(field)
)
}
}
const customerList = await baseQuery
return customerList
return await baseQuery
})
@@ -91,22 +116,19 @@ export default async function customerRoutes(server: FastifyInstance) {
} = queryConfig
const {
select,
search,
searchColumns,
distinctColumns
} = req.query as {
select?: string
search?: string
searchColumns?: string
distinctColumns?: string
}
// ----------------------------
// WHERE CONDITIONS
// WHERE CONDITIONS (Basis)
// ----------------------------
let whereCond: any = eq(customers.tenant, tenantId)
// Filters
if (filters) {
for (const [key, val] of Object.entries(filters)) {
const col = (customers as any)[key]
@@ -114,24 +136,29 @@ export default async function customerRoutes(server: FastifyInstance) {
if (Array.isArray(val)) {
whereCond = and(whereCond, inArray(col, val))
} else if (val === true || val === false || val === null) {
whereCond = and(whereCond, eq(col, val))
} else {
whereCond = and(whereCond, eq(col, val))
whereCond = and(whereCond, eq(col, val as any))
}
}
}
// ----------------------------
// 🔍 SEARCH
// ----------------------------
if (search && search.trim().length > 0) {
const searchTerm = `%${search.trim().toLowerCase()}%`
whereCond = and(
whereCond,
ilike(customers.name, searchTerm)
const searchCond = buildSearchCondition(
customers,
["name", "customerNumber", "firstname", "lastname", "notes"],
search.trim()
)
if (searchCond) {
whereCond = and(whereCond, searchCond)
}
}
// ----------------------------
// COUNT FIX (Drizzle-safe)
// COUNT
// ----------------------------
const totalRes = await server.db
.select({ value: count(customers.id) })
@@ -141,7 +168,7 @@ export default async function customerRoutes(server: FastifyInstance) {
const total = Number(totalRes[0]?.value ?? 0)
// ----------------------------
// DISTINCT VALUES (optional)
// DISTINCT VALUES
// ----------------------------
const distinctValues: Record<string, any[]> = {}
@@ -155,11 +182,9 @@ export default async function customerRoutes(server: FastifyInstance) {
.from(customers)
.where(eq(customers.tenant, tenantId))
const values = rows
.map(r => r.v)
.filter(v => v != null && v !== "")
distinctValues[colName] = [...new Set(values)].sort()
distinctValues[colName] =
[...new Set(rows.map(r => r.v).filter(v => v != null && v !== ""))]
.sort()
}
}
@@ -200,6 +225,7 @@ export default async function customerRoutes(server: FastifyInstance) {
.limit(limit)
if (orderField) {
//@ts-ignore
dataQuery =
orderDirection === "asc"
? dataQuery.orderBy(asc(orderField))
@@ -209,7 +235,7 @@ export default async function customerRoutes(server: FastifyInstance) {
const data = await dataQuery
// ----------------------------
// BUILD RETURN CONFIG
// CONFIG RESPONSE
// ----------------------------
const totalPages = pagination?.limit
? Math.ceil(total / pagination.limit)
@@ -231,7 +257,6 @@ export default async function customerRoutes(server: FastifyInstance) {
catch (e) {
console.log(e)
}
})
@@ -269,28 +294,11 @@ export default async function customerRoutes(server: FastifyInstance) {
customerFiles,
customerEvents,
] = await Promise.all([
// Projekte, die dem Kunden zugeordnet sind
server.db
.select()
.from(projects)
.where(eq(projects.customer, Number(id))),
server.db.select().from(projects).where(eq(projects.customer, Number(id))),
server.db.select().from(plants).where(eq(plants.customer, Number(id))),
server.db.select().from(contracts).where(eq(contracts.customer, Number(id))),
server.db.select().from(contacts).where(eq(contacts.customer, Number(id))),
server.db
.select()
.from(plants)
.where(eq(plants.customer, Number(id))),
server.db
.select()
.from(contracts)
.where(eq(contracts.customer, Number(id))),
server.db
.select()
.from(contacts)
.where(eq(contacts.customer, Number(id))),
// createddocuments + inner join statementallocations
server.db
.select({
...createddocuments,
@@ -303,15 +311,8 @@ export default async function customerRoutes(server: FastifyInstance) {
)
.where(eq(createddocuments.customer, Number(id))),
server.db
.select()
.from(files)
.where(eq(files.customer, Number(id))),
server.db
.select()
.from(events)
.where(eq(events.customer, Number(id))),
server.db.select().from(files).where(eq(files.customer, Number(id))),
server.db.select().from(events).where(eq(events.customer, Number(id))),
])
return {