Feat: Shipping functionalities redesign, elta courier integration, commenting out acs since no integration can happen, flow updates

This commit is contained in:
arvanitakis committed 2026-09-30 17:28:47 +03:00
1 parent f411dec1da
commit 49ec4333af
63 files changed
+3143 -347

No files matched your search

@@ -3,17 +3,22 @@
namespace Modules\Core\Shipping\Extensions;
use Filament\Actions\Action;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Notifications\Notification;
use Filament\Infolists\Components\TextEntry;
use Illuminate\Support\Collection;
use Modules\Core\Shipping\Models\ShipmentInfo;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Section;
use Illuminate\Support\Facades\URL;
use Lunar\Admin\Support\Extending\ViewPageExtension;
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
use Modules\Core\Shipping\Enums\ExtraService;
use Modules\Core\Shipping\Enums\TrackingStatus;
use Modules\Core\Shipping\Events\ShipmentStatusUpdatedByCarrier;
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
use Modules\Core\Shipping\Models\Shipment;
use Throwable;
/**
* Adds a "Shipments" section to the order page's main column — previously
@@ -85,8 +90,9 @@ class OrderShipmentsExtension extends ViewPageExtension
->contained(true)
->schema([
TextEntry::make('tracking_reference')
->label(fn (Shipment $record) => $this->carrierLabel($record))
->label(fn (Shipment $record) => $record->carrierLabel())
->inlineLabel()
->placeholder('Voucher not issued yet')
->copyable(),
TextEntry::make('status')
->label('Status')
@@ -104,14 +110,57 @@ class OrderShipmentsExtension extends ViewPageExtension
now()->addMinutes(5),
['shipment' => $record->id],
), shouldOpenInNewTab: true)
->visible(fn (Shipment $record) => ! $record->cancelled_at),
->visible(fn (Shipment $record) => $record->hasCarrierLabel()),
Action::make('open_carrier_tracking')
->label('Carrier tracking')
->icon('heroicon-o-arrow-top-right-on-square')
->url(fn (Shipment $record) => $record->trackingUrl(), shouldOpenInNewTab: true)
->visible(fn (Shipment $record) => filled($record->trackingUrl())),
Action::make('edit_tracking_reference')
->label('Edit number')
->icon('heroicon-o-pencil-square')
->fillForm(fn (Shipment $record) => ['tracking_reference' => $record->tracking_reference])
->schema(fn (Shipment $record) => [
TextInput::make('tracking_reference')
->label('Voucher / tracking number')
->unique(Shipment::class, 'tracking_reference', ignorable: $record),
])
->action(fn (Shipment $record, array $data) => $record->update([
'tracking_reference' => filled($data['tracking_reference']) ? trim($data['tracking_reference']) : null,
]))
->visible(fn (Shipment $record) => $record->source === Shipment::SOURCE_MANUAL && ! $record->isCancelled()),
Action::make('add_tracking_update')
->label('Add tracking update')
->icon('heroicon-o-plus-circle')
->schema([
Select::make('status')
->label('Status')
->options(collect(TrackingStatus::cases())
->reject(fn (TrackingStatus $status) => in_array($status, [TrackingStatus::Unknown, TrackingStatus::Pending], true))
->mapWithKeys(fn (TrackingStatus $status) => [$status->value => (string) str($status->value)->replace('_', ' ')->title()]))
->native(false)
->required(),
DateTimePicker::make('occurred_at')
->label('When')
->seconds(false)
->default(now())
->required(),
TextInput::make('location')->label('Location'),
TextInput::make('message')
->label('Message')
->helperText('Shown to the customer on their order page.'),
])
->action(fn (Shipment $record, array $data) => $this->addTrackingUpdate($record, $data))
->visible(fn (Shipment $record) => $record->source === Shipment::SOURCE_MANUAL && ! $record->isCancelled()),
Action::make('cancel_shipment')
->label('Cancel')
->icon('heroicon-o-x-circle')
->color('danger')
->requiresConfirmation()
->modalDescription('Cancels this shipment with the carrier. This cannot be undone.')
->action(fn (Shipment $record) => $this->cancel($record))
->modalDescription(fn (Shipment $record) => $record->cancelsLocallyOnly()
? 'Marks this shipment as cancelled here only. Void the voucher with the courier as well.'
: 'Cancels this shipment with the carrier. This cannot be undone.')
->action(fn (Shipment $record) => ShipmentResource::cancelShipment($record))
->visible(fn (Shipment $record) => ! $record->cancelled_at),
]),
RepeatableEntry::make('shipmentInfo')
@@ -123,7 +172,11 @@ class OrderShipmentsExtension extends ViewPageExtension
->label(fn (ShipmentInfo $record) => $record->occurred_at->format('Y-m-d H:i'))
->inlineLabel()
->state(fn (ShipmentInfo $record) => (string) str($record->status->value)->replace('_', ' ')->title())
->helperText(fn (ShipmentInfo $record) => $record->location),
// Our status as the label, the carrier's own wording underneath.
->helperText(fn (ShipmentInfo $record) => collect([
$record->carrier_status !== 'manual' ? $record->carrier_status : null,
$record->location,
])->filter()->unique()->implode(' · ') ?: null),
]),
]),
]);
@@ -142,13 +195,29 @@ class OrderShipmentsExtension extends ViewPageExtension
return $record->shipmentInfo->sortBy('occurred_at')->values();
}
private function carrierLabel(Shipment $record): string
/**
* A manual carrier's checkpoint, entered by staff. Dispatches the same
* event as carrier polling, so the order's status and emails follow it
* exactly like an integrated carrier's.
*/
private function addTrackingUpdate(Shipment $record, array $data): void
{
return match ($record->carrier) {
'acs' => 'ACS',
'box-now' => 'Box Now',
default => (string) str($record->carrier)->title(),
};
$info = ShipmentInfo::create([
'shipment_id' => $record->id,
'status' => TrackingStatus::from($data['status']),
'carrier_status' => 'manual',
'message' => $data['message'] ?? null,
'location' => $data['location'] ?? null,
'occurred_at' => $data['occurred_at'],
]);
ShipmentStatusUpdatedByCarrier::dispatch($info);
Notification::make()
->title('Tracking update added.')
->success()
->send();
}
private function helperText(Shipment $record): string
@@ -159,6 +228,22 @@ class OrderShipmentsExtension extends ViewPageExtension
$parts[] = 'Locker '.$locker;
}
if ($cod = $record->meta['cod_amount'] ?? null) {
$parts[] = 'Cash on delivery: €'.number_format((float) $cod, 2);
}
$services = collect($record->meta['services'] ?? [])
->map(fn (string $value) => ExtraService::tryFrom($value)?->label())
->filter();
if ($services->isNotEmpty()) {
$parts[] = $services->implode(', ');
}
if ($record->source === Shipment::SOURCE_MANUAL_VOUCHER) {
$parts[] = 'Manual voucher';
}
return implode(' · ', $parts);
}
@@ -187,26 +272,4 @@ class OrderShipmentsExtension extends ViewPageExtension
};
}
private function cancel(Shipment $record): void
{
$service = app(CarrierFulfillmentInterface::class, ['carrier' => $record->carrier]);
try {
$service->cancelShipment($record);
} catch (Throwable $e) {
report($e);
Notification::make()
->title('Failed to cancel shipment: '.$e->getMessage())
->color('danger')
->send();
return;
}
Notification::make()
->title('Shipment cancelled.')
->color('success')
->send();
}
}
+217 -11
View File
@@ -3,17 +3,30 @@
namespace Modules\Core\Shipping\Extensions;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Lunar\Admin\Support\Extending\ViewPageExtension;
use Lunar\Models\Order;
use Lunar\Shipping\Facades\Shipping;
use Modules\Core\Order\DTOs\OrderFulfillmentResult;
use Modules\Core\Order\Services\OrderFulfillmentService;
use Modules\Core\Order\Services\OrderStatusFlow;
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
use Modules\Core\Shipping\Contracts\SupportsExtraServices;
use Modules\Core\Shipping\Contracts\SupportsVoucherLookup;
use Modules\Core\Shipping\DTOs\ShipmentRequest;
use Modules\Core\Shipping\Enums\ExtraService;
use Modules\Core\Shipping\Models\Shipment;
use Modules\Core\Shipping\Support\WeightCalculator;
use Throwable;
/**
* Filament wiring only (labels, icons, visibility, form schema) for the
@@ -35,11 +48,12 @@ use Modules\Core\Shipping\Support\WeightCalculator;
*
* "Create Shipment" is its own separate header action, visible only for a
* carrier order sitting at 'ready_for_dispatch' — this is the one action
* that talks to a real carrier API and writes Order::status to
* 'dispatched' as a side effect of that succeeding, so it needs its own
* weight/locker inputs specific to that one real-world action, not
* bundled into the general-purpose status select where they'd appear for
* every revert/manual-override use of 'dispatched' too. The form branches
* that talks to a real carrier API, so it needs its own weight/locker
* inputs specific to that one real-world action. It does NOT move the
* order to 'dispatched': that happens when the carrier reports picking the
* parcel up (AdvanceFulfillmentOnCarrierCheckpoint). Staff also pick the
* carrier's extra services here (Saturday delivery, insurance, …) from the
* normalized ExtraService list the carrier offers. The form branches
* on which carrier the order actually uses
* (OrderFulfillmentService::carrierFor()): a weight-billed carrier (ACS)
* gets a single TOTAL weight field for the whole shipment (ACS has no
@@ -62,6 +76,13 @@ use Modules\Core\Shipping\Support\WeightCalculator;
* customer's choice turns out to be unavailable) or fill it in manually for
* an order placed before the checkout locker picker existed.
*
* "Add manual voucher" records a voucher of an integrated carrier that
* wasn't created through our API — the carrier's system was down and staff
* filled a pre-numbered paper voucher, or the courier wrote his own at
* pickup. Tracking picks its history up like any other shipment; the
* carrier's lookup (when it has one) previews what it reports for the
* number before saving.
*
* "Mark Paid" is a third, separate header action — Order::paid is
* independent of `status` (see OrderStatusFlow's own docblock), so it
* doesn't belong bundled into the status select either. Visible only when
@@ -86,6 +107,7 @@ class OrderViewExtension extends ViewPageExtension
: true);
$actions[] = $this->createShipmentAction();
$actions[] = $this->addManualVoucherAction();
$actions[] = $this->updateStatusAction();
$actions[] = $this->markPaidAction();
@@ -99,11 +121,28 @@ class OrderViewExtension extends ViewPageExtension
->icon('heroicon-o-truck')
->modalSubmitActionLabel('Create Shipment')
->schema(function (Order $record) {
$isBoxNow = $this->service()->carrierFor($record) === 'box-now';
$carrier = $this->service()->carrierFor($record);
$isBoxNow = $carrier === 'box-now';
$lockerId = $record->shippingAddress?->meta['box_now_locker']['locationId'] ?? null;
if (! $isBoxNow) {
if ($carrier === 'manual') {
return [
TextInput::make('tracking_reference')
->label('Voucher / tracking number')
->unique(Shipment::class, 'tracking_reference')
->helperText('Optional — add it later from the shipment if the courier hasn\'t given one yet.'),
TextInput::make('package_count')
->label('Number of packages')
->numeric()
->integer()
->minValue(1)
->default(1)
->required(),
];
}
if (! $isBoxNow) {
return [...[
TextInput::make('weight')
->label('Total weight (kg)')
->numeric()
@@ -118,10 +157,10 @@ class OrderViewExtension extends ViewPageExtension
->default(1)
->required()
->helperText('More than 1 issues a main voucher plus a sub-voucher per extra package, all sharing the total weight above.'),
];
], ...$this->extraServiceFields($record)];
}
return [
return [...[
TextInput::make('destination_location_id')
->label('Box Now locker ID')
->default($lockerId)
@@ -143,7 +182,7 @@ class OrderViewExtension extends ViewPageExtension
->addActionLabel('Add another box')
->minItems(1)
->helperText('One row per physical parcel — Box Now ships by compartment size, not weight.'),
];
], ...$this->extraServiceFields($record)];
})
->action(function (Order $record, array $data, Action $action) {
// Derived from the order itself, never from staff input —
@@ -161,7 +200,9 @@ class OrderViewExtension extends ViewPageExtension
// full payment was already settled, and never collect it.
$isCod = app(OrderStatusFlow::class)->isCod($record);
$result = $this->service()->createShipmentAndDispatch(
$services = array_map(fn (string $value) => ExtraService::from($value), $data['services'] ?? []);
$result = $this->service()->createShipment(
$record,
new ShipmentRequest(
weight: filled($data['weight'] ?? null) ? (float) $data['weight'] : null,
@@ -170,6 +211,14 @@ class OrderViewExtension extends ViewPageExtension
paymentMode: $isCod ? 'cod' : 'prepaid',
amountToCollect: $isCod ? $record->total->decimal : null,
boxes: collect($data['boxes'] ?? [])->pluck('size')->all(),
services: $services,
insuranceAmount: in_array(ExtraService::Insurance, $services, true) && filled($data['insurance_amount'] ?? null)
? (float) $data['insurance_amount']
: null,
deliveryUntil: in_array(ExtraService::TimedDelivery, $services, true)
? ($data['delivery_until'] ?? null)
: null,
trackingReference: $data['tracking_reference'] ?? null,
),
);
@@ -182,6 +231,163 @@ class OrderViewExtension extends ViewPageExtension
->visible(fn (Order $record) => $this->service()->canCreateShipment($record));
}
/**
* The extra services the order's carrier offers, plus the details some
* of them need. Nothing is shown for carriers that offer none.
*/
private function extraServiceFields(Order $record): array
{
$options = $this->extraServiceOptions($this->service()->carrierFor($record));
if ($options === []) {
return [];
}
$ticked = fn (Get $get, ExtraService $service) => in_array($service->value, $get('services') ?? [], true);
return [
CheckboxList::make('services')
->label('Extra services')
->options($options)
->columns(2)
->live(),
TextInput::make('insurance_amount')
->label('Insured value')
->numeric()
->minValue(0)
->prefix('€')
->default($record->total->decimal)
->visible(fn (Get $get) => $ticked($get, ExtraService::Insurance))
->required(fn (Get $get) => $ticked($get, ExtraService::Insurance)),
TimePicker::make('delivery_until')
->label('Deliver by')
->seconds(false)
->visible(fn (Get $get) => $ticked($get, ExtraService::TimedDelivery))
->required(fn (Get $get) => $ticked($get, ExtraService::TimedDelivery)),
];
}
/**
* @return array<string, string> ExtraService value => label
*/
private function extraServiceOptions(?string $carrier): array
{
$service = $carrier ? app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]) : null;
if (! $service instanceof SupportsExtraServices) {
return [];
}
return collect(array_keys($service->extraServices()))
->mapWithKeys(fn (string $value) => [$value => ExtraService::from($value)->label()])
->all();
}
private function addManualVoucherAction(): Action
{
return Action::make('add_manual_voucher')
->label('Add manual voucher')
->icon('heroicon-o-pencil-square')
->modalDescription("For a voucher that exists at the carrier but wasn't created here — e.g. the carrier's system was down, or the courier wrote his own voucher at pickup. Its tracking history is picked up from the carrier.")
->modalSubmitActionLabel('Add voucher')
->schema(fn (Order $record) => [
Select::make('carrier')
->label('Carrier')
->options($this->integratedCarriers())
->default($this->service()->carrierFor($record))
->native(false)
->required()
->live()
->afterStateUpdated(fn (Set $set) => $set('lookup', null)),
TextInput::make('voucher_number')
->label('Voucher number')
->required()
->unique(Shipment::class, 'tracking_reference')
->live(onBlur: true)
->afterStateUpdated(fn (Set $set) => $set('lookup', null))
->suffixAction(
Action::make('lookup')
->icon('heroicon-o-magnifying-glass')
->tooltip('Look up at the carrier')
->action(fn (Get $get, Set $set) => $set('lookup', $this->describeLookup($get('carrier'), $get('voucher_number')))),
),
Hidden::make('lookup'),
Placeholder::make('lookup_preview')
->label('Carrier reports')
->content(fn (Get $get) => $get('lookup'))
->visible(fn (Get $get) => filled($get('lookup'))),
CheckboxList::make('services')
->label('Extra services')
->options(fn (Get $get) => $this->extraServiceOptions($get('carrier')))
->columns(2)
->visible(fn (Get $get) => $this->extraServiceOptions($get('carrier')) !== []),
])
->action(function (Order $record, array $data, Action $action) {
$result = $this->service()->addManualVoucher(
$record,
$data['carrier'],
$data['voucher_number'],
array_map(fn (string $value) => ExtraService::from($value), $data['services'] ?? []),
);
$this->notify($result);
if (! $result->success) {
$action->halt();
}
})
->visible(fn (Order $record) => $this->service()->canAddManualVoucher($record));
}
/**
* Carriers with an API integration — manual carriers have no voucher
* of their own to look up or track.
*
* @return array<string, string>
*/
private function integratedCarriers(): array
{
return collect(Shipping::getSupportedDrivers())
->filter(fn ($driver, string $carrier) => $carrier !== 'manual'
&& app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]) !== null)
->map(fn ($driver) => $driver->name())
->all();
}
private function describeLookup(?string $carrier, ?string $number): string
{
if (blank($carrier) || blank($number)) {
return 'Pick the carrier and enter the voucher number first.';
}
$service = app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]);
if (! $service instanceof SupportsVoucherLookup) {
return "This carrier doesn't support looking vouchers up — you can still add it.";
}
try {
$voucher = $service->lookupVoucher(trim($number));
} catch (Throwable $e) {
report($e);
return "Couldn't reach the carrier ({$e->getMessage()}) — you can still add it; its history is picked up once the carrier responds.";
}
if (! $voucher) {
return 'The carrier has no record of this voucher yet — you can still add it.';
}
return collect([
$voucher->recipientName,
$voucher->postcode,
$voucher->reference ? 'Ref. '.$voucher->reference : null,
$voucher->statusText,
$voucher->codAmount ? 'COD €'.number_format($voucher->codAmount, 2) : null,
$voucher->isReturn ? 'Return voucher' : null,
])->filter()->implode(' · ');
}
private function updateStatusAction(): Action
{
return Action::make('update_status')
@@ -8,6 +8,8 @@ use Filament\Schemas\Components\Concerns\HasChildComponents;
use Filament\Schemas\Components\Utilities\Get;
use InvalidArgumentException;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Lunar\Admin\Support\Extending\ResourceExtension;
@@ -110,15 +112,49 @@ class ShippingMethodResourceExtension extends ResourceExtension
}
if (in_array(HasChildComponents::class, class_uses_recursive($component), true)) {
$component->schema(
$this->replaceChargeByField($component->getDefaultChildComponents())
$children = $this->replaceChargeByField($component->getDefaultChildComponents());
// The manual carrier's settings sit next to charge_by, in
// the same `data` group.
$hasChargeBy = collect($children)->contains(
fn (Component $child) => method_exists($child, 'getName') && $child->getName() === 'charge_by'
);
$component->schema($hasChargeBy ? [...$children, ...$this->manualCarrierFields()] : $children);
}
return $component;
}, $components);
}
/**
* Settings for a carrier without an integration (ManualRateDriver),
* stored in the method's `data`. Shown only for that driver.
*
* @return array<Component>
*/
private function manualCarrierFields(): array
{
$isManual = fn (Get $get) => $get('../driver') === 'manual';
return [
TextInput::make('carrier_name')
->label('Carrier name')
->helperText('Shown to staff and customers on this carrier\'s shipments, e.g. "Geniki Taxydromiki".')
->visible($isManual)
->required($isManual),
TextInput::make('tracking_url')
->label('Tracking URL')
->helperText('Optional. The carrier\'s tracking page, with {number} where the voucher number goes, e.g. https://example.com/track?number={number}.')
->rule('starts_with:http://,https://')
->visible($isManual),
Toggle::make('collects_cash')
->label('Courier collects cash on delivery')
->helperText('Offers cash on delivery at checkout for this shipping method.')
->visible($isManual),
];
}
private function chargeBySelect(): Select
{
return Select::make('charge_by')