Feature: Moving Payment Methods to DB, adding fees, Transaction Updates, Refund Updates, General Updates to Payments
This commit is contained in:
+9
-29
@@ -1,37 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Modules\Core\Payment\Drivers\OfflinePaymentDriver;
|
|
||||||
use Modules\Core\Payment\Pipelines\Cart\ApplyCashOnDeliveryFee;
|
use Modules\Core\Payment\Pipelines\Cart\ApplyCashOnDeliveryFee;
|
||||||
|
|
||||||
return [
|
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 —
|
|
||||||
| the driver instance Modules\Core\Payment\Services\PaymentDriverResolver
|
|
||||||
| resolves via the container. 'capture_mode' ('pay' or 'authorize') is
|
|
||||||
| also boboko-owned — which contract method
|
|
||||||
| CheckoutService::initiatePayment() calls for this type. Kept on the
|
|
||||||
| same row as 'driver' rather than a second, separately-keyed map, so a
|
|
||||||
| type's full definition lives in one place.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
'types' => [
|
|
||||||
'cash-on-delivery' => [
|
|
||||||
'driver' => 'offline',
|
|
||||||
'payment_driver' => OfflinePaymentDriver::class,
|
|
||||||
'capture_mode' => 'pay',
|
|
||||||
'captured_status' => 'payment-offline',
|
|
||||||
'fee' => 0,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
| Lunar cart pipeline additions
|
| Lunar cart pipeline additions
|
||||||
@@ -41,6 +12,15 @@ return [
|
|||||||
| the cash-on-delivery fee is added to the shipping total before the
|
| the cash-on-delivery fee is added to the shipping total before the
|
||||||
| final Calculate step sums everything up.
|
| final Calculate step sums everything up.
|
||||||
|
|
|
|
||||||
|
| This is the one thing left in this file — everything about WHICH
|
||||||
|
| payment methods exist (driver mapping, capture_mode, statuses) moved
|
||||||
|
| onto Modules\Core\Payment\Models\PaymentMethod's own row (see
|
||||||
|
| docs/payments.md): that's a per-instance, merchant decision, not a
|
||||||
|
| store-wide-singular setting, so it never belonged in config at all.
|
||||||
|
| This pipeline registration IS genuinely cross-cutting — every store
|
||||||
|
| using this driver gets the same cart-pipeline wiring, regardless of
|
||||||
|
| how many payment methods it configures.
|
||||||
|
|
|
||||||
*/
|
*/
|
||||||
'cart_pipeline' => [
|
'cart_pipeline' => [
|
||||||
ApplyCashOnDeliveryFee::class,
|
ApplyCashOnDeliveryFee::class,
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the driver mapping and per-type behavior that used to live in
|
||||||
|
* config('lunar.payments.types.{type}.*') onto the PaymentMethod row
|
||||||
|
* itself — same DB-instance-vs-config split Modules\Core\Shipping's own
|
||||||
|
* shipping_methods table already has (code/driver/name/enabled columns,
|
||||||
|
* no driver mapping in any config file). See docs/payments.md.
|
||||||
|
*
|
||||||
|
* - driver: the Modules\Core\Payment\Services\PaymentDriverRegistry key
|
||||||
|
* (NOT the same as `type` — two rows can share one driver).
|
||||||
|
* - name: admin-facing label. Nothing played this role before; `type`
|
||||||
|
* was always the machine slug.
|
||||||
|
* - capture_mode / captured_status / authorized_status: per-instance
|
||||||
|
* behavior — fails the "would a store ever want two different answers
|
||||||
|
* to this" cross-cutting-config test, so these move off config.
|
||||||
|
* - position: admin-controlled display/checkout order.
|
||||||
|
* - driver_missing_at: set by the payment:sync-drivers command when
|
||||||
|
* `driver` no longer resolves via the registry — deliberately
|
||||||
|
* separate from `enabled`, so a driver vanishing (a deploy removed
|
||||||
|
* it) is never confused with an admin's own manual toggle, and a
|
||||||
|
* driver that comes back later auto-clears this with no admin action.
|
||||||
|
*/
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('payment_methods', function (Blueprint $table) {
|
||||||
|
$table->string('name')->nullable()->after('type');
|
||||||
|
$table->string('driver')->nullable()->after('name');
|
||||||
|
$table->string('capture_mode')->nullable()->after('driver');
|
||||||
|
$table->string('captured_status')->nullable()->after('capture_mode');
|
||||||
|
$table->string('authorized_status')->nullable()->after('captured_status');
|
||||||
|
$table->unsignedInteger('position')->default(0)->after('authorized_status');
|
||||||
|
$table->timestamp('driver_missing_at')->nullable()->after('position');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('payment_methods', function (Blueprint $table) {
|
||||||
|
$table->dropColumn([
|
||||||
|
'name', 'driver', 'capture_mode', 'captured_status',
|
||||||
|
'authorized_status', 'position', 'driver_missing_at',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* captured_status/authorized_status (added in 2026_09_05_000001) cover a
|
||||||
|
* payment being taken, but nothing wrote Order.status on a REFUND —
|
||||||
|
* Order::paymentStatus() (Order\Support\OrderStatus::payment(), derived
|
||||||
|
* live from transactions) already reflects a refund correctly, but the
|
||||||
|
* stored status column — the one admin filtering, customer emails, etc.
|
||||||
|
* actually key off — never moved. Same reasoning as captured_status/
|
||||||
|
* authorized_status: a store could plausibly want a different resulting
|
||||||
|
* status per payment method (e.g. a "Refunded" vs. a "Refund Pending"
|
||||||
|
* variant), so this is a PaymentMethod column, not cross-cutting config.
|
||||||
|
*
|
||||||
|
* Deliberately no separate void_status — void never moved money (it
|
||||||
|
* releases an authorization hold before any capture), so it doesn't carry
|
||||||
|
* the same "the customer needs to see this changed" weight a refund does;
|
||||||
|
* add one later if a real need for it shows up.
|
||||||
|
*/
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('payment_methods', function (Blueprint $table) {
|
||||||
|
$table->string('refunded_status')->nullable()->after('authorized_status');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('payment_methods', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('refunded_status');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
@php
|
||||||
|
$transaction = $getRecord();
|
||||||
|
$notes = $transaction->notes ?: ($transaction->meta['notes'] ?? null);
|
||||||
|
@endphp
|
||||||
|
|
||||||
|
@once
|
||||||
|
@php
|
||||||
|
$renderPaymentIcons();
|
||||||
|
@endphp
|
||||||
|
@endonce
|
||||||
|
<div
|
||||||
|
@class([
|
||||||
|
'text-sm rounded-lg shadow-md border dark:bg-gray-900',
|
||||||
|
'text-gray-950 dark:text-white',
|
||||||
|
match($transaction->type){
|
||||||
|
'refund' => 'border-orange-300',
|
||||||
|
'intent' => 'border-sky-300',
|
||||||
|
'capture' => 'border-green-300',
|
||||||
|
default => 'border-gray-300',
|
||||||
|
},
|
||||||
|
'!border-red-500 bg-red-50' => !$transaction->success,
|
||||||
|
'bg-gray-50' => $transaction->success,
|
||||||
|
])
|
||||||
|
>
|
||||||
|
<div class="p-2 space-y-2">
|
||||||
|
<div class="px-4 py-2 rounded text-xs bg-white dark:bg-gray-800 shadow text-gray-600 dark:text-gray-400 ring-1 ring-gray-100 dark:ring-gray-700">
|
||||||
|
<span>{{ $transaction->driver }}</span> //
|
||||||
|
<span>{{ $transaction->reference }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center justify-between p-4 bg-white dark:bg-gray-800 rounded shadow ring-1 ring-gray-100 dark:ring-gray-700">
|
||||||
|
<div class="flex items-center gap-6">
|
||||||
|
<div>
|
||||||
|
<strong class="text-xs">
|
||||||
|
{{ $transaction->status }}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<svg viewBox="0 0 50 50" class="w-10">
|
||||||
|
<use xlink:href="#{{ strtolower($transaction->card_type) }}"></use>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if($transaction->last_four)
|
||||||
|
<p class="text-sm">
|
||||||
|
<span class="inline-block -translate-y-px">
|
||||||
|
∗∗∗∗ ∗∗∗∗ ∗∗∗∗
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span class="font-medium">
|
||||||
|
{{ (string) $transaction->last_four }}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<strong
|
||||||
|
@class([
|
||||||
|
"text-sm",
|
||||||
|
'text-red-500' => !$transaction->success,
|
||||||
|
match($transaction->type){
|
||||||
|
'refund' => "text-orange-500",
|
||||||
|
default => "text-gray-900 dark:text-gray-100",
|
||||||
|
},
|
||||||
|
])
|
||||||
|
>
|
||||||
|
@if($transaction->type == 'refund')-@endif{{ $transaction->amount->formatted }}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="px-4 py-2 bg-white dark:bg-gray-800 shadow rounded flex items-center justify-between text-gray-600 dark:text-gray-400 ring-1 ring-gray-100 dark:ring-gray-700">
|
||||||
|
<div class="text-xs flex items-center gap-2">
|
||||||
|
<div>
|
||||||
|
<x-filament::icon
|
||||||
|
icon="heroicon-o-clock"
|
||||||
|
class="w-4"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span>{{ $transaction->created_at->format('jS F Y h:ia') }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex space-x-2">
|
||||||
|
@foreach($transaction->paymentChecks() as $check)
|
||||||
|
<x-filament::badge
|
||||||
|
:icon="$check->successful ? 'heroicon-m-check' : 'heroicon-m-x-mark'"
|
||||||
|
:color="$check->successful ? \Filament\Support\Colors\Color::Sky : 'gray'"
|
||||||
|
>
|
||||||
|
{{ $check->label }}: {{ $check->message }}
|
||||||
|
</x-filament::badge>
|
||||||
|
@endforeach
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if($notes)
|
||||||
|
<div class="px-4 py-2 bg-white dark:bg-gray-800 shadow flex items-center rounded gap-2 ring-1 ring-gray-100 dark:ring-gray-700">
|
||||||
|
<div>
|
||||||
|
<x-filament::icon
|
||||||
|
icon="heroicon-o-chat-bubble-oval-left-ellipsis"
|
||||||
|
class="w-4"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="text-sm">{{ $notes }}</p>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
@class([
|
||||||
|
"bottom-0 left-0 block w-full text-center rounded-b-lg border-t text-xs py-1",
|
||||||
|
"!bg-red-50 !dark:bg-red-400/10 !border-red-300 !text-red-600 !dark:text-red-400" => !$transaction->success,
|
||||||
|
match($transaction->type){
|
||||||
|
'refund' => "bg-orange-50 dark:bg-orange-400/10 border-orange-300 text-orange-600 dark:text-orange-400",
|
||||||
|
'intent' => "bg-sky-50 dark:bg-sky-400/10 border-sky-300 text-sky-600 dark:text-sky-400",
|
||||||
|
'capture' => "bg-green-50 dark:bg-green-400/10 border-green-300 text-green-600 dark:text-green-400",
|
||||||
|
default => "bg-gray-50 dark:bg-gray-400/10 border-gray-300 text-gray-600 dark:text-gray-400",
|
||||||
|
},
|
||||||
|
])
|
||||||
|
>
|
||||||
|
@if(!$transaction->success)
|
||||||
|
{{ __('lunarpanel::order.transactions.failed') }}
|
||||||
|
@else
|
||||||
|
{{ __('lunarpanel::order.transactions.'.$transaction->type) }}
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -19,7 +19,8 @@ use Modules\Core\Checkout\Exceptions\InvalidShippingOptionException;
|
|||||||
use Modules\Core\Checkout\Exceptions\UnknownPaymentTypeException;
|
use Modules\Core\Checkout\Exceptions\UnknownPaymentTypeException;
|
||||||
use Modules\Core\Payment\DTOs\PaymentResult;
|
use Modules\Core\Payment\DTOs\PaymentResult;
|
||||||
use Modules\Core\Payment\Models\PaymentMethod;
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
use Modules\Core\Payment\Services\PaymentDriverResolver;
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodCache;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Storefront-facing checkout operations, mirroring
|
* Storefront-facing checkout operations, mirroring
|
||||||
@@ -42,7 +43,8 @@ class CheckoutService
|
|||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly CartService $cart,
|
private readonly CartService $cart,
|
||||||
private readonly PaymentDriverResolver $paymentDrivers,
|
private readonly PaymentDriverRegistry $paymentDrivers,
|
||||||
|
private readonly PaymentMethodCache $paymentMethods,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function setShippingAddress(array|Addressable $address): Cart
|
public function setShippingAddress(array|Addressable $address): Cart
|
||||||
@@ -100,25 +102,28 @@ class CheckoutService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Every payment type currently offered to the storefront — every key
|
* Every payment method currently offered to the storefront, ordered by
|
||||||
* in config('lunar.payments.types') that is BOTH administratively
|
* Modules\Core\Payment\Models\PaymentMethod::position — a row is
|
||||||
* enabled (Modules\Core\Payment\Models\PaymentMethod::enabled) AND
|
* offered only when ALL three checks pass, each meaning something
|
||||||
* whose registered driver reports itself usable right now
|
* different to an admin diagnosing why a method isn't showing up (see
|
||||||
* (Configurable::isConfigured() — e.g. Stripe with no API key set is
|
* docs/payments.md):
|
||||||
* never offered, regardless of the enabled toggle). A type with no
|
* 1. `enabled` — an admin turned it on.
|
||||||
* PaymentMethod row at all (never seeded) is treated as not offered,
|
* 2. its `driver` still resolves via PaymentDriverRegistry — the
|
||||||
* same as disabled — nothing here creates one; see
|
* driver class hasn't been removed (see the `payment:sync-drivers`
|
||||||
* InstallLunarCommand::seedPaymentMethods().
|
* command, which sets `driver_missing_at` when this fails; a row
|
||||||
|
* with that set is excluded here regardless of `enabled`, so a
|
||||||
|
* vanished driver can never silently look "available").
|
||||||
|
* 3. the resolved driver reports Configurable::isConfigured() — its
|
||||||
|
* own runtime requirements (e.g. an API key) are met.
|
||||||
*
|
*
|
||||||
* @return array<string>
|
* @return Collection<int, PaymentMethod>
|
||||||
*/
|
*/
|
||||||
public function getPaymentMethods(): array
|
public function getPaymentMethods(): Collection
|
||||||
{
|
{
|
||||||
return PaymentMethod::where('enabled', true)
|
return $this->paymentMethods->all()
|
||||||
->pluck('type')
|
->filter(fn (PaymentMethod $method) => $method->enabled && $method->driver_missing_at === null)
|
||||||
->filter(fn (string $type) => $this->paymentDrivers->resolve($type)?->isConfigured() ?? false)
|
->filter(fn (PaymentMethod $method) => $this->paymentDrivers->resolve($method->driver)?->isConfigured() ?? false)
|
||||||
->values()
|
->values();
|
||||||
->all();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -142,12 +147,11 @@ class CheckoutService
|
|||||||
* as selecting a shipping option happens before placing the order.
|
* as selecting a shipping option happens before placing the order.
|
||||||
*
|
*
|
||||||
* @throws UnknownPaymentTypeException if $type isn't currently offered
|
* @throws UnknownPaymentTypeException if $type isn't currently offered
|
||||||
* — see getPaymentMethods() for what that means (registered,
|
* — see getPaymentMethods() for what that means
|
||||||
* administratively enabled, and its driver reports itself usable)
|
|
||||||
*/
|
*/
|
||||||
public function selectPaymentMethod(string $type): Cart
|
public function selectPaymentMethod(string $type): Cart
|
||||||
{
|
{
|
||||||
if (! in_array($type, $this->getPaymentMethods(), true)) {
|
if (! $this->getPaymentMethods()->contains('type', $type)) {
|
||||||
throw new UnknownPaymentTypeException($type);
|
throw new UnknownPaymentTypeException($type);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,11 +174,9 @@ class CheckoutService
|
|||||||
* Order exists (Cart::createOrder() — confirmed idempotent against a
|
* Order exists (Cart::createOrder() — confirmed idempotent against a
|
||||||
* cart's own pre-existing, not-yet-placed-at draft; see
|
* cart's own pre-existing, not-yet-placed-at draft; see
|
||||||
* vendor/lunarphp/core/src/Actions/Carts/CreateOrder.php), then
|
* vendor/lunarphp/core/src/Actions/Carts/CreateOrder.php), then
|
||||||
* resolves the payment type selected by selectPaymentMethod() and
|
* resolves the payment method selected by selectPaymentMethod() and
|
||||||
* calls pay() or authorize() on its driver, per that type's
|
* calls pay() or authorize() on its driver, per that method's own
|
||||||
* config('lunar.payments.types.{type}.capture_mode') — boboko-core's
|
* `capture_mode` column.
|
||||||
* own types (config/payment.php) are merged into that same Lunar
|
|
||||||
* config key by PaymentServiceProvider::boot().
|
|
||||||
*
|
*
|
||||||
* Returns the driver's own PaymentResult UNCHANGED — this method does
|
* Returns the driver's own PaymentResult UNCHANGED — this method does
|
||||||
* not wait for or resolve anything past what pay()/authorize() itself
|
* not wait for or resolve anything past what pay()/authorize() itself
|
||||||
@@ -183,14 +185,6 @@ class CheckoutService
|
|||||||
* outcome, not an error — the caller (a storefront controller) is
|
* outcome, not an error — the caller (a storefront controller) is
|
||||||
* responsible for whatever the gateway needs next.
|
* responsible for whatever the gateway needs next.
|
||||||
*
|
*
|
||||||
* KNOWN GAP, explicitly out of scope for now: PaymentResult alone does
|
|
||||||
* not carry gateway-specific continuation data (e.g. Stripe's
|
|
||||||
* PaymentIntent client_secret for a Pending result needing frontend
|
|
||||||
* confirmation) — that concept existed on the deleted PaymentInitiation
|
|
||||||
* DTO and was intentionally removed from Payment's abstraction layer.
|
|
||||||
* Nothing here re-introduces it; only OfflinePaymentDriver's
|
|
||||||
* always-Immediate-Succeeded path is fully wired end-to-end today.
|
|
||||||
*
|
|
||||||
* The draft order's own $order->total (not the Cart's) is what gets
|
* The draft order's own $order->total (not the Cart's) is what gets
|
||||||
* passed as $amount — Order::$total is Lunar's own Price-cast
|
* passed as $amount — Order::$total is Lunar's own Price-cast
|
||||||
* attribute, already resolving the correct Currency via the order's
|
* attribute, already resolving the correct Currency via the order's
|
||||||
@@ -210,8 +204,8 @@ class CheckoutService
|
|||||||
*
|
*
|
||||||
* @throws UnknownPaymentTypeException if the cart's selected
|
* @throws UnknownPaymentTypeException if the cart's selected
|
||||||
* payment_method (from selectPaymentMethod()) is no longer offered
|
* payment_method (from selectPaymentMethod()) is no longer offered
|
||||||
* — re-checked here, not just at selection time, since a type could
|
* — re-checked here, not just at selection time, since a method
|
||||||
* be disabled in between
|
* could be disabled (or its driver removed) in between
|
||||||
* @throws FingerprintMismatchException
|
* @throws FingerprintMismatchException
|
||||||
* @throws CartException
|
* @throws CartException
|
||||||
*/
|
*/
|
||||||
@@ -221,19 +215,18 @@ class CheckoutService
|
|||||||
$cart->checkFingerprint($fingerprint);
|
$cart->checkFingerprint($fingerprint);
|
||||||
|
|
||||||
$type = $cart->meta['payment_method'] ?? null;
|
$type = $cart->meta['payment_method'] ?? null;
|
||||||
|
$method = $type !== null ? $this->getPaymentMethods()->firstWhere('type', $type) : null;
|
||||||
|
|
||||||
if ($type === null || ! in_array($type, $this->getPaymentMethods(), true)) {
|
if ($method === null) {
|
||||||
throw new UnknownPaymentTypeException((string) $type);
|
throw new UnknownPaymentTypeException((string) $type);
|
||||||
}
|
}
|
||||||
|
|
||||||
$order = $cart->createOrder();
|
$order = $cart->createOrder();
|
||||||
|
|
||||||
$driver = $this->paymentDrivers->resolve($type);
|
$driver = $this->paymentDrivers->resolve($method->driver);
|
||||||
$captureMode = config("lunar.payments.types.{$type}.capture_mode", 'pay');
|
|
||||||
|
|
||||||
$context = ['cart_id' => $cart->id, 'order_id' => $order->id];
|
$context = ['cart_id' => $cart->id, 'order_id' => $order->id];
|
||||||
|
|
||||||
return $captureMode === 'authorize'
|
return $method->capture_mode === 'authorize'
|
||||||
? $driver->authorize($type, $order->total, $data, $context)
|
? $driver->authorize($type, $order->total, $data, $context)
|
||||||
: $driver->pay($type, $order->total, $data, $context);
|
: $driver->pay($type, $order->total, $data, $context);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -284,35 +284,39 @@ class InstallLunarCommand extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Per-type skip-if-exists, same idempotent convention as
|
* A single, deliberately opinionated starter row on fresh install —
|
||||||
* seedStorefrontLabels() — a type already present (including one an
|
* `PaymentMethod` is now fully admin-creatable/deletable (see
|
||||||
* admin has since edited via the Filament Payment Methods resource) is
|
* docs/payments.md), so this is no longer "seed every config-defined
|
||||||
* left untouched. Safe to re-run after a new payment type is added to
|
* type," it's "give a fresh store one reasonable payment method to
|
||||||
* config('lunar.payments.types') (e.g. installing a Stripe/Nexi
|
* start from instead of zero." Every value here is a plain literal in
|
||||||
* package), which is the whole reason this isn't a one-time-only seed.
|
* THIS command, not sourced from config or PaymentDriverRegistry — a
|
||||||
|
* driver has no business carrying opinions about what its captured
|
||||||
|
* order status should be called; that's a merchant decision.
|
||||||
*
|
*
|
||||||
* Seeded disabled — a newly-seeded row (whether from this store's
|
* Skip-if-exists on `type`, same idempotent convention as
|
||||||
* initial install, or a payment provider package installed later)
|
* seedStorefrontLabels() — an admin who has since edited or deleted
|
||||||
* shouldn't go live for shoppers before staff have actually reviewed
|
* this row (via the Filament Payment Methods resource) is left alone;
|
||||||
* it (real credentials configured, a fee set, etc.) and turned it on
|
* re-running lunar:install never recreates a deleted starter row.
|
||||||
* via the Payment Methods resource. See CheckoutService::
|
*
|
||||||
* getPaymentMethods(), which only offers a type once both 'enabled'
|
* Seeded disabled — shouldn't go live for shoppers before staff have
|
||||||
* here and its driver's own isConfigured() check pass.
|
* actually reviewed it and turned it on via the Payment Methods
|
||||||
|
* resource. See CheckoutService::getPaymentMethods().
|
||||||
*/
|
*/
|
||||||
private function seedPaymentMethods(): void
|
private function seedPaymentMethods(): void
|
||||||
{
|
{
|
||||||
$existingTypes = PaymentMethod::pluck('type');
|
if (PaymentMethod::where('type', 'cash-on-delivery')->exists()) {
|
||||||
|
return;
|
||||||
foreach (array_keys(config('lunar.payments.types', [])) as $type) {
|
|
||||||
if ($existingTypes->contains($type)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
PaymentMethod::create([
|
|
||||||
'type' => $type,
|
|
||||||
'enabled' => false,
|
|
||||||
'data' => [],
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PaymentMethod::create([
|
||||||
|
'type' => 'cash-on-delivery',
|
||||||
|
'name' => 'Cash on Delivery',
|
||||||
|
'driver' => 'offline',
|
||||||
|
'capture_mode' => 'pay',
|
||||||
|
'captured_status' => 'payment-offline',
|
||||||
|
'position' => 0,
|
||||||
|
'enabled' => false,
|
||||||
|
'data' => [],
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Command;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconciles every Modules\Core\Payment\Models\PaymentMethod row's `driver`
|
||||||
|
* column against PaymentDriverRegistry — the registry only knows "which
|
||||||
|
* driver classes exist THIS deploy," and only at the moment something
|
||||||
|
* calls resolve(); nothing else notices a driver disappearing (a package
|
||||||
|
* removed, a custom Registry::register() call deleted) on its own. Meant
|
||||||
|
* to run unconditionally on every container start/deploy (alongside
|
||||||
|
* `migrate`), not on a schedule — "did the set of registered drivers
|
||||||
|
* change" is a deploy-time event, cheap enough to check every single time
|
||||||
|
* regardless of whether anything actually changed. See docs/payments.md.
|
||||||
|
*
|
||||||
|
* Sets/clears `driver_missing_at` — deliberately NOT the `enabled` column,
|
||||||
|
* so an admin's own manual toggle is never confused with "the driver
|
||||||
|
* vanished," and a driver that comes back in a later deploy auto-clears
|
||||||
|
* this with no admin action needed.
|
||||||
|
*/
|
||||||
|
class SyncPaymentDriversCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'boboko:payment:sync-drivers';
|
||||||
|
|
||||||
|
protected $description = 'Flag PaymentMethod rows whose driver no longer resolves via the registry, and clear the flag for ones that do again';
|
||||||
|
|
||||||
|
public function handle(PaymentDriverRegistry $registry): int
|
||||||
|
{
|
||||||
|
$missing = 0;
|
||||||
|
$restored = 0;
|
||||||
|
|
||||||
|
PaymentMethod::query()->each(function (PaymentMethod $method) use ($registry, &$missing, &$restored) {
|
||||||
|
$resolves = $method->driver !== null && $registry->resolve($method->driver) !== null;
|
||||||
|
|
||||||
|
if (! $resolves && $method->driver_missing_at === null) {
|
||||||
|
$method->update(['driver_missing_at' => now()]);
|
||||||
|
$missing++;
|
||||||
|
} elseif ($resolves && $method->driver_missing_at !== null) {
|
||||||
|
$method->update(['driver_missing_at' => null]);
|
||||||
|
$restored++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->components->info("Payment driver sync complete: {$missing} newly flagged, {$restored} restored.");
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-1
@@ -3,6 +3,7 @@
|
|||||||
namespace Modules\Core;
|
namespace Modules\Core;
|
||||||
|
|
||||||
use Lunar\Admin\Filament\Resources\OrderResource\Pages\ManageOrder;
|
use Lunar\Admin\Filament\Resources\OrderResource\Pages\ManageOrder;
|
||||||
|
use Lunar\Admin\Filament\Resources\OrderResource\Pages\Components\OrderItemsTable;
|
||||||
use Filament\Contracts\Plugin;
|
use Filament\Contracts\Plugin;
|
||||||
use Filament\Panel;
|
use Filament\Panel;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
@@ -25,6 +26,9 @@ use Modules\Core\Cart\Filament\Resources\CartResource;
|
|||||||
use Modules\Core\Catalog\Filament\Extensions\ProductOptionResourceExtension;
|
use Modules\Core\Catalog\Filament\Extensions\ProductOptionResourceExtension;
|
||||||
use Modules\Core\Catalog\Filament\Extensions\ValuesRelationManagerExtension;
|
use Modules\Core\Catalog\Filament\Extensions\ValuesRelationManagerExtension;
|
||||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource;
|
use Modules\Core\Localization\Filament\Resources\LanguageLineResource;
|
||||||
|
use Modules\Core\Order\Filament\Extensions\OrderItemsTableExtension;
|
||||||
|
use Modules\Core\Order\Filament\Extensions\OrderRefundActionsExtension;
|
||||||
|
use Modules\Core\Order\Filament\Extensions\OrderTransactionsExtension;
|
||||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
||||||
use Modules\Core\Review\Filament\Extensions\ProductResourceExtension;
|
use Modules\Core\Review\Filament\Extensions\ProductResourceExtension;
|
||||||
use Modules\Core\Review\Models\ProductReview;
|
use Modules\Core\Review\Models\ProductReview;
|
||||||
@@ -62,7 +66,8 @@ class CorePlugin implements Plugin
|
|||||||
ValuesRelationManager::class => ValuesRelationManagerExtension::class,
|
ValuesRelationManager::class => ValuesRelationManagerExtension::class,
|
||||||
ShippingMethodResource::class => ShippingMethodResourceExtension::class,
|
ShippingMethodResource::class => ShippingMethodResourceExtension::class,
|
||||||
ListShippingMethod::class => ShippingMethodListExtension::class,
|
ListShippingMethod::class => ShippingMethodListExtension::class,
|
||||||
ManageOrder::class => OrderViewExtension::class,
|
ManageOrder::class => [OrderViewExtension::class, OrderRefundActionsExtension::class, OrderTransactionsExtension::class],
|
||||||
|
OrderItemsTable::class => OrderItemsTableExtension::class,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
Product::macro('reviews', function (): HasMany {
|
Product::macro('reviews', function (): HasMany {
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Order\Filament\Extensions;
|
||||||
|
|
||||||
|
use Filament\Actions\BulkAction;
|
||||||
|
use Filament\Support\Exceptions\Halt;
|
||||||
|
use Filament\Tables\Table;
|
||||||
|
use Lunar\Admin\Support\Extending\BaseExtension;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same fix as OrderRefundActionsExtension, applied to the order lines
|
||||||
|
* table's "bulk_refund" toolbar action (Lunar\Admin\...\OrderItemsTable::
|
||||||
|
* getBulkRefundAction()) — see that class's docblock for the underlying
|
||||||
|
* Filament bug (failureNotification()+failure()+halt() never actually
|
||||||
|
* sends the notification, because halt()'s Halt exception is caught before
|
||||||
|
* Filament reaches the code that would send it).
|
||||||
|
*/
|
||||||
|
class OrderItemsTableExtension extends BaseExtension
|
||||||
|
{
|
||||||
|
public function extendTable(Table $table): Table
|
||||||
|
{
|
||||||
|
return $table->toolbarActions(
|
||||||
|
array_map(
|
||||||
|
fn ($action) => $action instanceof BulkAction && $action->getName() === 'bulk_refund'
|
||||||
|
? $this->fixFailureNotification($action)
|
||||||
|
: $action,
|
||||||
|
$table->getToolbarActions(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function fixFailureNotification(BulkAction $action): BulkAction
|
||||||
|
{
|
||||||
|
$originalAction = $action->getActionFunction();
|
||||||
|
|
||||||
|
if ($originalAction === null) {
|
||||||
|
return $action;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $action->action(function (array $arguments) use ($action, $originalAction) {
|
||||||
|
try {
|
||||||
|
return $action->evaluate($originalAction, $arguments);
|
||||||
|
} catch (Halt $exception) {
|
||||||
|
$action->sendFailureNotification();
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Order\Filament\Extensions;
|
||||||
|
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Support\Exceptions\Halt;
|
||||||
|
use Lunar\Admin\Support\Extending\ViewPageExtension;
|
||||||
|
use Lunar\Models\Transaction;
|
||||||
|
use Modules\Core\Payment\Contracts\SupportsRefunds;
|
||||||
|
use Modules\Core\Payment\Models\CoreTransaction;
|
||||||
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
use Modules\Core\Payment\Support\TransactionDriverAdapter;
|
||||||
|
use ReflectionProperty;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fixes a real bug in Lunar's own admin panel, not anything specific to how
|
||||||
|
* boboko resolves payment drivers: ManageOrder::getRefundAction() and
|
||||||
|
* ::getCaptureAction() (vendor/lunarphp/lunar/.../ManageOrder.php) both
|
||||||
|
* report a failed refund/capture by calling, in this order:
|
||||||
|
* $action->failureNotification(...); $action->failure(); $action->halt();
|
||||||
|
* but Filament\Actions\Concerns\InteractsWithActions::callMountedAction()
|
||||||
|
* only ever calls sendFailureNotification() from a match($action->getStatus())
|
||||||
|
* block that runs AFTER the action's call() returns normally — halt() throws
|
||||||
|
* Filament\Support\Exceptions\Halt, which is caught in an earlier catch block
|
||||||
|
* that rolls back the DB transaction and returns null, never reaching that
|
||||||
|
* match block. So the notification set via failureNotification() is built
|
||||||
|
* but never sent: the admin sees the modal just close/reset with no
|
||||||
|
* indication anything happened. This was always broken in Lunar; it was
|
||||||
|
* invisible before because nothing in this codebase's Transaction::driver()
|
||||||
|
* could return a real, honest failure — see Payment\Support\
|
||||||
|
* TransactionDriverAdapter's own docblock for that history.
|
||||||
|
*
|
||||||
|
* Fix, for capture: wrap the action's own action() closure so that, on
|
||||||
|
* Halt, we call $action->sendFailureNotification() ourselves before letting
|
||||||
|
* the Halt continue propagating — everything else is untouched.
|
||||||
|
*
|
||||||
|
* Fix, for refund: same notification fix, but the action() closure is
|
||||||
|
* replaced outright (not wrapped) rather than reused, because refund also
|
||||||
|
* needs a "Refund via" driver Select added to the modal (see
|
||||||
|
* fixRefundAction()) and the actual call routed through
|
||||||
|
* Payment\Support\TransactionDriverAdapter::refundVia() instead of
|
||||||
|
* Lunar\Models\Transaction::refund() — see fixRefundAction()'s own
|
||||||
|
* docblock.
|
||||||
|
*/
|
||||||
|
class OrderRefundActionsExtension extends ViewPageExtension
|
||||||
|
{
|
||||||
|
public function headerActions(array $actions): array
|
||||||
|
{
|
||||||
|
return array_map(
|
||||||
|
fn (Action $action) => match ($action->getName()) {
|
||||||
|
'refund' => $this->fixRefundAction($action),
|
||||||
|
'capture' => $this->fixFailureNotification($action),
|
||||||
|
default => $action,
|
||||||
|
},
|
||||||
|
$actions,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Combines both refund-only changes on top of the failure-notification
|
||||||
|
* fix every action here gets: adds a "Refund via" driver Select
|
||||||
|
* (defaulting to the transaction's own driver) to the modal, and
|
||||||
|
* replaces the actual refund call with one that honours that field —
|
||||||
|
* calling Payment\Support\TransactionDriverAdapter::refundVia()
|
||||||
|
* directly (bypassing Lunar\Models\Transaction::refund(), whose fixed
|
||||||
|
* refund(int $amount, $notes = null) signature has no room for a
|
||||||
|
* driver override) whenever the admin picked a driver other than the
|
||||||
|
* transaction's own. When left at the default, behaviour is identical
|
||||||
|
* to calling $transaction->refund() — refundVia() resolves to the same
|
||||||
|
* driver either way.
|
||||||
|
*
|
||||||
|
* The Select is appended to Lunar's own schema closure (read via
|
||||||
|
* reflection — HasSchema::$schema has no public getter) rather than
|
||||||
|
* replacing it outright, so the transaction/amount/notes/confirm
|
||||||
|
* fields Lunar already built are untouched.
|
||||||
|
*/
|
||||||
|
private function fixRefundAction(Action $action): Action
|
||||||
|
{
|
||||||
|
$originalSchema = $this->readProtectedProperty($action, 'schema');
|
||||||
|
|
||||||
|
$action->schema(function (array $arguments) use ($action, $originalSchema) {
|
||||||
|
$fields = is_callable($originalSchema)
|
||||||
|
? $action->evaluate($originalSchema, $arguments)
|
||||||
|
: ($originalSchema ?? []);
|
||||||
|
|
||||||
|
return [
|
||||||
|
...$fields,
|
||||||
|
Select::make('driver')
|
||||||
|
->label('Refund via')
|
||||||
|
->options(fn () => $this->refundCapableDriverLabels())
|
||||||
|
->default(fn ($get) => $this->driverKeyForTransaction($get('transaction')))
|
||||||
|
->native(false)
|
||||||
|
->required(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return $action->action(function (array $data, Action $action) {
|
||||||
|
$transaction = Transaction::find($data['transaction']);
|
||||||
|
|
||||||
|
if (! $transaction instanceof CoreTransaction) {
|
||||||
|
$action->failureNotification(fn () => Notification::make('refund_failure')->danger()->title('Transaction not found.'))
|
||||||
|
->sendFailureNotification();
|
||||||
|
|
||||||
|
throw new Halt;
|
||||||
|
}
|
||||||
|
|
||||||
|
$adapter = app(TransactionDriverAdapter::class);
|
||||||
|
$driverKey = $data['driver'] ?? $adapter->driverKeyFor($transaction);
|
||||||
|
|
||||||
|
$response = $adapter->refundVia($transaction, $driverKey, (int) bcmul((string) $data['amount'], (string) $transaction->order->currency->factor), $data['notes'] ?? null);
|
||||||
|
|
||||||
|
if (! $response->success) {
|
||||||
|
$action->failureNotification(
|
||||||
|
fn () => Notification::make('refund_failure')->color('danger')->title($response->message)
|
||||||
|
)->sendFailureNotification();
|
||||||
|
|
||||||
|
throw new Halt;
|
||||||
|
}
|
||||||
|
|
||||||
|
$action->success();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
private function refundCapableDriverLabels(): array
|
||||||
|
{
|
||||||
|
$registry = app(PaymentDriverRegistry::class);
|
||||||
|
|
||||||
|
$labels = [];
|
||||||
|
|
||||||
|
foreach ($registry->all() as $key => $driverClass) {
|
||||||
|
if (app($driverClass) instanceof SupportsRefunds) {
|
||||||
|
$labels[$key] = $registry->label($key) ?? $key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function driverKeyForTransaction(mixed $transactionId): ?string
|
||||||
|
{
|
||||||
|
if (blank($transactionId)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$transaction = Transaction::find($transactionId);
|
||||||
|
|
||||||
|
if (! $transaction instanceof CoreTransaction) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return app(TransactionDriverAdapter::class)->driverKeyFor($transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function readProtectedProperty(object $object, string $property): mixed
|
||||||
|
{
|
||||||
|
$reflected = new ReflectionProperty($object, $property);
|
||||||
|
$reflected->setAccessible(true);
|
||||||
|
|
||||||
|
return $reflected->getValue($object);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps the action's own configured action() closure so that, if it
|
||||||
|
* halts (Lunar's closures throw via $action->halt() to signal failure —
|
||||||
|
* see this class's own docblock for why that alone never sends the
|
||||||
|
* notification queued via failureNotification()), we send that
|
||||||
|
* notification ourselves before letting the Halt continue propagating
|
||||||
|
* (still needed — it's what stops callMountedAction() from treating
|
||||||
|
* this as a success and closing the modal/committing the DB transaction).
|
||||||
|
*
|
||||||
|
* $this->evaluate() (not a plain call) matches exactly how Action::call()
|
||||||
|
* itself invokes the closure — Lunar's closures type-hint $data/$record/
|
||||||
|
* $action and rely on Filament's own container-style parameter
|
||||||
|
* resolution, not positional arguments.
|
||||||
|
*/
|
||||||
|
private function fixFailureNotification(Action $action): Action
|
||||||
|
{
|
||||||
|
$originalAction = $action->getActionFunction();
|
||||||
|
|
||||||
|
if ($originalAction === null) {
|
||||||
|
return $action;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $action->action(function (array $arguments) use ($action, $originalAction) {
|
||||||
|
try {
|
||||||
|
return $action->evaluate($originalAction, $arguments);
|
||||||
|
} catch (Halt $exception) {
|
||||||
|
$action->sendFailureNotification();
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Order\Filament\Extensions;
|
||||||
|
|
||||||
|
use Filament\Infolists\Components\RepeatableEntry;
|
||||||
|
use Lunar\Admin\Support\Extending\ViewPageExtension;
|
||||||
|
use Modules\Core\Order\Filament\Infolists\TransactionEntry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Swaps Lunar\Admin\Support\Infolists\Components\Transaction for our own
|
||||||
|
* TransactionEntry in the order page's transactions list — same component,
|
||||||
|
* different Blade view, so a Transaction.meta['notes'] value (written by
|
||||||
|
* a manual/attested driver like Payment\Drivers\BankTransferPaymentDriver)
|
||||||
|
* actually renders somewhere, instead of only the notes column Lunar's own
|
||||||
|
* view reads (see TransactionEntry's own docblock for why that column is
|
||||||
|
* usually empty for a successful manual payment/refund).
|
||||||
|
*
|
||||||
|
* Uses the extendTransactionsRepeatableEntry hook ManageOrder's own
|
||||||
|
* DisplaysTransactions trait already calls
|
||||||
|
* (getTransactionsRepeatableEntry() → callStaticLunarHook(
|
||||||
|
* 'extendTransactionsRepeatableEntry', ...)) — a class/component swap via
|
||||||
|
* a Lunar-provided hook, the same category of extension already used
|
||||||
|
* throughout CorePlugin, not a Blade view-path override.
|
||||||
|
*/
|
||||||
|
class OrderTransactionsExtension extends ViewPageExtension
|
||||||
|
{
|
||||||
|
public function extendTransactionsRepeatableEntry(RepeatableEntry $entry): RepeatableEntry
|
||||||
|
{
|
||||||
|
return $entry->schema([
|
||||||
|
TransactionEntry::make('transaction_detail'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Order\Filament\Infolists;
|
||||||
|
|
||||||
|
use Lunar\Admin\Support\Infolists\Components\Transaction as LunarTransactionEntry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same component as Lunar's own Transaction infolist entry — only the
|
||||||
|
* Blade view differs, to also show Transaction.meta['notes'] (what
|
||||||
|
* Payment\Drivers\BankTransferPaymentDriver and any other manual/attested
|
||||||
|
* driver write a staff-entered note into — see that driver's own
|
||||||
|
* docblock) when the notes column itself is empty. The notes column is
|
||||||
|
* populated by Order\Services\TransactionRecorder from
|
||||||
|
* PaymentResult::$failureReason, which is only ever set on a FAILED
|
||||||
|
* result — a successful manual payment/refund's note would otherwise be
|
||||||
|
* recorded (Transaction.meta) but never shown anywhere in the admin
|
||||||
|
* panel, since Lunar's own view only ever reads the notes column.
|
||||||
|
*
|
||||||
|
* Registered in place of Lunar's own Transaction component via
|
||||||
|
* Order\Filament\Extensions\OrderTransactionsExtension's
|
||||||
|
* extendTransactionsRepeatableEntry() hook (see that class), not a
|
||||||
|
* view-path override — this is the same "swap the concrete
|
||||||
|
* class/component" pattern already used throughout CorePlugin
|
||||||
|
* (LunarPanel::extensions()), rather than shadowing Lunar's Blade file
|
||||||
|
* from underneath it.
|
||||||
|
*/
|
||||||
|
class TransactionEntry extends LunarTransactionEntry
|
||||||
|
{
|
||||||
|
protected string $view = 'core::order.infolists.transaction';
|
||||||
|
}
|
||||||
@@ -7,13 +7,17 @@ use Lunar\Models\Order;
|
|||||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||||
use Modules\Core\Payment\Events\PaymentAuthorized;
|
use Modules\Core\Payment\Events\PaymentAuthorized;
|
||||||
use Modules\Core\Payment\Events\PaymentCaptured;
|
use Modules\Core\Payment\Events\PaymentCaptured;
|
||||||
|
use Modules\Core\Payment\Events\PaymentRefunded;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodCache;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The only place an Order's status column is written in reaction to a
|
* The only place an Order's status column is written in reaction to a
|
||||||
* payment outcome. Registered against BOTH PaymentCaptured and
|
* payment outcome. Registered against PaymentCaptured, PaymentAuthorized,
|
||||||
* PaymentAuthorized (see OrderServiceProvider) — same handler either way,
|
* AND PaymentRefunded (see OrderServiceProvider) — same handler for all
|
||||||
* since both carry the same {type, result, context} shape and only differ
|
* three, differing only in which PaymentMethod column decides the
|
||||||
* in which config key decides the resulting status.
|
* resulting status and, for a refund, which PaymentMethod row that even
|
||||||
|
* is (see resolvePaymentMethod()).
|
||||||
*
|
*
|
||||||
* Reads $event->context['order_id'] to find which Order this outcome
|
* Reads $event->context['order_id'] to find which Order this outcome
|
||||||
* belongs to — Payment has no concept of an Order, so this is the one
|
* belongs to — Payment has no concept of an Order, so this is the one
|
||||||
@@ -28,11 +32,19 @@ use Modules\Core\Payment\Events\PaymentCaptured;
|
|||||||
*
|
*
|
||||||
* Dispatches Checkout\Events\OrderPlaced itself, once placed_at is set —
|
* Dispatches Checkout\Events\OrderPlaced itself, once placed_at is set —
|
||||||
* see that event's own docblock for why this, not CheckoutService, is now
|
* see that event's own docblock for why this, not CheckoutService, is now
|
||||||
* the dispatch point.
|
* the dispatch point. Never fires from the PaymentRefunded path — a
|
||||||
|
* refund can only ever happen after an order was already placed.
|
||||||
|
*
|
||||||
|
* Deliberately does NOT react to PaymentVoided — see PaymentMethod's own
|
||||||
|
* docblock for why there's no void_status column at all yet.
|
||||||
*/
|
*/
|
||||||
class ApplyResolvedPaymentStatus
|
class ApplyResolvedPaymentStatus
|
||||||
{
|
{
|
||||||
public function handle(PaymentCaptured|PaymentAuthorized $event): void
|
public function __construct(
|
||||||
|
private readonly PaymentMethodCache $paymentMethods,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function handle(PaymentCaptured|PaymentAuthorized|PaymentRefunded $event): void
|
||||||
{
|
{
|
||||||
$orderId = $event->context['order_id'] ?? null;
|
$orderId = $event->context['order_id'] ?? null;
|
||||||
|
|
||||||
@@ -42,8 +54,13 @@ class ApplyResolvedPaymentStatus
|
|||||||
|
|
||||||
$order = Order::findOrFail($orderId);
|
$order = Order::findOrFail($orderId);
|
||||||
|
|
||||||
$configKey = $event instanceof PaymentCaptured ? 'captured_status' : 'authorized_status';
|
$method = $this->resolvePaymentMethod($event, $order);
|
||||||
$status = config("lunar.payments.types.{$event->type}.{$configKey}");
|
$column = match (true) {
|
||||||
|
$event instanceof PaymentCaptured => 'captured_status',
|
||||||
|
$event instanceof PaymentAuthorized => 'authorized_status',
|
||||||
|
$event instanceof PaymentRefunded => 'refunded_status',
|
||||||
|
};
|
||||||
|
$status = $method?->{$column};
|
||||||
|
|
||||||
if ($status === null) {
|
if ($status === null) {
|
||||||
return;
|
return;
|
||||||
@@ -56,8 +73,40 @@ class ApplyResolvedPaymentStatus
|
|||||||
'placed_at' => $order->placed_at ?? now(),
|
'placed_at' => $order->placed_at ?? now(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (! $wasPlaced) {
|
if (! $wasPlaced && ! $event instanceof PaymentRefunded) {
|
||||||
Event::dispatch(new OrderPlaced($order));
|
Event::dispatch(new OrderPlaced($order));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PaymentCaptured/PaymentAuthorized carry $event->type as the
|
||||||
|
* PaymentMethod.type that was actually charged — a direct lookup.
|
||||||
|
*
|
||||||
|
* PaymentRefunded's $event->type is the REFUND driver's own registry
|
||||||
|
* key (e.g. 'bank-transfer' — see BankTransferPaymentDriver::refund()),
|
||||||
|
* which may not correspond to any PaymentMethod row at all when the
|
||||||
|
* admin refunded through a different driver than the one that took
|
||||||
|
* the original payment (Payment\Support\TransactionDriverAdapter::
|
||||||
|
* refundVia()). refunded_status is a business decision about the
|
||||||
|
* ORIGINAL payment method, not the refund mechanism, so this instead
|
||||||
|
* finds the order's earliest successful capture/intent transaction —
|
||||||
|
* the actual payment the refund is reversing — and resolves that
|
||||||
|
* transaction's own driver (a real PaymentMethod.type) instead.
|
||||||
|
*/
|
||||||
|
private function resolvePaymentMethod(PaymentCaptured|PaymentAuthorized|PaymentRefunded $event, Order $order): ?PaymentMethod
|
||||||
|
{
|
||||||
|
if (! $event instanceof PaymentRefunded) {
|
||||||
|
return $this->paymentMethods->all()->firstWhere('type', $event->type);
|
||||||
|
}
|
||||||
|
|
||||||
|
$originalType = $order->transactions()
|
||||||
|
->whereIn('type', ['capture', 'intent'])
|
||||||
|
->where('success', true)
|
||||||
|
->oldest('created_at')
|
||||||
|
->value('driver');
|
||||||
|
|
||||||
|
return $originalType !== null
|
||||||
|
? $this->paymentMethods->all()->firstWhere('type', $originalType)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Drivers;
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Lunar\DataTypes\Price;
|
||||||
|
use Modules\Core\Payment\Contracts\Configurable;
|
||||||
|
use Modules\Core\Payment\Contracts\SupportsPay;
|
||||||
|
use Modules\Core\Payment\Contracts\SupportsRefunds;
|
||||||
|
use Modules\Core\Payment\DTOs\PaymentResult;
|
||||||
|
use Modules\Core\Payment\Enums\PaymentResultStatus;
|
||||||
|
use Modules\Core\Payment\Events\PaymentCaptured;
|
||||||
|
use Modules\Core\Payment\Events\PaymentRefunded;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual/attested, same trust model as OfflinePaymentDriver — there is no
|
||||||
|
* bank API to call, so both pay() and refund() decide success immediately
|
||||||
|
* on a staff member's say-so (they've already sent/received the wire
|
||||||
|
* outside the system). Distinct from OfflinePaymentDriver in intent: this
|
||||||
|
* exists so a payment taken through a DIFFERENT method (e.g.
|
||||||
|
* cash-on-delivery) can still be REFUNDED via bank transfer — an admin
|
||||||
|
* chooses this driver explicitly in the refund action, independent of
|
||||||
|
* which driver the original payment went through (see
|
||||||
|
* Payment\Support\TransactionDriverAdapter::refundVia() and
|
||||||
|
* Order\Filament\Extensions\OrderRefundActionsExtension). pay() exists so
|
||||||
|
* the same driver also covers receiving a payment by bank transfer, but
|
||||||
|
* the admin UI for that (bank reference, notes, proof-of-transfer upload)
|
||||||
|
* is deliberately not built yet — see the follow-up work tracked from this
|
||||||
|
* session; pay() itself is complete and usable via the registry today.
|
||||||
|
*
|
||||||
|
* $reference is generated here for the same reason as OfflinePaymentDriver's
|
||||||
|
* pay(): there is no gateway to hand one back. 'notes' in $context (not
|
||||||
|
* $data — refund() has no $data parameter) is folded into
|
||||||
|
* PaymentResult::$meta, which Order\Services\TransactionRecorder::record()
|
||||||
|
* already writes straight into Transaction.meta with no extra plumbing.
|
||||||
|
*/
|
||||||
|
class BankTransferPaymentDriver implements Configurable, SupportsPay, SupportsRefunds
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Always true — no external dependency to be missing.
|
||||||
|
*/
|
||||||
|
public function isConfigured(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pay(string $type, Price $amount, array $data = [], array $context = []): PaymentResult
|
||||||
|
{
|
||||||
|
$result = new PaymentResult(
|
||||||
|
status: PaymentResultStatus::Succeeded,
|
||||||
|
reference: 'bank-transfer-'.Str::uuid(),
|
||||||
|
amount: $amount,
|
||||||
|
meta: array_filter(['notes' => $data['notes'] ?? null]),
|
||||||
|
);
|
||||||
|
|
||||||
|
PaymentCaptured::dispatch($type, $result, $context);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function refund(string $reference, Price $amount, array $context = []): PaymentResult
|
||||||
|
{
|
||||||
|
$result = new PaymentResult(
|
||||||
|
status: PaymentResultStatus::Succeeded,
|
||||||
|
reference: 'bank-transfer-'.Str::uuid(),
|
||||||
|
amount: $amount,
|
||||||
|
meta: array_filter(['notes' => $context['notes'] ?? null]),
|
||||||
|
);
|
||||||
|
|
||||||
|
PaymentRefunded::dispatch('bank-transfer', $result, $context);
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Events;
|
||||||
|
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
|
||||||
|
class PaymentMethodCreated
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public readonly PaymentMethod $method,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Events;
|
||||||
|
|
||||||
|
class PaymentMethodDeleted
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $method Snapshot of the deleted row —
|
||||||
|
* already gone from the database by dispatch time, so this can't be
|
||||||
|
* a fresh PaymentMethod model instance.
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly array $method,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Events;
|
||||||
|
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
|
||||||
|
class PaymentMethodUpdated
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $old Snapshot of the changed attributes
|
||||||
|
* before the update.
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly PaymentMethod $method,
|
||||||
|
public readonly array $old,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Events;
|
||||||
|
|
||||||
|
class PaymentMethodsReordered
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, int> $ids PaymentMethod ids, in their new order —
|
||||||
|
* the same array Filament's own reorderTable() already wrote to the
|
||||||
|
* database directly (bulk SQL, not PaymentMethodService::update() —
|
||||||
|
* see PaymentMethodResource's own docblock for why this is the one
|
||||||
|
* PaymentMethod write that doesn't go through the service).
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly array $ids,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -3,21 +3,57 @@
|
|||||||
namespace Modules\Core\Payment\Filament\Resources;
|
namespace Modules\Core\Payment\Filament\Resources;
|
||||||
|
|
||||||
use Filament\Actions\Action;
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
use Filament\Forms\Components\TextInput;
|
use Filament\Forms\Components\TextInput;
|
||||||
use Filament\Resources\Resource;
|
use Filament\Resources\Resource;
|
||||||
|
use Filament\Schemas\Components\Component;
|
||||||
|
use Filament\Schemas\Components\Utilities\Get;
|
||||||
|
use Filament\Tables\Columns\IconColumn;
|
||||||
use Filament\Tables\Columns\TextColumn;
|
use Filament\Tables\Columns\TextColumn;
|
||||||
use Filament\Tables\Columns\ToggleColumn;
|
use Filament\Tables\Columns\ToggleColumn;
|
||||||
use Filament\Tables\Table;
|
use Filament\Tables\Table;
|
||||||
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodsReordered;
|
||||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages\ListPaymentMethods;
|
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages\ListPaymentMethods;
|
||||||
use Modules\Core\Payment\Models\PaymentMethod;
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodCache;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One row per payment type key (config('lunar.payments.types')), seeded by
|
* The DB-instance layer for Payment (see docs/payments.md) — admin
|
||||||
* InstallLunarCommand — never created/deleted here, only edited. `enabled`
|
* creatable/deletable, same as Lunar's own ShippingMethodResource. A row's
|
||||||
* toggles inline; `data.fee` (currently the only type-specific setting, for
|
* `driver` is picked from a Select populated by
|
||||||
* cash-on-delivery's flat surcharge — see ApplyCashOnDeliveryFee) is edited
|
* PaymentDriverRegistry::labels() (mirrors Modules\Core\Shipping\
|
||||||
* via a modal action rather than a dedicated form field, since not every
|
* Extensions\ShippingMethodResourceExtension::driverSelect()'s use of
|
||||||
* type has the same data keys.
|
* Shipping::getSupportedDrivers()), not a hardcoded options list, and
|
||||||
|
* never the raw driver class name — a third-party driver registered from
|
||||||
|
* its own package's service provider shows up here with no change to
|
||||||
|
* this class.
|
||||||
|
*
|
||||||
|
* Every write goes through Modules\Core\Payment\Services\
|
||||||
|
* PaymentMethodService — create/edit/delete/the enabled toggle all call
|
||||||
|
* it, not PaymentMethod::create()/update()/delete() directly, so cache
|
||||||
|
* invalidation and event dispatch happen in one place. The ONE exception
|
||||||
|
* is drag-to-reorder: Filament's own reorderTable() always writes the new
|
||||||
|
* `position` values via its own raw bulk SQL query before our
|
||||||
|
* afterReordering() hook ever runs — there is no seam to route that
|
||||||
|
* specific write through the service (short of disabling drag-reorder
|
||||||
|
* entirely and rebuilding it from scratch), so that hook only forgets the
|
||||||
|
* cache and dispatches PaymentMethodsReordered; the data itself is
|
||||||
|
* already correct in the database by the time it fires.
|
||||||
|
*
|
||||||
|
* `driver_missing_at` (set by the `boboko:payment:sync-drivers` command
|
||||||
|
* when a row's driver no longer resolves) is surfaced as its own table
|
||||||
|
* column, deliberately distinct from `enabled` — an admin needs to tell
|
||||||
|
* "I turned this off" apart from "the driver code was removed" at a
|
||||||
|
* glance, not have both look like the same disabled state.
|
||||||
|
*
|
||||||
|
* `authorized_status` only appears in the form when `capture_mode` is
|
||||||
|
* "Hold now, charge later" — it's simply unreachable for a "Charge
|
||||||
|
* immediately" method (that mode only ever produces PaymentCaptured,
|
||||||
|
* never PaymentAuthorized), so showing it unconditionally would just be
|
||||||
|
* a confusing, always-irrelevant field for most methods.
|
||||||
*/
|
*/
|
||||||
class PaymentMethodResource extends Resource
|
class PaymentMethodResource extends Resource
|
||||||
{
|
{
|
||||||
@@ -35,10 +71,31 @@ class PaymentMethodResource extends Resource
|
|||||||
{
|
{
|
||||||
return $table
|
return $table
|
||||||
->columns([
|
->columns([
|
||||||
|
TextColumn::make('position')
|
||||||
|
->label('Order')
|
||||||
|
->sortable(),
|
||||||
|
TextColumn::make('name')
|
||||||
|
->label('Name')
|
||||||
|
->searchable(),
|
||||||
TextColumn::make('type')
|
TextColumn::make('type')
|
||||||
->label('Type'),
|
->label('Type'),
|
||||||
|
TextColumn::make('driver')
|
||||||
|
->label('Driver')
|
||||||
|
->formatStateUsing(fn (?string $state) => static::driverLabel($state)),
|
||||||
|
IconColumn::make('driver_missing_at')
|
||||||
|
->label('Driver status')
|
||||||
|
->boolean()
|
||||||
|
->trueIcon('heroicon-o-exclamation-triangle')
|
||||||
|
->falseIcon('heroicon-o-check-circle')
|
||||||
|
->trueColor('danger')
|
||||||
|
->falseColor('success')
|
||||||
|
->tooltip(fn (PaymentMethod $record) => $record->driver_missing_at
|
||||||
|
? 'Driver not found as of '.$record->driver_missing_at->diffForHumans()
|
||||||
|
: 'Driver resolves correctly'),
|
||||||
ToggleColumn::make('enabled')
|
ToggleColumn::make('enabled')
|
||||||
->label('Enabled'),
|
->label('Enabled')
|
||||||
|
->updateStateUsing(fn (PaymentMethod $record, $state) => app(PaymentMethodService::class)
|
||||||
|
->update($record, ['enabled' => $state])),
|
||||||
TextColumn::make('data.fee')
|
TextColumn::make('data.fee')
|
||||||
->label('Fee')
|
->label('Fee')
|
||||||
->formatStateUsing(fn (?int $state) => $state
|
->formatStateUsing(fn (?int $state) => $state
|
||||||
@@ -48,10 +105,110 @@ class PaymentMethodResource extends Resource
|
|||||||
->label('Last updated')
|
->label('Last updated')
|
||||||
->dateTime(),
|
->dateTime(),
|
||||||
])
|
])
|
||||||
|
->reorderable('position')
|
||||||
|
->afterReordering(function (array $order) {
|
||||||
|
app(PaymentMethodCache::class)->forget();
|
||||||
|
|
||||||
|
Event::dispatch(new PaymentMethodsReordered(array_map('intval', array_values($order))));
|
||||||
|
})
|
||||||
->recordActions([
|
->recordActions([
|
||||||
|
static::editAction(),
|
||||||
static::editFeeAction(),
|
static::editFeeAction(),
|
||||||
|
static::deleteAction(),
|
||||||
])
|
])
|
||||||
->defaultSort('type');
|
->defaultSort('position');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<Component>
|
||||||
|
*/
|
||||||
|
public static function getFormComponents(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
TextInput::make('name')
|
||||||
|
->label('Name')
|
||||||
|
->required()
|
||||||
|
->maxLength(255),
|
||||||
|
TextInput::make('type')
|
||||||
|
->label('Type')
|
||||||
|
->helperText('Machine-facing slug — stored on the cart/order, used by other code to identify this method. Cannot be changed once orders reference it.')
|
||||||
|
->required()
|
||||||
|
->unique(ignoreRecord: true)
|
||||||
|
->maxLength(255),
|
||||||
|
static::getDriverFormComponent(),
|
||||||
|
Select::make('capture_mode')
|
||||||
|
->label('Capture mode')
|
||||||
|
->helperText('Whether checkout charges immediately, or places a hold to settle later.')
|
||||||
|
->options([
|
||||||
|
'pay' => 'Charge immediately',
|
||||||
|
'authorize' => 'Hold now, charge later',
|
||||||
|
])
|
||||||
|
->default('pay')
|
||||||
|
->live()
|
||||||
|
->required(),
|
||||||
|
static::getOrderStatusSelect('captured_status', 'Order status once paid')
|
||||||
|
->helperText('Applied the moment a payment is fully charged.'),
|
||||||
|
static::getOrderStatusSelect('authorized_status', 'Order status once held')
|
||||||
|
->helperText('Applied the moment a hold is placed, before it\'s charged.')
|
||||||
|
->visible(fn (Get $get) => $get('capture_mode') === 'authorize'),
|
||||||
|
static::getOrderStatusSelect('refunded_status', 'Order status once refunded')
|
||||||
|
->helperText('Applied when a payment taken through this method is refunded — even if the refund itself is processed through a different method.'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getDriverFormComponent(): Component
|
||||||
|
{
|
||||||
|
return Select::make('driver')
|
||||||
|
->label('Driver')
|
||||||
|
->options(fn () => app(PaymentDriverRegistry::class)->labels())
|
||||||
|
->required();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lunar's own Order::status is a plain, admin-extensible string
|
||||||
|
* (config('lunar.orders.statuses')) rather than a fixed enum —
|
||||||
|
* deliberately so a store can add its own custom status without a
|
||||||
|
* code change (see docs/payments.md). This Select still reads from
|
||||||
|
* that same open-ended list, just so an admin picks a real status
|
||||||
|
* instead of typing a slug from memory.
|
||||||
|
*/
|
||||||
|
private static function getOrderStatusSelect(string $name, string $label): Select
|
||||||
|
{
|
||||||
|
return Select::make($name)
|
||||||
|
->label($label)
|
||||||
|
->options(collect(config('lunar.orders.statuses', []))
|
||||||
|
->map(fn (array $status) => $status['label'] ?? $status)
|
||||||
|
->all())
|
||||||
|
->native(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getPages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'index' => ListPaymentMethods::route('/'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function canCreate(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function canDelete($record = null): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function editAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('edit')
|
||||||
|
->label('Edit')
|
||||||
|
->icon('heroicon-o-pencil-square')
|
||||||
|
->schema(static::getFormComponents())
|
||||||
|
->fillForm(fn (PaymentMethod $record) => $record->only([
|
||||||
|
'name', 'type', 'driver', 'capture_mode', 'captured_status', 'authorized_status', 'refunded_status',
|
||||||
|
]))
|
||||||
|
->action(fn (PaymentMethod $record, array $data) => app(PaymentMethodService::class)->update($record, $data));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,7 +233,7 @@ class PaymentMethodResource extends Resource
|
|||||||
'fee' => filled($record->data['fee'] ?? null) ? $record->data['fee'] / 100 : null,
|
'fee' => filled($record->data['fee'] ?? null) ? $record->data['fee'] / 100 : null,
|
||||||
])
|
])
|
||||||
->action(function (PaymentMethod $record, array $data) {
|
->action(function (PaymentMethod $record, array $data) {
|
||||||
$record->update([
|
app(PaymentMethodService::class)->update($record, [
|
||||||
'data' => [
|
'data' => [
|
||||||
...$record->data->toArray(),
|
...$record->data->toArray(),
|
||||||
'fee' => filled($data['fee']) ? (int) round($data['fee'] * 100) : null,
|
'fee' => filled($data['fee']) ? (int) round($data['fee'] * 100) : null,
|
||||||
@@ -85,20 +242,22 @@ class PaymentMethodResource extends Resource
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getPages(): array
|
private static function deleteAction(): Action
|
||||||
{
|
{
|
||||||
return [
|
return Action::make('delete')
|
||||||
'index' => ListPaymentMethods::route('/'),
|
->label('Delete')
|
||||||
];
|
->icon('heroicon-o-trash')
|
||||||
|
->color('danger')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->action(fn (PaymentMethod $record) => app(PaymentMethodService::class)->delete($record));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function canCreate(): bool
|
private static function driverLabel(?string $key): string
|
||||||
{
|
{
|
||||||
return false;
|
if ($key === null) {
|
||||||
}
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
public static function canDelete($record = null): bool
|
return app(PaymentDriverRegistry::class)->label($key) ?? $key;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,31 @@
|
|||||||
|
|
||||||
namespace Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages;
|
namespace Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages;
|
||||||
|
|
||||||
|
use Filament\Actions;
|
||||||
use Filament\Resources\Pages\ListRecords;
|
use Filament\Resources\Pages\ListRecords;
|
||||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodService;
|
||||||
|
|
||||||
class ListPaymentMethods extends ListRecords
|
class ListPaymentMethods extends ListRecords
|
||||||
{
|
{
|
||||||
protected static string $resource = PaymentMethodResource::class;
|
protected static string $resource = PaymentMethodResource::class;
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Actions\CreateAction::make()
|
||||||
|
->schema(PaymentMethodResource::getFormComponents())
|
||||||
|
->fillForm(fn () => [
|
||||||
|
'position' => (PaymentMethod::max('position') ?? 0) + 1,
|
||||||
|
'enabled' => false,
|
||||||
|
'data' => [],
|
||||||
|
])
|
||||||
|
// Every PaymentMethod write goes through PaymentMethodService
|
||||||
|
// — see PaymentMethodResource's own docblock — so this
|
||||||
|
// replaces CreateAction's default $model::create($data), not
|
||||||
|
// just the form/fill behavior above.
|
||||||
|
->using(fn (array $data) => app(PaymentMethodService::class)->create($data)),
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use Stripe\Webhook;
|
|||||||
* anywhere reusable, it only gates the request through.
|
* anywhere reusable, it only gates the request through.
|
||||||
*
|
*
|
||||||
* Resolves the driver directly by class, not via
|
* Resolves the driver directly by class, not via
|
||||||
* Modules\Core\Payment\Services\PaymentDriverResolver — this endpoint is
|
* Modules\Core\Payment\Services\PaymentDriverRegistry — this endpoint is
|
||||||
* inherently Stripe-specific (Stripe's own webhook payload carries no
|
* inherently Stripe-specific (Stripe's own webhook payload carries no
|
||||||
* boboko payment-type key, only its own payment_intent id), and
|
* boboko payment-type key, only its own payment_intent id), and
|
||||||
* StripePaymentDriver::handleCallback() already recovers $type itself
|
* StripePaymentDriver::handleCallback() already recovers $type itself
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Listeners;
|
||||||
|
|
||||||
|
use Modules\Core\Logging\ActivityLogService;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodCreated;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodDeleted;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodUpdated;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same pattern as Localization\Listeners\LogTranslationActivity — routes
|
||||||
|
* PaymentMethodService's own events through the existing
|
||||||
|
* Logging\ActivityLogService instead of PaymentMethod separately opting
|
||||||
|
* into Lunar\Base\Traits\LogsActivity (Spatie's generic model-observer
|
||||||
|
* logging): PaymentMethodUpdated::$old and PaymentMethodDeleted::$method
|
||||||
|
* already carry richer, deliberate before/after context than Eloquent's
|
||||||
|
* own dirty-attribute diffing would reconstruct on its own.
|
||||||
|
*
|
||||||
|
* PaymentMethodDeleted's snapshot is a plain array (the row is already
|
||||||
|
* gone from the database by dispatch time — see that event's own
|
||||||
|
* docblock), so performedOn() gets an unsaved PaymentMethod instance
|
||||||
|
* built from it purely to carry the right subject_type/id, not a real
|
||||||
|
* persisted model.
|
||||||
|
*
|
||||||
|
* PaymentMethodsReordered is deliberately NOT logged here — it's a
|
||||||
|
* multi-row position change (ActivityLogService's methods all take one
|
||||||
|
* Model $subject) for a low-stakes, purely-cosmetic setting, not worth
|
||||||
|
* forcing into a one-subject shape or adding a new method to the shared
|
||||||
|
* service for.
|
||||||
|
*/
|
||||||
|
class LogPaymentMethodActivity
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ActivityLogService $activityLog,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function handleCreated(PaymentMethodCreated $event): void
|
||||||
|
{
|
||||||
|
$this->activityLog->created($event->method, $event->method->getAttributes());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handleUpdated(PaymentMethodUpdated $event): void
|
||||||
|
{
|
||||||
|
$this->activityLog->updated(
|
||||||
|
$event->method,
|
||||||
|
$event->old,
|
||||||
|
$event->method->only(array_keys($event->old)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handleDeleted(PaymentMethodDeleted $event): void
|
||||||
|
{
|
||||||
|
$subject = (new PaymentMethod)->forceFill($event->method);
|
||||||
|
$subject->exists = true;
|
||||||
|
$subject->id = $event->method['id'];
|
||||||
|
|
||||||
|
$this->activityLog->deleted($subject, $event->method);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Models;
|
||||||
|
|
||||||
|
use Lunar\Models\Transaction;
|
||||||
|
use Modules\Core\Payment\Support\TransactionDriverAdapter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registered via Lunar\Facades\ModelManifest::replace(Lunar\Models\
|
||||||
|
* Contracts\Transaction::class, self::class) in PaymentServiceProvider —
|
||||||
|
* the same contract-swap mechanism this codebase already uses for
|
||||||
|
* Customer/Staff. Every place Lunar's own code resolves a transaction via
|
||||||
|
* Transaction::modelClass() (which reads this replacement, see
|
||||||
|
* Lunar\Base\Traits\HasModelExtending::modelClass()) — including
|
||||||
|
* Order::transactions()'s own hasMany(Transaction::modelClass()) relation
|
||||||
|
* — gets an instance of THIS class instead of the vendor's own
|
||||||
|
* Lunar\Models\Transaction. No override anywhere else is needed: this is
|
||||||
|
* the one seam that makes $order->transactions, and everything the admin
|
||||||
|
* panel's refund/capture actions call on one of those rows, silently run
|
||||||
|
* through our own system.
|
||||||
|
*
|
||||||
|
* Only driver() is overridden — refund()/capture()/paymentChecks() on the
|
||||||
|
* parent class all just call driver()->{method}(), so replacing what
|
||||||
|
* driver() returns is the entire fix (see TransactionDriverAdapter).
|
||||||
|
*/
|
||||||
|
class CoreTransaction extends Transaction
|
||||||
|
{
|
||||||
|
public function driver(): TransactionDriverAdapter
|
||||||
|
{
|
||||||
|
return app(TransactionDriverAdapter::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,17 +6,35 @@ use Illuminate\Database\Eloquent\Casts\AsArrayObject;
|
|||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin-editable settings for one payment type key (matching a key in
|
* A merchant-configured payment method — the DB-instance layer, admin
|
||||||
* config('lunar.payments.types')) — enabled/disabled, and whatever type-
|
* creatable/deletable, same split Modules\Core\Shipping's own
|
||||||
* specific data it needs (starts with 'fee' for cash-on-delivery's flat
|
* shipping_methods table already has (see docs/payments.md):
|
||||||
* surcharge). Mirrors Lunar's own Discount model: a single jsonb 'data'
|
* - type: unique, machine-facing slug (Cart::meta['payment_method'],
|
||||||
* column holding keyed settings, rather than a fixed column per setting or
|
* ApplyCashOnDeliveryFee's lookup key, every Payment event's $type).
|
||||||
* a separate conditions table — new settings are a code change (a new key
|
* - name: admin-facing label.
|
||||||
* read from data), not a migration.
|
* - driver: the Modules\Core\Payment\Services\PaymentDriverRegistry key
|
||||||
*
|
* — NOT the same as `type`, and not unique (two rows can share one
|
||||||
* Seeded once per type by InstallLunarCommand (skip-if-exists, same
|
* driver, e.g. two differently-named offline-style methods).
|
||||||
* idempotent convention as seedStorefrontLabels()) — never auto-created on
|
* - capture_mode: 'pay' or 'authorize' — which SupportsPay/
|
||||||
* read, so a read path stays a pure read.
|
* SupportsAuthorization method CheckoutService::initiatePayment()
|
||||||
|
* calls for this row.
|
||||||
|
* - captured_status / authorized_status / refunded_status: the
|
||||||
|
* Order::status value Modules\Core\Order\Listeners\
|
||||||
|
* ApplyResolvedPaymentStatus applies on a PaymentCaptured/
|
||||||
|
* PaymentAuthorized/PaymentRefunded event. For a refund, this is
|
||||||
|
* always the ORIGINAL payment method's row (the one the customer
|
||||||
|
* actually paid with), never the driver the refund itself was routed
|
||||||
|
* through (Payment\Support\TransactionDriverAdapter::refundVia() may
|
||||||
|
* use a different one entirely — e.g. a cash-on-delivery order
|
||||||
|
* refunded via a Bank Transfer driver with no PaymentMethod row of
|
||||||
|
* its own) — see that listener's own docblock.
|
||||||
|
* - position: admin-controlled display/checkout order.
|
||||||
|
* - driver_missing_at: set by `payment:sync-drivers` when `driver` no
|
||||||
|
* longer resolves via the registry — separate from `enabled`, so a
|
||||||
|
* driver vanishing (a deploy removed it) is never confused with an
|
||||||
|
* admin's own manual toggle.
|
||||||
|
* - data: jsonb, driver-specific settings that don't warrant their own
|
||||||
|
* column (starts with 'fee', the offline flat surcharge).
|
||||||
*/
|
*/
|
||||||
class PaymentMethod extends Model
|
class PaymentMethod extends Model
|
||||||
{
|
{
|
||||||
@@ -24,6 +42,8 @@ class PaymentMethod extends Model
|
|||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
'enabled' => 'boolean',
|
'enabled' => 'boolean',
|
||||||
|
'position' => 'integer',
|
||||||
|
'driver_missing_at' => 'datetime',
|
||||||
'data' => AsArrayObject::class,
|
'data' => AsArrayObject::class,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Services;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which payment driver CLASSES exist this deploy — the code-registry layer,
|
||||||
|
* mirroring Lunar\Shipping\Managers\ShippingManager's own built-in-methods
|
||||||
|
* + Manager::extend() pattern, but purpose-built rather than extending
|
||||||
|
* Illuminate\Support\Manager: Manager's create{X}Driver() convention fits
|
||||||
|
* a uniform one-interface-per-driver contract (ShippingRateInterface); a
|
||||||
|
* Payment driver instead implements several independent, opt-in capability
|
||||||
|
* interfaces at once (Configurable, SupportsPay, SupportsAuthorization,
|
||||||
|
* ...), so there's no single "the" method to generate per driver.
|
||||||
|
*
|
||||||
|
* Deliberately knows NOTHING about Modules\Core\Payment\Models\PaymentMethod
|
||||||
|
* or the database — resolve() is a pure "does this key still exist"
|
||||||
|
* lookup. Whether a resolved driver is administratively enabled, or
|
||||||
|
* reports itself Configurable::isConfigured(), is the DOMAIN's job
|
||||||
|
* (Modules\Core\Checkout\Services\CheckoutService::getPaymentMethods()) —
|
||||||
|
* see docs/payments.md. This split is what lets the identical registry
|
||||||
|
* shape be lifted for a future Invoicing/AntiFraud domain without dragging
|
||||||
|
* Payment-specific concepts along with it.
|
||||||
|
*
|
||||||
|
* Built-in drivers are registered in Modules\Core\Providers\
|
||||||
|
* PaymentServiceProvider::boot() via register(); a consuming app or a
|
||||||
|
* future payment-provider package registers its own the same way, from
|
||||||
|
* its own service provider's boot() — exactly how Shipping::extend() works
|
||||||
|
* for ACS/Box Now (src/Providers/ShippingServiceProvider.php).
|
||||||
|
*/
|
||||||
|
class PaymentDriverRegistry
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
private array $drivers = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
private array $labels = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* $key is the registry key a Modules\Core\Payment\Models\PaymentMethod
|
||||||
|
* row's own `driver` column stores — NOT the same as that row's `type`
|
||||||
|
* (its merchant-facing slug). Two rows can share one driver key (e.g.
|
||||||
|
* both 'cash-on-delivery' and 'cash-in-hand' using the same 'offline'
|
||||||
|
* driver with different type/name/fee).
|
||||||
|
*
|
||||||
|
* $label is a short, human-readable name (e.g. "Stripe", "Offline /
|
||||||
|
* Manual") — this is where that comes from, not $driverClass's own
|
||||||
|
* FQCN. Payment's driver classes implement several independent,
|
||||||
|
* opt-in capability interfaces (Configurable, SupportsPay, ...), none
|
||||||
|
* of which carries a display name the way Lunar\Shipping\Interfaces\
|
||||||
|
* ShippingRateInterface::name() does for every shipping driver — the
|
||||||
|
* registry is the one place that DOES know every driver at once, so
|
||||||
|
* it's the natural (and only) place to also hold this.
|
||||||
|
*/
|
||||||
|
public function register(string $key, string $driverClass, string $label): void
|
||||||
|
{
|
||||||
|
$this->drivers[$key] = $driverClass;
|
||||||
|
$this->labels[$key] = $label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Null if $key was never registered — deliberately non-throwing, same
|
||||||
|
* reasoning the old PaymentDriverResolver already had: a caller
|
||||||
|
* checking availability (or the payment:sync-drivers command checking
|
||||||
|
* every PaymentMethod row) needs "not found" to be a normal, silent
|
||||||
|
* result, not an exception to catch.
|
||||||
|
*/
|
||||||
|
public function resolve(string $key): ?object
|
||||||
|
{
|
||||||
|
$driverClass = $this->drivers[$key] ?? null;
|
||||||
|
|
||||||
|
return $driverClass ? app($driverClass) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every registered key => driver class — what payment:sync-drivers
|
||||||
|
* checks every PaymentMethod row's `driver` column against.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function all(): array
|
||||||
|
{
|
||||||
|
return $this->drivers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every registered key => human-readable label — what a Filament
|
||||||
|
* driver Select populates its options from (mirroring
|
||||||
|
* ShippingMethodResourceExtension::driverSelect()'s use of
|
||||||
|
* Shipping::getSupportedDrivers(), which reads each driver's own
|
||||||
|
* name()) — never the raw class name from all().
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function labels(): array
|
||||||
|
{
|
||||||
|
return $this->labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function label(string $key): ?string
|
||||||
|
{
|
||||||
|
return $this->labels[$key] ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Core\Payment\Services;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves a payment type key (e.g. 'stripe', 'cash-on-delivery') to its
|
|
||||||
* registered driver instance — extracted out of CheckoutService so both it
|
|
||||||
* and anything else needing the same lookup share one implementation
|
|
||||||
* instead of duplicating this config read.
|
|
||||||
*
|
|
||||||
* Returns a plain object, not a shared interface — Payment's own drivers
|
|
||||||
* implement several independent, orthogonal capability interfaces at once
|
|
||||||
* (Configurable, SupportsPay, SupportsAuthorization, ...; see
|
|
||||||
* StripePaymentDriver implementing all six). There is no single common
|
|
||||||
* "PaymentDriver" contract to type this against; a caller checks
|
|
||||||
* `instanceof SupportsPay` / `instanceof SupportsAuthorization` itself,
|
|
||||||
* the same way Payment's own contracts are designed to be consumed.
|
|
||||||
*/
|
|
||||||
class PaymentDriverResolver
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Null if $type has no 'payment_driver' registered in
|
|
||||||
* config('lunar.payments.types.<type>') at all — deliberately
|
|
||||||
* non-throwing so a caller like CheckoutService::getPaymentMethods()
|
|
||||||
* can filter unresolvable types silently rather than treating "not
|
|
||||||
* registered" as an error condition when just checking availability.
|
|
||||||
*/
|
|
||||||
public function resolve(string $type): ?object
|
|
||||||
{
|
|
||||||
$driverClass = config("lunar.payments.types.{$type}.payment_driver");
|
|
||||||
|
|
||||||
return $driverClass ? app($driverClass) : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cached read layer over PaymentMethod — the single source both
|
||||||
|
* Modules\Core\Checkout\Services\CheckoutService (checkout-time
|
||||||
|
* availability) and anything else needing the payment-method list (e.g.
|
||||||
|
* PaymentServiceProvider's Lunar\Facades\Payments shim, order screens
|
||||||
|
* showing a transaction's driver) read from, so the table is fetched once
|
||||||
|
* per cache lifetime rather than once per caller/request. Mirrors
|
||||||
|
* Modules\Core\Localization\Services\LanguageCache's exact shape.
|
||||||
|
*
|
||||||
|
* Cached forever, invalidated via forget() by
|
||||||
|
* Modules\Core\Payment\Observers\FlushPaymentMethodCache on
|
||||||
|
* PaymentMethod::saved()/deleted() — no bespoke Created/Updated/Deleted
|
||||||
|
* event trio needed, unlike LanguageCache's (Language is a Lunar-owned
|
||||||
|
* model reacted to indirectly); PaymentMethod is entirely our own model,
|
||||||
|
* so a plain Eloquent observer is the direct route.
|
||||||
|
*/
|
||||||
|
class PaymentMethodCache
|
||||||
|
{
|
||||||
|
private const CACHE_KEY = 'core.payment.methods';
|
||||||
|
|
||||||
|
public function all(): Collection
|
||||||
|
{
|
||||||
|
return Cache::rememberForever(
|
||||||
|
self::CACHE_KEY,
|
||||||
|
fn () => PaymentMethod::query()->orderBy('position')->get(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function forget(): void
|
||||||
|
{
|
||||||
|
Cache::forget(self::CACHE_KEY);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodCreated;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodDeleted;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodUpdated;
|
||||||
|
use Modules\Core\Payment\Models\PaymentMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The single write (AND read) gateway for PaymentMethod — every Filament
|
||||||
|
* resource/action calls this, not PaymentMethod::create()/update()/delete()
|
||||||
|
* directly, so cache invalidation is one explicit step colocated with the
|
||||||
|
* mutation (not hidden in a model observer) and every admin change to a
|
||||||
|
* payment method dispatches a matching event, the same convention
|
||||||
|
* Modules\Core\Cart\Services\CartService already established for its own
|
||||||
|
* mutating methods.
|
||||||
|
*
|
||||||
|
* list() is what PaymentMethodCache actually reads through — see that
|
||||||
|
* class for why this needs caching at all (Modules\Core\Checkout\
|
||||||
|
* Services\CheckoutService and PaymentServiceProvider's Lunar\Facades\
|
||||||
|
* Payments shim both read the full payment-method list on the hot path).
|
||||||
|
*/
|
||||||
|
class PaymentMethodService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PaymentMethodCache $cache,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Collection<int, PaymentMethod>
|
||||||
|
*/
|
||||||
|
public function list(): Collection
|
||||||
|
{
|
||||||
|
return $this->cache->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
*/
|
||||||
|
public function create(array $data): PaymentMethod
|
||||||
|
{
|
||||||
|
$method = PaymentMethod::create($data);
|
||||||
|
|
||||||
|
$this->cache->forget();
|
||||||
|
|
||||||
|
Event::dispatch(new PaymentMethodCreated($method));
|
||||||
|
|
||||||
|
return $method;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
*/
|
||||||
|
public function update(PaymentMethod $method, array $data): PaymentMethod
|
||||||
|
{
|
||||||
|
$old = $method->only(array_keys($data));
|
||||||
|
|
||||||
|
$method->update($data);
|
||||||
|
|
||||||
|
$this->cache->forget();
|
||||||
|
|
||||||
|
Event::dispatch(new PaymentMethodUpdated($method, $old));
|
||||||
|
|
||||||
|
return $method;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(PaymentMethod $method): void
|
||||||
|
{
|
||||||
|
$snapshot = $method->only([
|
||||||
|
'id', 'type', 'name', 'driver', 'capture_mode',
|
||||||
|
'captured_status', 'authorized_status', 'position', 'enabled',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$method->delete();
|
||||||
|
|
||||||
|
$this->cache->forget();
|
||||||
|
|
||||||
|
Event::dispatch(new PaymentMethodDeleted($snapshot));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Core\Payment\Support;
|
||||||
|
|
||||||
|
use Lunar\Base\DataTransferObjects\PaymentCapture;
|
||||||
|
use Lunar\Base\DataTransferObjects\PaymentChecks;
|
||||||
|
use Lunar\Base\DataTransferObjects\PaymentRefund;
|
||||||
|
use Lunar\DataTypes\Price;
|
||||||
|
use Lunar\Models\Contracts\Transaction;
|
||||||
|
use Modules\Core\Payment\Contracts\SupportsCaptures;
|
||||||
|
use Modules\Core\Payment\Contracts\SupportsRefunds;
|
||||||
|
use Modules\Core\Payment\Enums\PaymentResultStatus;
|
||||||
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
use Modules\Core\Payment\Services\PaymentMethodCache;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What Modules\Core\Payment\Models\CoreTransaction::driver() returns
|
||||||
|
* instead of Lunar\Facades\Payments::driver($this->driver) — the point
|
||||||
|
* where every Lunar-native caller of a transaction's driver (today: the
|
||||||
|
* admin panel's "Refund"/"Capture" header actions on the order page,
|
||||||
|
* ManageOrder::getRefundAction()/getCaptureAction() — see
|
||||||
|
* $transaction->refund()/->capture() in vendor/lunarphp/core/src/Models/
|
||||||
|
* Transaction.php) transparently lands on OUR real payment system instead
|
||||||
|
* of Lunar's own, entirely separate, unused PaymentManager.
|
||||||
|
*
|
||||||
|
* Implements Lunar\Base\PaymentTypeInterface's refund()/capture()/
|
||||||
|
* getPaymentChecks() signatures exactly — each takes the Transaction as
|
||||||
|
* its own first argument (confirmed from vendor/lunarphp/core/src/Models/
|
||||||
|
* Transaction.php: `$this->driver()->refund($this, $amount, $notes)`),
|
||||||
|
* so this class holds no transaction state of its own; CoreTransaction's
|
||||||
|
* driver() can return one shared instance for any transaction.
|
||||||
|
*
|
||||||
|
* $transaction->driver is a Modules\Core\Payment\Models\PaymentMethod.type
|
||||||
|
* value (what Modules\Core\Order\Services\TransactionRecorder writes into
|
||||||
|
* Transaction.driver) — this resolves the REAL registry key from that
|
||||||
|
* type via PaymentMethodCache, then the real driver instance from
|
||||||
|
* PaymentDriverRegistry, so refund()/capture() called here call the
|
||||||
|
* ACTUAL Stripe/etc. driver, never a fake/no-op stand-in. If either
|
||||||
|
* lookup fails (the PaymentMethod row or its driver no longer exists),
|
||||||
|
* refund()/capture() report failure rather than silently doing nothing.
|
||||||
|
*/
|
||||||
|
class TransactionDriverAdapter
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PaymentMethodCache $paymentMethods,
|
||||||
|
private readonly PaymentDriverRegistry $registry,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function refund(Transaction $transaction, int $amount, ?string $notes = null): PaymentRefund
|
||||||
|
{
|
||||||
|
return $this->refundVia($transaction, $this->driverKeyFor($transaction), $amount, $notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The PaymentDriverRegistry key $transaction was originally taken
|
||||||
|
* through — what refund()/capture() resolve against by default, and
|
||||||
|
* what Order\Filament\Extensions\OrderRefundActionsExtension defaults
|
||||||
|
* its "Refund via" driver Select to, before an admin overrides it.
|
||||||
|
*/
|
||||||
|
public function driverKeyFor(Transaction $transaction): ?string
|
||||||
|
{
|
||||||
|
return $this->paymentMethods->all()->firstWhere('type', $transaction->driver)?->driver;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same as refund(), but against an explicitly chosen driver rather than
|
||||||
|
* the one $transaction was originally taken through — e.g. refunding a
|
||||||
|
* cash-on-delivery order via a Bank Transfer driver instead of trying
|
||||||
|
* (and failing) to refund through the offline driver that took the
|
||||||
|
* original payment. $driverKey is a PaymentDriverRegistry key (e.g.
|
||||||
|
* 'bank-transfer'), not a PaymentMethod.type — the two only coincide
|
||||||
|
* when refunding through the transaction's own original driver.
|
||||||
|
*
|
||||||
|
* Called directly by Order\Filament\Extensions\
|
||||||
|
* OrderRefundActionsExtension when the admin picks a different driver
|
||||||
|
* in the refund modal, bypassing Lunar\Models\Transaction::refund()
|
||||||
|
* (whose fixed refund(int $amount, $notes = null) signature has no
|
||||||
|
* room for a driver override) — see that extension's own docblock.
|
||||||
|
*/
|
||||||
|
public function refundVia(Transaction $transaction, ?string $driverKey, int $amount, ?string $notes = null): PaymentRefund
|
||||||
|
{
|
||||||
|
$driver = $driverKey !== null ? $this->registry->resolve($driverKey) : null;
|
||||||
|
|
||||||
|
if (! $driver instanceof SupportsRefunds) {
|
||||||
|
return new PaymentRefund(success: false, message: 'This payment method does not support refunds.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $driver->refund(
|
||||||
|
$transaction->reference,
|
||||||
|
$this->priceFor($transaction, $amount),
|
||||||
|
['notes' => $notes, 'order_id' => $transaction->order_id],
|
||||||
|
);
|
||||||
|
|
||||||
|
return new PaymentRefund(
|
||||||
|
success: $result->status === PaymentResultStatus::Succeeded,
|
||||||
|
message: $result->failureReason,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function capture(Transaction $transaction, int $amount = 0): PaymentCapture
|
||||||
|
{
|
||||||
|
$driver = $this->resolveDriver($transaction);
|
||||||
|
|
||||||
|
if (! $driver instanceof SupportsCaptures) {
|
||||||
|
return new PaymentCapture(success: false, message: 'This payment method does not support a separate capture step.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $driver->capture(
|
||||||
|
$transaction->reference,
|
||||||
|
$this->priceFor($transaction, $amount ?: $transaction->amount->value),
|
||||||
|
['order_id' => $transaction->order_id],
|
||||||
|
);
|
||||||
|
|
||||||
|
return new PaymentCapture(
|
||||||
|
success: $result->status === PaymentResultStatus::Succeeded,
|
||||||
|
message: $result->failureReason ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lunar's own PaymentChecks DTO (address/postcode/CVC verification
|
||||||
|
* results) has no equivalent in our own contracts — none of our
|
||||||
|
* drivers currently surface this level of gateway-specific detail.
|
||||||
|
* Empty, not null: Lunar's admin panel iterates this collection to
|
||||||
|
* render a checks list, so it needs to always be a valid (possibly
|
||||||
|
* empty) PaymentChecks, never missing entirely.
|
||||||
|
*/
|
||||||
|
public function getPaymentChecks(Transaction $transaction): PaymentChecks
|
||||||
|
{
|
||||||
|
return new PaymentChecks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolveDriver(Transaction $transaction): ?object
|
||||||
|
{
|
||||||
|
$driverKey = $this->driverKeyFor($transaction);
|
||||||
|
|
||||||
|
return $driverKey !== null ? $this->registry->resolve($driverKey) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function priceFor(Transaction $transaction, int $amount): Price
|
||||||
|
{
|
||||||
|
return new Price($amount, $transaction->order->currency);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ class OrderServiceProvider extends ServiceProvider
|
|||||||
Event::listen(ShipmentStatusUpdatedByCarrier::class, DeriveOrderDeliveredFromShipment::class);
|
Event::listen(ShipmentStatusUpdatedByCarrier::class, DeriveOrderDeliveredFromShipment::class);
|
||||||
Event::listen(PaymentCaptured::class, ApplyResolvedPaymentStatus::class);
|
Event::listen(PaymentCaptured::class, ApplyResolvedPaymentStatus::class);
|
||||||
Event::listen(PaymentAuthorized::class, ApplyResolvedPaymentStatus::class);
|
Event::listen(PaymentAuthorized::class, ApplyResolvedPaymentStatus::class);
|
||||||
|
Event::listen(PaymentRefunded::class, ApplyResolvedPaymentStatus::class);
|
||||||
Event::listen(PaymentCaptured::class, RecordPaymentTransaction::class);
|
Event::listen(PaymentCaptured::class, RecordPaymentTransaction::class);
|
||||||
Event::listen(PaymentAuthorized::class, RecordPaymentTransaction::class);
|
Event::listen(PaymentAuthorized::class, RecordPaymentTransaction::class);
|
||||||
Event::listen(PaymentVoided::class, RecordPaymentTransaction::class);
|
Event::listen(PaymentVoided::class, RecordPaymentTransaction::class);
|
||||||
|
|||||||
@@ -2,24 +2,37 @@
|
|||||||
|
|
||||||
namespace Modules\Core\Providers;
|
namespace Modules\Core\Providers;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Lunar\Facades\ModelManifest;
|
||||||
|
use Lunar\Models\Contracts\Transaction as TransactionContract;
|
||||||
use Lunar\Pipelines\Cart\ApplyShipping;
|
use Lunar\Pipelines\Cart\ApplyShipping;
|
||||||
|
use Modules\Core\Command\SyncPaymentDriversCommand;
|
||||||
|
use Modules\Core\Payment\Drivers\BankTransferPaymentDriver;
|
||||||
|
use Modules\Core\Payment\Drivers\OfflinePaymentDriver;
|
||||||
|
use Modules\Core\Payment\Drivers\StripePaymentDriver;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodCreated;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodDeleted;
|
||||||
|
use Modules\Core\Payment\Events\PaymentMethodUpdated;
|
||||||
|
use Modules\Core\Payment\Listeners\LogPaymentMethodActivity;
|
||||||
|
use Modules\Core\Payment\Models\CoreTransaction;
|
||||||
|
use Modules\Core\Payment\Services\PaymentDriverRegistry;
|
||||||
|
|
||||||
class PaymentServiceProvider extends ServiceProvider
|
class PaymentServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
$this->mergeConfigFrom(__DIR__ . '/../../config/payment.php', 'payment');
|
$this->mergeConfigFrom(__DIR__ . '/../../config/payment.php', 'payment');
|
||||||
|
|
||||||
|
$this->app->singleton(PaymentDriverRegistry::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function boot(): void
|
public function boot(): void
|
||||||
{
|
{
|
||||||
config([
|
$registry = $this->app->make(PaymentDriverRegistry::class);
|
||||||
'lunar.payments.types' => array_merge(
|
$registry->register('offline', OfflinePaymentDriver::class, 'Offline / Manual');
|
||||||
config('lunar.payments.types', []),
|
$registry->register('stripe', StripePaymentDriver::class, 'Stripe');
|
||||||
config('payment.types', [])
|
$registry->register('bank-transfer', BankTransferPaymentDriver::class, 'Bank Transfer');
|
||||||
),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$cartPipeline = config('lunar.cart.pipelines.cart', []);
|
$cartPipeline = config('lunar.cart.pipelines.cart', []);
|
||||||
$insertAfter = array_search(ApplyShipping::class, $cartPipeline, true);
|
$insertAfter = array_search(ApplyShipping::class, $cartPipeline, true);
|
||||||
@@ -39,6 +52,27 @@ class PaymentServiceProvider extends ServiceProvider
|
|||||||
|
|
||||||
config(['lunar.cart.pipelines.cart' => $cartPipeline]);
|
config(['lunar.cart.pipelines.cart' => $cartPipeline]);
|
||||||
|
|
||||||
|
// Same contract-swap mechanism this codebase already uses for
|
||||||
|
// Customer/Staff (see e.g. consuming apps' own AppServiceProvider,
|
||||||
|
// ModelManifest::replace(Contracts\Customer::class, ...)) — every
|
||||||
|
// place Lunar's own code resolves a transaction via
|
||||||
|
// Transaction::modelClass() (Order::transactions()'s own relation
|
||||||
|
// included) gets Modules\Core\Payment\Models\CoreTransaction
|
||||||
|
// instead of the vendor's own Transaction. That subclass's
|
||||||
|
// driver() override is the ENTIRE fix for the admin panel's
|
||||||
|
// refund/capture actions silently landing on our real payment
|
||||||
|
// system — see CoreTransaction's own docblock. Lunar's own
|
||||||
|
// Payments facade/PaymentManager is never touched at all.
|
||||||
|
ModelManifest::replace(TransactionContract::class, CoreTransaction::class);
|
||||||
|
|
||||||
|
Event::listen(PaymentMethodCreated::class, [LogPaymentMethodActivity::class, 'handleCreated']);
|
||||||
|
Event::listen(PaymentMethodUpdated::class, [LogPaymentMethodActivity::class, 'handleUpdated']);
|
||||||
|
Event::listen(PaymentMethodDeleted::class, [LogPaymentMethodActivity::class, 'handleDeleted']);
|
||||||
|
|
||||||
$this->loadRoutesFrom(__DIR__ . '/../Payment/routes/webhooks.php');
|
$this->loadRoutesFrom(__DIR__ . '/../Payment/routes/webhooks.php');
|
||||||
|
|
||||||
|
if ($this->app->runningInConsole()) {
|
||||||
|
$this->commands([SyncPaymentDriversCommand::class]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user