-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.ts
More file actions
77 lines (63 loc) · 2.08 KB
/
sync.ts
File metadata and controls
77 lines (63 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { CronJob } from "cron";
import { loadConfig } from "./config";
import { getAdapter } from "./adapters/index";
import { getDb, marks as marksTable } from "./db";
import { appendDayLog } from "./memory";
import { runAgent } from "./agent";
import { sql } from "drizzle-orm";
async function syncOnce() {
const config = loadConfig();
const adapter = getAdapter(config.adapter);
console.log(`[sync] Starting sync with adapter: ${config.adapter}`);
const token = await adapter.authenticate(config.credentials);
const to = new Date();
const from = new Date();
from.setDate(from.getDate() - 7);
const newMarks = await adapter.getMarks(token, from, to);
console.log(`[sync] Fetched ${newMarks.length} marks`);
const db = getDb();
const now = new Date().toISOString();
let inserted = 0;
for (const mark of newMarks) {
try {
db.insert(marksTable)
.values({
subject: mark.subject,
value: mark.value,
weight: mark.weight,
date: mark.date,
comment: mark.comment ?? null,
syncedAt: now,
})
.onConflictDoNothing()
.run();
inserted++;
} catch {
// duplicate — skip
}
}
console.log(`[sync] Inserted ${inserted} new marks`);
if (inserted > 0) {
const today = new Date().toISOString().slice(0, 10);
const summary = newMarks
.map((m) => `- ${m.subject}: ${m.value} (вес ${m.weight})${m.comment ? ` — ${m.comment}` : ""}`)
.join("\n");
appendDayLog(today, `### Sync ${now}\n${summary}`);
console.log("[sync] Running agent on new marks...");
await runAgent("sync");
}
}
// Run as standalone process with cron
const config = loadConfig();
console.log(`[sync] Scheduling with cron: ${config.sync_cron}`);
const job = new CronJob(config.sync_cron, async () => {
try {
await syncOnce();
} catch (err) {
console.error("[sync] Error:", err);
}
});
// Run once on start
syncOnce().catch((err) => console.error("[sync] Initial sync error:", err));
job.start();
console.log("[sync] Sync process running. Press Ctrl+C to stop.");