// Configurações gerais do painel (tabela app_settings, chave → valor em texto). Hoje: publicação pausada, // horários bons por rede, fuso e de quanto em quanto tempo ler os números dos posts. Valores ausentes ou estragados voltam ao padrão (nunca derrubam o despachante). import { all, db, run } from "./db"; import { DEFAULT_SLOTS, DEFAULT_TIMEZONE, isValidTimezone, normalizeSlots } from "./publishing-rules"; import { UserError } from "./stories"; import { PLATFORMS, type AppSettings, type SlotMap } from "./types"; /** Intervalos oferecidos para ler os números dos posts sozinho (0 = só pelo botão do dashboard). */ export const METRICS_EVERY_HOURS = [0, 3, 6, 12, 24] as const; const DEFAULT_METRICS_EVERY_HOURS = 6; function readRaw(): Record { return Object.fromEntries(all<{ key: string; value: string }>("SELECT key, value FROM app_settings").map((r) => [r.key, r.value])); } function parseSlots(raw: string | undefined): SlotMap { const slots: SlotMap = { ...DEFAULT_SLOTS }; if (!raw) return slots; try { const data = JSON.parse(raw) as Record; for (const p of PLATFORMS) { const list = normalizeSlots(data[p]); if (list) slots[p] = list; } } catch { /* JSON estragado: fica o padrão */ } return slots; } export function getSettings(): AppSettings { const raw = readRaw(); const timezone = raw.timezone && isValidTimezone(raw.timezone) ? raw.timezone : DEFAULT_TIMEZONE; const every = Number(raw.metrics_every_hours); const metricsEveryHours = (METRICS_EVERY_HOURS as readonly number[]).includes(every) && raw.metrics_every_hours !== undefined ? every : DEFAULT_METRICS_EVERY_HOURS; return { publishingPaused: raw.publishing_paused === "1", slots: parseSlots(raw.slots), timezone, metricsEveryHours }; } /** Atualiza só o que veio: {publishingPaused?, slots?: {youtube?: ["12:00", ...]}, timezone?}. */ export function updateSettings(input: { publishingPaused?: unknown; slots?: unknown; timezone?: unknown; metricsEveryHours?: unknown }): AppSettings { const current = getSettings(); const next: AppSettings = { ...current, slots: { ...current.slots } }; if (input.publishingPaused !== undefined) { if (typeof input.publishingPaused !== "boolean") throw new UserError("publishingPaused precisa ser verdadeiro ou falso."); next.publishingPaused = input.publishingPaused; } if (input.slots !== undefined) { if (!input.slots || typeof input.slots !== "object") throw new UserError("Horários bons inválidos."); for (const [platform, list] of Object.entries(input.slots as Record)) { if (!PLATFORMS.includes(platform as never)) throw new UserError(`Rede desconhecida nos horários: ${platform}.`); const clean = normalizeSlots(list); if (!clean) throw new UserError("Cada horário precisa estar no formato HH:MM (ex.: 08:00, 19:30)."); if (clean.length === 0) throw new UserError("Deixe pelo menos um horário bom em cada rede."); next.slots[platform as keyof SlotMap] = clean; } } if (input.timezone !== undefined) { const tz = String(input.timezone).trim(); if (!tz || !isValidTimezone(tz)) throw new UserError("Fuso horário inválido (use um nome como America/Sao_Paulo)."); next.timezone = tz; } if (input.metricsEveryHours !== undefined) { const every = Number(input.metricsEveryHours); if (!(METRICS_EVERY_HOURS as readonly number[]).includes(every)) throw new UserError("Escolha 3, 6, 12 ou 24 horas, ou “só quando eu pedir”."); next.metricsEveryHours = every; } const upsert = "INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value"; db().exec("BEGIN"); try { run(upsert, "publishing_paused", next.publishingPaused ? "1" : "0"); run(upsert, "slots", JSON.stringify(next.slots)); run(upsert, "timezone", next.timezone); run(upsert, "metrics_every_hours", String(next.metricsEveryHours)); db().exec("COMMIT"); } catch (error) { db().exec("ROLLBACK"); throw error; } return getSettings(); }