-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
1232 lines (1022 loc) · 50.9 KB
/
Copy path.cursorrules
File metadata and controls
1232 lines (1022 loc) · 50.9 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Smart Split - Cursor Rules
# VERSION: 2.7.0 | LAST UPDATED: 2024-12-16
#
# ╔═══════════════════════════════════════════════════════════════════════════╗
# ║ SELF-EVOLVING RULESET ║
# ║ This file MUST be updated at the end of every conversation. ║
# ║ Read the EVOLUTION PROTOCOL section for instructions. ║
# ╚═══════════════════════════════════════════════════════════════════════════╝
---
## EVOLUTION PROTOCOL
### How This File Evolves:
1. **START of conversation**: Read this entire file to understand current state
2. **DURING conversation**: Note any new patterns, decisions, or learnings
3. **END of conversation**: Update relevant sections below:
- Add to LEARNINGS LOG with date
- Move resolved items from PENDING to LEARNINGS
- Add new questions to PENDING DECISIONS
- Update MISTAKES & CORRECTIONS if errors were made
- Increment version if significant changes
### Version Format: MAJOR.MINOR.PATCH
- MAJOR: Breaking architecture changes
- MINOR: New features/patterns added
- PATCH: Small fixes, clarifications
---
## PROJECT IDENTITY
- **Name**: Smart Split
- **Type**: Expense sharing application (Splitwise clone)
- **Stack**: Next.js 16 (App Router), TypeScript, Supabase, Tailwind CSS 4
- **Started**: 2024-12-10
- **Supabase Project**: your-project-ref
---
## TECH STACK RULES
### Frontend
- **Framework**: Next.js 16 with App Router ONLY (no Pages Router)
- **Styling**: Tailwind CSS ONLY - no CSS modules, styled-components, or inline styles
- **Components**: React Server Components by default, "use client" only when necessary
- **Icons**: lucide-react ONLY
- **Fonts**: Plus Jakarta Sans (headings), Inter (body) via next/font
- **Images**: Always use `next/image` with configured domains in `next.config.ts`
- **Charts**: recharts for data visualization
### Backend
- **Database**: Supabase (PostgreSQL)
- **Auth**: Supabase Auth (email/password, Google OAuth, GitHub OAuth)
- **API**: Server Actions preferred over API routes
- **File Storage**: Supabase Storage (avatars bucket configured)
### Form Handling
- **Validation**: Zod schemas
- **Forms**: react-hook-form with @hookform/resolvers
### Testing
- **Framework**: Jest with React Testing Library
- **Config**: `jest.config.ts` with Next.js integration
- **Setup**: `jest.setup.ts` for global mocks
- **Pattern**: Mirror `src/` structure in `src/__tests__/`
### Dependencies (Current)
```json
{
"next": "16.0.8",
"react": "19.2.1",
"@supabase/supabase-js": "^2.87.1",
"@supabase/ssr": "^0.8.0",
"tailwindcss": "^4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"tailwind-merge": "^3.4.0",
"lucide-react": "^0.559.0",
"react-hook-form": "^7.68.0",
"zod": "^4.1.13",
"jest": "^30.2.0",
"@testing-library/react": "^16.3.0",
"@testing-library/jest-dom": "^6.9.1",
"qrcode.react": "^4.2.0",
"html5-qrcode": "^2.3.8",
"recharts": "^2.x",
"@upstash/redis": "^1.x",
"@upstash/ratelimit": "^2.x"
}
```
---
## ARCHITECTURE PRINCIPLES
### SOLID
1. **Single Responsibility**: One component/function = one job
2. **Open/Closed**: Extend via props/composition, don't modify existing components
3. **Liskov Substitution**: Components should be interchangeable with their abstractions
4. **Interface Segregation**: Small, focused interfaces over large ones
5. **Dependency Inversion**: Depend on abstractions (services, hooks), not implementations
### DRY (Don't Repeat Yourself)
- Extract repeated logic into hooks (`src/hooks/`)
- Extract repeated UI into components (`src/components/`)
- Centralize API calls in services (`src/services/`)
- Use the `cn()` utility for className merging
### Separation of Concerns
```
src/
├── app/ # Routes and page components ONLY
│ ├── (auth)/ # Auth route group (login, register)
│ ├── (dashboard)/ # Protected dashboard routes
│ ├── feedback/ # Public feedback page
│ └── auth/callback/ # OAuth callback handler
├── components/
│ ├── ui/ # Base reusable components (Button, Input, Card)
│ ├── forms/ # Form-specific components
│ ├── layout/ # Navbar, Footer, Sidebar
│ └── features/ # Feature-specific components
├── services/ # Business logic and Supabase calls
├── hooks/ # Custom React hooks
├── lib/ # Utilities, configs, Supabase clients
├── types/ # TypeScript interfaces and types
└── __tests__/ # Jest test files (mirrors src/ structure)
```
---
## CODE STYLE
### TypeScript
- Strict mode enabled
- Explicit return types on exported functions
- Use `interface` for object shapes, `type` for unions/primitives
- No `any` - use `unknown` if type is truly unknown
### Components
- Functional components only
- Props interface named `{ComponentName}Props`
- Use forwardRef for components that need ref access
- Export named exports (not default) for non-page components
### Naming Conventions
- **Files**: kebab-case (`expense-card.tsx`)
- **Components**: PascalCase (`ExpenseCard`)
- **Hooks**: camelCase with `use` prefix (`useExpenses`)
- **Services**: camelCase (`profileService`)
- **Types**: PascalCase (`Expense`, `CreateExpenseInput`)
- **Tests**: `*.test.ts` or `*.test.tsx`
### Tailwind
- Use `cn()` utility for conditional classes
- Mobile-first responsive design
- Dark mode support via `dark:` prefix
- Custom colors defined in `globals.css` under `@theme`
---
## ESTABLISHED PATTERNS
### UI Components Pattern (src/components/ui/)
```tsx
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
import { cva, type VariantProps } from "class-variance-authority";
const componentVariants = cva("base-classes", {
variants: { variant: {}, size: {} },
defaultVariants: {},
});
interface ComponentProps extends React.HTMLAttributes<HTMLElement>,
VariantProps<typeof componentVariants> {}
const Component = forwardRef<HTMLElement, ComponentProps>(
({ className, variant, size, ...props }, ref) => (
<element
ref={ref}
className={cn(componentVariants({ variant, size, className }))}
{...props}
/>
)
);
Component.displayName = "Component";
export { Component, componentVariants };
```
### Service Pattern (src/services/)
```tsx
import { createClient } from "@/lib/supabase/client";
export const myService = {
async getData(id: string) {
const supabase = createClient();
const { data, error } = await supabase
.from("table")
.select("*")
.eq("id", id)
.single();
if (error) return null;
return data;
},
async updateData(id: string, input: UpdateInput) {
const supabase = createClient();
const { error } = await supabase
.from("table")
.update(input)
.eq("id", id);
return { success: !error, error: error?.message };
},
};
```
### Server Action Pattern
```tsx
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
export async function actionName(formData: FormData) {
const supabase = await createClient();
// 1. Extract and validate input
const input = formData.get("field") as string;
// 2. Perform operation
const { data, error } = await supabase.from("table").insert({});
// 3. Handle errors
if (error) return { error: error.message };
// 4. Revalidate and redirect on success
revalidatePath("/path");
redirect("/destination");
}
```
### OAuth Action Pattern
```tsx
"use server";
export async function signInWithGoogle() {
const supabase = await createClient();
const headersList = await headers();
const origin = headersList.get("origin") || "http://localhost:3000";
const { data, error } = await supabase.auth.signInWithOAuth({
provider: "google",
options: {
redirectTo: `${origin}/auth/callback`,
},
});
if (error) return { error: error.message };
if (data.url) redirect(data.url);
}
```
### Protected Layout Pattern
```tsx
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
export default async function ProtectedLayout({ children }) {
const supabase = await createClient();
const { data, error } = await supabase.auth.getUser();
if (error || !data?.user) {
redirect("/login");
}
// Fetch additional profile data
const { data: profile } = await supabase
.from("profiles")
.select("*")
.eq("id", data.user.id)
.single();
return <Layout user={profile}>{children}</Layout>;
}
```
### Test File Pattern
```tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Component } from "@/components/ui/component";
describe("Component", () => {
it("renders correctly", () => {
render(<Component>Text</Component>);
expect(screen.getByText("Text")).toBeInTheDocument();
});
it("handles user interaction", async () => {
const user = userEvent.setup();
const handleClick = jest.fn();
render(<Component onClick={handleClick}>Click</Component>);
await user.click(screen.getByRole("button"));
expect(handleClick).toHaveBeenCalled();
});
});
```
---
## SUPABASE PATTERNS
### Client Usage
- Browser: `import { createClient } from "@/lib/supabase/client"`
- Server Components/Actions: `import { createClient } from "@/lib/supabase/server"`
- Middleware: `import { updateSession } from "@/lib/supabase/middleware"`
### Row Level Security
- ALWAYS enable RLS on tables
- Create policies before inserting data
- Test policies in Supabase dashboard
### Storage Buckets
- `avatars` bucket created with RLS policies
- Max file size: 2MB
- Allowed types: image/jpeg, image/png, image/gif, image/webp
### Type Safety
- Generate types: `npx supabase gen types typescript --project-id your-project-ref > src/types/database.ts`
- Use generated types in services
---
## DATABASE SCHEMA
### Tables Created
| Table | Purpose |
|-------|---------|
| `profiles` | User profiles (extends auth.users) |
| `groups` | Expense sharing groups |
| `group_members` | Group membership junction |
| `expenses` | Individual expenses |
| `expense_splits` | Who owes what per expense |
| `settlements` | Payment records |
| `friendships` | Friend connections |
| `activities` | Activity feed log |
| `feedback` | User feedback, bug reports, feature requests |
| `pending_settlements` | Settlement approval workflow |
| `placeholder_members` | Non-registered group members |
### Custom Types
- `expense_category`: food, transport, entertainment, utilities, rent, shopping, travel, healthcare, groceries, other
- `split_type`: equal, exact, percentage
- `member_role`: admin, member
- `friendship_status`: pending, accepted, blocked
- `feedback_type`: suggestion, feature_request, bug_report, other
- `feedback_priority`: low, medium, high, critical
- `feedback_status`: new, reviewing, planned, in_progress, completed, declined
### Key Functions
- `get_group_balances(group_uuid)` - Calculate who owes whom in a group
- `handle_new_user()` - Auto-create profile on user signup (trigger)
- `update_updated_at_column()` - Auto-update timestamps (trigger)
- `generate_invite_code()` - Generate unique 8-char alphanumeric code
- `regenerate_group_invite_code(group_uuid)` - Reset group's invite code
- `join_group_by_invite_code(code, user_id)` - Join group with invite code
---
## TESTING RULES
### Always Create Tests For:
- New UI components (`src/__tests__/components/`)
- New services (`src/__tests__/services/`)
- New utilities (`src/__tests__/lib/`)
- Complex business logic
### Test Commands
```bash
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
```
### Coverage Thresholds
- Branches: 70%
- Functions: 70%
- Lines: 70%
- Statements: 70%
---
## SECURITY RULES
1. Never expose service role key to client
2. Always validate user input with Zod
3. Use RLS policies for data access control
4. Sanitize user-generated content before display
5. Use HTTPS in production
6. Validate file uploads (size, type) before processing
---
## PERFORMANCE RULES
1. Use React Server Components for data fetching
2. Lazy load heavy components with `dynamic()`
3. Optimize images with `next/image` (add `unoptimized` for dynamic URLs)
4. Minimize "use client" components
5. Use Suspense boundaries for loading states
---
## LEARNINGS & DECISIONS LOG
### 2024-12-16: Session 10 - System Design & Performance Optimizations
#### Redis Caching with Circuit Breaker:
- Implemented Redis caching using Upstash for serverless compatibility
- Added circuit breaker pattern to handle Redis failures gracefully
- Circuit states: CLOSED (normal) → OPEN (bypass cache) → HALF-OPEN (test)
- Configuration: 5 failures threshold, 60 second reset timeout
#### Caching Strategies Implemented:
- **Stale-While-Revalidate (SWR)**: Return stale data, refresh in background
- **Cache Stampede Protection**: Lock mechanism prevents thundering herd
- **TTL Jitter**: Random ±10% variation prevents synchronized expiration
- **Null Caching**: Cache "not found" results to prevent cache penetration
#### Rate Limiting (DDoS Protection):
- Using `@upstash/ratelimit` with Token Bucket algorithm
- Path-based limits: auth (10/15min), api (100/1min), sensitive (5/hour)
- Added to middleware via `src/proxy.ts`
- Returns 429 with `Retry-After` header when rate limited
#### Tag-Based Cache Invalidation:
- Using Next.js `unstable_cache` with semantic tags
- Tags: `user:{id}:groups`, `group:{id}:expenses`, `dashboard`, etc.
- Hybrid approach: Redis (single items) + Tags (lists/related data)
- Helper functions: `revalidateGroupTags()`, `revalidateExpenseTags()`
#### Optimistic UI:
- Created reusable hooks: `useOptimisticAction`, `useOptimisticList`, `useOptimisticToggle`
- Applied to settlement button for instant feedback
- Uses React 19's `useOptimistic` + `useTransition`
#### Compression:
- Auto-compress data >1KB using gzip before Redis storage
- ~80% size reduction on large payloads
- Transparent serialize/deserialize with `__GZIP__` prefix marker
#### Key Files Created:
- `src/lib/redis.ts` - Redis client with circuit breaker
- `src/lib/cache.ts` - Caching utilities with SWR, stampede protection
- `src/lib/rate-limit.ts` - Rate limiting configuration
- `src/lib/cache-tags.ts` - Tag definitions and helpers
- `src/lib/compression.ts` - Gzip compression utilities
- `src/hooks/use-optimistic-action.ts` - Optimistic UI hooks
- `docs/development/system-design.md` - Full documentation
#### Distributed Locking (Race Condition Prevention):
- Created `withLock()` utility for critical sections
- `LockKeys` for consistent lock key generation
- Applied to settlement recording to prevent double-settle
- Configurable TTL, retry delay, and max retries
- Fail-open behavior when Redis unavailable
#### Cache Versioning (Safe Deployments):
- Added `CACHE_VERSION` constant ("v1")
- All cache keys auto-prefixed with version
- Prevents crashes when cached data structure changes
- Bump version when: data shape changes, computation changes
- Old versioned keys expire silently (never accessed)
#### API Endpoints Added:
- `GET /api/cache/health` - Redis health check
- `GET /api/cache/stats` - Cache statistics (dev only)
- `GET /api/rate-limit/test` - Rate limit testing
---
### 2024-12-16: Session 9 - Analytics, Charts, Feedback System
#### Analytics Page with Multiple Charts:
- Created dedicated analytics page at `/groups/[id]/analytics`
- Implemented 5 different chart types using `recharts`:
1. **CategoryChart** (Donut) - Expense breakdown by category
2. **TrendChart** (Line) - Spending over time
3. **ContributionsChart** (Horizontal Bar) - Who paid what
4. **SpendByMemberChart** (Radar) - Each member's share of expenses
5. **BalancesChart** (Vertical Bar) - Member balances
#### Recharts Pattern:
```tsx
// Define custom tooltip outside component to avoid re-creation
function CustomTooltip({ active, payload, currency }: TooltipProps) {
if (active && payload?.length) {
return (
<div className="rounded-lg border bg-white p-3 shadow-lg dark:bg-gray-800">
<p className="text-sm font-semibold">{formatCurrency(payload[0].value, currency)}</p>
</div>
);
}
return null;
}
// Use ResponsiveContainer for responsive charts
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie data={data} dataKey="value" />
<Tooltip content={<CustomTooltip currency={currency} />} />
</PieChart>
</ResponsiveContainer>
```
#### Feedback System (Public):
- Created `/feedback` page accessible to both registered and unregistered users
- Feedback types: Suggestion, Feature Request, Bug Report, Other
- Priority levels for bugs: Low, Medium, High, Critical
- Auto-captures browser/device info
- Pre-fills email/name for logged-in users
- Floating feedback button on all dashboard pages
#### Feedback Components:
- `FeedbackForm` - Main form with type selection, validation
- `FeedbackButton` - Floating or inline button variants
- API route at `/api/feedback` for submissions
#### Currency on Dashboard:
- Dashboard now fetches user's preferred currency from profile
- Uses `formatCurrency(amount, currency)` for all balance displays
- Profile settings saves redirect to dashboard after save
#### Placeholder Member Handling in Charts:
```tsx
// Always check both profile and placeholder for names
const payerName = expense.paid_by_profile?.full_name
|| expense.paid_by_placeholder?.name
|| "Unknown";
const payerId = expense.paid_by || expense.paid_by_placeholder?.id || "unknown";
```
#### Key Learnings:
- Custom Tooltip components must be defined OUTSIDE the main component to avoid re-render issues
- Use `ResponsiveContainer` wrapper for all recharts components
- For expenses, always check both `paid_by_profile` AND `paid_by_placeholder` for names
- Feedback table uses permissive INSERT policy for anonymous submissions
- Floating buttons use `fixed` positioning with `z-50` for proper stacking
---
### 2024-12-16: Session 8 - Settlement Flow Implementation
#### Settlement Feature:
- Complete settlement flow for recording payments and marking splits as settled
- Settlement history component shows past settlements with expand/collapse
- Page automatically refreshes after settlement to show updated balances
- Database already accounts for settlements in `get_group_balances` function
#### New Components:
- `SettlementHistory` - Shows list of past settlements with expand/collapse
- `SimplifiedDebtsClient` - Client wrapper for SimplifiedDebts that handles page refresh
#### Settlement Flow Architecture:
1. User clicks "Settle" or "Mark Paid" button in SimplifiedDebts component
2. `groupsService.recordSettlement()` creates settlement record in database
3. Related expense_splits are marked as `is_settled = true`
4. Activity is logged for the settlement
5. `router.refresh()` triggers server-side revalidation
6. Page re-fetches balances which now account for the settlement
#### Server Service Pattern for Settlements:
```tsx
// Use !fkey syntax for foreign key joins in Supabase
const { data } = await supabase
.from("settlements")
.select(`
id, from_user, to_user, amount, settled_at, note,
from_profile:profiles!settlements_from_user_fkey(id, full_name, email),
to_profile:profiles!settlements_to_user_fkey(id, full_name, email)
`)
.eq("group_id", groupId);
// Type casting for Supabase join results
type ProfileData = { full_name: string | null; email: string };
const fromProfile = s.from_profile as unknown as ProfileData | null;
```
#### Key Learnings:
- Database function `get_group_balances` already handles settlements in balance calculation
- Use `as unknown as Type` pattern when Supabase type inference is incorrect for joins
- Client wrapper components useful for adding client-side behavior (router.refresh) to server-rendered data
---
### 2024-12-16: Session 7 - Toast Notifications Integration
#### Toast Notifications Implementation:
- Integrated `useToast` hook across all form components for user feedback
- Components updated: `add-member-form`, `group-form`, `expense-form`, `join-group-form`, `profile-form`, `group-qr-code`
- Toast shows success messages on successful operations (member added, group created, etc.)
- Toast shows error messages alongside inline form errors for visibility
#### Testing Pattern for Components with Toast:
```tsx
// Components using useToast MUST be wrapped in ToastProvider in tests
const TestWrapper = ({ children }: { children: React.ReactNode }) => (
<ToastProvider>{children}</ToastProvider>
);
// Use wrapper option in render
render(<MyComponent />, { wrapper: TestWrapper });
// When error appears in both inline and toast, use getAllByText
await waitFor(() => {
expect(screen.getAllByText("Error message").length).toBeGreaterThanOrEqual(1);
});
```
#### Key Learnings:
- Toast context requires ToastProvider wrapper - components using useToast will throw if not wrapped
- Error messages may appear in multiple places (inline form error + toast) - use `getAllByText` in tests
- Removed inline success states (`setSuccess`, `setInviteSent`) in favor of toast notifications
- Keep inline error displays for form validation (accessibility) but also show toast for visibility
---
### 2024-12-15: Session 6 - QR Code Invite System & Test Fixes
#### QR Code Group Joining Feature:
- Implemented complete QR code-based group joining system
- Added `invite_code` column to groups table (auto-generated 8-char alphanumeric)
- Database functions: `generate_invite_code()`, `regenerate_group_invite_code()`, `join_group_by_invite_code()`
- Join flow: Scan QR → Preview group → Confirm → Join as member
#### QR Code Libraries:
- `qrcode.react` - For generating QR codes (`QRCodeSVG` component)
- `html5-qrcode` - For scanning QR codes with camera
#### QR Scanner Implementation Pattern:
```tsx
// Key learnings for html5-qrcode:
// 1. Scanner container div MUST exist in DOM before calling start()
// 2. Use minHeight on container to ensure video has space to render
// 3. Add global CSS to force video visibility
// 4. Use facingMode: "environment" for back camera preference on mobile
// 5. Cleanup: call stop() in useEffect cleanup
const html5Qrcode = new Html5Qrcode("qr-reader-container");
await html5Qrcode.start(
{ facingMode: "environment" }, // Prefer back camera
{ fps: 10, qrbox: { width: 250, height: 250 } },
onScanSuccess,
onScanError
);
```
#### Camera Permission Handling:
- Request permission with `navigator.mediaDevices.getUserMedia()` before starting scanner
- Handle `NotAllowedError`, `NotFoundError`, `NotReadableError`, `OverconstrainedError`
- Provide clear error messages and retry button for users
#### UI Components Added:
- `QRScanner` - Camera-based QR scanning with error handling
- `GroupQRCode` - QR code display with copy/download/share options
- `ShareGroupButton` - Dropdown with QR code and invite link sharing
#### New Files:
- `src/components/ui/qr-scanner.tsx` - Reusable QR scanner component
- `src/components/features/groups/group-qr-code.tsx` - Group QR code display
- `src/components/features/groups/share-group-button.tsx` - Share dropdown
- `src/app/(dashboard)/groups/join/` - Join group page with form
- `src/app/api/groups/preview/route.ts` - API route for group preview
- `supabase/migrations/20241215_add_group_invite_codes.sql` - Database migration
#### Testing Patterns for Browser APIs:
**Mocking navigator.clipboard (jsdom limitation):**
```tsx
// Must use Object.defineProperty at module level, not in beforeEach
Object.defineProperty(navigator, "clipboard", {
value: { writeText: jest.fn().mockResolvedValue(undefined) },
writable: true,
configurable: true,
});
```
**Mocking html5-qrcode:**
```tsx
jest.mock("html5-qrcode", () => ({
Html5Qrcode: Object.assign(
jest.fn().mockImplementation(() => ({
start: jest.fn().mockResolvedValue(undefined),
stop: jest.fn().mockResolvedValue(undefined),
})),
{ getCameras: () => mockGetCameras() }
),
}));
```
**Mocking navigator.mediaDevices:**
```tsx
Object.defineProperty(navigator, "mediaDevices", {
value: { getUserMedia: mockGetUserMedia },
configurable: true,
});
```
#### Test Fixes Applied:
1. `simplified-debts.test.tsx` - Added required `expenses` prop, removed obsolete badge test
2. `add-member-form.test.tsx` - Updated for new 3-tab UI ("From Trips", "By Email", "New Person")
3. `expense-form.test.tsx` - Changed `getByText` to `getAllByText` for elements in multiple locations
#### Key Testing Lessons:
- When component signature changes (new required props), tests MUST be updated
- Use `getAllByText` when element text appears in multiple places (dropdown + list)
- Mocking browser APIs in jsdom requires `Object.defineProperty` with `configurable: true`
- Static methods on mocked classes need `Object.assign` pattern
- Test actual behavior, not implementation details that may change
### 2024-12-12: Session 5 - Navigation Progress & Bug Fixes
#### Navigation & Loading States:
- Created `Spinner` component with size/variant props using CVA pattern
- Created `Link` component wrapping `next/link` that triggers navigation progress
- Created `NavigationProgressProvider` context for global navigation state
- Added `loading.tsx` files for all dashboard routes with skeleton UIs
- Created `Providers` component wrapper for client-side providers in root layout
#### Navigation Progress Pattern:
```tsx
// Wrap app with provider in root layout
<Providers>{children}</Providers>
// Use enhanced Link component for automatic progress
import { Link } from "@/components/ui/link";
<Link href="/groups">Groups</Link>
// Or use hook for manual control
const { start, done, isNavigating } = useNavigationProgress();
```
#### Bug Fixes Applied:
1. **Placeholder check bug**: `split.placeholder_id !== null` returns `true` for `undefined`
- Fix: Use `!!split.placeholder_id` for truthy check covering both `undefined` and `null`
2. **Missing avatar for current user**: When `isCurrentUser` was true, `avatarUrl` stayed `null`
- Fix: Set `avatarUrl = split.participant_avatar || split.profile?.avatar_url || null`
#### UI Components Added:
- `Spinner` - Loading indicator with size (sm/md/lg/xl) and variant (default/muted/white)
- `Link` - Enhanced Next.js Link that triggers navigation progress bar
- `NavigationProgressProvider` - Context provider for navigation state
#### Loading.tsx Pattern:
```tsx
// src/app/(dashboard)/groups/loading.tsx
import { Spinner } from "@/components/ui/spinner";
import { Card, CardContent } from "@/components/ui/card";
export default function GroupsLoading() {
return (
<div className="space-y-6">
{/* Skeleton UI matching the page structure */}
<div className="h-8 w-32 animate-pulse rounded-lg bg-gray-200 dark:bg-gray-800" />
<Spinner size="md" variant="muted" />
</div>
);
}
```
#### Testing Notes:
- Components using `useSearchParams` need `Suspense` wrapper in tests
- State updates from custom hooks may not work reliably with `renderHook` + fake timers
- Focus on testing: rendering, props, function availability rather than internal state transitions
- Use `getAllByText` when multiple elements have same text (visible + sr-only)
### 2024-12-11: Session 4 - Groups, Expenses & Dark Mode
#### Groups & Expenses Feature:
- Created full CRUD for Groups and Expenses
- **Server vs Client Services**: Server Components MUST use server services (`*.server.ts`)
- Browser client (`createBrowserClient`) cannot access user session in server context
- Created `src/services/groups.server.ts` and `src/services/expenses.server.ts` for RSC usage
- Client services (`src/services/groups.ts`) still used for client-side mutations
#### RLS Policy Fixes:
- Infinite recursion in RLS: Don't query the same table in its own SELECT policy
- Fix: Create `SECURITY DEFINER` functions (`is_group_member`, `is_group_admin`)
- Groups INSERT needed permissive policy: `WITH CHECK (true)` for authenticated users
- Foreign key constraint on `created_by` requires profile to exist first
#### Dark Mode Implementation:
- Tailwind CSS v4 uses `@custom-variant dark (&:where(.dark, .dark *));` for class-based dark mode
- Theme toggle must use `useSyncExternalStore` to avoid hydration issues
- Don't call `setState` synchronously in `useEffect` - use lazy initialization instead
- Store preference in localStorage, apply `.dark` class to `document.documentElement`
#### UI Components Added:
- `Select` - Dropdown with `useId()` for SSR-safe IDs
- `Textarea` - Multi-line input
- `Badge` - Status/category badges with variants
- `ThemeToggle` - Self-contained dark/light mode toggle
#### Form ID Generation:
- Never use `Math.random()` for IDs in components - causes hydration mismatch
- Use React's `useId()` hook for SSR-safe unique IDs
### 2024-12-11: Session 3 - Vercel Deployment
#### Deployment:
- Successfully deployed to Vercel at `https://smart-split-one.vercel.app`
- Production URL is different from preview URLs (use `--prod` flag)
- Environment variables MUST be set in Vercel Dashboard before deployment
#### OAuth Production Setup:
- OAuth redirect URLs must be configured for production domain
- Google Cloud Console: Add production URL to authorized origins + redirect URIs
- Supabase Dashboard: Add production URL to Site URL and Redirect URLs
- Use `NEXT_PUBLIC_SITE_URL` env var for reliable OAuth redirects (don't rely on `headers().get("origin")`)
#### Middleware Edge Runtime:
- Middleware runs on Vercel Edge - must handle missing env vars gracefully
- Added null checks for environment variables in middleware
- Server actions also need env var validation
#### Environment Variables Pattern:
```
NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...
NEXT_PUBLIC_SITE_URL=https://your-domain.vercel.app
```
### 2024-12-10: Session 2 - Full Feature Build
#### Database & Schema:
- Created complete database schema with 8 tables
- Used `gen_random_uuid()` instead of `uuid_generate_v4()` (built-in, no extension needed)
- Added RLS policies for all tables
- Created `avatars` storage bucket with upload/delete policies
#### Authentication:
- Email/password auth working
- Google OAuth configured (requires Google Cloud Console setup)
- GitHub OAuth configured (requires GitHub Developer settings)
- OAuth callback route at `/auth/callback`
- Error handling for auth errors (otp_expired, access_denied) via URL params
#### Dashboard & Navigation:
- Created Navbar component with profile dropdown
- Mobile-responsive hamburger menu
- Navigation links: Dashboard, Groups, Expenses, Activity
- Profile dropdown with settings and logout
- Dashboard layout fetches profile from database for latest avatar
#### Profile System:
- Profile settings page with full CRUD
- Avatar upload to Supabase Storage (2MB limit, image types only)
- Avatar delete functionality
- Profile service (`src/services/profile.ts`) for all profile operations
- Form with Zod validation for name, phone, currency
#### Testing Setup:
- Jest configured with Next.js integration
- React Testing Library for component tests
- 66 tests passing across 5 test suites
- Test files mirror src/ structure
#### Image Handling:
- Configured `next.config.ts` for external images
- Allowed domains: Google (lh3.googleusercontent.com), GitHub (avatars.githubusercontent.com), Supabase storage
- Use `unoptimized` prop for dynamic Supabase URLs
### 2024-12-10: Session 1 - Project Bootstrap
#### Decisions Made:
- **Fonts**: Plus Jakarta Sans (headings) + Inter (body)
- **Primary Color**: Teal (#14b8a6)
- **Auth Layout**: Split-screen design
- **Utility Function**: `cn()` with clsx + tailwind-merge
- **Component Variants**: CVA (class-variance-authority)
#### Architecture Established:
- Supabase SSR setup with @supabase/ssr
- Middleware handles session refresh + route protection
- Protected routes pattern: `/dashboard/*` requires auth
---
## MISTAKES & CORRECTIONS
### 2024-12-16 (Session 10)
- **Mistake**: Used `unstable_cache()` wrapping functions that call Supabase `createClient()` which uses `cookies()`
- **Correction**: Remove `unstable_cache()` and use only Redis caching (`cached()`) for server-side data
- **Prevention**: `unstable_cache()` cannot contain dynamic functions (cookies, headers). Use Redis for caching with Supabase.
### 2024-12-16 (Session 9)
- **Mistake**: Tooltip components defined inside main component caused re-render issues
- **Correction**: Define custom tooltip components OUTSIDE the main chart component
- **Prevention**: Always define sub-components outside parent when used in render props
- **Mistake**: "Top Spender" showing "Unknown" instead of name
- **Correction**: Check both `paid_by_profile?.full_name` AND `paid_by_placeholder?.name`
- **Prevention**: Expenses can be paid by either registered users or placeholders - always check both
### 2024-12-15 (Session 6)
- **Mistake**: Tests using `getByText("Mom")` failed when "Mom" appeared in both dropdown and list
- **Correction**: Use `getAllByText("Mom")` and check `.length` or use more specific queries
- **Prevention**: When element text may appear multiple times, use `getAllByText` or more specific selectors
- **Mistake**: Test expected "Existing User" button but component was refactored to "By Email"
- **Correction**: Updated test to match new component text
- **Prevention**: When refactoring component UI, search for tests that may reference old text
- **Mistake**: Mocking `navigator.clipboard` in `beforeEach` caused "Cannot redefine property" error
- **Correction**: Use `Object.defineProperty` at module level with `configurable: true`
- **Prevention**: Browser API mocks must be defined at module level, not in test lifecycle hooks
- **Mistake**: html5-qrcode scanner container div didn't exist when `start()` was called
- **Correction**: Always render the container div (hidden when not active), use `minHeight` for space
- **Prevention**: DOM elements for third-party libraries must exist before library initialization
### 2024-12-11 (Session 4)
- **Mistake**: Server Components using browser Supabase client - RLS saw no authenticated user
- **Correction**: Created separate `*.server.ts` services that use server client
- **Prevention**: Always use server client in RSC, browser client only in "use client" components
- **Mistake**: RLS policy infinite recursion on `group_members` table
- **Correction**: Created `SECURITY DEFINER` functions to check membership without RLS
- **Prevention**: Never query a table within its own RLS policy SELECT clause
- **Mistake**: Hydration mismatch from `Math.random()` IDs in form components
- **Correction**: Use React's `useId()` hook for SSR-safe unique IDs
- **Prevention**: Never use non-deterministic values (Math.random, Date.now) in initial render
- **Mistake**: Calling `setState` synchronously in `useEffect` body
- **Correction**: Use `useSyncExternalStore` for mount state, lazy init for localStorage values
- **Prevention**: Effects should sync external systems, not update React state directly
- **Mistake**: Dark mode not working - CSS used `@media (prefers-color-scheme)` only
- **Correction**: Added `@custom-variant dark` in Tailwind CSS v4 for class-based dark mode
- **Prevention**: For manual theme toggle, must configure class-based dark mode
### 2024-12-11 (Session 3)
- **Mistake**: OAuth not working in production - `headers().get("origin")` returns null on Vercel
- **Correction**: Use `NEXT_PUBLIC_SITE_URL` env var instead of headers
- **Prevention**: Always use explicit env vars for site URLs, never rely on request headers
- **Mistake**: 500 errors on Vercel due to missing env vars with `!` assertion
- **Correction**: Added null checks and descriptive error messages in Supabase clients
- **Prevention**: Always validate env vars exist before using them, provide helpful error messages
- **Mistake**: Middleware crashes when env vars undefined
- **Correction**: Added early return with `NextResponse.next()` if env vars missing
- **Prevention**: Edge runtime code must handle missing config gracefully
### 2024-12-10
- **Mistake**: Used `uuid_generate_v4()` which doesn't exist in Supabase
- **Correction**: Use `gen_random_uuid()` which is built-in
- **Prevention**: Always use `gen_random_uuid()` for UUID generation
- **Mistake**: Used wrong Supabase key format (`sb_publishable_...`)
- **Correction**: Must use anon key in JWT format (`eyJ...`)
- **Prevention**: Verify key format matches JWT structure
- **Mistake**: Auth errors not handled gracefully
- **Correction**: Added `useSearchParams()` + `useMemo()` to read URL error params
- **Prevention**: Always handle error query params on auth pages
- **Mistake**: External images not loading (Google avatars)
- **Correction**: Added domains to `next.config.ts` remotePatterns
- **Prevention**: Always configure image domains for external sources
- **Mistake**: Jest import error with `next/jest`
- **Correction**: Use `next/jest.js` (with .js extension)
- **Prevention**: Check Next.js docs for correct import paths
---
## PENDING DECISIONS
- [ ] State management approach (Context vs Zustand vs none)
- [ ] Push notification implementation (Web Push vs third-party)
- [ ] Offline support requirements (PWA?)
- [ ] Settlement methods (PayPal, Venmo integration?)
- [ ] Email templates for notifications
- [ ] Mobile app strategy (React Native, PWA, or web-only?)
---
## RESOLVED DECISIONS
- [x] Image upload strategy → Supabase Storage with `avatars` bucket
- [x] Currency handling → User preference stored in profile, 8 currencies supported
- [x] Deployment platform → Vercel with `NEXT_PUBLIC_SITE_URL` for OAuth redirects