// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so // a stray message never creates a story by itself. Drafts live in `settings` for a day. import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core"; import type { Db } from "@peppa/db"; export const DRAFT_TTL_MS = 24 * 3600_000; export const TITLE_MAX = 120; export interface Draft { id: number; userId: number; chatId: number; text: string; projectId: number | null; voice: boolean; createdAt: number; } const key = (id: number) => `bot.draft:${id}`; export async function saveDraft(db: Db, d: Omit): Promise { const id = ((await getSetting(db, "bot.draft.seq")) ?? 0) + 1; await setSetting(db, "bot.draft.seq", id); const draft: Draft = { ...d, id, createdAt: Date.now() }; await setSetting(db, key(id), draft); return draft; } /** The user's own, not expired draft. */ export async function loadDraft(db: Db, id: number, userId: number): Promise { const d = await getSetting(db, key(id)); if (!d || d.userId !== userId) return null; if (Date.now() - d.createdAt > DRAFT_TTL_MS) { await deleteSetting(db, key(id)); return null; } return d; } export async function updateDraft(db: Db, d: Draft): Promise { await setSetting(db, key(d.id), d); } export async function dropDraft(db: Db, id: number): Promise { await deleteSetting(db, key(id)); } /** * "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…" and * "в проекте Pay экспорт…" (how whisper writes it down, PEP-108). * The key counts only if it is one of the user's projects; otherwise the whole text is the story. */ export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } { const t = text.trim(); const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null; const withSep = /^(?:(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t); if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() }; const spoken = /^(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t); if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() }; return { project: null, body: t }; } /** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */ export function splitStory(body: string): { title: string; rest: string } { const [first = "", ...lines] = body.trim().split("\n"); let title = first.trim(); let rest = lines.join("\n").trim(); if (title.length > TITLE_MAX) { const cut = title.lastIndexOf(" ", TITLE_MAX - 1); const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1; rest = `${title}${rest ? `\n\n${rest}` : ""}`; title = `${title.slice(0, at).trim()}…`; } return { title, rest }; }