# Phase 0 — Product Foundation

## Vision Statement

> A modular, rule-driven Sports Organization ERP where every business capability — people, finance, scheduling, facilities, space management, assignments, attendance, inventory, pricing, and reporting — is built on generic business concepts rather than sport-specific workflows.

## The Golden Rule

**No module invents its own concepts.** Every module composes from the business language defined here.

---

## Core Business Entities

These are the abstract building blocks. Every table, every model, every service builds on top of these.

### Person
The universal human identity. Everyone is a Person first — before they become a participant, trainer, staff, or guardian. A single human exists exactly ONCE in the system.

### Organization
The top-level tenant. An academy, club, or sports center. Owns everything below it.

### Branch
A physical or logical division of an Organization. One organization can have many branches. Some rules differ per branch.

### Activity
A type of sport or activity the organization offers. Football, Swimming, Karate, Chess, Music. Activities are NOT hardcoded — they are configurations.

### Service
Anything the organization can offer and charge for. A Training Program is one type of service. Tomorrow: private coaching, camps, tournaments, equipment rental, birthday events. The service catalog is infinitely extensible.

### Training Program
The commercial product — what the academy SELLS. Defines rules, pricing, capacity, duration, and requirements. Does NOT contain actual participants or schedules.

### Training Group
An operational instance of a program. Contains real people, real schedules, and real assignments. Many groups can exist under one program.

### Activity Session
The atomic operational event where everything converges — group, facility, space, trainers, participants, equipment, attendance. Generated from schedules.

### Facility
A physical place. Football field, pool, gym, court. Has capacity, operating hours, maintenance status, and ownership type (owned/rented/shared).

### Space Layout
A temporary physical division of a facility during a specific time window. NOT permanent — changes per time slot.

### Space Segment
One bookable unit within a layout. Could be a grid cell, swimming lane, half-court, tatami, named zone. The scheduling engine doesn't care what shape it is.

### Assignment
A responsibility given to a person for a period of time. Target can be anything: program, group, session, facility, area, equipment, event, branch. Roles are unlimited and configurable.

### Attendance
Proof that a person was present (or absent) for something they were expected to attend. Subjects: players, trainers, staff, volunteers, visitors. Sources: sessions, shifts, events, meetings.

### Financial Transaction
An immutable ledger entry. Double-entry: every movement has a debit account and credit account. Never edited — corrections create new entries.

### Product
A physical or virtual item that can be sold. Equipment, uniforms, merchandise. Tracked in inventory.

### Kit
A virtual bundle of products sold as a package. Assembled at point of sale — reduces stock of component items.

### Inventory
Quantity tracking of products across locations (warehouses, stores, branches). Every movement is recorded with a reason.

### Supplier
An external entity from which products are purchased.

### Purchase
A procurement transaction — ordering products from a supplier and receiving them into inventory.

### Participant
A Person enrolled in one or more activities. Has classifications, guardian links, medical info, enrollment history.

### Employee
A Person employed by the organization. Has department, position, employment type.

### Trainer
A specialized Employee (or contractor) who delivers activities. Has qualifications, sports, compensation model, availability.

### Customer
Any billable entity. Could be a Participant, a Guardian paying on behalf of a child, a Company renting a facility, or any future payer type.

### Pricing Rule
A configurable rule that determines or modifies a price. Rules stack, have priorities, and can conflict — the Pricing Engine resolves them.

### Business Rule
A configurable rule that governs any business decision: eligibility, approval, booking, assignment, attendance thresholds. The platform is RULE-DRIVEN, not code-driven.

### Notification
A message sent to a person through any channel: SMS, Email, WhatsApp, Push, Internal. Templated, logged, retriable.

### Document
A generated output: invoice PDF, receipt, contract, certificate, attendance report, enrollment form. Uses editable templates.

### Audit Record
An immutable log of who did what, when, and why. Every business action produces an audit record. Used for compliance, dispute resolution, and change tracking.

---

## Entity Relationships (Conceptual)

```
Organization
├── Branch (1:many)
├── Person (1:many — through registration)
│   ├── Participant (1:1 specialization)
│   ├── Employee (1:1 specialization)
│   │   └── Trainer (1:1 further specialization)
│   ├── Guardian (role — links to participants)
│   └── Customer (role — billable)
├── Activity (1:many)
│   └── Training Program (1:many per activity)
│       └── Training Group (1:many per program)
│           ├── Enrollment (many:many with Participant)
│           ├── Assignment (many:many with Person via roles)
│           ├── Training Schedule (1:many)
│           │   └── Activity Session (generated, 1:many)
│           │       ├── Attendance Record (1:many)
│           │       ├── Space Reservation (1:many)
│           │       └── Assignment (session-level overrides)
│           └── Facility (assigned via schedule)
├── Facility (1:many)
│   ├── Space Layout (1:many, time-bound)
│   │   └── Space Segment (1:many)
│   │       └── Space Reservation (1:many, time-bound)
│   └── Operating Hours (1:many)
├── Financial Account (1:many — chart of accounts)
│   └── Transaction (1:many — immutable ledger)
├── Invoice (1:many)
│   ├── Invoice Item (1:many)
│   ├── Payment (1:many)
│   └── Payment Plan (1:1 optional)
│       └── Installment (1:many)
├── Wallet (1:many — per customer)
│   └── Wallet Transaction (1:many)
├── Product (1:many)
│   └── Inventory Movement (1:many)
├── Kit (1:many)
│   └── Kit Item (1:many)
├── Pricing Rule (1:many)
├── Business Rule (1:many)
├── Template (1:many)
├── Notification Log (1:many)
└── Audit Log (1:many — everything tracked)
```

---

## Cross-Cutting Concerns (Apply to EVERY Entity)

These are NOT afterthoughts. They are baked into every migration, every model, every service from day one.

### 1. Multi-Tenancy
- Every business table has `academy_id` (FK to organizations)
- Global query scope auto-filters by current tenant
- SuperAdmin bypasses tenant scope

### 2. Multi-Branch
- Business tables that are branch-specific have `branch_id` (nullable — null means "all branches")
- Users can be assigned to one or more branches
- Queries can filter by branch within a tenant

### 3. Access Control (RBAC + ABAC Hybrid)
- Roles: SuperAdmin, AcademyOwner, BranchManager, FinanceManager, Trainer, Receptionist, Parent, custom...
- Permissions: granular, per-module, per-action (view, create, edit, delete, approve, export)
- Attribute-based rules: "Can only see participants in their own branch", "Can only edit invoices they created"
- Permission matrix: Role × Module × Action × Scope (own/branch/academy/all)

### 4. Audit Trail
- Every CREATE, UPDATE, DELETE logged with: who, what, when, old values, new values
- Immutable — audit records can never be edited or deleted
- Login history: IP, user agent, success/failure
- Financial actions: double-logged (financial audit + general audit)

### 5. Status Lifecycle
- Every business entity with a status has a defined state machine
- Valid transitions are enforced (can't go from "cancelled" to "active")
- Status changes produce audit records and can trigger notifications

### 6. Soft Deletion
- All business entities use soft delete
- Deleted records remain queryable for historical reports
- Permanent purge is a SuperAdmin action with additional confirmation

### 7. Attachments
- Polymorphic `attachments` table: any entity can have files
- Types: documents, images, certificates, contracts, receipts
- Storage: local disk (CapRover persistent volume) or S3 (future)

### 8. Notes
- Polymorphic `notes` table: any entity can have internal notes
- Notes are audit-logged (who wrote what, when)
- Notes can be pinned, marked internal-only, or flagged

### 9. Search & Filtering
- Every list view supports: text search, date range, status filter, custom field filters
- Reusable filter components per module
- Saved filters per user (future)

### 10. Bulk Actions
- Select multiple records → apply action (change status, delete, export, assign, notify)
- Bulk actions respect permissions and produce audit records per item

### 11. Import/Export
- CSV import for initial data migration (participants, products, accounts)
- Excel export for any filtered list view
- Export respects current filters and permissions

### 12. Approval Workflows
- Configurable: which actions require approval, by whom
- Examples: refunds > 500 EGP need manager approval, program cancellation needs director approval
- Pending approvals dashboard for approvers

### 13. Notifications
- Every significant business event can trigger notifications
- Channel preferences configurable per user (email, SMS, push, internal)
- Templates per event type (editable in CMS)

### 14. Localization
- Arabic primary (RTL), English secondary
- All user-facing strings bilingual (`name` + `name_ar`)
- Currency: EGP default, configurable per organization
- Date format: configurable (Gregorian primary, Hijri optional)
- National ID: Egyptian format default, extensible

### 15. Historical Records
- Price at time of sale (not current price)
- Status at time of report (snapshots for period reports)
- Assignment history (who was assigned when, not just current)
- Enrollment history (transfers, freezes, withdrawals preserved)

---

## Technical Foundation Rules

### Amounts
- ALWAYS stored as integers (piasters, not pounds)
- 1 EGP = 100 piasters
- Display layer converts to human-readable
- NEVER use floats for money

### UUIDs
- Every business entity has a `uuid` column (for public API/URLs)
- Internal relationships use `id` (bigint) for performance
- Route model binding uses `uuid` (never expose auto-increment IDs)

### Timestamps
- `created_at`, `updated_at` on every table
- `deleted_at` for soft deletes
- Business-meaningful dates are separate columns (`issue_date`, `payment_date`, `session_date`)

### JSON Columns (PostgreSQL JSONB)
- Used for: settings, metadata, flexible attributes, operating hours
- NOT used for: relationships, queryable business data, amounts
- Always have a default `'{}'` to avoid null handling

### CHECK Constraints
- Every status column has a PostgreSQL CHECK constraint
- Every type/category column has a CHECK constraint
- Enums in PHP mirror the CHECK values exactly

### Indexes
- Every `academy_id` column is indexed
- Every `status` column is indexed (composite with academy_id)
- Every foreign key is indexed
- Date columns used in range queries are indexed
- Unique constraints on business identifiers (invoice number per academy, national ID per academy)

---

## What This Document Gates

Nothing gets built without conforming to:
1. The entity definitions above
2. The cross-cutting concerns
3. The technical rules

If a new feature needs a concept not listed here, it gets added here FIRST, then built.
