# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

SignageTV Paragon Restaurant — a Laravel 10 application for restaurant management with TV display scheduling, task/project management, payment processing, DSR (Daily Sales Report) tracking, staff management, and inventory control. Supports both a web admin panel (Blade templates) and a mobile API (Laravel Sanctum).

## Build & Development Commands

```bash
# Install dependencies
composer install
npm install

# Environment setup
cp .env.example .env
php artisan key:generate
php artisan migrate

# Development
php artisan serve          # Start PHP dev server
npm run dev                # Start Vite dev server (HMR)
npm run build              # Production asset build

# Testing
php artisan test           # Run all tests
php ./vendor/bin/phpunit   # Alternative test runner

# Cache management
php artisan optimize:clear # Clear all caches (config, route, view, etc.)

# Scheduled commands (registered in Console/Kernel)
php artisan app:change-time-status
php artisan app:create-scheduled-rank
php artisan app:create-scheduled-tasks
```

## Architecture

### Request Flow
- **Web routes** (`routes/web.php`): Session-based auth via `isAuth` middleware, permission checks via `permission` middleware
- **API routes** (`routes/api.php`): Token auth via `auth:sanctum`, versioned under `/api/v1`
- **TV device auth**: Custom Bearer token system via `unique_code` registration

### Code Organization
- **Actions** (`app/Actions/`): Encapsulated business operations, organized by domain (Admin, Api, InternalManagementAction, User)
- **Services** (`app/Services/`): Domain services — FirebaseService (push notifications), SseService (real-time TV updates), TvScheduleService (media rotation scheduling), plus Indent/MaterialIndent/Purchase services
- **Traits** (`app/Traits/`): `ApiResponseTrait` for API responses, `ResponseTrait` for web responses, `CommonVars` for shared variables
- **Helpers** (`app/Http/Helpers/Helper.php`): Global functions auto-loaded via composer — includes `checkUserRole()`, `checkPermission()`, `CheckStatus()`, `CheckTimeStatus()`
- **Jobs** (`app/Jobs/`): Async operations — activity logging, routine task creation, notification sending (indent, payment, target), DSR logging
- **Resources** (`app/Http/Resources/Api/`): API response transformers organized by entity

### Authorization
- Role-Based Access Control (RBAC) with `PermissionMiddleware`
- Role 1 = Admin (all permissions)
- Use `checkPermission($permission)` and `checkUserRole($role)` helpers

### TV/Display Management System

The TV module is the core of this application — a digital signage system for managing content displayed on TV devices across restaurant branches.

#### Models & Database
- `Tv` — TV device record with `unique_code`, `branch_id`, `tag_id`, `type` (portrait/landscape), `status`, FCM token. Soft deletes.
- `TvMedia` — Media files linked to a TV via `tv_id`. Fields: `media_type` (image/video), `file_path`, `file_name`, `duration` (for images), `display_order`, `status` (active/inactive). Soft deletes.
- `TvTag` — Grouping/categorization for TVs (e.g., "Front Desk", "Outdoor"). Soft deletes.
- `TvTimeSlot` — Named time windows (e.g., Breakfast, Lunch, Dinner) with `start_time`, `end_time`, `display_order`.
- `TvDisplaySchedule` — Links TV + time slot + media for time-based content. Fields: `schedule_type` (standard/happy_hour/special_announcement), `priority`, `is_schedule_active`, optional `valid_from`/`valid_until` date bounds.
- `TvRegistrationRequest` — Pending device registration requests with status (pending/allowed/declined/blocked).

#### Controllers
- `app/Http/Controllers/TV/TvController.php` — Main controller for TV CRUD, media upload (single + bulk), media management (reorder, toggle status, delete, update duration).
- `app/Http/Controllers/TV/TvTagController.php` — CRUD for TV tags.
- `app/Http/Controllers/TV/TvDisplayScheduleController.php` — Schedule CRUD, time-slot-based content assignment.
- `app/Http/Controllers/TV/TvRegistrationRequestController.php` — Allow/decline/block device registration requests.
- `app/Http/Controllers/Api/V1/TvController.php` — API endpoints for TV devices (register, update FCM token, fetch playlist, acknowledge notifications).

#### Services
- `app/Services/TvScheduleService.php` — Resolves what media to play on a TV. `resolveFullSchedule()` returns default media + all active time-slot schedules with priority. `resolvePlaylistForTvNow()` determines current playlist based on time and priority.
- `app/Services/TvNotificationService.php` — Sends OneSignal push notifications to TV devices when media changes (actions: media_added, media_deleted, media_updated, media_reordered).

#### Admin Panel Views
- `resources/views/admin/tv/media.blade.php` — Media management page for a single TV. Includes upload form, drag-to-reorder, image cropping (aspect ratio enforcement), file preview, status toggles. Has JS-based video validation (resolution, aspect ratio).
- `resources/views/admin/tv/bulk-upload.blade.php` — Upload same media to multiple TVs at once. Similar validation and preview as single upload.
- `resources/views/admin/tv/partials/media-list.blade.php` — Partial for rendering the media list (loaded via AJAX).

#### Media Upload Flow
1. Admin uploads via web form (`POST /tv/{tv}/media` or `POST /tv/bulk-upload`)
2. Validation: any image or video/audio MIME type accepted, max 500MB per file
3. Images >1MB are resized to 1920px wide via Intervention Image
4. Files stored in `public/tv/images/` or `public/tv/videos/`
5. `TvMedia` record created with auto-incremented `display_order`
6. OneSignal push notification sent to TV device
7. TV device receives notification, calls `GET /api/v1/tv/medias` to fetch updated playlist

#### TV Device Registration Flow
1. TV device sends `POST /api/v1/tv/register` with `registerId` (unique_code) and device info
2. If TV not found in system: creates `TvRegistrationRequest` with status=pending, returns 202
3. Admin approves via `/tv/registration-requests/{id}/allow`
4. Device re-calls register endpoint, gets Sanctum token
5. Device uses token for authenticated API calls

#### Schedule System
- Admins create display schedules assigning media to TVs for specific time windows
- Schedule types: `standard`, `happy_hour`, `special_announcement`
- Priority-based resolution when schedules overlap (higher priority wins; type weights: happy_hour=3, special_announcement=2, standard=1)
- Optional `valid_from`/`valid_until` for time-limited campaigns
- `is_schedule_active` toggle without deleting

#### Key Web Routes (all under `/tv` prefix)
- TV CRUD: `GET|POST /tv`, `GET /tv/{tv}/edit`, `PUT /tv/{tv}`, `DELETE /tv/{tv}`
- Media: `GET /tv/{tv}/media`, `POST /tv/{tv}/media`, `DELETE /tv/media/{media}`, `PUT /tv/media/{media}/order`, `PUT /tv/media/{media}/toggle-status`, `PUT /tv/media/{media}/duration`, `PUT /tv/{tv}/bulk-media-order`
- Bulk upload: `GET|POST /tv/bulk-upload`
- Tags: `GET|POST /tv/tag`, `PUT|DELETE /tv/tag/{tag}`
- Schedules: `GET|POST /tv/schedule`, `GET /tv/schedule/create`, `PUT /tv/schedule/toggle-active`, `DELETE /tv/schedule`
- Registration: `GET /tv/registration-requests`, `POST /tv/registration-requests/{id}/allow|decline|block`

#### Key API Routes
- `POST /api/v1/tv/register` — Device self-registration (public)
- `PUT /api/v1/tv/fcm-token` — Update FCM token (authenticated)
- `GET /api/v1/tv/medias` — Fetch full schedule payload (authenticated)
- `POST /api/v1/tv/acknowledge-notification` — Acknowledge push notification (authenticated)

### Other Key Modules
- **Task/Project Management**: Assignment, tracking, reviews, KPIs
- **Payment Processing**: Multi-level approval workflow with specialized types (vendor, unloading charges)
- **Inventory**: Stock tracking, material indent system
- **Scheduling**: Duty roster, shift management, work tracking

### Database
- MySQL with 87+ migrations, 120 Eloquent models
- Many models use soft deletes

### External Integrations
- Firebase (push notifications)
- OneSignal (push notifications)
- DomPDF (PDF generation)
- Maatwebsite Excel (import/export)
- Intervention Image (image manipulation)

### CI/CD
- GitLab CI (`.gitlab-ci.yml`) with SAST and secret detection stages

### Postman Collection
- **Always update `postman_collection.json`** in the project root whenever API routes are added, removed, or modified in `routes/api.php`. Keep the collection in sync with the actual API endpoints, including request method, URL, and body fields.
