diff --git a/server.js b/server.js index 5e0c504..b23de20 100644 --- a/server.js +++ b/server.js @@ -136,9 +136,26 @@ app.get('/api/templates', async (req, res) => { // SAVE (Upsert) Template app.post('/api/templates', async (req, res) => { const t = req.body; - const fullHtml = `${t.header}${t.body}${t.footer}`; - const templateKey = t.name.trim().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, ''); - const variablesJson = JSON.stringify(t.variables); + // Ensure default values to prevent undefined errors in Postgres + const header = t.header || ''; + const body = t.body || ''; + const footer = t.footer || ''; + const fullHtml = `${header}${body}${footer}`; + const templateKey = (t.name || '').trim().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, ''); + const variablesJson = JSON.stringify(t.variables || []); + + const params = [ + t.id, + templateKey, + t.name, + t.description || '', + t.subject || '', + header, + body, + footer, + fullHtml, + variablesJson + ]; try { if (DB_TYPE === 'postgres') { @@ -157,7 +174,7 @@ app.post('/api/templates', async (req, res) => { required_variables = EXCLUDED.required_variables, updated_at = NOW(); `; - await pool.query(query, [t.id, templateKey, t.name, t.description, t.subject, t.header, t.body, t.footer, fullHtml, variablesJson]); + await pool.query(query, params); } else { const query = ` INSERT INTO email_templates (id, template_key, name, description, subject, header_html, body_html, footer_html, full_html, required_variables, updated_at) @@ -174,7 +191,7 @@ app.post('/api/templates', async (req, res) => { required_variables = VALUES(required_variables), updated_at = NOW(); `; - await pool.query(query, [t.id, templateKey, t.name, t.description, t.subject, t.header, t.body, t.footer, fullHtml, variablesJson]); + await pool.query(query, params); } res.json({ success: true }); } catch (err) {