Files
core/src/Shipping/Extensions/OrderShipmentsExtension.php
T

275 lines
14 KiB
PHP
Raw Normal View History

<?php
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\Schemas\Components\Section;
use Illuminate\Support\Facades\URL;
use Lunar\Admin\Support\Extending\ViewPageExtension;
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;
/**
* Adds a "Shipments" section to the order page's main column — previously
* "Create Shipment" (Modules\Core\Shipping\Extensions\OrderViewExtension)
* had no counterpart anywhere on the order to actually SEE what it
* created (carrier, tracking reference, current status, whether a label's
* been printed or the shipment cancelled). One row per Shipment record —
* a Box Now order with several boxes shows one row per box/parcel (see
* Modules\Core\Shipping\Carriers\BoxNow\BoxNowFulfillmentService, which
* creates one Shipment row per parcel Box Now returns), not one row per
* "Create Shipment" click.
*
* Uses the extendInfolistSchema hook (main column — alongside shipping
* address, order lines, totals, transactions, timeline), not
* extendInfolistAsideSchema (sidebar) — a shipment list can grow long
* (multi-box Box Now orders, a re-dispatched order after a delivery
* failure) and reads more naturally as a main-column section like
* Transactions, not a compact sidebar entry.
*
* Each shipment renders as two inline-labelled lines (carrier + tracking
* reference, then status + timestamp) rather than a grid of individually
* stacked label/value blocks — Filament's own multi-column grid still
* collapses to one column below its lg breakpoint (1024px), which is
* exactly where the admin's main content area commonly sits with the
* sidebar open, so a 5-6 field grid reads as a wall of repeated labels
* there.
*
* "Print Label" opens Modules\Core\Shipping\Http\Controllers\
* DownloadShipmentLabelController via a short-lived signed URL — the same
* auth model (and Action wiring pattern) Lunar's own vendor PdfDownload
* action uses for order PDFs. Previously the only place that called
* CarrierFulfillmentInterface::printLabel() (Modules\Core\Shipping\
* Filament\Pages\ManagePickupManifests) discarded the returned bytes
* entirely — this is the first place that actually delivers a label to
* staff.
*/
class OrderShipmentsExtension extends ViewPageExtension
{
/**
* Inserted right after Transactions and before Timeline — vendor
* ManageOrder::getInfolistSchema() builds this array as
* [shipping, orderLines, orderTotals, transactions, timeline] (see
* Lunar\Admin\...\Concerns\DisplaysTransactions/DisplaysTimeline), so
* splicing at index 4 lands the new section there regardless of how
* many earlier entries any OTHER extension on this same hook has
* already added/removed — counting from the end (timeline is always
* last) would be equally fragile to some other extension appending
* its own section after timeline, so this anchors on the known
* vendor order instead.
*/
public function extendInfolistSchema(array $schema): array
{
array_splice($schema, 4, 0, [$this->shipmentsSection()]);
return $schema;
}
private function shipmentsSection(): Section
{
return Section::make('shipments')
->heading('Shipments')
->compact()
->collapsed(fn ($record) => $record->shipments->isEmpty())
->collapsible(fn ($record) => $record->shipments->isNotEmpty())
->schema([
RepeatableEntry::make('shipments')
->hiddenLabel()
->placeholder('No shipments have been created for this order yet.')
->contained(true)
->schema([
TextEntry::make('tracking_reference')
->label(fn (Shipment $record) => $record->carrierLabel())
->inlineLabel()
->placeholder('Voucher not issued yet')
->copyable(),
TextEntry::make('status')
->label('Status')
->inlineLabel()
->state(fn (Shipment $record) => $this->statusLabel($record))
->badge()
->color(fn (Shipment $record) => $this->statusColor($record))
->helperText(fn (Shipment $record) => $this->helperText($record))
->suffixActions([
Action::make('print_label')
->label('Print Label')
->icon('heroicon-o-printer')
->url(fn (Shipment $record) => URL::temporarySignedRoute(
'shipments.label',
now()->addMinutes(5),
['shipment' => $record->id],
), shouldOpenInNewTab: true)
->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(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')
->label('Tracking history')
->state(fn (Shipment $record) => $this->orderedCheckpoints($record))
->hidden(fn (Shipment $record) => $record->shipmentInfo->isEmpty())
->schema([
TextEntry::make('status')
->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())
// 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),
]),
]),
]);
}
/**
* Oldest first — a delivery journey (Collected → In Transit →
* Delivered) reads naturally top-to-bottom in that order, unlike
* statusLabel()/statusColor() above which only ever need the single
* latest checkpoint and so use latestShipmentInfo() directly instead.
*
* @return Collection<int, ShipmentInfo>
*/
private function orderedCheckpoints(Shipment $record): Collection
{
return $record->shipmentInfo->sortBy('occurred_at')->values();
}
/**
* 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
{
$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
{
$parts = ['Created '.$record->created_at->format('Y-m-d H:i')];
if ($record->carrier === 'box-now' && $locker = $record->meta['locker_id'] ?? null) {
$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);
}
private function statusLabel(Shipment $record): string
{
if ($record->cancelled_at) {
return 'Cancelled';
}
$latest = $record->latestShipmentInfo();
return $latest ? (string) str($latest->status->value)->replace('_', ' ')->title() : 'Pending';
}
private function statusColor(Shipment $record): string
{
if ($record->cancelled_at) {
return 'danger';
}
return match ($record->latestShipmentInfo()?->status?->value) {
'delivered' => 'success',
'failed', 'returned' => 'danger',
'in_transit', 'out_for_delivery', 'collected_from_sender' => 'warning',
default => 'gray',
};
}
}