File size: 3,891 Bytes
5bd4e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
import type { Account, AccountKind, LedgerStore, Transaction } from "./types.js";

/** Typed subset of the wallet schema (see supabase/migrations). */
export interface WalletDatabase {
  public: {
    Tables: {
      wallet_accounts: { Row: { id: string; user_id: string; kind: AccountKind; currency: string }; Insert: { id?: string; user_id: string; kind: AccountKind; currency: string }; Update: Partial<Account>; Relationships: [] };
      wallet_transactions: {
        Row: { id: string; user_id: string; kind: string; idempotency_key: string; memo: string | null; created_at: string };
        Insert: { id: string; user_id: string; kind: string; idempotency_key: string; memo?: string | null; created_at?: string };
        Update: Record<string, never>; Relationships: [];
      };
      wallet_postings: {
        Row: { id: number; transaction_id: string; account_id: string; amount: number };
        Insert: { transaction_id: string; account_id: string; amount: number };
        Update: Record<string, never>; Relationships: [];
      };
    };
    Views: { wallet_account_balances: { Row: { account_id: string; balance: number }; Relationships: [] } };
    Functions: {
      wallet_post_transaction: {
        Args: { p_id: string; p_user_id: string; p_kind: string; p_key: string; p_memo: string | null; p_postings: unknown };
        Returns: string;
      };
    };
    Enums: { [_ in never]: never }; CompositeTypes: { [_ in never]: never };
  };
}

export class SupabaseStore implements LedgerStore {
  private db: SupabaseClient<WalletDatabase>;
  constructor(url: string, serviceKey: string) {
    this.db = createClient<WalletDatabase>(url, serviceKey, { auth: { persistSession: false } });
  }
  async getOrCreateAccount(userId: string, kind: AccountKind, currency: string): Promise<Account> {
    const { data, error } = await this.db.from("wallet_accounts")
      .upsert({ user_id: userId, kind, currency }, { onConflict: "user_id,kind,currency", ignoreDuplicates: false })
      .select().single();
    if (error) throw error;
    return data as Account;
  }
  async findTransactionByKey(userId: string, key: string): Promise<Transaction | null> {
    const { data, error } = await this.db.from("wallet_transactions")
      .select("*, wallet_postings(account_id, amount)").eq("user_id", userId).eq("idempotency_key", key).maybeSingle();
    if (error) throw error;
    return data ? toTx(data) : null;
  }
  async insertTransaction(tx: Transaction): Promise<void> {
    // Atomic insert via SQL function (single DB transaction, balance check enforced in SQL).
    const { error } = await this.db.rpc("wallet_post_transaction", {
      p_id: tx.id, p_user_id: tx.user_id, p_kind: tx.kind, p_key: tx.idempotency_key,
      p_memo: tx.memo ?? null, p_postings: tx.postings,
    });
    if (error) throw error;
  }
  async balance(accountId: string): Promise<number> {
    const { data, error } = await this.db.from("wallet_account_balances").select("balance").eq("account_id", accountId).maybeSingle();
    if (error) throw error;
    return Number(data?.balance ?? 0);
  }
  async listTransactions(userId: string, limit = 50): Promise<Transaction[]> {
    const { data, error } = await this.db.from("wallet_transactions")
      .select("*, wallet_postings(account_id, amount)").eq("user_id", userId).order("created_at", { ascending: false }).limit(limit);
    if (error) throw error;
    return (data ?? []).map(toTx);
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toTx(r: any): Transaction {
  return { id: r.id, user_id: r.user_id, kind: r.kind, idempotency_key: r.idempotency_key, memo: r.memo ?? undefined,
    created_at: r.created_at, postings: (r.wallet_postings ?? []).map((p: any) => ({ account_id: p.account_id, amount: Number(p.amount) })) };
}