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 { 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->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) $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' => $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' => $volumetric ?? '', 'pel_x' => $dimensions ? (string) $dimensions[0] : '', 'pel_y' => $dimensions ? (string) $dimensions[1] : '', 'pel_z' => $dimensions ? (string) $dimensions[2] : '', 'pel_temaxia' => (string) $request->packageCount, // 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' => '', 'pel_ant_poso1' => '', 'pel_ant_poso2' => '', 'pel_ant_poso3' => '', 'pel_ant_poso4' => '', 'pel_ant_date1' => '', 'pel_ant_date2' => '', 'pel_ant_date3' => '', 'pel_ant_date4' => '', 'pel_asf_poso' => $request->has(ExtraService::Insurance) && $request->insuranceAmount ? number_format($request->insuranceAmount, 2, '.', '') : '', 'pel_user' => config('elta.user_code'), // 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' => $reference, // "0" = save without issuing (see this class's docblock). 'pel_insert_flag' => '0', 'pel_paral_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; if (! $codAmount) { throw new EltaApiException('Enter the cash on delivery amount.'); } $params['pel_ant_poso'] = number_format($codAmount, 2, '.', ''); } $this->client->createVoucher($params)->throwIfError(); $pieces = max(1, $request->packageCount); // PELVGNEW doesn't return the new voucher's id, so find it in the // 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, 'carrier' => 'elta', 'source' => Shipment::SOURCE_CREATED, 'tracking_reference' => null, 'meta' => [ '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, ...($pieces > 1 ? ['piece' => 1, 'pieces' => $pieces] : []), ], ]); // One row per extra parcel straight away, so the order shows every // parcel; ELTA gives them their own voucher numbers only when the // main voucher is issued (issue()). They belong to the main voucher: // no COD or services of their own. for ($piece = 2; $piece <= $pieces; $piece++) { Shipment::create([ 'order_id' => $order?->id, 'carrier' => 'elta', 'source' => Shipment::SOURCE_CREATED, 'tracking_reference' => null, 'meta' => [ 'master_shipment_id' => $master->id, 'reference' => $reference, 'piece' => $piece, 'pieces' => $pieces, 'weight' => $weight, 'package_count' => $pieces, ], ]); } return $master; } /** * Like ELTA's own client: printing the main voucher of a multi-parcel * 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 { return $this->printLabels(collect([$shipment])); } /** * Several labels in one PDF. A selected main voucher brings its * 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 { $pages = collect(); foreach ($shipments as $shipment) { $master = $this->masterOf($shipment); $this->issue($master); $group = $shipment->is($master) ? [$master->refresh(), ...$this->childrenOf($master)] : [$shipment->refresh()]; foreach ($group as $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($pages->values()); Shipment::whereIn('id', $pages->whereInstanceOf(Shipment::class)->keys())->update(['label_printed_at' => now()]); return $pdf; } /** * Pending (not yet printed) vouchers are deleted at ELTA. Issued ones * can't be — ELTA only allows that before printing. */ public function cancelShipment(Shipment $shipment): void { $master = $this->masterOf($shipment); if (! $shipment->is($master)) { $piece = $shipment->meta['piece'] ?? null; throw new EltaApiException( 'This is '.($piece ? "parcel {$piece}" : 'an extra parcel').' of a multi-parcel ELTA voucher — ELTA cancels the whole voucher, so cancel the main parcel instead.', ); } if (filled($shipment->tracking_reference)) { throw new EltaApiException( "ELTA voucher {$shipment->tracking_reference} is already printed, and ELTA only allows cancelling vouchers that haven't been printed yet. Contact ELTA to cancel it.", ); } $this->client->deleteVoucher(['pel_vg_id' => $this->pendingVoucherId($shipment)])->throwIfError(); $shipment->update(['cancelled_at' => now()]); $this->childrenOf($shipment)->each->update(['cancelled_at' => now()]); } /** * The main voucher's shipment for a child parcel, or the shipment * itself. Children created by createShipment() point at it via * meta.master_shipment_id; older ones only via parent_reference. */ private function masterOf(Shipment $shipment): Shipment { if ($id = $shipment->meta['master_shipment_id'] ?? null) { return Shipment::find($id) ?? $shipment; } if (filled($shipment->parent_reference)) { return Shipment::where('tracking_reference', $shipment->parent_reference)->first() ?? $shipment; } return $shipment; } /** * @return Collection the main voucher's child parcels, in piece order */ private function childrenOf(Shipment $master): Collection { return Shipment::query() ->where('carrier', 'elta') ->where(fn ($query) => $query ->where('meta->master_shipment_id', $master->id) ->when($master->tracking_reference, fn ($q) => $q->orWhere('parent_reference', $master->tracking_reference))) ->orderBy('id') ->get() ->sortBy(fn (Shipment $child) => $child->meta['piece'] ?? PHP_INT_MAX) ->values(); } public function trackShipment(Shipment $shipment): Collection { // ELTA tracks a multi-parcel send by its main voucher only — an // extra parcel's own number is rejected ("Λάθος ΣΥΔΕΤΑ"). Its // history is the main voucher's, which is tracked on its own row. if (! $shipment->is($this->masterOf($shipment))) { return collect(); } $response = $this->client->getTracking([ 'web_vg' => $shipment->tracking_reference, 'pel_code' => config('elta.apost_code'), ])->throwIfError(); $rows = array_filter( (array) ($response->data['web_status'] ?? []), fn (array $row) => filled($row['web_date_time'] ?? null), ); // No explicit delivered-confirmation field like the old // PELTT01's pod_name — pel_rec.a_rec_date_time is blank until // delivery per the real client's own rendering, used as the // delivered signal here; unconfirmed against a genuinely // 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'] ?? ''; return new TrackingCheckpoint( status: $isLast && $isDelivered ? TrackingStatus::Delivered : $this->guessStatusFromTitle($row['web_status_name'] ?? ''), carrierStatus: $row['web_status_name'] ?? null, message: $row['web_sxolia'] ?: ($row['web_status_name'] ?? null), location: $row['web_station'] ?? null, // ELTA reports Greek local time. occurredAt: Carbon::createFromFormat('YmdHi', substr($dateTime, 0, 12), 'Europe/Athens')->setTimezone(config('app.timezone')), meta: $row, ); }); } /** * 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 $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 * status_flag 3 ("Προς Επιστροφή") marks the ones heading back to us. */ public function listVouchers(CarbonInterface $from, CarbonInterface $to): iterable { $returning = collect($this->searchVouchers($from, $to, '3'))->pluck('pel_col_1')->flip(); foreach ($this->searchVouchers($from, $to, '0') as $row) { $number = trim($row['pel_col_1']); yield new CarrierVoucher( carrier: 'elta', voucherNumber: $number, reference: filled($row['pel_col_2'] ?? null) ? trim($row['pel_col_2']) : null, recipientName: trim($row['pel_col_3'] ?? '') ?: null, postcode: trim($row['pel_col_4'] ?? '') ?: null, statusText: trim($row['pel_col_6'] ?? '') ?: null, status: filled(trim($row['pel_col_6'] ?? '')) ? $this->guessStatusFromTitle(trim($row['pel_col_6'])) : null, codAmount: (float) ($row['pel_col_8'] ?? 0) ?: null, isReturn: $returning->has($row['pel_col_1']), date: $this->dateFromListRow($row['pel_col_7'] ?? ''), raw: $row, ); } } /** * PELTTNEW01 (tracking) also returns the voucher's details (pel_rec): * recipient, postcode, our reference, cash on delivery. */ public function lookupVoucher(string $voucherNumber): ?CarrierVoucher { $response = $this->client->getTracking([ 'web_vg' => trim($voucherNumber), 'pel_code' => config('elta.apost_code'), ]); $record = $response->data['pel_rec'] ?? []; if ($response->hasError || blank($record['a_vg_3'] ?? null)) { return null; } $statuses = array_values(array_filter( (array) ($response->data['web_status'] ?? []), fn (array $row) => filled($row['web_date_time'] ?? null), )); return new CarrierVoucher( carrier: 'elta', voucherNumber: trim($record['a_vg_3']), reference: trim($record['a_ref'] ?? '') ?: null, recipientName: trim($record['a_rec_title'] ?? '') ?: null, postcode: trim($record['a_rec_postal'] ?? '') ?: null, phone: trim($record['a_rec_tel_1'] ?? '') ?: null, statusText: filled($statuses) ? trim(end($statuses)['web_status_name'] ?? '') : null, status: filled($statuses) ? $this->guessStatusFromTitle(trim(end($statuses)['web_status_name'] ?? '')) : null, codAmount: (float) ($record['a_antik'] ?? 0) ?: null, date: $this->dateFromListRow($record['a_sender_date'] ?? ''), raw: $record, ); } /** * Issues a pending voucher (no-op once it has a number): stores the * voucher number and what ELTA returns for the label, plus one shipment * per child voucher of a multi-piece send. */ private function issue(Shipment $shipment): void { if (filled($shipment->tracking_reference)) { return; } $response = $this->client->issueVoucher([ 'pel_id' => $this->pendingVoucherId($shipment), 'sender_station' => $this->senderStation(), ])->throwIfError(); $data = $response->data; $voucherNo = trim((string) ($data['vg_code'] ?? '')); if ($voucherNo === '') { throw new EltaApiException('ELTA issued the voucher but returned no voucher number.', $data); } $shipment->tracking_reference = $voucherNo; $shipment->meta = array_merge($shipment->meta?->toArray() ?? [], [ 'ocr_line' => $data['ocr_line'] ?? null, 'date_time' => $data['date_time'] ?? null, 'rec_station' => $data['rec_station'] ?? null, 'rec_station_t' => $data['rec_station_t'] ?? null, '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(); // The children's numbers, in ELTA's order (vg_child_no), go to the // pending child rows in piece order; any parcel without a row (older // shipments) gets one. $pending = $this->childrenOf($shipment)->filter(fn (Shipment $child) => blank($child->tracking_reference))->values(); $pieces = (int) ($shipment->meta['package_count'] ?? 1); $childNumbers = array_values(array_filter(array_map('trim', (array) ($data['vg_child_no'] ?? [])))); foreach ($childNumbers as $i => $childVoucherNo) { $child = $pending->get($i) ?? new Shipment([ 'order_id' => $shipment->order_id, 'carrier' => 'elta', 'source' => Shipment::SOURCE_CREATED, 'meta' => [ 'master_shipment_id' => $shipment->id, 'reference' => $shipment->meta['reference'] ?? null, 'piece' => $i + 2, 'pieces' => max($pieces, count($childNumbers) + 1), 'weight' => $shipment->meta['weight'] ?? null, 'package_count' => max($pieces, count($childNumbers) + 1), ], ]); $child->tracking_reference = $childVoucherNo; $child->parent_reference = $voucherNo; $child->save(); } } /** * @return 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 { 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' : '', ]; } /** * 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; $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]); $shipment->save(); } } if (blank($id)) { throw new EltaApiException("Couldn't find this shipment's pending voucher at ELTA."); } return $id; } /** * The newest not-yet-issued voucher in ELTA's list carrying our * reference. flag_1/flag_2 are the client's "Show all" / "All users" * checkboxes — both "1", or even a just-created voucher is filtered out. */ private function findPendingVoucherId(string $reference): ?string { $inId = '0'; $match = null; for ($page = 0; $page < self::MAX_PAGES; $page++) { $rows = array_values(array_filter( (array) ($this->client->listVouchers([ 'pel_code' => config('elta.apost_code'), 'pel_user_code' => config('elta.user_code'), 'flag_1' => '1', 'flag_2' => '1', 'in_id' => $inId, ])->throwIfError()->data['vg_rec'] ?? []), fn (array $row) => filled($row['pel_vg_id'] ?? null), )); foreach ($rows as $row) { if (trim($row['pel_ref_no'] ?? '') === $reference && blank(trim($row['pel_paral_vg'] ?? '')) && ($match === null || $row['pel_vg_id'] > $match)) { $match = $row['pel_vg_id']; } } if (count($rows) < 100) { break; } $inId = (string) end($rows)['pel_vg_id']; } return $match; } /** * @return array> */ private function searchVouchers(CarbonInterface $from, CarbonInterface $to, string $statusFlag): array { $inId = '0'; $all = []; for ($page = 0; $page < self::MAX_PAGES; $page++) { $rows = array_values(array_filter( (array) ($this->client->searchVouchers([ 'pel_code' => config('elta.apost_code'), 'date_1' => $from->format('d/m/Y'), 'date_2' => $to->format('d/m/Y'), 'paral_code' => '', 'status_flag' => $statusFlag, 'in_id' => $inId, ])->throwIfError()->data['ag_pel_rec'] ?? []), fn (array $row) => filled(trim($row['pel_col_1'] ?? '')), )); array_push($all, ...$rows); if (count($rows) < 100) { break; } $inId = (string) end($rows)['pel_col_id']; } return $all; } /** * ELTA dates in its lists look like "29/09/26 09:41 PEL CLIENT" or * "29/09/2026 09:51". */ private function dateFromListRow(string $value): ?CarbonInterface { if (! preg_match('#(\d{2})/(\d{2})/(\d{2,4})#', $value, $m)) { return null; } $year = strlen($m[3]) === 2 ? '20'.$m[3] : $m[3]; return Carbon::createFromDate((int) $year, (int) $m[2], (int) $m[1])->startOfDay(); } /** * The station ELTA needs when issuing a voucher: configured * (ELTA_ORIGIN_STATION_CODE), or read from the login response once — * ELTA returns the account's user_station there even though our * account's login password is rejected. */ private function senderStation(): string { if (filled(config('elta.origin_station_code'))) { return (string) config('elta.origin_station_code'); } return (string) Cache::rememberForever('elta.user_station', fn () => $this->client->login([ 'pel_code' => config('elta.apost_code'), 'user_code' => config('elta.user_code'), 'user_pass' => config('elta.user_pass'), ])->data['user_station'] ?? ''); } /** * web_status_name is free text with no structured status code — same * limitation Acs\AcsFulfillmentService::guessStatusFromAction() has. * Live-confirmed text seen so far: "ΔΗΜΙΟΥΡΓΙΑ ΣΥ.ΔΕ.ΤΑ. ΑΠΟ ΠΕΛΑΤΗ" * (voucher created) — matched via a Pending-ish fallback below since * it isn't yet in transit. Other statuses are best-guess substring * matches to refine as more real tracking text is observed. */ /** * ELTA's status texts come in unaccented capitals ("ΠΑΡΑΔΟΘΗΚΕ"), so * they're lowercased and stripped of accents before matching. */ private function guessStatusFromTitle(string $title): TrackingStatus { $title = strtr(mb_strtolower($title), [ 'ά' => 'α', 'έ' => 'ε', 'ή' => 'η', 'ί' => 'ι', 'ό' => 'ο', 'ύ' => 'υ', 'ώ' => 'ω', 'ϊ' => 'ι', 'ϋ' => 'υ', 'ΐ' => 'ι', 'ΰ' => 'υ', ]); return match (true) { str_contains($title, 'επιστροφ') => TrackingStatus::Returned, str_contains($title, 'παραδοθηκε') => TrackingStatus::Delivered, str_contains($title, 'διανομη') => TrackingStatus::OutForDelivery, str_contains($title, 'παραλαβη') => TrackingStatus::CollectedFromSender, str_contains($title, 'μεταφορα') || str_contains($title, 'διαμετακομιση') || str_contains($title, 'διακινηση') => TrackingStatus::InTransit, default => TrackingStatus::Pending, }; } }