# Sunfix System Overview

## 1. System Overview

Sunfix is an enterprise-grade beach reservation and services management platform that connects customers, beach operators (providers), vendors, and administrators. The system enables discovery and reservation of beach chairs, events, and ancillary services, supports real-time operational workflows, payment processing, provider settlements, and analytics. The backend serves RESTful APIs for web and mobile clients, implements real-time channels for live updates and chat, and operates event-driven processes for notifications, reconciliation, and reporting. It is designed for high availability, observability, and incremental evolution from a modular monolith toward service-oriented or microservice architectures as required by scale.

Primary audiences:
- Consumers (mobile/web) booking beach services.
- Providers managing inventory and fulfillment.
- Admins and finance teams overseeing operations and reconciliation.
- Vendors providing third-party services (catering, entertainment).
- Support and operations teams for incident response and customer care.

Key design goals:
- Operational reliability: consistent booking and payment outcomes.
- Real-time responsiveness: updates, chat, and alarms delivered instantly.
- Financial traceability: full audit trails for transactions and settlements.
- Extensibility: modular boundaries for new features and service extraction.
- Security & compliance: secure payment handling, data protection, and access control.

---

## 2. User Roles

### Customer
Responsibilities:
- Discover beaches, view availability and pricing.
- Reserve chairs, events, and add-ons.
- Pay, manage bookings, request cancellations, and receive notifications.
Business privileges:
- Create/read/update own bookings and profile.
- Use in-app wallet, view receipts, and communicate with providers via chat.
Interactions:
- Primary consumer of Booking, Payment, Notification, Chat, and Dashboard modules.

### Provider (Beach Operator)
Responsibilities:
- Manage inventory (zones, chairs), pricing, schedules.
- Accept or reject bookings where applicable, manage check-in/out.
- Manage staff (Manager/Employee) and vendor assignments.
Business privileges:
- CRUD on inventory and services; view bookings and financial reports.
- Trigger provider-side cancellations and mark fulfillment.
Interactions:
- Heavy interaction with Inventory, Booking, Order, Payment, Notification, and Reporting modules.

### Manager / Employee
Responsibilities:
- Operational handling: check-ins, manifests, local adjustments.
- Limited administrative tasks within provider scope.
Business privileges:
- Manage bookings and daily operations; restricted financial actions.
Interactions:
- Uses Dashboard, Booking, Notification, and Scheduling modules.

### Vendor
Responsibilities:
- Fulfill third-party services assigned to orders (e.g., catering).
Business privileges:
- View assigned orders and update fulfillment status.
Interactions:
- Order Module, Notification Module, and Chat Module.

### Admin / Super Admin
Responsibilities:
- Global configuration, user/provider onboarding, financial reconciliations, and audits.
Business privileges:
- Full system access, policy management, and emergency overrides.
Interactions:
- All modules; particularly Reporting, Payment, User Management, and Admin Management.

### Support Agent
Responsibilities:
- Customer service, dispute resolution, manual adjustments.
Business privileges:
- Access to booking details, chat, constrained edit capabilities for remediation.
Interactions:
- Chat, Booking, Notification, and Audit logs.

### Auditor / Finance
Responsibilities:
- Reconciliation, reporting, export of financial data.
Business privileges:
- Read-only or limited write access to transaction and settlement records.
Interactions:
- Reporting, Payment, and Audit systems.

---

## 3. Core Modules

For each module below: responsibilities, internal behavior, business logic, and integration points are described.

### Authentication Module
Responsibilities:
- Centralized identity and session management; OTP and password flows.
Internal behavior:
- Manages registration, login, JWT issuance, refresh tokens, and session invalidation. Integrates OTP generation and verification through Notification Module.
Business logic:
- Enforce password policies, MFA for privileged flows, device/session management, login throttling.
Interactions:
- Applies to all APIs; interacts with User Management for roles, Audit logging for auth events, Notification for OTP delivery.

### User Management Module
Responsibilities:
- Profile and role lifecycle, permission assignment, FCM/APNs token management, provider-user relationships.
Internal behavior:
- Persist user metadata, KYC flags, role/permission mappings, and soft-deletion semantics.
Business logic:
- Role-based permission enforcement, provider affiliation workflows, profile verifications.
Interactions:
- Used by RBAC middleware, Dashboard for account views, Payment for KYC-dependent payouts.

### Booking Module
Responsibilities:
- Reservation life-cycle orchestration and seat/slot allocation.
Internal behavior:
- Coordinates availability checks, temporary holds, final confirmations, cancellations, and no-show rules. Supports optimistic locking or allocation tokens to prevent race conditions.
Business logic:
- Booking validation (capacity, time windows, provider rules), hold expiry, deposit vs full-pay flows, cancellation rules with penalty logic.
Interactions:
- Inventory (allocation), Payment (authorize/capture/refund), Scheduling (recurrence), Notification (user/provider updates), Reporting (booking metrics), Real-Time (live updates).

### Inventory Module
Responsibilities:
- Canonical store of beaches, zones, chairs, capacities, and services.
Internal behavior:
- Maintains time-slot calendars, capacity rollups, blackout dates, and dynamic pricing hooks.
Business logic:
- Capacity constraints, allocation strategies (first-come, priority), maintenance blocks, automatic release of held resources.
Interactions:
- Consulted by Booking and Pricing engines; broadcasts updates to cache and real-time channels; feeds Reporting.

### Order Module
Responsibilities:
- Represent confirmed purchase items, vendor assignments, and fulfillment workflows.
Internal behavior:
- Tracks order line items, fulfillment states, vendor acceptance, and status transitions.
Business logic:
- Order lifecycle transitions (Pending, Accepted, In-Progress, Fulfilled, Cancelled), vendor commission calculations.
Interactions:
- Payment Module for captures and payouts; Notification Module for confirmations; Inventory for resource mark-off.

### Payment Module
Responsibilities:
- Orchestrates payments, refunds, platform fees, wallet ledger, and settlement flows.
Internal behavior:
- Implements gateway adapters, idempotency, transaction records, and reconciliation tasks.
Business logic:
- Fee calculation, split payments, holds vs captures, refund rules and chargeback handling.
Interactions:
- Triggered by Booking and Order modules; emits events to Reporting and Accounting; processes gateway webhooks.

### Wallet / Ledger Subsystem
Responsibilities:
- Internal ledger for customer/provider balances, promotions, and deposit handling.
Internal behavior:
- Transactional writes with strong consistency guarantees. Event-sourced history for auditability.
Business logic:
- Top-ups, refunds, holds, auto-apply promotions, provider payouts.
Interactions:
- Payment Module (top-ups, payouts), Booking (use wallet for payments), Reporting (balance reports).

### Chat Module
Responsibilities:
- Enables customer-provider and support communication with message history.
Internal behavior:
- Stores conversations, enforces retention policies, supports attachments and message metadata.
Business logic:
- Access controls, rate limits, profanity and attachment scanning (optional).
Interactions:
- Real-Time for live delivery, Notification for push triggers, User Management for identity mapping.

### Notification Module
Responsibilities:
- Orchestrates email, SMS, push, and in-app notifications.
Internal behavior:
- Templates, channels, retry/backoff, scheduling, and deduplication.
Business logic:
- Event-to-template mapping, rate-limits per user, escalation rules for critical alerts.
Interactions:
- Subscribes to domain events (BookingCreated, PaymentSucceeded, BookingCancelled), leverages Queue workers for delivery reliability, integrates with SMTP, Twilio, FCM/APNs.

### Scheduling Module
Responsibilities:
- Manages recurring events, manifests, reminders, and automated policy checks.
Internal behavior:
- Central scheduler that enqueues jobs, uses distributed locks for single execution, and triggers notifications and reconciliation flows.
Business logic:
- Recurrence rules, auto-cancellation windows, buffer times, manifest generation.
Interactions:
- Invokes Booking, Notification, Reporting modules; enqueues background tasks to workers.

### Analytics & Reporting Module
Responsibilities:
- Aggregates business metrics, supports ad-hoc and scheduled reports, and provides data exports.
Internal behavior:
- Event ingestion pipeline, ETL to analytics store/data warehouse, aggregates for dashboards.
Business logic:
- KPI calculations (occupancy, revenue, cancellations), provider settlements, trend analysis.
Interactions:
- Consumes events from Booking, Payment, and Order modules; powers Dashboard and Admin reporting; integrates with BI tools.

### Dashboard Module
Responsibilities:
- Operator and Admin dashboards for operations, finance, and analytics.
Internal behavior:
- Read-optimized endpoints, role-scoped views, and real-time data feeds.
Business logic:
- Conditional UIs for roles, operational controls (confirm/cancel), manifests, and reconciliation actions.
Interactions:
- Aggregates data from Reporting and Booking modules; writes via Booking/Order APIs; listens to real-time updates.

### Admin Management Module
Responsibilities:
- Platform configuration, policy management, user/provider onboarding, and audit controls.
Internal behavior:
- Centralized settings store, audit trail, and admin action logs.
Business logic:
- Approvals, manual overrides, provider verification, financial settlement controls.
Interactions:
- Coordinates with User Management, Payment, Reporting, and Notification modules.

---

## 4. Workflow Architecture

This section describes the canonical request and booking lifecycle, including validation, state transitions, approvals, and cancellation.

### Discovery & Availability
- Client queries REST API (/api/v1/beaches, /api/v1/inventory) with filters.
- Inventory Module returns availability snapshots (cache-accelerated) and pricing metadata.
- Clients may receive real-time updates if subscribed to resource channels.

### Reservation Request (Create)
1. Client issues POST /api/v1/bookings with requested slot and payment intent.
2. API Gateway performs authentication and basic validation middleware (rate-limit, schema validation).
3. Booking Module executes domain validation:
   - Check inventory for capacity/time conflicts.
   - Evaluate provider rules (min/max booking, blackouts).
   - Apply business rules (promotions, wallet use).
4. If checks pass, Booking Module creates a temporary hold transaction and persists a "Pending" booking with hold expiry metadata.
5. Emit domain event "BookingPending" to the event bus.

### Payment & Confirmation
- Payment Module is invoked to create an authorization or payment intent.
- On payment success:
  - Booking transitions from Pending -> Confirmed.
  - If provider policy specifies, capture may be immediate or deferred.
  - Enqueue notifications and real-time broadcasts.
- On payment failure:
  - Booking remains Pending or transitions to Failed depending on retriable status.
  - Holds are released after configured timeout.

### Fulfillment & Live State
- Provider or staff mark booking as Checked-In -> In-Use.
- On completion, booking transitions to Completed; post-processing jobs update reporting and schedule provider payouts.
- Status changes are emitted as domain events and broadcast in real-time.

### Cancellation & Refunds
- Cancellation requests validated against policy (time windows, penalties).
- If eligible for refund, Payment Module initiates refund flows and ledger updates.
- Booking transitions to Cancelled with metadata on refund and penalties.
- Notifications sent to affected parties; inventory is released.

### Approval / Rejection (Manual Flows)
- Certain flows (high-value bookings, flagged KYC issues) create an Admin task.
- Admin reviews and either approves (booking confirmed) or rejects (booking cancelled/refunded).
- Actions recorded in Admin Management logs and audit trails.

### Validation Flow
- Validation is layered: API-level (format), service-level (business), and background checks (fraud/KYC).
- Invalid or suspicious requests annotate the booking and trigger manual or automated review.

### State Transition Summary
- Typical states: Pending -> Confirmed -> In-Use -> Completed
- Exception states: Failed, Cancelled, Expired, Disputed
- Transitions are deterministic and recorded with timestamps and actor metadata.

### Real-Time Updates
- Event bus + broadcaster push state changes to subscribed clients.
- Chat messages and operational alarms are delivered instantly.
- Provider dashboards maintain near-real-time occupancy and booking feeds.

---

## 5. Payment Architecture

Sunfix's payment subsystem ensures secure, auditable financial operations across authorizations, captures, refunds, and settlements.

### Gateway Integrations
- Adapters abstract Stripe, Square, PayPal, and other gateways.
- Idempotency keys and retry logic protect against double-charges.
- Secrets and keys managed in environment vaults and rotated regularly.

### Stripe / PayPal Handling
- Payment intents (Stripe) and equivalent PayPal flows are supported.
- Supports direct and delayed capture patterns; supports 3DS and SCA where required.
- Webhook endpoints verify signatures and enqueue background reconciliation tasks.

### Marketplace Fee System
- On checkout, platform fee is calculated per order and stored in transaction metadata.
- Supports split payments and disbursements:
  - Direct charge to provider (if supported by gateway) OR
  - Platform capture then transfer to provider ledger with scheduled payouts.

### Wallet Architecture
- Internal ledger with transaction types: top-up, hold, capture, refund, payout.
- Wallet operations are atomic and event-sourced for traceability.
- Wallet holds are used for deposits and can be released or converted to charges.

### Due Payments & Holds
- Hold semantics for reservations: pre-authorization or temporary reserve.
- Automatic hold expiry and notifications to user to complete payments.
- Business rules define deposit percentages and full payment windows.

### Refund Logic
- Refund eligibility determined by cancellation policies and provider-specific rules.
- Refunds processed via gateway with idempotency and reconciled against ledger entries.
- Partial refunds and fee handling are supported; audit trails retained.

### Webhook Handling
- Webhook endpoints validate signatures and enqueue events to the queue for eventual consistency processing.
- Webhook consumers update booking/payment states and trigger reconciliation jobs.
- Retries and dead-letter queues handle persistent failures.

### Transaction Lifecycle
- Transaction records include: request_id, gateway_id, amount, fees, status, timestamps, and related booking/order.
- Immutable logs for financial audits; exports for accounting.

---

## 6. Real-Time Communication

Real-time capabilities provide responsiveness for bookings, chat, and operations.

### WebSockets & Broadcasting
- Stateless WebSocket servers behind a load balancer or managed service (Pusher, Realtime provider).
- Broadcasting uses Redis Pub/Sub or a dedicated message broker to fan-out domain events to WebSocket servers.
- Channels are namespaced by tenant/provider and resource to enforce access.

### Laravel Reverb / Broadcasting Layer
- Event-driven broadcasting of domain events through a broadcaster layer (e.g., Laravel Echo + Pusher/Socket, or custom socket clusters).
- Reverb (Laravel broadcasting extensions) may be used for efficient pub/sub and to integrate worker-emitted events.

### Chat & Live Updates
- Chat uses the same real-time channels; messages persisted to storage and delivered via WebSocket and push notifications.
- Typing indicators, read receipts, and presence are supported.

### Queue Workers & Background Processing
- Long-running or unreliable tasks are offloaded to workers (queue consumers).
- Workers process notifications, webhooks, reconciliation, and heavy analytic ETL jobs.
- Worker autoscaling responds to queue depth and job latency.

### Push Notifications
- Mobile push via FCM and APNs; Notification Module composes platform-specific payloads.
- Push fallbacks: in-app/bulk email/SMS for critical messages.

### Event-Driven Updates
- Domain events decouple producers and consumers, enabling scalable rule additions and downstream processing without coupling.
- Event schema evolution managed with versioning and backward compatibility guarantees.

---

## 7. API Architecture

### REST API Structure
- Versioned APIs: /api/v1/..., with clear resource-based endpoints (bookings, payments, inventories, users).
- Consistent request/response contracts, standardized error models, and pagination.

### Route Organization & Modular Architecture
- Routes grouped by functional module and guarded by middleware stacks.
- Provider and Admin routes isolated with explicit scopes.
- Controllers thin; business logic encapsulated in service/domain layers to facilitate extractability.

### JWT Authentication & Sessions
- JWT tokens for mobile; optional stateful sessions for web admin with CSRF protections.
- Access tokens include scopes and role claims to enable RBAC without database lookups on every request (short-lived tokens + refresh).

### Middleware Usage
- Common middleware: authentication, authorization, input validation, rate-limiting, logging, error handling, and metrics.
- Service-level guards validate business constraints beyond simple schema checks.

### RBAC Authorization
- Role and permission model stored in User Management; middleware enforces actions based on required permissions.
- Fine-grained checks inside domain services to prevent privilege escalation.

### API Scalability
- API Gateway for routing, authorization, and rate-limiting.
- Autoscaled stateless app servers behind load balancers.
- Caching layer (Redis, CDN) for read-heavy endpoints.
- Circuit breakers and bulkheads for external dependency resilience.

### Mobile / Web Client Communication
- Support for JSON over HTTPS with optimized payloads for mobile.
- Optional real-time channels for live updates; webhooks for server-to-server integrations.

---

## 8. Database & Infrastructure

### Database Architecture
- Primary relational database (MySQL/Postgres) for transactional consistency.
- Read replicas for reporting and analytics queries.
- Partitioning and archiving strategies for high-volume tables (transactions, events).
- Audit-log and event-store tables for immutable history.

### Queue System
- Redis queues or RabbitMQ as message broker.
- Separate queues by priority and task type (notifications, payments, reconciliation).
- Dead-letter queues and monitoring for job failures.

### Redis Usage
- Caching hot datasets (availability, pricing).
- Session/state store for rate-limiting and locks.
- Pub/Sub for real-time broadcaster.
- Distributed locks to coordinate scheduled jobs.

### Scheduler Jobs & Background Workers
- Cron-like scheduler enqueues periodic jobs: settlement runs, hold expiries, daily manifests, and report exports.
- Worker fleet deployed separately from API processes for resiliency.

### VPS / Cloud Deployment
- Containerized deployments (Docker) orchestrated by Kubernetes or managed container services.
- Separate clusters/namespaces per environment (dev/stage/prod).
- Load balancers, auto-scaling groups, and health checks for HA.

### File Storage Strategy & CDN
- User uploads and static assets stored on object storage (S3-compatible) with lifecycle policies.
- CDN (CloudFront/Akamai) for static assets and signed URL delivery for private content.
- Use pre-signed upload URLs to allow secure direct uploads from clients.

### Third-Party Integrations
- Payment gateways, SMS/email providers, push services, analytics and monitoring providers.
- Integration adapters with retry policies, throttling, and circuit breakers.

### Observability
- Centralized logging (ELK/EFK), metrics (Prometheus), tracing (Jaeger), and dashboards (Grafana).
- Alerts for queue latency, payment failures, and service errors.

---

## 9. Security Overview

### Authentication Security
- Enforced strong password requirements and optional 2FA/OTP.
- Token rotation, refresh token revocation, and session management.
- Rate-limited authentication endpoints and banned credential lists.

### Authorization
- RBAC enforced at middleware and service layers.
- Granular permissions for admin/provider actions; principle of least privilege.

### Protected Routes & Data Access
- Sensitive endpoints require elevated scopes and additional verification.
- Parameterized queries and ORM safeguards to mitigate injection.
- Data masking for exports and limited PII visibility in dashboards.

### Validation Layers
- Multi-layer validation: API schema validation, domain invariants, and background fraud checks.
- Input sanitization and content scanning for uploads.

### Rate Limiting & Abuse Prevention
- Per-user, per-IP, and per-route rate-limits.
- Circuit breakers for third-party dependencies; progressive throttling for abusive clients.

### Webhook Validation
- Signature verification for incoming webhooks with replay window checks.
- Idempotency and deduplication on webhook processing.

### Secure Transactions & PCI Considerations
- Prefer tokenized payment flows; minimal storage of card data.
- Use gateway-hosted pages or SDKs where possible to avoid PCI scope.
- Regular audits and logging of financial operations.

### Data Protection & Compliance
- Encryption at rest and in transit (TLS 1.2+), database field-level encryption for sensitive data.
- Data retention policies, consent management, and compliance with regional data regulations.
- Role-based access to backups and export controls.

---

## 10. Scalability Architecture

### Horizontal Scaling
- Stateless application servers enable simple horizontal scaling.
- Autoscaling policies based on CPU, request latency, and queue depth.

### Modular Expansion & Service Separation
- Modular monolith approach: clearly separated domain modules within a single deployable initially.
- Easy extraction into microservices (payments, notifications, booking) when operational scale demands.

### Multi-Tenant Considerations
- Logical multi-tenancy via tenant_id scoping initially; option for database-per-tenant when isolation or compliance mandates it.
- Tenant-aware caches and rate-limits.

### Queue Scalability
- Multiple queue backends, prioritized processing, and dedicated worker pools for heavy tasks.
- Partitioned queues for high-throughput event streams.

### High-Traffic Handling
- Cache-first strategies for read-heavy endpoints; CDN for static content.
- Graceful degradation: non-critical features (analytics, personalized recommendations) may defer under heavy load.
- Circuit breakers and backpressure to protect core booking flows.

### Microservice Migration Strategy
- Extract services along bounded contexts and communicate via event bus (Kafka/RabbitMQ) and HTTP/gRPC.
- Maintain backward-compatible API contracts and consumer-driven contracts during migration.

---

## 11. Deployment Architecture

### Production Deployment Flow
- CI pipelines validate code, run tests, build images, and produce artifacts.
- CD pipelines deploy to staging, run smoke tests, and promote to production after approval.
- Immutable deployments with versioned releases.

### CI/CD Overview
- Stages: lint -> unit tests -> integration tests -> build -> image push -> deploy -> smoke tests.
- Environment-specific configuration via encrypted secrets manager and infrastructure as code.

### Environment Management
- Distinct environments (dev/stage/prod) with mirrored infra topology.
- Feature flags for progressive rollout and A/B testing.

### Queue & Background Worker Deployment
- Worker deployment independent from API servers to scale processing separately.
- Blue/green or rolling updates with drained queues before shutdown to avoid job loss.

### Real-Time Server Deployment
- WebSocket clusters deployed with sticky sessions or using a shared session store and token-based authentication.
- Broadcaster service scales to fan-out events reliably.

### Monitoring & Logging Strategy
- Health probes, metrics, and alerting integrated into deployment pipeline.
- Log aggregation with structured logs and tracing to troubleshoot distributed flows.
- SLOs and SLIs defined for key user flows (booking creation latency, payment success rate).

---

## 12. Conclusion

Sunfix is architected as a robust, scalable backend platform tailored for operational reliability and rapid business evolution. The design balances immediate operational needs (transactional integrity, real-time updates, and secure payments) with long-term maintainability (modular boundaries, event-driven architecture, and observability). The platform supports complex business rules for bookings, provider settlement models, and integrated vendor workflows while prioritizing fault-tolerant payment and notification handling. With clear migration paths to microservices, multi-tenant patterns, and autoscaling infrastructure, Sunfix is positioned for enterprise deployments and extended growth.

---

PROJECT INFORMATION:
Sunfix — a beach reservation and services management platform enabling discovery, reservation, provider operations, payments, and real-time communications between customers, providers, vendors, and administrators.

TECH STACK:
Laravel (PHP) backend, MySQL/Postgres primary database, Redis for caching/queues/pubsub, Docker, Vite + Tailwind frontend, WebSockets / Pusher or managed realtime provider, Stripe / Square / PayPal payment gateways, FCM/APNs for push notifications, RabbitMQ or Redis queues, Prometheus/Grafana observability stack, ELK/EFK logging.

FEATURES:
- OTP and optional multi-factor authentication
- Wallet and ledger system for deposits/refunds
- Provider payouts and settlement reporting
- Real-time chat and operational notifications
- Exportable financial and operational reports
- Audit logs and admin management tooling
- Modular architecture to support future service extraction and multi-tenant expansion
