Update Commercial order shipping Address
The updateCommercialOrderShippingAddress
function updates the shipping address for an existing commercial order. This function is essential for order management workflows where customers need to change delivery addresses before shipment or when address corrections are required. It enables flexible order management while maintaining proper audit trails and validation.
This function is typically used during order processing phases before the order transitions to fulfillment stages, ensuring that products are delivered to the correct address as specified by the customer.
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 Address Validation participant DB as Database User->>Component: Update Shipping Address Component->>UCO: updateCommercialOrderShippingAddress(params) UCO->>Auth: ensureAuthenticated() alt Authentication Valid Auth-->>UCO: Authenticated UCO->>API: PUT /api/commercial-orders/{orderId}/shipping-address API->>Validation: Validate Address ID Validation-->>API: Address Valid API->>DB: Update Order Shipping Address DB-->>API: Update Successful API-->>UCO: Update Response UCO-->>Component: Success Response Component-->>User: Confirmation Message else Authentication Failed Auth-->>UCO: Authentication Error UCO-->>Component: Error Response Component-->>User: Redirect to Login else Invalid Address Validation-->>API: Invalid Address ID API-->>UCO: 400 Error UCO-->>Component: Validation Error Component-->>User: Show Validation Message else Order Not Modifiable API-->>UCO: 412 Error UCO-->>Component: Precondition Failed Component-->>User: Show Order Status Message end
Call Parameters
Request Interface
interface UpdateCommercialOrderShippingAddressRequest {
orderId: string;
shippingAddressId: string;
}
Parameters Detail
Parameter | Type | Required | Default | Example | Business Impact |
---|---|---|---|---|---|
orderId | string | ✅ | - | "co-123456" | Identifies the order to update |
shippingAddressId | string | ✅ | - | "addr-789012" | New shipping address to assign to the order |
Example Call
const { updateCommercialOrderShippingAddress } = useCommercialOrder();
// Update shipping address for an order
const updateResult = await updateCommercialOrderShippingAddress({
orderId: "co-123456",
shippingAddressId: "addr-789012",
});
console.log("Shipping address updated:", updateResult.success);
Composable Returns
Response Interface
interface UpdateCommercialOrderShippingAddressResponse {
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": 18.0,
"currency": "EUR",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-16T15:45:00Z",
"shippingInformation": {
"type": "standard",
"addressId": "addr-789012",
"address": {
"id": "addr-789012",
"name": "John Doe",
"company": "Acme Corp",
"street": "456 New Business Avenue",
"city": "Lyon",
"postalCode": "69001",
"country": "France",
"phone": "+33 1 23 45 67 89",
"email": "[email protected]"
},
"estimatedDeliveryDate": "2024-01-20T00:00:00Z",
"carrier": "Colissimo",
"notes": "Updated shipping address"
},
"customFields": [
{
"externalId": "address-change-reason",
"value": "Customer requested address change",
"type": "text",
"label": "Address Change Reason"
}
]
},
"message": "Shipping address updated 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 address ID or order ID | Log validation error | "Invalid address or order identifier" | Verify address and order IDs |
403 | Insufficient permissions | Log access attempt | "You don't have permission to modify this order" | Contact administrator |
404 | Order or address not found | Log search attempt | "Order or address not found" | Verify order and address exist |
409 | Address already assigned | Log conflict | "This address is already assigned to the order" | Check current order address |
412 | Order not modifiable | Log status check | "Order cannot be modified in current status" | Check order status |
422 | Address validation failed | Log validation failure | "Address validation failed" | Check address format and completeness |
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 |
Error Handling Implementation
const updateCommercialOrderShippingAddress = async (
params: UpdateCommercialOrderShippingAddressRequest
) => {
try {
await ensureAuthenticated();
const { data, error } =
await useFetch<UpdateCommercialOrderShippingAddressResponse>(
`/api/commercial-orders/${params.orderId}/shipping-address`,
{
method: "PUT",
body: { shippingAddressId: params.shippingAddressId },
retry: 2,
retryDelay: 1000,
timeout: 10000,
}
);
if (error.value) {
throw new Error(
`Failed to update shipping address: ${error.value.statusMessage}`
);
}
return data.value as UpdateCommercialOrderShippingAddressResponse;
} catch (error) {
const toast = useToast();
if (error.statusCode === 401) {
const { logout } = useDjustAuth();
await logout();
await navigateTo("/auth/login");
} else if (error.statusCode === 412) {
toast.add({
title: "Cannot Modify Order",
description: "This order cannot be modified in its current status",
color: "warning",
});
} else if (error.statusCode === 404) {
toast.add({
title: "Not Found",
description: "Order or address not found",
color: "warning",
});
} else if (error.statusCode === 422) {
toast.add({
title: "Address Validation Failed",
description: "Please check the address information and try again",
color: "warning",
});
} else {
toast.add({
title: "Update Failed",
description: "Failed to update shipping address. Please try again.",
color: "error",
});
}
throw error;
}
};
Use Cases
1. Customer Address Change Request
Allow customers to update shipping addresses before shipment:
- Validate new address against customer's address book
- Check order status to ensure modification is allowed
- Update delivery estimates based on new location
- Send confirmation to customer about address change
2. Address Correction Workflow
Enable address corrections for delivery optimization:
- Verify address validity and deliverability
- Update shipping costs based on new location
- Adjust delivery timeframes for new destination
- Maintain audit trail of address changes
3. Business Relocation Handling
Manage address updates for business customers:
- Support multiple delivery locations for business accounts
- Handle address validation for commercial properties
- Update default shipping preferences if requested
- Coordinate with logistics partners for delivery changes
4. Emergency Address Changes
Handle urgent address modification requests:
- Validate time constraints for address changes
- Check order fulfillment status before allowing changes
- Expedite processing for time-sensitive deliveries
- Notify relevant parties of address modifications
Key Performance Points
Performance Optimization
- Validation Caching: Cache address validation results to reduce API calls
- Batch Updates: Support multiple address changes in single transaction
- Async Processing: Process address validation asynchronously when possible
- Delivery Estimation: Update shipping costs and delivery dates efficiently
Security Considerations
- Authentication Validation: Always verify user authentication before address updates
- Permission Checking: Validate user permissions for order modifications
- Address Validation: Ensure address belongs to customer or is valid business address
- Audit Logging: Log all address changes for security and compliance tracking
Flexibility Features
- Multiple Address Types: Support different address types (shipping, billing, pickup)
- Address Book Integration: Seamless integration with customer address management
- Validation Rules: Configurable address validation rules by region
- Status Checking: Intelligent order status validation before allowing changes
Integration Capabilities
- Store Integration: Update Order Store state after successful address changes
- Component Integration: Reactive UI updates for address displays
- Shipping Integration: Automatic recalculation of shipping costs and times
- Notification Integration: Trigger notifications to relevant parties
Technical Implementation
Complete Function Code
/**
* Update the shipping address of a commercial order
* @param params - Request parameters including order ID and new address ID
* @param config - Optional configuration for API call
* @returns Promise resolving to updated order with new shipping address
*/
const updateCommercialOrderShippingAddress = async (
params: UpdateCommercialOrderShippingAddressRequest,
config?: Partial<DjustConfig>
): Promise<UpdateCommercialOrderShippingAddressResponse> => {
try {
// Ensure user is authenticated before proceeding
await ensureAuthenticated();
const { orderId, shippingAddressId } = params;
if (!orderId) {
throw new Error('The "orderId" parameter is required.');
}
if (!shippingAddressId) {
throw new Error('The "shippingAddressId" parameter is required.');
}
// Update shipping address via API
const { data, error } =
await useFetch<UpdateCommercialOrderShippingAddressResponse>(
`/api/commercial-orders/${orderId}/shipping-address`,
{
method: "PUT",
query: config,
body: { shippingAddressId },
// Performance optimizations
key: `update-shipping-address-${orderId}-${Date.now()}`,
server: false,
}
);
if (error.value) {
throw new Error("Failed to update shipping address.");
}
console.log("Shipping address updated successfully");
return data.value as UpdateCommercialOrderShippingAddressResponse;
} catch (error) {
console.error("Failed to update shipping address:", error);
throw new Error(
"Failed to update shipping address. 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.'); if (!shippingAddressId) throw new Error('The "shippingAddressId" parameter is required.');
-
API Call Execution
const { data, error } = await useFetch( `/api/commercial-orders/${orderId}/shipping-address`, { method: "PUT", body: { shippingAddressId }, } );
-
Error Handling
if (error.value) throw new Error("Failed to update shipping address.");
-
Success Response
return data.value as UpdateCommercialOrderShippingAddressResponse;
-
Post-Update Actions (in calling component)
// Update local state const orderStore = useOrderStore(); orderStore.updateOrder(response.order); // Show success notification toast.add({ title: "Address Updated", description: "Shipping address has been updated successfully", color: "success", }); // Recalculate shipping costs if needed await recalculateShippingCosts(response.order.id);
This comprehensive function provides robust address update capabilities with proper validation, error handling, and integration with the broader order management system.
Updated about 2 months ago