Skip to content

Commit cb6f7c0

Browse files
authored
Merge pull request #21 from weorbitant/staging
fix: error api and add docs to validate definition of the weekly endpoint
2 parents e5c5470 + 971a23f commit cb6f7c0

3 files changed

Lines changed: 143 additions & 24 deletions

File tree

app/_lib/_db/index.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,8 @@ interface LeaderboardEntry {
134134
}
135135

136136
/**
137-
* Get all transactions from the last 7 days with user details
137+
* Returns all transactions (points given or taken) from the last 7 days.
138+
* Includes messages, amounts, timestamps, and who gave/received points.
138139
*/
139140
export async function getLastWeekTransactions(): Promise<LastWeekTransaction[]> {
140141
const result = await prisma.$queryRaw<LastWeekTransaction[]>`
@@ -148,7 +149,7 @@ export async function getLastWeekTransactions(): Promise<LastWeekTransaction[]>
148149
FROM "Transaction" t
149150
JOIN "User" u_from ON u_from.id = t."fromUserId"
150151
JOIN "User" u_to ON u_to.id = t."toUserId"
151-
WHERE t.timestamp <= datetime('now', '-7 days')
152+
WHERE t.timestamp >= datetime('now', '-7 days')
152153
AND u_from.realName IS NOT NULL
153154
AND u_to.realName IS NOT NULL
154155
ORDER BY t.timestamp DESC
@@ -157,7 +158,8 @@ export async function getLastWeekTransactions(): Promise<LastWeekTransaction[]>
157158
}
158159

159160
/**
160-
* Get leaderboard with total karma received per user from last 7 days
161+
* Retrieves the leaderboard snapshot from 7 days ago.
162+
* Returns the leaderboard state as it was exactly 7 days ago (all transactions up to that point).
161163
*/
162164
export async function getLastWeekLeaderboard(): Promise<LeaderboardEntry[]> {
163165
const result = await prisma.$queryRaw<LeaderboardEntry[]>`
@@ -172,7 +174,7 @@ export async function getLastWeekLeaderboard(): Promise<LeaderboardEntry[]> {
172174
ROW_NUMBER() OVER (ORDER BY SUM(t.amount) DESC) AS rank
173175
FROM "Transaction" t
174176
WHERE
175-
t.timestamp >= datetime('now', '-7 days')
177+
t.timestamp <= datetime('now', '-7 days')
176178
AND t."toUserId" IS NOT NULL
177179
GROUP BY t."toUserId"
178180
) q
@@ -188,7 +190,8 @@ export async function getLastWeekLeaderboard(): Promise<LeaderboardEntry[]> {
188190
}
189191

190192
/**
191-
* Get leaderboard with total karma received per user from today (total karma)
193+
* Shows the current leaderboard as of today.
194+
* Returns all-time leaderboard up to and including today.
192195
*/
193196
export async function getTodayLeaderboard(): Promise<LeaderboardEntry[]> {
194197
const result = await prisma.$queryRaw<LeaderboardEntry[]>`

docs/AI_WEEKLY_SUMMARY_QUERIES.md

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# AI Weekly Summary Queries Documentation
2+
3+
## Overview
4+
5+
This document explains the behavior of the three database queries used by the AI Weekly Summary feature. These queries provide different perspectives on karma transactions and leaderboards for generating weekly summaries.
6+
7+
## Query Functions
8+
9+
### 1. `getLastWeekTransactions()`
10+
11+
**Purpose:** Returns all transactions (points given or taken) from the last 7 days.
12+
13+
**Description:**
14+
- Returns individual transaction records from the **most recent 7 days** (recent activity)
15+
- Includes full transaction details: message, amount, timestamp, running total, and user names
16+
- Used to show what happened in the current week
17+
18+
**SQL Logic:**
19+
```sql
20+
WHERE t.timestamp >= datetime('now', '-7 days')
21+
```
22+
- Gets transactions where timestamp is **greater than or equal to** 7 days ago
23+
- This means: transactions from the last 7 days (recent)
24+
25+
**Returns:**
26+
- Array of `LastWeekTransaction` objects
27+
- Each transaction includes:
28+
- `message`: The transaction message
29+
- `amount`: Karma amount (positive or negative)
30+
- `timestamp`: When the transaction occurred
31+
- `newTotal`: Running total after this transaction
32+
- `fromName`: Real name of the user who gave/took karma
33+
- `toName`: Real name of the user who received/lost karma
34+
35+
---
36+
37+
### 2. `getLastWeekLeaderboard()`
38+
39+
**Purpose:** Retrieves the leaderboard snapshot from 7 days ago.
40+
41+
**Description:**
42+
- Returns the leaderboard state **as it was exactly 7 days ago** (historical snapshot)
43+
- Shows who was leading 7 days ago, before the current week's activity
44+
- Used to compare "where we were" vs "where we are now"
45+
46+
**SQL Logic:**
47+
```sql
48+
WHERE t.timestamp <= datetime('now', '-7 days')
49+
```
50+
- Gets transactions where timestamp is **less than or equal to** 7 days ago
51+
- This means: all transactions up to 7 days ago (historical data)
52+
- Calculates totals and ranks based only on transactions that existed 7 days ago
53+
54+
**Returns:**
55+
- Array of `LeaderboardEntry` objects
56+
- Each entry includes:
57+
- `toRealName`: User's real name
58+
- `totalReceived`: Total karma received (up to 7 days ago)
59+
- `rank`: User's rank in the leaderboard (1 = highest)
60+
61+
---
62+
63+
### 3. `getTodayLeaderboard()`
64+
65+
**Purpose:** Shows the current leaderboard as of today.
66+
67+
**Description:**
68+
- Returns the **all-time leaderboard** up to and including today
69+
- Shows the current state of who has the most karma overall
70+
- Used to show "where we are now"
71+
72+
**SQL Logic:**
73+
```sql
74+
WHERE date(t.timestamp) <= date('now')
75+
```
76+
- Gets all transactions up to and including today
77+
- This means: all historical transactions (no time limit)
78+
- Calculates totals and ranks based on all transactions ever
79+
80+
**Returns:**
81+
- Array of `LeaderboardEntry` objects
82+
- Each entry includes:
83+
- `toRealName`: User's real name
84+
- `totalReceived`: Total karma received (all-time)
85+
- `rank`: User's current rank in the leaderboard (1 = highest)
86+
87+
---
88+
89+
## Key Differences
90+
91+
| Query | Time Range | Purpose | Use Case |
92+
|-------|-----------|---------|----------|
93+
| `getLastWeekTransactions` | **Last 7 days** (recent) | Show recent activity | "What happened this week?" |
94+
| `getLastWeekLeaderboard` | **Up to 7 days ago** (historical) | Show past state | "Where were we last week?" |
95+
| `getTodayLeaderboard` | **All time up to today** | Show current state | "Where are we now?" |
96+
97+
## Visual Timeline Example
98+
99+
```
100+
Timeline: [14 days ago] [7 days ago] [Today]
101+
|--------------|--------------|
102+
103+
getLastWeekLeaderboard: [============] (up to 7 days ago)
104+
getLastWeekTransactions: [========] (last 7 days)
105+
getTodayLeaderboard: [========================] (all time)
106+
```
107+
108+
## Related Files
109+
110+
- `app/_lib/_db/index.ts`: Query implementations
111+
- `app/_lib/_agent/agent.ts`: Query usage in AI agent
112+
- `tests/e2e/aiWeeklySummary/aiWeeklySummary.spec.ts`: Test suite

tests/e2e/aiWeeklySummary/aiWeeklySummary.spec.ts

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -115,14 +115,18 @@ describe('aiWeeklySummary', () => {
115115
},
116116
})
117117
await aiWeeklySummary('C123', 'prompt')
118-
const expectedLeaderboard = [
118+
// Transaction from today should appear in getLastWeekTransactions (last 7 days) and getTodayLeaderboard (all time)
119+
// but NOT in getLastWeekLeaderboard (snapshot from 7 days ago)
120+
const expectedLastWeekTransactions = [
119121
{
120-
toRealName: 'User 2',
121-
totalReceived: 100,
122-
rank: 1,
122+
message: 'Test message',
123+
amount: 100,
124+
timestamp: date,
125+
newTotal: 100,
126+
fromName: 'User 1',
127+
toName: 'User 2',
123128
},
124129
]
125-
// current date but in format for example yyyy-mm-ddThh:mm
126130
const expectedTodayLeaderboard = [
127131
{
128132
toRealName: 'User 2',
@@ -131,9 +135,9 @@ describe('aiWeeklySummary', () => {
131135
},
132136
]
133137
const expectedToolResults = {
134-
getLastWeekLeaderboard: expectedLeaderboard,
135-
getLastWeekTransactions: [],
136-
getTodayLeaderboard: expectedTodayLeaderboard,
138+
getLastWeekLeaderboard: [], // Empty - today's transaction is not in snapshot from 7 days ago
139+
getLastWeekTransactions: expectedLastWeekTransactions, // Today is within last 7 days
140+
getTodayLeaderboard: expectedTodayLeaderboard, // All time up to today
137141
}
138142
// Second call: message composition
139143
expect(mockCreateChatCompletion).toHaveBeenNthCalledWith(
@@ -167,7 +171,7 @@ describe('aiWeeklySummary', () => {
167171
)
168172
})
169173

170-
it('should correctly filter transactions by date: last week vs this week', async () => {
174+
it('should correctly filter transactions by date: validates getLastWeekTransactions (last 7 days), getLastWeekLeaderboard (snapshot from 7 days ago), and getTodayLeaderboard (all time)', async () => {
171175
// Create two users
172176
const sender1 = await prisma.user.create({
173177
data: {
@@ -259,23 +263,23 @@ describe('aiWeeklySummary', () => {
259263

260264
await aiWeeklySummary('C123', 'prompt')
261265

262-
// Expected results: getLastWeekTransactions should include transaction from last week (8 days ago)
266+
// Expected results: getLastWeekTransactions should include transaction from this week (3 days ago - within last 7 days)
263267
const expectedLastWeekTransactions = [
264268
{
265-
message: 'Last week karma',
266-
amount: 50,
267-
timestamp: lastWeekDate,
268-
newTotal: 50,
269-
fromName: 'Sender 1',
270-
toName: 'Receiver 1',
269+
message: 'This week karma',
270+
amount: 100,
271+
timestamp: thisWeekDate,
272+
newTotal: 100,
273+
fromName: 'Sender 2',
274+
toName: 'Receiver 2',
271275
},
272276
]
273277

274-
// Expected results: getLastWeekLeaderboard should include transaction from this week (3 days ago), NOT last week
278+
// Expected results: getLastWeekLeaderboard should include transaction from last week (8 days ago - snapshot from 7 days ago)
275279
const expectedLastWeekLeaderboard = [
276280
{
277-
toRealName: 'Receiver 2',
278-
totalReceived: 100,
281+
toRealName: 'Receiver 1',
282+
totalReceived: 50,
279283
rank: 1,
280284
},
281285
]

0 commit comments

Comments
 (0)