Branchwell

Become a Pro / website · becomeapro.ai / src / lib / account-store.ts

Raw 6.1 KB on 6c7ce85c3441baadd17890ab9cc9bf8ed5112901
1import { getCloudflareContext } from "@opennextjs/cloudflare";
2import { parseSurvey, type AiSurvey } from "@/lib/ai-survey";
3import { parseProfile, profileRow, type LearningProfile } from "@/lib/onboarding";
4import type { AccountUser } from "@/lib/session-server";
5
6type AccountStore = {
7 saved(): Promise<string[]>;
8 profile(): Promise<LearningProfile | null>;
9 progress(): Promise<string[]>;
10 survey(): Promise<AiSurvey | null>;
11 setSaved(key: string, saved: boolean): Promise<void>;
12 setProfile(profile: LearningProfile): Promise<LearningProfile>;
13 setProgress(keys: string[], completed: boolean): Promise<void>;
14 recordView(key: string): Promise<void>;
15 setSurvey(survey: AiSurvey | null): Promise<AiSurvey | null>;
16};
17
18type D1Statement = {
19 bind(...args: (string | null)[]): D1Statement;
20 first<T>(): Promise<T | null>;
21 all<T>(): Promise<{ results: T[] }>;
22 run(): Promise<unknown>;
23};
24type D1 = {
25 prepare(sql: string): D1Statement;
26 batch(statements: D1Statement[]): Promise<unknown>;
27};
28type TutorialRow = { tutorial_slug: string };
29type ProfileRow = { goals: string; tracks: string };
30type SurveyRow = { uses: string; tools: string };
31
32export function d1AccountStore(db: D1, user: AccountUser): AccountStore {
33 function ensureUser(now: string) {
34 return db.prepare(`
35 INSERT INTO users (id, email, full_name, avatar_url, created_at, updated_at)
36 VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING
37 `).bind(user.id, user.email, user.name || null, user.image ?? null, new Date(user.createdAt).toISOString(), now);
38 }
39
40 return {
41 async saved() {
42 const { results } = await db.prepare(
43 "SELECT tutorial_slug FROM saved_tutorials WHERE user_id = ? ORDER BY created_at DESC",
44 ).bind(user.id).all<TutorialRow>();
45 return results.map((row) => row.tutorial_slug);
46 },
47 async profile() {
48 const row = await db.prepare("SELECT * FROM learning_profiles WHERE user_id = ?")
49 .bind(user.id).first<ProfileRow>();
50 return row ? parseProfile({ ...row, goals: JSON.parse(row.goals), tracks: JSON.parse(row.tracks) }) : null;
51 },
52 async progress() {
53 const { results } = await db.prepare(
54 "SELECT tutorial_slug FROM tutorial_activity WHERE user_id = ? AND completed_at IS NOT NULL",
55 ).bind(user.id).all<TutorialRow>();
56 return results.map((row) => row.tutorial_slug);
57 },
58 async survey() {
59 const row = await db.prepare("SELECT * FROM ai_surveys WHERE user_id = ?").bind(user.id).first<SurveyRow>();
60 return row ? parseSurvey({ ...row, uses: JSON.parse(row.uses), tools: JSON.parse(row.tools) }) : null;
61 },
62 async setSaved(key, saved) {
63 if (!saved) {
64 await db.prepare("DELETE FROM saved_tutorials WHERE user_id = ? AND tutorial_slug = ?").bind(user.id, key).run();
65 return;
66 }
67 const now = new Date().toISOString();
68 await db.batch([ensureUser(now), db.prepare(`
69 INSERT INTO saved_tutorials (user_id, tutorial_slug, created_at) VALUES (?, ?, ?)
70 ON CONFLICT (user_id, tutorial_slug) DO NOTHING
71 `).bind(user.id, key, now)]);
72 },
73 async setProfile(profile) {
74 const row = profileRow(user.id, profile);
75 await db.batch([ensureUser(row.updated_at), db.prepare(`
76 INSERT INTO learning_profiles (user_id, goals, tracks, level, weekly_time, format, created_at, updated_at)
77 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
78 ON CONFLICT (user_id) DO UPDATE SET goals=excluded.goals, tracks=excluded.tracks,
79 level=excluded.level, weekly_time=excluded.weekly_time, format=excluded.format, updated_at=excluded.updated_at
80 `).bind(row.user_id, JSON.stringify(row.goals), JSON.stringify(row.tracks), row.level,
81 row.weekly_time, row.format, row.updated_at, row.updated_at)]);
82 return { ...profile, updatedAt: row.updated_at };
83 },
84 async setProgress(keys, completed) {
85 const now = new Date().toISOString();
86 const statements = keys.map((key) => db.prepare(`
87 INSERT INTO tutorial_activity (user_id, tutorial_slug, completed_at) VALUES (?, ?, ?)
88 ON CONFLICT (user_id, tutorial_slug) DO UPDATE SET completed_at=excluded.completed_at
89 `).bind(user.id, key, completed ? now : null));
90 await db.batch([ensureUser(now), ...statements]);
91 },
92 async recordView(key) {
93 const now = new Date().toISOString();
94 await db.batch([ensureUser(now), db.prepare(`
95 INSERT INTO tutorial_activity (user_id, tutorial_slug, view_count, first_viewed_at, last_viewed_at)
96 VALUES (?, ?, 1, ?, ?)
97 ON CONFLICT (user_id, tutorial_slug) DO UPDATE
98 SET view_count=tutorial_activity.view_count+1,
99 first_viewed_at=COALESCE(tutorial_activity.first_viewed_at, excluded.first_viewed_at),
100 last_viewed_at=excluded.last_viewed_at
101 `).bind(user.id, key, now, now)]);
102 },
103 async setSurvey(survey) {
104 if (!survey) {
105 await db.prepare("DELETE FROM ai_surveys WHERE user_id = ?").bind(user.id).run();
106 return null;
107 }
108 const now = new Date().toISOString();
109 await db.batch([ensureUser(now), db.prepare(`
110 INSERT INTO ai_surveys (user_id, role, uses, uses_other, tools, daily_hours, ai_years, depth, coding, created_at, updated_at)
111 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
112 ON CONFLICT (user_id) DO UPDATE SET role=excluded.role, uses=excluded.uses, uses_other=excluded.uses_other,
113 tools=excluded.tools, daily_hours=excluded.daily_hours, ai_years=excluded.ai_years, depth=excluded.depth,
114 coding=excluded.coding, updated_at=excluded.updated_at
115 `).bind(user.id, survey.role ?? null, JSON.stringify(survey.uses), survey.usesOther ?? null, JSON.stringify(survey.tools),
116 survey.dailyHours ?? null, survey.aiYears ?? null, survey.depth ?? null, survey.coding ?? null, now, now)]);
117 return { ...survey, updatedAt: now };
118 },
119 };
120}
121
122export function accountStore(user: AccountUser): AccountStore {
123 const { ACCOUNTS_DB } = getCloudflareContext().env as { ACCOUNTS_DB?: D1 };
124 if (!ACCOUNTS_DB) throw new Error("Cloudflare D1 account binding is unavailable.");
125 return d1AccountStore(ACCOUNTS_DB, user);
126}