Feature: Shipping Carrier Additions, Creating a voucher without an order, verifying order details before creating voucher, ELTA Courier voucher print updates
This commit is contained in:
1 parent
c455c8adf2
commit
5ff0d60f54
27 files changed
+2189
-376
No files matched your search
@@ -8,11 +8,13 @@ use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Shipping\Carriers\BoxNow\Exceptions\BoxNowApiException;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\CreatesStandaloneVouchers;
|
||||
use Modules\Core\Shipping\Contracts\SupportsTracking;
|
||||
use Modules\Core\Shipping\Contracts\SupportsVoucherListing;
|
||||
use Modules\Core\Shipping\Contracts\SupportsVoucherLookup;
|
||||
use Modules\Core\Shipping\DTOs\CarrierVoucher;
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
use Modules\Core\Shipping\DTOs\TrackingCheckpoint;
|
||||
use Modules\Core\Shipping\Enums\TrackingStatus;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
@@ -31,12 +33,11 @@ use Modules\Core\Shipping\Models\Shipment;
|
||||
* $order->shippingAddress->meta['box_now_locker']).
|
||||
*
|
||||
* Box Now ships by compartment size, not weight — unlike ACS, which bills
|
||||
* by kg. One 'items' entry per box in ShipmentRequest::$boxes, so an order
|
||||
* needing more than one physical parcel (doesn't fit one compartment)
|
||||
* sends that many entries in a single delivery request rather than
|
||||
* several separate ones.
|
||||
* by kg. Each box in ShipmentRequest::$boxes is its own delivery request
|
||||
* (and so its own parcel, voucher and compartment): Box Now merges the
|
||||
* items of one request into a single parcel — see create().
|
||||
*/
|
||||
class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsTracking, SupportsVoucherListing, SupportsVoucherLookup
|
||||
class BoxNowFulfillmentService implements CarrierFulfillmentInterface, CreatesStandaloneVouchers, SupportsTracking, SupportsVoucherListing, SupportsVoucherLookup
|
||||
{
|
||||
private const COMPARTMENT_SIZES = ['S' => 1, 'M' => 2, 'L' => 3];
|
||||
|
||||
@@ -44,7 +45,35 @@ class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsT
|
||||
|
||||
public function createShipment(Order $order, ShipmentRequest $request): Shipment
|
||||
{
|
||||
$address = $order->shippingAddress;
|
||||
// Box Now rejects an orderNumber it has seen before (P410), even
|
||||
// for a cancelled request — so a re-created shipment after a cancel
|
||||
// gets "-2", "-3", …; the first attempt keeps "{reference}-{id}".
|
||||
$previousRequests = Shipment::where('order_id', $order->id)
|
||||
->where('carrier', 'box-now')
|
||||
->where('source', Shipment::SOURCE_CREATED)
|
||||
->get()
|
||||
// One per attempt — the boxes of one attempt share its reference.
|
||||
->map(fn (Shipment $shipment) => $shipment->meta['reference'] ?? $shipment->meta['delivery_request_id'] ?? $shipment->id)
|
||||
->unique()
|
||||
->count();
|
||||
|
||||
$orderNumber = $order->reference.'-'.$order->id.($previousRequests > 0 ? '-'.($previousRequests + 1) : '');
|
||||
|
||||
return $this->create($request->recipient ?? VoucherRecipient::fromAddress($order->shippingAddress), $orderNumber, $request, $order);
|
||||
}
|
||||
|
||||
/**
|
||||
* A delivery request for a parcel that isn't a shop order ("Create
|
||||
* voucher" on Carrier Vouchers). Our reference is its orderNumber, so
|
||||
* it must be one Box Now hasn't seen before.
|
||||
*/
|
||||
public function createStandaloneVoucher(VoucherRecipient $recipient, string $reference, ShipmentRequest $request): Shipment
|
||||
{
|
||||
return $this->create($recipient, $reference, $request);
|
||||
}
|
||||
|
||||
private function create(VoucherRecipient $recipient, string $orderNumber, ShipmentRequest $request, ?Order $order = null): Shipment
|
||||
{
|
||||
$destinationLocationId = $request->destinationLocationId;
|
||||
|
||||
if (! $destinationLocationId) {
|
||||
@@ -55,77 +84,105 @@ class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsT
|
||||
throw new BoxNowApiException('At least one box (compartment size) is required for a Box Now shipment.');
|
||||
}
|
||||
|
||||
$isCod = $request->paymentMode === 'cod';
|
||||
// The locker's pickup code goes out by SMS and email.
|
||||
$contactNumber = $recipient->mobile ?: $recipient->phone;
|
||||
|
||||
// Box Now rejects an orderNumber it has seen before (P410), even
|
||||
// for a cancelled request — so a re-created shipment after a cancel
|
||||
// gets "-2", "-3", …; the first attempt keeps "{reference}-{id}".
|
||||
$previousRequests = Shipment::where('order_id', $order->id)
|
||||
->where('carrier', 'box-now')
|
||||
->where('source', Shipment::SOURCE_CREATED)
|
||||
->get()
|
||||
->map(fn (Shipment $shipment) => $shipment->meta['delivery_request_id'] ?? $shipment->id)
|
||||
->unique()
|
||||
->count();
|
||||
|
||||
$orderNumber = $order->reference.'-'.$order->id.($previousRequests > 0 ? '-'.($previousRequests + 1) : '');
|
||||
|
||||
$response = $this->client->request('post', '/delivery-requests', [
|
||||
'orderNumber' => $orderNumber,
|
||||
'invoiceValue' => number_format($order->total->decimal, 2, '.', ''),
|
||||
'paymentMode' => $isCod ? 'cod' : 'prepaid',
|
||||
'amountToBeCollected' => $isCod
|
||||
? number_format($request->amountToCollect ?? $order->total->decimal, 2, '.', '')
|
||||
: '0.00',
|
||||
'origin' => [
|
||||
'contactNumber' => config('boxnow.sender.phone'),
|
||||
'contactEmail' => config('boxnow.sender.email'),
|
||||
'contactName' => config('boxnow.sender.name'),
|
||||
'locationId' => config('boxnow.origin_location_id'),
|
||||
],
|
||||
'destination' => [
|
||||
'contactNumber' => $this->internationalPhone($address->contact_phone),
|
||||
'contactEmail' => $address->contact_email,
|
||||
'contactName' => trim("{$address->first_name} {$address->last_name}"),
|
||||
'locationId' => $destinationLocationId,
|
||||
],
|
||||
'items' => collect($request->boxes)->values()->map(fn (string $size, int $index) => [
|
||||
'id' => $order->id.'-'.($index + 1),
|
||||
'name' => 'Order '.$order->reference.' (box '.($index + 1).')',
|
||||
'value' => '0.00',
|
||||
'compartmentSize' => self::COMPARTMENT_SIZES[$size] ?? self::COMPARTMENT_SIZES['S'],
|
||||
])->all(),
|
||||
]);
|
||||
|
||||
$parcels = collect($response['parcels'] ?? []);
|
||||
|
||||
if ($parcels->isEmpty()) {
|
||||
throw new BoxNowApiException('Box Now delivery request succeeded but returned no parcel ids.', $response);
|
||||
if (blank($contactNumber) || blank($recipient->email)) {
|
||||
throw new BoxNowApiException('Box Now needs the recipient\'s mobile and email — the locker pickup code is sent to both.');
|
||||
}
|
||||
|
||||
// One Shipment row per box/parcel — each is independently
|
||||
// trackable/printable/cancellable via its own tracking_reference
|
||||
// (printLabel()/cancelShipment()/trackShipment() below already
|
||||
// operate per-Shipment), even though all boxes were submitted in
|
||||
// one delivery request. Siblings are linked via the shared
|
||||
// delivery_request_id in meta.
|
||||
// The cash is collected once for the whole request, so only the
|
||||
// first parcel carries cod_amount.
|
||||
$codAmount = $isCod ? (float) ($request->amountToCollect ?? $order->total->decimal) : null;
|
||||
$isCod = $request->paymentMode === 'cod';
|
||||
$codAmount = $isCod ? (float) ($request->amountToCollect ?? $order?->total->decimal) : null;
|
||||
|
||||
$shipments = $parcels->values()->map(fn (array $parcel, int $index) => Shipment::create([
|
||||
'order_id' => $order->id,
|
||||
'carrier' => 'box-now',
|
||||
'tracking_reference' => (string) $parcel['id'],
|
||||
'meta' => [
|
||||
'delivery_request_id' => $response['id'] ?? null,
|
||||
'reference' => $orderNumber,
|
||||
'locker_id' => $destinationLocationId,
|
||||
'cod_amount' => $index === 0 ? $codAmount : null,
|
||||
],
|
||||
]));
|
||||
if ($isCod && ! $codAmount) {
|
||||
throw new BoxNowApiException('Enter the cash on delivery amount.');
|
||||
}
|
||||
|
||||
return $shipments->first();
|
||||
// The parcel's value: the order's total, or what staff entered
|
||||
// (falling back to the cash to collect).
|
||||
$value = $order?->total->decimal ?? $request->value ?? $codAmount ?? 0;
|
||||
|
||||
// One delivery request per box. Box Now's manual says every entry
|
||||
// in "items" becomes its own parcel, but in practice (staging,
|
||||
// Any-APM origin, verified 2026-10-01 with our payload and with
|
||||
// the official plugin's) it puts all items of a request into ONE
|
||||
// parcel at the largest size — two boxes would get one voucher.
|
||||
// A request per box gives each box its own parcel, label and
|
||||
// compartment. Each needs its own orderNumber ("-b1", "-b2", …);
|
||||
// the order's value and any cash on delivery go on the first box.
|
||||
$boxes = array_values($request->boxes);
|
||||
$count = count($boxes);
|
||||
$shipments = [];
|
||||
|
||||
try {
|
||||
foreach ($boxes as $index => $size) {
|
||||
$first = $index === 0;
|
||||
$boxNumber = $count > 1 ? "{$orderNumber}-b".($index + 1) : $orderNumber;
|
||||
|
||||
$response = $this->client->request('post', '/delivery-requests', [
|
||||
'orderNumber' => $boxNumber,
|
||||
'invoiceValue' => number_format($first ? $value : 0, 2, '.', ''),
|
||||
'paymentMode' => $isCod && $first ? 'cod' : 'prepaid',
|
||||
'amountToBeCollected' => number_format($first ? ($codAmount ?? 0) : 0, 2, '.', ''),
|
||||
'origin' => [
|
||||
'contactNumber' => config('boxnow.sender.phone'),
|
||||
'contactEmail' => config('boxnow.sender.email'),
|
||||
'contactName' => config('boxnow.sender.name'),
|
||||
'locationId' => config('boxnow.origin_location_id'),
|
||||
],
|
||||
'destination' => [
|
||||
'contactNumber' => $this->internationalPhone($contactNumber),
|
||||
'contactEmail' => $recipient->email,
|
||||
'contactName' => $recipient->name,
|
||||
'locationId' => $destinationLocationId,
|
||||
],
|
||||
'items' => [[
|
||||
'id' => $boxNumber,
|
||||
'name' => ($order ? 'Order '.$order->reference : $orderNumber).($count > 1 ? ' (box '.($index + 1).' of '.$count.')' : ''),
|
||||
'value' => '0.00',
|
||||
'weight' => 0,
|
||||
'compartmentSize' => self::COMPARTMENT_SIZES[$size] ?? self::COMPARTMENT_SIZES['S'],
|
||||
]],
|
||||
]);
|
||||
|
||||
$parcelId = $response['parcels'][0]['id'] ?? null;
|
||||
|
||||
if (! $parcelId) {
|
||||
throw new BoxNowApiException('Box Now delivery request succeeded but returned no parcel id.', $response);
|
||||
}
|
||||
|
||||
$shipments[] = Shipment::create([
|
||||
'order_id' => $order?->id,
|
||||
'carrier' => 'box-now',
|
||||
'tracking_reference' => (string) $parcelId,
|
||||
'meta' => [
|
||||
'delivery_request_id' => $response['id'] ?? null,
|
||||
// Shared by the boxes of one shipment; each box's
|
||||
// own orderNumber is box_order_number.
|
||||
'reference' => $orderNumber,
|
||||
'box_order_number' => $boxNumber,
|
||||
'locker_id' => $destinationLocationId,
|
||||
'cod_amount' => $first ? $codAmount : null,
|
||||
...($count > 1 ? ['box' => $index + 1, 'boxes' => $count] : []),
|
||||
// Who it goes to, as sent (Shipment::recipient()).
|
||||
'recipient' => $recipient->toArray(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// No half shipments: cancel the boxes already created.
|
||||
foreach ($shipments as $shipment) {
|
||||
try {
|
||||
$this->cancelShipment($shipment);
|
||||
} catch (\Throwable $cancelFailure) {
|
||||
report($cancelFailure);
|
||||
}
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $shipments[0];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace Modules\Core\Shipping\Carriers\Elta;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Modules\Core\Shipping\Carriers\Elta\Exceptions\EltaApiException;
|
||||
|
||||
@@ -12,7 +14,8 @@ use Modules\Core\Shipping\Carriers\Elta\Exceptions\EltaApiException;
|
||||
* SOAP transport for ELTA Courier's web services.
|
||||
*
|
||||
* ELTA runs two parallel operation families at the same endpoint
|
||||
* (212.205.47.226:9003). The original CREATEAWB/PELB64VG/PELTT01/PELSTATION
|
||||
* (https://clients.elta-courier.gr; formerly 212.205.47.226:9003, which is
|
||||
* plain HTTP only — see docs/elta.md). The original CREATEAWB/PELB64VG/PELTT01/PELSTATION
|
||||
* set (sourced from the unofficial chinchillabrains/eltaws reference client)
|
||||
* rejects this account's credentials with st_flag=3 ("invalid password").
|
||||
* Decompiling ELTA's own official desktop client (ELTA_PEL.exe, from their
|
||||
@@ -99,6 +102,15 @@ class EltaClient
|
||||
return $this->call('PELTKNEW', $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* PELTKBOX: the PostBox station and service for a postcode — what the
|
||||
* client calls instead of PELTKNEW when "ΕΠΙΔΟΣΗ POST BOX" is ticked.
|
||||
*/
|
||||
public function getPostBoxStation(array $params): EltaResponse
|
||||
{
|
||||
return $this->call('PELTKBOX', $params);
|
||||
}
|
||||
|
||||
private function call(string $operation, array $params): EltaResponse
|
||||
{
|
||||
$namespace = '/'.$operation;
|
||||
@@ -112,11 +124,17 @@ class EltaClient
|
||||
.'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cre="'.$namespace.'">'
|
||||
.'<soapenv:Header/><soapenv:Body><cre:READ>'.$body.'</cre:READ></soapenv:Body></soapenv:Envelope>';
|
||||
|
||||
// The host occasionally times out or answers a one-off 500; two
|
||||
// quick retries cover that. Every call is idempotent except
|
||||
// PELVGNEW, where a retry after a lost response could create a
|
||||
// duplicate pending voucher — rare, and visible in the pending list.
|
||||
$response = Http::withHeaders([
|
||||
'SOAPAction' => 'Get',
|
||||
'Content-Type' => 'text/xml',
|
||||
])
|
||||
->timeout($this->config['timeout'])
|
||||
->retry(2, 500, fn (\Throwable $e) => $e instanceof ConnectionException
|
||||
|| ($e instanceof RequestException && $e->response->serverError()), throw: false)
|
||||
->withBody($envelope, 'text/xml')
|
||||
->post($this->config['service_location']);
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Cache;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Shipping\Carriers\Elta\Exceptions\EltaApiException;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\CreatesStandaloneVouchers;
|
||||
use Modules\Core\Shipping\Contracts\IssuesVoucherOnPrint;
|
||||
use Modules\Core\Shipping\Contracts\SupportsBatchLabels;
|
||||
use Modules\Core\Shipping\Contracts\SupportsExtraServices;
|
||||
@@ -18,6 +19,7 @@ use Modules\Core\Shipping\Contracts\SupportsVoucherLookup;
|
||||
use Modules\Core\Shipping\DTOs\CarrierVoucher;
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\DTOs\TrackingCheckpoint;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
use Modules\Core\Shipping\Enums\ExtraService;
|
||||
use Modules\Core\Shipping\Enums\TrackingStatus;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
@@ -33,7 +35,7 @@ use Modules\Core\Shipping\Models\Shipment;
|
||||
*
|
||||
* Not SupportsManifestBatching — ELTA has no manifest/pickup-list step.
|
||||
*/
|
||||
class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVoucherOnPrint, SupportsBatchLabels, SupportsExtraServices, SupportsTracking, SupportsVoucherListing, SupportsVoucherLookup
|
||||
class EltaFulfillmentService implements CarrierFulfillmentInterface, CreatesStandaloneVouchers, IssuesVoucherOnPrint, SupportsBatchLabels, SupportsExtraServices, SupportsTracking, SupportsVoucherListing, SupportsVoucherLookup
|
||||
{
|
||||
/** PELMANIF2 / PELPARALVGNEW1 page through 100 rows at a time. */
|
||||
private const MAX_PAGES = 50;
|
||||
@@ -53,40 +55,109 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
ExtraService::SaturdayDelivery->value => '004',
|
||||
ExtraService::TimedDelivery->value => '003',
|
||||
ExtraService::SpecialHandling->value => '002',
|
||||
ExtraService::PostBoxDelivery->value => '917',
|
||||
ExtraService::Insurance->value => 'pel_asf_poso',
|
||||
];
|
||||
}
|
||||
|
||||
public function createShipment(Order $order, ShipmentRequest $request): Shipment
|
||||
{
|
||||
$address = $order->shippingAddress;
|
||||
return $this->create($request->recipient ?? VoucherRecipient::fromAddress($order->shippingAddress), (string) $order->reference, $request, $order);
|
||||
}
|
||||
|
||||
/**
|
||||
* A voucher for a parcel that isn't a shop order ("Create voucher" on
|
||||
* Carrier Vouchers): created pending, exactly like an order's.
|
||||
*/
|
||||
public function createStandaloneVoucher(VoucherRecipient $recipient, string $reference, ShipmentRequest $request): Shipment
|
||||
{
|
||||
return $this->create($recipient, $reference, $request);
|
||||
}
|
||||
|
||||
private function create(VoucherRecipient $recipient, string $reference, ShipmentRequest $request, ?Order $order = null): Shipment
|
||||
{
|
||||
// Where the staff fix a missing or wrong phone: the order's
|
||||
// shipping address, or the form they're filling in.
|
||||
$fixIt = $order ? ' — add one to the shipping address.' : '.';
|
||||
$given = $recipient->phones();
|
||||
$weight = $request->weight ?? 0.5;
|
||||
$surcharges = $this->surchargeCodes($request);
|
||||
$surcharges = $this->surchargeSlots($request);
|
||||
|
||||
// The rules ELTA's own client checks before calling (docs/elta.md,
|
||||
// A5) — ELTA itself accepts a pending voucher without them.
|
||||
if ($request->packageCount > 20) {
|
||||
throw new EltaApiException('ELTA allows at most 20 pieces per voucher.');
|
||||
}
|
||||
|
||||
// All three dimensions or none, whole cm up to 999 ("Λάθος
|
||||
// Διαστάσεις"); volumetric weight = X × Y × Z ÷ 5000.
|
||||
$dimensions = $request->dimensions ? array_map('intval', array_values($request->dimensions)) : null;
|
||||
|
||||
if ($dimensions && (count($dimensions) !== 3 || min($dimensions) < 1 || max($dimensions) > 999)) {
|
||||
throw new EltaApiException('ELTA needs all three dimensions, in whole cm from 1 to 999.');
|
||||
}
|
||||
|
||||
$volumetric = $dimensions ? number_format(array_product($dimensions) / 5000, 3, '.', '') : null;
|
||||
|
||||
[$phone, $mobile] = $this->phones((string) $recipient->phone);
|
||||
|
||||
if (filled($recipient->mobile)) {
|
||||
[$otherPhone, $otherMobile] = $this->phones($recipient->mobile);
|
||||
$phone = $phone ?: $otherPhone;
|
||||
$mobile = $mobile ?: $otherMobile;
|
||||
}
|
||||
|
||||
if ($phone === '' && $mobile === '') {
|
||||
throw new EltaApiException('ELTA needs a recipient phone number'.$fixIt);
|
||||
}
|
||||
|
||||
$postBox = $request->has(ExtraService::PostBoxDelivery);
|
||||
|
||||
if ($postBox) {
|
||||
match (true) {
|
||||
$request->has(ExtraService::SpecialHandling) => throw new EltaApiException("ELTA doesn't allow PostBox delivery with special handling."),
|
||||
$request->paymentMode === 'cod' => throw new EltaApiException("ELTA doesn't allow PostBox delivery with cash on delivery."),
|
||||
// ELTA's client: "Χωρίς Κινητό" / "Λάθος Κινητό Τηλέφωνο".
|
||||
$mobile === '' => throw new EltaApiException($order
|
||||
? "ELTA needs a mobile number (10 digits, starting with 69) for PostBox delivery — the shipping address has \"{$given}\"."
|
||||
: "ELTA needs a mobile number (10 digits, starting with 69) for PostBox delivery — \"{$given}\" isn't one."),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
// The customer's delivery instructions, as ELTA's remarks
|
||||
// (ΠΑΡΑΤΗΡΗΣΕΙΣ): one line, at most 90 characters — the ELTA
|
||||
// client's own field limit.
|
||||
$remarks = mb_substr(trim(preg_replace('/\s+/u', ' ', (string) $address->delivery_instructions)), 0, 90);
|
||||
$remarks = mb_substr(trim(preg_replace('/\s+/u', ' ', (string) $recipient->notes)), 0, 90);
|
||||
|
||||
$routing = $postBox
|
||||
? $this->postBoxRouting($recipient->postcode, $recipient->city)
|
||||
: $this->routing($recipient->postcode, $recipient->city);
|
||||
|
||||
$params = [
|
||||
'pel_apost_code' => config('elta.apost_code'),
|
||||
'pel_paral_name' => trim("{$address->first_name} {$address->last_name}"),
|
||||
'pel_paral_address' => $address->line_one,
|
||||
'pel_paral_area' => $address->city,
|
||||
'pel_paral_tk' => $address->postcode,
|
||||
'pel_paral_thl_1' => $address->contact_phone,
|
||||
'pel_paral_thl_2' => '',
|
||||
'pel_service' => '',
|
||||
'pel_paral_name' => $recipient->name,
|
||||
'pel_paral_address' => $recipient->address,
|
||||
'pel_paral_area' => $routing['area'],
|
||||
'pel_paral_tk' => $recipient->postcode,
|
||||
'pel_paral_thl_1' => $phone,
|
||||
'pel_paral_thl_2' => $mobile,
|
||||
'pel_service' => $routing['service'],
|
||||
'pel_baros' => number_format($weight, 3, '.', ''),
|
||||
'pel_baros_xyz' => '',
|
||||
'pel_x' => '',
|
||||
'pel_y' => '',
|
||||
'pel_z' => '',
|
||||
'pel_baros_xyz' => $volumetric ?? '',
|
||||
'pel_x' => $dimensions ? (string) $dimensions[0] : '',
|
||||
'pel_y' => $dimensions ? (string) $dimensions[1] : '',
|
||||
'pel_z' => $dimensions ? (string) $dimensions[2] : '',
|
||||
'pel_temaxia' => (string) $request->packageCount,
|
||||
'pel_paral_sxolia' => $remarks,
|
||||
'pel_sur_1' => $surcharges[0] ?? '',
|
||||
'pel_sur_2' => $surcharges[1] ?? '',
|
||||
'pel_sur_3' => $surcharges[2] ?? '',
|
||||
// Remarks right-aligned in 99 characters, then "2" = parcel or
|
||||
// "1" = envelope — the client's encoding of its mandatory
|
||||
// envelope/parcel choice. ELTA keeps the digit as the
|
||||
// last character of the stored remarks. Padded by characters,
|
||||
// not bytes (sprintf), so Greek remarks line up too.
|
||||
'pel_paral_sxolia' => str_repeat(' ', 99 - mb_strlen($remarks)).$remarks.($request->envelope ? '1' : '2'),
|
||||
'pel_sur_1' => $surcharges[1],
|
||||
'pel_sur_2' => $surcharges[2],
|
||||
'pel_sur_3' => $surcharges[3],
|
||||
// pel_ant_poso is the cash-on-delivery amount; pel_ant_poso1..4
|
||||
// are cheques (with dates) in ELTA's client — never used here.
|
||||
'pel_ant_poso' => '',
|
||||
@@ -105,17 +176,25 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
// Our order reference — comes back in ELTA's lists and tracking,
|
||||
// which is how we find the pending voucher's id below and match
|
||||
// vouchers to orders on the Carrier Vouchers screen.
|
||||
'pel_ref_no' => (string) $order->reference,
|
||||
'pel_ref_no' => $reference,
|
||||
// "0" = save without issuing (see this class's docblock).
|
||||
'pel_insert_flag' => '0',
|
||||
'pel_paral_code' => '',
|
||||
'pel_retur_code' => '',
|
||||
// Special handling needs a return-to party; the client defaults
|
||||
// it to the sender (us). ELTA then issues a return voucher
|
||||
// (return_vg) along with the main one — printed as RETOUR.
|
||||
'pel_retur_code' => $request->has(ExtraService::SpecialHandling) ? (string) config('elta.apost_code') : '',
|
||||
];
|
||||
|
||||
$codAmount = null;
|
||||
|
||||
if ($request->paymentMode === 'cod') {
|
||||
$codAmount = $request->amountToCollect ?? $order->total->decimal;
|
||||
$codAmount = $request->amountToCollect ?? $order?->total->decimal;
|
||||
|
||||
if (! $codAmount) {
|
||||
throw new EltaApiException('Enter the cash on delivery amount.');
|
||||
}
|
||||
|
||||
$params['pel_ant_poso'] = number_format($codAmount, 2, '.', '');
|
||||
}
|
||||
|
||||
@@ -127,16 +206,23 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
// pending list by our reference. Saved even if that lookup fails —
|
||||
// the voucher exists at ELTA either way, and printing retries it.
|
||||
$master = Shipment::create([
|
||||
'order_id' => $order->id,
|
||||
'order_id' => $order?->id,
|
||||
'carrier' => 'elta',
|
||||
'source' => Shipment::SOURCE_CREATED,
|
||||
'tracking_reference' => null,
|
||||
'meta' => [
|
||||
'carrier_id' => $this->findPendingVoucherId((string) $order->reference),
|
||||
'reference' => (string) $order->reference,
|
||||
'carrier_id' => $this->findPendingVoucherId($reference),
|
||||
'reference' => $reference,
|
||||
// Who it goes to, as sent — the label and the lists read it
|
||||
// from here (Shipment::recipient()), never from the order.
|
||||
'recipient' => $recipient->toArray(),
|
||||
'delivery_instructions' => $remarks ?: null,
|
||||
'routing' => $routing['note'],
|
||||
'weight' => $weight,
|
||||
'package_count' => $pieces,
|
||||
// The label's volumetric cell, as the client prints it (ogos_2).
|
||||
'volumetric_weight' => $dimensions ? implode('x', $dimensions).' = '.$volumetric : null,
|
||||
'envelope' => $request->envelope ?: null,
|
||||
'cod_amount' => $codAmount,
|
||||
'services' => $request->serviceValues(),
|
||||
'insurance_amount' => $request->has(ExtraService::Insurance) ? $request->insuranceAmount : null,
|
||||
@@ -150,13 +236,13 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
// no COD or services of their own.
|
||||
for ($piece = 2; $piece <= $pieces; $piece++) {
|
||||
Shipment::create([
|
||||
'order_id' => $order->id,
|
||||
'order_id' => $order?->id,
|
||||
'carrier' => 'elta',
|
||||
'source' => Shipment::SOURCE_CREATED,
|
||||
'tracking_reference' => null,
|
||||
'meta' => [
|
||||
'master_shipment_id' => $master->id,
|
||||
'reference' => (string) $order->reference,
|
||||
'reference' => $reference,
|
||||
'piece' => $piece,
|
||||
'pieces' => $pieces,
|
||||
'weight' => $weight,
|
||||
@@ -170,35 +256,24 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
|
||||
/**
|
||||
* Like ELTA's own client: printing the main voucher of a multi-parcel
|
||||
* send prints every parcel (main first, then each child); printing a
|
||||
* child prints just that parcel. Either way the main voucher is issued
|
||||
* first — that's what gives the children their numbers.
|
||||
* send prints every parcel (main first, then each child), then the
|
||||
* return voucher when ELTA issued one; printing a child prints just
|
||||
* that parcel. Either way the main voucher is issued first — that's
|
||||
* what gives the children their numbers.
|
||||
*/
|
||||
public function printLabel(Shipment $shipment): string
|
||||
{
|
||||
$master = $this->masterOf($shipment);
|
||||
|
||||
$this->issue($master);
|
||||
|
||||
$labels = $shipment->is($master)
|
||||
? collect([$master->refresh(), ...$this->childrenOf($master)])
|
||||
: collect([$shipment->refresh()]);
|
||||
|
||||
$pdf = $this->labelRenderer->renderMany($labels);
|
||||
|
||||
Shipment::whereIn('id', $labels->pluck('id'))->update(['label_printed_at' => now()]);
|
||||
|
||||
return $pdf;
|
||||
return $this->printLabels(collect([$shipment]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Several labels in one PDF. A selected main voucher brings its
|
||||
* children along (as printLabel() does); each parcel is printed once,
|
||||
* main voucher before its children.
|
||||
* children and its return voucher along (as printLabel() does); each
|
||||
* page is printed once, in the client's order.
|
||||
*/
|
||||
public function printLabels(Collection $shipments): string
|
||||
{
|
||||
$labels = collect();
|
||||
$pages = collect();
|
||||
|
||||
foreach ($shipments as $shipment) {
|
||||
$master = $this->masterOf($shipment);
|
||||
@@ -209,13 +284,17 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
: [$shipment->refresh()];
|
||||
|
||||
foreach ($group as $label) {
|
||||
$labels->put($label->id, $label);
|
||||
$pages->put($label->id, $label);
|
||||
}
|
||||
|
||||
if ($shipment->is($master) && filled($master->meta['return_vg'] ?? null)) {
|
||||
$pages->put("retour-{$master->id}", new EltaReturnLabel($master));
|
||||
}
|
||||
}
|
||||
|
||||
$pdf = $this->labelRenderer->renderMany($labels->values());
|
||||
$pdf = $this->labelRenderer->renderMany($pages->values());
|
||||
|
||||
Shipment::whereIn('id', $labels->keys())->update(['label_printed_at' => now()]);
|
||||
Shipment::whereIn('id', $pages->whereInstanceOf(Shipment::class)->keys())->update(['label_printed_at' => now()]);
|
||||
|
||||
return $pdf;
|
||||
}
|
||||
@@ -308,6 +387,8 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
// delivered parcel yet.
|
||||
$isDelivered = filled(trim($response->data['pel_rec']['a_rec_date_time'] ?? '', ' /:'));
|
||||
|
||||
$this->storeDeliveryDetails($shipment, (array) ($response->data['pel_rec'] ?? []));
|
||||
|
||||
return collect(array_values($rows))->map(function (array $row, int $index) use ($rows, $isDelivered) {
|
||||
$isLast = $index === count($rows) - 1;
|
||||
$dateTime = $row['web_date_time'] ?? '';
|
||||
@@ -326,6 +407,38 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* What tracking's voucher record (pel_rec) says beyond the checkpoints:
|
||||
* who received the parcel and when (a_rec_name / a_rec_date_time, blank
|
||||
* until delivery), and the COD remittance — the cash ELTA paid back to
|
||||
* us (a_antik1 / a_antik_text1). Kept on the shipment's meta as ELTA
|
||||
* reports them; saved only when something changed.
|
||||
*
|
||||
* @param array<string, mixed> $record
|
||||
*/
|
||||
private function storeDeliveryDetails(Shipment $shipment, array $record): void
|
||||
{
|
||||
$text = fn (string $key) => trim((string) ($record[$key] ?? ''), " \t\n\r\0\x0B/:") !== ''
|
||||
? trim((string) $record[$key])
|
||||
: null;
|
||||
|
||||
$details = array_filter([
|
||||
'delivered_to' => $text('a_rec_name'),
|
||||
'delivered_at' => $text('a_rec_date_time'),
|
||||
'cod_remitted' => (float) ($record['a_antik1'] ?? 0) > 0 ? (float) $record['a_antik1'] : null,
|
||||
'cod_remittance' => $text('a_antik_text1'),
|
||||
], fn ($value) => $value !== null);
|
||||
|
||||
$meta = $shipment->meta?->toArray() ?? [];
|
||||
|
||||
if ($details === [] || array_intersect_assoc($details, $meta) === $details) {
|
||||
return;
|
||||
}
|
||||
|
||||
$shipment->meta = array_merge($meta, $details);
|
||||
$shipment->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* PELMANIF2 (the client's "Πολλαπλή Αναζήτηση"): every issued voucher
|
||||
* in the date range with its latest status. A second pass with
|
||||
@@ -423,6 +536,7 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
'rec_srv' => $data['rec_srv'] ?? null,
|
||||
'rec_srv_t' => $data['rec_srv_t'] ?? null,
|
||||
'return_vg' => trim((string) ($data['return_vg'] ?? '')) ?: null,
|
||||
'r_ocr_line' => trim((string) ($data['r_ocr_line'] ?? '')) ?: null,
|
||||
'epitagh_vg' => trim((string) ($data['epitagh_vg'] ?? '')) ?: null,
|
||||
]);
|
||||
$shipment->save();
|
||||
@@ -458,25 +572,141 @@ class EltaFulfillmentService implements CarrierFulfillmentInterface, IssuesVouch
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function surchargeCodes(ShipmentRequest $request): array
|
||||
/**
|
||||
* ELTA's surcharge slots are fixed, as its client fills them: special
|
||||
* handling in pel_sur_1, set time in pel_sur_2, Saturday in pel_sur_3.
|
||||
* ELTA stores whatever slot it's sent (it doesn't reorder them), and its
|
||||
* own client only reads Saturday from slot 3.
|
||||
*
|
||||
* @return array{1: string, 2: string, 3: string}
|
||||
*/
|
||||
private function surchargeSlots(ShipmentRequest $request): array
|
||||
{
|
||||
$codes = $this->extraServices();
|
||||
return [
|
||||
1 => match (true) {
|
||||
$request->has(ExtraService::SpecialHandling) => '002',
|
||||
$request->has(ExtraService::PostBoxDelivery) => '917',
|
||||
default => '',
|
||||
},
|
||||
2 => $request->has(ExtraService::TimedDelivery) ? '003' : '',
|
||||
3 => $request->has(ExtraService::SaturdayDelivery) ? '004' : '',
|
||||
];
|
||||
}
|
||||
|
||||
return collect($request->services)
|
||||
->reject(fn (ExtraService $service) => $service === ExtraService::Insurance)
|
||||
->map(fn (ExtraService $service) => $codes[$service->value] ?? null)
|
||||
->filter()
|
||||
->values()
|
||||
->take(3)
|
||||
->all();
|
||||
/**
|
||||
* The recipient's number as ELTA's two phone fields take it: 10 digits
|
||||
* (a +30 / 0030 prefix dropped); a mobile (69…) goes in the mobile
|
||||
* field, anything else in the phone field.
|
||||
*
|
||||
* @return array{0: string, 1: string} [phone, mobile]
|
||||
*/
|
||||
private function phones(string $number): array
|
||||
{
|
||||
$digits = preg_replace('/\D/', '', $number);
|
||||
$digits = preg_replace('/^(0030|30)(?=\d{10}$)/', '', $digits);
|
||||
|
||||
if (strlen($digits) !== 10) {
|
||||
return [substr($digits, 0, 10), ''];
|
||||
}
|
||||
|
||||
return str_starts_with($digits, '69') ? ['', $digits] : [$digits, ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* The service and area ELTA's client would send (docs/elta.md, A4):
|
||||
* PELTKNEW from our station gives the postcode's service. When the
|
||||
* postcode is split into localities, the customer's city is matched to
|
||||
* one — the area becomes "code/title" and the service 231 (hard to
|
||||
* reach) or 201. Without a match the service is left for ELTA to
|
||||
* decide, as before, and the note says so.
|
||||
*
|
||||
* @return array{service: string, area: string, note: ?string}
|
||||
*/
|
||||
private function routing(string $postcode, string $city): array
|
||||
{
|
||||
$response = $this->client->getStation([
|
||||
'pel_tk' => $postcode,
|
||||
'sender_station' => $this->senderStation(),
|
||||
]);
|
||||
|
||||
if ($response->hasError) {
|
||||
throw new EltaApiException("ELTA doesn't accept the postcode {$postcode}: {$response->errorMessage}", $response->data);
|
||||
}
|
||||
|
||||
$fields = $response->data['pel_fields'] ?? [];
|
||||
$localities = array_values(array_filter(
|
||||
(array) ($response->data['a_lview_data'] ?? []),
|
||||
fn ($row) => is_array($row) && filled($row['wloc_code'] ?? null) && trim($row['wloc_code']) !== '0',
|
||||
));
|
||||
|
||||
if ($localities === []) {
|
||||
return ['service' => trim($fields['pel_service'] ?? ''), 'area' => $city, 'note' => null];
|
||||
}
|
||||
|
||||
$wanted = $this->comparable($city);
|
||||
$matches = array_values(array_filter($localities, fn ($row) => $this->comparable($row['wloc_title'] ?? '') === $wanted));
|
||||
|
||||
if (count($matches) !== 1) {
|
||||
return ['service' => '', 'area' => $city, 'note' => "No single ELTA locality matches \"{$city}\" in {$postcode}; ELTA chose the service."];
|
||||
}
|
||||
|
||||
$locality = $matches[0];
|
||||
|
||||
return [
|
||||
'service' => trim($locality['wloc_disp_flag'] ?? '') === '1' ? '231' : '201',
|
||||
'area' => trim($locality['wloc_code']).'/'.trim($locality['wloc_title']),
|
||||
'note' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* PostBox delivery routes through PELTKBOX instead (the client's
|
||||
* "ΕΠΙΔΟΣΗ POST BOX"): it gives the PostBox station's service, or
|
||||
* "Το Τ.Κ. Δεν Εχει PostBox" when the postcode has none.
|
||||
*
|
||||
* @return array{service: string, area: string, note: ?string}
|
||||
*/
|
||||
private function postBoxRouting(string $postcode, string $city): array
|
||||
{
|
||||
$response = $this->client->getPostBoxStation([
|
||||
'pel_tk' => $postcode,
|
||||
'sender_station' => $this->senderStation(),
|
||||
]);
|
||||
|
||||
if ($response->hasError) {
|
||||
throw new EltaApiException("ELTA can't deliver to a PostBox for {$postcode}: {$response->errorMessage}", $response->data);
|
||||
}
|
||||
|
||||
$fields = $response->data['pel_fields'] ?? [];
|
||||
$station = trim($fields['rec_station_t'] ?? '');
|
||||
|
||||
return [
|
||||
'service' => trim($fields['pel_service'] ?? ''),
|
||||
'area' => $city,
|
||||
'note' => $station !== '' ? "PostBox: {$station}" : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Upper-case, without accents or punctuation — ELTA's locality titles
|
||||
* and customers' city names differ in exactly those ways.
|
||||
*/
|
||||
private function comparable(string $text): string
|
||||
{
|
||||
$text = mb_strtoupper(trim($text));
|
||||
$text = strtr($text, ['Ά' => 'Α', 'Έ' => 'Ε', 'Ή' => 'Η', 'Ί' => 'Ι', 'Ό' => 'Ο', 'Ύ' => 'Υ', 'Ώ' => 'Ω', 'Ϊ' => 'Ι', 'Ϋ' => 'Υ']);
|
||||
|
||||
return preg_replace('/[^\p{L}\p{N}]+/u', ' ', $text);
|
||||
}
|
||||
|
||||
private function pendingVoucherId(Shipment $shipment): string
|
||||
{
|
||||
$id = $shipment->meta['carrier_id'] ?? null;
|
||||
|
||||
if (blank($id) && $shipment->order) {
|
||||
$id = $this->findPendingVoucherId((string) $shipment->order->reference);
|
||||
$reference = $shipment->meta['reference'] ?? $shipment->order?->reference;
|
||||
|
||||
if (blank($id) && filled($reference)) {
|
||||
$id = $this->findPendingVoucherId((string) $reference);
|
||||
|
||||
if ($id) {
|
||||
$shipment->meta = array_merge($shipment->meta?->toArray() ?? [], ['carrier_id' => $id]);
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Modules\Core\Shipping\Carriers\Elta;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
use Picqer\Barcode\BarcodeGeneratorPNG;
|
||||
|
||||
@@ -38,6 +40,7 @@ class EltaLabelRenderer
|
||||
'special_handling' => '002 ΕΙΔΙΚΗ ΔΙΑΧΕΙΡΗΣΗ',
|
||||
'timed_delivery' => '003 ΠΡΟΚΑΘΟΡΙΣΜΕΝΗ ΩΡΑ',
|
||||
'saturday_delivery' => '004 ΕΠΙΔΟΣΗ ΣΑΒΒΑΤΟΥ',
|
||||
'post_box_delivery' => '* ΠΡΟΣΟΧΗ PostBox *',
|
||||
];
|
||||
|
||||
public function __construct(private readonly AreaResolver $areaResolver) {}
|
||||
@@ -54,7 +57,7 @@ class EltaLabelRenderer
|
||||
* <head> (the styles are the same for every label) with a page break
|
||||
* between them.
|
||||
*
|
||||
* @param Collection<int, Shipment> $shipments
|
||||
* @param Collection<int, Shipment|EltaReturnLabel> $shipments
|
||||
*/
|
||||
public function renderMany(Collection $shipments): string
|
||||
{
|
||||
@@ -65,7 +68,9 @@ class EltaLabelRenderer
|
||||
$pages = [];
|
||||
|
||||
foreach ($shipments as $shipment) {
|
||||
$data = $this->data($shipment);
|
||||
$data = $shipment instanceof EltaReturnLabel
|
||||
? $this->returnData($shipment->shipment)
|
||||
: $this->data($shipment);
|
||||
|
||||
// A6 prints every parcel on the same label; on A4 the extra
|
||||
// parcels of a multi-parcel send use ELTA's own separate, smaller
|
||||
@@ -113,8 +118,6 @@ class EltaLabelRenderer
|
||||
*/
|
||||
private function data(Shipment $shipment): array
|
||||
{
|
||||
$order = $shipment->order;
|
||||
$address = $order->shippingAddress;
|
||||
$paperSize = config('elta.label_paper_size', 'a4');
|
||||
$piece = $this->pieceOf($shipment);
|
||||
$master = $piece['master'] ?? null;
|
||||
@@ -126,21 +129,30 @@ class EltaLabelRenderer
|
||||
array_filter($shipment->meta?->toArray() ?? [], fn ($value) => $value !== null),
|
||||
);
|
||||
|
||||
// Who it goes to, as saved on the voucher — the label never reads
|
||||
// the order.
|
||||
$recipient = $shipment->recipient() ?? $master?->recipient()
|
||||
?? throw new \RuntimeException("Shipment {$shipment->id} has no recipient to print.");
|
||||
|
||||
// Issuing a pending voucher (PELVG01NEW1) returns the real
|
||||
// destination station and service; vouchers issued before that flow
|
||||
// existed don't have them, so fall back to the postcode lookup.
|
||||
$station = filled($meta['rec_station'] ?? null)
|
||||
? ['code' => $meta['rec_station'], 'name' => $meta['rec_station_t'] ?? '']
|
||||
: (fn ($s) => ['code' => $s->code, 'name' => $s->name])($this->areaResolver->resolve($address->postcode));
|
||||
: (fn ($s) => ['code' => $s->code, 'name' => $s->name])($this->areaResolver->resolve($recipient->postcode));
|
||||
|
||||
$isChild = $piece !== null && $piece['number'] > 1;
|
||||
$masterVoucher = $isChild ? ($master?->tracking_reference ?? $shipment->parent_reference) : null;
|
||||
|
||||
$services = $isChild ? [] : (array) ($meta['services'] ?? []);
|
||||
$surcharges = $this->surchargeSlots($services);
|
||||
$cod = $isChild
|
||||
? $this->childCodFields(($master?->meta['cod_amount'] ?? null) > 0)
|
||||
: $this->codFields(isset($meta['cod_amount']) ? (float) $meta['cod_amount'] : null);
|
||||
$cod = match (true) {
|
||||
$isChild => $this->childCodFields(($master?->meta['cod_amount'] ?? null) > 0),
|
||||
// PostBox never has COD (ELTA refuses it); its antik_1 is the
|
||||
// PostBox warning instead (print_vg()).
|
||||
in_array('post_box_delivery', $services, true) => $this->postBoxCodFields(),
|
||||
default => $this->codFields(isset($meta['cod_amount']) ? (float) $meta['cod_amount'] : null),
|
||||
};
|
||||
|
||||
$dateTime = (string) ($meta['date_time'] ?? '');
|
||||
$occurredAt = strlen($dateTime) >= 12
|
||||
@@ -162,11 +174,11 @@ class EltaLabelRenderer
|
||||
'sender_phone' => config('elta.sender_phone'),
|
||||
'apost_code' => config('elta.apost_code'),
|
||||
|
||||
'recipient_name' => trim("{$address->first_name} {$address->last_name}"),
|
||||
'recipient_address' => $address->line_one,
|
||||
'recipient_postcode' => $address->postcode,
|
||||
'recipient_area' => $address->city,
|
||||
'recipient_phone' => $address->contact_phone,
|
||||
'recipient_name' => $recipient->name,
|
||||
'recipient_address' => $recipient->address,
|
||||
'recipient_postcode' => $recipient->postcode,
|
||||
'recipient_area' => $recipient->city,
|
||||
'recipient_phone' => $recipient->phones(),
|
||||
|
||||
// Mirrors Sydeta.cs::print_vg()'s own dataRow["sender_1..5"] /
|
||||
// dataRow["rec_1..5"] construction: name on its own line, then
|
||||
@@ -182,12 +194,7 @@ class EltaLabelRenderer
|
||||
config('elta.sender_address'),
|
||||
'TK:'.config('elta.sender_postcode').' '.config('elta.sender_area').' ΤΗΛ:'.config('elta.sender_phone'),
|
||||
],
|
||||
'recipient_lines' => [
|
||||
trim("{$address->first_name} {$address->last_name}"),
|
||||
$address->line_one,
|
||||
'TK:'.$address->postcode.' '.$address->city,
|
||||
'ΤΗΛ: '.$address->contact_phone,
|
||||
],
|
||||
'recipient_lines' => $this->partyLines($recipient),
|
||||
|
||||
'date' => $occurredAt->format('d/m/Y'),
|
||||
'time' => $occurredAt->format('H:i'),
|
||||
@@ -217,7 +224,9 @@ class EltaLabelRenderer
|
||||
// voucher (*NZ…GR*) under "ΜASTER ΣΥΔΕΤΑ" on an A4 child.
|
||||
'copy' => $isChild ? ($paperSize === 'a6' ? 'ΠΟΛΛΑΠΛH' : '*'.$masterVoucher.'*') : null,
|
||||
|
||||
'station_apo' => config('elta.origin_station_code'),
|
||||
// Our deposit station: configured, or the one ELTA's login
|
||||
// reported (cached by EltaFulfillmentService::senderStation()).
|
||||
'station_apo' => config('elta.origin_station_code') ?: Cache::get('elta.user_station'),
|
||||
'station_pros' => $station['code'],
|
||||
'station_pros_title' => $station['name'],
|
||||
|
||||
@@ -238,7 +247,7 @@ class EltaLabelRenderer
|
||||
|
||||
// The reference we send ELTA as pel_ref_no (order reference;
|
||||
// older vouchers were sent the order id).
|
||||
'order_reference' => $isChild ? null : (string) $order->reference,
|
||||
'order_reference' => $isChild ? null : $shipment->reference(),
|
||||
|
||||
// ΠΑΡΑΤΗΡΗΣΕΙΣ: the remarks we sent ELTA (the customer's delivery
|
||||
// instructions), in the client's 27-character lines — up to 3
|
||||
@@ -256,7 +265,10 @@ class EltaLabelRenderer
|
||||
// we never send any, so the box stays empty like the client's.
|
||||
'volumetric_weight' => $meta['volumetric_weight'] ?? null,
|
||||
|
||||
'eltaLogo' => $this->logoDataUri(),
|
||||
'eltaLogo' => $this->logoDataUri('elta-courier-logo.png'),
|
||||
// The A4 payment stub's "Hellenic Post" logo (the RDLC's
|
||||
// Point5_ELTACourier_ΑποστολήμαςΕσείς image).
|
||||
'hellenicPostLogo' => $this->logoDataUri('elta-logo.png'),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -275,6 +287,8 @@ class EltaLabelRenderer
|
||||
|
||||
if ($has('special_handling')) {
|
||||
$slots[1] = self::SERVICE_TEXT['special_handling'];
|
||||
} elseif ($has('post_box_delivery')) {
|
||||
$slots[1] = self::SERVICE_TEXT['post_box_delivery'];
|
||||
}
|
||||
|
||||
if ($has('timed_delivery')) {
|
||||
@@ -327,11 +341,95 @@ class EltaLabelRenderer
|
||||
...$lines,
|
||||
'antik_lines' => array_values(array_filter($lines)),
|
||||
'antik_minima' => '* ΠΡΟΣΟΧΗ ΑΝΤΙΚΑΤΑΒΟΛΗ *',
|
||||
'apodiksi' => '* Απόδειξη Είσπαξης *',
|
||||
'apodiksi' => '* Απόδειξη Είσπραξης *',
|
||||
'antik_poso' => $sent,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* rec_1..4 as print_vg() builds them: name, address, "TK:" line, phones
|
||||
* (also the RETOUR voucher's sender lines).
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function partyLines(VoucherRecipient $recipient): array
|
||||
{
|
||||
return [
|
||||
$recipient->name,
|
||||
$recipient->address,
|
||||
'TK:'.$recipient->postcode.' '.$recipient->city,
|
||||
'ΤΗΛ: '.$recipient->phones(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A PostBox voucher's COD column: just the PostBox warning (antik_1).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function postBoxCodFields(): array
|
||||
{
|
||||
return [
|
||||
...$this->codFields(null),
|
||||
'antik_1' => self::SERVICE_TEXT['post_box_delivery'],
|
||||
'antik_lines' => [self::SERVICE_TEXT['post_box_delivery']],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The return voucher ("RETOUR", docs/elta.md B6), as the client fills
|
||||
* it from the main voucher: the parties swap (our customer sends it
|
||||
* back to us, the return-to party), it's charged to the recipient,
|
||||
* 0.100 kg, one piece, no COD, and the remarks name the main voucher.
|
||||
* Service 461 when the main voucher's service is in-city (1xx), else
|
||||
* 462. It goes from the main voucher's destination station back to
|
||||
* ours.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function returnData(Shipment $master): array
|
||||
{
|
||||
$data = $this->data($master);
|
||||
$meta = $master->meta?->toArray() ?? [];
|
||||
|
||||
$returnVoucher = (string) $meta['return_vg'];
|
||||
$ocrLine = (string) ($meta['r_ocr_line'] ?? '');
|
||||
$inCity = str_starts_with((string) ($meta['rec_srv'] ?? ''), '1');
|
||||
|
||||
return [
|
||||
...$data,
|
||||
...$this->codFields(null),
|
||||
|
||||
'sender_lines' => $this->partyLines($master->recipient()),
|
||||
'recipient_lines' => $data['sender_lines'],
|
||||
|
||||
'voucher_no' => $returnVoucher,
|
||||
'barcode_voucher' => $this->barcodeDataUri(new BarcodeGeneratorPNG(), $returnVoucher),
|
||||
'ocr_line' => $ocrLine,
|
||||
'ocr_reference' => strlen($ocrLine) >= 14 ? substr($ocrLine, 1, 13) : null,
|
||||
|
||||
'service_code' => $inCity ? '461' : '462',
|
||||
'service_name' => $inCity ? 'RETOUR ΕΝΤΟΣ ΠΟΛΗΣ' : 'RETOUR ΠΟΛΗ ΠΟΛΗ',
|
||||
'xreosi' => 'ΧΡΕΩΣΗ ΠΑΡΑΛΗΠΤΗ ΠΙΣΤΩΣΗ',
|
||||
'copy' => 'RETOUR',
|
||||
|
||||
'station_apo' => $data['station_pros'],
|
||||
'station_pros' => $data['station_apo'],
|
||||
'station_pros_title' => '',
|
||||
|
||||
'weight' => '0.100',
|
||||
'package_count' => 1,
|
||||
'package_label' => '1',
|
||||
'piece_label' => '001/001',
|
||||
'multiPiece' => false,
|
||||
'polaplo' => null,
|
||||
'isChild' => false,
|
||||
|
||||
'sur_1' => null, 'sur_2' => null, 'sur_3' => null, 'sur_4' => null,
|
||||
'sxolia' => array_slice(mb_str_split('ΣΥΔΕΤΑ '.$master->tracking_reference.' Χρέωση Πελάτη '.config('elta.apost_code'), 27), 0, 3),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A child parcel's COD text (print_child()): only the warning, never the
|
||||
* amount — the cash is collected against the main voucher.
|
||||
@@ -404,9 +502,9 @@ class EltaLabelRenderer
|
||||
* vendor:publish, which isn't guaranteed to have run, and dompdf
|
||||
* needs either a real filesystem path or a working absolute URL.
|
||||
*/
|
||||
private function logoDataUri(): string
|
||||
private function logoDataUri(string $file): string
|
||||
{
|
||||
$path = __DIR__.'/../../../../resources/logos/elta-courier-logo.png';
|
||||
$path = __DIR__.'/../../../../resources/logos/'.$file;
|
||||
|
||||
return 'data:image/png;base64,'.base64_encode(file_get_contents($path));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Carriers\Elta;
|
||||
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
/**
|
||||
* A page for the main voucher's return voucher ("RETOUR", docs/elta.md B6):
|
||||
* ELTA issues one along with a special-handling voucher (meta.return_vg),
|
||||
* and its client prints it after the voucher and its parcels. It isn't a
|
||||
* shipment of its own, so EltaLabelRenderer gets the main voucher wrapped
|
||||
* in this.
|
||||
*/
|
||||
final class EltaReturnLabel
|
||||
{
|
||||
public function __construct(public readonly Shipment $shipment) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Contracts;
|
||||
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
/**
|
||||
* A carrier whose vouchers can be created without an order — from the
|
||||
* Carrier Vouchers screen's "Create voucher", for a parcel that isn't a
|
||||
* shop order. The voucher is an ordinary created shipment with no
|
||||
* order_id: it prints, cancels and tracks like any other, and can be
|
||||
* linked to an order later.
|
||||
*/
|
||||
interface CreatesStandaloneVouchers
|
||||
{
|
||||
/**
|
||||
* @param string $reference sent to the carrier as our reference
|
||||
* (it comes back in its lists and tracking).
|
||||
*/
|
||||
public function createStandaloneVoucher(VoucherRecipient $recipient, string $reference, ShipmentRequest $request): Shipment;
|
||||
}
|
||||
@@ -38,6 +38,18 @@ class ShipmentRequest
|
||||
public readonly ?float $insuranceAmount = null,
|
||||
public readonly ?string $deliveryUntil = null,
|
||||
public readonly ?string $trackingReference = null,
|
||||
/** An envelope (documents) rather than a parcel — ELTA only. */
|
||||
public readonly bool $envelope = false,
|
||||
/** @var array{0: int, 1: int, 2: int}|null length × width × height in cm, for volumetric weight — ELTA only. */
|
||||
public readonly ?array $dimensions = null,
|
||||
/** The parcel's value, for a voucher without an order (an order's is its total) — Box Now's invoiceValue. */
|
||||
public readonly ?float $value = null,
|
||||
/**
|
||||
* Who it goes to, as staff confirmed it in the Create Shipment form —
|
||||
* sent instead of the order's shipping address, which stays as the
|
||||
* customer entered it. Null = the shipping address as is.
|
||||
*/
|
||||
public readonly ?VoucherRecipient $recipient = null,
|
||||
) {}
|
||||
|
||||
public function has(ExtraService $service): bool
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\DTOs;
|
||||
|
||||
use Lunar\Models\Contracts\OrderAddress;
|
||||
|
||||
/**
|
||||
* Who a voucher goes to — from an order's shipping address, or typed in
|
||||
* by staff for a voucher that isn't for an order
|
||||
* (CreatesStandaloneVouchers). Saved on the voucher (meta.recipient) when
|
||||
* it's created, so labels and lists read it from there, never from the
|
||||
* order.
|
||||
*/
|
||||
class VoucherRecipient
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $name,
|
||||
public readonly string $address,
|
||||
public readonly string $postcode,
|
||||
public readonly string $city,
|
||||
public readonly ?string $phone = null,
|
||||
public readonly ?string $mobile = null,
|
||||
/** The remarks for the courier (an order's delivery instructions). */
|
||||
public readonly ?string $notes = null,
|
||||
/** Box Now sends the locker's pickup code here. */
|
||||
public readonly ?string $email = null,
|
||||
) {}
|
||||
|
||||
public static function fromAddress(OrderAddress $address): self
|
||||
{
|
||||
return new self(
|
||||
name: trim("{$address->first_name} {$address->last_name}"),
|
||||
address: (string) $address->line_one,
|
||||
postcode: (string) $address->postcode,
|
||||
city: (string) $address->city,
|
||||
phone: $address->contact_phone,
|
||||
notes: $address->delivery_instructions,
|
||||
email: $address->contact_email,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, ?string> $data as toArray() gives it
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
name: (string) ($data['name'] ?? ''),
|
||||
address: (string) ($data['address'] ?? ''),
|
||||
postcode: (string) ($data['postcode'] ?? ''),
|
||||
city: (string) ($data['city'] ?? ''),
|
||||
phone: $data['phone'] ?? null,
|
||||
mobile: $data['mobile'] ?? null,
|
||||
notes: $data['notes'] ?? null,
|
||||
email: $data['email'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ?string>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'name' => $this->name,
|
||||
'address' => $this->address,
|
||||
'postcode' => $this->postcode,
|
||||
'city' => $this->city,
|
||||
'phone' => $this->phone,
|
||||
'mobile' => $this->mobile,
|
||||
'notes' => $this->notes,
|
||||
'email' => $this->email,
|
||||
];
|
||||
}
|
||||
|
||||
/** Both numbers, as they're printed on the label ("ΤΗΛ: …"). */
|
||||
public function phones(): string
|
||||
{
|
||||
return trim($this->phone.' '.$this->mobile);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ enum ExtraService: string
|
||||
case Protocol = 'protocol';
|
||||
case Refrigerated = 'refrigerated';
|
||||
case ExchangePackage = 'exchange_package';
|
||||
/** Delivered to a PostBox (parcel locker / post office box) instead of the address. */
|
||||
case PostBoxDelivery = 'post_box_delivery';
|
||||
|
||||
/**
|
||||
* Admin-facing only (staff pick these), so plain English like the rest
|
||||
@@ -42,6 +44,7 @@ enum ExtraService: string
|
||||
self::Protocol => 'Protocol',
|
||||
self::Refrigerated => 'Refrigerated',
|
||||
self::ExchangePackage => 'Exchange package',
|
||||
self::PostBoxDelivery => 'PostBox delivery',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -250,6 +250,25 @@ class OrderShipmentsExtension extends ViewPageExtension
|
||||
$parts[] = 'Manual voucher';
|
||||
}
|
||||
|
||||
// Carrier-reported extras (ELTA so far): its routing note, the
|
||||
// return voucher issued with special handling, who received the
|
||||
// parcel and when, and the COD cash paid back to us.
|
||||
if ($routing = $record->meta['routing'] ?? null) {
|
||||
$parts[] = $routing;
|
||||
}
|
||||
|
||||
if ($returnVoucher = $record->meta['return_vg'] ?? null) {
|
||||
$parts[] = 'Return voucher '.$returnVoucher;
|
||||
}
|
||||
|
||||
if ($deliveredTo = $record->meta['delivered_to'] ?? null) {
|
||||
$parts[] = trim('Received by '.$deliveredTo.' '.($record->meta['delivered_at'] ?? ''));
|
||||
}
|
||||
|
||||
if ($remitted = $record->meta['cod_remitted'] ?? null) {
|
||||
$parts[] = trim('COD paid back: €'.number_format((float) $remitted, 2).' '.($record->meta['cod_remittance'] ?? ''));
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -24,8 +23,8 @@ 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\Filament\Support\VoucherForm;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
use Modules\Core\Shipping\Support\BoxNowShipping;
|
||||
use Modules\Core\Shipping\Support\WeightCalculator;
|
||||
use Throwable;
|
||||
|
||||
@@ -54,28 +53,24 @@ use Throwable;
|
||||
* 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
|
||||
* per-package weight concept — one Weight value is sent alongside
|
||||
* Item_Quantity in the same ACS_Create_Voucher call, see
|
||||
* AcsFulfillmentService::createShipment()), pre-filled from the order's
|
||||
* own line weights (Modules\Core\Shipping\Support\WeightCalculator) but
|
||||
* still staff-editable, plus a package count (ShipmentRequest::
|
||||
* $packageCount) — more than 1 issues a main voucher plus a
|
||||
* multi-part sub-voucher per extra package (persistMultipartVouchers()),
|
||||
* each recorded as its own Shipment row sharing the same total weight in
|
||||
* meta. Box Now, which bills by compartment size rather than
|
||||
* weight, gets a repeatable list of boxes (one row per physical parcel,
|
||||
* each with its own S/M/L size) instead — see
|
||||
* Modules\Core\Shipping\Carriers\BoxNow\BoxNowFulfillmentService for how
|
||||
* multiple boxes become multiple Shipment rows from one delivery request.
|
||||
* Box Now's locker field defaults from the shopper's own checkout
|
||||
* selection ($order->shippingAddress->meta['box_now_locker']) when present,
|
||||
* but stays editable — staff can override to a different locker (e.g. the
|
||||
* customer's choice turns out to be unavailable) or fill it in manually for
|
||||
* an order placed before the checkout locker picker existed.
|
||||
* normalized ExtraService list the carrier offers. The form depends on
|
||||
* the order's carrier (OrderFulfillmentService::carrierFor()):
|
||||
*
|
||||
* - ELTA and Box Now (CreatesStandaloneVouchers) get the full voucher
|
||||
* form — Modules\Core\Shipping\Filament\Support\VoucherForm, the one
|
||||
* Carrier Vouchers' "Create voucher" uses — prefilled from the order:
|
||||
* recipient and delivery instructions from the shipping address, weight
|
||||
* from the order lines (WeightCalculator), Box Now's locker from the
|
||||
* customer's checkout choice, cash on delivery read-only from the
|
||||
* payment method. What staff change there (a phone, a typo in the
|
||||
* address, another locker) goes to the carrier only
|
||||
* (ShipmentRequest::$recipient); the order keeps what the customer
|
||||
* entered.
|
||||
* - A manual carrier gets its optional tracking number and a package
|
||||
* count.
|
||||
* - ACS gets a total weight (prefilled from the line weights) and a
|
||||
* package count — more than 1 issues a main voucher plus a sub-voucher
|
||||
* per extra package, each its own Shipment row.
|
||||
*
|
||||
* "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
|
||||
@@ -121,10 +116,15 @@ class OrderViewExtension extends ViewPageExtension
|
||||
->label('Create Shipment')
|
||||
->icon('heroicon-o-truck')
|
||||
->modalSubmitActionLabel('Create Shipment')
|
||||
->modalWidth(fn (Order $record) => VoucherForm::handles($this->service()->carrierFor($record)) ? '3xl' : null)
|
||||
->schema(function (Order $record) {
|
||||
$carrier = $this->service()->carrierFor($record);
|
||||
$isBoxNow = BoxNowShipping::isDriver($carrier);
|
||||
$lockerId = $record->shippingAddress?->meta['box_now_locker']['locationId'] ?? null;
|
||||
|
||||
// ELTA and Box Now: the full voucher form, prefilled from the
|
||||
// order (the same one Carrier Vouchers' "Create voucher" uses).
|
||||
if (VoucherForm::handles($carrier)) {
|
||||
return VoucherForm::schema($record);
|
||||
}
|
||||
|
||||
if ($carrier === 'manual') {
|
||||
return [
|
||||
@@ -142,47 +142,22 @@ class OrderViewExtension extends ViewPageExtension
|
||||
];
|
||||
}
|
||||
|
||||
if (! $isBoxNow) {
|
||||
return [...[
|
||||
TextInput::make('weight')
|
||||
->label('Total weight (kg)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->default(fn () => round(WeightCalculator::totalKg($record->lines), 2) ?: null)
|
||||
->helperText("Calculated from the order's line weights — adjust if needed, or leave blank to use the carrier's default. One figure for the whole shipment, not per package."),
|
||||
TextInput::make('package_count')
|
||||
->label('Number of packages')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->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)];
|
||||
}
|
||||
|
||||
// Weight-billed carriers without the voucher form (ACS).
|
||||
return [...[
|
||||
TextInput::make('destination_location_id')
|
||||
->label('Box Now locker ID')
|
||||
->default($lockerId)
|
||||
TextInput::make('weight')
|
||||
->label('Total weight (kg)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->default(fn () => round(WeightCalculator::totalKg($record->lines), 2) ?: null)
|
||||
->helperText("Calculated from the order's line weights — adjust if needed, or leave blank to use the carrier's default. One figure for the whole shipment, not per package."),
|
||||
TextInput::make('package_count')
|
||||
->label('Number of packages')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->default(1)
|
||||
->required()
|
||||
->helperText($lockerId
|
||||
? 'Set by the customer at checkout — override if the parcel needs to go to a different locker.'
|
||||
: 'No locker was selected at checkout — enter it manually.'),
|
||||
Repeater::make('boxes')
|
||||
->label('Boxes')
|
||||
->schema([
|
||||
Select::make('size')
|
||||
->label('Size')
|
||||
->options(['S' => 'Small', 'M' => 'Medium', 'L' => 'Large'])
|
||||
->default('S')
|
||||
->native(false)
|
||||
->required(),
|
||||
])
|
||||
->defaultItems(1)
|
||||
->addActionLabel('Add another box')
|
||||
->minItems(1)
|
||||
->helperText('One row per physical parcel — Box Now ships by compartment size, not weight.'),
|
||||
->helperText('More than 1 issues a main voucher plus a sub-voucher per extra package, all sharing the total weight above.'),
|
||||
], ...$this->extraServiceFields($record)];
|
||||
})
|
||||
->action(function (Order $record, array $data, Action $action) {
|
||||
@@ -203,9 +178,10 @@ class OrderViewExtension extends ViewPageExtension
|
||||
|
||||
$services = array_map(fn (string $value) => ExtraService::from($value), $data['services'] ?? []);
|
||||
|
||||
$result = $this->service()->createShipment(
|
||||
$record,
|
||||
new ShipmentRequest(
|
||||
$request = VoucherForm::handles($this->service()->carrierFor($record))
|
||||
// The recipient as staff confirmed it in the form.
|
||||
? VoucherForm::request($data, $isCod ? $record->total->decimal : null, VoucherForm::recipient($data))
|
||||
: new ShipmentRequest(
|
||||
weight: filled($data['weight'] ?? null) ? (float) $data['weight'] : null,
|
||||
packageCount: (int) ($data['package_count'] ?? 1),
|
||||
destinationLocationId: $data['destination_location_id'] ?? null,
|
||||
@@ -220,8 +196,9 @@ class OrderViewExtension extends ViewPageExtension
|
||||
? ($data['delivery_until'] ?? null)
|
||||
: null,
|
||||
trackingReference: $data['tracking_reference'] ?? null,
|
||||
),
|
||||
);
|
||||
);
|
||||
|
||||
$result = $this->service()->createShipment($record, $request);
|
||||
|
||||
$this->notify($result);
|
||||
// The page still holds the shipments loaded before this action.
|
||||
|
||||
@@ -76,11 +76,24 @@ class CarrierVoucherResource extends Resource
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
return parent::getEloquentQuery()
|
||||
->whereNotNull('tracking_reference')
|
||||
return self::vouchers(parent::getEloquentQuery())
|
||||
->with(['order.shippingAddress', 'shipmentInfo']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vouchers with a number, plus ours still waiting for one (an ELTA
|
||||
* voucher gets its number when printed) so they can be printed from
|
||||
* here too.
|
||||
*/
|
||||
public static function vouchers(Builder $query): Builder
|
||||
{
|
||||
return $query->where(fn (Builder $q) => $q
|
||||
->whereNotNull('tracking_reference')
|
||||
->orWhere(fn (Builder $pending) => $pending
|
||||
->where('source', Shipment::SOURCE_CREATED)
|
||||
->whereNull('cancelled_at')));
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
@@ -88,8 +101,12 @@ class CarrierVoucherResource extends Resource
|
||||
->columns([
|
||||
TextColumn::make('tracking_reference')
|
||||
->label('Tracking number')
|
||||
->placeholder('Not issued yet')
|
||||
->description(fn (Shipment $record) => $record->parcelDescription())
|
||||
->copyable(),
|
||||
TextColumn::make('carrier')
|
||||
->label('Carrier')
|
||||
->formatStateUsing(fn (Shipment $record) => $record->carrierLabel()),
|
||||
TextColumn::make('source')
|
||||
->label('Source')
|
||||
->badge()
|
||||
@@ -98,12 +115,12 @@ class CarrierVoucherResource extends Resource
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->state(fn (Shipment $record) => self::status($record))
|
||||
->placeholder('No updates yet')
|
||||
->placeholder('None yet')
|
||||
->badge()
|
||||
->color(fn (Shipment $record) => self::statusColor($record)),
|
||||
TextColumn::make('order.reference')
|
||||
->label('Order')
|
||||
->placeholder('Not linked'),
|
||||
->placeholder('None'),
|
||||
TextColumn::make('recipient')
|
||||
->label('Recipient')
|
||||
->state(fn (Shipment $record) => self::recipient($record))
|
||||
@@ -114,6 +131,9 @@ class CarrierVoucherResource extends Resource
|
||||
->where('tracking_reference', 'ilike', "%{$search}%")
|
||||
->orWhere('meta->recipient_name', 'ilike', "%{$search}%")
|
||||
->orWhere('meta->phone', 'ilike', "%{$search}%")
|
||||
->orWhere('meta->recipient->name', 'ilike', "%{$search}%")
|
||||
->orWhere('meta->recipient->phone', 'ilike', "%{$search}%")
|
||||
->orWhere('meta->recipient->mobile', 'ilike', "%{$search}%")
|
||||
->orWhereHas('order', fn (Builder $order) => $order
|
||||
->where('reference', 'ilike', "%{$search}%")
|
||||
->orWhereHas('shippingAddress', fn (Builder $address) => $address
|
||||
@@ -131,6 +151,7 @@ class CarrierVoucherResource extends Resource
|
||||
SelectFilter::make('source')->options(self::SOURCES),
|
||||
])
|
||||
->recordActions([
|
||||
self::printAction(),
|
||||
ViewAction::make(),
|
||||
]);
|
||||
}
|
||||
@@ -145,6 +166,7 @@ class CarrierVoucherResource extends Resource
|
||||
->formatStateUsing(fn (Shipment $record) => $record->carrierLabel()),
|
||||
TextEntry::make('tracking_reference')
|
||||
->label('Voucher')
|
||||
->placeholder('Not issued yet — printing issues it')
|
||||
->helperText(fn (Shipment $record) => $record->parcelDescription())
|
||||
->copyable(),
|
||||
TextEntry::make('source')
|
||||
@@ -188,12 +210,30 @@ class CarrierVoucherResource extends Resource
|
||||
->state(fn (Shipment $record) => self::recipient($record))
|
||||
->placeholder('—'),
|
||||
TextEntry::make('postcode')
|
||||
->state(fn (Shipment $record) => $record->meta['postcode'] ?? $record->order?->shippingAddress?->postcode)
|
||||
->state(fn (Shipment $record) => self::postcode($record))
|
||||
->placeholder('—'),
|
||||
TextEntry::make('phone')
|
||||
->state(fn (Shipment $record) => self::phone($record))
|
||||
->placeholder('—'),
|
||||
]),
|
||||
// What the carrier's tracking reports beyond the checkpoints
|
||||
// (ELTA's pel_rec) — filled in by the tracking polls.
|
||||
Section::make('Delivery')
|
||||
->columns(3)
|
||||
->schema([
|
||||
TextEntry::make('meta.delivered_to')->label('Received by')->placeholder('—'),
|
||||
TextEntry::make('meta.delivered_at')->label('Received at')->placeholder('—'),
|
||||
TextEntry::make('cod_remitted')
|
||||
->label('COD paid back')
|
||||
->state(fn (Shipment $record) => ($amount = $record->meta['cod_remitted'] ?? null)
|
||||
? trim('€'.number_format((float) $amount, 2).' '.($record->meta['cod_remittance'] ?? ''))
|
||||
: null)
|
||||
->placeholder('—'),
|
||||
TextEntry::make('meta.return_vg')->label('Return voucher')->placeholder('—'),
|
||||
])
|
||||
->visible(fn (Shipment $record) => filled($record->meta['delivered_to'] ?? null)
|
||||
|| filled($record->meta['cod_remitted'] ?? null)
|
||||
|| filled($record->meta['return_vg'] ?? null)),
|
||||
Section::make('Order')
|
||||
->schema([
|
||||
TextEntry::make('order.reference')
|
||||
@@ -241,6 +281,21 @@ class CarrierVoucherResource extends Resource
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the voucher's label (the same signed link as the order page and
|
||||
* Pending Vouchers) — for vouchers created here, from an order or with
|
||||
* "Create voucher". Carrier-reported and typed-in vouchers have no label
|
||||
* of ours to print.
|
||||
*/
|
||||
public static function printAction(): Action
|
||||
{
|
||||
return Action::make('print')
|
||||
->label('Print')
|
||||
->icon('heroicon-o-printer')
|
||||
->url(fn (Shipment $record) => ShipmentResource::labelUrl($record), shouldOpenInNewTab: true)
|
||||
->visible(fn (Shipment $record) => $record->hasCarrierLabel());
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches an unlinked voucher to an order (suggestions first), from the
|
||||
* view page.
|
||||
@@ -328,20 +383,25 @@ class CarrierVoucherResource extends Resource
|
||||
: $record->order->reference;
|
||||
}
|
||||
|
||||
/*
|
||||
* A synced voucher's recipient is what the carrier reported
|
||||
* (meta.recipient_name / phone / postcode); our own vouchers' is the
|
||||
* one saved when they were created (Shipment::recipient()).
|
||||
*/
|
||||
|
||||
private static function phone(Shipment $record): ?string
|
||||
{
|
||||
return $record->meta['phone'] ?? $record->order?->shippingAddress?->contact_phone;
|
||||
return $record->meta['phone'] ?? ($record->recipient()?->phones() ?: null);
|
||||
}
|
||||
|
||||
private static function recipient(Shipment $record): ?string
|
||||
{
|
||||
if ($name = $record->meta['recipient_name'] ?? null) {
|
||||
return $name;
|
||||
}
|
||||
return $record->meta['recipient_name'] ?? ($record->recipient()?->name ?: null);
|
||||
}
|
||||
|
||||
$address = $record->order?->shippingAddress;
|
||||
|
||||
return $address ? trim("{$address->first_name} {$address->last_name}") : null;
|
||||
private static function postcode(Shipment $record): ?string
|
||||
{
|
||||
return $record->meta['postcode'] ?? ($record->recipient()?->postcode ?: null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources\CarrierVoucherResource\Actions;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\CreatesStandaloneVouchers;
|
||||
use Modules\Core\Shipping\Contracts\IssuesVoucherOnPrint;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
|
||||
use Modules\Core\Shipping\Filament\Support\VoucherForm;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* "Create voucher" on Carrier Vouchers: a voucher that isn't for an order
|
||||
* (a replacement part, documents, a parcel for a partner), with every
|
||||
* field the carrier takes (VoucherForm — the same form an order's Create
|
||||
* Shipment uses, there prefilled from the order). Offered for carriers
|
||||
* implementing CreatesStandaloneVouchers. The voucher is an ordinary
|
||||
* created shipment without an order: an ELTA one is pending until
|
||||
* printed, so it waits on Pending Vouchers like any other, and it can be
|
||||
* linked to an order later from its view page.
|
||||
*/
|
||||
class CreateVoucherAction
|
||||
{
|
||||
public static function make(): Action
|
||||
{
|
||||
return Action::make('create_voucher')
|
||||
->label('Create voucher')
|
||||
->icon('heroicon-o-plus')
|
||||
->modalHeading('Create a voucher')
|
||||
->modalDescription('For a parcel that isn\'t a shop order. It\'s created with the carrier straight away.')
|
||||
->modalSubmitActionLabel('Create voucher')
|
||||
->modalWidth('3xl')
|
||||
->schema(VoucherForm::schema())
|
||||
->action(fn (array $data, Action $action) => self::create($data, $action))
|
||||
->visible(fn () => VoucherForm::carriers() !== []);
|
||||
}
|
||||
|
||||
private static function create(array $data, Action $action): void
|
||||
{
|
||||
$service = app(CarrierFulfillmentInterface::class, ['carrier' => $data['carrier']]);
|
||||
$cod = (float) ($data['cod_amount'] ?? 0) > 0 ? (float) $data['cod_amount'] : null;
|
||||
|
||||
try {
|
||||
if (! $service instanceof CreatesStandaloneVouchers) {
|
||||
throw new \RuntimeException('This carrier can\'t create vouchers without an order.');
|
||||
}
|
||||
|
||||
$shipment = $service->createStandaloneVoucher(
|
||||
VoucherForm::recipient($data),
|
||||
trim($data['reference']),
|
||||
VoucherForm::request($data, $cod),
|
||||
);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()->title('Failed to create the voucher: '.$e->getMessage())->danger()->send();
|
||||
|
||||
// Keep the form open with what was typed.
|
||||
$action->halt();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// ELTA vouchers get their number when printed, so they wait on
|
||||
// Pending Vouchers; offer the print straight away.
|
||||
$pending = $service instanceof IssuesVoucherOnPrint && blank($shipment->tracking_reference);
|
||||
|
||||
Notification::make()
|
||||
->title($pending ? 'Voucher created — it gets its number when printed.' : "Voucher {$shipment->tracking_reference} created.")
|
||||
->body($pending ? 'Print it now, or later from Pending Vouchers.' : null)
|
||||
->success()
|
||||
->persistent()
|
||||
->actions([
|
||||
Action::make('print')
|
||||
->label('Print')
|
||||
->url(ShipmentResource::labelUrl($shipment), shouldOpenInNewTab: true),
|
||||
Action::make('pending')
|
||||
->label('Pending Vouchers')
|
||||
->url(ShipmentResource::getUrl('index'))
|
||||
->visible($pending),
|
||||
])
|
||||
->send();
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -13,6 +13,7 @@ use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\SupportsVoucherLookup;
|
||||
use Modules\Core\Shipping\Filament\Resources\CarrierVoucherResource;
|
||||
use Modules\Core\Shipping\Filament\Resources\CarrierVoucherResource\Actions\CreateVoucherAction;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
use Modules\Core\Shipping\Services\CarrierVoucherSync;
|
||||
use Throwable;
|
||||
@@ -29,12 +30,12 @@ class ListCarrierVouchers extends ListRecords
|
||||
'all' => Tab::make('All'),
|
||||
'unlinked' => Tab::make('Unlinked')
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->whereNull('order_id'))
|
||||
->badge(fn () => Shipment::whereNotNull('tracking_reference')->whereNull('order_id')->count() ?: null),
|
||||
->badge(fn () => CarrierVoucherResource::vouchers(Shipment::query())->whereNull('order_id')->count() ?: null),
|
||||
'returns' => Tab::make('Returns')
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->where(fn (Builder $q) => $q
|
||||
->where('meta->is_return', true)
|
||||
->orWhere('meta->reported_return', true)))
|
||||
->badge(fn () => Shipment::whereNotNull('tracking_reference')
|
||||
->badge(fn () => CarrierVoucherResource::vouchers(Shipment::query())
|
||||
->where(fn (Builder $q) => $q->where('meta->is_return', true)->orWhere('meta->reported_return', true))
|
||||
->count() ?: null),
|
||||
];
|
||||
@@ -43,6 +44,7 @@ class ListCarrierVouchers extends ListRecords
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateVoucherAction::make(),
|
||||
Action::make('lookup')
|
||||
->label('Look up voucher')
|
||||
->icon('heroicon-o-magnifying-glass')
|
||||
|
||||
@@ -14,12 +14,13 @@ class ViewCarrierVoucher extends ViewRecord
|
||||
|
||||
public function getTitle(): string
|
||||
{
|
||||
return 'Voucher '.$this->getRecord()->tracking_reference;
|
||||
return 'Voucher '.($this->getRecord()->tracking_reference ?? '(not issued yet)');
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CarrierVoucherResource::printAction(),
|
||||
Action::make('open_order')
|
||||
->label('Open order')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
|
||||
@@ -57,6 +57,8 @@ class ShipmentResource extends Resource
|
||||
* done: on a manifest for carriers that batch (ACS), printed for
|
||||
* carriers that issue the voucher on print (ELTA — every parcel of a
|
||||
* multi-parcel send is printed together, so they leave together).
|
||||
* Includes vouchers created without an order (Carrier Vouchers' "Create
|
||||
* voucher"); carrier-reported ones never show here.
|
||||
*/
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
@@ -67,7 +69,6 @@ class ShipmentResource extends Resource
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->where('source', Shipment::SOURCE_CREATED)
|
||||
->whereNotNull('order_id')
|
||||
->whereNull('manifest_id')
|
||||
->whereNull('cancelled_at')
|
||||
->where(fn (Builder $query) => $query
|
||||
@@ -88,7 +89,10 @@ class ShipmentResource extends Resource
|
||||
->placeholder('Not issued yet')
|
||||
->description(fn (Shipment $record) => $record->parcelDescription())
|
||||
->copyable(),
|
||||
TextColumn::make('order.reference')->label('Order'),
|
||||
TextColumn::make('order.reference')
|
||||
->label('Order')
|
||||
->placeholder('No order')
|
||||
->description(fn (Shipment $record) => $record->order_id ? null : $record->recipient()?->name),
|
||||
TextColumn::make('created_at')->label('Created')->dateTime(),
|
||||
TextColumn::make('label_printed_at')->label('Printed')->dateTime()->placeholder('Not printed'),
|
||||
])
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Support;
|
||||
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\TimePicker;
|
||||
use Filament\Forms\Components\ToggleButtons;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Lunar\Models\Order;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Order\Services\OrderFulfillmentService;
|
||||
use Modules\Core\Order\Services\OrderStatusFlow;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\CreatesStandaloneVouchers;
|
||||
use Modules\Core\Shipping\Contracts\SupportsExtraServices;
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
use Modules\Core\Shipping\Enums\ExtraService;
|
||||
use Modules\Core\Shipping\Support\BoxNowShipping;
|
||||
use Modules\Core\Shipping\Support\WeightCalculator;
|
||||
|
||||
/**
|
||||
* The voucher form, shared by Carrier Vouchers' "Create voucher" and an
|
||||
* order's "Create Shipment" (for carriers implementing
|
||||
* CreatesStandaloneVouchers). Its fields follow the carrier:
|
||||
*
|
||||
* - ELTA: recipient address and phones, remarks, envelope or parcel,
|
||||
* packages, weight, dimensions and extra services;
|
||||
* - Box Now: the locker, one size per box, and the recipient's mobile and
|
||||
* email (the pickup code goes to both) — no address.
|
||||
*
|
||||
* For an order, the carrier is the order's, every field is prefilled
|
||||
* from it (recipient, delivery instructions, weight, locker), cash on
|
||||
* delivery is shown read-only (it follows the order's payment method),
|
||||
* and the reference is the order's own. What staff change goes to the
|
||||
* carrier only (ShipmentRequest::$recipient); the order stays as the
|
||||
* customer entered it.
|
||||
*/
|
||||
class VoucherForm
|
||||
{
|
||||
/**
|
||||
* @return array<int, mixed> the form's components
|
||||
*/
|
||||
public static function schema(?Order $order = null): array
|
||||
{
|
||||
$carrier = $order ? self::carrierOf($order) : null;
|
||||
$defaults = $order ? self::defaultsFor($order, $carrier) : [
|
||||
'package_count' => 1,
|
||||
'weight' => 0.5,
|
||||
];
|
||||
$default = fn (string $key) => $defaults[$key] ?? null;
|
||||
|
||||
return [
|
||||
$order
|
||||
? Hidden::make('carrier')->default($carrier)
|
||||
: Select::make('carrier')
|
||||
->label('Carrier')
|
||||
->options(fn () => self::carriers())
|
||||
->default(fn () => array_key_first(self::carriers()))
|
||||
->native(false)
|
||||
->live()
|
||||
->required(),
|
||||
|
||||
Section::make('Recipient')
|
||||
->description($order ? 'From the order\'s shipping address — changes here go to the carrier only.' : null)
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->required()->maxLength(150)->default($default('name'))->columnSpanFull(),
|
||||
TextInput::make('address')
|
||||
->label('Address')
|
||||
->required()
|
||||
->maxLength(150)
|
||||
->default($default('address'))
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get)),
|
||||
TextInput::make('postcode')
|
||||
->label('Postcode')
|
||||
->required()
|
||||
->rule('regex:/^\d{3}\s?\d{2}$/')
|
||||
->validationMessages(['regex' => 'Enter a 5-digit postcode.'])
|
||||
->default($default('postcode'))
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get)),
|
||||
TextInput::make('city')
|
||||
->label('City / area')
|
||||
->required()
|
||||
->maxLength(40)
|
||||
->default($default('city'))
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get)),
|
||||
TextInput::make('phone')
|
||||
->label('Phone')
|
||||
->tel()
|
||||
// ELTA needs at least one of the two numbers.
|
||||
->requiredWithout('mobile')
|
||||
->validationMessages(['required_without' => 'Enter a phone or a mobile.'])
|
||||
->default($default('phone'))
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get)),
|
||||
TextInput::make('mobile')
|
||||
->label('Mobile')
|
||||
->tel()
|
||||
->required(fn (Get $get) => self::isBoxNow($get))
|
||||
->default($default('mobile'))
|
||||
->helperText(fn (Get $get) => self::isBoxNow($get)
|
||||
? 'The locker pickup code is sent here by SMS.'
|
||||
: '10 digits, starting with 69 — required for PostBox delivery.'),
|
||||
TextInput::make('email')
|
||||
->label('Email')
|
||||
->email()
|
||||
->required()
|
||||
->default($default('email'))
|
||||
->helperText('The locker pickup code is sent here too.')
|
||||
->visible(fn (Get $get) => self::isBoxNow($get)),
|
||||
Textarea::make('notes')
|
||||
->label('Remarks for the courier')
|
||||
->maxLength(90)
|
||||
->rows(2)
|
||||
->default($default('notes'))
|
||||
->helperText('Printed in ΠΑΡΑΤΗΡΗΣΕΙΣ, up to 90 characters.')
|
||||
->columnSpanFull()
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get)),
|
||||
]),
|
||||
|
||||
Section::make('Locker and boxes')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get) => self::isBoxNow($get))
|
||||
->schema([
|
||||
TextInput::make('locker_id')
|
||||
->label('Box Now locker ID')
|
||||
->required()
|
||||
->default($default('locker_id'))
|
||||
->helperText($order
|
||||
? ($default('locker_id')
|
||||
? 'Set by the customer at checkout — override if the parcel needs to go to a different locker.'
|
||||
: 'No locker was selected at checkout — enter it manually.')
|
||||
: null),
|
||||
// An order's value is its total.
|
||||
TextInput::make('value')
|
||||
->label('Parcel value')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->prefix('€')
|
||||
->helperText('Declared to Box Now; defaults to the cash on delivery amount.')
|
||||
->visible(! $order),
|
||||
Repeater::make('boxes')
|
||||
->label('Boxes')
|
||||
->schema([
|
||||
Select::make('size')
|
||||
->label('Size')
|
||||
->options(['S' => 'Small', 'M' => 'Medium', 'L' => 'Large'])
|
||||
->default('S')
|
||||
->native(false)
|
||||
->required(),
|
||||
])
|
||||
->defaultItems(1)
|
||||
->minItems(1)
|
||||
->addActionLabel('Add another box')
|
||||
->helperText('One row per physical box — each gets its own voucher and locker compartment. Box Now ships by size, not weight.')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
|
||||
Section::make('Parcel')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get) => ! self::isBoxNow($get))
|
||||
->schema([
|
||||
ToggleButtons::make('type')
|
||||
->label('Type')
|
||||
->options(['parcel' => 'Parcel', 'envelope' => 'Envelope'])
|
||||
->default('parcel')
|
||||
->inline()
|
||||
->required(),
|
||||
TextInput::make('package_count')
|
||||
->label('Number of packages')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(20)
|
||||
->default($default('package_count'))
|
||||
->required()
|
||||
->helperText('More than 1 issues a main voucher plus a voucher per extra package.'),
|
||||
TextInput::make('weight')
|
||||
->label('Weight')
|
||||
->numeric()
|
||||
->minValue(0.001)
|
||||
->default($default('weight'))
|
||||
->suffix('kg')
|
||||
->required()
|
||||
->helperText($order
|
||||
? 'Calculated from the order\'s line weights — adjust if needed. The whole shipment, not per package.'
|
||||
: 'The whole shipment, not per package.'),
|
||||
Grid::make(3)
|
||||
->schema([
|
||||
TextInput::make('length')->label('Length')->numeric()->integer()->minValue(1)->maxValue(999)->suffix('cm'),
|
||||
TextInput::make('width')->label('Width')->numeric()->integer()->minValue(1)->maxValue(999)->suffix('cm'),
|
||||
TextInput::make('height')->label('Height')->numeric()->integer()->minValue(1)->maxValue(999)->suffix('cm'),
|
||||
])
|
||||
->columnSpan(1),
|
||||
]),
|
||||
|
||||
Section::make('Payment and services')
|
||||
->columns(2)
|
||||
->schema([
|
||||
$order
|
||||
// Whether a shipment collects cash is a fact about the
|
||||
// order (its payment method), not a choice made here.
|
||||
? TextInput::make('cod_amount')
|
||||
->label('Cash on delivery')
|
||||
->prefix('€')
|
||||
->default($default('cod_amount'))
|
||||
->disabled()
|
||||
->dehydrated(false)
|
||||
->helperText('The order is paid on delivery — the courier collects its total.')
|
||||
->visible(filled($default('cod_amount')))
|
||||
: TextInput::make('cod_amount')
|
||||
->label('Cash on delivery')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->prefix('€')
|
||||
->helperText('Leave empty when the recipient pays nothing.'),
|
||||
// An order's vouchers carry the order's reference.
|
||||
TextInput::make('reference')
|
||||
->label('Reference')
|
||||
->required()
|
||||
->maxLength(30)
|
||||
->default(fn () => 'V'.now()->format('ymdHis'))
|
||||
->helperText(fn (Get $get) => self::isBoxNow($get)
|
||||
? 'Sent to Box Now as the order number — it must be one Box Now hasn\'t seen before.'
|
||||
: 'Sent to the carrier and printed on the voucher — also how you find it in the carrier\'s lists.')
|
||||
->visible(! $order),
|
||||
CheckboxList::make('services')
|
||||
->label('Extra services')
|
||||
->options(fn (Get $get) => self::extraServices($get('carrier')))
|
||||
->visible(fn (Get $get) => self::extraServices($get('carrier')) !== [])
|
||||
->columns(2)
|
||||
->live()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('insurance_amount')
|
||||
->label('Insured value')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->prefix('€')
|
||||
->default($default('insurance_amount'))
|
||||
->visible(fn (Get $get) => self::ticked($get, ExtraService::Insurance))
|
||||
->required(fn (Get $get) => self::ticked($get, ExtraService::Insurance)),
|
||||
TimePicker::make('delivery_until')
|
||||
->label('Deliver by')
|
||||
->seconds(false)
|
||||
->visible(fn (Get $get) => self::ticked($get, ExtraService::TimedDelivery))
|
||||
->required(fn (Get $get) => self::ticked($get, ExtraService::TimedDelivery)),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The recipient as the form has it.
|
||||
*/
|
||||
public static function recipient(array $data): VoucherRecipient
|
||||
{
|
||||
$text = fn (string $key) => filled($data[$key] ?? null) ? trim($data[$key]) : null;
|
||||
|
||||
return new VoucherRecipient(
|
||||
name: trim($data['name']),
|
||||
address: (string) $text('address'),
|
||||
postcode: preg_replace('/\s+/', '', (string) $text('postcode')),
|
||||
city: (string) $text('city'),
|
||||
phone: $text('phone'),
|
||||
mobile: $text('mobile'),
|
||||
notes: $text('notes'),
|
||||
email: $text('email'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shipment request as the form has it. $cod is the cash to collect
|
||||
* (null = prepaid); for an order it comes from the order, not the form.
|
||||
*/
|
||||
public static function request(array $data, ?float $cod, ?VoucherRecipient $recipient = null): ShipmentRequest
|
||||
{
|
||||
$services = array_map(fn (string $value) => ExtraService::from($value), $data['services'] ?? []);
|
||||
$dimensions = array_values(array_filter([$data['length'] ?? null, $data['width'] ?? null, $data['height'] ?? null], 'filled'));
|
||||
|
||||
return new ShipmentRequest(
|
||||
weight: filled($data['weight'] ?? null) ? (float) $data['weight'] : null,
|
||||
packageCount: (int) ($data['package_count'] ?? 1),
|
||||
destinationLocationId: filled($data['locker_id'] ?? null) ? trim($data['locker_id']) : null,
|
||||
paymentMode: $cod ? 'cod' : 'prepaid',
|
||||
amountToCollect: $cod,
|
||||
boxes: collect($data['boxes'] ?? [])->pluck('size')->all(),
|
||||
services: $services,
|
||||
insuranceAmount: in_array(ExtraService::Insurance, $services, true) ? (float) $data['insurance_amount'] : null,
|
||||
deliveryUntil: in_array(ExtraService::TimedDelivery, $services, true) ? ($data['delivery_until'] ?? null) : null,
|
||||
envelope: ($data['type'] ?? 'parcel') === 'envelope',
|
||||
// All three or none — a partial set is ignored.
|
||||
dimensions: count($dimensions) === 3 ? $dimensions : null,
|
||||
value: filled($data['value'] ?? null) ? (float) $data['value'] : null,
|
||||
recipient: $recipient,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an order's Create Shipment uses this form: its carrier can
|
||||
* take a recipient from it.
|
||||
*/
|
||||
public static function handles(?string $carrier): bool
|
||||
{
|
||||
return $carrier !== null && app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]) instanceof CreatesStandaloneVouchers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> carrier => name, for carriers that can create vouchers without an order
|
||||
*/
|
||||
public static function carriers(): array
|
||||
{
|
||||
return collect(Shipping::getSupportedDrivers())
|
||||
->filter(fn ($driver, string $carrier) => self::handles($carrier))
|
||||
->map(fn ($driver) => $driver->name())
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> field => default, from the order
|
||||
*/
|
||||
private static function defaultsFor(Order $order, ?string $carrier): array
|
||||
{
|
||||
$address = $order->shippingAddress;
|
||||
$recipient = VoucherRecipient::fromAddress($address);
|
||||
$isBoxNow = BoxNowShipping::isDriver($carrier);
|
||||
|
||||
return [
|
||||
...$recipient->toArray(),
|
||||
// One number on the order: Box Now texts it, ELTA sorts
|
||||
// landlines from mobiles itself.
|
||||
'phone' => $isBoxNow ? null : $recipient->phone,
|
||||
'mobile' => $isBoxNow ? $recipient->phone : null,
|
||||
'locker_id' => $address?->meta['box_now_locker']['locationId'] ?? null,
|
||||
'package_count' => 1,
|
||||
'weight' => round(WeightCalculator::totalKg($order->lines), 2) ?: 0.5,
|
||||
'cod_amount' => app(OrderStatusFlow::class)->isCod($order) ? number_format($order->total->decimal, 2, '.', '') : null,
|
||||
'insurance_amount' => $order->total->decimal,
|
||||
];
|
||||
}
|
||||
|
||||
private static function carrierOf(Order $order): ?string
|
||||
{
|
||||
return app(OrderFulfillmentService::class)->carrierFor($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> ExtraService value => label
|
||||
*/
|
||||
private static function extraServices(?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 static function isBoxNow(Get $get): bool
|
||||
{
|
||||
return BoxNowShipping::isDriver($get('carrier'));
|
||||
}
|
||||
|
||||
private static function ticked(Get $get, ExtraService $service): bool
|
||||
{
|
||||
return in_array($service->value, $get('services') ?? [], true);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Lunar\Models\Order;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Shipping\DTOs\VoucherRecipient;
|
||||
|
||||
class Shipment extends Model
|
||||
{
|
||||
@@ -51,6 +52,38 @@ class Shipment extends Model
|
||||
return $this->shipmentInfo()->latest('occurred_at')->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Who the voucher goes to, as saved when it was created
|
||||
* (meta.recipient). Vouchers created before that was saved fall back to
|
||||
* their order's shipping address; an extra parcel of a multi-parcel
|
||||
* send falls back to its main voucher's.
|
||||
*/
|
||||
public function recipient(): ?VoucherRecipient
|
||||
{
|
||||
if (filled($this->meta['recipient'] ?? null)) {
|
||||
return VoucherRecipient::fromArray((array) $this->meta['recipient']);
|
||||
}
|
||||
|
||||
if ($address = $this->order?->shippingAddress) {
|
||||
return VoucherRecipient::fromAddress($address);
|
||||
}
|
||||
|
||||
$masterId = $this->meta['master_shipment_id'] ?? null;
|
||||
|
||||
return $masterId ? self::find($masterId)?->recipient() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference we sent the carrier with this voucher (saved since
|
||||
* 0.29.2); older vouchers were sent their order's reference.
|
||||
*/
|
||||
public function reference(): ?string
|
||||
{
|
||||
return filled($this->meta['reference'] ?? null)
|
||||
? (string) $this->meta['reference']
|
||||
: $this->order?->reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* The carrier's display name: a manual carrier's own name (snapshotted
|
||||
* from its shipping method), otherwise the shipping driver's name().
|
||||
@@ -135,6 +168,11 @@ class Shipment extends Model
|
||||
*/
|
||||
public function parcelDescription(): ?string
|
||||
{
|
||||
// Box Now: every box is its own voucher (no main voucher).
|
||||
if (($this->meta['boxes'] ?? 0) > 1) {
|
||||
return "Box {$this->meta['box']} of {$this->meta['boxes']}";
|
||||
}
|
||||
|
||||
$piece = $this->meta['piece'] ?? null;
|
||||
$pieces = $this->meta['pieces'] ?? null;
|
||||
|
||||
|
||||
Reference in new issue
Block a user