Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce405d20e6 | ||
|
|
0f07751559 | ||
|
|
53d8a5aefe | ||
|
|
380e860386 | ||
|
|
d680200ab1 | ||
|
|
9529036585 | ||
|
|
2db1e1331f | ||
|
|
d873cb4931 | ||
|
|
661e8b9a96 | ||
|
|
637da37b9b | ||
|
|
be0c037c62 | ||
|
|
808c769595 |
@@ -4,6 +4,51 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [0.11.0] - 2026-09-01
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Catalog\Services\RecommendationService` — computes "related products" for a given product as a configurable, ordered chain of strategies (`config('catalog.recommendation_rules')`), not one hardcoded rule. Tops up from each successive rule until the limit (default 4) is reached or every rule is exhausted — e.g. 3 products from a same-category rule plus 1 from a random fallback — deduplicated across rules so the same product is never returned twice. Ships with `Modules\Core\Catalog\Recommendations\SameCategoryRule` (other products sharing the source product's first collection) and `RandomRule` (the universal fallback, placed last in the default chain). A new rule is just a class implementing `Modules\Core\Catalog\Contracts\RecommendationRule`. Documented in `docs/product-recommendations.md`.
|
||||
- `Modules\Core\Catalog\Services\ProductIndexer` embeds the result directly into each product's own Meilisearch document as `recommendations: [{id, name, price, image}, ...]` (`recommendations.id` filterable) — a product detail page renders its "related products" section with zero extra queries, same reasoning as the existing `collections` field. Deliberately embeds an `id` for the view to build a locale-correct URL from, not a resolved `href` — `product.show` is locale-prefixed, so a URL baked in at index time would only be correct for whichever locale happened to be active during that index run.
|
||||
- `Modules\Core\Catalog\Events\ProductSaved`/`ProductDeleted`, dispatched from `Product::saved()`/`Product::deleted()` in `CatalogServiceProvider` (the latter fires for both a soft delete and a force delete, matching Scout's own `unsearchable()` trigger point) — feed `Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct`, which reverse-searches Meilisearch for every product currently recommending the changed/deleted one (`recommendations.id = "..."` — there's no Postgres relation for this, a recommendation only exists inside the index) and re-indexes them via Scout's own `->searchable()`. Product creation is deliberately not hooked into this: a new product not yet appearing as a recommendation elsewhere is an accepted staleness window, the same tradeoff already documented for `in_stock`/`price` — see `docs/product-recommendations.md`.
|
||||
- `CatalogServiceProvider` schedules `lunar:search:index "Lunar\Models\Product" --refresh` daily at 03:00 — a safety net on top of the event-driven reindexing above, covering a newly-created product not yet appearing as a recommendation and any other drift already accepted between reindexes. `--refresh` also re-syncs filterable/sortable index settings, not just documents.
|
||||
|
||||
## [0.10.1] - 2026-09-01
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Localization\Services\StorefrontLabels::all()` gains three keys found missing from `3dealer`'s actual `storefront.*` translation usage: `shop.price_min`, `shop.price_max`, `shop.reset` (the price-filter sidebar's min/max labels and its reset link). Picked up by `InstallLunarCommand`'s existing per-key upsert — re-running `lunar:install` on an already-installed store adds only these three rows, leaving everything already seeded or admin-edited untouched.
|
||||
|
||||
## [0.10.0] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
- **Breaking:** Upgraded `lunarphp/lunar`, `lunarphp/core`, `lunarphp/stripe`, `lunarphp/table-rate-shipping`, and `lunarphp/search` to `1.5.0`, and `filament/filament` to `v4.12.6` — the first Filament v4 admin panel on this codebase. `lunarphp/filament3-2fa` and `kalnoy/nestedset` are gone, replaced by Filament v4's native two-factor auth and `lunarphp/nestedset`. Ran Filament's automated `filament-v4` migration tool across `src/`, then hand-fixed three bugs it introduced or left behind: a stale `$infolist` variable reference in `CartResource`'s `ViewCart` page (the parameter had been renamed to `$schema` but the body wasn't updated), `ShippingMethodResourceExtension` rewritten to call `getDefaultChildComponents()` (returns `array|Schema`) instead of the type-safe `getChildComponents()` (always `array<Component>`), and — unrelated to the tool, but surfaced by the same PHP version bump — `InvalidCouponException`'s `readonly $code` property illegally shadowing the built-in `Exception::$code`, renamed to `$couponCode`. `LunarStaff::addActivitylogExcept()` updated for the renamed `two_factor_secret`/`two_factor_recovery_codes` staff columns (now `app_authentication_secret`/`app_authentication_recovery_codes`; `two_factor_confirmed_at` removed). Consuming apps must run `composer update boboko/core --with-all-dependencies` and `php artisan migrate`.
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Checkout\Contracts\PaymentDriver` — the abstraction every payment provider implements: `confirm(Cart $cart, string $type, string $fingerprint, array $data): Order` and `isConfigured(): bool`. A driver only ever calls `CheckoutService::placeOrder()` once it has, by whatever mechanism is native to that gateway, independently confirmed payment — never Lunar's raw `Cart::createOrder()`. This is what lets the storefront checkout sequence stay uniform regardless of which provider is active: set addresses, select shipping, hand off to whichever driver is configured, and the driver decides when (or whether) the order gets created.
|
||||
- `Modules\Core\Payment\Drivers\OfflinePaymentDriver` — shared by every payment type with no real gateway to confirm against (`cash-in-hand`, `cash-on-delivery`): places the order immediately via `CheckoutService::placeOrder()`, then sets the order status from `config("lunar.payments.types.{$type}.authorized")` using the type actually confirmed, not a hardcoded key, since one driver instance serves multiple types.
|
||||
- `Modules\Core\Payment\Drivers\StripePaymentDriver` — a fork, not a decoration, of `lunarphp/stripe`'s `StripePaymentType::authorize()`: that method is `final` and calls `Cart::createOrder()` directly with no seam to redirect into our fingerprint-checked `placeOrder()`, so this class reimplements its logic (intent retrieval, capture-on-policy, status mapping via `UpdateOrderFromIntent`) with that one substitution. Throws the new `Modules\Core\Payment\Exceptions\PaymentNotConfirmedException` on anything short of a genuinely confirmed payment intent — never falls through to placing an order on ambiguity.
|
||||
- `CheckoutService::getPaymentMethods(): array` — every payment type currently offered to the storefront: every key in `config('lunar.payments.types')` that is both administratively enabled (`Modules\Core\Payment\Models\PaymentMethod::enabled`) and whose driver reports `isConfigured()` (e.g. Stripe with no API key set is never offered, regardless of the enabled toggle). `selectPaymentMethod(string $type)` and `confirmPayment(string $type, array $data)` both validate against this list, throwing the new `UnknownPaymentTypeException` for a type that isn't currently offered — re-checked in `confirmPayment()` too, since a type could be disabled between selection and confirmation.
|
||||
- `CheckoutService::selectPaymentMethod()` snapshots `Cart::fingerprint()` into `cart->meta['checkout_fingerprint']` *after* saving the chosen type and recalculating — the fingerprint has to reflect the final total including any payment-type-specific adjustment (e.g. a COD surcharge), which only exists once `payment_method` is set. `confirmPayment()` reads this stored fingerprint internally rather than taking one as a parameter: a storefront should never need to know `Cart::fingerprint()` exists or capture it at exactly the right moment itself.
|
||||
- `Modules\Core\Payment\Models\PaymentMethod` — one DB row per payment type key (matching `config('lunar.payments.types')`), `enabled` boolean plus a `data` jsonb column (starting with `fee`, the flat cash-on-delivery surcharge) — mirrors Lunar's own `Discount` model (a single jsonb column of keyed settings, not a fixed column per setting or a separate conditions table). Seeded idempotently by `InstallLunarCommand` (skip-if-exists per type, safe to re-run after installing a new payment-provider package), always `enabled: false` — a newly-seeded type shouldn't go live for shoppers before staff have configured and reviewed it. Admin-editable via the new `PaymentMethodResource` (inline enabled toggle, modal fee editor) under Settings.
|
||||
- `ApplyCashOnDeliveryFee` now reads its surcharge from `PaymentMethod` instead of static config, so it's admin-editable without a deploy.
|
||||
|
||||
### Fixed
|
||||
- `CashOnDeliveryPaymentDriver` renamed to `OfflinePaymentDriver` and generalized to work for any offline-style type — it previously hardcoded `'cash-on-delivery'` when reading the post-placement order status from config, which would have silently read the wrong type's status the moment a second offline type (`cash-in-hand`) used it.
|
||||
|
||||
## [0.9.0] - 2026-08-29
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Cart\Services\CartService` — the boboko-owned API for all cart mutation, wrapping Lunar's `CartSession`/`Cart` primitives: `addLine()`, `updateLine()`, `removeLine()`, `clear()`, `applyCoupon()`/`removeCoupon()` (throws `InvalidCouponException` on an invalid code), and save-for-later (`saveForLater()`/`moveToCart()`/`activeLines()`/`savedLines()`, backed by a `meta.saved_for_later` flag and a new `Modules\Core\Cart\Pipelines\ZeroSavedForLaterPrice` cart-line pipeline step that zeroes a saved line's price so it's excluded from cart totals without being removed). Dispatches 8 real domain events (`CartLineAdded`/`Updated`/`Removed`/`Saved`/`MovedToCart`, `CartCleared`, `CartCouponApplied`/`Removed`) — none have a listener yet, built so a future concern (analytics, recovery) has something to attach to. Documented in `docs/cart.md`.
|
||||
- `Modules\Core\Checkout\Services\CheckoutService` — the boboko-owned API for the checkout stage (address → shipping selection → order placement), sitting between `CartService` and `Order`: `setShippingAddress()`/`setBillingAddress()`, `getShippingOptions()`/`selectShippingOption()` (throws the new `InvalidShippingOptionException` on an identifier that doesn't resolve — previously a silent no-op), and `placeOrder(string $fingerprint)` (the fingerprint is mandatory, not optional — forces re-confirmation via Lunar's own `FingerprintMismatchException` if the cart changed since the shopper last saw its total). Dispatches `ShippingAddressSet`/`BillingAddressSet`/`ShippingOptionSelected`/`OrderPlaced`, each carrying richer, already-resolved payload (e.g. the resolved `ShippingOption`, not just its identifier) than `CartService`'s events. No exception wrapping otherwise — Lunar's own `CartException`/`FingerprintMismatchException` are already the right shape for a storefront to render as form errors. Documented in `docs/checkout.md`.
|
||||
- `Modules\Core\Cart\Filament\Resources\CartResource`'s list view now classifies every cart into one of four states — **Ongoing**, **Abandoned Cart**, **Abandoned Checkout**, **Completed** — instead of the previous two-tab Abandoned/Completed split, distinguishing a cart that never reached checkout from one that has a started-but-unplaced order (mirrors the real distinction in Lunar's own `Cart::scopeActive()`). Abandonment threshold is a fixed, configurable cutoff (`config('core.cart.abandoned_after')`, default 1 hour). Added a customer hyperlink (list column + a "View Customer" header action on the view page, both pointing straight at `customers/{id}` via the plain `customer_id` column, no extra query via the `customer` relation).
|
||||
- `Modules\Core\Cart\Commands\DetectAbandonedCarts` (`boboko:cart:detect-abandoned`, scheduled hourly) dispatches `Modules\Core\Recovery\Events\CartAbandoned`/`CheckoutAbandoned` for carts/checkouts past the abandonment cutoff — detection only, no persistence; a real tracking table is left for when `Recovery` is built as its own concern. Fixed a self-defeating bug from an earlier draft: marking a cart as notified by writing to it bumped `updated_at`, which immediately un-staled it for the next run's own cutoff check.
|
||||
- Merged the `Shipping-Carriers` branch: live carrier rate quoting and fulfillment for **ACS Courier** and **Box Now** (`Modules\Core\Shipping\Carriers\{Acs,BoxNow}`) on top of `lunarphp/table-rate-shipping` — `AcsRateDriver`/`BoxNowRateDriver` (live + static price-break resolution), `AcsFulfillmentService`/`BoxNowFulfillmentService` (shipment creation, label printing, cancellation via the new `Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface`, resolved per-carrier via contextual container binding), `Modules\Core\Shipping\Models\Shipment`/`ShipmentInfo`, `PollShipmentTrackingJob` (scheduled every 30 minutes), `ManagePickupManifests` (Filament page for carrier manifest batching), and an `OrderViewExtension` adding a "Create Shipment" header action to Lunar's order view. Carrier credentials are published config (`config/shippingCarriers/{acs,boxnow}.php`), never committed.
|
||||
- `Modules\Core\Shipping\Concerns\CachesLivePricing` caches a live-priced carrier quote per `(rate, cart)` for 30 minutes — a real, billed API call that's otherwise re-run on every `getShippingOptions()`/`selectShippingOption()` call within the same checkout attempt. `Modules\Core\Shipping\Listeners\FlushLivePricingCache` invalidates it on the only two things that can change a quote: a cart line changing or the shipping address changing (deliberately **not** on order placement — the price the shopper was quoted must still be readable afterwards). Scoped generically to any `SupportsLivePricing` driver, not hardcoded to ACS.
|
||||
- `AcsRateDriver::resolveLivePrice()` now falls back to the rate's own configured static price if the live ACS API call fails (previously: the shipping option silently disappeared from the list on any API error, including a brief outage). `ManageShippingRates` (our Filament subclass of the vendor rates page) now allows a static price to be configured and saved on a "live" rate specifically for this fallback — previously those fields were hidden and discarded on save for any live-priced rate.
|
||||
|
||||
### Fixed
|
||||
- Fixed a crash (`Attempt to read property "price" on null`) opening/editing a live-priced shipping rate with no fallback price configured yet — the vendor `ManageShippingRates` page's `afterStateHydrated` callback for the price field had no null-guard for a rate with zero `basePrices`, which is now the routine case for an unconfigured live rate.
|
||||
- Fixed the Filament admin panel's home URL (`/boboko/home`) incorrectly resolving to the Shipping module's `ManagePickupManifests` page instead of the Dashboard — Filament falls back to the first item of the first registered navigation group when no explicit `homeUrl()` is set, and `ManagePickupManifests` had no `navigationGroup`/`navigationSort` of its own. Fixed via explicit `navigationGroup = 'Sales'` / `navigationSort = 100`, placing it after Sales in the nav instead of first overall.
|
||||
|
||||
## [0.8.0] - 2026-08-27
|
||||
|
||||
### Added
|
||||
|
||||
+8
-5
@@ -2,7 +2,7 @@
|
||||
"name": "boboko/core",
|
||||
"description": "Core module — authentication and shared panel behaviour",
|
||||
"type": "library",
|
||||
"version": "0.8.0",
|
||||
"version": "0.11.0",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Core\\": "src/"
|
||||
@@ -10,14 +10,15 @@
|
||||
},
|
||||
"require": {
|
||||
"php": "^8.5",
|
||||
"lunarphp/lunar": "1.3.0",
|
||||
"lunarphp/lunar": "1.5.0",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/tinker": "^3.0",
|
||||
"symfony/yaml": "^7.0",
|
||||
"lunarphp/table-rate-shipping": "^1.3",
|
||||
"lunarphp/table-rate-shipping": "1.5.0",
|
||||
"lunarphp/search": "*",
|
||||
"lunarphp/meilisearch": "*",
|
||||
"spatie/laravel-translation-loader": "^2.8"
|
||||
"spatie/laravel-translation-loader": "^2.8",
|
||||
"lunarphp/stripe": "^1.5"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
@@ -27,7 +28,8 @@
|
||||
"mockery/mockery": "^1.6",
|
||||
"nunomaduro/collision": "^8.6",
|
||||
"pestphp/pest": "^4.6",
|
||||
"pestphp/pest-plugin-laravel": "^4.1"
|
||||
"pestphp/pest-plugin-laravel": "^4.1",
|
||||
"filament/upgrade": "^4.0"
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
@@ -35,6 +37,7 @@
|
||||
"Modules\\Core\\Providers\\CoreServiceProvider",
|
||||
"Modules\\Core\\Providers\\AuthServiceProvider",
|
||||
"Modules\\Core\\Providers\\CustomerServiceProvider",
|
||||
"Modules\\Core\\Providers\\PaymentServiceProvider",
|
||||
"Modules\\Core\\Providers\\LocalizationServiceProvider",
|
||||
"Modules\\Core\\Providers\\CatalogServiceProvider",
|
||||
"Modules\\Core\\Providers\\CartServiceProvider",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Modules\Core\Catalog\Recommendations\RandomRule;
|
||||
use Modules\Core\Catalog\Recommendations\SameCategoryRule;
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Product recommendation rules
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Tried in order by Modules\Core\Catalog\Services\RecommendationService —
|
||||
| the first rule that returns at least one product wins. The order here IS
|
||||
| the fallback chain: SameCategoryRule first, then RandomRule as a
|
||||
| last-resort so a product page is never left with zero recommendations
|
||||
| (as long as the store has more than one product). A consuming app can
|
||||
| reorder, add, or remove rules freely — nothing about the chain shape is
|
||||
| hardcoded in the service itself.
|
||||
|
|
||||
*/
|
||||
'recommendation_rules' => [
|
||||
SameCategoryRule::class,
|
||||
RandomRule::class,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use Modules\Core\Payment\Drivers\OfflinePaymentDriver;
|
||||
use Modules\Core\Payment\Pipelines\Cart\ApplyCashOnDeliveryFee;
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Lunar payment types merged in by Boboko Core
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These are merged into config('lunar.payments.types') so every app using
|
||||
| boboko-core gets cash-on-delivery out of the box, without publishing
|
||||
| Lunar's own config.
|
||||
|
|
||||
| 'payment_driver' is boboko-owned, alongside Lunar's own 'driver' key —
|
||||
| it's the Modules\Core\Checkout\Contracts\PaymentDriver class
|
||||
| CheckoutService::confirmPayment() resolves via the container and calls
|
||||
| confirm() on. Kept on the same row as 'driver' rather than a second,
|
||||
| separately-keyed map, so a type's full definition — Lunar's driver,
|
||||
| its config, and its PaymentDriver — lives in one place.
|
||||
|
|
||||
*/
|
||||
'types' => [
|
||||
'cash-on-delivery' => [
|
||||
'driver' => 'offline',
|
||||
'payment_driver' => OfflinePaymentDriver::class,
|
||||
'authorized' => 'awaiting-payment',
|
||||
'fee' => 0,
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Lunar cart pipeline additions
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Appended to config('lunar.cart.pipelines.cart') after ApplyShipping so
|
||||
| the cash-on-delivery fee is added to the shipping total before the
|
||||
| final Calculate step sums everything up.
|
||||
|
|
||||
*/
|
||||
'cart_pipeline' => [
|
||||
ApplyCashOnDeliveryFee::class,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('payment_methods', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('type')->unique();
|
||||
$table->boolean('enabled')->default(true);
|
||||
$table->json('data')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('payment_methods');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,155 @@
|
||||
# Product Recommendations
|
||||
|
||||
`Modules\Core\Catalog\Services\RecommendationService` computes "related products" for a given
|
||||
product — a same-category pick today, with a random fallback, but built as a configurable chain of
|
||||
strategies rather than one hardcoded rule. `Modules\Core\Catalog\Services\ProductIndexer` embeds
|
||||
the result directly into each product's own Meilisearch document, so a product detail page renders
|
||||
its recommendations with zero extra queries — same reasoning as `collections` (see
|
||||
`docs/product-listing.md`).
|
||||
|
||||
---
|
||||
|
||||
## The rule chain
|
||||
|
||||
```php
|
||||
use Modules\Core\Catalog\Services\RecommendationService;
|
||||
|
||||
$recommendations = app(RecommendationService::class)->recommend($product, limit: 4);
|
||||
// Illuminate\Support\Collection<int, Lunar\Models\Product>
|
||||
```
|
||||
|
||||
`recommend()` walks `config('catalog.recommendation_rules')` in order, **topping up** from each
|
||||
successive rule until `$limit` distinct products are collected or every rule is exhausted — it does
|
||||
not stop at the first rule that returns *something*. If a product's category only has 3 other
|
||||
products, `SameCategoryRule` contributes those 3 and `RandomRule` fills the last slot. A rule is
|
||||
handed the ids already collected (`$exclude`, always including the source product's own id) so it
|
||||
never wastes its own `$limit` budget re-suggesting something already picked, and the same product
|
||||
is never returned twice even if two rules would both suggest it.
|
||||
|
||||
Default chain (`config/catalog.php`):
|
||||
|
||||
```php
|
||||
'recommendation_rules' => [
|
||||
SameCategoryRule::class, // other products sharing $product's first collection
|
||||
RandomRule::class, // universal fallback — always returns something as
|
||||
// long as the store has more than one product
|
||||
],
|
||||
```
|
||||
|
||||
A consuming app publishes and edits this config to reorder, add, or remove rules — nothing about
|
||||
the chain shape is hardcoded in `RecommendationService` itself. A new rule (same tag, best sellers,
|
||||
"frequently bought together", ...) is a class implementing `Modules\Core\Catalog\Contracts\
|
||||
RecommendationRule`, added to the array:
|
||||
|
||||
```php
|
||||
interface RecommendationRule
|
||||
{
|
||||
/**
|
||||
* @param array<int> $exclude ids to never return — the source product's own
|
||||
* id, plus every id an earlier rule in the chain already picked
|
||||
* @return Collection<int, Product> at most $limit products
|
||||
*/
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection;
|
||||
}
|
||||
```
|
||||
|
||||
Rules query Eloquent directly (`$product->collections->first()->products()`, `Product::query()`),
|
||||
not `Modules\Core\Catalog\Services\ProductService` — see "Why not `ProductService`" below.
|
||||
|
||||
---
|
||||
|
||||
## Why not `ProductService`
|
||||
|
||||
Every other read path in `Modules\Core\Catalog` goes through `ProductService`, which reads
|
||||
Meilisearch and resolves translated fields to whatever locale the *current request* is in (see
|
||||
`docs/product-listing.md`, "Locale resolution"). Recommendation rules deliberately don't use it:
|
||||
they run inside `ProductIndexer::toSearchableArray()`, at **index time** — there is no request, no
|
||||
meaningful "current locale" to resolve against, and Meilisearch itself may be mid-write for the very
|
||||
product being indexed. Rules return raw `Lunar\Models\Product` models instead; `ProductIndexer`
|
||||
resolves what it embeds (`name` via `translateAttribute()`, `price` via the indexer's own
|
||||
`cheapestPrice()`, `image` via its own `mapMedia()`) the same way it already does for the embedded
|
||||
`collections` field — including that field's same accepted index-time-locale tradeoff (a
|
||||
recommendation's embedded `name` reflects whatever locale was active when *that* product was last
|
||||
indexed, not the viewer's current locale).
|
||||
|
||||
---
|
||||
|
||||
## What's embedded, and why not just an id
|
||||
|
||||
`ProductIndexer` embeds full card data per recommendation, not just an id:
|
||||
|
||||
```php
|
||||
$data['recommendations'] = [
|
||||
['id' => 42, 'name' => 'Espresso Cup', 'price' => 12.5, 'image' => 'https://.../thumb.jpg'],
|
||||
// ...
|
||||
];
|
||||
```
|
||||
|
||||
This shape is deliberately exactly what `x-ui.product-card`/`x-product-grid` (3dealer's storefront
|
||||
components) need — `name`, `price`, `image`, and an `id` the view resolves to a URL itself via
|
||||
`route('product.show', ['id' => $rec['id']])`. A resolved `href` is **not** embedded: `product.show`
|
||||
is locale-prefixed (`{locale}/products/{id}`), so a URL baked in at index time would be correct only
|
||||
for whichever locale happened to be active during that index run — wrong for every other locale.
|
||||
Building the URL is left to the view, which knows the current request's locale.
|
||||
|
||||
`recommendations.id` is marked **filterable** — not for the storefront, but for the reverse-lookup
|
||||
reindexing below.
|
||||
|
||||
---
|
||||
|
||||
## Keeping it fresh: `ProductSaved` / `ProductDeleted`
|
||||
|
||||
A recommendation is computed once, at index time, and embedded — it does not update itself when the
|
||||
recommended product later changes name, price, or image, or is deleted. Unlike `Modules\Core\Catalog\
|
||||
Observers\ProductOptionReindexObserver`'s equivalent problem (which product option value is used by),
|
||||
there is no Postgres relation for "which products currently recommend product X" — a recommendation
|
||||
only exists inside Meilisearch. The fix is a reverse Meilisearch filter query, not a database join,
|
||||
wired through a real event → listener pair (`Modules\Core\Providers\CatalogServiceProvider`):
|
||||
|
||||
- `Product::saved()` dispatches `Modules\Core\Catalog\Events\ProductSaved`.
|
||||
- `Product::deleted()` dispatches `Modules\Core\Catalog\Events\ProductDeleted` — fires for both a
|
||||
soft delete and a force delete (`Lunar\Models\Product` uses `SoftDeletes`), the same model event
|
||||
Laravel Scout's own `ModelObserver` hooks to make a deleted product `unsearchable()`.
|
||||
- `Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct` handles both: it searches the
|
||||
product index for `recommendations.id = "{id}"`, finds every referencing product, and calls
|
||||
`->searchable()` on each — which recomputes their `recommendations` field fresh, picking up the
|
||||
changed name/price/image, or (for a delete) dropping the now-gone product and topping back up to
|
||||
the configured limit via the rule chain, same as any other reindex.
|
||||
|
||||
`->searchable()` dispatches Scout's own reindex job, queued if `SCOUT_QUEUE` is configured — this
|
||||
listener does no synchronous Meilisearch writing itself.
|
||||
|
||||
**Product creation is deliberately not hooked into this.** A brand-new product has no
|
||||
`recommendations` of its own until Scout's existing create-triggered indexing runs (already correct
|
||||
— nothing to add). What's *not* immediate is other products picking the new one up as a fresh
|
||||
recommendation candidate — that happens on their own next natural reindex (a save, or the nightly
|
||||
full reindex below), the same accepted staleness window `docs/product-listing.md` already documents
|
||||
for `in_stock`/`price`. A full proactive "who could now recommend this new product" pass was
|
||||
considered and rejected as unnecessary cost for a cosmetic delay.
|
||||
|
||||
---
|
||||
|
||||
## Nightly full reindex
|
||||
|
||||
`Modules\Core\Providers\CatalogServiceProvider` schedules `lunar:search:index "Lunar\Models\Product"
|
||||
--refresh` daily at 03:00 — a safety net on top of the event-driven reindexing above, not a
|
||||
replacement for it. Catches what event-driven reindexing deliberately doesn't cover: a newly-created
|
||||
product not yet appearing as a recommendation elsewhere, and any other drift already accepted
|
||||
between reindexes (see `docs/product-listing.md`, "Stock goes stale between orders"). `--refresh`
|
||||
also re-syncs filterable/sortable index *settings*, not just documents, so a deploy that changed
|
||||
`ProductIndexer`'s field list self-heals overnight even if `lunar:meilisearch:setup` wasn't run
|
||||
manually right after that deploy.
|
||||
|
||||
---
|
||||
|
||||
## Re-syncing after this change
|
||||
|
||||
Same as any other `ProductIndexer` field change (see `docs/product-listing.md`):
|
||||
|
||||
```bash
|
||||
php artisan lunar:meilisearch:setup
|
||||
php artisan lunar:search:index "Lunar\Models\Product" --refresh
|
||||
```
|
||||
|
||||
Restart the queue worker if `SCOUT_QUEUE=true` — see `docs/product-listing.md`'s "Re-syncing after
|
||||
this change" for why a running worker won't otherwise pick up the new indexer code.
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
namespace Modules\Core\Auth\Extensions;
|
||||
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Schemas\Schema;
|
||||
use Lunar\Admin\Support\Extending\ResourceExtension;
|
||||
|
||||
class StaffResourceExtension extends ResourceExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
public function extendForm(Schema $form): Schema
|
||||
{
|
||||
$schema = collect($form->getComponents())
|
||||
->reject(fn ($component) => method_exists($component, 'getName') && $component->getName() == 'password')
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return $form->schema($schema);
|
||||
return $form->components($schema);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ class Login extends SimplePage
|
||||
{
|
||||
use WithRateLimiting;
|
||||
|
||||
protected static string $view = 'core::auth.filament.pages.login';
|
||||
protected string $view = 'core::auth.filament.pages.login';
|
||||
|
||||
public ?string $email = '';
|
||||
public ?string $otp = '';
|
||||
@@ -78,7 +78,7 @@ class Login extends SimplePage
|
||||
]);
|
||||
}
|
||||
|
||||
if ($staff instanceof FilamentUser && !$staff->canAccessPanel(Filament::getCurrentPanel())) {
|
||||
if ($staff instanceof FilamentUser && !$staff->canAccessPanel(Filament::getCurrentOrDefaultPanel())) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => 'You do not have access to this panel.',
|
||||
]);
|
||||
|
||||
@@ -12,8 +12,8 @@ use RuntimeException;
|
||||
*/
|
||||
class InvalidCouponException extends RuntimeException
|
||||
{
|
||||
public function __construct(public readonly string $code)
|
||||
public function __construct(public readonly string $couponCode)
|
||||
{
|
||||
parent::__construct("The coupon code \"{$code}\" is not valid.");
|
||||
parent::__construct("The coupon code \"{$couponCode}\" is not valid.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
namespace Modules\Core\Cart\Filament\Resources;
|
||||
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource\Pages\ListCarts;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource\Pages\ViewCart;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
@@ -24,9 +28,9 @@ class CartResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Cart::class;
|
||||
|
||||
protected static ?string $navigationIcon = 'heroicon-o-shopping-cart';
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-shopping-cart';
|
||||
|
||||
protected static ?string $navigationGroup = 'Sales';
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Sales';
|
||||
|
||||
protected static ?string $modelLabel = 'Cart';
|
||||
|
||||
@@ -70,37 +74,37 @@ class CartResource extends Resource
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('id')
|
||||
TextColumn::make('id')
|
||||
->label('Cart')
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('customer.full_name')
|
||||
TextColumn::make('customer.full_name')
|
||||
->label('Customer')
|
||||
->placeholder('—')
|
||||
->searchable()
|
||||
->url(fn (Cart $record) => $record->customer_id !== null
|
||||
? CustomerResource::getUrl('view', ['record' => $record->customer_id])
|
||||
: null),
|
||||
Tables\Columns\TextColumn::make('user.email')
|
||||
TextColumn::make('user.email')
|
||||
->label('User')
|
||||
->placeholder('—')
|
||||
->searchable(),
|
||||
Tables\Columns\TextColumn::make('lines_count')
|
||||
TextColumn::make('lines_count')
|
||||
->label('Lines')
|
||||
->counts('lines')
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('lines_sum_quantity')
|
||||
TextColumn::make('lines_sum_quantity')
|
||||
->label('Items')
|
||||
->sum('lines', 'quantity')
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('currency.code')
|
||||
TextColumn::make('currency.code')
|
||||
->label('Currency'),
|
||||
Tables\Columns\TextColumn::make('updated_at')
|
||||
TextColumn::make('updated_at')
|
||||
->label('Last activity')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
])
|
||||
->actions([
|
||||
Tables\Actions\ViewAction::make(),
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
])
|
||||
->defaultSort('updated_at', 'desc');
|
||||
}
|
||||
@@ -108,8 +112,8 @@ class CartResource extends Resource
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListCarts::route('/'),
|
||||
'view' => Pages\ViewCart::route('/{record}'),
|
||||
'index' => ListCarts::route('/'),
|
||||
'view' => ViewCart::route('/{record}'),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Cart\Filament\Resources\CartResource\Pages;
|
||||
|
||||
use Filament\Resources\Components\Tab;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource;
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
namespace Modules\Core\Cart\Filament\Resources\CartResource\Pages;
|
||||
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\Section;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Infolists\Infolist;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Lunar\Admin\Filament\Resources\CustomerResource;
|
||||
use Lunar\Models\Cart;
|
||||
@@ -44,10 +44,10 @@ class ViewCart extends ViewRecord
|
||||
return $cart->calculate();
|
||||
}
|
||||
|
||||
public function infolist(Infolist $infolist): Infolist
|
||||
public function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $infolist
|
||||
->schema([
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Cart')
|
||||
->columns(3)
|
||||
->schema([
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Catalog\Contracts;
|
||||
|
||||
use Filament\Forms\Components\Component;
|
||||
use Filament\Schemas\Components\Component;
|
||||
|
||||
/**
|
||||
* A Product Option Type describes how a category of Lunar `ProductOption` (e.g.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Contracts;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
|
||||
/**
|
||||
* One strategy for producing recommended products for a given product —
|
||||
* e.g. same category, same tag, best sellers, random. Modules\Core\Catalog\
|
||||
* Services\RecommendationService runs rules registered in
|
||||
* config('catalog.recommendation_rules') in order, topping up from each
|
||||
* successive rule until $limit distinct products are collected or every
|
||||
* rule is exhausted (e.g. 3 from SameCategoryRule + 1 from RandomRule) —
|
||||
* nothing here decides that accumulation itself; a store composes its own
|
||||
* chain by ordering rules in config (e.g. [SameCategoryRule::class,
|
||||
* RandomRule::class]).
|
||||
*
|
||||
* Returns raw Product models, not ProductService::list()'s locale-resolved
|
||||
* array output — this runs at index time (ProductIndexer::toSearchableArray()),
|
||||
* where "the current locale" isn't a meaningful concept the way it is for a
|
||||
* storefront request. ProductIndexer resolves translated fields itself via
|
||||
* translateAttribute(), same as it already does for the embedded `collections`
|
||||
* field — same known index-time-locale tradeoff, not a new one.
|
||||
*/
|
||||
interface RecommendationRule
|
||||
{
|
||||
/**
|
||||
* $exclude carries $product's own id plus every id already picked by an
|
||||
* earlier rule this call — RecommendationService never shows the same
|
||||
* product twice even when two rules would both suggest it, and a rule
|
||||
* shouldn't spend its $limit budget re-returning something already
|
||||
* collected.
|
||||
*
|
||||
* @param array<int> $exclude
|
||||
* @return Collection<int, Product> at most $limit products
|
||||
*/
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Events;
|
||||
|
||||
/**
|
||||
* Dispatched whenever a Product is deleted (see CatalogServiceProvider,
|
||||
* which wires this to the model's own deleted() hook — fires for both a
|
||||
* soft delete and a force delete, same as Laravel Scout's own
|
||||
* ModelObserver::deleted() that triggers unsearchable() for the product
|
||||
* itself). Same purpose as Modules\Core\Catalog\Events\ProductSaved: lets
|
||||
* Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct find
|
||||
* and re-index every OTHER product that currently embeds this one in its
|
||||
* `recommendations` field, so a deleted product doesn't linger as a dead
|
||||
* reference elsewhere. Carries only the id, not the Product model — by the
|
||||
* time this fires the model may already be gone (force delete), and the
|
||||
* reverse lookup only ever needs the id to filter on.
|
||||
*/
|
||||
class ProductDeleted
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $productId,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Events;
|
||||
|
||||
use Lunar\Models\Product;
|
||||
|
||||
/**
|
||||
* Dispatched whenever a Product is saved (see CatalogServiceProvider,
|
||||
* which wires this to the model's own saved() hook) — exists specifically
|
||||
* so Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct can
|
||||
* find and re-index every OTHER product that currently embeds this one in
|
||||
* its own `recommendations` field (see ProductIndexer). Those products
|
||||
* have no direct database relationship to this one — a recommendation is
|
||||
* computed and stored only inside Meilisearch (Modules\Core\Catalog\
|
||||
* Services\RecommendationService) — so nothing about their own save
|
||||
* lifecycle would otherwise pick up this product's changed name/price/
|
||||
* image.
|
||||
*/
|
||||
class ProductSaved
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Product $product,
|
||||
) {}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace Modules\Core\Catalog\Filament\Extensions;
|
||||
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Form;
|
||||
use Illuminate\Support\Str;
|
||||
use Lunar\Admin\Support\Extending\ResourceExtension;
|
||||
use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
@@ -16,7 +16,7 @@ use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
*/
|
||||
class ProductOptionResourceExtension extends ResourceExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
public function extendForm(Schema $schema): Schema
|
||||
{
|
||||
$options = collect(ProductOptionTypeManager::get()->all())
|
||||
->keys()
|
||||
@@ -24,11 +24,11 @@ class ProductOptionResourceExtension extends ResourceExtension
|
||||
->all();
|
||||
|
||||
if ($options === []) {
|
||||
return $form;
|
||||
return $schema;
|
||||
}
|
||||
|
||||
return $form->schema([
|
||||
...$form->getComponents(),
|
||||
return $schema->components([
|
||||
...$schema->getComponents(),
|
||||
Select::make('meta.option_type')
|
||||
->label('Option Type')
|
||||
->options($options)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Catalog\Filament\Extensions;
|
||||
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Schemas\Schema;
|
||||
use Lunar\Admin\Support\Extending\RelationManagerExtension;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
@@ -15,7 +15,7 @@ use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
*/
|
||||
class ValuesRelationManagerExtension extends RelationManagerExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
public function extendForm(Schema $schema): Schema
|
||||
{
|
||||
/** @var ProductOption $option */
|
||||
$option = $this->caller->getOwnerRecord();
|
||||
@@ -23,11 +23,11 @@ class ValuesRelationManagerExtension extends RelationManagerExtension
|
||||
$type = ProductOptionTypeManager::get()->resolve($option->meta['option_type'] ?? null);
|
||||
|
||||
if ($type === null) {
|
||||
return $form;
|
||||
return $schema;
|
||||
}
|
||||
|
||||
return $form->schema([
|
||||
...$form->getComponents(),
|
||||
return $schema->components([
|
||||
...$schema->getComponents(),
|
||||
...$type->getMetaForm(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Listeners;
|
||||
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Events\ProductDeleted;
|
||||
use Modules\Core\Catalog\Events\ProductSaved;
|
||||
|
||||
/**
|
||||
* Keeps every product's embedded `recommendations` field (see
|
||||
* ProductIndexer) in sync when a product they recommend changes or is
|
||||
* removed. Unlike Modules\Core\Catalog\Observers\ProductOptionReindexObserver's
|
||||
* equivalent ("who references this option value"), there is no Postgres
|
||||
* table to query here — a recommendation only exists inside Meilisearch,
|
||||
* computed by RecommendationService at index time — so the reverse lookup
|
||||
* is a Meilisearch filter query against `recommendations.id`, not a
|
||||
* database join.
|
||||
*
|
||||
* Handles both ProductSaved (name/price/image changed — referencing
|
||||
* products' embedded copy is stale) and ProductDeleted (the recommended
|
||||
* product no longer exists at all — referencing products need to drop it
|
||||
* and, since RecommendationService tops up to its limit, naturally pick up
|
||||
* a replacement on reindex). Same reverse lookup either way, just a
|
||||
* different source for the id being searched for.
|
||||
*
|
||||
* Re-indexing via ->searchable() dispatches Scout's own (queued, if
|
||||
* SCOUT_QUEUE is configured) reindex job per matched product — this
|
||||
* listener itself does no synchronous Meilisearch writing.
|
||||
*/
|
||||
class ReindexProductsRecommendingProduct
|
||||
{
|
||||
public function handleSaved(ProductSaved $event): void
|
||||
{
|
||||
$this->reindexReferencingProducts($event->product->id);
|
||||
}
|
||||
|
||||
public function handleDeleted(ProductDeleted $event): void
|
||||
{
|
||||
$this->reindexReferencingProducts($event->productId);
|
||||
}
|
||||
|
||||
private function reindexReferencingProducts(int $productId): void
|
||||
{
|
||||
$hits = Product::search('')
|
||||
->options([
|
||||
'filter' => "recommendations.id = \"{$productId}\"",
|
||||
'attributesToRetrieve' => ['id'],
|
||||
// Meilisearch's own hitsPerPage default (20) would silently
|
||||
// drop referencing products past that count — this is a
|
||||
// reverse lookup, not a paginated storefront result, so it
|
||||
// needs every match, up to Meilisearch's hard limit.
|
||||
'hitsPerPage' => 1000,
|
||||
])
|
||||
->raw()['hits'] ?? [];
|
||||
|
||||
$ids = collect($hits)->pluck('id')->unique()->values();
|
||||
|
||||
if ($ids->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Product::whereIn('id', $ids)->get()->each->searchable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Recommendations;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* The universal fallback — always returns something as long as the store
|
||||
* has more than one product, since it has no eligibility condition of its
|
||||
* own to come up empty on. Meant to be placed last in
|
||||
* config('catalog.recommendation_rules'), not first: every store using
|
||||
* the default chain gets a real fallback, but one that only kicks in once
|
||||
* more specific rules (same category, same tag, ...) have had a chance.
|
||||
*/
|
||||
class RandomRule implements RecommendationRule
|
||||
{
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection
|
||||
{
|
||||
return Product::query()
|
||||
->whereKeyNot($exclude)
|
||||
->inRandomOrder()
|
||||
->limit($limit)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Recommendations;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* Recommends other products sharing at least one of $product's directly-
|
||||
* assigned collections — takes $product's first collection (a product
|
||||
* usually has one primary category; if it has several, the first is as
|
||||
* good a choice as any without a "primary collection" concept to prefer).
|
||||
* Returns nothing if $product has no collection at all, letting the next
|
||||
* rule in the chain (see RecommendationRule's docblock) take over.
|
||||
*
|
||||
* Queries Eloquent directly rather than going through Modules\Core\Catalog\
|
||||
* Services\ProductService — this runs at index time (see
|
||||
* RecommendationRule's docblock), where Meilisearch may be mid-reindex for
|
||||
* this very product and ProductService::list()'s locale-resolution has no
|
||||
* meaningful "current locale" to resolve against anyway.
|
||||
*/
|
||||
class SameCategoryRule implements RecommendationRule
|
||||
{
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection
|
||||
{
|
||||
$collection = $product->collections->first();
|
||||
|
||||
if ($collection === null) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return $collection->products()
|
||||
->whereKeyNot($exclude)
|
||||
->inRandomOrder()
|
||||
->limit($limit)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,21 @@ use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
* Reflects stock as of the last reindex only — nothing currently reindexes a
|
||||
* product when an order decrements its stock (see docs/product-listing.md).
|
||||
*
|
||||
* - recommendations (recommendations.id filterable): [{id, name, price, image}, ...]
|
||||
* up to 4 other products to show alongside this one (a "related products"
|
||||
* section), sourced from Modules\Core\Catalog\Services\RecommendationService's
|
||||
* configured rule chain (config('catalog.recommendation_rules')). Embedded
|
||||
* card data, not just ids, same reasoning as `collections`: renders
|
||||
* directly with zero extra Meilisearch calls. `name` is resolved via
|
||||
* translateAttribute() at index time (not through ProductService's
|
||||
* per-request locale resolution, since indexing has no "current locale"
|
||||
* the way a storefront request does) — same known index-time-locale
|
||||
* tradeoff `collections` already has. `recommendations.id` is filterable
|
||||
* specifically so Modules\Core\Catalog\Listeners\
|
||||
* ReindexProductsRecommendingProduct can find every product currently
|
||||
* recommending a given one, when that one changes — there's no Postgres
|
||||
* relation for this, a recommendation only exists inside the index.
|
||||
*
|
||||
* A review is created/edited independently of its product (Modules\Core\Providers\
|
||||
* ReviewServiceProvider re-indexes the product on review create/update/delete), so
|
||||
* this data doesn't go stale between full reindexes.
|
||||
@@ -67,6 +82,7 @@ class ProductIndexer extends BaseProductIndexer
|
||||
'slugs',
|
||||
'channel_ids',
|
||||
'in_stock',
|
||||
'recommendations.id',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -126,6 +142,16 @@ class ProductIndexer extends BaseProductIndexer
|
||||
$data['in_stock'] = $model->variants->contains(
|
||||
fn (ProductVariant $variant) => $variant->canBeFulfilledAtQuantity(1)
|
||||
);
|
||||
$data['recommendations'] = app(RecommendationService::class)
|
||||
->recommend($model)
|
||||
->load(['media', 'variants.prices'])
|
||||
->map(fn (Product $recommendation) => [
|
||||
'id' => $recommendation->id,
|
||||
'name' => $recommendation->translateAttribute('name'),
|
||||
'price' => $this->cheapestPrice($recommendation, $currency),
|
||||
'image' => $recommendation->media->first() ? $this->mapMedia($recommendation->media->first())['thumb'] : null,
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Services;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* Runs each rule in config('catalog.recommendation_rules'), in order,
|
||||
* topping up from each successive rule until $limit distinct products are
|
||||
* collected or every rule is exhausted — e.g. 3 from SameCategoryRule
|
||||
* (the product's category only has 3 other products) + 1 from RandomRule.
|
||||
* No rule is special-cased as "the fallback" here; a store gets fallback
|
||||
* behaviour purely by how it orders its own config (e.g. SameCategoryRule
|
||||
* before RandomRule). Never returns the same product twice even if two
|
||||
* rules would both suggest it (see RecommendationRule's $exclude), and
|
||||
* never returns fewer than $limit unless the store genuinely doesn't have
|
||||
* that many other products at all.
|
||||
*/
|
||||
class RecommendationService
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Product>
|
||||
*/
|
||||
public function recommend(Product $product, int $limit = 4): Collection
|
||||
{
|
||||
$recommendations = collect();
|
||||
|
||||
foreach (config('catalog.recommendation_rules', []) as $ruleClass) {
|
||||
if ($recommendations->count() >= $limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
$exclude = [$product->id, ...$recommendations->pluck('id')];
|
||||
$remaining = $limit - $recommendations->count();
|
||||
|
||||
/** @var RecommendationRule $rule */
|
||||
$rule = app($ruleClass);
|
||||
$recommendations = $recommendations->merge(
|
||||
$rule->recommend($product, $remaining, $exclude)
|
||||
);
|
||||
}
|
||||
|
||||
return $recommendations->take($limit)->values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Checkout\Contracts;
|
||||
|
||||
use Lunar\Exceptions\FingerprintMismatchException;
|
||||
use Lunar\Exceptions\Carts\CartException;
|
||||
use Lunar\Models\Cart;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* A boboko-owned payment driver — wraps a payment gateway's own confirmation
|
||||
* mechanics (Stripe's synchronous authorize() call, a redirect-based
|
||||
* provider's async callback/webhook, anything else) behind one uniform
|
||||
* moment: "payment is confirmed, place the order."
|
||||
*
|
||||
* confirm() is the only thing a driver is required to do: once it has,
|
||||
* by whatever mechanism is native to that gateway, independently decided
|
||||
* the payment succeeded, it calls Modules\Core\Checkout\Services\
|
||||
* CheckoutService::placeOrder($fingerprint) itself — no driver ever calls
|
||||
* Lunar\Models\Cart::createOrder() directly. This is what lets the
|
||||
* storefront checkout sequence stay uniform regardless of which provider is
|
||||
* active: set addresses, select shipping, hand off to whichever driver is
|
||||
* configured, and the driver decides when (or whether) the order actually
|
||||
* gets created. See docs/checkout.md / docs/payments.md.
|
||||
*/
|
||||
interface PaymentDriver
|
||||
{
|
||||
/**
|
||||
* Whether this driver can actually be used right now — e.g. Stripe
|
||||
* checking its own API key is present, an offline-style driver always
|
||||
* returning true since it has no external dependency. Independent of
|
||||
* Modules\Core\Payment\Models\PaymentMethod::enabled (the admin
|
||||
* on/off toggle) — CheckoutService::getPaymentMethods() combines both:
|
||||
* a type is only offered to the storefront if it's administratively
|
||||
* enabled AND its driver reports itself configured.
|
||||
*/
|
||||
public function isConfigured(): bool;
|
||||
|
||||
/**
|
||||
* $type is the payment type key being confirmed (e.g. 'cash-in-hand',
|
||||
* 'cash-on-delivery', 'stripe') — passed through even though most
|
||||
* drivers only ever serve one type, because a driver shared across
|
||||
* several types (e.g. one "no real confirmation" offline driver behind
|
||||
* both cash-in-hand and cash-on-delivery) needs it to look up that
|
||||
* type's own config (e.g. its 'authorized' status) rather than another
|
||||
* type's.
|
||||
*
|
||||
* $data carries whatever the gateway needs to confirm this specific
|
||||
* payment (Stripe: ['payment_intent' => $id], a redirect-based
|
||||
* provider: its callback payload) — passed explicitly by the caller
|
||||
* (a controller, a webhook job) rather than a driver reaching into the
|
||||
* global request(), so confirm() works the same whether it's called
|
||||
* from a synchronous HTTP request or an async webhook/job with no
|
||||
* active request at all.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*
|
||||
* @throws FingerprintMismatchException
|
||||
* @throws CartException
|
||||
*/
|
||||
public function confirm(Cart $cart, string $type, string $fingerprint, array $data): Order;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Checkout\Events;
|
||||
|
||||
use Lunar\Models\Cart;
|
||||
|
||||
/**
|
||||
* Dispatched by CheckoutService::selectPaymentMethod() — carries the plain
|
||||
* type key (e.g. 'cash-on-delivery', 'stripe'), same convention as
|
||||
* CartService's events (a plain reference the listener resolves further
|
||||
* itself, rather than an already-resolved object) since a payment type key
|
||||
* has nothing further to eagerly resolve the way a ShippingOption does.
|
||||
*/
|
||||
class PaymentMethodSelected
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Cart $cart,
|
||||
public readonly string $type,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Checkout\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Thrown by CheckoutService::selectPaymentMethod()/confirmPayment() when
|
||||
* $type doesn't resolve to a registered Modules\Core\Checkout\Contracts\
|
||||
* PaymentDriver (config('payment.drivers')) — same reasoning as
|
||||
* InvalidShippingOptionException: nothing here has a matching Lunar
|
||||
* exception type to reuse, so this is the boboko-owned signal instead of a
|
||||
* silent no-op or an opaque container-resolution error.
|
||||
*/
|
||||
class UnknownPaymentTypeException extends RuntimeException
|
||||
{
|
||||
public function __construct(public readonly string $type)
|
||||
{
|
||||
parent::__construct("The payment type \"{$type}\" is not registered.");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\Checkout\Services;
|
||||
|
||||
use Lunar\Exceptions\FingerprintMismatchException;
|
||||
use Lunar\Exceptions\Carts\CartException;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Lunar\Base\Addressable;
|
||||
@@ -10,11 +12,15 @@ use Lunar\Facades\ShippingManifest;
|
||||
use Lunar\Models\Cart;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Cart\Services\CartService;
|
||||
use Modules\Core\Checkout\Contracts\PaymentDriver;
|
||||
use Modules\Core\Checkout\Events\BillingAddressSet;
|
||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||
use Modules\Core\Checkout\Events\PaymentMethodSelected;
|
||||
use Modules\Core\Checkout\Events\ShippingAddressSet;
|
||||
use Modules\Core\Checkout\Events\ShippingOptionSelected;
|
||||
use Modules\Core\Checkout\Exceptions\InvalidShippingOptionException;
|
||||
use Modules\Core\Checkout\Exceptions\UnknownPaymentTypeException;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
/**
|
||||
* Storefront-facing checkout operations, mirroring
|
||||
@@ -99,6 +105,10 @@ class CheckoutService
|
||||
* stock adjusted the total, another tab modified the cart) rather than
|
||||
* silently placing an order at a different total than what was shown.
|
||||
*
|
||||
* Not called directly by a storefront — see confirmPayment(), which is
|
||||
* the only caller and supplies the fingerprint captured in
|
||||
* selectPaymentMethod(), not one the storefront has to obtain itself.
|
||||
*
|
||||
* No exception wrapping: Lunar\Validation\Cart\ValidateCartForOrderCreation
|
||||
* (run inside Cart::createOrder()) already throws
|
||||
* Lunar\Exceptions\Carts\CartException with a field-keyed MessageBag
|
||||
@@ -107,8 +117,8 @@ class CheckoutService
|
||||
* render as form errors directly. FingerprintMismatchException
|
||||
* propagates the same way, for the same reason.
|
||||
*
|
||||
* @throws \Lunar\Exceptions\FingerprintMismatchException
|
||||
* @throws \Lunar\Exceptions\Carts\CartException
|
||||
* @throws FingerprintMismatchException
|
||||
* @throws CartException
|
||||
*/
|
||||
public function placeOrder(string $fingerprint): Order
|
||||
{
|
||||
@@ -121,4 +131,118 @@ class CheckoutService
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every payment type currently offered to the storefront — every key
|
||||
* in config('lunar.payments.types') that is BOTH administratively
|
||||
* enabled (Modules\Core\Payment\Models\PaymentMethod::enabled) AND
|
||||
* whose registered PaymentDriver reports itself usable right now
|
||||
* (PaymentDriver::isConfigured() — e.g. Stripe with no API key set is
|
||||
* never offered, regardless of the enabled toggle). A type with no
|
||||
* PaymentMethod row at all (never seeded) is treated as not offered,
|
||||
* same as disabled — nothing here creates one; see
|
||||
* InstallLunarCommand::seedPaymentMethods().
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public function getPaymentMethods(): array
|
||||
{
|
||||
return PaymentMethod::where('enabled', true)
|
||||
->pluck('type')
|
||||
->filter(fn (string $type) => $this->resolvePaymentDriver($type)?->isConfigured() ?? false)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Records which payment type the shopper picked (Cart::meta
|
||||
* ['payment_method']) — read by e.g. Modules\Core\Payment\Pipelines\
|
||||
* Cart\ApplyCashOnDeliveryFee to add that type's own cart-total
|
||||
* adjustments before recalculation.
|
||||
*
|
||||
* Also snapshots Cart::fingerprint() into meta, *after* saving the
|
||||
* chosen type — the fingerprint has to reflect the final total
|
||||
* including any payment-type-specific adjustment (e.g. a COD
|
||||
* surcharge), which only exists once payment_method is set and the
|
||||
* cart recalculates. Captured here, server-side, rather than asked of
|
||||
* the storefront: this is the last moment before confirmPayment() that
|
||||
* the shopper's reviewed total is known, and confirmPayment() reads it
|
||||
* back internally instead of taking a fingerprint parameter — a
|
||||
* storefront should never need to know Cart::fingerprint() exists.
|
||||
*
|
||||
* Does not itself call a PaymentDriver — selecting a method and
|
||||
* confirming payment against it are deliberately separate steps, same
|
||||
* as selecting a shipping option happens before placing the order.
|
||||
*
|
||||
* @throws UnknownPaymentTypeException if $type isn't currently offered
|
||||
* — see getPaymentMethods() for what that means (registered,
|
||||
* administratively enabled, and its driver reports itself usable)
|
||||
*/
|
||||
public function selectPaymentMethod(string $type): Cart
|
||||
{
|
||||
if (! in_array($type, $this->getPaymentMethods(), true)) {
|
||||
throw new UnknownPaymentTypeException($type);
|
||||
}
|
||||
|
||||
$cart = $this->cart->currentOrCreate();
|
||||
$cart->meta = [...$cart->meta->toArray(), 'payment_method' => $type];
|
||||
$cart->save();
|
||||
|
||||
$cart = $cart->calculate();
|
||||
$cart->meta = [...$cart->meta->toArray(), 'checkout_fingerprint' => $cart->fingerprint()];
|
||||
$cart->save();
|
||||
|
||||
Event::dispatch(new PaymentMethodSelected($cart, $type));
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves $type's registered PaymentDriver and calls confirm() —
|
||||
* the driver decides whether/when the order actually gets placed (see
|
||||
* Modules\Core\Checkout\Contracts\PaymentDriver's docblock). $data
|
||||
* carries whatever that driver needs (Stripe's payment_intent id, a
|
||||
* future redirect-based provider's callback payload).
|
||||
*
|
||||
* The fingerprint passed to the driver is the one captured by
|
||||
* selectPaymentMethod(), not supplied by the caller — see that
|
||||
* method's docblock. Throws the same FingerprintMismatchException a
|
||||
* caller-supplied one would if the cart's total has since changed;
|
||||
* missing entirely (selectPaymentMethod() was never called for this
|
||||
* cart) is treated the same as a mismatch, not a different error.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*
|
||||
* @throws UnknownPaymentTypeException if $type isn't currently offered
|
||||
* (see getPaymentMethods()) — re-checked here, not just in
|
||||
* selectPaymentMethod(), since a type could be disabled between
|
||||
* selection and confirmation
|
||||
* @throws \Lunar\Exceptions\FingerprintMismatchException
|
||||
* @throws \Lunar\Exceptions\Carts\CartException
|
||||
*/
|
||||
public function confirmPayment(string $type, array $data = []): Order
|
||||
{
|
||||
if (! in_array($type, $this->getPaymentMethods(), true)) {
|
||||
throw new UnknownPaymentTypeException($type);
|
||||
}
|
||||
|
||||
$cart = $this->cart->currentOrCreate();
|
||||
$fingerprint = $cart->meta['checkout_fingerprint'] ?? '';
|
||||
|
||||
return $this->resolvePaymentDriver($type)->confirm($cart, $type, $fingerprint, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves $type's registered PaymentDriver, or null if $type has no
|
||||
* 'payment_driver' registered in config('lunar.payments.types.<type>')
|
||||
* at all — deliberately non-throwing so getPaymentMethods() can filter
|
||||
* unresolvable types silently rather than treating "not registered"
|
||||
* as an error condition when just checking availability.
|
||||
*/
|
||||
private function resolvePaymentDriver(string $type): ?PaymentDriver
|
||||
{
|
||||
$driverClass = config("lunar.payments.types.{$type}.payment_driver");
|
||||
|
||||
return $driverClass ? app($driverClass) : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Command;
|
||||
|
||||
use Lunar\Admin\Models\Staff;
|
||||
use Lunar\Admin\Console\Commands\MakeLunarAdminCommand;
|
||||
|
||||
use function Laravel\Prompts\text;
|
||||
@@ -31,7 +32,7 @@ class CreateAdminCommand extends MakeLunarAdminCommand
|
||||
required: true,
|
||||
validate: fn (string $email): ?string => match (true) {
|
||||
! filter_var($email, FILTER_VALIDATE_EMAIL) => 'The email address must be valid.',
|
||||
\Lunar\Admin\Models\Staff::where('email', $email)->exists() => 'A user with this email address already exists',
|
||||
Staff::where('email', $email)->exists() => 'A user with this email address already exists',
|
||||
default => null,
|
||||
},
|
||||
),
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace Modules\Core\Command;
|
||||
|
||||
use RecursiveIteratorIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use FilesystemIterator;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Modules\Core\ResultType\Error;
|
||||
@@ -88,10 +91,10 @@ class ExportCommand extends Command
|
||||
$zip->addFile($sqlFile, basename($sqlFile));
|
||||
|
||||
if (is_dir($filesDir)) {
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator(
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator(
|
||||
$filesDir,
|
||||
\FilesystemIterator::SKIP_DOTS,
|
||||
FilesystemIterator::SKIP_DOTS,
|
||||
),
|
||||
);
|
||||
foreach ($iterator as $file) {
|
||||
|
||||
@@ -21,6 +21,7 @@ use Lunar\Models\TaxZone;
|
||||
use Modules\Core\Localization\Models\LanguageLine;
|
||||
use Modules\Core\Localization\Services\StorefrontLabels;
|
||||
use Modules\Core\Localization\Services\TranslationService;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
/**
|
||||
* Overrides Lunar's own lunar:install to skip the interactive prompts (migrate
|
||||
@@ -247,6 +248,9 @@ class InstallLunarCommand extends Command
|
||||
$this->components->info('Seeding storefront label translations');
|
||||
$this->seedStorefrontLabels($translations);
|
||||
|
||||
$this->components->info('Seeding payment method settings');
|
||||
$this->seedPaymentMethods();
|
||||
|
||||
$this->components->info('Publishing Filament assets');
|
||||
$this->call('filament:assets');
|
||||
|
||||
@@ -278,4 +282,37 @@ class InstallLunarCommand extends Command
|
||||
$translations->create('storefront', $key, $text);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-type skip-if-exists, same idempotent convention as
|
||||
* seedStorefrontLabels() — a type already present (including one an
|
||||
* admin has since edited via the Filament Payment Methods resource) is
|
||||
* left untouched. Safe to re-run after a new payment type is added to
|
||||
* config('lunar.payments.types') (e.g. installing a Stripe/Nexi
|
||||
* package), which is the whole reason this isn't a one-time-only seed.
|
||||
*
|
||||
* Seeded disabled — a newly-seeded row (whether from this store's
|
||||
* initial install, or a payment provider package installed later)
|
||||
* shouldn't go live for shoppers before staff have actually reviewed
|
||||
* it (real credentials configured, a fee set, etc.) and turned it on
|
||||
* via the Payment Methods resource. See CheckoutService::
|
||||
* getPaymentMethods(), which only offers a type once both 'enabled'
|
||||
* here and its driver's own isConfigured() check pass.
|
||||
*/
|
||||
private function seedPaymentMethods(): void
|
||||
{
|
||||
$existingTypes = PaymentMethod::pluck('type');
|
||||
|
||||
foreach (array_keys(config('lunar.payments.types', [])) as $type) {
|
||||
if ($existingTypes->contains($type)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
PaymentMethod::create([
|
||||
'type' => $type,
|
||||
'enabled' => false,
|
||||
'data' => [],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+6
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core;
|
||||
|
||||
use Lunar\Admin\Filament\Resources\OrderResource\Pages\ManageOrder;
|
||||
use Filament\Contracts\Plugin;
|
||||
use Filament\Panel;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
@@ -24,6 +25,7 @@ use Modules\Core\Cart\Filament\Resources\CartResource;
|
||||
use Modules\Core\Catalog\Filament\Extensions\ProductOptionResourceExtension;
|
||||
use Modules\Core\Catalog\Filament\Extensions\ValuesRelationManagerExtension;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource;
|
||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
||||
use Modules\Core\Review\Filament\Extensions\ProductResourceExtension;
|
||||
use Modules\Core\Review\Models\ProductReview;
|
||||
use Modules\Core\Shipping\Extensions\OrderViewExtension;
|
||||
@@ -48,6 +50,7 @@ class CorePlugin implements Plugin
|
||||
->resources([
|
||||
LanguageLineResource::class,
|
||||
CartResource::class,
|
||||
PaymentMethodResource::class,
|
||||
])
|
||||
->plugin(ShippingPlugin::make())
|
||||
->pages([ManagePickupManifests::class]);
|
||||
@@ -59,7 +62,7 @@ class CorePlugin implements Plugin
|
||||
ValuesRelationManager::class => ValuesRelationManagerExtension::class,
|
||||
ShippingMethodResource::class => ShippingMethodResourceExtension::class,
|
||||
ListShippingMethod::class => ShippingMethodListExtension::class,
|
||||
OrderResource\Pages\ManageOrder::class => OrderViewExtension::class,
|
||||
ManageOrder::class => OrderViewExtension::class,
|
||||
]);
|
||||
|
||||
Product::macro('reviews', function (): HasMany {
|
||||
@@ -73,9 +76,8 @@ class CorePlugin implements Plugin
|
||||
'password',
|
||||
'remember_token',
|
||||
'email_verified_at',
|
||||
'two_factor_secret',
|
||||
'two_factor_recovery_codes',
|
||||
'two_factor_confirmed_at',
|
||||
'app_authentication_secret',
|
||||
'app_authentication_recovery_codes',
|
||||
]);
|
||||
|
||||
LunarStaff::created(function (LunarStaff $staff) {
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace Modules\Core\Customer\RelationManagers;
|
||||
|
||||
use Filament\Forms\Components\Group;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Tables\Actions\CreateAction;
|
||||
use Filament\Tables\Actions\DeleteAction;
|
||||
use Filament\Tables\Actions\EditAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -38,9 +38,9 @@ class AddressRelationManager extends BaseAddressRelationManager
|
||||
),
|
||||
])
|
||||
->headerActions([
|
||||
CreateAction::make()->form($this->addressForm()),
|
||||
CreateAction::make()->schema($this->addressForm()),
|
||||
])
|
||||
->actions([
|
||||
->recordActions([
|
||||
EditAction::make('editAddress')
|
||||
->fillForm(fn (AddressContract $record): array => [
|
||||
'line_one' => $record->line_one,
|
||||
@@ -51,7 +51,7 @@ class AddressRelationManager extends BaseAddressRelationManager
|
||||
'contact_email' => $record->contact_email,
|
||||
'contact_phone' => $record->contact_phone,
|
||||
])
|
||||
->form($this->addressForm()),
|
||||
->schema($this->addressForm()),
|
||||
DeleteAction::make('deleteAddress'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\Customer\RelationManagers;
|
||||
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
@@ -14,16 +16,16 @@ class UserRelationManager extends BaseUserRelationManager
|
||||
public function getDefaultTable(Table $table): Table
|
||||
{
|
||||
return $table->columns([
|
||||
Tables\Columns\TextColumn::make('name')
|
||||
TextColumn::make('name')
|
||||
->label(__('lunarpanel::user.table.name.label')),
|
||||
Tables\Columns\TextColumn::make('email')
|
||||
TextColumn::make('email')
|
||||
->label(__('lunarpanel::user.table.email.label')),
|
||||
])->actions([
|
||||
Tables\Actions\EditAction::make('edit')
|
||||
])->recordActions([
|
||||
EditAction::make('edit')
|
||||
->after(
|
||||
fn (Model $record) => CustomerUserEdited::dispatch($record)
|
||||
)
|
||||
->form([
|
||||
->schema([
|
||||
TextInput::make('email')
|
||||
->label(__('lunarpanel::user.form.email.label'))
|
||||
->required()
|
||||
|
||||
@@ -2,8 +2,17 @@
|
||||
|
||||
namespace Modules\Core\Localization\Filament\Resources;
|
||||
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Fieldset;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource\Pages\ListLanguageLines;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource\Pages\CreateLanguageLine;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource\Pages\EditLanguageLine;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Illuminate\Support\Collection;
|
||||
use Filament\Forms;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
@@ -15,29 +24,29 @@ class LanguageLineResource extends Resource
|
||||
{
|
||||
protected static ?string $model = LanguageLine::class;
|
||||
|
||||
protected static ?string $navigationIcon = 'heroicon-o-language';
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-language';
|
||||
|
||||
protected static ?string $navigationGroup = 'Settings';
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Settings';
|
||||
|
||||
protected static ?string $modelLabel = 'Translation';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Translations';
|
||||
|
||||
public static function form(Form $form): Form
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $form->schema([
|
||||
Forms\Components\TextInput::make('group')
|
||||
return $schema->components([
|
||||
TextInput::make('group')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->default('storefront')
|
||||
->helperText('Namespace for this label, e.g. "storefront" for e-shop UI text.'),
|
||||
|
||||
Forms\Components\TextInput::make('key')
|
||||
TextInput::make('key')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->helperText('Dot-notation key, e.g. "nav.cart".'),
|
||||
|
||||
Forms\Components\Fieldset::make('Translations')
|
||||
Fieldset::make('Translations')
|
||||
->schema(static::localeInputs()),
|
||||
]);
|
||||
}
|
||||
@@ -46,16 +55,16 @@ class LanguageLineResource extends Resource
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('group')
|
||||
TextColumn::make('group')
|
||||
->badge()
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('key')
|
||||
TextColumn::make('key')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
...static::localeColumns(),
|
||||
])
|
||||
->filters([
|
||||
Tables\Filters\SelectFilter::make('group')
|
||||
SelectFilter::make('group')
|
||||
->options(fn () => LanguageLine::query()->distinct()->pluck('group', 'group')),
|
||||
])
|
||||
->defaultSort('key');
|
||||
@@ -69,38 +78,38 @@ class LanguageLineResource extends Resource
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListLanguageLines::route('/'),
|
||||
'create' => Pages\CreateLanguageLine::route('/create'),
|
||||
'edit' => Pages\EditLanguageLine::route('/{record}/edit'),
|
||||
'index' => ListLanguageLines::route('/'),
|
||||
'create' => CreateLanguageLine::route('/create'),
|
||||
'edit' => EditLanguageLine::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Forms\Components\Textarea>
|
||||
* @return array<Textarea>
|
||||
*/
|
||||
private static function localeInputs(): array
|
||||
{
|
||||
return static::localeCodes()
|
||||
->map(fn (string $code) => Forms\Components\Textarea::make("text.{$code}")
|
||||
->map(fn (string $code) => Textarea::make("text.{$code}")
|
||||
->label(strtoupper($code))
|
||||
->rows(2))
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Tables\Columns\TextColumn>
|
||||
* @return array<TextColumn>
|
||||
*/
|
||||
private static function localeColumns(): array
|
||||
{
|
||||
return static::localeCodes()
|
||||
->map(fn (string $code) => Tables\Columns\TextColumn::make("text.{$code}")
|
||||
->map(fn (string $code) => TextColumn::make("text.{$code}")
|
||||
->label(strtoupper($code))
|
||||
->limit(40)
|
||||
->toggleable())
|
||||
->all();
|
||||
}
|
||||
|
||||
private static function localeCodes(): \Illuminate\Support\Collection
|
||||
private static function localeCodes(): Collection
|
||||
{
|
||||
return Language::query()->pluck('code');
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Localization\Filament\Resources\LanguageLineResource\Pages;
|
||||
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
@@ -17,7 +18,7 @@ class EditLanguageLine extends EditRecord
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\DeleteAction::make()
|
||||
DeleteAction::make()
|
||||
->action(function (LanguageLine $record) {
|
||||
app(TranslationService::class)->delete($record);
|
||||
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Localization\Filament\Resources\LanguageLineResource\Pages;
|
||||
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource;
|
||||
@@ -13,7 +14,7 @@ class ListLanguageLines extends ListRecords
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\CreateAction::make(),
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,9 @@ class StorefrontLabels
|
||||
'shop.search_label' => ['en' => 'Search products', 'el' => 'Αναζήτηση προϊόντων'],
|
||||
'shop.search_placeholder' => ['en' => 'Search products…', 'el' => 'Αναζήτησε προϊόντα…'],
|
||||
'shop.filter_price' => ['en' => 'Filter by price', 'el' => 'Φίλτρο τιμής'],
|
||||
'shop.price_min' => ['en' => 'Min price', 'el' => 'Ελάχιστη τιμή'],
|
||||
'shop.price_max' => ['en' => 'Max price', 'el' => 'Μέγιστη τιμή'],
|
||||
'shop.reset' => ['en' => 'Reset', 'el' => 'Επαναφορά'],
|
||||
'shop.apply' => ['en' => 'Apply', 'el' => 'Εφαρμογή'],
|
||||
'shop.availability' => ['en' => 'Availability', 'el' => 'Διαθεσιμότητα'],
|
||||
'shop.in_stock_only' => ['en' => 'In-stock products only', 'el' => 'Μόνο διαθέσιμα προϊόντα'],
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\MigrateImport;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Modules\Core\MigrateImport\JudgeMe\JudgeMeExportImporter;
|
||||
use Modules\Core\MigrateImport\Shopify\ShopifyExportImporter;
|
||||
|
||||
@@ -15,7 +16,7 @@ class ImporterFactory
|
||||
['judgeme', 'export'] => new JudgeMeExportImporter,
|
||||
// ["woocommerce", "export"] => new WooCommerceExportImporter(),
|
||||
// ["woocommerce", "api"] => new WooCommerceApiImporter(),
|
||||
default => throw new \InvalidArgumentException(
|
||||
default => throw new InvalidArgumentException(
|
||||
"No importer available for source \"{$spec->source}\" with type \"{$spec->type}\".",
|
||||
),
|
||||
};
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\MigrateImport\JudgeMe;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class JudgeMeCsvReader
|
||||
{
|
||||
/**
|
||||
@@ -12,7 +14,7 @@ class JudgeMeCsvReader
|
||||
$handle = fopen($csvPath, 'r');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new \RuntimeException("Could not open CSV file: {$csvPath}");
|
||||
throw new RuntimeException("Could not open CSV file: {$csvPath}");
|
||||
}
|
||||
|
||||
$headers = fgetcsv($handle);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\MigrateImport\JudgeMe;
|
||||
|
||||
use Throwable;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Core\MigrateImport\Importer;
|
||||
@@ -75,7 +76,7 @@ class JudgeMeExportImporter implements Importer
|
||||
foreach ($urls as $url) {
|
||||
try {
|
||||
$review->addMediaFromUrl($url)->toMediaCollection(ProductReview::IMAGES_COLLECTION);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
Log::warning('JudgeMe import: failed to download review image', [
|
||||
'review_id' => $review->id,
|
||||
'url' => $url,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\MigrateImport\Shopify;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ShopifyCsvReader
|
||||
{
|
||||
/**
|
||||
@@ -12,7 +14,7 @@ class ShopifyCsvReader
|
||||
$handle = fopen($csvPath, 'r');
|
||||
|
||||
if ($handle === false) {
|
||||
throw new \RuntimeException("Could not open CSV file: {$csvPath}");
|
||||
throw new RuntimeException("Could not open CSV file: {$csvPath}");
|
||||
}
|
||||
|
||||
$headers = fgetcsv($handle);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\MigrateImport\Shopify;
|
||||
|
||||
use Lunar\Models\TaxClass;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Lunar\Models\Collection;
|
||||
use Lunar\Models\CollectionGroup;
|
||||
@@ -120,7 +122,7 @@ class ShopifyExportImporter implements Importer
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, \Lunar\Models\ProductOption>
|
||||
* @return array<int, ProductOption>
|
||||
*/
|
||||
private function attachOptions(Product $product, array $row): array
|
||||
{
|
||||
@@ -146,7 +148,7 @@ class ShopifyExportImporter implements Importer
|
||||
string $handle,
|
||||
int $index,
|
||||
array $row,
|
||||
\Lunar\Models\TaxClass $taxClass,
|
||||
TaxClass $taxClass,
|
||||
Currency $currency,
|
||||
array $options,
|
||||
): void {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Notification;
|
||||
|
||||
use Throwable;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class NotificationRegistry
|
||||
@@ -44,7 +45,7 @@ class NotificationRegistry
|
||||
$notification->delay($event->delaySeconds);
|
||||
}
|
||||
$notification->notifiable()->notify($notification);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace Modules\Core\Option;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Exception;
|
||||
use RuntimeException;
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
@@ -39,7 +42,7 @@ final class LazyOption extends Option
|
||||
public function __construct($callback, array $arguments = [])
|
||||
{
|
||||
if (!is_callable($callback)) {
|
||||
throw new \InvalidArgumentException("Invalid callback given");
|
||||
throw new InvalidArgumentException("Invalid callback given");
|
||||
}
|
||||
|
||||
$this->callback = $callback;
|
||||
@@ -71,7 +74,7 @@ final class LazyOption extends Option
|
||||
return $this->option()->getOrCall($callable);
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
public function getOrThrow(Exception $ex)
|
||||
{
|
||||
return $this->option()->getOrThrow($ex);
|
||||
}
|
||||
@@ -146,7 +149,7 @@ final class LazyOption extends Option
|
||||
if ($option instanceof Option) {
|
||||
$this->option = $option;
|
||||
} else {
|
||||
throw new \RuntimeException(
|
||||
throw new RuntimeException(
|
||||
sprintf("Expected instance of %s", Option::class),
|
||||
);
|
||||
}
|
||||
|
||||
+4
-2
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\Core\Option;
|
||||
|
||||
use RuntimeException;
|
||||
use Exception;
|
||||
use EmptyIterator;
|
||||
|
||||
/**
|
||||
@@ -24,7 +26,7 @@ final class None extends Option
|
||||
|
||||
public function get()
|
||||
{
|
||||
throw new \RuntimeException("None has no value.");
|
||||
throw new RuntimeException("None has no value.");
|
||||
}
|
||||
|
||||
public function getOrCall($callable)
|
||||
@@ -37,7 +39,7 @@ final class None extends Option
|
||||
return $default;
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
public function getOrThrow(Exception $ex)
|
||||
{
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Option;
|
||||
|
||||
use Exception;
|
||||
use ArrayAccess;
|
||||
use IteratorAggregate;
|
||||
|
||||
@@ -164,7 +165,7 @@ abstract class Option implements IteratorAggregate
|
||||
abstract public function getOrCall($callable);
|
||||
|
||||
/** @return T */
|
||||
abstract public function getOrThrow(\Exception $ex);
|
||||
abstract public function getOrThrow(Exception $ex);
|
||||
|
||||
abstract public function isEmpty(): bool;
|
||||
|
||||
|
||||
+3
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Option;
|
||||
|
||||
use RuntimeException;
|
||||
use ArrayIterator;
|
||||
use Exception;
|
||||
|
||||
@@ -56,7 +57,7 @@ final class Some extends Option
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
public function getOrThrow(Exception $ex)
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
@@ -88,7 +89,7 @@ final class Some extends Option
|
||||
/** @var mixed */
|
||||
$rs = $callable($this->value);
|
||||
if (!$rs instanceof Option) {
|
||||
throw new \RuntimeException(
|
||||
throw new RuntimeException(
|
||||
"Callables passed to flatMap() must return an Option. Maybe you should use map() instead?",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Drivers;
|
||||
|
||||
use Lunar\Exceptions\Carts\CartException;
|
||||
use Lunar\Exceptions\DisallowMultipleCartOrdersException;
|
||||
use Lunar\Exceptions\FingerprintMismatchException;
|
||||
use Lunar\Models\Cart;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Checkout\Contracts\PaymentDriver;
|
||||
use Modules\Core\Checkout\Services\CheckoutService;
|
||||
|
||||
/**
|
||||
* Shared by every payment type with no real gateway to confirm against —
|
||||
* cash-in-hand, cash-on-delivery — where the shopper pays at pickup/on
|
||||
* delivery, not at checkout. confirm() has nothing to wait on, so it places
|
||||
* the order immediately, same as Lunar's own OfflinePayment would, but
|
||||
* through CheckoutService::placeOrder() so it goes through the same
|
||||
* fingerprint check every other driver does. $data is unused: nothing about
|
||||
* this confirmation depends on gateway-specific payload.
|
||||
*
|
||||
* Sets the order status to config("lunar.payments.types.{$type}.authorized")
|
||||
* afterward, using the type actually confirmed — not a hardcoded key —
|
||||
* since this one driver is shared across multiple types.
|
||||
* placeOrder() itself leaves the order at Lunar's configured draft_status,
|
||||
* same as every driver is responsible for moving it on from.
|
||||
*/
|
||||
class OfflinePaymentDriver implements PaymentDriver
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkout,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Always true — no external dependency to be missing.
|
||||
*/
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FingerprintMismatchException
|
||||
* @throws CartException
|
||||
* @throws DisallowMultipleCartOrdersException
|
||||
*/
|
||||
public function confirm(Cart $cart, string $type, string $fingerprint, array $data): Order
|
||||
{
|
||||
$order = $this->checkout->placeOrder($fingerprint);
|
||||
|
||||
$order->update([
|
||||
'status' => config("lunar.payments.types.{$type}.authorized", $order->status),
|
||||
]);
|
||||
|
||||
return $order->refresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Drivers;
|
||||
|
||||
use Lunar\Exceptions\FingerprintMismatchException;
|
||||
use Lunar\Exceptions\Carts\CartException;
|
||||
use Lunar\Exceptions\DisallowMultipleCartOrdersException;
|
||||
use Lunar\Models\Cart;
|
||||
use Lunar\Models\Order;
|
||||
use Lunar\Stripe\Actions\UpdateOrderFromIntent;
|
||||
use Lunar\Stripe\Facades\Stripe;
|
||||
use Lunar\Stripe\Models\StripePaymentIntent;
|
||||
use Modules\Core\Checkout\Contracts\PaymentDriver;
|
||||
use Modules\Core\Checkout\Services\CheckoutService;
|
||||
use Modules\Core\Payment\Exceptions\PaymentNotConfirmedException;
|
||||
use Stripe\PaymentIntent;
|
||||
|
||||
/**
|
||||
* Wraps Lunar\Stripe\StripePaymentType::authorize() to satisfy
|
||||
* Modules\Core\Checkout\Contracts\PaymentDriver — calls
|
||||
* CheckoutService::placeOrder($fingerprint) at the moment Stripe confirms
|
||||
* payment, instead of the vendor's own Cart::createOrder() call.
|
||||
*
|
||||
* This is a fork, not a decoration: StripePaymentType::authorize() is
|
||||
* `final` and calls Cart::createOrder() directly with no seam to redirect
|
||||
* that one call — so this class reimplements authorize()'s logic (intent
|
||||
* retrieval, capture-on-policy, status mapping via UpdateOrderFromIntent)
|
||||
* rather than wrapping the vendor method. Kept deliberately close to the
|
||||
* original so a lunarphp/stripe upgrade is easy to diff against. See
|
||||
* docs/payments.md.
|
||||
*/
|
||||
class StripePaymentDriver implements PaymentDriver
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkout,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Same key lunarphp/stripe's own StripeManager reads its API key from
|
||||
* (Stripe::setApiKey(config('services.stripe.key')) in
|
||||
* StripeManager::__construct()) — no key, no usable driver.
|
||||
*/
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return filled(config('services.stripe.key'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws PaymentNotConfirmedException if Stripe hasn't confirmed the
|
||||
* payment intent (wrong intent id, already processed, order already
|
||||
* placed, or the gateway call itself fails) — nothing here should be
|
||||
* treated as "place the order anyway."
|
||||
* @throws FingerprintMismatchException
|
||||
* @throws CartException
|
||||
*/
|
||||
public function confirm(Cart $cart, string $type, string $fingerprint, array $data): Order
|
||||
{
|
||||
$paymentIntentId = $data['payment_intent'];
|
||||
|
||||
$paymentIntentModel = StripePaymentIntent::where('intent_id', $paymentIntentId)->first();
|
||||
|
||||
if ($paymentIntentModel && ! $paymentIntentModel->isActive()) {
|
||||
throw new PaymentNotConfirmedException('Payment intent already processed.');
|
||||
}
|
||||
|
||||
if (! $paymentIntentModel) {
|
||||
$paymentIntentModel = StripePaymentIntent::create([
|
||||
'intent_id' => $paymentIntentId,
|
||||
'cart_id' => $cart->id,
|
||||
]);
|
||||
}
|
||||
|
||||
$paymentIntentModel->update(['processing_at' => now()]);
|
||||
|
||||
$stripe = Stripe::getClient();
|
||||
$paymentIntent = $stripe->paymentIntents->retrieve($paymentIntentId);
|
||||
|
||||
if (! $paymentIntent) {
|
||||
throw new PaymentNotConfirmedException('Unable to locate payment intent.');
|
||||
}
|
||||
|
||||
$policy = config('lunar.stripe.policy', 'automatic');
|
||||
|
||||
if ($paymentIntent->status === PaymentIntent::STATUS_REQUIRES_CAPTURE && $policy === 'automatic') {
|
||||
$paymentIntent = $stripe->paymentIntents->capture($paymentIntentId);
|
||||
}
|
||||
|
||||
if ($paymentIntent->status !== PaymentIntent::STATUS_SUCCEEDED) {
|
||||
$paymentIntentModel->update(['status' => $paymentIntent->status]);
|
||||
|
||||
throw new PaymentNotConfirmedException(
|
||||
$paymentIntent->last_payment_error->message ?? "Payment intent status: {$paymentIntent->status}."
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$order = $this->checkout->placeOrder($fingerprint);
|
||||
} catch (DisallowMultipleCartOrdersException|CartException $e) {
|
||||
throw new PaymentNotConfirmedException($e->getMessage(), previous: $e);
|
||||
}
|
||||
|
||||
$paymentIntentModel->order_id = $order->id;
|
||||
$paymentIntentModel->status = $paymentIntent->status;
|
||||
$paymentIntentModel->processed_at = now();
|
||||
$paymentIntentModel->save();
|
||||
|
||||
UpdateOrderFromIntent::execute($order, $paymentIntent);
|
||||
|
||||
return $order->refresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Thrown by a Modules\Core\Checkout\Contracts\PaymentDriver when the
|
||||
* gateway has not confirmed payment — wrong/expired intent, already
|
||||
* processed, or the gateway itself rejects the confirmation. A driver
|
||||
* throws this instead of silently placing the order: CheckoutService::
|
||||
* placeOrder() must only ever be called once a driver has positively
|
||||
* confirmed payment, never as a fallback.
|
||||
*/
|
||||
class PaymentNotConfirmedException extends RuntimeException
|
||||
{
|
||||
public function __construct(string $message, ?Throwable $previous = null)
|
||||
{
|
||||
parent::__construct($message, previous: $previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Filament\Resources;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages\ListPaymentMethods;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
/**
|
||||
* One row per payment type key (config('lunar.payments.types')), seeded by
|
||||
* InstallLunarCommand — never created/deleted here, only edited. `enabled`
|
||||
* toggles inline; `data.fee` (currently the only type-specific setting, for
|
||||
* cash-on-delivery's flat surcharge — see ApplyCashOnDeliveryFee) is edited
|
||||
* via a modal action rather than a dedicated form field, since not every
|
||||
* type has the same data keys.
|
||||
*/
|
||||
class PaymentMethodResource extends Resource
|
||||
{
|
||||
protected static ?string $model = PaymentMethod::class;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-credit-card';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Settings';
|
||||
|
||||
protected static ?string $modelLabel = 'Payment Method';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Payment Methods';
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('type')
|
||||
->label('Type'),
|
||||
ToggleColumn::make('enabled')
|
||||
->label('Enabled'),
|
||||
TextColumn::make('data.fee')
|
||||
->label('Fee')
|
||||
->formatStateUsing(fn (?int $state) => $state
|
||||
? number_format($state / 100, 2)
|
||||
: '—'),
|
||||
TextColumn::make('updated_at')
|
||||
->label('Last updated')
|
||||
->dateTime(),
|
||||
])
|
||||
->recordActions([
|
||||
static::editFeeAction(),
|
||||
])
|
||||
->defaultSort('type');
|
||||
}
|
||||
|
||||
/**
|
||||
* $data['fee'] is stored as an integer minor unit (cents), matching
|
||||
* Lunar's own Price convention everywhere else in this codebase — the
|
||||
* form collects/displays a decimal and converts at the boundary.
|
||||
*/
|
||||
private static function editFeeAction(): Action
|
||||
{
|
||||
return Action::make('edit_fee')
|
||||
->label('Edit fee')
|
||||
->icon('heroicon-o-pencil')
|
||||
->schema([
|
||||
TextInput::make('fee')
|
||||
->label('Fee')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->step(0.01)
|
||||
->helperText('Flat surcharge added when this payment method is selected.'),
|
||||
])
|
||||
->fillForm(fn (PaymentMethod $record) => [
|
||||
'fee' => filled($record->data['fee'] ?? null) ? $record->data['fee'] / 100 : null,
|
||||
])
|
||||
->action(function (PaymentMethod $record, array $data) {
|
||||
$record->update([
|
||||
'data' => [
|
||||
...$record->data->toArray(),
|
||||
'fee' => filled($data['fee']) ? (int) round($data['fee'] * 100) : null,
|
||||
],
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListPaymentMethods::route('/'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function canDelete($record = null): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages;
|
||||
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
||||
|
||||
class ListPaymentMethods extends ListRecords
|
||||
{
|
||||
protected static string $resource = PaymentMethodResource::class;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Admin-editable settings for one payment type key (matching a key in
|
||||
* config('lunar.payments.types')) — enabled/disabled, and whatever type-
|
||||
* specific data it needs (starts with 'fee' for cash-on-delivery's flat
|
||||
* surcharge). Mirrors Lunar's own Discount model: a single jsonb 'data'
|
||||
* column holding keyed settings, rather than a fixed column per setting or
|
||||
* a separate conditions table — new settings are a code change (a new key
|
||||
* read from data), not a migration.
|
||||
*
|
||||
* Seeded once per type by InstallLunarCommand (skip-if-exists, same
|
||||
* idempotent convention as seedStorefrontLabels()) — never auto-created on
|
||||
* read, so a read path stays a pure read.
|
||||
*/
|
||||
class PaymentMethod extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'enabled' => 'boolean',
|
||||
'data' => AsArrayObject::class,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Pipelines\Cart;
|
||||
|
||||
use Closure;
|
||||
use Lunar\DataTypes\Price;
|
||||
use Lunar\Models\Contracts\Cart as CartContract;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
final class ApplyCashOnDeliveryFee
|
||||
{
|
||||
/**
|
||||
* Called just before cart totals are calculated.
|
||||
*
|
||||
* @param Closure(CartContract): mixed $next
|
||||
*/
|
||||
public function handle(CartContract $cart, Closure $next): mixed
|
||||
{
|
||||
if (($cart->meta['payment_method'] ?? null) === 'cash-on-delivery') {
|
||||
$fee = (int) (PaymentMethod::where('type', 'cash-on-delivery')->value('data->fee') ?? 0);
|
||||
|
||||
$cart->shippingTotal = new Price(
|
||||
($cart->shippingTotal?->value ?? 0) + $fee,
|
||||
$cart->currency,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
return $next($cart);
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,32 @@
|
||||
|
||||
namespace Modules\Core\Providers;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Lunar\Models\Product;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Lunar\Models\ProductOptionValue;
|
||||
use Modules\Core\Catalog\Events\ProductDeleted;
|
||||
use Modules\Core\Catalog\Events\ProductSaved;
|
||||
use Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct;
|
||||
use Modules\Core\Catalog\Observers\ProductOptionReindexObserver;
|
||||
use Modules\Core\Catalog\OptionTypes\ColorOptionType;
|
||||
use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
|
||||
class CatalogServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__ . '/../../config/catalog.php', 'catalog');
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$this->publishes([
|
||||
__DIR__ . '/../../config/catalog.php' => config_path('catalog.php'),
|
||||
], 'core-config');
|
||||
|
||||
ProductOptionTypeManager::get()->register([
|
||||
ColorOptionType::class,
|
||||
]);
|
||||
@@ -24,5 +39,28 @@ class CatalogServiceProvider extends ServiceProvider
|
||||
|
||||
ProductOptionValue::saved(fn (ProductOptionValue $value) => $observer->valueSaved($value));
|
||||
ProductOptionValue::deleted(fn (ProductOptionValue $value) => $observer->valueDeleted($value));
|
||||
|
||||
Product::saved(fn (Product $product) => Event::dispatch(new ProductSaved($product)));
|
||||
Product::deleted(fn (Product $product) => Event::dispatch(new ProductDeleted($product->id)));
|
||||
|
||||
Event::listen(ProductSaved::class, [ReindexProductsRecommendingProduct::class, 'handleSaved']);
|
||||
Event::listen(ProductDeleted::class, [ReindexProductsRecommendingProduct::class, 'handleDeleted']);
|
||||
|
||||
$this->app->booted(function () {
|
||||
// A full nightly reindex, on top of the per-event reindexing
|
||||
// above — catches everything event-driven reindexing
|
||||
// deliberately doesn't cover: a newly-created product not yet
|
||||
// appearing as a recommendation elsewhere, in_stock/price
|
||||
// drifting from an order decrementing stock outside a product
|
||||
// save, and any other staleness ProductIndexer's own docblock
|
||||
// already documents as accepted between reindexes. --refresh
|
||||
// re-syncs filterable/sortable field settings too, not just
|
||||
// documents, so a deploy that changed ProductIndexer's field
|
||||
// list self-heals here even if `lunar:meilisearch:setup`
|
||||
// wasn't run manually after that deploy.
|
||||
$this->app->make(Schedule::class)
|
||||
->command('lunar:search:index', ['Lunar\\Models\\Product', '--refresh'])
|
||||
->dailyAt('03:00');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Lunar\Pipelines\Cart\ApplyShipping;
|
||||
|
||||
class PaymentServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__ . '/../../config/payment.php', 'payment');
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
config([
|
||||
'lunar.payments.types' => array_merge(
|
||||
config('lunar.payments.types', []),
|
||||
config('payment.types', [])
|
||||
),
|
||||
]);
|
||||
|
||||
$cartPipeline = config('lunar.cart.pipelines.cart', []);
|
||||
$insertAfter = array_search(ApplyShipping::class, $cartPipeline, true);
|
||||
|
||||
foreach (config('payment.cart_pipeline', []) as $pipe) {
|
||||
if (in_array($pipe, $cartPipeline, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($insertAfter === false) {
|
||||
$cartPipeline[] = $pipe;
|
||||
} else {
|
||||
array_splice($cartPipeline, $insertAfter + 1, 0, [$pipe]);
|
||||
$insertAfter++;
|
||||
}
|
||||
}
|
||||
|
||||
config(['lunar.cart.pipelines.cart' => $cartPipeline]);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Modules\Core\ResultType;
|
||||
|
||||
use Modules\Core\Option\Option;
|
||||
use Modules\Core\Option\None;
|
||||
use Modules\Core\Option\Some;
|
||||
|
||||
@@ -11,7 +12,7 @@ use Modules\Core\Option\Some;
|
||||
* @template T
|
||||
* @template E
|
||||
*
|
||||
* @extends \Modules\Core\ResultType\Result<T,E>
|
||||
* @extends Result<T, E>
|
||||
*/
|
||||
final class Error extends Result
|
||||
{
|
||||
@@ -39,7 +40,7 @@ final class Error extends Result
|
||||
*
|
||||
* @param F $value
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<T,F>
|
||||
* @return Result<T, F>
|
||||
*/
|
||||
public static function create($value): Error
|
||||
{
|
||||
@@ -49,7 +50,7 @@ final class Error extends Result
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<T>
|
||||
* @return Option<T>
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
@@ -63,7 +64,7 @@ final class Error extends Result
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,E>
|
||||
* @return Result<S, E>
|
||||
*/
|
||||
public function map(callable $f): Result
|
||||
{
|
||||
@@ -76,20 +77,20 @@ final class Error extends Result
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\Modules\Core\ResultType\Result<S,F> $f
|
||||
* @param callable(T):Result<S, F> $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,F>
|
||||
* @return Result<S, F>
|
||||
*/
|
||||
public function flatMap(callable $f): Result
|
||||
{
|
||||
/** @var \Modules\Core\ResultType\Result<S,F> */
|
||||
/** @var Result<S, F> */
|
||||
return self::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<E>
|
||||
* @return Option<E>
|
||||
*/
|
||||
public function error(): Some
|
||||
{
|
||||
@@ -103,7 +104,7 @@ final class Error extends Result
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<T,F>
|
||||
* @return Result<T, F>
|
||||
*/
|
||||
public function mapError(callable $f): Result
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Modules\Core\ResultType;
|
||||
|
||||
use Modules\Core\Option\Option;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @template E
|
||||
@@ -13,7 +15,7 @@ abstract class Result
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<T>
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function success();
|
||||
|
||||
@@ -24,7 +26,7 @@ abstract class Result
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,E>
|
||||
* @return Result<S, E>
|
||||
*/
|
||||
abstract public function map(callable $f);
|
||||
|
||||
@@ -34,16 +36,16 @@ abstract class Result
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\Modules\Core\ResultType\Result<S,F> $f
|
||||
* @param callable(T):Result<S, F> $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,F>
|
||||
* @return Result<S, F>
|
||||
*/
|
||||
abstract public function flatMap(callable $f);
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<E>
|
||||
* @return Option<E>
|
||||
*/
|
||||
abstract public function error();
|
||||
|
||||
@@ -54,7 +56,7 @@ abstract class Result
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<T,F>
|
||||
* @return Result<T, F>
|
||||
*/
|
||||
abstract public function mapError(callable $f);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Modules\Core\ResultType;
|
||||
|
||||
use Modules\Core\Option\Option;
|
||||
use Modules\Core\Option\None;
|
||||
use Modules\Core\Option\Some;
|
||||
|
||||
@@ -11,7 +12,7 @@ use Modules\Core\Option\Some;
|
||||
* @template T
|
||||
* @template E
|
||||
*
|
||||
* @extends \Modules\Core\ResultType\Result<T,E>
|
||||
* @extends Result<T, E>
|
||||
*/
|
||||
final class Success extends Result
|
||||
{
|
||||
@@ -39,7 +40,7 @@ final class Success extends Result
|
||||
*
|
||||
* @param S $value
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,E>
|
||||
* @return Result<S, E>
|
||||
*/
|
||||
public static function create($value): Success
|
||||
{
|
||||
@@ -49,7 +50,7 @@ final class Success extends Result
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<T>
|
||||
* @return Option<T>
|
||||
*/
|
||||
public function success(): Some
|
||||
{
|
||||
@@ -63,7 +64,7 @@ final class Success extends Result
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,E>
|
||||
* @return Result<S, E>
|
||||
*/
|
||||
public function map(callable $f): Result
|
||||
{
|
||||
@@ -76,9 +77,9 @@ final class Success extends Result
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\Modules\Core\ResultType\Result<S,F> $f
|
||||
* @param callable(T):Result<S, F> $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<S,F>
|
||||
* @return Result<S, F>
|
||||
*/
|
||||
public function flatMap(callable $f)
|
||||
{
|
||||
@@ -88,7 +89,7 @@ final class Success extends Result
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \Modules\Core\Option\Option<E>
|
||||
* @return Option<E>
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
@@ -102,7 +103,7 @@ final class Success extends Result
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \Modules\Core\ResultType\Result<T,F>
|
||||
* @return Result<T, F>
|
||||
*/
|
||||
public function mapError(callable $f): Result
|
||||
{
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
namespace Modules\Core\Review\Filament\Pages;
|
||||
|
||||
use Filament\Forms\Components\Group;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\DeleteBulkAction;
|
||||
use Filament\Forms\Components\Placeholder;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Tables\Actions\Action;
|
||||
use Filament\Tables\Actions\DeleteAction;
|
||||
use Filament\Tables\Actions\DeleteBulkAction;
|
||||
use Filament\Tables\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -40,10 +40,10 @@ class ManageProductReviews extends BaseManageRelatedRecords
|
||||
return 'Reviews';
|
||||
}
|
||||
|
||||
public function form(Form $form): Form
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $form
|
||||
->schema([
|
||||
return $schema
|
||||
->components([
|
||||
TextInput::make('rating')
|
||||
->label('Rating')
|
||||
->disabled(),
|
||||
@@ -127,12 +127,12 @@ class ManageProductReviews extends BaseManageRelatedRecords
|
||||
->filters([
|
||||
//
|
||||
])
|
||||
->actions([
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
Action::make('reply')
|
||||
->label(fn (ProductReview $record) => $record->reply ? 'Edit reply' : 'Reply')
|
||||
->icon('heroicon-o-chat-bubble-left-right')
|
||||
->form([
|
||||
->schema([
|
||||
Textarea::make('reply')
|
||||
->label('Reply')
|
||||
->required(),
|
||||
@@ -146,7 +146,7 @@ class ManageProductReviews extends BaseManageRelatedRecords
|
||||
}),
|
||||
DeleteAction::make(),
|
||||
])
|
||||
->bulkActions([
|
||||
->toolbarActions([
|
||||
DeleteBulkAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Carriers\Acs;
|
||||
|
||||
use RuntimeException;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Order;
|
||||
@@ -88,7 +89,7 @@ class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsMani
|
||||
public function cancelShipment(Shipment $shipment): void
|
||||
{
|
||||
if ($shipment->manifest_reference) {
|
||||
throw new \RuntimeException('Cannot cancel a shipment already included in an issued manifest.');
|
||||
throw new RuntimeException('Cannot cancel a shipment already included in an issued manifest.');
|
||||
}
|
||||
|
||||
$this->client->call('ACS_Delete_Voucher', [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Lunar\DataTypes\ShippingOption;
|
||||
use Lunar\Models\Cart;
|
||||
@@ -27,7 +28,7 @@ use Lunar\Shipping\Models\ShippingRate;
|
||||
*/
|
||||
trait CachesLivePricing
|
||||
{
|
||||
private function cached(ShippingRate $shippingRate, Cart $cart, \Closure $resolve): ?ShippingOption
|
||||
private function cached(ShippingRate $shippingRate, Cart $cart, Closure $resolve): ?ShippingOption
|
||||
{
|
||||
return Cache::remember(
|
||||
"shipping.live_price.{$shippingRate->id}.{$cart->id}",
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Extensions;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Closure;
|
||||
use Throwable;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms;
|
||||
use Filament\Notifications\Notification;
|
||||
@@ -20,28 +25,28 @@ class OrderViewExtension extends ViewPageExtension
|
||||
return $actions;
|
||||
}
|
||||
|
||||
private function createShipmentAction(): Actions\Action
|
||||
private function createShipmentAction(): Action
|
||||
{
|
||||
return Actions\Action::make('create_shipment')
|
||||
return Action::make('create_shipment')
|
||||
->label('Create Shipment')
|
||||
->icon('heroicon-o-truck')
|
||||
->modalSubmitActionLabel('Create Shipment')
|
||||
->form([
|
||||
Forms\Components\TextInput::make('weight')
|
||||
->schema([
|
||||
TextInput::make('weight')
|
||||
->label('Package weight (kg)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->helperText('Leave blank to use the carrier\'s default.'),
|
||||
Forms\Components\TextInput::make('destination_location_id')
|
||||
TextInput::make('destination_location_id')
|
||||
->label('Box Now locker ID')
|
||||
->helperText('Only required for Box Now shipments.')
|
||||
->default(fn (Order $record) => $record->shippingAddress?->meta['box_now_locker']['locationId'] ?? null),
|
||||
Forms\Components\Toggle::make('confirm')
|
||||
Toggle::make('confirm')
|
||||
->label('Confirm')
|
||||
->helperText('This will create a real shipment with the carrier.')
|
||||
->rules([
|
||||
function () {
|
||||
return function (string $attribute, $value, \Closure $fail) {
|
||||
return function (string $attribute, $value, Closure $fail) {
|
||||
if ($value !== true) {
|
||||
$fail('Please confirm before creating the shipment.');
|
||||
}
|
||||
@@ -49,7 +54,7 @@ class OrderViewExtension extends ViewPageExtension
|
||||
},
|
||||
]),
|
||||
])
|
||||
->action(function (Order $record, array $data, Actions\Action $action) {
|
||||
->action(function (Order $record, array $data, Action $action) {
|
||||
$service = $this->resolveFulfillmentService($record);
|
||||
|
||||
if (! $service) {
|
||||
@@ -70,7 +75,7 @@ class OrderViewExtension extends ViewPageExtension
|
||||
|
||||
try {
|
||||
$service->createShipment($record, $request);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Extensions;
|
||||
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms\Components\Group;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Lunar\Admin\Support\Extending\BaseExtension;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
@@ -22,8 +23,8 @@ class ShippingMethodListExtension extends BaseExtension
|
||||
public function headerActions(array $actions): array
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if ($action instanceof Actions\CreateAction) {
|
||||
$action->form([
|
||||
if ($action instanceof CreateAction) {
|
||||
$action->schema([
|
||||
ShippingMethodResource::getNameFormComponent(),
|
||||
Group::make([
|
||||
ShippingMethodResource::getCodeFormComponent(),
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Extensions;
|
||||
|
||||
use Filament\Forms\Components\Component;
|
||||
use Filament\Forms\Components\Concerns\HasChildComponents;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Concerns\HasChildComponents;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use InvalidArgumentException;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Forms\Get;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Lunar\Admin\Support\Extending\ResourceExtension;
|
||||
@@ -15,11 +16,11 @@ use Modules\Core\Shipping\Contracts\SupportsLivePricing;
|
||||
|
||||
class ShippingMethodResourceExtension extends ResourceExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
public function extendForm(Schema $schema): Schema
|
||||
{
|
||||
return $form->schema(
|
||||
return $schema->components(
|
||||
$this->replaceChargeByField(
|
||||
$this->replaceDriverField($form->getComponents())
|
||||
$this->replaceDriverField($schema->getComponents())
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -83,7 +84,7 @@ class ShippingMethodResourceExtension extends ResourceExtension
|
||||
|
||||
try {
|
||||
return Shipping::driver($driver) instanceof SupportsLivePricing;
|
||||
} catch (\InvalidArgumentException) {
|
||||
} catch (InvalidArgumentException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -120,7 +121,7 @@ class ShippingMethodResourceExtension extends ResourceExtension
|
||||
* Select (nested inside Section > Group) with one listing every
|
||||
* registered driver, built-in or custom.
|
||||
*
|
||||
* @param array<Component> $components
|
||||
* @param array<Component> $components
|
||||
* @return array<Component>
|
||||
*/
|
||||
private function replaceDriverField(array $components): array
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Pages;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\BulkAction;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Actions\Action;
|
||||
use Filament\Tables\Actions\BulkAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
@@ -21,7 +21,7 @@ class ManagePickupManifests extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationIcon = 'heroicon-o-truck';
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-truck';
|
||||
|
||||
protected static ?string $navigationLabel = 'Pickup Manifests';
|
||||
|
||||
@@ -38,11 +38,11 @@ class ManagePickupManifests extends Page implements HasTable
|
||||
* OrderResource uses 1) so this page never competes to be first even as
|
||||
* more Sales-group items are added later.
|
||||
*/
|
||||
protected static ?string $navigationGroup = 'Sales';
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Sales';
|
||||
|
||||
protected static ?int $navigationSort = 100;
|
||||
|
||||
protected static string $view = 'core::shipping.filament.pages.manage-pickup-manifests';
|
||||
protected string $view = 'core::shipping.filament.pages.manage-pickup-manifests';
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
@@ -54,13 +54,13 @@ class ManagePickupManifests extends Page implements HasTable
|
||||
TextColumn::make('order.reference')->label('Order'),
|
||||
TextColumn::make('label_printed_at')->label('Printed')->dateTime()->placeholder('Not printed'),
|
||||
])
|
||||
->actions([
|
||||
->recordActions([
|
||||
Action::make('print')
|
||||
->label('Print')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Shipment $record) => $this->printShipment($record)),
|
||||
])
|
||||
->bulkActions([
|
||||
->toolbarActions([
|
||||
BulkAction::make('print_selected')
|
||||
->label('Print selected')
|
||||
->icon('heroicon-o-printer')
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Pages;
|
||||
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Forms\Get;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -36,12 +36,12 @@ use Lunar\Shipping\Models\ShippingRate;
|
||||
*/
|
||||
class ManageShippingRates extends BaseManageShippingRates
|
||||
{
|
||||
public function form(Form $form): Form
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$form = parent::form($form);
|
||||
$schema = parent::form($schema);
|
||||
|
||||
return $form->schema(
|
||||
$this->labelPriceFieldsAsFallbackWhenLive($form->getComponents())
|
||||
return $schema->components(
|
||||
$this->labelPriceFieldsAsFallbackWhenLive($schema->getComponents())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user