--- PAGE 1 --- About This Document This guide contains all 10 build phases for Mone ySmar t PNG – an AI-power ed personal finance coach designed for Papua New Guinea. Each phase is a standalone, copy‑paste ready prompt for your AI builder (Cursor , Replit, Bolt, Lovable, etc.) or developer . Rules for Using These Prompts 1. Complete and test each phase befor e moving to the next. 2. If the AI builder stops midwa y, type: “Continue from wher e you stopped. ” 3. If something breaks after a phase, type: “Revert the last change and try again. ” 4. Never paste two phases into the same prompt at once. 5. After Phase 4, test the full app befor e proceeding to Phase 5. 6. Phases 5 (Security) and 6 (Payments) must be completed befor e any real user accesses the app. Minimum Viable Launch Set If you are under time or budget pressur e, the minimum phases requir ed befor e any public launch are: Phase 1, Phase 3, Phase 5, Phase 6, and Phase 10. All other phases must follow within 30 days of launch. Tech Stack Overview Layer Technology --- PAGE 2 --- Backend Laravel 13 (PHP 8.2+) Database MySQL 8.0+ Frontend React 19 + TypeScript + Inertia.js Styling Tailwind CSS + shadcn/ui components State React Context / Zustand (optional) Auth Laravel Breeze (Inertia React stack) Payments Stripe PHP SDK + manual mobile money flow AI API Anthropic Claude (server‑side calls) Deployment Laravel Forge / Vapor, Vite build, PWA All 10 Phases at a Glance Phase Title 1 Foundation – Auth, Dashboard, Transaction Tracker, Navigation 2 Budget Planner, Smart Alerts, Savings Goals, Spending Insights 3 AI Budget Coach – Chat, Context Injection, Claude API 4 Freemium Gating, Referral System, Settings, PWA, Polish --- PAGE 3 --- 5 Security – Policies, Rate Limiting, Input Sanitisation 6 Payments – Stripe, Mobile Money, Subscriptions 7 Admin Dashboard & Business Analytics 8 Testing & QA – Unit, Component, Manual 9 Localisation – Tok Pisin, i18n, Formatting 10 Production Deployment – Forge, Monitoring, Launch Checklist Phase 1: Foundation & UI Goal Build the core Laravel + Inertia application with authentication, dashboar d, transaction tracker, bottom navigation, and translation scaffolding. Tech ● Laravel 13 with Breeze (Iner tia React stack) ● Tailwind CSS + shadcn/ui ● React 19 + TypeScript ● MySQL database Tasks 1.1 Laravel Setup & Configur ation bash --- PAGE 4 --- composer create-project laravel/laravel moneysmart-png cd moneysmart-png composer require laravel/breeze --dev php artisan breeze:install react --typescript npm install npm install tailwindcss @tailwindcss/vite @headlessui/react @heroicons/react npm install shadcn-ui # Follow shadcn/ui CLI setup to add components (e.g., button, card, dialog, etc.) ● Configur e .env with database credentials, APP_URL , etc. ● Set up Vite with Tailwind (already done by Breeze). ● Configur e inertia to shar e common data (e.g., user , flash messages, locale) in AppServiceProvider : php // App\Providers\AppServiceProvider.php Inertia::share('locale', fn () => app()->getLocale()); Inertia::share('translations', fn () => [ 'en' => __('en', [], 'en'), 'tpi' => __('tpi', [], 'tpi'), ]); 1.2 Database Schema & Models Create migr ations for all tables (run php artisan make:migration ): php Schema::create('profiles', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('full_name'); $table->string('phone_number')->nullable(); $table->string('preferred_language')->default('en'); $table->decimal('monthly_income', 12, 2)->nullable(); $table->string('plan')->default('free'); // 'free' or 'premium' $table->string('referral_code', 6)->unique(); --- PAGE 5 --- $table->string('referred_by')->nullable(); $table->integer('premium_days_earned')->default(0); $table->timestamps(); }); Schema::create('transactions', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->decimal('amount', 12, 2); $table->enum('type', ['income', 'expense']); $table->string('category'); $table->string('description')->nullable(); $table->date('date'); $table->timestamps(); }); // similarly for budgets, goals, chat_messages, usage_tracking Create models (User , Profile, Transaction, Budget, Goal, ChatMessage, UsageT racking) with proper relationships. 1.3 Authentication & User Profile ● Use Laravel Breeze’s Inertia React pages for login, register , forgot passwor d. ● Add an onboar ding flow after registr ation: ○ Create a separ ate Inertia page Onboarding with three steps (Welcome, Language, Setup). ○ After registr ation, redirect to /onboarding if profile incomplete. ○ In Profile model, add fillable fields. ○ On final step, store profile data and gener ate a unique 6‑char acter referral code. 1.4 Layout & Navigation ● Create a Layout component (with Head , BottomNav , etc.) that wraps all authenticated pages. --- PAGE 6 --- ● Bottom navigation bar (fixed at bottom) with 5 tabs: Home, Track, Budget, Goals, Coach. ● Use shadcn/ui Button , Card , Dialog , etc. ● Style: primar y color #1B4332 , accent #F59E0B , back ground #FAFAF7 , fonts (Google Fonts: Plus Jakar ta Sans & DM Sans). ● Mobile‑first: ensur e layout works on 375p x. 1.5 Dashboar d (Home) ● Inertia page: Dashboard.tsx . ● Fetch user ’s profile, current month transactions, spending summar y. ● Displa y greeting (Good morning/afternoon/e vening [Name]) based on time. ● Monthly summar y card (total income, total spent, remaining). ● Spending donut char t (use recharts library). ● Quick Add floating action button (gold) – opens a modal to add transaction. ● Recent transactions list (last 5). ● Alert cards area (populated in Phase 2). 1.6 Transaction Tracker ● Page: Transactions.tsx . ● Add transaction form (using shadcn/ui form components). ● Transaction history with sear ch, filters, pagination. ● Delete transaction with confirmation. 1.7 Translation Scaffolding ● Create a React context LanguageContext that reads locale from Laravel’s shar ed locale and allows switching. ● Store all user‑facing strings in Laravel language files ( lang/en.json , lang/tpi.json ). ● Use a cust om useTranslation hook that returns t(key) and locale . ● For Phase 1, populate en.json with all requir ed strings; tpi.json can be placeholder [TPI: English text] . ● Ensur e strings are used everywher e (e.g., “Get Started”, “Add Transaction ”, etc.). --- PAGE 7 --- 1.8 Deliv erable A fully runnable Laravel + Inertia project with: ● Authentication working (register/login/logout). ● Onboar ding flow. ● Dashboar d showing real data. ● Transaction add/edit/delete. ● Bottom navigation. ● Translation system (English only, with Tok Pisin placeholders). ● No external APIs yet. Test: After completing, add at least 10 sample transactions manually (via UI or database seeder) to prepar e for Phase 2. Phase 2: Budget Planner & Goals Goal Add budget planning, savings goals, smar t alerts, and spending insights. Tech ● Laravel back end with new contr ollers, routes, policies. ● Rechar ts for char ts. ● React state management. Tasks 2.1 Monthly Budget Planner ● Create BudgetController (Iner tia render and API endpoints). ● Add a new Inertia page Budget.tsx . --- PAGE 8 --- ● Fetch current month budgets (if none exist, suggest defaults based on monthly income). ● Form to set/update budget limits per PNG expense categor y. ● Save to budgets table (unique per user , categor y, month). ● Displa y budget progress cards (showing spent, limit, progress bar with color coding). ● “Cop y last month budgets” button. 2.2 Smar t Aler ts Engine ● Create a Laravel service AlertsService with method generateAlerts($userId) . ● It queries transactions, budgets, goals for the current month and returns an array of alert objects. ● Alert types: budget_warning, budget_ex ceeded, goal_ur gent, overspend_for ecast. ● In the Dashboar d, fetch alerts via a separ ate Inertia request (or inject when rendering page). ● Displa y dismissible alert cards (dismiss state stored in localSt orage, as befor e). ● Use shadcn/ui Alert component. 2.3 Savings Goals Screen ● Page: Goals.tsx . ● List of goals with progress bars, on‑tr ack indicat or, “Add Savings” button. ● Add/E dit/Delete goal functionality . ● Use modal for adding savings amount. ● Store goals in goals table. 2.4 Spending Insights ● Add a sub‑section on Dashboar d (or a separ ate tab) showing: ○ This month vs last month bar char t (grouped by categor y). ○ Top 3 spending categories, biggest single expense, average daily spending. ○ Rule‑based insight (e.g., “You spent X% more on Food this month… ”). --- PAGE 9 --- 2.5 Data Loading ● Use Inertia’s shar ed data or separ ate API endpoints. ● Show loading skeletons (using shadcn/ui Skeleton ) while data loads. ● Handle empty states with illustr ations. Phase 3: AI Budget Coach Goal Build the chat inter face that provides personalised PNG‑specific financial advice using Claude API. Tech ● Laravel contr oller to proxy Claude API calls. ● Web Speech API for voice input. Tasks 3.1 Chat Inter face (Iner tia Page) ● Replace the placeholder Coach tab with Coach.tsx . ● Chat bubbles, message input, micr ophone button, send button. ● Store messages in chat_messages table. ● Use Inertia form submissions to send messages (or use Axios to a Laravel endpoint). ● Implement optimistic UI updates. 3.2 User Context Builder --- PAGE 10 --- ● Create a Laravel helper buildUserContext($userId) that fetches profile, transactions, budgets, goals and returns a formatted string exactly as in original spec. 3.3 AI System Prompt ● Store the system prompt as a string in a config file or directly in the contr oller . ● Inject the built user context into the system prompt. 3.4 Claude API Call ● Create a route POST /api/coach in api.php (or an Inertia endpoint). ● In contr oller , use Guzzle to call Anthr opic API (store API key in .env ). ● Implement error handling, rate limiting (preliminar y – refined in Phase 5). ● Return AI response as JSON, then save to database. 3.5 Quick Prompt Chips & Voice Input ● Horiz ontal scrollable chips (randomly selected from list). ● Web Speech API integr ation in React (micr ophone button). ● On voice input, fill input field and auto‑send. 3.6 History & Auto‑scr oll ● Load last 50 messages on page load. ● Scroll to bottom after each message. Test: Send “How am I doing this month?” – response must reference actual Kina amounts. Phase 4: Freemium Gating, Referral System & Polish --- PAGE 11 --- Goal Enfor ce free plan limits, implement referral system, add settings screen, and polish the UI. Tasks 4.1 Freemium Gating ● Free plan limits: 50 transactions/month, 2 activ e goals, 3 budget categories, 10 AI messages/da y. ● Create a middlewar e or helper CheckPlanGate that checks usage from usage_tracking table. ● In React components, wrap actions (add transaction, add goal, set budget, send AI message) with a component that shows upgr ade modal if limit reached. ● Usage tracking: update counts on each relevant action. 4.2 Referral System ● On signup, referral code is gener ated. ● Add optional referral code field to onboar ding. ● When a user signs up with a code, increment referrer’s premium_days_earned by 30. ● Create a referral sharing screen (part of Settings) showing code, referral link, shar e buttons (WhatsApp, Facebook, copy link). ● Show friends joined count. 4.3 Settings Screen ● Add a gear icon on Home header → navigate to Settings.tsx . ● Sections: My Account (editable fields), Language (toggle English/T ok Pisin), Notifications (toggle switches – stored in localSt orage), Referral, Data (Expor t CSV – premium only), Danger Zone (delete account), Log Out. ● Update LanguageContext to reflect changes in profile.pr eferred_language. --- PAGE 12 --- 4.4 PWA Setup ● Create public/manifest.json with correct icons (192, 512). ● Register service work er (public/sw .js) for offline caching and offline banner . ● Add install prompt banner . 4.5 Performance & Polish ● Lazy load route components (using React.lazy + Suspense). ● Add entrance animations (fade/slide) for cards. ● Micr o‑inter actions (butt on scale, vibrate on success). ● Memoiz e expensiv e calculations. ● Paginate transaction history. ● Global error boundar y. Phase 5: Security & Data Protection Goal Protect user data, prevent abuse, enfor ce access contr ols. Tasks 5.1 Laravel Policies ● Create policies for each model (Transaction, Budget, Goal, ChatMessage, UsageT racking). ● Ensur e users can only view/edit their own recor ds. ● Apply policies in contr ollers and views. 5.2 Input Sanitisation & Validation ● Use Laravel Form Requests to validate all incoming data. --- PAGE 13 --- ● Cust om sanitisation: ○ sanitise_text : strip HTML tags, trim, limit length. ○ sanitise_amount : ensur e valid numeric and within reasonable bounds. ● Apply befor e saving to database. 5.3 Rate Limiting ● Use Laravel’s built‑in rate limiter ( RateLimiter facade) to limit AI API calls per user per minute/da y based on plan. ● Define rate limiter in App\Http\Kernel or via middlewar e. 5.4 Session Security ● Laravel automatically handles session security (cookies, CSRF). ● Implement inactivity timeout: ○ Use JavaScript to track last inter action; after 30 minutes, show a modal; if no response, trigger logout via Axios to /logout . 5.5 Envir onment & Error Handling ● All secr ets in .env . ● Ensur e .env.example is committed, .env is gitignor ed. ● Catch exceptions in contr ollers; return friendly error messages to Inertia (using back()->with('error', ...) ). 5.6 Admin Protection ● Add a column is_admin to users table (default false). ● Create a middlewar e IsAdmin that checks this flag. ● All admin routes will be protected by this middlewar e. Phase 6: Payment Integr ation & Subscription Management --- PAGE 14 --- Goal Enable revenue via Stripe (cards) and manual mobile mone y (BSP , Kina). Tasks 6.1 Database Additions ● Create subscriptions and manual_payments tables via migr ations. ● Add foreign keys to users. 6.2 Stripe Integr ation ● Install Stripe PHP SDK: composer require stripe/stripe-php . ● Create a route /api/create-checkout-session that returns a Stripe Checkout session ID. ● In frontend, use @stripe/stripe-js to redirect to Stripe. ● After successful payment, handle webhook (endpoint /stripe/webhook ) to update subscriptions and users.plan . ● Add a PremiumScreen.tsx (route /premium ) with pricing, featur e table, and two payment options. 6.3 Mobile Mone y Flow ● In PremiumScreen , when “Pay with Mobile Mone y” is click ed, open a modal with instructions (BSP number , reference format). ● User submits reference number , phone, months (1/3/6/12). ● Store in manual_payments table with status pending . ● Notify admin (later via admin dashboar d) to verify . 6.4 Subscription Management in Settings ● Show current plan and usage. ● For free users: “Upgr ade” button links to /premium . --- PAGE 15 --- ● For premium users: show next billing date, payment method, and option to manage subscription (Stripe Cust omer Portal for card users; contact WhatsApp for mobile mone y). 6.5 Plan Enfor cement ● Update CheckPlanGate helper to read from subscriptions table (activ e status). ● Automatically downgr ade if subscription period ends. Phase 7: Admin Dashboar d & Business Analytics Goal Internal tool to monit or users, payments, AI usage, and app health. Tasks 7.1 Admin Authentication ● Use the is_admin flag on user model. ● Create middlewar e AdminMiddleware . ● Add route group /admin protected by this middlewar e. ● Admin views are Inertia pages, but only accessible to admins. 7.2 Dashboar d Overview ● Page Admin/Dashboard.tsx with KPI cards (total users, new today, activ e premium, conv ersion %, AI messages, estimated revenue). ● Char ts: daily signups (last 30 days), weekly premium upgr ades (last 8 weeks). ● Recent activity feed (latest 20 events from logs or dedicated table). 7.3 Users Management --- PAGE 16 --- ● Admin/Users.tsx with sear chable, sortable table. ● Click a row to open a side panel with full user details and actions (grant premium, revoke premium, delete user). ● Deleting user must remo ve all related data. 7.4 Payments Management ● Tabs: Stripe Payments, Mobile Mone y. ● For pending mobile mone y, admin can verify or reject (with reason). ● Verification: update user plan, create subscription row with appr opriate end date. 7.5 AI Usage Monit oring ● Admin/AIUsage.tsx showing total API calls and cost estimates. ● Char t of hourly AI message volume. ● Alert if daily calls exceed threshold. Phase 8: Testing & QA Goal Write automated tests and manually verify all featur es. Tasks 8.1 Back end Tests (PHPUnit) ● Write tests for models, policies, rate limiting, sanitisation helpers. ● Example: test_budget_calculations – sums spending per categor y. ● Test referral code gener ation uniqueness. 8.2 Frontend Tests (Jest + React Testing Library) --- PAGE 17 --- ● Test components like PlanGate , TransactionForm . ● Test rate limiter logic in JS. 8.3 Manual QA Checklist ● Execute checklist covering authentication, transactions, budgets, goals, AI coach, payments, referral, mobile responsiv eness, security (XSS, logged‑out redirect). ● Fix any failur es befor e moving to Phase 9. Phase 9: Tok Pisin Localisation Goal Replace all placeholder translations with proper Tok Pisin, implement full i18n system. Tasks 9.1 Language Context & useT ranslation ● Already built in Phase 1; now ensur e setLanguage updates the user ’s preferred language in the database. ● The entir e app re‑renders when locale changes. 9.2 Translation Files ● In resources/lang/tpi.json , replace all placeholder values with actual Tok Pisin phrases. ● Work with a nativ e speak er to verify accur acy. 9.3 AI Coach Language Detection ● Pass the user ’s preferred language to the system prompt. --- PAGE 18 --- ● Instruct Claude to respond in that language. 9.4 Curr ency & Date Formatting ● Create helper functions formatKina() and formatKinaShort() (use toLocaleString with en-PG ). ● Create formatDate() and formatRelativeDate() using Intl.DateTimeFormat . 9.5 Language Switcher ● In Settings, add a toggle between English and Tok Pisin. ● When toggled, call setLanguage and also update the user ’s preferred_language in the database. Phase 10: Production Deplo yment Goal Deplo y the application to a live server with monit oring and launch verification. Tasks 10.1 Envir onment Configur ation ● Create .env.production with production values (database, Stripe keys, Claude key, etc.). ● Ensur e no secr ets are hardcoded. 10.2 Deplo yment Platform ● Use Laravel Forge to provision a server (or Laravel Vapor for serverless). ● Set up MySQL, queue work ers, cron jobs. --- PAGE 19 --- ● Configur e Vite to build assets ( npm run build ). ● Set up SSL via Let’s Encr ypt. 10.3 Error Monit oring ● Install Sentr y for Laravel ( sentry/sentry-laravel ) and for React ( @sentry/react ). ● Configur e DSN in .env . 10.4 PWA Finalisation ● Ensur e manifest.json uses production domain. ● Verify service work er caches assets correctly . 10.5 Launch Checklist Script ● Create a PHP script (or Node script) to verify: ○ All env variables set ○ No console.log in production build ○ No TODO comments ○ All requir ed files exist ○ SSL configur ed, etc. ● Print “READ Y FOR LAUNCH” when all checks pass. 10.6 Uptime & Cost Monit oring ● Set up UptimeRobot to monit or /api/health . ● In Anthr opic dashboar d, set a monthly spending cap (e.g., USD 50). 10.7 Soft Launch Procedur e ● Shar e with 10–20 trusted users in Port Moresby. ● Monit or Sentr y for 48 hours, fix any errors. ● Verify at least 5 successful signups and 1 successful payment. ● Then announce publicly . --- PAGE 20 --- Final Notes This guide provides a complete, step‑b y‑step blueprint for building Mone ySmar t PNG with a modern Laravel + Inertia + React + TypeScript + Tailwind + shadcn/ui stack. Follow the phases sequentially , test thoroughly , and alwa ys prioritise security and localisation. Good luck! further update the prompt to include the Laravel AI SDK in the app We need to incorpor ate the Laravel AI SDK (probably meant to refer to the "Laravel AI" package, such as the official Laravel AI package for inter acting with LLMs) into the prompt. The original PDF didn 't mention any Laravel AI SDK, but since we are now using Laravel, we should leverage the official Laravel AI package for simpler integr ation with Claude. The user wants to "further update the prompt to include the Laravel AI SDK in the app". So we need to modify the prompt to replace the manual Guzzle calls with the Laravel AI SDK, and perhaps add configur ation steps for it. Let's analyz e the original Phase 3 section: it uses fetch to Anthr opic API. In the Laravel version, we should use the Laravel AI SDK (if that' s the official one). The Laravel AI SDK (https:/ /github.com/lar avel/ai) is a new package by Laravel that provides a unified inter face for multiple AI providers (OpenAI, Anthr opic, etc.). We'll need to install it, configur e, and use it in the contr oller . We'll update the Phase 3 tasks accor dingly . Also, we might add a note in the tech stack and in Phase 1 (installation). We'll also need to ensur e the API key is set correctly . Let's rewrite the Phase 3 with Laravel AI SDK integr ation. --- PAGE 21 --- I'll produce a modified version of the overall prompt, focusing on the changes to include Laravel AI SDK. Since the previous response already gave a full guide, we need to update it to incorpor ate the AI SDK. I'll produce a new "Phase 3" section that replaces the earlier one. Also update the Tech Stack Overview to include the package. But the user asked: "further update the prompt to include the Laravel AI SDK in the app". That means we should revise the overall prompt (the one I provided earlier) to include this change. I'll produce an updated version of the main prompt, focusing on the modifications. I can either present the entir e updated prompt again (which would be lengthy) or just the delta. Since the original request was to provide a complete AI prompt, I'll provide a complete revised version with the Laravel AI SDK integr ated. I'll incorpor ate Laravel AI SDK in Phase 1 (installation) and Phase 3 (implementation). I'll also adjust the description in the overview and tech stack. I'll also note that we'll use the official laravel/ai package. Let's write the updated prompt. I'll structur e it as a single document again, but with the changes. I have updated the Mone ySmar t PNG build guide to integr ate the Laravel AI SDK (the official Laravel package for inter acting with LLMs). This replaces the previous manual Guzzle calls to the Anthr opic API, providing a cleaner , more Laravel‑nativ e appr oach. The rest of the stack remains Laravel 13 + Inertia + React 19 + TypeScript + Tailwind + shadcn/ui. Below is the complete, revised prompt – you can feed this entir e document to your AI builder or developer . --- PAGE 22 --- Mone ySmar t PNG – Complete AI Builder Prompt Guide Laravel 13 + Inertia + React 19 + TypeScript + Tailwind + shadcn/ui + Laravel AI SDK All 10 Phases – Foundation to Launch About This Document This guide contains all 10 build phases for Mone ySmar t PNG – an AI‑power ed personal finance coach designed for Papua New Guinea. Each phase is a standalone, copy‑paste ready prompt for your AI builder (Cursor , Replit, Bolt, Lovable, etc.) or developer . Rules for Using These Prompts 1. Complete and test each phase befor e moving to the next. 2. If the AI builder stops midwa y, type: “Continue from wher e you stopped. ” 3. If something breaks after a phase, type: “Revert the last change and try again. ” 4. Never paste two phases into the same prompt at once. 5. After Phase 4, test the full app befor e proceeding to Phase 5. 6. Phases 5 (Security) and 6 (Payments) must be completed befor e any real user accesses the app. Minimum Viable Launch Set If you are under time or budget pressur e, the minimum phases requir ed befor e any public launch are: --- PAGE 23 --- Phase 1, Phase 3, Phase 5, Phase 6, and Phase 10. All other phases must follow within 30 days of launch. Tech Stack Overview Layer Technology Backend Laravel 13 (PHP 8.2+) Database MySQL 8.0+ Frontend React 19 + TypeScript + Inertia.js Styling Tailwind CSS + shadcn/ui components State React Context / Zustand (optional) Auth Laravel Breeze (Inertia React stack) AI Integration Laravel AI SDK (official package) – Claude Payments Stripe PHP SDK + manual mobile money flow Deployment Laravel Forge / Vapor, Vite build, PWA All 10 Phases at a Glance --- PAGE 24 --- Phase Title 1 Foundation – Auth, Dashboard, Transaction Tracker, Navigation 2 Budget Planner, Smart Alerts, Savings Goals, Spending Insights 3 AI Budget Coach – Chat, Context Injection, Laravel AI SDK 4 Freemium Gating, Referral System, Settings, PWA, Polish 5 Security – Policies, Rate Limiting, Input Sanitisation 6 Payments – Stripe, Mobile Money, Subscriptions 7 Admin Dashboard & Business Analytics 8 Testing & QA – Unit, Component, Manual 9 Localisation – Tok Pisin, i18n, Formatting 10 Production Deployment – Forge, Monitoring, Launch Checklist Phase 1: Foundation & UI Goal Build the core Laravel + Inertia application with authentication, dashboar d, transaction tracker, bottom navigation, and translation scaffolding. Tech --- PAGE 25 --- ● Laravel 13 with Breeze (Iner tia React stack) ● Tailwind CSS + shadcn/ui ● React 19 + TypeScript ● MySQL database Tasks 1.1 Laravel Setup & Configur ation bash composer create-project laravel/laravel moneysmart-png cd moneysmart-png composer require laravel/breeze --dev php artisan breeze:install react --typescript npm install npm install tailwindcss @tailwindcss/vite @headlessui/react @heroicons/react npm install shadcn-ui # Follow shadcn/ui CLI setup to add components (e.g., button, card, dialog, etc.) ● Configur e .env with database credentials, APP_URL , etc. ● Set up Vite with Tailwind (already done by Breeze). ● Configur e inertia to shar e common data (e.g., user , flash messages, locale) in AppServiceProvider : php // App\Providers\AppServiceProvider.php Inertia::share('locale', fn () => app()->getLocale()); Inertia::share('translations', fn () => [ 'en' => __('en', [], 'en'), 'tpi' => __('tpi', [], 'tpi'), ]); 1.2 Database Schema & Models Create migr ations for all tables (run php artisan make:migration ): --- PAGE 26 --- php Schema::create('profiles', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('full_name'); $table->string('phone_number')->nullable(); $table->string('preferred_language')->default('en'); $table->decimal('monthly_income', 12, 2)->nullable(); $table->string('plan')->default('free'); // 'free' or 'premium' $table->string('referral_code', 6)->unique(); $table->string('referred_by')->nullable(); $table->integer('premium_days_earned')->default(0); $table->timestamps(); }); Schema::create('transactions', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->decimal('amount', 12, 2); $table->enum('type', ['income', 'expense']); $table->string('category'); $table->string('description')->nullable(); $table->date('date'); $table->timestamps(); }); // similarly for budgets, goals, chat_messages, usage_tracking Create models (User , Profile, Transaction, Budget, Goal, ChatMessage, UsageT racking) with proper relationships. 1.3 Authentication & User Profile ● Use Laravel Breeze’s Inertia React pages for login, register , forgot passwor d. ● Add an onboar ding flow after registr ation: ○ Create a separ ate Inertia page Onboarding with three steps (Welcome, Language, Setup). ○ After registr ation, redirect to /onboarding if profile incomplete. --- PAGE 27 --- ○ In Profile model, add fillable fields. ○ On final step, store profile data and gener ate a unique 6‑char acter referral code. 1.4 Layout & Navigation ● Create a Layout component (with Head , BottomNav , etc.) that wraps all authenticated pages. ● Bottom navigation bar (fixed at bottom) with 5 tabs: Home, Track, Budget, Goals, Coach. ● Use shadcn/ui Button , Card , Dialog , etc. ● Style: primar y color #1B4332 , accent #F59E0B , back ground #FAFAF7 , fonts (Google Fonts: Plus Jakar ta Sans & DM Sans). ● Mobile‑first: ensur e layout works on 375p x. 1.5 Dashboar d (Home) ● Inertia page: Dashboard.tsx . ● Fetch user ’s profile, current month transactions, spending summar y. ● Displa y greeting (Good morning/afternoon/e vening [Name]) based on time. ● Monthly summar y card (total income, total spent, remaining). ● Spending donut char t (use recharts library). ● Quick Add floating action button (gold) – opens a modal to add transaction. ● Recent transactions list (last 5). ● Alert cards area (populated in Phase 2). 1.6 Transaction Tracker ● Page: Transactions.tsx . ● Add transaction form (using shadcn/ui form components). ● Transaction history with sear ch, filters, pagination. ● Delete transaction with confirmation. 1.7 Translation Scaffolding --- PAGE 28 --- ● Create a React context LanguageContext that reads locale from Laravel’s shar ed locale and allows switching. ● Store all user‑facing strings in Laravel language files ( lang/en.json , lang/tpi.json ). ● Use a cust om useTranslation hook that returns t(key) and locale . ● For Phase 1, populate en.json with all requir ed strings; tpi.json can be placeholder [TPI: English text] . ● Ensur e strings are used everywher e (e.g., “Get Started”, “Add Transaction ”, etc.). 1.8 Deliv erable A fully runnable Laravel + Inertia project with: ● Authentication working (register/login/logout). ● Onboar ding flow. ● Dashboar d showing real data. ● Transaction add/edit/delete. ● Bottom navigation. ● Translation system (English only, with Tok Pisin placeholders). ● No external APIs yet. Test: After completing, add at least 10 sample transactions manually (via UI or database seeder) to prepar e for Phase 2. Phase 2: Budget Planner & Goals Goal Add budget planning, savings goals, smar t alerts, and spending insights. Tech ● Laravel back end with new contr ollers, routes, policies. ● Rechar ts for char ts. --- PAGE 29 --- ● React state management. Tasks 2.1 Monthly Budget Planner ● Create BudgetController (Iner tia render and API endpoints). ● Add a new Inertia page Budget.tsx . ● Fetch current month budgets (if none exist, suggest defaults based on monthly income). ● Form to set/update budget limits per PNG expense categor y. ● Save to budgets table (unique per user , categor y, month). ● Displa y budget progress cards (showing spent, limit, progress bar with color coding). ● “Cop y last month budgets” button. 2.2 Smar t Aler ts Engine ● Create a Laravel service AlertsService with method generateAlerts($userId) . ● It queries transactions, budgets, goals for the current month and returns an array of alert objects. ● Alert types: budget_warning, budget_ex ceeded, goal_ur gent, overspend_for ecast. ● In the Dashboar d, fetch alerts via a separ ate Inertia request (or inject when rendering page). ● Displa y dismissible alert cards (dismiss state stored in localSt orage, as befor e). ● Use shadcn/ui Alert component. 2.3 Savings Goals Screen ● Page: Goals.tsx . ● List of goals with progress bars, on‑tr ack indicat or, “Add Savings” button. ● Add/E dit/Delete goal functionality . ● Use modal for adding savings amount. ● Store goals in goals table. --- PAGE 30 --- 2.4 Spending Insights ● Add a sub‑section on Dashboar d (or a separ ate tab) showing: ○ This month vs last month bar char t (grouped by categor y). ○ Top 3 spending categories, biggest single expense, average daily spending. ○ Rule‑based insight (e.g., “You spent X% more on Food this month… ”). 2.5 Data Loading ● Use Inertia’s shar ed data or separ ate API endpoints. ● Show loading skeletons (using shadcn/ui Skeleton ) while data loads. ● Handle empty states with illustr ations. Phase 3: AI Budget Coach with Laravel AI SDK Goal Build the chat inter face that provides personalised PNG‑specific financial advice using Claude via Laravel AI SDK. Tech ● Laravel AI SDK ( laravel/ai package). ● Web Speech API for voice input. Tasks 3.1 Install Laravel AI SDK bash composer require laravel/ai --- PAGE 31 --- Publish the configur ation: bash php artisan vendor:publish --tag=ai-config In config/ai.php , set the default provider to anthropic and add your API key to .env : text ANTHROPIC_API_KEY=your_anthropic_api_key 3.2 Chat Inter face (Iner tia Page) ● Replace the placeholder Coach tab with Coach.tsx . ● Chat bubbles, message input, micr ophone button, send button. ● Store messages in chat_messages table. ● Use Inertia form submissions to send messages (or use Axios to a Laravel endpoint). ● Implement optimistic UI updates. 3.3 User Context Builder ● Create a Laravel helper buildUserContext($userId) that fetches profile, transactions, budgets, goals and returns a formatted string exactly as in original spec. 3.4 AI System Prompt ● Store the system prompt as a string in a config file or directly in the contr oller . ● Inject the built user context into the system prompt. 3.5 Claude API Call using Laravel AI SDK ● In the contr oller (e.g., CoachController ), inject the AI service: --- PAGE 32 --- php use Laravel\Ai\Ai; public function sendMessage(Request $request, Ai $ai) { $user = $request->user(); $userMessage = $request->input('message'); // Build user context $context = buildUserContext($user->id); // Build system prompt with context $systemPrompt = str_replace('{USER_CONTEXT}', $context, config('ai.system_prompt')); // Get last 20 messages from database $history = ChatMessage::where('user_id', $user->id) ->latest() ->limit(20) ->orderBy('created_at') ->get() ->map(fn($msg) => ['role' => $msg->role, 'content' => $msg->content]) ->toArray(); // Add current user message $history[] = ['role' => 'user', 'content' => $userMessage]; // Call Claude via Laravel AI SDK $response = $ai->chat() ->system($systemPrompt) ->messages($history) ->create(); $aiText = $response->content; // Save both messages to database ChatMessage::create([ 'user_id' => $user->id, 'role' => 'user', 'content' => $userMessage, ]); ChatMessage::create([ --- PAGE 33 --- 'user_id' => $user->id, 'role' => 'assistant', 'content' => $aiText, ]); return response()->json(['response' => $aiText]); } ● Set up a route /api/coach (or an Inertia endpoint) to call this method. 3.6 Quick Prompt Chips & Voice Input ● Horiz ontal scrollable chips (randomly selected from list). ● Web Speech API integr ation in React (micr ophone button). ● On voice input, fill input field and auto‑send. 3.7 History & Auto‑scr oll ● Load last 50 messages on page load. ● Scroll to bottom after each message. Test: Send “How am I doing this month?” – response must reference actual Kina amounts. Phase 4: Freemium Gating, Referral System & Polish Goal Enfor ce free plan limits, implement referral system, add settings screen, and polish the UI. Tasks --- PAGE 34 --- 4.1 Freemium Gating ● Free plan limits: 50 transactions/month, 2 activ e goals, 3 budget categories, 10 AI messages/da y. ● Create a middlewar e or helper CheckPlanGate that checks usage from usage_tracking table. ● In React components, wrap actions (add transaction, add goal, set budget, send AI message) with a component that shows upgr ade modal if limit reached. ● Usage tracking: update counts on each relevant action. 4.2 Referral System ● On signup, referral code is gener ated. ● Add optional referral code field to onboar ding. ● When a user signs up with a code, increment referrer’s premium_days_earned by 30. ● Create a referral sharing screen (part of Settings) showing code, referral link, shar e buttons (WhatsApp, Facebook, copy link). ● Show friends joined count. 4.3 Settings Screen ● Add a gear icon on Home header → navigate to Settings.tsx . ● Sections: My Account (editable fields), Language (toggle English/T ok Pisin), Notifications (toggle switches – stored in localSt orage), Referral, Data (Expor t CSV – premium only), Danger Zone (delete account), Log Out. ● Update LanguageContext to reflect changes in profile.pr eferred_language. 4.4 PWA Setup ● Create public/manifest.json with correct icons (192, 512). ● Register service work er (public/sw .js) for offline caching and offline banner . ● Add install prompt banner . 4.5 Performance & Polish --- PAGE 35 --- ● Lazy load route components (using React.lazy + Suspense). ● Add entrance animations (fade/slide) for cards. ● Micr o‑inter actions (butt on scale, vibrate on success). ● Memoiz e expensiv e calculations. ● Paginate transaction history. ● Global error boundar y. Phase 5: Security & Data Protection Goal Protect user data, prevent abuse, enfor ce access contr ols. Tasks 5.1 Laravel Policies ● Create policies for each model (Transaction, Budget, Goal, ChatMessage, UsageT racking). ● Ensur e users can only view/edit their own recor ds. ● Apply policies in contr ollers and views. 5.2 Input Sanitisation & Validation ● Use Laravel Form Requests to validate all incoming data. ● Cust om sanitisation: ○ sanitise_text : strip HTML tags, trim, limit length. ○ sanitise_amount : ensur e valid numeric and within reasonable bounds. ● Apply befor e saving to database. 5.3 Rate Limiting --- PAGE 36 --- ● Use Laravel’s built‑in rate limiter ( RateLimiter facade) to limit AI API calls per user per minute/da y based on plan. ● Define rate limiter in App\Http\Kernel or via middlewar e. 5.4 Session Security ● Laravel automatically handles session security (cookies, CSRF). ● Implement inactivity timeout: ○ Use JavaScript to track last inter action; after 30 minutes, show a modal; if no response, trigger logout via Axios to /logout . 5.5 Envir onment & Error Handling ● All secr ets in .env . ● Ensur e .env.example is committed, .env is gitignor ed. ● Catch exceptions in contr ollers; return friendly error messages to Inertia (using back()->with('error', ...) ). 5.6 Admin Protection ● Add a column is_admin to users table (default false). ● Create a middlewar e IsAdmin that checks this flag. ● All admin routes will be protected by this middlewar e. Phase 6: Payment Integr ation & Subscription Management Goal Enable revenue via Stripe (cards) and manual mobile mone y (BSP , Kina). Tasks --- PAGE 37 --- 6.1 Database Additions ● Create subscriptions and manual_payments tables via migr ations. ● Add foreign keys to users. 6.2 Stripe Integr ation ● Install Stripe PHP SDK: composer require stripe/stripe-php . ● Create a route /api/create-checkout-session that returns a Stripe Checkout session ID. ● In frontend, use @stripe/stripe-js to redirect to Stripe. ● After successful payment, handle webhook (endpoint /stripe/webhook ) to update subscriptions and users.plan . ● Add a PremiumScreen.tsx (route /premium ) with pricing, featur e table, and two payment options. 6.3 Mobile Mone y Flow ● In PremiumScreen , when “Pay with Mobile Mone y” is click ed, open a modal with instructions (BSP number , reference format). ● User submits reference number , phone, months (1/3/6/12). ● Store in manual_payments table with status pending . ● Notify admin (later via admin dashboar d) to verify . 6.4 Subscription Management in Settings ● Show current plan and usage. ● For free users: “Upgr ade” button links to /premium . ● For premium users: show next billing date, payment method, and option to manage subscription (Stripe Cust omer Portal for card users; contact WhatsApp for mobile mone y). 6.5 Plan Enfor cement ● Update CheckPlanGate helper to read from subscriptions table (activ e status). --- PAGE 38 --- ● Automatically downgr ade if subscription period ends. Phase 7: Admin Dashboar d & Business Analytics Goal Internal tool to monit or users, payments, AI usage, and app health. Tasks 7.1 Admin Authentication ● Use the is_admin flag on user model. ● Create middlewar e AdminMiddleware . ● Add route group /admin protected by this middlewar e. ● Admin views are Inertia pages, but only accessible to admins. 7.2 Dashboar d Overview ● Page Admin/Dashboard.tsx with KPI cards (total users, new today, activ e premium, conv ersion %, AI messages, estimated revenue). ● Char ts: daily signups (last 30 days), weekly premium upgr ades (last 8 weeks). ● Recent activity feed (latest 20 events from logs or dedicated table). 7.3 Users Management ● Admin/Users.tsx with sear chable, sortable table. ● Click a row to open a side panel with full user details and actions (grant premium, revoke premium, delete user). ● Deleting user must remo ve all related data. 7.4 Payments Management --- PAGE 39 --- ● Tabs: Stripe Payments, Mobile Mone y. ● For pending mobile mone y, admin can verify or reject (with reason). ● Verification: update user plan, create subscription row with appr opriate end date. 7.5 AI Usage Monit oring ● Admin/AIUsage.tsx showing total API calls and cost estimates. ● Char t of hourly AI message volume. ● Alert if daily calls exceed threshold. Phase 8: Testing & QA Goal Write automated tests and manually verify all featur es. Tasks 8.1 Back end Tests (PHPUnit) ● Write tests for models, policies, rate limiting, sanitisation helpers. ● Example: test_budget_calculations – sums spending per categor y. ● Test referral code gener ation uniqueness. 8.2 Frontend Tests (Jest + React Testing Library) ● Test components like PlanGate , TransactionForm . ● Test rate limiter logic in JS. 8.3 Manual QA Checklist --- PAGE 40 --- ● Execute checklist covering authentication, transactions, budgets, goals, AI coach, payments, referral, mobile responsiv eness, security (XSS, logged‑out redirect). ● Fix any failur es befor e moving to Phase 9. Phase 9: Tok Pisin Localisation Goal Replace all placeholder translations with proper Tok Pisin, implement full i18n system. Tasks 9.1 Language Context & useT ranslation ● Already built in Phase 1; now ensur e setLanguage updates the user ’s preferred language in the database. ● The entir e app re‑renders when locale changes. 9.2 Translation Files ● In resources/lang/tpi.json , replace all placeholder values with actual Tok Pisin phrases. ● Work with a nativ e speak er to verify accur acy. 9.3 AI Coach Language Detection ● Pass the user ’s preferred language to the system prompt. ● Instruct Claude to respond in that language. 9.4 Curr ency & Date Formatting --- PAGE 41 --- ● Create helper functions formatKina() and formatKinaShort() (use toLocaleString with en-PG ). ● Create formatDate() and formatRelativeDate() using Intl.DateTimeFormat . 9.5 Language Switcher ● In Settings, add a toggle between English and Tok Pisin. ● When toggled, call setLanguage and also update the user ’s preferred_language in the database. Phase 10: Production Deplo yment Goal Deplo y the application to a live server with monit oring and launch verification. Tasks 10.1 Envir onment Configur ation ● Create .env.production with production values (database, Stripe keys, Claude key, etc.). ● Ensur e no secr ets are hardcoded. 10.2 Deplo yment Platform ● Use Laravel Forge to provision a server (or Laravel Vapor for serverless). ● Set up MySQL, queue work ers, cron jobs. ● Configur e Vite to build assets ( npm run build ). ● Set up SSL via Let’s Encr ypt. 10.3 Error Monit oring --- PAGE 42 --- ● Install Sentr y for Laravel ( sentry/sentry-laravel ) and for React ( @sentry/react ). ● Configur e DSN in .env . 10.4 PWA Finalisation ● Ensur e manifest.json uses production domain. ● Verify service work er caches assets correctly . 10.5 Launch Checklist Script ● Create a PHP script (or Node script) to verify: ○ All env variables set ○ No console.log in production build ○ No TODO comments ○ All requir ed files exist ○ SSL configur ed, etc. ● Print “READ Y FOR LAUNCH” when all checks pass. 10.6 Uptime & Cost Monit oring ● Set up UptimeRobot to monit or /api/health . ● In Anthr opic dashboar d, set a monthly spending cap (e.g., USD 50). 10.7 Soft Launch Procedur e ● Shar e with 10–20 trusted users in Port Moresby. ● Monit or Sentr y for 48 hours, fix any errors. ● Verify at least 5 successful signups and 1 successful payment. ● Then announce publicly . Final Notes --- PAGE 43 --- This guide provides a complete, step‑b y‑step blueprint for building Mone ySmar t PNG with a modern Laravel + Inertia + React + TypeScript + Tailwind + shadcn/ui stack, now enhanced with Laravel AI SDK for clean AI integr ation. Follow the phases sequentially , test thoroughly , and alwa ys prioritise security and localisation.