# Orphan Sponsorship Platform

## English Implementation Plan and Master Prompt for Sol

> **Current architecture override (2026-07-26):** The implemented platform is private and account-based. Do not restore public orphan listings, public orphan data, sponsorship-request routes/tables, sponsor email login, consent-gated document access, CSV/PDF report exports, or the legacy aggregate monthly-support/partial-payment UI described in older sections of this plan. Administrators create phone/password sponsor accounts and may create an orphan case with no manual data or documents; PostgreSQL generates the immutable case number. Incoming sponsor payments live in `sponsor_monthly_payments`; outgoing sponsor-linked orphan transfers live in `orphan_transfers`, with one protected receipt per transfer. A sponsor can access only the sponsor's own linked cases, payments, transfers, and receipts. The current source of truth is the live schema migrations plus `README.md` and `SECURITY.md`.

Currency: Sudanese Pound (SDG)  
Default monthly sponsorship: SDG 50,000 per orphan, editable for each orphan.

---

# Part 1: Implementation Plan

## Phase 1 — Project Foundation

1. Inspect the existing repository and preserve any valid existing work.
2. Create or configure a production-ready Next.js application using:
   - App Router
   - TypeScript
   - Tailwind CSS
   - shadcn/ui or an equivalent lightweight component system
   - React Hook Form
   - Zod
3. Configure the entire application for Arabic and true RTL layout.
4. Add a responsive application shell for:
   - Public pages
   - Admin dashboard
   - Donor dashboard
5. Create:
   - `.env.example`
   - `README.md`
   - `DEPLOYMENT-CPANEL.md`
   - `SECURITY.md`
6. Add ESLint, formatting, type-checking, and test commands.

## Phase 2 — Supabase Database

1. Connect the project to the supplied Supabase project.
2. Create SQL migrations for:
   - Profiles
   - Orphans
   - Orphan documents
   - Sponsors/donors
   - Sponsorship relationships
   - Monthly support records
   - Monthly contributor snapshots
   - Transfer payments
   - Transfer receipts
   - Sponsorship requests
   - Notifications
   - Audit logs
   - Application settings
3. Add enums, foreign keys, indexes, unique constraints, and validation constraints.
4. Set the default orphan sponsorship amount to `50000`.
5. Enable Row Level Security on all applicable tables.
6. Create policies that guarantee:
   - Admins can manage all platform data through trusted server-side operations.
   - A donor can only see orphans connected to that donor.
   - A donor can only see that donor’s sponsorships, requests, notifications, and permitted monthly records.
   - Donors cannot create or modify transfers.
7. Create safe development seed data using obviously fictional identities and bank details.

## Phase 3 — Authentication and Authorization

1. Implement Supabase email/password authentication.
2. Support only two roles:
   - `admin`
   - `donor`
3. Do not create a financial reviewer role.
4. Protect dashboard routes on the server.
5. Create a centralized authorization library.
6. Check account activation status on every sensitive request.
7. Add a secure workflow for creating the first admin.
8. Allow admins to create, activate, deactivate, and manage donor accounts.
9. Never rely only on hidden UI controls for authorization.

## Phase 4 — Secure Local File Storage

1. Store documents on the cPanel hosting filesystem, not in Supabase Storage.
2. Store all documents outside the Next.js `public` directory.
3. Use a configurable absolute directory:

```env
UPLOAD_ROOT=/absolute/private/path/private_uploads
```

4. Organize files by orphan and transfer period.
5. Rename uploaded files using UUIDs.
6. Allow only PDF, JPG, JPEG, PNG, and WEBP.
7. Validate both MIME type and extension.
8. Enforce a configurable default 10MB upload limit.
9. Serve documents only through protected Next.js Route Handlers.
10. Before serving a document, verify that the user is:
    - An admin; or
    - A donor authorized to view the related orphan or monthly transfer record.
11. Never expose physical file paths or permanent public URLs.
12. Record file views and downloads in the audit log.
13. Add optional donor-specific watermarks to displayed documents.

## Phase 5 — Orphan Management

Build complete admin CRUD and archive workflows for orphan records.

Each orphan must contain:

- Automatically generated internal case number.
- Full name.
- Date of birth.
- Age calculated dynamically from the date of birth; do not store age as a fixed field.
- Gender.
- Orphan’s national ID.
- Mother’s or related guardian’s name.
- Mother’s or related guardian’s national ID.
- Relationship to the orphan when the person is not the mother.
- Contact number.
- Bank account holder’s name.
- Full bank account number.
- Optional bank name.
- Father’s death certificate as a required document.
- Required monthly sponsorship amount.
- Default required amount: SDG 50,000.
- Public summary.
- Donor-visible notes.
- Internal admin notes.
- Status.

Do not add:

- Father’s date of death.
- Orphan profile photo.
- Bank account verification document.
- Verification date.
- Region.

Supported orphan statuses:

- New
- Available
- Partially sponsored
- Fully sponsored
- Suspended
- Closed

Avoid hard-deleting records that already have sponsorship or transfer history.

## Phase 6 — Shared Sponsorships

Support:

- One donor sponsoring one orphan.
- Multiple donors sponsoring one orphan.
- One donor sponsoring multiple orphans.

Each sponsorship relationship must contain:

- Orphan
- Donor
- Monthly contribution amount
- Start date
- Optional end date
- Active, stopped, or completed status
- Optional stop reason
- Notes
- Creation and update timestamps

Business calculations:

- Covered amount = sum of active monthly donor contributions.
- Remaining amount = maximum of zero and required amount minus covered amount.
- No active contribution: available for sponsorship.
- Covered amount below required amount: partially sponsored.
- Covered amount equal to or above required amount: fully sponsored.
- Warn the admin before contributions exceed the required amount.
- Editing an orphan’s required amount must not silently rewrite historical sponsorship or monthly records.
- Preserve ended sponsorship relationships for history.

## Phase 7 — Monthly Transfers

The platform must not process online payments.

The admin transfers money outside the platform, then records the transaction and uploads the transfer receipt.

Each monthly record must contain:

- Orphan
- Month and year
- Required amount snapshot
- Total pledged contribution snapshot
- Actual transferred amount
- Transfer date
- Optional transaction reference
- Transfer receipt
- Status
- Donor-visible notes
- Internal notes
- Admin who recorded the transaction
- Creation and update timestamps

Statuses:

- Pending
- Partially transferred
- Transferred
- Overdue
- Paused

Requirements:

- Support multiple partial payments for the same monthly record.
- Calculate the total transferred amount from the related payments.
- Keep contributor snapshots so future sponsorship changes do not rewrite history.
- Allow donors who participated during that month to view its transfer receipt.
- Use Arabic currency formatting such as `50,000 ج.س`.
- Record all important edits in the audit log.

## Phase 8 — Donor Dashboard

Create a simple Arabic RTL donor dashboard containing:

- Number of sponsored orphans.
- Total current monthly contribution.
- Total recorded historical contribution.
- Current month transfer status.
- Recent notifications.
- List of linked orphans.
- Sponsorship requests.
- Account management and password change.

For every linked orphan, the donor can view:

- Full orphan information.
- Full orphan national ID.
- Full mother/guardian information and national ID.
- Full contact number.
- Full bank account details.
- Father’s death certificate.
- Required monthly amount.
- Donor’s contribution.
- Monthly history.
- Transferred amounts.
- Transfer receipt for each permitted month.
- Total historical transfers.

A donor must never be able to access another orphan by changing a URL or record ID.

## Phase 9 — Public Available-Orphans Page

Create a public page showing only:

- Internal case number.
- Calculated age.
- Gender.
- Public summary.
- Required monthly amount.
- Covered amount.
- Remaining amount.
- Coverage percentage.
- Available or partially sponsored status.
- “Request Sponsorship” action.

Do not expose names, national IDs, death certificates, phone numbers, bank accounts, or private documents publicly.

For logged-in donors:

- Select a proposed monthly contribution.
- Add an optional message.
- Submit the request.

For visitors:

- Enter name.
- Enter contact number.
- Add optional secondary contact.
- Enter proposed amount.
- Add an optional message.

Request statuses:

- New
- Under review
- Accepted
- Rejected
- Cancelled

Acceptance must not create sponsorship automatically without admin confirmation. The admin must connect or create the donor account, confirm the contribution amount and start date, then create the sponsorship relationship.

## Phase 10 — Admin Dashboard

Create a complete admin dashboard with:

- Total orphans.
- Fully sponsored orphans.
- Partially sponsored orphans.
- Unsponsored orphans.
- Suspended cases.
- Active donors.
- Total monthly required amount.
- Total active monthly contributions.
- Total transferred this month.
- Remaining amount this month.
- Overdue transfers.
- Records missing receipts.
- New sponsorship requests.

Include complete management sections for:

- Orphans
- Donors
- Sponsorship relationships
- Monthly transfer records
- Partial payments
- Transfer receipts
- Sponsorship requests
- Notifications
- Reports
- Settings
- Audit logs

Reports should include:

- Monthly sponsorship report.
- Fully, partially, and unsponsored orphan report.
- Donor contribution report.
- Family transfer report.
- Overdue transfer report.
- Admin-only CSV export.

## Phase 11 — Public Website

Create:

- Home
- About the initiative
- How sponsorship works
- Available orphans
- Sponsorship request
- Login
- Privacy policy
- Terms of use
- Contact

The home page should communicate trust, simplicity, privacy, and transparency, and may display public statistics controlled by the admin.

## Phase 12 — Security and Privacy Review

Because the platform stores minors’ national IDs, bank information, and death certificates:

1. Apply authorization on the server and database.
2. Never include sensitive data in unauthorized HTML responses.
3. Never log national IDs, bank accounts, secrets, or passwords.
4. Add rate limiting to authentication, public requests, and protected document access.
5. Add appropriate security headers.
6. Block search-engine indexing of dashboards and protected files.
7. Require HTTPS in production.
8. Add configurable idle session expiration.
9. Log sensitive views, downloads, and modifications.
10. Add an administrative record for guardian consent to share documents with linked donors.

## Phase 13 — Testing

Add tests for:

- Amount and coverage calculations.
- Age calculation.
- Shared sponsorship behavior.
- Monthly contribution snapshots.
- Partial transfer calculations.
- Role and permission checks.
- File authorization.
- Sponsorship request acceptance.

Add end-to-end tests for:

- Admin login and orphan creation.
- Admin donor creation.
- Shared sponsorship creation.
- Monthly transfer and receipt upload.
- Donor viewing an authorized orphan.
- Donor being denied access to an unrelated orphan.
- Anonymous user being denied access to protected files.
- Public sponsorship request submission.

## Phase 14 — cPanel Deployment

1. Ensure the project runs with:

```bash
npm run build
npm run start
```

2. Do not use Vercel-only features.
3. Document cPanel Node.js Application setup.
4. Document environment variable configuration.
5. Ensure the hosting user can write to `UPLOAD_ROOT`.
6. Create storage directories safely when missing.
7. Add `/api/health`.
8. Document database and `private_uploads` backup procedures.
9. Confirm that production storage is persistent and not temporary.

## Phase 15 — Final Verification

Before completion:

1. Run lint.
2. Run type checking.
3. Run unit and integration tests.
4. Run the production build.
5. Test admin and donor workflows.
6. Attempt unauthorized orphan access using another record ID.
7. Attempt protected file access:
   - Without authentication.
   - As an unrelated donor.
   - As an authorized donor.
8. Confirm no secret is included in client bundles.
9. Confirm no private file exists inside `public`.
10. Confirm the project is ready for cPanel deployment.

---

# Part 2: Master Prompt for Sol

```text
I have attached the project requirements file for an Orphan Sponsorship Management Platform. Treat that specification, together with the requirements in this prompt, as the authoritative source of truth.

Build the complete application and make it production-ready. Do not stop after generating UI mockups, sample pages, a plan, or placeholder data.

PROJECT PURPOSE

This is a private individual initiative for managing orphan sponsorships with complete transparency for linked donors.

The admin stores orphan records, national IDs, guardian information, the father’s death certificate, contact information, bank account information, sponsorship relationships, monthly transfer records, and transfer receipts.

A donor can only access orphans linked to that donor. For linked orphans, the donor can view the full information and documents, including national IDs, the full bank account number, contact information, the father’s death certificate, monthly transferred amounts, and transfer receipts.

The platform does not accept or process online payments. Money is transferred outside the platform. The admin then records the transfer and uploads its receipt.

BUSINESS RULES

- Currency: Sudanese Pound (SDG).
- Default monthly sponsorship amount: SDG 50,000 per orphan.
- The default amount must be editable for each orphan.
- One orphan may be sponsored by multiple donors.
- One donor may sponsor multiple orphans.
- Each donor has an independent monthly contribution amount.
- Calculate the covered and remaining amounts from active sponsorship relationships.
- Preserve historical sponsorship and monthly contribution snapshots.
- Do not create a financial reviewer role.
- Age must be calculated dynamically from the date of birth.
- Do not add the father’s date of death; the death certificate file is sufficient.
- Do not add an orphan profile photo.
- Do not add a bank account verification document.
- Do not add a verification date or region field.

REQUIRED STACK

- Next.js using App Router
- TypeScript
- Tailwind CSS
- shadcn/ui or an equivalent lightweight UI system
- Supabase PostgreSQL
- Supabase Auth
- React Hook Form
- Zod
- Next.js Server Actions and Route Handlers
- No separate backend service
- Arabic-only interface with true RTL layout
- Responsive UI for desktop and mobile
- Compatible with a standard Node.js application hosted on cPanel

SUPABASE SETUP

Read the supplied environment variables and use them to connect to the intended Supabase project.

Create real SQL migrations, relationships, indexes, constraints, enums, triggers where useful, and Row Level Security policies.

If SUPABASE_ACCESS_TOKEN and SUPABASE_PROJECT_REF are available, use them only for Supabase CLI or Management API setup and migration tasks.

Never print, reveal, commit, or expose any secret value.

Security rules:

- SUPABASE_ACCESS_TOKEN is for setup and migrations only.
- SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY is server-only.
- No secret variable may use the NEXT_PUBLIC_ prefix.
- The browser may only receive the Supabase URL and publishable key.
- Never include access tokens or secret keys in source code, logs, screenshots, documentation examples, or client bundles.

AUTHENTICATION AND ROLES

Implement two roles only:

1. admin
2. donor

Implement real server-side authorization and Supabase RLS. Do not rely on hidden buttons or client-side redirects as security.

The admin can manage all orphans, donors, sponsorships, requests, monthly transfers, receipts, settings, reports, notifications, and audit logs.

The donor can view only:

- The donor’s own profile.
- Orphans connected to that donor.
- The donor’s sponsorship relationships.
- Monthly records and receipts the donor is authorized to view.
- The donor’s requests and notifications.

A donor must be denied access when trying to open an unrelated orphan or document, even if the donor knows or changes the record ID in the URL.

ORPHAN DATA

Create the orphan record with:

- Automatically generated internal case number
- Full name
- Date of birth
- Dynamically calculated age
- Gender
- Orphan national ID
- Mother or related guardian name
- Mother or related guardian national ID
- Relationship when the person is not the mother
- Contact number
- Bank account holder name
- Full bank account number
- Optional bank name
- Required father’s death certificate
- Required monthly sponsorship amount
- Default amount of 50000 SDG
- Public summary
- Donor-visible notes
- Internal admin notes
- Status
- Created and updated timestamps

Do not create fields for:

- Father’s date of death
- Orphan photo
- Bank verification document
- Verification date
- Region

LOCAL DOCUMENT STORAGE

Do not use Supabase Storage.

Store uploaded documents on the cPanel hosting filesystem in a private directory outside the Next.js public directory, using the UPLOAD_ROOT environment variable.

Example:

private_uploads/
  orphans/{orphanId}/
  transfers/{year}/{month}/

Requirements:

- Never store sensitive documents inside public.
- Rename files using UUIDs.
- Validate extension and MIME type.
- Allow PDF, JPG, JPEG, PNG, and WEBP only.
- Enforce the configured upload size.
- Prevent executable uploads.
- Never reveal the real filesystem path.
- Never generate permanent public URLs.
- Serve every file through a protected Route Handler.
- Authorize the requester before streaming or downloading the file.
- Log sensitive document views and downloads.

SPONSORSHIP SYSTEM

Create complete shared-sponsorship support.

Each relationship must store:

- Orphan
- Donor
- Monthly contribution
- Start date
- Optional end date
- Status
- Optional stop reason
- Notes
- Timestamps

Calculate:

- Covered amount = sum of active contributions.
- Remaining amount = max(0, required amount - covered amount).
- No coverage = available.
- Partial coverage = partially sponsored.
- Full coverage = fully sponsored.

Warn admins before contributions exceed the orphan’s required monthly amount.

Never delete historical sponsorship relationships when they end.

MONTHLY TRANSFERS

Create a monthly support record per orphan and month.

Store:

- Required amount snapshot
- Pledged amount snapshot
- Contributor snapshots
- Actual transferred amount
- Transfer date
- Optional reference
- Transfer status
- Donor-visible notes
- Internal notes
- Recording admin
- Transfer receipt

Support multiple partial payments for the same month. The monthly transferred total must be calculated from those payments.

Monthly statuses:

- Pending
- Partially transferred
- Transferred
- Overdue
- Paused

Future changes to sponsorship relationships must not alter old monthly records or contributor snapshots.

PUBLIC SPONSORSHIP PAGE

Create a public page for unsponsored and partially sponsored orphans.

Show only:

- Internal case number
- Calculated age
- Gender
- Public summary
- Required amount
- Covered amount
- Remaining amount
- Coverage percentage
- Status
- Request Sponsorship button

Never show names, national IDs, phone numbers, bank accounts, death certificates, or private documents publicly.

Allow logged-in donors and public visitors to submit sponsorship requests. Every request must require admin review. Accepting a request must allow the admin to create or connect the donor account and create the final sponsorship relationship.

ADMIN DASHBOARD

Build complete production-ready pages for:

- Dashboard statistics
- Orphans
- Donors
- Sponsorship relationships
- Monthly support records
- Partial payments
- Transfer receipts
- Sponsorship requests
- Notifications
- Reports
- Settings
- Audit logs

Include search, filters, pagination where appropriate, empty states, loading states, error states, validation, confirmation dialogs, and responsive mobile layouts.

DONOR DASHBOARD

Build complete pages for:

- Donor overview
- Linked orphans
- Full orphan details and documents
- Sponsorship contribution details
- Monthly transfer history
- Transfer receipts
- Sponsorship requests
- Notifications
- Profile and password management

PUBLIC WEBSITE

Create:

- Home
- About
- How Sponsorship Works
- Available Orphans
- Sponsorship Request
- Login
- Privacy Policy
- Terms of Use
- Contact

The design must be calm, trustworthy, simple, accessible, and easy for non-technical users. Use a clear Arabic font, true RTL layout, strong mobile support, readable tables or mobile cards, Arabic validation messages, and clear SDG currency formatting such as “50,000 ج.س”.

SECURITY

This system stores highly sensitive information about minors.

Implement:

- RLS and server-side authorization
- Protected routes
- Secure file access
- Rate limiting for login, public requests, and file endpoints
- Security headers
- Audit logging
- Active-account checks
- Idle session expiration
- HTTPS production assumptions
- No indexing for dashboards or protected documents
- No sensitive values in logs
- Guardian consent record for document sharing

Do not send national IDs or bank data to external analytics.

CPANEL REQUIREMENTS

The application must run as a standard cPanel Node.js Application.

It must build and start using:

npm run build
npm run start

Do not use Vercel-only features.

Create DEPLOYMENT-CPANEL.md explaining:

- Required Node.js version
- Application root
- Startup command
- Environment variables
- Supabase migration procedure
- Writable UPLOAD_ROOT setup
- Build and restart process
- HTTPS
- Database backup
- private_uploads backup and restore

Add a health endpoint at /api/health.

REQUIRED PROJECT FILES

Create:

- Complete Next.js source code
- .env.example
- README.md
- DEPLOYMENT-CPANEL.md
- SECURITY.md
- supabase/migrations/*.sql
- supabase/seed.sql with clearly fictional data
- Browser and server Supabase clients
- Central authorization helpers
- Secure local file utilities
- Reusable UI components
- Tests
- Secure first-admin creation script or documented command

EXECUTION METHOD

First:

1. Read this prompt and the attached specification completely.
2. Inspect the repository.
3. Produce a concise implementation checklist.
4. Start implementation immediately.

Work phase by phase, but do not stop after planning.

After each meaningful phase:

- Run type checking.
- Run lint.
- Run relevant tests.
- Fix errors before proceeding.

Do not leave:

- TODO comments for required functionality.
- Non-working buttons.
- Placeholder pages.
- Fake authorization.
- Mock-only database operations.
- Publicly accessible sensitive files.

FINAL VERIFICATION

Before reporting completion:

1. Run the production build.
2. Run lint, type checking, and tests.
3. Verify admin and donor workflows.
4. Verify shared sponsorship calculations.
5. Verify monthly snapshots and partial transfers.
6. Attempt to access an unrelated orphan as a donor.
7. Attempt to access protected documents without a session.
8. Attempt to access protected documents as an unrelated donor.
9. Verify authorized document access.
10. Confirm that no secret appears in the browser bundle.
11. Confirm that no private document exists under public.

In your final response, provide:

- A concise list of completed functionality.
- Applied Supabase migrations.
- How to create the first admin.
- Only the names of missing environment variables, never their values.
- Exact local run instructions.
- Exact cPanel deployment instructions.
- Test and production build results.
- Any genuine remaining blocker, if one exists.

Make reasonable small technical decisions independently. Do not change the agreed business rules or reduce the project scope without explicit approval.
```
