Commit 100e6ffe authored by Mahmoud Aglan's avatar Mahmoud Aglan

init

parents
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[{compose,docker-compose}.{yml,yaml}]
indent_size = 4
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.codex
/.cursor/
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/fonts-manifest.dev.json
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
ignore-scripts=true
audit=true
Welcome to the EL-Captain Brand Identity & Design System presentation. As your branding agency, we have approached this project with a singular vision: to position EL-Captain as the definitive "Command Center" for membership-based organizations.
We have stripped away any clichéd sports imagery to focus on what matters to enterprise clients and academy founders: Trust, Navigation, Control, and Scale. The following comprehensive brand identity is designed to stand alongside industry giants like Stripe, Linear, and Atlassian.
1. Brand Strategy & Personality
The Core Idea: The Modern Operating System for Leadership.
EL-Captain is not just management software; it is the silent partner that brings order to chaos. It guides organizations to operate with precision.
Brand Archetype: The Ruler / The Sage (Authoritative, organized, analytical, and empowering).
Voice: Clear, concise, confident, and professional.
Keywords: Command, Navigation, Trust, Precision, Enterprise, Connected.
2. Logo Concepts & Rationale
We have developed three distinct directions for the EL-Captain visual identity. All are flat, geometric, scalable, and function perfectly in monochrome.
Concept 1: The Commander's Compass (Recommended)
The Mark: A minimalist, geometric monogram integrating the letter 'C' with a subtle, abstract compass needle in the negative space. The needle points 'North-East' (up and to the right), universally symbolizing growth, forward momentum, and navigation.
The Wordmark: Clean, custom-tracked sans-serif with a slightly bolder weight on "EL" to anchor the name.
Rationale: Captures the essence of a "Captain" navigating a ship. It communicates leadership and direction without relying on literal maritime or sports imagery.
Concept 2: The Vanguard Shield
The Mark: A highly simplified, tech-forward shield constructed from two interlocking 'L' shapes (nodding to EL and leadership) that form a protective, solid 'C' in the center.
Rationale: Speaks directly to data security, trust, and organizational integrity—crucial for enterprise clients managing thousands of members and financial data.
Concept 3: The Connected Nodes
The Mark: Three distinct geometric pillars (representing Members, Staff, and Facilities) seamlessly connected by a singular sweeping line that forms the letter 'E'.
Rationale: Focuses on the "All-in-One" nature of the CRM/ERP system, emphasizing community, organization, and seamless integration.
Iconography & Sizing Rules
App Icon: The standalone mark (Compass, Shield, or Nodes) placed precisely in the center of a solid Midnight Blue square with a subtle 10% corner radius.
Favicon: A stripped-down, thickened version of the mark optimized for 16x16 pixel rendering.
Clear Space: The minimum clear space around the logo must be equal to the height of the "C" in the wordmark.
3. Color System
We have selected a variation of Option D, optimized for modern SaaS interfaces. It exudes enterprise authority while maintaining a sharp, modern technological edge.
Core Brand Palette
Color Name HEX Code RGB Value Usage
Midnight Blue #0B132B 11, 19, 43 Primary brand color, primary text, dark mode backgrounds.
Electric Blue #1D4ED8 29, 78, 216 Primary CTA buttons, active states, key brand accents.
Cloud White #FFFFFF 255, 255, 255 Light mode backgrounds, text on dark buttons.
Slate Gray #64748B 100, 116, 139 Secondary text, inactive icons, subtle borders.
Semantic & UI Palette (Light / Dark Mode)
Semantic Role Light Mode (HEX) Dark Mode (HEX) Purpose
Success #10B981 (Emerald) #059669 Payment confirmed, attendance logged.
Warning #F59E0B (Amber) #D97706 Pending invoices, expiring memberships.
Error #EF4444 (Rose) #DC2626 Failed payments, system errors.
Information #3B82F6 (Blue) #2563EB Tooltips, general system notifications.
Surface #F8FAFC (Cool White) #1E293B Card backgrounds, sidebar panels.
Borders #E2E8F0 (Light Gray) #334155 Dividers, table borders, input outlines.
Accessibility Note: Electric Blue (#1D4ED8) on Cloud White (#FFFFFF) provides a contrast ratio of 7.1:1, easily passing WCAG AAA standards for normal text.
4. Typography System
We recommend a dual-font system that balances marketing appeal with extreme dashboard utility.
Primary/UI Font: Inter
Why: Inter is the gold standard for dense, data-heavy dashboards. Its tall x-height and exceptional legibility at small sizes (like 11px table data) make it perfect for the EL-Captain ERP/CRM features.
Display/Marketing Font: Plus Jakarta Sans
Why: Used for headings, landing pages, and the logo wordmark. It has a geometric, modern tech feel (similar to Stripe and Linear) that commands attention and feels premium.
5. UI Design Language
The UI must feel like a high-end financial or productivity tool—quiet, organized, and frictionless.
Cards & Containers: Flat design. Use Surface colors rather than heavy drop shadows to distinguish cards.
Shadows: Extremely subtle. Only use drop shadows for floating elements (dropdowns, modals, popovers) to establish z-index hierarchy.
Border Radius: 6px for buttons and inputs. 12px for larger cards and modals. This slight rounding feels modern but retains an architectural, structured edge.
Input Fields & Forms: Minimalist. A 1px solid border (#E2E8F0), transitioning to a 2px Electric Blue border on focus. Labels should be crisp, uppercase, and tracked out.
Tables: The core of the software. Striped rows should be avoided; instead, use generous padding (16px vertical) and thin, 1px horizontal dividers to maintain a breathable layout.
Grid & Spacing: Based on a strict 8pt grid system. Spacing should be predictable (8, 16, 24, 32, 48, 64) to create a rhythmic, orderly interface.
Motion Principles: Snappy and functional. Transitions (hover states, modal opens) should be quick (150-200ms) and use an ease-out curve. No bouncy or playful animations.
6. Conceptual Deliverables & Mockups
To visualize the brand in action, here is the creative direction for the primary brand touchpoints:
Dashboard Appearance
A persistent left-hand sidebar in Midnight Blue featuring crisp, monochrome linear icons for navigation (Members, Finance, Scheduling). The main work area is Cloud White featuring a grid of metric cards (Total Revenue, Active Members). A large, clean data table dominates the center, utilizing Inter for absolute clarity. Data visualizations (charts) utilize gradients of Electric Blue and Slate Gray.
Landing Page Hero Concept
Headline: The Command Center for Modern Organizations. (Plus Jakarta Sans, Midnight Blue)
Sub-headline: Everything you need to manage members, scale operations, and lead your club—in one intelligent platform.
Visual: A massive, high-fidelity, edge-to-edge mockup of the dashboard, angled slightly to show depth, glowing softly against a clean, off-white background. A single, bold Electric Blue primary CTA button reads: "Request Enterprise Demo".
Mobile App Concept
The app prioritizes on-the-go actions. The bottom navigation bar features cleanly stroked icons. The home screen offers a "Quick Action" FAB (Floating Action Button) for taking attendance or scanning member QR codes. The interface relies entirely on typography and white space for hierarchy, avoiding heavy colored headers.
Brand Rules: Do's and Don'ts
DO: Ensure the logo has ample breathing room.
DO: Use the solid white logo on Midnight Blue or photography with a dark overlay.
DON'T: Add drop shadows or gradients to the primary logo mark.
DON'T: Use generic clip-art icons (whistles, soccer balls, clipboards) in the UI or marketing materials.
DON'T: Mix the semantic colors (e.g., don't use the Error Red for a marketing highlight).
\ No newline at end of file
# El Captain Sports Management
## What This Is
A modular ERP specialized for sports organizations. Activity-agnostic platform — any sport/activity is a configuration of the same underlying business model.
## Stack
- **Framework:** Laravel 13 (PHP 8.5)
- **Database:** PostgreSQL 16 at `18.192.166.221:5434` (db: `elcaptainsportsonly`, user: `elcaptain`)
- **Frontend:** Livewire 3 + Alpine.js + Tailwind CSS (to be added)
- **Multi-tenancy:** Single database with `academy_id` column + global scope
- **Deploy:** CapRover at `*.caprover.al-arcade.com`
## Architecture
### Domain-Driven Layout
```
app/Domain/{Module}/Models/ — Eloquent models
app/Domain/{Module}/Services/ — Business logic (DB::transaction wrapped)
app/Domain/{Module}/Events/ — Domain events (dispatched after commit)
app/Domain/{Module}/Enums/ — PHP 8.1+ backed enums
app/Domain/Shared/Traits/ — BelongsToAcademy, HasUuid
```
### Key Patterns
- **BelongsToAcademy trait** — auto-scopes queries to `app('current_academy')`
- **HasUuid trait** — auto-generates UUID, uses `uuid` as route key
- **Amounts stored as integers** (piasters, not pounds) to avoid float issues
- **Double-entry transactions** — every financial operation creates debit + credit entries
- **Events for side effects** — never send email/notification inline from services
### Modules (in build order)
1. Financial (DONE - schema + models + services)
2. People (next)
3. Training Programs + Groups
4. Facility & Scheduling
5. Attendance
6. Inventory
7. Pricing Engine
## Commands
```bash
php artisan serve # Dev server at :8000
php artisan migrate # Run migrations
php artisan db:seed # Seed default data
php artisan tinker # REPL
```
## Login Credentials (dev)
- Email: `admin@elcaptain.com`
- Password: `password`
## Rules
- Laravel Discipline is ALWAYS active (see global CLAUDE.md)
- Migration first — schema is source of truth
- One vertical slice at a time
- Arabic locale default (`ar`), bilingual (name + name_ar)
- CHECK constraints on all status/type columns
- No `href="#"` — real routes or don't render the link
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
In addition, [Laracasts](https://laracasts.com) contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
You can also watch bite-sized lessons with real-world projects on [Laravel Learn](https://laravel.com/learn), where you will be guided through building a Laravel application from scratch while learning PHP fundamentals.
## Agentic Development
Laravel's predictable structure and conventions make it ideal for AI coding agents like Claude Code, Cursor, and GitHub Copilot. Install [Laravel Boost](https://laravel.com/docs/ai) to supercharge your AI workflow:
```bash
composer require laravel/boost --dev
php artisan boost:install
```
Boost provides your agent 15+ tools and skills that help agents build Laravel applications while following best practices.
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
<?php
namespace App\Domain\Financial\Enums;
enum AccountType: string
{
case Asset = 'asset';
case Liability = 'liability';
case Equity = 'equity';
case Revenue = 'revenue';
case Expense = 'expense';
}
<?php
namespace App\Domain\Financial\Enums;
enum InvoiceStatus: string
{
case Draft = 'draft';
case Pending = 'pending';
case AwaitingApproval = 'awaiting_approval';
case Sent = 'sent';
case Paid = 'paid';
case PartiallyPaid = 'partially_paid';
case Overpaid = 'overpaid';
case Overdue = 'overdue';
case Cancelled = 'cancelled';
case Refunded = 'refunded';
case PartiallyRefunded = 'partially_refunded';
case WrittenOff = 'written_off';
case Disputed = 'disputed';
public function label(): string
{
return match ($this) {
self::Draft => 'مسودة',
self::Pending => 'معلق',
self::AwaitingApproval => 'في انتظار الموافقة',
self::Sent => 'مرسلة',
self::Paid => 'مدفوعة',
self::PartiallyPaid => 'مدفوعة جزئياً',
self::Overpaid => 'مدفوعة بالزيادة',
self::Overdue => 'متأخرة',
self::Cancelled => 'ملغاة',
self::Refunded => 'مستردة',
self::PartiallyRefunded => 'مستردة جزئياً',
self::WrittenOff => 'شُطبت',
self::Disputed => 'متنازع عليها',
};
}
}
<?php
namespace App\Domain\Financial\Enums;
enum PaymentMethod: string
{
case Cash = 'cash';
case Card = 'card';
case BankTransfer = 'bank_transfer';
case Wallet = 'wallet';
case Online = 'online';
case Cheque = 'cheque';
case Other = 'other';
public function label(): string
{
return match ($this) {
self::Cash => 'نقدي',
self::Card => 'بطاقة',
self::BankTransfer => 'تحويل بنكي',
self::Wallet => 'محفظة',
self::Online => 'إلكتروني',
self::Cheque => 'شيك',
self::Other => 'أخرى',
};
}
}
<?php
namespace App\Domain\Financial\Enums;
enum PaymentStatus: string
{
case Pending = 'pending';
case Confirmed = 'confirmed';
case Failed = 'failed';
case Cancelled = 'cancelled';
case Refunded = 'refunded';
public function label(): string
{
return match ($this) {
self::Pending => 'معلق',
self::Confirmed => 'مؤكد',
self::Failed => 'فشل',
self::Cancelled => 'ملغى',
self::Refunded => 'مسترد',
};
}
}
<?php
namespace App\Domain\Financial\Enums;
enum TransactionType: string
{
case PaymentReceived = 'payment_received';
case PaymentMade = 'payment_made';
case Refund = 'refund';
case Transfer = 'transfer';
case Adjustment = 'adjustment';
case Fee = 'fee';
case Discount = 'discount';
case WriteOff = 'write_off';
case OpeningBalance = 'opening_balance';
}
<?php
namespace App\Domain\Financial\Events;
use App\Domain\Financial\Models\Invoice;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class InvoiceCreated
{
use Dispatchable, SerializesModels;
public function __construct(public Invoice $invoice) {}
}
<?php
namespace App\Domain\Financial\Events;
use App\Domain\Financial\Models\Invoice;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class InvoicePaid
{
use Dispatchable, SerializesModels;
public function __construct(public Invoice $invoice) {}
}
<?php
namespace App\Domain\Financial\Events;
use App\Domain\Financial\Models\Payment;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PaymentReceived
{
use Dispatchable, SerializesModels;
public function __construct(public Payment $payment) {}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Financial\Enums\AccountType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class FinancialAccount extends Model
{
use HasUuid, BelongsToAcademy;
protected $fillable = [
'academy_id',
'parent_id',
'code',
'name',
'name_ar',
'type',
'category',
'is_system',
'is_active',
'description',
];
protected function casts(): array
{
return [
'type' => AccountType::class,
'is_system' => 'boolean',
'is_active' => 'boolean',
];
}
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(self::class, 'parent_id');
}
public function debitTransactions(): HasMany
{
return $this->hasMany(Transaction::class, 'debit_account_id');
}
public function creditTransactions(): HasMany
{
return $this->hasMany(Transaction::class, 'credit_account_id');
}
}
<?php
namespace App\Domain\Financial\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Installment extends Model
{
protected $fillable = [
'payment_plan_id',
'payment_id',
'sequence',
'amount',
'due_date',
'status',
'paid_at',
];
protected function casts(): array
{
return [
'sequence' => 'integer',
'amount' => 'integer',
'due_date' => 'date',
'paid_at' => 'datetime',
];
}
public function paymentPlan(): BelongsTo
{
return $this->belongsTo(PaymentPlan::class);
}
public function payment(): BelongsTo
{
return $this->belongsTo(Payment::class);
}
public function isOverdue(): bool
{
return $this->status === 'pending' && $this->due_date->isPast();
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends Model
{
use HasUuid, BelongsToAcademy, SoftDeletes;
protected $fillable = [
'academy_id',
'number',
'type',
'status',
'billable_type',
'billable_id',
'contact_name',
'contact_phone',
'contact_email',
'subtotal_amount',
'discount_amount',
'tax_amount',
'total_amount',
'paid_amount',
'due_amount',
'currency',
'issue_date',
'due_date',
'paid_at',
'cancelled_at',
'notes',
'metadata',
'created_by',
'approved_by',
];
protected function casts(): array
{
return [
'status' => InvoiceStatus::class,
'subtotal_amount' => 'integer',
'discount_amount' => 'integer',
'tax_amount' => 'integer',
'total_amount' => 'integer',
'paid_amount' => 'integer',
'due_amount' => 'integer',
'issue_date' => 'date',
'due_date' => 'date',
'paid_at' => 'datetime',
'cancelled_at' => 'datetime',
'metadata' => 'array',
];
}
public function billable(): MorphTo
{
return $this->morphTo();
}
public function items(): HasMany
{
return $this->hasMany(InvoiceItem::class);
}
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
public function paymentPlan(): HasOne
{
return $this->hasOne(PaymentPlan::class);
}
public function transactions(): HasMany
{
return $this->hasMany(Transaction::class);
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function approver(): BelongsTo
{
return $this->belongsTo(User::class, 'approved_by');
}
public function recalculateTotals(): void
{
$this->subtotal_amount = $this->items()->sum('total_amount');
$this->total_amount = $this->subtotal_amount - $this->discount_amount + $this->tax_amount;
$this->due_amount = $this->total_amount - $this->paid_amount;
$this->save();
}
}
<?php
namespace App\Domain\Financial\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class InvoiceItem extends Model
{
protected $fillable = [
'invoice_id',
'itemable_type',
'itemable_id',
'description',
'quantity',
'unit_price',
'discount_amount',
'tax_amount',
'total_amount',
'metadata',
];
protected function casts(): array
{
return [
'quantity' => 'integer',
'unit_price' => 'integer',
'discount_amount' => 'integer',
'tax_amount' => 'integer',
'total_amount' => 'integer',
'metadata' => 'array',
];
}
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function itemable(): MorphTo
{
return $this->morphTo();
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Financial\Enums\PaymentMethod;
use App\Domain\Financial\Enums\PaymentStatus;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class Payment extends Model
{
use HasUuid, BelongsToAcademy, SoftDeletes;
protected $fillable = [
'academy_id',
'invoice_id',
'reference',
'direction',
'method',
'status',
'payer_type',
'payer_id',
'amount',
'currency',
'payment_date',
'confirmed_at',
'failed_at',
'notes',
'gateway_data',
'metadata',
'received_by',
'created_by',
];
protected function casts(): array
{
return [
'method' => PaymentMethod::class,
'status' => PaymentStatus::class,
'amount' => 'integer',
'payment_date' => 'date',
'confirmed_at' => 'datetime',
'failed_at' => 'datetime',
'gateway_data' => 'array',
'metadata' => 'array',
];
}
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function payer(): MorphTo
{
return $this->morphTo();
}
public function transactions(): HasMany
{
return $this->hasMany(Transaction::class);
}
public function receiver(): BelongsTo
{
return $this->belongsTo(User::class, 'received_by');
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function isInbound(): bool
{
return $this->direction === 'inbound';
}
public function isConfirmed(): bool
{
return $this->status === PaymentStatus::Confirmed;
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class PaymentPlan extends Model
{
use HasUuid, BelongsToAcademy;
protected $fillable = [
'academy_id',
'invoice_id',
'status',
'total_installments',
'paid_installments',
'installment_amount',
'frequency',
'start_date',
'next_due_date',
'notes',
];
protected function casts(): array
{
return [
'total_installments' => 'integer',
'paid_installments' => 'integer',
'installment_amount' => 'integer',
'start_date' => 'date',
'next_due_date' => 'date',
];
}
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function installments(): HasMany
{
return $this->hasMany(Installment::class);
}
public function isComplete(): bool
{
return $this->paid_installments >= $this->total_installments;
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Financial\Enums\TransactionType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Transaction extends Model
{
use HasUuid, BelongsToAcademy;
protected $fillable = [
'academy_id',
'debit_account_id',
'credit_account_id',
'payment_id',
'invoice_id',
'reference_type',
'reference_id',
'amount',
'currency',
'type',
'description',
'transaction_date',
'metadata',
'created_by',
];
protected function casts(): array
{
return [
'type' => TransactionType::class,
'amount' => 'integer',
'transaction_date' => 'date',
'metadata' => 'array',
];
}
public function debitAccount(): BelongsTo
{
return $this->belongsTo(FinancialAccount::class, 'debit_account_id');
}
public function creditAccount(): BelongsTo
{
return $this->belongsTo(FinancialAccount::class, 'credit_account_id');
}
public function payment(): BelongsTo
{
return $this->belongsTo(Payment::class);
}
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function reference(): MorphTo
{
return $this->morphTo();
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Wallet extends Model
{
use HasUuid, BelongsToAcademy;
protected $fillable = [
'academy_id',
'owner_type',
'owner_id',
'balance',
'currency',
'is_active',
];
protected function casts(): array
{
return [
'balance' => 'integer',
'is_active' => 'boolean',
];
}
public function owner(): MorphTo
{
return $this->morphTo();
}
public function walletTransactions(): HasMany
{
return $this->hasMany(WalletTransaction::class);
}
public function formattedBalance(): string
{
return number_format($this->balance / 100, 2) . ' ' . $this->currency;
}
}
<?php
namespace App\Domain\Financial\Models;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class WalletTransaction extends Model
{
use HasUuid;
protected $fillable = [
'wallet_id',
'type',
'direction',
'amount',
'balance_before',
'balance_after',
'reference_type',
'reference_id',
'description',
'metadata',
'created_by',
];
protected function casts(): array
{
return [
'amount' => 'integer',
'balance_before' => 'integer',
'balance_after' => 'integer',
'metadata' => 'array',
];
}
public function wallet(): BelongsTo
{
return $this->belongsTo(Wallet::class);
}
public function reference(): MorphTo
{
return $this->morphTo();
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
}
<?php
namespace App\Domain\Financial\Services;
use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Financial\Events\InvoiceCreated;
use App\Domain\Financial\Events\InvoicePaid;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\InvoiceItem;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class InvoiceService
{
public function create(array $data, array $items, User $creator): Invoice
{
return DB::transaction(function () use ($data, $items, $creator) {
$invoice = Invoice::create([
...$data,
'status' => InvoiceStatus::Draft,
'created_by' => $creator->id,
'due_amount' => $data['total_amount'] ?? 0,
]);
foreach ($items as $item) {
$item['total_amount'] = ($item['quantity'] * $item['unit_price'])
- ($item['discount_amount'] ?? 0)
+ ($item['tax_amount'] ?? 0);
$invoice->items()->create($item);
}
$invoice->recalculateTotals();
InvoiceCreated::dispatch($invoice);
return $invoice->fresh(['items']);
});
}
public function addItem(Invoice $invoice, array $itemData): InvoiceItem
{
return DB::transaction(function () use ($invoice, $itemData) {
$itemData['total_amount'] = ($itemData['quantity'] * $itemData['unit_price'])
- ($itemData['discount_amount'] ?? 0)
+ ($itemData['tax_amount'] ?? 0);
$item = $invoice->items()->create($itemData);
$invoice->recalculateTotals();
return $item;
});
}
public function cancel(Invoice $invoice, User $user): Invoice
{
return DB::transaction(function () use ($invoice, $user) {
$invoice->update([
'status' => InvoiceStatus::Cancelled,
'cancelled_at' => now(),
]);
return $invoice;
});
}
public function markAsPaid(Invoice $invoice): void
{
$invoice->update([
'status' => InvoiceStatus::Paid,
'paid_at' => now(),
'due_amount' => 0,
]);
InvoicePaid::dispatch($invoice);
}
public function updatePaidAmount(Invoice $invoice, int $amount): void
{
$invoice->paid_amount += $amount;
$invoice->due_amount = $invoice->total_amount - $invoice->paid_amount;
if ($invoice->due_amount <= 0) {
$invoice->status = $invoice->due_amount < 0
? InvoiceStatus::Overpaid
: InvoiceStatus::Paid;
$invoice->paid_at = now();
} else {
$invoice->status = InvoiceStatus::PartiallyPaid;
}
$invoice->save();
if ($invoice->status === InvoiceStatus::Paid) {
InvoicePaid::dispatch($invoice);
}
}
public function generateNumber(int $academyId): string
{
$count = Invoice::withoutGlobalScopes()
->where('academy_id', $academyId)
->count();
return 'INV-' . str_pad($count + 1, 6, '0', STR_PAD_LEFT);
}
}
<?php
namespace App\Domain\Financial\Services;
use App\Domain\Financial\Enums\PaymentStatus;
use App\Domain\Financial\Enums\TransactionType;
use App\Domain\Financial\Events\PaymentReceived;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\Payment;
use App\Domain\Financial\Models\Transaction;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class PaymentService
{
public function __construct(
private InvoiceService $invoiceService,
) {}
public function recordPayment(array $data, User $creator): Payment
{
return DB::transaction(function () use ($data, $creator) {
$payment = Payment::create([
...$data,
'status' => PaymentStatus::Confirmed,
'confirmed_at' => now(),
'created_by' => $creator->id,
]);
if ($payment->invoice_id) {
$this->invoiceService->updatePaidAmount(
$payment->invoice,
$payment->amount
);
}
$this->createTransaction($payment);
PaymentReceived::dispatch($payment);
return $payment;
});
}
public function refund(Payment $payment, int $amount, User $creator): Payment
{
return DB::transaction(function () use ($payment, $amount, $creator) {
$refund = Payment::create([
'academy_id' => $payment->academy_id,
'invoice_id' => $payment->invoice_id,
'reference' => 'REF-' . $payment->reference,
'direction' => 'outbound',
'method' => $payment->method,
'status' => PaymentStatus::Confirmed,
'payer_type' => $payment->payer_type,
'payer_id' => $payment->payer_id,
'amount' => $amount,
'currency' => $payment->currency,
'payment_date' => now()->toDateString(),
'confirmed_at' => now(),
'notes' => "Refund for payment #{$payment->reference}",
'created_by' => $creator->id,
]);
if ($payment->invoice_id) {
$this->invoiceService->updatePaidAmount(
$payment->invoice,
-$amount
);
}
$this->createTransaction($refund, TransactionType::Refund);
return $refund;
});
}
private function createTransaction(Payment $payment, ?TransactionType $type = null): Transaction
{
$isInbound = $payment->direction === 'inbound';
$type ??= $isInbound ? TransactionType::PaymentReceived : TransactionType::PaymentMade;
return Transaction::create([
'academy_id' => $payment->academy_id,
'debit_account_id' => $this->resolveDebitAccount($payment),
'credit_account_id' => $this->resolveCreditAccount($payment),
'payment_id' => $payment->id,
'invoice_id' => $payment->invoice_id,
'amount' => $payment->amount,
'currency' => $payment->currency,
'type' => $type,
'description' => $this->buildDescription($payment, $type),
'transaction_date' => $payment->payment_date,
'created_by' => $payment->created_by,
]);
}
private function resolveDebitAccount(Payment $payment): int
{
// TODO: resolve from chart of accounts based on payment method
return 1;
}
private function resolveCreditAccount(Payment $payment): int
{
// TODO: resolve from chart of accounts based on invoice source
return 2;
}
private function buildDescription(Payment $payment, TransactionType $type): string
{
return match ($type) {
TransactionType::PaymentReceived => "Payment received: {$payment->amount} {$payment->currency}",
TransactionType::PaymentMade => "Payment made: {$payment->amount} {$payment->currency}",
TransactionType::Refund => "Refund: {$payment->amount} {$payment->currency}",
default => "Transaction: {$payment->amount} {$payment->currency}",
};
}
}
<?php
namespace App\Domain\Financial\Services;
use App\Domain\Financial\Models\Wallet;
use App\Domain\Financial\Models\WalletTransaction;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
class WalletService
{
public function getOrCreateWallet(Model $owner, int $academyId): Wallet
{
return Wallet::firstOrCreate([
'academy_id' => $academyId,
'owner_type' => $owner->getMorphClass(),
'owner_id' => $owner->getKey(),
], [
'balance' => 0,
'currency' => 'EGP',
'is_active' => true,
]);
}
public function deposit(Wallet $wallet, int $amount, string $description, ?Model $reference = null, ?User $creator = null): WalletTransaction
{
if ($amount <= 0) {
throw new InvalidArgumentException('Deposit amount must be positive');
}
return DB::transaction(function () use ($wallet, $amount, $description, $reference, $creator) {
$wallet->lockForUpdate();
$balanceBefore = $wallet->balance;
$wallet->increment('balance', $amount);
return WalletTransaction::create([
'wallet_id' => $wallet->id,
'type' => 'deposit',
'direction' => 'credit',
'amount' => $amount,
'balance_before' => $balanceBefore,
'balance_after' => $balanceBefore + $amount,
'reference_type' => $reference?->getMorphClass(),
'reference_id' => $reference?->getKey(),
'description' => $description,
'created_by' => $creator?->id,
]);
});
}
public function withdraw(Wallet $wallet, int $amount, string $description, ?Model $reference = null, ?User $creator = null): WalletTransaction
{
if ($amount <= 0) {
throw new InvalidArgumentException('Withdrawal amount must be positive');
}
return DB::transaction(function () use ($wallet, $amount, $description, $reference, $creator) {
$wallet->lockForUpdate();
if ($wallet->balance < $amount) {
throw new InvalidArgumentException('Insufficient wallet balance');
}
$balanceBefore = $wallet->balance;
$wallet->decrement('balance', $amount);
return WalletTransaction::create([
'wallet_id' => $wallet->id,
'type' => 'withdrawal',
'direction' => 'debit',
'amount' => $amount,
'balance_before' => $balanceBefore,
'balance_after' => $balanceBefore - $amount,
'reference_type' => $reference?->getMorphClass(),
'reference_id' => $reference?->getKey(),
'description' => $description,
'created_by' => $creator?->id,
]);
});
}
}
<?php
namespace App\Domain\Shared\Models;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Academy extends Model
{
use HasUuid, SoftDeletes;
protected $fillable = [
'name',
'name_ar',
'slug',
'email',
'phone',
'logo_path',
'currency',
'timezone',
'locale',
'settings',
'status',
];
protected $casts = [
'settings' => 'array',
];
}
<?php
namespace App\Domain\Shared\Traits;
use App\Domain\Shared\Models\Academy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
trait BelongsToAcademy
{
public static function bootBelongsToAcademy(): void
{
static::creating(function ($model) {
if (! $model->academy_id && app()->has('current_academy')) {
$model->academy_id = app('current_academy')->id;
}
});
static::addGlobalScope('academy', function (Builder $builder) {
if (app()->has('current_academy')) {
$builder->where(
$builder->getModel()->getTable() . '.academy_id',
app('current_academy')->id
);
}
});
}
public function academy(): BelongsTo
{
return $this->belongsTo(Academy::class);
}
}
<?php
namespace App\Domain\Shared\Traits;
use Illuminate\Support\Str;
trait HasUuid
{
public static function bootHasUuid(): void
{
static::creating(function ($model) {
if (empty($model->uuid)) {
$model->uuid = (string) Str::uuid();
}
});
}
public function getRouteKeyName(): string
{
return 'uuid';
}
}
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SetCurrentAcademy
{
public function handle(Request $request, Closure $next): Response
{
if ($user = $request->user()) {
$academy = $user->academy;
app()->instance('current_academy', $academy);
}
return $next($request);
}
}
<?php
namespace App\Models;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasUuid, BelongsToAcademy, SoftDeletes;
protected $fillable = [
'academy_id',
'name',
'name_ar',
'email',
'phone',
'national_id',
'date_of_birth',
'gender',
'password',
'avatar_path',
'status',
];
protected $hidden = [
'password',
'remember_token',
];
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'date_of_birth' => 'date',
'password' => 'hashed',
];
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [
\App\Http\Middleware\SetCurrentAcademy::class,
]);
$middleware->api(append: [
\App\Http\Middleware\SetCurrentAcademy::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
fn (Request $request) => $request->is('api/*'),
);
})->create();
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.3",
"laravel/framework": "^13.8",
"laravel/tinker": "^3.0"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.5",
"laravel/pao": "^1.0.6",
"laravel/pint": "^1.27",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^12.5.12"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install --ignore-scripts",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi @no_additional_args",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}
This diff is collapsed.
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "storage", "octane",
| "session", "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'storage' => [
'driver' => 'storage',
'disk' => env('CACHE_STORAGE_DISK'),
'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
/*
|--------------------------------------------------------------------------
| Serializable Classes
|--------------------------------------------------------------------------
|
| This value determines the classes that can be unserialized from cache
| storage. By default, no PHP classes will be unserialized from your
| cache to prevent gadget chain attacks if your APP_KEY is leaked.
|
*/
'serializable_classes' => false,
];
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
/*
|--------------------------------------------------------------------------
| Session Serialization
|--------------------------------------------------------------------------
|
| This value controls the serialization strategy for session data, which
| is JSON by default. Setting this to "php" allows the storage of PHP
| objects in the session but can make an application vulnerable to
| "gadget chain" serialization attacks if the APP_KEY is leaked.
|
| Supported: "json", "php"
|
*/
'serialization' => 'json',
];
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('academies', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('name');
$table->string('name_ar')->nullable();
$table->string('slug')->unique();
$table->string('email')->nullable();
$table->string('phone')->nullable();
$table->string('logo_path')->nullable();
$table->string('currency', 3)->default('EGP');
$table->string('timezone')->default('Africa/Cairo');
$table->string('locale', 5)->default('ar');
$table->jsonb('settings')->default('{}');
$table->string('status', 20)->default('active');
$table->timestamps();
$table->softDeletes();
$table->index('status');
});
DB::statement("ALTER TABLE academies ADD CONSTRAINT academies_status_check CHECK (status IN ('active', 'suspended', 'trial', 'cancelled'))");
}
public function down(): void
{
Schema::dropIfExists('academies');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('name_ar')->nullable();
$table->string('email')->unique();
$table->string('phone', 20)->nullable();
$table->string('national_id', 14)->nullable();
$table->date('date_of_birth')->nullable();
$table->string('gender', 10)->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('avatar_path')->nullable();
$table->string('status', 20)->default('active');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
$table->index('academy_id');
$table->index('status');
$table->index('national_id');
});
DB::statement("ALTER TABLE users ADD CONSTRAINT users_status_check CHECK (status IN ('active', 'inactive', 'suspended', 'pending'))");
DB::statement("ALTER TABLE users ADD CONSTRAINT users_gender_check CHECK (gender IN ('male', 'female'))");
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
public function down(): void
{
Schema::dropIfExists('sessions');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('users');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration');
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration');
});
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('failed_jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('jobs');
Schema::dropIfExists('cache_locks');
Schema::dropIfExists('cache');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('financial_accounts', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->foreignId('parent_id')->nullable()->constrained('financial_accounts')->nullOnDelete();
$table->string('code', 20);
$table->string('name');
$table->string('name_ar')->nullable();
$table->string('type', 20);
$table->string('category', 30)->nullable();
$table->boolean('is_system')->default(false);
$table->boolean('is_active')->default(true);
$table->text('description')->nullable();
$table->timestamps();
$table->unique(['academy_id', 'code']);
$table->index(['academy_id', 'type']);
$table->index('parent_id');
});
DB::statement("ALTER TABLE financial_accounts ADD CONSTRAINT financial_accounts_type_check CHECK (type IN ('asset', 'liability', 'equity', 'revenue', 'expense'))");
}
public function down(): void
{
Schema::dropIfExists('financial_accounts');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('invoices', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->string('number', 30);
$table->string('type', 20)->default('standard');
$table->string('status', 20)->default('draft');
$table->nullableMorphs('billable');
$table->string('contact_name')->nullable();
$table->string('contact_phone', 20)->nullable();
$table->string('contact_email')->nullable();
$table->bigInteger('subtotal_amount')->default(0);
$table->bigInteger('discount_amount')->default(0);
$table->bigInteger('tax_amount')->default(0);
$table->bigInteger('total_amount')->default(0);
$table->bigInteger('paid_amount')->default(0);
$table->bigInteger('due_amount')->default(0);
$table->string('currency', 3)->default('EGP');
$table->date('issue_date');
$table->date('due_date')->nullable();
$table->timestamp('paid_at')->nullable();
$table->timestamp('cancelled_at')->nullable();
$table->text('notes')->nullable();
$table->jsonb('metadata')->default('{}');
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->softDeletes();
$table->unique(['academy_id', 'number']);
$table->index(['academy_id', 'status']);
$table->index(['academy_id', 'due_date']);
});
DB::statement("ALTER TABLE invoices ADD CONSTRAINT invoices_status_check CHECK (status IN ('draft', 'pending', 'awaiting_approval', 'sent', 'paid', 'partially_paid', 'overpaid', 'overdue', 'cancelled', 'refunded', 'partially_refunded', 'written_off', 'disputed'))");
DB::statement("ALTER TABLE invoices ADD CONSTRAINT invoices_type_check CHECK (type IN ('standard', 'recurring', 'credit_note', 'proforma'))");
Schema::create('invoice_items', function (Blueprint $table) {
$table->id();
$table->foreignId('invoice_id')->constrained()->cascadeOnDelete();
$table->nullableMorphs('itemable');
$table->string('description');
$table->integer('quantity')->default(1);
$table->bigInteger('unit_price')->default(0);
$table->bigInteger('discount_amount')->default(0);
$table->bigInteger('tax_amount')->default(0);
$table->bigInteger('total_amount')->default(0);
$table->jsonb('metadata')->default('{}');
$table->timestamps();
$table->index('invoice_id');
});
}
public function down(): void
{
Schema::dropIfExists('invoice_items');
Schema::dropIfExists('invoices');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->foreignId('invoice_id')->nullable()->constrained()->nullOnDelete();
$table->string('reference', 50)->nullable();
$table->string('direction', 10);
$table->string('method', 20);
$table->string('status', 20)->default('pending');
$table->nullableMorphs('payer');
$table->bigInteger('amount')->default(0);
$table->string('currency', 3)->default('EGP');
$table->date('payment_date');
$table->timestamp('confirmed_at')->nullable();
$table->timestamp('failed_at')->nullable();
$table->text('notes')->nullable();
$table->jsonb('gateway_data')->default('{}');
$table->jsonb('metadata')->default('{}');
$table->foreignId('received_by')->nullable()->constrained('users')->nullOnDelete();
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->softDeletes();
$table->index(['academy_id', 'status']);
$table->index(['academy_id', 'direction']);
$table->index(['academy_id', 'payment_date']);
$table->index('invoice_id');
});
DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_direction_check CHECK (direction IN ('inbound', 'outbound'))");
DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_method_check CHECK (method IN ('cash', 'card', 'bank_transfer', 'wallet', 'online', 'cheque', 'other'))");
DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_status_check CHECK (status IN ('pending', 'confirmed', 'failed', 'cancelled', 'refunded'))");
}
public function down(): void
{
Schema::dropIfExists('payments');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('transactions', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->foreignId('debit_account_id')->constrained('financial_accounts');
$table->foreignId('credit_account_id')->constrained('financial_accounts');
$table->foreignId('payment_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('invoice_id')->nullable()->constrained()->nullOnDelete();
$table->nullableMorphs('reference');
$table->bigInteger('amount');
$table->string('currency', 3)->default('EGP');
$table->string('type', 30);
$table->text('description')->nullable();
$table->date('transaction_date');
$table->jsonb('metadata')->default('{}');
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->index(['academy_id', 'transaction_date']);
$table->index(['academy_id', 'type']);
$table->index('debit_account_id');
$table->index('credit_account_id');
});
DB::statement("ALTER TABLE transactions ADD CONSTRAINT transactions_type_check CHECK (type IN ('payment_received', 'payment_made', 'refund', 'transfer', 'adjustment', 'fee', 'discount', 'write_off', 'opening_balance'))");
}
public function down(): void
{
Schema::dropIfExists('transactions');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('wallets', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->morphs('owner');
$table->bigInteger('balance')->default(0);
$table->string('currency', 3)->default('EGP');
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->unique(['academy_id', 'owner_type', 'owner_id']);
});
Schema::create('wallet_transactions', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('wallet_id')->constrained()->cascadeOnDelete();
$table->string('type', 20);
$table->string('direction', 10);
$table->bigInteger('amount');
$table->bigInteger('balance_before');
$table->bigInteger('balance_after');
$table->nullableMorphs('reference');
$table->text('description')->nullable();
$table->jsonb('metadata')->default('{}');
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->index(['wallet_id', 'created_at']);
});
DB::statement("ALTER TABLE wallet_transactions ADD CONSTRAINT wallet_transactions_type_check CHECK (type IN ('deposit', 'withdrawal', 'payment', 'refund', 'adjustment', 'transfer'))");
DB::statement("ALTER TABLE wallet_transactions ADD CONSTRAINT wallet_transactions_direction_check CHECK (direction IN ('credit', 'debit'))");
}
public function down(): void
{
Schema::dropIfExists('wallet_transactions');
Schema::dropIfExists('wallets');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('payment_plans', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('academy_id')->constrained()->cascadeOnDelete();
$table->foreignId('invoice_id')->constrained()->cascadeOnDelete();
$table->string('status', 20)->default('active');
$table->integer('total_installments');
$table->integer('paid_installments')->default(0);
$table->bigInteger('installment_amount');
$table->string('frequency', 20)->default('monthly');
$table->date('start_date');
$table->date('next_due_date')->nullable();
$table->text('notes')->nullable();
$table->timestamps();
$table->index(['academy_id', 'status']);
$table->index('next_due_date');
});
DB::statement("ALTER TABLE payment_plans ADD CONSTRAINT payment_plans_status_check CHECK (status IN ('active', 'completed', 'defaulted', 'cancelled'))");
DB::statement("ALTER TABLE payment_plans ADD CONSTRAINT payment_plans_frequency_check CHECK (frequency IN ('weekly', 'biweekly', 'monthly', 'quarterly'))");
Schema::create('installments', function (Blueprint $table) {
$table->id();
$table->foreignId('payment_plan_id')->constrained()->cascadeOnDelete();
$table->foreignId('payment_id')->nullable()->constrained()->nullOnDelete();
$table->integer('sequence');
$table->bigInteger('amount');
$table->date('due_date');
$table->string('status', 20)->default('pending');
$table->timestamp('paid_at')->nullable();
$table->timestamps();
$table->index(['payment_plan_id', 'sequence']);
$table->index('due_date');
});
DB::statement("ALTER TABLE installments ADD CONSTRAINT installments_status_check CHECK (status IN ('pending', 'paid', 'overdue', 'cancelled', 'waived'))");
}
public function down(): void
{
Schema::dropIfExists('installments');
Schema::dropIfExists('payment_plans');
}
};
<?php
namespace Database\Seeders;
use App\Domain\Shared\Models\Academy;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
$academy = Academy::firstOrCreate(
['slug' => 'el-captain'],
[
'name' => 'El Captain Academy',
'name_ar' => 'أكاديمية الكابتن',
'slug' => 'el-captain',
'email' => 'info@elcaptain.com',
'currency' => 'EGP',
'timezone' => 'Africa/Cairo',
'locale' => 'ar',
'status' => 'active',
]
);
User::firstOrCreate(
['email' => 'admin@elcaptain.com'],
[
'academy_id' => $academy->id,
'name' => 'Mahmoud Aglan',
'name_ar' => 'محمود عجلان',
'email' => 'admin@elcaptain.com',
'password' => Hash::make('password'),
'status' => 'active',
]
);
$this->call(FinancialAccountsSeeder::class);
}
}
<?php
namespace Database\Seeders;
use App\Domain\Financial\Models\FinancialAccount;
use App\Domain\Shared\Models\Academy;
use Illuminate\Database\Seeder;
class FinancialAccountsSeeder extends Seeder
{
public function run(): void
{
$academy = Academy::first();
if (! $academy) {
$academy = Academy::create([
'name' => 'El Captain Academy',
'name_ar' => 'أكاديمية الكابتن',
'slug' => 'el-captain',
'email' => 'info@elcaptain.com',
'currency' => 'EGP',
'timezone' => 'Africa/Cairo',
'locale' => 'ar',
'status' => 'active',
]);
}
$accounts = [
// Assets
['code' => '1000', 'name' => 'Cash', 'name_ar' => 'النقدية', 'type' => 'asset', 'category' => 'current_asset', 'is_system' => true],
['code' => '1010', 'name' => 'Bank Account', 'name_ar' => 'الحساب البنكي', 'type' => 'asset', 'category' => 'current_asset', 'is_system' => true],
['code' => '1100', 'name' => 'Accounts Receivable', 'name_ar' => 'المدينون', 'type' => 'asset', 'category' => 'current_asset', 'is_system' => true],
['code' => '1200', 'name' => 'Wallets Receivable', 'name_ar' => 'أرصدة المحافظ', 'type' => 'asset', 'category' => 'current_asset', 'is_system' => true],
// Revenue
['code' => '4000', 'name' => 'Training Revenue', 'name_ar' => 'إيرادات التدريب', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
['code' => '4010', 'name' => 'Registration Fees', 'name_ar' => 'رسوم التسجيل', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
['code' => '4020', 'name' => 'Equipment Sales', 'name_ar' => 'مبيعات المعدات', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
['code' => '4030', 'name' => 'Facility Rental', 'name_ar' => 'إيجار الملاعب', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
['code' => '4040', 'name' => 'Private Sessions', 'name_ar' => 'الحصص الخاصة', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
['code' => '4050', 'name' => 'Tournament Fees', 'name_ar' => 'رسوم البطولات', 'type' => 'revenue', 'category' => 'operating', 'is_system' => true],
// Expenses
['code' => '5000', 'name' => 'Trainer Salaries', 'name_ar' => 'رواتب المدربين', 'type' => 'expense', 'category' => 'operating', 'is_system' => true],
['code' => '5010', 'name' => 'Facility Rent', 'name_ar' => 'إيجار المنشآت', 'type' => 'expense', 'category' => 'operating', 'is_system' => true],
['code' => '5020', 'name' => 'Equipment Purchases', 'name_ar' => 'مشتريات المعدات', 'type' => 'expense', 'category' => 'operating', 'is_system' => true],
['code' => '5030', 'name' => 'Utilities', 'name_ar' => 'المرافق', 'type' => 'expense', 'category' => 'operating', 'is_system' => true],
['code' => '5040', 'name' => 'Marketing', 'name_ar' => 'التسويق', 'type' => 'expense', 'category' => 'operating', 'is_system' => true],
// Liability
['code' => '2000', 'name' => 'Accounts Payable', 'name_ar' => 'الدائنون', 'type' => 'liability', 'category' => 'current_liability', 'is_system' => true],
['code' => '2010', 'name' => 'Unearned Revenue', 'name_ar' => 'إيرادات مقدمة', 'type' => 'liability', 'category' => 'current_liability', 'is_system' => true],
['code' => '2020', 'name' => 'Refunds Payable', 'name_ar' => 'مستردات مستحقة', 'type' => 'liability', 'category' => 'current_liability', 'is_system' => true],
];
foreach ($accounts as $account) {
FinancialAccount::firstOrCreate(
['academy_id' => $academy->id, 'code' => $account['code']],
$account + ['academy_id' => $academy->id]
);
}
}
}
# El Captain Sports Only Database
## Connection Details
| Key | Value |
|-----|-------|
| **Host (public)** | `18.192.166.221` |
| **Port (public)** | `5434` |
| **Host (internal/CapRover apps)** | `srv-captain--elcaptainsportsonlydb` |
| **Port (internal)** | `5432` |
| **User** | `elcaptain` |
| **Password** | `ElCaptain2024!` |
| **Default DB** | `elcaptainsportsonly` |
| **Superuser** | `postgres` |
| **Superuser Password** | `Alarcade123#` |
| **Version** | PostgreSQL 16.14 (Alpine) |
| **Docker Service** | `srv-captain--elcaptainsportsonlydb` |
| **Storage** | Persistent volume: `captain--elcaptainsportsonlydb-data` |
---
## Connection Strings
```bash
# External apps (public internet)
postgresql://elcaptain:ElCaptain2024!@18.192.166.221:5434/elcaptainsportsonly
# CapRover apps (internal Docker network)
postgresql://elcaptain:ElCaptain2024!@srv-captain--elcaptainsportsonlydb:5432/elcaptainsportsonly
# Superuser (external)
postgresql://postgres:Alarcade123#@18.192.166.221:5434/postgres
```
---
## Quick Connect
### psql (CLI)
```bash
PGPASSWORD='ElCaptain2024!' psql -h 18.192.166.221 -p 5434 -U elcaptain -d elcaptainsportsonly
```
### Python (psycopg2)
```python
import psycopg2
conn = psycopg2.connect(
host="18.192.166.221",
port=5434,
user="elcaptain",
password="ElCaptain2024!",
dbname="elcaptainsportsonly"
)
```
### Node.js (pg)
```javascript
const { Pool } = require('pg');
const pool = new Pool({
host: '18.192.166.221',
port: 5434,
user: 'elcaptain',
password: 'ElCaptain2024!',
database: 'elcaptainsportsonly',
ssl: false
});
```
### Go
```go
dsn := "host=18.192.166.221 port=5434 user=elcaptain password=ElCaptain2024! dbname=elcaptainsportsonly sslmode=disable"
```
### C# / Unity
```csharp
string connStr = "Host=18.192.166.221;Port=5434;Username=elcaptain;Password=ElCaptain2024!;Database=elcaptainsportsonly";
```
### Laravel (.env)
```env
DB_CONNECTION=pgsql
DB_HOST=18.192.166.221
DB_PORT=5434
DB_DATABASE=elcaptainsportsonly
DB_USERNAME=elcaptain
DB_PASSWORD=ElCaptain2024!
```
### Flutter (Dart)
```dart
final connection = await Connection.open(Endpoint(
host: '18.192.166.221',
port: 5434,
database: 'elcaptainsportsonly',
username: 'elcaptain',
password: 'ElCaptain2024!',
));
```
---
## Admin Operations
### Create a New Database
```sql
CREATE DATABASE my_new_db;
```
### Create a New User (for an app)
```sql
CREATE USER myapp_user WITH PASSWORD 'secure_password_here';
GRANT ALL PRIVILEGES ON DATABASE my_new_db TO myapp_user;
```
### Create a Read-Only User
```sql
CREATE USER readonly_user WITH PASSWORD 'readonly_pass';
GRANT CONNECT ON DATABASE elcaptainsportsonly TO readonly_user;
GRANT USAGE ON SCHEMA public TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_user;
```
### List All Databases
```sql
\l
-- or
SELECT datname FROM pg_database WHERE datistemplate = false;
```
### List All Tables
```sql
\dt
-- or
SELECT tablename FROM pg_tables WHERE schemaname = 'public';
```
### Check Database Size
```sql
SELECT pg_size_pretty(pg_database_size('elcaptainsportsonly'));
```
### Check All Database Sizes
```sql
SELECT datname, pg_size_pretty(pg_database_size(datname))
FROM pg_database WHERE datistemplate = false ORDER BY pg_database_size(datname) DESC;
```
---
## Useful Extensions
```sql
-- Enable UUID generation
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Enable full-text search extras
CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- Enable crypto functions
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Check available extensions
SELECT name, comment FROM pg_available_extensions ORDER BY name;
```
---
## SSH Access (Server-Side)
```bash
# SSH to server
ssh -i /Users/mahmoudaglan/NewMigration/newServer.pem -o StrictHostKeyChecking=no ubuntu@18.192.166.221
# Connect to DB from inside container
sudo docker exec -it $(sudo docker ps -q --filter "name=srv-captain--elcaptainsportsonlydb") psql -U elcaptain -d elcaptainsportsonly
# Connect as superuser
sudo docker exec -it $(sudo docker ps -q --filter "name=srv-captain--elcaptainsportsonlydb") psql -U postgres
# View logs
sudo docker logs $(sudo docker ps -q --filter "name=srv-captain--elcaptainsportsonlydb") --tail 50
# Restart
sudo docker service update --force srv-captain--elcaptainsportsonlydb
# Backup a database
sudo docker exec $(sudo docker ps -q --filter "name=srv-captain--elcaptainsportsonlydb") pg_dump -U elcaptain elcaptainsportsonly > backup.sql
# Restore a database
cat backup.sql | sudo docker exec -i $(sudo docker ps -q --filter "name=srv-captain--elcaptainsportsonlydb") psql -U elcaptain -d elcaptainsportsonly
```
---
## Notes
- `elcaptain` user owns the `elcaptainsportsonly` database and has full privileges on it.
- `postgres` superuser can create databases, users, extensions, and manage everything.
- Port `5434` is exposed publicly — any app on the internet can connect with the credentials.
- For CapRover apps, use the internal hostname `srv-captain--elcaptainsportsonlydb` on port `5432` (faster, no SSL needed).
- Data persists across container restarts via the Docker volume `captain--elcaptainsportsonlydb-data`.
- Image pinned to `postgres:16-alpine` — do NOT use `postgres:latest` (v18+ breaks with the `/var/lib/postgresql/data` mount path).
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^3.1",
"tailwindcss": "^4.0.0",
"vite": "^8.0.0"
}
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_URL" value=""/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());
User-agent: *
Disallow:
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}
This diff is collapsed.
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
*
!private/
!public/
!.gitignore
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json
This diff is collapsed.
<?php
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { bunny } from 'laravel-vite-plugin/fonts';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
fonts: [
bunny('Instrument Sans', {
weights: [400, 500, 600],
}),
],
}),
tailwindcss(),
],
server: {
watch: {
ignored: ['**/storage/framework/views/**'],
},
},
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment