@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
JavaScript
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;