70 lines
2.6 KiB
JavaScript
70 lines
2.6 KiB
JavaScript
const UnitOfWork = require('../../database/UnitOfWork');
|
|
const PoolRepository = require('../../repositories/pool/poolRepository');
|
|
|
|
function isValidPoolType(pool_type) {
|
|
return pool_type === 'coffee' || pool_type === 'other';
|
|
}
|
|
|
|
async function createPool({ pool_name, description = null, price = 0.00, pool_type = 'other', is_active = true, created_by = null }) {
|
|
if (!isValidPoolType(pool_type)) {
|
|
const err = new Error('Invalid pool_type. Allowed: coffee, other');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.createPool] start', { pool_name, pool_type });
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const pool = await repo.create({ pool_name, description, price, pool_type, is_active, created_by });
|
|
await uow.commit();
|
|
console.debug('[PoolService.createPool] success', { id: pool.id });
|
|
return pool;
|
|
} catch (err) {
|
|
console.error('[PoolService.createPool] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.createPool] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function listPools() {
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.listPools] start');
|
|
// Ensure connection exists even for read-only
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const pools = await repo.findAll();
|
|
await uow.commit(); // harmless commit; ensures proper cleanup if UnitOfWork requires it
|
|
console.debug('[PoolService.listPools] success', { count: pools.length });
|
|
return pools;
|
|
} catch (err) {
|
|
console.error('[PoolService.listPools] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.listPools] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function updatePoolState(id, is_active, actorUserId) {
|
|
if (typeof is_active !== 'boolean') {
|
|
const err = new Error('is_active must be a boolean');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.updatePoolState] start', { id, is_active });
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const updated = await repo.updateActive(id, is_active, actorUserId);
|
|
await uow.commit();
|
|
console.debug('[PoolService.updatePoolState] success', { id, is_active });
|
|
return updated;
|
|
} catch (err) {
|
|
console.error('[PoolService.updatePoolState] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.updatePoolState] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
module.exports = { createPool, listPools, updatePoolState }; |