Initialize Commercial Order

The createCommercialOrder function initializes a new commercial order within the system. This function serves as the primary entry point for order creation, converting quotes, carts, or direct purchases into formal commercial orders. It handles the initial order setup including payment information, custom fields, and business metadata required for order processing.

This function is crucial for the order lifecycle as it transitions from shopping/quoting phase to the formal order management phase, establishing the foundation for subsequent logistic order creation and fulfillment processing.

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 Store as Order Store

    User->>Component: Initiate Order Creation
    Component->>UCO: createCommercialOrder(params)
    UCO->>Auth: ensureAuthenticated()

    alt Authentication Valid
        Auth-->>UCO: Authenticated
        UCO->>API: POST /api/commercial-orders
        API->>API: Validate Order Data
        API->>API: Create Commercial Order
        API-->>UCO: Order Created Response
        UCO-->>Component: CreateCommercialOrderResponse
        Component->>Store: Update Order State (optional)
        Component-->>User: Order Confirmation
    else Authentication Failed
        Auth-->>UCO: Authentication Error
        UCO-->>Component: Error Response
        Component-->>User: Redirect to Login
    else Validation Error
        API-->>UCO: Validation Error (400)
        UCO-->>Component: Validation Error
        Component-->>User: Show Validation Messages
    else Server Error
        API-->>UCO: Server Error (500)
        UCO-->>Component: Error Thrown
        Component-->>User: Error Message
    end

Call Parameters

Request Interface

interface CreateCommercialOrderRequest {
  nbPreviewLines?: number;
  channel?: string;
  customFields?: CustomFieldValue[];
  locale?: string;
  origin?: string;
  originId?: string;
  paymentInfo?: PaymentInfo;
}

Parameters Detail

ParameterTypeRequiredDefaultExampleBusiness Impact
nbPreviewLinesnumber30, 5, 10Controls order line preview in response
channelstring'web''web', 'mobile', 'api'Tracks order source for analytics
customFieldsCustomFieldValue[][][{externalId: 'po-number', value: 'PO-123'}]Business-specific metadata
localestring'en''fr', 'en', 'de'Affects localized content
originstringundefined'quote', 'cart', 'direct'Tracks order source type
originIdstringundefined'quote-123', 'cart-456'Links to source entity
paymentInfoPaymentInfoundefined{method: 'credit_card', details: {...}}Payment processing information

Example Call

const { createCommercialOrder } = useCommercialOrder();

const newOrder = await createCommercialOrder({
  channel: "web",
  locale: "fr",
  origin: "quote",
  originId: "quote-12345",
  nbPreviewLines: 5,
  customFields: [
    {
      externalId: "purchase-order-number",
      value: "PO-2024-001",
      type: "text",
    },
    {
      externalId: "delivery-instructions",
      value: "Leave at reception desk",
      type: "text",
    },
  ],
  paymentInfo: {
    method: "credit_card",
    amount: 1250.99,
    currency: "EUR",
  },
});

Composable Returns

Response Interface

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

Response Structure

{
  "success": true,
  "order": {
    "id": "co-123456",
    "reference": "CO-2024-001",
    "status": "DRAFT",
    "totalPrice": 1250.99,
    "totalPriceWithoutTax": 1042.49,
    "totalTaxAmount": 208.5,
    "totalShippingFees": 15.0,
    "currency": "EUR",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z",
    "logistics": [],
    "customFields": [
      {
        "externalId": "purchase-order-number",
        "value": "PO-2024-001",
        "type": "text",
        "label": "Purchase Order Number"
      }
    ],
    "paymentInfo": {
      "method": "credit_card",
      "amount": 1250.99,
      "currency": "EUR"
    },
    "billingInformation": {
      "method": "credit_card",
      "details": {
        "cardType": "visa",
        "lastFourDigits": "1234"
      }
    },
    "shippingInformation": {
      "type": "standard",
      "estimatedDeliveryDate": "2024-01-20T00:00:00Z"
    }
  }
}

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 request dataLog validation errors"Please check your order information"Highlight invalid fields
403Insufficient permissionsLog access attempt"You don't have permission to create orders"Contact administrator
409Conflict (duplicate order)Log conflict details"This order already exists"Check existing orders
412Precondition failedLog validation failure"Order requirements not met"Check prerequisites
422Unprocessable entityLog business rule violations"Order validation failed"Review business rules
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 createCommercialOrder = async (params: CreateCommercialOrderRequest) => {
  try {
    await ensureAuthenticated();

    const { data, error } = await useFetch<CreateCommercialOrderResponse>(
      "/api/commercial-orders",
      {
        method: "POST",
        body: params,
        retry: 2,
        retryDelay: 1000,
        timeout: 15000,
      }
    );

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

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

    if (error.statusCode === 401) {
      const { logout } = useDjustAuth();
      await logout();
      await navigateTo("/auth/login");
    } else if (error.statusCode === 400 || error.statusCode === 422) {
      toast.add({
        title: "Validation Error",
        description: "Please check your order information and try again",
        color: "warning",
      });
    } else if (error.statusCode === 409) {
      toast.add({
        title: "Order Exists",
        description: "This order has already been created",
        color: "warning",
      });
    } else {
      toast.add({
        title: "Error",
        description: "Failed to create order. Please try again.",
        color: "error",
      });
    }

    throw error;
  }
};

Use Cases

1. Quote to Order Conversion

Convert approved quotes into commercial orders:

  • Transfer quote data including line items and pricing
  • Preserve custom fields and business metadata
  • Maintain audit trail with origin and originId
  • Handle payment information setup

2. Cart Checkout Process

Transform shopping cart contents into formal orders:

  • Convert cart items to order lines
  • Apply final pricing and discounts
  • Capture payment method selection
  • Set appropriate delivery options

3. Direct Order Creation

Create orders directly without intermediate steps:

  • B2B repeat orders with known products
  • API-driven order creation from external systems
  • Bulk order processing scenarios
  • Emergency or expedited orders

4. Multi-Channel Order Processing

Handle orders from various channels:

  • Web application orders
  • Mobile application orders
  • API integration orders
  • Partner portal orders

Key Performance Points

Performance Optimization

  • Payload Minimization: Only include necessary data to reduce request size
  • Preview Lines Control: Use nbPreviewLines to limit response payload for UI display
  • Async Processing: Consider async order processing for complex orders
  • Caching Strategy: Cache customer data and preferences for faster order creation

Security Considerations

  • Authentication Validation: Always verify user authentication before order creation
  • Input Sanitization: Validate and sanitize all input parameters
  • Permission Verification: Ensure user has order creation permissions
  • Audit Trail: Maintain complete audit trail for order creation events

Flexibility Features

  • Custom Fields Support: Extensible custom field system for business-specific requirements
  • Multi-Channel Support: Flexible channel tracking for analytics and processing
  • Payment Integration: Flexible payment information handling for various payment methods
  • Localization Support: Full internationalization support for global deployments

Integration Capabilities

  • Source Tracking: Complete traceability from source (quote/cart) to order
  • Workflow Integration: Seamless integration with order workflow management
  • External System Integration: Support for API-driven order creation
  • Event Emission: Order creation events for downstream processing

Technical Implementation

Complete Function Code

/**
 * Create a new commercial order
 * @param params - Order creation parameters
 * @param config - Optional configuration for API call
 * @returns Promise resolving to created commercial order
 */
const createCommercialOrder = async (
  params: CreateCommercialOrderRequest,
  config?: Partial<DjustConfig>
): Promise<CreateCommercialOrderResponse> => {
  try {
    // Ensure user is authenticated before proceeding
    await ensureAuthenticated();

    const {
      nbPreviewLines,
      channel,
      customFields,
      locale,
      origin,
      originId,
      paymentInfo,
    } = params;

    // Create commercial order via API
    const { data, error } = await useFetch<CreateCommercialOrderResponse>(
      "/api/commercial-orders",
      {
        method: "POST",
        query: config,
        body: {
          nbPreviewLines,
          channel,
          customFields,
          locale,
          origin,
          originId,
          paymentInfo,
        },
        // Performance and reliability settings
        key: `create-commercial-order-${Date.now()}`,
        server: false, // Client-side execution for order creation
        retry: 2,
        retryDelay: 1000,
      }
    );

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

    console.log(
      "Commercial order created successfully:",
      data.value?.order?.reference
    );
    return data.value as CreateCommercialOrderResponse;
  } catch (error) {
    console.error("Failed to create commercial order:", error);
    throw new Error(
      "Failed to create commercial order. Please try again later."
    );
  }
};

Execution Flow

Step-by-Step Process

  1. Authentication Verification

    await ensureAuthenticated();
  2. Parameter Destructuring

    const {
      nbPreviewLines,
      channel,
      customFields,
      locale,
      origin,
      originId,
      paymentInfo,
    } = params;
  3. API Call Execution

    const { data, error } = await useFetch("/api/commercial-orders", {
      method: "POST",
      body: params,
    });
  4. Error Handling

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

    return data.value as CreateCommercialOrderResponse;
  6. Post-Creation Actions (in calling component)

    // Navigate to order confirmation
    await navigateTo(`/orders/${response.order.id}`);
    
    // Update application state
    const orderStore = useOrderStore();
    orderStore.addOrder(response.order);
    
    // Show success notification
    toast.add({
      title: "Order Created",
      description: `Order ${response.order.reference} has been created successfully`,
      color: "success",
    });

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