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

325 lines (285 loc) • 11.4 kB
require('dotenv').config(); const Dispatch9Client = require('../src/client'); /** * Client Management Example * Demonstrates comprehensive client operations: * - Create clients with different configurations * - Get clients with filtering * - Update client information and settings * - Handle various client types and business models * - Error handling and validation */ async function clientManagementExample() { console.log('šŸš€ Dispatch9 SDK - Client 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'); // ========================================== // 1. CREATE RESTAURANT CLIENT // ========================================== console.log('šŸ• Step 1: Creating restaurant client...'); const restaurantClient = await dispatch9.createClient({ name: 'Mario\'s Pizza Palace', email: 'orders@mariospizza.com', businessType: 'restaurant', websiteURL: 'https://www.mariospizza.com', taxId: '12-3456789', webhookURL: 'https://www.mariospizza.com/webhooks/dispatch9', apiConfig: { enabled: true, rateLimit: 500 }, orderSettings: { autoAccept: true, autoAssign: false, maxOrdersPerHour: 40, preparationTime: 25, deliveryRadius: 8.0 }, permissions: { modify: false, delete: false, createOrders: true, viewOrders: true }, authentication: { enablePortalAccess: true, firstName: 'Mario', lastName: 'Rossi', businessName: 'Mario\'s Pizza Palace', phone: '+1-555-0123' } }); console.log(`āœ… Restaurant client created!`); console.log(` ID: ${restaurantClient.id}`); console.log(` Name: ${restaurantClient.name}`); console.log(` Business Type: ${restaurantClient.businessType}`); console.log(` Max Orders/Hour: ${restaurantClient.orderSettings?.maxOrdersPerHour || 'N/A'}\n`); // ========================================== // 2. CREATE RETAIL CLIENT // ========================================== console.log('šŸ›ļø Step 2: Creating retail client...'); const retailClient = await dispatch9.createClient({ name: 'TechGadgets Pro', email: 'fulfillment@techgadgets.com', businessType: 'retail', websiteURL: 'https://www.techgadgets.com', logoURL: 'https://www.techgadgets.com/logo.png', taxId: '98-7654321', integrations: [ { platform: 'shopify', enabled: true, config: { storeUrl: 'techgadgets.myshopify.com', apiVersion: '2023-10' }, webhookSecret: 'webhook_secret_123', syncOrders: true }, { platform: 'woocommerce', enabled: false, config: {}, syncOrders: false } ], orderSettings: { autoAccept: false, autoAssign: true, maxOrdersPerHour: 100, preparationTime: 60, deliveryRadius: 25.0 }, permissions: { modify: true, delete: false, createOrders: true, viewOrders: true } }); console.log(`āœ… Retail client created!`); console.log(` ID: ${retailClient.id}`); console.log(` Name: ${retailClient.name}`); console.log(` Integrations: ${retailClient.integrations?.length || 0}`); console.log(` Delivery Radius: ${retailClient.orderSettings?.deliveryRadius || 'N/A'} km\n`); // ========================================== // 3. GET CLIENTS WITH FILTERING // ========================================== console.log('šŸ“‹ Step 3: Retrieving clients with filtering...'); // Get all restaurant clients const restaurants = await dispatch9.getClients({ businessType: 'restaurant', status: 'active', limit: 10, sortBy: 'createdAt:desc' }); console.log(`āœ… Found ${restaurants.results.length} restaurant clients`); if (restaurants.results.length > 0) { console.log(' Restaurant clients:'); restaurants.results.forEach((client, index) => { console.log(` ${index + 1}. ${client.name} - ${client.email}`); }); } // Get all retail clients const retailers = await dispatch9.getClients({ businessType: 'retail', limit: 5 }); console.log(`āœ… Found ${retailers.results.length} retail clients`); if (retailers.results.length > 0) { console.log(' Retail clients:'); retailers.results.forEach((client, index) => { console.log(` ${index + 1}. ${client.name} - ${client.email}`); }); } console.log(); // ========================================== // 4. UPDATE RESTAURANT CLIENT // ========================================== console.log('šŸ“ Step 4: Updating restaurant client settings...'); const updatedRestaurant = await dispatch9.updateClient(restaurantClient.id, { orderSettings: { autoAccept: false, // Changed from true maxOrdersPerHour: 50, // Increased capacity preparationTime: 20, // Reduced prep time deliveryRadius: 12.0 // Expanded radius }, apiConfig: { enabled: true, rateLimit: 750 // Increased rate limit }, contactName: 'Mario Rossi', contactPhone: '+1-555-0123-EXT-1' }); console.log(`āœ… Restaurant client updated!`); console.log(` ID: ${updatedRestaurant.id}`); console.log(` Auto Accept: ${updatedRestaurant.orderSettings?.autoAccept}`); console.log(` Max Orders/Hour: ${updatedRestaurant.orderSettings?.maxOrdersPerHour}`); console.log(` Delivery Radius: ${updatedRestaurant.orderSettings?.deliveryRadius} km`); console.log(` Rate Limit: ${updatedRestaurant.apiConfig?.rateLimit}\n`); // ========================================== // 5. UPDATE RETAIL CLIENT // ========================================== console.log('šŸ“ Step 5: Updating retail client integrations...'); const updatedRetail = await dispatch9.updateClient(retailClient.id, { status: 'active', websiteURL: 'https://www.techgadgetspro.com', // Updated URL logoURL: 'https://www.techgadgetspro.com/new-logo.png', orderSettings: { autoAssign: false, // Changed assignment strategy maxOrdersPerHour: 150, // Increased capacity deliveryRadius: 30.0 // Expanded coverage } }); console.log(`āœ… Retail client updated!`); console.log(` ID: ${updatedRetail.id}`); console.log(` Status: ${updatedRetail.status}`); console.log(` Website: ${updatedRetail.websiteURL}`); console.log(` Auto Assign: ${updatedRetail.orderSettings?.autoAssign}`); console.log(` Max Orders/Hour: ${updatedRetail.orderSettings?.maxOrdersPerHour}\n`); // ========================================== // 6. CREATE PHARMACY CLIENT // ========================================== console.log('šŸ’Š Step 6: Creating pharmacy client with special requirements...'); const pharmacyClient = await dispatch9.createClient({ name: 'HealthCare Pharmacy', email: 'prescriptions@healthcare-rx.com', businessType: 'pharmacy', websiteURL: 'https://www.healthcare-rx.com', taxId: '55-9988776', orderSettings: { autoAccept: false, // Manual review required for prescriptions autoAssign: false, // Specialized delivery required maxOrdersPerHour: 20, // Lower volume, higher care preparationTime: 45, // More time for prescription verification deliveryRadius: 15.0 }, permissions: { modify: false, delete: false, createOrders: true, viewOrders: true }, authentication: { enablePortalAccess: true, firstName: 'Dr. Sarah', lastName: 'Johnson', businessName: 'HealthCare Pharmacy' } }); console.log(`āœ… Pharmacy client created!`); console.log(` ID: ${pharmacyClient.id}`); console.log(` Name: ${pharmacyClient.name}`); console.log(` Preparation Time: ${pharmacyClient.orderSettings?.preparationTime} minutes`); console.log(` Auto Accept: ${pharmacyClient.orderSettings?.autoAccept}\n`); // ========================================== // 7. DEMONSTRATE ERROR HANDLING // ========================================== console.log('āš ļø Step 7: Demonstrating error handling...'); try { // Try to create client with invalid email await dispatch9.createClient({ name: 'Invalid Client', email: 'invalid-email-format' }); } catch (error) { console.log(`āœ… Email validation error caught: ${error.message}`); } try { // Try to create client with invalid business type await dispatch9.createClient({ name: 'Invalid Business', email: 'test@example.com', businessType: 'invalid_type' }); } catch (error) { console.log(`āœ… Business type validation error caught: ${error.message}`); } try { // Try to update with invalid URL await dispatch9.updateClient(retailClient.id, { websiteURL: 'not-a-valid-url' }); } catch (error) { console.log(`āœ… URL validation error caught: ${error.message}`); } console.log('\nšŸŽ‰ Client management example completed successfully!'); console.log('\nšŸ“Š Summary:'); console.log(` āœ“ Created restaurant client: ${restaurantClient.name}`); console.log(` āœ“ Created retail client: ${retailClient.name}`); console.log(` āœ“ Retrieved ${restaurants.results.length} restaurant clients`); console.log(` āœ“ Retrieved ${retailers.results.length} retail clients`); console.log(` āœ“ Updated restaurant settings`); console.log(` āœ“ Updated retail configuration`); console.log(` āœ“ Created pharmacy client: ${pharmacyClient.name}`); console.log(` āœ“ Demonstrated error handling`); } catch (error) { console.error('āŒ Error in client 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: clients.create, clients.read, clients.update'); } else if (error.message.includes('Rate limit exceeded')) { console.error('\nšŸ”§ Troubleshooting:'); console.error(' • You are making requests too quickly'); console.error(' • Wait a moment and try again'); } process.exit(1); } } // Run the example if (require.main === module) { clientManagementExample(); } module.exports = clientManagementExample;