UNPKG

@dispatch9/client-sdk

Version:

Official Node.js SDK for Dispatch9 API - Complete solution with email/phone client creation, order management, client management, and dual-method authentication

285 lines (249 loc) • 10.4 kB
require('dotenv').config(); const Dispatch9Client = require('../src/client'); /** * Order Management Example * Demonstrates comprehensive order operations: * - Create orders with different configurations * - Update order status and details * - Handle various order types (goods, services, workers) * - Error handling and validation */ async function orderManagementExample() { console.log('šŸš€ Dispatch9 SDK - Order Management Example\n'); try { // Initialize the SDK const dispatch9 = new Dispatch9Client({ apiKey: process.env.DISPATCH9_API_KEY, baseURL: process.env.DISPATCH9_BASE_URL || 'https://api.dispatch9.com', debug: true }); console.log('āœ… SDK initialized successfully\n'); // First, let's get an existing client to use for orders console.log('šŸ“‹ Getting existing clients...'); const clients = await dispatch9.getClients({ limit: 1 }); if (!clients.results || clients.results.length === 0) { console.log('āŒ No clients found. Please create a client first.'); return; } const clientId = clients.results[0].id; console.log(`āœ… Using client: ${clients.results[0].name} (${clientId})\n`); // ========================================== // 1. CREATE DELIVERY ORDER WITH GOODS // ========================================== console.log('šŸ“¦ Step 1: Creating delivery order with goods...'); console.log(' Note: Addresses must be created first via POST /v1/addresses'); console.log(' Required: {street, city, state, country}'); console.log(' Optional: {building, apartment, postalCode, contactName, contactPhone, instructions}'); const deliveryOrder = await dispatch9.createOrder({ orderTotal: 89.97, client: clientId, orderCurrency: 'USD', hasGoods: true, priority: 5, items: [ { SKU: 'LAPTOP001', itemName: 'Business Laptop', price: 799.99, quantity: 1, category: 'Electronics', description: '15-inch business laptop with warranty', weight: 2.5, weightUnit: 'kg', dimensionH: 25, dimensionW: 35, dimensionL: 2, dimensionUnit: 'cm', packaging: 'Original box with foam padding', handling: 'Fragile - handle with care' }, { SKU: 'MOUSE001', itemName: 'Wireless Mouse', price: 29.99, quantity: 2, category: 'Electronics', description: 'Ergonomic wireless mouse', weight: 0.15, weightUnit: 'kg' } ], pickupLocation: '507f1f77bcf86cd799439012', // ID from created pickup address deliveryLocation: '507f1f77bcf86cd799439013', // ID from created delivery address specialInstructions: 'Deliver to reception desk during business hours', customerNotes: 'Important business equipment - handle carefully', requiredProof: { signature: true, photo: true } }); console.log(`āœ… Delivery order created!`); console.log(` Order ID: ${deliveryOrder.id}`); console.log(` Status: ${deliveryOrder.status}`); console.log(` Total: $${deliveryOrder.orderTotal}`); console.log(` Items: ${deliveryOrder.items.length}\n`); // ========================================== // 2. CREATE SERVICE ORDER // ========================================== console.log('šŸ”§ Step 2: Creating service order...'); const serviceOrder = await dispatch9.createOrder({ orderTotal: 150.00, client: clientId, hasServices: true, priority: 3, services: [ { serviceCode: 'INSTALL001', serviceName: 'Laptop Setup and Installation', category: 'installation', description: 'Complete laptop setup with software installation', estimatedDuration: 120, // 2 hours workersRequired: 1, // Single technician required price: 150.00, currency: 'USD', requirements: ['Power outlet access', 'Internet connection'], notes: 'Includes data transfer from old device' } ], serviceLocation: '507f1f77bcf86cd799439013', // ID from created service address specialInstructions: 'Call customer 30 minutes before arrival', customerNotes: 'Customer will be available after 2 PM' }); console.log(`āœ… Service order created!`); console.log(` Order ID: ${serviceOrder.id}`); console.log(` Status: ${serviceOrder.status}`); console.log(` Total: $${serviceOrder.orderTotal}`); console.log(` Services: ${serviceOrder.services.length}\n`); // ========================================== // 3. UPDATE ORDER STATUS // ========================================== console.log('šŸ“ Step 3: Updating delivery order status...'); const statusUpdate = await dispatch9.updateOrder(deliveryOrder.id, { status: 'confirmed', statusNotes: 'Order confirmed by customer service team', priority: 7 // Increased priority }); console.log(`āœ… Order status updated!`); console.log(` Order ID: ${statusUpdate.id}`); console.log(` New Status: ${statusUpdate.status}`); console.log(` Priority: ${statusUpdate.priority}\n`); // ========================================== // 4. UPDATE ORDER ITEMS // ========================================== console.log('šŸ“ Step 4: Updating order items...'); const itemsUpdate = await dispatch9.updateOrder(deliveryOrder.id, { specialInstructions: 'URGENT: Customer needs delivery by 5 PM today', items: [ { SKU: 'LAPTOP001', itemName: 'Business Laptop (Premium Model)', price: 899.99, // Price updated quantity: 1, category: 'Electronics', description: '15-inch premium business laptop with extended warranty', weight: 2.5, weightUnit: 'kg', dimensionH: 25, dimensionW: 35, dimensionL: 2, dimensionUnit: 'cm', packaging: 'Original box with foam padding', handling: 'Fragile - handle with care', notes: 'Upgraded to premium model per customer request' }, { SKU: 'MOUSE001', itemName: 'Wireless Mouse', price: 29.99, quantity: 2, category: 'Electronics', description: 'Ergonomic wireless mouse', weight: 0.15, weightUnit: 'kg' }, { SKU: 'PAD001', itemName: 'Mouse Pad', price: 15.99, quantity: 2, category: 'Electronics', description: 'Premium mouse pad with wrist support', weight: 0.2, weightUnit: 'kg' } ] }); console.log(`āœ… Order items updated!`); console.log(` Order ID: ${itemsUpdate.id}`); console.log(` Updated Items: ${itemsUpdate.items.length}`); console.log(` Special Instructions: ${itemsUpdate.specialInstructions}\n`); // ========================================== // 5. UPDATE SERVICE ORDER // ========================================== console.log('šŸ“ Step 5: Updating service order...'); const serviceUpdate = await dispatch9.updateOrder(serviceOrder.id, { status: 'in_progress', statusNotes: 'Technician assigned and en route', customerNotes: 'Customer confirmed availability at 2:30 PM', metadata: { assignedTechnician: 'John Smith', estimatedArrival: '2024-01-15T14:30:00Z', customerPhone: '+1-555-0123' } }); console.log(`āœ… Service order updated!`); console.log(` Order ID: ${serviceUpdate.id}`); console.log(` Status: ${serviceUpdate.status}`); console.log(` Assigned: ${serviceUpdate.metadata?.assignedTechnician || 'N/A'}\n`); // ========================================== // 6. DEMONSTRATE ERROR HANDLING // ========================================== console.log('āš ļø Step 6: Demonstrating error handling...'); try { // Try to update with invalid status await dispatch9.updateOrder(deliveryOrder.id, { status: 'invalid_status' }); } catch (error) { console.log(`āœ… Validation error caught: ${error.message}`); } try { // Try to update non-existent order await dispatch9.updateOrder('invalid_order_id', { status: 'confirmed' }); } catch (error) { console.log(`āœ… Not found error caught: ${error.message}`); } console.log('\nšŸŽ‰ Order management example completed successfully!'); console.log('\nšŸ“Š Summary:'); console.log(` āœ“ Created delivery order: ${deliveryOrder.id}`); console.log(` āœ“ Created service order: ${serviceOrder.id}`); console.log(` āœ“ Updated order status: ${statusUpdate.status}`); console.log(` āœ“ Updated order items: ${itemsUpdate.items.length} items`); console.log(` āœ“ Updated service order: ${serviceUpdate.status}`); console.log(` āœ“ Demonstrated error handling`); } catch (error) { console.error('āŒ Error in order management example:', error.message); // Provide helpful troubleshooting information if (error.message.includes('Authentication failed')) { console.error('\nšŸ”§ Troubleshooting:'); console.error(' • Check your DISPATCH9_API_KEY in the .env file'); console.error(' • Ensure the API key is valid and not expired'); } else if (error.message.includes('Access forbidden')) { console.error('\nšŸ”§ Troubleshooting:'); console.error(' • Your API key may not have the required permissions'); console.error(' • Required permissions: orders.create, orders.update, clients.read'); } else if (error.message.includes('Client ID is required')) { console.error('\nšŸ”§ Troubleshooting:'); console.error(' • Make sure you have at least one client in your system'); console.error(' • Run the basic-usage.js example first to create a client'); } process.exit(1); } } // Run the example if (require.main === module) { orderManagementExample(); } module.exports = orderManagementExample;