46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
import { db } from '$lib/server/db';
|
|
import * as schema from '$lib/server/db/schema';
|
|
import { asc, eq, or, like } from 'drizzle-orm';
|
|
import type { PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async ({ url }) => {
|
|
const search = url.searchParams.get('search') || '';
|
|
const status = url.searchParams.get('status') || '';
|
|
|
|
try {
|
|
let query = db.select().from(schema.beneficiaries);
|
|
|
|
// We can fetch all and filter in memory since table size is guaranteed to be small (<20 tables, low concurrency).
|
|
// This keeps SQLite query logic extremely simple and readable.
|
|
let list = query.orderBy(asc(schema.beneficiaries.name)).all();
|
|
|
|
if (search) {
|
|
const searchLower = search.toLowerCase();
|
|
list = list.filter(
|
|
(b) =>
|
|
b.name.toLowerCase().includes(searchLower) ||
|
|
b.number.toString().includes(searchLower) ||
|
|
(b.contact && b.contact.includes(searchLower))
|
|
);
|
|
}
|
|
|
|
if (status && status !== 'todos') {
|
|
list = list.filter((b) => b.status === status);
|
|
}
|
|
|
|
return {
|
|
beneficiaries: list,
|
|
search,
|
|
status: status || 'todos'
|
|
};
|
|
} catch (err) {
|
|
console.error('Error loading beneficiaries:', err);
|
|
return {
|
|
beneficiaries: [],
|
|
search,
|
|
status: status || 'todos',
|
|
error: 'Erro ao carregar a lista de beneficiários.'
|
|
};
|
|
}
|
|
};
|