File size: 2,036 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Skill tree multiplier resolution.
 *
 * Looks up a user's unlocked multiplier nodes for a given category
 * and sums their percentage bonuses. Multiplier nodes have descriptions
 * following the pattern "+N% Category XP".
 */

import type { Prisma } from "@prisma/client";

/**
 * Parse the multiplier percentage from a skill tree node description.
 * Expected format: "+10% Chess XP", "+25% Reading XP", etc.
 * Returns 0 if the description doesn't match.
 */
export function parseMultiplierPercent(description: string): number {
  const match = description.match(/^\+(\d+)%\s/);
  if (!match) return 0;
  return parseInt(match[1], 10);
}

/**
 * Get the total multiplier percentage for a user in a specific category.
 *
 * Queries the user's unlocked skill tree nodes of type "multiplier" for the
 * given category, parses each node's percentage from its description, and
 * returns the sum.
 *
 * @param tx - Prisma client or transaction
 * @param userId - The user's ID
 * @param category - The exercise category (e.g. "chess", "reading")
 * @returns Total multiplier percentage (e.g. 35 means +35% XP)
 */
/** Minimal shape of a Prisma-like client accepted by getMultiplierPercent. */
export interface MultiplierTx {
  unlock: {
    findMany: (args: Record<string, unknown>) => Promise<Array<{ node: { description: string } }>>;
  };
  skillTreeNode: {
    findMany: (args: Record<string, unknown>) => Promise<unknown[]>;
  };
}

export async function getMultiplierPercent(
  tx: Prisma.TransactionClient | MultiplierTx,
  userId: number,
  category: string,
): Promise<number> {
  // Find all unlocked multiplier nodes for this user + category
  const unlocks = await tx.unlock.findMany({
    where: {
      userId,
      node: {
        category,
        nodeType: "multiplier",
      },
    },
    include: {
      node: {
        select: { description: true },
      },
    },
  });

  let total = 0;
  for (const unlock of unlocks) {
    total += parseMultiplierPercent(unlock.node.description);
  }

  return total;
}