diff --git a/.agents/skills/infer-conventions/SKILL.md b/.agents/skills/infer-conventions/SKILL.md new file mode 100644 index 0000000..e7fcafc --- /dev/null +++ b/.agents/skills/infer-conventions/SKILL.md @@ -0,0 +1,104 @@ +--- +name: infer-conventions +description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand." +license: MIT +metadata: + author: laravel +--- + +# Infer Conventions + +Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it. + +## Ground Rules (read before you start) + +- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer. +- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record. +- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule. +- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering. +- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped. +- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar. +- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details. + +## Process + +Each step ends on a checkable completion criterion. Do not advance until it holds. + +Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output. + +### Step 0: Orient + +Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2. + +This app has no Livewire/Inertia/Flux packages installed. Treat the frontend group as likely API-only: confirm from `resources/views` before spending time there, and skip the Livewire/Inertia/Flux dimensions. + +Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents. + +### Step 1: Predefined sweep + +Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict: + +- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files. +- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled. +- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention. +- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most). +- Tooling-owned or Already-recorded. Skip per the ground rules. + +Done when: every applicable dimension carries exactly one of those verdicts. + +### Step 2: Open-ended pass + +First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude. + +Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal. + +Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none). + +### Step 3: Confirm + +Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style. + +Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo. + +Done when: every candidate is approved, rejected, or (conflicts) decided. + +### Step 4: Record + +Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand. + +Record this: + +> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models. + +Not this: + +> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models. + +Done when: every approved item has a successful tool response, and any failure is reported with its rule text. + +### Step 5: Summarize + +List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions. + +## Glob mapping + +Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path. + +Examples: + +- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one. +- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer. +- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses. +- Tests: `tests/**`. +- Migrations and database: `database/migrations/**`. +- Truly app-wide (rare, e.g. auth retrieval): `app/**`. + +`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there. + +## Edge cases + +- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4. +- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing. +- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything. +- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface. +- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths. diff --git a/.agents/skills/infer-conventions/references/checklist.md b/.agents/skills/infer-conventions/references/checklist.md new file mode 100644 index 0000000..80cef34 --- /dev/null +++ b/.agents/skills/infer-conventions/references/checklist.md @@ -0,0 +1,137 @@ +# Detection Checklist + +Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`). + +Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence. + +--- + +## A. Validation & HTTP input + +1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`. + - Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`. +2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal. + - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`. +3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties. + - Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`. +4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods. + - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`. + +## B. Controllers & routing + +5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method. + - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes. +6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs. + - Hint: read a few controller methods; `ls app/Actions app/Services`. +7. Route handler style: closures in `routes/*.php` vs controller classes. + - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`. +8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute. + - Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes. +9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`. + - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`. +10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`. + - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files. + +## C. Authorization + +11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`. + - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`. +12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade. + - Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`. + +## D. Eloquent & models + +13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list. + - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`. +14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain. + - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`. +15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`. + - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`. +16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings. + - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models. +17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`). + - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built. +18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes. + - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`. +19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes. + - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`. +20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture. + - Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`. + +## E. Architecture & organization + +21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked. + - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find. +22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere. + - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`. +23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location. + - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps. +24. Decoupling: events + listeners vs direct service calls. + - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`. +25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`). + - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`. +26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules). + - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders. +27. Enums: backed vs pure; case naming; where they live. + - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`. + +## F. Frontend & views + +No Livewire/Inertia/Flux package is installed. This app may be API-only. Confirm from `resources/views` before sweeping, and treat the Livewire/Flux dimensions as not applicable. + +28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA. + - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`. +29. Blade composition: class `` components vs anonymous components (`@props`) vs `@include` partials. + - Hint: `ls app/View/Components`; grep `constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`. + - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`. +34. `down()` methods: real reverse logic vs omitted / one-way migrations. + - Hint: grep `function down` vs the migration count. +35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model. + - Hint: grep `->enum(` in migrations vs string columns cast to enums. +36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`. + - Hint: grep `DB::transaction`, `beginTransaction` in `app/`. +37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save. + - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`. + +## H. Testing + +38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes. + - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`. +39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`. + - Hint: grep those trait names in `tests/`. +40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories. + - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide. +41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery. + - Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`. +42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`. + - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`. + +## I. Responses & API resources + +43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly. + - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers. +44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately. + - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`. +45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority. + - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them. +46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`. + - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views. + +## J. Strings, collections & dates + +47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`. + - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`. +48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`). + - Hint: grep `Str::of(` vs `Str::` vs native string funcs. +49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting. + - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy. + +--- + +Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from. diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.md new file mode 100644 index 0000000..d136d75 --- /dev/null +++ b/.agents/skills/laravel-best-practices/SKILL.md @@ -0,0 +1,59 @@ +--- +name: laravel-best-practices +description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns." +license: MIT +metadata: + author: laravel +--- + +# Laravel Best Practices + +Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`. + +## Consistency First + +Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern. + +Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides. + +## How to Apply + +1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out. +2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files. +3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job. +4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable. +5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them. +6. Re-read the diff against every mapped rule before finishing. + +## Rule Index + +Cross-cutting changes often need more than one rule file. + +| Concern | Read | +| --- | --- | +| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) | +| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) | +| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) | +| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) | +| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) | +| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) | +| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) | +| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) | +| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) | +| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) | +| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) | +| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) | +| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) | +| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) | +| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) | +| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) | +| Environment values and application configuration | [`rules/config.md`](rules/config.md) | +| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) | +| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) | +| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) | + +## Decision Rules + +- Prefer framework features and existing application abstractions over new helpers or dependencies. +- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable. +- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization. diff --git a/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.md new file mode 100644 index 0000000..f12876e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/advanced-queries.md @@ -0,0 +1,106 @@ +# Advanced Query Patterns + +## Use `addSelect()` Subqueries for Single Values from Has-Many + +Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries. + +```php +public function scopeWithLastLoginAt($query): void +{ + $query->addSelect([ + 'last_login_at' => Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->withCasts(['last_login_at' => 'datetime']); +} +``` + +## Create Dynamic Relationships via Subquery FK + +Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection. + +```php +public function lastLogin(): BelongsTo +{ + return $this->belongsTo(Login::class); +} + +public function scopeWithLastLogin($query): void +{ + $query->addSelect([ + 'last_login_id' => Login::select('id') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->with('lastLogin'); +} +``` + +## Use Conditional Aggregates Instead of Multiple Count Queries + +Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values. + +```php +$statuses = Feature::toBase() + ->selectRaw("count(case when status = 'Requested' then 1 end) as requested") + ->selectRaw("count(case when status = 'Planned' then 1 end) as planned") + ->selectRaw("count(case when status = 'Completed' then 1 end) as completed") + ->first(); +``` + +## Use `setRelation()` to Prevent Circular N+1 + +When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries. + +```php +$feature->load('comments.user'); +$feature->comments->each->setRelation('feature', $feature); +``` + +## Prefer `whereIn` + Subquery Over `whereHas` + +`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory. + +Incorrect (correlated EXISTS re-executes per row): + +```php +$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term)); +``` + +Correct (index-friendly subquery, no PHP memory overhead): + +```php +$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id')); +``` + +## Sometimes Two Simple Queries Beat One Complex Query + +Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index. + +## Use Compound Indexes Matching `orderBy` Column Order + +When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index. + +```php +// Migration +$table->index(['last_name', 'first_name']); + +// Query — column order must match the index +User::query()->orderBy('last_name')->orderBy('first_name')->paginate(); +``` + +## Use Correlated Subqueries for Has-Many Ordering + +When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading. + +```php +public function scopeOrderByLastLogin($query): void +{ + $query->orderByDesc(Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1) + ); +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.md new file mode 100644 index 0000000..138d5a4 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/architecture.md @@ -0,0 +1,202 @@ +# Architecture Best Practices + +## Single-Purpose Action Classes + +Extract discrete business operations into invokable Action classes. + +```php +class CreateOrderAction +{ + public function __construct(private InventoryService $inventory) {} + + public function handle(array $data): Order + { + $order = Order::create($data); + $this->inventory->reserve($order); + + return $order; + } +} +``` + +## Use Dependency Injection + +Always use constructor injection. Avoid `app()` or `resolve()` inside classes. + +Incorrect: +```php +class OrderController extends Controller +{ + public function store(StoreOrderRequest $request) + { + $service = app(OrderService::class); + + return $service->create($request->validated()); + } +} +``` + +Correct: +```php +class OrderController extends Controller +{ + public function __construct(private OrderService $service) {} + + public function store(StoreOrderRequest $request) + { + return $this->service->create($request->validated()); + } +} +``` + +## Code to Interfaces + +Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability. + +Incorrect (concrete dependency): +```php +class OrderService +{ + public function __construct(private StripeGateway $gateway) {} +} +``` + +Correct (interface dependency): +```php +interface PaymentGateway +{ + public function charge(int $amount, string $customerId): PaymentResult; +} + +class OrderService +{ + public function __construct(private PaymentGateway $gateway) {} +} +``` + +Bind in a service provider: + +```php +$this->app->bind(PaymentGateway::class, StripeGateway::class); +``` + +## Default Sort by Descending + +When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined. + +Incorrect: +```php +$posts = Post::paginate(); +``` + +Correct: +```php +$posts = Post::latest()->paginate(); +``` + +## Use Atomic Locks for Race Conditions + +Prevent race conditions with `Cache::lock()` or `lockForUpdate()`. + +```php +Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) { + $order->process(); +}); + +// Or at query level +$product = Product::where('id', $id)->lockForUpdate()->first(); +``` + +## Use `mb_*` String Functions + +When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters. + +Incorrect: +```php +strlen('José'); // 5 (bytes, not characters) +strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte +``` + +Correct: +```php +mb_strlen('José'); // 4 (characters) +mb_strtolower('MÜNCHEN'); // 'münchen' + +// Prefer Laravel's Str helpers when available +Str::length('José'); // 4 +Str::lower('MÜNCHEN'); // 'münchen' +``` + +## Use `defer()` for Post-Response Work + +For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead. + +Incorrect (job overhead for trivial work): +```php +dispatch(new LogPageView($page)); +``` + +Correct (runs after response, same process): +```php +defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()])); +``` + +Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work. + +## Use `Context` for Request-Scoped Data + +The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually. + +```php +// In middleware +Context::add('tenant_id', $request->header('X-Tenant-ID')); + +// Anywhere later — controllers, jobs, log context +$tenantId = Context::get('tenant_id'); +``` + +Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`. + +## Use `Concurrency::run()` for Parallel Execution + +Run independent operations in parallel using child processes — no async libraries needed. + +```php +use Illuminate\Support\Facades\Concurrency; + +[$users, $orders] = Concurrency::run([ + fn () => User::count(), + fn () => Order::where('status', 'pending')->count(), +]); +``` + +Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially. + +## Convention Over Configuration + +Follow Laravel conventions. Don't override defaults unnecessarily. + +Incorrect: +```php +class Customer extends Model +{ + protected $table = 'Customer'; + protected $primaryKey = 'customer_id'; + + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); + } +} +``` + +Correct: +```php +class Customer extends Model +{ + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class); + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.md new file mode 100644 index 0000000..5f0b3a1 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/blade-views.md @@ -0,0 +1,36 @@ +# Blade & Views Best Practices + +## Use `$attributes->merge()` in Component Templates + +Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly. + +```blade +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## Use `@pushOnce` for Per-Component Scripts + +If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once. + +## Prefer Blade Components Over `@include` + +`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots. + +## Use View Composers for Shared View Data + +If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it. + +## Use Blade Fragments for Partial Re-Renders (htmx/Turbo) + +A single view can return either the full page or just a fragment, keeping routing clean. + +```php +return view('dashboard', compact('users')) + ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); +``` + +## Use `@aware` for Deeply Nested Component Props + +Avoids re-passing parent props through every level of nested components. diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.md new file mode 100644 index 0000000..67408d6 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/caching.md @@ -0,0 +1,70 @@ +# Caching Best Practices + +## Use `Cache::remember()` Instead of Manual Get/Put + +Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions. + +Incorrect: +```php +$val = Cache::get('stats'); +if (! $val) { + $val = $this->computeStats(); + Cache::put('stats', $val, 60); +} +``` + +Correct: +```php +$val = Cache::remember('stats', 60, fn () => $this->computeStats()); +``` + +## Use `Cache::flexible()` for Stale-While-Revalidate + +On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background. + +Incorrect: `Cache::remember('users', 300, fn () => User::all());` + +Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function. + +## Use `Cache::memo()` to Avoid Redundant Hits Within a Request + +If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory. + +`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5. + +## Use Cache Tags to Invalidate Related Groups + +Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`. + +```php +Cache::tags(['user-1'])->flush(); +``` + +## Use `Cache::add()` for Atomic Conditional Writes + +`add()` only writes if the key does not exist — atomic, no race condition between checking and writing. + +Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }` + +Correct: `Cache::add('lock', true, 10);` + +## Use `once()` for Per-Request Memoization + +`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory. + +```php +public function roles(): Collection +{ + return once(fn () => $this->loadRoles()); +} +``` + +Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching. + +## Configure Failover Cache Stores in Production + +If Redis goes down, the app falls back to a secondary store automatically. + +```php +'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']], +``` diff --git a/.agents/skills/laravel-best-practices/rules/collections.md b/.agents/skills/laravel-best-practices/rules/collections.md new file mode 100644 index 0000000..18e8d9e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/collections.md @@ -0,0 +1,44 @@ +# Collection Best Practices + +## Use Higher-Order Messages for Simple Operations + +Incorrect: +```php +$users->each(function (User $user) { + $user->markAsVip(); +}); +``` + +Correct: `$users->each->markAsVip();` + +Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc. + +## Choose `cursor()` vs. `lazy()` Correctly + +- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk). +- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading. + +Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored. + +Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work. + +## Use `lazyById()` When Updating Records While Iterating + +`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation. + +## Use `toQuery()` for Bulk Operations on Collections + +Avoids manual `whereIn` construction. + +Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);` + +Correct: `$users->toQuery()->update([...]);` + +## Use `#[CollectedBy]` for Custom Collection Classes + +More declarative than overriding `newCollection()`. + +```php +#[CollectedBy(UserCollection::class)] +class User extends Model {} +``` diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.md new file mode 100644 index 0000000..9bea727 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/config.md @@ -0,0 +1,73 @@ +# Configuration Best Practices + +## `env()` Only in Config Files + +Direct `env()` calls may return `null` when config is cached. + +Incorrect: +```php +$key = env('API_KEY'); +``` + +Correct: +```php +// config/services.php +'key' => env('API_KEY'), + +// Application code +$key = config('services.key'); +``` + +## Use Encrypted Env or External Secrets + +Never store production secrets in plain `.env` files in version control. + +Incorrect: +```bash + +# .env committed to repo or shared in Slack + +STRIPE_SECRET=sk_live_abc123 +AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI +``` + +Correct: +```bash +php artisan env:encrypt --env=production --readable +php artisan env:decrypt --env=production +``` + +For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime. + +## Use `App::environment()` for Environment Checks + +Incorrect: +```php +if (env('APP_ENV') === 'production') { +``` + +Correct: +```php +if (app()->isProduction()) { +// or +if (App::environment('production')) { +``` + +## Use Constants and Language Files + +Use class constants instead of hardcoded magic strings for model states, types, and statuses. + +```php +// Incorrect +return $this->type === 'normal'; + +// Correct +return $this->type === self::TYPE_NORMAL; +``` + +If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there. + +```php +// Only when lang files already exist in the project +return back()->with('message', __('app.article_added')); +``` diff --git a/.agents/skills/laravel-best-practices/rules/db-performance.md b/.agents/skills/laravel-best-practices/rules/db-performance.md new file mode 100644 index 0000000..c49ba16 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/db-performance.md @@ -0,0 +1,192 @@ +# Database Performance Best Practices + +## Always Eager Load Relationships + +Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront. + +Incorrect (N+1 — executes 1 + N queries): +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Correct (2 queries total): +```php +$posts = Post::with('author')->get(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Constrain eager loads to select only needed columns (always include the foreign key): + +```php +$users = User::with(['posts' => function ($query) { + $query->select('id', 'user_id', 'title') + ->where('published', true) + ->latest() + ->limit(10); +}])->get(); +``` + +## Prevent Lazy Loading in Development + +Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development. + +```php +public function boot(): void +{ + Model::preventLazyLoading(! app()->isProduction()); +} +``` + +Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded. + +## Select Only Needed Columns + +Avoid `SELECT *` — especially when tables have large text or JSON columns. + +Incorrect: +```php +$posts = Post::with('author')->get(); +``` + +Correct: +```php +$posts = Post::select('id', 'title', 'user_id', 'created_at') + ->with(['author:id,name,avatar']) + ->get(); +``` + +When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match. + +## Chunk Large Datasets + +Never load thousands of records at once. Use chunking for batch processing. + +Incorrect: +```php +$users = User::all(); +foreach ($users as $user) { + $user->notify(new WeeklyDigest); +} +``` + +Correct: +```php +User::where('subscribed', true)->chunk(200, function ($users) { + foreach ($users as $user) { + $user->notify(new WeeklyDigest); + } +}); +``` + +Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change: + +```php +User::where('active', false)->chunkById(200, function ($users) { + $users->each->delete(); +}); +``` + +## Add Database Indexes + +Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses. + +Incorrect: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); +}); +``` + +Correct: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->index()->constrained(); + $table->string('status')->index(); + $table->timestamps(); + $table->index(['status', 'created_at']); +}); +``` + +Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`). + +## Use `withCount()` for Counting Relations + +Never load entire collections just to count them. + +Incorrect: +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->comments->count(); +} +``` + +Correct: +```php +$posts = Post::withCount('comments')->get(); +foreach ($posts as $post) { + echo $post->comments_count; +} +``` + +Conditional counting: + +```php +$posts = Post::withCount([ + 'comments', + 'comments as approved_comments_count' => function ($query) { + $query->where('approved', true); + }, +])->get(); +``` + +## Use `cursor()` for Memory-Efficient Iteration + +For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator. + +Incorrect: +```php +$users = User::where('active', true)->get(); +``` + +Correct: +```php +foreach (User::where('active', true)->cursor() as $user) { + ProcessUser::dispatch($user->id); +} +``` + +Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records. + +## No Queries in Blade Templates + +Never execute queries in Blade templates. Pass data from controllers. + +Incorrect: +```blade +@foreach (User::all() as $user) + {{ $user->profile->name }} +@endforeach +``` + +Correct: +```php +// Controller +$users = User::with('profile')->get(); +return view('users.index', compact('users')); +``` + +```blade +@foreach ($users as $user) + {{ $user->profile->name }} +@endforeach +``` diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.md new file mode 100644 index 0000000..bd2cfca --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/eloquent.md @@ -0,0 +1,150 @@ +# Eloquent Best Practices + +## Use Correct Relationship Types + +Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints. + +```php +public function comments(): HasMany +{ + return $this->hasMany(Comment::class); +} + +public function author(): BelongsTo +{ + return $this->belongsTo(User::class, 'user_id'); +} +``` + +## Use Local Scopes for Reusable Queries + +Extract reusable query constraints into local scopes to avoid duplication. + +Incorrect: +```php +$active = User::where('verified', true)->whereNotNull('activated_at')->get(); +$articles = Article::whereHas('user', function ($q) { + $q->where('verified', true)->whereNotNull('activated_at'); +})->get(); +``` + +Correct: +```php +#[Scope] +protected function active(Builder $query): Builder +{ + return $query->where('verified', true)->whereNotNull('activated_at'); +} + +// Usage +$active = User::active()->get(); +$articles = Article::whereHas('user', fn ($q) => $q->active())->get(); +``` + +## Apply Global Scopes Sparingly + +Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy. + +Incorrect (global scope for a conditional filter): +```php +class PublishedScope implements Scope +{ + public function apply(Builder $builder, Model $model): void + { + $builder->where('published', true); + } +} +// Now admin panels, reports, and background jobs all silently skip drafts +``` + +Correct (local scope you opt into): +```php +#[Scope] +protected function published(Builder $query): Builder +{ + return $query->where('published', true); +} + +Post::published()->paginate(); // Explicit +Post::paginate(); // Admin sees all +``` + +## Define Attribute Casts + +Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion. + +```php +protected function casts(): array +{ + return [ + 'is_active' => 'boolean', + 'metadata' => 'array', + 'total' => 'decimal:2', + ]; +} +``` + +## Cast Date Columns Properly + +Always cast date columns. Use Carbon instances in templates instead of formatting strings manually. + +Incorrect: +```blade +{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }} +``` + +Correct: +```php +protected function casts(): array +{ + return [ + 'ordered_at' => 'datetime', + ]; +} +``` + +```blade +{{ $order->ordered_at->toDateString() }} +{{ $order->ordered_at->format('m-d') }} +``` + +## Use `whereBelongsTo()` for Relationship Queries + +Cleaner than manually specifying foreign keys. + +Incorrect: +```php +Post::where('user_id', $user->id)->get(); +``` + +Correct: +```php +Post::whereBelongsTo($user)->get(); +Post::whereBelongsTo($user, 'author')->get(); +``` + +## Avoid Hardcoded Table Names in Queries + +Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string). + +Incorrect: +```php +DB::table('users')->where('active', true)->get(); + +$query->join('companies', 'companies.id', '=', 'users.company_id'); + +DB::select('SELECT * FROM orders WHERE status = ?', ['pending']); +``` + +Correct — reference the model's table: +```php +DB::table((new User)->getTable())->where('active', true)->get(); + +// Even better — use Eloquent or the query builder instead of raw SQL +User::where('active', true)->get(); +Order::where('status', 'pending')->get(); +``` + +Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable. + +**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration. diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.md new file mode 100644 index 0000000..4b14866 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/error-handling.md @@ -0,0 +1,72 @@ +# Error Handling Best Practices + +## Exception Reporting and Rendering + +There are two valid approaches — choose one and apply it consistently across the project. + +**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find: + +```php +class InvalidOrderException extends Exception +{ + public function report(): void { /* custom reporting */ } + + public function render(Request $request): Response + { + return response()->view('errors.invalid-order', status: 422); + } +} +``` + +**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture: + +```php +->withExceptions(function (Exceptions $exceptions) { + $exceptions->report(function (InvalidOrderException $e) { /* ... */ }); + $exceptions->render(function (InvalidOrderException $e, Request $request) { + return response()->view('errors.invalid-order', status: 422); + }); +}) +``` + +Check the existing codebase and follow whichever pattern is already established. + +## Use `ShouldntReport` for Exceptions That Should Never Log + +More discoverable than listing classes in `dontReport()`. + +```php +class PodcastProcessingException extends Exception implements ShouldntReport {} +``` + +## Throttle High-Volume Exceptions + +A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type. + +## Enable `dontReportDuplicates()` + +Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks. + +## Force JSON Error Rendering for API Routes + +Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes. + +```php +$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { + return $request->is('api/*') || $request->expectsJson(); +}); +``` + +## Add Context to Exception Classes + +Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry. + +```php +class InvalidOrderException extends Exception +{ + public function context(): array + { + return ['order_id' => $this->orderId]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.md new file mode 100644 index 0000000..82e329e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/events-notifications.md @@ -0,0 +1,52 @@ +# Events & Notifications Best Practices + +## Rely on Event Discovery + +Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`. + +## Run `event:cache` in Production Deploy + +Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`. + +## Use `ShouldDispatchAfterCommit` Inside Transactions + +Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet. + +```php +class OrderShipped implements ShouldDispatchAfterCommit {} +``` + +## Always Queue Notifications + +Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response. + +```php +class InvoicePaid extends Notification implements ShouldQueue +{ + use Queueable; +} +``` + +## Use `afterCommit()` on Notifications in Transactions + +Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits. + +```php +$user->notify((new InvoicePaid($invoice))->afterCommit()); +``` + +## Route Notification Channels to Dedicated Queues + +Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues. + +## Use On-Demand Notifications for Non-User Recipients + +Avoid creating dummy models to send notifications to arbitrary addresses. + +```php +Notification::route('mail', 'admin@example.com')->notify(new SystemAlert()); +``` + +## Implement `HasLocalePreference` on Notifiable Models + +Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed. diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.md new file mode 100644 index 0000000..8e2f16e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/http-client.md @@ -0,0 +1,160 @@ +# HTTP Client Best Practices + +## Always Set Explicit Timeouts + +The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast. + +Incorrect: +```php +$response = Http::get('https://api.example.com/users'); +``` + +Correct: +```php +$response = Http::timeout(5) + ->connectTimeout(3) + ->get('https://api.example.com/users'); +``` + +For service-specific clients, define timeouts in a macro: + +```php +Http::macro('github', function () { + return Http::baseUrl('https://api.github.com') + ->timeout(10) + ->connectTimeout(3) + ->withToken(config('services.github.token')); +}); + +$response = Http::github()->get('/repos/laravel/framework'); +``` + +## Use Retry with Backoff for External APIs + +External APIs have transient failures. Use `retry()` with increasing delays. + +Incorrect: +```php +$response = Http::post('https://api.stripe.com/v1/charges', $data); + +if ($response->failed()) { + throw new PaymentFailedException('Charge failed'); +} +``` + +Correct: +```php +$response = Http::retry([100, 500, 1000]) + ->timeout(10) + ->post('https://api.stripe.com/v1/charges', $data); +``` + +Only retry on specific errors: + +```php +$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) { + return $exception instanceof ConnectionException + || ($exception instanceof RequestException && $exception->response->serverError()); +})->post('https://api.example.com/data'); +``` + +## Handle Errors Explicitly + +The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`. + +Incorrect: +```php +$response = Http::get('https://api.example.com/users/1'); +$user = $response->json(); // Could be an error body +``` + +Correct: +```php +$response = Http::timeout(5) + ->get('https://api.example.com/users/1') + ->throw(); + +$user = $response->json(); +``` + +For graceful degradation: + +```php +$response = Http::get('https://api.example.com/users/1'); + +if ($response->successful()) { + return $response->json(); +} + +if ($response->notFound()) { + return null; +} + +$response->throw(); +``` + +## Use Request Pooling for Concurrent Requests + +When making multiple independent API calls, use `Http::pool()` instead of sequential calls. + +Incorrect: +```php +$users = Http::get('https://api.example.com/users')->json(); +$posts = Http::get('https://api.example.com/posts')->json(); +$comments = Http::get('https://api.example.com/comments')->json(); +``` + +Correct: +```php +use Illuminate\Http\Client\Pool; + +$responses = Http::pool(fn (Pool $pool) => [ + $pool->as('users')->get('https://api.example.com/users'), + $pool->as('posts')->get('https://api.example.com/posts'), + $pool->as('comments')->get('https://api.example.com/comments'), +]); + +$users = $responses['users']->json(); +$posts = $responses['posts']->json(); +``` + +## Fake HTTP Calls in Tests + +Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`. + +Incorrect: +```php +it('syncs user from API', function () { + $service = new UserSyncService; + $service->sync(1); // Hits the real API +}); +``` + +Correct: +```php +it('syncs user from API', function () { + Http::preventStrayRequests(); + + Http::fake([ + 'api.example.com/users/1' => Http::response([ + 'name' => 'John Doe', + 'email' => 'john@example.com', + ]), + ]); + + $service = new UserSyncService; + $service->sync(1); + + Http::assertSent(function (Request $request) { + return $request->url() === 'https://api.example.com/users/1'; + }); +}); +``` + +Test failure scenarios too: + +```php +Http::fake([ + 'api.example.com/*' => Http::failedConnection(), +]); +``` diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.md new file mode 100644 index 0000000..7c71733 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/mail.md @@ -0,0 +1,27 @@ +# Mail Best Practices + +## Implement `ShouldQueue` on the Mailable Class + +Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it. + +## Use `afterCommit()` on Mailables Inside Transactions + +A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor. + +## Use `assertQueued()` Not `assertSent()` for Queued Mailables + +`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint. + +Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. + +Correct: `Mail::assertQueued(OrderShipped::class);` + +## Use Markdown Mailables for Transactional Emails + +Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag. + +## Separate Content Tests from Sending Tests + +Content tests: instantiate the mailable directly, call `assertSeeInHtml()`. +Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`. +Don't mix them — it conflates concerns and makes tests brittle. diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.md new file mode 100644 index 0000000..df6f5f3 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/migrations.md @@ -0,0 +1,121 @@ +# Migration Best Practices + +## Generate Migrations with Artisan + +Always use `php artisan make:migration` for consistent naming and timestamps. + +Incorrect (manually created file): +```php +// database/migrations/posts_migration.php ← wrong naming, no timestamp +``` + +Correct (Artisan-generated): +```bash +php artisan make:migration create_posts_table +php artisan make:migration add_slug_to_posts_table +``` + +## Use `constrained()` for Foreign Keys + +Automatic naming and referential integrity. + +```php +$table->foreignId('user_id')->constrained()->cascadeOnDelete(); + +// Non-standard names +$table->foreignId('author_id')->constrained('users'); +``` + +## Never Modify Deployed Migrations + +Once a migration has run in production, treat it as immutable. Create a new migration to change the table. + +Incorrect (editing a deployed migration): +```php +// 2024_01_01_create_posts_table.php — already in production +$table->string('slug')->unique(); // ← added after deployment +``` + +Correct (new migration to alter): +```php +// 2024_03_15_add_slug_to_posts_table.php +Schema::table('posts', function (Blueprint $table) { + $table->string('slug')->unique()->after('title'); +}); +``` + +## Add Indexes in the Migration + +Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes. + +Incorrect: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); +}); +``` + +Correct: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained()->index(); + $table->string('status')->index(); + $table->timestamp('shipped_at')->nullable()->index(); + $table->timestamps(); +}); +``` + +## Mirror Defaults in Model `$attributes` + +When a column has a database default, mirror it in the model so new instances have correct values before saving. + +```php +// Migration +$table->string('status')->default('pending'); + +// Model +protected $attributes = [ + 'status' => 'pending', +]; +``` + +## Write Reversible `down()` Methods by Default + +Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments. + +```php +public function down(): void +{ + Schema::table('posts', function (Blueprint $table) { + $table->dropColumn('slug'); + }); +} +``` + +For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported. + +## Keep Migrations Focused + +One concern per migration. Never mix DDL (schema changes) and DML (data manipulation). + +Incorrect (partial failure creates unrecoverable state): +```php +public function up(): void +{ + Schema::create('settings', function (Blueprint $table) { ... }); + DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); +} +``` + +Correct (separate migrations): +```php +// Migration 1: create_settings_table +Schema::create('settings', function (Blueprint $table) { ... }); + +// Migration 2: seed_default_settings +DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); +``` diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.md new file mode 100644 index 0000000..c41915e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/queue-jobs.md @@ -0,0 +1,144 @@ +# Queue & Job Best Practices + +## Set `retry_after` Greater Than `timeout` + +If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution. + +Incorrect (`retry_after` ≤ `timeout`): +```php +class ProcessReport implements ShouldQueue +{ + public $timeout = 120; +} + +// config/queue.php — retry_after: 90 ← job retried while still running! +``` + +Correct (`retry_after` > `timeout`): +```php +class ProcessReport implements ShouldQueue +{ + public $timeout = 120; +} + +// config/queue.php — retry_after: 180 ← safely longer than any job timeout +``` + +## Use Exponential Backoff + +Use progressively longer delays between retries to avoid hammering failing services. + +Incorrect (fixed retry interval): +```php +class SyncWithStripe implements ShouldQueue +{ + public $tries = 3; + // Default: retries immediately, overwhelming the API +} +``` + +Correct (exponential backoff): +```php +class SyncWithStripe implements ShouldQueue +{ + public $tries = 3; + public $backoff = [1, 5, 10]; +} +``` + +## Implement `ShouldBeUnique` + +Prevent duplicate job processing. + +```php +class GenerateInvoice implements ShouldQueue, ShouldBeUnique +{ + public function uniqueId(): string + { + return $this->order->id; + } + + public $uniqueFor = 3600; +} +``` + +## Always Implement `failed()` + +Handle errors explicitly — don't rely on silent failure. + +```php +public function failed(?Throwable $exception): void +{ + $this->podcast->update(['status' => 'failed']); + Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]); +} +``` + +## Rate Limit External API Calls in Jobs + +Use `RateLimited` middleware to throttle jobs calling third-party APIs. + +```php +public function middleware(): array +{ + return [new RateLimited('external-api')]; +} +``` + +## Batch Related Jobs + +Use `Bus::batch()` when jobs should succeed or fail together. + +```php +Bus::batch([ + new ImportCsvChunk($chunk1), + new ImportCsvChunk($chunk2), +]) +->then(fn (Batch $batch) => Notification::send($user, new ImportComplete)) +->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed')) +->dispatch(); +``` + +## `retryUntil()` Needs `$tries = 0` + +When using time-based retry limits, set `$tries = 0` to avoid premature failure. + +```php +public $tries = 0; + +public function retryUntil(): \DateTimeInterface +{ + return now()->addHours(4); +} +``` + +## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release + +`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue. + +```php +class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing +{ + // Lock releases when processing begins, not when it finishes +} +``` + +## Use Horizon for Complex Queue Scenarios + +Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. + +```php +// config/horizon.php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + 'connection' => 'redis', + 'queue' => ['high', 'default', 'low'], + 'balance' => 'auto', + 'minProcesses' => 1, + 'maxProcesses' => 10, + 'tries' => 3, + ], + ], +], +``` diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.md new file mode 100644 index 0000000..b6e3086 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/routing.md @@ -0,0 +1,99 @@ +# Routing & Controllers Best Practices + +## Use Implicit Route Model Binding + +Let Laravel resolve models automatically from route parameters. + +Incorrect: +```php +public function show(int $id) +{ + $post = Post::findOrFail($id); +} +``` + +Correct: +```php +public function show(Post $post) +{ + return view('posts.show', ['post' => $post]); +} +``` + +## Use Scoped Bindings for Nested Resources + +Enforce parent-child relationships automatically. + +```php +Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) { + // $post is automatically scoped to $user +})->scopeBindings(); +``` + +## Use Resource Controllers + +Use `Route::resource()` or `apiResource()` for RESTful endpoints. + +```php +Route::resource('posts', PostController::class); +// In routes/api.php — the /api prefix is applied automatically +Route::apiResource('posts', Api\PostController::class); +``` + +## Keep Controllers Thin + +Aim for under 10 lines per method. Extract business logic to action or service classes. + +Incorrect: +```php +public function store(Request $request) +{ + $validated = $request->validate([...]); + if ($request->hasFile('image')) { + $request->file('image')->move(public_path('images')); + } + $post = Post::create($validated); + $post->tags()->sync($validated['tags']); + event(new PostCreated($post)); + return redirect()->route('posts.show', $post); +} +``` + +Correct: +```php +public function store(StorePostRequest $request, CreatePostAction $create) +{ + $post = $create->execute($request->validated()); + + return redirect()->route('posts.show', $post); +} +``` + +## Type-Hint Form Requests + +Type-hinting Form Requests triggers automatic validation and authorization before the method executes. + +Incorrect: +```php +public function store(Request $request): RedirectResponse +{ + $validated = $request->validate([ + 'title' => ['required', 'max:255'], + 'body' => ['required'], + ]); + + Post::create($validated); + + return redirect()->route('posts.index'); +} +``` + +Correct: +```php +public function store(StorePostRequest $request): RedirectResponse +{ + Post::create($request->validated()); + + return redirect()->route('posts.index'); +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.md new file mode 100644 index 0000000..a984794 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/scheduling.md @@ -0,0 +1,39 @@ +# Task Scheduling Best Practices + +## Use `withoutOverlapping()` on Variable-Duration Tasks + +Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion. + +## Use `onOneServer()` on Multi-Server Deployments + +Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached). + +## Use `runInBackground()` for Concurrent Long Tasks + +By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes. + +## Use `environments()` to Restrict Tasks + +Prevent accidental execution of production-only tasks (billing, reporting) on staging. + +```php +Schedule::command('billing:charge')->monthly()->environments(['production']); +``` + +## Use `takeUntilTimeout()` for Time-Bounded Processing + +A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time. + +## Use Schedule Groups for Shared Configuration + +Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks. + +```php +Schedule::daily() + ->onOneServer() + ->timezone('America/New_York') + ->group(function () { + Schedule::command('emails:send --force'); + Schedule::command('emails:prune'); + }); +``` diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.md new file mode 100644 index 0000000..447e1b6 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/security.md @@ -0,0 +1,198 @@ +# Security Best Practices + +## Mass Assignment Protection + +Every model must define `$fillable` (whitelist) or `$guarded` (blacklist). + +Incorrect: +```php +class User extends Model +{ + protected $guarded = []; // All fields are mass assignable +} +``` + +Correct: +```php +class User extends Model +{ + protected $fillable = [ + 'name', + 'email', + 'password', + ]; +} +``` + +Never use `$guarded = []` on models that accept user input. + +## Authorize Every Action + +Use policies or gates in controllers. Never skip authorization. + +Incorrect: +```php +public function update(UpdatePostRequest $request, Post $post) +{ + $post->update($request->validated()); +} +``` + +Correct: +```php +public function update(UpdatePostRequest $request, Post $post) +{ + Gate::authorize('update', $post); + + $post->update($request->validated()); +} +``` + +Or via Form Request: + +```php +public function authorize(): bool +{ + return $this->user()->can('update', $this->route('post')); +} +``` + +## Prevent SQL Injection + +Always use parameter binding. Never interpolate user input into queries. + +Incorrect: +```php +DB::select("SELECT * FROM users WHERE name = '{$request->name}'"); +``` + +Correct: +```php +User::where('name', $request->name)->get(); + +// Raw expressions with bindings +User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get(); +``` + +## Escape Output to Prevent XSS + +Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content. + +Incorrect: +```blade +{!! $user->bio !!} +``` + +Correct: +```blade +{{ $user->bio }} +``` + +## CSRF Protection + +Include `@csrf` in all POST/PUT/DELETE Blade forms. Inertia doesn't use `@csrf`; its HTTP client sends the `XSRF-TOKEN` cookie back as the `X-XSRF-TOKEN` header, which Laravel accepts in place of the `_token` field. + +Incorrect: +```blade +
+ +
+``` + +Correct: +```blade +
+ @csrf + +
+``` + +## Rate Limit Auth and API Routes + +Apply `throttle` middleware to authentication and API routes. + +```php +RateLimiter::for('login', function (Request $request) { + return Limit::perMinute(5)->by($request->ip()); +}); + +Route::post('/login', LoginController::class)->middleware('throttle:login'); +``` + +## Validate File Uploads + +Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames. + +```php +public function rules(): array +{ + return [ + 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], + ]; +} +``` + +Store with generated filenames: + +```php +$path = $request->file('avatar')->store('avatars', 'public'); +``` + +## Keep Secrets Out of Code + +Never commit `.env`. Access secrets via `config()` only. + +Incorrect: +```php +$key = env('API_KEY'); +``` + +Correct: +```php +// config/services.php +'api_key' => env('API_KEY'), + +// In application code +$key = config('services.api_key'); +``` + +## Audit Dependencies + +Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment. + +```bash +composer audit +``` + +## Encrypt Sensitive Database Fields + +Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`. + +Incorrect: +```php +class Integration extends Model +{ + protected function casts(): array + { + return [ + 'api_key' => 'string', + ]; + } +} +``` + +Correct: +```php +class Integration extends Model +{ + protected $hidden = ['api_key', 'api_secret']; + + protected function casts(): array + { + return [ + 'api_key' => 'encrypted', + 'api_secret' => 'encrypted', + ]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.md new file mode 100644 index 0000000..a8afb36 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/style.md @@ -0,0 +1,125 @@ +# Conventions & Style + +## Follow Laravel Naming Conventions + +| What | Convention | Good | Bad | +|------|-----------|------|-----| +| Controller | singular | `ArticleController` | `ArticlesController` | +| Model | singular | `User` | `Users` | +| Table | plural, snake_case | `article_comments` | `articleComments` | +| Pivot table | singular alphabetical | `article_user` | `user_article` | +| Column | snake_case, no model name | `meta_title` | `article_meta_title` | +| Foreign key | singular model + `_id` | `article_id` | `articles_id` | +| Route | plural | `articles/1` | `article/1` | +| Route name | snake_case with dots | `users.show_active` | `users.show-active` | +| Method | camelCase | `getAll` | `get_all` | +| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` | +| Collection | descriptive, plural | `$activeUsers` | `$data` | +| Object | descriptive, singular | `$activeUser` | `$users` | +| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` | +| Config | snake_case | `google_calendar.php` | `googleCalendar.php` | +| Enum | singular | `UserType` | `UserTypes` | + +## Prefer Shorter Readable Syntax + +| Verbose | Shorter | +|---------|---------| +| `Session::get('cart')` | `session('cart')` | +| `$request->session()->get('cart')` | `session('cart')` | +| `$request->input('name')` | `$request->name` | +| `return Redirect::back()` | `return back()` | +| `Carbon::now()` | `now()` | +| `App::make('Class')` | `app('Class')` | +| `->where('column', '=', 1)` | `->where('column', 1)` | +| `->orderBy('created_at', 'desc')` | `->latest()` | +| `->orderBy('created_at', 'asc')` | `->oldest()` | +| `->first()->name` | `->value('name')` | + +## Use Laravel String & Array Helpers + +Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them. + +Strings — use `Str` and fluent `Str::of()` over raw PHP: +```php +// Incorrect +$slug = strtolower(str_replace(' ', '-', $title)); +$short = substr($text, 0, 100) . '...'; +$class = substr(strrchr('App\Models\User', '\\'), 1); + +// Correct +$slug = Str::slug($title); +$short = Str::limit($text, 100); +$class = class_basename('App\Models\User'); +``` + +Fluent strings — chain operations for complex transformations: +```php +// Incorrect +$result = strtolower(trim(str_replace('_', '-', $input))); + +// Correct +$result = Str::of($input)->trim()->replace('_', '-')->lower(); +``` + +Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`. + +Arrays — use `Arr` over raw PHP: +```php +// Incorrect +$name = isset($array['user']['name']) ? $array['user']['name'] : 'default'; + +// Correct +$name = Arr::get($array, 'user.name', 'default'); +``` + +Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`. + +Numbers — use `Number` for display formatting: +```php +Number::format(1000000); // "1,000,000" +Number::currency(1500, 'USD'); // "$1,500.00" +Number::abbreviate(1000000); // "1M" +Number::fileSize(1024 * 1024); // "1 MB" +Number::percentage(75.5); // "75.5%" +``` + +URIs — use `Uri` for URL manipulation: +```php +$uri = Uri::of('https://example.com/search') + ->withQuery(['q' => 'laravel', 'page' => 1]); +``` + +Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining. + +Use `search-docs` for the full list of available methods — these helpers are extensive. + +## No Inline JS/CSS in Blade + +Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes. + +Incorrect: +```blade +let article = `{{ json_encode($article) }}`; +``` + +Correct: +```blade + +``` + +Pass data to JS via data attributes or use a dedicated PHP-to-JS package. + +## No Unnecessary Comments + +Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected. + +Incorrect: +```php +// Check if there are any joins +if (count((array) $builder->getQuery()->joins) > 0) +``` + +Correct: +```php +if ($this->hasJoins()) +``` diff --git a/.agents/skills/laravel-best-practices/rules/testing.md b/.agents/skills/laravel-best-practices/rules/testing.md new file mode 100644 index 0000000..4fbf12f --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/testing.md @@ -0,0 +1,43 @@ +# Testing Best Practices + +## Use `LazilyRefreshDatabase` Over `RefreshDatabase` + +`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date. + +## Use Model Assertions Over Raw Database Assertions + +Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);` + +Correct: `$this->assertModelExists($user);` + +More expressive, type-safe, and fails with clearer messages. + +## Use Factory States and Sequences + +Named states make tests self-documenting. Sequences eliminate repetitive setup. + +Incorrect: `User::factory()->create(['email_verified_at' => null]);` + +Correct: `User::factory()->unverified()->create();` + +## Use `Exceptions::fake()` to Assert Exception Reporting + +Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally. + +## Call `Event::fake()` After Factory Setup + +Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models. + +Incorrect: `Event::fake(); $user = User::factory()->create();` + +Correct: `$user = User::factory()->create(); Event::fake();` + +## Use `recycle()` to Share Relationship Instances Across Factories + +Without `recycle()`, nested factories create separate instances of the same conceptual entity. + +```php +Ticket::factory() + ->recycle(Airline::factory()->create()) + ->create(); +``` diff --git a/.agents/skills/laravel-best-practices/rules/validation.md b/.agents/skills/laravel-best-practices/rules/validation.md new file mode 100644 index 0000000..5fde106 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/validation.md @@ -0,0 +1,75 @@ +# Validation & Forms Best Practices + +## Use Form Request Classes + +Extract validation from controllers into dedicated Form Request classes. + +Incorrect: +```php +public function store(Request $request) +{ + $request->validate([ + 'title' => 'required|max:255', + 'body' => 'required', + ]); +} +``` + +Correct: +```php +public function store(StorePostRequest $request) +{ + Post::create($request->validated()); +} +``` + +## Array vs. String Notation for Rules + +Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses. + +```php +// Preferred for new code +'email' => ['required', 'email', Rule::unique('users')], + +// Follow existing convention if the project uses string notation +'email' => 'required|email|unique:users', +``` + +## Always Use `validated()` + +Get only validated data. Never use `$request->all()` for mass operations. + +Incorrect: +```php +Post::create($request->all()); +``` + +Correct: +```php +Post::create($request->validated()); +``` + +## Use `Rule::when()` for Conditional Validation + +```php +'company_name' => [ + Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']), +], +``` + +## Use the `after()` Method for Custom Validation + +Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields. + +```php +public function after(): array +{ + return [ + function (Validator $validator) { + if ($this->quantity > Product::find($this->product_id)?->stock) { + $validator->errors()->add('quantity', 'Not enough stock.'); + } + }, + ]; +} +``` diff --git a/.agents/skills/socialite-development/SKILL.md b/.agents/skills/socialite-development/SKILL.md new file mode 100644 index 0000000..562e417 --- /dev/null +++ b/.agents/skills/socialite-development/SKILL.md @@ -0,0 +1,80 @@ +--- +name: socialite-development +description: "Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication." +license: MIT +metadata: + author: laravel +--- + +# Socialite Authentication + +## Documentation + +Use `search-docs` for detailed Socialite patterns and documentation (installation, configuration, routing, callbacks, testing, scopes, stateless auth). + +## Available Providers + +Built-in: `facebook`, `twitter`, `twitter-oauth-2`, `linkedin`, `linkedin-openid`, `google`, `github`, `gitlab`, `bitbucket`, `slack`, `slack-openid`, `twitch` + +Community: 150+ additional providers at [socialiteproviders.com](https://socialiteproviders.com). For provider-specific setup, use `WebFetch` on `https://socialiteproviders.com/{provider-name}`. + +Configuration key in `config/services.php` must match the driver name exactly — note the hyphenated keys: `twitter-oauth-2`, `linkedin-openid`, `slack-openid`. + +Twitter/X: Use `twitter-oauth-2` (OAuth 2.0) for new projects. The legacy `twitter` driver is OAuth 1.0. Driver names remain unchanged despite the platform rebrand. + +Community providers differ from built-in providers in the following ways: +- Installed via `composer require socialiteproviders/{name}` +- Must register via event listener — NOT auto-discovered like built-in providers +- Use `search-docs` for the registration pattern + +## Adding a Provider + +### 1. Configure the provider + +Add the provider's `client_id`, `client_secret`, and `redirect` to `config/services.php`. The config key must match the driver name exactly. + +### 2. Create redirect and callback routes + +Two routes are needed: one that calls `Socialite::driver('provider')->redirect()` to send the user to the OAuth provider, and one that calls `Socialite::driver('provider')->user()` to receive the callback and retrieve user details. + +### 3. Authenticate and store the user + +In the callback, use `updateOrCreate` to find or create a user record from the provider's response (`id`, `name`, `email`, `token`, `refreshToken`), then call `Auth::login()`. + +### 4. Customize the redirect (optional) + +- `scopes()` — merge additional scopes with the provider's defaults +- `setScopes()` — replace all scopes entirely +- `with()` — pass optional parameters (e.g., `['hd' => 'example.com']` for Google) +- `asBotUser()` — Slack only; generates a bot token (`xoxb-`) instead of a user token (`xoxp-`). Must be called before both `redirect()` and `user()`. Only the `token` property will be hydrated on the user object. +- `stateless()` — for API/SPA contexts where session state is not maintained + +### 5. Verify + +1. Config key matches driver name exactly (check the list above for hyphenated names) +2. `client_id`, `client_secret`, and `redirect` are all present +3. Redirect URL matches what is registered in the provider's OAuth dashboard +4. Callback route handles denied grants (when user declines authorization) + +Use `search-docs` for complete code examples of each step. + +## Additional Features + +Use `search-docs` for usage details on: `enablePKCE()`, `userFromToken($token)`, `userFromTokenAndSecret($token, $secret)` (OAuth 1.0), retrieving user details. + +User object: `getId()`, `getName()`, `getEmail()`, `getAvatar()`, `getNickname()`, `token`, `refreshToken`, `expiresIn`, `approvedScopes` + +## Testing + +Socialite provides `Socialite::fake()` for testing redirects and callbacks. Use `search-docs` for faking redirects, callback user data, custom token properties, and assertion methods. + +## Common Pitfalls + +- Config key must match driver name exactly — hyphenated drivers need hyphenated keys (`linkedin-openid`, `slack-openid`, `twitter-oauth-2`). Mismatch silently fails. +- Every provider needs `client_id`, `client_secret`, and `redirect` in `config/services.php`. Missing any one causes cryptic errors. +- `scopes()` merges with defaults; `setScopes()` replaces all scopes entirely. +- Missing `stateless()` in API/SPA contexts causes `InvalidStateException`. +- Redirect URL in `config/services.php` must exactly match the provider's OAuth dashboard (including trailing slashes and protocol). +- Do not pass `state`, `response_type`, `client_id`, `redirect_uri`, or `scope` via `with()` — these are reserved. +- Community providers require event listener registration via `SocialiteWasCalled`. +- `user()` throws when the user declines authorization. Always handle denied grants. diff --git a/.agents/skills/tailwindcss-development/SKILL.md b/.agents/skills/tailwindcss-development/SKILL.md new file mode 100644 index 0000000..c0cb2fb --- /dev/null +++ b/.agents/skills/tailwindcss-development/SKILL.md @@ -0,0 +1,119 @@ +--- +name: tailwindcss-development +description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS." +license: MIT +metadata: + author: laravel +--- + +# Tailwind CSS Development + +## Documentation + +Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation. + +## Basic Usage + +- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns. +- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue). +- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically. + +## Tailwind CSS v4 Specifics + +- Always use Tailwind CSS v4 and avoid deprecated utilities. +- `corePlugins` is not supported in Tailwind v4. + +### CSS-First Configuration + +In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed: + + +```css +@theme { + --color-brand: oklch(0.72 0.11 178); +} +``` + +### Import Syntax + +In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3: + + +```diff +- @tailwind base; +- @tailwind components; +- @tailwind utilities; ++ @import "tailwindcss"; +``` + +### Replaced Utilities + +Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric. + +| Deprecated | Replacement | +|------------|-------------| +| bg-opacity-* | bg-black/* | +| text-opacity-* | text-black/* | +| border-opacity-* | border-black/* | +| divide-opacity-* | divide-black/* | +| ring-opacity-* | ring-black/* | +| placeholder-opacity-* | placeholder-black/* | +| flex-shrink-* | shrink-* | +| flex-grow-* | grow-* | +| overflow-ellipsis | text-ellipsis | +| decoration-slice | box-decoration-slice | +| decoration-clone | box-decoration-clone | + +## Spacing + +Use `gap` utilities instead of margins for spacing between siblings: + + +```html +
+
Item 1
+
Item 2
+
+``` + +## Dark Mode + +If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant: + + +```html +
+ Content adapts to color scheme +
+``` + +## Common Patterns + +### Flexbox Layout + + +```html +
+
Left content
+
Right content
+
+``` + +### Grid Layout + + +```html +
+
Card 1
+
Card 2
+
Card 3
+
+``` + +## Common Pitfalls + +- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.) +- Using `@tailwind` directives instead of `@import "tailwindcss"` +- Trying to use `tailwind.config.js` instead of CSS `@theme` directive +- Using margins for spacing between siblings instead of gap utilities +- Forgetting to add dark mode variants when the project uses dark mode diff --git a/.env.example b/.env.example index 3f030a1..9cea110 100644 --- a/.env.example +++ b/.env.example @@ -76,3 +76,5 @@ METERED_KEY= # Interview Configurations MAX_INTERVIEWER=2 +INTERVIEW_RECORDINGS_FOLDER=uploads/candidate_recordings +INTERVIEW_RECORDINGS_TEMP_FOLDER=app/temp_recordings diff --git a/app/Actions/Interview/FinalizeRecordingAction.php b/app/Actions/Interview/FinalizeRecordingAction.php new file mode 100644 index 0000000..eb2fdec --- /dev/null +++ b/app/Actions/Interview/FinalizeRecordingAction.php @@ -0,0 +1,38 @@ +id, + $sessionId, + $tempDir, + $folderName, + $totalChunks, + $duration + ); + } +} diff --git a/app/Actions/Interview/MergeRecordingChunksAction.php b/app/Actions/Interview/MergeRecordingChunksAction.php new file mode 100644 index 0000000..7a11d23 --- /dev/null +++ b/app/Actions/Interview/MergeRecordingChunksAction.php @@ -0,0 +1,201 @@ + $sessionId, + 'temp_dir' => $resolvedTempDir, + ]); + return null; + } + + $parts = $this->findAndSortParts($resolvedTempDir); + if (empty($parts)) { + Log::warning('[MergeRecordingChunksAction] No chunk parts found to merge', [ + 'session_id' => $sessionId, + 'temp_dir' => $resolvedTempDir, + ]); + return null; + } + + // Validate that part_000000.webm exists and starts with valid EBML container header + $firstPart = $parts[0]; + $headerCheck = @file_get_contents($firstPart, false, null, 0, 4); + if ($headerCheck === false || !str_starts_with($headerCheck, "\x1a\x45\xdf\xa3")) { + Log::error('[MergeRecordingChunksAction] First chunk missing EBML container header. Possible incomplete initial chunk upload.', [ + 'session_id' => $sessionId, + 'first_part' => $firstPart, + 'header_hex' => $headerCheck ? bin2hex($headerCheck) : 'null', + ]); + return null; + } + + $baseFolder = config('interview.recordings.base_folder', 'uploads/candidate_recordings'); + $uniqueFolder = $folderName ?: ($interview->submission_unique_id ?: (string) $interview->id); + $subDir = trim($baseFolder, '/') . '/' . $uniqueFolder; + $destinationDir = public_path($subDir); + + $this->ensureDestinationDirectory($destinationDir); + + $filename = 'recording_' . time() . '.webm'; + $finalPath = $destinationDir . DIRECTORY_SEPARATOR . $filename; + + $this->streamMergeFiles($parts, $finalPath); + + if (!file_exists($finalPath) || filesize($finalPath) === 0) { + Log::error('[MergeRecordingChunksAction] Output recording file is empty or was not created', [ + 'final_path' => $finalPath, + 'session_id' => $sessionId, + ]); + return null; + } + + $relativePath = '/' . $subDir . '/' . $filename; + $url = asset($subDir . '/' . $filename); + + $this->updateInterviewRecordings($interview, $relativePath, $url, $filename, $duration); + + $this->cleanupTempParts($parts, $resolvedTempDir); + + Log::info('[MergeRecordingChunksAction] Recording assembled successfully', [ + 'interview_id' => $interview->id, + 'session_id' => $sessionId, + 'total_parts' => count($parts), + 'duration' => $duration, + 'path' => $relativePath, + ]); + + return $relativePath; + } + + /** + * Locate and sort chunk part files in ascending numerical order. + * + * @param string $tempDir + * @return array + */ + private function findAndSortParts(string $tempDir): array + { + $parts = glob($tempDir . DIRECTORY_SEPARATOR . 'part_*.webm') ?: []; + natsort($parts); + return array_values($parts); + } + + /** + * Ensure that the destination directory exists and is writable. + * + * @param string $dir + * @return void + */ + private function ensureDestinationDirectory(string $dir): void + { + if (!is_dir($dir)) { + if (!mkdir($dir, 0755, true) && !is_dir($dir)) { + throw new RuntimeException("Failed to create destination directory: {$dir}"); + } + } + } + + /** + * Stream merge multiple binary chunk files into a single destination file. + * + * @param array $parts + * @param string $finalPath + * @return void + */ + private function streamMergeFiles(array $parts, string $finalPath): void + { + $out = fopen($finalPath, 'wb'); + if ($out === false) { + throw new RuntimeException("Cannot open destination file for writing: {$finalPath}"); + } + + try { + foreach ($parts as $partFile) { + $in = fopen($partFile, 'rb'); + if ($in === false) { + Log::warning("[MergeRecordingChunksAction] Could not read part: {$partFile}"); + continue; + } + stream_copy_to_stream($in, $out); + fclose($in); + } + } finally { + fclose($out); + } + } + + /** + * Update the interview model with the newly merged recording metadata. + * + * @param Interview $interview + * @param string $relativePath + * @param string $url + * @param string $filename + * @param int|null $duration + * @return void + */ + private function updateInterviewRecordings(Interview $interview, string $relativePath, string $url, string $filename, ?int $duration = null): void + { + $recordings = $interview->recordings ?? []; + if (!is_array($recordings)) { + $recordings = $interview->recording_path ? [$interview->recording_path] : []; + } + + $recordings[] = [ + 'url' => $relativePath, + 'full_url' => $url, + 'filename' => $filename, + 'created_at' => now()->toIso8601String(), + 'duration' => $duration ?: 0, + ]; + + $interview->update([ + 'recording_path' => $relativePath, + 'recordings' => $recordings, + ]); + } + + /** + * Clean up temporary parts and remove the session directory. + * + * @param array $parts + * @param string $tempDir + * @return void + */ + private function cleanupTempParts(array $parts, string $tempDir): void + { + foreach ($parts as $partFile) { + @unlink($partFile); + } + @rmdir($tempDir); + } +} diff --git a/app/Actions/Interview/StoreRecordingChunkAction.php b/app/Actions/Interview/StoreRecordingChunkAction.php new file mode 100644 index 0000000..82876b0 --- /dev/null +++ b/app/Actions/Interview/StoreRecordingChunkAction.php @@ -0,0 +1,34 @@ +move($tempDir, $partName); + + return $tempDir . DIRECTORY_SEPARATOR . $partName; + } +} diff --git a/app/Http/Controllers/AdminController.php b/app/Http/Controllers/AdminController.php index 2937cc8..f51a51b 100644 --- a/app/Http/Controllers/AdminController.php +++ b/app/Http/Controllers/AdminController.php @@ -303,7 +303,7 @@ public function updateOnboardingToggle(Request $request) \App\Models\Setting::set('onboarding_enabled', $enabled); $msg = $enabled === '1' ? 'Onboarding & Offboarding module enabled.' : 'Onboarding & Offboarding module disabled.'; - return redirect()->route('admin.dashboard')->with('success', $msg); + return redirect()->back(fallback: route('admin.dashboard'))->with('success', $msg); } /** @@ -315,7 +315,7 @@ public function updateScreenshotToggle(Request $request) \App\Models\Setting::set('enable_candidate_screenshots', $enabled); $msg = $enabled === '1' ? 'Candidate System Screenshot Capture ENABLED globally.' : 'Candidate System Screenshot Capture DISABLED globally by Admin.'; - return redirect()->route('admin.dashboard')->with('success', $msg); + return redirect()->back(fallback: route('admin.dashboard'))->with('success', $msg); } /** diff --git a/app/Http/Controllers/InterviewController.php b/app/Http/Controllers/InterviewController.php index de5de06..a71007f 100644 --- a/app/Http/Controllers/InterviewController.php +++ b/app/Http/Controllers/InterviewController.php @@ -2,6 +2,11 @@ namespace App\Http\Controllers; +use App\Actions\Interview\FinalizeRecordingAction; +use App\Actions\Interview\StoreRecordingChunkAction; +use App\Http\Requests\Interview\UploadRecordingChunkRequest; +use App\Http\Responses\Interview\RecordingChunkReceivedResponse; +use App\Http\Responses\Interview\RecordingFinalizedResponse; use App\Models\Interview; use App\Models\InterviewWarning; use App\Models\User; @@ -587,6 +592,7 @@ private function getFormattedRecordings($interview) $rec['stream_url'] = $streamUrl; $rec['download_url'] = route('interview.download-recording', $interview->id) . '?index=' . $idx; $rec['mime_type'] = $mimeType; + $rec['duration'] = isset($rec['duration']) ? (int) $rec['duration'] : 0; $formatted[] = $rec; } @@ -945,49 +951,117 @@ public function toggleTabScreenshot(Request $request, $id) */ public function uploadRecording(Request $request, $id) { - $interview = Interview::where('id', $id) - ->orWhere('submission_unique_id', $id) - ->firstOrFail(); + try { + $interview = Interview::where('id', $id) + ->orWhere('submission_unique_id', $id) + ->first(); - if ($request->hasFile('video')) { - $file = $request->file('video'); - $ext = strtolower($file->getClientOriginalExtension() ?: 'webm'); - if (!in_array($ext, ['mp4', 'webm', 'm4v', 'mov'])) { - $ext = 'webm'; + if (!$interview) { + return response()->json(['success' => false, 'message' => 'Interview session not found.'], 404); } - $uniqueFolder = $interview->submission_unique_id ?: $interview->id; - $subDir = 'uploads/candidate_recordings/' . $uniqueFolder; - $destinationPath = public_path($subDir); - if (!file_exists($destinationPath)) { - mkdir($destinationPath, 0777, true); + if ($request->hasFile('video')) { + $file = $request->file('video'); + $ext = strtolower($file->getClientOriginalExtension() ?: 'webm'); + if (!in_array($ext, ['mp4', 'webm', 'm4v', 'mov'])) { + $ext = 'webm'; + } + + $baseFolder = config('interview.recordings.base_folder', 'uploads/candidate_recordings'); + $uniqueFolder = $interview->submission_unique_id ?: $interview->id; + $subDir = trim($baseFolder, '/') . '/' . $uniqueFolder; + $destinationPath = public_path($subDir); + if (!file_exists($destinationPath)) { + mkdir($destinationPath, 0777, true); + } + + $filename = 'recording_' . time() . '.' . $ext; + $file->move($destinationPath, $filename); + $url = asset($subDir . '/' . $filename); + $relativePath = '/' . $subDir . '/' . $filename; + + $recordings = $interview->recordings ?? []; + if (!is_array($recordings)) { + $recordings = $interview->recording_path ? [$interview->recording_path] : []; + } + $recordings[] = [ + 'url' => $relativePath, + 'full_url' => $url, + 'filename' => $filename, + 'created_at' => now()->toIso8601String(), + ]; + + $interview->update([ + 'recording_path' => $relativePath, + 'recordings' => $recordings, + ]); + + return response()->json(['success' => true, 'path' => $relativePath, 'url' => $url, 'recordings' => $recordings]); } - $filename = 'recording_' . time() . '.' . $ext; - $file->move($destinationPath, $filename); - $url = asset($subDir . '/' . $filename); - $relativePath = '/' . $subDir . '/' . $filename; + return response()->json(['success' => false, 'message' => 'No video payload received (file may exceed server upload size limit).'], 422); + } catch (\Throwable $e) { + \Log::error('Recording upload failed: ' . $e->getMessage()); + return response()->json(['success' => false, 'message' => 'Server error saving recording: ' . $e->getMessage()], 500); + } + } - $recordings = $interview->recordings ?? []; - if (!is_array($recordings)) { - $recordings = $interview->recording_path ? [$interview->recording_path] : []; + /** + * Handle live chunked video recording upload from the interviewer proctoring session. + * + * @param UploadRecordingChunkRequest $request + * @param int|string $id + * @param StoreRecordingChunkAction $storeChunkAction + * @param FinalizeRecordingAction $finalizeRecordingAction + * @return \Illuminate\Http\JsonResponse|\Illuminate\Contracts\Support\Responsable + */ + public function uploadRecordingChunk( + UploadRecordingChunkRequest $request, + $id, + StoreRecordingChunkAction $storeChunkAction, + FinalizeRecordingAction $finalizeRecordingAction + ) { + try { + $interview = Interview::where('id', $id) + ->orWhere('submission_unique_id', $id) + ->first(); + + if (!$interview) { + return response()->json(['success' => false, 'message' => 'Interview session not found.'], 404); } - $recordings[] = [ - 'url' => $relativePath, - 'full_url' => $url, - 'filename' => $filename, - 'created_at' => now()->toIso8601String(), - ]; - $interview->update([ - 'recording_path' => $relativePath, - 'recordings' => $recordings, + $validated = $request->validated(); + $sessionId = $validated['session_id']; + $chunkIndex = (int) $validated['chunk_index']; + $isFinal = filter_var($validated['is_final'] ?? false, FILTER_VALIDATE_BOOLEAN); + + if ($request->hasFile('chunk')) { + $file = $request->file('chunk'); + $storeChunkAction->execute($interview, $sessionId, $chunkIndex, $file); + } + + if ($isFinal) { + $totalChunks = (int) ($validated['total_chunks'] ?? ($chunkIndex + 1)); + $duration = isset($validated['duration']) ? (int) $validated['duration'] : null; + $finalizeRecordingAction->execute($interview, $sessionId, $totalChunks, null, null, $duration); + + return new RecordingFinalizedResponse($sessionId); + } + + return new RecordingChunkReceivedResponse($sessionId, $chunkIndex); + } catch (\Throwable $e) { + \Log::error('Recording chunk upload failed: ' . $e->getMessage(), [ + 'id' => $id, + 'session_id' => $request->input('session_id'), + 'chunk_index' => $request->input('chunk_index'), + 'trace' => $e->getTraceAsString(), ]); - return response()->json(['success' => true, 'path' => $relativePath, 'url' => $url, 'recordings' => $recordings]); + return response()->json([ + 'success' => false, + 'message' => 'Error processing recording chunk: ' . $e->getMessage() + ], 500); } - - return response()->json(['success' => false, 'message' => 'No video payload received']); } /** diff --git a/app/Http/Requests/Interview/UploadRecordingChunkRequest.php b/app/Http/Requests/Interview/UploadRecordingChunkRequest.php new file mode 100644 index 0000000..5e90ef9 --- /dev/null +++ b/app/Http/Requests/Interview/UploadRecordingChunkRequest.php @@ -0,0 +1,46 @@ +|string> + */ + public function rules(): array + { + return [ + 'session_id' => ['required', 'string', 'max:255'], + 'chunk_index' => ['required', 'integer', 'min:0'], + 'is_final' => ['nullable', 'boolean'], + 'total_chunks' => ['nullable', 'integer', 'min:0'], + 'duration' => ['nullable', 'integer', 'min:0'], + 'chunk' => ['nullable', 'file', 'max:25600'], // 25MB max per chunk + ]; + } + + /** + * Get custom messages for validator errors. + * + * @return array + */ + public function messages(): array + { + return [ + 'session_id.required' => 'A valid recording session identifier is required.', + 'chunk_index.required' => 'Chunk index must be provided.', + ]; + } +} diff --git a/app/Http/Responses/Interview/RecordingChunkReceivedResponse.php b/app/Http/Responses/Interview/RecordingChunkReceivedResponse.php new file mode 100644 index 0000000..f07a846 --- /dev/null +++ b/app/Http/Responses/Interview/RecordingChunkReceivedResponse.php @@ -0,0 +1,36 @@ +json([ + 'success' => true, + 'chunk_index' => $this->chunkIndex, + 'is_final' => false, + 'session_id' => $this->sessionId, + ], 200); + } +} diff --git a/app/Http/Responses/Interview/RecordingFinalizedResponse.php b/app/Http/Responses/Interview/RecordingFinalizedResponse.php new file mode 100644 index 0000000..9dbf2e6 --- /dev/null +++ b/app/Http/Responses/Interview/RecordingFinalizedResponse.php @@ -0,0 +1,37 @@ +json([ + 'success' => true, + 'is_final' => true, + 'processing' => true, + 'session_id' => $this->sessionId, + 'message' => $this->message, + ], 200); + } +} diff --git a/app/Jobs/MergeRecordingChunksJob.php b/app/Jobs/MergeRecordingChunksJob.php new file mode 100644 index 0000000..34592ce --- /dev/null +++ b/app/Jobs/MergeRecordingChunksJob.php @@ -0,0 +1,98 @@ +interviewId . '_' . $this->sessionId; + } + + /** + * Execute the job. + */ + public function handle(MergeRecordingChunksAction $mergeAction): void + { + Cache::lock('interview_merge_lock_' . $this->interviewId, 60)->block(15, function () use ($mergeAction) { + $interview = Interview::where('id', $this->interviewId) + ->orWhere('submission_unique_id', $this->interviewId) + ->first(); + + if (!$interview) { + Log::warning('[MergeRecordingChunksJob] Interview not found', [ + 'interview_id' => $this->interviewId, + 'session_id' => $this->sessionId, + ]); + return; + } + + $mergeAction->execute( + $interview, + $this->sessionId, + $this->tempDir, + $this->folderName, + $this->duration + ); + }); + } + + /** + * Handle a job failure. + */ + public function failed(?Throwable $exception): void + { + Log::error('[MergeRecordingChunksJob] Recording merge job failed', [ + 'interview_id' => $this->interviewId, + 'session_id' => $this->sessionId, + 'error' => $exception?->getMessage(), + 'trace' => $exception?->getTraceAsString(), + ]); + } +} diff --git a/app/Models/Interview.php b/app/Models/Interview.php index 2c158c3..a81f96b 100644 --- a/app/Models/Interview.php +++ b/app/Models/Interview.php @@ -101,4 +101,44 @@ public function isAssignedInterviewer($userId): bool $interviewers = array_map('strval', (array) $this->assigned_interviewers); return in_array((string) $userId, $interviewers, true); } + + /** + * Get computed initials for candidate (e.g. "John Doe" -> "JD"). + */ + public function getCandidateInitialsAttribute(): string + { + $parts = preg_split('/\s+/', trim($this->candidate_name ?? '')); + if (count($parts) >= 2) { + return strtoupper(substr($parts[0], 0, 1) . substr(end($parts), 0, 1)); + } + $nameStr = trim($this->candidate_name ?? ''); + return strtoupper(substr($nameStr, 0, 1) . (strlen($nameStr) > 1 ? substr($nameStr, -1) : '')); + } + + /** + * Get proctoring alert metrics summary. + */ + public function getProctorMetricsAttribute(): array + { + $logs = $this->proctor_logs ?? []; + return [ + 'tab_switches' => count(array_filter($logs, fn($l) => ($l['type'] ?? '') === 'tab_switch')), + 'focus_lost' => count(array_filter($logs, fn($l) => ($l['type'] ?? '') === 'focus_lost')), + 'gaze_alerts' => count(array_filter($logs, fn($l) => in_array($l['type'] ?? '', ['gaze_anomaly', 'gaze_fixed_staring', 'looking_away']))), + 'lower_gaze' => count(array_filter($logs, fn($l) => ($l['type'] ?? '') === 'gaze_lower_device')), + 'question_repeat' => count(array_filter($logs, fn($l) => in_array($l['type'] ?? '', ['question_repeat_lower', 'question_repetition']))), + 'external_ai' => count(array_filter($logs, fn($l) => ($l['type'] ?? '') === 'external_ai_detected')), + 'paste_events' => count(array_filter($logs, fn($l) => ($l['type'] ?? '') === 'paste_event')), + 'total_incidents' => count($logs), + ]; + } + + /** + * Format timeline string: "M d, H:i – H:i". + */ + public function getFormattedTimelineAttribute(): string + { + $start = $this->scheduled_at ?? $this->created_at; + return $start->format('M d, H:i') . ' – ' . $this->expires_at->format('H:i'); + } } diff --git a/boost.json b/boost.json new file mode 100644 index 0000000..b8e5b76 --- /dev/null +++ b/boost.json @@ -0,0 +1,17 @@ +{ + "agents": [ + "antigravity", + "zed" + ], + "cloud": false, + "guidelines": true, + "mcp": true, + "nightwatch": false, + "sail": false, + "skills": [ + "infer-conventions", + "laravel-best-practices", + "socialite-development", + "tailwindcss-development" + ] +} diff --git a/composer.json b/composer.json index 4f97839..29f1289 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,7 @@ "license": "MIT", "require": { "php": "^8.3", + "gehrisandro/tailwind-merge-laravel": "^1.4", "laravel/framework": "^13.8", "laravel/socialite": "^5.28", "laravel/tinker": "^3.0", @@ -17,6 +18,7 @@ }, "require-dev": { "fakerphp/faker": "^1.23", + "laravel/boost": "^2.5", "laravel/pail": "^1.2.5", "laravel/pao": "^1.0.6", "laravel/pint": "^1.27", diff --git a/composer.lock b/composer.lock index 684f94f..ac7cdb8 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c4355def664b0181bc293f22335a84f1", + "content-hash": "d8109d7765ee6f6846cd672d742ad3e6", "packages": [ { "name": "brick/math", @@ -644,6 +644,147 @@ ], "time": "2025-12-03T09:33:47+00:00" }, + { + "name": "gehrisandro/tailwind-merge-laravel", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/gehrisandro/tailwind-merge-laravel.git", + "reference": "4dfc54d2f1c148b87a7f9803b3bae74c3437e7d9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/gehrisandro/tailwind-merge-laravel/zipball/4dfc54d2f1c148b87a7f9803b3bae74c3437e7d9", + "reference": "4dfc54d2f1c148b87a7f9803b3bae74c3437e7d9", + "shasum": "" + }, + "require": { + "gehrisandro/tailwind-merge-php": "^v1.1.0", + "guzzlehttp/guzzle": "^7.5.1", + "laravel/framework": "^12.0|^13.0", + "php": "^8.2.0" + }, + "require-dev": { + "laravel/pint": "^1.13.8", + "orchestra/testbench": "^10.0|^11.0", + "pestphp/pest": "^3.7|^4.4", + "pestphp/pest-plugin-arch": "^3.0|^4.0", + "pestphp/pest-plugin-type-coverage": "^3.3|^4.0", + "phpstan/phpstan": "^1.10.55|^2.1", + "rector/rector": "^0.19|^2.0", + "symfony/var-dumper": "^6.4.2|^7.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "TailwindMerge\\Laravel\\TailwindMergeServiceProvider" + ] + } + }, + "autoload": { + "files": [ + "src/helpers.php" + ], + "psr-4": { + "TailwindMerge\\Laravel\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sandro Gehri", + "email": "sandrogehri@gmail.com" + } + ], + "description": "TailwindMerge for Laravel merges multiple Tailwind CSS classes by automatically resolving conflicts between them", + "keywords": [ + "classes", + "laravel", + "merge", + "php", + "tailwindcss" + ], + "support": { + "issues": "https://github.com/gehrisandro/tailwind-merge-laravel/issues", + "source": "https://github.com/gehrisandro/tailwind-merge-laravel/tree/v1.4.0" + }, + "funding": [ + { + "url": "https://github.com/gehrisandro", + "type": "github" + } + ], + "time": "2026-03-21T06:54:49+00:00" + }, + { + "name": "gehrisandro/tailwind-merge-php", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/gehrisandro/tailwind-merge-php.git", + "reference": "400040c89bc958ed130699ee4db0213f689cd498" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/gehrisandro/tailwind-merge-php/zipball/400040c89bc958ed130699ee4db0213f689cd498", + "reference": "400040c89bc958ed130699ee4db0213f689cd498", + "shasum": "" + }, + "require": { + "php": "^8.2.0", + "psr/simple-cache": "^3.0" + }, + "require-dev": { + "laravel/pint": "^1.13.8", + "nunomaduro/collision": "^v8.9.1", + "pestphp/pest": "^v4.4.2", + "pestphp/pest-plugin-type-coverage": "^v4.0.3", + "phpstan/phpstan": "^2.1.42", + "rector/rector": "^2.3.9", + "symfony/var-dumper": "^v7.4.6" + }, + "type": "library", + "autoload": { + "files": [ + "src/TailwindMerge.php" + ], + "psr-4": { + "TailwindMerge\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sandro Gehri", + "email": "sandrogehri@gmail.com" + } + ], + "description": "TailwindMerge for PHP merges multiple Tailwind CSS classes by automatically resolving conflicts between them", + "keywords": [ + "classes", + "merge", + "php", + "tailwindcss" + ], + "support": { + "issues": "https://github.com/gehrisandro/tailwind-merge-php/issues", + "source": "https://github.com/gehrisandro/tailwind-merge-php/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://github.com/gehrisandro", + "type": "github" + } + ], + "time": "2026-03-21T06:39:15+00:00" + }, { "name": "graham-campbell/result-type", "version": "v1.1.4", @@ -6565,6 +6706,83 @@ } ], "packages-dev": [ + { + "name": "composer/semver", + "version": "3.4.4", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.4" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "time": "2025-08-20T19:15:30+00:00" + }, { "name": "fakerphp/faker", "version": "v1.24.1", @@ -6812,6 +7030,146 @@ }, "time": "2026-04-29T18:32:34+00:00" }, + { + "name": "laravel/boost", + "version": "v2.5.3", + "source": { + "type": "git", + "url": "https://github.com/laravel/boost.git", + "reference": "f5f9297225aba9857d014b3140f55a7c50cb1a92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/boost/zipball/f5f9297225aba9857d014b3140f55a7c50cb1a92", + "reference": "f5f9297225aba9857d014b3140f55a7c50cb1a92", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^7.9", + "illuminate/console": "^11.45.3|^12.41.1|^13.0", + "illuminate/contracts": "^11.45.3|^12.41.1|^13.0", + "illuminate/routing": "^11.45.3|^12.41.1|^13.0", + "illuminate/support": "^11.45.3|^12.41.1|^13.0", + "laravel/mcp": "^0.7.1|^0.8.0|^0.9.0", + "laravel/prompts": "^0.3.10", + "laravel/roster": "^1.0.0", + "php": "^8.2" + }, + "require-dev": { + "laravel/pint": "^1.27.0", + "mockery/mockery": "^1.6.12", + "orchestra/testbench": "^9.15.0|^10.6|^11.0", + "pestphp/pest": "^2.36.0|^3.8.4|^4.1.5", + "phpstan/phpstan": "^2.1.27", + "rector/rector": "^2.1" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Boost\\BoostServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\Boost\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.", + "homepage": "https://github.com/laravel/boost", + "keywords": [ + "ai", + "dev", + "laravel" + ], + "support": { + "issues": "https://github.com/laravel/boost/issues", + "source": "https://github.com/laravel/boost" + }, + "time": "2026-08-07T05:46:02+00:00" + }, + { + "name": "laravel/mcp", + "version": "v0.9.4", + "source": { + "type": "git", + "url": "https://github.com/laravel/mcp.git", + "reference": "7ca5b923630118696602d14348cd0466a5e853ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/mcp/zipball/7ca5b923630118696602d14348cd0466a5e853ec", + "reference": "7ca5b923630118696602d14348cd0466a5e853ec", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "illuminate/console": "^11.45.3|^12.41.1|^13.0", + "illuminate/container": "^11.45.3|^12.41.1|^13.0", + "illuminate/contracts": "^11.45.3|^12.41.1|^13.0", + "illuminate/http": "^11.45.3|^12.41.1|^13.0", + "illuminate/json-schema": "^12.41.1|^13.0", + "illuminate/routing": "^11.45.3|^12.41.1|^13.0", + "illuminate/support": "^11.45.3|^12.41.1|^13.0", + "illuminate/validation": "^11.45.3|^12.41.1|^13.0", + "php": "^8.2", + "symfony/process": "^7.4.5|^8.0.5" + }, + "require-dev": { + "laravel/pint": "^1.20", + "orchestra/testbench": "^9.15|^10.8|^11.0", + "pestphp/pest": "^3.8.5|^4.3.2", + "phpstan/phpstan": "^2.1.27", + "rector/rector": "^2.2.4" + }, + "type": "library", + "extra": { + "laravel": { + "aliases": { + "Mcp": "Laravel\\Mcp\\Facades\\Mcp" + }, + "providers": [ + "Laravel\\Mcp\\Server\\McpServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Mcp\\": "src/", + "Laravel\\Mcp\\Server\\": "src/Server/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Rapidly build MCP servers for your Laravel applications.", + "homepage": "https://github.com/laravel/mcp", + "keywords": [ + "laravel", + "mcp" + ], + "support": { + "issues": "https://github.com/laravel/mcp/issues", + "source": "https://github.com/laravel/mcp" + }, + "time": "2026-08-13T15:01:07+00:00" + }, { "name": "laravel/pail", "version": "v1.2.7", @@ -7045,6 +7403,68 @@ }, "time": "2026-06-16T15:34:04+00:00" }, + { + "name": "laravel/roster", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/roster.git", + "reference": "89e518bd88ae98ff50f6082f6b517c8d8e8245fa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/roster/zipball/89e518bd88ae98ff50f6082f6b517c8d8e8245fa", + "reference": "89e518bd88ae98ff50f6082f6b517c8d8e8245fa", + "shasum": "" + }, + "require": { + "composer/semver": "^3.0", + "illuminate/console": "^11.0|^12.0|^13.0", + "illuminate/contracts": "^11.0|^12.0|^13.0", + "illuminate/support": "^11.0|^12.0|^13.0", + "php": "^8.2", + "symfony/yaml": "^7.2|^8.0" + }, + "require-dev": { + "laravel/pint": "^1.29", + "mockery/mockery": "^1.6", + "orchestra/testbench": "^9.0|^10.0|^11.0", + "pestphp/pest": "^3.0|^4.1", + "phpstan/phpstan": "^2.0", + "rector/rector": "^2.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Roster\\RosterServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\Roster\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Detect packages & approaches in use within a Laravel project", + "homepage": "https://github.com/laravel/roster", + "keywords": [ + "dev", + "laravel" + ], + "support": { + "issues": "https://github.com/laravel/roster/issues", + "source": "https://github.com/laravel/roster" + }, + "time": "2026-07-18T17:53:15+00:00" + }, { "name": "mockery/mockery", "version": "1.6.12", @@ -8798,6 +9218,82 @@ ], "time": "2024-10-20T05:08:20+00:00" }, + { + "name": "symfony/yaml", + "version": "v8.1.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "faabdbe998e8c5c599dceffa27aa265b185c0736" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/faabdbe998e8c5c599dceffa27aa265b185c0736", + "reference": "faabdbe998e8c5c599dceffa27aa265b185c0736", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/polyfill-ctype": "^1.8" + }, + "conflict": { + "symfony/console": "<7.4" + }, + "require-dev": { + "symfony/console": "^7.4|^8.0", + "yaml/yaml-test-suite": "*" + }, + "bin": [ + "Resources/bin/yaml-lint" + ], + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Loads and dumps YAML files", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/yaml/tree/v8.1.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-07-22T15:42:13+00:00" + }, { "name": "theseer/tokenizer", "version": "2.0.1", @@ -8858,5 +9354,5 @@ "php": "^8.3" }, "platform-dev": {}, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.6.0" } diff --git a/config/interview.php b/config/interview.php index c58a1d7..8d8c380 100644 --- a/config/interview.php +++ b/config/interview.php @@ -7,5 +7,18 @@ |-------------------------------------------------------------------------- | */ - 'max_interviewer' => (int) env('MAX_INTERVIEWER', 2) + 'max_interviewer' => (int) env('MAX_INTERVIEWER', 2), + + /* + |-------------------------------------------------------------------------- + | Candidate Recordings Storage Configuration + |-------------------------------------------------------------------------- + | + | Base folder and temporary chunk storage locations for session recordings. + | + */ + 'recordings' => [ + 'base_folder' => env('INTERVIEW_RECORDINGS_FOLDER', 'uploads/candidate_recordings'), + 'temp_folder' => env('INTERVIEW_RECORDINGS_TEMP_FOLDER', 'app/temp_recordings'), + ], ]; diff --git a/package-lock.json b/package-lock.json index e8ea27f..6b88799 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,9 +1,12 @@ { - "name": "singlelogin", + "name": "sls", "lockfileVersion": 3, "requires": true, "packages": { "": { + "dependencies": { + "@sapphi-red/web-noise-suppressor": "^0.4.0" + }, "devDependencies": { "@tailwindcss/vite": "^4.0.0", "concurrently": "^9.0.1", @@ -407,6 +410,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@sapphi-red/web-noise-suppressor": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@sapphi-red/web-noise-suppressor/-/web-noise-suppressor-0.4.0.tgz", + "integrity": "sha512-vkBEL/VDkbeP3qqSRQFRtPLGa19a38JUzO6J0r5D/MQSumrlERy671DAMaETgY6etXjDCoJcD7JBIaXnuGVtVw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/sapphi-red" + } + }, "node_modules/@tailwindcss/node": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.1.tgz", diff --git a/package.json b/package.json index 49c869e..b41d648 100644 --- a/package.json +++ b/package.json @@ -12,5 +12,8 @@ "laravel-vite-plugin": "^3.1", "tailwindcss": "^4.0.0", "vite": "^8.0.0" + }, + "dependencies": { + "@sapphi-red/web-noise-suppressor": "^0.4.0" } } diff --git a/resources/js/audio-monitor.js b/resources/js/audio-monitor.js new file mode 100644 index 0000000..44c24cf --- /dev/null +++ b/resources/js/audio-monitor.js @@ -0,0 +1,105 @@ +/** + * Real-Time Voice Activity Detector (VAD) & Active Speaking Border Engine + */ + +// Easily configurable Tailwind CSS classes applied when a participant is actively speaking +export const SPEAKING_ACTIVE_CLASSES = [ + 'border-emerald-500/80', +]; + +export class AudioActivityMonitor { + constructor(speakingClasses = SPEAKING_ACTIVE_CLASSES) { + this.audioCtx = null; + this.monitors = new Map(); // key -> { source, analyser, animId, targetElemId } + this.speakingClasses = speakingClasses; + } + + getAudioContext() { + if (!this.audioCtx) { + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (AudioCtx) { + this.audioCtx = new AudioCtx(); + } + } + if (this.audioCtx && this.audioCtx.state === 'suspended') { + this.audioCtx.resume().catch(() => {}); + } + return this.audioCtx; + } + + attach(key, mediaStream, targetElemId, threshold = 12) { + this.detach(key); + if (!mediaStream || !mediaStream.getAudioTracks || mediaStream.getAudioTracks().length === 0) return; + + const ctx = this.getAudioContext(); + if (!ctx) return; + + try { + const source = ctx.createMediaStreamSource(mediaStream); + const analyser = ctx.createAnalyser(); + analyser.fftSize = 256; + analyser.smoothingTimeConstant = 0.3; + source.connect(analyser); + + const bufferLength = analyser.frequencyBinCount; + const dataArray = new Uint8Array(bufferLength); + + let isSpeaking = false; + let silenceTimer = null; + + const checkAudio = () => { + const entry = this.monitors.get(key); + if (!entry) return; + + analyser.getByteFrequencyData(dataArray); + let sum = 0; + for (let i = 0; i < bufferLength; i++) { + sum += dataArray[i]; + } + const average = sum / bufferLength; + + const elem = document.getElementById(targetElemId); + if (average > threshold) { + if (!isSpeaking) { + isSpeaking = true; + if (silenceTimer) clearTimeout(silenceTimer); + if (elem) { + elem.classList.add(...this.speakingClasses); + } + } else { + if (silenceTimer) clearTimeout(silenceTimer); + } + silenceTimer = setTimeout(() => { + isSpeaking = false; + if (elem) { + elem.classList.remove(...this.speakingClasses); + } + }, 350); + } + + entry.animId = requestAnimationFrame(checkAudio); + }; + + const animId = requestAnimationFrame(checkAudio); + this.monitors.set(key, { source, analyser, animId, targetElemId }); + } catch (e) { + console.log('VAD attach notice:', e); + } + } + + detach(key) { + if (this.monitors.has(key)) { + const m = this.monitors.get(key); + if (m.animId) cancelAnimationFrame(m.animId); + try { if (m.source) m.source.disconnect(); } catch(e) {} + try { if (m.analyser) m.analyser.disconnect(); } catch(e) {} + const elem = document.getElementById(m.targetElemId); + if (elem) { + elem.classList.remove(...this.speakingClasses); + } + this.monitors.delete(key); + } + } +} + +export const globalAudioMonitor = new AudioActivityMonitor(); diff --git a/resources/js/candidate-proctor.js b/resources/js/candidate-proctor.js index 4791d6b..92d9303 100644 --- a/resources/js/candidate-proctor.js +++ b/resources/js/candidate-proctor.js @@ -446,19 +446,18 @@ export function broadcastCandidateScreenStream(stream) { const targetPeerIds = new Set(); - // Collect dedicated screen receiver targets from active interviewers + // Collect dedicated screen receiver targets and main interviewer peers if (typeof window.latestActivePeers !== 'undefined' && Array.isArray(window.latestActivePeers)) { window.latestActivePeers.forEach(p => { if (p.peer_id && (p.peer_id.startsWith('interviewer_') || p.role === 'admin' || p.role === 'interviewer')) { const screenTargetId = p.peer_id.replace('interviewer_', 'interviewer_screen_'); targetPeerIds.add(screenTargetId); + targetPeerIds.add(p.peer_id); } }); } - if (targetPeerIds.size === 0) { - targetPeerIds.add(legacyScreenPeerId); - } + targetPeerIds.add(legacyScreenPeerId); const makeCalls = (peer) => { targetPeerIds.forEach(targetId => { @@ -626,12 +625,12 @@ export function updateScreenShareButton(active) { const btn = document.getElementById('share-screen-btn'); if (!btn) return; if (active) { - btn.innerHTML = '🛑 Stop Screen Sharing'; + btn.innerHTML = ' Stop Screen Sharing'; btn.style.background = '#ef4444'; btn.style.borderColor = '#dc2626'; btn.onclick = stopScreenShare; } else { - btn.innerHTML = '🖥️ Share Screen with Interviewer'; + btn.innerHTML = ' Share Screen with Interviewer'; btn.style.background = 'linear-gradient(135deg, #6366f1 0%, #0078d4 100%)'; btn.style.borderColor = '#6366f1'; btn.onclick = startScreenShare; diff --git a/resources/js/candidate-room.js b/resources/js/candidate-room.js index 7731286..8d0dc3a 100644 --- a/resources/js/candidate-room.js +++ b/resources/js/candidate-room.js @@ -5,10 +5,13 @@ */ import { safePlayMediaStream, getInitials } from './interview-call.js'; +import { globalAudioMonitor, SPEAKING_ACTIVE_CLASSES } from './audio-monitor.js'; import { initMeteredIceServers } from './metered.js'; +import { createNoiseSuppressedStream, getRNNoisePreference, setRNNoisePreference } from './noise-suppressor.js'; let editor = null; let candidateLocalStream = null; +let candidateNoiseSuppressor = null; let candidatePeerInstance = null; let candidatePeerConnection = null; let liveSyncChannel = null; @@ -437,22 +440,20 @@ export function addOrUpdateCandidateInterviewerTile(peerId, stream, labelName = if (!tile) { tile = document.createElement('div'); tile.id = 'cand-iv-tile-' + peerId; - tile.className = 'webcam-box'; - tile.style.position = 'relative'; - tile.style.borderColor = '#6366f1'; + tile.className = 'w-full aspect-[16/10] bg-black rounded-xl border-2 border-indigo-500/40 overflow-hidden relative shrink-0'; tile.innerHTML = ` - -
-
+ +
+
${initials}
-
${labelName}
-
Camera Turned Off
+
${labelName}
+
Camera Turned Off
-
- 🎙️ ${labelName} - | +
+ ${labelName} + |
@@ -477,7 +478,13 @@ export function addOrUpdateCandidateInterviewerTile(peerId, stream, labelName = camIcon.title = camOnVal ? 'Camera On' : 'Camera Off'; } if (placeholderEl) { - placeholderEl.style.display = camOnVal ? 'none' : 'flex'; + if (camOnVal) { + placeholderEl.classList.add('hidden'); + placeholderEl.classList.remove('flex'); + } else { + placeholderEl.classList.remove('hidden'); + placeholderEl.classList.add('flex'); + } } } @@ -492,7 +499,7 @@ export function addOrUpdateCandidateInterviewerTile(peerId, stream, labelName = const badge = document.getElementById('call-status-badge'); if (badge) { - badge.innerText = '🟢 CALL CONNECTED (LIVE)'; + badge.innerHTML = ' CALL LIVE'; badge.style.background = 'rgba(16,185,129,0.3)'; badge.style.color = '#34d399'; } @@ -500,6 +507,7 @@ export function addOrUpdateCandidateInterviewerTile(peerId, stream, labelName = } export function removeCandidateInterviewerTile(peerId) { + globalAudioMonitor.detach('cand-iv-video-' + peerId); const stream = candidateInterviewerTiles.get(peerId); if (stream && stream.active && latestCallStatus !== 'ended') { return; @@ -516,11 +524,11 @@ export function removeCandidateInterviewerTile(peerId) { const badge = document.getElementById('call-status-badge'); if (badge) { if (latestCallStatus === 'ended') { - badge.innerText = 'CALL ENDED BY HOST'; + badge.innerText = 'CALL ENDED'; badge.style.background = 'rgba(239,68,68,0.2)'; badge.style.color = '#fca5a5'; } else { - badge.innerText = 'READY (Waiting for Interviewer)'; + badge.innerText = 'READY'; badge.style.background = 'rgba(16,185,129,0.2)'; badge.style.color = '#34d399'; } @@ -550,7 +558,7 @@ export function triggerCandidateRing(offer = null, callStartedAt = null) { const badge = document.getElementById('call-status-badge'); if (badge) { - badge.innerText = '🔔 INCOMING CALL... RINGING'; + badge.innerHTML = ' INCOMING CALL... RINGING'; badge.style.background = 'rgba(234,179,8,0.3)'; badge.style.color = '#fde047'; } @@ -618,7 +626,7 @@ export function showCandidateJoinOption() { } const badge = document.getElementById('call-status-badge'); if (badge) { - badge.innerText = '📞 CALL IN PROGRESS'; + badge.innerText = 'CALL IN PROGRESS'; badge.style.background = 'rgba(59,130,246,0.3)'; badge.style.color = '#93c5fd'; } @@ -626,7 +634,7 @@ export function showCandidateJoinOption() { if (joinBtn) { joinBtn.style.display = 'block'; joinBtn.disabled = false; - joinBtn.innerText = '🟢 📞 Call in Progress • Join Call Now'; + joinBtn.innerHTML = ' Join Call Now'; } } @@ -679,7 +687,7 @@ export async function acceptCandidateCall() { const badge = document.getElementById('call-status-badge'); if (badge) { - badge.innerText = '🟢 CALL CONNECTED (LIVE)'; + badge.innerText = 'CALL CONNECTED'; badge.style.background = 'rgba(16,185,129,0.3)'; badge.style.color = '#34d399'; } @@ -759,6 +767,11 @@ export function candidateLeaveCall(isEndedByHost = false) { candidatePeerConnection = null; } + if (candidateNoiseSuppressor) { + try { candidateNoiseSuppressor.dispose(); } catch(e) {} + candidateNoiseSuppressor = null; + } + sendCandidatePeerHeartbeat('leave'); const interviewId = document.body.dataset.interviewId; @@ -791,7 +804,7 @@ export function candidateLeaveCall(isEndedByHost = false) { } } else { if (joinBtn) { - joinBtn.innerText = '🟢 📞 Rejoin Call Now'; + joinBtn.innerHTML = ' Rejoin Call Now'; joinBtn.style.display = 'block'; joinBtn.disabled = false; } @@ -962,8 +975,28 @@ export function startCandidateCameraStream() { .catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: true })) .catch(() => navigator.mediaDevices.getUserMedia({ video: false, audio: true })) .catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: false })) - .then(stream => { + .then(async rawStream => { if (window.endNativePrompt) window.endNativePrompt(); + + if (candidateNoiseSuppressor) { + try { candidateNoiseSuppressor.dispose(); } catch(e) {} + candidateNoiseSuppressor = null; + } + + let stream = rawStream; + if (rawStream && rawStream.getAudioTracks().length > 0) { + candidateNoiseSuppressor = await createNoiseSuppressedStream(rawStream); + const processedTrack = candidateNoiseSuppressor.getProcessedAudioTrack(); + const videoTracks = rawStream.getVideoTracks(); + const tracks = [...videoTracks]; + if (processedTrack) { + processedTrack.enabled = isCandidateMicEnabled; + tracks.push(processedTrack); + } + stream = new MediaStream(tracks); + updateCandidateNoiseSuppressionUI(candidateNoiseSuppressor.isEnabled()); + } + candidateLocalStream = stream; const vid = document.getElementById('webcam'); if (vid) { @@ -1080,28 +1113,65 @@ function debouncedCandidatePeerHeartbeat() { }, 300); } -export function toggleMic() { - if (!candidateLocalStream) return; - const audioTracks = candidateLocalStream.getAudioTracks(); - if (audioTracks.length > 0) { - isCandidateMicEnabled = !isCandidateMicEnabled; - audioTracks[0].enabled = isCandidateMicEnabled; - const btn = document.getElementById('toggle-mic-btn'); - if (btn) { - btn.innerText = isCandidateMicEnabled ? '🎤 Mic On' : '🔇 Mic Muted'; - btn.style.background = isCandidateMicEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)'; - btn.style.borderColor = isCandidateMicEnabled ? '#10b981' : '#ef4444'; +export function updateCandidateNoiseSuppressionUI(isEnabled) { + const btn = document.getElementById('toggle-candidate-noise-btn'); + if (btn) { + const span = btn.querySelector('span'); + if (span) span.textContent = isEnabled ? 'Noise Cancellation Active' : 'Noise Cancellation Deactivated'; + if (isEnabled) { + btn.className = 'w-full mb-2.5 py-1.5 px-2 text-xs font-semibold rounded-lg bg-emerald-500/20 border-none text-emerald-300 hover:bg-emerald-500/30 transition-all cursor-pointer flex items-center justify-center gap-1.5'; + btn.title = 'Noise Cancellation Active - Click to disable'; + } else { + btn.className = 'w-full mb-2.5 py-1.5 px-2 text-xs font-semibold rounded-lg bg-slate-800/80 border-none text-slate-400 hover:bg-slate-700/80 hover:text-slate-300 transition-all cursor-pointer flex items-center justify-center gap-1.5'; + btn.title = 'Noise Cancellation Disabled - Click to enable'; } - const icon = document.getElementById('cand-self-mic-icon'); - if (icon) { - icon.className = isCandidateMicEnabled ? 'fa-solid fa-microphone' : 'fa-solid fa-microphone-slash'; - icon.style.color = isCandidateMicEnabled ? '#34d399' : '#ef4444'; - icon.title = isCandidateMicEnabled ? 'Mic On' : 'Mic Muted'; - } - debouncedCandidatePeerHeartbeat(); } } +export function toggleCandidateNoiseSuppression() { + let isEnabled = false; + if (candidateNoiseSuppressor) { + isEnabled = candidateNoiseSuppressor.toggle(); + } else { + isEnabled = !getRNNoisePreference(); + setRNNoisePreference(isEnabled); + } + updateCandidateNoiseSuppressionUI(isEnabled); + return isEnabled; +} + +export function toggleMic() { + isCandidateMicEnabled = !isCandidateMicEnabled; + + if (candidateNoiseSuppressor) { + const processedTrack = candidateNoiseSuppressor.getProcessedAudioTrack(); + if (processedTrack) processedTrack.enabled = isCandidateMicEnabled; + const origTrack = candidateNoiseSuppressor.getOriginalAudioTrack(); + if (origTrack) origTrack.enabled = isCandidateMicEnabled; + } + + if (candidateLocalStream) { + const audioTracks = candidateLocalStream.getAudioTracks(); + if (audioTracks.length > 0) { + audioTracks[0].enabled = isCandidateMicEnabled; + } + } + + const btn = document.getElementById('toggle-mic-btn'); + if (btn) { + btn.innerHTML = ` ${isCandidateMicEnabled ? 'Mic On' : 'Mic Off'}`; + btn.style.background = isCandidateMicEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)'; + btn.className = `flex-1 py-2 px-2 text-xs font-semibold rounded-lg ${isCandidateMicEnabled ? 'bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30' : 'bg-red-500/20 text-red-300 hover:bg-red-500/30'} border-none transition-all cursor-pointer flex items-center justify-center gap-1.5`; + } + const icon = document.getElementById('cand-self-mic-icon'); + if (icon) { + icon.className = isCandidateMicEnabled ? 'fa-solid fa-microphone' : 'fa-solid fa-microphone-slash'; + icon.style.color = isCandidateMicEnabled ? '#34d399' : '#ef4444'; + icon.title = isCandidateMicEnabled ? 'Mic On' : 'Mic Muted'; + } + debouncedCandidatePeerHeartbeat(); +} + export function toggleCam() { const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder'); if (candidateLocalStream) { @@ -1111,9 +1181,9 @@ export function toggleCam() { videoTracks[0].enabled = isCandidateCamEnabled; const btn = document.getElementById('toggle-cam-btn'); if (btn) { - btn.innerText = isCandidateCamEnabled ? '📷 Cam On' : '🚫 Cam Off'; + btn.innerHTML = ` ${isCandidateCamEnabled ? 'Cam On' : 'Cam Off'}`; btn.style.background = isCandidateCamEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)'; - btn.style.borderColor = isCandidateCamEnabled ? '#10b981' : '#ef4444'; + btn.className = `flex-1 py-2 px-2 text-xs font-semibold rounded-lg ${isCandidateCamEnabled ? 'bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30' : 'bg-red-500/20 text-red-300 hover:bg-red-500/30'} border-none transition-all cursor-pointer flex items-center justify-center gap-1.5`; } if (avatarPlaceholder) avatarPlaceholder.style.display = isCandidateCamEnabled ? 'none' : 'flex'; } @@ -1471,6 +1541,8 @@ if (typeof window !== 'undefined') { window.candRingtone = candRingtone; window.toggleMic = toggleMic; window.toggleCam = toggleCam; + window.toggleCandidateNoiseSuppression = toggleCandidateNoiseSuppression; + window.updateCandidateNoiseSuppressionUI = updateCandidateNoiseSuppressionUI; window.sendCandidateMessage = sendCandidateMessage; window.pollCandidateChat = pollCandidateChat; window.initCandidateRoom = initCandidateRoom; diff --git a/resources/js/interview-call.js b/resources/js/interview-call.js index a3baa1c..cdbea41 100644 --- a/resources/js/interview-call.js +++ b/resources/js/interview-call.js @@ -5,6 +5,9 @@ */ import { initMeteredIceServers } from './metered.js'; +import { globalAudioMonitor, AudioActivityMonitor, SPEAKING_ACTIVE_CLASSES } from './audio-monitor.js'; +import { RecordingCompositor } from './recording-compositor.js'; +import { createNoiseSuppressedStream, getRNNoisePreference, setRNNoisePreference } from './noise-suppressor.js'; // --- Global Audio Ringtone Synthesizer Engine --- export class CallRingtoneEngine { @@ -145,6 +148,7 @@ export function getInterviewerScreenPeerId(userId = null) { : ('interviewer_screen_' + currentInterviewId + '_' + currentUserId); } let interviewerLocalStream = null; +let interviewerNoiseSuppressor = null; let activeCall = null; let isInterviewerMicOn = true; let isInterviewerCamOn = true; @@ -362,8 +366,71 @@ export function updateScreenshotToggleBtnUI(enabled) { } } -export function switchIdeTab(tab) { - const tabs = ['code', 'notes', 'drawing', 'recordings', 'screenshots']; +let currentInspectorTab = null; + +export function closeInspectorPanel() { + currentInspectorTab = null; + try { + if (currentInterviewId) { + sessionStorage.removeItem('interview_inspector_tab_' + currentInterviewId); + } + } catch(e) {} + + const details = document.getElementById('inspector-details'); + if (details) details.open = false; + + const tabs = ['logs', 'code', 'notes', 'drawing', 'recordings', 'screenshots']; + tabs.forEach(t => { + const contentEl = document.getElementById(`tab-content-${t}`); + const btnEl = document.getElementById(`tab-btn-${t}`); + if (contentEl) contentEl.style.display = 'none'; + if (btnEl) { + btnEl.classList.remove('bg-indigo-600', 'text-white'); + btnEl.classList.add('text-slate-400', 'hover:bg-white/5'); + } + }); +} + +export function switchIdeTab(tab, event = null) { + if (event) { + event.stopPropagation(); + } + + const details = document.getElementById('inspector-details'); + + // If user clicks the currently active open tab button, toggle it collapsed + if (currentInspectorTab === tab && details && details.open) { + closeInspectorPanel(); + return; + } + + currentInspectorTab = tab; + try { + if (currentInterviewId) { + sessionStorage.setItem('interview_inspector_tab_' + currentInterviewId, tab); + } + } catch(e) {} + + if (details) details.open = true; + + const tabs = ['logs', 'code', 'notes', 'drawing', 'recordings', 'screenshots']; + const tabMeta = { + logs: { title: 'Proctoring Logs', icon: 'fa-solid fa-shield-halved' }, + notes: { title: 'Candidate Notepad', icon: 'fa-solid fa-note-sticky' }, + drawing: { title: 'Candidate Drawing Board', icon: 'fa-solid fa-pen' }, + recordings: { title: 'Saved Video Recordings', icon: 'fa-solid fa-film' }, + screenshots: { title: 'Tab Switch Screenshots', icon: 'fa-solid fa-image' }, + code: { title: 'Candidate Code', icon: 'fa-solid fa-code' } + }; + + const floatingTitle = document.getElementById('inspector-floating-text'); + const floatingIcon = document.getElementById('inspector-floating-icon'); + + if (tabMeta[tab]) { + if (floatingTitle) floatingTitle.innerText = tabMeta[tab].title; + if (floatingIcon) floatingIcon.className = `${tabMeta[tab].icon} text-indigo-400`; + } + tabs.forEach(t => { const contentEl = document.getElementById(`tab-content-${t}`); const btnEl = document.getElementById(`tab-btn-${t}`); @@ -372,16 +439,26 @@ export function switchIdeTab(tab) { } if (btnEl) { if (t === tab) { - btnEl.classList.add('bg-indigo-600', 'text-white', 'border-indigo-500'); - btnEl.classList.remove('bg-white/5', 'text-slate-400', 'border-slate-700/60'); + btnEl.classList.add('bg-indigo-600', 'text-white'); + btnEl.classList.remove('text-slate-400', 'hover:bg-white/5'); } else { - btnEl.classList.remove('bg-indigo-600', 'text-white', 'border-indigo-500'); - btnEl.classList.add('bg-white/5', 'text-slate-400', 'border-slate-700/60'); + btnEl.classList.remove('bg-indigo-600', 'text-white'); + btnEl.classList.add('text-slate-400', 'hover:bg-white/5'); } } }); } +// Click outside to dismiss floating inspector details +if (typeof document !== 'undefined') { + document.addEventListener('click', function(e) { + const details = document.getElementById('inspector-details'); + if (details && details.open && !details.contains(e.target)) { + closeInspectorPanel(); + } + }); +} + export function triggerIncomingCallRing(callData, isRealtimeBroadcast = false) { if (!callData || !callData.id) return; if (typeof document !== 'undefined' && document.body && document.body.dataset.interviewId) return; @@ -593,6 +670,7 @@ export function openReviewModal(id, name, uid, autoJoinCall = false) { toggleSw.classList.add('on'); } } + updateInterviewerNoiseSuppressionUI(interviewerNoiseSuppressor ? interviewerNoiseSuppressor.isEnabled() : getRNNoisePreference()); const candNameEl = document.getElementById('modal-cand-name'); const candUidEl = document.getElementById('modal-cand-uid'); @@ -609,7 +687,24 @@ export function openReviewModal(id, name, uid, autoJoinCall = false) { if (reviewModal) reviewModal.classList.add('active'); resetZoomScreen(); - switchIdeTab('code'); + if (document.getElementById('inspector-content-container')) { + let savedInspectorTab = null; + try { + savedInspectorTab = sessionStorage.getItem('interview_inspector_tab_' + id); + } catch(e) {} + + if (savedInspectorTab) { + switchIdeTab(savedInspectorTab); + } else { + closeInspectorPanel(); + } + } else if (document.getElementById('tab-btn-logs')) { + switchIdeTab('logs'); + } else if (document.getElementById('tab-btn-notes')) { + switchIdeTab('notes'); + } else { + switchIdeTab('code'); + } updateCandidateStatusIcons(false, false, false); initInterviewerSigChannel(); @@ -783,6 +878,9 @@ export function pollReviewData() { const screenPlace = document.getElementById('screen-video-placeholder'); if (screenVid) screenVid.srcObject = null; if (screenPlace) screenPlace.style.display = 'flex'; + if (typeof window.updateScreenShareLayout === 'function') { + window.updateScreenShareLayout(false); + } panelistMeshTiles.forEach((_, pid) => { removePanelistTile(pid); @@ -888,6 +986,77 @@ export function pollReviewData() { recList = [{ url: recPath, created_at: new Date().toISOString(), original_index: 0 }]; } + // Auto-clear one-time processing notice if new recordings arrived + if (isRecordingProcessing && recList.length > recordingKnownCountBeforeProcessing) { + isRecordingProcessing = false; + recordingProcessingSessionId = null; + } + + let processingBannerHtml = ''; + if (isRecordingProcessing) { + processingBannerHtml = ` +
+ +
+ Processing Call Recording… +
Your video recording is currently being assembled on the server. It will appear here shortly with a download link once ready.
+
+ +
`; + } + +function formatDurationBadgeText(sec) { + if (!sec || isNaN(sec) || sec <= 0) return null; + const m = Math.floor(sec / 60); + const s = Math.round(sec % 60); + return m > 0 ? `${m}m ${String(s).padStart(2, '0')}s` : `${s}s`; +} + +function resolveMediaDuration(videoUrl, badgeElementId, fallbackDuration = 0) { + const el = document.getElementById(badgeElementId); + if (!el) return; + + if (fallbackDuration && fallbackDuration > 0) { + const text = formatDurationBadgeText(fallbackDuration); + if (text) { + el.innerHTML = ` ${text}`; + el.style.display = 'inline-flex'; + return; + } + } + + if (!videoUrl) return; + + const v = document.createElement('video'); + v.preload = 'metadata'; + v.src = videoUrl; + + const applyDuration = (d) => { + if (!d || isNaN(d) || d <= 0) return; + const text = formatDurationBadgeText(d); + const targetEl = document.getElementById(badgeElementId); + if (text && targetEl) { + targetEl.innerHTML = ` ${text}`; + targetEl.style.display = 'inline-flex'; + } + }; + + v.onloadedmetadata = function() { + if (v.duration && !isNaN(v.duration) && v.duration !== Infinity && v.duration > 0) { + applyDuration(v.duration); + } else { + // Workaround for WebM streaming containers where duration is Infinity until seeked + v.currentTime = 1e101; + v.ontimeupdate = function() { + v.ontimeupdate = null; + if (v.currentTime && !isNaN(v.currentTime) && v.currentTime > 0) { + applyDuration(v.currentTime); + } + }; + } + }; +} + if (recList.length > 0) { recList.sort((a, b) => { const timeA = a.created_at ? new Date(a.created_at).getTime() : 0; @@ -895,12 +1064,11 @@ export function pollReviewData() { return timeB - timeA; }); - let recHtml = `
- 📹 Stored Video Sessions (${recList.length} recording${recList.length > 1 ? 's' : ''}) - 📜 Scroll to view older recordings -
`; + let recHtml = processingBannerHtml + `
`; recList.forEach((r, displayIdx) => { + const recNum = recList.length - displayIdx; + const origIdx = (typeof r === 'object' && r.original_index !== undefined) ? r.original_index : displayIdx; let videoUrl = typeof r === 'string' ? r : (r.stream_url || r.url || recPath); if (videoUrl && !videoUrl.startsWith('http') && !videoUrl.startsWith('/')) { videoUrl = '/' + videoUrl; @@ -908,32 +1076,84 @@ export function pollReviewData() { if (videoUrl && videoUrl.includes('/storage/')) { videoUrl = videoUrl.replace('/storage/', '/media-stream/'); } - const origIdx = (typeof r === 'object' && r.original_index !== undefined) ? r.original_index : displayIdx; const dateObj = (r && r.created_at) ? new Date(r.created_at) : new Date(); - const dateStr = dateObj.toLocaleDateString() + ' ' + dateObj.toLocaleTimeString(); + const dateFormatted = dateObj.toLocaleDateString(undefined, { + month: 'short', + day: 'numeric', + year: 'numeric' + }); + const timeFormatted = dateObj.toLocaleTimeString(undefined, { + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + hour12: true + }); const downloadUrl = (typeof r === 'object' && r.download_url) ? r.download_url : (`/interviews/${currentInterviewId}/download-recording?index=${origIdx}`); - const mimeType = (typeof r === 'object' && r.mime_type) ? r.mime_type : ((videoUrl && videoUrl.includes('.mp4')) ? 'video/mp4' : 'video/webm'); + const badgeId = `rec-duration-badge-${origIdx}-${displayIdx}`; + const initialDuration = (r && r.duration && r.duration > 0) ? r.duration : 0; + const initialDurationText = formatDurationBadgeText(initialDuration); - recHtml += `
-
-
- 📹 Session Recording #${recList.length - displayIdx} - 📅 ${dateStr} + recHtml += ` + `; }); + recHtml += `
`; recContainer.innerHTML = recHtml; + + // Dynamically resolve media duration for all cards + recList.forEach((r, displayIdx) => { + const origIdx = (typeof r === 'object' && r.original_index !== undefined) ? r.original_index : displayIdx; + let videoUrl = typeof r === 'string' ? r : (r.stream_url || r.url || recPath); + if (videoUrl && !videoUrl.startsWith('http') && !videoUrl.startsWith('/')) { + videoUrl = '/' + videoUrl; + } + if (videoUrl && videoUrl.includes('/storage/')) { + videoUrl = videoUrl.replace('/storage/', '/media-stream/'); + } + const badgeId = `rec-duration-badge-${origIdx}-${displayIdx}`; + const initialDuration = (r && r.duration && r.duration > 0) ? r.duration : 0; + resolveMediaDuration(videoUrl, badgeId, initialDuration); + }); } else { - recContainer.innerHTML = '
No video recordings saved for this candidate yet.
'; + recContainer.innerHTML = processingBannerHtml + ` +
+
+ +
+

No video recordings saved yet

+

Recordings captured during the call will appear here for download.

+
`; } } @@ -957,7 +1177,7 @@ export function pollReviewData() { const badgeLabel = isCand ? 'Candidate' : 'Panelist'; const badgeClass = isCand ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-indigo-500/20 text-indigo-300 border-indigo-500/30'; - chatHtml += `
+ chatHtml += `
@@ -969,11 +1189,11 @@ export function pollReviewData() {
${w.message}
`; }); - chatHistory.className = 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] h-[150px] overflow-y-auto p-3 flex flex-col gap-2 mb-2.5'; + chatHistory.className = 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] h-full overflow-y-auto p-3 flex flex-col gap-2 mb-2.5'; chatHistory.innerHTML = chatHtml; chatHistory.scrollTop = chatHistory.scrollHeight; } else { - chatHistory.className = 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] h-[150px] overflow-y-auto p-3 mb-2.5'; + chatHistory.className = 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] h-full overflow-y-auto p-3 mb-2.5'; chatHistory.innerHTML = '
No chat history. Send a message below.
'; } } @@ -1371,7 +1591,7 @@ export function blockCandidateAction() { } } -export { initMeteredIceServers }; +export { initMeteredIceServers, globalAudioMonitor, AudioActivityMonitor, SPEAKING_ACTIVE_CLASSES }; export function safePlayMediaStream(videoElem, stream, isSelf = false) { if (!videoElem || !stream) return; @@ -1382,6 +1602,33 @@ export function safePlayMediaStream(videoElem, stream, isSelf = false) { if (videoElem.srcObject !== stream) { videoElem.srcObject = stream; } + + // Attach dynamic emerald speaking border VAD monitor + if (!isScreenShare && stream.getAudioTracks && stream.getAudioTracks().length > 0) { + let targetId = null; + let monitorKey = videoElem.id; + + if (videoElem.id === 'interviewer-cand-video') { + targetId = 'cand-video-wrapper'; + } else if (videoElem.id === 'interviewer-self-video') { + targetId = 'self-video-wrapper'; + } else if (videoElem.id === 'webcam') { + targetId = 'cand-self-video-box'; + } else if (videoElem.id === 'interviewer-video-default') { + targetId = 'interviewer-placeholder-box'; + } else if (videoElem.id.startsWith('panelist-video-')) { + const pid = videoElem.id.replace('panelist-video-', ''); + targetId = 'panelist-tile-' + pid; + } else if (videoElem.id.startsWith('cand-iv-video-')) { + const pid = videoElem.id.replace('cand-iv-video-', ''); + targetId = 'cand-iv-tile-' + pid; + } + + if (targetId) { + globalAudioMonitor.attach(monitorKey, stream, targetId); + } + } + const playPromise = videoElem.play(); if (playPromise !== undefined) { playPromise.catch(err => { @@ -1419,7 +1666,7 @@ export function addOrUpdatePanelistTile(peerId, stream, name = 'Panelist', micOn if (!tile) { tile = document.createElement('div'); tile.id = 'panelist-tile-' + peerId; - tile.className = 'video-tile relative aspect-[16/11] bg-[#0d1220] border border-[#1b2233] rounded-[10px] overflow-hidden flex flex-col items-center justify-center transition-all'; + tile.className = 'video-tile relative w-[220px] aspect-video shrink-0 bg-[#0d1220] border border-[#1b2233] rounded-[10px] overflow-hidden flex flex-col items-center justify-center transition-all duration-200'; tile.innerHTML = ` @@ -1474,6 +1721,7 @@ export function addOrUpdatePanelistTile(peerId, stream, name = 'Panelist', micOn } export function removePanelistTile(peerId) { + globalAudioMonitor.detach('panelist-video-' + peerId); const tile = document.getElementById('panelist-tile-' + peerId); if (tile) tile.remove(); panelistMeshTiles.delete(peerId); @@ -1513,6 +1761,18 @@ export async function initInterviewerPeer() { console.log('[WebRTC Screen] Attaching incoming screen stream to video element'); const screenVid = document.getElementById('interviewer-screen-video'); const placeholder = document.getElementById('screen-video-placeholder'); + if (typeof window.updateScreenShareLayout === 'function') { + window.updateScreenShareLayout(true); + } + if (screenStream && screenStream.getVideoTracks) { + screenStream.getVideoTracks().forEach(track => { + track.onended = () => { + if (typeof window.updateScreenShareLayout === 'function') { + window.updateScreenShareLayout(false); + } + }; + }); + } if (screenVid && screenStream) { screenVid.muted = true; if (screenVid.srcObject !== screenStream) { @@ -1724,7 +1984,25 @@ export function startInterviewerCall(isRejoin = false) { body: JSON.stringify({ call_status: 'active', is_rejoin: isRejoin }) }); - const handleStream = (stream) => { + const handleStream = async (rawStream) => { + if (interviewerNoiseSuppressor) { + try { interviewerNoiseSuppressor.dispose(); } catch(e) {} + interviewerNoiseSuppressor = null; + } + + let stream = rawStream; + if (rawStream && rawStream.getAudioTracks().length > 0) { + interviewerNoiseSuppressor = await createNoiseSuppressedStream(rawStream); + const processedTrack = interviewerNoiseSuppressor.getProcessedAudioTrack(); + const videoTracks = rawStream.getVideoTracks(); + const tracks = [...videoTracks]; + if (processedTrack) { + processedTrack.enabled = isInterviewerMicOn; + tracks.push(processedTrack); + } + stream = new MediaStream(tracks); + } + interviewerLocalStream = stream; const selfVid = document.getElementById('interviewer-self-video'); const selfPlace = document.getElementById('self-video-placeholder'); @@ -1749,6 +2027,7 @@ export function startInterviewerCall(isRejoin = false) { if (recStartBtn && (!adminMediaRecorder || adminMediaRecorder.state === 'inactive')) { recStartBtn.style.display = 'inline-flex'; } + updateInterviewerNoiseSuppressionUI(interviewerNoiseSuppressor ? interviewerNoiseSuppressor.isEnabled() : getRNNoisePreference()); if (interviewerSigChannel) { interviewerSigChannel.postMessage({ type: 'interviewer_joined', sender: 'interviewer' }); @@ -1883,6 +2162,10 @@ export function leaveInterviewerCall(isEndAll = false) { } catch(e) {} interviewerLocalStream = null; } + if (interviewerNoiseSuppressor) { + try { interviewerNoiseSuppressor.dispose(); } catch(e) {} + interviewerNoiseSuppressor = null; + } if (activeCall) { try { activeCall.close(); } catch(e) {} activeCall = null; @@ -1961,6 +2244,10 @@ export function leaveInterviewerCall(isEndAll = false) { const recStopBtn = document.getElementById('btn-stop-recording'); if (recStopBtn) recStopBtn.style.display = 'none'; + + const recUploadBtn = document.getElementById('btn-uploading-recording'); + if (recUploadBtn) recUploadBtn.style.display = 'none'; + if (adminMediaRecorder && adminMediaRecorder.state !== 'inactive') { try { adminMediaRecorder.stop(); } catch(e) {} } @@ -2006,10 +2293,199 @@ export function endCallForAll() { } } -// MediaRecorder recording +// MediaRecorder, Chunked Uploader & Recording Compositor let adminMediaRecorder = null; -let adminRecordedChunks = []; -let recAudioContext = null; +let recordingCompositor = null; +let recordingTimerInterval = null; +let recordingStartTime = null; + +let isRecordingProcessing = false; +let recordingProcessingSessionId = null; +let recordingKnownCountBeforeProcessing = 0; +let currentChunkIndex = 0; +let chunkUploadQueue = []; +let currentRecordingSessionId = null; +let isStopRecordingRequested = false; +let totalRecordedChunksCount = 0; +let isFinalizingRecording = false; +const MAX_CONCURRENT_UPLOADS = 2; +let activeUploadsCount = 0; + +window.dismissRecordingProcessingBanner = function() { + isRecordingProcessing = false; + recordingProcessingSessionId = null; + const b = document.getElementById('recording-processing-banner'); + if (b) b.remove(); +}; + +function updateRecordingButtonProgress(isFinalStep = false) { + const total = Math.max(1, totalRecordedChunksCount || currentChunkIndex || 1); + const uploaded = chunkUploadQueue.filter(item => item.isUploaded && !item.isFinal).length; + + let pct = isFinalStep ? 100 : Math.min(92, Math.max(15, Math.round((uploaded / total) * 90))); + + const recStopBtn = document.getElementById('btn-stop-recording'); + if (!recStopBtn) return; + + if (isFinalStep) { + recStopBtn.innerHTML = 'Saved!'; + } else { + recStopBtn.innerHTML = 'Saving ' + pct + '%'; + } +} + +let currentSessionDuration = 0; + +function queueChunkUpload(chunkBlob, isFinal = false, duration = null) { + if (!currentRecordingSessionId) return; + + if (chunkBlob && chunkBlob.size > 0) { + const index = currentChunkIndex++; + chunkUploadQueue.push({ + sessionId: currentRecordingSessionId, + index: index, + blob: chunkBlob, + isFinal: false, + isUploading: false, + isUploaded: false, + retries: 0 + }); + } + + if (isFinal) { + totalRecordedChunksCount = currentChunkIndex; + chunkUploadQueue.push({ + sessionId: currentRecordingSessionId, + index: currentChunkIndex, + blob: null, + isFinal: true, + totalChunks: currentChunkIndex, + duration: duration || currentSessionDuration || 0, + isUploading: false, + isUploaded: false, + retries: 0 + }); + } + + if (isStopRecordingRequested) { + updateRecordingButtonProgress(false); + } + + triggerChunkQueueProcessing(); +} + +function triggerChunkQueueProcessing() { + // 1. Dispatch concurrent data uploads + while (activeUploadsCount < MAX_CONCURRENT_UPLOADS) { + const nextItem = chunkUploadQueue.find(item => !item.isUploading && !item.isUploaded && !item.isFinal); + if (!nextItem) break; + uploadSingleChunk(nextItem); + } + + // 2. Dispatch finalization trigger once all data chunks are confirmed uploaded + const hasPendingDataChunks = chunkUploadQueue.some(item => !item.isUploaded && !item.isFinal); + const finalMarker = chunkUploadQueue.find(item => item.isFinal && !item.isUploading && !item.isUploaded); + + if (!hasPendingDataChunks && finalMarker && activeUploadsCount === 0 && !isFinalizingRecording) { + isFinalizingRecording = true; + uploadSingleChunk(finalMarker); + } +} + +async function uploadSingleChunk(item) { + item.isUploading = true; + activeUploadsCount++; + + if (!currentInterviewId && typeof document !== 'undefined') { + currentInterviewId = document.body?.dataset?.interviewId || window.interviewId; + } + if (!currentInterviewId) { + console.error('[Recording Chunk] Missing currentInterviewId'); + item.isUploading = false; + activeUploadsCount--; + return; + } + + const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || window.csrfToken; + const formData = new FormData(); + formData.append('session_id', item.sessionId); + formData.append('chunk_index', item.index); + formData.append('is_final', item.isFinal ? '1' : '0'); + formData.append('total_chunks', item.totalChunks || currentChunkIndex); + if (item.duration) { + formData.append('duration', item.duration); + } + formData.append('_token', csrfToken); + if (item.blob && item.blob.size > 0) { + formData.append('chunk', item.blob, `part_${item.index}.webm`); + } + + try { + const response = await fetch(`/candidate/upload-recording-chunk/${currentInterviewId}`, { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'X-CSRF-TOKEN': csrfToken, + 'X-Requested-With': 'XMLHttpRequest' + }, + body: formData + }); + + if (!response.ok) { + const errText = await response.text(); + throw new Error(`HTTP ${response.status}: ${errText}`); + } + + const resJson = await response.json(); + item.isUploading = false; + item.isUploaded = true; + activeUploadsCount--; + + if (isStopRecordingRequested) { + updateRecordingButtonProgress(item.isFinal); + } + + if (item.isFinal) { + console.log('[Recording Chunk] Final chunk processed by server:', resJson); + isRecordingProcessing = true; + recordingProcessingSessionId = item.sessionId; + isStopRecordingRequested = false; + isFinalizingRecording = false; + updateRecordingButtonProgress(true); + pollReviewData(); + + setTimeout(() => { + const stopBtn = document.getElementById('btn-stop-recording'); + const startBtn = document.getElementById('btn-start-recording'); + if (stopBtn) { + stopBtn.style.display = 'none'; + stopBtn.disabled = false; + stopBtn.className = 'hidden inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white shadow-sm animate-pulse transition-all cursor-pointer'; + stopBtn.innerHTML = ' Recording (00:00) - Stop'; + } + if (startBtn) startBtn.style.display = 'inline-flex'; + }, 1200); + } + + triggerChunkQueueProcessing(); + } catch(err) { + console.warn(`[Recording Chunk] Upload failed for chunk ${item.index} (attempt ${item.retries + 1}):`, err); + item.isUploading = false; + activeUploadsCount--; + item.retries++; + + if (item.retries < 5) { + setTimeout(() => { + triggerChunkQueueProcessing(); + }, item.retries * 800); + } else { + console.error(`[Recording Chunk] Critical upload failure for chunk ${item.index}. Retrying after delay...`); + setTimeout(() => { + triggerChunkQueueProcessing(); + }, 2500); + } + } +} export function startCallRecording() { if (!currentInterviewId) { @@ -2022,75 +2498,88 @@ export function startCallRecording() { } const candVid = document.getElementById('interviewer-cand-video'); - const candidateStream = (candVid && candVid.srcObject) ? candVid.srcObject : null; - const streamToRecord = new MediaStream(); + const candNameEl = document.getElementById('modal-cand-name'); + const candidateName = candNameEl ? candNameEl.innerText.trim() : 'Candidate'; - if (candidateStream) { - candidateStream.getVideoTracks().forEach(track => { - if (track.readyState === 'live') { - try { streamToRecord.addTrack(track); } catch(e) {} - } - }); - } + // 1. Initialize RecordingCompositor (1280x720 @ 24fps for ultra-fast, smooth streaming) + recordingCompositor = new RecordingCompositor({ + width: 1280, + height: 720, + fps: 24, + getParticipantsData: () => { + const candStream = (candVid && candVid.srcObject) ? candVid.srcObject : null; + const candCamIcon = document.getElementById('cand-cam-status'); + const candMicIcon = document.getElementById('cand-mic-status'); + const isCandCamOn = candCamIcon ? candCamIcon.classList.contains('fa-video') : true; + const isCandMicOn = candMicIcon ? candMicIcon.classList.contains('fa-microphone') : true; - if (streamToRecord.getVideoTracks().length === 0 && interviewerLocalStream) { - interviewerLocalStream.getVideoTracks().forEach(track => { - if (track.readyState === 'live') { - try { streamToRecord.addTrack(track); } catch(e) {} - } - }); - } + const panelistsList = []; + const panelistStreamsList = []; - const candAudioTracks = candidateStream ? candidateStream.getAudioTracks().filter(t => t.readyState === 'live') : []; - const adminAudioTracks = interviewerLocalStream ? interviewerLocalStream.getAudioTracks().filter(t => t.readyState === 'live') : []; + panelistMeshTiles.forEach((stream, pid) => { + const peerInfo = latestActivePeers.find(p => p.peer_id === pid); + const pMicEl = document.getElementById('mesh-mic-' + pid); + const pCamEl = document.getElementById('mesh-cam-' + pid); + const isMicOn = pMicEl ? pMicEl.classList.contains('fa-microphone') : (peerInfo ? isTrueVal(peerInfo.mic_on) : true); + const isCamOn = pCamEl ? pCamEl.classList.contains('fa-video') : (peerInfo ? isTrueVal(peerInfo.cam_on) : true); + const pName = peerInfo ? (peerInfo.name || 'Panelist') : 'Panelist'; + const pRole = peerInfo ? (peerInfo.role === 'admin' ? 'Admin' : 'Panelist') : 'Panelist'; - if (candAudioTracks.length > 0 || adminAudioTracks.length > 0) { - try { - const AudioContextClass = window.AudioContext || window.webkitAudioContext; - if (recAudioContext) { - try { recAudioContext.close(); } catch(e) {} - } - recAudioContext = new AudioContextClass(); - const audioDestination = recAudioContext.createMediaStreamDestination(); + panelistsList.push({ + peerId: pid, + name: pName, + role: pRole, + micOn: isMicOn, + camOn: isCamOn + }); - if (candAudioTracks.length > 0) { - const candAudioStream = new MediaStream(candAudioTracks); - const candSource = recAudioContext.createMediaStreamSource(candAudioStream); - candSource.connect(audioDestination); - } + if (stream) { + panelistStreamsList.push({ peerId: pid, stream: stream }); + } + }); - if (adminAudioTracks.length > 0) { - const adminAudioStream = new MediaStream(adminAudioTracks); - const adminSource = recAudioContext.createMediaStreamSource(adminAudioStream); - adminSource.connect(audioDestination); - } - - const mixedAudioTrack = audioDestination.stream.getAudioTracks()[0]; - if (mixedAudioTrack) { - streamToRecord.addTrack(mixedAudioTrack); - } - } catch(e) { - const fallbackAudio = candAudioTracks[0] || adminAudioTracks[0]; - if (fallbackAudio) { - try { streamToRecord.addTrack(fallbackAudio); } catch(err) {} - } + return { + candidateStream: candStream, + candidateName: candidateName, + candidateCamOn: isCandCamOn, + candidateMicOn: isCandMicOn, + selfStream: interviewerLocalStream, + selfName: window.currentUserName || 'Interviewer', + selfCamOn: isInterviewerCamOn, + selfMicOn: isInterviewerMicOn, + panelists: panelistsList, + panelistStreams: panelistStreamsList + }; } - } + }); - const activeTracks = streamToRecord.getTracks().filter(t => t.readyState === 'live'); - if (activeTracks.length === 0) { - alert('No active video/audio stream available to record. Please start or join the call first.'); - return; - } - - adminRecordedChunks = []; try { - let options = {}; + recordingCompositor.start(); + const streamToRecord = recordingCompositor.getStream(); + + currentRecordingSessionId = 'rec_' + currentInterviewId + '_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7); + currentChunkIndex = 0; + chunkUploadQueue = []; + isStopRecordingRequested = false; + totalRecordedChunksCount = 0; + isFinalizingRecording = false; + activeUploadsCount = 0; + currentSessionDuration = 0; + + const existingCards = document.querySelectorAll('#modal-recordings-container .recording-card, #modal-recordings-container video'); + recordingKnownCountBeforeProcessing = existingCards ? existingCards.length : 0; + + // Controlled bitrate configuration (1.2 Mbps video, 64 kbps audio) + let options = { + videoBitsPerSecond: 1200000, + audioBitsPerSecond: 64000 + }; + if (typeof MediaRecorder.isTypeSupported === 'function') { if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8,opus')) { - options = { mimeType: 'video/webm;codecs=vp8,opus' }; + options.mimeType = 'video/webm;codecs=vp8,opus'; } else if (MediaRecorder.isTypeSupported('video/webm')) { - options = { mimeType: 'video/webm' }; + options.mimeType = 'video/webm'; } } @@ -2100,62 +2589,93 @@ export function startCallRecording() { adminMediaRecorder = new MediaRecorder(streamToRecord); } + // Real-time chunk slice handler adminMediaRecorder.ondataavailable = function(e) { if (e.data && e.data.size > 0) { - adminRecordedChunks.push(e.data); + queueChunkUpload(e.data, false); } }; adminMediaRecorder.onstop = function() { - if (recAudioContext) { - try { recAudioContext.close(); } catch(e) {} - recAudioContext = null; + if (recordingCompositor) { + recordingCompositor.stop(); + recordingCompositor = null; } - if (adminRecordedChunks.length === 0) return; - const recMime = adminMediaRecorder.mimeType || 'video/webm'; - const isMp4 = recMime.includes('mp4'); - const ext = isMp4 ? 'mp4' : 'webm'; - const blobType = isMp4 ? 'video/mp4' : 'video/webm'; - - const blob = new Blob(adminRecordedChunks, { type: blobType }); - uploadRecordedBlob(blob, ext); + // Signal finalization after the final slice is recorded + queueChunkUpload(null, true, currentSessionDuration); }; - adminMediaRecorder.start(1000); + // Start timeslice recording (6,000ms = 6s chunks ~800KB each for near-instant concurrent background uploads) + adminMediaRecorder.start(6000); + recordingStartTime = Date.now(); + // Update UI buttons & Live Timer const recStartBtn = document.getElementById('btn-start-recording'); const recStopBtn = document.getElementById('btn-stop-recording'); if (recStartBtn) recStartBtn.style.display = 'none'; - if (recStopBtn) recStopBtn.style.display = 'inline-flex'; - - if (typeof window.Swal !== 'undefined') { - window.Swal.fire({ - icon: 'info', - title: 'Recording Started', - text: 'Interview call recording is active (silent mode - candidate is not notified).', - toast: true, - position: 'top-end', - timer: 3000, - showConfirmButton: false - }); + if (recStopBtn) { + recStopBtn.style.display = 'inline-flex'; + recStopBtn.disabled = false; + recStopBtn.className = 'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-rose-600 hover:bg-rose-700 text-white shadow-sm animate-pulse transition-all'; + recStopBtn.innerHTML = ' Recording (00:00) - Stop'; } + + if (recordingTimerInterval) clearInterval(recordingTimerInterval); + recordingTimerInterval = setInterval(() => { + const timerEl = document.getElementById('rec-live-timer'); + if (timerEl && recordingStartTime) { + const totalSec = Math.floor((Date.now() - recordingStartTime) / 1000); + const mins = String(Math.floor(totalSec / 60)).padStart(2, '0'); + const secs = String(totalSec % 60).padStart(2, '0'); + timerEl.innerText = `(${mins}:${secs})`; + } + }, 1000); } catch(e) { + if (recordingCompositor) { + recordingCompositor.stop(); + recordingCompositor = null; + } alert('Recording failed to initialize: ' + e.message); } } export function stopCallRecording() { + if (recordingTimerInterval) { + clearInterval(recordingTimerInterval); + recordingTimerInterval = null; + } + isStopRecordingRequested = true; + + currentSessionDuration = recordingStartTime ? Math.max(1, Math.round((Date.now() - recordingStartTime) / 1000)) : 0; + + const recStartBtn = document.getElementById('btn-start-recording'); + const recStopBtn = document.getElementById('btn-stop-recording'); + + if (recStartBtn) recStartBtn.style.display = 'none'; + if (recStopBtn) { + recStopBtn.style.display = 'inline-flex'; + recStopBtn.disabled = true; + recStopBtn.className = 'relative inline-flex items-center gap-2 px-3.5 py-1.5 text-xs font-semibold text-white bg-indigo-600 rounded-lg shadow-lg shadow-indigo-500/50 ring-2 ring-indigo-400 ring-offset-2 ring-offset-slate-900 animate-pulse transition-all'; + recStopBtn.innerHTML = 'Saving 15%'; + } + if (adminMediaRecorder && adminMediaRecorder.state !== 'inactive') { adminMediaRecorder.stop(); } - const recStartBtn = document.getElementById('btn-start-recording'); - const recStopBtn = document.getElementById('btn-stop-recording'); - if (recStartBtn) recStartBtn.style.display = 'inline-flex'; - if (recStopBtn) recStopBtn.style.display = 'none'; + if (recordingCompositor) { + recordingCompositor.stop(); + recordingCompositor = null; + } } export function uploadRecordedBlob(blob, ext = 'webm') { - if (!currentInterviewId) return; + if (!currentInterviewId && typeof document !== 'undefined') { + currentInterviewId = document.body?.dataset?.interviewId || window.interviewId; + } + if (!currentInterviewId) { + console.error('Cannot upload recording: missing interview ID'); + return; + } const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || window.csrfToken; const formData = new FormData(); @@ -2164,16 +2684,44 @@ export function uploadRecordedBlob(blob, ext = 'webm') { fetch(`/candidate/upload-recording/${currentInterviewId}`, { method: 'POST', + headers: { + 'Accept': 'application/json', + 'X-CSRF-TOKEN': csrfToken, + 'X-Requested-With': 'XMLHttpRequest' + }, body: formData }) - .then(r => r.json()) + .then(async r => { + const contentType = r.headers.get('content-type') || ''; + const isJson = contentType.includes('application/json'); + if (!r.ok) { + const errText = await r.text(); + let errMsg = `Upload failed (HTTP ${r.status})`; + if (isJson) { + try { + const errJson = JSON.parse(errText); + if (errJson && errJson.message) errMsg = errJson.message; + } catch(e) {} + } + throw new Error(errMsg); + } + if (isJson) { + return r.json(); + } + const text = await r.text(); + try { + return JSON.parse(text); + } catch(e) { + return { success: true }; + } + }) .then(res => { - if (res.success) { + if (res && res.success) { if (typeof window.Swal !== 'undefined') { window.Swal.fire({ icon: 'success', title: 'Recording Saved!', - text: 'Call recording saved successfully under Candidate Profile and Report.', + text: 'Call recording saved successfully to server and candidate report.', toast: true, position: 'top-end', timer: 3500, @@ -2181,9 +2729,57 @@ export function uploadRecordedBlob(blob, ext = 'webm') { }); } pollReviewData(); + } else if (res && res.message) { + if (typeof window.Swal !== 'undefined') { + window.Swal.fire({ + icon: 'warning', + title: 'Recording Notice', + text: res.message, + toast: true, + position: 'top-end', + timer: 4000, + showConfirmButton: false + }); + } } }) - .catch(err => console.log('Recording upload error:', err)); + .catch(err => { + console.error('Recording upload error:', err); + if (typeof window.Swal !== 'undefined') { + window.Swal.fire({ + icon: 'error', + title: 'Recording Upload Failed', + text: err.message || 'Failed to save recording to server.', + toast: true, + position: 'top-end', + timer: 4500, + showConfirmButton: false + }); + } + }); +} + +export function updateInterviewerNoiseSuppressionUI(isEnabled) { + const toggleSw = document.getElementById('noiseCancellationToggle'); + if (toggleSw) { + if (isEnabled) { + toggleSw.classList.add('on'); + } else { + toggleSw.classList.remove('on'); + } + } +} + +export function toggleInterviewerNoiseSuppression() { + let isEnabled = false; + if (interviewerNoiseSuppressor) { + isEnabled = interviewerNoiseSuppressor.toggle(); + } else { + isEnabled = !getRNNoisePreference(); + setRNNoisePreference(isEnabled); + } + updateInterviewerNoiseSuppressionUI(isEnabled); + return isEnabled; } export function toggleInterviewerMic() { @@ -2194,6 +2790,13 @@ export function toggleInterviewerMic() { isInterviewerMicOn = !isInterviewerMicOn; audioTracks[0].enabled = isInterviewerMicOn; + if (interviewerNoiseSuppressor) { + const procTrack = interviewerNoiseSuppressor.getProcessedAudioTrack(); + if (procTrack) procTrack.enabled = isInterviewerMicOn; + const origTrack = interviewerNoiseSuppressor.getOriginalAudioTrack(); + if (origTrack) origTrack.enabled = isInterviewerMicOn; + } + const btn = document.getElementById('btn-toggle-interviewer-mic'); if (btn) { const icon = btn.querySelector('i'); @@ -2352,15 +2955,27 @@ if (typeof window !== 'undefined') { window.stopCallRecording = stopCallRecording; window.toggleInterviewerMic = toggleInterviewerMic; window.toggleInterviewerCam = toggleInterviewerCam; + window.toggleInterviewerNoiseSuppression = toggleInterviewerNoiseSuppression; + window.updateInterviewerNoiseSuppressionUI = updateInterviewerNoiseSuppressionUI; window.closeReviewModal = closeReviewModal; window.sendSilentWarning = sendSilentWarning; window.setCurrentInterviewId = setCurrentInterviewId; + window.closeInspectorPanel = closeInspectorPanel; // Attach listeners ['click', 'keydown', 'touchstart'].forEach(evt => { document.addEventListener(evt, () => callRingtone.init(), { passive: true }); }); + const initNoiseState = () => { + updateInterviewerNoiseSuppressionUI(getRNNoisePreference()); + }; + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initNoiseState); + } else { + initNoiseState(); + } + globalCallChannel = new BroadcastChannel('global_call_alerts'); globalCallChannel.onmessage = (event) => { const data = event.data; diff --git a/resources/js/noise-suppressor.js b/resources/js/noise-suppressor.js new file mode 100644 index 0000000..cbc38ed --- /dev/null +++ b/resources/js/noise-suppressor.js @@ -0,0 +1,297 @@ +/** + * RNNoise WebAssembly & AudioWorklet Real-Time Noise Suppression Engine + * + * Provides neural-network-powered speech enhancement and background noise suppression + * for WebRTC audio streams (candidate and interviewer calls) using Xiph's RNNoise. + */ + +import { RnnoiseWorkletNode, loadRnnoise } from '@sapphi-red/web-noise-suppressor'; +import rnnoiseWorkletUrl from '@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js?url'; +import rnnoiseWasmUrl from '@sapphi-red/web-noise-suppressor/rnnoise.wasm?url'; +import rnnoiseSimdWasmUrl from '@sapphi-red/web-noise-suppressor/rnnoise_simd.wasm?url'; + +// Cache loaded WASM binary and worklet registration across audio contexts +let cachedWasmBinaryPromise = null; +const registeredAudioContexts = new WeakSet(); + +/** + * Check if the browser environment supports AudioWorklet & WebAssembly + */ +export function isRNNoiseSupported() { + return typeof window !== 'undefined' && + typeof window.AudioContext !== 'undefined' && + typeof window.WebAssembly !== 'undefined' && + typeof AudioWorkletNode !== 'undefined'; +} + +/** + * Get user preference for RNNoise noise suppression (default: enabled) + */ +export function getRNNoisePreference() { + if (typeof localStorage === 'undefined') return true; + const pref = localStorage.getItem('sls_rnnoise_enabled'); + return pref === null ? true : pref === 'true'; +} + +/** + * Save user preference for RNNoise noise suppression + */ +export function setRNNoisePreference(enabled) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem('sls_rnnoise_enabled', enabled ? 'true' : 'false'); + } +} + +/** + * Load the RNNoise WASM binary (with SIMD detection fallback) + */ +async function getWasmBinary() { + if (!cachedWasmBinaryPromise) { + cachedWasmBinaryPromise = loadRnnoise({ + url: rnnoiseWasmUrl, + simdUrl: rnnoiseSimdWasmUrl, + }).catch((err) => { + console.warn('[RNNoise] Failed to load WASM binary:', err); + cachedWasmBinaryPromise = null; + throw err; + }); + } + return cachedWasmBinaryPromise; +} + +/** + * Register the RNNoise AudioWorklet module in the given AudioContext + */ +async function registerWorkletModule(audioCtx) { + if (!registeredAudioContexts.has(audioCtx)) { + await audioCtx.audioWorklet.addModule(rnnoiseWorkletUrl); + registeredAudioContexts.add(audioCtx); + } +} + +/** + * Noise Suppressor Controller for an active MediaStream + */ +export class NoiseSuppressorController { + constructor({ + audioCtx, + sourceNode, + rnnoiseNode, + noiseGain, + bypassGain, + destinationNode, + rawStream, + processedStream, + initialEnabled = true, + }) { + this.audioCtx = audioCtx; + this.sourceNode = sourceNode; + this.rnnoiseNode = rnnoiseNode; + this.noiseGain = noiseGain; + this.bypassGain = bypassGain; + this.destinationNode = destinationNode; + this.rawStream = rawStream; + this.processedStream = processedStream; + this._enabled = initialEnabled; + this._disposed = false; + + this.applyState(initialEnabled, true); + } + + /** + * Enable or disable noise suppression with smooth audio gain transition + */ + setEnabled(enabled) { + if (this._disposed) return; + this._enabled = Boolean(enabled); + setRNNoisePreference(this._enabled); + this.applyState(this._enabled, false); + } + + applyState(enabled, immediate = false) { + if (!this.noiseGain || !this.bypassGain || !this.audioCtx) return; + const now = this.audioCtx.currentTime; + const transitionDuration = immediate ? 0 : 0.02; // 20ms click-free cross-fade + + if (enabled) { + // Enable RNNoise path, disable raw bypass + this.bypassGain.gain.setValueAtTime(this.bypassGain.gain.value, now); + this.bypassGain.gain.linearRampToValueAtTime(0.0, now + transitionDuration); + + this.noiseGain.gain.setValueAtTime(this.noiseGain.gain.value, now); + this.noiseGain.gain.linearRampToValueAtTime(1.0, now + transitionDuration); + } else { + // Disable RNNoise path, enable raw bypass + this.noiseGain.gain.setValueAtTime(this.noiseGain.gain.value, now); + this.noiseGain.gain.linearRampToValueAtTime(0.0, now + transitionDuration); + + this.bypassGain.gain.setValueAtTime(this.bypassGain.gain.value, now); + this.bypassGain.gain.linearRampToValueAtTime(1.0, now + transitionDuration); + } + } + + toggle() { + this.setEnabled(!this._enabled); + return this._enabled; + } + + isEnabled() { + return this._enabled; + } + + getProcessedStream() { + return this.processedStream || this.rawStream; + } + + getProcessedAudioTrack() { + if (this.processedStream) { + const tracks = this.processedStream.getAudioTracks(); + if (tracks.length > 0) return tracks[0]; + } + if (this.rawStream) { + const tracks = this.rawStream.getAudioTracks(); + if (tracks.length > 0) return tracks[0]; + } + return null; + } + + getOriginalAudioTrack() { + if (this.rawStream) { + const tracks = this.rawStream.getAudioTracks(); + if (tracks.length > 0) return tracks[0]; + } + return null; + } + + dispose() { + if (this._disposed) return; + this._disposed = true; + + try { + if (this.sourceNode) this.sourceNode.disconnect(); + if (this.rnnoiseNode) { + this.rnnoiseNode.disconnect(); + if (typeof this.rnnoiseNode.destroy === 'function') { + this.rnnoiseNode.destroy(); + } + } + if (this.noiseGain) this.noiseGain.disconnect(); + if (this.bypassGain) this.bypassGain.disconnect(); + if (this.destinationNode) this.destinationNode.disconnect(); + } catch (e) { + console.warn('[RNNoise] Cleanup warning:', e); + } + + if (this.processedStream) { + this.processedStream.getTracks().forEach((t) => { + try { t.stop(); } catch (e) {} + }); + } + + if (this.audioCtx && this.audioCtx.state !== 'closed') { + try { this.audioCtx.close(); } catch (e) {} + } + } +} + +/** + * Fallback Controller when RNNoise is unavailable or fails + */ +class FallbackNoiseSuppressorController { + constructor(rawStream) { + this.rawStream = rawStream; + this._enabled = false; + } + setEnabled(enabled) { this._enabled = Boolean(enabled); } + toggle() { this._enabled = !this._enabled; return this._enabled; } + isEnabled() { return this._enabled; } + getProcessedStream() { return this.rawStream; } + getProcessedAudioTrack() { + return this.rawStream?.getAudioTracks()[0] || null; + } + getOriginalAudioTrack() { + return this.rawStream?.getAudioTracks()[0] || null; + } + dispose() {} +} + +/** + * Create a noise-suppressed MediaStream from a raw microphone MediaStream + * + * @param {MediaStream} rawStream - Input media stream with microphone audio + * @param {Object} options - Optional configuration + * @returns {Promise} Controller with processed stream + */ +export async function createNoiseSuppressedStream(rawStream, options = {}) { + if (!rawStream || !rawStream.getAudioTracks || rawStream.getAudioTracks().length === 0) { + return new FallbackNoiseSuppressorController(rawStream); + } + + if (!isRNNoiseSupported()) { + console.warn('[RNNoise] WebAudio AudioWorklet / WASM not supported in this browser, using standard audio'); + return new FallbackNoiseSuppressorController(rawStream); + } + + try { + const AudioCtxClass = window.AudioContext || window.webkitAudioContext; + // RNNoise is trained on 48,000Hz (48kHz) audio. Create a 48kHz audio context. + const audioCtx = new AudioCtxClass({ sampleRate: 48000 }); + + if (audioCtx.state === 'suspended') { + await audioCtx.resume().catch(() => {}); + } + + // Parallelize WASM binary loading & worklet module registration with timeout + const wasmPromise = getWasmBinary(); + const workletPromise = registerWorkletModule(audioCtx); + + // Fail-safe 3500ms timeout + const timeoutPromise = new Promise((_, reject) => + setTimeout(() => reject(new Error('RNNoise init timeout')), 3500) + ); + + const [wasmBinary] = await Promise.race([ + Promise.all([wasmPromise, workletPromise]), + timeoutPromise, + ]); + + const sourceNode = audioCtx.createMediaStreamSource(rawStream); + const rnnoiseNode = new RnnoiseWorkletNode(audioCtx, { + maxChannels: 1, + wasmBinary, + }); + + const noiseGain = audioCtx.createGain(); + const bypassGain = audioCtx.createGain(); + const destinationNode = audioCtx.createMediaStreamDestination(); + + // Connect RNNoise path: Source -> RNNoise -> NoiseGain -> Destination + sourceNode.connect(rnnoiseNode); + rnnoiseNode.connect(noiseGain); + noiseGain.connect(destinationNode); + + // Connect Bypass path: Source -> BypassGain -> Destination + sourceNode.connect(bypassGain); + bypassGain.connect(destinationNode); + + const processedStream = destinationNode.stream; + const initialEnabled = options.enabled !== undefined ? options.enabled : getRNNoisePreference(); + + console.log('[RNNoise] Audio suppressor initialized successfully (enabled:', initialEnabled, ')'); + + return new NoiseSuppressorController({ + audioCtx, + sourceNode, + rnnoiseNode, + noiseGain, + bypassGain, + destinationNode, + rawStream, + processedStream, + initialEnabled, + }); + } catch (err) { + console.warn('[RNNoise] Failed to initialize noise suppression worklet, falling back to raw audio:', err); + return new FallbackNoiseSuppressorController(rawStream); + } +} diff --git a/resources/js/recording-compositor.js b/resources/js/recording-compositor.js new file mode 100644 index 0000000..5756daa --- /dev/null +++ b/resources/js/recording-compositor.js @@ -0,0 +1,685 @@ +/** + * Recording Compositor & Multi-Track Audio Mixer Engine + * + * Creates a unified 1920x1080 composite video stream from multiple WebRTC video sources + * (Candidate Webcam, Screen Share, Self Interviewer, Remote Mesh Panelists) + * matching the interviewer layout: + * - Large Main Area: Candidate Webcam (or Screen Share when active) + * - Right Sidebar: Stacked Peers (and Candidate Webcam at top when screen share is active) + * - Camera-off Avatar Placeholders with initials and badges + * - Bottom Overflow Row: Placed horizontally below main area if peers > 3 + * - AudioContext multi-track audio mixing + */ + +export class RecordingCompositor { + /** + * @param {{width:number, height:number, fps: number, getParticipantsData: () => {}}} options + */ + constructor(options = {}) { + this.width = options.width || 1920; + this.height = options.height || 1080; + this.fps = options.fps || 30; + + this.canvas = document.createElement("canvas"); + this.canvas.width = this.width; + this.canvas.height = this.height; + this.ctx = this.canvas.getContext("2d", { alpha: false }); + + this.audioCtx = null; + this.audioDestination = null; + this.audioSourceNodes = []; + this.mixedAudioTrack = null; + + this.animationFrameId = null; + this.isRunning = false; + this.startTime = null; + this.speakingStates = new Map(); + + // Metadata provider function + this.getParticipantsData = options.getParticipantsData || (() => ({})); + } + + start() { + if (this.isRunning) return; + this.isRunning = true; + this.startTime = Date.now(); + + this.initAudioMixer(); + this.renderLoop(); + } + + stop() { + this.isRunning = false; + if (this.animationFrameId) { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + } + + if (this.audioSourceNodes.length > 0) { + this.audioSourceNodes.forEach((node) => { + try { + node.disconnect(); + } catch (e) {} + }); + this.audioSourceNodes = []; + } + + if (this.audioCtx) { + try { + this.audioCtx.close(); + } catch (e) {} + this.audioCtx = null; + } + this.audioDestination = null; + this.mixedAudioTrack = null; + } + + getStream() { + const videoTrack = this.canvas + .captureStream(this.fps) + .getVideoTracks()[0]; + const tracks = []; + if (videoTrack) tracks.push(videoTrack); + if (this.mixedAudioTrack) tracks.push(this.mixedAudioTrack); + return new MediaStream(tracks); + } + + setSpeakingState(key, isSpeaking) { + this.speakingStates.set(key, Boolean(isSpeaking)); + } + + initAudioMixer() { + try { + const AudioCtxClass = + window.AudioContext || window.webkitAudioContext; + if (!AudioCtxClass) return; + + this.audioCtx = new AudioCtxClass(); + this.audioDestination = + this.audioCtx.createMediaStreamDestination(); + + const data = this.getParticipantsData(); + const audioStreams = []; + + // 1. Candidate Audio + if ( + data.candidateStream && + data.candidateStream.getAudioTracks().length > 0 + ) { + audioStreams.push(data.candidateStream); + } + // 2. Interviewer Self Audio + if ( + data.selfStream && + data.selfStream.getAudioTracks().length > 0 + ) { + audioStreams.push(data.selfStream); + } + // 3. Panelist Mesh Audios + if (data.panelistStreams && Array.isArray(data.panelistStreams)) { + data.panelistStreams.forEach((ps) => { + if ( + ps && + ps.stream && + ps.stream.getAudioTracks().length > 0 + ) { + audioStreams.push(ps.stream); + } + }); + } + + audioStreams.forEach((stream) => { + try { + const source = + this.audioCtx.createMediaStreamSource(stream); + source.connect(this.audioDestination); + this.audioSourceNodes.push(source); + } catch (e) {} + }); + + this.mixedAudioTrack = + this.audioDestination.stream.getAudioTracks()[0] || null; + } catch (e) { + console.warn("[RecordingCompositor] Audio mixing error:", e); + } + } + + renderLoop() { + if (!this.isRunning) return; + this.renderFrame(); + this.animationFrameId = requestAnimationFrame(() => this.renderLoop()); + } + + renderFrame() { + const ctx = this.ctx; + const W = this.width; + const H = this.height; + + // Dark background + ctx.fillStyle = "#090d16"; + ctx.fillRect(0, 0, W, H); + + const data = this.getParticipantsData(); + + // 1. Candidate Feed + const candVideo = document.getElementById("interviewer-cand-video"); + const isCandCamOn = data.candidateCamOn !== false; + const isCandMicOn = data.candidateMicOn !== false; + const candidateFeed = { + id: "candidate", + type: "candidate", + name: data.candidateName || "Candidate", + initials: this.extractInitials(data.candidateName || "Candidate"), + video: candVideo, + hasVideo: isCandCamOn && this.isVideoPlaying(candVideo), + isCamOn: isCandCamOn, + isMicOn: isCandMicOn, + isSpeaking: + this.speakingStates.get("interviewer-cand-video") || false, + badge: "Candidate", + }; + + // 2. Screen Share Feed + const screenVideo = document.getElementById("interviewer-screen-video"); + const isScreenSharing = this.isScreenShareActive(screenVideo); + const screenFeed = { + id: "screen", + type: "screen", + name: "Candidate Live Screen", + initials: "SCR", + video: screenVideo, + hasVideo: isScreenSharing, + isCamOn: true, + isMicOn: false, + isSpeaking: false, + badge: "Shared Screen", + }; + + // 3. Self Interviewer Feed + const selfVideo = document.getElementById("interviewer-self-video"); + const isSelfCamOn = data.selfCamOn !== false; + const isSelfMicOn = data.selfMicOn !== false; + const selfFeed = { + id: "self", + type: "interviewer", + name: data.selfName + ? `${data.selfName} (You)` + : "Interviewer (You)", + initials: this.extractInitials(data.selfName || "IV"), + video: selfVideo, + hasVideo: isSelfCamOn && this.isVideoPlaying(selfVideo), + isCamOn: isSelfCamOn, + isMicOn: isSelfMicOn, + isSpeaking: false, + badge: "Interviewer", + }; + + // 4. Panelist Feeds + const panelistFeeds = []; + if (data.panelists && Array.isArray(data.panelists)) { + data.panelists.forEach((p) => { + const pVid = document.getElementById( + "panelist-video-" + p.peerId, + ); + const isCamOn = p.camOn !== false; + const isMicOn = p.micOn !== false; + panelistFeeds.push({ + id: p.peerId, + type: "panelist", + name: p.name || "Panelist", + initials: this.extractInitials(p.name || "Panelist"), + video: pVid, + hasVideo: isCamOn && this.isVideoPlaying(pVid), + isCamOn: isCamOn, + isMicOn: isMicOn, + isSpeaking: false, + badge: p.role || "Panelist", + }); + }); + } + + // Layout determination + let mainFeed; + let secondaryFeeds = []; + + if (isScreenSharing) { + // When screen share is active: + // Main = Screen Share + // Right Sidebar Top = Candidate Webcam + // Followed by Self and Panelists + mainFeed = screenFeed; + secondaryFeeds = [candidateFeed, selfFeed, ...panelistFeeds]; + } else { + // Normal Call: + // Main = Candidate Webcam + // Right Sidebar = Self and Panelists + mainFeed = candidateFeed; + secondaryFeeds = [selfFeed, ...panelistFeeds]; + } + + // Compute geometry with strict 16:9 aspect ratio preservation for every tile + const gap = 16; + const padX = 24; + const totalSecondary = secondaryFeeds.length; + + if (totalSecondary === 0) { + // Case 0: Only Main Feed (Full Canvas 16:9) + const mainH = 1032; + const mainW = Math.round(mainH * (16 / 9)); // 1835px + const mainX = Math.round((W - mainW) / 2); + const mainY = Math.round((H - mainH) / 2); + this.renderTile( + ctx, + mainFeed, + { x: mainX, y: mainY, w: mainW, h: mainH }, + true, + ); + } else if (totalSecondary === 1) { + // Case 1: Main + 1 Sidebar Tile (Both 16:9) + const sideW = 480; + const sideH = Math.round(sideW * (9 / 16)); // 270px + const mainW = 1376; + const mainH = Math.round(mainW * (9 / 16)); // 774px + + const mainX = padX; + const mainY = Math.round((H - mainH) / 2); + const sideX = padX + mainW + gap; + const sideY = Math.round((H - sideH) / 2); + + this.renderTile( + ctx, + mainFeed, + { x: mainX, y: mainY, w: mainW, h: mainH }, + true, + ); + this.renderTile( + ctx, + secondaryFeeds[0], + { x: sideX, y: sideY, w: sideW, h: sideH }, + false, + ); + } else if (totalSecondary === 2) { + // Case 2: Main + 2 Sidebar Tiles (All 16:9) + const sideW = 480; + const sideH = Math.round(sideW * (9 / 16)); // 270px + const mainW = 1376; + const mainH = Math.round(mainW * (9 / 16)); // 774px + + const mainX = padX; + const mainY = Math.round((H - mainH) / 2); + const sideX = padX + mainW + gap; + + const totalSideH = 2 * sideH + gap; // 556px + const sideYStart = Math.round((H - totalSideH) / 2); + + this.renderTile( + ctx, + mainFeed, + { x: mainX, y: mainY, w: mainW, h: mainH }, + true, + ); + this.renderTile( + ctx, + secondaryFeeds[0], + { x: sideX, y: sideYStart, w: sideW, h: sideH }, + false, + ); + this.renderTile( + ctx, + secondaryFeeds[1], + { x: sideX, y: sideYStart + sideH + gap, w: sideW, h: sideH }, + false, + ); + } else if (totalSecondary === 3) { + // Case 3: Main + 3 Sidebar Tiles (All 16:9) + const sideH = 330; + const sideW = Math.round(sideH * (16 / 9)); // 587px + const totalSideH = 3 * sideH + 2 * gap; // 1022px + const topY = Math.round((H - totalSideH) / 2); // 29px + + const sideX = W - padX - sideW; + const mainW = sideX - gap - padX; // 1270px + const mainH = Math.round(mainW * (9 / 16)); // 714px + + const mainX = padX; + const mainY = topY; + + this.renderTile( + ctx, + mainFeed, + { x: mainX, y: mainY, w: mainW, h: mainH }, + true, + ); + + for (let i = 0; i < 3; i++) { + const feed = secondaryFeeds[i]; + const tileY = topY + i * (sideH + gap); + this.renderTile( + ctx, + feed, + { x: sideX, y: tileY, w: sideW, h: sideH }, + false, + ); + } + } else { + // Case 4: Main + 3 Sidebar Tiles + Bottom Overflow Row (All 16:9) + const sideH = 330; + const sideW = Math.round(sideH * (16 / 9)); // 587px + const totalSideH = 3 * sideH + 2 * gap; // 1022px + const topY = Math.round((H - totalSideH) / 2); // 29px + + const sideX = W - padX - sideW; + const mainW = sideX - gap - padX; // 1270px + const mainH = Math.round(mainW * (9 / 16)); // 714px + + const mainX = padX; + const mainY = topY; + + // 1. Render Main + this.renderTile( + ctx, + mainFeed, + { x: mainX, y: mainY, w: mainW, h: mainH }, + true, + ); + + // 2. Render 3 Sidebar Tiles + for (let i = 0; i < 3; i++) { + const feed = secondaryFeeds[i]; + const tileY = topY + i * (sideH + gap); + this.renderTile( + ctx, + feed, + { x: sideX, y: tileY, w: sideW, h: sideH }, + false, + ); + } + + // 3. Render Bottom Overflow Tiles (each 16:9) + const overflowFeeds = secondaryFeeds.slice(3); + const numOverflow = overflowFeeds.length; + const botMaxH = totalSideH - mainH - gap; // 292px + const botYBase = topY + mainH + gap; // 759px + + // Calculate width per tile to fit in mainW + const candBotW = Math.floor( + (mainW - (numOverflow - 1) * gap) / numOverflow, + ); + const candBotH = Math.round(candBotW * (9 / 16)); + + let botW, botH; + if (candBotH > botMaxH) { + botH = botMaxH; + botW = Math.round(botH * (16 / 9)); + } else { + botW = candBotW; + botH = candBotH; + } + + const totalBotW = numOverflow * botW + (numOverflow - 1) * gap; + const botXStart = mainX + Math.round((mainW - totalBotW) / 2); + const botY = botYBase + Math.round((botMaxH - botH) / 2); + + overflowFeeds.forEach((feed, j) => { + const tileX = botXStart + j * (botW + gap); + this.renderTile( + ctx, + feed, + { x: tileX, y: botY, w: botW, h: botH }, + false, + ); + }); + } + } + + renderTile(ctx, feed, rect, isMain = false) { + const { x, y, w, h } = rect; + const radius = 12; + + ctx.save(); + this.drawRoundedClip(ctx, x, y, w, h, radius); + + // Base tile background + ctx.fillStyle = "#0d1220"; + ctx.fillRect(x, y, w, h); + + if (feed.hasVideo && feed.video) { + // Draw video frame + if (feed.type === "screen") { + this.drawVideoContain(ctx, feed.video, x, y, w, h); + } else { + this.drawVideoCover(ctx, feed.video, x, y, w, h); + } + } else { + // Draw avatar placeholder + this.drawPlaceholder(ctx, feed, x, y, w, h, isMain); + } + + ctx.restore(); + + // Sleek subtle border + ctx.save(); + ctx.lineWidth = 1; + ctx.strokeStyle = "rgba(255, 255, 255, 0.08)"; + this.drawRoundedStroke(ctx, x, y, w, h, radius); + ctx.restore(); + + // Overlay Pill Tag (Bottom-Left) + this.drawPillTag(ctx, feed, x + 10, y + h - 12); + } + + drawVideoCover(ctx, video, x, y, w, h) { + try { + const vw = video.videoWidth || 640; + const vh = video.videoHeight || 480; + + const targetRatio = w / h; + const videoRatio = vw / vh; + + let sx = 0, + sy = 0, + sw = vw, + sh = vh; + + if (videoRatio > targetRatio) { + // Video is wider than 16:9 target: crop horizontally + sw = Math.round(vh * targetRatio); + sx = Math.round((vw - sw) / 2); + } else { + // Video is taller than 16:9 target: crop vertically + sh = Math.round(vw / targetRatio); + sy = Math.round((vh - sh) / 2); + } + + ctx.drawImage(video, sx, sy, sw, sh, x, y, w, h); + } catch (e) {} + } + + drawVideoContain(ctx, video, x, y, w, h) { + try { + const vw = video.videoWidth || 1920; + const vh = video.videoHeight || 1080; + + const targetRatio = w / h; + const videoRatio = vw / vh; + + let dw = w; + let dh = h; + let dx = x; + let dy = y; + + if (videoRatio > targetRatio) { + // Video is wider than tile + dh = Math.round(w / videoRatio); + dy = Math.round(y + (h - dh) / 2); + } else { + // Video is taller than tile + dw = Math.round(h * videoRatio); + dx = Math.round(x + (w - dw) / 2); + } + + ctx.drawImage(video, 0, 0, vw, vh, dx, dy, dw, dh); + } catch (e) {} + } + + drawPlaceholder(ctx, feed, x, y, w, h, isMain = false) { + const cx = x + w / 2; + const cy = y + h / 2 - (isMain ? 15 : 8); + const circleRadius = isMain + ? Math.min(54, h * 0.18) + : Math.min(32, h * 0.22); + + // Circular gradient avatar + const gradient = ctx.createLinearGradient( + cx - circleRadius, + cy - circleRadius, + cx + circleRadius, + cy + circleRadius, + ); + if (feed.type === "candidate") { + gradient.addColorStop(0, "#10b981"); + gradient.addColorStop(1, "#059669"); + } else { + gradient.addColorStop(0, "#5b8bff"); + gradient.addColorStop(1, "#3b63e0"); + } + + ctx.fillStyle = gradient; + ctx.beginPath(); + ctx.arc(cx, cy, circleRadius, 0, Math.PI * 2); + ctx.fill(); + + // Avatar Initials Text + ctx.fillStyle = "#ffffff"; + ctx.font = `bold ${Math.round(circleRadius * 0.85)}px sans-serif`; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(feed.initials || "IV", cx, cy); + + // Participant Name + ctx.fillStyle = "#ffffff"; + ctx.font = `600 ${isMain ? 18 : 13}px sans-serif`; + ctx.textBaseline = "top"; + ctx.fillText(feed.name, cx, cy + circleRadius + (isMain ? 14 : 8)); + + // Subtitle status + ctx.fillStyle = "#94a3b8"; + ctx.font = `400 ${isMain ? 13 : 10.5}px sans-serif`; + ctx.fillText( + feed.isCamOn ? "Connecting video..." : "Camera turned off", + cx, + cy + circleRadius + (isMain ? 36 : 24), + ); + } + + drawPillTag(ctx, feed, x, y) { + const text = feed.name; + const fontSize = 11; + ctx.font = `600 ${fontSize}px sans-serif`; + + const textMetrics = ctx.measureText(text); + const tagPaddingX = 8; + const tagW = textMetrics.width + tagPaddingX * 2; + const tagH = 20; + + const tagX = x; + const tagY = y - tagH; + + ctx.save(); + // Background + ctx.fillStyle = "rgba(9, 13, 22, 0.8)"; + this.drawRoundedFill(ctx, tagX, tagY, tagW, tagH, 5); + + // Border + ctx.strokeStyle = "rgba(255, 255, 255, 0.12)"; + ctx.lineWidth = 1; + this.drawRoundedStroke(ctx, tagX, tagY, tagW, tagH, 5); + + // Name text + ctx.fillStyle = "#e2e8f0"; + ctx.textBaseline = "middle"; + ctx.textAlign = "left"; + ctx.fillText(text, tagX + tagPaddingX, tagY + tagH / 2); + + ctx.restore(); + } + + isScreenShareActive(video) { + if (!video) return false; + const stream = video.srcObject; + if (!stream || !stream.active) return false; + const tracks = stream.getVideoTracks ? stream.getVideoTracks() : []; + if (tracks.length === 0) return false; + const hasLiveTrack = tracks.some( + (t) => t.readyState === "live" && t.enabled, + ); + if (!hasLiveTrack) return false; + + if (video.paused && typeof video.play === "function") { + video.play().catch(() => {}); + } + return true; + } + + isVideoPlaying(video) { + if (!video) return false; + const stream = video.srcObject; + if (!stream || !stream.active) return false; + const tracks = stream.getVideoTracks ? stream.getVideoTracks() : []; + if (tracks.length === 0) return false; + const hasLiveTrack = tracks.some( + (t) => t.readyState === "live" && t.enabled, + ); + if (!hasLiveTrack) return false; + + if (video.paused && typeof video.play === "function") { + video.play().catch(() => {}); + } + return Boolean( + video.videoWidth > 0 || video.readyState >= 1 || hasLiveTrack, + ); + } + + extractInitials(name) { + if (!name) return "CD"; + const parts = name.trim().split(/\s+/); + if (parts.length >= 2) { + return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + } + return name.slice(0, 2).toUpperCase(); + } + + roundedRectPath(ctx, x, y, w, h, r) { + if (typeof ctx.roundRect === "function") { + ctx.beginPath(); + ctx.roundRect(x, y, w, h, r); + return; + } + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.lineTo(x + w - r, y); + ctx.arcTo(x + w, y, x + w, y + r, r); + ctx.lineTo(x + w, y + h - r); + ctx.arcTo(x + w, y + h, x + w - r, y + h, r); + ctx.lineTo(x + r, y + h); + ctx.arcTo(x, y + h, x, y + h - r, r); + ctx.lineTo(x, y + r); + ctx.arcTo(x, y, x + r, y, r); + ctx.closePath(); + } + + drawRoundedClip(ctx, x, y, w, h, r) { + this.roundedRectPath(ctx, x, y, w, h, r); + ctx.clip(); + } + + drawRoundedStroke(ctx, x, y, w, h, r) { + this.roundedRectPath(ctx, x, y, w, h, r); + ctx.stroke(); + } + + drawRoundedFill(ctx, x, y, w, h, r) { + this.roundedRectPath(ctx, x, y, w, h, r); + ctx.fill(); + } +} diff --git a/resources/views/components/alert.blade.php b/resources/views/components/alert.blade.php new file mode 100644 index 0000000..8e13cf5 --- /dev/null +++ b/resources/views/components/alert.blade.php @@ -0,0 +1,32 @@ +@props([ + 'variant' => 'info', // success, danger, warning, info + 'icon' => null, +]) + +@php + $variants = [ + 'success' => 'bg-emerald-500/15 border-emerald-500/30 text-emerald-300', + 'danger' => 'bg-red-500/15 border-red-500/30 text-red-300', + 'warning' => 'bg-amber-500/15 border-amber-500/30 text-amber-300', + 'info' => 'bg-sky-500/15 border-sky-500/30 text-sky-300', + ]; + + $defaultIcons = [ + 'success' => 'fa-solid fa-circle-check', + 'danger' => 'fa-solid fa-triangle-exclamation', + 'warning' => 'fa-solid fa-circle-exclamation', + 'info' => 'fa-solid fa-circle-info', + ]; + + $selectedIcon = $icon ?? ($defaultIcons[$variant] ?? $defaultIcons['info']); + $variantClass = $variants[$variant] ?? $variants['info']; +@endphp + +
merge(['class' => "flex items-start gap-2.5 px-4 py-3 border rounded-xl text-xs font-medium {$variantClass}"]) }}> + @if($selectedIcon) + + @endif +
+ {{ $slot }} +
+
diff --git a/resources/views/components/audit-log.blade.php b/resources/views/components/audit-log.blade.php index 21000a0..3e047f2 100644 --- a/resources/views/components/audit-log.blade.php +++ b/resources/views/components/audit-log.blade.php @@ -2,7 +2,7 @@ 'logs' => [], ]) -
merge(['class' => 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] max-h-[260px] overflow-y-auto']) }}> +
twMerge(['class' => 'bg-[#0d1220] border border-[#1b2233] rounded-[9px] overflow-y-auto']) }}> @if(is_array($logs) && count($logs) > 0) @foreach($logs as $log) merge(['class' => $classes]) }}> + +
+ + +
+ {{ $slot }} +
+ + + @if(isset($footer)) +
+ {{ $footer }} +
+ @endif +
+
diff --git a/resources/views/components/hamburger-menu.blade.php b/resources/views/components/hamburger-menu.blade.php new file mode 100644 index 0000000..7aadf58 --- /dev/null +++ b/resources/views/components/hamburger-menu.blade.php @@ -0,0 +1,25 @@ +@props([ + 'align' => 'left', // left, right + 'width' => 'w-80 sm:w-96', +]) + +@php + $alignmentClasses = $align === 'right' ? 'right-0 origin-top-right' : 'left-0 origin-top-left'; +@endphp + +
+ + {{ $trigger ?? '' }} + @if(!isset($trigger)) + + @endif + + + +
+ + +
+ {{ $slot }} +
+
diff --git a/resources/views/components/input.blade.php b/resources/views/components/input.blade.php new file mode 100644 index 0000000..0a18193 --- /dev/null +++ b/resources/views/components/input.blade.php @@ -0,0 +1,29 @@ +@props([ + 'type' => 'text', + 'name' => null, + 'value' => null, + 'placeholder' => null, + 'required' => false, + 'disabled' => false, + 'size' => 'md', // sm, md, lg +]) + +@php + $sizeClasses = [ + 'sm' => 'px-2.5 py-1.5 text-xs', + 'md' => 'px-3 py-2 text-xs', + 'lg' => 'px-3.5 py-2.5 text-sm', + ]; + + $classes = 'w-full bg-white/5 border border-slate-700/60 rounded-lg text-white outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40 placeholder-slate-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ' . ($sizeClasses[$size] ?? $sizeClasses['md']); +@endphp + +merge(['class' => $classes]) }} +/> diff --git a/resources/views/components/interview/admin-settings-card.blade.php b/resources/views/components/interview/admin-settings-card.blade.php new file mode 100644 index 0000000..cd8cf89 --- /dev/null +++ b/resources/views/components/interview/admin-settings-card.blade.php @@ -0,0 +1,75 @@ +@php + $screenshotActive = \App\Models\Setting::get('enable_candidate_screenshots', '1') === '1'; + $onboardingActive = \App\Models\Setting::get('onboarding_enabled', '1') === '1'; + $isAdmin = Auth::check() && Auth::user()->isAdmin(); +@endphp + +
+ +
+
+
+ +
+
+
+

Screenshot Capture

+ @if($screenshotActive) + Active + @else + Stopped + @endif +
+

+ Captures candidate's desktop automatically on call start & tab switches. +

+
+ + @if($isAdmin) +
+
+ @csrf + +
+
+ @endif +
+
+ + +
+
+
+ +
+
+
+

Candidate Onboarding

+ @if($onboardingActive) + Active + @else + Disabled + @endif +
+

+ Automatic provisioning checklist and one-click revocation. +

+
+ + @if($isAdmin) +
+
+ @csrf + +
+
+ @endif +
+
+
diff --git a/resources/views/components/interview/call-controls.blade.php b/resources/views/components/interview/call-controls.blade.php new file mode 100644 index 0000000..35804d7 --- /dev/null +++ b/resources/views/components/interview/call-controls.blade.php @@ -0,0 +1,43 @@ +@props([ + 'interview', +]) + +
+ + + + + + + + @if($interview->call_status === 'ended') + + Call Ended + + @elseif($interview->call_status === 'active') + + Join Call + + @else + + Start Call + + @endif + + + + + + + + + + +
diff --git a/resources/views/components/interview/candidate-header.blade.php b/resources/views/components/interview/candidate-header.blade.php new file mode 100644 index 0000000..d621e83 --- /dev/null +++ b/resources/views/components/interview/candidate-header.blade.php @@ -0,0 +1,87 @@ +@props([ + 'interview', +]) + +
+ +
+
+ Session Details +
+
+
+
Submission ID
+ +
+
+
Temp Pass
+
{{ $interview->temp_password }}
+
+
+
Language
+
{{ $interview->language }}
+
+
+
Timeline
+
{{ $interview->formatted_timeline }}
+
+
+
+ +
+
+ + SOS auto-trigger alert + + +
+ +
+ + Noise Cancellation + + +
+ +
+ Password + PDF Report + Block +
+
+
+ + +
+ {{ $interview->candidate_initials }} +
+ + +
+ +
+ {{ $interview->candidate_email }} · {{ $interview->candidate_phone }} +
+
+ + +
+ + Not Joined + + + @if($interview->isExpired()) + Expired + @elseif($interview->status === 'completed') + Completed + @elseif($interview->call_status === 'active') + Call in progress + @elseif($interview->isActiveTimeline()) + Timeline live + @else + Scheduled + @endif +
+
diff --git a/resources/views/components/interview/candidate/drawing-modal.blade.php b/resources/views/components/interview/candidate/drawing-modal.blade.php new file mode 100644 index 0000000..74040c8 --- /dev/null +++ b/resources/views/components/interview/candidate/drawing-modal.blade.php @@ -0,0 +1,25 @@ + diff --git a/resources/views/components/interview/candidate/ide-header.blade.php b/resources/views/components/interview/candidate/ide-header.blade.php new file mode 100644 index 0000000..6f44a0e --- /dev/null +++ b/resources/views/components/interview/candidate/ide-header.blade.php @@ -0,0 +1,49 @@ +@props([ + 'interview', +]) + +
+
+
+ + Candidate Assessment Room +
+ + ID: {{ $interview->submission_unique_id }} + +
+ +
+ + Notepad + + + + Drawing Board + + +
+ + +
+ + + Run Code + + + + Submit Solution + + + + Logout + +
+
diff --git a/resources/views/components/interview/candidate/incoming-overlay.blade.php b/resources/views/components/interview/candidate/incoming-overlay.blade.php new file mode 100644 index 0000000..a991c13 --- /dev/null +++ b/resources/views/components/interview/candidate/incoming-overlay.blade.php @@ -0,0 +1,35 @@ +
+
+
+
+
+
+ +
+
+ +
+ + INCOMING INTERVIEW CALL +
+ +

+ Interviewer Panel Calling... +

+ +
+ The interviewer panel has initiated a live 2-way call. +
+ +
+ + +
+
+
diff --git a/resources/views/components/interview/candidate/notepad-modal.blade.php b/resources/views/components/interview/candidate/notepad-modal.blade.php new file mode 100644 index 0000000..d605ec6 --- /dev/null +++ b/resources/views/components/interview/candidate/notepad-modal.blade.php @@ -0,0 +1,20 @@ +@props([ + 'notes' => '', +]) + + diff --git a/resources/views/components/interview/candidate/proctor-sidebar.blade.php b/resources/views/components/interview/candidate/proctor-sidebar.blade.php new file mode 100644 index 0000000..0ddbdeb --- /dev/null +++ b/resources/views/components/interview/candidate/proctor-sidebar.blade.php @@ -0,0 +1,112 @@ +@props([ + 'interview', +]) + + diff --git a/resources/views/components/interview/candidate/terminal.blade.php b/resources/views/components/interview/candidate/terminal.blade.php new file mode 100644 index 0000000..439e0c5 --- /dev/null +++ b/resources/views/components/interview/candidate/terminal.blade.php @@ -0,0 +1,10 @@ +
+
+ + + EXECUTION OUTPUT TERMINAL (STDOUT / STDERR) + + Ready +
+
// Press 'Run Code' to execute candidate solution live...
+
diff --git a/resources/views/components/interview/incoming-call-modal.blade.php b/resources/views/components/interview/incoming-call-modal.blade.php new file mode 100644 index 0000000..29a813d --- /dev/null +++ b/resources/views/components/interview/incoming-call-modal.blade.php @@ -0,0 +1,36 @@ + +
+
+
+
+
+ +
+
+ +
+ ⚡ Incoming Assessment Call +
+ +

+ Candidate Name +

+ +
+ Initiated by Panelist +
+ +
+ Another interviewer has started calling the candidate. Click Accept Call to join live, or Decline if busy. +
+ +
+ + Decline / Miss + + + Accept Call + +
+
+
diff --git a/resources/views/components/interview/inspector-panel.blade.php b/resources/views/components/interview/inspector-panel.blade.php new file mode 100644 index 0000000..217784f --- /dev/null +++ b/resources/views/components/interview/inspector-panel.blade.php @@ -0,0 +1,95 @@ +@props([ + 'interview', +]) + +
+ + +
+ + Inspector Panel +
+ +
+ +
+ + + + + +
+
+
+ + +
+ +
+
+ + Proctoring Logs +
+ +
+ + +
+ + + + + +
+
+
diff --git a/resources/views/components/interview/navbar.blade.php b/resources/views/components/interview/navbar.blade.php new file mode 100644 index 0000000..73a1ed9 --- /dev/null +++ b/resources/views/components/interview/navbar.blade.php @@ -0,0 +1,35 @@ +@props([ + 'activeNav' => 'interview', +]) + +
+
+ + + +
+

Candidate Live Assessment Portal

+
Proctored IDE & Code Submissions
+
+
+ +
+ @if(Auth::check() && Auth::user()->isAdmin()) + + Control Panel + + @endif + + Onboarding Hub + + + User Portal + +
+ @csrf + + Logout + +
+
+
diff --git a/resources/views/components/interview/proctor-badges.blade.php b/resources/views/components/interview/proctor-badges.blade.php new file mode 100644 index 0000000..979fccf --- /dev/null +++ b/resources/views/components/interview/proctor-badges.blade.php @@ -0,0 +1,39 @@ +@props([ + 'metrics' => [], +]) + +@php + $tabSwitches = $metrics['tab_switches'] ?? 0; + $focusLost = $metrics['focus_lost'] ?? 0; + $gazeAlerts = $metrics['gaze_alerts'] ?? 0; + $lowerGaze = $metrics['lower_gaze'] ?? 0; + $questionRepeat = $metrics['question_repeat'] ?? 0; + $externalAi = $metrics['external_ai'] ?? 0; +@endphp + +
merge(['class' => 'flex flex-col gap-0.5 text-xs']) }}> + + Tab Switches: {{ $tabSwitches }} + + + Focus Loss / Overlay: {{ $focusLost }} + + + Eye Gaze Anomaly: {{ $gazeAlerts }} + + @if($lowerGaze > 0) + + Lower Gaze (>10s): {{ $lowerGaze }} + + @endif + @if($questionRepeat > 0) + + Question Repetition: {{ $questionRepeat }} + + @endif + @if($externalAi > 0) + + Parakeet / External AI: {{ $externalAi }} + + @endif +
diff --git a/resources/views/components/interview/report/artifacts-section.blade.php b/resources/views/components/interview/report/artifacts-section.blade.php new file mode 100644 index 0000000..c73a1d7 --- /dev/null +++ b/resources/views/components/interview/report/artifacts-section.blade.php @@ -0,0 +1,55 @@ +@props([ + 'interview', +]) + +@if(!empty($interview->candidate_notes) || !empty($interview->interviewer_notes) || !empty($interview->candidate_drawing) || (is_array($interview->formatted_recordings) && count($interview->formatted_recordings) > 0)) +
+ 📝 Workspace Artifacts, Evaluation Notes & Call Session Recordings +
+
+ @if(!empty($interview->candidate_notes)) +
+ CANDIDATE NOTEPAD NOTES (UNIQUE ID SYNCED): +
+
{{ $interview->candidate_notes }}
+ @endif + + @if(!empty($interview->interviewer_notes)) +
+ INTERVIEWER EVALUATION NOTES (STORED BY UNIQUE ID): +
+
{{ $interview->interviewer_notes }}
+ @endif + + @if(!empty($interview->candidate_drawing)) +
+ CANDIDATE DRAWING DIAGRAM: +
+ Candidate Drawing + @endif + + @if(is_array($interview->formatted_recordings) && count($interview->formatted_recordings) > 0) +
+ 📹 STORED CALL SESSION RECORDINGS ({{ count($interview->formatted_recordings) }} RECORDINGS): + 📜 Scroll to view all +
+
+ @foreach($interview->formatted_recordings as $displayIdx => $rec) +
+
+ Recording #{{ count($interview->formatted_recordings) - $displayIdx }} ({{ $rec['created_at'] }}) + + 📥 Download MP4 Video + +
+ +
+ @endforeach +
+ @endif +
+@endif diff --git a/resources/views/components/interview/report/audit-table.blade.php b/resources/views/components/interview/report/audit-table.blade.php new file mode 100644 index 0000000..0e48f26 --- /dev/null +++ b/resources/views/components/interview/report/audit-table.blade.php @@ -0,0 +1,37 @@ +@props([ + 'logs' => [], +]) + +@if(is_array($logs) && count($logs) > 0) +
+ + + + + + + + + + @foreach($logs as $log) + + + + + + @endforeach + +
TimestampViolation CategoryAudit Details
+ {{ isset($log['timestamp']) ? \Carbon\Carbon::parse($log['timestamp'])->format('H:i:s T') : '--:--:--' }} + + {{ str_replace('_', ' ', $log['type'] ?? 'Violation') }} + + {{ $log['details'] ?? 'Incident flagged by proctoring engine.' }} +
+
+@else +
+ + Zero proctoring violations or malpractice detected during the session. +
+@endif diff --git a/resources/views/components/interview/report/code-section.blade.php b/resources/views/components/interview/report/code-section.blade.php new file mode 100644 index 0000000..8cb4397 --- /dev/null +++ b/resources/views/components/interview/report/code-section.blade.php @@ -0,0 +1,21 @@ +@props([ + 'code' => null, + 'output' => null, + 'language' => 'code', +]) + + +
+ 💻 Submitted Code Solution ({{ strtoupper($language) }}) +
+
+{{ $code ?? '// No code solution submitted by candidate.' }} +
+ + +
+ 🖥️ Engine Execution Stdout Output +
+
+{{ $output ?? 'No execution output recorded.' }} +
diff --git a/resources/views/components/interview/report/header.blade.php b/resources/views/components/interview/report/header.blade.php new file mode 100644 index 0000000..29ed349 --- /dev/null +++ b/resources/views/components/interview/report/header.blade.php @@ -0,0 +1,39 @@ +@props([ + 'interview', +]) + + +
+
+ + Executive Assessment Performance Report +
+ +
+ + +
+
+
+ SingleLogin Enterprise Assessment +
+
+ Candidate Technical Competency & Behavioral Audit Report +
+
+ +
+ + Executive Summary + +
+ Report ID: RPT-{{ $interview->submission_unique_id }} +
+
+ Date: {{ now()->format('M d, Y - H:i:s T') }} +
+
+
diff --git a/resources/views/components/interview/report/incident-grid.blade.php b/resources/views/components/interview/report/incident-grid.blade.php new file mode 100644 index 0000000..23403f3 --- /dev/null +++ b/resources/views/components/interview/report/incident-grid.blade.php @@ -0,0 +1,43 @@ +@props([ + 'metrics' => [], +]) + +@php + $tabSwitches = $metrics['tab_switches'] ?? 0; + $focusLosses = $metrics['focus_lost'] ?? 0; + $gazeAnomalies = $metrics['gaze_alerts'] ?? 0; + $pasteEvents = $metrics['paste_events'] ?? 0; + $lowerGaze = $metrics['lower_gaze'] ?? 0; + $questionRepeat = $metrics['question_repeat'] ?? 0; +@endphp + +
+ 🔍 Behavioral Audit & Proctoring Incident Breakdown +
+ +
+
+
{{ $tabSwitches }}
+
Tab Switches
+
+
+
{{ $focusLosses }}
+
Focus Lost
+
+
+
{{ $gazeAnomalies }}
+
Gaze Anomalies
+
+
+
{{ $pasteEvents }}
+
Code Pastes
+
+
+
{{ $lowerGaze }}
+
📱 Lower Gaze
+
+
+
{{ $questionRepeat }}
+
🗣️ Question Repeat
+
+
diff --git a/resources/views/components/interview/report/meta-grid.blade.php b/resources/views/components/interview/report/meta-grid.blade.php new file mode 100644 index 0000000..ca125b3 --- /dev/null +++ b/resources/views/components/interview/report/meta-grid.blade.php @@ -0,0 +1,32 @@ +@props([ + 'interview', +]) + +@php + $statusColor = match($interview->status) { + 'completed' => 'text-emerald-600', + 'blocked' => 'text-red-600', + default => 'text-indigo-600', + }; +@endphp + +
+
+ + {{ $interview->candidate_name }} +
+
+ + {{ $interview->candidate_email }} +
+
+ + {{ $interview->language }} +
+
+ + + {{ $interview->status }} + +
+
diff --git a/resources/views/components/interview/report/score-card.blade.php b/resources/views/components/interview/report/score-card.blade.php new file mode 100644 index 0000000..31d152f --- /dev/null +++ b/resources/views/components/interview/report/score-card.blade.php @@ -0,0 +1,46 @@ +@props([ + 'integrityScore' => 100, + 'integrityLabel' => 'Optimal Candidate Trust', + 'integrityColor' => '#10b981', + 'incidentCount' => 0, + 'codeScore' => 0, + 'hasSubmittedCode' => false, +]) + +@php + $codeLabel = $codeScore >= 80 ? 'Strong Technical Match' : ($codeScore >= 50 ? 'Moderate Competency' : 'Needs Further Review'); +@endphp + +
+ +
+
+ 🛡️ Behavioral Integrity Rating +
+
+ {{ $integrityScore }}% +
+
+ {{ $integrityLabel }} +
+
+ Recorded Violations: {{ $incidentCount }} incident(s) +
+
+ + +
+
+ 💻 Technical Code Competency +
+
+ {{ $codeScore }} / 100 +
+
+ {{ $codeLabel }} +
+
+ Solution Code: {{ $hasSubmittedCode ? 'Submitted' : 'Pending' }} +
+
+
diff --git a/resources/views/components/interview/report/signoff.blade.php b/resources/views/components/interview/report/signoff.blade.php new file mode 100644 index 0000000..169092a --- /dev/null +++ b/resources/views/components/interview/report/signoff.blade.php @@ -0,0 +1,23 @@ +@props([ + 'recommended' => true, +]) + +
+
+
+ HR & Lead Panel Approval +
+
+ SingleLogin Enterprise HR Board +
+
+ +
+
+ Final Recommendation +
+
+ {{ $recommended ? 'RECOMMENDED FOR HIRE' : 'REQUIRES FURTHER REVIEW / FLAGGED' }} +
+
+
diff --git a/resources/views/components/interview/schedule-drawer.blade.php b/resources/views/components/interview/schedule-drawer.blade.php new file mode 100644 index 0000000..77489a1 --- /dev/null +++ b/resources/views/components/interview/schedule-drawer.blade.php @@ -0,0 +1,82 @@ +@props([ + 'interviewers' => [], +]) + + +
+ @csrf +
+
+ Candidate Name + +
+ +
+ Candidate Email + +
+ +
+
+ Phone Number + +
+
+ Access Duration + + + + + + + +
+
+ +
+ Start Time (Timeline) + +
+ +
+ Coding Language + + + + + + + + +
+ +
+
+ Assign Internal Interviewers / Panelists +
+
+ @foreach($interviewers as $usr) + + @endforeach +
+
+
+ +
+ + Cancel + + + Create Session & Password + +
+
+
diff --git a/resources/views/components/interview/schedule-modal.blade.php b/resources/views/components/interview/schedule-modal.blade.php new file mode 100644 index 0000000..8c5af67 --- /dev/null +++ b/resources/views/components/interview/schedule-modal.blade.php @@ -0,0 +1,75 @@ +@props([ + 'interviewers' => [], +]) + + +
+ @csrf +
+
+ Candidate Name + +
+
+ Candidate Email + +
+
+ +
+
+ Phone Number + +
+
+ Start Time (Timeline) + +
+
+ Access Duration + + + + + + + +
+
+ +
+ Coding Language + + + + + + + + +
+ +
+
+ Assign Internal Interviewers / Panelists +
+
+ @foreach($interviewers as $usr) + + @endforeach +
+
+ +
+ + Cancel + + + Create Session & Password + +
+
+
diff --git a/resources/views/components/interview/session-row.blade.php b/resources/views/components/interview/session-row.blade.php new file mode 100644 index 0000000..34936e1 --- /dev/null +++ b/resources/views/components/interview/session-row.blade.php @@ -0,0 +1,89 @@ +@props([ + 'interview', +]) + +@php + $metrics = $interview->proctor_metrics; +@endphp + + + + +
+ {{ $interview->candidate_name }} +
{{ $interview->candidate_email }} • {{ $interview->candidate_phone }}
+
+
+ Temp Pass: {{ $interview->temp_password }} +
+ +
+
+ + + + + + {{ $interview->submission_unique_id }} + + + + + + @if($interview->isExpired()) + EXPIRED + @elseif($interview->status === 'completed') + COMPLETED + @elseif($interview->call_status === 'active') + CALL IN PROGRESS + @elseif($interview->isActiveTimeline()) + TIMELINE LIVE + @else + SCHEDULED + @endif +
+ Timeline: {{ $interview->formatted_timeline }} +
+ + + + + + {{ $interview->language }} + + + + + + + + + + +
+ + + + PDF Report + + + + + @if($interview->call_status === 'active') + + + Join Active Call + + + @else + + + Join Call + + + @endif +
+ + diff --git a/resources/views/components/interview/sos-modal.blade.php b/resources/views/components/interview/sos-modal.blade.php new file mode 100644 index 0000000..9388c32 --- /dev/null +++ b/resources/views/components/interview/sos-modal.blade.php @@ -0,0 +1,13 @@ + +
+ Violation details loading... +
+
+ + Acknowledge Alert + + + Acknowledge & Disable SOS + +
+
diff --git a/resources/views/components/interview/tabs/code-tab.blade.php b/resources/views/components/interview/tabs/code-tab.blade.php new file mode 100644 index 0000000..22a1001 --- /dev/null +++ b/resources/views/components/interview/tabs/code-tab.blade.php @@ -0,0 +1,7 @@ +
+
Current code solution — visible even if candidate does not share screen
+ + +
Execution stdout / stderr
+ +
diff --git a/resources/views/components/interview/tabs/drawing-tab.blade.php b/resources/views/components/interview/tabs/drawing-tab.blade.php new file mode 100644 index 0000000..3955662 --- /dev/null +++ b/resources/views/components/interview/tabs/drawing-tab.blade.php @@ -0,0 +1,7 @@ + diff --git a/resources/views/components/interview/tabs/notes-tab.blade.php b/resources/views/components/interview/tabs/notes-tab.blade.php new file mode 100644 index 0000000..069386c --- /dev/null +++ b/resources/views/components/interview/tabs/notes-tab.blade.php @@ -0,0 +1,4 @@ + diff --git a/resources/views/components/interview/tabs/recordings-tab.blade.php b/resources/views/components/interview/tabs/recordings-tab.blade.php new file mode 100644 index 0000000..ac179b7 --- /dev/null +++ b/resources/views/components/interview/tabs/recordings-tab.blade.php @@ -0,0 +1,11 @@ + diff --git a/resources/views/components/interview/tabs/screenshots-tab.blade.php b/resources/views/components/interview/tabs/screenshots-tab.blade.php new file mode 100644 index 0000000..e54f06f --- /dev/null +++ b/resources/views/components/interview/tabs/screenshots-tab.blade.php @@ -0,0 +1,9 @@ + diff --git a/resources/views/components/label.blade.php b/resources/views/components/label.blade.php new file mode 100644 index 0000000..904db63 --- /dev/null +++ b/resources/views/components/label.blade.php @@ -0,0 +1,10 @@ +@props([ + 'required' => false, +]) + + diff --git a/resources/views/components/layouts/candidate.blade.php b/resources/views/components/layouts/candidate.blade.php new file mode 100644 index 0000000..cda65ec --- /dev/null +++ b/resources/views/components/layouts/candidate.blade.php @@ -0,0 +1,37 @@ +@props([ + 'title' => 'Live Assessment Room', +]) + + + + + + + + {{ $title }} | SingleLogin + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + + + + + + + + + + + + + + @stack('styles') + @stack('head-scripts') + +merge(['class' => "bg-[#080c14] text-white h-screen flex flex-col font-['Instrument_Sans',sans-serif] overflow-hidden antialiased select-none"]) }}> + + {{ $slot }} + + @stack('scripts') + + diff --git a/resources/views/components/layouts/guest.blade.php b/resources/views/components/layouts/guest.blade.php new file mode 100644 index 0000000..4210489 --- /dev/null +++ b/resources/views/components/layouts/guest.blade.php @@ -0,0 +1,32 @@ +@props([ + 'title' => 'Candidate Portal', +]) + + + + + + + + {{ $title }} | SingleLogin + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + + + + @stack('styles') + @stack('head-scripts') + +merge(['class' => "bg-[#0b0f19] text-white min-h-screen flex items-center justify-center p-4 relative overflow-hidden font-['Instrument_Sans',sans-serif] antialiased"]) }}> + + +
+ +
+ {{ $slot }} +
+ + @stack('scripts') + + diff --git a/resources/views/components/layouts/interview.blade.php b/resources/views/components/layouts/interview.blade.php new file mode 100644 index 0000000..655d366 --- /dev/null +++ b/resources/views/components/layouts/interview.blade.php @@ -0,0 +1,57 @@ +@props([ + 'title' => 'Candidate Live Assessment Portal', + 'activeNav' => 'interview', +]) + + + + + + + + {{ $title }} | SingleLogin + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + + + + + + @stack('styles') + @stack('head-scripts') + +merge(['class' => "bg-[#0a0e17] text-white min-h-screen flex flex-col font-['Instrument_Sans',sans-serif] antialiased"]) }}> + + + +
+ @if(session('success')) + + {{ session('success') }} + + @endif + + @if(session('error')) + + {{ session('error') }} + + @endif + + {{ $slot }} +
+ + + + + + + @stack('scripts') + + diff --git a/resources/views/components/layouts/report.blade.php b/resources/views/components/layouts/report.blade.php new file mode 100644 index 0000000..3ba7f0f --- /dev/null +++ b/resources/views/components/layouts/report.blade.php @@ -0,0 +1,26 @@ +@props([ + 'title' => 'Executive Evaluation Report', +]) + + + + + + + {{ $title }} | SingleLogin + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + + + + @stack('styles') + @stack('head-scripts') + +merge(['class' => "bg-slate-100 text-slate-900 leading-normal p-5 md:p-10 font-['Instrument_Sans',sans-serif] antialiased print:bg-white print:p-0 print:text-black"]) }}> + + {{ $slot }} + + @stack('scripts') + + diff --git a/resources/views/components/select.blade.php b/resources/views/components/select.blade.php new file mode 100644 index 0000000..5be7854 --- /dev/null +++ b/resources/views/components/select.blade.php @@ -0,0 +1,25 @@ +@props([ + 'name' => null, + 'required' => false, + 'disabled' => false, + 'size' => 'md', +]) + +@php + $sizeClasses = [ + 'sm' => 'px-2.5 py-1.5 text-xs', + 'md' => 'px-3 py-2 text-xs', + 'lg' => 'px-3.5 py-2.5 text-sm', + ]; + + $classes = 'w-full bg-slate-900 border border-slate-700/60 rounded-lg text-white outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500/40 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ' . ($sizeClasses[$size] ?? $sizeClasses['md']); +@endphp + + diff --git a/resources/views/components/video-tile.blade.php b/resources/views/components/video-tile.blade.php index 38c3375..5bd67d5 100644 --- a/resources/views/components/video-tile.blade.php +++ b/resources/views/components/video-tile.blade.php @@ -21,7 +21,7 @@ 'focused' => false, ]) -
merge(['class' => 'video-tile relative aspect-[16/11] bg-[#0d1220] border rounded-[10px] overflow-hidden flex flex-col items-center justify-center transition-all ' . ($focused ? 'border-[rgba(75,130,247,0.35)] shadow-[0_0_0_1px_rgba(75,130,247,0.35)]' : 'border-[#1b2233]')]) }}> +
twMerge(['class' => 'video-tile relative aspect-[16/10] bg-[#0d1220] border-2 rounded-xl overflow-hidden flex flex-col items-center justify-center transition-all duration-200 ' . ($focused ? 'border-[rgba(75,130,247,0.35)] shadow-[0_0_0_1px_rgba(75,130,247,0.35)]' : 'border-[#1b2233]')]) }}> @if($showZoom || $showFullscreen)
@if($showZoom) @@ -44,16 +44,16 @@ @endif
-
+
{{ $initials }}
-
{{ $avatarTitle }}
-
+
{{ $avatarTitle }}
+
{{ $slot->isNotEmpty() ? $slot : "Waiting for candidate…" }}
- + {{ $badgeText }} @if($micStatusId || $camStatusId) diff --git a/resources/views/interview/candidate_login.blade.php b/resources/views/interview/candidate_login.blade.php index a83ae78..d1f947b 100644 --- a/resources/views/interview/candidate_login.blade.php +++ b/resources/views/interview/candidate_login.blade.php @@ -1,103 +1,40 @@ - - - - - - Candidate Assessment Login | SingleLogin - @vite(['resources/css/app.css', 'resources/js/app.js']) - - - - - - -