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

334 lines (291 loc) • 14.6 kB
require('dotenv').config(); const Dispatch9Client = require('../src/client'); /** * Service Workers Example * Demonstrates the new workersRequired field for services: * - Single worker services * - Multi-worker services * - Team-based service operations * - Resource planning and allocation */ async function serviceWorkersExample() { console.log('šŸš€ Dispatch9 SDK - Service Workers Example\n'); console.log('šŸ“– Demonstrating workersRequired field for better resource planning\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: false }); console.log('āœ… SDK initialized successfully\n'); // Get an existing client console.log('šŸ‘¤ Getting existing client...'); const clients = await dispatch9.getClients({ limit: 1 }); if (!clients.results || clients.results.length === 0) { throw new Error('No clients found. Please create a client first using basic-usage.js'); } const clientId = clients.results[0].id; console.log(`āœ… Using client: ${clients.results[0].name} (${clientId})\n`); // ========================================== // EXAMPLE 1: SINGLE WORKER SERVICE // ========================================== console.log('šŸ‘¤ EXAMPLE 1: Single Worker Service'); console.log('═'.repeat(50)); const singleWorkerOrder = await dispatch9.createOrder({ orderTotal: 75.00, client: clientId, hasServices: true, priority: 5, services: [ { serviceCode: 'CLEAN001', serviceName: 'Office Cleaning', category: 'cleaning', description: 'Standard office cleaning service', estimatedDuration: 90, price: 75.00, requirements: [ { type: 'workers', count: 1, description: 'Single cleaner required' }, 'Cleaning supplies', 'Vacuum cleaner' ], notes: 'Focus on high-traffic areas' } ], serviceLocation: '507f1f77bcf86cd799439014', // Replace with actual address ID specialInstructions: 'Service can be performed during business hours', customerNotes: 'Please be quiet during meetings' }); console.log(`āœ… Single worker service order created!`); console.log(` Order ID: ${singleWorkerOrder.id}`); console.log(` Service: ${singleWorkerOrder.services[0].serviceName}`); console.log(` Workers Required: ${singleWorkerOrder.services[0].workersRequired}`); console.log(` Estimated Duration: ${singleWorkerOrder.services[0].estimatedDuration} minutes\n`); // ========================================== // EXAMPLE 2: MULTI-WORKER SERVICE // ========================================== console.log('šŸ‘„ EXAMPLE 2: Multi-Worker Service'); console.log('═'.repeat(50)); const multiWorkerOrder = await dispatch9.createOrder({ orderTotal: 450.00, client: clientId, hasServices: true, priority: 7, services: [ { serviceCode: 'MOVE001', serviceName: 'Furniture Moving', category: 'maintenance', description: 'Move heavy furniture and equipment', estimatedDuration: 180, price: 300.00, requirements: [ { type: 'workers', count: 3, description: 'Team of 3 movers required' }, 'Moving equipment', 'Protective gear', 'Dolly' ], notes: 'Heavy lifting required - experienced team needed' }, { serviceCode: 'SETUP001', serviceName: 'Office Setup', category: 'installation', description: 'Set up workstations and connect equipment', estimatedDuration: 120, price: 150.00, requirements: [ { type: 'workers', count: 2, description: '2 technicians required' }, 'Tools', 'Cable management', { type: 'qualifications', description: 'Technical knowledge', mandatory: true } ], notes: 'Requires coordination with IT department' } ], serviceLocation: '507f1f77bcf86cd799439015', // Replace with actual address ID specialInstructions: 'Coordinate with building management for elevator access', customerNotes: 'Service must be completed over weekend' }); console.log(`āœ… Multi-worker service order created!`); console.log(` Order ID: ${multiWorkerOrder.id}`); console.log(` Services: ${multiWorkerOrder.services.length}`); multiWorkerOrder.services.forEach((service, index) => { const workerReq = service.requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const workerCount = workerReq?.count || workerReq?.workers || workerReq?.numberOfWorkers || 1; console.log(` ${index + 1}. ${service.serviceName}: ${workerCount} workers`); }); const totalMultiWorkers = multiWorkerOrder.services.reduce((sum, service) => { const workerReq = service.requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const workerCount = workerReq?.count || workerReq?.workers || workerReq?.numberOfWorkers || 1; return sum + workerCount; }, 0); console.log(` Total Workers Needed: ${totalMultiWorkers}\n`); // ========================================== // EXAMPLE 3: SPECIALIZED TEAM SERVICE // ========================================== console.log('šŸ”§ EXAMPLE 3: Specialized Team Service'); console.log('═'.repeat(50)); const teamServiceOrder = await dispatch9.createOrder({ orderTotal: 800.00, client: clientId, hasServices: true, priority: 9, services: [ { serviceCode: 'HVAC001', serviceName: 'HVAC System Installation', category: 'installation', description: 'Install new HVAC system with ductwork', estimatedDuration: 480, // 8 hours price: 600.00, requirements: [ { type: 'workers', count: 4, description: 'Specialized HVAC team required' }, { type: 'tools', description: 'HVAC tools', mandatory: true }, { type: 'equipment', description: 'Electrical equipment', mandatory: true }, 'Safety gear', { type: 'qualifications', description: 'Certified technicians', mandatory: true } ], notes: 'Requires licensed HVAC technicians and electrical work' }, { serviceCode: 'INSPECT001', serviceName: 'System Inspection & Testing', category: 'inspection', description: 'Test and certify new HVAC installation', estimatedDuration: 60, price: 200.00, requirements: [ { type: 'workers', count: 1, description: 'Certified inspector required' }, { type: 'equipment', description: 'Testing equipment', mandatory: true }, { type: 'qualifications', description: 'Certification authority', mandatory: true } ], notes: 'Must be performed by certified inspector' } ], serviceLocation: '507f1f77bcf86cd799439016', // Replace with actual address ID specialInstructions: 'Power must be shut off during installation - coordinate with facilities', customerNotes: 'Critical for business operations - minimize downtime' }); console.log(`āœ… Specialized team service order created!`); console.log(` Order ID: ${teamServiceOrder.id}`); console.log(` Complex Installation: ${teamServiceOrder.services[0].serviceName}`); const hvacWorkerReq = teamServiceOrder.services[0].requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const hvacWorkerCount = hvacWorkerReq?.count || hvacWorkerReq?.workers || hvacWorkerReq?.numberOfWorkers || 1; console.log(` Team Size: ${hvacWorkerCount} specialists`); console.log(` Duration: ${teamServiceOrder.services[0].estimatedDuration / 60} hours`); console.log(` Follow-up Inspection: ${teamServiceOrder.services[1].serviceName}`); const inspectorWorkerReq = teamServiceOrder.services[1].requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const inspectorWorkerCount = inspectorWorkerReq?.count || inspectorWorkerReq?.workers || inspectorWorkerReq?.numberOfWorkers || 1; console.log(` Inspector: ${inspectorWorkerCount} certified professional\n`); // ========================================== // EXAMPLE 4: UPDATE SERVICE WORKERS // ========================================== console.log('šŸ“ EXAMPLE 4: Update Service Workers'); console.log('═'.repeat(50)); const updatedOrder = await dispatch9.updateOrder(multiWorkerOrder.id, { services: [ { serviceCode: 'MOVE001', serviceName: 'Furniture Moving (Expanded Team)', category: 'maintenance', description: 'Move heavy furniture and equipment - additional items discovered', estimatedDuration: 240, // Extended time price: 400.00, // Adjusted price requirements: [ { type: 'workers', count: 5, description: 'Expanded team - increased from 3 to 5 workers' }, 'Moving equipment', 'Protective gear', 'Dolly', 'Additional truck' ], notes: 'Expanded scope - more items than initially assessed' }, { serviceCode: 'SETUP001', serviceName: 'Office Setup', category: 'installation', description: 'Set up workstations and connect equipment', estimatedDuration: 120, price: 150.00, requirements: [ { type: 'workers', count: 2, description: 'Same team size - 2 technicians' }, 'Tools', 'Cable management', { type: 'qualifications', description: 'Technical knowledge', mandatory: true } ], notes: 'Requires coordination with IT department' } ], statusNotes: 'Service scope expanded - additional workers assigned', priority: 8 // Increased priority }); console.log(`āœ… Service workers updated!`); console.log(` Order ID: ${updatedOrder.id}`); console.log(` Updated Service: ${updatedOrder.services[0].serviceName}`); const originalWorkerReq = multiWorkerOrder.services[0].requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const originalWorkerCount = originalWorkerReq?.count || originalWorkerReq?.workers || originalWorkerReq?.numberOfWorkers || 1; const updatedWorkerReq = updatedOrder.services[0].requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const updatedWorkerCount = updatedWorkerReq?.count || updatedWorkerReq?.workers || updatedWorkerReq?.numberOfWorkers || 1; console.log(` Workers: ${originalWorkerCount} → ${updatedWorkerCount} (increased)`); console.log(` Duration: ${multiWorkerOrder.services[0].estimatedDuration} → ${updatedOrder.services[0].estimatedDuration} minutes (extended)\n`); // ========================================== // RESOURCE PLANNING SUMMARY // ========================================== console.log('šŸ“Š RESOURCE PLANNING SUMMARY'); console.log('═'.repeat(50)); const allOrders = [singleWorkerOrder, multiWorkerOrder, teamServiceOrder, updatedOrder]; let totalWorkersNeeded = 0; let totalDuration = 0; let serviceBreakdown = {}; allOrders.forEach(order => { order.services.forEach(service => { const workerReq = service.requirements?.find(req => typeof req === 'object' && req.type === 'workers'); const workerCount = workerReq?.count || workerReq?.workers || workerReq?.numberOfWorkers || 1; totalWorkersNeeded += workerCount; totalDuration += service.estimatedDuration; if (!serviceBreakdown[service.category]) { serviceBreakdown[service.category] = { count: 0, workers: 0 }; } serviceBreakdown[service.category].count++; serviceBreakdown[service.category].workers += workerCount; }); }); console.log(`šŸ“ˆ Resource Requirements:`); console.log(` Total Orders: ${allOrders.length}`); console.log(` Total Services: ${allOrders.reduce((sum, o) => sum + o.services.length, 0)}`); console.log(` Total Workers Needed: ${totalWorkersNeeded}`); console.log(` Total Service Hours: ${Math.round(totalDuration / 60)} hours`); console.log(` Average Workers per Service: ${Math.round(totalWorkersNeeded / allOrders.reduce((sum, o) => sum + o.services.length, 0))}`); console.log(`\nšŸ”§ Service Category Breakdown:`); Object.entries(serviceBreakdown).forEach(([category, data]) => { console.log(` ${category.charAt(0).toUpperCase() + category.slice(1)}: ${data.count} services, ${data.workers} workers`); }); console.log('\nšŸŽ‰ Service Workers Example Completed Successfully!'); console.log('\nšŸš€ Key Benefits of workersRequired Field:'); console.log(' āœ“ Better resource planning and allocation'); console.log(' āœ“ Accurate scheduling based on team size'); console.log(' āœ“ Cost estimation with labor requirements'); console.log(' āœ“ Capacity management for service operations'); console.log(' āœ“ Improved customer expectations management'); } catch (error) { console.error('āŒ Error in service workers example:', error.message); if (error.message.includes('workersRequired is required')) { console.error('\nšŸ”§ Service Validation:'); console.error(' • workersRequired is now a required field for all services'); console.error(' • Must be between 1 and 10 workers'); console.error(' • Helps with resource planning and scheduling'); } else if (error.message.includes('No clients found')) { console.error('\nšŸ”§ Setup Required:'); console.error(' • Run basic-usage.js first to create a client'); console.error(' • Or use client-management.js to create test clients'); } process.exit(1); } } // Run the example if (require.main === module) { serviceWorkersExample(); } module.exports = serviceWorkersExample;