64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
import type { Pool } from 'pg';
|
|
|
|
export interface Banco {
|
|
id: number;
|
|
banco: string;
|
|
terminacionCuenta: string;
|
|
creadoEn: string;
|
|
}
|
|
|
|
export async function getBancos(pool: Pool, contribuyenteId?: string | null): Promise<Banco[]> {
|
|
const conditions = [];
|
|
const params: unknown[] = [];
|
|
if (contribuyenteId) {
|
|
params.push(contribuyenteId);
|
|
conditions.push(`contribuyente_id = $${params.length}`);
|
|
}
|
|
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
const { rows } = await pool.query(`
|
|
SELECT id, banco, terminacion_cuenta as "terminacionCuenta",
|
|
creado_en as "creadoEn"
|
|
FROM bancos ${where} ORDER BY banco
|
|
`, params);
|
|
return rows;
|
|
}
|
|
|
|
export async function createBanco(pool: Pool, data: { banco: string; terminacionCuenta: string; contribuyenteId?: string }): Promise<Banco> {
|
|
const { rows } = await pool.query(`
|
|
INSERT INTO bancos (banco, terminacion_cuenta, contribuyente_id)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, banco, terminacion_cuenta as "terminacionCuenta", creado_en as "creadoEn"
|
|
`, [data.banco, data.terminacionCuenta, data.contribuyenteId || null]);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function updateBanco(pool: Pool, id: number, data: { banco?: string; terminacionCuenta?: string }): Promise<Banco> {
|
|
const fields: string[] = [];
|
|
const params: any[] = [];
|
|
let idx = 1;
|
|
|
|
if (data.banco) { fields.push(`banco = $${idx++}`); params.push(data.banco); }
|
|
if (data.terminacionCuenta) { fields.push(`terminacion_cuenta = $${idx++}`); params.push(data.terminacionCuenta); }
|
|
|
|
if (fields.length === 0) throw new Error('Nada que actualizar');
|
|
|
|
params.push(id);
|
|
const { rows } = await pool.query(`
|
|
UPDATE bancos SET ${fields.join(', ')} WHERE id = $${idx}
|
|
RETURNING id, banco, terminacion_cuenta as "terminacionCuenta", creado_en as "creadoEn"
|
|
`, params);
|
|
|
|
if (rows.length === 0) throw new Error('Banco no encontrado');
|
|
return rows[0];
|
|
}
|
|
|
|
export async function deleteBanco(pool: Pool, id: number): Promise<void> {
|
|
const { rows } = await pool.query(
|
|
`SELECT COUNT(*)::int as count FROM conciliaciones WHERE id_banco = $1`, [id]
|
|
);
|
|
if (rows[0].count > 0) {
|
|
throw new Error('No se puede eliminar un banco con conciliaciones asociadas');
|
|
}
|
|
await pool.query(`DELETE FROM bancos WHERE id = $1`, [id]);
|
|
}
|