diff --git a/Modules/Freight/Config/config.php b/Modules/Freight/Config/config.php index 33a60535eda..8d196fe3a4c 100644 --- a/Modules/Freight/Config/config.php +++ b/Modules/Freight/Config/config.php @@ -19,6 +19,30 @@ return [ 'account_url' => 'https://www.wearewarp.com/agents/account', ], + /* + |-------------------------------------------------------------------------- + | ShipStation (SKU-8974) — V2 API /v2/freight + |-------------------------------------------------------------------------- + | + | The merchant's own V2 API key (`api-key` header). A TEST_ key is ShipStation's sandbox, which has + | no freight provider today. Rates come from the Worldwide Express / Unishippers account the + | merchant connected in ShipStation. A lost booking is searched for from the booking attempt's + | send time, less `booking_clock_skew_seconds` (our clock vs ShipStation's), over at most + | `booking_search_pages` pages of `booking_search_page_size`; a search that runs out of pages, + | or can't tell a page is the last, leaves the load unconfirmed. + | + */ + 'shipstation' => [ + 'base_url' => env('FREIGHT_SHIPSTATION_BASE_URL', 'https://api.shipstation.com'), + 'timeout' => (int) env('FREIGHT_SHIPSTATION_TIMEOUT', 30), + 'booking_clock_skew_seconds' => 120, + 'booking_search_pages' => 5, + 'booking_search_page_size' => 100, + // A booking can take a while to appear in ShipStation's list: until this long after the + // attempt, finding nothing leaves the load unconfirmed instead of "not booked" + 'booking_settle_seconds' => 300, + ], + /* |-------------------------------------------------------------------------- | Tracking diff --git a/Modules/Freight/Contracts/FreightProviderDriver.php b/Modules/Freight/Contracts/FreightProviderDriver.php index 98b4d3e2558..68c11f63fd4 100644 --- a/Modules/Freight/Contracts/FreightProviderDriver.php +++ b/Modules/Freight/Contracts/FreightProviderDriver.php @@ -3,6 +3,7 @@ namespace Modules\Freight\Contracts; use Modules\Freight\Data\FreightAccountStatusData; +use Modules\Freight\Data\FreightBookingAttemptData; use Modules\Freight\Data\FreightBookingRequestData; use Modules\Freight\Data\FreightBookingResultData; use Modules\Freight\Data\FreightCapabilitiesData; @@ -70,9 +71,13 @@ interface FreightProviderDriver public function documents(FreightIntegrationInstance $instance, FreightShipment $shipment): array; /** - * Find a booking made for a provider quote id, after a booking call whose outcome was unknown + * Find a booking made for a provider quote id, after a booking call whose outcome was unknown. + * `$attempt` is the booking try (its unique reference and send time), for providers that match on + * the reference they were booked with. Null means "not booked"; a search that could not be + * completed throws {@see FreightProviderUnavailableException} so the load stays unconfirmed. * + * @throws FreightProviderUnavailableException * @throws FreightProviderException */ - public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference): ?FreightBookingResultData; + public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference, ?FreightBookingAttemptData $attempt = null): ?FreightBookingResultData; } diff --git a/Modules/Freight/Data/FreightAccountStatusData.php b/Modules/Freight/Data/FreightAccountStatusData.php index 53f6604efbf..d74f3327abb 100644 --- a/Modules/Freight/Data/FreightAccountStatusData.php +++ b/Modules/Freight/Data/FreightAccountStatusData.php @@ -12,10 +12,14 @@ class FreightAccountStatusData extends Data { /** * @param list $warnings + * @param array $settings provider settings the test found, merged into the + * connection's `integration_settings` (ShipStation: its + * freight provider accounts and the one selected) */ public function __construct( public string $environment, public ?string $account_label = null, public array $warnings = [], + public array $settings = [], ) {} } diff --git a/Modules/Freight/Data/FreightBookingAttemptData.php b/Modules/Freight/Data/FreightBookingAttemptData.php new file mode 100644 index 00000000000..d540921d32e --- /dev/null +++ b/Modules/Freight/Data/FreightBookingAttemptData.php @@ -0,0 +1,36 @@ +|null $contacts + */ + public static function fromContacts(?array $contacts): ?self + { + $reference = data_get($contacts, 'booking_reference'); + $attemptedAt = data_get($contacts, 'attempted_at'); + + return filled($reference) && filled($attemptedAt) + ? new self((string) $reference, CarbonImmutable::parse((string) $attemptedAt)) + : null; + } +} diff --git a/Modules/Freight/Data/FreightBookingRequestData.php b/Modules/Freight/Data/FreightBookingRequestData.php index e13dc58c51e..123feb35753 100644 --- a/Modules/Freight/Data/FreightBookingRequestData.php +++ b/Modules/Freight/Data/FreightBookingRequestData.php @@ -11,6 +11,9 @@ use Spatie\LaravelData\Data; */ class FreightBookingRequestData extends Data { + /** + * @param list $handling_units + */ public function __construct( public string $provider_quote_id, public FreightAddressData $origin, @@ -26,5 +29,9 @@ class FreightBookingRequestData extends Data /** Reference on the delivery stop's BOL line (the customer's PO) */ public ?string $delivery_reference = null, public ?string $special_instructions = null, + /** This try's unique reference and send time, printed into the booking so a lost answer can be found */ + public ?FreightBookingAttemptData $attempt = null, + /** The load as quoted, for providers that book it inline */ + public array $handling_units = [], ) {} } diff --git a/Modules/Freight/Data/FreightCapabilitiesData.php b/Modules/Freight/Data/FreightCapabilitiesData.php index 2e102d67892..b938dd927e7 100644 --- a/Modules/Freight/Data/FreightCapabilitiesData.php +++ b/Modules/Freight/Data/FreightCapabilitiesData.php @@ -27,5 +27,7 @@ class FreightCapabilitiesData extends Data public array $countries = ['US'], /** How cancelling works when there is no API, shown in the cancel dialog */ public ?string $cancel_instructions = null, + /** Shown when "Check booking" finds no booking and the load returns to Quoted: what is safe to do next */ + public ?string $missing_booking_message = null, ) {} } diff --git a/Modules/Freight/Database/Factories/FreightIntegrationInstanceFactory.php b/Modules/Freight/Database/Factories/FreightIntegrationInstanceFactory.php index 68a71940f55..3b9edad8ad0 100644 --- a/Modules/Freight/Database/Factories/FreightIntegrationInstanceFactory.php +++ b/Modules/Freight/Database/Factories/FreightIntegrationInstanceFactory.php @@ -31,6 +31,15 @@ class FreightIntegrationInstanceFactory extends Factory return $this->state(fn (): array => $this->attributesFor($provider)); } + /** + * A ShipStation connection (SKU-8974) on a production V2 key, with one Worldwide Express provider + * account found and selected + */ + public function shipStation(): static + { + return $this->provider(FreightProviderEnum::ShipStation); + } + public function production(): static { return $this->state(fn (): array => [ @@ -46,15 +55,28 @@ class FreightIntegrationInstanceFactory extends Factory { $integration = Integration::query()->firstOrCreate( ['name' => $provider->integrationName()], - ['integration_type' => Integration::TYPE_FREIGHT, 'supports_multiple_instances' => false, 'integration_settings_template' => []], + ['integration_type' => Integration::TYPE_FREIGHT, 'supports_multiple_instances' => $provider->allowsMultipleConnections(), 'integration_settings_template' => []], ); return [ 'integration_id' => $integration->id, 'name' => $provider->label().' '.Str::random(6), - 'connection_settings' => ['api_key' => 'wak_test_'.Str::random(40)], - 'integration_settings' => ['carrier_scac' => null, 'account_warnings' => []], - 'environment' => IntegrationEnvironmentEnum::SANDBOX->value, + ...match ($provider) { + FreightProviderEnum::Warp => [ + 'connection_settings' => ['api_key' => 'wak_test_'.Str::random(40)], + 'integration_settings' => ['carrier_scac' => null, 'account_warnings' => []], + 'environment' => IntegrationEnvironmentEnum::SANDBOX->value, + ], + FreightProviderEnum::ShipStation => [ + 'connection_settings' => ['api_key' => Str::random(44)], + 'integration_settings' => [ + 'provider_accounts' => [['id' => 'se-4433221', 'code' => 'WWEX', 'nickname' => 'WWEX Main']], + 'freight_provider_account_id' => 'se-4433221', + 'account_warnings' => [], + ], + 'environment' => IntegrationEnvironmentEnum::PRODUCTION->value, + ], + }, 'is_automatic_sync_enabled' => true, ]; } diff --git a/Modules/Freight/Drivers/ShipStationFreightDriver.php b/Modules/Freight/Drivers/ShipStationFreightDriver.php new file mode 100644 index 00000000000..51130b39889 --- /dev/null +++ b/Modules/Freight/Drivers/ShipStationFreightDriver.php @@ -0,0 +1,949 @@ + ShipStation freight provider code → the broker's name */ + private const PROVIDER_NAMES = [ + 'WWEX' => 'Worldwide Express', + 'UNISHIPPERS' => 'Unishippers', + ]; + + /** @var array neutral code → ShipStation accessorial per stop */ + private const ACCESSORIALS = [ + 'liftgate' => ['pickup' => 'liftgate_pickup', 'delivery' => 'liftgate_delivery'], + 'inside' => ['pickup' => 'inside_pickup', 'delivery' => 'inside_delivery'], + 'residential' => ['pickup' => 'residential_pickup', 'delivery' => 'residential_delivery'], + // Limited access is a location type in ShipStation, not an accessorial ({@see self::locationType()}) + 'limited_access' => ['pickup' => null, 'delivery' => null], + 'appointment' => ['pickup' => null, 'delivery' => 'appointment_delivery'], + 'notify' => ['pickup' => null, 'delivery' => 'notify_before_delivery'], + ]; + + /** @var array SKU.io destination type → ShipStation location_type */ + private const LOCATION_TYPES = [ + DestinationTypeEnum::BusinessDock->value => 'commercial', + DestinationTypeEnum::BusinessNoDock->value => 'commercial', + DestinationTypeEnum::Residence->value => 'residential', + DestinationTypeEnum::RetailDc->value => 'distribution_center', + DestinationTypeEnum::LimitedAccess->value => 'limited_access', + DestinationTypeEnum::TradeShow->value => 'trade_show', + DestinationTypeEnum::Construction->value => 'construction', + ]; + + /** @var array ShipStation freight status (and event status) → SKU.io status */ + private const STATUS_MAP = [ + 'pending' => FreightShipmentStatusEnum::Booked, + 'quoted' => FreightShipmentStatusEnum::Booked, + 'booked' => FreightShipmentStatusEnum::Booked, + 'picked_up' => FreightShipmentStatusEnum::PickedUp, + 'in_transit' => FreightShipmentStatusEnum::InTransit, + 'out_for_delivery' => FreightShipmentStatusEnum::OutForDelivery, + 'delivered' => FreightShipmentStatusEnum::Delivered, + 'cancelled' => FreightShipmentStatusEnum::Cancelled, + 'canceled' => FreightShipmentStatusEnum::Cancelled, + 'exception' => FreightShipmentStatusEnum::Exception, + ]; + + public function __construct( + private readonly FreightSettings $settings, + private readonly FreightShipmentRepository $freightShipments, + ) {} + + public function capabilities(): FreightCapabilitiesData + { + $codes = array_map(fn (FreightAccessorialEnum $accessorial) => $accessorial->value, FreightAccessorialEnum::cases()); + + return new FreightCapabilitiesData( + modes: [FreightModeEnum::Ltl->value], + pickup_accessorials: array_values(array_filter($codes, fn (string $code) => $this->supportsAt($code, 'pickup'))), + delivery_accessorials: array_values(array_filter($codes, fn (string $code) => $this->supportsAt($code, 'delivery'))), + supports_cancel: true, + supports_hazmat: true, + supports_tracking: true, + supports_documents: true, + countries: ['US'], + missing_booking_message: 'ShipStation has no booking carrying this attempt\'s SKU.io reference, so nothing was booked. Get new rates or book the rate again.', + ); + } + + /** + * Lists the account's freight provider accounts. None → saved, with a warning that blocks quoting; + * one → selected; several → the merchant picks (the selection is kept while the account has it). + * + * @throws FreightProviderAuthException + * @throws FreightProviderException + */ + public function testConnection(FreightIntegrationInstance $instance): FreightAccountStatusData + { + $body = $this->send($instance, new ShipStationListProviderAccountsRequest, 'Testing the connection'); + + $accounts = []; + foreach ($this->listFrom($body, ['provider_accounts', 'freight_provider_accounts']) as $account) { + $id = (string) ($account['freight_provider_account_id'] ?? $account['provider_account_id'] ?? ''); + if ($id === '') { + continue; + } + + $accounts[] = [ + 'id' => $id, + 'code' => strtoupper((string) ($account['freight_provider_code'] ?? '')), + 'nickname' => filled($account['nickname'] ?? null) ? (string) $account['nickname'] : null, + ]; + } + + $ids = array_column($accounts, 'id'); + $current = (string) ($instance->setting(self::SETTING_PROVIDER_ACCOUNT) ?? ''); + $selected = match (true) { + $current !== '' && in_array($current, $ids, true) => $current, + count($ids) === 1 => $ids[0], + default => null, + }; + + $warnings = match (true) { + $accounts === [] => [self::NO_PROVIDER_ACCOUNT_MESSAGE], + $selected === null => [self::PICK_PROVIDER_ACCOUNT_MESSAGE], + default => [], + }; + + return new FreightAccountStatusData( + environment: $this->isSandboxKey($instance) ? IntegrationEnvironmentEnum::SANDBOX->value : IntegrationEnvironmentEnum::PRODUCTION->value, + account_label: $accounts === [] ? null : implode(', ', array_map(fn (array $account) => self::accountLabel($account), $accounts)), + warnings: $warnings, + settings: ['provider_accounts' => $accounts, self::SETTING_PROVIDER_ACCOUNT => $selected], + ); + } + + /** + * @throws FreightProviderException + */ + public function quote(FreightIntegrationInstance $instance, FreightQuoteRequestData $request): FreightQuoteResultData + { + if (! in_array($request->mode, [FreightModeEnum::Ltl, FreightModeEnum::Any], true)) { + throw new FreightProviderException('ShipStation freight quotes LTL only.', 'MODE_NOT_SUPPORTED'); + } + + $blocker = self::quoteBlocker($instance); + if ($blocker !== null) { + throw new FreightProviderException($blocker, 'NO_PROVIDER_ACCOUNT'); + } + + $payload = [ + 'freight_provider_account_id' => (string) $instance->setting(self::SETTING_PROVIDER_ACCOUNT), + 'pickup_date' => $request->pickup_date->toDateString(), + 'ship_from' => $this->addressPayload($request->origin, 'pickup', $request->accessorials), + 'ship_to' => $this->addressPayload($request->destination, 'delivery', $request->accessorials), + 'handling_units' => $this->handlingUnitsPayload($request->handling_units, $request->origin), + 'accessorials' => $this->accessorialPayload($request->accessorials), + ]; + $this->assertPhones($request->origin, $request->destination); + + $body = $this->send($instance, new ShipStationQuoteRequest($payload), 'Quoting LTL'); + + $unsupported = $this->unsupportedAccessorials($request->accessorials); + $rates = []; + foreach ((array) ($body['quotes'] ?? []) as $quote) { + $total = $this->amount($quote['total_charges'] ?? null); + if (blank($quote['offer_id'] ?? null) || $total === null) { + continue; + } + + $provider = self::PROVIDER_NAMES[strtoupper((string) ($quote['freight_provider_code'] ?? ''))] ?? null; + $guaranteed = (bool) ($quote['is_guaranteed'] ?? false); + + $rates[] = new FreightRateData( + provider_quote_id: (string) $quote['offer_id'], + mode: FreightModeEnum::Ltl, + total: round($total, 2), + currency: strtoupper((string) (data_get($quote, 'total_charges.currency') ?? 'USD')), + carrier_name: filled($quote['carrier_name'] ?? null) ? (string) $quote['carrier_name'] : null, + carrier_scac: filled($quote['carrier_scac'] ?? null) ? strtoupper((string) $quote['carrier_scac']) : null, + vehicle: $provider !== null ? "LTL via {$provider}" : 'LTL', + service_level: trim(implode(' · ', array_filter([$quote['service_name'] ?? null, $guaranteed ? 'Guaranteed' : null]))) ?: null, + transit_days: is_numeric($quote['transit_days'] ?? null) ? (int) $quote['transit_days'] : null, + estimated_delivery_date: $this->date($quote['estimated_delivery_date'] ?? null), + expires_at: $this->dateTime($quote['quote_expiration_date'] ?? null), + tier: $guaranteed ? 'guaranteed' : null, + warnings: [], + unsupported_accessorials: $unsupported, + charges: null, + ); + } + + if ($rates === []) { + throw new FreightProviderException('No carrier through your ShipStation freight account serves this lane as described.', 'NO_QUOTES'); + } + + return new FreightQuoteResultData(rates: $rates); + } + + /** + * @throws FreightProviderUnavailableException when the outcome is unknown (timeout, 5xx) + * @throws FreightProviderException + */ + public function book(FreightIntegrationInstance $instance, FreightBookingRequestData $request): FreightBookingResultData + { + $this->assertPhones($request->origin, $request->destination); + + $payload = array_filter([ + 'offer_id' => $request->provider_quote_id, + 'pickup_details' => [ + 'pickup_date' => $request->pickup_date->toDateString(), + 'ready_time' => $request->pickup_window?->from ?? $this->settings->dock_open, + 'close_time' => $request->pickup_window?->to ?? $this->settings->dock_close, + 'is_self_scheduled' => false, + 'location_type' => $this->locationType($request->origin, 'pickup', $request->accessorials), + ], + 'ship_from' => $this->addressPayload($request->origin, 'pickup', $request->accessorials), + 'ship_to' => $this->addressPayload($request->destination, 'delivery', $request->accessorials), + 'handling_units' => $request->handling_units !== [] ? $this->handlingUnitsPayload($request->handling_units, $request->origin) : null, + 'references' => $this->referencesPayload($request), + 'pickup_instructions' => $request->special_instructions, + 'delivery_instructions' => $request->delivery_window && in_array(FreightAccessorialEnum::Appointment->value, $request->accessorials->delivery, true) + ? "Delivery appointment {$request->delivery_window->from}–{$request->delivery_window->to}" + : null, + 'notifications' => filled($request->origin->email) ? [[ + 'events' => ['booked', 'in_transit', 'delivered', 'cancelled', 'exception'], + 'email_addresses' => [(string) $request->origin->email], + ]] : null, + ], fn ($value) => $value !== null && $value !== '' && $value !== []); + + $body = $this->send($instance, new ShipStationCreateShipmentRequest($payload), 'Booking'); + + if (blank($body['freight_shipment_id'] ?? null)) { + throw new FreightProviderUnavailableException('ShipStation did not confirm the booking. Check the booking before trying again.'); + } + + if ($request->attempt !== null && $this->referenceValue($body, self::LOAD_REFERENCE_TYPE) !== $request->attempt->reference) { + Log::warning('ShipStation freight booking did not echo the SKU.io booking reference; a lost answer for this connection may not be checkable', [ + 'freight_shipment_id' => (string) $body['freight_shipment_id'], + 'integration_instance_id' => $instance->id, + ]); + } + + return $this->bookingResult($instance, $body); + } + + /** + * @throws FreightProviderException + */ + public function cancel(FreightIntegrationInstance $instance, FreightShipment $shipment): void + { + $this->sendRaw($instance, new ShipStationCancelShipmentRequest((string) $shipment->provider_shipment_id), 'Cancelling'); + } + + /** + * @throws FreightProviderException + */ + public function track(FreightIntegrationInstance $instance, FreightShipment $shipment): FreightTrackingResultData + { + $body = $this->send($instance, new ShipStationTrackShipmentRequest((string) $shipment->provider_shipment_id), 'Tracking'); + + $events = []; + foreach ($this->listFrom($body, ['events', 'tracking_events']) as $event) { + $when = $this->dateTime($event['occurred_at'] ?? $event['event_date'] ?? null); + $providerStatus = mb_strtolower((string) ($event['status'] ?? $event['status_code'] ?? '')); + if ($when === null) { + continue; + } + + $description = $event['description'] ?? $event['message'] ?? null; + $location = trim(implode(', ', array_filter([$event['city_locality'] ?? null, $event['state_province'] ?? null]))); + + $events[] = new FreightTrackingEventData( + provider_event_id: substr(sha1($providerStatus.'|'.$when->toIso8601String().'|'.$description), 0, 40), + occurred_at: $when, + // An event status ShipStation documents no meaning for keeps the load where it is + status: self::STATUS_MAP[$providerStatus] ?? $shipment->status, + provider_status: $providerStatus !== '' ? $providerStatus : null, + description: $description !== null ? mb_substr((string) $description, 0, 255) : null, + location: $location !== '' ? $location : null, + latitude: is_numeric($event['latitude'] ?? null) ? (float) $event['latitude'] : null, + longitude: is_numeric($event['longitude'] ?? null) ? (float) $event['longitude'] : null, + ); + } + + usort($events, fn (FreightTrackingEventData $a, FreightTrackingEventData $b) => $a->occurred_at <=> $b->occurred_at); + + $liveStatus = mb_strtolower((string) ($body['status'] ?? '')); + // Picked up only when ShipStation says so: a pickup date, or an explicit picked-up event + $pickedUp = collect($events)->first(fn (FreightTrackingEventData $event) => $event->provider_status === 'picked_up'); + $delivered = collect($events)->first(fn (FreightTrackingEventData $event) => $event->provider_status === 'delivered'); + + return new FreightTrackingResultData( + status: self::STATUS_MAP[$liveStatus] ?? null, + provider_status: $liveStatus !== '' ? $liveStatus : null, + carrier_pro_number: filled($body['pro_number'] ?? null) ? mb_substr((string) $body['pro_number'], 0, 35) : null, + estimated_delivery_date: $this->date($body['estimated_delivery_date'] ?? null), + picked_up_at: $this->dateTime($body['actual_pickup_date'] ?? null) ?? $pickedUp?->occurred_at, + delivered_at: $this->dateTime($body['actual_delivery_date'] ?? null) ?? $delivered?->occurred_at, + events: $events, + ); + } + + /** + * @return list + * + * @throws FreightProviderException + */ + public function documents(FreightIntegrationInstance $instance, FreightShipment $shipment): array + { + $body = $this->send($instance, new ShipStationShipmentDocumentsRequest((string) $shipment->provider_shipment_id), 'Fetching documents'); + + $documents = []; + foreach ($this->listFrom($body, ['documents']) as $document) { + $type = mb_strtolower((string) ($document['type'] ?? '')); + $url = $document['url'] ?? $document['href'] ?? null; + if ($type === '' || blank($url)) { + continue; + } + + $documents[] = new FreightDocumentData( + type: $type, + label: match ($type) { + 'bol', 'bill_of_lading' => 'ShipStation bill of lading', + 'label', 'labels', 'pallet_label', 'pallet_labels', 'shipping_label' => 'Pallet labels', + 'pod', 'proof_of_delivery' => 'Proof of delivery', + default => 'ShipStation '.str_replace('_', ' ', $type), + }, + url: (string) $url, + ); + } + + return $documents; + } + + /** + * ShipStation has no idempotency key, so a booking whose answer was lost is found among the + * account's freight shipments created since the attempt was sent, by the attempt's unique + * `sku_load` reference only (never the load number or PO, which other bookings can share). + * Cancelled shipments never match. A search that runs out of pages before the window is covered + * throws, so the load stays unconfirmed rather than being read as "not booked". + * + * @throws FreightProviderUnavailableException + * @throws FreightProviderException + */ + public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference, ?FreightBookingAttemptData $attempt = null): ?FreightBookingResultData + { + if ($attempt === null) { + throw new FreightProviderUnavailableException('This booking was sent without a SKU.io booking reference, so it can\'t be checked automatically. Look for it in ShipStation → Freight: if it is not there, mark the load cancelled and quote it again.', 'NO_BOOKING_REFERENCE'); + } + + $start = $attempt->attempted_at->utc()->subSeconds((int) config('freight.shipstation.booking_clock_skew_seconds', 120)); + $end = CarbonImmutable::now('UTC')->addMinutes(5); + $maxPages = max(1, (int) config('freight.shipstation.booking_search_pages', 5)); + $pageSize = max(1, (int) config('freight.shipstation.booking_search_page_size', 100)); + + $seenIds = []; + $sawReferenceType = false; + + for ($page = 1; $page <= $maxPages; $page++) { + $body = $this->send($instance, new ShipStationListShipmentsRequest($start->toIso8601ZuluString(), $end->toIso8601ZuluString(), $page, $pageSize), 'Checking bookings'); + $listed = $this->shipmentListFrom($body); + foreach ($listed as $index => $shipment) { + $seenIds[(string) ($shipment['freight_shipment_id'] ?? "page{$page}-{$index}")] = true; + } + $seen = count($seenIds); + + foreach ($listed as $shipment) { + if ($this->referenceValue($shipment, self::LOAD_REFERENCE_TYPE) !== null) { + $sawReferenceType = true; + } + + if (blank($shipment['freight_shipment_id'] ?? null) || in_array(mb_strtolower((string) ($shipment['status'] ?? '')), ['cancelled', 'canceled'], true)) { + continue; + } + + if ($this->referenceValue($shipment, self::LOAD_REFERENCE_TYPE) !== $attempt->reference) { + continue; + } + + // The reference is this attempt's own, so a shipment carrying it from before the + // attempt was sent is not something to adopt or to read as "not booked" + $createdAt = $this->dateTime($shipment['created_at'] ?? null); + if ($createdAt !== null && $createdAt->lt($start)) { + throw new FreightProviderUnavailableException("ShipStation shows freight shipment {$shipment['freight_shipment_id']} with this booking's reference, created before the booking was sent, so it was not attached. Check the booking in ShipStation → Freight.", 'REFERENCE_BEFORE_ATTEMPT'); + } + + return $this->bookingResult($instance, $shipment); + } + + if (! $this->isLastPage($body, $page, count($listed), $seen, $pageSize)) { + continue; + } + + // "Not booked" needs proof the search could have seen our reference: some listed + // shipment carries a sku_load reference, or the window held no shipments at all + if ($seen > 0 && ! $sawReferenceType && ! $this->referenceRoundTrips($instance)) { + throw new FreightProviderUnavailableException(self::REFERENCE_UNSUPPORTED_MESSAGE, 'REFERENCE_UNSUPPORTED'); + } + + if (CarbonImmutable::now()->lt($attempt->attempted_at->addSeconds((int) config('freight.shipstation.booking_settle_seconds', 300)))) { + throw new FreightProviderUnavailableException(self::BOOKING_SETTLING_MESSAGE, 'BOOKING_SETTLING'); + } + + return null; + } + + throw new FreightProviderUnavailableException("ShipStation lists more freight shipments since this booking was sent than SKU.io searches ({$maxPages} pages), so whether it booked is unknown. Look for it in ShipStation → Freight before booking again.", 'SEARCH_INCOMPLETE'); + } + + /** + * Proof that ShipStation keeps and returns SKU.io's booking reference: the connection's latest + * booking made through SKU.io still carries it. Needed when the search window only held shipments + * booked outside SKU.io (they have no sku_load reference), so the window alone proves nothing. + * + * @throws FreightProviderException + */ + private function referenceRoundTrips(FreightIntegrationInstance $instance): bool + { + $latest = $this->freightShipments->latestProviderShipmentIdForConnection($instance->id); + if ($latest === null) { + return false; + } + + $body = $this->send($instance, new ShipStationGetShipmentRequest($latest), 'Checking bookings'); + + return $this->referenceValue($body, self::LOAD_REFERENCE_TYPE) !== null; + } + + /** + * Why a connection can't quote yet: no freight provider account in ShipStation, or none picked + */ + public static function quoteBlocker(FreightIntegrationInstance $instance): ?string + { + $accounts = (array) ($instance->setting('provider_accounts') ?? []); + $selected = (string) ($instance->setting(self::SETTING_PROVIDER_ACCOUNT) ?? ''); + + return match (true) { + $accounts === [] && $selected === '' => self::NO_PROVIDER_ACCOUNT_MESSAGE, + $selected === '' => self::PICK_PROVIDER_ACCOUNT_MESSAGE, + default => null, + }; + } + + /** + * The freight provider accounts the last test found, as select options + * + * @return list + */ + public static function providerAccountOptions(FreightIntegrationInstance $instance): array + { + $options = []; + foreach ((array) ($instance->setting('provider_accounts') ?? []) as $account) { + if (filled($account['id'] ?? null)) { + $options[] = ['value' => (string) $account['id'], 'label' => self::accountLabel($account)]; + } + } + + return $options; + } + + /** + * "WWEX Main (Worldwide Express)" + * + * @param array{id?: string, code?: string, nickname?: string|null} $account + */ + private static function accountLabel(array $account): string + { + $provider = self::PROVIDER_NAMES[strtoupper((string) ($account['code'] ?? ''))] ?? ($account['code'] ?? null); + $name = $account['nickname'] ?? null; + + return match (true) { + filled($name) && filled($provider) => "{$name} ({$provider})", + filled($provider) => (string) $provider, + default => (string) ($name ?? $account['id'] ?? ''), + }; + } + + /** + * @param array $body + */ + private function bookingResult(FreightIntegrationInstance $instance, array $body): FreightBookingResultData + { + $pro = filled($body['pro_number'] ?? null) ? mb_substr((string) $body['pro_number'], 0, 35) : null; + $bol = filled($body['bol_number'] ?? null) ? (string) $body['bol_number'] : null; + $confirmation = filled($body['confirmation_number'] ?? null) ? (string) $body['confirmation_number'] : null; + + return new FreightBookingResultData( + provider_shipment_id: (string) $body['freight_shipment_id'], + provider_order_id: $confirmation, + shipment_number: $confirmation ?? $bol ?? (string) $body['freight_shipment_id'], + bill_of_lading_number: $bol, + carrier_pro_number: $pro, + carrier_scac: filled($body['carrier_scac'] ?? null) ? strtoupper((string) $body['carrier_scac']) : null, + carrier_name: filled($body['carrier_name'] ?? null) ? (string) $body['carrier_name'] : null, + tracking_url: null, + pickup_date: $this->date(data_get($body, 'pickup_details.pickup_date')), + estimated_delivery_date: $this->date($body['estimated_delivery_date'] ?? null), + total: $this->amount($body['total_charges'] ?? null), + is_sandbox: $this->isSandboxKey($instance), + ); + } + + /** + * A ShipStation stop. Name, company name and phone are required, so each falls back on the other. + * + * @return array + */ + private function addressPayload(FreightAddressData $address, string $stop, FreightAccessorialsData $accessorials): array + { + $name = $address->contact_name ?: $address->company ?: ($stop === 'pickup' ? 'Shipping' : 'Receiving'); + + return array_filter([ + 'name' => $name, + 'company_name' => $address->company ?: $name, + 'phone' => $address->phone, + 'email' => $address->email, + 'address_line1' => $address->street1, + 'address_line2' => $address->street2, + 'city_locality' => $address->city, + 'state_province' => $address->state, + 'postal_code' => $address->zip, + 'country_code' => strtoupper($address->country ?: 'US'), + 'location_type' => $this->locationType($address, $stop, $accessorials), + ], fn ($value) => $value !== null && $value !== ''); + } + + /** + * The stop's location type. Limited access asked for at the stop wins (ShipStation has no + * limited-access accessorial, so it is priced through the location type); then the stop's + * destination type; then residential for a residential stop; else commercial. + */ + private function locationType(FreightAddressData $address, string $stop, FreightAccessorialsData $accessorials): string + { + $codes = $stop === 'pickup' ? $accessorials->pickup : $accessorials->delivery; + + return match (true) { + in_array(FreightAccessorialEnum::LimitedAccess->value, $codes, true) => 'limited_access', + $address->destination_type !== null && isset(self::LOCATION_TYPES[$address->destination_type]) => self::LOCATION_TYPES[$address->destination_type], + in_array(FreightAccessorialEnum::Residential->value, $codes, true) => 'residential', + default => 'commercial', + }; + } + + /** + * Whether ShipStation can be asked for a service at a stop: as an accessorial flag, or (limited + * access) through the stop's location type + */ + private function supportsAt(string $code, string $stop): bool + { + return (self::ACCESSORIALS[$code][$stop] ?? null) !== null || $code === FreightAccessorialEnum::LimitedAccess->value; + } + + /** + * Each handling-unit line with its one commodity. Units always ride along: the live API rejects a + * unit without `dimension_unit` or a commodity without `weight_unit`. + * + * @param list $units + * @return list> + * + * @throws FreightProviderException + */ + private function handlingUnitsPayload(array $units, FreightAddressData $origin): array + { + return array_map(function (HandlingUnitData $unit) use ($origin): array { + $class = $unit->freight_class !== null ? FreightClassEnum::tryFrom((string) $unit->freight_class) : null; + if ($unit->freight_class !== null && $class === null) { + throw new FreightProviderException("Freight class {$unit->freight_class} is not one ShipStation accepts (50 to 500).", 'INVALID_FREIGHT_CLASS', ['freight_class' => 'Not an NMFC class']); + } + $class ??= FreightClassEnum::forDensity((float) ($unit->density() ?? 0)); + + return [ + 'type' => $unit->type, + 'quantity' => $unit->quantity, + 'length' => (int) ceil($unit->length_in), + 'width' => (int) ceil($unit->width_in), + 'height' => (int) ceil($unit->height_in), + 'dimension_unit' => 'inch', + 'stackable' => $unit->stackable, + 'commodities' => [array_filter([ + 'description' => $unit->description ?: 'Freight', + 'quantity' => $unit->quantity, + 'packaging_type' => $unit->type, + 'weight' => (int) ceil($unit->weight_lb_each), + 'weight_unit' => 'pound', + 'freight_class' => $class->value, + 'nmfc_code' => $unit->nmfc_code, + 'hazardous_materials' => $unit->isHazmat() ? $this->hazmatPayload($unit, $origin) : null, + ], fn ($value) => $value !== null && $value !== '')], + ]; + }, $units); + } + + /** + * @return array + */ + private function hazmatPayload(HandlingUnitData $unit, FreightAddressData $origin): array + { + $hazmat = $unit->hazmat; + $id = strtoupper(preg_replace('/\s+/', '', (string) $hazmat?->un_number) ?? ''); + $type = str_starts_with($id, 'NA') ? 'na' : 'un'; + $group = mb_strtolower(trim((string) $hazmat?->packing_group)); + + return array_filter([ + 'identification_number_type' => $type, + 'identification_number' => preg_replace('/^(UN|NA)/', '', $id), + 'proper_shipping_name' => $hazmat?->proper_shipping_name, + 'hazard_class' => $hazmat?->hazard_class, + 'packing_group' => in_array($group, ['i', 'ii', 'iii'], true) ? $group : 'none', + 'emergency_contact_name' => $origin->company ?: $origin->contact_name, + 'emergency_contact_phone' => $this->settings->hazmat_emergency_phone, + 'emergency_response_reference' => $this->settings->hazmat_emergency_contract, + ], fn ($value) => $value !== null && $value !== ''); + } + + /** + * @return array + */ + private function accessorialPayload(FreightAccessorialsData $accessorials): array + { + $flags = []; + foreach (['pickup' => $accessorials->pickup, 'delivery' => $accessorials->delivery] as $stop => $codes) { + foreach ($codes as $code) { + $name = self::ACCESSORIALS[$code][$stop] ?? null; + if ($name !== null) { + $flags[$name] = true; + } + } + } + + return $flags; + } + + /** + * Services asked for at either stop that ShipStation has no way to request (e.g. a pickup + * appointment), so the rate says it does not include them instead of dropping them silently + * + * @return list + */ + private function unsupportedAccessorials(FreightAccessorialsData $accessorials): array + { + $unsupported = []; + foreach (['pickup' => $accessorials->pickup, 'delivery' => $accessorials->delivery] as $stop => $codes) { + foreach ($codes as $code) { + if (! $this->supportsAt((string) $code, $stop)) { + $unsupported[] = (string) $code; + } + } + } + + return array_values(array_unique($unsupported)); + } + + /** + * @return list + */ + private function referencesPayload(FreightBookingRequestData $request): array + { + $references = []; + foreach ([ + self::LOAD_REFERENCE_TYPE => $request->attempt?->reference, + 'po_number' => $request->delivery_reference ?? $request->reference, + 'shipper_reference' => $request->pickup_reference, + ] as $type => $value) { + if (filled($value)) { + $references[] = ['type' => $type, 'value' => (string) $value]; + } + } + + return $references; + } + + /** + * The shipments of a list response. Only the documented shapes count (`freight_shipments` or + * `shipments` holding a list, or a bare list): anything else, an error body sent with a 2xx + * included, can't prove a booking is absent. A bare list carries no paging data, so it can only + * ever find a match; on its own it never concludes "not booked". + * + * @param array $body + * @return list> + * + * @throws FreightProviderUnavailableException + */ + private function shipmentListFrom(array $body): array + { + foreach (['freight_shipments', 'shipments'] as $key) { + if (array_key_exists($key, $body) && is_array($body[$key]) && array_is_list($body[$key])) { + return array_values(array_filter($body[$key], 'is_array')); + } + } + + if ($body !== [] && array_is_list($body)) { + return array_values(array_filter($body, 'is_array')); + } + + throw new FreightProviderUnavailableException('ShipStation answered the booking search in a shape SKU.io doesn\'t recognise, so whether this booked is unknown. Look for it in ShipStation → Freight before booking again.', 'SEARCH_INCOMPLETE'); + } + + /** + * Whether a page of the booking search is provably the last: ShipStation's page count or next + * link says so, its total is reached, or the page is short and ShipStation echoed the page size + * asked for (a short page from a server capping the size proves nothing). Anything else throws. + * + * @param array $body + * + * @throws FreightProviderUnavailableException + */ + private function isLastPage(array $body, int $page, int $count, int $seen, int $pageSize): bool + { + $incomplete = fn (): FreightProviderUnavailableException => new FreightProviderUnavailableException('ShipStation\'s booking search didn\'t show whether more shipments follow, so whether this booked is unknown. Look for it in ShipStation → Freight before booking again.', 'SEARCH_INCOMPLETE'); + + if (isset($body['pages']) && is_numeric($body['pages'])) { + return $page >= (int) $body['pages']; + } + + if (filled(data_get($body, 'links.next.href'))) { + return false; + } + + if (isset($body['total']) && is_numeric($body['total'])) { + if ($seen >= (int) $body['total']) { + return true; + } + if ($count === 0) { + throw $incomplete(); + } + + return false; + } + + if (isset($body['page_size']) && (int) $body['page_size'] === $pageSize && $count < $pageSize) { + return true; + } + + throw $incomplete(); + } + + /** + * @param array $shipment + */ + private function referenceValue(array $shipment, string $type): ?string + { + foreach ((array) ($shipment['references'] ?? []) as $reference) { + if (($reference['type'] ?? null) === $type && filled($reference['value'] ?? null)) { + return (string) $reference['value']; + } + } + + return null; + } + + /** + * ShipStation requires a phone on both stops; asked before calling so the message names the stop + * + * @throws FreightProviderException + */ + private function assertPhones(FreightAddressData $origin, FreightAddressData $destination): void + { + $fieldErrors = []; + foreach (['origin.phone' => $origin, 'destination.phone' => $destination] as $field => $address) { + if (blank($address->phone)) { + $fieldErrors[$field] = 'ShipStation needs a phone number for this stop'; + } + } + + if ($fieldErrors !== []) { + throw new FreightProviderException('ShipStation needs a phone number on the ship-from and ship-to addresses.', 'PHONE_REQUIRED', $fieldErrors); + } + } + + private function isSandboxKey(FreightIntegrationInstance $instance): bool + { + return str_starts_with($instance->credential('api_key'), 'TEST_'); + } + + /** + * A list in a response body under one of `$keys`, or the body itself when it is a list + * + * @param array $body + * @param list $keys + * @return list> + */ + private function listFrom(array $body, array $keys): array + { + foreach ($keys as $key) { + if (isset($body[$key]) && is_array($body[$key])) { + return array_values(array_filter($body[$key], 'is_array')); + } + } + + return array_is_list($body) ? array_values(array_filter($body, 'is_array')) : []; + } + + /** + * A money value, bare (`140.2`) or ShipStation's `{currency, amount}` + */ + private function amount(mixed $value): ?float + { + if (is_array($value)) { + $value = $value['amount'] ?? null; + } + + return is_numeric($value) ? (float) $value : null; + } + + /** + * @return array + * + * @throws FreightProviderAuthException + * @throws FreightProviderUnavailableException + * @throws FreightProviderException + */ + private function send(FreightIntegrationInstance $instance, Request $request, string $action): array + { + return (array) ($this->sendRaw($instance, $request, $action)->json() ?? []); + } + + /** + * Send, and turn ShipStation's error bodies (`{request_id, errors: [{error_source, error_type, + * error_code, message, field_name}]}`) into messages a merchant can act on + * + * @throws FreightProviderAuthException + * @throws FreightProviderUnavailableException + * @throws FreightProviderException + */ + private function sendRaw(FreightIntegrationInstance $instance, Request $request, string $action): Response + { + try { + $response = (new ShipStationConnector($instance))->send($request); + } catch (RequestException $e) { + $response = $e->getResponse(); + } catch (FatalRequestException $e) { + report($e); + + throw new FreightProviderUnavailableException('ShipStation did not answer. Try again in a few minutes.', null, [], $e); + } catch (Throwable $e) { + report($e); + + throw new FreightProviderUnavailableException('ShipStation request failed. Try again in a few minutes.', null, [], $e); + } + + if ($response->successful()) { + return $response; + } + + $body = (array) ($response->json() ?? []); + $errors = array_values(array_filter((array) ($body['errors'] ?? []), 'is_array')); + $code = isset($errors[0]['error_code']) ? (string) $errors[0]['error_code'] : null; + $messages = array_values(array_unique(array_filter(array_map(fn (array $error) => trim((string) ($error['message'] ?? '')), $errors)))); + $message = implode(' ', $messages) ?: trim((string) ($body['message'] ?? '')); + + if (in_array($response->status(), [401, 403], true)) { + throw new FreightProviderAuthException('ShipStation didn\'t accept this key. Use a V2 API key from Settings → Account → API Settings.', $code); + } + + if ($response->status() === 429 || $response->status() >= 500) { + throw new FreightProviderUnavailableException("{$action} failed: ShipStation answered {$response->status()}".($message !== '' ? " ({$message})" : '').'. Try again in a few minutes.', $code); + } + + $fieldErrors = []; + foreach ($errors as $error) { + if (filled($error['field_name'] ?? null)) { + $fieldErrors[(string) $error['field_name']] = (string) ($error['message'] ?? 'Rejected by ShipStation'); + } + } + + if (str_contains($message, 'freight_provider_account_id must be a valid provider account id')) { + throw new FreightProviderException(self::PROVIDER_ACCOUNT_GONE_MESSAGE, $code ?? 'INVALID_PROVIDER_ACCOUNT', $fieldErrors); + } + + throw new FreightProviderException($message !== '' ? $message : "{$action} failed (HTTP {$response->status()}).", $code, $fieldErrors); + } + + private function date(mixed $value): ?CarbonImmutable + { + return $this->dateTime($value)?->startOfDay(); + } + + /** + * A date-time ShipStation sent, or null when it is missing or unreadable + */ + private function dateTime(mixed $value): ?CarbonImmutable + { + if (! is_string($value) || $value === '') { + return null; + } + + try { + return CarbonImmutable::parse($value); + } catch (InvalidFormatException) { + return null; + } + } +} diff --git a/Modules/Freight/Drivers/WarpFreightDriver.php b/Modules/Freight/Drivers/WarpFreightDriver.php index c94f5e48ac3..d82129001d4 100644 --- a/Modules/Freight/Drivers/WarpFreightDriver.php +++ b/Modules/Freight/Drivers/WarpFreightDriver.php @@ -7,6 +7,7 @@ use Carbon\CarbonImmutable; use Modules\Freight\Contracts\FreightProviderDriver; use Modules\Freight\Data\FreightAccountStatusData; use Modules\Freight\Data\FreightAddressData; +use Modules\Freight\Data\FreightBookingAttemptData; use Modules\Freight\Data\FreightBookingRequestData; use Modules\Freight\Data\FreightBookingResultData; use Modules\Freight\Data\FreightCapabilitiesData; @@ -105,6 +106,7 @@ class WarpFreightDriver implements FreightProviderDriver max_ltl_height_in: self::MAX_LTL_HEIGHT_IN, countries: ['US'], cancel_instructions: 'Warp cancels bookings by email. Email '.config('freight.warp.support_email').' with the shipment number, then mark the load cancelled here.', + missing_booking_message: 'Warp has no booking for this quote, so nothing was booked. Booking the same rate again is safe: Warp books a quote only once.', ); } @@ -285,7 +287,7 @@ class WarpFreightDriver implements FreightProviderDriver * * @throws FreightProviderException */ - public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference): ?FreightBookingResultData + public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference, ?FreightBookingAttemptData $attempt = null): ?FreightBookingResultData { if (blank($providerQuoteId) && blank($reference)) { return null; diff --git a/Modules/Freight/Enums/FreightProviderEnum.php b/Modules/Freight/Enums/FreightProviderEnum.php index 1e10000f449..5a8a27a9436 100644 --- a/Modules/Freight/Enums/FreightProviderEnum.php +++ b/Modules/Freight/Enums/FreightProviderEnum.php @@ -4,7 +4,9 @@ namespace Modules\Freight\Enums; use App\Models\Integration; use Modules\Freight\Contracts\FreightProviderDriver; +use Modules\Freight\Drivers\ShipStationFreightDriver; use Modules\Freight\Drivers\WarpFreightDriver; +use Modules\Freight\Entities\FreightIntegrationInstance; /** * Freight providers SKU.io can connect, each an `integrations` row of type freight @@ -12,11 +14,13 @@ use Modules\Freight\Drivers\WarpFreightDriver; enum FreightProviderEnum: string { case Warp = 'warp'; + case ShipStation = 'shipstation'; public function label(): string { return match ($this) { self::Warp => 'Warp', + self::ShipStation => 'ShipStation', }; } @@ -24,6 +28,7 @@ enum FreightProviderEnum: string { return match ($this) { self::Warp => Integration::NAME_WARP_FREIGHT, + self::ShipStation => Integration::NAME_SHIPSTATION_FREIGHT, }; } @@ -50,9 +55,19 @@ enum FreightProviderEnum: string { return app(match ($this) { self::Warp => WarpFreightDriver::class, + self::ShipStation => ShipStationFreightDriver::class, }); } + /** + * Whether a tenant may connect several accounts of this provider (two ShipStation accounts, each + * with its own freight provider account) + */ + public function allowsMultipleConnections(): bool + { + return $this === self::ShipStation; + } + /** * Credentials the merchant pastes in, stored in `connection_settings` * @@ -68,23 +83,66 @@ enum FreightProviderEnum: string 'help' => 'From your Warp account (wearewarp.com/agents/account). A key starting wak_test_ is the sandbox: quotes and bookings are test data and nothing is charged.', 'placeholder' => 'wak_live_… or wak_test_…', ]], + self::ShipStation => [[ + 'key' => 'api_key', + 'label' => 'API key', + 'secret' => true, + 'help' => 'Your ShipStation V2 API key (ShipStation → Settings → Account → API Settings → V2 API → Generate API Key). Freight must be set up in ShipStation first: Freight → Connect your account (Worldwide Express or Unishippers).', + 'placeholder' => 'V2 API key', + ]], }; } /** * Provider settings beyond credentials, stored in `integration_settings` * - * @return list + * A `select` field's choices come from the connection ({@see self::settingOptions()}); a `text` + * field is free text up to `max` characters. + * + * @return list */ public function settingFields(): array { return match ($this) { self::Warp => [[ 'key' => 'carrier_scac', + 'type' => 'text', 'label' => 'SCAC on ship notices', 'help' => 'Warp is the carrier of record and does not send a SCAC with a booking. Ask Warp for theirs and enter it here so retailer ship notices (856) carry it.', 'max' => 4, ]], + self::ShipStation => [[ + 'key' => ShipStationFreightDriver::SETTING_PROVIDER_ACCOUNT, + 'type' => 'select', + 'label' => 'Freight provider account', + 'help' => 'The Worldwide Express or Unishippers account connected in ShipStation that quotes and books these loads. Test the connection to refresh the list.', + 'max' => null, + ]], + }; + } + + /** + * Choices of each `select` setting, from what the connection's last test found + * + * @return array> + */ + public function settingOptions(FreightIntegrationInstance $instance): array + { + return match ($this) { + self::Warp => [], + self::ShipStation => [ShipStationFreightDriver::SETTING_PROVIDER_ACCOUNT => ShipStationFreightDriver::providerAccountOptions($instance)], + }; + } + + /** + * Why this connection can't quote yet (shown on its card; its quotes fail with the same reason), + * or null when it can + */ + public function quoteBlocker(FreightIntegrationInstance $instance): ?string + { + return match ($this) { + self::Warp => null, + self::ShipStation => ShipStationFreightDriver::quoteBlocker($instance), }; } @@ -92,6 +150,7 @@ enum FreightProviderEnum: string { return match ($this) { self::Warp => 'https://www.wearewarp.com', + self::ShipStation => 'https://www.shipstation.com', }; } @@ -99,6 +158,7 @@ enum FreightProviderEnum: string { return match ($this) { self::Warp => 'LTL, full truckload and box truck across the US on Warp\'s network. Quote without a card; add one in Warp before booking.', + self::ShipStation => 'LTL rates from the Worldwide Express or Unishippers account connected in your ShipStation, booked, tracked and cancelled without leaving SKU.io.', }; } } diff --git a/Modules/Freight/Http/Controllers/FreightConnectionController.php b/Modules/Freight/Http/Controllers/FreightConnectionController.php index 9035cf6cee5..1f6c033f4aa 100644 --- a/Modules/Freight/Http/Controllers/FreightConnectionController.php +++ b/Modules/Freight/Http/Controllers/FreightConnectionController.php @@ -36,6 +36,7 @@ class FreightConnectionController extends Controller 'website_url' => $provider->websiteUrl(), 'credential_fields' => $provider->credentialFields(), 'setting_fields' => $provider->settingFields(), + 'allows_multiple_connections' => $provider->allowsMultipleConnections(), 'capabilities' => $capabilities->toArray(), ]; }, FreightProviderEnum::cases())]); diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCancelShipmentRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCancelShipmentRequest.php new file mode 100644 index 00000000000..3417d8c7506 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCancelShipmentRequest.php @@ -0,0 +1,21 @@ +freightShipmentId); + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCreateShipmentRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCreateShipmentRequest.php new file mode 100644 index 00000000000..f4088090886 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationCreateShipmentRequest.php @@ -0,0 +1,33 @@ + $payload + */ + public function __construct(protected array $payload) {} + + public function resolveEndpoint(): string + { + return '/v2/freight/shipments'; + } + + protected function defaultBody(): array + { + return $this->payload; + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationGetShipmentRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationGetShipmentRequest.php new file mode 100644 index 00000000000..d0ddfcfd327 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationGetShipmentRequest.php @@ -0,0 +1,21 @@ +freightShipmentId); + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationListProviderAccountsRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationListProviderAccountsRequest.php new file mode 100644 index 00000000000..4c0579cdee5 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationListProviderAccountsRequest.php @@ -0,0 +1,19 @@ + $this->createdAtStart, 'created_at_end' => $this->createdAtEnd, 'page' => $this->page, 'page_size' => $this->pageSize]; + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationQuoteRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationQuoteRequest.php new file mode 100644 index 00000000000..a58fc2b5e65 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationQuoteRequest.php @@ -0,0 +1,33 @@ + $payload + */ + public function __construct(protected array $payload) {} + + public function resolveEndpoint(): string + { + return '/v2/freight/quotes'; + } + + protected function defaultBody(): array + { + return $this->payload; + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationShipmentDocumentsRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationShipmentDocumentsRequest.php new file mode 100644 index 00000000000..035153dfd65 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationShipmentDocumentsRequest.php @@ -0,0 +1,21 @@ +freightShipmentId).'/documents'; + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationTrackShipmentRequest.php b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationTrackShipmentRequest.php new file mode 100644 index 00000000000..e79e1d71694 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/Requests/ShipStationTrackShipmentRequest.php @@ -0,0 +1,21 @@ +freightShipmentId).'/tracking'; + } +} diff --git a/Modules/Freight/Http/Integrations/ShipStation/ShipStationConnector.php b/Modules/Freight/Http/Integrations/ShipStation/ShipStationConnector.php new file mode 100644 index 00000000000..e43b5fefbc6 --- /dev/null +++ b/Modules/Freight/Http/Integrations/ShipStation/ShipStationConnector.php @@ -0,0 +1,55 @@ +baseUrl = (string) config('freight.shipstation.base_url'); + } + + protected function defaultHeaders(): array + { + return [ + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + 'api-key' => $this->integrationInstance->credential('api_key'), + ]; + } + + protected function defaultConfig(): array + { + return ['timeout' => (int) config('freight.shipstation.timeout', 30)]; + } + + /** + * A booking is never retried: ShipStation has no idempotency key, so a second POST after a + * timeout or 5xx could book the load twice. The booking manager marks it unconfirmed instead and + * "Check booking" finds it by its load reference. + */ + public function handleRetry(FatalRequestException|RequestException $exception, Request $request): bool + { + if ($request instanceof ShipStationCreateShipmentRequest) { + return false; + } + + return parent::handleRetry($exception, $request); + } +} diff --git a/Modules/Freight/Http/Requests/SaveFreightConnectionRequest.php b/Modules/Freight/Http/Requests/SaveFreightConnectionRequest.php index b5dc50784cb..b5d0c98f0ad 100644 --- a/Modules/Freight/Http/Requests/SaveFreightConnectionRequest.php +++ b/Modules/Freight/Http/Requests/SaveFreightConnectionRequest.php @@ -5,6 +5,7 @@ namespace Modules\Freight\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Modules\Freight\Data\SaveFreightConnectionData; +use Modules\Freight\Entities\FreightIntegrationInstance; use Modules\Freight\Enums\FreightProviderEnum; use Modules\Freight\Repositories\FreightConnectionRepository; @@ -25,7 +26,8 @@ class SaveFreightConnectionRequest extends FormRequest public function rules(): array { $creating = $this->isMethod('post'); - $existing = $creating ? null : $this->existingProvider(); + $connection = $creating ? null : $this->existingConnection(); + $existing = $connection?->provider(); $provider = $existing ?? FreightProviderEnum::tryFrom((string) $this->input('provider')); $rules = [ @@ -42,18 +44,50 @@ class SaveFreightConnectionRequest extends FormRequest $rules["credentials.{$field['key']}"] = [$creating ? 'required' : 'nullable', 'string', 'max:500']; } + // A select's choices are what the connection's last test found, so they are checked only on an + // edit that keeps the credentials: on connect, or with new credentials, the test that follows + // keeps a choice only when the account has it. The saved value always passes, even once the + // account no longer lists it, so an edit of anything else never fails on it. + $checkOptions = $connection !== null && ! $this->changesCredentials($connection); + $options = $checkOptions ? $connection->provider()->settingOptions($connection) : []; + foreach ($provider?->settingFields() ?? [] as $field) { + if ($field['type'] !== 'select') { + continue; + } + + $allowed = [...array_column($options[$field['key']] ?? [], 'value'), ...array_filter([(string) ($connection?->setting($field['key']) ?? '')])]; + $rules["settings.{$field['key']}"] = $checkOptions + ? ['nullable', 'string', Rule::in($allowed)] + : ['nullable', 'string', 'max:100']; + } + return $rules; } + /** + * Whether the request carries a credential different from the stored one (so the connection is + * tested again); a blank one keeps the stored value + */ + private function changesCredentials(FreightIntegrationInstance $connection): bool + { + foreach ((array) $this->input('credentials', []) as $key => $value) { + if (is_string($value) && trim($value) !== '' && trim($value) !== $connection->credential((string) $key)) { + return true; + } + } + + return false; + } + /** * On edit the credentials are checked against the connection's own provider; a body `provider` * can't switch it. */ - private function existingProvider(): ?FreightProviderEnum + private function existingConnection(): ?FreightIntegrationInstance { $id = $this->route('id'); - return $id === null ? null : app(FreightConnectionRepository::class)->find((int) $id)?->provider(); + return $id === null ? null : app(FreightConnectionRepository::class)->find((int) $id); } /** @@ -65,6 +99,7 @@ class SaveFreightConnectionRequest extends FormRequest 'provider.in' => 'A connection can\'t change provider. Connect the other provider separately.', 'credentials.api_key.required' => 'Paste the API key from your freight account.', 'settings.carrier_scac.regex' => 'A SCAC is 2 to 4 letters.', + 'settings.freight_provider_account_id.in' => 'Pick one of the freight provider accounts ShipStation listed. Test the connection to refresh the list.', ]; } diff --git a/Modules/Freight/Http/Resources/FreightConnectionResource.php b/Modules/Freight/Http/Resources/FreightConnectionResource.php index e1d18efb531..b272879c4bf 100644 --- a/Modules/Freight/Http/Resources/FreightConnectionResource.php +++ b/Modules/Freight/Http/Resources/FreightConnectionResource.php @@ -57,6 +57,8 @@ class FreightConnectionResource extends JsonResource 'environment' => $instance->isSandbox() ? 'sandbox' : 'production', 'credentials' => $credentials, 'settings' => $settings, + 'setting_options' => (object) $provider->settingOptions($instance), + 'quote_blocked_reason' => $provider->quoteBlocker($instance), 'account_label' => $instance->setting('account_label'), 'account_warnings' => $instance->accountWarnings(), 'last_tested_at' => $instance->setting('last_tested_at'), diff --git a/Modules/Freight/Managers/FreightBookingManager.php b/Modules/Freight/Managers/FreightBookingManager.php index 29739799022..9542a5ee780 100644 --- a/Modules/Freight/Managers/FreightBookingManager.php +++ b/Modules/Freight/Managers/FreightBookingManager.php @@ -7,8 +7,10 @@ use App\Models\SalesOrderFulfillment; use App\Models\User; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Str; use Modules\Freight\Data\BookFreightData; use Modules\Freight\Data\FreightAddressData; +use Modules\Freight\Data\FreightBookingAttemptData; use Modules\Freight\Data\FreightBookingRequestData; use Modules\Freight\Data\FreightBookingResultData; use Modules\Freight\Data\FreightContactData; @@ -155,7 +157,8 @@ class FreightBookingManager $this->assertCompleteStops($origin, $destination); $pickupDate = CarbonImmutable::parse($data->pickup_date ?? $locked->pickup_date ?? today()); - $request = $this->bookingRequest($locked, $rate, $origin, $destination, $pickupDate, $data->pickup_window, $data->delivery_window); + $attempt = $this->newAttempt($locked); + $request = $this->bookingRequest($locked, $rate, $origin, $destination, $pickupDate, $data->pickup_window, $data->delivery_window, $attempt); $this->shipments->update($locked, [ 'status' => FreightShipmentStatusEnum::BookingUnknown, @@ -169,6 +172,8 @@ class FreightBookingManager 'pickup_window' => $data->pickup_window?->toArray(), 'delivery_window' => $data->delivery_window?->toArray(), 'reference' => $request->reference, + 'booking_reference' => $attempt->reference, + 'attempted_at' => $attempt->attempted_at->toIso8601String(), 'replaced_retailer_routing' => $routing, 'checking_at' => now()->toIso8601String(), ], @@ -255,7 +260,7 @@ class FreightBookingManager $provider = $connection->provider()->label(); $found = $this->findBooking($shipment, $rate, $connection); if ($found === null) { - $this->revertToQuoted($shipment, "{$provider} has no booking for this quote, so nothing was booked. Booking the same rate again is safe: {$provider} books a quote only once."); + $this->revertToQuoted($shipment, $connection->driver()->capabilities()->missing_booking_message ?? "{$provider} has no booking for this quote, so nothing was booked."); return $shipment; } @@ -419,6 +424,7 @@ class FreightBookingManager CarbonImmutable::parse($shipment->pickup_date ?? today()), $pickupWindow ? FreightTimeWindowData::from($pickupWindow) : null, $deliveryWindow ? FreightTimeWindowData::from($deliveryWindow) : null, + FreightBookingAttemptData::fromContacts($contacts), ); try { @@ -459,7 +465,7 @@ class FreightBookingManager */ private function findBooking(FreightShipment $shipment, FreightRate $rate, FreightIntegrationInstance $connection): ?FreightBookingResultData { - return $connection->driver()->findBookingForQuote($connection, (string) ($shipment->provider_quote_id ?? $rate->provider_quote_id), data_get($shipment->booking_contacts, 'reference')); + return $connection->driver()->findBookingForQuote($connection, (string) ($shipment->provider_quote_id ?? $rate->provider_quote_id), data_get($shipment->booking_contacts, 'reference'), FreightBookingAttemptData::fromContacts((array) ($shipment->booking_contacts ?? []))); } /** @@ -529,10 +535,22 @@ class FreightBookingManager }); } + /** + * A new booking try: a reference no other tenant, load or try shares (`sku---`) + * and its send time, saved on the load with the reservation before the provider is asked + */ + private function newAttempt(FreightShipment $shipment): FreightBookingAttemptData + { + return new FreightBookingAttemptData( + reference: sprintf('sku-%s-%d-%s', tenant()?->getTenantKey() ?? 'central', $shipment->id, Str::lower(Str::random(10))), + attempted_at: CarbonImmutable::now(), + ); + } + /** * What the provider is asked to book, from a load and the stops and windows booked with */ - private function bookingRequest(FreightShipment $shipment, FreightRate $rate, FreightAddressData $origin, FreightAddressData $destination, CarbonImmutable $pickupDate, ?FreightTimeWindowData $pickupWindow, ?FreightTimeWindowData $deliveryWindow): FreightBookingRequestData + private function bookingRequest(FreightShipment $shipment, FreightRate $rate, FreightAddressData $origin, FreightAddressData $destination, CarbonImmutable $pickupDate, ?FreightTimeWindowData $pickupWindow, ?FreightTimeWindowData $deliveryWindow, ?FreightBookingAttemptData $attempt): FreightBookingRequestData { return new FreightBookingRequestData( provider_quote_id: (string) $rate->provider_quote_id, @@ -546,6 +564,8 @@ class FreightBookingManager pickup_reference: $shipment->reference('shipper_reference') ?? $shipment->number, delivery_reference: $shipment->reference('customer_po'), special_instructions: $shipment->special_instructions, + attempt: $attempt, + handling_units: $shipment->handlingUnitData(), ); } diff --git a/Modules/Freight/Managers/FreightConnectionManager.php b/Modules/Freight/Managers/FreightConnectionManager.php index 89b27f5851c..23a0074dcf9 100644 --- a/Modules/Freight/Managers/FreightConnectionManager.php +++ b/Modules/Freight/Managers/FreightConnectionManager.php @@ -32,7 +32,8 @@ class FreightConnectionManager } /** - * Connect a provider: test the credentials first, refuse a second connection of the same provider + * Connect a provider: test the credentials first, refuse a second connection of a provider that + * takes one ({@see FreightProviderEnum::allowsMultipleConnections()}) * * @throws FreightActionRefusedException * @throws FreightProviderException @@ -41,12 +42,12 @@ class FreightConnectionManager { $provider = FreightProviderEnum::from($data->provider); - if ($this->connections->forProvider($provider) !== null) { + if (! $provider->allowsMultipleConnections() && $this->connections->forProvider($provider) !== null) { throw new FreightActionRefusedException("{$provider->label()} is already connected. Edit the existing connection instead."); } $instance = $this->connections->make($provider, [ - 'name' => $data->name ?: $provider->label(), + 'name' => $this->nameFor($provider, $data->name), 'connection_settings' => $this->credentialsFrom($provider, $data->credentials, []), 'integration_settings' => $this->settingsFrom($provider, $data->settings, []), ]); @@ -67,6 +68,7 @@ class FreightConnectionManager * Update a connection. New credentials are tested before they replace the old ones; a blank * secret keeps the stored one (the form never receives secrets back). * + * @throws FreightActionRefusedException when the new name is another connection's * @throws FreightProviderException */ public function update(FreightIntegrationInstance $instance, SaveFreightConnectionData $data): FreightIntegrationInstance @@ -75,11 +77,15 @@ class FreightConnectionManager $credentials = $this->credentialsFrom($provider, $data->credentials, (array) $instance->connection_settings); $settings = $this->settingsFrom($provider, $data->settings, (array) ($instance->integration_settings ?? [])); $attributes = ['name' => $data->name ?: $instance->name, 'integration_settings' => $settings]; + if ($attributes['name'] !== $instance->name && $this->connections->nameTaken($attributes['name'], $instance->id)) { + throw new FreightActionRefusedException("Another connection is already named {$attributes['name']}. Pick another name."); + } if ($credentials !== (array) $instance->connection_settings) { $candidate = $instance->replicate(); $candidate->setRelation('integration', $instance->integration); $candidate->connection_settings = $credentials; + $candidate->integration_settings = $settings; $status = $provider->driver()->testConnection($candidate); $attributes['connection_settings'] = $credentials; @@ -157,6 +163,36 @@ class FreightConnectionManager return $this->shipments->countMovingForConnection($instance->id); } + /** + * The connection's name: the one given (refused when another integration holds it), else the + * provider's label made unique ("ShipStation" is often the shipping connection's name already) + * + * @throws FreightActionRefusedException + */ + private function nameFor(FreightProviderEnum $provider, ?string $given): string + { + if (filled($given)) { + if ($this->connections->nameTaken((string) $given)) { + throw new FreightActionRefusedException("Another connection is already named {$given}. Pick another name."); + } + + return (string) $given; + } + + foreach ([$provider->label(), $provider->label().' Freight'] as $candidate) { + if (! $this->connections->nameTaken($candidate)) { + return $candidate; + } + } + + $number = 2; + while ($this->connections->nameTaken("{$provider->label()} Freight {$number}")) { + $number++; + } + + return "{$provider->label()} Freight {$number}"; + } + /** * Credentials a provider takes, trimmed; a blank value keeps the stored one * @@ -186,7 +222,7 @@ class FreightConnectionManager { foreach ($provider->settingFields() as $field) { if (array_key_exists($field['key'], $given)) { - $value = trim((string) $given[$field['key']]); + $value = trim((string) ($given[$field['key']] ?? '')); $stored[$field['key']] = $value === '' ? null : ($field['key'] === 'carrier_scac' ? strtoupper($value) : $value); } } @@ -202,6 +238,7 @@ class FreightConnectionManager { return [ ...$settings, + ...$status->settings, 'last_tested_at' => now()->toIso8601String(), 'last_test_error' => null, 'account_label' => $status->account_label, diff --git a/Modules/Freight/Repositories/FreightConnectionRepository.php b/Modules/Freight/Repositories/FreightConnectionRepository.php index 926339c24c0..eccf45c90d8 100644 --- a/Modules/Freight/Repositories/FreightConnectionRepository.php +++ b/Modules/Freight/Repositories/FreightConnectionRepository.php @@ -3,6 +3,7 @@ namespace Modules\Freight\Repositories; use App\Models\Integration; +use App\Models\IntegrationInstance; use Illuminate\Database\Eloquent\Collection; use Modules\Freight\Entities\FreightIntegrationInstance; use Modules\Freight\Enums\FreightProviderEnum; @@ -30,6 +31,18 @@ class FreightConnectionRepository return FreightIntegrationInstance::query()->with('integration')->findOrFail($id); } + /** + * Whether any integration instance (freight or not) already has this name: names are unique + * across every integration, so a ShipStation shipping connection named "ShipStation" holds it + */ + public function nameTaken(string $name, ?int $exceptId = null): bool + { + return IntegrationInstance::query() + ->where('name', $name) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + public function forProvider(FreightProviderEnum $provider): ?FreightIntegrationInstance { return FreightIntegrationInstance::query() @@ -42,7 +55,7 @@ class FreightConnectionRepository { return Integration::query()->firstOrCreate( ['name' => $provider->integrationName()], - ['integration_type' => Integration::TYPE_FREIGHT, 'supports_multiple_instances' => false, 'integration_settings_template' => []], + ['integration_type' => Integration::TYPE_FREIGHT, 'supports_multiple_instances' => $provider->allowsMultipleConnections(), 'integration_settings_template' => []], ); } diff --git a/Modules/Freight/Repositories/FreightShipmentRepository.php b/Modules/Freight/Repositories/FreightShipmentRepository.php index 808606035d0..f6843c84337 100644 --- a/Modules/Freight/Repositories/FreightShipmentRepository.php +++ b/Modules/Freight/Repositories/FreightShipmentRepository.php @@ -150,6 +150,21 @@ class FreightShipmentRepository ->first(); } + /** + * The provider shipment id of the connection's most recent booking made through SKU.io, or null + */ + public function latestProviderShipmentIdForConnection(int $integrationInstanceId): ?string + { + $id = FreightShipment::query() + ->where('integration_instance_id', $integrationInstanceId) + ->whereNotNull('provider_shipment_id') + ->whereNotNull('booked_at') + ->latest('booked_at') + ->value('provider_shipment_id'); + + return $id === null ? null : (string) $id; + } + public function countBookedSince(int $integrationInstanceId, DateTimeInterface $since): int { return FreightShipment::query() diff --git a/Modules/Freight/Tests/Feature/FreightBookingTest.php b/Modules/Freight/Tests/Feature/FreightBookingTest.php index 4adfbed4d32..60bf156f01d 100644 --- a/Modules/Freight/Tests/Feature/FreightBookingTest.php +++ b/Modules/Freight/Tests/Feature/FreightBookingTest.php @@ -9,6 +9,7 @@ use App\Models\SalesOrderFulfillmentFreightDetail; use App\Models\User; use Laravel\Sanctum\Sanctum; use Mockery; +use Modules\Freight\Data\FreightBookingAttemptData; use Modules\Freight\Data\FreightBookingResultData; use Modules\Freight\Data\FreightCapabilitiesData; use Modules\Freight\Drivers\WarpFreightDriver; @@ -200,7 +201,7 @@ class FreightBookingTest extends FreightTestCase ->assertJsonPath('data.status', 'quoted') ->assertJsonPath('data.booking', null); - $this->assertStringContainsString('Booking the same rate again is safe', (string) $shipment->fresh()->last_tracking_error); + $this->assertSame('Warp has no booking for this quote, so nothing was booked. Booking the same rate again is safe: Warp books a quote only once.', $shipment->fresh()->last_tracking_error, 'Warp\'s wording is unchanged now that the provider supplies it'); } public function test_a_shipment_whose_ship_notice_was_sent_keeps_its_freight_details(): void @@ -558,7 +559,7 @@ class FreightBookingTest extends FreightTestCase { public function __construct(private readonly int $cancelledId) {} - public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference): ?FreightBookingResultData + public function findBookingForQuote(FreightIntegrationInstance $instance, string $providerQuoteId, ?string $reference, ?FreightBookingAttemptData $attempt = null): ?FreightBookingResultData { FreightShipment::query()->whereKey($this->cancelledId)->update(['status' => FreightShipmentStatusEnum::Cancelled->value, 'cancelled_at' => now()]); diff --git a/Modules/Freight/Tests/Feature/FreightIntegrationCatalogTest.php b/Modules/Freight/Tests/Feature/FreightIntegrationCatalogTest.php index 2be0ad9aafb..2cfd084589f 100644 --- a/Modules/Freight/Tests/Feature/FreightIntegrationCatalogTest.php +++ b/Modules/Freight/Tests/Feature/FreightIntegrationCatalogTest.php @@ -24,12 +24,12 @@ class FreightIntegrationCatalogTest extends FreightTestCase $this->assertSame([], $warp['integration_instances']); } - public function test_the_freight_category_filter_returns_warp(): void + public function test_the_freight_category_filter_returns_every_freight_provider(): void { $names = collect($this->getJson('/api/integrations?filter[integration_type]='.Integration::TYPE_FREIGHT)->assertOk()->json('data')) ->pluck('name'); - $this->assertSame([Integration::NAME_WARP_FREIGHT], $names->all()); + $this->assertEqualsCanonicalizing([Integration::NAME_WARP_FREIGHT, Integration::NAME_SHIPSTATION_FREIGHT], $names->all()); } public function test_a_connected_warp_account_shows_on_its_catalog_card(): void diff --git a/Modules/Freight/Tests/Feature/ShipStationFreightDriverTest.php b/Modules/Freight/Tests/Feature/ShipStationFreightDriverTest.php new file mode 100644 index 00000000000..f610d714b20 --- /dev/null +++ b/Modules/Freight/Tests/Feature/ShipStationFreightDriverTest.php @@ -0,0 +1,670 @@ +attempt(), + handling_units: [new HandlingUnitData(quantity: 2, weight_lb_each: 500, freight_class: '70', description: 'Candles')], + ); + } + + public function test_a_test_lists_the_provider_accounts_and_keeps_a_selection_the_account_still_has(): void + { + $sent = null; + MockClient::global([ShipStationListProviderAccountsRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request; + + return $this->shipStationResponse('provider_accounts'); + }]); + + $connection = $this->shipStationConnection(['freight_provider_account_id' => 'se-4433298']); + $status = $this->driver()->testConnection($connection); + + $this->assertSame('https://api.shipstation.com/v2/freight/provider_accounts', $sent->getUrl()); + $this->assertSame($connection->credential('api_key'), $sent->headers()->get('api-key')); + $this->assertSame('production', $status->environment); + $this->assertSame('WWEX Main (Worldwide Express), Unishippers East (Unishippers)', $status->account_label); + $this->assertSame([], $status->warnings); + $this->assertSame('se-4433298', $status->settings['freight_provider_account_id']); + $this->assertSame([ + ['id' => 'se-4433221', 'code' => 'WWEX', 'nickname' => 'WWEX Main'], + ['id' => 'se-4433298', 'code' => 'UNISHIPPERS', 'nickname' => 'Unishippers East'], + ], $status->settings['provider_accounts']); + + $unselected = $this->driver()->testConnection($this->shipStationConnection(['freight_provider_account_id' => 'se-REMOVED'])); + $this->assertNull($unselected->settings['freight_provider_account_id'], 'a selection the account no longer has is dropped'); + $this->assertSame([ShipStationFreightDriver::PICK_PROVIDER_ACCOUNT_MESSAGE], $unselected->warnings); + } + + public function test_one_provider_account_is_selected_and_none_warns_and_blocks_quoting(): void + { + $single = $this->fixture('provider_accounts', 'shipstation'); + $single['provider_accounts'] = [$single['provider_accounts'][1]]; + MockClient::global([ShipStationListProviderAccountsRequest::class => MockResponse::make($single)]); + + $status = $this->driver()->testConnection($this->shipStationConnection(['freight_provider_account_id' => null])); + $this->assertSame('se-4433298', $status->settings['freight_provider_account_id']); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('provider_accounts_empty')]); + $connection = $this->shipStationConnection(); + $connection->connection_settings = ['api_key' => 'TEST_abc123']; + + $empty = $this->driver()->testConnection($connection); + $this->assertSame('sandbox', $empty->environment, 'a TEST_ key is ShipStation\'s sandbox'); + $this->assertSame([ShipStationFreightDriver::NO_PROVIDER_ACCOUNT_MESSAGE], $empty->warnings); + $this->assertNull($empty->settings['freight_provider_account_id']); + + $blocked = $this->shipStationConnection(['provider_accounts' => [], 'freight_provider_account_id' => null]); + $this->assertSame(ShipStationFreightDriver::NO_PROVIDER_ACCOUNT_MESSAGE, ShipStationFreightDriver::quoteBlocker($blocked)); + + MockClient::destroyGlobal(); + MockClient::global([]); + $this->expectException(FreightProviderException::class); + $this->expectExceptionMessage('No freight account is connected in ShipStation'); + $this->driver()->quote($blocked, $this->request()); + } + + public function test_a_rejected_key_is_an_auth_error(): void + { + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('unauthorized', 401)]); + + $this->expectException(FreightProviderAuthException::class); + $this->expectExceptionMessage('ShipStation didn\'t accept this key. Use a V2 API key from Settings → Account → API Settings.'); + + $this->driver()->testConnection($this->shipStationConnection()); + } + + public function test_a_quote_sends_the_load_inline_with_units_classes_location_types_and_accessorials(): void + { + $this->setHazmatPhone(); + $sent = null; + MockClient::global([ShipStationQuoteRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->body()->all(); + + return $this->shipStationResponse('quotes'); + }]); + + $result = $this->driver()->quote($this->shipStationConnection(), $this->request(hazmat: new HazmatData('UN1266', 'Perfumery products', '3', 'II'))); + + $this->assertSame('se-4433221', $sent['freight_provider_account_id']); + $this->assertSame('2026-11-24', $sent['pickup_date']); + $this->assertSame(['name' => 'Dock Lead', 'company_name' => 'Lumen Candle Co.', 'phone' => '909-555-0142', 'email' => 'dock@example.com', 'address_line1' => '4200 E Airport Dr', 'city_locality' => 'Ontario', 'state_province' => 'CA', 'postal_code' => '91761', 'country_code' => 'US', 'location_type' => 'commercial'], $sent['ship_from']); + $this->assertSame('Target DC 3801', $sent['ship_to']['name'], 'a stop without a contact name falls back on its company'); + $this->assertSame('distribution_center', $sent['ship_to']['location_type']); + + $first = $sent['handling_units'][0]; + $this->assertSame(['type' => 'pallet', 'quantity' => 3, 'length' => 48, 'width' => 40, 'height' => 52, 'dimension_unit' => 'inch', 'stackable' => true], array_diff_key($first, ['commodities' => true])); + $this->assertSame(['description' => 'Candles', 'quantity' => 3, 'packaging_type' => 'pallet', 'weight' => 640, 'weight_unit' => 'pound', 'freight_class' => '77.5'], $first['commodities'][0]); + $this->assertSame('85', $sent['handling_units'][1]['commodities'][0]['freight_class']); + $this->assertSame([ + 'identification_number_type' => 'un', + 'identification_number' => '1266', + 'proper_shipping_name' => 'Perfumery products', + 'hazard_class' => '3', + 'packing_group' => 'ii', + 'emergency_contact_name' => 'Lumen Candle Co.', + 'emergency_contact_phone' => '800-424-9300', + ], $sent['handling_units'][1]['commodities'][0]['hazardous_materials']); + $this->assertSame(['liftgate_pickup' => true, 'appointment_delivery' => true, 'notify_before_delivery' => true], $sent['accessorials']); + + $this->assertCount(2, $result->rates); + $rate = $result->rates[0]; + $this->assertSame('ofr_7Q2K9M4XWB', $rate->provider_quote_id); + $this->assertSame(FreightModeEnum::Ltl, $rate->mode); + $this->assertSame(412.37, $rate->total); + $this->assertSame('USD', $rate->currency); + $this->assertSame('Estes Express Lines', $rate->carrier_name); + $this->assertSame('EXLA', $rate->carrier_scac); + $this->assertSame('LTL via Worldwide Express', $rate->vehicle); + $this->assertSame('Standard LTL', $rate->service_level); + $this->assertSame(4, $rate->transit_days); + $this->assertSame('2026-11-30', $rate->estimated_delivery_date?->toDateString()); + $this->assertSame('2026-12-01T23:59:00+00:00', $rate->expires_at?->toIso8601String()); + $this->assertSame('Guaranteed by 5 PM · Guaranteed', $result->rates[1]->service_level); + $this->assertSame('guaranteed', $result->rates[1]->tier); + } + + public function test_a_class_shipstation_does_not_take_is_refused_before_calling_and_a_missing_class_follows_density(): void + { + MockClient::global([]); + $request = $this->request(); + $request->handling_units[0]->freight_class = '72'; + + try { + $this->driver()->quote($this->shipStationConnection(), $request); + $this->fail('Expected the class to be refused'); + } catch (FreightProviderException $e) { + $this->assertSame('INVALID_FREIGHT_CLASS', $e->providerCode); + } + + $sent = null; + MockClient::destroyGlobal(); + MockClient::global([ShipStationQuoteRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->body()->all(); + + return $this->shipStationResponse('quotes'); + }]); + $request->handling_units[0]->freight_class = null; + $this->driver()->quote($this->shipStationConnection(), $request); + + // 3 × 639.4 lb in 3 × 48×40×51.5 in = 11.17 lb/ft³ → class 92.5 + $this->assertSame('92.5', $sent['handling_units'][0]['commodities'][0]['freight_class']); + } + + public function test_shipstation_quotes_ltl_only_and_an_empty_answer_says_the_lane_is_not_served(): void + { + MockClient::global([]); + + try { + $this->driver()->quote($this->shipStationConnection(), $this->request(FreightModeEnum::Ftl)); + $this->fail('Expected FTL to be refused'); + } catch (FreightProviderException $e) { + $this->assertSame('ShipStation freight quotes LTL only.', $e->getMessage()); + } + + MockClient::destroyGlobal(); + MockClient::global([ShipStationQuoteRequest::class => $this->shipStationResponse('quotes_empty')]); + + $this->expectException(FreightProviderException::class); + $this->expectExceptionMessage('No carrier through your ShipStation freight account serves this lane as described.'); + $this->driver()->quote($this->shipStationConnection(), $this->request(FreightModeEnum::Any)); + } + + public function test_a_pickup_appointment_is_reported_unsupported_on_each_rate(): void + { + MockClient::global([ShipStationQuoteRequest::class => $this->shipStationResponse('quotes')]); + + $rate = $this->driver()->quote($this->shipStationConnection(), $this->request(accessorials: new FreightAccessorialsData(pickup: ['appointment', 'limited_access'], delivery: [])))->rates[0]; + + $this->assertSame(['appointment'], $rate->unsupported_accessorials); + } + + public function test_the_live_no_provider_error_asks_to_test_again_and_carrier_errors_keep_their_wording(): void + { + MockClient::global([ShipStationQuoteRequest::class => $this->shipStationResponse('invalid_provider_account', 400)]); + + try { + $this->driver()->quote($this->shipStationConnection(), $this->request()); + $this->fail('Expected a provider error'); + } catch (FreightProviderException $e) { + $this->assertNotInstanceOf(FreightProviderUnavailableException::class, $e); + $this->assertSame(ShipStationFreightDriver::PROVIDER_ACCOUNT_GONE_MESSAGE, $e->getMessage()); + $this->assertSame('invalid_field_value', $e->providerCode); + $this->assertArrayHasKey('seller_freight_provider_id', $e->fieldErrors); + } + + MockClient::destroyGlobal(); + MockClient::global([ShipStationQuoteRequest::class => $this->shipStationResponse('validation_error', 400)]); + + try { + $this->driver()->quote($this->shipStationConnection(), $this->request()); + $this->fail('Expected a provider error'); + } catch (FreightProviderException $e) { + $this->assertStringContainsString('outside the carrier\'s service area', $e->getMessage()); + $this->assertArrayHasKey('ship_to.postal_code', $e->fieldErrors); + } + } + + public function test_rate_limits_and_server_errors_are_unavailable(): void + { + MockClient::global([ShipStationQuoteRequest::class => MockResponse::make(['errors' => [['message' => 'Too many requests']]], 429)]); + + try { + $this->driver()->quote($this->shipStationConnection(), $this->request()); + $this->fail('Expected unavailable'); + } catch (FreightProviderUnavailableException $e) { + $this->assertStringContainsString('ShipStation answered 429', $e->getMessage()); + } + + MockClient::destroyGlobal(); + MockClient::global([ShipStationQuoteRequest::class => MockResponse::make(['errors' => [['message' => 'Internal error']]], 503)]); + + $this->expectException(FreightProviderUnavailableException::class); + $this->driver()->quote($this->shipStationConnection(), $this->request()); + } + + public function test_booking_sends_the_offer_pickup_details_references_and_notifications(): void + { + $sent = null; + MockClient::global([ShipStationCreateShipmentRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->body()->all(); + + return $this->shipStationResponse('book'); + }]); + + $result = $this->driver()->book($this->shipStationConnection(), $this->bookingRequest()); + + $this->assertSame('ofr_7Q2K9M4XWB', $sent['offer_id']); + $this->assertSame(['pickup_date' => '2026-11-24', 'ready_time' => '08:00', 'close_time' => '15:00', 'is_self_scheduled' => false, 'location_type' => 'commercial'], $sent['pickup_details']); + $this->assertSame([ + ['type' => 'sku_load', 'value' => 'sku-tenant1-42-p7m2c8v1aa'], + ['type' => 'po_number', 'value' => 'PO-4471203'], + ['type' => 'shipper_reference', 'value' => 'SO-1042'], + ], $sent['references']); + $this->assertSame('Call 30 min ahead', $sent['pickup_instructions']); + $this->assertSame('Delivery appointment 09:00–11:00', $sent['delivery_instructions']); + $this->assertSame([['events' => ['booked', 'in_transit', 'delivered', 'cancelled', 'exception'], 'email_addresses' => ['dock@example.com']]], $sent['notifications']); + $this->assertSame('Dock 4', $sent['ship_to']['address_line2']); + $this->assertSame('inch', $sent['handling_units'][0]['dimension_unit']); + + $this->assertSame('fs-77001234', $result->provider_shipment_id); + $this->assertSame('WWX20261124-0031', $result->bill_of_lading_number); + $this->assertNull($result->carrier_pro_number, 'the carrier assigns the PRO later; tracking fills it'); + $this->assertSame('WX-5521983', $result->provider_order_id); + $this->assertSame('WX-5521983', $result->shipment_number); + $this->assertFalse($result->is_sandbox); + } + + public function test_a_server_error_while_booking_is_an_unknown_outcome_and_is_sent_once(): void + { + $calls = 0; + MockClient::global([ShipStationCreateShipmentRequest::class => function () use (&$calls) { + $calls++; + + return MockResponse::make(['errors' => [['message' => 'Upstream timeout']]], 502); + }]); + + try { + $this->driver()->book($this->shipStationConnection(), $this->bookingRequest()); + $this->fail('Expected unavailable'); + } catch (FreightProviderUnavailableException) { + $this->assertSame(1, $calls, 'a booking is never retried: it could book the load twice'); + } + } + + public function test_a_lost_booking_is_found_only_by_its_attempts_reference_from_the_attempt_time(): void + { + $sent = null; + MockClient::global([ShipStationListShipmentsRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->query()->all(); + + return $this->shipStationResponse('shipments'); + }]); + + $found = $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', 'PO-4471203', $this->attempt()); + + $this->assertSame('fs-77001234', $found?->provider_shipment_id, 'the cancelled booking with the same reference and the same load\'s other attempt are skipped'); + $this->assertSame('WWX20261124-0031', $found?->bill_of_lading_number); + $this->assertSame('2026-11-24T14:58:00Z', $sent['created_at_start'], 'the search starts at the attempt (less the clock-skew allowance), not now'); + $this->assertSame(1, $sent['page']); + $this->assertSame(100, $sent['page_size'], 'the page size is sent, so a full page can be told from the last one'); + } + + public function test_another_attempt_of_the_same_load_or_a_shared_po_is_never_adopted(): void + { + MockClient::global([ShipStationListShipmentsRequest::class => $this->shipStationResponse('shipments')]); + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + + $this->assertNull($this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', 'PO-4471203', $this->attempt('sku-tenant1-42-n0tthis0ne')), 'fs-77001100 carries the same load id and PO but another attempt\'s nonce'); + } + + public function test_a_search_that_runs_out_of_pages_or_finds_the_reference_before_the_attempt_is_unknown_not_empty(): void + { + $paged = $this->fixture('shipments', 'shipstation'); + $paged['freight_shipments'] = []; + $paged['pages'] = 9; + $calls = 0; + MockClient::global([ShipStationListShipmentsRequest::class => function () use ($paged, &$calls) { + $calls++; + + return MockResponse::make($paged); + }]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected the incomplete search to be unknown'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('SEARCH_INCOMPLETE', $e->providerCode); + $this->assertSame(5, $calls); + } + + $early = $this->fixture('shipments', 'shipstation'); + $early['freight_shipments'][3]['created_at'] = '2026-11-24T14:00:00Z'; + unset($early['freight_shipments'][1]); + $early['freight_shipments'] = array_values($early['freight_shipments']); + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($early)]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected a booking from before the attempt to stay unknown'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('REFERENCE_BEFORE_ATTEMPT', $e->providerCode); + } + + MockClient::destroyGlobal(); + MockClient::global([]); + $this->expectException(FreightProviderUnavailableException::class); + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', 'PO-4471203', null); + } + + public function test_a_full_page_without_paging_data_is_unknown_not_empty(): void + { + config(['freight.shipstation.booking_search_page_size' => 3]); + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + $full = $this->fixture('shipments', 'shipstation'); + $full['freight_shipments'] = array_slice($full['freight_shipments'], 0, 3); + unset($full['pages'], $full['page'], $full['total']); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($full)]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected a full page with no paging data to be unknown'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('SEARCH_INCOMPLETE', $e->providerCode); + } + + $full['freight_shipments'] = array_slice($full['freight_shipments'], 0, 2); + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($full)]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected a short page with no paging data to be unknown: the server may cap the page size'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('SEARCH_INCOMPLETE', $e->providerCode); + } + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make([...$full, 'page_size' => 3])]); + + $this->assertNull($this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()), 'a short page is the last one once ShipStation echoes the page size asked for'); + } + + public function test_an_unrecognised_list_shape_is_unknown_not_empty(): void + { + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['data' => [], 'pages' => 1])]); + + $this->expectException(FreightProviderUnavailableException::class); + $this->expectExceptionMessage('shape SKU.io doesn\'t recognise'); + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + } + + public function test_listed_shipments_without_any_skuio_reference_cannot_prove_not_booked_but_an_empty_window_can(): void + { + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + $stripped = $this->fixture('shipments', 'shipstation'); + foreach ($stripped['freight_shipments'] as $index => $shipment) { + $stripped['freight_shipments'][$index]['references'] = array_values(array_filter($shipment['references'], fn ($reference) => $reference['type'] !== 'sku_load')); + } + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($stripped)]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected unknown: the sku_load reference may not round-trip'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('REFERENCE_UNSUPPORTED', $e->providerCode); + $this->assertSame(ShipStationFreightDriver::REFERENCE_UNSUPPORTED_MESSAGE, $e->getMessage()); + } + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [], 'total' => 0])]); + + $this->assertNull($this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt()), 'no shipments in the window, past the settle time: not booked'); + } + + public function test_a_window_of_shipments_booked_outside_skuio_is_not_booked_once_an_earlier_skuio_booking_proves_the_reference_round_trips(): void + { + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + $connection = $this->shipStationConnection(); + FreightShipment::factory()->booked()->create(['integration_instance_id' => $connection->id, 'provider_shipment_id' => 'fs-76990001', 'booked_at' => now()->subDays(3)]); + $manual = $this->fixture('shipments', 'shipstation'); + foreach ($manual['freight_shipments'] as $index => $shipment) { + $manual['freight_shipments'][$index]['references'] = [['type' => 'po_number', 'value' => 'PO-MANUAL-'.$index]]; + } + $earlier = $this->fixture('book', 'shipstation'); + $earlier['freight_shipment_id'] = 'fs-76990001'; + $earlier['references'] = [['type' => 'sku_load', 'value' => 'sku-tenant1-7-earlier01']]; + $requested = []; + MockClient::global([ + ShipStationListShipmentsRequest::class => MockResponse::make($manual), + ShipStationGetShipmentRequest::class => function (PendingRequest $request) use ($earlier, &$requested) { + $requested[] = $request->getRequest()->resolveEndpoint(); + + return MockResponse::make($earlier); + }, + ]); + + $this->assertNull($this->driver()->findBookingForQuote($connection, 'ofr_7Q2K9M4XWB', null, $this->attempt()), 'only manual shipments in the window, and ShipStation kept the reference on our last booking: not booked'); + $this->assertCount(1, $requested); + $this->assertStringEndsWith('fs-76990001', $requested[0]); + + $earlier['references'] = [['type' => 'po_number', 'value' => 'PO-1']]; + MockClient::destroyGlobal(); + MockClient::global([ + ShipStationListShipmentsRequest::class => MockResponse::make($manual), + ShipStationGetShipmentRequest::class => MockResponse::make($earlier), + ]); + + try { + $this->driver()->findBookingForQuote($connection, 'ofr_7Q2K9M4XWB', null, $this->attempt()); + $this->fail('Expected unknown: our earlier booking lost the reference too'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('REFERENCE_UNSUPPORTED', $e->providerCode); + } + } + + public function test_a_page_repeated_by_a_server_ignoring_page_does_not_reach_the_total(): void + { + $this->travelTo(CarbonImmutable::parse('2026-11-24T16:00:00Z')); + $repeated = $this->fixture('shipments', 'shipstation'); + unset($repeated['pages'], $repeated['links'], $repeated['page_size']); + $repeated['total'] = count($repeated['freight_shipments']) + 1; + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($repeated)]); + + try { + $this->driver()->findBookingForQuote($this->shipStationConnection(), 'ofr_7Q2K9M4XWB', null, $this->attempt('sku-tenant1-42-notlisted0')); + $this->fail('Expected unknown: the same page twice must not count toward the total'); + } catch (FreightProviderUnavailableException $e) { + $this->assertSame('SEARCH_INCOMPLETE', $e->providerCode); + } + } + + public function test_a_booking_that_does_not_echo_the_reference_is_kept_and_logged(): void + { + Log::spy(); + $body = $this->fixture('book', 'shipstation'); + $body['references'] = [['type' => 'po_number', 'value' => 'PO-4471203']]; + MockClient::global([ShipStationCreateShipmentRequest::class => MockResponse::make($body)]); + + $result = $this->driver()->book($this->shipStationConnection(), $this->bookingRequest()); + + $this->assertSame('fs-77001234', $result->provider_shipment_id); + Log::shouldHaveReceived('warning')->once()->withArgs(fn (string $message, array $context) => str_contains($message, 'did not echo') && $context['freight_shipment_id'] === 'fs-77001234'); + } + + public function test_limited_access_at_a_stop_wins_over_its_destination_type(): void + { + $sent = null; + MockClient::global([ShipStationQuoteRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->body()->all(); + + return $this->shipStationResponse('quotes'); + }]); + + $rate = $this->driver()->quote($this->shipStationConnection(), $this->request(accessorials: new FreightAccessorialsData(pickup: [], delivery: ['limited_access'])))->rates[0]; + + $this->assertSame('limited_access', $sent['ship_to']['location_type'], 'the retailer-DC destination type gives way to limited access'); + $this->assertSame([], $sent['accessorials']); + $this->assertSame([], $rate->unsupported_accessorials); + } + + public function test_an_unknown_tracking_status_keeps_the_load_where_it_is_and_records_no_pickup(): void + { + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + MockClient::global([ShipStationTrackShipmentRequest::class => MockResponse::make([ + 'freight_shipment_id' => 'fs-77001234', + 'status' => 'awaiting_dispatch', + 'events' => [['occurred_at' => '2026-11-24T16:00:00Z', 'status' => 'arrived_at_terminal', 'description' => 'At terminal']], + ])]); + + $result = $this->driver()->track($this->shipStationConnection(), $shipment); + + $this->assertNull($result->status); + $this->assertSame(FreightShipmentStatusEnum::Booked, $result->events[0]->status, 'an unknown event status is the load\'s current status, never in transit'); + $this->assertSame('arrived_at_terminal', $result->events[0]->provider_status); + $this->assertNull($result->picked_up_at); + } + + public function test_newest_first_events_are_sorted_and_the_dates_come_from_explicit_events(): void + { + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + $body = $this->fixture('tracking_delivered', 'shipstation'); + $body['events'] = array_reverse($body['events']); + $body['actual_pickup_date'] = null; + $body['actual_delivery_date'] = null; + MockClient::global([ShipStationTrackShipmentRequest::class => MockResponse::make($body)]); + + $result = $this->driver()->track($this->shipStationConnection(), $shipment); + + $this->assertSame(['booked', 'picked_up', 'in_transit', 'delivered'], array_map(fn ($event) => $event->provider_status, $result->events)); + $this->assertSame('2026-11-24T19:42:00+00:00', $result->picked_up_at?->toIso8601String()); + $this->assertSame('2026-11-28T17:05:00+00:00', $result->delivered_at?->toIso8601String()); + } + + public function test_an_unreadable_date_is_ignored(): void + { + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + $body = $this->fixture('tracking_in_transit', 'shipstation'); + $body['estimated_delivery_date'] = '2026-13-45T99:99:99'; + $body['events'][0]['occurred_at'] = '2026-13-45T99:99:99'; + MockClient::global([ShipStationTrackShipmentRequest::class => MockResponse::make($body)]); + + $result = $this->driver()->track($this->shipStationConnection(), $shipment); + + $this->assertNull($result->estimated_delivery_date); + $this->assertCount(2, $result->events); + } + + public function test_tracking_maps_status_events_and_fills_the_pro(): void + { + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + + MockClient::global([ShipStationTrackShipmentRequest::class => $this->shipStationResponse('tracking_in_transit')]); + $moving = $this->driver()->track($this->shipStationConnection(), $shipment); + $this->assertSame(FreightShipmentStatusEnum::InTransit, $moving->status); + $this->assertSame('1234567890', $moving->carrier_pro_number); + $this->assertSame('2026-11-24T19:42:00+00:00', $moving->picked_up_at?->toIso8601String()); + $this->assertSame(FreightShipmentStatusEnum::PickedUp, $moving->events[1]->status); + $this->assertSame('Phoenix, AZ', $moving->events[2]->location); + $this->assertNull($moving->delivered_at); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationTrackShipmentRequest::class => $this->shipStationResponse('tracking_delivered')]); + $delivered = $this->driver()->track($this->shipStationConnection(), $shipment); + $this->assertSame(FreightShipmentStatusEnum::Delivered, $delivered->status); + $this->assertSame('2026-11-28T17:05:00+00:00', $delivered->delivered_at?->toIso8601String()); + $this->assertCount(4, $delivered->events); + $this->assertSame($moving->events[0]->provider_event_id, $delivered->events[0]->provider_event_id, 'event ids are stable across polls'); + } + + public function test_documents_are_the_bol_and_pallet_labels(): void + { + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + MockClient::global([ShipStationShipmentDocumentsRequest::class => $this->shipStationResponse('documents')]); + + $documents = $this->driver()->documents($this->shipStationConnection(), $shipment); + + $this->assertSame(['bill_of_lading', 'pallet_labels'], array_map(fn ($document) => $document->type, $documents)); + $this->assertSame(['ShipStation bill of lading', 'Pallet labels'], array_map(fn ($document) => $document->label, $documents)); + } + + public function test_cancel_deletes_the_shipment_and_a_refusal_keeps_shipstations_message(): void + { + $this->assertTrue($this->driver()->capabilities()->supports_cancel); + $shipment = FreightShipment::factory()->booked()->create(['provider_shipment_id' => 'fs-77001234']); + + $url = null; + MockClient::global([ShipStationCancelShipmentRequest::class => function (PendingRequest $request) use (&$url) { + $url = $request->getMethod()->value.' '.$request->getUrl(); + + return MockResponse::make([], 204); + }]); + $this->driver()->cancel($this->shipStationConnection(), $shipment); + $this->assertSame('DELETE https://api.shipstation.com/v2/freight/shipments/fs-77001234', $url); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationCancelShipmentRequest::class => $this->shipStationResponse('cancel_refused', 400)]); + + $this->expectException(FreightProviderException::class); + $this->expectExceptionMessage('This shipment has been picked up and can no longer be cancelled.'); + $this->driver()->cancel($this->shipStationConnection(), $shipment); + } +} diff --git a/Modules/Freight/Tests/Feature/ShipStationFreightFlowTest.php b/Modules/Freight/Tests/Feature/ShipStationFreightFlowTest.php new file mode 100644 index 00000000000..6f0755137cd --- /dev/null +++ b/Modules/Freight/Tests/Feature/ShipStationFreightFlowTest.php @@ -0,0 +1,370 @@ +quotedLoad($connection, $attributes); + $rate->update(['provider_quote_id' => 'ofr_7Q2K9M4XWB', 'carrier_name' => 'Estes Express Lines', 'carrier_scac' => 'EXLA', 'total' => 412.37]); + + return [$shipment->refresh(), $rate->refresh()]; + } + + public function test_the_provider_list_offers_shipstation_with_a_select_setting(): void + { + $providers = collect($this->getJson('/api/freight/providers')->assertOk()->json('data'))->keyBy('key'); + + $shipStation = $providers['shipstation']; + $this->assertSame('ShipStation', $shipStation['label']); + $this->assertSame('https://www.shipstation.com', $shipStation['website_url']); + $this->assertStringContainsString('Freight → Connect your account', $shipStation['credential_fields'][0]['help']); + $this->assertSame([['key' => 'freight_provider_account_id', 'type' => 'select']], array_map(fn ($field) => ['key' => $field['key'], 'type' => $field['type']], $shipStation['setting_fields'])); + $this->assertTrue($shipStation['allows_multiple_connections']); + $this->assertSame(['ltl'], $shipStation['capabilities']['modes']); + $this->assertSame('text', $providers['warp']['setting_fields'][0]['type']); + $this->assertFalse($providers['warp']['allows_multiple_connections']); + } + + public function test_connecting_lists_the_provider_accounts_as_options_and_validates_the_choice(): void + { + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('provider_accounts')]); + + $response = $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'credentials' => ['api_key' => 'live-key-abcdef9876']]) + ->assertCreated() + ->assertJsonPath('data.provider', 'shipstation') + ->assertJsonPath('data.environment', 'production') + ->assertJsonPath('data.credentials.api_key', ['is_set' => true, 'hint' => '…9876']) + ->assertJsonPath('data.settings.freight_provider_account_id', null) + ->assertJsonPath('data.setting_options.freight_provider_account_id', [ + ['value' => 'se-4433221', 'label' => 'WWEX Main (Worldwide Express)'], + ['value' => 'se-4433298', 'label' => 'Unishippers East (Unishippers)'], + ]) + ->assertJsonPath('data.account_warnings', [ShipStationFreightDriver::PICK_PROVIDER_ACCOUNT_MESSAGE]) + ->assertJsonPath('data.quote_blocked_reason', ShipStationFreightDriver::PICK_PROVIDER_ACCOUNT_MESSAGE); + $id = $response->json('data.id'); + + $errors = $this->putJson("/api/freight/connections/{$id}", ['settings' => ['freight_provider_account_id' => 'se-NOT-LISTED']]) + ->assertUnprocessable() + ->json('errors'); + $this->assertStringStartsWith('Pick one of the freight provider accounts ShipStation listed', $errors['settings.freight_provider_account_id'][0]['message']); + + $this->putJson("/api/freight/connections/{$id}", ['settings' => ['freight_provider_account_id' => 'se-4433298']]) + ->assertOk() + ->assertJsonPath('data.settings.freight_provider_account_id', 'se-4433298') + ->assertJsonPath('data.quote_blocked_reason', null); + + // A second ShipStation account may be connected; a second Warp may not + $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'credentials' => ['api_key' => 'second-account-key']])->assertCreated(); + $this->assertSame(2, FreightIntegrationInstance::query()->count()); + + $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'name' => 'ShipStation', 'credentials' => ['api_key' => 'third-account-key']]) + ->assertStatus(409) + ->assertJsonPath('message', 'Another connection is already named ShipStation. Pick another name.'); + } + + public function test_a_single_provider_account_is_selected_and_none_saves_with_a_blocking_warning(): void + { + $single = $this->fixture('provider_accounts', 'shipstation'); + $single['provider_accounts'] = [$single['provider_accounts'][0]]; + MockClient::global([ShipStationListProviderAccountsRequest::class => MockResponse::make($single)]); + + $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'credentials' => ['api_key' => 'live-key-one']]) + ->assertCreated() + ->assertJsonPath('data.settings.freight_provider_account_id', 'se-4433221') + ->assertJsonPath('data.account_warnings', []) + ->assertJsonPath('data.account_label', 'WWEX Main (Worldwide Express)'); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('provider_accounts_empty')]); + + $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'credentials' => ['api_key' => 'live-key-none']]) + ->assertCreated() + ->assertJsonPath('data.name', 'ShipStation Freight', 'integration instance names are unique, so the second takes the next free name') + ->assertJsonPath('data.account_warnings', [ShipStationFreightDriver::NO_PROVIDER_ACCOUNT_MESSAGE]) + ->assertJsonPath('data.quote_blocked_reason', ShipStationFreightDriver::NO_PROVIDER_ACCOUNT_MESSAGE) + ->assertJsonPath('data.setting_options.freight_provider_account_id', []); + } + + public function test_a_rejected_key_is_not_saved(): void + { + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('unauthorized', 401)]); + + $this->postJson('/api/freight/connections', ['provider' => 'shipstation', 'credentials' => ['api_key' => 'bad']]) + ->assertStatus(422) + ->assertJsonPath('errors.credentials.0', 'ShipStation didn\'t accept this key. Use a V2 API key from Settings → Account → API Settings.'); + + $this->assertSame(0, FreightIntegrationInstance::query()->count()); + } + + public function test_shipstation_rates_appear_beside_and_a_connection_without_a_provider_account_explains_why_it_has_none(): void + { + $this->shipStationConnection(); + $this->shipStationConnection(['provider_accounts' => [], 'freight_provider_account_id' => null]); + MockClient::global([ShipStationQuoteRequest::class => $this->shipStationResponse('quotes')]); + $shipment = FreightShipment::factory()->create(); + + $response = $this->postJson("/api/freight/shipments/{$shipment->id}/quote")->assertOk(); + + $response->assertJsonCount(2, 'data.rates') + ->assertJsonPath('data.rates.0.total', 412.37) + ->assertJsonPath('data.rates.0.carrier_scac', 'EXLA') + ->assertJsonPath('data.failed_providers.0.message', ShipStationFreightDriver::NO_PROVIDER_ACCOUNT_MESSAGE); + + $this->assertSame(1, FreightQuoteAttempt::query()->where('status', FreightQuoteAttemptStatusEnum::Failed)->count()); + $this->assertSame(['ofr_7Q2K9M4XWB', 'ofr_8R3L0N5YXC'], FreightRate::query()->orderBy('total')->pluck('provider_quote_id')->all()); + } + + public function test_booking_writes_shipstations_bol_and_scac_to_the_shipment_and_tracking_fills_the_pro_later(): void + { + $connection = $this->shipStationConnection(); + $fulfillment = SalesOrderFulfillment::factory()->create(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection, ['sales_order_id' => $fulfillment->sales_order_id, 'sales_order_fulfillment_id' => $fulfillment->id]); + $sent = null; + MockClient::global([ShipStationCreateShipmentRequest::class => function (PendingRequest $request) use (&$sent) { + $sent = $request->body()->all(); + + return $this->shipStationResponse('book'); + }]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/book", ['rate_id' => $rate->id, 'acknowledge_retailer_routing' => true]) + ->assertOk() + ->assertJsonPath('data.status', 'booked') + ->assertJsonPath('data.booking.bill_of_lading_number', 'WWX20261124-0031') + ->assertJsonPath('data.booking.carrier_scac', 'EXLA') + ->assertJsonPath('data.booking.carrier_name', 'Estes Express Lines') + ->assertJsonPath('data.is_sandbox', false); + + $this->assertSame('sku_load', $sent['references'][0]['type']); + $this->assertMatchesRegularExpression('/^sku-.+-'.$shipment->id.'-[a-z0-9]{10}$/', $sent['references'][0]['value'], 'tenant, load id and a per-attempt nonce'); + $this->assertSame($sent['references'][0]['value'], data_get($shipment->fresh()->booking_contacts, 'booking_reference'), 'saved on the load before ShipStation was asked'); + $this->assertSame('ofr_7Q2K9M4XWB', $sent['offer_id']); + + $fresh = $shipment->fresh(); + $this->assertSame('fs-77001234', $fresh->provider_shipment_id); + $this->assertNull($fresh->carrier_pro_number); + $freight = SalesOrderFulfillmentFreightDetail::query()->where('sales_order_fulfillment_id', $fulfillment->id)->sole(); + $this->assertSame('WWX20261124-0031', $freight->bill_of_lading_number); + $this->assertSame('EXLA', $freight->carrier_scac); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationTrackShipmentRequest::class => $this->shipStationResponse('tracking_in_transit')]); + app(FreightTrackingManager::class)->refresh($fresh); + + $tracked = $shipment->fresh(); + $this->assertSame(FreightShipmentStatusEnum::InTransit, $tracked->status); + $this->assertSame('1234567890', $tracked->carrier_pro_number); + $this->assertSame('1234567890', SalesOrderFulfillmentFreightDetail::query()->where('sales_order_fulfillment_id', $fulfillment->id)->sole()->carrier_pro_number); + } + + public function test_a_lost_booking_answer_is_unconfirmed_and_check_booking_adopts_it_by_its_attempt_reference(): void + { + $connection = $this->shipStationConnection(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection); + MockClient::global([ShipStationCreateShipmentRequest::class => MockResponse::make(['errors' => [['message' => 'Gateway timeout']]], 504)]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/book", ['rate_id' => $rate->id, 'acknowledge_retailer_routing' => true])->assertStatus(502); + $unconfirmed = $shipment->fresh(); + $this->assertSame(FreightShipmentStatusEnum::BookingUnknown, $unconfirmed->status); + $reference = (string) data_get($unconfirmed->booking_contacts, 'booking_reference'); + $this->assertNotSame('', $reference); + $this->assertNotNull(data_get($unconfirmed->booking_contacts, 'attempted_at')); + + $listed = $this->fixture('shipments', 'shipstation'); + foreach ($listed['freight_shipments'] as $index => $listedShipment) { + $listed['freight_shipments'][$index]['created_at'] = now()->utc()->toIso8601ZuluString(); + } + $listed['freight_shipments'][2]['references'][0]['value'] = $shipment->number; + $listed['freight_shipments'][3]['references'][0]['value'] = $reference; + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make($listed)]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking") + ->assertOk() + ->assertJsonPath('data.status', 'booked'); + $this->assertSame('fs-77001234', $shipment->fresh()->provider_shipment_id, 'the shipment carrying only the load number is not the one adopted'); + } + + public function test_a_check_whose_search_runs_out_of_pages_stays_unconfirmed_and_no_match_says_so_without_claiming_once_only(): void + { + $connection = $this->shipStationConnection(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection); + $shipment->update([ + 'status' => FreightShipmentStatusEnum::BookingUnknown, + 'booked_rate_id' => $rate->id, + 'integration_instance_id' => $connection->id, + 'provider_quote_id' => $rate->provider_quote_id, + 'booking_contacts' => ['reference' => 'PO-1', 'booking_reference' => 'sku-t-1-abcdefghij', 'attempted_at' => now()->subMinutes(10)->toIso8601String()], + ]); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [], 'page' => 1, 'pages' => 40])]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking")->assertStatus(502); + $this->assertSame(FreightShipmentStatusEnum::BookingUnknown, $shipment->fresh()->status, 'an incomplete search is never read as "not booked"'); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [], 'page' => 1, 'pages' => 1])]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking")->assertOk()->assertJsonPath('data.status', 'quoted'); + $message = (string) $shipment->fresh()->last_tracking_error; + $this->assertStringStartsWith('ShipStation has no booking', $message); + $this->assertStringNotContainsString('only once', $message); + } + + public function test_a_check_while_shipstation_may_still_be_processing_stays_unconfirmed(): void + { + $connection = $this->shipStationConnection(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection); + $shipment->update([ + 'status' => FreightShipmentStatusEnum::BookingUnknown, + 'booked_rate_id' => $rate->id, + 'integration_instance_id' => $connection->id, + 'provider_quote_id' => $rate->provider_quote_id, + 'booking_contacts' => ['reference' => 'PO-1', 'booking_reference' => 'sku-t-1-abcdefghij', 'attempted_at' => now()->subMinute()->toIso8601String()], + ]); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [], 'page' => 1, 'pages' => 1])]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking") + ->assertStatus(502) + ->assertJsonPath('message', ShipStationFreightDriver::BOOKING_SETTLING_MESSAGE) + ->assertJsonPath('code', 'BOOKING_SETTLING'); + $this->assertSame(FreightShipmentStatusEnum::BookingUnknown, $shipment->fresh()->status, 'never back to Quoted while the booking may still appear'); + + $this->travel(5)->minutes(); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking")->assertOk()->assertJsonPath('data.status', 'quoted'); + $this->assertSame((string) $connection->driver()->capabilities()->missing_booking_message, $shipment->fresh()->last_tracking_error); + } + + public function test_a_check_whose_list_hides_skuios_reference_stays_unconfirmed(): void + { + $connection = $this->shipStationConnection(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection); + $shipment->update([ + 'status' => FreightShipmentStatusEnum::BookingUnknown, + 'booked_rate_id' => $rate->id, + 'integration_instance_id' => $connection->id, + 'provider_quote_id' => $rate->provider_quote_id, + 'booking_contacts' => ['reference' => 'PO-1', 'booking_reference' => 'sku-t-1-abcdefghij', 'attempted_at' => now()->subMinutes(10)->toIso8601String()], + ]); + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [ + ['freight_shipment_id' => 'fs-1', 'status' => 'booked', 'references' => [['type' => 'po_number', 'value' => 'PO-1']]], + ], 'page' => 1, 'pages' => 1])]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking") + ->assertStatus(502) + ->assertJsonPath('code', 'REFERENCE_UNSUPPORTED') + ->assertJsonPath('message', ShipStationFreightDriver::REFERENCE_UNSUPPORTED_MESSAGE); + $this->assertSame(FreightShipmentStatusEnum::BookingUnknown, $shipment->fresh()->status); + } + + public function test_a_check_on_a_full_page_without_paging_data_stays_unconfirmed(): void + { + config(['freight.shipstation.booking_search_page_size' => 2]); + $connection = $this->shipStationConnection(); + [$shipment, $rate] = $this->shipStationQuotedLoad($connection); + $shipment->update([ + 'status' => FreightShipmentStatusEnum::BookingUnknown, + 'booked_rate_id' => $rate->id, + 'integration_instance_id' => $connection->id, + 'provider_quote_id' => $rate->provider_quote_id, + 'booking_contacts' => ['reference' => 'PO-1', 'booking_reference' => 'sku-t-1-abcdefghij', 'attempted_at' => now()->subMinutes(10)->toIso8601String()], + ]); + $other = ['status' => 'booked', 'created_at' => now()->utc()->toIso8601ZuluString(), 'references' => [['type' => 'sku_load', 'value' => 'sku-t-9-otherother']]]; + MockClient::global([ShipStationListShipmentsRequest::class => MockResponse::make(['freight_shipments' => [ + ['freight_shipment_id' => 'fs-1', ...$other], + ['freight_shipment_id' => 'fs-2', ...$other], + ]])]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/check-booking") + ->assertStatus(502) + ->assertJsonPath('code', 'SEARCH_INCOMPLETE'); + $this->assertSame(FreightShipmentStatusEnum::BookingUnknown, $shipment->fresh()->status); + } + + public function test_editing_keeps_a_saved_account_shipstation_no_longer_lists_and_new_credentials_retest_the_choice(): void + { + $connection = $this->shipStationConnection(['provider_accounts' => [['id' => 'se-4433221', 'code' => 'WWEX', 'nickname' => 'WWEX Main']], 'freight_provider_account_id' => 'se-STALE']); + MockClient::global([]); + + $this->putJson("/api/freight/connections/{$connection->id}", ['name' => 'ShipStation east', 'settings' => ['freight_provider_account_id' => 'se-STALE']]) + ->assertOk() + ->assertJsonPath('data.name', 'ShipStation east'); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationListProviderAccountsRequest::class => $this->shipStationResponse('provider_accounts')]); + + $this->putJson("/api/freight/connections/{$connection->id}", ['credentials' => ['api_key' => 'rotated-key-1234'], 'settings' => ['freight_provider_account_id' => 'se-4433298']]) + ->assertOk() + ->assertJsonPath('data.settings.freight_provider_account_id', 'se-4433298', 'the new key\'s test lists it, so the choice stands'); + } + + public function test_documents_and_cancel_go_through_shipstation(): void + { + $connection = $this->shipStationConnection(); + $shipment = FreightShipment::factory()->booked()->create(['integration_instance_id' => $connection->id, 'provider_shipment_id' => 'fs-77001234']); + MockClient::global([ + ShipStationShipmentDocumentsRequest::class => $this->shipStationResponse('documents'), + ShipStationCancelShipmentRequest::class => $this->shipStationResponse('cancel_refused', 400), + ]); + + $this->getJson("/api/freight/shipments/{$shipment->id}/documents") + ->assertOk() + ->assertJsonPath('data.0.label', 'ShipStation bill of lading') + ->assertJsonPath('data.1.label', 'Pallet labels'); + + $this->postJson("/api/freight/shipments/{$shipment->id}/cancel") + ->assertStatus(422) + ->assertJsonPath('message', 'This shipment has been picked up and can no longer be cancelled.'); + $this->assertSame(FreightShipmentStatusEnum::Booked, $shipment->fresh()->status, 'a refused cancel leaves the load booked'); + + MockClient::destroyGlobal(); + MockClient::global([ShipStationCancelShipmentRequest::class => MockResponse::make([], 204)]); + + $this->postJson("/api/freight/shipments/{$shipment->id}/cancel")->assertOk()->assertJsonPath('data.status', 'cancelled'); + } + + public function test_shipstation_freight_is_in_the_catalog_with_its_logo_and_no_sync_chip(): void + { + $shipStation = collect($this->getJson('/api/integrations?filter[integration_type]='.Integration::TYPE_FREIGHT)->assertOk()->json('data')) + ->firstWhere('name', Integration::NAME_SHIPSTATION_FREIGHT); + + $this->assertNotNull($shipStation, 'ShipStation Freight must be listed in the Freight category'); + $this->assertSame('/images/shipping_providers/shipstation_square.png', $shipStation['image_url']); + $this->assertFalse((new Integration(['name' => Integration::NAME_SHIPSTATION_FREIGHT]))->hasSyncSurface()); + $this->assertSame('/v2/settings/freight', (new Integration(['name' => Integration::NAME_SHIPSTATION_FREIGHT]))->instancePath(3)); + } +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/book.json b/Modules/Freight/Tests/Fixtures/shipstation/book.json new file mode 100644 index 00000000000..bdb3e04940c --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/book.json @@ -0,0 +1,23 @@ +{ + "freight_shipment_id": "fs-77001234", + "freight_provider_account_id": "se-4433221", + "freight_provider_code": "WWEX", + "status": "booked", + "bol_number": "WWX20261124-0031", + "pro_number": null, + "confirmation_number": "WX-5521983", + "pickup_details": { + "pickup_date": "2026-11-24", + "ready_time": "08:00", + "close_time": "16:00", + "is_self_scheduled": false, + "location_type": "commercial" + }, + "references": [ + { "type": "sku_load", "value": "sku-tenant1-42-p7m2c8v1aa" }, + { "type": "po_number", "value": "PO-4471203" } + ], + "documents": [ + { "type": "bill_of_lading", "url": "https://api.shipstation.com/v2/downloads/freight/fs-77001234/bol.pdf" } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/cancel_refused.json b/Modules/Freight/Tests/Fixtures/shipstation/cancel_refused.json new file mode 100644 index 00000000000..96529ca0f19 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/cancel_refused.json @@ -0,0 +1,11 @@ +{ + "request_id": "c8a1f3e2-4b6d-49a0-8e17-5d2f9b0c3a64", + "errors": [ + { + "error_source": "provider", + "error_type": "business_rules", + "error_code": "shipment_not_cancellable", + "message": "This shipment has been picked up and can no longer be cancelled." + } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/documents.json b/Modules/Freight/Tests/Fixtures/shipstation/documents.json new file mode 100644 index 00000000000..ad622f05556 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/documents.json @@ -0,0 +1,6 @@ +{ + "documents": [ + { "type": "bill_of_lading", "url": "https://api.shipstation.com/v2/downloads/freight/fs-77001234/bol.pdf" }, + { "type": "pallet_labels", "url": "https://api.shipstation.com/v2/downloads/freight/fs-77001234/labels.pdf" } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/invalid_provider_account.json b/Modules/Freight/Tests/Fixtures/shipstation/invalid_provider_account.json new file mode 100644 index 00000000000..c1b71b48d84 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/invalid_provider_account.json @@ -0,0 +1,12 @@ +{ + "request_id": "1f0e5a2b-8c34-4d71-9a6e-2b7c0d4e9f35", + "errors": [ + { + "error_source": "shipengine", + "error_type": "business_rules", + "error_code": "invalid_field_value", + "message": "freight_provider_account_id must be a valid provider account id", + "field_name": "seller_freight_provider_id" + } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts.json b/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts.json new file mode 100644 index 00000000000..cac10c9279f --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts.json @@ -0,0 +1,14 @@ +{ + "provider_accounts": [ + { + "freight_provider_account_id": "se-4433221", + "freight_provider_code": "WWEX", + "nickname": "WWEX Main" + }, + { + "freight_provider_account_id": "se-4433298", + "freight_provider_code": "UNISHIPPERS", + "nickname": "Unishippers East" + } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts_empty.json b/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts_empty.json new file mode 100644 index 00000000000..67c627ca933 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/provider_accounts_empty.json @@ -0,0 +1,3 @@ +{ + "provider_accounts": [] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/quotes.json b/Modules/Freight/Tests/Fixtures/shipstation/quotes.json new file mode 100644 index 00000000000..5f74a541f33 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/quotes.json @@ -0,0 +1,36 @@ +{ + "quotes": [ + { + "freight_provider_account_id": "se-4433221", + "freight_provider_code": "WWEX", + "offer_id": "ofr_7Q2K9M4XWB", + "carrier_name": "Estes Express Lines", + "carrier_scac": "EXLA", + "service_name": "Standard LTL", + "service_type": "standard", + "total_charges": { "currency": "usd", "amount": 412.37 }, + "transit_days": 4, + "estimated_delivery_date": "2026-11-30", + "is_guaranteed": false, + "quote_expiration_date": "2026-12-01T23:59:00Z", + "max_liability_new": { "currency": "usd", "amount": 25000.0 }, + "max_liability_used": { "currency": "usd", "amount": 2500.0 } + }, + { + "freight_provider_account_id": "se-4433221", + "freight_provider_code": "WWEX", + "offer_id": "ofr_8R3L0N5YXC", + "carrier_name": "Old Dominion Freight Line", + "carrier_scac": "ODFL", + "service_name": "Guaranteed by 5 PM", + "service_type": "guaranteed", + "total_charges": { "currency": "usd", "amount": 498.1 }, + "transit_days": 3, + "estimated_delivery_date": "2026-11-27", + "is_guaranteed": true, + "quote_expiration_date": "2026-12-01T23:59:00Z", + "max_liability_new": { "currency": "usd", "amount": 25000.0 }, + "max_liability_used": { "currency": "usd", "amount": 2500.0 } + } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/quotes_empty.json b/Modules/Freight/Tests/Fixtures/shipstation/quotes_empty.json new file mode 100644 index 00000000000..bfd813ef913 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/quotes_empty.json @@ -0,0 +1,3 @@ +{ + "quotes": [] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/shipments.json b/Modules/Freight/Tests/Fixtures/shipstation/shipments.json new file mode 100644 index 00000000000..95e3adb0984 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/shipments.json @@ -0,0 +1,46 @@ +{ + "freight_shipments": [ + { + "freight_shipment_id": "fs-77000999", + "status": "booked", + "created_at": "2026-11-24T14:10:00Z", + "bol_number": "WWX20261123-0007", + "confirmation_number": "WX-5521001", + "references": [{ "type": "sku_load", "value": "sku-tenant1-41-k3j9x0q2wd" }] + }, + { + "freight_shipment_id": "fs-77001000", + "status": "cancelled", + "created_at": "2026-11-24T15:00:20Z", + "bol_number": "WWX20261124-0030", + "confirmation_number": "WX-5521982", + "references": [{ "type": "sku_load", "value": "sku-tenant1-42-p7m2c8v1aa" }] + }, + { + "freight_shipment_id": "fs-77001100", + "status": "booked", + "created_at": "2026-11-24T15:00:30Z", + "bol_number": "WWX20261124-0029", + "confirmation_number": "WX-5521980", + "references": [ + { "type": "sku_load", "value": "sku-tenant1-42-zzzzzzzzzz" }, + { "type": "po_number", "value": "PO-4471203" } + ] + }, + { + "freight_shipment_id": "fs-77001234", + "status": "booked", + "created_at": "2026-11-24T15:00:40Z", + "bol_number": "WWX20261124-0031", + "pro_number": null, + "confirmation_number": "WX-5521983", + "references": [ + { "type": "sku_load", "value": "sku-tenant1-42-p7m2c8v1aa" }, + { "type": "po_number", "value": "PO-4471203" } + ] + } + ], + "total": 4, + "page": 1, + "pages": 1 +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/tracking_delivered.json b/Modules/Freight/Tests/Fixtures/shipstation/tracking_delivered.json new file mode 100644 index 00000000000..343d2314b48 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/tracking_delivered.json @@ -0,0 +1,14 @@ +{ + "freight_shipment_id": "fs-77001234", + "status": "delivered", + "pro_number": "1234567890", + "estimated_delivery_date": "2026-11-28", + "actual_pickup_date": "2026-11-24T19:42:00Z", + "actual_delivery_date": "2026-11-28T17:05:00Z", + "events": [ + { "occurred_at": "2026-11-24T15:02:00Z", "status": "booked", "description": "Pickup scheduled with Estes Express Lines", "city_locality": "Ontario", "state_province": "CA" }, + { "occurred_at": "2026-11-24T19:42:00Z", "status": "picked_up", "description": "Picked up", "city_locality": "Ontario", "state_province": "CA" }, + { "occurred_at": "2026-11-25T06:10:00Z", "status": "in_transit", "description": "Departed terminal", "city_locality": "Phoenix", "state_province": "AZ" }, + { "occurred_at": "2026-11-28T17:05:00Z", "status": "delivered", "description": "Delivered, signed by RECEIVING", "city_locality": "Atlanta", "state_province": "GA" } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/tracking_in_transit.json b/Modules/Freight/Tests/Fixtures/shipstation/tracking_in_transit.json new file mode 100644 index 00000000000..763cd1f33ce --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/tracking_in_transit.json @@ -0,0 +1,13 @@ +{ + "freight_shipment_id": "fs-77001234", + "status": "in_transit", + "pro_number": "1234567890", + "estimated_delivery_date": "2026-11-28", + "actual_pickup_date": "2026-11-24T19:42:00Z", + "actual_delivery_date": null, + "events": [ + { "occurred_at": "2026-11-24T15:02:00Z", "status": "booked", "description": "Pickup scheduled with Estes Express Lines", "city_locality": "Ontario", "state_province": "CA" }, + { "occurred_at": "2026-11-24T19:42:00Z", "status": "picked_up", "description": "Picked up", "city_locality": "Ontario", "state_province": "CA" }, + { "occurred_at": "2026-11-25T06:10:00Z", "status": "in_transit", "description": "Departed terminal", "city_locality": "Phoenix", "state_province": "AZ" } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/unauthorized.json b/Modules/Freight/Tests/Fixtures/shipstation/unauthorized.json new file mode 100644 index 00000000000..9cf4caf98c3 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/unauthorized.json @@ -0,0 +1,11 @@ +{ + "request_id": "9d2c4b1e-5a7f-4c3e-8b21-0f6a3d9e7c12", + "errors": [ + { + "error_source": "shipengine", + "error_type": "security", + "error_code": "unauthorized", + "message": "The API key is invalid. Please see https://www.shipengine.com/docs/auth" + } + ] +} diff --git a/Modules/Freight/Tests/Fixtures/shipstation/validation_error.json b/Modules/Freight/Tests/Fixtures/shipstation/validation_error.json new file mode 100644 index 00000000000..d1051de6967 --- /dev/null +++ b/Modules/Freight/Tests/Fixtures/shipstation/validation_error.json @@ -0,0 +1,12 @@ +{ + "request_id": "6b3e1d9a-2f47-4c85-a0b1-7e9d2c4f6a18", + "errors": [ + { + "error_source": "carrier", + "error_type": "validation", + "error_code": "invalid_field_value", + "message": "Destination postal code 30336 is outside the carrier's service area for liftgate delivery.", + "field_name": "ship_to.postal_code" + } + ] +} diff --git a/Modules/Freight/Tests/FreightTestCase.php b/Modules/Freight/Tests/FreightTestCase.php index 39bb4105f0f..d496c9320ac 100644 --- a/Modules/Freight/Tests/FreightTestCase.php +++ b/Modules/Freight/Tests/FreightTestCase.php @@ -49,9 +49,35 @@ abstract class FreightTestCase extends TestCase /** * @return array */ - protected function fixture(string $name): array + protected function fixture(string $name, string $provider = 'warp'): array { - return json_decode((string) file_get_contents(__DIR__.'/Fixtures/warp/'.$name.'.json'), true, 512, JSON_THROW_ON_ERROR); + return json_decode((string) file_get_contents(__DIR__.'/Fixtures/'.$provider.'/'.$name.'.json'), true, 512, JSON_THROW_ON_ERROR); + } + + /** + * ShipStation's answers (Tests/Fixtures/shipstation), built from the documented V2 freight + * contract and the errors probed live on 2026-11-21 (SKU-8974) + */ + protected function shipStationResponse(string $fixture, int $status = 200): MockResponse + { + return MockResponse::make($this->fixture($fixture, 'shipstation'), $status); + } + + /** + * A production ShipStation connection with its Worldwide Express provider account selected + * + * @param array $settings + */ + protected function shipStationConnection(array $settings = []): FreightIntegrationInstance + { + return FreightIntegrationInstance::factory()->shipStation()->create([ + 'integration_settings' => [ + 'provider_accounts' => [['id' => 'se-4433221', 'code' => 'WWEX', 'nickname' => 'WWEX Main']], + 'freight_provider_account_id' => 'se-4433221', + 'account_warnings' => [], + ...$settings, + ], + ]); } protected function warpResponse(string $fixture, int $status = 200): MockResponse diff --git a/app/Models/Integration.php b/app/Models/Integration.php index 36543be1446..fb4dba74f6a 100644 --- a/app/Models/Integration.php +++ b/app/Models/Integration.php @@ -304,6 +304,9 @@ class Integration extends Model /** Warp — LTL / FTL / box truck freight network; API v1 with a per-account bearer key (sandbox wak_test_*). */ const NAME_WARP_FREIGHT = 'Warp Freight'; + /** ShipStation Freight — LTL through the Worldwide Express / Unishippers account connected in ShipStation; V2 API key (SKU-8974). */ + const NAME_SHIPSTATION_FREIGHT = 'ShipStation Freight'; + /** AfterShip Warranty — warranty claims over its Warranty API (as-api-key) and signed webhooks. */ const NAME_AFTERSHIP_WARRANTY = 'AfterShip Warranty'; @@ -442,6 +445,7 @@ class Integration extends Model */ public const MANAGED_ON_FREIGHT_SETTINGS = [ self::NAME_WARP_FREIGHT, + self::NAME_SHIPSTATION_FREIGHT, ]; /** @@ -553,6 +557,7 @@ class Integration extends Model self::NAME_REPAIR_CLAIM_FORM, // SKU-8948: a freight account is asked on demand (quotes, bookings, tracking polls); it never syncs self::NAME_WARP_FREIGHT, + self::NAME_SHIPSTATION_FREIGHT, ]; /** diff --git a/app/Support/FeatureCatalog.php b/app/Support/FeatureCatalog.php index 5d412292740..fc6f4c770cd 100644 --- a/app/Support/FeatureCatalog.php +++ b/app/Support/FeatureCatalog.php @@ -1329,7 +1329,7 @@ class FeatureCatalog 'untracked_routes' => ['freight.shipments.show', 'freight.shipments.activity'], 'pages' => ['/freight', '/freight/*', '/settings/freight'], 'adoption' => [[TableRowsCollector::class, ['table' => 'freight_shipments', 'userColumn' => 'created_by']]], - 'configured' => [IntegrationConfiguredCheck::class, ['integrationNames' => [Integration::NAME_WARP_FREIGHT]]], + 'configured' => [IntegrationConfiguredCheck::class, ['integrationNames' => [Integration::NAME_WARP_FREIGHT, Integration::NAME_SHIPSTATION_FREIGHT]]], 'eligibility' => ['permission' => 'freight.view', 'modules' => ['Freight']], ], 'label_batches' => [ diff --git a/database/migrations/tenant/2026_11_21_210000_seed_shipstation_freight_integration.php b/database/migrations/tenant/2026_11_21_210000_seed_shipstation_freight_integration.php new file mode 100644 index 00000000000..1c5a7b7f05c --- /dev/null +++ b/database/migrations/tenant/2026_11_21_210000_seed_shipstation_freight_integration.php @@ -0,0 +1,36 @@ +exists() || DB::table('integrations')->where('name', 'ShipStation Freight')->exists()) { + return; + } + + DB::table('integrations')->insert([ + 'name' => 'ShipStation Freight', + 'description' => 'Quote, book and track LTL freight through the Worldwide Express or Unishippers account connected in your ShipStation, with the bill of lading, PRO and carrier written to the shipment for its ship notice.', + 'integration_settings_template' => '[]', + 'image_url' => '/images/shipping_providers/shipstation_square.png', + 'icon_url' => '/images/shipping_providers/shipstation_square.png', + 'integration_type' => 'freight', + 'supports_multiple_instances' => true, + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + public function down(): void + { + DB::table('integrations')->where('name', 'ShipStation Freight')->delete(); + } +}; diff --git a/database/seeders/ImmutableData/IntegrationsSeeder.php b/database/seeders/ImmutableData/IntegrationsSeeder.php index 3462ad6a79e..34507d36573 100644 --- a/database/seeders/ImmutableData/IntegrationsSeeder.php +++ b/database/seeders/ImmutableData/IntegrationsSeeder.php @@ -591,15 +591,17 @@ class IntegrationsSeeder extends Seeder |-------------------------------------------------------------------------- */ foreach ([ - Integration::NAME_WARP_FREIGHT => 'Quote, book and track LTL and truckload freight on your Warp account, with the bill of lading, PRO and carrier written to the shipment for its ship notice.', - ] as $name => $description) { + Integration::NAME_WARP_FREIGHT => ['Quote, book and track LTL and truckload freight on your Warp account, with the bill of lading, PRO and carrier written to the shipment for its ship notice.', '/images/integrations/icons/warp.svg', false], + // SKU-8974: one connection per ShipStation account, so a tenant may connect several + Integration::NAME_SHIPSTATION_FREIGHT => ['Quote, book and track LTL freight through the Worldwide Express or Unishippers account connected in your ShipStation, with the bill of lading, PRO and carrier written to the shipment for its ship notice.', '/images/shipping_providers/shipstation_square.png', true], + ] as $name => [$description, $logo, $supportsMultiple]) { /** @var Integration $integration */ $integration = Integration::with([])->firstOrNew(['name' => $name]); $integration->description = $description; $integration->integration_settings_template = []; - $integration->image_url = '/images/integrations/icons/warp.svg'; - $integration->icon_url = '/images/integrations/icons/warp.svg'; - $integration->supports_multiple_instances = false; + $integration->image_url = $logo; + $integration->icon_url = $logo; + $integration->supports_multiple_instances = $supportsMultiple; $integration->integration_type = Integration::TYPE_FREIGHT; $integration->save(); } diff --git a/docs/plans/shipstation-freight-driver.md b/docs/plans/shipstation-freight-driver.md new file mode 100644 index 00000000000..2f8f0330c4a --- /dev/null +++ b/docs/plans/shipstation-freight-driver.md @@ -0,0 +1,279 @@ +# PRD: ShipStation as the second Freight provider + +**Ticket:** SKU-8974 (child of SKU-8948) +**Status:** Draft +**Created:** 2026-11-21 + +--- + +## Overview + +SKU-8948 shipped a provider-agnostic Freight module (quote, book, track, BOL, stale-quote detection, write-through to the shipment's freight details that feed the SPS 856) with Warp as its first provider. This PRD adds **ShipStation** as the second provider: a merchant connects their own ShipStation account with its V2 API key, picks which of their ShipStation freight provider accounts (Worldwide Express or Unishippers) to use, and SKU.io quotes, books, cancels, tracks and fetches documents through ShipStation's `/v2/freight` API. Nothing in the quote, book or track flow changes for the user; ShipStation rates simply appear beside Warp's. + +--- + +## Problem Statement + +### Current Pain Points + +1. Many SKU.io merchants already ship parcels through ShipStation, and ShipStation now brokers LTL through Worldwide Express and Unishippers. Those merchants have negotiated freight rates in ShipStation that SKU.io cannot see. +2. A merchant who wants to compare Warp against their ShipStation freight rates has to quote twice, in two systems, and re-key the winning booking's BOL, PRO and SCAC into SKU.io for the ship notice. +3. Warp is the only provider, so a merchant whose lanes Warp does not serve has no in-app freight option. + +### Business Impact + +- Freight is where multichannel brands selling to big-box retailers lose the most time per order (routing guides, BOLs, PRO numbers on the 856). Covering the broker most of our ShipStation-using merchants already have turns Freight from "a Warp feature" into the place they quote everything. +- ShipStation is the most common shipping tool among SKU.io's merchants, so it is the provider most likely to be connected on day one. + +--- + +## Goals & Success Metrics + +### Primary Goals + +1. A merchant connects ShipStation (V2 API key) in Settings → Freight or Apps & integrations → Freight → ShipStation Freight, exactly like Warp. +2. Rates from the selected ShipStation freight provider account appear in the quote drawer and workspace next to Warp's, labelled with the carrier and the provider (Worldwide Express / Unishippers). +3. Booking a ShipStation rate writes BOL, PRO (when the carrier assigns it) and SCAC to the shipment the same way Warp does. +4. Cancel, tracking and provider documents work through the existing Freight screens. +5. No change to the provider-agnostic core beyond what a second provider needs (a select-type provider setting). + +### Success Metrics + +| Metric | Current | Target | +|--------|---------|--------| +| Freight providers a merchant can connect | 1 (Warp) | 2 (Warp, ShipStation) | +| Steps to compare Warp vs ShipStation rates for one load | Two systems, re-key | One quote, one list | +| Manual BOL/PRO/SCAC entry after a ShipStation freight booking | Every booking | None | + +--- + +## Competitive Analysis + +- **ShipStation's own Freight tab** quotes and books LTL only through Worldwide Express or Unishippers. Merchants either activate Worldwide Express from inside ShipStation (it asks for a payment method and auto-pay authorisation) or connect an existing WWEX/Unishippers account. SKU.io inherits exactly that: we never create the freight account, we use the one the merchant connected in ShipStation. +- **Order management tools with freight (Cin7, Extensiv, Logiwa)** typically either integrate one broker or push the order to the merchant's TMS. None we found compares two freight sources side by side on the order. Doing that, and writing the result to the retailer ship notice, is the differentiator. +- **Lesson:** the connect step must say plainly that freight has to be set up in ShipStation first (Freight → Connect your account), or the merchant gets an empty provider list and no rates with no explanation. + +--- + +## Background + +### Current State + +- `Modules/Freight` (SKU-8948): `FreightProviderDriver` contract (`capabilities`, `testConnection`, `quote`, `book`, `cancel`, `track`, `documents`, `findBookingForQuote`), `FreightProviderEnum` (one case, `Warp`, with `credentialFields()` / `settingFields()` driving the connect drawer), `WarpFreightDriver` + Saloon `WarpConnector`, quote attempts as queued jobs, booking with idempotency + held-for-approval handling, tracking polls every 30 minutes, generated VICS BOL, catalog entry `Warp Freight` (type `freight`). +- Connect drawer (`FreightConnectionDrawer.vue`) renders credential and setting fields from the backend; settings are text inputs with a max length. + +### What the ShipStation API offers (verified 2026-11-21) + +| Need | ShipStation V2 | +|---|---| +| Auth | `api-key` header, the merchant's own V2 key (Settings → Account → API Settings → V2 API → Generate) | +| Provider accounts | `GET /v2/freight/provider_accounts` → `freight_provider_account_id` (`se-…`), `freight_provider_code` (`WWEX`, `UNISHIPPERS`), `nickname` | +| Quote | `POST /v2/freight/quotes` (inline ship_from/ship_to/handling_units/accessorials/insurance) → `quotes[]` with `offer_id`, `carrier_name`, `carrier_scac`, `service_name`, `total_charges`, `transit_days`, `estimated_delivery_date`, `is_guaranteed`, `quote_expiration_date` | +| Book | `POST /v2/freight/shipments` (`offer_id`, `pickup_details`, `references`, instructions, `notifications`) → `freight_shipment_id`, `status`, `bol_number`, `pro_number` (often null until pickup), `confirmation_number`, `documents[]` | +| Get / list | `GET /v2/freight/shipments/{id}`, `GET /v2/freight/shipments?created_at_start…` | +| Documents | `GET /v2/freight/shipments/{id}/documents` (BOL, pallet labels…) | +| Tracking | `GET /v2/freight/shipments/{id}/tracking`; webhook `freight_track_event_v2` | +| Cancel | `DELETE /v2/freight/shipments/{id}` | +| Hazmat | per commodity `hazardous_materials` (UN/NA id, proper shipping name, class, packing group, 24-hour emergency contact) | + +Verified live with a merchant trial account's V2 key: `provider_accounts` and `shipments` answer 200; a quote passes request validation and stops at "freight_provider_account_id must be a valid provider account id" because no provider is connected. **Doc drift found:** the live API requires `handling_units[].dimension_unit` and `commodities[].weight_unit` although the docs say units are fixed; the driver always sends them (`inch`, `pound`). + +**No sandbox freight provider exists.** The ShipStation API sandbox (TEST_ keys) has no freight provider, and activating Worldwide Express on a trial requires a payment method. Live quote/book/track are therefore NOT VERIFIED until ShipStation enables a test provider (asked in the partner email) or a merchant lends a connected account. + +### Existing Infrastructure + +Everything in SKU-8948 is reused: quote attempts, rates, stale detection, booking manager (idempotency, locks, cancel recording), tracking poller, BOL generation, write-through to `sales_order_fulfillment_freight_details`, permissions, Freight list, catalog/category, Postman collection. + +--- + +## Feature Details + +### Feature 1: ShipStation provider + connection + +**Description:** `FreightProviderEnum::ShipStation` (`shipstation`), integration row `ShipStation Freight` (type `freight`, logo reused from the ShipStation shipping-provider image), credential field `api_key` (secret, help text naming where the V2 key lives and that freight must be set up in ShipStation first), setting field `freight_provider_account_id` of a new type **select** whose options are the account's provider accounts. + +#### Behavior + +1. Merchant opens Connect (from Settings → Freight or the catalog's ShipStation Freight card), pastes the V2 key, clicks Test connection. +2. `testConnection` calls `GET /v2/freight/provider_accounts`. + - Key rejected (401/403) → "ShipStation didn't accept this key. Use a V2 API key from Settings → Account → API Settings." Nothing saved. + - Zero provider accounts → connection saves, but the status card shows a blocking warning: "No freight account is connected in ShipStation. In ShipStation, open Freight → Connect your account (Worldwide Express or Unishippers), then test again." Quote is disabled for this connection with that reason. + - One account → selected automatically. + - Several → the **Freight provider account** select lists `nickname (Worldwide Express)` / `(Unishippers)`; required before quoting. +3. Environment: ShipStation merchant keys are always production; the connection shows **Production** and the sandbox-writes guard does not apply. (A TEST_ key from a ShipStation API account is accepted and shown as **Sandbox**, but it has no freight provider today; the warning above explains it.) + +#### Data Flow + +1. **UI** → Connect drawer posts `{provider: "shipstation", credentials: {api_key}}` to the existing connection endpoints. +2. **Backend** → `FreightConnectionManager` saves, calls `ShipStationFreightDriver::testConnection`, stores `account_warnings` and the provider-account list in `integration_settings.provider_accounts`. +3. **UI** → drawer shows the select (options from `GET /api/freight/connections/{id}` → `setting_options.freight_provider_account_id`). + +#### API Specification + +No new routes. `GET /api/freight/providers` returns the ShipStation entry with `setting_fields[].type = "select"`. `GET /api/freight/connections/{id}` gains `setting_options` (key → list of `{value, label}`). `PUT /api/freight/connections/{id}` validates `settings.freight_provider_account_id` against the stored options. + +### Feature 2: Quote + +**Description:** `ShipStationFreightDriver::quote` posts an inline quote for the load to the selected provider account and maps each offer to a SKU.io rate. + +#### Behavior / mapping + +| SKU.io | ShipStation | +|---|---| +| origin / destination address + contact | `ship_from` / `ship_to` (name, company_name, phone required) | +| destination type | `ship_to.location_type` (commercial, residential, distribution_center, limited_access, construction, trade_show…) | +| handling unit type, qty, L×W×H, stackable | `handling_units[]` (`type`, `quantity`, `length`/`width`/`height`, `dimension_unit: inch`, `stackable`) | +| commodity description, qty, weight, class, packaging | `commodities[]` (`weight` per handling unit, `weight_unit: pound`, `freight_class` as string, `packaging_type`) | +| hazmat (UN number, proper shipping name, class, packing group, emergency contact) | `commodities[].hazardous_materials` (uses Freight settings' emergency contact) | +| accessorials (liftgate, inside, residential, appointment, notify, construction, trade show) | `accessorials` booleans | +| declared value | `insurance.insured_value` only when the user asks for cargo insurance | +| rate: carrier, SCAC, service, total, transit days, ETA, guaranteed, expires | `carrier_name`, `carrier_scac`, `service_name`, `total_charges`, `transit_days`, `estimated_delivery_date`, `is_guaranteed`, `quote_expiration_date` | +| provider quote id | `offer_id` | + +- Modes: LTL only (`capabilities` reports LTL; FTL/box truck requests return a mode error "ShipStation freight quotes LTL only"). +- Empty `quotes` → "No carrier through your ShipStation freight account serves this lane as described." +- Provider/carrier errors (`error_source: carrier|provider`) are shown with the provider's wording; validation errors map to the offending field. + +### Feature 3: Book + +**Description:** `book` posts `offer_id`, `pickup_details` (date, ready/close time, location type), `references` (customer PO, sales order number), pickup/delivery instructions, and notifications (the booking contact's email) to `POST /v2/freight/shipments`. + +- Result: provider shipment id = `freight_shipment_id`; BOL = `bol_number`; PRO = `pro_number` (null → filled later by tracking); SCAC = the booked offer's `carrier_scac`; confirmation number stored as a reference; documents listed. +- Idempotency: the API has no idempotency key, so a booking POST is never retried. Before the POST, the load stores a per-attempt reference (`sku_load` = tenant + load id + random nonce) and the attempt time; the reference is printed into `references`. After an unknown outcome (timeout/5xx) "Check booking" lists `GET /v2/freight/shipments` from the attempt time onward (2-minute clock-skew allowance) and adopts only a shipment carrying that exact reference. It concludes "nothing was booked" only when the search is provably complete and the attempt is older than the settle window (`freight.shipstation.booking_settle_seconds`, 5 minutes); an incomplete search (page cap, missing paging metadata on a full page) or a check inside the settle window leaves the load unconfirmed. +- Write-through to the shipment and sandbox guard: unchanged (production keys write; a TEST_ key is sandbox). + +### Feature 4: Track, documents, cancel + +- `track`: `GET /v2/freight/shipments/{id}/tracking` → status (`booked`, `in_transit`, `delivered`, `cancelled`, `exception`) + events; fills PRO when assigned. Polled by the existing 30-minute poller. (Webhook `freight_track_event_v2` is a follow-up, out of scope.) +- `documents`: `GET /v2/freight/shipments/{id}/documents` → BOL, pallet labels; shown under Provider documents. SKU.io's own generated BOL stays available. +- `cancel`: `DELETE /v2/freight/shipments/{id}`; a refusal shows the provider's message and leaves the load booked. + +### Feature 5: Catalog, settings, docs + +- Catalog: `ShipStation Freight` in the Freight category with the ShipStation logo; Connect opens `/settings/freight?connect=shipstation`; no sync chip (added to `NAMES_WITHOUT_SYNC`, `MANAGED_ON_FREIGHT_SETTINGS`). +- FeatureCatalog `freight` configured check includes the new integration name. +- Postman: provider list/connection responses show the select field and `setting_options`. + +--- + +## Database Changes + +### New Tables + +None. + +### Modified Tables + +None. `integrations` gets a `ShipStation Freight` row (seeder + tenant migration with literal values). Provider accounts are stored in the existing `integration_settings` JSON. + +### Migrations + +1. `seed_shipstation_freight_integration` (tenant): insert the integration row when the table is seeded and the row is missing. + +--- + +## UI Design + +### Wireframes + +``` +Settings → Freight → Connect ShipStation +┌────────────────────────────────────────────┐ +│ Connect ShipStation Freight │ +│ API key [••••••••••••••••••••] (V2 key) │ +│ From ShipStation: Settings → Account → │ +│ API Settings → V2 API → Generate API Key │ +│ Name [ShipStation — main] │ +│ [Test connection] │ +│ ────────────────────────────────────────── │ +│ Freight provider account [WWEX – Main ▾] │ +│ ⚠ No freight account is connected in │ +│ ShipStation. Open Freight → Connect your │ +│ account, then test again. (when empty) │ +└────────────────────────────────────────────┘ +``` + +Quote drawer / workspace: unchanged; ShipStation rates carry a "ShipStation · Worldwide Express" provider chip like Warp's. + +### Component Architecture + +| Component | Location | New/Modified | Description | +|-----------|----------|-------------|-------------| +| FreightConnectionDrawer | `pages/settings/freight/components/` | Modified | Render `type: "select"` setting fields from `setting_options`; drop the hard-coded `INTEGRATION_NAMES` map in favour of the provider list | +| settings/freight/index.vue | `pages/settings/freight/` | Modified | `?connect=shipstation`; names from the provider list | +| integrations constants | `pages/integrations/constants.ts` | Modified | Branding, connect + instance routes for `ShipStation Freight` | + +No new page, so no mockup round (same screens as SKU-8948). + +--- + +## Edge Cases & Considerations + +1. **No freight provider in ShipStation** → connection saves with a blocking warning; quoting disabled with the reason (most common first-run state). +2. **Provider account removed in ShipStation after setup** → quote returns "must be a valid provider account id" → mark the connection's warning, prompt to re-test and pick again. +3. **Key revoked/rotated** → 401 → connection shows "Key rejected"; quoting stops; same as Warp. +4. **Units** → always send `dimension_unit: inch`, `weight_unit: pound` (live API requires them despite the docs). +5. **Freight class** → send as a string from the allowed list (50…500); reject others before calling. +6. **Expired offer** → `quote_expiration_date` drives the existing expired-quote handling; booking an expired offer re-quotes. +7. **PRO null at booking** → filled by tracking; the 856 hold logic from `kmizzi/sps-ltl-pro-required` already waits for a PRO when the retailer requires it. +8. **Unknown booking outcome** → reference match (Feature 3); never double-book. +9. **Cancel after pickup** → provider refusal shown, load unchanged. +10. **Rate limits (429)** → treated as unavailable with retry-after, like Warp. +11. **Multiple ShipStation connections** (two ShipStation accounts) → allowed, each with its own provider account; rates labelled by connection name. +12. **TEST_ key** → accepted, shown as Sandbox; no provider exists so the warning explains; sandbox-writes guard applies. +13. **Hazmat without emergency contact in Freight settings** → blocked before calling (existing rule). +14. **FTL / box truck** requested → per-mode error for ShipStation, other providers still quote. + +--- + +## Implementation Plan + +### Phase 1: Provider plumbing (Medium) +- [ ] `FreightProviderEnum::ShipStation` (label, integration name, credential + select setting fields, website, description) +- [ ] `Integration::NAME_SHIPSTATION_FREIGHT`, seeder row with logo, tenant migration (literal values), `NAMES_WITHOUT_SYNC`, `MANAGED_ON_FREIGHT_SETTINGS`, FeatureCatalog configured check, ResetInventory unaffected +- [ ] Setting-field type `select` + `setting_options` on connection resource; validation against stored options +- [ ] Config `freight.shipstation` (base URL, timeouts) + +### Phase 2: Driver (Large) +- [ ] Saloon `ShipStationConnector` + requests (provider accounts, quotes, create shipment, get/list shipments, tracking, documents, cancel) +- [ ] `ShipStationFreightDriver` implementing the contract; error mapping (auth, validation, provider/carrier, 429/5xx unavailable) +- [ ] Fixtures from the documented contract and the probed live errors +- [ ] Feature tests mirroring `WarpFreightDriverTest` + quote/book/track/cancel flow tests on ShipStation fixtures + +### Phase 3: Frontend (Small) +- [ ] Drawer select setting, provider names from the API, catalog constants/branding/routes, `?connect=shipstation` +- [ ] Vitest for the select field and catalog routes + +### Phase 4: Docs & verification (Small) +- [ ] `/api-docs` (Postman), PRD testing instructions +- [ ] Live verification once a provider exists (NOT VERIFIED until then), including: the list-shipments filter names (`created_at_start` / `created_at_end`) are honoured, list items return `references[]`, paging metadata (`pages` / `links.next`), custom `sku_load` reference type kept and returned on list items; page_size honoured/echoed, and tracking/list response shapes + +--- + +## UI Testing Instructions + +### Prerequisites +- Freight module enabled; a user with freight.view/quote/book. +- A ShipStation V2 API key. Without a freight provider connected in ShipStation, only the connection and warning paths can be exercised; quote/book/track need a merchant account with Worldwide Express or Unishippers connected. + +### Test Scenarios + +#### Happy Path +1. Navigate to `{BASE_URL}/v2/settings/freight`, click **Connect** on ShipStation (or `{BASE_URL}/v2/integrations` → Freight → ShipStation Freight → Connect). +2. Paste the V2 key, click **Test connection**. +3. **Expected:** connection saved; provider account select shows the account(s) (or the warning when none). +4. Open a sales order → **Get freight quote** → **Get rates**. +5. **Expected:** ShipStation rates appear beside Warp's with carrier, SCAC, transit days, total; book one → BOL/PRO/SCAC on the shipment. + +#### Validation & Error States +1. Paste a wrong key → **Expected:** "ShipStation didn't accept this key…", nothing saved. +2. Account with no freight provider → **Expected:** warning on the card; Get rates explains why ShipStation is skipped. + +#### Edge Cases +1. Request FTL on a load → **Expected:** ShipStation reports LTL only; Warp still quotes. +2. Remove the provider account in ShipStation, re-quote → **Expected:** warning asks to test again and pick an account. + +### Visual Verification Points +- [ ] ShipStation Freight card in the catalog's Freight category with the ShipStation logo +- [ ] Select field renders like other settings fields +- [ ] Provider chip on ShipStation rates diff --git a/docs/postman/postman-orders.json b/docs/postman/postman-orders.json index 958fb225351..d8a2145ffdd 100644 --- a/docs/postman/postman-orders.json +++ b/docs/postman/postman-orders.json @@ -194370,7 +194370,7 @@ "providers" ] }, - "description": "The freight providers SKU.io can connect to, with what each needs and supports: `credential_fields` and `setting_fields` (key, label, help, whether secret), and `capabilities` (`modes`, `pickup_accessorials`, `delivery_accessorials`, `countries`, `max_ltl_height_in`, `supports_cancel`, `supports_hazmat`, `supports_tracking`, `supports_documents`, `cancel_instructions`).\n\nAuthentication: Requires Bearer token with the `integrations:read` scope.\n\n**Requires permission:** `freight.view` or `integrations.index`" + "description": "The freight providers SKU.io can connect to, with what each needs and supports: `credential_fields` and `setting_fields` (key, label, help, whether secret), and `capabilities` (`modes`, `pickup_accessorials`, `delivery_accessorials`, `countries`, `max_ltl_height_in`, `supports_cancel`, `supports_hazmat`, `supports_tracking`, `supports_documents`, `cancel_instructions`).\n\nAuthentication: Requires Bearer token with the `integrations:read` scope.\n\n**Requires permission:** `freight.view` or `integrations.index`\n\nEach provider lists `setting_fields`, each with a `type`: `text` (free text, `max` characters) or `select` (choose one of the connection's `setting_options`, which are filled when the connection is tested; ShipStation's freight provider account is a select). `allows_multiple_connections` is true when the provider can be connected more than once (ShipStation); Warp is one connection per account." }, "response": [ { @@ -194416,7 +194416,7 @@ } ], "cookie": [], - "body": "{\n \"data\": [\n {\n \"key\": \"warp\",\n \"label\": \"Warp\",\n \"description\": \"LTL, full truckload and box truck across the US on Warp's network. Quote without a card; add one in Warp before booking.\",\n \"website_url\": \"https://www.wearewarp.com\",\n \"credential_fields\": [\n {\n \"key\": \"api_key\",\n \"label\": \"API key\",\n \"secret\": true,\n \"help\": \"From your Warp account (wearewarp.com/agents/account). A key starting wak_test_ is the sandbox: quotes and bookings are test data and nothing is charged.\",\n \"placeholder\": \"wak_live_… or wak_test_…\"\n }\n ],\n \"setting_fields\": [\n {\n \"key\": \"carrier_scac\",\n \"label\": \"SCAC on ship notices\",\n \"help\": \"Warp is the carrier of record and does not send a SCAC with a booking. Ask Warp for theirs and enter it here so retailer ship notices (856) carry it.\",\n \"max\": 4\n }\n ],\n \"capabilities\": {\n \"modes\": [\n \"ltl\",\n \"ftl\",\n \"box_truck\"\n ],\n \"pickup_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\"\n ],\n \"delivery_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\",\n \"notify\"\n ],\n \"supports_cancel\": false,\n \"supports_hazmat\": true,\n \"supports_tracking\": true,\n \"supports_documents\": true,\n \"max_ltl_height_in\": 85,\n \"countries\": [\n \"US\"\n ],\n \"cancel_instructions\": \"Warp cancels bookings by email. Email support@wearewarp.com with the shipment number, then mark the load cancelled here.\"\n }\n }\n ]\n}" + "body": "{\n \"data\": [\n {\n \"key\": \"warp\",\n \"label\": \"Warp\",\n \"description\": \"LTL, full truckload and box truck across the US on Warp's network. Quote without a card; add one in Warp before booking.\",\n \"website_url\": \"https://www.wearewarp.com\",\n \"credential_fields\": [\n {\n \"key\": \"api_key\",\n \"label\": \"API key\",\n \"secret\": true,\n \"help\": \"From your Warp account (wearewarp.com/agents/account). A key starting wak_test_ is the sandbox: quotes and bookings are test data and nothing is charged.\",\n \"placeholder\": \"wak_live_… or wak_test_…\"\n }\n ],\n \"setting_fields\": [\n {\n \"key\": \"carrier_scac\",\n \"label\": \"SCAC on ship notices\",\n \"help\": \"Warp is the carrier of record and does not send a SCAC with a booking. Ask Warp for theirs and enter it here so retailer ship notices (856) carry it.\",\n \"max\": 4,\n \"type\": \"text\"\n }\n ],\n \"capabilities\": {\n \"modes\": [\n \"ltl\",\n \"ftl\",\n \"box_truck\"\n ],\n \"pickup_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\"\n ],\n \"delivery_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\",\n \"notify\"\n ],\n \"supports_cancel\": false,\n \"supports_hazmat\": true,\n \"supports_tracking\": true,\n \"supports_documents\": true,\n \"max_ltl_height_in\": 85,\n \"countries\": [\n \"US\"\n ],\n \"cancel_instructions\": \"Warp cancels bookings by email. Email support@wearewarp.com with the shipment number, then mark the load cancelled here.\",\n \"missing_booking_message\": \"Warp has no booking for this quote, so nothing was booked. Booking the same rate again is safe: Warp books a quote only once.\"\n },\n \"allows_multiple_connections\": false\n },\n {\n \"key\": \"shipstation\",\n \"label\": \"ShipStation\",\n \"description\": \"LTL rates from the Worldwide Express or Unishippers account connected in your ShipStation, booked, tracked and cancelled without leaving SKU.io.\",\n \"website_url\": \"https://www.shipstation.com\",\n \"credential_fields\": [\n {\n \"key\": \"api_key\",\n \"label\": \"API key\",\n \"secret\": true,\n \"help\": \"Your ShipStation V2 API key (ShipStation → Settings → Account → API Settings → V2 API → Generate API Key). Freight must be set up in ShipStation first: Freight → Connect your account (Worldwide Express or Unishippers).\",\n \"placeholder\": \"V2 API key\"\n }\n ],\n \"setting_fields\": [\n {\n \"key\": \"freight_provider_account_id\",\n \"type\": \"select\",\n \"label\": \"Freight provider account\",\n \"help\": \"The Worldwide Express or Unishippers account connected in ShipStation that quotes and books these loads. Test the connection to refresh the list.\",\n \"max\": null\n }\n ],\n \"allows_multiple_connections\": true,\n \"capabilities\": {\n \"modes\": [\n \"ltl\"\n ],\n \"pickup_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\"\n ],\n \"delivery_accessorials\": [\n \"liftgate\",\n \"inside\",\n \"residential\",\n \"limited_access\",\n \"appointment\",\n \"notify\"\n ],\n \"supports_cancel\": true,\n \"supports_hazmat\": true,\n \"supports_tracking\": true,\n \"supports_documents\": true,\n \"max_ltl_height_in\": 85,\n \"countries\": [\n \"US\"\n ],\n \"cancel_instructions\": \"Warp cancels bookings by email. Email support@wearewarp.com with the shipment number, then mark the load cancelled here.\",\n \"missing_booking_message\": \"ShipStation has no booking carrying this attempt's SKU.io reference, so nothing was booked. Get new rates or book the rate again.\"\n }\n }\n ]\n}" } ] }, @@ -194498,7 +194498,7 @@ } ], "cookie": [], - "body": "{\n \"data\": [\n {\n \"id\": 4,\n \"name\": \"Warp\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": 12,\n \"moving_bookings\": 3,\n \"created_at\": \"2026-11-02T17:20:31+00:00\"\n }\n ]\n}" + "body": "{\n \"data\": [\n {\n \"id\": 4,\n \"name\": \"Warp\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"setting_options\": {},\n \"quote_blocked_reason\": null,\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": 12,\n \"moving_bookings\": 3,\n \"created_at\": \"2026-11-02T17:20:31+00:00\"\n },\n {\n \"id\": 5,\n \"name\": \"ShipStation Freight\",\n \"provider\": \"shipstation\",\n \"provider_label\": \"ShipStation\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…cT4\"\n }\n },\n \"settings\": {\n \"freight_provider_account_id\": \"se-4821\"\n },\n \"setting_options\": {\n \"freight_provider_account_id\": [\n {\n \"value\": \"se-4821\",\n \"label\": \"Main (Worldwide Express)\"\n }\n ]\n },\n \"quote_blocked_reason\": null,\n \"account_label\": null,\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": 12,\n \"moving_bookings\": 3,\n \"created_at\": \"2026-11-02T17:20:31+00:00\"\n }\n ]\n}" } ] }, @@ -194538,7 +194538,7 @@ "connections" ] }, - "description": "Connect a freight account. The credentials are checked with the provider before saving; an invalid key returns 422 with `errors.credentials`. A provider can be connected once.\n\n**Body fields**\n- `provider` (required on create): `warp`.\n- `name` (optional, max 60).\n- `credentials` (required on create, object): the provider's credential fields from List Freight Providers; for Warp `credentials.api_key` (max 500). A key starting `wak_test_` is the sandbox: quotes and bookings are test data and nothing is charged. On update, a blank credential keeps the stored value.\n- `settings.carrier_scac` (optional, 2-4 letters): the SCAC to put on retailer ship notices when the provider is the carrier of record and does not send one (Warp).\n\nSecrets are never returned: `credentials.` gives only `is_set` and the last four characters (`hint`).\n\nReturns 201.\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`", + "description": "Connect a freight account. The credentials are checked with the provider before saving; an invalid key returns 422 with `errors.credentials`. A provider can be connected once.\n\n**Body fields**\n- `provider` (required on create): `warp`.\n- `name` (optional, max 60).\n- `credentials` (required on create, object): the provider's credential fields from List Freight Providers; for Warp `credentials.api_key` (max 500). A key starting `wak_test_` is the sandbox: quotes and bookings are test data and nothing is charged. On update, a blank credential keeps the stored value.\n- `settings.carrier_scac` (optional, 2-4 letters): the SCAC to put on retailer ship notices when the provider is the carrier of record and does not send one (Warp).\n\nSecrets are never returned: `credentials.` gives only `is_set` and the last four characters (`hint`).\n\nReturns 201.\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`\n\n**ShipStation** (`provider: shipstation`): `credentials.api_key` is the account's V2 API key. `settings.freight_provider_account_id` picks the Worldwide Express or Unishippers account to quote and book through; on edit it must be one of the connection's `setting_options.freight_provider_account_id` values (test the connection to refresh them). When the account has exactly one, testing selects it. ShipStation can be connected more than once; a name already used by another connection is refused (409).", "body": { "mode": "raw", "raw": "{\n \"provider\": \"warp\",\n \"name\": \"Warp\",\n \"credentials\": {\n \"api_key\": \"wak_test_your_warp_api_key\"\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n }\n}", @@ -194606,7 +194606,7 @@ } ], "cookie": [], - "body": "{\n \"data\": {\n \"id\": 4,\n \"name\": \"Warp\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": null,\n \"moving_bookings\": null,\n \"created_at\": \"2026-11-21T14:40:02+00:00\"\n }\n}" + "body": "{\n \"data\": {\n \"id\": 4,\n \"name\": \"Warp\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"setting_options\": {},\n \"quote_blocked_reason\": null,\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": null,\n \"moving_bookings\": null,\n \"created_at\": \"2026-11-21T14:40:02+00:00\"\n }\n}" }, { "id": "e71eff3a-cd89-5615-92de-b263fa052003", @@ -194770,7 +194770,7 @@ } ] }, - "description": "Edit a freight connection. The provider can't change; send only what changes. A blank credential keeps the stored value; a new one is checked with the provider.\n\n**Body fields**\n- `provider` (optional on update): if sent it must be the connection's own provider, else 422 on `provider`. Credentials are always checked against the connection's provider.\n- `name` (optional, max 60).\n- `credentials` (required on create, object): the provider's credential fields from List Freight Providers; for Warp `credentials.api_key` (max 500). A key starting `wak_test_` is the sandbox: quotes and bookings are test data and nothing is charged. On update, a blank credential keeps the stored value.\n- `settings.carrier_scac` (optional, 2-4 letters): the SCAC to put on retailer ship notices when the provider is the carrier of record and does not send one (Warp).\n\nSecrets are never returned: `credentials.` gives only `is_set` and the last four characters (`hint`).\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`", + "description": "Edit a freight connection. The provider can't change; send only what changes. A blank credential keeps the stored value; a new one is checked with the provider.\n\n**Body fields**\n- `provider` (optional on update): if sent it must be the connection's own provider, else 422 on `provider`. Credentials are always checked against the connection's provider.\n- `name` (optional, max 60).\n- `credentials` (required on create, object): the provider's credential fields from List Freight Providers; for Warp `credentials.api_key` (max 500). A key starting `wak_test_` is the sandbox: quotes and bookings are test data and nothing is charged. On update, a blank credential keeps the stored value.\n- `settings.carrier_scac` (optional, 2-4 letters): the SCAC to put on retailer ship notices when the provider is the carrier of record and does not send one (Warp).\n\nSecrets are never returned: `credentials.` gives only `is_set` and the last four characters (`hint`).\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`\n\n**ShipStation** (`provider: shipstation`): `credentials.api_key` is the account's V2 API key. `settings.freight_provider_account_id` picks the Worldwide Express or Unishippers account to quote and book through; on edit it must be one of the connection's `setting_options.freight_provider_account_id` values (test the connection to refresh them). When the account has exactly one, testing selects it. ShipStation can be connected more than once; a name already used by another connection is refused (409).", "body": { "mode": "raw", "raw": "{\n \"name\": \"Warp (main account)\",\n \"credentials\": {\n \"api_key\": \"\"\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n }\n}", @@ -194846,7 +194846,7 @@ } ], "cookie": [], - "body": "{\n \"data\": {\n \"id\": 4,\n \"name\": \"Warp (main account)\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": null,\n \"moving_bookings\": null,\n \"created_at\": \"2026-11-02T17:20:31+00:00\"\n }\n}" + "body": "{\n \"data\": {\n \"id\": 4,\n \"name\": \"Warp (main account)\",\n \"provider\": \"warp\",\n \"provider_label\": \"Warp\",\n \"environment\": \"production\",\n \"credentials\": {\n \"api_key\": {\n \"is_set\": true,\n \"hint\": \"…9f3a\"\n }\n },\n \"settings\": {\n \"carrier_scac\": \"WRPF\"\n },\n \"setting_options\": {},\n \"quote_blocked_reason\": null,\n \"account_label\": \"Lumen & Wick Candle Co.\",\n \"account_warnings\": [],\n \"last_tested_at\": \"2026-11-21T14:40:02+00:00\",\n \"last_test_error\": null,\n \"recent_bookings\": null,\n \"moving_bookings\": null,\n \"created_at\": \"2026-11-02T17:20:31+00:00\"\n }\n}" }, { "id": "2d6c28f1-1ce7-53d6-87de-2f9548cc03d6", @@ -194957,7 +194957,7 @@ } ] }, - "description": "Check a connection's credentials with the provider. Returns the `environment` the key is for, the provider's `account_label`, and `warnings` that will stop a booking (such as no payment card on file), plus the refreshed connection.\n\nNo body.\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`" + "description": "Check a connection's credentials with the provider. Returns the `environment` the key is for, the provider's `account_label`, and `warnings` that will stop a booking (such as no payment card on file), plus the refreshed connection.\n\nNo body.\n\n**Errors.** `409` when the load is in a state that does not allow this action; the body carries `message` and `reasons` (every problem, one per entry). `422` when the freight provider rejected the request; `errors` maps each field the provider named to its messages (an invalid API key appears under `credentials`). `502` when the freight provider did not answer; `code` carries the provider's error code when it sent one.\n\nAuthentication: Requires Bearer token with the `integrations:write` scope.\n\n**Requires permission:** `integrations.update`\n\nFor ShipStation the test lists the account's freight provider accounts and saves them as the choices for `settings.freight_provider_account_id`. With none, the connection is saved with a warning and `quote_blocked_reason` explains that freight must first be connected in ShipStation (Freight → Connect your account)." }, "response": [ { diff --git a/frontend-vue-3/src/pages/integrations/constants.ts b/frontend-vue-3/src/pages/integrations/constants.ts index 5a295e46135..1f410c78de3 100644 --- a/frontend-vue-3/src/pages/integrations/constants.ts +++ b/frontend-vue-3/src/pages/integrations/constants.ts @@ -96,6 +96,7 @@ export const INTEGRATION_BRANDING: Record< "Repair claim form": { abbr: "Fm", bg: "#8E24AA", color: "#FFFFFF" }, // Freight (SKU-8948) — Modules/Freight, managed at /settings/freight "Warp Freight": { abbr: "W", bg: "#0A0A0A", color: "#00FF33" }, + "ShipStation Freight": { abbr: "SS", bg: "#3B8E3E", color: "#FFFFFF" }, } export const CATEGORY_CONFIG: Record< @@ -284,6 +285,7 @@ export function getInstanceRoute( "Repair claim form": `/settings/repairs/connectors?connector=${instanceId}`, // Freight (SKU-8948) — every freight account is managed on Settings → Freight. "Warp Freight": `/settings/freight?connection=${instanceId}`, + "ShipStation Freight": `/settings/freight?connection=${instanceId}`, } return routes[name] || "/integrations" } @@ -450,6 +452,7 @@ export function getConnectRoute(integrationName: string): ConnectRoute { "Repair claim form": "/settings/repairs/connectors?connect=form", // Freight (SKU-8948) — connected from Settings → Freight. "Warp Freight": "/settings/freight?connect=warp", + "ShipStation Freight": "/settings/freight?connect=shipstation", } return connectRoutes[integrationName] ?? null diff --git a/frontend-vue-3/src/pages/settings/freight/__tests__/freightSettings.spec.ts b/frontend-vue-3/src/pages/settings/freight/__tests__/freightSettings.spec.ts index e9c3548765a..641bb8b403d 100644 --- a/frontend-vue-3/src/pages/settings/freight/__tests__/freightSettings.spec.ts +++ b/frontend-vue-3/src/pages/settings/freight/__tests__/freightSettings.spec.ts @@ -7,14 +7,16 @@ import { disconnectConfirmText, environmentChip, environmentFromKey, + freightIntegrationName, missingCredentialFields, movingBookingsText, recentBookingsText, settingsFormFrom, + settingSelectItems, settingsSnapshot, testResultChip, } from "../freightSettings"; -import type { FreightProviderInfo } from "@/types/freight"; +import type { FreightConnection, FreightProviderInfo } from "@/types/freight"; const WARP: FreightProviderInfo = { key: "warp", @@ -51,6 +53,11 @@ describe("connection chips", () => { expect(environmentFromKey("")).toBeNull(); }); + it("reads a ShipStation API TEST_ key as sandbox; a plain V2 key stays unknown until tested (SKU-8974)", () => { + expect(environmentFromKey("TEST_abc123")).toBe("sandbox"); + expect(environmentFromKey("K4yAbCdEf")).toBeNull(); + }); + it("reports the last test: failed beats passed, never tested is grey", () => { expect(testResultChip({ last_tested_at: "2026-11-20T10:00:00Z", last_test_error: null }).label).toBe("Connection OK"); expect(testResultChip({ last_tested_at: "2026-11-20T10:00:00Z", last_test_error: "401 Invalid API key" })).toMatchObject({ label: "Test failed", color: "error" }); @@ -136,3 +143,49 @@ describe("freight defaults payload", () => { expect(FREIGHT_CLASSES).toContain("77.5"); }); }); + +describe("ShipStation provider settings (SKU-8974)", () => { + const connection = (settings: Record, options?: FreightConnection["setting_options"]): FreightConnection => ({ + id: 3, + name: "ShipStation — main", + provider: "shipstation", + provider_label: "ShipStation", + environment: "production", + credentials: { api_key: { is_set: true, hint: "…T4" } }, + settings, + setting_options: options, + account_label: null, + account_warnings: [], + last_tested_at: null, + last_test_error: null, + recent_bookings: null, + moving_bookings: null, + created_at: null, + }); + + it("names each provider's catalog integration, falling back to the label", () => { + expect(freightIntegrationName("warp")).toBe("Warp Freight"); + expect(freightIntegrationName("shipstation")).toBe("ShipStation Freight"); + expect(freightIntegrationName("other", "Other")).toBe("Other"); + }); + + it("offers the tested provider accounts as select choices", () => { + const options = [{ value: "se-4821", label: "Main (Worldwide Express)" }]; + expect(settingSelectItems(connection({ freight_provider_account_id: null }, { freight_provider_account_id: options }), "freight_provider_account_id")).toEqual(options); + }); + + it("keeps a saved account that is no longer listed, so the form does not silently clear it", () => { + expect(settingSelectItems(connection({ freight_provider_account_id: "se-9" }, { freight_provider_account_id: [] }), "freight_provider_account_id")).toEqual([{ value: "se-9", label: "se-9" }]); + }); + + it("has no choices before the connection exists", () => { + expect(settingSelectItems(null, "freight_provider_account_id")).toEqual([]); + }); + + it("sends a selected account as-is (only a SCAC is upper-cased)", () => { + const shipstation: FreightProviderInfo = { ...WARP, key: "shipstation", label: "ShipStation", setting_fields: [{ key: "freight_provider_account_id", label: "Freight provider account", help: "", type: "select" }] }; + const payload = buildConnectionPayload(shipstation, { name: null, credentials: { api_key: "abc" }, settings: { freight_provider_account_id: "se-4821" } }, true); + expect(payload.settings).toEqual({ freight_provider_account_id: "se-4821" }); + expect(payload.provider).toBe("shipstation"); + }); +}); diff --git a/frontend-vue-3/src/pages/settings/freight/components/FreightConnectionDrawer.vue b/frontend-vue-3/src/pages/settings/freight/components/FreightConnectionDrawer.vue index 0ee2b6444a9..b930153f9cc 100644 --- a/frontend-vue-3/src/pages/settings/freight/components/FreightConnectionDrawer.vue +++ b/frontend-vue-3/src/pages/settings/freight/components/FreightConnectionDrawer.vue @@ -115,7 +115,7 @@ :error-messages="fieldError('name')" data-testid="input-connection-name" /> -
Shown on rates and bookings, e.g. "Warp — main account".
+
Shown on rates and bookings, e.g. "{{ provider.label }} — main account".
@@ -125,7 +125,25 @@
+ (); -// CONSTANTS -const INTEGRATION_NAMES: Record = { warp: "Warp Freight" }; - // VARIABLES const { isMobile } = useResponsive(); const { notify } = useNotification(); @@ -244,7 +259,7 @@ const saving = ref(false); const testing = ref(false); // METHODS -const integrationNameFor = (key: string): string => INTEGRATION_NAMES[key] ?? props.provider?.label ?? key; +const integrationNameFor = (key: string): string => freightIntegrationName(key, props.provider?.label); const reset = (): void => { name.value = props.connection?.name ?? null; diff --git a/frontend-vue-3/src/pages/settings/freight/freightSettings.ts b/frontend-vue-3/src/pages/settings/freight/freightSettings.ts index 4492fa21f27..17d1eb5dc46 100644 --- a/frontend-vue-3/src/pages/settings/freight/freightSettings.ts +++ b/frontend-vue-3/src/pages/settings/freight/freightSettings.ts @@ -5,6 +5,7 @@ import type { FreightConnection, FreightConnectionPayload, FreightProviderInfo, + FreightSettingOption, FreightSettings, } from "@/types/freight"; @@ -118,6 +119,25 @@ export const disconnectConfirmText = (connection: Pick = { + warp: "Warp Freight", + shipstation: "ShipStation Freight", +}; + +export const freightIntegrationName = (providerKey: string, fallback?: string | null): string => + FREIGHT_INTEGRATION_NAMES[providerKey] ?? fallback ?? providerKey; + +/** Choices for a "select" setting: the connection's tested options, plus the saved value if it is no longer listed. */ +export const settingSelectItems = ( + connection: FreightConnection | null, + key: string +): FreightSettingOption[] => { + const options = connection?.setting_options?.[key] ?? []; + const saved = connection?.settings?.[key] ?? null; + return saved && !options.some((option) => option.value === saved) ? [...options, { value: saved, label: saved }] : options; +}; + /** * The Connect / Edit payload. A blank secret on edit keeps the stored value, so only typed * credentials are sent; setting fields are trimmed and a SCAC is upper-cased. diff --git a/frontend-vue-3/src/pages/settings/freight/index.vue b/frontend-vue-3/src/pages/settings/freight/index.vue index d4f96e3e88c..c4a2a7a75cd 100644 --- a/frontend-vue-3/src/pages/settings/freight/index.vue +++ b/frontend-vue-3/src/pages/settings/freight/index.vue @@ -127,6 +127,17 @@
{{ connection.last_test_error }}
+ + {{ connection.quote_blocked_reason }} +
{{ connections.length === 0 ? "Connect a freight account" : "All providers" }}
-
One account per provider. Quoting is free; a booking is billed by the provider to your account.
+
Quoting is free; a booking is billed by the provider to your account.
@@ -231,7 +242,7 @@
- + @@ -287,7 +298,7 @@ import IntegrationLogo from "@/pages/integrations/components/IntegrationLogo.vue import FreightConnectionDrawer from "./components/FreightConnectionDrawer.vue"; import FreightDefaultsCard from "./components/FreightDefaultsCard.vue"; import { deleteFreightConnection, listFreightConnections, listFreightProviders, testFreightConnection } from "@/pages/freight/service"; -import { disconnectConfirmText, environmentChip, movingBookingsText, recentBookingsText, testResultChip } from "./freightSettings"; +import { disconnectConfirmText, environmentChip, freightIntegrationName, movingBookingsText, recentBookingsText, testResultChip } from "./freightSettings"; import { useResponsive } from "@/composables/useResponsive"; import { useNotification } from "@/utils/composables/useNotification"; import { usePermissions } from "@/utils/composables/usePermissions"; @@ -299,8 +310,6 @@ definePage({ name: "Freight Settings", }); -// CONSTANTS -const INTEGRATION_NAMES: Record = { warp: "Warp Freight" }; const route = useRoute(); const router = useRouter(); const { isMobile } = useResponsive(); @@ -318,7 +327,7 @@ const loadError = ref(null); const busy = ref>({}); // METHODS -const integrationNameFor = (key: string): string => INTEGRATION_NAMES[key] ?? key; +const integrationNameFor = (key: string): string => freightIntegrationName(key); const providerFor = (key: string): FreightProviderInfo | undefined => providers.value.find((provider) => provider.key === key); diff --git a/frontend-vue-3/src/test/integrations/freightCatalog.spec.ts b/frontend-vue-3/src/test/integrations/freightCatalog.spec.ts index e16c537c0da..c05c92ece6f 100644 --- a/frontend-vue-3/src/test/integrations/freightCatalog.spec.ts +++ b/frontend-vue-3/src/test/integrations/freightCatalog.spec.ts @@ -11,4 +11,9 @@ describe("Warp Freight in the integrations catalog (SKU-8948)", () => { expect(getConnectRoute("Warp Freight")).toBe("/settings/freight?connect=warp"); expect(getInstanceRoute({ name: "Warp Freight" }, 5)).toBe("/settings/freight?connection=5"); }); + + it("connects and opens ShipStation Freight on Settings → Freight (SKU-8974)", () => { + expect(getConnectRoute("ShipStation Freight")).toBe("/settings/freight?connect=shipstation"); + expect(getInstanceRoute({ name: "ShipStation Freight" }, 7)).toBe("/settings/freight?connection=7"); + }); }); diff --git a/frontend-vue-3/src/types/freight.ts b/frontend-vue-3/src/types/freight.ts index 8150d657af4..323fc1327eb 100644 --- a/frontend-vue-3/src/types/freight.ts +++ b/frontend-vue-3/src/types/freight.ts @@ -270,6 +270,13 @@ export interface FreightProviderField { help: string; placeholder?: string | null; max?: number | null; + /** "select" settings take their choices from the connection's `setting_options` (e.g. ShipStation's freight provider accounts). */ + type?: "text" | "select"; +} + +export interface FreightSettingOption { + value: string; + label: string; } export interface FreightProviderInfo { @@ -279,6 +286,8 @@ export interface FreightProviderInfo { website_url: string; credential_fields: FreightProviderField[]; setting_fields: FreightProviderField[]; + /** ShipStation allows several accounts (SKU-8974); Warp is one per tenant. */ + allows_multiple_connections?: boolean; capabilities: { modes: FreightRateMode[]; pickup_accessorials: FreightAccessorial[]; @@ -301,8 +310,12 @@ export interface FreightConnection { environment: "sandbox" | "production"; credentials: Record; settings: Record; + /** Choices for "select" setting fields, keyed by field; filled when the connection is tested. */ + setting_options?: Record; account_label: string | null; account_warnings: string[]; + /** Why this connection can't quote yet (e.g. no ShipStation freight provider account selected). */ + quote_blocked_reason?: string | null; last_tested_at: string | null; last_test_error: string | null; recent_bookings: number | null; diff --git a/resources/mcp/api-index.json b/resources/mcp/api-index.json index 4552fa4c34a..4720929726e 100644 --- a/resources/mcp/api-index.json +++ b/resources/mcp/api-index.json @@ -1,4 +1,4 @@ -{"version":1,"inputs_hash":"ff5c14c271972daa79fc81fb2a016f04f777d56d0c7cafa502513e5bfdc9960e","pages":{"get /api/assemblies/{}":"/v2/inventory/assemblies/{id}","get /api/customers/{}":"/v2/crm/customers/{id}","get /api/fifo-layers/{}":"/v2/inventory/fifo-layers/{id}","get /api/inbound-shipments/{}":"/v2/inbound-shipments/{id}","get /api/inventory-adjustments/{}":"/v2/inventory/inventory-adjustments/{id}","get /api/manufacturing-orders/{}":"/v2/manufacturing/orders/{id}","get /api/products/{}":"/v2/products/{id}","get /api/purchase-orders/{}":"/v2/orders/purchase-orders/{id}","get /api/rmas/{}":"/v2/rma/{id}","get /api/sales-credits/{}":"/v2/inventory/sales-credits/{id}","get /api/sales-orders/{}":"/v2/orders/sales-orders/{id}","get /api/stock-takes/{}":"/v2/inventory/stock-takes/{id}","get /api/suppliers/{}":"/v2/crm/suppliers/{id}","get /api/vendor-credits/{}":"/v2/purchases/vendor-credits/{id}","get /api/warehouse-transfers/{}":"/v2/inventory/warehouse-transfers/{id}","get /api/warehouses/{}":"/v2/crm/warehouses/{id}"},"endpoints":[ +{"version":1,"inputs_hash":"e46eec02b176508b527d5e7ed0d6bee169e08e931b3b59a464b653dc6141528d","pages":{"get /api/assemblies/{}":"/v2/inventory/assemblies/{id}","get /api/customers/{}":"/v2/crm/customers/{id}","get /api/fifo-layers/{}":"/v2/inventory/fifo-layers/{id}","get /api/inbound-shipments/{}":"/v2/inbound-shipments/{id}","get /api/inventory-adjustments/{}":"/v2/inventory/inventory-adjustments/{id}","get /api/manufacturing-orders/{}":"/v2/manufacturing/orders/{id}","get /api/products/{}":"/v2/products/{id}","get /api/purchase-orders/{}":"/v2/orders/purchase-orders/{id}","get /api/rmas/{}":"/v2/rma/{id}","get /api/sales-credits/{}":"/v2/inventory/sales-credits/{id}","get /api/sales-orders/{}":"/v2/orders/sales-orders/{id}","get /api/stock-takes/{}":"/v2/inventory/stock-takes/{id}","get /api/suppliers/{}":"/v2/crm/suppliers/{id}","get /api/vendor-credits/{}":"/v2/purchases/vendor-credits/{id}","get /api/warehouse-transfers/{}":"/v2/inventory/warehouse-transfers/{id}","get /api/warehouses/{}":"/v2/crm/warehouses/{id}"},"endpoints":[ {"endpoint_id":"delete.3pl.tokens.{integrationInstance}","method":"DELETE","path":"/api/3pl/tokens/{integrationInstance}","summary":"Delete 3pl tokens","kind":"session-only"}, {"endpoint_id":"delete.account-invitations.{invitation}","method":"DELETE","path":"/api/account-invitations/{invitation}","summary":"Delete account invitations","kind":"session-only"}, {"endpoint_id":"delete.accounting.bill-sync.rules.{rule}","method":"DELETE","path":"/api/accounting/bill-sync/rules/{rule}","summary":"Delete Bill Sync Supplier Rule","description":"Delete a supplier rule. The supplier follows the connection's expense bill mode again. Nothing already sent or linked changes.\nAuthentication: Requires Bearer token. Scope: `accounting` (read/write). The user must hold the **Manage bill sync** permission (`ac…","kind":"scoped","scope":"accounting:write","permissions":["accounting.bill_sync"],"path_params":[{"name":"rule","description":"Supplier rule ID"}],"documented":true}, diff --git a/tests/Feature/IntegrationSyncSurfaceTest.php b/tests/Feature/IntegrationSyncSurfaceTest.php index f1f82d87366..8bfdbadb26a 100644 --- a/tests/Feature/IntegrationSyncSurfaceTest.php +++ b/tests/Feature/IntegrationSyncSurfaceTest.php @@ -49,7 +49,7 @@ class IntegrationSyncSurfaceTest extends TestCase // API Shipping Provider is where every D3 connection lives now; the partner polls it, nothing syncs. // A repair claim form (SKU-8604) only receives webhook posts; there is no remote to poll. // A freight account (SKU-8948) only quotes and books on demand; tracking is polled per load, not an account sync. - [Integration::NAME_SKU_IO, Integration::NAME_D3, Integration::NAME_API_SHIPPING_PROVIDER, Integration::NAME_EASYPOST, Integration::NAME_PAYPAL, Integration::NAME_MERCURY, Integration::NAME_REPAIR_CLAIM_FORM, Integration::NAME_WARP_FREIGHT], + [Integration::NAME_SKU_IO, Integration::NAME_D3, Integration::NAME_API_SHIPPING_PROVIDER, Integration::NAME_EASYPOST, Integration::NAME_PAYPAL, Integration::NAME_MERCURY, Integration::NAME_REPAIR_CLAIM_FORM, Integration::NAME_WARP_FREIGHT, Integration::NAME_SHIPSTATION_FREIGHT], Integration::NAMES_WITHOUT_SYNC, 'the no-sync list is deliberately tiny; adding to it hides a real sync state' );