@vulog/aima-promocode
v1.2.37
Published
Promocode and referral management module for the AIMA platform. This module provides functionality to manage promotional codes, referral systems, and invitation codes.
Downloads
1,393
Readme
@vulog/aima-promocode
Promocode and referral management module for the AIMA platform. This module provides functionality to manage promotional codes, referral systems, and invitation codes.
Installation
npm install @vulog/aima-client @vulog/aima-core @vulog/aima-promocodeUsage
Initialize Client
import { getClient } from '@vulog/aima-client';
import {
getPromoCodeById,
getPromoCode,
submitPromoCode,
checkInvitationCode,
submitReferral
} from '@vulog/aima-promocode';
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
Promocode Management
getPromoCodeById
Retrieve a specific promocode by its ID.
const promocode = await getPromoCodeById(client, 25);Parameters:
client: AIMA client instancepromocodeId: Promocode identifier
Returns: Promocode object with details
getPromoCode
Get promocode information by code.
const promocode = await getPromoCode(client, 'WELCOME2024');Parameters:
client: AIMA client instancecode: Promocode string
Returns: Promocode object
submitPromoCode
Submit a promocode for redemption.
const result = await submitPromoCode(client, {
code: 'WELCOME2024',
entityId: 'user-uuid-here'
});Parameters:
client: AIMA client instancesubmissionData: Promocode submission datacode: Promocode stringentityId: User UUID
Returns: Redemption result
Referral System
checkInvitationCode
Check if an invitation code is valid.
const isValid = await checkInvitationCode(client, 'INVITE123');Parameters:
client: AIMA client instanceinvitationCode: Invitation code string
Returns: Boolean indicating validity
submitReferral
Submit a referral.
const referral = await submitReferral(client, {
referrerId: 'user-uuid-here',
refereeEmail: '[email protected]',
invitationCode: 'INVITE123'
});Parameters:
client: AIMA client instancereferralData: Referral submission datareferrerId: User ID of the referrerrefereeEmail: Email of the person being referredinvitationCode: Invitation code used
Returns: Referral object
Types
Promocode
interface Promocode {
id: number;
code: string;
name: string;
description: string;
discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
discountValue: number;
currency?: string;
minAmount?: number;
maxDiscount?: number;
usageLimit?: number;
usedCount: number;
isActive: boolean;
validFrom: string;
validTo: string;
applicableTo: string[];
createdAt: string;
updatedAt: string;
}PromocodeSubmission
interface PromocodeSubmission {
code: string;
entityId: string;
}Referral
interface Referral {
id: string;
referrerId: string;
refereeEmail: string;
invitationCode: string;
status: 'PENDING' | 'ACCEPTED' | 'REJECTED';
rewardAmount?: number;
rewardCurrency?: string;
createdAt: string;
updatedAt: string;
}InvitationCode
interface InvitationCode {
code: string;
isValid: boolean;
expiresAt?: string;
usageLimit?: number;
usedCount?: number;
}Error Handling
All functions include validation and will throw appropriate errors if:
- Required parameters are missing
- Invalid promocode or invitation codes are provided
- Promocode has expired or reached usage limit
- User not found
- Network errors occur
Examples
Complete Promocode Workflow
import { getClient } from '@vulog/aima-client';
import {
getPromoCodeById,
getPromoCode,
submitPromoCode,
checkInvitationCode,
submitReferral
} from '@vulog/aima-promocode';
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 promocodeWorkflow() {
try {
// Get promocode by ID
const promocodeById = await getPromoCodeById(client, 25);
console.log('Promocode by ID:', promocodeById);
// Get promocode by code
const promocodeByCode = await getPromoCode(client, 'WELCOME2024');
console.log('Promocode by code:', promocodeByCode);
// Submit promocode for redemption
const redemption = await submitPromoCode(client, {
code: 'WELCOME2024',
entityId: 'user-uuid-here'
});
console.log('Promocode redeemed:', redemption);
// Check invitation code
const isValidInvite = await checkInvitationCode(client, 'INVITE123');
console.log('Invitation code valid:', isValidInvite);
// Submit referral
const referral = await submitReferral(client, {
referrerId: 'user-uuid-here',
refereeEmail: '[email protected]',
invitationCode: 'INVITE123'
});
console.log('Referral submitted:', referral);
return { promocodeById, promocodeByCode, redemption, isValidInvite, referral };
} catch (error) {
console.error('Promocode workflow error:', error);
throw error;
}
}Promocode Validation
async function validatePromocode(client, code, userId, amount) {
try {
const promocode = await getPromoCode(client, code);
// Check if promocode is active
if (!promocode.isActive) {
throw new Error('Promocode is not active');
}
// Check validity period
const now = new Date();
const validFrom = new Date(promocode.validFrom);
const validTo = new Date(promocode.validTo);
if (now < validFrom || now > validTo) {
throw new Error('Promocode is not valid at this time');
}
// Check usage limit
if (promocode.usageLimit && promocode.usedCount >= promocode.usageLimit) {
throw new Error('Promocode usage limit exceeded');
}
// Check minimum amount
if (promocode.minAmount && amount < promocode.minAmount) {
throw new Error(`Minimum amount required: ${promocode.minAmount}`);
}
// Calculate discount
let discount = 0;
if (promocode.discountType === 'PERCENTAGE') {
discount = (amount * promocode.discountValue) / 100;
if (promocode.maxDiscount) {
discount = Math.min(discount, promocode.maxDiscount);
}
} else if (promocode.discountType === 'FIXED_AMOUNT') {
discount = promocode.discountValue;
}
return {
isValid: true,
promocode,
discount,
finalAmount: amount - discount
};
} catch (error) {
console.error('Promocode validation error:', error);
return {
isValid: false,
error: error.message
};
}
}Referral System Management
async function manageReferralSystem(client, referrerId) {
try {
// Check if user has valid invitation codes
const invitationCodes = ['INVITE123', 'INVITE456', 'INVITE789'];
const validCodes = [];
for (const code of invitationCodes) {
try {
const isValid = await checkInvitationCode(client, code);
if (isValid) {
validCodes.push(code);
}
} catch (error) {
console.log(`Code ${code} is invalid:`, error.message);
}
}
console.log(`User has ${validCodes.length} valid invitation codes`);
// Simulate referral submissions
const referrals = [];
for (const code of validCodes.slice(0, 2)) { // Use first 2 valid codes
try {
const referral = await submitReferral(client, {
referrerId,
refereeEmail: `referee${Math.random().toString(36).substr(2, 9)}@example.com`,
invitationCode: code
});
referrals.push(referral);
} catch (error) {
console.error(`Referral submission failed for ${code}:`, error.message);
}
}
console.log(`Successfully submitted ${referrals.length} referrals`);
return { validCodes, referrals };
} catch (error) {
console.error('Referral system management error:', error);
throw error;
}
}Promocode Analytics
async function analyzePromocodes(client) {
try {
// This would require additional API endpoints for promocode analytics
// For now, we'll demonstrate with individual promocode lookups
const promocodeIds = [1, 2, 3, 4, 5]; // Example IDs
const promocodes = [];
for (const id of promocodeIds) {
try {
const promocode = await getPromoCodeById(client, id);
promocodes.push(promocode);
} catch (error) {
console.log(`Promocode ${id} not found or error:`, error.message);
}
}
const analysis = {
totalPromocodes: promocodes.length,
activePromocodes: promocodes.filter(p => p.isActive).length,
expiredPromocodes: promocodes.filter(p => new Date(p.validTo) < new Date()).length,
usageStats: {
totalUsed: promocodes.reduce((sum, p) => sum + p.usedCount, 0),
averageUsage: promocodes.reduce((sum, p) => sum + p.usedCount, 0) / promocodes.length,
maxUsage: Math.max(...promocodes.map(p => p.usedCount))
},
discountTypes: {
percentage: promocodes.filter(p => p.discountType === 'PERCENTAGE').length,
fixedAmount: promocodes.filter(p => p.discountType === 'FIXED_AMOUNT').length
}
};
console.log('Promocode Analytics:');
console.log(`Total Promocodes: ${analysis.totalPromocodes}`);
console.log(`Active: ${analysis.activePromocodes}`);
console.log(`Expired: ${analysis.expiredPromocodes}`);
console.log(`Total Used: ${analysis.usageStats.totalUsed}`);
console.log(`Average Usage: ${analysis.usageStats.averageUsage.toFixed(2)}`);
console.log(`Max Usage: ${analysis.usageStats.maxUsage}`);
console.log(`Percentage Discounts: ${analysis.discountTypes.percentage}`);
console.log(`Fixed Amount Discounts: ${analysis.discountTypes.fixedAmount}`);
return analysis;
} catch (error) {
console.error('Promocode analytics error:', error);
throw error;
}
}