Skip to main content

Building a Custom Transport Management System for Complex Logistics

How DreamWebCrafts designed a custom transport management system around controlled workflows, role privacy, and configurable adapters.

Category: Web Development | By DreamWebCrafts Engineering | Published Aug 31, 2026

Logistics teams rarely struggle because they lack operational data. The harder engineering challenge is that bookings, documents, warehouse activity, trucking dispatches, financial ledgers, and customer notifications live in disconnected silos. At DreamWebCrafts, we architected a custom transport management system (TMS) that turns fragmented hand-offs into deterministic, role-aware workflows backed by strict state machines, configurable provider adapters, and encrypted evidence trails.

This is an anonymised architectural case study. Client identity, brands, routes, shipment records, operational volumes, commercial terms, credentials, screenshots, and partner details are intentionally excluded.

What to Choose: Model complex logistics platforms in PHP 8.3 (backed Enums plus atomic database row locking) and Laravel 13 modular queues paired with a Vue 3 + TypeScript control tower UI—replacing unconstrained status string edits with enforced transition graphs, adapter contracts, minor-unit financial ledgers, and record-level authorization scopes.

1. Controlled Workflow State Machines Instead of Free-Form Status Edits

Operational visibility only works when dispatchers, warehouse supervisors, finance officers, and customer service teams trust what a status badge actually guarantees. Allowing generic PATCH endpoints to overwrite a shipment string directly—for example jumping straight from draft to delivered—corrupts billing triggers, strands unverified compliance paperwork, and creates silent audit gaps when two operators edit the same record concurrently.

Shipment, Trucking & Warehouse Lifecycle Alignment

Instead of scattering status checks across controllers, encode every operational domain as an explicit transition graph enforced by a backed PHP 8.3 Enum and transactional service boundary:

  • Shipment Operations: Governed progression from draft → confirmed → documentation → customs_review → cleared → in_transit → delivered, gating downstream stages behind document completeness and compliance verification checks.
  • Trucking Dispatch: Connects quotation acceptance to booking creation, carrier assignment, pickup check-in, milestone updates, proof of delivery (POD) capture, minor-unit integer invoicing, and operational close-out.
  • Warehouse Handling: Coordinates dock appointment slots, physical receiving inspection, hold tagging, bin put-away locations, outbound release verification, and storage charge triggers along one chronological timeline.
PHP 8.3app/Modules/Logistics/Enums/ShipmentStage.phpCopy
<?php

declare(strict_types=1);

namespace App\Modules\Logistics\Enums;

enum ShipmentStage: string
{
    case Draft = 'draft';
    case Confirmed = 'confirmed';
    case Documentation = 'documentation';
    case CustomsReview = 'customs_review';
    case Cleared = 'cleared';
    case InTransit = 'in_transit';
    case Delivered = 'delivered';

    /** @return list<self> */
    public function allowedNext(): array
    {
        return match ($this) {
            self::Draft => [self::Confirmed],
            self::Confirmed => [self::Documentation],
            self::Documentation => [self::CustomsReview],
            self::CustomsReview => [self::Cleared],
            self::Cleared => [self::InTransit],
            self::InTransit => [self::Delivered],
            self::Delivered => [],
        };
    }

    public function canTransitionTo(self $target): bool
    {
        return in_array($target, $this->allowedNext(), true);
    }
}

To protect state invariants under concurrent operator clicks or arriving carrier webhooks, wrap stage transitions inside DB::transaction() with pessimistic row locking (lockForUpdate()). Every accepted transition writes an append-only event record containing the actor ID, previous stage, next stage, UTC timestamp, and optional evidence reference—giving supervisors a verifiable chain of custody whenever an exception requires investigation.

PHP 8.3app/Modules/Logistics/Services/TransitionShipmentStage.phpCopy
<?php

declare(strict_types=1);

namespace App\Modules\Logistics\Services;

use App\Modules\Logistics\Enums\ShipmentStage;
use App\Modules\Logistics\Models\TmsShipment;
use DomainException;
use Illuminate\Support\Facades\DB;

final class TransitionShipmentStage
{
    public function advance(int $shipmentId, int $tenantId, ShipmentStage $target, int $actorId, ?string $note = null): TmsShipment
    {
        return DB::transaction(static function () use ($shipmentId, $tenantId, $target, $actorId, $note): TmsShipment {
            /** @var TmsShipment|null $shipment */
            $shipment = TmsShipment::query()
                ->where('tenant_id', $tenantId)
                ->lockForUpdate()
                ->find($shipmentId);

            if ($shipment === null) {
                throw new DomainException('Shipment not found within tenant scope.');
            }

            if ($shipment->current_stage === $target) {
                return $shipment; // Idempotent retry guard
            }

            if (! $shipment->current_stage->canTransitionTo($target)) {
                throw new DomainException("Blocked transition from {$shipment->current_stage->value} to {$target->value}.");
            }

            $fromStage = $shipment->current_stage;
            $shipment->forceFill(['current_stage' => $target])->save();

            DB::table('tms_stage_events')->insert([
                'tenant_id' => $tenantId,
                'shipment_id' => $shipment->id,
                'from_stage' => $fromStage->value,
                'to_stage' => $target->value,
                'actor_id' => $actorId,
                'note' => $note,
                'occurred_at_utc' => now()->utc(),
            ]);

            return $shipment;
        });
    }
}

2. Configurable Integration Adapters With Idempotent Event Ingestion

Logistics platforms routinely exchange milestone updates with external transport, storage, routing, messaging, and accounting tools. Hardcoding one vendor's webhook payload or status vocabulary directly inside core shipment models creates brittle coupling whenever a partner updates an API version or an individual deployment connects a different regional carrier.

Decoupling Core Domain Models From External Carrier Payloads

Instead, bind per-deployment integrations behind typed PHP adapter interfaces. Configured providers activate only after explicit deployment onboarding and encrypted credential storage. When a webhook or scheduled poll delivers an external event, the adapter normalizes provider-specific codes into an internal timeline contract and enforces a composite unique index on (tenant_id, provider_key, external_event_id) via insertOrIgnore() so duplicate carrier retries never double-trigger customer alerts or duplicate milestone rows.

Routing outbound connector dispatches and inbound webhook parsing onto dedicated asynchronous queues protects core booking responsiveness. If an external messaging or carrier endpoint slows down temporarily, queue workers apply bounded exponential backoff and route persistent failures to a dead-letter review queue rather than blocking dispatchers saving booking updates in the control tower UI. Every inbound webhook handler also verifies cryptographic signatures and checks event timestamps before queuing adapter normalization, preventing stale delayed deliveries from regressing a shipment's current lifecycle stage.

PHP 8.3app/Modules/Logistics/Contracts/TrackingAdapterContract.phpCopy
<?php

declare(strict_types=1);

namespace App\Modules\Logistics\Contracts;

interface TrackingAdapterContract
{
    /**
     * Normalize an external carrier webhook or poll payload into a deduplicated timeline event.
     *
     * @param  array<string, mixed>  $rawPayload
     * @return array{external_event_id: string, occurred_at_utc: string, milestone_code: string, summary: string}
     */
    public function normalizeEvent(array $rawPayload): array;

    public function providerKey(): string;
}
A privacy-safe architectural view of configurable operational connectors and normalized event ingestion pipelines.

3. Sub-10ms SLA & Exception Monitoring Queries in SQL

Operations managers rely on a control-tower exception queue highlighting stalled milestones, missing POD uploads, or overdue customs hand-offs across active shipments. Running unindexed LIKE filters or joining five tables in memory quickly stalls control-tower dashboards once historical records grow.

Composite Indexing Strategy for High-Volume Dispatch Queues

Align indexes directly with the primary filter predicate of the exception dashboard: scope first by tenant_id, filter out terminal stages via current_stage, and range-scan expected_milestone_at in UTC. Storing all operational timestamps normalized in UTC avoids daylight-saving drift when shipments cross time zones, while keeping SLA exception queries consistently under 10 milliseconds.

Equally important in operational design is separating actionable delays from expected hold periods. Pairing milestone timestamps with explicit hold reason codes lets control-tower filters exclude planned inspection holds from red-alert escalation queues—preventing alert fatigue so dispatch supervisors focus immediately on genuinely overdue hand-offs.

SQLdatabase/queries/tms_sla_exceptions.sqlCopy
-- Supporting index: CREATE INDEX idx_tms_sla_scan ON tms_shipments (tenant_id, current_stage, expected_milestone_at);

SELECT
    s.id,
    s.reference_code,
    s.current_stage,
    s.expected_milestone_at,
    TIMESTAMPDIFF(HOUR, s.expected_milestone_at, UTC_TIMESTAMP()) AS overdue_hours
FROM tms_shipments s
WHERE s.tenant_id = 12
  AND s.current_stage NOT IN ('draft', 'delivered')
  AND s.expected_milestone_at < UTC_TIMESTAMP()
ORDER BY overdue_hours DESC
LIMIT 50;
Architectural Pitfall in Custom TMS Builds: Never allow unauthenticated webhook retries to force backward stage transitions out of order, and never compute freight tariffs, detention charges, or warehouse handling fees in floating-point SQL columns. Minor rounding errors across multi-leg invoices break ledger reconciliation, while unchecked webhook replays can re-open completed dispatches or send duplicate customer alerts.

4. Security, Privacy & Role-Aware Data Boundaries

Multi-party logistics operations bring together internal dispatchers, warehouse supervisors, finance reconcilers, compliance reviewers, and external client portal users inside one shared workspace. Rendering a single monolithic shipment JSON payload for every role leaks sensitive supplier rate cards, internal exception notes, or decrypted partner credentials into browser network tabs.

Operational Role Permitted Control-Tower Actions Restricted / Redacted Fields Storage & Serializer Guard
Operations & Dispatch Advance booking, carrier dispatch, and milestone updates; upload POD documents Decrypted external connector API secrets and internal margin-only ledgers Laravel policy scope plus encrypted model casts on connector config
Warehouse Supervisor Confirm dock arrival, log inspection holds, assign put-away bins, authorize release Client invoice totals, carrier settlement pricing, and admin tenant settings Dock-scoped API resource projection omitting financial attributes
Finance Team Reconcile chargeable line items, minor-unit invoices, and settlement status External provider credentials and raw warehouse dock override logs Integer minor-unit casts plus strict role middleware on billing routes
Client Portal User Inspect sanitized timeline milestones, approved POD links, and customer invoices Internal operator notes, supplier rate cards, cost margins, and draft filings Dedicated ClientShipmentResource allowlisting public fields only

Encrypting Secrets While Preserving Append-Only Evidence

Selected sensitive fields—including configured external connector secrets and designated compliance evidence payloads—are protected with application-level encryption via Laravel casts so raw database dumps never expose usable credentials. At the same time, integrity-sensitive transition and approval records preserve append-only audit trails with immutable timestamps and actor metadata, ensuring unauthorized edits or unexpected state overrides remain detectable during operational reviews.

Financial clarity follows the same boundary discipline. Chargeable trucking legs, warehouse storage triggers, and invoice adjustments store exact integer minor units rather than floating-point decimals, tying every billing line back to verified stage-transition timestamps and authorized operator actions so finance reconcilers can resolve billing questions without manual spreadsheet archaeology.

Security controls, role-based serializer projections, and approval gates belong inside the domain workflow rather than bolted on afterward.

5. Export-Filing Preparation Needs Gates, Not Blind Buttons

Export-related documentation workflows carry strict regulatory sensitivity. A naive single-click "Submit Filing" button that marks a shipment cleared in the local database before verifying supporting documents, approved deployment credentials, or genuine external acknowledgement creates serious compliance risk for operators.

Separating Checklist Readiness From Verified Submission State

The TMS architecture separates preparation from external execution. Inside the application, teams run structured field validation checklists, assemble document bundles, record pre-submission evidence reviews, and surface clear readiness indicators inside the Vue 3 + TypeScript control tower. Each checklist highlights missing commercial invoice weights, unverified consignment references, or unsigned packing declarations early so operators resolve issues before dispatching external hand-offs. Actual external filing submission stays intentionally gated behind explicit per-deployment onboarding, verified encrypted credentials, and verifiable external acknowledgement paths—preventing a generic UI action from falsely implying regulatory clearance.

TypeScriptresources/js/composables/useShipmentTimeline.tsCopy
export interface TimelineCheckpoint {
  id: number;
  stage: string;
  summary: string;
  occurredAtUtc: string;
  verifiedEvidence: boolean;
  externalAckRef: string | null;
}

export function hasPendingComplianceGate(checkpoints: TimelineCheckpoint[]): boolean {
  return checkpoints.some(
    (item) => item.stage === 'customs_review' && (!item.verifiedEvidence || !item.externalAckRef),
  );
}

export function canRenderClientDownload(checkpoint: TimelineCheckpoint): boolean {
  return checkpoint.verifiedEvidence && checkpoint.stage !== 'draft';
}
Where to Structure TMS Modules: Isolate workflow transition Enums in app/Modules/Logistics/Enums/, row-locked stage services in app/Modules/Logistics/Services/, external webhook deduplication keys (tenant_id, provider_key, external_event_id) in unique SQL indexes, client-facing API projections inside dedicated resource transformers, and provider secrets behind Laravel's 'encrypted' model cast. How to Take These Architecture Lessons Into Your Own Logistics Build:
  1. Map every operational hand-off across bookings, warehouse receiving, trucking dispatch, finance billing, and customer visibility before designing screens.
  2. Encode lifecycle stages as strict backed Enums with prerequisite guards and row-level locking instead of unconstrained status dropdowns.
  3. Isolate carrier, storage, and messaging connectors behind typed adapter contracts with database-enforced webhook deduplication.
  4. Enforce role-scoped API serializers so client portals never receive internal operator notes, supplier rate cards, or margin data.
  5. Need a tailored TMS, fleet portal, or ERP workflow layer? Talk to the DreamWebCrafts engineering team or book a discovery session.

Related Engineering Articles