121 lines
3.1 KiB
TypeScript
121 lines
3.1 KiB
TypeScript
import { db } from '$lib/server/db';
|
|
import * as schema from '$lib/server/db/schema';
|
|
import { eq, and, ne } from 'drizzle-orm';
|
|
import { error, fail, redirect } from '@sveltejs/kit';
|
|
import type { Actions, PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async ({ params }) => {
|
|
const id = params.id;
|
|
|
|
try {
|
|
const beneficiary = db
|
|
.select()
|
|
.from(schema.beneficiaries)
|
|
.where(eq(schema.beneficiaries.id, id))
|
|
.get();
|
|
|
|
if (!beneficiary) {
|
|
throw error(404, 'Beneficiário não encontrado');
|
|
}
|
|
|
|
return {
|
|
beneficiary
|
|
};
|
|
} catch (err) {
|
|
if (err && typeof err === 'object' && 'status' in err && err.status === 404) {
|
|
throw err;
|
|
}
|
|
console.error('Error loading beneficiary details:', err);
|
|
throw error(500, 'Ocorreu um erro ao carregar os dados do beneficiário.');
|
|
}
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
default: async ({ params, request }) => {
|
|
const id = params.id;
|
|
const data = await request.formData();
|
|
const numberStr = data.get('number')?.toString().trim();
|
|
const name = data.get('name')?.toString().trim();
|
|
const contact = data.get('contact')?.toString().trim();
|
|
const householdSizeStr = data.get('householdSize')?.toString().trim();
|
|
const observations = data.get('observations')?.toString().trim();
|
|
const status = data.get('status')?.toString().trim();
|
|
|
|
// Basic validation
|
|
if (!numberStr || !name || !contact || !householdSizeStr || !status) {
|
|
return fail(400, {
|
|
success: false,
|
|
error: 'Todos os campos obrigatórios devem ser preenchidos.'
|
|
});
|
|
}
|
|
|
|
const number = parseInt(numberStr, 10);
|
|
const householdSize = parseInt(householdSizeStr, 10);
|
|
|
|
if (isNaN(number) || number <= 0) {
|
|
return fail(400, {
|
|
success: false,
|
|
error: 'O número de beneficiário deve ser um número inteiro positivo.'
|
|
});
|
|
}
|
|
|
|
if (isNaN(householdSize) || householdSize < 1) {
|
|
return fail(400, {
|
|
success: false,
|
|
error: 'O agregado familiar deve ter pelo menos 1 pessoa.'
|
|
});
|
|
}
|
|
|
|
if (status !== 'ativo' && status !== 'inativo') {
|
|
return fail(400, {
|
|
success: false,
|
|
error: 'Estado inválido selecionado.'
|
|
});
|
|
}
|
|
|
|
try {
|
|
// Check if new number conflicts with another beneficiary (excluding self)
|
|
const existingConflict = db
|
|
.select()
|
|
.from(schema.beneficiaries)
|
|
.where(
|
|
and(
|
|
eq(schema.beneficiaries.number, number),
|
|
ne(schema.beneficiaries.id, id)
|
|
)
|
|
)
|
|
.get();
|
|
|
|
if (existingConflict) {
|
|
return fail(400, {
|
|
success: false,
|
|
error: `O número de beneficiário #${number} já está atribuído a outro registo.`
|
|
});
|
|
}
|
|
|
|
// Update details
|
|
db.update(schema.beneficiaries)
|
|
.set({
|
|
number,
|
|
name,
|
|
contact,
|
|
householdSize,
|
|
observations,
|
|
status,
|
|
updatedAt: Date.now()
|
|
})
|
|
.where(eq(schema.beneficiaries.id, id))
|
|
.run();
|
|
} catch (err) {
|
|
console.error('Error updating beneficiary details:', err);
|
|
return fail(500, {
|
|
success: false,
|
|
error: 'Erro ao guardar as alterações na base de dados.'
|
|
});
|
|
}
|
|
|
|
// Redirect on success
|
|
throw redirect(303, `/admin/beneficiarios?success=${encodeURIComponent('Alterações guardadas com sucesso.')}`);
|
|
}
|
|
};
|