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

302 lines (255 loc) • 11.7 kB
require('dotenv').config(); const Dispatch9Client = require('../src/client'); /** * Address Creation Example * * This example demonstrates the complete workflow of: * 1. Creating addresses using the Dispatch9 Address API * 2. Using the returned address IDs in order creation * * Note: This SDK only handles the 4 core operations. * Address creation is done via direct API calls to /v1/addresses */ async function addressCreationExample() { console.log('šŸš€ Address Creation & Order Workflow Example\n'); try { // Initialize the SDK for order operations 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 for order operations\n'); // ========================================== // STEP 1: CREATE PICKUP ADDRESS // ========================================== console.log('šŸ“ Step 1: Creating pickup address...'); const pickupAddressData = { // REQUIRED FIELDS street: '123 Warehouse Boulevard', city: 'San Francisco', state: 'California', country: 'United States', // OPTIONAL FIELDS building: 'Building A', postalCode: '94105', contactName: 'Warehouse Manager', contactPhone: '+1-555-WAREHOUSE', contactEmail: 'warehouse@company.com', instructions: 'Use loading dock entrance. Ring bell twice.', // TIME WINDOW (Optional) timeWindow: { start: new Date('2024-01-15T08:00:00Z'), end: new Date('2024-01-15T17:00:00Z'), timezone: 'America/Los_Angeles', days: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], notes: 'Business hours only, closed for lunch 12-1pm' } }; // Create pickup address via direct API call const pickupResponse = await fetch(`${process.env.DISPATCH9_BASE_URL || 'https://api.dispatch9.com'}/v1/addresses`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.DISPATCH9_API_KEY }, body: JSON.stringify(pickupAddressData) }); if (!pickupResponse.ok) { throw new Error(`Failed to create pickup address: ${pickupResponse.status} ${pickupResponse.statusText}`); } const pickupAddress = await pickupResponse.json(); console.log(`āœ… Pickup address created!`); console.log(` ID: ${pickupAddress.id}`); console.log(` Address: ${pickupAddress.street}, ${pickupAddress.city}, ${pickupAddress.state}`); console.log(` Contact: ${pickupAddress.contactName} (${pickupAddress.contactPhone})\n`); // ========================================== // STEP 2: CREATE DELIVERY ADDRESS // ========================================== console.log('šŸ“ Step 2: Creating delivery address...'); const deliveryAddressData = { // REQUIRED FIELDS street: '456 Customer Street', city: 'Oakland', state: 'California', country: 'United States', // OPTIONAL FIELDS apartment: 'Apt 3B', postalCode: '94607', contactName: 'Sarah Johnson', contactPhone: '+1-555-CUSTOMER', contactEmail: 'sarah.j@email.com', instructions: 'Ring apartment 3B. Leave at door if no answer.', // TIME WINDOW (Optional) timeWindow: { start: new Date('2024-01-15T09:00:00Z'), end: new Date('2024-01-15T18:00:00Z'), timezone: 'America/Los_Angeles', days: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'], notes: 'Available most days, prefer afternoon delivery' } }; // Create delivery address via direct API call const deliveryResponse = await fetch(`${process.env.DISPATCH9_BASE_URL || 'https://api.dispatch9.com'}/v1/addresses`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.DISPATCH9_API_KEY }, body: JSON.stringify(deliveryAddressData) }); if (!deliveryResponse.ok) { throw new Error(`Failed to create delivery address: ${deliveryResponse.status} ${deliveryResponse.statusText}`); } const deliveryAddress = await deliveryResponse.json(); console.log(`āœ… Delivery address created!`); console.log(` ID: ${deliveryAddress.id}`); console.log(` Address: ${deliveryAddress.street}, ${deliveryAddress.apartment}, ${deliveryAddress.city}, ${deliveryAddress.state}`); console.log(` Contact: ${deliveryAddress.contactName} (${deliveryAddress.contactPhone})\n`); // ========================================== // STEP 3: CREATE SERVICE ADDRESS (Optional) // ========================================== console.log('šŸ“ Step 3: Creating service address...'); const serviceAddressData = { // REQUIRED FIELDS street: '789 Office Park Drive', city: 'Palo Alto', state: 'California', country: 'United States', // OPTIONAL FIELDS building: 'Suite 200', postalCode: '94301', contactName: 'IT Department', contactPhone: '+1-555-OFFICE', contactEmail: 'it@company.com', instructions: 'Check in at reception. Ask for IT department.', // GEOCODING DATA (Optional - usually populated automatically) formatted_address: '789 Office Park Drive, Suite 200, Palo Alto, CA 94301, USA', place_id: 'ChIJexample123456789', location: { type: 'Point', coordinates: [-122.1430195, 37.4419896] // [longitude, latitude] } }; // Create service address via direct API call const serviceResponse = await fetch(`${process.env.DISPATCH9_BASE_URL || 'https://api.dispatch9.com'}/v1/addresses`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.DISPATCH9_API_KEY }, body: JSON.stringify(serviceAddressData) }); if (!serviceResponse.ok) { throw new Error(`Failed to create service address: ${serviceResponse.status} ${serviceResponse.statusText}`); } const serviceAddress = await serviceResponse.json(); console.log(`āœ… Service address created!`); console.log(` ID: ${serviceAddress.id}`); console.log(` Address: ${serviceAddress.street}, ${serviceAddress.building}, ${serviceAddress.city}, ${serviceAddress.state}`); console.log(` Contact: ${serviceAddress.contactName} (${serviceAddress.contactPhone})\n`); // ========================================== // STEP 4: GET EXISTING CLIENT // ========================================== console.log('šŸ‘¤ Step 4: Getting existing client for order...'); 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 the basic-usage.js example.'); } const client = clients.results[0]; console.log(`āœ… Using client: ${client.name} (${client.id})\n`); // ========================================== // STEP 5: CREATE ORDER USING ADDRESS IDs // ========================================== console.log('šŸ“¦ Step 5: Creating order with the created addresses...'); const order = await dispatch9.createOrder({ orderTotal: 299.99, client: client.id, orderCurrency: 'USD', hasGoods: true, priority: 7, // USE THE ADDRESS IDs FROM STEPS 1-3 pickupLocation: pickupAddress.id, deliveryLocation: deliveryAddress.id, serviceLocation: serviceAddress.id, // Optional items: [ { SKU: 'LAPTOP001', itemName: 'Business Laptop', price: 299.99, quantity: 1, category: 'Electronics', description: 'High-performance business laptop', weight: 2.5, weightUnit: 'kg', handling: 'Fragile - handle with care' } ], specialInstructions: 'High-value electronics - require signature and photo proof', customerNotes: 'Customer prefers afternoon delivery between 2-4 PM', requiredProof: { signature: true, photo: true }, metadata: { addressCreationExample: true, pickupAddressId: pickupAddress.id, deliveryAddressId: deliveryAddress.id, serviceAddressId: serviceAddress.id } }); console.log(`āœ… Order created successfully!`); console.log(` Order ID: ${order.id}`); console.log(` Total: $${order.orderTotal}`); console.log(` Status: ${order.status}`); console.log(` Pickup: ${pickupAddress.street} (${pickupAddress.id})`); console.log(` Delivery: ${deliveryAddress.street} (${deliveryAddress.id})`); console.log(` Service: ${serviceAddress.street} (${serviceAddress.id})\n`); // ========================================== // STEP 6: SUMMARY // ========================================== console.log('šŸŽ‰ Address Creation & Order Workflow Completed!'); console.log('═'.repeat(60)); console.log('šŸ“‹ Summary of Created Resources:'); console.log(); console.log('šŸ“ ADDRESSES CREATED:'); console.log(` āœ“ Pickup: ${pickupAddress.id} - ${pickupAddress.street}, ${pickupAddress.city}`); console.log(` āœ“ Delivery: ${deliveryAddress.id} - ${deliveryAddress.street}, ${deliveryAddress.city}`); console.log(` āœ“ Service: ${serviceAddress.id} - ${serviceAddress.street}, ${serviceAddress.city}`); console.log(); console.log('šŸ“¦ ORDER CREATED:'); console.log(` āœ“ Order: ${order.id} - $${order.orderTotal} (${order.status})`); console.log(` āœ“ Client: ${client.name} (${client.id})`); console.log(` āœ“ Items: ${order.items.length} items`); console.log(); console.log('šŸ”‘ KEY TAKEAWAYS:'); console.log(' • Addresses must be created BEFORE orders'); console.log(' • Address creation requires: street, city, state, country'); console.log(' • Contact info and instructions are optional but recommended'); console.log(' • Address IDs are used as references in orders'); console.log(' • Time windows help optimize delivery scheduling'); } catch (error) { console.error('āŒ Error in address creation example:', error.message); if (error.message.includes('Failed to create')) { console.error('\nšŸ”§ Address Creation Troubleshooting:'); console.error(' • Check that all required fields are provided: street, city, state, country'); console.error(' • Ensure contactPhone follows international format: +1-555-0123'); console.error(' • Verify contactEmail is a valid email address'); console.error(' • Check that coordinates are valid: longitude [-180,180], latitude [-90,90]'); } else if (error.message.includes('Authentication failed')) { console.error('\nšŸ”§ Authentication 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šŸ”§ Permission Troubleshooting:'); console.error(' • Your API key needs: addresses.create, orders.create, clients.read'); console.error(' • Contact support if you need additional permissions'); } process.exit(1); } } // Run the example if (require.main === module) { addressCreationExample(); } module.exports = addressCreationExample;