From bab648d3cad6b7bd8e218ba5d5bd76eb2fae761b Mon Sep 17 00:00:00 2001 From: seaznCode Date: Wed, 11 Mar 2026 22:29:07 +0100 Subject: [PATCH] feat: add deactivateOtherActiveInvoices method to manage invoice template states --- .../template/DocumentTemplateRepository.js | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/repositories/template/DocumentTemplateRepository.js b/repositories/template/DocumentTemplateRepository.js index 5dd113e..c3355d7 100644 --- a/repositories/template/DocumentTemplateRepository.js +++ b/repositories/template/DocumentTemplateRepository.js @@ -193,6 +193,36 @@ class DocumentTemplateRepository { } } + // Deactivate other active invoice templates for the same language. + // Invoices always use user_type='both', so only lang matters. + async deactivateOtherActiveInvoices({ excludeId, lang }, conn) { + logger.info('DocumentTemplateRepository.deactivateOtherActiveInvoices:start', { excludeId, lang }); + const safeLang = (lang === 'en' || lang === 'de') ? lang : 'en'; + + const query = ` + UPDATE document_templates + SET state = 'inactive', updatedAt = NOW() + WHERE id <> ? + AND type = 'invoice' + AND lang = ? + AND state = 'active' + `; + const params = [excludeId, safeLang]; + try { + if (conn) { + const [res] = await conn.execute(query, params); + logger.info('DocumentTemplateRepository.deactivateOtherActiveInvoices:success', { affected: res?.affectedRows }); + return res?.affectedRows || 0; + } + const res = await db.execute(query, params); + logger.info('DocumentTemplateRepository.deactivateOtherActiveInvoices:success', { affected: res?.affectedRows }); + return res?.affectedRows || 0; + } catch (error) { + logger.error('DocumentTemplateRepository.deactivateOtherActiveInvoices:error', { error: error.message }); + throw error; + } + } + async delete(id, conn) { logger.info('DocumentTemplateRepository.delete:start', { id }); const query = `DELETE FROM document_templates WHERE id = ?`; @@ -209,9 +239,11 @@ class DocumentTemplateRepository { async findActiveByUserType(userType, templateType = null, contractType = null, conn) { logger.info('DocumentTemplateRepository.findActiveByUserType:start', { userType, templateType, contractType }); - const safeType = (userType === 'personal' || userType === 'company') ? userType : 'personal'; - let query = `SELECT * FROM document_templates WHERE state = 'active' AND (user_type = ? OR user_type = 'both')`; - const params = [safeType]; + const safeType = (userType === 'both') ? 'both' : (userType === 'personal' || userType === 'company') ? userType : 'personal'; + let query = safeType === 'both' + ? `SELECT * FROM document_templates WHERE state = 'active' AND user_type = 'both'` + : `SELECT * FROM document_templates WHERE state = 'active' AND (user_type = ? OR user_type = 'both')`; + const params = safeType === 'both' ? [] : [safeType]; if (templateType) { query += ` AND type = ?`; params.push(templateType);