import { findResidentByCode } from "../auth/users.ts"; import { canonicalJson, safeEqualHex, sha256 } from "../crypto.ts"; import type { Db } from "../db/database.ts"; import { transaction } from "../db/database.ts"; import { badRequest, conflict, unauthorized } from "../errors.ts"; import { postLedgerEntry } from "../points/ledger.ts"; import { CONTAINER_TYPES, type ContainerItem, pointsForItems } from "../points/rates.ts"; export type EventOutcome = "credited" | "unlinked" | "ignored" | "resident_blocked"; export interface FandomatEvent { eventId: string; fandomatId: string; status: "confirmed" | "rejected"; residentCode: string | null; occurredAt: string | null; items: ContainerItem[]; } export interface EventResult { eventId: string; fandomatId: string; outcome: EventOutcome; points: number; duplicate: boolean; } const MAX_ITEMS = 50; const ID_PATTERN = /^[A-Za-z0-9._:-]{1,100}$/; /** Фандомат по ключу устройства (заголовок `X-Fandomat-Key`) или 401. */ export function authenticateFandomat(db: Db, key: unknown): string { if (typeof key !== "string" || key.length === 0) throw invalidKey(); const keyHash = sha256(key); const row = db .prepare("SELECT id, api_key_hash FROM fandomats WHERE api_key_hash = ?") .get(keyHash); if (!row || !safeEqualHex(String(row.api_key_hash), keyHash)) throw invalidKey(); return String(row.id); } const invalidKey = () => unauthorized("invalid_fandomat_key", "Неверный ключ фандомата"); function fail(message: string): never { throw badRequest("validation_error", message); } const isInt = (v: unknown, min: number, max: number): v is number => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max; export function parseFandomatEvent(body: unknown): FandomatEvent { if (body === null || typeof body !== "object" || Array.isArray(body)) fail("Ожидается JSON-объект"); const b = body as Record; if (typeof b.eventId !== "string" || !ID_PATTERN.test(b.eventId)) fail("eventId: 1–100 символов [A-Za-z0-9._:-]"); if (typeof b.fandomatId !== "string" || b.fandomatId.length === 0) fail("fandomatId обязателен"); if (b.status !== "confirmed" && b.status !== "rejected") fail("status: confirmed или rejected"); if ( b.residentCode !== undefined && b.residentCode !== null && typeof b.residentCode !== "string" ) { fail("residentCode должен быть строкой"); } if ( b.occurredAt !== undefined && (typeof b.occurredAt !== "string" || Number.isNaN(Date.parse(b.occurredAt))) ) { fail("occurredAt: дата в формате ISO 8601"); } if (!Array.isArray(b.items) || b.items.length === 0 || b.items.length > MAX_ITEMS) { fail(`items: от 1 до ${MAX_ITEMS} позиций`); } const items = b.items.map((raw, i): ContainerItem => { const it = (raw ?? {}) as Record; if (!(CONTAINER_TYPES as readonly unknown[]).includes(it.type)) { fail(`items[${i}].type: ${CONTAINER_TYPES.join(", ")}`); } if (!isInt(it.volumeMl, 100, 5000)) fail(`items[${i}].volumeMl: целое 100–5000`); if (!isInt(it.count, 1, 500)) fail(`items[${i}].count: целое 1–500`); return { type: it.type as ContainerItem["type"], volumeMl: it.volumeMl, count: it.count }; }); return { eventId: b.eventId, fandomatId: b.fandomatId, status: b.status, residentCode: (b.residentCode as string | null | undefined) || null, occurredAt: (b.occurredAt as string | undefined) ?? null, items, }; } /** * Обрабатывает событие ровно один раз по паре (fandomatId, eventId). * Повтор с тем же содержимым возвращает прежний итог (`duplicate: true`), с другим — 409. */ export function processFandomatEvent(db: Db, event: FandomatEvent): EventResult { const payload = canonicalJson({ status: event.status, residentCode: event.residentCode, occurredAt: event.occurredAt, items: event.items, }); const payloadHash = sha256(payload); return transaction(db, () => { const existing = db .prepare( "SELECT payload_hash, outcome, points FROM fandomat_events WHERE fandomat_id = ? AND event_id = ?", ) .get(event.fandomatId, event.eventId); if (existing) { if (existing.payload_hash !== payloadHash) { throw conflict("event_conflict", "Событие с этим eventId уже получено с другим содержимым"); } return { eventId: event.eventId, fandomatId: event.fandomatId, outcome: existing.outcome as EventOutcome, points: Number(existing.points), duplicate: true, }; } const resident = event.residentCode ? findResidentByCode(db, event.residentCode) : null; let outcome: EventOutcome; if (event.status !== "confirmed") outcome = "ignored"; else if (!resident) outcome = "unlinked"; else if (resident.status === "blocked") outcome = "resident_blocked"; else outcome = "credited"; const points = outcome === "credited" ? pointsForItems(event.items) : 0; db.prepare( `INSERT INTO fandomat_events (fandomat_id, event_id, payload_hash, payload, resident_id, outcome, points, received_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, ).run( event.fandomatId, event.eventId, payloadHash, payload, resident?.id ?? null, outcome, points, new Date().toISOString(), ); if (outcome === "credited" && resident) { postLedgerEntry(db, { userId: resident.id, kind: "earn", delta: points, sourceType: "fandomat_event", sourceId: `${event.fandomatId}:${event.eventId}`, description: `Сдача тары: фандомат ${event.fandomatId}, событие ${event.eventId}`, }); } return { eventId: event.eventId, fandomatId: event.fandomatId, outcome, points, duplicate: false, }; }); }