Commit b092c6c3 authored by Hendrik Garske's avatar Hendrik Garske

fix: Customer-Query korrigiert - separate TimeEntries-Abfrage für TypeScript-Kompatibilität

parent c2f2c5ce
Pipeline #22 failed with stages
in 25 seconds
......@@ -8,57 +8,63 @@ export async function GET(request: NextRequest) {
const search = searchParams.get("search")
let customersQuery = `
SELECT c.*,
COALESCE(
json_agg(
json_build_object(
'id', te.id,
'description', te.description,
'startTime', te."startTime",
'endTime', te."endTime",
'duration', te.duration,
'createdAt', te."createdAt",
'updatedAt', te."updatedAt",
'customerId', te."customerId",
'userId', te."userId",
'user', json_build_object(
'name', u.name,
'email', u.email
)
)
) FILTER (WHERE te.id IS NOT NULL),
'[]'::json
) as "timeEntries"
SELECT c.*
FROM customers c
LEFT JOIN time_entries te ON te."customerId" = c.id
LEFT JOIN users u ON u.id = te."userId"
`
const params: string[] = []
if (search) {
customersQuery += `
WHERE c.name ILIKE $1 OR c.email ILIKE $1 OR c.company ILIKE $1
`
customersQuery += ` WHERE c.name ILIKE $1 OR c.email ILIKE $1 OR c.company ILIKE $1`
params.push(`%${search}%`)
}
customersQuery += `
GROUP BY c.id
ORDER BY c."createdAt" DESC
`
customersQuery += ` ORDER BY c."createdAt" DESC`
const result = await query(customersQuery, params.length > 0 ? params : undefined)
const customers = result.rows.map((row: { timeEntries: string | unknown[] }) => {
const customer = rowToCustomer(row)
return {
...customer,
timeEntries: typeof row.timeEntries === 'string'
? JSON.parse(row.timeEntries)
: (Array.isArray(row.timeEntries) ? row.timeEntries : []),
}
})
// Get time entries for each customer
const customers = await Promise.all(
result.rows.map(async (row) => {
const customer = rowToCustomer(row)
const timeEntriesResult = await query(
`SELECT te.*,
json_build_object('name', u.name, 'email', u.email) as user
FROM time_entries te
LEFT JOIN users u ON u.id = te."userId"
WHERE te."customerId" = $1
ORDER BY te."createdAt" DESC`,
[customer.id]
)
const timeEntries = timeEntriesResult.rows.map((entry: {
id: string
description: string
startTime: Date
endTime: Date
duration: number
createdAt: Date
updatedAt: Date
customerId: string
userId: string
user: unknown
}) => ({
id: entry.id,
description: entry.description,
startTime: entry.startTime,
endTime: entry.endTime,
duration: entry.duration,
createdAt: entry.createdAt,
updatedAt: entry.updatedAt,
customerId: entry.customerId,
userId: entry.userId,
user: typeof entry.user === 'string' ? JSON.parse(entry.user) : entry.user,
}))
return {
...customer,
timeEntries,
}
})
)
return NextResponse.json(customers)
} catch (error) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment