UNPKG

@debito/hippo-lib

Version:

Double-entry accounting library for CouchDB

102 lines (85 loc) 2.97 kB
import { getMetaDB } from './config.js'; /** * COA Template CRUD operations on hippo-meta database * Separate from COA class which handles book-level COA operations */ class COATemplate { /** * List all COA templates from meta DB * @returns {Promise<Array>} Array of template summary objects */ static async list() { const metaDB = getMetaDB(); const result = await metaDB.find({ selector: { type: 'coa_template' }, sort: [{ 'name': 'asc' }], limit: 999999 }); return result.docs; } /** * Get a full COA template document by ID * @param {string} templateId - Template identifier (without prefix) * @returns {Promise<Object>} Full template document */ static async get(templateId) { const metaDB = getMetaDB(); const docId = templateId.startsWith('coa-template-') ? templateId : `coa-template-${templateId}`; try { return await metaDB.get(docId); } catch (error) { if (error.status === 404) { throw new Error(`COA template '${templateId}' not found`); } throw error; } } /** * Save (create or update) a COA template * If _id and _rev exist on the data, it updates; otherwise creates new * @param {Object} templateData - Template data to save * @returns {Promise<Object>} Saved template document */ static async save(templateData) { const metaDB = getMetaDB(); const doc = { ...templateData }; // Ensure type is set doc.type = 'coa_template'; // If no _id, generate one from the name if (!doc._id) { if (!doc.name) { throw new Error('Template name is required for new templates'); } const slug = doc.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''); doc._id = `coa-template-${slug}`; } doc.updatedAt = new Date().toISOString(); if (!doc.created) { doc.created = doc.updatedAt; } const result = await metaDB.insert(doc, doc._id); doc._rev = result.rev; return doc; } /** * Delete a COA template from meta DB * @param {string} templateId - Template identifier (without prefix) * @returns {Promise<void>} */ static async delete(templateId) { const metaDB = getMetaDB(); const docId = templateId.startsWith('coa-template-') ? templateId : `coa-template-${templateId}`; try { const doc = await metaDB.get(docId); await metaDB.destroy(doc._id, doc._rev); } catch (error) { if (error.status === 404) { throw new Error(`COA template '${templateId}' not found`); } throw error; } } } export default COATemplate;