diff --git a/.agents/skills/developing-with-fortify/SKILL.md b/.agents/skills/developing-with-fortify/SKILL.md new file mode 100644 index 00000000..db3558bc --- /dev/null +++ b/.agents/skills/developing-with-fortify/SKILL.md @@ -0,0 +1,116 @@ +--- +name: developing-with-fortify +description: Laravel Fortify headless authentication backend development. Activate when implementing authentication features including login, registration, password reset, email verification, two-factor authentication (2FA/TOTP), profile updates, headless auth, authentication scaffolding, or auth guards in Laravel applications. +--- + +# Laravel Fortify Development + +Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications. + +## Documentation + +Use `search-docs` for detailed Laravel Fortify patterns and documentation. + +## Usage + +- **Routes**: Use `list-routes` with `only_vendor: true` and `action: "Fortify"` to see all registered endpoints +- **Actions**: Check `app/Actions/Fortify/` for customizable business logic (user creation, password validation, etc.) +- **Config**: See `config/fortify.php` for all options including features, guards, rate limiters, and username field +- **Contracts**: Look in `Laravel\Fortify\Contracts\` for overridable response classes (`LoginResponse`, `LogoutResponse`, etc.) +- **Views**: All view callbacks are set in `FortifyServiceProvider::boot()` using `Fortify::loginView()`, `Fortify::registerView()`, etc. + +## Available Features + +Enable in `config/fortify.php` features array: + +- `Features::registration()` - User registration +- `Features::resetPasswords()` - Password reset via email +- `Features::emailVerification()` - Requires User to implement `MustVerifyEmail` +- `Features::updateProfileInformation()` - Profile updates +- `Features::updatePasswords()` - Password changes +- `Features::twoFactorAuthentication()` - 2FA with QR codes and recovery codes + +> Use `search-docs` for feature configuration options and customization patterns. + +## Setup Workflows + +### Two-Factor Authentication Setup + +``` +- [ ] Add TwoFactorAuthenticatable trait to User model +- [ ] Enable feature in config/fortify.php +- [ ] Run migrations for 2FA columns +- [ ] Set up view callbacks in FortifyServiceProvider +- [ ] Create 2FA management UI +- [ ] Test QR code and recovery codes +``` + +> Use `search-docs` for TOTP implementation and recovery code handling patterns. + +### Email Verification Setup + +``` +- [ ] Enable emailVerification feature in config +- [ ] Implement MustVerifyEmail interface on User model +- [ ] Set up verifyEmailView callback +- [ ] Add verified middleware to protected routes +- [ ] Test verification email flow +``` + +> Use `search-docs` for MustVerifyEmail implementation patterns. + +### Password Reset Setup + +``` +- [ ] Enable resetPasswords feature in config +- [ ] Set up requestPasswordResetLinkView callback +- [ ] Set up resetPasswordView callback +- [ ] Define password.reset named route (if views disabled) +- [ ] Test reset email and link flow +``` + +> Use `search-docs` for custom password reset flow patterns. + +### SPA Authentication Setup + +``` +- [ ] Set 'views' => false in config/fortify.php +- [ ] Install and configure Laravel Sanctum +- [ ] Use 'web' guard in fortify config +- [ ] Set up CSRF token handling +- [ ] Test XHR authentication flows +``` + +> Use `search-docs` for integration and SPA authentication patterns. + +## Best Practices + +### Custom Authentication Logic + +Override authentication behavior using `Fortify::authenticateUsing()` for custom user retrieval or `Fortify::authenticateThrough()` to customize the authentication pipeline. Override response contracts in `AppServiceProvider` for custom redirects. + +### Registration Customization + +Modify `app/Actions/Fortify/CreateNewUser.php` to customize user creation logic, validation rules, and additional fields. + +### Rate Limiting + +Configure via `fortify.limiters.login` in config. Default configuration throttles by username + IP combination. + +## Key Endpoints + +| Feature | Method | Endpoint | +|------------------------|----------|---------------------------------------------| +| Login | POST | `/login` | +| Logout | POST | `/logout` | +| Register | POST | `/register` | +| Password Reset Request | POST | `/forgot-password` | +| Password Reset | POST | `/reset-password` | +| Email Verify Notice | GET | `/email/verify` | +| Resend Verification | POST | `/email/verification-notification` | +| Password Confirm | POST | `/user/confirm-password` | +| Enable 2FA | POST | `/user/two-factor-authentication` | +| Confirm 2FA | POST | `/user/confirmed-two-factor-authentication` | +| 2FA Challenge | POST | `/two-factor-challenge` | +| Get QR Code | GET | `/user/two-factor-qr-code` | +| Recovery Codes | GET/POST | `/user/two-factor-recovery-codes` | diff --git a/.agents/skills/fluxui-development/SKILL.md b/.agents/skills/fluxui-development/SKILL.md new file mode 100644 index 00000000..d4fb5a03 --- /dev/null +++ b/.agents/skills/fluxui-development/SKILL.md @@ -0,0 +1,81 @@ +--- +name: fluxui-development +description: "Use this skill for Flux UI development in Livewire applications only. Trigger when working with components, building or customizing Livewire component UIs, creating forms, modals, tables, or other interactive elements. Covers: flux: components (buttons, inputs, modals, forms, tables, date-pickers, kanban, badges, tooltips, etc.), component composition, Tailwind CSS styling, Heroicons/Lucide icon integration, validation patterns, responsive design, and theming. Do not use for non-Livewire frameworks or non-component styling." +license: MIT +metadata: + author: laravel +--- + +# Flux UI Development + +## Documentation + +Use `search-docs` for detailed Flux UI patterns and documentation. + +## Basic Usage + +This project uses the free edition of Flux UI, which includes all free components and variants but not Pro components. + +Flux UI is a component library for Livewire built with Tailwind CSS. It provides components that are easy to use and customize. + +Use Flux UI components when available. Fall back to standard Blade components when no Flux component exists for your needs. + + +```blade +Click me +``` + +## Available Components (Free Edition) + +Available: avatar, badge, brand, breadcrumbs, button, callout, card, checkbox, dropdown, field, heading, icon, input, modal, navbar, otp-input, pagination, profile, progress, radio, select, separator, skeleton, switch, table, text, textarea, toast, tooltip + +## Icons + +Flux includes [Heroicons](https://heroicons.com/) as its default icon set. Search for exact icon names on the Heroicons site - do not guess or invent icon names. + + +```blade +Export +``` + +For icons not available in Heroicons, use [Lucide](https://lucide.dev/). Import the icons you need with the Artisan command: + +```bash +php artisan flux:icon crown grip-vertical github +``` + +## Common Patterns + +### Form Fields + + +```blade + + Email + + + +``` + +### Modals + + +```blade + + Title +

Content

+
+``` + +## Verification + +1. Check component renders correctly +2. Test interactive states +3. Verify mobile responsiveness + +## Common Pitfalls + +- Trying to use Pro-only components in the free edition +- Not checking if a Flux component exists before creating custom implementations +- Forgetting to use the `search-docs` tool for component-specific documentation +- Not following existing project patterns for Flux usage diff --git a/.agents/skills/infer-conventions/SKILL.md b/.agents/skills/infer-conventions/SKILL.md new file mode 100644 index 00000000..11a93275 --- /dev/null +++ b/.agents/skills/infer-conventions/SKILL.md @@ -0,0 +1,104 @@ +--- +name: infer-conventions +description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand." +license: MIT +metadata: + author: laravel +--- + +# Infer Conventions + +Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it. + +## Ground Rules (read before you start) + +- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer. +- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record. +- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule. +- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering. +- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped. +- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar. +- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details. + +## Process + +Each step ends on a checkable completion criterion. Do not advance until it holds. + +Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output. + +### Step 0: Orient + +Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2. + +This app ships a frontend stack, so the frontend checklist group applies. Sweep it. + +Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents. + +### Step 1: Predefined sweep + +Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict: + +- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files. +- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled. +- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention. +- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most). +- Tooling-owned or Already-recorded. Skip per the ground rules. + +Done when: every applicable dimension carries exactly one of those verdicts. + +### Step 2: Open-ended pass + +First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude. + +Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal. + +Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none). + +### Step 3: Confirm + +Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style. + +Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo. + +Done when: every candidate is approved, rejected, or (conflicts) decided. + +### Step 4: Record + +Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand. + +Record this: + +> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models. + +Not this: + +> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models. + +Done when: every approved item has a successful tool response, and any failure is reported with its rule text. + +### Step 5: Summarize + +List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions. + +## Glob mapping + +Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path. + +Examples: + +- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one. +- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer. +- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses. +- Tests: `tests/**`. +- Migrations and database: `database/migrations/**`. +- Truly app-wide (rare, e.g. auth retrieval): `app/**`. + +`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there. + +## Edge cases + +- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4. +- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing. +- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything. +- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface. +- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths. diff --git a/.agents/skills/infer-conventions/references/checklist.md b/.agents/skills/infer-conventions/references/checklist.md new file mode 100644 index 00000000..2b45cc25 --- /dev/null +++ b/.agents/skills/infer-conventions/references/checklist.md @@ -0,0 +1,141 @@ +# Detection Checklist + +Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`). + +Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence. + +--- + +## A. Validation & HTTP input + +1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`. + - Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`. +2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal. + - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`. +3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties. + - Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`. +4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods. + - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`. + +## B. Controllers & routing + +5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method. + - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes. +6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs. + - Hint: read a few controller methods; `ls app/Actions app/Services`. +7. Route handler style: closures in `routes/*.php` vs controller classes. + - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`. +8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute. + - Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes. +9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`. + - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`. +10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`. + - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files. + +## C. Authorization + +11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`. + - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`. +12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade. + - Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`. + +## D. Eloquent & models + +13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list. + - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`. +14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain. + - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`. +15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`. + - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`. +16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings. + - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models. +17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`). + - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built. +18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes. + - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`. +19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes. + - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`. +20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture. + - Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`. + +## E. Architecture & organization + +21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked. + - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find. +22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere. + - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`. +23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location. + - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps. +24. Decoupling: events + listeners vs direct service calls. + - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`. +25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`). + - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`. +26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules). + - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders. +27. Enums: backed vs pure; case naming; where they live. + - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`. + +## F. Frontend & views + +This app ships a frontend stack, so the items below apply. + +28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA. + - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`. +29. Blade composition: class `` components vs anonymous components (`@props`) vs `@include` partials. + - Hint: `ls app/View/Components`; grep `constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`. + - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`. +34. `down()` methods: real reverse logic vs omitted / one-way migrations. + - Hint: grep `function down` vs the migration count. +35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model. + - Hint: grep `->enum(` in migrations vs string columns cast to enums. +36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`. + - Hint: grep `DB::transaction`, `beginTransaction` in `app/`. +37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save. + - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`. + +## H. Testing + +38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes. + - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`. +39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`. + - Hint: grep those trait names in `tests/`. +40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories. + - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide. +41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery. + - Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`. +42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`. + - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`. + +## I. Responses & API resources + +43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly. + - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers. +44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately. + - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`. +45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority. + - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them. +46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`. + - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views. + +## J. Strings, collections & dates + +47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`. + - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`. +48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`). + - Hint: grep `Str::of(` vs `Str::` vs native string funcs. +49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting. + - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy. + +--- + +Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from. diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.md new file mode 100644 index 00000000..d136d755 --- /dev/null +++ b/.agents/skills/laravel-best-practices/SKILL.md @@ -0,0 +1,59 @@ +--- +name: laravel-best-practices +description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns." +license: MIT +metadata: + author: laravel +--- + +# Laravel Best Practices + +Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`. + +## Consistency First + +Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern. + +Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides. + +## How to Apply + +1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out. +2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files. +3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job. +4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable. +5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them. +6. Re-read the diff against every mapped rule before finishing. + +## Rule Index + +Cross-cutting changes often need more than one rule file. + +| Concern | Read | +| --- | --- | +| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) | +| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) | +| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) | +| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) | +| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) | +| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) | +| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) | +| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) | +| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) | +| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) | +| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) | +| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) | +| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) | +| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) | +| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) | +| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) | +| Environment values and application configuration | [`rules/config.md`](rules/config.md) | +| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) | +| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) | +| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) | + +## Decision Rules + +- Prefer framework features and existing application abstractions over new helpers or dependencies. +- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable. +- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization. diff --git a/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.md new file mode 100644 index 00000000..f12876e4 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/advanced-queries.md @@ -0,0 +1,106 @@ +# Advanced Query Patterns + +## Use `addSelect()` Subqueries for Single Values from Has-Many + +Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries. + +```php +public function scopeWithLastLoginAt($query): void +{ + $query->addSelect([ + 'last_login_at' => Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->withCasts(['last_login_at' => 'datetime']); +} +``` + +## Create Dynamic Relationships via Subquery FK + +Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection. + +```php +public function lastLogin(): BelongsTo +{ + return $this->belongsTo(Login::class); +} + +public function scopeWithLastLogin($query): void +{ + $query->addSelect([ + 'last_login_id' => Login::select('id') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->with('lastLogin'); +} +``` + +## Use Conditional Aggregates Instead of Multiple Count Queries + +Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values. + +```php +$statuses = Feature::toBase() + ->selectRaw("count(case when status = 'Requested' then 1 end) as requested") + ->selectRaw("count(case when status = 'Planned' then 1 end) as planned") + ->selectRaw("count(case when status = 'Completed' then 1 end) as completed") + ->first(); +``` + +## Use `setRelation()` to Prevent Circular N+1 + +When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries. + +```php +$feature->load('comments.user'); +$feature->comments->each->setRelation('feature', $feature); +``` + +## Prefer `whereIn` + Subquery Over `whereHas` + +`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory. + +Incorrect (correlated EXISTS re-executes per row): + +```php +$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term)); +``` + +Correct (index-friendly subquery, no PHP memory overhead): + +```php +$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id')); +``` + +## Sometimes Two Simple Queries Beat One Complex Query + +Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index. + +## Use Compound Indexes Matching `orderBy` Column Order + +When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index. + +```php +// Migration +$table->index(['last_name', 'first_name']); + +// Query — column order must match the index +User::query()->orderBy('last_name')->orderBy('first_name')->paginate(); +``` + +## Use Correlated Subqueries for Has-Many Ordering + +When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading. + +```php +public function scopeOrderByLastLogin($query): void +{ + $query->orderByDesc(Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1) + ); +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.md new file mode 100644 index 00000000..b65e3b56 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/architecture.md @@ -0,0 +1,206 @@ +# Architecture Best Practices + +## Single-Purpose Action Classes + +Extract discrete business operations into invokable Action classes. + +```php +class CreateOrderAction +{ + public function __construct(private InventoryService $inventory) {} + + public function handle(array $data): Order + { + $order = Order::create($data); + $this->inventory->reserve($order); + + return $order; + } +} +``` + +## Use Dependency Injection + +Always use constructor injection. Avoid `app()` or `resolve()` inside classes. + +Incorrect: +```php +class OrderController extends Controller +{ + public function store(StoreOrderRequest $request) + { + $service = app(OrderService::class); + + return $service->create($request->validated()); + } +} +``` + +Correct: +```php +class OrderController extends Controller +{ + public function __construct(private OrderService $service) {} + + public function store(StoreOrderRequest $request) + { + return $this->service->create($request->validated()); + } +} +``` + +## Code to Interfaces + +Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability. + +Incorrect (concrete dependency): +```php +class OrderService +{ + public function __construct(private StripeGateway $gateway) {} +} +``` + +Correct (interface dependency): +```php +interface PaymentGateway +{ + public function charge(int $amount, string $customerId): PaymentResult; +} + +class OrderService +{ + public function __construct(private PaymentGateway $gateway) {} +} +``` + +Bind in a service provider: + +```php +$this->app->bind(PaymentGateway::class, StripeGateway::class); +``` + +## Default Sort by Descending + +When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined. + +Incorrect: +```php +$posts = Post::paginate(); +``` + +Correct: +```php +$posts = Post::latest()->paginate(); +``` + +## Use Atomic Locks for Race Conditions + +Prevent race conditions with `Cache::lock()` or `lockForUpdate()`. + +```php +Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) { + $order->process(); +}); + +// Or at query level, inside a transaction +DB::transaction(function () use ($id) { + $product = Product::where('id', $id)->lockForUpdate()->first(); + + // Read and update the product while the lock is held... +}); +``` + +## Use `mb_*` String Functions + +When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters. + +Incorrect: +```php +strlen('José'); // 5 (bytes, not characters) +strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte +``` + +Correct: +```php +mb_strlen('José'); // 4 (characters) +mb_strtolower('MÜNCHEN'); // 'münchen' + +// Prefer Laravel's Str helpers when available +Str::length('José'); // 4 +Str::lower('MÜNCHEN'); // 'münchen' +``` + +## Use `defer()` for Post-Response Work + +For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead. + +Incorrect (job overhead for trivial work): +```php +dispatch(new LogPageView($page)); +``` + +Correct (runs after response, same process): +```php +defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()])); +``` + +Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work. + +## Use `Context` for Request-Scoped Data + +The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually. + +```php +// In middleware +Context::add('tenant_id', $request->header('X-Tenant-ID')); + +// Anywhere later — controllers, jobs, log context +$tenantId = Context::get('tenant_id'); +``` + +Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`. + +## Use `Concurrency::run()` for Parallel Execution + +Run independent operations in parallel using child processes — no async libraries needed. + +```php +use Illuminate\Support\Facades\Concurrency; + +[$users, $orders] = Concurrency::run([ + fn () => User::count(), + fn () => Order::where('status', 'pending')->count(), +]); +``` + +Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially. + +## Convention Over Configuration + +Follow Laravel conventions. Don't override defaults unnecessarily. + +Incorrect: +```php +class Customer extends Model +{ + protected $table = 'Customer'; + protected $primaryKey = 'customer_id'; + + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); + } +} +``` + +Correct: +```php +class Customer extends Model +{ + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class); + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.md new file mode 100644 index 00000000..5f0b3a1e --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/blade-views.md @@ -0,0 +1,36 @@ +# Blade & Views Best Practices + +## Use `$attributes->merge()` in Component Templates + +Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly. + +```blade +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## Use `@pushOnce` for Per-Component Scripts + +If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once. + +## Prefer Blade Components Over `@include` + +`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots. + +## Use View Composers for Shared View Data + +If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it. + +## Use Blade Fragments for Partial Re-Renders (htmx/Turbo) + +A single view can return either the full page or just a fragment, keeping routing clean. + +```php +return view('dashboard', compact('users')) + ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); +``` + +## Use `@aware` for Deeply Nested Component Props + +Avoids re-passing parent props through every level of nested components. diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.md new file mode 100644 index 00000000..c5becef8 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/caching.md @@ -0,0 +1,70 @@ +# Caching Best Practices + +## Use `Cache::remember()` Instead of Manual Get/Put + +Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions. + +Incorrect: +```php +$val = Cache::get('stats'); +if (! $val) { + $val = $this->computeStats(); + Cache::put('stats', $val, 60); +} +``` + +Correct: +```php +$val = Cache::remember('stats', 60, fn () => $this->computeStats()); +``` + +## Use `Cache::flexible()` for Stale-While-Revalidate + +On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background. + +Incorrect: `Cache::remember('users', 300, fn () => User::all());` + +Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function. + +## Use `Cache::memo()` to Avoid Redundant Hits Within a Request + +If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory. + +`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5. + +## Use Cache Tags to Invalidate Related Groups + +Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Not supported by the `file`, `dynamodb`, `database` or `storage` drivers. + +```php +Cache::tags(['user-1'])->flush(); +``` + +## Use `Cache::add()` for Atomic Conditional Writes + +`add()` only writes if the key does not exist — atomic, no race condition between checking and writing. + +Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }` + +Correct: `Cache::add('lock', true, 10);` + +## Use `once()` for Per-Request Memoization + +`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory. + +```php +public function roles(): Collection +{ + return once(fn () => $this->loadRoles()); +} +``` + +Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching. + +## Configure Failover Cache Stores in Production + +If Redis goes down, the app falls back to a secondary store automatically. + +```php +'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']], +``` diff --git a/.agents/skills/laravel-best-practices/rules/collections.md b/.agents/skills/laravel-best-practices/rules/collections.md new file mode 100644 index 00000000..18e8d9e1 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/collections.md @@ -0,0 +1,44 @@ +# Collection Best Practices + +## Use Higher-Order Messages for Simple Operations + +Incorrect: +```php +$users->each(function (User $user) { + $user->markAsVip(); +}); +``` + +Correct: `$users->each->markAsVip();` + +Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc. + +## Choose `cursor()` vs. `lazy()` Correctly + +- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk). +- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading. + +Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored. + +Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work. + +## Use `lazyById()` When Updating Records While Iterating + +`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation. + +## Use `toQuery()` for Bulk Operations on Collections + +Avoids manual `whereIn` construction. + +Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);` + +Correct: `$users->toQuery()->update([...]);` + +## Use `#[CollectedBy]` for Custom Collection Classes + +More declarative than overriding `newCollection()`. + +```php +#[CollectedBy(UserCollection::class)] +class User extends Model {} +``` diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.md new file mode 100644 index 00000000..9bea727b --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/config.md @@ -0,0 +1,73 @@ +# Configuration Best Practices + +## `env()` Only in Config Files + +Direct `env()` calls may return `null` when config is cached. + +Incorrect: +```php +$key = env('API_KEY'); +``` + +Correct: +```php +// config/services.php +'key' => env('API_KEY'), + +// Application code +$key = config('services.key'); +``` + +## Use Encrypted Env or External Secrets + +Never store production secrets in plain `.env` files in version control. + +Incorrect: +```bash + +# .env committed to repo or shared in Slack + +STRIPE_SECRET=sk_live_abc123 +AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI +``` + +Correct: +```bash +php artisan env:encrypt --env=production --readable +php artisan env:decrypt --env=production +``` + +For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime. + +## Use `App::environment()` for Environment Checks + +Incorrect: +```php +if (env('APP_ENV') === 'production') { +``` + +Correct: +```php +if (app()->isProduction()) { +// or +if (App::environment('production')) { +``` + +## Use Constants and Language Files + +Use class constants instead of hardcoded magic strings for model states, types, and statuses. + +```php +// Incorrect +return $this->type === 'normal'; + +// Correct +return $this->type === self::TYPE_NORMAL; +``` + +If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there. + +```php +// Only when lang files already exist in the project +return back()->with('message', __('app.article_added')); +``` diff --git a/.agents/skills/laravel-best-practices/rules/db-performance.md b/.agents/skills/laravel-best-practices/rules/db-performance.md new file mode 100644 index 00000000..c49ba164 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/db-performance.md @@ -0,0 +1,192 @@ +# Database Performance Best Practices + +## Always Eager Load Relationships + +Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront. + +Incorrect (N+1 — executes 1 + N queries): +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Correct (2 queries total): +```php +$posts = Post::with('author')->get(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Constrain eager loads to select only needed columns (always include the foreign key): + +```php +$users = User::with(['posts' => function ($query) { + $query->select('id', 'user_id', 'title') + ->where('published', true) + ->latest() + ->limit(10); +}])->get(); +``` + +## Prevent Lazy Loading in Development + +Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development. + +```php +public function boot(): void +{ + Model::preventLazyLoading(! app()->isProduction()); +} +``` + +Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded. + +## Select Only Needed Columns + +Avoid `SELECT *` — especially when tables have large text or JSON columns. + +Incorrect: +```php +$posts = Post::with('author')->get(); +``` + +Correct: +```php +$posts = Post::select('id', 'title', 'user_id', 'created_at') + ->with(['author:id,name,avatar']) + ->get(); +``` + +When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match. + +## Chunk Large Datasets + +Never load thousands of records at once. Use chunking for batch processing. + +Incorrect: +```php +$users = User::all(); +foreach ($users as $user) { + $user->notify(new WeeklyDigest); +} +``` + +Correct: +```php +User::where('subscribed', true)->chunk(200, function ($users) { + foreach ($users as $user) { + $user->notify(new WeeklyDigest); + } +}); +``` + +Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change: + +```php +User::where('active', false)->chunkById(200, function ($users) { + $users->each->delete(); +}); +``` + +## Add Database Indexes + +Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses. + +Incorrect: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); +}); +``` + +Correct: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->index()->constrained(); + $table->string('status')->index(); + $table->timestamps(); + $table->index(['status', 'created_at']); +}); +``` + +Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`). + +## Use `withCount()` for Counting Relations + +Never load entire collections just to count them. + +Incorrect: +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->comments->count(); +} +``` + +Correct: +```php +$posts = Post::withCount('comments')->get(); +foreach ($posts as $post) { + echo $post->comments_count; +} +``` + +Conditional counting: + +```php +$posts = Post::withCount([ + 'comments', + 'comments as approved_comments_count' => function ($query) { + $query->where('approved', true); + }, +])->get(); +``` + +## Use `cursor()` for Memory-Efficient Iteration + +For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator. + +Incorrect: +```php +$users = User::where('active', true)->get(); +``` + +Correct: +```php +foreach (User::where('active', true)->cursor() as $user) { + ProcessUser::dispatch($user->id); +} +``` + +Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records. + +## No Queries in Blade Templates + +Never execute queries in Blade templates. Pass data from controllers. + +Incorrect: +```blade +@foreach (User::all() as $user) + {{ $user->profile->name }} +@endforeach +``` + +Correct: +```php +// Controller +$users = User::with('profile')->get(); +return view('users.index', compact('users')); +``` + +```blade +@foreach ($users as $user) + {{ $user->profile->name }} +@endforeach +``` diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.md new file mode 100644 index 00000000..bd2cfca0 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/eloquent.md @@ -0,0 +1,150 @@ +# Eloquent Best Practices + +## Use Correct Relationship Types + +Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints. + +```php +public function comments(): HasMany +{ + return $this->hasMany(Comment::class); +} + +public function author(): BelongsTo +{ + return $this->belongsTo(User::class, 'user_id'); +} +``` + +## Use Local Scopes for Reusable Queries + +Extract reusable query constraints into local scopes to avoid duplication. + +Incorrect: +```php +$active = User::where('verified', true)->whereNotNull('activated_at')->get(); +$articles = Article::whereHas('user', function ($q) { + $q->where('verified', true)->whereNotNull('activated_at'); +})->get(); +``` + +Correct: +```php +#[Scope] +protected function active(Builder $query): Builder +{ + return $query->where('verified', true)->whereNotNull('activated_at'); +} + +// Usage +$active = User::active()->get(); +$articles = Article::whereHas('user', fn ($q) => $q->active())->get(); +``` + +## Apply Global Scopes Sparingly + +Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy. + +Incorrect (global scope for a conditional filter): +```php +class PublishedScope implements Scope +{ + public function apply(Builder $builder, Model $model): void + { + $builder->where('published', true); + } +} +// Now admin panels, reports, and background jobs all silently skip drafts +``` + +Correct (local scope you opt into): +```php +#[Scope] +protected function published(Builder $query): Builder +{ + return $query->where('published', true); +} + +Post::published()->paginate(); // Explicit +Post::paginate(); // Admin sees all +``` + +## Define Attribute Casts + +Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion. + +```php +protected function casts(): array +{ + return [ + 'is_active' => 'boolean', + 'metadata' => 'array', + 'total' => 'decimal:2', + ]; +} +``` + +## Cast Date Columns Properly + +Always cast date columns. Use Carbon instances in templates instead of formatting strings manually. + +Incorrect: +```blade +{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }} +``` + +Correct: +```php +protected function casts(): array +{ + return [ + 'ordered_at' => 'datetime', + ]; +} +``` + +```blade +{{ $order->ordered_at->toDateString() }} +{{ $order->ordered_at->format('m-d') }} +``` + +## Use `whereBelongsTo()` for Relationship Queries + +Cleaner than manually specifying foreign keys. + +Incorrect: +```php +Post::where('user_id', $user->id)->get(); +``` + +Correct: +```php +Post::whereBelongsTo($user)->get(); +Post::whereBelongsTo($user, 'author')->get(); +``` + +## Avoid Hardcoded Table Names in Queries + +Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string). + +Incorrect: +```php +DB::table('users')->where('active', true)->get(); + +$query->join('companies', 'companies.id', '=', 'users.company_id'); + +DB::select('SELECT * FROM orders WHERE status = ?', ['pending']); +``` + +Correct — reference the model's table: +```php +DB::table((new User)->getTable())->where('active', true)->get(); + +// Even better — use Eloquent or the query builder instead of raw SQL +User::where('active', true)->get(); +Order::where('status', 'pending')->get(); +``` + +Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable. + +**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration. diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.md new file mode 100644 index 00000000..4b148667 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/error-handling.md @@ -0,0 +1,72 @@ +# Error Handling Best Practices + +## Exception Reporting and Rendering + +There are two valid approaches — choose one and apply it consistently across the project. + +**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find: + +```php +class InvalidOrderException extends Exception +{ + public function report(): void { /* custom reporting */ } + + public function render(Request $request): Response + { + return response()->view('errors.invalid-order', status: 422); + } +} +``` + +**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture: + +```php +->withExceptions(function (Exceptions $exceptions) { + $exceptions->report(function (InvalidOrderException $e) { /* ... */ }); + $exceptions->render(function (InvalidOrderException $e, Request $request) { + return response()->view('errors.invalid-order', status: 422); + }); +}) +``` + +Check the existing codebase and follow whichever pattern is already established. + +## Use `ShouldntReport` for Exceptions That Should Never Log + +More discoverable than listing classes in `dontReport()`. + +```php +class PodcastProcessingException extends Exception implements ShouldntReport {} +``` + +## Throttle High-Volume Exceptions + +A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type. + +## Enable `dontReportDuplicates()` + +Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks. + +## Force JSON Error Rendering for API Routes + +Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes. + +```php +$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { + return $request->is('api/*') || $request->expectsJson(); +}); +``` + +## Add Context to Exception Classes + +Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry. + +```php +class InvalidOrderException extends Exception +{ + public function context(): array + { + return ['order_id' => $this->orderId]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.md new file mode 100644 index 00000000..82e329e8 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/events-notifications.md @@ -0,0 +1,52 @@ +# Events & Notifications Best Practices + +## Rely on Event Discovery + +Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`. + +## Run `event:cache` in Production Deploy + +Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`. + +## Use `ShouldDispatchAfterCommit` Inside Transactions + +Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet. + +```php +class OrderShipped implements ShouldDispatchAfterCommit {} +``` + +## Always Queue Notifications + +Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response. + +```php +class InvoicePaid extends Notification implements ShouldQueue +{ + use Queueable; +} +``` + +## Use `afterCommit()` on Notifications in Transactions + +Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits. + +```php +$user->notify((new InvoicePaid($invoice))->afterCommit()); +``` + +## Route Notification Channels to Dedicated Queues + +Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues. + +## Use On-Demand Notifications for Non-User Recipients + +Avoid creating dummy models to send notifications to arbitrary addresses. + +```php +Notification::route('mail', 'admin@example.com')->notify(new SystemAlert()); +``` + +## Implement `HasLocalePreference` on Notifiable Models + +Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed. diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.md new file mode 100644 index 00000000..feaecf80 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/http-client.md @@ -0,0 +1,160 @@ +# HTTP Client Best Practices + +## Always Set Explicit Timeouts + +The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast. + +Incorrect: +```php +$response = Http::get('https://api.example.com/users'); +``` + +Correct: +```php +$response = Http::timeout(5) + ->connectTimeout(3) + ->get('https://api.example.com/users'); +``` + +For service-specific clients, define timeouts in a macro: + +```php +Http::macro('github', function () { + return Http::baseUrl('https://api.github.com') + ->timeout(10) + ->connectTimeout(3) + ->withToken(config('services.github.token')); +}); + +$response = Http::github()->get('/repos/laravel/framework'); +``` + +## Use Retry with Backoff for External APIs + +External APIs have transient failures. Use `retry()` with increasing delays. + +Incorrect: +```php +$response = Http::post('https://api.example.com/v1/charges', $data); + +if ($response->failed()) { + throw new PaymentFailedException('Charge failed'); +} +``` + +Correct: +```php +$response = Http::retry([100, 500, 1000]) + ->timeout(10) + ->post('https://api.example.com/v1/charges', $data); +``` + +Only retry on specific errors: + +```php +$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) { + return $exception instanceof ConnectionException + || ($exception instanceof RequestException && $exception->response->serverError()); +})->post('https://api.example.com/data'); +``` + +## Handle Errors Explicitly + +The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`. + +Incorrect: +```php +$response = Http::get('https://api.example.com/users/1'); +$user = $response->json(); // Could be an error body +``` + +Correct: +```php +$response = Http::timeout(5) + ->get('https://api.example.com/users/1') + ->throw(); + +$user = $response->json(); +``` + +For graceful degradation: + +```php +$response = Http::get('https://api.example.com/users/1'); + +if ($response->successful()) { + return $response->json(); +} + +if ($response->notFound()) { + return null; +} + +$response->throw(); +``` + +## Use Request Pooling for Concurrent Requests + +When making multiple independent API calls, use `Http::pool()` instead of sequential calls. + +Incorrect: +```php +$users = Http::get('https://api.example.com/users')->json(); +$posts = Http::get('https://api.example.com/posts')->json(); +$comments = Http::get('https://api.example.com/comments')->json(); +``` + +Correct: +```php +use Illuminate\Http\Client\Pool; + +$responses = Http::pool(fn (Pool $pool) => [ + $pool->as('users')->get('https://api.example.com/users'), + $pool->as('posts')->get('https://api.example.com/posts'), + $pool->as('comments')->get('https://api.example.com/comments'), +]); + +$users = $responses['users']->json(); +$posts = $responses['posts']->json(); +``` + +## Fake HTTP Calls in Tests + +Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`. + +Incorrect: +```php +it('syncs user from API', function () { + $service = new UserSyncService; + $service->sync(1); // Hits the real API +}); +``` + +Correct: +```php +it('syncs user from API', function () { + Http::preventStrayRequests(); + + Http::fake([ + 'api.example.com/users/1' => Http::response([ + 'name' => 'John Doe', + 'email' => 'john@example.com', + ]), + ]); + + $service = new UserSyncService; + $service->sync(1); + + Http::assertSent(function (Request $request) { + return $request->url() === 'https://api.example.com/users/1'; + }); +}); +``` + +Test failure scenarios too: + +```php +Http::fake([ + 'api.example.com/*' => Http::failedConnection(), +]); +``` diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.md new file mode 100644 index 00000000..7c717336 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/mail.md @@ -0,0 +1,27 @@ +# Mail Best Practices + +## Implement `ShouldQueue` on the Mailable Class + +Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it. + +## Use `afterCommit()` on Mailables Inside Transactions + +A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor. + +## Use `assertQueued()` Not `assertSent()` for Queued Mailables + +`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint. + +Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`. + +Correct: `Mail::assertQueued(OrderShipped::class);` + +## Use Markdown Mailables for Transactional Emails + +Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag. + +## Separate Content Tests from Sending Tests + +Content tests: instantiate the mailable directly, call `assertSeeInHtml()`. +Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`. +Don't mix them — it conflates concerns and makes tests brittle. diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.md new file mode 100644 index 00000000..af671c0d --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/migrations.md @@ -0,0 +1,121 @@ +# Migration Best Practices + +## Generate Migrations with Artisan + +Always use `php artisan make:migration` for consistent naming and timestamps. + +Incorrect (manually created file): +```php +// database/migrations/posts_migration.php ← wrong naming, no timestamp +``` + +Correct (Artisan-generated): +```bash +php artisan make:migration create_posts_table +php artisan make:migration add_slug_to_posts_table +``` + +## Use `constrained()` for Foreign Keys + +Automatic naming and referential integrity. + +```php +$table->foreignId('user_id')->constrained()->cascadeOnDelete(); + +// Non-standard names +$table->foreignId('author_id')->constrained('users'); +``` + +## Never Modify Deployed Migrations + +Once a migration has run in production, treat it as immutable. Create a new migration to change the table. + +Incorrect (editing a deployed migration): +```php +// 2024_01_01_create_posts_table.php — already in production +$table->string('slug')->unique(); // ← added after deployment +``` + +Correct (new migration to alter): +```php +// 2024_03_15_add_slug_to_posts_table.php +Schema::table('posts', function (Blueprint $table) { + $table->string('slug')->unique()->after('title'); +}); +``` + +## Add Indexes in the Migration + +Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes. + +Incorrect: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); +}); +``` + +Correct: +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->index()->constrained(); + $table->string('status')->index(); + $table->timestamp('shipped_at')->nullable()->index(); + $table->timestamps(); +}); +``` + +## Mirror Defaults in Model `$attributes` + +When a column has a database default, mirror it in the model so new instances have correct values before saving. + +```php +// Migration +$table->string('status')->default('pending'); + +// Model +protected $attributes = [ + 'status' => 'pending', +]; +``` + +## Write Reversible `down()` Methods by Default + +Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments. + +```php +public function down(): void +{ + Schema::table('posts', function (Blueprint $table) { + $table->dropColumn('slug'); + }); +} +``` + +For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported. + +## Keep Migrations Focused + +One concern per migration. Never mix DDL (schema changes) and DML (data manipulation). + +Incorrect (partial failure creates unrecoverable state): +```php +public function up(): void +{ + Schema::create('settings', function (Blueprint $table) { ... }); + DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); +} +``` + +Correct (separate migrations): +```php +// Migration 1: create_settings_table +Schema::create('settings', function (Blueprint $table) { ... }); + +// Migration 2: seed_default_settings +DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']); +``` diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.md new file mode 100644 index 00000000..c41915e2 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/queue-jobs.md @@ -0,0 +1,144 @@ +# Queue & Job Best Practices + +## Set `retry_after` Greater Than `timeout` + +If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution. + +Incorrect (`retry_after` ≤ `timeout`): +```php +class ProcessReport implements ShouldQueue +{ + public $timeout = 120; +} + +// config/queue.php — retry_after: 90 ← job retried while still running! +``` + +Correct (`retry_after` > `timeout`): +```php +class ProcessReport implements ShouldQueue +{ + public $timeout = 120; +} + +// config/queue.php — retry_after: 180 ← safely longer than any job timeout +``` + +## Use Exponential Backoff + +Use progressively longer delays between retries to avoid hammering failing services. + +Incorrect (fixed retry interval): +```php +class SyncWithStripe implements ShouldQueue +{ + public $tries = 3; + // Default: retries immediately, overwhelming the API +} +``` + +Correct (exponential backoff): +```php +class SyncWithStripe implements ShouldQueue +{ + public $tries = 3; + public $backoff = [1, 5, 10]; +} +``` + +## Implement `ShouldBeUnique` + +Prevent duplicate job processing. + +```php +class GenerateInvoice implements ShouldQueue, ShouldBeUnique +{ + public function uniqueId(): string + { + return $this->order->id; + } + + public $uniqueFor = 3600; +} +``` + +## Always Implement `failed()` + +Handle errors explicitly — don't rely on silent failure. + +```php +public function failed(?Throwable $exception): void +{ + $this->podcast->update(['status' => 'failed']); + Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]); +} +``` + +## Rate Limit External API Calls in Jobs + +Use `RateLimited` middleware to throttle jobs calling third-party APIs. + +```php +public function middleware(): array +{ + return [new RateLimited('external-api')]; +} +``` + +## Batch Related Jobs + +Use `Bus::batch()` when jobs should succeed or fail together. + +```php +Bus::batch([ + new ImportCsvChunk($chunk1), + new ImportCsvChunk($chunk2), +]) +->then(fn (Batch $batch) => Notification::send($user, new ImportComplete)) +->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed')) +->dispatch(); +``` + +## `retryUntil()` Needs `$tries = 0` + +When using time-based retry limits, set `$tries = 0` to avoid premature failure. + +```php +public $tries = 0; + +public function retryUntil(): \DateTimeInterface +{ + return now()->addHours(4); +} +``` + +## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release + +`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue. + +```php +class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing +{ + // Lock releases when processing begins, not when it finishes +} +``` + +## Use Horizon for Complex Queue Scenarios + +Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities. + +```php +// config/horizon.php +'environments' => [ + 'production' => [ + 'supervisor-1' => [ + 'connection' => 'redis', + 'queue' => ['high', 'default', 'low'], + 'balance' => 'auto', + 'minProcesses' => 1, + 'maxProcesses' => 10, + 'tries' => 3, + ], + ], +], +``` diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.md new file mode 100644 index 00000000..b6e30864 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/routing.md @@ -0,0 +1,99 @@ +# Routing & Controllers Best Practices + +## Use Implicit Route Model Binding + +Let Laravel resolve models automatically from route parameters. + +Incorrect: +```php +public function show(int $id) +{ + $post = Post::findOrFail($id); +} +``` + +Correct: +```php +public function show(Post $post) +{ + return view('posts.show', ['post' => $post]); +} +``` + +## Use Scoped Bindings for Nested Resources + +Enforce parent-child relationships automatically. + +```php +Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) { + // $post is automatically scoped to $user +})->scopeBindings(); +``` + +## Use Resource Controllers + +Use `Route::resource()` or `apiResource()` for RESTful endpoints. + +```php +Route::resource('posts', PostController::class); +// In routes/api.php — the /api prefix is applied automatically +Route::apiResource('posts', Api\PostController::class); +``` + +## Keep Controllers Thin + +Aim for under 10 lines per method. Extract business logic to action or service classes. + +Incorrect: +```php +public function store(Request $request) +{ + $validated = $request->validate([...]); + if ($request->hasFile('image')) { + $request->file('image')->move(public_path('images')); + } + $post = Post::create($validated); + $post->tags()->sync($validated['tags']); + event(new PostCreated($post)); + return redirect()->route('posts.show', $post); +} +``` + +Correct: +```php +public function store(StorePostRequest $request, CreatePostAction $create) +{ + $post = $create->execute($request->validated()); + + return redirect()->route('posts.show', $post); +} +``` + +## Type-Hint Form Requests + +Type-hinting Form Requests triggers automatic validation and authorization before the method executes. + +Incorrect: +```php +public function store(Request $request): RedirectResponse +{ + $validated = $request->validate([ + 'title' => ['required', 'max:255'], + 'body' => ['required'], + ]); + + Post::create($validated); + + return redirect()->route('posts.index'); +} +``` + +Correct: +```php +public function store(StorePostRequest $request): RedirectResponse +{ + Post::create($request->validated()); + + return redirect()->route('posts.index'); +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.md new file mode 100644 index 00000000..a9847945 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/scheduling.md @@ -0,0 +1,39 @@ +# Task Scheduling Best Practices + +## Use `withoutOverlapping()` on Variable-Duration Tasks + +Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion. + +## Use `onOneServer()` on Multi-Server Deployments + +Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached). + +## Use `runInBackground()` for Concurrent Long Tasks + +By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes. + +## Use `environments()` to Restrict Tasks + +Prevent accidental execution of production-only tasks (billing, reporting) on staging. + +```php +Schedule::command('billing:charge')->monthly()->environments(['production']); +``` + +## Use `takeUntilTimeout()` for Time-Bounded Processing + +A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time. + +## Use Schedule Groups for Shared Configuration + +Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks. + +```php +Schedule::daily() + ->onOneServer() + ->timezone('America/New_York') + ->group(function () { + Schedule::command('emails:send --force'); + Schedule::command('emails:prune'); + }); +``` diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.md new file mode 100644 index 00000000..358af15f --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/security.md @@ -0,0 +1,198 @@ +# Security Best Practices + +## Mass Assignment Protection + +Every model must define `$fillable` (whitelist) or `$guarded` (blacklist). + +Incorrect: +```php +class User extends Model +{ + protected $guarded = []; // All fields are mass assignable +} +``` + +Correct: +```php +class User extends Model +{ + protected $fillable = [ + 'name', + 'email', + 'password', + ]; +} +``` + +Never use `$guarded = []` on models that accept user input. + +## Authorize Every Action + +Use policies or gates in controllers. Never skip authorization. + +Incorrect: +```php +public function update(UpdatePostRequest $request, Post $post) +{ + $post->update($request->validated()); +} +``` + +Correct: +```php +public function update(UpdatePostRequest $request, Post $post) +{ + Gate::authorize('update', $post); + + $post->update($request->validated()); +} +``` + +Or via Form Request: + +```php +public function authorize(): bool +{ + return $this->user()->can('update', $this->route('post')); +} +``` + +## Prevent SQL Injection + +Always use parameter binding. Never interpolate user input into queries. + +Incorrect: +```php +DB::select("SELECT * FROM users WHERE name = '{$request->name}'"); +``` + +Correct: +```php +User::where('name', $request->name)->get(); + +// Raw expressions with bindings +User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get(); +``` + +## Escape Output to Prevent XSS + +Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content. + +Incorrect: +```blade +{!! $user->bio !!} +``` + +Correct: +```blade +{{ $user->bio }} +``` + +## CSRF Protection + +Include `@csrf` in all POST/PUT/PATCH/DELETE Blade forms. Inertia doesn't use `@csrf`; its HTTP client sends the `XSRF-TOKEN` cookie back as the `X-XSRF-TOKEN` header, which Laravel accepts in place of the `_token` field. + +Incorrect: +```blade +
+ +
+``` + +Correct: +```blade +
+ @csrf + +
+``` + +## Rate Limit Auth and API Routes + +Apply `throttle` middleware to authentication and API routes. + +```php +RateLimiter::for('login', function (Request $request) { + return Limit::perMinute(5)->by($request->ip()); +}); + +Route::post('/login', LoginController::class)->middleware('throttle:login'); +``` + +## Validate File Uploads + +Validate MIME type and size. Both `mimes` and `mimetypes` read the file's contents to guess its MIME type; `mimes` just expresses the allow-list as extensions. The `extensions` rule checks only the client-supplied filename, so never rely on it alone. Never trust client-provided filenames. + +```php +public function rules(): array +{ + return [ + 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], + ]; +} +``` + +Store with generated filenames: + +```php +$path = $request->file('avatar')->store('avatars', 'public'); +``` + +## Keep Secrets Out of Code + +Never commit `.env`. Access secrets via `config()` only. + +Incorrect: +```php +$key = env('API_KEY'); +``` + +Correct: +```php +// config/services.php +'api_key' => env('API_KEY'), + +// In application code +$key = config('services.api_key'); +``` + +## Audit Dependencies + +Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment. + +```bash +composer audit +``` + +## Encrypt Sensitive Database Fields + +Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`. + +Incorrect: +```php +class Integration extends Model +{ + protected function casts(): array + { + return [ + 'api_key' => 'string', + ]; + } +} +``` + +Correct: +```php +class Integration extends Model +{ + protected $hidden = ['api_key', 'api_secret']; + + protected function casts(): array + { + return [ + 'api_key' => 'encrypted', + 'api_secret' => 'encrypted', + ]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.md new file mode 100644 index 00000000..a8afb369 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/style.md @@ -0,0 +1,125 @@ +# Conventions & Style + +## Follow Laravel Naming Conventions + +| What | Convention | Good | Bad | +|------|-----------|------|-----| +| Controller | singular | `ArticleController` | `ArticlesController` | +| Model | singular | `User` | `Users` | +| Table | plural, snake_case | `article_comments` | `articleComments` | +| Pivot table | singular alphabetical | `article_user` | `user_article` | +| Column | snake_case, no model name | `meta_title` | `article_meta_title` | +| Foreign key | singular model + `_id` | `article_id` | `articles_id` | +| Route | plural | `articles/1` | `article/1` | +| Route name | snake_case with dots | `users.show_active` | `users.show-active` | +| Method | camelCase | `getAll` | `get_all` | +| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` | +| Collection | descriptive, plural | `$activeUsers` | `$data` | +| Object | descriptive, singular | `$activeUser` | `$users` | +| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` | +| Config | snake_case | `google_calendar.php` | `googleCalendar.php` | +| Enum | singular | `UserType` | `UserTypes` | + +## Prefer Shorter Readable Syntax + +| Verbose | Shorter | +|---------|---------| +| `Session::get('cart')` | `session('cart')` | +| `$request->session()->get('cart')` | `session('cart')` | +| `$request->input('name')` | `$request->name` | +| `return Redirect::back()` | `return back()` | +| `Carbon::now()` | `now()` | +| `App::make('Class')` | `app('Class')` | +| `->where('column', '=', 1)` | `->where('column', 1)` | +| `->orderBy('created_at', 'desc')` | `->latest()` | +| `->orderBy('created_at', 'asc')` | `->oldest()` | +| `->first()->name` | `->value('name')` | + +## Use Laravel String & Array Helpers + +Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them. + +Strings — use `Str` and fluent `Str::of()` over raw PHP: +```php +// Incorrect +$slug = strtolower(str_replace(' ', '-', $title)); +$short = substr($text, 0, 100) . '...'; +$class = substr(strrchr('App\Models\User', '\\'), 1); + +// Correct +$slug = Str::slug($title); +$short = Str::limit($text, 100); +$class = class_basename('App\Models\User'); +``` + +Fluent strings — chain operations for complex transformations: +```php +// Incorrect +$result = strtolower(trim(str_replace('_', '-', $input))); + +// Correct +$result = Str::of($input)->trim()->replace('_', '-')->lower(); +``` + +Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`. + +Arrays — use `Arr` over raw PHP: +```php +// Incorrect +$name = isset($array['user']['name']) ? $array['user']['name'] : 'default'; + +// Correct +$name = Arr::get($array, 'user.name', 'default'); +``` + +Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`. + +Numbers — use `Number` for display formatting: +```php +Number::format(1000000); // "1,000,000" +Number::currency(1500, 'USD'); // "$1,500.00" +Number::abbreviate(1000000); // "1M" +Number::fileSize(1024 * 1024); // "1 MB" +Number::percentage(75.5); // "75.5%" +``` + +URIs — use `Uri` for URL manipulation: +```php +$uri = Uri::of('https://example.com/search') + ->withQuery(['q' => 'laravel', 'page' => 1]); +``` + +Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining. + +Use `search-docs` for the full list of available methods — these helpers are extensive. + +## No Inline JS/CSS in Blade + +Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes. + +Incorrect: +```blade +let article = `{{ json_encode($article) }}`; +``` + +Correct: +```blade + +``` + +Pass data to JS via data attributes or use a dedicated PHP-to-JS package. + +## No Unnecessary Comments + +Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected. + +Incorrect: +```php +// Check if there are any joins +if (count((array) $builder->getQuery()->joins) > 0) +``` + +Correct: +```php +if ($this->hasJoins()) +``` diff --git a/.agents/skills/laravel-best-practices/rules/testing.md b/.agents/skills/laravel-best-practices/rules/testing.md new file mode 100644 index 00000000..2677e0bb --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/testing.md @@ -0,0 +1,43 @@ +# Testing Best Practices + +## Use `LazilyRefreshDatabase` Over `RefreshDatabase` + +`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` behaves the same, except it defers that work until a test actually touches the database, so tests that never query it skip the migration entirely. + +## Use Model Assertions Over Raw Database Assertions + +Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);` + +Correct: `$this->assertModelExists($user);` + +More expressive, type-safe, and fails with clearer messages. + +## Use Factory States and Sequences + +Named states make tests self-documenting. Sequences eliminate repetitive setup. + +Incorrect: `User::factory()->create(['email_verified_at' => null]);` + +Correct: `User::factory()->unverified()->create();` + +## Use `Exceptions::fake()` to Assert Exception Reporting + +Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally. + +## Call `Event::fake()` After Factory Setup + +Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models. + +Incorrect: `Event::fake(); $user = User::factory()->create();` + +Correct: `$user = User::factory()->create(); Event::fake();` + +## Use `recycle()` to Share Relationship Instances Across Factories + +Without `recycle()`, nested factories create separate instances of the same conceptual entity. + +```php +Ticket::factory() + ->recycle(Airline::factory()->create()) + ->create(); +``` diff --git a/.agents/skills/laravel-best-practices/rules/validation.md b/.agents/skills/laravel-best-practices/rules/validation.md new file mode 100644 index 00000000..5fde1064 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/validation.md @@ -0,0 +1,75 @@ +# Validation & Forms Best Practices + +## Use Form Request Classes + +Extract validation from controllers into dedicated Form Request classes. + +Incorrect: +```php +public function store(Request $request) +{ + $request->validate([ + 'title' => 'required|max:255', + 'body' => 'required', + ]); +} +``` + +Correct: +```php +public function store(StorePostRequest $request) +{ + Post::create($request->validated()); +} +``` + +## Array vs. String Notation for Rules + +Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses. + +```php +// Preferred for new code +'email' => ['required', 'email', Rule::unique('users')], + +// Follow existing convention if the project uses string notation +'email' => 'required|email|unique:users', +``` + +## Always Use `validated()` + +Get only validated data. Never use `$request->all()` for mass operations. + +Incorrect: +```php +Post::create($request->all()); +``` + +Correct: +```php +Post::create($request->validated()); +``` + +## Use `Rule::when()` for Conditional Validation + +```php +'company_name' => [ + Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']), +], +``` + +## Use the `after()` Method for Custom Validation + +Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields. + +```php +public function after(): array +{ + return [ + function (Validator $validator) { + if ($this->quantity > Product::find($this->product_id)?->stock) { + $validator->errors()->add('quantity', 'Not enough stock.'); + } + }, + ]; +} +``` diff --git a/.agents/skills/livewire-development/SKILL.md b/.agents/skills/livewire-development/SKILL.md new file mode 100644 index 00000000..4643ccbf --- /dev/null +++ b/.agents/skills/livewire-development/SKILL.md @@ -0,0 +1,175 @@ +--- +name: livewire-development +description: "Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, wire:sort, or islands, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, drag-and-drop, loading states, migrating from Livewire 3 to 4, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire." +license: MIT +metadata: + author: laravel +--- + +# Livewire Development + +## Documentation + +Use `search-docs` for detailed Livewire 4 patterns and documentation. + +## Basic Usage + +### Creating Components + +```bash + +# Single-file component (SFC - default in v4) + +# Creates: resources/views/components/⚡create-post.blade.php + +php artisan make:livewire create-post + +# Page component (SFC - Full Page in v4) + +# Creates: resources/views/pages/⚡create-post.blade.php + +php artisan make:livewire pages::create-post + +# Multi-file component (MFC) + +# Creates: resources/views/components/⚡create-post/create-post.php + +# resources/views/components/⚡create-post/create-post.blade.php + +php artisan make:livewire create-post --mfc + +# Class-based component (v3 style) + +# Creates: app/Livewire/CreatePost.php AND resources/views/livewire/create-post.blade.php + +php artisan make:livewire create-post --class + +# With namespace + +php artisan make:livewire Posts/CreatePost +``` + +### Converting Between Formats + +Use `php artisan livewire:convert create-post` to convert between single-file, multi-file, and class-based formats. + +### Choosing a Component Format + +> **Always follow the project's existing conventions first.** Before creating any component, inspect the project's existing Livewire components to determine the established format (SFC, MFC, or class-based) and directory structure. Check `app/Livewire/`, `resources/views/components/`, and `resources/views/livewire/` for existing components. If the project already uses a consistent format, **use that same format** — even if it differs from the Livewire v4 defaults below. Only fall back to the v4 defaults (SFC in `resources/views/components/`) when no existing convention is established. + +Also check `config/livewire.php` for `make_command.type`, `make_command.emoji`, `component_locations`, and `component_namespaces` overrides, which change the default format and where files are stored. + +### Component Format Reference + +| Format | Flag | Class Path | View Path | +|--------|------|------------|-----------| +| Single-file (SFC) | default | — | `resources/views/components/⚡create-post.blade.php` (PHP + Blade in one file) | +| Full Page SFC | `pages::name` | — | `resources/views/pages/⚡create-post.blade.php` | +| Multi-file (MFC) | `--mfc` | `resources/views/components/⚡create-post/create-post.php` | `resources/views/components/⚡create-post/create-post.blade.php` | +| Class-based | `--class` | `app/Livewire/CreatePost.php` | `resources/views/livewire/create-post.blade.php` | +| View-based | default (Blade-only) | — | `resources/views/components/⚡create-post.blade.php` (Blade-only with functional state) | + +> **Important:** The ⚡ prefix shown above is the **default** behavior in Livewire v4 — it is **configurable**. Check `config/livewire.php` for the `make_command.emoji` setting. When `true` (default), always include the ⚡ prefix in filenames you create. When `false`, omit the ⚡ prefix from all paths above. + +Namespaced components map to subdirectories: `make:livewire Posts/CreatePost` creates `resources/views/components/posts/⚡create-post.blade.php` (single-file by default). Use `make:livewire Posts/CreatePost --mfc` for multi-file output at `resources/views/components/posts/⚡create-post/create-post.php` and `resources/views/components/posts/⚡create-post/create-post.blade.php`. + +### Single-File Component Example + + +```php +count++; + } +}; +?> + +
+ +
+``` + +## Livewire 4 Specifics + +### Key Changes From Livewire 3 + +These things changed in Livewire 4, but may not have been updated in this application. Verify this application's setup to ensure you follow existing conventions. + +- Use `Route::livewire()` for full-page components (e.g., `Route::livewire('/posts/create', CreatePost::class)`); config keys renamed: `layout` → `component_layout`, `lazy_placeholder` → `component_placeholder`. +- `wire:model` now ignores child events by default (use `wire:model.deep` for old behavior); `wire:scroll` renamed to `wire:navigate:scroll`. +- Component tags must be properly closed; `wire:transition` now uses View Transitions API (modifiers removed). +- JavaScript: `$wire.$js('name', fn)` → `$wire.$js.name = fn`; `commit`/`request` hooks → `interceptMessage()`/`interceptRequest()`. + +### New Features + +- Component formats: single-file (SFC), multi-file (MFC), view-based components. +- Islands (`@island`) for isolated updates; async actions (`wire:click.async`, `#[Async]`) for parallel execution. +- Deferred/bundled loading: `defer`, `lazy.bundle` for optimized component loading. + +| Feature | Usage | Purpose | +|---------|-------|---------| +| Islands | `@island(name: 'stats')` | Isolated update regions | +| Async | `wire:click.async` or `#[Async]` | Non-blocking actions | +| Deferred | `defer` attribute | Load after page render | +| Bundled | `lazy.bundle` | Load multiple together | + +### New Directives + +- `wire:sort`, `wire:intersect`, `wire:ref`, `.renderless`, `.preserve-scroll` are available for use. +- `data-loading` attribute automatically added to elements triggering network requests. + +| Directive | Purpose | +|-----------|---------| +| `wire:sort` | Drag-and-drop sorting | +| `wire:intersect` | Viewport intersection detection | +| `wire:ref` | Element references for JS | +| `.renderless` | Component without rendering | +| `.preserve-scroll` | Preserve scroll position | + +## Best Practices + +- Always use `wire:key` in loops +- Use `wire:loading` for loading states +- Use `wire:model.live` for live updates; `wire:model` is deferred by default +- Validate and authorize in actions (treat like HTTP requests) + +## Configuration + +- `smart_wire_keys` defaults to `true`; new configs: `component_locations`, `component_namespaces`, `make_command`, `csp_safe`. + +## Alpine & JavaScript + +- `wire:transition` uses browser View Transitions API; `$errors` and `$intercept` magic properties available. +- Non-blocking `wire:poll` and parallel `wire:model.live` updates improve performance. + +For interceptors and hooks, see [reference/javascript-hooks.md](reference/javascript-hooks.md). + +## Testing + + +```php +Livewire::test(Counter::class) + ->assertSet('count', 0) + ->call('increment') + ->assertSet('count', 1); +``` + +## Verification + +1. Browser console: Check for JS errors +2. Network tab: Verify Livewire requests return 200 +3. Ensure `wire:key` on all `@foreach` loops + +## Common Pitfalls + +- Missing `wire:key` in loops → unexpected re-rendering +- Expecting `wire:model` real-time → use `wire:model.live` +- Unclosed component tags → syntax errors in v4 +- Using deprecated config keys or JS hooks +- Including Alpine.js separately (already bundled in Livewire 4) diff --git a/.agents/skills/livewire-development/reference/javascript-hooks.md b/.agents/skills/livewire-development/reference/javascript-hooks.md new file mode 100644 index 00000000..660d66b5 --- /dev/null +++ b/.agents/skills/livewire-development/reference/javascript-hooks.md @@ -0,0 +1,39 @@ +# Livewire 4 JavaScript Integration + +## Interceptor System (v4) + +### Intercept Messages + +```js +Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError }) => { + onFinish(() => { /* After response, before processing */ }); + onSuccess(({ payload }) => { /* payload.snapshot, payload.effects */ }); + onError(() => { /* Server errors */ }); +}); +``` + +### Intercept Requests + +```js +Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure }) => { + onResponse(({ response }) => { /* When received */ }); + onSuccess(({ response, responseJson }) => { /* Success */ }); + onError(({ response, responseBody, preventDefault }) => { /* 4xx/5xx */ }); + onFailure(({ error }) => { /* Network failures */ }); +}); +``` + +### Component-Scoped Interceptors + +```blade + +``` + +## Magic Properties + +- `$errors` - Access validation errors from JavaScript +- `$intercept` - Component-scoped interceptors diff --git a/.agents/skills/pest-testing/SKILL.md b/.agents/skills/pest-testing/SKILL.md new file mode 100644 index 00000000..ab271616 --- /dev/null +++ b/.agents/skills/pest-testing/SKILL.md @@ -0,0 +1,166 @@ +--- +name: pest-testing +description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code." +license: MIT +metadata: + author: laravel +--- + +# Pest Testing 4 + +## Documentation + +Use `search-docs` for detailed Pest 4 patterns and documentation. + +## Basic Usage + +### Creating Tests + +All tests must be written using Pest. Use `php artisan make:test --pest {name}`. + +The `{name}` argument should include only the path and test name, but should not include the test suite. +- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php` +- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php` +- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php` +- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php` + +### Test Organization + +- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories. +- Browser tests: `tests/Browser/` directory. +- Do NOT remove tests without approval - these are core application code. + +### Basic Test Structure + +Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`. + + +```php +it('is true', function () { + expect(true)->toBeTrue(); +}); +``` + +### Running Tests + +- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`. +- Run all tests: `php artisan test --compact`. +- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`. + +## Assertions + +Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`: + + +```php +it('returns all', function () { + $this->postJson('/api/docs', [])->assertSuccessful(); +}); +``` + +| Use | Instead of | +|-----|------------| +| `assertSuccessful()` | `assertStatus(200)` | +| `assertNotFound()` | `assertStatus(404)` | +| `assertForbidden()` | `assertStatus(403)` | + +## Mocking + +Import mock function before use: `use function Pest\Laravel\mock;` + +## Datasets + +Use datasets for repetitive tests (validation rules, etc.): + + +```php +it('has emails', function (string $email) { + expect($email)->not->toBeEmpty(); +})->with([ + 'james' => 'james@laravel.com', + 'taylor' => 'taylor@laravel.com', +]); +``` + +## Pest 4 Features + +| Feature | Purpose | +|---------|---------| +| Browser Testing | Full integration tests in real browsers | +| Smoke Testing | Validate multiple pages quickly | +| Visual Regression | Compare screenshots for visual changes | +| Test Sharding | Parallel CI runs | +| Architecture Testing | Enforce code conventions | + +### Browser Test Example + +Browser tests run in real browsers for full integration testing: + +- Browser tests live in `tests/Browser/`. +- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories. +- Use `RefreshDatabase` for clean state per test. +- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures. +- Test on multiple browsers (Chrome, Firefox, Safari) if requested. +- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested. +- Switch color schemes (light/dark mode) when appropriate. +- Take screenshots or pause tests for debugging. + + +```php +it('may reset the password', function () { + Notification::fake(); + + $this->actingAs(User::factory()->create()); + + $page = visit('/sign-in'); + + $page->assertSee('Sign In') + ->assertNoJavaScriptErrors() + ->click('Forgot Password?') + ->fill('email', 'nuno@laravel.com') + ->click('Send Reset Link') + ->assertSee('We have emailed your password reset link!'); + + Notification::assertSent(ResetPassword::class); +}); +``` + +### Smoke Testing + +Quickly validate multiple pages have no JavaScript errors: + + +```php +$pages = visit(['/', '/about', '/contact']); + +$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs(); +``` + +### Visual Regression Testing + +Capture and compare screenshots to detect visual changes. + +### Test Sharding + +Split tests across parallel processes for faster CI runs. + +### Architecture Testing + +Pest 4 includes architecture testing (from Pest 3): + + +```php +arch('controllers') + ->expect('App\Http\Controllers') + ->toExtendNothing() + ->toHaveSuffix('Controller'); +``` + +## Common Pitfalls + +- Not importing `use function Pest\Laravel\mock;` before using mock +- Using `assertStatus(200)` instead of `assertSuccessful()` +- Forgetting datasets for repetitive validation tests +- Deleting tests without approval +- Forgetting `assertNoJavaScriptErrors()` in browser tests +- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test` diff --git a/.agents/skills/tailwindcss-development/SKILL.md b/.agents/skills/tailwindcss-development/SKILL.md new file mode 100644 index 00000000..c0cb2fbc --- /dev/null +++ b/.agents/skills/tailwindcss-development/SKILL.md @@ -0,0 +1,119 @@ +--- +name: tailwindcss-development +description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS." +license: MIT +metadata: + author: laravel +--- + +# Tailwind CSS Development + +## Documentation + +Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation. + +## Basic Usage + +- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns. +- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue). +- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically. + +## Tailwind CSS v4 Specifics + +- Always use Tailwind CSS v4 and avoid deprecated utilities. +- `corePlugins` is not supported in Tailwind v4. + +### CSS-First Configuration + +In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed: + + +```css +@theme { + --color-brand: oklch(0.72 0.11 178); +} +``` + +### Import Syntax + +In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3: + + +```diff +- @tailwind base; +- @tailwind components; +- @tailwind utilities; ++ @import "tailwindcss"; +``` + +### Replaced Utilities + +Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric. + +| Deprecated | Replacement | +|------------|-------------| +| bg-opacity-* | bg-black/* | +| text-opacity-* | text-black/* | +| border-opacity-* | border-black/* | +| divide-opacity-* | divide-black/* | +| ring-opacity-* | ring-black/* | +| placeholder-opacity-* | placeholder-black/* | +| flex-shrink-* | shrink-* | +| flex-grow-* | grow-* | +| overflow-ellipsis | text-ellipsis | +| decoration-slice | box-decoration-slice | +| decoration-clone | box-decoration-clone | + +## Spacing + +Use `gap` utilities instead of margins for spacing between siblings: + + +```html +
+
Item 1
+
Item 2
+
+``` + +## Dark Mode + +If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant: + + +```html +
+ Content adapts to color scheme +
+``` + +## Common Patterns + +### Flexbox Layout + + +```html +
+
Left content
+
Right content
+
+``` + +### Grid Layout + + +```html +
+
Card 1
+
Card 2
+
Card 3
+
+``` + +## Common Pitfalls + +- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.) +- Using `@tailwind` directives instead of `@import "tailwindcss"` +- Trying to use `tailwind.config.js` instead of CSS `@theme` directive +- Using margins for spacing between siblings instead of gap utilities +- Forgetting to add dark mode variants when the project uses dark mode diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 00000000..864e1fbd --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,3 @@ +[mcp_servers.laravel-boost] +command = "php" +args = ["artisan", "boost:mcp"] diff --git a/.env.example b/.env.example index c0660ea1..3ba18ff7 100644 --- a/.env.example +++ b/.env.example @@ -27,17 +27,17 @@ DB_CONNECTION=sqlite # DB_USERNAME=root # DB_PASSWORD= -SESSION_DRIVER=database +SESSION_DRIVER=file SESSION_LIFETIME=120 -SESSION_ENCRYPT=false +SESSION_ENCRYPT=true SESSION_PATH=/ SESSION_DOMAIN=null BROADCAST_CONNECTION=log FILESYSTEM_DISK=local -QUEUE_CONNECTION=database +QUEUE_CONNECTION=sync -CACHE_STORE=database +CACHE_STORE=file # CACHE_PREFIX= MEMCACHED_HOST=127.0.0.1 diff --git a/AGENTS.md b/AGENTS.md index 296f2af0..67c206f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,3 +23,208 @@ The complete specification is in `specs/`. Start with `specs/09-IMPLEMENTATION-R - `specs/07-SEEDERS-AND-TEST-DATA.md` - Seeders and test data - `specs/08-PLAYWRIGHT-E2E-PLAN.md` - E2E browser tests - `specs/09-IMPLEMENTATION-ROADMAP.md` - Implementation roadmap + +=== + + +=== 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 ensure the best experience when building Laravel applications. + +## Foundational Context + +This application is a Laravel application running on PHP 8.4. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version. + +Before relying on a package's API, confirm its installed version: +- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show ` for a single package. +- JS packages: check `package.json` for the installed versions. + +## Skills Activation + +This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck. + +## 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 they work. 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. + +## Documentation Files + +- You must only create documentation files if explicitly requested by the user. + +## Replies + +- Be concise in your explanations - focus on what's important rather than explaining obvious details. + +=== boost rules === + +# Laravel Boost + +## Tools + +- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads. +- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker. +- Use `database-schema` to inspect table structure before writing migrations or models. +- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user. +- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries. + +## Searching Documentation (IMPORTANT) + +- Use `search-docs` before changes that depend on Laravel ecosystem APIs, behavior, configuration, or version-specific syntax. Skip it for copy-only edits and other changes where package documentation is irrelevant. Reuse sufficient results already in context instead of searching again. +- Pass a `packages` array to scope results when you know which packages are relevant. +- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first. +- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`. + +### Search Syntax + +1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit". +2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order. +3. Combine words and phrases for mixed queries: `middleware "rate limit"`. +4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`. + +## Project Rules + +- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule. If `.ai/rules` does not exist, continue without it. +- Record durable rules with `record-rule` so the next agent or teammate inherits them instead of working them out again. Pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Always use `record-rule`, never your native memory or notes tool — native memory is personal and session-scoped; only `.ai/rules` is shared with the team and persists in the repo. + +## Artisan + +- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters. +- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`. +- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory. + +## Tinker + +- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code. +- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'` + - Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'` + +=== php rules === + +# PHP + +- Always use curly braces for control structures, even for single-line bodies. +- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private. +- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool` +- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`. +- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic. +- Use array shape type definitions in PHPDoc blocks. + +=== deployments rules === + +# Deployment + +- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications. + +=== 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-fortify/core rules === + +# Laravel Fortify + +- Fortify is a headless authentication backend that provides authentication routes and controllers for Laravel applications. +- IMPORTANT: Always use the `search-docs` tool for detailed Laravel Fortify patterns and documentation. +- IMPORTANT: Activate `developing-with-fortify` skill when working with Fortify authentication features. + +=== 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 `php artisan list` and check their parameters with `php artisan [command] --help`. +- 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. + +### Model Creation + +- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options. + +## 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. + +## URL Generation + +- When generating links to other pages, prefer named routes and the `route()` function. + +## 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 + +- CRITICAL: ALWAYS use `search-docs` tool for version-specific Laravel documentation and updated code examples. +- Since Laravel 11, Laravel has a new streamlined file structure which this project uses. + +## Laravel 12 Structure + +- In Laravel 12, middleware are no longer registered in `app/Http/Kernel.php`. +- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`. +- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files. +- `bootstrap/providers.php` contains application specific service providers. +- The `app/Console/Kernel.php` file no longer exists; use `bootstrap/app.php` or `routes/console.php` for console configuration. +- Console commands in `app/Console/Commands/` are automatically available and do not require manual registration. + +## 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. + +=== livewire/core rules === + +# Livewire + +- Livewire allow to build dynamic, reactive interfaces in PHP without writing JavaScript. +- You can use Alpine.js for client-side interactions instead of JavaScript frameworks. +- Keep state server-side so the UI reflects it. Validate and authorize in actions as you would in HTTP requests. + +=== pint/core rules === + +# Laravel Pint Code Formatter + +- If you have modified any PHP files, you must run `vendor/bin/pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style. +- Do not run `vendor/bin/pint --test --format agent`, simply run `vendor/bin/pint --format agent` to fix any formatting issues. + +=== pest/core rules === + +## Pest + +- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`. +- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`. +- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`. +- Do NOT delete tests without approval. + + diff --git a/README.md b/README.md new file mode 100644 index 00000000..245fb805 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +Your mission is to implement an entire shop system based on the specifications im specs/*. You must do in one go without stopping. You must use sub-agents! You must test everything via Pest (unit, and functional tests). You must also additional simulate user behaviour using the Playwright MPC and confirm that all acceptance criterias are met. If you find bugs, you must fix them. The result is a perfect shop system. All requirements are perfectly implemented. All acceptance criterias are met, tested and verified by a 2nd agent. + +Continuously keep track of the progress in specs/progress.md Commit your progress after every relevant iteration with a meaningful message. + +When implementation is fully done, then make a full review meeting and showcase all features (customer- and admin-side) to me. In case bugs appear, you must fix them all and restart the review meeting. + +Don't re-use any existing implementation in another branch. Build it from scratch. diff --git a/app/Auth/CustomerUserProvider.php b/app/Auth/CustomerUserProvider.php new file mode 100644 index 00000000..5b2deb17 --- /dev/null +++ b/app/Auth/CustomerUserProvider.php @@ -0,0 +1,27 @@ +createModel(); + $query = $model->newQuery(); + + if (app()->bound('current_store')) { + $query->where($model->qualifyColumn('store_id'), app('current_store')->getKey()); + } + + return $query; + } +} diff --git a/app/Auth/StoreScopedPasswordBrokerManager.php b/app/Auth/StoreScopedPasswordBrokerManager.php new file mode 100644 index 00000000..8de9c786 --- /dev/null +++ b/app/Auth/StoreScopedPasswordBrokerManager.php @@ -0,0 +1,39 @@ +app['config']['app.key']; + + if (str_starts_with($key, 'base64:')) { + $key = base64_decode(substr($key, 7)); + } + + if (($config['table'] ?? null) === 'customer_password_reset_tokens') { + return new StoreScopedTokenRepository( + $this->app['db']->connection($config['connection'] ?? null), + $this->app['hash'], + $config['table'], + $key, + ($config['expire'] ?? 60) * 60, + $config['throttle'] ?? 0, + ); + } + + return new DatabaseTokenRepository( + $this->app['db']->connection($config['connection'] ?? null), + $this->app['hash'], + $config['table'], + $key, + ($config['expire'] ?? 60) * 60, + $config['throttle'] ?? 0, + ); + } +} diff --git a/app/Auth/StoreScopedTokenRepository.php b/app/Auth/StoreScopedTokenRepository.php new file mode 100644 index 00000000..54a7acd9 --- /dev/null +++ b/app/Auth/StoreScopedTokenRepository.php @@ -0,0 +1,72 @@ +getEmailForPasswordReset(); + $this->deleteExisting($user); + $token = $this->createNewToken(); + $this->scopedTable()->insert($this->getPayload($email, $token)); + + return $token; + } + + public function exists(CanResetPasswordContract $user, $token): bool + { + $record = (array) $this->scopedTable()->where('email', $user->getEmailForPasswordReset())->first(); + + return $record !== [] + && ! $this->tokenExpired($record['created_at']) + && $this->getHasher()->check($token, $record['token']); + } + + public function recentlyCreatedToken(CanResetPasswordContract $user): bool + { + $record = (array) $this->scopedTable()->where('email', $user->getEmailForPasswordReset())->first(); + + return $record !== [] && $this->tokenRecentlyCreated($record['created_at']); + } + + public function delete(CanResetPasswordContract $user): void + { + $this->deleteExisting($user); + } + + public function deleteExpired(): void + { + $expiredAt = Carbon::now()->subSeconds($this->expires); + $this->getTable()->where('created_at', '<', $expiredAt)->delete(); + } + + protected function deleteExisting(CanResetPasswordContract $user): int + { + return $this->scopedTable()->where('email', $user->getEmailForPasswordReset())->delete(); + } + + protected function getPayload($email, #[\SensitiveParameter] $token): array + { + return array_merge(parent::getPayload($email, $token), ['store_id' => $this->currentStoreId()]); + } + + private function scopedTable(): \Illuminate\Database\Query\Builder + { + return $this->getTable()->where('store_id', $this->currentStoreId()); + } + + private function currentStoreId(): int + { + if (! app()->bound('current_store') || ! app('current_store') instanceof Store) { + throw new \LogicException('A current store is required for customer password reset tokens.'); + } + + return (int) app('current_store')->getKey(); + } +} diff --git a/app/Contracts/PaymentProvider.php b/app/Contracts/PaymentProvider.php new file mode 100644 index 00000000..aa5aa1aa --- /dev/null +++ b/app/Contracts/PaymentProvider.php @@ -0,0 +1,16 @@ +assertStore($storeId); + $data = $request->validate(['status' => ['nullable', 'in:draft,active,archived'], 'query' => ['nullable', 'string'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:100']]); + $products = Product::withoutGlobalScopes()->where('store_id', $storeId)->with(['variants.inventory', 'collections'])->when($data['status'] ?? null, fn ($query, string $status) => $query->where('status', $status))->when($data['query'] ?? null, fn ($query, string $queryText) => $query->where(function ($nested) use ($queryText): void { + $nested->where('title', 'like', '%'.$queryText.'%')->orWhere('vendor', 'like', '%'.$queryText.'%')->orWhereHas('variants', fn ($variants) => $variants->where('sku', 'like', '%'.$queryText.'%')); + }))->latest('updated_at')->paginate($data['per_page'] ?? 25); + + return $this->paginated($products); + } + + public function storeProduct(StoreProductRequest $request, int $storeId, ProductService $products): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $product = $products->create(app('current_store'), [...$data, 'status' => ProductStatus::from($data['status'] ?? ProductStatus::Draft->value)]); + + return response()->json(['data' => $product->load(['variants.inventory', 'variants.optionValues.option', 'options.values', 'media', 'collections'])->toArray()], 201); + } + + public function showProduct(int $storeId, int $productId): JsonResponse + { + $this->assertStore($storeId); + $product = Product::withoutGlobalScopes()->where('store_id', $storeId)->with(['variants.inventory', 'variants.optionValues.option', 'options.values', 'media', 'collections'])->findOrFail($productId); + + return response()->json(['data' => $product->toArray()]); + } + + public function updateProduct(UpdateProductRequest $request, int $storeId, int $productId, ProductService $products): JsonResponse + { + $this->assertStore($storeId); + $product = Product::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($productId); + $data = $request->validated(); + + return response()->json(['data' => $products->update($product, $data)->load(['variants.inventory', 'variants.optionValues.option', 'options.values', 'media', 'collections'])->toArray()]); + } + + public function deleteProduct(int $storeId, int $productId, ProductService $products): JsonResponse + { + $this->assertStore($storeId); + $product = Product::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($productId); + $products->transitionStatus($product, ProductStatus::Archived); + + return response()->json(['message' => 'Product archived']); + } + + public function collections(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validate(['query' => ['nullable', 'string'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:100']]); + $collections = Collection::withoutGlobalScopes()->where('store_id', $storeId)->withCount('products')->when($data['query'] ?? null, fn ($query, string $queryText) => $query->where('title', 'like', '%'.$queryText.'%'))->latest()->paginate($data['per_page'] ?? 25); + + return $this->paginated($collections); + } + + public function storeCollection(StoreCollectionRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $collection = Collection::withoutGlobalScopes()->create(['store_id' => $storeId, 'title' => $data['title'], 'handle' => $data['handle'] ?? Str::slug($data['title']), 'description' => $data['description_html'] ?? null, 'status' => $data['status'] ?? 'active']); + $this->syncCollectionProducts($collection, $data['product_ids'] ?? [], $storeId); + + return response()->json(['data' => $collection->load('products')->toArray()], 201); + } + + public function updateCollection(UpdateCollectionRequest $request, int $storeId, int $collectionId): JsonResponse + { + $this->assertStore($storeId); + $collection = Collection::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($collectionId); + $data = $request->validated(); + $collection->update(array_filter(['title' => $data['title'] ?? null, 'description' => $data['description_html'] ?? null, 'status' => $data['status'] ?? null], fn ($value): bool => $value !== null)); + + if (array_key_exists('product_ids', $data)) { + $this->syncCollectionProducts($collection, $data['product_ids'], $storeId); + } + + return response()->json(['data' => $collection->load('products')->toArray()]); + } + + public function deleteCollection(int $storeId, int $collectionId): JsonResponse + { + $this->assertStore($storeId); + Collection::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($collectionId)->delete(); + + return response()->json(['message' => 'Collection deleted']); + } + + public function orders(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validate(['status' => ['nullable', 'string'], 'financial_status' => ['nullable', 'string'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:100']]); + $orders = Order::withoutGlobalScopes()->where('store_id', $storeId)->with('customer')->when($data['status'] ?? null, fn ($query, string $status) => $query->where('status', $status))->when($data['financial_status'] ?? null, fn ($query, string $status) => $query->where('financial_status', $status))->latest('placed_at')->paginate($data['per_page'] ?? 25); + + return $this->paginated($orders); + } + + public function showOrder(int $storeId, int $orderId): JsonResponse + { + $this->assertStore($storeId); + $order = Order::withoutGlobalScopes()->where('store_id', $storeId)->with(['customer', 'lines', 'payments', 'refunds', 'fulfillments.lines'])->findOrFail($orderId); + + return response()->json(['data' => $order->toArray()]); + } + + public function customers(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validate(['query' => ['nullable', 'string'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:100']]); + $customers = Customer::withoutGlobalScopes()->where('store_id', $storeId)->when($data['query'] ?? null, fn ($query, string $queryText) => $query->where(function ($nested) use ($queryText): void { + $nested->where('email', 'like', '%'.$queryText.'%')->orWhere('first_name', 'like', '%'.$queryText.'%')->orWhere('last_name', 'like', '%'.$queryText.'%'); + }))->latest()->paginate($data['per_page'] ?? 25); + + return $this->paginated($customers); + } + + public function discounts(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + + return $this->paginated(Discount::withoutGlobalScopes()->where('store_id', $storeId)->latest()->paginate($request->integer('per_page', 25))); + } + + public function storeDiscount(StoreDiscountRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $discount = Discount::withoutGlobalScopes()->create([...$data, 'store_id' => $storeId, 'status' => $data['status'] ?? 'active', 'usage_count' => 0]); + + return response()->json(['data' => $discount], 201); + } + + public function updateDiscount(UpdateDiscountRequest $request, int $storeId, int $discountId): JsonResponse + { + $this->assertStore($storeId); + $discount = Discount::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($discountId); + $discount->update($request->validated()); + + return response()->json(['data' => $discount->refresh()]); + } + + public function deleteDiscount(int $storeId, int $discountId): JsonResponse + { + $this->assertStore($storeId); + Discount::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($discountId)->delete(); + + return response()->json(['message' => 'Discount deleted.']); + } + + public function fulfillOrder(CreateFulfillmentRequest $request, int $storeId, int $orderId, FulfillmentService $fulfillments): JsonResponse + { + $this->assertStore($storeId); + $order = Order::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($orderId); + $data = $request->validated(); + $fulfillment = $fulfillments->create($order, $data['lines'], array_filter(['tracking_company' => $data['tracking_company'] ?? null, 'tracking_number' => $data['tracking_number'] ?? null, 'tracking_url' => $data['tracking_url'] ?? null])); + + return response()->json(['data' => $fulfillment->toArray()], 201); + } + + public function refundOrder(CreateRefundRequest $request, int $storeId, int $orderId, RefundService $refunds): JsonResponse + { + $this->assertStore($storeId); + $order = Order::withoutGlobalScopes()->where('store_id', $storeId)->with('payments')->findOrFail($orderId); + $data = $request->validated(); + $payment = $order->payments->firstWhere('id', $data['payment_id'] ?? null) ?? $order->payments->firstWhere('status', 'captured'); + abort_unless($payment !== null, 422, 'No captured payment is available.'); + $refund = $refunds->create($order, $payment, $data['lines'] ?? $data['amount'] ?? null, $data['reason'] ?? null, (bool) ($data['restock'] ?? false), $data['lines'] ?? []); + + return response()->json(['data' => $refund->toArray()], 201); + } + + public function shippingZones(int $storeId): JsonResponse + { + $this->assertStore($storeId); + + return response()->json(['data' => ShippingZone::withoutGlobalScopes()->where('store_id', $storeId)->with('rates')->get()]); + } + + public function storeShippingZone(StoreShippingZoneRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + + return response()->json(['data' => ShippingZone::withoutGlobalScopes()->create([...$data, 'store_id' => $storeId])], 201); + } + + public function updateShippingZone(UpdateShippingZoneRequest $request, int $storeId, int $zoneId): JsonResponse + { + $this->assertStore($storeId); + $zone = ShippingZone::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($zoneId); + $zone->update($request->validated()); + + return response()->json(['data' => $zone->refresh()]); + } + + public function storeShippingRate(StoreShippingRateRequest $request, int $storeId, int $zoneId): JsonResponse + { + $this->assertStore($storeId); + ShippingZone::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($zoneId); + $data = $request->validated(); + + $config = $data['config_json']; + $price = (int) ($data['price_amount'] ?? $config['price_amount'] ?? 0); + $currency = $data['currency'] ?? $config['currency'] ?? app('current_store')->default_currency; + + return response()->json(['data' => ShippingRate::create([...$data, 'shipping_zone_id' => $zoneId, 'price_amount' => $price, 'currency' => $currency, 'config_json' => $config, 'is_active' => $data['is_active'] ?? true])], 201); + } + + public function taxSettings(int $storeId): JsonResponse + { + $this->assertStore($storeId); + + return response()->json(['data' => TaxSettings::withoutGlobalScopes()->firstOrCreate(['store_id' => $storeId])]); + } + + public function updateTaxSettings(UpdateTaxSettingsRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $settings = TaxSettings::withoutGlobalScopes()->updateOrCreate(['store_id' => $storeId], [...$data, 'provider_config_json' => $data['config_json']]); + + return response()->json(['data' => $settings]); + } + + public function pages(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + + return $this->paginated(Page::withoutGlobalScopes()->where('store_id', $storeId)->latest()->paginate($request->integer('per_page', 25))); + } + + public function storePage(StorePageRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $page = Page::withoutGlobalScopes()->create([...$data, 'store_id' => $storeId, 'handle' => $data['handle'] ?? Str::slug($data['title']), 'published_at' => $data['status'] === 'published' ? now() : null]); + + return response()->json(['data' => $page], 201); + } + + public function updatePage(UpdatePageRequest $request, int $storeId, int $pageId): JsonResponse + { + $this->assertStore($storeId); + $page = Page::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($pageId); + $data = $request->validated(); + if (($data['status'] ?? null) === 'published') { + $data['published_at'] = $page->published_at ?? now(); + } + $page->update($data); + + return response()->json(['data' => $page->refresh()]); + } + + public function deletePage(int $storeId, int $pageId): JsonResponse + { + $this->assertStore($storeId); + Page::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($pageId)->delete(); + + return response()->json(['message' => 'Page deleted.']); + } + + public function storeTheme(StoreThemeRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + /** @var UploadedFile $file */ + $file = $request->file('file'); + $archive = new \ZipArchive; + abort_unless($archive->open($file->getRealPath()) === true, 422, 'The theme archive is invalid.'); + $manifest = []; + $paths = []; + + for ($index = 0; $index < $archive->numFiles; $index++) { + $path = $archive->getNameIndex($index); + abort_if($path === false || str_contains($path, '..') || str_starts_with($path, '/'), 422, 'The theme archive contains an invalid path.'); + if (! str_ends_with($path, '/')) { + $paths[] = $path; + } + if ($path === 'theme.json') { + $manifest = json_decode((string) $archive->getFromIndex($index), true) ?: []; + } + } + abort_if($paths === [], 422, 'The theme archive is empty.'); + abort_if($manifest === [] || ! is_string($manifest['name'] ?? null) || ! is_string($manifest['version'] ?? null), 422, 'The theme archive has an invalid manifest.'); + abort_if(! collect($paths)->contains(fn (string $path): bool => str_starts_with($path, 'templates/') || str_ends_with($path, '.blade.php')), 422, 'The theme archive is missing storefront templates.'); + $theme = Theme::withoutGlobalScopes()->create(['store_id' => $storeId, 'name' => $data['name'] ?? ($manifest['name'] ?? 'Uploaded theme'), 'version' => $manifest['version'] ?? '1.0.0', 'status' => 'draft']); + foreach ($paths as $path) { + $contents = $archive->getFromName($path); + $theme->files()->create(['path' => $path, 'storage_key' => 'themes/'.$theme->getKey().'/'.$path, 'sha256' => hash('sha256', (string) $contents), 'byte_size' => strlen((string) $contents), 'content' => $contents]); + } + $archive->close(); + $theme->settings()->create(['settings_json' => []]); + + return response()->json(['data' => $theme->load('settings')], 201); + } + + public function publishTheme(int $storeId, int $themeId): JsonResponse + { + $this->assertStore($storeId); + $theme = Theme::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($themeId); + Theme::withoutGlobalScopes()->where('store_id', $storeId)->update(['status' => 'draft']); + $theme->update(['status' => 'published', 'published_at' => now()]); + + return response()->json(['data' => $theme->refresh()]); + } + + public function updateThemeSettings(UpdateThemeSettingsRequest $request, int $storeId, int $themeId): JsonResponse + { + $this->assertStore($storeId); + $theme = Theme::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($themeId); + $theme->settings()->updateOrCreate(['theme_id' => $theme->getKey()], ['settings_json' => $request->validated()['settings_json']]); + + return response()->json(['data' => $theme->refresh()->load('settings')]); + } + + public function reindex(SearchService $search, int $storeId): JsonResponse + { + $this->assertStore($storeId); + Product::withoutGlobalScopes()->where('store_id', $storeId)->each(fn (Product $product) => $search->syncProduct($product)); + + return response()->json(['status' => 'completed']); + } + + public function searchStatus(int $storeId): JsonResponse + { + $this->assertStore($storeId); + + return response()->json(['status' => 'ready', 'product_count' => Product::withoutGlobalScopes()->where('store_id', $storeId)->count()]); + } + + public function analyticsSummary(Request $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validate(['from' => ['required', 'date_format:Y-m-d'], 'to' => ['required', 'date_format:Y-m-d', 'after_or_equal:from'], 'granularity' => ['sometimes', 'in:day,week,month']]); + $from = CarbonImmutable::createFromFormat('Y-m-d', $data['from'])->startOfDay(); + $to = CarbonImmutable::createFromFormat('Y-m-d', $data['to'])->endOfDay(); + abort_if($from->diffInDays($to) > 365, 422, 'The analytics range may not exceed 365 days.'); + $days = \App\Models\AnalyticsDaily::withoutGlobalScopes()->where('store_id', $storeId)->whereBetween('date', [$from->toDateString(), $to->toDateString()])->orderBy('date')->get(); + $orders = (int) $days->sum('orders_count'); + $revenue = (int) $days->sum('revenue_amount'); + $visits = (int) $days->sum('visits_count'); + $topProducts = DB::table('order_lines')->join('orders', 'orders.id', '=', 'order_lines.order_id')->where('orders.store_id', $storeId)->whereBetween('orders.placed_at', [$from, $to])->whereIn('orders.financial_status', ['paid', 'partially_refunded'])->select('order_lines.product_id', 'order_lines.product_title as title')->selectRaw('sum(order_lines.quantity) as units_sold')->selectRaw('sum(order_lines.line_total_amount) as revenue_amount')->groupBy('order_lines.product_id', 'order_lines.product_title')->orderByDesc('units_sold')->limit(10)->get(); + + return response()->json(['data' => ['period' => ['from' => $from->toDateString(), 'to' => $to->toDateString()], 'summary' => ['orders_count' => $orders, 'revenue_amount' => $revenue, 'aov_amount' => $orders > 0 ? intdiv($revenue, $orders) : 0, 'visits_count' => $visits, 'add_to_cart_count' => (int) $days->sum('add_to_cart_count'), 'checkout_started_count' => (int) $days->sum('checkout_started_count'), 'conversion_rate' => $visits > 0 ? round($orders / $visits, 4) : 0, 'currency' => app('current_store')->default_currency], 'daily' => $days, 'top_products' => $topProducts]]); + } + + public function createOrderExport(CreateOrderExportRequest $request, int $storeId): JsonResponse + { + $this->assertStore($storeId); + $data = $request->validated(); + $export = OrderExport::withoutGlobalScopes()->create(['store_id' => $storeId, 'format' => $data['format'] ?? 'csv', 'filters_json' => $data['filters'] ?? [], 'status' => 'queued']); + GenerateOrderExport::dispatch($export); + + return response()->json(['export_id' => $export->getKey(), 'status' => 'queued', 'created_at' => $export->created_at], 202); + } + + public function showOrderExport(int $storeId, int $exportId): JsonResponse + { + $this->assertStore($storeId); + $export = OrderExport::withoutGlobalScopes()->where('store_id', $storeId)->findOrFail($exportId); + + return response()->json(['data' => ['id' => $export->getKey(), 'status' => $export->status, 'format' => $export->format, 'row_count' => $export->row_count, 'download_url' => $export->download_url, 'download_expires_at' => $export->download_expires_at, 'created_at' => $export->created_at, 'completed_at' => $export->completed_at, 'error_message' => $export->error_message]]); + } + + private function assertStore(int $storeId): void + { + abort_unless((int) app('current_store')->getKey() === $storeId, 404); + } + + private function syncCollectionProducts(Collection $collection, array $productIds, int $storeId): void + { + $validIds = Product::withoutGlobalScopes()->where('store_id', $storeId)->whereIn('id', $productIds)->pluck('id')->all(); + $collection->products()->sync(array_fill_keys($validIds, ['position' => 0])); + } + + private function paginated(LengthAwarePaginator $paginator): JsonResponse + { + return response()->json(['data' => $paginator->items(), 'meta' => ['current_page' => $paginator->currentPage(), 'per_page' => $paginator->perPage(), 'total' => $paginator->total(), 'last_page' => $paginator->lastPage()]]); + } +} diff --git a/app/Http/Controllers/Api/PlatformController.php b/app/Http/Controllers/Api/PlatformController.php new file mode 100644 index 00000000..6833039d --- /dev/null +++ b/app/Http/Controllers/Api/PlatformController.php @@ -0,0 +1,153 @@ +assertPlatformAdministrator(); + $data = $request->validated(); + $slug = Str::slug($data['name']); + $suffix = 1; + while (Organization::query()->where('slug', $slug)->exists()) { + $slug = Str::slug($data['name']).'-'.$suffix++; + } + + return response()->json(['data' => Organization::create([...$data, 'slug' => $slug, 'status' => 'active'])], 201); + } + + public function storeStore(CreatePlatformStoreRequest $request): JsonResponse + { + $this->assertPlatformAdministrator(); + $data = $request->validated(); + $store = Store::create([...$data, 'status' => 'active']); + $store->users()->syncWithoutDetaching([ + request()->user('sanctum')->getKey() => ['role' => 'owner'], + ]); + + return response()->json(['data' => $store], 201); + } + + public function invite(StoreInvitationRequest $request, int $storeId): JsonResponse + { + $store = $this->store($storeId); + $data = $request->validated(); + $user = User::query()->where('email', $data['email'])->first(); + + if ($user !== null && $store->users()->whereKey($user->getKey())->exists()) { + return response()->json(['message' => 'The user is already a member of this store.'], 409); + } + + $invitation = StoreInvitation::query()->updateOrCreate( + ['store_id' => $store->getKey(), 'email' => $data['email']], + ['role' => $data['role'], 'invited_at' => now(), 'expires_at' => now()->addDays(7), 'accepted_at' => null], + ); + + return response()->json(['data' => ['email' => $invitation->email, 'role' => $invitation->role, 'invited_at' => $invitation->invited_at, 'expires_at' => $invitation->expires_at]], 201); + } + + public function me(int $storeId): JsonResponse + { + $store = $this->store($storeId); + $user = request()->user('sanctum'); + $membership = $user?->stores()->whereKey($store->getKey())->first(); + abort_unless($membership !== null, 403); + + return response()->json(['data' => [ + 'user_id' => $user->getKey(), + 'store_id' => $store->getKey(), + 'role' => $membership->pivot->role->value ?? $membership->pivot->role, + 'email' => $user->email, + 'name' => $user->name, + 'permissions' => $this->permissionsFor($membership->pivot->role->value ?? (string) $membership->pivot->role), + ]]); + } + + public function presignMediaUpload(PresignMediaUploadRequest $request, int $storeId, int $productId): JsonResponse + { + $store = $this->store($storeId); + $product = Product::withoutGlobalScopes()->where('store_id', $store->getKey())->findOrFail($productId); + $data = $request->validated(); + $extension = strtolower(pathinfo($data['filename'], PATHINFO_EXTENSION)); + $storageKey = 'stores/'.$store->getKey().'/products/'.$product->getKey().'/media/'.Str::uuid().'.'.$extension; + $disk = Storage::disk('public'); + $media = ProductMedia::query()->create([ + 'product_id' => $product->getKey(), + 'type' => str_starts_with($data['content_type'], 'video/') ? 'video' : 'image', + 'path' => $storageKey, + 'storage_key' => $storageKey, + 'url' => $disk->url($storageKey), + 'mime_type' => $data['content_type'], + 'byte_size' => $data['byte_size'], + 'status' => 'processing', + 'position' => (int) $product->media()->max('position') + 1, + ]); + + $uploadUrl = $disk->url($storageKey); + if (method_exists($disk, 'temporaryUploadUrl')) { + try { + $uploadUrl = $disk->temporaryUploadUrl($storageKey, now()->addMinutes(10), ['ContentType' => $data['content_type']]); + } catch (Throwable) { + // Local development disks do not support presigned uploads. + } + } + + if (config('queue.default') !== 'sync') { + ProcessMediaUpload::dispatch($media)->delay(now()->addMinutes(10)); + } + + return response()->json(['upload_url' => $uploadUrl, 'method' => 'PUT', 'headers' => ['Content-Type' => $data['content_type']], 'storage_key' => $storageKey, 'media_id' => $media->getKey(), 'expires_at' => now()->addMinutes(10)], 201); + } + + public function completeMediaUpload(int $storeId, int $productId, int $mediaId): JsonResponse + { + $store = $this->store($storeId); + $product = Product::withoutGlobalScopes()->where('store_id', $store->getKey())->findOrFail($productId); + $media = $product->media()->whereKey($mediaId)->firstOrFail(); + $disk = Storage::disk('public'); + $storageKey = $media->storage_key ?: $media->path; + + abort_unless($storageKey !== null && $disk->exists($storageKey), 409, 'The media upload has not completed.'); + ProcessMediaUpload::dispatch($media); + + return response()->json(['data' => $media->refresh()], 202); + } + + private function store(int $storeId): Store + { + return Store::query()->findOrFail($storeId); + } + + private function assertPlatformAdministrator(): void + { + abort_unless(request()->user('sanctum')?->isPlatformAdmin(), 403, 'Platform administrator access is required.'); + } + + /** @return array */ + private function permissionsFor(string $role): array + { + return match ($role) { + 'owner', 'admin' => ['read-products', 'write-products', 'read-orders', 'write-orders', 'read-settings', 'write-settings', 'read-customers', 'write-customers', 'read-analytics', 'read-content', 'write-content'], + 'staff' => ['read-products', 'write-products', 'read-orders', 'write-orders', 'read-settings', 'read-customers'], + default => ['read-products', 'read-orders', 'read-customers'], + }; + } +} diff --git a/app/Http/Controllers/Api/StorefrontAnalyticsController.php b/app/Http/Controllers/Api/StorefrontAnalyticsController.php new file mode 100644 index 00000000..470e34e6 --- /dev/null +++ b/app/Http/Controllers/Api/StorefrontAnalyticsController.php @@ -0,0 +1,24 @@ +validated()['events']; + $stored = []; + foreach ($events as $event) { + $stored[] = $this->analytics->track(app('current_store'), $event['type'], $event['properties'] ?? [], $event['session_id'] ?? ($request->hasSession() ? $request->session()->getId() : null), $request->user('customer')?->getKey(), $event['client_event_id'] ?? null, isset($event['occurred_at']) ? new \DateTimeImmutable($event['occurred_at']) : null); + } + + return response()->json(['accepted' => count($stored), 'rejected' => 0], 202); + } +} diff --git a/app/Http/Controllers/Api/StorefrontCartController.php b/app/Http/Controllers/Api/StorefrontCartController.php new file mode 100644 index 00000000..1a5c53bb --- /dev/null +++ b/app/Http/Controllers/Api/StorefrontCartController.php @@ -0,0 +1,109 @@ +validate(['currency' => ['nullable', 'string', 'size:3']]); + $cart = $this->carts->create(app('current_store'), $request->user('customer')); + + if (isset($data['currency'])) { + $cart->update(['currency' => strtoupper($data['currency'])]); + } + + $request->session()->put(['cart_id' => $cart->getKey(), 'cart_id_'.app('current_store')->getKey() => $cart->getKey()]); + + return response()->json($this->payload($cart->refresh()), 201); + } + + public function show(int $cartId): JsonResponse + { + return response()->json($this->payload($this->cart($cartId))); + } + + public function addLine(Request $request, int $cartId): JsonResponse + { + $data = $request->validate(['variant_id' => ['required', 'integer'], 'quantity' => ['required', 'integer', 'min:1', 'max:9999'], 'cart_version' => ['nullable', 'integer'], 'expected_version' => ['nullable', 'integer']]); + $cart = $this->cart($cartId); + + try { + $this->carts->assertVersion($cart, $data['cart_version'] ?? $data['expected_version'] ?? null); + $this->carts->addLine($cart, $data['variant_id'], $data['quantity']); + } catch (CartVersionConflictException $exception) { + return response()->json(['message' => $exception->getMessage(), 'cart' => $this->payload($cart->refresh())], 409); + } catch (InsufficientInventoryException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'insufficient_inventory'], 422); + } + + return response()->json($this->payload($this->cart($cartId)), 201); + } + + public function updateLine(Request $request, int $cartId, int $lineId): JsonResponse + { + $data = $request->validate(['quantity' => ['required', 'integer', 'min:1', 'max:9999'], 'cart_version' => ['required', 'integer']]); + $cart = $this->cart($cartId); + + try { + $this->carts->assertVersion($cart, $data['cart_version']); + $this->carts->updateLineQuantity($cart, $lineId, $data['quantity']); + } catch (CartVersionConflictException $exception) { + return response()->json(['message' => $exception->getMessage(), 'cart' => $this->payload($cart->refresh())], 409); + } catch (InsufficientInventoryException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'insufficient_inventory'], 422); + } + + return response()->json($this->payload($this->cart($cartId))); + } + + public function removeLine(Request $request, int $cartId, int $lineId): JsonResponse + { + $data = $request->validate(['cart_version' => ['required', 'integer']]); + $cart = $this->cart($cartId); + + try { + $this->carts->assertVersion($cart, $data['cart_version']); + $this->carts->removeLine($cart, $lineId); + } catch (CartVersionConflictException $exception) { + return response()->json(['message' => $exception->getMessage(), 'cart' => $this->payload($cart->refresh())], 409); + } + + return response()->json($this->payload($this->cart($cartId))); + } + + private function cart(int $cartId): Cart + { + $cart = Cart::query() + ->where('store_id', app('current_store')->getKey()) + ->where('status', 'active') + ->with(['lines.variant.product.media', 'lines.variant.inventory']) + ->findOrFail($cartId); + $customerId = request()->user('customer')?->getKey(); + + if ($customerId !== null) { + abort_unless((int) $cart->customer_id === (int) $customerId, 404); + } + + return $cart; + } + + /** @return array */ + private function payload(Cart $cart): array + { + $lines = $cart->lines->map(fn ($line): array => ['id' => $line->id, 'variant_id' => $line->variant_id, 'product_title' => $line->variant->product->title, 'variant_title' => $line->variant->title, 'sku' => $line->variant->sku, 'quantity' => $line->quantity, 'unit_price_amount' => $line->unit_price_amount, 'line_subtotal_amount' => $line->line_subtotal_amount, 'line_discount_amount' => $line->line_discount_amount, 'line_total_amount' => $line->line_total_amount, 'image_url' => $line->variant->product->media->first()?->url, 'requires_shipping' => $line->variant->requires_shipping, 'available_quantity' => $line->variant->inventory?->availableQuantity() ?? 0])->values()->all(); + $subtotal = (int) collect($lines)->sum('line_total_amount'); + + return ['id' => $cart->id, 'store_id' => $cart->store_id, 'customer_id' => $cart->customer_id, 'currency' => $cart->currency, 'cart_version' => $cart->cart_version, 'status' => $cart->status, 'lines' => $lines, 'totals' => ['subtotal' => $subtotal, 'discount' => 0, 'total' => $subtotal, 'currency' => $cart->currency, 'line_count' => count($lines), 'item_count' => (int) collect($lines)->sum('quantity')], 'created_at' => $cart->created_at, 'updated_at' => $cart->updated_at]; + } +} diff --git a/app/Http/Controllers/Api/StorefrontCheckoutController.php b/app/Http/Controllers/Api/StorefrontCheckoutController.php new file mode 100644 index 00000000..0514aa9f --- /dev/null +++ b/app/Http/Controllers/Api/StorefrontCheckoutController.php @@ -0,0 +1,173 @@ +validate(['cart_id' => ['required', 'integer'], 'email' => ['required', 'email']]); + $cart = Cart::query()->where('status', 'active')->with('lines')->findOrFail($data['cart_id']); + $customerId = $request->user('customer')?->getKey(); + if ($customerId !== null) { + abort_unless((int) $cart->customer_id === (int) $customerId, 404); + } else { + $sessionCartIds = array_filter([$request->session()->get('cart_id'), $request->session()->get('cart_id_'.app('current_store')->getKey())]); + abort_unless(in_array($cart->getKey(), $sessionCartIds, true), 404); + } + $checkout = $this->checkouts->create($cart, $data['email'], $request->user('customer')); + $this->pricing->calculate($checkout); + + return response()->json($this->payload($checkout->refresh()), 201); + } + + public function show(int $checkoutId): JsonResponse + { + $checkout = $this->checkout($checkoutId); + + if ($checkout->isExpired()) { + return response()->json(['message' => 'Checkout expired.'], 410); + } + + return response()->json($this->payload($checkout)); + } + + public function address(SetCheckoutAddressRequest $request, int $checkoutId): JsonResponse + { + $checkout = $this->checkout($checkoutId); + $useShippingAsBilling = $request->boolean('use_shipping_as_billing', true); + $data = $request->validated(); + try { + $checkout = $this->checkouts->setAddress($checkout, $data['shipping_address'] ?? [], $data['billing_address'] ?? null, $useShippingAsBilling); + } catch (\LogicException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'checkout_state_invalid'], 409); + } catch (PaymentDeclinedException $exception) { + return response()->json(['message' => $exception->getMessage(), 'error_code' => $exception->errorCode], 422); + } + + return response()->json($this->payload($checkout)); + } + + public function shippingMethod(Request $request, int $checkoutId): JsonResponse + { + $data = $request->validate(['shipping_method_id' => ['required', 'integer'], 'shipping_rate_id' => ['nullable', 'integer']]); + try { + $checkout = $this->checkouts->setShippingMethod($this->checkout($checkoutId), $data['shipping_rate_id'] ?? $data['shipping_method_id']); + } catch (\LogicException|\InvalidArgumentException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'checkout_state_invalid'], 422); + } + + return response()->json($this->payload($checkout)); + } + + public function applyDiscount(ApplyDiscountRequest $request, int $checkoutId): JsonResponse + { + $data = $request->validated(); + $checkout = $this->checkout($checkoutId); + try { + $discount = $this->discounts->validate($data['code'], app('current_store'), $checkout->cart); + } catch (InvalidDiscountException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => $exception->reason], 422); + } + $checkout->update(['discount_code' => $discount->code]); + $this->pricing->calculate($checkout->refresh()); + + return response()->json($this->payload($checkout->refresh())); + } + + public function removeDiscount(int $checkoutId): JsonResponse + { + $checkout = $this->checkout($checkoutId); + $checkout->update(['discount_code' => null]); + $this->pricing->calculate($checkout->refresh()); + + return response()->json($this->payload($checkout->refresh())); + } + + public function pay(Request $request, int $checkoutId): JsonResponse + { + $data = $request->validate([ + 'payment_method' => ['required', 'string', 'in:credit_card,paypal,bank_transfer'], + 'card_number' => ['exclude_unless:payment_method,credit_card', 'required', 'string', 'regex:/^(?=.*\d)[0-9 ]+$/'], + 'card_expiry' => ['exclude_unless:payment_method,credit_card', 'required', 'string', 'regex:/^(0[1-9]|1[0-2])\/\d{2}$/'], + 'card_cvc' => ['exclude_unless:payment_method,credit_card', 'required', 'string', 'regex:/^\d{3,4}$/'], + 'card_holder' => ['exclude_unless:payment_method,credit_card', 'required', 'string', 'max:255'], + ]); + try { + $checkout = $this->checkouts->selectPaymentMethod($this->checkout($checkoutId), $data['payment_method']); + $order = $this->payments->pay($checkout, PaymentMethod::from($data['payment_method']), $data); + } catch (InsufficientInventoryException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'insufficient_inventory'], 422); + } catch (PaymentDeclinedException $exception) { + return response()->json(['message' => $exception->getMessage(), 'error_code' => $exception->errorCode], 422); + } catch (\LogicException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'checkout_state_invalid'], 422); + } + + $order = $order->load('checkout'); + $payload = ['checkout_id' => $order->checkout_id, 'status' => 'completed', 'order' => ['id' => $order->id, 'order_number' => $order->order_number, 'status' => $order->status, 'financial_status' => $order->financial_status, 'payment_method' => $order->payment_method, 'total_amount' => $order->total_amount, 'currency' => $order->currency]]; + + if ($order->financial_status->value === 'pending') { + $payload['bank_transfer_instructions'] = ['bank_name' => 'Mock Bank AG', 'iban' => 'DE89 3704 0044 0532 0130 00', 'bic' => 'COBADEFFXXX', 'reference' => $order->order_number, 'amount_formatted' => number_format($order->total_amount / 100, 2, '.', '').' '.$order->currency]; + } + + return response()->json($payload); + } + + public function paymentMethod(Request $request, int $checkoutId): JsonResponse + { + $data = $request->validate(['payment_method' => ['required', 'in:credit_card,paypal,bank_transfer']]); + try { + $checkout = $this->checkouts->selectPaymentMethod($this->checkout($checkoutId), $data['payment_method']); + } catch (InsufficientInventoryException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'insufficient_inventory'], 422); + } catch (\LogicException $exception) { + return response()->json(['message' => $exception->getMessage(), 'code' => 'checkout_state_invalid'], 422); + } + + return response()->json($this->payload($checkout)); + } + + private function checkout(int $checkoutId): Checkout + { + $checkout = Checkout::query()->with(['cart.lines.variant.product', 'shippingRate'])->findOrFail($checkoutId); + $customerId = request()->user('customer')?->getKey(); + + if ($customerId !== null) { + abort_unless((int) $checkout->customer_id === (int) $customerId, 404); + } else { + $sessionCartIds = array_filter([request()->session()->get('cart_id'), request()->session()->get('cart_id_'.app('current_store')->getKey())]); + abort_unless(in_array($checkout->cart_id, $sessionCartIds, true), 404); + } + + return $checkout; + } + + /** @return array */ + private function payload(Checkout $checkout): array + { + $totals = $checkout->totals_json ?? $this->pricing->calculate($checkout)->toArray(); + $rates = $checkout->shipping_address_json === null ? collect() : $this->shipping->getAvailableRates(app('current_store'), $checkout->shipping_address_json); + + return ['id' => $checkout->id, 'store_id' => $checkout->store_id, 'cart_id' => $checkout->cart_id, 'customer_id' => $checkout->customer_id, 'status' => $checkout->status, 'email' => $checkout->email, 'payment_method' => $checkout->payment_method, 'shipping_address_json' => $checkout->shipping_address_json, 'billing_address_json' => $checkout->billing_address_json, 'shipping_method_id' => $checkout->shipping_rate_id, 'discount_code' => $checkout->discount_code, 'lines' => $checkout->cart->lines->map(fn ($line): array => ['variant_id' => $line->variant_id, 'product_title' => $line->variant->product->title, 'variant_title' => $line->variant->title, 'sku' => $line->variant->sku, 'quantity' => $line->quantity, 'unit_price_amount' => $line->unit_price_amount, 'line_total_amount' => $line->line_total_amount])->all(), 'totals' => $totals, 'available_shipping_methods' => $rates->map(fn ($rate): array => ['id' => $rate->id, 'name' => $rate->name, 'type' => $rate->type, 'price_amount' => $rate->price_amount, 'currency' => $rate->currency, 'estimated_days_min' => $rate->estimated_days_min, 'estimated_days_max' => $rate->estimated_days_max])->all(), 'expires_at' => $checkout->expires_at, 'created_at' => $checkout->created_at]; + } +} diff --git a/app/Http/Controllers/Api/StorefrontOrderController.php b/app/Http/Controllers/Api/StorefrontOrderController.php new file mode 100644 index 00000000..242cf759 --- /dev/null +++ b/app/Http/Controllers/Api/StorefrontOrderController.php @@ -0,0 +1,22 @@ +with(['lines', 'payments', 'fulfillments.lines'])->where('order_number', $orderNumber)->firstOrFail(); + $customerId = $request->user('customer')?->getKey(); + $token = (string) $request->query('token', ''); + $expected = hash_hmac('sha256', $order->order_number, (string) config('app.key')); + abort_unless(($customerId !== null && (int) $order->customer_id === (int) $customerId) || ($token !== '' && hash_equals($expected, $token)), 401, 'A valid order access token is required.'); + + return response()->json(['order_number' => $order->order_number, 'status' => $order->status, 'financial_status' => $order->financial_status, 'fulfillment_status' => $order->fulfillment_status, 'email' => $order->email, 'currency' => $order->currency, 'placed_at' => $order->placed_at, 'lines' => $order->lines->map(fn ($line): array => ['title_snapshot' => $line->title_snapshot, 'variant_title' => $line->variant_title, 'sku_snapshot' => $line->sku_snapshot, 'quantity' => $line->quantity, 'unit_price_amount' => $line->unit_price_amount, 'total_amount' => $line->line_total_amount])->all(), 'totals' => ['subtotal_amount' => $order->subtotal_amount, 'discount_amount' => $order->discount_amount, 'shipping_amount' => $order->shipping_amount, 'tax_amount' => $order->tax_amount, 'total_amount' => $order->total_amount], 'shipping_address' => $order->shipping_address_json, 'billing_address' => $order->billing_address_json, 'fulfillments' => $order->fulfillments->map(fn ($fulfillment): array => ['id' => $fulfillment->id, 'status' => $fulfillment->status, 'tracking_company' => $fulfillment->tracking_company, 'tracking_number' => $fulfillment->tracking_number, 'tracking_url' => $fulfillment->tracking_url])->all()]); + } +} diff --git a/app/Http/Controllers/Api/StorefrontSearchController.php b/app/Http/Controllers/Api/StorefrontSearchController.php new file mode 100644 index 00000000..90e3ec5c --- /dev/null +++ b/app/Http/Controllers/Api/StorefrontSearchController.php @@ -0,0 +1,66 @@ +validate([ + 'q' => ['required', 'string', 'min:1', 'max:200'], + 'filters' => ['nullable', 'json'], + 'sort' => ['nullable', 'in:relevance,price_asc,price_desc,newest,best_selling'], + 'page' => ['nullable', 'integer', 'min:1'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:50'], + ]); + $filters = ($data['filters'] ?? null) === null ? [] : json_decode($data['filters'], true, 512, JSON_THROW_ON_ERROR); + abort_unless(is_array($filters) && ($filters === [] || ! array_is_list($filters)), 422, 'The filters parameter must be a JSON object.'); + $results = $this->search->search(app('current_store'), $data['q'], $filters, $data['per_page'] ?? 24, $data['page'] ?? 1, $data['sort'] ?? 'relevance'); + $items = collect($results->items()); + $prices = $items->map(fn ($product): int => (int) ($product->defaultVariant()?->price_amount ?? 0))->filter(); + $vendors = $items->pluck('vendor')->filter()->countBy()->map(fn (int $count, string $value): array => ['value' => $value, 'count' => $count])->values(); + $tags = $items->flatMap(fn ($product): array => $product->tags ?? [])->countBy()->map(fn (int $count, string $value): array => ['value' => $value, 'count' => $count])->values(); + + return response()->json([ + 'query' => $data['q'], + 'results' => $items->map(fn ($product): array => [ + 'id' => $product->id, + 'title' => $product->title, + 'handle' => $product->handle, + 'vendor' => $product->vendor, + 'product_type' => $product->product_type, + 'price_amount' => $product->defaultVariant()?->price_amount, + 'compare_at_amount' => $product->defaultVariant()?->compare_at_amount, + 'currency' => $product->defaultVariant()?->currency, + 'image_url' => $product->media->first()?->url, + 'in_stock' => $product->variants->contains(fn ($variant): bool => $variant->availableQuantity() > 0 || $variant->inventory?->policy?->value === 'continue'), + 'tags' => $product->tags ?? [], + ])->values()->all(), + 'facets' => ['vendors' => $vendors, 'tags' => $tags, 'price_range' => ['min' => $prices->min(), 'max' => $prices->max()]], + 'pagination' => ['current_page' => $results->currentPage(), 'per_page' => $results->perPage(), 'total' => $results->total(), 'last_page' => $results->lastPage()], + ]); + } + + public function suggest(Request $request): JsonResponse + { + $data = $request->validate(['q' => ['required', 'string', 'min:1', 'max:100'], 'limit' => ['nullable', 'integer', 'min:1', 'max:10']]); + $store = app('current_store'); + $limit = $data['limit'] ?? 5; + $products = $this->search->autocomplete($store, $data['q'], $limit); + $remaining = max(0, $limit - $products->count()); + $collections = $remaining === 0 ? collect() : Collection::query()->where('status', 'active')->where('title', 'like', trim($data['q']).'%')->with('products.media')->orderBy('title')->limit($remaining)->get(); + + return response()->json(['query' => $data['q'], 'suggestions' => [ + ...$products->map(fn ($product): array => ['type' => 'product', 'title' => $product->title, 'handle' => $product->handle, 'image_url' => $product->media->first()?->url, 'price_amount' => $product->defaultVariant()?->price_amount, 'currency' => $product->defaultVariant()?->currency])->all(), + ...$collections->map(fn (Collection $collection): array => ['type' => 'collection', 'title' => $collection->title, 'handle' => $collection->handle, 'image_url' => $collection->image_url])->all(), + ]]); + } +} diff --git a/app/Http/Middleware/EnsureApiAbility.php b/app/Http/Middleware/EnsureApiAbility.php new file mode 100644 index 00000000..ae10d8d9 --- /dev/null +++ b/app/Http/Middleware/EnsureApiAbility.php @@ -0,0 +1,73 @@ +user('sanctum'); + + abort_unless($request->bearerToken() !== null && $user !== null, 401, 'A Sanctum bearer token is required.'); + + $ability = $this->abilityFor($request, $user); + + abort_unless($ability !== null && $user->tokenCan($ability), 403, 'This token does not have the required ability.'); + + return $next($request); + } + + private function abilityFor(Request $request, User $user): ?string + { + $path = $request->path(); + $method = $request->method(); + + if (Str::contains($path, '/platform/')) { + abort_unless($user->isPlatformAdmin(), 403, 'Platform administration is restricted to platform administrators.'); + + return 'manage-platform'; + } + + if (Str::endsWith($path, '/invites')) { + return 'manage-platform'; + } + + if (Str::contains($path, '/exports/')) { + return 'read-orders'; + } + + foreach (['products' => 'products', 'collections' => 'collections', 'orders' => 'orders', 'customers' => 'customers', 'discounts' => 'discounts'] as $segment => $resource) { + if (Str::contains($path, '/'.$segment)) { + return in_array($method, ['GET', 'HEAD'], true) ? 'read-'.$resource : 'write-'.$resource; + } + } + + if (Str::contains($path, '/themes')) { + return in_array($method, ['GET', 'HEAD'], true) ? 'read-themes' : 'write-themes'; + } + + if (Str::contains($path, '/pages')) { + return in_array($method, ['GET', 'HEAD'], true) ? 'read-content' : 'write-content'; + } + + if (Str::contains($path, '/shipping') || Str::contains($path, '/tax/')) { + return in_array($method, ['GET', 'HEAD'], true) ? 'read-settings' : 'write-settings'; + } + + if (Str::contains($path, '/analytics')) { + return 'read-analytics'; + } + + if (Str::contains($path, '/search')) { + return in_array($method, ['GET', 'HEAD'], true) ? 'read-products' : 'write-products'; + } + + return null; + } +} diff --git a/app/Http/Middleware/EnsureStoreRole.php b/app/Http/Middleware/EnsureStoreRole.php new file mode 100644 index 00000000..5180c142 --- /dev/null +++ b/app/Http/Middleware/EnsureStoreRole.php @@ -0,0 +1,22 @@ +user()?->roleForStore($store); + $allowedRoles = array_map(fn (string $value): StoreUserRole => StoreUserRole::from($value), $roles); + + abort_unless($role !== null && in_array($role, $allowedRoles, true), 403); + + return $next($request); + } +} diff --git a/app/Http/Middleware/ResolveStore.php b/app/Http/Middleware/ResolveStore.php new file mode 100644 index 00000000..8d421ce3 --- /dev/null +++ b/app/Http/Middleware/ResolveStore.php @@ -0,0 +1,137 @@ +isPublicAdminAuthRequest($request)) { + return $next($request); + } + + if ($this->isAdminRequest($request) && $request->user('web') === null && $request->user('sanctum') === null) { + return $next($request); + } + + if ($this->isAdminApiRequest($request) && $request->user('sanctum') === null) { + return $next($request); + } + + $context = $context === 'storefront' && $this->isAdminRequest($request) + ? 'admin' + : $context; + + $store = $context === 'admin' + ? $this->resolveAdminStore($request) + : $this->resolveStorefrontStore($request); + + if ($store === null && $context === 'storefront' && $this->isPublicCustomerAuthRequest($request) && Store::query()->doesntExist()) { + return $next($request); + } + + abort_unless($store instanceof Store, $context === 'admin' ? 403 : 404); + + if ($store->status === StoreStatus::Suspended) { + if ($context === 'storefront') { + abort(503, 'This store is currently unavailable.'); + } + + if (! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true)) { + abort(403); + } + } + + $binding = (string) config('tenancy.binding', 'current_store'); + app()->instance($binding, $store); + View::share((string) config('tenancy.view_share', 'currentStore'), $store); + + return $next($request); + } + + private function resolveStorefrontStore(Request $request): ?Store + { + $hostname = Str::lower(rtrim(trim($request->getHost()), '.')); + $cacheKey = config('tenancy.cache_prefix', 'store-domains').':'.$hostname; + + $storeId = Cache::remember( + $cacheKey, + (int) config('tenancy.store_cache_ttl', 300), + fn (): ?int => StoreDomain::query() + ->where('hostname', $hostname) + ->where('type', config('tenancy.storefront_domain_type', StoreDomainType::Storefront->value)) + ->value('store_id'), + ); + + return $storeId === null ? null : Store::query()->find($storeId); + } + + private function resolveAdminStore(Request $request): ?Store + { + $isApiRequest = $this->isAdminApiRequest($request); + $storeId = $isApiRequest + ? $request->route('storeId') + : $request->session()->get(config('tenancy.admin_session_key', 'current_store_id')); + $user = $isApiRequest + ? $request->user('sanctum') + : ($request->user('web') ?? $request->user()); + + if ($storeId === null || $user === null) { + return null; + } + + return $user->stores()->whereKey($storeId)->first(); + } + + private function isAdminRequest(Request $request): bool + { + if ($this->isAdminApiRequest($request)) { + return true; + } + + $prefix = trim((string) config('tenancy.admin_path_prefix', 'admin'), '/'); + + if ($request->is($prefix, $prefix.'/*') || $request->routeIs($prefix.'.*')) { + return true; + } + + return $request->is('livewire/update', 'livewire-*/update') && str_contains((string) $request->headers->get('referer'), '/admin'); + } + + private function isAdminApiRequest(Request $request): bool + { + $prefix = trim((string) config('tenancy.admin_path_prefix', 'admin'), '/'); + + return $request->is('api/'.$prefix, 'api/'.$prefix.'/*'); + } + + private function isPublicCustomerAuthRequest(Request $request): bool + { + return $request->is('forgot-password', 'reset-password/*'); + } + + private function isPublicAdminAuthRequest(Request $request): bool + { + $path = $request->is('livewire/update', 'livewire-*/update') + ? trim((string) parse_url((string) $request->headers->get('referer'), PHP_URL_PATH), '/') + : trim($request->path(), '/'); + + return Str::is(['admin/login', 'admin/forgot-password', 'admin/reset-password/*'], $path); + } +} diff --git a/app/Http/Requests/ApplyDiscountRequest.php b/app/Http/Requests/ApplyDiscountRequest.php new file mode 100644 index 00000000..cb534214 --- /dev/null +++ b/app/Http/Requests/ApplyDiscountRequest.php @@ -0,0 +1,26 @@ +|string> + */ + public function rules(): array + { + return ['code' => ['required', 'string', 'max:64']]; + } +} diff --git a/app/Http/Requests/CreateFulfillmentRequest.php b/app/Http/Requests/CreateFulfillmentRequest.php new file mode 100644 index 00000000..ab2f6ef5 --- /dev/null +++ b/app/Http/Requests/CreateFulfillmentRequest.php @@ -0,0 +1,39 @@ +where('store_id', app('current_store')->getKey()) + ->find($this->route('orderId')); + + return $order instanceof Order && Gate::allows('createFulfillment', $order); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'lines' => ['required', 'array', 'min:1'], + 'lines.*.order_line_id' => ['required', 'integer'], + 'lines.*.quantity' => ['required', 'integer', 'min:1'], + 'tracking_company' => ['nullable', 'string', 'max:100'], + 'tracking_number' => ['nullable', 'string', 'max:255'], + 'tracking_url' => ['nullable', 'url'], + ]; + } +} diff --git a/app/Http/Requests/CreateOrderExportRequest.php b/app/Http/Requests/CreateOrderExportRequest.php new file mode 100644 index 00000000..523256ec --- /dev/null +++ b/app/Http/Requests/CreateOrderExportRequest.php @@ -0,0 +1,33 @@ +|string> + */ + public function rules(): array + { + return [ + 'format' => ['sometimes', 'in:csv'], + 'filters' => ['nullable', 'array'], + 'filters.status' => ['nullable', 'string'], + 'filters.financial_status' => ['nullable', 'string'], + 'filters.created_after' => ['nullable', 'date'], + 'filters.created_before' => ['nullable', 'date', 'after_or_equal:filters.created_after'], + ]; + } +} diff --git a/app/Http/Requests/CreateOrganizationRequest.php b/app/Http/Requests/CreateOrganizationRequest.php new file mode 100644 index 00000000..21fe7f81 --- /dev/null +++ b/app/Http/Requests/CreateOrganizationRequest.php @@ -0,0 +1,29 @@ +user('sanctum')?->tokenCan('manage-platform'); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'billing_email' => ['required', 'email', 'max:255'], + ]; + } +} diff --git a/app/Http/Requests/CreatePlatformStoreRequest.php b/app/Http/Requests/CreatePlatformStoreRequest.php new file mode 100644 index 00000000..f95dd4eb --- /dev/null +++ b/app/Http/Requests/CreatePlatformStoreRequest.php @@ -0,0 +1,34 @@ +user('sanctum')?->tokenCan('manage-platform'); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'organization_id' => ['required', 'integer', 'exists:organizations,id'], + 'name' => ['required', 'string', 'max:255'], + 'handle' => ['required', 'string', 'lowercase', 'max:63', 'regex:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/', Rule::unique('stores', 'handle')], + 'default_currency' => ['required', 'string', 'size:3', 'alpha', 'uppercase'], + 'default_locale' => ['required', 'string', 'max:10', 'regex:/^[a-z]{2}(?:-[A-Z]{2})?$/'], + 'timezone' => ['required', 'timezone'], + ]; + } +} diff --git a/app/Http/Requests/CreateRefundRequest.php b/app/Http/Requests/CreateRefundRequest.php new file mode 100644 index 00000000..7f9037a1 --- /dev/null +++ b/app/Http/Requests/CreateRefundRequest.php @@ -0,0 +1,40 @@ +where('store_id', app('current_store')->getKey()) + ->find($this->route('orderId')); + + return $order instanceof Order && Gate::allows('createRefund', $order); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'payment_id' => ['nullable', 'integer'], + 'amount' => ['nullable', 'integer', 'min:1'], + 'lines' => ['nullable', 'array'], + 'lines.*.order_line_id' => ['required_with:lines', 'integer'], + 'lines.*.quantity' => ['required_with:lines', 'integer', 'min:1'], + 'reason' => ['nullable', 'string', 'max:500'], + 'restock' => ['nullable', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/InviteStaffRequest.php b/app/Http/Requests/InviteStaffRequest.php new file mode 100644 index 00000000..22a8810c --- /dev/null +++ b/app/Http/Requests/InviteStaffRequest.php @@ -0,0 +1,30 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'email'], + 'role' => ['required', 'in:admin,staff,support'], + ]; + } +} diff --git a/app/Http/Requests/LoginRequest.php b/app/Http/Requests/LoginRequest.php new file mode 100644 index 00000000..2cb0f09b --- /dev/null +++ b/app/Http/Requests/LoginRequest.php @@ -0,0 +1,29 @@ +|string> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'email'], + 'password' => ['required', 'string'], + ]; + } +} diff --git a/app/Http/Requests/PresignMediaUploadRequest.php b/app/Http/Requests/PresignMediaUploadRequest.php new file mode 100644 index 00000000..4f7140dd --- /dev/null +++ b/app/Http/Requests/PresignMediaUploadRequest.php @@ -0,0 +1,33 @@ +user('sanctum')?->tokenCan('write-products'); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + $contentType = (string) $this->input('content_type'); + $maxBytes = $contentType === 'video/mp4' ? 500 * 1024 * 1024 : 50 * 1024 * 1024; + + return [ + 'filename' => ['required', 'string', 'max:255', 'regex:/\.[a-z0-9]{2,5}$/i'], + 'content_type' => ['required', 'in:image/jpeg,image/png,image/webp,image/avif,video/mp4'], + 'byte_size' => ['required', 'integer', 'min:1', 'max:'.$maxBytes], + ]; + } +} diff --git a/app/Http/Requests/RegisterCustomerRequest.php b/app/Http/Requests/RegisterCustomerRequest.php new file mode 100644 index 00000000..2fa2d4b7 --- /dev/null +++ b/app/Http/Requests/RegisterCustomerRequest.php @@ -0,0 +1,30 @@ +|string> + */ + public function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'email'], + 'password' => ['required', 'string', 'min:8', 'confirmed'], + ]; + } +} diff --git a/app/Http/Requests/SetCheckoutAddressRequest.php b/app/Http/Requests/SetCheckoutAddressRequest.php new file mode 100644 index 00000000..104ae74f --- /dev/null +++ b/app/Http/Requests/SetCheckoutAddressRequest.php @@ -0,0 +1,76 @@ +|string> + */ + public function rules(): array + { + $requiresShipping = $this->checkoutRequiresShipping(); + $useShippingAsBilling = $this->boolean('use_shipping_as_billing', true); + $rules = [ + 'use_shipping_as_billing' => ['sometimes', 'boolean'], + ...$this->addressRules('shipping_address', $requiresShipping), + ]; + + if (! $useShippingAsBilling) { + $rules = [...$rules, ...$this->addressRules('billing_address', true)]; + } + + return $rules; + } + + /** + * @return array> + */ + private function addressRules(string $key, bool $required): array + { + $presence = $required ? 'required' : 'sometimes'; + $root = $required ? 'required' : 'nullable'; + + return [ + $key => [$root, 'array'], + "{$key}.first_name" => [$presence, 'string', 'max:255'], + "{$key}.last_name" => [$presence, 'string', 'max:255'], + "{$key}.address1" => [$presence, 'string', 'max:500'], + "{$key}.address2" => ['sometimes', 'nullable', 'string', 'max:500'], + "{$key}.company" => ['sometimes', 'nullable', 'string', 'max:255'], + "{$key}.city" => [$presence, 'string', 'max:255'], + "{$key}.province" => ['sometimes', 'nullable', 'string', 'max:255'], + "{$key}.province_code" => ['sometimes', 'nullable', 'string', 'max:10'], + "{$key}.country" => [$presence, 'string', 'max:255'], + "{$key}.country_code" => [$presence, 'string', 'regex:/^[A-Z]{2}$/'], + "{$key}.postal_code" => [$presence, 'string', 'max:20'], + "{$key}.phone" => ['sometimes', 'nullable', 'string', 'max:50'], + ]; + } + + private function checkoutRequiresShipping(): bool + { + $checkoutId = $this->route('checkoutId'); + + if (! is_numeric($checkoutId)) { + return true; + } + + $checkout = Checkout::query()->with('cart.lines.variant')->find((int) $checkoutId); + + return $checkout?->cart?->lines?->contains(fn ($line): bool => (bool) $line->variant?->requires_shipping) ?? true; + } +} diff --git a/app/Http/Requests/StoreAnalyticsEventsRequest.php b/app/Http/Requests/StoreAnalyticsEventsRequest.php new file mode 100644 index 00000000..525585f5 --- /dev/null +++ b/app/Http/Requests/StoreAnalyticsEventsRequest.php @@ -0,0 +1,63 @@ +|string> + */ + public function rules(): array + { + return [ + 'events' => ['required', 'array', 'min:1', 'max:50'], + 'events.*.type' => ['required', 'in:page_view,product_view,add_to_cart,remove_from_cart,checkout_started,checkout_completed,search'], + 'events.*.session_id' => ['required', 'string', 'max:100'], + 'events.*.client_event_id' => ['required', 'string', 'max:100'], + 'events.*.properties' => ['nullable', 'array'], + 'events.*.occurred_at' => ['required', 'date'], + ]; + } + + protected function withValidator(Validator $validator): void + { + $validator->after(function (Validator $validator): void { + foreach ($this->input('events', []) as $index => $event) { + try { + $occurredAt = new \DateTimeImmutable((string) ($event['occurred_at'] ?? '')); + if (abs(now()->getTimestamp() - $occurredAt->getTimestamp()) > 3600) { + $validator->errors()->add("events.$index.occurred_at", 'The event timestamp must be within one hour of the current time.'); + } + } catch (\Throwable) { + // The date rule reports malformed timestamps. + } + + if ($this->jsonDepth($event['properties'] ?? []) > 3) { + $validator->errors()->add("events.$index.properties", 'Event properties may not be deeper than three levels.'); + } + } + }); + } + + private function jsonDepth(mixed $value): int + { + if (! is_array($value) || $value === []) { + return 1; + } + + return 1 + max(array_map(fn (mixed $item): int => $this->jsonDepth($item), $value)); + } +} diff --git a/app/Http/Requests/StoreCollectionRequest.php b/app/Http/Requests/StoreCollectionRequest.php new file mode 100644 index 00000000..a13034d1 --- /dev/null +++ b/app/Http/Requests/StoreCollectionRequest.php @@ -0,0 +1,36 @@ +|string> + */ + public function rules(): array + { + return [ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['nullable', 'string', 'max:255'], + 'description_html' => ['nullable', 'string'], + 'type' => ['required', 'in:manual,automated'], + 'rules_json' => ['required_if:type,automated', 'nullable', 'array'], + 'status' => ['nullable', 'in:active,draft,archived'], + 'product_ids' => ['nullable', 'array'], + ]; + } +} diff --git a/app/Http/Requests/StoreDiscountRequest.php b/app/Http/Requests/StoreDiscountRequest.php new file mode 100644 index 00000000..dc0d4ccc --- /dev/null +++ b/app/Http/Requests/StoreDiscountRequest.php @@ -0,0 +1,45 @@ +|string> + */ + public function rules(): array + { + return [ + 'type' => ['required', 'in:code,automatic'], + 'code' => ['required_if:type,code', 'nullable', 'string', 'max:50'], + 'value_type' => ['required', 'in:fixed,percent,free_shipping'], + 'value_amount' => ['required_unless:value_type,free_shipping', 'integer', 'min:0'], + 'minimum_order_amount' => ['nullable', 'integer', 'min:0'], + 'usage_limit' => ['nullable', 'integer', 'min:1'], + 'starts_at' => ['nullable', 'date'], + 'ends_at' => ['nullable', 'date', 'after:starts_at'], + 'rules_json' => ['nullable', 'array'], + 'status' => ['nullable', 'in:active,inactive'], + ]; + } + + protected function withValidator(Validator $validator): void + { + $validator->sometimes('value_amount', ['max:100'], fn (): bool => $this->input('value_type') === 'percent'); + } +} diff --git a/app/Http/Requests/StoreInvitationRequest.php b/app/Http/Requests/StoreInvitationRequest.php new file mode 100644 index 00000000..1fb1d202 --- /dev/null +++ b/app/Http/Requests/StoreInvitationRequest.php @@ -0,0 +1,29 @@ +user('sanctum')?->tokenCan('manage-platform'); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'email', 'max:255'], + 'role' => ['required', 'in:admin,staff,support'], + ]; + } +} diff --git a/app/Http/Requests/StorePageRequest.php b/app/Http/Requests/StorePageRequest.php new file mode 100644 index 00000000..f6280ba6 --- /dev/null +++ b/app/Http/Requests/StorePageRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('create', \App\Models\Page::class); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['title' => ['required', 'string', 'max:255'], 'handle' => ['nullable', 'string', 'max:255'], 'body_html' => ['nullable', 'string'], 'status' => ['required', 'in:draft,published']]; + } +} diff --git a/app/Http/Requests/StoreProductRequest.php b/app/Http/Requests/StoreProductRequest.php new file mode 100644 index 00000000..70b81f3c --- /dev/null +++ b/app/Http/Requests/StoreProductRequest.php @@ -0,0 +1,67 @@ +|string> + */ + public function rules(): array + { + return [ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['nullable', 'string', 'max:255'], + 'description_html' => ['nullable', 'string'], + 'description' => ['nullable', 'string'], + 'status' => ['sometimes', 'in:active,draft,archived'], + 'vendor' => ['nullable', 'string', 'max:255'], + 'product_type' => ['nullable', 'string', 'max:255'], + 'tags' => ['nullable', 'array', 'max:50'], + 'tags.*' => ['string', 'max:255'], + 'options' => ['nullable', 'array', 'max:3'], + 'options.*.name' => ['required', 'string', 'max:255'], + 'options.*.position' => ['required', 'integer', 'between:1,3'], + 'options.*.values' => ['nullable', 'array'], + 'options.*.values.*.value' => ['required', 'string', 'max:255'], + 'options.*.values.*.position' => ['nullable', 'integer', 'min:1'], + 'variants' => ['required', 'array', 'min:1', 'max:100'], + 'variants.*.sku' => ['required', 'string', 'max:255'], + 'variants.*.barcode' => ['nullable', 'string', 'max:255'], + 'variants.*.title' => ['nullable', 'string', 'max:255'], + 'variants.*.price_amount' => ['required', 'integer', 'min:0'], + 'variants.*.compare_at_amount' => ['nullable', 'integer', 'min:0'], + 'variants.*.currency' => ['nullable', 'string', 'size:3', 'uppercase'], + 'variants.*.weight_g' => ['nullable', 'integer', 'min:0'], + 'variants.*.requires_shipping' => ['nullable', 'boolean'], + 'variants.*.is_default' => ['nullable', 'boolean'], + 'variants.*.position' => ['nullable', 'integer', 'min:1'], + 'variants.*.status' => ['nullable', 'in:active,archived'], + 'variants.*.option_values' => ['nullable', 'array'], + 'variants.*.option_values.*.option_name' => ['required', 'string', 'max:255'], + 'variants.*.option_values.*.value' => ['required', 'string', 'max:255'], + 'variants.*.inventory.quantity_on_hand' => ['nullable', 'integer', 'min:0'], + 'variants.*.inventory.policy' => ['nullable', 'in:deny,continue'], + 'collections' => ['nullable', 'array'], + 'collections.*' => [ + 'integer', + Rule::exists('collections', 'id')->where(fn ($query) => $query->where('store_id', app('current_store')->getKey())), + ], + ]; + } +} diff --git a/app/Http/Requests/StoreShippingRateRequest.php b/app/Http/Requests/StoreShippingRateRequest.php new file mode 100644 index 00000000..7fd12673 --- /dev/null +++ b/app/Http/Requests/StoreShippingRateRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['name' => ['required', 'string', 'max:255'], 'type' => ['required', 'in:flat,weight,price,carrier'], 'price_amount' => ['nullable', 'integer', 'min:0'], 'currency' => ['nullable', 'size:3', 'uppercase'], 'config_json' => ['required', 'array'], 'is_active' => ['nullable', 'boolean'], 'estimated_days_min' => ['nullable', 'integer', 'min:0'], 'estimated_days_max' => ['nullable', 'integer', 'min:0']]; + } +} diff --git a/app/Http/Requests/StoreShippingZoneRequest.php b/app/Http/Requests/StoreShippingZoneRequest.php new file mode 100644 index 00000000..4f27f4eb --- /dev/null +++ b/app/Http/Requests/StoreShippingZoneRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['name' => ['required', 'string', 'max:255'], 'countries_json' => ['required', 'array', 'min:1'], 'countries_json.*' => ['required', 'string', 'size:2', 'uppercase'], 'regions_json' => ['nullable', 'array'], 'regions_json.*' => ['string', 'max:20']]; + } +} diff --git a/app/Http/Requests/StoreThemeRequest.php b/app/Http/Requests/StoreThemeRequest.php new file mode 100644 index 00000000..df1cfa3c --- /dev/null +++ b/app/Http/Requests/StoreThemeRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('create', \App\Models\Theme::class); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['file' => ['required', 'file', 'mimes:zip', 'max:51200'], 'name' => ['nullable', 'string', 'max:255']]; + } +} diff --git a/app/Http/Requests/UpdateCollectionRequest.php b/app/Http/Requests/UpdateCollectionRequest.php new file mode 100644 index 00000000..6476e63c --- /dev/null +++ b/app/Http/Requests/UpdateCollectionRequest.php @@ -0,0 +1,36 @@ +|string> + */ + public function rules(): array + { + return [ + 'title' => ['sometimes', 'string', 'max:255'], + 'handle' => ['sometimes', 'string', 'max:255'], + 'description_html' => ['sometimes', 'nullable', 'string'], + 'type' => ['sometimes', 'in:manual,automated'], + 'rules_json' => ['sometimes', 'nullable', 'array'], + 'status' => ['sometimes', 'in:active,draft,archived'], + 'product_ids' => ['sometimes', 'array'], + ]; + } +} diff --git a/app/Http/Requests/UpdateDiscountRequest.php b/app/Http/Requests/UpdateDiscountRequest.php new file mode 100644 index 00000000..e1fd97af --- /dev/null +++ b/app/Http/Requests/UpdateDiscountRequest.php @@ -0,0 +1,45 @@ +|string> + */ + public function rules(): array + { + return [ + 'type' => ['sometimes', 'in:code,automatic'], + 'code' => ['sometimes', 'nullable', 'string', 'max:50'], + 'value_type' => ['sometimes', 'in:fixed,percent,free_shipping'], + 'value_amount' => ['sometimes', 'integer', 'min:0'], + 'minimum_order_amount' => ['sometimes', 'nullable', 'integer', 'min:0'], + 'usage_limit' => ['sometimes', 'nullable', 'integer', 'min:1'], + 'starts_at' => ['sometimes', 'nullable', 'date'], + 'ends_at' => ['sometimes', 'nullable', 'date', 'after:starts_at'], + 'rules_json' => ['sometimes', 'nullable', 'array'], + 'status' => ['sometimes', 'in:active,inactive'], + ]; + } + + protected function withValidator(Validator $validator): void + { + $validator->sometimes('value_amount', ['max:100'], fn (): bool => $this->input('value_type') === 'percent'); + } +} diff --git a/app/Http/Requests/UpdatePageRequest.php b/app/Http/Requests/UpdatePageRequest.php new file mode 100644 index 00000000..d96a8eac --- /dev/null +++ b/app/Http/Requests/UpdatePageRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('viewAny', \App\Models\Page::class); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['title' => ['sometimes', 'string', 'max:255'], 'handle' => ['sometimes', 'string', 'max:255'], 'body_html' => ['sometimes', 'nullable', 'string'], 'status' => ['sometimes', 'in:draft,published']]; + } +} diff --git a/app/Http/Requests/UpdateProductRequest.php b/app/Http/Requests/UpdateProductRequest.php new file mode 100644 index 00000000..9eed72b1 --- /dev/null +++ b/app/Http/Requests/UpdateProductRequest.php @@ -0,0 +1,70 @@ +|string> + */ + public function rules(): array + { + return [ + 'title' => ['sometimes', 'string', 'max:255'], + 'handle' => ['sometimes', 'string', 'max:255'], + 'description_html' => ['sometimes', 'nullable', 'string'], + 'description' => ['sometimes', 'nullable', 'string'], + 'status' => ['sometimes', 'in:active,draft,archived'], + 'vendor' => ['sometimes', 'nullable', 'string', 'max:255'], + 'product_type' => ['sometimes', 'nullable', 'string', 'max:255'], + 'tags' => ['sometimes', 'nullable', 'array', 'max:50'], + 'tags.*' => ['string', 'max:255'], + 'options' => ['sometimes', 'array', 'max:3'], + 'options.*.name' => ['required', 'string', 'max:255'], + 'options.*.position' => ['required', 'integer', 'between:1,3'], + 'options.*.values' => ['nullable', 'array'], + 'options.*.values.*.value' => ['required', 'string', 'max:255'], + 'options.*.values.*.position' => ['nullable', 'integer', 'min:1'], + 'variants' => ['sometimes', 'array', 'min:1', 'max:100'], + 'variants.*.id' => ['nullable', 'integer'], + 'variants.*.sku' => ['sometimes', 'string', 'max:255'], + 'variants.*.barcode' => ['sometimes', 'nullable', 'string', 'max:255'], + 'variants.*.title' => ['sometimes', 'nullable', 'string', 'max:255'], + 'variants.*.price_amount' => ['sometimes', 'integer', 'min:0'], + 'variants.*.compare_at_amount' => ['sometimes', 'nullable', 'integer', 'min:0'], + 'variants.*.currency' => ['sometimes', 'nullable', 'string', 'size:3', 'uppercase'], + 'variants.*.weight_g' => ['sometimes', 'nullable', 'integer', 'min:0'], + 'variants.*.requires_shipping' => ['sometimes', 'boolean'], + 'variants.*.is_default' => ['sometimes', 'boolean'], + 'variants.*.position' => ['sometimes', 'integer', 'min:1'], + 'variants.*.status' => ['sometimes', 'in:active,archived'], + 'variants.*.option_values' => ['sometimes', 'array'], + 'variants.*.option_values.*.option_name' => ['required', 'string', 'max:255'], + 'variants.*.option_values.*.value' => ['required', 'string', 'max:255'], + 'variants.*.inventory.quantity_on_hand' => ['sometimes', 'integer', 'min:0'], + 'variants.*.inventory.policy' => ['sometimes', 'in:deny,continue'], + 'remove_variant_ids' => ['sometimes', 'array'], + 'remove_variant_ids.*' => ['integer'], + 'collections' => ['sometimes', 'array'], + 'collections.*' => [ + 'integer', + Rule::exists('collections', 'id')->where(fn ($query) => $query->where('store_id', app('current_store')->getKey())), + ], + ]; + } +} diff --git a/app/Http/Requests/UpdateShippingZoneRequest.php b/app/Http/Requests/UpdateShippingZoneRequest.php new file mode 100644 index 00000000..ca996391 --- /dev/null +++ b/app/Http/Requests/UpdateShippingZoneRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['name' => ['sometimes', 'string', 'max:255'], 'countries_json' => ['sometimes', 'array'], 'regions_json' => ['sometimes', 'array']]; + } +} diff --git a/app/Http/Requests/UpdateStoreSettingsRequest.php b/app/Http/Requests/UpdateStoreSettingsRequest.php new file mode 100644 index 00000000..2b58d488 --- /dev/null +++ b/app/Http/Requests/UpdateStoreSettingsRequest.php @@ -0,0 +1,32 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'default_currency' => ['required', 'in:EUR,USD,GBP'], + 'default_locale' => ['required', 'string', 'max:10'], + 'timezone' => ['required', 'timezone'], + ]; + } +} diff --git a/app/Http/Requests/UpdateTaxSettingsRequest.php b/app/Http/Requests/UpdateTaxSettingsRequest.php new file mode 100644 index 00000000..8ff77dbd --- /dev/null +++ b/app/Http/Requests/UpdateTaxSettingsRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('update', app('current_store')); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['mode' => ['required', 'in:manual,provider'], 'provider' => ['required_if:mode,provider', 'nullable', 'in:none,stripe_tax'], 'prices_include_tax' => ['required', 'boolean'], 'config_json' => ['required', 'array'], 'default_rate_basis_points' => ['sometimes', 'integer', 'min:0', 'max:10000'], 'rates_json' => ['sometimes', 'array'], 'provider_config_json' => ['sometimes', 'array']]; + } +} diff --git a/app/Http/Requests/UpdateThemeSettingsRequest.php b/app/Http/Requests/UpdateThemeSettingsRequest.php new file mode 100644 index 00000000..04f6f0e5 --- /dev/null +++ b/app/Http/Requests/UpdateThemeSettingsRequest.php @@ -0,0 +1,27 @@ +bound('current_store') && Gate::allows('viewAny', \App\Models\Theme::class); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return ['settings_json' => ['required', 'array']]; + } +} diff --git a/app/Jobs/AggregateAnalytics.php b/app/Jobs/AggregateAnalytics.php new file mode 100644 index 00000000..c8e70363 --- /dev/null +++ b/app/Jobs/AggregateAnalytics.php @@ -0,0 +1,45 @@ +date ?? now()->subDay()->toDateString()); + $stores = $this->store === null ? Store::query()->get() : collect([$this->store]); + + foreach ($stores as $store) { + $events = AnalyticsEvent::withoutGlobalScopes()->where('store_id', $store->getKey())->whereDate('occurred_at', $date)->get(); + $completed = $events->where('type', 'checkout_completed'); + $ordersCount = $completed->count(); + $revenue = (int) $completed->sum(fn (AnalyticsEvent $event): int => (int) ($event->properties_json['total_amount'] ?? $event->properties_json['order_total_amount'] ?? 0)); + + AnalyticsDaily::withoutGlobalScopes()->newQuery()->updateOrInsert( + ['store_id' => $store->getKey(), 'date' => $date->toDateString()], + [ + 'orders_count' => $ordersCount, + 'revenue_amount' => $revenue, + 'aov_amount' => $ordersCount > 0 ? intdiv($revenue, $ordersCount) : 0, + 'visits_count' => $events->where('type', 'page_view')->pluck('session_id')->filter()->unique()->count(), + 'add_to_cart_count' => $events->where('type', 'add_to_cart')->count(), + 'checkout_started_count' => $events->where('type', 'checkout_started')->count(), + 'checkout_completed_count' => $events->where('type', 'checkout_completed')->count(), + ], + ); + } + } +} diff --git a/app/Jobs/CancelUnpaidBankTransferOrders.php b/app/Jobs/CancelUnpaidBankTransferOrders.php new file mode 100644 index 00000000..73fdf730 --- /dev/null +++ b/app/Jobs/CancelUnpaidBankTransferOrders.php @@ -0,0 +1,33 @@ +where('payment_method', 'bank_transfer') + ->where('financial_status', FinancialStatus::Pending) + ->with('lines.variant.inventory') + ->each(function (Order $order) use ($orders): void { + $settings = StoreSettings::withoutGlobalScopes()->find($order->store_id); + $days = (int) ($settings?->settings_json['bank_transfer_cancel_days'] ?? config('shop.bank_transfer_expiry_days', 7)); + + if ($order->placed_at?->isBefore(now()->subDays($days))) { + $orders->cancel($order, 'Bank transfer payment expired.'); + } + }); + } +} diff --git a/app/Jobs/CleanupAbandonedCarts.php b/app/Jobs/CleanupAbandonedCarts.php new file mode 100644 index 00000000..fe86e927 --- /dev/null +++ b/app/Jobs/CleanupAbandonedCarts.php @@ -0,0 +1,44 @@ +where('status', 'active')->where('updated_at', '<', now()->subDays(14))->each(function (Cart $cart) use ($inventory): void { + DB::transaction(function () use ($cart, $inventory): void { + $cart->load('lines.variant.inventory'); + $checkouts = Checkout::withoutGlobalScopes() + ->where('cart_id', $cart->getKey()) + ->where('status', CheckoutStatus::PaymentSelected->value) + ->lockForUpdate() + ->get(); + + foreach ($checkouts as $checkout) { + foreach ($cart->lines as $line) { + if ($line->variant?->inventory !== null) { + $inventory->release($line->variant->inventory, $line->quantity); + } + } + + $checkout->update(['status' => CheckoutStatus::Expired]); + } + + $cart->update(['status' => 'abandoned']); + }); + }); + } +} diff --git a/app/Jobs/DeliverWebhook.php b/app/Jobs/DeliverWebhook.php new file mode 100644 index 00000000..ab38d644 --- /dev/null +++ b/app/Jobs/DeliverWebhook.php @@ -0,0 +1,72 @@ + */ + public function backoff(): array + { + return [60, 300, 1800, 7200, 43200]; + } + + public function handle(WebhookService $webhooks): void + { + $this->delivery->load('subscription'); + $payload = json_encode($this->delivery->payload, JSON_THROW_ON_ERROR); + $subscription = $this->delivery->subscription; + $timestamp = (string) now()->timestamp; + $response = Http::withHeaders([ + 'Content-Type' => 'application/json', + 'X-Platform-Signature' => $webhooks->sign($payload, $subscription->signing_secret_encrypted), + 'X-Platform-Event' => $this->delivery->event, + 'X-Platform-Delivery-Id' => (string) $this->delivery->getKey(), + 'X-Platform-Timestamp' => $timestamp, + ])->timeout(10)->post($subscription->target_url, $this->delivery->payload); + + $this->delivery->increment('attempts'); + $this->delivery->increment('attempt_count'); + $this->delivery->update([ + 'response_status' => $response->status(), + 'response_code' => $response->status(), + 'response_body' => mb_substr($response->body(), 0, 10000), + 'response_body_snippet' => mb_substr($response->body(), 0, 1000), + 'last_attempt_at' => now(), + ]); + + if ($response->successful()) { + $subscription->update(['consecutive_failures' => 0]); + $this->delivery->update(['status' => 'delivered', 'delivered_at' => now(), 'next_attempt_at' => null]); + + return; + } + + $subscription->increment('consecutive_failures'); + + if ($subscription->fresh()->consecutive_failures >= 5) { + $subscription->update(['status' => 'paused']); + } + + throw new \RuntimeException('Webhook delivery failed with HTTP '.$response->status()); + } + + public function failed(?Throwable $exception): void + { + $this->delivery->update(['status' => 'failed', 'next_attempt_at' => null]); + } +} diff --git a/app/Jobs/ExpireAbandonedCheckouts.php b/app/Jobs/ExpireAbandonedCheckouts.php new file mode 100644 index 00000000..61d1b29e --- /dev/null +++ b/app/Jobs/ExpireAbandonedCheckouts.php @@ -0,0 +1,31 @@ +whereNotIn('status', [CheckoutStatus::Completed, CheckoutStatus::Expired])->where('expires_at', '<', now())->with('cart.lines.variant.inventory')->each(function (Checkout $checkout) use ($inventory): void { + foreach ($checkout->cart->lines as $line) { + if ($line->variant->inventory !== null && $checkout->status === CheckoutStatus::PaymentSelected) { + $inventory->release($line->variant->inventory, $line->quantity); + } + } + + $checkout->update(['status' => CheckoutStatus::Expired]); + CheckoutExpired::dispatch($checkout->refresh()); + }); + } +} diff --git a/app/Jobs/GenerateOrderExport.php b/app/Jobs/GenerateOrderExport.php new file mode 100644 index 00000000..5b41a04c --- /dev/null +++ b/app/Jobs/GenerateOrderExport.php @@ -0,0 +1,74 @@ +export->update(['status' => 'processing', 'error_message' => null]); + + try { + $filters = $this->export->filters_json ?? []; + $orders = Order::withoutGlobalScopes() + ->where('store_id', $this->export->store_id) + ->with(['customer', 'checkout.shippingRate']) + ->when($filters['status'] ?? null, fn ($query, string $status) => $query->where('status', $status)) + ->when($filters['financial_status'] ?? null, fn ($query, string $status) => $query->where('financial_status', $status)) + ->when($filters['created_after'] ?? null, fn ($query, string $date) => $query->where('created_at', '>=', $date)) + ->when($filters['created_before'] ?? null, fn ($query, string $date) => $query->where('created_at', '<=', $date)) + ->orderBy('created_at') + ->get(); + + $handle = fopen('php://temp', 'w+'); + fputcsv($handle, ['order_number', 'created_at', 'status', 'financial_status', 'fulfillment_status', 'customer_email', 'customer_name', 'subtotal_amount', 'discount_amount', 'shipping_amount', 'tax_amount', 'total_amount', 'currency', 'shipping_method', 'tracking_number']); + + foreach ($orders as $order) { + fputcsv($handle, [ + $order->order_number, + $order->created_at?->toIso8601String(), + $order->status?->value ?? $order->status, + $order->financial_status?->value ?? $order->financial_status, + $order->fulfillment_status?->value ?? $order->fulfillment_status, + $order->customer?->email ?? $order->email, + $order->customer?->name, + $order->subtotal_amount, + $order->discount_amount, + $order->shipping_amount, + $order->tax_amount, + $order->total_amount, + $order->currency, + $order->checkout?->shippingRate?->name, + $order->fulfillments()->latest()->value('tracking_number'), + ]); + } + + rewind($handle); + $contents = stream_get_contents($handle); + fclose($handle); + $key = 'exports/orders-'.$this->export->getKey().'-'.now()->format('YmdHis').'.csv'; + Storage::disk('public')->put($key, $contents); + $expiresAt = now()->addHour(); + + $this->export->update(['status' => 'completed', 'row_count' => $orders->count(), 'storage_key' => $key, 'download_url' => Storage::disk('public')->url($key), 'download_expires_at' => $expiresAt, 'completed_at' => now()]); + } catch (Throwable $exception) { + $this->export->update(['status' => 'failed', 'error_message' => $exception->getMessage()]); + + throw $exception; + } + } +} diff --git a/app/Jobs/ProcessMediaUpload.php b/app/Jobs/ProcessMediaUpload.php new file mode 100644 index 00000000..487b697d --- /dev/null +++ b/app/Jobs/ProcessMediaUpload.php @@ -0,0 +1,166 @@ + */ + public array $backoff = [10, 30, 60]; + + public function __construct(public ProductMedia $media) {} + + public function handle(): void + { + $media = $this->media->fresh(); + $disk = Storage::disk('public'); + $sourceKey = $media?->storage_key ?: $media?->path; + + if ($media === null || $sourceKey === null || ! $disk->exists($sourceKey)) { + throw new RuntimeException('The uploaded media file is not available yet.'); + } + + $contents = $disk->get($sourceKey); + $mimeType = $media->mime_type ?: $disk->mimeType($sourceKey) ?: 'application/octet-stream'; + $metadata = $media->metadata ?? []; + $width = null; + $height = null; + $variants = ['original' => $sourceKey]; + + if (str_starts_with($mimeType, 'image/')) { + $dimensions = @getimagesizefromstring($contents); + if ($dimensions === false) { + throw new RuntimeException('The uploaded image could not be decoded.'); + } + [$width, $height] = $dimensions; + $variants = $this->writeImageVariants($disk, $sourceKey, $contents, $mimeType, $width, $height); + } + + $metadata['variants'] = $variants; + $metadata['processed_at'] = now()->toIso8601String(); + $media->update([ + 'status' => 'ready', + 'width' => $width, + 'height' => $height, + 'mime_type' => $mimeType, + 'byte_size' => strlen($contents), + 'checksum' => hash('sha256', $contents), + 'url' => $disk->url($sourceKey), + 'metadata' => $metadata, + ]); + } + + public function failed(Throwable $exception): void + { + $media = $this->media->fresh(); + $metadata = $media?->metadata ?? []; + $metadata['error'] = $exception->getMessage(); + $metadata['failed_at'] = now()->toIso8601String(); + $media?->update(['status' => 'failed', 'metadata' => $metadata]); + } + + /** + * @return array + */ + private function writeImageVariants(object $disk, string $sourceKey, string $contents, string $mimeType, int $width, int $height): array + { + $variants = ['original' => $sourceKey]; + $directory = trim(pathinfo($sourceKey, PATHINFO_DIRNAME), '.'); + $extension = strtolower(pathinfo($sourceKey, PATHINFO_EXTENSION)); + + $basename = pathinfo($sourceKey, PATHINFO_FILENAME); + + foreach (['thumbnail' => 150, 'small' => 300, 'medium' => 600, 'large' => 1200] as $name => $maximum) { + $variantContents = $contents; + if ($width <= $maximum && $height <= $maximum) { + $variants[$name] = $sourceKey; + } else { + $variantContents = $this->resize($contents, $mimeType, $width, $height, $maximum); + if ($variantContents === null) { + $variants[$name] = $sourceKey; + + continue; + } + } + + $key = $directory.'/'.$basename.'/'.$name.'.'.$extension; + $disk->put($key, $variantContents); + $variants[$name] = $key; + + if (function_exists('imagewebp')) { + $webp = $this->resizeToWebp($contents, $width, $height, $maximum); + if ($webp !== null) { + $webpKey = $directory.'/'.$basename.'/'.$name.'.webp'; + $disk->put($webpKey, $webp); + $variants[$name.'_webp'] = $webpKey; + } + } + } + + return $variants; + } + + private function resize(string $contents, string $mimeType, int $width, int $height, int $maximum): ?string + { + $source = @imagecreatefromstring($contents); + if ($source === false) { + return null; + } + + $scale = min($maximum / $width, $maximum / $height); + $targetWidth = max(1, (int) round($width * $scale)); + $targetHeight = max(1, (int) round($height * $scale)); + $target = imagecreatetruecolor($targetWidth, $targetHeight); + imagealphablending($target, false); + imagesavealpha($target, true); + imagecopyresampled($target, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height); + ob_start(); + + $written = match ($mimeType) { + 'image/png' => imagepng($target, null, 8), + 'image/webp' => function_exists('imagewebp') ? imagewebp($target, null, 85) : false, + default => imagejpeg($target, null, 85), + }; + + $result = $written ? ob_get_clean() : false; + imagedestroy($source); + imagedestroy($target); + + return is_string($result) ? $result : null; + } + + private function resizeToWebp(string $contents, int $width, int $height, int $maximum): ?string + { + $source = @imagecreatefromstring($contents); + if ($source === false) { + return null; + } + + $scale = min(1, $maximum / $width, $maximum / $height); + $targetWidth = max(1, (int) round($width * $scale)); + $targetHeight = max(1, (int) round($height * $scale)); + $target = imagecreatetruecolor($targetWidth, $targetHeight); + imagealphablending($target, false); + imagesavealpha($target, true); + imagecopyresampled($target, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height); + ob_start(); + $written = imagewebp($target, null, 85); + $result = $written ? ob_get_clean() : false; + imagedestroy($source); + imagedestroy($target); + + return is_string($result) ? $result : null; + } +} diff --git a/app/Listeners/DispatchWebhooks.php b/app/Listeners/DispatchWebhooks.php new file mode 100644 index 00000000..4e40f9c7 --- /dev/null +++ b/app/Listeners/DispatchWebhooks.php @@ -0,0 +1,44 @@ + [$event->order->store, 'order.created', $event->order], + $event instanceof OrderPaid => [$event->order->store, 'order.paid', $event->order], + $event instanceof OrderFulfilled => [$event->order->store, 'order.fulfilled', $event->order], + $event instanceof OrderRefunded => [$event->order->store, 'order.refunded', $event->order], + $event instanceof CheckoutCompleted => [$event->checkout->store, 'checkout.completed', $event->checkout], + $event instanceof ProductCreated => [$event->product->store, 'product.created', $event->product], + $event instanceof ProductDeleted => [$event->product->store, 'product.deleted', $event->product], + $event instanceof ProductUpdated => [$event->product->store, $event->product->status->value === 'archived' ? 'product.deleted' : 'product.updated', $event->product], + default => [null, null, null], + }; + + if ($store === null || $eventType === null || $resource === null) { + return; + } + + $this->webhooks->dispatch($store, $eventType, [ + 'api_version' => '2026-01', + 'id' => (string) $resource->getKey(), + 'type' => $eventType, + 'data' => $resource->toArray(), + ]); + } +} diff --git a/app/Listeners/RecordAuthenticationEvent.php b/app/Listeners/RecordAuthenticationEvent.php new file mode 100644 index 00000000..4e3c746c --- /dev/null +++ b/app/Listeners/RecordAuthenticationEvent.php @@ -0,0 +1,31 @@ + 'auth.login', + $event instanceof Failed => 'auth.failed', + default => 'auth.logout', + }; + $subject = $event->user instanceof Model ? $event->user : null; + $context = ['guard' => $event->guard]; + + if ($event instanceof Failed) { + $context['identifier'] = $event->credentials['email'] ?? null; + } + + $this->audit->record($name, $subject, $context); + } +} diff --git a/app/Livewire/Admin/Analytics/Index.php b/app/Livewire/Admin/Analytics/Index.php new file mode 100644 index 00000000..9679da5e --- /dev/null +++ b/app/Livewire/Admin/Analytics/Index.php @@ -0,0 +1,27 @@ +where('date', '>=', now()->subDays((int) $this->range - 1)->toDateString())->orderBy('date')->get(); + $summary = [ + 'visits' => (int) $days->sum('visits_count'), + 'orders' => (int) $days->sum('orders_count'), + 'revenue' => (int) $days->sum('revenue_amount'), + 'add_to_cart' => (int) $days->sum('add_to_cart_count'), + 'checkout_started' => (int) $days->sum('checkout_started_count'), + 'checkout_completed' => (int) $days->sum('checkout_completed_count'), + ]; + + return view('livewire.admin.analytics.index', compact('days', 'summary'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Apps/Index.php b/app/Livewire/Admin/Apps/Index.php new file mode 100644 index 00000000..2111e65a --- /dev/null +++ b/app/Livewire/Admin/Apps/Index.php @@ -0,0 +1,21 @@ +user()?->canManageStore(app('current_store')), 403); + AppInstallation::query()->findOrFail($installationId)->delete(); + } + + public function render(): View + { + return view('livewire.admin.apps.index', ['installations' => AppInstallation::query()->with('app')->latest()->get(), 'availableApps' => \App\Models\App::query()->whereDoesntHave('installations', fn ($query) => $query->where('store_id', app('current_store')->getKey()))->get()])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Apps/Show.php b/app/Livewire/Admin/Apps/Show.php new file mode 100644 index 00000000..aeab02ee --- /dev/null +++ b/app/Livewire/Admin/Apps/Show.php @@ -0,0 +1,7 @@ +validate(['email' => ['required', 'email']]); + Password::broker('users')->sendResetLink(['email' => $this->email]); + $this->message = 'If an account exists for that email, a reset link has been sent.'; + } + + public function render(): mixed + { + return view('livewire.admin.auth.forgot-password')->layout('layouts.auth'); + } +} diff --git a/app/Livewire/Admin/Auth/Login.php b/app/Livewire/Admin/Auth/Login.php new file mode 100644 index 00000000..ac613745 --- /dev/null +++ b/app/Livewire/Admin/Auth/Login.php @@ -0,0 +1,51 @@ +validate(['email' => ['required', 'email'], 'password' => ['required', 'string']]); + $key = 'admin-login|'.request()->ip(); + + if (RateLimiter::tooManyAttempts($key, 5)) { + $this->addError('email', 'Too many attempts. Try again later.'); + + return; + } + + RateLimiter::hit($key, 60); + + if (! Auth::guard('web')->attempt([...$credentials, 'status' => 'active'], $this->remember)) { + $this->addError('email', 'Invalid credentials'); + + return; + } + + RateLimiter::clear($key); + session()->regenerate(); + $store = auth()->user()->stores()->first(); + + if ($store !== null) { + session()->put('current_store_id', $store->getKey()); + } + + $this->redirect(route('admin.dashboard'), navigate: true); + } + + public function render(): mixed + { + return view('livewire.admin.auth.login')->layout('layouts.auth'); + } +} diff --git a/app/Livewire/Admin/Auth/ResetPassword.php b/app/Livewire/Admin/Auth/ResetPassword.php new file mode 100644 index 00000000..5dee5bd3 --- /dev/null +++ b/app/Livewire/Admin/Auth/ResetPassword.php @@ -0,0 +1,46 @@ +token = $token; + $this->email = request()->string('email')->toString(); + } + + public function resetPassword(): void + { + $data = $this->validate(['email' => ['required', 'email'], 'password' => ['required', 'min:8', 'same:passwordConfirmation']]); + $status = Password::broker('users')->reset(['email' => $data['email'], 'password' => $data['password'], 'password_confirmation' => $this->passwordConfirmation, 'token' => $this->token], function (User $user, string $password): void { + $user->password = $password; + $user->save(); + }); + + if ($status !== Password::PASSWORD_RESET) { + $this->addError('email', __($status)); + + return; + } + + $this->redirect(route('admin.login'), navigate: true); + } + + public function render(): mixed + { + return view('livewire.admin.auth.reset-password')->layout('layouts.auth'); + } +} diff --git a/app/Livewire/Admin/Collections/Create.php b/app/Livewire/Admin/Collections/Create.php new file mode 100644 index 00000000..1d13ce83 --- /dev/null +++ b/app/Livewire/Admin/Collections/Create.php @@ -0,0 +1,53 @@ + */ + public array $productIds = []; + + public function save(): void + { + $this->authorize('create', Collection::class); + $data = $this->validate([ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['nullable', 'string', 'max:255'], + 'description' => ['nullable', 'string'], + 'status' => ['required', 'in:draft,active,archived'], + 'productIds' => ['array'], + ]); + $collection = Collection::query()->create([ + 'title' => $data['title'], + 'handle' => $data['handle'] !== '' ? $data['handle'] : str($data['title'])->slug()->toString(), + 'description' => $data['description'], + 'status' => $data['status'], + ]); + $this->syncProducts($collection, $data['productIds']); + $this->redirectRoute('admin.collections.edit', ['collection' => $collection], navigate: true); + } + + /** @param list $productIds */ + private function syncProducts(Collection $collection, array $productIds): void + { + $validIds = \App\Models\Product::query()->whereIn('id', $productIds)->pluck('id')->all(); + $collection->products()->sync(array_fill_keys($validIds, ['position' => 0])); + } + + public function render(): View + { + return view('livewire.admin.collections.form', ['collection' => null])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Collections/Edit.php b/app/Livewire/Admin/Collections/Edit.php new file mode 100644 index 00000000..ae2fda6c --- /dev/null +++ b/app/Livewire/Admin/Collections/Edit.php @@ -0,0 +1,59 @@ + */ + public array $productIds = []; + + public function mount(Collection $collection): void + { + $this->collection = $collection; + $this->title = $collection->title; + $this->handle = $collection->handle; + $this->description = (string) $collection->description; + $this->status = $collection->status->value; + $this->productIds = $collection->products()->pluck('products.id')->all(); + } + + public function save(): void + { + $this->authorize('update', $this->collection); + $data = $this->validate([ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['required', 'string', 'max:255'], + 'description' => ['nullable', 'string'], + 'status' => ['required', 'in:draft,active,archived'], + 'productIds' => ['array'], + ]); + $this->collection->update([ + 'title' => $data['title'], + 'handle' => $data['handle'], + 'description' => $data['description'], + 'status' => $data['status'], + ]); + $validIds = \App\Models\Product::query()->whereIn('id', $data['productIds'])->pluck('id')->all(); + $this->collection->products()->sync(array_fill_keys($validIds, ['position' => 0])); + $this->dispatch('toast', message: 'Collection saved.'); + } + + public function render(): View + { + return view('livewire.admin.collections.form')->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Collections/Form.php b/app/Livewire/Admin/Collections/Form.php new file mode 100644 index 00000000..56d0c528 --- /dev/null +++ b/app/Livewire/Admin/Collections/Form.php @@ -0,0 +1,13 @@ +resetPage(); + } + + public function updatedStatus(): void + { + $this->resetPage(); + } + + public function delete(int $collectionId): void + { + $collection = Collection::query()->findOrFail($collectionId); + $this->authorize('delete', $collection); + $collection->delete(); + $this->dispatch('toast', message: 'Collection deleted.'); + } + + public function render(): View + { + $collections = Collection::query() + ->withCount('products') + ->when($this->search !== '', fn ($query) => $query->where(function ($nested): void { + $nested->where('title', 'like', '%'.$this->search.'%') + ->orWhere('handle', 'like', '%'.$this->search.'%'); + })) + ->when($this->status !== 'all', fn ($query) => $query->where('status', $this->status)) + ->latest() + ->paginate(20); + + return view('livewire.admin.collections.index', compact('collections'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Customers/Index.php b/app/Livewire/Admin/Customers/Index.php new file mode 100644 index 00000000..316b283c --- /dev/null +++ b/app/Livewire/Admin/Customers/Index.php @@ -0,0 +1,44 @@ +authorize('viewAny', Customer::class); + } + + public function updatedSearch(): void + { + $this->resetPage(); + } + + public function render(): mixed + { + $search = trim($this->search); + $customers = Customer::query() + ->select(['id', 'store_id', 'first_name', 'last_name', 'email', 'created_at']) + ->withCount('orders') + ->withSum('orders', 'total_amount') + ->when($search !== '', function ($query) use ($search): void { + $query->where(function ($query) use ($search): void { + $query->where('email', 'like', '%'.$search.'%') + ->orWhere('first_name', 'like', '%'.$search.'%') + ->orWhere('last_name', 'like', '%'.$search.'%'); + }); + }) + ->latest() + ->paginate(15); + + return view('livewire.admin.customers.index', compact('customers'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Customers/Show.php b/app/Livewire/Admin/Customers/Show.php new file mode 100644 index 00000000..0fc36471 --- /dev/null +++ b/app/Livewire/Admin/Customers/Show.php @@ -0,0 +1,177 @@ + */ + public array $addressJson = [ + 'line1' => '', + 'line2' => '', + 'city' => '', + 'state' => '', + 'zip' => '', + 'country' => 'DE', + ]; + + public string $message = ''; + + public function mount(Customer $customer): void + { + $this->customer = $customer; + $this->authorize('view', $this->customer); + $this->loadCustomer(); + $this->fillCustomerForm(); + } + + public function openCustomerForm(): void + { + $this->authorize('update', $this->customer); + $this->fillCustomerForm(); + $this->resetValidation(); + $this->editingCustomer = true; + } + + public function saveCustomer(): void + { + $this->authorize('update', $this->customer); + $data = $this->validate([ + 'firstName' => ['required', 'string', 'max:255'], + 'lastName' => ['required', 'string', 'max:255'], + 'email' => ['required', 'email', 'max:255', Rule::unique('customers', 'email')->where(fn ($query) => $query->where('store_id', app('current_store')->getKey()))->ignore($this->customer->id)], + ]); + + $this->customer->update([ + 'first_name' => $data['firstName'], + 'last_name' => $data['lastName'], + 'email' => $data['email'], + 'metadata' => array_merge($this->customer->metadata ?? [], ['marketing_opt_in' => $this->marketingOptIn]), + ]); + $this->editingCustomer = false; + $this->message = 'Customer details saved.'; + $this->loadCustomer(); + } + + public function openAddressForm(?int $addressId = null): void + { + $this->authorize('update', $this->customer); + $this->resetValidation(); + $this->editingAddress = $addressId === null + ? null + : $this->customer->addresses()->whereKey($addressId)->firstOrFail(); + $this->addressLabel = (string) ($this->editingAddress?->label ?? ''); + $stored = $this->editingAddress?->address_json ?? []; + $this->addressJson = [ + 'line1' => (string) ($stored['line1'] ?? $stored['address1'] ?? ''), + 'line2' => (string) ($stored['line2'] ?? $stored['address2'] ?? ''), + 'city' => (string) ($stored['city'] ?? ''), + 'state' => (string) ($stored['state'] ?? $stored['province'] ?? ''), + 'zip' => (string) ($stored['zip'] ?? $stored['postal_code'] ?? ''), + 'country' => strtoupper((string) ($stored['country'] ?? $stored['country_code'] ?? 'DE')), + ]; + $this->showAddressModal = true; + } + + public function saveAddress(): void + { + $this->authorize('update', $this->customer); + $data = $this->validate([ + 'addressLabel' => ['nullable', 'string', 'max:100'], + 'addressJson.line1' => ['required', 'string', 'max:500'], + 'addressJson.line2' => ['nullable', 'string', 'max:500'], + 'addressJson.city' => ['required', 'string', 'max:255'], + 'addressJson.state' => ['nullable', 'string', 'max:255'], + 'addressJson.zip' => ['required', 'string', 'max:30'], + 'addressJson.country' => ['required', 'string', 'size:2'], + ]); + $addressData = [ + 'label' => $data['addressLabel'] ?: null, + 'address_json' => array_map('trim', $data['addressJson']), + ]; + + if ($this->editingAddress === null) { + $this->customer->addresses()->create($addressData + ['is_default' => ! $this->customer->addresses()->exists()]); + } else { + $this->editingAddress->update($addressData); + } + + $this->showAddressModal = false; + $this->message = 'Address saved.'; + $this->loadCustomer(); + } + + public function deleteAddress(int $addressId): void + { + $this->authorize('update', $this->customer); + $address = $this->customer->addresses()->whereKey($addressId)->firstOrFail(); + $wasDefault = $address->is_default; + $address->delete(); + + if ($wasDefault) { + $this->customer->addresses()->latest('id')->first()?->update(['is_default' => true]); + } + + $this->message = 'Address deleted.'; + $this->loadCustomer(); + } + + public function setDefaultAddress(int $addressId): void + { + $this->authorize('update', $this->customer); + $address = $this->customer->addresses()->whereKey($addressId)->firstOrFail(); + $this->customer->addresses()->update(['is_default' => false]); + $address->update(['is_default' => true]); + $this->message = 'Default address updated.'; + $this->loadCustomer(); + } + + public function render(): mixed + { + $orders = $this->customer->orders() + ->select(['id', 'customer_id', 'order_number', 'status', 'financial_status', 'total_amount', 'currency', 'placed_at']) + ->latest('placed_at') + ->paginate(8, pageName: 'customer-orders'); + + return view('livewire.admin.customers.show', compact('orders'))->layout('layouts.admin'); + } + + private function loadCustomer(): void + { + $this->customer = $this->customer->refresh()->load('addresses'); + } + + private function fillCustomerForm(): void + { + $this->firstName = (string) $this->customer->first_name; + $this->lastName = (string) $this->customer->last_name; + $this->email = (string) $this->customer->email; + $this->marketingOptIn = (bool) Arr::get($this->customer->metadata ?? [], 'marketing_opt_in', false); + } +} diff --git a/app/Livewire/Admin/Dashboard.php b/app/Livewire/Admin/Dashboard.php new file mode 100644 index 00000000..70e92ba9 --- /dev/null +++ b/app/Livewire/Admin/Dashboard.php @@ -0,0 +1,28 @@ +range, ['7', '30', '90'], true) ? (int) $this->range : 30; + $from = now()->subDays($days - 1)->startOfDay(); + $to = now()->endOfDay(); + $orders = Order::query()->with('customer')->whereBetween('placed_at', [$from, $to])->latest('placed_at')->take(10)->get(); + $sales = (int) Order::query()->where('financial_status', 'paid')->whereBetween('placed_at', [$from, $to])->sum('total_amount'); + $orderCount = (int) Order::query()->whereBetween('placed_at', [$from, $to])->count(); + $analytics = AnalyticsDaily::query()->whereBetween('date', [$from->toDateString(), $to->toDateString()])->orderBy('date')->get(); + $topProducts = OrderLine::query()->whereHas('order', fn ($query) => $query->where('financial_status', 'paid')->whereBetween('placed_at', [$from, $to]))->select('product_id', 'product_title')->selectRaw('SUM(quantity) AS units, SUM(line_total_amount) AS revenue')->groupBy('product_id', 'product_title')->orderByDesc('revenue')->limit(5)->get(); + + return view('livewire.admin.dashboard', ['orders' => $orders, 'sales' => $sales, 'orderCount' => $orderCount, 'productCount' => Product::query()->count(), 'analytics' => $analytics, 'topProducts' => $topProducts, 'visitors' => (int) $analytics->sum('visits_count'), 'addToCart' => (int) $analytics->sum('add_to_cart_count'), 'checkoutStarted' => (int) $analytics->sum('checkout_started_count')])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Developers/Index.php b/app/Livewire/Admin/Developers/Index.php new file mode 100644 index 00000000..758ede46 --- /dev/null +++ b/app/Livewire/Admin/Developers/Index.php @@ -0,0 +1,70 @@ +user()?->canManageStore(app('current_store')), 403); + $data = $this->validate(['event' => ['required', 'string', 'max:100'], 'targetUrl' => ['required', 'url', 'max:2000']]); + WebhookSubscription::query()->create(['event' => $data['event'], 'event_type' => $data['event'], 'target_url' => $data['targetUrl'], 'signing_secret_encrypted' => Str::random(48), 'status' => 'active']); + $this->reset('targetUrl'); + } + + public function pause(int $subscriptionId): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + $subscription = WebhookSubscription::query()->findOrFail($subscriptionId); + $subscription->update(['status' => $subscription->status === 'active' ? 'paused' : 'active']); + } + + public function createToken(): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + $data = $this->validate([ + 'tokenName' => ['required', 'string', 'max:100'], + 'tokenExpiresAt' => ['nullable', 'date', 'after:today'], + 'tokenAbilities' => ['required', 'string', 'max:1000'], + ]); + $allowed = ['read-products', 'write-products', 'read-orders', 'write-orders', 'read-customers', 'write-customers', 'read-collections', 'write-collections', 'read-discounts', 'write-discounts', 'read-analytics', 'read-settings', 'write-settings', 'read-themes', 'write-themes', 'read-content', 'write-content']; + + if (auth()->user()?->isPlatformAdmin()) { + $allowed[] = 'manage-platform'; + } + $abilities = array_values(array_intersect($allowed, array_filter(array_map('trim', explode(',', $data['tokenAbilities']))))); + abort_if($abilities === [], 422, 'Select at least one token ability.'); + $expiresAt = empty($data['tokenExpiresAt']) ? null : CarbonImmutable::parse($data['tokenExpiresAt']); + $this->plainTextToken = auth()->user()->createToken($data['tokenName'], $abilities, $expiresAt)->plainTextToken; + $this->reset(['tokenName', 'tokenExpiresAt']); + } + + public function revokeToken(int $tokenId): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + auth()->user()->tokens()->whereKey($tokenId)->delete(); + } + + public function render(): View + { + return view('livewire.admin.developers.index', ['subscriptions' => WebhookSubscription::query()->latest()->get(), 'tokens' => auth()->user()->tokens()->latest()->get()])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Discounts/Form.php b/app/Livewire/Admin/Discounts/Form.php new file mode 100644 index 00000000..79acf3ff --- /dev/null +++ b/app/Livewire/Admin/Discounts/Form.php @@ -0,0 +1,187 @@ + */ + public array $specificProductIds = []; + + /** @var array */ + public array $specificCollectionIds = []; + + public ?int $usageLimit = null; + + public bool $onePerCustomer = false; + + public string $startsAt = ''; + + public ?string $endsAt = null; + + public bool $isActive = true; + + public string $productSearch = ''; + + public string $collectionSearch = ''; + + public string $message = ''; + + public function mount(?Discount $discount = null): void + { + $this->discount = $discount; + $this->authorize($discount === null ? 'create' : 'view', $discount ?? Discount::class); + $this->startsAt = now()->format('Y-m-d\TH:i'); + + if ($discount !== null) { + $rules = $discount->rules_json ?? []; + $this->type = $discount->type instanceof DiscountType ? $discount->type->value : (string) $discount->type; + $this->code = (string) ($discount->code ?? ''); + $this->valueType = $discount->value_type instanceof DiscountValueType ? $discount->value_type->value : (string) $discount->value_type; + $this->valueAmount = $discount->value_amount; + $this->minimumPurchaseAmount = $rules['min_purchase_amount'] ?? $rules['minimum_purchase_amount'] ?? null; + $this->specificProductIds = array_map('intval', $rules['applicable_product_ids'] ?? []); + $this->specificCollectionIds = array_map('intval', $rules['applicable_collection_ids'] ?? []); + $this->usageLimit = $discount->usage_limit; + $this->onePerCustomer = (bool) ($rules['one_per_customer'] ?? false); + $this->startsAt = $discount->starts_at?->format('Y-m-d\TH:i') ?? ''; + $this->endsAt = $discount->ends_at?->format('Y-m-d\TH:i'); + $this->isActive = $discount->status === 'active'; + } + } + + public function generateCode(): void + { + $this->code = Str::upper(Str::random(10)); + } + + public function addProduct(int $productId): void + { + $this->authorize($this->discount === null ? 'create' : 'update', $this->discount ?? Discount::class); + $product = Product::query()->findOrFail($productId); + + if (! in_array($product->id, $this->specificProductIds, true)) { + $this->specificProductIds[] = $product->id; + } + $this->productSearch = ''; + } + + public function removeProduct(int $productId): void + { + $this->authorize($this->discount === null ? 'create' : 'update', $this->discount ?? Discount::class); + $this->specificProductIds = array_values(array_filter($this->specificProductIds, fn (int $id): bool => $id !== $productId)); + } + + public function addCollection(int $collectionId): void + { + $this->authorize($this->discount === null ? 'create' : 'update', $this->discount ?? Discount::class); + $collection = Collection::query()->findOrFail($collectionId); + + if (! in_array($collection->id, $this->specificCollectionIds, true)) { + $this->specificCollectionIds[] = $collection->id; + } + $this->collectionSearch = ''; + } + + public function removeCollection(int $collectionId): void + { + $this->authorize($this->discount === null ? 'create' : 'update', $this->discount ?? Discount::class); + $this->specificCollectionIds = array_values(array_filter($this->specificCollectionIds, fn (int $id): bool => $id !== $collectionId)); + } + + public function save(): void + { + $data = $this->validate([ + 'type' => ['required', 'in:code,automatic'], + 'code' => ['nullable', 'string', 'max:64', 'required_if:type,code', Rule::when($this->type === 'code', [Rule::unique('discounts', 'code')->where(fn ($query) => $query->where('store_id', app('current_store')->getKey()))->ignore($this->discount?->id)])], + 'valueType' => ['required', 'in:percent,fixed,free_shipping'], + 'valueAmount' => ['nullable', 'integer', 'min:0', 'required_unless:valueType,free_shipping'], + 'minimumPurchaseAmount' => ['nullable', 'integer', 'min:0'], + 'usageLimit' => ['nullable', 'integer', 'min:1'], + 'startsAt' => ['required', 'date'], + 'endsAt' => ['nullable', 'date', 'after:startsAt'], + 'specificProductIds' => ['array'], + 'specificProductIds.*' => ['integer', 'exists:products,id'], + 'specificCollectionIds' => ['array'], + 'specificCollectionIds.*' => ['integer', 'exists:collections,id'], + 'onePerCustomer' => ['boolean'], + 'isActive' => ['boolean'], + ]); + + if ($data['valueType'] === 'percent' && $data['valueAmount'] > 100) { + $this->addError('valueAmount', 'Percentage discounts cannot exceed 100%.'); + + return; + } + + $ability = $this->discount === null ? 'create' : 'update'; + $this->authorize($ability, $this->discount ?? Discount::class); + $rules = [ + 'min_purchase_amount' => $data['minimumPurchaseAmount'], + 'applicable_product_ids' => array_map('intval', $data['specificProductIds']), + 'applicable_collection_ids' => array_map('intval', $data['specificCollectionIds']), + 'one_per_customer' => (bool) $data['onePerCustomer'], + ]; + $attributes = [ + 'store_id' => app('current_store')->getKey(), + 'code' => $data['type'] === 'code' ? Str::upper(trim($data['code'])) : null, + 'type' => $data['type'], + 'value_type' => $data['valueType'], + 'value_amount' => $data['valueAmount'] ?? 0, + 'status' => $data['isActive'] ? 'active' : 'disabled', + 'usage_limit' => $data['usageLimit'], + 'starts_at' => Carbon::parse($data['startsAt']), + 'ends_at' => $data['endsAt'] ? Carbon::parse($data['endsAt']) : null, + 'rules_json' => $rules, + ]; + + if ($this->discount === null) { + $this->discount = Discount::create($attributes); + } else { + $this->discount->update($attributes); + } + + $this->message = 'Discount saved.'; + } + + public function render(): mixed + { + $productResults = Product::query() + ->select(['id', 'title']) + ->when(trim($this->productSearch) !== '', fn ($query) => $query->where('title', 'like', '%'.trim($this->productSearch).'%')) + ->whereNotIn('id', $this->specificProductIds ?: [0]) + ->limit(8) + ->get(); + $collectionResults = Collection::query() + ->select(['id', 'title']) + ->when(trim($this->collectionSearch) !== '', fn ($query) => $query->where('title', 'like', '%'.trim($this->collectionSearch).'%')) + ->whereNotIn('id', $this->specificCollectionIds ?: [0]) + ->limit(8) + ->get(); + $selectedProducts = Product::query()->select(['id', 'title'])->whereIn('id', $this->specificProductIds ?: [0])->get(); + $selectedCollections = Collection::query()->select(['id', 'title'])->whereIn('id', $this->specificCollectionIds ?: [0])->get(); + + return view('livewire.admin.discounts.form', compact('productResults', 'collectionResults', 'selectedProducts', 'selectedCollections'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Discounts/Index.php b/app/Livewire/Admin/Discounts/Index.php new file mode 100644 index 00000000..9b36da42 --- /dev/null +++ b/app/Livewire/Admin/Discounts/Index.php @@ -0,0 +1,64 @@ +authorize('viewAny', Discount::class); + } + + public function updatedSearch(): void + { + $this->resetPage(); + } + + public function updatedStatusFilter(): void + { + $this->resetPage(); + } + + public function delete(int $discountId): void + { + $discount = Discount::query()->findOrFail($discountId); + $this->authorize('delete', $discount); + $discount->delete(); + $this->dispatch('toast', message: 'Discount deleted.'); + } + + public function render(): mixed + { + $search = trim($this->search); + $now = Carbon::now(); + $discounts = Discount::query() + ->when($search !== '', fn ($query) => $query->where('code', 'like', '%'.$search.'%')) + ->when($this->statusFilter === 'active', fn ($query) => $query->where('status', 'active')->where(function ($query) use ($now): void { + $query->whereNull('starts_at')->orWhere('starts_at', '<=', $now); + })->where(function ($query) use ($now): void { + $query->whereNull('ends_at')->orWhere('ends_at', '>', $now); + })) + ->when($this->statusFilter === 'scheduled', fn ($query) => $query->where('starts_at', '>', $now)) + ->when($this->statusFilter === 'expired', fn ($query) => $query->where(function ($query) use ($now): void { + $query->where('ends_at', '<=', $now) + ->orWhere(function ($query): void { + $query->whereNotNull('usage_limit')->whereColumn('usage_count', '>=', 'usage_limit'); + }); + })) + ->latest() + ->paginate(15); + + return view('livewire.admin.discounts.index', compact('discounts'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Inventory/Index.php b/app/Livewire/Admin/Inventory/Index.php new file mode 100644 index 00000000..6cc0b43b --- /dev/null +++ b/app/Livewire/Admin/Inventory/Index.php @@ -0,0 +1,64 @@ + */ + public array $quantities = []; + + /** @var array */ + public array $policies = []; + + public function updatedSearch(): void + { + $this->resetPage(); + } + + public function updatedStock(): void + { + $this->resetPage(); + } + + public function save(int $inventoryId): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + $item = InventoryItem::query()->findOrFail($inventoryId); + $data = $this->validate([ + 'quantities.'.$inventoryId => ['required', 'integer', 'min:0'], + 'policies.'.$inventoryId => ['required', 'in:deny,continue'], + ]); + $item->update(['quantity_on_hand' => $data['quantities'][$inventoryId], 'policy' => $data['policies'][$inventoryId]]); + $this->dispatch('toast', message: 'Inventory updated.'); + } + + public function render(): View + { + $items = InventoryItem::query() + ->with('variant.product') + ->when($this->search !== '', fn ($query) => $query->whereHas('variant.product', fn ($product) => $product->where('title', 'like', '%'.$this->search.'%'))->orWhereHas('variant', fn ($variant) => $variant->where('sku', 'like', '%'.$this->search.'%'))) + ->when($this->stock === 'out', fn ($query) => $query->whereColumn('quantity_on_hand', '<=', 'quantity_reserved')) + ->when($this->stock === 'low', fn ($query) => $query->whereRaw('(quantity_on_hand - quantity_reserved) between 1 and 10')) + ->latest('updated_at') + ->paginate(25); + + foreach ($items as $item) { + $this->quantities[$item->id] ??= $item->quantity_on_hand; + $this->policies[$item->id] ??= $item->policy instanceof InventoryPolicy ? $item->policy->value : (string) $item->policy; + } + + return view('livewire.admin.inventory.index', compact('items'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Navigation/Index.php b/app/Livewire/Admin/Navigation/Index.php new file mode 100644 index 00000000..a33c7401 --- /dev/null +++ b/app/Livewire/Admin/Navigation/Index.php @@ -0,0 +1,71 @@ +first(); + $this->selectMenu($menu?->getKey() ?? 0); + } + + public function selectMenu(int $menuId): void + { + $menu = NavigationMenu::query()->find($menuId); + $this->menuId = $menu?->getKey() ?? 0; + $this->menuName = $menu?->name ?? ''; + $this->menuHandle = $menu?->handle ?? ''; + } + + public function saveMenu(): void + { + $this->authorizeStoreManager(); + $data = $this->validate(['menuName' => ['required', 'string', 'max:255'], 'menuHandle' => ['required', 'string', 'max:255']]); + $menu = $this->menuId > 0 ? NavigationMenu::query()->findOrFail($this->menuId) : new NavigationMenu; + $menu->fill(['name' => $data['menuName'], 'handle' => $data['menuHandle']])->save(); + $this->selectMenu($menu->getKey()); + } + + public function addItem(): void + { + $this->authorizeStoreManager(); + $data = $this->validate(['menuId' => ['required', 'integer'], 'label' => ['required', 'string', 'max:255'], 'url' => ['required', 'string', 'max:500'], 'type' => ['required', 'string']]); + $menu = NavigationMenu::query()->findOrFail($data['menuId']); + $menu->items()->create(['label' => $data['label'], 'url' => $data['url'], 'type' => $data['type'], 'position' => (int) $menu->items()->max('position') + 1]); + $this->reset(['label', 'url']); + } + + public function deleteItem(int $itemId): void + { + $this->authorizeStoreManager(); + NavigationItem::query()->where('navigation_menu_id', $this->menuId)->findOrFail($itemId)->delete(); + } + + public function render(): View + { + return view('livewire.admin.navigation.index', ['menus' => NavigationMenu::query()->with('items')->latest()->get(), 'menu' => $this->menuId > 0 ? NavigationMenu::query()->with('items')->find($this->menuId) : null])->layout('layouts.admin'); + } + + private function authorizeStoreManager(): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + } +} diff --git a/app/Livewire/Admin/Orders/Index.php b/app/Livewire/Admin/Orders/Index.php new file mode 100644 index 00000000..bab6b061 --- /dev/null +++ b/app/Livewire/Admin/Orders/Index.php @@ -0,0 +1,89 @@ +authorize('viewAny', Order::class); + } + + public function updatedSearch(): void + { + $this->resetPage(); + } + + public function updatedStatusFilter(): void + { + $this->resetPage(); + } + + public function sortBy(string $field): void + { + if (! in_array($field, ['order_number', 'placed_at', 'total_amount'], true)) { + return; + } + + if ($this->sortField === $field) { + $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc'; + } else { + $this->sortField = $field; + $this->sortDirection = $field === 'order_number' ? 'asc' : 'desc'; + } + + $this->resetPage(); + } + + public function render(): mixed + { + $search = trim($this->search); + + $orders = Order::query() + ->select(['id', 'store_id', 'customer_id', 'order_number', 'email', 'status', 'financial_status', 'fulfillment_status', 'total_amount', 'currency', 'placed_at']) + ->with('customer:id,store_id,first_name,last_name,email') + ->when($search !== '', function ($query) use ($search): void { + $query->where(function ($query) use ($search): void { + $query->where('order_number', 'like', '%'.$search.'%') + ->orWhere('email', 'like', '%'.$search.'%') + ->orWhereHas('customer', function ($customerQuery) use ($search): void { + $customerQuery->where(function ($customerQuery) use ($search): void { + $customerQuery->where('first_name', 'like', '%'.$search.'%') + ->orWhere('last_name', 'like', '%'.$search.'%') + ->orWhere('email', 'like', '%'.$search.'%'); + }); + }); + }); + }) + ->when($this->statusFilter !== 'all', function ($query): void { + match ($this->statusFilter) { + 'pending' => $query->where('financial_status', 'pending'), + 'paid' => $query->where('financial_status', 'paid'), + 'fulfilled' => $query->where(function ($query): void { + $query->where('status', 'fulfilled')->orWhere('fulfillment_status', 'fulfilled'); + }), + 'cancelled' => $query->where('status', 'cancelled'), + 'refunded' => $query->where('financial_status', 'refunded'), + default => null, + }; + }) + ->orderBy($this->sortField, $this->sortDirection) + ->paginate(15); + + return view('livewire.admin.orders.index', compact('orders'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Orders/Show.php b/app/Livewire/Admin/Orders/Show.php new file mode 100644 index 00000000..e6753632 --- /dev/null +++ b/app/Livewire/Admin/Orders/Show.php @@ -0,0 +1,233 @@ + */ + public array $fulfillmentLines = []; + + /** @var array */ + public array $selectedFulfillmentLines = []; + + public string $trackingCompany = ''; + + public string $trackingNumber = ''; + + public string $trackingUrl = ''; + + public ?int $refundAmount = null; + + public string $refundReason = ''; + + /** @var array */ + public array $refundLines = []; + + /** @var array */ + public array $selectedRefundLines = []; + + public bool $showFulfillmentModal = false; + + public bool $showRefundModal = false; + + public string $message = ''; + + public function mount(Order $order): void + { + $this->order = $order; + $this->authorize('view', $this->order); + $this->loadOrder(); + } + + public function openFulfillmentModal(): void + { + $this->authorize('createFulfillment', $this->order); + $this->resetValidation(); + $this->fulfillmentLines = []; + $this->selectedFulfillmentLines = []; + + foreach ($this->order->lines as $line) { + $remaining = max(0, $line->quantity - $this->fulfilledQuantity($line->id)); + + if ($remaining > 0) { + $this->fulfillmentLines[$line->id] = $remaining; + $this->selectedFulfillmentLines[$line->id] = true; + } + } + + $this->showFulfillmentModal = true; + } + + public function openRefundModal(): void + { + $this->authorize('createRefund', $this->order); + $this->resetValidation(); + $this->refundAmount = null; + $this->refundReason = ''; + $this->refundLines = []; + $this->selectedRefundLines = []; + foreach ($this->order->lines as $line) { + $this->refundLines[$line->id] = $line->quantity; + $this->selectedRefundLines[$line->id] = false; + } + $this->showRefundModal = true; + } + + public function confirmPayment(OrderService $orders): void + { + $this->authorize('update', $this->order); + + try { + $orders->confirmPayment($this->order); + $this->message = 'Payment confirmed.'; + $this->loadOrder(); + } catch (\Throwable $exception) { + $this->addError('payment', $exception->getMessage()); + } + } + + public function createFulfillment(FulfillmentService $fulfillments): void + { + $this->authorize('createFulfillment', $this->order); + + $this->validate([ + 'trackingCompany' => ['nullable', 'string', 'max:100'], + 'trackingNumber' => ['nullable', 'string', 'max:100'], + 'trackingUrl' => ['nullable', 'url', 'max:500'], + 'fulfillmentLines' => ['array'], + 'fulfillmentLines.*' => ['integer', 'min:0'], + ]); + + $lines = collect($this->fulfillmentLines) + ->mapWithKeys(fn (int|string $quantity, int|string $lineId): array => [(int) $lineId => (int) $quantity]) + ->filter(fn (int $quantity, int $lineId): bool => (bool) ($this->selectedFulfillmentLines[$lineId] ?? false)) + ->filter(fn (int $quantity): bool => $quantity > 0) + ->map(fn (int $quantity, int $lineId): array => ['order_line_id' => $lineId, 'quantity' => $quantity]) + ->values() + ->all(); + + if ($lines === []) { + $this->addError('fulfillmentLines', 'Select at least one item to fulfill.'); + + return; + } + + try { + $fulfillments->create($this->order, $lines, array_filter([ + 'tracking_company' => $this->trackingCompany, + 'tracking_number' => $this->trackingNumber, + 'tracking_url' => $this->trackingUrl, + ])); + $this->showFulfillmentModal = false; + $this->message = 'Fulfillment created.'; + $this->loadOrder(); + } catch (\Throwable $exception) { + $this->addError('fulfillmentLines', $exception->getMessage()); + } + } + + public function markAsShipped(int $fulfillmentId, FulfillmentService $fulfillments): void + { + $this->authorize('createFulfillment', $this->order); + $fulfillment = $this->order->fulfillments->firstWhere('id', $fulfillmentId); + + abort_if($fulfillment === null, 404); + + try { + $fulfillments->markAsShipped($fulfillment); + $this->message = 'Fulfillment marked as shipped.'; + $this->loadOrder(); + } catch (\Throwable $exception) { + $this->addError('fulfillment', $exception->getMessage()); + } + } + + public function markAsDelivered(int $fulfillmentId, FulfillmentService $fulfillments): void + { + $this->authorize('createFulfillment', $this->order); + $fulfillment = $this->order->fulfillments->firstWhere('id', $fulfillmentId); + + abort_if($fulfillment === null, 404); + + try { + $fulfillments->markAsDelivered($fulfillment); + $this->message = 'Fulfillment marked as delivered.'; + $this->loadOrder(); + } catch (\Throwable $exception) { + $this->addError('fulfillment', $exception->getMessage()); + } + } + + public function createRefund(RefundService $refunds): void + { + $this->authorize('createRefund', $this->order); + $this->validate([ + 'refundAmount' => ['nullable', 'integer', 'min:1'], + 'refundReason' => ['nullable', 'string', 'max:1000'], + 'refundLines' => ['array'], + 'refundLines.*' => ['integer', 'min:0'], + ]); + + $lines = collect($this->refundLines) + ->mapWithKeys(fn (int|string $quantity, int|string $lineId): array => [(int) $lineId => (int) $quantity]) + ->filter(fn (int $quantity, int $lineId): bool => (bool) ($this->selectedRefundLines[$lineId] ?? false)) + ->filter(fn (int $quantity): bool => $quantity > 0) + ->all(); + + if ($lines === [] && $this->refundAmount === null) { + $this->addError('refundAmount', 'Select items or enter a refund amount in cents.'); + + return; + } + + $payment = $this->order->payments->first(); + + if ($payment === null) { + $this->addError('refundAmount', 'No payment is available for this order.'); + + return; + } + + try { + $refunds->create($this->order, $payment, $lines !== [] ? $lines : $this->refundAmount, $this->refundReason ?: null, true); + $this->showRefundModal = false; + $this->message = 'Refund processed.'; + $this->loadOrder(); + } catch (\Throwable $exception) { + $this->addError('refundAmount', $exception->getMessage()); + } + } + + public function render(): mixed + { + return view('livewire.admin.orders.show')->layout('layouts.admin'); + } + + private function loadOrder(): void + { + $this->order = $this->order->refresh()->load([ + 'customer', + 'lines.variant.product', + 'payments', + 'refunds', + 'fulfillments.lines.orderLine', + ]); + } + + private function fulfilledQuantity(int $lineId): int + { + return (int) $this->order->fulfillments + ->whereIn('status', ['shipped', 'delivered']) + ->flatMap->lines + ->where('order_line_id', $lineId) + ->sum('quantity'); + } +} diff --git a/app/Livewire/Admin/Pages/Create.php b/app/Livewire/Admin/Pages/Create.php new file mode 100644 index 00000000..363dec02 --- /dev/null +++ b/app/Livewire/Admin/Pages/Create.php @@ -0,0 +1,42 @@ +authorize('create', Page::class); + $data = $this->validate([ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['nullable', 'string', 'max:255'], + 'bodyHtml' => ['nullable', 'string'], + 'status' => ['required', 'in:draft,published'], + ]); + $page = Page::query()->create([ + 'title' => $data['title'], + 'handle' => $data['handle'] !== '' ? $data['handle'] : str($data['title'])->slug()->toString(), + 'body_html' => $data['bodyHtml'], + 'status' => $data['status'], + 'published_at' => $data['status'] === 'published' ? now() : null, + ]); + $this->redirectRoute('admin.pages.edit', ['page' => $page], navigate: true); + } + + public function render(): View + { + return view('livewire.admin.pages.form', ['page' => null])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Pages/Edit.php b/app/Livewire/Admin/Pages/Edit.php new file mode 100644 index 00000000..5517e02e --- /dev/null +++ b/app/Livewire/Admin/Pages/Edit.php @@ -0,0 +1,53 @@ +page = $page; + $this->title = $page->title; + $this->handle = $page->handle; + $this->bodyHtml = (string) $page->body_html; + $this->status = $page->status->value; + } + + public function save(): void + { + $this->authorize('update', $this->page); + $data = $this->validate([ + 'title' => ['required', 'string', 'max:255'], + 'handle' => ['required', 'string', 'max:255'], + 'bodyHtml' => ['nullable', 'string'], + 'status' => ['required', 'in:draft,published'], + ]); + $this->page->update([ + 'title' => $data['title'], + 'handle' => $data['handle'], + 'body_html' => $data['bodyHtml'], + 'status' => $data['status'], + 'published_at' => $data['status'] === 'published' ? ($this->page->published_at ?? now()) : null, + ]); + $this->dispatch('toast', message: 'Page saved.'); + } + + public function render(): View + { + return view('livewire.admin.pages.form')->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Pages/Form.php b/app/Livewire/Admin/Pages/Form.php new file mode 100644 index 00000000..76345d84 --- /dev/null +++ b/app/Livewire/Admin/Pages/Form.php @@ -0,0 +1,13 @@ +resetPage(); + } + + public function updatedStatus(): void + { + $this->resetPage(); + } + + public function delete(int $pageId): void + { + $page = Page::query()->findOrFail($pageId); + $this->authorize('delete', $page); + $page->delete(); + $this->dispatch('toast', message: 'Page deleted.'); + } + + public function render(): View + { + $pages = Page::query() + ->when($this->search !== '', fn ($query) => $query->where(function ($nested): void { + $nested->where('title', 'like', '%'.$this->search.'%') + ->orWhere('handle', 'like', '%'.$this->search.'%'); + })) + ->when($this->status !== 'all', fn ($query) => $query->where('status', $this->status)) + ->latest('updated_at') + ->paginate(20); + + return view('livewire.admin.pages.index', compact('pages'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Products/Form.php b/app/Livewire/Admin/Products/Form.php new file mode 100644 index 00000000..48281d16 --- /dev/null +++ b/app/Livewire/Admin/Products/Form.php @@ -0,0 +1,62 @@ +product = $product; + + if ($product !== null) { + $this->title = $product->title; + $this->description = (string) $product->description; + $this->vendor = (string) $product->vendor; + $this->productType = (string) $product->product_type; + $this->status = $product->status->value; + $this->priceAmount = (int) ($product->defaultVariant()?->price_amount ?? 0); + } + } + + public function save(ProductService $products): void + { + $data = $this->validate(['title' => ['required', 'string', 'max:255'], 'description' => ['nullable', 'string'], 'vendor' => ['nullable', 'string', 'max:255'], 'productType' => ['nullable', 'string', 'max:255'], 'priceAmount' => ['required', 'integer', 'min:0'], 'status' => ['required', 'in:draft,active,archived']]); + $payload = ['title' => $data['title'], 'description' => $data['description'], 'vendor' => $data['vendor'], 'product_type' => $data['productType'], 'status' => ProductStatus::from($data['status']), 'variants' => [['title' => 'Default', 'price_amount' => $data['priceAmount'], 'is_default' => true]]]; + + if ($this->product === null) { + $this->authorize('create', Product::class); + $this->product = $products->create(app('current_store'), $payload); + } else { + $this->authorize('update', $this->product); + $products->update($this->product, $payload); + } + + $this->message = 'Product saved'; + } + + public function render(): mixed + { + return view('livewire.admin.products.form')->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Products/Index.php b/app/Livewire/Admin/Products/Index.php new file mode 100644 index 00000000..b3bfa11d --- /dev/null +++ b/app/Livewire/Admin/Products/Index.php @@ -0,0 +1,68 @@ + */ + public array $selectedIds = []; + + public bool $selectAll = false; + + public string $message = ''; + + public function updatedSelectAll(bool $selected): void + { + $this->selectedIds = $selected ? $this->filteredProductsQuery()->pluck('id')->all() : []; + } + + public function archive(int $productId, ProductService $products): void + { + $product = Product::query()->findOrFail($productId); + $this->authorize('archive', $product); + $products->transitionStatus($product, ProductStatus::Archived); + $this->message = 'Product archived'; + } + + public function bulkArchive(ProductService $products): void + { + foreach ($this->selectedIds as $productId) { + $product = Product::query()->find($productId); + + if ($product !== null) { + $this->authorize('archive', $product); + $products->transitionStatus($product, ProductStatus::Archived); + } + } + + $this->reset(['selectedIds', 'selectAll']); + $this->message = 'Selected products archived.'; + } + + public function render(): mixed + { + $products = $this->filteredProductsQuery()->with(['variants.inventory'])->latest()->paginate(15); + + return view('livewire.admin.products.index', compact('products'))->layout('layouts.admin'); + } + + private function filteredProductsQuery(): \Illuminate\Database\Eloquent\Builder + { + return Product::query()->when($this->search !== '', fn ($query) => $query->where(function ($nested): void { + $nested->where('title', 'like', '%'.$this->search.'%')->orWhere('handle', 'like', '%'.$this->search.'%'); + }))->when($this->status !== 'all', fn ($query) => $query->where('status', $this->status))->when($this->productType !== 'all', fn ($query) => $query->where('product_type', $this->productType))->when($this->vendor !== '', fn ($query) => $query->where('vendor', 'like', '%'.$this->vendor.'%')); + } +} diff --git a/app/Livewire/Admin/Search/Settings.php b/app/Livewire/Admin/Search/Settings.php new file mode 100644 index 00000000..c5d94590 --- /dev/null +++ b/app/Livewire/Admin/Search/Settings.php @@ -0,0 +1,53 @@ +first(); + $this->enabled = $settings?->enabled ?? true; + $this->synonyms = collect($settings?->synonyms ?? [])->map(fn ($group): string => is_array($group) ? implode(',', $group) : (string) $group)->implode("\n"); + $this->stopwords = implode("\n", $settings?->stopwords ?? []); + } + + public function save(): void + { + $this->authorizeStoreManager(); + $data = $this->validate(['enabled' => ['boolean'], 'synonyms' => ['nullable', 'string'], 'stopwords' => ['nullable', 'string']]); + SearchSetting::query()->updateOrCreate(['store_id' => app('current_store')->getKey()], ['enabled' => $data['enabled'], 'synonyms' => collect(preg_split('/\R/', $data['synonyms'] ?? '', -1, PREG_SPLIT_NO_EMPTY))->map(fn (string $line): array => array_values(array_filter(array_map('trim', explode(',', $line)))))->filter()->values()->all(), 'stopwords' => array_values(array_filter(array_map('trim', preg_split('/\R/', $data['stopwords'] ?? '', -1, PREG_SPLIT_NO_EMPTY))))]); + $this->message = 'Search settings saved.'; + } + + public function reindex(SearchService $search): void + { + $this->authorizeStoreManager(); + Product::query()->each(fn (Product $product) => $search->syncProduct($product)); + $this->message = 'Search index rebuilt.'; + } + + public function render(): View + { + return view('livewire.admin.search.settings')->layout('layouts.admin'); + } + + private function authorizeStoreManager(): void + { + abort_unless(auth()->user()?->canManageStore(app('current_store')), 403); + } +} diff --git a/app/Livewire/Admin/Section.php b/app/Livewire/Admin/Section.php new file mode 100644 index 00000000..7cfee8ac --- /dev/null +++ b/app/Livewire/Admin/Section.php @@ -0,0 +1,57 @@ +heading = match (true) { + request()->is('admin/inventory') => 'Inventory', + request()->is('admin/collections') => 'Collections', + request()->is('admin/themes*') => 'Themes', + request()->is('admin/pages') => 'Pages', + request()->is('admin/navigation') => 'Navigation', + request()->is('admin/apps*') => 'Apps', + request()->is('admin/developers') => 'Developers', + request()->is('admin/analytics') => 'Analytics', + request()->is('admin/search/settings') => 'Search settings', + default => $this->heading, + }; + } + + public function render(): mixed + { + return view('livewire.admin.section', ['rows' => $this->rows()])->layout('layouts.admin'); + } + + /** @return list */ + private function rows(): array + { + return match (true) { + request()->is('admin/inventory') => InventoryItem::query()->with('variant.product')->latest()->take(50)->get()->map(fn (InventoryItem $item): array => ['title' => $item->variant?->product?->title ?? 'Unknown product', 'subtitle' => $item->variant?->title ?? 'Unknown variant', 'value' => $item->availableQuantity().' available'])->all(), + request()->is('admin/collections*') => Collection::query()->withCount('products')->latest()->take(50)->get()->map(fn (Collection $collection): array => ['title' => $collection->title, 'subtitle' => $collection->status->value, 'value' => $collection->products_count.' products'])->all(), + request()->is('admin/themes*') => Theme::query()->latest()->take(50)->get()->map(fn (Theme $theme): array => ['title' => $theme->name, 'subtitle' => 'Version '.$theme->version, 'value' => $theme->status->value])->all(), + request()->is('admin/pages*') => Page::query()->latest()->take(50)->get()->map(fn (Page $page): array => ['title' => $page->title, 'subtitle' => '/pages/'.$page->handle, 'value' => $page->status->value])->all(), + request()->is('admin/navigation') => NavigationMenu::query()->withCount('items')->latest()->take(50)->get()->map(fn (NavigationMenu $menu): array => ['title' => $menu->name, 'subtitle' => $menu->handle, 'value' => $menu->items_count.' links'])->all(), + request()->is('admin/apps*') => AppInstallation::query()->with('app')->latest()->take(50)->get()->map(fn (AppInstallation $installation): array => ['title' => $installation->app?->name ?? 'Installed app', 'subtitle' => $installation->status, 'value' => 'Connected'])->all(), + request()->is('admin/developers') => WebhookSubscription::query()->latest()->take(50)->get()->map(fn (WebhookSubscription $subscription): array => ['title' => $subscription->event, 'subtitle' => $subscription->target_url, 'value' => $subscription->status])->all(), + request()->is('admin/analytics') => AnalyticsDaily::query()->latest('date')->take(30)->get()->map(fn (AnalyticsDaily $day): array => ['title' => $day->date->toDateString(), 'subtitle' => $day->visits_count.' visits', 'value' => $day->orders_count.' orders · €'.number_format($day->revenue_amount / 100, 2)])->all(), + request()->is('admin/search/settings') => (($settings = SearchSetting::query()->first()) === null ? [] : [['title' => 'Search indexing', 'subtitle' => count($settings->synonyms ?? []).' synonym groups', 'value' => $settings->enabled ? 'Enabled' : 'Disabled']]), + default => [], + }; + } +} diff --git a/app/Livewire/Admin/Settings/Domains.php b/app/Livewire/Admin/Settings/Domains.php new file mode 100644 index 00000000..a23bd904 --- /dev/null +++ b/app/Livewire/Admin/Settings/Domains.php @@ -0,0 +1,74 @@ +authorize('update', app('current_store')); + } + + public function addDomain(): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'newHostname' => ['required', 'string', 'max:255', 'regex:/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i'], + 'newType' => ['required', 'in:storefront,admin,api'], + ]); + $store = app('current_store'); + $isPrimary = ! StoreDomain::query()->where('store_id', $store->getKey())->where('type', $data['newType'])->exists(); + StoreDomain::create([ + 'store_id' => $store->getKey(), + 'hostname' => strtolower($data['newHostname']), + 'type' => $data['newType'], + 'is_primary' => $isPrimary, + 'tls_mode' => 'managed', + ]); + $this->reset(['newHostname', 'showModal']); + $this->newType = 'storefront'; + $this->dispatch('toast', message: 'Domain added.'); + } + + public function removeDomain(int $domainId): void + { + $this->authorize('update', app('current_store')); + $domain = StoreDomain::query()->where('store_id', app('current_store')->getKey())->findOrFail($domainId); + $wasPrimary = $domain->is_primary; + $type = $domain->type->value; + $domain->delete(); + + if ($wasPrimary) { + StoreDomain::query()->where('store_id', app('current_store')->getKey())->where('type', $type)->latest('id')->first()?->update(['is_primary' => true]); + } + $this->dispatch('toast', message: 'Domain removed.'); + } + + public function setPrimary(int $domainId): void + { + $this->authorize('update', app('current_store')); + $domain = StoreDomain::query()->where('store_id', app('current_store')->getKey())->findOrFail($domainId); + DB::transaction(function () use ($domain): void { + StoreDomain::query()->where('store_id', $domain->store_id)->where('type', $domain->type->value)->update(['is_primary' => false]); + $domain->update(['is_primary' => true]); + }); + $this->dispatch('toast', message: 'Primary domain updated.'); + } + + public function render(): mixed + { + $domains = StoreDomain::query()->where('store_id', app('current_store')->getKey())->orderByDesc('is_primary')->orderBy('hostname')->get(); + + return view('livewire.admin.settings.domains', compact('domains'))->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Settings/General.php b/app/Livewire/Admin/Settings/General.php new file mode 100644 index 00000000..4febfa36 --- /dev/null +++ b/app/Livewire/Admin/Settings/General.php @@ -0,0 +1,67 @@ +authorize('update', app('current_store')); + $store = app('current_store'); + $settings = $store->settings; + $general = $settings?->general_json ?? []; + $this->storeName = (string) ($general['store_name'] ?? $store->name); + $this->storeHandle = (string) $store->handle; + $this->defaultCurrency = (string) $store->default_currency; + $this->defaultLocale = (string) $store->default_locale; + $this->timezone = (string) $store->timezone; + } + + public function save(): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'storeName' => ['required', 'string', 'max:255'], + 'defaultCurrency' => ['required', 'string', 'size:3'], + 'defaultLocale' => ['required', 'string', 'max:10'], + 'timezone' => ['required', 'timezone'], + ]); + $store = app('current_store'); + $settings = StoreSettings::query()->first(); + $store->update([ + 'name' => $data['storeName'], + 'default_currency' => strtoupper($data['defaultCurrency']), + 'default_locale' => $data['defaultLocale'], + 'timezone' => $data['timezone'], + ]); + StoreSettings::updateOrCreate( + ['store_id' => $store->getKey()], + ['general_json' => array_merge($settings?->general_json ?? [], ['store_name' => $data['storeName']])], + ); + $this->message = 'General settings saved.'; + } + + public function render(): mixed + { + return view('livewire.admin.settings.general', [ + 'currencies' => ['EUR' => 'Euro (EUR)', 'USD' => 'US Dollar (USD)', 'GBP' => 'British Pound (GBP)', 'CHF' => 'Swiss Franc (CHF)', 'CAD' => 'Canadian Dollar (CAD)', 'AUD' => 'Australian Dollar (AUD)'], + 'locales' => ['en' => 'English', 'de' => 'German', 'fr' => 'French', 'es' => 'Spanish'], + 'timezones' => \DateTimeZone::listIdentifiers(), + ])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Settings/Shipping.php b/app/Livewire/Admin/Settings/Shipping.php new file mode 100644 index 00000000..40032a4a --- /dev/null +++ b/app/Livewire/Admin/Settings/Shipping.php @@ -0,0 +1,210 @@ + */ + public array $zoneCountries = []; + + public ?ShippingRate $editingRate = null; + + public ?int $editingRateZoneId = null; + + public string $rateName = ''; + + public string $rateType = 'flat'; + + /** @var array */ + public array $rateConfig = ['price' => 0, 'min' => null, 'max' => null]; + + public bool $rateActive = true; + + /** @var array */ + public array $testAddress = ['country_code' => 'DE', 'province_code' => '', 'city' => '', 'postal_code' => '']; + + /** @var array|null */ + public ?array $testResult = null; + + public bool $showZoneModal = false; + + public bool $showRateModal = false; + + public string $message = ''; + + public function mount(): void + { + $this->authorize('update', app('current_store')); + } + + public function openZoneModal(?int $zoneId = null): void + { + $this->authorize('update', app('current_store')); + $this->resetValidation(); + $this->editingZone = $zoneId === null ? null : $this->storeZones()->findOrFail($zoneId); + $this->zoneName = (string) ($this->editingZone?->name ?? ''); + $this->zoneCountries = array_map('strtoupper', $this->editingZone?->countries_json ?? []); + $this->showZoneModal = true; + } + + public function saveZone(): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'zoneName' => ['required', 'string', 'max:255'], + 'zoneCountries' => ['array'], + 'zoneCountries.*' => ['string', 'size:2'], + ]); + $attributes = [ + 'name' => $data['zoneName'], + 'countries_json' => array_values(array_unique(array_map('strtoupper', $data['zoneCountries']))), + 'regions_json' => $this->editingZone?->regions_json ?? [], + ]; + + if ($this->editingZone === null) { + ShippingZone::create(['store_id' => app('current_store')->getKey()] + $attributes); + } else { + $this->editingZone->update($attributes); + } + + $this->showZoneModal = false; + $this->message = 'Shipping zone saved.'; + } + + public function deleteZone(int $zoneId): void + { + $this->authorize('update', app('current_store')); + $this->storeZones()->findOrFail($zoneId)->delete(); + $this->message = 'Shipping zone deleted.'; + } + + public function openRateModal(int $zoneId, ?int $rateId = null): void + { + $this->authorize('update', app('current_store')); + $zone = $this->storeZones()->findOrFail($zoneId); + $this->resetValidation(); + $this->editingRateZoneId = $zone->id; + $this->editingRate = $rateId === null ? null : $zone->rates()->findOrFail($rateId); + $this->rateName = (string) ($this->editingRate?->name ?? ''); + $this->rateType = (string) ($this->editingRate?->type ?? 'flat'); + $config = $this->editingRate?->config_json ?? []; + $range = $config['ranges'][0] ?? []; + $this->rateConfig = [ + 'price' => (int) ($this->editingRate?->price_amount ?? $range['amount'] ?? 0), + 'min' => $range['min_g'] ?? $range['min_amount'] ?? null, + 'max' => $range['max_g'] ?? $range['max_amount'] ?? null, + ]; + $this->rateActive = $this->editingRate?->is_active ?? true; + $this->showRateModal = true; + } + + public function saveRate(): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'editingRateZoneId' => ['required', 'integer'], + 'rateName' => ['required', 'string', 'max:255'], + 'rateType' => ['required', 'in:flat,weight,price,carrier'], + 'rateConfig.price' => ['nullable', 'integer', 'min:0'], + 'rateConfig.min' => ['nullable', 'integer', 'min:0'], + 'rateConfig.max' => ['nullable', 'integer', 'gte:rateConfig.min'], + 'rateActive' => ['boolean'], + ]); + + if ($data['rateType'] !== 'carrier' && ($data['rateConfig']['price'] ?? null) === null) { + $this->addError('rateConfig.price', 'Enter a price for this rate.'); + + return; + } + + $data['rateConfig']['price'] ??= 0; + $zone = $this->storeZones()->findOrFail($data['editingRateZoneId']); + $config = []; + + if (in_array($data['rateType'], ['weight', 'price'], true)) { + $config['ranges'] = [[ + $data['rateType'] === 'weight' ? 'min_g' : 'min_amount' => $data['rateConfig']['min'] ?? 0, + $data['rateType'] === 'weight' ? 'max_g' : 'max_amount' => $data['rateConfig']['max'] ?? PHP_INT_MAX, + 'amount' => $data['rateConfig']['price'], + ]]; + } + $attributes = [ + 'name' => $data['rateName'], + 'type' => $data['rateType'], + 'price_amount' => $data['rateConfig']['price'], + 'currency' => app('current_store')->default_currency, + 'config_json' => $config, + 'is_active' => (bool) $data['rateActive'], + ]; + + if ($this->editingRate === null) { + $zone->rates()->create($attributes); + } else { + $this->editingRate->update($attributes); + } + + $this->showRateModal = false; + $this->message = 'Shipping rate saved.'; + } + + public function deleteRate(int $rateId): void + { + $this->authorize('update', app('current_store')); + $rate = ShippingRate::query()->whereHas('zone', fn ($query) => $query->where('store_id', app('current_store')->getKey()))->findOrFail($rateId); + $rate->delete(); + $this->message = 'Shipping rate deleted.'; + } + + public function toggleRate(int $rateId): void + { + $this->authorize('update', app('current_store')); + $rate = ShippingRate::query()->whereHas('zone', fn ($query) => $query->where('store_id', app('current_store')->getKey()))->findOrFail($rateId); + $rate->update(['is_active' => ! $rate->is_active]); + } + + public function testShippingAddress(ShippingCalculator $shipping): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'testAddress.country_code' => ['required', 'string', 'size:2'], + 'testAddress.province_code' => ['nullable', 'string', 'max:10'], + 'testAddress.city' => ['nullable', 'string', 'max:255'], + 'testAddress.postal_code' => ['nullable', 'string', 'max:30'], + ]); + $rates = $shipping->getAvailableRates(app('current_store'), $data['testAddress']); + $this->testResult = [ + 'zone' => $rates->first()?->zone?->name, + 'rates' => $rates->map(fn (ShippingRate $rate): array => ['name' => $rate->name, 'price_amount' => $rate->price_amount, 'currency' => $rate->currency])->values()->all(), + ]; + } + + public function render(): mixed + { + return view('livewire.admin.settings.shipping', [ + 'zones' => $this->storeZones()->with('rates')->latest()->get(), + 'countries' => $this->countryOptions(), + ])->layout('layouts.admin'); + } + + private function storeZones(): \Illuminate\Database\Eloquent\Builder + { + return ShippingZone::query()->where('store_id', app('current_store')->getKey()); + } + + /** @return array */ + private function countryOptions(): array + { + return [ + 'AU' => 'Australia', 'AT' => 'Austria', 'BE' => 'Belgium', 'BR' => 'Brazil', 'CA' => 'Canada', 'CH' => 'Switzerland', 'CN' => 'China', 'DE' => 'Germany', 'DK' => 'Denmark', 'ES' => 'Spain', 'FI' => 'Finland', 'FR' => 'France', 'GB' => 'United Kingdom', 'IE' => 'Ireland', 'IN' => 'India', 'IT' => 'Italy', 'JP' => 'Japan', 'LU' => 'Luxembourg', 'MX' => 'Mexico', 'NL' => 'Netherlands', 'NO' => 'Norway', 'NZ' => 'New Zealand', 'PL' => 'Poland', 'PT' => 'Portugal', 'SE' => 'Sweden', 'SG' => 'Singapore', 'US' => 'United States', + ]; + } +} diff --git a/app/Livewire/Admin/Settings/Taxes.php b/app/Livewire/Admin/Settings/Taxes.php new file mode 100644 index 00000000..a5271139 --- /dev/null +++ b/app/Livewire/Admin/Settings/Taxes.php @@ -0,0 +1,101 @@ + */ + public array $manualRates = []; + + public string $message = ''; + + public function mount(): void + { + $this->authorize('update', app('current_store')); + $settings = TaxSettings::query()->first(); + $storedMode = (string) ($settings?->mode ?? 'manual'); + $this->mode = in_array($storedMode, ['manual', 'provider'], true) ? $storedMode : 'manual'; + $this->pricesIncludeTax = (bool) ($settings?->prices_include_tax ?? $storedMode === 'inclusive'); + $providerConfig = $settings?->provider_config_json ?? []; + $this->provider = (string) ($settings?->provider ?? $providerConfig['provider'] ?? 'none'); + $this->providerKeyConfigured = isset($providerConfig['api_key_encrypted']) || isset($providerConfig['api_key']); + $this->manualRates = collect($settings?->rates_json ?? []) + ->map(fn (int|float|string $rate, string $zone): array => ['zone_name' => $zone, 'rate_percentage' => number_format(((float) $rate) / 100, 2, '.', '')]) + ->values() + ->all(); + + if ($this->manualRates === []) { + $this->manualRates[] = ['zone_name' => 'DE', 'rate_percentage' => '19.00']; + } + } + + public function addManualRate(): void + { + $this->manualRates[] = ['zone_name' => '', 'rate_percentage' => '']; + } + + public function removeManualRate(int $index): void + { + unset($this->manualRates[$index]); + $this->manualRates = array_values($this->manualRates); + } + + public function save(): void + { + $this->authorize('update', app('current_store')); + $data = $this->validate([ + 'mode' => ['required', 'in:manual,provider'], + 'pricesIncludeTax' => ['boolean'], + 'provider' => ['required', 'in:none,stripe_tax'], + 'providerApiKey' => ['nullable', 'string', 'max:500'], + 'manualRates' => ['array'], + 'manualRates.*.zone_name' => ['required', 'string', 'max:50'], + 'manualRates.*.rate_percentage' => ['required', 'numeric', 'min:0', 'max:100'], + ]); + $rates = collect($data['manualRates']) + ->mapWithKeys(fn (array $rate): array => [strtoupper(trim($rate['zone_name'])) => (int) round(((float) $rate['rate_percentage']) * 100)]) + ->all(); + $providerConfig = ['provider' => $data['provider']]; + $existingApiKey = TaxSettings::query()->first()?->provider_config_json['api_key_encrypted'] ?? null; + + if ($data['providerApiKey'] !== '') { + $providerConfig['api_key_encrypted'] = Crypt::encryptString($data['providerApiKey']); + } elseif ($existingApiKey !== null) { + $providerConfig['api_key_encrypted'] = $existingApiKey; + } + + TaxSettings::updateOrCreate( + ['store_id' => app('current_store')->getKey()], + [ + 'mode' => $data['mode'], + 'provider' => $data['provider'], + 'prices_include_tax' => (bool) $data['pricesIncludeTax'], + 'default_rate_basis_points' => (int) (array_values($rates)[0] ?? 0), + 'rates_json' => $rates, + 'provider_config_json' => $providerConfig, + ], + ); + $this->providerApiKey = ''; + $this->providerKeyConfigured = isset($providerConfig['api_key_encrypted']); + $this->message = 'Tax settings saved.'; + } + + public function render(): mixed + { + return view('livewire.admin.settings.taxes')->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Themes/Editor.php b/app/Livewire/Admin/Themes/Editor.php new file mode 100644 index 00000000..32c5e117 --- /dev/null +++ b/app/Livewire/Admin/Themes/Editor.php @@ -0,0 +1,36 @@ +theme = $theme; + $this->settingsJson = json_encode($theme->settings?->settings_json ?? [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: '{}'; + } + + public function save(): void + { + $this->authorize('update', $this->theme); + $data = $this->validate(['settingsJson' => ['required', 'json']]); + $this->theme->settings()->updateOrCreate( + ['theme_id' => $this->theme->getKey()], + ['settings_json' => json_decode($data['settingsJson'], true, 512, JSON_THROW_ON_ERROR)], + ); + $this->dispatch('toast', message: 'Theme settings saved.'); + } + + public function render(): View + { + return view('livewire.admin.themes.editor')->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Admin/Themes/Index.php b/app/Livewire/Admin/Themes/Index.php new file mode 100644 index 00000000..19120ffc --- /dev/null +++ b/app/Livewire/Admin/Themes/Index.php @@ -0,0 +1,48 @@ +findOrFail($themeId); + $this->authorize('publish', $theme); + Theme::query()->where('store_id', $theme->store_id)->whereKeyNot($theme->id)->where('status', ThemeStatus::Published)->update(['status' => ThemeStatus::Draft]); + $theme->update(['status' => ThemeStatus::Published]); + $this->dispatch('toast', message: 'Theme published.'); + } + + public function duplicate(int $themeId): void + { + $theme = Theme::query()->with(['files', 'settings'])->findOrFail($themeId); + $this->authorize('create', Theme::class); + $copy = $theme->replicate(['status']); + $copy->name = $theme->name.' copy'; + $copy->status = ThemeStatus::Draft; + $copy->save(); + foreach ($theme->files as $file) { + $copy->files()->create($file->only(['path', 'content', 'storage_key', 'sha256', 'byte_size'])); + } + $copy->settings()->create(['settings_json' => $theme->settings?->settings_json ?? []]); + $this->dispatch('toast', message: 'Theme duplicated.'); + } + + public function delete(int $themeId): void + { + $theme = Theme::query()->findOrFail($themeId); + $this->authorize('delete', $theme); + abort_if($theme->status === ThemeStatus::Published, 422, 'Publish another theme before deleting this one.'); + $theme->delete(); + } + + public function render(): View + { + return view('livewire.admin.themes.index', ['themes' => Theme::query()->latest()->get()])->layout('layouts.admin'); + } +} diff --git a/app/Livewire/Storefront/Account/Addresses/Index.php b/app/Livewire/Storefront/Account/Addresses/Index.php new file mode 100644 index 00000000..6c3dbb31 --- /dev/null +++ b/app/Livewire/Storefront/Account/Addresses/Index.php @@ -0,0 +1,30 @@ +validate(['label' => ['nullable', 'string', 'max:255'], 'address1' => ['required', 'string', 'max:500'], 'city' => ['required', 'string', 'max:255'], 'countryCode' => ['required', 'size:2'], 'postalCode' => ['required', 'max:20']]); + auth('customer')->user()->addresses()->create(['label' => $data['label'], 'address_json' => ['address1' => $data['address1'], 'city' => $data['city'], 'country_code' => $data['countryCode'], 'postal_code' => $data['postalCode']], 'is_default' => auth('customer')->user()->addresses()->count() === 0]); + $this->reset(['label', 'address1', 'city', 'postalCode']); + } + + public function render(): mixed + { + return view('livewire.storefront.account.addresses.index', ['addresses' => auth('customer')->user()->addresses()->latest()->get()])->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Auth/ForgotPassword.php b/app/Livewire/Storefront/Account/Auth/ForgotPassword.php new file mode 100644 index 00000000..9f0a5bd1 --- /dev/null +++ b/app/Livewire/Storefront/Account/Auth/ForgotPassword.php @@ -0,0 +1,25 @@ +validate(['email' => ['required', 'email']]); + Password::broker('customers')->sendResetLink(['email' => $this->email]); + $this->message = 'If an account exists for that email, a reset link has been sent.'; + } + + public function render(): mixed + { + return view('livewire.storefront.account.auth.forgot-password')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Auth/Login.php b/app/Livewire/Storefront/Account/Auth/Login.php new file mode 100644 index 00000000..e9c2d33b --- /dev/null +++ b/app/Livewire/Storefront/Account/Auth/Login.php @@ -0,0 +1,59 @@ +validate(['email' => ['required', 'email'], 'password' => ['required', 'string']]); + $key = 'customer-login|'.request()->ip(); + + if (RateLimiter::tooManyAttempts($key, 5)) { + $this->addError('email', 'Too many attempts. Try again later.'); + + return; + } + + RateLimiter::hit($key, 60); + + if (! Auth::guard('customer')->attempt([...$credentials, 'status' => 'active'], $this->remember)) { + $this->addError('email', 'Invalid credentials'); + + return; + } + + RateLimiter::clear($key); + session()->regenerate(); + $customer = Auth::guard('customer')->user(); + $store = app('current_store'); + $guestCartId = session('cart_id_'.$store->getKey(), session('cart_id')); + $guestCart = $guestCartId === null ? null : Cart::withoutGlobalScopes()->whereKey($guestCartId)->where('store_id', $store->getKey())->whereNull('customer_id')->where('status', 'active')->first(); + $customerCart = $customer->carts()->where('status', 'active')->latest()->first() ?? $carts->create($store, $customer); + + if ($guestCart !== null && $guestCart->getKey() !== $customerCart->getKey()) { + $carts->mergeOnLogin($guestCart, $customerCart); + } else { + session(['cart_id_'.$store->getKey() => $customerCart->getKey(), 'cart_id' => $customerCart->getKey()]); + } + + $this->redirect(route('account.dashboard')); + } + + public function render(): mixed + { + return view('livewire.storefront.account.auth.login')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Auth/Register.php b/app/Livewire/Storefront/Account/Auth/Register.php new file mode 100644 index 00000000..0e4a557e --- /dev/null +++ b/app/Livewire/Storefront/Account/Auth/Register.php @@ -0,0 +1,36 @@ +validate(['firstName' => ['required', 'string', 'max:255'], 'lastName' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', Rule::unique('customers', 'email')->where('store_id', app('current_store')->getKey())], 'password' => ['required', 'min:8', 'same:passwordConfirmation'], 'marketingOptIn' => ['boolean']]); + $customer = Customer::create(['store_id' => app('current_store')->getKey(), 'first_name' => $data['firstName'], 'last_name' => $data['lastName'], 'name' => trim($data['firstName'].' '.$data['lastName']), 'email' => $data['email'], 'password_hash' => $data['password'], 'marketing_opt_in' => $data['marketingOptIn'], 'status' => 'active']); + Auth::guard('customer')->login($customer); + $this->redirect(route('account.dashboard')); + } + + public function render(): mixed + { + return view('livewire.storefront.account.auth.register')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Auth/ResetPassword.php b/app/Livewire/Storefront/Account/Auth/ResetPassword.php new file mode 100644 index 00000000..7472c578 --- /dev/null +++ b/app/Livewire/Storefront/Account/Auth/ResetPassword.php @@ -0,0 +1,46 @@ +token = $token; + $this->email = request()->string('email')->toString(); + } + + public function resetPassword(): void + { + $data = $this->validate(['email' => ['required', 'email'], 'password' => ['required', 'min:8', 'same:passwordConfirmation']]); + $status = Password::broker('customers')->reset(['email' => $data['email'], 'password' => $data['password'], 'password_confirmation' => $this->passwordConfirmation, 'token' => $this->token], function (Customer $customer, string $password): void { + $customer->password_hash = $password; + $customer->save(); + }); + + if ($status !== Password::PASSWORD_RESET) { + $this->addError('email', __($status)); + + return; + } + + $this->redirect(route('account.login'), navigate: true); + } + + public function render(): mixed + { + return view('livewire.storefront.account.auth.reset-password')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Dashboard.php b/app/Livewire/Storefront/Account/Dashboard.php new file mode 100644 index 00000000..3cd164f6 --- /dev/null +++ b/app/Livewire/Storefront/Account/Dashboard.php @@ -0,0 +1,15 @@ +user()->loadCount('orders'); + + return view('livewire.storefront.account.dashboard', compact('customer'))->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Orders/Index.php b/app/Livewire/Storefront/Account/Orders/Index.php new file mode 100644 index 00000000..b5a0da0f --- /dev/null +++ b/app/Livewire/Storefront/Account/Orders/Index.php @@ -0,0 +1,13 @@ + auth('customer')->user()->orders()->latest()->get()])->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Account/Orders/Show.php b/app/Livewire/Storefront/Account/Orders/Show.php new file mode 100644 index 00000000..2e385dfd --- /dev/null +++ b/app/Livewire/Storefront/Account/Orders/Show.php @@ -0,0 +1,21 @@ +order = auth('customer')->user()->orders()->with('lines')->where('order_number', $orderNumber)->firstOrFail(); + } + + public function render(): mixed + { + return view('livewire.storefront.account.orders.show')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Cart/Show.php b/app/Livewire/Storefront/Cart/Show.php new file mode 100644 index 00000000..949fd1a6 --- /dev/null +++ b/app/Livewire/Storefront/Cart/Show.php @@ -0,0 +1,146 @@ +cart = $carts->getOrCreateForSession(app('current_store'), auth('customer')->user()); + $this->discountCode = (string) ($this->cart->discount_code ?? ''); + $this->refreshCart($discounts); + } + + public function increase(int $lineId, CartService $carts, DiscountService $discounts): void + { + $line = $this->cart->lines->firstWhere('id', $lineId); + + if ($line === null) { + return; + } + + $carts->updateLineQuantity($this->cart, $lineId, $line->quantity + 1); + $this->refreshCart($discounts); + } + + public function decrease(int $lineId, CartService $carts, DiscountService $discounts): void + { + $line = $this->cart->lines->firstWhere('id', $lineId); + + if ($line === null) { + return; + } + + if ($line->quantity > 1) { + $carts->updateLineQuantity($this->cart, $lineId, $line->quantity - 1); + } + + $this->refreshCart($discounts); + } + + public function remove(int $lineId, CartService $carts, DiscountService $discounts): void + { + if (! $this->cart->lines->contains('id', $lineId)) { + return; + } + + $carts->removeLine($this->cart, $lineId); + $this->message = 'Item removed from your cart.'; + $this->refreshCart($discounts); + } + + public function checkout(CheckoutService $checkouts): void + { + if ($this->cart->lines->isEmpty()) { + $this->addError('cart', 'Your cart is empty.'); + + return; + } + + $checkout = $checkouts->create($this->cart, auth('customer')->user()?->email ?? 'guest@example.com', auth('customer')->user()); + $this->redirect(route('checkout.show', $checkout), navigate: true); + } + + public function applyDiscount(DiscountService $discounts): void + { + $this->validate(['discountCode' => ['required', 'string', 'max:64']]); + + try { + $discount = $discounts->validate(trim($this->discountCode), app('current_store'), $this->cart); + $this->cart->update(['discount_code' => $discount->code]); + $this->discountCode = $discount->code; + $this->message = 'Discount applied.'; + $this->resetValidation('discountCode'); + $this->refreshCart($discounts); + } catch (InvalidDiscountException $exception) { + $this->addError('discountCode', $exception->getMessage()); + } + } + + public function removeDiscount(DiscountService $discounts): void + { + $this->cart->update(['discount_code' => null]); + $this->discountCode = ''; + $this->message = 'Discount removed.'; + $this->resetValidation('discountCode'); + $this->refreshCart($discounts); + } + + public function formatMoney(int|float $amount): string + { + return number_format((float) $amount / 100, 2, '.', ',').' '.($this->cart->currency ?: 'EUR'); + } + + private function refreshCart(DiscountService $discounts): void + { + $this->cart = $this->cart->refresh()->load(['lines.variant.product.media', 'lines.variant.product.collections', 'lines.variant.inventory']); + $this->discountAmount = $this->calculateDiscountAmount($discounts); + $subtotal = (int) $this->cart->lines->sum('line_subtotal_amount'); + $this->totalAmount = max(0, $subtotal - $this->discountAmount); + } + + private function calculateDiscountAmount(DiscountService $discounts): int + { + if ($this->cart->discount_code === null || $this->cart->lines->isEmpty()) { + return 0; + } + + try { + $discount = $discounts->validate($this->cart->discount_code, app('current_store'), $this->cart); + } catch (InvalidDiscountException) { + return 0; + } + + $subtotal = (int) $this->cart->lines->sum('line_subtotal_amount'); + $result = $discounts->calculate($discount, $subtotal, $this->cart->lines->map(fn ($line): array => [ + 'line_id' => $line->id, + 'amount' => $line->line_subtotal_amount, + 'product_id' => $line->variant->product_id, + 'collection_ids' => $line->variant->product->collections->modelKeys(), + ])->all()); + + return $result->amount; + } + + public function render(): mixed + { + return view('livewire.storefront.cart.show')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/CartDrawer.php b/app/Livewire/Storefront/CartDrawer.php new file mode 100644 index 00000000..895d8814 --- /dev/null +++ b/app/Livewire/Storefront/CartDrawer.php @@ -0,0 +1,159 @@ +cart = $carts->getOrCreateForSession(app('current_store'), auth('customer')->user()); + $this->discountCode = (string) ($this->cart->discount_code ?? ''); + $this->dispatch('cart-count-updated', count: $this->cart->itemCount()); + } + + #[On('open-cart-drawer')] + public function open(): void + { + $this->refreshCart(); + $this->open = true; + } + + #[On('cart-updated')] + public function refreshCart(): void + { + $this->cart = app(CartService::class)->getOrCreateForSession(app('current_store'), auth('customer')->user()); + $this->discountCode = (string) ($this->cart->discount_code ?? ''); + $this->discountAmount = $this->calculateDiscountAmount(); + $this->open = true; + $this->dispatch('cart-count-updated', count: $this->cart->itemCount()); + } + + public function increase(int $lineId): void + { + $line = $this->cart->lines->firstWhere('id', $lineId); + + if ($line === null) { + return; + } + + try { + app(CartService::class)->updateLineQuantity($this->cart, $lineId, $line->quantity + 1); + $this->refreshCart(); + } catch (InsufficientInventoryException $exception) { + $this->addError('cart', $exception->getMessage()); + } + } + + public function decrease(int $lineId): void + { + $line = $this->cart->lines->firstWhere('id', $lineId); + + if ($line === null || $line->quantity < 2) { + return; + } + + app(CartService::class)->updateLineQuantity($this->cart, $lineId, $line->quantity - 1); + $this->refreshCart(); + } + + public function remove(int $lineId): void + { + if (! $this->cart->lines->contains('id', $lineId)) { + return; + } + + app(CartService::class)->removeLine($this->cart, $lineId); + $this->message = 'Item removed from your cart.'; + $this->refreshCart(); + } + + public function applyDiscount(DiscountService $discounts): void + { + $this->validate(['discountCode' => ['required', 'string', 'max:64']]); + + try { + $discount = $discounts->validate(trim($this->discountCode), app('current_store'), $this->cart); + $this->cart->update(['discount_code' => $discount->code]); + $this->message = 'Discount applied.'; + $this->resetValidation('discountCode'); + $this->refreshCart(); + } catch (InvalidDiscountException $exception) { + $this->addError('discountCode', $exception->getMessage()); + } + } + + public function removeDiscount(): void + { + $this->cart->update(['discount_code' => null]); + $this->discountCode = ''; + $this->message = 'Discount removed.'; + $this->resetValidation('discountCode'); + $this->refreshCart(); + } + + public function checkout(CheckoutService $checkouts): void + { + if ($this->cart->lines->isEmpty()) { + $this->addError('cart', 'Your cart is empty.'); + + return; + } + + $checkout = $checkouts->create($this->cart, auth('customer')->user()?->email ?? 'guest@example.com', auth('customer')->user()); + $this->redirect(route('checkout.show', $checkout), navigate: true); + } + + public function formatMoney(int|float $amount): string + { + return number_format((float) $amount / 100, 2, '.', ',').' '.($this->cart->currency ?: 'EUR'); + } + + public function close(): void + { + $this->open = false; + } + + public function render(): mixed + { + return view('livewire.storefront.cart-drawer'); + } + + private function calculateDiscountAmount(): int + { + if ($this->cart->discount_code === null || $this->cart->lines->isEmpty()) { + return 0; + } + + try { + $discount = app(DiscountService::class)->validate($this->cart->discount_code, app('current_store'), $this->cart); + } catch (InvalidDiscountException) { + return 0; + } + + return app(DiscountService::class)->calculate($discount, (int) $this->cart->lines->sum('line_subtotal_amount'), $this->cart->lines->map(fn ($line): array => [ + 'line_id' => $line->id, + 'amount' => $line->line_subtotal_amount, + 'product_id' => $line->variant->product_id, + 'collection_ids' => $line->variant->product->collections->modelKeys(), + ])->all())->amount; + } +} diff --git a/app/Livewire/Storefront/Checkout/Confirmation.php b/app/Livewire/Storefront/Checkout/Confirmation.php new file mode 100644 index 00000000..28cdc0fd --- /dev/null +++ b/app/Livewire/Storefront/Checkout/Confirmation.php @@ -0,0 +1,66 @@ +order = Order::query() + ->with(['lines.variant.product.media', 'customer', 'checkout', 'payments']) + ->where('checkout_id', $checkoutId) + ->first() + ?? Order::query() + ->with(['lines.variant.product.media', 'customer', 'checkout', 'payments']) + ->where('id', $checkoutId) + ->firstOrFail(); + + $customerId = auth('customer')->id(); + $sessionCartIds = array_filter([ + session('cart_id'), + session('cart_id_'.app('current_store')->getKey()), + ]); + + abort_unless( + ($customerId !== null && (int) $this->order->customer_id === (int) $customerId) + || ($customerId === null && in_array($this->order->checkout?->cart_id, $sessionCartIds, true)), + 404, + ); + } + + public function formatMoney(int|float $amount): string + { + return number_format((float) $amount / 100, 2, '.', ',').' '.($this->order->currency ?: 'EUR'); + } + + public function paymentLabel(): string + { + return match ((string) $this->order->payment_method) { + 'credit_card' => 'Credit card', + 'paypal' => 'PayPal', + 'bank_transfer' => 'Bank transfer', + default => Str::headline((string) $this->order->payment_method), + }; + } + + public function isBankTransfer(): bool + { + return $this->order->payment_method === 'bank_transfer'; + } + + public function canViewAccountOrder(): bool + { + return auth('customer')->check() && $this->order->customer_id !== null; + } + + public function render(): mixed + { + return view('livewire.storefront.checkout.confirmation')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Checkout/Show.php b/app/Livewire/Storefront/Checkout/Show.php new file mode 100644 index 00000000..569edabc --- /dev/null +++ b/app/Livewire/Storefront/Checkout/Show.php @@ -0,0 +1,400 @@ + */ + public array $shippingAddress = [ + 'first_name' => '', + 'last_name' => '', + 'address1' => '', + 'address2' => '', + 'city' => '', + 'state' => '', + 'country_code' => 'DE', + 'postal_code' => '', + 'phone' => '', + ]; + + /** @var array */ + public array $billingAddress = [ + 'first_name' => '', + 'last_name' => '', + 'address1' => '', + 'address2' => '', + 'city' => '', + 'state' => '', + 'country_code' => 'DE', + 'postal_code' => '', + 'phone' => '', + ]; + + public bool $billingSameAsShipping = true; + + public ?int $savedAddressId = null; + + public ?int $shippingRateId = null; + + public string $paymentMethod = PaymentMethod::CreditCard->value; + + public string $cardNumber = '4242424242424242'; + + public string $cardholderName = ''; + + public string $cardExpiry = ''; + + public string $cardCvc = ''; + + public string $discountCode = ''; + + public string $message = ''; + + public bool $processing = false; + + public int $activeStep = 1; + + public bool $showOrderSummary = false; + + public function mount(int $checkoutId): void + { + $this->checkout = CheckoutModel::query() + ->with(['cart.lines.variant.product.media', 'shippingRate']) + ->findOrFail($checkoutId); + + $customerId = auth('customer')->id(); + $sessionCartIds = array_filter([ + session('cart_id'), + session('cart_id_'.app('current_store')->getKey()), + ]); + + abort_unless( + ($customerId !== null && (int) $this->checkout->customer_id === (int) $customerId) + || ($customerId === null && in_array($this->checkout->cart_id, $sessionCartIds, true)), + 404, + ); + + $this->email = (string) $this->checkout->email; + $this->discountCode = (string) ($this->checkout->discount_code ?? ''); + $this->shippingRateId = $this->checkout->shipping_rate_id; + $this->paymentMethod = (string) ($this->checkout->payment_method ?? PaymentMethod::CreditCard->value); + + if ($this->checkout->shipping_address_json !== null) { + $this->shippingAddress = array_merge($this->shippingAddress, $this->checkout->shipping_address_json); + } + + if ($this->checkout->billing_address_json !== null) { + $this->billingAddress = array_merge($this->billingAddress, $this->checkout->billing_address_json); + $this->billingSameAsShipping = $this->billingAddress === $this->shippingAddress; + } + + $this->activeStep = match ($this->checkout->status) { + CheckoutStatus::Started => 1, + CheckoutStatus::Addressed => 3, + CheckoutStatus::ShippingSelected, CheckoutStatus::PaymentSelected, CheckoutStatus::PaymentPending, CheckoutStatus::Completed => 4, + default => 1, + }; + } + + public function saveContact(): void + { + $this->validate([ + 'email' => ['required', 'email', 'max:255'], + ], [ + 'email.required' => 'Enter an email address to receive your order confirmation.', + ]); + + $this->checkout->update(['email' => $this->email]); + $this->checkout->refresh(); + $this->message = 'Contact information saved.'; + $this->activeStep = 2; + } + + public function saveAddress(CheckoutService $checkouts, PricingEngine $pricing): void + { + $this->normalizeAddresses(); + + $rules = [ + 'email' => ['required', 'email', 'max:255'], + ...$this->addressRules('shippingAddress'), + ]; + + if (! $this->billingSameAsShipping) { + $rules = [...$rules, ...$this->addressRules('billingAddress')]; + } + + $this->validate($rules); + + $this->checkout->update(['email' => $this->email]); + $this->checkout = $checkouts->setAddress( + $this->checkout->refresh(), + $this->shippingAddress, + $this->billingAddress, + $this->billingSameAsShipping, + ); + + if ($this->requiresShipping()) { + $this->checkout->update([ + 'shipping_rate_id' => null, + 'shipping_method_id' => null, + 'status' => CheckoutStatus::Addressed, + ]); + $this->checkout = $this->checkout->refresh(); + $pricing->calculate($this->checkout); + $this->checkout = $this->checkout->refresh(); + $this->shippingRateId = null; + $this->activeStep = 3; + } else { + $this->checkout = $checkouts->setShippingMethod($this->checkout, 0); + $this->shippingRateId = null; + $this->activeStep = 4; + } + + $this->message = 'Address saved.'; + } + + public function selectSavedAddress(int|string|null $addressId): void + { + $customerId = auth('customer')->id(); + + if ($customerId === null || $addressId === null || $addressId === '') { + $this->savedAddressId = null; + + return; + } + + $address = CustomerAddress::query() + ->whereKey((int) $addressId) + ->where('customer_id', $customerId) + ->firstOrFail(); + + $this->savedAddressId = $address->getKey(); + $this->shippingAddress = array_merge($this->shippingAddress, $address->address_json ?? []); + + if ($this->billingSameAsShipping) { + $this->billingAddress = $this->shippingAddress; + } + } + + public function updatedBillingSameAsShipping(bool $same): void + { + if ($same) { + $this->billingAddress = $this->shippingAddress; + } + } + + public function chooseShipping(CheckoutService $checkouts): void + { + if (! $this->requiresShipping()) { + $this->checkout = $checkouts->setShippingMethod($this->checkout, 0); + $this->activeStep = 4; + + return; + } + + $this->validate(['shippingRateId' => ['required', 'integer']]); + + try { + $this->checkout = $checkouts->setShippingMethod($this->checkout, $this->shippingRateId); + $this->message = 'Shipping method saved.'; + $this->activeStep = 4; + } catch (Throwable $exception) { + $this->addError('shippingRateId', $exception->getMessage()); + } + } + + public function applyDiscount(DiscountService $discounts, PricingEngine $pricing): void + { + $this->validate(['discountCode' => ['required', 'string', 'max:64']]); + + try { + $code = trim($this->discountCode); + $discount = $discounts->validate($code, app('current_store'), $this->checkout->cart); + $this->checkout->cart->update(['discount_code' => $discount->code]); + $this->checkout->update(['discount_code' => $discount->code]); + $this->checkout = $this->checkout->refresh(); + $pricing->calculate($this->checkout); + $this->checkout = $this->checkout->refresh(); + $this->checkout->load(['cart.lines.variant.product.media', 'shippingRate']); + $this->discountCode = $discount->code; + $this->message = 'Discount applied.'; + } catch (InvalidDiscountException $exception) { + $this->addError('discountCode', $exception->getMessage()); + } + } + + public function removeDiscount(PricingEngine $pricing): void + { + $this->checkout->cart->update(['discount_code' => null]); + $this->checkout->update(['discount_code' => null]); + $this->checkout = $this->checkout->refresh(); + $pricing->calculate($this->checkout); + $this->checkout = $this->checkout->refresh(); + $this->checkout->load(['cart.lines.variant.product.media', 'shippingRate']); + $this->discountCode = ''; + $this->message = 'Discount removed.'; + $this->resetValidation('discountCode'); + } + + public function pay(CheckoutService $checkouts, PaymentService $payments): void + { + if ($this->processing) { + return; + } + + $this->cardNumber = preg_replace('/\D+/', '', $this->cardNumber) ?? ''; + $rules = [ + 'email' => ['required', 'email', 'max:255'], + 'paymentMethod' => ['required', 'in:credit_card,paypal,bank_transfer'], + ]; + + if ($this->paymentMethod === PaymentMethod::CreditCard->value) { + $rules = [ + ...$rules, + 'cardNumber' => ['required', 'digits:16'], + 'cardholderName' => ['required', 'string', 'max:255'], + 'cardExpiry' => ['required', 'regex:/^(0[1-9]|1[0-2])\/\d{2}$/'], + 'cardCvc' => ['required', 'digits_between:3,4'], + ]; + } + + $this->validate($rules); + + if ($this->paymentMethod === PaymentMethod::CreditCard->value && ! $this->cardExpiryIsFuture()) { + $this->addError('cardExpiry', 'Enter a future expiry date in MM/YY format.'); + + return; + } + + if ($this->checkout->shipping_address_json === null) { + $this->addError('payment', 'Save your shipping address before placing the order.'); + $this->activeStep = 2; + + return; + } + + if ($this->requiresShipping() && $this->checkout->shipping_rate_id === null) { + $this->addError('payment', 'Choose a shipping method before placing the order.'); + $this->activeStep = 3; + + return; + } + + $this->processing = true; + $this->resetValidation('payment'); + + try { + $this->checkout->update(['email' => $this->email]); + $this->checkout = $checkouts->selectPaymentMethod($this->checkout->refresh(), $this->paymentMethod); + $order = $payments->pay($this->checkout, PaymentMethod::from($this->paymentMethod), [ + 'card_number' => $this->cardNumber, + 'cardholder_name' => $this->cardholderName, + 'card_expiry' => $this->cardExpiry, + 'card_cvc' => $this->cardCvc, + ]); + + if ($order === null) { + $this->addError('payment', 'Payment declined. Check your details and try again.'); + + return; + } + + $this->redirect(route('checkout.confirmation', ['checkoutId' => $order->checkout_id]), navigate: true); + } catch (Throwable $exception) { + $this->addError('payment', $exception->getMessage() ?: 'We could not process your payment. Please try again.'); + } finally { + $this->processing = false; + } + } + + public function setActiveStep(int $step): void + { + if ($step >= 1 && $step <= $this->maxAvailableStep()) { + $this->activeStep = $step; + } + } + + public function toggleOrderSummary(): void + { + $this->showOrderSummary = ! $this->showOrderSummary; + } + + public function requiresShipping(): bool + { + return $this->checkout->cart->lines->contains(fn ($line): bool => (bool) $line->variant?->requires_shipping); + } + + public function formatMoney(int|float $amount, ?string $currency = null): string + { + return number_format((float) $amount / 100, 2, '.', ',').' '.($currency ?? $this->checkout->cart->currency ?? 'EUR'); + } + + public function render(ShippingCalculator $shipping, PricingEngine $pricing): mixed + { + $this->checkout->load(['cart.lines.variant.product.media', 'shippingRate']); + $rates = $this->checkout->shipping_address_json === null || ! $this->requiresShipping() + ? collect() + : $shipping->getAvailableRates(app('current_store'), $this->checkout->shipping_address_json); + $totals = $this->checkout->totals_json ?? $pricing->calculate($this->checkout)->toArray(); + $savedAddresses = auth('customer')->user()?->addresses()->latest()->get() ?? collect(); + + return view('livewire.storefront.checkout.show', compact('rates', 'totals', 'savedAddresses'))->layout('layouts.storefront'); + } + + /** @return array> */ + private function addressRules(string $prefix): array + { + return [ + $prefix.'.first_name' => ['required', 'string', 'max:255'], + $prefix.'.last_name' => ['required', 'string', 'max:255'], + $prefix.'.address1' => ['required', 'string', 'max:500'], + $prefix.'.address2' => ['nullable', 'string', 'max:500'], + $prefix.'.city' => ['required', 'string', 'max:255'], + $prefix.'.state' => ['required', 'string', 'max:255'], + $prefix.'.country_code' => ['required', 'string', 'size:2'], + $prefix.'.postal_code' => ['required', 'string', 'max:20'], + $prefix.'.phone' => ['nullable', 'string', 'max:40'], + ]; + } + + private function normalizeAddresses(): void + { + $this->shippingAddress['country_code'] = strtoupper(trim($this->shippingAddress['country_code'] ?? '')); + $this->billingAddress['country_code'] = strtoupper(trim($this->billingAddress['country_code'] ?? '')); + } + + private function cardExpiryIsFuture(): bool + { + [$month, $year] = array_map('intval', explode('/', $this->cardExpiry)); + + return Carbon::create(2000 + $year, $month, 1)->endOfMonth()->isFuture(); + } + + private function maxAvailableStep(): int + { + return match ($this->checkout->status) { + CheckoutStatus::Started => $this->checkout->email === $this->email && $this->email !== '' ? 2 : 1, + CheckoutStatus::Addressed => 3, + CheckoutStatus::ShippingSelected, CheckoutStatus::PaymentSelected, CheckoutStatus::PaymentPending, CheckoutStatus::Completed => 4, + default => 1, + }; + } +} diff --git a/app/Livewire/Storefront/Collections/Index.php b/app/Livewire/Storefront/Collections/Index.php new file mode 100644 index 00000000..77e5bd09 --- /dev/null +++ b/app/Livewire/Storefront/Collections/Index.php @@ -0,0 +1,14 @@ + ProductCollection::query()->where('status', 'active')->latest()->get()])->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Collections/Show.php b/app/Livewire/Storefront/Collections/Show.php new file mode 100644 index 00000000..fd05990e --- /dev/null +++ b/app/Livewire/Storefront/Collections/Show.php @@ -0,0 +1,53 @@ +resetPage(); + } + + public function updatedInStock(): void + { + $this->resetPage(); + } + + public function mount(string $handle): void + { + $this->collection = ProductCollection::query()->where('handle', $handle)->with(['products.variants.inventory', 'products.media'])->firstOrFail(); + } + + public function render(): mixed + { + $products = $this->collection->products() + ->where('products.status', 'active') + ->with(['variants.inventory', 'media']) + ->when($this->inStock, fn ($query) => $query->whereHas('variants.inventory', fn ($inventory) => $inventory->whereColumn('quantity_on_hand', '>', 'quantity_reserved')->orWhere('policy', 'continue'))) + ->when($this->sort === 'price_asc', fn ($query) => $query->withMin('variants', 'price_amount')->orderBy('variants_min_price_amount')) + ->when($this->sort === 'price_desc', fn ($query) => $query->withMin('variants', 'price_amount')->orderByDesc('variants_min_price_amount')) + ->when($this->sort === 'newest', fn ($query) => $query->latest('products.created_at')) + ->paginate(12); + + return view('livewire.storefront.collections.show', ['products' => $products])->layout('layouts.storefront'); + } + + public function clearFilters(): void + { + $this->inStock = false; + $this->sort = 'featured'; + } +} diff --git a/app/Livewire/Storefront/Home.php b/app/Livewire/Storefront/Home.php new file mode 100644 index 00000000..d599cebd --- /dev/null +++ b/app/Livewire/Storefront/Home.php @@ -0,0 +1,27 @@ +store = app()->bound('current_store') ? app('current_store') : null; + } + + public function render(): mixed + { + if ($this->store === null) { + return view('livewire.storefront.home-fallback')->layout('layouts.empty'); + } + + return view('livewire.storefront.home', ['collections' => Collection::query()->where('status', 'active')->withCount('products')->latest()->take(4)->get(), 'products' => Product::query()->published()->with(['variants.inventory', 'media'])->latest('published_at')->take(8)->get()])->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Pages/Show.php b/app/Livewire/Storefront/Pages/Show.php new file mode 100644 index 00000000..7e8ff858 --- /dev/null +++ b/app/Livewire/Storefront/Pages/Show.php @@ -0,0 +1,21 @@ +page = Page::query()->where('handle', $handle)->where('status', 'published')->firstOrFail(); + } + + public function render(): mixed + { + return view('livewire.storefront.pages.show')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Products/Show.php b/app/Livewire/Storefront/Products/Show.php new file mode 100644 index 00000000..c6e255e3 --- /dev/null +++ b/app/Livewire/Storefront/Products/Show.php @@ -0,0 +1,86 @@ + */ + public array $selectedOptions = []; + + public int $quantity = 1; + + public string $message = ''; + + public function mount(string $handle): void + { + $this->product = Product::query()->with(['variants.inventory', 'variants.optionValues', 'media', 'options.values'])->where('handle', $handle)->firstOrFail(); + abort_unless($this->product->status->value === 'active', 404); + $this->selectedVariantId = $this->product->defaultVariant()?->getKey() ?? 0; + $this->selectedMediaId = $this->product->media->first()?->getKey(); + $default = $this->product->defaultVariant(); + $this->selectedOptions = $default?->optionValues->mapWithKeys(fn ($value): array => [$value->product_option_id => $value->getKey()])->all() ?? []; + } + + public function addToCart(CartService $carts): void + { + $cart = $carts->getOrCreateForSession(app('current_store'), auth('customer')->user()); + try { + $carts->addLine($cart, $this->selectedVariantId, $this->quantity); + } catch (InsufficientInventoryException $exception) { + $this->addError('quantity', $exception->getMessage()); + + return; + } + $this->message = 'Added to cart'; + $this->dispatch('cart-updated'); + } + + public function selectVariant(int $variantId): void + { + abort_unless($this->product->variants->contains('id', $variantId), 404); + + $this->selectedVariantId = $variantId; + } + + public function selectMedia(int $mediaId): void + { + abort_unless($this->product->media->contains('id', $mediaId), 404); + + $this->selectedMediaId = $mediaId; + } + + public function selectOption(int $optionId, int $valueId): void + { + abort_unless($this->product->options->firstWhere('id', $optionId)?->values->contains('id', $valueId), 404); + $this->selectedOptions[$optionId] = $valueId; + $selectedValueIds = array_values($this->selectedOptions); + $variant = $this->product->variants->first(function ($candidate) use ($selectedValueIds): bool { + $candidateValueIds = $candidate->optionValues->modelKeys(); + + return count($selectedValueIds) === count($candidateValueIds) + && count(array_intersect($selectedValueIds, $candidateValueIds)) === count($selectedValueIds); + }); + + if ($variant !== null) { + $this->selectedVariantId = $variant->getKey(); + } + } + + public function render(): mixed + { + $this->product->loadMissing(['variants.inventory', 'variants.optionValues', 'media', 'options.values']); + + return view('livewire.storefront.products.show')->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Search/Index.php b/app/Livewire/Storefront/Search/Index.php new file mode 100644 index 00000000..f14f6a0d --- /dev/null +++ b/app/Livewire/Storefront/Search/Index.php @@ -0,0 +1,23 @@ +query = $q ?? request()->string('q')->toString(); + } + + public function render(SearchService $search): mixed + { + $products = $search->search(app('current_store'), $this->query, [], 12); + + return view('livewire.storefront.search.index', compact('products'))->layout('layouts.storefront'); + } +} diff --git a/app/Livewire/Storefront/Search/Modal.php b/app/Livewire/Storefront/Search/Modal.php new file mode 100644 index 00000000..044198a5 --- /dev/null +++ b/app/Livewire/Storefront/Search/Modal.php @@ -0,0 +1,37 @@ +open) { + return; + } + + $this->suggestions = $search->autocomplete(app('current_store'), $this->query)->map(fn ($product): array => ['id' => $product->getKey(), 'title' => $product->title, 'handle' => $product->handle])->all(); + } + + /** @var array */ + public array $suggestions = []; + + #[On('open-search-modal')] + public function open(): void + { + $this->open = true; + } + + public function render(): mixed + { + return view('livewire.storefront.search.modal'); + } +} diff --git a/app/Models/AnalyticsDaily.php b/app/Models/AnalyticsDaily.php new file mode 100644 index 00000000..c99ca464 --- /dev/null +++ b/app/Models/AnalyticsDaily.php @@ -0,0 +1,24 @@ + 'date']; + } +} diff --git a/app/Models/AnalyticsEvent.php b/app/Models/AnalyticsEvent.php new file mode 100644 index 00000000..5c60691e --- /dev/null +++ b/app/Models/AnalyticsEvent.php @@ -0,0 +1,25 @@ + 'array', 'properties_json' => 'array', 'occurred_at' => 'datetime']; + } + + protected static function booted(): void + { + static::saving(function (AnalyticsEvent $event): void { + $event->properties_json = $event->payload ?? []; + }); + } +} diff --git a/app/Models/App.php b/app/Models/App.php new file mode 100644 index 00000000..6621c4cb --- /dev/null +++ b/app/Models/App.php @@ -0,0 +1,21 @@ + 'array']; + } + + public function installations(): HasMany + { + return $this->hasMany(AppInstallation::class); + } +} diff --git a/app/Models/AppInstallation.php b/app/Models/AppInstallation.php new file mode 100644 index 00000000..d0afec6f --- /dev/null +++ b/app/Models/AppInstallation.php @@ -0,0 +1,24 @@ + 'array']; + } + + public function app(): BelongsTo + { + return $this->belongsTo(App::class); + } +} diff --git a/app/Models/Cart.php b/app/Models/Cart.php new file mode 100644 index 00000000..5e1b275e --- /dev/null +++ b/app/Models/Cart.php @@ -0,0 +1,41 @@ + CartStatus::class]; + } + + public function customer(): BelongsTo + { + return $this->belongsTo(Customer::class); + } + + public function lines(): HasMany + { + return $this->hasMany(CartLine::class); + } + + public function subtotalAmount(): int + { + return (int) $this->lines->sum('line_total_amount'); + } + + public function itemCount(): int + { + return (int) $this->lines->sum('quantity'); + } +} diff --git a/app/Models/CartLine.php b/app/Models/CartLine.php new file mode 100644 index 00000000..38c9e79c --- /dev/null +++ b/app/Models/CartLine.php @@ -0,0 +1,21 @@ +belongsTo(Cart::class); + } + + public function variant(): BelongsTo + { + return $this->belongsTo(ProductVariant::class, 'variant_id')->with(['product', 'inventory']); + } +} diff --git a/app/Models/Checkout.php b/app/Models/Checkout.php new file mode 100644 index 00000000..0c124b17 --- /dev/null +++ b/app/Models/Checkout.php @@ -0,0 +1,45 @@ + CheckoutStatus::class, 'shipping_address_json' => 'array', 'billing_address_json' => 'array', 'totals_json' => 'array', 'tax_provider_snapshot_json' => 'array', 'expires_at' => 'datetime']; + } + + public function cart(): BelongsTo + { + return $this->belongsTo(Cart::class); + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } + + public function customer(): BelongsTo + { + return $this->belongsTo(Customer::class); + } + + public function shippingRate(): BelongsTo + { + return $this->belongsTo(ShippingRate::class); + } + + public function isExpired(): bool + { + return $this->expires_at !== null && $this->expires_at->isPast(); + } +} diff --git a/app/Models/Collection.php b/app/Models/Collection.php new file mode 100644 index 00000000..0642630c --- /dev/null +++ b/app/Models/Collection.php @@ -0,0 +1,25 @@ + CollectionStatus::class]; + } + + public function products(): BelongsToMany + { + return $this->belongsToMany(Product::class, 'collection_products')->withPivot('position')->orderBy('collection_products.position'); + } +} diff --git a/app/Models/Concerns/BelongsToStore.php b/app/Models/Concerns/BelongsToStore.php new file mode 100644 index 00000000..15228382 --- /dev/null +++ b/app/Models/Concerns/BelongsToStore.php @@ -0,0 +1,27 @@ +bound('current_store') && app('current_store') instanceof Store) { + $model->setAttribute('store_id', app('current_store')->getKey()); + } + }); + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/Customer.php b/app/Models/Customer.php new file mode 100644 index 00000000..d30cc38a --- /dev/null +++ b/app/Models/Customer.php @@ -0,0 +1,57 @@ + 'datetime', 'marketing_opt_in' => 'boolean', 'metadata' => 'array', 'password_hash' => 'hashed']; + } + + public function getAuthPasswordName(): string + { + return 'password_hash'; + } + + public function getAuthPassword(): ?string + { + return $this->password_hash; + } + + public function getNameAttribute(): string + { + return trim($this->first_name.' '.$this->last_name); + } + + public function addresses(): HasMany + { + return $this->hasMany(CustomerAddress::class); + } + + public function orders(): HasMany + { + return $this->hasMany(Order::class); + } + + public function carts(): HasMany + { + return $this->hasMany(Cart::class); + } +} diff --git a/app/Models/CustomerAddress.php b/app/Models/CustomerAddress.php new file mode 100644 index 00000000..c7a86bc2 --- /dev/null +++ b/app/Models/CustomerAddress.php @@ -0,0 +1,21 @@ + 'array', 'is_default' => 'boolean']; + } + + public function customer(): BelongsTo + { + return $this->belongsTo(Customer::class); + } +} diff --git a/app/Models/Discount.php b/app/Models/Discount.php new file mode 100644 index 00000000..1262f302 --- /dev/null +++ b/app/Models/Discount.php @@ -0,0 +1,28 @@ + DiscountType::class, 'value_type' => DiscountValueType::class, 'starts_at' => 'datetime', 'ends_at' => 'datetime', 'rules_json' => 'array']; + } + + public function isAvailable(): bool + { + return $this->status === 'active' + && ($this->starts_at === null || $this->starts_at->isPast()) + && ($this->ends_at === null || $this->ends_at->isFuture()) + && ($this->usage_limit === null || $this->usage_count < $this->usage_limit); + } +} diff --git a/app/Models/Fulfillment.php b/app/Models/Fulfillment.php new file mode 100644 index 00000000..8d4052d0 --- /dev/null +++ b/app/Models/Fulfillment.php @@ -0,0 +1,27 @@ + 'datetime', 'delivered_at' => 'datetime', 'fulfilled_at' => 'datetime']; + } + + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } + + public function lines(): HasMany + { + return $this->hasMany(FulfillmentLine::class); + } +} diff --git a/app/Models/FulfillmentLine.php b/app/Models/FulfillmentLine.php new file mode 100644 index 00000000..d3dd1dcf --- /dev/null +++ b/app/Models/FulfillmentLine.php @@ -0,0 +1,21 @@ +belongsTo(Fulfillment::class); + } + + public function orderLine(): BelongsTo + { + return $this->belongsTo(OrderLine::class); + } +} diff --git a/app/Models/InventoryItem.php b/app/Models/InventoryItem.php new file mode 100644 index 00000000..f6c5e11d --- /dev/null +++ b/app/Models/InventoryItem.php @@ -0,0 +1,35 @@ + InventoryPolicy::class]; + } + + public function variant(): BelongsTo + { + return $this->belongsTo(ProductVariant::class, 'variant_id'); + } + + public function availableQuantity(): int + { + return $this->quantity_on_hand - $this->quantity_reserved; + } + + public function canSell(int $quantity): bool + { + return $this->policy === InventoryPolicy::Continue || $this->availableQuantity() >= $quantity; + } +} diff --git a/app/Models/NavigationItem.php b/app/Models/NavigationItem.php new file mode 100644 index 00000000..67f3a074 --- /dev/null +++ b/app/Models/NavigationItem.php @@ -0,0 +1,21 @@ +belongsTo(NavigationMenu::class, 'navigation_menu_id'); + } + + public function parent(): BelongsTo + { + return $this->belongsTo(self::class, 'parent_id'); + } +} diff --git a/app/Models/NavigationMenu.php b/app/Models/NavigationMenu.php new file mode 100644 index 00000000..0ad0eb43 --- /dev/null +++ b/app/Models/NavigationMenu.php @@ -0,0 +1,19 @@ +hasMany(NavigationItem::class)->orderBy('position'); + } +} diff --git a/app/Models/Order.php b/app/Models/Order.php new file mode 100644 index 00000000..783dc555 --- /dev/null +++ b/app/Models/Order.php @@ -0,0 +1,53 @@ + OrderStatus::class, 'financial_status' => FinancialStatus::class, 'fulfillment_status' => FulfillmentStatus::class, 'shipping_address_json' => 'array', 'billing_address_json' => 'array', 'placed_at' => 'datetime', 'metadata' => 'array']; + } + + public function customer(): BelongsTo + { + return $this->belongsTo(Customer::class); + } + + public function checkout(): BelongsTo + { + return $this->belongsTo(Checkout::class); + } + + public function lines(): HasMany + { + return $this->hasMany(OrderLine::class); + } + + public function payments(): HasMany + { + return $this->hasMany(Payment::class); + } + + public function refunds(): HasMany + { + return $this->hasMany(Refund::class); + } + + public function fulfillments(): HasMany + { + return $this->hasMany(Fulfillment::class); + } +} diff --git a/app/Models/OrderExport.php b/app/Models/OrderExport.php new file mode 100644 index 00000000..5c5800dc --- /dev/null +++ b/app/Models/OrderExport.php @@ -0,0 +1,26 @@ + */ + protected $fillable = ['store_id', 'format', 'filters_json', 'status', 'row_count', 'storage_key', 'download_url', 'download_expires_at', 'completed_at', 'error_message']; + + protected function casts(): array + { + return ['filters_json' => 'array', 'download_expires_at' => 'datetime', 'completed_at' => 'datetime']; + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/OrderLine.php b/app/Models/OrderLine.php new file mode 100644 index 00000000..9024ea89 --- /dev/null +++ b/app/Models/OrderLine.php @@ -0,0 +1,41 @@ + 'array', 'discount_allocations_json' => 'array']; + } + + protected static function booted(): void + { + static::saving(function (OrderLine $line): void { + if ($line->isDirty('total_amount') && ! $line->isDirty('line_total_amount')) { + $line->line_total_amount = $line->total_amount; + } + $line->total_amount = $line->line_total_amount; + }); + } + + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } + + public function product(): BelongsTo + { + return $this->belongsTo(Product::class); + } + + public function variant(): BelongsTo + { + return $this->belongsTo(ProductVariant::class, 'variant_id'); + } +} diff --git a/app/Models/Organization.php b/app/Models/Organization.php new file mode 100644 index 00000000..7f90697a --- /dev/null +++ b/app/Models/Organization.php @@ -0,0 +1,19 @@ +hasMany(Store::class); + } +} diff --git a/app/Models/Page.php b/app/Models/Page.php new file mode 100644 index 00000000..34192256 --- /dev/null +++ b/app/Models/Page.php @@ -0,0 +1,31 @@ + PageStatus::class, 'published_at' => 'datetime']; + } + + protected static function booted(): void + { + static::saving(function (Page $page): void { + if ($page->isDirty('body_html') && ! $page->isDirty('content')) { + $page->content = $page->body_html; + } + $page->content = app(HtmlSanitizer::class)->sanitize($page->content); + $page->body_html = $page->content; + }); + } +} diff --git a/app/Models/Payment.php b/app/Models/Payment.php new file mode 100644 index 00000000..106f09ee --- /dev/null +++ b/app/Models/Payment.php @@ -0,0 +1,25 @@ + PaymentMethod::class, 'status' => PaymentStatus::class, 'raw_json' => 'encrypted:array']; + } + + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } +} diff --git a/app/Models/Product.php b/app/Models/Product.php new file mode 100644 index 00000000..ea159b2f --- /dev/null +++ b/app/Models/Product.php @@ -0,0 +1,57 @@ + ProductStatus::class, 'tags' => 'array', 'metadata' => 'array', 'published_at' => 'datetime']; + } + + public function variants(): HasMany + { + return $this->hasMany(ProductVariant::class)->orderBy('position'); + } + + public function options(): HasMany + { + return $this->hasMany(ProductOption::class)->orderBy('position'); + } + + public function media(): HasMany + { + return $this->hasMany(ProductMedia::class)->orderBy('position'); + } + + public function collections(): BelongsToMany + { + return $this->belongsToMany(Collection::class, 'collection_products')->withPivot('position'); + } + + public function orders(): BelongsToMany + { + return $this->belongsToMany(Order::class, 'order_lines'); + } + + public function scopePublished($query): void + { + $query->where('status', ProductStatus::Active)->whereNotNull('published_at')->where('published_at', '<=', now()); + } + + public function defaultVariant(): ?ProductVariant + { + return $this->variants->firstWhere('is_default', true) ?? $this->variants->first(); + } +} diff --git a/app/Models/ProductMedia.php b/app/Models/ProductMedia.php new file mode 100644 index 00000000..73c38abc --- /dev/null +++ b/app/Models/ProductMedia.php @@ -0,0 +1,34 @@ + 'array']; + } + + protected static function booted(): void + { + static::deleting(function (ProductMedia $media): void { + $keys = array_values(array_filter([$media->storage_key, $media->path, ...array_values($media->metadata['variants'] ?? [])])); + $disk = Storage::disk('public'); + + foreach (array_unique($keys) as $key) { + $disk->delete($key); + } + }); + } + + public function product(): BelongsTo + { + return $this->belongsTo(Product::class); + } +} diff --git a/app/Models/ProductOption.php b/app/Models/ProductOption.php new file mode 100644 index 00000000..8733f007 --- /dev/null +++ b/app/Models/ProductOption.php @@ -0,0 +1,22 @@ +belongsTo(Product::class); + } + + public function values(): HasMany + { + return $this->hasMany(ProductOptionValue::class)->orderBy('position'); + } +} diff --git a/app/Models/ProductOptionValue.php b/app/Models/ProductOptionValue.php new file mode 100644 index 00000000..9ffba709 --- /dev/null +++ b/app/Models/ProductOptionValue.php @@ -0,0 +1,22 @@ +belongsTo(ProductOption::class, 'product_option_id'); + } + + public function variants(): BelongsToMany + { + return $this->belongsToMany(ProductVariant::class, 'variant_option_values', 'product_option_value_id', 'variant_id'); + } +} diff --git a/app/Models/ProductVariant.php b/app/Models/ProductVariant.php new file mode 100644 index 00000000..7d1873c5 --- /dev/null +++ b/app/Models/ProductVariant.php @@ -0,0 +1,46 @@ + 'boolean', 'is_default' => 'boolean', 'metadata' => 'array', 'status' => VariantStatus::class]; + } + + public function product(): BelongsTo + { + return $this->belongsTo(Product::class); + } + + public function inventory(): HasOne + { + return $this->hasOne(InventoryItem::class, 'variant_id'); + } + + public function optionValues(): BelongsToMany + { + return $this->belongsToMany(ProductOptionValue::class, 'variant_option_values', 'variant_id', 'product_option_value_id'); + } + + public function orders(): BelongsToMany + { + return $this->belongsToMany(Order::class, 'order_lines', 'variant_id', 'order_id'); + } + + public function availableQuantity(): int + { + $inventory = $this->inventory; + + return $inventory ? $inventory->availableQuantity() : 0; + } +} diff --git a/app/Models/Refund.php b/app/Models/Refund.php new file mode 100644 index 00000000..e25aa017 --- /dev/null +++ b/app/Models/Refund.php @@ -0,0 +1,26 @@ + 'boolean', 'lines_json' => 'array']; + } + + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } + + public function payment(): BelongsTo + { + return $this->belongsTo(Payment::class); + } +} diff --git a/app/Models/Scopes/StoreScope.php b/app/Models/Scopes/StoreScope.php new file mode 100644 index 00000000..e9b4c6d0 --- /dev/null +++ b/app/Models/Scopes/StoreScope.php @@ -0,0 +1,29 @@ +bound('current_store')) { + $builder->whereNull($model->qualifyColumn('store_id')); + + return; + } + + $currentStore = app('current_store'); + + if ($currentStore instanceof \App\Models\Store) { + $builder->where($model->qualifyColumn('store_id'), $currentStore->getKey()); + + return; + } + + $builder->whereNull($model->qualifyColumn('store_id')); + } +} diff --git a/app/Models/SearchQuery.php b/app/Models/SearchQuery.php new file mode 100644 index 00000000..f87cd926 --- /dev/null +++ b/app/Models/SearchQuery.php @@ -0,0 +1,18 @@ + 'array']; + } +} diff --git a/app/Models/SearchSetting.php b/app/Models/SearchSetting.php new file mode 100644 index 00000000..84babab9 --- /dev/null +++ b/app/Models/SearchSetting.php @@ -0,0 +1,30 @@ + 'array', 'stopwords' => 'array', 'synonyms_json' => 'array', 'stop_words_json' => 'array', 'enabled' => 'boolean']; + } + + protected static function booted(): void + { + static::saving(function (SearchSetting $settings): void { + $settings->synonyms_json = $settings->synonyms ?? []; + $settings->stop_words_json = $settings->stopwords ?? []; + }); + } +} diff --git a/app/Models/ShippingRate.php b/app/Models/ShippingRate.php new file mode 100644 index 00000000..ed2e6750 --- /dev/null +++ b/app/Models/ShippingRate.php @@ -0,0 +1,21 @@ + 'array', 'is_active' => 'boolean']; + } + + public function zone(): BelongsTo + { + return $this->belongsTo(ShippingZone::class, 'shipping_zone_id'); + } +} diff --git a/app/Models/ShippingZone.php b/app/Models/ShippingZone.php new file mode 100644 index 00000000..1622d81f --- /dev/null +++ b/app/Models/ShippingZone.php @@ -0,0 +1,31 @@ + 'array', 'regions_json' => 'array']; + } + + public function rates(): HasMany + { + return $this->hasMany(ShippingRate::class); + } + + public function matchesCountry(string $countryCode): bool + { + $countries = $this->countries_json ?? []; + + return $countries === [] || in_array(strtoupper($countryCode), array_map('strtoupper', $countries), true); + } +} diff --git a/app/Models/Store.php b/app/Models/Store.php new file mode 100644 index 00000000..859dd614 --- /dev/null +++ b/app/Models/Store.php @@ -0,0 +1,55 @@ + StoreStatus::Active->value, + 'default_currency' => 'USD', + 'default_locale' => 'en', + 'timezone' => 'UTC', + ]; + + protected function casts(): array + { + return ['status' => StoreStatus::class, 'metadata' => 'array']; + } + + public function organization(): BelongsTo + { + return $this->belongsTo(Organization::class); + } + + public function domains(): HasMany + { + return $this->hasMany(StoreDomain::class); + } + + public function users(): BelongsToMany + { + return $this->belongsToMany(User::class, 'store_users')->using(StoreUser::class)->withPivot('role')->withTimestamps(); + } + + public function settings(): HasOne + { + return $this->hasOne(StoreSettings::class); + } + + public function isActive(): bool + { + return $this->status === StoreStatus::Active; + } +} diff --git a/app/Models/StoreDomain.php b/app/Models/StoreDomain.php new file mode 100644 index 00000000..2d4d4c29 --- /dev/null +++ b/app/Models/StoreDomain.php @@ -0,0 +1,25 @@ + StoreDomainType::class, 'is_primary' => 'boolean']; + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/StoreInvitation.php b/app/Models/StoreInvitation.php new file mode 100644 index 00000000..be12d70c --- /dev/null +++ b/app/Models/StoreInvitation.php @@ -0,0 +1,24 @@ + */ + use HasFactory; + + protected $fillable = ['store_id', 'email', 'role', 'invited_at', 'expires_at', 'accepted_at']; + + protected function casts(): array + { + return ['invited_at' => 'datetime', 'expires_at' => 'datetime', 'accepted_at' => 'datetime']; + } + + public function store(): \Illuminate\Database\Eloquent\Relations\BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/StoreSettings.php b/app/Models/StoreSettings.php new file mode 100644 index 00000000..867155e2 --- /dev/null +++ b/app/Models/StoreSettings.php @@ -0,0 +1,36 @@ + */ + use BelongsToStore, HasFactory; + + protected $primaryKey = 'store_id'; + + public $incrementing = false; + + protected $keyType = 'int'; + + protected $fillable = ['store_id', 'settings_json', 'general_json', 'checkout_json', 'notification_json', 'social_json']; + + protected $attributes = [ + 'settings_json' => '{}', + ]; + + protected function casts(): array + { + return ['settings_json' => 'array', 'general_json' => 'array', 'checkout_json' => 'array', 'notification_json' => 'array', 'social_json' => 'array']; + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/StoreUser.php b/app/Models/StoreUser.php new file mode 100644 index 00000000..b53f10d9 --- /dev/null +++ b/app/Models/StoreUser.php @@ -0,0 +1,35 @@ + */ + use HasFactory; + + public $incrementing = false; + + protected $table = 'store_users'; + + protected $fillable = ['store_id', 'user_id', 'role']; + + protected function casts(): array + { + return ['role' => StoreUserRole::class]; + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Models/TaxSettings.php b/app/Models/TaxSettings.php new file mode 100644 index 00000000..9470454d --- /dev/null +++ b/app/Models/TaxSettings.php @@ -0,0 +1,28 @@ + 'array', 'provider_config_json' => 'array', 'config_json' => 'array', 'prices_include_tax' => 'boolean']; + } + + public function store(): BelongsTo + { + return $this->belongsTo(Store::class); + } +} diff --git a/app/Models/Theme.php b/app/Models/Theme.php new file mode 100644 index 00000000..23ac5aaf --- /dev/null +++ b/app/Models/Theme.php @@ -0,0 +1,45 @@ + */ + use HasFactory; + + protected $fillable = ['store_id', 'name', 'status', 'version', 'published_at']; + + protected function casts(): array + { + return ['status' => ThemeStatus::class, 'published_at' => 'datetime']; + } + + public function files(): HasMany + { + return $this->hasMany(ThemeFile::class); + } + + public function themeSettings(): HasOne + { + return $this->hasOne(ThemeSetting::class, 'theme_id', 'id'); + } + + public function settings(): HasOne + { + return $this->themeSettings(); + } + + public function settingsRows(): HasOne + { + return $this->themeSettings(); + } +} diff --git a/app/Models/ThemeFile.php b/app/Models/ThemeFile.php new file mode 100644 index 00000000..ab087020 --- /dev/null +++ b/app/Models/ThemeFile.php @@ -0,0 +1,16 @@ +belongsTo(Theme::class); + } +} diff --git a/app/Models/ThemeSetting.php b/app/Models/ThemeSetting.php new file mode 100644 index 00000000..f732d390 --- /dev/null +++ b/app/Models/ThemeSetting.php @@ -0,0 +1,35 @@ + */ + use HasFactory; + + protected $primaryKey = 'theme_id'; + + public $incrementing = false; + + public const CREATED_AT = null; + + protected $keyType = 'int'; + + protected $attributes = ['settings_json' => '{}']; + + protected $fillable = ['theme_id', 'settings_json']; + + protected function casts(): array + { + return ['settings_json' => 'array']; + } + + public function theme(): BelongsTo + { + return $this->belongsTo(Theme::class); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 214bea4e..3d768863 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,17 +2,20 @@ namespace App\Models; -// use Illuminate\Contracts\Auth\MustVerifyEmail; +use App\Enums\StoreUserRole; use Illuminate\Database\Eloquent\Factories\HasFactory; +// use Illuminate\Contracts\Auth\MustVerifyEmail; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Str; use Laravel\Fortify\TwoFactorAuthenticatable; +use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { /** @use HasFactory<\Database\Factories\UserFactory> */ - use HasFactory, Notifiable, TwoFactorAuthenticatable; + use HasApiTokens, HasFactory, Notifiable, TwoFactorAuthenticatable; /** * The attributes that are mass assignable. @@ -23,6 +26,10 @@ class User extends Authenticatable 'name', 'email', 'password', + 'password_hash', + 'status', + 'last_login_at', + 'is_platform_admin', ]; /** @@ -32,6 +39,7 @@ class User extends Authenticatable */ protected $hidden = [ 'password', + 'password_hash', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token', @@ -47,9 +55,54 @@ protected function casts(): array return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', + 'last_login_at' => 'datetime', + 'is_platform_admin' => 'boolean', ]; } + protected static function booted(): void + { + static::saving(function (User $user): void { + if ($user->isDirty('password')) { + $user->password_hash = $user->password; + } elseif ($user->isDirty('password_hash')) { + $user->password = $user->password_hash; + } + }); + } + + public function stores(): BelongsToMany + { + return $this->belongsToMany(Store::class, 'store_users')->using(StoreUser::class)->withPivot('role')->withTimestamps(); + } + + public function getAuthPasswordName(): string + { + return 'password_hash'; + } + + public function getAuthPassword(): ?string + { + return $this->password_hash; + } + + public function isPlatformAdmin(): bool + { + return (bool) $this->is_platform_admin; + } + + public function roleForStore(Store $store): ?StoreUserRole + { + $pivot = $this->stores()->where('stores.id', $store->getKey())->first()?->pivot; + + return $pivot?->role instanceof StoreUserRole ? $pivot->role : ($pivot?->role ? StoreUserRole::tryFrom($pivot->role) : null); + } + + public function canManageStore(Store $store): bool + { + return in_array($this->roleForStore($store), [StoreUserRole::Owner, StoreUserRole::Admin], true); + } + /** * Get the user's initials */ diff --git a/app/Models/WebhookDelivery.php b/app/Models/WebhookDelivery.php new file mode 100644 index 00000000..e3c2e129 --- /dev/null +++ b/app/Models/WebhookDelivery.php @@ -0,0 +1,30 @@ + 'array', 'delivered_at' => 'datetime', 'last_attempt_at' => 'datetime', 'next_attempt_at' => 'datetime']; + } + + protected static function booted(): void + { + static::creating(function (WebhookDelivery $delivery): void { + $delivery->subscription_id ??= $delivery->webhook_subscription_id; + $delivery->attempt_count ??= $delivery->attempts ?? 0; + $delivery->event_id ??= (string) str()->uuid(); + }); + } + + public function subscription(): BelongsTo + { + return $this->belongsTo(WebhookSubscription::class, 'webhook_subscription_id'); + } +} diff --git a/app/Models/WebhookSubscription.php b/app/Models/WebhookSubscription.php new file mode 100644 index 00000000..0843161a --- /dev/null +++ b/app/Models/WebhookSubscription.php @@ -0,0 +1,33 @@ + 'encrypted']; + } + + protected static function booted(): void + { + static::saving(function (WebhookSubscription $subscription): void { + $subscription->event_type = $subscription->event; + }); + } + + public function deliveries(): HasMany + { + return $this->hasMany(WebhookDelivery::class); + } +} diff --git a/app/Observers/ProductObserver.php b/app/Observers/ProductObserver.php new file mode 100644 index 00000000..4f9c9dea --- /dev/null +++ b/app/Observers/ProductObserver.php @@ -0,0 +1,30 @@ +syncProduct($product); + ProductCreated::dispatch($product); + } + + public function updated(Product $product): void + { + app(SearchService::class)->syncProduct($product); + ProductUpdated::dispatch($product); + } + + public function deleted(Product $product): void + { + app(SearchService::class)->removeProduct($product->getKey()); + ProductDeleted::dispatch($product); + } +} diff --git a/app/Policies/CollectionPolicy.php b/app/Policies/CollectionPolicy.php new file mode 100644 index 00000000..d3218877 --- /dev/null +++ b/app/Policies/CollectionPolicy.php @@ -0,0 +1,38 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Collection $collection): bool + { + return $this->userHasModelStoreRole($user, $collection, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function update(User $user, Collection $collection): bool + { + return $this->userHasModelStoreRole($user, $collection, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function delete(User $user, Collection $collection): bool + { + return $this->userHasModelStoreRole($user, $collection, [StoreUserRole::Owner, StoreUserRole::Admin]); + } +} diff --git a/app/Policies/CustomerPolicy.php b/app/Policies/CustomerPolicy.php new file mode 100644 index 00000000..19f4fc62 --- /dev/null +++ b/app/Policies/CustomerPolicy.php @@ -0,0 +1,28 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Customer $customer): bool + { + return $this->userHasModelStoreRole($user, $customer, StoreUserRole::cases()); + } + + public function update(User $user, Customer $customer): bool + { + return $this->userHasModelStoreRole($user, $customer, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } +} diff --git a/app/Policies/DiscountPolicy.php b/app/Policies/DiscountPolicy.php new file mode 100644 index 00000000..8d236583 --- /dev/null +++ b/app/Policies/DiscountPolicy.php @@ -0,0 +1,38 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Discount $discount): bool + { + return $this->userHasModelStoreRole($user, $discount, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function update(User $user, Discount $discount): bool + { + return $this->userHasModelStoreRole($user, $discount, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function delete(User $user, Discount $discount): bool + { + return $this->userHasModelStoreRole($user, $discount, [StoreUserRole::Owner, StoreUserRole::Admin]); + } +} diff --git a/app/Policies/FulfillmentPolicy.php b/app/Policies/FulfillmentPolicy.php new file mode 100644 index 00000000..521cf7f7 --- /dev/null +++ b/app/Policies/FulfillmentPolicy.php @@ -0,0 +1,24 @@ +userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function view(User $user, Fulfillment $fulfillment): bool + { + return $this->userHasModelStoreRole($user, $fulfillment->loadMissing('order')->order, StoreUserRole::cases()); + } +} diff --git a/app/Policies/OrderPolicy.php b/app/Policies/OrderPolicy.php new file mode 100644 index 00000000..953d87e9 --- /dev/null +++ b/app/Policies/OrderPolicy.php @@ -0,0 +1,43 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Order $order): bool + { + return $this->userHasModelStoreRole($user, $order, StoreUserRole::cases()); + } + + public function update(User $user, Order $order): bool + { + return $this->userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function cancel(User $user, Order $order): bool + { + return $this->userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function createFulfillment(User $user, Order $order): bool + { + return $this->userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function createRefund(User $user, Order $order): bool + { + return $this->userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin]); + } +} diff --git a/app/Policies/PagePolicy.php b/app/Policies/PagePolicy.php new file mode 100644 index 00000000..ba5c8a74 --- /dev/null +++ b/app/Policies/PagePolicy.php @@ -0,0 +1,38 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Page $page): bool + { + return $this->userHasModelStoreRole($user, $page, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function update(User $user, Page $page): bool + { + return $this->userHasModelStoreRole($user, $page, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function delete(User $user, Page $page): bool + { + return $this->userHasModelStoreRole($user, $page, [StoreUserRole::Owner, StoreUserRole::Admin]); + } +} diff --git a/app/Policies/ProductPolicy.php b/app/Policies/ProductPolicy.php new file mode 100644 index 00000000..4f17597e --- /dev/null +++ b/app/Policies/ProductPolicy.php @@ -0,0 +1,48 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Product $product): bool + { + return $this->userHasModelStoreRole($user, $product, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function update(User $user, Product $product): bool + { + return $this->userHasModelStoreRole($user, $product, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]); + } + + public function delete(User $user, Product $product): bool + { + return $this->userHasModelStoreRole($user, $product, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function archive(User $user, Product $product): bool + { + return $this->delete($user, $product); + } + + public function restore(User $user, Product $product): bool + { + return $this->delete($user, $product); + } +} diff --git a/app/Policies/RefundPolicy.php b/app/Policies/RefundPolicy.php new file mode 100644 index 00000000..e54476bb --- /dev/null +++ b/app/Policies/RefundPolicy.php @@ -0,0 +1,24 @@ +userHasModelStoreRole($user, $order, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function view(User $user, Refund $refund): bool + { + return $this->userHasModelStoreRole($user, $refund->loadMissing('order')->order, StoreUserRole::cases()); + } +} diff --git a/app/Policies/StorePolicy.php b/app/Policies/StorePolicy.php new file mode 100644 index 00000000..e4beff23 --- /dev/null +++ b/app/Policies/StorePolicy.php @@ -0,0 +1,48 @@ +stores()->exists(); + } + + public function view(User $user, Store $store): bool + { + return $this->userHasModelStoreRole($user, $store, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function update(User $user, Store $store): bool + { + return $this->userHasModelStoreRole($user, $store, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function delete(User $user, Store $store): bool + { + return $this->userHasModelStoreRole($user, $store, [StoreUserRole::Owner]); + } + + public function restore(User $user, Store $store): bool + { + return $this->delete($user, $store); + } + + public function forceDelete(User $user, Store $store): bool + { + return $this->delete($user, $store); + } +} diff --git a/app/Policies/ThemePolicy.php b/app/Policies/ThemePolicy.php new file mode 100644 index 00000000..7a07bde7 --- /dev/null +++ b/app/Policies/ThemePolicy.php @@ -0,0 +1,43 @@ +userHasCurrentStoreRole($user, StoreUserRole::cases()); + } + + public function view(User $user, Theme $theme): bool + { + return $this->userHasModelStoreRole($user, $theme, StoreUserRole::cases()); + } + + public function create(User $user): bool + { + return $this->userHasCurrentStoreRole($user, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function update(User $user, Theme $theme): bool + { + return $this->userHasModelStoreRole($user, $theme, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function delete(User $user, Theme $theme): bool + { + return $this->userHasModelStoreRole($user, $theme, [StoreUserRole::Owner, StoreUserRole::Admin]); + } + + public function publish(User $user, Theme $theme): bool + { + return $this->update($user, $theme); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8a29e6f5..4064f084 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,11 +2,43 @@ namespace App\Providers; +use App\Auth\CustomerUserProvider; +use App\Auth\StoreScopedPasswordBrokerManager; +use App\Contracts\PaymentProvider as PaymentProviderContract; +use App\Contracts\TaxProvider; +use App\Events\CheckoutAddressed; +use App\Events\CheckoutCompleted; +use App\Events\CheckoutExpired; +use App\Events\CheckoutShippingSelected; +use App\Events\FulfillmentCreated; +use App\Events\OrderCreated; +use App\Events\OrderFulfilled; +use App\Events\OrderPaid; +use App\Events\OrderRefunded; +use App\Events\ProductCreated; +use App\Events\ProductDeleted; +use App\Events\ProductUpdated; +use App\Listeners\DispatchWebhooks; +use App\Listeners\RecordAuthenticationEvent; +use App\Models\Product; +use App\Observers\ProductObserver; +use App\Services\MockPaymentProvider; +use App\Services\Tax\ManualTaxProvider; use Carbon\CarbonImmutable; +use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\RateLimiter; +use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; +use Livewire\Livewire; +use Livewire\Mechanisms\HandleRequests\EndpointResolver; class AppServiceProvider extends ServiceProvider { @@ -15,7 +47,10 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + $this->app->bind(PaymentProviderContract::class, MockPaymentProvider::class); + $this->app->bind(TaxProvider::class, ManualTaxProvider::class); + Auth::provider('customer', fn ($app, array $config): CustomerUserProvider => new CustomerUserProvider($app['hash'], $config['model'])); + $this->app->extend('auth.password', fn ($manager, $app): StoreScopedPasswordBrokerManager => new StoreScopedPasswordBrokerManager($app)); } /** @@ -24,6 +59,49 @@ public function register(): void public function boot(): void { $this->configureDefaults(); + Model::preventLazyLoading(! app()->isProduction()); + Product::observe(ProductObserver::class); + Gate::policy(\App\Models\Collection::class, \App\Policies\CollectionPolicy::class); + Gate::policy(\App\Models\Customer::class, \App\Policies\CustomerPolicy::class); + Gate::policy(\App\Models\Discount::class, \App\Policies\DiscountPolicy::class); + Gate::policy(\App\Models\Fulfillment::class, \App\Policies\FulfillmentPolicy::class); + Gate::policy(\App\Models\Order::class, \App\Policies\OrderPolicy::class); + Gate::policy(\App\Models\Page::class, \App\Policies\PagePolicy::class); + Gate::policy(\App\Models\Product::class, \App\Policies\ProductPolicy::class); + Gate::policy(\App\Models\Refund::class, \App\Policies\RefundPolicy::class); + Gate::policy(\App\Models\Store::class, \App\Policies\StorePolicy::class); + Gate::policy(\App\Models\Theme::class, \App\Policies\ThemePolicy::class); + Event::listen([ + CheckoutAddressed::class, + CheckoutCompleted::class, + CheckoutExpired::class, + CheckoutShippingSelected::class, + FulfillmentCreated::class, + OrderCreated::class, + OrderFulfilled::class, + OrderPaid::class, + OrderRefunded::class, + ProductCreated::class, + ProductDeleted::class, + ProductUpdated::class, + ], DispatchWebhooks::class); + Event::listen([ + \Illuminate\Auth\Events\Failed::class, + \Illuminate\Auth\Events\Login::class, + \Illuminate\Auth\Events\Logout::class, + ], RecordAuthenticationEvent::class); + Livewire::setUpdateRoute(function ($handle): mixed { + return Route::post(EndpointResolver::updatePath(), $handle) + ->middleware(['web', 'store.resolve']) + ->name('shop.livewire.update'); + }); + RateLimiter::for('login', fn (Request $request): Limit => Limit::perMinute(5)->by($request->ip())); + RateLimiter::for('api.storefront', fn (Request $request): Limit => Limit::perMinute(120)->by($request->ip())); + RateLimiter::for('api.admin', fn (Request $request): Limit => Limit::perMinute(60)->by($request->user()?->getAuthIdentifier() ?? $request->ip())); + RateLimiter::for('checkout', fn (Request $request): Limit => Limit::perMinute(10)->by($request->hasSession() ? $request->session()->getId() : $request->ip())); + RateLimiter::for('search', fn (Request $request): Limit => Limit::perMinute(30)->by($request->ip())); + RateLimiter::for('analytics', fn (Request $request): Limit => Limit::perMinute(60)->by($request->ip())); + RateLimiter::for('webhooks', fn (Request $request): Limit => Limit::perMinute(100)->by($request->ip())); } /** diff --git a/app/Services/AnalyticsService.php b/app/Services/AnalyticsService.php new file mode 100644 index 00000000..d85d0547 --- /dev/null +++ b/app/Services/AnalyticsService.php @@ -0,0 +1,35 @@ + */ + private array $eventTypes = ['page_view', 'product_view', 'add_to_cart', 'remove_from_cart', 'checkout_started', 'checkout_completed', 'search']; + + public function track(Store $store, string $type, array $properties = [], ?string $sessionId = null, ?int $customerId = null, ?string $clientEventId = null, ?\DateTimeInterface $occurredAt = null): AnalyticsEvent + { + if (! in_array($type, $this->eventTypes, true)) { + throw new \InvalidArgumentException('Unsupported analytics event type.'); + } + + if ($clientEventId !== null) { + $existing = AnalyticsEvent::withoutGlobalScopes()->where('store_id', $store->getKey())->where('client_event_id', $clientEventId)->first(); + + if ($existing !== null) { + return $existing; + } + } + + return AnalyticsEvent::withoutGlobalScopes()->create(['store_id' => $store->getKey(), 'type' => $type, 'session_id' => $sessionId, 'customer_id' => $customerId, 'client_event_id' => $clientEventId, 'payload' => $properties, 'properties_json' => $properties, 'occurred_at' => $occurredAt ?? now()]); + } + + public function getDailyMetrics(Store $store, string $startDate, string $endDate): Collection + { + return \App\Models\AnalyticsDaily::withoutGlobalScopes()->where('store_id', $store->getKey())->whereBetween('date', [$startDate, $endDate])->orderBy('date')->get(); + } +} diff --git a/app/Services/AuditLogger.php b/app/Services/AuditLogger.php new file mode 100644 index 00000000..26ea7534 --- /dev/null +++ b/app/Services/AuditLogger.php @@ -0,0 +1,22 @@ +user(); + + Log::channel('audit')->info($event, array_merge([ + 'user_id' => $user?->getAuthIdentifier(), + 'subject_type' => $subject?->getMorphClass(), + 'subject_id' => $subject?->getKey(), + 'ip' => app()->runningInConsole() ? null : request()->ip(), + 'user_agent' => app()->runningInConsole() ? null : request()->userAgent(), + ], $context)); + } +} diff --git a/app/Services/CartService.php b/app/Services/CartService.php new file mode 100644 index 00000000..6435746a --- /dev/null +++ b/app/Services/CartService.php @@ -0,0 +1,160 @@ +create(['store_id' => $store->getKey(), 'customer_id' => $customer?->getKey(), 'currency' => $store->default_currency, 'cart_version' => 1, 'status' => 'active']); + } + + public function addLine(Cart $cart, int $variantId, int $quantity): CartLine + { + if ($quantity < 1 || $quantity > 9999) { + throw new \InvalidArgumentException('Quantity must be between 1 and 9999.'); + } + + return DB::transaction(function () use ($cart, $variantId, $quantity): CartLine { + $cart = Cart::withoutGlobalScopes()->lockForUpdate()->with('lines')->findOrFail($cart->getKey()); + $variant = ProductVariant::with(['product', 'inventory'])->findOrFail($variantId); + + if ($variant->product->store_id !== $cart->store_id || $variant->product->status !== ProductStatus::Active || $variant->status !== VariantStatus::Active) { + abort(404); + } + + $line = $cart->lines->firstWhere('variant_id', $variant->getKey()); + $newQuantity = ($line?->quantity ?? 0) + $quantity; + + if ($variant->inventory !== null && ! $variant->inventory->canSell($newQuantity)) { + throw new InsufficientInventoryException; + } + + $line ??= new CartLine(['cart_id' => $cart->getKey(), 'variant_id' => $variant->getKey()]); + $line->fill([ + 'quantity' => $newQuantity, + 'unit_price_amount' => $variant->price_amount, + 'line_subtotal_amount' => $variant->price_amount * $newQuantity, + 'line_discount_amount' => 0, + 'line_total_amount' => $variant->price_amount * $newQuantity, + ])->save(); + $cart->increment('cart_version'); + + return $line->load('variant.product'); + }); + } + + public function updateLineQuantity(Cart $cart, int $lineId, int $quantity): CartLine + { + if ($quantity < 1 || $quantity > 9999) { + throw new \InvalidArgumentException('Quantity must be between 1 and 9999.'); + } + + return DB::transaction(function () use ($cart, $lineId, $quantity): CartLine { + $line = $cart->lines()->with(['variant.inventory'])->findOrFail($lineId); + + if ($line->variant->inventory !== null && ! $line->variant->inventory->canSell($quantity)) { + throw new InsufficientInventoryException; + } + + $line->update(['quantity' => $quantity, 'line_subtotal_amount' => $line->unit_price_amount * $quantity, 'line_total_amount' => $line->unit_price_amount * $quantity]); + $cart->increment('cart_version'); + + return $line->refresh(); + }); + } + + public function removeLine(Cart $cart, int $lineId): void + { + DB::transaction(function () use ($cart, $lineId): void { + $cart->lines()->findOrFail($lineId)->delete(); + $cart->increment('cart_version'); + }); + } + + public function assertVersion(Cart $cart, ?int $expectedVersion): void + { + if ($expectedVersion !== null && $expectedVersion !== $cart->cart_version) { + throw new CartVersionConflictException; + } + } + + public function getOrCreateForSession(Store $store, ?Customer $customer = null): Cart + { + $key = 'cart_id_'.$store->getKey(); + $cart = $customer?->carts()->where('status', 'active')->latest()->first(); + + if ($cart === null) { + $sessionCartId = session($key, session('cart_id')); + $cart = Cart::withoutGlobalScopes()->whereKey($sessionCartId)->where('store_id', $store->getKey())->where('status', 'active')->first(); + } + + $cart ??= $this->create($store, $customer); + session([$key => $cart->getKey(), 'cart_id' => $cart->getKey()]); + + return $cart->load(['lines.variant.product', 'lines.variant.inventory']); + } + + public function mergeOnLogin(Cart $guest, Cart $customer): Cart + { + if ($guest->store_id !== $customer->store_id) { + throw new \InvalidArgumentException('Carts must belong to the same store.'); + } + + DB::transaction(function () use ($guest, $customer): void { + $guest = Cart::withoutGlobalScopes()->lockForUpdate()->with('lines.variant.product')->findOrFail($guest->getKey()); + $customer = Cart::withoutGlobalScopes()->lockForUpdate()->with('lines')->findOrFail($customer->getKey()); + $customerLines = $customer->lines->keyBy('variant_id'); + + foreach ($guest->lines as $guestLine) { + $variant = $guestLine->variant; + + if ($variant === null || $variant->product === null || $variant->product->status !== ProductStatus::Active || $variant->status !== VariantStatus::Active) { + continue; + } + + $customerLine = $customerLines->get($guestLine->variant_id); + $quantity = max((int) ($customerLine?->quantity ?? 0), (int) $guestLine->quantity); + + if ($variant->inventory !== null && ! $variant->inventory->canSell($quantity)) { + continue; + } + + $attributes = [ + 'quantity' => $quantity, + 'unit_price_amount' => $variant->price_amount, + 'line_subtotal_amount' => $variant->price_amount * $quantity, + 'line_discount_amount' => 0, + 'line_total_amount' => $variant->price_amount * $quantity, + ]; + + if ($customerLine === null) { + $customerLine = $customer->lines()->create(['variant_id' => $variant->getKey(), ...$attributes]); + $customerLines->put($variant->getKey(), $customerLine); + } else { + $customerLine->update($attributes); + } + + $customer->increment('cart_version'); + } + + $guest->update(['status' => 'abandoned']); + session()->forget(['cart_id_'.$guest->store_id, 'cart_id']); + }); + + return $customer->refresh()->load('lines'); + } +} diff --git a/app/Services/CheckoutService.php b/app/Services/CheckoutService.php new file mode 100644 index 00000000..e7b8e51b --- /dev/null +++ b/app/Services/CheckoutService.php @@ -0,0 +1,138 @@ +load('lines'); + + if ($cart->lines->isEmpty()) { + throw new \InvalidArgumentException('Cannot checkout an empty cart.'); + } + + Validator::make(['email' => $email], ['email' => ['required', 'email']])->validate(); + + return Checkout::create(['store_id' => $cart->store_id, 'cart_id' => $cart->getKey(), 'customer_id' => $customer?->getKey(), 'status' => CheckoutStatus::Started, 'email' => $email, 'discount_code' => $cart->discount_code, 'expires_at' => now()->addHours(24)]); + } + + public function setAddress(Checkout $checkout, array $address, ?array $billing = null, bool $useShippingAsBilling = true): Checkout + { + if (in_array($checkout->status, [CheckoutStatus::PaymentSelected, CheckoutStatus::PaymentPending, CheckoutStatus::Completed, CheckoutStatus::Expired], true)) { + throw new \LogicException('This checkout can no longer be changed.'); + } + + Validator::make($address, ['first_name' => ['required', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'address1' => ['required', 'string', 'max:500'], 'city' => ['required', 'string', 'max:255'], 'country_code' => ['required', 'string', 'size:2'], 'postal_code' => ['required', 'string', 'max:20']])->validate(); + $checkout->update(['shipping_address_json' => $address, 'billing_address_json' => $useShippingAsBilling ? $address : $billing, 'status' => CheckoutStatus::Addressed]); + $this->pricing->calculate($checkout->refresh()); + CheckoutAddressed::dispatch($checkout); + + return $checkout->refresh(); + } + + public function setShippingMethod(Checkout $checkout, int $rateId): Checkout + { + $checkout->loadMissing('cart.lines.variant'); + + if (! in_array($checkout->status, [CheckoutStatus::Addressed, CheckoutStatus::ShippingSelected], true)) { + throw new \LogicException('Checkout must have an address before selecting shipping.'); + } + + if (! $this->requiresShipping($checkout)) { + $checkout->update(['shipping_rate_id' => null, 'shipping_method_id' => null, 'status' => CheckoutStatus::ShippingSelected]); + $this->pricing->calculate($checkout->refresh()); + CheckoutShippingSelected::dispatch($checkout); + + return $checkout->refresh(); + } + + if ($checkout->shipping_address_json === null) { + throw new \LogicException('An address is required before selecting shipping.'); + } + + $rate = $checkout->shipping_address_json === null ? null : $this->shipping->getAvailableRates($checkout->store, $checkout->shipping_address_json)->firstWhere('id', $rateId); + + if ($rate === null) { + throw new \InvalidArgumentException('The selected shipping method is unavailable.'); + } + + $checkout->update(['shipping_rate_id' => $rate->getKey(), 'shipping_method_id' => $rate->getKey(), 'status' => CheckoutStatus::ShippingSelected]); + $this->pricing->calculate($checkout->refresh()); + CheckoutShippingSelected::dispatch($checkout); + + return $checkout->refresh(); + } + + public function selectPaymentMethod(Checkout $checkout, string $method): Checkout + { + Validator::make(['method' => $method], ['method' => ['required', 'in:credit_card,paypal,bank_transfer']])->validate(); + + $checkout->loadMissing('cart.lines.variant'); + + if ($checkout->shipping_address_json === null) { + throw new \LogicException('An address is required before selecting payment.'); + } + + if ($this->requiresShipping($checkout) && $checkout->shipping_rate_id === null) { + throw new \LogicException('A shipping method is required before selecting payment.'); + } + + if ($checkout->status !== CheckoutStatus::ShippingSelected) { + throw new \LogicException('Checkout must have a selected shipping method before selecting payment.'); + } + + $checkout->load('cart.lines.variant.inventory'); + + DB::transaction(function () use ($checkout, $method): void { + foreach ($checkout->cart->lines as $line) { + if ($line->variant->inventory !== null) { + $this->inventory->reserve($line->variant->inventory, $line->quantity); + } + } + + $checkout->update(['payment_method' => $method, 'status' => CheckoutStatus::PaymentSelected, 'expires_at' => now()->addHours(24)]); + }); + + return $checkout->refresh(); + } + + public function expireCheckout(Checkout $checkout): void + { + if ($checkout->status === CheckoutStatus::Expired || $checkout->status === CheckoutStatus::Completed) { + return; + } + + DB::transaction(function () use ($checkout): void { + if ($checkout->status === CheckoutStatus::PaymentSelected) { + $checkout->load('cart.lines.variant.inventory'); + + foreach ($checkout->cart->lines as $line) { + if ($line->variant->inventory !== null) { + $this->inventory->release($line->variant->inventory, $line->quantity); + } + } + } + + $checkout->update(['status' => CheckoutStatus::Expired]); + CheckoutExpired::dispatch($checkout->refresh()); + }); + } + + private function requiresShipping(Checkout $checkout): bool + { + return $checkout->cart->lines->contains(fn ($line): bool => (bool) $line->variant->requires_shipping); + } +} diff --git a/app/Services/DiscountService.php b/app/Services/DiscountService.php new file mode 100644 index 00000000..9df01e6e --- /dev/null +++ b/app/Services/DiscountService.php @@ -0,0 +1,103 @@ +where('store_id', $store->getKey())->whereRaw('lower(code) = ?', [strtolower($code)])->first(); + + if ($discount === null) { + throw new InvalidDiscountException('This discount code does not exist.', 'discount_not_found'); + } + + if ($discount->status !== 'active' || ($discount->ends_at !== null && $discount->ends_at->isPast())) { + throw new InvalidDiscountException('This discount code has expired.', 'discount_expired'); + } + + if ($discount->starts_at !== null && $discount->starts_at->isFuture()) { + throw new InvalidDiscountException('This discount code is not active yet.', 'discount_not_yet_active'); + } + + if ($discount->usage_limit !== null && $discount->usage_count >= $discount->usage_limit) { + throw new InvalidDiscountException('This discount code has reached its usage limit.', 'discount_usage_limit_reached'); + } + + $cart->loadMissing('lines.variant.product.collections'); + $minimum = (int) ($discount->rules_json['min_purchase_amount'] ?? $discount->rules_json['minimum_purchase_amount'] ?? 0); + + if ((int) $cart->lines->sum('line_subtotal_amount') < $minimum) { + throw new InvalidDiscountException('This discount requires a higher subtotal.', 'discount_min_purchase_not_met'); + } + + if ($this->qualifyingLines($discount, $cart->lines)->isEmpty()) { + throw new InvalidDiscountException('This discount does not apply to the items in your cart.', 'discount_not_applicable'); + } + + return $discount; + } + + /** @param array, quantity?: int}> $lines */ + public function calculate(Discount $discount, int $subtotal, array $lines): DiscountResult + { + $qualifyingLines = array_values(array_filter($lines, fn (array $line): bool => $this->lineQualifies($discount, $line))); + $eligibleSubtotal = array_sum(array_map(fn (array $line): int => (int) ($line['amount'] ?? 0), $qualifyingLines)); + $amount = match ($discount->value_type) { + DiscountValueType::Percent => intdiv($eligibleSubtotal * $discount->value_amount, 100), + DiscountValueType::Fixed => min($discount->value_amount, $eligibleSubtotal), + DiscountValueType::FreeShipping => 0, + }; + $allocations = []; + + if ($amount > 0 && $eligibleSubtotal > 0) { + $lastIndex = count($qualifyingLines) - 1; + $allocated = 0; + + foreach ($qualifyingLines as $index => $line) { + $lineAmount = (int) ($line['amount'] ?? 0); + $allocation = $index === $lastIndex + ? $amount - $allocated + : min($amount - $allocated, intdiv((2 * $amount * $lineAmount) + $eligibleSubtotal, 2 * $eligibleSubtotal)); + $allocations[(int) ($line['line_id'] ?? 0)] = $allocation; + $allocated += $allocation; + } + } + + return new DiscountResult($amount, $allocations, $discount->value_type === DiscountValueType::FreeShipping); + } + + /** @param \Illuminate\Support\Collection $lines */ + private function qualifyingLines(Discount $discount, Collection $lines): Collection + { + return $lines->filter(function ($line) use ($discount): bool { + return $this->lineQualifies($discount, [ + 'product_id' => $line->variant?->product_id, + 'collection_ids' => $line->variant?->product?->collections?->modelKeys() ?? [], + ]); + }); + } + + /** @param array{product_id?: int|null, collection_ids?: array} $line */ + private function lineQualifies(Discount $discount, array $line): bool + { + $rules = $discount->rules_json ?? []; + $productIds = array_map('intval', array_filter($rules['applicable_product_ids'] ?? [])); + $collectionIds = array_map('intval', array_filter($rules['applicable_collection_ids'] ?? [])); + + if ($productIds === [] && $collectionIds === []) { + return true; + } + + return in_array((int) ($line['product_id'] ?? 0), $productIds, true) + || array_intersect($collectionIds, array_map('intval', $line['collection_ids'] ?? [])) !== []; + } +} diff --git a/app/Services/FulfillmentService.php b/app/Services/FulfillmentService.php new file mode 100644 index 00000000..fe1081f6 --- /dev/null +++ b/app/Services/FulfillmentService.php @@ -0,0 +1,101 @@ +financial_status, [FinancialStatus::Paid, FinancialStatus::PartiallyRefunded], true)) { + throw new FulfillmentGuardException; + } + + return DB::transaction(function () use ($order, $lines, $tracking): Fulfillment { + $order->load(['lines', 'fulfillments.lines']); + $fulfilledQuantities = $order->fulfillments->flatMap->lines->groupBy('order_line_id')->map(fn ($items): int => (int) $items->sum('quantity')); + $requestedQuantities = []; + + foreach ($lines as $line) { + $orderLine = $order->lines->firstWhere('id', $line['order_line_id']); + $quantity = (int) ($line['quantity'] ?? 0); + $requestedQuantities[$line['order_line_id']] = ($requestedQuantities[$line['order_line_id']] ?? 0) + $quantity; + + if ($orderLine === null || $quantity < 1 || $orderLine->quantity < $requestedQuantities[$line['order_line_id']] + (int) ($fulfilledQuantities[$orderLine->id] ?? 0)) { + throw new \InvalidArgumentException('The fulfillment quantity exceeds the unfulfilled quantity.'); + } + } + + $fulfillment = $order->fulfillments()->create(array_merge($tracking ?? [], ['status' => 'pending'])); + + foreach ($lines as $line) { + $fulfillment->lines()->create(['order_line_id' => $line['order_line_id'], 'quantity' => $line['quantity']]); + } + + $this->refreshOrderStatus($order->refresh()); + FulfillmentCreated::dispatch($fulfillment->refresh()); + + return $fulfillment->load('lines.orderLine'); + }); + } + + public function markAsShipped(Fulfillment $fulfillment, ?array $tracking = null): void + { + if ($fulfillment->status !== 'pending') { + throw new \LogicException('Only pending fulfillments can be shipped.'); + } + + $fulfillment->update(array_merge($tracking ?? [], ['status' => 'shipped', 'shipped_at' => now(), 'fulfilled_at' => now()])); + FulfillmentShipped::dispatch($fulfillment->refresh()); + $this->refreshOrderStatus($fulfillment->load('order')->order); + } + + public function markAsDelivered(Fulfillment $fulfillment): void + { + if ($fulfillment->status !== 'shipped') { + throw new \LogicException('Only shipped fulfillments can be delivered.'); + } + + $fulfillment->update(['status' => 'delivered', 'delivered_at' => now()]); + $fulfillment->load('order'); + FulfillmentDelivered::dispatch($fulfillment); + + if ($fulfillment->order !== null) { + $this->refreshOrderStatus($fulfillment->order); + } + } + + private function refreshOrderStatus(Order $order): void + { + $order->load(['lines', 'fulfillments.lines']); + $fulfilledQuantities = []; + + foreach ($order->fulfillments->whereIn('status', ['shipped', 'delivered']) as $fulfillment) { + foreach ($fulfillment->lines as $line) { + $fulfilledQuantities[$line->order_line_id] = ($fulfilledQuantities[$line->order_line_id] ?? 0) + $line->quantity; + } + } + + $fulfilled = collect($order->lines)->every(fn ($line): bool => ($fulfilledQuantities[$line->id] ?? 0) >= $line->quantity); + $partial = $fulfilledQuantities !== []; + $order->update(['fulfillment_status' => $fulfilled ? FulfillmentStatus::Fulfilled : ($partial ? FulfillmentStatus::Partial : FulfillmentStatus::Unfulfilled)]); + + if ($fulfilled) { + $order->update(['status' => OrderStatus::Fulfilled]); + OrderFulfilled::dispatch($order->refresh()); + } elseif ($order->status === OrderStatus::Fulfilled) { + $order->update(['status' => OrderStatus::Paid]); + } + } +} diff --git a/app/Services/InventoryService.php b/app/Services/InventoryService.php new file mode 100644 index 00000000..2a7b2d81 --- /dev/null +++ b/app/Services/InventoryService.php @@ -0,0 +1,70 @@ +canSell($quantity); + } + + public function reserve(InventoryItem $item, int $quantity): void + { + $this->assertPositiveQuantity($quantity); + + DB::transaction(function () use ($item, $quantity): void { + $lockedItem = InventoryItem::withoutGlobalScopes()->lockForUpdate()->findOrFail($item->getKey()); + + if (! $lockedItem->canSell($quantity)) { + throw new InsufficientInventoryException; + } + + $lockedItem->increment('quantity_reserved', $quantity); + }); + } + + public function release(InventoryItem $item, int $quantity): void + { + $this->assertPositiveQuantity($quantity); + + DB::transaction(function () use ($item, $quantity): void { + $lockedItem = InventoryItem::withoutGlobalScopes()->lockForUpdate()->findOrFail($item->getKey()); + $lockedItem->update(['quantity_reserved' => max(0, $lockedItem->quantity_reserved - $quantity)]); + }); + } + + public function commit(InventoryItem $item, int $quantity): void + { + $this->assertPositiveQuantity($quantity); + + DB::transaction(function () use ($item, $quantity): void { + $lockedItem = InventoryItem::withoutGlobalScopes()->lockForUpdate()->findOrFail($item->getKey()); + $lockedItem->update([ + 'quantity_on_hand' => $lockedItem->quantity_on_hand - $quantity, + 'quantity_reserved' => max(0, $lockedItem->quantity_reserved - $quantity), + ]); + }); + } + + public function restock(InventoryItem $item, int $quantity): void + { + $this->assertPositiveQuantity($quantity); + + DB::transaction(function () use ($item, $quantity): void { + $lockedItem = InventoryItem::withoutGlobalScopes()->lockForUpdate()->findOrFail($item->getKey()); + $lockedItem->increment('quantity_on_hand', $quantity); + }); + } + + private function assertPositiveQuantity(int $quantity): void + { + if ($quantity < 1) { + throw new \InvalidArgumentException('Inventory quantity must be positive.'); + } + } +} diff --git a/app/Services/MockPaymentProvider.php b/app/Services/MockPaymentProvider.php new file mode 100644 index 00000000..3d863a55 --- /dev/null +++ b/app/Services/MockPaymentProvider.php @@ -0,0 +1,39 @@ + new PaymentResult(PaymentStatus::Failed, 'mock_'.Str::lower(Str::random(16)), 'Your card was declined.', 'card_declined'), + '4000000000009995' => new PaymentResult(PaymentStatus::Failed, 'mock_'.Str::lower(Str::random(16)), 'Your card has insufficient funds.', 'insufficient_funds'), + default => new PaymentResult(PaymentStatus::Captured, 'mock_'.Str::lower(Str::random(16)), 'Payment captured.'), + }; + } + + return new PaymentResult(PaymentStatus::Captured, 'mock_'.Str::lower(Str::random(16)), 'Payment captured.'); + } + + public function refund(Payment $payment, int $amount): RefundResult + { + return new RefundResult(true, 'mock_refund_'.Str::lower(Str::random(16)), 'Refund issued.'); + } +} diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php new file mode 100644 index 00000000..5eec46ef --- /dev/null +++ b/app/Services/OrderService.php @@ -0,0 +1,212 @@ +load(['cart.lines.variant.product', 'cart.lines.variant.inventory', 'shippingRate']); + $existing = Order::withoutGlobalScopes()->where('checkout_id', $checkout->getKey())->first(); + + if ($existing !== null) { + return $existing->load(['lines', 'payments']); + } + + $totals = $checkout->totals_json ?? ['subtotal' => 0, 'discount' => 0, 'shipping' => 0, 'tax' => 0, 'total' => 0, 'currency' => $checkout->cart->currency]; + if ($checkout->customer_id === null) { + $customer = Customer::withoutGlobalScopes()->firstOrCreate( + ['store_id' => $checkout->store_id, 'email' => strtolower($checkout->email)], + ['first_name' => 'Guest', 'last_name' => 'Customer', 'status' => 'active', 'metadata' => ['guest_checkout' => true]], + ); + $checkout->update(['customer_id' => $customer->getKey()]); + } + + $status = $paymentResult?->status === PaymentStatus::Captured ? FinancialStatus::Paid : FinancialStatus::Pending; + $taxByLine = $this->allocateTaxLines($checkout->cart->lines, $totals['tax_lines'] ?? []); + $order = Order::withoutGlobalScopes()->create([ + 'store_id' => $checkout->store_id, + 'customer_id' => $checkout->customer_id, + 'checkout_id' => $checkout->getKey(), + 'order_number' => $this->generateOrderNumber(Store::findOrFail($checkout->store_id)), + 'currency' => $totals['currency'], + 'status' => $status === FinancialStatus::Paid ? OrderStatus::Paid : OrderStatus::Pending, + 'financial_status' => $status, + 'fulfillment_status' => 'unfulfilled', + 'payment_method' => $checkout->payment_method, + 'email' => $checkout->email, + 'shipping_address_json' => $checkout->shipping_address_json, + 'billing_address_json' => $checkout->billing_address_json, + 'subtotal_amount' => $totals['subtotal'], + 'discount_amount' => $totals['discount'] ?? 0, + 'shipping_amount' => $totals['shipping'] ?? 0, + 'tax_amount' => $totals['tax'] ?? 0, + 'total_amount' => $totals['total'], + 'placed_at' => now(), + ]); + + foreach ($checkout->cart->lines as $line) { + $order->lines()->create([ + 'product_id' => $line->variant->product_id, + 'variant_id' => $line->variant_id, + 'product_title' => $line->variant->product->title, + 'title_snapshot' => $line->variant->product->title.' · '.$line->variant->title, + 'variant_title' => $line->variant->title, + 'sku' => $line->variant->sku, + 'sku_snapshot' => $line->variant->sku, + 'quantity' => $line->quantity, + 'unit_price_amount' => $line->unit_price_amount, + 'line_subtotal_amount' => $line->line_subtotal_amount, + 'line_discount_amount' => $line->line_discount_amount, + 'line_total_amount' => $line->line_total_amount, + 'tax_lines_json' => $taxByLine[$line->getKey()] ?? [], + 'discount_allocations_json' => $totals['discount_allocations'][$line->getKey()] ?? [], + ]); + + if ($paymentResult?->status === PaymentStatus::Captured && $line->variant->inventory !== null) { + $this->inventory->commit($line->variant->inventory, $line->quantity); + } + } + + $checkout->update(['status' => 'completed']); + $checkout->cart->update(['status' => 'converted']); + CheckoutCompleted::dispatch($checkout->refresh(), $order); + OrderCreated::dispatch($order); + $this->audit->record('order.created', $order, ['store_id' => $order->store_id, 'order_number' => $order->order_number]); + $order->load(['lines', 'payments']); + + if ($status === FinancialStatus::Paid) { + OrderPaid::dispatch($order); + $this->audit->record('order.paid', $order, ['store_id' => $order->store_id, 'order_number' => $order->order_number]); + + if ($checkout->cart->lines->every(fn ($line): bool => ! $line->variant->requires_shipping)) { + $fulfillment = $order->fulfillments()->create(['status' => 'delivered', 'fulfilled_at' => now(), 'delivered_at' => now()]); + + foreach ($order->lines as $line) { + $fulfillment->lines()->create(['order_line_id' => $line->getKey(), 'quantity' => $line->quantity]); + } + + $order->update(['status' => OrderStatus::Fulfilled, 'fulfillment_status' => FulfillmentStatus::Fulfilled]); + } + } + + return $order; + }); + } + + public function generateOrderNumber(Store $store): string + { + $lastNumber = Order::withoutGlobalScopes()->where('store_id', $store->getKey())->selectRaw("max(cast(replace(order_number, '#', '') as integer)) as value")->value('value'); + + return (string) config('shop.order_prefix', '#').(max(1000, (int) $lastNumber) + 1); + } + + public function cancel(Order $order, string $reason): void + { + if ($order->fulfillment_status !== FulfillmentStatus::Unfulfilled) { + throw new \LogicException('Fulfilled orders cannot be cancelled.'); + } + + DB::transaction(function () use ($order, $reason): void { + $wasPending = $order->financial_status === FinancialStatus::Pending; + $order->load('lines.variant.inventory')->update(['status' => OrderStatus::Cancelled, 'financial_status' => $order->financial_status === FinancialStatus::Pending ? FinancialStatus::Voided : $order->financial_status, 'metadata' => array_merge($order->metadata ?? [], ['cancellation_reason' => $reason])]); + + foreach ($order->lines as $line) { + if ($line->variant?->inventory !== null && $wasPending) { + $this->inventory->release($line->variant->inventory, $line->quantity); + } + } + + $order->payments()->whereIn('status', [PaymentStatus::Pending, PaymentStatus::Authorized])->update(['status' => PaymentStatus::Failed]); + + OrderCancelled::dispatch($order->refresh()); + $this->audit->record('order.cancelled', $order, ['store_id' => $order->store_id, 'order_number' => $order->order_number, 'reason' => $reason]); + }); + } + + public function confirmPayment(Order $order): void + { + if ($order->payment_method !== 'bank_transfer' || $order->financial_status !== FinancialStatus::Pending) { + throw new \LogicException('Only pending bank transfer orders can be confirmed.'); + } + + DB::transaction(function () use ($order): void { + $order->load('lines.variant.inventory')->update(['financial_status' => FinancialStatus::Paid, 'status' => OrderStatus::Paid]); + + foreach ($order->lines as $line) { + if ($line->variant?->inventory !== null) { + $this->inventory->commit($line->variant->inventory, $line->quantity); + } + } + + $order->payments()->where('status', PaymentStatus::Pending)->update(['status' => PaymentStatus::Captured]); + OrderPaid::dispatch($order->refresh()); + $this->audit->record('order.paid', $order, ['store_id' => $order->store_id, 'order_number' => $order->order_number]); + + if ($order->lines->every(fn ($line): bool => ! $line->variant?->requires_shipping)) { + $this->autoFulfillDigitalOrder($order->refresh()); + } + }); + } + + private function autoFulfillDigitalOrder(Order $order): void + { + if ($order->fulfillments()->exists()) { + return; + } + + $fulfillment = $order->fulfillments()->create(['status' => 'delivered', 'fulfilled_at' => now(), 'delivered_at' => now()]); + foreach ($order->lines as $line) { + $fulfillment->lines()->create(['order_line_id' => $line->getKey(), 'quantity' => $line->quantity]); + } + $order->update(['status' => OrderStatus::Fulfilled, 'fulfillment_status' => FulfillmentStatus::Fulfilled]); + } + + /** + * @param \Illuminate\Support\Collection $lines + * @param array $taxLines + * @return array>> + */ + private function allocateTaxLines(Collection $lines, array $taxLines): array + { + $base = max(1, (int) $lines->sum('line_total_amount')); + $allocations = $lines->mapWithKeys(fn ($line): array => [$line->getKey() => []])->all(); + + foreach ($taxLines as $taxLine) { + $remaining = (int) ($taxLine['amount'] ?? 0); + $lineCount = $lines->count(); + + foreach ($lines->values() as $index => $line) { + $amount = $index === $lineCount - 1 + ? $remaining + : intdiv((int) ($taxLine['amount'] ?? 0) * (int) $line->line_total_amount, $base); + $remaining -= $amount; + + if ($amount > 0) { + $allocations[$line->getKey()][] = [...$taxLine, 'amount' => $amount]; + } + } + } + + return $allocations; + } +} diff --git a/app/Services/PaymentProvider.php b/app/Services/PaymentProvider.php new file mode 100644 index 00000000..548859ca --- /dev/null +++ b/app/Services/PaymentProvider.php @@ -0,0 +1,5 @@ +where('checkout_id', $checkout->getKey())->first(); + + if ($existing !== null) { + return $existing->load(['lines', 'payments']); + } + + if ($checkout->status !== CheckoutStatus::PaymentSelected) { + throw new \LogicException('Checkout must have a selected payment method before payment.'); + } + + $checkout->update(['payment_method' => $method]); + $this->pricing->calculate($checkout->refresh()); + $checkout->load('cart.lines.variant.inventory'); + + $result = $this->provider->charge($checkout, $method, $details); + + if ($result->status === PaymentStatus::Failed) { + foreach ($checkout->cart->lines as $line) { + if ($line->variant->inventory !== null) { + $this->inventory->release($line->variant->inventory, $line->quantity); + } + } + + $checkout->update(['status' => CheckoutStatus::ShippingSelected]); + $declined = $result; + + return null; + } + + $order = $this->orders->createFromCheckout($checkout, $result); + Payment::create(['order_id' => $order->getKey(), 'provider' => 'mock', 'provider_payment_id' => $result->reference, 'method' => $method, 'status' => $result->status, 'amount' => $order->total_amount, 'currency' => $order->currency, 'raw_json' => ['reference' => $result->reference, 'message' => $result->message]]); + + $discountIds = collect($checkout->totals_json['discount_allocations'] ?? []) + ->flatMap(fn (array $allocations): array => $allocations) + ->pluck('discount_id') + ->filter() + ->unique(); + + if ($discountIds->isNotEmpty()) { + Discount::withoutGlobalScopes()->where('store_id', $checkout->store_id)->whereIn('id', $discountIds)->increment('usage_count'); + } + + return $order->refresh()->load(['lines', 'payments']); + }); + + if ($declined !== null) { + throw new PaymentDeclinedException($declined->errorCode ?? 'payment_failed', $declined->message ?: 'Payment failed.'); + } + + return $order; + } +} diff --git a/app/Services/PricingEngine.php b/app/Services/PricingEngine.php new file mode 100644 index 00000000..ced94738 --- /dev/null +++ b/app/Services/PricingEngine.php @@ -0,0 +1,107 @@ +load(['cart.lines.variant.product.collections', 'shippingRate']); + $cart = $checkout->cart; + $lines = $cart->lines; + $subtotal = (int) $lines->sum(fn ($line): int => $line->unit_price_amount * $line->quantity); + $discountAmount = 0; + $freeShipping = false; + $discountAllocations = []; + + foreach ($lines as $line) { + $line->updateQuietly(['line_discount_amount' => 0, 'line_total_amount' => $line->line_subtotal_amount]); + } + + $discounts = collect(); + + if ($checkout->discount_code !== null) { + $discount = Discount::withoutGlobalScopes()->where('store_id', $checkout->store_id)->whereRaw('lower(code) = ?', [strtolower($checkout->discount_code)])->first(); + + if ($discount?->isAvailable()) { + $discounts->push($discount); + } + } + + Discount::withoutGlobalScopes() + ->where('store_id', $checkout->store_id) + ->where('type', DiscountType::Automatic) + ->get() + ->filter(fn (Discount $discount): bool => $discount->isAvailable()) + ->each(fn (Discount $discount): mixed => $discounts->push($discount)); + + foreach ($discounts as $discount) { + $currentSubtotal = (int) $lines->sum('line_total_amount'); + $minimum = (int) ($discount->rules_json['min_purchase_amount'] ?? $discount->rules_json['minimum_purchase_amount'] ?? 0); + + if ($currentSubtotal < $minimum) { + continue; + } + + $result = $this->discounts->calculate($discount, $currentSubtotal, $lines->map(fn ($line): array => [ + 'line_id' => $line->id, + 'amount' => $line->line_total_amount, + 'product_id' => $line->variant->product_id, + 'collection_ids' => $line->variant->product->collections->modelKeys(), + ])->all()); + $discountAmount += $result->amount; + $freeShipping = $freeShipping || $result->freeShipping; + + foreach ($lines as $line) { + $lineDiscount = $result->allocations[$line->id] ?? 0; + $line->updateQuietly([ + 'line_discount_amount' => $line->line_discount_amount + $lineDiscount, + 'line_total_amount' => max(0, $line->line_total_amount - $lineDiscount), + ]); + if ($lineDiscount > 0) { + $discountAllocations[$line->id][] = ['discount_id' => $discount->getKey(), 'amount' => $lineDiscount]; + } + } + } + + $shippingAmount = $checkout->shippingRate !== null && ! $freeShipping ? ($this->shipping->calculate($checkout->shippingRate, $cart) ?? 0) : 0; + $taxSettings = TaxSettings::withoutGlobalScopes()->firstOrCreate(['store_id' => $checkout->store_id], ['default_rate_basis_points' => 0]); + $taxLines = []; + + foreach ($lines as $line) { + $lineAmount = max(0, $line->line_subtotal_amount - $line->line_discount_amount); + $taxLines = [...$taxLines, ...$this->taxes->calculate($lineAmount, $taxSettings, $checkout->shipping_address_json ?? [])->lines]; + } + + if ($shippingAmount > 0) { + $taxLines = [...$taxLines, ...$this->taxes->calculate($shippingAmount, $taxSettings, $checkout->shipping_address_json ?? [])->lines]; + } + + $taxTotal = (int) collect($taxLines)->sum('amount'); + $discountedSubtotal = max(0, $subtotal - $discountAmount); + $pricesIncludeTax = (bool) $taxSettings->prices_include_tax || $taxSettings->mode === 'inclusive'; + $total = max(0, $discountedSubtotal + $shippingAmount + ($pricesIncludeTax ? 0 : $taxTotal)); + $result = new PricingResult($subtotal, $discountAmount, $shippingAmount, $taxLines, $taxTotal, $total, $cart->currency); + $totals = [...$result->toArray(), 'discount_allocations' => $discountAllocations]; + $checkout->update([ + 'totals_json' => $totals, + 'tax_provider_snapshot_json' => [ + 'provider' => $taxSettings->provider, + 'mode' => $taxSettings->mode, + 'rates' => $taxSettings->rates_json ?? [], + 'captured_at' => now()->toIso8601String(), + 'tax_total' => $taxTotal, + ], + ]); + + return $result; + } +} diff --git a/app/Services/ProductService.php b/app/Services/ProductService.php new file mode 100644 index 00000000..22f3023d --- /dev/null +++ b/app/Services/ProductService.php @@ -0,0 +1,264 @@ + 'Default', 'price_amount' => 0, 'is_default' => true]]; + $status = $data['status'] ?? ProductStatus::Draft; + $status = $status instanceof ProductStatus ? $status : ProductStatus::from($status); + $product = Product::withoutGlobalScopes()->create([ + 'store_id' => $store->getKey(), + 'title' => $data['title'], + 'handle' => $data['handle'] ?? $this->handles->generate($data['title'], 'products', $store->getKey()), + 'description' => $this->sanitizer->sanitize($data['description'] ?? null), + 'description_html' => $this->sanitizer->sanitize($data['description_html'] ?? $data['description'] ?? null), + 'vendor' => $data['vendor'] ?? null, + 'product_type' => $data['product_type'] ?? null, + 'tags' => $data['tags'] ?? [], + 'status' => $status, + 'published_at' => $status === ProductStatus::Active ? now() : null, + ]); + + $this->syncCatalogDetails($product, $store, $data, true); + + if ($status === ProductStatus::Active && (trim((string) $product->title) === '' || ! $product->variants()->where('price_amount', '>', 0)->exists())) { + throw new InvalidProductTransitionException('An active product requires a title and a priced variant.'); + } + + $this->audit->record('product.created', $product, ['store_id' => $store->getKey()]); + + return $product->load(['variants.inventory', 'options.values', 'variants.optionValues', 'media', 'collections']); + }); + } + + public function update(Product $product, array $data): Product + { + return DB::transaction(function () use ($product, $data): Product { + $updates = array_intersect_key($data, array_flip(['title', 'handle', 'description', 'description_html', 'vendor', 'product_type', 'tags', 'published_at'])); + + $newStatus = null; + + if (array_key_exists('status', $data)) { + $newStatus = $data['status'] instanceof ProductStatus ? $data['status'] : ProductStatus::from($data['status']); + } + + if (array_key_exists('description', $data)) { + $updates['description'] = $this->sanitizer->sanitize($data['description']); + $updates['description_html'] = $this->sanitizer->sanitize($data['description']); + } elseif (array_key_exists('description_html', $data)) { + $updates['description_html'] = $this->sanitizer->sanitize($data['description_html']); + } + + $product->update($updates); + + if ($newStatus !== null) { + $this->transitionStatus($product->refresh(), $newStatus); + } + + if (array_key_exists('options', $data) || array_key_exists('variants', $data) || array_key_exists('remove_variant_ids', $data) || array_key_exists('collections', $data)) { + $this->syncCatalogDetails($product->refresh(), $product->store, $data, array_key_exists('options', $data)); + } + + $product = $product->refresh()->load(['variants.inventory', 'options.values', 'variants.optionValues', 'media', 'collections']); + $this->audit->record('product.updated', $product, ['store_id' => $product->store_id]); + + return $product; + }); + } + + public function transitionStatus(Product $product, ProductStatus $newStatus): void + { + $from = $product->status instanceof ProductStatus ? $product->status : ProductStatus::from($product->status); + + if ($from === $newStatus) { + return; + } + + if ($newStatus === ProductStatus::Active && (! $product->variants()->where('price_amount', '>', 0)->exists() || trim((string) $product->title) === '')) { + throw new InvalidProductTransitionException('An active product requires a title and a priced variant.'); + } + + if ($newStatus === ProductStatus::Draft && in_array($from, [ProductStatus::Active, ProductStatus::Archived], true) && $product->orders()->exists()) { + throw new InvalidProductTransitionException('Products with order history cannot be reverted to draft.'); + } + + $product->update(['status' => $newStatus, 'published_at' => $newStatus === ProductStatus::Active ? ($product->published_at ?? now()) : null]); + ProductStatusChanged::dispatch($product->refresh(), $from, $newStatus); + $this->audit->record('product.updated', $product, ['from_status' => $from->value, 'to_status' => $newStatus->value, 'store_id' => $product->store_id]); + } + + public function delete(Product $product): void + { + if ($product->status !== ProductStatus::Draft || $product->orders()->exists()) { + throw new LogicException('Only draft products with no order history can be deleted.'); + } + + $product->delete(); + $this->audit->record('product.deleted', $product, ['store_id' => $product->store_id]); + } + + /** + * Persist product options, variants, inventory, option-value links, and collections. + * + * @param array $data + */ + private function syncCatalogDetails(Product $product, Store $store, array $data, bool $replaceOptions): void + { + $optionsByName = $this->optionMap($product, $data['options'] ?? [], $replaceOptions); + $variants = $data['variants'] ?? []; + + foreach ($variants as $position => $variantData) { + $optionValues = $variantData['option_values'] ?? []; + $inventoryData = $variantData['inventory'] ?? null; + $variantId = $variantData['id'] ?? null; + $attributes = Arr::except($variantData, ['id', 'option_values', 'inventory', 'quantity_on_hand', 'policy']); + $weight = $attributes['weight_g'] ?? $attributes['weight_grams'] ?? 0; + $attributes['weight_g'] = $weight; + $attributes['weight_grams'] = $weight; + $attributes['currency'] ??= $store->default_currency; + $attributes['position'] ??= $position + 1; + $attributes['is_default'] ??= $position === 0; + $attributes['title'] ??= $this->variantTitle($optionValues); + + if (($attributes['compare_at_amount'] ?? null) !== null && (int) $attributes['compare_at_amount'] <= (int) ($attributes['price_amount'] ?? 0)) { + throw new \InvalidArgumentException('A compare-at price must be greater than the variant price.'); + } + + if (($attributes['sku'] ?? null) !== null) { + $skuQuery = ProductVariant::query()->where('sku', $attributes['sku'])->whereHas('product', fn ($query) => $query->where('store_id', $store->getKey())); + if ($variantId !== null) { + $skuQuery->where('id', '!=', $variantId); + } + if ($skuQuery->exists()) { + throw new \InvalidArgumentException('Variant SKUs must be unique within a store.'); + } + } + + if ($variantId !== null) { + $variant = $product->variants()->whereKey($variantId)->first(); + if ($variant === null) { + throw new \InvalidArgumentException('The variant does not belong to this product.'); + } + $variant->update($attributes); + } else { + $variant = $product->variants()->create($attributes); + } + + if ($inventoryData !== null || $variantId === null) { + $inventoryData ??= []; + InventoryItem::withoutGlobalScopes()->updateOrCreate( + ['variant_id' => $variant->getKey()], + ['store_id' => $store->getKey(), 'quantity_on_hand' => (int) ($inventoryData['quantity_on_hand'] ?? 0), 'policy' => $inventoryData['policy'] ?? 'deny'], + ); + } + + if ($optionValues !== []) { + $variant->optionValues()->sync($this->resolveOptionValueIds($optionsByName, $optionValues)); + } + } + + if ($data['remove_variant_ids'] ?? false) { + $product->variants()->whereIn('id', $data['remove_variant_ids'])->delete(); + } + + if (array_key_exists('variants', $data)) { + $this->ensureSingleDefaultVariant($product); + } + + if (array_key_exists('collections', $data)) { + $collectionIds = $data['collections'] ?? []; + $product->collections()->sync(array_fill_keys($collectionIds, ['position' => 0])); + } + } + + /** + * @param array> $optionData + * @return array + */ + private function optionMap(Product $product, array $optionData, bool $replace): array + { + if ($replace) { + $product->options()->delete(); + } + + $options = $replace ? collect() : $product->options()->with('values')->get(); + + foreach ($optionData as $position => $optionDataItem) { + $option = $product->options()->updateOrCreate( + ['position' => $optionDataItem['position'] ?? $position + 1], + ['name' => $optionDataItem['name']], + ); + $options = $options->push($option->load('values')); + + foreach ($optionDataItem['values'] ?? [] as $valuePosition => $valueData) { + $option->values()->updateOrCreate( + ['value' => $valueData['value']], + ['position' => $valueData['position'] ?? $valuePosition + 1], + ); + } + } + + return $options->keyBy('name')->all(); + } + + /** + * @param array $optionsByName + * @param array> $optionValues + * @return array + */ + private function resolveOptionValueIds(array $optionsByName, array $optionValues): array + { + $ids = []; + + foreach ($optionValues as $optionValue) { + $option = $optionsByName[$optionValue['option_name']] ?? null; + if ($option === null) { + throw new \InvalidArgumentException('Variant option values must match the product options.'); + } + + $value = $option->values()->firstOrCreate(['value' => $optionValue['value']], ['position' => $option->values()->count() + 1]); + $ids[] = $value->getKey(); + } + + return $ids; + } + + /** @param array> $optionValues */ + private function variantTitle(array $optionValues): string + { + return $optionValues === [] ? 'Default' : implode(' / ', array_column($optionValues, 'value')); + } + + private function ensureSingleDefaultVariant(Product $product): void + { + $variants = $product->variants()->get(); + $default = $variants->firstWhere('is_default', true) ?? $variants->first(); + + if ($default === null) { + throw new \InvalidArgumentException('A product must have at least one variant.'); + } + + $product->variants()->where('id', '!=', $default->getKey())->update(['is_default' => false]); + $default->update(['is_default' => true]); + } +} diff --git a/app/Services/RefundService.php b/app/Services/RefundService.php new file mode 100644 index 00000000..7e073676 --- /dev/null +++ b/app/Services/RefundService.php @@ -0,0 +1,102 @@ +|null $amount + * @param array $lines + */ + public function create(Order $order, Payment $payment, int|array|null $amount = null, ?string $reason = null, bool $restock = false, array $lines = []): Refund + { + if ((int) $payment->order_id !== (int) $order->getKey() || $payment->status !== PaymentStatus::Captured) { + throw new \InvalidArgumentException('The payment is not refundable for this order.'); + } + + if (is_array($amount)) { + $lines = $amount; + $amount = null; + } + + $refunded = (int) $order->refunds()->where('status', 'processed')->sum('amount'); + $order->loadMissing('lines'); + $restockLines = $lines; + $previousLineQuantities = []; + foreach ($order->refunds()->where('status', 'processed')->get(['lines_json']) as $previousRefund) { + foreach ($previousRefund->lines_json ?? [] as $lineId => $quantity) { + $previousLineQuantities[(string) $lineId] = ($previousLineQuantities[(string) $lineId] ?? 0) + (int) $quantity; + } + } + + if ($lines !== []) { + $amount = 0; + + foreach ($lines as $lineId => $quantity) { + $orderLine = $order->lines->firstWhere('id', (int) $lineId); + + if ($orderLine === null || $quantity < 1 || $quantity > $orderLine->quantity) { + throw new \InvalidArgumentException('The refund quantity is invalid.'); + } + + if (($previousLineQuantities[(string) $lineId] ?? 0) + $quantity > $orderLine->quantity) { + throw new \InvalidArgumentException('The refund quantity exceeds the remaining refundable quantity.'); + } + + $unitAmount = intdiv($orderLine->line_total_amount, $orderLine->quantity); + $amount += $unitAmount * $quantity; + } + } + + $amount ??= $payment->amount - $refunded; + + if ($amount < 1 || $refunded + $amount > $payment->amount) { + throw new \InvalidArgumentException('Refund amount exceeds the captured payment.'); + } + + if ($restock && $restockLines === [] && $refunded + $amount >= $payment->amount) { + $restockLines = $order->lines->mapWithKeys(fn ($line): array => [$line->getKey() => $line->quantity])->all(); + } + + return DB::transaction(function () use ($order, $payment, $amount, $reason, $restock, $restockLines, $lines): Refund { + $result = $this->provider->refund($payment, $amount); + $refund = $order->refunds()->create(['payment_id' => $payment->getKey(), 'amount' => $amount, 'status' => $result->successful ? 'processed' : 'failed', 'provider_refund_id' => $result->reference, 'reason' => $reason, 'restock' => $restock, 'lines_json' => $lines !== [] ? $lines : null]); + + if ($result->successful) { + $totalRefunded = (int) $order->refunds()->where('status', 'processed')->sum('amount'); + $order->update([ + 'financial_status' => $totalRefunded >= $payment->amount ? FinancialStatus::Refunded : FinancialStatus::PartiallyRefunded, + 'status' => $totalRefunded >= $payment->amount ? 'refunded' : $order->status, + ]); + $payment->update(['status' => $totalRefunded >= $payment->amount ? PaymentStatus::Refunded : $payment->status]); + + if ($restock && $restockLines !== []) { + $order->load('lines.variant.inventory'); + foreach ($restockLines as $lineId => $quantity) { + $line = $order->lines->firstWhere('id', (int) $lineId); + + if ($line->variant?->inventory !== null) { + $this->inventory->restock($line->variant->inventory, (int) $quantity); + } + } + } + + OrderRefunded::dispatch($order->refresh()); + $this->audit->record('order.refunded', $order, ['store_id' => $order->store_id, 'order_number' => $order->order_number, 'amount' => $amount]); + } + + return $refund; + }); + } +} diff --git a/app/Services/SearchService.php b/app/Services/SearchService.php new file mode 100644 index 00000000..a7e8a42f --- /dev/null +++ b/app/Services/SearchService.php @@ -0,0 +1,95 @@ +published() + ->where('store_id', $store->getKey()) + ->when(trim($query) !== '', function (Builder $builder) use ($query): void { + $tokens = preg_split('/[^\pL\pN]+/u', trim($query), -1, PREG_SPLIT_NO_EMPTY); + $match = collect($tokens ?: [])->map(fn (string $token): string => '"'.str_replace('"', '""', $token).'*"')->implode(' '); + + if ($match !== '' && Schema::hasTable('products_fts')) { + $builder->whereIn('id', DB::table('products_fts')->select('product_id')->whereColumn('products_fts.store_id', 'products.store_id')->whereRaw('products_fts MATCH ?', [$match])); + } + }) + ->when($filters['vendor'] ?? null, fn (Builder $builder, string $vendor): Builder => $builder->where('vendor', $vendor)) + ->when(isset($filters['collection_id']), fn (Builder $builder): Builder => $builder->whereHas('collections', fn (Builder $collections): Builder => $collections->whereKey((int) $filters['collection_id']))) + ->when($minimumPrice !== null, fn (Builder $builder): Builder => $builder->whereHas('variants', fn (Builder $variants): Builder => $variants->where('price_amount', '>=', (int) $minimumPrice))) + ->when($maximumPrice !== null, fn (Builder $builder): Builder => $builder->whereHas('variants', fn (Builder $variants): Builder => $variants->where('price_amount', '<=', (int) $maximumPrice))) + ->when($filters['in_stock'] ?? false, fn (Builder $builder): Builder => $builder->whereHas('variants', fn (Builder $variants): Builder => $variants->whereHas('inventory', fn (Builder $inventory): Builder => $inventory->whereColumn('quantity_on_hand', '>', 'quantity_reserved')->orWhere('policy', 'continue')))) + ->when($filters['tags'] ?? [], fn (Builder $builder, array $tags): Builder => $builder->where(function (Builder $products) use ($tags): void { + foreach ($tags as $tag) { + $products->whereJsonContains('tags', $tag); + } + })) + ->with(['variants.inventory', 'media']) + ->when($sort === 'price_asc', fn (Builder $builder): Builder => $builder->withMin('variants', 'price_amount')->orderBy('variants_min_price_amount')) + ->when($sort === 'price_desc', fn (Builder $builder): Builder => $builder->withMin('variants', 'price_amount')->orderByDesc('variants_min_price_amount')) + ->when($sort === 'best_selling', fn (Builder $builder): Builder => $builder->orderByDesc('sales_count')) + ->when(! in_array($sort, ['price_asc', 'price_desc', 'best_selling'], true), fn (Builder $builder): Builder => $builder->latest('published_at')) + ->paginate($perPage, ['*'], 'page', $page); + + if (Schema::hasTable('search_queries')) { + SearchQuery::withoutGlobalScopes()->create(['store_id' => $store->getKey(), 'query' => $query, 'results_count' => $products->total(), 'customer_id' => auth('customer')->id()]); + } + + return $products; + } + + public function autocomplete(Store $store, string $prefix, int $limit = 8): Collection + { + if (mb_strlen(trim($prefix)) < 2) { + return collect(); + } + + return Product::withoutGlobalScopes() + ->published() + ->where('store_id', $store->getKey()) + ->where('title', 'like', '%'.trim($prefix).'%') + ->orderBy('title') + ->limit($limit) + ->with(['media', 'variants']) + ->get(); + } + + public function syncProduct(Product $product): void + { + if (! Schema::hasTable('products_fts')) { + return; + } + + $this->removeProduct($product->getKey()); + DB::table('products_fts')->insert([ + 'product_id' => $product->getKey(), + 'store_id' => $product->store_id, + 'title' => $product->title, + 'description' => $product->description, + 'vendor' => $product->vendor, + 'product_type' => $product->product_type, + 'tags' => is_array($product->tags) ? implode(' ', $product->tags) : (string) $product->tags, + ]); + } + + public function removeProduct(int $productId): void + { + if (Schema::hasTable('products_fts')) { + DB::table('products_fts')->where('product_id', $productId)->delete(); + } + } +} diff --git a/app/Services/ShippingCalculator.php b/app/Services/ShippingCalculator.php new file mode 100644 index 00000000..33255bc0 --- /dev/null +++ b/app/Services/ShippingCalculator.php @@ -0,0 +1,63 @@ +where('is_active', true)->whereHas('zone', fn ($query) => $query->where('store_id', $store->getKey()))->with('zone')->get(); + + $matching = $rates->filter(function (ShippingRate $rate) use ($country, $region): bool { + $countries = array_map('strtoupper', $rate->zone->countries_json ?? []); + $regions = array_map('strtoupper', $rate->zone->regions_json ?? []); + + return $country !== '' && in_array($country, $countries, true) + && ($region === '' || $regions === [] || in_array($region, $regions, true)); + }); + + $specificity = $matching->groupBy(function (ShippingRate $rate) use ($region): int { + $countries = array_map('strtoupper', $rate->zone->countries_json ?? []); + $regions = array_map('strtoupper', $rate->zone->regions_json ?? []); + + return $region !== '' && in_array($region, $regions, true) ? 2 : 1; + }); + + return $specificity->sortKeysDesc()->first()?->sortBy('id')->values() ?? collect(); + } + + public function calculate(ShippingRate $rate, Cart $cart): ?int + { + $lines = $cart->load('lines.variant')->lines; + $lines = $lines->filter(fn ($line): bool => (bool) $line->variant->requires_shipping); + $weight = (int) $lines->sum(fn ($line): int => $line->quantity * ($line->variant->weight_g ?? $line->variant->weight_grams)); + $subtotal = (int) $lines->sum('line_total_amount'); + $config = $rate->config_json ?? []; + + return match ($rate->type) { + 'weight' => $this->rangeAmount($config['ranges'] ?? [], $weight, $rate->price_amount), + 'price' => $this->rangeAmount($config['ranges'] ?? [], $subtotal, $rate->price_amount), + 'carrier' => (int) ($config['amount'] ?? $rate->price_amount ?? 0), + default => (int) ($config['amount'] ?? $rate->price_amount ?? 0), + }; + } + + private function rangeAmount(array $ranges, int $value, ?int $fallback): ?int + { + foreach ($ranges as $range) { + if ($value >= (int) ($range['min_g'] ?? $range['min_amount'] ?? 0) && $value <= (int) ($range['max_g'] ?? $range['max_amount'] ?? PHP_INT_MAX)) { + return (int) ($range['amount'] ?? $fallback ?? 0); + } + } + + return null; + } +} diff --git a/app/Services/Tax/ManualTaxProvider.php b/app/Services/Tax/ManualTaxProvider.php new file mode 100644 index 00000000..65f9d9cc --- /dev/null +++ b/app/Services/Tax/ManualTaxProvider.php @@ -0,0 +1,51 @@ +address['country_code'] ?? '')); + $rate = (int) ($request->settings->rates_json[$country] ?? $request->settings->default_rate_basis_points); + $taxLines = []; + + foreach ($request->lineItems as $line) { + $amount = (int) ($line['amount'] ?? $line['line_total_amount'] ?? 0); + $tax = $request->settings->prices_include_tax || $request->settings->mode === 'inclusive' + ? $this->extractInclusive($amount, $rate) + : $this->roundTax($amount, $rate); + + if ($tax > 0) { + $taxLines[] = new TaxLine('Sales tax', $rate, $tax); + } + } + + if ($request->shippingAmount > 0) { + $tax = $request->settings->prices_include_tax || $request->settings->mode === 'inclusive' + ? $this->extractInclusive($request->shippingAmount, $rate) + : $this->roundTax($request->shippingAmount, $rate); + + if ($tax > 0) { + $taxLines[] = new TaxLine('Shipping tax', $rate, $tax); + } + } + + return new TaxResult(array_sum(array_map(fn (TaxLine $line): int => $line->amount, $taxLines)), $taxLines); + } + + private function roundTax(int $amount, int $rate): int + { + return (int) floor(($amount * $rate / 10000) + 0.5); + } + + private function extractInclusive(int $amount, int $rate): int + { + return $rate > 0 ? $amount - intdiv($amount * 10000, 10000 + $rate) : 0; + } +} diff --git a/app/Services/Tax/StripeTaxProvider.php b/app/Services/Tax/StripeTaxProvider.php new file mode 100644 index 00000000..04664a50 --- /dev/null +++ b/app/Services/Tax/StripeTaxProvider.php @@ -0,0 +1,21 @@ +settings->provider_config_json['fallback'] ?? 'allow') === 'block') { + throw new \RuntimeException('Stripe Tax is not configured for this environment.'); + } + + return new TaxResult(0, []); + } +} diff --git a/app/Services/TaxCalculator.php b/app/Services/TaxCalculator.php new file mode 100644 index 00000000..bfdfe3db --- /dev/null +++ b/app/Services/TaxCalculator.php @@ -0,0 +1,36 @@ +provider; + + if ($provider === null) { + $provider = $settings->mode === 'provider' && $settings->provider === 'stripe_tax' + ? new \App\Services\Tax\StripeTaxProvider(new \App\Services\Tax\ManualTaxProvider) + : new \App\Services\Tax\ManualTaxProvider; + } + + return $provider->calculate(new TaxCalculationRequest([['amount' => $amount]], 0, $address, $settings)); + } + + public function extractInclusive(int $grossAmount, int $rateBasisPoints): int + { + return $rateBasisPoints > 0 ? intdiv($grossAmount * $rateBasisPoints, 10000 + $rateBasisPoints) : 0; + } + + public function addExclusive(int $netAmount, int $rateBasisPoints): int + { + return intdiv($netAmount * $rateBasisPoints, 10000); + } +} diff --git a/app/Services/VariantMatrixService.php b/app/Services/VariantMatrixService.php new file mode 100644 index 00000000..d647095a --- /dev/null +++ b/app/Services/VariantMatrixService.php @@ -0,0 +1,68 @@ +load(['options.values', 'variants.optionValues']); + $groups = $product->options->map(fn ($option): array => $option->values->all())->filter()->values()->all(); + + if ($groups === []) { + if ($product->variants->isEmpty()) { + $product->variants()->create(['title' => 'Default', 'price_amount' => 0, 'is_default' => true, 'position' => 0]); + } + + return; + } + + $combinations = $this->cartesianProduct($groups); + $existing = $product->variants->keyBy(fn (ProductVariant $variant): string => $variant->optionValues->modelKeys()->sort()->implode('-')); + $position = 0; + + foreach ($combinations as $combination) { + $key = collect($combination)->pluck('id')->sort()->implode('-'); + $variant = $existing->pull($key); + + if ($variant === null) { + $variant = $product->variants()->create([ + 'title' => collect($combination)->pluck('value')->implode(' / '), + 'price_amount' => (int) ($product->variants->first()?->price_amount ?? 0), + 'is_default' => $position === 0, + 'position' => $position, + ]); + InventoryItem::withoutGlobalScopes()->create(['store_id' => $product->store_id, 'variant_id' => $variant->getKey(), 'quantity_on_hand' => 0, 'policy' => 'deny']); + } + + $variant->optionValues()->sync(collect($combination)->pluck('id')->all()); + $position++; + } + + foreach ($existing as $orphan) { + if ($orphan->orders()->exists()) { + $orphan->update(['status' => 'archived', 'is_default' => false]); + + continue; + } + + $orphan->delete(); + } + } + + /** @param array> $groups */ + private function cartesianProduct(array $groups): array + { + $result = [[]]; + + foreach ($groups as $group) { + $result = collect($result)->flatMap(fn (array $prefix): array => array_map(fn ($value): array => [...$prefix, $value], $group))->all(); + } + + return $result; + } +} diff --git a/app/Services/WebhookService.php b/app/Services/WebhookService.php new file mode 100644 index 00000000..48fc6532 --- /dev/null +++ b/app/Services/WebhookService.php @@ -0,0 +1,35 @@ +where('store_id', $store->getKey()) + ->where(function ($query) use ($eventType): void { + $query->where('event', $eventType)->orWhere('event_type', $eventType); + }) + ->where('status', 'active') + ->get() + ->each(function (WebhookSubscription $subscription) use ($eventType, $payload): void { + $delivery = $subscription->deliveries()->create(['event' => $eventType, 'event_id' => (string) str()->uuid(), 'payload' => $payload, 'attempts' => 0, 'attempt_count' => 0, 'next_attempt_at' => now()]); + DeliverWebhook::dispatch($delivery); + }); + } + + public function sign(string $payload, string $secret): string + { + return hash_hmac('sha256', $payload, $secret); + } + + public function verify(string $payload, string $signature, string $secret): bool + { + return hash_equals($this->sign($payload, $secret), $signature); + } +} diff --git a/app/Support/HandleGenerator.php b/app/Support/HandleGenerator.php new file mode 100644 index 00000000..cdd63f51 --- /dev/null +++ b/app/Support/HandleGenerator.php @@ -0,0 +1,22 @@ +where('store_id', $storeId)->where('handle', $handle)->when($excludeId !== null, fn ($query) => $query->where('id', '<>', $excludeId))->exists()) { + $handle = $base.'-'.$suffix++; + } + + return $handle; + } +} diff --git a/app/Support/HtmlSanitizer.php b/app/Support/HtmlSanitizer.php new file mode 100644 index 00000000..50ae63e1 --- /dev/null +++ b/app/Support/HtmlSanitizer.php @@ -0,0 +1,18 @@ +