import type { Database } from "bun:sqlite"; import type { SyncRunRow, SyncRunStatus } from "@/interfaces"; import { nowMs } from "@/utils/dates"; interface SyncRunRecord { id: number; author: string; started_at: number; finished_at: number | null; status: SyncRunStatus; new_works: number; price_changes: number; new_magnets: number; with_detail: number; with_sukebei: number; error_message: string | null; } const toRow = (r: SyncRunRecord): SyncRunRow => ({ id: r.id, author: r.author, startedAt: r.started_at, finishedAt: r.finished_at, status: r.status, newWorks: r.new_works, priceChanges: r.price_changes, newMagnets: r.new_magnets, withDetail: r.with_detail === 1, withSukebei: r.with_sukebei === 1, errorMessage: r.error_message }); export const startRun = ( db: Database, author: string, flags: { withDetail: boolean; withSukebei: boolean } ): number => { const res = db .query( `INSERT INTO sync_runs (author, started_at, status, with_detail, with_sukebei) VALUES (?, ?, 'running', ?, ?)` ) .run(author, nowMs(), flags.withDetail ? 1 : 0, flags.withSukebei ? 1 : 0); return Number(res.lastInsertRowid); }; export interface FinishRunArgs { status: SyncRunStatus; counts?: { newWorks?: number; priceChanges?: number; newMagnets?: number }; errorMessage?: string | null; } export const finishRun = (db: Database, id: number, args: FinishRunArgs): void => { const counts = args.counts ?? {}; db.query( `UPDATE sync_runs SET finished_at = ?, status = ?, new_works = ?, price_changes = ?, new_magnets = ?, error_message = ? WHERE id = ?` ).run( nowMs(), args.status, counts.newWorks ?? 0, counts.priceChanges ?? 0, counts.newMagnets ?? 0, args.errorMessage ?? null, id ); }; export const lastSuccessfulRun = (db: Database, author?: string): SyncRunRow | null => { const record = author ? db .query( `SELECT * FROM sync_runs WHERE author = ? AND status IN ('ok','partial') AND finished_at IS NOT NULL ORDER BY finished_at DESC LIMIT 1` ) .get(author) : db .query( `SELECT * FROM sync_runs WHERE status IN ('ok','partial') AND finished_at IS NOT NULL ORDER BY finished_at DESC LIMIT 1` ) .get(); return record ? toRow(record) : null; };