feat: initial commit - Band Management application

This commit is contained in:
2026-01-06 03:11:46 +01:00
commit 34e12e00b3
24543 changed files with 3991790 additions and 0 deletions

866
.cursor/ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,866 @@
# Band Management - Architecture
> This document describes the system architecture, design decisions, and patterns used in this application.
## System Overview
```
┌─────────────────────────────────────────────────────────────────────────┐
│ INTERNET │
└─────────────────────────────────────────────────────────────────────────┘
┌───────────────────────────┼───────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Admin SPA │ │ Band SPA │ │ Customer SPA │
│ (Vuexy Full) │ │ (Vuexy Lite) │ │ (Vuexy Lite) │
│ :5173 │ │ :5174 │ │ :5175 │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
└───────────────────────────┼───────────────────────────┘
┌───────────────────────┐
│ Laravel API │
│ (Sanctum) │
│ :8000 │
└───────────┬───────────┘
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ MySQL │ │ Redis │ │ Mailpit │
│ :3306 │ │ :6379 │ │ :8025 │
└───────────┘ └───────────┘ └───────────┘
```
---
## Applications
### Admin Dashboard (`apps/admin/`)
**Purpose**: Full management interface for band administrators.
**Users**: Band leaders, managers, booking agents
**Features**:
- Member management (CRUD, roles, invitations)
- Event/gig management (calendar, list, RSVP tracking)
- Music catalog (songs, attachments, metadata)
- Setlist builder (drag-drop, templates)
- Location management (venues, contacts)
- Customer CRM (companies, individuals, history)
- Booking request management
- Reports and analytics
**Vuexy Version**: `typescript-version/full-version`
---
### Band Portal (`apps/band/`)
**Purpose**: Member-facing interface for band members.
**Users**: Musicians, performers, crew
**Features**:
- Personal dashboard (upcoming gigs)
- Event calendar with RSVP
- View setlists and music
- Download attachments (lyrics, charts)
- Profile settings
- Notifications
**Vuexy Version**: `typescript-version/starter-kit`
---
### Customer Portal (`apps/customers/`)
**Purpose**: Client-facing interface for customers.
**Users**: Event organizers, venue managers, clients
**Features**:
- View booked events
- Submit booking requests
- Track request status
- View assigned setlists (if permitted)
- Profile settings
**Vuexy Version**: `typescript-version/starter-kit`
---
## API Structure
### Base URL
- Development: `http://localhost:8000/api/v1`
- Production: `https://api.bandmanagement.nl/api/v1`
### Authentication Endpoints
```
POST /auth/register Register new user
POST /auth/login Login, returns token
POST /auth/logout Logout, revokes token
GET /auth/user Get authenticated user
POST /auth/forgot-password Request password reset
POST /auth/reset-password Reset password with token
```
### Resource Endpoints
```
# Events
GET /events List events (paginated, filterable)
POST /events Create event
GET /events/{id} Get event details
PUT /events/{id} Update event
DELETE /events/{id} Delete event
POST /events/{id}/invite Invite members to event
GET /events/{id}/invitations Get event invitations
POST /events/{id}/rsvp Submit RSVP response
POST /events/{id}/duplicate Duplicate event
# Members
GET /members List members
POST /members Create member
GET /members/{id} Get member details
PUT /members/{id} Update member
DELETE /members/{id} Delete/deactivate member
POST /members/invite Send invitation email
# Music
GET /music List music numbers
POST /music Create music number
GET /music/{id} Get music number
PUT /music/{id} Update music number
DELETE /music/{id} Delete music number
POST /music/{id}/attachments Upload attachment
DELETE /music/{id}/attachments/{aid} Delete attachment
# Setlists
GET /setlists List setlists
POST /setlists Create setlist
GET /setlists/{id} Get setlist with items
PUT /setlists/{id} Update setlist
DELETE /setlists/{id} Delete setlist
POST /setlists/{id}/clone Clone setlist
PUT /setlists/{id}/items Reorder/update items
# Locations
GET /locations List locations
POST /locations Create location
GET /locations/{id} Get location
PUT /locations/{id} Update location
DELETE /locations/{id} Delete location
# Customers
GET /customers List customers
POST /customers Create customer
GET /customers/{id} Get customer
PUT /customers/{id} Update customer
DELETE /customers/{id} Delete customer
# Booking Requests (Customer Portal)
GET /booking-requests List user's requests
POST /booking-requests Submit booking request
GET /booking-requests/{id} Get request details
# Notifications
GET /notifications List notifications
PUT /notifications/{id}/read Mark as read
POST /notifications/read-all Mark all as read
```
---
## Database Schema
### Entity Relationship Diagram
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ users │ │ customers │ │ locations │
├──────────────┤ ├──────────────┤ ├──────────────┤
│ id (ULID) │──┐ │ id (ULID) │ │ id (ULID) │
│ name │ │ │ user_id (FK) │───────│ name │
│ email │ │ │ name │ │ address │
│ type │ │ │ company_name │ │ city │
│ role │ │ │ type │ │ capacity │
│ status │ │ │ email │ │ contact_* │
└──────────────┘ │ └──────────────┘ └──────────────┘
│ │ │ │
│ │ │ │
▼ │ ▼ ▼
┌──────────────┐ │ ┌──────────────┐ ┌──────────────┐
│event_invites │ │ │ events │───────│ setlists │
├──────────────┤ │ ├──────────────┤ ├──────────────┤
│ id (ULID) │ │ │ id (ULID) │ │ id (ULID) │
│ event_id(FK) │──┼───▶│ title │ │ name │
│ user_id (FK) │──┘ │ location_id │ │ description │
│ rsvp_status │ │ customer_id │ │ is_template │
│ rsvp_note │ │ setlist_id │◀──────│ is_archived │
└──────────────┘ │ event_date │ └──────────────┘
│ status │ │
│ created_by │ │
└──────────────┘ ▼
┌──────────────┐
┌──────────────┐ ┌──────────────┐ │setlist_items │
│music_numbers │───────│music_attach │ ├──────────────┤
├──────────────┤ ├──────────────┤ │ id (ULID) │
│ id (ULID) │ │ id (ULID) │ │ setlist_id │
│ title │ │ music_num_id │ │ music_num_id │
│ artist │ │ file_name │ │ position │
│ duration │ │ file_type │ │ set_number │
│ key, tempo │ │ file_path │ │ is_break │
│ tags (JSON) │ └──────────────┘ └──────────────┘
└──────────────┘
```
### Table Definitions
#### users
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| name | string | Full name |
| email | string | Unique email |
| email_verified_at | timestamp | Email verification |
| password | string | Hashed password |
| phone | string? | Phone number |
| bio | text? | Biography |
| instruments | json? | Array of instruments |
| avatar_path | string? | Avatar file path |
| type | enum | `member`, `customer` |
| role | enum? | `admin`, `booking_agent`, `music_manager`, `member` |
| status | enum | `active`, `inactive` |
| invited_at | timestamp? | When invited |
| last_login_at | timestamp? | Last login |
| remember_token | string? | Remember me token |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### customers
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| user_id | ULID? | FK to users (for portal access) |
| name | string | Contact name |
| company_name | string? | Company name |
| type | enum | `individual`, `company` |
| email | string? | Email |
| phone | string? | Phone |
| address | string? | Street address |
| city | string? | City |
| postal_code | string? | Postal code |
| country | string | Country (default: NL) |
| notes | text? | Internal notes |
| is_portal_enabled | boolean | Can access portal |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### locations
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| name | string | Venue name |
| address | string | Street address |
| city | string | City |
| postal_code | string? | Postal code |
| country | string | Country (default: NL) |
| latitude | decimal? | GPS latitude |
| longitude | decimal? | GPS longitude |
| capacity | integer? | Max capacity |
| contact_name | string? | Contact person |
| contact_email | string? | Contact email |
| contact_phone | string? | Contact phone |
| stage_specs | text? | Stage specifications |
| technical_notes | text? | Technical requirements |
| parking_info | text? | Parking information |
| notes | text? | General notes |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### events
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| title | string | Event title |
| description | text? | Description |
| location_id | ULID? | FK to locations |
| customer_id | ULID? | FK to customers |
| setlist_id | ULID? | FK to setlists |
| event_date | date | Date of event |
| start_time | time | Start time |
| end_time | time? | End time |
| load_in_time | time? | Load-in time |
| soundcheck_time | time? | Soundcheck time |
| fee | decimal(10,2)? | Payment amount |
| currency | string | Currency (default: EUR) |
| status | enum | `draft`, `pending`, `confirmed`, `completed`, `cancelled` |
| visibility | enum | `private`, `members`, `public` |
| rsvp_deadline | datetime? | RSVP deadline |
| notes | text? | Public notes |
| internal_notes | text? | Admin-only notes |
| is_public_setlist | boolean | Show setlist to customer |
| created_by | ULID | FK to users |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### event_invitations
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| event_id | ULID | FK to events |
| user_id | ULID | FK to users |
| rsvp_status | enum | `pending`, `available`, `unavailable`, `tentative` |
| rsvp_note | text? | Response note |
| rsvp_responded_at | timestamp? | When responded |
| invited_at | timestamp | When invited |
| reminder_sent_at | timestamp? | Last reminder |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### music_numbers
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| title | string | Song title |
| artist | string? | Original artist |
| genre | string? | Genre/style |
| duration_seconds | integer? | Duration in seconds |
| key | string? | Musical key (e.g., "Am", "G") |
| tempo_bpm | integer? | Tempo in BPM |
| time_signature | string? | Time signature (e.g., "4/4") |
| lyrics | text? | Full lyrics |
| notes | text? | Performance notes |
| tags | json? | Array of tags |
| play_count | integer | Times played (default: 0) |
| last_played_at | timestamp? | Last performed |
| is_active | boolean | Active in catalog |
| created_by | ULID? | FK to users |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### music_attachments
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| music_number_id | ULID | FK to music_numbers |
| file_name | string | Stored filename |
| original_name | string | Original filename |
| file_path | string | Storage path |
| file_type | enum | `lyrics`, `chords`, `sheet_music`, `audio`, `other` |
| file_size | integer | Size in bytes |
| mime_type | string | MIME type |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### setlists
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| name | string | Setlist name |
| description | text? | Description |
| total_duration_seconds | integer? | Calculated total |
| is_template | boolean | Is a template |
| is_archived | boolean | Archived |
| created_by | ULID? | FK to users |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### setlist_items
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| setlist_id | ULID | FK to setlists |
| music_number_id | ULID? | FK to music_numbers |
| position | integer | Order position |
| set_number | integer | Set number (1, 2, 3) |
| is_break | boolean | Is a break |
| break_duration_seconds | integer? | Break length |
| notes | string? | Item notes |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### booking_requests
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| customer_id | ULID | FK to customers |
| event_date | date | Requested date |
| start_time | time? | Requested start |
| end_time | time? | Requested end |
| location_name | string? | Venue name |
| location_address | string? | Venue address |
| event_type | string? | Type of event |
| expected_guests | integer? | Guest count |
| message | text? | Request message |
| status | enum | `pending`, `reviewed`, `accepted`, `declined` |
| admin_notes | text? | Admin notes |
| event_id | ULID? | FK to created event |
| reviewed_by | ULID? | FK to users |
| reviewed_at | timestamp? | When reviewed |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### notifications
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| user_id | ULID | FK to users |
| type | string | Notification type |
| title | string | Title |
| message | text | Message body |
| data | json? | Additional data |
| action_url | string? | Link URL |
| read_at | timestamp? | When read |
| created_at | timestamp | Created |
| updated_at | timestamp | Updated |
#### activity_logs
| Column | Type | Description |
|--------|------|-------------|
| id | ULID | Primary key |
| user_id | ULID? | FK to users |
| loggable_type | string | Model class |
| loggable_id | ULID | Model ID |
| action | string | Action performed |
| description | text? | Description |
| changes | json? | Before/after data |
| ip_address | string? | Client IP |
| user_agent | string? | Browser info |
| created_at | timestamp | Created |
---
## API Response Format
### Success Response
```json
{
"success": true,
"data": { ... },
"message": "Event created successfully",
"meta": {
"pagination": {
"current_page": 1,
"per_page": 15,
"total": 100,
"last_page": 7,
"from": 1,
"to": 15
}
}
}
```
### Error Response
```json
{
"success": false,
"message": "Validation failed",
"errors": {
"title": ["The title field is required."],
"event_date": ["The event date must be a future date."]
}
}
```
### Single Resource
```json
{
"success": true,
"data": {
"id": "01HQ3K5P7X...",
"title": "Summer Concert",
"event_date": "2025-07-15",
"status": "confirmed",
"location": {
"id": "01HQ3K5P7X...",
"name": "City Park Amphitheater"
},
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T10:30:00Z"
}
}
```
### Collection (Paginated)
```json
{
"success": true,
"data": [
{ "id": "...", "title": "Event 1" },
{ "id": "...", "title": "Event 2" }
],
"meta": {
"pagination": {
"current_page": 1,
"per_page": 15,
"total": 45,
"last_page": 3
}
}
}
```
---
## User Roles & Permissions
### Roles
| Role | Description |
|------|-------------|
| `admin` | Full access to everything |
| `booking_agent` | Manage events, locations, customers |
| `music_manager` | Manage music catalog and setlists |
| `member` | View events, RSVP, view music |
### Permissions Matrix
| Resource | Admin | Booking Agent | Music Manager | Member |
|----------|-------|---------------|---------------|--------|
| Members | CRUD | Read | Read | Read |
| Events | CRUD | CRUD | Read | Read |
| Locations | CRUD | CRUD | Read | Read |
| Customers | CRUD | CRUD | Read | - |
| Music | CRUD | Read | CRUD | Read |
| Setlists | CRUD | Read | CRUD | Read |
| Booking Requests | CRUD | CRUD | - | - |
| RSVP | All | All | Own | Own |
---
## File Storage
### Structure
```
storage/app/
├── public/
│ ├── avatars/ # User avatars
│ └── music/ # Music attachments
│ ├── lyrics/
│ ├── chords/
│ ├── sheet_music/
│ └── audio/
└── private/
└── exports/ # Generated reports
```
### File Types Allowed
| Type | Extensions | Max Size |
|------|------------|----------|
| Avatar | jpg, png, webp | 2 MB |
| Lyrics | txt, pdf, docx | 5 MB |
| Chords | pdf, png, jpg | 10 MB |
| Sheet Music | pdf, png, jpg | 10 MB |
| Audio | mp3, wav, m4a | 50 MB |
---
## Architectural Decisions
### ADR-001: API-First Architecture
**Status**: Accepted
**Date**: 2025-01-01
**Context**: We need to build a web application with three separate SPAs (Admin, Band, Customers) that may have mobile clients in the future.
**Decision**: Implement a completely separated frontend and backend communicating via RESTful JSON API.
**Consequences**:
- ✅ Frontend and backend can be developed/deployed independently
- ✅ Easy to add mobile or other clients later
- ✅ Clear API contracts
- ✅ Better scalability options
- ⚠️ More complex initial setup
- ⚠️ Requires CORS configuration
---
### ADR-002: Laravel Sanctum for Authentication
**Status**: Accepted
**Date**: 2025-01-01
**Context**: Need authentication for SPAs that's secure and simple to implement.
**Decision**: Use Laravel Sanctum with token-based authentication for the SPAs.
**Alternatives Considered**:
- **Passport**: Too complex for our needs (OAuth2 overkill for first-party SPA)
- **JWT**: Requires token storage in localStorage (XSS vulnerable)
**Consequences**:
- ✅ Simple token-based auth for multiple SPAs
- ✅ Built into Laravel, minimal setup
- ✅ Works well with separate domains
- ⚠️ Need to handle token storage securely
---
### ADR-003: TanStack Query for Server State
**Status**: Accepted
**Date**: 2025-01-01
**Context**: Need efficient data fetching with caching, background updates, and optimistic updates.
**Decision**: Use TanStack Query (Vue Query) for all server state management.
**Consequences**:
- ✅ Automatic caching and deduplication
- ✅ Built-in loading/error states
- ✅ Background refetching
- ✅ Optimistic updates for better UX
- ✅ DevTools for debugging
- ⚠️ Learning curve for query key management
---
### ADR-004: Action Pattern for Business Logic
**Status**: Accepted
**Date**: 2025-01-01
**Context**: Controllers should be thin, and business logic needs to be reusable and testable.
**Decision**: Use single-responsibility Action classes for all business logic.
**Pattern**:
```php
class CreateEventAction
{
public function execute(array $data): Event
{
// Business logic here
}
}
// Usage in controller
public function store(Request $request, CreateEventAction $action)
{
return $action->execute($request->validated());
}
```
**Consequences**:
- ✅ Single Responsibility Principle
- ✅ Easy to test in isolation
- ✅ Reusable across controllers, commands, jobs
- ⚠️ More files to manage
---
### ADR-005: Vuexy for All SPAs
**Status**: Accepted
**Date**: 2025-01-01
**Context**: Need consistent UI across three SPAs with professional admin components.
**Decision**: Use Vuexy Vue template for all SPAs (full version for Admin, starter-kit for Band/Customers).
**Consequences**:
- ✅ Consistent UI/UX across all portals
- ✅ Pre-built admin components
- ✅ Single learning curve for the team
- ✅ Professional look out of the box
- ⚠️ License cost
- ⚠️ Dependency on third-party template
---
## Security Architecture
### Defense in Depth
```
┌─────────────────────────────────────────────────────────────┐
│ 1. Network Layer │
│ - HTTPS only │
│ - Rate limiting │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 2. Application Layer │
│ - CORS validation │
│ - Input validation (Form Requests) │
│ - SQL injection prevention (Eloquent) │
│ - XSS prevention (Vue escaping) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 3. Authentication & Authorization │
│ - Sanctum token authentication │
│ - Role-based access control │
│ - Resource authorization (Policies) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 4. Data Layer │
│ - Encrypted connections (TLS) │
│ - Sensitive data hashing (bcrypt) │
│ - Database credentials via environment │
└─────────────────────────────────────────────────────────────┘
```
### CORS Configuration
```php
// config/cors.php
'allowed_origins' => [
'http://localhost:5173', // Admin
'http://localhost:5174', // Band
'http://localhost:5175', // Customers
],
'supports_credentials' => true,
```
---
## Performance Considerations
### Backend Optimizations
1. **Database**
- Eager loading relationships (`with()`)
- Database indexes on filtered/sorted columns
- Query caching for expensive operations
2. **Caching Strategy**
```php
// Cache expensive queries
Cache::remember('stats:dashboard', 3600, fn() =>
$this->calculateStats()
);
```
3. **Queue Heavy Operations**
- Email sending
- File processing
- Report generation
### Frontend Optimizations
1. **Code Splitting**
- Lazy load routes
- Dynamic imports for heavy components
2. **Query Optimization**
```typescript
// Deduplicate requests
useQuery({ queryKey: ['events'], staleTime: 5 * 60 * 1000 })
// Prefetch on hover
queryClient.prefetchQuery({ queryKey: ['event', id] })
```
3. **Bundle Size**
- Tree shaking enabled
- Dynamic imports for routes
---
## Monitoring & Observability
### Logging Strategy
| Level | Use Case | Example |
|-------|----------|---------|
| DEBUG | Development only | Query details, variable dumps |
| INFO | Normal operations | User login, API calls |
| WARNING | Unexpected but handled | Rate limit approached |
| ERROR | Errors requiring attention | Failed payment |
| CRITICAL | System failures | Database down |
### Health Checks
```
GET /api/v1/health
{
"status": "healthy",
"checks": {
"database": "ok",
"redis": "ok",
"queue": "ok"
}
}
```
---
## Model Relationships
**User**
- User has many EventInvitations
- User has many Notifications
- User has many ActivityLogs
- User has many created Events (as creator)
- User has many created MusicNumbers (as creator)
- User has many created Setlists (as creator)
**Event**
- Event belongs to Location (nullable)
- Event belongs to Customer (nullable)
- Event belongs to Setlist (nullable)
- Event belongs to User (created_by)
- Event has many EventInvitations
- Event has many Users through EventInvitations (invited members)
**EventInvitation**
- EventInvitation belongs to Event
- EventInvitation belongs to User
**Location**
- Location has many Events
**Customer**
- Customer belongs to User (nullable, for portal access)
- Customer has many Events
- Customer has many BookingRequests
**MusicNumber**
- MusicNumber belongs to User (created_by, nullable)
- MusicNumber has many MusicAttachments
- MusicNumber has many SetlistItems
- MusicNumber has many Setlists through SetlistItems
**MusicAttachment**
- MusicAttachment belongs to MusicNumber
**Setlist**
- Setlist belongs to User (created_by, nullable)
- Setlist has many SetlistItems
- Setlist has many MusicNumbers through SetlistItems
- Setlist has many Events
**SetlistItem**
- SetlistItem belongs to Setlist
- SetlistItem belongs to MusicNumber (nullable, null when is_break = true)
**BookingRequest**
- BookingRequest belongs to Customer
- BookingRequest belongs to Event (nullable, when accepted)
- BookingRequest belongs to User (reviewed_by, nullable)
**Notification**
- Notification belongs to User
**ActivityLog**
- ActivityLog belongs to User (nullable)
- ActivityLog is polymorphic (loggable_type, loggable_id)
---
*Last updated: 2025-01-01*

318
.cursor/instructions.md Normal file
View File

@@ -0,0 +1,318 @@
# Band Management - Cursor AI Instructions
> This document provides AI assistants with comprehensive context about the project.
> Update this file as the project evolves.
## Project Overview
**Name**: Band Management Platform
**Type**: Full-stack web application (API-first architecture)
**Status**: Development
### Description
Band Management is a full-stack web application designed to streamline band operations by centralizing member coordination, gig management, music cataloging, and setlist planning. The platform serves as the single source of truth for all band-related activities.
## Quick Reference
| Component | Technology | Location | Port |
|-----------|------------|----------|------|
| API | Laravel 12 + Sanctum | `api/` | 8000 |
| Admin Dashboard | Vue 3 + Vuexy (full) | `apps/admin/` | 5173 |
| Band Portal | Vue 3 + Vuexy (starter) | `apps/band/` | 5174 |
| Customer Portal | Vue 3 + Vuexy (starter) | `apps/customers/` | 5175 |
| Database | MySQL 8.0 | Docker | 3306 |
| Cache | Redis | Docker | 6379 |
| Mail | Mailpit | Docker | 8025 |
## Documentation Structure
```
.cursor/
├── instructions.md # This file - overview and quick start
├── ARCHITECTURE.md # System architecture and data models
└── rules/
├── 001_workspace.mdc # Project structure and conventions
├── 100_laravel.mdc # Laravel API patterns
├── 101_vue.mdc # Vue + Vuexy patterns
└── 200_testing.mdc # Testing strategies
```
---
## Core Features
### Authentication & Authorization
- [ ] User registration with email verification
- [ ] User login/logout
- [ ] Password reset functionality
- [ ] Role-based access control (Admin, Booking Agent, Music Manager, Member)
- [ ] Permission middleware for route protection
- [ ] Session management
### Member Management
- [ ] List all members with search and filter
- [ ] Create new member with role assignment
- [ ] Edit member profile and roles
- [ ] Deactivate/reactivate members
- [ ] Member profile page (instruments, bio, contact info)
- [ ] Avatar upload
- [ ] Member invitation via email
- [ ] Activity log per member
### Events/Gigs Management
- [ ] List events with calendar and list view
- [ ] Create event with details (title, date, time, fee, notes)
- [ ] Edit/delete events
- [ ] Link event to location (from Location Manager)
- [ ] Link event to customer (from Customer Manager)
- [ ] Event status workflow (Draft → Pending → Confirmed → Completed → Cancelled)
- [ ] Invite members to event
- [ ] View RSVP responses per event
- [ ] Attach setlist to event
- [ ] Event detail page with all related info
- [ ] Duplicate event functionality
### RSVP System
- [ ] Member receives event invitation notification
- [ ] RSVP response options (Available, Unavailable, Tentative)
- [ ] Add note/reason with RSVP
- [ ] Change RSVP before deadline
- [ ] RSVP deadline per event
- [ ] Overview of member availability per event
- [ ] Automatic reminders for pending RSVPs
### Music Management
- [ ] List all music numbers with search and filter
- [ ] Add music number with metadata (title, artist, genre, duration)
- [ ] Edit/delete music numbers
- [ ] Additional fields: key, tempo (BPM), time signature
- [ ] File attachments (lyrics, chord sheets, audio files)
- [ ] Categorization with tags/genres
- [ ] Notes field for arrangements/cues
### Setlist Manager
- [ ] List all setlists
- [ ] Create setlist with name and description
- [ ] Add music numbers to setlist from catalog
- [ ] Drag-and-drop reordering of songs
- [ ] Add set breaks/intermissions
- [ ] Auto-calculate total duration
- [ ] Clone existing setlist
- [ ] Link setlist to event(s)
- [ ] Delete/archive setlists
### Location Manager
- [ ] List all locations with search
- [ ] Add location with details (name, address, capacity)
- [ ] Edit/delete locations
- [ ] Contact information (phone, email, contact person)
- [ ] Technical specifications (stage size, PA, backline, parking)
- [ ] Notes and special requirements
### Customer Manager
- [ ] List all customers with search
- [ ] Add customer (company or individual)
- [ ] Edit/delete customers
- [ ] Contact details (name, email, phone, address)
- [ ] Customer type classification
- [ ] Notes and preferences
- [ ] View booking history per customer
### Customer Portal
- [ ] Customer dashboard with booked events
- [ ] Submit booking requests
- [ ] Track request status
- [ ] View assigned setlists (if permitted)
- [ ] Profile settings
### Band Member Portal
- [ ] Member dashboard with upcoming events
- [ ] Personal event calendar
- [ ] RSVP management interface
- [ ] View event details (location, time, setlist)
- [ ] Browse music catalog (view-only)
- [ ] View setlists assigned to events
- [ ] Profile settings
- [ ] Notification preferences
### Admin Dashboard
- [ ] Dashboard with statistics/overview
- [ ] Quick actions panel
- [ ] Recent activity feed
- [ ] Upcoming events widget
- [ ] Pending RSVPs overview
- [ ] Booking requests management
### Notifications
- [ ] Email notifications for event invitations
- [ ] RSVP reminder notifications
- [ ] Event update notifications
- [ ] In-app notification center
- [ ] Notification preferences per user
---
## Getting Started Prompts
### 1. Create Laravel API
```
Create a Laravel 12 project in api/ with:
- Sanctum for API authentication
- MySQL configuration (host: 127.0.0.1, db: band_management, user: band_management, pass: secret)
- CORS configured for localhost:5173, localhost:5174, localhost:5175
- API response trait for consistent JSON responses
- Base controller with response helpers
Follow the patterns in .cursor/rules/100_laravel.mdc
```
### 2. Create Database Migrations
```
Create all migrations based on the schema in .cursor/ARCHITECTURE.md:
- Users, Customers, Locations
- Events, EventInvitations
- MusicNumbers, MusicAttachments
- Setlists, SetlistItems
- BookingRequests, Notifications, ActivityLogs
Use ULIDs for primary keys. Follow Laravel conventions.
```
### 3. Create Models with Relationships
```
Create Eloquent models for all tables with:
- HasUlids trait for ULID primary keys
- Proper relationships (belongsTo, hasMany, etc.)
- Fillable arrays
- Casts for enums, dates, and JSON fields
- Scopes for common queries
Follow patterns in .cursor/rules/100_laravel.mdc
```
### 4. Create Authentication System
```
Create auth system with:
- AuthController (login, logout, register, user, forgot-password, reset-password)
- Form requests for validation
- API resources for responses
- Sanctum token generation
Follow patterns in .cursor/rules/100_laravel.mdc
```
### 5. Integrate Vuexy with API
```
I've copied Vuexy Vue (typescript-version/full-version) to apps/admin/.
Update it to:
1. Create src/lib/api-client.ts for API calls with auth token handling
2. Install and configure @tanstack/vue-query
3. Replace Vuexy's fake auth with our Laravel API
4. Update navigation menu for our modules
Follow patterns in .cursor/rules/101_vue.mdc
```
### 6. Create Feature Modules
```
Create the Events module with:
- EventController with CRUD + invite/RSVP endpoints
- StoreEventRequest, UpdateEventRequest for validation
- EventResource, EventCollection for responses
- CreateEventAction, UpdateEventAction for business logic
- EventPolicy for authorization
- Feature tests
Follow patterns in .cursor/rules/100_laravel.mdc and .cursor/rules/200_testing.mdc
```
---
## Common Tasks
### Add a New API Endpoint
1. Create/update Controller in `app/Http/Controllers/Api/V1/`
2. Create Form Request in `app/Http/Requests/Api/V1/`
3. Create/update API Resource in `app/Http/Resources/Api/V1/`
4. Add route in `routes/api.php`
5. Create Action class if complex logic needed
6. Write feature test
### Add a New Vue Page
1. Create page component in `src/pages/`
2. Add route in `src/router/index.ts`
3. Add navigation item in `src/navigation/`
4. Create composable for API calls in `src/composables/`
5. Use Vuexy components for UI
### Add a New Database Table
1. Create migration: `php artisan make:migration create_tablename_table`
2. Create model with relationships
3. Create factory and seeder
4. Create controller, requests, resources
5. Add API routes
6. Write tests
---
## Code Generation Preferences
When generating code, always:
- Use PHP 8.3 features (typed properties, enums, match, readonly)
- Use strict types: `declare(strict_types=1);`
- Use `final` classes for Actions, Form Requests, Resources
- Use ULIDs for all primary keys
- Follow PSR-12 coding standards
- Use TypeScript strict mode in Vue
- Use Vue 3 Composition API with `<script setup lang="ts">`
- Use TanStack Query for API calls
- Return consistent API response format
---
## Environment Setup
### Docker Services
```bash
make services # Start MySQL, Redis, Mailpit
make services-stop # Stop services
```
### Development Servers
```bash
make api # Laravel on :8000
make admin # Admin SPA on :5173
make band # Band Portal on :5174
make customers # Customer Portal on :5175
```
### Database
```bash
make migrate # Run migrations
make fresh # Fresh migrate + seed
make db-shell # MySQL CLI
```

View File

@@ -0,0 +1,223 @@
---
description: Core workspace rules for Laravel + Vue/TypeScript full-stack application
globs: ["**/*"]
alwaysApply: true
---
# Workspace Rules
You are an expert full-stack developer working on a Laravel API backend with a Vue 3/TypeScript frontend using Vuexy admin template. This is an API-first architecture where the backend and frontend are completely separated.
## Tech Stack
### Backend (Laravel)
- PHP 8.3+
- Laravel 12+
- Laravel Sanctum for SPA authentication (token-based)
- MySQL 8.0 database
- Redis for cache and queues
- Pest for testing
### Frontend (Vue)
- Vue 3 with TypeScript (strict mode)
- Vite as build tool
- Vuexy Admin Template
- TanStack Query (Vue Query) for server state
- Pinia for client state
- Vue Router for routing
- Axios for HTTP client
## Project Structure
```
band-management/
├── api/ # Laravel 12 API
│ ├── app/
│ │ ├── Actions/ # Single-purpose business logic
│ │ ├── Enums/ # PHP enums
│ │ ├── Http/
│ │ │ ├── Controllers/Api/V1/
│ │ │ ├── Middleware/
│ │ │ ├── Requests/ # Form Request validation
│ │ │ └── Resources/ # API Resources
│ │ ├── Models/ # Eloquent models
│ │ ├── Policies/ # Authorization
│ │ ├── Services/ # Complex business logic
│ │ └── Traits/ # Shared traits
│ ├── database/
│ │ ├── factories/
│ │ ├── migrations/
│ │ └── seeders/
│ ├── routes/
│ │ └── api.php # API routes
│ └── tests/
│ ├── Feature/Api/
│ └── Unit/
├── apps/
│ ├── admin/ # Admin Dashboard (Vuexy full)
│ │ ├── src/
│ │ │ ├── @core/ # Vuexy core (don't modify)
│ │ │ ├── @layouts/ # Vuexy layouts (don't modify)
│ │ │ ├── components/ # Custom components
│ │ │ ├── composables/ # Vue composables
│ │ │ ├── layouts/ # App layouts
│ │ │ ├── lib/ # Utilities (api-client, etc.)
│ │ │ ├── navigation/ # Menu configuration
│ │ │ ├── pages/ # Page components
│ │ │ ├── plugins/ # Vue plugins
│ │ │ ├── router/ # Vue Router
│ │ │ ├── stores/ # Pinia stores
│ │ │ └── types/ # TypeScript types
│ │ └── ...
│ │
│ ├── band/ # Band Portal (Vuexy starter)
│ └── customers/ # Customer Portal (Vuexy starter)
├── docker/ # Docker configurations
├── docs/ # Documentation
└── .cursor/ # Cursor AI configuration
```
## Naming Conventions
### PHP (Laravel)
| Type | Convention | Example |
|------|------------|---------|
| Models | Singular PascalCase | `Event`, `MusicNumber` |
| Controllers | PascalCase + Controller | `EventController` |
| Form Requests | Action + Resource + Request | `StoreEventRequest` |
| Resources | Resource + Resource | `EventResource` |
| Actions | Verb + Resource + Action | `CreateEventAction` |
| Migrations | snake_case with timestamp | `create_events_table` |
| Tables | Plural snake_case | `events`, `music_numbers` |
| Columns | snake_case | `event_date`, `created_at` |
| Enums | Singular PascalCase | `EventStatus` |
### TypeScript (Vue)
| Type | Convention | Example |
|------|------------|---------|
| Components | PascalCase | `EventCard.vue` |
| Pages | PascalCase + Page | `EventsPage.vue` |
| Composables | camelCase with "use" | `useEvents.ts` |
| Stores | camelCase | `authStore.ts` |
| Types/Interfaces | PascalCase | `Event`, `ApiResponse` |
| Files | kebab-case or camelCase | `api-client.ts` |
## Code Style
### General Principles
1. **Explicit over implicit** - Be clear about types, returns, and intentions
2. **Small, focused units** - Each file/function does one thing well
3. **Consistent formatting** - Use automated formatters
4. **Descriptive names** - Names should explain purpose
5. **No magic** - Avoid hidden behavior
### PHP
- Use `declare(strict_types=1);` in all files
- Use `final` for classes that shouldn't be extended
- Use readonly properties where applicable
- Prefer named arguments for clarity
- Use enums instead of string constants
### TypeScript
- Enable strict mode in tsconfig
- No `any` types - use `unknown` if truly unknown
- Use interface for objects, type for unions/primitives
- Prefer `const` over `let`
- Use optional chaining and nullish coalescing
## Environment Configuration
### Development URLs
| Service | URL |
|---------|-----|
| API | http://localhost:8000/api/v1 |
| Admin SPA | http://localhost:5173 |
| Band SPA | http://localhost:5174 |
| Customer SPA | http://localhost:5175 |
| MySQL | localhost:3306 |
| Redis | localhost:6379 |
| Mailpit | http://localhost:8025 |
### Database Credentials (Development)
```
Host: 127.0.0.1
Port: 3306
Database: band_management
Username: band_management
Password: secret
```
### Production URLs
| Service | URL |
|---------|-----|
| API | https://api.bandmanagement.nl |
| Admin | https://admin.bandmanagement.nl |
| Band | https://band.bandmanagement.nl |
| Customers | https://customers.bandmanagement.nl |
## Git Conventions
### Branch Names
- `feature/event-management`
- `fix/rsvp-validation`
- `refactor/auth-system`
### Commit Messages
```
feat: add event RSVP functionality
fix: correct date validation in events
refactor: extract event creation to action class
docs: update API documentation
test: add event controller tests
```
## Dependencies
### PHP (api/composer.json)
- PHP 8.3+
- Laravel 12
- Laravel Sanctum
- Laravel Pint (formatting)
- Pest PHP (testing)
### Node (apps/*/package.json)
- Vue 3.4+
- TypeScript 5.3+
- Vite 5+
- Pinia
- @tanstack/vue-query
- axios
## Code Style Principles
1. **Readability over cleverness** - Write code that is easy to understand
2. **Single Responsibility** - Each class/function does one thing well
3. **Type Safety** - Leverage TypeScript and PHP type hints everywhere
4. **Testability** - Write code that is easy to test
5. **API Consistency** - Follow RESTful conventions
## Response Format
When generating code:
1. Always include proper type hints/annotations
2. Add brief comments for complex logic only
3. Follow the established patterns in the codebase
4. Consider error handling and edge cases
5. Suggest tests for new functionality
## Communication Style
- Be concise and direct
- Provide working code examples
- Explain architectural decisions briefly
- Ask clarifying questions only when truly ambiguous

View File

@@ -0,0 +1,786 @@
---
description: Laravel API development guidelines
globs: ["api/**/*.php"]
alwaysApply: true
---
# Laravel API Development Rules
## PHP Conventions
- Use PHP 8.3+ features: constructor property promotion, readonly properties, match expressions
- Use `match` operator over `switch` wherever possible
- Import all classes with `use` statements; avoid fully-qualified class names inline
- Use named arguments for functions with 3+ parameters
- Prefer early returns over nested conditionals
```php
// ✅ Good - constructor property promotion
public function __construct(
private readonly UserRepository $users,
private readonly Mailer $mailer,
) {}
// ✅ Good - early return
public function handle(Request $request): Response
{
if (!$request->user()) {
return response()->json(['error' => 'Unauthorized'], 401);
}
// Main logic here
}
// ❌ Avoid - nested conditionals
public function handle(Request $request): Response
{
if ($request->user()) {
// Nested logic
} else {
return response()->json(['error' => 'Unauthorized'], 401);
}
}
```
## Core Principles
1. **API-only** - No Blade views, no web routes
2. **Thin controllers** - Business logic in Actions
3. **Consistent responses** - Use API Resources and response trait
4. **Validate everything** - Use Form Requests
5. **Authorize properly** - Use Policies
6. **Test thoroughly** - Feature tests for all endpoints
## File Templates
### Model
```php
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\EventStatus;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Event extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'title',
'description',
'location_id',
'customer_id',
'setlist_id',
'event_date',
'start_time',
'end_time',
'fee',
'currency',
'status',
'visibility',
'rsvp_deadline',
'notes',
'internal_notes',
'created_by',
];
protected $casts = [
'event_date' => 'date',
'start_time' => 'datetime:H:i',
'end_time' => 'datetime:H:i',
'fee' => 'decimal:2',
'status' => EventStatus::class,
'rsvp_deadline' => 'datetime',
];
// Relationships
public function location(): BelongsTo
{
return $this->belongsTo(Location::class);
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function setlist(): BelongsTo
{
return $this->belongsTo(Setlist::class);
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function invitations(): HasMany
{
return $this->hasMany(EventInvitation::class);
}
// Scopes
public function scopeUpcoming($query)
{
return $query->where('event_date', '>=', now()->toDateString())
->orderBy('event_date');
}
public function scopeConfirmed($query)
{
return $query->where('status', EventStatus::Confirmed);
}
}
```
### Enum
```php
<?php
declare(strict_types=1);
namespace App\Enums;
enum EventStatus: string
{
case Draft = 'draft';
case Pending = 'pending';
case Confirmed = 'confirmed';
case Completed = 'completed';
case Cancelled = 'cancelled';
public function label(): string
{
return match ($this) {
self::Draft => 'Draft',
self::Pending => 'Pending Confirmation',
self::Confirmed => 'Confirmed',
self::Completed => 'Completed',
self::Cancelled => 'Cancelled',
};
}
public function color(): string
{
return match ($this) {
self::Draft => 'gray',
self::Pending => 'yellow',
self::Confirmed => 'green',
self::Completed => 'blue',
self::Cancelled => 'red',
};
}
}
```
### Migration
```php
<?php
declare(strict_types=1);
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('events', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('title');
$table->text('description')->nullable();
$table->foreignUlid('location_id')->nullable()->constrained()->nullOnDelete();
$table->foreignUlid('customer_id')->nullable()->constrained()->nullOnDelete();
$table->foreignUlid('setlist_id')->nullable()->constrained()->nullOnDelete();
$table->date('event_date');
$table->time('start_time');
$table->time('end_time')->nullable();
$table->time('load_in_time')->nullable();
$table->time('soundcheck_time')->nullable();
$table->decimal('fee', 10, 2)->nullable();
$table->string('currency', 3)->default('EUR');
$table->enum('status', ['draft', 'pending', 'confirmed', 'completed', 'cancelled'])->default('draft');
$table->enum('visibility', ['private', 'members', 'public'])->default('members');
$table->dateTime('rsvp_deadline')->nullable();
$table->text('notes')->nullable();
$table->text('internal_notes')->nullable();
$table->boolean('is_public_setlist')->default(false);
$table->foreignUlid('created_by')->constrained('users');
$table->timestamps();
$table->index(['event_date', 'status']);
});
}
public function down(): void
{
Schema::dropIfExists('events');
}
};
```
### Controller
```php
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Actions\Events\CreateEventAction;
use App\Actions\Events\UpdateEventAction;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\StoreEventRequest;
use App\Http\Requests\Api\V1\UpdateEventRequest;
use App\Http\Resources\Api\V1\EventCollection;
use App\Http\Resources\Api\V1\EventResource;
use App\Models\Event;
use Illuminate\Http\JsonResponse;
final class EventController extends Controller
{
public function index(): EventCollection
{
$events = Event::query()
->with(['location', 'customer'])
->latest('event_date')
->paginate();
return new EventCollection($events);
}
public function store(StoreEventRequest $request, CreateEventAction $action): JsonResponse
{
$event = $action->execute($request->validated());
return $this->created(
new EventResource($event->load(['location', 'customer'])),
'Event created successfully'
);
}
public function show(Event $event): EventResource
{
return new EventResource(
$event->load(['location', 'customer', 'setlist', 'invitations.user'])
);
}
public function update(UpdateEventRequest $request, Event $event, UpdateEventAction $action): JsonResponse
{
$event = $action->execute($event, $request->validated());
return $this->success(
new EventResource($event),
'Event updated successfully'
);
}
public function destroy(Event $event): JsonResponse
{
$event->delete();
return $this->success(null, 'Event deleted successfully');
}
}
```
### Form Request
```php
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class StoreEventRequest extends FormRequest
{
public function authorize(): bool
{
return true; // Or use policy
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:5000'],
'location_id' => ['nullable', 'ulid', 'exists:locations,id'],
'customer_id' => ['nullable', 'ulid', 'exists:customers,id'],
'setlist_id' => ['nullable', 'ulid', 'exists:setlists,id'],
'event_date' => ['required', 'date', 'after_or_equal:today'],
'start_time' => ['required', 'date_format:H:i'],
'end_time' => ['nullable', 'date_format:H:i', 'after:start_time'],
'load_in_time' => ['nullable', 'date_format:H:i'],
'soundcheck_time' => ['nullable', 'date_format:H:i'],
'fee' => ['nullable', 'numeric', 'min:0', 'max:999999.99'],
'currency' => ['sometimes', 'string', 'size:3'],
'status' => ['sometimes', Rule::enum(EventStatus::class)],
'visibility' => ['sometimes', Rule::enum(EventVisibility::class)],
'rsvp_deadline' => ['nullable', 'date', 'before:event_date'],
'notes' => ['nullable', 'string', 'max:5000'],
'internal_notes' => ['nullable', 'string', 'max:5000'],
];
}
public function messages(): array
{
return [
'event_date.after_or_equal' => 'The event date must be today or a future date.',
'end_time.after' => 'The end time must be after the start time.',
];
}
}
```
### API Resource
```php
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class EventResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'event_date' => $this->event_date->toDateString(),
'start_time' => $this->start_time?->format('H:i'),
'end_time' => $this->end_time?->format('H:i'),
'load_in_time' => $this->load_in_time?->format('H:i'),
'soundcheck_time' => $this->soundcheck_time?->format('H:i'),
'fee' => $this->fee,
'currency' => $this->currency,
'status' => $this->status->value,
'status_label' => $this->status->label(),
'visibility' => $this->visibility,
'rsvp_deadline' => $this->rsvp_deadline?->toIso8601String(),
'notes' => $this->notes,
'internal_notes' => $this->when(
$request->user()?->isAdmin(),
$this->internal_notes
),
'location' => new LocationResource($this->whenLoaded('location')),
'customer' => new CustomerResource($this->whenLoaded('customer')),
'setlist' => new SetlistResource($this->whenLoaded('setlist')),
'invitations' => EventInvitationResource::collection(
$this->whenLoaded('invitations')
),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}
```
### Resource Collection
```php
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
final class EventCollection extends ResourceCollection
{
public $collects = EventResource::class;
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
];
}
public function with(Request $request): array
{
return [
'success' => true,
'meta' => [
'pagination' => [
'current_page' => $this->currentPage(),
'per_page' => $this->perPage(),
'total' => $this->total(),
'last_page' => $this->lastPage(),
'from' => $this->firstItem(),
'to' => $this->lastItem(),
],
],
];
}
}
```
### Action Class
```php
<?php
declare(strict_types=1);
namespace App\Actions\Events;
use App\Models\Event;
use Illuminate\Support\Facades\Auth;
final class CreateEventAction
{
public function execute(array $data): Event
{
$data['created_by'] = Auth::id();
return Event::create($data);
}
}
```
### API Response Trait
```php
<?php
declare(strict_types=1);
namespace App\Traits;
use Illuminate\Http\JsonResponse;
trait ApiResponse
{
protected function success(mixed $data = null, string $message = 'Success', int $code = 200): JsonResponse
{
return response()->json([
'success' => true,
'data' => $data,
'message' => $message,
], $code);
}
protected function created(mixed $data = null, string $message = 'Created'): JsonResponse
{
return $this->success($data, $message, 201);
}
protected function error(string $message, int $code = 400, array $errors = []): JsonResponse
{
$response = [
'success' => false,
'message' => $message,
];
if (!empty($errors)) {
$response['errors'] = $errors;
}
return response()->json($response, $code);
}
protected function notFound(string $message = 'Resource not found'): JsonResponse
{
return $this->error($message, 404);
}
protected function unauthorized(string $message = 'Unauthorized'): JsonResponse
{
return $this->error($message, 401);
}
protected function forbidden(string $message = 'Forbidden'): JsonResponse
{
return $this->error($message, 403);
}
}
```
### Base Controller
```php
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Traits\ApiResponse;
abstract class Controller
{
use ApiResponse;
}
```
### Policy
```php
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Event;
use App\Models\User;
final class EventPolicy
{
public function viewAny(User $user): bool
{
return true;
}
public function view(User $user, Event $event): bool
{
return true;
}
public function create(User $user): bool
{
return $user->isAdmin() || $user->isBookingAgent();
}
public function update(User $user, Event $event): bool
{
return $user->isAdmin() || $user->isBookingAgent();
}
public function delete(User $user, Event $event): bool
{
return $user->isAdmin();
}
}
```
### Routes (api.php)
```php
<?php
declare(strict_types=1);
use App\Http\Controllers\Api\V1\AuthController;
use App\Http\Controllers\Api\V1\EventController;
use App\Http\Controllers\Api\V1\LocationController;
use App\Http\Controllers\Api\V1\MemberController;
use App\Http\Controllers\Api\V1\MusicController;
use App\Http\Controllers\Api\V1\SetlistController;
use App\Http\Controllers\Api\V1\CustomerController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function () {
// Public routes
Route::post('auth/login', [AuthController::class, 'login']);
Route::post('auth/register', [AuthController::class, 'register']);
Route::post('auth/forgot-password', [AuthController::class, 'forgotPassword']);
Route::post('auth/reset-password', [AuthController::class, 'resetPassword']);
// Protected routes
Route::middleware('auth:sanctum')->group(function () {
// Auth
Route::get('auth/user', [AuthController::class, 'user']);
Route::post('auth/logout', [AuthController::class, 'logout']);
// Resources
Route::apiResource('events', EventController::class);
Route::post('events/{event}/invite', [EventController::class, 'invite']);
Route::post('events/{event}/rsvp', [EventController::class, 'rsvp']);
Route::apiResource('members', MemberController::class);
Route::apiResource('music', MusicController::class);
Route::apiResource('setlists', SetlistController::class);
Route::apiResource('locations', LocationController::class);
Route::apiResource('customers', CustomerController::class);
});
});
```
## Best Practices
### Always Use
- `declare(strict_types=1)` at the top of every file
- `final` keyword for Action classes, Form Requests, Resources
- Type hints for all parameters and return types
- Named arguments for better readability
- Enums for status fields and fixed options
- ULIDs for all primary keys
- Eager loading to prevent N+1 queries
- API Resources for all responses
### Avoid
- Business logic in controllers
- String constants (use enums)
- Auto-increment IDs
- Direct model creation in controllers
- Returning raw models (use Resources)
- Hardcoded strings for error messages
## DTOs (Data Transfer Objects)
Use DTOs for complex data passing between layers:
```php
<?php
declare(strict_types=1);
namespace App\DTOs;
readonly class CreateEventDTO
{
public function __construct(
public string $title,
public string $eventDate,
public string $startTime,
public ?string $description = null,
public ?string $locationId = null,
public ?string $customerId = null,
public ?string $endTime = null,
public ?float $fee = null,
) {}
public static function from(array $data): self
{
return new self(
title: $data['title'],
eventDate: $data['event_date'],
startTime: $data['start_time'],
description: $data['description'] ?? null,
locationId: $data['location_id'] ?? null,
customerId: $data['customer_id'] ?? null,
endTime: $data['end_time'] ?? null,
fee: $data['fee'] ?? null,
);
}
}
// Usage
$dto = CreateEventDTO::from($request->validated());
$event = $action->execute($dto);
```
## Helpers
Use Laravel helpers instead of facades:
```php
// ✅ Good
auth()->id()
auth()->user()
now()
str($string)->slug()
collect($array)->filter()
cache()->remember('key', 3600, fn() => $value)
// ❌ Avoid
Auth::id()
Carbon::now()
Str::slug($string)
Cache::remember(...)
```
## Error Handling
Create domain-specific exceptions:
```php
<?php
declare(strict_types=1);
namespace App\Exceptions;
use Exception;
use Illuminate\Http\JsonResponse;
class EventNotFoundException extends Exception
{
public function render(): JsonResponse
{
return response()->json([
'success' => false,
'message' => 'Event not found',
], 404);
}
}
class EventAlreadyConfirmedException extends Exception
{
public function render(): JsonResponse
{
return response()->json([
'success' => false,
'message' => 'Event has already been confirmed and cannot be modified',
], 422);
}
}
// Usage in Action
if ($event->isConfirmed()) {
throw new EventAlreadyConfirmedException();
}
```
## Query Scopes
Add reusable query scopes to models:
```php
// In Event model
public function scopeUpcoming(Builder $query): Builder
{
return $query->where('event_date', '>=', now()->toDateString())
->orderBy('event_date');
}
public function scopeForUser(Builder $query, User $user): Builder
{
return $query->whereHas('invitations', fn ($q) =>
$q->where('user_id', $user->id)
);
}
public function scopeConfirmed(Builder $query): Builder
{
return $query->where('status', EventStatus::Confirmed);
}
// Usage
Event::upcoming()->confirmed()->get();
Event::forUser($user)->upcoming()->get();
```

1056
.cursor/rules/101_vue.mdc Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,870 @@
---
description: Testing standards for Laravel API and Vue frontend
globs: ["**/tests/**", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx", "**/Test.php"]
alwaysApply: true
---
# Testing Standards
## Philosophy
1. **Test behavior, not implementation** - Focus on what, not how
2. **Feature tests for APIs** - Test full request/response cycles
3. **Unit tests for logic** - Test Actions and complex functions
4. **Integration tests for Vue** - Test component interactions
5. **Fast and isolated** - Each test should be independent
## Laravel Testing
### Directory Structure
```
api/tests/
├── Feature/
│ └── Api/
│ ├── AuthTest.php
│ ├── EventTest.php
│ ├── MemberTest.php
│ ├── MusicTest.php
│ ├── SetlistTest.php
│ ├── LocationTest.php
│ └── CustomerTest.php
├── Unit/
│ ├── Actions/
│ │ ├── CreateEventActionTest.php
│ │ └── ...
│ └── Models/
│ ├── EventTest.php
│ └── ...
└── TestCase.php
```
### Feature Test Template
```php
<?php
declare(strict_types=1);
namespace Tests\Feature\Api;
use App\Enums\EventStatus;
use App\Models\Event;
use App\Models\Location;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class EventTest extends TestCase
{
use RefreshDatabase;
private User $admin;
private User $member;
protected function setUp(): void
{
parent::setUp();
$this->admin = User::factory()->admin()->create();
$this->member = User::factory()->member()->create();
}
// ==========================================
// INDEX
// ==========================================
public function test_guests_cannot_list_events(): void
{
$response = $this->getJson('/api/v1/events');
$response->assertStatus(401);
}
public function test_authenticated_users_can_list_events(): void
{
Event::factory()->count(3)->create();
$response = $this->actingAs($this->member)
->getJson('/api/v1/events');
$response->assertStatus(200)
->assertJsonStructure([
'success',
'data' => [
'*' => ['id', 'title', 'event_date', 'status'],
],
'meta' => ['pagination'],
])
->assertJsonCount(3, 'data');
}
public function test_events_are_paginated(): void
{
Event::factory()->count(20)->create();
$response = $this->actingAs($this->member)
->getJson('/api/v1/events?per_page=10');
$response->assertStatus(200)
->assertJsonCount(10, 'data')
->assertJsonPath('meta.pagination.total', 20)
->assertJsonPath('meta.pagination.per_page', 10);
}
// ==========================================
// SHOW
// ==========================================
public function test_can_view_single_event(): void
{
$event = Event::factory()->create(['title' => 'Summer Concert']);
$response = $this->actingAs($this->member)
->getJson("/api/v1/events/{$event->id}");
$response->assertStatus(200)
->assertJsonPath('success', true)
->assertJsonPath('data.title', 'Summer Concert');
}
public function test_returns_404_for_nonexistent_event(): void
{
$response = $this->actingAs($this->member)
->getJson('/api/v1/events/nonexistent-id');
$response->assertStatus(404);
}
// ==========================================
// STORE
// ==========================================
public function test_admin_can_create_event(): void
{
$location = Location::factory()->create();
$eventData = [
'title' => 'New Year Concert',
'event_date' => now()->addMonth()->toDateString(),
'start_time' => '20:00',
'location_id' => $location->id,
'status' => 'draft',
];
$response = $this->actingAs($this->admin)
->postJson('/api/v1/events', $eventData);
$response->assertStatus(201)
->assertJsonPath('success', true)
->assertJsonPath('data.title', 'New Year Concert');
$this->assertDatabaseHas('events', [
'title' => 'New Year Concert',
'location_id' => $location->id,
]);
}
public function test_member_cannot_create_event(): void
{
$eventData = [
'title' => 'Unauthorized Event',
'event_date' => now()->addMonth()->toDateString(),
'start_time' => '20:00',
];
$response = $this->actingAs($this->member)
->postJson('/api/v1/events', $eventData);
$response->assertStatus(403);
}
public function test_validation_errors_are_returned(): void
{
$response = $this->actingAs($this->admin)
->postJson('/api/v1/events', []);
$response->assertStatus(422)
->assertJsonPath('success', false)
->assertJsonValidationErrors(['title', 'event_date', 'start_time']);
}
public function test_event_date_must_be_future(): void
{
$response = $this->actingAs($this->admin)
->postJson('/api/v1/events', [
'title' => 'Past Event',
'event_date' => now()->subDay()->toDateString(),
'start_time' => '20:00',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['event_date']);
}
// ==========================================
// UPDATE
// ==========================================
public function test_admin_can_update_event(): void
{
$event = Event::factory()->create(['title' => 'Old Title']);
$response = $this->actingAs($this->admin)
->putJson("/api/v1/events/{$event->id}", [
'title' => 'Updated Title',
]);
$response->assertStatus(200)
->assertJsonPath('data.title', 'Updated Title');
$this->assertDatabaseHas('events', [
'id' => $event->id,
'title' => 'Updated Title',
]);
}
public function test_can_update_event_status(): void
{
$event = Event::factory()->draft()->create();
$response = $this->actingAs($this->admin)
->putJson("/api/v1/events/{$event->id}", [
'status' => 'confirmed',
]);
$response->assertStatus(200)
->assertJsonPath('data.status', 'confirmed');
}
// ==========================================
// DELETE
// ==========================================
public function test_admin_can_delete_event(): void
{
$event = Event::factory()->create();
$response = $this->actingAs($this->admin)
->deleteJson("/api/v1/events/{$event->id}");
$response->assertStatus(200)
->assertJsonPath('success', true);
$this->assertDatabaseMissing('events', ['id' => $event->id]);
}
public function test_member_cannot_delete_event(): void
{
$event = Event::factory()->create();
$response = $this->actingAs($this->member)
->deleteJson("/api/v1/events/{$event->id}");
$response->assertStatus(403);
$this->assertDatabaseHas('events', ['id' => $event->id]);
}
// ==========================================
// RELATIONSHIPS
// ==========================================
public function test_event_includes_location_when_loaded(): void
{
$location = Location::factory()->create(['name' => 'City Hall']);
$event = Event::factory()->create(['location_id' => $location->id]);
$response = $this->actingAs($this->member)
->getJson("/api/v1/events/{$event->id}");
$response->assertStatus(200)
->assertJsonPath('data.location.name', 'City Hall');
}
}
```
### Unit Test Template (Action)
```php
<?php
declare(strict_types=1);
namespace Tests\Unit\Actions;
use App\Actions\Events\CreateEventAction;
use App\Models\Event;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class CreateEventActionTest extends TestCase
{
use RefreshDatabase;
private CreateEventAction $action;
protected function setUp(): void
{
parent::setUp();
$this->action = new CreateEventAction();
}
public function test_creates_event_with_valid_data(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$data = [
'title' => 'Test Event',
'event_date' => now()->addMonth()->toDateString(),
'start_time' => '20:00',
];
$event = $this->action->execute($data);
$this->assertInstanceOf(Event::class, $event);
$this->assertEquals('Test Event', $event->title);
$this->assertEquals($user->id, $event->created_by);
}
public function test_sets_default_values(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$event = $this->action->execute([
'title' => 'Test',
'event_date' => now()->addMonth()->toDateString(),
'start_time' => '20:00',
]);
$this->assertEquals('EUR', $event->currency);
$this->assertEquals('draft', $event->status->value);
}
}
```
### Model Factory Template
```php
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use App\Models\Event;
use App\Models\Location;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Event>
*/
final class EventFactory extends Factory
{
protected $model = Event::class;
public function definition(): array
{
return [
'title' => fake()->sentence(3),
'description' => fake()->optional()->paragraph(),
'event_date' => fake()->dateTimeBetween('+1 week', '+6 months'),
'start_time' => fake()->time('H:i'),
'end_time' => fake()->optional()->time('H:i'),
'fee' => fake()->optional()->randomFloat(2, 100, 5000),
'currency' => 'EUR',
'status' => fake()->randomElement(EventStatus::cases()),
'visibility' => EventVisibility::Members,
'created_by' => User::factory(),
];
}
public function draft(): static
{
return $this->state(fn () => ['status' => EventStatus::Draft]);
}
public function confirmed(): static
{
return $this->state(fn () => ['status' => EventStatus::Confirmed]);
}
public function withLocation(): static
{
return $this->state(fn () => ['location_id' => Location::factory()]);
}
public function upcoming(): static
{
return $this->state(fn () => [
'event_date' => fake()->dateTimeBetween('+1 day', '+1 month'),
'status' => EventStatus::Confirmed,
]);
}
public function past(): static
{
return $this->state(fn () => [
'event_date' => fake()->dateTimeBetween('-6 months', '-1 day'),
'status' => EventStatus::Completed,
]);
}
}
```
### User Factory States
```php
<?php
// In UserFactory.php
public function admin(): static
{
return $this->state(fn () => [
'type' => 'member',
'role' => 'admin',
'status' => 'active',
]);
}
public function member(): static
{
return $this->state(fn () => [
'type' => 'member',
'role' => 'member',
'status' => 'active',
]);
}
public function bookingAgent(): static
{
return $this->state(fn () => [
'type' => 'member',
'role' => 'booking_agent',
'status' => 'active',
]);
}
public function customer(): static
{
return $this->state(fn () => [
'type' => 'customer',
'role' => null,
'status' => 'active',
]);
}
```
### Test Helpers (TestCase.php)
```php
<?php
declare(strict_types=1);
namespace Tests;
use App\Models\User;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
/**
* Create and authenticate as admin user.
*/
protected function actingAsAdmin(): User
{
$admin = User::factory()->admin()->create();
$this->actingAs($admin);
return $admin;
}
/**
* Create and authenticate as regular member.
*/
protected function actingAsMember(): User
{
$member = User::factory()->member()->create();
$this->actingAs($member);
return $member;
}
/**
* Assert API success response structure.
*/
protected function assertApiSuccess($response, int $status = 200): void
{
$response->assertStatus($status)
->assertJsonStructure(['success', 'data'])
->assertJsonPath('success', true);
}
/**
* Assert API error response structure.
*/
protected function assertApiError($response, int $status = 400): void
{
$response->assertStatus($status)
->assertJsonPath('success', false)
->assertJsonStructure(['success', 'message']);
}
}
```
## Running Tests
### Laravel
```bash
# Run all tests
cd api && php artisan test
# Run with coverage
php artisan test --coverage
# Run specific test file
php artisan test tests/Feature/Api/EventTest.php
# Run specific test method
php artisan test --filter test_admin_can_create_event
# Run in parallel
php artisan test --parallel
```
### Pest PHP Syntax
```php
<?php
use App\Models\Event;
use App\Models\User;
beforeEach(function () {
$this->admin = User::factory()->admin()->create();
});
it('allows admin to create events', function () {
$response = $this->actingAs($this->admin)
->postJson('/api/v1/events', [
'title' => 'Concert',
'event_date' => now()->addMonth()->toDateString(),
'start_time' => '20:00',
]);
$response->assertStatus(201);
expect(Event::count())->toBe(1);
});
it('validates required fields', function () {
$response = $this->actingAs($this->admin)
->postJson('/api/v1/events', []);
$response->assertStatus(422)
->assertJsonValidationErrors(['title', 'event_date']);
});
it('returns paginated results', function () {
Event::factory()->count(25)->create();
$response = $this->actingAs($this->admin)
->getJson('/api/v1/events?per_page=10');
expect($response->json('data'))->toHaveCount(10);
expect($response->json('meta.pagination.total'))->toBe(25);
});
```
## Vue Testing (Vitest + Vue Test Utils)
### File Organization
```
src/
├── components/
│ └── EventCard/
│ ├── EventCard.vue
│ └── EventCard.test.ts
├── composables/
│ └── useEvents.test.ts
└── test/
├── setup.ts
├── mocks/
│ ├── handlers.ts # MSW handlers
│ └── server.ts
└── utils.ts # Custom render with providers
```
### Vitest Configuration
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath } from 'node:url'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})
```
### Test Setup
```typescript
// src/test/setup.ts
import { vi, beforeAll, afterAll, afterEach } from 'vitest'
import { config } from '@vue/test-utils'
import { server } from './mocks/server'
// Start MSW server
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
// Global stubs for Vuexy components
config.global.stubs = {
VBtn: true,
VCard: true,
VCardText: true,
VCardTitle: true,
VTable: true,
VDialog: true,
VProgressCircular: true,
RouterLink: true,
}
```
### MSW Setup for API Mocking
```typescript
// src/test/mocks/handlers.ts
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/v1/events', () => {
return HttpResponse.json({
success: true,
data: [
{ id: '1', title: 'Event 1', status: 'confirmed' },
{ id: '2', title: 'Event 2', status: 'draft' },
{ id: '3', title: 'Event 3', status: 'pending' },
],
meta: { pagination: { current_page: 1, total: 3, per_page: 15 } }
})
}),
http.post('/api/v1/events', async ({ request }) => {
const body = await request.json()
return HttpResponse.json({
success: true,
data: { id: '4', ...body },
message: 'Event created successfully'
}, { status: 201 })
}),
http.get('/api/v1/auth/user', () => {
return HttpResponse.json({
success: true,
data: { id: '1', name: 'Test User', email: 'test@example.com', role: 'admin' }
})
}),
]
// src/test/mocks/server.ts
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
```
### Test Utilities
```typescript
// src/test/utils.ts
import { mount, VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
import { createRouter, createWebHistory } from 'vue-router'
import type { Component } from 'vue'
export function createTestingPinia() {
const pinia = createPinia()
setActivePinia(pinia)
return pinia
}
export function createTestQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0 },
mutations: { retry: false },
},
})
}
export function mountWithProviders(component: Component, options = {}) {
const pinia = createTestingPinia()
const queryClient = createTestQueryClient()
const router = createRouter({
history: createWebHistory(),
routes: [{ path: '/', component: { template: '<div />' } }],
})
return mount(component, {
global: {
plugins: [pinia, router, [VueQueryPlugin, { queryClient }]],
stubs: {
VBtn: true,
VCard: true,
VTable: true,
},
},
...options,
})
}
```
### Component Test Pattern
```typescript
// src/components/EventCard.test.ts
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import EventCard from './EventCard.vue'
describe('EventCard', () => {
const mockEvent = {
id: '1',
title: 'Summer Concert',
event_date: '2025-07-15',
status: 'confirmed',
status_label: 'Confirmed',
}
it('displays event title', () => {
const wrapper = mount(EventCard, {
props: { event: mockEvent },
})
expect(wrapper.text()).toContain('Summer Concert')
})
it('emits edit event when edit button clicked', async () => {
const wrapper = mount(EventCard, {
props: { event: mockEvent },
})
await wrapper.find('[data-test="edit-btn"]').trigger('click')
expect(wrapper.emitted('edit')).toBeTruthy()
expect(wrapper.emitted('edit')?.[0]).toEqual([mockEvent])
})
it('shows correct status color', () => {
const wrapper = mount(EventCard, {
props: { event: mockEvent },
})
const chip = wrapper.find('[data-test="status-chip"]')
expect(chip.classes()).toContain('bg-success')
})
})
```
### Composable Test Pattern
```typescript
// src/composables/__tests__/useEvents.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { useEvents } from '../useEvents'
import { createTestQueryClient, createTestingPinia } from '@/test/utils'
import { VueQueryPlugin } from '@tanstack/vue-query'
import { createApp } from 'vue'
describe('useEvents', () => {
beforeEach(() => {
createTestingPinia()
})
it('fetches events successfully', async () => {
const app = createApp({ template: '<div />' })
const queryClient = createTestQueryClient()
app.use(VueQueryPlugin, { queryClient })
// Mount and test...
await flushPromises()
// Assertions
})
})
```
### Pest Expectations (Laravel)
```php
// Use fluent expectations
expect($user)->toBeInstanceOf(User::class);
expect($collection)->toHaveCount(5);
expect($response->json('data'))->toMatchArray([...]);
// Chain expectations
expect($user)
->name->toBe('John')
->email->toContain('@')
->created_at->toBeInstanceOf(Carbon::class);
```
## Test Coverage Goals
| Area | Target | Priority |
|------|--------|----------|
| API Endpoints | 90%+ | High |
| Actions | 100% | High |
| Models | 80%+ | Medium |
| Vue Composables | 80%+ | Medium |
| Vue Components | 60%+ | Low |
**Minimum Coverage**: 80% line coverage
## Coverage Requirements
- **Feature tests**: All API endpoints must have tests
- **Unit tests**: All Actions and Services with business logic
- **Component tests**: All interactive components
- **Composable tests**: All custom composables that fetch data
## Best Practices
### Do
- Test happy path AND edge cases
- Use descriptive test names
- One assertion focus per test
- Use factories for test data
- Clean up after tests (RefreshDatabase)
- Test authorization separately
### Don't
- Test framework code (Laravel, Vue)
- Test private methods directly
- Share state between tests
- Use real external APIs
- Over-mock (test real behavior)

44
.gitignore vendored Normal file
View File

@@ -0,0 +1,44 @@
# Dependencies
node_modules/
vendor/
# Build outputs
dist/
build/
public/build/
public/hot
# Environment files
.env
.env.local
.env.*.local
!.env.example
# IDE
.idea/
*.swp
*.swo
.DS_Store
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
storage/logs/*
!storage/logs/.gitkeep
# Laravel
bootstrap/cache/*
!bootstrap/cache/.gitkeep
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
# Testing
.phpunit.result.cache
coverage/
# Misc
*.pem
.cache/

10
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"recommendations": [
"bmewburn.vscode-intelephense-client",
"Vue.volar",
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"mikestead.dotenv",
"ms-azuretools.vscode-docker"
]
}

37
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"editor.formatOnSave": true,
"editor.tabSize": 2,
"[php]": {
"editor.defaultFormatter": "bmewburn.vscode-intelephense-client",
"editor.tabSize": 4
},
"[vue]": {
"editor.defaultFormatter": "Vue.volar"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"typescript.preferences.importModuleSpecifier": "relative",
"typescript.suggest.autoImports": true,
"files.associations": {
"*.php": "php",
".env*": "dotenv"
},
"search.exclude": {
"**/node_modules": true,
"**/vendor": true,
"**/dist": true
},
"eslint.workingDirectories": [
{ "directory": "apps/admin", "changeProcessCWD": true },
{ "directory": "apps/band", "changeProcessCWD": true },
{ "directory": "apps/customers", "changeProcessCWD": true }
]
}

71
Makefile Normal file
View File

@@ -0,0 +1,71 @@
.PHONY: help services services-stop api admin band customers
# Colors
GREEN := \033[0;32m
YELLOW := \033[0;33m
CYAN := \033[0;36m
NC := \033[0m
help:
@echo ""
@echo "$(GREEN)╔══════════════════════════════════════════════════════════════╗$(NC)"
@echo "$(GREEN)║ BAND MANAGEMENT - Development Commands ║$(NC)"
@echo "$(GREEN)╚══════════════════════════════════════════════════════════════╝$(NC)"
@echo ""
@echo " $(YELLOW)Services (Docker):$(NC)"
@echo " make services Start MySQL, Redis, Mailpit"
@echo " make services-stop Stop all Docker services"
@echo ""
@echo " $(YELLOW)Development Servers:$(NC)"
@echo " make api Laravel API → http://localhost:8000"
@echo " make admin Admin Dashboard → http://localhost:5173"
@echo " make band Band Portal → http://localhost:5174"
@echo " make customers Customer Portal → http://localhost:5175"
@echo ""
@echo " $(YELLOW)Database:$(NC)"
@echo " make migrate Run migrations"
@echo " make fresh Fresh migrate + seed"
@echo " make db-shell Open MySQL shell"
@echo ""
services:
@echo "$(GREEN)Starting Docker services...$(NC)"
@docker compose up -d
@echo ""
@echo "$(GREEN)Services:$(NC)"
@echo " $(CYAN)MySQL:$(NC) localhost:3306 (band_management / secret)"
@echo " $(CYAN)Redis:$(NC) localhost:6379"
@echo " $(CYAN)Mailpit:$(NC) http://localhost:8025"
@echo ""
@echo "$(YELLOW)Waiting for MySQL...$(NC)"
@until docker exec bm_mysql mysqladmin ping -h localhost -u root -proot --silent 2>/dev/null; do sleep 1; done
@echo "$(GREEN)✓ Ready!$(NC)"
services-stop:
@docker compose down
@echo "$(GREEN)✓ Services stopped$(NC)"
api:
@echo "$(GREEN)Starting Laravel API → http://localhost:8000$(NC)"
@cd api && php artisan serve
admin:
@echo "$(GREEN)Starting Admin SPA → http://localhost:5173$(NC)"
@cd apps/admin && pnpm dev
band:
@echo "$(GREEN)Starting Band Portal → http://localhost:5174$(NC)"
@cd apps/band && pnpm dev --port 5174
customers:
@echo "$(GREEN)Starting Customer Portal → http://localhost:5175$(NC)"
@cd apps/customers && pnpm dev --port 5175
migrate:
@cd api && php artisan migrate
fresh:
@cd api && php artisan migrate:fresh --seed
db-shell:
@docker exec -it bm_mysql mysql -u band_management -psecret band_management

73
README.md Normal file
View File

@@ -0,0 +1,73 @@
# Band Management
Full-stack band/artist operations management platform.
## Tech Stack
| Layer | Technology |
|-------|------------|
| Backend | Laravel 12 + PHP 8.3 + Sanctum |
| Database | MySQL 8.0 |
| Frontend | Vue 3 + TypeScript + Vuexy |
| Local Dev | Native PHP/Node + Docker |
## Quick Start
```bash
# 1. Start Docker services
make services
# 2. Open in Cursor and start building!
```
See [docs/SETUP.md](docs/SETUP.md) for detailed instructions.
## Project Structure
```
band-management/
├── api/ # Laravel 12 API
├── apps/
│ ├── admin/ # Admin Dashboard
│ ├── band/ # Band Member Portal
│ └── customers/ # Customer Portal
├── docker/ # Docker configs
├── docs/ # Documentation
├── resources/ # Vuexy template source (reference)
├── .cursor/rules # Cursor AI instructions
└── Makefile # Development commands
```
## Frontend Apps (Vuexy v10.11.1)
All frontend apps are built with **Vue 3 + TypeScript** using the [Vuexy Admin Template](https://pixinvent.com/vuexy-vuejs-admin-dashboard-template/).
| App | Template | Description |
|-----|----------|-------------|
| **Admin** | TypeScript Full Version | Complete admin dashboard with all Vuexy features |
| **Band Portal** | TypeScript Starter Kit | Lightweight portal for band members |
| **Customer Portal** | TypeScript Starter Kit | Lightweight portal for customers |
**Template source:** `resources/vuexy-admin-v10.11.1/vue-version/typescript-version/`
> **Note:** The `@core/` and `@layouts/` folders should not be modified directly. Customize through `themeConfig.ts` and override styles in `assets/styles/`.
## URLs
| App | Development | Production |
|-----|-------------|------------|
| API | http://localhost:8000/api/v1 | https://api.bandmanagement.nl |
| Admin | http://localhost:5173 | https://admin.bandmanagement.nl |
| Band Portal | http://localhost:5174 | https://band.bandmanagement.nl |
| Customer Portal | http://localhost:5175 | https://customers.bandmanagement.nl |
## Development Commands
```bash
make services # Start MySQL, Redis, Mailpit
make services-stop # Stop Docker services
make api # Start Laravel API
make admin # Start Admin SPA
make band # Start Band Portal
make customers # Start Customer Portal
```

18
api/.editorconfig Normal file
View File

@@ -0,0 +1,18 @@
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.yaml]
indent_size = 4

57
api/.env.example Normal file
View File

@@ -0,0 +1,57 @@
APP_NAME="Band Management"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=band_management
DB_USERNAME=band_management
DB_PASSWORD=secret
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=redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="noreply@bandmanagement.nl"
MAIL_FROM_NAME="${APP_NAME}"
# CORS - Frontend SPAs
FRONTEND_URL=http://localhost:5173
SANCTUM_STATEFUL_DOMAINS=localhost:5173,localhost:5174,localhost:5175
VITE_APP_NAME="${APP_NAME}"

11
api/.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
* 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

24
api/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

59
api/README.md Normal file
View File

@@ -0,0 +1,59 @@
<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. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts 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.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## 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).

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum EventStatus: string
{
case Draft = 'draft';
case Pending = 'pending';
case Confirmed = 'confirmed';
case Completed = 'completed';
case Cancelled = 'cancelled';
public function label(): string
{
return match ($this) {
self::Draft => 'Draft',
self::Pending => 'Pending Confirmation',
self::Confirmed => 'Confirmed',
self::Completed => 'Completed',
self::Cancelled => 'Cancelled',
};
}
public function color(): string
{
return match ($this) {
self::Draft => 'secondary',
self::Pending => 'warning',
self::Confirmed => 'success',
self::Completed => 'info',
self::Cancelled => 'error',
};
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum EventVisibility: string
{
case Private = 'private';
case Members = 'members';
case Public = 'public';
public function label(): string
{
return match ($this) {
self::Private => 'Private',
self::Members => 'Members Only',
self::Public => 'Public',
};
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum RsvpStatus: string
{
case Pending = 'pending';
case Available = 'available';
case Unavailable = 'unavailable';
case Tentative = 'tentative';
public function label(): string
{
return match ($this) {
self::Pending => 'Pending',
self::Available => 'Available',
self::Unavailable => 'Unavailable',
self::Tentative => 'Tentative',
};
}
public function color(): string
{
return match ($this) {
self::Pending => 'secondary',
self::Available => 'success',
self::Unavailable => 'error',
self::Tentative => 'warning',
};
}
}

View File

@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\LoginRequest;
use App\Http\Requests\Api\V1\RegisterRequest;
use App\Http\Resources\Api\V1\UserResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
final class AuthController extends Controller
{
public function login(LoginRequest $request): JsonResponse
{
$credentials = $request->only('email', 'password');
if (!Auth::attempt($credentials)) {
return $this->unauthorized('Invalid credentials');
}
$user = Auth::user();
if (!$user->isActive()) {
Auth::logout();
return $this->forbidden('Your account is inactive');
}
$token = $user->createToken('auth-token')->plainTextToken;
return $this->success([
'user' => new UserResource($user),
'token' => $token,
], 'Login successful');
}
public function register(RegisterRequest $request): JsonResponse
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'type' => 'member',
'role' => 'member',
'status' => 'active',
]);
$token = $user->createToken('auth-token')->plainTextToken;
return $this->created([
'user' => new UserResource($user),
'token' => $token,
], 'Registration successful');
}
public function user(Request $request): JsonResponse
{
return $this->success(
new UserResource($request->user())
);
}
public function logout(Request $request): JsonResponse
{
$request->user()->currentAccessToken()->delete();
return $this->success(null, 'Logged out successfully');
}
}

View File

@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\RsvpStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\InviteToEventRequest;
use App\Http\Requests\Api\V1\RsvpEventRequest;
use App\Http\Requests\Api\V1\StoreEventRequest;
use App\Http\Requests\Api\V1\UpdateEventRequest;
use App\Http\Resources\Api\V1\EventCollection;
use App\Http\Resources\Api\V1\EventInvitationResource;
use App\Http\Resources\Api\V1\EventResource;
use App\Models\Event;
use App\Models\EventInvitation;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
final class EventController extends Controller
{
/**
* Display a listing of events.
*/
public function index(): EventCollection
{
Gate::authorize('viewAny', Event::class);
$events = Event::query()
->with(['location', 'customer'])
->latest('event_date')
->paginate();
return new EventCollection($events);
}
/**
* Store a newly created event.
*/
public function store(StoreEventRequest $request): JsonResponse
{
Gate::authorize('create', Event::class);
$data = $request->validated();
$data['created_by'] = auth()->id();
$data['currency'] = $data['currency'] ?? 'EUR';
$event = Event::create($data);
return $this->created(
new EventResource($event->load(['location', 'customer'])),
'Event created successfully'
);
}
/**
* Display the specified event.
*/
public function show(Event $event): EventResource
{
Gate::authorize('view', $event);
return new EventResource(
$event->load(['location', 'customer', 'setlist.items.musicNumber', 'invitations.user', 'creator'])
);
}
/**
* Update the specified event.
*/
public function update(UpdateEventRequest $request, Event $event): JsonResponse
{
Gate::authorize('update', $event);
$event->update($request->validated());
return $this->success(
new EventResource($event->load(['location', 'customer'])),
'Event updated successfully'
);
}
/**
* Remove the specified event.
*/
public function destroy(Event $event): JsonResponse
{
Gate::authorize('delete', $event);
$event->delete();
return $this->success(null, 'Event deleted successfully');
}
/**
* Invite members to an event.
*/
public function invite(InviteToEventRequest $request, Event $event): JsonResponse
{
Gate::authorize('invite', $event);
$userIds = $request->validated()['user_ids'];
$invitedCount = 0;
foreach ($userIds as $userId) {
// Skip if already invited
if ($event->invitations()->where('user_id', $userId)->exists()) {
continue;
}
$event->invitations()->create([
'user_id' => $userId,
'rsvp_status' => RsvpStatus::Pending,
'invited_at' => now(),
]);
$invitedCount++;
}
return $this->success(
EventInvitationResource::collection(
$event->invitations()->with('user')->get()
),
"{$invitedCount} member(s) invited successfully"
);
}
/**
* Respond to an event invitation (RSVP).
*/
public function rsvp(RsvpEventRequest $request, Event $event): JsonResponse
{
Gate::authorize('rsvp', $event);
$invitation = EventInvitation::where('event_id', $event->id)
->where('user_id', auth()->id())
->firstOrFail();
$data = $request->validated();
$invitation->update([
'rsvp_status' => $data['status'],
'rsvp_note' => $data['note'] ?? null,
'rsvp_responded_at' => now(),
]);
return $this->success(
new EventInvitationResource($invitation->load('user')),
'RSVP updated successfully'
);
}
}

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
abstract class Controller
{
protected function success(mixed $data = null, string $message = 'Success', int $code = 200): JsonResponse
{
return response()->json([
'success' => true,
'data' => $data,
'message' => $message,
], $code);
}
protected function created(mixed $data = null, string $message = 'Created'): JsonResponse
{
return $this->success($data, $message, 201);
}
protected function error(string $message, int $code = 400, array $errors = []): JsonResponse
{
$response = [
'success' => false,
'message' => $message,
];
if (!empty($errors)) {
$response['errors'] = $errors;
}
return response()->json($response, $code);
}
protected function unauthorized(string $message = 'Unauthorized'): JsonResponse
{
return $this->error($message, 401);
}
protected function forbidden(string $message = 'Forbidden'): JsonResponse
{
return $this->error($message, 403);
}
protected function notFound(string $message = 'Resource not found'): JsonResponse
{
return $this->error($message, 404);
}
}

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class InviteToEventRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'user_ids' => ['required', 'array', 'min:1'],
'user_ids.*' => ['required', 'ulid', 'exists:users,id'],
];
}
public function messages(): array
{
return [
'user_ids.required' => 'Please select at least one member to invite.',
'user_ids.*.exists' => 'One or more selected members do not exist.',
];
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class LoginRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string', 'min:8'],
];
}
public function messages(): array
{
return [
'email.required' => 'Email is required',
'email.email' => 'Please enter a valid email address',
'password.required' => 'Password is required',
'password.min' => 'Password must be at least 8 characters',
];
}
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
final class RegisterRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
'password' => ['required', 'string', 'confirmed', Password::defaults()],
];
}
public function messages(): array
{
return [
'name.required' => 'Name is required',
'email.required' => 'Email is required',
'email.email' => 'Please enter a valid email address',
'email.unique' => 'This email is already registered',
'password.required' => 'Password is required',
'password.confirmed' => 'Password confirmation does not match',
];
}
}

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Enums\RsvpStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class RsvpEventRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'status' => ['required', Rule::enum(RsvpStatus::class)],
'note' => ['nullable', 'string', 'max:1000'],
];
}
public function messages(): array
{
return [
'status.required' => 'Please select your availability status.',
];
}
}

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class StoreEventRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:5000'],
'location_id' => ['nullable', 'ulid', 'exists:locations,id'],
'customer_id' => ['nullable', 'ulid', 'exists:customers,id'],
'setlist_id' => ['nullable', 'ulid', 'exists:setlists,id'],
'event_date' => ['required', 'date', 'after_or_equal:today'],
'start_time' => ['required', 'date_format:H:i'],
'end_time' => ['nullable', 'date_format:H:i', 'after:start_time'],
'load_in_time' => ['nullable', 'date_format:H:i'],
'soundcheck_time' => ['nullable', 'date_format:H:i'],
'fee' => ['nullable', 'numeric', 'min:0', 'max:999999.99'],
'currency' => ['sometimes', 'string', 'size:3'],
'status' => ['sometimes', Rule::enum(EventStatus::class)],
'visibility' => ['sometimes', Rule::enum(EventVisibility::class)],
'rsvp_deadline' => ['nullable', 'date', 'before:event_date'],
'notes' => ['nullable', 'string', 'max:5000'],
'internal_notes' => ['nullable', 'string', 'max:5000'],
'is_public_setlist' => ['sometimes', 'boolean'],
];
}
public function messages(): array
{
return [
'event_date.after_or_equal' => 'The event date must be today or a future date.',
'end_time.after' => 'The end time must be after the start time.',
'rsvp_deadline.before' => 'The RSVP deadline must be before the event date.',
];
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class UpdateEventRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'title' => ['sometimes', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:5000'],
'location_id' => ['nullable', 'ulid', 'exists:locations,id'],
'customer_id' => ['nullable', 'ulid', 'exists:customers,id'],
'setlist_id' => ['nullable', 'ulid', 'exists:setlists,id'],
'event_date' => ['sometimes', 'date'],
'start_time' => ['sometimes', 'date_format:H:i'],
'end_time' => ['nullable', 'date_format:H:i'],
'load_in_time' => ['nullable', 'date_format:H:i'],
'soundcheck_time' => ['nullable', 'date_format:H:i'],
'fee' => ['nullable', 'numeric', 'min:0', 'max:999999.99'],
'currency' => ['sometimes', 'string', 'size:3'],
'status' => ['sometimes', Rule::enum(EventStatus::class)],
'visibility' => ['sometimes', Rule::enum(EventVisibility::class)],
'rsvp_deadline' => ['nullable', 'date'],
'notes' => ['nullable', 'string', 'max:5000'],
'internal_notes' => ['nullable', 'string', 'max:5000'],
'is_public_setlist' => ['sometimes', 'boolean'],
];
}
public function messages(): array
{
return [
'end_time.after' => 'The end time must be after the start time.',
];
}
}

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class CustomerResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'company_name' => $this->company_name,
'type' => $this->type,
'email' => $this->email,
'phone' => $this->phone,
'address' => $this->address,
'city' => $this->city,
'postal_code' => $this->postal_code,
'country' => $this->country,
'notes' => $this->notes,
'is_portal_enabled' => $this->is_portal_enabled,
'display_name' => $this->displayName(),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
final class EventCollection extends ResourceCollection
{
public $collects = EventResource::class;
public function toArray(Request $request): array
{
return [
'data' => $this->collection,
];
}
public function with(Request $request): array
{
return [
'success' => true,
'meta' => [
'pagination' => [
'current_page' => $this->currentPage(),
'per_page' => $this->perPage(),
'total' => $this->total(),
'last_page' => $this->lastPage(),
'from' => $this->firstItem(),
'to' => $this->lastItem(),
],
],
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class EventInvitationResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'event_id' => $this->event_id,
'user_id' => $this->user_id,
'rsvp_status' => $this->rsvp_status->value,
'rsvp_status_label' => $this->rsvp_status->label(),
'rsvp_status_color' => $this->rsvp_status->color(),
'rsvp_note' => $this->rsvp_note,
'rsvp_responded_at' => $this->rsvp_responded_at?->toIso8601String(),
'invited_at' => $this->invited_at?->toIso8601String(),
'user' => new UserResource($this->whenLoaded('user')),
];
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class EventResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'event_date' => $this->event_date->toDateString(),
'start_time' => $this->start_time?->format('H:i'),
'end_time' => $this->end_time?->format('H:i'),
'load_in_time' => $this->load_in_time?->format('H:i'),
'soundcheck_time' => $this->soundcheck_time?->format('H:i'),
'fee' => $this->fee,
'currency' => $this->currency,
'status' => $this->status->value,
'status_label' => $this->status->label(),
'status_color' => $this->status->color(),
'visibility' => $this->visibility->value,
'visibility_label' => $this->visibility->label(),
'rsvp_deadline' => $this->rsvp_deadline?->toIso8601String(),
'notes' => $this->notes,
'internal_notes' => $this->when(
$request->user()?->role === 'admin' || $request->user()?->role === 'booking_agent',
$this->internal_notes
),
'is_public_setlist' => $this->is_public_setlist,
'location' => new LocationResource($this->whenLoaded('location')),
'customer' => new CustomerResource($this->whenLoaded('customer')),
'setlist' => new SetlistResource($this->whenLoaded('setlist')),
'invitations' => EventInvitationResource::collection($this->whenLoaded('invitations')),
'creator' => new UserResource($this->whenLoaded('creator')),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class LocationResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'address' => $this->address,
'city' => $this->city,
'postal_code' => $this->postal_code,
'country' => $this->country,
'latitude' => $this->latitude,
'longitude' => $this->longitude,
'capacity' => $this->capacity,
'contact_name' => $this->contact_name,
'contact_email' => $this->contact_email,
'contact_phone' => $this->contact_phone,
'notes' => $this->notes,
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class MusicAttachmentResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'music_number_id' => $this->music_number_id,
'file_name' => $this->file_name,
'original_name' => $this->original_name,
'file_type' => $this->file_type,
'file_size' => $this->file_size,
'mime_type' => $this->mime_type,
'created_at' => $this->created_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class MusicNumberResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'artist' => $this->artist,
'genre' => $this->genre,
'duration_seconds' => $this->duration_seconds,
'key' => $this->key,
'tempo_bpm' => $this->tempo_bpm,
'time_signature' => $this->time_signature,
'lyrics' => $this->lyrics,
'notes' => $this->notes,
'tags' => $this->tags,
'play_count' => $this->play_count,
'is_active' => $this->is_active,
'attachments' => MusicAttachmentResource::collection($this->whenLoaded('attachments')),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class SetlistItemResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'setlist_id' => $this->setlist_id,
'music_number_id' => $this->music_number_id,
'position' => $this->position,
'set_number' => $this->set_number,
'is_break' => $this->is_break,
'break_duration_seconds' => $this->break_duration_seconds,
'notes' => $this->notes,
'music_number' => new MusicNumberResource($this->whenLoaded('musicNumber')),
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class SetlistResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'total_duration_seconds' => $this->total_duration_seconds,
'formatted_duration' => $this->formattedDuration(),
'is_template' => $this->is_template,
'is_archived' => $this->is_archived,
'items' => SetlistItemResource::collection($this->whenLoaded('items')),
'creator' => new UserResource($this->whenLoaded('creator')),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
'bio' => $this->bio,
'instruments' => $this->instruments,
'avatar' => $this->avatar_path ? asset('storage/' . $this->avatar_path) : null,
'type' => $this->type,
'role' => $this->role,
'status' => $this->status,
'email_verified_at' => $this->email_verified_at?->toIso8601String(),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Customer extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'name',
'company_name',
'type',
'email',
'phone',
'address',
'city',
'postal_code',
'country',
'notes',
'is_portal_enabled',
'user_id',
];
protected function casts(): array
{
return [
'is_portal_enabled' => 'boolean',
];
}
// Relationships
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function events(): HasMany
{
return $this->hasMany(Event::class);
}
// Helper methods
public function isCompany(): bool
{
return $this->type === 'company';
}
public function displayName(): string
{
return $this->company_name ?? $this->name;
}
}

132
api/app/Models/Event.php Normal file
View File

@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Event extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'title',
'description',
'location_id',
'customer_id',
'setlist_id',
'event_date',
'start_time',
'end_time',
'load_in_time',
'soundcheck_time',
'fee',
'currency',
'status',
'visibility',
'rsvp_deadline',
'notes',
'internal_notes',
'is_public_setlist',
'created_by',
];
protected function casts(): array
{
return [
'event_date' => 'date',
'start_time' => 'datetime:H:i',
'end_time' => 'datetime:H:i',
'load_in_time' => 'datetime:H:i',
'soundcheck_time' => 'datetime:H:i',
'fee' => 'decimal:2',
'status' => EventStatus::class,
'visibility' => EventVisibility::class,
'rsvp_deadline' => 'datetime',
'is_public_setlist' => 'boolean',
];
}
// Relationships
public function location(): BelongsTo
{
return $this->belongsTo(Location::class);
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function setlist(): BelongsTo
{
return $this->belongsTo(Setlist::class);
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function invitations(): HasMany
{
return $this->hasMany(EventInvitation::class);
}
// Scopes
public function scopeUpcoming(Builder $query): Builder
{
return $query->where('event_date', '>=', now()->toDateString())
->orderBy('event_date');
}
public function scopePast(Builder $query): Builder
{
return $query->where('event_date', '<', now()->toDateString())
->orderByDesc('event_date');
}
public function scopeConfirmed(Builder $query): Builder
{
return $query->where('status', EventStatus::Confirmed);
}
public function scopeForUser(Builder $query, User $user): Builder
{
return $query->whereHas('invitations', fn (Builder $q) => $q->where('user_id', $user->id));
}
// Helper methods
public function isUpcoming(): bool
{
return $this->event_date->isFuture() || $this->event_date->isToday();
}
public function isPast(): bool
{
return $this->event_date->isPast() && !$this->event_date->isToday();
}
public function isConfirmed(): bool
{
return $this->status === EventStatus::Confirmed;
}
public function isCancelled(): bool
{
return $this->status === EventStatus::Cancelled;
}
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\RsvpStatus;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class EventInvitation extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'event_id',
'user_id',
'rsvp_status',
'rsvp_note',
'rsvp_responded_at',
'invited_at',
];
protected function casts(): array
{
return [
'rsvp_status' => RsvpStatus::class,
'rsvp_responded_at' => 'datetime',
'invited_at' => 'datetime',
];
}
// Relationships
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
// Helper methods
public function isPending(): bool
{
return $this->rsvp_status === RsvpStatus::Pending;
}
public function isAvailable(): bool
{
return $this->rsvp_status === RsvpStatus::Available;
}
public function hasResponded(): bool
{
return $this->rsvp_responded_at !== null;
}
}

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Location extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'name',
'address',
'city',
'postal_code',
'country',
'latitude',
'longitude',
'capacity',
'contact_name',
'contact_email',
'contact_phone',
'notes',
];
protected function casts(): array
{
return [
'latitude' => 'decimal:7',
'longitude' => 'decimal:7',
'capacity' => 'integer',
];
}
// Relationships
public function events(): HasMany
{
return $this->hasMany(Event::class);
}
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class MusicAttachment extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'music_number_id',
'file_name',
'original_name',
'file_path',
'file_type',
'file_size',
'mime_type',
];
protected function casts(): array
{
return [
'file_size' => 'integer',
];
}
// Relationships
public function musicNumber(): BelongsTo
{
return $this->belongsTo(MusicNumber::class);
}
}

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class MusicNumber extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'title',
'artist',
'genre',
'duration_seconds',
'key',
'tempo_bpm',
'time_signature',
'lyrics',
'notes',
'tags',
'play_count',
'is_active',
'created_by',
];
protected function casts(): array
{
return [
'duration_seconds' => 'integer',
'tempo_bpm' => 'integer',
'tags' => 'array',
'play_count' => 'integer',
'is_active' => 'boolean',
];
}
// Relationships
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function attachments(): HasMany
{
return $this->hasMany(MusicAttachment::class);
}
public function setlistItems(): HasMany
{
return $this->hasMany(SetlistItem::class);
}
// Helper methods
public function formattedDuration(): string
{
if (!$this->duration_seconds) {
return '0:00';
}
$minutes = floor($this->duration_seconds / 60);
$seconds = $this->duration_seconds % 60;
return sprintf('%d:%02d', $minutes, $seconds);
}
public function isActive(): bool
{
return $this->is_active;
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Setlist extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'name',
'description',
'total_duration_seconds',
'is_template',
'is_archived',
'created_by',
];
protected function casts(): array
{
return [
'total_duration_seconds' => 'integer',
'is_template' => 'boolean',
'is_archived' => 'boolean',
];
}
// Relationships
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function items(): HasMany
{
return $this->hasMany(SetlistItem::class)->orderBy('position');
}
public function events(): HasMany
{
return $this->hasMany(Event::class);
}
// Helper methods
public function isTemplate(): bool
{
return $this->is_template;
}
public function isArchived(): bool
{
return $this->is_archived;
}
public function formattedDuration(): string
{
if (!$this->total_duration_seconds) {
return '0:00';
}
$minutes = floor($this->total_duration_seconds / 60);
$seconds = $this->total_duration_seconds % 60;
return sprintf('%d:%02d', $minutes, $seconds);
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class SetlistItem extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'setlist_id',
'music_number_id',
'position',
'set_number',
'is_break',
'break_duration_seconds',
'notes',
];
protected function casts(): array
{
return [
'position' => 'integer',
'set_number' => 'integer',
'is_break' => 'boolean',
'break_duration_seconds' => 'integer',
];
}
// Relationships
public function setlist(): BelongsTo
{
return $this->belongsTo(Setlist::class);
}
public function musicNumber(): BelongsTo
{
return $this->belongsTo(MusicNumber::class);
}
// Helper methods
public function isBreak(): bool
{
return $this->is_break;
}
public function formattedBreakDuration(): string
{
if (!$this->is_break || !$this->break_duration_seconds) {
return '';
}
$minutes = floor($this->break_duration_seconds / 60);
$seconds = $this->break_duration_seconds % 60;
return sprintf('%d:%02d', $minutes, $seconds);
}
}

78
api/app/Models/User.php Normal file
View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
final class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasUlids;
use Notifiable;
protected $fillable = [
'name',
'email',
'phone',
'bio',
'instruments',
'avatar_path',
'type',
'role',
'status',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'instruments' => 'array',
];
}
// Helper methods
public function isAdmin(): bool
{
return $this->role === 'admin';
}
public function isBookingAgent(): bool
{
return $this->role === 'booking_agent';
}
public function isMusicManager(): bool
{
return $this->role === 'music_manager';
}
public function isMember(): bool
{
return $this->type === 'member';
}
public function isCustomer(): bool
{
return $this->type === 'customer';
}
public function isActive(): bool
{
return $this->status === 'active';
}
}

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Event;
use App\Models\User;
final class EventPolicy
{
/**
* Determine whether the user can view any events.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the event.
*/
public function view(User $user, Event $event): bool
{
// Admins and booking agents can view all events
if ($this->isAdminOrBookingAgent($user)) {
return true;
}
// Members can view events they're invited to
return $event->invitations()->where('user_id', $user->id)->exists();
}
/**
* Determine whether the user can create events.
*/
public function create(User $user): bool
{
return $this->isAdminOrBookingAgent($user);
}
/**
* Determine whether the user can update the event.
*/
public function update(User $user, Event $event): bool
{
return $this->isAdminOrBookingAgent($user);
}
/**
* Determine whether the user can delete the event.
*/
public function delete(User $user, Event $event): bool
{
return $user->role === 'admin';
}
/**
* Determine whether the user can invite members to the event.
*/
public function invite(User $user, Event $event): bool
{
return $this->isAdminOrBookingAgent($user);
}
/**
* Determine whether the user can RSVP to the event.
*/
public function rsvp(User $user, Event $event): bool
{
// User must be invited to RSVP
return $event->invitations()->where('user_id', $user->id)->exists();
}
/**
* Check if the user is an admin or booking agent.
*/
private function isAdminOrBookingAgent(User $user): bool
{
return in_array($user->role, ['admin', 'booking_agent'], true);
}
}

View File

@@ -0,0 +1,24 @@
<?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
{
//
}
}

18
api/artisan Executable file
View File

@@ -0,0 +1,18 @@
#!/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);

31
api/bootstrap/app.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix: 'api/v1',
)
->withMiddleware(function (Middleware $middleware): void {
// API uses token-based auth, no CSRF needed
})
->withExceptions(function (Exceptions $exceptions): void {
// Return JSON for all API exceptions
$exceptions->render(function (NotFoundHttpException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'success' => false,
'message' => 'Resource not found',
], 404);
}
});
})->create();

2
api/bootstrap/cache/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,5 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

87
api/composer.json Normal file
View File

@@ -0,0 +1,87 @@
{
"$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.2",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.3"
},
"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",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@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
}

8436
api/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
api/config/app.php Normal file
View File

@@ -0,0 +1,126 @@
<?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'),
],
];

115
api/config/auth.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
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', App\Models\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),
];

117
api/config/cache.php Normal file
View File

@@ -0,0 +1,117 @@
<?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", "octane",
| "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'),
],
'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-'),
];

40
api/config/cors.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => [
'http://localhost:5173', // Admin SPA
'http://localhost:5174', // Band SPA
'http://localhost:5175', // Customer SPA
],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];

183
api/config/database.php Normal file
View File

@@ -0,0 +1,183 @@
<?php
use Illuminate\Support\Str;
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([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::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([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::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' => '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),
],
],
];

View File

@@ -0,0 +1,80 @@
<?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' => env('APP_URL').'/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'),
],
];

132
api/config/logging.php Normal file
View File

@@ -0,0 +1,132 @@
<?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', 'Laravel Log'),
'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'),
],
],
];

118
api/config/mail.php Normal file
View File

@@ -0,0 +1,118 @@
<?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', 'Example'),
],
];

129
api/config/queue.php Normal file
View File

@@ -0,0 +1,129 @@
<?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',
],
];

86
api/config/sanctum.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

38
api/config/services.php Normal file
View File

@@ -0,0 +1,38 @@
<?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'),
],
],
];

217
api/config/session.php Normal file
View File

@@ -0,0 +1,217 @@
<?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),
];

1
api/database/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.sqlite*

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Models\Customer;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Customer>
*/
final class CustomerFactory extends Factory
{
protected $model = Customer::class;
public function definition(): array
{
$type = fake()->randomElement(['individual', 'company']);
return [
'name' => fake()->name(),
'company_name' => $type === 'company' ? fake()->company() : null,
'type' => $type,
'email' => fake()->optional()->safeEmail(),
'phone' => fake()->optional()->phoneNumber(),
'address' => fake()->optional()->streetAddress(),
'city' => fake()->optional()->city(),
'postal_code' => fake()->optional()->postcode(),
'country' => 'NL',
'notes' => fake()->optional()->paragraph(),
'is_portal_enabled' => fake()->boolean(20),
];
}
public function individual(): static
{
return $this->state(fn () => [
'type' => 'individual',
'company_name' => null,
]);
}
public function company(): static
{
return $this->state(fn () => [
'type' => 'company',
'company_name' => fake()->company(),
]);
}
public function withPortal(): static
{
return $this->state(fn () => ['is_portal_enabled' => true]);
}
}

View File

@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\EventStatus;
use App\Enums\EventVisibility;
use App\Models\Customer;
use App\Models\Event;
use App\Models\Location;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Event>
*/
final class EventFactory extends Factory
{
protected $model = Event::class;
public function definition(): array
{
$startTime = fake()->time('H:i');
$endTime = fake()->optional()->time('H:i');
return [
'title' => fake()->sentence(3),
'description' => fake()->optional()->paragraph(),
'event_date' => fake()->dateTimeBetween('+1 week', '+6 months'),
'start_time' => $startTime,
'end_time' => $endTime,
'fee' => fake()->optional()->randomFloat(2, 100, 5000),
'currency' => 'EUR',
'status' => fake()->randomElement(EventStatus::cases()),
'visibility' => EventVisibility::Members,
'notes' => fake()->optional()->paragraph(),
'created_by' => User::factory(),
];
}
public function draft(): static
{
return $this->state(fn () => ['status' => EventStatus::Draft]);
}
public function pending(): static
{
return $this->state(fn () => ['status' => EventStatus::Pending]);
}
public function confirmed(): static
{
return $this->state(fn () => ['status' => EventStatus::Confirmed]);
}
public function completed(): static
{
return $this->state(fn () => ['status' => EventStatus::Completed]);
}
public function cancelled(): static
{
return $this->state(fn () => ['status' => EventStatus::Cancelled]);
}
public function withLocation(): static
{
return $this->state(fn () => ['location_id' => Location::factory()]);
}
public function withCustomer(): static
{
return $this->state(fn () => ['customer_id' => Customer::factory()]);
}
public function upcoming(): static
{
return $this->state(fn () => [
'event_date' => fake()->dateTimeBetween('+1 day', '+1 month'),
'status' => EventStatus::Confirmed,
]);
}
public function past(): static
{
return $this->state(fn () => [
'event_date' => fake()->dateTimeBetween('-6 months', '-1 day'),
'status' => EventStatus::Completed,
]);
}
public function privateEvent(): static
{
return $this->state(fn () => ['visibility' => EventVisibility::Private]);
}
public function publicEvent(): static
{
return $this->state(fn () => ['visibility' => EventVisibility::Public]);
}
}

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Enums\RsvpStatus;
use App\Models\Event;
use App\Models\EventInvitation;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<EventInvitation>
*/
final class EventInvitationFactory extends Factory
{
protected $model = EventInvitation::class;
public function definition(): array
{
return [
'event_id' => Event::factory(),
'user_id' => User::factory(),
'rsvp_status' => RsvpStatus::Pending,
'rsvp_note' => null,
'rsvp_responded_at' => null,
'invited_at' => now(),
];
}
public function pending(): static
{
return $this->state(fn () => [
'rsvp_status' => RsvpStatus::Pending,
'rsvp_responded_at' => null,
]);
}
public function available(): static
{
return $this->state(fn () => [
'rsvp_status' => RsvpStatus::Available,
'rsvp_responded_at' => now(),
]);
}
public function unavailable(): static
{
return $this->state(fn () => [
'rsvp_status' => RsvpStatus::Unavailable,
'rsvp_responded_at' => now(),
]);
}
public function tentative(): static
{
return $this->state(fn () => [
'rsvp_status' => RsvpStatus::Tentative,
'rsvp_responded_at' => now(),
'rsvp_note' => fake()->sentence(),
]);
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Models\Location;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Location>
*/
final class LocationFactory extends Factory
{
protected $model = Location::class;
public function definition(): array
{
return [
'name' => fake()->company() . ' ' . fake()->randomElement(['Theater', 'Hall', 'Arena', 'Club', 'Venue']),
'address' => fake()->streetAddress(),
'city' => fake()->city(),
'postal_code' => fake()->postcode(),
'country' => 'NL',
'latitude' => fake()->optional()->latitude(),
'longitude' => fake()->optional()->longitude(),
'capacity' => fake()->optional()->numberBetween(50, 2000),
'contact_name' => fake()->optional()->name(),
'contact_email' => fake()->optional()->safeEmail(),
'contact_phone' => fake()->optional()->phoneNumber(),
'notes' => fake()->optional()->paragraph(),
];
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\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,
]);
}
}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
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->ulid('id')->primary();
$table->string('name');
$table->string('email')->unique();
$table->string('phone', 20)->nullable();
$table->text('bio')->nullable();
$table->json('instruments')->nullable();
$table->string('avatar_path')->nullable();
$table->enum('type', ['member', 'customer'])->default('member');
$table->enum('role', ['admin', 'booking_agent', 'music_manager', 'member'])->nullable();
$table->enum('status', ['active', 'inactive'])->default('active');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->index(['type', 'status']);
});
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->foreignUlid('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');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
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');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
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();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
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('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->ulidMorphs('tokenable'); // Use ULID morphs for ULID primary keys
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
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('customers', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('name');
$table->string('company_name')->nullable();
$table->enum('type', ['individual', 'company'])->default('individual');
$table->string('email')->nullable();
$table->string('phone', 20)->nullable();
$table->text('address')->nullable();
$table->string('city')->nullable();
$table->string('postal_code', 20)->nullable();
$table->string('country', 2)->default('NL');
$table->text('notes')->nullable();
$table->boolean('is_portal_enabled')->default(false);
$table->foreignUlid('user_id')->nullable()->constrained()->nullOnDelete();
$table->timestamps();
$table->index(['type', 'city']);
});
}
public function down(): void
{
Schema::dropIfExists('customers');
}
};

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
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('locations', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('name');
$table->text('address')->nullable();
$table->string('city');
$table->string('postal_code', 20)->nullable();
$table->string('country', 2)->default('NL');
$table->decimal('latitude', 10, 7)->nullable();
$table->decimal('longitude', 10, 7)->nullable();
$table->unsignedInteger('capacity')->nullable();
$table->string('contact_name')->nullable();
$table->string('contact_email')->nullable();
$table->string('contact_phone', 20)->nullable();
$table->text('notes')->nullable();
$table->timestamps();
$table->index('city');
});
}
public function down(): void
{
Schema::dropIfExists('locations');
}
};

View File

@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
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('setlists', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('name');
$table->text('description')->nullable();
$table->unsignedInteger('total_duration_seconds')->nullable();
$table->boolean('is_template')->default(false);
$table->boolean('is_archived')->default(false);
$table->foreignUlid('created_by')->constrained('users');
$table->timestamps();
$table->index(['is_template', 'is_archived']);
});
}
public function down(): void
{
Schema::dropIfExists('setlists');
}
};

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
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('events', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('title');
$table->text('description')->nullable();
$table->foreignUlid('location_id')->nullable()->constrained()->nullOnDelete();
$table->foreignUlid('customer_id')->nullable()->constrained()->nullOnDelete();
$table->foreignUlid('setlist_id')->nullable()->constrained()->nullOnDelete();
$table->date('event_date');
$table->time('start_time');
$table->time('end_time')->nullable();
$table->time('load_in_time')->nullable();
$table->time('soundcheck_time')->nullable();
$table->decimal('fee', 10, 2)->nullable();
$table->string('currency', 3)->default('EUR');
$table->enum('status', ['draft', 'pending', 'confirmed', 'completed', 'cancelled'])->default('draft');
$table->enum('visibility', ['private', 'members', 'public'])->default('members');
$table->dateTime('rsvp_deadline')->nullable();
$table->text('notes')->nullable();
$table->text('internal_notes')->nullable();
$table->boolean('is_public_setlist')->default(false);
$table->foreignUlid('created_by')->constrained('users');
$table->timestamps();
$table->index(['event_date', 'status']);
$table->index('status');
});
}
public function down(): void
{
Schema::dropIfExists('events');
}
};

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
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('event_invitations', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->foreignUlid('event_id')->constrained()->cascadeOnDelete();
$table->foreignUlid('user_id')->constrained()->cascadeOnDelete();
$table->enum('rsvp_status', ['pending', 'available', 'unavailable', 'tentative'])->default('pending');
$table->text('rsvp_note')->nullable();
$table->timestamp('rsvp_responded_at')->nullable();
$table->timestamp('invited_at');
$table->timestamps();
$table->unique(['event_id', 'user_id']);
$table->index(['user_id', 'rsvp_status']);
});
}
public function down(): void
{
Schema::dropIfExists('event_invitations');
}
};

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
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('music_numbers', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('title');
$table->string('artist')->nullable();
$table->string('genre')->nullable();
$table->unsignedInteger('duration_seconds')->nullable();
$table->string('key', 10)->nullable();
$table->unsignedSmallInteger('tempo_bpm')->nullable();
$table->string('time_signature', 10)->nullable();
$table->text('lyrics')->nullable();
$table->text('notes')->nullable();
$table->json('tags')->nullable();
$table->unsignedInteger('play_count')->default(0);
$table->boolean('is_active')->default(true);
$table->foreignUlid('created_by')->constrained('users');
$table->timestamps();
$table->index(['is_active', 'title']);
$table->index('genre');
});
}
public function down(): void
{
Schema::dropIfExists('music_numbers');
}
};

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
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('music_attachments', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->foreignUlid('music_number_id')->constrained()->cascadeOnDelete();
$table->string('file_name');
$table->string('original_name');
$table->string('file_path');
$table->enum('file_type', ['lyrics', 'chords', 'sheet_music', 'audio', 'other'])->default('other');
$table->unsignedInteger('file_size');
$table->string('mime_type');
$table->timestamps();
$table->index(['music_number_id', 'file_type']);
});
}
public function down(): void
{
Schema::dropIfExists('music_attachments');
}
};

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
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('setlist_items', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->foreignUlid('setlist_id')->constrained()->cascadeOnDelete();
$table->foreignUlid('music_number_id')->nullable()->constrained()->nullOnDelete();
$table->unsignedSmallInteger('position');
$table->unsignedTinyInteger('set_number')->default(1);
$table->boolean('is_break')->default(false);
$table->unsignedSmallInteger('break_duration_seconds')->nullable();
$table->text('notes')->nullable();
$table->timestamps();
$table->index(['setlist_id', 'position']);
$table->index(['setlist_id', 'set_number']);
});
}
public function down(): void
{
Schema::dropIfExists('setlist_items');
}
};

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
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('booking_requests', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->foreignUlid('customer_id')->nullable()->constrained()->nullOnDelete();
$table->string('contact_name');
$table->string('contact_email');
$table->string('contact_phone', 20)->nullable();
$table->string('event_type')->nullable();
$table->date('preferred_date');
$table->date('alternative_date')->nullable();
$table->time('preferred_time')->nullable();
$table->string('location')->nullable();
$table->unsignedInteger('expected_guests')->nullable();
$table->decimal('budget', 10, 2)->nullable();
$table->text('message')->nullable();
$table->enum('status', ['new', 'contacted', 'quoted', 'accepted', 'declined', 'cancelled'])->default('new');
$table->text('internal_notes')->nullable();
$table->foreignUlid('assigned_to')->nullable()->constrained('users')->nullOnDelete();
$table->foreignUlid('converted_event_id')->nullable()->constrained('events')->nullOnDelete();
$table->timestamps();
$table->index(['status', 'preferred_date']);
$table->index('assigned_to');
});
}
public function down(): void
{
Schema::dropIfExists('booking_requests');
}
};

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
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('notifications', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('type');
$table->morphs('notifiable');
$table->json('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
$table->index(['notifiable_type', 'notifiable_id', 'read_at']);
});
}
public function down(): void
{
Schema::dropIfExists('notifications');
}
};

View File

@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
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('activity_logs', function (Blueprint $table) {
$table->ulid('id')->primary();
$table->string('log_name')->nullable();
$table->text('description');
$table->nullableMorphs('subject');
$table->nullableMorphs('causer');
$table->json('properties')->nullable();
$table->string('event')->nullable();
$table->uuid('batch_uuid')->nullable();
$table->timestamps();
$table->index('log_name');
});
}
public function down(): void
{
Schema::dropIfExists('activity_logs');
}
};

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
// Create admin user
User::create([
'name' => 'Admin User',
'email' => 'admin@bandmanagement.nl',
'password' => Hash::make('password'),
'type' => 'member',
'role' => 'admin',
'status' => 'active',
]);
// Create booking agent
User::create([
'name' => 'Booking Agent',
'email' => 'booking@bandmanagement.nl',
'password' => Hash::make('password'),
'type' => 'member',
'role' => 'booking_agent',
'status' => 'active',
]);
// Create music manager
User::create([
'name' => 'Music Manager',
'email' => 'music@bandmanagement.nl',
'password' => Hash::make('password'),
'type' => 'member',
'role' => 'music_manager',
'status' => 'active',
]);
// Create regular member
User::create([
'name' => 'Band Member',
'email' => 'member@bandmanagement.nl',
'password' => Hash::make('password'),
'type' => 'member',
'role' => 'member',
'status' => 'active',
]);
}
}

35
api/phpunit.xml Normal file
View File

@@ -0,0 +1,35 @@
<?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="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>

25
api/public/.htaccess Normal file
View File

@@ -0,0 +1,25 @@
<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>

0
api/public/favicon.ico Normal file
View File

20
api/public/index.php Normal file
View File

@@ -0,0 +1,20 @@
<?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());

2
api/public/robots.txt Normal file
View File

@@ -0,0 +1,2 @@
User-agent: *
Disallow:

11
api/resources/css/app.css Normal file
View File

@@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

1
api/resources/js/app.js Normal file
View File

@@ -0,0 +1 @@
import './bootstrap';

4
api/resources/js/bootstrap.js vendored Normal file
View File

@@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

43
api/routes/api.php Normal file
View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
use App\Http\Controllers\Api\V1\AuthController;
use App\Http\Controllers\Api\V1\EventController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| All routes are automatically prefixed with /api/v1
|
*/
// Health check
Route::get('/', fn () => response()->json([
'success' => true,
'message' => 'Band Management API v1',
'timestamp' => now()->toIso8601String(),
]));
// Public auth routes
Route::prefix('auth')->group(function () {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
});
// Protected routes
Route::middleware('auth:sanctum')->group(function () {
// Auth
Route::prefix('auth')->group(function () {
Route::get('/user', [AuthController::class, 'user']);
Route::post('/logout', [AuthController::class, 'logout']);
});
// Events
Route::apiResource('events', EventController::class);
Route::post('events/{event}/invite', [EventController::class, 'invite'])->name('events.invite');
Route::post('events/{event}/rsvp', [EventController::class, 'rsvp'])->name('events.rsvp');
});

8
api/routes/console.php Normal file
View File

@@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

4
api/storage/app/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

Some files were not shown because too many files have changed in this diff Show More