Get Logisitic orders list
The getLogisticOrders
function retrieves a paginated list of logistic orders for the authenticated user's account. This function is essential for displaying order lists, filtering orders by status, and managing order workflows. It provides comprehensive filtering options including status filtering, pagination, and sorting capabilities to efficiently handle large order datasets.
This function serves as the primary entry point for order list management in the application, supporting various use cases from simple order listing to complex filtered views based on business requirements.
Process Flow
sequenceDiagram participant User as User participant Component as Vue Component participant ULO as useLogisticOrder participant Auth as Authentication participant API as Order API participant Store as Order Store User->>Component: Request Orders List Component->>ULO: getLogisticOrders(params) ULO->>Auth: ensureAuthenticated() alt Authentication Valid Auth-->>ULO: Authenticated ULO->>API: GET /api/logistic-orders API-->>ULO: Orders Response ULO->>Store: setOrders(orders) ULO->>Store: setOrdersByStatus(orders) ULO-->>Component: GetLogisticOrdersResponse Component-->>User: Display Orders List else Authentication Failed Auth-->>ULO: Authentication Error ULO-->>Component: Error Response Component-->>User: Redirect to Login else API Error API-->>ULO: Error Response (400/500) ULO-->>Component: Error Thrown Component-->>User: Error Message end
Call Parameters
Request Interface
interface GetLogisticOrdersRequest {
approvalIds?: string[];
locale?: string;
logisticStatus?: LogisticOrderStatusType[];
commercialOrderIds?: string[];
supplierIds?: string[];
sort?: string[];
size?: number;
page?: number;
nbPreviewLines?: number;
}
Parameters Detail
Parameter | Type | Required | Default | Example | Business Impact |
---|---|---|---|---|---|
approvalIds | string[] | ❌ | undefined | ["approval-123", "approval-456"] | Filters orders by specific approval workflows |
locale | string | ❌ | 'en' | 'fr' , 'en' | Affects localized content and date formatting |
logisticStatus | LogisticOrderStatusType[] | ❌ | [] (all statuses) | ['WAITING_SHIPMENT', 'SHIPPED'] | Critical for order workflow filtering |
commercialOrderIds | string[] | ❌ | undefined | ["co-123", "co-456"] | Links logistic orders to commercial orders |
supplierIds | string[] | ❌ | undefined | ["supplier-abc", "supplier-def"] | Filters by specific suppliers |
sort | string[] | ❌ | ['created_at,DESC'] | ['created_at,ASC', 'totalPrice,DESC'] | Controls result ordering for user experience |
size | number | ❌ | 20 | 10 , 50 , 100 | Pagination size affects performance |
page | number | ❌ | 0 | 0 , 1 , 2 | Current page for pagination |
nbPreviewLines | number | ❌ | 3 | 0 , 5 , 10 | Number of order lines to include per order |
Example Call
const { getLogisticOrders } = useLogisticOrder();
const orders = await getLogisticOrders({
locale: "fr",
logisticStatus: ["WAITING_SHIPMENT", "SHIPPED"],
size: 20,
page: 0,
sort: ["created_at,DESC"],
nbPreviewLines: 5,
});
Composable Returns
Response Interface
interface GetLogisticOrdersResponse {
success: boolean;
orders: {
content: LogisticOrder[];
totalElements: number;
totalPages: number;
size: number;
number: number;
};
}
Response Structure
{
"success": true,
"orders": {
"content": [
{
"id": "lo-123456",
"reference": "LO-2024-001",
"status": "WAITING_SHIPMENT",
"commercialOrderReference": "CO-2024-001",
"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",
"validationDate": "2024-01-15T11:00:00Z",
"lines": [
{
"id": "line-789",
"productId": "prod-456",
"productName": "Professional Keyboard",
"productSku": "KB-PRO-001",
"variantId": "var-123",
"quantity": 2,
"unitPrice": 125.99,
"totalPrice": 251.98,
"currency": "EUR",
"status": "CONFIRMED"
}
],
"billingAddressSnapshot": {
"name": "Acme Corp",
"street": "123 Business Ave",
"city": "Paris",
"country": "France",
"postalCode": "75001"
},
"shippingAddressSnapshot": {
"name": "Acme Corp - Warehouse",
"street": "456 Industrial St",
"city": "Lyon",
"country": "France",
"postalCode": "69001"
}
}
],
"totalElements": 156,
"totalPages": 8,
"size": 20,
"number": 0
}
}
Error Handling
HTTP Error Codes
Code | Cause | System Action | User Message | Recovery Action |
---|---|---|---|---|
401 | Invalid/expired token | Automatic token refresh attempt | "Session expired, please log in again" | Redirect to login |
400 | Invalid request parameters | Log error details | "Invalid request parameters" | Validate input and retry |
403 | Insufficient permissions | Log access attempt | "You don't have permission to view orders" | Contact administrator |
404 | Resource not found | Return empty result | "No orders found" | Display empty state |
412 | Precondition failed | Log validation failure | "Request validation failed" | Check required parameters |
429 | Rate limit exceeded | Implement retry logic | "Too many requests, please wait" | Implement exponential backoff |
500 | Server error | Log error, fallback | "Server error, please try again later" | Retry with exponential backoff |
502 | Bad gateway | Service monitoring alert | "Service temporarily unavailable" | Show maintenance message |
503 | Service unavailable | Circuit breaker activation | "Service under maintenance" | Display maintenance notice |
Error Handling Implementation
const getLogisticOrders = async (params: GetLogisticOrdersRequest) => {
try {
await ensureAuthenticated();
const { data, error } = await useFetch<GetLogisticOrdersResponse>(
"/api/logistic-orders",
{
query: params,
retry: 3,
retryDelay: 500,
timeout: 10000,
}
);
if (error.value) {
throw new Error(
`Failed to retrieve logistic orders: ${error.value.statusMessage}`
);
}
return data.value as GetLogisticOrdersResponse;
} catch (error) {
const toast = useToast();
if (error.statusCode === 401) {
// Handle authentication error
const { logout } = useDjustAuth();
await logout();
await navigateTo("/auth/login");
} else if (error.statusCode === 403) {
toast.add({
title: "Access Denied",
description: "You do not have permission to view orders",
color: "error",
});
} else {
toast.add({
title: "Error",
description: "Failed to load orders. Please try again.",
color: "error",
});
}
throw error;
}
};
Use Cases
1. Order Dashboard Display
Display all orders with status filtering for admin overview:
- Load orders with pagination for performance
- Group by status for workflow management
- Include preview lines for quick reference
- Sort by creation date for chronological view
2. Status-Based Order Management
Filter orders by specific statuses for workflow processing:
WAITING_SUPPLIER_APPROVAL
for approval workflowsWAITING_SHIPMENT
for fulfillment processingSHIPPED
for tracking managementCOMPLETED
for completed order analysis
3. Supplier-Specific Order Views
Filter orders by specific suppliers for partner management:
- Track supplier performance metrics
- Manage supplier-specific workflows
- Monitor delivery timelines per supplier
- Handle supplier communications efficiently
4. Search and Pagination
Handle large order datasets with efficient pagination:
- Implement infinite scroll for user experience
- Use appropriate page sizes for performance
- Maintain filter state across pagination
- Optimize load times with preview line limits
Key Performance Points
Performance Optimization
- Pagination Strategy: Use appropriate page sizes (10-50) to balance performance and user experience
- Preview Lines Limit: Set
nbPreviewLines
to 3-5 to reduce payload size while providing sufficient preview - Caching Implementation: Leverage Nuxt's built-in caching with unique cache keys based on parameters
- Status Filtering: Use status arrays to reduce server-side processing and improve response times
Security Considerations
- Authentication Validation: Always verify user authentication before API calls
- Account Isolation: Orders are automatically filtered by customer account to ensure data security
- Permission Checking: Backend validates user permissions for order access
- Input Validation: Validate all parameters client-side before API calls
Flexibility Features
- Multi-Status Filtering: Support arrays of statuses for complex workflow filtering
- Supplier Filtering: Enable partner-specific views for B2B scenarios
- Locale Support: Full internationalization support for global deployments
- Custom Sorting: Flexible sorting options for different business requirements
Integration Capabilities
- Store Integration: Automatic state management through Order Store for reactive UI updates
- Component Integration: Seamless integration with Vue components through reactive returns
- 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 logistic orders with filtering, pagination, and sorting
* @param params - Request parameters for filtering and pagination
* @param config - Optional configuration for API call
* @returns Promise resolving to paginated logistic orders response
*/
const getLogisticOrders = async (
params: GetLogisticOrdersRequest,
config?: Partial<DjustConfig>
): Promise<GetLogisticOrdersResponse> => {
try {
// Ensure user is authenticated before proceeding
await ensureAuthenticated();
const {
approvalIds,
locale,
logisticStatus,
commercialOrderIds,
supplierIds,
nbPreviewLines,
page,
size,
sort,
} = params;
// Make API request with all parameters
const { data, error } = await useFetch<GetLogisticOrdersResponse>(
"/api/logistic-orders",
{
query: {
approvalIds,
locale,
logisticStatus,
commercialOrderIds,
supplierIds,
nbPreviewLines,
page,
size,
sort,
...config,
},
// Performance optimizations
key: `logistic-orders-${JSON.stringify(params)}`,
server: true,
lazy: false,
}
);
if (error.value) {
throw new Error("Failed to retrieve logistic orders.");
}
console.log("Logistic orders retrieved successfully");
return data.value as GetLogisticOrdersResponse;
} catch (error) {
console.error("Failed to retrieve logistic orders:", error);
throw new Error(
"Failed to retrieve logistic orders. Please try again later."
);
}
};
Execution Flow
Step-by-Step Process
-
Authentication Verification
await ensureAuthenticated();
-
Parameter Extraction
const { approvalIds, locale, logisticStatus, ...otherParams } = params;
-
API Call Execution
const { data, error } = await useFetch("/api/logistic-orders", { query: params, });
-
Error Handling
if (error.value) throw new Error("Failed to retrieve logistic orders.");
-
Response Return
return data.value as GetLogisticOrdersResponse;
-
Store Updates (if needed in calling component)
const orderStore = useOrderStore(); orderStore.setOrders(response.orders.content); orderStore.setOrdersByStatus(response.orders.content);
This comprehensive function provides robust order retrieval capabilities with proper error handling, performance optimization, and seamless integration with the application's architecture.
Updated about 2 months ago