Get Commercial Order détail

The getCommercialOrder function retrieves detailed information for a specific commercial order by its identifier. This function is essential for displaying complete order information, including order status, financial details, customer information, and associated logistic orders. It provides comprehensive order data needed for order management, customer service, and business operations.

This function serves as the primary method for accessing individual commercial order details, supporting various use cases from order confirmation displays to detailed administrative views.

Process Flow

sequenceDiagram
    participant User as User
    participant Component as Vue Component
    participant UCO as useCommercialOrder
    participant Auth as Authentication
    participant API as Order API
    participant DB as Database

    User->>Component: Request Order Details
    Component->>UCO: getCommercialOrder({orderId})
    UCO->>Auth: ensureAuthenticated()

    alt Authentication Valid
        Auth-->>UCO: Authenticated
        UCO->>API: GET /api/commercial-orders/{orderId}
        API->>DB: Query Order Data
        DB-->>API: Order Details
        API-->>UCO: Commercial Order Response
        UCO-->>Component: GetCommercialOrderResponse
        Component-->>User: Display Order Details
    else Authentication Failed
        Auth-->>UCO: Authentication Error
        UCO-->>Component: Error Response
        Component-->>User: Redirect to Login
    else Order Not Found
        API-->>UCO: 404 Error
        UCO-->>Component: Order Not Found
        Component-->>User: Show Not Found Message
    else Access Denied
        API-->>UCO: 403 Error
        UCO-->>Component: Access Denied
        Component-->>User: Show Access Denied Message
    end

Call Parameters

Request Interface

interface GetCommercialOrderRequest {
  orderId: string;
  locale?: string;
  idType?: "ID" | "EXTERNAL_ID";
  nbPreviewLines?: number;
}

Parameters Detail

ParameterTypeRequiredDefaultExampleBusiness Impact
orderIdstring-"co-123456", "EXT-ORDER-001"Identifies the specific order to retrieve
localestring'en''fr', 'en', 'de'Affects localized content and date formatting
idType'ID' | 'EXTERNAL_ID''ID''ID', 'EXTERNAL_ID'Specifies identifier type for lookup
nbPreviewLinesnumber30, 5, 10Number of order lines to include in response

Example Call

const { getCommercialOrder } = useCommercialOrder();

// Get order by internal ID
const orderDetails = await getCommercialOrder({
  orderId: "co-123456",
  locale: "fr",
  nbPreviewLines: 5,
});

// Get order by external ID
const orderByExternalId = await getCommercialOrder({
  orderId: "EXT-ORDER-001",
  idType: "EXTERNAL_ID",
  locale: "en",
  nbPreviewLines: 10,
});

Composable Returns

Response Interface

interface GetCommercialOrderResponse {
  success: boolean;
  order: CommercialOrder;
}

Response Structure

{
  "success": true,
  "order": {
    "id": "co-123456",
    "reference": "CO-2024-001",
    "status": "CREATED",
    "totalPrice": 1250.99,
    "totalPriceWithoutTax": 1042.49,
    "totalTaxAmount": 208.5,
    "totalShippingFees": 15.0,
    "currency": "EUR",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-16T14:20:00Z",
    "logistics": [
      {
        "id": "lo-789012",
        "reference": "LO-2024-001",
        "status": "WAITING_SHIPMENT",
        "totalPrice": 1250.99,
        "lines": [
          {
            "id": "line-456",
            "productId": "prod-123",
            "productName": "Professional Monitor",
            "productSku": "MON-PRO-001",
            "quantity": 1,
            "unitPrice": 1235.99,
            "totalPrice": 1235.99,
            "currency": "EUR"
          }
        ]
      }
    ],
    "customFields": [
      {
        "externalId": "purchase-order-number",
        "value": "PO-2024-001",
        "type": "text",
        "label": "Purchase Order Number"
      },
      {
        "externalId": "delivery-instructions",
        "value": "Ring doorbell twice",
        "type": "text",
        "label": "Delivery Instructions"
      }
    ],
    "billingInformation": {
      "method": "credit_card",
      "details": {
        "cardType": "visa",
        "lastFourDigits": "1234",
        "expirationMonth": "12",
        "expirationYear": "2025"
      }
    },
    "shippingInformation": {
      "type": "express",
      "carrier": "DHL",
      "estimatedDeliveryDate": "2024-01-18T00:00:00Z",
      "notes": "Express delivery requested"
    },
    "paymentInfo": {
      "method": "credit_card",
      "amount": 1250.99,
      "currency": "EUR",
      "status": "confirmed"
    }
  }
}

Error Handling

HTTP Error Codes

CodeCauseSystem ActionUser MessageRecovery Action
401Invalid/expired tokenAutomatic token refresh attempt"Session expired, please log in again"Redirect to login
400Invalid order ID formatLog validation error"Invalid order identifier"Check order ID format
403Insufficient permissionsLog access attempt"You don't have permission to view this order"Contact administrator
404Order not foundLog search attempt"Order not found"Verify order ID or search orders
412Precondition failedLog validation failure"Request validation failed"Check request parameters
429Rate limit exceededImplement retry logic"Too many requests, please wait"Implement exponential backoff
500Server errorLog error, fallback"Server error, please try again later"Retry with exponential backoff

Error Handling Implementation

const getCommercialOrder = async (params: GetCommercialOrderRequest) => {
  try {
    await ensureAuthenticated();

    const { data, error } = await useFetch<GetCommercialOrderResponse>(
      `/api/commercial-orders/${params.orderId}`,
      {
        query: {
          locale: params.locale,
          idType: params.idType,
          nbPreviewLines: params.nbPreviewLines,
        },
        retry: 3,
        retryDelay: 500,
        timeout: 10000,
      }
    );

    if (error.value) {
      throw new Error(
        `Failed to retrieve commercial order: ${error.value.statusMessage}`
      );
    }

    return data.value as GetCommercialOrderResponse;
  } catch (error) {
    const toast = useToast();

    if (error.statusCode === 401) {
      const { logout } = useDjustAuth();
      await logout();
      await navigateTo("/auth/login");
    } else if (error.statusCode === 404) {
      toast.add({
        title: "Order Not Found",
        description: "The requested order could not be found",
        color: "warning",
      });
      await navigateTo("/orders");
    } else if (error.statusCode === 403) {
      toast.add({
        title: "Access Denied",
        description: "You do not have permission to view this order",
        color: "error",
      });
    } else {
      toast.add({
        title: "Error",
        description: "Failed to load order details. Please try again.",
        color: "error",
      });
    }

    throw error;
  }
};

Use Cases

1. Order Detail Page Display

Show comprehensive order information for customer review:

  • Display complete order summary with financial details
  • Show order status and timeline progression
  • Include product details with preview lines
  • Present shipping and billing information

2. Customer Service Interface

Provide customer support with complete order context:

  • Access full order history and status
  • View customer information and preferences
  • Check payment and shipping details
  • Review custom fields and special instructions

3. Order Management Dashboard

Enable administrative order oversight:

  • Monitor order progression through workflows
  • Access financial data for reporting
  • Review logistics coordination details
  • Manage order modifications and updates

4. Mobile Application Views

Optimized order display for mobile interfaces:

  • Use nbPreviewLines to limit data for mobile performance
  • Show essential order information first
  • Provide drill-down capability for detailed views
  • Support offline viewing with cached data

Key Performance Points

Performance Optimization

  • Preview Lines Control: Use nbPreviewLines parameter to limit response size for list views
  • Caching Strategy: Implement caching with unique keys based on order ID and parameters
  • Lazy Loading: Load additional order details on-demand for complex orders
  • Data Pagination: For orders with many lines, implement pagination for line items

Security Considerations

  • Authentication Validation: Always verify user authentication before order access
  • Permission Checking: Validate user permissions for specific order access
  • Data Sanitization: Filter sensitive data based on user role and permissions
  • Audit Logging: Log all order access attempts for security monitoring

Flexibility Features

  • ID Type Support: Flexible identifier lookup (internal ID vs external ID)
  • Localization: Full internationalization support for global deployments
  • Custom Fields: Support for business-specific metadata and requirements
  • Preview Control: Configurable level of detail for different use cases

Integration Capabilities

  • Store Integration: Seamless integration with Order Store for state management
  • Component Integration: Direct integration with Vue components for reactive UI
  • Error Propagation: Consistent error handling with global error management
  • Type Safety: Full TypeScript support ensures compile-time error detection

Technical Implementation

Complete Function Code

/**
 * Get a commercial order by ID
 * @param params - Request parameters including order ID and options
 * @param config - Optional configuration for API call
 * @returns Promise resolving to commercial order details
 */
const getCommercialOrder = async (
  params: GetCommercialOrderRequest,
  config?: Partial<DjustConfig>
): Promise<GetCommercialOrderResponse> => {
  try {
    // Ensure user is authenticated before proceeding
    await ensureAuthenticated();

    const { orderId, locale, idType, nbPreviewLines } = params;

    if (!orderId) {
      throw new Error('The "orderId" parameter is required.');
    }

    // Retrieve commercial order from API
    const { data, error } = await useFetch<GetCommercialOrderResponse>(
      `/api/commercial-orders/${orderId}`,
      {
        query: {
          locale,
          idType,
          nbPreviewLines,
          ...config,
        },
        // Performance optimizations
        key: `commercial-order-${orderId}-${locale}-${nbPreviewLines}`,
        server: true,
        lazy: false,
      }
    );

    if (error.value) {
      throw new Error("Failed to retrieve commercial order.");
    }

    console.log("Commercial order retrieved successfully");
    return data.value as GetCommercialOrderResponse;
  } catch (error) {
    console.error("Failed to retrieve commercial order:", error);
    throw new Error(
      "Failed to retrieve commercial order. Please try again later."
    );
  }
};

Execution Flow

Step-by-Step Process

  1. Authentication Verification

    await ensureAuthenticated();
  2. Parameter Validation

    if (!orderId) throw new Error('The "orderId" parameter is required.');
  3. API Call Execution

    const { data, error } = await useFetch(`/api/commercial-orders/${orderId}`, {
      query: params,
    });
  4. Error Handling

    if (error.value) throw new Error("Failed to retrieve commercial order.");
  5. Response Return

    return data.value as GetCommercialOrderResponse;
  6. UI Integration (in calling component)

    // Display order details
    const order = response.order;
    
    // Update navigation breadcrumbs
    setBreadcrumbs([
      { name: "Orders", path: "/orders" },
      { name: order.reference, path: `/orders/${order.id}` },
    ]);
    
    // Handle order status display
    const statusColor = getOrderStatusColor(order.status);
    const statusLabel = getLocalizedStatus(order.status);

This comprehensive function provides robust order retrieval capabilities with proper validation, error handling, and integration with the broader order management system.