// 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"; export { splitStory, TITLE_MAX } from "@peppa/core"; import type { Db } from "@peppa/db"; export const DRAFT_TTL_MS = 24 * 3600_000; export interface Draft { id: number; userId: number; chatId: number; text: string; projectId: number | null; voice: boolean; /** PEP-153: not a story yet — a message the bot answered or asked about («Завести как задачу»). */ offer?: boolean; /** PEP-153: the bot asked «Ответить или завести задачу?» and the person has not picked yet. */ asked?: boolean; /** PEP-153: the answer at hand for «Ответить» (null — answer from the platform's data). */ answer?: string | null; 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 }; }