const prisma = require('../config/db'); const { encrypt, decrypt } = require('./crypto'); const { DEFAULT_AI_MODEL } = require('./aiModels'); // Hub settings Joshua edits on the Settings page, with their defaults. const DEFAULTS = { latest_version: '', alert_email: '', // Alert thresholds offline_minutes: '60', backup_max_age_hours: '48', disk_min_free_percent: '10', errors_per_day: '50', licence_expiry_warning_days: '14', // Outgoing email. The password is stored encrypted and never sent to the browser. smtp_host: '', smtp_port: '587', smtp_user: '', smtp_pass: '', smtp_from: '', // Releases and their notes are read from git (utils/releaseSync.js). Hub 2.0: release_sources // is the list of sources per product (JSON, Releases page); blank = the defaults, which include // release_repo_url (Cross Events before the monorepo, v1.2.3 tags) and release_notes_path. release_sources: '', release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events', release_notes_path: 'WHATS-NEW.md', release_repo_token: '', // Written by the sync, not the Settings page. release_synced_at: '', release_sync_error: '', // AI for Cross Events 2.0 (utils/ai.js). Off until a key and the exchange rate are set. ai_api_key: '', // One of utils/aiModels.js, or another model ID typed in. ai_model: DEFAULT_AI_MODEL.id, // US dollars per million tokens, for prompts under 100K tokens (the Hub refuses bigger ones). // Filled in from utils/aiModels.js when a model is chosen; blank means the built-in price. ai_input_usd_per_mtok: String(DEFAULT_AI_MODEL.inputUsd), ai_output_usd_per_mtok: String(DEFAULT_AI_MODEL.outputUsd), // Rand per US dollar. ai_usd_zar: '', // Default markup on the real cost, in %; a licence can override it. ai_markup_percent: '15', // Billing (1.7.0, utils/billing/). Drafts are made billing_draft_days before an invoice's date // and emailed to alert_email for approval; approved invoices go out on their date at // billing_send_hour (South African time). billing_enabled: 'true', billing_draft_days: '14', billing_send_hour: '8', payment_terms_days: '7', invoice_prefix: 'INV', receipt_prefix: 'REC', change_prefix: 'LC', // Printed on every document. business_name: 'Cross Code', business_owner: 'Joshua Oosthuizen', business_address: '44 Gordon Road, Henley on Klip, Gauteng, South Africa', business_email: 'admin@crosscode.co.za', business_phone: '+27 68 903 8075', business_website: 'crosscode.co.za', business_registration: '', // Not VAT registered: no VAT on documents. Once registered, prices are VAT-inclusive: the // totals stay the same, documents become tax invoices and show the VAT included. vat_registered: '', vat_number: '', vat_rate: '15', bank_name: '', bank_account_name: '', bank_account_number: '', bank_branch_code: '', bank_account_type: '', invoice_footer: 'Thank you for using Cross Events.', // Replies to billing emails go here (blank: business_email). billing_reply_to: '', }; // Stored encrypted and never sent to the browser: only "is one saved" (_set). const SECRETS = ['smtp_pass', 'release_repo_token', 'ai_api_key']; async function rawSettings() { const rows = await prisma.setting.findMany(); const saved = Object.fromEntries(rows.map(r => [r.key, r.value])); return { ...DEFAULTS, ...saved }; } /** Settings for the Settings page: secrets (SMTP password, repo token) only as "is one saved". */ async function getSettings() { const settings = await rawSettings(); for (const key of SECRETS) { settings[`${key}_set`] = settings[key] ? 'true' : ''; delete settings[key]; } return settings; } /** * Save settings. A blank secret keeps the saved one (the page never has it); _clear * removes it. */ async function setSettings(values) { const input = { ...(values || {}) }; for (const key of SECRETS) { if (input[`${key}_clear`]) input[key] = ''; else if (input[key]) input[key] = encrypt(input[key]); else delete input[key]; } const updates = Object.entries(input).filter(([k]) => k in DEFAULTS); for (const [key, value] of updates) { await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } }); } return getSettings(); } /** * SMTP settings to send with, password decrypted. Pass `overrides` (from the Settings form) * to try values before saving them; a blank password there means the saved one. */ async function smtpSettings(overrides) { const saved = await rawSettings(); const pick = key => (overrides && overrides[key] != null ? String(overrides[key]).trim() : saved[key]); let pass = overrides?.smtp_pass_clear ? '' : overrides?.smtp_pass || ''; if (!pass && !overrides?.smtp_pass_clear && saved.smtp_pass) pass = decrypt(saved.smtp_pass); return { host: pick('smtp_host'), port: parseInt(pick('smtp_port') || '587', 10), user: pick('smtp_user'), pass, from: pick('smtp_from'), }; } /** * Before 1.2.0 SMTP was set with SMTP_* in backend/.env. If the database has no SMTP host yet, * copy them over once, so an update doesn't stop the alert emails. */ async function importSmtpFromEnv() { if (!process.env.SMTP_HOST) return false; const saved = await rawSettings(); if (saved.smtp_host) return false; await setSettings({ smtp_host: process.env.SMTP_HOST, smtp_port: process.env.SMTP_PORT || '587', smtp_user: process.env.SMTP_USER || '', smtp_pass: process.env.SMTP_PASS || '', smtp_from: process.env.SMTP_FROM || '', }); return true; } /** The saved repo token, decrypted ('' when none). */ async function releaseRepoToken() { const { release_repo_token } = await rawSettings(); return release_repo_token ? decrypt(release_repo_token) : ''; } /** The saved Claude API key, decrypted ('' when none). */ async function aiApiKey() { const { ai_api_key } = await rawSettings(); return ai_api_key ? decrypt(ai_api_key) : ''; } module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken, aiApiKey };