## AI Master Prompt: BetAware (Financial Guard) - MVP Generation
**1. PROJECT OVERVIEW:**
BetAware (Financial Guard) is a SaaS application designed to help individuals manage their finances in the context of increasing legal sports betting. The app addresses the growing problem of financial distress linked to sports betting, as highlighted by user problems on platforms like Hacker News. Our core value proposition is to provide users with tools and insights to track their betting expenditures, understand associated financial risks, and maintain healthy financial habits. BetAware empowers users to make informed decisions by setting spending limits, analyzing betting patterns, and receiving proactive alerts about potential financial strain. The goal is to foster responsible gambling and financial well-being.
**2. TECH STACK:**
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **ORM:** Drizzle ORM (PostgreSQL compatible - e.g., with Vercel Postgres, Neon)
* **UI Library:** shadcn/ui (for accessible, reusable components)
* **Authentication:** NextAuth.js (for robust authentication, including OAuth with Google/Apple, and email/password)
* **State Management:** React Context API / Zustand (for global state like user auth) and local component state.
* **Form Handling:** React Hook Form + Zod (for validation)
* **Charting:** Recharts or Chart.js (for data visualization)
* **Database:** PostgreSQL (recommended via Vercel Postgres, Neon, or self-hosted)
* **Deployment:** Vercel (recommended for Next.js)
**3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL syntax):**
```typescript
// Schema definition using Drizzle ORM
// Users Table
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
name: varchar('name', { length: 255 }),
email: varchar('email', { length: 255 }).notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: varchar('image', { length: 255 }),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow()
});
// Accounts Table (for NextAuth.js integration)
export const accounts = pgTable('accounts', {
id: bigserial('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: varchar('type', { length: 255 }).notNull(),
provider: varchar('provider', { length: 255 }).notNull(),
providerAccountId: varchar('providerAccountId', { length: 255 }).notNull(),
refreshToken: text('refreshToken'),
accessToken: text('accessToken'),
expiresAt: timestamp('expiresAt', { withTimezone: true, mode: 'date' }),
tokenType: varchar('tokenType', { length: 255 }),
scope: varchar('scope', { length: 255 }),
// Drizzle doesn't have a direct `refresh_token_expires_in` like some providers, handle expiration logic in the app.
});
// Sessions Table (for NextAuth.js integration)
export const sessions = pgTable('sessions', {
sessionToken: varchar('sessionToken', { length: 255 }).primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { withTimezone: true, mode: 'date' }).notNull()
});
// Verification Tokens Table (for NextAuth.js integration)
export const verificationTokens = pgTable('verificationTokens', {
identifier: varchar('identifier', { length: 255 }).notNull(),
token: varchar('token', { length: 255 }).notNull(),
expires: timestamp('expires', { withTimezone: true, mode: 'date' }).notNull()
}).primaryKey(['identifier', 'token']);
// Betting Limits Table
export const bettingLimits = pgTable('bettingLimits', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
limitType: varchar('limitType', { length: 50 }).notNull(), // e.g., 'daily', 'weekly', 'monthly'
amount: decimal('amount', { precision: 10, scale: 2 }).notNull(), // Max amount allowed
currency: varchar('currency', { length: 10 }).default('USD').notNull(),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow(),
updatedAt: timestamp('updatedAt', { mode: 'date' }).defaultNow()
});
// Betting Transactions Table
export const bettingTransactions = pgTable('bettingTransactions', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
amount: decimal('amount', { precision: 10, scale: 2 }).notNull(),
currency: varchar('currency', { length: 10 }).default('USD').notNull(),
transactionType: varchar('transactionType', { length: 50 }).notNull(), // e.g., 'bet_placed', 'winnings', 'deposit', 'withdrawal'
description: varchar('description', { length: 255 }), // e.g., 'Bet on Lakers vs Celtics'
transactionDate: timestamp('transactionDate', { mode: 'date' }).notNull().defaultNow(),
createdAt: timestamp('createdAt', { mode: 'date' }).defaultNow()
});
// Relations (implicitly defined by references, but good to document)
// - users -> bettingLimits (one-to-many)
// - users -> bettingTransactions (one-to-many)
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* **Flow:** User lands on the landing page. Clicks 'Sign Up' or 'Log In'. Presented with options: Email/Password, Google, Apple.
* **Sign Up:** Enters email, password, confirms password. Submits. Email verification (optional for MVP, but recommended). Redirected to dashboard/onboarding.
* **Log In:** Enters credentials or uses OAuth provider. Redirected to dashboard.
* **Edge Case:** Password reset flow. Invalid credentials handling. OAuth errors.
* **Manual Transaction Entry:**
* **Flow:** User navigates to 'Add Transaction' from the dashboard or navigation. Selects transaction type ('Bet Placed', 'Winnings', 'Deposit', 'Withdrawal'). Enters amount, currency (defaults to USD), an optional description (e.g., 'March Madness Final Bet'), and selects/confirms the date. Clicks 'Save'.
* **Validation:** Amount must be a positive number. Description is optional.
* **Update:** Transaction appears in the 'Transactions' list and updates relevant financial summaries and limit tracking.
* **Setting Betting Limits:**
* **Flow:** User navigates to 'Settings' > 'Betting Limits'. Sees options to set 'Daily', 'Weekly', 'Monthly' limits. Clicks 'Edit' for a limit type. Enters the desired amount (e.g., '$100' for weekly). Selects currency. Clicks 'Save'.
* **Validation:** Amount must be a non-negative number. Limits should be sensible (e.g., minimum $5).
* **Backend:** Limit data is saved associated with the user ID.
* **Dashboard & Overview:**
* **Flow:** Upon login, the user sees the main dashboard. Displays a summary: Total spent on betting this month/week, total winnings, net balance. Shows progress against set limits (e.g., 'Weekly Limit: $50/$100 used'). Features a chart visualizing spending over time (last 7 days, last 30 days). Quick access button to 'Add Transaction'.
* **Data Fetching:** Retrieves summary data, recent transactions, and limit progress from the backend based on the logged-in user.
* **Transaction History & Analysis:**
* **Flow:** User navigates to 'Transactions' page. A sortable, filterable table displays all recorded betting transactions (date, type, amount, description). User can click to edit or delete entries. A separate 'Analysis' or 'Reports' section provides charts (e.g., spending breakdown by type, spending over time, win/loss ratio).
* **Functionality:** Filtering by date range, transaction type. Sorting by date, amount.
* **Risk Alert System:**
* **Flow:** Backend logic continuously monitors new transactions against user-defined limits. If a transaction causes a limit to be approached (e.g., 80%) or exceeded, a notification is triggered. This could be an in-app notification and/or an email alert.
* **Logic:** `IF (current_spending + new_bet_amount) >= (limit * threshold_percentage) THEN trigger_alert`.
* **Edge Cases:** Alerts for exceeding daily, weekly, and monthly limits. Handling timezones for daily/weekly/monthly calculations.
**5. API & DATA FETCHING (Next.js App Router - Server Actions & Route Handlers):**
* **Authentication:** Handled by NextAuth.js (uses server actions internally).
* **Transactions API (`/api/transactions` or Server Actions):
* `POST /api/transactions` (or `addTransaction` Server Action): Adds a new betting transaction. Request Body: `{ amount: number, currency: string, description?: string, type: string, date: string }`. Response: `{ success: boolean, id?: string, error?: string }`.
* `GET /api/transactions` (or `getTransactions` Server Action): Fetches transactions for the logged-in user, with support for pagination, filtering (`?type=bet_placed&startDate=...&endDate=...`). Response: `[{ id, amount, currency, description, type, date }, ...]`. Server fetches and returns data.
* `PUT /api/transactions/:id` (or `updateTransaction` Server Action): Updates an existing transaction. Request Body: (similar to POST). Response: `{ success: boolean, error?: string }`.
* `DELETE /api/transactions/:id` (or `deleteTransaction` Server Action): Deletes a transaction. Response: `{ success: boolean, error?: string }`.
* **Limits API (`/api/limits` or Server Actions):
* `GET /api/limits` (or `getLimits` Server Action): Fetches betting limits for the user. Response: `[{ limitType, amount, currency }, ...]`. Server fetches.
* `PUT /api/limits` (or `updateLimit` Server Action): Updates or sets a betting limit. Request Body: `{ limitType: string, amount: number, currency: string }`. Response: `{ success: boolean, error?: string }`.
* **Dashboard Summary API (`/api/dashboard` or Server Actions):
* `GET /api/dashboard` (or `getDashboardData` Server Action): Fetches aggregated data for the dashboard. Response: `{ totalSpent: number, totalWinnings: number, netBalance: number, limitProgress: { daily, weekly, monthly }, recentTransactions: [...] }`. Server performs calculations.
**Data Fetching in Components:** Primarily using Server Components where possible for direct data access. Client Components will use Server Actions or fetch data from API routes defined above, passing user auth info implicitly via cookies/session.
**6. UI/UX DESIGN & VISUAL IDENTITY:**
* **Design Style:** Minimalist Clean with subtle Gamification elements.
* **Color Palette:**
* Primary (Brand): `#007AFF` (Calm Blue)
* Secondary (Accent/Action): `#34C759` (Positive Green)
* Alert/Warning: `#FF9500` (Vivid Orange)
* Danger/Over Limit: `#FF3B30` (Strong Red)
* Background: `#F2F2F7` (Light Gray)
* Card/Element Background: `#FFFFFF` (White)
* Text (Primary): `#1C1C1E` (Near Black)
* Text (Secondary): `#8E8E93` (Gray)
* **Typography:** San Francisco (system font) or Inter. Use clear hierarchy (e.g., `font-bold text-2xl` for headings, `font-medium text-base` for body).
* **Layout:** Clean, card-based dashboard. Sidebar navigation for authenticated users. Centered forms for input. Responsive grid system.
* **Interactivity:** Smooth transitions on hover effects, subtle loading indicators (spinners, skeleton loaders), clear visual feedback on form submission.
* **Responsive Rules:** Mobile-first approach. Navigation collapses into a hamburger menu on smaller screens. Grids adjust column count. Ensure readability and usability across devices (phones, tablets, desktops).
**7. COMPONENT BREAKDOWN (Next.js App Router):**
* **(App) Layouts:**
* `app/layout.tsx`: Root layout (HTML, Body, Providers like ThemeProvider, AuthProvider).
* `app/(marketing)/layout.tsx`: Layout for marketing pages (Navbar, Footer).
* `app/(app)/layout.tsx`: Authenticated layout (Sidebar/Navbar, Main Content Area).
* **Pages (`app/(...)` directory):**
* `app/(marketing)/page.tsx`: Landing Page (Value Proposition, Features overview, Call to Action).
* `app/(marketing)/login/page.tsx`: Login Page.
* `app/(marketing)/signup/page.tsx`: Sign Up Page.
* `app/(app)/dashboard/page.tsx`: Main Dashboard (Summary cards, Charts, Limit Progress).
* `app/(app)/transactions/page.tsx`: Transactions List Page (Table, Filters, Add Button).
* `app/(app)/transactions/[id]/edit/page.tsx`: Edit Transaction Page (Form).
* `app/(app)/limits/page.tsx`: Betting Limits Setting Page (Form).
* `app/(app)/reports/page.tsx`: Detailed Reports/Analysis Page (Advanced Charts).
* `app/(app)/settings/page.tsx`: User Settings (Profile, Notifications).
* `app/api/auth/[...nextauth]/route.ts`: NextAuth.js API route.
* `app/api/transactions/route.ts` (if not using Server Actions exclusively).
* **UI Components (`components/ui`, `components/`):
* `Button`: Primary action, secondary actions.
* `Input`: Standard text input.
* `Label`: Form label.
* `Card`, `CardHeader`, `CardContent`: For dashboard widgets.
* `Sheet`, `SheetContent`, `SheetTrigger`: For mobile navigation or quick forms.
* `Dialog`, `DialogContent`, `DialogTrigger`: For confirmation modals.
* `DataTable`: For displaying transactions.
* `ChartComponent`: Wrapper for Recharts/Chart.js.
* `LimitProgress`: Custom component showing limit usage bar.
* `Navbar`, `Sidebar`, `Footer`: Site-wide navigation.
* `Notification`: In-app alert display.
* `Alert`, `AlertTitle`, `AlertDescription`: For displaying risk warnings.
* `FormField`, `FormItem`, `FormLabel`, `FormControl`, `FormMessage`: From shadcn/ui for forms.
* `Skeleton`: For loading states.
* **State Management:**
* Global (Auth state, User settings): React Context or Zustand.
* Page/Component Level: `useState`, `useReducer` for forms, local UI states (e.g., modal open/closed).
* Server Actions handle data mutations, often returning updated data to re-render components.
**8. ANIMATIONS:**
* **Page Transitions:** Subtle fade-in/fade-out using Next.js `useRouter` events or a library like `Framer Motion` (optional, can add complexity).
* **Button Hovers:** Slight scale-up or background color change.
* **Loading States:** Use `Skeleton` components from shadcn/ui while data is fetching. Implement spinners within buttons during form submission.
* **Chart Transitions:** Animate chart data loading and updates.
* **Element Transitions:** Use Tailwind CSS transitions (`transition-all duration-300 ease-in-out`) for properties like background color, transform, opacity on hover or state changes.
**9. EDGE CASES & VALIDATION:**
* **Authentication:** Ensure secure session management. Handle token refresh. Implement rate limiting on login attempts.
* **Authorization:** Protect all `/app/*` routes, ensuring only logged-in users can access them. Server-side checks are crucial.
* **Data Validation:** Use Zod with React Hook Form for all user inputs (limits, transaction amounts, forms). Server-side validation is mandatory for all API routes and Server Actions.
* **Empty States:** Design clear UI for when there are no transactions, no limits set, or no report data available (e.g., 'No transactions yet. Add your first one!').
* **Error Handling:** Graceful error display for API failures, validation errors, or unexpected issues. Use `try...catch` blocks in Server Actions and API routes. Show user-friendly messages.
* **Zero/Negative Amounts:** Prevent saving transactions or limits with zero or negative amounts where inappropriate.
* **Concurrency:** Handle potential race conditions if multiple updates happen simultaneously (less critical for MVP but good to consider for scaling).
* **Timezones:** Ensure dates and times (especially for daily/weekly/monthly limits) are handled consistently, ideally storing in UTC and converting for display based on user locale if available.
**10. SAMPLE/MOCK DATA:**
* **User Profile:**
* `{ id: 'user-123', name: 'Alex Johnson', email: 'alex.j@example.com', image: 'https://...', createdAt: '2024-01-15T10:00:00Z' }`
* **Betting Limits:**
* `{ id: 'limit-daily-abc', userId: 'user-123', limitType: 'daily', amount: 50.00, currency: 'USD', updatedAt: '2024-05-10T09:00:00Z' }`
* `{ id: 'limit-weekly-def', userId: 'user-123', limitType: 'weekly', amount: 150.00, currency: 'USD', updatedAt: '2024-05-10T09:00:00Z' }`
* **Betting Transactions (Recent):**
* `{ id: 'txn-1', userId: 'user-123', amount: 25.00, currency: 'USD', description: 'NBA Finals Game 1 Bet', transactionType: 'bet_placed', transactionDate: '2024-05-10T20:30:00Z' }`
* `{ id: 'txn-2', userId: 'user-123', amount: 75.00, currency: 'USD', description: 'Successful Parlay Bet', transactionType: 'winnings', transactionDate: '2024-05-09T23:15:00Z' }`
* `{ id: 'txn-3', userId: 'user-123', amount: 10.00, currency: 'USD', description: 'Small bet on Tennis', transactionType: 'bet_placed', transactionDate: '2024-05-09T15:00:00Z' }`
* `{ id: 'txn-4', userId: 'user-123', amount: 30.00, currency: 'USD', description: 'Horse Racing Bet', transactionType: 'bet_placed', transactionDate: '2024-05-08T14:00:00Z' }`
* `{ id: 'txn-5', userId: 'user-123', amount: 200.00, currency: 'USD', description: 'Deposit to betting account', transactionType: 'deposit', transactionDate: '2024-05-07T11:00:00Z' }`
* **Dashboard Summary (Example Calculation based on above):**
* `{ totalSpent: 65.00, totalWinnings: 75.00, netBalance: 10.00, limitProgress: { daily: { used: 35.00, limit: 50.00, percentage: 70 }, weekly: { used: 65.00, limit: 150.00, percentage: 43.33 } }, recentTransactions: [...] }`
This comprehensive prompt provides the AI with all necessary details to generate a functional, multi-page Next.js MVP application for BetAware.