Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Reschedule posts by dragging them on the calendar (#455)
Paulo Castellano4dbb8d8bee79
diff --git a/.agents/skills/configure-nightwatch/SKILL.md b/.agents/skills/configure-nightwatch/SKILL.mdindex 1fc580bbd..000a031b1 100644--- a/.agents/skills/configure-nightwatch/SKILL.md+++ b/.agents/skills/configure-nightwatch/SKILL.md@@ -62,15 +62,10 @@ Sampling determines which entry points (requests, commands, scheduled tasks) triConfigure via environment variables:```bash-# Default: 100% sampling (all requests/commands captured)-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions-```**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.@@ -312,22 +307,17 @@ Redaction modifies captured data to remove or obfuscate sensitive information. U**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):```bash-# Customize redacted headers-NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key```**Redact request payloads** (disabled by default):```bash-# Enable payload capture-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true# Customize redacted fields-NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card```diff --git a/.agents/skills/configure-nightwatch/reference.md b/.agents/skills/configure-nightwatch/reference.mdindex b071d2f2e..eddd8842e 100644--- a/.agents/skills/configure-nightwatch/reference.md+++ b/.agents/skills/configure-nightwatch/reference.md@@ -21,49 +21,36 @@### High-Traffic Applications```bash-# Conservative sampling-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions# Filter noisy events-NIGHTWATCH_IGNORE_CACHE_EVENTS=trueNIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically-```### Privacy-Conscious Applications```bash-# Disable sensitive data collection-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=falseNIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN# Or use redaction in AppServiceProvider-```### Balanced Configuration (Recommended Start)```bash-# Sample rates-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0# Filter obvious noise programmatically-# Redact PII as needed-```---diff --git a/.agents/skills/infer-conventions/SKILL.md b/.agents/skills/infer-conventions/SKILL.mdindex 11a932753..b42bca89e 100644--- a/.agents/skills/infer-conventions/SKILL.md+++ b/.agents/skills/infer-conventions/SKILL.md@@ -1,6 +1,7 @@---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."+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, API responses), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+disable-model-invocation: truelicense: MITmetadata:author: laraveldiff --git a/.agents/skills/infer-conventions/references/checklist.md b/.agents/skills/infer-conventions/references/checklist.mdindex f8d1b1441..3de1f1775 100644--- a/.agents/skills/infer-conventions/references/checklist.md+++ b/.agents/skills/infer-conventions/references/checklist.md@@ -9,11 +9,11 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app## A. Validation & HTTP input1. 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`.+ - 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`.+ - 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`.@@ -26,7 +26,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app7. 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.+ - 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`.@@ -37,7 +37,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app11. 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(`.+ - Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.## D. Eloquent & models@@ -56,7 +56,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app19. 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/`.+ - Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.## E. Architecture & organization@@ -89,11 +89,11 @@ This app ships a frontend stack, so the items below apply.## G. Database & migrations33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.- - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+ - 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.+ - 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.@@ -108,14 +108,14 @@ This app ships a frontend stack, so the items below apply.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/`.+ - 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 resources43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.- - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+ - 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.@@ -126,7 +126,7 @@ This app ships a frontend stack, so the items below apply.## J. Strings, collections & dates47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.- - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+ - 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.diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.mdindex d136d7556..311ab8443 100644--- a/.agents/skills/laravel-best-practices/SKILL.md+++ b/.agents/skills/laravel-best-practices/SKILL.md@@ -48,7 +48,7 @@ Cross-cutting changes often need more than one rule file.| 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) |+| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill || Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) || Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |diff --git a/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.mdindex f12876e4c..54dd783d9 100644--- a/.agents/skills/laravel-best-practices/rules/advanced-queries.md+++ b/.agents/skills/laravel-best-practices/rules/advanced-queries.md@@ -1,8 +1,8 @@-# Advanced Query Patterns+# Advanced Query Best Practices-## Use `addSelect()` Subqueries for Single Values from Has-Many+## Select Single Relationship Values with Subqueries-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.+When only one value from a has-many relationship is needed, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. This selects the value as part of the main query without an additional relationship query.```phppublic function scopeWithLastLoginAt($query): void@@ -16,14 +16,14 @@ public function scopeWithLastLoginAt($query): void}```-## Create Dynamic Relationships via Subquery FK+## Create Dynamic Relationships with a Subquery Foreign Key-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.+The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still executes a separate query, but it avoids loading the full has-many collection.```phppublic function lastLogin(): BelongsTo{- return $this->belongsTo(Login::class);+ return $this->belongsTo(Login::class, 'last_login_id');}public function scopeWithLastLogin($query): void@@ -37,9 +37,9 @@ public function scopeWithLastLogin($query): void}```-## Use Conditional Aggregates Instead of Multiple Count Queries+## Combine Related Counts with Conditional Aggregates-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.+Combine several counts over the same filtered data set into one query by using conditional aggregates. Use `toBase()` when only scalar values are needed and model hydration provides no benefit. Confirm the expression syntax against the application's database engine.```php$statuses = Feature::toBase()@@ -49,50 +49,50 @@ $statuses = Feature::toBase()->first();```-## Use `setRelation()` to Prevent Circular N+1+## Reuse Loaded Parent Models with `setRelation()`-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.+When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. This avoids an additional lazy-loading query for each child.```php$feature->load('comments.user');$feature->comments->each->setRelation('feature', $feature);```-## Prefer `whereIn` + Subquery Over `whereHas`+## Compare `whereHas()` with an `IN` Subquery-`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.+`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form may be faster depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data; neither subquery loads its result set into PHP memory.-Incorrect (correlated EXISTS re-executes per row):+Option using `EXISTS`:```php$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));```-Correct (index-friendly subquery, no PHP memory overhead):+Option using `IN`:```php$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));```-## Sometimes Two Simple Queries Beat One Complex Query+## Measure Two Simple Queries Against 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.+Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.-## Use Compound Indexes Matching `orderBy` Column Order+## Design Composite Indexes for the Query-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.+For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that an index will be used. Verify the query plan.```php// Migration$table->index(['last_name', 'first_name']);-// Query — column order must match the index+// Query that this index may supportUser::query()->orderBy('last_name')->orderBy('first_name')->paginate();```-## Use Correlated Subqueries for Has-Many Ordering+## Consider a Correlated Subquery 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.+When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes.```phppublic function scopeOrderByLastLogin($query): voiddiff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.mdindex 138d5a48d..d0a9a55c0 100644--- a/.agents/skills/laravel-best-practices/rules/architecture.md+++ b/.agents/skills/laravel-best-practices/rules/architecture.md@@ -1,8 +1,8 @@# Architecture Best Practices-## Single-Purpose Action Classes+## Extract Focused Business Operations-Extract discrete business operations into invokable Action classes.+Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel; follow the project's naming and invocation conventions.```phpclass CreateOrderAction@@ -19,11 +19,12 @@ class CreateOrderAction}```-## Use Dependency Injection+## Inject Required Dependencies-Always use constructor injection. Avoid `app()` or `resolve()` inside classes.+Prefer constructor injection for dependencies required throughout an object's lifetime. Method injection is appropriate for dependencies needed by one controller action, listener, job handler, or other container-invoked method. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.++Hidden dependency:-Incorrect:```phpclass OrderController extends Controller{@@ -36,24 +37,24 @@ class OrderController extends Controller}```-Correct:+Injected dependency:+```phpclass OrderController extends Controller{- public function __construct(private OrderService $service) {}-- public function store(StoreOrderRequest $request)+ public function store(StoreOrderRequest $request, OrderService $service){- return $this->service->create($request->validated());+ return $service->create($request->validated());}}```-## Code to Interfaces+## Depend on Contracts at Boundaries++Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.-Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.+Concrete boundary dependency:-Incorrect (concrete dependency):```phpclass OrderService{@@ -61,7 +62,8 @@ class OrderService}```-Correct (interface dependency):+Contract boundary dependency:+```phpinterface PaymentGateway{@@ -80,86 +82,99 @@ Bind in a service provider:$this->app->bind(PaymentGateway::class, StripeGateway::class);```-## Default Sort by Descending+## Specify a Deterministic Sort Order-When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.+Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters.++Unspecified order:-Incorrect:```php$posts = Post::paginate();```-Correct:+Newest first with a stable tie-breaker:+```php-$posts = Post::latest()->paginate();+$posts = Post::query()+ ->orderByDesc('created_at')+ ->orderByDesc('id')+ ->paginate();```## Use Atomic Locks for Race Conditions-Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.+Use a lock when concurrent execution must be serialized. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems. Set the lease (`10` below) longer than the callback can ever run: once it expires, another process can acquire the lock while the first is still working.```phpCache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {$order->process();});-// Or at query level-$product = Product::where('id', $id)->lockForUpdate()->first();+// Or at query level, inside a transaction+DB::transaction(function () use ($id) {+ $product = Product::where('id', $id)->lockForUpdate()->first();++ // Read and update the product while the database lock is held.+});```## 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.+When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware.Incorrect:+```php-strlen('José'); // 5 (bytes, not characters)-strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte+strlen('José'); // 5 bytes, not 4 characters+strtolower('MÜNCHEN'); // Does not lowercase Ü```Correct:+```php-mb_strlen('José'); // 4 (characters)-mb_strtolower('MÜNCHEN'); // 'münchen'+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'+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.+For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after the response has been sent but remains in the same PHP process.++Queued and durable:-Incorrect (job overhead for trivial work):```phpdispatch(new LogPageView($page));```-Correct (runs after response, same process):+Deferred in the current process:+```phpdefer(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 a queued job when the work needs retries, queue controls, or durability across process failures.## Use `Context` for Request-Scoped Data-The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.+The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.```php// In middlewareContext::add('tenant_id', $request->header('X-Tenant-ID'));-// Anywhere later — controllers, jobs, log context+// Later in the same execution lifecycle$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`.+Visible context is added to log context, and both visible and hidden context are captured and restored for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless that propagation is intended.## Use `Concurrency::run()` for Parallel Execution-Run independent operations in parallel using child processes — no async libraries needed.+Run independent operations concurrently through Laravel's configured concurrency driver.```phpuse Illuminate\Support\Facades\Concurrency;@@ -170,13 +185,14 @@ use Illuminate\Support\Facades\Concurrency;]);```-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.+With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver executes closures sequentially and is useful primarily during testing.-## Convention Over Configuration+## Follow Framework Conventions-Follow Laravel conventions. Don't override defaults unnecessarily.+Follow Laravel conventions unless the domain or an existing schema requires an override.++Customized schema:-Incorrect:```phpclass Customer extends Model{@@ -190,7 +206,8 @@ class Customer extends Model}```-Correct:+Conventional schema:+```phpclass Customer extends Model{diff --git a/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.mdindex 5f0b3a1e3..4ea2c6c34 100644--- a/.agents/skills/laravel-best-practices/rules/blade-views.md+++ b/.agents/skills/laravel-best-practices/rules/blade-views.md@@ -1,8 +1,8 @@-# Blade & Views Best Practices+# Blade and View Best Practices## Use `$attributes->merge()` in Component Templates-Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.+Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior.```blade<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>@@ -12,25 +12,25 @@ Hardcoding classes prevents consumers from adding their own. `merge()` combines## 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.+If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response.-## Prefer Blade Components Over `@include`+## Prefer Components for Explicit Interfaces-`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.+Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include remains suitable for a small partial that intentionally uses the current view data; pass an explicit data array when implicit variable sharing would obscure its dependencies.-## Use View Composers for Shared View Data+## Share Compatible View Data with a View Composer-If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.+Use a view composer to centralize data needed whenever one or more named Blade views are rendered. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view; it does not supply data to JSON, streamed, or other non-view responses.-## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)+## Return Blade Fragments for Partial Rendering-A single view can return either the full page or just a fragment, keeping routing clean.+A route can return either a full view or a named fragment for clients such as htmx or Turbo.```phpreturn view('dashboard', compact('users'))->fragmentIf($request->hasHeader('HX-Request'), 'user-list');```-## Use `@aware` for Deeply Nested Component Props+## Share Parent Component Props with `@aware`-Avoids re-passing parent props through every level of nested components.+Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. It does not expose an ancestor's default prop value unless that value was passed through the attribute bag.diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.mdindex 67408d6e1..cd2ffd602 100644--- a/.agents/skills/laravel-best-practices/rules/caching.md+++ b/.agents/skills/laravel-best-practices/rules/caching.md@@ -1,10 +1,13 @@# Caching Best Practices-## Use `Cache::remember()` Instead of Manual Get/Put+## Use `Cache::remember()` for Cache-Aside Reads-Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.+`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value; use an atomic lock when duplicate computation must be prevented.++The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses.Incorrect:+```php$val = Cache::get('stats');if (! $val) {@@ -14,27 +17,42 @@ if (! $val) {```Correct:+```php$val = Cache::remember('stats', 60, fn () => $this->computeStats());```-## Use `Cache::flexible()` for Stale-While-Revalidate+## Consider `Cache::flexible()` for Stale-While-Revalidate++For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response; it is not a durable background job. Once the stale period has elapsed, the request recomputes the value synchronously.++Synchronous expiration:++```php+Cache::remember('users', 300, fn () => User::all());+```-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.+Stale-while-revalidate tradeoff:-Incorrect: `Cache::remember('users', 300, fn () => User::all());`+```php+Cache::flexible('users', [300, 600], 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.+This value is fresh for five minutes and may be served stale until ten minutes after it was cached.-## Use `Cache::memo()` to Avoid Redundant Hits Within a Request+## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution-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.+If the same cache key is read repeatedly during one request or job, `memo()` decorates a cache store and retains resolved values in memory for that execution.-`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.+```php+$settings = Cache::memo()->get('settings');+```++Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate.## 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`.+Tags group related entries for invalidation without tracking each key. Cache tags are not supported by the `file`, `dynamodb`, or `database` drivers; confirm support before choosing a store.```phpCache::tags(['user-1'])->flush();@@ -42,15 +60,27 @@ 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.+`add()` atomically writes a value only when the key does not already exist.++Incorrect:-Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`+```php+if (! Cache::has('lock')) {+ Cache::put('lock', true, 10);+}+```++Correct:++```php+Cache::add('lock', true, 10);+```-Correct: `Cache::add('lock', true, 10);`+Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required.-## Use `once()` for Per-Request Memoization+## Use `once()` for In-Process 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.+`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store.```phppublic function roles(): Collection@@ -59,11 +89,11 @@ public function roles(): Collection}```-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.+Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions.## Configure Failover Cache Stores in Production-If Redis goes down, the app falls back to a secondary store automatically.+The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and data is not replicated between stores.```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.mdindex 18e8d9e1d..211fec11d 100644--- a/.agents/skills/laravel-best-practices/rules/collections.md+++ b/.agents/skills/laravel-best-practices/rules/collections.md@@ -2,41 +2,69 @@## Use Higher-Order Messages for Simple Operations-Incorrect:+Explicit closure:+```php$users->each(function (User $user) {$user->markAsVip();});```-Correct: `$users->each->markAsVip();`+Concise equivalent:++```php+$users->each->markAsVip();+```++Higher-order messages are available for supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.-Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.+## Choose Between `cursor()` and `lazy()`-## Choose `cursor()` vs. `lazy()` Correctly+`cursor()` executes one query and hydrates models individually, but it cannot eager load relationships. The database driver's result buffering can still consume substantial memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.-- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).-- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.+`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration.++With relationships:++```php+User::with('roles')->lazy()->each(function (User $user) {+ // The roles for this chunk have been eager loaded.+});+```-Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.+Without relationships:-Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.+```php+User::cursor()->each(function (User $user) {+ // Process model attributes.+});+```## 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.+`lazy()` uses offset pagination, so updates to columns that affect the query can shift rows and cause records to be skipped or processed twice. `lazyById()` paginates by a monotonic key and is safer when updating other columns during iteration. Do not change the pagination key itself while iterating.## Use `toQuery()` for Bulk Operations on Collections-Avoids manual `whereIn` construction.+Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.++Manual query:++```php+User::whereIn('id', $users->modelKeys())->update(['active' => false]);+```++Collection query:-Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`+```php+$users->toQuery()->update(['active' => false]);+```-Correct: `$users->toQuery()->update([...]);`+`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when those events are not required.## Use `#[CollectedBy]` for Custom Collection Classes-More declarative than overriding `newCollection()`.+The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.```php#[CollectedBy(UserCollection::class)]diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.mdindex 9bea727b3..82691c42a 100644--- a/.agents/skills/laravel-best-practices/rules/config.md+++ b/.agents/skills/laravel-best-practices/rules/config.md@@ -1,73 +1,85 @@# Configuration Best Practices-## `env()` Only in Config Files+## Read Environment Variables in Configuration Files-Direct `env()` calls may return `null` when config is cached.+Call `env()` only from configuration files. After configuration is cached, Laravel does not load the application's `.env` file, so application code should read configuration values through `config()`.Incorrect:+```php$key = env('API_KEY');```Correct:+```php// config/services.php-'key' => env('API_KEY'),+return [+ 'key' => env('API_KEY'),+];// Application code$key = config('services.key');```-## Use Encrypted Env or External Secrets+## Protect Production Secrets-Never store production secrets in plain `.env` files in version control.+Do not commit plaintext production secrets. Laravel can encrypt an environment file so its encrypted form can be stored safely, while deployment platforms can supply secrets through their native secret stores.Incorrect:-```bash-# .env committed to repo or shared in Slack--STRIPE_SECRET=sk_live_abc123-AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI+```bash+# A plaintext .env file committed to the repository+STRIPE_SECRET=<your-stripe-secret>+AWS_SECRET_ACCESS_KEY=<your-aws-secret>```-Correct:+Encrypted environment file:+```bashphp artisan env:encrypt --env=production --readablephp artisan env:decrypt --env=production```-For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.+For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime.## Use `App::environment()` for Environment ChecksIncorrect:+```phpif (env('APP_ENV') === 'production') {+ // ...+}```Correct:+```phpif (app()->isProduction()) {-// or+ // ...+}+if (App::environment('production')) {+ // ...+}```-## Use Constants and Language Files+## Name Repeated Domain Values-Use class constants instead of hardcoded magic strings for model states, types, and statuses.+Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant.```php-// Incorrect+// Repeated literalreturn $this->type === 'normal';-// Correct+// Named domain valuereturn $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.+If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages.```php-// Only when lang files already exist in the project+// In a localized applicationreturn 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.mdindex c49ba164e..3f339770d 100644--- a/.agents/skills/laravel-best-practices/rules/db-performance.md+++ b/.agents/skills/laravel-best-practices/rules/db-performance.md@@ -1,10 +1,11 @@# Database Performance Best Practices-## Always Eager Load Relationships+## Eager Load Relationships Before Iterating-Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.+When a relationship will be accessed for many models, eager load it with `with()` to avoid running one initial query plus one relationship query per model, commonly called an N+1 query pattern. Lazy loading is reasonable when the relationship may not be needed or only one model is involved.++Lazy-loaded version:-Incorrect (N+1 — executes 1 + N queries):```php$posts = Post::all();foreach ($posts as $post) {@@ -12,7 +13,8 @@ foreach ($posts as $post) {}```-Correct (2 queries total):+Eager-loaded version:+```php$posts = Post::with('author')->get();foreach ($posts as $post) {@@ -20,7 +22,7 @@ foreach ($posts as $post) {}```-Constrain eager loads to select only needed columns (always include the foreign key):+Constrain eager loads when large columns are unnecessary. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, while selecting `posts.id` preserves each related model's primary key:```php$users = User::with(['posts' => function ($query) {@@ -42,31 +44,34 @@ public function boot(): void}```-Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.+By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`.## Select Only Needed Columns-Avoid `SELECT *` — especially when tables have large text or JSON columns.+Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit.++All columns:-Incorrect:```php$posts = Post::with('author')->get();```-Correct:+Selected columns:+```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.+When limiting selected columns, retain every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key.++## Process Large Data Sets Incrementally-## Chunk Large Datasets+Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget.-Never load thousands of records at once. Use chunking for batch processing.+Loads the complete result set:-Incorrect:```php$users = User::all();foreach ($users as $user) {@@ -74,7 +79,8 @@ foreach ($users as $user) {}```-Correct:+Processes bounded chunks:+```phpUser::where('subscribed', true)->chunk(200, function ($users) {foreach ($users as $user) {@@ -83,7 +89,7 @@ User::where('subscribed', true)->chunk(200, function ($users) {});```-Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:+Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change:```phpUser::where('active', false)->chunkById(200, function ($users) {@@ -91,11 +97,14 @@ User::where('active', false)->chunkById(200, function ($users) {});```-## Add Database Indexes+For read-only, attribute-only iteration, `cursor()` hydrates models individually from one query, although some database drivers still buffer raw results. Use `lazy()` when relationships must be eager loaded in chunks, and use `lazyById()` or `chunkById()` when updates can affect query membership. See the collection rules for detailed tradeoffs.-Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.+## Add Indexes for Measured Query Patterns++Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index; selectivity, write cost, existing indexes, and the database query plan all matter.++Schema without an application-specific query index:-Incorrect:```phpSchema::create('orders', function (Blueprint $table) {$table->id();@@ -105,24 +114,26 @@ Schema::create('orders', function (Blueprint $table) {});```-Correct:+Schema optimized for `WHERE status = ? ORDER BY created_at`:+```phpSchema::create('orders', function (Blueprint $table) {$table->id();- $table->foreignId('user_id')->index()->constrained();- $table->string('status')->index();+ $table->foreignId('user_id')->constrained();+ $table->string('status');$table->timestamps();$table->index(['status', 'created_at']);});```-Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).+Confirm composite index column order and effectiveness with production-like data and the database's query-plan tools. Also check whether the database already created an index to support a foreign key before adding another one.++## Count Relationships Without Loading Them-## Use `withCount()` for Counting Relations+Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory.-Never load entire collections just to count them.+Loads related models:-Incorrect:```php$posts = Post::all();foreach ($posts as $post) {@@ -130,7 +141,8 @@ foreach ($posts as $post) {}```-Correct:+Selects relationship counts:+```php$posts = Post::withCount('comments')->get();foreach ($posts as $post) {@@ -149,39 +161,24 @@ $posts = Post::withCount([])->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);-}-```+## Keep Queries Out of Blade Templates-Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.+Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable.-## No Queries in Blade Templates+Query in the template:-Never execute queries in Blade templates. Pass data from controllers.--Incorrect:```blade@foreach (User::all() as $user){{ $user->profile->name }}@endforeach```-Correct:+Data prepared before rendering:+```php// Controller$users = User::with('profile')->get();+return view('users.index', compact('users'));```diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.mdindex bd2cfca08..5a89510d0 100644--- a/.agents/skills/laravel-best-practices/rules/eloquent.md+++ b/.agents/skills/laravel-best-practices/rules/eloquent.md@@ -1,8 +1,8 @@# Eloquent Best Practices-## Use Correct Relationship Types+## Define Precise Relationship Types-Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.+Define the relationship that matches the database association, and declare its concrete return type.```phppublic function comments(): HasMany@@ -20,7 +20,8 @@ public function author(): BelongsToExtract reusable query constraints into local scopes to avoid duplication.-Incorrect:+Duplicated constraints:+```php$active = User::where('verified', true)->whereNotNull('activated_at')->get();$articles = Article::whereHas('user', function ($q) {@@ -28,7 +29,8 @@ $articles = Article::whereHas('user', function ($q) {})->get();```-Correct:+Reusable local scope:+```php#[Scope]protected function active(Builder $query): Builder@@ -45,7 +47,8 @@ $articles = Article::whereHas('user', fn ($q) => $q->active())->get();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):+Global scope tradeoff:+```phpclass PublishedScope implements Scope{@@ -54,10 +57,12 @@ class PublishedScope implements Scope$builder->where('published', true);}}-// Now admin panels, reports, and background jobs all silently skip drafts++// Admin panels, reports, and jobs now omit drafts unless the scope is removed.```-Correct (local scope you opt into):+Explicit local scope:+```php#[Scope]protected function published(Builder $query): Builder@@ -84,16 +89,18 @@ protected function casts(): array}```-## Cast Date Columns Properly+## Cast Date and Time Attributes++Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps.-Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.+Manual parsing in the template:-Incorrect:```blade-{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}+{{ Carbon::parse($order->ordered_at)->toDateString() }}```-Correct:+Model cast:+```phpprotected function casts(): array{@@ -110,24 +117,27 @@ protected function casts(): array## Use `whereBelongsTo()` for Relationship Queries-Cleaner than manually specifying foreign keys.+`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key.++Foreign key constraint:-Incorrect:```phpPost::where('user_id', $user->id)->get();```-Correct:+Relationship-aware constraint:+```phpPost::whereBelongsTo($user)->get();Post::whereBelongsTo($user, 'author')->get();```-## Avoid Hardcoded Table Names in Queries+## Keep Application Queries Model-Aware-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).+Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL legitimately require table names, so use them when their lower-level behavior is intentional.++Lower-level alternatives:-Incorrect:```phpDB::table('users')->where('active', true)->get();@@ -136,15 +146,13 @@ $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();+Model-aware queries:-// Even better — use Eloquent or the query builder instead of raw SQL+```phpUser::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.+When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer; keep those references covered by tests when schema changes are possible.-**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.+In migrations, use explicit table names rather than application models. Migrations are historical snapshots, while models and their scopes can change after a migration is deployed.diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.mdindex 4b1486676..afcdf4ac5 100644--- a/.agents/skills/laravel-best-practices/rules/error-handling.md+++ b/.agents/skills/laravel-best-practices/rules/error-handling.md@@ -1,15 +1,18 @@# Error Handling Best Practices-## Exception Reporting and Rendering+## Choose Where to Report and Render Exceptions-There are two valid approaches — choose one and apply it consistently across the project.+Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project.-**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:+Exception methods keep behavior beside the exception definition:```phpclass InvalidOrderException extends Exception{- public function report(): void { /* custom reporting */ }+ public function report(): void+ {+ // Send the exception to a custom reporter.+ }public function render(Request $request): Response{@@ -18,38 +21,40 @@ class InvalidOrderException extends Exception}```-**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:+Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together:```php->withExceptions(function (Exceptions $exceptions) {- $exceptions->report(function (InvalidOrderException $e) { /* ... */ });+ $exceptions->report(function (InvalidOrderException $e) {+ // Send the exception to a custom reporter.+ });$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.+An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering.-## Use `ShouldntReport` for Exceptions That Should Never Log+## Mark Exceptions the Handler Should Not Report-More discoverable than listing classes in `dontReport()`.+Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly.```phpclass PodcastProcessingException extends Exception implements ShouldntReport {}```-## Throttle High-Volume Exceptions+## Throttle High-Volume Exception Reports-A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.+A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits.-## Enable `dontReportDuplicates()`+## Prevent Duplicate Reports of One Exception Instance-Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.+Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message.-## Force JSON Error Rendering for API Routes+## Define JSON Rendering for API Routes-Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.+Laravel normally uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes.```php$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {@@ -59,7 +64,7 @@ $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {## 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.+Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.```phpclass InvalidOrderException extends Exceptiondiff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.mdindex 82e329e8f..a8cce31a8 100644--- a/.agents/skills/laravel-best-practices/rules/events-notifications.md+++ b/.agents/skills/laravel-best-practices/rules/events-notifications.md@@ -1,24 +1,24 @@-# Events & Notifications Best Practices+# Events and Notifications Best Practices## Rely on Event Discovery-Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.+Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer.-## Run `event:cache` in Production Deploy+## Cache Event Discovery During Production Deployment-Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.+Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.## Use `ShouldDispatchAfterCommit` Inside Transactions-Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.+When an event is dispatched inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. This affects synchronous and queued listeners; it is not limited to queue timing.```phpclass OrderShipped implements ShouldDispatchAfterCommit {}```-## Always Queue Notifications+## Queue Slow Notifications-Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.+Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation.```phpclass InvoicePaid extends Notification implements ShouldQueue@@ -27,9 +27,9 @@ class InvoicePaid extends Notification implements ShouldQueue}```-## Use `afterCommit()` on Notifications in Transactions+## Dispatch Queued Notifications After Commit-Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.+A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. This setting has no scheduling effect on a synchronous notification.```php$user->notify((new InvoicePaid($invoice))->afterCommit());@@ -37,7 +37,7 @@ $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.+Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues.## Use On-Demand Notifications for Non-User Recipients@@ -49,4 +49,4 @@ Notification::route('mail', '[email protected]')->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.+Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification.diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.mdindex 8e2f16e8a..cc8fdd6ab 100644--- a/.agents/skills/laravel-best-practices/rules/http-client.md+++ b/.agents/skills/laravel-best-practices/rules/http-client.md@@ -1,86 +1,100 @@# HTTP Client Best Practices-## Always Set Explicit Timeouts+## Set Explicit Timeouts-The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.+Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Remember that retries can multiply the total elapsed time.++Less resilient:-Incorrect:```php$response = Http::get('https://api.example.com/users');```-Correct:+Preferred:+```php-$response = Http::timeout(5)- ->connectTimeout(3)+$response = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users');```-For service-specific clients, define timeouts in a macro:+Define shared settings in a macro or a dedicated client:```phpHttp::macro('github', function () {return Http::baseUrl('https://api.github.com')- ->timeout(10)->connectTimeout(3)+ ->timeout(10)->withToken(config('services.github.token'));});$response = Http::github()->get('/repos/laravel/framework');```-## Use Retry with Backoff for External APIs+## Retry Only Safe Operations-External APIs have transient failures. Use `retry()` with increasing delays.+Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection.-Incorrect:-```php-$response = Http::post('https://api.stripe.com/v1/charges', $data);+Unsafe without an idempotency guarantee:-if ($response->failed()) {- throw new PaymentFailedException('Charge failed');-}+```php+$response = Http::retry([100, 500, 1000])+ ->post('https://api.example.com/v1/charges', $data);```-Correct:+Safe for an idempotent request:+```php-$response = Http::retry([100, 500, 1000])+$response = Http::connectTimeout(3)->timeout(10)- ->post('https://api.stripe.com/v1/charges', $data);+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->get('https://api.example.com/data');```-Only retry on specific errors:+For a supported state-changing API, send a stable idempotency key for every attempt:```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');+$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])+ ->connectTimeout(3)+ ->timeout(10)+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->post('https://api.example.com/v1/charges', $data);```## Handle Errors Explicitly-The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.+The HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing by default. Inspect the expected statuses or call `throw()` before consuming a success payload.++Unsafe when a success payload is expected:-Incorrect:```php-$response = Http::get('https://api.example.com/users/1');-$user = $response->json(); // Could be an error body+$user = Http::get('https://api.example.com/users/1')->json();```-Correct:+Preferred:+```php-$response = Http::timeout(5)+$user = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users/1')- ->throw();--$user = $response->json();+ ->throw()+ ->json();```-For graceful degradation:+Handle expected alternatives explicitly when graceful degradation is required:```php-$response = Http::get('https://api.example.com/users/1');+$response = Http::connectTimeout(3)+ ->timeout(5)+ ->get('https://api.example.com/users/1');if ($response->successful()) {return $response->json();@@ -93,46 +107,30 @@ if ($response->notFound()) {$response->throw();```-## Use Request Pooling for Concurrent Requests+## Pool Independent Requests-When making multiple independent API calls, use `Http::pool()` instead of sequential calls.+Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling; inspect or throw for each response as needed.-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:```phpuse 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'),+ $pool->as('users')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/users'),+ $pool->as('posts')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/posts'),]);-$users = $responses['users']->json();-$posts = $responses['posts']->json();+$users = $responses['users']->throw()->json();+$posts = $responses['posts']->throw()->json();```-## Fake HTTP Calls in Tests--Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.+## Fake HTTP Requests in Tests-Incorrect:-```php-it('syncs user from API', function () {- $service = new UserSyncService;- $service->sync(1); // Hits the real API-});-```+Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles.-Correct:```php-it('syncs user from API', function () {+it('syncs a user from the API', function () {Http::preventStrayRequests();Http::fake([@@ -142,16 +140,15 @@ it('syncs user from API', function () {]),]);- $service = new UserSyncService;- $service->sync(1);+ (new UserSyncService)->sync(1);- Http::assertSent(function (Request $request) {- return $request->url() === 'https://api.example.com/users/1';- });+ Http::assertSent(fn (Request $request) =>+ $request->url() === 'https://api.example.com/users/1'+ );});```-Test failure scenarios too:+For example, fake a connection failure when testing the integration's failure path:```phpHttp::fake([diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.mdindex 7c717336d..f6310437c 100644--- a/.agents/skills/laravel-best-practices/rules/mail.md+++ b/.agents/skills/laravel-best-practices/rules/mail.md@@ -1,27 +1,54 @@# Mail Best Practices-## Implement `ShouldQueue` on the Mailable Class+## Queue Slow Mail Delivery-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.+Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`.-## Use `afterCommit()` on Mailables Inside Transactions+```php+class OrderShipped extends Mailable implements ShouldQueue+{+ use Queueable, SerializesModels;+}+```-A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.+Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.-## Use `assertQueued()` Not `assertSent()` for Queued Mailables+## Dispatch Queued Mail After Commit-`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.+A queued mailable dispatched during a database transaction can be processed before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records.-Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.+```php+Mail::to($user)->send(+ (new OrderShipped($order))->afterCommit()+);+```-Correct: `Mail::assertQueued(OrderShipped::class);`+If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery.-## Use Markdown Mailables for Transactional Emails+## Assert the Delivery Mode-Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.+Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.-## Separate Content Tests from Sending Tests+Incorrect for a mailable that implements `ShouldQueue`:-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.+```php+Mail::assertSent(OrderShipped::class);+```++Correct:++```php+Mail::assertQueued(OrderShipped::class);+```++## Use Markdown Mailables When They Fit++Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They are useful for conventional transactional messages, but a custom HTML and text pair may be more appropriate for a specialized design.++```bash+php artisan make:mail OrderShipped --markdown=mail.orders.shipped+```++## Separate Content and Delivery Tests++Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior.diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.mdindex df6f5f33c..3345402eb 100644--- a/.agents/skills/laravel-best-practices/rules/migrations.md+++ b/.agents/skills/laravel-best-practices/rules/migrations.md@@ -2,76 +2,51 @@## Generate Migrations with Artisan-Always use `php artisan make:migration` for consistent naming and timestamps.+Use `php artisan make:migration` to generate the timestamped filename and migration structure.-Incorrect (manually created file):-```php-// database/migrations/posts_migration.php ← wrong naming, no timestamp-```--Correct (Artisan-generated):```bashphp artisan make:migration create_posts_tablephp artisan make:migration add_slug_to_posts_table```-## Use `constrained()` for Foreign Keys+## Define Foreign-Key Constraints Deliberately-Automatic naming and referential integrity.+Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.```php$table->foreignId('user_id')->constrained()->cascadeOnDelete();--// Non-standard names$table->foreignId('author_id')->constrained('users');```-## Never Modify Deployed Migrations+Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration.-Once a migration has run in production, treat it as immutable. Create a new migration to change the table.+## Treat Deployed Migrations as Immutable-Incorrect (editing a deployed migration):-```php-// 2024_01_01_create_posts_table.php — already in production-$table->string('slug')->unique(); // ← added after deployment-```+After a migration has run in a shared or production environment, create a new migration for subsequent changes. Editing the old file makes fresh installations differ from upgraded installations.-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');-});-```+For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.-## Add Indexes in the Migration+## Design Indexes for Real Queries-Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.+Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column appearing in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index.-Incorrect:-```php-Schema::create('orders', function (Blueprint $table) {- $table->id();- $table->foreignId('user_id')->constrained();- $table->string('status');- $table->timestamps();-});-```+Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan, and avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance.++## Stage Changes That Affect Existing Rows++Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid.++Do not assume this migration is safe on a populated table:-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();-});+$table->string('slug')->unique();```-## Mirror Defaults in Model `$attributes`+Large backfills are usually better implemented as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when their locking, transaction, and deployment behavior is understood.-When a column has a database default, mirror it in the model so new instances have correct values before saving.+## Mirror Defaults Only When Unsaved Models Need Them++A database default is applied when a row is inserted, not when a model is instantiated. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions synchronized.```php// Migration@@ -83,39 +58,10 @@ protected $attributes = [];```-## 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');- });-}-```+## Make Rollbacks Honest-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.+Implement `down()` when the change can be safely reversed. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible; document that limitation and prefer a forward-fix migration in production.## 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']);-```+Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when doing so reduces locks and supports phased deployment, but do not split related operations merely to enforce a blanket separation between data definition and data manipulation.diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.mdindex c41915e2b..011828a6c 100644--- a/.agents/skills/laravel-best-practices/rules/queue-jobs.md+++ b/.agents/skills/laravel-best-practices/rules/queue-jobs.md@@ -1,82 +1,82 @@-# Queue & Job Best Practices+# Queue and Job Best Practices-## Set `retry_after` Greater Than `timeout`+## Keep Reservation Time Longer Than Execution Time-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.+For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`.-Incorrect (`retry_after` ≤ `timeout`):```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}+// Job+public $timeout = 120;-// config/queue.php — retry_after: 90 ← job retried while still running!+// config/queue.php for the connection+'retry_after' => 150,```-Correct (`retry_after` > `timeout`):-```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}--// config/queue.php — retry_after: 180 ← safely longer than any job timeout-```+Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`; configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings.-## Use Exponential Backoff+## Back Off Transient Failures-Use progressively longer delays between retries to avoid hammering failing services.+Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.-Incorrect (fixed retry interval):```phpclass SyncWithStripe implements ShouldQueue{- public $tries = 3;- // Default: retries immediately, overwhelming the API-}-```+ public $tries = 4;-Correct (exponential backoff):-```php-class SyncWithStripe implements ShouldQueue-{- public $tries = 3;public $backoff = [1, 5, 10];}```-## Implement `ShouldBeUnique`+Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window.++## Use Unique Jobs for Dispatch Deduplication-Prevent duplicate job processing.+Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock and is not a substitute for idempotent processing or a database constraint.```phpclass GenerateInvoice implements ShouldQueue, ShouldBeUnique{+ public $uniqueFor = 3600;+public function uniqueId(): string{- return $this->order->id;+ return (string) $this->order->id;}+}+```- public $uniqueFor = 3600;+All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.++Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running:++```php+class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing+{+ // ...}```-## Always Implement `failed()`+## Handle Terminal Failure When Needed++Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting.-Handle errors explicitly — don't rely on silent failure.+Laravel invokes `failed()` on a new job instance, so mutations made to the job during `handle()` are not available there.```phppublic function failed(?Throwable $exception): void{$this->podcast->update(['status' => 'failed']);- Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);++ Log::error('Podcast processing failed', [+ 'podcast_id' => $this->podcast->id,+ 'exception' => $exception,+ ]);}```-## Rate Limit External API Calls in Jobs+## Rate Limit External Calls-Use `RateLimited` middleware to throttle jobs calling third-party APIs.+Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together.```phppublic function middleware(): array@@ -85,60 +85,33 @@ public function middleware(): array}```-## Batch Related Jobs+## Batch Jobs for Group Coordination-Use `Bus::batch()` when jobs should succeed or fail together.+Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction: completed jobs are not rolled back when another job fails. By default, one failed job cancels the batch; call `allowFailures()` only when partial failure is acceptable.```phpBus::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();+ ->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))+ ->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [+ 'exception' => $exception,+ ]))+ ->dispatch();```-## `retryUntil()` Needs `$tries = 0`+## Configure Time-Based Retry Limits Deliberately-When using time-based retry limits, set `$tries = 0` to avoid premature failure.+Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. The method takes precedence over attempt-based limits, so setting `$tries = 0` is not required.```php-public $tries = 0;--public function retryUntil(): \DateTimeInterface+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.+## Use Horizon for Redis Queue Operations-```php-// config/horizon.php-'environments' => [- 'production' => [- 'supervisor-1' => [- 'connection' => 'redis',- 'queue' => ['high', 'default', 'low'],- 'balance' => 'auto',- 'minProcesses' => 1,- 'maxProcesses' => 10,- 'tries' => 3,- ],- ],-],-```+Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.mdindex b6e30864f..604a8d96d 100644--- a/.agents/skills/laravel-best-practices/rules/routing.md+++ b/.agents/skills/laravel-best-practices/rules/routing.md@@ -1,99 +1,106 @@-# Routing & Controllers Best Practices+# Routing and Controller Best Practices## Use Implicit Route Model Binding-Let Laravel resolve models automatically from route parameters.+Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.++Instead of manual lookup:-Incorrect:```php-public function show(int $id)+public function show(int $id): View{$post = Post::findOrFail($id);++ return view('posts.show', ['post' => $post]);}```-Correct:+Use route model binding:+```php-public function show(Post $post)+public function show(Post $post): View{return view('posts.show', ['post' => $post]);}```-## Use Scoped Bindings for Nested Resources+## Scope Nested Bindings-Enforce parent-child relationships automatically.+Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization.```phpRoute::get('/users/{user}/posts/{post}', function (User $user, Post $post) {- // $post is automatically scoped to $user+ // The resolved post belongs to the resolved user.})->scopeBindings();```-## Use Resource Controllers+## Use Resource Routes for Resourceful Actions-Use `Route::resource()` or `apiResource()` for RESTful endpoints.+Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary.```phpRoute::resource('posts', PostController::class);-// In routes/api.php — the /api prefix is applied automatically-Route::apiResource('posts', Api\PostController::class);++// Alternatively, for an API-only resource:+Route::apiResource('posts', ApiPostController::class);```-## Keep Controllers Thin+`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not itself add an `/api` prefix; that prefix comes from the application's API route configuration.++## Organize Controllers Around Resources++As a general default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This keeps routes predictable and prevents controllers from accumulating unrelated behavior.-Aim for under 10 lines per method. Extract business logic to action or service classes.+When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary.++Custom action on the primary controller:-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);-}+Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']);```-Correct:+The published podcast modeled as a resource:+```php-public function store(StorePostRequest $request, CreatePostAction $create)-{- $post = $create->execute($request->validated());+Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store'])+ ->name('published-podcasts.store');- return redirect()->route('posts.show', $post);-}+Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy'])+ ->name('published-podcasts.destroy');```-## 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+class PublishedPodcastController extends Controller{- $validated = $request->validate([- 'title' => ['required', 'max:255'],- 'body' => ['required'],- ]);+ public function store(Podcast $podcast): RedirectResponse+ {+ $podcast->publish();++ return back();+ }- Post::create($validated);+ public function destroy(Podcast $podcast): RedirectResponse+ {+ $podcast->unpublish();- return redirect()->route('posts.index');+ return back();+ }}```-Correct:+Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions.++## Keep Controllers Focused on HTTP Concerns++Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service merely to satisfy an arbitrary line limit.+```php-public function store(StorePostRequest $request): RedirectResponse+public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse{- Post::create($request->validated());+ $post = $create->handle($request->validated());- return redirect()->route('posts.index');+ return redirect()->route('posts.show', $post);}```++A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity; see the validation rules for detailed guidance.diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.mdindex a98479450..4c25134a9 100644--- a/.agents/skills/laravel-best-practices/rules/scheduling.md+++ b/.agents/skills/laravel-best-practices/rules/scheduling.md@@ -1,32 +1,50 @@# Task Scheduling Best Practices-## Use `withoutOverlapping()` on Variable-Duration Tasks+## Prevent Unwanted Overlap-Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.+Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. This is appropriate for variable-duration tasks that are not safe to run concurrently.-## Use `onOneServer()` on Multi-Server Deployments+```php+Schedule::command('reports:generate')+ ->everyFifteenMinutes()+ ->withoutOverlapping(30);+```++The optional value is the lock expiration time in minutes, not the task timeout. Choose it carefully: the default is 24 hours, stale locks can be cleared with `php artisan schedule:clear-cache`, and an expiration that is too short can permit overlap while the first task still runs. The task itself should still tolerate retries and partial execution where practical.-Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).+## Run a Task on One Server-## Use `runInBackground()` for Concurrent Long Tasks+Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`.++```php+Schedule::command('billing:charge')->daily()->onOneServer();+```-By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.+Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity.-## Use `environments()` to Restrict Tasks+## Run Eligible Commands in the Background-Prevent accidental execution of production-only tasks (billing, reporting) on staging.+Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.```php-Schedule::command('billing:charge')->monthly()->environments(['production']);+Schedule::command('analytics:process')->hourly()->runInBackground();```-## Use `takeUntilTimeout()` for Time-Bounded Processing+Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`; it is not available for scheduled closures. Ensure background processes have appropriate logging and failure monitoring.-A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.+## Restrict Tasks by Environment-## Use Schedule Groups for Shared Configuration+Use `environments()` when a task should run only in named application environments. Treat this as an operational safeguard, not an authorization control.-Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.+```php+Schedule::command('billing:charge')+ ->monthly()+ ->environments(['production']);+```++## Group Shared Configuration++Use schedule groups when several tasks genuinely share frequency or constraints.```phpSchedule::daily()@@ -37,3 +55,7 @@ Schedule::daily()Schedule::command('emails:prune');});```++## Bound Work Inside the Task++The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required.diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.mdindex 2d7200c29..57b57f0fa 100644--- a/.agents/skills/laravel-best-practices/rules/security.md+++ b/.agents/skills/laravel-best-practices/rules/security.md@@ -1,18 +1,9 @@# Security Best Practices-## Mass Assignment Protection+## Control Mass Assignment-Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).+Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default; `$guarded = []` opts out of that protection.-Incorrect:-```php-class User extends Model-{- protected $guarded = []; // All fields are mass assignable-}-```--Correct:```phpclass User extends Model{@@ -24,82 +15,71 @@ class User extends Model}```-Never use `$guarded = []` on models that accept user input.--## Authorize Every Action+Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set; it does not validate values or authorize the operation.-Use policies or gates in controllers. Never skip authorization.+## Authorize Protected Actions-Incorrect:-```php-public function update(UpdatePostRequest $request, Post $post)-{- $post->update($request->validated());-}-```+Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.-Correct:```php-public function update(UpdatePostRequest $request, Post $post)+public function update(UpdatePostRequest $request, Post $post): RedirectResponse{Gate::authorize('update', $post);$post->update($request->validated());++ return redirect()->route('posts.show', $post);}```-Or via Form Request:+Authorization may instead live in the form request:```phppublic function authorize(): bool{- return $this->user()->can('update', $this->route('post'));+ return $this->user()?->can('update', $this->route('post')) ?? false;}```-## Prevent SQL Injection+Public actions intentionally available to everyone do not need a redundant authorization check.++## Bind Query Parameters-Always use parameter binding. Never interpolate user input into queries.+Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions; map user-selected identifiers to an allow-list.Incorrect:+```phpDB::select("SELECT * FROM users WHERE name = '{$request->name}'");```Correct:+```phpUser::where('name', $request->name)->get();--// Raw expressions with bindings-User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();+User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();```-## Escape Output to Prevent XSS+## Escape Output in Its Context-Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.+Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content that has been sanitized for the exact HTML context in which it is rendered. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.++Incorrect for untrusted content:-Incorrect:```blade{!! $user->bio !!}```Correct:+```blade{{ $user->bio }}```-## CSRF Protection--Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.+## Apply Cross-Site Request Forgery Protection-Incorrect:-```blade-<form method="POST" action="/posts">- <input type="text" name="title">-</form>-```+Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.-Correct:```blade<form method="POST" action="/posts">@csrf@@ -107,21 +87,27 @@ Correct:</form>```-## Rate Limit Auth and API Routes+Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Confirm equivalent configuration when using another HTTP client. Do not disable CSRF protection merely to fix a token mismatch.-Apply `throttle` middleware to authentication and API routes.+## Rate Limit Sensitive Endpoints++Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately; an Internet Protocol (IP) address alone can unfairly group users behind a shared network, while an account identifier alone can enable targeted denial of service.```phpRateLimiter::for('login', function (Request $request) {- return Limit::perMinute(5)->by($request->ip());+ return Limit::perMinute(5)->by(Str::transliterate(+ Str::lower($request->string('email')).'|'.$request->ip()+ ));});Route::post('/login', LoginController::class)->middleware('throttle:login');```-## Validate File Uploads+Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection.++## Validate and Store Uploads Safely-Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.+Validate expected content type, dimensions where relevant, and size. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions; it does not validate the user-assigned filename extension. The `extensions` rule checks that extension and should not be used by itself.```phppublic function rules(): array@@ -132,56 +118,28 @@ public function rules(): array}```-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.+Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.-Incorrect:```php-$key = env('API_KEY');+$path = $request->file('avatar')->store('avatars');```-Correct:-```php-// config/services.php-'api_key' => env('API_KEY'),+## Keep Secrets Out of Application Code-// In application code-$key = config('services.api_key');-```+Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works correctly. See the configuration rules for encrypted environment files and external secret stores.## Audit Dependencies-Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.+Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.```bashcomposer audit```-## Encrypt Sensitive Database Fields--Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.+## Encrypt Sensitive Attributes When Appropriate-Incorrect:-```php-class Integration extends Model-{- protected function casts(): array- {- return [- 'api_key' => 'string',- ];- }-}-```+Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. Encrypted values cannot be meaningfully queried and should use a `TEXT` or larger column because ciphertext length is variable.-Correct:```phpclass Integration extends Model{diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.mdindex a8afb3695..3f3f14fbc 100644--- a/.agents/skills/laravel-best-practices/rules/style.md+++ b/.agents/skills/laravel-best-practices/rules/style.md@@ -1,125 +1,110 @@-# 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 |-|---------|---------|+# Convention and Style Best Practices++## Follow Project Naming Conventions++Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.++| Element | Convention | Example |+| --- | --- | --- |+| Controller | Singular resource name | `ArticleController` |+| Model | Singular StudlyCase | `User` |+| Table | Plural snake_case | `article_comments` |+| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` |+| Column | snake_case | `meta_title` |+| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |+| Resource URI | Plural resource | `articles/1` |+| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` |+| Method | camelCase | `getAll` |+| Variable | camelCase | `$articlesWithAuthor` |+| Collection | Descriptive and plural | `$activeUsers` |+| Object | Descriptive and singular | `$activeUser` |+| View | kebab-case | `show-filtered.blade.php` |+| Configuration file | snake_case | `google_calendar.php` |+| Enumeration | Singular StudlyCase | `UserType` |++## Prefer Clear, Idiomatic Syntax++Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.++| More verbose | Idiomatic alternative |+| --- | --- || `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')` |+| `->first()?->name` | `->value('name')` when only that value is needed |-## Use Laravel String & Array Helpers+Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.-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.+## Use Utilities When They Clarify Intent-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);+Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as an unconditional replacement for every built-in function.-// Correct+```php$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+$class = class_basename(User::class);$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()`.+Use `Arr` for dot notation and common transformations:-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');+$public = Arr::only($attributes, ['name', 'email']);```-Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.+Use `Number` for localized display formatting rather than values that will be stored or calculated:-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%"+Number::format(1000000);+Number::currency(1500, 'USD');+Number::fileSize(1024 * 1024);```-URIs — use `Uri` for URL manipulation:+Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API:+```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.+Check the documentation for the Laravel version supported by the project before using newer utility classes or methods.-Use `search-docs` for the full list of available methods — these helpers are extensive.+## Keep Presentation Code Maintainable-## No Inline JS/CSS in Blade+Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks; avoid mixing large behavior and style blocks into templates.-Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.+Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript:-Incorrect:```blade-let article = `{{ json_encode($article) }}`;+<script>+ const article = {{ Js::from($article) }};+</script>```-Correct:-```blade-<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>-```+Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.-Pass data to JS via data attributes or use a dedicated PHP-to-JS package.+## Write Comments That Explain Why-## No Unnecessary Comments+Prefer clear names and small units of code over comments that merely restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.-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.+Unhelpful:-Incorrect:```php-// Check if there are any joins-if (count((array) $builder->getQuery()->joins) > 0)+// Check whether the query has joins.+if (count((array) $builder->getQuery()->joins) > 0) {+ // ...+}```-Correct:+Clearer:+```php-if ($this->hasJoins())+if ($this->hasJoins()) {+ // ...+}```diff --git a/.agents/skills/laravel-best-practices/rules/testing.md b/.agents/skills/laravel-best-practices/rules/testing.mddeleted file mode 100644index 4fbf12f8a..000000000--- a/.agents/skills/laravel-best-practices/rules/testing.md+++ /dev/null@@ -1,43 +0,0 @@-# 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.mdindex 5fde1064a..37ce6c5e2 100644--- a/.agents/skills/laravel-best-practices/rules/validation.md+++ b/.agents/skills/laravel-best-practices/rules/validation.md@@ -1,75 +1,89 @@-# Validation & Forms Best Practices+# Validation and Forms Best Practices-## Use Form Request Classes+## Extract Validation When It Improves the Boundary-Extract validation from controllers into dedicated Form Request classes.+Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set.-Incorrect:```php-public function store(Request $request)+public function store(StorePostRequest $request): RedirectResponse{- $request->validate([- 'title' => 'required|max:255',- 'body' => 'required',- ]);-}-```+ $post = Post::create($request->validated());-Correct:-```php-public function store(StorePostRequest $request)-{- Post::create($request->validated());+ return redirect()->route('posts.show', $post);}```-## Array vs. String Notation for Rules+A form request's `authorize()` method can enforce access to the operation. Validation establishes the shape and values of input; it does not itself authorize the user.-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.+## Prefer Readable Rule Syntax++Array syntax composes cleanly with rule objects and avoids delimiter issues. Prefer it in new code when it improves readability, while following a consistent local style.```php-// Preferred for new code'email' => ['required', 'email', Rule::unique('users')],+```-// Follow existing convention if the project uses string notation+String syntax remains valid for simple rules:++```php'email' => 'required|email|unique:users',```-## Always Use `validated()`+## Use Only Intended Validated Data-Get only validated data. Never use `$request->all()` for mass operations.+Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. Then select the fields intended for the operation when the validation rules also cover control fields or nested data.++Unsafe:-Incorrect:```phpPost::create($request->all());```-Correct:+Preferred:+```php-Post::create($request->validated());+$post = Post::create($request->safe()->only(['title', 'body']));```-## Use `Rule::when()` for Conditional Validation+Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation merely to make mass assignment convenient.++## Express Conditional Rules Clearly++Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test.```php'company_name' => [- Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),+ 'string',+ 'max:255',+ Rule::when(+ $this->input('account_type') === 'business',+ ['required'],+ ['nullable'],+ ),],```-## Use the `after()` Method for Custom Validation+## Add Cross-Field Validation After Base Rules-Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.+Use a form request's `after()` method for validation that depends on multiple fields or application state. Avoid expensive queries when prerequisite fields have already failed validation.```phppublic function after(): array{return [function (Validator $validator) {- if ($this->quantity > Product::find($this->product_id)?->stock) {+ if ($validator->errors()->hasAny(['product_id', 'quantity'])) {+ return;+ }++ $stock = Product::find($this->integer('product_id'))?->stock;++ if ($stock !== null && $this->integer('quantity') > $stock) {$validator->errors()->add('quantity', 'Not enough stock.');}},];}```++Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate.diff --git a/.agents/skills/mcp-development/SKILL.md b/.agents/skills/mcp-development/SKILL.mdindex 4ef1bb9a6..ca63d9fb2 100644--- a/.agents/skills/mcp-development/SKILL.md+++ b/.agents/skills/mcp-development/SKILL.md@@ -22,22 +22,17 @@ Register MCP servers in `routes/ai.php`:```phpuse Laravel\Mcp\Facades\Mcp;-Mcp::web();+Mcp::web('/mcp/demo', \App\Mcp\Servers\AppServer::class);```### Creating MCP Primitives```bashphp artisan make:mcp-tool ToolName # Create a tool-php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)-```After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.diff --git a/.agents/skills/mcp-development/references/app.md b/.agents/skills/mcp-development/references/app.mdindex db2e752a3..93042c3f9 100644--- a/.agents/skills/mcp-development/references/app.md+++ b/.agents/skills/mcp-development/references/app.md@@ -27,7 +27,14 @@ class DashboardApp extends AppResourcecreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -104,7 +111,7 @@ MCP Apps add interactive UI to the Model Context Protocol. The server returns se└─────────────────────────────────────────────┘```-The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.+The server automatically advertises `capabilities.extensions["io.modelcontextprotocol/ui"]` on `server/discover` when any `AppResource` is registered. Add cases of the `Extension` enum to the server's `$extensions` property to declare any other extension. The client declares its own support in the `io.modelcontextprotocol/clientCapabilities` member of each request's `_meta`.---@@ -307,7 +314,14 @@ Renders a complete self-contained HTML document with the MCP SDK inlined. `creatcreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -703,9 +717,19 @@ class GetMonitorData extends Tool```jscreateMcpApp(async (app) => {async function poll() {- const result = await app.callServerTool('get-monitor-data');- const data = JSON.parse(result.content[0]?.text ?? '{}');- document.getElementById('cpu').textContent = data.cpu;+ try {+ const result = await app.callServerTool('get-monitor-data');++ if (result.isError) {+ document.getElementById('cpu').textContent = result.content[0]?.text ?? 'Unavailable';+ return;+ }++ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ } catch {+ // transport failure or malformed payload, retry on next tick+ }}setInterval(poll, 2000);@@ -776,6 +800,11 @@ In the client, convert the base64 blob to a data URI for rendering:```jsconst result = await app.callServerTool('get-image', { id: 42 });++if (result.isError) {+ return;+}+const blob = result.content[0];img.src = `data:${blob.mimeType};base64,${blob.data}`;```@@ -798,8 +827,17 @@ createMcpApp(async (app) => {});app.onToolResult((params) => {- const data = JSON.parse(params.result.content[0]?.text ?? "{}");- renderResults(data);+ if (params.result.isError) {+ document.getElementById("error").textContent =+ params.result.content[0]?.text ?? "Unknown error";+ return;+ }++ try {+ renderResults(JSON.parse(params.result.content[0]?.text ?? "{}"));+ } catch {+ document.getElementById("error").textContent = "Malformed tool result";+ }});});```diff --git a/.agents/skills/passport-development/SKILL.md b/.agents/skills/passport-development/SKILL.mdindex e5dce352f..6a083d9c0 100644--- a/.agents/skills/passport-development/SKILL.md+++ b/.agents/skills/passport-development/SKILL.md@@ -95,15 +95,10 @@ Create clients with the appropriate flag for the grant type:```bashphp artisan passport:client # Authorization code-php artisan passport:client --public # PKCE (no secret)-php artisan passport:client --client # Client credentials-php artisan passport:client --personal # Personal access tokens-php artisan passport:client --device # Device authorization-```Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.@@ -182,11 +177,8 @@ Passport::actingAsClient($client, ['scope1']);```bashphp artisan passport:purge # Purge revoked & expired-php artisan passport:purge --revoked # Only revoked-php artisan passport:purge --expired # Only expired-```Schedule `passport:purge` for regular expired token clean-up.diff --git a/.agents/skills/pest-testing/SKILL.md b/.agents/skills/pest-testing/SKILL.mddeleted file mode 100644index 79cd0bcce..000000000--- a/.agents/skills/pest-testing/SKILL.md+++ /dev/null@@ -1,203 +0,0 @@-----name: pest-testing-description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."-license: MIT-metadata:- author: laravel------# Pest Testing 5--## Documentation--Use `search-docs` for detailed Pest 5 patterns and documentation.--## Basic Usage--### Creating Tests--All tests must be written using Pest. Use `php artisan make:test --pest {name}`.--The `{name}` argument should include only the path and test name, but should not include the test suite.-- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`-- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`-- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`-- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`--### Test Organization--- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.-- Browser tests: `tests/Browser/` directory.-- Do NOT remove tests without approval - these are core application code.--### Basic Test Structure--Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.--<!-- Basic Pest Test Example -->-```php-it('is true', function () {- expect(true)->toBeTrue();-});-```--### Running Tests--- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.-- Run all tests: `php artisan test --compact`.-- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.-- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.--## Assertions--Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:--<!-- Pest Response Assertion -->-```php-it('returns all', function () {- $this->postJson('/api/docs', [])->assertSuccessful();-});-```--| Use | Instead of |-|-----|------------|-| `assertSuccessful()` | `assertStatus(200)` |-| `assertNotFound()` | `assertStatus(404)` |-| `assertForbidden()` | `assertStatus(403)` |--## Mocking--Import mock function before use: `use function Pest\Laravel\mock;`--## Datasets--Use datasets for repetitive tests (validation rules, etc.):--<!-- Pest Dataset Example -->-```php-it('has emails', function (string $email) {- expect($email)->not->toBeEmpty();-})->with([- 'james' => '[email protected]',- 'taylor' => '[email protected]',-]);-```--## Pest 5 Features--| Feature | Purpose |-|---------|---------|-| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |-| Time-Balanced Sharding | Split tests across CI shards by execution time |-| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |-| Browser Testing | Full integration tests in real browsers |-| Smoke Testing | Validate multiple pages quickly |-| Visual Regression | Compare screenshots for visual changes |-| Architecture Testing | Enforce code conventions |--### Tia (Test Impact Analysis)--Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:--<!-- Tia Example -->-```shell-./vendor/bin/pest --parallel --tia-```--- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.-- Detects Laravel, Symfony, Livewire, and Inertia automatically.--### New Validation Expectations--Pest 5 ships eight new validation matchers, all supporting `.not` negation:--<!-- Pest 5 Validation Expectations -->-```php-expect('[email protected]')->toBeEmail();-expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();-expect('192.168.1.1')->toBeIpAddress();-expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();-expect('example.com')->toBeHostname();-expect('example.co.uk')->toBeDomain();-expect('Zm9vYmFy')->toBeBase64();-expect('deadbeef')->toBeHexadecimal();-```--### Time-Balanced Sharding--Distribute tests across CI shards by execution time rather than count:--<!-- Pest Sharding Example -->-```shell-./vendor/bin/pest --update-shards-./vendor/bin/pest --shard=1/4-```--Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.--### Browser Test Example--Browser tests run in real browsers for full integration testing:--- Browser tests live in `tests/Browser/`.-- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.-- Use `RefreshDatabase` for clean state per test.-- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.-- Test on multiple browsers (Chrome, Firefox, Safari) if requested.-- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.-- Switch color schemes (light/dark mode) when appropriate.-- Take screenshots or pause tests for debugging.--<!-- Pest Browser Test Example -->-```php-it('may reset the password', function () {- Notification::fake();-- $this->actingAs(User::factory()->create());-- $page = visit('/sign-in');-- $page->assertSee('Sign In')- ->assertNoJavaScriptErrors()- ->click('Forgot Password?')- ->fill('email', '[email protected]')- ->click('Send Reset Link')- ->assertSee('We have emailed your password reset link!');-- Notification::assertSent(ResetPassword::class);-});-```--### Smoke Testing--Quickly validate multiple pages have no JavaScript errors:--<!-- Pest Smoke Testing Example -->-```php-$pages = visit(['/', '/about', '/contact']);--$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();-```--### Visual Regression Testing--Capture and compare screenshots to detect visual changes.--### Architecture Testing--<!-- Architecture Test Example -->-```php-arch('controllers')- ->expect('App\Http\Controllers')- ->toExtendNothing()- ->toHaveSuffix('Controller');-```--## Common Pitfalls--- Not importing `use function Pest\Laravel\mock;` before using mock-- Using `assertStatus(200)` instead of `assertSuccessful()`-- Forgetting datasets for repetitive validation tests-- Deleting tests without approval-- Forgetting `assertNoJavaScriptErrors()` in browser tests-- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`diff --git a/.agents/skills/tailwindcss-development/SKILL.md b/.agents/skills/tailwindcss-development/SKILL.mdindex c0cb2fbcd..98f9f1712 100644--- a/.agents/skills/tailwindcss-development/SKILL.md+++ b/.agents/skills/tailwindcss-development/SKILL.md@@ -48,16 +48,16 @@ In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead o### Replaced Utilities-Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.+Tailwind v4 removed deprecated utilities. Use the replacements shown below. For opacity, drop the `*-opacity-*` class and append the value as a modifier on the existing color: `bg-blue-500 bg-opacity-50` becomes `bg-blue-500/50`, `text-white text-opacity-75` becomes `text-white/75`.| 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/* |+| bg-opacity-* | bg-{color}/* |+| text-opacity-* | text-{color}/* |+| border-opacity-* | border-{color}/* |+| divide-opacity-* | divide-{color}/* |+| ring-opacity-* | ring-{color}/* |+| placeholder-opacity-* | placeholder-{color}/* || flex-shrink-* | shrink-* || flex-grow-* | grow-* || overflow-ellipsis | text-ellipsis |@@ -87,29 +87,6 @@ If existing pages and components support dark mode, new pages and components mus</div>```-## Common Patterns--### Flexbox Layout--<!-- Flexbox Layout -->-```html-<div class="flex items-center justify-between gap-4">- <div>Left content</div>- <div>Right content</div>-</div>-```--### Grid Layout--<!-- Grid Layout -->-```html-<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">- <div>Card 1</div>- <div>Card 2</div>- <div>Card 3</div>-</div>-```-## Common Pitfalls- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)diff --git a/.agents/skills/testing-best-practices/SKILL.md b/.agents/skills/testing-best-practices/SKILL.mdnew file mode 100644index 000000000..9b0aa7f91--- /dev/null+++ b/.agents/skills/testing-best-practices/SKILL.md@@ -0,0 +1,58 @@+---+name: testing-best-practices+description: "Laravel test design and review. Use when selecting coverage, naming or structuring tests, choosing assertions or test data, isolating dependencies, testing HTTP or security boundaries, improving suite performance, or reviewing test value. Use framework guidance or search-docs for Pest and PHPUnit syntax."+license: MIT+metadata:+ author: laravel+---++# Testing Best Practices++This skill provides rules for designing Laravel tests. Each rule file explains what to do and why. Use `search-docs` for Laravel and Pest API syntax.+This project uses Pest. Follow the corresponding guidance in each rule.++## Consistency First++Read nearby tests before you choose syntax and organization.++A pattern repeated throughout the project is a convention, and project conventions take precedence over this skill. Follow them and give new tests the same structure.++These rules govern the tests you write now. An existing test that follows a project convention is not defective merely because it conflicts with this skill. Do not delete or rewrite it. If the convention has drawbacks, explain them and let the user decide.++## What to Test++Read this section before you write a test.++- Test observable behavior and application contracts. A test must pass after an implementation change if the behavior stays the same.+- Cover every changed decision and each applicable high-value failure mode. A decision is a branch, a validation, a calculation, or an authorization.+- Exercise declarations through behavior instead of repeating their text.+- Leave framework behavior to framework tests. Testing project configuration is not testing the framework. A constrained relationship, cast, scope, or validation rule belongs to this project.+- Keep every test that can detect a distinct defect. When two tests detect the same defect, trim the higher-layer test to one case and report the duplication. Do not delete an existing test.+- Write a feature test first. Write a unit test only for logic that does not use the framework.+- Write a browser test only for behavior in JavaScript that a feature test cannot reach. Put a browser test in `tests/Browser`, and call `assertNoJavaScriptErrors()` in it.+- Judge an architecture test by the convention it protects, not by the rules above. An `arch()` test declares a rule for an entire directory, such as the parent class of every model, the classes that may use an enum, or the methods every factory declares. It intentionally checks declarations and fails when a new file breaks the convention.+- Use the test tools that the project installs. Add a new test dependency, plugin, or browser only after the user asks for it.++## How to Apply++1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.+2. Select every applicable branch in the rule index. Read every selected rule file.+3. Report each defect in the code before you write a test. Examples are a method with no body, a policy that no action calls, and a write action with no validation. Test the actual behavior. Report the defect to the user.+4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.+5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.++## Rule Index++Most changes need more than one rule file.++| Subject | Rule File |+| --- | --- |+| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |+| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |+| Arrange-act-assert and choosing the correct assertion | [`rules/assertions.md`](rules/assertions.md) |+| Endpoint coverage, authentication, authorization, tenant isolation, validation, and browser tests | [`rules/endpoint-tests.md`](rules/endpoint-tests.md) |+| Factories, test data ownership, and repeated input values | [`rules/test-data.md`](rules/test-data.md) |+| Fakes, mocks, outbound HTTP, time, randomness, and databases | [`rules/isolation.md`](rules/isolation.md) |+| Escaping, injection, cross-tenant access, and privilege checks | [`rules/security.md`](rules/security.md) |+| Environment and CI settings for a slow suite | [`rules/performance.md`](rules/performance.md) |+| Reviewing a test or suite | [`rules/review.md`](rules/review.md) |diff --git a/.agents/skills/testing-best-practices/rules/assertions.md b/.agents/skills/testing-best-practices/rules/assertions.mdnew file mode 100644index 000000000..528bdd4b0--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/assertions.md@@ -0,0 +1,64 @@+# Assertions++## Arrange, Act, Assert++Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.++Keep each test self-contained. Do not use values created by another test.++## How to Find the Correct Assertion++First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.++1. Search Laravel's assertions for framework subjects such as responses, the database, sessions, models, queues, events, mail, and notifications.+2. Fetch `https://pestphp.com/docs/expectations.md` for the expectations of Pest for a plain value, a type, a format, or a shape.+3. Build the check by hand only if no assertion exists for the subject.+4. Confirm the name in the documentation before you use it. Do not write an assertion that you did not confirm.++Use the assertion in this table for each subject.++| Subject | Assertion to use |+| --- | --- |+| A return value, the state of an object, or a transformation of a value | an `expect()` chain |+| An HTTP status, JSON, a session, or Inertia | a Laravel response assertion |+| The state in the database | a Laravel database assertion |+| The existence of a model | `assertModelExists($model)` rather than `assertDatabaseHas('users', ['id' => $user->id])` |++Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exists for the subject.++Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.++## Named Response Assertions++Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.++Keep one `expect()` chain on one subject. Start a new chain when the subject changes, or when the chain is difficult to read.++## Format Expectations++Use Pest's format expectations rather than regular expressions because they provide clearer failure messages. Pest covers email addresses, URLs, UUIDs, IP addresses, and other common formats, and each expectation supports `not` for the negative case.++## Assert a Known Value++Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.++```php+// The test calculates the value with the logic of the implementation...+$expected = now()->subHours(24)->floorSeconds(30)->toJson();+expect($from)->toBe($expected);++// The test sets a fixed input and asserts a known value...+travelTo('2025-01-01 00:00:00');+expect($from)->toBe('2024-12-31T00:00:00.000000Z');+```++## Assert the Complete Result++A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:++- The response or the return value.+- The state in the database.+- The jobs and the events that the operation dispatches.+- The notifications and the mail that the operation sends.++On the failure path, assert that the operation makes none of these changes. A test that asserts only `assertOk()` passes even when the application saves no record.diff --git a/.agents/skills/testing-best-practices/rules/endpoint-tests.md b/.agents/skills/testing-best-practices/rules/endpoint-tests.mdnew file mode 100644index 000000000..e3fc18b75--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/endpoint-tests.md@@ -0,0 +1,73 @@+# Endpoint Tests++## How to Write the Test++Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.++Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.++## Endpoint Coverage++Write a test for each applicable case:++- The request has missing or invalid authentication.+- The request comes from a different tenant, team, or organization.+- The user has an insufficient role or permission.+- The request does not satisfy a route or scope constraint.+- The request fails the validation.+- The request is valid. Assert both the response and the persisted state.++Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.++## Tenant Isolation++Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.++## Test Authorization at the Policy Level++An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.++- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.+- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.+- Use the helper of the project that asserts the ability and the arguments of the gate, if such a helper exists.++## Browser Tests++Write a browser test only for JavaScript behavior that an HTTP test cannot reach, such as modal interaction, drag-and-drop, live search, or client-side validation. Browser tests are slower than HTTP tests and can fail for reasons unrelated to the code under test.++- Assert the state that the user can see, and assert the state in the database that the interaction saves.+- Wait until the test reaches the required state. Do not wait for a fixed number of seconds, which can fail on a slower machine.+- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.++### Where a Browser Test Lives and How to Run It++The plugin runs browser tests as normal Pest tests, so they need no separate suite. Put them in `tests/Browser` to separate them from faster tests and run the directory with one command.++- Run a browser test with `vendor/bin/pest tests/Browser`, and add `--parallel` for the complete suite.+- Run `vendor/bin/pest --debug` to open the window of the browser and to pause at a failure. Use `--headed` to watch a run that passes.+- Add `--browser firefox` or `--browser safari` to run the test in a different browser. The default browser is Chrome.+- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.+- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.++### Browser Test Pitfalls++- The plugin waits five seconds for an element. Raise the value with `pest()->browser()->timeout(10000)` in `Pest.php` for a page that is slower, and do not add a wait for a number of seconds to the test.+- Apply `RefreshDatabase` to the browser tests in `Pest.php`. A browser test hits the application through a real request, and the records that it leaves break the next test.+- Add `tests/Browser/Screenshots` to `.gitignore`. A failure writes a screenshot, and the file is not part of the repository.+- Give `withKeyDown()` a key code, such as `KeyA`. A letter such as `'a'` gives the lowercase character, whatever modifier the test holds.+- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.++## Testing Validation++- Write one test for each validation rule when each failure represents a separate contract.+- Write one test with an empty payload to assert several required fields together.+- Assert the text of the message that the user gets. A message that is present but wrong is a defect.+- Use a dataset for input values that need the same setup and the same assertions.++Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.++### Which Layer Owns Which Case++The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.++When both tests contain the matrix, move it to the rule-class test and retain one case in the endpoint test. Never remove the last case, because the rule-class test still passes if the request omits the rule. The same division applies to policies, scopes, and other classes called by a request.diff --git a/.agents/skills/testing-best-practices/rules/finding-features.md b/.agents/skills/testing-best-practices/rules/finding-features.mdnew file mode 100644index 000000000..fc16c39bd--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/finding-features.md@@ -0,0 +1,37 @@+# How to Find Test Framework Features++Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.++- Give `search-docs` the capability you need rather than the name of a function you remember. It returns features available in the installed version.+- Fetch `https://pestphp.com/llms.txt` for the complete feature list and additions in each release.+- If a search returns no results, tell the user that the installed version does not provide the feature. Do not write an API that you have not confirmed.++Search for a feature in this table before you write the code by hand.++| Work that you need | Term to search for |+| --- | --- |+| Run one test with many input values | datasets, bound datasets |+| Assert over many values or over a collection | higher-order expectations |+| Remove the same setup from each test in a file | hooks, higher-order tests |+| Apply a convention to the complete codebase | architecture testing |+| Measure if the suite finds a defect | mutation testing |+| Find code with no types | type coverage |+| Reduce the time of a slow suite | parallel, profiling |+| Split the suite across CI jobs | sharding, `--update-shards` |+| Run only the tests that a change affects | Test Impact Analysis, `--tia` |+| Assert that a value has a known format | validation expectations |+| Run one test while you debug | filtering, `--bail`, `--dirty` |++## Built-in Laravel Assertion Methods++Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before building a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.++A hand-built check fails with `false is not true`, which identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure indicates what to fix.++```php+// The failure says that false is not true. Instead of this...+expect(User::where('email', '[email protected]')->exists())->toBeTrue();++// Use this... the failure names the table and the attributes that it did not find...+$this->assertDatabaseHas('users', ['email' => '[email protected]']);+```diff --git a/.agents/skills/testing-best-practices/rules/isolation.md b/.agents/skills/testing-best-practices/rules/isolation.mdnew file mode 100644index 000000000..e1a21fdb4--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/isolation.md@@ -0,0 +1,52 @@+# Fakes, Mocks, and Determinism++Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.++## How to Isolate a Dependency++Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.++Identify the dependency, then choose the first applicable option. A framework fake preserves the real code path, while a mock replaces the dependency.++1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.+2. Use a developer-defined fake implementation of a service if the application provides one.+3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.+4. Use the real implementation for everything else, including the database.++## Framework Fakes++- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.+- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.+- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.+- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.+- Assert the data of a job or of an event if that data is part of the behavior.+- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.++Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID, and a fake without class names suppresses those events and can produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.++## Mocking++Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. Use `Mockery::on()` or `withArgs()` if an equality check cannot state the expected argument, such as a check of one field of a value object.++Import the mock function before you use it: `use function Pest\Laravel\mock;`.++## Outbound HTTP Testing++Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.++Fake the exact endpoint used by each test. Do not call `Http::fake()` without an endpoint because it accepts unexpected requests and can hide defects.++## Time and Randomness++- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.+- Use the framework helpers `freezeTime()`, `travelTo()`, `travel()`, and `travelBack()`. Do not call `Carbon::setTestNow()`.+- Use `Str::createRandomStringsUsing()` to fix a generated string, if the test asserts an identifier or a slug.+- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.+- Restore the time and the randomness after each test, if the suite does not restore them for every test.++## Database++- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.+- Assert the exact keys of `toArray()` if the shape of the serialized model is a contract. The test then fails when the model exposes a new attribute.+- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.+- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.diff --git a/.agents/skills/testing-best-practices/rules/naming.md b/.agents/skills/testing-best-practices/rules/naming.mdnew file mode 100644index 000000000..4f3f5b1d1--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/naming.md@@ -0,0 +1,45 @@+# Naming and Structure++## File Layout++- Name each test file `{ClassName}Test.php`.+- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.+- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.+- Move large literal values out of the test body and into fixture files.++## Test Function++Use the test function used by other files in the same directory. If no neighboring test files exist:++- Use `it()` for the behavior of the code, and write the name as a verb phrase.+- Use `test()` for a declarative fact, such as a grant in a policy, the labels of an enum, or the shape of a serialized model.++Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.++## Naming Tests++The name of a test is a specification. State the user-visible result and the condition that causes it.++- Name the behavior, and not the method under test. The file name already gives the class.+- Give the exact status code in the name of a test for an API error.+- Do not write `Given`, `When`, or `Then` in the name.++```php+it('returns 401 when no token is provided', function () { ... });+it('does not include deployments from deleted environments', function () { ... });+it('falls back to the default region when none is configured', function () { ... });+```++Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.++Do not write `it('works correctly')` or `it('returns data')`, because neither specifies a meaningful result. Do not write `it('handleMethod creates record')`, because it names a method rather than behavior.++## Grouping++Use `describe()` if one file covers separate actions in a lifecycle. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.++Do not use `describe()` in these cases:++- The file covers one action or one flow.+- The tests are different only in the input value. Use a dataset instead.+- The group adds a level but does not make the file easier to read.diff --git a/.agents/skills/testing-best-practices/rules/performance.md b/.agents/skills/testing-best-practices/rules/performance.mdnew file mode 100644index 000000000..f1d9c9b35--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/performance.md@@ -0,0 +1,58 @@+# Test Suite Performance++These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.++Fetch `https://pestphp.com/docs/optimizing-tests` for Pest options that make test runs faster.+Verify each flag in the documentation before adding it to CI.++Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.++## Test Environment++- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.+- Disable XDebug. Disable pcov also, unless the run needs the coverage.+- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.+- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.+- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.++## Global Fakes++Put these three calls in the base `Pest.php` of the project:++- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. This catches requests made through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.+- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.+- `Exceptions::fake()`, so the suite does not report an exception to an external service.++## How to Run the Suite in Parallel++Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. Add `--processes=N` if the default count is unsuitable for the machine or CI.++A parallel run gives each process a separate database. Tests must meet these conditions; a test that fails only in parallel breaks one of them:++- The test creates each record that it reads. It does not read a record that another test creates.+- The test does not depend on the order of the run.+- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.++## How to Run Fewer Tests++Run `vendor/bin/pest --parallel --tia` to run only the tests that the recent changes affect. Pest replays the cached result of each other test.++Pest replays cached results rather than skipping unaffected tests. The cache includes each produced value and the covered lines and branches. Pest finds affected Laravel, Symfony, Livewire, and Inertia tests without configuration.++## How to Split Tests Across CI++Run `vendor/bin/pest --update-shards` to measure the time of each test. Run `vendor/bin/pest --shard=1/4` in each CI job, and change the first number for each job.++Commit `tests/.pest/shards.json` so each CI job gets the same shard and the shards remain balanced by runtime rather than test count.++## How to Find a Slow Test++Run `vendor/bin/pest --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.++If the cause of a slow test is unclear, add an event listener or temporary log entry to identify its work.++## Common Errors++- The run loads XDebug for a test that does not need it.+- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.+- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.diff --git a/.agents/skills/testing-best-practices/rules/review.md b/.agents/skills/testing-best-practices/rules/review.mdnew file mode 100644index 000000000..e0cfca147--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/review.md@@ -0,0 +1,44 @@+# Reviewing Tests++Check every item in this file. A passing test may still provide no value. For each test, identify the defect it would catch.++Report each finding. Do not delete or rewrite a test without the user's approval. When an issue appears throughout the suite as a convention, report the pattern once rather than every affected file.++## Test Value++Apply this section to behavioral tests. An architecture test states a convention for a directory, so these items do not apply to it.++- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.+- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.+- [ ] Each test detects a distinct defect that no other test covers. A duplicate shrinks at the higher layer to the one case that proves the wiring.+- [ ] Every changed decision and each applicable high-value failure mode has coverage.++## Names and Structure++- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.+- [ ] Each name states a result, the condition that causes it, and the status code for an API error.+- [ ] Each file uses one declaration style consistently, and each `describe()` group holds separate behavior.++## Coverage++- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.+- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.+- [ ] The complete permission matrix belongs in policy tests, not controller tests.+- [ ] Each validation rule has one test that asserts the user-visible message. When a unit test owns a matrix, reduce duplicate higher-level coverage to one case rather than deleting it.+- [ ] Rendered user input and each dynamic part of a query have a security test.++## Data and Determinism++- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.+- [ ] Each `beforeEach()` holds configuration only.+- [ ] Each factory state and each relationship gives the meaning of the data.+- [ ] Each call to `make()` is in a test that does not need the database.+- [ ] Time, randomness, sleep, and outbound HTTP are controlled.+- [ ] Each test passes alone, and passes in the complete suite in any order.++## Assertions++- [ ] Each expected value is a known value, and the test does not calculate the value with the logic of the implementation.+- [ ] Each test of a write operation asserts the response, the state in the database, and the side effects.+- [ ] Each fake has one assertion, and gives the class names unless the test asserts the complete result.+- [ ] Each `expect()` chain stays on one subject.diff --git a/.agents/skills/testing-best-practices/rules/security.md b/.agents/skills/testing-best-practices/rules/security.mdnew file mode 100644index 000000000..234f5b005--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/security.md@@ -0,0 +1,27 @@+# Security Tests++Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary can be difficult to detect because the feature may continue to work.++Write a test for each of these cases:++- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for why the response should possibly be `404` rather than `403`.+- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.+- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners may decode it.+- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.+- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.++```php+it('escapes dangerous content in the notification', function () {+ $organization = Organization::factory()->make([+ 'name' => "O'Reilly <script>alert('xss')</script>",+ ]);++ $content = (new QuotaApproaching($organization, 80))->toMail()->render();++ expect($content)+ ->toContain('<script>')+ ->not->toContain("<script>alert('xss')</script>");+});+```++Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the appropriate defense to each attribute, route, and template.diff --git a/.agents/skills/testing-best-practices/rules/test-data.md b/.agents/skills/testing-best-practices/rules/test-data.mdnew file mode 100644index 000000000..65124683b--- /dev/null+++ b/.agents/skills/testing-best-practices/rules/test-data.md@@ -0,0 +1,56 @@+# Factories and Test Data++## Each Test Makes Its Own Data++Create mutable records inside the test that uses them. This keeps setup visible and lets each test select its factory state.++Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.++## Record Construction++- Use `create()` if the test needs the record in the database.+- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.+- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning; `create(['email_verified_at' => null])` gives only its value.+- Use `for()` or the relationship helper of the project to declare the owner of a record.+- Use `recycle()` if several records must share one parent record.+- Use `sequence()` if several records need different attributes.++```php+$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();++$environment = Environment::factory()->recycle($organization)->create();++$organizations = Organization::factory()+ ->count(3)+ ->sequence(+ ['created_at' => now()->setSeconds(30)],+ ['created_at' => now()->setSeconds(1)],+ )+ ->create();+```++Create only the records required to arrange the behavior or support an assertion.++## Datasets++Use a dataset when the setup, test body, and assertions remain the same across input values.++```php+it('forbids roles other than admin', function (Role $role) {+ actingAs(User::factory()->hasOrganization($role)->create())+ ->post('/settings')+ ->assertForbidden();+})->with(collect(Role::cases())->reject(fn (Role $role) => $role === Role::ADMIN));+```++Use parameterized tests for:++- enum cases+- roles and plans+- boundary values+- input values that are invalid in the same way+- input and output value pairs++Write separate tests if the cases need a different setup, a different behavior, or different assertions. One test function with a branch in the body is two tests in one function.++Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.diff --git a/.agents/skills/wayfinder-development/SKILL.md b/.agents/skills/wayfinder-development/SKILL.mdindex a13cfc3b4..e80d131c0 100644--- a/.agents/skills/wayfinder-development/SKILL.md+++ b/.agents/skills/wayfinder-development/SKILL.md@@ -17,10 +17,13 @@ Use `search-docs` for detailed Wayfinder patterns and documentation.### Generate RoutesRun after route changes if Vite plugin isn't installed:+```bashphp artisan wayfinder:generate --no-interaction```+For form helpers, use `--with-form` flag:+```bashphp artisan wayfinder:generate --with-form --no-interaction```@@ -56,7 +59,7 @@ destroy.delete(1)store.form() // { action: "/posts", method: "post" }// Query parameters...-show(1, { query: { page: 1 } }) // "/posts/1?page=1"+show(1, { query: { page: 1 } }) // { url: "/posts/1?page=1", method: "get" }```## Wayfinder + Inertiadiff --git a/.claude/skills/configure-nightwatch/SKILL.md b/.claude/skills/configure-nightwatch/SKILL.mdindex 1fc580bbd..000a031b1 100644--- a/.claude/skills/configure-nightwatch/SKILL.md+++ b/.claude/skills/configure-nightwatch/SKILL.md@@ -62,15 +62,10 @@ Sampling determines which entry points (requests, commands, scheduled tasks) triConfigure via environment variables:```bash-# Default: 100% sampling (all requests/commands captured)-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions-```**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.@@ -312,22 +307,17 @@ Redaction modifies captured data to remove or obfuscate sensitive information. U**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):```bash-# Customize redacted headers-NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key```**Redact request payloads** (disabled by default):```bash-# Enable payload capture-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true# Customize redacted fields-NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card```diff --git a/.claude/skills/configure-nightwatch/reference.md b/.claude/skills/configure-nightwatch/reference.mdindex b071d2f2e..eddd8842e 100644--- a/.claude/skills/configure-nightwatch/reference.md+++ b/.claude/skills/configure-nightwatch/reference.md@@ -21,49 +21,36 @@### High-Traffic Applications```bash-# Conservative sampling-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions# Filter noisy events-NIGHTWATCH_IGNORE_CACHE_EVENTS=trueNIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically-```### Privacy-Conscious Applications```bash-# Disable sensitive data collection-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=falseNIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN# Or use redaction in AppServiceProvider-```### Balanced Configuration (Recommended Start)```bash-# Sample rates-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0# Filter obvious noise programmatically-# Redact PII as needed-```---diff --git a/.claude/skills/infer-conventions/SKILL.md b/.claude/skills/infer-conventions/SKILL.mdindex 11a932753..b42bca89e 100644--- a/.claude/skills/infer-conventions/SKILL.md+++ b/.claude/skills/infer-conventions/SKILL.md@@ -1,6 +1,7 @@---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."+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, API responses), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+disable-model-invocation: truelicense: MITmetadata:author: laraveldiff --git a/.claude/skills/infer-conventions/references/checklist.md b/.claude/skills/infer-conventions/references/checklist.mdindex f8d1b1441..3de1f1775 100644--- a/.claude/skills/infer-conventions/references/checklist.md+++ b/.claude/skills/infer-conventions/references/checklist.md@@ -9,11 +9,11 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app## A. Validation & HTTP input1. 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`.+ - 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`.+ - 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`.@@ -26,7 +26,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app7. 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.+ - 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`.@@ -37,7 +37,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app11. 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(`.+ - Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.## D. Eloquent & models@@ -56,7 +56,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app19. 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/`.+ - Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.## E. Architecture & organization@@ -89,11 +89,11 @@ This app ships a frontend stack, so the items below apply.## G. Database & migrations33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.- - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+ - 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.+ - 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.@@ -108,14 +108,14 @@ This app ships a frontend stack, so the items below apply.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/`.+ - 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 resources43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.- - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+ - 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.@@ -126,7 +126,7 @@ This app ships a frontend stack, so the items below apply.## J. Strings, collections & dates47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.- - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+ - 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.diff --git a/.claude/skills/laravel-best-practices/SKILL.md b/.claude/skills/laravel-best-practices/SKILL.mdindex d136d7556..311ab8443 100644--- a/.claude/skills/laravel-best-practices/SKILL.md+++ b/.claude/skills/laravel-best-practices/SKILL.md@@ -48,7 +48,7 @@ Cross-cutting changes often need more than one rule file.| 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) |+| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill || Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) || Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |diff --git a/.claude/skills/laravel-best-practices/rules/advanced-queries.md b/.claude/skills/laravel-best-practices/rules/advanced-queries.mdindex f12876e4c..54dd783d9 100644--- a/.claude/skills/laravel-best-practices/rules/advanced-queries.md+++ b/.claude/skills/laravel-best-practices/rules/advanced-queries.md@@ -1,8 +1,8 @@-# Advanced Query Patterns+# Advanced Query Best Practices-## Use `addSelect()` Subqueries for Single Values from Has-Many+## Select Single Relationship Values with Subqueries-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.+When only one value from a has-many relationship is needed, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. This selects the value as part of the main query without an additional relationship query.```phppublic function scopeWithLastLoginAt($query): void@@ -16,14 +16,14 @@ public function scopeWithLastLoginAt($query): void}```-## Create Dynamic Relationships via Subquery FK+## Create Dynamic Relationships with a Subquery Foreign Key-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.+The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still executes a separate query, but it avoids loading the full has-many collection.```phppublic function lastLogin(): BelongsTo{- return $this->belongsTo(Login::class);+ return $this->belongsTo(Login::class, 'last_login_id');}public function scopeWithLastLogin($query): void@@ -37,9 +37,9 @@ public function scopeWithLastLogin($query): void}```-## Use Conditional Aggregates Instead of Multiple Count Queries+## Combine Related Counts with Conditional Aggregates-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.+Combine several counts over the same filtered data set into one query by using conditional aggregates. Use `toBase()` when only scalar values are needed and model hydration provides no benefit. Confirm the expression syntax against the application's database engine.```php$statuses = Feature::toBase()@@ -49,50 +49,50 @@ $statuses = Feature::toBase()->first();```-## Use `setRelation()` to Prevent Circular N+1+## Reuse Loaded Parent Models with `setRelation()`-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.+When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. This avoids an additional lazy-loading query for each child.```php$feature->load('comments.user');$feature->comments->each->setRelation('feature', $feature);```-## Prefer `whereIn` + Subquery Over `whereHas`+## Compare `whereHas()` with an `IN` Subquery-`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.+`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form may be faster depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data; neither subquery loads its result set into PHP memory.-Incorrect (correlated EXISTS re-executes per row):+Option using `EXISTS`:```php$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));```-Correct (index-friendly subquery, no PHP memory overhead):+Option using `IN`:```php$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));```-## Sometimes Two Simple Queries Beat One Complex Query+## Measure Two Simple Queries Against 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.+Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.-## Use Compound Indexes Matching `orderBy` Column Order+## Design Composite Indexes for the Query-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.+For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that an index will be used. Verify the query plan.```php// Migration$table->index(['last_name', 'first_name']);-// Query — column order must match the index+// Query that this index may supportUser::query()->orderBy('last_name')->orderBy('first_name')->paginate();```-## Use Correlated Subqueries for Has-Many Ordering+## Consider a Correlated Subquery 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.+When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes.```phppublic function scopeOrderByLastLogin($query): voiddiff --git a/.claude/skills/laravel-best-practices/rules/architecture.md b/.claude/skills/laravel-best-practices/rules/architecture.mdindex 138d5a48d..d0a9a55c0 100644--- a/.claude/skills/laravel-best-practices/rules/architecture.md+++ b/.claude/skills/laravel-best-practices/rules/architecture.md@@ -1,8 +1,8 @@# Architecture Best Practices-## Single-Purpose Action Classes+## Extract Focused Business Operations-Extract discrete business operations into invokable Action classes.+Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel; follow the project's naming and invocation conventions.```phpclass CreateOrderAction@@ -19,11 +19,12 @@ class CreateOrderAction}```-## Use Dependency Injection+## Inject Required Dependencies-Always use constructor injection. Avoid `app()` or `resolve()` inside classes.+Prefer constructor injection for dependencies required throughout an object's lifetime. Method injection is appropriate for dependencies needed by one controller action, listener, job handler, or other container-invoked method. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.++Hidden dependency:-Incorrect:```phpclass OrderController extends Controller{@@ -36,24 +37,24 @@ class OrderController extends Controller}```-Correct:+Injected dependency:+```phpclass OrderController extends Controller{- public function __construct(private OrderService $service) {}-- public function store(StoreOrderRequest $request)+ public function store(StoreOrderRequest $request, OrderService $service){- return $this->service->create($request->validated());+ return $service->create($request->validated());}}```-## Code to Interfaces+## Depend on Contracts at Boundaries++Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.-Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.+Concrete boundary dependency:-Incorrect (concrete dependency):```phpclass OrderService{@@ -61,7 +62,8 @@ class OrderService}```-Correct (interface dependency):+Contract boundary dependency:+```phpinterface PaymentGateway{@@ -80,86 +82,99 @@ Bind in a service provider:$this->app->bind(PaymentGateway::class, StripeGateway::class);```-## Default Sort by Descending+## Specify a Deterministic Sort Order-When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.+Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters.++Unspecified order:-Incorrect:```php$posts = Post::paginate();```-Correct:+Newest first with a stable tie-breaker:+```php-$posts = Post::latest()->paginate();+$posts = Post::query()+ ->orderByDesc('created_at')+ ->orderByDesc('id')+ ->paginate();```## Use Atomic Locks for Race Conditions-Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.+Use a lock when concurrent execution must be serialized. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems. Set the lease (`10` below) longer than the callback can ever run: once it expires, another process can acquire the lock while the first is still working.```phpCache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {$order->process();});-// Or at query level-$product = Product::where('id', $id)->lockForUpdate()->first();+// Or at query level, inside a transaction+DB::transaction(function () use ($id) {+ $product = Product::where('id', $id)->lockForUpdate()->first();++ // Read and update the product while the database lock is held.+});```## 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.+When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware.Incorrect:+```php-strlen('José'); // 5 (bytes, not characters)-strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte+strlen('José'); // 5 bytes, not 4 characters+strtolower('MÜNCHEN'); // Does not lowercase Ü```Correct:+```php-mb_strlen('José'); // 4 (characters)-mb_strtolower('MÜNCHEN'); // 'münchen'+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'+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.+For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after the response has been sent but remains in the same PHP process.++Queued and durable:-Incorrect (job overhead for trivial work):```phpdispatch(new LogPageView($page));```-Correct (runs after response, same process):+Deferred in the current process:+```phpdefer(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 a queued job when the work needs retries, queue controls, or durability across process failures.## Use `Context` for Request-Scoped Data-The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.+The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.```php// In middlewareContext::add('tenant_id', $request->header('X-Tenant-ID'));-// Anywhere later — controllers, jobs, log context+// Later in the same execution lifecycle$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`.+Visible context is added to log context, and both visible and hidden context are captured and restored for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless that propagation is intended.## Use `Concurrency::run()` for Parallel Execution-Run independent operations in parallel using child processes — no async libraries needed.+Run independent operations concurrently through Laravel's configured concurrency driver.```phpuse Illuminate\Support\Facades\Concurrency;@@ -170,13 +185,14 @@ use Illuminate\Support\Facades\Concurrency;]);```-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.+With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver executes closures sequentially and is useful primarily during testing.-## Convention Over Configuration+## Follow Framework Conventions-Follow Laravel conventions. Don't override defaults unnecessarily.+Follow Laravel conventions unless the domain or an existing schema requires an override.++Customized schema:-Incorrect:```phpclass Customer extends Model{@@ -190,7 +206,8 @@ class Customer extends Model}```-Correct:+Conventional schema:+```phpclass Customer extends Model{diff --git a/.claude/skills/laravel-best-practices/rules/blade-views.md b/.claude/skills/laravel-best-practices/rules/blade-views.mdindex 5f0b3a1e3..4ea2c6c34 100644--- a/.claude/skills/laravel-best-practices/rules/blade-views.md+++ b/.claude/skills/laravel-best-practices/rules/blade-views.md@@ -1,8 +1,8 @@-# Blade & Views Best Practices+# Blade and View Best Practices## Use `$attributes->merge()` in Component Templates-Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.+Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior.```blade<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>@@ -12,25 +12,25 @@ Hardcoding classes prevents consumers from adding their own. `merge()` combines## 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.+If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response.-## Prefer Blade Components Over `@include`+## Prefer Components for Explicit Interfaces-`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.+Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include remains suitable for a small partial that intentionally uses the current view data; pass an explicit data array when implicit variable sharing would obscure its dependencies.-## Use View Composers for Shared View Data+## Share Compatible View Data with a View Composer-If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.+Use a view composer to centralize data needed whenever one or more named Blade views are rendered. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view; it does not supply data to JSON, streamed, or other non-view responses.-## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)+## Return Blade Fragments for Partial Rendering-A single view can return either the full page or just a fragment, keeping routing clean.+A route can return either a full view or a named fragment for clients such as htmx or Turbo.```phpreturn view('dashboard', compact('users'))->fragmentIf($request->hasHeader('HX-Request'), 'user-list');```-## Use `@aware` for Deeply Nested Component Props+## Share Parent Component Props with `@aware`-Avoids re-passing parent props through every level of nested components.+Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. It does not expose an ancestor's default prop value unless that value was passed through the attribute bag.diff --git a/.claude/skills/laravel-best-practices/rules/caching.md b/.claude/skills/laravel-best-practices/rules/caching.mdindex 67408d6e1..cd2ffd602 100644--- a/.claude/skills/laravel-best-practices/rules/caching.md+++ b/.claude/skills/laravel-best-practices/rules/caching.md@@ -1,10 +1,13 @@# Caching Best Practices-## Use `Cache::remember()` Instead of Manual Get/Put+## Use `Cache::remember()` for Cache-Aside Reads-Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.+`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value; use an atomic lock when duplicate computation must be prevented.++The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses.Incorrect:+```php$val = Cache::get('stats');if (! $val) {@@ -14,27 +17,42 @@ if (! $val) {```Correct:+```php$val = Cache::remember('stats', 60, fn () => $this->computeStats());```-## Use `Cache::flexible()` for Stale-While-Revalidate+## Consider `Cache::flexible()` for Stale-While-Revalidate++For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response; it is not a durable background job. Once the stale period has elapsed, the request recomputes the value synchronously.++Synchronous expiration:++```php+Cache::remember('users', 300, fn () => User::all());+```-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.+Stale-while-revalidate tradeoff:-Incorrect: `Cache::remember('users', 300, fn () => User::all());`+```php+Cache::flexible('users', [300, 600], 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.+This value is fresh for five minutes and may be served stale until ten minutes after it was cached.-## Use `Cache::memo()` to Avoid Redundant Hits Within a Request+## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution-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.+If the same cache key is read repeatedly during one request or job, `memo()` decorates a cache store and retains resolved values in memory for that execution.-`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.+```php+$settings = Cache::memo()->get('settings');+```++Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate.## 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`.+Tags group related entries for invalidation without tracking each key. Cache tags are not supported by the `file`, `dynamodb`, or `database` drivers; confirm support before choosing a store.```phpCache::tags(['user-1'])->flush();@@ -42,15 +60,27 @@ 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.+`add()` atomically writes a value only when the key does not already exist.++Incorrect:-Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`+```php+if (! Cache::has('lock')) {+ Cache::put('lock', true, 10);+}+```++Correct:++```php+Cache::add('lock', true, 10);+```-Correct: `Cache::add('lock', true, 10);`+Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required.-## Use `once()` for Per-Request Memoization+## Use `once()` for In-Process 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.+`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store.```phppublic function roles(): Collection@@ -59,11 +89,11 @@ public function roles(): Collection}```-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.+Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions.## Configure Failover Cache Stores in Production-If Redis goes down, the app falls back to a secondary store automatically.+The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and data is not replicated between stores.```php'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],diff --git a/.claude/skills/laravel-best-practices/rules/collections.md b/.claude/skills/laravel-best-practices/rules/collections.mdindex 18e8d9e1d..211fec11d 100644--- a/.claude/skills/laravel-best-practices/rules/collections.md+++ b/.claude/skills/laravel-best-practices/rules/collections.md@@ -2,41 +2,69 @@## Use Higher-Order Messages for Simple Operations-Incorrect:+Explicit closure:+```php$users->each(function (User $user) {$user->markAsVip();});```-Correct: `$users->each->markAsVip();`+Concise equivalent:++```php+$users->each->markAsVip();+```++Higher-order messages are available for supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.-Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.+## Choose Between `cursor()` and `lazy()`-## Choose `cursor()` vs. `lazy()` Correctly+`cursor()` executes one query and hydrates models individually, but it cannot eager load relationships. The database driver's result buffering can still consume substantial memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.-- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).-- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.+`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration.++With relationships:++```php+User::with('roles')->lazy()->each(function (User $user) {+ // The roles for this chunk have been eager loaded.+});+```-Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.+Without relationships:-Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.+```php+User::cursor()->each(function (User $user) {+ // Process model attributes.+});+```## 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.+`lazy()` uses offset pagination, so updates to columns that affect the query can shift rows and cause records to be skipped or processed twice. `lazyById()` paginates by a monotonic key and is safer when updating other columns during iteration. Do not change the pagination key itself while iterating.## Use `toQuery()` for Bulk Operations on Collections-Avoids manual `whereIn` construction.+Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.++Manual query:++```php+User::whereIn('id', $users->modelKeys())->update(['active' => false]);+```++Collection query:-Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`+```php+$users->toQuery()->update(['active' => false]);+```-Correct: `$users->toQuery()->update([...]);`+`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when those events are not required.## Use `#[CollectedBy]` for Custom Collection Classes-More declarative than overriding `newCollection()`.+The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.```php#[CollectedBy(UserCollection::class)]diff --git a/.claude/skills/laravel-best-practices/rules/config.md b/.claude/skills/laravel-best-practices/rules/config.mdindex 9bea727b3..82691c42a 100644--- a/.claude/skills/laravel-best-practices/rules/config.md+++ b/.claude/skills/laravel-best-practices/rules/config.md@@ -1,73 +1,85 @@# Configuration Best Practices-## `env()` Only in Config Files+## Read Environment Variables in Configuration Files-Direct `env()` calls may return `null` when config is cached.+Call `env()` only from configuration files. After configuration is cached, Laravel does not load the application's `.env` file, so application code should read configuration values through `config()`.Incorrect:+```php$key = env('API_KEY');```Correct:+```php// config/services.php-'key' => env('API_KEY'),+return [+ 'key' => env('API_KEY'),+];// Application code$key = config('services.key');```-## Use Encrypted Env or External Secrets+## Protect Production Secrets-Never store production secrets in plain `.env` files in version control.+Do not commit plaintext production secrets. Laravel can encrypt an environment file so its encrypted form can be stored safely, while deployment platforms can supply secrets through their native secret stores.Incorrect:-```bash-# .env committed to repo or shared in Slack--STRIPE_SECRET=sk_live_abc123-AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI+```bash+# A plaintext .env file committed to the repository+STRIPE_SECRET=<your-stripe-secret>+AWS_SECRET_ACCESS_KEY=<your-aws-secret>```-Correct:+Encrypted environment file:+```bashphp artisan env:encrypt --env=production --readablephp artisan env:decrypt --env=production```-For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.+For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime.## Use `App::environment()` for Environment ChecksIncorrect:+```phpif (env('APP_ENV') === 'production') {+ // ...+}```Correct:+```phpif (app()->isProduction()) {-// or+ // ...+}+if (App::environment('production')) {+ // ...+}```-## Use Constants and Language Files+## Name Repeated Domain Values-Use class constants instead of hardcoded magic strings for model states, types, and statuses.+Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant.```php-// Incorrect+// Repeated literalreturn $this->type === 'normal';-// Correct+// Named domain valuereturn $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.+If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages.```php-// Only when lang files already exist in the project+// In a localized applicationreturn back()->with('message', __('app.article_added'));```diff --git a/.claude/skills/laravel-best-practices/rules/db-performance.md b/.claude/skills/laravel-best-practices/rules/db-performance.mdindex c49ba164e..3f339770d 100644--- a/.claude/skills/laravel-best-practices/rules/db-performance.md+++ b/.claude/skills/laravel-best-practices/rules/db-performance.md@@ -1,10 +1,11 @@# Database Performance Best Practices-## Always Eager Load Relationships+## Eager Load Relationships Before Iterating-Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.+When a relationship will be accessed for many models, eager load it with `with()` to avoid running one initial query plus one relationship query per model, commonly called an N+1 query pattern. Lazy loading is reasonable when the relationship may not be needed or only one model is involved.++Lazy-loaded version:-Incorrect (N+1 — executes 1 + N queries):```php$posts = Post::all();foreach ($posts as $post) {@@ -12,7 +13,8 @@ foreach ($posts as $post) {}```-Correct (2 queries total):+Eager-loaded version:+```php$posts = Post::with('author')->get();foreach ($posts as $post) {@@ -20,7 +22,7 @@ foreach ($posts as $post) {}```-Constrain eager loads to select only needed columns (always include the foreign key):+Constrain eager loads when large columns are unnecessary. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, while selecting `posts.id` preserves each related model's primary key:```php$users = User::with(['posts' => function ($query) {@@ -42,31 +44,34 @@ public function boot(): void}```-Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.+By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`.## Select Only Needed Columns-Avoid `SELECT *` — especially when tables have large text or JSON columns.+Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit.++All columns:-Incorrect:```php$posts = Post::with('author')->get();```-Correct:+Selected columns:+```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.+When limiting selected columns, retain every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key.++## Process Large Data Sets Incrementally-## Chunk Large Datasets+Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget.-Never load thousands of records at once. Use chunking for batch processing.+Loads the complete result set:-Incorrect:```php$users = User::all();foreach ($users as $user) {@@ -74,7 +79,8 @@ foreach ($users as $user) {}```-Correct:+Processes bounded chunks:+```phpUser::where('subscribed', true)->chunk(200, function ($users) {foreach ($users as $user) {@@ -83,7 +89,7 @@ User::where('subscribed', true)->chunk(200, function ($users) {});```-Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:+Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change:```phpUser::where('active', false)->chunkById(200, function ($users) {@@ -91,11 +97,14 @@ User::where('active', false)->chunkById(200, function ($users) {});```-## Add Database Indexes+For read-only, attribute-only iteration, `cursor()` hydrates models individually from one query, although some database drivers still buffer raw results. Use `lazy()` when relationships must be eager loaded in chunks, and use `lazyById()` or `chunkById()` when updates can affect query membership. See the collection rules for detailed tradeoffs.-Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.+## Add Indexes for Measured Query Patterns++Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index; selectivity, write cost, existing indexes, and the database query plan all matter.++Schema without an application-specific query index:-Incorrect:```phpSchema::create('orders', function (Blueprint $table) {$table->id();@@ -105,24 +114,26 @@ Schema::create('orders', function (Blueprint $table) {});```-Correct:+Schema optimized for `WHERE status = ? ORDER BY created_at`:+```phpSchema::create('orders', function (Blueprint $table) {$table->id();- $table->foreignId('user_id')->index()->constrained();- $table->string('status')->index();+ $table->foreignId('user_id')->constrained();+ $table->string('status');$table->timestamps();$table->index(['status', 'created_at']);});```-Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).+Confirm composite index column order and effectiveness with production-like data and the database's query-plan tools. Also check whether the database already created an index to support a foreign key before adding another one.++## Count Relationships Without Loading Them-## Use `withCount()` for Counting Relations+Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory.-Never load entire collections just to count them.+Loads related models:-Incorrect:```php$posts = Post::all();foreach ($posts as $post) {@@ -130,7 +141,8 @@ foreach ($posts as $post) {}```-Correct:+Selects relationship counts:+```php$posts = Post::withCount('comments')->get();foreach ($posts as $post) {@@ -149,39 +161,24 @@ $posts = Post::withCount([])->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);-}-```+## Keep Queries Out of Blade Templates-Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.+Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable.-## No Queries in Blade Templates+Query in the template:-Never execute queries in Blade templates. Pass data from controllers.--Incorrect:```blade@foreach (User::all() as $user){{ $user->profile->name }}@endforeach```-Correct:+Data prepared before rendering:+```php// Controller$users = User::with('profile')->get();+return view('users.index', compact('users'));```diff --git a/.claude/skills/laravel-best-practices/rules/eloquent.md b/.claude/skills/laravel-best-practices/rules/eloquent.mdindex bd2cfca08..5a89510d0 100644--- a/.claude/skills/laravel-best-practices/rules/eloquent.md+++ b/.claude/skills/laravel-best-practices/rules/eloquent.md@@ -1,8 +1,8 @@# Eloquent Best Practices-## Use Correct Relationship Types+## Define Precise Relationship Types-Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.+Define the relationship that matches the database association, and declare its concrete return type.```phppublic function comments(): HasMany@@ -20,7 +20,8 @@ public function author(): BelongsToExtract reusable query constraints into local scopes to avoid duplication.-Incorrect:+Duplicated constraints:+```php$active = User::where('verified', true)->whereNotNull('activated_at')->get();$articles = Article::whereHas('user', function ($q) {@@ -28,7 +29,8 @@ $articles = Article::whereHas('user', function ($q) {})->get();```-Correct:+Reusable local scope:+```php#[Scope]protected function active(Builder $query): Builder@@ -45,7 +47,8 @@ $articles = Article::whereHas('user', fn ($q) => $q->active())->get();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):+Global scope tradeoff:+```phpclass PublishedScope implements Scope{@@ -54,10 +57,12 @@ class PublishedScope implements Scope$builder->where('published', true);}}-// Now admin panels, reports, and background jobs all silently skip drafts++// Admin panels, reports, and jobs now omit drafts unless the scope is removed.```-Correct (local scope you opt into):+Explicit local scope:+```php#[Scope]protected function published(Builder $query): Builder@@ -84,16 +89,18 @@ protected function casts(): array}```-## Cast Date Columns Properly+## Cast Date and Time Attributes++Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps.-Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.+Manual parsing in the template:-Incorrect:```blade-{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}+{{ Carbon::parse($order->ordered_at)->toDateString() }}```-Correct:+Model cast:+```phpprotected function casts(): array{@@ -110,24 +117,27 @@ protected function casts(): array## Use `whereBelongsTo()` for Relationship Queries-Cleaner than manually specifying foreign keys.+`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key.++Foreign key constraint:-Incorrect:```phpPost::where('user_id', $user->id)->get();```-Correct:+Relationship-aware constraint:+```phpPost::whereBelongsTo($user)->get();Post::whereBelongsTo($user, 'author')->get();```-## Avoid Hardcoded Table Names in Queries+## Keep Application Queries Model-Aware-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).+Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL legitimately require table names, so use them when their lower-level behavior is intentional.++Lower-level alternatives:-Incorrect:```phpDB::table('users')->where('active', true)->get();@@ -136,15 +146,13 @@ $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();+Model-aware queries:-// Even better — use Eloquent or the query builder instead of raw SQL+```phpUser::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.+When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer; keep those references covered by tests when schema changes are possible.-**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.+In migrations, use explicit table names rather than application models. Migrations are historical snapshots, while models and their scopes can change after a migration is deployed.diff --git a/.claude/skills/laravel-best-practices/rules/error-handling.md b/.claude/skills/laravel-best-practices/rules/error-handling.mdindex 4b1486676..afcdf4ac5 100644--- a/.claude/skills/laravel-best-practices/rules/error-handling.md+++ b/.claude/skills/laravel-best-practices/rules/error-handling.md@@ -1,15 +1,18 @@# Error Handling Best Practices-## Exception Reporting and Rendering+## Choose Where to Report and Render Exceptions-There are two valid approaches — choose one and apply it consistently across the project.+Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project.-**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:+Exception methods keep behavior beside the exception definition:```phpclass InvalidOrderException extends Exception{- public function report(): void { /* custom reporting */ }+ public function report(): void+ {+ // Send the exception to a custom reporter.+ }public function render(Request $request): Response{@@ -18,38 +21,40 @@ class InvalidOrderException extends Exception}```-**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:+Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together:```php->withExceptions(function (Exceptions $exceptions) {- $exceptions->report(function (InvalidOrderException $e) { /* ... */ });+ $exceptions->report(function (InvalidOrderException $e) {+ // Send the exception to a custom reporter.+ });$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.+An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering.-## Use `ShouldntReport` for Exceptions That Should Never Log+## Mark Exceptions the Handler Should Not Report-More discoverable than listing classes in `dontReport()`.+Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly.```phpclass PodcastProcessingException extends Exception implements ShouldntReport {}```-## Throttle High-Volume Exceptions+## Throttle High-Volume Exception Reports-A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.+A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits.-## Enable `dontReportDuplicates()`+## Prevent Duplicate Reports of One Exception Instance-Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.+Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message.-## Force JSON Error Rendering for API Routes+## Define JSON Rendering for API Routes-Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.+Laravel normally uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes.```php$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {@@ -59,7 +64,7 @@ $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {## 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.+Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.```phpclass InvalidOrderException extends Exceptiondiff --git a/.claude/skills/laravel-best-practices/rules/events-notifications.md b/.claude/skills/laravel-best-practices/rules/events-notifications.mdindex 82e329e8f..a8cce31a8 100644--- a/.claude/skills/laravel-best-practices/rules/events-notifications.md+++ b/.claude/skills/laravel-best-practices/rules/events-notifications.md@@ -1,24 +1,24 @@-# Events & Notifications Best Practices+# Events and Notifications Best Practices## Rely on Event Discovery-Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.+Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer.-## Run `event:cache` in Production Deploy+## Cache Event Discovery During Production Deployment-Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.+Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.## Use `ShouldDispatchAfterCommit` Inside Transactions-Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.+When an event is dispatched inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. This affects synchronous and queued listeners; it is not limited to queue timing.```phpclass OrderShipped implements ShouldDispatchAfterCommit {}```-## Always Queue Notifications+## Queue Slow Notifications-Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.+Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation.```phpclass InvoicePaid extends Notification implements ShouldQueue@@ -27,9 +27,9 @@ class InvoicePaid extends Notification implements ShouldQueue}```-## Use `afterCommit()` on Notifications in Transactions+## Dispatch Queued Notifications After Commit-Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.+A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. This setting has no scheduling effect on a synchronous notification.```php$user->notify((new InvoicePaid($invoice))->afterCommit());@@ -37,7 +37,7 @@ $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.+Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues.## Use On-Demand Notifications for Non-User Recipients@@ -49,4 +49,4 @@ Notification::route('mail', '[email protected]')->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.+Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification.diff --git a/.claude/skills/laravel-best-practices/rules/http-client.md b/.claude/skills/laravel-best-practices/rules/http-client.mdindex 8e2f16e8a..cc8fdd6ab 100644--- a/.claude/skills/laravel-best-practices/rules/http-client.md+++ b/.claude/skills/laravel-best-practices/rules/http-client.md@@ -1,86 +1,100 @@# HTTP Client Best Practices-## Always Set Explicit Timeouts+## Set Explicit Timeouts-The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.+Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Remember that retries can multiply the total elapsed time.++Less resilient:-Incorrect:```php$response = Http::get('https://api.example.com/users');```-Correct:+Preferred:+```php-$response = Http::timeout(5)- ->connectTimeout(3)+$response = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users');```-For service-specific clients, define timeouts in a macro:+Define shared settings in a macro or a dedicated client:```phpHttp::macro('github', function () {return Http::baseUrl('https://api.github.com')- ->timeout(10)->connectTimeout(3)+ ->timeout(10)->withToken(config('services.github.token'));});$response = Http::github()->get('/repos/laravel/framework');```-## Use Retry with Backoff for External APIs+## Retry Only Safe Operations-External APIs have transient failures. Use `retry()` with increasing delays.+Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection.-Incorrect:-```php-$response = Http::post('https://api.stripe.com/v1/charges', $data);+Unsafe without an idempotency guarantee:-if ($response->failed()) {- throw new PaymentFailedException('Charge failed');-}+```php+$response = Http::retry([100, 500, 1000])+ ->post('https://api.example.com/v1/charges', $data);```-Correct:+Safe for an idempotent request:+```php-$response = Http::retry([100, 500, 1000])+$response = Http::connectTimeout(3)->timeout(10)- ->post('https://api.stripe.com/v1/charges', $data);+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->get('https://api.example.com/data');```-Only retry on specific errors:+For a supported state-changing API, send a stable idempotency key for every attempt:```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');+$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])+ ->connectTimeout(3)+ ->timeout(10)+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->post('https://api.example.com/v1/charges', $data);```## Handle Errors Explicitly-The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.+The HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing by default. Inspect the expected statuses or call `throw()` before consuming a success payload.++Unsafe when a success payload is expected:-Incorrect:```php-$response = Http::get('https://api.example.com/users/1');-$user = $response->json(); // Could be an error body+$user = Http::get('https://api.example.com/users/1')->json();```-Correct:+Preferred:+```php-$response = Http::timeout(5)+$user = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users/1')- ->throw();--$user = $response->json();+ ->throw()+ ->json();```-For graceful degradation:+Handle expected alternatives explicitly when graceful degradation is required:```php-$response = Http::get('https://api.example.com/users/1');+$response = Http::connectTimeout(3)+ ->timeout(5)+ ->get('https://api.example.com/users/1');if ($response->successful()) {return $response->json();@@ -93,46 +107,30 @@ if ($response->notFound()) {$response->throw();```-## Use Request Pooling for Concurrent Requests+## Pool Independent Requests-When making multiple independent API calls, use `Http::pool()` instead of sequential calls.+Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling; inspect or throw for each response as needed.-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:```phpuse 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'),+ $pool->as('users')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/users'),+ $pool->as('posts')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/posts'),]);-$users = $responses['users']->json();-$posts = $responses['posts']->json();+$users = $responses['users']->throw()->json();+$posts = $responses['posts']->throw()->json();```-## Fake HTTP Calls in Tests--Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.+## Fake HTTP Requests in Tests-Incorrect:-```php-it('syncs user from API', function () {- $service = new UserSyncService;- $service->sync(1); // Hits the real API-});-```+Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles.-Correct:```php-it('syncs user from API', function () {+it('syncs a user from the API', function () {Http::preventStrayRequests();Http::fake([@@ -142,16 +140,15 @@ it('syncs user from API', function () {]),]);- $service = new UserSyncService;- $service->sync(1);+ (new UserSyncService)->sync(1);- Http::assertSent(function (Request $request) {- return $request->url() === 'https://api.example.com/users/1';- });+ Http::assertSent(fn (Request $request) =>+ $request->url() === 'https://api.example.com/users/1'+ );});```-Test failure scenarios too:+For example, fake a connection failure when testing the integration's failure path:```phpHttp::fake([diff --git a/.claude/skills/laravel-best-practices/rules/mail.md b/.claude/skills/laravel-best-practices/rules/mail.mdindex 7c717336d..f6310437c 100644--- a/.claude/skills/laravel-best-practices/rules/mail.md+++ b/.claude/skills/laravel-best-practices/rules/mail.md@@ -1,27 +1,54 @@# Mail Best Practices-## Implement `ShouldQueue` on the Mailable Class+## Queue Slow Mail Delivery-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.+Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`.-## Use `afterCommit()` on Mailables Inside Transactions+```php+class OrderShipped extends Mailable implements ShouldQueue+{+ use Queueable, SerializesModels;+}+```-A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.+Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.-## Use `assertQueued()` Not `assertSent()` for Queued Mailables+## Dispatch Queued Mail After Commit-`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.+A queued mailable dispatched during a database transaction can be processed before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records.-Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.+```php+Mail::to($user)->send(+ (new OrderShipped($order))->afterCommit()+);+```-Correct: `Mail::assertQueued(OrderShipped::class);`+If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery.-## Use Markdown Mailables for Transactional Emails+## Assert the Delivery Mode-Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.+Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.-## Separate Content Tests from Sending Tests+Incorrect for a mailable that implements `ShouldQueue`:-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.+```php+Mail::assertSent(OrderShipped::class);+```++Correct:++```php+Mail::assertQueued(OrderShipped::class);+```++## Use Markdown Mailables When They Fit++Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They are useful for conventional transactional messages, but a custom HTML and text pair may be more appropriate for a specialized design.++```bash+php artisan make:mail OrderShipped --markdown=mail.orders.shipped+```++## Separate Content and Delivery Tests++Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior.diff --git a/.claude/skills/laravel-best-practices/rules/migrations.md b/.claude/skills/laravel-best-practices/rules/migrations.mdindex df6f5f33c..3345402eb 100644--- a/.claude/skills/laravel-best-practices/rules/migrations.md+++ b/.claude/skills/laravel-best-practices/rules/migrations.md@@ -2,76 +2,51 @@## Generate Migrations with Artisan-Always use `php artisan make:migration` for consistent naming and timestamps.+Use `php artisan make:migration` to generate the timestamped filename and migration structure.-Incorrect (manually created file):-```php-// database/migrations/posts_migration.php ← wrong naming, no timestamp-```--Correct (Artisan-generated):```bashphp artisan make:migration create_posts_tablephp artisan make:migration add_slug_to_posts_table```-## Use `constrained()` for Foreign Keys+## Define Foreign-Key Constraints Deliberately-Automatic naming and referential integrity.+Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.```php$table->foreignId('user_id')->constrained()->cascadeOnDelete();--// Non-standard names$table->foreignId('author_id')->constrained('users');```-## Never Modify Deployed Migrations+Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration.-Once a migration has run in production, treat it as immutable. Create a new migration to change the table.+## Treat Deployed Migrations as Immutable-Incorrect (editing a deployed migration):-```php-// 2024_01_01_create_posts_table.php — already in production-$table->string('slug')->unique(); // ← added after deployment-```+After a migration has run in a shared or production environment, create a new migration for subsequent changes. Editing the old file makes fresh installations differ from upgraded installations.-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');-});-```+For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.-## Add Indexes in the Migration+## Design Indexes for Real Queries-Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.+Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column appearing in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index.-Incorrect:-```php-Schema::create('orders', function (Blueprint $table) {- $table->id();- $table->foreignId('user_id')->constrained();- $table->string('status');- $table->timestamps();-});-```+Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan, and avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance.++## Stage Changes That Affect Existing Rows++Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid.++Do not assume this migration is safe on a populated table:-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();-});+$table->string('slug')->unique();```-## Mirror Defaults in Model `$attributes`+Large backfills are usually better implemented as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when their locking, transaction, and deployment behavior is understood.-When a column has a database default, mirror it in the model so new instances have correct values before saving.+## Mirror Defaults Only When Unsaved Models Need Them++A database default is applied when a row is inserted, not when a model is instantiated. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions synchronized.```php// Migration@@ -83,39 +58,10 @@ protected $attributes = [];```-## 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');- });-}-```+## Make Rollbacks Honest-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.+Implement `down()` when the change can be safely reversed. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible; document that limitation and prefer a forward-fix migration in production.## 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']);-```+Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when doing so reduces locks and supports phased deployment, but do not split related operations merely to enforce a blanket separation between data definition and data manipulation.diff --git a/.claude/skills/laravel-best-practices/rules/queue-jobs.md b/.claude/skills/laravel-best-practices/rules/queue-jobs.mdindex c41915e2b..011828a6c 100644--- a/.claude/skills/laravel-best-practices/rules/queue-jobs.md+++ b/.claude/skills/laravel-best-practices/rules/queue-jobs.md@@ -1,82 +1,82 @@-# Queue & Job Best Practices+# Queue and Job Best Practices-## Set `retry_after` Greater Than `timeout`+## Keep Reservation Time Longer Than Execution Time-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.+For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`.-Incorrect (`retry_after` ≤ `timeout`):```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}+// Job+public $timeout = 120;-// config/queue.php — retry_after: 90 ← job retried while still running!+// config/queue.php for the connection+'retry_after' => 150,```-Correct (`retry_after` > `timeout`):-```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}--// config/queue.php — retry_after: 180 ← safely longer than any job timeout-```+Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`; configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings.-## Use Exponential Backoff+## Back Off Transient Failures-Use progressively longer delays between retries to avoid hammering failing services.+Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.-Incorrect (fixed retry interval):```phpclass SyncWithStripe implements ShouldQueue{- public $tries = 3;- // Default: retries immediately, overwhelming the API-}-```+ public $tries = 4;-Correct (exponential backoff):-```php-class SyncWithStripe implements ShouldQueue-{- public $tries = 3;public $backoff = [1, 5, 10];}```-## Implement `ShouldBeUnique`+Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window.++## Use Unique Jobs for Dispatch Deduplication-Prevent duplicate job processing.+Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock and is not a substitute for idempotent processing or a database constraint.```phpclass GenerateInvoice implements ShouldQueue, ShouldBeUnique{+ public $uniqueFor = 3600;+public function uniqueId(): string{- return $this->order->id;+ return (string) $this->order->id;}+}+```- public $uniqueFor = 3600;+All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.++Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running:++```php+class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing+{+ // ...}```-## Always Implement `failed()`+## Handle Terminal Failure When Needed++Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting.-Handle errors explicitly — don't rely on silent failure.+Laravel invokes `failed()` on a new job instance, so mutations made to the job during `handle()` are not available there.```phppublic function failed(?Throwable $exception): void{$this->podcast->update(['status' => 'failed']);- Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);++ Log::error('Podcast processing failed', [+ 'podcast_id' => $this->podcast->id,+ 'exception' => $exception,+ ]);}```-## Rate Limit External API Calls in Jobs+## Rate Limit External Calls-Use `RateLimited` middleware to throttle jobs calling third-party APIs.+Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together.```phppublic function middleware(): array@@ -85,60 +85,33 @@ public function middleware(): array}```-## Batch Related Jobs+## Batch Jobs for Group Coordination-Use `Bus::batch()` when jobs should succeed or fail together.+Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction: completed jobs are not rolled back when another job fails. By default, one failed job cancels the batch; call `allowFailures()` only when partial failure is acceptable.```phpBus::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();+ ->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))+ ->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [+ 'exception' => $exception,+ ]))+ ->dispatch();```-## `retryUntil()` Needs `$tries = 0`+## Configure Time-Based Retry Limits Deliberately-When using time-based retry limits, set `$tries = 0` to avoid premature failure.+Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. The method takes precedence over attempt-based limits, so setting `$tries = 0` is not required.```php-public $tries = 0;--public function retryUntil(): \DateTimeInterface+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.+## Use Horizon for Redis Queue Operations-```php-// config/horizon.php-'environments' => [- 'production' => [- 'supervisor-1' => [- 'connection' => 'redis',- 'queue' => ['high', 'default', 'low'],- 'balance' => 'auto',- 'minProcesses' => 1,- 'maxProcesses' => 10,- 'tries' => 3,- ],- ],-],-```+Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.diff --git a/.claude/skills/laravel-best-practices/rules/routing.md b/.claude/skills/laravel-best-practices/rules/routing.mdindex b6e30864f..604a8d96d 100644--- a/.claude/skills/laravel-best-practices/rules/routing.md+++ b/.claude/skills/laravel-best-practices/rules/routing.md@@ -1,99 +1,106 @@-# Routing & Controllers Best Practices+# Routing and Controller Best Practices## Use Implicit Route Model Binding-Let Laravel resolve models automatically from route parameters.+Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.++Instead of manual lookup:-Incorrect:```php-public function show(int $id)+public function show(int $id): View{$post = Post::findOrFail($id);++ return view('posts.show', ['post' => $post]);}```-Correct:+Use route model binding:+```php-public function show(Post $post)+public function show(Post $post): View{return view('posts.show', ['post' => $post]);}```-## Use Scoped Bindings for Nested Resources+## Scope Nested Bindings-Enforce parent-child relationships automatically.+Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization.```phpRoute::get('/users/{user}/posts/{post}', function (User $user, Post $post) {- // $post is automatically scoped to $user+ // The resolved post belongs to the resolved user.})->scopeBindings();```-## Use Resource Controllers+## Use Resource Routes for Resourceful Actions-Use `Route::resource()` or `apiResource()` for RESTful endpoints.+Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary.```phpRoute::resource('posts', PostController::class);-// In routes/api.php — the /api prefix is applied automatically-Route::apiResource('posts', Api\PostController::class);++// Alternatively, for an API-only resource:+Route::apiResource('posts', ApiPostController::class);```-## Keep Controllers Thin+`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not itself add an `/api` prefix; that prefix comes from the application's API route configuration.++## Organize Controllers Around Resources++As a general default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This keeps routes predictable and prevents controllers from accumulating unrelated behavior.-Aim for under 10 lines per method. Extract business logic to action or service classes.+When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary.++Custom action on the primary controller:-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);-}+Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']);```-Correct:+The published podcast modeled as a resource:+```php-public function store(StorePostRequest $request, CreatePostAction $create)-{- $post = $create->execute($request->validated());+Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store'])+ ->name('published-podcasts.store');- return redirect()->route('posts.show', $post);-}+Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy'])+ ->name('published-podcasts.destroy');```-## 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+class PublishedPodcastController extends Controller{- $validated = $request->validate([- 'title' => ['required', 'max:255'],- 'body' => ['required'],- ]);+ public function store(Podcast $podcast): RedirectResponse+ {+ $podcast->publish();++ return back();+ }- Post::create($validated);+ public function destroy(Podcast $podcast): RedirectResponse+ {+ $podcast->unpublish();- return redirect()->route('posts.index');+ return back();+ }}```-Correct:+Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions.++## Keep Controllers Focused on HTTP Concerns++Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service merely to satisfy an arbitrary line limit.+```php-public function store(StorePostRequest $request): RedirectResponse+public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse{- Post::create($request->validated());+ $post = $create->handle($request->validated());- return redirect()->route('posts.index');+ return redirect()->route('posts.show', $post);}```++A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity; see the validation rules for detailed guidance.diff --git a/.claude/skills/laravel-best-practices/rules/scheduling.md b/.claude/skills/laravel-best-practices/rules/scheduling.mdindex a98479450..4c25134a9 100644--- a/.claude/skills/laravel-best-practices/rules/scheduling.md+++ b/.claude/skills/laravel-best-practices/rules/scheduling.md@@ -1,32 +1,50 @@# Task Scheduling Best Practices-## Use `withoutOverlapping()` on Variable-Duration Tasks+## Prevent Unwanted Overlap-Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.+Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. This is appropriate for variable-duration tasks that are not safe to run concurrently.-## Use `onOneServer()` on Multi-Server Deployments+```php+Schedule::command('reports:generate')+ ->everyFifteenMinutes()+ ->withoutOverlapping(30);+```++The optional value is the lock expiration time in minutes, not the task timeout. Choose it carefully: the default is 24 hours, stale locks can be cleared with `php artisan schedule:clear-cache`, and an expiration that is too short can permit overlap while the first task still runs. The task itself should still tolerate retries and partial execution where practical.-Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).+## Run a Task on One Server-## Use `runInBackground()` for Concurrent Long Tasks+Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`.++```php+Schedule::command('billing:charge')->daily()->onOneServer();+```-By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.+Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity.-## Use `environments()` to Restrict Tasks+## Run Eligible Commands in the Background-Prevent accidental execution of production-only tasks (billing, reporting) on staging.+Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.```php-Schedule::command('billing:charge')->monthly()->environments(['production']);+Schedule::command('analytics:process')->hourly()->runInBackground();```-## Use `takeUntilTimeout()` for Time-Bounded Processing+Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`; it is not available for scheduled closures. Ensure background processes have appropriate logging and failure monitoring.-A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.+## Restrict Tasks by Environment-## Use Schedule Groups for Shared Configuration+Use `environments()` when a task should run only in named application environments. Treat this as an operational safeguard, not an authorization control.-Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.+```php+Schedule::command('billing:charge')+ ->monthly()+ ->environments(['production']);+```++## Group Shared Configuration++Use schedule groups when several tasks genuinely share frequency or constraints.```phpSchedule::daily()@@ -37,3 +55,7 @@ Schedule::daily()Schedule::command('emails:prune');});```++## Bound Work Inside the Task++The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required.diff --git a/.claude/skills/laravel-best-practices/rules/security.md b/.claude/skills/laravel-best-practices/rules/security.mdindex 2d7200c29..57b57f0fa 100644--- a/.claude/skills/laravel-best-practices/rules/security.md+++ b/.claude/skills/laravel-best-practices/rules/security.md@@ -1,18 +1,9 @@# Security Best Practices-## Mass Assignment Protection+## Control Mass Assignment-Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).+Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default; `$guarded = []` opts out of that protection.-Incorrect:-```php-class User extends Model-{- protected $guarded = []; // All fields are mass assignable-}-```--Correct:```phpclass User extends Model{@@ -24,82 +15,71 @@ class User extends Model}```-Never use `$guarded = []` on models that accept user input.--## Authorize Every Action+Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set; it does not validate values or authorize the operation.-Use policies or gates in controllers. Never skip authorization.+## Authorize Protected Actions-Incorrect:-```php-public function update(UpdatePostRequest $request, Post $post)-{- $post->update($request->validated());-}-```+Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.-Correct:```php-public function update(UpdatePostRequest $request, Post $post)+public function update(UpdatePostRequest $request, Post $post): RedirectResponse{Gate::authorize('update', $post);$post->update($request->validated());++ return redirect()->route('posts.show', $post);}```-Or via Form Request:+Authorization may instead live in the form request:```phppublic function authorize(): bool{- return $this->user()->can('update', $this->route('post'));+ return $this->user()?->can('update', $this->route('post')) ?? false;}```-## Prevent SQL Injection+Public actions intentionally available to everyone do not need a redundant authorization check.++## Bind Query Parameters-Always use parameter binding. Never interpolate user input into queries.+Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions; map user-selected identifiers to an allow-list.Incorrect:+```phpDB::select("SELECT * FROM users WHERE name = '{$request->name}'");```Correct:+```phpUser::where('name', $request->name)->get();--// Raw expressions with bindings-User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();+User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();```-## Escape Output to Prevent XSS+## Escape Output in Its Context-Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.+Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content that has been sanitized for the exact HTML context in which it is rendered. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.++Incorrect for untrusted content:-Incorrect:```blade{!! $user->bio !!}```Correct:+```blade{{ $user->bio }}```-## CSRF Protection--Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.+## Apply Cross-Site Request Forgery Protection-Incorrect:-```blade-<form method="POST" action="/posts">- <input type="text" name="title">-</form>-```+Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.-Correct:```blade<form method="POST" action="/posts">@csrf@@ -107,21 +87,27 @@ Correct:</form>```-## Rate Limit Auth and API Routes+Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Confirm equivalent configuration when using another HTTP client. Do not disable CSRF protection merely to fix a token mismatch.-Apply `throttle` middleware to authentication and API routes.+## Rate Limit Sensitive Endpoints++Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately; an Internet Protocol (IP) address alone can unfairly group users behind a shared network, while an account identifier alone can enable targeted denial of service.```phpRateLimiter::for('login', function (Request $request) {- return Limit::perMinute(5)->by($request->ip());+ return Limit::perMinute(5)->by(Str::transliterate(+ Str::lower($request->string('email')).'|'.$request->ip()+ ));});Route::post('/login', LoginController::class)->middleware('throttle:login');```-## Validate File Uploads+Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection.++## Validate and Store Uploads Safely-Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.+Validate expected content type, dimensions where relevant, and size. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions; it does not validate the user-assigned filename extension. The `extensions` rule checks that extension and should not be used by itself.```phppublic function rules(): array@@ -132,56 +118,28 @@ public function rules(): array}```-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.+Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.-Incorrect:```php-$key = env('API_KEY');+$path = $request->file('avatar')->store('avatars');```-Correct:-```php-// config/services.php-'api_key' => env('API_KEY'),+## Keep Secrets Out of Application Code-// In application code-$key = config('services.api_key');-```+Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works correctly. See the configuration rules for encrypted environment files and external secret stores.## Audit Dependencies-Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.+Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.```bashcomposer audit```-## Encrypt Sensitive Database Fields--Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.+## Encrypt Sensitive Attributes When Appropriate-Incorrect:-```php-class Integration extends Model-{- protected function casts(): array- {- return [- 'api_key' => 'string',- ];- }-}-```+Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. Encrypted values cannot be meaningfully queried and should use a `TEXT` or larger column because ciphertext length is variable.-Correct:```phpclass Integration extends Model{diff --git a/.claude/skills/laravel-best-practices/rules/style.md b/.claude/skills/laravel-best-practices/rules/style.mdindex a8afb3695..3f3f14fbc 100644--- a/.claude/skills/laravel-best-practices/rules/style.md+++ b/.claude/skills/laravel-best-practices/rules/style.md@@ -1,125 +1,110 @@-# 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 |-|---------|---------|+# Convention and Style Best Practices++## Follow Project Naming Conventions++Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.++| Element | Convention | Example |+| --- | --- | --- |+| Controller | Singular resource name | `ArticleController` |+| Model | Singular StudlyCase | `User` |+| Table | Plural snake_case | `article_comments` |+| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` |+| Column | snake_case | `meta_title` |+| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |+| Resource URI | Plural resource | `articles/1` |+| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` |+| Method | camelCase | `getAll` |+| Variable | camelCase | `$articlesWithAuthor` |+| Collection | Descriptive and plural | `$activeUsers` |+| Object | Descriptive and singular | `$activeUser` |+| View | kebab-case | `show-filtered.blade.php` |+| Configuration file | snake_case | `google_calendar.php` |+| Enumeration | Singular StudlyCase | `UserType` |++## Prefer Clear, Idiomatic Syntax++Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.++| More verbose | Idiomatic alternative |+| --- | --- || `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')` |+| `->first()?->name` | `->value('name')` when only that value is needed |-## Use Laravel String & Array Helpers+Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.-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.+## Use Utilities When They Clarify Intent-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);+Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as an unconditional replacement for every built-in function.-// Correct+```php$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+$class = class_basename(User::class);$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()`.+Use `Arr` for dot notation and common transformations:-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');+$public = Arr::only($attributes, ['name', 'email']);```-Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.+Use `Number` for localized display formatting rather than values that will be stored or calculated:-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%"+Number::format(1000000);+Number::currency(1500, 'USD');+Number::fileSize(1024 * 1024);```-URIs — use `Uri` for URL manipulation:+Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API:+```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.+Check the documentation for the Laravel version supported by the project before using newer utility classes or methods.-Use `search-docs` for the full list of available methods — these helpers are extensive.+## Keep Presentation Code Maintainable-## No Inline JS/CSS in Blade+Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks; avoid mixing large behavior and style blocks into templates.-Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.+Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript:-Incorrect:```blade-let article = `{{ json_encode($article) }}`;+<script>+ const article = {{ Js::from($article) }};+</script>```-Correct:-```blade-<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>-```+Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.-Pass data to JS via data attributes or use a dedicated PHP-to-JS package.+## Write Comments That Explain Why-## No Unnecessary Comments+Prefer clear names and small units of code over comments that merely restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.-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.+Unhelpful:-Incorrect:```php-// Check if there are any joins-if (count((array) $builder->getQuery()->joins) > 0)+// Check whether the query has joins.+if (count((array) $builder->getQuery()->joins) > 0) {+ // ...+}```-Correct:+Clearer:+```php-if ($this->hasJoins())+if ($this->hasJoins()) {+ // ...+}```diff --git a/.claude/skills/laravel-best-practices/rules/testing.md b/.claude/skills/laravel-best-practices/rules/testing.mddeleted file mode 100644index 4fbf12f8a..000000000--- a/.claude/skills/laravel-best-practices/rules/testing.md+++ /dev/null@@ -1,43 +0,0 @@-# 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/.claude/skills/laravel-best-practices/rules/validation.md b/.claude/skills/laravel-best-practices/rules/validation.mdindex 5fde1064a..37ce6c5e2 100644--- a/.claude/skills/laravel-best-practices/rules/validation.md+++ b/.claude/skills/laravel-best-practices/rules/validation.md@@ -1,75 +1,89 @@-# Validation & Forms Best Practices+# Validation and Forms Best Practices-## Use Form Request Classes+## Extract Validation When It Improves the Boundary-Extract validation from controllers into dedicated Form Request classes.+Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set.-Incorrect:```php-public function store(Request $request)+public function store(StorePostRequest $request): RedirectResponse{- $request->validate([- 'title' => 'required|max:255',- 'body' => 'required',- ]);-}-```+ $post = Post::create($request->validated());-Correct:-```php-public function store(StorePostRequest $request)-{- Post::create($request->validated());+ return redirect()->route('posts.show', $post);}```-## Array vs. String Notation for Rules+A form request's `authorize()` method can enforce access to the operation. Validation establishes the shape and values of input; it does not itself authorize the user.-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.+## Prefer Readable Rule Syntax++Array syntax composes cleanly with rule objects and avoids delimiter issues. Prefer it in new code when it improves readability, while following a consistent local style.```php-// Preferred for new code'email' => ['required', 'email', Rule::unique('users')],+```-// Follow existing convention if the project uses string notation+String syntax remains valid for simple rules:++```php'email' => 'required|email|unique:users',```-## Always Use `validated()`+## Use Only Intended Validated Data-Get only validated data. Never use `$request->all()` for mass operations.+Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. Then select the fields intended for the operation when the validation rules also cover control fields or nested data.++Unsafe:-Incorrect:```phpPost::create($request->all());```-Correct:+Preferred:+```php-Post::create($request->validated());+$post = Post::create($request->safe()->only(['title', 'body']));```-## Use `Rule::when()` for Conditional Validation+Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation merely to make mass assignment convenient.++## Express Conditional Rules Clearly++Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test.```php'company_name' => [- Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),+ 'string',+ 'max:255',+ Rule::when(+ $this->input('account_type') === 'business',+ ['required'],+ ['nullable'],+ ),],```-## Use the `after()` Method for Custom Validation+## Add Cross-Field Validation After Base Rules-Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.+Use a form request's `after()` method for validation that depends on multiple fields or application state. Avoid expensive queries when prerequisite fields have already failed validation.```phppublic function after(): array{return [function (Validator $validator) {- if ($this->quantity > Product::find($this->product_id)?->stock) {+ if ($validator->errors()->hasAny(['product_id', 'quantity'])) {+ return;+ }++ $stock = Product::find($this->integer('product_id'))?->stock;++ if ($stock !== null && $this->integer('quantity') > $stock) {$validator->errors()->add('quantity', 'Not enough stock.');}},];}```++Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate.diff --git a/.claude/skills/mcp-development/SKILL.md b/.claude/skills/mcp-development/SKILL.mdindex 4ef1bb9a6..ca63d9fb2 100644--- a/.claude/skills/mcp-development/SKILL.md+++ b/.claude/skills/mcp-development/SKILL.md@@ -22,22 +22,17 @@ Register MCP servers in `routes/ai.php`:```phpuse Laravel\Mcp\Facades\Mcp;-Mcp::web();+Mcp::web('/mcp/demo', \App\Mcp\Servers\AppServer::class);```### Creating MCP Primitives```bashphp artisan make:mcp-tool ToolName # Create a tool-php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)-```After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.diff --git a/.claude/skills/mcp-development/references/app.md b/.claude/skills/mcp-development/references/app.mdindex db2e752a3..93042c3f9 100644--- a/.claude/skills/mcp-development/references/app.md+++ b/.claude/skills/mcp-development/references/app.md@@ -27,7 +27,14 @@ class DashboardApp extends AppResourcecreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -104,7 +111,7 @@ MCP Apps add interactive UI to the Model Context Protocol. The server returns se└─────────────────────────────────────────────┘```-The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.+The server automatically advertises `capabilities.extensions["io.modelcontextprotocol/ui"]` on `server/discover` when any `AppResource` is registered. Add cases of the `Extension` enum to the server's `$extensions` property to declare any other extension. The client declares its own support in the `io.modelcontextprotocol/clientCapabilities` member of each request's `_meta`.---@@ -307,7 +314,14 @@ Renders a complete self-contained HTML document with the MCP SDK inlined. `creatcreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -703,9 +717,19 @@ class GetMonitorData extends Tool```jscreateMcpApp(async (app) => {async function poll() {- const result = await app.callServerTool('get-monitor-data');- const data = JSON.parse(result.content[0]?.text ?? '{}');- document.getElementById('cpu').textContent = data.cpu;+ try {+ const result = await app.callServerTool('get-monitor-data');++ if (result.isError) {+ document.getElementById('cpu').textContent = result.content[0]?.text ?? 'Unavailable';+ return;+ }++ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ } catch {+ // transport failure or malformed payload, retry on next tick+ }}setInterval(poll, 2000);@@ -776,6 +800,11 @@ In the client, convert the base64 blob to a data URI for rendering:```jsconst result = await app.callServerTool('get-image', { id: 42 });++if (result.isError) {+ return;+}+const blob = result.content[0];img.src = `data:${blob.mimeType};base64,${blob.data}`;```@@ -798,8 +827,17 @@ createMcpApp(async (app) => {});app.onToolResult((params) => {- const data = JSON.parse(params.result.content[0]?.text ?? "{}");- renderResults(data);+ if (params.result.isError) {+ document.getElementById("error").textContent =+ params.result.content[0]?.text ?? "Unknown error";+ return;+ }++ try {+ renderResults(JSON.parse(params.result.content[0]?.text ?? "{}"));+ } catch {+ document.getElementById("error").textContent = "Malformed tool result";+ }});});```diff --git a/.claude/skills/passport-development/SKILL.md b/.claude/skills/passport-development/SKILL.mdindex e5dce352f..6a083d9c0 100644--- a/.claude/skills/passport-development/SKILL.md+++ b/.claude/skills/passport-development/SKILL.md@@ -95,15 +95,10 @@ Create clients with the appropriate flag for the grant type:```bashphp artisan passport:client # Authorization code-php artisan passport:client --public # PKCE (no secret)-php artisan passport:client --client # Client credentials-php artisan passport:client --personal # Personal access tokens-php artisan passport:client --device # Device authorization-```Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.@@ -182,11 +177,8 @@ Passport::actingAsClient($client, ['scope1']);```bashphp artisan passport:purge # Purge revoked & expired-php artisan passport:purge --revoked # Only revoked-php artisan passport:purge --expired # Only expired-```Schedule `passport:purge` for regular expired token clean-up.diff --git a/.claude/skills/pest-testing/SKILL.md b/.claude/skills/pest-testing/SKILL.mddeleted file mode 100644index 79cd0bcce..000000000--- a/.claude/skills/pest-testing/SKILL.md+++ /dev/null@@ -1,203 +0,0 @@-----name: pest-testing-description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."-license: MIT-metadata:- author: laravel------# Pest Testing 5--## Documentation--Use `search-docs` for detailed Pest 5 patterns and documentation.--## Basic Usage--### Creating Tests--All tests must be written using Pest. Use `php artisan make:test --pest {name}`.--The `{name}` argument should include only the path and test name, but should not include the test suite.-- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`-- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`-- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`-- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`--### Test Organization--- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.-- Browser tests: `tests/Browser/` directory.-- Do NOT remove tests without approval - these are core application code.--### Basic Test Structure--Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.--<!-- Basic Pest Test Example -->-```php-it('is true', function () {- expect(true)->toBeTrue();-});-```--### Running Tests--- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.-- Run all tests: `php artisan test --compact`.-- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.-- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.--## Assertions--Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:--<!-- Pest Response Assertion -->-```php-it('returns all', function () {- $this->postJson('/api/docs', [])->assertSuccessful();-});-```--| Use | Instead of |-|-----|------------|-| `assertSuccessful()` | `assertStatus(200)` |-| `assertNotFound()` | `assertStatus(404)` |-| `assertForbidden()` | `assertStatus(403)` |--## Mocking--Import mock function before use: `use function Pest\Laravel\mock;`--## Datasets--Use datasets for repetitive tests (validation rules, etc.):--<!-- Pest Dataset Example -->-```php-it('has emails', function (string $email) {- expect($email)->not->toBeEmpty();-})->with([- 'james' => '[email protected]',- 'taylor' => '[email protected]',-]);-```--## Pest 5 Features--| Feature | Purpose |-|---------|---------|-| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |-| Time-Balanced Sharding | Split tests across CI shards by execution time |-| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |-| Browser Testing | Full integration tests in real browsers |-| Smoke Testing | Validate multiple pages quickly |-| Visual Regression | Compare screenshots for visual changes |-| Architecture Testing | Enforce code conventions |--### Tia (Test Impact Analysis)--Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:--<!-- Tia Example -->-```shell-./vendor/bin/pest --parallel --tia-```--- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.-- Detects Laravel, Symfony, Livewire, and Inertia automatically.--### New Validation Expectations--Pest 5 ships eight new validation matchers, all supporting `.not` negation:--<!-- Pest 5 Validation Expectations -->-```php-expect('[email protected]')->toBeEmail();-expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();-expect('192.168.1.1')->toBeIpAddress();-expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();-expect('example.com')->toBeHostname();-expect('example.co.uk')->toBeDomain();-expect('Zm9vYmFy')->toBeBase64();-expect('deadbeef')->toBeHexadecimal();-```--### Time-Balanced Sharding--Distribute tests across CI shards by execution time rather than count:--<!-- Pest Sharding Example -->-```shell-./vendor/bin/pest --update-shards-./vendor/bin/pest --shard=1/4-```--Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.--### Browser Test Example--Browser tests run in real browsers for full integration testing:--- Browser tests live in `tests/Browser/`.-- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.-- Use `RefreshDatabase` for clean state per test.-- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.-- Test on multiple browsers (Chrome, Firefox, Safari) if requested.-- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.-- Switch color schemes (light/dark mode) when appropriate.-- Take screenshots or pause tests for debugging.--<!-- Pest Browser Test Example -->-```php-it('may reset the password', function () {- Notification::fake();-- $this->actingAs(User::factory()->create());-- $page = visit('/sign-in');-- $page->assertSee('Sign In')- ->assertNoJavaScriptErrors()- ->click('Forgot Password?')- ->fill('email', '[email protected]')- ->click('Send Reset Link')- ->assertSee('We have emailed your password reset link!');-- Notification::assertSent(ResetPassword::class);-});-```--### Smoke Testing--Quickly validate multiple pages have no JavaScript errors:--<!-- Pest Smoke Testing Example -->-```php-$pages = visit(['/', '/about', '/contact']);--$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();-```--### Visual Regression Testing--Capture and compare screenshots to detect visual changes.--### Architecture Testing--<!-- Architecture Test Example -->-```php-arch('controllers')- ->expect('App\Http\Controllers')- ->toExtendNothing()- ->toHaveSuffix('Controller');-```--## Common Pitfalls--- Not importing `use function Pest\Laravel\mock;` before using mock-- Using `assertStatus(200)` instead of `assertSuccessful()`-- Forgetting datasets for repetitive validation tests-- Deleting tests without approval-- Forgetting `assertNoJavaScriptErrors()` in browser tests-- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`diff --git a/.claude/skills/tailwindcss-development/SKILL.md b/.claude/skills/tailwindcss-development/SKILL.mdindex c0cb2fbcd..98f9f1712 100644--- a/.claude/skills/tailwindcss-development/SKILL.md+++ b/.claude/skills/tailwindcss-development/SKILL.md@@ -48,16 +48,16 @@ In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead o### Replaced Utilities-Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.+Tailwind v4 removed deprecated utilities. Use the replacements shown below. For opacity, drop the `*-opacity-*` class and append the value as a modifier on the existing color: `bg-blue-500 bg-opacity-50` becomes `bg-blue-500/50`, `text-white text-opacity-75` becomes `text-white/75`.| 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/* |+| bg-opacity-* | bg-{color}/* |+| text-opacity-* | text-{color}/* |+| border-opacity-* | border-{color}/* |+| divide-opacity-* | divide-{color}/* |+| ring-opacity-* | ring-{color}/* |+| placeholder-opacity-* | placeholder-{color}/* || flex-shrink-* | shrink-* || flex-grow-* | grow-* || overflow-ellipsis | text-ellipsis |@@ -87,29 +87,6 @@ If existing pages and components support dark mode, new pages and components mus</div>```-## Common Patterns--### Flexbox Layout--<!-- Flexbox Layout -->-```html-<div class="flex items-center justify-between gap-4">- <div>Left content</div>- <div>Right content</div>-</div>-```--### Grid Layout--<!-- Grid Layout -->-```html-<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">- <div>Card 1</div>- <div>Card 2</div>- <div>Card 3</div>-</div>-```-## Common Pitfalls- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)diff --git a/.claude/skills/testing-best-practices/SKILL.md b/.claude/skills/testing-best-practices/SKILL.mdnew file mode 100644index 000000000..9b0aa7f91--- /dev/null+++ b/.claude/skills/testing-best-practices/SKILL.md@@ -0,0 +1,58 @@+---+name: testing-best-practices+description: "Laravel test design and review. Use when selecting coverage, naming or structuring tests, choosing assertions or test data, isolating dependencies, testing HTTP or security boundaries, improving suite performance, or reviewing test value. Use framework guidance or search-docs for Pest and PHPUnit syntax."+license: MIT+metadata:+ author: laravel+---++# Testing Best Practices++This skill provides rules for designing Laravel tests. Each rule file explains what to do and why. Use `search-docs` for Laravel and Pest API syntax.+This project uses Pest. Follow the corresponding guidance in each rule.++## Consistency First++Read nearby tests before you choose syntax and organization.++A pattern repeated throughout the project is a convention, and project conventions take precedence over this skill. Follow them and give new tests the same structure.++These rules govern the tests you write now. An existing test that follows a project convention is not defective merely because it conflicts with this skill. Do not delete or rewrite it. If the convention has drawbacks, explain them and let the user decide.++## What to Test++Read this section before you write a test.++- Test observable behavior and application contracts. A test must pass after an implementation change if the behavior stays the same.+- Cover every changed decision and each applicable high-value failure mode. A decision is a branch, a validation, a calculation, or an authorization.+- Exercise declarations through behavior instead of repeating their text.+- Leave framework behavior to framework tests. Testing project configuration is not testing the framework. A constrained relationship, cast, scope, or validation rule belongs to this project.+- Keep every test that can detect a distinct defect. When two tests detect the same defect, trim the higher-layer test to one case and report the duplication. Do not delete an existing test.+- Write a feature test first. Write a unit test only for logic that does not use the framework.+- Write a browser test only for behavior in JavaScript that a feature test cannot reach. Put a browser test in `tests/Browser`, and call `assertNoJavaScriptErrors()` in it.+- Judge an architecture test by the convention it protects, not by the rules above. An `arch()` test declares a rule for an entire directory, such as the parent class of every model, the classes that may use an enum, or the methods every factory declares. It intentionally checks declarations and fails when a new file breaks the convention.+- Use the test tools that the project installs. Add a new test dependency, plugin, or browser only after the user asks for it.++## How to Apply++1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.+2. Select every applicable branch in the rule index. Read every selected rule file.+3. Report each defect in the code before you write a test. Examples are a method with no body, a policy that no action calls, and a write action with no validation. Test the actual behavior. Report the defect to the user.+4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.+5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.++## Rule Index++Most changes need more than one rule file.++| Subject | Rule File |+| --- | --- |+| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |+| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |+| Arrange-act-assert and choosing the correct assertion | [`rules/assertions.md`](rules/assertions.md) |+| Endpoint coverage, authentication, authorization, tenant isolation, validation, and browser tests | [`rules/endpoint-tests.md`](rules/endpoint-tests.md) |+| Factories, test data ownership, and repeated input values | [`rules/test-data.md`](rules/test-data.md) |+| Fakes, mocks, outbound HTTP, time, randomness, and databases | [`rules/isolation.md`](rules/isolation.md) |+| Escaping, injection, cross-tenant access, and privilege checks | [`rules/security.md`](rules/security.md) |+| Environment and CI settings for a slow suite | [`rules/performance.md`](rules/performance.md) |+| Reviewing a test or suite | [`rules/review.md`](rules/review.md) |diff --git a/.claude/skills/testing-best-practices/rules/assertions.md b/.claude/skills/testing-best-practices/rules/assertions.mdnew file mode 100644index 000000000..528bdd4b0--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/assertions.md@@ -0,0 +1,64 @@+# Assertions++## Arrange, Act, Assert++Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.++Keep each test self-contained. Do not use values created by another test.++## How to Find the Correct Assertion++First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.++1. Search Laravel's assertions for framework subjects such as responses, the database, sessions, models, queues, events, mail, and notifications.+2. Fetch `https://pestphp.com/docs/expectations.md` for the expectations of Pest for a plain value, a type, a format, or a shape.+3. Build the check by hand only if no assertion exists for the subject.+4. Confirm the name in the documentation before you use it. Do not write an assertion that you did not confirm.++Use the assertion in this table for each subject.++| Subject | Assertion to use |+| --- | --- |+| A return value, the state of an object, or a transformation of a value | an `expect()` chain |+| An HTTP status, JSON, a session, or Inertia | a Laravel response assertion |+| The state in the database | a Laravel database assertion |+| The existence of a model | `assertModelExists($model)` rather than `assertDatabaseHas('users', ['id' => $user->id])` |++Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exists for the subject.++Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.++## Named Response Assertions++Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.++Keep one `expect()` chain on one subject. Start a new chain when the subject changes, or when the chain is difficult to read.++## Format Expectations++Use Pest's format expectations rather than regular expressions because they provide clearer failure messages. Pest covers email addresses, URLs, UUIDs, IP addresses, and other common formats, and each expectation supports `not` for the negative case.++## Assert a Known Value++Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.++```php+// The test calculates the value with the logic of the implementation...+$expected = now()->subHours(24)->floorSeconds(30)->toJson();+expect($from)->toBe($expected);++// The test sets a fixed input and asserts a known value...+travelTo('2025-01-01 00:00:00');+expect($from)->toBe('2024-12-31T00:00:00.000000Z');+```++## Assert the Complete Result++A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:++- The response or the return value.+- The state in the database.+- The jobs and the events that the operation dispatches.+- The notifications and the mail that the operation sends.++On the failure path, assert that the operation makes none of these changes. A test that asserts only `assertOk()` passes even when the application saves no record.diff --git a/.claude/skills/testing-best-practices/rules/endpoint-tests.md b/.claude/skills/testing-best-practices/rules/endpoint-tests.mdnew file mode 100644index 000000000..e3fc18b75--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/endpoint-tests.md@@ -0,0 +1,73 @@+# Endpoint Tests++## How to Write the Test++Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.++Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.++## Endpoint Coverage++Write a test for each applicable case:++- The request has missing or invalid authentication.+- The request comes from a different tenant, team, or organization.+- The user has an insufficient role or permission.+- The request does not satisfy a route or scope constraint.+- The request fails the validation.+- The request is valid. Assert both the response and the persisted state.++Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.++## Tenant Isolation++Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.++## Test Authorization at the Policy Level++An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.++- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.+- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.+- Use the helper of the project that asserts the ability and the arguments of the gate, if such a helper exists.++## Browser Tests++Write a browser test only for JavaScript behavior that an HTTP test cannot reach, such as modal interaction, drag-and-drop, live search, or client-side validation. Browser tests are slower than HTTP tests and can fail for reasons unrelated to the code under test.++- Assert the state that the user can see, and assert the state in the database that the interaction saves.+- Wait until the test reaches the required state. Do not wait for a fixed number of seconds, which can fail on a slower machine.+- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.++### Where a Browser Test Lives and How to Run It++The plugin runs browser tests as normal Pest tests, so they need no separate suite. Put them in `tests/Browser` to separate them from faster tests and run the directory with one command.++- Run a browser test with `vendor/bin/pest tests/Browser`, and add `--parallel` for the complete suite.+- Run `vendor/bin/pest --debug` to open the window of the browser and to pause at a failure. Use `--headed` to watch a run that passes.+- Add `--browser firefox` or `--browser safari` to run the test in a different browser. The default browser is Chrome.+- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.+- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.++### Browser Test Pitfalls++- The plugin waits five seconds for an element. Raise the value with `pest()->browser()->timeout(10000)` in `Pest.php` for a page that is slower, and do not add a wait for a number of seconds to the test.+- Apply `RefreshDatabase` to the browser tests in `Pest.php`. A browser test hits the application through a real request, and the records that it leaves break the next test.+- Add `tests/Browser/Screenshots` to `.gitignore`. A failure writes a screenshot, and the file is not part of the repository.+- Give `withKeyDown()` a key code, such as `KeyA`. A letter such as `'a'` gives the lowercase character, whatever modifier the test holds.+- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.++## Testing Validation++- Write one test for each validation rule when each failure represents a separate contract.+- Write one test with an empty payload to assert several required fields together.+- Assert the text of the message that the user gets. A message that is present but wrong is a defect.+- Use a dataset for input values that need the same setup and the same assertions.++Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.++### Which Layer Owns Which Case++The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.++When both tests contain the matrix, move it to the rule-class test and retain one case in the endpoint test. Never remove the last case, because the rule-class test still passes if the request omits the rule. The same division applies to policies, scopes, and other classes called by a request.diff --git a/.claude/skills/testing-best-practices/rules/finding-features.md b/.claude/skills/testing-best-practices/rules/finding-features.mdnew file mode 100644index 000000000..fc16c39bd--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/finding-features.md@@ -0,0 +1,37 @@+# How to Find Test Framework Features++Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.++- Give `search-docs` the capability you need rather than the name of a function you remember. It returns features available in the installed version.+- Fetch `https://pestphp.com/llms.txt` for the complete feature list and additions in each release.+- If a search returns no results, tell the user that the installed version does not provide the feature. Do not write an API that you have not confirmed.++Search for a feature in this table before you write the code by hand.++| Work that you need | Term to search for |+| --- | --- |+| Run one test with many input values | datasets, bound datasets |+| Assert over many values or over a collection | higher-order expectations |+| Remove the same setup from each test in a file | hooks, higher-order tests |+| Apply a convention to the complete codebase | architecture testing |+| Measure if the suite finds a defect | mutation testing |+| Find code with no types | type coverage |+| Reduce the time of a slow suite | parallel, profiling |+| Split the suite across CI jobs | sharding, `--update-shards` |+| Run only the tests that a change affects | Test Impact Analysis, `--tia` |+| Assert that a value has a known format | validation expectations |+| Run one test while you debug | filtering, `--bail`, `--dirty` |++## Built-in Laravel Assertion Methods++Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before building a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.++A hand-built check fails with `false is not true`, which identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure indicates what to fix.++```php+// The failure says that false is not true. Instead of this...+expect(User::where('email', '[email protected]')->exists())->toBeTrue();++// Use this... the failure names the table and the attributes that it did not find...+$this->assertDatabaseHas('users', ['email' => '[email protected]']);+```diff --git a/.claude/skills/testing-best-practices/rules/isolation.md b/.claude/skills/testing-best-practices/rules/isolation.mdnew file mode 100644index 000000000..e1a21fdb4--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/isolation.md@@ -0,0 +1,52 @@+# Fakes, Mocks, and Determinism++Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.++## How to Isolate a Dependency++Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.++Identify the dependency, then choose the first applicable option. A framework fake preserves the real code path, while a mock replaces the dependency.++1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.+2. Use a developer-defined fake implementation of a service if the application provides one.+3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.+4. Use the real implementation for everything else, including the database.++## Framework Fakes++- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.+- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.+- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.+- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.+- Assert the data of a job or of an event if that data is part of the behavior.+- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.++Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID, and a fake without class names suppresses those events and can produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.++## Mocking++Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. Use `Mockery::on()` or `withArgs()` if an equality check cannot state the expected argument, such as a check of one field of a value object.++Import the mock function before you use it: `use function Pest\Laravel\mock;`.++## Outbound HTTP Testing++Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.++Fake the exact endpoint used by each test. Do not call `Http::fake()` without an endpoint because it accepts unexpected requests and can hide defects.++## Time and Randomness++- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.+- Use the framework helpers `freezeTime()`, `travelTo()`, `travel()`, and `travelBack()`. Do not call `Carbon::setTestNow()`.+- Use `Str::createRandomStringsUsing()` to fix a generated string, if the test asserts an identifier or a slug.+- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.+- Restore the time and the randomness after each test, if the suite does not restore them for every test.++## Database++- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.+- Assert the exact keys of `toArray()` if the shape of the serialized model is a contract. The test then fails when the model exposes a new attribute.+- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.+- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.diff --git a/.claude/skills/testing-best-practices/rules/naming.md b/.claude/skills/testing-best-practices/rules/naming.mdnew file mode 100644index 000000000..4f3f5b1d1--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/naming.md@@ -0,0 +1,45 @@+# Naming and Structure++## File Layout++- Name each test file `{ClassName}Test.php`.+- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.+- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.+- Move large literal values out of the test body and into fixture files.++## Test Function++Use the test function used by other files in the same directory. If no neighboring test files exist:++- Use `it()` for the behavior of the code, and write the name as a verb phrase.+- Use `test()` for a declarative fact, such as a grant in a policy, the labels of an enum, or the shape of a serialized model.++Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.++## Naming Tests++The name of a test is a specification. State the user-visible result and the condition that causes it.++- Name the behavior, and not the method under test. The file name already gives the class.+- Give the exact status code in the name of a test for an API error.+- Do not write `Given`, `When`, or `Then` in the name.++```php+it('returns 401 when no token is provided', function () { ... });+it('does not include deployments from deleted environments', function () { ... });+it('falls back to the default region when none is configured', function () { ... });+```++Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.++Do not write `it('works correctly')` or `it('returns data')`, because neither specifies a meaningful result. Do not write `it('handleMethod creates record')`, because it names a method rather than behavior.++## Grouping++Use `describe()` if one file covers separate actions in a lifecycle. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.++Do not use `describe()` in these cases:++- The file covers one action or one flow.+- The tests are different only in the input value. Use a dataset instead.+- The group adds a level but does not make the file easier to read.diff --git a/.claude/skills/testing-best-practices/rules/performance.md b/.claude/skills/testing-best-practices/rules/performance.mdnew file mode 100644index 000000000..f1d9c9b35--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/performance.md@@ -0,0 +1,58 @@+# Test Suite Performance++These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.++Fetch `https://pestphp.com/docs/optimizing-tests` for Pest options that make test runs faster.+Verify each flag in the documentation before adding it to CI.++Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.++## Test Environment++- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.+- Disable XDebug. Disable pcov also, unless the run needs the coverage.+- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.+- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.+- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.++## Global Fakes++Put these three calls in the base `Pest.php` of the project:++- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. This catches requests made through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.+- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.+- `Exceptions::fake()`, so the suite does not report an exception to an external service.++## How to Run the Suite in Parallel++Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. Add `--processes=N` if the default count is unsuitable for the machine or CI.++A parallel run gives each process a separate database. Tests must meet these conditions; a test that fails only in parallel breaks one of them:++- The test creates each record that it reads. It does not read a record that another test creates.+- The test does not depend on the order of the run.+- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.++## How to Run Fewer Tests++Run `vendor/bin/pest --parallel --tia` to run only the tests that the recent changes affect. Pest replays the cached result of each other test.++Pest replays cached results rather than skipping unaffected tests. The cache includes each produced value and the covered lines and branches. Pest finds affected Laravel, Symfony, Livewire, and Inertia tests without configuration.++## How to Split Tests Across CI++Run `vendor/bin/pest --update-shards` to measure the time of each test. Run `vendor/bin/pest --shard=1/4` in each CI job, and change the first number for each job.++Commit `tests/.pest/shards.json` so each CI job gets the same shard and the shards remain balanced by runtime rather than test count.++## How to Find a Slow Test++Run `vendor/bin/pest --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.++If the cause of a slow test is unclear, add an event listener or temporary log entry to identify its work.++## Common Errors++- The run loads XDebug for a test that does not need it.+- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.+- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.diff --git a/.claude/skills/testing-best-practices/rules/review.md b/.claude/skills/testing-best-practices/rules/review.mdnew file mode 100644index 000000000..e0cfca147--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/review.md@@ -0,0 +1,44 @@+# Reviewing Tests++Check every item in this file. A passing test may still provide no value. For each test, identify the defect it would catch.++Report each finding. Do not delete or rewrite a test without the user's approval. When an issue appears throughout the suite as a convention, report the pattern once rather than every affected file.++## Test Value++Apply this section to behavioral tests. An architecture test states a convention for a directory, so these items do not apply to it.++- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.+- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.+- [ ] Each test detects a distinct defect that no other test covers. A duplicate shrinks at the higher layer to the one case that proves the wiring.+- [ ] Every changed decision and each applicable high-value failure mode has coverage.++## Names and Structure++- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.+- [ ] Each name states a result, the condition that causes it, and the status code for an API error.+- [ ] Each file uses one declaration style consistently, and each `describe()` group holds separate behavior.++## Coverage++- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.+- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.+- [ ] The complete permission matrix belongs in policy tests, not controller tests.+- [ ] Each validation rule has one test that asserts the user-visible message. When a unit test owns a matrix, reduce duplicate higher-level coverage to one case rather than deleting it.+- [ ] Rendered user input and each dynamic part of a query have a security test.++## Data and Determinism++- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.+- [ ] Each `beforeEach()` holds configuration only.+- [ ] Each factory state and each relationship gives the meaning of the data.+- [ ] Each call to `make()` is in a test that does not need the database.+- [ ] Time, randomness, sleep, and outbound HTTP are controlled.+- [ ] Each test passes alone, and passes in the complete suite in any order.++## Assertions++- [ ] Each expected value is a known value, and the test does not calculate the value with the logic of the implementation.+- [ ] Each test of a write operation asserts the response, the state in the database, and the side effects.+- [ ] Each fake has one assertion, and gives the class names unless the test asserts the complete result.+- [ ] Each `expect()` chain stays on one subject.diff --git a/.claude/skills/testing-best-practices/rules/security.md b/.claude/skills/testing-best-practices/rules/security.mdnew file mode 100644index 000000000..234f5b005--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/security.md@@ -0,0 +1,27 @@+# Security Tests++Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary can be difficult to detect because the feature may continue to work.++Write a test for each of these cases:++- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for why the response should possibly be `404` rather than `403`.+- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.+- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners may decode it.+- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.+- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.++```php+it('escapes dangerous content in the notification', function () {+ $organization = Organization::factory()->make([+ 'name' => "O'Reilly <script>alert('xss')</script>",+ ]);++ $content = (new QuotaApproaching($organization, 80))->toMail()->render();++ expect($content)+ ->toContain('<script>')+ ->not->toContain("<script>alert('xss')</script>");+});+```++Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the appropriate defense to each attribute, route, and template.diff --git a/.claude/skills/testing-best-practices/rules/test-data.md b/.claude/skills/testing-best-practices/rules/test-data.mdnew file mode 100644index 000000000..65124683b--- /dev/null+++ b/.claude/skills/testing-best-practices/rules/test-data.md@@ -0,0 +1,56 @@+# Factories and Test Data++## Each Test Makes Its Own Data++Create mutable records inside the test that uses them. This keeps setup visible and lets each test select its factory state.++Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.++## Record Construction++- Use `create()` if the test needs the record in the database.+- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.+- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning; `create(['email_verified_at' => null])` gives only its value.+- Use `for()` or the relationship helper of the project to declare the owner of a record.+- Use `recycle()` if several records must share one parent record.+- Use `sequence()` if several records need different attributes.++```php+$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();++$environment = Environment::factory()->recycle($organization)->create();++$organizations = Organization::factory()+ ->count(3)+ ->sequence(+ ['created_at' => now()->setSeconds(30)],+ ['created_at' => now()->setSeconds(1)],+ )+ ->create();+```++Create only the records required to arrange the behavior or support an assertion.++## Datasets++Use a dataset when the setup, test body, and assertions remain the same across input values.++```php+it('forbids roles other than admin', function (Role $role) {+ actingAs(User::factory()->hasOrganization($role)->create())+ ->post('/settings')+ ->assertForbidden();+})->with(collect(Role::cases())->reject(fn (Role $role) => $role === Role::ADMIN));+```++Use parameterized tests for:++- enum cases+- roles and plans+- boundary values+- input values that are invalid in the same way+- input and output value pairs++Write separate tests if the cases need a different setup, a different behavior, or different assertions. One test function with a branch in the body is two tests in one function.++Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.diff --git a/.claude/skills/wayfinder-development/SKILL.md b/.claude/skills/wayfinder-development/SKILL.mdindex a13cfc3b4..e80d131c0 100644--- a/.claude/skills/wayfinder-development/SKILL.md+++ b/.claude/skills/wayfinder-development/SKILL.md@@ -17,10 +17,13 @@ Use `search-docs` for detailed Wayfinder patterns and documentation.### Generate RoutesRun after route changes if Vite plugin isn't installed:+```bashphp artisan wayfinder:generate --no-interaction```+For form helpers, use `--with-form` flag:+```bashphp artisan wayfinder:generate --with-form --no-interaction```@@ -56,7 +59,7 @@ destroy.delete(1)store.form() // { action: "/posts", method: "post" }// Query parameters...-show(1, { query: { page: 1 } }) // "/posts/1?page=1"+show(1, { query: { page: 1 } }) // { url: "/posts/1?page=1", method: "get" }```## Wayfinder + Inertiadiff --git a/.cursor/skills/configure-nightwatch/SKILL.md b/.cursor/skills/configure-nightwatch/SKILL.mdindex 1fc580bbd..000a031b1 100644--- a/.cursor/skills/configure-nightwatch/SKILL.md+++ b/.cursor/skills/configure-nightwatch/SKILL.md@@ -62,15 +62,10 @@ Sampling determines which entry points (requests, commands, scheduled tasks) triConfigure via environment variables:```bash-# Default: 100% sampling (all requests/commands captured)-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions-```**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.@@ -312,22 +307,17 @@ Redaction modifies captured data to remove or obfuscate sensitive information. U**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):```bash-# Customize redacted headers-NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key```**Redact request payloads** (disabled by default):```bash-# Enable payload capture-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true# Customize redacted fields-NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card```diff --git a/.cursor/skills/configure-nightwatch/reference.md b/.cursor/skills/configure-nightwatch/reference.mdindex b071d2f2e..eddd8842e 100644--- a/.cursor/skills/configure-nightwatch/reference.md+++ b/.cursor/skills/configure-nightwatch/reference.md@@ -21,49 +21,36 @@### High-Traffic Applications```bash-# Conservative sampling-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests-NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands-NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions# Filter noisy events-NIGHTWATCH_IGNORE_CACHE_EVENTS=trueNIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically-```### Privacy-Conscious Applications```bash-# Disable sensitive data collection-NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=falseNIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN# Or use redaction in AppServiceProvider-```### Balanced Configuration (Recommended Start)```bash-# Sample rates-NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0# Filter obvious noise programmatically-# Redact PII as needed-```---diff --git a/.cursor/skills/infer-conventions/SKILL.md b/.cursor/skills/infer-conventions/SKILL.mdindex 11a932753..b42bca89e 100644--- a/.cursor/skills/infer-conventions/SKILL.md+++ b/.cursor/skills/infer-conventions/SKILL.md@@ -1,6 +1,7 @@---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."+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, API responses), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+disable-model-invocation: truelicense: MITmetadata:author: laraveldiff --git a/.cursor/skills/infer-conventions/references/checklist.md b/.cursor/skills/infer-conventions/references/checklist.mdindex f8d1b1441..3de1f1775 100644--- a/.cursor/skills/infer-conventions/references/checklist.md+++ b/.cursor/skills/infer-conventions/references/checklist.md@@ -9,11 +9,11 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app## A. Validation & HTTP input1. 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`.+ - 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`.+ - 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`.@@ -26,7 +26,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app7. 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.+ - 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`.@@ -37,7 +37,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app11. 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(`.+ - Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.## D. Eloquent & models@@ -56,7 +56,7 @@ Each item gives the fork, then a hint (a grep or dir to spot which side the app19. 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/`.+ - Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.## E. Architecture & organization@@ -89,11 +89,11 @@ This app ships a frontend stack, so the items below apply.## G. Database & migrations33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.- - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+ - 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.+ - 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.@@ -108,14 +108,14 @@ This app ships a frontend stack, so the items below apply.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/`.+ - 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 resources43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.- - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+ - 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.@@ -126,7 +126,7 @@ This app ships a frontend stack, so the items below apply.## J. Strings, collections & dates47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.- - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+ - 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.diff --git a/.cursor/skills/laravel-best-practices/SKILL.md b/.cursor/skills/laravel-best-practices/SKILL.mdindex d136d7556..311ab8443 100644--- a/.cursor/skills/laravel-best-practices/SKILL.md+++ b/.cursor/skills/laravel-best-practices/SKILL.md@@ -48,7 +48,7 @@ Cross-cutting changes often need more than one rule file.| 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) |+| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill || Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) || Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |diff --git a/.cursor/skills/laravel-best-practices/rules/advanced-queries.md b/.cursor/skills/laravel-best-practices/rules/advanced-queries.mdindex f12876e4c..54dd783d9 100644--- a/.cursor/skills/laravel-best-practices/rules/advanced-queries.md+++ b/.cursor/skills/laravel-best-practices/rules/advanced-queries.md@@ -1,8 +1,8 @@-# Advanced Query Patterns+# Advanced Query Best Practices-## Use `addSelect()` Subqueries for Single Values from Has-Many+## Select Single Relationship Values with Subqueries-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.+When only one value from a has-many relationship is needed, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. This selects the value as part of the main query without an additional relationship query.```phppublic function scopeWithLastLoginAt($query): void@@ -16,14 +16,14 @@ public function scopeWithLastLoginAt($query): void}```-## Create Dynamic Relationships via Subquery FK+## Create Dynamic Relationships with a Subquery Foreign Key-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.+The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still executes a separate query, but it avoids loading the full has-many collection.```phppublic function lastLogin(): BelongsTo{- return $this->belongsTo(Login::class);+ return $this->belongsTo(Login::class, 'last_login_id');}public function scopeWithLastLogin($query): void@@ -37,9 +37,9 @@ public function scopeWithLastLogin($query): void}```-## Use Conditional Aggregates Instead of Multiple Count Queries+## Combine Related Counts with Conditional Aggregates-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.+Combine several counts over the same filtered data set into one query by using conditional aggregates. Use `toBase()` when only scalar values are needed and model hydration provides no benefit. Confirm the expression syntax against the application's database engine.```php$statuses = Feature::toBase()@@ -49,50 +49,50 @@ $statuses = Feature::toBase()->first();```-## Use `setRelation()` to Prevent Circular N+1+## Reuse Loaded Parent Models with `setRelation()`-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.+When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. This avoids an additional lazy-loading query for each child.```php$feature->load('comments.user');$feature->comments->each->setRelation('feature', $feature);```-## Prefer `whereIn` + Subquery Over `whereHas`+## Compare `whereHas()` with an `IN` Subquery-`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.+`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form may be faster depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data; neither subquery loads its result set into PHP memory.-Incorrect (correlated EXISTS re-executes per row):+Option using `EXISTS`:```php$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));```-Correct (index-friendly subquery, no PHP memory overhead):+Option using `IN`:```php$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));```-## Sometimes Two Simple Queries Beat One Complex Query+## Measure Two Simple Queries Against 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.+Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.-## Use Compound Indexes Matching `orderBy` Column Order+## Design Composite Indexes for the Query-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.+For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that an index will be used. Verify the query plan.```php// Migration$table->index(['last_name', 'first_name']);-// Query — column order must match the index+// Query that this index may supportUser::query()->orderBy('last_name')->orderBy('first_name')->paginate();```-## Use Correlated Subqueries for Has-Many Ordering+## Consider a Correlated Subquery 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.+When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes.```phppublic function scopeOrderByLastLogin($query): voiddiff --git a/.cursor/skills/laravel-best-practices/rules/architecture.md b/.cursor/skills/laravel-best-practices/rules/architecture.mdindex 138d5a48d..d0a9a55c0 100644--- a/.cursor/skills/laravel-best-practices/rules/architecture.md+++ b/.cursor/skills/laravel-best-practices/rules/architecture.md@@ -1,8 +1,8 @@# Architecture Best Practices-## Single-Purpose Action Classes+## Extract Focused Business Operations-Extract discrete business operations into invokable Action classes.+Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel; follow the project's naming and invocation conventions.```phpclass CreateOrderAction@@ -19,11 +19,12 @@ class CreateOrderAction}```-## Use Dependency Injection+## Inject Required Dependencies-Always use constructor injection. Avoid `app()` or `resolve()` inside classes.+Prefer constructor injection for dependencies required throughout an object's lifetime. Method injection is appropriate for dependencies needed by one controller action, listener, job handler, or other container-invoked method. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.++Hidden dependency:-Incorrect:```phpclass OrderController extends Controller{@@ -36,24 +37,24 @@ class OrderController extends Controller}```-Correct:+Injected dependency:+```phpclass OrderController extends Controller{- public function __construct(private OrderService $service) {}-- public function store(StoreOrderRequest $request)+ public function store(StoreOrderRequest $request, OrderService $service){- return $this->service->create($request->validated());+ return $service->create($request->validated());}}```-## Code to Interfaces+## Depend on Contracts at Boundaries++Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.-Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.+Concrete boundary dependency:-Incorrect (concrete dependency):```phpclass OrderService{@@ -61,7 +62,8 @@ class OrderService}```-Correct (interface dependency):+Contract boundary dependency:+```phpinterface PaymentGateway{@@ -80,86 +82,99 @@ Bind in a service provider:$this->app->bind(PaymentGateway::class, StripeGateway::class);```-## Default Sort by Descending+## Specify a Deterministic Sort Order-When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.+Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters.++Unspecified order:-Incorrect:```php$posts = Post::paginate();```-Correct:+Newest first with a stable tie-breaker:+```php-$posts = Post::latest()->paginate();+$posts = Post::query()+ ->orderByDesc('created_at')+ ->orderByDesc('id')+ ->paginate();```## Use Atomic Locks for Race Conditions-Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.+Use a lock when concurrent execution must be serialized. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems. Set the lease (`10` below) longer than the callback can ever run: once it expires, another process can acquire the lock while the first is still working.```phpCache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {$order->process();});-// Or at query level-$product = Product::where('id', $id)->lockForUpdate()->first();+// Or at query level, inside a transaction+DB::transaction(function () use ($id) {+ $product = Product::where('id', $id)->lockForUpdate()->first();++ // Read and update the product while the database lock is held.+});```## 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.+When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware.Incorrect:+```php-strlen('José'); // 5 (bytes, not characters)-strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte+strlen('José'); // 5 bytes, not 4 characters+strtolower('MÜNCHEN'); // Does not lowercase Ü```Correct:+```php-mb_strlen('José'); // 4 (characters)-mb_strtolower('MÜNCHEN'); // 'münchen'+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'+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.+For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after the response has been sent but remains in the same PHP process.++Queued and durable:-Incorrect (job overhead for trivial work):```phpdispatch(new LogPageView($page));```-Correct (runs after response, same process):+Deferred in the current process:+```phpdefer(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 a queued job when the work needs retries, queue controls, or durability across process failures.## Use `Context` for Request-Scoped Data-The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.+The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.```php// In middlewareContext::add('tenant_id', $request->header('X-Tenant-ID'));-// Anywhere later — controllers, jobs, log context+// Later in the same execution lifecycle$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`.+Visible context is added to log context, and both visible and hidden context are captured and restored for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless that propagation is intended.## Use `Concurrency::run()` for Parallel Execution-Run independent operations in parallel using child processes — no async libraries needed.+Run independent operations concurrently through Laravel's configured concurrency driver.```phpuse Illuminate\Support\Facades\Concurrency;@@ -170,13 +185,14 @@ use Illuminate\Support\Facades\Concurrency;]);```-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.+With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver executes closures sequentially and is useful primarily during testing.-## Convention Over Configuration+## Follow Framework Conventions-Follow Laravel conventions. Don't override defaults unnecessarily.+Follow Laravel conventions unless the domain or an existing schema requires an override.++Customized schema:-Incorrect:```phpclass Customer extends Model{@@ -190,7 +206,8 @@ class Customer extends Model}```-Correct:+Conventional schema:+```phpclass Customer extends Model{diff --git a/.cursor/skills/laravel-best-practices/rules/blade-views.md b/.cursor/skills/laravel-best-practices/rules/blade-views.mdindex 5f0b3a1e3..4ea2c6c34 100644--- a/.cursor/skills/laravel-best-practices/rules/blade-views.md+++ b/.cursor/skills/laravel-best-practices/rules/blade-views.md@@ -1,8 +1,8 @@-# Blade & Views Best Practices+# Blade and View Best Practices## Use `$attributes->merge()` in Component Templates-Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.+Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior.```blade<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>@@ -12,25 +12,25 @@ Hardcoding classes prevents consumers from adding their own. `merge()` combines## 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.+If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response.-## Prefer Blade Components Over `@include`+## Prefer Components for Explicit Interfaces-`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.+Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include remains suitable for a small partial that intentionally uses the current view data; pass an explicit data array when implicit variable sharing would obscure its dependencies.-## Use View Composers for Shared View Data+## Share Compatible View Data with a View Composer-If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.+Use a view composer to centralize data needed whenever one or more named Blade views are rendered. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view; it does not supply data to JSON, streamed, or other non-view responses.-## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)+## Return Blade Fragments for Partial Rendering-A single view can return either the full page or just a fragment, keeping routing clean.+A route can return either a full view or a named fragment for clients such as htmx or Turbo.```phpreturn view('dashboard', compact('users'))->fragmentIf($request->hasHeader('HX-Request'), 'user-list');```-## Use `@aware` for Deeply Nested Component Props+## Share Parent Component Props with `@aware`-Avoids re-passing parent props through every level of nested components.+Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. It does not expose an ancestor's default prop value unless that value was passed through the attribute bag.diff --git a/.cursor/skills/laravel-best-practices/rules/caching.md b/.cursor/skills/laravel-best-practices/rules/caching.mdindex 67408d6e1..cd2ffd602 100644--- a/.cursor/skills/laravel-best-practices/rules/caching.md+++ b/.cursor/skills/laravel-best-practices/rules/caching.md@@ -1,10 +1,13 @@# Caching Best Practices-## Use `Cache::remember()` Instead of Manual Get/Put+## Use `Cache::remember()` for Cache-Aside Reads-Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.+`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value; use an atomic lock when duplicate computation must be prevented.++The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses.Incorrect:+```php$val = Cache::get('stats');if (! $val) {@@ -14,27 +17,42 @@ if (! $val) {```Correct:+```php$val = Cache::remember('stats', 60, fn () => $this->computeStats());```-## Use `Cache::flexible()` for Stale-While-Revalidate+## Consider `Cache::flexible()` for Stale-While-Revalidate++For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response; it is not a durable background job. Once the stale period has elapsed, the request recomputes the value synchronously.++Synchronous expiration:++```php+Cache::remember('users', 300, fn () => User::all());+```-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.+Stale-while-revalidate tradeoff:-Incorrect: `Cache::remember('users', 300, fn () => User::all());`+```php+Cache::flexible('users', [300, 600], 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.+This value is fresh for five minutes and may be served stale until ten minutes after it was cached.-## Use `Cache::memo()` to Avoid Redundant Hits Within a Request+## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution-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.+If the same cache key is read repeatedly during one request or job, `memo()` decorates a cache store and retains resolved values in memory for that execution.-`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.+```php+$settings = Cache::memo()->get('settings');+```++Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate.## 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`.+Tags group related entries for invalidation without tracking each key. Cache tags are not supported by the `file`, `dynamodb`, or `database` drivers; confirm support before choosing a store.```phpCache::tags(['user-1'])->flush();@@ -42,15 +60,27 @@ 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.+`add()` atomically writes a value only when the key does not already exist.++Incorrect:-Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`+```php+if (! Cache::has('lock')) {+ Cache::put('lock', true, 10);+}+```++Correct:++```php+Cache::add('lock', true, 10);+```-Correct: `Cache::add('lock', true, 10);`+Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required.-## Use `once()` for Per-Request Memoization+## Use `once()` for In-Process 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.+`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store.```phppublic function roles(): Collection@@ -59,11 +89,11 @@ public function roles(): Collection}```-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.+Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions.## Configure Failover Cache Stores in Production-If Redis goes down, the app falls back to a secondary store automatically.+The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and data is not replicated between stores.```php'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],diff --git a/.cursor/skills/laravel-best-practices/rules/collections.md b/.cursor/skills/laravel-best-practices/rules/collections.mdindex 18e8d9e1d..211fec11d 100644--- a/.cursor/skills/laravel-best-practices/rules/collections.md+++ b/.cursor/skills/laravel-best-practices/rules/collections.md@@ -2,41 +2,69 @@## Use Higher-Order Messages for Simple Operations-Incorrect:+Explicit closure:+```php$users->each(function (User $user) {$user->markAsVip();});```-Correct: `$users->each->markAsVip();`+Concise equivalent:++```php+$users->each->markAsVip();+```++Higher-order messages are available for supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.-Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.+## Choose Between `cursor()` and `lazy()`-## Choose `cursor()` vs. `lazy()` Correctly+`cursor()` executes one query and hydrates models individually, but it cannot eager load relationships. The database driver's result buffering can still consume substantial memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.-- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).-- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.+`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration.++With relationships:++```php+User::with('roles')->lazy()->each(function (User $user) {+ // The roles for this chunk have been eager loaded.+});+```-Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.+Without relationships:-Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.+```php+User::cursor()->each(function (User $user) {+ // Process model attributes.+});+```## 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.+`lazy()` uses offset pagination, so updates to columns that affect the query can shift rows and cause records to be skipped or processed twice. `lazyById()` paginates by a monotonic key and is safer when updating other columns during iteration. Do not change the pagination key itself while iterating.## Use `toQuery()` for Bulk Operations on Collections-Avoids manual `whereIn` construction.+Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.++Manual query:++```php+User::whereIn('id', $users->modelKeys())->update(['active' => false]);+```++Collection query:-Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`+```php+$users->toQuery()->update(['active' => false]);+```-Correct: `$users->toQuery()->update([...]);`+`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when those events are not required.## Use `#[CollectedBy]` for Custom Collection Classes-More declarative than overriding `newCollection()`.+The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.```php#[CollectedBy(UserCollection::class)]diff --git a/.cursor/skills/laravel-best-practices/rules/config.md b/.cursor/skills/laravel-best-practices/rules/config.mdindex 9bea727b3..82691c42a 100644--- a/.cursor/skills/laravel-best-practices/rules/config.md+++ b/.cursor/skills/laravel-best-practices/rules/config.md@@ -1,73 +1,85 @@# Configuration Best Practices-## `env()` Only in Config Files+## Read Environment Variables in Configuration Files-Direct `env()` calls may return `null` when config is cached.+Call `env()` only from configuration files. After configuration is cached, Laravel does not load the application's `.env` file, so application code should read configuration values through `config()`.Incorrect:+```php$key = env('API_KEY');```Correct:+```php// config/services.php-'key' => env('API_KEY'),+return [+ 'key' => env('API_KEY'),+];// Application code$key = config('services.key');```-## Use Encrypted Env or External Secrets+## Protect Production Secrets-Never store production secrets in plain `.env` files in version control.+Do not commit plaintext production secrets. Laravel can encrypt an environment file so its encrypted form can be stored safely, while deployment platforms can supply secrets through their native secret stores.Incorrect:-```bash-# .env committed to repo or shared in Slack--STRIPE_SECRET=sk_live_abc123-AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI+```bash+# A plaintext .env file committed to the repository+STRIPE_SECRET=<your-stripe-secret>+AWS_SECRET_ACCESS_KEY=<your-aws-secret>```-Correct:+Encrypted environment file:+```bashphp artisan env:encrypt --env=production --readablephp artisan env:decrypt --env=production```-For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.+For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime.## Use `App::environment()` for Environment ChecksIncorrect:+```phpif (env('APP_ENV') === 'production') {+ // ...+}```Correct:+```phpif (app()->isProduction()) {-// or+ // ...+}+if (App::environment('production')) {+ // ...+}```-## Use Constants and Language Files+## Name Repeated Domain Values-Use class constants instead of hardcoded magic strings for model states, types, and statuses.+Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant.```php-// Incorrect+// Repeated literalreturn $this->type === 'normal';-// Correct+// Named domain valuereturn $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.+If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages.```php-// Only when lang files already exist in the project+// In a localized applicationreturn back()->with('message', __('app.article_added'));```diff --git a/.cursor/skills/laravel-best-practices/rules/db-performance.md b/.cursor/skills/laravel-best-practices/rules/db-performance.mdindex c49ba164e..3f339770d 100644--- a/.cursor/skills/laravel-best-practices/rules/db-performance.md+++ b/.cursor/skills/laravel-best-practices/rules/db-performance.md@@ -1,10 +1,11 @@# Database Performance Best Practices-## Always Eager Load Relationships+## Eager Load Relationships Before Iterating-Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.+When a relationship will be accessed for many models, eager load it with `with()` to avoid running one initial query plus one relationship query per model, commonly called an N+1 query pattern. Lazy loading is reasonable when the relationship may not be needed or only one model is involved.++Lazy-loaded version:-Incorrect (N+1 — executes 1 + N queries):```php$posts = Post::all();foreach ($posts as $post) {@@ -12,7 +13,8 @@ foreach ($posts as $post) {}```-Correct (2 queries total):+Eager-loaded version:+```php$posts = Post::with('author')->get();foreach ($posts as $post) {@@ -20,7 +22,7 @@ foreach ($posts as $post) {}```-Constrain eager loads to select only needed columns (always include the foreign key):+Constrain eager loads when large columns are unnecessary. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, while selecting `posts.id` preserves each related model's primary key:```php$users = User::with(['posts' => function ($query) {@@ -42,31 +44,34 @@ public function boot(): void}```-Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.+By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`.## Select Only Needed Columns-Avoid `SELECT *` — especially when tables have large text or JSON columns.+Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit.++All columns:-Incorrect:```php$posts = Post::with('author')->get();```-Correct:+Selected columns:+```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.+When limiting selected columns, retain every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key.++## Process Large Data Sets Incrementally-## Chunk Large Datasets+Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget.-Never load thousands of records at once. Use chunking for batch processing.+Loads the complete result set:-Incorrect:```php$users = User::all();foreach ($users as $user) {@@ -74,7 +79,8 @@ foreach ($users as $user) {}```-Correct:+Processes bounded chunks:+```phpUser::where('subscribed', true)->chunk(200, function ($users) {foreach ($users as $user) {@@ -83,7 +89,7 @@ User::where('subscribed', true)->chunk(200, function ($users) {});```-Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:+Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change:```phpUser::where('active', false)->chunkById(200, function ($users) {@@ -91,11 +97,14 @@ User::where('active', false)->chunkById(200, function ($users) {});```-## Add Database Indexes+For read-only, attribute-only iteration, `cursor()` hydrates models individually from one query, although some database drivers still buffer raw results. Use `lazy()` when relationships must be eager loaded in chunks, and use `lazyById()` or `chunkById()` when updates can affect query membership. See the collection rules for detailed tradeoffs.-Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.+## Add Indexes for Measured Query Patterns++Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index; selectivity, write cost, existing indexes, and the database query plan all matter.++Schema without an application-specific query index:-Incorrect:```phpSchema::create('orders', function (Blueprint $table) {$table->id();@@ -105,24 +114,26 @@ Schema::create('orders', function (Blueprint $table) {});```-Correct:+Schema optimized for `WHERE status = ? ORDER BY created_at`:+```phpSchema::create('orders', function (Blueprint $table) {$table->id();- $table->foreignId('user_id')->index()->constrained();- $table->string('status')->index();+ $table->foreignId('user_id')->constrained();+ $table->string('status');$table->timestamps();$table->index(['status', 'created_at']);});```-Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).+Confirm composite index column order and effectiveness with production-like data and the database's query-plan tools. Also check whether the database already created an index to support a foreign key before adding another one.++## Count Relationships Without Loading Them-## Use `withCount()` for Counting Relations+Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory.-Never load entire collections just to count them.+Loads related models:-Incorrect:```php$posts = Post::all();foreach ($posts as $post) {@@ -130,7 +141,8 @@ foreach ($posts as $post) {}```-Correct:+Selects relationship counts:+```php$posts = Post::withCount('comments')->get();foreach ($posts as $post) {@@ -149,39 +161,24 @@ $posts = Post::withCount([])->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);-}-```+## Keep Queries Out of Blade Templates-Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.+Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable.-## No Queries in Blade Templates+Query in the template:-Never execute queries in Blade templates. Pass data from controllers.--Incorrect:```blade@foreach (User::all() as $user){{ $user->profile->name }}@endforeach```-Correct:+Data prepared before rendering:+```php// Controller$users = User::with('profile')->get();+return view('users.index', compact('users'));```diff --git a/.cursor/skills/laravel-best-practices/rules/eloquent.md b/.cursor/skills/laravel-best-practices/rules/eloquent.mdindex bd2cfca08..5a89510d0 100644--- a/.cursor/skills/laravel-best-practices/rules/eloquent.md+++ b/.cursor/skills/laravel-best-practices/rules/eloquent.md@@ -1,8 +1,8 @@# Eloquent Best Practices-## Use Correct Relationship Types+## Define Precise Relationship Types-Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.+Define the relationship that matches the database association, and declare its concrete return type.```phppublic function comments(): HasMany@@ -20,7 +20,8 @@ public function author(): BelongsToExtract reusable query constraints into local scopes to avoid duplication.-Incorrect:+Duplicated constraints:+```php$active = User::where('verified', true)->whereNotNull('activated_at')->get();$articles = Article::whereHas('user', function ($q) {@@ -28,7 +29,8 @@ $articles = Article::whereHas('user', function ($q) {})->get();```-Correct:+Reusable local scope:+```php#[Scope]protected function active(Builder $query): Builder@@ -45,7 +47,8 @@ $articles = Article::whereHas('user', fn ($q) => $q->active())->get();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):+Global scope tradeoff:+```phpclass PublishedScope implements Scope{@@ -54,10 +57,12 @@ class PublishedScope implements Scope$builder->where('published', true);}}-// Now admin panels, reports, and background jobs all silently skip drafts++// Admin panels, reports, and jobs now omit drafts unless the scope is removed.```-Correct (local scope you opt into):+Explicit local scope:+```php#[Scope]protected function published(Builder $query): Builder@@ -84,16 +89,18 @@ protected function casts(): array}```-## Cast Date Columns Properly+## Cast Date and Time Attributes++Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps.-Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.+Manual parsing in the template:-Incorrect:```blade-{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}+{{ Carbon::parse($order->ordered_at)->toDateString() }}```-Correct:+Model cast:+```phpprotected function casts(): array{@@ -110,24 +117,27 @@ protected function casts(): array## Use `whereBelongsTo()` for Relationship Queries-Cleaner than manually specifying foreign keys.+`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key.++Foreign key constraint:-Incorrect:```phpPost::where('user_id', $user->id)->get();```-Correct:+Relationship-aware constraint:+```phpPost::whereBelongsTo($user)->get();Post::whereBelongsTo($user, 'author')->get();```-## Avoid Hardcoded Table Names in Queries+## Keep Application Queries Model-Aware-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).+Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL legitimately require table names, so use them when their lower-level behavior is intentional.++Lower-level alternatives:-Incorrect:```phpDB::table('users')->where('active', true)->get();@@ -136,15 +146,13 @@ $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();+Model-aware queries:-// Even better — use Eloquent or the query builder instead of raw SQL+```phpUser::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.+When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer; keep those references covered by tests when schema changes are possible.-**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.+In migrations, use explicit table names rather than application models. Migrations are historical snapshots, while models and their scopes can change after a migration is deployed.diff --git a/.cursor/skills/laravel-best-practices/rules/error-handling.md b/.cursor/skills/laravel-best-practices/rules/error-handling.mdindex 4b1486676..afcdf4ac5 100644--- a/.cursor/skills/laravel-best-practices/rules/error-handling.md+++ b/.cursor/skills/laravel-best-practices/rules/error-handling.md@@ -1,15 +1,18 @@# Error Handling Best Practices-## Exception Reporting and Rendering+## Choose Where to Report and Render Exceptions-There are two valid approaches — choose one and apply it consistently across the project.+Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project.-**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:+Exception methods keep behavior beside the exception definition:```phpclass InvalidOrderException extends Exception{- public function report(): void { /* custom reporting */ }+ public function report(): void+ {+ // Send the exception to a custom reporter.+ }public function render(Request $request): Response{@@ -18,38 +21,40 @@ class InvalidOrderException extends Exception}```-**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:+Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together:```php->withExceptions(function (Exceptions $exceptions) {- $exceptions->report(function (InvalidOrderException $e) { /* ... */ });+ $exceptions->report(function (InvalidOrderException $e) {+ // Send the exception to a custom reporter.+ });$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.+An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering.-## Use `ShouldntReport` for Exceptions That Should Never Log+## Mark Exceptions the Handler Should Not Report-More discoverable than listing classes in `dontReport()`.+Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly.```phpclass PodcastProcessingException extends Exception implements ShouldntReport {}```-## Throttle High-Volume Exceptions+## Throttle High-Volume Exception Reports-A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.+A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits.-## Enable `dontReportDuplicates()`+## Prevent Duplicate Reports of One Exception Instance-Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.+Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message.-## Force JSON Error Rendering for API Routes+## Define JSON Rendering for API Routes-Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.+Laravel normally uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes.```php$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {@@ -59,7 +64,7 @@ $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {## 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.+Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.```phpclass InvalidOrderException extends Exceptiondiff --git a/.cursor/skills/laravel-best-practices/rules/events-notifications.md b/.cursor/skills/laravel-best-practices/rules/events-notifications.mdindex 82e329e8f..a8cce31a8 100644--- a/.cursor/skills/laravel-best-practices/rules/events-notifications.md+++ b/.cursor/skills/laravel-best-practices/rules/events-notifications.md@@ -1,24 +1,24 @@-# Events & Notifications Best Practices+# Events and Notifications Best Practices## Rely on Event Discovery-Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.+Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer.-## Run `event:cache` in Production Deploy+## Cache Event Discovery During Production Deployment-Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.+Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.## Use `ShouldDispatchAfterCommit` Inside Transactions-Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.+When an event is dispatched inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. This affects synchronous and queued listeners; it is not limited to queue timing.```phpclass OrderShipped implements ShouldDispatchAfterCommit {}```-## Always Queue Notifications+## Queue Slow Notifications-Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.+Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation.```phpclass InvoicePaid extends Notification implements ShouldQueue@@ -27,9 +27,9 @@ class InvoicePaid extends Notification implements ShouldQueue}```-## Use `afterCommit()` on Notifications in Transactions+## Dispatch Queued Notifications After Commit-Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.+A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. This setting has no scheduling effect on a synchronous notification.```php$user->notify((new InvoicePaid($invoice))->afterCommit());@@ -37,7 +37,7 @@ $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.+Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues.## Use On-Demand Notifications for Non-User Recipients@@ -49,4 +49,4 @@ Notification::route('mail', '[email protected]')->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.+Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification.diff --git a/.cursor/skills/laravel-best-practices/rules/http-client.md b/.cursor/skills/laravel-best-practices/rules/http-client.mdindex 8e2f16e8a..cc8fdd6ab 100644--- a/.cursor/skills/laravel-best-practices/rules/http-client.md+++ b/.cursor/skills/laravel-best-practices/rules/http-client.md@@ -1,86 +1,100 @@# HTTP Client Best Practices-## Always Set Explicit Timeouts+## Set Explicit Timeouts-The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.+Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Remember that retries can multiply the total elapsed time.++Less resilient:-Incorrect:```php$response = Http::get('https://api.example.com/users');```-Correct:+Preferred:+```php-$response = Http::timeout(5)- ->connectTimeout(3)+$response = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users');```-For service-specific clients, define timeouts in a macro:+Define shared settings in a macro or a dedicated client:```phpHttp::macro('github', function () {return Http::baseUrl('https://api.github.com')- ->timeout(10)->connectTimeout(3)+ ->timeout(10)->withToken(config('services.github.token'));});$response = Http::github()->get('/repos/laravel/framework');```-## Use Retry with Backoff for External APIs+## Retry Only Safe Operations-External APIs have transient failures. Use `retry()` with increasing delays.+Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection.-Incorrect:-```php-$response = Http::post('https://api.stripe.com/v1/charges', $data);+Unsafe without an idempotency guarantee:-if ($response->failed()) {- throw new PaymentFailedException('Charge failed');-}+```php+$response = Http::retry([100, 500, 1000])+ ->post('https://api.example.com/v1/charges', $data);```-Correct:+Safe for an idempotent request:+```php-$response = Http::retry([100, 500, 1000])+$response = Http::connectTimeout(3)->timeout(10)- ->post('https://api.stripe.com/v1/charges', $data);+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->get('https://api.example.com/data');```-Only retry on specific errors:+For a supported state-changing API, send a stable idempotency key for every attempt:```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');+$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])+ ->connectTimeout(3)+ ->timeout(10)+ ->retry([100, 500, 1000], 0, function (Throwable $exception) {+ return $exception instanceof ConnectionException+ || ($exception instanceof RequestException+ && ($exception->response->serverError() || $exception->response->status() === 429));+ })+ ->post('https://api.example.com/v1/charges', $data);```## Handle Errors Explicitly-The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.+The HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing by default. Inspect the expected statuses or call `throw()` before consuming a success payload.++Unsafe when a success payload is expected:-Incorrect:```php-$response = Http::get('https://api.example.com/users/1');-$user = $response->json(); // Could be an error body+$user = Http::get('https://api.example.com/users/1')->json();```-Correct:+Preferred:+```php-$response = Http::timeout(5)+$user = Http::connectTimeout(3)+ ->timeout(5)->get('https://api.example.com/users/1')- ->throw();--$user = $response->json();+ ->throw()+ ->json();```-For graceful degradation:+Handle expected alternatives explicitly when graceful degradation is required:```php-$response = Http::get('https://api.example.com/users/1');+$response = Http::connectTimeout(3)+ ->timeout(5)+ ->get('https://api.example.com/users/1');if ($response->successful()) {return $response->json();@@ -93,46 +107,30 @@ if ($response->notFound()) {$response->throw();```-## Use Request Pooling for Concurrent Requests+## Pool Independent Requests-When making multiple independent API calls, use `Http::pool()` instead of sequential calls.+Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling; inspect or throw for each response as needed.-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:```phpuse 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'),+ $pool->as('users')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/users'),+ $pool->as('posts')->connectTimeout(3)->timeout(5)+ ->get('https://api.example.com/posts'),]);-$users = $responses['users']->json();-$posts = $responses['posts']->json();+$users = $responses['users']->throw()->json();+$posts = $responses['posts']->throw()->json();```-## Fake HTTP Calls in Tests--Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.+## Fake HTTP Requests in Tests-Incorrect:-```php-it('syncs user from API', function () {- $service = new UserSyncService;- $service->sync(1); // Hits the real API-});-```+Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles.-Correct:```php-it('syncs user from API', function () {+it('syncs a user from the API', function () {Http::preventStrayRequests();Http::fake([@@ -142,16 +140,15 @@ it('syncs user from API', function () {]),]);- $service = new UserSyncService;- $service->sync(1);+ (new UserSyncService)->sync(1);- Http::assertSent(function (Request $request) {- return $request->url() === 'https://api.example.com/users/1';- });+ Http::assertSent(fn (Request $request) =>+ $request->url() === 'https://api.example.com/users/1'+ );});```-Test failure scenarios too:+For example, fake a connection failure when testing the integration's failure path:```phpHttp::fake([diff --git a/.cursor/skills/laravel-best-practices/rules/mail.md b/.cursor/skills/laravel-best-practices/rules/mail.mdindex 7c717336d..f6310437c 100644--- a/.cursor/skills/laravel-best-practices/rules/mail.md+++ b/.cursor/skills/laravel-best-practices/rules/mail.md@@ -1,27 +1,54 @@# Mail Best Practices-## Implement `ShouldQueue` on the Mailable Class+## Queue Slow Mail Delivery-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.+Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`.-## Use `afterCommit()` on Mailables Inside Transactions+```php+class OrderShipped extends Mailable implements ShouldQueue+{+ use Queueable, SerializesModels;+}+```-A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.+Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.-## Use `assertQueued()` Not `assertSent()` for Queued Mailables+## Dispatch Queued Mail After Commit-`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.+A queued mailable dispatched during a database transaction can be processed before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records.-Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.+```php+Mail::to($user)->send(+ (new OrderShipped($order))->afterCommit()+);+```-Correct: `Mail::assertQueued(OrderShipped::class);`+If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery.-## Use Markdown Mailables for Transactional Emails+## Assert the Delivery Mode-Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.+Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.-## Separate Content Tests from Sending Tests+Incorrect for a mailable that implements `ShouldQueue`:-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.+```php+Mail::assertSent(OrderShipped::class);+```++Correct:++```php+Mail::assertQueued(OrderShipped::class);+```++## Use Markdown Mailables When They Fit++Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They are useful for conventional transactional messages, but a custom HTML and text pair may be more appropriate for a specialized design.++```bash+php artisan make:mail OrderShipped --markdown=mail.orders.shipped+```++## Separate Content and Delivery Tests++Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior.diff --git a/.cursor/skills/laravel-best-practices/rules/migrations.md b/.cursor/skills/laravel-best-practices/rules/migrations.mdindex df6f5f33c..3345402eb 100644--- a/.cursor/skills/laravel-best-practices/rules/migrations.md+++ b/.cursor/skills/laravel-best-practices/rules/migrations.md@@ -2,76 +2,51 @@## Generate Migrations with Artisan-Always use `php artisan make:migration` for consistent naming and timestamps.+Use `php artisan make:migration` to generate the timestamped filename and migration structure.-Incorrect (manually created file):-```php-// database/migrations/posts_migration.php ← wrong naming, no timestamp-```--Correct (Artisan-generated):```bashphp artisan make:migration create_posts_tablephp artisan make:migration add_slug_to_posts_table```-## Use `constrained()` for Foreign Keys+## Define Foreign-Key Constraints Deliberately-Automatic naming and referential integrity.+Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.```php$table->foreignId('user_id')->constrained()->cascadeOnDelete();--// Non-standard names$table->foreignId('author_id')->constrained('users');```-## Never Modify Deployed Migrations+Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration.-Once a migration has run in production, treat it as immutable. Create a new migration to change the table.+## Treat Deployed Migrations as Immutable-Incorrect (editing a deployed migration):-```php-// 2024_01_01_create_posts_table.php — already in production-$table->string('slug')->unique(); // ← added after deployment-```+After a migration has run in a shared or production environment, create a new migration for subsequent changes. Editing the old file makes fresh installations differ from upgraded installations.-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');-});-```+For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.-## Add Indexes in the Migration+## Design Indexes for Real Queries-Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.+Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column appearing in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index.-Incorrect:-```php-Schema::create('orders', function (Blueprint $table) {- $table->id();- $table->foreignId('user_id')->constrained();- $table->string('status');- $table->timestamps();-});-```+Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan, and avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance.++## Stage Changes That Affect Existing Rows++Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid.++Do not assume this migration is safe on a populated table:-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();-});+$table->string('slug')->unique();```-## Mirror Defaults in Model `$attributes`+Large backfills are usually better implemented as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when their locking, transaction, and deployment behavior is understood.-When a column has a database default, mirror it in the model so new instances have correct values before saving.+## Mirror Defaults Only When Unsaved Models Need Them++A database default is applied when a row is inserted, not when a model is instantiated. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions synchronized.```php// Migration@@ -83,39 +58,10 @@ protected $attributes = [];```-## 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');- });-}-```+## Make Rollbacks Honest-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.+Implement `down()` when the change can be safely reversed. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible; document that limitation and prefer a forward-fix migration in production.## 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']);-```+Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when doing so reduces locks and supports phased deployment, but do not split related operations merely to enforce a blanket separation between data definition and data manipulation.diff --git a/.cursor/skills/laravel-best-practices/rules/queue-jobs.md b/.cursor/skills/laravel-best-practices/rules/queue-jobs.mdindex c41915e2b..011828a6c 100644--- a/.cursor/skills/laravel-best-practices/rules/queue-jobs.md+++ b/.cursor/skills/laravel-best-practices/rules/queue-jobs.md@@ -1,82 +1,82 @@-# Queue & Job Best Practices+# Queue and Job Best Practices-## Set `retry_after` Greater Than `timeout`+## Keep Reservation Time Longer Than Execution Time-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.+For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`.-Incorrect (`retry_after` ≤ `timeout`):```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}+// Job+public $timeout = 120;-// config/queue.php — retry_after: 90 ← job retried while still running!+// config/queue.php for the connection+'retry_after' => 150,```-Correct (`retry_after` > `timeout`):-```php-class ProcessReport implements ShouldQueue-{- public $timeout = 120;-}--// config/queue.php — retry_after: 180 ← safely longer than any job timeout-```+Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`; configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings.-## Use Exponential Backoff+## Back Off Transient Failures-Use progressively longer delays between retries to avoid hammering failing services.+Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.-Incorrect (fixed retry interval):```phpclass SyncWithStripe implements ShouldQueue{- public $tries = 3;- // Default: retries immediately, overwhelming the API-}-```+ public $tries = 4;-Correct (exponential backoff):-```php-class SyncWithStripe implements ShouldQueue-{- public $tries = 3;public $backoff = [1, 5, 10];}```-## Implement `ShouldBeUnique`+Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window.++## Use Unique Jobs for Dispatch Deduplication-Prevent duplicate job processing.+Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock and is not a substitute for idempotent processing or a database constraint.```phpclass GenerateInvoice implements ShouldQueue, ShouldBeUnique{+ public $uniqueFor = 3600;+public function uniqueId(): string{- return $this->order->id;+ return (string) $this->order->id;}+}+```- public $uniqueFor = 3600;+All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.++Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running:++```php+class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing+{+ // ...}```-## Always Implement `failed()`+## Handle Terminal Failure When Needed++Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting.-Handle errors explicitly — don't rely on silent failure.+Laravel invokes `failed()` on a new job instance, so mutations made to the job during `handle()` are not available there.```phppublic function failed(?Throwable $exception): void{$this->podcast->update(['status' => 'failed']);- Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);++ Log::error('Podcast processing failed', [+ 'podcast_id' => $this->podcast->id,+ 'exception' => $exception,+ ]);}```-## Rate Limit External API Calls in Jobs+## Rate Limit External Calls-Use `RateLimited` middleware to throttle jobs calling third-party APIs.+Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together.```phppublic function middleware(): array@@ -85,60 +85,33 @@ public function middleware(): array}```-## Batch Related Jobs+## Batch Jobs for Group Coordination-Use `Bus::batch()` when jobs should succeed or fail together.+Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction: completed jobs are not rolled back when another job fails. By default, one failed job cancels the batch; call `allowFailures()` only when partial failure is acceptable.```phpBus::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();+ ->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))+ ->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [+ 'exception' => $exception,+ ]))+ ->dispatch();```-## `retryUntil()` Needs `$tries = 0`+## Configure Time-Based Retry Limits Deliberately-When using time-based retry limits, set `$tries = 0` to avoid premature failure.+Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. The method takes precedence over attempt-based limits, so setting `$tries = 0` is not required.```php-public $tries = 0;--public function retryUntil(): \DateTimeInterface+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.+## Use Horizon for Redis Queue Operations-```php-// config/horizon.php-'environments' => [- 'production' => [- 'supervisor-1' => [- 'connection' => 'redis',- 'queue' => ['high', 'default', 'low'],- 'balance' => 'auto',- 'minProcesses' => 1,- 'maxProcesses' => 10,- 'tries' => 3,- ],- ],-],-```+Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.diff --git a/.cursor/skills/laravel-best-practices/rules/routing.md b/.cursor/skills/laravel-best-practices/rules/routing.mdindex b6e30864f..604a8d96d 100644--- a/.cursor/skills/laravel-best-practices/rules/routing.md+++ b/.cursor/skills/laravel-best-practices/rules/routing.md@@ -1,99 +1,106 @@-# Routing & Controllers Best Practices+# Routing and Controller Best Practices## Use Implicit Route Model Binding-Let Laravel resolve models automatically from route parameters.+Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.++Instead of manual lookup:-Incorrect:```php-public function show(int $id)+public function show(int $id): View{$post = Post::findOrFail($id);++ return view('posts.show', ['post' => $post]);}```-Correct:+Use route model binding:+```php-public function show(Post $post)+public function show(Post $post): View{return view('posts.show', ['post' => $post]);}```-## Use Scoped Bindings for Nested Resources+## Scope Nested Bindings-Enforce parent-child relationships automatically.+Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization.```phpRoute::get('/users/{user}/posts/{post}', function (User $user, Post $post) {- // $post is automatically scoped to $user+ // The resolved post belongs to the resolved user.})->scopeBindings();```-## Use Resource Controllers+## Use Resource Routes for Resourceful Actions-Use `Route::resource()` or `apiResource()` for RESTful endpoints.+Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary.```phpRoute::resource('posts', PostController::class);-// In routes/api.php — the /api prefix is applied automatically-Route::apiResource('posts', Api\PostController::class);++// Alternatively, for an API-only resource:+Route::apiResource('posts', ApiPostController::class);```-## Keep Controllers Thin+`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not itself add an `/api` prefix; that prefix comes from the application's API route configuration.++## Organize Controllers Around Resources++As a general default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This keeps routes predictable and prevents controllers from accumulating unrelated behavior.-Aim for under 10 lines per method. Extract business logic to action or service classes.+When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary.++Custom action on the primary controller:-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);-}+Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']);```-Correct:+The published podcast modeled as a resource:+```php-public function store(StorePostRequest $request, CreatePostAction $create)-{- $post = $create->execute($request->validated());+Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store'])+ ->name('published-podcasts.store');- return redirect()->route('posts.show', $post);-}+Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy'])+ ->name('published-podcasts.destroy');```-## 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+class PublishedPodcastController extends Controller{- $validated = $request->validate([- 'title' => ['required', 'max:255'],- 'body' => ['required'],- ]);+ public function store(Podcast $podcast): RedirectResponse+ {+ $podcast->publish();++ return back();+ }- Post::create($validated);+ public function destroy(Podcast $podcast): RedirectResponse+ {+ $podcast->unpublish();- return redirect()->route('posts.index');+ return back();+ }}```-Correct:+Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions.++## Keep Controllers Focused on HTTP Concerns++Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service merely to satisfy an arbitrary line limit.+```php-public function store(StorePostRequest $request): RedirectResponse+public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse{- Post::create($request->validated());+ $post = $create->handle($request->validated());- return redirect()->route('posts.index');+ return redirect()->route('posts.show', $post);}```++A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity; see the validation rules for detailed guidance.diff --git a/.cursor/skills/laravel-best-practices/rules/scheduling.md b/.cursor/skills/laravel-best-practices/rules/scheduling.mdindex a98479450..4c25134a9 100644--- a/.cursor/skills/laravel-best-practices/rules/scheduling.md+++ b/.cursor/skills/laravel-best-practices/rules/scheduling.md@@ -1,32 +1,50 @@# Task Scheduling Best Practices-## Use `withoutOverlapping()` on Variable-Duration Tasks+## Prevent Unwanted Overlap-Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.+Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. This is appropriate for variable-duration tasks that are not safe to run concurrently.-## Use `onOneServer()` on Multi-Server Deployments+```php+Schedule::command('reports:generate')+ ->everyFifteenMinutes()+ ->withoutOverlapping(30);+```++The optional value is the lock expiration time in minutes, not the task timeout. Choose it carefully: the default is 24 hours, stale locks can be cleared with `php artisan schedule:clear-cache`, and an expiration that is too short can permit overlap while the first task still runs. The task itself should still tolerate retries and partial execution where practical.-Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).+## Run a Task on One Server-## Use `runInBackground()` for Concurrent Long Tasks+Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`.++```php+Schedule::command('billing:charge')->daily()->onOneServer();+```-By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.+Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity.-## Use `environments()` to Restrict Tasks+## Run Eligible Commands in the Background-Prevent accidental execution of production-only tasks (billing, reporting) on staging.+Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.```php-Schedule::command('billing:charge')->monthly()->environments(['production']);+Schedule::command('analytics:process')->hourly()->runInBackground();```-## Use `takeUntilTimeout()` for Time-Bounded Processing+Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`; it is not available for scheduled closures. Ensure background processes have appropriate logging and failure monitoring.-A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.+## Restrict Tasks by Environment-## Use Schedule Groups for Shared Configuration+Use `environments()` when a task should run only in named application environments. Treat this as an operational safeguard, not an authorization control.-Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.+```php+Schedule::command('billing:charge')+ ->monthly()+ ->environments(['production']);+```++## Group Shared Configuration++Use schedule groups when several tasks genuinely share frequency or constraints.```phpSchedule::daily()@@ -37,3 +55,7 @@ Schedule::daily()Schedule::command('emails:prune');});```++## Bound Work Inside the Task++The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required.diff --git a/.cursor/skills/laravel-best-practices/rules/security.md b/.cursor/skills/laravel-best-practices/rules/security.mdindex 2d7200c29..57b57f0fa 100644--- a/.cursor/skills/laravel-best-practices/rules/security.md+++ b/.cursor/skills/laravel-best-practices/rules/security.md@@ -1,18 +1,9 @@# Security Best Practices-## Mass Assignment Protection+## Control Mass Assignment-Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).+Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default; `$guarded = []` opts out of that protection.-Incorrect:-```php-class User extends Model-{- protected $guarded = []; // All fields are mass assignable-}-```--Correct:```phpclass User extends Model{@@ -24,82 +15,71 @@ class User extends Model}```-Never use `$guarded = []` on models that accept user input.--## Authorize Every Action+Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set; it does not validate values or authorize the operation.-Use policies or gates in controllers. Never skip authorization.+## Authorize Protected Actions-Incorrect:-```php-public function update(UpdatePostRequest $request, Post $post)-{- $post->update($request->validated());-}-```+Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.-Correct:```php-public function update(UpdatePostRequest $request, Post $post)+public function update(UpdatePostRequest $request, Post $post): RedirectResponse{Gate::authorize('update', $post);$post->update($request->validated());++ return redirect()->route('posts.show', $post);}```-Or via Form Request:+Authorization may instead live in the form request:```phppublic function authorize(): bool{- return $this->user()->can('update', $this->route('post'));+ return $this->user()?->can('update', $this->route('post')) ?? false;}```-## Prevent SQL Injection+Public actions intentionally available to everyone do not need a redundant authorization check.++## Bind Query Parameters-Always use parameter binding. Never interpolate user input into queries.+Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions; map user-selected identifiers to an allow-list.Incorrect:+```phpDB::select("SELECT * FROM users WHERE name = '{$request->name}'");```Correct:+```phpUser::where('name', $request->name)->get();--// Raw expressions with bindings-User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();+User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();```-## Escape Output to Prevent XSS+## Escape Output in Its Context-Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.+Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content that has been sanitized for the exact HTML context in which it is rendered. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.++Incorrect for untrusted content:-Incorrect:```blade{!! $user->bio !!}```Correct:+```blade{{ $user->bio }}```-## CSRF Protection--Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.+## Apply Cross-Site Request Forgery Protection-Incorrect:-```blade-<form method="POST" action="/posts">- <input type="text" name="title">-</form>-```+Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.-Correct:```blade<form method="POST" action="/posts">@csrf@@ -107,21 +87,27 @@ Correct:</form>```-## Rate Limit Auth and API Routes+Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Confirm equivalent configuration when using another HTTP client. Do not disable CSRF protection merely to fix a token mismatch.-Apply `throttle` middleware to authentication and API routes.+## Rate Limit Sensitive Endpoints++Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately; an Internet Protocol (IP) address alone can unfairly group users behind a shared network, while an account identifier alone can enable targeted denial of service.```phpRateLimiter::for('login', function (Request $request) {- return Limit::perMinute(5)->by($request->ip());+ return Limit::perMinute(5)->by(Str::transliterate(+ Str::lower($request->string('email')).'|'.$request->ip()+ ));});Route::post('/login', LoginController::class)->middleware('throttle:login');```-## Validate File Uploads+Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection.++## Validate and Store Uploads Safely-Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.+Validate expected content type, dimensions where relevant, and size. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions; it does not validate the user-assigned filename extension. The `extensions` rule checks that extension and should not be used by itself.```phppublic function rules(): array@@ -132,56 +118,28 @@ public function rules(): array}```-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.+Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.-Incorrect:```php-$key = env('API_KEY');+$path = $request->file('avatar')->store('avatars');```-Correct:-```php-// config/services.php-'api_key' => env('API_KEY'),+## Keep Secrets Out of Application Code-// In application code-$key = config('services.api_key');-```+Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works correctly. See the configuration rules for encrypted environment files and external secret stores.## Audit Dependencies-Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.+Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.```bashcomposer audit```-## Encrypt Sensitive Database Fields--Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.+## Encrypt Sensitive Attributes When Appropriate-Incorrect:-```php-class Integration extends Model-{- protected function casts(): array- {- return [- 'api_key' => 'string',- ];- }-}-```+Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. Encrypted values cannot be meaningfully queried and should use a `TEXT` or larger column because ciphertext length is variable.-Correct:```phpclass Integration extends Model{diff --git a/.cursor/skills/laravel-best-practices/rules/style.md b/.cursor/skills/laravel-best-practices/rules/style.mdindex a8afb3695..3f3f14fbc 100644--- a/.cursor/skills/laravel-best-practices/rules/style.md+++ b/.cursor/skills/laravel-best-practices/rules/style.md@@ -1,125 +1,110 @@-# 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 |-|---------|---------|+# Convention and Style Best Practices++## Follow Project Naming Conventions++Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.++| Element | Convention | Example |+| --- | --- | --- |+| Controller | Singular resource name | `ArticleController` |+| Model | Singular StudlyCase | `User` |+| Table | Plural snake_case | `article_comments` |+| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` |+| Column | snake_case | `meta_title` |+| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |+| Resource URI | Plural resource | `articles/1` |+| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` |+| Method | camelCase | `getAll` |+| Variable | camelCase | `$articlesWithAuthor` |+| Collection | Descriptive and plural | `$activeUsers` |+| Object | Descriptive and singular | `$activeUser` |+| View | kebab-case | `show-filtered.blade.php` |+| Configuration file | snake_case | `google_calendar.php` |+| Enumeration | Singular StudlyCase | `UserType` |++## Prefer Clear, Idiomatic Syntax++Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.++| More verbose | Idiomatic alternative |+| --- | --- || `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')` |+| `->first()?->name` | `->value('name')` when only that value is needed |-## Use Laravel String & Array Helpers+Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.-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.+## Use Utilities When They Clarify Intent-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);+Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as an unconditional replacement for every built-in function.-// Correct+```php$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+$class = class_basename(User::class);$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()`.+Use `Arr` for dot notation and common transformations:-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');+$public = Arr::only($attributes, ['name', 'email']);```-Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.+Use `Number` for localized display formatting rather than values that will be stored or calculated:-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%"+Number::format(1000000);+Number::currency(1500, 'USD');+Number::fileSize(1024 * 1024);```-URIs — use `Uri` for URL manipulation:+Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API:+```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.+Check the documentation for the Laravel version supported by the project before using newer utility classes or methods.-Use `search-docs` for the full list of available methods — these helpers are extensive.+## Keep Presentation Code Maintainable-## No Inline JS/CSS in Blade+Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks; avoid mixing large behavior and style blocks into templates.-Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.+Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript:-Incorrect:```blade-let article = `{{ json_encode($article) }}`;+<script>+ const article = {{ Js::from($article) }};+</script>```-Correct:-```blade-<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>-```+Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.-Pass data to JS via data attributes or use a dedicated PHP-to-JS package.+## Write Comments That Explain Why-## No Unnecessary Comments+Prefer clear names and small units of code over comments that merely restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.-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.+Unhelpful:-Incorrect:```php-// Check if there are any joins-if (count((array) $builder->getQuery()->joins) > 0)+// Check whether the query has joins.+if (count((array) $builder->getQuery()->joins) > 0) {+ // ...+}```-Correct:+Clearer:+```php-if ($this->hasJoins())+if ($this->hasJoins()) {+ // ...+}```diff --git a/.cursor/skills/laravel-best-practices/rules/testing.md b/.cursor/skills/laravel-best-practices/rules/testing.mddeleted file mode 100644index 4fbf12f8a..000000000--- a/.cursor/skills/laravel-best-practices/rules/testing.md+++ /dev/null@@ -1,43 +0,0 @@-# 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/.cursor/skills/laravel-best-practices/rules/validation.md b/.cursor/skills/laravel-best-practices/rules/validation.mdindex 5fde1064a..37ce6c5e2 100644--- a/.cursor/skills/laravel-best-practices/rules/validation.md+++ b/.cursor/skills/laravel-best-practices/rules/validation.md@@ -1,75 +1,89 @@-# Validation & Forms Best Practices+# Validation and Forms Best Practices-## Use Form Request Classes+## Extract Validation When It Improves the Boundary-Extract validation from controllers into dedicated Form Request classes.+Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set.-Incorrect:```php-public function store(Request $request)+public function store(StorePostRequest $request): RedirectResponse{- $request->validate([- 'title' => 'required|max:255',- 'body' => 'required',- ]);-}-```+ $post = Post::create($request->validated());-Correct:-```php-public function store(StorePostRequest $request)-{- Post::create($request->validated());+ return redirect()->route('posts.show', $post);}```-## Array vs. String Notation for Rules+A form request's `authorize()` method can enforce access to the operation. Validation establishes the shape and values of input; it does not itself authorize the user.-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.+## Prefer Readable Rule Syntax++Array syntax composes cleanly with rule objects and avoids delimiter issues. Prefer it in new code when it improves readability, while following a consistent local style.```php-// Preferred for new code'email' => ['required', 'email', Rule::unique('users')],+```-// Follow existing convention if the project uses string notation+String syntax remains valid for simple rules:++```php'email' => 'required|email|unique:users',```-## Always Use `validated()`+## Use Only Intended Validated Data-Get only validated data. Never use `$request->all()` for mass operations.+Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. Then select the fields intended for the operation when the validation rules also cover control fields or nested data.++Unsafe:-Incorrect:```phpPost::create($request->all());```-Correct:+Preferred:+```php-Post::create($request->validated());+$post = Post::create($request->safe()->only(['title', 'body']));```-## Use `Rule::when()` for Conditional Validation+Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation merely to make mass assignment convenient.++## Express Conditional Rules Clearly++Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test.```php'company_name' => [- Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),+ 'string',+ 'max:255',+ Rule::when(+ $this->input('account_type') === 'business',+ ['required'],+ ['nullable'],+ ),],```-## Use the `after()` Method for Custom Validation+## Add Cross-Field Validation After Base Rules-Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.+Use a form request's `after()` method for validation that depends on multiple fields or application state. Avoid expensive queries when prerequisite fields have already failed validation.```phppublic function after(): array{return [function (Validator $validator) {- if ($this->quantity > Product::find($this->product_id)?->stock) {+ if ($validator->errors()->hasAny(['product_id', 'quantity'])) {+ return;+ }++ $stock = Product::find($this->integer('product_id'))?->stock;++ if ($stock !== null && $this->integer('quantity') > $stock) {$validator->errors()->add('quantity', 'Not enough stock.');}},];}```++Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate.diff --git a/.cursor/skills/mcp-development/SKILL.md b/.cursor/skills/mcp-development/SKILL.mdindex 4ef1bb9a6..ca63d9fb2 100644--- a/.cursor/skills/mcp-development/SKILL.md+++ b/.cursor/skills/mcp-development/SKILL.md@@ -22,22 +22,17 @@ Register MCP servers in `routes/ai.php`:```phpuse Laravel\Mcp\Facades\Mcp;-Mcp::web();+Mcp::web('/mcp/demo', \App\Mcp\Servers\AppServer::class);```### Creating MCP Primitives```bashphp artisan make:mcp-tool ToolName # Create a tool-php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)-```After creating primitives, register them in your server's `$tools`, `$resources`, or `$prompts` properties.diff --git a/.cursor/skills/mcp-development/references/app.md b/.cursor/skills/mcp-development/references/app.mdindex db2e752a3..93042c3f9 100644--- a/.cursor/skills/mcp-development/references/app.md+++ b/.cursor/skills/mcp-development/references/app.md@@ -27,7 +27,14 @@ class DashboardApp extends AppResourcecreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -104,7 +111,7 @@ MCP Apps add interactive UI to the Model Context Protocol. The server returns se└─────────────────────────────────────────────┘```-The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.+The server automatically advertises `capabilities.extensions["io.modelcontextprotocol/ui"]` on `server/discover` when any `AppResource` is registered. Add cases of the `Extension` enum to the server's `$extensions` property to declare any other extension. The client declares its own support in the `io.modelcontextprotocol/clientCapabilities` member of each request's `_meta`.---@@ -307,7 +314,14 @@ Renders a complete self-contained HTML document with the MCP SDK inlined. `creatcreateMcpApp(async (app) => {document.getElementById('run-btn').addEventListener('click', async () => {const result = await app.callServerTool({ name: 'tool-name', arguments: {} });- document.getElementById('output').textContent = result.content[0]?.text ?? '';+ const output = document.getElementById('output');++ if (result.isError) {+ output.textContent = `Error: ${result.content[0]?.text ?? 'Unknown error'}`;+ return;+ }++ output.textContent = result.content[0]?.text ?? '';});});</script>@@ -703,9 +717,19 @@ class GetMonitorData extends Tool```jscreateMcpApp(async (app) => {async function poll() {- const result = await app.callServerTool('get-monitor-data');- const data = JSON.parse(result.content[0]?.text ?? '{}');- document.getElementById('cpu').textContent = data.cpu;+ try {+ const result = await app.callServerTool('get-monitor-data');++ if (result.isError) {+ document.getElementById('cpu').textContent = result.content[0]?.text ?? 'Unavailable';+ return;+ }++ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ } catch {+ // transport failure or malformed payload, retry on next tick+ }}setInterval(poll, 2000);@@ -776,6 +800,11 @@ In the client, convert the base64 blob to a data URI for rendering:```jsconst result = await app.callServerTool('get-image', { id: 42 });++if (result.isError) {+ return;+}+const blob = result.content[0];img.src = `data:${blob.mimeType};base64,${blob.data}`;```@@ -798,8 +827,17 @@ createMcpApp(async (app) => {});app.onToolResult((params) => {- const data = JSON.parse(params.result.content[0]?.text ?? "{}");- renderResults(data);+ if (params.result.isError) {+ document.getElementById("error").textContent =+ params.result.content[0]?.text ?? "Unknown error";+ return;+ }++ try {+ renderResults(JSON.parse(params.result.content[0]?.text ?? "{}"));+ } catch {+ document.getElementById("error").textContent = "Malformed tool result";+ }});});```diff --git a/.cursor/skills/passport-development/SKILL.md b/.cursor/skills/passport-development/SKILL.mdindex e5dce352f..6a083d9c0 100644--- a/.cursor/skills/passport-development/SKILL.md+++ b/.cursor/skills/passport-development/SKILL.md@@ -95,15 +95,10 @@ Create clients with the appropriate flag for the grant type:```bashphp artisan passport:client # Authorization code-php artisan passport:client --public # PKCE (no secret)-php artisan passport:client --client # Client credentials-php artisan passport:client --personal # Personal access tokens-php artisan passport:client --device # Device authorization-```Additional flags: `--name=`, `--redirect_uri=`, `--provider=`.@@ -182,11 +177,8 @@ Passport::actingAsClient($client, ['scope1']);```bashphp artisan passport:purge # Purge revoked & expired-php artisan passport:purge --revoked # Only revoked-php artisan passport:purge --expired # Only expired-```Schedule `passport:purge` for regular expired token clean-up.diff --git a/.cursor/skills/pest-testing/SKILL.md b/.cursor/skills/pest-testing/SKILL.mddeleted file mode 100644index 79cd0bcce..000000000--- a/.cursor/skills/pest-testing/SKILL.md+++ /dev/null@@ -1,203 +0,0 @@-----name: pest-testing-description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."-license: MIT-metadata:- author: laravel------# Pest Testing 5--## Documentation--Use `search-docs` for detailed Pest 5 patterns and documentation.--## Basic Usage--### Creating Tests--All tests must be written using Pest. Use `php artisan make:test --pest {name}`.--The `{name}` argument should include only the path and test name, but should not include the test suite.-- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`-- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`-- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`-- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`--### Test Organization--- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.-- Browser tests: `tests/Browser/` directory.-- Do NOT remove tests without approval - these are core application code.--### Basic Test Structure--Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.--<!-- Basic Pest Test Example -->-```php-it('is true', function () {- expect(true)->toBeTrue();-});-```--### Running Tests--- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.-- Run all tests: `php artisan test --compact`.-- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.-- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.--## Assertions--Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:--<!-- Pest Response Assertion -->-```php-it('returns all', function () {- $this->postJson('/api/docs', [])->assertSuccessful();-});-```--| Use | Instead of |-|-----|------------|-| `assertSuccessful()` | `assertStatus(200)` |-| `assertNotFound()` | `assertStatus(404)` |-| `assertForbidden()` | `assertStatus(403)` |--## Mocking--Import mock function before use: `use function Pest\Laravel\mock;`--## Datasets--Use datasets for repetitive tests (validation rules, etc.):--<!-- Pest Dataset Example -->-```php-it('has emails', function (string $email) {- expect($email)->not->toBeEmpty();-})->with([- 'james' => '[email protected]',- 'taylor' => '[email protected]',-]);-```--## Pest 5 Features--| Feature | Purpose |-|---------|---------|-| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |-| Time-Balanced Sharding | Split tests across CI shards by execution time |-| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |-| Browser Testing | Full integration tests in real browsers |-| Smoke Testing | Validate multiple pages quickly |-| Visual Regression | Compare screenshots for visual changes |-| Architecture Testing | Enforce code conventions |--### Tia (Test Impact Analysis)--Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:--<!-- Tia Example -->-```shell-./vendor/bin/pest --parallel --tia-```--- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.-- Detects Laravel, Symfony, Livewire, and Inertia automatically.--### New Validation Expectations--Pest 5 ships eight new validation matchers, all supporting `.not` negation:--<!-- Pest 5 Validation Expectations -->-```php-expect('[email protected]')->toBeEmail();-expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();-expect('192.168.1.1')->toBeIpAddress();-expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();-expect('example.com')->toBeHostname();-expect('example.co.uk')->toBeDomain();-expect('Zm9vYmFy')->toBeBase64();-expect('deadbeef')->toBeHexadecimal();-```--### Time-Balanced Sharding--Distribute tests across CI shards by execution time rather than count:--<!-- Pest Sharding Example -->-```shell-./vendor/bin/pest --update-shards-./vendor/bin/pest --shard=1/4-```--Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.--### Browser Test Example--Browser tests run in real browsers for full integration testing:--- Browser tests live in `tests/Browser/`.-- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.-- Use `RefreshDatabase` for clean state per test.-- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.-- Test on multiple browsers (Chrome, Firefox, Safari) if requested.-- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.-- Switch color schemes (light/dark mode) when appropriate.-- Take screenshots or pause tests for debugging.--<!-- Pest Browser Test Example -->-```php-it('may reset the password', function () {- Notification::fake();-- $this->actingAs(User::factory()->create());-- $page = visit('/sign-in');-- $page->assertSee('Sign In')- ->assertNoJavaScriptErrors()- ->click('Forgot Password?')- ->fill('email', '[email protected]')- ->click('Send Reset Link')- ->assertSee('We have emailed your password reset link!');-- Notification::assertSent(ResetPassword::class);-});-```--### Smoke Testing--Quickly validate multiple pages have no JavaScript errors:--<!-- Pest Smoke Testing Example -->-```php-$pages = visit(['/', '/about', '/contact']);--$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();-```--### Visual Regression Testing--Capture and compare screenshots to detect visual changes.--### Architecture Testing--<!-- Architecture Test Example -->-```php-arch('controllers')- ->expect('App\Http\Controllers')- ->toExtendNothing()- ->toHaveSuffix('Controller');-```--## Common Pitfalls--- Not importing `use function Pest\Laravel\mock;` before using mock-- Using `assertStatus(200)` instead of `assertSuccessful()`-- Forgetting datasets for repetitive validation tests-- Deleting tests without approval-- Forgetting `assertNoJavaScriptErrors()` in browser tests-- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`diff --git a/.cursor/skills/tailwindcss-development/SKILL.md b/.cursor/skills/tailwindcss-development/SKILL.mdindex c0cb2fbcd..98f9f1712 100644--- a/.cursor/skills/tailwindcss-development/SKILL.md+++ b/.cursor/skills/tailwindcss-development/SKILL.md@@ -48,16 +48,16 @@ In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead o### Replaced Utilities-Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.+Tailwind v4 removed deprecated utilities. Use the replacements shown below. For opacity, drop the `*-opacity-*` class and append the value as a modifier on the existing color: `bg-blue-500 bg-opacity-50` becomes `bg-blue-500/50`, `text-white text-opacity-75` becomes `text-white/75`.| 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/* |+| bg-opacity-* | bg-{color}/* |+| text-opacity-* | text-{color}/* |+| border-opacity-* | border-{color}/* |+| divide-opacity-* | divide-{color}/* |+| ring-opacity-* | ring-{color}/* |+| placeholder-opacity-* | placeholder-{color}/* || flex-shrink-* | shrink-* || flex-grow-* | grow-* || overflow-ellipsis | text-ellipsis |@@ -87,29 +87,6 @@ If existing pages and components support dark mode, new pages and components mus</div>```-## Common Patterns--### Flexbox Layout--<!-- Flexbox Layout -->-```html-<div class="flex items-center justify-between gap-4">- <div>Left content</div>- <div>Right content</div>-</div>-```--### Grid Layout--<!-- Grid Layout -->-```html-<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">- <div>Card 1</div>- <div>Card 2</div>- <div>Card 3</div>-</div>-```-## Common Pitfalls- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)diff --git a/.cursor/skills/testing-best-practices/SKILL.md b/.cursor/skills/testing-best-practices/SKILL.mdnew file mode 100644index 000000000..9b0aa7f91--- /dev/null+++ b/.cursor/skills/testing-best-practices/SKILL.md@@ -0,0 +1,58 @@+---+name: testing-best-practices+description: "Laravel test design and review. Use when selecting coverage, naming or structuring tests, choosing assertions or test data, isolating dependencies, testing HTTP or security boundaries, improving suite performance, or reviewing test value. Use framework guidance or search-docs for Pest and PHPUnit syntax."+license: MIT+metadata:+ author: laravel+---++# Testing Best Practices++This skill provides rules for designing Laravel tests. Each rule file explains what to do and why. Use `search-docs` for Laravel and Pest API syntax.+This project uses Pest. Follow the corresponding guidance in each rule.++## Consistency First++Read nearby tests before you choose syntax and organization.++A pattern repeated throughout the project is a convention, and project conventions take precedence over this skill. Follow them and give new tests the same structure.++These rules govern the tests you write now. An existing test that follows a project convention is not defective merely because it conflicts with this skill. Do not delete or rewrite it. If the convention has drawbacks, explain them and let the user decide.++## What to Test++Read this section before you write a test.++- Test observable behavior and application contracts. A test must pass after an implementation change if the behavior stays the same.+- Cover every changed decision and each applicable high-value failure mode. A decision is a branch, a validation, a calculation, or an authorization.+- Exercise declarations through behavior instead of repeating their text.+- Leave framework behavior to framework tests. Testing project configuration is not testing the framework. A constrained relationship, cast, scope, or validation rule belongs to this project.+- Keep every test that can detect a distinct defect. When two tests detect the same defect, trim the higher-layer test to one case and report the duplication. Do not delete an existing test.+- Write a feature test first. Write a unit test only for logic that does not use the framework.+- Write a browser test only for behavior in JavaScript that a feature test cannot reach. Put a browser test in `tests/Browser`, and call `assertNoJavaScriptErrors()` in it.+- Judge an architecture test by the convention it protects, not by the rules above. An `arch()` test declares a rule for an entire directory, such as the parent class of every model, the classes that may use an enum, or the methods every factory declares. It intentionally checks declarations and fails when a new file breaks the convention.+- Use the test tools that the project installs. Add a new test dependency, plugin, or browser only after the user asks for it.++## How to Apply++1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.+2. Select every applicable branch in the rule index. Read every selected rule file.+3. Report each defect in the code before you write a test. Examples are a method with no body, a policy that no action calls, and a write action with no validation. Test the actual behavior. Report the defect to the user.+4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.+5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.++## Rule Index++Most changes need more than one rule file.++| Subject | Rule File |+| --- | --- |+| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |+| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |+| Arrange-act-assert and choosing the correct assertion | [`rules/assertions.md`](rules/assertions.md) |+| Endpoint coverage, authentication, authorization, tenant isolation, validation, and browser tests | [`rules/endpoint-tests.md`](rules/endpoint-tests.md) |+| Factories, test data ownership, and repeated input values | [`rules/test-data.md`](rules/test-data.md) |+| Fakes, mocks, outbound HTTP, time, randomness, and databases | [`rules/isolation.md`](rules/isolation.md) |+| Escaping, injection, cross-tenant access, and privilege checks | [`rules/security.md`](rules/security.md) |+| Environment and CI settings for a slow suite | [`rules/performance.md`](rules/performance.md) |+| Reviewing a test or suite | [`rules/review.md`](rules/review.md) |diff --git a/.cursor/skills/testing-best-practices/rules/assertions.md b/.cursor/skills/testing-best-practices/rules/assertions.mdnew file mode 100644index 000000000..528bdd4b0--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/assertions.md@@ -0,0 +1,64 @@+# Assertions++## Arrange, Act, Assert++Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.++Keep each test self-contained. Do not use values created by another test.++## How to Find the Correct Assertion++First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.++1. Search Laravel's assertions for framework subjects such as responses, the database, sessions, models, queues, events, mail, and notifications.+2. Fetch `https://pestphp.com/docs/expectations.md` for the expectations of Pest for a plain value, a type, a format, or a shape.+3. Build the check by hand only if no assertion exists for the subject.+4. Confirm the name in the documentation before you use it. Do not write an assertion that you did not confirm.++Use the assertion in this table for each subject.++| Subject | Assertion to use |+| --- | --- |+| A return value, the state of an object, or a transformation of a value | an `expect()` chain |+| An HTTP status, JSON, a session, or Inertia | a Laravel response assertion |+| The state in the database | a Laravel database assertion |+| The existence of a model | `assertModelExists($model)` rather than `assertDatabaseHas('users', ['id' => $user->id])` |++Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exists for the subject.++Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.++## Named Response Assertions++Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.++Keep one `expect()` chain on one subject. Start a new chain when the subject changes, or when the chain is difficult to read.++## Format Expectations++Use Pest's format expectations rather than regular expressions because they provide clearer failure messages. Pest covers email addresses, URLs, UUIDs, IP addresses, and other common formats, and each expectation supports `not` for the negative case.++## Assert a Known Value++Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.++```php+// The test calculates the value with the logic of the implementation...+$expected = now()->subHours(24)->floorSeconds(30)->toJson();+expect($from)->toBe($expected);++// The test sets a fixed input and asserts a known value...+travelTo('2025-01-01 00:00:00');+expect($from)->toBe('2024-12-31T00:00:00.000000Z');+```++## Assert the Complete Result++A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:++- The response or the return value.+- The state in the database.+- The jobs and the events that the operation dispatches.+- The notifications and the mail that the operation sends.++On the failure path, assert that the operation makes none of these changes. A test that asserts only `assertOk()` passes even when the application saves no record.diff --git a/.cursor/skills/testing-best-practices/rules/endpoint-tests.md b/.cursor/skills/testing-best-practices/rules/endpoint-tests.mdnew file mode 100644index 000000000..e3fc18b75--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/endpoint-tests.md@@ -0,0 +1,73 @@+# Endpoint Tests++## How to Write the Test++Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.++Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.++## Endpoint Coverage++Write a test for each applicable case:++- The request has missing or invalid authentication.+- The request comes from a different tenant, team, or organization.+- The user has an insufficient role or permission.+- The request does not satisfy a route or scope constraint.+- The request fails the validation.+- The request is valid. Assert both the response and the persisted state.++Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.++## Tenant Isolation++Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.++## Test Authorization at the Policy Level++An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.++- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.+- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.+- Use the helper of the project that asserts the ability and the arguments of the gate, if such a helper exists.++## Browser Tests++Write a browser test only for JavaScript behavior that an HTTP test cannot reach, such as modal interaction, drag-and-drop, live search, or client-side validation. Browser tests are slower than HTTP tests and can fail for reasons unrelated to the code under test.++- Assert the state that the user can see, and assert the state in the database that the interaction saves.+- Wait until the test reaches the required state. Do not wait for a fixed number of seconds, which can fail on a slower machine.+- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.++### Where a Browser Test Lives and How to Run It++The plugin runs browser tests as normal Pest tests, so they need no separate suite. Put them in `tests/Browser` to separate them from faster tests and run the directory with one command.++- Run a browser test with `vendor/bin/pest tests/Browser`, and add `--parallel` for the complete suite.+- Run `vendor/bin/pest --debug` to open the window of the browser and to pause at a failure. Use `--headed` to watch a run that passes.+- Add `--browser firefox` or `--browser safari` to run the test in a different browser. The default browser is Chrome.+- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.+- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.++### Browser Test Pitfalls++- The plugin waits five seconds for an element. Raise the value with `pest()->browser()->timeout(10000)` in `Pest.php` for a page that is slower, and do not add a wait for a number of seconds to the test.+- Apply `RefreshDatabase` to the browser tests in `Pest.php`. A browser test hits the application through a real request, and the records that it leaves break the next test.+- Add `tests/Browser/Screenshots` to `.gitignore`. A failure writes a screenshot, and the file is not part of the repository.+- Give `withKeyDown()` a key code, such as `KeyA`. A letter such as `'a'` gives the lowercase character, whatever modifier the test holds.+- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.++## Testing Validation++- Write one test for each validation rule when each failure represents a separate contract.+- Write one test with an empty payload to assert several required fields together.+- Assert the text of the message that the user gets. A message that is present but wrong is a defect.+- Use a dataset for input values that need the same setup and the same assertions.++Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.++### Which Layer Owns Which Case++The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.++When both tests contain the matrix, move it to the rule-class test and retain one case in the endpoint test. Never remove the last case, because the rule-class test still passes if the request omits the rule. The same division applies to policies, scopes, and other classes called by a request.diff --git a/.cursor/skills/testing-best-practices/rules/finding-features.md b/.cursor/skills/testing-best-practices/rules/finding-features.mdnew file mode 100644index 000000000..fc16c39bd--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/finding-features.md@@ -0,0 +1,37 @@+# How to Find Test Framework Features++Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.++- Give `search-docs` the capability you need rather than the name of a function you remember. It returns features available in the installed version.+- Fetch `https://pestphp.com/llms.txt` for the complete feature list and additions in each release.+- If a search returns no results, tell the user that the installed version does not provide the feature. Do not write an API that you have not confirmed.++Search for a feature in this table before you write the code by hand.++| Work that you need | Term to search for |+| --- | --- |+| Run one test with many input values | datasets, bound datasets |+| Assert over many values or over a collection | higher-order expectations |+| Remove the same setup from each test in a file | hooks, higher-order tests |+| Apply a convention to the complete codebase | architecture testing |+| Measure if the suite finds a defect | mutation testing |+| Find code with no types | type coverage |+| Reduce the time of a slow suite | parallel, profiling |+| Split the suite across CI jobs | sharding, `--update-shards` |+| Run only the tests that a change affects | Test Impact Analysis, `--tia` |+| Assert that a value has a known format | validation expectations |+| Run one test while you debug | filtering, `--bail`, `--dirty` |++## Built-in Laravel Assertion Methods++Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before building a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.++A hand-built check fails with `false is not true`, which identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure indicates what to fix.++```php+// The failure says that false is not true. Instead of this...+expect(User::where('email', '[email protected]')->exists())->toBeTrue();++// Use this... the failure names the table and the attributes that it did not find...+$this->assertDatabaseHas('users', ['email' => '[email protected]']);+```diff --git a/.cursor/skills/testing-best-practices/rules/isolation.md b/.cursor/skills/testing-best-practices/rules/isolation.mdnew file mode 100644index 000000000..e1a21fdb4--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/isolation.md@@ -0,0 +1,52 @@+# Fakes, Mocks, and Determinism++Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.++## How to Isolate a Dependency++Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.++Identify the dependency, then choose the first applicable option. A framework fake preserves the real code path, while a mock replaces the dependency.++1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.+2. Use a developer-defined fake implementation of a service if the application provides one.+3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.+4. Use the real implementation for everything else, including the database.++## Framework Fakes++- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.+- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.+- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.+- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.+- Assert the data of a job or of an event if that data is part of the behavior.+- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.++Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID, and a fake without class names suppresses those events and can produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.++## Mocking++Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. Use `Mockery::on()` or `withArgs()` if an equality check cannot state the expected argument, such as a check of one field of a value object.++Import the mock function before you use it: `use function Pest\Laravel\mock;`.++## Outbound HTTP Testing++Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.++Fake the exact endpoint used by each test. Do not call `Http::fake()` without an endpoint because it accepts unexpected requests and can hide defects.++## Time and Randomness++- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.+- Use the framework helpers `freezeTime()`, `travelTo()`, `travel()`, and `travelBack()`. Do not call `Carbon::setTestNow()`.+- Use `Str::createRandomStringsUsing()` to fix a generated string, if the test asserts an identifier or a slug.+- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.+- Restore the time and the randomness after each test, if the suite does not restore them for every test.++## Database++- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.+- Assert the exact keys of `toArray()` if the shape of the serialized model is a contract. The test then fails when the model exposes a new attribute.+- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.+- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.diff --git a/.cursor/skills/testing-best-practices/rules/naming.md b/.cursor/skills/testing-best-practices/rules/naming.mdnew file mode 100644index 000000000..4f3f5b1d1--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/naming.md@@ -0,0 +1,45 @@+# Naming and Structure++## File Layout++- Name each test file `{ClassName}Test.php`.+- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.+- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.+- Move large literal values out of the test body and into fixture files.++## Test Function++Use the test function used by other files in the same directory. If no neighboring test files exist:++- Use `it()` for the behavior of the code, and write the name as a verb phrase.+- Use `test()` for a declarative fact, such as a grant in a policy, the labels of an enum, or the shape of a serialized model.++Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.++## Naming Tests++The name of a test is a specification. State the user-visible result and the condition that causes it.++- Name the behavior, and not the method under test. The file name already gives the class.+- Give the exact status code in the name of a test for an API error.+- Do not write `Given`, `When`, or `Then` in the name.++```php+it('returns 401 when no token is provided', function () { ... });+it('does not include deployments from deleted environments', function () { ... });+it('falls back to the default region when none is configured', function () { ... });+```++Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.++Do not write `it('works correctly')` or `it('returns data')`, because neither specifies a meaningful result. Do not write `it('handleMethod creates record')`, because it names a method rather than behavior.++## Grouping++Use `describe()` if one file covers separate actions in a lifecycle. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.++Do not use `describe()` in these cases:++- The file covers one action or one flow.+- The tests are different only in the input value. Use a dataset instead.+- The group adds a level but does not make the file easier to read.diff --git a/.cursor/skills/testing-best-practices/rules/performance.md b/.cursor/skills/testing-best-practices/rules/performance.mdnew file mode 100644index 000000000..f1d9c9b35--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/performance.md@@ -0,0 +1,58 @@+# Test Suite Performance++These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.++Fetch `https://pestphp.com/docs/optimizing-tests` for Pest options that make test runs faster.+Verify each flag in the documentation before adding it to CI.++Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.++## Test Environment++- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.+- Disable XDebug. Disable pcov also, unless the run needs the coverage.+- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.+- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.+- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.++## Global Fakes++Put these three calls in the base `Pest.php` of the project:++- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. This catches requests made through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.+- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.+- `Exceptions::fake()`, so the suite does not report an exception to an external service.++## How to Run the Suite in Parallel++Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. Add `--processes=N` if the default count is unsuitable for the machine or CI.++A parallel run gives each process a separate database. Tests must meet these conditions; a test that fails only in parallel breaks one of them:++- The test creates each record that it reads. It does not read a record that another test creates.+- The test does not depend on the order of the run.+- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.++## How to Run Fewer Tests++Run `vendor/bin/pest --parallel --tia` to run only the tests that the recent changes affect. Pest replays the cached result of each other test.++Pest replays cached results rather than skipping unaffected tests. The cache includes each produced value and the covered lines and branches. Pest finds affected Laravel, Symfony, Livewire, and Inertia tests without configuration.++## How to Split Tests Across CI++Run `vendor/bin/pest --update-shards` to measure the time of each test. Run `vendor/bin/pest --shard=1/4` in each CI job, and change the first number for each job.++Commit `tests/.pest/shards.json` so each CI job gets the same shard and the shards remain balanced by runtime rather than test count.++## How to Find a Slow Test++Run `vendor/bin/pest --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.++If the cause of a slow test is unclear, add an event listener or temporary log entry to identify its work.++## Common Errors++- The run loads XDebug for a test that does not need it.+- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.+- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.diff --git a/.cursor/skills/testing-best-practices/rules/review.md b/.cursor/skills/testing-best-practices/rules/review.mdnew file mode 100644index 000000000..e0cfca147--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/review.md@@ -0,0 +1,44 @@+# Reviewing Tests++Check every item in this file. A passing test may still provide no value. For each test, identify the defect it would catch.++Report each finding. Do not delete or rewrite a test without the user's approval. When an issue appears throughout the suite as a convention, report the pattern once rather than every affected file.++## Test Value++Apply this section to behavioral tests. An architecture test states a convention for a directory, so these items do not apply to it.++- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.+- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.+- [ ] Each test detects a distinct defect that no other test covers. A duplicate shrinks at the higher layer to the one case that proves the wiring.+- [ ] Every changed decision and each applicable high-value failure mode has coverage.++## Names and Structure++- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.+- [ ] Each name states a result, the condition that causes it, and the status code for an API error.+- [ ] Each file uses one declaration style consistently, and each `describe()` group holds separate behavior.++## Coverage++- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.+- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.+- [ ] The complete permission matrix belongs in policy tests, not controller tests.+- [ ] Each validation rule has one test that asserts the user-visible message. When a unit test owns a matrix, reduce duplicate higher-level coverage to one case rather than deleting it.+- [ ] Rendered user input and each dynamic part of a query have a security test.++## Data and Determinism++- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.+- [ ] Each `beforeEach()` holds configuration only.+- [ ] Each factory state and each relationship gives the meaning of the data.+- [ ] Each call to `make()` is in a test that does not need the database.+- [ ] Time, randomness, sleep, and outbound HTTP are controlled.+- [ ] Each test passes alone, and passes in the complete suite in any order.++## Assertions++- [ ] Each expected value is a known value, and the test does not calculate the value with the logic of the implementation.+- [ ] Each test of a write operation asserts the response, the state in the database, and the side effects.+- [ ] Each fake has one assertion, and gives the class names unless the test asserts the complete result.+- [ ] Each `expect()` chain stays on one subject.diff --git a/.cursor/skills/testing-best-practices/rules/security.md b/.cursor/skills/testing-best-practices/rules/security.mdnew file mode 100644index 000000000..234f5b005--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/security.md@@ -0,0 +1,27 @@+# Security Tests++Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary can be difficult to detect because the feature may continue to work.++Write a test for each of these cases:++- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for why the response should possibly be `404` rather than `403`.+- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.+- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners may decode it.+- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.+- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.++```php+it('escapes dangerous content in the notification', function () {+ $organization = Organization::factory()->make([+ 'name' => "O'Reilly <script>alert('xss')</script>",+ ]);++ $content = (new QuotaApproaching($organization, 80))->toMail()->render();++ expect($content)+ ->toContain('<script>')+ ->not->toContain("<script>alert('xss')</script>");+});+```++Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the appropriate defense to each attribute, route, and template.diff --git a/.cursor/skills/testing-best-practices/rules/test-data.md b/.cursor/skills/testing-best-practices/rules/test-data.mdnew file mode 100644index 000000000..65124683b--- /dev/null+++ b/.cursor/skills/testing-best-practices/rules/test-data.md@@ -0,0 +1,56 @@+# Factories and Test Data++## Each Test Makes Its Own Data++Create mutable records inside the test that uses them. This keeps setup visible and lets each test select its factory state.++Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.++## Record Construction++- Use `create()` if the test needs the record in the database.+- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.+- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning; `create(['email_verified_at' => null])` gives only its value.+- Use `for()` or the relationship helper of the project to declare the owner of a record.+- Use `recycle()` if several records must share one parent record.+- Use `sequence()` if several records need different attributes.++```php+$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();++$environment = Environment::factory()->recycle($organization)->create();++$organizations = Organization::factory()+ ->count(3)+ ->sequence(+ ['created_at' => now()->setSeconds(30)],+ ['created_at' => now()->setSeconds(1)],+ )+ ->create();+```++Create only the records required to arrange the behavior or support an assertion.++## Datasets++Use a dataset when the setup, test body, and assertions remain the same across input values.++```php+it('forbids roles other than admin', function (Role $role) {+ actingAs(User::factory()->hasOrganization($role)->create())+ ->post('/settings')+ ->assertForbidden();+})->with(collect(Role::cases())->reject(fn (Role $role) => $role === Role::ADMIN));+```++Use parameterized tests for:++- enum cases+- roles and plans+- boundary values+- input values that are invalid in the same way+- input and output value pairs++Write separate tests if the cases need a different setup, a different behavior, or different assertions. One test function with a branch in the body is two tests in one function.++Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.diff --git a/.cursor/skills/wayfinder-development/SKILL.md b/.cursor/skills/wayfinder-development/SKILL.mdindex a13cfc3b4..e80d131c0 100644--- a/.cursor/skills/wayfinder-development/SKILL.md+++ b/.cursor/skills/wayfinder-development/SKILL.md@@ -17,10 +17,13 @@ Use `search-docs` for detailed Wayfinder patterns and documentation.### Generate RoutesRun after route changes if Vite plugin isn't installed:+```bashphp artisan wayfinder:generate --no-interaction```+For form helpers, use `--with-form` flag:+```bashphp artisan wayfinder:generate --with-form --no-interaction```@@ -56,7 +59,7 @@ destroy.delete(1)store.form() // { action: "/posts", method: "post" }// Query parameters...-show(1, { query: { page: 1 } }) // "/posts/1?page=1"+show(1, { query: { page: 1 } }) // { url: "/posts/1?page=1", method: "get" }```## Wayfinder + Inertiadiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex c34d9515b..429320771 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -178,7 +178,9 @@ jobs:uses: actions/upload-artifact@v7with:name: playwright-artifacts-${{ matrix.shard }}- path: tests/Browser/Screenshots+ path: |+ tests/Browser/Screenshots+ tests/Browser/Tracesif-no-files-found: ignoreretention-days: 7diff --git a/.gitignore b/.gitignoreindex 01ee02451..0280b51bb 100644--- a/.gitignore+++ b/.gitignore@@ -2,6 +2,7 @@/bootstrap/ssr/node_modules/tests/Browser/Screenshots+/tests/Browser/Traces/public/build/lang/php_*.json/public/hotdiff --git a/AGENTS.md b/AGENTS.mdindex d7df3c329..a72fd20d5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -3,11 +3,9 @@# Laravel Boost Guidelines-The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.-## Foundational Context-This application is a Laravel application running on PHP 8.5. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version.+This application is a Laravel application running on PHP 8.5. Always use the APIs that match the installed major version of each package — do not assume a version.Before relying on a package's API, confirm its installed version:- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.@@ -34,16 +32,12 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac## Frontend Bundling-- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.+- If a frontend change doesn't show in the UI or you get a "Unable to locate file in Vite manifest" error, run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.## Documentation Files- You must only create documentation files if explicitly requested by the user.-## Replies--- Be concise in your explanations - focus on what's important rather than explaining obvious details.-=== boost rules ===# Laravel Boost@@ -58,7 +52,7 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac## Searching Documentation (IMPORTANT)-- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically.+- Use `search-docs` before changes that depend on Laravel ecosystem APIs, behavior, configuration, or version-specific syntax. Skip it for copy-only edits and other changes where package documentation is irrelevant. Reuse sufficient results already in context instead of searching again.- Pass a `packages` array to scope results when you know which packages are relevant.- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.@@ -72,8 +66,7 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac## Project Rules-- This project keeps committed, area-grouped rules in `.ai/rules` (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule.-- Record durable rules with `record-rule` so the next agent or teammate inherits them instead of working them out again. Pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Always use `record-rule`, never your native memory or notes tool — native memory is personal and session-scoped; only `.ai/rules` is shared with the team and persists in the repo.+- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists, including path-scoped framework guidelines under `.ai/rules/boost`. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule. If `.ai/rules` does not exist, continue without it.## Artisan@@ -115,8 +108,11 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac# Test Enforcement-- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.-- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter.+- Add or update tests for behavior and logic changes when a test provides meaningful regression coverage.+- Pure copy, styling, and layout-only changes do not require new or updated tests.+- When test coverage applies, run the affected tests and ensure they pass.+- Test the changed behavior and its important failure modes, but do not add tests beyond them.+- Read the `testing-best-practices` skill before writing tests.=== inertia-laravel/core rules ===@@ -167,10 +163,6 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.-## Vite Error--- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.-=== wayfinder/core rules ===# Laravel Wayfinder@@ -186,12 +178,19 @@ Use Wayfinder to generate TypeScript functions for Laravel routes. Import from `=== pest/core rules ===-## Pest+# Pest-- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.-- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`.-- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.-- Do NOT delete tests without approval.+- This project uses Pest. Create tests with `php artisan make:test --pest {name}`.+- Do not include the test suite directory in `{name}`. Use `SomeFeatureTest`, not `Feature/SomeFeatureTest`.+- Read the `testing-best-practices` skill for guidance on coverage, naming, structure, dependency isolation, and review.+- Do not delete tests or test files without approval. They are part of the application.++## Running Tests++- Run the narrowest set of tests that covers the change. Pass a file path or `--filter=testName` to `php artisan test --compact`.+- Rerun a test after each change to it.+- Run `vendor/bin/pest` to call the test runner directly. It accepts the same file path and `--filter=testName` arguments.+- After the feature tests pass, ask the user to run the complete suite with `php artisan test --compact`.=== inertia-vue/core rules ===@@ -216,6 +215,7 @@ Vue components must have a single root element.- Every change to the guard ships with a browser test in `tests/Browser/ComposerUnsavedChangesTest.php` that fails without it, checked by removing the change and running the test. History bugs here showed up only in a real browser (Inertia's own popstate handler is part of every flow).- **Composables are scoped by area.** A composable used by one area only lives in that area's folder, `resources/js/composables/<area>/` (e.g. `composables/composer/useComposerUnsavedChanges.ts`, `composables/echo/usePostEcho.ts`). Only composables shared across areas stay at the root of `resources/js/composables/`. When a scoped composable gains a consumer in another area, move it to the root in the same change.- Searching a list in the UI goes through `matchesSearch` / `filterBySearch` (`resources/js/lib/search.ts`): word by word, ignoring case and accents. Never hand-roll `.toLowerCase().includes(...)` for a search box.+- **A translated sentence with markup (bold, italic, a link) goes through `TransSlots`** (`resources/js/components/TransSlots.vue`, owner decision October 2026), our take on vue-i18n's `<i18n-t>` component interpolation for laravel-vue-i18n's `:placeholder` syntax. The lang string holds plain text and `:placeholders` only, in all 16 locales; each placeholder is filled by a named slot, so the markup lives in the template and every value is escaped by Vue: `<TransSlots :message="$t('calendar.reschedule.custom_time.description')"><template #from><strong>{{ fromTime }}</strong></template></TransSlots>`. Never put HTML in a lang string rendered with `v-html`, never escape replacement values by hand, and never split one sentence across several keys to style part of it. The `v-html` translations that predate this rule (`LegalLinks`, `BlueskyConnect`) move to `TransSlots` when touched.## Inertia SSR@@ -847,6 +847,7 @@ view turns a forgotten variable into a runtime-only failure.- ALWAYS use Wayfinder-generated route helpers in Vue pages (e.g. `register()`, `login()`, `dashboard()`). NEVER hardcode URL strings like `href="/register"`.- After creating or modifying PHP routes/controllers, run `php artisan wayfinder:generate` to regenerate the TypeScript route helpers.- Import routes from `@/routes/...` (e.g. `import { store } from '@/routes/login'`).+- On the backend, every URL of the app comes from Laravel's helpers (owner decision October 2026): `route()` / `redirect()->route()` for pages, `Illuminate\Support\Uri` to read or change a query. Never `url('/...')`, `redirect('/...')`, a path or query string built by hand, or `parse_url()` on our own URLs. A page rebuilt from the Referer goes through the route it matches (`RendersPublishPage::previousUrl()`), so it can never point at another host.## Pagination@@ -1149,6 +1150,16 @@ Browser tests live in `tests/Browser` and run on `pestphp/pest-plugin-browser` d- A new test for a fix must fail without the fix. Check it by removing the change, running the test, and restoring it.- CI runs them in three shards, each in parallel with three processes (`./vendor/bin/pest tests/Browser --compact --parallel --processes=3 --shard=N/3`), leaving a CPU of the 4-vCPU runner to the database and the app server, against `npm run build` output, so keep them independent of a running dev server and of each other. Run them in parallel through `./vendor/bin/pest`, never `php artisan test --parallel`, which does not start the Playwright server. A test that only passes alone has a race: wait for the state you assert (poll the DOM or the database) instead of assuming timing.+## Laravel helpers over native PHP++Whenever Laravel has a helper for something, use it instead of a native PHP function or a hand-written equivalent (owner decision October 2026). The helper already handles the edge cases (encoding, base paths, nulls, empty strings) that a hand-written version gets wrong.++- **URLs and routes:** `route()`, `redirect()->route()`, `url()->previous()`, `Illuminate\Support\Uri` and `Request`. Never `parse_url()`, `http_build_query()`, `explode('&', ...)` or string concatenation to build or read a URL of the app (see "Routing (Wayfinder)").+- **Values:** `blank()`, `filled()`, `transform()`, `data_get()` / `data_set()`, `Arr::*` and collections, instead of `=== null` / `empty()` / `isset()` checks and `array_*` loops.+- **Dates:** `now()`, Carbon and `CarbonImmutable`, never `time()`, `date()` or `strtotime()`.+- **Strings are not a parser.** `Str` is for text (slugs, case, limits). Taking a URL, path or query apart with `Str::after`, `Str::before` or `Str::startsWith` is the same hand-written parsing in another form: reach for the helper that understands the structure (`Uri`, `Request`, `route()`) instead.+- A native function is fine when Laravel has no equivalent; say so in the code review, not in a comment.+## Array Data Access- In Action classes and similar service classes, ALWAYS use Laravel's `data_get()` helper instead of direct array access.diff --git a/app/Actions/Post/BuildCalendarPageProps.php b/app/Actions/Post/BuildCalendarPageProps.phpindex 707235cfa..a2288751b 100644--- a/app/Actions/Post/BuildCalendarPageProps.php+++ b/app/Actions/Post/BuildCalendarPageProps.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Actions\Post;use App\Actions\Post\Queue\BuildQueueTimeline;+use App\Actions\Post\Queue\MoveChannelPostToQueueSlot;use App\Enums\Post\Status as PostStatus;use App\Http\Resources\App\PostCardResource;use App\Http\Resources\App\SocialAccountResource;@@ -124,29 +125,33 @@ class BuildCalendarPageProps->through(fn (Post $post): array => PostCardResource::make($post)->resolve()));}- if ($request->boolean('slots')) {- $props['slots'] = fn (): array => self::slots(- $workspace,- match (true) {- $channel !== null => collect([$channel]),- $requestedChannelIds !== [] => $filterAccounts()->whereIn('id', $requestedChannelIds)->values(),- default => $filterAccounts(),- },- $timezone,- $rangeStart,- $rangeEnd,- $labelIds === [] && ! $untagged && in_array($status, [self::STATUS_ALL, 'scheduled'], true),- );- }+ $slots = fn (): array => self::slots(+ $workspace,+ match (true) {+ $channel !== null => collect([$channel]),+ $requestedChannelIds !== [] => $filterAccounts()->whereIn('id', $requestedChannelIds)->values(),+ default => $filterAccounts(),+ },+ $timezone,+ $rangeStart,+ $rangeEnd,+ $labelIds === [] && ! $untagged && in_array($status, [self::STATUS_ALL, 'scheduled'], true),+ );++ $props['slots'] = $request->boolean('slots') ? $slots : Inertia::optional($slots);return $props;}/*** Empty posting slots of the visible range, bucketed by day of the display time zone.+ * Sent eagerly with `slots=1`, else only when a partial reload asks for them by name, so a+ * reload that follows a URL without it (a move answered with back()) still refreshes them.+ * `queueable` says whether a queued post may take the slot (within the queue window);+ * a later slot still opens the composer, and a post dropped there gets a custom time.** @param Collection<int, SocialAccount> $channels- * @return array<string, list<array{at: string, channel_id: string}>>+ * @return array<string, list<array{at: string, channel_id: string, queueable: bool}>>*/private static function slots(Workspace $workspace, Collection $channels, string $timezone, CarbonImmutable $rangeStart, CarbonImmutable $rangeEnd, bool $visible): array{@@ -158,11 +163,21 @@ class BuildCalendarPagePropsforeach (BuildQueueTimeline::handle($workspace, $channels, $timezone, $rangeEnd) as $day) {foreach (data_get($day, 'items', []) as $item) {- if (data_get($item, 'type') !== 'slot' || CarbonImmutable::parse(data_get($item, 'at'))->lessThan($rangeStart)) {+ if (data_get($item, 'type') !== 'slot') {+ continue;+ }++ $slotAt = CarbonImmutable::parse(data_get($item, 'at'));++ if ($slotAt->lessThan($rangeStart)) {continue;}- $slots[data_get($day, 'date')][] = ['at' => data_get($item, 'at'), 'channel_id' => data_get($item, 'channel_id')];+ $slots[data_get($day, 'date')][] = [+ 'at' => data_get($item, 'at'),+ 'channel_id' => data_get($item, 'channel_id'),+ 'queueable' => MoveChannelPostToQueueSlot::withinQueueWindow($slotAt),+ ];}}diff --git a/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php b/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.phpindex 969a75e3e..41597cf9b 100644--- a/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php+++ b/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php@@ -6,11 +6,13 @@ namespace App\Actions\Post\Queue;use App\Actions\Post\BuildPublishPageProps;use App\Actions\Post\UpdatePost;+use App\Enums\Post\Action as PostAction;use App\Enums\Post\Status as PostStatus;use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;use Illuminate\Validation\ValidationException;class MoveChannelPostToQueueSlot@@ -18,10 +20,12 @@ class MoveChannelPostToQueueSlot/*** Moves a scheduled post of the channel onto one of its free posting slots, as a queue post.* The write goes through UpdatePost with the acting user, so PostApproval still decides.+ *+ * @return array{post: Post, action: PostAction|null}*/- public static function handle(SocialAccount $channel, string $postId, CarbonImmutable $slotAt, User $actor): void+ public static function handle(SocialAccount $channel, string $postId, CarbonImmutable $slotAt, User $actor): array{- ReflowChannelQueue::withLock([$channel->id], function () use ($channel, $postId, $slotAt, $actor): void {+ return ReflowChannelQueue::withLock([$channel->id], function () use ($channel, $postId, $slotAt, $actor): array {$channel->refresh();$post = Post::query()@@ -33,16 +37,23 @@ class MoveChannelPostToQueueSlotthrow ValidationException::withMessages(['slot_at' => __('posts.errors.queue_order_stale')]);}- UpdatePost::execute($channel->workspace, $post, [+ return UpdatePost::execute($channel->workspace, $post, ['status' => PostStatus::Scheduled->value,'queue_slot' => $slotAt->utc()->toIso8601String(),], $actor);});}+ /**+ * Whether a posting slot is close enough to take a queued post (BuildPublishPageProps::MAX_QUEUE_DAYS).+ */+ public static function withinQueueWindow(CarbonInterface $slotAt): bool+ {+ return $slotAt->lessThanOrEqualTo(now()->addDays(BuildPublishPageProps::MAX_QUEUE_DAYS));+ }+private static function isFreeSlot(SocialAccount $channel, Post $post, CarbonImmutable $slotAt): bool{- return $slotAt->lessThanOrEqualTo(now()->addDays(BuildPublishPageProps::MAX_QUEUE_DAYS))- && ReflowChannelQueue::isFreeSlot($channel, $slotAt, $post->id);+ return self::withinQueueWindow($slotAt) && ReflowChannelQueue::isFreeSlot($channel, $slotAt, $post->id);}}diff --git a/app/Actions/Post/ReschedulePost.php b/app/Actions/Post/ReschedulePost.phpnew file mode 100644index 000000000..61b77bedc--- /dev/null+++ b/app/Actions/Post/ReschedulePost.php@@ -0,0 +1,69 @@+<?php++declare(strict_types=1);++namespace App\Actions\Post;++use App\Actions\Post\Queue\MoveChannelPostToQueueSlot;+use App\Enums\Post\Action as PostAction;+use App\Enums\Post\Status as PostStatus;+use App\Models\Post;+use App\Models\User;+use App\Models\Workspace;+use App\Support\PostApproval;+use Carbon\CarbonImmutable;+use Illuminate\Support\Arr;+use Illuminate\Validation\ValidationException;++class ReschedulePost+{+ /**+ * Moves a post to the instant it receives. A draft stays a draft and only changes its date.+ * A null instant (a drop on No Date) takes the post off the schedule: it becomes a draft+ * without a date, which frees a queued post's slot and never needs approval.+ * A scheduled post sent with `$queueSlot` goes into its channel's queue at that free slot+ * (MoveChannelPostToQueueSlot, which refuses a taken slot or an instant that is not one; the+ * calendar says so on `scheduled_at`, the field its drop sends).+ * A slot past the queue window (MoveChannelPostToQueueSlot::withinQueueWindow) counts as a+ * custom time, like any other drop: a queued post becomes custom at the instant it receives.+ * The write goes through UpdatePost with the acting user, so PostApproval still decides.+ * The post is re-read under its approval lock: a post waiting for approval, or a scheduled+ * one due within a minute, keeps its time. The channel queue lock is taken inside the+ * approval lock, the same order UpdatePost, ApprovePost and AppendPostMedia use.+ *+ * @return array{post: Post, action: PostAction|null}+ */+ public static function execute(Workspace $workspace, Post $post, ?string $scheduledAt, User $actor, bool $queueSlot = false): array+ {+ if (! $post->hasChannel()) {+ throw ValidationException::withMessages(['scheduled_at' => __('posts.errors.choose_channel')]);+ }++ return PostApproval::locked($post, function () use ($workspace, $post, $scheduledAt, $actor, $queueSlot): array {+ if ($post->status === PostStatus::PendingApproval) {+ throw ValidationException::withMessages(['scheduled_at' => __('calendar.reschedule.errors.pending')]);+ }++ if ($post->status === PostStatus::Scheduled && filled($post->scheduled_at) && ! $post->scheduled_at->isAfter(now()->addMinute())) {+ throw ValidationException::withMessages(['scheduled_at' => __('calendar.reschedule.errors.publishing_soon')]);+ }++ $slotAt = filled($scheduledAt) ? CarbonImmutable::parse($scheduledAt)->utc() : null;++ if ($queueSlot && filled($slotAt) && $post->status === PostStatus::Scheduled && MoveChannelPostToQueueSlot::withinQueueWindow($slotAt)) {+ try {+ return MoveChannelPostToQueueSlot::handle($post->socialAccount, $post->id, $slotAt, $actor);+ } catch (ValidationException $exception) {+ throw Arr::has($exception->errors(), 'slot_at')+ ? ValidationException::withMessages(['scheduled_at' => __('calendar.reschedule.errors.slot_taken')])+ : $exception;+ }+ }++ return UpdatePost::execute($workspace, $post, [+ 'status' => blank($scheduledAt) || $post->status === PostStatus::Draft ? PostStatus::Draft->value : PostStatus::Scheduled->value,+ 'scheduled_at' => $scheduledAt,+ ], $actor);+ });+ }+}diff --git a/app/Enums/Post/ScheduleAction.php b/app/Enums/Post/ScheduleAction.phpnew file mode 100644index 000000000..dde652492--- /dev/null+++ b/app/Enums/Post/ScheduleAction.php@@ -0,0 +1,33 @@+<?php++declare(strict_types=1);++namespace App\Enums\Post;++use LogicException;++enum ScheduleAction: string+{+ case Draft = 'draft';+ case PublishNow = 'publish_now';+ case QueueNext = 'queue_next';+ case QueueTop = 'queue_top';+ case Reschedule = 'reschedule';++ /**+ * What UpdatePost receives for an action that only changes the post's status or queue position.+ * Reschedule carries a time and goes through ReschedulePost instead.+ *+ * @return array{status: string, queue?: string}+ */+ public function postChanges(): array+ {+ return match ($this) {+ self::Draft => ['status' => Status::Draft->value],+ self::PublishNow => ['status' => Status::Publishing->value],+ self::QueueNext => ['status' => Status::Scheduled->value, 'queue' => QueuePosition::Next->value],+ self::QueueTop => ['status' => Status::Scheduled->value, 'queue' => QueuePosition::Top->value],+ self::Reschedule => throw new LogicException('Reschedule goes through ReschedulePost.'),+ };+ }+}diff --git a/app/Http/Controllers/App/Concerns/RendersPublishPage.php b/app/Http/Controllers/App/Concerns/RendersPublishPage.phpindex f011c3ab4..9af06b69a 100644--- a/app/Http/Controllers/App/Concerns/RendersPublishPage.php+++ b/app/Http/Controllers/App/Concerns/RendersPublishPage.php@@ -12,15 +12,22 @@ use App\Models\Workspace;use App\Support\PostStatusRules;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;+use Illuminate\Routing\Route as RoutingRoute;use Illuminate\Support\Arr;use Illuminate\Support\Facades\Route;use Illuminate\Support\Str;+use Illuminate\Support\Uri;use Inertia\Inertia;use Inertia\Response;+use League\Uri\Contracts\UriException;+use League\Uri\QueryString;+use Symfony\Component\HttpFoundation\Exception\BadRequestException;use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;trait RendersPublishPage{+ private const array PUBLISH_PAGE_ROUTES = ['app.posts.index', 'app.channels.publish'];+private function renderPublishPage(Request $request, Workspace $workspace, ?SocialAccount $channel = null): Response|RedirectResponse{$composerPost = null;@@ -42,54 +49,102 @@ trait RendersPublishPagereturn Inertia::render('publish/Index', BuildPublishPageProps::handle($request, $workspace, $channel, $composerPost));}+ /**+ * Where a post saved or deleted from a composer or post dialog returns: the+ * Publish page it came from on the tab given, or any other page of the app+ * as it was. The Referer is matched once for both; without one, the home page.+ *+ * @param array<string, string> $publishQuery+ */+ private function originPageUrl(array $publishQuery = []): string+ {+ $route = $this->previousRoute();++ return $this->publishPageUrl($route, $publishQuery) ?? $this->previousUrl($route);+ }+/*** The Publish page (all channels or one channel) the request was sent from,* with its tab, time zone and filters, minus the composer and notes context.+ * Null when the request came from any other page.** @param array<string, string> $extraQuery*/private function publishPageReturnUrl(array $extraQuery = []): ?string{- if (! in_array($this->previousRouteName(), ['app.posts.index', 'app.channels.publish'], true)) {+ return $this->publishPageUrl($this->previousRoute(), $extraQuery);+ }++ /**+ * @param array<string, string> $extraQuery+ */+ private function publishPageUrl(?RoutingRoute $route, array $extraQuery): ?string+ {+ if (! in_array($route?->getName(), self::PUBLISH_PAGE_ROUTES, true)) {return null;}- $previous = parse_url(url()->previous());- $path = data_get($previous, 'path', '/');-- parse_str(data_get($previous, 'query', ''), $query);-- $query = [- ...Arr::except($query, ['edit', 'notes', 'note', 'post', 'compose', 'date', 'ai', 'assistant']),- ...$extraQuery,- ];+ return $this->previousUrl(+ $route,+ except: ['edit', 'notes', 'note', 'post', 'compose', 'date', 'ai', 'assistant'],+ extraQuery: $extraQuery,+ );+ }- $url = url($path);+ /**+ * The page the request was sent from, rebuilt with route() from the route its+ * Referer matched, so it always points at this app, at the same route+ * parameters (a query key, named or numeric, never replaces or fills one: a key named like+ * an optional parameter the path left out stays in the query, where the page reads it). Its query is+ * read form-encoded, as PHP reads it (`+` is a space), with dots kept in keys, which Laravel's+ * and Symfony's request parsers turn into underscores, and kept, minus the+ * keys in `$except`, with `$extraQuery` replacing or adding keys. A Referer+ * that matches no route of the app, or cannot be read, returns to the home page.+ *+ * @param list<string> $except+ * @param array<string, string> $extraQuery+ */+ private function previousUrl(?RoutingRoute $route, array $except = [], array $extraQuery = []): string+ {+ if (blank($route?->getName())) {+ return route('app.home');+ }- if ($query === []) {- return $url;+ try {+ $query = Arr::where(+ Arr::except(+ QueryString::extract(Uri::of(url()->previous())->query()->value(), encType: PHP_QUERY_RFC1738),+ [...$except, ...array_keys($route->parameters())],+ ),+ fn (mixed $value, int|string $key): bool => is_string($key),+ );+ } catch (UriException) {+ return route('app.home');}- $queryString = Arr::query($query);+ $unboundParameters = array_diff($route->parameterNames(), array_keys($route->parameters()));+ $url = route($route->getName(), [...Arr::except($query, $unboundParameters), ...$extraQuery, ...$route->parameters()]);+ $keptAsQuery = Arr::only($query, $unboundParameters);- return "{$url}?{$queryString}";+ return $keptAsQuery === [] ? $url : (string) Uri::of($url)->withQuery($keptAsQuery);}/**- * The calendar (all channels or one channel) the request was sent from, as it was.+ * The route of the page the request was sent from. The Referer is read as a+ * request served by this one's script, so an app served from a subfolder+ * matches its routes without the subfolder. Without a Referer (a browser or+ * extension that strips it) the page is unknown: the session's last full page+ * load, which url()->previous() falls back to, is too old to stand for it.*/- private function calendarReturnUrl(): ?string+ private function previousRoute(): ?RoutingRoute{- return in_array($this->previousRouteName(), ['app.calendar', 'app.channels.calendar'], true)- ? url()->previous()- : null;- }+ if (blank(request()->header('referer'))) {+ return null;+ }- private function previousRouteName(): ?string- {try {- return Route::getRoutes()->match(Request::create(data_get(parse_url(url()->previous()), 'path', '/')))->getName();- } catch (HttpExceptionInterface) {+ return Route::getRoutes()->match(Request::create(url()->previous(), server: request()->server->all()));+ } catch (HttpExceptionInterface|BadRequestException) {return null;}}diff --git a/app/Http/Controllers/App/PostController.php b/app/Http/Controllers/App/PostController.phpindex fc675d0ed..befc4000b 100644--- a/app/Http/Controllers/App/PostController.php+++ b/app/Http/Controllers/App/PostController.php@@ -130,7 +130,7 @@ class PostController extends Controllerdefault => [],};- return redirect($this->publishPageReturnUrl($tab) ?? route('app.posts.index', $tab))+ return redirect($this->originPageUrl($tab))->with('created_post_ids', $posts->pluck('id')->all());}@@ -182,19 +182,13 @@ class PostController extends Controllerreturn back();}- if ($action === PostAction::Publishing) {- return redirect($this->publishPageReturnUrl(['tab' => 'queue']) ?? route('app.posts.index', ['tab' => 'queue']));- }-- if ($action === PostAction::Scheduled) {- return redirect($this->publishPageReturnUrl(['tab' => 'queue']) ?? route('app.posts.index', ['post' => $post->id]));- }-- $publishPage = $this->publishPageReturnUrl(- $request->validated('status') === PostStatus::Draft->value ? ['tab' => 'drafts'] : [],- );+ $tab = match (true) {+ in_array($action, [PostAction::Publishing, PostAction::Scheduled], true) => ['tab' => 'queue'],+ $request->validated('status') === PostStatus::Draft->value => ['tab' => 'drafts'],+ default => [],+ };- return $publishPage ? redirect($publishPage) : back();+ return redirect($this->originPageUrl($tab));}public function destroy(Request $request, Post $post): RedirectResponse@@ -224,7 +218,7 @@ class PostController extends Controller}}- return redirect($this->publishPageReturnUrl() ?? $this->calendarReturnUrl() ?? route('app.posts.index'));+ return redirect($this->originPageUrl());}public function duplicate(Request $request, Post $post): RedirectResponsediff --git a/app/Http/Controllers/App/PostScheduleController.php b/app/Http/Controllers/App/PostScheduleController.phpindex 5de99e018..ab9a4b604 100644--- a/app/Http/Controllers/App/PostScheduleController.php+++ b/app/Http/Controllers/App/PostScheduleController.php@@ -4,10 +4,10 @@ declare(strict_types=1);namespace App\Http\Controllers\App;+use App\Actions\Post\ReschedulePost;use App\Actions\Post\UpdatePost;use App\Enums\Post\Action as PostAction;-use App\Enums\Post\QueuePosition;-use App\Enums\Post\Status as PostStatus;+use App\Enums\Post\ScheduleAction;use App\Http\Controllers\App\Concerns\RendersPublishPage;use App\Http\Requests\App\Post\UpdatePostScheduleRequest;use App\Models\Post;@@ -28,19 +28,21 @@ class PostScheduleController extends Controller$this->authorize('update', $post);- if ($request->validated('action') === 'publish_now' && ! PostStatusRules::blocksEditing($post)) {+ $scheduleAction = $request->enum('action', ScheduleAction::class);++ if ($scheduleAction === ScheduleAction::Reschedule && $request->boolean('queue_slot')) {+ $this->authorize('publishDirectly', $workspace);+ }++ if ($scheduleAction === ScheduleAction::PublishNow && ! PostStatusRules::blocksEditing($post)) {PostStatusRules::assertStoredPostPublishable($post);}- $data = match ($request->validated('action')) {- 'draft' => ['status' => PostStatus::Draft->value],- 'publish_now' => ['status' => PostStatus::Publishing->value],- 'queue_next' => ['status' => PostStatus::Scheduled->value, 'queue' => QueuePosition::Next->value],- 'queue_top' => ['status' => PostStatus::Scheduled->value, 'queue' => QueuePosition::Top->value],+ $result = match ($scheduleAction) {+ ScheduleAction::Reschedule => ReschedulePost::execute($workspace, $post, $request->validated('scheduled_at'), $request->user(), $request->boolean('queue_slot')),+ ScheduleAction::Draft, ScheduleAction::PublishNow, ScheduleAction::QueueNext, ScheduleAction::QueueTop => UpdatePost::execute($workspace, $post, $scheduleAction->postChanges(), $request->user()),};- $result = UpdatePost::execute($workspace, $post, $data, $request->user());-$action = data_get($result, 'action');if ($action === PostAction::Finalized) {@@ -48,7 +50,7 @@ class PostScheduleController extends Controllersession()->flash('flash.bannerStyle', 'danger');}- if ($action === PostAction::Publishing || $action === PostAction::Scheduled) {+ if ($scheduleAction === ScheduleAction::PublishNow && in_array($action, [PostAction::Publishing, PostAction::Scheduled], true)) {$queue = $this->publishPageReturnUrl(['tab' => 'queue']);return $queue ? redirect($queue) : back();diff --git a/app/Http/Controllers/App/Settings/ProfileController.php b/app/Http/Controllers/App/Settings/ProfileController.phpindex 50e5f4c27..dab7c1741 100644--- a/app/Http/Controllers/App/Settings/ProfileController.php+++ b/app/Http/Controllers/App/Settings/ProfileController.php@@ -97,6 +97,6 @@ class ProfileController extends Controllerreturn to_route('app.profile.edit');}- return redirect('/');+ return redirect()->route('login');}}diff --git a/app/Http/Controllers/Auth/AuthenticatedSessionController.php b/app/Http/Controllers/Auth/AuthenticatedSessionController.phpindex b586dd687..251f1050c 100644--- a/app/Http/Controllers/Auth/AuthenticatedSessionController.php+++ b/app/Http/Controllers/Auth/AuthenticatedSessionController.php@@ -65,6 +65,6 @@ class AuthenticatedSessionController extends Controller$request->session()->regenerateToken();- return redirect('/');+ return redirect()->route('app.home');}}diff --git a/app/Http/Controllers/Auth/GitHubController.php b/app/Http/Controllers/Auth/GitHubController.phpindex 3810ae972..3b38ac470 100644--- a/app/Http/Controllers/Auth/GitHubController.php+++ b/app/Http/Controllers/Auth/GitHubController.php@@ -103,7 +103,7 @@ class GitHubController extends Controllerreturn redirect()->route('app.invites.show', $invite);}- return redirect()->route('app.home');+ return redirect()->intended(route('app.calendar'));}private function registerNewUser(\Laravel\Socialite\Contracts\User $githubUser): RedirectResponsediff --git a/app/Http/Controllers/Auth/GoogleController.php b/app/Http/Controllers/Auth/GoogleController.phpindex 9c3b15753..5e47a8d6e 100644--- a/app/Http/Controllers/Auth/GoogleController.php+++ b/app/Http/Controllers/Auth/GoogleController.php@@ -95,7 +95,7 @@ class GoogleController extends Controllerreturn redirect()->route('app.invites.show', $invite);}- return redirect()->route('app.home');+ return redirect()->intended(route('app.calendar'));}private function registerNewUser(\Laravel\Socialite\Contracts\User $googleUser): RedirectResponsediff --git a/app/Http/Requests/App/Post/UpdatePostScheduleRequest.php b/app/Http/Requests/App/Post/UpdatePostScheduleRequest.phpindex 418186871..b83da460a 100644--- a/app/Http/Requests/App/Post/UpdatePostScheduleRequest.php+++ b/app/Http/Requests/App/Post/UpdatePostScheduleRequest.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Http\Requests\App\Post;+use App\Enums\Post\ScheduleAction;use Illuminate\Contracts\Validation\ValidationRule;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Rule;@@ -21,7 +22,31 @@ class UpdatePostScheduleRequest extends FormRequestpublic function rules(): array{return [- 'action' => ['required', Rule::in(['draft', 'publish_now', 'queue_next', 'queue_top'])],+ 'action' => ['required', Rule::enum(ScheduleAction::class)],+ 'scheduled_at' => [+ 'exclude_unless:action,reschedule',+ 'present',+ 'nullable',+ 'date',+ 'after:now',+ 'before:2038-01-19',+ ],+ 'queue_slot' => [+ 'exclude_unless:action,reschedule',+ 'sometimes',+ 'boolean',+ ],+ ];+ }++ /**+ * @return array<string, string>+ */+ public function messages(): array+ {+ return [+ 'scheduled_at.after' => __('calendar.reschedule.errors.past'),+ 'scheduled_at.before' => __('calendar.reschedule.errors.too_far'),];}}diff --git a/boost.json b/boost.jsonindex 80f344e44..201151dc0 100644--- a/boost.json+++ b/boost.json@@ -15,13 +15,13 @@"ai-sdk-development","cashier-stripe-development","laravel-best-practices",+ "testing-best-practices","configuring-horizon","mcp-development","configure-nightwatch","passport-development","socialite-development","wayfinder-development",- "pest-testing","inertia-vue-development","tailwindcss-development"]diff --git a/composer.lock b/composer.lockindex 81a1d6514..3c8f3e144 100644--- a/composer.lock+++ b/composer.lock@@ -159,23 +159,24 @@},{"name": "brick/math",- "version": "0.18.0",+ "version": "1.0.0","source": {"type": "git","url": "https://github.com/brick/math.git",- "reference": "82944324d1c1bdb2c2618e89978d4e2ad78d69ad"+ "reference": "2effe05d2177c451b86c6a073196a4034c02f211"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/brick/math/zipball/82944324d1c1bdb2c2618e89978d4e2ad78d69ad",- "reference": "82944324d1c1bdb2c2618e89978d4e2ad78d69ad",+ "url": "https://api.github.com/repos/brick/math/zipball/2effe05d2177c451b86c6a073196a4034c02f211",+ "reference": "2effe05d2177c451b86c6a073196a4034c02f211","shasum": ""},"require": {"php": "^8.2"},"require-dev": {- "phpstan/phpstan": "2.1.22",+ "phpstan/phpstan": "2.2.13",+ "phpstan/phpstan-phpunit": "2.0.18","phpunit/phpunit": "^11.5"},"type": "library",@@ -206,7 +207,7 @@],"support": {"issues": "https://github.com/brick/math/issues",- "source": "https://github.com/brick/math/tree/0.18.0"+ "source": "https://github.com/brick/math/tree/1.0.0"},"funding": [{@@ -214,20 +215,20 @@"type": "github"}],- "time": "2026-06-14T18:21:03+00:00"+ "time": "2026-09-12T10:28:18+00:00"},{"name": "carbonphp/carbon-doctrine-types",- "version": "3.2.0",+ "version": "3.2.1","source": {"type": "git","url": "https://github.com/CarbonPHP/carbon-doctrine-types.git",- "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d"+ "reference": "5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/18ba5ddfec8976260ead6e866180bd5d2f71aa1d",- "reference": "18ba5ddfec8976260ead6e866180bd5d2f71aa1d",+ "url": "https://api.github.com/repos/CarbonPHP/carbon-doctrine-types/zipball/5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc",+ "reference": "5fa5eacafd9ef47c8c6ab9143fc901ba0194d3dc","shasum": ""},"require": {@@ -242,6 +243,11 @@"phpunit/phpunit": "^10.3"},"type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.x-dev"+ }+ },"autoload": {"psr-4": {"Carbon\\Doctrine\\": "src/Carbon/Doctrine/"@@ -267,7 +273,7 @@],"support": {"issues": "https://github.com/CarbonPHP/carbon-doctrine-types/issues",- "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.0"+ "source": "https://github.com/CarbonPHP/carbon-doctrine-types/tree/3.2.1"},"funding": [{@@ -283,7 +289,7 @@"type": "tidelift"}],- "time": "2024-02-09T16:56:22+00:00"+ "time": "2026-09-06T14:11:38+00:00"},{"name": "clue/redis-protocol",@@ -636,23 +642,23 @@},{"name": "doctrine/inflector",- "version": "2.1.0",+ "version": "2.1.1","source": {"type": "git","url": "https://github.com/doctrine/inflector.git",- "reference": "6d6c96277ea252fc1304627204c3d5e6e15faa3b"+ "reference": "46351b6812b7b6d52b82c3efa5dfb786a198ec88"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/doctrine/inflector/zipball/6d6c96277ea252fc1304627204c3d5e6e15faa3b",- "reference": "6d6c96277ea252fc1304627204c3d5e6e15faa3b",+ "url": "https://api.github.com/repos/doctrine/inflector/zipball/46351b6812b7b6d52b82c3efa5dfb786a198ec88",+ "reference": "46351b6812b7b6d52b82c3efa5dfb786a198ec88","shasum": ""},"require": {"php": "^7.2 || ^8.0"},"require-dev": {- "doctrine/coding-standard": "^12.0 || ^13.0",+ "doctrine/coding-standard": "^12.0 || ^14.0","phpstan/phpstan": "^1.12 || ^2.0","phpstan/phpstan-phpunit": "^1.4 || ^2.0","phpstan/phpstan-strict-rules": "^1.6 || ^2.0",@@ -706,7 +712,7 @@],"support": {"issues": "https://github.com/doctrine/inflector/issues",- "source": "https://github.com/doctrine/inflector/tree/2.1.0"+ "source": "https://github.com/doctrine/inflector/tree/2.1.1"},"funding": [{@@ -722,31 +728,29 @@"type": "tidelift"}],- "time": "2025-08-10T19:31:58+00:00"+ "time": "2026-10-26T08:14:14+00:00"},{"name": "doctrine/lexer",- "version": "3.0.1",+ "version": "3.0.3","source": {"type": "git","url": "https://github.com/doctrine/lexer.git",- "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd"+ "reference": "71d305eaa6480d3d3460c7d053d1da7749fa9cca"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/doctrine/lexer/zipball/31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd",- "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd",+ "url": "https://api.github.com/repos/doctrine/lexer/zipball/71d305eaa6480d3d3460c7d053d1da7749fa9cca",+ "reference": "71d305eaa6480d3d3460c7d053d1da7749fa9cca","shasum": ""},"require": {"php": "^8.1"},"require-dev": {- "doctrine/coding-standard": "^12",- "phpstan/phpstan": "^1.10",- "phpunit/phpunit": "^10.5",- "psalm/plugin-phpunit": "^0.18.3",- "vimeo/psalm": "^5.21"+ "doctrine/coding-standard": "^14",+ "phpstan/phpstan": "^2",+ "phpunit/phpunit": "^10.5.58 || ^12.5.4"},"type": "library","autoload": {@@ -783,7 +787,7 @@],"support": {"issues": "https://github.com/doctrine/lexer/issues",- "source": "https://github.com/doctrine/lexer/tree/3.0.1"+ "source": "https://github.com/doctrine/lexer/tree/3.0.3"},"funding": [{@@ -799,20 +803,20 @@"type": "tidelift"}],- "time": "2024-02-05T11:56:58+00:00"+ "time": "2026-10-01T06:59:29+00:00"},{"name": "dragonmantank/cron-expression",- "version": "v3.6.0",+ "version": "v3.6.1","source": {"type": "git","url": "https://github.com/dragonmantank/cron-expression.git",- "reference": "d61a8a9604ec1f8c3d150d09db6ce98b32675013"+ "reference": "4189372ffeff09bf14f731f67a9de90c7b413ebe"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/d61a8a9604ec1f8c3d150d09db6ce98b32675013",- "reference": "d61a8a9604ec1f8c3d150d09db6ce98b32675013",+ "url": "https://api.github.com/repos/dragonmantank/cron-expression/zipball/4189372ffeff09bf14f731f67a9de90c7b413ebe",+ "reference": "4189372ffeff09bf14f731f67a9de90c7b413ebe","shasum": ""},"require": {@@ -823,8 +827,8 @@},"require-dev": {"phpstan/extension-installer": "^1.4.3",- "phpstan/phpstan": "^1.12.32|^2.1.31",- "phpunit/phpunit": "^8.5.48|^9.0"+ "phpstan/phpstan": "^2.1.31",+ "phpunit/phpunit": "^11.5.43 || ^12.4"},"type": "library","extra": {@@ -855,7 +859,7 @@],"support": {"issues": "https://github.com/dragonmantank/cron-expression/issues",- "source": "https://github.com/dragonmantank/cron-expression/tree/v3.6.0"+ "source": "https://github.com/dragonmantank/cron-expression/tree/v3.6.1"},"funding": [{@@ -863,7 +867,7 @@"type": "github"}],- "time": "2025-10-31T18:51:33+00:00"+ "time": "2026-10-19T17:53:57+00:00"},{"name": "egulias/email-validator",@@ -1295,24 +1299,24 @@},{"name": "graham-campbell/result-type",- "version": "v1.1.4",+ "version": "v1.2.0","source": {"type": "git","url": "https://github.com/GrahamCampbell/Result-Type.git",- "reference": "e01f4a821471308ba86aa202fed6698b6b695e3b"+ "reference": "adccca3324eece92ca35463648c12b9e6293c05b"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/e01f4a821471308ba86aa202fed6698b6b695e3b",- "reference": "e01f4a821471308ba86aa202fed6698b6b695e3b",+ "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/adccca3324eece92ca35463648c12b9e6293c05b",+ "reference": "adccca3324eece92ca35463648c12b9e6293c05b","shasum": ""},"require": {"php": "^7.2.5 || ^8.0",- "phpoption/phpoption": "^1.9.5"+ "phpoption/phpoption": "^1.10"},"require-dev": {- "phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"+ "phpunit/phpunit": "^8.5.52 || ^9.6.34 || ^10.5.63 || ^11.5.55 || ^12.5.14"},"type": "library","autoload": {@@ -1341,7 +1345,7 @@],"support": {"issues": "https://github.com/GrahamCampbell/Result-Type/issues",- "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.4"+ "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.2.0"},"funding": [{@@ -1353,26 +1357,26 @@"type": "tidelift"}],- "time": "2025-12-27T19:43:20+00:00"+ "time": "2026-08-24T09:06:52+00:00"},{"name": "guzzlehttp/guzzle",- "version": "7.15.3",+ "version": "7.16.1","source": {"type": "git","url": "https://github.com/guzzle/guzzle.git",- "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc"+ "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",- "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",+ "url": "https://api.github.com/repos/guzzle/guzzle/zipball/81755d989b3007ca7f88a069857553cd08e7dc2e",+ "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e","shasum": ""},"require": {"ext-json": "*",- "guzzlehttp/promises": "^2.5.2",- "guzzlehttp/psr7": "^2.13",+ "guzzlehttp/promises": "^2.6",+ "guzzlehttp/psr7": "^2.13.2","php": "^7.2.5 || ^8.0","psr/http-client": "^1.0","symfony/deprecation-contracts": "^2.5 || ^3.0",@@ -1465,7 +1469,7 @@],"support": {"issues": "https://github.com/guzzle/guzzle/issues",- "source": "https://github.com/guzzle/guzzle/tree/7.15.3"+ "source": "https://github.com/guzzle/guzzle/tree/7.16.1"},"funding": [{@@ -1481,20 +1485,20 @@"type": "tidelift"}],- "time": "2026-08-05T19:48:21+00:00"+ "time": "2026-10-25T21:35:21+00:00"},{"name": "guzzlehttp/promises",- "version": "2.5.2",+ "version": "2.6.0","source": {"type": "git","url": "https://github.com/guzzle/promises.git",- "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce"+ "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/promises/zipball/2823687acff28b2dbe67b2508a6b300e2c3fa4ce",- "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce",+ "url": "https://api.github.com/repos/guzzle/promises/zipball/3d88c829bd5f13d13847b39067dbf09a60af2154",+ "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154","shasum": ""},"require": {@@ -1549,7 +1553,7 @@],"support": {"issues": "https://github.com/guzzle/promises/issues",- "source": "https://github.com/guzzle/promises/tree/2.5.2"+ "source": "https://github.com/guzzle/promises/tree/2.6.0"},"funding": [{@@ -1565,20 +1569,20 @@"type": "tidelift"}],- "time": "2026-08-05T19:30:54+00:00"+ "time": "2026-10-18T12:46:59+00:00"},{"name": "guzzlehttp/psr7",- "version": "2.13.0",+ "version": "2.13.2","source": {"type": "git","url": "https://github.com/guzzle/psr7.git",- "reference": "dad89620b7a6edb60c15858442eb2e408b45d8f4"+ "reference": "adee536f95101929f262b8c59e8a61472f347d58"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/psr7/zipball/dad89620b7a6edb60c15858442eb2e408b45d8f4",- "reference": "dad89620b7a6edb60c15858442eb2e408b45d8f4",+ "url": "https://api.github.com/repos/guzzle/psr7/zipball/adee536f95101929f262b8c59e8a61472f347d58",+ "reference": "adee536f95101929f262b8c59e8a61472f347d58","shasum": ""},"require": {@@ -1668,7 +1672,7 @@],"support": {"issues": "https://github.com/guzzle/psr7/issues",- "source": "https://github.com/guzzle/psr7/tree/2.13.0"+ "source": "https://github.com/guzzle/psr7/tree/2.13.2"},"funding": [{@@ -1684,30 +1688,30 @@"type": "tidelift"}],- "time": "2026-07-16T22:23:49+00:00"+ "time": "2026-10-17T23:49:46+00:00"},{"name": "guzzlehttp/uri-template",- "version": "v1.0.10",+ "version": "v2.0.1","source": {"type": "git","url": "https://github.com/guzzle/uri-template.git",- "reference": "f6c24c21f42b990e9a58912b332d0874df6ba839"+ "reference": "7a466ad606491eb6528c717482f7cca77f1851f3"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/uri-template/zipball/f6c24c21f42b990e9a58912b332d0874df6ba839",- "reference": "f6c24c21f42b990e9a58912b332d0874df6ba839",+ "url": "https://api.github.com/repos/guzzle/uri-template/zipball/7a466ad606491eb6528c717482f7cca77f1851f3",+ "reference": "7a466ad606491eb6528c717482f7cca77f1851f3","shasum": ""},"require": {- "php": "^7.2.5 || ^8.0",+ "php": "^7.4 || ^8.0","symfony/polyfill-php80": "^1.25"},"require-dev": {"bamarni/composer-bin-plugin": "^1.8.2",- "phpunit/phpunit": "^8.5.52 || ^9.6.34",- "uri-template/tests": "1.0.0"+ "phpunit/phpunit": "^9.6.34",+ "uri-template/tests": "1.0.2"},"type": "library","extra": {@@ -1754,7 +1758,7 @@],"support": {"issues": "https://github.com/guzzle/uri-template/issues",- "source": "https://github.com/guzzle/uri-template/tree/v1.0.10"+ "source": "https://github.com/guzzle/uri-template/tree/v2.0.1"},"funding": [{@@ -1770,7 +1774,7 @@"type": "tidelift"}],- "time": "2026-07-17T13:53:03+00:00"+ "time": "2026-08-24T17:13:02+00:00"},{"name": "inertiajs/inertia-laravel",@@ -2222,20 +2226,20 @@},{"name": "laravel/framework",- "version": "v13.24.0",+ "version": "v13.39.0","source": {"type": "git","url": "https://github.com/laravel/framework.git",- "reference": "6d481710375d2aa67656922ef760cdd2b18bcfe0"+ "reference": "d52c3b3129e4c8e213c97cdc68f94b0b7d27f181"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/framework/zipball/6d481710375d2aa67656922ef760cdd2b18bcfe0",- "reference": "6d481710375d2aa67656922ef760cdd2b18bcfe0",+ "url": "https://api.github.com/repos/laravel/framework/zipball/d52c3b3129e4c8e213c97cdc68f94b0b7d27f181",+ "reference": "d52c3b3129e4c8e213c97cdc68f94b0b7d27f181","shasum": ""},"require": {- "brick/math": "^0.14.2 || ^0.15 || ^0.16 || ^0.17 || ^0.18",+ "brick/math": "^0.14.2 || ^0.15 || ^0.16 || ^0.17 || ^0.18 || ^0.19 || ^0.20 || ^1.0","composer-runtime-api": "^2.2","doctrine/inflector": "^2.0.5","dragonmantank/cron-expression": "^3.4",@@ -2248,10 +2252,11 @@"ext-session": "*","ext-tokenizer": "*","fruitcake/php-cors": "^1.3",- "guzzlehttp/guzzle": "^7.8.2",- "guzzlehttp/promises": "^2.0.3",- "guzzlehttp/uri-template": "^1.0",- "laravel/prompts": "^0.3.11",+ "guzzlehttp/guzzle": "^7.8.2 || ^8.0",+ "guzzlehttp/promises": "^2.0.3 || ^3.0",+ "guzzlehttp/psr7": "^2.9 || ^3.0",+ "guzzlehttp/uri-template": "^1.0 || ^2.0",+ "laravel/prompts": "^0.3.25","laravel/serializable-closure": "^2.0.10","league/commonmark": "^2.8.1","league/flysystem": "^3.25.1",@@ -2262,6 +2267,7 @@"nunomaduro/termwind": "^2.0","php": "^8.3","psr/container": "^1.1.1 || ^2.0.1",+ "psr/http-message": "^1.0 || ^2.0","psr/log": "^1.0 || ^2.0 || ^3.0","psr/simple-cache": "^1.0 || ^2.0 || ^3.0","ramsey/uuid": "^4.7",@@ -2336,8 +2342,7 @@"aws/aws-sdk-php": "^3.322.9","ext-gmp": "*","fakerphp/faker": "^1.24",- "guzzlehttp/psr7": "^2.9",- "intervention/image": "^4.0",+ "intervention/image": "^4.2","laravel/pint": "^1.18","league/flysystem-aws-s3-v3": "^3.25.1","league/flysystem-ftp": "^3.25.1",@@ -2346,18 +2351,20 @@"league/flysystem-sftp-v3": "^3.25.1","mockery/mockery": "^1.6.10","opis/json-schema": "^2.4.1",- "orchestra/testbench-core": "^11.0.0",+ "orchestra/testbench-core": "^11.6.0","pda/pheanstalk": "^7.0.0 || ^8.0.0","php-http/discovery": "^1.15",- "phpstan/phpstan": "^2.0",+ "phpstan/phpstan": "2.3.1","phpunit/phpunit": "^11.5.50 || ^12.5.8 || ^13.0.3","predis/predis": "^2.3 || ^3.0",- "rector/rector": "^2.3",+ "rector/rector": "2.6.3","resend/resend-php": "^1.0","symfony/cache": "^7.4.0 || ^8.0.0","symfony/http-client": "^7.4.0 || ^8.0.0",+ "symfony/mercure": "^0.8.0","symfony/psr-http-message-bridge": "^7.4.0 || ^8.0.0",- "symfony/translation": "^7.4.0 || ^8.0.0"+ "symfony/translation": "^7.4.0 || ^8.0.0",+ "web-token/jwt-library": "^4.1"},"suggest": {"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",@@ -2374,7 +2381,7 @@"ext-redis": "Required to use the Redis cache and queue drivers (^4.0 || ^5.0 || ^6.0).","fakerphp/faker": "Required to generate fake data using the fake() helper (^1.23).","filp/whoops": "Required for friendly error pages in development (^2.14.3).",- "intervention/image": "Required to use the image processing features (^4.0).",+ "intervention/image": "Required to use the image processing features (^4.2).","laravel/tinker": "Required to use the tinker console command (^2.0).","league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.25.1).","league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.25.1).",@@ -2386,7 +2393,6 @@"php-http/discovery": "Required to use PSR-7 bridging features (^1.15).","phpunit/phpunit": "Required to use assertions and run tests (^11.5.50 || ^12.5.8 || ^13.0.3).","predis/predis": "Required to use the predis connector (^2.3 || ^3.0).",- "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).","pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0 || ^7.0).","resend/resend-php": "Required to enable support for the Resend mail transport (^0.10.0 || ^1.0).","spatie/fork": "Required to use the 'fork' concurrency driver (^1.2).",@@ -2394,8 +2400,10 @@"symfony/filesystem": "Required to enable support for relative symbolic links (^7.4 || ^8.0).","symfony/http-client": "Required to enable support for the Symfony API mail transports (^7.4 || ^8.0).","symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^7.4 || ^8.0).",+ "symfony/mercure": "Required to use the Mercure broadcast driver (^0.8).","symfony/postmark-mailer": "Required to enable support for the Postmark mail transport (^7.4 || ^8.0).",- "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^7.4 || ^8.0)."+ "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^7.4 || ^8.0).",+ "web-token/jwt-library": "Required to sign Mercure JWTs and use end-to-end encrypted channels (^4.1)."},"type": "library","extra": {@@ -2445,7 +2453,7 @@"issues": "https://github.com/laravel/framework/issues","source": "https://github.com/laravel/framework"},- "time": "2026-08-04T15:54:59+00:00"+ "time": "2026-10-27T14:04:39+00:00"},{"name": "laravel/horizon",@@ -2773,16 +2781,16 @@},{"name": "laravel/prompts",- "version": "v0.3.22",+ "version": "v0.3.26","source": {"type": "git","url": "https://github.com/laravel/prompts.git",- "reference": "02b89b39e8972a998db4d5d4ad4719239dd4aee4"+ "reference": "2d1e9bf6bab8d3f383c254db7f2b4ea8816d55e0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/prompts/zipball/02b89b39e8972a998db4d5d4ad4719239dd4aee4",- "reference": "02b89b39e8972a998db4d5d4ad4719239dd4aee4",+ "url": "https://api.github.com/repos/laravel/prompts/zipball/2d1e9bf6bab8d3f383c254db7f2b4ea8816d55e0",+ "reference": "2d1e9bf6bab8d3f383c254db7f2b4ea8816d55e0","shasum": ""},"require": {@@ -2825,10 +2833,9 @@],"description": "Add beautiful and user-friendly forms to your command-line applications.","support": {- "issues": "https://github.com/laravel/prompts/issues",- "source": "https://github.com/laravel/prompts/tree/v0.3.22"+ "source": "https://github.com/laravel/prompts/tree/v0.3.26"},- "time": "2026-08-04T14:50:50+00:00"+ "time": "2026-10-09T14:45:13+00:00"},{"name": "laravel/reverb",@@ -3029,16 +3036,16 @@},{"name": "laravel/serializable-closure",- "version": "v2.0.15",+ "version": "v2.1.0","source": {"type": "git","url": "https://github.com/laravel/serializable-closure.git",- "reference": "dccd8bcb851bb03fcc005df650b708b57cc52661"+ "reference": "2d5869a838bbcf37e0d8b0568fc41914e81374b5"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/dccd8bcb851bb03fcc005df650b708b57cc52661",- "reference": "dccd8bcb851bb03fcc005df650b708b57cc52661",+ "url": "https://api.github.com/repos/laravel/serializable-closure/zipball/2d5869a838bbcf37e0d8b0568fc41914e81374b5",+ "reference": "2d5869a838bbcf37e0d8b0568fc41914e81374b5","shasum": ""},"require": {@@ -3086,7 +3093,7 @@"issues": "https://github.com/laravel/serializable-closure/issues","source": "https://github.com/laravel/serializable-closure"},- "time": "2026-07-21T16:49:22+00:00"+ "time": "2026-09-22T14:32:34+00:00"},{"name": "laravel/socialite",@@ -3431,16 +3438,16 @@},{"name": "league/commonmark",- "version": "2.9.0",+ "version": "2.10.4","source": {"type": "git","url": "https://github.com/thephpleague/commonmark.git",- "reference": "5703d83ba3da3b2e356a5fedc848ed6d8ffb6529"+ "reference": "40821b7606d8d946bac57dbd2290076c722e3a65"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/5703d83ba3da3b2e356a5fedc848ed6d8ffb6529",- "reference": "5703d83ba3da3b2e356a5fedc848ed6d8ffb6529",+ "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/40821b7606d8d946bac57dbd2290076c722e3a65",+ "reference": "40821b7606d8d946bac57dbd2290076c722e3a65","shasum": ""},"require": {@@ -3477,7 +3484,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "2.10-dev"+ "dev-main": "2.11-dev"}},"autoload": {@@ -3534,7 +3541,7 @@"type": "tidelift"}],- "time": "2026-08-03T13:42:31+00:00"+ "time": "2026-10-17T19:59:50+00:00"},{"name": "league/config",@@ -3679,16 +3686,16 @@},{"name": "league/flysystem",- "version": "3.35.2",+ "version": "3.36.0","source": {"type": "git","url": "https://github.com/thephpleague/flysystem.git",- "reference": "b277b5dc3d56650b68904117124e79c851e12376"+ "reference": "f7fb152932f30072d573510cbd4dd657d6475b25"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/b277b5dc3d56650b68904117124e79c851e12376",- "reference": "b277b5dc3d56650b68904117124e79c851e12376",+ "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/f7fb152932f30072d573510cbd4dd657d6475b25",+ "reference": "f7fb152932f30072d573510cbd4dd657d6475b25","shasum": ""},"require": {@@ -3756,9 +3763,9 @@],"support": {"issues": "https://github.com/thephpleague/flysystem/issues",- "source": "https://github.com/thephpleague/flysystem/tree/3.35.2"+ "source": "https://github.com/thephpleague/flysystem/tree/3.36.0"},- "time": "2026-07-06T14:42:07+00:00"+ "time": "2026-09-02T08:00:27+00:00"},{"name": "league/flysystem-aws-s3-v3",@@ -3817,16 +3824,16 @@},{"name": "league/flysystem-local",- "version": "3.31.0",+ "version": "3.35.3","source": {"type": "git","url": "https://github.com/thephpleague/flysystem-local.git",- "reference": "2f669db18a4c20c755c2bb7d3a7b0b2340488079"+ "reference": "a099b24dce160f3b2239043d13d47c4a1a214ea4"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/flysystem-local/zipball/2f669db18a4c20c755c2bb7d3a7b0b2340488079",- "reference": "2f669db18a4c20c755c2bb7d3a7b0b2340488079",+ "url": "https://api.github.com/repos/thephpleague/flysystem-local/zipball/a099b24dce160f3b2239043d13d47c4a1a214ea4",+ "reference": "a099b24dce160f3b2239043d13d47c4a1a214ea4","shasum": ""},"require": {@@ -3860,9 +3867,9 @@"local"],"support": {- "source": "https://github.com/thephpleague/flysystem-local/tree/3.31.0"+ "source": "https://github.com/thephpleague/flysystem-local/tree/3.35.3"},- "time": "2026-01-23T15:30:45+00:00"+ "time": "2026-08-12T13:29:21+00:00"},{"name": "league/mime-type-detection",@@ -4095,20 +4102,21 @@},{"name": "league/uri",- "version": "7.8.1",+ "version": "7.9.1","source": {"type": "git","url": "https://github.com/thephpleague/uri.git",- "reference": "08cf38e3924d4f56238125547b5720496fac8fd4"+ "reference": "40403f5c3141457a61f7f1aba6706e8fa4a0ece5"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/uri/zipball/08cf38e3924d4f56238125547b5720496fac8fd4",- "reference": "08cf38e3924d4f56238125547b5720496fac8fd4",+ "url": "https://api.github.com/repos/thephpleague/uri/zipball/40403f5c3141457a61f7f1aba6706e8fa4a0ece5",+ "reference": "40403f5c3141457a61f7f1aba6706e8fa4a0ece5","shasum": ""},"require": {- "league/uri-interfaces": "^7.8.1",+ "ext-mbstring": "*",+ "league/uri-interfaces": "^7.9.1","php": "^8.1","psr/http-factory": "^1"},@@ -4181,7 +4189,7 @@"docs": "https://uri.thephpleague.com","forum": "https://thephpleague.slack.com","issues": "https://github.com/thephpleague/uri-src/issues",- "source": "https://github.com/thephpleague/uri/tree/7.8.1"+ "source": "https://github.com/thephpleague/uri/tree/7.9.1"},"funding": [{@@ -4189,20 +4197,20 @@"type": "github"}],- "time": "2026-03-15T20:22:25+00:00"+ "time": "2026-10-27T07:14:23+00:00"},{"name": "league/uri-interfaces",- "version": "7.8.1",+ "version": "7.9.1","source": {"type": "git","url": "https://github.com/thephpleague/uri-interfaces.git",- "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928"+ "reference": "994300a79e17f179112dc259f8df0c4de982f736"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/85d5c77c5d6d3af6c54db4a78246364908f3c928",- "reference": "85d5c77c5d6d3af6c54db4a78246364908f3c928",+ "url": "https://api.github.com/repos/thephpleague/uri-interfaces/zipball/994300a79e17f179112dc259f8df0c4de982f736",+ "reference": "994300a79e17f179112dc259f8df0c4de982f736","shasum": ""},"require": {@@ -4265,7 +4273,7 @@"docs": "https://uri.thephpleague.com","forum": "https://thephpleague.slack.com","issues": "https://github.com/thephpleague/uri-src/issues",- "source": "https://github.com/thephpleague/uri-interfaces/tree/7.8.1"+ "source": "https://github.com/thephpleague/uri-interfaces/tree/7.9.1"},"funding": [{@@ -4273,7 +4281,7 @@"type": "github"}],- "time": "2026-03-08T20:05:35+00:00"+ "time": "2026-10-27T07:14:23+00:00"},{"name": "moneyphp/money",@@ -4367,16 +4375,16 @@},{"name": "monolog/monolog",- "version": "3.10.0",+ "version": "3.12.1","source": {"type": "git","url": "https://github.com/Seldaek/monolog.git",- "reference": "b321dd6749f0bf7189444158a3ce785cc16d69b0"+ "reference": "d7059e4c691d05ea1222b5124bed0f961be46e15"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/Seldaek/monolog/zipball/b321dd6749f0bf7189444158a3ce785cc16d69b0",- "reference": "b321dd6749f0bf7189444158a3ce785cc16d69b0",+ "url": "https://api.github.com/repos/Seldaek/monolog/zipball/d7059e4c691d05ea1222b5124bed0f961be46e15",+ "reference": "d7059e4c691d05ea1222b5124bed0f961be46e15","shasum": ""},"require": {@@ -4402,6 +4410,7 @@"phpstan/phpstan-strict-rules": "^2","phpunit/phpunit": "^10.5.17 || ^11.0.7","predis/predis": "^1.1 || ^2",+ "psr/clock": "^1.0","rollbar/rollbar": "^4.0","ruflin/elastica": "^7 || ^8","symfony/mailer": "^5.4 || ^6",@@ -4420,6 +4429,7 @@"graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server","mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)","php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",+ "psr/clock": "Required to pass a clock to the Logger and control the timestamp of log records","rollbar/rollbar": "Allow sending log messages to Rollbar","ruflin/elastica": "Allow sending log messages to an Elastic Search server"},@@ -4454,7 +4464,7 @@],"support": {"issues": "https://github.com/Seldaek/monolog/issues",- "source": "https://github.com/Seldaek/monolog/tree/3.10.0"+ "source": "https://github.com/Seldaek/monolog/tree/3.12.1"},"funding": [{@@ -4466,7 +4476,7 @@"type": "tidelift"}],- "time": "2026-01-02T08:56:05+00:00"+ "time": "2026-09-29T19:21:12+00:00"},{"name": "mtdowling/jmespath.php",@@ -4536,16 +4546,16 @@},{"name": "nesbot/carbon",- "version": "3.13.1",+ "version": "3.15.1","source": {"type": "git","url": "https://github.com/CarbonPHP/carbon.git",- "reference": "2937ad3d1d2c506fd2bc97d571438a95641f44e2"+ "reference": "ce0e5636fae7d1e99856eb70cae4c719a284aa08"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/2937ad3d1d2c506fd2bc97d571438a95641f44e2",- "reference": "2937ad3d1d2c506fd2bc97d571438a95641f44e2",+ "url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/ce0e5636fae7d1e99856eb70cae4c719a284aa08",+ "reference": "ce0e5636fae7d1e99856eb70cae4c719a284aa08","shasum": ""},"require": {@@ -4555,6 +4565,7 @@"psr/clock": "^1.0","symfony/clock": "^6.3.12 || ^7.0 || ^8.0","symfony/polyfill-mbstring": "^1.0",+ "symfony/polyfill-time": "^1.0","symfony/translation": "^4.4.18 || ^5.2.1 || ^6.0 || ^7.0 || ^8.0"},"provide": {@@ -4565,7 +4576,7 @@"doctrine/orm": "^2.15.2 || ^3.0","friendsofphp/php-cs-fixer": "^v3.87.1","kylekatarnls/multi-tester": "^2.5.3",- "phpmd/phpmd": "^2.15.0",+ "phpmd/phpmd": "^3.0@dev","phpstan/extension-installer": "^1.4.3","phpstan/phpstan": "^2.1.22","phpunit/phpunit": "^10.5.53",@@ -4637,37 +4648,37 @@"type": "tidelift"}],- "time": "2026-07-09T18:23:49+00:00"+ "time": "2026-10-25T14:32:48+00:00"},{"name": "nette/schema",- "version": "v1.3.5",+ "version": "v1.4.0","source": {"type": "git","url": "https://github.com/nette/schema.git",- "reference": "f0ab1a3cda782dbc5da270d28545236aa80c4002"+ "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/nette/schema/zipball/f0ab1a3cda782dbc5da270d28545236aa80c4002",- "reference": "f0ab1a3cda782dbc5da270d28545236aa80c4002",+ "url": "https://api.github.com/repos/nette/schema/zipball/af9fa8a86bfca9b02b10346220db26e62ef942ec",+ "reference": "af9fa8a86bfca9b02b10346220db26e62ef942ec","shasum": ""},"require": {"nette/utils": "^4.0",- "php": "8.1 - 8.5"+ "php": "8.1 - 8.6"},"require-dev": {- "nette/phpstan-rules": "^1.0",+ "nette/phpstan-rules": "^1.0.7","nette/tester": "^2.6","phpstan/extension-installer": "^1.4@stable",- "phpstan/phpstan": "^2.1.39@stable",+ "phpstan/phpstan": "^2.3@stable","tracy/tracy": "^2.8"},"type": "library","extra": {"branch-alias": {- "dev-master": "1.3-dev"+ "dev-master": "1.4-dev"}},"autoload": {@@ -4688,40 +4699,40 @@{"name": "David Grudl","homepage": "https://davidgrudl.com"- },- {- "name": "Nette Community",- "homepage": "https://nette.org/contributors"}],- "description": "📐 Nette Schema: validating data structures against a given Schema.",- "homepage": "https://nette.org",+ "description": "📐 Nette Schema: validates and normalizes data such as configuration or API input against a schema described in a few readable lines of PHP, with precise error messages.",+ "homepage": "https://doc.nette.org/schema","keywords": [- "config",- "nette"+ "configuration",+ "data validation",+ "nette",+ "normalization",+ "schema",+ "validation"],"support": {"issues": "https://github.com/nette/schema/issues",- "source": "https://github.com/nette/schema/tree/v1.3.5"+ "source": "https://github.com/nette/schema/tree/v1.4.0"},- "time": "2026-02-23T03:47:12+00:00"+ "time": "2026-10-22T02:12:50+00:00"},{"name": "nette/utils",- "version": "v4.1.5",+ "version": "v4.1.6","source": {"type": "git","url": "https://github.com/nette/utils.git",- "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0"+ "reference": "6bf24518accf32cf845bca305e0b92078700fd01"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/nette/utils/zipball/b043439dbdf954e6c28b5ea7e34b0100f83165e0",- "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0",+ "url": "https://api.github.com/repos/nette/utils/zipball/6bf24518accf32cf845bca305e0b92078700fd01",+ "reference": "6bf24518accf32cf845bca305e0b92078700fd01","shasum": ""},"require": {- "php": "8.2 - 8.5"+ "php": "8.2 - 8.6"},"conflict": {"nette/finder": "<3",@@ -4793,22 +4804,22 @@],"support": {"issues": "https://github.com/nette/utils/issues",- "source": "https://github.com/nette/utils/tree/v4.1.5"+ "source": "https://github.com/nette/utils/tree/v4.1.6"},- "time": "2026-07-17T23:02:45+00:00"+ "time": "2026-10-20T17:07:56+00:00"},{"name": "nikic/php-parser",- "version": "v5.8.0",+ "version": "v5.9.0","source": {"type": "git","url": "https://github.com/nikic/PHP-Parser.git",- "reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f"+ "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/044a6a392ff8ad0d61f14370a5fbbd0a0107152f",- "reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f",+ "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/9e33da9553fe7786f0962b35f4e4ecf01be89def",+ "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def","shasum": ""},"require": {@@ -4850,9 +4861,9 @@],"support": {"issues": "https://github.com/nikic/PHP-Parser/issues",- "source": "https://github.com/nikic/PHP-Parser/tree/v5.8.0"+ "source": "https://github.com/nikic/PHP-Parser/tree/v5.9.0"},- "time": "2026-07-04T14:30:18+00:00"+ "time": "2026-09-13T18:51:52+00:00"},{"name": "nunomaduro/termwind",@@ -5141,16 +5152,16 @@},{"name": "phpoption/phpoption",- "version": "1.9.5",+ "version": "1.10.0","source": {"type": "git","url": "https://github.com/schmittjoh/php-option.git",- "reference": "75365b91986c2405cf5e1e012c5595cd487a98be"+ "reference": "67b192b6a42ec03944b972d6e633ddec78ad2c6d"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/75365b91986c2405cf5e1e012c5595cd487a98be",- "reference": "75365b91986c2405cf5e1e012c5595cd487a98be",+ "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/67b192b6a42ec03944b972d6e633ddec78ad2c6d",+ "reference": "67b192b6a42ec03944b972d6e633ddec78ad2c6d","shasum": ""},"require": {@@ -5158,7 +5169,7 @@},"require-dev": {"bamarni/composer-bin-plugin": "^1.8.2",- "phpunit/phpunit": "^8.5.44 || ^9.6.25 || ^10.5.53 || ^11.5.34"+ "phpunit/phpunit": "^8.5.54 || ^9.6.36 || ^10.5.64 || ^11.5.56 || ^12.5.33"},"type": "library","extra": {@@ -5200,7 +5211,7 @@],"support": {"issues": "https://github.com/schmittjoh/php-option/issues",- "source": "https://github.com/schmittjoh/php-option/tree/1.9.5"+ "source": "https://github.com/schmittjoh/php-option/tree/1.10.0"},"funding": [{@@ -5212,7 +5223,7 @@"type": "tidelift"}],- "time": "2025-12-27T19:41:33+00:00"+ "time": "2026-08-24T00:54:40+00:00"},{"name": "phpseclib/phpseclib",@@ -5326,16 +5337,16 @@},{"name": "phpstan/phpdoc-parser",- "version": "2.3.3",+ "version": "2.4.0","source": {"type": "git","url": "https://github.com/phpstan/phpdoc-parser.git",- "reference": "fb19eedd2bb67ff8cf7a5502ad329e701d6398a3"+ "reference": "e3647094ed8f0f1f67393d812b793a5143e25af3"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/fb19eedd2bb67ff8cf7a5502ad329e701d6398a3",- "reference": "fb19eedd2bb67ff8cf7a5502ad329e701d6398a3",+ "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/e3647094ed8f0f1f67393d812b793a5143e25af3",+ "reference": "e3647094ed8f0f1f67393d812b793a5143e25af3","shasum": ""},"require": {@@ -5367,9 +5378,9 @@"description": "PHPDoc parser with support for nullable, intersection and generic types","support": {"issues": "https://github.com/phpstan/phpdoc-parser/issues",- "source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.3"+ "source": "https://github.com/phpstan/phpdoc-parser/tree/2.4.0"},- "time": "2026-07-08T07:01:06+00:00"+ "time": "2026-10-28T20:28:58+00:00"},{"name": "posthog/posthog-php",@@ -6322,20 +6333,20 @@},{"name": "ramsey/uuid",- "version": "4.9.3",+ "version": "4.9.4","source": {"type": "git","url": "https://github.com/ramsey/uuid.git",- "reference": "1df15849d00943a67d677dc9cfd80795f038c9f8"+ "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/ramsey/uuid/zipball/1df15849d00943a67d677dc9cfd80795f038c9f8",- "reference": "1df15849d00943a67d677dc9cfd80795f038c9f8",+ "url": "https://api.github.com/repos/ramsey/uuid/zipball/75d73f48d02797c2c285a7e9f348fadc0102ffe2",+ "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2","shasum": ""},"require": {- "brick/math": ">=0.8.16 <=0.18",+ "brick/math": "^0.8.16 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14 || ^0.15 || ^0.16 || ^0.17 || ^0.18 || ^0.19 || ^0.20 || ^1.0","php": "^8.0","ramsey/collection": "^1.2 || ^2.0"},@@ -6394,9 +6405,9 @@],"support": {"issues": "https://github.com/ramsey/uuid/issues",- "source": "https://github.com/ramsey/uuid/tree/4.9.3"+ "source": "https://github.com/ramsey/uuid/tree/4.9.4"},- "time": "2026-06-18T03:57:49+00:00"+ "time": "2026-09-16T11:39:30+00:00"},{"name": "ratchet/rfc6455",@@ -7520,16 +7531,16 @@},{"name": "symfony/clock",- "version": "v8.1.0",+ "version": "v8.1.9","source": {"type": "git","url": "https://github.com/symfony/clock.git",- "reference": "701ef4de9705d6c32292ebee5e8044094a09fbf6"+ "reference": "945ea3b64d6da9c1c2c354fe5c07b27455df6442"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/clock/zipball/701ef4de9705d6c32292ebee5e8044094a09fbf6",- "reference": "701ef4de9705d6c32292ebee5e8044094a09fbf6",+ "url": "https://api.github.com/repos/symfony/clock/zipball/945ea3b64d6da9c1c2c354fe5c07b27455df6442",+ "reference": "945ea3b64d6da9c1c2c354fe5c07b27455df6442","shasum": ""},"require": {@@ -7573,7 +7584,7 @@"time"],"support": {- "source": "https://github.com/symfony/clock/tree/v8.1.0"+ "source": "https://github.com/symfony/clock/tree/v8.1.9"},"funding": [{@@ -7593,20 +7604,20 @@"type": "tidelift"}],- "time": "2026-05-29T05:06:50+00:00"+ "time": "2026-10-12T14:32:04+00:00"},{"name": "symfony/console",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/console.git",- "reference": "535e18a1b8925f6c01a55b171d157ab66c2ace15"+ "reference": "5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/console/zipball/535e18a1b8925f6c01a55b171d157ab66c2ace15",- "reference": "535e18a1b8925f6c01a55b171d157ab66c2ace15",+ "url": "https://api.github.com/repos/symfony/console/zipball/5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083",+ "reference": "5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083","shasum": ""},"require": {@@ -7673,7 +7684,7 @@"terminal"],"support": {- "source": "https://github.com/symfony/console/tree/v8.1.2"+ "source": "https://github.com/symfony/console/tree/v8.1.10"},"funding": [{@@ -7693,7 +7704,7 @@"type": "tidelift"}],- "time": "2026-07-27T13:58:19+00:00"+ "time": "2026-10-28T11:16:19+00:00"},{"name": "symfony/css-selector",@@ -7907,16 +7918,16 @@},{"name": "symfony/error-handler",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/error-handler.git",- "reference": "dc98404be5e8c949815e23fee1928f5de4f3f5d3"+ "reference": "84c6d73f990ae22dbd45625c056d7ff99ca6810d"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/error-handler/zipball/dc98404be5e8c949815e23fee1928f5de4f3f5d3",- "reference": "dc98404be5e8c949815e23fee1928f5de4f3f5d3",+ "url": "https://api.github.com/repos/symfony/error-handler/zipball/84c6d73f990ae22dbd45625c056d7ff99ca6810d",+ "reference": "84c6d73f990ae22dbd45625c056d7ff99ca6810d","shasum": ""},"require": {@@ -7964,7 +7975,7 @@"description": "Provides tools to manage errors and ease debugging PHP code","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/error-handler/tree/v8.1.2"+ "source": "https://github.com/symfony/error-handler/tree/v8.1.10"},"funding": [{@@ -7984,20 +7995,20 @@"type": "tidelift"}],- "time": "2026-07-22T15:42:13+00:00"+ "time": "2026-10-25T14:40:25+00:00"},{"name": "symfony/event-dispatcher",- "version": "v8.1.2",+ "version": "v8.1.5","source": {"type": "git","url": "https://github.com/symfony/event-dispatcher.git",- "reference": "c14c05a9e6da7f5e375e6efc28952c7e7dbddffb"+ "reference": "7458da64220376b2e0dc2d8451bf43382c1ad297"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/c14c05a9e6da7f5e375e6efc28952c7e7dbddffb",- "reference": "c14c05a9e6da7f5e375e6efc28952c7e7dbddffb",+ "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/7458da64220376b2e0dc2d8451bf43382c1ad297",+ "reference": "7458da64220376b2e0dc2d8451bf43382c1ad297","shasum": ""},"require": {@@ -8050,7 +8061,7 @@"description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/event-dispatcher/tree/v8.1.2"+ "source": "https://github.com/symfony/event-dispatcher/tree/v8.1.5"},"funding": [{@@ -8070,7 +8081,7 @@"type": "tidelift"}],- "time": "2026-07-22T15:42:13+00:00"+ "time": "2026-08-21T17:47:34+00:00"},{"name": "symfony/event-dispatcher-contracts",@@ -8225,16 +8236,16 @@},{"name": "symfony/finder",- "version": "v8.1.1",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/finder.git",- "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531"+ "reference": "2f4c0f26106520d82e1b71759d2fb8d32d8b7a43"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/finder/zipball/e2989e762c70f9490fa3a00a0ac0fae5aa97a531",- "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531",+ "url": "https://api.github.com/repos/symfony/finder/zipball/2f4c0f26106520d82e1b71759d2fb8d32d8b7a43",+ "reference": "2f4c0f26106520d82e1b71759d2fb8d32d8b7a43","shasum": ""},"require": {@@ -8269,7 +8280,7 @@"description": "Finds files and directories via an intuitive fluent interface","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/finder/tree/v8.1.1"+ "source": "https://github.com/symfony/finder/tree/v8.1.10"},"funding": [{@@ -8289,20 +8300,20 @@"type": "tidelift"}],- "time": "2026-06-27T09:05:56+00:00"+ "time": "2026-10-19T17:00:07+00:00"},{"name": "symfony/http-foundation",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/http-foundation.git",- "reference": "9943adbf5a64e2951a8d9eb0485310d55624f0e8"+ "reference": "79325f87c3a2acc7564ddce9f457046e980e7255"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/http-foundation/zipball/9943adbf5a64e2951a8d9eb0485310d55624f0e8",- "reference": "9943adbf5a64e2951a8d9eb0485310d55624f0e8",+ "url": "https://api.github.com/repos/symfony/http-foundation/zipball/79325f87c3a2acc7564ddce9f457046e980e7255",+ "reference": "79325f87c3a2acc7564ddce9f457046e980e7255","shasum": ""},"require": {@@ -8350,7 +8361,7 @@"description": "Defines an object-oriented layer for the HTTP specification","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/http-foundation/tree/v8.1.2"+ "source": "https://github.com/symfony/http-foundation/tree/v8.1.10"},"funding": [{@@ -8370,20 +8381,20 @@"type": "tidelift"}],- "time": "2026-07-29T07:22:54+00:00"+ "time": "2026-10-27T12:24:10+00:00"},{"name": "symfony/http-kernel",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/http-kernel.git",- "reference": "c7bb08dc26a7a7da68fb7ac1ce9de925e6464dbc"+ "reference": "924974dbdcdf4cc40d7bb2c65ae83bb6dc67cff1"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/http-kernel/zipball/c7bb08dc26a7a7da68fb7ac1ce9de925e6464dbc",- "reference": "c7bb08dc26a7a7da68fb7ac1ce9de925e6464dbc",+ "url": "https://api.github.com/repos/symfony/http-kernel/zipball/924974dbdcdf4cc40d7bb2c65ae83bb6dc67cff1",+ "reference": "924974dbdcdf4cc40d7bb2c65ae83bb6dc67cff1","shasum": ""},"require": {@@ -8460,7 +8471,7 @@"description": "Provides a structured process for converting a Request into a Response","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/http-kernel/tree/v8.1.2"+ "source": "https://github.com/symfony/http-kernel/tree/v8.1.10"},"funding": [{@@ -8480,20 +8491,20 @@"type": "tidelift"}],- "time": "2026-07-29T11:54:54+00:00"+ "time": "2026-10-28T18:22:19+00:00"},{"name": "symfony/mailer",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/mailer.git",- "reference": "221c7f326ace1ac2baee8331d829d5b7f04f4d53"+ "reference": "4ba81a8f04fbf0bb1691f7bff760b301f1956fd7"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/mailer/zipball/221c7f326ace1ac2baee8331d829d5b7f04f4d53",- "reference": "221c7f326ace1ac2baee8331d829d5b7f04f4d53",+ "url": "https://api.github.com/repos/symfony/mailer/zipball/4ba81a8f04fbf0bb1691f7bff760b301f1956fd7",+ "reference": "4ba81a8f04fbf0bb1691f7bff760b301f1956fd7","shasum": ""},"require": {@@ -8540,7 +8551,7 @@"description": "Helps sending emails","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/mailer/tree/v8.1.2"+ "source": "https://github.com/symfony/mailer/tree/v8.1.10"},"funding": [{@@ -8560,20 +8571,20 @@"type": "tidelift"}],- "time": "2026-07-28T07:35:25+00:00"+ "time": "2026-10-23T17:06:53+00:00"},{"name": "symfony/mime",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/mime.git",- "reference": "75f4779d4ec2e13f24a3a7e5d0347c340c7ca627"+ "reference": "8d1232052c9cdef170ed9608b3147bca4f61ff69"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/mime/zipball/75f4779d4ec2e13f24a3a7e5d0347c340c7ca627",- "reference": "75f4779d4ec2e13f24a3a7e5d0347c340c7ca627",+ "url": "https://api.github.com/repos/symfony/mime/zipball/8d1232052c9cdef170ed9608b3147bca4f61ff69",+ "reference": "8d1232052c9cdef170ed9608b3147bca4f61ff69","shasum": ""},"require": {@@ -8594,7 +8605,7 @@"symfony/process": "^7.4|^8.0","symfony/property-access": "^7.4|^8.0","symfony/property-info": "^7.4|^8.0",- "symfony/serializer": "^7.4|^8.0"+ "symfony/serializer": "^7.4.17|^8.1.5"},"type": "library","autoload": {@@ -8626,7 +8637,7 @@"mime-type"],"support": {- "source": "https://github.com/symfony/mime/tree/v8.1.2"+ "source": "https://github.com/symfony/mime/tree/v8.1.10"},"funding": [{@@ -8646,7 +8657,7 @@"type": "tidelift"}],- "time": "2026-07-29T08:00:47+00:00"+ "time": "2026-10-28T17:58:38+00:00"},{"name": "symfony/polyfill-ctype",@@ -8733,16 +8744,16 @@},{"name": "symfony/polyfill-intl-grapheme",- "version": "v1.41.0",+ "version": "v1.43.3","source": {"type": "git","url": "https://github.com/symfony/polyfill-intl-grapheme.git",- "reference": "bb899c1db0aa8127dc3afe8cda4a67eb24915f8d"+ "reference": "5a8f33c87aeecffce24e721b5064fab05f4becf8"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/bb899c1db0aa8127dc3afe8cda4a67eb24915f8d",- "reference": "bb899c1db0aa8127dc3afe8cda4a67eb24915f8d",+ "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/5a8f33c87aeecffce24e721b5064fab05f4becf8",+ "reference": "5a8f33c87aeecffce24e721b5064fab05f4becf8","shasum": ""},"require": {@@ -8791,7 +8802,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.41.0"+ "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.43.3"},"funding": [{@@ -8811,7 +8822,7 @@"type": "tidelift"}],- "time": "2026-07-28T08:25:59+00:00"+ "time": "2026-10-15T09:18:53+00:00"},{"name": "symfony/polyfill-intl-icu",@@ -8903,16 +8914,16 @@},{"name": "symfony/polyfill-intl-idn",- "version": "v1.38.1",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-intl-idn.git",- "reference": "dc21118016c039a66235cf93d96b435ffb282412"+ "reference": "533d68cf99c8f8ee2e8893c59ed59192e92cfd74"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/dc21118016c039a66235cf93d96b435ffb282412",- "reference": "dc21118016c039a66235cf93d96b435ffb282412",+ "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/533d68cf99c8f8ee2e8893c59ed59192e92cfd74",+ "reference": "533d68cf99c8f8ee2e8893c59ed59192e92cfd74","shasum": ""},"require": {@@ -8966,7 +8977,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.38.1"+ "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.43.0"},"funding": [{@@ -8986,20 +8997,20 @@"type": "tidelift"}],- "time": "2026-05-25T15:22:23+00:00"+ "time": "2026-09-23T14:40:04+00:00"},{"name": "symfony/polyfill-intl-normalizer",- "version": "v1.38.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-intl-normalizer.git",- "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b"+ "reference": "ebd57ccc7edb93d632e184efbe7693d2517bab3b"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/2d446c214bdbe5b71bde5011b060a05fece3ae6b",- "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b",+ "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/ebd57ccc7edb93d632e184efbe7693d2517bab3b",+ "reference": "ebd57ccc7edb93d632e184efbe7693d2517bab3b","shasum": ""},"require": {@@ -9051,7 +9062,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.38.0"+ "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.43.0"},"funding": [{@@ -9071,20 +9082,20 @@"type": "tidelift"}],- "time": "2026-05-25T13:48:31+00:00"+ "time": "2026-09-23T22:02:09+00:00"},{"name": "symfony/polyfill-mbstring",- "version": "v1.38.2",+ "version": "v1.43.3","source": {"type": "git","url": "https://github.com/symfony/polyfill-mbstring.git",- "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6"+ "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6",- "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6",+ "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/122889ed24dc000165bcbfd77ec412f15cbdfc6a",+ "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a","shasum": ""},"require": {@@ -9136,7 +9147,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.38.2"+ "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.3"},"funding": [{@@ -9156,20 +9167,20 @@"type": "tidelift"}],- "time": "2026-05-27T06:59:30+00:00"+ "time": "2026-10-28T09:35:49+00:00"},{"name": "symfony/polyfill-php80",- "version": "v1.37.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-php80.git",- "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"+ "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",- "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",+ "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74",+ "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74","shasum": ""},"require": {@@ -9220,7 +9231,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"+ "source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0"},"funding": [{@@ -9240,20 +9251,20 @@"type": "tidelift"}],- "time": "2026-04-10T16:19:22+00:00"+ "time": "2026-09-25T15:50:05+00:00"},{"name": "symfony/polyfill-php83",- "version": "v1.41.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-php83.git",- "reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6"+ "reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/5ea99087fb99c273a9b9236ed4c31e78b16103c6",- "reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6",+ "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/80ccff923a8d61f73ebe9da0aa94e25232f004ce",+ "reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce","shasum": ""},"require": {@@ -9300,7 +9311,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-php83/tree/v1.41.0"+ "source": "https://github.com/symfony/polyfill-php83/tree/v1.43.0"},"funding": [{@@ -9320,20 +9331,20 @@"type": "tidelift"}],- "time": "2026-07-01T12:47:55+00:00"+ "time": "2026-09-25T15:50:05+00:00"},{"name": "symfony/polyfill-php84",- "version": "v1.38.1",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-php84.git",- "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa"+ "reference": "22c6548499cbe5c5bb072fc0c42312dff062a015"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa",- "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa",+ "url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/22c6548499cbe5c5bb072fc0c42312dff062a015",+ "reference": "22c6548499cbe5c5bb072fc0c42312dff062a015","shasum": ""},"require": {@@ -9380,7 +9391,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-php84/tree/v1.38.1"+ "source": "https://github.com/symfony/polyfill-php84/tree/v1.43.0"},"funding": [{@@ -9400,20 +9411,20 @@"type": "tidelift"}],- "time": "2026-05-26T12:51:13+00:00"+ "time": "2026-09-23T22:01:09+00:00"},{"name": "symfony/polyfill-php85",- "version": "v1.41.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-php85.git",- "reference": "255fab485aaa1006ed411040c42aecd7b5302d7a"+ "reference": "86a42cbcc07adc331481a5ab310a4024bfc227f6"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/255fab485aaa1006ed411040c42aecd7b5302d7a",- "reference": "255fab485aaa1006ed411040c42aecd7b5302d7a",+ "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/86a42cbcc07adc331481a5ab310a4024bfc227f6",+ "reference": "86a42cbcc07adc331481a5ab310a4024bfc227f6","shasum": ""},"require": {@@ -9460,7 +9471,7 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-php85/tree/v1.41.0"+ "source": "https://github.com/symfony/polyfill-php85/tree/v1.43.0"},"funding": [{@@ -9480,20 +9491,20 @@"type": "tidelift"}],- "time": "2026-07-01T12:47:55+00:00"+ "time": "2026-09-25T15:46:47+00:00"},{"name": "symfony/polyfill-php86",- "version": "v1.41.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-php86.git",- "reference": "6bc356ed3d8dbfeea8f0de235e34d670704e880e"+ "reference": "8840df45b24f33a49dc419fa18dc0057231ae1d8"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-php86/zipball/6bc356ed3d8dbfeea8f0de235e34d670704e880e",- "reference": "6bc356ed3d8dbfeea8f0de235e34d670704e880e",+ "url": "https://api.github.com/repos/symfony/polyfill-php86/zipball/8840df45b24f33a49dc419fa18dc0057231ae1d8",+ "reference": "8840df45b24f33a49dc419fa18dc0057231ae1d8","shasum": ""},"require": {@@ -9540,7 +9551,90 @@"shim"],"support": {- "source": "https://github.com/symfony/polyfill-php86/tree/v1.41.0"+ "source": "https://github.com/symfony/polyfill-php86/tree/v1.43.0"+ },+ "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-09-25T15:46:47+00:00"+ },+ {+ "name": "symfony/polyfill-time",+ "version": "v1.42.0",+ "source": {+ "type": "git",+ "url": "https://github.com/symfony/polyfill-time.git",+ "reference": "ac9f1ed802dd58f37e720388130c088434aa09fc"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/symfony/polyfill-time/zipball/ac9f1ed802dd58f37e720388130c088434aa09fc",+ "reference": "ac9f1ed802dd58f37e720388130c088434aa09fc",+ "shasum": ""+ },+ "require": {+ "php": ">=8.1"+ },+ "type": "library",+ "extra": {+ "thanks": {+ "url": "https://github.com/symfony/polyfill",+ "name": "symfony/polyfill"+ }+ },+ "autoload": {+ "psr-4": {+ "Symfony\\Polyfill\\Time\\": ""+ },+ "classmap": [+ "Resources/stubs"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Ignace Philippe Nyamagana Butera",+ "email": "[email protected]"+ },+ {+ "name": "Tim Düsterhus",+ "email": "[email protected]"+ },+ {+ "name": "Symfony Community",+ "homepage": "https://symfony.com/contributors"+ }+ ],+ "description": "Symfony polyfill for the Time API added to PHP 8.6",+ "homepage": "https://symfony.com",+ "keywords": [+ "compatibility",+ "duration",+ "polyfill",+ "portable",+ "shim",+ "time"+ ],+ "support": {+ "source": "https://github.com/symfony/polyfill-time/tree/v1.42.0"},"funding": [{@@ -9560,20 +9654,20 @@"type": "tidelift"}],- "time": "2026-07-02T13:42:24+00:00"+ "time": "2026-08-07T13:08:13+00:00"},{"name": "symfony/polyfill-uuid",- "version": "v1.37.0",+ "version": "v1.43.0","source": {"type": "git","url": "https://github.com/symfony/polyfill-uuid.git",- "reference": "26dfec253c4cf3e51b541b52ddf7e42cb0908e94"+ "reference": "b23ff8245cc5c4479ea2be3d0132d2e6dd433993"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/polyfill-uuid/zipball/26dfec253c4cf3e51b541b52ddf7e42cb0908e94",- "reference": "26dfec253c4cf3e51b541b52ddf7e42cb0908e94",+ "url": "https://api.github.com/repos/symfony/polyfill-uuid/zipball/b23ff8245cc5c4479ea2be3d0132d2e6dd433993",+ "reference": "b23ff8245cc5c4479ea2be3d0132d2e6dd433993","shasum": ""},"require": {@@ -9623,7 +9717,7 @@"uuid"],"support": {- "source": "https://github.com/symfony/polyfill-uuid/tree/v1.37.0"+ "source": "https://github.com/symfony/polyfill-uuid/tree/v1.43.0"},"funding": [{@@ -9643,20 +9737,20 @@"type": "tidelift"}],- "time": "2026-04-10T16:19:22+00:00"+ "time": "2026-09-24T05:20:52+00:00"},{"name": "symfony/process",- "version": "v8.1.0",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/process.git",- "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5"+ "reference": "08aa69fa0998bb65a089f9e148a2c0f8b391398e"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/process/zipball/c4a9e58f235a6bf7f97ffbfedae2687353ac79e5",- "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5",+ "url": "https://api.github.com/repos/symfony/process/zipball/08aa69fa0998bb65a089f9e148a2c0f8b391398e",+ "reference": "08aa69fa0998bb65a089f9e148a2c0f8b391398e","shasum": ""},"require": {@@ -9688,7 +9782,7 @@"description": "Executes commands in sub-processes","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/process/tree/v8.1.0"+ "source": "https://github.com/symfony/process/tree/v8.1.10"},"funding": [{@@ -9708,7 +9802,7 @@"type": "tidelift"}],- "time": "2026-05-29T05:06:50+00:00"+ "time": "2026-10-25T14:40:25+00:00"},{"name": "symfony/psr-http-message-bridge",@@ -9799,16 +9893,16 @@},{"name": "symfony/routing",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/routing.git",- "reference": "1058d4e13bb81dd9a6f7565686df7e13b880cdbd"+ "reference": "41b32d2c5d907abe2c3ffaa7a112dd7492353822"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/routing/zipball/1058d4e13bb81dd9a6f7565686df7e13b880cdbd",- "reference": "1058d4e13bb81dd9a6f7565686df7e13b880cdbd",+ "url": "https://api.github.com/repos/symfony/routing/zipball/41b32d2c5d907abe2c3ffaa7a112dd7492353822",+ "reference": "41b32d2c5d907abe2c3ffaa7a112dd7492353822","shasum": ""},"require": {@@ -9855,7 +9949,7 @@"url"],"support": {- "source": "https://github.com/symfony/routing/tree/v8.1.2"+ "source": "https://github.com/symfony/routing/tree/v8.1.10"},"funding": [{@@ -9875,20 +9969,20 @@"type": "tidelift"}],- "time": "2026-07-22T15:42:13+00:00"+ "time": "2026-10-26T21:55:04+00:00"},{"name": "symfony/service-contracts",- "version": "v3.7.1",+ "version": "v3.7.3","source": {"type": "git","url": "https://github.com/symfony/service-contracts.git",- "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0"+ "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/service-contracts/zipball/c0a284bab1ed8aa0417e3d69250ab437739563a0",- "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0",+ "url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257",+ "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257","shasum": ""},"require": {@@ -9942,7 +10036,7 @@"standards"],"support": {- "source": "https://github.com/symfony/service-contracts/tree/v3.7.1"+ "source": "https://github.com/symfony/service-contracts/tree/v3.7.3"},"funding": [{@@ -9962,20 +10056,20 @@"type": "tidelift"}],- "time": "2026-06-16T09:55:08+00:00"+ "time": "2026-07-27T15:39:01+00:00"},{"name": "symfony/string",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/string.git",- "reference": "286a76b7255e5cc4bf0101a0bc5388ecf1c38ccc"+ "reference": "6c6110979c0150393bbb336170e286d51ab4d76c"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/string/zipball/286a76b7255e5cc4bf0101a0bc5388ecf1c38ccc",- "reference": "286a76b7255e5cc4bf0101a0bc5388ecf1c38ccc",+ "url": "https://api.github.com/repos/symfony/string/zipball/6c6110979c0150393bbb336170e286d51ab4d76c",+ "reference": "6c6110979c0150393bbb336170e286d51ab4d76c","shasum": ""},"require": {@@ -10032,7 +10126,7 @@"utf8"],"support": {- "source": "https://github.com/symfony/string/tree/v8.1.2"+ "source": "https://github.com/symfony/string/tree/v8.1.10"},"funding": [{@@ -10052,20 +10146,20 @@"type": "tidelift"}],- "time": "2026-07-28T07:35:25+00:00"+ "time": "2026-10-23T17:06:53+00:00"},{"name": "symfony/translation",- "version": "v8.1.1",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/translation.git",- "reference": "342b4218630dc2cf284cedcb2080c80b13404014"+ "reference": "8fbbb32f4bbbece5079acb01ab648fd20583fc93"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/translation/zipball/342b4218630dc2cf284cedcb2080c80b13404014",- "reference": "342b4218630dc2cf284cedcb2080c80b13404014",+ "url": "https://api.github.com/repos/symfony/translation/zipball/8fbbb32f4bbbece5079acb01ab648fd20583fc93",+ "reference": "8fbbb32f4bbbece5079acb01ab648fd20583fc93","shasum": ""},"require": {@@ -10125,7 +10219,7 @@"description": "Provides tools to internationalize your application","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/translation/tree/v8.1.1"+ "source": "https://github.com/symfony/translation/tree/v8.1.10"},"funding": [{@@ -10145,7 +10239,7 @@"type": "tidelift"}],- "time": "2026-06-06T11:11:44+00:00"+ "time": "2026-10-25T14:40:25+00:00"},{"name": "symfony/translation-contracts",@@ -10231,16 +10325,16 @@},{"name": "symfony/uid",- "version": "v8.1.0",+ "version": "v8.1.9","source": {"type": "git","url": "https://github.com/symfony/uid.git",- "reference": "7393f157a55f7e70a4de0334435c55a5a8fe749a"+ "reference": "cb487cf30380f0b0b090973bb9c0588193c06685"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/uid/zipball/7393f157a55f7e70a4de0334435c55a5a8fe749a",- "reference": "7393f157a55f7e70a4de0334435c55a5a8fe749a",+ "url": "https://api.github.com/repos/symfony/uid/zipball/cb487cf30380f0b0b090973bb9c0588193c06685",+ "reference": "cb487cf30380f0b0b090973bb9c0588193c06685","shasum": ""},"require": {@@ -10285,7 +10379,7 @@"uuid"],"support": {- "source": "https://github.com/symfony/uid/tree/v8.1.0"+ "source": "https://github.com/symfony/uid/tree/v8.1.9"},"funding": [{@@ -10305,20 +10399,20 @@"type": "tidelift"}],- "time": "2026-05-29T05:06:50+00:00"+ "time": "2026-10-12T14:32:04+00:00"},{"name": "symfony/var-dumper",- "version": "v8.1.2",+ "version": "v8.1.10","source": {"type": "git","url": "https://github.com/symfony/var-dumper.git",- "reference": "865103cf742a039f34645b971fc3ace308d6c167"+ "reference": "3412a5af7d34a19515a77890fc804fe8e50d1a4f"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/var-dumper/zipball/865103cf742a039f34645b971fc3ace308d6c167",- "reference": "865103cf742a039f34645b971fc3ace308d6c167",+ "url": "https://api.github.com/repos/symfony/var-dumper/zipball/3412a5af7d34a19515a77890fc804fe8e50d1a4f",+ "reference": "3412a5af7d34a19515a77890fc804fe8e50d1a4f","shasum": ""},"require": {@@ -10372,7 +10466,7 @@"dump"],"support": {- "source": "https://github.com/symfony/var-dumper/tree/v8.1.2"+ "source": "https://github.com/symfony/var-dumper/tree/v8.1.10"},"funding": [{@@ -10392,7 +10486,7 @@"type": "tidelift"}],- "time": "2026-07-22T15:42:13+00:00"+ "time": "2026-10-26T21:55:04+00:00"},{"name": "symfony/yaml",@@ -10527,23 +10621,23 @@},{"name": "vlucas/phpdotenv",- "version": "v5.6.4",+ "version": "v5.8.0","source": {"type": "git",- "url": "https://github.com/vlucas/phpdotenv.git",- "reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b"+ "url": "https://github.com/phpdotenv/phpdotenv.git",+ "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/416df702837983f8d5ff48c9c3fee4f5f57b980b",- "reference": "416df702837983f8d5ff48c9c3fee4f5f57b980b",+ "url": "https://api.github.com/repos/phpdotenv/phpdotenv/zipball/96149103e62ac67e915f6d2ef59b72dee2e011e0",+ "reference": "96149103e62ac67e915f6d2ef59b72dee2e011e0","shasum": ""},"require": {"ext-pcre": "*",- "graham-campbell/result-type": "^1.1.4",+ "graham-campbell/result-type": "^1.2","php": "^7.2.5 || ^8.0",- "phpoption/phpoption": "^1.9.5",+ "phpoption/phpoption": "^1.10","symfony/polyfill-ctype": "^1.26","symfony/polyfill-mbstring": "^1.26","symfony/polyfill-php80": "^1.26"@@ -10563,7 +10657,7 @@"forward-command": false},"branch-alias": {- "dev-master": "5.6-dev"+ "dev-master": "5.8-dev"}},"autoload": {@@ -10587,15 +10681,15 @@"homepage": "https://github.com/vlucas"}],- "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.",+ "description": "Loads environment variables from `.env` to `$_ENV` and `$_SERVER` automagically, and optionally to `getenv()`.","keywords": ["dotenv","env","environment"],"support": {- "issues": "https://github.com/vlucas/phpdotenv/issues",- "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.4"+ "issues": "https://github.com/phpdotenv/phpdotenv/issues",+ "source": "https://github.com/phpdotenv/phpdotenv/tree/v5.8.0"},"funding": [{@@ -10607,7 +10701,7 @@"type": "tidelift"}],- "time": "2026-07-06T19:11:50+00:00"+ "time": "2026-10-25T16:26:19+00:00"},{"name": "voku/portable-ascii",@@ -10908,16 +11002,16 @@},{"name": "amphp/dns",- "version": "v2.4.0",+ "version": "v2.4.1","source": {"type": "git","url": "https://github.com/amphp/dns.git",- "reference": "78eb3db5fc69bf2fc0cb503c4fcba667bc223c71"+ "reference": "ec5948bfafac808f410406e18bc7b52a2d4629b7"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/amphp/dns/zipball/78eb3db5fc69bf2fc0cb503c4fcba667bc223c71",- "reference": "78eb3db5fc69bf2fc0cb503c4fcba667bc223c71",+ "url": "https://api.github.com/repos/amphp/dns/zipball/ec5948bfafac808f410406e18bc7b52a2d4629b7",+ "reference": "ec5948bfafac808f410406e18bc7b52a2d4629b7","shasum": ""},"require": {@@ -10936,7 +11030,7 @@"amphp/php-cs-fixer-config": "^2","amphp/phpunit-util": "^3","phpunit/phpunit": "^9",- "psalm/phar": "5.20"+ "psalm/phar": "6.16.1"},"type": "library","autoload": {@@ -10985,7 +11079,7 @@],"support": {"issues": "https://github.com/amphp/dns/issues",- "source": "https://github.com/amphp/dns/tree/v2.4.0"+ "source": "https://github.com/amphp/dns/tree/v2.4.1"},"funding": [{@@ -10993,7 +11087,7 @@"type": "github"}],- "time": "2025-01-19T15:43:40+00:00"+ "time": "2026-07-26T17:53:54+00:00"},{"name": "amphp/hpack",@@ -11232,16 +11326,16 @@},{"name": "amphp/http-server",- "version": "v3.4.6",+ "version": "v3.4.7","source": {"type": "git","url": "https://github.com/amphp/http-server.git",- "reference": "8a971bf92cf8cf2bc511f37a75b39126d5305315"+ "reference": "aa96ca38c5f822a827236543d5417d0c2a782ef0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/amphp/http-server/zipball/8a971bf92cf8cf2bc511f37a75b39126d5305315",- "reference": "8a971bf92cf8cf2bc511f37a75b39126d5305315",+ "url": "https://api.github.com/repos/amphp/http-server/zipball/aa96ca38c5f822a827236543d5417d0c2a782ef0",+ "reference": "aa96ca38c5f822a827236543d5417d0c2a782ef0","shasum": ""},"require": {@@ -11317,7 +11411,7 @@],"support": {"issues": "https://github.com/amphp/http-server/issues",- "source": "https://github.com/amphp/http-server/tree/v3.4.6"+ "source": "https://github.com/amphp/http-server/tree/v3.4.7"},"funding": [{@@ -11325,7 +11419,7 @@"type": "github"}],- "time": "2026-06-27T10:31:48+00:00"+ "time": "2026-10-04T15:14:17+00:00"},{"name": "amphp/parser",@@ -11593,16 +11687,16 @@},{"name": "amphp/socket",- "version": "v2.4.0",+ "version": "v2.4.1","source": {"type": "git","url": "https://github.com/amphp/socket.git",- "reference": "dadb63c5d3179fd83803e29dfeac27350e619314"+ "reference": "b347be5aff6b2cc025208bb4d896607eb470c018"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/amphp/socket/zipball/dadb63c5d3179fd83803e29dfeac27350e619314",- "reference": "dadb63c5d3179fd83803e29dfeac27350e619314",+ "url": "https://api.github.com/repos/amphp/socket/zipball/b347be5aff6b2cc025208bb4d896607eb470c018",+ "reference": "b347be5aff6b2cc025208bb4d896607eb470c018","shasum": ""},"require": {@@ -11665,7 +11759,7 @@],"support": {"issues": "https://github.com/amphp/socket/issues",- "source": "https://github.com/amphp/socket/tree/v2.4.0"+ "source": "https://github.com/amphp/socket/tree/v2.4.1"},"funding": [{@@ -11673,7 +11767,7 @@"type": "github"}],- "time": "2026-04-19T15:09:56+00:00"+ "time": "2026-08-22T18:13:20+00:00"},{"name": "amphp/sync",@@ -11917,16 +12011,16 @@},{"name": "brianium/paratest",- "version": "v7.23.1",+ "version": "v7.27.5","source": {"type": "git","url": "https://github.com/paratestphp/paratest.git",- "reference": "6b2aaf7d0e8d5220710d78921f28e5464a816596"+ "reference": "fe4a1fd811fd79ead7476fa109c5f4ed721cc18a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/paratestphp/paratest/zipball/6b2aaf7d0e8d5220710d78921f28e5464a816596",- "reference": "6b2aaf7d0e8d5220710d78921f28e5464a816596",+ "url": "https://api.github.com/repos/paratestphp/paratest/zipball/fe4a1fd811fd79ead7476fa109c5f4ed721cc18a",+ "reference": "fe4a1fd811fd79ead7476fa109c5f4ed721cc18a","shasum": ""},"require": {@@ -11934,27 +12028,27 @@"ext-pcre": "*","ext-reflection": "*","ext-simplexml": "*",- "fidry/cpu-core-counter": "^1.3.0",+ "fidry/cpu-core-counter": "^1.4.1","jean85/pretty-package-versions": "^2.1.1",- "php": "~8.4.0 || ~8.5.0",- "phpunit/php-code-coverage": "^14.2.3",- "phpunit/php-file-iterator": "^7",+ "php": "~8.4.0 || ~8.5.0 || ~8.6.0",+ "phpunit/php-code-coverage": "^14.4.1",+ "phpunit/php-file-iterator": "^7.0.2","phpunit/php-timer": "^9",- "phpunit/phpunit": "^13.2.5",- "sebastian/environment": "^9.3.2",- "symfony/console": "^7.4.8 || ^8.1.1",- "symfony/process": "^7.4.8 || ^8.1.0"+ "phpunit/phpunit": "^13.4.3",+ "sebastian/environment": "^9.3.3",+ "symfony/console": "^7.4.20 || ^8.1.8",+ "symfony/process": "^7.4.19 || ^8.1.7"},"require-dev": {"doctrine/coding-standard": "^14.0.0","ext-pcntl": "*","ext-pcov": "*","ext-posix": "*",- "phpstan/phpstan": "^2.2.6",+ "phpstan/phpstan": "^2.3.2","phpstan/phpstan-deprecation-rules": "^2.0.5",- "phpstan/phpstan-phpunit": "^2.0.18",- "phpstan/phpstan-strict-rules": "^2.0.12",- "symfony/filesystem": "^7.4.8 || ^8.1.0"+ "phpstan/phpstan-phpunit": "^2.1.1",+ "phpstan/phpstan-strict-rules": "^2.1.0",+ "symfony/filesystem": "^7.4.18 || ^8.1.6"},"bin": ["bin/paratest",@@ -11994,7 +12088,7 @@],"support": {"issues": "https://github.com/paratestphp/paratest/issues",- "source": "https://github.com/paratestphp/paratest/tree/v7.23.1"+ "source": "https://github.com/paratestphp/paratest/tree/v7.27.5"},"funding": [{@@ -12006,7 +12100,7 @@"type": "paypal"}],- "time": "2026-07-28T13:47:02+00:00"+ "time": "2026-10-29T13:58:46+00:00"},{"name": "daverandom/libdns",@@ -12165,23 +12259,23 @@},{"name": "fidry/cpu-core-counter",- "version": "1.3.0",+ "version": "1.4.1","source": {"type": "git","url": "https://github.com/theofidry/cpu-core-counter.git",- "reference": "db9508f7b1474469d9d3c53b86f817e344732678"+ "reference": "d384a7d0d6e67aa497327260ca95023e92dc2032"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678",- "reference": "db9508f7b1474469d9d3c53b86f817e344732678",+ "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/d384a7d0d6e67aa497327260ca95023e92dc2032",+ "reference": "d384a7d0d6e67aa497327260ca95023e92dc2032","shasum": ""},"require": {"php": "^7.2 || ^8.0"},"require-dev": {- "fidry/makefile": "^0.2.0",+ "fidry/makefile": "^0.2.0 || ^1.1.2","fidry/php-cs-fixer-config": "^1.1.2","phpstan/extension-installer": "^1.2.0","phpstan/phpstan": "^2.0",@@ -12189,6 +12283,7 @@"phpstan/phpstan-phpunit": "^2.0","phpstan/phpstan-strict-rules": "^2.0","phpunit/phpunit": "^8.5.31 || ^9.5.26",+ "symfony/polyfill-mbstring": "^1.33","webmozarts/strict-phpunit": "^7.5"},"type": "library",@@ -12214,7 +12309,7 @@],"support": {"issues": "https://github.com/theofidry/cpu-core-counter/issues",- "source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0"+ "source": "https://github.com/theofidry/cpu-core-counter/tree/1.4.1"},"funding": [{@@ -12222,7 +12317,7 @@"type": "github"}],- "time": "2025-08-14T07:29:31+00:00"+ "time": "2026-09-29T22:11:39+00:00"},{"name": "filp/whoops",@@ -12746,20 +12841,20 @@},{"name": "league/uri-components",- "version": "7.8.1",+ "version": "7.9.1","source": {"type": "git","url": "https://github.com/thephpleague/uri-components.git",- "reference": "848ff9db2f0be06229d6034b7c2e33d41b4fd675"+ "reference": "d831eb3ca07f43b771d7208e13421761efcdf724"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/uri-components/zipball/848ff9db2f0be06229d6034b7c2e33d41b4fd675",- "reference": "848ff9db2f0be06229d6034b7c2e33d41b4fd675",+ "url": "https://api.github.com/repos/thephpleague/uri-components/zipball/d831eb3ca07f43b771d7208e13421761efcdf724",+ "reference": "d831eb3ca07f43b771d7208e13421761efcdf724","shasum": ""},"require": {- "league/uri": "^7.8.1",+ "league/uri": "^7.9.1","php": "^8.1"},"suggest": {@@ -12818,7 +12913,7 @@"docs": "https://uri.thephpleague.com","forum": "https://thephpleague.slack.com","issues": "https://github.com/thephpleague/uri-src/issues",- "source": "https://github.com/thephpleague/uri-components/tree/7.8.1"+ "source": "https://github.com/thephpleague/uri-components/tree/7.9.1"},"funding": [{@@ -12826,7 +12921,7 @@"type": "github"}],- "time": "2026-03-15T20:22:25+00:00"+ "time": "2026-10-27T07:14:23+00:00"},{"name": "mockery/mockery",@@ -12913,20 +13008,20 @@},{"name": "myclabs/deep-copy",- "version": "1.13.4",+ "version": "1.14.0","source": {"type": "git","url": "https://github.com/myclabs/DeepCopy.git",- "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a"+ "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/07d290f0c47959fd5eed98c95ee5602db07e0b6a",- "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a",+ "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae",+ "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae","shasum": ""},"require": {- "php": "^7.1 || ^8.0"+ "php": "^8.0"},"conflict": {"doctrine/collections": "<1.6.8",@@ -12961,15 +13056,15 @@],"support": {"issues": "https://github.com/myclabs/DeepCopy/issues",- "source": "https://github.com/myclabs/DeepCopy/tree/1.13.4"+ "source": "https://github.com/myclabs/DeepCopy/tree/1.14.0"},"funding": [{- "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",- "type": "tidelift"+ "url": "https://github.com/mnapoli",+ "type": "github"}],- "time": "2025-08-01T08:46:24+00:00"+ "time": "2026-08-11T10:17:44+00:00"},{"name": "nunomaduro/collision",@@ -13069,43 +13164,43 @@},{"name": "pestphp/pest",- "version": "v5.0.2",+ "version": "v5.3.4","source": {"type": "git","url": "https://github.com/pestphp/pest.git",- "reference": "ae080becd6f036a2c83d9ebdd90079a06de118b3"+ "reference": "159514bacefb30fd674aa74c52738f8a535bfaa9"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/pestphp/pest/zipball/ae080becd6f036a2c83d9ebdd90079a06de118b3",- "reference": "ae080becd6f036a2c83d9ebdd90079a06de118b3",+ "url": "https://api.github.com/repos/pestphp/pest/zipball/159514bacefb30fd674aa74c52738f8a535bfaa9",+ "reference": "159514bacefb30fd674aa74c52738f8a535bfaa9","shasum": ""},"require": {- "brianium/paratest": "^7.23.1",+ "brianium/paratest": "^7.27.4","nunomaduro/collision": "^8.9.5","nunomaduro/termwind": "^2.4.0","pestphp/pest-plugin": "^5.0.0","pestphp/pest-plugin-arch": "^5.0.0",- "pestphp/pest-plugin-mutate": "^5.0.0",- "pestphp/pest-plugin-profanity": "^5.0.0",+ "pestphp/pest-plugin-mutate": "^5.0.2",+ "pestphp/pest-plugin-profanity": "^5.0.1","php": "^8.4",- "phpunit/phpunit": "^13.2.6",- "symfony/process": "^8.1.0"+ "phpunit/phpunit": "^13.4.5",+ "symfony/process": "^8.1.9"},"conflict": {"filp/whoops": "<2.18.3",- "phpunit/phpunit": ">13.2.6",+ "laravel/boost": "<2.6.0",+ "phpunit/phpunit": ">13.4.5","sebastian/exporter": "<7.0.0","webmozart/assert": "<1.11.0"},"require-dev": {- "laravel/pao": "^1.1.3","pestphp/pest-dev-tools": "^5.0.0",- "pestphp/pest-plugin-browser": "^5.0.0",- "pestphp/pest-plugin-phpstan": "^5.0.0",- "pestphp/pest-plugin-rector": "^5.0.0",- "pestphp/pest-plugin-type-coverage": "^5.0.0",+ "pestphp/pest-plugin-browser": "^5.1.2",+ "pestphp/pest-plugin-phpstan": "^5.2.2",+ "pestphp/pest-plugin-rector": "^5.0.6",+ "pestphp/pest-plugin-type-coverage": "^5.0.3","psy/psysh": "^0.12.24"},"bin": [@@ -13173,7 +13268,7 @@],"support": {"issues": "https://github.com/pestphp/pest/issues",- "source": "https://github.com/pestphp/pest/tree/v5.0.2"+ "source": "https://github.com/pestphp/pest/tree/v5.3.4"},"funding": [{@@ -13185,7 +13280,7 @@"type": "github"}],- "time": "2026-07-29T19:27:11+00:00"+ "time": "2026-10-27T11:04:36+00:00"},{"name": "pestphp/pest-plugin",@@ -13332,38 +13427,38 @@},{"name": "pestphp/pest-plugin-browser",- "version": "v5.0.0",+ "version": "v5.2.0","source": {"type": "git","url": "https://github.com/pestphp/pest-plugin-browser.git",- "reference": "cfe0fc085c2d1ea33d9dec6e014c486ba3e2f525"+ "reference": "2b5c7b51bceba3a04a5ca1c5e3f0bb236f544357"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/pestphp/pest-plugin-browser/zipball/cfe0fc085c2d1ea33d9dec6e014c486ba3e2f525",- "reference": "cfe0fc085c2d1ea33d9dec6e014c486ba3e2f525",+ "url": "https://api.github.com/repos/pestphp/pest-plugin-browser/zipball/2b5c7b51bceba3a04a5ca1c5e3f0bb236f544357",+ "reference": "2b5c7b51bceba3a04a5ca1c5e3f0bb236f544357","shasum": ""},"require": {- "amphp/amp": "^3.1.2",+ "amphp/amp": "^3.1.3","amphp/http-server": "^3.4.6","amphp/websocket-client": "^2.0.2","ext-sockets": "*",- "pestphp/pest": "^5.0.0",+ "pestphp/pest": "^5.2.1","pestphp/pest-plugin": "^5.0.0","php": "^8.4",- "symfony/process": "^8.1.0"+ "symfony/process": "^8.1.7"},"conflict": {"pestphp/pest": "<5.0.0"},"require-dev": {- "livewire/livewire": "^4.3.3",+ "livewire/livewire": "^4.4.7","nunomaduro/collision": "^8.9.5",- "orchestra/testbench": "^11.1",+ "orchestra/testbench": "^11.3","pestphp/pest-dev-tools": "^5.0.0",- "pestphp/pest-plugin-laravel": "^5.0.0",- "pestphp/pest-plugin-type-coverage": "^5.0.0"+ "pestphp/pest-plugin-laravel": "^5.0.1",+ "pestphp/pest-plugin-type-coverage": "^5.0.2"},"type": "library","extra": {@@ -13396,7 +13491,7 @@"unit"],"support": {- "source": "https://github.com/pestphp/pest-plugin-browser/tree/v5.0.0"+ "source": "https://github.com/pestphp/pest-plugin-browser/tree/v5.2.0"},"funding": [{@@ -13412,7 +13507,7 @@"type": "patreon"}],- "time": "2026-07-21T07:48:55+00:00"+ "time": "2026-10-29T06:29:23+00:00"},{"name": "pestphp/pest-plugin-laravel",@@ -13493,31 +13588,32 @@},{"name": "pestphp/pest-plugin-mutate",- "version": "v5.0.0",+ "version": "v5.0.2","source": {"type": "git","url": "https://github.com/pestphp/pest-plugin-mutate.git",- "reference": "fc4a0b3d3bc75bad1148d4c046cf0fa66c508f77"+ "reference": "d0c87110416b699413cc073b8dcc92e440d81931"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/fc4a0b3d3bc75bad1148d4c046cf0fa66c508f77",- "reference": "fc4a0b3d3bc75bad1148d4c046cf0fa66c508f77",+ "url": "https://api.github.com/repos/pestphp/pest-plugin-mutate/zipball/d0c87110416b699413cc073b8dcc92e440d81931",+ "reference": "d0c87110416b699413cc073b8dcc92e440d81931","shasum": ""},"require": {"nikic/php-parser": "^5.8.0","pestphp/pest-plugin": "^5.0.0","php": "^8.4",+ "phpunit/php-code-coverage": "^14.3.0","psr/simple-cache": "^3.0.0"},"conflict": {"pestphp/pest": "<5.0.0"},"require-dev": {- "pestphp/pest": "^5.0.0",+ "pestphp/pest": "^5.0.4","pestphp/pest-dev-tools": "^5.0.0",- "pestphp/pest-plugin-type-coverage": "^5.0.0"+ "pestphp/pest-plugin-type-coverage": "^5.0.2"},"type": "library","autoload": {@@ -13552,7 +13648,7 @@"unit"],"support": {- "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v5.0.0"+ "source": "https://github.com/pestphp/pest-plugin-mutate/tree/v5.0.2"},"funding": [{@@ -13568,20 +13664,20 @@"type": "github"}],- "time": "2026-07-21T07:48:56+00:00"+ "time": "2026-08-10T11:01:27+00:00"},{"name": "pestphp/pest-plugin-profanity",- "version": "v5.0.0",+ "version": "v5.0.1","source": {"type": "git","url": "https://github.com/pestphp/pest-plugin-profanity.git",- "reference": "3dedf9ea6e2876b5b31f7733d3eacbd86f4653b9"+ "reference": "2b5fc73ce561b835ba5bf9596c97a84333af2eb8"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/pestphp/pest-plugin-profanity/zipball/3dedf9ea6e2876b5b31f7733d3eacbd86f4653b9",- "reference": "3dedf9ea6e2876b5b31f7733d3eacbd86f4653b9",+ "url": "https://api.github.com/repos/pestphp/pest-plugin-profanity/zipball/2b5fc73ce561b835ba5bf9596c97a84333af2eb8",+ "reference": "2b5fc73ce561b835ba5bf9596c97a84333af2eb8","shasum": ""},"require": {@@ -13589,7 +13685,8 @@"php": "^8.4"},"conflict": {- "pestphp/pest": "<5.0.0"+ "pestphp/pest": "<5.0.0",+ "phpunit/phpunit": "<13.4.1"},"require-dev": {"faissaloux/pest-plugin-inside": "^1.11",@@ -13625,9 +13722,9 @@"unit"],"support": {- "source": "https://github.com/pestphp/pest-plugin-profanity/tree/v5.0.0"+ "source": "https://github.com/pestphp/pest-plugin-profanity/tree/v5.0.1"},- "time": "2026-07-21T07:48:56+00:00"+ "time": "2026-10-07T19:41:52+00:00"},{"name": "phar-io/manifest",@@ -13749,20 +13846,25 @@},{"name": "phpdocumentor/reflection-common",- "version": "2.2.0",+ "version": "2.2.1","source": {"type": "git","url": "https://github.com/phpDocumentor/ReflectionCommon.git",- "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b"+ "reference": "ee15a5a2022c8383906b225055e9496a6a5e6e3b"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b",- "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b",+ "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/ee15a5a2022c8383906b225055e9496a6a5e6e3b",+ "reference": "ee15a5a2022c8383906b225055e9496a6a5e6e3b","shasum": ""},"require": {- "php": "^7.2 || ^8.0"+ "php": "^7.4 || ^8.0"+ },+ "require-dev": {+ "phpstan/phpstan": "^1.8",+ "phpunit/phpunit": "^9.5",+ "vimeo/psalm": "^4.25"},"type": "library","extra": {@@ -13786,7 +13888,7 @@}],"description": "Common reflection classes used by phpdocumentor to reflect the code structure",- "homepage": "http://www.phpdoc.org",+ "homepage": "https://www.phpdoc.org","keywords": ["FQSEN","phpDocumentor",@@ -13796,9 +13898,9 @@],"support": {"issues": "https://github.com/phpDocumentor/ReflectionCommon/issues",- "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x"+ "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.2.1"},- "time": "2020-06-27T09:03:43+00:00"+ "time": "2025-11-10T21:21:55+00:00"},{"name": "phpdocumentor/reflection-docblock",@@ -13867,16 +13969,16 @@},{"name": "phpdocumentor/type-resolver",- "version": "2.0.0",+ "version": "2.1.0","source": {"type": "git","url": "https://github.com/phpDocumentor/TypeResolver.git",- "reference": "327a05bbee54120d4786a0dc67aad30226ad4cf9"+ "reference": "dbe2133bb23e2e33a6834f4ed417f24a1b167769"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/327a05bbee54120d4786a0dc67aad30226ad4cf9",- "reference": "327a05bbee54120d4786a0dc67aad30226ad4cf9",+ "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/dbe2133bb23e2e33a6834f4ed417f24a1b167769",+ "reference": "dbe2133bb23e2e33a6834f4ed417f24a1b167769","shasum": ""},"require": {@@ -13919,22 +14021,22 @@"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names","support": {"issues": "https://github.com/phpDocumentor/TypeResolver/issues",- "source": "https://github.com/phpDocumentor/TypeResolver/tree/2.0.0"+ "source": "https://github.com/phpDocumentor/TypeResolver/tree/2.1.0"},- "time": "2026-01-06T21:53:42+00:00"+ "time": "2026-09-27T19:32:54+00:00"},{"name": "phpunit/php-code-coverage",- "version": "14.2.4",+ "version": "14.4.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-code-coverage.git",- "reference": "048a5c12bdb4580f4767ce2761793a16b170fbe4"+ "reference": "f1e54f06b6b4cea73cd6104ba3c0cfa0efa6d73f"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/048a5c12bdb4580f4767ce2761793a16b170fbe4",- "reference": "048a5c12bdb4580f4767ce2761793a16b170fbe4",+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f1e54f06b6b4cea73cd6104ba3c0cfa0efa6d73f",+ "reference": "f1e54f06b6b4cea73cd6104ba3c0cfa0efa6d73f","shasum": ""},"require": {@@ -13942,18 +14044,18 @@"ext-libxml": "*","ext-mbstring": "*","ext-xmlwriter": "*",- "nikic/php-parser": "^5.8.0",+ "nikic/php-parser": "^5.9.0","php": ">=8.4",- "phpunit/php-text-template": "^6.0",+ "phpunit/php-text-template": "^6.0.1","sebastian/complexity": "^6.0",- "sebastian/environment": "^9.3.2",+ "sebastian/environment": "^9.3.3","sebastian/git-state": "^1.0",- "sebastian/lines-of-code": "^5.0.1",+ "sebastian/lines-of-code": "^5.0.2","sebastian/version": "^7.0","theseer/tokenizer": "^2.0.1"},"require-dev": {- "phpunit/phpunit": "^13.2.2"+ "phpunit/phpunit": "^13.3.6"},"suggest": {"ext-pcov": "PHP extension that provides line coverage",@@ -13962,7 +14064,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "14.2.x-dev"+ "dev-main": "14.4.x-dev"}},"autoload": {@@ -13991,7 +14093,7 @@"support": {"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues","security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.2.4"+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.4.1"},"funding": [{@@ -14011,27 +14113,27 @@"type": "tidelift"}],- "time": "2026-07-30T17:01:07+00:00"+ "time": "2026-10-03T14:05:38+00:00"},{"name": "phpunit/php-file-iterator",- "version": "7.0.0",+ "version": "7.0.2","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-file-iterator.git",- "reference": "6e5aa1fb0a95b1703d83e721299ee18bb4e2de50"+ "reference": "9bb4e6c58b62c1e043be995c66abec7c97307aae"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/6e5aa1fb0a95b1703d83e721299ee18bb4e2de50",- "reference": "6e5aa1fb0a95b1703d83e721299ee18bb4e2de50",+ "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/9bb4e6c58b62c1e043be995c66abec7c97307aae",+ "reference": "9bb4e6c58b62c1e043be995c66abec7c97307aae","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.3.1"},"type": "library","extra": {@@ -14064,7 +14166,7 @@"support": {"issues": "https://github.com/sebastianbergmann/php-file-iterator/issues","security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy",- "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/7.0.0"+ "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/7.0.2"},"funding": [{@@ -14084,7 +14186,7 @@"type": "tidelift"}],- "time": "2026-02-06T04:33:26+00:00"+ "time": "2026-08-25T14:47:43+00:00"},{"name": "phpunit/php-invoker",@@ -14164,23 +14266,23 @@},{"name": "phpunit/php-text-template",- "version": "6.0.0",+ "version": "6.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/php-text-template.git",- "reference": "a47af19f93f76aa3368303d752aa5272ca3299f4"+ "reference": "97107691cb2b6c743b5e0c44be19e983cb337a02"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/a47af19f93f76aa3368303d752aa5272ca3299f4",- "reference": "a47af19f93f76aa3368303d752aa5272ca3299f4",+ "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/97107691cb2b6c743b5e0c44be19e983cb337a02",+ "reference": "97107691cb2b6c743b5e0c44be19e983cb337a02","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.3.6"},"type": "library","extra": {@@ -14212,7 +14314,7 @@"support": {"issues": "https://github.com/sebastianbergmann/php-text-template/issues","security": "https://github.com/sebastianbergmann/php-text-template/security/policy",- "source": "https://github.com/sebastianbergmann/php-text-template/tree/6.0.0"+ "source": "https://github.com/sebastianbergmann/php-text-template/tree/6.0.1"},"funding": [{@@ -14232,7 +14334,7 @@"type": "tidelift"}],- "time": "2026-02-06T04:36:37+00:00"+ "time": "2026-10-03T04:54:24+00:00"},{"name": "phpunit/php-timer",@@ -14308,16 +14410,16 @@},{"name": "phpunit/phpunit",- "version": "13.2.6",+ "version": "13.4.5","source": {"type": "git","url": "https://github.com/sebastianbergmann/phpunit.git",- "reference": "5d2afe181339a56348ef9a80fa7eb806b7eae508"+ "reference": "941457a4f147a60fe2074d40e1fce0d08ea8d930"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/5d2afe181339a56348ef9a80fa7eb806b7eae508",- "reference": "5d2afe181339a56348ef9a80fa7eb806b7eae508",+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/941457a4f147a60fe2074d40e1fce0d08ea8d930",+ "reference": "941457a4f147a60fe2074d40e1fce0d08ea8d930","shasum": ""},"require": {@@ -14327,27 +14429,27 @@"ext-libxml": "*","ext-mbstring": "*","ext-xmlwriter": "*",- "myclabs/deep-copy": "^1.13.4",+ "myclabs/deep-copy": "^1.14.0","phar-io/manifest": "^2.0.4","phar-io/version": "^3.2.1","php": ">=8.4.1",- "phpunit/php-code-coverage": "^14.2.3",- "phpunit/php-file-iterator": "^7.0.0",+ "phpunit/php-code-coverage": "^14.4.1",+ "phpunit/php-file-iterator": "^7.0.2","phpunit/php-invoker": "^7.0.0",- "phpunit/php-text-template": "^6.0.0",+ "phpunit/php-text-template": "^6.0.1","phpunit/php-timer": "^9.0.0",- "sebastian/cli-parser": "^5.0.0",- "sebastian/comparator": "^8.3.0",- "sebastian/diff": "^9.0",- "sebastian/environment": "^9.3.2",- "sebastian/exporter": "^8.1.1",+ "sebastian/cli-parser": "^5.0.1",+ "sebastian/comparator": "^8.4",+ "sebastian/diff": "^9.0.1",+ "sebastian/environment": "^9.3.3",+ "sebastian/exporter": "^8.2.1","sebastian/file-filter": "^1.0",- "sebastian/git-state": "^1.0",+ "sebastian/git-state": "^1.1","sebastian/global-state": "^9.0.1",- "sebastian/object-enumerator": "^8.0.0",- "sebastian/recursion-context": "^8.0.0",- "sebastian/type": "^7.0.1",- "sebastian/version": "^7.0.0",+ "sebastian/object-enumerator": "^8.1.0",+ "sebastian/recursion-context": "^8.0.1",+ "sebastian/type": "^7.0.2",+ "sebastian/version": "^7.0.1","staabm/side-effects-detector": "^1.0.5"},"bin": [@@ -14356,7 +14458,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "13.2-dev"+ "dev-main": "13.4-dev"}},"autoload": {@@ -14388,7 +14490,7 @@"support": {"issues": "https://github.com/sebastianbergmann/phpunit/issues","security": "https://github.com/sebastianbergmann/phpunit/security/policy",- "source": "https://github.com/sebastianbergmann/phpunit/tree/13.2.6"+ "source": "https://github.com/sebastianbergmann/phpunit/tree/13.4.5"},"funding": [{@@ -14396,7 +14498,7 @@"type": "other"}],- "time": "2026-07-28T14:00:09+00:00"+ "time": "2026-10-27T04:16:22+00:00"},{"name": "revolt/event-loop",@@ -14472,23 +14574,23 @@},{"name": "sebastian/cli-parser",- "version": "5.0.0",+ "version": "5.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/cli-parser.git",- "reference": "48a4654fa5e48c1c81214e9930048a572d4b23ca"+ "reference": "eeb759ad3146b7096fb59c3195d39e071cd409e3"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/48a4654fa5e48c1c81214e9930048a572d4b23ca",- "reference": "48a4654fa5e48c1c81214e9930048a572d4b23ca",+ "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/eeb759ad3146b7096fb59c3195d39e071cd409e3",+ "reference": "eeb759ad3146b7096fb59c3195d39e071cd409e3","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.2.6"},"type": "library","extra": {@@ -14517,7 +14619,7 @@"support": {"issues": "https://github.com/sebastianbergmann/cli-parser/issues","security": "https://github.com/sebastianbergmann/cli-parser/security/policy",- "source": "https://github.com/sebastianbergmann/cli-parser/tree/5.0.0"+ "source": "https://github.com/sebastianbergmann/cli-parser/tree/5.0.1"},"funding": [{@@ -14537,20 +14639,20 @@"type": "tidelift"}],- "time": "2026-02-06T04:39:44+00:00"+ "time": "2026-08-01T04:27:14+00:00"},{"name": "sebastian/comparator",- "version": "8.3.0",+ "version": "8.4.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/comparator.git",- "reference": "c025fc7604afab3f195fab7cdaf72327331af241"+ "reference": "3b070e608146cba00fd6fd1f0ffba89e5a8897fb"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/c025fc7604afab3f195fab7cdaf72327331af241",- "reference": "c025fc7604afab3f195fab7cdaf72327331af241",+ "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/3b070e608146cba00fd6fd1f0ffba89e5a8897fb",+ "reference": "3b070e608146cba00fd6fd1f0ffba89e5a8897fb","shasum": ""},"require": {@@ -14558,10 +14660,10 @@"ext-mbstring": "*","php": ">=8.4","sebastian/diff": "^9.0",- "sebastian/exporter": "^8.1.0"+ "sebastian/exporter": "^8.2"},"require-dev": {- "phpunit/phpunit": "^13.2"+ "phpunit/phpunit": "^13.3"},"suggest": {"ext-bcmath": "For comparing BcMath\\Number objects"@@ -14569,7 +14671,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "8.3-dev"+ "dev-main": "8.4-dev"}},"autoload": {@@ -14609,7 +14711,7 @@"support": {"issues": "https://github.com/sebastianbergmann/comparator/issues","security": "https://github.com/sebastianbergmann/comparator/security/policy",- "source": "https://github.com/sebastianbergmann/comparator/tree/8.3.0"+ "source": "https://github.com/sebastianbergmann/comparator/tree/8.4.0"},"funding": [{@@ -14629,7 +14731,7 @@"type": "tidelift"}],- "time": "2026-06-05T03:06:45+00:00"+ "time": "2026-08-07T07:23:13+00:00"},{"name": "sebastian/complexity",@@ -14703,24 +14805,24 @@},{"name": "sebastian/diff",- "version": "9.0.0",+ "version": "9.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/diff.git",- "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226"+ "reference": "a2df6626c1baf31d5a88674882a3072f151b5a26"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/a3fb6a298a265ff487a91bbea46e03cd01dbb226",- "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226",+ "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/a2df6626c1baf31d5a88674882a3072f151b5a26",+ "reference": "a2df6626c1baf31d5a88674882a3072f151b5a26","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.2",- "symfony/process": "^7.4.13"+ "phpunit/phpunit": "^13.3.1",+ "symfony/process": "^7.4.17"},"type": "library","extra": {@@ -14758,7 +14860,7 @@"support": {"issues": "https://github.com/sebastianbergmann/diff/issues","security": "https://github.com/sebastianbergmann/diff/security/policy",- "source": "https://github.com/sebastianbergmann/diff/tree/9.0.0"+ "source": "https://github.com/sebastianbergmann/diff/tree/9.0.1"},"funding": [{@@ -14778,27 +14880,27 @@"type": "tidelift"}],- "time": "2026-06-05T03:04:51+00:00"+ "time": "2026-08-25T15:38:55+00:00"},{"name": "sebastian/environment",- "version": "9.3.2",+ "version": "9.3.3","source": {"type": "git","url": "https://github.com/sebastianbergmann/environment.git",- "reference": "6c9e487c9eb706a8d258102a1c0b0a3e53e86c2e"+ "reference": "d4dd10267a11055066a2a78ae04583d8ddd4f595"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/6c9e487c9eb706a8d258102a1c0b0a3e53e86c2e",- "reference": "6c9e487c9eb706a8d258102a1c0b0a3e53e86c2e",+ "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/d4dd10267a11055066a2a78ae04583d8ddd4f595",+ "reference": "d4dd10267a11055066a2a78ae04583d8ddd4f595","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.1.11"+ "phpunit/phpunit": "^13.3.6"},"suggest": {"ext-posix": "*"@@ -14834,7 +14936,7 @@"support": {"issues": "https://github.com/sebastianbergmann/environment/issues","security": "https://github.com/sebastianbergmann/environment/security/policy",- "source": "https://github.com/sebastianbergmann/environment/tree/9.3.2"+ "source": "https://github.com/sebastianbergmann/environment/tree/9.3.3"},"funding": [{@@ -14854,34 +14956,34 @@"type": "tidelift"}],- "time": "2026-05-25T13:41:38+00:00"+ "time": "2026-10-01T12:37:56+00:00"},{"name": "sebastian/exporter",- "version": "8.1.1",+ "version": "8.2.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/exporter.git",- "reference": "cfaa77c750dcad6f44c9bac8f62ac486e1c82c26"+ "reference": "24a3b69bba4a12ab615fca9d34680c5598d9ab7a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/cfaa77c750dcad6f44c9bac8f62ac486e1c82c26",- "reference": "cfaa77c750dcad6f44c9bac8f62ac486e1c82c26",+ "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/24a3b69bba4a12ab615fca9d34680c5598d9ab7a",+ "reference": "24a3b69bba4a12ab615fca9d34680c5598d9ab7a","shasum": ""},"require": {"ext-mbstring": "*","php": ">=8.4",- "sebastian/recursion-context": "^8.0"+ "sebastian/recursion-context": "^8.0.1"},"require-dev": {- "phpunit/phpunit": "^13.2.4"+ "phpunit/phpunit": "^13.3"},"type": "library","extra": {"branch-alias": {- "dev-main": "8.1-dev"+ "dev-main": "8.2-dev"}},"autoload": {@@ -14924,7 +15026,7 @@"support": {"issues": "https://github.com/sebastianbergmann/exporter/issues","security": "https://github.com/sebastianbergmann/exporter/security/policy",- "source": "https://github.com/sebastianbergmann/exporter/tree/8.1.1"+ "source": "https://github.com/sebastianbergmann/exporter/tree/8.2.1"},"funding": [{@@ -14944,7 +15046,7 @@"type": "tidelift"}],- "time": "2026-07-13T11:35:11+00:00"+ "time": "2026-08-07T07:22:06+00:00"},{"name": "sebastian/file-filter",@@ -15017,28 +15119,28 @@},{"name": "sebastian/git-state",- "version": "1.0.0",+ "version": "1.1.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/git-state.git",- "reference": "792a952e0eba55b6960a48aeceb9f371aad1f76b"+ "reference": "31a565f463686f0eefa85f899549256bf5805985"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/git-state/zipball/792a952e0eba55b6960a48aeceb9f371aad1f76b",- "reference": "792a952e0eba55b6960a48aeceb9f371aad1f76b",+ "url": "https://api.github.com/repos/sebastianbergmann/git-state/zipball/31a565f463686f0eefa85f899549256bf5805985",+ "reference": "31a565f463686f0eefa85f899549256bf5805985","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.4.3"},"type": "library","extra": {"branch-alias": {- "dev-main": "1.0-dev"+ "dev-main": "1.1-dev"}},"autoload": {@@ -15062,7 +15164,7 @@"support": {"issues": "https://github.com/sebastianbergmann/git-state/issues","security": "https://github.com/sebastianbergmann/git-state/security/policy",- "source": "https://github.com/sebastianbergmann/git-state/tree/1.0.0"+ "source": "https://github.com/sebastianbergmann/git-state/tree/1.1.0"},"funding": [{@@ -15082,7 +15184,7 @@"type": "tidelift"}],- "time": "2026-03-21T12:54:28+00:00"+ "time": "2026-10-21T05:59:52+00:00"},{"name": "sebastian/global-state",@@ -15230,30 +15332,29 @@},{"name": "sebastian/object-enumerator",- "version": "8.0.0",+ "version": "8.1.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/object-enumerator.git",- "reference": "b39ab125fd9a7434b0ecbc4202eebce11a98cfc5"+ "reference": "511064ecde82bd747e2ba2fab3dda8d977b59576"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/b39ab125fd9a7434b0ecbc4202eebce11a98cfc5",- "reference": "b39ab125fd9a7434b0ecbc4202eebce11a98cfc5",+ "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/511064ecde82bd747e2ba2fab3dda8d977b59576",+ "reference": "511064ecde82bd747e2ba2fab3dda8d977b59576","shasum": ""},"require": {"php": ">=8.4",- "sebastian/object-reflector": "^6.0",- "sebastian/recursion-context": "^8.0"+ "sebastian/recursion-context": "^8.0.1"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.3.0"},"type": "library","extra": {"branch-alias": {- "dev-main": "8.0-dev"+ "dev-main": "8.1-dev"}},"autoload": {@@ -15276,7 +15377,7 @@"support": {"issues": "https://github.com/sebastianbergmann/object-enumerator/issues","security": "https://github.com/sebastianbergmann/object-enumerator/security/policy",- "source": "https://github.com/sebastianbergmann/object-enumerator/tree/8.0.0"+ "source": "https://github.com/sebastianbergmann/object-enumerator/tree/8.1.0"},"funding": [{@@ -15296,27 +15397,27 @@"type": "tidelift"}],- "time": "2026-02-06T04:46:36+00:00"+ "time": "2026-08-13T07:05:05+00:00"},{"name": "sebastian/object-reflector",- "version": "6.0.0",+ "version": "6.1.0","source": {"type": "git","url": "https://github.com/sebastianbergmann/object-reflector.git",- "reference": "3ca042c2c60b0eab094f8a1b6a7093f4d4c72200"+ "reference": "f71bbcdc4f95456b4622810bec64eb06372e25b2"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/3ca042c2c60b0eab094f8a1b6a7093f4d4c72200",- "reference": "3ca042c2c60b0eab094f8a1b6a7093f4d4c72200",+ "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/f71bbcdc4f95456b4622810bec64eb06372e25b2",+ "reference": "f71bbcdc4f95456b4622810bec64eb06372e25b2","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.3.0"},"type": "library","extra": {@@ -15344,7 +15445,7 @@"support": {"issues": "https://github.com/sebastianbergmann/object-reflector/issues","security": "https://github.com/sebastianbergmann/object-reflector/security/policy",- "source": "https://github.com/sebastianbergmann/object-reflector/tree/6.0.0"+ "source": "https://github.com/sebastianbergmann/object-reflector/tree/6.1.0"},"funding": [{@@ -15364,27 +15465,27 @@"type": "tidelift"}],- "time": "2026-02-06T04:47:13+00:00"+ "time": "2026-08-13T06:34:36+00:00"},{"name": "sebastian/recursion-context",- "version": "8.0.0",+ "version": "8.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/recursion-context.git",- "reference": "74c5af21f6a5833e91767ca068c4d3dfec15317e"+ "reference": "32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/74c5af21f6a5833e91767ca068c4d3dfec15317e",- "reference": "74c5af21f6a5833e91767ca068c4d3dfec15317e",+ "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0",+ "reference": "32dba72f2b4642d6a93db22d6c0a9280ff2e3ca0","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.0"+ "phpunit/phpunit": "^13.2.6"},"type": "library","extra": {@@ -15420,7 +15521,7 @@"support": {"issues": "https://github.com/sebastianbergmann/recursion-context/issues","security": "https://github.com/sebastianbergmann/recursion-context/security/policy",- "source": "https://github.com/sebastianbergmann/recursion-context/tree/8.0.0"+ "source": "https://github.com/sebastianbergmann/recursion-context/tree/8.0.1"},"funding": [{@@ -15440,27 +15541,27 @@"type": "tidelift"}],- "time": "2026-02-06T04:51:28+00:00"+ "time": "2026-08-03T05:58:12+00:00"},{"name": "sebastian/type",- "version": "7.0.1",+ "version": "7.0.2","source": {"type": "git","url": "https://github.com/sebastianbergmann/type.git",- "reference": "fee0309275847fefd7636167085e379c1dbf6990"+ "reference": "bd1df467864cb95140414059a535b2d906173fcf"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/fee0309275847fefd7636167085e379c1dbf6990",- "reference": "fee0309275847fefd7636167085e379c1dbf6990",+ "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/bd1df467864cb95140414059a535b2d906173fcf",+ "reference": "bd1df467864cb95140414059a535b2d906173fcf","shasum": ""},"require": {"php": ">=8.4"},"require-dev": {- "phpunit/phpunit": "^13.1.10"+ "phpunit/phpunit": "^13.3.0"},"type": "library","extra": {@@ -15489,7 +15590,7 @@"support": {"issues": "https://github.com/sebastianbergmann/type/issues","security": "https://github.com/sebastianbergmann/type/security/policy",- "source": "https://github.com/sebastianbergmann/type/tree/7.0.1"+ "source": "https://github.com/sebastianbergmann/type/tree/7.0.2"},"funding": [{@@ -15509,20 +15610,20 @@"type": "tidelift"}],- "time": "2026-05-20T06:49:11+00:00"+ "time": "2026-08-10T08:00:57+00:00"},{"name": "sebastian/version",- "version": "7.0.0",+ "version": "7.0.1","source": {"type": "git","url": "https://github.com/sebastianbergmann/version.git",- "reference": "ad37a5552c8e2b88572249fdc19b6da7792e021b"+ "reference": "f1598cf1d8d1ca4c0f194a52f2fe72a559a7b0b1"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/ad37a5552c8e2b88572249fdc19b6da7792e021b",- "reference": "ad37a5552c8e2b88572249fdc19b6da7792e021b",+ "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/f1598cf1d8d1ca4c0f194a52f2fe72a559a7b0b1",+ "reference": "f1598cf1d8d1ca4c0f194a52f2fe72a559a7b0b1","shasum": ""},"require": {@@ -15555,7 +15656,7 @@"support": {"issues": "https://github.com/sebastianbergmann/version/issues","security": "https://github.com/sebastianbergmann/version/security/policy",- "source": "https://github.com/sebastianbergmann/version/tree/7.0.0"+ "source": "https://github.com/sebastianbergmann/version/tree/7.0.1"},"funding": [{@@ -15575,7 +15676,7 @@"type": "tidelift"}],- "time": "2026-02-06T04:52:52+00:00"+ "time": "2026-10-04T05:51:14+00:00"},{"name": "staabm/side-effects-detector",@@ -15740,16 +15841,16 @@},{"name": "webmozart/assert",- "version": "2.4.1",+ "version": "2.5.0","source": {"type": "git","url": "https://github.com/webmozarts/assert.git",- "reference": "2ccb7c2e821038c03a3e6e1700c570c158c55f70"+ "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/webmozarts/assert/zipball/2ccb7c2e821038c03a3e6e1700c570c158c55f70",- "reference": "2ccb7c2e821038c03a3e6e1700c570c158c55f70",+ "url": "https://api.github.com/repos/webmozarts/assert/zipball/8a163706bbcac613733dba03f51e13b5eb1bb819",+ "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819","shasum": ""},"require": {@@ -15800,9 +15901,9 @@],"support": {"issues": "https://github.com/webmozarts/assert/issues",- "source": "https://github.com/webmozarts/assert/tree/2.4.1"+ "source": "https://github.com/webmozarts/assert/tree/2.5.0"},- "time": "2026-06-15T15:31:57+00:00"+ "time": "2026-10-05T23:14:19+00:00"}],"aliases": [],diff --git a/lang/ar/calendar.php b/lang/ar/calendar.phpindex fa5d11f81..4a9ebf45d 100644--- a/lang/ar/calendar.php+++ b/lang/ar/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count المزيد','less' => 'عرض أقل','empty_day' => 'لا شيء مخطط لهذا اليوم.',+ 'post_status' => [+ 'draft' => 'مسودة',+ 'pending_approval' => 'بانتظار الموافقة',+ 'queue' => 'في قائمة الانتظار',+ 'custom' => 'وقت مخصص',+ 'recurring' => 'متكرر',+ 'publishing' => 'قيد النشر',+ 'published' => 'منشور',+ 'failed' => 'فشل',+ ],'status' => ['label' => 'الحالة','all' => 'كل المنشورات',@@ -31,4 +41,40 @@ return ['draft' => 'مسودة','no_channel' => 'بلا قناة',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'نقل المنشور إلى وقت مخصص',+ 'description' => 'ستنقل هذا المنشور من موعد في قائمة الانتظار، :from، إلى وقت مخصص، :to.',+ 'unqueued' => 'سيُنشر المنشور في الوقت الجديد الذي اخترته، لكنه لن يشغل مكانًا في قائمة الانتظار.',+ 'dont_show_again' => 'عدم الإظهار مرة أخرى',+ 'cancel' => 'إلغاء',+ 'confirm' => 'النقل إلى الوقت المخصص',+ ],+ 'error' => 'تعذّر نقل هذا المنشور. حاول مرة أخرى.',+ 'errors' => [+ 'past' => 'هذا الوقت قد مضى. اختر وقتًا لاحقًا.',+ 'slot_taken' => 'لم يعد هذا الموعد في قائمة الانتظار متاحًا. اختر وقتًا آخر.',+ 'pending' => 'هذا المنشور بانتظار الموافقة. يمكنك نقله بعد الموافقة عليه أو رفضه.',+ 'publishing_soon' => 'هذا المنشور على وشك النشر، لذا لم يعد بالإمكان نقله.',+ 'too_far' => 'اختر تاريخًا قبل 19 يناير 2038.',+ ],+ 'drag_hint' => 'اسحب لإعادة الجدولة',+ 'drag_hint_undated' => 'اسحب المسودة بلا تاريخ الخاصة بـ :channel لجدولتها',+ 'announce' => [+ 'over' => 'العنصر المجدول في :from فوق :target.',+ 'over_undated' => 'المسودة بلا تاريخ الخاصة بـ :channel فوق :target.',+ 'moved' => 'تمت إعادة جدولة العنصر المجدول في :from إلى :to.',+ 'returned' => 'أُعيد العنصر إلى موضعه الأصلي.',+ 'undated' => 'تم إسقاط العنصر المجدول في :from على بلا تاريخ.',+ 'from_undated' => 'تمت جدولة المسودة بلا تاريخ الخاصة بـ :channel في :to.',+ 'date_time' => ':date في :time',+ ],+ 'toast' => [+ 'moved' => 'تمت إعادة جدولة منشورك إلى :time.',+ 'moved_draft' => 'تمت إعادة جدولة مسودتك إلى :time.',+ 'undated' => 'تم نقل مسودتك إلى بلا تاريخ.',+ 'unscheduled' => 'تم نقل منشورك إلى بلا تاريخ كمسودة.',+ 'unqueued_suffix' => 'أصبح الموعد في قائمة الانتظار متاحًا مرة أخرى.',+ ],+ ],];diff --git a/lang/de/calendar.php b/lang/de/calendar.phpindex 62801115b..3eed9a386 100644--- a/lang/de/calendar.php+++ b/lang/de/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count weitere','less' => 'Weniger anzeigen','empty_day' => 'Für diesen Tag ist nichts geplant.',+ 'post_status' => [+ 'draft' => 'Entwurf',+ 'pending_approval' => 'Wartet auf Freigabe',+ 'queue' => 'In der Warteschlange',+ 'custom' => 'Eigene Zeit',+ 'recurring' => 'Wiederkehrend',+ 'publishing' => 'Wird veröffentlicht',+ 'published' => 'Veröffentlicht',+ 'failed' => 'Fehlgeschlagen',+ ],'status' => ['label' => 'Status','all' => 'Alle Beiträge',@@ -31,4 +41,40 @@ return ['draft' => 'Entwurf','no_channel' => 'Kein Kanal',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Beitrag auf eine eigene Uhrzeit verschieben',+ 'description' => 'Du verschiebst diesen Beitrag von seiner Zeit in der Warteschlange, :from, auf eine eigene Uhrzeit, :to.',+ 'unqueued' => 'Der Beitrag wird zur neu gewählten Zeit veröffentlicht, belegt aber keinen Platz in deiner Warteschlange.',+ 'dont_show_again' => 'Nicht mehr zeigen',+ 'cancel' => 'Abbrechen',+ 'confirm' => 'Eigene Zeit nutzen',+ ],+ 'error' => 'Beitrag konnte nicht verschoben werden. Versuche es erneut.',+ 'errors' => [+ 'past' => 'Diese Zeit ist bereits vorbei. Wähle eine spätere Zeit.',+ 'slot_taken' => 'Diese Zeit in der Warteschlange ist nicht mehr frei. Wähle eine andere Zeit.',+ 'pending' => 'Dieser Beitrag wartet auf Freigabe. Verschiebe ihn, sobald er freigegeben oder abgelehnt ist.',+ 'publishing_soon' => 'Dieser Beitrag wird gleich veröffentlicht und kann nicht mehr verschoben werden.',+ 'too_far' => 'Wähle ein Datum vor dem 19. Januar 2038.',+ ],+ 'drag_hint' => 'Zum Verschieben ziehen',+ 'drag_hint_undated' => 'Entwurf ohne Datum für :channel zum Planen ziehen',+ 'announce' => [+ 'over' => 'Element geplant für :from befindet sich über :target.',+ 'over_undated' => 'Entwurf ohne Datum für :channel befindet sich über :target.',+ 'moved' => 'Element geplant für :from wurde auf :to verschoben.',+ 'returned' => 'Element wurde an seiner ursprünglichen Position abgelegt.',+ 'undated' => 'Element geplant für :from wurde auf Ohne Datum abgelegt.',+ 'from_undated' => 'Entwurf ohne Datum für :channel wurde für :to geplant.',+ 'date_time' => ':date um :time',+ ],+ 'toast' => [+ 'moved' => 'Dein Beitrag wurde auf :time verschoben.',+ 'moved_draft' => 'Dein Entwurf wurde auf :time verschoben.',+ 'undated' => 'Dein Entwurf wurde zu Ohne Datum verschoben.',+ 'unscheduled' => 'Dein Beitrag wurde als Entwurf zu Ohne Datum verschoben.',+ 'unqueued_suffix' => 'Die Zeit in der Warteschlange ist wieder frei.',+ ],+ ],];diff --git a/lang/el/calendar.php b/lang/el/calendar.phpindex 6b2519101..13ec6a4b1 100644--- a/lang/el/calendar.php+++ b/lang/el/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count ακόμη','less' => 'Λιγότερα','empty_day' => 'Τίποτα προγραμματισμένο για αυτή την ημέρα.',+ 'post_status' => [+ 'draft' => 'Πρόχειρο',+ 'pending_approval' => 'Σε αναμονή έγκρισης',+ 'queue' => 'Στην ουρά',+ 'custom' => 'Προσαρμοσμένη ώρα',+ 'recurring' => 'Επαναλαμβανόμενη',+ 'publishing' => 'Δημοσιεύεται',+ 'published' => 'Δημοσιεύτηκε',+ 'failed' => 'Απέτυχε',+ ],'status' => ['label' => 'Κατάσταση','all' => 'Όλες οι αναρτήσεις',@@ -31,4 +41,40 @@ return ['draft' => 'Πρόχειρο','no_channel' => 'Χωρίς κανάλι',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Μετακίνηση ανάρτησης σε προσαρμοσμένη ώρα',+ 'description' => 'Μετακινείτε αυτή την ανάρτηση από την ώρα της στην ουρά, :from, σε προσαρμοσμένη ώρα, :to.',+ 'unqueued' => 'Η ανάρτηση θα δημοσιευτεί τη νέα ώρα που επιλέξατε, αλλά δεν θα καταλαμβάνει θέση στην ουρά σας.',+ 'dont_show_again' => 'Να μην εμφανίζεται',+ 'cancel' => 'Ακύρωση',+ 'confirm' => 'Ορισμός ώρας',+ ],+ 'error' => 'Δεν ήταν δυνατή η μετακίνηση. Δοκιμάστε ξανά.',+ 'errors' => [+ 'past' => 'Αυτή η ώρα έχει ήδη περάσει. Επιλέξτε μια μεταγενέστερη ώρα.',+ 'slot_taken' => 'Αυτή η ώρα στην ουρά δεν είναι πια ελεύθερη. Επιλέξτε άλλη ώρα.',+ 'pending' => 'Αυτή η ανάρτηση περιμένει έγκριση. Μετακινήστε την όταν εγκριθεί ή απορριφθεί.',+ 'publishing_soon' => 'Αυτή η ανάρτηση πρόκειται να δημοσιευτεί, οπότε δεν μπορεί πλέον να μετακινηθεί.',+ 'too_far' => 'Επιλέξτε ημερομηνία πριν από τις 19 Ιανουαρίου 2038.',+ ],+ 'drag_hint' => 'Σύρετε για αλλαγή προγραμματισμού',+ 'drag_hint_undated' => 'Σύρετε το πρόχειρο χωρίς ημερομηνία για :channel για να το προγραμματίσετε',+ 'announce' => [+ 'over' => 'το στοιχείο που έχει προγραμματιστεί για :from βρίσκεται πάνω από :target.',+ 'over_undated' => 'Το πρόχειρο χωρίς ημερομηνία για :channel βρίσκεται πάνω από :target.',+ 'moved' => 'το στοιχείο που είχε προγραμματιστεί για :from μετακινήθηκε στις :to.',+ 'returned' => 'Το στοιχείο επέστρεψε στην αρχική του θέση.',+ 'undated' => 'το στοιχείο που είχε προγραμματιστεί για :from αφέθηκε στο Χωρίς ημερομηνία.',+ 'from_undated' => 'Το πρόχειρο χωρίς ημερομηνία για :channel προγραμματίστηκε για :to.',+ 'date_time' => ':date, :time',+ ],+ 'toast' => [+ 'moved' => 'Η δημοσίευσή σας μετακινήθηκε στις :time.',+ 'moved_draft' => 'Το πρόχειρό σας μετακινήθηκε στις :time.',+ 'undated' => 'Το πρόχειρό σας μετακινήθηκε στο Χωρίς ημερομηνία.',+ 'unscheduled' => 'Η ανάρτησή σας μετακινήθηκε στο Χωρίς ημερομηνία ως πρόχειρο.',+ 'unqueued_suffix' => 'Η ώρα στην ουρά είναι πάλι ελεύθερη.',+ ],+ ],];diff --git a/lang/en/calendar.php b/lang/en/calendar.phpindex 54b5c7bce..894281057 100644--- a/lang/en/calendar.php+++ b/lang/en/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count more','less' => 'Show less','empty_day' => 'Nothing planned for this day.',+ 'post_status' => [+ 'draft' => 'Draft',+ 'pending_approval' => 'Pending approval',+ 'queue' => 'In the queue',+ 'custom' => 'Custom time',+ 'recurring' => 'Recurring',+ 'publishing' => 'Publishing',+ 'published' => 'Published',+ 'failed' => 'Failed',+ ],'status' => ['label' => 'Status','all' => 'All posts',@@ -31,4 +41,40 @@ return ['draft' => 'Draft','no_channel' => 'No channel',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Moving post to a custom time',+ 'description' => 'You\'re moving this post from its time in the queue, :from, to a custom time, :to.',+ 'unqueued' => 'The post will be published at the new time you picked, but it won\'t use a spot in your queue.',+ 'dont_show_again' => 'Don\'t show this again',+ 'cancel' => 'Cancel',+ 'confirm' => 'Move to custom time',+ ],+ 'error' => 'Couldn\'t move this post. Try again.',+ 'errors' => [+ 'past' => 'This time has already passed. Pick a later time.',+ 'slot_taken' => 'This time in the queue isn\'t free anymore. Pick another time.',+ 'pending' => 'This post is waiting for approval. Move it once it\'s approved or rejected.',+ 'publishing_soon' => 'This post is about to be published, so it can\'t be moved anymore.',+ 'too_far' => 'Pick a date before January 19, 2038.',+ ],+ 'drag_hint' => 'Drag to reschedule',+ 'drag_hint_undated' => 'Drag No Date draft for :channel to schedule',+ 'announce' => [+ 'over' => 'item scheduled for :from is over :target.',+ 'over_undated' => 'No Date draft for :channel is over :target.',+ 'moved' => 'item scheduled for :from was rescheduled to :to.',+ 'returned' => 'Item was dropped back in its original position.',+ 'undated' => 'item scheduled for :from was dropped on No Date.',+ 'from_undated' => 'No Date draft for :channel was scheduled for :to.',+ 'date_time' => ':date at :time',+ ],+ 'toast' => [+ 'moved' => 'Rescheduled your post for :time.',+ 'moved_draft' => 'Rescheduled your draft for :time.',+ 'undated' => 'Moved your draft to No Date.',+ 'unscheduled' => 'Moved your post to No Date as a draft.',+ 'unqueued_suffix' => 'Its time in the queue is free again.',+ ],+ ],];diff --git a/lang/es/calendar.php b/lang/es/calendar.phpindex 5c9c52e8a..3de20e401 100644--- a/lang/es/calendar.php+++ b/lang/es/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count más','less' => 'Ver menos','empty_day' => 'Nada planeado para este día.',+ 'post_status' => [+ 'draft' => 'Borrador',+ 'pending_approval' => 'Pendiente de aprobación',+ 'queue' => 'En la cola',+ 'custom' => 'Hora personalizada',+ 'recurring' => 'Recurrente',+ 'publishing' => 'Publicando',+ 'published' => 'Publicado',+ 'failed' => 'Fallido',+ ],'status' => ['label' => 'Estado','all' => 'Todas las publicaciones',@@ -31,4 +41,40 @@ return ['draft' => 'Borrador','no_channel' => 'Sin canal',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Mover publicación a una hora personalizada',+ 'description' => 'Vas a mover esta publicación de su hora en la cola, :from, a una hora personalizada, :to.',+ 'unqueued' => 'La publicación se publicará a la nueva hora elegida, pero no ocupará un hueco en tu cola.',+ 'dont_show_again' => 'No mostrar más',+ 'cancel' => 'Cancelar',+ 'confirm' => 'Usar esta hora',+ ],+ 'error' => 'No se pudo mover esta publicación. Inténtalo de nuevo.',+ 'errors' => [+ 'past' => 'Esa hora ya pasó. Elige una hora posterior.',+ 'slot_taken' => 'Esta hora en la cola ya no está libre. Elige otra hora.',+ 'pending' => 'Esta publicación está esperando aprobación. Muévela cuando se apruebe o se rechace.',+ 'publishing_soon' => 'Esta publicación está a punto de publicarse, así que ya no se puede mover.',+ 'too_far' => 'Elige una fecha anterior al 19 de enero de 2038.',+ ],+ 'drag_hint' => 'Arrastra para reprogramar',+ 'drag_hint_undated' => 'Arrastra el borrador sin fecha de :channel para programarlo',+ 'announce' => [+ 'over' => 'el elemento programado para :from está sobre :target.',+ 'over_undated' => 'El borrador sin fecha de :channel está sobre :target.',+ 'moved' => 'el elemento programado para :from se reprogramó para :to.',+ 'returned' => 'El elemento volvió a su posición original.',+ 'undated' => 'el elemento programado para :from se soltó en Sin fecha.',+ 'from_undated' => 'El borrador sin fecha de :channel se programó para :to.',+ 'date_time' => ':date a las :time',+ ],+ 'toast' => [+ 'moved' => 'Tu publicación se reprogramó para :time.',+ 'moved_draft' => 'Tu borrador se reprogramó para :time.',+ 'undated' => 'Tu borrador pasó a Sin fecha.',+ 'unscheduled' => 'Tu publicación pasó a Sin fecha como borrador.',+ 'unqueued_suffix' => 'Su hora en la cola vuelve a estar libre.',+ ],+ ],];diff --git a/lang/fr/calendar.php b/lang/fr/calendar.phpindex d08b8387f..c98c9995a 100644--- a/lang/fr/calendar.php+++ b/lang/fr/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count de plus','less' => 'Voir moins','empty_day' => 'Rien de prévu ce jour-là.',+ 'post_status' => [+ 'draft' => 'Brouillon',+ 'pending_approval' => 'En attente d\'approbation',+ 'queue' => 'Dans la file d\'attente',+ 'custom' => 'Heure choisie',+ 'recurring' => 'Récurrent',+ 'publishing' => 'Publication en cours',+ 'published' => 'Publiée',+ 'failed' => 'Échec',+ ],'status' => ['label' => 'Statut','all' => 'Toutes les publications',@@ -31,4 +41,40 @@ return ['draft' => 'Brouillon','no_channel' => 'Aucun canal',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Déplacer la publication à une heure personnalisée',+ 'description' => 'Vous déplacez cette publication de son horaire dans la file d\'attente, :from, vers une heure personnalisée, :to.',+ 'unqueued' => 'La publication sera diffusée à la nouvelle heure choisie, mais n\'occupera pas de place dans votre file d\'attente.',+ 'dont_show_again' => 'Ne plus afficher',+ 'cancel' => 'Annuler',+ 'confirm' => 'Déplacer à l\'heure choisie',+ ],+ 'error' => 'Impossible de déplacer cette publication. Réessayez.',+ 'errors' => [+ 'past' => 'Cette heure est déjà passée. Choisissez une heure plus tardive.',+ 'slot_taken' => 'Cet horaire dans la file d\'attente n\'est plus libre. Choisissez un autre horaire.',+ 'pending' => 'Cette publication attend une approbation. Déplacez-la une fois approuvée ou refusée.',+ 'publishing_soon' => 'Cette publication est sur le point d\'être publiée, elle ne peut plus être déplacée.',+ 'too_far' => 'Choisissez une date avant le 19 janvier 2038.',+ ],+ 'drag_hint' => 'Faites glisser pour reprogrammer',+ 'drag_hint_undated' => 'Faites glisser le brouillon sans date de :channel pour le programmer',+ 'announce' => [+ 'over' => 'l\'élément prévu pour :from est au-dessus de :target.',+ 'over_undated' => 'Le brouillon sans date de :channel est au-dessus de :target.',+ 'moved' => 'l\'élément prévu pour :from a été reprogrammé pour :to.',+ 'returned' => 'L\'élément a été remis à sa position d\'origine.',+ 'undated' => 'l\'élément prévu pour :from a été déposé sur Sans date.',+ 'from_undated' => 'Le brouillon sans date de :channel a été programmé pour :to.',+ 'date_time' => ':date à :time',+ ],+ 'toast' => [+ 'moved' => 'Votre publication a été reprogrammée pour :time.',+ 'moved_draft' => 'Votre brouillon a été reprogrammé pour :time.',+ 'undated' => 'Votre brouillon a été déplacé vers Sans date.',+ 'unscheduled' => 'Votre publication a été déplacée vers Sans date en brouillon.',+ 'unqueued_suffix' => 'Son horaire dans la file d\'attente est de nouveau libre.',+ ],+ ],];diff --git a/lang/it/calendar.php b/lang/it/calendar.phpindex c6d86e054..68989d06a 100644--- a/lang/it/calendar.php+++ b/lang/it/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count in più','less' => 'Mostra meno','empty_day' => 'Niente in programma per questo giorno.',+ 'post_status' => [+ 'draft' => 'Bozza',+ 'pending_approval' => 'In attesa di approvazione',+ 'queue' => 'In coda',+ 'custom' => 'Orario scelto',+ 'recurring' => 'Ricorrente',+ 'publishing' => 'In pubblicazione',+ 'published' => 'Pubblicato',+ 'failed' => 'Non riuscito',+ ],'status' => ['label' => 'Stato','all' => 'Tutti i post',@@ -31,4 +41,40 @@ return ['draft' => 'Bozza','no_channel' => 'Nessun canale',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Sposta il post a un orario personalizzato',+ 'description' => 'Stai spostando questo post dal suo orario in coda, :from, a un orario personalizzato, :to.',+ 'unqueued' => 'Il post verrà pubblicato al nuovo orario scelto, ma non occuperà un posto nella tua coda.',+ 'dont_show_again' => 'Non mostrare più',+ 'cancel' => 'Annulla',+ 'confirm' => 'Sposta all\'orario scelto',+ ],+ 'error' => 'Impossibile spostare questo post. Riprova.',+ 'errors' => [+ 'past' => 'Questo orario è già passato. Scegli un orario successivo.',+ 'slot_taken' => 'Questo orario in coda non è più libero. Scegli un altro orario.',+ 'pending' => 'Questo post è in attesa di approvazione. Spostalo dopo che è stato approvato o rifiutato.',+ 'publishing_soon' => 'Questo post sta per essere pubblicato, quindi non può più essere spostato.',+ 'too_far' => 'Scegli una data precedente al 19 gennaio 2038.',+ ],+ 'drag_hint' => 'Trascina per riprogrammare',+ 'drag_hint_undated' => 'Trascina la bozza senza data di :channel per programmarla',+ 'announce' => [+ 'over' => 'l\'elemento programmato per :from è sopra :target.',+ 'over_undated' => 'La bozza senza data di :channel è sopra :target.',+ 'moved' => 'l\'elemento programmato per :from è stato riprogrammato per :to.',+ 'returned' => 'L\'elemento è tornato nella posizione originale.',+ 'undated' => 'l\'elemento programmato per :from è stato rilasciato su Senza data.',+ 'from_undated' => 'La bozza senza data di :channel è stata programmata per :to.',+ 'date_time' => ':date alle :time',+ ],+ 'toast' => [+ 'moved' => 'Il tuo post è stato riprogrammato per :time.',+ 'moved_draft' => 'La tua bozza è stata riprogrammata per :time.',+ 'undated' => 'La tua bozza è stata spostata in Senza data.',+ 'unscheduled' => 'Il tuo post è stato spostato in Senza data come bozza.',+ 'unqueued_suffix' => 'Il suo orario in coda è di nuovo libero.',+ ],+ ],];diff --git a/lang/ja/calendar.php b/lang/ja/calendar.phpindex 551359e31..e204208ab 100644--- a/lang/ja/calendar.php+++ b/lang/ja/calendar.php@@ -15,6 +15,16 @@ return ['more' => '他 :count 件','less' => '閉じる','empty_day' => 'この日の予定はありません。',+ 'post_status' => [+ 'draft' => '下書き',+ 'pending_approval' => '承認待ち',+ 'queue' => 'キュー内',+ 'custom' => '指定の時刻',+ 'recurring' => '繰り返し',+ 'publishing' => '公開中',+ 'published' => '公開済み',+ 'failed' => '失敗',+ ],'status' => ['label' => 'ステータス','all' => 'すべての投稿',@@ -31,4 +41,40 @@ return ['draft' => '下書き','no_channel' => 'チャンネルなし',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => '投稿を指定の時刻に移動',+ 'description' => 'この投稿をキューの時刻:fromから、指定の時刻:toに移動します。',+ 'unqueued' => '投稿は選択した新しい時刻に公開されますが、キューの枠は使用しません。',+ 'dont_show_again' => '今後は表示しない',+ 'cancel' => 'キャンセル',+ 'confirm' => '指定の時刻に移動',+ ],+ 'error' => '投稿を移動できませんでした。もう一度お試しください。',+ 'errors' => [+ 'past' => 'この時刻はすでに過ぎています。後の時刻を選んでください。',+ 'slot_taken' => 'このキューの時刻は空いていません。別の時刻を選んでください。',+ 'pending' => 'この投稿は承認待ちです。承認または却下されてから移動してください。',+ 'publishing_soon' => 'この投稿はまもなく公開されるため、移動できません。',+ 'too_far' => '2038年1月19日より前の日付を選んでください。',+ ],+ 'drag_hint' => 'ドラッグして予定を変更',+ 'drag_hint_undated' => ':channel の日付なしの下書きをドラッグして予約',+ 'announce' => [+ 'over' => ':from に予定されている項目が :target の上にあります。',+ 'over_undated' => ':channel の日付なしの下書きが :target の上にあります。',+ 'moved' => ':from に予定されていた項目を :to に変更しました。',+ 'returned' => '項目を元の位置に戻しました。',+ 'undated' => ':from に予定されていた項目を「日付なし」に移しました。',+ 'from_undated' => ':channel の日付なしの下書きを :to に予約しました。',+ 'date_time' => ':date :time',+ ],+ 'toast' => [+ 'moved' => '投稿を :time に変更しました。',+ 'moved_draft' => '下書きを :time に変更しました。',+ 'undated' => '下書きを「日付なし」に移しました。',+ 'unscheduled' => '投稿を下書きとして「日付なし」に移しました。',+ 'unqueued_suffix' => 'キューの時刻が再び空きました。',+ ],+ ],];diff --git a/lang/ko/calendar.php b/lang/ko/calendar.phpindex 1437ddaa9..0bbc56121 100644--- a/lang/ko/calendar.php+++ b/lang/ko/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count개 더보기','less' => '접기','empty_day' => '이 날 예정된 게시물이 없습니다.',+ 'post_status' => [+ 'draft' => '초안',+ 'pending_approval' => '승인 대기 중',+ 'queue' => '대기열에 있음',+ 'custom' => '지정 시간',+ 'recurring' => '반복',+ 'publishing' => '게시 중',+ 'published' => '게시됨',+ 'failed' => '실패',+ ],'status' => ['label' => '상태','all' => '모든 게시물',@@ -31,4 +41,40 @@ return ['draft' => '임시 저장','no_channel' => '채널 없음',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => '게시물을 지정한 시간으로 이동',+ 'description' => '이 게시물을 대기열 시간:from에서 지정 시간:to으로 이동합니다.',+ 'unqueued' => '게시물은 선택한 새 시간에 게시되지만 대기열 자리는 차지하지 않습니다.',+ 'dont_show_again' => '다시 표시하지 않기',+ 'cancel' => '취소',+ 'confirm' => '지정 시간으로 이동',+ ],+ 'error' => '게시물을 이동하지 못했습니다. 다시 시도해 주세요.',+ 'errors' => [+ 'past' => '이미 지난 시간입니다. 이후 시간을 선택하세요.',+ 'slot_taken' => '이 대기열 시간은 더 이상 비어 있지 않습니다. 다른 시간을 선택하세요.',+ 'pending' => '이 게시물은 승인 대기 중입니다. 승인되거나 거절된 후에 이동하세요.',+ 'publishing_soon' => '이 게시물은 곧 게시되므로 더 이상 이동할 수 없습니다.',+ 'too_far' => '2038년 1월 19일 이전 날짜를 선택하세요.',+ ],+ 'drag_hint' => '끌어서 일정 변경',+ 'drag_hint_undated' => ':channel의 날짜 없는 임시 저장 글을 끌어서 예약',+ 'announce' => [+ 'over' => ':from에 예약된 항목이 :target 위에 있습니다.',+ 'over_undated' => ':channel의 날짜 없는 임시 저장 글이 :target 위에 있습니다.',+ 'moved' => ':from에 예약된 항목을 :to(으)로 변경했습니다.',+ 'returned' => '항목을 원래 위치로 되돌렸습니다.',+ 'undated' => ':from에 예약된 항목을 날짜 없음으로 옮겼습니다.',+ 'from_undated' => ':channel의 날짜 없는 임시 저장 글을 :to에 예약했습니다.',+ 'date_time' => ':date :time',+ ],+ 'toast' => [+ 'moved' => '게시물을 :time(으)로 변경했습니다.',+ 'moved_draft' => '임시 저장 글을 :time(으)로 변경했습니다.',+ 'undated' => '임시 저장 글을 날짜 없음으로 옮겼습니다.',+ 'unscheduled' => '게시물을 임시 저장 글로 날짜 없음에 옮겼습니다.',+ 'unqueued_suffix' => '대기열 시간이 다시 비었습니다.',+ ],+ ],];diff --git a/lang/nl/calendar.php b/lang/nl/calendar.phpindex 24872bc09..1a337d575 100644--- a/lang/nl/calendar.php+++ b/lang/nl/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count meer','less' => 'Minder tonen','empty_day' => 'Niets gepland voor deze dag.',+ 'post_status' => [+ 'draft' => 'Concept',+ 'pending_approval' => 'Wacht op goedkeuring',+ 'queue' => 'In de wachtrij',+ 'custom' => 'Eigen tijd',+ 'recurring' => 'Terugkerend',+ 'publishing' => 'Publiceren',+ 'published' => 'Gepubliceerd',+ 'failed' => 'Mislukt',+ ],'status' => ['label' => 'Status','all' => 'Alle berichten',@@ -31,4 +41,40 @@ return ['draft' => 'Concept','no_channel' => 'Geen kanaal',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Bericht naar een eigen tijd verplaatsen',+ 'description' => 'Je verplaatst dit bericht van zijn tijd in de wachtrij, :from, naar een eigen tijd, :to.',+ 'unqueued' => 'Het bericht wordt op de nieuwe tijd gepubliceerd, maar neemt geen plek in je wachtrij in.',+ 'dont_show_again' => 'Niet meer tonen',+ 'cancel' => 'Annuleren',+ 'confirm' => 'Eigen tijd gebruiken',+ ],+ 'error' => 'Kon dit bericht niet verplaatsen. Probeer het opnieuw.',+ 'errors' => [+ 'past' => 'Deze tijd is al voorbij. Kies een latere tijd.',+ 'slot_taken' => 'Deze tijd in de wachtrij is niet meer vrij. Kies een andere tijd.',+ 'pending' => 'Dit bericht wacht op goedkeuring. Verplaats het zodra het is goedgekeurd of afgewezen.',+ 'publishing_soon' => 'Dit bericht wordt zo gepubliceerd en kan niet meer worden verplaatst.',+ 'too_far' => 'Kies een datum vóór 19 januari 2038.',+ ],+ 'drag_hint' => 'Sleep om te verplaatsen',+ 'drag_hint_undated' => 'Sleep het concept zonder datum voor :channel om te plannen',+ 'announce' => [+ 'over' => 'item gepland voor :from staat boven :target.',+ 'over_undated' => 'Concept zonder datum voor :channel staat boven :target.',+ 'moved' => 'item gepland voor :from is verplaatst naar :to.',+ 'returned' => 'Item is teruggezet op de oorspronkelijke plek.',+ 'undated' => 'item gepland voor :from is neergezet op Geen datum.',+ 'from_undated' => 'Concept zonder datum voor :channel is gepland voor :to.',+ 'date_time' => ':date om :time',+ ],+ 'toast' => [+ 'moved' => 'Je bericht is verplaatst naar :time.',+ 'moved_draft' => 'Je concept is verplaatst naar :time.',+ 'undated' => 'Je concept is verplaatst naar Geen datum.',+ 'unscheduled' => 'Je bericht is als concept naar Geen datum verplaatst.',+ 'unqueued_suffix' => 'De tijd in de wachtrij is weer vrij.',+ ],+ ],];diff --git a/lang/pl/calendar.php b/lang/pl/calendar.phpindex 0d7ed5b34..9d02fa836 100644--- a/lang/pl/calendar.php+++ b/lang/pl/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count więcej','less' => 'Pokaż mniej','empty_day' => 'Nic nie zaplanowano na ten dzień.',+ 'post_status' => [+ 'draft' => 'Szkic',+ 'pending_approval' => 'Oczekuje na zatwierdzenie',+ 'queue' => 'W kolejce',+ 'custom' => 'Własna godzina',+ 'recurring' => 'Cykliczny',+ 'publishing' => 'Publikowanie',+ 'published' => 'Opublikowany',+ 'failed' => 'Nieudany',+ ],'status' => ['label' => 'Status','all' => 'Wszystkie posty',@@ -31,4 +41,40 @@ return ['draft' => 'Szkic','no_channel' => 'Brak kanału',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Przenoszenie wpisu na własną godzinę',+ 'description' => 'Ten wpis zostanie przeniesiony z godziny w kolejce, :from, na własną godzinę, :to.',+ 'unqueued' => 'Wpis zostanie opublikowany o wybranej godzinie, ale nie zajmie miejsca w Twojej kolejce.',+ 'dont_show_again' => 'Nie pokazuj więcej',+ 'cancel' => 'Anuluj',+ 'confirm' => 'Użyj tej godziny',+ ],+ 'error' => 'Nie udało się przenieść wpisu. Spróbuj ponownie.',+ 'errors' => [+ 'past' => 'Ta godzina już minęła. Wybierz późniejszą godzinę.',+ 'slot_taken' => 'Ta godzina w kolejce nie jest już wolna. Wybierz inną godzinę.',+ 'pending' => 'Ten wpis czeka na zatwierdzenie. Przenieś go, gdy zostanie zatwierdzony lub odrzucony.',+ 'publishing_soon' => 'Ten wpis zaraz zostanie opublikowany, więc nie można go już przenieść.',+ 'too_far' => 'Wybierz datę przed 19 stycznia 2038.',+ ],+ 'drag_hint' => 'Przeciągnij, aby zmienić termin',+ 'drag_hint_undated' => 'Przeciągnij szkic bez daty dla :channel, aby go zaplanować',+ 'announce' => [+ 'over' => 'element zaplanowany na :from znajduje się nad :target.',+ 'over_undated' => 'Szkic bez daty dla :channel znajduje się nad :target.',+ 'moved' => 'element zaplanowany na :from przeniesiono na :to.',+ 'returned' => 'Element wrócił na pierwotne miejsce.',+ 'undated' => 'element zaplanowany na :from upuszczono w sekcji Bez daty.',+ 'from_undated' => 'Szkic bez daty dla :channel zaplanowano na :to.',+ 'date_time' => ':date, :time',+ ],+ 'toast' => [+ 'moved' => 'Wpis przeniesiono na :time.',+ 'moved_draft' => 'Szkic przeniesiono na :time.',+ 'undated' => 'Szkic przeniesiono do sekcji Bez daty.',+ 'unscheduled' => 'Wpis przeniesiono do sekcji Bez daty jako szkic.',+ 'unqueued_suffix' => 'Godzina w kolejce jest znów wolna.',+ ],+ ],];diff --git a/lang/pt-BR/calendar.php b/lang/pt-BR/calendar.phpindex ae396dfb8..5c19ff6d2 100644--- a/lang/pt-BR/calendar.php+++ b/lang/pt-BR/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count mais','less' => 'Ver menos','empty_day' => 'Nada planejado para este dia.',+ 'post_status' => [+ 'draft' => 'Rascunho',+ 'pending_approval' => 'Aguardando aprovação',+ 'queue' => 'Na fila',+ 'custom' => 'Horário personalizado',+ 'recurring' => 'Recorrente',+ 'publishing' => 'Publicando',+ 'published' => 'Publicado',+ 'failed' => 'Falhou',+ ],'status' => ['label' => 'Status','all' => 'Todos os posts',@@ -31,4 +41,40 @@ return ['draft' => 'Rascunho','no_channel' => 'Sem canal',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Movendo o post para um horário personalizado',+ 'description' => 'Você está movendo este post de um horário da fila, :from, para um horário personalizado, :to.',+ 'unqueued' => 'O post será publicado no novo horário escolhido, mas não vai ocupar um lugar na sua fila.',+ 'dont_show_again' => 'Não mostrar de novo',+ 'cancel' => 'Cancelar',+ 'confirm' => 'Usar este horário',+ ],+ 'error' => 'Não foi possível mover este post. Tente novamente.',+ 'errors' => [+ 'past' => 'Esse horário já passou. Escolha um horário mais tarde.',+ 'slot_taken' => 'Esse horário da fila não está mais livre. Escolha outro horário.',+ 'pending' => 'Este post está aguardando aprovação. Mova-o depois que for aprovado ou rejeitado.',+ 'publishing_soon' => 'Este post está prestes a ser publicado, então não pode mais ser movido.',+ 'too_far' => 'Escolha uma data antes de 19 de janeiro de 2038.',+ ],+ 'drag_hint' => 'Arraste para reagendar',+ 'drag_hint_undated' => 'Arraste o rascunho sem data de :channel para agendar',+ 'announce' => [+ 'over' => 'item agendado para :from está sobre :target.',+ 'over_undated' => 'O rascunho sem data de :channel está sobre :target.',+ 'moved' => 'item agendado para :from foi reagendado para :to.',+ 'returned' => 'O item voltou à posição original.',+ 'undated' => 'item agendado para :from foi solto em Sem data.',+ 'from_undated' => 'O rascunho sem data de :channel foi agendado para :to.',+ 'date_time' => ':date às :time',+ ],+ 'toast' => [+ 'moved' => 'Seu post foi reagendado para :time.',+ 'moved_draft' => 'Seu rascunho foi reagendado para :time.',+ 'undated' => 'Seu rascunho foi movido para Sem data.',+ 'unscheduled' => 'Seu post foi movido para Sem data como rascunho.',+ 'unqueued_suffix' => 'O horário da fila ficou livre de novo.',+ ],+ ],];diff --git a/lang/ru/calendar.php b/lang/ru/calendar.phpindex b239fdf6d..39b33c192 100644--- a/lang/ru/calendar.php+++ b/lang/ru/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count ещё','less' => 'Свернуть','empty_day' => 'На этот день ничего не запланировано.',+ 'post_status' => [+ 'draft' => 'Черновик',+ 'pending_approval' => 'Ожидает одобрения',+ 'queue' => 'В очереди',+ 'custom' => 'Своё время',+ 'recurring' => 'Повторяется',+ 'publishing' => 'Публикуется',+ 'published' => 'Опубликован',+ 'failed' => 'Ошибка',+ ],'status' => ['label' => 'Статус','all' => 'Все публикации',@@ -31,4 +41,40 @@ return ['draft' => 'Черновик','no_channel' => 'Нет канала',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Перенос публикации на другое время',+ 'description' => 'Публикация переносится со времени в очереди, :from, на своё время, :to.',+ 'unqueued' => 'Публикация выйдет в выбранное время, но не займёт место в вашей очереди.',+ 'dont_show_again' => 'Не показывать',+ 'cancel' => 'Отмена',+ 'confirm' => 'Перенести сюда',+ ],+ 'error' => 'Не удалось перенести публикацию. Попробуйте ещё раз.',+ 'errors' => [+ 'past' => 'Это время уже прошло. Выберите более позднее время.',+ 'slot_taken' => 'Это время в очереди уже занято. Выберите другое время.',+ 'pending' => 'Эта публикация ждёт одобрения. Перенесите её после одобрения или отклонения.',+ 'publishing_soon' => 'Эта публикация вот-вот выйдет, поэтому её уже нельзя перенести.',+ 'too_far' => 'Выберите дату до 19 января 2038 года.',+ ],+ 'drag_hint' => 'Перетащите, чтобы перенести',+ 'drag_hint_undated' => 'Перетащите черновик без даты для :channel, чтобы запланировать',+ 'announce' => [+ 'over' => 'элемент, запланированный на :from, находится над :target.',+ 'over_undated' => 'Черновик без даты для :channel находится над :target.',+ 'moved' => 'элемент, запланированный на :from, перенесён на :to.',+ 'returned' => 'Элемент возвращён на прежнее место.',+ 'undated' => 'элемент, запланированный на :from, перенесён в раздел «Без даты».',+ 'from_undated' => 'Черновик без даты для :channel запланирован на :to.',+ 'date_time' => ':date в :time',+ ],+ 'toast' => [+ 'moved' => 'Публикация перенесена на :time.',+ 'moved_draft' => 'Черновик перенесён на :time.',+ 'undated' => 'Черновик перенесён в раздел «Без даты».',+ 'unscheduled' => 'Публикация перенесена в раздел «Без даты» как черновик.',+ 'unqueued_suffix' => 'Время в очереди снова свободно.',+ ],+ ],];diff --git a/lang/tr/calendar.php b/lang/tr/calendar.phpindex 2e5e083e0..89e68b4ed 100644--- a/lang/tr/calendar.php+++ b/lang/tr/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count daha','less' => 'Daha az göster','empty_day' => 'Bu gün için planlanmış bir şey yok.',+ 'post_status' => [+ 'draft' => 'Taslak',+ 'pending_approval' => 'Onay bekliyor',+ 'queue' => 'Kuyrukta',+ 'custom' => 'Özel saat',+ 'recurring' => 'Yinelenen',+ 'publishing' => 'Yayınlanıyor',+ 'published' => 'Yayınlandı',+ 'failed' => 'Başarısız',+ ],'status' => ['label' => 'Durum','all' => 'Tüm gönderiler',@@ -31,4 +41,40 @@ return ['draft' => 'Taslak','no_channel' => 'Kanal yok',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Gönderi özel bir saate taşınıyor',+ 'description' => 'Bu gönderiyi kuyruktaki bir saatten :from özel bir saate :to taşıyorsunuz.',+ 'unqueued' => 'Gönderi seçtiğiniz yeni saatte yayınlanır, ancak kuyruğunuzda yer kaplamaz.',+ 'dont_show_again' => 'Bir daha gösterme',+ 'cancel' => 'İptal',+ 'confirm' => 'Özel saate taşı',+ ],+ 'error' => 'Gönderi taşınamadı. Tekrar deneyin.',+ 'errors' => [+ 'past' => 'Bu saat geçti. Daha sonraki bir saat seçin.',+ 'slot_taken' => 'Kuyruktaki bu saat artık boş değil. Başka bir saat seçin.',+ 'pending' => 'Bu gönderi onay bekliyor. Onaylandıktan veya reddedildikten sonra taşıyın.',+ 'publishing_soon' => 'Bu gönderi birazdan yayınlanacak, bu yüzden artık taşınamaz.',+ 'too_far' => '19 Ocak 2038\'den önce bir tarih seçin.',+ ],+ 'drag_hint' => 'Taşımak için sürükleyin',+ 'drag_hint_undated' => ':channel için tarihsiz taslağı planlamak üzere sürükleyin',+ 'announce' => [+ 'over' => ':from için planlanan öğe :target üzerinde.',+ 'over_undated' => ':channel için tarihsiz taslak :target üzerinde.',+ 'moved' => ':from için planlanan öğe :to tarihine taşındı.',+ 'returned' => 'Öğe özgün konumuna geri bırakıldı.',+ 'undated' => ':from için planlanan öğe Tarihsiz alanına bırakıldı.',+ 'from_undated' => ':channel için tarihsiz taslak :to tarihine planlandı.',+ 'date_time' => ':date, :time',+ ],+ 'toast' => [+ 'moved' => 'Gönderiniz :time tarihine taşındı.',+ 'moved_draft' => 'Taslağınız :time tarihine taşındı.',+ 'undated' => 'Taslağınız Tarihsiz alanına taşındı.',+ 'unscheduled' => 'Gönderiniz taslak olarak Tarihsiz alanına taşındı.',+ 'unqueued_suffix' => 'Kuyruktaki saat yeniden boş.',+ ],+ ],];diff --git a/lang/uk/calendar.php b/lang/uk/calendar.phpindex 3c63cf5c9..d2f5f7184 100644--- a/lang/uk/calendar.php+++ b/lang/uk/calendar.php@@ -15,6 +15,16 @@ return ['more' => '+:count ще','less' => 'Згорнути','empty_day' => 'На цей день нічого не заплановано.',+ 'post_status' => [+ 'draft' => 'Чернетка',+ 'pending_approval' => 'Очікує схвалення',+ 'queue' => 'У черзі',+ 'custom' => 'Свій час',+ 'recurring' => 'Повторюваний',+ 'publishing' => 'Публікується',+ 'published' => 'Опубліковано',+ 'failed' => 'Помилка',+ ],'status' => ['label' => 'Статус','all' => 'Усі дописи',@@ -31,4 +41,40 @@ return ['draft' => 'Чернетка','no_channel' => 'Немає каналу',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => 'Перенесення допису на інший час',+ 'description' => 'Допис переноситься з часу в черзі, :from, на власний час, :to.',+ 'unqueued' => 'Допис вийде у вибраний час, але не займе місце у вашій черзі.',+ 'dont_show_again' => 'Не показувати',+ 'cancel' => 'Скасувати',+ 'confirm' => 'Перенести сюди',+ ],+ 'error' => 'Не вдалося перенести допис. Спробуйте ще раз.',+ 'errors' => [+ 'past' => 'Цей час уже минув. Виберіть пізніший час.',+ 'slot_taken' => 'Цей час у черзі вже не вільний. Виберіть інший час.',+ 'pending' => 'Цей допис чекає на схвалення. Перенесіть його після схвалення або відхилення.',+ 'publishing_soon' => 'Цей допис ось-ось буде опубліковано, тому його вже не можна перенести.',+ 'too_far' => 'Виберіть дату до 19 січня 2038 року.',+ ],+ 'drag_hint' => 'Перетягніть, щоб перенести',+ 'drag_hint_undated' => 'Перетягніть чернетку без дати для :channel, щоб запланувати',+ 'announce' => [+ 'over' => 'елемент, запланований на :from, перебуває над: :target.',+ 'over_undated' => 'Чернетка без дати для :channel перебуває над: :target.',+ 'moved' => 'елемент, запланований на :from, перенесено на :to.',+ 'returned' => 'Елемент повернуто на попереднє місце.',+ 'undated' => 'елемент, запланований на :from, перенесено до розділу «Без дати».',+ 'from_undated' => 'Чернетку без дати для :channel заплановано на :to.',+ 'date_time' => ':date о :time',+ ],+ 'toast' => [+ 'moved' => 'Допис перенесено на :time.',+ 'moved_draft' => 'Чернетку перенесено на :time.',+ 'undated' => 'Чернетку перенесено до розділу «Без дати».',+ 'unscheduled' => 'Допис перенесено до розділу «Без дати» як чернетку.',+ 'unqueued_suffix' => 'Час у черзі знову вільний.',+ ],+ ],];diff --git a/lang/zh/calendar.php b/lang/zh/calendar.phpindex b6030e023..871392ec2 100644--- a/lang/zh/calendar.php+++ b/lang/zh/calendar.php@@ -15,6 +15,16 @@ return ['more' => '还有 :count 项','less' => '收起','empty_day' => '这一天没有安排。',+ 'post_status' => [+ 'draft' => '草稿',+ 'pending_approval' => '待审批',+ 'queue' => '在队列中',+ 'custom' => '自定义时间',+ 'recurring' => '重复',+ 'publishing' => '发布中',+ 'published' => '已发布',+ 'failed' => '已失败',+ ],'status' => ['label' => '状态','all' => '所有帖子',@@ -31,4 +41,40 @@ return ['draft' => '草稿','no_channel' => '无频道',],+ 'reschedule' => [+ 'custom_time' => [+ 'title' => '将帖子移到自定义时间',+ 'description' => '你正在将此帖子从队列时间 :from 移到自定义时间 :to。',+ 'unqueued' => '帖子将在你选择的新时间发布,但不会占用队列中的位置。',+ 'dont_show_again' => '不再显示',+ 'cancel' => '取消',+ 'confirm' => '移到自定义时间',+ ],+ 'error' => '无法移动此帖子。请重试。',+ 'errors' => [+ 'past' => '这个时间已经过去了。请选择更晚的时间。',+ 'slot_taken' => '队列中的这个时间已不再空闲。请选择其他时间。',+ 'pending' => '这条帖子正在等待批准。批准或拒绝后再移动它。',+ 'publishing_soon' => '这条帖子即将发布,因此无法再移动。',+ 'too_far' => '请选择 2038 年 1 月 19 日之前的日期。',+ ],+ 'drag_hint' => '拖动以改期',+ 'drag_hint_undated' => '拖动 :channel 的无日期草稿以安排时间',+ 'announce' => [+ 'over' => '计划在 :from 的项目正位于 :target 上方。',+ 'over_undated' => ':channel 的无日期草稿正位于 :target 上方。',+ 'moved' => '计划在 :from 的项目已改期至 :to。',+ 'returned' => '项目已放回原位置。',+ 'undated' => '计划在 :from 的项目已放入无日期。',+ 'from_undated' => ':channel 的无日期草稿已安排在 :to。',+ 'date_time' => ':date :time',+ ],+ 'toast' => [+ 'moved' => '你的帖子已改期至 :time。',+ 'moved_draft' => '你的草稿已改期至 :time。',+ 'undated' => '你的草稿已移到无日期。',+ 'unscheduled' => '你的帖子已作为草稿移到无日期。',+ 'unqueued_suffix' => '队列中的时间已重新空出。',+ ],+ ],];diff --git a/package-lock.json b/package-lock.jsonindex 0d691da24..2c8a40dd2 100644--- a/package-lock.json+++ b/package-lock.json@@ -20,7 +20,7 @@"embla-carousel-vue": "^8.6.0","highlight.js": "^11.11.1","laravel-vite-plugin": "^3.1.0",- "laravel-vue-i18n": "^2.8.0",+ "laravel-vue-i18n": "^2.9.0","posthog-js": "^1.364.2","reka-ui": "^2.9.10","tailwind-merge": "^3.2.0",@@ -6422,12 +6422,12 @@}},"node_modules/laravel-vue-i18n": {- "version": "2.8.0",- "resolved": "https://registry.npmjs.org/laravel-vue-i18n/-/laravel-vue-i18n-2.8.0.tgz",- "integrity": "sha512-5D4GvITMZaLVwnirMU8NeQBCSfhEqDyRHiFshfP9ycdczB6e2oYZl5ow95M2sLOViPCuroYzMXqybfG9yFhoCw==",+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/laravel-vue-i18n/-/laravel-vue-i18n-2.9.0.tgz",+ "integrity": "sha512-rt1JnXITQx85UCy2kxWdaBpgqSmZg+RNDcWC2l96zfrEPI/xGknD1CoYr9GPAHqtl4/XosK5t4Rt4J9kd/VzdQ==","license": "MIT","dependencies": {- "php-parser": "3.2.2",+ "php-parser": "3.7.0","vue": "^3.5.13"}},@@ -7176,9 +7176,9 @@}},"node_modules/php-parser": {- "version": "3.2.2",- "resolved": "https://registry.npmjs.org/php-parser/-/php-parser-3.2.2.tgz",- "integrity": "sha512-voj3rzCJmEbwHwH3QteON28wA6K+JbcaJEofyUZkUXmcViiXofjbSbcE5PtqtjX6nstnnAEYCFoRq0mkjP5/cg==",+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/php-parser/-/php-parser-3.7.0.tgz",+ "integrity": "sha512-JRc1t78GZAEa+MuzVC5A5RJS1NDFTS4UnprUEu/NnsN9cyHbGZLUqghO9IQZUSCay62HYQiWd3PxyWAEF45zmA==","license": "BSD-3-Clause"},"node_modules/picocolors": {diff --git a/package.json b/package.jsonindex 4e1e30edc..9835b6b7c 100644--- a/package.json+++ b/package.json@@ -52,7 +52,7 @@"embla-carousel-vue": "^8.6.0","highlight.js": "^11.11.1","laravel-vite-plugin": "^3.1.0",- "laravel-vue-i18n": "^2.8.0",+ "laravel-vue-i18n": "^2.9.0","posthog-js": "^1.364.2","reka-ui": "^2.9.10","tailwind-merge": "^3.2.0",diff --git a/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/cover.png b/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/cover.pngnew file mode 100644index 000000000..ceecf9350Binary files /dev/null and b/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/cover.png differdiff --git a/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/entry.md b/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/entry.mdnew file mode 100644index 000000000..337fff509--- /dev/null+++ b/resources/changelog/2026-10-30-drag-to-reschedule-on-the-calendar/entry.md@@ -0,0 +1,13 @@+---+title: Drag posts on the calendar to reschedule them+date: 2026-10-30+tags: [new]+---++Moving a post to another day or time now takes one drag on the calendar.++- **Every calendar view:** drop a post on an hour to move it there, or on a day to keep its time. Drafts stay drafts, and a recurring series follows the post you move.+- **Posting times:** drop a scheduled post on one of its channel's posting times and it joins the queue there. Anywhere else, it gets a custom time, and you confirm first if it was in the queue.+- **No Date:** drag a post in to take it off the schedule and keep it as a draft, or drag a draft out onto the calendar to give it a date.+- **Status at a glance:** every post on the calendar shows an icon for its status, with its name when you hover it.+- **On your phone:** press and hold a post, then drag it to another day or time.diff --git a/resources/js/components/MultiSelectFilter.vue b/resources/js/components/MultiSelectFilter.vueindex 681bc32c0..28b59f7a9 100644--- a/resources/js/components/MultiSelectFilter.vue+++ b/resources/js/components/MultiSelectFilter.vue@@ -106,7 +106,7 @@ const toggleAll = (): void => {<slot v-if="$slots.panel" name="panel" /><template v-else><slot name="header" :sheet="asSheet" :close="close" />- <div class="relative">+ <div class="relative mb-2"><IconSearchclass="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"/>@@ -122,7 +122,7 @@ const toggleAll = (): void => {<divv-if="showHeader"- class="mt-2 flex items-center justify-between p-2 text-sm text-foreground"+ class="flex items-center justify-between p-2 text-sm text-foreground"><span>{{ label }}</span><buttondiff --git a/resources/js/components/Toast.vue b/resources/js/components/Toast.vueindex a9a937446..4f83beb8b 100644--- a/resources/js/components/Toast.vue+++ b/resources/js/components/Toast.vue@@ -26,17 +26,17 @@ watch(if (flash.banner) {switch (flash.bannerStyle) {case 'danger':- toast.error(flash.banner, { id: 'flash-banner' });+ toast.error(flash.banner, { id: 'flash-banner', testId: 'flash-banner-toast' });break;case 'warning':- toast.warning(flash.banner, { id: 'flash-banner' });+ toast.warning(flash.banner, { id: 'flash-banner', testId: 'flash-banner-toast' });break;case 'info':- toast.info(flash.banner, { id: 'flash-banner' });+ toast.info(flash.banner, { id: 'flash-banner', testId: 'flash-banner-toast' });break;case 'success':default:- toast.success(flash.banner, { id: 'flash-banner' });+ toast.success(flash.banner, { id: 'flash-banner', testId: 'flash-banner-toast' });}}diff --git a/resources/js/components/TransSlots.vue b/resources/js/components/TransSlots.vuenew file mode 100644index 000000000..e96e88613--- /dev/null+++ b/resources/js/components/TransSlots.vue@@ -0,0 +1,44 @@+<script setup lang="ts">+import { computed, useSlots } from 'vue';++/**+ * A translated sentence with markup in it, without v-html: the lang string+ * holds plain text and `:placeholders`, and each placeholder with a slot of+ * its name is rendered from that slot, so the markup (bold, italic, a link)+ * lives in the template and every value is escaped by Vue. The same idea as+ * vue-i18n's `<i18n-t>`, for laravel-vue-i18n's `:placeholder` syntax.+ *+ * <TransSlots :message="$t('calendar.reschedule.custom_time.description')">+ * <template #from><strong>{{ fromTime }}</strong></template>+ * </TransSlots>+ */+const props = defineProps<{+ message: string;+}>();++const slots = useSlots();++const PLACEHOLDER = /(:\w+)/;++type Segment = { slot: string } | { text: string };++const segments = computed((): Segment[] =>+ props.message+ .split(PLACEHOLDER)+ .filter(Boolean)+ .map((part) =>+ part.startsWith(':') && slots[part.slice(1)]+ ? { slot: part.slice(1) }+ : { text: part },+ ),+);+</script>++<template>+ <span>+ <template v-for="(segment, index) in segments" :key="index">+ <slot v-if="'slot' in segment" :name="segment.slot" />+ <template v-else>{{ segment.text }}</template>+ </template>+ </span>+</template>diff --git a/resources/js/components/analytics/channel/PostTypeFilter.vue b/resources/js/components/analytics/channel/PostTypeFilter.vueindex ac3399910..e25b30af2 100644--- a/resources/js/components/analytics/channel/PostTypeFilter.vue+++ b/resources/js/components/analytics/channel/PostTypeFilter.vue@@ -43,9 +43,6 @@ const clear = (): void => {<template #icon><IconLayoutGrid class="size-4" /></template>- <template #before-options>- <div class="pt-2" />- </template><template #footer><divclass="-mx-3 mt-2 flex items-center border-t border-border px-3 pt-2"diff --git a/resources/js/components/labels/LabelBadge.vue b/resources/js/components/labels/LabelBadge.vueindex a692a23c2..7680ccdca 100644--- a/resources/js/components/labels/LabelBadge.vue+++ b/resources/js/components/labels/LabelBadge.vue@@ -5,46 +5,20 @@ interface Label {color: string;}-withDefaults(- defineProps<{- label: Label;- interactive?: boolean;- selected?: boolean;- disabled?: boolean;- }>(),- {- interactive: false,- selected: false,- disabled: false,- },-);--defineEmits<{ click: [] }>();+defineProps<{+ label: Label;+}>();</script><template>- <component- :is="interactive ? 'button' : 'span'"- :type="interactive ? 'button' : undefined"- :disabled="interactive && disabled"- class="inline-flex items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-[10px] font-bold tracking-widest text-foreground uppercase shadow-2xs"- :class="[- selected- ? 'border-primary-strong bg-primary-subtle text-foreground shadow-sm'- : 'bg-card',- interactive- ? 'cursor-pointer transition-transform hover:-translate-y-0.5 disabled:cursor-not-allowed'- : '',- interactive && !selected && !disabled- ? 'opacity-80 hover:opacity-100'- : '',- ]"- @click="interactive && !disabled ? $emit('click') : undefined"+ <span+ class="inline-flex h-6 max-w-full min-w-0 items-center gap-1.5 rounded-md border border-border-strong bg-card px-2 text-xs font-medium text-foreground"><spanclass="size-2 shrink-0 rounded-full":style="{ backgroundColor: label.color }"+ aria-hidden="true"/><span class="truncate">{{ label.name }}</span>- </component>+ </span></template>diff --git a/resources/js/components/labels/LabelFilter.vue b/resources/js/components/labels/LabelFilter.vueindex bbcb3cf82..0a848b674 100644--- a/resources/js/components/labels/LabelFilter.vue+++ b/resources/js/components/labels/LabelFilter.vue@@ -168,7 +168,7 @@ const clear = (): void => {<IconTag class="size-4" /></template><template #before-options="{ search }">- <div v-if="showUntagged && labels.length > 0" class="pt-2">+ <div v-if="showUntagged && labels.length > 0"><labelv-if="matchesSearch(search, [$t('posts.label_filter_untagged')])"class="flex min-h-8 cursor-pointer items-center gap-3 rounded-lg px-2 py-1.5 text-sm leading-5 transition-control hover:bg-accent"diff --git a/resources/js/components/publish/CalendarCustomTimeDialog.vue b/resources/js/components/publish/CalendarCustomTimeDialog.vuenew file mode 100644index 000000000..88689a15b--- /dev/null+++ b/resources/js/components/publish/CalendarCustomTimeDialog.vue@@ -0,0 +1,165 @@+<script setup lang="ts">+import { usePage } from '@inertiajs/vue3';+import { AlertDialogCancel } from 'reka-ui';+import { ref } from 'vue';++import TransSlots from '@/components/TransSlots.vue';+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { Separator } from '@/components/ui/separator';+import date from '@/date';++const page = usePage();++const storageKey = (): string =>+ `calendar.skipCustomTimeConfirm.${page.props.auth.user.id}`;++const isOpen = ref(false);+const skipNextTime = ref(false);+const fromTime = ref('');+const toTime = ref('');+const zone = ref('');++let resolveChoice: ((confirmed: boolean) => void) | null = null;++const readSkip = (): boolean => {+ try {+ return window.localStorage.getItem(storageKey()) === 'true';+ } catch {+ return false;+ }+};++const storeSkip = (): void => {+ try {+ window.localStorage.setItem(storageKey(), 'true');+ } catch {+ return;+ }+};++const settle = (confirmed: boolean): void => {+ isOpen.value = false;+ resolveChoice?.(confirmed);+ resolveChoice = null;+};++const confirm = (+ from: string,+ to: string,+ timezone: string,+): Promise<boolean> => {+ if (readSkip()) {+ return Promise.resolve(true);+ }++ resolveChoice?.(false);+ fromTime.value = date.formatMonthDayTimeInTimezone(from, timezone);+ toTime.value = date.formatMonthDayTimeInTimezone(to, timezone);+ zone.value = timezone;+ skipNextTime.value = false;+ isOpen.value = true;++ return new Promise((resolve) => {+ resolveChoice = resolve;+ });+};++const onOpenChange = (value: boolean): void => {+ if (!value) {+ settle(false);+ }+};++const accept = (): void => {+ if (skipNextTime.value) {+ storeSkip();+ }++ settle(true);+};++const setSkipNextTime = (value: boolean | 'indeterminate'): void => {+ skipNextTime.value = value === true;+};++defineExpose({ confirm });+</script>++<template>+ <AlertDialog :open="isOpen" @update:open="onOpenChange">+ <AlertDialogContent+ disable-outside-pointer-events+ class="gap-4 px-0 pt-6 pb-4 sm:max-w-[480px]"+ data-testid="calendar-custom-time-dialog"+ >+ <AlertDialogTitle class="px-6 text-base leading-5 font-[550]">+ {{ $t('calendar.reschedule.custom_time.title') }}+ </AlertDialogTitle>+ <AlertDialogDescription+ as="div"+ class="flex flex-col gap-4 px-6 text-sm leading-[21px] text-foreground"+ >+ <p data-testid="calendar-custom-time-description">+ <TransSlots+ :message="+ $t('calendar.reschedule.custom_time.description')+ "+ >+ <template #from>+ <strong+ class="font-[650]"+ data-testid="calendar-custom-time-from"+ >{{ fromTime }}+ <i data-testid="calendar-custom-time-from-zone"+ >({{ zone }})</i+ ></strong+ >+ </template>+ <template #to>+ <strong+ class="font-[650]"+ data-testid="calendar-custom-time-to"+ >{{ toTime }} <i>({{ zone }})</i></strong+ >+ </template>+ </TransSlots>+ </p>+ <p>{{ $t('calendar.reschedule.custom_time.unqueued') }}</p>+ </AlertDialogDescription>+ <Separator class="max-sm:mt-auto" />+ <div+ class="flex items-center justify-end gap-2 px-6 max-sm:flex-wrap"+ data-testid="calendar-custom-time-footer"+ >+ <label+ class="me-auto flex shrink-0 items-center gap-2 text-sm leading-[21px] whitespace-nowrap text-foreground max-sm:me-0 max-sm:w-full"+ >+ <Checkbox+ :model-value="skipNextTime"+ data-testid="calendar-custom-time-skip"+ @update:model-value="setSkipNextTime"+ />+ {{ $t('calendar.reschedule.custom_time.dont_show_again') }}+ </label>+ <AlertDialogCancel as-child>+ <Button+ variant="ghost"+ data-testid="calendar-custom-time-cancel"+ >+ {{ $t('calendar.reschedule.custom_time.cancel') }}+ </Button>+ </AlertDialogCancel>+ <Button data-testid="calendar-custom-time-confirm" @click="accept">+ {{ $t('calendar.reschedule.custom_time.confirm') }}+ </Button>+ </div>+ </AlertDialogContent>+ </AlertDialog>+</template>diff --git a/resources/js/components/publish/CalendarDragAnnouncer.vue b/resources/js/components/publish/CalendarDragAnnouncer.vuenew file mode 100644index 000000000..fcbc152de--- /dev/null+++ b/resources/js/components/publish/CalendarDragAnnouncer.vue@@ -0,0 +1,16 @@+<script setup lang="ts">+defineProps<{+ text: string;+}>();+</script>++<template>+ <div+ class="sr-only"+ aria-live="polite"+ aria-atomic="true"+ data-testid="calendar-drag-announcer"+ >+ {{ text }}+ </div>+</template>diff --git a/resources/js/components/publish/CalendarMonthGrid.vue b/resources/js/components/publish/CalendarMonthGrid.vuenew file mode 100644index 000000000..535ea9165--- /dev/null+++ b/resources/js/components/publish/CalendarMonthGrid.vue@@ -0,0 +1,284 @@+<script setup lang="ts">+import { IconChevronDown, IconPlus } from '@tabler/icons-vue';+import { computed } from 'vue';++import CalendarPostChip from '@/components/publish/CalendarPostChip.vue';+import CalendarSlotChip from '@/components/publish/CalendarSlotChip.vue';+import {+ calendarTargetKey,+ useCalendarDragContext,+} from '@/composables/calendar/useCalendarDrag';+import dayjs from '@/dayjs';+import { DRAFT_DAY_CLOCK, type CalendarDropTarget } from '@/lib/calendarDrop';+import {+ calendarDayKey as dayKey,+ calendarItems,+ type CalendarItem,+} from '@/lib/calendarItems';+import type {+ CalendarPost,+ CalendarSlot,+ PublishSocialAccount,+} from '@/types/publish';++const props = defineProps<{+ weeks: dayjs.Dayjs[][];+ month: dayjs.Dayjs;+ posts: Record<string, CalendarPost[]>;+ slots: Record<string, CalendarSlot[]>;+ channels: Record<string, PublishSocialAccount>;+ timezone: string;+ now: dayjs.Dayjs;+ canCreatePost: boolean;+ isDesktop: boolean;+}>();++const emit = defineEmits<{+ compose: [at: string];+}>();++const expandedDays = defineModel<string[]>('expandedDays', { required: true });++/**+ * How many items a day shows before "+N more": a phone's shorter cells fit one less.+ */+const monthChips = computed(() => (props.isDesktop ? 4 : 3));++const { overTarget, draggingPostId, vCalendarTarget } =+ useCalendarDragContext();++const todayKey = computed(() =>+ props.now.tz(props.timezone).format('YYYY-MM-DD'),+);++const weekdayNames = computed(() =>+ (props.weeks[0] ?? []).map((day) =>+ day.format(props.isDesktop ? 'dddd' : 'ddd'),+ ),+);++const dayTargetKey = (day: dayjs.Dayjs): string =>+ calendarTargetKey({ kind: 'day', dayKey: dayKey(day) });++const isDayOver = (day: dayjs.Dayjs): boolean =>+ overTarget.value === dayTargetKey(day);++const isToday = (day: dayjs.Dayjs): boolean => dayKey(day) === todayKey.value;++const isPast = (day: dayjs.Dayjs): boolean => dayKey(day) < todayKey.value;++const isCurrentMonth = (day: dayjs.Dayjs): boolean =>+ day.month() === props.month.month();++const itemsByDay = computed<Record<string, CalendarItem[]>>(() =>+ Object.fromEntries(+ props.weeks+ .flat()+ .map((day) => [+ dayKey(day),+ calendarItems(+ props.posts[dayKey(day)] ?? [],+ props.slots[dayKey(day)] ?? [],+ ),+ ]),+ ),+);++const dayTargets = computed<Record<string, CalendarDropTarget>>(() =>+ Object.fromEntries(+ props.weeks+ .flat()+ .map((day) => [dayKey(day), { kind: 'day', dayKey: dayKey(day) }]),+ ),+);++const itemsFor = (day: dayjs.Dayjs): CalendarItem[] =>+ itemsByDay.value[dayKey(day)] ?? [];++const composeOn = (day: dayjs.Dayjs): void =>+ emit(+ 'compose',+ dayjs+ .tz(`${dayKey(day)}T${DRAFT_DAY_CLOCK}`, props.timezone)+ .utc()+ .format(),+ );++const toggleDay = (key: string): void => {+ expandedDays.value = expandedDays.value.includes(key)+ ? expandedDays.value.filter((day) => day !== key)+ : [...expandedDays.value, key];+};++const isDayExpanded = (day: dayjs.Dayjs): boolean =>+ expandedDays.value.includes(dayKey(day));++const hiddenCount = (day: dayjs.Dayjs): number =>+ itemsFor(day).length - monthChips.value;++const visibleMonthItems = (day: dayjs.Dayjs): CalendarItem[] =>+ isDayExpanded(day)+ ? itemsFor(day)+ : itemsFor(day).slice(0, monthChips.value);+</script>++<template>+ <div+ class="flex flex-1 flex-col overflow-y-auto overscroll-contain"+ data-calendar-scroller+ data-testid="calendar-month-grid"+ >+ <div+ class="sticky top-0 z-10 grid grid-cols-7 border-b border-border-strong bg-card"+ >+ <div+ v-for="(name, index) in weekdayNames"+ :key="name"+ class="border-border-strong p-1.5 text-center text-sm font-medium text-muted-foreground capitalize md:p-2.5"+ :class="{ 'border-l': index > 0 }"+ >+ {{ name }}+ </div>+ </div>++ <div class="flex flex-1 flex-col">+ <div+ v-for="(week, weekIndex) in weeks"+ :key="weekIndex"+ class="grid min-h-40 flex-1 auto-rows-[minmax(0,1fr)] grid-cols-7 border-border-strong md:min-h-[208px]"+ :class="{ 'border-t': weekIndex > 0 }"+ >+ <div+ v-for="(day, index) in week"+ :key="dayKey(day)"+ v-calendar-target="dayTargets[dayKey(day)]"+ class="group flex min-h-0 min-w-0 flex-col gap-1 border-border-strong p-1 md:p-2"+ :class="{+ 'border-l': index > 0,+ 'bg-accent': isPast(day),+ 'bg-primary/15': isDayOver(day),+ }"+ :data-drop-over="isDayOver(day) || undefined"+ :data-testid="`calendar-day-${dayKey(day)}`"+ >+ <div class="flex items-center justify-between">+ <span+ class="inline-flex size-6 items-center justify-center rounded-full text-sm font-medium"+ :class="{+ 'bg-primary text-primary-foreground':+ isToday(day),+ 'text-subtle-foreground':+ !isToday(day) &&+ !isCurrentMonth(day),+ 'text-muted-foreground':+ !isToday(day) &&+ isCurrentMonth(day),+ }"+ >+ {{ day.format('D') }}+ </span>+ <button+ v-if="+ canCreatePost &&+ !isPast(day) &&+ !draggingPostId+ "+ type="button"+ :aria-label="$t('calendar.new_post')"+ class="flex size-6 items-center justify-center rounded-md border border-border-strong bg-card text-muted-foreground opacity-0 transition-opacity duration-100 ease-in-out group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 max-md:hidden [@media(hover:none)]:opacity-100"+ :data-testid="`calendar-add-${dayKey(day)}`"+ @click="composeOn(day)"+ >+ <IconPlus class="size-3.5" />+ </button>+ </div>++ <div class="relative min-h-0 flex-1">+ <div+ class="flex flex-col gap-1"+ :class="{+ 'absolute inset-0 overflow-y-auto overscroll-contain':+ isDayExpanded(day),+ }"+ :data-testid="`calendar-items-${dayKey(day)}`"+ >+ <template+ v-for="item in visibleMonthItems(day)"+ :key="item.key"+ >+ <CalendarPostChip+ v-if="item.post"+ :post="item.post"+ :timezone="timezone"+ :compact="!isDesktop"+ :class="{+ 'opacity-50':+ isDayOver(day) &&+ item.post.id !==+ draggingPostId,+ }"+ />+ <CalendarSlotChip+ v-else-if="item.slot"+ :posting-slot="item.slot"+ :channel="+ channels[+ item.slot.channel_id+ ] ?? null+ "+ :timezone="timezone"+ :can-create-post="canCreatePost"+ :compact="!isDesktop"+ />+ </template>+ </div>+ </div>+ <button+ v-if="hiddenCount(day) > 0"+ type="button"+ class="inline-flex shrink-0 items-center gap-1 rounded-md text-xs font-medium text-foreground transition-control hover:bg-accent"+ :class="+ isDesktop+ ? 'h-6 self-end px-2'+ : 'h-7 min-w-7 justify-center self-start px-1'+ "+ :aria-expanded="isDayExpanded(day)"+ :aria-label="+ isDesktop+ ? undefined+ : isDayExpanded(day)+ ? $t('calendar.less')+ : $t('calendar.more', {+ count: String(+ hiddenCount(day),+ ),+ })+ "+ :data-testid="`calendar-more-${dayKey(day)}`"+ @click="toggleDay(dayKey(day))"+ >+ <IconChevronDown+ v-if="isDesktop || isDayExpanded(day)"+ class="size-3.5 transition-transform"+ :class="{+ 'rotate-180': isDayExpanded(day),+ }"+ />+ <template v-if="isDesktop">{{+ isDayExpanded(day)+ ? $t('calendar.less')+ : $t('calendar.more', {+ count: String(+ hiddenCount(day),+ ),+ })+ }}</template>+ <template v-else-if="!isDayExpanded(day)"+ >+{{ hiddenCount(day) }}</template+ >+ </button>+ </div>+ </div>+ </div>+ </div>+</template>diff --git a/resources/js/components/publish/CalendarPostChip.vue b/resources/js/components/publish/CalendarPostChip.vueindex c6a022185..631b079f3 100644--- a/resources/js/components/publish/CalendarPostChip.vue+++ b/resources/js/components/publish/CalendarPostChip.vue@@ -1,66 +1,56 @@<script setup lang="ts">-import { IconPlayerPlayFilled, IconRepeat } from '@tabler/icons-vue';-import { Presence } from 'reka-ui';-import { computed, ref, watch } from 'vue';+import {+ IconAlertCircle,+ IconCircleCheck,+ IconHourglass,+ IconListNumbers,+ IconPencil,+ IconPin,+ IconPlayerPlayFilled,+ IconRepeat,+ IconSend,+} from '@tabler/icons-vue';+import { computed, nextTick, ref, type Component } from 'vue';import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';-import PostScheduleModeBadge from '@/components/posts/PostScheduleModeBadge.vue';import PostTimelineCard from '@/components/publish/PostTimelineCard.vue';import {- Popover,- PopoverContent,- PopoverTrigger,-} from '@/components/ui/popover';-import { useBelowBreakpoint } from '@/composables/useBreakpoint';+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import { useCalendarDragContext } from '@/composables/calendar/useCalendarDrag';import { getPlatformLabel } from '@/composables/usePlatformLogo';import date from '@/date';import { isImage, isVideo } from '@/lib/mediaType';import { htmlToPlainText } from '@/lib/utils';import { videoFrameUrl } from '@/lib/videoFrame';-import { PostStatus } from '@/types/post';+import { PostStatus, ScheduleMode } from '@/types/post';import type { CalendarPost, PublishTab } from '@/types/publish';defineOptions({ inheritAttrs: false });-const props = withDefaults(- defineProps<{- post: CalendarPost;- timezone: string;- layout?: 'month' | 'week';- compact?: boolean;- }>(),- { layout: 'month' },-);---const open = ref(false);-const detailsOpen = ref(false);-const isPhone = useBelowBreakpoint('sm');-const card = ref<InstanceType<typeof PostTimelineCard> | null>(null);--const onOpenChange = (value: boolean): void => {- if (value && isPhone.value) {- card.value?.openDetails();+const props = defineProps<{+ post: CalendarPost;+ timezone: string;+ compact?: boolean;+}>();- return;- }+const { draggingPostId, vCalendarPost } = useCalendarDragContext();- open.value = value;-};--watch(- () => [props.post.status, props.post.calendar_at, props.post.schedule_mode],- () => {- open.value = false;- },-);+const isDragging = computed(() => draggingPostId.value === props.post.id);-const onDetails = (value: boolean): void => {- detailsOpen.value = value;-- if (value) {- open.value = false;- }+const card = ref<InstanceType<typeof PostTimelineCard> | null>(null);+const cardMounted = ref(false);++/**+ * A click opens the post's details. The card that holds the details dialog+ * mounts on the first click only, so a busy calendar doesn't mount one per chip.+ */+const openDetails = async (): Promise<void> => {+ cardMounted.value = true;+ await nextTick();+ card.value?.openDetails();};const SENT_STATUSES: readonly string[] = [@@ -68,11 +58,6 @@ const SENT_STATUSES: readonly string[] = [PostStatus.Failed,];-const STATUS_CLASSES: Record<string, string> = {- draft: 'border-dashed',- failed: 'border-destructive/40 bg-destructive/5',-};-const tab = computed((): PublishTab => {if (SENT_STATUSES.includes(props.post.status)) {return 'sent';@@ -107,136 +92,151 @@ const thumbnail = computed() ?? null,);-const focusPopover = (event: Event): void => {- event.preventDefault();- (event.target as HTMLElement).focus();+type StatusKey =+ | 'draft'+ | 'pending_approval'+ | 'queue'+ | 'custom'+ | 'recurring'+ | 'publishing'+ | 'published'+ | 'failed';++interface StatusMarker {+ icon: Component;+ tone: string;+ testId: string;+}++const STATUS_MARKERS: Record<StatusKey, StatusMarker> = {+ draft: { icon: IconPencil, tone: 'text-muted-foreground', testId: 'calendar-post-draft' },+ pending_approval: { icon: IconHourglass, tone: 'text-muted-foreground', testId: 'calendar-post-pending' },+ queue: { icon: IconListNumbers, tone: 'text-muted-foreground', testId: 'post-schedule-mode' },+ custom: { icon: IconPin, tone: 'text-muted-foreground', testId: 'post-schedule-mode' },+ recurring: { icon: IconRepeat, tone: 'text-muted-foreground', testId: 'calendar-post-recurring' },+ publishing: { icon: IconSend, tone: 'text-muted-foreground', testId: 'calendar-post-publishing' },+ published: { icon: IconCircleCheck, tone: 'text-success', testId: 'calendar-post-published' },+ failed: { icon: IconAlertCircle, tone: 'text-destructive', testId: 'calendar-post-failed' },};-const scheduleMode = computed(() =>- props.post.status === PostStatus.Scheduled- ? (props.post.schedule_mode ?? null)- : null,+const statusKey = computed((): StatusKey => {+ const { status, schedule_mode, recurrence_frequency } = props.post;++ if (status !== PostStatus.Scheduled) {+ return status as StatusKey;+ }++ if (recurrence_frequency) {+ return 'recurring';+ }++ return schedule_mode === ScheduleMode.Queue ? 'queue' : 'custom';+});++const statusMarker = computed(() => STATUS_MARKERS[statusKey.value]);++const statusLabelKey = computed(+ () => `calendar.post_status.${statusKey.value}`,);++const chipClass = computed(() => [+ props.compact ? 'justify-center gap-0.5' : 'gap-1.5',+ isDragging.value+ ? 'border-transparent bg-muted *:invisible hover:bg-muted'+ : '',+]);</script><template>- <Popover :open="open" @update:open="onOpenChange">- <Teleport to="body">- <Presence :present="open">- <div- :data-state="open ? 'open' : 'closed'"- class="motion-dialog-overlay fixed inset-0 z-50 bg-black/50"- :data-testid="`calendar-post-overlay-${post.id}`"- aria-hidden="true"- />- </Presence>- </Teleport>- <PopoverTrigger as-child>- <button- type="button"- v-bind="$attrs"- class="flex min-w-0 shrink-0 gap-1.5 rounded-lg border border-border-strong bg-card text-start transition-control hover:bg-secondary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[state=open]:bg-secondary"- :class="[- STATUS_CLASSES[post.status] ?? '',- compact- ? 'size-7 items-center justify-center'- : layout === 'week'- ? 'items-start p-1.5'- : 'h-7 items-center px-1',- ]"- :aria-label="`${channels} · ${time} · ${text || $t('calendar.no_content')}`"- :data-testid="`calendar-post-${post.id}`"+ <div class="contents">+ <button+ v-calendar-post="post"+ type="button"+ v-bind="$attrs"+ class="flex h-7 min-w-0 shrink-0 items-center rounded-lg border border-border-strong bg-card px-1 text-start transition-control hover:bg-secondary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&[data-calendar-draggable=true]]:cursor-grab"+ :class="chipClass"+ :aria-label="+ [+ channels,+ time,+ $t(statusLabelKey),+ text || $t('calendar.no_content'),+ ].join(' · ')+ "+ :data-dragging="isDragging || undefined"+ :data-testid="`calendar-post-${post.id}`"+ @click="openDetails"+ >+ <span+ class="flex min-w-0 items-center gap-1"+ :class="{ 'flex-1': !compact }">- <template v-if="compact">- <PlatformBrandIcon- v-if="post.platform"- :platform="post.platform"- colored- class="size-4 shrink-0"- />- </template>- <template v-else>- <span class="flex min-w-0 flex-1 flex-col gap-1">- <span class="flex min-w-0 items-center gap-1">- <PlatformBrandIcon- v-if="post.platform"- :platform="post.platform"- class="size-4 shrink-0"- />- <span- class="truncate text-xs font-medium text-muted-foreground"- >{{ time }}</span- >- <IconRepeat- v-if="scheduleMode && post.recurrence_frequency"- class="size-3 shrink-0 text-muted-foreground"- :aria-label="$t('posts.recurrence.marker')"- :data-testid="`calendar-post-recurring-${post.id}`"- />- <PostScheduleModeBadge- v-else-if="scheduleMode"- :post-id="post.id"- :mode="scheduleMode"- compact- plain- />- </span>- <span- v-if="layout === 'week'"- class="line-clamp-2 text-xs break-words text-foreground"- :class="{ 'text-muted-foreground': !text }"- :data-testid="`calendar-post-text-${post.id}`"- >{{ text || $t('calendar.no_content') }}</span- >- </span>+ <PlatformBrandIcon+ v-if="post.platform"+ :platform="post.platform"+ colored+ class="size-4 shrink-0"+ :data-testid="`calendar-post-platform-${post.id}`"+ />+ <span+ v-if="!compact"+ class="min-w-0 truncate text-xs font-medium text-muted-foreground"+ >{{ time }}</span+ >+ </span>+ <Tooltip :delay-duration="200">+ <TooltipTrigger as-child><span- v-if="thumbnail"- class="relative shrink-0 overflow-hidden rounded bg-secondary"- :class="layout === 'week' ? 'size-9' : 'size-5'"+ class="flex shrink-0 items-center"+ :class="statusMarker.tone"+ :aria-label="$t(statusLabelKey)"+ :data-testid="`${statusMarker.testId}-${post.id}`"+ :data-mode="statusKey">- <img- v-if="isImage(thumbnail)"- :src="thumbnail.url"- alt=""- loading="lazy"- class="size-full object-cover"+ <component+ :is="statusMarker.icon"+ :class="compact ? 'size-3' : 'size-3.5'"+ aria-hidden="true"/>- <template v-else>- <video- :src="videoFrameUrl(thumbnail)"- class="size-full object-cover"- muted- playsinline- preload="metadata"- />- <IconPlayerPlayFilled- aria-hidden="true"- class="absolute top-1/2 left-1/2 size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/60 p-0.5 text-white"- />- </template></span>+ </TooltipTrigger>+ <TooltipContent>{{ $t(statusLabelKey) }}</TooltipContent>+ </Tooltip>+ <span+ v-if="!compact && thumbnail"+ class="relative size-5 shrink-0 overflow-hidden rounded bg-secondary"+ :data-testid="`calendar-post-thumbnail-${post.id}`"+ >+ <img+ v-if="isImage(thumbnail)"+ :src="thumbnail.url"+ alt=""+ loading="lazy"+ class="size-full object-cover"+ />+ <template v-else>+ <video+ :src="videoFrameUrl(thumbnail)"+ class="size-full object-cover"+ muted+ playsinline+ preload="metadata"+ />+ <IconPlayerPlayFilled+ aria-hidden="true"+ class="absolute top-1/2 left-1/2 size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/60 p-0.5 text-white"+ /></template>- </button>- </PopoverTrigger>- <PopoverContent- side="right"- align="start"- :collision-padding="16"- class="max-h-(--reka-popover-content-available-height) w-[min(28rem,calc(100vw-2rem))] overflow-y-auto border border-border-strong p-0"- :class="{ hidden: !open }"- :force-mount="detailsOpen || isPhone"- :data-testid="`calendar-post-popover-${post.id}`"- @open-auto-focus="focusPopover"- >+ </span>+ </button>+ <div v-if="cardMounted" hidden><PostTimelineCardref="card":post="post":tab="tab":display-timezone="timezone":movable="false"- popover- @details="onDetails"/>- </PopoverContent>- </Popover>+ </div>+ </div></template>diff --git a/resources/js/components/publish/CalendarSlotChip.vue b/resources/js/components/publish/CalendarSlotChip.vueindex b0d92998c..4ea247248 100644--- a/resources/js/components/publish/CalendarSlotChip.vue+++ b/resources/js/components/publish/CalendarSlotChip.vue@@ -3,10 +3,15 @@ import { IconPlus } from '@tabler/icons-vue';import { computed } from 'vue';import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';+import {+ calendarTargetKey,+ useCalendarDragContext,+} from '@/composables/calendar/useCalendarDrag';import { openPostComposer } from '@/composables/useGlobalPostComposer';import { getPlatformLabel } from '@/composables/usePlatformLogo';import date from '@/date';import dayjs from '@/dayjs';+import type { CalendarDropTarget } from '@/lib/calendarDrop';import type { CalendarSlot, PublishSocialAccount } from '@/types/publish';const props = withDefaults(@@ -29,6 +34,21 @@ const testKey = computed(() => `${props.postingSlot.channel_id}-${dayjs.utc(props.postingSlot.at).unix()}`,);+const { overTarget, vCalendarTarget } = useCalendarDragContext();++const dropTarget = computed(+ (): CalendarDropTarget => ({+ kind: 'slot',+ at: props.postingSlot.at,+ channelId: props.postingSlot.channel_id,+ queueable: props.postingSlot.queueable,+ }),+);++const isOver = computed(+ () => overTarget.value === calendarTargetKey(dropTarget.value),+);+const newPost = (): void => {openPostComposer({socialAccountIds: [props.postingSlot.channel_id],@@ -79,14 +99,17 @@ const newPost = (): void => {</component><componentv-else+ v-calendar-target="dropTarget":is="canCreatePost ? 'button' : 'div'":type="canCreatePost ? 'button' : undefined"- class="group/slot flex shrink-0 items-center rounded-lg border border-dashed border-border-strong text-xs font-medium text-muted-foreground transition-control enabled:hover:bg-secondary enabled:hover:text-foreground enabled:focus-visible:bg-secondary enabled:focus-visible:text-foreground"- :class="+ class="group/slot flex shrink-0 items-center rounded-lg border border-dashed border-border-strong bg-[linear-gradient(135deg,transparent_45%,color-mix(in_srgb,var(--color-border)_60%,transparent)_45%_55%,transparent_55%)] bg-size-[8px_8px] text-xs font-medium text-subtle-foreground transition-control enabled:hover:bg-secondary enabled:hover:text-foreground enabled:focus-visible:bg-secondary enabled:focus-visible:text-foreground"+ :class="[compact? 'size-7 justify-center'- : 'h-7 w-full min-w-0 gap-1.5 px-1.5'- "+ : 'h-7 w-full min-w-0 gap-1.5 px-1.5',+ { 'bg-accent': isOver },+ ]"+ :data-drop-over="isOver || undefined":title="channel?.display_label":aria-label="channel@@ -103,6 +126,7 @@ const newPost = (): void => {<PlatformBrandIconv-if="channel":platform="channel.platform"+ class="opacity-60":class="compact ? 'size-3.5' : 'shrink-0'":data-testid="`calendar-posting-slot-icon-${testKey}`"/>diff --git a/resources/js/components/publish/CalendarTimeGrid.vue b/resources/js/components/publish/CalendarTimeGrid.vueindex bd1c08e77..adc0a3890 100644--- a/resources/js/components/publish/CalendarTimeGrid.vue+++ b/resources/js/components/publish/CalendarTimeGrid.vue@@ -4,9 +4,14 @@ import { computed, nextTick, onMounted, ref, watch } from 'vue';import CalendarPostChip from '@/components/publish/CalendarPostChip.vue';import CalendarSlotChip from '@/components/publish/CalendarSlotChip.vue';+import {+ calendarTargetKey,+ useCalendarDragContext,+} from '@/composables/calendar/useCalendarDrag';import { useBelowBreakpoint } from '@/composables/useBreakpoint';import date from '@/date';import dayjs from '@/dayjs';+import { wallClockIn, type CalendarDropTarget } from '@/lib/calendarDrop';import { calendarItems, type CalendarItem } from '@/lib/calendarItems';import type {CalendarPost,@@ -93,17 +98,60 @@ const visibleItems = (? items.slice(0, MAX_CHIPS - 1): items;-const slotStart = (key: string, hour: number): dayjs.Dayjs =>- dayjs.tz(`${key} ${String(hour).padStart(2, '0')}:00`, props.timezone);+const hourLabel = (hour: number): string => String(hour).padStart(2, '0');-const isPastSlot = (key: string, hour: number): boolean =>- slotStart(key, hour).isBefore(props.now);+const hourSlots = computed(() =>+ props.days.map((day) =>+ HOURS.map((hour) => {+ const start = dayjs.tz(+ `${day.format('YYYY-MM-DD')} ${hourLabel(hour)}:00`,+ props.timezone,+ );+ const target: CalendarDropTarget | null =+ wallClockIn(start, props.timezone).hour === hour+ ? { kind: 'hour', at: start.utc().format() }+ : null;-const hourLabel = (hour: number): string =>- `${String(hour).padStart(2, '0')}`;+ return {+ start,+ target,+ key: target ? calendarTargetKey(target) : null,+ };+ }),+ ),+);++const pastHours = computed(() =>+ hourSlots.value.map((hours) =>+ hours.map(({ start }) => start.isBefore(props.now)),+ ),+);++const isPastSlot = (column: number, hour: number): boolean =>+ pastHours.value[column][hour];++const { overTarget, draggingPostId, vCalendarTarget } =+ useCalendarDragContext();++const isHourOver = (column: number, hour: number): boolean =>+ hourSlots.value[column][hour].key !== null &&+ overTarget.value === hourSlots.value[column][hour].key;-const compose = (key: string, hour: number): void => {- emit('compose', slotStart(key, hour).utc().format());+const isDimmed = (column: number, hour: number, item: CalendarItem): boolean =>+ isHourOver(column, hour) && item.post?.id !== draggingPostId.value;++const itemClass = (+ column: { byHour: Map<number, CalendarItem[]> },+ index: number,+ hour: number,+ item: CalendarItem,+): string[] => [+ chipClass(column, hour),+ isDimmed(index, hour, item) ? 'opacity-50' : '',+];++const compose = (column: number, hour: number): void => {+ emit('compose', hourSlots.value[column][hour].start.utc().format());};const scrollToCurrentHour = (): void => {@@ -127,6 +175,7 @@ watch(<divref="scroller"class="flex-1 overflow-y-auto overscroll-contain"+ data-calendar-scrollerdata-testid="calendar-time-grid"><div@@ -163,13 +212,16 @@ watch(<divv-for="hour in HOURS":key="hour"+ v-calendar-target="hourSlots[index][hour].target"class="group relative flex items-start justify-between gap-1 px-1 py-2 md:px-3":class="{- 'bg-accent': isPastSlot(column.key, hour),+ 'bg-accent': isPastSlot(index, hour),+ 'bg-primary/15': isHourOver(index, hour),'border-t border-border-strong':hour > 0 && (index > 0 || hour % 2 === 1),}":style="{ height: `${ROW_HEIGHT}px` }"+ :data-drop-over="isHourOver(index, hour) || undefined":data-testid="`calendar-slot-${column.key}-${hourLabel(hour)}`"><div@@ -209,13 +261,8 @@ watch(v-if="item.post":post="item.post":timezone="timezone"- :layout="- isStacked(column, hour)- ? 'month'- : 'week'- ":compact="iconOnly"- :class="chipClass(column, hour)"+ :class="itemClass(column, index, hour, item)"/><CalendarSlotChipv-else-if="item.slot"@@ -224,7 +271,7 @@ watch(:timezone="timezone":can-create-post="canCreatePost":compact="iconOnly"- :class="chipClass(column, hour)"+ :class="itemClass(column, index, hour, item)"/></template><button@@ -247,12 +294,17 @@ watch(</div><button- v-if="canCreatePost && !isPastSlot(column.key, hour)"+ v-if="+ canCreatePost &&+ hourSlots[index][hour].target &&+ !isPastSlot(index, hour) &&+ !draggingPostId+ "type="button":aria-label="$t('calendar.new_post')"class="flex size-7 shrink-0 items-center justify-center rounded-lg border border-dashed border-border-strong text-muted-foreground opacity-0 transition-opacity duration-100 ease-in-out group-hover:opacity-100 hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100 max-md:hidden [@media(hover:none)]:opacity-100":data-testid="`calendar-add-${column.key}-${hourLabel(hour)}`"- @click="compose(column.key, hour)"+ @click="compose(index, hour)"><IconPlus class="size-3.5" /></button>diff --git a/resources/js/components/publish/CalendarUndatedPanel.vue b/resources/js/components/publish/CalendarUndatedPanel.vueindex d95c28121..e1cd27cef 100644--- a/resources/js/components/publish/CalendarUndatedPanel.vue+++ b/resources/js/components/publish/CalendarUndatedPanel.vue@@ -1,19 +1,26 @@<script setup lang="ts">import { InfiniteScroll, Link } from '@inertiajs/vue3';import { IconEdit, IconX } from '@tabler/icons-vue';+import { computed } from 'vue';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import {+ calendarTargetKey,+ HINT_ID_PREFIX,+ useCalendarDragContext,+} from '@/composables/calendar/useCalendarDrag';import {getPlatformLabel,getPlatformLogo,} from '@/composables/usePlatformLogo';+import type { CalendarDropTarget } from '@/lib/calendarDrop';import { isImage } from '@/lib/mediaType';import { htmlToPlainText } from '@/lib/utils';import { edit as editPost } from '@/routes/app/posts';import type { UndatedDraft } from '@/types/publish';-defineProps<{+const props = defineProps<{drafts: UndatedDraft[] | null;}>();@@ -21,16 +28,47 @@ const emit = defineEmits<{close: [];}>();-const thumbnail = (draft: UndatedDraft): string | null =>- (draft.media ?? []).find(isImage)?.url ?? null;+const UNDATED_TARGET: CalendarDropTarget = { kind: 'undated' };++const { overTarget, draggingPostId, vCalendarPost, vCalendarTarget } =+ useCalendarDragContext();++const isOver = computed(+ () => overTarget.value === calendarTargetKey(UNDATED_TARGET),+);++interface DraftPreview {+ text: string;+ thumbnail: string | null;+}-const plainText = (draft: UndatedDraft): string =>- htmlToPlainText(draft.content ?? '').trim();+/**+ * Each draft's text and thumbnail, worked out when the list changes, not on+ * every render (a drag re-renders the list).+ */+const previews = computed(+ () =>+ new Map<string, DraftPreview>(+ (props.drafts ?? []).map((draft) => [+ draft.id,+ {+ text: htmlToPlainText(draft.content ?? '').trim(),+ thumbnail: (draft.media ?? []).find(isImage)?.url ?? null,+ },+ ]),+ ),+);++const preview = (draft: UndatedDraft): DraftPreview =>+ previews.value.get(draft.id) ?? { text: '', thumbnail: null };</script><template><aside- class="flex min-h-0 w-full shrink-0 flex-col rounded-t-xl bg-muted md:w-[360px]"+ v-calendar-target="UNDATED_TARGET"+ class="flex min-h-0 w-full shrink-0 flex-col rounded-t-xl border bg-muted md:w-[360px]"+ :class="isOver ? 'border-primary' : 'border-transparent'"+ :data-drop-over="isOver || undefined"data-testid="calendar-undated-panel"><div class="flex shrink-0 items-start gap-4 px-4 pt-4 pb-3">@@ -84,51 +122,68 @@ const plainText = (draft: UndatedDraft): string =>preserve-url><div id="calendar-undated-list" class="flex flex-col gap-2">- <Link- v-for="draft in drafts"- :key="draft.id"- :href="editPost.url(draft.id)"- class="flex flex-col gap-1 rounded-lg border border-dashed border-border-strong bg-card px-2 py-2 text-start transition-control hover:bg-secondary"- :data-testid="`calendar-undated-${draft.id}`"- >- <div class="flex min-w-0 items-center gap-2">- <img- v-if="draft.platform"- :src="getPlatformLogo(draft.platform)"- :alt="getPlatformLabel(draft.platform)"- class="size-4 shrink-0 rounded-sm"- />- <span- class="min-w-0 flex-1 truncate text-sm leading-[17.5px] font-emphasis text-foreground"- >- {{- draft.social_account?.display_label ??- $t('calendar.undated.no_channel')- }}- </span>- <Badge variant="info" class="shrink-0">- <IconEdit />- {{ $t('calendar.undated.draft') }}- </Badge>- </div>- <div- v-if="plainText(draft) || thumbnail(draft)"- class="flex min-w-0 items-end gap-2"+ <template v-for="draft in drafts" :key="draft.id">+ <span+ v-if="draft.social_account"+ :id="`${HINT_ID_PREFIX}${draft.id}`"+ hidden+ :data-testid="`calendar-drag-hint-${draft.id}`"+ >{{+ $t('calendar.reschedule.drag_hint_undated', {+ channel: draft.social_account.display_label,+ })+ }}</span+ >+ <Link+ v-calendar-post="draft"+ :href="editPost.url(draft.id)"+ class="flex flex-col gap-1 rounded-lg border px-2 py-2 text-start transition-control [&[data-calendar-draggable=true]]:cursor-grab"+ :class="+ draggingPostId === draft.id+ ? 'border-transparent bg-secondary *:invisible'+ : 'border-dashed border-border-strong bg-card hover:bg-secondary'+ "+ :data-testid="`calendar-undated-${draft.id}`">- <p- class="line-clamp-2 min-w-0 flex-1 text-sm leading-[17.5px] break-words text-foreground"+ <div class="flex min-w-0 items-center gap-2">+ <img+ v-if="draft.platform"+ :src="getPlatformLogo(draft.platform)"+ :alt="getPlatformLabel(draft.platform)"+ class="size-4 shrink-0 rounded-sm"+ />+ <span+ class="min-w-0 flex-1 truncate text-sm leading-[17.5px] font-emphasis text-foreground"+ >+ {{+ draft.social_account?.display_label ??+ $t('calendar.undated.no_channel')+ }}+ </span>+ <Badge variant="info" class="shrink-0">+ <IconEdit />+ {{ $t('calendar.undated.draft') }}+ </Badge>+ </div>+ <div+ v-if="preview(draft).text || preview(draft).thumbnail"+ class="flex min-w-0 items-end gap-2">- {{ plainText(draft) }}- </p>- <img- v-if="thumbnail(draft)"- :src="thumbnail(draft)!"- alt=""- loading="lazy"- class="size-8 shrink-0 rounded object-cover"- />- </div>- </Link>+ <p+ class="line-clamp-2 min-w-0 flex-1 text-sm leading-[17.5px] break-words text-foreground"+ >+ {{ preview(draft).text }}+ </p>+ <img+ v-if="preview(draft).thumbnail"+ :src="preview(draft).thumbnail!"+ alt=""+ loading="lazy"+ class="size-8 shrink-0 rounded object-cover"+ />+ </div>+ </Link>+ </template></div><template #next="{ loading }">diff --git a/resources/js/components/publish/PostCardLabels.vue b/resources/js/components/publish/PostCardLabels.vueindex d5ff58fbb..ab161b78c 100644--- a/resources/js/components/publish/PostCardLabels.vue+++ b/resources/js/components/publish/PostCardLabels.vue@@ -102,6 +102,7 @@ const update = (ids: string[]): void => {<spanclass="inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-border-strong text-muted-foreground transition-control group-hover:bg-accent group-hover:text-foreground":class="{ 'bg-accent text-foreground': open }"+ :data-testid="`post-labels-${testKey}-edit`"><IconTag class="size-3.5" aria-hidden="true" /></span>diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vueindex 5327dc4c1..c0362ef1d 100644--- a/resources/js/components/publish/PostTimelineCard.vue+++ b/resources/js/components/publish/PostTimelineCard.vue@@ -95,7 +95,6 @@ const props = withDefaults(draggable?: boolean;gutterHandle?: boolean;movable?: boolean;- popover?: boolean;}>(),{canMoveUp: false,@@ -103,7 +102,6 @@ const props = withDefaults(draggable: false,gutterHandle: false,movable: true,- popover: false,},);@@ -168,7 +166,7 @@ const scheduleMode = computed(() => {: null;});-const showNotes = computed(() => !props.popover && !isPublishing.value);+const showNotes = computed(() => !isPublishing.value);const notesOpen = ref(openPostNotesId.value === props.post.id);const noteCount = ref(props.post.notes_count);@@ -392,20 +390,10 @@ defineExpose({ openDetails });<div:data-testid="`post-card-${post.id}`":data-post-id="post.id"- class="group/post relative"- :class="- popover- ? 'flex flex-col'- : 'grid grid-cols-1 gap-y-2 md:grid-cols-[71px_minmax(0,1fr)] md:gap-x-8'- "+ class="group/post relative grid grid-cols-1 gap-y-2 md:grid-cols-[71px_minmax(0,1fr)] md:gap-x-8"><div- class="flex flex-wrap items-center gap-2"- :class="- popover- ? 'border-b border-border-strong px-4 py-3'- : 'md:flex-col md:flex-nowrap md:items-start'- "+ class="flex flex-wrap items-center gap-2 md:flex-col md:flex-nowrap md:items-start"><span class="inline-flex items-center gap-1"><IconGripVertical@@ -421,16 +409,11 @@ defineExpose({ openDetails });/><timev-if="time"- class="text-sm text-foreground"- :class="popover ? 'font-emphasis' : 'font-medium'"+ class="text-sm font-medium text-foreground":datetime="time":data-testid="`post-time-${post.id}`">- {{- popover- ? date.formatDateTimeInTimezone(time, timezone)- : formatTime(time)- }}+ {{ formatTime(time) }}</time><span v-else class="text-sm font-medium text-muted-foreground">{{ $t('posts.publish.no_time') }}@@ -485,26 +468,11 @@ defineExpose({ openDetails });/>{{ $t(`posts.status.${post.status}`) }}</Badge>- <Button- v-if="popover && canCreatePost"- variant="ghost"- size="icon"- class="-my-1 ms-auto -me-2"- :aria-label="$t('posts.show.title')"- :data-testid="`post-details-expand-${post.id}`"- @click="openDetails"- >- <IconArrowsMaximize class="size-4" />- </Button></div><Collapsible v-model:open="notesOpen" as-child><article- class="min-w-0 overflow-hidden"- :class="{- 'rounded-xl border bg-card': !popover,- 'border-border-strong': !popover,- }"+ class="min-w-0 overflow-hidden rounded-xl border border-border-strong bg-card"><pv-if="recurrence && post.scheduled_at"@@ -521,7 +489,7 @@ defineExpose({ openDetails });/></p><div- v-if="isPublishing && !popover"+ v-if="isPublishing"class="relative flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-border-strong bg-secondary px-4 py-2.5 text-sm text-foreground"role="status":data-testid="`post-publishing-${post.id}`"@@ -578,7 +546,7 @@ defineExpose({ openDetails });</div><divclass="relative flex gap-4 p-4 md:gap-6"- :class="{ 'opacity-70': isPublishing && !popover }"+ :class="{ 'opacity-70': isPublishing }"><div:draggable="draggable ? 'false' : undefined"@@ -610,12 +578,6 @@ defineExpose({ openDetails });getPlatformLabel(platform ?? '')}}</p>- <p- v-if="popover && account?.handle_label"- class="truncate text-xs text-muted-foreground"- >- {{ account.handle_label }}- </p></div><Badgev-if="contentTypeKey"@@ -637,7 +599,6 @@ defineExpose({ openDetails });class="line-clamp-4 text-sm whitespace-pre-line text-foreground":class="{'text-muted-foreground': !preview,- 'leading-relaxed': popover,}">{{ preview || $t('calendar.no_content') }}@@ -648,7 +609,7 @@ defineExpose({ openDetails });class="relative z-10 grid w-24 shrink-0 content-start gap-2":class="[thumbnails.length > 1 ? 'grid-cols-2' : '',- popover ? 'w-36' : 'md:w-[180px]',+ 'md:w-[180px]',]"><button@@ -729,12 +690,10 @@ defineExpose({ openDetails });/><div- class="m-2 flex min-h-14 flex-wrap items-center gap-x-4 gap-y-2 rounded-xl bg-muted p-3 [&_[data-variant=ghost]:hover]:bg-secondary"- :class="popover ? 'justify-end' : 'justify-between'"+ class="m-2 flex min-h-14 flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-xl bg-muted p-3 [&_[data-variant=ghost]:hover]:bg-secondary":data-testid="`post-footer-${post.id}`"><p- v-if="!popover"class="min-w-0 truncate text-sm text-foreground":class="{ 'max-sm:hidden': post.origin === PostOrigin.Network }">diff --git a/resources/js/components/ui/sonner/Sonner.vue b/resources/js/components/ui/sonner/Sonner.vueindex 878aa58c6..2142d6d1c 100644--- a/resources/js/components/ui/sonner/Sonner.vue+++ b/resources/js/components/ui/sonner/Sonner.vue@@ -6,6 +6,7 @@ import {IconCircleCheckFilled,IconInfoCircleFilled,IconLoader2,+ IconX,} from "@tabler/icons-vue"import { Toaster as Sonner } from "vue-sonner"@@ -15,8 +16,11 @@ const props = defineProps<ToasterProps>()<template><Sonnerv-bind="props"- position="bottom-right"+ position="top-center"+ offset="16px"+ close-button:style="{+ '--width': '480px','--normal-bg': 'var(--popover)','--normal-text': 'var(--popover-foreground)','--normal-border': 'var(--border)',@@ -49,29 +53,63 @@ const props = defineProps<ToasterProps>()<template #loading-icon><IconLoader2 class="size-5 animate-spin" /></template>+ <template #close-icon>+ <IconX class="size-4" />+ </template></Sonner></template><style>[data-sonner-toaster] [data-sonner-toast][data-styled="true"] {- gap: 10px;- padding: 14px 16px;- border-color: transparent;+ align-items: flex-start;+ gap: 8px;+ padding: 12px 16px 12px 12px;+ border: 0;border-radius: 12px;- box-shadow: var(--shadow-md);+ box-shadow:+ 0 0 0 1px var(--border),+ 0 0 1px 1px rgb(0 0 0 / 0.09),+ 0 4px 8px -4px rgb(0 0 0 / 0.12),+ 0 16px 24px -8px rgb(0 0 0 / 0.12);font-size: 14px;- font-weight: 500;- line-height: 20px;+ font-weight: 400;+ line-height: 21px;}-.dark [data-sonner-toaster] [data-sonner-toast][data-styled="true"] {- border-color: var(--border);+[data-sonner-toaster] [data-sonner-toast] [data-icon] {+ width: 24px;+ height: 24px;+ margin: 0;+ justify-content: center;}-[data-sonner-toaster] [data-sonner-toast] [data-icon] {+[data-sonner-toaster] [data-sonner-toast] [data-icon] svg {width: 20px;height: 20px;- margin: 0;+}++[data-sonner-toaster] [data-sonner-toast] [data-content] {+ flex: 1 1 auto;+ min-width: 0;+ padding-top: 1.5px;+}++[data-sonner-toaster] [data-sonner-toast][data-styled="true"] [data-close-button] {+ position: static;+ order: 99;+ flex-shrink: 0;+ width: 24px;+ height: 24px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--muted-foreground);+ transform: none;+}++[data-sonner-toaster] [data-sonner-toast][data-styled="true"] [data-close-button]:hover {+ background: var(--accent);+ color: var(--foreground);}[data-sonner-toaster] [data-sonner-toast] [data-description] {diff --git a/resources/js/composables/calendar/useCalendarAnnouncer.ts b/resources/js/composables/calendar/useCalendarAnnouncer.tsnew file mode 100644index 000000000..308e08f2c--- /dev/null+++ b/resources/js/composables/calendar/useCalendarAnnouncer.ts@@ -0,0 +1,146 @@+import { trans } from 'laravel-vue-i18n';+import { ref, type Ref } from 'vue';++import type { CalendarDragLifecycle } from '@/composables/calendar/useCalendarDrag';+import { getPlatformLabel } from '@/composables/usePlatformLogo';+import date from '@/date';+import dayjs from '@/dayjs';+import type { CalendarDropTarget } from '@/lib/calendarDrop';+import type { PostCard } from '@/types/publish';++export const useCalendarAnnouncer = (+ timezone: Readonly<Ref<string>>,+): {+ announcement: Ref<string>;+ describeInstant: (+ at: string,+ target: CalendarDropTarget,+ previousAt: string | null,+ ) => string;+ hooks: Required<CalendarDragLifecycle>;+} => {+ const announcement = ref('');++ const describeAt = (at: string, dateOnly: boolean): string => {+ const day = date.formatWeekdayMonthDay(at, timezone.value);++ return dateOnly+ ? day+ : trans('calendar.reschedule.announce.date_time', {+ date: day,+ time: date.formatTimeInTimezone(at, timezone.value),+ });+ };++ const clockOf = (at: string): string =>+ dayjs.utc(at).tz(timezone.value).format('HH:mm');++ /**+ * A day drop keeps the post's clock time, so it names the date only, unless+ * the time changed too (today after that time moves it to a few minutes+ * from now) or was never the user's (an undated draft lands at nine), which+ * the user has to hear.+ */+ const describeInstant = (+ at: string,+ target: CalendarDropTarget,+ previousAt: string | null,+ ): string =>+ describeAt(+ at,+ target.kind === 'day' &&+ previousAt !== null &&+ clockOf(previousAt) === clockOf(at),+ );++ const describeTarget = (target: CalendarDropTarget): string => {+ switch (target.kind) {+ case 'undated':+ return trans('calendar.no_date');+ case 'day':+ return describeAt(+ date.wallClockToUtc(`${target.dayKey}T00:00`, timezone.value),+ true,+ );+ default:+ return describeAt(target.at, false);+ }+ };++ const channelLabel = (post: PostCard): string =>+ post.social_account?.display_label ??+ (post.platform ? getPlatformLabel(post.platform) : '');++ const announce = (message: string): void => {+ announcement.value = message;+ };++ const announceOver = (+ post: PostCard,+ target: CalendarDropTarget | null,+ accepts: boolean,+ ): void => {+ if (!target || !accepts) {+ return;+ }++ const message = post.scheduled_at+ ? trans('calendar.reschedule.announce.over', {+ from: describeAt(post.scheduled_at, false),+ target: describeTarget(target),+ })+ : trans('calendar.reschedule.announce.over_undated', {+ channel: channelLabel(post),+ target: describeTarget(target),+ });++ announcement.value = message;+ };++ const announceDrop = (+ post: PostCard,+ target: CalendarDropTarget,+ scheduledAt: string | null,+ ): void => {+ if (scheduledAt === null) {+ announce(+ trans('calendar.reschedule.announce.undated', {+ from: describeAt(post.scheduled_at ?? '', false),+ }),+ );++ return;+ }++ const to = describeInstant(scheduledAt, target, post.scheduled_at);++ announce(+ post.scheduled_at+ ? trans('calendar.reschedule.announce.moved', {+ from: describeAt(post.scheduled_at, false),+ to,+ })+ : trans('calendar.reschedule.announce.from_undated', {+ channel: channelLabel(post),+ to,+ }),+ );+ };++ const clearAnnouncement = (): void => announce('');++ const announceReturn = (): void =>+ announce(trans('calendar.reschedule.announce.returned'));++ return {+ announcement,+ describeInstant,+ hooks: {+ onDragStart: clearAnnouncement,+ onOver: announceOver,+ onConfirmed: announceDrop,+ onRejected: announceReturn,+ onCancel: announceReturn,+ },+ };+};diff --git a/resources/js/composables/calendar/useCalendarDrag.ts b/resources/js/composables/calendar/useCalendarDrag.tsnew file mode 100644index 000000000..d3a792c77--- /dev/null+++ b/resources/js/composables/calendar/useCalendarDrag.ts@@ -0,0 +1,1141 @@+import { router, usePage } from '@inertiajs/vue3';+import { trans } from 'laravel-vue-i18n';+import {+ inject,+ onBeforeUnmount,+ ref,+ type Directive,+ type InjectionKey,+ type Ref,+} from 'vue';+import { toast } from 'vue-sonner';++import { update as updatePostSchedule } from '@/actions/App/Http/Controllers/App/PostScheduleController';+import dayjs from '@/dayjs';+import {+ canDragCalendarPost,+ dropInstant,+ entersQueueSlot,+ needsCustomTimeConfirmation,+ wallClockIn,+ type CalendarDropTarget,+} from '@/lib/calendarDrop';+import { cancelDragOnEscape, edgeScrollDelta } from '@/lib/dragPlaceholder';+import { PostStatus, ScheduleMode } from '@/types/post';+import type {+ CalendarPost,+ PostCard,+ ScrollUndatedDrafts,+ UndatedDraft,+} from '@/types/publish';++const CALENDAR_AUTO_SCROLL_STEP = 20;++export interface CalendarDrag {+ overTarget: Ref<string | null>;+ draggingPostId: Ref<string | null>;+ movingPostIds: Ref<string[]>;+ vCalendarPost: Directive<HTMLElement, PostCard>;+ vCalendarTarget: Directive<HTMLElement, CalendarDropTarget | null>;+}++type CalendarDragContext = Pick<+ CalendarDrag,+ | 'overTarget'+ | 'draggingPostId'+ | 'vCalendarPost'+ | 'vCalendarTarget'+>;++export const calendarDragKey: InjectionKey<CalendarDragContext> =+ Symbol('calendarDrag');++export interface CalendarDragLifecycle {+ onDragStart?: (post: PostCard) => void;+ onOver?: (+ post: PostCard,+ target: CalendarDropTarget | null,+ accepts: boolean,+ ) => void;+ onCancel?: (post: PostCard) => void;+ onConfirmed?: (+ post: PostCard,+ target: CalendarDropTarget,+ scheduledAt: string | null,+ ) => void;+ onRejected?: (post: PostCard) => void;+}++interface Gesture {+ el: HTMLElement;+ post: PostCard;+ pointerId: number;+ pointerType: string;+ startX: number;+ startY: number;+ x: number;+ y: number;+ active: boolean;+ timer: number | null;+}++interface HoveredTarget {+ target: CalendarDropTarget;+ accepts: boolean;+}++const MOUSE_ACTIVATION_DISTANCE = 4;+const TOUCH_ACTIVATION_DELAY = 250;+const TOUCH_ACTIVATION_TOLERANCE = 5;+const DRAGGABLE_ATTRIBUTE = 'data-calendar-draggable';+const DROP_ATTRIBUTE = 'data-calendar-drop';+const SCROLLER_ATTRIBUTE = 'data-calendar-scroller';+const PREVIEW_CLASSES = [+ 'pointer-events-none',+ 'fixed',+ 'z-50',+ 'm-0',+ 'opacity-80',+ 'rotate-[2.765deg]',+];+export const HINT_ID_PREFIX = 'calendar-drag-hint-';++/**+ * The hint every dated card shares; a No Date draft has its own, naming its channel.+ */+export const DRAG_HINT_ID = 'calendar-drag-hint';+const GRABBING_CLASS = 'cursor-grabbing';++export const calendarTargetKey = (target: CalendarDropTarget): string => {+ switch (target.kind) {+ case 'hour':+ return `hour-${target.at}`;+ case 'day':+ return `day-${target.dayKey}`;+ case 'slot':+ return `slot-${target.channelId}-${target.at}`;+ default:+ return 'undated';+ }+};++const swallowClick = (event: Event): void => {+ event.preventDefault();+ event.stopPropagation();+};++const suppressNextClick = (): void => {+ window.addEventListener('click', swallowClick, {+ capture: true,+ once: true,+ });+ window.setTimeout(() => {+ window.removeEventListener('click', swallowClick, { capture: true });+ }, 0);+};++export const useCalendarDragContext = (): CalendarDragContext =>+ inject(+ calendarDragKey,+ () => ({+ overTarget: ref<string | null>(null),+ draggingPostId: ref<string | null>(null),+ vCalendarPost: {},+ vCalendarTarget: {},+ }),+ true,+ );++export const useCalendarDrag = (+ options: {+ timezone: Readonly<Ref<string>>;+ canCreatePost: Readonly<Ref<boolean>>;+ requiresApproval: Readonly<Ref<boolean>>;+ reloadProps: () => string[];+ isCalendarPath: (pathname: string) => boolean;+ confirmCustomTime: (from: string, to: string) => Promise<boolean>;+ describeInstant: (+ at: string,+ target: CalendarDropTarget,+ previousAt: string | null,+ ) => string;+ } & CalendarDragLifecycle,+): CalendarDrag => {+ const page = usePage();+ const overTarget = ref<string | null>(null);+ let hoveredTarget: string | null = null;+ const draggingPostId = ref<string | null>(null);+ const movingPostIds = ref<string[]>([]);+ const waitingForServer: Array<() => void> = [];+ let movesSent = 0;+ let newestMoveAnswered = 0;+ let heldVisit: { url: string; method: string } | null = null;++ const posts = new Map<HTMLElement, PostCard>();+ const targets = new Map<Element, CalendarDropTarget>();+ const postCleanups = new Map<HTMLElement, () => void>();++ let preview: HTMLElement | null = null;+ let previewOffset = { x: 0, y: 0 };+ let gesture: Gesture | null = null;+ let frame: number | null = null;+ let scroller: HTMLElement | null = null;+ let pointerMoved = false;+ let stopEscape: (() => void) | null = null;++ const isDraggable = (post: PostCard): boolean =>+ !movingPostIds.value.includes(post.id) &&+ canDragCalendarPost(post, dayjs(), options.canCreatePost.value);++ /**+ * A member who needs approval cannot put a post in the queue at a posting+ * time, as on the queue page, so its channel's posting times refuse it.+ */+ const instantFor = (+ post: PostCard,+ target: CalendarDropTarget,+ ): string | null | undefined =>+ options.requiresApproval.value && entersQueueSlot(post, target)+ ? undefined+ : dropInstant(post, target, options.timezone.value, dayjs());++ const placePreview = (input: { clientX: number; clientY: number }): void => {+ if (preview) {+ preview.style.left = `${input.clientX - previewOffset.x}px`;+ preview.style.top = `${input.clientY - previewOffset.y}px`;+ }+ };++ const showPreview = (+ el: HTMLElement,+ input: { clientX: number; clientY: number },+ ): void => {+ const rect = el.getBoundingClientRect();+ const copy = el.cloneNode(true) as HTMLElement;++ copy.querySelectorAll('[data-testid], [id]').forEach((node) => {+ node.removeAttribute('data-testid');+ node.removeAttribute('id');+ });+ copy.removeAttribute('id');+ copy.removeAttribute('aria-describedby');+ copy.querySelectorAll('video').forEach((video) => {+ video.removeAttribute('src');+ video.preload = 'none';+ });+ copy.removeAttribute(DRAGGABLE_ATTRIBUTE);+ copy.setAttribute('aria-hidden', 'true');+ copy.dataset.testid = 'calendar-drag-preview';+ copy.classList.add(...PREVIEW_CLASSES);+ copy.style.width = `${rect.width}px`;+ copy.style.height = `${rect.height}px`;++ previewOffset = {+ x: input.clientX - rect.left,+ y: input.clientY - rect.top,+ };+ preview = copy;+ placePreview(input);+ document.body.appendChild(copy);+ };++ const endDrag = (): void => {+ preview?.remove();+ preview = null;+ overTarget.value = null;+ hoveredTarget = null;+ draggingPostId.value = null;+ document.body.classList.remove(GRABBING_CLASS);+ };++ const movedScheduleMode = (+ post: PostCard,+ target: CalendarDropTarget,+ ): PostCard['schedule_mode'] => {+ if (post.status !== PostStatus.Scheduled) {+ return post.schedule_mode;+ }++ return entersQueueSlot(post, target)+ ? ScheduleMode.Queue+ : ScheduleMode.Custom;+ };++ const movedPost = (+ post: PostCard,+ target: CalendarDropTarget,+ scheduledAt: string | null,+ ): CalendarPost => ({+ ...post,+ status: scheduledAt === null ? PostStatus.Draft : post.status,+ scheduled_at: scheduledAt,+ calendar_at: scheduledAt ?? '',+ schedule_mode: movedScheduleMode(post, target),+ });++ /**+ * Ends a move: the post's cards may be dragged again. A card mounted in its+ * new cell while the move was on its way registered as not draggable, and+ * nothing re-renders it when the move lands, so its cards are synced here.+ */+ const forget = (postId: string): void => {+ movingPostIds.value = movingPostIds.value.filter((id) => id !== postId);++ posts.forEach((card, el) => {+ if (card.id === postId) {+ syncPost(el, card);+ }+ });+ };++ /**+ * The page props with a post shown where it was dropped, for Inertia's+ * optimistic update: it is applied at once, kept while other moves of the+ * same props are in flight, and rolled back when the move fails.+ */+ const movedProps = (+ props: Record<string, unknown>,+ moved: CalendarPost,+ touchesNoDate: boolean,+ ): Record<string, unknown> => {+ const posts = Object.fromEntries(+ Object.entries(+ (props.posts ?? {}) as Record<string, CalendarPost[]>,+ ).map(([key, list]) => [+ key,+ list.some((post) => post.id === moved.id)+ ? list.filter((post) => post.id !== moved.id)+ : list,+ ]),+ );++ if (moved.scheduled_at !== null) {+ const key = wallClockIn(+ dayjs.utc(moved.calendar_at),+ options.timezone.value,+ ).date;++ posts[key] = [...(posts[key] ?? []), moved];+ }++ const undatedDrafts = props.undatedDrafts as+ | ScrollUndatedDrafts+ | undefined;++ if (!touchesNoDate || !undatedDrafts) {+ return { posts };+ }++ return {+ posts,+ undatedDrafts: {+ ...undatedDrafts,+ data: [+ ...(moved.scheduled_at === null+ ? [{ ...moved, scheduled_at: null } as UndatedDraft]+ : []),+ ...undatedDrafts.data.filter(+ (draft) => draft.id !== moved.id,+ ),+ ],+ },+ };+ };++ const rollback = (postId: string, message?: string): void => {+ forget(postId);+ toast.error(message ?? trans('calendar.reschedule.error'), {+ testId: 'calendar-reschedule-error-toast',+ });+ };++ const successMessage = (+ post: PostCard,+ target: CalendarDropTarget,+ scheduledAt: string | null,+ ): string => {+ const leavesTheQueue =+ post.status === PostStatus.Scheduled &&+ post.schedule_mode === ScheduleMode.Queue &&+ !entersQueueSlot(post, target);+ const queueNote = leavesTheQueue+ ? ` ${trans('calendar.reschedule.toast.unqueued_suffix')}`+ : '';++ if (scheduledAt === null) {+ return post.status === PostStatus.Draft+ ? trans('calendar.reschedule.toast.undated')+ : `${trans('calendar.reschedule.toast.unscheduled')}${queueNote}`;+ }++ const time = options.describeInstant(+ scheduledAt,+ target,+ post.scheduled_at,+ );+ const message = trans(+ post.status === PostStatus.Draft+ ? 'calendar.reschedule.toast.moved_draft'+ : 'calendar.reschedule.toast.moved',+ { time },+ );++ return `${message}${queueNote}`;+ };++ const postIn = (+ props: Record<string, unknown>,+ postId: string,+ ): CalendarPost | null =>+ Object.values(+ (props.posts as Record<string, CalendarPost[]> | undefined) ?? {},+ )+ .flat()+ .find((candidate) => candidate.id === postId) ?? null;++ /**+ * While a move is in flight, Inertia shows its guess in place of the props+ * another move's answer brought back. A move answered then settles when the+ * last move in flight finishes: the page shows the server's props by then,+ * and a failed move's guess has been rolled back.+ */+ const settleWaitingMoves = (): void => {+ if (movingPostIds.value.length > 0) {+ return;+ }++ waitingForServer.splice(0).forEach((settle) => settle());++ if (heldVisit) {+ const { url, method } = heldVisit;++ heldVisit = null;+ router.visit(url, { method: method as 'get' });+ }+ };++ /**+ * While a move is in flight, Inertia keeps its guess in the `posts` prop of+ * any page it renders, so a visit that leaves the calendar's path waits for+ * the moves in flight and goes once they finish.+ */+ const stopHoldingVisits = router.on('before', (event) => {+ const { visit } = event.detail;++ if (+ movingPostIds.value.length === 0 ||+ visit.async ||+ visit.prefetch ||+ options.isCalendarPath(visit.url.pathname)+ ) {+ return;+ }++ heldVisit = { url: visit.url.href, method: visit.method };++ return false;+ });++ onBeforeUnmount(stopHoldingVisits);++ const isSameInstant = (+ stored: string | null,+ requested: string | null,+ ): boolean =>+ stored === null || requested === null+ ? stored === requested+ : dayjs.utc(stored).isSame(dayjs.utc(requested));++ /**+ * The custom time dialog can stay open for a while: once confirmed, the drop+ * is checked again against the clock. The time the dialog showed is sent+ * while it is still ahead; once it has passed, it is worked out again.+ */+ const confirmedInstant = async (+ post: PostCard,+ target: CalendarDropTarget,+ droppedAt: string | null,+ ): Promise<string | null | undefined> => {+ if (+ !needsCustomTimeConfirmation(post, target) ||+ !post.scheduled_at ||+ !droppedAt+ ) {+ return droppedAt;+ }++ if (!(await options.confirmCustomTime(post.scheduled_at, droppedAt))) {+ return undefined;+ }++ if (!isDraggable(post)) {+ return undefined;+ }++ return dayjs.utc(droppedAt).isAfter(dayjs())+ ? droppedAt+ : instantFor(post, target);+ };++ const move = async (+ post: PostCard,+ target: CalendarDropTarget,+ droppedAt: string | null,+ ): Promise<void> => {+ const scheduledAt = await confirmedInstant(post, target, droppedAt);++ if (scheduledAt === undefined) {+ options.onCancel?.(post);++ return;+ }++ movingPostIds.value = [...movingPostIds.value, post.id];++ let settled = false;++ const confirm = (): void => {+ if (!settled) {+ settled = true;+ options.onConfirmed?.(post, target, scheduledAt);+ }+ };++ const reject = (): void => {+ if (!settled) {+ settled = true;+ options.onRejected?.(post);+ }+ };++ const fail = (message?: string): false => {+ reject();+ rollback(post.id, message);++ return false;+ };++ const component = page.component;+ const touchesNoDate =+ target.kind === 'undated' || post.scheduled_at === null;+ const props = (): string[] =>+ options+ .reloadProps()+ .filter((prop) => touchesNoDate || prop !== 'undatedDrafts')+ .filter(+ (prop) =>+ post.status !== PostStatus.Draft || prop !== 'slots',+ );+ const reset = touchesNoDate ? ['undatedDrafts'] : [];+ let reloaded: CalendarPost | null | undefined;+ let staleResponse = false;+ let guessed = false;+ let answered = false;+ const moveNumber = ++movesSent;++ const announceApproval = (): void => {+ toast.success(trans('posts.approvals.requested'), {+ testId: 'calendar-reschedule-approval-toast',+ });+ confirm();+ };++ const announceMoved = (): void => {+ confirm();+ toast.success(successMessage(post, target, scheduledAt), {+ testId: 'calendar-reschedule-success-toast',+ });+ };++ /**+ * Settles a move from the post as the server shows it: gone from a list+ * it should still be on means it waits for approval (or was refused for+ * a user who publishes directly), another time means it was refused.+ */+ const settleFrom = (shown: CalendarPost | null): void => {+ if (settled) {+ return;+ }++ const leftTheList =+ shown === null &&+ scheduledAt !== null &&+ post.status !== PostStatus.Draft;++ if (leftTheList && !options.requiresApproval.value) {+ reject();++ return;+ }++ if (leftTheList || shown?.status === PostStatus.PendingApproval) {+ announceApproval();++ return;+ }++ if (shown && !isSameInstant(shown.scheduled_at, scheduledAt)) {+ reject();++ return;+ }++ announceMoved();+ };++ /**+ * Reloads the page shown instead of reading a move's answer. Inertia+ * reloads asynchronously, so an answer that lands after the user moved+ * to another page of the same path (a filter, a period) is dropped like+ * a stale move answer instead of bringing the old page back.+ */+ const reloadInstead = (settleFromIt: boolean): void => {+ staleResponse = true;++ let shown: CalendarPost | null | undefined;++ router.reload({+ only: props(),+ reset,+ onBeforeUpdate: (response) => {+ if (response.component !== page.component) {+ return;+ }++ if (response.url !== page.url) {+ response.props = { ...page.props };+ response.url = page.url;++ return;+ }++ shown = postIn(response.props, post.id);+ },+ onSuccess: () => {+ if (settleFromIt && shown) {+ settleFrom(shown);+ }+ },+ onFinish: () => {+ forget(post.id);+ settleWaitingMoves();+ },+ });+ };++ router.put(+ updatePostSchedule.url(post.id),+ {+ action: 'reschedule',+ scheduled_at: scheduledAt,+ queue_slot: entersQueueSlot(post, target),+ },+ {+ async: true,+ preserveScroll: true,+ preserveState: true,+ only: [...props(), 'flash'],+ reset,+ optimistic: (pageProps) =>+ movedProps(+ pageProps,+ movedPost(post, target, scheduledAt),+ touchesNoDate,+ ),+ onBeforeUpdate: (response) => {+ answered = true;+ guessed =+ router.hasPendingOptimistic() ||+ newestMoveAnswered > moveNumber;+ newestMoveAnswered = Math.max(+ newestMoveAnswered,+ moveNumber,+ );+ reloaded = postIn(response.props, post.id);++ if (+ response.url === page.url ||+ response.component !== page.component+ ) {+ return;+ }++ staleResponse = true;+ response.props = {+ ...page.props,+ flash: response.props.flash,+ errors: response.props.errors,+ };+ response.url = page.url;+ },+ onSuccess: () => {+ answered = true;++ if (page.component !== component) {+ return;+ }++ if (reloaded === undefined) {+ reloadInstead(true);++ return;+ }++ if (staleResponse) {+ reloadInstead(false);++ if (guessed) {+ waitingForServer.push(() => {+ const shown = postIn(page.props, post.id);++ if (shown) {+ settleFrom(shown);+ }+ });++ return;+ }+ } else if (guessed) {+ waitingForServer.push(() =>+ settleFrom(postIn(page.props, post.id)),+ );++ return;+ }++ settleFrom(reloaded);+ },+ onError: (errors) => {+ answered = true;+ fail(Object.values(errors)[0]);+ },+ onHttpException: () => {+ answered = true;++ return fail();+ },+ onNetworkError: () => {+ answered = true;++ return fail();+ },+ onCancel: () => {+ answered = true;+ reject();+ },+ onFinish: () => {+ if (!staleResponse) {+ forget(post.id);+ }++ settleWaitingMoves();++ if (!answered) {+ router.visit(page.url, { preserveScroll: true });+ }+ },+ },+ );+ };++ const targetAt = (+ post: PostCard,+ x: number,+ y: number,+ ): HoveredTarget | null => {+ let refusing: CalendarDropTarget | null = null;++ for (const element of document.elementsFromPoint(x, y)) {+ const target = targets.get(element);++ if (!target) {+ continue;+ }++ if (instantFor(post, target) !== undefined) {+ return { target, accepts: true };+ }++ if (entersQueueSlot(post, target)) {+ return { target, accepts: false };+ }++ refusing ??= target;+ }++ return refusing ? { target: refusing, accepts: false } : null;+ };++ const updateOver = (): void => {+ if (!gesture?.active) {+ return;+ }++ placePreview({ clientX: gesture.x, clientY: gesture.y });++ const hovered = targetAt(gesture.post, gesture.x, gesture.y);+ const key = hovered ? calendarTargetKey(hovered.target) : null;+ const acceptingKey = hovered?.accepts ? key : null;++ if (key === hoveredTarget && acceptingKey === overTarget.value) {+ return;+ }++ hoveredTarget = key;+ overTarget.value = acceptingKey;+ options.onOver?.(+ gesture.post,+ hovered?.target ?? null,+ hovered?.accepts ?? false,+ );+ };++ const tick = (): void => {+ if (!gesture?.active) {+ frame = null;++ return;+ }++ if (scroller) {+ const before = scroller.scrollTop;++ scroller.scrollTop += edgeScrollDelta(+ scroller,+ { clientX: gesture.x, clientY: gesture.y },+ 'vertical',+ CALENDAR_AUTO_SCROLL_STEP,+ );+ pointerMoved ||= scroller.scrollTop !== before;+ }++ if (pointerMoved) {+ pointerMoved = false;+ updateOver();+ }++ frame = requestAnimationFrame(tick);+ };++ const preventWhileDragging = (event: Event): void => {+ if (gesture?.active) {+ event.preventDefault();+ }+ };++ const onPointerMove = (event: PointerEvent): void => {+ if (!gesture || event.pointerId !== gesture.pointerId) {+ return;+ }++ if (gesture.pointerType !== 'touch' && event.buttons === 0) {+ cancel();++ return;+ }++ gesture.x = event.clientX;+ gesture.y = event.clientY;++ if (gesture.active) {+ event.preventDefault();+ pointerMoved = true;++ return;+ }++ const distance = Math.hypot(+ gesture.x - gesture.startX,+ gesture.y - gesture.startY,+ );++ if (gesture.pointerType === 'touch') {+ if (distance > TOUCH_ACTIVATION_TOLERANCE) {+ release();+ }++ return;+ }++ if (distance > MOUSE_ACTIVATION_DISTANCE) {+ activate();+ }+ };++ const onPointerUp = (event: PointerEvent): void => {+ if (!gesture || event.pointerId !== gesture.pointerId) {+ return;+ }++ if (!gesture.active) {+ release();++ return;+ }++ gesture.x = event.clientX;+ gesture.y = event.clientY;++ const post = gesture.post;+ const hovered = targetAt(post, gesture.x, gesture.y);++ release();+ suppressNextClick();++ const scheduledAt = hovered?.accepts+ ? instantFor(post, hovered.target)+ : undefined;++ if (!hovered || scheduledAt === undefined || !isDraggable(post)) {+ options.onCancel?.(post);++ return;+ }++ void move(post, hovered.target, scheduledAt);+ };++ const cancel = (): void => {+ const post = gesture?.active ? gesture.post : null;++ release();++ if (post) {+ options.onCancel?.(post);+ }+ };++ /**+ * Esc ends a drag while the button is still down: the click the release+ * then fires on the card it started from is swallowed like after a drop.+ * A blur or a hidden tab does not: the release may never reach this window.+ */+ const cancelOnEscape = (): void => {+ cancel();+ window.addEventListener('pointerup', suppressNextClick, {+ capture: true,+ once: true,+ });+ window.addEventListener(+ 'pointerdown',+ () =>+ window.removeEventListener('pointerup', suppressNextClick, {+ capture: true,+ }),+ { capture: true, once: true },+ );+ };++ const onPointerCancel = (event: PointerEvent): void => {+ if (gesture && event.pointerId === gesture.pointerId) {+ cancel();+ }+ };++ const onVisibilityChange = (): void => {+ if (document.visibilityState === 'hidden') {+ cancel();+ }+ };++ const listen = (): void => {+ window.addEventListener('pointermove', onPointerMove);+ window.addEventListener('pointerup', onPointerUp);+ window.addEventListener('pointercancel', onPointerCancel);+ stopEscape = cancelDragOnEscape(+ cancelOnEscape,+ () => gesture?.active === true,+ );+ window.addEventListener('contextmenu', preventWhileDragging);+ window.addEventListener('blur', cancel);+ document.addEventListener('visibilitychange', onVisibilityChange);+ };++ const unlisten = (): void => {+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ window.removeEventListener('pointercancel', onPointerCancel);+ stopEscape?.();+ stopEscape = null;+ window.removeEventListener('contextmenu', preventWhileDragging);+ window.removeEventListener('blur', cancel);+ document.removeEventListener('visibilitychange', onVisibilityChange);+ };++ const activate = (): void => {+ if (!gesture || gesture.active) {+ return;+ }++ if (gesture.timer !== null) {+ window.clearTimeout(gesture.timer);+ gesture.timer = null;+ }++ gesture.active = true;+ gesture.el.style.touchAction = 'none';+ draggingPostId.value = gesture.post.id;+ document.body.classList.add(GRABBING_CLASS);+ window.getSelection()?.removeAllRanges();+ showPreview(gesture.el, {+ clientX: gesture.startX,+ clientY: gesture.startY,+ });+ scroller = document.querySelector<HTMLElement>(`[${SCROLLER_ATTRIBUTE}]`);+ options.onDragStart?.(gesture.post);+ updateOver();+ frame = requestAnimationFrame(tick);+ };++ const release = (): void => {+ if (gesture?.timer !== null && gesture?.timer !== undefined) {+ window.clearTimeout(gesture.timer);+ }++ if (gesture?.active) {+ gesture.el.style.removeProperty('touch-action');+ }++ if (frame !== null) {+ cancelAnimationFrame(frame);+ frame = null;+ }++ gesture = null;+ scroller = null;+ pointerMoved = false;+ unlisten();+ endDrag();+ };++ const startGesture = (el: HTMLElement, event: PointerEvent): void => {+ const post = posts.get(el);++ if (+ gesture ||+ !post ||+ !isDraggable(post) ||+ !event.isPrimary ||+ (event.pointerType !== 'touch' && event.button !== 0)+ ) {+ return;+ }++ gesture = {+ el,+ post,+ pointerId: event.pointerId,+ pointerType: event.pointerType,+ startX: event.clientX,+ startY: event.clientY,+ x: event.clientX,+ y: event.clientY,+ active: false,+ timer:+ event.pointerType === 'touch'+ ? window.setTimeout(activate, TOUCH_ACTIVATION_DELAY)+ : null,+ };+ listen();+ };++ onBeforeUnmount(cancel);++ const registerPost = (el: HTMLElement, post: PostCard): (() => void) => {+ const onPointerDown = (event: PointerEvent): void =>+ startGesture(el, event);+ const onDragStart = (event: DragEvent): void => event.preventDefault();++ el.setAttribute(DRAGGABLE_ATTRIBUTE, 'true');+ el.setAttribute(+ 'aria-describedby',+ post.scheduled_at === null+ ? `${HINT_ID_PREFIX}${post.id}`+ : DRAG_HINT_ID,+ );+ el.style.setProperty('-webkit-touch-callout', 'none');+ el.style.setProperty('user-select', 'none');+ el.style.setProperty('-webkit-user-select', 'none');+ el.addEventListener('pointerdown', onPointerDown);+ el.addEventListener('dragstart', onDragStart);+ el.addEventListener('touchmove', preventWhileDragging, {+ passive: false,+ });++ return () => {+ if (gesture?.el === el) {+ cancel();+ }++ el.removeAttribute(DRAGGABLE_ATTRIBUTE);+ el.removeAttribute('aria-describedby');+ el.style.removeProperty('-webkit-touch-callout');+ el.style.removeProperty('user-select');+ el.style.removeProperty('-webkit-user-select');+ el.removeEventListener('pointerdown', onPointerDown);+ el.removeEventListener('dragstart', onDragStart);+ el.removeEventListener('touchmove', preventWhileDragging);+ };+ };++ const syncPost = (el: HTMLElement, post: PostCard): void => {+ posts.set(el, post);++ const registered = postCleanups.get(el);++ if (isDraggable(post) && !registered) {+ postCleanups.set(el, registerPost(el, post));+ } else if (!isDraggable(post) && registered) {+ registered();+ postCleanups.delete(el);+ }+ };++ const forgetTarget = (el: HTMLElement): void => {+ targets.delete(el);+ el.removeAttribute(DROP_ATTRIBUTE);+ };++ const syncTarget = (+ el: HTMLElement,+ target: CalendarDropTarget | null,+ ): void => {+ if (!target) {+ forgetTarget(el);++ return;+ }++ const key = calendarTargetKey(target);++ targets.set(el, target);++ if (el.getAttribute(DROP_ATTRIBUTE) !== key) {+ el.setAttribute(DROP_ATTRIBUTE, key);+ }+ };++ const vCalendarPost: Directive<HTMLElement, PostCard> = {+ mounted: (el, { value }) => syncPost(el, value),+ updated: (el, { value }) => syncPost(el, value),+ beforeUnmount: (el) => {+ postCleanups.get(el)?.();+ postCleanups.delete(el);+ posts.delete(el);+ },+ };++ const vCalendarTarget: Directive<HTMLElement, CalendarDropTarget | null> = {+ mounted: (el, { value }) => syncTarget(el, value),+ updated: (el, { value }) => syncTarget(el, value),+ beforeUnmount: forgetTarget,+ };++ return {+ overTarget,+ draggingPostId,+ movingPostIds,+ vCalendarPost,+ vCalendarTarget,+ };+};diff --git a/resources/js/composables/useDisplayTimezone.ts b/resources/js/composables/useDisplayTimezone.tsindex 5dbfd354a..8da768b34 100644--- a/resources/js/composables/useDisplayTimezone.ts+++ b/resources/js/composables/useDisplayTimezone.ts@@ -27,7 +27,12 @@ export const useDisplayTimezone = (defaultTz: string,available: string[],currentTab?: () => string,- reloadProps: string[] = ['posts', 'queue', 'counts', 'displayTimezone'],+ reloadProps: () => string[] = () => [+ 'posts',+ 'queue',+ 'counts',+ 'displayTimezone',+ ],): {timezone: Ref<string>;setTimezone: (tz: string) => void;@@ -60,7 +65,7 @@ export const useDisplayTimezone = (preserveState: true,preserveScroll: true,replace: true,- only: reloadProps,+ only: reloadProps(),reset: ['posts'],},);diff --git a/resources/js/date.ts b/resources/js/date.tsindex f0b95cc65..fc070b82f 100644--- a/resources/js/date.ts+++ b/resources/js/date.ts@@ -27,6 +27,18 @@ const getUserTimezone = (): string => userTimezone.value;const userNow = () =>localized(dayjs().tz(getUserTimezone()).format('YYYY-MM-DDTHH:mm:ss'));+/**+ * `{ year: 'numeric' }` when the instant falls in another year than now, in+ * that zone, so an `Intl` date shows the year only when it is not obvious.+ */+const yearUnlessCurrent = (+ instant: dayjs.Dayjs,+ timezone: string,+): Intl.DateTimeFormatOptions =>+ instant.tz(timezone).year() === dayjs().tz(timezone).year()+ ? {}+ : { year: 'numeric' };+/** Resolve scheduled local datetime for platform previews, else now. */const resolvePreviewPostedAt = (postedAt?: string | null) => {if (postedAt) {@@ -142,6 +154,23 @@ export default {return `${day}, ${instant.format(timeToken())}`;},+ /**+ * Weekday + month + day of a UTC instant in an explicit time zone, in the+ * active locale's order ("Thursday, October 29"), with the year only when+ * it is not the current one.+ */+ formatWeekdayMonthDay(date: string, timezone: string): string {+ const instant = dayjs.utc(date);++ return new Intl.DateTimeFormat(activeLocale.value, {+ weekday: 'long',+ month: 'long',+ day: 'numeric',+ ...yearUnlessCurrent(instant, timezone),+ timeZone: timezone,+ }).format(instant.toDate());+ },+/*** Format a local date-only value (YYYY-MM-DD or Date) with the active locale.*/@@ -217,6 +246,23 @@ export default {.format(timeToken());},+ /**+ * Short month and day in the active locale's order, then the time ("Oct 1,+ * 4:21 PM", "1 de out., 16:21") of a UTC instant in an explicit time zone,+ * with the year only when it is not the current one.+ */+ formatMonthDayTimeInTimezone(date: string, timezone: string): string {+ const instant = dayjs.utc(date);+ const day = new Intl.DateTimeFormat(activeLocale.value, {+ month: 'short',+ day: 'numeric',+ ...yearUnlessCurrent(instant, timezone),+ timeZone: timezone,+ }).format(instant.toDate());++ return `${day}, ${this.formatTimeInTimezone(date, timezone)}`;+ },+/*** Date and time (e.g. "October 1, 2026 4:21 PM") of a UTC instant in an* explicit time zone.diff --git a/resources/js/language.ts b/resources/js/language.tsindex 20d5258d0..dba86e6a6 100644--- a/resources/js/language.ts+++ b/resources/js/language.ts@@ -98,7 +98,9 @@ export const syncLocale = (props: LocaleProps): void => {export const i18nConfig = (lang: string) => ({lang,resolve: async (locale: string) => {- const langs = import.meta.glob('../../lang/*.json');+ const langs = import.meta.glob<{ default: Record<string, string> }>(+ '../../lang/*.json',+ );return await langs[`../../lang/php_${locale}.json`]();},diff --git a/resources/js/lib/calendarDrop.ts b/resources/js/lib/calendarDrop.tsnew file mode 100644index 000000000..1aa1e8dbc--- /dev/null+++ b/resources/js/lib/calendarDrop.ts@@ -0,0 +1,198 @@+import dayjs from '@/dayjs';+import { PostStatus, ScheduleMode } from '@/types/post';+import type { PostCard } from '@/types/publish';++export type CalendarDropTarget =+ | { kind: 'hour'; at: string }+ | { kind: 'day'; dayKey: string }+ | { kind: 'slot'; at: string; channelId: string; queueable: boolean }+ | { kind: 'undated' };++/**+ * Where a day drop or a day's "+ New" lands when there is no clock to keep.+ */+export const DRAFT_DAY_CLOCK = '09:00:00';++export const canDragCalendarPost = (+ post: PostCard,+ now: dayjs.Dayjs,+ canCreatePost: boolean,+): boolean =>+ canCreatePost &&+ post.platform !== null &&+ (post.status === PostStatus.Draft ||+ (post.status === PostStatus.Scheduled &&+ post.scheduled_at !== null &&+ dayjs.utc(post.scheduled_at).isAfter(now.add(1, 'minute'))));++const SOON_MINUTES = 5;++/**+ * Five minutes from now, to the minute: where a drop lands when the time it+ * names has already started (today on the month grid, the current hour).+ */+const soon = (now: dayjs.Dayjs): dayjs.Dayjs =>+ now.add(SOON_MINUTES, 'minute').startOf('minute');++const wallClockFormats = new Map<string, Intl.DateTimeFormat>();++export interface WallClock {+ date: string;+ hour: number;+ clock: string;+}++/**+ * The wall clock of an instant in a zone: its day (`YYYY-MM-DD`), hour and+ * clock (`HH:mm:ss`). Read with Intl rather than dayjs' local fields, which go+ * through the browser's zone and come out an hour off around the browser's own+ * daylight saving changes.+ */+export const wallClockIn = (+ instant: dayjs.Dayjs,+ timezone: string,+): WallClock => {+ let format = wallClockFormats.get(timezone);++ if (!format) {+ format = new Intl.DateTimeFormat('en-CA', {+ timeZone: timezone,+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hourCycle: 'h23',+ });+ wallClockFormats.set(timezone, format);+ }++ const parts = Object.fromEntries(+ format+ .formatToParts(instant.valueOf())+ .map((part) => [part.type, part.value]),+ );++ return {+ date: `${parts.year}-${parts.month}-${parts.day}`,+ hour: Number(parts.hour),+ clock: `${parts.hour}:${parts.minute}:${parts.second}`,+ };+};++const instantOnDay = (+ post: PostCard,+ dayKey: string,+ timezone: string,+ now: dayjs.Dayjs,+): dayjs.Dayjs | undefined => {+ const today = now.tz(timezone).format('YYYY-MM-DD');++ if (dayKey < today) {+ return undefined;+ }++ const clock = post.scheduled_at+ ? wallClockIn(dayjs.utc(post.scheduled_at), timezone).clock+ : DRAFT_DAY_CLOCK;+ const instant = dayjs.tz(`${dayKey}T${clock}`, timezone);+ const landed = wallClockIn(instant, timezone);++ if (landed.date !== dayKey || landed.clock !== clock) {+ return undefined;+ }++ if (instant.isAfter(now)) {+ return instant;+ }++ const later = soon(now);++ return later.tz(timezone).format('YYYY-MM-DD') === dayKey+ ? later+ : undefined;+};++/**+ * An hour cell takes the start of its hour, or, for the hour under way, five+ * minutes from now while that is still inside the hour.+ */+const instantInHour = (+ at: string,+ now: dayjs.Dayjs,+): dayjs.Dayjs | undefined => {+ const start = dayjs.utc(at);++ if (start.isAfter(now)) {+ return start;+ }++ const later = soon(now);++ return later.isBefore(start.add(1, 'hour')) ? later : undefined;+};++const isInHourOf = (+ post: PostCard,+ at: string,+ timezone: string,+): boolean => {+ if (!post.scheduled_at) {+ return false;+ }++ const hourOf = (instant: string): string =>+ dayjs.utc(instant).tz(timezone).format('YYYY-MM-DD HH');++ return hourOf(post.scheduled_at) === hourOf(at);+};++export const dropInstant = (+ post: PostCard,+ target: CalendarDropTarget,+ timezone: string,+ now: dayjs.Dayjs,+): string | null | undefined => {+ if (target.kind === 'undated') {+ return post.scheduled_at !== null ? null : undefined;+ }++ if (target.kind === 'hour' && isInHourOf(post, target.at, timezone)) {+ return undefined;+ }++ const instant =+ target.kind === 'day'+ ? instantOnDay(post, target.dayKey, timezone, now)+ : target.kind === 'hour'+ ? instantInHour(target.at, now)+ : dayjs.utc(target.at);++ if (+ !instant ||+ !instant.isAfter(now) ||+ (post.scheduled_at && dayjs.utc(post.scheduled_at).isSame(instant))+ ) {+ return undefined;+ }++ return instant.utc().format();+};++export const entersQueueSlot = (+ post: PostCard,+ target: CalendarDropTarget,+): boolean =>+ post.status === PostStatus.Scheduled &&+ target.kind === 'slot' &&+ target.queueable &&+ target.channelId === post.social_account_id;++export const needsCustomTimeConfirmation = (+ post: PostCard,+ target: CalendarDropTarget,+): boolean =>+ post.schedule_mode === ScheduleMode.Queue &&+ post.status === PostStatus.Scheduled &&+ !entersQueueSlot(post, target);diff --git a/resources/js/lib/calendarItems.ts b/resources/js/lib/calendarItems.tsindex ec3d9ad2d..e48d3ccee 100644--- a/resources/js/lib/calendarItems.ts+++ b/resources/js/lib/calendarItems.ts@@ -24,3 +24,6 @@ export const calendarItems = (slot,})),].sort((first, second) => dayjs(first.at).diff(dayjs(second.at)));++export const calendarDayKey = (day: dayjs.Dayjs): string =>+ day.format('YYYY-MM-DD');diff --git a/resources/js/lib/dragPlaceholder.ts b/resources/js/lib/dragPlaceholder.tsindex 84dbefab3..6dba2006c 100644--- a/resources/js/lib/dragPlaceholder.ts+++ b/resources/js/lib/dragPlaceholder.ts@@ -39,6 +39,35 @@ export const placeholderIndexAt = (}).length;};+/**+ * How far to scroll `container` this frame while the pointer rests within+ * 48px of one of its edges: negative toward the start, 0 away from the edges.+ */+export const edgeScrollDelta = (+ container: HTMLElement,+ pointer: { clientX: number; clientY: number },+ axis: DragAxis,+ maxStep: number = AUTO_SCROLL_MAX_STEP,+): number => {+ const rect = container.getBoundingClientRect();+ const vertical = axis === 'vertical';+ const coordinate = vertical ? pointer.clientY : pointer.clientX;+ const fromStart = coordinate - (vertical ? rect.top : rect.left);+ const fromEnd = (vertical ? rect.bottom : rect.right) - coordinate;+ const speed = (distance: number): number =>+ Math.ceil(maxStep * (1 - Math.max(distance, 0) / AUTO_SCROLL_EDGE));++ if (fromStart < AUTO_SCROLL_EDGE) {+ return -speed(fromStart);+ }++ if (fromEnd < AUTO_SCROLL_EDGE) {+ return speed(fromEnd);+ }++ return 0;+};+/*** Scrolls a container while the pointer rests near one of its edges during a* drag, calling `onScroll` after every step so the placeholder can follow.@@ -57,32 +86,10 @@ export const createDragAutoScroller = (let pointer: { clientX: number; clientY: number } | null = null;let frame = 0;- const step = (): number => {- if (!container || !pointer) {- return 0;- }-- const rect = container.getBoundingClientRect();- const coordinate = axis === 'vertical' ? pointer.clientY : pointer.clientX;- const fromStart =- coordinate - (axis === 'vertical' ? rect.top : rect.left);- const fromEnd = (axis === 'vertical' ? rect.bottom : rect.right) - coordinate;- const speed = (distance: number): number =>- Math.ceil(- AUTO_SCROLL_MAX_STEP *- (1 - Math.max(distance, 0) / AUTO_SCROLL_EDGE),- );-- if (fromStart < AUTO_SCROLL_EDGE) {- return -speed(fromStart);- }-- if (fromEnd < AUTO_SCROLL_EDGE) {- return speed(fromEnd);- }-- return 0;- };+ const step = (): number =>+ container && pointer+ ? edgeScrollDelta(container, pointer, axis)+ : 0;const tick = (): void => {frame = 0;@@ -134,12 +141,24 @@ export const createDragAutoScroller = (/*** Calls `onCancel` when Escape is pressed during a drag; returns the cleanup.+ * When `swallow` answers true, the key stops there, so an open dialog under+ * the drag does not close as well.*/-export const cancelDragOnEscape = (onCancel: () => void): (() => void) => {+export const cancelDragOnEscape = (+ onCancel: () => void,+ swallow: () => boolean = () => false,+): (() => void) => {const onKeydown = (event: KeyboardEvent): void => {- if (event.key === 'Escape') {- onCancel();+ if (event.key !== 'Escape') {+ return;}++ if (swallow()) {+ event.preventDefault();+ event.stopPropagation();+ }++ onCancel();};window.addEventListener('keydown', onKeydown, true);diff --git a/resources/js/pages/posts/Calendar.vue b/resources/js/pages/posts/Calendar.vueindex e291a4e90..ce266bee9 100644--- a/resources/js/pages/posts/Calendar.vue+++ b/resources/js/pages/posts/Calendar.vue@@ -1,12 +1,15 @@<script setup lang="ts">import { Head, router, usePage } from '@inertiajs/vue3';import {- IconChevronDown,IconLayoutSidebarRightCollapse,IconLayoutSidebarRightExpand,IconPlus,} from '@tabler/icons-vue';-import { useSwipe, type UseSwipeDirection } from '@vueuse/core';+import {+ useEventListener,+ useSwipe,+ type UseSwipeDirection,+} from '@vueuse/core';import {computed,onMounted,@@ -23,14 +26,21 @@ import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';import LabelFilter from '@/components/labels/LabelFilter.vue';import PostChannelFilter from '@/components/posts/PostChannelFilter.vue';import ScheduleViewSwitch from '@/components/posts/ScheduleViewSwitch.vue';+import CalendarCustomTimeDialog from '@/components/publish/CalendarCustomTimeDialog.vue';+import CalendarDragAnnouncer from '@/components/publish/CalendarDragAnnouncer.vue';+import CalendarMonthGrid from '@/components/publish/CalendarMonthGrid.vue';import CalendarPeriodPicker from '@/components/publish/CalendarPeriodPicker.vue';-import CalendarPostChip from '@/components/publish/CalendarPostChip.vue';-import CalendarSlotChip from '@/components/publish/CalendarSlotChip.vue';import CalendarTimeGrid from '@/components/publish/CalendarTimeGrid.vue';import CalendarUndatedPanel from '@/components/publish/CalendarUndatedPanel.vue';import PublishFilterMenu from '@/components/publish/PublishFilterMenu.vue';import PublishHeader from '@/components/publish/PublishHeader.vue';import { Button } from '@/components/ui/button';+import { useCalendarAnnouncer } from '@/composables/calendar/useCalendarAnnouncer';+import {+ calendarDragKey,+ DRAG_HINT_ID,+ useCalendarDrag,+} from '@/composables/calendar/useCalendarDrag';import { useAtLeastBreakpoint } from '@/composables/useBreakpoint';import { useCollapseWhenTruncated } from '@/composables/useCollapseWhenTruncated';import { useDisplayTimezone } from '@/composables/useDisplayTimezone';@@ -46,7 +56,7 @@ import date from '@/date';import dayjs from '@/dayjs';import { activeLocale } from '@/language';import AppLayout from '@/layouts/AppLayout.vue';-import { calendarItems, type CalendarItem } from '@/lib/calendarItems';+import { calendarDayKey } from '@/lib/calendarItems';import { calendar } from '@/routes/app';import {calendar as channelCalendar,@@ -94,12 +104,12 @@ interface Props {const props = defineProps<Props>();const page = usePage();-const { canCreatePost, canManageAccounts } = useWorkspaceAbilities();+const { canCreatePost, canManageAccounts, requiresApproval } =+ useWorkspaceAbilities();const { showSlots, setShowSlots } = useShowPostingSlots();const VIEWS: readonly CalendarView[] = ['days', 'week', 'month'];const DAYS_SPAN = 3;-const MONTH_CHIPS = 3;const RELOAD_PROPS = ['posts','currentDay',@@ -108,10 +118,19 @@ const RELOAD_PROPS = ['view','displayTimezone','filters',- 'slots',];+/**+ * The props a reload of this page asks for. The posting slots are an optional+ * prop, so they are only asked for (and built) while the viewer shows them.+ */+const reloadProps = (): string[] =>+ showSlots.value ? [...RELOAD_PROPS, 'slots'] : RELOAD_PROPS;+const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);+const customTimeDialog = ref<InstanceType<+ typeof CalendarCustomTimeDialog+> | null>(null);provide(deletePostCardKey, (post: PostCard) => {deleteModal.value?.open({ url: destroyPost.url(post.id) });@@ -137,7 +156,7 @@ const { timezone, setTimezone } = useDisplayTimezone(props.displayTimezone,props.timezones.map((option) => option.value),undefined,- RELOAD_PROPS,+ reloadProps,);provideViewTimezone(timezone);@@ -149,6 +168,39 @@ watch(},);+const confirmCustomTime = (from: string, to: string): Promise<boolean> =>+ customTimeDialog.value?.confirm(from, to, timezone.value) ??+ Promise.resolve(false);++const { announcement, describeInstant, hooks } =+ useCalendarAnnouncer(timezone);++const CALENDAR_VIEWS: CalendarView[] = ['days', 'week', 'month'];++const calendarDrag = useCalendarDrag({+ timezone,+ canCreatePost,+ requiresApproval,+ reloadProps: () => [...reloadProps(), 'undatedDrafts'],+ isCalendarPath: (pathname) =>+ CALENDAR_VIEWS.some(+ (view) =>+ new URL(calendarUrl(view), window.location.origin).pathname ===+ pathname,+ ),+ confirmCustomTime,+ describeInstant,+ ...hooks,+});++provide(calendarDragKey, calendarDrag);++const { movingPostIds } = calendarDrag;++const isRescheduling = computed(() => movingPostIds.value.length > 0);++const undatedDraftList = computed(() => props.undatedDrafts?.data ?? null);+const selectedLabelIds = ref<string[]>(props.filters.labels ?? []);const selectedUntagged = ref<boolean>(props.filters.untagged ?? false);const selectedChannelIds = ref<string[]>(props.filters.channels ?? []);@@ -201,17 +253,22 @@ const visit = (url: string): void => {router.get(url,{},- { preserveState: true, preserveScroll: true, only: RELOAD_PROPS },+ { preserveState: true, preserveScroll: true, only: reloadProps() },);};-const reload = (only: string[], reset: string[] = []): void => {+const reload = (+ only: string[],+ reset: string[] = [],+ preserveUrl = false,+): void => {router.get(calendarUrl(props.view, currentDateQuery()),{},{preserveState: true,preserveScroll: true,+ preserveUrl,replace: true,only,reset,@@ -221,7 +278,7 @@ const reload = (only: string[], reset: string[] = []): void => {watch([selectedLabelIds, selectedUntagged, selectedChannelIds, selectedStatus],- () => reload([...RELOAD_PROPS, 'undatedDrafts'], ['undatedDrafts']),+ () => reload([...reloadProps(), 'undatedDrafts'], ['undatedDrafts']),{ deep: true },);@@ -238,25 +295,36 @@ const closeUndated = (): void => {const toggleSlots = (value: boolean): void => {setShowSlots(value);- reload(['slots']);++ if (value) {+ reload(['slots']);++ return;+ }++ reload(['displayTimezone']);};+/**+ * A full visit back to the calendar (after saving or deleting a post) brings no+ * posting times unless its URL asks for them, so they are loaded again.+ */+watch(+ () => props.slots,+ (slots) => {+ if (showSlots.value && slots === undefined) {+ reload(['slots'], [], true);+ }+ },+);+onMounted(() => {clock = setInterval(() => {now.value = dayjs();}, 60_000);if (showSlots.value && props.slots === undefined) {- router.get(- calendarUrl(props.view, currentDateQuery()),- {},- {- preserveState: true,- preserveScroll: true,- preserveUrl: true,- only: ['slots'],- },- );+ reload(['slots'], [], true);}});@@ -286,14 +354,6 @@ const compactFilters = computed(() => !isDesktop.value || filtersCollapsed.value,);-const weekdayNames = computed(() => {- const start = localized().startOf('week');-- return Array.from({ length: 7 }, (_, index) =>- start.add(index, 'day').format(isDesktop.value ? 'dddd' : 'ddd'),- );-});-const periodStart = computed(() =>localized(props.view === 'days' ? props.currentDay : props.currentWeekStart),);@@ -382,15 +442,6 @@ const navigate = (direction: number): void => {const switchView = (view: CalendarView): void => visit(calendarUrl(view));-const dayKey = (day: dayjs.Dayjs): string => day.format('YYYY-MM-DD');--const isToday = (day: dayjs.Dayjs): boolean => dayKey(day) === todayKey.value;--const isPast = (day: dayjs.Dayjs): boolean => dayKey(day) < todayKey.value;--const isCurrentMonth = (day: dayjs.Dayjs): boolean =>- day.month() === monthDate.value.month();-const visibleSlots = computed<Record<string, CalendarSlot[]>>(() =>showSlots.value ? (props.slots ?? {}) : {},);@@ -403,12 +454,6 @@ const slotChannels = computed<Record<string, PublishSocialAccount>>(() =>),);-const itemsFor = (day: dayjs.Dayjs): CalendarItem[] =>- calendarItems(- props.posts[dayKey(day)] ?? [],- visibleSlots.value[dayKey(day)] ?? [],- );-const composerAccounts = (): string[] =>props.channel ? [props.channel.id] : [];@@ -421,26 +466,8 @@ const composeAt = (utcIso: string): void =>socialAccountIds: composerAccounts(),});-const composeOn = (day: dayjs.Dayjs): void =>- composeAt(dayjs.tz(`${dayKey(day)}T09:00`, timezone.value).utc().format());-const expandedDays = ref<string[]>([]);-const toggleDay = (key: string): void => {- expandedDays.value = expandedDays.value.includes(key)- ? expandedDays.value.filter((day) => day !== key)- : [...expandedDays.value, key];-};--const isDayExpanded = (day: dayjs.Dayjs): boolean =>- expandedDays.value.includes(dayKey(day));--const hiddenCount = (day: dayjs.Dayjs): number =>- itemsFor(day).length - MONTH_CHIPS;--const visibleMonthItems = (day: dayjs.Dayjs): CalendarItem[] =>- isDayExpanded(day) ? itemsFor(day) : itemsFor(day).slice(0, MONTH_CHIPS);-const mobileTitle = computed(() => {if (props.view === 'month') {return monthDate.value.format('MMMM YYYY');@@ -462,7 +489,7 @@ const mobileTitle = computed(() => {const dayKeys = computed(() =>(props.view === 'month' ? calendarWeeks.value.flat() : periodDays.value).map(- dayKey,+ calendarDayKey,),);@@ -519,9 +546,33 @@ const swipeStep = (direction: UseSwipeDirection): number => {const periodSwipeTarget = ref<HTMLElement | null>(null);+/**+ * A touch that dragged a post is not a period swipe, even when it moved sideways.+ */+let touchDraggedPost = false;++useEventListener(+ periodSwipeTarget,+ 'touchstart',+ () => {+ touchDraggedPost = false;+ },+ { passive: true },+);++watch(calendarDrag.draggingPostId, (postId) => {+ if (postId !== null) {+ touchDraggedPost = true;+ }+});+useSwipe(periodSwipeTarget, {threshold: 48,onSwipeEnd: (_event, direction) => {+ if (touchDraggedPost) {+ return;+ }+const step = swipeStep(direction);if (step !== 0) {@@ -641,7 +692,9 @@ const goToDay = (key: string): void => {<ScheduleViewSwitchactive-view="calendar":list-href="listHref"- :calendar-href="calendarUrl('month')"+ :calendar-href="+ calendarUrl(isDesktop ? 'month' : 'days')+ ":grid-href="channel?.has_grid? grid.url(channel.id)@@ -679,6 +732,7 @@ const goToDay = (key: string): void => {ref="periodSwipeTarget"class="mb-4 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-xl border border-border-strong md:mb-6":class="{ 'max-md:hidden': undatedOpen }"+ :aria-busy="isRescheduling || undefined"data-testid="calendar-grid"><CalendarTimeGrid@@ -693,151 +747,20 @@ const goToDay = (key: string): void => {@compose="composeAt"/>- <div+ <CalendarMonthGridv-else- class="flex flex-1 flex-col overflow-y-auto overscroll-contain"- data-testid="calendar-month-grid"- >- <div- class="sticky top-0 z-10 grid grid-cols-7 border-b border-border-strong bg-card"- >- <div- v-for="(name, index) in weekdayNames"- :key="name"- class="border-border-strong p-1.5 text-center text-sm font-medium text-muted-foreground capitalize md:p-2.5"- :class="{ 'border-l': index > 0 }"- >- {{ name }}- </div>- </div>-- <div class="flex flex-1 flex-col">- <div- v-for="(week, weekIndex) in calendarWeeks"- :key="weekIndex"- class="grid min-h-40 flex-1 auto-rows-[minmax(0,1fr)] grid-cols-7 border-border-strong md:min-h-[208px]"- :class="{ 'border-t': weekIndex > 0 }"- >- <div- v-for="(day, index) in week"- :key="dayKey(day)"- class="group flex min-h-0 min-w-0 flex-col gap-1 border-border-strong p-1 md:p-2"- :class="{- 'border-l': index > 0,- 'bg-accent': isPast(day),- }"- :data-testid="`calendar-day-${dayKey(day)}`"- >- <div class="flex items-center justify-between">- <span- class="inline-flex size-6 items-center justify-center rounded-full text-sm font-medium"- :class="{- 'bg-primary text-primary-foreground':- isToday(day),- 'text-subtle-foreground':- !isToday(day) &&- !isCurrentMonth(day),- 'text-muted-foreground':- !isToday(day) &&- isCurrentMonth(day),- }"- >- {{ day.format('D') }}- </span>- <button- v-if="canCreatePost && !isPast(day)"- type="button"- :aria-label="$t('calendar.new_post')"- class="flex size-6 items-center justify-center rounded-md border border-border-strong bg-card text-muted-foreground opacity-0 transition-opacity duration-100 ease-in-out group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 max-md:hidden [@media(hover:none)]:opacity-100"- :data-testid="`calendar-add-${dayKey(day)}`"- @click="composeOn(day)"- >- <IconPlus class="size-3.5" />- </button>- </div>-- <div class="relative min-h-0 flex-1">- <div- class="flex flex-col gap-1"- :class="{- 'absolute inset-0 overflow-y-auto overscroll-contain':- isDayExpanded(day),- }"- :data-testid="`calendar-items-${dayKey(day)}`"- >- <template- v-for="item in visibleMonthItems(day)"- :key="item.key"- >- <CalendarPostChip- v-if="item.post"- :post="item.post"- :timezone="timezone"- :compact="!isDesktop"- />- <CalendarSlotChip- v-else-if="item.slot"- :posting-slot="item.slot"- :channel="- slotChannels[- item.slot.channel_id- ] ?? null- "- :timezone="timezone"- :can-create-post="canCreatePost"- :compact="!isDesktop"- />- </template>- </div>- </div>- <button- v-if="hiddenCount(day) > 0"- type="button"- class="inline-flex shrink-0 items-center gap-1 rounded-md text-xs font-medium text-foreground transition-control hover:bg-accent"- :class="- isDesktop- ? 'h-6 self-end px-2'- : 'h-7 min-w-7 justify-center self-start px-1'- "- :aria-expanded="isDayExpanded(day)"- :aria-label="- isDesktop- ? undefined- : isDayExpanded(day)- ? $t('calendar.less')- : $t('calendar.more', {- count: String(- hiddenCount(day),- ),- })- "- :data-testid="`calendar-more-${dayKey(day)}`"- @click="toggleDay(dayKey(day))"- >- <IconChevronDown- v-if="isDesktop || isDayExpanded(day)"- class="size-3.5 transition-transform"- :class="{- 'rotate-180': isDayExpanded(day),- }"- />- <template v-if="isDesktop">{{- isDayExpanded(day)- ? $t('calendar.less')- : $t('calendar.more', {- count: String(- hiddenCount(day),- ),- })- }}</template>- <template v-else-if="!isDayExpanded(day)"- >+{{ hiddenCount(day) }}</template- >- </button>- </div>- </div>- </div>- </div>+ v-model:expanded-days="expandedDays"+ :weeks="calendarWeeks"+ :month="monthDate"+ :posts="posts"+ :slots="visibleSlots"+ :channels="slotChannels"+ :timezone="timezone"+ :now="now"+ :can-create-post="canCreatePost"+ :is-desktop="isDesktop"+ @compose="composeAt"+ /></div><Transition@@ -852,7 +775,7 @@ const goToDay = (key: string): void => {data-testid="calendar-undated-slide"><CalendarUndatedPanel- :drafts="undatedDrafts?.data ?? null"+ :drafts="undatedDraftList"@close="closeUndated"/></div>@@ -861,6 +784,13 @@ const goToDay = (key: string): void => {</div></AppLayout>+ <CalendarCustomTimeDialog ref="customTimeDialog" />++ <CalendarDragAnnouncer :text="announcement" />+ <span :id="DRAG_HINT_ID" hidden data-testid="calendar-drag-hint">{{+ $t('calendar.reschedule.drag_hint')+ }}</span>+<ConfirmDeleteModalref="deleteModal":title="$t('posts.edit.delete_modal.title')"diff --git a/resources/js/types/publish.ts b/resources/js/types/publish.tsindex 97d5a9133..e5cab2236 100644--- a/resources/js/types/publish.ts+++ b/resources/js/types/publish.ts@@ -163,6 +163,7 @@ export const CALENDAR_STATUSES: readonly CalendarStatus[] = [export interface CalendarSlot {at: string;channel_id: string;+ queueable: boolean;}export interface UndatedDraft extends Omit<PostCard, 'scheduled_at'> {diff --git a/tests/Browser/CalendarDragAndDropTest.php b/tests/Browser/CalendarDragAndDropTest.phpnew file mode 100644index 000000000..b01c59cb5--- /dev/null+++ b/tests/Browser/CalendarDragAndDropTest.php@@ -0,0 +1,3166 @@+<?php++declare(strict_types=1);++use App\Enums\Post\RecurrenceFrequency;+use App\Enums\Post\ScheduleMode;+use App\Enums\Post\Status as PostStatus;+use App\Enums\User\Locale;+use App\Enums\User\TimeFormat;+use App\Enums\User\WeekStart;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Support\PostingSchedule;+use Carbon\CarbonImmutable;+use Pest\Browser\Playwright\Client;++/**+ * @return array{0: User, 1: SocialAccount}+ */+function calendarDragSetup(string $timezone = 'UTC', ?string $slotTime = null): array+{+ $user = User::factory()->create(['timezone' => $timezone]);+ $workspace = Workspace::factory()->create([+ 'user_id' => $user->id,+ 'account_id' => $user->account_id,+ ]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ $schedule = PostingSchedule::empty();++ if (filled($slotTime)) {+ foreach (range(0, 6) as $weekday) {+ $schedule = $schedule->withTime($weekday, $slotTime);+ }+ }++ return [+ $user,+ SocialAccount::factory()->linkedin()->create([+ 'workspace_id' => $workspace->id,+ 'timezone' => 'UTC',+ 'posting_schedule' => $schedule,+ ]),+ ];+}++function calendarDragPost(SocialAccount $channel, ?CarbonImmutable $at, PostStatus $status = PostStatus::Scheduled, ?ScheduleMode $mode = ScheduleMode::Custom, array $attributes = []): Post+{+ return Post::factory()->forAccount($channel)->create(array_merge([+ 'user_id' => $channel->workspace->user_id,+ 'content' => 'A post to move',+ 'status' => $status,+ 'schedule_mode' => $status === PostStatus::Draft ? null : $mode,+ 'scheduled_at' => $at,+ ], $attributes));+}++function calendarDragDay(): CarbonImmutable+{+ return now('UTC')->startOfWeek()->addWeek()->addDays(2)->startOfDay();+}++function calendarDragWeekUrl(CarbonImmutable $day, array $query = []): string+{+ return route('app.calendar', ['view' => 'week', 'week' => $day->format('Y-m-d'), ...$query]);+}++function calendarDragSlotKey(SocialAccount $channel, CarbonImmutable $at): string+{+ return "{$channel->id}-{$at->getTimestamp()}";+}++function calendarDragCellOf(mixed $page, Post $post): ?string+{+ return $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]')?.closest('[data-testid^=\"calendar-slot-\"], [data-testid^=\"calendar-day-\"]')?.dataset.testid ?? null");+}++/**+ * Drags a card onto a target with both ends on screen: down on the card once+ * it takes the pointer (a closing dialog may still hold it), one move onto+ * the target and up there.+ */+function calendarDragOnto(mixed $page, string $from, string $to): void+{+ calendarGesture($page, <<<JS+ query('{$from}').scrollIntoView({ block: 'center' });+ query('{$to}').scrollIntoView({ block: 'nearest' });+ JS);+ waitForState($page, $from, '((box) => element.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2)))(element.getBoundingClientRect())');+ calendarGesture($page, <<<JS+ await down(center('{$from}'));+ await move(center('{$to}'));+ await up(center('{$to}'));+ JS);+}++function calendarDragAssertLive(mixed $page, string $selector): void+{+ waitForState($page, $selector, "element.dataset.calendarDraggable === 'true'");+}++/**+ * Runs a gesture in the page. Pest drives the mouse only through whole+ * drags, so partial moves, holds and touch pointers are dispatched as+ * PointerEvents: `down`, `move`, `up` and `hover` (no button) take a point, `center` and `at`+ * give one, `pause` waits in the page and `state` reads the drag visuals.+ */+function calendarGesture(mixed $page, string $steps, string $pointerType = 'mouse'): mixed+{+ return $page->script(<<<JS+ (async () => {+ const pointerType = '{$pointerType}';+ const pointerId = pointerType === 'touch' ? 2 : 1;+ const query = (selector) => document.querySelector(selector.replace(/@([\w-]+)/g, '[data-testid="$1"]'));+ const center = (selector) => {+ const box = query(selector).getBoundingClientRect();++ return { x: box.left + box.width / 2, y: box.top + box.height / 2 };+ };+ const at = (point, dx = 0, dy = 0) => ({ x: point.x + dx, y: point.y + dy });+ const fire = (type, point, buttons = type === 'pointerup' ? 0 : 1) => (document.elementFromPoint(point.x, point.y) ?? document.body).dispatchEvent(new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ composed: true,+ pointerId,+ pointerType,+ isPrimary: true,+ button: type === 'pointermove' ? -1 : 0,+ buttons,+ clientX: point.x,+ clientY: point.y,+ }));+ const frame = () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ const down = async (point) => { fire('pointerdown', point); await frame(); };+ const move = async (point) => { fire('pointermove', point); await frame(); };+ const up = async (point) => { fire('pointerup', point); await frame(); };+ const hover = async (point) => { fire('pointermove', point, 0); await frame(); };+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+ const touchMovePrevented = (selector) => {+ const element = query(selector);+ const box = element.getBoundingClientRect();+ const touch = new Touch({ identifier: pointerId, target: element, clientX: box.left + 2, clientY: box.top + 2 });+ const event = new TouchEvent('touchmove', { bubbles: true, cancelable: true, touches: [touch], targetTouches: [touch], changedTouches: [touch] });+ element.dispatchEvent(event);++ return event.defaultPrevented;+ };+ const state = () => {+ const preview = query('@calendar-drag-preview');++ return {+ dragging: preview !== null,+ opacity: preview ? getComputedStyle(preview).opacity : null,+ rotated: preview ? getComputedStyle(preview).rotate !== 'none' || getComputedStyle(preview).transform !== 'none' : false,+ };+ };+ {$steps}+ })()+ JS);+}++test('dragging a custom post onto an hour moves it to that hour', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, "@calendar-slot-{$key}-12 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->status)->toBe(PostStatus::Scheduled);+ $page->assertMissing('@calendar-custom-time-dialog')+ ->assertNoJavaScriptErrors();+});++test('dragging onto a slot of its channel takes the slot\'s exact time in the queue', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '15:25');+ $day = calendarDragDay();+ $slotAt = $day->setTime(15, 25);+ $post = calendarDragPost($channel, $day->setTime(13, 30));+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-slot-{$day->format('Y-m-d')}-15 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('a member who needs approval cannot drop a post on a posting time, as on the queue page', function () {+ [$owner, $channel] = calendarDragSetup(slotTime: '15:25');+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $at = $day->setTime(13, 30);+ $post = calendarDragPost($channel, $at, attributes: ['user_id' => $member->id]);+ $slotKey = calendarDragSlotKey($channel, $day->setTime(15, 25));+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day, ['slots' => 1]));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitForGone($page, '@calendar-drag-preview');++ expect($page->script('window.__heldRequests.length'))->toBe(0)+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue()+ ->and($post->status)->toBe(PostStatus::Scheduled);+ $page->assertNoJavaScriptErrors();+});++test('a custom post dropped on a free slot of its channel goes back into the queue', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '15:25');+ $day = calendarDragDay();+ $slotAt = $day->setTime(15, 25);+ $post = calendarDragPost($channel, $day->setTime(13, 30));+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ waitForState($page, "@post-schedule-mode-{$post->id}", "element.dataset.mode === 'custom'");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitForState($page, "@calendar-slot-{$day->format('Y-m-d')}-15 @post-schedule-mode-{$post->id}", "element.dataset.mode === 'queue'");++ $page->assertMissing('@calendar-custom-time-dialog')+ ->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved', ['time' => calendarDragWhen($slotAt)]))+ ->assertDontSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unqueued_suffix'));+ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('dragging a queued post off its slot asks first; cancel leaves it', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $queuedAt = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');+ waitForState($page, '@calendar-custom-time-cancel', 'document.activeElement === element');++ expect($page->script('document.activeElement?.dataset.testid'))->toBe('calendar-custom-time-cancel');+ $page->assertSeeIn('@calendar-custom-time-dialog', __('calendar.reschedule.custom_time.title'))+ ->assertSeeIn('@calendar-custom-time-description', "{$queuedAt->format('M j, g:i A')} (UTC)")+ ->assertSeeIn('@calendar-custom-time-description', "{$day->setTime(11, 0)->format('M j, g:i A')} (UTC)")+ ->assertDontSeeIn('@calendar-custom-time-description', 'posting times');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $styles = $page->script(<<<'JS'+ (() => {+ const dialog = document.querySelector('[data-testid="calendar-custom-time-dialog"]');+ const title = dialog.querySelector('[data-slot="alert-dialog-title"]');+ const strong = dialog.querySelector('[data-testid="calendar-custom-time-from"]');+ const zone = dialog.querySelector('[data-testid="calendar-custom-time-from-zone"]');+ const cancel = dialog.querySelector('[data-testid="calendar-custom-time-cancel"]');+ const confirm = dialog.querySelector('[data-testid="calendar-custom-time-confirm"]');+ const box = getComputedStyle(dialog);++ return {+ width: dialog.offsetWidth,+ padding: box.padding,+ gap: box.rowGap,+ radius: box.borderTopLeftRadius,+ title: [getComputedStyle(title).fontSize, getComputedStyle(title).lineHeight, getComputedStyle(title).fontWeight],+ strong: [getComputedStyle(strong).fontWeight, getComputedStyle(zone).fontStyle],+ buttons: [cancel.offsetHeight, confirm.offsetHeight],+ cancelFirst: cancel.offsetLeft + cancel.offsetWidth <= confirm.offsetLeft,+ };+ })()+ JS);++ expect($styles)->toBe([+ 'width' => 480,+ 'padding' => '24px 0px 16px',+ 'gap' => '16px',+ 'radius' => '16px',+ 'title' => ['16px', '20px', '550'],+ 'strong' => ['650', 'italic'],+ 'buttons' => [32, 32],+ 'cancelFirst' => true,+ ]);++ $page->click('@calendar-custom-time-cancel');+ waitForGone($page, '@calendar-custom-time-dialog');++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-09");+ $post->refresh();+ expect($post->scheduled_at->equalTo($queuedAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('confirming makes the queued post custom', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-confirm');+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, "@calendar-slot-{$key}-11 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($day->setTime(11, 0)))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom);+ $page->assertMissing('@calendar-custom-time-dialog')+ ->assertNoJavaScriptErrors();+});++test('ticking the box and confirming stores the choice and the next drop skips the dialog', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $nextKey = $day->addDay()->format('Y-m-d');+ $first = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $second = calendarDragPost($channel, $day->addDay()->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$first->id}");+ calendarDragOnto($page, "@calendar-post-{$first->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-skip');+ $page->click('@calendar-custom-time-skip');+ $page->click('@calendar-custom-time-confirm');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($page->script("localStorage.getItem('calendar.skipCustomTimeConfirm.{$user->id}')"))->toBe('true');+ waitFor($page, '@calendar-posting-slot-'.calendarDragSlotKey($channel, $day->setTime(9, 25)));++ waitFor($page, "@calendar-post-{$second->id}");+ calendarDragOnto($page, "@calendar-post-{$second->id}", "@calendar-slot-{$nextKey}-11");+ waitFor($page, "@calendar-slot-{$nextKey}-11 @calendar-post-{$second->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitFor($page, '@calendar-posting-slot-'.calendarDragSlotKey($channel, $day->addDay()->setTime(9, 25)));++ $page->assertMissing('@calendar-custom-time-dialog');+ $second->refresh();+ expect($second->scheduled_at->equalTo($day->addDay()->setTime(11, 0)))->toBeTrue()+ ->and($second->schedule_mode)->toBe(ScheduleMode::Custom);+ $page->assertNoJavaScriptErrors();+});++test('another user\'s choice to skip the dialog on this browser does not skip it', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $other = User::factory()->create();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ $page->script("localStorage.setItem('calendar.skipCustomTimeConfirm.{$other->id}', 'true'); localStorage.setItem('calendar.skipCustomTimeConfirm', 'true')");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');++ expect($post->refresh()->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('ticking the box and cancelling stores nothing', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-skip');+ $page->click('@calendar-custom-time-skip');+ $page->click('@calendar-custom-time-cancel');+ waitForGone($page, '@calendar-custom-time-dialog');++ expect($page->script("localStorage.getItem('calendar.skipCustomTimeConfirm.{$user->id}')"))->toBeNull()+ ->and($post->refresh()->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('dropping a queued post on a free slot of its channel moves it there in the queue without asking', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $slotAt = $day->addDay()->setTime(9, 25);+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-slot-{$slotAt->format('Y-m-d')}-09 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ waitFor($page, '@calendar-reschedule-success-toast');++ $toast = $page->script('document.querySelector(\'[data-testid="calendar-reschedule-success-toast"]\')?.textContent ?? ""');++ expect($toast)->toContain('Rescheduled your post')+ ->not->toContain(__('calendar.reschedule.toast.unqueued_suffix'));+ $page->assertMissing('@calendar-custom-time-dialog');+ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('past hours and past days are not drop targets', function () {+ [$user, $channel] = calendarDragSetup();+ $now = now('UTC');+ $yesterday = $now->subDay()->startOfDay();+ $today = $now->format('Y-m-d');+ $at = $now->addDay()->startOfHour();+ $post = calendarDragPost($channel, $at);+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'days', 'day' => $yesterday->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ if ($now->hour > 0) {+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$today}-{$now->subHour()->format('H')}");+ waitForGone($page, '@calendar-grid[aria-busy]');+ }++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$yesterday->format('Y-m-d')}-{$now->format('H')}");+ waitForGone($page, '@calendar-grid[aria-busy]');+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$at->format('Y-m-d')}-{$at->format('H')}");++ $month = visit(route('app.calendar', ['view' => 'month', 'month' => $yesterday->format('Y-m-d'), 'undated' => 1]));+ waitFor($month, "@calendar-undated-{$draft->id}");+ calendarDragAssertLive($month, "@calendar-undated-{$draft->id}");+ calendarDragOnto($month, "@calendar-undated-{$draft->id}", "@calendar-day-{$yesterday->format('Y-m-d')}");+ waitForGone($month, '@calendar-grid[aria-busy]');+ $month->assertVisible("@calendar-undated-{$draft->id}");++ expect($post->refresh()->scheduled_at->equalTo($at))->toBeTrue()+ ->and($draft->refresh()->scheduled_at)->toBeNull();+ $page->assertMissing('@calendar-reschedule-error-toast');++ $validAt = $at->hour > 0 ? $at->subHour() : $at->addHour();+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$validAt->format('Y-m-d')}-{$validAt->format('H')}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($validAt))->toBeTrue();+ $page->assertNoJavaScriptErrors();+ $month->assertNoJavaScriptErrors();+});++test('month drop keeps the clock time', function () {+ [$user, $channel] = calendarDragSetup();+ $from = now('UTC')->startOfMonth()->addMonth()->addDays(3)->setTime(14, 35);+ $to = $from->addDays(2);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $from->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$to->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$to->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($to))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('month drop on today after that time lands five minutes from now', function () {+ [$user, $channel] = calendarDragSetup();+ $today = now('UTC')->startOfDay();+ $gridEnd = $today->endOfMonth()->endOfWeek($user->week_starts_on->lastDay())->startOfDay();+ $post = $today->equalTo($gridEnd)+ ? calendarDragPost($channel, $today->subDay(), PostStatus::Draft)+ : calendarDragPost($channel, $today->addDay());+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $today->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$today->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$today->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ waitFor($page, '@calendar-reschedule-success-toast');++ $scheduledAt = $post->refresh()->scheduled_at;+ expect($scheduledAt->between(now()->addMinutes(3), now()->addMinutes(6)))->toBeTrue()+ ->and($scheduledAt->second)->toBe(0);+ $page->assertSeeIn('@calendar-reschedule-success-toast', $scheduledAt->format('g:i A'))+ ->assertNoJavaScriptErrors();+});++test('drafts move and stay drafts; the No Date panel takes and gives them', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-slot-{$key}-11");+ waitFor($page, "@calendar-slot-{$key}-11 @calendar-post-{$draft->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitForGone($page, "@calendar-undated-{$draft->id}");++ $draft->refresh();+ expect($draft->scheduled_at->equalTo($day->setTime(11, 0)))->toBeTrue()+ ->and($draft->status)->toBe(PostStatus::Draft);++ calendarDragOnto($page, "@calendar-post-{$draft->id}", "@calendar-slot-{$key}-13");+ waitFor($page, "@calendar-slot-{$key}-13 @calendar-post-{$draft->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $draft->refresh();+ expect($draft->scheduled_at->equalTo($day->setTime(13, 0)))->toBeTrue()+ ->and($draft->status)->toBe(PostStatus::Draft);++ calendarDragOnto($page, "@calendar-post-{$draft->id}", '@calendar-undated-panel');+ waitFor($page, "@calendar-undated-{$draft->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitForGone($page, "@calendar-post-{$draft->id}");++ $draft->refresh();+ expect($draft->scheduled_at)->toBeNull()+ ->and($draft->status)->toBe(PostStatus::Draft);+ $page->assertNoJavaScriptErrors();+});++test('a draft from the No Date panel dropped on a month day lands at nine', function () {+ [$user, $channel] = calendarDragSetup();+ $day = now('UTC')->startOfMonth()->addMonth()->addDays(4)->startOfDay();+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d'), 'undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-day-{$day->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$day->format('Y-m-d')} @calendar-post-{$draft->id}");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $draft->refresh();+ expect($draft->scheduled_at->equalTo($day->setTime(9, 0)))->toBeTrue()+ ->and($draft->status)->toBe(PostStatus::Draft);+ $page->assertSeeIn('@calendar-reschedule-success-toast', '9:00 AM')+ ->assertNoJavaScriptErrors();+});++test('a queued post dropped on No Date becomes a draft without a date and frees its slot', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $at = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $at, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, '@calendar-undated-empty');+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ calendarDragOnto($page, "@calendar-post-{$post->id}", '@calendar-undated-panel');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitFor($page, "@calendar-undated-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unscheduled'))+ ->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unqueued_suffix'))+ ->assertMissing("@calendar-post-{$post->id}")+ ->assertPresent('@calendar-posting-slot-'.calendarDragSlotKey($channel, $at));+ $post->refresh();+ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull();+ $page->assertNoJavaScriptErrors();+});++test('published posts are not draggable', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $published = calendarDragPost($channel, $day->setTime(8, 0), PostStatus::Published, attributes: ['published_at' => $day->setTime(8, 0)]);+ $failed = calendarDragPost($channel, $day->setTime(9, 0), PostStatus::Failed);+ $pending = calendarDragPost($channel, $day->setTime(10, 0), PostStatus::PendingApproval);+ $movable = calendarDragPost($channel, $day->setTime(12, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$movable->id}");+ waitForState($page, "@calendar-post-{$movable->id}", "element.dataset.calendarDraggable === 'true'");++ $draggable = fn (Post $post): ?string => $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]').dataset.calendarDraggable ?? null");++ expect($draggable($movable))->toBe('true')+ ->and($draggable($published))->toBeNull()+ ->and($draggable($failed))->toBeNull()+ ->and($draggable($pending))->toBeNull();+ $page->assertNoJavaScriptErrors();+});++test('a recurring post can be dragged and stays recurring', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(9, 0), attributes: [+ 'recurrence_interval' => 1,+ 'recurrence_frequency' => RecurrenceFrequency::Week,+ 'recurrence_remaining' => 3,+ ]);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, "@calendar-post-recurring-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$day->format('Y-m-d')}-10");+ waitFor($page, "@calendar-slot-{$day->format('Y-m-d')}-10 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();++ expect($post->scheduled_at->equalTo($day->setTime(10, 0)))->toBeTrue()+ ->and($post->recurrence_frequency)->toBe(RecurrenceFrequency::Week)+ ->and($post->recurrence_interval)->toBe(1)+ ->and($post->recurrence_remaining)->toBe(3);+ waitFor($page, "@calendar-post-recurring-{$post->id}");+ $page->assertNoJavaScriptErrors();+});++test('the drop uses the display zone', function () {+ [$user, $channel] = calendarDragSetup();+ $tokyoDay = calendarDragDay()->shiftTimezone('Asia/Tokyo');+ $key = $tokyoDay->format('Y-m-d');+ $post = calendarDragPost($channel, $tokyoDay->setTime(8, 30)->utc());+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($tokyoDay, ['tz' => 'Asia/Tokyo']));+ waitFor($page, "@calendar-slot-{$key}-08 @calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-10");+ waitFor($page, "@calendar-slot-{$key}-10 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($tokyoDay->setTime(10, 0)))->toBeTrue()+ ->and($post->scheduled_at->utc()->format('H:i'))->toBe('01:00');+ $page->assertNoJavaScriptErrors();+});++test('a post published meanwhile goes back and the reason is shown', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $post->forceFill(['status' => PostStatus::Published, 'published_at' => $at])->save();+ calendarDragWatchAnnouncer($page);++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@flash-banner-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@flash-banner-toast', __('posts.flash.cannot_edit_finalized'));+ expect($page->script('document.querySelectorAll(\'[data-testid="calendar-reschedule-success-toast"]\').length'))->toBe(0)+ ->and(array_slice(calendarDragAnnouncements($page), -1))->toBe([__('calendar.reschedule.announce.returned')])+ ->and(collect(calendarDragAnnouncements($page))->filter(fn (string $text): bool => $text === __('calendar.reschedule.announce.returned'))->count())->toBe(1);+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a time that passed meanwhile is refused with the reason', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $this->travelTo($day->addDays(2));++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-reschedule-error-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-error-toast', __('calendar.reschedule.errors.past'));+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('two drops in a row both land', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $first = calendarDragPost($channel, $day->setTime(10, 0));+ $second = calendarDragPost($channel, $day->setTime(11, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$first->id}");+ calendarDragAssertLive($page, "@calendar-post-{$second->id}");+ calendarDragWatchAnnouncer($page);++ calendarGesture($page, <<<JS+ query('@calendar-slot-{$key}-11').scrollIntoView({ block: 'center' });+ const first = center('@calendar-post-{$first->id}');+ const second = center('@calendar-post-{$second->id}');+ const target = center('@calendar-slot-{$key}-12');+ fire('pointerdown', first);+ fire('pointermove', target);+ fire('pointerup', target);+ fire('pointerdown', second);+ fire('pointermove', target);+ fire('pointerup', target);+ JS);+ waitFor($page, "@calendar-slot-{$key}-12 @calendar-post-{$first->id}");+ waitFor($page, "@calendar-slot-{$key}-12 @calendar-post-{$second->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($first->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue()+ ->and($second->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue()+ ->and(calendarDragCellOf($page, $first))->toBe("calendar-slot-{$key}-12")+ ->and(calendarDragCellOf($page, $second))->toBe("calendar-slot-{$key}-12")+ ->and(calendarDragAnnouncements($page))->not->toContain(__('calendar.reschedule.announce.returned'));+ $page->assertMissing('@calendar-reschedule-error-toast')+ ->assertNoJavaScriptErrors();+});++test('a move by a member who needs approval says it was sent for approval', function () {+ [$owner, $channel] = calendarDragSetup();+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 0), attributes: ['user_id' => $member->id]);+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-reschedule-approval-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $announcements = calendarDragAnnouncements($page);+ expect(array_slice($announcements, -1))->toBe([__('calendar.reschedule.announce.moved', ['from' => calendarDragWhen($day->setTime(10, 0)), 'to' => calendarDragWhen($day->setTime(11, 0))])])+ ->and($announcements)->not->toContain(__('calendar.reschedule.announce.returned'));++ $page->assertSeeIn('@calendar-reschedule-approval-toast', __('posts.approvals.requested'));+ expect($page->script('document.querySelectorAll(\'[data-testid="calendar-reschedule-success-toast"]\').length'))->toBe(0);+ expect($post->refresh()->status)->toBe(PostStatus::PendingApproval);+ $page->assertNoJavaScriptErrors();+});++test('a move answered while another is in flight is settled from the server, not from the guess on screen', function () {+ [$owner, $channel] = calendarDragSetup();+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $first = calendarDragPost($channel, $day->setTime(10, 0), attributes: ['user_id' => $member->id]);+ $second = calendarDragPost($channel, $day->setTime(11, 0), attributes: ['user_id' => $member->id]);+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$first->id}");+ calendarDragAssertLive($page, "@calendar-post-{$second->id}");+ calendarDragHoldResponses($page);++ calendarDragOnto($page, "@calendar-post-{$first->id}", "@calendar-slot-{$key}-12");+ calendarDragAssertLive($page, "@calendar-post-{$second->id}");+ calendarDragOnto($page, "@calendar-post-{$second->id}", "@calendar-slot-{$key}-13");+ waitForCondition($page, 'window.__heldResponses.length === 2');++ $page->script(<<<'JS'+ (() => {+ window.__toastsSeen = new Set();+ new MutationObserver(() => document.querySelectorAll('[data-testid^="calendar-reschedule-"]').forEach((toast) => window.__toastsSeen.add(toast.dataset.testid)))+ .observe(document.body, { childList: true, subtree: true });+ })()+ JS);+ $page->script('window.__heldResponses.shift()()');+ waitForCondition($page, 'window.__heldResponses.length === 1');+ $page->script('window.__releaseHeldResponses()');+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitForCondition($page, 'window.__toastsSeen.has("calendar-reschedule-approval-toast")');++ expect($page->script('[...window.__toastsSeen]'))->toBe(['calendar-reschedule-approval-toast'])+ ->and($first->refresh()->status)->toBe(PostStatus::PendingApproval)+ ->and($second->refresh()->status)->toBe(PostStatus::PendingApproval);+ $page->assertNoJavaScriptErrors();+});++test('a drag that ends on its own cell sends nothing', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 40);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-10");++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10");++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(11, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a post in the repeated hour of a daylight saving change dropped on its own cell sends nothing', function () {+ [$user, $channel] = calendarDragSetup();+ $fallBack = CarbonImmutable::parse('first sunday of november this year', 'America/New_York');+ $fallBack = $fallBack->isFuture() ? $fallBack : CarbonImmutable::parse('first sunday of november next year', 'America/New_York');+ $key = $fallBack->format('Y-m-d');+ $at = CarbonImmutable::parse("{$key} 06:30", 'UTC');+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($fallBack, ['tz' => 'America/New_York']));+ waitFor($page, "@calendar-slot-{$key}-01 @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-01");++ waitForGone($page, '@calendar-grid[aria-busy]');+ $page->assertMissing('@calendar-reschedule-success-toast');+ expect($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the custom time dialog footer fits a phone', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$day->format('Y-m-d')}-11");+ waitFor($page, '@calendar-custom-time-dialog');+ $page->resize(390, 844);+ waitForState($page, '@calendar-custom-time-dialog', 'element.offsetWidth === 390');++ $layout = $page->script(<<<'JS'+ (() => {+ const dialog = document.querySelector('[data-testid="calendar-custom-time-dialog"]');+ const footer = dialog.querySelector('[data-testid="calendar-custom-time-footer"]');+ const bounds = dialog.getBoundingClientRect();++ return {+ inside: [...footer.children].every((child) => {+ const box = child.getBoundingClientRect();++ return box.left >= bounds.left && box.right <= bounds.right;+ }),+ atBottom: Math.round(bounds.bottom - footer.getBoundingClientRect().bottom) <= 16,+ };+ })()+ JS);++ expect($layout)->toBe(['inside' => true, 'atBottom' => true]);+ $page->assertNoJavaScriptErrors();+});++test('a mouse drag starts only after 4px', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await move(at(start, 3, 0));+ const short = state();+ await move(at(start, 5, 0));++ return [short, state()];+ JS);++ expect($steps[0]['dragging'])->toBeFalse()+ ->and($steps[1]['dragging'])->toBeTrue();++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertMissing('@calendar-drag-preview')+ ->assertNoJavaScriptErrors();+});++test('a touch press held 250ms drags the card', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day))->on()->iPadPro()->resize(1024, 1366);+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-12\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await move(at(start, 2, 2));+ await pause(100);+ const early = state();+ await pause(250);+ const held = state();+ await move(center('@calendar-slot-{$key}-12'));+ const prevented = touchMovePrevented('@calendar-post-{$post->id}');+ const touchAction = getComputedStyle(query('@calendar-post-{$post->id}')).touchAction;+ await up(center('@calendar-slot-{$key}-12'));++ return { early: early.dragging, held: held.dragging, prevented, touchAction };+ JS, 'touch');++ expect($steps)->toBe(['early' => false, 'held' => true, 'prevented' => true, 'touchAction' => 'none']);++ waitFor($page, "@calendar-slot-{$key}-12 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a sideways touch drag moves the post and does not swipe to another period', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $nextKey = $day->addDay()->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day))->on()->iPadPro()->resize(1024, 1366);+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $week = $page->script('location.search');++ calendarGesture($page, <<<JS+ query('@calendar-post-{$post->id}').scrollIntoView({ block: 'center' });+ await frame();+ const start = center('@calendar-post-{$post->id}');+ const end = center('@calendar-slot-{$nextKey}-10');+ const touch = (type, point) => {+ const target = query('@calendar-post-{$post->id}');+ const contact = new Touch({ identifier: 7, target, clientX: point.x, clientY: point.y });+ target.dispatchEvent(new TouchEvent(type, {+ bubbles: true,+ cancelable: true,+ touches: type === 'touchend' ? [] : [contact],+ changedTouches: [contact],+ }));+ };+ touch('touchstart', start);+ await down(start);+ await move(at(start, 2, 2));+ await pause(350);+ await move(end);+ touch('touchmove', end);+ await up(end);+ touch('touchend', end);+ await frame();+ JS, 'touch');++ waitFor($page, "@calendar-slot-{$nextKey}-10 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($page->script('location.search'))->toBe($week)+ ->and($post->refresh()->scheduled_at->equalTo($day->addDay()->setTime(10, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a touch swipe before 250ms scrolls and does not drag', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day))->on()->iPadPro()->resize(1024, 1366);+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ const start = center('@calendar-post-{$post->id}');+ const touchAction = getComputedStyle(query('@calendar-post-{$post->id}')).touchAction;+ await down(start);+ await pause(50);+ await move(at(start, 0, -20));+ const prevented = touchMovePrevented('@calendar-post-{$post->id}');+ await pause(300);+ const after = state();+ await move(center('@calendar-slot-{$key}-12'));+ const prevented2 = touchMovePrevented('@calendar-post-{$post->id}');+ await up(center('@calendar-slot-{$key}-12'));++ return { touchAction, prevented: prevented || prevented2, dragging: after.dragging };+ JS, 'touch');++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect($steps)->toBe(['touchAction' => 'auto', 'prevented' => false, 'dragging' => false])+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a tap still opens the post', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day))->on()->iPadPro()->resize(1024, 1366);+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->page()->locator("[data-testid=\"calendar-post-{$post->id}\"]")->tap();+ waitFor($page, "@post-details-{$post->id}");++ $page->assertVisible("@post-details-{$post->id}")+ ->assertMissing('@calendar-drag-preview');+ $page->keys("@post-details-{$post->id}", 'Escape');+ waitForGone($page, "@post-details-{$post->id}");++ $page->click("@calendar-post-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");+ $page->assertVisible("@post-details-{$post->id}")+ ->assertNoJavaScriptErrors();+});++test('mid-drag the preview, placeholder, hovered cell and hovered slot show the drag', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '15:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(13, 30));+ $other = calendarDragPost($channel, $day->setTime(12, 10));+ $slotKey = calendarDragSlotKey($channel, $day->setTime(15, 25));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-13\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ const origin = () => query('@calendar-post-{$post->id}');+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const overCell = {+ ...state(),+ placeholder: origin().hasAttribute('data-dragging') && getComputedStyle(origin().firstElementChild).visibility === 'hidden',+ cell: query('@calendar-slot-{$key}-12').hasAttribute('data-drop-over'),+ dimmed: getComputedStyle(query('@calendar-post-{$other->id}')).opacity,+ };+ await move(center('@calendar-posting-slot-{$slotKey}'));+ const overSlot = {+ slot: query('@calendar-posting-slot-{$slotKey}').hasAttribute('data-drop-over'),+ cell: query('@calendar-slot-{$key}-15').hasAttribute('data-drop-over'),+ previous: query('@calendar-slot-{$key}-12').hasAttribute('data-drop-over'),+ };++ return { overCell, overSlot };+ JS);++ expect($steps['overCell'])->toBe([+ 'dragging' => true,+ 'opacity' => '0.8',+ 'rotated' => true,+ 'placeholder' => true,+ 'cell' => true,+ 'dimmed' => '0.5',+ ])->and($steps['overSlot'])->toBe(['slot' => true, 'cell' => false, 'previous' => false]);++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertNoJavaScriptErrors();+});++test('the grid auto-scrolls near its bottom edge', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(1, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-time-grid\"]').scrollTop = 0");++ calendarGesture($page, <<<JS+ const box = query('@calendar-time-grid').getBoundingClientRect();+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await move({ x: start.x, y: box.bottom - 10 });+ JS);+ waitForState($page, '@calendar-time-grid', 'element.scrollTop > 0');++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertNoJavaScriptErrors();+});++test('Esc cancels a drag', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-12\"]').scrollIntoView({ block: 'center' })");++ $over = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));++ return state().dragging && query('@calendar-slot-{$key}-12').hasAttribute('data-drop-over');+ JS);++ expect($over)->toBeTrue();++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');++ $after = calendarGesture($page, <<<JS+ await up(center('@calendar-slot-{$key}-12'));++ return query('@calendar-slot-{$key}-12').hasAttribute('data-drop-over');+ JS);++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect($after)->toBeFalse()+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the release after Esc does not open the post it started from', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-12\"]').scrollIntoView({ block: 'center' })");++ $dragging = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));++ return state().dragging;+ JS);+ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');++ calendarGesture($page, <<<JS+ fire('pointerup', center('@calendar-post-{$post->id}'));+ query('@calendar-post-{$post->id}').click();+ await frame();+ JS);++ expect($dragging)->toBeTrue();+ $page->assertMissing("@post-details-{$post->id}");+ $page->click("@calendar-post-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");+ $page->assertNoJavaScriptErrors();+});++test('a drag ends when the window loses focus or the mouse button is already up', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-12\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const dragging = state().dragging;+ window.dispatchEvent(new Event('blur'));+ await frame();+ const blurred = state().dragging;+ await move(center('@calendar-slot-{$key}-13'));+ await up(center('@calendar-slot-{$key}-13'));++ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const again = state().dragging;+ await hover(center('@calendar-slot-{$key}-13'));+ const buttonless = state().dragging;+ await up(center('@calendar-slot-{$key}-13'));++ return { dragging, blurred, again, buttonless, cell: query('@calendar-slot-{$key}-12').hasAttribute('data-drop-over') };+ JS);++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect($steps)->toBe(['dragging' => true, 'blurred' => false, 'again' => true, 'buttonless' => false, 'cell' => false])+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++function calendarDragWatchAnnouncer(mixed $page): void+{+ $page->script(<<<'JS'+ window.__announcements = [];+ new MutationObserver(() => {+ const text = document.querySelector('[data-testid="calendar-drag-announcer"]').textContent.trim();++ if (text !== '') {+ window.__announcements.push(text);+ }+ }).observe(document.querySelector('[data-testid="calendar-drag-announcer"]'), { childList: true, characterData: true, subtree: true });+ JS);+}++/**+ * @return list<string>+ */+function calendarDragAnnouncements(mixed $page): array+{+ return $page->script('window.__announcements');+}++function calendarDragWhen(CarbonImmutable $at, bool $dateOnly = false): string+{+ $date = $at->format($at->year === now('UTC')->year ? 'l, F j' : 'l, F j, Y');++ return $dateOnly+ ? $date+ : __('calendar.reschedule.announce.date_time', ['date' => $date, 'time' => $at->format('g:i A')]);+}++test('a drop in the week view announces the target once and then the move once', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $from = $day->setTime(10, 30);+ $to = $day->setTime(12, 0);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, "@calendar-slot-{$key}-12 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragAnnouncements($page))->toBe([+ __('calendar.reschedule.announce.over', ['from' => calendarDragWhen($from), 'target' => calendarDragWhen($to)]),+ __('calendar.reschedule.announce.moved', ['from' => calendarDragWhen($from), 'to' => calendarDragWhen($to)]),+ ]);+ $page->assertNoJavaScriptErrors();+});++test('a month drop announces the date only for the target', function () {+ [$user, $channel] = calendarDragSetup();+ $from = now('UTC')->startOfMonth()->addMonth()->addDays(3)->setTime(14, 35);+ $to = $from->addDays(2);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $from->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$to->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$to->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragAnnouncements($page))->toBe([+ __('calendar.reschedule.announce.over', ['from' => calendarDragWhen($from), 'target' => calendarDragWhen($to, dateOnly: true)]),+ __('calendar.reschedule.announce.moved', ['from' => calendarDragWhen($from), 'to' => calendarDragWhen($to, dateOnly: true)]),+ ]);+ $page->assertNoJavaScriptErrors();+});++test('a drag released outside every target returns the card and announces it once', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $from = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);++ calendarGesture($page, <<<JS+ query('@calendar-slot-{$key}-12').scrollIntoView({ block: 'center' });+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ await move({ x: 2, y: 2 });+ await up({ x: 2, y: 2 });+ JS);+ waitForGone($page, '@calendar-drag-preview');++ expect(calendarDragAnnouncements($page))->toBe([+ __('calendar.reschedule.announce.over', ['from' => calendarDragWhen($from), 'target' => calendarDragWhen($day->setTime(12, 0))]),+ __('calendar.reschedule.announce.returned'),+ ])+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($from))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('Esc announces that the card went back, once', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);++ calendarGesture($page, <<<JS+ query('@calendar-slot-{$key}-12').scrollIntoView({ block: 'center' });+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ JS);+ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ calendarGesture($page, "await up(center('@calendar-slot-{$key}-12'));");++ $announcements = calendarDragAnnouncements($page);+ expect($announcements)->toHaveCount(2)+ ->and($announcements[1])->toBe(__('calendar.reschedule.announce.returned'));+ $page->assertNoJavaScriptErrors();+});++test('the No Date panel highlights for a scheduled post, takes it and announces where it went', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $from = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, '@calendar-undated-empty');+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);++ $highlighted = calendarGesture($page, <<<JS+ query('@calendar-post-{$post->id}').scrollIntoView({ block: 'center' });+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-undated-panel'));+ const highlighted = query('@calendar-undated-panel').hasAttribute('data-drop-over');+ await up(center('@calendar-undated-panel'));++ return highlighted;+ JS);+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($highlighted)->toBeTrue()+ ->and(calendarDragAnnouncements($page))->toContain(__('calendar.reschedule.announce.undated', ['from' => calendarDragWhen($from)]))+ ->and($post->refresh()->scheduled_at)->toBeNull();+ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unscheduled'))+ ->assertDontSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unqueued_suffix'))+ ->assertNoJavaScriptErrors();+});++test('dropping a dated draft on No Date announces it and toasts', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $from = $day->setTime(10, 0);+ $draft = calendarDragPost($channel, $from, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-post-{$draft->id}");+ waitFor($page, '@calendar-undated-empty');+ calendarDragAssertLive($page, "@calendar-post-{$draft->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$draft->id}", '@calendar-undated-panel');+ waitFor($page, "@calendar-undated-{$draft->id}");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragAnnouncements($page))->toBe([+ __('calendar.reschedule.announce.over', ['from' => calendarDragWhen($from), 'target' => __('calendar.no_date')]),+ __('calendar.reschedule.announce.undated', ['from' => calendarDragWhen($from)]),+ ]);+ expect($page->script(<<<'JS'+ (() => {+ const toast = document.querySelector('[data-testid="calendar-reschedule-success-toast"]').getBoundingClientRect();+ const centre = toast.left + toast.width / 2;++ return {+ top: toast.top < window.innerHeight / 4,+ centred: Math.abs(centre - window.innerWidth / 2) <= 2,+ };+ })()+ JS))->toBe(['top' => true, 'centred' => true]);+ expect($page->script(<<<'JS'+ (() => {+ const toast = document.querySelector('[data-testid="calendar-reschedule-success-toast"]');+ const style = getComputedStyle(toast);+ const icon = toast.querySelector('[data-icon]').getBoundingClientRect();+ const content = toast.querySelector('[data-content]').getBoundingClientRect();+ const close = toast.querySelector('[data-close-button]').getBoundingClientRect();++ return {+ width: toast.offsetWidth,+ padding: style.padding,+ radius: style.borderTopLeftRadius,+ font: [style.fontSize, style.lineHeight, style.fontWeight],+ icon: [icon.width, Math.round(icon.top - toast.getBoundingClientRect().top)],+ closeAfterContent: close.left >= content.right,+ closeSize: close.width,+ };+ })()+ JS))->toBe([+ 'width' => 480,+ 'padding' => '12px 16px 12px 12px',+ 'radius' => '12px',+ 'font' => ['14px', '21px', '400'],+ 'icon' => [24, 12],+ 'closeAfterContent' => true,+ 'closeSize' => 24,+ ]);+ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.undated'))+ ->assertNoJavaScriptErrors();+});++test('a draft from the No Date panel announces where it is over, then its channel and new time, and toasts as a draft', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $to = $day->setTime(11, 0);+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-slot-{$key}-11");+ waitFor($page, "@calendar-slot-{$key}-11 @calendar-post-{$draft->id}");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragAnnouncements($page))->toBe([+ __('calendar.reschedule.announce.over_undated', ['channel' => $channel->display_label, 'target' => calendarDragWhen($to)]),+ __('calendar.reschedule.announce.from_undated', ['channel' => $channel->display_label, 'to' => calendarDragWhen($to)]),+ ]);+ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved_draft', ['time' => calendarDragWhen($to)]))+ ->assertNoJavaScriptErrors();+});++test('every draggable card describes how to drag it', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 0));+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");++ $describe = fn (string $selector): ?string => $page->script("(() => { const id = document.querySelector('[data-testid=\"{$selector}\"]').getAttribute('aria-describedby'); return id ? document.getElementById(id)?.textContent.trim() ?? null : null; })()");++ $linkText = $page->script("document.querySelector('[data-testid=\"calendar-undated-{$draft->id}\"]').textContent");+ expect($linkText)->not->toContain(__('calendar.reschedule.drag_hint_undated', ['channel' => $channel->display_label]));++ $page->assertScript("[...document.querySelectorAll('[data-testid^=\"calendar-drag-hint-\"]')].every((hint) => getComputedStyle(hint).display === 'none')", true);++ expect($describe("calendar-post-{$post->id}"))->toBe(__('calendar.reschedule.drag_hint'))+ ->and($describe("calendar-undated-{$draft->id}"))->toBe(__('calendar.reschedule.drag_hint_undated', ['channel' => $channel->display_label]));+ $page->assertNoJavaScriptErrors();+});++test('a moved post toasts its new time', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-reschedule-success-toast');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved', ['time' => calendarDragWhen($day->setTime(12, 0))]))+ ->assertNoJavaScriptErrors();+});++test('a month move toasts the date only', function () {+ [$user, $channel] = calendarDragSetup();+ $from = now('UTC')->startOfMonth()->addMonth()->addDays(3)->setTime(14, 35);+ $to = $from->addDays(2);+ $post = calendarDragPost($channel, $from);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $from->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$to->format('Y-m-d')}");+ waitFor($page, '@calendar-reschedule-success-toast');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved', ['time' => calendarDragWhen($to, dateOnly: true)]))+ ->assertNoJavaScriptErrors();+});++test('a queued post that leaves the queue says its slot is free again', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-custom-time-dialog');+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, '@calendar-reschedule-success-toast');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved', ['time' => calendarDragWhen($day->setTime(12, 0))]).' '.__('calendar.reschedule.toast.unqueued_suffix'))+ ->assertNoJavaScriptErrors();+});++test('toasts and announcements write dates in the order of the user\'s language', function () {+ [$user, $channel] = calendarDragSetup();+ $user->update(['locale' => Locale::PortugueseBrazil]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $to = $day->setTime(12, 0);+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $expected = $page->script("new Intl.DateTimeFormat('pt-BR', { weekday: 'long', month: 'long', day: 'numeric', timeZone: 'UTC' }).format(new Date('{$to->format('Y-m-d\\TH:i:s')}Z'))");+ $toast = $page->script('document.querySelector(\'[data-testid="calendar-reschedule-success-toast"]\').textContent');+ $announced = implode(' ', calendarDragAnnouncements($page));++ expect($toast)->toContain($expected)+ ->and($announced)->toContain($expected);+ $page->assertNoJavaScriptErrors();+});++test('toasts and announcements follow the user\'s 24-hour clock', function () {+ [$user, $channel] = calendarDragSetup();+ $user->update(['time_format' => TimeFormat::TwentyFourHour]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-15");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $toast = $page->script('document.querySelector(\'[data-testid="calendar-reschedule-success-toast"]\').textContent');+ $announced = implode(' ', calendarDragAnnouncements($page));++ expect($toast)->toContain('15:00')+ ->not->toContain('3:00 PM')+ ->and($announced)->toContain('15:00')+ ->and($announced)->toContain('10:30')+ ->and($announced)->not->toContain('PM');+ $page->assertNoJavaScriptErrors();+});++/**+ * Sends a Playwright protocol call to the page or its context, for what Pest+ * does not expose: the real mouse and the clock.+ */+function calendarDragPlaywright(object $target, string $method, array $params = []): void+{+ $guid = (fn (): string => $this->guid)->call($target);++ iterator_to_array(Client::instance()->execute($guid, $method, $params));+}++/**+ * Presses the real mouse on an element, moves it away and back, and releases+ * it there, so the browser fires the click a drag must swallow.+ */+function calendarDragRealMouseRoundTrip(mixed $page, string $selector): void+{+ $point = calendarGesture($page, <<<JS+ query('{$selector}').scrollIntoView({ block: 'center' });++ return center('{$selector}');+ JS);++ calendarDragPlaywright($page->page(), 'mouseMove', ['x' => $point['x'], 'y' => $point['y']]);+ calendarDragPlaywright($page->page(), 'mouseDown', ['button' => 'left', 'clickCount' => 1]);+ calendarDragPlaywright($page->page(), 'mouseMove', ['x' => $point['x'] + 30, 'y' => $point['y'] + 20, 'steps' => 5]);+ calendarDragPlaywright($page->page(), 'mouseMove', ['x' => $point['x'], 'y' => $point['y'], 'steps' => 5]);+ calendarDragPlaywright($page->page(), 'mouseUp', ['button' => 'left', 'clickCount' => 1]);+}++/**+ * Holds every PUT the page sends until `window.__releaseHeldRequests()`.+ */+function calendarDragHoldRequests(mixed $page): void+{+ $page->script(<<<'JS'+ (() => {+ window.__heldRequests = [];+ const open = XMLHttpRequest.prototype.open;+ const send = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.open = function (method, ...rest) {+ this.__method = method.toUpperCase();++ return open.call(this, method, ...rest);+ };+ XMLHttpRequest.prototype.send = function (body) {+ if (this.__method !== 'PUT') {+ return send.call(this, body);+ }++ window.__heldRequests.push(() => send.call(this, body));+ };+ window.__releaseHeldRequests = () => window.__heldRequests.splice(0).forEach((release) => release());+ })()+ JS);+}++/**+ * Sends every PUT at once but holds its answer until `window.__releaseHeldResponses()`,+ * so the request still carries the page it was sent from.+ */+function calendarDragHoldResponses(mixed $page): void+{+ $page->script(<<<'JS'+ (() => {+ window.__heldResponses = [];+ const open = XMLHttpRequest.prototype.open;+ const send = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.open = function (method, ...rest) {+ this.__method = method.toUpperCase();++ return open.call(this, method, ...rest);+ };+ XMLHttpRequest.prototype.send = function (body) {+ if (this.__method === 'PUT') {+ const onload = this.onload;++ this.onload = (...args) => window.__heldResponses.push(() => onload.apply(this, args));+ }++ return send.call(this, body);+ };+ window.__releaseHeldResponses = () => window.__heldResponses.splice(0).forEach((release) => release());+ })()+ JS);+}++/**+ * Sends every PUT the page makes to a closed port, so it fails as a network error.+ */+function calendarDragBreakNetwork(mixed $page): void+{+ $page->script(<<<'JS'+ (() => {+ const open = XMLHttpRequest.prototype.open;+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {+ return open.call(this, method, method.toUpperCase() === 'PUT' ? 'http://127.0.0.1:9/' : url, ...rest);+ };+ })()+ JS);+}++test('a queued post dropped on another channel\'s slot at the same time asks first; cancel leaves it', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $other = SocialAccount::factory()->linkedin()->create([+ 'workspace_id' => $channel->workspace_id,+ 'timezone' => 'UTC',+ 'posting_schedule' => $channel->posting_schedule,+ ]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $queuedAt = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $otherSlotKey = calendarDragSlotKey($other, $day->addDay()->setTime(9, 25));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$otherSlotKey}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$otherSlotKey}");+ waitFor($page, '@calendar-custom-time-dialog');++ $page->assertVisible('@calendar-custom-time-dialog');+ $page->click('@calendar-custom-time-cancel');+ waitForGone($page, '@calendar-custom-time-dialog');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-09");+ $post->refresh();+ expect($post->scheduled_at->equalTo($queuedAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertNoJavaScriptErrors();+});++test('a move the server cannot take goes back with the generic error', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ $post->delete();++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-reschedule-error-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-error-toast', __('calendar.reschedule.error'));+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and(array_slice(calendarDragAnnouncements($page), -1))->toBe([__('calendar.reschedule.announce.returned')]);+ $page->assertNoJavaScriptErrors();+});++test('a move lost to the network goes back with the generic error', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragBreakNetwork($page);++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-reschedule-error-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-error-toast', __('calendar.reschedule.error'));+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the click that ends a real mouse drag does not open the post', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $at = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ calendarDragRealMouseRoundTrip($page, "@calendar-post-{$post->id}");+ $opened = calendarGesture($page, <<<JS+ await pause(300);++ return query('@post-details-{$post->id}') !== null;+ JS);++ expect($opened)->toBeFalse()+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertMissing("@post-details-{$post->id}")+ ->assertNoJavaScriptErrors();+});++test('the click that ends a real mouse drag does not follow the draft link', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");++ calendarDragRealMouseRoundTrip($page, "@calendar-undated-{$draft->id}");+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-slot-{$key}-11");+ waitFor($page, "@calendar-slot-{$key}-11 @calendar-post-{$draft->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertPathIs(route('app.calendar', ['view' => 'week'], absolute: false))+ ->assertNoJavaScriptErrors();+});++test('Esc on the custom time dialog sends the card back and the next confirm still lands', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $queuedAt = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');+ $page->keys('@calendar-custom-time-dialog', 'Escape');+ waitForGone($page, '@calendar-custom-time-dialog');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-09")+ ->and(array_slice(calendarDragAnnouncements($page), -1))->toBe([__('calendar.reschedule.announce.returned')]);+ $post->refresh();+ expect($post->scheduled_at->equalTo($queuedAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-confirm');+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, "@calendar-slot-{$key}-11 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($day->setTime(11, 0)))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom);+ $page->assertNoJavaScriptErrors();+});++test('the custom time dialog, the toast and the announcement use the display zone', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $queuedAt = $day->setTime(9, 25);+ $tokyoFrom = $queuedAt->setTimezone('Asia/Tokyo');+ $tokyoTo = $tokyoFrom->setTime(20, 0);+ $key = $tokyoFrom->format('Y-m-d');+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['tz' => 'Asia/Tokyo']));+ waitFor($page, "@calendar-slot-{$key}-18 @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-20");+ waitFor($page, '@calendar-custom-time-dialog');++ $page->assertSeeIn('@calendar-custom-time-description', "{$tokyoFrom->format('M j, g:i A')} (Asia/Tokyo)")+ ->assertSeeIn('@calendar-custom-time-description', "{$tokyoTo->format('M j, g:i A')} (Asia/Tokyo)");+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.moved', ['time' => calendarDragWhen($tokyoTo)]));+ expect(array_slice(calendarDragAnnouncements($page), -1))->toBe([+ __('calendar.reschedule.announce.moved', ['from' => calendarDragWhen($tokyoFrom), 'to' => calendarDragWhen($tokyoTo)]),+ ])+ ->and($post->refresh()->scheduled_at->equalTo($tokyoTo))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the custom time dialog follows the user\'s 24-hour clock', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $user->update(['time_format' => TimeFormat::TwentyFourHour]);+ $day = calendarDragDay();+ $tokyoFrom = $day->setTime(9, 25)->setTimezone('Asia/Tokyo');+ $key = $tokyoFrom->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['tz' => 'Asia/Tokyo']));+ waitFor($page, "@calendar-slot-{$key}-18 @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-20");+ waitFor($page, '@calendar-custom-time-dialog');++ $description = $page->script('document.querySelector(\'[data-testid="calendar-custom-time-description"]\').textContent');++ expect($description)->toContain("{$tokyoFrom->format('M j')}, 18:25 (Asia/Tokyo)")+ ->toContain("{$tokyoFrom->format('M j')}, 20:00 (Asia/Tokyo)")+ ->not->toContain('AM')+ ->not->toContain('PM');+ $page->click('@calendar-custom-time-cancel');+ waitForGone($page, '@calendar-custom-time-dialog');+ $page->assertNoJavaScriptErrors();+});++test('a month drop in another display zone keeps the clock of that zone', function () {+ [$user, $channel] = calendarDragSetup();+ $from = now('Asia/Tokyo')->startOfMonth()->addMonth()->addDays(4)->setTime(8, 30);+ $to = $from->addDays(2);+ $draftDay = $from->addDays(3)->startOfDay();+ $post = calendarDragPost($channel, $from->utc());+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $from->format('Y-m-d'), 'tz' => 'Asia/Tokyo', 'undated' => 1]));+ waitFor($page, "@calendar-day-{$from->format('Y-m-d')} @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$to->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$to->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($to))->toBeTrue();++ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-day-{$draftDay->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$draftDay->format('Y-m-d')} @calendar-post-{$draft->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($draft->refresh()->scheduled_at->equalTo($draftDay->setTime(9, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a month drop on today is refused when five minutes from now is already tomorrow', function () {+ [$user, $channel] = calendarDragSetup();+ $late = now('UTC')->startOfMonth()->addMonth()->addDays(14)->setTime(23, 57);+ $this->travelTo($late);+ $today = $late->format('Y-m-d');+ $at = $late->addDay()->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $today]));+ calendarDragPlaywright($page->page()->context(), 'clockInstall', ['timeNumber' => $late->getTimestampMs()]);+ $page->page()->reload();+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $accepts = calendarGesture($page, <<<JS+ query('@calendar-post-{$post->id}').scrollIntoView({ block: 'center' });+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-day-{$today}'));+ const over = query('@calendar-day-{$today}').hasAttribute('data-drop-over');+ const clock = Date.now();+ await up(center('@calendar-day-{$today}'));++ return { over, clock };+ JS);+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($accepts['over'])->toBeFalse()+ ->and(abs($accepts['clock'] - $late->getTimestampMs()))->toBeLessThan(60_000)+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-day-{$at->format('Y-m-d')}")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();++ $noon = $late->setTime(12, 0);+ $this->travelTo($noon);+ calendarDragPlaywright($page->page()->context(), 'clockSetSystemTime', ['timeNumber' => $noon->getTimestampMs()]);+ $page->page()->reload();+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$today}");+ waitFor($page, "@calendar-day-{$today} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($noon->addMinutes(5)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a post due within a minute and a draft without a channel cannot be dragged', function () {+ [$user, $channel] = calendarDragSetup();+ $soon = now('UTC')->addSeconds(30);+ $due = calendarDragPost($channel, $soon);+ $movable = calendarDragPost($channel, $soon->addHours(2));+ $edge = calendarDragPost($channel, now('UTC')->addMinutes(2));+ $channelless = Post::factory()->create([+ 'workspace_id' => $channel->workspace_id,+ 'user_id' => $user->id,+ 'content' => 'No channel yet',+ 'status' => PostStatus::Draft,+ 'scheduled_at' => null,+ ]);+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'days', 'day' => $soon->format('Y-m-d'), 'undated' => 1]));+ waitFor($page, "@calendar-post-{$due->id}");+ waitFor($page, "@calendar-undated-{$channelless->id}");+ calendarDragAssertLive($page, "@calendar-post-{$movable->id}");+ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");++ $draggable = fn (string $selector): ?string => $page->script("document.querySelector('[data-testid=\"{$selector}\"]').dataset.calendarDraggable ?? null");++ expect($channelless->platform)->toBeNull()+ ->and($draggable("calendar-post-{$movable->id}"))->toBe('true')+ ->and($draggable("calendar-post-{$edge->id}"))->toBe('true')+ ->and($draggable("calendar-undated-{$draft->id}"))->toBe('true')+ ->and($draggable("calendar-post-{$due->id}"))->toBeNull()+ ->and($draggable("calendar-undated-{$channelless->id}"))->toBeNull();+ $page->assertNoJavaScriptErrors();+});++test('the card a member who needs approval moved is no longer draggable', function () {+ [$owner, $channel] = calendarDragSetup();+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 0), attributes: ['user_id' => $member->id]);+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-reschedule-approval-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitForState($page, "@calendar-post-{$post->id}", 'element.dataset.calendarDraggable === undefined');++ expect($post->refresh()->status)->toBe(PostStatus::PendingApproval)+ ->and($page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]').dataset.calendarDraggable ?? null"))->toBeNull();+ $page->assertNoJavaScriptErrors();+});++test('a pointercancel, a hidden tab or a period change ends a drag without sending anything', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 30);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-slot-{$key}-12\"]').scrollIntoView({ block: 'center' })");++ $steps = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const before = state().dragging;+ fire('pointercancel', center('@calendar-slot-{$key}-12'), 0);+ await frame();+ const cancelled = state().dragging;+ await up(center('@calendar-slot-{$key}-12'));++ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const again = state().dragging;+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });+ document.dispatchEvent(new Event('visibilitychange'));+ delete document.visibilityState;+ await frame();+ const hidden = state().dragging;+ await up(center('@calendar-slot-{$key}-12'));++ return { before, cancelled, again, hidden };+ JS);++ waitForGone($page, '@calendar-grid[aria-busy]');+ expect($steps)->toBe(['before' => true, 'cancelled' => false, 'again' => true, 'hidden' => false])+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-10")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();++ $nextKey = $day->addWeek()->format('Y-m-d');+ $dragging = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const dragging = state().dragging;+ query('@calendar-next').click();++ return dragging;+ JS);+ waitFor($page, "@calendar-slot-{$nextKey}-12");+ waitForGone($page, '@calendar-drag-preview');+ calendarGesture($page, <<<JS+ query('@calendar-slot-{$nextKey}-12').scrollIntoView({ block: 'center' });+ await move(center('@calendar-slot-{$nextKey}-12'));+ await up(center('@calendar-slot-{$nextKey}-12'));+ JS);+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($dragging)->toBeTrue()+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertMissing('@calendar-drag-preview')+ ->assertNoJavaScriptErrors();+});++test('the card sits in its new cell while the move is on its way and stays there', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-12")+ ->and($page->script('document.querySelector(\'[data-testid="calendar-grid"]\').getAttribute(\'aria-busy\')'))->toBe('true')+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();++ $page->script('window.__releaseHeldRequests()');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-12")+ ->and($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a card whose move is on its way cannot be dragged again until it lands', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $draggedAgain = calendarGesture($page, <<<JS+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-14'));+ const dragging = state().dragging;+ await up(center('@calendar-slot-{$key}-14'));++ return dragging;+ JS);++ expect($draggedAgain)->toBeFalse()+ ->and($page->script('window.__heldRequests.length'))->toBe(1);++ $page->script('window.__releaseHeldRequests()');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$key}-12")+ ->and($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();++ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-14");+ waitForCondition($page, 'window.__heldRequests.length === 1');+ $page->script('window.__releaseHeldRequests()');+ waitFor($page, "@calendar-slot-{$key}-14 @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(14, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a post that becomes due before the move reaches the server goes back with the reason', function () {+ [$user, $channel] = calendarDragSetup();+ $at = now('UTC')->addMinutes(3)->startOfMinute();+ $target = $at->addDay()->startOfHour();+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'days', 'day' => $at->format('Y-m-d')]));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $this->travelTo($at->subSeconds(30));++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$target->format('Y-m-d')}-{$target->format('H')}");+ waitFor($page, '@calendar-reschedule-error-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-error-toast', __('calendar.reschedule.errors.publishing_soon'));+ expect(calendarDragCellOf($page, $post))->toBe("calendar-slot-{$at->format('Y-m-d')}-{$at->format('H')}")+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a custom post dropped on a posting time of its channel in the month grid goes into the queue at that time', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '15:25');+ $day = calendarDragDay();+ $slotAt = $day->addDay()->setTime(15, 25);+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $post = calendarDragPost($channel, $day->setTime(13, 30));+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-day-{$slotAt->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertMissing('@calendar-custom-time-dialog')+ ->assertNoJavaScriptErrors();+});++test('a queued post dropped on a free posting time of its channel in the month grid stays in the queue there without asking', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $slotAt = $day->addDay()->setTime(9, 25);+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-day-{$slotAt->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertMissing('@calendar-custom-time-dialog')+ ->assertNoJavaScriptErrors();+});++/**+ * The next US daylight saving change of the given rule ("first sunday of+ * november", "second sunday of march") at least a few days away, in New York.+ */+function calendarDragNextDstSunday(string $rule): CarbonImmutable+{+ $year = now('UTC')->year;+ $sunday = CarbonImmutable::parse("{$rule} {$year}", 'America/New_York');++ return $sunday->subDays(3)->isAfter(now('UTC')) ? $sunday : CarbonImmutable::parse("{$rule} ".($year + 1), 'America/New_York');+}++test('a month drop across the end of daylight saving keeps the wall clock', function (string $userZone, array $query) {+ [$user, $channel] = calendarDragSetup($userZone);+ $user->update(['week_starts_on' => WeekStart::Monday]);+ $sunday = calendarDragNextDstSunday('first sunday of november');+ $from = $sunday->subDays(2)->setTime(10, 0);+ $to = $sunday->addDay()->setTime(10, 0);+ $post = calendarDragPost($channel, $from->utc());+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $sunday->format('Y-m-d'), ...$query]));+ waitFor($page, "@calendar-day-{$from->format('Y-m-d')} @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$to->format('Y-m-d')}");+ waitFor($page, "@calendar-day-{$to->format('Y-m-d')} @calendar-post-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($from->utc()->format('H:i'))->toBe('14:00')+ ->and($post->refresh()->scheduled_at->utc()->format('Y-m-d H:i'))->toBe($to->utc()->format('Y-m-d').' 15:00');+ $page->assertNoJavaScriptErrors();+})->with([+ 'user zone' => ['America/New_York', []],+ 'display zone' => ['UTC', ['tz' => 'America/New_York']],+]);++test('the hour skipped by the start of daylight saving is not a drop target', function () {+ [$user, $channel] = calendarDragSetup('America/New_York');+ $sunday = calendarDragNextDstSunday('second sunday of march');+ $key = $sunday->format('Y-m-d');+ $post = calendarDragPost($channel, $sunday->setTime(10, 0)->utc());+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($sunday));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $keys = $page->script("[...document.querySelectorAll('[data-testid^=\"calendar-slot-{$key}-\"]')].map((cell) => cell.dataset.calendarDrop ?? null)");+ $dropKeys = array_values(array_filter($keys));++ expect($keys)->toHaveCount(24)+ ->and($keys[2])->toBeNull()+ ->and($dropKeys)->toHaveCount(23)+ ->and(array_unique($dropKeys))->toHaveCount(23);+ $page->assertNoJavaScriptErrors();+});++test('the hour skipped by the start of daylight saving is not highlighted and offers no new post', function () {+ [$user, $channel] = calendarDragSetup('America/New_York');+ $sunday = calendarDragNextDstSunday('second sunday of march');+ $key = $sunday->format('Y-m-d');+ $post = calendarDragPost($channel, $sunday->setTime(10, 0)->utc());+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($sunday));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $cells = $page->script(<<<JS+ ({+ skippedOver: document.querySelector('[data-testid="calendar-slot-{$key}-02"]').hasAttribute('data-drop-over'),+ skippedAdd: document.querySelector('[data-testid="calendar-add-{$key}-02"]') !== null,+ nextAdd: document.querySelector('[data-testid="calendar-add-{$key}-03"]') !== null,+ })+ JS);++ expect($cells)->toBe(['skippedOver' => false, 'skippedAdd' => false, 'nextAdd' => true]);+ $page->assertNoJavaScriptErrors();+});++test('a month drop whose clock falls in the hour skipped by daylight saving is refused', function () {+ [$user, $channel] = calendarDragSetup('America/New_York');+ $sunday = calendarDragNextDstSunday('second sunday of march');+ $from = $sunday->subDays(2)->setTime(2, 30);+ $post = calendarDragPost($channel, $from->utc());+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $sunday->format('Y-m-d')]));+ waitFor($page, "@calendar-day-{$from->format('Y-m-d')} @calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-day-{$sunday->format('Y-m-d')}");+ waitForGone($page, '@calendar-drag-preview');++ expect($page->script('window.__heldRequests.length'))->toBe(0)+ ->and(calendarDragCellOf($page, $post))->toBe("calendar-day-{$from->format('Y-m-d')}")+ ->and($post->refresh()->scheduled_at->equalTo($from))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the grid auto-scrolls near its top edge', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(22, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $scroll = calendarGesture($page, <<<JS+ const grid = query('@calendar-time-grid');+ grid.scrollTop = grid.scrollHeight;+ await frame();+ window.__scrollBefore = grid.scrollTop;+ const box = grid.getBoundingClientRect();+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await move({ x: start.x, y: box.top + 10 });++ return window.__scrollBefore;+ JS);++ expect($scroll)->toBeGreaterThan(0);+ waitForState($page, '@calendar-time-grid', 'element.scrollTop < window.__scrollBefore');++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertNoJavaScriptErrors();+});++test('the month grid auto-scrolls near its bottom edge', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $scroll = calendarGesture($page, <<<JS+ const grid = query('@calendar-month-grid');+ query('@calendar-post-{$post->id}').scrollIntoView({ block: 'center' });+ grid.scrollTop = 0;+ await frame();+ const box = grid.getBoundingClientRect();+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await move({ x: start.x, y: box.bottom - 10 });++ return grid.scrollHeight > grid.clientHeight;+ JS);++ expect($scroll)->toBeTrue();+ waitForState($page, '@calendar-month-grid', 'element.scrollTop > 0');++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertNoJavaScriptErrors();+});++test('the context menu does not open during a drag', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");++ $prevented = calendarGesture($page, <<<JS+ const contextMenu = (point) => {+ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y });+ document.elementFromPoint(point.x, point.y).dispatchEvent(event);++ return event.defaultPrevented;+ };+ query('@calendar-slot-{$key}-12').scrollIntoView({ block: 'center' });+ const idle = contextMenu(center('@calendar-post-{$post->id}'));+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const dragging = state().dragging && contextMenu(center('@calendar-slot-{$key}-12'));++ return { idle, dragging };+ JS);++ expect($prevented)->toBe(['idle' => false, 'dragging' => true]);++ $page->keys("@calendar-post-{$post->id}", 'Escape');+ waitForGone($page, '@calendar-drag-preview');+ $page->assertNoJavaScriptErrors();+});++test('a move cancelled by going Back sends nothing more and announces the return once', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $at = $day->setTime(10, 0);+ $post = calendarDragPost($channel, $at);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day->subWeek()));+ $page->click('@calendar-next');+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $page->script('history.back()');+ waitForCondition($page, "window.__announcements.includes('".__('calendar.reschedule.announce.returned')."')");+ waitForCondition($page, "new URLSearchParams(location.search).get('week') === '{$day->subWeek()->format('Y-m-d')}'");+ waitForGone($page, "@calendar-post-{$post->id}");++ expect(array_count_values(calendarDragAnnouncements($page))[__('calendar.reschedule.announce.returned')])->toBe(1)+ ->and($post->refresh()->scheduled_at->equalTo($at))->toBeTrue();+ $page->assertMissing('@calendar-reschedule-error-toast')+ ->assertMissing('@calendar-reschedule-success-toast')+ ->assertNoJavaScriptErrors();+});++test('a move still saving when the week changes does not bring the old week back', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $nextWeek = $day->addWeek()->startOfWeek()->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldResponses($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldResponses.length === 1');++ $page->click('@calendar-next');+ waitFor($page, "@calendar-column-{$nextWeek}");+ $page->script('window.__releaseHeldResponses()');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();+ $page->assertScript("new URLSearchParams(location.search).get('week')", $nextWeek)+ ->assertPresent("@calendar-column-{$nextWeek}")+ ->assertMissing("@calendar-column-{$key}")+ ->assertNoJavaScriptErrors();+});++test('a move by a member who needs approval says so even when the status filter hides the post afterwards', function () {+ [$owner, $channel] = calendarDragSetup();+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 0), attributes: ['user_id' => $member->id]);+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day, ['status' => 'scheduled']));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitForGoneOrShown($page, gone: '@calendar-grid[aria-busy]', shown: '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertPresent('@calendar-reschedule-approval-toast')+ ->assertMissing('@calendar-reschedule-success-toast');+ expect($post->refresh()->status)->toBe(PostStatus::PendingApproval);+ $page->assertNoJavaScriptErrors();+});++test('the custom time dialog writes the dates in the order of the user\'s language', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $user->update(['locale' => Locale::PortugueseBrazil]);+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $queuedAt = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');++ $expected = $page->script("new Intl.DateTimeFormat('pt-BR', { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(new Date('{$queuedAt->format('Y-m-d\\TH:i:s')}Z'))");++ expect($page->script('document.querySelector(\'[data-testid="calendar-custom-time-description"]\').textContent'))+ ->toContain("{$expected}, 9:25 AM (UTC)");+ $page->assertNoJavaScriptErrors();+});++test('a queued post dropped on its channel\'s slot past the queue window asks first and becomes custom', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay()->addWeeks(15);+ $slotAt = $day->addDay()->setTime(9, 25);+ $slotKey = calendarDragSlotKey($channel, $slotAt);+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-posting-slot-{$slotKey}");+ waitFor($page, '@calendar-custom-time-dialog');+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unqueued_suffix'));+ $post->refresh();+ expect($post->scheduled_at->equalTo($slotAt))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom);+ $page->assertNoJavaScriptErrors();+});++test('the custom time dialog shows the year of a date in another year', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = now('UTC')->addYear()->startOfYear()->addWeeks(2)->startOfWeek()->addDays(2)->toImmutable();+ $key = $day->format('Y-m-d');+ $queuedAt = $day->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');++ $page->assertSeeIn('@calendar-custom-time-description', "{$queuedAt->format('M j, Y, g:i A')} (UTC)")+ ->assertNoJavaScriptErrors();+});++test('a post that comes due while it is being dragged goes back without a request', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ $due = $day->setTime(10, 30)->getTimestampMs();++ calendarGesture($page, <<<JS+ query('@calendar-post-{$post->id}').scrollIntoView({ block: 'center' });+ await down(center('@calendar-post-{$post->id}'));+ await move(center('@calendar-slot-{$key}-12'));+ const RealDate = Date;+ const shift = {$due} - RealDate.now();+ window.Date = class extends RealDate {+ constructor(...args) {+ super(...(args.length ? args : [RealDate.now() + shift]));+ }++ static now() {+ return RealDate.now() + shift;+ }+ };+ await up(center('@calendar-slot-{$key}-12'));+ JS);+ waitFor($page, "@calendar-slot-{$key}-10 @calendar-post-{$post->id}");++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(10, 30)))->toBeTrue()+ ->and(calendarDragAnnouncements($page))->toContain(__('calendar.reschedule.announce.returned'));+ $page->assertMissing('@calendar-reschedule-success-toast')+ ->assertMissing('@calendar-reschedule-error-toast')+ ->assertNoJavaScriptErrors();+});++test('an older move answered after a newer one keeps both cards where they were dropped', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $first = calendarDragPost($channel, $day->setTime(10, 0));+ $second = calendarDragPost($channel, $day->setTime(11, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$first->id}");+ calendarDragAssertLive($page, "@calendar-post-{$second->id}");+ calendarDragHoldRequests($page);++ calendarDragOnto($page, "@calendar-post-{$first->id}", "@calendar-slot-{$key}-13");+ waitForCondition($page, 'window.__heldRequests.length === 1');+ calendarDragOnto($page, "@calendar-post-{$second->id}", "@calendar-slot-{$key}-14");+ waitForCondition($page, 'window.__heldRequests.length === 2');++ $page->script('window.__heldRequests[1]()');+ waitFor($page, '@calendar-reschedule-success-toast');+ $page->script(<<<'JS'+ (() => {+ window.__heldReloads = [];+ const send = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.send = function (body) {+ if (this.__method !== 'GET') {+ return send.call(this, body);+ }++ window.__heldReloads.push(() => send.call(this, body));+ };+ })()+ JS);+ $page->script('window.__heldRequests[0]()');+ waitForCondition($page, 'window.__heldReloads.length === 1');++ expect(calendarDragCellOf($page, $first))->toBe("calendar-slot-{$key}-13");++ $page->script('window.__heldReloads.splice(0).forEach((release) => release())');+ waitForGone($page, '@calendar-grid[aria-busy]');+ waitFor($page, "@calendar-slot-{$key}-13 @calendar-post-{$first->id}");+ waitFor($page, "@calendar-slot-{$key}-14 @calendar-post-{$second->id}");++ expect(calendarDragCellOf($page, $first))->toBe("calendar-slot-{$key}-13")+ ->and(calendarDragCellOf($page, $second))->toBe("calendar-slot-{$key}-14")+ ->and($first->refresh()->scheduled_at->equalTo($day->setTime(13, 0)))->toBeTrue()+ ->and($second->refresh()->scheduled_at->equalTo($day->setTime(14, 0)))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a No Date draft dropped on a day while the status filter hides drafts says it moved, not that it went for approval', function () {+ [$user, $channel] = calendarDragSetup();+ $day = now('UTC')->startOfMonth()->addMonth()->addDays(4)->startOfDay();+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d'), 'undated' => 1, 'status' => 'scheduled']));+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragOnto($page, "@calendar-undated-{$draft->id}", "@calendar-day-{$day->format('Y-m-d')}");+ waitForGoneOrShown($page, gone: '@calendar-grid[aria-busy]', shown: '@calendar-reschedule-approval-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertMissing('@calendar-reschedule-approval-toast')+ ->assertPresent('@calendar-reschedule-success-toast');+ $draft->refresh();+ expect($draft->scheduled_at->equalTo($day->setTime(9, 0)))->toBeTrue()+ ->and($draft->status)->toBe(PostStatus::Draft);+ $page->assertNoJavaScriptErrors();+});++test('a move into a free slot updates the posting slots shown, even when the URL does not ask for them', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $queuedAt = $day->setTime(9, 25);+ $slotAt = $day->addDay()->setTime(9, 25);+ $post = calendarDragPost($channel, $queuedAt, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ $page->assertScript("new URLSearchParams(location.search).has('slots')", false);+ waitFor($page, '@calendar-posting-slot-'.calendarDragSlotKey($channel, $slotAt));+ waitFor($page, "@calendar-post-{$post->id}");+ $page->assertMissing('@calendar-posting-slot-'.calendarDragSlotKey($channel, $queuedAt));++ calendarDragOnto($page, "@calendar-post-{$post->id}", '@calendar-posting-slot-'.calendarDragSlotKey($channel, $slotAt));+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-posting-slot-'.calendarDragSlotKey($channel, $slotAt));+ waitFor($page, '@calendar-posting-slot-'.calendarDragSlotKey($channel, $queuedAt));++ $page->assertMissing('@calendar-posting-slot-'.calendarDragSlotKey($channel, $slotAt))+ ->assertPresent('@calendar-posting-slot-'.calendarDragSlotKey($channel, $queuedAt))+ ->assertNoJavaScriptErrors();+});++test('a post that leaves the week while it moves goes back instead of claiming it went for approval', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $post->forceFill(['status' => PostStatus::Published, 'published_at' => now()->subWeeks(2)])->saveQuietly();+ $page->script('window.__releaseHeldRequests()');+ waitForCondition($page, 'window.__announcements.length >= 2');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(calendarDragAnnouncements($page))->toContain(__('calendar.reschedule.announce.returned'));+ $page->assertMissing('@calendar-reschedule-approval-toast')+ ->assertMissing('@calendar-reschedule-success-toast')+ ->assertNoJavaScriptErrors();+});++test('the hour under way takes a drop five minutes from now while that is still inside the hour', function () {+ [$user, $channel] = calendarDragSetup();+ $now = now('UTC');+ $today = $now->format('Y-m-d');+ $post = calendarDragPost($channel, $now->addDay()->startOfHour());+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'days', 'day' => $today]));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$today}-{$now->format('H')}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ $scheduledAt = $post->refresh()->scheduled_at;+ $insideTheHour = $now->addMinutes(6)->format('Y-m-d H') === $now->format('Y-m-d H');++ expect($insideTheHour+ ? $scheduledAt->between($now->addMinutes(4), $now->addMinutes(6)) && $scheduledAt->format('H') === $now->format('H')+ : $scheduledAt->equalTo($now->addDay()->startOfHour()))->toBeTrue();+ $page->assertMissing('@calendar-reschedule-error-toast')+ ->assertNoJavaScriptErrors();+});++test('an older move refused by the server and answered after a newer one still shows why', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $first = calendarDragPost($channel, $day->setTime(10, 0));+ $second = calendarDragPost($channel, $day->setTime(11, 0));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ calendarDragAssertLive($page, "@calendar-post-{$first->id}");+ calendarDragAssertLive($page, "@calendar-post-{$second->id}");+ calendarDragHoldRequests($page);++ calendarDragOnto($page, "@calendar-post-{$first->id}", "@calendar-slot-{$key}-13");+ waitForCondition($page, 'window.__heldRequests.length === 1');+ calendarDragOnto($page, "@calendar-post-{$second->id}", "@calendar-slot-{$key}-14");+ waitForCondition($page, 'window.__heldRequests.length === 2');++ $page->script('window.__heldRequests[1]()');+ waitFor($page, '@calendar-reschedule-success-toast');+ $first->forceFill(['status' => PostStatus::PendingApproval])->saveQuietly();+ $page->script('window.__heldRequests[0]()');+ waitFor($page, '@calendar-reschedule-error-toast');++ $page->assertSeeIn('@calendar-reschedule-error-toast', __('calendar.reschedule.errors.pending'))+ ->assertNoJavaScriptErrors();+ expect($first->refresh()->scheduled_at->equalTo($day->setTime(10, 0)))->toBeTrue();+});++test('a move answered after the view changed is not announced as done without knowing', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $page->click('@calendar-view-trigger');+ waitFor($page, '@calendar-view-month');+ $page->click('@calendar-view-month');+ waitForPath($page, route('app.calendar', ['view' => 'month'], absolute: false));+ waitFor($page, '@calendar-month-grid');++ $post->forceFill(['status' => PostStatus::PendingApproval])->saveQuietly();+ $page->script('window.__releaseHeldRequests()');+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect(implode(' ', calendarDragAnnouncements($page)))->not->toContain(__('calendar.reschedule.announce.moved', ['from' => calendarDragWhen($day->setTime(10, 30)), 'to' => calendarDragWhen($day->setTime(12, 0))]))+ ->and($post->refresh()->scheduled_at->equalTo($day->setTime(10, 30)))->toBeTrue();+ $page->assertMissing('@calendar-reschedule-success-toast')+ ->assertNoJavaScriptErrors();+});++test('a move answered after the view changed is still confirmed when the new view shows it moved', function () {+ $day = now('UTC')->addDay()->startOfDay()->toImmutable();++ if (! $day->isSameMonth(now('UTC'))) {+ $this->markTestSkipped('The month view opens on the current month, which has no day left after today.');+ }++ [$user, $channel] = calendarDragSetup();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $page->click('@calendar-view-trigger');+ waitFor($page, '@calendar-view-month');+ $page->click('@calendar-view-month');+ waitForPath($page, route('app.calendar', ['view' => 'month'], absolute: false));+ waitFor($page, "@calendar-day-{$key}");++ $page->script('window.__releaseHeldRequests()');+ waitFor($page, '@calendar-reschedule-success-toast');++ expect($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();+ $page->assertPresent('@calendar-reschedule-success-toast')+ ->assertNoJavaScriptErrors();+});++test('a custom time confirmed after its time has passed sends nothing and returns the card', function () {+ [$user, $channel] = calendarDragSetup(slotTime: '09:25');+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(9, 25), mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-11");+ waitFor($page, '@calendar-custom-time-dialog');++ $later = $day->addDay()->getTimestampMs();+ $page->script(<<<JS+ (() => {+ const RealDate = Date;+ const shift = {$later} - RealDate.now();+ window.Date = class extends RealDate {+ constructor(...args) {+ super(...(args.length ? args : [RealDate.now() + shift]));+ }++ static now() {+ return RealDate.now() + shift;+ }+ };+ })()+ JS);+ $page->click('@calendar-custom-time-confirm');+ waitForGone($page, '@calendar-custom-time-dialog');+ waitForCondition($page, 'window.__announcements.length >= 2');++ expect(calendarDragAnnouncements($page))->toContain(__('calendar.reschedule.announce.returned'))+ ->and($post->refresh()->scheduled_at->equalTo($day->setTime(9, 25)))->toBeTrue()+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);+ $page->assertMissing('@calendar-reschedule-error-toast')+ ->assertNoJavaScriptErrors();+});++test('a custom time confirmed while it is still ahead keeps the time the dialog showed', function () {+ $now = now('UTC');++ if ($now->hour >= 21 || $now->minute >= 50) {+ $this->markTestSkipped('The current hour has no room for a drop five minutes out, or the post would fall on another day.');+ }++ $at = $now->addHours(2)->startOfHour()->addMinutes(25);+ [$user, $channel] = calendarDragSetup(slotTime: $at->format('H:i'));+ $key = $now->format('Y-m-d');+ $post = calendarDragPost($channel, $at, mode: ScheduleMode::Queue);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($now->startOfDay()));+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-{$now->format('H')}");+ waitFor($page, '@calendar-custom-time-dialog');+ $shown = $page->script('document.querySelector(\'[data-testid="calendar-custom-time-description"]\').innerText');++ $page->script(<<<'JS'+ (() => {+ const RealDate = Date;+ const shift = 2 * 60 * 1000;+ window.Date = class extends RealDate {+ constructor(...args) {+ super(...(args.length ? args : [RealDate.now() + shift]));+ }++ static now() {+ return RealDate.now() + shift;+ }+ };+ })()+ JS);+ $page->click('@calendar-custom-time-confirm');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $scheduledAt = $post->refresh()->scheduled_at;+ expect($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($shown)->toContain("{$scheduledAt->format('M j, g:i A')} (UTC)");+ $page->assertNoJavaScriptErrors();+});++test('a move that does not touch No Date leaves the open No Date list as it is', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script(<<<'JS'+ (() => {+ window.__partialData = [];+ const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;+ XMLHttpRequest.prototype.setRequestHeader = function (name, value) {+ if (name.toLowerCase() === 'x-inertia-partial-data') {+ window.__partialData.push(String(value));+ }++ return setRequestHeader.call(this, name, value);+ };+ })()+ JS);++ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitFor($page, '@calendar-reschedule-success-toast');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertScript("window.__partialData.length > 0 && window.__partialData.every((props) => !props.split(',').includes('undatedDrafts'))", true)+ ->assertPresent("@calendar-undated-{$draft->id}")+ ->assertNoJavaScriptErrors();+});++test('a draft already in No Date is not highlighted as a drop on the panel, is refused and nothing is sent', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $draft = calendarDragPost($channel, null, PostStatus::Draft);+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");+ calendarDragAssertLive($page, "@calendar-undated-{$draft->id}");+ calendarDragWatchAnnouncer($page);+ calendarDragHoldRequests($page);++ $highlighted = calendarGesture($page, <<<JS+ const start = center('@calendar-undated-{$draft->id}');+ await down(start);+ await move(at(start, 0, 40));+ await move(at(start, 0, 80));+ const highlighted = query('@calendar-undated-panel').hasAttribute('data-drop-over');+ await up(at(start, 0, 80));++ return highlighted;+ JS);+ waitForCondition($page, 'window.__announcements.length >= 1');++ expect($highlighted)->toBeFalse()+ ->and(calendarDragAnnouncements($page))->toContain(__('calendar.reschedule.announce.returned'))+ ->and($page->script('window.__heldRequests.length'))->toBe(0)+ ->and($draft->refresh()->scheduled_at)->toBeNull();+ $page->assertPresent("@calendar-undated-{$draft->id}")+ ->assertMissing('@calendar-reschedule-success-toast')+ ->assertNoJavaScriptErrors();+});++test('a member who needs approval takes a post off the schedule into No Date with the usual toast', function () {+ [$owner, $channel] = calendarDragSetup();+ $member = User::factory()->create(['account_id' => $owner->account_id, 'timezone' => 'UTC']);+ $channel->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $channel->workspace_id]);+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 0), attributes: ['user_id' => $member->id]);+ $this->actingAs($member);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]));+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, '@calendar-undated-empty');+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragOnto($page, "@calendar-post-{$post->id}", '@calendar-undated-panel');+ waitFor($page, '@calendar-reschedule-success-toast');+ waitFor($page, "@calendar-undated-{$post->id}");++ $page->assertSeeIn('@calendar-reschedule-success-toast', __('calendar.reschedule.toast.unscheduled'))+ ->assertMissing('@calendar-reschedule-approval-toast')+ ->assertNoJavaScriptErrors();+ $post->refresh();+ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull();+});++test('a touch press held on a post drags it into No Date', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day, ['undated' => 1]))->on()->iPadPro()->resize(1366, 1024);+ waitFor($page, "@calendar-post-{$post->id}");+ waitFor($page, '@calendar-undated-empty');+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]').scrollIntoView({ block: 'center' })");++ $held = calendarGesture($page, <<<JS+ const start = center('@calendar-post-{$post->id}');+ await down(start);+ await pause(350);+ const held = state().dragging;+ await move(center('@calendar-undated-panel'));+ await up(center('@calendar-undated-panel'));++ return held;+ JS, 'touch');+ waitFor($page, "@calendar-undated-{$post->id}");+ waitForGone($page, '@calendar-grid[aria-busy]');++ expect($held)->toBeTrue()+ ->and($post->refresh()->scheduled_at)->toBeNull()+ ->and($post->status)->toBe(PostStatus::Draft);+ $page->assertNoJavaScriptErrors();+});++test('the reload that settles a move answered after a view change never brings back the page a filter change left', function () {+ [$user, $channel] = calendarDragSetup();+ $day = calendarDragDay();+ $key = $day->format('Y-m-d');+ $post = calendarDragPost($channel, $day->setTime(10, 30));+ $this->actingAs($user);++ $page = visit(calendarDragWeekUrl($day))->resize(1600, 900);+ waitFor($page, "@calendar-post-{$post->id}");+ calendarDragAssertLive($page, "@calendar-post-{$post->id}");+ calendarDragHoldRequests($page);+ calendarDragOnto($page, "@calendar-post-{$post->id}", "@calendar-slot-{$key}-12");+ waitForCondition($page, 'window.__heldRequests.length === 1');++ $page->click('@calendar-view-trigger');+ waitFor($page, '@calendar-view-month');+ $page->click('@calendar-view-month');+ waitForPath($page, route('app.calendar', ['view' => 'month'], absolute: false));+ waitFor($page, '@calendar-month-grid');++ $page->script(<<<'JS'+ (() => {+ window.__heldGets = [];+ const open = XMLHttpRequest.prototype.open;+ const send = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.open = function (method, ...rest) {+ this.__get = method.toUpperCase() === 'GET';++ return open.call(this, method, ...rest);+ };+ XMLHttpRequest.prototype.send = function (body) {+ if (!this.__get) {+ return send.call(this, body);+ }++ window.__heldGets.push(() => send.call(this, body));+ };+ })()+ JS);+ $page->click('@calendar-status-filter');+ waitFor($page, '@calendar-status-drafts');+ $page->click('@calendar-status-drafts');+ waitForCondition($page, 'window.__heldGets.length === 1');++ $page->script('window.__heldRequests[0]()');+ waitForCondition($page, 'window.__heldGets.length === 2');++ $page->script('window.__heldGets[0]()');+ waitForCondition($page, "new URLSearchParams(location.search).get('status') === 'drafts'");+ $page->script('window.__heldGets[1]()');+ waitForGone($page, '@calendar-grid[aria-busy]');++ $page->assertScript("new URLSearchParams(location.search).get('status')", 'drafts')+ ->assertNoJavaScriptErrors();+ expect($post->refresh()->scheduled_at->equalTo($day->setTime(12, 0)))->toBeTrue();+});diff --git a/tests/Browser/CalendarPageTest.php b/tests/Browser/CalendarPageTest.phpindex ab3d56a18..920395ae0 100644--- a/tests/Browser/CalendarPageTest.php+++ b/tests/Browser/CalendarPageTest.php@@ -18,18 +18,6 @@ use App\Support\PostingSchedule;use Carbon\CarbonInterface;use Illuminate\Support\Facades\Queue;-function waitForCalendarTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}-/*** @return array{0: User, 1: SocialAccount, 2: SocialAccount}*/@@ -51,18 +39,6 @@ function calendarPageSetup(): array];}-function waitForCalendarCondition(mixed $page, string $condition): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if ({$condition}) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}-function calendarPagePost(SocialAccount $account, ?CarbonInterface $at, PostStatus $status = PostStatus::Scheduled): Post{return Post::factory()->forAccount($account)->create([@@ -72,6 +48,24 @@ function calendarPagePost(SocialAccount $account, ?CarbonInterface $at, PostStat]);}+/**+ * How many items a month day shows before "+N more", and whether the last one+ * stays above the "+N more" button inside the cell.+ */+function calendarMonthDayFits(string $dayKey): string+{+ return <<<JS+ (() => {+ const cell = document.querySelector('[data-testid="calendar-day-{$dayKey}"]').getBoundingClientRect();+ const items = [...document.querySelector('[data-testid="calendar-items-{$dayKey}"]').children];+ const last = items.at(-1).getBoundingClientRect();+ const more = document.querySelector('[data-testid="calendar-more-{$dayKey}"]').getBoundingClientRect();++ return { shown: items.length, fits: last.bottom <= more.top + 0.5 && more.bottom <= cell.bottom + 0.5 };+ })()+ JS;+}+function calendarChipSlot(mixed $page, Post $post): ?string{return $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]')?.closest('[data-testid^=\"calendar-slot-\"]')?.dataset.testid ?? null");@@ -90,7 +84,7 @@ test('the week grid places posts in their hour row, stacked as compact rows when$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));- waitForCalendarTestId($page, "calendar-post-{$first->id}");+ waitFor($page, "@calendar-post-{$first->id}");expect(calendarChipSlot($page, $first))->toBe("calendar-slot-{$dayKey}-14")->and(calendarChipSlot($page, $second))->toBe("calendar-slot-{$dayKey}-14")@@ -128,7 +122,7 @@ test('the week grid has no now line and scrolls to the current hour', function ($this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week']));- waitForCalendarTestId($page, 'calendar-time-grid');+ waitFor($page, '@calendar-time-grid');$page->assertMissing('@calendar-now-line')->assertScript(@@ -154,7 +148,7 @@ test('the calendar honours the channels filter and the display time zone', funct'channels' => [$x->id],'tz' => 'Asia/Tokyo',]))->resize(1600, 900);- waitForCalendarTestId($page, "calendar-post-{$xPost->id}");+ waitFor($page, "@calendar-post-{$xPost->id}");$page->assertMissing("@calendar-post-{$linkedinPost->id}")->assertSeeIn('@publish-timezone-select', 'Tokyo');@@ -180,17 +174,17 @@ test('an overflowing week hour expands in place', function () {$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));- waitForCalendarTestId($page, "calendar-more-{$dayKey}-11");+ waitFor($page, "@calendar-more-{$dayKey}-11");$page->assertSeeIn("@calendar-more-{$dayKey}-11", '+2')->assertMissing("@calendar-post-{$posts[3]->id}")->click("@calendar-more-{$dayKey}-11");- waitForCalendarTestId($page, "calendar-post-{$posts[3]->id}");+ waitFor($page, "@calendar-post-{$posts[3]->id}");$page->assertVisible("@calendar-post-{$posts[2]->id}")->assertVisible("@calendar-post-{$posts[3]->id}")->assertMissing("@calendar-more-{$dayKey}-11")- ->assertScript('location.pathname', parse_url(route('app.calendar', ['view' => 'week']), PHP_URL_PATH))+ ->assertScript('location.pathname', route('app.calendar', ['view' => 'week'], absolute: false))->assertNoJavaScriptErrors();});@@ -205,12 +199,12 @@ test('the status filter narrows the calendar to one kind of post', function () {$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]))->resize(1600, 900);- waitForCalendarTestId($page, "calendar-post-{$scheduled->id}");+ waitFor($page, "@calendar-post-{$scheduled->id}");$page->assertSeeIn('@calendar-status-filter', 'All posts')->click('@calendar-status-filter');- waitForCalendarTestId($page, 'calendar-status-drafts');+ waitFor($page, '@calendar-status-drafts');$page->click('@calendar-status-drafts');- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-{$scheduled->id}\"]')");+ waitForGone($page, "@calendar-post-{$scheduled->id}");$page->assertMissing("@calendar-post-{$scheduled->id}")->assertVisible("@calendar-post-{$draft->id}")@@ -226,7 +220,7 @@ test('the no date panel slides open and closed, pushing the calendar aside gradu$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month']))->resize(1280, 900);- waitForCalendarTestId($page, 'calendar-no-date');+ waitFor($page, '@calendar-no-date');$sample = fn (int $settled): string => <<<JS(async () => {@@ -252,6 +246,25 @@ test('the no date panel slides open and closed, pushing the calendar aside gradu$page->assertMissing('@calendar-undated-panel')->assertNoJavaScriptErrors();});+test('an undated draft without a channel says so in the language of the user and has no drag hint', function () {+ [$user, $linkedin] = calendarPageSetup();+ $user->update(['locale' => Locale::PortugueseBrazil]);+ $draft = Post::factory()->draft()->create([+ 'workspace_id' => $linkedin->workspace_id,+ 'user_id' => $user->id,+ 'scheduled_at' => null,+ ]);++ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'undated' => 1]));+ waitFor($page, "@calendar-undated-{$draft->id}");++ $page->assertSeeIn("@calendar-undated-{$draft->id}", 'Sem canal')+ ->assertMissing("@calendar-drag-hint-{$draft->id}")+ ->assertNoJavaScriptErrors();+});+test('the no date panel lists undated drafts and a card opens the composer', function () {[$user, $linkedin, $x] = calendarPageSetup();$undated = calendarPagePost($linkedin, null, PostStatus::Draft);@@ -260,12 +273,12 @@ test('the no date panel lists undated drafts and a card opens the composer', fun$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month']));- waitForCalendarTestId($page, 'calendar-no-date');+ waitFor($page, '@calendar-no-date');$page->assertMissing('@calendar-undated-panel')->assertPresent('@calendar-no-date-icon-closed')->assertMissing('@calendar-no-date-icon-open')->click('@calendar-no-date');- waitForCalendarTestId($page, "calendar-undated-{$undated->id}");+ waitFor($page, "@calendar-undated-{$undated->id}");$page->assertVisible('@calendar-undated-panel')->assertPresent('@calendar-no-date-icon-open')@@ -275,13 +288,13 @@ test('the no date panel lists undated drafts and a card opens the composer', fun->assertAttribute('@calendar-no-date', 'aria-pressed', 'true')->assertScript('new URLSearchParams(location.search).get("undated")', '1')->click('@calendar-undated-close');- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-undated-panel\"]')");+ waitForGone($page, '@calendar-undated-panel');$page->assertMissing('@calendar-undated-panel')->click('@calendar-no-date');- waitForCalendarTestId($page, "calendar-undated-{$undated->id}");+ waitFor($page, "@calendar-undated-{$undated->id}");$page->click("@calendar-undated-{$undated->id}");- waitForCalendarTestId($page, 'post-composer-dialog');+ waitFor($page, '@post-composer-dialog');$page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();@@ -306,7 +319,7 @@ test('show posting times renders empty slots in the week and month views', funct$page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));$page->script('window.localStorage.clear()');$page->refresh();- waitForCalendarTestId($page, "calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-posting-slot-{$slotKey}");expect($page->script("(() => { const chip = document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]'); return [chip.querySelector('svg[data-testid=\"calendar-posting-slot-icon-{$slotKey}\"]') !== null, chip.querySelector('img') === null]; })()"))->toBe([true, true]);@@ -319,20 +332,36 @@ test('show posting times renders empty slots in the week and month views', functexpect($page->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').closest('[data-testid^=\"calendar-slot-\"]').dataset.testid"))->toBe("calendar-slot-{$day->format('Y-m-d')}-15");+ $page->script(<<<'JS'+ (() => {+ window.__partialData = [];+ const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;+ XMLHttpRequest.prototype.setRequestHeader = function (name, value) {+ if (name.toLowerCase() === 'x-inertia-partial-data') {+ window.__partialData.push(String(value));+ }++ return setRequestHeader.call(this, name, value);+ };+ })()+ JS);$page->click('@calendar-menu');- waitForCalendarTestId($page, 'calendar-toggle-slots');+ waitFor($page, '@calendar-toggle-slots');$page->click('@calendar-toggle-slots');- waitForCalendarCondition($page, "!document.querySelector('[data-testid^=\"calendar-posting-slot-\"]')");+ waitForGone($page, '[data-testid^="calendar-posting-slot-"]');+ waitForCondition($page, "!new URLSearchParams(location.search).has('slots')");$page->assertMissing("@calendar-posting-slot-{$slotKey}")- ->assertScript('window.localStorage.getItem("publish.showSlots")', 'false');+ ->assertScript('window.localStorage.getItem("publish.showSlots")', 'false')+ ->assertScript("new URLSearchParams(location.search).has('slots')", false)+ ->assertScript("window.__partialData.every((only) => !only.split(',').includes('slots'))", true);$page->refresh();- waitForCalendarTestId($page, "calendar-slot-{$day->format('Y-m-d')}-15");+ waitFor($page, "@calendar-slot-{$day->format('Y-m-d')}-15");$page->assertMissing("@calendar-posting-slot-{$slotKey}");$month = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]));- waitForCalendarTestId($month, "calendar-posting-slot-{$slotKey}");+ waitFor($month, "@calendar-posting-slot-{$slotKey}");expect($month->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').closest('[data-testid^=\"calendar-day-\"]').dataset.testid"))->toBe("calendar-day-{$day->format('Y-m-d')}");@@ -340,14 +369,14 @@ test('show posting times renders empty slots in the week and month views', funct$month->hover("@calendar-posting-slot-{$slotKey}");$month->assertSeeIn("@calendar-posting-slot-{$slotKey}", __('posts.publish.add_post_in_slot'))->click("@calendar-posting-slot-{$slotKey}");- waitForCalendarTestId($month, "composer-caption-{$linkedin->id}");+ waitFor($month, "@composer-caption-{$linkedin->id}");$month->fill("@composer-caption-{$linkedin->id}", 'From a calendar slot');- waitForCalendarTestId($month, 'composer-submit');+ waitFor($month, '@composer-submit');expect($month->script('document.querySelector(\'[data-testid="composer-submit"]\').dataset.scheduleMode'))->toBe('custom');$month->click('@composer-submit');- waitForCalendarCondition($month, '!document.querySelector(\'[data-testid="post-composer-dialog"]\')');+ waitForGone($month, '@post-composer-dialog');$post = Post::query()->where('workspace_id', $linkedin->workspace_id)->sole();expect($post->scheduled_at->equalTo($day->copy()->setTime(15, 0)))->toBeTrue()@@ -355,64 +384,110 @@ test('show posting times renders empty slots in the week and month views', funct$month->assertNoJavaScriptErrors();});-test('clicking a scheduled post chip in the month view opens its timeline card in a popover', function () {+test('in the month a post shows its network in color and a status icon with a tooltip, and a free posting time reads as a hatched empty slot', function () {[$user, $linkedin] = calendarPageSetup();- $at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0);- $post = calendarPagePost($linkedin, $at);- $post->update(['content' => '<p>Popover caption</p>']);+ $schedule = PostingSchedule::empty();++ foreach (range(0, 6) as $weekday) {+ $schedule = $schedule->withTime($weekday, '18:00');+ }++ $linkedin->update(['posting_schedule' => $schedule]);++ $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(9);+ $scheduled = calendarPagePost($linkedin, $day->copy()->setTime(15, 0));+ $scheduled->update(['content' => '<p>Launch recap</p>']);+ $draft = calendarPagePost($linkedin, $day->copy()->setTime(10, 0), PostStatus::Draft);+ $pending = calendarPagePost($linkedin, $day->copy()->addDay()->setTime(12, 0), PostStatus::PendingApproval);+ $failed = calendarPagePost($linkedin, $day->copy()->addDays(2)->setTime(13, 0), PostStatus::Failed);+ $slotKey = "{$linkedin->id}-{$day->copy()->setTime(18, 0)->getTimestamp()}";$this->actingAs($user);- $page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]));- waitForCalendarTestId($page, "calendar-post-{$post->id}");+ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d'), 'slots' => 1]))->resize(1440, 900);+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@calendar-post-{$scheduled->id}");- expect($page->script("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]'); return [chip.tagName.toLowerCase(), chip.querySelector('svg') !== null, chip.querySelector('img') === null]; })()"))- ->toBe(['button', true, true]);+ $page->assertDontSeeIn("@calendar-post-{$scheduled->id}", 'Launch recap')+ ->assertPresent("@calendar-post-draft-{$draft->id}")+ ->assertPresent("@calendar-post-pending-{$pending->id}")+ ->assertPresent("@calendar-post-failed-{$failed->id}")+ ->assertMissing("@calendar-post-pending-{$scheduled->id}")+ ->assertMissing("@calendar-post-failed-{$scheduled->id}");- $page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "calendar-post-popover-{$post->id}");+ $styles = $page->script(<<<JS+ (() => {+ const chip = (id) => document.querySelector('[data-testid="' + id + '"]');+ const style = (id) => getComputedStyle(chip(id));- $page->assertPresent("[data-testid=\"calendar-post-popover-{$post->id}\"] [data-testid=\"post-card-{$post->id}\"]")- ->assertSeeIn("@calendar-post-popover-{$post->id}", 'Popover caption')- ->assertPresent("@post-edit-{$post->id}")- ->assertPresent("@post-publish-now-{$post->id}");+ return {+ postIcon: getComputedStyle(chip('calendar-post-platform-{$scheduled->id}')).color,+ draftIcon: getComputedStyle(chip('calendar-post-platform-{$draft->id}')).color,+ draftBorder: style('calendar-post-{$draft->id}').borderStyle,+ slotBorder: style('calendar-posting-slot-{$slotKey}').borderStyle,+ slotHatched: style('calendar-posting-slot-{$slotKey}').backgroundImage.startsWith('linear-gradient'),+ slotIcons: chip('calendar-posting-slot-{$slotKey}').querySelectorAll('svg').length,+ failedChipLooksScheduled: ['borderColor', 'backgroundColor'].every((key) => style('calendar-post-{$failed->id}')[key] === style('calendar-post-{$scheduled->id}')[key]),+ failedIconColored: style('calendar-post-failed-{$failed->id}').color !== style('post-schedule-mode-{$scheduled->id}').color,+ pendingIconMuted: style('calendar-post-pending-{$pending->id}').color === style('post-schedule-mode-{$scheduled->id}').color,+ };+ })()+ JS);- $page->keys("@calendar-post-popover-{$post->id}", 'Escape');- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-popover-{$post->id}\"]')");+ expect($styles)->toMatchArray([+ 'postIcon' => 'rgb(10, 102, 194)',+ 'draftBorder' => 'solid',+ 'slotBorder' => 'dashed',+ 'slotHatched' => true,+ 'slotIcons' => 1,+ 'draftIcon' => 'rgb(10, 102, 194)',+ 'failedChipLooksScheduled' => true,+ 'failedIconColored' => true,+ 'pendingIconMuted' => true,+ ]);- $page->assertMissing("@calendar-post-popover-{$post->id}");- expect($page->script('document.activeElement?.dataset.testid'))->toBe("calendar-post-{$post->id}");+ $page->hover("@calendar-post-pending-{$pending->id}");+ waitForText($page, '[data-slot="tooltip-content"]', __('calendar.post_status.pending_approval'));+ $page->assertSee(__('calendar.post_status.pending_approval'));- $page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "calendar-post-overlay-{$post->id}");+ $page->assertNoJavaScriptErrors();+});- $page->assertVisible("@calendar-post-overlay-{$post->id}");- $page->script("document.querySelector('[data-testid=\"calendar-post-overlay-{$post->id}\"]').dispatchEvent(new PointerEvent('pointerdown', {bubbles: true, pointerType: 'mouse'}))");- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-popover-{$post->id}\"]')");+test('clicking a scheduled post chip in the month view opens its details', function () {+ [$user, $linkedin] = calendarPageSetup();+ $at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0);+ $post = calendarPagePost($linkedin, $at);+ $post->update(['content' => '<p>Details caption</p>']);- $page->assertMissing("@calendar-post-popover-{$post->id}");+ $this->actingAs($user);- $page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "post-details-expand-{$post->id}");+ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]));+ waitFor($page, "@calendar-post-{$post->id}");- $page->script("document.querySelector('[data-testid=\"post-card-menu-{$post->id}\"]').dispatchEvent(new PointerEvent('pointermove', {bubbles: true, pointerType: 'mouse'}))");- waitForCalendarTestId($page, "post-card-menu-tooltip-{$post->id}");- $page->assertSeeIn("@post-card-menu-tooltip-{$post->id}", __('posts.publish.actions.more'));+ $page->assertAttribute("@calendar-post-{$post->id}", 'type', 'button')+ ->assertPresent("@calendar-post-platform-{$post->id}")+ ->assertMissing("@calendar-post-thumbnail-{$post->id}")+ ->assertMissing("@post-card-{$post->id}");- $page->click("@post-details-expand-{$post->id}");- waitForCalendarTestId($page, "post-details-{$post->id}");+ $page->click("@calendar-post-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");$page->assertVisible("@post-details-{$post->id}")- ->assertMissing("@calendar-post-popover-{$post->id}");+ ->assertSeeIn("@post-details-{$post->id}", 'Details caption')+ ->assertPresent("@post-details-edit-{$post->id}")+ ->assertPresent("@post-details-publish-now-{$post->id}");$page->keys("@post-details-{$post->id}", 'Escape');- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"post-details-{$post->id}\"]') && !document.querySelector('[data-testid=\"calendar-post-popover-{$post->id}\"]')");+ waitForGone($page, "@post-details-{$post->id}");+ expect($page->script('document.activeElement?.dataset.testid'))->toBe("calendar-post-{$post->id}");- expect($page->script("document.querySelector('[data-testid=\"calendar-post-popover-{$post->id}\"]') === null"))->toBeTrue();- $page->assertNoJavaScriptErrors();+ $page->click("@calendar-post-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");+ $page->assertVisible("@post-details-{$post->id}")+ ->assertNoJavaScriptErrors();});-test('a published post popover shows its metrics, go to post and the sent menu', function () {+test('a published post opens details with its metrics, go to post and the sent menu', function () {Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);[$user] = calendarPageSetup();$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $user->current_workspace_id, 'timezone' => 'UTC']);@@ -442,30 +517,20 @@ test('a published post popover shows its metrics, go to post and the sent menu',$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month']));- waitForCalendarTestId($page, "calendar-post-{$post->id}");+ waitFor($page, "@calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "calendar-post-popover-{$post->id}");-- $page->assertPresent("[data-testid=\"calendar-post-popover-{$post->id}\"] [data-testid=\"post-metrics-{$post->id}\"]")- ->assertPresent("@post-view-{$post->id}")- ->assertMissing("@post-edit-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");- $page->script("document.querySelector('[data-testid=\"post-view-{$post->id}\"]').dispatchEvent(new PointerEvent('pointermove', {bubbles: true, pointerType: 'mouse'}))");- waitForCalendarTestId($page, "post-view-tooltip-{$post->id}");- $page->assertSeeIn("@post-view-tooltip-{$post->id}", __('posts.publish.actions.open_on_network', ['network' => 'Instagram']));+ $page->assertPresent("@post-details-metrics-{$post->id}")+ ->assertPresent("@post-details-view-{$post->id}")+ ->assertMissing("@post-details-edit-{$post->id}");- $page->click("@post-card-menu-{$post->id}");- waitForCalendarTestId($page, "post-card-menu-content-{$post->id}");+ $page->click("@post-card-menu-details-{$post->id}");+ waitFor($page, "@post-card-menu-content-details-{$post->id}");- expect($page->script("Array.from(document.querySelectorAll('[data-testid=\"post-card-menu-content-{$post->id}\"] [role=\"menuitem\"]')).map((element) => element.dataset.testid)"))- ->toBe(["post-duplicate-{$post->id}", "post-details-open-{$post->id}", "post-share-link-{$post->id}", "post-copy-link-{$post->id}"]);-- $page->click("@post-details-open-{$post->id}");- waitForCalendarTestId($page, "post-details-{$post->id}");-- $page->assertVisible("@post-details-{$post->id}")- ->assertMissing("@calendar-post-popover-{$post->id}")- ->assertNoJavaScriptErrors();+ expect($page->script("Array.from(document.querySelectorAll('[data-testid=\"post-card-menu-content-details-{$post->id}\"] [role=\"menuitem\"]')).map((element) => element.dataset.testid)"))+ ->toBe(["post-duplicate-details-{$post->id}", "post-share-link-details-{$post->id}", "post-copy-link-details-{$post->id}"]);+ $page->assertNoJavaScriptErrors();});test('an overflowing month day expands and collapses back, scrolling inside its cell', function () {@@ -478,15 +543,16 @@ test('an overflowing month day expands and collapses back, scrolling inside its$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]))->resize(1440, 900);- waitForCalendarTestId($page, "calendar-more-{$dayKey}");+ waitFor($page, "@calendar-more-{$dayKey}");$cellHeight = "document.querySelector('[data-testid=\"calendar-day-{$dayKey}\"]').getBoundingClientRect().height";$heightBefore = $page->script($cellHeight);+ expect($page->script(calendarMonthDayFits($dayKey)))->toBe(['shown' => 4, 'fits' => true]);- $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 7]))+ $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 6]))->assertMissing("@calendar-post-{$last->id}")->click("@calendar-more-{$dayKey}");- waitForCalendarTestId($page, "calendar-post-{$last->id}");+ waitFor($page, "@calendar-post-{$last->id}");$layout = $page->script(<<<JS(() => {@@ -506,14 +572,14 @@ test('an overflowing month day expands and collapses back, scrolling inside its$page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.less'))->click("@calendar-more-{$dayKey}");- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-{$last->id}\"]')");+ waitForGone($page, "@calendar-post-{$last->id}");$page->assertMissing("@calendar-post-{$last->id}")- ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 7]))+ ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 6]))->assertNoJavaScriptErrors();});-test('a popover action reloads the calendar and closes the popover', function () {+test('a details action reloads the calendar and the details show the new status', function () {[$user, $linkedin] = calendarPageSetup();$at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0);$post = calendarPagePost($linkedin, $at);@@ -521,18 +587,21 @@ test('a popover action reloads the calendar and closes the popover', function ()$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]));- waitForCalendarTestId($page, "calendar-post-{$post->id}");+ waitFor($page, "@calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "post-card-menu-{$post->id}");- $page->click("@post-card-menu-{$post->id}");- waitForCalendarTestId($page, "post-move-drafts-{$post->id}");- $page->click("@post-move-drafts-{$post->id}");- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-popover-{$post->id}\"]')");-- $page->assertMissing("@calendar-post-popover-{$post->id}")- ->assertVisible("@calendar-post-{$post->id}")- ->assertNoJavaScriptErrors();+ waitFor($page, "@post-card-menu-details-{$post->id}");+ $page->click("@post-card-menu-details-{$post->id}");+ waitFor($page, "@post-move-drafts-details-{$post->id}");+ $page->click("@post-move-drafts-details-{$post->id}");+ waitForText($page, "@post-details-status-{$post->id}", __('posts.status.draft'));+ waitFor($page, "@calendar-post-draft-{$post->id}");+expect($post->refresh()->status)->toBe(PostStatus::Draft);++ $page->keys("@post-details-{$post->id}", 'Escape');+ waitForGone($page, "@post-details-{$post->id}");+ $page->assertVisible("@calendar-post-{$post->id}")+ ->assertNoJavaScriptErrors();});test('on a phone the week shows its seven days in columns with their posts', function () {@@ -544,14 +613,14 @@ test('on a phone the week shows its seven days in columns with their posts', fun$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]))->resize(390, 844);- waitForCalendarTestId($page, 'calendar-time-grid');+ waitFor($page, '@calendar-time-grid');expect($page->script('document.querySelectorAll(\'[data-testid^="calendar-column-"]\').length'))->toBe(7);expect($page->script('[...document.querySelectorAll(\'[data-testid^="calendar-add-"]\')].every((button) => button.getBoundingClientRect().width === 0)'))->toBeTrue();$page->assertPresent("@calendar-post-{$first->id}")->assertPresent("@calendar-post-{$second->id}")- ->assertScript("(() => { const box = document.querySelector('[data-testid=\"calendar-post-{$first->id}\"]').getBoundingClientRect(); return box.width === box.height; })()", true)+ ->assertScript("(() => { const box = document.querySelector('[data-testid=\"calendar-post-{$first->id}\"]').getBoundingClientRect(); return box.height === 28 && box.width >= box.height; })()", true)->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)->assertNoJavaScriptErrors();});@@ -564,7 +633,7 @@ test('the three days view shows three columns, and only the phone picker offers$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'days', 'day' => $day->format('Y-m-d')]))->resize(390, 844);- waitForCalendarTestId($page, 'calendar-time-grid');+ waitFor($page, '@calendar-time-grid');expect($page->script('[...document.querySelectorAll(\'[data-testid^="calendar-column-"]\')].map((el) => el.dataset.testid)'))->toBe(collect(range(0, 2))->map(fn (int $offset): string => "calendar-column-{$day->copy()->addDays($offset)->format('Y-m-d')}")->all());@@ -574,20 +643,40 @@ test('the three days view shows three columns, and only the phone picker offers->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true);$page->resize(1280, 900);- waitForCalendarTestId($page, 'calendar-view-trigger');+ waitFor($page, '@calendar-view-trigger');$page->assertSeeIn('@calendar-view-trigger', __('calendar.days'))->click('@calendar-view-trigger');- waitForCalendarTestId($page, 'calendar-view-week');+ waitFor($page, '@calendar-view-week');$page->assertPresent('@calendar-view-month')->assertMissing('@calendar-view-days')->keys('@calendar-view-week', 'Escape');- waitForCalendarCondition($page, '!document.querySelector(\'[data-testid="calendar-view-week"]\')');+ waitForGone($page, '@calendar-view-week');$page->click('@calendar-next');- waitForCalendarCondition($page, "new URLSearchParams(location.search).get('day') === '{$day->copy()->addDays(3)->format('Y-m-d')}'");+ waitForCondition($page, "new URLSearchParams(location.search).get('day') === '{$day->copy()->addDays(3)->format('Y-m-d')}'");$page->assertMissing("@calendar-post-{$post->id}")->assertNoJavaScriptErrors();});+test('on a phone the calendar tab of the view switch keeps the three days view, on a desktop it opens the month', function () {+ [$user] = calendarPageSetup();++ $this->actingAs($user);++ $calendarTabPath = 'new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname';++ $page = visit(route('app.calendar', ['view' => 'days']))->resize(390, 844);+ waitFor($page, '@schedule-view-calendar');+ $page->assertScript($calendarTabPath, route('app.calendar', ['view' => 'days'], false))+ ->click('@schedule-view-calendar');+ waitFor($page, '@calendar-time-grid');+ $page->assertPathIs(route('app.calendar', ['view' => 'days'], false));++ $page->resize(1280, 900);+ waitForState($page, '@schedule-view-calendar', 'new URL(element.href).pathname.endsWith("/month")');+ $page->assertScript($calendarTabPath, route('app.calendar', ['view' => 'month'], false))+ ->assertNoJavaScriptErrors();+});+test('on a phone the month shows its weeks in columns with the posts of each day as icon tiles', function () {[$user, $linkedin, $x] = calendarPageSetup();$day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(12);@@ -597,18 +686,19 @@ test('on a phone the month shows its weeks in columns with the posts of each day$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]))->resize(390, 844);- waitForCalendarTestId($page, 'calendar-month-grid');+ waitFor($page, '@calendar-month-grid');$page->assertPresent("@calendar-day-{$dayKey}")->assertPresent("@calendar-post-{$posts[0]->id}")->assertSeeIn("@calendar-more-{$dayKey}", '+2')->assertDontSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 2]))- ->assertScript("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$posts[0]->id}\"]'); const box = chip.getBoundingClientRect(); return box.width === box.height && chip.innerText.trim() === '' && !chip.querySelector('img, video'); })()", true)+ ->assertScript(calendarMonthDayFits($dayKey), ['shown' => 3, 'fits' => true])+ ->assertScript("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$posts[0]->id}\"]'); const box = chip.getBoundingClientRect(); return box.height === 28 && box.width >= box.height && chip.innerText.trim() === '' && !chip.querySelector('img, video'); })()", true)->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)->assertNoJavaScriptErrors();$page->click("@calendar-more-{$dayKey}");- waitForCalendarTestId($page, "calendar-post-{$posts[4]->id}");+ waitFor($page, "@calendar-post-{$posts[4]->id}");$page->assertAttribute("@calendar-more-{$dayKey}", 'aria-label', __('calendar.less'));});@@ -620,12 +710,11 @@ test('on a phone, tapping a post in the month opens its details directly', funct$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]))->resize(390, 844);- waitForCalendarTestId($page, "calendar-post-{$post->id}");+ waitFor($page, "@calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");- waitForCalendarTestId($page, "post-details-{$post->id}");+ waitFor($page, "@post-details-{$post->id}");$page->assertVisible("@post-details-{$post->id}")- ->assertMissing("@calendar-post-popover-{$post->id}")->assertNoJavaScriptErrors();});@@ -635,7 +724,7 @@ test('in Portuguese the week columns show one-word weekday names', function () {$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week']))->resize(1280, 900);- waitForCalendarTestId($page, 'calendar-time-grid');+ waitFor($page, '@calendar-time-grid');$names = $page->script('[...document.querySelectorAll(\'[data-testid^="calendar-column-"] span:first-child\')].map((el) => el.textContent.trim().toLowerCase())');@@ -652,38 +741,38 @@ test('on a phone the period picker opens from the bottom, switches the view in p$shownWeek = now()->addYear()->setDate(now()->addYear()->year, 3, 1)->toDateString();$pickedDay = now()->addYear()->setDate(now()->addYear()->year, 3, 17);$page = visit(route('app.calendar', ['view' => 'week', 'week' => $shownWeek]))->resize(390, 844);- waitForCalendarTestId($page, 'calendar-period-trigger');+ waitFor($page, '@calendar-period-trigger');expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-previous"]\'))'))->toBeFalse();$page->click('@calendar-period-trigger');- waitForCalendarTestId($page, 'calendar-period-calendar');- waitForCalendarCondition($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="calendar-period-picker"]\').getBoundingClientRect().bottom) <= 1');+ waitFor($page, '@calendar-period-calendar');+ waitForState($page, '@calendar-period-picker', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');$page->assertVisible('@calendar-view-days')->click("[data-testid=\"calendar-period-calendar\"] [data-testid=\"calendar-date-{$pickedDay->toDateString()}\"]");- waitForCalendarCondition($page, "new URLSearchParams(location.search).get(\"week\") !== \"{$shownWeek}\"");+ waitForCondition($page, "new URLSearchParams(location.search).get(\"week\") !== \"{$shownWeek}\"");$week = $page->script('new URLSearchParams(location.search).get("week")');expect($week >= $pickedDay->subDays(6)->toDateString() && $week <= $pickedDay->toDateString())->toBeTrue();- waitForCalendarCondition($page, '!document.querySelector(\'[data-testid="calendar-period-picker"]\')');+ waitForGone($page, '@calendar-period-picker');$page->assertMissing('@calendar-period-picker');$page->click('@calendar-period-trigger');- waitForCalendarTestId($page, 'calendar-view-month');+ waitFor($page, '@calendar-view-month');$page->click('@calendar-view-month');- waitForCalendarCondition($page, 'location.pathname.endsWith("/month")');+ waitForCondition($page, 'location.pathname.endsWith("/month")');expect($page->script('location.pathname.endsWith("/month")'))->toBeTrue();$page->assertVisible('@calendar-period-calendar')->assertAttribute('@calendar-view-month', 'aria-pressed', 'true')->click('@calendar-today');- waitForCalendarCondition($page, '!document.querySelector(\'[data-testid="calendar-period-picker"]\')');+ waitForGone($page, '@calendar-period-picker');$page->assertMissing('@calendar-period-picker')->assertNoJavaScriptErrors();$page->resize(1280, 900);- waitForCalendarTestId($page, 'calendar-previous');+ waitFor($page, '@calendar-previous');$page->assertVisible('@calendar-next')->assertVisible('@calendar-view-trigger');});@@ -692,9 +781,40 @@ test('the previous period arrow starts on the same line as the calendar', functi$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week']))->resize(1440, 900);- waitForCalendarTestId($page, 'calendar-time-grid');+ waitFor($page, '@calendar-time-grid');expect($page->script("Math.round(document.querySelector('[data-testid=\"calendar-previous\"]').getBoundingClientRect().left)"))->toBe($page->script("Math.round(document.querySelector('[data-testid=\"calendar-grid\"]').getBoundingClientRect().left)"));$page->assertNoJavaScriptErrors();});++test('on a phone the month chips show each post\'s status icon and fit their day', function () {+ [$user, $linkedin] = calendarPageSetup();+ $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10);+ $draft = calendarPagePost($linkedin, $day->setTime(9, 0), PostStatus::Draft);+ $failed = calendarPagePost($linkedin, $day->setTime(11, 0), PostStatus::Failed);+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]))->resize(390, 844);+ waitFor($page, "@calendar-post-{$draft->id}");++ $page->assertPresent("@calendar-post-draft-{$draft->id}")+ ->assertPresent("@calendar-post-failed-{$failed->id}");+ expect($page->script("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$draft->id}\"]'); const day = document.querySelector('[data-testid=\"calendar-day-{$day->format('Y-m-d')}\"]'); return chip.getBoundingClientRect().right <= day.getBoundingClientRect().right; })()"))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('hiding posting times keeps the page address in the form the server answers with', function () {+ [$user] = calendarPageSetup();+ $week = now('UTC')->addWeek()->startOfWeek()->format('Y-m-d');+ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'week', 'week' => $week, 'undated' => 1, 'slots' => 1]));+ $page->click('@calendar-menu');+ waitFor($page, '@calendar-toggle-slots');+ $page->click('@calendar-toggle-slots');+ waitForCondition($page, "!new URLSearchParams(location.search).has('slots')");++ $page->assertScript('location.search', "?undated=1&week={$week}")+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/ChannelMetricsCardTest.php b/tests/Browser/ChannelMetricsCardTest.phpindex 216810530..260148955 100644--- a/tests/Browser/ChannelMetricsCardTest.php+++ b/tests/Browser/ChannelMetricsCardTest.php@@ -91,7 +91,7 @@ beforeEach(function () {]);$today = CarbonImmutable::today('UTC');- foreach (range(0, 59) as $daysAgo) {+ foreach (range(0, 94) as $daysAgo) {metricsCardFollowers($this->instagram, $today->subDays($daysAgo), 3000 + (60 - $daysAgo) * 5);}diff --git a/tests/Browser/ComposerReturnPageTest.php b/tests/Browser/ComposerReturnPageTest.phpnew file mode 100644index 000000000..dc82214cb--- /dev/null+++ b/tests/Browser/ComposerReturnPageTest.php@@ -0,0 +1,98 @@+<?php++declare(strict_types=1);++use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Support\PostingSchedule;+use Illuminate\Support\Arr;+use Illuminate\Support\Uri;++function composerReturnPageChannel(): SocialAccount+{+ $user = User::factory()->create(['timezone' => 'UTC']);+ $workspace = Workspace::factory()->create([+ 'user_id' => $user->id,+ 'account_id' => $user->account_id,+ ]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ $schedule = PostingSchedule::empty();++ foreach (range(0, 6) as $weekday) {+ $schedule = $schedule->withTime($weekday, '15:00');+ }++ test()->actingAs($user);++ return SocialAccount::factory()->linkedin()->create([+ 'workspace_id' => $workspace->id,+ 'timezone' => 'UTC',+ 'posting_schedule' => $schedule,+ ]);+}++function assertComposerReturnedTo(mixed $page, string $url): void+{+ $uri = Uri::of($url);+ $query = $uri->query()->all();+ ksort($query);+ $sortedSearch = "[...new URLSearchParams(window.location.search)].sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `\${key}=\${value}`).join('&')";+ $expected = Arr::query($query);++ waitForGone($page, '@post-composer-dialog');+ waitForCondition($page, "{$sortedSearch} === ".json_encode($expected));++ $page->assertPathIs("/{$uri->path()}")+ ->assertScript($sortedSearch, $expected)+ ->assertNoJavaScriptErrors();+}++test('scheduling a post from a free calendar slot stays on the calendar as it was', function (string $view, string $period) {+ $channel = composerReturnPageChannel();+ $day = now('UTC')->startOfWeek()->addWeek()->addDays(2);+ $slotKey = "{$channel->id}-{$day->copy()->setTime(15, 0)->getTimestamp()}";+ $calendar = route('app.calendar', ['view' => $view, $period => $day->format('Y-m-d'), 'slots' => 1]);++ $page = visit($calendar)->resize(1280, 900);+ waitFor($page, "@calendar-posting-slot-{$slotKey}");+ $page->hover("@calendar-posting-slot-{$slotKey}")+ ->click("@calendar-posting-slot-{$slotKey}");+ waitFor($page, "@composer-caption-{$channel->id}");+ $page->fill("@composer-caption-{$channel->id}", 'From a calendar slot');+ waitFor($page, '@composer-submit');+ $page->click('@composer-submit');++ assertComposerReturnedTo($page, $calendar);+ expect(Post::query()->where('social_account_id', $channel->id)->sole()->scheduled_at->equalTo($day->copy()->setTime(15, 0)))->toBeTrue();+})->with([+ 'week' => ['week', 'week'],+ 'month' => ['month', 'month'],+]);++test('a post started from the sidebar stays on the page it was started from', function (string $origin) {+ $channel = composerReturnPageChannel();+ $url = match ($origin) {+ 'app.channels.calendar' => route($origin, ['account' => $channel, 'view' => 'week', 'slots' => 1]),+ default => route($origin),+ };++ $page = visit($url)->resize(1280, 900);+ waitFor($page, "@sidebar-channel-row-{$channel->id}");+ $page->hover("@sidebar-channel-row-{$channel->id}")+ ->click("@sidebar-channel-{$channel->id}-new-post");+ waitFor($page, "@composer-caption-{$channel->id}");+ $page->fill("@composer-caption-{$channel->id}", 'From the sidebar');+ waitFor($page, '@composer-save-draft');+ $page->click('@composer-save-draft');++ assertComposerReturnedTo($page, $url);+ expect(Post::query()->where('social_account_id', $channel->id)->sole()->content)->toContain('From the sidebar');+})->with([+ 'the channel calendar' => ['app.channels.calendar'],+ 'insights' => ['app.insights'],+]);diff --git a/tests/Browser/ComposerSharedDataTest.php b/tests/Browser/ComposerSharedDataTest.phpindex daf44ea20..2450a48d2 100644--- a/tests/Browser/ComposerSharedDataTest.php+++ b/tests/Browser/ComposerSharedDataTest.php@@ -103,8 +103,8 @@ test('editing from the calendar opens the post with its board', function () {$page = visit(route('app.calendar', ['view' => 'month', 'month' => $post->scheduled_at->format('Y-m-d')]));waitForComposerSharedDataTestId($page, "calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");- waitForComposerSharedDataTestId($page, "post-edit-{$post->id}");- $page->click("@post-edit-{$post->id}");+ waitForComposerSharedDataTestId($page, "post-details-edit-{$post->id}");+ $page->click("@post-details-edit-{$post->id}");waitForComposerSharedDataTestId($page, 'pinterest-board-selected');$page->assertSeeIn('@pinterest-board-selected', 'Live board')@@ -113,13 +113,14 @@ test('editing from the calendar opens the post with its board', function () {function clickComposerSharedDataNewPost(mixed $page): void{- $item = "document.querySelector('[data-testid=\"sidebar-new-post\"]')?.getBoundingClientRect().height > 0";+ $menuOpen = "Boolean(document.querySelector('[data-testid=\"sidebar-new-menu\"][data-state=\"open\"]'))";- for ($attempt = 0; $attempt < 3 && ! $page->script("Boolean({$item})"); $attempt++) {+ for ($attempt = 0; $attempt < 3 && ! $page->script($menuOpen); $attempt++) {$page->click('@sidebar-new');- waitForComposerSharedDataCondition($page, $item);+ waitForCondition($page, $menuOpen);}+ waitFor($page, '@sidebar-new-post');$page->click('@sidebar-new-post');}diff --git a/tests/Browser/ComposerUnsavedChangesTest.php b/tests/Browser/ComposerUnsavedChangesTest.phpindex dd95f11bb..13fb5d32c 100644--- a/tests/Browser/ComposerUnsavedChangesTest.php+++ b/tests/Browser/ComposerUnsavedChangesTest.php@@ -175,12 +175,13 @@ test('after saving a post edited from the calendar, a channel drafts tab or the$before = (string) parse_url(route('app.settings.preferences'), PHP_URL_PATH);$page = visit(route('app.settings.preferences'))->resize(1280, 900)->navigate($list);+ $edit = $from === 'calendar' ? "@post-details-edit-{$post->id}" : "@post-edit-{$post->id}";if ($from === 'calendar') {waitFor($page, "@calendar-post-{$post->id}");$page->click("@calendar-post-{$post->id}");}- waitFor($page, "@post-edit-{$post->id}");- $page->click("@post-edit-{$post->id}");+ waitFor($page, $edit);+ $page->click($edit);waitFor($page, '@instagram-share-to-feed');$page->click('@instagram-share-to-feed')diff --git a/tests/Browser/PostCardLabelsTest.php b/tests/Browser/PostCardLabelsTest.phpindex cba0fe6f1..8df20e3dc 100644--- a/tests/Browser/PostCardLabelsTest.php+++ b/tests/Browser/PostCardLabelsTest.php@@ -11,28 +11,6 @@ use App\Models\Workspace;use App\Models\WorkspaceLabel;use App\Support\PostingSchedule;-function waitForCardLabelsCondition(mixed $page, string $condition): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if ({$condition}) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForCardLabelsTestId(mixed $page, string $testId): void-{- waitForCardLabelsCondition($page, "document.querySelector('[data-testid=\"{$testId}\"]')?.getBoundingClientRect().height > 0");-}--function waitForCardLabelsMissing(mixed $page, string $testId): void-{- waitForCardLabelsCondition($page, "!document.querySelector('[data-testid=\"{$testId}\"]')");-}-/*** @param list<string> $expected*/@@ -109,9 +87,9 @@ function cardLabelsPost(User $user, Workspace $workspace, SocialAccount $channelfunction openCardLabelsPicker(mixed $page, string $key): void{- waitForCardLabelsTestId($page, "post-labels-{$key}-trigger");+ waitFor($page, "@post-labels-{$key}-trigger");$page->click("@post-labels-{$key}-trigger");- waitForCardLabelsTestId($page, "post-labels-{$key}-search");+ waitFor($page, "@post-labels-{$key}-search");}test('a queued card assigns and unassigns a label from its picker', function () {@@ -130,17 +108,17 @@ test('a queued card assigns and unassigns a label from its picker', function ()->assertScript("document.querySelector('[data-testid=\"post-labels-{$post->id}-settings\"]').getAttribute('href')", route('app.labels.index', absolute: false));$page->type("@post-labels-{$post->id}-search", 'camp');- waitForCardLabelsMissing($page, "post-labels-{$post->id}-option-{$other->id}");+ waitForGone($page, "@post-labels-{$post->id}-option-{$other->id}");$page->assertMissing("@post-labels-{$post->id}-option-{$other->id}")->click("@post-labels-{$post->id}-checkbox-{$label->id}");- waitForCardLabelsTestId($page, "post-label-chip-{$post->id}-{$label->id}");+ waitFor($page, "@post-label-chip-{$post->id}-{$label->id}");waitForCardLabelsStored($page, $post, [$label->id]);expect($post->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id]);$page->assertVisible("@post-label-chip-{$post->id}-{$label->id}");$page->click("@post-labels-{$post->id}-checkbox-{$label->id}");- waitForCardLabelsMissing($page, "post-label-chip-{$post->id}-{$label->id}");+ waitForGone($page, "@post-label-chip-{$post->id}-{$label->id}");waitForCardLabelsStored($page, $post, []);expect($post->labels()->count())->toBe(0);@@ -161,14 +139,14 @@ test('a draft card clears every label with clear all', function () {$page->click("@post-labels-{$draft->id}-checkbox-{$first->id}");waitForCardLabelsStored($page, $draft, [$first->id]);$page->click("@post-labels-{$draft->id}-checkbox-{$second->id}");- waitForCardLabelsTestId($page, "post-label-chip-{$draft->id}-{$second->id}");+ waitFor($page, "@post-label-chip-{$draft->id}-{$second->id}");waitForCardLabelsStored($page, $draft, [$first->id, $second->id]);expect($draft->labels()->count())->toBe(2);$page->assertVisible("@post-label-chip-{$draft->id}-{$first->id}")->assertVisible("@post-label-chip-{$draft->id}-{$second->id}")->click("@post-labels-{$draft->id}-clear");- waitForCardLabelsMissing($page, "post-label-chip-{$draft->id}-{$first->id}");+ waitForGone($page, "@post-label-chip-{$draft->id}-{$first->id}");waitForCardLabelsStored($page, $draft, []);expect($draft->labels()->count())->toBe(0);@@ -185,7 +163,7 @@ test('the label filter drops a card once its label is removed', function () {$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'drafts', 'labels' => [$label->id]]));- waitForCardLabelsTestId($page, "post-label-chip-{$tagged->id}-{$label->id}");+ waitFor($page, "@post-label-chip-{$tagged->id}-{$label->id}");$page->assertVisible("@post-card-{$tagged->id}")->assertMissing("@post-card-{$untagged->id}")@@ -193,7 +171,7 @@ test('the label filter drops a card once its label is removed', function () {openCardLabelsPicker($page, $tagged->id);$page->click("@post-labels-{$tagged->id}-checkbox-{$label->id}");- waitForCardLabelsMissing($page, "post-card-{$tagged->id}");+ waitForGone($page, "@post-card-{$tagged->id}");waitForCardLabelsStored($page, $tagged, []);expect($tagged->labels()->count())->toBe(0);@@ -214,10 +192,70 @@ test('a rejected change rolls the card back and shows an error', function () {$label->delete();$page->click("@post-labels-{$post->id}-checkbox-{$label->id}");- waitForCardLabelsTestId($page, 'post-labels-error-toast');- waitForCardLabelsMissing($page, "post-label-chip-{$post->id}-{$label->id}");+ waitFor($page, '@post-labels-error-toast');+ waitForGone($page, "@post-label-chip-{$post->id}-{$label->id}");expect($post->labels()->count())->toBe(0);$page->assertSeeIn('@post-labels-error-toast', __('posts.publish.actions.edit_labels_failed'))->assertMissing("@post-label-chip-{$post->id}-{$label->id}");});++test('the first label of the card picker sits apart from its search box', function () {+ [$user, $workspace, $channel] = cardLabelsSetup();+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id, 'name' => 'Campaign']);+ $post = cardLabelsPost($user, $workspace, $channel);+ $this->actingAs($user);++ $page = visit(route('app.posts.index'));+ openCardLabelsPicker($page, $post->id);++ $gap = $page->script(<<<JS+ (() => {+ const search = document.querySelector('[data-testid="post-labels-{$post->id}-search"]').getBoundingClientRect();+ const option = document.querySelector('[data-testid="post-labels-{$post->id}-option-{$label->id}"]').getBoundingClientRect();++ return Math.round(option.top - search.bottom);+ })()+ JS);++ expect($gap)->toBe(8);+ $page->assertNoJavaScriptErrors();+});++test('a card label shows its name as typed, in a chip as tall as the label button beside it', function () {+ [$user, $workspace, $channel] = cardLabelsSetup();+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id, 'name' => 'Coca Cola']);+ $post = cardLabelsPost($user, $workspace, $channel);+ $post->labels()->attach($label);+ $this->actingAs($user);++ $page = visit(route('app.posts.index'));+ waitFor($page, "@post-label-chip-{$post->id}-{$label->id}");++ $chip = $page->script(<<<JS+ (() => {+ const chip = document.querySelector('[data-testid="post-label-chip-{$post->id}-{$label->id}"]');+ const button = document.querySelector('[data-testid="post-labels-{$post->id}-edit"]');+ const style = getComputedStyle(chip);++ return {+ text: chip.innerText.trim(),+ transform: style.textTransform,+ fontSize: style.fontSize,+ radius: style.borderTopLeftRadius,+ shadow: style.boxShadow,+ sameHeight: Math.round(chip.getBoundingClientRect().height) === Math.round(button.getBoundingClientRect().height),+ };+ })()+ JS);++ expect($chip)->toBe([+ 'text' => 'Coca Cola',+ 'transform' => 'none',+ 'fontSize' => '12px',+ 'radius' => '6px',+ 'shadow' => 'none',+ 'sameHeight' => true,+ ]);+ $page->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/ProfileTabsTest.php b/tests/Browser/ProfileTabsTest.phpindex 46834d567..4db929280 100644--- a/tests/Browser/ProfileTabsTest.php+++ b/tests/Browser/ProfileTabsTest.php@@ -137,7 +137,7 @@ test('logging out other devices asks for a plain confirmation without a password$table = config('session.table', 'sessions');DB::table($table)->insert([['id' => 'phone', 'user_id' => $user->id, 'ip_address' => '203.0.113.9', 'user_agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1', 'payload' => '', 'last_activity' => now()->subHour()->timestamp],- ['id' => 'laptop', 'user_id' => $user->id, 'ip_address' => '203.0.113.10', 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0', 'payload' => '', 'last_activity' => now()->subDay()->timestamp],+ ['id' => 'laptop', 'user_id' => $user->id, 'ip_address' => '203.0.113.10', 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0', 'payload' => '', 'last_activity' => now()->subHours(3)->timestamp],]);$this->actingAs($user);diff --git a/tests/Browser/PublishPageTest.php b/tests/Browser/PublishPageTest.phpindex 770b1cab6..c743aae80 100644--- a/tests/Browser/PublishPageTest.php+++ b/tests/Browser/PublishPageTest.php@@ -126,7 +126,7 @@ test('the weekly goal shows its progress, fills the pie and opens a popover with->toBe('1 '.__('posts.publish.goal_popover.sent').'·0 '.__('posts.publish.goal_popover.scheduled').'·2 '.__('posts.publish.goal_popover.to_do'));});-test('a draft is added to the queue from the drafts tab', function () {+test('a draft is added to the queue from the drafts tab, which stays open', function () {[$user, $workspace, $channel] = publishPageSetup();$draft = publishPagePost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);$this->actingAs($user);@@ -143,7 +143,10 @@ test('a draft is added to the queue from the drafts tab', function () {expect($draft->refresh()->status)->toBe(PostStatus::Scheduled)->and($draft->schedule_mode)->toBe(ScheduleMode::Queue);- $page->assertNoJavaScriptErrors();+ waitForGone($page, "@post-card-{$draft->id}");+ $page->assertPathIs(route('app.channels.publish', $channel, false))+ ->assertScript("new URLSearchParams(location.search).get('tab')", 'drafts')+ ->assertNoJavaScriptErrors();});test('add to queue explains how to set up the queue when the channel has no posting times', function () {@@ -172,7 +175,7 @@ test('add to queue explains how to set up the queue when the channel has no post$page->click("@post-queue-setup-action-{$draft->id}");waitForPublishPageTestId($page, 'channel-settings-page');- $page->assertPathIs(parse_url(route('app.channels.settings', $channel), PHP_URL_PATH))+ $page->assertPathIs(route('app.channels.settings', $channel, absolute: false))->assertNoJavaScriptErrors();});@@ -225,7 +228,7 @@ test('editing a draft from a channel page keeps the channel page and tab', funct$page->click("@post-edit-{$draft->id}");waitForPublishPageTestId($page, 'post-composer-dialog');- expect($page->script('location.pathname'))->toBe(parse_url(route('app.channels.publish', $channel), PHP_URL_PATH))+ expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('drafts')->and($page->script('new URLSearchParams(location.search).get("edit")'))->toBe($draft->id);$page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();@@ -252,7 +255,7 @@ test('saving a queued post edited on a channel page returns to that page and tabJS);waitForPublishPageTestId($page, "post-card-{$queued->id}");- expect($page->script('location.pathname'))->toBe(parse_url(route('app.channels.publish', $channel), PHP_URL_PATH))+ expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('queue')->and($page->script('new URLSearchParams(location.search).has("edit")'))->toBeFalse();$page->assertVisible("@post-card-{$queued->id}")->assertNoJavaScriptErrors();@@ -295,7 +298,7 @@ test('a sent card shows the metrics band in order and links to the publication iexpect($page->script("[...document.querySelectorAll('[data-testid=\"post-metrics-{$post->id}\"] dd')].map((value) => value.textContent.trim())"))->toBe(['40', '7', '5.5%', '900', '3'])->and($page->script("new URL(document.querySelector('[data-testid=\"post-insights-{$post->id}\"]').href).pathname"))- ->toBe(parse_url(route('app.channels.insights', $account), PHP_URL_PATH));+ ->toBe(route('app.channels.insights', $account, absolute: false));$page->assertNoJavaScriptErrors();});diff --git a/tests/Feature/Analytics/PublicationBackfillJobsTest.php b/tests/Feature/Analytics/PublicationBackfillJobsTest.phpindex f8ca5e141..483ac4626 100644--- a/tests/Feature/Analytics/PublicationBackfillJobsTest.php+++ b/tests/Feature/Analytics/PublicationBackfillJobsTest.php@@ -539,7 +539,7 @@ test('a transient failure dispatches a delayed retry and preserves the cursor',test('a rate limited failure waits for the provider retry time when it is later than the backoff', function () {Bus::fake();- $this->freezeTime();+ $this->travelTo(CarbonImmutable::parse('2026-10-07 12:00:00', 'UTC'));$account = SocialAccount::factory()->instagram()->create();$state = AnalyticsSyncState::factory()->create(['social_account_id' => $account->id,diff --git a/tests/Feature/Auth/SignupClickIdTrackingTest.php b/tests/Feature/Auth/SignupClickIdTrackingTest.phpindex b1a3dd01c..e80d34957 100644--- a/tests/Feature/Auth/SignupClickIdTrackingTest.php+++ b/tests/Feature/Auth/SignupClickIdTrackingTest.php@@ -150,7 +150,7 @@ test('existing google user login consumes the click id session so it does not le->andReturn($socialiteUser);$this->get(route('auth.google.callback'))- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('app.calendar'));expect(session()->get('attribution_parameters'))->toBeNull();});@@ -179,7 +179,7 @@ test('existing github user login consumes the click id session so it does not le->andReturn($socialiteUser);$this->get(route('auth.github.callback'))- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('app.calendar'));expect(session()->get('attribution_parameters'))->toBeNull();});diff --git a/tests/Feature/Auth/SignupUtmTrackingTest.php b/tests/Feature/Auth/SignupUtmTrackingTest.phpindex 3c0ac17f5..7c6cef0b0 100644--- a/tests/Feature/Auth/SignupUtmTrackingTest.php+++ b/tests/Feature/Auth/SignupUtmTrackingTest.php@@ -158,7 +158,7 @@ test('existing google user login consumes the utm session so utms do not leak to->andReturn($socialiteUser);$this->get(route('auth.google.callback'))- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('app.calendar'));expect(session()->get('attribution_parameters'))->toBeNull();});@@ -346,7 +346,7 @@ test('existing github user login consumes the utm session and skips signup succe->andReturn($socialiteUser);$this->get(route('auth.github.callback'))- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('app.calendar'));expect(session()->get('attribution_parameters'))->toBeNull();});diff --git a/tests/Feature/Auth/VerificationNotificationTest.php b/tests/Feature/Auth/VerificationNotificationTest.phpindex bf8e56f86..1249b8969 100644--- a/tests/Feature/Auth/VerificationNotificationTest.php+++ b/tests/Feature/Auth/VerificationNotificationTest.php@@ -12,8 +12,11 @@ test('sends verification notification', function () {$user = User::factory()->unverified()->create();$this->actingAs($user)+ ->from(route('verification.notice'))->post(route('verification.send'))- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('verification.notice'))+ ->assertSessionHas('status', 'verification-link-sent')+ ->assertSessionHas('flash.success', __('settings.profile.verification_sent'));Notification::assertSentTo($user, VerifyEmail::class);});diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/HomeRedirectTest.phpsimilarity index 100%rename from tests/Feature/ExampleTest.phprename to tests/Feature/HomeRedirectTest.phpdiff --git a/tests/Feature/PostControllerTest.php b/tests/Feature/PostControllerTest.phpindex 65d0af24f..1d3ff47a9 100644--- a/tests/Feature/PostControllerTest.php+++ b/tests/Feature/PostControllerTest.php@@ -23,6 +23,7 @@ use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Mail;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Route;+use Illuminate\Support\Uri;beforeEach(function () {Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);@@ -494,7 +495,7 @@ test('store post creates one independent draft per selected account', function (]),);- $this->actingAs($this->user)->post(route('app.posts.store'), [+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), ['status' => 'draft','content' => 'Shared caption','media' => [],@@ -523,7 +524,7 @@ test('store post schedules each selected account independently', function () {]);$date = now()->addDay()->startOfMinute()->toIso8601String();- $this->actingAs($this->user)->post(route('app.posts.store'), [+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), ['status' => 'scheduled','content' => 'Scheduled caption','media' => [],@@ -549,7 +550,7 @@ test('saving a zero-target legacy draft creates independent posts and removes th$other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);$accounts = [$this->socialAccount, $other];- $this->actingAs($this->user)->post(route('app.posts.store'), [+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), ['recover_post_id' => $legacy->id,'status' => 'draft','content' => 'Recovered caption',@@ -847,7 +848,7 @@ test('publish now updates scheduled_at to current time', function () {'scheduled_at' => now()->addDays(7),]);- $response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [+ $response = $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $post), ['status' => 'publishing','content' => 'Test content','content_type' => ContentType::LinkedInPost->value,@@ -1018,13 +1019,106 @@ test('destroy post deletes the post and redirects to posts index', function () {'user_id' => $this->user->id,]);- $response = $this->actingAs($this->user)+ $response = $this->actingAs($this->user)->from(route('app.posts.index'))->delete(route('app.posts.destroy', $post));$response->assertRedirect(route('app.posts.index'));expect(Post::find($post->id))->toBeNull();});+test('destroy never sends the browser to another host named in the referer path', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from('https://evil.example//evil.com/x')+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.home'));++ expect(Post::find($post->id))->toBeNull();+});++test('destroy with a referer that cannot be read deletes the post and returns home', function (string $referer) {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from($referer)+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.home'));++ expect(Post::find($post->id))->toBeNull();+})->with([+ 'no host' => 'http://:80/x',+ 'a page of the app the URI parser refuses' => 'https://user@:[email protected]/schedule',+]);++test('destroy without a referer returns home, not to the last page loaded in full', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->withSession(['_previous' => ['url' => route('app.settings.preferences')]])+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.home'));++ expect(Post::find($post->id))->toBeNull();+});++test('destroy returns to the page it came from even when its query names a route parameter', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from(route('app.calendar', ['view' => 'week']).'?view=month')+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.calendar', ['view' => 'week']));+});++test('destroy keeps a query key named like an optional route parameter in the query, where the page reads it', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from(route('app.calendar', ['week' => '2026-10-26']).'&view=month')+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect((string) Uri::of(route('app.calendar', ['week' => '2026-10-26']))->withQuery(['view' => 'month']));+});++test('destroy ignores a numeric query key of the page it returns to', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from(route('app.calendar', ['week' => '2026-10-26']).'&0=foo')+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.calendar', ['week' => '2026-10-26']));+});++test('destroy returns to a page whose query has a form-encoded space with the same value', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)+ ->from(route('app.calendar', ['view' => 'week']).'?search=foo+bar')+ ->delete(route('app.posts.destroy', $post))+ ->assertRedirect(route('app.calendar', ['view' => 'week', 'search' => 'foo bar']));+});+test('destroy post with redirect param redirects to calendar', function () {$post = Post::factory()->create(['workspace_id' => $this->workspace->id,@@ -1289,7 +1383,7 @@ test('update post goes back to the queue after publishing without opening the po'content' => 'Test',]);- $response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [+ $response = $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $post), ['status' => 'publishing','content' => 'Test','content_type' => ContentType::LinkedInPost->value,@@ -1641,23 +1735,24 @@ test('saving a draft from the calendar stays on the calendar', function () {->assertRedirect($calendar);});-test('a new draft goes to the drafts tab, from the publish list or anywhere else', function (?string $from) {- $request = $this->actingAs($this->user);-- if ($from !== null) {- $request = $request->from($from);- }-- $request->post(route('app.posts.store'), [+test('a new draft from the publish list goes to the drafts tab', function (string $from) {+ $this->actingAs($this->user)->from($from)->post(route('app.posts.store'), ['status' => 'draft','content' => 'New draft','destinations' => [['social_account_id' => $this->socialAccount->id, 'content_type' => ContentType::LinkedInPost->value]],])->assertRedirect(route('app.posts.index', ['tab' => 'drafts']));})->with(['the queue tab' => fn () => route('app.posts.index', ['tab' => 'queue', 'compose' => 1]),- 'insights' => fn () => route('app.insights'),]);+test('a post saved with no page to return to lands on the app home', function () {+ $this->actingAs($this->user)->post(route('app.posts.store'), [+ 'status' => 'draft',+ 'content' => 'New draft',+ 'destinations' => [['social_account_id' => $this->socialAccount->id, 'content_type' => ContentType::LinkedInPost->value]],+ ])->assertRedirect(route('app.home'));+});+test('every way of scheduling from the editor lands on the queue tab', function (array $schedule) {$this->socialAccount->update(['posting_schedule' => PostingSchedule::empty()->withTime(1, '10:00')]);diff --git a/tests/Feature/Posts/CalendarPageTest.php b/tests/Feature/Posts/CalendarPageTest.phpindex ebe76764e..57ee6a794 100644--- a/tests/Feature/Posts/CalendarPageTest.php+++ b/tests/Feature/Posts/CalendarPageTest.php@@ -300,6 +300,23 @@ test('undated drafts are paginated with the default page size', function () {->assertInertia(fn (AssertableInertia $page) => $page->has('undatedDrafts.data', 1));});+test('posting slots past the queue window still show, marked as not taking a queued post', function () {+ $schedule = PostingSchedule::empty();++ foreach (range(0, 6) as $weekday) {+ $schedule = $schedule->withTime($weekday, '09:00');+ }++ $this->linkedin->update(['timezone' => 'UTC', 'posting_schedule' => $schedule]);++ $this->actingAs($this->user)+ ->get(route('app.calendar', ['view' => 'month', 'month' => '2027-01-01', 'slots' => 1, 'tz' => 'UTC']))+ ->assertInertia(fn (AssertableInertia $page) => $page+ ->where('slots.2027-01-03.0.queueable', true)+ ->where('slots.2027-01-04.0.queueable', false)+ ->where('slots.2027-01-31.0.queueable', false));+});+test('posting slots load only when enabled, cover the visible range and follow the display time zone', function () {$this->linkedin->update(['timezone' => 'America/Sao_Paulo',@@ -313,14 +330,17 @@ test('posting slots load only when enabled, cover the visible range and follow t$this->actingAs($this->user)->get(route('app.calendar', ['view' => 'week']))- ->assertInertia(fn (AssertableInertia $page) => $page->missing('slots'));+ ->assertInertia(fn (AssertableInertia $page) => $page+ ->missing('slots')+ ->reloadOnly('slots', fn (AssertableInertia $reload) => $reload+ ->where('slots.2026-10-05.0.at', '2026-10-05T12:00:00+00:00')));$this->actingAs($this->user)->get(route('app.calendar', ['view' => 'week', 'slots' => 1]))->assertInertia(fn (AssertableInertia $page) => $page->where('slots', [- '2026-10-05' => [['at' => '2026-10-05T12:00:00+00:00', 'channel_id' => $this->linkedin->id]],- '2026-10-07' => [['at' => '2026-10-08T02:30:00+00:00', 'channel_id' => $this->linkedin->id]],+ '2026-10-05' => [['at' => '2026-10-05T12:00:00+00:00', 'channel_id' => $this->linkedin->id, 'queueable' => true]],+ '2026-10-07' => [['at' => '2026-10-08T02:30:00+00:00', 'channel_id' => $this->linkedin->id, 'queueable' => true]],]));$this->actingAs($this->user)diff --git a/tests/Feature/Posts/ChannelAltTextTest.php b/tests/Feature/Posts/ChannelAltTextTest.phpindex b660a244d..f6681a89d 100644--- a/tests/Feature/Posts/ChannelAltTextTest.php+++ b/tests/Feature/Posts/ChannelAltTextTest.php@@ -60,7 +60,7 @@ function channelAltTextPost(SocialAccount $account): Post*/function storeChannelAltTextComposition(object $test): void{- $test->actingAs($test->user)->post(route('app.posts.store'), [+ $test->actingAs($test->user)->from(route('app.posts.index'))->post(route('app.posts.store'), ['status' => 'draft','content' => 'Alt text per channel','media' => [channelAltTextItem($test->upload, ['alt_text' => 'Shared description'])],diff --git a/tests/Feature/Posts/PostQueueTest.php b/tests/Feature/Posts/PostQueueTest.phpindex 3f54c52db..d9397a84e 100644--- a/tests/Feature/Posts/PostQueueTest.php+++ b/tests/Feature/Posts/PostQueueTest.php@@ -63,7 +63,7 @@ function postQueuePayload(array $channels, array $overrides = []): arrayfunction postQueueStore(object $test, SocialAccount $channel, string $position = 'next'): Post{- $test->actingAs($test->user)+ $test->actingAs($test->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$channel], ['queue' => $position]))->assertSessionHasNoErrors()->assertRedirect(route('app.posts.index', ['tab' => 'queue']));@@ -84,7 +84,7 @@ test('storing with queue next gives each channel its own first slot', function ('posting_schedule' => PostingSchedule::empty()->withTime(2, '10:00'),]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel, $other]))->assertSessionHasNoErrors()->assertRedirect(route('app.posts.index', ['tab' => 'queue']));@@ -119,7 +119,7 @@ test('storing with queue top takes the first slot and shifts the others', functi});test('storing with queue and scheduled_at is rejected', function () {- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->postJson(route('app.posts.store'), postQueuePayload([$this->channel], ['scheduled_at' => now()->addDay()->toIso8601String(),]))@@ -130,7 +130,7 @@ test('storing with queue and scheduled_at is rejected', function () {});test('storing with queue on a draft is rejected', function () {- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->postJson(route('app.posts.store'), postQueuePayload([$this->channel], ['status' => 'draft']))->assertUnprocessable()->assertJsonValidationErrors(['queue']);@@ -143,7 +143,7 @@ test('storing with queue for a channel without slots is rejected on that destina'posting_schedule' => null,]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->postJson(route('app.posts.store'), postQueuePayload([$empty]))->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.social_account_id']);@@ -152,7 +152,7 @@ test('storing with queue for a channel without slots is rejected on that destina});test('storing with scheduled_at and no queue makes a custom post', function () {- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel], ['queue' => null,'scheduled_at' => now()->addDays(2)->toIso8601String(),@@ -166,7 +166,7 @@ test('storing with scheduled_at and no queue makes a custom post', function () {});test('storing a draft leaves the schedule mode empty', function () {- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel], ['status' => 'draft', 'queue' => null]))->assertSessionHasNoErrors();@@ -177,7 +177,7 @@ test('updating only the content of a queued post keeps every slot', function ()$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'content' => 'Edited caption'])->assertSessionHasNoErrors();@@ -194,7 +194,7 @@ test('giving a queued post a custom time pins it and the others keep their slots$second = postQueueStore($this, $this->channel);$custom = CarbonImmutable::parse('2026-10-10 15:30', 'America/Sao_Paulo');- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value,'status' => 'scheduled',@@ -214,7 +214,7 @@ test('moving a queued post to draft clears its mode and leaves its slot free', f$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'draft', 'content' => 'Back to draft'])->assertSessionHasNoErrors();@@ -229,7 +229,7 @@ test('publishing a queued post now leaves the others in their slots', function ($first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'publishing', 'content' => 'Now'])->assertSessionHasNoErrors();@@ -241,12 +241,12 @@ test('publishing a queued post now leaves the others in their slots', function (test('adding a draft to the queue puts it at the end', function () {$first = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel], ['status' => 'draft', 'queue' => null]))->assertSessionHasNoErrors();$draft = Post::findOrFail(session('created_post_ids')[0]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $draft), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])->assertSessionHasNoErrors();@@ -260,11 +260,11 @@ test('adding a draft to the queue puts it at the end', function () {test('updating with queue is rejected when the channel has no slots', function () {$this->channel->update(['posting_schedule' => null]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel], ['status' => 'draft', 'queue' => null]));$draft = Post::sole();- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.posts.update', $draft), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])->assertUnprocessable()->assertJsonValidationErrors(['queue']);@@ -275,7 +275,7 @@ test('updating with queue is rejected when the channel has no slots', function (test('updating with queue and scheduled_at is rejected', function () {$post = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.posts.update', $post), ['content_type' => ContentType::LinkedInPost->value,'status' => 'scheduled',@@ -321,7 +321,7 @@ test('changing the posting schedule reassigns the queued posts', function () {$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'America/Sao_Paulo','posting_goal' => 2,@@ -337,7 +337,7 @@ test('a schedule change keeps posts whose slot still exists and re-places only t$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'America/Sao_Paulo','posting_goal' => 2,@@ -356,7 +356,7 @@ test('a time zone change keeps the local clock time of every queued post', funct$third = postQueueStore($this, $this->channel);$this->actingAs($this->user)->delete(route('app.posts.destroy', $second))->assertRedirect();- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'America/New_York','posting_goal' => 3,@@ -374,7 +374,7 @@ test('a time zone change keeps each local clock time even when the old instant i$posts = [postQueueStore($this, $this->channel), postQueueStore($this, $this->channel), postQueueStore($this, $this->channel)];- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'UTC','posting_goal' => 4,@@ -396,7 +396,7 @@ test('a time zone change keeps the local clock time of hourly slots', function ($this->channel->update(['posting_schedule' => $schedule]);$posts = array_map(fn (): Post => postQueueStore($this, $this->channel), range(1, 4));- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'UTC','posting_goal' => 4,@@ -416,7 +416,7 @@ test('a time zone change keeps the local clock time of a pending approval slot h$holder = Post::query()->sole();$queued = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'UTC','posting_goal' => 3,@@ -439,7 +439,7 @@ test('a time zone change moves a pending holder to the first free slot when its$holder = Post::query()->sole();$custom = Post::factory()->forAccount($this->channel)->scheduled()->create(['user_id' => $this->user->id, 'scheduled_at' => CarbonImmutable::parse('2026-10-05 09:00', 'UTC'), 'schedule_mode' => ScheduleMode::Custom]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'UTC','posting_goal' => 3,@@ -461,7 +461,7 @@ test('a time zone change with no slot left turns a pending holder custom at its$queued = postQueueStore($this, $this->channel);$at = $holder->refresh()->scheduled_at;- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'UTC','posting_goal' => 3,@@ -530,7 +530,7 @@ test('clearing the posting schedule turns queued posts custom at their times', f$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->putJson(route('app.channels.posting-schedule.update', $this->channel), ['timezone' => 'America/Sao_Paulo','posting_goal' => 2,@@ -547,7 +547,7 @@ test('clearing the posting schedule turns queued posts custom at their times', ftest('generating a posting schedule reflows the queue', function () {$post = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->postJson(route('app.channels.posting-schedule.generate', $this->channel), ['mode' => 'goal', 'goal' => 3])->assertOk();@@ -566,7 +566,7 @@ test('copying a posting schedule reflows the queue', function () {'posting_schedule' => PostingSchedule::empty()->withTime(6, '07:15'),]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->postJson(route('app.channels.posting-schedule.copy', $this->channel), ['from' => $source->id])->assertOk();@@ -596,7 +596,7 @@ test('re-sending queue next on a queued post keeps its slot', function () {$first = postQueueStore($this, $this->channel);$second = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited'])->assertSessionHasNoErrors();@@ -611,7 +611,7 @@ test('queue top on a queued post moves it to the top', function () {$second = postQueueStore($this, $this->channel);$third = postQueueStore($this, $this->channel);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->put(route('app.posts.update', $second), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'top', 'content' => 'Urgent'])->assertSessionHasNoErrors();@@ -628,7 +628,7 @@ test('recovering an empty legacy draft into the queue gives it a slot', function'status' => PostStatus::Draft,]);- $this->actingAs($this->user)+ $this->actingAs($this->user)->from(route('app.posts.index'))->post(route('app.posts.store'), postQueuePayload([$this->channel], ['recover_post_id' => $legacy->id]))->assertSessionHasNoErrors()->assertRedirect(route('app.posts.index', ['tab' => 'queue']));diff --git a/tests/Feature/Posts/PostScheduleActionTest.php b/tests/Feature/Posts/PostScheduleActionTest.phpindex 71ed697f2..b14e14c86 100644--- a/tests/Feature/Posts/PostScheduleActionTest.php+++ b/tests/Feature/Posts/PostScheduleActionTest.php@@ -247,13 +247,21 @@ test('moving a post to drafts stays on the tab it was moved from', function () {->assertRedirect($queue);});-test('adding a draft to the queue from its card goes to the queue tab', function (string $action) {+test('adding a draft to the queue from its card stays on the tab it was added from', function (string $action, bool $onChannelPage) {$this->channel->update(['posting_schedule' => PostingSchedule::empty()->withTime(1, '10:00')]);$draft = scheduleActionPost($this->channel, $this->user);+ $drafts = $onChannelPage+ ? route('app.channels.publish', ['account' => $this->channel, 'tab' => 'drafts'])+ : route('app.posts.index', ['tab' => 'drafts']);$this->actingAs($this->user)- ->from(route('app.posts.index', ['tab' => 'drafts']))+ ->from($drafts)->put(route('app.posts.schedule.update', $draft), ['action' => $action])->assertSessionHasNoErrors()- ->assertRedirect(route('app.posts.index', ['tab' => 'queue']));-})->with(['queue_next', 'queue_top']);+ ->assertRedirect($drafts);++ expect($draft->fresh()->status)->toBe(PostStatus::Scheduled);+})->with(['queue_next', 'queue_top'])->with([+ 'the drafts tab' => false,+ 'a channel drafts tab' => true,+]);diff --git a/tests/Feature/Posts/PublishPageRedirectsTest.php b/tests/Feature/Posts/PublishPageRedirectsTest.phpindex 7dfb3cf93..1bf5a02a4 100644--- a/tests/Feature/Posts/PublishPageRedirectsTest.php+++ b/tests/Feature/Posts/PublishPageRedirectsTest.php@@ -10,7 +10,9 @@ use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;+use App\Support\PostingSchedule;use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\URL;use Inertia\Testing\AssertableInertia;beforeEach(function () {@@ -33,6 +35,18 @@ function publishRedirectPost(SocialAccount $channel, PostStatus $status = PostSt]);}+function publishRedirectOrigin(string $origin, SocialAccount $channel): string+{+ return match ($origin) {+ 'calendar week' => route('app.calendar', ['view' => 'week', 'week' => '2026-10-25', 'slots' => 1]),+ 'calendar month' => route('app.calendar', ['view' => 'month', 'month' => '2026-10-01', 'channels' => $channel->id]),+ 'channel calendar' => route('app.channels.calendar', ['account' => $channel, 'view' => 'days', 'day' => '2026-10-27']),+ 'channel grid' => route('app.channels.grid', ['account' => $channel]),+ 'insights' => route('app.insights', ['range' => '30d']),+ 'ideas' => route('app.create.ideas.index'),+ };+}+/*** @return array<string, mixed>*/@@ -67,14 +81,16 @@ test('saving a draft from the all channels page keeps the tab and filters but dr->assertRedirect(route('app.posts.index', ['tab' => 'drafts', 'channels' => [$this->channel->id]]));});-test('scheduling an edit outside the publish page still lands on the post', function () {+test('saving an edit from another page of the app returns to that page as it was', function (string $status, string $origin) {$post = publishRedirectPost($this->channel);+ $from = publishRedirectOrigin($origin, $this->channel);$this->actingAs($this->user)- ->from(route('app.calendar'))- ->put(route('app.posts.update', $post), publishRedirectUpdatePayload($post, 'scheduled'))- ->assertRedirect(route('app.posts.index', ['post' => $post->id]));-});+ ->from($from)+ ->put(route('app.posts.update', $post), publishRedirectUpdatePayload($post, $status))+ ->assertSessionHasNoErrors()+ ->assertRedirect($from);+})->with(['draft', 'scheduled'])->with(['calendar week', 'insights']);test('returning to the publish page drops the post details deep link', function () {$post = publishRedirectPost($this->channel);@@ -102,22 +118,73 @@ test('creating from the channel page returns to that page', function () {->assertSessionHas('created_post_ids');});-test('a draft created from outside the publish page lands on the all channels drafts tab', function () {+test('a post created from another page of the app returns to that page as it was', function (array $schedule, string $origin) {+ $this->channel->update(['posting_schedule' => PostingSchedule::empty()->withTime(1, '10:00')]);+ $from = publishRedirectOrigin($origin, $this->channel);+$this->actingAs($this->user)- ->from(route('app.calendar'))+ ->from($from)->post(route('app.posts.store'), [- 'status' => 'draft','content' => 'New caption','media' => [],+ ...$schedule,'destinations' => [['social_account_id' => $this->channel->id,'content_type' => ContentType::LinkedInPost->value,'meta' => [],]],])- ->assertRedirect(route('app.posts.index', ['tab' => 'drafts']));+ ->assertSessionHasNoErrors()+ ->assertRedirect($from);+})->with([+ 'a draft' => [['status' => 'draft']],+ 'a scheduled post' => [['status' => 'scheduled', 'scheduled_at' => '2037-01-01T10:00:00Z']],+ 'a queued post' => [['status' => 'scheduled', 'queue' => 'next']],+])->with(['calendar week', 'calendar month', 'channel calendar', 'channel grid', 'insights', 'ideas']);++test('a page named by a referer on another host is returned to on this app', function () {+ $this->actingAs($this->user)+ ->withHeader('referer', 'https://evil.example/schedule/calendar/week?week=2026-10-25')+ ->post(route('app.posts.store'), [+ 'status' => 'draft',+ 'content' => 'New caption',+ 'destinations' => [['social_account_id' => $this->channel->id, 'content_type' => ContentType::LinkedInPost->value]],+ ])+ ->assertRedirect(route('app.calendar', ['view' => 'week', 'week' => '2026-10-25']));+});++test('a page with a dotted query key is returned to with that key as it was', function () {+ $post = publishRedirectPost($this->channel);+ $from = route('app.create.ideas.index', ['columns.unassigned_page' => 2]);++ $this->actingAs($this->user)+ ->from($from)+ ->put(route('app.posts.update', $post), publishRedirectUpdatePayload($post, 'draft'))+ ->assertSessionHasNoErrors()+ ->assertRedirect($from);});+test('on an app served from a subfolder a page is returned to without doubling the base path', function (string $origin, array $originQuery, array $expectedQuery) {+ $post = publishRedirectPost($this->channel);+ $update = route('app.posts.update', $post);+ $root = rtrim(config('app.url'), '/').'/trypost';+ URL::forceRootUrl($root);+ $origin = match ($origin) {+ 'calendar' => route('app.calendar', $originQuery),+ 'all channels' => route('app.posts.index', $originQuery),+ };++ $this->actingAs($this->user)+ ->withServerVariables(['SCRIPT_NAME' => '/trypost/index.php', 'SCRIPT_FILENAME' => public_path('index.php')])+ ->from($origin)+ ->put($update, publishRedirectUpdatePayload($post, 'draft'))+ ->assertSessionHasNoErrors()+ ->assertRedirect(blank($expectedQuery) ? $origin : route('app.posts.index', $expectedQuery));+})->with([+ 'calendar' => ['calendar', ['view' => 'week', 'week' => '2026-10-25'], []],+ 'all channels' => ['all channels', ['tab' => 'drafts', 'edit' => 'x'], ['tab' => 'drafts']],+]);+test('deleting from the channel page returns to that page', function () {$post = publishRedirectPost($this->channel);@@ -130,13 +197,13 @@ test('deleting from the channel page returns to that page', function () {expect(Post::find($post->id))->toBeNull();});-test('deleting from outside the publish page falls back to the all channels page', function () {+test('deleting from another page of the app returns to that page', function () {$post = publishRedirectPost($this->channel);$this->actingAs($this->user)->from(route('app.settings.preferences'))->delete(route('app.posts.destroy', $post))- ->assertRedirect(route('app.posts.index'));+ ->assertRedirect(route('app.settings.preferences'));});test('deleting from a calendar returns to that calendar as it was', function (string $route) {diff --git a/tests/Feature/Posts/ReschedulePostTest.php b/tests/Feature/Posts/ReschedulePostTest.phpnew file mode 100644index 000000000..463e4f077--- /dev/null+++ b/tests/Feature/Posts/ReschedulePostTest.php@@ -0,0 +1,719 @@+<?php++declare(strict_types=1);++use App\Actions\Post\FinalizePostPublication;+use App\Actions\Post\Queue\ReflowChannelQueue;+use App\Enums\Post\PublishStatus;+use App\Enums\Post\QueuePosition;+use App\Enums\Post\RecurrenceFrequency;+use App\Enums\Post\ScheduleMode;+use App\Enums\Post\Status as PostStatus;+use App\Enums\SocialAccount\Platform;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Support\PostingSchedule;+use Carbon\CarbonImmutable;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ Queue::fake();+ $this->travelTo(CarbonImmutable::parse('2026-10-05 08:00', 'UTC'));++ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id, 'user_id' => $this->user->id]);+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));+ $this->user->update(['current_workspace_id' => $this->workspace->id]);++ $this->channel = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ 'timezone' => 'UTC',+ 'posting_schedule' => PostingSchedule::empty()->withTime(1, '09:00')->withTime(3, '09:00')->withTime(5, '09:00'),+ ]);+});++function reschedulePost(SocialAccount $channel, User $user, array $attributes = []): Post+{+ return Post::factory()->forAccount($channel)->create(array_merge([+ 'user_id' => $user->id,+ 'content' => 'A caption',+ 'status' => PostStatus::Draft,+ 'schedule_mode' => null,+ 'scheduled_at' => null,+ ], $attributes))->refresh();+}++function rescheduleCustom(SocialAccount $channel, User $user, string $at = '2026-10-06 10:00'): Post+{+ return reschedulePost($channel, $user, [+ 'status' => PostStatus::Scheduled,+ 'schedule_mode' => ScheduleMode::Custom,+ 'scheduled_at' => CarbonImmutable::parse($at, 'UTC'),+ ]);+}++function rescheduleQueued(SocialAccount $channel, User $user): Post+{+ $post = reschedulePost($channel, $user, ['status' => PostStatus::Scheduled, 'schedule_mode' => ScheduleMode::Queue]);++ ReflowChannelQueue::handle($channel, $post, QueuePosition::Next);++ return $post->refresh();+}++test('reschedule moves a custom post to the instant it receives', function () {+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-06T14:00:00Z'])+ ->assertSessionHasNoErrors()+ ->assertRedirect();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Scheduled)+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-06 14:00', 'UTC')->toIso8601String());+});++test('reschedule stores the instant it receives, not the channel clock', function () {+ $this->channel->update(['timezone' => 'America/Sao_Paulo']);+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-06T01:00:00Z'])+ ->assertSessionHasNoErrors();++ expect($post->fresh()->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-06 01:00', 'UTC')->toIso8601String());+});++test('a queued post dropped on a free slot of its own channel becomes custom at that slot', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $slot = CarbonImmutable::parse('2026-10-09 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String()])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe($slot->toIso8601String());+});++test('a post dropped on a slot another post already holds stacks on that instant', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $slotAt = CarbonImmutable::parse('2026-10-09 09:00', 'UTC');+ $occupant = rescheduleCustom($this->channel, $this->user, $slotAt->toDateTimeString());++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slotAt->toIso8601String()])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe($slotAt->toIso8601String())+ ->and($occupant->fresh()->scheduled_at->toIso8601String())->toBe($slotAt->toIso8601String());+});++test('reschedule makes a queued post custom when the target is not a slot', function () {+ $first = rescheduleQueued($this->channel, $this->user);+ $second = rescheduleQueued($this->channel, $this->user);+ $oldSlot = $first->scheduled_at;+ $secondSlot = $second->scheduled_at->toIso8601String();+ $target = CarbonImmutable::parse('2026-10-06 15:30', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $first), ['action' => 'reschedule', 'scheduled_at' => $target->toIso8601String()])+ ->assertSessionHasNoErrors();++ $first->refresh();++ expect($first->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($first->scheduled_at->toIso8601String())->toBe($target->toIso8601String())+ ->and(ReflowChannelQueue::isFreeSlot($this->channel->refresh(), $oldSlot))->toBeTrue()+ ->and($second->fresh()->scheduled_at->toIso8601String())->toBe($secondSlot);+});++test('reschedule keeps a custom post custom on a free slot of its channel', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $slot = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String()])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe($slot->toIso8601String());+});++test('a custom post sent to a free slot of its channel goes into the queue at that slot', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $slot = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Scheduled)+ ->and($post->schedule_mode)->toBe(ScheduleMode::Queue)+ ->and($post->scheduled_at->toIso8601String())->toBe($slot->toIso8601String());+});++test('a queued post sent to another free slot stays in the queue there and frees its old slot', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $oldSlot = $post->scheduled_at;+ $slot = CarbonImmutable::parse('2026-10-09 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Queue)+ ->and($post->scheduled_at->toIso8601String())->toBe($slot->toIso8601String())+ ->and(ReflowChannelQueue::isFreeSlot($this->channel->refresh(), $oldSlot))->toBeTrue();+});++test('a post sent to a slot another post holds is refused and keeps its time', function () {+ $slot = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');+ rescheduleCustom($this->channel, $this->user, $slot->toDateTimeString());+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.slot_taken')]);++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-06 10:00', 'UTC')->toIso8601String());+});++test('a post sent to the queue at an instant that is not a slot is refused instead of becoming custom', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $queuedAt = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-06T15:30:00Z', 'queue_slot' => true])+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.slot_taken')]);++ $post->refresh();++ expect($post->schedule_mode)->toBe(ScheduleMode::Queue)+ ->and($post->scheduled_at->toIso8601String())->toBe($queuedAt);+});++test('a post sent to a slot past the queue window becomes custom at that slot', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $slot = CarbonImmutable::parse('2027-02-03 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Scheduled)+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe($slot->toIso8601String());+});++test('a post sent to a slot after it started publishing shows the finalized banner and keeps its time', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $at = $post->scheduled_at->toIso8601String();+ $retrievals = 0;++ Post::retrieved(function (Post $retrieved) use ($post, &$retrievals): void {+ if ($retrieved->id === $post->id && ++$retrievals === 3) {+ Post::query()->whereKey($post->id)->toBase()->update(['status' => PostStatus::Publishing->value]);+ }+ });++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-07T09:00:00Z', 'queue_slot' => true])+ ->assertSessionHasNoErrors()+ ->assertSessionHas('flash.banner', __('posts.flash.cannot_edit_finalized'));++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Publishing)+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->scheduled_at->toIso8601String())->toBe($at);+});++test('a draft sent to a slot stays a draft with that date', function () {+ $draft = reschedulePost($this->channel, $this->user, ['scheduled_at' => CarbonImmutable::parse('2026-10-06 10:00', 'UTC')]);+ $slot = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertSessionHasNoErrors();++ $draft->refresh();++ expect($draft->status)->toBe(PostStatus::Draft)+ ->and($draft->scheduled_at->toIso8601String())->toBe($slot->toIso8601String());+});++test('a post sent to a slot by a member who needs approval is refused, as on the queue page', function () {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $post = rescheduleCustom($this->channel, $member);+ $at = $post->scheduled_at->toIso8601String();+ $slot = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');++ $this->actingAs($member)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String(), 'queue_slot' => true])+ ->assertForbidden();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Scheduled)+ ->and($post->scheduled_at->toIso8601String())->toBe($at)+ ->and($post->approval_requested_by)->toBeNull();+});++test('another action ignores queue_slot', function () {+ $draft = reschedulePost($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'queue_next', 'queue_slot' => 'not-a-boolean'])+ ->assertSessionHasNoErrors();++ expect($draft->fresh()->schedule_mode)->toBe(ScheduleMode::Queue);+});++test('reschedule keeps a draft a draft and moves its date', function () {+ $draft = reschedulePost($this->channel, $this->user, ['scheduled_at' => CarbonImmutable::parse('2026-10-06 10:00', 'UTC')]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertSessionHasNoErrors();++ $draft->refresh();++ expect($draft->status)->toBe(PostStatus::Draft)+ ->and($draft->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-08 11:00', 'UTC')->toIso8601String());+});++test('reschedule with a null time removes a draft date', function () {+ $draft = reschedulePost($this->channel, $this->user, ['scheduled_at' => CarbonImmutable::parse('2026-10-06 10:00', 'UTC')]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'reschedule', 'scheduled_at' => null])+ ->assertSessionHasNoErrors();++ $draft->refresh();++ expect($draft->status)->toBe(PostStatus::Draft)+ ->and($draft->scheduled_at)->toBeNull();+});++test('reschedule with a null time takes a scheduled post off the schedule as a draft without a date', function () {+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => null])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull();+});++test('reschedule with a null time takes a queued post out of the queue and frees its slot', function () {+ $post = rescheduleQueued($this->channel, $this->user);+ $slot = $post->scheduled_at;+ $next = rescheduleQueued($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => null])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull()+ ->and($next->refresh()->scheduled_at->equalTo($slot))->toBeFalse()+ ->and(Post::query()->where('social_account_id', $this->channel->id)->where('status', PostStatus::Scheduled)->where('scheduled_at', $slot)->exists())->toBeFalse();+});++test('reschedule with a null time takes a recurring post off the schedule, drops its rule like any move to drafts and starts no next occurrence', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $post->forceFill([+ 'recurrence_frequency' => RecurrenceFrequency::Week,+ 'recurrence_interval' => 1,+ 'recurrence_remaining' => 3,+ ])->save();+ $posts = Post::query()->count();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => null])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull()+ ->and($post->recurrence_frequency)->toBeNull()+ ->and($post->recurrence_remaining)->toBeNull()+ ->and(Post::query()->count())->toBe($posts);+});++test('a member who needs approval takes a post off the schedule without asking for approval', function () {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $post = rescheduleCustom($this->channel, $member);++ $this->actingAs($member)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => null])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull();+});++test('reschedule refuses a past instant and asks for a later time', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $at = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => now()->subMinute()->toIso8601String()])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.past')]);++ expect($post->fresh()->scheduled_at->toIso8601String())->toBe($at);+});++test('reschedule refuses a channel-less draft', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'content' => 'A caption',+ 'status' => PostStatus::Draft,+ ]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('posts.errors.choose_channel')]);+});++test('reschedule by a member who needs approval stores a pending request', function () {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $post = rescheduleCustom($this->channel, $member);++ $this->actingAs($member)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertSessionHasNoErrors();++ expect($post->fresh()->status)->toBe(PostStatus::PendingApproval);+});++test('reschedule of a queued post by a member who needs approval stores a pending custom time request', function () {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $post = rescheduleQueued($this->channel, $member);+ $slot = CarbonImmutable::parse('2026-10-09 09:00', 'UTC');++ $this->actingAs($member)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => $slot->toIso8601String()])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::PendingApproval)+ ->and($post->schedule_mode)->toBe(ScheduleMode::Custom)+ ->and($post->approval_requested_by)->toBe($member->id);+});++test('reschedule of a published post does nothing', function () {+ $post = reschedulePost($this->channel, $this->user, [+ 'status' => PostStatus::Published,+ 'scheduled_at' => CarbonImmutable::parse('2026-10-04 10:00', 'UTC'),+ ]);+ $at = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertRedirect()+ ->assertSessionHas('flash.banner', __('posts.flash.cannot_edit_finalized'));++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Published)+ ->and($post->scheduled_at->toIso8601String())->toBe($at);+});++test('reschedule of a post the viewer cannot see is not found', function () {+ $other = User::factory()->create();+ $otherWorkspace = Workspace::factory()->create(['account_id' => $other->account_id, 'user_id' => $other->id]);+ $otherChannel = SocialAccount::factory()->create(['workspace_id' => $otherWorkspace->id, 'platform' => Platform::LinkedIn]);+ $post = rescheduleCustom($otherChannel, $other);++ $this->actingAs($this->user)+ ->putJson(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertNotFound();+});++test('reschedule keeps a recurring post\'s rule and remaining count', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $post->forceFill([+ 'recurrence_frequency' => RecurrenceFrequency::Week,+ 'recurrence_interval' => 1,+ 'recurrence_remaining' => 3,+ ])->save();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-09T10:00:00Z'])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->recurrence_frequency)->toBe(RecurrenceFrequency::Week)+ ->and($post->recurrence_interval)->toBe(1)+ ->and($post->recurrence_remaining)->toBe(3)+ ->and($post->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-09 10:00', 'UTC')->toIso8601String());+});++test('the next occurrence of a rescheduled recurring post follows the new time', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $post->forceFill([+ 'recurrence_frequency' => RecurrenceFrequency::Week,+ 'recurrence_interval' => 1,+ 'recurrence_remaining' => 3,+ ])->save();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-09T10:00:00Z'])+ ->assertSessionHasNoErrors();++ $this->travelTo(CarbonImmutable::parse('2026-10-09 10:05', 'UTC'));+ $post->refresh()->forceFill(['status' => PostStatus::Publishing, 'publish_status' => PublishStatus::Published])->save();+ app(FinalizePostPublication::class)->handle($post);++ $next = Post::query()->whereKeyNot($post->id)->where('workspace_id', $this->workspace->id)->sole();++ expect($next->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-16 10:00', 'UTC')->toIso8601String())+ ->and($next->recurrence_remaining)->toBe(2)+ ->and($next->recurrence_frequency)->toBe(RecurrenceFrequency::Week);+});++test('reschedule without a time field is refused and keeps a draft\'s date', function () {+ $draft = reschedulePost($this->channel, $this->user, ['scheduled_at' => CarbonImmutable::parse('2026-10-06 10:00', 'UTC')]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'reschedule'])+ ->assertRedirect()+ ->assertSessionHasErrors('scheduled_at');++ expect($draft->fresh()->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-06 10:00', 'UTC')->toIso8601String());+});++test('another action ignores a stray past time', function () {+ $draft = reschedulePost($this->channel, $this->user);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'queue_next', 'scheduled_at' => now()->subDay()->toIso8601String()])+ ->assertSessionHasNoErrors()+ ->assertRedirect();++ $draft->refresh();++ expect($draft->status)->toBe(PostStatus::Scheduled)+ ->and($draft->schedule_mode)->toBe(ScheduleMode::Queue)+ ->and($draft->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-05 09:00', 'UTC')->toIso8601String());+});++test('reschedule from the publish list stays on the page it came from', function () {+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->from(route('app.posts.index'))+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-06T14:00:00Z'])+ ->assertSessionHasNoErrors()+ ->assertRedirect(route('app.posts.index'));+});++test('reschedule of a pending post is refused and keeps the request as it is', function (string $who) {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, membershipPivot('approval'));+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $post = rescheduleCustom($this->channel, $member);++ $this->actingAs($member)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertSessionHasNoErrors();++ $pending = $post->fresh();+ $actor = $who === 'requester' ? $member : $this->user;++ $this->actingAs($actor)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-09T15:00:00Z'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.pending')]);++ $post->refresh();++ expect($post->status)->toBe(PostStatus::PendingApproval)+ ->and($post->scheduled_at?->toIso8601String())->toBe($pending->scheduled_at?->toIso8601String())+ ->and($post->approved_by)->toBeNull()+ ->and($post->approval_requested_by)->toBe($member->id);+})->with(['requester', 'approver']);++test('reschedule of a failed or publishing post does nothing', function (PostStatus $status) {+ $post = reschedulePost($this->channel, $this->user, [+ 'status' => $status,+ 'scheduled_at' => CarbonImmutable::parse('2026-10-05 07:00', 'UTC'),+ ]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertRedirect()+ ->assertSessionHas('flash.banner', __('posts.flash.cannot_edit_finalized'));++ $post->refresh();++ expect($post->status)->toBe($status)+ ->and($post->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-05 07:00', 'UTC')->toIso8601String());+})->with([PostStatus::Failed, PostStatus::Publishing]);++test('reschedule of a scheduled post due within a minute or overdue is refused', function (string $due) {+ $post = rescheduleCustom($this->channel, $this->user, now()->modify($due)->toDateTimeString());+ $at = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.publishing_soon')]);++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Scheduled)+ ->and($post->scheduled_at->toIso8601String())->toBe($at);+})->with(['in 20 seconds' => '+20 seconds', '30 seconds ago' => '-30 seconds']);++test('reschedule of a scheduled post due in two minutes moves it', function () {+ $post = rescheduleCustom($this->channel, $this->user, now()->addMinutes(2)->toDateTimeString());++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertSessionHasNoErrors()+ ->assertRedirect();++ expect($post->fresh()->scheduled_at->toIso8601String())->toBe(CarbonImmutable::parse('2026-10-08 11:00', 'UTC')->toIso8601String());+});++test('reschedule is refused when the post went to approval after the request was validated', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $at = $post->scheduled_at->toIso8601String();+ $flipped = false;++ Post::retrieved(function (Post $retrieved) use ($post, &$flipped): void {+ if ($flipped || $retrieved->id !== $post->id) {+ return;+ }++ $flipped = true;+ Post::query()->whereKey($post->id)->toBase()->update(['status' => PostStatus::PendingApproval->value]);+ });++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2026-10-08T11:00:00Z'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.pending')]);++ $post->refresh();++ expect($post->status)->toBe(PostStatus::PendingApproval)+ ->and($post->scheduled_at->toIso8601String())->toBe($at)+ ->and($post->approved_by)->toBeNull();+});++test('a null time takes a post scheduled after the request was validated off the schedule', function () {+ $post = reschedulePost($this->channel, $this->user, ['scheduled_at' => CarbonImmutable::parse('2026-10-07 10:00', 'UTC')]);+ $flipped = false;++ Post::retrieved(function (Post $retrieved) use ($post, &$flipped): void {+ if ($flipped || $retrieved->id !== $post->id) {+ return;+ }++ $flipped = true;+ Post::query()->whereKey($post->id)->toBase()->update(['status' => PostStatus::Scheduled->value, 'schedule_mode' => ScheduleMode::Custom->value]);+ });++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => null, 'queue_slot' => true])+ ->assertSessionHasNoErrors();++ $post->refresh();++ expect($post->status)->toBe(PostStatus::Draft)+ ->and($post->scheduled_at)->toBeNull();+});++test('reschedule refuses a time past the 2038 ceiling before it reaches the post', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'content' => 'A caption',+ 'status' => PostStatus::Draft,+ ]);++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => '2038-01-19T00:00:00Z'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('calendar.reschedule.errors.too_far')]);+});++test('reschedule refuses a time sent as a number', function () {+ $post = rescheduleCustom($this->channel, $this->user);++ $this->actingAs($this->user)+ ->putJson(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => 20301231])+ ->assertUnprocessable()+ ->assertJsonValidationErrors('scheduled_at');+});++test('reschedule refuses a malformed time', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $at = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->put(route('app.posts.schedule.update', $post), ['action' => 'reschedule', 'scheduled_at' => 'next tuesday-ish'])+ ->assertRedirect()+ ->assertSessionHasErrors(['scheduled_at' => __('validation.date', ['attribute' => 'scheduled at'])]);++ expect($post->fresh()->scheduled_at->toIso8601String())->toBe($at);+});++test('a schedule action sent as a list is refused instead of failing', function () {+ $post = rescheduleCustom($this->channel, $this->user);+ $at = $post->scheduled_at->toIso8601String();++ $this->actingAs($this->user)+ ->putJson(route('app.posts.schedule.update', $post), ['action' => ['reschedule'], 'scheduled_at' => '2026-10-07 10:00'])+ ->assertUnprocessable()+ ->assertJsonValidationErrors('action');++ expect($post->fresh()->scheduled_at->toIso8601String())->toBe($at);+});diff --git a/tests/Feature/Settings/ProfileUpdateTest.php b/tests/Feature/Settings/ProfileUpdateTest.phpindex 88df9e9ac..e3945543c 100644--- a/tests/Feature/Settings/ProfileUpdateTest.php+++ b/tests/Feature/Settings/ProfileUpdateTest.php@@ -119,7 +119,7 @@ test('user can delete their account', function () {$response->assertSessionHasNoErrors()- ->assertRedirect(route('app.home'));+ ->assertRedirect(route('login'));$this->assertGuest();expect($user->fresh())->toBeNull();diff --git a/tests/Feature/SocialLoginControllerTest.php b/tests/Feature/SocialLoginControllerTest.phpindex 749017e26..600e2ce46 100644--- a/tests/Feature/SocialLoginControllerTest.php+++ b/tests/Feature/SocialLoginControllerTest.php@@ -46,10 +46,35 @@ test('google callback logs in existing user by email', function () {$response = $this->get(route('auth.google.callback'));- $response->assertRedirect(route('app.home'));+ $response->assertRedirect(route('app.calendar'));$this->assertAuthenticatedAs($user);});+test('an existing user signing in with google or github returns to the page that asked for the login', function (string $driver, string $callback, bool $deepLink) {+ $user = User::factory()->create(['email' => '[email protected]']);+ $intended = route('app.insights', ['range' => '30d']);++ $socialiteUser = new SocialiteUser;+ $socialiteUser->map(['id' => 'deep-link', 'name' => 'Deep Link', 'email' => '[email protected]']);++ Socialite::shouldReceive('driver')+ ->with($driver)+ ->andReturn($socialiteDriver = Mockery::mock());+ $socialiteDriver->shouldReceive('user')->andReturn($socialiteUser);++ $this->withSession($deepLink ? ['url.intended' => $intended] : [])+ ->get(route($callback))+ ->assertRedirect($deepLink ? $intended : route('app.calendar'));++ $this->assertAuthenticatedAs($user);+})->with([+ 'google' => ['google-auth', 'auth.google.callback'],+ 'github' => ['github', 'auth.github.callback'],+])->with([+ 'with a deep link' => true,+ 'without one' => false,+]);+test('google callback creates new user when email does not exist', function () {$socialiteUser = new SocialiteUser;$socialiteUser->map([@@ -151,7 +176,7 @@ test('google registration with an invite param completes it instead of creatingexpect($user->workspaces()->count())->toBe(0);});-test('google login with a pending invite sends an existing user there instead of app.home', function () {+test('google login with a pending invite sends an existing user there instead of the calendar', function () {$inviterAccount = Account::factory()->create();$inviter = User::factory()->create(['account_id' => $inviterAccount->id]);$inviterAccount->update(['owner_id' => $inviter->id]);@@ -230,7 +255,7 @@ test('github registration with an invite param completes it instead of creatingexpect($user->workspaces()->count())->toBe(0);});-test('github login with a pending invite sends an existing user there instead of app.home', function () {+test('github login with a pending invite sends an existing user there instead of the calendar', function () {$inviterAccount = Account::factory()->create();$inviter = User::factory()->create(['account_id' => $inviterAccount->id]);$inviterAccount->update(['owner_id' => $inviter->id]);@@ -467,7 +492,7 @@ test('google login for an existing user is never blocked by the self-hosted gate$response = $this->get(route('auth.google.callback'));- $response->assertRedirect(route('app.home'));+ $response->assertRedirect(route('app.calendar'));$this->assertAuthenticatedAs($user);});@@ -547,7 +572,7 @@ test('github login for an existing user is never blocked by the self-hosted gate$response = $this->get(route('auth.github.callback'));- $response->assertRedirect(route('app.home'));+ $response->assertRedirect(route('app.calendar'));$this->assertAuthenticatedAs($user);});diff --git a/tests/Pest.php b/tests/Pest.phpindex c898f16e0..4aaf7f816 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -82,6 +82,22 @@ pest()->tia()->locally();pest()->browser()->timeout(15000);+/*+|--------------------------------------------------------------------------+| Browser Traces+|--------------------------------------------------------------------------+|+| On CI each browser test records a Playwright trace, kept only when the test+| fails, in tests/Browser/Traces (uploaded with the screenshots). Open one+| with `npx playwright show-trace <file>.zip`. Set here and not with --trace,+| which does not reach the parallel workers.+|+*/++if (filled(getenv('CI'))) {+ pest()->browser()->trace(open: false);+}+/*|--------------------------------------------------------------------------| Expectationsdiff --git a/tests/Unit/Enums/Post/ScheduleActionTest.php b/tests/Unit/Enums/Post/ScheduleActionTest.phpnew file mode 100644index 000000000..f981156bf--- /dev/null+++ b/tests/Unit/Enums/Post/ScheduleActionTest.php@@ -0,0 +1,18 @@+<?php++declare(strict_types=1);++use App\Enums\Post\ScheduleAction;++test('each action that only changes the status or queue position maps to its post changes', function (ScheduleAction $action, array $changes) {+ expect($action->postChanges())->toBe($changes);+})->with([+ 'draft' => [ScheduleAction::Draft, ['status' => 'draft']],+ 'publish now' => [ScheduleAction::PublishNow, ['status' => 'publishing']],+ 'queue next' => [ScheduleAction::QueueNext, ['status' => 'scheduled', 'queue' => 'next']],+ 'queue top' => [ScheduleAction::QueueTop, ['status' => 'scheduled', 'queue' => 'top']],+]);++test('reschedule has no post changes because it carries a time', function () {+ expect(fn () => ScheduleAction::Reschedule->postChanges())->toThrow(LogicException::class);+});diff --git a/tests/Unit/ExampleTest.php b/tests/Unit/ExampleTest.phpdeleted file mode 100644index e7ad3f1fa..000000000--- a/tests/Unit/ExampleTest.php+++ /dev/null@@ -1,7 +0,0 @@-<?php--declare(strict_types=1);--test('that true is true', function () {- expect(true)->toBeTrue();-});diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.phpindex 1690e833c..a4c351d26 100644--- a/tests/fixtures/single-line-copy.php+++ b/tests/fixtures/single-line-copy.php@@ -64,6 +64,9 @@ return ['billing.invoices.columns.date' => 10,'billing.invoices.columns.amount' => 7,'billing.invoices.columns.status' => 9,+ 'calendar.reschedule.custom_time.cancel' => 9,+ 'calendar.reschedule.custom_time.confirm' => 26,+ 'calendar.reschedule.custom_time.dont_show_again' => 21,'calendar.title' => 10,'channels.description' => 43,'channels.goal_dialog.description' => 57,