Branchwell

Skillfarm / website · skillfarm.ai / src / lib / points.ts

Raw 2.5 KB on 1483ab8a067e2125e25ab4212527521810bbb6af
1import type { Env, User } from '../env';
2import { mail } from './email';
3import { tierFor, tierIndex } from './tiers';
4import { newId, now } from './util';
5
6export type Grant = { userId: string; kind: string; amount: number; sourceType: string; sourceId: string; skillId?: string | null };
7
8/** Statements that add one ledger row (idempotent) and rebuild the cached total. Run them in one batch. */
9export function grantStatements(env: Env, g: Grant): D1PreparedStatement[] {
10 return [
11 env.DB.prepare(
12 'INSERT OR IGNORE INTO point_events (id, user_id, kind, amount, source_type, source_id, skill_id, created_at) VALUES (?,?,?,?,?,?,?,?)',
13 ).bind(newId(), g.userId, g.kind, g.amount, g.sourceType, g.sourceId, g.skillId ?? null, now()),
14 env.DB.prepare('UPDATE users SET seeds_total = MAX(0, (SELECT COALESCE(SUM(amount), 0) FROM point_events WHERE user_id = ?1)) WHERE id = ?1').bind(g.userId),
15 ];
16}
17
18/** Grant Seeds and send a tier-up notice if the grant moved the member up a tier. */
19export async function grant(env: Env, g: Grant): Promise<void> {
20 const before = await env.DB.prepare('SELECT seeds_total FROM users WHERE id = ?').bind(g.userId).first<{ seeds_total: number }>();
21 await env.DB.batch(grantStatements(env, g));
22 if (g.amount <= 0 || !before) return;
23 const after = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(g.userId).first<User>();
24 if (after && tierIndex(after.seeds_total) > tierIndex(before.seeds_total)) {
25 const t = tierFor(after.seeds_total);
26 await mail.tierUp(env, after, t.name, t.perk, after.handle);
27 }
28}
29
30/** Reverse every Seed a skill generated, for every member it paid, with one compensating row each. */
31export async function reverseSkillPoints(env: Env, skillId: string): Promise<void> {
32 const rows = await env.DB.prepare('SELECT user_id, SUM(amount) AS net FROM point_events WHERE skill_id = ? GROUP BY user_id HAVING net != 0').bind(skillId).all<{ user_id: string; net: number }>();
33 const stmts: D1PreparedStatement[] = [];
34 for (const r of rows.results) {
35 stmts.push(...grantStatements(env, { userId: r.user_id, kind: 'reversal', amount: -r.net, sourceType: 'skill', sourceId: `${skillId}:${now()}`, skillId }));
36 }
37 if (stmts.length) await env.DB.batch(stmts);
38}
39
40export const KIND_LABEL: Record<string, string> = {
41 share: 'Shared a skill',
42 install: 'Skill installed',
43 replant: 'Skill replanted',
44 review: 'Wrote a review',
45 like: 'Like received',
46 like_reversal: 'Like removed',
47 review_reversal: 'Review removed',
48 reversal: 'Skill removed',
49};