Update commercial order to Created status
The setCommercialOrderStatusAsCreated
function transitions a commercial order from DRAFT status to CREATED status, marking it as a confirmed order ready for processing. This function is a critical workflow step that validates order completeness, finalizes payment information, and initiates the order fulfillment process. It represents the formal confirmation of an order by the customer.
This function is typically used at the end of the order creation workflow when all order details have been finalized, payment information is confirmed, and the customer is ready to proceed with the order.
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 Validation as Order Validation participant Payment as Payment Service participant Fulfillment as Fulfillment Service participant DB as Database User->>Component: Confirm Order Component->>UCO: setCommercialOrderStatusAsCreated(params) UCO->>Auth: ensureAuthenticated() alt Authentication Valid Auth-->>UCO: Authenticated UCO->>API: PUT /api/commercial-orders/{orderId}/created API->>Validation: Validate Order Completeness Validation-->>API: Order Valid API->>Payment: Process Payment Information Payment-->>API: Payment Confirmed API->>DB: Update Order Status to CREATED DB-->>API: Status Updated API->>Fulfillment: Initialize Order Processing Fulfillment-->>API: Processing Started API-->>UCO: Status Update Response UCO-->>Component: Success Response Component-->>User: Order Confirmed else Authentication Failed Auth-->>UCO: Authentication Error UCO-->>Component: Error Response Component-->>User: Redirect to Login else Order Incomplete Validation-->>API: Validation Failed API-->>UCO: 422 Error UCO-->>Component: Validation Error Component-->>User: Show Missing Information else Payment Failed Payment-->>API: Payment Error API-->>UCO: 402 Error UCO-->>Component: Payment Error Component-->>User: Show Payment Issue else Already Created API-->>UCO: 409 Error UCO-->>Component: Conflict Error Component-->>User: Order Already Confirmed end
Call Parameters
Request Interface
interface SetCommercialOrderStatusAsCreatedRequest {
orderId: string;
paymentInfo?: PaymentInfo;
}
Parameters Detail
Parameter | Type | Required | Default | Example | Business Impact |
---|---|---|---|---|---|
orderId | string | ✅ | - | "co-123456" | Identifies the order to confirm |
paymentInfo | PaymentInfo | ❌ | undefined | {method: 'credit_card', ...} | Final payment information for order processing |
Example Call
const { setCommercialOrderStatusAsCreated } = useCommercialOrder();
// Confirm order with payment information
const confirmResult = await setCommercialOrderStatusAsCreated({
orderId: "co-123456",
paymentInfo: {
method: "credit_card",
amount: 1250.99,
currency: "EUR",
status: "confirmed",
transactionId: "tx-789012345",
},
});
console.log("Order confirmed:", confirmResult.success);
Composable Returns
Response Interface
interface SetCommercialOrderStatusAsCreatedResponse {
success: boolean;
order: CommercialOrder;
message: string;
}
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-16T17:00:00Z",
"confirmedAt": "2024-01-16T17:00:00Z",
"logistics": [
{
"id": "lo-789012",
"reference": "LO-2024-001",
"status": "WAITING_SUPPLIER_APPROVAL",
"createdAt": "2024-01-16T17:00:00Z"
}
],
"paymentInfo": {
"method": "credit_card",
"amount": 1250.99,
"currency": "EUR",
"status": "confirmed",
"transactionId": "tx-789012345",
"confirmedAt": "2024-01-16T17:00:00Z"
},
"workflow": {
"currentStage": "fulfillment",
"nextSteps": ["supplier_approval", "inventory_allocation"],
"estimatedCompletionDate": "2024-01-20T18:00:00Z"
},
"customFields": [
{
"externalId": "order-confirmation-method",
"value": "online_checkout",
"type": "text",
"label": "Order Confirmation Method"
}
]
},
"message": "Order status set to created successfully"
}
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 order ID | Log validation error | "Invalid order identifier" | Verify order ID |
402 | Payment required/failed | Log payment issue | "Payment processing failed" | Update payment method |
403 | Insufficient permissions | Log access attempt | "You don't have permission to confirm this order" | Contact administrator |
404 | Order not found | Log search attempt | "Order not found" | Verify order exists |
409 | Order already created | Log status conflict | "Order has already been confirmed" | Navigate to order details |
412 | Order incomplete | Log validation failure | "Order is missing required information" | Complete order details |
422 | Validation failed | Log validation errors | "Order validation failed" | Review and fix order data |
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 |
Use Cases
1. Order Checkout Completion
Finalize customer orders at checkout:
- Validate all order information is complete
- Confirm payment method and process payment
- Transition order from draft to active status
- Initialize fulfillment and logistics workflows
2. B2B Order Approval Workflow
Handle business order confirmation processes:
- Validate business approval requirements
- Confirm purchase order numbers and budgets
- Set payment terms for invoicing
- Trigger internal approval notifications
3. Quote-to-Order Conversion
Convert approved quotes to confirmed orders:
- Validate quote expiration and pricing
- Confirm final terms and conditions
- Process any quote modifications
- Initialize order processing workflows
4. Batch Order Processing
Handle bulk order confirmations:
- Process multiple draft orders simultaneously
- Validate payment processing for bulk orders
- Coordinate fulfillment timing across orders
- Manage inventory allocation priorities
Key Performance Points
Performance Optimization
- Validation Batching: Batch validation checks to reduce processing time
- Async Processing: Process non-critical steps asynchronously after confirmation
- Payment Caching: Cache payment validation results for faster processing
- Workflow Optimization: Streamline order-to-fulfillment transition
Security Considerations
- Authentication Validation: Always verify user authentication before order confirmation
- Payment Security: Secure handling of payment information during confirmation
- Order Integrity: Validate order hasn't been modified during confirmation process
- Audit Logging: Complete audit trail of order confirmation events
Flexibility Features
- Conditional Confirmation: Support different confirmation requirements by order type
- Payment Integration: Flexible payment processing for various payment methods
- Workflow Customization: Configurable post-confirmation workflows
- Notification Management: Customizable confirmation notifications
Integration Capabilities
- Store Integration: Update Order Store state after successful confirmation
- Payment Integration: Seamless integration with payment processing services
- Fulfillment Integration: Automatic fulfillment workflow initiation
- Notification Integration: Trigger confirmation emails and notifications
Technical Implementation
Complete Function Code
/**
* Set the status of a commercial order to "created"
* @param params - Request parameters including order ID and optional payment info
* @param config - Optional configuration for API call
* @returns Promise resolving to confirmed order with created status
*/
const setCommercialOrderStatusAsCreated = async (
params: SetCommercialOrderStatusAsCreatedRequest,
config?: Partial<DjustConfig>
): Promise<SetCommercialOrderStatusAsCreatedResponse> => {
try {
// Ensure user is authenticated before proceeding
await ensureAuthenticated();
const { orderId, paymentInfo } = params;
if (!orderId) {
throw new Error('The "orderId" parameter is required.');
}
// Set order status to created via API
const { data, error } =
await useFetch<SetCommercialOrderStatusAsCreatedResponse>(
`/api/commercial-orders/${orderId}/created`,
{
method: "PUT",
query: config,
body: { paymentInfo },
// Performance optimizations
key: `confirm-order-${orderId}-${Date.now()}`,
server: false,
timeout: 15000, // Longer timeout for order processing
}
);
if (error.value) {
throw new Error("Failed to set order status as 'created'.");
}
console.log("Order status set to created successfully");
return data.value as SetCommercialOrderStatusAsCreatedResponse;
} catch (error) {
console.error("Failed to set order status as 'created':", error);
throw new Error(
"Failed to set order status as 'created'. Please try again later."
);
}
};
Execution Flow
Step-by-Step Process
-
Authentication Verification
await ensureAuthenticated();
-
Parameter Validation
if (!orderId) throw new Error('The "orderId" parameter is required.');
-
Order Confirmation API Call
const { data, error } = await useFetch( `/api/commercial-orders/${orderId}/created`, { method: "PUT", body: { paymentInfo }, } );
-
Error Handling
if (error.value) throw new Error("Failed to set order status as 'created'.");
-
Success Response
return data.value as SetCommercialOrderStatusAsCreatedResponse;
-
Post-Confirmation Actions (in calling component)
// Update local state const orderStore = useOrderStore(); orderStore.updateOrder(response.order); // Navigate to confirmation page await navigateTo(`/orders/${response.order.id}/confirmation`); // Send confirmation notifications await sendOrderConfirmationEmail(response.order); // Show success notification toast.add({ title: "Order Confirmed", description: `Order ${response.order.reference} has been confirmed successfully`, color: "success", });
This comprehensive function provides robust order confirmation capabilities with proper validation, payment processing, and workflow integration for seamless order management.
Updated about 2 months ago