get_setting('base_url', '')); return $own !== '' ? $own : 'https://api.brt.it/rest/v1'; } public function capabilities() { return array('create', 'cancel', 'track'); } public function settings_schema() { return array( 'user_id' => array('type' => 'text', 'label' => __('User ID', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('The web-services user BRT issued with your contract.', 'ai-eshop-optimizer')), 'password' => array('type' => 'password', 'label' => __('Password', 'ai-eshop-optimizer'), 'required' => true), 'client_id' => array('type' => 'text', 'label' => __('Client ID (codice cliente)', 'ai-eshop-optimizer'), 'required' => true, 'help' => __('Your BRT customer code. It also forms part of every tracking lookup.', 'ai-eshop-optimizer')), 'departure_depot' => array('type' => 'text', 'label' => __('Departure depot', 'ai-eshop-optimizer'), 'help' => __('Filiale di partenza — the three-digit depot on your contract.', 'ai-eshop-optimizer')), 'service_type' => array( 'type' => 'select', 'label' => __('Service', 'ai-eshop-optimizer'), 'options' => array( 'DDT' => __('DDT — standard', 'ai-eshop-optimizer'), 'DDS' => __('DDS — with delivery note', 'ai-eshop-optimizer'), ), ), 'label_format' => array( 'type' => 'select', 'label' => __('Label format', 'ai-eshop-optimizer'), 'options' => array( 'PDF' => __('PDF', 'ai-eshop-optimizer'), 'ZPL' => __('ZPL (thermal)', 'ai-eshop-optimizer'), ), ), 'base_url' => array( 'type' => 'url', 'label' => __('API base URL', 'ai-eshop-optimizer'), 'help' => __('Leave empty for the standard endpoint. BRT issues per-customer hosts, so check your contract letter before assuming this is wrong.', 'ai-eshop-optimizer'), ), 'sender_name' => array('type' => 'text', 'label' => __('Sender name', 'ai-eshop-optimizer'), 'required' => true), 'sender_street' => array('type' => 'text', 'label' => __('Sender street', 'ai-eshop-optimizer'), 'required' => true), 'sender_zip' => array('type' => 'text', 'label' => __('Sender postcode (CAP)', 'ai-eshop-optimizer'), 'required' => true), 'sender_city' => array('type' => 'text', 'label' => __('Sender city', 'ai-eshop-optimizer'), 'required' => true), 'sender_province'=> array('type' => 'text', 'label' => __('Sender province (2 letters)', 'ai-eshop-optimizer'), 'required' => true), 'sender_country' => array('type' => 'text', 'label' => __('Sender country code', 'ai-eshop-optimizer'), 'required' => true), ); } public function tracking_url($voucher_no) { $own = parent::tracking_url($voucher_no); if ($own !== '') { return $own; } return 'https://vas.brt.it/vas/sped_det_show.hsm?ChiSono=&Spedizione=' . rawurlencode((string) $voucher_no); } public function authenticate(array $creds) { $cfg = array_merge($this->credentials(), $creds); $missing = array(); foreach (array('user_id', 'password', 'client_id') as $req) { if (empty($cfg[$req])) { $missing[] = $req; } } if (!empty($missing)) { return array('ok' => false, 'error' => sprintf( __('BRT credentials missing: %s', 'ai-eshop-optimizer'), implode(', ', $missing) )); } return array('ok' => true, 'auth_token' => null, 'expires_at' => null); } private function credentials() { return class_exists('AIEO_Fulfillment_Settings') ? (array) AIEO_Fulfillment_Settings::get('courier_' . $this->code(), array()) : array(); } private function account_block() { $c = $this->credentials(); return array( 'userID' => (string) ($c['user_id'] ?? ''), 'password' => (string) ($c['password'] ?? ''), ); } public function create_voucher(array $payload) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $cfg = $this->credentials(); $rec = isset($payload['recipient']) && is_array($payload['recipient']) ? $payload['recipient'] : array(); $weight = (float) ($payload['weight'] ?? 0.5); if ($weight <= 0) { $weight = 0.5; } $pieces = max(1, (int) ($payload['pieces'] ?? 1)); $create = array( 'senderCustomerCode' => (string) ($cfg['client_id'] ?? ''), 'departureDepot' => (string) ($cfg['departure_depot'] ?? ''), 'deliveryFreightTypeCode' => (string) ($cfg['service_type'] ?: 'DDT'), 'numericSenderReference' => (string) preg_replace('/\D+/', '', (string) ($payload['reference_1'] ?? '')), 'alphanumericSenderReference'=> $this->reference($payload, 15), 'consigneeCompanyName' => mb_substr((string) ($rec['name'] ?? ''), 0, 40), 'consigneeAddress' => mb_substr(trim((string) ($rec['address'] ?? '')), 0, 40), 'consigneeZIPCode' => (string) ($rec['zip'] ?? ''), 'consigneeCity' => mb_substr((string) ($rec['city'] ?? ''), 0, 30), 'consigneeProvinceAbbreviation' => strtoupper(mb_substr((string) ($rec['state'] ?? ''), 0, 2)), 'consigneeCountryAbbreviationISOAlpha2' => strtoupper(substr((string) ($rec['country'] ?? 'IT'), 0, 2)), 'consigneeContactName' => mb_substr((string) ($rec['name'] ?? ''), 0, 40), 'consigneeTelephone' => $this->digits((string) ($rec['phone'] ?? '')), 'consigneeEMail' => (string) ($rec['email'] ?? ''), 'numberOfParcels' => $pieces, 'weightKG' => number_format($weight, 2, '.', ''), 'pinCodeRequired' => 0, ); $cod = (float) ($payload['cod_amount'] ?? 0); if ($cod > 0) { $create['cashOnDelivery'] = number_format($cod, 2, '.', ''); $create['codPaymentType'] = 'CONTANTI'; $create['codCurrency'] = get_woocommerce_currency(); } $body = array( 'account' => $this->account_block(), 'createData' => $create, 'isLabelRequired' => 1, 'labelParameters' => array( 'outputType' => (string) ($cfg['label_format'] ?: 'PDF'), 'offsetX' => 0, 'offsetY' => 0, 'isBorderRequired' => 0, 'isLogoRequired' => 1, ), ); $resp = $this->request('POST', '/spedizioni/shipment', $body); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $create_resp = $resp['createResponse'] ?? array(); $exec = $create_resp['executionMessage'] ?? array(); $code = (int) ($exec['code'] ?? 0); if ($code !== 0) { $msg = trim((string) ($exec['message'] ?? '')); return array('ok' => false, 'error' => $msg !== '' ? $msg : sprintf( __('BRT rejected the shipment (code %d).', 'ai-eshop-optimizer'), $code ), 'raw' => $resp); } $labels = $create_resp['labels']['label'] ?? array(); $parcel = (string) ($create_resp['parcelNumberFrom'] ?? ''); $tracking = $parcel !== '' ? $parcel : (string) ($create_resp['parcelNumber'] ?? ''); if ($tracking === '') { return array('ok' => false, 'error' => __('BRT accepted the shipment but returned no parcel number.', 'ai-eshop-optimizer'), 'raw' => $resp); } return array( 'ok' => true, 'voucher_no' => $tracking, 'subvouchers' => array(), 'job_id' => null, 'raw' => array_merge($resp, array('aieo_label_b64' => (string) ($labels[0]['stream'] ?? ''))), ); } public function get_label_pdf($voucher_no, $format = 'A4') { return array( 'ok' => false, 'error' => __('BRT returns the label with the shipment. Reprint it from the copy saved with the voucher.', 'ai-eshop-optimizer'), ); } public function label_from_create(array $create_response) { $b64 = (string) ($create_response['raw']['aieo_label_b64'] ?? ''); if ($b64 === '') { return array('ok' => false, 'pdf' => null, 'error' => __('No label in the BRT response.', 'ai-eshop-optimizer')); } return $this->decode_label($b64); } public function map_status($raw_code) { $raw = mb_strtoupper((string) $raw_code); if ($raw === '') { return 'unknown'; } if (mb_strpos($raw, 'CONSEGNATA') !== false) { return 'delivered'; } if (mb_strpos($raw, 'IN CONSEGNA') !== false) { return 'out_for_delivery'; } if (mb_strpos($raw, 'PARTITA') !== false) { return 'in_transit'; } if (mb_strpos($raw, 'ARRIVATA') !== false) { return 'in_transit'; } if (mb_strpos($raw, 'TRANSITO') !== false) { return 'in_transit'; } if (mb_strpos($raw, 'PRESA') !== false) { return 'in_transit'; } if (mb_strpos($raw, 'GIACENZA') !== false) { return 'on_hold'; } if (mb_strpos($raw, 'RESA') !== false) { return 'returned'; } if (mb_strpos($raw, 'ANNULLAT') !== false) { return 'canceled'; } return 'unknown'; } public function track($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $client = (string) ($this->credentials()['client_id'] ?? ''); $resp = $this->request( 'GET', '/tracking/parcelID/' . rawurlencode($client) . '/' . rawurlencode((string) $voucher_no) ); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $tr = $resp['TrackingResponse'] ?? ($resp['trackingResponse'] ?? array()); $exec = $tr['executionMessage'] ?? array(); if ((int) ($exec['code'] ?? 0) !== 0) { return array('ok' => false, 'error' => trim((string) ($exec['message'] ?? '')) ?: __('BRT does not recognise that parcel.', 'ai-eshop-optimizer')); } $checkpoints = array(); $latest = ''; $delivered_at = null; foreach ((array) ($tr['list'] ?? array()) as $e) { $stamp = trim((string) ($e['date'] ?? '') . ' ' . (string) ($e['hour'] ?? '')); $ts = $stamp !== '' ? strtotime(str_replace('.', '-', $stamp)) : false; $desc = (string) ($e['statusDescription'] ?? ''); $checkpoints[] = array( 'code' => (string) ($e['statusCode'] ?? ''), 'description' => $desc, 'location' => (string) ($e['branch'] ?? ''), 'checkpoint_at' => $ts ?: null, ); if ($desc !== '') { $latest = $desc; } if ('delivered' === $this->map_status($desc) && $ts) { $delivered_at = $ts; } } return array( 'ok' => true, 'status_code' => $latest, 'checkpoints' => $checkpoints, 'consignee' => null, 'delivered_at' => $delivered_at, ); } public function cancel($voucher_no) { $auth = $this->authenticate(array()); if (empty($auth['ok'])) { return $auth; } $resp = $this->request('POST', '/spedizioni/delete', array( 'account' => $this->account_block(), 'deleteData' => array( 'senderCustomerCode' => (string) ($this->credentials()['client_id'] ?? ''), 'parcelNumber' => (string) $voucher_no, ), )); if (is_wp_error($resp)) { return array('ok' => false, 'error' => $resp->get_error_message()); } $exec = $resp['deleteResponse']['executionMessage'] ?? array(); if ((int) ($exec['code'] ?? 0) !== 0) { return array('ok' => false, 'error' => trim((string) ($exec['message'] ?? '')) ?: __('BRT declined to cancel this shipment.', 'ai-eshop-optimizer')); } return array('ok' => true); } } add_filter('aieo_fulfillment_couriers', static function (array $drivers) { if (!isset($drivers['brt']) && class_exists('AIEO_Courier_Driver_BRT')) { $drivers['brt'] = new AIEO_Courier_Driver_BRT(); } return $drivers; });