Skip to main content

Basic Customer Operations

Creating a Customer

import { Moflay } from "@moflay/sdk";

const moflay = new Moflay({
  token: process.env.MOFLAY_API_KEY,
});

async function createCustomer() {
  try {
    const customer = await moflay.customers.create({
      phoneNumber: "254712345678",
      name: "John Doe",
      email: "[email protected]",
      description: "VIP Customer",
      metadata: {
        "user_id": "12345",
        "subscription_type": "premium",
        "signup_date": "2024-01-15",
      },
    });

    console.log("Customer created:", customer);
    return customer;
  } catch (error) {
    console.error("Failed to create customer:", error);
    throw error;
  }
}

Retrieving a Customer

async function getCustomer(customerId: string) {
  try {
    const customer = await moflay.customers.getOne({
      id: customerId,
    });

    console.log("Customer details:", customer);
    return customer;
  } catch (error) {
    console.error("Failed to get customer:", error);
    throw error;
  }
}

Updating a Customer

async function updateCustomer(customerId: string, updates: any) {
  try {
    const updatedCustomer = await moflay.customers.update({
      id: customerId,
      ...updates,
    });

    console.log("Customer updated:", updatedCustomer);
    return updatedCustomer;
  } catch (error) {
    console.error("Failed to update customer:", error);
    throw error;
  }
}

// Usage example
updateCustomer("customer_123", {
  name: "John Smith",
  email: "[email protected]",
  metadata: {
    "subscription_type": "enterprise",
    "last_updated": new Date().toISOString(),
  },
});

Deleting a Customer

async function deleteCustomer(customerId: string) {
  try {
    await moflay.customers.delete({
      id: customerId,
    });

    console.log("Customer deleted successfully");
  } catch (error) {
    console.error("Failed to delete customer:", error);
    throw error;
  }
}

List All Customers

async function listAllCustomers() {
  try {
    const customers = await moflay.customers.list({});
    
    for await (const page of customers) {
      console.log("Customers page:", page);
    }
  } catch (error) {
    console.error("Failed to list customers:", error);
    throw error;
  }
}

Search Customers

async function searchCustomers(query: string) {
  try {
    const customers = await moflay.customers.list({
      q: query,
    });
    
    for await (const page of customers) {
      console.log("Search results:", page);
    }
  } catch (error) {
    console.error("Failed to search customers:", error);
    throw error;
  }
}

// Search by name
searchCustomers("John Doe");

// Search by email
searchCustomers("[email protected]");

Filter Customers by Date Range

async function getCustomersByDateRange(startDate: Date, endDate: Date) {
  try {
    const customers = await moflay.customers.list({
      start: startDate,
      end: endDate,
    });
    
    for await (const page of customers) {
      console.log("Customers in date range:", page);
    }
  } catch (error) {
    console.error("Failed to filter customers by date:", error);
    throw error;
  }
}

// Get customers created in the last 30 days
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const now = new Date();
getCustomersByDateRange(thirtyDaysAgo, now);

Advanced Customer Management

Customer Registration with Validation

interface CustomerData {
  phoneNumber: string;
  name: string;
  email: string;
  description?: string;
  metadata?: Record<string, any>;
}

async function registerCustomerWithValidation(customerData: CustomerData) {
  // Validate phone number format
  const phoneRegex = /^254[0-9]{9}$/;
  if (!phoneRegex.test(customerData.phoneNumber)) {
    throw new Error("Invalid phone number format. Use format: 254XXXXXXXXX");
  }

  // Validate email format
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(customerData.email)) {
    throw new Error("Invalid email format");
  }

  try {
    const customer = await moflay.customers.create(customerData);
    console.log("Customer registered successfully:", customer);
    return customer;
  } catch (error) {
    console.error("Customer registration failed:", error);
    throw error;
  }
}

Bulk Customer Operations

async function createMultipleCustomers(customersData: CustomerData[]) {
  const results = [];
  const errors = [];

  for (const customerData of customersData) {
    try {
      const customer = await moflay.customers.create(customerData);
      results.push(customer);
      console.log(`Customer ${customerData.email} created successfully`);
    } catch (error) {
      errors.push({ customerData, error });
      console.error(`Failed to create customer ${customerData.email}:`, error);
    }
  }

  return { results, errors };
}

// Usage
const customersToCreate = [
  {
    phoneNumber: "254712345678",
    name: "John Doe",
    email: "[email protected]",
    description: "Customer 1",
  },
  {
    phoneNumber: "254712345679",
    name: "Jane Smith",
    email: "[email protected]",
    description: "Customer 2",
  },
];

createMultipleCustomers(customersToCreate);

Customer Analytics and Reporting

async function getCustomerAnalytics() {
  try {
    // Get all customers
    const allCustomers = await moflay.customers.list({});
    let totalCustomers = 0;
    let customersByMonth: Record<string, number> = {};

    for await (const page of allCustomers) {
      totalCustomers += page.data.length;
      
      page.data.forEach(customer => {
        const createdAt = new Date(customer.createdAt);
        const monthKey = `${createdAt.getFullYear()}-${String(createdAt.getMonth() + 1).padStart(2, '0')}`;
        customersByMonth[monthKey] = (customersByMonth[monthKey] || 0) + 1;
      });
    }

    console.log("Customer Analytics:");
    console.log(`Total customers: ${totalCustomers}`);
    console.log("Customers by month:", customersByMonth);

    return {
      totalCustomers,
      customersByMonth,
    };
  } catch (error) {
    console.error("Failed to get customer analytics:", error);
    throw error;
  }
}

Customer Segmentation

async function segmentCustomers() {
  try {
    const allCustomers = await moflay.customers.list({});
    const segments = {
      premium: [],
      standard: [],
      new: [],
    };

    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

    for await (const page of allCustomers) {
      page.data.forEach(customer => {
        const createdAt = new Date(customer.createdAt);
        const metadata = customer.metadata || {};

        if (createdAt > thirtyDaysAgo) {
          segments.new.push(customer);
        } else if (metadata.subscription_type === "premium") {
          segments.premium.push(customer);
        } else {
          segments.standard.push(customer);
        }
      });
    }

    console.log("Customer Segments:");
    console.log(`Premium customers: ${segments.premium.length}`);
    console.log(`Standard customers: ${segments.standard.length}`);
    console.log(`New customers (last 30 days): ${segments.new.length}`);

    return segments;
  } catch (error) {
    console.error("Failed to segment customers:", error);
    throw error;
  }
}

Error Handling for Customer Operations

import * as errors from "@moflay/sdk/models/errors";

async function handleCustomerOperations() {
  try {
    const customer = await moflay.customers.create({
      phoneNumber: "254712345678",
      name: "John Doe",
      email: "[email protected]",
    });

    return customer;
  } catch (error) {
    if (error instanceof errors.ValidationError) {
      console.error("Validation error:", error.data$);
    } else if (error instanceof errors.NotFoundError) {
      console.error("Customer not found");
    } else if (error instanceof errors.RateLimitExceededError) {
      console.error("Rate limit exceeded, please try again later");
    } else if (error instanceof errors.MoflayError) {
      console.error("Customer operation error:", error.message);
    } else {
      console.error("Unexpected error:", error);
    }
    
    throw error;
  }
}

Integration with Express Payments

async function createCustomerAndMakePayment(customerData: CustomerData, paymentData: any) {
  try {
    // First, create the customer
    const customer = await moflay.customers.create(customerData);
    console.log("Customer created:", customer);

    // Then, make a payment using the customer's details
    const payment = await moflay.express.pay({
      phoneNumber: customer.phoneNumber,
      customerName: customer.name,
      customerEmail: customer.email,
      customerDescription: customer.description,
      customerMetadata: customer.metadata,
      ...paymentData,
    });

    console.log("Payment initiated:", payment);
    return { customer, payment };
  } catch (error) {
    console.error("Failed to create customer and make payment:", error);
    throw error;
  }
}