# Recharge Offer API Documentation

Base URL: `https://api.alldigtalseva.com`

---

## Table of Contents

### Public APIs (No Authentication Required)
1. [Get All Active Offers](#get-all-active-offers)
2. [Get Single Offer](#get-single-offer)
3. [Get Applicable Offers for Recharge Amount](#get-applicable-offers-for-recharge-amount)

### Admin APIs (Requires Admin Token)
4. [Get All Offers (Admin)](#get-all-offers-admin)
5. [Get Single Offer (Admin)](#get-single-offer-admin)
6. [Add New Offer](#add-new-offer)
7. [Update Offer](#update-offer)
8. [Delete Offer](#delete-offer)

---

## Get All Active Offers

Get list of all active and valid recharge offers (public endpoint).

**Endpoint:** `GET /api/recharge-offer`

**Headers:** None required

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "title": "Festive Recharge Offer",
            "description": "Get 10% discount on recharge above ₹500",
            "minimum_recharge_amount": "500.00",
            "discount_type": "percentage",
            "discount_value": "10.00",
            "cashback_amount": "50.00",
            "validity_start_date": "2025-12-01",
            "validity_end_date": "2025-12-31",
            "is_active": true,
            "created_at": "2025-12-04T16:12:45.000000Z",
            "updated_at": "2025-12-04T16:12:45.000000Z"
        }
    ]
}
```

**Note:** Only returns offers that are:
- Active (`is_active = true`)
- Currently valid (between `validity_start_date` and `validity_end_date`)

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/recharge-offer
```

**JavaScript/Fetch Example:**
```javascript
fetch('https://api.alldigtalseva.com/api/recharge-offer')
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      console.log('Active Offers:', data.data);
    }
  });
```

---

## Get Single Offer

Get detailed information about a specific recharge offer.

**Endpoint:** `GET /api/recharge-offer/{id}`

**Headers:** None required

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "title": "Festive Recharge Offer",
        "description": "Get 10% discount on recharge above ₹500",
        "minimum_recharge_amount": "500.00",
        "discount_type": "percentage",
        "discount_value": "10.00",
        "cashback_amount": "50.00",
        "validity_start_date": "2025-12-01",
        "validity_end_date": "2025-12-31",
        "is_active": true,
        "created_at": "2025-12-04T16:12:45.000000Z",
        "updated_at": "2025-12-04T16:12:45.000000Z"
    },
    "is_valid": true
}
```

**Error Response (404):**
```json
{
    "success": false,
    "message": "Recharge offer not found"
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/recharge-offer/1
```

---

## Get Applicable Offers for Recharge Amount

Get all offers that are applicable for a specific recharge amount, with calculated benefits.

**Endpoint:** `GET /api/recharge-offer/applicable`

**Query Parameters:**
- `recharge_amount` (required, numeric, min: 0.01): The recharge amount to check offers for

**Success Response (200):**
```json
{
    "success": true,
    "recharge_amount": "1000",
    "data": [
        {
            "id": 1,
            "title": "Festive Recharge Offer",
            "description": "Get 10% discount on recharge above ₹500",
            "minimum_recharge_amount": "500.00",
            "discount_type": "percentage",
            "discount_value": "10.00",
            "cashback_amount": "50.00",
            "total_benefit": 150,
            "benefit_description": "10.00% discount = ₹100 + ₹50.00 cashback",
            "validity_start_date": "2025-12-01",
            "validity_end_date": "2025-12-31"
        }
    ]
}
```

**Response Fields:**
- `total_benefit`: Total benefit amount (discount + cashback)
- `benefit_description`: Human-readable description of the benefit

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "recharge_amount": ["The recharge amount field is required."]
    }
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/recharge-offer/applicable?recharge_amount=1000"
```

**JavaScript/Fetch Example:**
```javascript
const rechargeAmount = 1000;
fetch(`https://api.alldigtalseva.com/api/recharge-offer/applicable?recharge_amount=${rechargeAmount}`)
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      console.log('Applicable Offers:', data.data);
      data.data.forEach(offer => {
        console.log(`${offer.title}: ${offer.benefit_description}`);
        console.log(`Total Benefit: ₹${offer.total_benefit}`);
      });
    }
  });
```

---

## Get All Offers (Admin)

Get list of all recharge offers (including inactive and expired ones).

**Endpoint:** `GET /api/admin/recharge-offer`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "title": "Festive Recharge Offer",
            "description": "Get 10% discount on recharge above ₹500",
            "minimum_recharge_amount": "500.00",
            "discount_type": "percentage",
            "discount_value": "10.00",
            "cashback_amount": "50.00",
            "validity_start_date": "2025-12-01",
            "validity_end_date": "2025-12-31",
            "is_active": true,
            "created_by": 1,
            "created_at": "2025-12-04T16:12:45.000000Z",
            "updated_at": "2025-12-04T16:12:45.000000Z"
        }
    ]
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/recharge-offer \
  -H "Authorization: Bearer {admin_token}"
```

---

## Get Single Offer (Admin)

Get detailed information about a specific recharge offer (admin view).

**Endpoint:** `GET /api/admin/recharge-offer/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "title": "Festive Recharge Offer",
        "description": "Get 10% discount on recharge above ₹500",
        "minimum_recharge_amount": "500.00",
        "discount_type": "percentage",
        "discount_value": "10.00",
        "cashback_amount": "50.00",
        "validity_start_date": "2025-12-01",
        "validity_end_date": "2025-12-31",
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-04T16:12:45.000000Z",
        "updated_at": "2025-12-04T16:12:45.000000Z"
    }
}
```

**Error Response (404):**
```json
{
    "success": false,
    "message": "Recharge offer not found"
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/recharge-offer/1 \
  -H "Authorization: Bearer {admin_token}"
```

---

## Add New Offer

Create a new recharge offer.

**Endpoint:** `POST /api/admin/recharge-offer`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "title": "Festive Recharge Offer",
    "description": "Get 10% discount on recharge above ₹500",
    "minimum_recharge_amount": 500,
    "discount_type": "percentage",
    "discount_value": 10,
    "cashback_amount": 50,
    "validity_start_date": "2025-12-01",
    "validity_end_date": "2025-12-31",
    "is_active": true
}
```

**Parameters:**
- `title` (required, string, max: 255): Offer title
- `description` (optional, string): Offer description
- `minimum_recharge_amount` (required, numeric, min: 0.01): Minimum recharge amount to qualify
- `discount_type` (optional, enum): `"percentage"` or `"fixed"`
- `discount_value` (optional, numeric, min: 0): Discount amount (required if `discount_type` is provided)
- `cashback_amount` (optional, numeric, min: 0): Cashback amount (default: 0)
- `validity_start_date` (required, date): Offer start date (YYYY-MM-DD)
- `validity_end_date` (required, date): Offer end date (YYYY-MM-DD, must be >= start date)
- `is_active` (optional, boolean): Whether offer is active (default: true)

**Success Response (201):**
```json
{
    "success": true,
    "message": "Recharge offer added successfully",
    "data": {
        "id": 1,
        "title": "Festive Recharge Offer",
        "description": "Get 10% discount on recharge above ₹500",
        "minimum_recharge_amount": "500.00",
        "discount_type": "percentage",
        "discount_value": "10.00",
        "cashback_amount": "50.00",
        "validity_start_date": "2025-12-01",
        "validity_end_date": "2025-12-31",
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-04T16:12:45.000000Z",
        "updated_at": "2025-12-04T16:12:45.000000Z"
    }
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "title": ["The title field is required."],
        "validity_end_date": ["The validity end date must be a date after or equal to validity start date."]
    }
}
```

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/admin/recharge-offer \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Festive Recharge Offer",
    "description": "Get 10% discount on recharge above ₹500",
    "minimum_recharge_amount": 500,
    "discount_type": "percentage",
    "discount_value": 10,
    "cashback_amount": 50,
    "validity_start_date": "2025-12-01",
    "validity_end_date": "2025-12-31",
    "is_active": true
  }'
```

**Example: Fixed Discount Offer:**
```bash
curl -X POST https://api.alldigtalseva.com/api/admin/recharge-offer \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Flat ₹100 Off",
    "description": "Get flat ₹100 discount on recharge above ₹1000",
    "minimum_recharge_amount": 1000,
    "discount_type": "fixed",
    "discount_value": 100,
    "cashback_amount": 0,
    "validity_start_date": "2025-12-01",
    "validity_end_date": "2025-12-31",
    "is_active": true
  }'
```

**Example: Cashback Only Offer:**
```bash
curl -X POST https://api.alldigtalseva.com/api/admin/recharge-offer \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Cashback Offer",
    "description": "Get ₹50 cashback on recharge above ₹500",
    "minimum_recharge_amount": 500,
    "cashback_amount": 50,
    "validity_start_date": "2025-12-01",
    "validity_end_date": "2025-12-31",
    "is_active": true
  }'
```

---

## Update Offer

Update an existing recharge offer.

**Endpoint:** `PUT /api/admin/recharge-offer/{id}` or `PATCH /api/admin/recharge-offer/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body (all fields optional):**
```json
{
    "title": "Updated Offer Title",
    "description": "Updated description",
    "minimum_recharge_amount": 600,
    "discount_type": "percentage",
    "discount_value": 15,
    "cashback_amount": 75,
    "validity_start_date": "2025-12-05",
    "validity_end_date": "2025-12-31",
    "is_active": false
}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "Recharge offer updated successfully",
    "data": {
        "id": 1,
        "title": "Updated Offer Title",
        "description": "Updated description",
        "minimum_recharge_amount": "600.00",
        "discount_type": "percentage",
        "discount_value": "15.00",
        "cashback_amount": "75.00",
        "validity_start_date": "2025-12-05",
        "validity_end_date": "2025-12-31",
        "is_active": false,
        "created_by": 1,
        "created_at": "2025-12-04T16:12:45.000000Z",
        "updated_at": "2025-12-04T16:15:30.000000Z"
    }
}
```

**Error Response (404):**
```json
{
    "success": false,
    "message": "Recharge offer not found"
}
```

**cURL Example:**
```bash
curl -X PUT https://api.alldigtalseva.com/api/admin/recharge-offer/1 \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "discount_value": 15,
    "cashback_amount": 75
  }'
```

**Deactivate an Offer:**
```bash
curl -X PATCH https://api.alldigtalseva.com/api/admin/recharge-offer/1 \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": false
  }'
```

---

## Delete Offer

Delete a recharge offer.

**Endpoint:** `DELETE /api/admin/recharge-offer/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "Recharge offer deleted successfully"
}
```

**Error Response (404):**
```json
{
    "success": false,
    "message": "Recharge offer not found"
}
```

**cURL Example:**
```bash
curl -X DELETE https://api.alldigtalseva.com/api/admin/recharge-offer/1 \
  -H "Authorization: Bearer {admin_token}"
```

---

## Complete Examples

### Angular Service Example

**recharge-offer.service.ts:**
```typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RechargeOfferService {
  private apiUrl = 'https://api.alldigtalseva.com/api';
  private adminToken = localStorage.getItem('admin_token');

  constructor(private http: HttpClient) {}

  // Public APIs
  getActiveOffers(): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/recharge-offer`);
  }

  getOffer(id: number): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/recharge-offer/${id}`);
  }

  getApplicableOffers(rechargeAmount: number): Observable<any> {
    const params = new HttpParams().set('recharge_amount', rechargeAmount.toString());
    return this.http.get<any>(`${this.apiUrl}/recharge-offer/applicable`, { params });
  }

  // Admin APIs
  getAllOffers(): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/admin/recharge-offer`, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }

  createOffer(offerData: any): Observable<any> {
    return this.http.post<any>(`${this.apiUrl}/admin/recharge-offer`, offerData, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`,
        'Content-Type': 'application/json'
      }
    });
  }

  updateOffer(id: number, offerData: any): Observable<any> {
    return this.http.put<any>(`${this.apiUrl}/admin/recharge-offer/${id}`, offerData, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`,
        'Content-Type': 'application/json'
      }
    });
  }

  deleteOffer(id: number): Observable<any> {
    return this.http.delete<any>(`${this.apiUrl}/admin/recharge-offer/${id}`, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }
}
```

### React Hook Example

**useRechargeOffers.ts:**
```typescript
import { useState, useEffect } from 'react';

export function useRechargeOffers() {
  const [offers, setOffers] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchActiveOffers = async () => {
    setLoading(true);
    try {
      const response = await fetch('https://api.alldigtalseva.com/api/recharge-offer');
      const data = await response.json();
      if (data.success) {
        setOffers(data.data);
      }
    } catch (error) {
      console.error('Failed to fetch offers:', error);
    } finally {
      setLoading(false);
    }
  };

  const getApplicableOffers = async (rechargeAmount: number) => {
    setLoading(true);
    try {
      const response = await fetch(
        `https://api.alldigtalseva.com/api/recharge-offer/applicable?recharge_amount=${rechargeAmount}`
      );
      const data = await response.json();
      if (data.success) {
        return data.data;
      }
    } catch (error) {
      console.error('Failed to fetch applicable offers:', error);
    } finally {
      setLoading(false);
    }
  };

  return {
    offers,
    loading,
    fetchActiveOffers,
    getApplicableOffers
  };
}
```

### Angular Component Example

**recharge-offer.component.ts:**
```typescript
import { Component, OnInit } from '@angular/core';
import { RechargeOfferService } from './recharge-offer.service';

@Component({
  selector: 'app-recharge-offer',
  template: `
    <div *ngFor="let offer of offers">
      <h3>{{ offer.title }}</h3>
      <p>{{ offer.description }}</p>
      <p>Min Recharge: ₹{{ offer.minimum_recharge_amount }}</p>
      <p *ngIf="offer.discount_type === 'percentage'">
        Discount: {{ offer.discount_value }}%
      </p>
      <p *ngIf="offer.discount_type === 'fixed'">
        Discount: ₹{{ offer.discount_value }}
      </p>
      <p *ngIf="offer.cashback_amount > 0">
        Cashback: ₹{{ offer.cashback_amount }}
      </p>
    </div>
  `
})
export class RechargeOfferComponent implements OnInit {
  offers: any[] = [];
  rechargeAmount: number = 0;

  constructor(private offerService: RechargeOfferService) {}

  ngOnInit() {
    this.loadOffers();
  }

  loadOffers() {
    this.offerService.getActiveOffers().subscribe(response => {
      if (response.success) {
        this.offers = response.data;
      }
    });
  }

  checkApplicableOffers() {
    if (this.rechargeAmount > 0) {
      this.offerService.getApplicableOffers(this.rechargeAmount).subscribe(response => {
        if (response.success) {
          this.offers = response.data;
          // Display benefits to user
          response.data.forEach(offer => {
            console.log(`${offer.title}: ${offer.benefit_description}`);
          });
        }
      });
    }
  }
}
```

---

## Important Notes

1. **Discount Types:**
   - `percentage`: Discount is calculated as percentage of recharge amount
   - `fixed`: Fixed discount amount

2. **Offer Validity:**
   - Public APIs only return offers that are:
     - Active (`is_active = true`)
     - Currently within validity period
   - Admin APIs return all offers regardless of status

3. **Applicable Offers:**
   - Only returns offers where `minimum_recharge_amount <= recharge_amount`
   - Benefits are calculated automatically:
     - Percentage discount: `(recharge_amount * discount_value) / 100`
     - Fixed discount: `discount_value`
     - Total benefit: `discount + cashback_amount`

4. **Date Format:**
   - All dates should be in `YYYY-MM-DD` format
   - Example: `"2025-12-01"`

5. **Amount Format:**
   - All amounts are stored with 2 decimal places
   - Minimum recharge amount: ₹0.01

6. **Admin Authentication:**
   - All admin endpoints require Bearer token in Authorization header
   - Token obtained from `/api/admin/login`

---

## Response Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success |
| 201 | Created (for POST requests) |
| 401 | Unauthorized - Invalid or missing admin token |
| 404 | Not Found - Offer not found |
| 422 | Validation Error - Invalid input data |
| 500 | Server Error - Internal server error |

---

## Common Use Cases

### 1. Display All Active Offers to Users
```bash
GET /api/recharge-offer
```

### 2. Check Offers for Specific Recharge Amount
```bash
GET /api/recharge-offer/applicable?recharge_amount=1000
```

### 3. Create Percentage Discount Offer
```json
{
  "title": "10% Off",
  "minimum_recharge_amount": 500,
  "discount_type": "percentage",
  "discount_value": 10,
  "validity_start_date": "2025-12-01",
  "validity_end_date": "2025-12-31"
}
```

### 4. Create Fixed Discount Offer
```json
{
  "title": "Flat ₹100 Off",
  "minimum_recharge_amount": 1000,
  "discount_type": "fixed",
  "discount_value": 100,
  "validity_start_date": "2025-12-01",
  "validity_end_date": "2025-12-31"
}
```

### 5. Create Cashback Only Offer
```json
{
  "title": "₹50 Cashback",
  "minimum_recharge_amount": 500,
  "cashback_amount": 50,
  "validity_start_date": "2025-12-01",
  "validity_end_date": "2025-12-31"
}
```

### 6. Deactivate an Offer
```bash
PATCH /api/admin/recharge-offer/1
{
  "is_active": false
}
```

---

---

## Integration with Top-Up Requests

### How Users Apply Offers

When users create a top-up request, they can include a `recharge_offer_id` to apply an offer:

**Example Request:**
```json
{
    "user_id": 1,
    "upi_id": 1,
    "amount": 1000,
    "recharge_offer_id": 1
}
```

**Benefits Applied:**
- Discount amount is calculated based on offer type (percentage or fixed)
- Cashback amount is added
- Final credited amount = `amount + discount + cashback`

**Example:**
- User requests: ₹1000
- Offer: 10% discount (₹100) + ₹50 cashback
- Final credited: ₹1150

**Note:** See [UPI & Top-Up Request API Documentation](../UPI_TOPUP_API.md) for complete integration details.

---

**Last Updated:** December 4, 2025

