Skip to content

Real-World Examples

Production-ready query patterns for common logistics workflows.

E-commerce Order Routing

Complete example of routing orders to optimal warehouses based on location, capacity, and performance.

Scenario

An e-commerce platform needs to route incoming orders to the best warehouse for fulfillment, considering:

  • Geographic proximity to customer
  • Warehouse capacity and inventory
  • Service provider performance history
  • Cost efficiency

Implementation

typescript
import { DeClient } from '@dedot/sdk'

interface Order {
  id: string
  customerId: string
  items: Array<{
    sku: string
    quantity: number
    weight: number
    requiresColdChain?: boolean
  }>
  deliveryAddress: {
    lat: number
    lng: number
    city: string
    country: string
    zip: string
  }
  priority: 'STANDARD' | 'EXPRESS' | 'SAME_DAY'
}

class OrderRoutingService {
  private client: DeClient
  
  constructor(apiKey: string, workspaceId: string) {
    this.client = new DeClient({ apiKey, workspace: workspaceId })
  }
  
  async routeOrder(order: Order) {
    console.log(`Routing order ${order.id}...`)
    
    // Step 1: Build requirements from order
    const requirements = this.buildRequirements(order)
    
    // Step 2: Match order to optimal warehouse
    const match = await this.client.realm.queries.matching.match({
      serviceTypes: ['WAREHOUSE'],
      delivery: {
        country: order.deliveryAddress.country,
        city: order.deliveryAddress.city,
        coordinates: [order.deliveryAddress.lat, order.deliveryAddress.lng]
      },
      items: order.items,
      requirements,
      strategy: this.getStrategy(order.priority)
    })
    
    if (match.recommendations.length === 0) {
      throw new Error('No suitable warehouse found')
    }
    
    const warehouse = match.recommendations[0]
    
    // Step 3: Verify capacity
    const hasCapacity = await this.verifyCapacity(warehouse.service, order)
    
    if (!hasCapacity) {
      console.log('Primary warehouse lacks capacity, trying next option...')
      // Try second-best warehouse
      if (match.recommendations.length > 1) {
        return this.assignWarehouse(match.recommendations[1], order)
      }
      throw new Error('No warehouse with sufficient capacity')
    }
    
    // Step 4: Assign warehouse
    return this.assignWarehouse(warehouse, order)
  }
  
  private buildRequirements(order: Order): string[] {
    const requirements: string[] = []
    
    // Priority-based requirements
    if (order.priority === 'SAME_DAY') {
      requirements.push('SAME_DAY_DELIVERY')
    } else if (order.priority === 'EXPRESS') {
      requirements.push('EXPRESS_SHIPPING')
    }
    
    // Item-based requirements
    const hasColdChain = order.items.some(item => item.requiresColdChain)
    if (hasColdChain) {
      requirements.push('COLD_CHAIN')
    }
    
    return requirements
  }
  
  private getStrategy(priority: Order['priority']) {
    switch (priority) {
      case 'SAME_DAY':
        return 'SPEED_OPTIMIZED'
      case 'EXPRESS':
        return 'BALANCED'
      case 'STANDARD':
        return 'COST_OPTIMIZED'
    }
  }
  
  private async verifyCapacity(warehouse: any, order: Order) {
    try {
      const capacity = await this.client.realm.queries.capacity.query({
        lsp: warehouse.lsp,
        serviceId: warehouse.serviceId,
        capacityType: 'STORAGE_SLOTS'
      })
      
      const requiredSlots = order.items.reduce((sum, item) => sum + item.quantity, 0)
      return capacity.available >= requiredSlots
    } catch (error) {
      console.warn('Capacity check failed:', error)
      return true // Assume capacity if check fails
    }
  }
  
  private async assignWarehouse(recommendation: any, order: Order) {
    console.log(`✅ Assigned to: ${recommendation.service.name}`)
    console.log(`   Score: ${recommendation.scores.overall}/100`)
    console.log(`   Distance: ${recommendation.service.distance}km`)
    
    return {
      orderId: order.id,
      warehouseId: recommendation.service.serviceId,
      warehouseName: recommendation.service.name,
      warehouseLsp: recommendation.service.lsp,
      scores: recommendation.scores,
      distance: recommendation.service.distance
    }
  }
}

// Usage
const router = new OrderRoutingService(
  process.env.DE_API_KEY!,
  process.env.DE_WORKSPACE_ID!
)

const order: Order = {
  id: 'ORD-12345',
  customerId: 'CUST-789',
  items: [
    { sku: 'WIDGET-001', quantity: 5, weight: 2.5 },
    { sku: 'GADGET-002', quantity: 3, weight: 1.0, requiresColdChain: true }
  ],
  deliveryAddress: {
    lat: 40.7128,
    lng: -74.0060,
    city: 'New York',
    country: 'US',
    zip: '10001'
  },
  priority: 'EXPRESS'
}

const assignment = await router.routeOrder(order)
console.log('Order routed:', assignment)

Output:

Routing order ORD-12345...
✅ Assigned to: Manhattan Fulfillment Center
   Score: 92/100
   Distance: 2.5km

Cold Chain Monitoring

Monitor cold chain warehouse performance and automatically flag underperforming facilities.

Scenario

A pharmaceutical distributor needs to monitor all cold chain warehouses and ensure they maintain high performance standards for temperature-sensitive products.

Implementation

typescript
class ColdChainMonitor {
  private client: DeClient
  private performanceThreshold = 95 // 95% on-time delivery
  private scoreThreshold = 85       // Overall score threshold
  
  constructor(apiKey: string, workspaceId: string) {
    this.client = new DeClient({ apiKey, workspace: workspaceId })
  }
  
  async monitorAllColdChainFacilities() {
    console.log('🔍 Scanning cold chain facilities...\n')
    
    // Step 1: Discover all cold chain warehouses
    const result = await this.client.realm.queries.discovery.advancedDiscover({
      serviceType: 'WAREHOUSE',
      capabilities: {
        environmental: {
          temperatureControlled: true
        }
      }
    })
    
    console.log(`Found ${result.total} cold chain warehouses\n`)
    
    // Step 2: Check performance for each warehouse
    const reports = await Promise.all(
      result.services.map(warehouse => this.checkWarehousePerformance(warehouse))
    )
    
    // Step 3: Identify underperforming warehouses
    const underperforming = reports.filter(r => !r.meetsStandards)
    
    if (underperforming.length > 0) {
      console.log(`\n⚠️  ${underperforming.length} warehouse(s) need attention:\n`)
      underperforming.forEach(report => {
        console.log(`   ${report.name}:`)
        console.log(`   - On-time rate: ${report.performance.onTimeRate}%`)
        console.log(`   - Overall score: ${report.performance.score}`)
        console.log(`   - Status: ${report.status}\n`)
      })
    } else {
      console.log('\n✅ All warehouses meet performance standards')
    }
    
    return {
      total: reports.length,
      passing: reports.filter(r => r.meetsStandards).length,
      failing: underperforming.length,
      reports
    }
  }
  
  private async checkWarehousePerformance(warehouse: any) {
    try {
      const performance = await this.client.realm.queries.performance.get({
        lsp: warehouse.lsp,
        serviceId: warehouse.serviceId
      })
      
      const onTimeRate = performance.onTimeDeliveryRate * 100
      const score = performance.overallScore
      
      const meetsStandards = 
        onTimeRate >= this.performanceThreshold &&
        score >= this.scoreThreshold
      
      console.log(`${meetsStandards ? '✅' : '❌'} ${warehouse.name}`)
      console.log(`   On-time: ${onTimeRate.toFixed(1)}% | Score: ${score}`)
      
      return {
        name: warehouse.name,
        lsp: warehouse.lsp,
        serviceId: warehouse.serviceId,
        performance: {
          onTimeRate: onTimeRate.toFixed(1),
          accuracy: (performance.orderAccuracy * 100).toFixed(1),
          score
        },
        meetsStandards,
        status: this.getStatus(onTimeRate, score)
      }
    } catch (error) {
      console.log(`⚠️  ${warehouse.name} - No performance data`)
      return {
        name: warehouse.name,
        lsp: warehouse.lsp,
        serviceId: warehouse.serviceId,
        performance: null,
        meetsStandards: false,
        status: 'NO_DATA'
      }
    }
  }
  
  private getStatus(onTimeRate: number, score: number) {
    if (onTimeRate >= 95 && score >= 90) return 'EXCELLENT'
    if (onTimeRate >= 90 && score >= 85) return 'GOOD'
    if (onTimeRate >= 80 && score >= 70) return 'NEEDS_IMPROVEMENT'
    return 'CRITICAL'
  }
}

// Usage
const monitor = new ColdChainMonitor(
  process.env.DE_API_KEY!,
  process.env.DE_WORKSPACE_ID!
)

const report = await monitor.monitorAllColdChainFacilities()
console.log('\n📊 Summary:', {
  total: report.total,
  passing: report.passing,
  failing: report.failing
})

Output:

🔍 Scanning cold chain facilities...

Found 5 cold chain warehouses

✅ Manhattan Cold Storage
   On-time: 97.5% | Score: 93
✅ Brooklyn Refrigerated Warehouse
   On-time: 96.2% | Score: 91
❌ Queens Distribution Center
   On-time: 88.0% | Score: 78
✅ Bronx Cold Chain Hub
   On-time: 98.1% | Score: 95
❌ Staten Island Frozen Storage
   On-time: 82.5% | Score: 72

⚠️  2 warehouse(s) need attention:

   Queens Distribution Center:
   - On-time rate: 88.0%
   - Overall score: 78
   - Status: NEEDS_IMPROVEMENT

   Staten Island Frozen Storage:
   - On-time rate: 82.5%
   - Overall score: 72
   - Status: NEEDS_IMPROVEMENT

📊 Summary: { total: 5, passing: 3, failing: 2 }

Multi-Carrier Cost Comparison

Compare delivery costs across multiple carriers to optimize shipping expenses.

Scenario

An online retailer wants to compare delivery costs from different carriers before assigning shipments.

Implementation

typescript
class CarrierCostOptimizer {
  private client: DeClient
  
  constructor(apiKey: string, workspaceId: string) {
    this.client = new DeClient({ apiKey, workspace: workspaceId })
  }
  
  async findCheapestCarrier(shipment: {
    origin: { lat: number; lng: number; city: string }
    destination: { lat: number; lng: number; city: string; country: string }
    items: Array<{ sku: string; quantity: number; weight: number }>
    serviceLevel: 'STANDARD' | 'EXPRESS' | 'SAME_DAY'
  }) {
    console.log('🚚 Finding cheapest carrier...\n')
    
    // Step 1: Find available carriers
    const carriers = await this.client.realm.queries.discovery.discover({
      serviceType: 'CARRIER',
      location: {
        coordinates: [shipment.origin.lat, shipment.origin.lng],
        maxDistance: 100
      },
      filters: {
        status: 'ACTIVE',
        serviceLevel: shipment.serviceLevel
      }
    })
    
    if (carriers.services.length === 0) {
      throw new Error('No carriers available for this route')
    }
    
    console.log(`Found ${carriers.total} available carriers\n`)
    
    // Step 2: Get cost estimates for each carrier
    const estimates = await Promise.all(
      carriers.services.map(async carrier => {
        try {
          const pricing = await this.client.realm.queries.pricing.estimate({
            lsp: carrier.lsp,
            serviceId: carrier.serviceId,
            serviceType: 'CARRIER',
            orderContext: {
              items: shipment.items,
              deliveryLocation: {
                country: shipment.destination.country,
                city: shipment.destination.city
              }
            }
          })
          
          // Get performance score
          const performance = await this.client.realm.queries.performance.get({
            lsp: carrier.lsp,
            serviceId: carrier.serviceId
          }).catch(() => null)
          
          return {
            carrier: carrier.name,
            lsp: carrier.lsp,
            serviceId: carrier.serviceId,
            cost: pricing.totalCost,
            currency: pricing.currency,
            breakdown: pricing.breakdown,
            performance: performance?.overallScore || null,
            distance: carrier.distance
          }
        } catch (error) {
          console.warn(`Failed to get estimate for ${carrier.name}`)
          return null
        }
      })
    )
    
    // Filter out failed estimates
    const validEstimates = estimates.filter(e => e !== null)
    
    if (validEstimates.length === 0) {
      throw new Error('Could not get estimates from any carrier')
    }
    
    // Sort by cost (ascending)
    validEstimates.sort((a, b) => a!.cost - b!.cost)
    
    // Display results
    console.log('💰 Cost Comparison:\n')
    validEstimates.forEach((estimate, index) => {
      const marker = index === 0 ? '🏆' : '  '
      console.log(`${marker} ${estimate!.carrier}`)
      console.log(`   Total: $${estimate!.cost.toFixed(2)}`)
      console.log(`   Base: $${estimate!.breakdown.baseRate.toFixed(2)} + Fees: $${estimate!.breakdown.fees.toFixed(2)}`)
      if (estimate!.performance) {
        console.log(`   Performance: ${estimate!.performance}/100`)
      }
      console.log(`   Distance: ${estimate!.distance}km\n`)
    })
    
    const cheapest = validEstimates[0]!
    const savings = validEstimates[validEstimates.length - 1]!.cost - cheapest.cost
    
    console.log(`✅ Best option: ${cheapest.carrier}`)
    console.log(`💵 Potential savings: $${savings.toFixed(2)}\n`)
    
    return {
      recommended: cheapest,
      alternatives: validEstimates.slice(1),
      savings
    }
  }
}

// Usage
const optimizer = new CarrierCostOptimizer(
  process.env.DE_API_KEY!,
  process.env.DE_WORKSPACE_ID!
)

const result = await optimizer.findCheapestCarrier({
  origin: {
    lat: 40.7128,
    lng: -74.0060,
    city: 'New York'
  },
  destination: {
    lat: 42.3601,
    lng: -71.0589,
    city: 'Boston',
    country: 'US'
  },
  items: [
    { sku: 'PROD-001', quantity: 10, weight: 5.0 }
  ],
  serviceLevel: 'STANDARD'
})

Output:

🚚 Finding cheapest carrier...

Found 4 available carriers

💰 Cost Comparison:

🏆 FastShip Logistics
   Total: $45.50
   Base: $35.00 + Fees: $10.50
   Performance: 92/100
   Distance: 215km

   QuickMove Express
   Total: $52.30
   Base: $40.00 + Fees: $12.30
   Performance: 88/100
   Distance: 225km

   SpeedyDelivery Inc
   Total: $58.75
   Base: $45.00 + Fees: $13.75
   Performance: 95/100
   Distance: 210km

   RapidTransport Co
   Total: $63.20
   Base: $48.00 + Fees: $15.20
   Performance: 90/100
   Distance: 230km

✅ Best option: FastShip Logistics
💵 Potential savings: $17.70

Dynamic Capacity Planning

Monitor warehouse capacity across multiple facilities for inventory planning.

Scenario

A 3PL operator needs to monitor capacity utilization across all warehouses and identify facilities that are approaching full capacity.

Implementation

typescript
class CapacityPlanner {
  private client: DeClient
  private warningThreshold = 80  // 80% utilization
  private criticalThreshold = 90 // 90% utilization
  
  constructor(apiKey: string, workspaceId: string) {
    this.client = new DeClient({ apiKey, workspace: workspaceId })
  }
  
  async analyzeNetworkCapacity() {
    console.log('📊 Analyzing network capacity...\n')
    
    // Step 1: Get all warehouses
    const warehouses = await this.client.realm.queries.discovery.discover({
      serviceType: 'WAREHOUSE'
    })
    
    console.log(`Analyzing ${warehouses.total} warehouses\n`)
    
    // Step 2: Batch query capacities
    const capacityQueries = warehouses.services.map(w => ({
      lsp: w.lsp,
      serviceId: w.serviceId,
      capacityType: 'STORAGE_SLOTS'
    }))
    
    const capacities = await this.client.realm.queries.capacity.batchQuery({
      queries: capacityQueries
    })
    
    // Step 3: Analyze utilization
    const analysis = warehouses.services.map(warehouse => {
      const key = `${warehouse.lsp}:${warehouse.serviceId}`
      const capacity = capacities.capacities[key]
      
      if (!capacity) {
        return {
          name: warehouse.name,
          location: warehouse.location.city,
          status: 'NO_DATA',
          utilization: 0,
          available: 0,
          total: 0
        }
      }
      
      const utilization = capacity.utilizationRate
      let status: string
      
      if (utilization >= this.criticalThreshold) {
        status = 'CRITICAL'
      } else if (utilization >= this.warningThreshold) {
        status = 'WARNING'
      } else {
        status = 'HEALTHY'
      }
      
      return {
        name: warehouse.name,
        location: warehouse.location.city,
        status,
        utilization: capacity.utilizationRate,
        available: capacity.available,
        total: capacity.total
      }
    })
    
    // Display results grouped by status
    const critical = analysis.filter(a => a.status === 'CRITICAL')
    const warning = analysis.filter(a => a.status === 'WARNING')
    const healthy = analysis.filter(a => a.status === 'HEALTHY')
    
    if (critical.length > 0) {
      console.log('🔴 CRITICAL - Immediate Action Required:\n')
      critical.forEach(w => {
        console.log(`   ${w.name} (${w.location})`)
        console.log(`   Utilization: ${w.utilization}%`)
        console.log(`   Available: ${w.available}/${w.total} slots\n`)
      })
    }
    
    if (warning.length > 0) {
      console.log('🟡 WARNING - Monitor Closely:\n')
      warning.forEach(w => {
        console.log(`   ${w.name} (${w.location})`)
        console.log(`   Utilization: ${w.utilization}%`)
        console.log(`   Available: ${w.available}/${w.total} slots\n`)
      })
    }
    
    console.log(`✅ HEALTHY: ${healthy.length} warehouses\n`)
    
    // Network summary
    const totalCapacity = analysis.reduce((sum, a) => sum + a.total, 0)
    const totalUsed = analysis.reduce((sum, a) => sum + (a.total - a.available), 0)
    const networkUtilization = (totalUsed / totalCapacity * 100).toFixed(1)
    
    console.log('📈 Network Summary:')
    console.log(`   Total Capacity: ${totalCapacity.toLocaleString()} slots`)
    console.log(`   Used: ${totalUsed.toLocaleString()} slots`)
    console.log(`   Available: ${(totalCapacity - totalUsed).toLocaleString()} slots`)
    console.log(`   Network Utilization: ${networkUtilization}%`)
    
    return {
      total: analysis.length,
      critical: critical.length,
      warning: warning.length,
      healthy: healthy.length,
      networkUtilization: parseFloat(networkUtilization),
      details: analysis
    }
  }
}

// Usage
const planner = new CapacityPlanner(
  process.env.DE_API_KEY!,
  process.env.DE_WORKSPACE_ID!
)

const analysis = await planner.analyzeNetworkCapacity()

Output:

📊 Analyzing network capacity...

Analyzing 8 warehouses

🔴 CRITICAL - Immediate Action Required:

   Manhattan Fulfillment Center (New York)
   Utilization: 94%
   Available: 120/2000 slots

   Brooklyn Distribution Hub (New York)
   Utilization: 91%
   Available: 180/2000 slots

🟡 WARNING - Monitor Closely:

   Queens Warehouse (New York)
   Utilization: 85%
   Available: 300/2000 slots

   Newark Logistics Center (Newark)
   Utilization: 82%
   Available: 360/2000 slots

✅ HEALTHY: 4 warehouses

📈 Network Summary:
   Total Capacity: 16,000 slots
   Used: 12,340 slots
   Available: 3,660 slots
   Network Utilization: 77.1%

Intelligent Load Balancing

Distribute incoming orders across warehouses to balance utilization.

Scenario

During peak season, orders need to be distributed evenly across available warehouses to prevent any single facility from being overwhelmed.

Implementation

typescript
class LoadBalancer {
  private client: DeClient
  private targetUtilization = 75 // Target 75% utilization
  
  constructor(apiKey: string, workspaceId: string) {
    this.client = new DeClient({ apiKey, workspace: workspaceId })
  }
  
  async assignOrderWithLoadBalancing(order: {
    items: Array<{ sku: string; quantity: number }>
    destination: { lat: number; lng: number; city: string; country: string }
  }) {
    // Step 1: Find candidate warehouses
    const candidates = await this.client.realm.queries.matching.match({
      serviceTypes: ['WAREHOUSE'],
      delivery: {
        country: order.destination.country,
        city: order.destination.city,
        coordinates: [order.destination.lat, order.destination.lng]
      },
      items: order.items,
      strategy: 'BALANCED'
    })
    
    // Step 2: Check capacity and utilization for top candidates
    const scoredCandidates = await Promise.all(
      candidates.recommendations.slice(0, 5).map(async rec => {
        const capacity = await this.client.realm.queries.capacity.query({
          lsp: rec.service.lsp,
          serviceId: rec.service.serviceId,
          capacityType: 'STORAGE_SLOTS'
        })
        
        // Calculate load balancing score
        // Prefer warehouses with utilization closer to target
        const utilizationDiff = Math.abs(capacity.utilizationRate - this.targetUtilization)
        const loadBalanceScore = Math.max(0, 100 - utilizationDiff)
        
        // Combine with match score (60% match quality, 40% load balance)
        const combinedScore = (rec.scores.overall * 0.6) + (loadBalanceScore * 0.4)
        
        return {
          ...rec,
          capacity,
          loadBalanceScore,
          combinedScore
        }
      })
    )
    
    // Sort by combined score
    scoredCandidates.sort((a, b) => b.combinedScore - a.combinedScore)
    
    const selected = scoredCandidates[0]
    
    console.log('🎯 Selected warehouse:', selected.service.name)
    console.log(`   Match Score: ${selected.scores.overall}/100`)
    console.log(`   Load Balance Score: ${selected.loadBalanceScore}/100`)
    console.log(`   Combined Score: ${selected.combinedScore.toFixed(1)}/100`)
    console.log(`   Current Utilization: ${selected.capacity.utilizationRate}%`)
    
    return selected
  }
}

Next Steps