diff --git a/.cursor/rules/laravel-boost.mdc b/.cursor/rules/laravel-boost.mdc index aecaa3e0..f677987c 100644 --- a/.cursor/rules/laravel-boost.mdc +++ b/.cursor/rules/laravel-boost.mdc @@ -11,18 +11,28 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for ## Foundational Context This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. -- php - 8.4.11 +- php - 8.4.18 - filament/filament (FILAMENT) - v3 -- laravel/framework (LARAVEL) - v10 +- laravel/cashier (CASHIER) - v15 +- laravel/framework (LARAVEL) - v12 +- laravel/horizon (HORIZON) - v5 +- laravel/nightwatch (NIGHTWATCH) - v1 +- laravel/pennant (PENNANT) - v1 - laravel/prompts (PROMPTS) - v0 +- laravel/sanctum (SANCTUM) - v4 +- laravel/socialite (SOCIALITE) - v5 - livewire/livewire (LIVEWIRE) - v3 +- laravel/mcp (MCP) - v0 - laravel/pint (PINT) - v1 +- laravel/sail (SAIL) - v1 +- phpunit/phpunit (PHPUNIT) - v11 +- rector/rector (RECTOR) - v2 - alpinejs (ALPINEJS) - v3 +- prettier (PRETTIER) - v3 - tailwindcss (TAILWINDCSS) - v4 - ## Conventions -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming. +- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. - Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. - Check for existing components to reuse before writing a new one. @@ -30,7 +40,7 @@ This application is a Laravel application and its main Laravel ecosystems packag - Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important. ## Application Structure & Architecture -- Stick to existing directory structure - don't create new base folders without approval. +- Stick to existing directory structure; don't create new base folders without approval. - Do not change the application's dependencies without approval. ## Frontend Bundling @@ -42,17 +52,16 @@ This application is a Laravel application and its main Laravel ecosystems packag ## Documentation Files - You must only create documentation files if explicitly requested by the user. - === boost rules === ## Laravel Boost - Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them. ## Artisan -- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters. +- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters. ## URLs -- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port. +- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port. ## Tinker / Debugging - You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly. @@ -63,22 +72,21 @@ This application is a Laravel application and its main Laravel ecosystems packag - Only recent browser logs will be useful - ignore old logs. ## Searching Documentation (Critically Important) -- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. -- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. -- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches. +- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. +- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. +- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches. - Search the documentation before making code changes to ensure we are taking the correct approach. -- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. -- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. +- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. +- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. ### Available Search Syntax - You can and should pass multiple queries at once. The most relevant results will be returned first. -1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth' -2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit" -3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order -4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit" -5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms - +1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'. +2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit". +3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order. +4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit". +5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms. === php rules === @@ -89,7 +97,7 @@ This application is a Laravel application and its main Laravel ecosystems packag ### Constructors - Use PHP 8 constructor property promotion in `__construct()`. - public function __construct(public GitHub $github) { } -- Do not allow empty `__construct()` methods with zero parameters. +- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private. ### Type Declarations - Always use explicit return type declarations for methods and functions. @@ -103,7 +111,7 @@ protected function isAccessible(User $user, ?string $path = null): bool ## Comments -- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on. +- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on. ## PHPDoc Blocks - Add useful array shape type definitions for arrays when appropriate. @@ -111,116 +119,31 @@ protected function isAccessible(User $user, ?string $path = null): bool ## Enums - Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. +=== herd rules === -=== filament/core rules === - -## Filament -- Filament is used by this application, check how and where to follow existing application conventions. -- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS. -- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices. -- Utilize static `make()` methods for consistent component initialization. - -### Artisan -- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option. -- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable. - -### Filament's Core Features -- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input. -- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more. -- Infolists: Read-only lists of data. -- Notifications: Flash notifications displayed to users within the application. -- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets. -- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`. -- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists. -- Tables: Interactive tables with filtering, sorting, pagination, and more. -- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat. - -### Relationships -- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`: - - -Forms\Components\Select::make('user_id') - ->label('Author') - ->relationship('author') - ->required(), - - - -## Testing -- It's important to test Filament functionality for user satisfaction. -- Ensure that you are authenticated to access the application within the test. -- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`. - -### Example Tests - - - livewire(ListUsers::class) - ->assertCanSeeTableRecords($users) - ->searchTable($users->first()->name) - ->assertCanSeeTableRecords($users->take(1)) - ->assertCanNotSeeTableRecords($users->skip(1)) - ->searchTable($users->last()->email) - ->assertCanSeeTableRecords($users->take(-1)) - ->assertCanNotSeeTableRecords($users->take($users->count() - 1)); - - - - livewire(CreateUser::class) - ->fillForm([ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]) - ->call('create') - ->assertNotified() - ->assertRedirect(); - - assertDatabaseHas(User::class, [ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]); - - - - use Filament\Facades\Filament; - - Filament::setCurrentPanel('app'); - - - - livewire(EditInvoice::class, [ - 'invoice' => $invoice, - ])->callAction('send'); - - expect($invoice->refresh())->isSent()->toBeTrue(); - +## Laravel Herd +- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd. -=== filament/v3 rules === - -## Filament 3 +=== tests rules === -## Version 3 Changes To Focus On -- Resources are located in `app/Filament/Resources/` directory. -- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`. -- Forms use the `Forms\Components` namespace for form fields. -- Tables use the `Tables\Columns` namespace for table columns. -- A new `Filament\Forms\Components\RichEditor` component is available. -- Form and table schemas now use fluent method chaining. -- Added `php artisan filament:optimize` command for production optimization. -- Requires implementing `FilamentUser` contract for production access control. +## 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. === laravel/core rules === ## Do Things the Laravel Way - Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. -- If you're creating a generic PHP class, use `artisan make:class`. +- If you're creating a generic PHP class, use `php artisan make:class`. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. ### Database - Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins. -- Use Eloquent models and relationships before suggesting raw database queries +- Use Eloquent models and relationships before suggesting raw database queries. - Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them. - Generate code that prevents N+1 query problems by using eager loading. - Use Laravel's query builder for very complex database operations. @@ -250,33 +173,49 @@ Forms\Components\Select::make('user_id') ### Testing - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - 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] ` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. +- 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`. +=== laravel/v12 rules === -=== laravel/v10 rules === +## Laravel 12 -## Laravel 10 +- Use the `search-docs` tool to get version-specific documentation. +- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure. +- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it. -- Use the `search-docs` tool to get version specific documentation. -- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`. -- There is no `bootstrap/app.php` application configuration in Laravel 10: - - Middleware registration is in `app/Http/Kernel.php` +### Laravel 10 Structure +- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`. +- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure: + - Middleware registration happens in `app/Http/Kernel.php` - Exception handling is in `app/Exceptions/Handler.php` - - Console commands and schedule registration is in `app/Console/Kernel.php` + - Console commands and schedule register in `app/Console/Kernel.php` - Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php` -- When using Eloquent model casts, you must use `protected $casts = [];` and not the `casts()` method. The `casts()` method isn't available on models in Laravel 10. +### Database +- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost. +- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`. + +### Models +- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. + +=== pennant/core rules === + +## Laravel Pennant + +- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types. +- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags. === livewire/core rules === -## Livewire Core -- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests. -- Use the `php artisan make:livewire [Posts\\CreatePost]` artisan command to create new components +## Livewire + +- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. +- Use the `php artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. - State should live on the server, with the UI reflecting it. -- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions. +- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. ## Livewire Best Practices - Livewire components require a single root element. @@ -291,17 +230,16 @@ Forms\Components\Select::make('user_id') @endforeach ``` -- Prefer lifecycle hooks like `mount()`, `updatedFoo()`) for initialization and reactive side effects: +- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects: - + public function mount(User $user) { $this->user = $user; } public function updatedSearch() { $this->resetPage(); } - ## Testing Livewire - + Livewire::test(Counter::class) ->assertSet('count', 0) ->call('increment') @@ -310,19 +248,17 @@ Forms\Components\Select::make('user_id') ->assertStatus(200); - - - $this->get('/posts/create') - ->assertSeeLivewire(CreatePost::class); - - + + $this->get('/posts/create') + ->assertSeeLivewire(CreatePost::class); + === livewire/v3 rules === ## Livewire 3 ### Key Changes From Livewire 2 -- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. +- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. - Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default. - Components now use the `App\Livewire` namespace (not `App\Http\Livewire`). - Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`). @@ -332,13 +268,13 @@ Forms\Components\Select::make('user_id') - `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples. ### Alpine -- Alpine is now included with Livewire, don't manually include Alpine.js. +- Alpine is now included with Livewire; don't manually include Alpine.js. - Plugins included with Alpine: persist, intersect, collapse, and focus. ### Lifecycle Hooks - You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring: - + document.addEventListener('livewire:init', function () { Livewire.hook('request', ({ fail }) => { if (fail && fail.status === 419) { @@ -352,7 +288,6 @@ document.addEventListener('livewire:init', function () { }); - === pint/core rules === ## Laravel Pint Code Formatter @@ -360,50 +295,71 @@ document.addEventListener('livewire:init', function () { - You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style. - Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues. +=== phpunit/core rules === + +## PHPUnit + +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. +- If you see a test using "Pest", convert it to PHPUnit. +- Every time a test has been updated, run that singular test. +- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. +- Tests should test all of the happy paths, failure paths, and weird paths. +- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application. + +### Running Tests +- Run the minimal number of tests, using an appropriate filter, before finalizing. +- To run all tests: `php artisan test --compact`. +- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`. +- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file). === tailwindcss/core rules === -## Tailwind Core +## Tailwind CSS -- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own. -- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..) -- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically +- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own. +- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.). +- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically. - You can use the `search-docs` tool to get exact examples from the official documentation when needed. ### Spacing -- When listing items, use gap utilities for spacing, don't use margins. - - -
-
Superior
-
Michigan
-
Erie
-
-
- +- When listing items, use gap utilities for spacing; don't use margins. + + +
+
Superior
+
Michigan
+
Erie
+
+
### Dark Mode - If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`. - === tailwindcss/v4 rules === -## Tailwind 4 +## Tailwind CSS 4 -- Always use Tailwind CSS v4 - do not use the deprecated utilities. +- Always use Tailwind CSS v4; do not use the deprecated utilities. - `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + - In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: - - @tailwind base; - @tailwind components; - @tailwind utilities; + @import "tailwindcss"; - ### Replaced Utilities -- Tailwind v4 removed deprecated utilities. Do not use the deprecated option - use the replacement. +- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement. - Opacity values are still numeric. | Deprecated | Replacement | @@ -419,12 +375,4 @@ document.addEventListener('livewire:init', function () { | overflow-ellipsis | text-ellipsis | | decoration-slice | box-decoration-slice | | decoration-clone | box-decoration-clone | - - -=== tests rules === - -## 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` with a specific filename or filter. - \ No newline at end of file + diff --git a/.env.example b/.env.example index a82d36de..126e69cd 100644 --- a/.env.example +++ b/.env.example @@ -67,7 +67,10 @@ STRIPE_MINI_PRICE_ID_EAP= STRIPE_PRO_PRICE_ID= STRIPE_PRO_PRICE_ID_EAP= STRIPE_MAX_PRICE_ID= +STRIPE_MAX_PRICE_ID_MONTHLY= STRIPE_MAX_PRICE_ID_EAP= +STRIPE_EXTRA_SEAT_PRICE_ID= +STRIPE_EXTRA_SEAT_PRICE_ID_MONTHLY= STRIPE_FOREVER_PRICE_ID= STRIPE_TRIAL_PRICE_ID= STRIPE_MINI_PAYMENT_LINK= diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index bc83ebc7..126421d1 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -8,18 +8,28 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for ## Foundational Context This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. -- php - 8.4.11 +- php - 8.4.18 - filament/filament (FILAMENT) - v3 -- laravel/framework (LARAVEL) - v10 +- laravel/cashier (CASHIER) - v15 +- laravel/framework (LARAVEL) - v12 +- laravel/horizon (HORIZON) - v5 +- laravel/nightwatch (NIGHTWATCH) - v1 +- laravel/pennant (PENNANT) - v1 - laravel/prompts (PROMPTS) - v0 +- laravel/sanctum (SANCTUM) - v4 +- laravel/socialite (SOCIALITE) - v5 - livewire/livewire (LIVEWIRE) - v3 +- laravel/mcp (MCP) - v0 - laravel/pint (PINT) - v1 +- laravel/sail (SAIL) - v1 +- phpunit/phpunit (PHPUNIT) - v11 +- rector/rector (RECTOR) - v2 - alpinejs (ALPINEJS) - v3 +- prettier (PRETTIER) - v3 - tailwindcss (TAILWINDCSS) - v4 - ## Conventions -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming. +- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. - Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. - Check for existing components to reuse before writing a new one. @@ -27,7 +37,7 @@ This application is a Laravel application and its main Laravel ecosystems packag - Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important. ## Application Structure & Architecture -- Stick to existing directory structure - don't create new base folders without approval. +- Stick to existing directory structure; don't create new base folders without approval. - Do not change the application's dependencies without approval. ## Frontend Bundling @@ -39,17 +49,16 @@ This application is a Laravel application and its main Laravel ecosystems packag ## Documentation Files - You must only create documentation files if explicitly requested by the user. - === boost rules === ## Laravel Boost - Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them. ## Artisan -- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters. +- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters. ## URLs -- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port. +- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port. ## Tinker / Debugging - You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly. @@ -60,22 +69,21 @@ This application is a Laravel application and its main Laravel ecosystems packag - Only recent browser logs will be useful - ignore old logs. ## Searching Documentation (Critically Important) -- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. -- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. -- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches. +- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. +- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. +- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches. - Search the documentation before making code changes to ensure we are taking the correct approach. -- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. -- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. +- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. +- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. ### Available Search Syntax - You can and should pass multiple queries at once. The most relevant results will be returned first. -1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth' -2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit" -3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order -4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit" -5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms - +1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'. +2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit". +3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order. +4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit". +5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms. === php rules === @@ -86,7 +94,7 @@ This application is a Laravel application and its main Laravel ecosystems packag ### Constructors - Use PHP 8 constructor property promotion in `__construct()`. - public function __construct(public GitHub $github) { } -- Do not allow empty `__construct()` methods with zero parameters. +- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private. ### Type Declarations - Always use explicit return type declarations for methods and functions. @@ -100,7 +108,7 @@ protected function isAccessible(User $user, ?string $path = null): bool
## Comments -- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on. +- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on. ## PHPDoc Blocks - Add useful array shape type definitions for arrays when appropriate. @@ -108,116 +116,31 @@ protected function isAccessible(User $user, ?string $path = null): bool ## Enums - Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. +=== herd rules === -=== filament/core rules === - -## Filament -- Filament is used by this application, check how and where to follow existing application conventions. -- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS. -- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices. -- Utilize static `make()` methods for consistent component initialization. - -### Artisan -- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option. -- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable. - -### Filament's Core Features -- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input. -- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more. -- Infolists: Read-only lists of data. -- Notifications: Flash notifications displayed to users within the application. -- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets. -- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`. -- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists. -- Tables: Interactive tables with filtering, sorting, pagination, and more. -- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat. - -### Relationships -- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`: - - -Forms\Components\Select::make('user_id') - ->label('Author') - ->relationship('author') - ->required(), - - - -## Testing -- It's important to test Filament functionality for user satisfaction. -- Ensure that you are authenticated to access the application within the test. -- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`. - -### Example Tests - - - livewire(ListUsers::class) - ->assertCanSeeTableRecords($users) - ->searchTable($users->first()->name) - ->assertCanSeeTableRecords($users->take(1)) - ->assertCanNotSeeTableRecords($users->skip(1)) - ->searchTable($users->last()->email) - ->assertCanSeeTableRecords($users->take(-1)) - ->assertCanNotSeeTableRecords($users->take($users->count() - 1)); - - - - livewire(CreateUser::class) - ->fillForm([ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]) - ->call('create') - ->assertNotified() - ->assertRedirect(); - - assertDatabaseHas(User::class, [ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]); - - - - use Filament\Facades\Filament; - - Filament::setCurrentPanel('app'); - - - - livewire(EditInvoice::class, [ - 'invoice' => $invoice, - ])->callAction('send'); - - expect($invoice->refresh())->isSent()->toBeTrue(); - +## Laravel Herd +- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd. -=== filament/v3 rules === - -## Filament 3 +=== tests rules === -## Version 3 Changes To Focus On -- Resources are located in `app/Filament/Resources/` directory. -- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`. -- Forms use the `Forms\Components` namespace for form fields. -- Tables use the `Tables\Columns` namespace for table columns. -- A new `Filament\Forms\Components\RichEditor` component is available. -- Form and table schemas now use fluent method chaining. -- Added `php artisan filament:optimize` command for production optimization. -- Requires implementing `FilamentUser` contract for production access control. +## 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. === laravel/core rules === ## Do Things the Laravel Way - Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. -- If you're creating a generic PHP class, use `artisan make:class`. +- If you're creating a generic PHP class, use `php artisan make:class`. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. ### Database - Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins. -- Use Eloquent models and relationships before suggesting raw database queries +- Use Eloquent models and relationships before suggesting raw database queries. - Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them. - Generate code that prevents N+1 query problems by using eager loading. - Use Laravel's query builder for very complex database operations. @@ -247,33 +170,49 @@ Forms\Components\Select::make('user_id') ### Testing - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - 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] ` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. +- 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`. +=== laravel/v12 rules === -=== laravel/v10 rules === +## Laravel 12 -## Laravel 10 +- Use the `search-docs` tool to get version-specific documentation. +- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure. +- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it. -- Use the `search-docs` tool to get version specific documentation. -- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`. -- There is no `bootstrap/app.php` application configuration in Laravel 10: - - Middleware registration is in `app/Http/Kernel.php` +### Laravel 10 Structure +- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`. +- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure: + - Middleware registration happens in `app/Http/Kernel.php` - Exception handling is in `app/Exceptions/Handler.php` - - Console commands and schedule registration is in `app/Console/Kernel.php` + - Console commands and schedule register in `app/Console/Kernel.php` - Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php` -- When using Eloquent model casts, you must use `protected $casts = [];` and not the `casts()` method. The `casts()` method isn't available on models in Laravel 10. +### Database +- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost. +- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`. + +### Models +- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. + +=== pennant/core rules === + +## Laravel Pennant + +- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types. +- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags. === livewire/core rules === -## Livewire Core -- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests. -- Use the `php artisan make:livewire [Posts\\CreatePost]` artisan command to create new components +## Livewire + +- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. +- Use the `php artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. - State should live on the server, with the UI reflecting it. -- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions. +- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. ## Livewire Best Practices - Livewire components require a single root element. @@ -288,17 +227,16 @@ Forms\Components\Select::make('user_id') @endforeach ``` -- Prefer lifecycle hooks like `mount()`, `updatedFoo()`) for initialization and reactive side effects: +- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects: - + public function mount(User $user) { $this->user = $user; } public function updatedSearch() { $this->resetPage(); } - ## Testing Livewire - + Livewire::test(Counter::class) ->assertSet('count', 0) ->call('increment') @@ -307,19 +245,17 @@ Forms\Components\Select::make('user_id') ->assertStatus(200); - - - $this->get('/posts/create') - ->assertSeeLivewire(CreatePost::class); - - + + $this->get('/posts/create') + ->assertSeeLivewire(CreatePost::class); + === livewire/v3 rules === ## Livewire 3 ### Key Changes From Livewire 2 -- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. +- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. - Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default. - Components now use the `App\Livewire` namespace (not `App\Http\Livewire`). - Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`). @@ -329,13 +265,13 @@ Forms\Components\Select::make('user_id') - `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples. ### Alpine -- Alpine is now included with Livewire, don't manually include Alpine.js. +- Alpine is now included with Livewire; don't manually include Alpine.js. - Plugins included with Alpine: persist, intersect, collapse, and focus. ### Lifecycle Hooks - You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring: - + document.addEventListener('livewire:init', function () { Livewire.hook('request', ({ fail }) => { if (fail && fail.status === 419) { @@ -349,7 +285,6 @@ document.addEventListener('livewire:init', function () { }); - === pint/core rules === ## Laravel Pint Code Formatter @@ -357,50 +292,71 @@ document.addEventListener('livewire:init', function () { - You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style. - Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues. +=== phpunit/core rules === + +## PHPUnit + +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. +- If you see a test using "Pest", convert it to PHPUnit. +- Every time a test has been updated, run that singular test. +- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. +- Tests should test all of the happy paths, failure paths, and weird paths. +- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application. + +### Running Tests +- Run the minimal number of tests, using an appropriate filter, before finalizing. +- To run all tests: `php artisan test --compact`. +- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`. +- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file). === tailwindcss/core rules === -## Tailwind Core +## Tailwind CSS -- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own. -- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..) -- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically +- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own. +- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.). +- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically. - You can use the `search-docs` tool to get exact examples from the official documentation when needed. ### Spacing -- When listing items, use gap utilities for spacing, don't use margins. - - -
-
Superior
-
Michigan
-
Erie
-
-
- +- When listing items, use gap utilities for spacing; don't use margins. + + +
+
Superior
+
Michigan
+
Erie
+
+
### Dark Mode - If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`. - === tailwindcss/v4 rules === -## Tailwind 4 +## Tailwind CSS 4 -- Always use Tailwind CSS v4 - do not use the deprecated utilities. +- Always use Tailwind CSS v4; do not use the deprecated utilities. - `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + - In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: - - @tailwind base; - @tailwind components; - @tailwind utilities; + @import "tailwindcss"; - ### Replaced Utilities -- Tailwind v4 removed deprecated utilities. Do not use the deprecated option - use the replacement. +- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement. - Opacity values are still numeric. | Deprecated | Replacement | @@ -416,12 +372,4 @@ document.addEventListener('livewire:init', function () { | overflow-ellipsis | text-ellipsis | | decoration-slice | box-decoration-slice | | decoration-clone | box-decoration-clone | - - -=== tests rules === - -## 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` with a specific filename or filter. - \ No newline at end of file + diff --git a/.junie/guidelines.md b/.junie/guidelines.md index bc83ebc7..126421d1 100644 --- a/.junie/guidelines.md +++ b/.junie/guidelines.md @@ -8,18 +8,28 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for ## Foundational Context This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. -- php - 8.4.11 +- php - 8.4.18 - filament/filament (FILAMENT) - v3 -- laravel/framework (LARAVEL) - v10 +- laravel/cashier (CASHIER) - v15 +- laravel/framework (LARAVEL) - v12 +- laravel/horizon (HORIZON) - v5 +- laravel/nightwatch (NIGHTWATCH) - v1 +- laravel/pennant (PENNANT) - v1 - laravel/prompts (PROMPTS) - v0 +- laravel/sanctum (SANCTUM) - v4 +- laravel/socialite (SOCIALITE) - v5 - livewire/livewire (LIVEWIRE) - v3 +- laravel/mcp (MCP) - v0 - laravel/pint (PINT) - v1 +- laravel/sail (SAIL) - v1 +- phpunit/phpunit (PHPUNIT) - v11 +- rector/rector (RECTOR) - v2 - alpinejs (ALPINEJS) - v3 +- prettier (PRETTIER) - v3 - tailwindcss (TAILWINDCSS) - v4 - ## Conventions -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming. +- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. - Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. - Check for existing components to reuse before writing a new one. @@ -27,7 +37,7 @@ This application is a Laravel application and its main Laravel ecosystems packag - Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important. ## Application Structure & Architecture -- Stick to existing directory structure - don't create new base folders without approval. +- Stick to existing directory structure; don't create new base folders without approval. - Do not change the application's dependencies without approval. ## Frontend Bundling @@ -39,17 +49,16 @@ This application is a Laravel application and its main Laravel ecosystems packag ## Documentation Files - You must only create documentation files if explicitly requested by the user. - === boost rules === ## Laravel Boost - Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them. ## Artisan -- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters. +- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters. ## URLs -- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port. +- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port. ## Tinker / Debugging - You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly. @@ -60,22 +69,21 @@ This application is a Laravel application and its main Laravel ecosystems packag - Only recent browser logs will be useful - ignore old logs. ## Searching Documentation (Critically Important) -- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. -- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. -- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches. +- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. +- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. +- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches. - Search the documentation before making code changes to ensure we are taking the correct approach. -- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. -- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. +- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. +- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. ### Available Search Syntax - You can and should pass multiple queries at once. The most relevant results will be returned first. -1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth' -2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit" -3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order -4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit" -5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms - +1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'. +2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit". +3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order. +4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit". +5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms. === php rules === @@ -86,7 +94,7 @@ This application is a Laravel application and its main Laravel ecosystems packag ### Constructors - Use PHP 8 constructor property promotion in `__construct()`. - public function __construct(public GitHub $github) { } -- Do not allow empty `__construct()` methods with zero parameters. +- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private. ### Type Declarations - Always use explicit return type declarations for methods and functions. @@ -100,7 +108,7 @@ protected function isAccessible(User $user, ?string $path = null): bool
## Comments -- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on. +- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on. ## PHPDoc Blocks - Add useful array shape type definitions for arrays when appropriate. @@ -108,116 +116,31 @@ protected function isAccessible(User $user, ?string $path = null): bool ## Enums - Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. +=== herd rules === -=== filament/core rules === - -## Filament -- Filament is used by this application, check how and where to follow existing application conventions. -- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS. -- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices. -- Utilize static `make()` methods for consistent component initialization. - -### Artisan -- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option. -- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable. - -### Filament's Core Features -- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input. -- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more. -- Infolists: Read-only lists of data. -- Notifications: Flash notifications displayed to users within the application. -- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets. -- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`. -- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists. -- Tables: Interactive tables with filtering, sorting, pagination, and more. -- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat. - -### Relationships -- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`: - - -Forms\Components\Select::make('user_id') - ->label('Author') - ->relationship('author') - ->required(), - - - -## Testing -- It's important to test Filament functionality for user satisfaction. -- Ensure that you are authenticated to access the application within the test. -- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`. - -### Example Tests - - - livewire(ListUsers::class) - ->assertCanSeeTableRecords($users) - ->searchTable($users->first()->name) - ->assertCanSeeTableRecords($users->take(1)) - ->assertCanNotSeeTableRecords($users->skip(1)) - ->searchTable($users->last()->email) - ->assertCanSeeTableRecords($users->take(-1)) - ->assertCanNotSeeTableRecords($users->take($users->count() - 1)); - - - - livewire(CreateUser::class) - ->fillForm([ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]) - ->call('create') - ->assertNotified() - ->assertRedirect(); - - assertDatabaseHas(User::class, [ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]); - - - - use Filament\Facades\Filament; - - Filament::setCurrentPanel('app'); - - - - livewire(EditInvoice::class, [ - 'invoice' => $invoice, - ])->callAction('send'); - - expect($invoice->refresh())->isSent()->toBeTrue(); - +## Laravel Herd +- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd. -=== filament/v3 rules === - -## Filament 3 +=== tests rules === -## Version 3 Changes To Focus On -- Resources are located in `app/Filament/Resources/` directory. -- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`. -- Forms use the `Forms\Components` namespace for form fields. -- Tables use the `Tables\Columns` namespace for table columns. -- A new `Filament\Forms\Components\RichEditor` component is available. -- Form and table schemas now use fluent method chaining. -- Added `php artisan filament:optimize` command for production optimization. -- Requires implementing `FilamentUser` contract for production access control. +## 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. === laravel/core rules === ## Do Things the Laravel Way - Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. -- If you're creating a generic PHP class, use `artisan make:class`. +- If you're creating a generic PHP class, use `php artisan make:class`. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. ### Database - Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins. -- Use Eloquent models and relationships before suggesting raw database queries +- Use Eloquent models and relationships before suggesting raw database queries. - Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them. - Generate code that prevents N+1 query problems by using eager loading. - Use Laravel's query builder for very complex database operations. @@ -247,33 +170,49 @@ Forms\Components\Select::make('user_id') ### Testing - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - 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] ` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. +- 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`. +=== laravel/v12 rules === -=== laravel/v10 rules === +## Laravel 12 -## Laravel 10 +- Use the `search-docs` tool to get version-specific documentation. +- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure. +- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it. -- Use the `search-docs` tool to get version specific documentation. -- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`. -- There is no `bootstrap/app.php` application configuration in Laravel 10: - - Middleware registration is in `app/Http/Kernel.php` +### Laravel 10 Structure +- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`. +- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure: + - Middleware registration happens in `app/Http/Kernel.php` - Exception handling is in `app/Exceptions/Handler.php` - - Console commands and schedule registration is in `app/Console/Kernel.php` + - Console commands and schedule register in `app/Console/Kernel.php` - Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php` -- When using Eloquent model casts, you must use `protected $casts = [];` and not the `casts()` method. The `casts()` method isn't available on models in Laravel 10. +### Database +- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost. +- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`. + +### Models +- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. + +=== pennant/core rules === + +## Laravel Pennant + +- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types. +- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags. === livewire/core rules === -## Livewire Core -- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests. -- Use the `php artisan make:livewire [Posts\\CreatePost]` artisan command to create new components +## Livewire + +- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. +- Use the `php artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. - State should live on the server, with the UI reflecting it. -- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions. +- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. ## Livewire Best Practices - Livewire components require a single root element. @@ -288,17 +227,16 @@ Forms\Components\Select::make('user_id') @endforeach ``` -- Prefer lifecycle hooks like `mount()`, `updatedFoo()`) for initialization and reactive side effects: +- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects: - + public function mount(User $user) { $this->user = $user; } public function updatedSearch() { $this->resetPage(); } - ## Testing Livewire - + Livewire::test(Counter::class) ->assertSet('count', 0) ->call('increment') @@ -307,19 +245,17 @@ Forms\Components\Select::make('user_id') ->assertStatus(200); - - - $this->get('/posts/create') - ->assertSeeLivewire(CreatePost::class); - - + + $this->get('/posts/create') + ->assertSeeLivewire(CreatePost::class); + === livewire/v3 rules === ## Livewire 3 ### Key Changes From Livewire 2 -- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. +- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. - Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default. - Components now use the `App\Livewire` namespace (not `App\Http\Livewire`). - Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`). @@ -329,13 +265,13 @@ Forms\Components\Select::make('user_id') - `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples. ### Alpine -- Alpine is now included with Livewire, don't manually include Alpine.js. +- Alpine is now included with Livewire; don't manually include Alpine.js. - Plugins included with Alpine: persist, intersect, collapse, and focus. ### Lifecycle Hooks - You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring: - + document.addEventListener('livewire:init', function () { Livewire.hook('request', ({ fail }) => { if (fail && fail.status === 419) { @@ -349,7 +285,6 @@ document.addEventListener('livewire:init', function () { }); - === pint/core rules === ## Laravel Pint Code Formatter @@ -357,50 +292,71 @@ document.addEventListener('livewire:init', function () { - You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style. - Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues. +=== phpunit/core rules === + +## PHPUnit + +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. +- If you see a test using "Pest", convert it to PHPUnit. +- Every time a test has been updated, run that singular test. +- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. +- Tests should test all of the happy paths, failure paths, and weird paths. +- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application. + +### Running Tests +- Run the minimal number of tests, using an appropriate filter, before finalizing. +- To run all tests: `php artisan test --compact`. +- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`. +- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file). === tailwindcss/core rules === -## Tailwind Core +## Tailwind CSS -- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own. -- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..) -- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically +- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own. +- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.). +- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically. - You can use the `search-docs` tool to get exact examples from the official documentation when needed. ### Spacing -- When listing items, use gap utilities for spacing, don't use margins. - - -
-
Superior
-
Michigan
-
Erie
-
-
- +- When listing items, use gap utilities for spacing; don't use margins. + + +
+
Superior
+
Michigan
+
Erie
+
+
### Dark Mode - If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`. - === tailwindcss/v4 rules === -## Tailwind 4 +## Tailwind CSS 4 -- Always use Tailwind CSS v4 - do not use the deprecated utilities. +- Always use Tailwind CSS v4; do not use the deprecated utilities. - `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + - In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: - - @tailwind base; - @tailwind components; - @tailwind utilities; + @import "tailwindcss"; - ### Replaced Utilities -- Tailwind v4 removed deprecated utilities. Do not use the deprecated option - use the replacement. +- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement. - Opacity values are still numeric. | Deprecated | Replacement | @@ -416,12 +372,4 @@ document.addEventListener('livewire:init', function () { | overflow-ellipsis | text-ellipsis | | decoration-slice | box-decoration-slice | | decoration-clone | box-decoration-clone | - - -=== tests rules === - -## 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` with a specific filename or filter. - \ No newline at end of file + diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..126421d1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,375 @@ + +=== foundation rules === + +# Laravel Boost Guidelines + +The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications. + +## Foundational Context +This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. + +- php - 8.4.18 +- filament/filament (FILAMENT) - v3 +- laravel/cashier (CASHIER) - v15 +- laravel/framework (LARAVEL) - v12 +- laravel/horizon (HORIZON) - v5 +- laravel/nightwatch (NIGHTWATCH) - v1 +- laravel/pennant (PENNANT) - v1 +- laravel/prompts (PROMPTS) - v0 +- laravel/sanctum (SANCTUM) - v4 +- laravel/socialite (SOCIALITE) - v5 +- livewire/livewire (LIVEWIRE) - v3 +- laravel/mcp (MCP) - v0 +- laravel/pint (PINT) - v1 +- laravel/sail (SAIL) - v1 +- phpunit/phpunit (PHPUNIT) - v11 +- rector/rector (RECTOR) - v2 +- alpinejs (ALPINEJS) - v3 +- prettier (PRETTIER) - v3 +- tailwindcss (TAILWINDCSS) - v4 + +## Conventions +- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. +- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. +- Check for existing components to reuse before writing a new one. + +## Verification Scripts +- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important. + +## Application Structure & Architecture +- Stick to existing directory structure; don't create new base folders without approval. +- Do not change the application's dependencies without approval. + +## 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. + +## Replies +- Be concise in your explanations - focus on what's important rather than explaining obvious details. + +## Documentation Files +- You must only create documentation files if explicitly requested by the user. + +=== boost rules === + +## Laravel Boost +- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them. + +## Artisan +- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters. + +## URLs +- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port. + +## Tinker / Debugging +- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly. +- Use the `database-query` tool when you only need to read from the database. + +## Reading Browser Logs With the `browser-logs` Tool +- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost. +- Only recent browser logs will be useful - ignore old logs. + +## Searching Documentation (Critically Important) +- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. +- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. +- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches. +- Search the documentation before making code changes to ensure we are taking the correct approach. +- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. +- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. + +### Available Search Syntax +- You can and should pass multiple queries at once. The most relevant results will be returned first. + +1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'. +2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit". +3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order. +4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit". +5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms. + +=== php rules === + +## PHP + +- Always use curly braces for control structures, even if it has one line. + +### Constructors +- Use PHP 8 constructor property promotion in `__construct()`. + - public function __construct(public GitHub $github) { } +- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private. + +### Type Declarations +- Always use explicit return type declarations for methods and functions. +- Use appropriate PHP type hints for method parameters. + + +protected function isAccessible(User $user, ?string $path = null): bool +{ + ... +} + + +## Comments +- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on. + +## PHPDoc Blocks +- Add useful array shape type definitions for arrays when appropriate. + +## Enums +- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. + +=== herd rules === + +## Laravel Herd + +- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd. + +=== tests rules === + +## 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. + +=== laravel/core rules === + +## Do Things the Laravel Way + +- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. +- If you're creating a generic PHP class, use `php artisan make:class`. +- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. + +### Database +- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins. +- Use Eloquent models and relationships before suggesting raw database queries. +- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them. +- Generate code that prevents N+1 query problems by using eager loading. +- Use Laravel's query builder for very complex database operations. + +### Model Creation +- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`. + +### APIs & Eloquent Resources +- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention. + +### Controllers & Validation +- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages. +- Check sibling Form Requests to see if the application uses array or string based validation rules. + +### Queues +- Use queued jobs for time-consuming operations with the `ShouldQueue` interface. + +### Authentication & Authorization +- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.). + +### URL Generation +- When generating links to other pages, prefer named routes and the `route()` function. + +### Configuration +- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`. + +### Testing +- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. +- 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`. + +=== laravel/v12 rules === + +## Laravel 12 + +- Use the `search-docs` tool to get version-specific documentation. +- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure. +- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it. + +### Laravel 10 Structure +- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`. +- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure: + - Middleware registration happens in `app/Http/Kernel.php` + - Exception handling is in `app/Exceptions/Handler.php` + - Console commands and schedule register in `app/Console/Kernel.php` + - Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php` + +### Database +- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost. +- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`. + +### Models +- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. + +=== pennant/core rules === + +## Laravel Pennant + +- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types. +- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags. + +=== livewire/core rules === + +## Livewire + +- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. +- Use the `php artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. +- State should live on the server, with the UI reflecting it. +- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. + +## Livewire Best Practices +- Livewire components require a single root element. +- Use `wire:loading` and `wire:dirty` for delightful loading states. +- Add `wire:key` in loops: + + ```blade + @foreach ($items as $item) +
+ {{ $item->name }} +
+ @endforeach + ``` + +- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects: + + + public function mount(User $user) { $this->user = $user; } + public function updatedSearch() { $this->resetPage(); } + + +## Testing Livewire + + + Livewire::test(Counter::class) + ->assertSet('count', 0) + ->call('increment') + ->assertSet('count', 1) + ->assertSee(1) + ->assertStatus(200); + + + + $this->get('/posts/create') + ->assertSeeLivewire(CreatePost::class); + + +=== livewire/v3 rules === + +## Livewire 3 + +### Key Changes From Livewire 2 +- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. + - Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default. + - Components now use the `App\Livewire` namespace (not `App\Http\Livewire`). + - Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`). + - Use the `components.layouts.app` view as the typical layout path (not `layouts.app`). + +### New Directives +- `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples. + +### Alpine +- Alpine is now included with Livewire; don't manually include Alpine.js. +- Plugins included with Alpine: persist, intersect, collapse, and focus. + +### Lifecycle Hooks +- You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring: + + +document.addEventListener('livewire:init', function () { + Livewire.hook('request', ({ fail }) => { + if (fail && fail.status === 419) { + alert('Your session expired'); + } + }); + + Livewire.hook('message.failed', (message, component) => { + console.error(message); + }); +}); + + +=== pint/core rules === + +## Laravel Pint Code Formatter + +- You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style. +- Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues. + +=== phpunit/core rules === + +## PHPUnit + +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. +- If you see a test using "Pest", convert it to PHPUnit. +- Every time a test has been updated, run that singular test. +- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. +- Tests should test all of the happy paths, failure paths, and weird paths. +- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application. + +### Running Tests +- Run the minimal number of tests, using an appropriate filter, before finalizing. +- To run all tests: `php artisan test --compact`. +- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`. +- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file). + +=== tailwindcss/core rules === + +## Tailwind CSS + +- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own. +- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.). +- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically. +- You can use the `search-docs` tool to get exact examples from the official documentation when needed. + +### Spacing +- When listing items, use gap utilities for spacing; don't use margins. + + +
+
Superior
+
Michigan
+
Erie
+
+
+ +### Dark Mode +- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`. + +=== tailwindcss/v4 rules === + +## Tailwind CSS 4 + +- Always use Tailwind CSS v4; do not use the deprecated utilities. +- `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + +- In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: + + + - @tailwind base; + - @tailwind components; + - @tailwind utilities; + + @import "tailwindcss"; + + +### Replaced Utilities +- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement. +- Opacity values are still numeric. + +| Deprecated | Replacement | +|------------+--------------| +| bg-opacity-* | bg-black/* | +| text-opacity-* | text-black/* | +| border-opacity-* | border-black/* | +| divide-opacity-* | divide-black/* | +| ring-opacity-* | ring-black/* | +| placeholder-opacity-* | placeholder-black/* | +| flex-shrink-* | shrink-* | +| flex-grow-* | grow-* | +| overflow-ellipsis | text-ellipsis | +| decoration-slice | box-decoration-slice | +| decoration-clone | box-decoration-clone | +
diff --git a/CLAUDE.md b/CLAUDE.md index bc83ebc7..126421d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,18 +8,28 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for ## Foundational Context This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions. -- php - 8.4.11 +- php - 8.4.18 - filament/filament (FILAMENT) - v3 -- laravel/framework (LARAVEL) - v10 +- laravel/cashier (CASHIER) - v15 +- laravel/framework (LARAVEL) - v12 +- laravel/horizon (HORIZON) - v5 +- laravel/nightwatch (NIGHTWATCH) - v1 +- laravel/pennant (PENNANT) - v1 - laravel/prompts (PROMPTS) - v0 +- laravel/sanctum (SANCTUM) - v4 +- laravel/socialite (SOCIALITE) - v5 - livewire/livewire (LIVEWIRE) - v3 +- laravel/mcp (MCP) - v0 - laravel/pint (PINT) - v1 +- laravel/sail (SAIL) - v1 +- phpunit/phpunit (PHPUNIT) - v11 +- rector/rector (RECTOR) - v2 - alpinejs (ALPINEJS) - v3 +- prettier (PRETTIER) - v3 - tailwindcss (TAILWINDCSS) - v4 - ## Conventions -- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming. +- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming. - Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`. - Check for existing components to reuse before writing a new one. @@ -27,7 +37,7 @@ This application is a Laravel application and its main Laravel ecosystems packag - Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important. ## Application Structure & Architecture -- Stick to existing directory structure - don't create new base folders without approval. +- Stick to existing directory structure; don't create new base folders without approval. - Do not change the application's dependencies without approval. ## Frontend Bundling @@ -39,17 +49,16 @@ This application is a Laravel application and its main Laravel ecosystems packag ## Documentation Files - You must only create documentation files if explicitly requested by the user. - === boost rules === ## Laravel Boost - Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them. ## Artisan -- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters. +- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters. ## URLs -- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port. +- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port. ## Tinker / Debugging - You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly. @@ -60,22 +69,21 @@ This application is a Laravel application and its main Laravel ecosystems packag - Only recent browser logs will be useful - ignore old logs. ## Searching Documentation (Critically Important) -- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. -- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. -- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches. +- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages. +- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc. +- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches. - Search the documentation before making code changes to ensure we are taking the correct approach. -- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. -- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. +- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`. +- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`. ### Available Search Syntax - You can and should pass multiple queries at once. The most relevant results will be returned first. -1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth' -2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit" -3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order -4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit" -5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms - +1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'. +2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit". +3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order. +4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit". +5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms. === php rules === @@ -86,7 +94,7 @@ This application is a Laravel application and its main Laravel ecosystems packag ### Constructors - Use PHP 8 constructor property promotion in `__construct()`. - public function __construct(public GitHub $github) { } -- Do not allow empty `__construct()` methods with zero parameters. +- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private. ### Type Declarations - Always use explicit return type declarations for methods and functions. @@ -100,7 +108,7 @@ protected function isAccessible(User $user, ?string $path = null): bool
## Comments -- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on. +- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on. ## PHPDoc Blocks - Add useful array shape type definitions for arrays when appropriate. @@ -108,116 +116,31 @@ protected function isAccessible(User $user, ?string $path = null): bool ## Enums - Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`. +=== herd rules === -=== filament/core rules === - -## Filament -- Filament is used by this application, check how and where to follow existing application conventions. -- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS. -- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices. -- Utilize static `make()` methods for consistent component initialization. - -### Artisan -- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option. -- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable. - -### Filament's Core Features -- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input. -- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more. -- Infolists: Read-only lists of data. -- Notifications: Flash notifications displayed to users within the application. -- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets. -- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`. -- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists. -- Tables: Interactive tables with filtering, sorting, pagination, and more. -- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat. - -### Relationships -- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`: - - -Forms\Components\Select::make('user_id') - ->label('Author') - ->relationship('author') - ->required(), - - - -## Testing -- It's important to test Filament functionality for user satisfaction. -- Ensure that you are authenticated to access the application within the test. -- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`. - -### Example Tests - - - livewire(ListUsers::class) - ->assertCanSeeTableRecords($users) - ->searchTable($users->first()->name) - ->assertCanSeeTableRecords($users->take(1)) - ->assertCanNotSeeTableRecords($users->skip(1)) - ->searchTable($users->last()->email) - ->assertCanSeeTableRecords($users->take(-1)) - ->assertCanNotSeeTableRecords($users->take($users->count() - 1)); - - - - livewire(CreateUser::class) - ->fillForm([ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]) - ->call('create') - ->assertNotified() - ->assertRedirect(); - - assertDatabaseHas(User::class, [ - 'name' => 'Howdy', - 'email' => 'howdy@example.com', - ]); - - - - use Filament\Facades\Filament; - - Filament::setCurrentPanel('app'); - - - - livewire(EditInvoice::class, [ - 'invoice' => $invoice, - ])->callAction('send'); - - expect($invoice->refresh())->isSent()->toBeTrue(); - +## Laravel Herd +- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs. +- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd. -=== filament/v3 rules === - -## Filament 3 +=== tests rules === -## Version 3 Changes To Focus On -- Resources are located in `app/Filament/Resources/` directory. -- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`. -- Forms use the `Forms\Components` namespace for form fields. -- Tables use the `Tables\Columns` namespace for table columns. -- A new `Filament\Forms\Components\RichEditor` component is available. -- Form and table schemas now use fluent method chaining. -- Added `php artisan filament:optimize` command for production optimization. -- Requires implementing `FilamentUser` contract for production access control. +## 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. === laravel/core rules === ## Do Things the Laravel Way - Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool. -- If you're creating a generic PHP class, use `artisan make:class`. +- If you're creating a generic PHP class, use `php artisan make:class`. - Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior. ### Database - Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins. -- Use Eloquent models and relationships before suggesting raw database queries +- Use Eloquent models and relationships before suggesting raw database queries. - Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them. - Generate code that prevents N+1 query problems by using eager loading. - Use Laravel's query builder for very complex database operations. @@ -247,33 +170,49 @@ Forms\Components\Select::make('user_id') ### Testing - When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model. - 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] ` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests. +- 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`. +=== laravel/v12 rules === -=== laravel/v10 rules === +## Laravel 12 -## Laravel 10 +- Use the `search-docs` tool to get version-specific documentation. +- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure. +- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it. -- Use the `search-docs` tool to get version specific documentation. -- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`. -- There is no `bootstrap/app.php` application configuration in Laravel 10: - - Middleware registration is in `app/Http/Kernel.php` +### Laravel 10 Structure +- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`. +- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure: + - Middleware registration happens in `app/Http/Kernel.php` - Exception handling is in `app/Exceptions/Handler.php` - - Console commands and schedule registration is in `app/Console/Kernel.php` + - Console commands and schedule register in `app/Console/Kernel.php` - Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php` -- When using Eloquent model casts, you must use `protected $casts = [];` and not the `casts()` method. The `casts()` method isn't available on models in Laravel 10. +### Database +- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost. +- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`. + +### Models +- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models. + +=== pennant/core rules === + +## Laravel Pennant + +- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types. +- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags. === livewire/core rules === -## Livewire Core -- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests. -- Use the `php artisan make:livewire [Posts\\CreatePost]` artisan command to create new components +## Livewire + +- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests. +- Use the `php artisan make:livewire [Posts\CreatePost]` Artisan command to create new components. - State should live on the server, with the UI reflecting it. -- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions. +- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions. ## Livewire Best Practices - Livewire components require a single root element. @@ -288,17 +227,16 @@ Forms\Components\Select::make('user_id') @endforeach ``` -- Prefer lifecycle hooks like `mount()`, `updatedFoo()`) for initialization and reactive side effects: +- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects: - + public function mount(User $user) { $this->user = $user; } public function updatedSearch() { $this->resetPage(); } - ## Testing Livewire - + Livewire::test(Counter::class) ->assertSet('count', 0) ->call('increment') @@ -307,19 +245,17 @@ Forms\Components\Select::make('user_id') ->assertStatus(200); - - - $this->get('/posts/create') - ->assertSeeLivewire(CreatePost::class); - - + + $this->get('/posts/create') + ->assertSeeLivewire(CreatePost::class); + === livewire/v3 rules === ## Livewire 3 ### Key Changes From Livewire 2 -- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. +- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions. - Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default. - Components now use the `App\Livewire` namespace (not `App\Http\Livewire`). - Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`). @@ -329,13 +265,13 @@ Forms\Components\Select::make('user_id') - `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples. ### Alpine -- Alpine is now included with Livewire, don't manually include Alpine.js. +- Alpine is now included with Livewire; don't manually include Alpine.js. - Plugins included with Alpine: persist, intersect, collapse, and focus. ### Lifecycle Hooks - You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring: - + document.addEventListener('livewire:init', function () { Livewire.hook('request', ({ fail }) => { if (fail && fail.status === 419) { @@ -349,7 +285,6 @@ document.addEventListener('livewire:init', function () { }); - === pint/core rules === ## Laravel Pint Code Formatter @@ -357,50 +292,71 @@ document.addEventListener('livewire:init', function () { - You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style. - Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues. +=== phpunit/core rules === + +## PHPUnit + +- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit {name}` to create a new test. +- If you see a test using "Pest", convert it to PHPUnit. +- Every time a test has been updated, run that singular test. +- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing. +- Tests should test all of the happy paths, failure paths, and weird paths. +- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application. + +### Running Tests +- Run the minimal number of tests, using an appropriate filter, before finalizing. +- To run all tests: `php artisan test --compact`. +- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`. +- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file). === tailwindcss/core rules === -## Tailwind Core +## Tailwind CSS -- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own. -- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..) -- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically +- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own. +- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.). +- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically. - You can use the `search-docs` tool to get exact examples from the official documentation when needed. ### Spacing -- When listing items, use gap utilities for spacing, don't use margins. - - -
-
Superior
-
Michigan
-
Erie
-
-
- +- When listing items, use gap utilities for spacing; don't use margins. + + +
+
Superior
+
Michigan
+
Erie
+
+
### Dark Mode - If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`. - === tailwindcss/v4 rules === -## Tailwind 4 +## Tailwind CSS 4 -- Always use Tailwind CSS v4 - do not use the deprecated utilities. +- Always use Tailwind CSS v4; do not use the deprecated utilities. - `corePlugins` is not supported in Tailwind v4. +- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed. + + +@theme { + --color-brand: oklch(0.72 0.11 178); +} + + - In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3: - - @tailwind base; - @tailwind components; - @tailwind utilities; + @import "tailwindcss"; - ### Replaced Utilities -- Tailwind v4 removed deprecated utilities. Do not use the deprecated option - use the replacement. +- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement. - Opacity values are still numeric. | Deprecated | Replacement | @@ -416,12 +372,4 @@ document.addEventListener('livewire:init', function () { | overflow-ellipsis | text-ellipsis | | decoration-slice | box-decoration-slice | | decoration-clone | box-decoration-clone | - - -=== tests rules === - -## 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` with a specific filename or filter. - \ No newline at end of file + diff --git a/app/Console/Commands/MarkCompedSubscriptions.php b/app/Console/Commands/MarkCompedSubscriptions.php new file mode 100644 index 00000000..11a67e7e --- /dev/null +++ b/app/Console/Commands/MarkCompedSubscriptions.php @@ -0,0 +1,125 @@ +argument('file'); + + if (! file_exists($path)) { + $this->error("File not found: {$path}"); + + return self::FAILURE; + } + + $emails = $this->parseEmails($path); + + if (empty($emails)) { + $this->error('No valid email addresses found in the file.'); + + return self::FAILURE; + } + + $this->info('Found '.count($emails).' email(s) to process.'); + + $updated = 0; + $skipped = []; + + foreach ($emails as $email) { + $user = User::where('email', $email)->first(); + + if (! $user) { + $skipped[] = "{$email} — user not found"; + + continue; + } + + $subscription = Subscription::where('user_id', $user->id) + ->where('stripe_status', 'active') + ->first(); + + if (! $subscription) { + $skipped[] = "{$email} — no active subscription"; + + continue; + } + + if ($subscription->is_comped) { + $skipped[] = "{$email} — already marked as comped"; + + continue; + } + + $subscription->update(['is_comped' => true]); + $updated++; + $this->info("Marked {$email} as comped (subscription #{$subscription->id})"); + } + + if (count($skipped) > 0) { + $this->warn('Skipped:'); + foreach ($skipped as $reason) { + $this->warn(" - {$reason}"); + } + } + + $this->info("Done. {$updated} subscription(s) marked as comped."); + + return self::SUCCESS; + } + + /** + * Parse email addresses from a CSV file. + * Supports: plain list (one email per line), or CSV with an "email" column header. + * + * @return array + */ + private function parseEmails(string $path): array + { + $handle = fopen($path, 'r'); + + if (! $handle) { + return []; + } + + $emails = []; + $emailColumnIndex = null; + $isFirstRow = true; + + while (($row = fgetcsv($handle)) !== false) { + if ($isFirstRow) { + $isFirstRow = false; + $headers = array_map(fn ($h) => strtolower(trim($h)), $row); + $emailColumnIndex = array_search('email', $headers); + + // If the first row looks like an email itself (no header), treat it as data + if ($emailColumnIndex === false && filter_var(trim($row[0]), FILTER_VALIDATE_EMAIL)) { + $emailColumnIndex = 0; + $emails[] = strtolower(trim($row[0])); + } + + continue; + } + + $value = trim($row[$emailColumnIndex] ?? ''); + + if (filter_var($value, FILTER_VALIDATE_EMAIL)) { + $emails[] = strtolower($value); + } + } + + fclose($handle); + + return array_unique($emails); + } +} diff --git a/app/Enums/Subscription.php b/app/Enums/Subscription.php index 29d2a3c8..f706f757 100644 --- a/app/Enums/Subscription.php +++ b/app/Enums/Subscription.php @@ -14,13 +14,35 @@ enum Subscription: string public static function fromStripeSubscription(\Stripe\Subscription $subscription): self { - $priceId = $subscription->items->first()?->price->id; + // Iterate items, skipping extra seat prices (multi-item subscriptions) + foreach ($subscription->items as $item) { + $priceId = $item->price->id; - if (! $priceId) { - throw new RuntimeException('Could not resolve Stripe price id from subscription object.'); + if (self::isExtraSeatPrice($priceId)) { + continue; + } + + return self::fromStripePriceId($priceId); } - return self::fromStripePriceId($priceId); + throw new RuntimeException('Could not resolve a plan price id from subscription items.'); + } + + public static function isExtraSeatPrice(string $priceId): bool + { + return in_array($priceId, array_filter([ + config('subscriptions.plans.max.stripe_extra_seat_price_id'), + config('subscriptions.plans.max.stripe_extra_seat_price_id_monthly'), + ])); + } + + public static function extraSeatStripePriceId(string $interval): ?string + { + return match ($interval) { + 'year' => config('subscriptions.plans.max.stripe_extra_seat_price_id'), + 'month' => config('subscriptions.plans.max.stripe_extra_seat_price_id_monthly'), + default => null, + }; } public static function fromStripePriceId(string $priceId): self @@ -34,6 +56,7 @@ public static function fromStripePriceId(string $priceId): self config('subscriptions.plans.pro.stripe_price_id_eap') => self::Pro, 'price_1RoZk0AyFo6rlwXqjkLj4hZ0', config('subscriptions.plans.max.stripe_price_id'), + config('subscriptions.plans.max.stripe_price_id_monthly'), config('subscriptions.plans.max.stripe_price_id_discounted'), config('subscriptions.plans.max.stripe_price_id_eap') => self::Max, default => throw new RuntimeException("Unknown Stripe price id: {$priceId}"), @@ -57,7 +80,7 @@ public function name(): string return config("subscriptions.plans.{$this->value}.name"); } - public function stripePriceId(bool $forceEap = false, bool $discounted = false): string + public function stripePriceId(bool $forceEap = false, bool $discounted = false, string $interval = 'year'): string { // EAP ends June 1st at midnight UTC if (now()->isBefore('2025-06-01 00:00:00') || $forceEap) { @@ -68,6 +91,10 @@ public function stripePriceId(bool $forceEap = false, bool $discounted = false): return config("subscriptions.plans.{$this->value}.stripe_price_id_discounted"); } + if ($interval === 'month') { + return config("subscriptions.plans.{$this->value}.stripe_price_id_monthly"); + } + return config("subscriptions.plans.{$this->value}.stripe_price_id"); } diff --git a/app/Enums/TeamUserRole.php b/app/Enums/TeamUserRole.php new file mode 100644 index 00000000..95fa8f29 --- /dev/null +++ b/app/Enums/TeamUserRole.php @@ -0,0 +1,9 @@ +isUltraTeamMember()) { + $officialPlugins = Plugin::query() + ->where('type', \App\Enums\PluginType::Paid) + ->where('is_official', true) + ->whereNotNull('name') + ->get(['name']); + + foreach ($officialPlugins as $plugin) { + if (! collect($plugins)->contains('name', $plugin->name)) { + $plugins[] = [ + 'name' => $plugin->name, + 'access' => 'team', + ]; + } + } + } + + $teamOwner = $user->getTeamOwner(); + + if ($teamOwner) { + $teamPlugins = $teamOwner->pluginLicenses() + ->active() + ->with('plugin:id,name') + ->get() + ->pluck('plugin') + ->filter() + ->unique('id'); + + foreach ($teamPlugins as $plugin) { + if (! collect($plugins)->contains('name', $plugin->name)) { + $plugins[] = [ + 'name' => $plugin->name, + 'access' => 'team', + ]; + } + } + } + return $plugins; } } diff --git a/app/Http/Controllers/Auth/CustomerAuthController.php b/app/Http/Controllers/Auth/CustomerAuthController.php index c23dae8c..1bfb8e41 100644 --- a/app/Http/Controllers/Auth/CustomerAuthController.php +++ b/app/Http/Controllers/Auth/CustomerAuthController.php @@ -2,9 +2,11 @@ namespace App\Http\Controllers\Auth; +use App\Enums\TeamUserStatus; use App\Http\Controllers\Controller; use App\Http\Requests\Auth\LoginRequest; use App\Models\Plugin; +use App\Models\TeamUser; use App\Models\User; use App\Services\CartService; use Illuminate\Http\RedirectResponse; @@ -46,6 +48,9 @@ public function register(Request $request): RedirectResponse // Transfer guest cart to user $this->cartService->transferGuestCartToUser($user); + // Check for pending team invitation + $this->acceptPendingTeamInvitation($user); + // Check for pending add-to-cart action $pendingPluginId = session()->pull('pending_add_to_cart'); if ($pendingPluginId) { @@ -77,6 +82,9 @@ public function login(LoginRequest $request): RedirectResponse // Transfer guest cart to user $this->cartService->transferGuestCartToUser($user); + // Check for pending team invitation + $this->acceptPendingTeamInvitation($user); + // Check for pending add-to-cart action $pendingPluginId = session()->pull('pending_add_to_cart'); if ($pendingPluginId) { @@ -155,4 +163,23 @@ function ($user, $password): void { ? to_route('customer.login')->with('status', __($status)) : back()->withErrors(['email' => [__($status)]]); } + + private function acceptPendingTeamInvitation(User $user): void + { + $token = session()->pull('pending_team_invitation_token'); + + if (! $token) { + return; + } + + $teamUser = TeamUser::where('invitation_token', $token) + ->where('email', $user->email) + ->where('status', TeamUserStatus::Pending) + ->first(); + + if ($teamUser) { + $teamUser->accept($user); + session()->flash('success', "You've joined {$teamUser->team->name}!"); + } + } } diff --git a/app/Http/Controllers/CartController.php b/app/Http/Controllers/CartController.php index 368f7ee6..e4001d33 100644 --- a/app/Http/Controllers/CartController.php +++ b/app/Http/Controllers/CartController.php @@ -2,8 +2,10 @@ namespace App\Http\Controllers; +use App\Models\Cart; use App\Models\Plugin; use App\Models\PluginBundle; +use App\Models\PluginLicense; use App\Models\Product; use App\Services\CartService; use Illuminate\Http\JsonResponse; @@ -264,6 +266,11 @@ public function checkout(Request $request): RedirectResponse // Refresh prices $this->cartService->refreshPrices($cart); + // If total is $0, skip Stripe entirely and create licenses directly + if ($cart->getSubtotal() === 0) { + return $this->processFreeCheckout($cart, $user); + } + try { $session = $this->createMultiItemCheckoutSession($cart, $user); @@ -285,6 +292,22 @@ public function checkout(Request $request): RedirectResponse public function success(Request $request): View|RedirectResponse { + if ($request->query('free')) { + $user = Auth::user(); + + $cart = Cart::where('user_id', $user->id) + ->whereNotNull('completed_at') + ->latest('completed_at') + ->with('items.plugin', 'items.pluginBundle.plugins', 'items.product') + ->first(); + + return view('cart.success', [ + 'sessionId' => null, + 'isFreeCheckout' => true, + 'cart' => $cart, + ]); + } + $sessionId = $request->query('session_id'); // Validate session ID exists and looks like a real Stripe session ID @@ -297,6 +320,51 @@ public function success(Request $request): View|RedirectResponse return view('cart.success', [ 'sessionId' => $sessionId, + 'isFreeCheckout' => false, + 'cart' => null, + ]); + } + + protected function processFreeCheckout(Cart $cart, $user): RedirectResponse + { + $cart->load('items.plugin', 'items.pluginBundle.plugins', 'items.product'); + + foreach ($cart->items as $item) { + if ($item->isBundle()) { + foreach ($item->pluginBundle->plugins as $plugin) { + $this->createFreePluginLicense($user, $plugin); + } + } elseif (! $item->isProduct() && $item->plugin) { + $this->createFreePluginLicense($user, $item->plugin); + } + } + + $cart->markAsCompleted(); + + $user->getPluginLicenseKey(); + + Log::info('Free checkout completed', [ + 'cart_id' => $cart->id, + 'user_id' => $user->id, + 'item_count' => $cart->items->count(), + ]); + + return to_route('cart.success', ['free' => 1]); + } + + protected function createFreePluginLicense($user, Plugin $plugin): void + { + if ($user->pluginLicenses()->forPlugin($plugin)->active()->exists()) { + return; + } + + PluginLicense::create([ + 'user_id' => $user->id, + 'plugin_id' => $plugin->id, + 'price_paid' => 0, + 'currency' => 'USD', + 'is_grandfathered' => false, + 'purchased_at' => now(), ]); } diff --git a/app/Http/Controllers/CustomerLicenseController.php b/app/Http/Controllers/CustomerLicenseController.php index e9c7d544..10be9dd9 100644 --- a/app/Http/Controllers/CustomerLicenseController.php +++ b/app/Http/Controllers/CustomerLicenseController.php @@ -26,13 +26,43 @@ public function index(): View $licenseCount = $user->licenses()->count(); $isEapCustomer = $user->isEapCustomer(); $activeSubscription = $user->subscription(); - $pluginLicenseCount = $user->pluginLicenses()->count(); + $ownPluginIds = $user->pluginLicenses()->pluck('plugin_id'); + $teamPluginCount = 0; + $teamMembership = $user->activeTeamMembership(); + + if ($teamMembership) { + $teamPluginCount = $teamMembership->team->owner + ->pluginLicenses() + ->active() + ->whereNotIn('plugin_id', $ownPluginIds) + ->distinct('plugin_id') + ->count('plugin_id'); + } + + $pluginLicenseCount = $ownPluginIds->count() + $teamPluginCount; // Get subscription plan name $subscriptionName = null; if ($activeSubscription) { try { - $subscriptionName = \App\Enums\Subscription::fromStripePriceId($activeSubscription->stripe_price)->name(); + // On multi-item subscriptions, stripe_price may be null. + // Find the plan price from subscription items, skipping extra seat prices. + $planPriceId = $activeSubscription->stripe_price; + + if (! $planPriceId) { + foreach ($activeSubscription->items as $item) { + if (! \App\Enums\Subscription::isExtraSeatPrice($item->stripe_price)) { + $planPriceId = $item->stripe_price; + break; + } + } + } + + if ($planPriceId) { + $subscriptionName = \App\Enums\Subscription::fromStripePriceId($planPriceId)->name(); + } else { + $subscriptionName = ucfirst($activeSubscription->type); + } } catch (\RuntimeException) { $subscriptionName = ucfirst($activeSubscription->type); } @@ -62,6 +92,14 @@ public function index(): View // Total purchases (licenses + plugins) $totalPurchases = $licenseCount + $pluginLicenseCount; + // Team info + $ownedTeam = $user->ownedTeam; + $hasTeam = $ownedTeam !== null; + $teamName = $ownedTeam?->name; + $teamMemberCount = $ownedTeam?->activeUserCount() ?? 0; + $teamPendingCount = $ownedTeam?->pendingInvitations()->count() ?? 0; + $hasMaxAccess = $user->hasActiveUltraSubscription(); + return view('customer.dashboard', compact( 'licenseCount', 'isEapCustomer', @@ -71,7 +109,12 @@ public function index(): View 'renewalLicenseKey', 'connectedAccountsCount', 'connectedAccountsDescription', - 'totalPurchases' + 'totalPurchases', + 'hasTeam', + 'teamName', + 'teamMemberCount', + 'teamPendingCount', + 'hasMaxAccess' )); } diff --git a/app/Http/Controllers/CustomerPluginController.php b/app/Http/Controllers/CustomerPluginController.php index c42a348f..9f82e836 100644 --- a/app/Http/Controllers/CustomerPluginController.php +++ b/app/Http/Controllers/CustomerPluginController.php @@ -37,13 +37,21 @@ public function index(): View public function create(): View { - return view('customer.plugins.create'); + $user = Auth::user(); + $developerAccount = $user->developerAccount; + + return view('customer.plugins.create', compact('developerAccount')); } public function store(SubmitPluginRequest $request, PluginSyncService $syncService): RedirectResponse { $user = Auth::user(); + // Save display name if provided during submission + if ($request->filled('display_name') && ! $user->display_name) { + $user->update(['display_name' => $request->input('display_name')]); + } + // Reject paid plugin submissions if the feature is disabled if ($request->type === 'paid' && ! Feature::active(AllowPaidPlugins::class)) { return to_route('customer.plugins.create') diff --git a/app/Http/Controllers/CustomerPurchasedPluginsController.php b/app/Http/Controllers/CustomerPurchasedPluginsController.php index 35a53669..53d16bee 100644 --- a/app/Http/Controllers/CustomerPurchasedPluginsController.php +++ b/app/Http/Controllers/CustomerPurchasedPluginsController.php @@ -23,6 +23,28 @@ public function index(): View ->orderBy('purchased_at', 'desc') ->get(); - return view('customer.purchased-plugins.index', compact('pluginLicenses', 'pluginLicenseKey')); + // Team plugins for team members + $teamPlugins = collect(); + $teamOwnerName = null; + $teamMembership = $user->activeTeamMembership(); + + if ($teamMembership) { + $teamOwner = $teamMembership->team->owner; + $teamOwnerName = $teamOwner->display_name; + $teamPlugins = $teamOwner->pluginLicenses() + ->active() + ->with('plugin') + ->get() + ->pluck('plugin') + ->filter() + ->unique('id'); + } + + return view('customer.purchased-plugins.index', compact( + 'pluginLicenses', + 'pluginLicenseKey', + 'teamPlugins', + 'teamOwnerName', + )); } } diff --git a/app/Http/Controllers/GitHubIntegrationController.php b/app/Http/Controllers/GitHubIntegrationController.php index 50652b27..4cf5c8a2 100644 --- a/app/Http/Controllers/GitHubIntegrationController.php +++ b/app/Http/Controllers/GitHubIntegrationController.php @@ -164,11 +164,11 @@ public function requestClaudePluginsAccess(): RedirectResponse return back()->with('error', 'Please connect your GitHub account first.'); } - // Check if user has a Plugin Dev Kit license + // Check if user has a Plugin Dev Kit license or is an Ultra team member $pluginDevKit = Product::where('slug', 'plugin-dev-kit')->first(); - if (! $pluginDevKit || ! $user->hasProductLicense($pluginDevKit)) { - return back()->with('error', 'You need a Plugin Dev Kit license to access the claude-code repository.'); + if (! $user->isUltraTeamMember() && (! $pluginDevKit || ! $user->hasProductLicense($pluginDevKit))) { + return back()->with('error', 'You need a Plugin Dev Kit license or Ultra team membership to access the claude-code repository.'); } $github = GitHubOAuth::make(); diff --git a/app/Http/Controllers/TeamController.php b/app/Http/Controllers/TeamController.php new file mode 100644 index 00000000..05a8461c --- /dev/null +++ b/app/Http/Controllers/TeamController.php @@ -0,0 +1,49 @@ +middleware('auth'); + } + + public function index(): View + { + $user = Auth::user(); + $team = $user->ownedTeam; + $membership = $user->activeTeamMembership(); + + return view('customer.team.index', compact('team', 'membership')); + } + + public function store(Request $request): RedirectResponse + { + $user = Auth::user(); + + if (! $user->hasActiveUltraSubscription()) { + return back()->with('error', 'You need an active Ultra subscription to create a team.'); + } + + if ($user->ownedTeam) { + return back()->with('error', 'You already have a team.'); + } + + $request->validate([ + 'name' => ['required', 'string', 'max:255'], + ]); + + $user->ownedTeam()->create([ + 'name' => $request->name, + ]); + + return to_route('customer.team.index') + ->with('success', 'Team created successfully!'); + } +} diff --git a/app/Http/Controllers/TeamUserController.php b/app/Http/Controllers/TeamUserController.php new file mode 100644 index 00000000..40ae2ba4 --- /dev/null +++ b/app/Http/Controllers/TeamUserController.php @@ -0,0 +1,148 @@ +middleware('auth')->except('accept'); + } + + public function invite(InviteTeamUserRequest $request): RedirectResponse + { + $user = Auth::user(); + $team = $user->ownedTeam; + + if (! $team) { + return back()->with('error', 'You do not have a team.'); + } + + if ($team->is_suspended) { + return back()->with('error', 'Your team is currently suspended.'); + } + + // Rate limit: 5 invites per minute per team + $rateLimitKey = "team-invite:{$team->id}"; + if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) { + return back()->with('error', 'Too many invitations sent. Please wait a moment.'); + } + RateLimiter::hit($rateLimitKey, 60); + + $email = $request->validated()['email']; + + // Check for duplicate (active or pending) + $existingMember = $team->users() + ->where('email', $email) + ->whereIn('status', [TeamUserStatus::Pending, TeamUserStatus::Active]) + ->first(); + + if ($existingMember) { + return back()->with('error', 'This email has already been invited or is an active member.'); + } + + if ($team->isOverIncludedLimit()) { + return back()->with('show_add_seats', true); + } + + $member = $team->users()->create([ + 'email' => $email, + 'invitation_token' => bin2hex(random_bytes(32)), + 'invited_at' => now(), + ]); + + Notification::route('mail', $email) + ->notify(new TeamInvitation($member)); + + return back()->with('success', "Invitation sent to {$email}."); + } + + public function remove(TeamUser $teamUser): RedirectResponse + { + $user = Auth::user(); + + if (! $user->ownedTeam || $teamUser->team_id !== $user->ownedTeam->id) { + return back()->with('error', 'You are not authorized to remove this member.'); + } + + $teamUser->remove(); + + Notification::route('mail', $teamUser->email) + ->notify(new TeamUserRemoved($teamUser)); + + if ($teamUser->user_id) { + dispatch(new RevokeTeamUserAccessJob($teamUser->user_id)); + } + + return back()->with('success', "{$teamUser->email} has been removed from the team."); + } + + public function resend(TeamUser $teamUser): RedirectResponse + { + $user = Auth::user(); + + if (! $user->ownedTeam || $teamUser->team_id !== $user->ownedTeam->id) { + return back()->with('error', 'You are not authorized to resend this invitation.'); + } + + if (! $teamUser->isPending()) { + return back()->with('error', 'This invitation cannot be resent.'); + } + + // Rate limit: 1 resend per minute per member + $rateLimitKey = "team-resend:{$teamUser->id}"; + if (RateLimiter::tooManyAttempts($rateLimitKey, 1)) { + return back()->with('error', 'Please wait before resending this invitation.'); + } + RateLimiter::hit($rateLimitKey, 60); + + Notification::route('mail', $teamUser->email) + ->notify(new TeamInvitation($teamUser)); + + return back()->with('success', "Invitation resent to {$teamUser->email}."); + } + + public function accept(string $token): RedirectResponse + { + $teamUser = TeamUser::where('invitation_token', $token) + ->where('status', TeamUserStatus::Pending) + ->first(); + + if (! $teamUser) { + return to_route('dashboard') + ->with('error', 'This invitation is invalid or has already been used.'); + } + + $user = Auth::user(); + + if ($user) { + // Authenticated user + if (strtolower($user->email) !== strtolower($teamUser->email)) { + return to_route('dashboard') + ->with('error', 'This invitation was sent to a different email address.'); + } + + $teamUser->accept($user); + + return to_route('dashboard') + ->with('success', "You've joined {$teamUser->team->name}!"); + } + + // Not authenticated — store token in session and redirect to login + session(['pending_team_invitation_token' => $token]); + + return to_route('customer.login') + ->with('message', 'Please log in or register to accept your team invitation.'); + } +} diff --git a/app/Http/Requests/InviteTeamUserRequest.php b/app/Http/Requests/InviteTeamUserRequest.php new file mode 100644 index 00000000..52e2f064 --- /dev/null +++ b/app/Http/Requests/InviteTeamUserRequest.php @@ -0,0 +1,23 @@ +> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'email', 'max:255'], + ]; + } +} diff --git a/app/Jobs/HandleInvoicePaidJob.php b/app/Jobs/HandleInvoicePaidJob.php index 9a2debdb..c8f4dd26 100644 --- a/app/Jobs/HandleInvoicePaidJob.php +++ b/app/Jobs/HandleInvoicePaidJob.php @@ -47,13 +47,22 @@ public function handle(): void match ($this->invoice->billing_reason) { Invoice::BILLING_REASON_SUBSCRIPTION_CREATE => $this->handleSubscriptionCreated(), - Invoice::BILLING_REASON_SUBSCRIPTION_UPDATE => null, // TODO: Handle subscription update + Invoice::BILLING_REASON_SUBSCRIPTION_UPDATE => $this->handleSubscriptionUpdate(), Invoice::BILLING_REASON_SUBSCRIPTION_CYCLE => $this->handleSubscriptionRenewal(), Invoice::BILLING_REASON_MANUAL => $this->handleManualInvoice(), default => null, }; } + private function handleSubscriptionUpdate(): void + { + Log::info('HandleInvoicePaidJob: subscription update invoice received, no license action needed.', [ + 'invoice_id' => $this->invoice->id, + ]); + + $this->updateSubscriptionCompedStatus(); + } + private function handleSubscriptionCreated(): void { // Get the subscription to check for renewal metadata @@ -66,12 +75,14 @@ private function handleSubscriptionCreated(): void if ($isRenewal && $licenseKey && $licenseId) { $this->handleLegacyLicenseRenewal($subscription, $licenseKey, $licenseId); + $this->updateSubscriptionCompedStatus(); return; } // Normal flow - create a new license $this->createLicense(); + $this->updateSubscriptionCompedStatus(); } private function handleLegacyLicenseRenewal($subscription, string $licenseKey, string $licenseId): void @@ -98,7 +109,7 @@ private function handleLegacyLicenseRenewal($subscription, string $licenseKey, s } // Get the subscription item - if (blank($subscriptionItemId = $this->invoice->lines->first()->subscription_item)) { + if (blank($subscriptionItemId = $this->findPlanLineItem()->subscription_item)) { throw new UnexpectedValueException('Failed to retrieve the Stripe subscription item id from invoice lines.'); } @@ -132,10 +143,10 @@ private function createLicense(): void \Illuminate\Support\Sleep::sleep(10); // Assert the invoice line item is for a price_id that relates to a license plan. - $plan = Subscription::fromStripePriceId($this->invoice->lines->first()->price->id); + $plan = Subscription::fromStripePriceId($this->findPlanLineItem()->price->id); // Assert the invoice line item relates to a subscription and has a subscription item id. - if (blank($subscriptionItemId = $this->invoice->lines->first()->subscription_item)) { + if (blank($subscriptionItemId = $this->findPlanLineItem()->subscription_item)) { throw new UnexpectedValueException('Failed to retrieve the Stripe subscription item id from invoice lines.'); } @@ -161,7 +172,7 @@ private function createLicense(): void private function handleSubscriptionRenewal(): void { // Get the subscription item ID from the invoice line - if (blank($subscriptionItemId = $this->invoice->lines->first()->subscription_item)) { + if (blank($subscriptionItemId = $this->findPlanLineItem()->subscription_item)) { throw new UnexpectedValueException('Failed to retrieve the Stripe subscription item id from invoice lines.'); } @@ -195,6 +206,8 @@ private function handleSubscriptionRenewal(): void 'subscription_id' => $this->invoice->subscription, 'invoice_id' => $this->invoice->id, ]); + + $this->updateSubscriptionCompedStatus(); } private function handleManualInvoice(): void @@ -605,6 +618,42 @@ private function createBundlePluginLicense(User $user, Plugin $plugin, PluginBun return $license; } + /** + * Mark the local Cashier subscription as comped if the invoice total is zero. + */ + private function updateSubscriptionCompedStatus(): void + { + if (! $this->invoice->subscription) { + return; + } + + $subscription = \Laravel\Cashier\Subscription::where('stripe_id', $this->invoice->subscription)->first(); + + if ($subscription) { + $invoiceTotal = $this->invoice->total ?? 0; + + $subscription->update([ + 'is_comped' => $invoiceTotal <= 0, + ]); + } + } + + /** + * Find the plan line item from invoice lines, filtering out extra seat price items. + */ + private function findPlanLineItem(): ?\Stripe\StripeObject + { + foreach ($this->invoice->lines->data as $line) { + if ($line->price && Subscription::isExtraSeatPrice($line->price->id)) { + continue; + } + + return $line; + } + + return null; + } + private function billable(): User { if ($user = Cashier::findBillable($this->invoice->customer)) { diff --git a/app/Jobs/RevokeTeamUserAccessJob.php b/app/Jobs/RevokeTeamUserAccessJob.php new file mode 100644 index 00000000..702f1bf0 --- /dev/null +++ b/app/Jobs/RevokeTeamUserAccessJob.php @@ -0,0 +1,61 @@ +userId); + + if (! $user) { + return; + } + + $pluginDevKit = Product::where('slug', 'plugin-dev-kit')->first(); + + if (! $pluginDevKit) { + return; + } + + // If user still has access via direct license or another team, skip + if ($user->productLicenses()->forProduct($pluginDevKit)->exists()) { + return; + } + + if ($user->isUltraTeamMember()) { + return; + } + + if (! $user->github_username || ! $user->claude_plugins_repo_access_granted_at) { + return; + } + + $github = GitHubOAuth::make(); + $github->removeFromClaudePluginsRepo($user->github_username); + + $user->update(['claude_plugins_repo_access_granted_at' => null]); + + Log::info('Revoked claude-plugins repo access for removed team member', [ + 'user_id' => $user->id, + ]); + } +} diff --git a/app/Jobs/SuspendTeamJob.php b/app/Jobs/SuspendTeamJob.php new file mode 100644 index 00000000..7b59451e --- /dev/null +++ b/app/Jobs/SuspendTeamJob.php @@ -0,0 +1,51 @@ +userId); + + if (! $user) { + return; + } + + $team = $user->ownedTeam; + + if (! $team) { + return; + } + + $team->suspend(); + + Log::info('Team suspended due to subscription change', [ + 'team_id' => $team->id, + 'user_id' => $user->id, + ]); + + // Revoke access for all active members + $team->activeUsers() + ->whereNotNull('user_id') + ->each(function ($member): void { + dispatch(new RevokeTeamUserAccessJob($member->user_id)); + }); + } +} diff --git a/app/Jobs/UnsuspendTeamJob.php b/app/Jobs/UnsuspendTeamJob.php new file mode 100644 index 00000000..fe5a2158 --- /dev/null +++ b/app/Jobs/UnsuspendTeamJob.php @@ -0,0 +1,48 @@ +userId); + + if (! $user) { + return; + } + + $team = $user->ownedTeam; + + if (! $team || ! $team->is_suspended) { + return; + } + + if (! $user->hasMaxAccess()) { + return; + } + + $team->unsuspend(); + + Log::info('Team unsuspended due to subscription reactivation', [ + 'team_id' => $team->id, + 'user_id' => $user->id, + ]); + } +} diff --git a/app/Listeners/StripeWebhookReceivedListener.php b/app/Listeners/StripeWebhookReceivedListener.php index b8274812..7544b010 100644 --- a/app/Listeners/StripeWebhookReceivedListener.php +++ b/app/Listeners/StripeWebhookReceivedListener.php @@ -5,6 +5,8 @@ use App\Jobs\CreateUserFromStripeCustomer; use App\Jobs\HandleInvoicePaidJob; use App\Jobs\RemoveDiscordMaxRoleJob; +use App\Jobs\SuspendTeamJob; +use App\Jobs\UnsuspendTeamJob; use App\Models\User; use App\Notifications\SubscriptionCancelled; use Exception; @@ -73,6 +75,8 @@ private function handleSubscriptionDeleted(WebhookReceived $event): void } $this->removeDiscordRoleIfNoMaxLicense($user); + + dispatch(new SuspendTeamJob($user->id)); } private function handleSubscriptionUpdated(WebhookReceived $event): void @@ -96,6 +100,12 @@ private function handleSubscriptionUpdated(WebhookReceived $event): void if (in_array($status, ['canceled', 'unpaid', 'past_due', 'incomplete_expired'])) { $this->removeDiscordRoleIfNoMaxLicense($user); + dispatch(new SuspendTeamJob($user->id)); + } + + // Detect reactivation: status changed to active from a non-active state + if ($status === 'active' && isset($previousAttributes['status'])) { + dispatch(new UnsuspendTeamJob($user->id)); } } diff --git a/app/Livewire/MobilePricing.php b/app/Livewire/MobilePricing.php index caf4f3c2..995b16f7 100644 --- a/app/Livewire/MobilePricing.php +++ b/app/Livewire/MobilePricing.php @@ -14,8 +14,7 @@ class MobilePricing extends Component { - #[Locked] - public bool $discounted = false; + public string $interval = 'month'; #[Locked] public $user; @@ -73,7 +72,7 @@ public function createCheckoutSession(?string $plan, ?User $user = null) $user->createOrGetStripeCustomer(); $checkout = $user - ->newSubscription('default', $subscription->stripePriceId(discounted: $this->discounted)) + ->newSubscription('default', $subscription->stripePriceId(interval: $this->interval)) ->allowPromotionCodes() ->checkout([ 'success_url' => $this->successUrl(), diff --git a/app/Livewire/TeamManager.php b/app/Livewire/TeamManager.php new file mode 100644 index 00000000..0049dfc8 --- /dev/null +++ b/app/Livewire/TeamManager.php @@ -0,0 +1,141 @@ +team = $team; + } + + public function addSeats(int $count = 1): void + { + $owner = $this->team->owner; + $subscription = $owner->subscription(); + + if (! $subscription) { + return; + } + + // Determine the correct extra seat price based on subscription interval + $planPriceId = $subscription->stripe_price; + + if (! $planPriceId) { + foreach ($subscription->items as $item) { + if (! Subscription::isExtraSeatPrice($item->stripe_price)) { + $planPriceId = $item->stripe_price; + break; + } + } + } + + $isMonthly = $planPriceId === config('subscriptions.plans.max.stripe_price_id_monthly'); + $interval = $isMonthly ? 'month' : 'year'; + $priceId = Subscription::extraSeatStripePriceId($interval); + + if (! $priceId) { + return; + } + + // Check if subscription already has this price item + $existingItem = $subscription->items->firstWhere('stripe_price', $priceId); + + if ($existingItem) { + $subscription->incrementAndInvoice($count, $priceId); + } else { + $subscription->addPriceAndInvoice($priceId, $count); + } + + $this->team->increment('extra_seats', $count); + $this->team->refresh(); + + $this->dispatch('seats-updated'); + } + + public function removeSeats(int $count = 1): void + { + if ($this->team->extra_seats < $count) { + return; + } + + // Don't allow removing seats if it would go below occupied count + $newCapacity = $this->team->totalSeatCapacity() - $count; + if ($newCapacity < $this->team->occupiedSeatCount()) { + return; + } + + $owner = $this->team->owner; + $subscription = $owner->subscription(); + + if (! $subscription) { + return; + } + + $planPriceId = $subscription->stripe_price; + + if (! $planPriceId) { + foreach ($subscription->items as $item) { + if (! Subscription::isExtraSeatPrice($item->stripe_price)) { + $planPriceId = $item->stripe_price; + break; + } + } + } + + $isMonthly = $planPriceId === config('subscriptions.plans.max.stripe_price_id_monthly'); + $interval = $isMonthly ? 'month' : 'year'; + $priceId = Subscription::extraSeatStripePriceId($interval); + + if (! $priceId) { + return; + } + + $existingItem = $subscription->items->firstWhere('stripe_price', $priceId); + + if ($existingItem) { + if ($existingItem->quantity <= $count) { + $subscription->removePrice($priceId); + } else { + $subscription->decrementQuantity($count, $priceId); + } + } + + $this->team->decrement('extra_seats', $count); + $this->team->refresh(); + + $this->dispatch('seats-updated'); + } + + public function render() + { + $this->team->refresh(); + $this->team->load('users'); + + $activeMembers = $this->team->users->where('status', TeamUserStatus::Active); + $pendingInvitations = $this->team->users->where('status', TeamUserStatus::Pending); + + $extraSeatPriceYearly = config('subscriptions.plans.max.extra_seat_price_yearly', 4); + $extraSeatPriceMonthly = config('subscriptions.plans.max.extra_seat_price_monthly', 5); + + $removableSeats = min( + $this->team->extra_seats, + $this->team->totalSeatCapacity() - $this->team->occupiedSeatCount() + ); + + return view('livewire.team-manager', [ + 'activeMembers' => $activeMembers, + 'pendingInvitations' => $pendingInvitations, + 'extraSeatPriceYearly' => $extraSeatPriceYearly, + 'extraSeatPriceMonthly' => $extraSeatPriceMonthly, + 'removableSeats' => max(0, $removableSeats), + ]); + } +} diff --git a/app/Models/Plugin.php b/app/Models/Plugin.php index 1342935f..053b6c1d 100644 --- a/app/Models/Plugin.php +++ b/app/Models/Plugin.php @@ -166,11 +166,23 @@ public function getBestPriceForUser(?User $user): ?PluginPrice $eligibleTiers = $user ? $user->getEligiblePriceTiers() : [\App\Enums\PriceTier::Regular]; // Get the lowest active price for the user's eligible tiers - return $this->prices() + $bestPrice = $this->prices() ->active() ->forTiers($eligibleTiers) ->orderBy('amount', 'asc') ->first(); + + // Ultra subscribers get official plugins for free + if ($bestPrice && $user && $this->isOfficial() && $user->hasUltraAccess()) { + $freePrice = $bestPrice->replicate(); + $freePrice->amount = 0; + $freePrice->id = $bestPrice->id; + $freePrice->exists = true; + + return $freePrice; + } + + return $bestPrice; } /** diff --git a/app/Models/Team.php b/app/Models/Team.php new file mode 100644 index 00000000..d09fd8a5 --- /dev/null +++ b/app/Models/Team.php @@ -0,0 +1,106 @@ + + */ + public function owner(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } + + /** + * @return HasMany + */ + public function users(): HasMany + { + return $this->hasMany(TeamUser::class); + } + + /** + * @return HasMany + */ + public function activeUsers(): HasMany + { + return $this->hasMany(TeamUser::class) + ->where('status', \App\Enums\TeamUserStatus::Active); + } + + /** + * @return HasMany + */ + public function pendingInvitations(): HasMany + { + return $this->hasMany(TeamUser::class) + ->where('status', \App\Enums\TeamUserStatus::Pending); + } + + public function activeUserCount(): int + { + return $this->activeUsers()->count(); + } + + public function includedSeats(): int + { + return config('subscriptions.plans.max.included_seats', 10); + } + + public function totalSeatCapacity(): int + { + return $this->includedSeats() + ($this->extra_seats ?? 0); + } + + public function occupiedSeatCount(): int + { + return $this->activeUserCount() + $this->pendingInvitations()->count(); + } + + public function availableSeats(): int + { + return max(0, $this->totalSeatCapacity() - $this->occupiedSeatCount()); + } + + public function isOverIncludedLimit(): bool + { + return $this->occupiedSeatCount() >= $this->totalSeatCapacity(); + } + + public function extraSeatsCount(): int + { + return max(0, $this->activeUserCount() - $this->includedSeats()); + } + + public function suspend(): bool + { + return $this->update(['is_suspended' => true]); + } + + public function unsuspend(): bool + { + return $this->update(['is_suspended' => false]); + } + + protected function casts(): array + { + return [ + 'is_suspended' => 'boolean', + ]; + } +} diff --git a/app/Models/TeamUser.php b/app/Models/TeamUser.php new file mode 100644 index 00000000..9711e7e8 --- /dev/null +++ b/app/Models/TeamUser.php @@ -0,0 +1,84 @@ + + */ + public function team(): BelongsTo + { + return $this->belongsTo(Team::class); + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + public function isActive(): bool + { + return $this->status === TeamUserStatus::Active; + } + + public function isPending(): bool + { + return $this->status === TeamUserStatus::Pending; + } + + public function isRemoved(): bool + { + return $this->status === TeamUserStatus::Removed; + } + + public function accept(User $user): void + { + $this->update([ + 'user_id' => $user->id, + 'status' => TeamUserStatus::Active, + 'invitation_token' => null, + 'accepted_at' => now(), + ]); + } + + public function remove(): void + { + $this->update([ + 'status' => TeamUserStatus::Removed, + 'invitation_token' => null, + ]); + } + + protected function casts(): array + { + return [ + 'status' => TeamUserStatus::class, + 'role' => TeamUserRole::class, + 'invited_at' => 'datetime', + 'accepted_at' => 'datetime', + ]; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 0e2b1534..ae1cf890 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,6 +3,7 @@ namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; +use App\Enums\TeamUserStatus; use Filament\Models\Contracts\FilamentUser; use Filament\Panel; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -36,6 +37,28 @@ public function isAdmin(): bool return in_array($this->email, config('filament.users'), true); } + /** + * @return HasOne + */ + public function ownedTeam(): HasOne + { + return $this->hasOne(Team::class); + } + + /** + * Get the team owner if this user is an active team member. + */ + public function getTeamOwner(): ?self + { + $membership = $this->activeTeamMembership(); + + if (! $membership) { + return null; + } + + return $membership->team->owner; + } + /** * @return HasMany */ @@ -81,9 +104,11 @@ public function productLicenses(): HasMany */ public function hasProductLicense(Product $product): bool { - return $this->productLicenses() - ->forProduct($product) - ->exists(); + if ($this->productLicenses()->forProduct($product)->exists()) { + return true; + } + + return $this->hasProductAccessViaTeam($product); } /** @@ -94,6 +119,52 @@ public function developerAccount(): HasOne return $this->hasOne(DeveloperAccount::class); } + /** + * @return HasMany + */ + public function teamMemberships(): HasMany + { + return $this->hasMany(TeamUser::class); + } + + public function isUltraTeamMember(): bool + { + // Team owners count as members + if ($this->ownedTeam && ! $this->ownedTeam->is_suspended) { + return true; + } + + return TeamUser::query() + ->where('user_id', $this->id) + ->where('status', TeamUserStatus::Active) + ->whereHas('team', fn ($query) => $query->where('is_suspended', false)) + ->exists(); + } + + public function activeTeamMembership(): ?TeamUser + { + return TeamUser::query() + ->where('user_id', $this->id) + ->where('status', TeamUserStatus::Active) + ->whereHas('team', fn ($query) => $query->where('is_suspended', false)) + ->with('team') + ->first(); + } + + public function hasProductAccessViaTeam(Product $product): bool + { + $membership = $this->activeTeamMembership(); + + if (! $membership) { + return false; + } + + // Check the owner's direct product licenses only (not via team) to avoid recursion + return $membership->team->owner->productLicenses() + ->forProduct($product) + ->exists(); + } + public function hasActiveMaxLicense(): bool { return $this->licenses() @@ -122,6 +193,60 @@ public function hasMaxAccess(): bool return $this->hasActiveMaxLicense() || $this->hasActiveMaxSubLicense(); } + public function hasActiveUltraSubscription(): bool + { + $subscription = $this->subscription(); + + if (! $subscription || $subscription->is_comped) { + return false; + } + + return $this->subscribedToPrice(array_filter([ + config('subscriptions.plans.max.stripe_price_id'), + config('subscriptions.plans.max.stripe_price_id_monthly'), + config('subscriptions.plans.max.stripe_price_id_eap'), + config('subscriptions.plans.max.stripe_price_id_discounted'), + ])); + } + + /** + * Check if the user has a paying (non-comped) Max subscription, + * qualifying them for Ultra benefits like Teams. + */ + public function hasUltraAccess(): bool + { + $subscription = $this->subscription(); + + if (! $subscription || ! $subscription->active()) { + return false; + } + + $planPriceId = $subscription->stripe_price; + + if (! $planPriceId) { + foreach ($subscription->items as $item) { + if (! \App\Enums\Subscription::isExtraSeatPrice($item->stripe_price)) { + $planPriceId = $item->stripe_price; + break; + } + } + } + + if (! $planPriceId) { + return false; + } + + try { + if (\App\Enums\Subscription::fromStripePriceId($planPriceId) !== \App\Enums\Subscription::Max) { + return false; + } + } catch (\RuntimeException) { + return false; + } + + return ! $subscription->is_comped; + } + /** * Check if user was an Early Access Program customer. * EAP customers purchased before June 1, 2025. @@ -143,7 +268,7 @@ public function getEligiblePriceTiers(): array { $tiers = [\App\Enums\PriceTier::Regular]; - if ($this->subscribed()) { + if ($this->subscribed() || $this->isUltraTeamMember()) { $tiers[] = \App\Enums\PriceTier::Subscriber; } @@ -233,10 +358,16 @@ public function hasPluginAccess(Plugin $plugin): bool return true; } - return $this->pluginLicenses() - ->forPlugin($plugin) - ->active() - ->exists(); + if ($this->pluginLicenses()->forPlugin($plugin)->active()->exists()) { + return true; + } + + // Ultra team members get access to all official (first-party) plugins + if ($plugin->isOfficial() && $this->isUltraTeamMember()) { + return true; + } + + return false; } public function getGitHubToken(): ?string diff --git a/app/Notifications/TeamInvitation.php b/app/Notifications/TeamInvitation.php new file mode 100644 index 00000000..0b5deca6 --- /dev/null +++ b/app/Notifications/TeamInvitation.php @@ -0,0 +1,55 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + public function toMail(object $notifiable): MailMessage + { + $team = $this->teamUser->team; + $ownerName = $team->owner->display_name; + + return (new MailMessage) + ->subject("You've been invited to join {$team->name} on NativePHP") + ->greeting('Hello!') + ->line("**{$ownerName}** ({$team->owner->email}) has invited you to join **{$team->name}** on NativePHP.") + ->line('As a team member, you will receive:') + ->line('- Free access to all first-party NativePHP plugins') + ->line('- Subscriber-tier pricing on third-party plugins') + ->line('- Access to the Plugin Dev Kit GitHub repository') + ->action('Accept Invitation', route('team.invitation.accept', $this->teamUser->invitation_token)) + ->line('If you did not expect this invitation, you can safely ignore this email.'); + } + + /** + * @return array + */ + public function toArray(object $notifiable): array + { + return [ + 'team_user_id' => $this->teamUser->id, + 'team_name' => $this->teamUser->team->name, + 'email' => $this->teamUser->email, + ]; + } +} diff --git a/app/Notifications/TeamUserRemoved.php b/app/Notifications/TeamUserRemoved.php new file mode 100644 index 00000000..8e81d065 --- /dev/null +++ b/app/Notifications/TeamUserRemoved.php @@ -0,0 +1,50 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + public function toMail(object $notifiable): MailMessage + { + $teamName = $this->teamUser->team->name; + + return (new MailMessage) + ->subject("You have been removed from {$teamName}") + ->greeting('Hello!') + ->line("You have been removed from **{$teamName}** on NativePHP.") + ->line('Your team benefits, including free plugin access and subscriber-tier pricing, have been revoked.') + ->action('View Plans', route('pricing')) + ->line('If you believe this was a mistake, please contact the team owner.'); + } + + /** + * @return array + */ + public function toArray(object $notifiable): array + { + return [ + 'team_user_id' => $this->teamUser->id, + 'team_name' => $this->teamUser->team->name, + ]; + } +} diff --git a/boost.json b/boost.json new file mode 100644 index 00000000..836a4274 --- /dev/null +++ b/boost.json @@ -0,0 +1,10 @@ +{ + "agents": [ + "claude_code", + "copilot", + "cursor", + "opencode", + "phpstorm" + ], + "guidelines": [] +} diff --git a/config/database.php b/config/database.php index 137ad18c..634f12e1 100644 --- a/config/database.php +++ b/config/database.php @@ -59,7 +59,7 @@ 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ - PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + Pdo\Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], diff --git a/config/subscriptions.php b/config/subscriptions.php index 2f4727b7..16008c0e 100644 --- a/config/subscriptions.php +++ b/config/subscriptions.php @@ -20,13 +20,19 @@ 'anystack_policy_id' => env('ANYSTACK_PRO_POLICY_ID'), ], 'max' => [ - 'name' => 'Max', + 'name' => 'Ultra', 'stripe_price_id' => env('STRIPE_MAX_PRICE_ID'), + 'stripe_price_id_monthly' => env('STRIPE_MAX_PRICE_ID_MONTHLY'), 'stripe_price_id_eap' => env('STRIPE_MAX_PRICE_ID_EAP'), 'stripe_price_id_discounted' => env('STRIPE_MAX_PRICE_ID_DISCOUNTED'), 'stripe_payment_link' => env('STRIPE_MAX_PAYMENT_LINK'), 'anystack_product_id' => env('ANYSTACK_PRODUCT_ID'), 'anystack_policy_id' => env('ANYSTACK_MAX_POLICY_ID'), + 'stripe_extra_seat_price_id' => env('STRIPE_EXTRA_SEAT_PRICE_ID'), + 'stripe_extra_seat_price_id_monthly' => env('STRIPE_EXTRA_SEAT_PRICE_ID_MONTHLY'), + 'included_seats' => 10, + 'extra_seat_price_yearly' => 4, + 'extra_seat_price_monthly' => 5, ], 'forever' => [ 'name' => 'Forever', diff --git a/database/factories/TeamFactory.php b/database/factories/TeamFactory.php new file mode 100644 index 00000000..781f21f3 --- /dev/null +++ b/database/factories/TeamFactory.php @@ -0,0 +1,36 @@ + + */ +class TeamFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'name' => fake()->company(), + 'is_suspended' => false, + ]; + } + + /** + * Indicate that the team is suspended. + */ + public function suspended(): static + { + return $this->state(fn (array $attributes) => [ + 'is_suspended' => true, + ]); + } +} diff --git a/database/factories/TeamUserFactory.php b/database/factories/TeamUserFactory.php new file mode 100644 index 00000000..efbf6f6f --- /dev/null +++ b/database/factories/TeamUserFactory.php @@ -0,0 +1,58 @@ + + */ +class TeamUserFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'team_id' => Team::factory(), + 'user_id' => null, + 'email' => fake()->unique()->safeEmail(), + 'role' => TeamUserRole::Member, + 'status' => TeamUserStatus::Pending, + 'invitation_token' => bin2hex(random_bytes(32)), + 'invited_at' => now(), + 'accepted_at' => null, + ]; + } + + /** + * Indicate the team user is active (accepted invitation). + */ + public function active(): static + { + return $this->state(fn (array $attributes) => [ + 'user_id' => User::factory(), + 'status' => TeamUserStatus::Active, + 'invitation_token' => null, + 'accepted_at' => now(), + ]); + } + + /** + * Indicate the team user has been removed. + */ + public function removed(): static + { + return $this->state(fn (array $attributes) => [ + 'status' => TeamUserStatus::Removed, + 'invitation_token' => null, + ]); + } +} diff --git a/database/migrations/2026_02_23_230918_create_teams_table.php b/database/migrations/2026_02_23_230918_create_teams_table.php new file mode 100644 index 00000000..e94da65d --- /dev/null +++ b/database/migrations/2026_02_23_230918_create_teams_table.php @@ -0,0 +1,30 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->boolean('is_suspended')->default(false); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('teams'); + } +}; diff --git a/database/migrations/2026_02_23_230919_create_team_users_table.php b/database/migrations/2026_02_23_230919_create_team_users_table.php new file mode 100644 index 00000000..b0715b91 --- /dev/null +++ b/database/migrations/2026_02_23_230919_create_team_users_table.php @@ -0,0 +1,37 @@ +id(); + $table->foreignId('team_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); + $table->string('email'); + $table->string('role')->default('member'); + $table->string('status')->default('pending'); + $table->string('invitation_token', 64)->unique()->nullable(); + $table->timestamp('invited_at')->nullable(); + $table->timestamp('accepted_at')->nullable(); + $table->timestamps(); + + $table->unique(['team_id', 'email']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('team_users'); + } +}; diff --git a/database/migrations/2026_03_05_114700_create_teams_tables.php b/database/migrations/2026_03_05_114700_create_teams_tables.php new file mode 100644 index 00000000..2d2ed3d9 --- /dev/null +++ b/database/migrations/2026_03_05_114700_create_teams_tables.php @@ -0,0 +1,44 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->boolean('is_suspended')->default(false); + $table->timestamps(); + }); + } + + if (! Schema::hasTable('team_users')) { + Schema::create('team_users', function (Blueprint $table) { + $table->id(); + $table->foreignId('team_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); + $table->string('email'); + $table->string('role')->default('member'); + $table->string('status')->default('pending'); + $table->string('invitation_token')->unique()->nullable(); + $table->timestamp('invited_at')->nullable(); + $table->timestamp('accepted_at')->nullable(); + $table->timestamps(); + + $table->unique(['team_id', 'email']); + }); + } + } + + public function down(): void + { + Schema::dropIfExists('team_users'); + Schema::dropIfExists('teams'); + } +}; diff --git a/database/migrations/2026_03_05_114737_add_extra_seats_to_teams_table.php b/database/migrations/2026_03_05_114737_add_extra_seats_to_teams_table.php new file mode 100644 index 00000000..0b13e5d0 --- /dev/null +++ b/database/migrations/2026_03_05_114737_add_extra_seats_to_teams_table.php @@ -0,0 +1,32 @@ +unsignedInteger('extra_seats')->default(0)->after('is_suspended'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('teams', function (Blueprint $table) { + $table->dropColumn('extra_seats'); + }); + } +}; diff --git a/database/migrations/2026_03_05_130556_add_is_comped_to_subscriptions_table.php b/database/migrations/2026_03_05_130556_add_is_comped_to_subscriptions_table.php new file mode 100644 index 00000000..03d52a5d --- /dev/null +++ b/database/migrations/2026_03_05_130556_add_is_comped_to_subscriptions_table.php @@ -0,0 +1,25 @@ +boolean('is_comped')->default(false)->after('quantity'); + }); + } + + public function down(): void + { + Schema::table('subscriptions', function (Blueprint $table) { + $table->dropColumn('is_comped'); + }); + } +}; diff --git a/resources/views/alt-pricing.blade.php b/resources/views/alt-pricing.blade.php deleted file mode 100644 index caaae847..00000000 --- a/resources/views/alt-pricing.blade.php +++ /dev/null @@ -1,191 +0,0 @@ - - {{-- Hero Section --}} -
-
- {{-- Primary Heading --}} -

- Discounted Licenses -

- - {{-- Introduction Description --}} -

- Thanks for supporting NativePHP and Bifrost.
- Now go get your discounted license! -

-
-
- - {{-- Pricing Section --}} - - - {{-- Ultra Section --}} - - - {{-- Testimonials Section --}} - {{-- --}} - - {{-- FAQ Section --}} -
- {{-- Section Heading --}} -

- Frequently Asked Questions -

- - {{-- FAQ List --}} -
- -

- No catch! They're the same licenses. -

-
- - -

- It'll renew at the discounted price. As long as you keep up your subscription, you'll - benefit from that discounted price. -

-
- - -

- Yes. Renewing your license entitles you to receive the - latest package updates but isn't required to build and - release apps. -

-
- - -

That's not currently possible.

-
- - -

- Absolutely! You can use NativePHP for any kind of project, - including commercial ones. We can't wait to see what you - build! -

-
- - -

- You'll get an invoice with your receipt via email and you can always retrieve past invoices - in the - - Stripe billing portal. - -

-
- - -

- You can manage your subscription via the - - Stripe billing portal. - -

-
-
-
-
diff --git a/resources/views/auth/register.blade.php b/resources/views/auth/register.blade.php index 18771ad7..51c79900 100644 --- a/resources/views/auth/register.blade.php +++ b/resources/views/auth/register.blade.php @@ -95,12 +95,6 @@ class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-3 -

- By creating an account, you agree to our - Terms of Service - and - Privacy Policy. -

@@ -122,13 +116,14 @@ class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-3
-

- By signing up with GitHub, you agree to our - Terms of Service - and - Privacy Policy. -

+ +

+ By creating an account, you agree to our + Terms of Service + and + Privacy Policy. +

diff --git a/resources/views/cart/show.blade.php b/resources/views/cart/show.blade.php index 382265bd..d014e8eb 100644 --- a/resources/views/cart/show.blade.php +++ b/resources/views/cart/show.blade.php @@ -232,9 +232,14 @@ class="flex gap-4 p-6" by {{ $item->plugin->user->display_name }}

-

- {{ $item->getFormattedPrice() }} -

+
+

+ {{ $item->getFormattedPrice() }} +

+ @if ($item->price_at_addition === 0 && $item->plugin->isOfficial()) + Included with Ultra + @endif +
diff --git a/resources/views/cart/success.blade.php b/resources/views/cart/success.blade.php index fd3e5111..972975de 100644 --- a/resources/views/cart/success.blade.php +++ b/resources/views/cart/success.blade.php @@ -1,238 +1,331 @@
-
- {{-- Loading State --}} - - {{-- Success State --}} - - {{-- Timeout/Error State --}} - +
+ @endif
diff --git a/resources/views/components/dashboard-card.blade.php b/resources/views/components/dashboard-card.blade.php index 7c8126a5..1ccf43d2 100644 --- a/resources/views/components/dashboard-card.blade.php +++ b/resources/views/components/dashboard-card.blade.php @@ -9,6 +9,8 @@ 'description' => null, 'badge' => null, 'badgeColor' => 'green', + 'secondBadge' => null, + 'secondBadgeColor' => 'yellow', ]) @php @@ -45,7 +47,7 @@
{{ $title }}
-
+
@if($count !== null) {{ $count }} @@ -55,9 +57,18 @@ {{ $value }} @endif - @if($badge) - - {{ $badge }} + @if($badge || $secondBadge) + + @if($badge) + + {{ $badge }} + + @endif + @if($secondBadge) + + {{ $secondBadge }} + + @endif @endif
diff --git a/resources/views/components/dashboard-menu.blade.php b/resources/views/components/dashboard-menu.blade.php index cedcb3c4..09d8ea41 100644 --- a/resources/views/components/dashboard-menu.blade.php +++ b/resources/views/components/dashboard-menu.blade.php @@ -48,6 +48,11 @@ class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 Integrations + @if(auth()->user()->hasActiveUltraSubscription() || auth()->user()->ownedTeam) + + Team + + @endif Manage Subscription diff --git a/resources/views/components/navbar/mobile-menu.blade.php b/resources/views/components/navbar/mobile-menu.blade.php index 7b163c7f..de95b16e 100644 --- a/resources/views/components/navbar/mobile-menu.blade.php +++ b/resources/views/components/navbar/mobile-menu.blade.php @@ -88,7 +88,7 @@ class="@md:grid-cols-3 grid grid-cols-2 text-xl" > @php $isHomeActive = request()->routeIs('welcome*'); - $isDocsActive = request()->is('docs*'); + $isUltraActive = request()->routeIs('pricing'); $isBlogActive = request()->routeIs('blog*'); $isPartnersActive = request()->routeIs('partners*'); $isServicesActive = request()->routeIs('build-my-app'); @@ -119,18 +119,18 @@ class="size-4 shrink-0"
- {{-- Docs Link --}} + {{-- Ultra Link --}} @@ -379,7 +379,7 @@ class="mx-auto mt-4 flex" aria-label="Social media" >
diff --git a/resources/views/components/navigation-bar.blade.php b/resources/views/components/navigation-bar.blade.php index 3161cba3..e17c770d 100644 --- a/resources/views/components/navigation-bar.blade.php +++ b/resources/views/components/navigation-bar.blade.php @@ -162,6 +162,25 @@ class="size-[3px] rotate-45 rounded-xs bg-gray-400 transition duration-200 dark: Develop + {{-- Decorative circle --}} + + + {{-- Link --}} + request()->routeIs('pricing'), + 'opacity-60 hover:opacity-100' => ! request()->routeIs('pricing'), + ]) + aria-current="{{ request()->routeIs('pricing') ? 'page' : 'false' }}" + > + Ultra + + {{-- Login/Logout --}} @feature(App\Features\ShowAuthButtons::class) {{-- Decorative circle --}} diff --git a/resources/views/components/plugin-card.blade.php b/resources/views/components/plugin-card.blade.php index 2db18917..498abd3f 100644 --- a/resources/views/components/plugin-card.blade.php +++ b/resources/views/components/plugin-card.blade.php @@ -20,7 +20,11 @@ class="size-12 shrink-0 rounded-xl object-cover" @endif - @if ($plugin->isPaid()) + @if ($plugin->isPaid() && $plugin->isOfficial() && auth()->user()?->hasUltraAccess()) + + Free with Ultra + + @elseif ($plugin->isPaid()) Paid diff --git a/resources/views/components/pricing-plan-features.blade.php b/resources/views/components/pricing-plan-features.blade.php index 4018ccbf..fca19834 100644 --- a/resources/views/components/pricing-plan-features.blade.php +++ b/resources/views/components/pricing-plan-features.blade.php @@ -48,6 +48,20 @@ class="size-5 shrink-0" developer seats (keys) + @if($features['teams'] ?? false) +
+
+ @endif {{-- Divider - Decorative --}} diff --git a/resources/views/customer/dashboard.blade.php b/resources/views/customer/dashboard.blade.php index a3109cb9..e001e1ad 100644 --- a/resources/views/customer/dashboard.blade.php +++ b/resources/views/customer/dashboard.blade.php @@ -15,6 +15,27 @@ + {{-- Session Messages --}} +
+ @if (session('success')) +
+

{{ session('success') }}

+
+ @endif + + @if (session('message')) +
+

{{ session('message') }}

+
+ @endif + + @if (session('error')) +
+

{{ session('error') }}

+
+ @endif +
+ {{-- Banners --}}
@@ -96,8 +117,35 @@ :href="route('customer.plugins.create')" link-text="Submit a plugin" /> + @endfeature + {{-- Team Card --}} + @if($hasTeam) + + @elseif($hasMaxAccess) + + @endif + {{-- Connected Accounts Card --}}
- {{-- Session Messages --}} -
- @if (session('success')) -
-

{{ session('success') }}

-
- @endif - - @if (session('message')) -
-

{{ session('message') }}

-
- @endif - - @if (session('error')) -
-

{{ session('error') }}

-
- @endif -
diff --git a/resources/views/customer/licenses/index.blade.php b/resources/views/customer/licenses/index.blade.php index c319521c..6655b490 100644 --- a/resources/views/customer/licenses/index.blade.php +++ b/resources/views/customer/licenses/index.blade.php @@ -296,9 +296,16 @@ class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text @endif -

- {{ $license->key }} -

+
+

+ {{ Str::mask($license->key, '*', 8, -4) }} + {{ $license->key }} +

+ +
@@ -378,9 +385,16 @@ class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text @endif
-

- {{ $subLicense->key }} -

+
+

+ {{ Str::mask($subLicense->key, '*', 8, -4) }} + {{ $subLicense->key }} +

+ +
diff --git a/resources/views/customer/licenses/list.blade.php b/resources/views/customer/licenses/list.blade.php index 70c05a92..ef147e1f 100644 --- a/resources/views/customer/licenses/list.blade.php +++ b/resources/views/customer/licenses/list.blade.php @@ -82,9 +82,16 @@ @endif
-

- {{ $license->key }} -

+
+

+ {{ Str::mask($license->key, '*', 8, -4) }} + {{ $license->key }} +

+ +
@@ -164,9 +171,16 @@ @endif
-

- {{ $subLicense->key }} -

+
+

+ {{ Str::mask($subLicense->key, '*', 8, -4) }} + {{ $subLicense->key }} +

+ +
diff --git a/resources/views/customer/licenses/show.blade.php b/resources/views/customer/licenses/show.blade.php index 96c074e6..faf6bdee 100644 --- a/resources/views/customer/licenses/show.blade.php +++ b/resources/views/customer/licenses/show.blade.php @@ -5,11 +5,11 @@
- + - Dashboard + Licenses

{{ $license->name ?: $license->policy_name }} @@ -68,18 +68,29 @@
License Key
-
+
- {{ $license->key }} + {{ Str::mask($license->key, '*', 8, -4) }} + {{ $license->key }} - +
+ + +

diff --git a/resources/views/customer/plugins/create.blade.php b/resources/views/customer/plugins/create.blade.php index 5b3e5674..cac4635a 100644 --- a/resources/views/customer/plugins/create.blade.php +++ b/resources/views/customer/plugins/create.blade.php @@ -196,6 +196,100 @@ class="sr-only" @endfeature + {{-- Author Display Name (only show if not set) --}} + @unless(auth()->user()->display_name) +
+

Author Display Name

+

+ This is how your name will appear on your plugins in the directory. You can change this later. +

+
+ +

+ Leave blank to use your account name: {{ auth()->user()->name }} +

+
+
+ @endunless + + {{-- Stripe Connect (only show when paid selected and not connected) --}} + @feature(App\Features\AllowPaidPlugins::class) +
+ @if ($developerAccount && $developerAccount->hasCompletedOnboarding()) +
+
+
+ + + +
+
+

Stripe Connect Active

+

+ Your account is ready to receive payouts for paid plugin sales. +

+
+
+
+ @elseif ($developerAccount) +
+
+
+ + + +
+
+

Stripe Setup Incomplete

+

+ You need to complete your Stripe Connect setup before you can submit a paid plugin. +

+ + Continue Setup + + + + +
+
+
+ @else +
+
+
+ + + +
+
+

Connect Stripe to Sell Plugins

+

+ To submit a paid plugin, you need to connect your Stripe account. You'll earn 70% of each sale. +

+ + Connect Stripe + + + + +
+
+
+ @endif +
+ @endfeature + {{-- Repository Selection (for all plugins) --}}
diff --git a/resources/views/customer/plugins/index.blade.php b/resources/views/customer/plugins/index.blade.php index d6dfc827..7211faec 100644 --- a/resources/views/customer/plugins/index.blade.php +++ b/resources/views/customer/plugins/index.blade.php @@ -84,151 +84,75 @@
- {{-- Author Display Name Section --}} -
-
-
-
-
- - - -
-
-

Author Display Name

-

- This is how your name will appear on your plugins in the directory. -

-
- @csrf - @method('PATCH') -
- - @error('display_name') -

{{ $message }}

- @enderror -
- -
-

- Leave blank to use your account name: {{ auth()->user()->name }} -

-
-
-
-
-
- - {{-- Stripe Connect Section (only show when paid plugins are enabled) --}} + {{-- Stripe Connect Status (only show when connected or in progress) --}} @feature(App\Features\AllowPaidPlugins::class) -
@if ($developerAccount && $developerAccount->hasCompletedOnboarding()) - {{-- Connected Account --}} -
-
-
-
- - - -
-
-

Stripe Connect Active

-

- Your developer account is set up and ready to receive payouts for paid plugin sales. -

-
- - - - - Payouts {{ $developerAccount->payouts_enabled ? 'Enabled' : 'Pending' }} - - - - - - {{ $developerAccount->stripe_connect_status->label() }} - +
+
+
+
+
+ + + +
+
+

Stripe Connect Active

+

+ Your developer account is set up and ready to receive payouts for paid plugin sales. +

+
+ + + + + Payouts {{ $developerAccount->payouts_enabled ? 'Enabled' : 'Pending' }} + + + + + + {{ $developerAccount->stripe_connect_status->label() }} + +
+ + View Dashboard + + + +
- - View Dashboard - - - -
@elseif ($developerAccount) - {{-- Onboarding In Progress --}} -
-
-
-
- - - -
-
-

Complete Your Stripe Setup

-

- You've started the Stripe Connect setup but there are still some steps remaining. Complete the onboarding to start receiving payouts. -

+
+
+
+
+
+ + + +
+
+

Complete Your Stripe Setup

+

+ You've started the Stripe Connect setup but there are still some steps remaining. Complete the onboarding to start receiving payouts. +

+
-
- - Continue Setup - - - - -
-
- @else - {{-- No Developer Account --}} -
-
-
- -
-

Sell Paid Plugins

-

- Want to sell premium plugins? Connect your Stripe account to receive payouts when customers purchase your paid plugins. You'll earn 70% of each sale. -

-
+
- - Connect Stripe - - - -
@endif -
@endfeature {{-- Success Message --}} diff --git a/resources/views/customer/purchased-plugins/index.blade.php b/resources/views/customer/purchased-plugins/index.blade.php index 53b96f0c..82862b75 100644 --- a/resources/views/customer/purchased-plugins/index.blade.php +++ b/resources/views/customer/purchased-plugins/index.blade.php @@ -247,6 +247,53 @@ class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text
@endif + + {{-- Team Plugins --}} + @if ($teamPlugins->isNotEmpty()) +

+ Team Plugins + — shared by {{ $teamOwnerName }} +

+ + @endif
diff --git a/resources/views/customer/team/index.blade.php b/resources/views/customer/team/index.blade.php new file mode 100644 index 00000000..b153262b --- /dev/null +++ b/resources/views/customer/team/index.blade.php @@ -0,0 +1,120 @@ + +
+ {{-- Header --}} +
+
+
+
+ + + + + Dashboard + +

Team

+

+ Manage your team and share your Ultra benefits +

+
+ +
+
+
+ + {{-- Content --}} +
+ {{-- Flash Messages --}} + @if(session()->has('success')) +
+
+ + + +

{{ session('success') }}

+
+
+ @endif + + @if(session()->has('error')) +
+
+ + + +

{{ session('error') }}

+
+
+ @endif + + @if($team) + {{-- User owns a team --}} + + @elseif($membership) + {{-- User is a member of another team --}} +
+

Team Membership

+

+ You are a member of {{ $membership->team->name }}. +

+
+

Your benefits include:

+
    +
  • Free access to all first-party NativePHP plugins
  • +
  • Subscriber-tier pricing on third-party plugins
  • +
  • Access to the Plugin Dev Kit GitHub repository
  • +
+
+
+ @elseif(auth()->user()->hasActiveUltraSubscription()) + {{-- User has Ultra but no team --}} +
+

Create a Team

+

+ As an Ultra subscriber, you can create a team and invite up to 10 members who will share your benefits. +

+
+ @csrf +
+
+ + +
+ +
+ @error('name') +

{{ $message }}

+ @enderror +
+
+ @else + {{-- User doesn't have Ultra --}} +
+

Teams

+

+ Teams are available to Ultra subscribers. Upgrade to Ultra to create a team and share benefits with up to 10 members. +

+ +
+ @endif +
+
+
diff --git a/resources/views/livewire/mobile-pricing.blade.php b/resources/views/livewire/mobile-pricing.blade.php index 71bc19df..0e6a12b1 100644 --- a/resources/views/livewire/mobile-pricing.blade.php +++ b/resources/views/livewire/mobile-pricing.blade.php @@ -1,192 +1,234 @@
- @if (! $discounted) -
- {{-- Section Heading --}} -

- Purchase a license -

+
+

+ Choose your plan +

- {{-- Section Description --}} -

- Start your journey to become a mobile developer -

-
- @endif +

+ Get the most out of NativePHP +

+
- {{-- Pricing Plans --}} + {{-- Interval Toggle --}}
- @if (! $discounted) - {{-- Mini Plan --}} -
+ + +
- {{-- Price --}} -
-
FREE
-
- with - - Bifrost - -
+ {{-- Ultra Plan Card --}} +
+ {{-- Plan Name --}} +

+ + Ultra + +

+ + {{-- Price --}} +
+
+ $ +
+
+
+
- + Save $70/year vs monthly +
+ + {{-- CTA Button --}} + @auth + + @else + + @endauth - {{-- OpenCollective Alternative --}} -
-
-
+ {{-- Features --}} +
+
+ -
- or +
All first-party plugins for free
+
+
+ +
Discounts on third-party plugins
- -
-

- Donate any amount via - - OpenCollective - -

- + +
Claude Code Plugin Dev Kit for free
+
+
+ +
Discounts on NativePHP courses and apps
+
+
+ +
Premium support — expedited turnaround
+
+
+ +
Teams support — invite and manage members
- -
- @endif - - {{-- Pro Plan --}} - - - {{-- Max Plan - Most Popular --}} - +
@guest diff --git a/resources/views/livewire/team-manager.blade.php b/resources/views/livewire/team-manager.blade.php new file mode 100644 index 00000000..35244879 --- /dev/null +++ b/resources/views/livewire/team-manager.blade.php @@ -0,0 +1,233 @@ +
+ @if($team->is_suspended) +
+
+
+ + + +
+
+

+ Your team is currently suspended. Reactivate your Ultra subscription to restore team benefits. +

+
+
+
+ @endif + + {{-- Invite Form --}} + @if(!$team->is_suspended) +
+

Invite a Team Member

+
+ @csrf +
+ +
+ +
+ @error('email') +

{{ $message }}

+ @enderror +
+ @endif + + {{-- Seat Management --}} +
+
+
+

Seats

+

+ {{ $team->occupiedSeatCount() }} of {{ $team->totalSeatCapacity() }} seats used + @if($team->extra_seats > 0) + ({{ $team->extra_seats }} extra) + @endif +

+
+ @if(!$team->is_suspended) +
+ + @if($removableSeats > 0) + + @endif + + {{-- Add Seats Modal --}} +
+
+

Add Extra Seats

+

+ Extra seats cost ${{ $extraSeatPriceMonthly }}/mo or ${{ $extraSeatPriceYearly }}/yr per seat, matching your current billing interval. +

+
+ + +
+
+ + +
+
+
+ + {{-- Remove Seats Modal --}} +
+
+

Remove Extra Seats

+

+ You currently have {{ $team->extra_seats }} extra seat(s). Seats are removed immediately and you'll be credited for the unused time on your next bill. +

+
+ + +
+
+ + +
+
+
+
+ @endif +
+
+ + {{-- Pending Invitations --}} + @if($pendingInvitations->isNotEmpty()) +
+

+ Pending Invitations + + ({{ $pendingInvitations->count() }}) + +

+
+
    + @foreach($pendingInvitations as $invitation) +
  • +
    +
    +

    + {{ $invitation->email }} +

    + @if($invitation->invited_at) +

    + Invited {{ $invitation->invited_at->diffForHumans() }} +

    + @endif +
    +
    +
    + @csrf + +
    +
    + @csrf + @method('DELETE') + +
    +
    +
    +
  • + @endforeach +
+
+
+ @endif + + {{-- Team Members --}} +
+

+ Team Members +

+
+ + {{-- Active Members --}} + @if($activeMembers->isNotEmpty()) +
+
    + @foreach($activeMembers as $member) +
  • +
    +
    +

    + {{ $member->user?->display_name ?? $member->email }} +

    +

    + {{ $member->email }} +

    + @if($member->accepted_at) +

    + Joined {{ $member->accepted_at->diffForHumans() }} +

    + @endif +
    +
    + @csrf + @method('DELETE') + +
    +
    +
  • + @endforeach +
+
+ @else +
+

No active team members yet. Invite someone to get started.

+
+ @endif +
diff --git a/resources/views/plugin-show.blade.php b/resources/views/plugin-show.blade.php index a0963e4f..8750c93a 100644 --- a/resources/views/plugin-show.blade.php +++ b/resources/views/plugin-show.blade.php @@ -133,8 +133,16 @@ class="w-full shrink-0 lg:sticky lg:top-24 lg:w-80" @if ($plugin->isPaid() && $bestPrice && $plugin->is_active)
-

Price

- @if ($hasDiscount && $regularPrice) + @if ($bestPrice->amount === 0 && $plugin->isOfficial()) +

Included with Ultra

+

Free

+ @if ($regularPrice) +

+ ${{ number_format($regularPrice->amount / 100) }} +

+ @endif + @elseif ($hasDiscount && $regularPrice) +

Price

${{ number_format($regularPrice->amount / 100) }}

@@ -144,12 +152,14 @@ class="w-full shrink-0 lg:sticky lg:top-24 lg:w-80"

{{ $bestPrice->tier->label() }} pricing applied

+

One-time purchase

@else +

Price

${{ number_format($bestPrice->amount / 100) }}

+

One-time purchase

@endif -

One-time purchase

@csrf diff --git a/resources/views/pricing.blade.php b/resources/views/pricing.blade.php index 6863466d..7152d7fd 100644 --- a/resources/views/pricing.blade.php +++ b/resources/views/pricing.blade.php @@ -1,11 +1,10 @@ - + {{-- Hero Section --}}
- {{-- Primary Heading --}}

- NativePHP for Mobile + NativePHP Ultra

- {{-- Introduction Description --}}

- This changes everything! Now you can use the tools you already - know to build rich, native, - mobile - apps... right now! + Premium plugins, tools, and support to supercharge your + NativePHP development.

- - {{-- Platform Cards --}} -
- {{-- iOS Card --}} -
-
- {{-- Subtitle --}} -

Available now for

- {{-- Title --}} -

- iOS -

- {{-- Text --}} -

- Build and ship App Store approved iOS apps today! -

- {{-- Mockup --}} -
- iOS phone mockup displaying a NativePHP application -
- {{-- White blurred circle - Decorative --}} - - {{-- Blue blurred circle - Decorative --}} - -
- - {{-- Blurred circle - Decorative --}} - -
- - {{-- Android Card --}} -
-
- {{-- Subtitle --}} -

Available now for

- {{-- Title --}} -

- Android -

- {{-- Text --}} -

- Sign up and build apps for Android today! -

- {{-- Mockup --}} -
- Android phone mockup displaying a NativePHP application -
- {{-- White blurred circle - Decorative --}} - - {{-- Center blurred circle - Decorative --}} - -
- - {{-- Blurred circle - Decorative --}} - -
-
-
- - {{-- Quick Instructions Section --}} -
-
- {{-- Section Heading --}} -

- Quick instructions -

- - {{-- Section Description --}} -

- Get your app up and running in minutes. -

-
- - {{-- Installation Steps --}} -
- {{-- Step 1 --}} -
- {{-- Step number --}} -

- Step 1 -

- {{-- Step description --}} -

- Buy a license. -

- {{-- Box --}} -
-
- {{-- Checkmark --}} - - {{-- Success message --}} -
-
- Payment successful! -
-
- You've purchased a license. -
-
-
-
-
- - {{-- Step 2 --}} -
- {{-- Step number --}} -

- Step 2 -

- {{-- Step description --}} -

- Install the private Composer package. -

- {{-- Box --}} -
- {{-- Terminal --}} -
-
- - - -
-
-
- ~/native-php-app -
-
- composer require nativephp/mobile -
-
-
- {{-- Background image - Decorative --}} - -
-
- - {{-- Step 3 --}} -
- {{-- Step number --}} -

- Step 3 -

- {{-- Step description --}} -

- Build your app. -

- {{-- Box --}} -
- {{-- Background image --}} - Developer holding a phone with NativePHP application -
-
-
{{-- Pricing Section --}} - - - {{-- Ultra Section --}} - - - {{-- Testimonials Section --}} - {{-- --}} + {{-- FAQ Section --}}
- {{-- Section Heading --}}

- {{-- FAQ List --}}
- +

- We want to build an amazing tool and make it sustainable. A - lot of NativePHP is already fully open source. With - NativePHP for Mobile, we need to take a different path to - ensure that the entire project continues to get the support - it deserves. + NativePHP Ultra is a premium subscription that gives you + access to all first-party plugins, discounts on + third-party plugins, the Claude Code Plugin Dev Kit, + discounts on NativePHP courses and apps, Teams + support, and premium support with expedited + turnaround times.

- +

- Yes! Once we've hit sustainability and can afford to - continue investing in this project indirectly, then a - version of it will be fully open source and made available - for free. + No! NativePHP for Mobile is completely free. Ultra is + an optional premium subscription for developers who + want access to additional tools, plugins, and + priority support.

- +

- Yes, a single license will let you build apps for both iOS - and Android. + All first-party NativePHP plugins are included with + your Ultra subscription at no additional cost. As we + release new first-party plugins, they will be + automatically available to you.

- -

- Every NativePHP for Mobile license entitles you to - release - a certain number of applications. A 'released' app is when - it's published or distributed (typically through an app - store). -

-
+

- However, you are welcome to - build - (develop), as many apps as you want. If no one else besides - you and other license holders have access to your app, then - it doesn't count towards your quota of 'released' apps. + The Claude Code Plugin Dev Kit is a set of tools and + resources that help you build NativePHP plugins using + Claude Code. It's available for free to Ultra + subscribers.

- -

- A 'developer seat' represents an individual developer that - can build apps under that license plan. -

-
-

- For example, on the Pro plan, the license holder can create - up to 10 unique license keys that can be assigned to - individual developers, one key per developer. -

-
+

- This allows the license holder to control who has the - ability to use their license for building apps. You can add - or remove developers and each will get their own unique - license key. If a developer leaves your team, you can revoke - their license key to prevent abuse. + Ultra subscribers get discounts on NativePHP courses + and apps. As we release new educational content and + tools, you'll automatically be eligible for + subscriber pricing.

- +

- You will get direct access to our GitHub repository for NativePHP for Mobile. This will allow you - to raise issues directly with the team, which are prioritized higher than issues we see on Discord. + Ultra includes Teams support, which lets you invite + other users into your team so they can share your + plugins and other Ultra benefits. As the account + owner, you can manage your team members and remove + access at any time.

-

- It also means you can try out features that are still in development before they're generally - available and help us to shape and refine them for release. -

-
- - -

You can purchase more Pro licenses as needed.

- +

- The Early Access Program (EAP) provided initial access to - the NativePHP for Mobile platform for early adopters at - reduced pricing while we worked on releasing v1 of the - technology. The EAP started in February and ended in May - 2025. + Ultra includes 10 team seats. If you need more, extra + seats can be purchased at $5/seat/month or $4/seat/year + from your team settings page.

- +

- Your license will renew at the price you originally paid, as - long as you renew before it expires. If you renew after it - expires, then you will have to pay the prices available at - that time. + Premium support gives you expedited turnaround on + support issues. When you need help, your requests are + prioritized so you can get back to building faster.

- +

- Yes. Renewing your license entitles you to receive the - latest package updates but isn't required to build and - release apps. + You can manage your billing via the Stripe billing + portal. If you'd like to switch between monthly and + annual, you can cancel your current subscription and + start a new one on the billing interval you prefer.

- -

That's not currently possible.

-
- - -

- Definitely. NativePHP for Mobile apps are just like other - iOS and Android apps - they're as secure as you make them. -

-
- {{-- --}} - {{--

--}} - {{--

--}} - {{--
--}} - +

- Absolutely! You can use NativePHP for any kind of project, - including commercial ones. We can't wait to see what you - build! + Yes, you can cancel at any time. You'll continue to + have access to Ultra benefits until the end of your + current billing period.

- If you purchased after May 6, 2025, you should get an - invoice with your receipt via email. -

-

- For purchases made before this, you simply need to - - follow the instructions here - - to generate your invoice. + Yes, invoices are sent automatically with your receipt + via email after each payment.

diff --git a/routes/web.php b/routes/web.php index de78bb68..43000d00 100644 --- a/routes/web.php +++ b/routes/web.php @@ -19,6 +19,8 @@ use App\Http\Controllers\PurchaseHistoryController; use App\Http\Controllers\ShowBlogController; use App\Http\Controllers\ShowDocumentationController; +use App\Http\Controllers\TeamController; +use App\Http\Controllers\TeamUserController; use Illuminate\Support\Facades\Route; use Illuminate\Support\Str; use Laravel\Pennant\Middleware\EnsureFeaturesAreActive; @@ -62,8 +64,7 @@ Route::get('opencollective/claim', App\Livewire\ClaimDonationLicense::class)->name('opencollective.claim'); Route::view('/', 'welcome')->name('welcome'); -Route::redirect('pricing', 'blog/nativephp-for-mobile-is-now-free')->name('pricing'); -Route::view('alt-pricing', 'alt-pricing')->name('alt-pricing')->middleware('signed'); +Route::view('ultra', 'pricing')->name('pricing'); Route::view('wall-of-love', 'wall-of-love')->name('wall-of-love'); Route::view('brand', 'brand')->name('brand'); Route::get('showcase/{platform?}', [App\Http\Controllers\ShowcaseController::class, 'index']) @@ -214,6 +215,9 @@ return response('Goodbye'); })->name('callback'); +// Team invitation acceptance (public route - no auth required) +Route::get('team/invitation/{token}', [TeamUserController::class, 'accept'])->name('team.invitation.accept'); + // Dashboard route Route::middleware(['auth', EnsureFeaturesAreActive::using(ShowAuthButtons::class)]) ->get('dashboard', [CustomerLicenseController::class, 'index']) @@ -271,6 +275,13 @@ return $user->redirectToBillingPortal(route('dashboard')); })->name('billing-portal'); + // Team management routes + Route::get('team', [TeamController::class, 'index'])->name('team.index'); + Route::post('team', [TeamController::class, 'store'])->name('team.store'); + Route::post('team/invite', [TeamUserController::class, 'invite'])->name('team.invite'); + Route::delete('team/users/{teamUser}', [TeamUserController::class, 'remove'])->name('team.users.remove'); + Route::post('team/users/{teamUser}/resend', [TeamUserController::class, 'resend'])->name('team.users.resend'); + // Sub-license management routes Route::post('licenses/{licenseKey}/sub-licenses', [CustomerSubLicenseController::class, 'store'])->name('licenses.sub-licenses.store'); Route::patch('licenses/{licenseKey}/sub-licenses/{subLicense}', [CustomerSubLicenseController::class, 'update'])->name('licenses.sub-licenses.update'); diff --git a/tests/Feature/MobilePricingTest.php b/tests/Feature/MobilePricingTest.php index 756ed61b..1bb9e391 100644 --- a/tests/Feature/MobilePricingTest.php +++ b/tests/Feature/MobilePricingTest.php @@ -22,13 +22,9 @@ public function authenticated_users_will_directly_create_checkout_session() $component = Livewire::test(MobilePricing::class); $component->assertSeeHtml([ - // 'wire:click="createCheckoutSession(\'mini\')"', - 'wire:click="createCheckoutSession(\'pro\')"', 'wire:click="createCheckoutSession(\'max\')"', ]); $component->assertDontSeeHtml([ - // '@click="$dispatch(\'open-purchase-modal\', { plan: \'mini\' })"', - '@click="$dispatch(\'open-purchase-modal\', { plan: \'pro\' })"', '@click="$dispatch(\'open-purchase-modal\', { plan: \'max\' })"', ]); } @@ -41,13 +37,9 @@ public function guest_users_see_purchase_modal_component() Livewire::test(MobilePricing::class) ->assertSeeLivewire('purchase-modal') ->assertSeeHtml([ - // '@click="$dispatch(\'open-purchase-modal\', { plan: \'mini\' })"', - '@click="$dispatch(\'open-purchase-modal\', { plan: \'pro\' })"', '@click="$dispatch(\'open-purchase-modal\', { plan: \'max\' })"', ]) ->assertDontSeeHtml([ - // 'wire:click="createCheckoutSession(\'mini\')"', - 'wire:click="createCheckoutSession(\'pro\')"', 'wire:click="createCheckoutSession(\'max\')"', ]); } @@ -68,4 +60,19 @@ public function it_validates_email_before_creating_user() ->call('handlePurchaseRequest', ['email' => 'invalid-email']) ->assertHasErrors('email'); } + + #[Test] + public function default_interval_is_month() + { + Livewire::test(MobilePricing::class) + ->assertSet('interval', 'month'); + } + + #[Test] + public function interval_can_be_set_to_year() + { + Livewire::test(MobilePricing::class) + ->set('interval', 'year') + ->assertSet('interval', 'year'); + } } diff --git a/tests/Feature/MobileRouteTest.php b/tests/Feature/MobileRouteTest.php index 090438bc..d02166a7 100644 --- a/tests/Feature/MobileRouteTest.php +++ b/tests/Feature/MobileRouteTest.php @@ -4,7 +4,6 @@ use App\Features\ShowAuthButtons; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Facades\URL; use Laravel\Pennant\Feature; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; @@ -17,33 +16,16 @@ protected function setUp(): void { parent::setUp(); - // Enable the auth feature flag since the pricing page might reference it Feature::define(ShowAuthButtons::class, false); } #[Test] - public function pricing_route_redirects_to_blog_post() - { - $this - ->get(route('pricing')) - ->assertRedirect('blog/nativephp-for-mobile-is-now-free'); - } - - #[Test] - public function alt_pricing_route_does_not_include_stripe_payment_links() + public function pricing_route_returns_pricing_page() { $this ->withoutVite() - ->get(URL::signedRoute('alt-pricing')) - ->assertDontSee('buy.stripe.com'); - } - - #[Test] - public function alt_pricing_route_includes_mobile_pricing_livewire_component() - { - $this - ->withoutVite() - ->get(URL::signedRoute('alt-pricing')) + ->get(route('pricing')) + ->assertOk() ->assertSeeLivewire('mobile-pricing'); } } diff --git a/tests/Feature/TeamManagementTest.php b/tests/Feature/TeamManagementTest.php new file mode 100644 index 00000000..7925af42 --- /dev/null +++ b/tests/Feature/TeamManagementTest.php @@ -0,0 +1,675 @@ + self::MAX_PRICE_ID]); + } + + private function createUltraUser(): User + { + $user = User::factory()->create(); + License::factory()->max()->active()->create(['user_id' => $user->id]); + Subscription::factory()->for($user)->active()->create([ + 'stripe_price' => self::MAX_PRICE_ID, + ]); + + return $user; + } + + private function createTeamWithOwner(): array + { + $owner = $this->createUltraUser(); + $team = Team::factory()->create(['user_id' => $owner->id, 'name' => 'Test Team']); + + return [$owner, $team]; + } + + // ======================================== + // Team Creation Tests + // ======================================== + + public function test_ultra_subscriber_can_create_team(): void + { + $user = $this->createUltraUser(); + + $response = $this->actingAs($user) + ->post(route('customer.team.store'), ['name' => 'My Team']); + + $response->assertRedirect(route('customer.team.index')); + $response->assertSessionHas('success'); + + $this->assertDatabaseHas('teams', [ + 'user_id' => $user->id, + 'name' => 'My Team', + 'is_suspended' => false, + ]); + } + + public function test_non_ultra_user_cannot_create_team(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user) + ->post(route('customer.team.store'), ['name' => 'My Team']); + + $response->assertSessionHas('error'); + $this->assertDatabaseMissing('teams', ['user_id' => $user->id]); + } + + public function test_cannot_create_duplicate_team(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $response = $this->actingAs($owner) + ->post(route('customer.team.store'), ['name' => 'Another Team']); + + $response->assertSessionHas('error'); + $this->assertCount(1, Team::where('user_id', $owner->id)->get()); + } + + public function test_team_name_is_required(): void + { + $user = $this->createUltraUser(); + + $response = $this->actingAs($user) + ->post(route('customer.team.store'), ['name' => '']); + + $response->assertSessionHasErrors('name'); + } + + // ======================================== + // Invitation Tests + // ======================================== + + public function test_owner_can_invite_member_by_email(): void + { + Notification::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + $response = $this->actingAs($owner) + ->post(route('customer.team.invite'), ['email' => 'member@example.com']); + + $response->assertSessionHas('success'); + + $this->assertDatabaseHas('team_users', [ + 'team_id' => $team->id, + 'email' => 'member@example.com', + 'status' => TeamUserStatus::Pending->value, + ]); + + Notification::assertSentOnDemand(TeamInvitation::class); + } + + public function test_cannot_invite_duplicate_email(): void + { + Notification::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'member@example.com', + 'status' => TeamUserStatus::Active, + ]); + + $response = $this->actingAs($owner) + ->post(route('customer.team.invite'), ['email' => 'member@example.com']); + + $response->assertSessionHas('error'); + } + + public function test_cannot_invite_when_team_suspended(): void + { + Notification::fake(); + + $owner = $this->createUltraUser(); + $team = Team::factory()->suspended()->create(['user_id' => $owner->id]); + + $response = $this->actingAs($owner) + ->post(route('customer.team.invite'), ['email' => 'member@example.com']); + + $response->assertSessionHas('error'); + Notification::assertNothingSent(); + } + + public function test_cannot_invite_beyond_seat_limit(): void + { + Notification::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + // Create 10 active members to fill all seats + TeamUser::factory()->count(10)->active()->create(['team_id' => $team->id]); + + $response = $this->actingAs($owner) + ->post(route('customer.team.invite'), ['email' => 'extra@example.com']); + + $response->assertSessionHas('show_add_seats', true); + Notification::assertNothingSent(); + } + + // ======================================== + // Member Removal Tests + // ======================================== + + public function test_owner_can_remove_member(): void + { + Notification::fake(); + Queue::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + $member = TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'email' => 'member@example.com', + ]); + + $response = $this->actingAs($owner) + ->delete(route('customer.team.users.remove', $member)); + + $response->assertSessionHas('success'); + + $member->refresh(); + $this->assertEquals(TeamUserStatus::Removed, $member->status); + + Notification::assertSentOnDemand(TeamUserRemoved::class); + Queue::assertPushed(RevokeTeamUserAccessJob::class); + } + + public function test_non_owner_cannot_remove_member(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + $otherUser = User::factory()->create(); + + $member = TeamUser::factory()->active()->create(['team_id' => $team->id]); + + $response = $this->actingAs($otherUser) + ->delete(route('customer.team.users.remove', $member)); + + $response->assertSessionHas('error'); + } + + // ======================================== + // Invitation Acceptance Tests + // ======================================== + + public function test_authenticated_user_can_accept_invitation(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(['email' => 'member@example.com']); + $teamUser = TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'member@example.com', + 'invitation_token' => 'test-token-123', + ]); + + $response = $this->actingAs($member) + ->get(route('team.invitation.accept', 'test-token-123')); + + $response->assertRedirect(route('dashboard')); + $response->assertSessionHas('success'); + + $teamUser->refresh(); + $this->assertEquals(TeamUserStatus::Active, $teamUser->status); + $this->assertEquals($member->id, $teamUser->user_id); + $this->assertNull($teamUser->invitation_token); + } + + public function test_email_mismatch_rejects_acceptance(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $otherUser = User::factory()->create(['email' => 'other@example.com']); + $teamUser = TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'member@example.com', + 'invitation_token' => 'test-token-456', + ]); + + $response = $this->actingAs($otherUser) + ->get(route('team.invitation.accept', 'test-token-456')); + + $response->assertRedirect(route('dashboard')); + $response->assertSessionHas('error'); + + $teamUser->refresh(); + $this->assertEquals(TeamUserStatus::Pending, $teamUser->status); + } + + public function test_unauthenticated_user_stores_token_in_session(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'newuser@example.com', + 'invitation_token' => 'test-token-789', + ]); + + $response = $this->get(route('team.invitation.accept', 'test-token-789')); + + $response->assertRedirect(route('customer.login')); + $response->assertSessionHas('pending_team_invitation_token', 'test-token-789'); + } + + public function test_invitation_accepted_after_registration(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $email = 'testuser@gmail.com'; + + $teamUser = TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => $email, + 'invitation_token' => 'test-token-abc', + ]); + + $response = $this->withSession(['pending_team_invitation_token' => 'test-token-abc']) + ->post(route('customer.register'), [ + 'name' => 'New User', + 'email' => $email, + 'password' => 'password123', + 'password_confirmation' => 'password123', + ]); + + $teamUser->refresh(); + $this->assertEquals(TeamUserStatus::Active, $teamUser->status); + $this->assertNotNull($teamUser->user_id); + } + + public function test_invitation_accepted_after_login(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create([ + 'email' => 'member@example.com', + 'password' => bcrypt('password123'), + ]); + + $teamUser = TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'member@example.com', + 'invitation_token' => 'test-token-def', + ]); + + $response = $this->withSession(['pending_team_invitation_token' => 'test-token-def']) + ->post(route('customer.login'), [ + 'email' => 'member@example.com', + 'password' => 'password123', + ]); + + $teamUser->refresh(); + $this->assertEquals(TeamUserStatus::Active, $teamUser->status); + $this->assertEquals($member->id, $teamUser->user_id); + } + + // ======================================== + // Access Tests + // ======================================== + + public function test_team_owner_is_ultra_team_member(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $this->assertTrue($owner->isUltraTeamMember()); + } + + public function test_team_owner_gets_official_plugin_access(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $officialPlugin = Plugin::factory()->paid()->approved()->create([ + 'is_official' => true, + ]); + + $this->assertTrue($owner->hasPluginAccess($officialPlugin)); + } + + public function test_suspended_team_owner_is_not_ultra_team_member(): void + { + $owner = $this->createUltraUser(); + $team = Team::factory()->suspended()->create(['user_id' => $owner->id]); + + $this->assertFalse($owner->isUltraTeamMember()); + } + + public function test_team_member_gets_official_plugin_access(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $officialPlugin = Plugin::factory()->paid()->approved()->create([ + 'is_official' => true, + ]); + + $this->assertTrue($member->hasPluginAccess($officialPlugin)); + } + + public function test_team_member_does_not_get_third_party_plugin_access(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $thirdPartyPlugin = Plugin::factory()->paid()->approved()->create([ + 'is_official' => false, + ]); + + $this->assertFalse($member->hasPluginAccess($thirdPartyPlugin)); + } + + public function test_team_member_gets_subscriber_pricing(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $tiers = $member->getEligiblePriceTiers(); + + $this->assertContains(PriceTier::Subscriber, $tiers); + } + + public function test_non_team_member_does_not_get_subscriber_pricing(): void + { + $user = User::factory()->create(); + + $tiers = $user->getEligiblePriceTiers(); + + $this->assertNotContains(PriceTier::Subscriber, $tiers); + } + + public function test_team_member_gets_product_access_via_team(): void + { + $owner = $this->createUltraUser(); + $team = Team::factory()->create(['user_id' => $owner->id]); + + $product = Product::factory()->create(['slug' => 'plugin-dev-kit']); + ProductLicense::factory()->create([ + 'user_id' => $owner->id, + 'product_id' => $product->id, + ]); + + $member = User::factory()->create(); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $this->assertTrue($member->hasProductLicense($product)); + } + + // ======================================== + // Suspension Tests + // ======================================== + + public function test_team_suspended_on_subscription_cancel(): void + { + Queue::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + $event = new \Laravel\Cashier\Events\WebhookReceived([ + 'type' => 'customer.subscription.deleted', + 'data' => [ + 'object' => [ + 'customer' => $owner->stripe_id ?? 'cus_test', + ], + ], + ]); + + // We can't fully simulate Stripe, but we can test the job dispatch + // by calling SuspendTeamJob directly + $job = new SuspendTeamJob($owner->id); + $job->handle(); + + $team->refresh(); + $this->assertTrue($team->is_suspended); + } + + public function test_team_unsuspended_on_resubscribe(): void + { + $owner = $this->createUltraUser(); + $team = Team::factory()->suspended()->create(['user_id' => $owner->id]); + + $job = new UnsuspendTeamJob($owner->id); + $job->handle(); + + $team->refresh(); + $this->assertFalse($team->is_suspended); + } + + public function test_suspended_team_member_loses_access(): void + { + $owner = $this->createUltraUser(); + $team = Team::factory()->suspended()->create(['user_id' => $owner->id]); + + $member = User::factory()->create(); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $this->assertFalse($member->isUltraTeamMember()); + } + + public function test_removed_member_loses_plugin_access(): void + { + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(); + $teamUser = TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $officialPlugin = Plugin::factory()->paid()->approved()->create([ + 'is_official' => true, + ]); + + $this->assertTrue($member->hasPluginAccess($officialPlugin)); + + $teamUser->remove(); + + // Clear cached state + $member->refresh(); + + $this->assertFalse($member->hasPluginAccess($officialPlugin)); + } + + // ======================================== + // API Plugin Access Tests + // ======================================== + + public function test_api_returns_team_based_plugin_access(): void + { + config(['services.bifrost.api_key' => 'test-api-key']); + + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create([ + 'plugin_license_key' => 'test-key-123', + ]); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $officialPlugin = Plugin::factory()->paid()->approved()->create([ + 'is_official' => true, + 'name' => 'nativephp/test-plugin', + ]); + + $response = $this->withHeaders([ + 'X-API-Key' => 'test-api-key', + 'PHP_AUTH_USER' => $member->email, + 'PHP_AUTH_PW' => 'test-key-123', + ])->getJson('/api/plugins/access'); + + $response->assertOk(); + $response->assertJsonFragment([ + 'name' => 'nativephp/test-plugin', + 'access' => 'team', + ]); + } + + // ======================================== + // GitHub Dev Kit Access Tests + // ======================================== + + public function test_ultra_team_member_can_request_claude_plugins_access(): void + { + Http::fake(['github.com/*' => Http::response([], 201)]); + + [$owner, $team] = $this->createTeamWithOwner(); + + $member = User::factory()->create(['github_username' => 'testuser']); + TeamUser::factory()->active()->create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + ]); + + $response = $this->actingAs($member) + ->post(route('github.request-claude-plugins-access')); + + $response->assertSessionHas('success'); + $this->assertNotNull($member->fresh()->claude_plugins_repo_access_granted_at); + } + + public function test_team_owner_can_request_claude_plugins_access(): void + { + Http::fake(['github.com/*' => Http::response([], 201)]); + + [$owner, $team] = $this->createTeamWithOwner(); + $owner->update(['github_username' => 'owneruser']); + + $response = $this->actingAs($owner) + ->post(route('github.request-claude-plugins-access')); + + $response->assertSessionHas('success'); + $this->assertNotNull($owner->fresh()->claude_plugins_repo_access_granted_at); + } + + public function test_non_team_member_without_product_license_cannot_request_claude_plugins_access(): void + { + $user = User::factory()->create(['github_username' => 'someuser']); + + $response = $this->actingAs($user) + ->post(route('github.request-claude-plugins-access')); + + $response->assertSessionHas('error'); + $this->assertNull($user->fresh()->claude_plugins_repo_access_granted_at); + } + + // ======================================== + // Resend Invitation Tests + // ======================================== + + public function test_owner_can_resend_invitation(): void + { + Notification::fake(); + + [$owner, $team] = $this->createTeamWithOwner(); + + $invitation = TeamUser::factory()->create([ + 'team_id' => $team->id, + 'email' => 'pending@example.com', + ]); + + $response = $this->actingAs($owner) + ->post(route('customer.team.users.resend', $invitation)); + + $response->assertSessionHas('success'); + Notification::assertSentOnDemand(TeamInvitation::class); + } + + // ======================================== + // View Tests + // ======================================== + + public function test_team_page_accessible_for_authenticated_user(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->get(route('customer.team.index')); + + $response->assertOk(); + } + + public function test_team_page_shows_create_form_for_ultra_user(): void + { + $user = $this->createUltraUser(); + + $response = $this->actingAs($user)->get(route('customer.team.index')); + + $response->assertOk(); + $response->assertSee('Create a Team'); + } + + public function test_team_page_shows_view_plans_for_non_ultra(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->get(route('customer.team.index')); + + $response->assertOk(); + $response->assertSee('View Plans'); + } +} diff --git a/tests/Feature/UltraPluginAccessTest.php b/tests/Feature/UltraPluginAccessTest.php new file mode 100644 index 00000000..a60ca154 --- /dev/null +++ b/tests/Feature/UltraPluginAccessTest.php @@ -0,0 +1,482 @@ +update(['stripe_id' => 'cus_'.uniqid()]); + + $subscription = \Laravel\Cashier\Subscription::factory() + ->for($user) + ->active() + ->create([ + 'stripe_price' => Subscription::Max->stripePriceId(), + 'is_comped' => false, + ]); + + \Laravel\Cashier\SubscriptionItem::factory() + ->for($subscription, 'subscription') + ->create([ + 'stripe_price' => Subscription::Max->stripePriceId(), + 'quantity' => 1, + ]); + + return $subscription; + } + + private function createCompedMaxSubscription(User $user): \Laravel\Cashier\Subscription + { + $user->update(['stripe_id' => 'cus_'.uniqid()]); + + $subscription = \Laravel\Cashier\Subscription::factory() + ->for($user) + ->active() + ->create([ + 'stripe_price' => Subscription::Max->stripePriceId(), + 'is_comped' => true, + ]); + + \Laravel\Cashier\SubscriptionItem::factory() + ->for($subscription, 'subscription') + ->create([ + 'stripe_price' => Subscription::Max->stripePriceId(), + 'quantity' => 1, + ]); + + return $subscription; + } + + private function createOfficialPlugin(): Plugin + { + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/test-plugin', + 'is_active' => true, + 'is_official' => true, + ]); + + PluginPrice::factory()->regular()->amount(2999)->create(['plugin_id' => $plugin->id]); + PluginPrice::factory()->subscriber()->amount(1999)->create(['plugin_id' => $plugin->id]); + + return $plugin; + } + + private function createThirdPartyPlugin(): Plugin + { + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'vendor/third-party-plugin', + 'is_active' => true, + 'is_official' => false, + ]); + + PluginPrice::factory()->regular()->amount(4900)->create(['plugin_id' => $plugin->id]); + PluginPrice::factory()->subscriber()->amount(2900)->create(['plugin_id' => $plugin->id]); + + return $plugin; + } + + // ---- Phase 1: Free official plugins for Ultra ---- + + public function test_ultra_user_gets_zero_price_for_official_plugin(): void + { + $user = User::factory()->create(); + $this->createPaidMaxSubscription($user); + $plugin = $this->createOfficialPlugin(); + + $bestPrice = $plugin->getBestPriceForUser($user); + + $this->assertNotNull($bestPrice); + $this->assertEquals(0, $bestPrice->amount); + } + + public function test_ultra_user_gets_normal_subscriber_price_for_third_party_plugin(): void + { + $user = User::factory()->create(); + $this->createPaidMaxSubscription($user); + $plugin = $this->createThirdPartyPlugin(); + + $bestPrice = $plugin->getBestPriceForUser($user); + + $this->assertNotNull($bestPrice); + $this->assertEquals(2900, $bestPrice->amount); + } + + public function test_comped_ultra_user_does_not_get_free_official_plugin(): void + { + $user = User::factory()->create(); + $this->createCompedMaxSubscription($user); + $plugin = $this->createOfficialPlugin(); + + $bestPrice = $plugin->getBestPriceForUser($user); + + $this->assertNotNull($bestPrice); + $this->assertGreaterThan(0, $bestPrice->amount); + } + + public function test_non_subscriber_gets_regular_price_for_official_plugin(): void + { + $user = User::factory()->create(); + $plugin = $this->createOfficialPlugin(); + + $bestPrice = $plugin->getBestPriceForUser($user); + + $this->assertNotNull($bestPrice); + $this->assertEquals(2999, $bestPrice->amount); + } + + public function test_guest_gets_regular_price_for_official_plugin(): void + { + $plugin = $this->createOfficialPlugin(); + + $bestPrice = $plugin->getBestPriceForUser(null); + + $this->assertNotNull($bestPrice); + $this->assertEquals(2999, $bestPrice->amount); + } + + // ---- Phase 2: $0 cart checkout ---- + + public function test_zero_cart_skips_stripe_and_creates_licenses(): void + { + $user = User::factory()->create(); + $this->createPaidMaxSubscription($user); + $plugin = $this->createOfficialPlugin(); + + $this->actingAs($user); + + $cartService = resolve(\App\Services\CartService::class); + $cart = $cartService->getCart($user); + $cartService->addPlugin($cart, $plugin); + + // Verify the price was captured as $0 + $cartItem = $cart->items()->first(); + $this->assertEquals(0, $cartItem->price_at_addition); + + // Checkout should skip Stripe and redirect to free success + $response = $this->post(route('cart.checkout')); + $response->assertRedirect(route('cart.success', ['free' => 1])); + + // License should have been created + $this->assertTrue( + $user->pluginLicenses()->forPlugin($plugin)->active()->exists() + ); + + // Cart should be completed + $this->assertNotNull($cart->fresh()->completed_at); + } + + public function test_free_checkout_does_not_create_duplicate_licenses(): void + { + $user = User::factory()->create(); + $this->createPaidMaxSubscription($user); + $plugin = $this->createOfficialPlugin(); + + // Pre-existing license + PluginLicense::factory()->create([ + 'user_id' => $user->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $this->actingAs($user); + + $cartService = resolve(\App\Services\CartService::class); + $cart = $cartService->getCart($user); + $cartService->addPlugin($cart, $plugin); + + $this->post(route('cart.checkout')); + + // Should still only have 1 license + $this->assertEquals(1, $user->pluginLicenses()->forPlugin($plugin)->count()); + } + + public function test_free_checkout_success_page_renders(): void + { + $user = User::factory()->create(); + $this->actingAs($user); + + $response = $this->get(route('cart.success', ['free' => 1])); + $response->assertStatus(200); + $response->assertSee('Plugins Added!'); + } + + // ---- Phase 3: Team plugin access ---- + + public function test_team_member_has_plugin_access_via_owner_license(): void + { + $owner = User::factory()->create(); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create(); + + TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'active', + 'role' => 'member', + 'accepted_at' => now(), + ]); + + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/licensed-plugin', + 'type' => PluginType::Paid, + 'is_active' => true, + 'is_official' => true, + ]); + + $this->assertTrue($member->hasPluginAccess($plugin)); + } + + public function test_team_member_loses_access_when_removed(): void + { + $owner = User::factory()->create(); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create(); + + $teamUser = TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'active', + 'role' => 'member', + 'accepted_at' => now(), + ]); + + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/licensed-plugin', + 'type' => PluginType::Paid, + 'is_active' => true, + 'is_official' => true, + ]); + + $this->assertTrue($member->hasPluginAccess($plugin)); + + // Remove from team + $teamUser->delete(); + + $this->assertFalse($member->hasPluginAccess($plugin)); + } + + public function test_non_team_member_does_not_get_team_plugin_access(): void + { + $owner = User::factory()->create(); + $this->createPaidMaxSubscription($owner); + + Team::factory()->create(['user_id' => $owner->id]); + $nonMember = User::factory()->create(); + + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/licensed-plugin', + 'type' => PluginType::Paid, + 'is_active' => true, + 'is_official' => true, + ]); + + PluginLicense::factory()->create([ + 'user_id' => $owner->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $this->assertFalse($nonMember->hasPluginAccess($plugin)); + } + + public function test_pending_team_member_does_not_get_plugin_access(): void + { + $owner = User::factory()->create(); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create(); + + TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'pending', + 'role' => 'member', + 'invited_at' => now(), + ]); + + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/licensed-plugin', + 'type' => PluginType::Paid, + 'is_active' => true, + 'is_official' => true, + ]); + + PluginLicense::factory()->create([ + 'user_id' => $owner->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $this->assertFalse($member->hasPluginAccess($plugin)); + } + + public function test_satis_api_includes_team_plugins(): void + { + $owner = User::factory()->create([ + 'plugin_license_key' => 'owner-key', + ]); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create([ + 'plugin_license_key' => 'member-key', + ]); + + TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'active', + 'role' => 'member', + 'accepted_at' => now(), + ]); + + $plugin = Plugin::factory()->create([ + 'name' => 'nativephp/team-plugin', + 'type' => PluginType::Paid, + 'status' => PluginStatus::Approved, + 'is_active' => true, + 'is_official' => true, + ]); + + PluginLicense::factory()->create([ + 'user_id' => $owner->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $response = $this->withHeaders([ + 'X-API-Key' => config('services.bifrost.api_key'), + 'Authorization' => 'Basic '.base64_encode("{$member->email}:member-key"), + ])->getJson('/api/plugins/access'); + + $response->assertStatus(200); + + $plugins = $response->json('plugins'); + $pluginNames = array_column($plugins, 'name'); + + $this->assertContains('nativephp/team-plugin', $pluginNames); + + $teamPlugin = collect($plugins)->firstWhere('name', 'nativephp/team-plugin'); + $this->assertEquals('team', $teamPlugin['access']); + } + + public function test_satis_check_access_returns_true_for_team_member(): void + { + $owner = User::factory()->create([ + 'plugin_license_key' => 'owner-key', + ]); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create([ + 'plugin_license_key' => 'member-key', + ]); + + TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'active', + 'role' => 'member', + 'accepted_at' => now(), + ]); + + $plugin = Plugin::factory()->create([ + 'name' => 'nativephp/team-plugin', + 'type' => PluginType::Paid, + 'status' => PluginStatus::Approved, + 'is_active' => true, + 'is_official' => true, + ]); + + PluginLicense::factory()->create([ + 'user_id' => $owner->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $response = $this->withHeaders([ + 'X-API-Key' => config('services.bifrost.api_key'), + 'Authorization' => 'Basic '.base64_encode("{$member->email}:member-key"), + ])->getJson('/api/plugins/access/nativephp/team-plugin'); + + $response->assertStatus(200) + ->assertJson([ + 'has_access' => true, + ]); + } + + // ---- Phase 4: Team Plugins on Purchased Plugins page ---- + + public function test_purchased_plugins_page_shows_team_plugins_for_team_member(): void + { + $owner = User::factory()->create(); + $this->createPaidMaxSubscription($owner); + + $team = Team::factory()->create(['user_id' => $owner->id]); + $member = User::factory()->create(); + + TeamUser::create([ + 'team_id' => $team->id, + 'user_id' => $member->id, + 'email' => $member->email, + 'status' => 'active', + 'role' => 'member', + 'accepted_at' => now(), + ]); + + $plugin = Plugin::factory()->approved()->paid()->create([ + 'name' => 'nativephp/shared-plugin', + 'is_active' => true, + ]); + + PluginLicense::factory()->create([ + 'user_id' => $owner->id, + 'plugin_id' => $plugin->id, + 'expires_at' => null, + ]); + + $this->actingAs($member); + $response = $this->get(route('customer.purchased-plugins.index')); + + $response->assertStatus(200); + $response->assertSee('Team Plugins'); + $response->assertSee($owner->display_name); + $response->assertSee('nativephp/shared-plugin'); + } + + public function test_purchased_plugins_page_does_not_show_team_plugins_for_non_member(): void + { + $user = User::factory()->create(); + $this->actingAs($user); + + $response = $this->get(route('customer.purchased-plugins.index')); + + $response->assertStatus(200); + $response->assertDontSee('Team Plugins'); + } +}