npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-promocode

Usage

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 instance
  • promocodeId: Promocode identifier

Returns: Promocode object with details

getPromoCode

Get promocode information by code.

const promocode = await getPromoCode(client, 'WELCOME2024');

Parameters:

  • client: AIMA client instance
  • code: 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 instance
  • submissionData: Promocode submission data
    • code: Promocode string
    • entityId: 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 instance
  • invitationCode: 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 instance
  • referralData: Referral submission data
    • referrerId: User ID of the referrer
    • refereeEmail: Email of the person being referred
    • invitationCode: 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;
    }
}