# Porosh Partner — Antigravity implementation brief

এই ফাইল সম্পূর্ণ পড়ুন, তারপর বাস্তব source code লিখুন। শুধু পরিকল্পনা বা static screen বানিয়ে শেষ করবেন না।

## Outcome and platform
Build Porosh Partner as a responsive Bengali web application, installable PWA, and versioned REST API reusable by a later Flutter Android/iOS app. Preserve the supplied reference design and POROSH green logo (#016937). The reference folder is a browser-local DEMO, not a backend. Do not migrate its sample balances or sample users into production accounts.
Use Laravel 13, PHP >=8.3, MySQL 8/InnoDB/utf8mb4, Blade, Tailwind and small Alpine components. Pin compatible dependency versions and commit lockfiles. Use Sanctum for mobile API authentication and session/CSRF auth for web. Verify official documentation for exact installation commands. If target hosting cannot run PHP8.3/extensions, report mismatch before silently downgrading. No Node server, Redis or always-on workers required on cPanel; compile assets locally and deploy built files. Database queue + scheduler-driven bounded queue worker for initial low volume.

## Deliverables
Full Laravel project: composer.json/lock, package.json/lock, migrations, Eloquent models and relations, form requests, controllers, Policies, service classes, Blade views, routes/web.php and routes/api.php, tests, seeders, .env.example, OpenAPI documentation, deployment README. Produce source.zip and cpanel-release.zip including vendor and built public assets. Never include real credentials, .env, real uploaded documents, node_modules or default admin passwords. Create admin through an interactive artisan command. Deliver PHASE-STATUS.md recording actual passing tests and incomplete integrations.

## Modules
1. Public landing page; work/services, geographic coverage, income estimator, privacy/terms/partner-wallet drafts. No guaranteed income, fabricated reviews or unsupported live-user counts.
2. Register/login/logout/password-reset, contact verification using configured provider; local mock mail only in development. Admin MFA; rate-limit authentication; password hash; session rotation/revocation. Partner profile, consent version/date, account status.
3. Central admin + scoped geographic supervisors + partner dashboard; merchant and delivery accounts see their own assigned records. Use explicit permissions, not role name alone. Finance approval separate from partner permissions. Suspension blocks new operations but retains statement/history.
4. Hierarchy: division → district → upazila OR thana → union OR urban local unit → ward → community. Six partner tiers: division/district/upazila/union/ward/community. One active division partner per division. Central admin is an operator role, not a seventh partner tier. Model alternative urban parents; validate actual geography and hierarchy server-side. Lower-level exclusivity must be configurable, not assumed. Scoped merchant/delivery assignment, supervised handover and immutable assignment history.
5. Partner work board: new merchant onboarding, catalog updates, order support, delivery coordination, business digital setup, local ads, subscriptions, local-service and ticket bookings, training, customer help/returns, provider-linked financial-service assistance. Partner owns no mandatory product inventory. Search/filter, assignee, due date, checklist, evidence, verified completion, rejection/reopen. Categories cover food/essentials, repair, transport, travel, beauty, health appointments, education, events, property, wholesale, ads, financial assistance.
6. Merchants: business consent, category, location, partner assignment, pending/verified/active/suspended, activation event; CRUD scoped by Policy. Products belong to merchants. Delivery team: location, assignment, delivery evidence, issues, compensation accrued/paid tracking; no fake settlement.
7. Orders/bookings: draft/confirmed/assigned/completed/cancelled/refunded. Merchant gross sales and company earned service revenue separate. Verified completion + earned revenue triggers commission service. Booking/provider adapters disabled unless configured.
8. Commission: proposed merchant activation 300 BDT once per eligible merchant; 30% of COMPANY earned eligible service revenue, never gross sales or wallet deposit. Persist rule version, eligible base, beneficiary, event key, approval, posting and reversal references. Default configurable rules; activation only after admin verification. Unique event+beneficiary+rule prevents repeats. Partial/full refunds generate proportional compensating reversals, never edit posted ledger. No invented multilevel/binary payouts.
9. Referral: inviter/code + invited partner + verified eligibility, proposed bonus3000; disabled pending approved eligibility policy. Signup or a10000 deposit alone never credits bonus. Prevent self-referral/cycles; payout event deduplication. Tier hierarchy is responsibility structure, not automatic recruitment rewards.
10. Activation: profile → identity/area/contract verification → training → admin approval. Proposed10000 add-money requirement disabled until operator declares whether fee/deposit/usable balance and refund conditions. Never auto-activate solely on deposit. Keep KYC documents private with minimal access if later enabled.
11. Wallet: earnings and deposited-funds pockets + reserved funds separately, ledger statement, add-money requests, send-money, bank withdrawal/cash-out requests. Store every BDT amount as integer poisha (300BDT=30000); avoid floats. Central double-entry ledger, journal debit=credit, unique idempotency key, DB transactions/row locks. Balance derived from posted entries or reconciled locked cache. Zero balance at new account creation. Reservation isn't paid; lifecycle requested/reserved/approved/processing/paid/failed/cancelled. Approved request still not marked paid until verified provider result. Unreserve on failure/cancel. Balance cannot go negative. Provider calls outside DB locks with outbox/event handling.
12. Add money only after verified provider callback or audited bank reconciliation by authorized finance staff; never trust browser payment success. Signature validation, replay protection, unique provider transaction and event ids; duplicate callbacks must be harmless. Provider adapter interface and mock provider for tests; all real payment operations OFF by default. No gateway credentials or PIN/OTP/card collection. Encrypt protected destination data at rest, mask output and redact logs. Bank destinations are private verified records, not freeform auto-approved requests.
13. Loan module = application assistance ONLY: merchant, amount, purpose, consent, supporting evidence, submitted/status history. Partner cannot approve/disburse. Lender integration disabled unless contracted/configured. No assumed interest or repayment promise.
14. Training lessons/enrollment/progress/completion; support tickets and messages; notification preferences; data export, deletion request handling with financial-retention policy to be set; audit of sensitive changes; terms versions and acceptance. Published policies must reflect real backend behavior, replacing demo localStorage wording.

## API
/api/v1/auth/register, /login, /logout; /me; /geographies?parent_id=; /dashboard; /merchants; /delivery-members; /tasks; /orders; /bookings; /wallet/accounts; /wallet/statement; /wallet/requests; /referrals; /loan-applications; /training/enrollments; /support-tickets. Scoped admin endpoints under /api/v1/admin with explicit Policies; webhook endpoints provider-specific with signature checks, not ordinary user authentication. Pagination, validation, consistent error envelope, UTC timestamps/display Asia/Dhaka. All state changes POST/PATCH with server authorization. API never directly exposes database access.

## SQL reference
Use database-schema.sql as conceptual SQL baseline. Convert into reversible Laravel migrations and extend with framework session/cache/jobs/password-reset/token tables, role permissions, provider settlement, private files, consent versions and training progress where needed. Do not import this SQL AND run equivalent migrations on the same database. Composite ledger and geographic consistency rules must be enforced by services/tests, not assumed from individual foreign keys. Use MySQL integration tests, not SQLite only, for concurrency/locking behavior.

## Acceptance tests (implement and actually run)
Two partners can't read/edit each other's merchants, loan drafts, wallet or documents; supervisor scope checked on every endpoint; admin assignment cannot escalate own permissions. New account wallet0. Double activation/event/callback never double credits. 10 eligible merchant activations +20000BDT company revenue yield9000BDT before expenses. Two simultaneous withdrawals cannot overspend. Unbalanced journal rejected atomically. Failed payouts release exact reserve; retries use same provider idempotency key; refunds reverse eligible commission once. No frontend-set balance. Missing payment configuration disables UI and server route execution. Geographic parent/tier mismatch rejected. Mobile widths360/390/768 and desktop1440 no overflow except intentional table scroll, accessible labels/focus/errors; PWA offline read-only public shell, do not cache private API/financial screens. Test backup restore in staging and include reproducible instructions.

## Execution order
A. Scaffold, migrations, auth, role/Policies and MySQL tests.
B. Geographic scopes, partner/merchant/delivery CRUD and responsive dashboard.
C. Tasks, orders/bookings, activation and commission state machine.
D. Ledger, reservations, reconciliation, mock provider and concurrent tests.
E. Training/support/loans/referrals, PWA, API docs and cPanel release.
Build each phase, run checks, record results, continue to next phase. Never label a placeholder page or mock bank transfer as complete production functionality.
