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:
arvanitakis committed 2026-10-01 01:51:13 +03:00
1 parent c455c8adf2
commit 5ff0d60f54
27 files changed
+2189 -376

No files matched your search

@@ -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]);