# Coupan Code - Referral Code, Coupon Code & Promo Code Management SDK

**The easiest way to manage referral codes, coupon codes, promo codes, and discount codes in your Node.js/TypeScript applications.** Create, verify, and track discount codes with percentage or fixed amount discounts. Zero MongoDB configuration required - just API key and you're ready!

[![npm version](https://img.shields.io/npm/v/coupan-code)](https://www.npmjs.com/package/coupan-code)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)](https://www.typescriptlang.org/)
[![License](https://img.shields.io/badge/License-ISC-green)](LICENSE)

## 🚀 Quick Start

### Step 1: Installation

```bash
npm install coupan-code
```

### Step 2: Get Your API Key

Before using the package, you need an API key and Client ID. 

**To get your API key and Client ID, please email us at:**
- **Email**: kakadiyaavadh44@gmail.com
- **Subject**: "API Key Request for Coupan Code"
- **Include**: Your name, company name (if applicable), and intended use case

We'll provide you with:
- Your unique **Client ID**
- Your **API Key** (format: `sk_live_<random_string>` or `sk_test_<random_string>`)

**Note**: Please store your API key securely. It cannot be retrieved again if lost.

### Step 3: Use the Package

```typescript
import { CoupanCodeSDK, DiscountType } from 'coupan-code';

// Initialize with your API key and Client ID
const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_api_key_here',
  clientId: 'your-client-id'
});

// Connect and validate (connects to our centralized database automatically)
await sdk.init();

// Create a referral code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  15,  // 15% discount
  10   // Can be used 10 times
);

if (result.success) {
  console.log('Code created:', result.code);
}
```

That's it! You're ready to use Coupan Code.

---

## 📖 Step-by-Step Guide

### Step 1: Install the Package

```bash
npm install coupan-code
```

### Step 2: Get Your Credentials

You need two things to use the package:

1. **API Key**: A secret key that authenticates your requests
   - Format: `sk_live_<random_string>` or `sk_test_<random_string>`
   - Get it by emailing: **kakadiyaavadh44@gmail.com**

2. **Client ID**: Your unique client identifier
   - Provided when you get your API key via email

**How to Request API Key:**
Send an email to **kakadiyaavadh44@gmail.com** with:
- Subject: "API Key Request for Coupan Code"
- Your name and company (if applicable)
- Brief description of your use case

**Need Help?** Contact us at **kakadiyaavadh44@gmail.com** for:
- Getting your API key
- Resetting your credentials
- Technical support
- Any questions about the package

### Step 3: Initialize the SDK

```typescript
import { CoupanCodeSDK } from 'coupan-code';

// Initialize with your API key and Client ID
// MongoDB connection is handled automatically - no configuration needed!
const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_api_key_here',
  clientId: 'your-client-id'
});

// This validates your API key and connects to our centralized database
await sdk.init();
```

**Note**: The package automatically connects to our centralized MongoDB database. You don't need to configure MongoDB connection - it's all handled internally!

### Step 5: Create Referral Codes

```typescript
import { DiscountType } from 'coupan-code';

// Create a percentage discount code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  20,  // 20% off
  5    // Can be used 5 times
);

// Create a fixed amount discount code
const fixedResult = await sdk.createCode(
  DiscountType.AMOUNT,
  50,  // $50 off
  10   // Can be used 10 times
);

// Create with a custom code
const customResult = await sdk.createCode(
  DiscountType.PERCENTAGE,
  15,
  10,
  'SUMMER2024'  // Your custom code
);
```

### Step 6: Verify Codes

```typescript
// Check if a code is valid
const verification = await sdk.verifyCode('SUMMER2024');

if (verification.isValid) {
  console.log('Code is valid!');
  console.log('Discount:', verification.discountInfo?.discountValue);
}

// Verify and calculate discount amount
const verifyWithAmount = await sdk.verifyCode('SUMMER2024', 1000);

if (verifyWithAmount.isValid && verifyWithAmount.discountInfo) {
  console.log('Original amount: $1000');
  console.log('Discount: $' + verifyWithAmount.discountInfo.discountAmount);
  console.log('Final amount: $' + verifyWithAmount.discountInfo.finalAmount);
}
```

### Step 7: Track Usage

```typescript
// When a customer uses the code, increment usage
const usage = await sdk.incrementUsage('SUMMER2024');

if (usage.success) {
  console.log('Usage count:', usage.usedCount);
  console.log('Still active:', usage.isActive);
}
```

---

## 💡 Common Use Cases

### Use Case 1: Create a Simple Discount Code

```typescript
const sdk = new CoupanCodeSDK({
  apiKey: 'sk_live_your_key',
  clientId: 'your-client-id'
});

await sdk.init();

// Create 10% off code, unlimited uses
const code = await sdk.createCode(
  DiscountType.PERCENTAGE,
  10
);

console.log('Your code:', code.code);
```

### Use Case 2: Create Limited-Time Promo Code

```typescript
// Create code with usage limit
const promo = await sdk.createCode(
  DiscountType.PERCENTAGE,
  25,  // 25% off
  100  // Only 100 uses allowed
);

console.log('Promo code:', promo.code);
```

### Use Case 3: Verify Code at Checkout

```typescript
// Customer enters code at checkout
const customerCode = 'SUMMER2024';
const cartTotal = 500;

const check = await sdk.verifyCode(customerCode, cartTotal);

if (check.isValid && check.discountInfo) {
  const finalPrice = check.discountInfo.finalAmount;
  console.log(`Total after discount: $${finalPrice}`);
  
  // Apply the discount and increment usage
  await sdk.incrementUsage(customerCode);
} else {
  console.log('Invalid code:', check.error);
}
```

---

## 📚 Complete Example

Here's a full example showing all features:

```typescript
import { CoupanCodeSDK, DiscountType } from 'coupan-code';

async function main() {
  try {
    // 1. Initialize SDK
    const sdk = new CoupanCodeSDK({
      apiKey: 'sk_live_your_api_key',
      clientId: 'your-client-id'
    });

    await sdk.init();
    console.log('✅ SDK initialized');

    // 2. Create a referral code
    const createResult = await sdk.createCode(
      DiscountType.PERCENTAGE,
      20,  // 20% discount
      5    // 5 uses allowed
    );

    if (!createResult.success) {
      throw new Error(createResult.error);
    }

    const code = createResult.code!;
    console.log(`✅ Created code: ${code}`);

    // 3. Verify the code
    const verifyResult = await sdk.verifyCode(code, 1000);
    
    if (verifyResult.isValid && verifyResult.discountInfo) {
      console.log('✅ Code is valid');
      console.log(`   Original: $1000`);
      console.log(`   Discount: $${verifyResult.discountInfo.discountAmount}`);
      console.log(`   Final: $${verifyResult.discountInfo.finalAmount}`);
    }

    // 4. Use the code
    const usage = await sdk.incrementUsage(code);
    console.log(`✅ Usage count: ${usage.usedCount}`);

  } catch (error) {
    console.error('❌ Error:', error);
  }
}

main();
```

---

## 🔑 API Reference

### CoupanCodeSDK

#### Constructor

```typescript
new CoupanCodeSDK(config: {
  apiKey: string;    // Your API key
  clientId: string; // Your client ID
})
```

#### Methods

##### `init()`

Initializes the SDK. Must be called before using any other methods.

```typescript
await sdk.init();
```

##### `createCode(discountType, discountValue, usageLimit?, customCode?)`

Creates a new referral code.

**Parameters:**
- `discountType`: `DiscountType.PERCENTAGE` or `DiscountType.AMOUNT`
- `discountValue`: Discount value (0-100 for percentage, any number for amount)
- `usageLimit` (optional): Maximum number of uses
- `customCode` (optional): Your custom code string

**Returns:**
```typescript
{
  success: boolean;
  code?: string;
  error?: string;
  message?: string;
}
```

**Example:**
```typescript
// Auto-generated code
const result = await sdk.createCode(DiscountType.PERCENTAGE, 15, 10);

// Custom code
const custom = await sdk.createCode(DiscountType.PERCENTAGE, 15, 10, 'MYCODE');
```

##### `verifyCode(code, originalAmount?)`

Verifies a referral code and calculates discount.

**Parameters:**
- `code`: The referral code to verify
- `originalAmount` (optional): Original amount for discount calculation

**Returns:**
```typescript
{
  isValid: boolean;
  discountInfo?: {
    discountType: DiscountType;
    discountValue: number;
    discountAmount?: number;
    finalAmount?: number;
  };
  error?: string;
}
```

**Example:**
```typescript
// Just verify
const check = await sdk.verifyCode('MYCODE');

// Verify and calculate
const checkWithAmount = await sdk.verifyCode('MYCODE', 1000);
```

##### `incrementUsage(code)`

Increments the usage count. Automatically deactivates when limit is reached.

**Parameters:**
- `code`: The referral code

**Returns:**
```typescript
{
  success: boolean;
  usedCount?: number;
  isActive?: boolean;
  error?: string;
}
```

**Example:**
```typescript
const usage = await sdk.incrementUsage('MYCODE');
```

---

## 🎯 Discount Types

### Percentage Discount

```typescript
// 15% off
await sdk.createCode(DiscountType.PERCENTAGE, 15);
```

### Fixed Amount Discount

```typescript
// $50 off
await sdk.createCode(DiscountType.AMOUNT, 50);
```

---

## 🔒 Custom Codes

You can create codes with your own custom string:

```typescript
// Create with custom code
const result = await sdk.createCode(
  DiscountType.PERCENTAGE,
  20,
  10,
  'SUMMER2024'  // Your custom code
);

// If code already exists and is available, it returns the existing code
// If code is fully used or inactive, it returns an error
```

---

## ⚙️ Configuration

### Environment Variables

### Database Connection

The SDK automatically connects to our centralized MongoDB database when you call `init()`. **No configuration needed!** All data is stored securely in our database.

**Connection Troubleshooting:**

If you get a connection error:

1. **Check your API Key and Client ID:**
   - Make sure they're correct and active
   - Contact support if you need to reset them

2. **Network Issues:**
   - Check your internet connection
   - Ensure your firewall allows outbound connections
   - Try again - connection errors are usually temporary

3. **Common Error Messages:**
   - ❌ **"Invalid API key or client ID"**: Check your credentials
   - ❌ **"MongoDB connection failed"**: This is an internal error - contact support
   - ❌ **"SDK not initialized"**: Make sure you called `await sdk.init()` first

---

## ❓ Need Help?

### Get API Key

To get your API key and Client ID, email us at:
- **Email**: kakadiyaavadh44@gmail.com
- **Subject**: "API Key Request for Coupan Code"

Include in your email:
- Your name
- Company name (if applicable)
- Brief description of your use case

### Support

For any questions, issues, or help with:
- Getting API keys
- Setting up your account
- Technical support
- Feature requests
- Resetting credentials

**Contact us**: kakadiyaavadh44@gmail.com

---

## 📝 Error Handling

Always check the `success` or `isValid` flag:

```typescript
const result = await sdk.createCode(DiscountType.PERCENTAGE, 15);

if (result.success) {
  // Use result.code
  console.log('Code:', result.code);
} else {
  // Handle error
  console.error('Error:', result.error);
}
```

---

## 🔧 Advanced Usage

### Direct Controller Access

For advanced use cases, you can use the controller directly:

```typescript
import { connectDB, ReferralController, DiscountType } from 'coupan-code';

// Connect to centralized database (handled automatically)
await connectDB();

const result = await ReferralController.createCode(
  'client-id',
  DiscountType.PERCENTAGE,
  15,
  10
);
```

**Note**: `connectDB()` connects to our centralized database automatically. No MongoDB URI needed!

---

## 📦 Package Structure

```
coupan-code/
├── src/
│   ├── models/        # Database models
│   ├── services/      # Business logic
│   ├── controllers/   # API controllers
│   └── sdk.ts        # Main SDK class
└── dist/             # Compiled JavaScript
```

---

## 🧪 Testing

Run the test suite:

```bash
npm test
```

---

## 📄 License

ISC

---

## 🙏 Support & Contact

- **Email**: kakadiyaavadh44@gmail.com
- **For API Key Requests**: Email us with subject "API Key Request for Coupan Code"

---

## 🔍 Why Choose Coupan Code?

- ✅ **Zero Configuration** - No MongoDB setup needed, connects automatically
- ✅ **TypeScript Ready** - Full TypeScript support with type definitions
- ✅ **Simple API** - Easy-to-use SDK similar to AWS SDK pattern
- ✅ **Flexible Discounts** - Percentage or fixed amount discounts
- ✅ **Usage Limits** - Set maximum usage per code
- ✅ **Custom Codes** - Use your own code strings
- ✅ **Production Ready** - Connection pooling, retry logic, error handling
- ✅ **Well Documented** - Comprehensive docs and examples

## 📦 Install

```bash
npm install coupan-code
```

## 🎯 Perfect For

- E-commerce platforms
- Shopping cart systems
- Marketing campaigns
- Affiliate programs
- Loyalty programs
- Reward systems
- Promotional campaigns
- Discount management

## 🔑 Keywords

This package helps with: **referral codes**, **coupon codes**, **promo codes**, **discount codes**, **voucher codes**, **promotional codes**, **discount management**, **coupon management**, **referral system**, **promo code generator**, **discount generator**, **ecommerce discounts**, **shopping cart discounts**, **checkout discounts**, **marketing tools**, **affiliate tracking**, **loyalty rewards**.

---

**Made with ❤️ for easy referral code management**
