UNPKG

@vulog/aima-user

Version:

User management module for the AIMA platform. This module provides comprehensive functionality to manage users, profiles, billing groups, and user-related operations.

452 lines (364 loc) 11.5 kB
# @vulog/aima-user User management module for the AIMA platform. This module provides comprehensive functionality to manage users, profiles, billing groups, and user-related operations. ## Installation ```bash npm install @vulog/aima-client @vulog/aima-core @vulog/aima-user ``` ## Usage ### Initialize Client ```javascript import { getClient } from '@vulog/aima-client'; import { createUser, findUser, getUserById, updateUser, createBusinessProfile, getFleetBillingGroups } from '@vulog/aima-user'; const client = getClient({ apiKey: 'your-api-key', baseUrl: 'https://your-api-base-url', clientId: 'your-client-id', clientSecret: 'your-client-secret', fleetId: 'your-fleet-id', }); ``` ## API Reference ### User Management #### createUser Create a new user account. ```javascript const user = await createUser(client, { userName: 'john.doe', password: 'securePassword123', locale: 'en_US', email: 'john.doe@example.com', dataPrivacyConsent: true, profilingConsent: false, marketingConsent: true, phoneNumber: '+1234567890' }, { tcApproval: true, skipUserNotification: false }); ``` **Parameters:** - `client`: AIMA client instance - `userData`: User creation data - `userName`: Unique username - `password`: User password - `locale`: Locale code (e.g., 'en_US', 'fr_FR') - `email`: User email address - `dataPrivacyConsent`: Data privacy consent (optional) - `profilingConsent`: Profiling consent (optional) - `marketingConsent`: Marketing consent (optional) - `phoneNumber`: Phone number (optional) - `options`: Creation options (optional) - `tcApproval`: Terms and conditions approval (default: true) - `skipUserNotification`: Skip user notification (default: false) #### findUser Search for users by various criteria. ```javascript const users = await findUser(client, { email: 'john.doe@example.com', userName: 'john.doe', phoneNumber: '+1234567890' }); ``` **Parameters:** - `client`: AIMA client instance - `searchCriteria`: Search criteria object - `email`: Email address to search - `userName`: Username to search - `phoneNumber`: Phone number to search #### getUserById Retrieve user by ID. ```javascript const user = await getUserById(client, 'user-uuid-here'); ``` **Parameters:** - `client`: AIMA client instance - `userId`: User UUID #### updateUser Update user information. ```javascript const updatedUser = await updateUser(client, 'user-uuid-here', { email: 'new.email@example.com', phoneNumber: '+0987654321', locale: 'fr_FR' }); ``` **Parameters:** - `client`: AIMA client instance - `userId`: User UUID - `updateData`: Data to update ### Profile Management #### createBusinessProfile Create a business profile for a user. ```javascript const businessProfile = await createBusinessProfile(client, { entityId: 'user-uuid-here', companyName: 'Acme Corp', vatNumber: 'VAT123456789', address: { street: '123 Main St', city: 'New York', postalCode: '10001', country: 'US' } }); ``` #### getProfilePersonalInfoById Get personal information for a user profile. ```javascript const personalInfo = await getProfilePersonalInfoById(client, 'user-uuid-here'); ``` #### updateProfilePersonalInfo Update personal information for a user profile. ```javascript const updatedInfo = await updateProfilePersonalInfo(client, 'user-uuid-here', { firstName: 'John', lastName: 'Doe', dateOfBirth: '1990-01-01', address: { street: '456 Oak Ave', city: 'Los Angeles', postalCode: '90210', country: 'US' } }); ``` ### Billing and Groups #### getFleetBillingGroups Retrieve billing groups for the fleet. ```javascript const billingGroups = await getFleetBillingGroups(client); ``` #### assignBillingGroup Assign a user to a billing group. ```javascript const result = await assignBillingGroup(client, { entityId: 'user-uuid-here', billingGroupId: 'billing-group-id-here' }); ``` ### Terms and Conditions #### acceptTAndC Accept terms and conditions for a user. ```javascript const result = await acceptTAndC(client, { entityId: 'user-uuid-here', version: '1.0', acceptedAt: new Date().toISOString() }); ``` ### Service Management #### setServicesStatus Set service status for a user. ```javascript const result = await setServicesStatus(client, { entityId: 'user-uuid-here', services: { 'SERVICE_A': true, 'SERVICE_B': false, 'SERVICE_C': true } }); ``` #### registerUserToService Register a user entity to a specific service it's optional if the service is public (users are subscribed by default to public services). but mandatory to be able to book on a private service. ```javascript await registerUserToService(client, 'entity-uuid-here', 'service-uuid-here'); ``` **Parameters:** - `client`: AIMA client instance - `entityId`: Entity UUID to register - `serviceId`: Service UUID to register the profile to ## Types ### User ```typescript interface User { id: string; userName: string; email: string; phoneNumber?: string; locale: string; status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED' | 'DELETED'; dataPrivacyConsent: boolean; profilingConsent: boolean; marketingConsent: boolean; createdAt: string; updatedAt: string; lastLoginAt?: string; } ``` ### BusinessProfile ```typescript interface BusinessProfile { id: string; entityId: string; companyName: string; vatNumber: string; address: { street: string; city: string; postalCode: string; country: string; }; createdAt: string; updatedAt: string; } ``` ### BillingGroup ```typescript interface BillingGroup { id: string; name: string; description: string; memberCount: number; billingRules: any[]; createdAt: string; updatedAt: string; } ``` ## Error Handling All functions include validation using Zod schemas and will throw appropriate errors if: - Required parameters are missing - Invalid user IDs are provided - Email format is invalid - Locale format is invalid - Network errors occur ## Examples ### Complete User Management Workflow ```javascript import { getClient } from '@vulog/aima-client'; import { createUser, findUser, getUserById, updateUser, createBusinessProfile, getFleetBillingGroups } from '@vulog/aima-user'; const client = getClient({ apiKey: 'your-api-key', baseUrl: 'https://your-api-base-url', clientId: 'your-client-id', clientSecret: 'your-client-secret', fleetId: 'your-fleet-id', }); async function userManagementWorkflow() { try { // Create a new user const newUser = await createUser(client, { userName: 'jane.doe', password: 'securePassword123', locale: 'en_US', email: 'jane.doe@example.com', dataPrivacyConsent: true, profilingConsent: false, marketingConsent: true, phoneNumber: '+1234567890' }); console.log('User created:', newUser); // Find user by email const foundUsers = await findUser(client, { email: 'jane.doe@example.com' }); console.log('Found users:', foundUsers); // Get user by ID const user = await getUserById(client, newUser.id); console.log('User details:', user); // Update user const updatedUser = await updateUser(client, newUser.id, { phoneNumber: '+0987654321', locale: 'fr_FR' }); console.log('User updated:', updatedUser); // Create business profile const businessProfile = await createBusinessProfile(client, { entityId: newUser.id, companyName: 'Doe Enterprises', vatNumber: 'VAT987654321', address: { street: '789 Business Blvd', city: 'San Francisco', postalCode: '94105', country: 'US' } }); console.log('Business profile created:', businessProfile); // Get billing groups const billingGroups = await getFleetBillingGroups(client); console.log('Billing groups:', billingGroups); return { newUser, updatedUser, businessProfile, billingGroups }; } catch (error) { console.error('User management error:', error); throw error; } } ``` ### User Search and Filtering ```javascript async function searchUsers(client, searchTerm) { try { // Search by email const emailResults = await findUser(client, { email: searchTerm }); // Search by username const usernameResults = await findUser(client, { userName: searchTerm }); // Search by phone number const phoneResults = await findUser(client, { phoneNumber: searchTerm }); // Combine and deduplicate results const allResults = [...emailResults, ...usernameResults, ...phoneResults]; const uniqueResults = allResults.filter((user, index, self) => index === self.findIndex(u => u.id === user.id) ); console.log(`Found ${uniqueResults.length} unique users for "${searchTerm}"`); return uniqueResults; } catch (error) { console.error('User search error:', error); throw error; } } ``` ### User Analytics ```javascript async function analyzeUsers(client) { try { // This would require a function to get all users // For now, we'll demonstrate with individual user lookups const sampleUserIds = ['user1', 'user2', 'user3']; // Replace with actual IDs const users = await Promise.all( sampleUserIds.map(id => getUserById(client, id).catch(() => null)) ); const validUsers = users.filter(user => user !== null); const analysis = { totalUsers: validUsers.length, activeUsers: validUsers.filter(u => u.status === 'ACTIVE').length, inactiveUsers: validUsers.filter(u => u.status === 'INACTIVE').length, suspendedUsers: validUsers.filter(u => u.status === 'SUSPENDED').length, consentStats: { dataPrivacy: validUsers.filter(u => u.dataPrivacyConsent).length, profiling: validUsers.filter(u => u.profilingConsent).length, marketing: validUsers.filter(u => u.marketingConsent).length }, localeDistribution: validUsers.reduce((acc, user) => { acc[user.locale] = (acc[user.locale] || 0) + 1; return acc; }, {}) }; console.log('User Analysis:'); console.log(`Total Users: ${analysis.totalUsers}`); console.log(`Active: ${analysis.activeUsers}`); console.log(`Inactive: ${analysis.inactiveUsers}`); console.log(`Suspended: ${analysis.suspendedUsers}`); console.log('Consent Stats:', analysis.consentStats); console.log('Locale Distribution:', analysis.localeDistribution); return analysis; } catch (error) { console.error('User analysis error:', error); throw error; } } ```