mumz-strapi-plugin-coupon
v5.0.0
Published
Strapi plugin for centralized coupon management across multiple services
Downloads
192
Maintainers
Readme
Strapi Plugin - Coupon Management
A centralized coupon management system for Strapi that handles validation, redemption, and tracking across multiple service domains.
Requirements
- Strapi 5.0.0 or higher
- Node.js 18.0.0 or higher
- npm 6.0.0 or higher
- PostgreSQL, MySQL, or SQLite
Features
- Centralized coupon creation and management
- Service scoping: bind a coupon to one service or keep it global
- Per-service or aggregated usage counting (
scopeMode) - Flexible discount types (percentage, flat)
- Max discount cap for percentage coupons (e.g., 50% off, max 100 AED)
- Per-user and global usage limits
- Validity period enforcement
- User restriction lists (phone number blocklist)
- Complete redemption audit trail, queryable over HTTP
- Bulk CSV import (up to 10,000 coupons)
- RESTful API endpoints
- Race condition protection via optimistic locking
- Rate limiting on public endpoints
- TypeScript with full type definitions
Installation
1. Install the package
# npm
npm install mumz-strapi-plugin-coupon
# yarn
yarn add mumz-strapi-plugin-coupon
# From GitHub (private repo)
npm install git+https://github.com/mumzworld-tech/mumz-services-coupons-strapi-plugin.git#v4.0.02. Enable the plugin
Add to your Strapi project's config/plugins.ts (or config/plugins.js):
// config/plugins.ts
export default () => ({
coupon: {
enabled: true,
resolve: './node_modules/mumz-strapi-plugin-coupon',
},
});3. Build and restart Strapi
npm run build
npm run developOn first startup, Strapi auto-creates the coupons and redemptions tables. No manual migration needed.
4. Configure permissions (optional)
By default, all routes have auth: false. To restrict admin endpoints:
- Go to Settings > Roles > Public in Strapi admin
- Under the Coupon plugin, enable only the endpoints you want public (typically
validateandredeem) - Disable
create,update,delete,bulk-createfor public access
API Endpoints
Base path: /api/coupon
| Method | Path | Description | Rate Limit |
|--------|------|-------------|------------|
| POST | /validate | Validate coupon for a user/order | 10 req/min |
| POST | /redeem | Redeem coupon after payment | 5 req/min |
| POST | / | Create a single coupon | None |
| GET | / | List all coupons | None |
| GET | /:id | Get coupon by ID | None |
| PUT | /:id | Update coupon | None |
| DELETE | /:id | Delete coupon | None |
| GET | /redemptions | List redemptions (audit trail) | None |
| GET | /csv-template | Download CSV template | None |
| POST | /bulk-create | Bulk create from CSV data | None |
Validate Coupon
Check if a coupon is valid for a user and calculate the discount.
service is required — it identifies the calling service and scopes both the
lookup and the usage counting (see Service scoping).
POST /api/coupon/validate
Content-Type: application/json
{
"couponCode": "SUMMER25",
"phoneNumber": "971501234567",
"orderAmount": 500,
"service": "nannies"
}Response (success):
{
"isValid": true,
"discountType": "percentage",
"discountValue": 25,
"maxDiscountAmount": 100,
"discountAmount": 100,
"finalAmount": 400,
"message": "Coupon applied successfully."
}Note: discountAmount is 100 (capped), not 125 (25% of 500), because maxDiscountAmount is 100.
Response (error):
{
"isValid": false,
"errorCode": "COUPON_EXPIRED",
"message": "This coupon has expired."
}Redeem Coupon
Redeem after successful payment. Creates an audit trail and increments usage counter.
service is required and must match the value sent to /validate for the
same order, otherwise usage counting is split across two services.
POST /api/coupon/redeem
Content-Type: application/json
{
"couponCode": "SUMMER25",
"phoneNumber": "971501234567",
"orderId": "ORD-12345",
"orderAmount": 500,
"service": "nannies"
}Response:
{
"success": true,
"message": "Coupon redeemed successfully.",
"redemptionId": "redeem_42"
}Create Coupon
POST /api/coupon
Content-Type: application/json
{
"code": "SUMMER25",
"service": "nannies",
"scopeMode": "per-service",
"discountType": "percentage",
"discountValue": 25,
"maxDiscountAmount": 100,
"maxUsage": 1000,
"maxUsagePerUser": 1,
"isActive": true,
"validFrom": "2025-06-01T00:00:00.000Z",
"validTo": "2025-08-31T23:59:59.000Z",
"description": "Summer sale - 25% off, max 100 AED",
"userRestrictions": ["971500000000"]
}Omit service (or send null) to create a GLOBAL coupon usable by every
service. Omit scopeMode to get the default, per-service. Omit isActive to
default to true.
Bulk Create (CSV)
POST /api/coupon/bulk-create
Content-Type: application/json
{
"coupons": [
{
"_row": 1,
"code": "BULK001",
"service": "nannies",
"scopeMode": "per-service",
"discountType": "percentage",
"discountValue": 20,
"maxDiscountAmount": 50,
"maxUsage": 100,
"maxUsagePerUser": 1,
"validFrom": "2025-01-01T00:00:00.000Z",
"validTo": "2025-12-31T23:59:59.000Z"
}
]
}Rows carrying _row are treated as already parsed and are used as-is, so they
must supply service / scopeMode themselves. Omitting a key applies the
defaults on create (service → null, scopeMode → per-service); on update, an
omitted key leaves the existing coupon's scoping untouched.
List Redemptions
GET /api/coupon/redemptions?service=nannies&couponCode=SUMMER25&page=1&pageSize=25| Query param | Default | Description |
|-------------|---------|-------------|
| couponCode | – | Upper-cased and matched against the redemption's own denormalized code, so redemptions whose coupon was deleted stay reachable |
| service | – | Service the redemption was made under |
| phoneNumber | – | Redeeming user |
| page | 1 | 1-based page number |
| pageSize | 25 | Rows per page, capped at 100 |
Response:
{
"results": [
{
"id": 42,
"service": "nannies",
"couponCode": "SUMMER25",
"orderId": "ORD-12345",
"phoneNumber": "971501234567",
"redemptionDate": "2026-08-17T09:12:44.000Z",
"discountType": "percentage",
"discountValue": 25,
"metadata": { "orderAmount": 500, "discountAmount": 100, "finalAmount": 400, "service": "nannies" }
}
],
"pagination": { "page": 1, "pageSize": 25, "pageCount": 3, "total": 68 }
}Ordered by redemptionDate descending. Unknown filter values are not rejected —
they simply return an empty page. This endpoint returns PII (phone numbers) and,
like every route in this plugin, ships with auth: false; front it with an API
token or a network policy in the host app.
Service scoping
Each coupon carries two scoping fields.
service decides who can use the coupon:
| service | Behaviour |
|-----------|-----------|
| null (default) | GLOBAL — every service can find and use the coupon |
| "nannies" | Only requests sent with "service": "nannies" resolve it |
A coupon bound to another service is reported as COUPON_NOT_FOUND, so a code
cannot be probed from a service it does not belong to.
scopeMode decides how usage is counted:
| scopeMode | Behaviour |
|-------------|-----------|
| per-service (default) | maxUsage / maxUsagePerUser are counted from redemptions made under the requesting service only |
| global | Counts aggregate across all services |
per-service is most useful on a GLOBAL coupon: e.g. WELCOME10 with
service: null, scopeMode: 'per-service' and maxUsagePerUser: 1 lets each
customer use the code once per service. Setting scopeMode: 'global' on the
same coupon gives them one use in total, whichever service they use first.
Coupon Schema
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| code | string | Yes | - | Unique, 3-50 uppercase alphanumeric |
| service | string | No | null | Owning service; null = global (any service) |
| scopeMode | enum | Yes | per-service | per-service or global usage counting |
| discountType | enum | Yes | percentage | percentage or flat |
| discountValue | decimal | Yes | - | Discount value (% or AED) |
| maxDiscountAmount | decimal | No | null | Max discount cap in AED (percentage only) |
| maxUsage | integer | No | null | Total redemptions allowed (null = unlimited) |
| maxUsagePerUser | integer | No | null | Per-user redemptions (null = 1, 0 = unlimited) |
| currentUsage | integer | Yes | 0 | Current total redemption count |
| validFrom | datetime | Yes | - | Start of validity period |
| validTo | datetime | Yes | - | End of validity period |
| isActive | boolean | Yes | true | Manual on/off toggle |
| description | text | No | null | Admin-facing description |
| userRestrictions | json | No | null | Array of blocked phone numbers |
Redemption Schema
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| coupon | relation | No | The redeemed coupon (null once that coupon is deleted) |
| service | string | No | Service the redemption happened under — the basis for per-service counting |
| couponCode | string | No | Denormalized code, captured at redemption time so the row stays auditable after the coupon is deleted |
| orderId | string | Yes | Order the coupon was redeemed against |
| phoneNumber | string | Yes | Redeeming user |
| redemptionDate | datetime | Yes | When it was redeemed |
| discountType | string | Yes | Copy of the coupon's discount type |
| discountValue | decimal | Yes | Copy of the coupon's discount value |
| metadata | json | No | orderAmount, discountAmount, finalAmount, service |
service and couponCode are nullable on purpose: rows written before v4.0.0
have neither, and making them required would break Strapi's schema sync on
existing installs.
maxUsagePerUser Logic
| Value | Behavior |
|-------|----------|
| null | 1 use per user (default) |
| 0 | Unlimited uses per user |
| N | N uses per user |
maxDiscountAmount Logic
Only applies when discountType is percentage. Ignored for flat discounts.
| Coupon | Order | Raw Discount | Cap | Final Discount | |--------|-------|-------------|-----|----------------| | 50% off, max 100 AED | 500 AED | 250 AED | 100 AED | 100 AED | | 50% off, max 100 AED | 150 AED | 75 AED | 100 AED | 75 AED | | 50% off, no cap | 500 AED | 250 AED | - | 250 AED | | 10 AED flat | 500 AED | 10 AED | ignored | 10 AED |
Error Codes
| Code | Description |
|------|-------------|
| COUPON_NOT_FOUND | Coupon code does not exist — or is bound to a different service |
| COUPON_EXPIRED | Coupon is inactive or outside validity period |
| COUPON_ALREADY_USED | Per-user usage limit reached |
| USAGE_LIMIT_REACHED | Global usage limit reached |
| INVALID_REQUEST | Invalid input (bad phone, negative amount, etc.) |
| USER_RESTRICTED | Phone number is on the blocklist |
CSV Bulk Import
Template columns
code,service,scopeMode,discountType,discountValue,maxDiscountAmount,maxUsage,maxUsagePerUser,validFrom,validTo,isActive,description,userRestrictionsDownload template via GET /api/coupon/csv-template.
service / scopeMode columns
Both are optional and understood by the API parser and the admin-panel parser alike:
- Blank cell → the column is omitted from the payload, so the defaults apply
on create (
service → null= global,scopeMode → per-service). On update of an existing code, a blank cell leaves the coupon's current scoping untouched — re-importing an older CSV that predates these columns cannot silently re-scope your coupons. scopeModeis case-insensitive but must beglobalorper-service; anything else fails that row with an error naming the column.serviceis trimmed and must be non-empty when supplied.
Admin Panel
The plugin adds a Coupon Bulk menu item in the Strapi admin sidebar. From there you can:
- Download the CSV template
- Upload a CSV file to bulk create coupons
- View import results (created/failed with row-level errors)
Integration Guide
Typical flow for client applications
1. Customer enters coupon code at checkout
2. Client calls POST /api/coupon/validate with code + phone + orderAmount + service
3. If isValid=true, display discountAmount and finalAmount to customer
4. After payment succeeds, call POST /api/coupon/redeem with orderId + the same service
5. Store the redemptionId for referenceSend your own service identifier (nannies, wallpaper, tutor-at-home, …) as
service on both calls. Using different values for the same order splits usage
counting between two services.
Concurrent redemption safety
The plugin uses optimistic locking (compare-and-set) on currentUsage. If two requests try to redeem the same coupon simultaneously, only one succeeds. The other gets USAGE_LIMIT_REACHED and can simply retry. No external locking or Redis required.
Because that counter lives on the coupon row, the lock is shared across services: two services redeeming the same GLOBAL coupon at the same instant contend on it even under scopeMode: 'per-service'. Limits themselves stay correct — per-service coupons are bounded by counting redemption rows filtered by service, and currentUsage only bounds maxUsage for global coupons.
Environment considerations
- Development: Schema auto-syncs on Strapi restart
- Production: All v4.0.0 columns (
coupons.service,coupons.scope_mode,coupon_redemptions.service,coupon_redemptions.coupon_code) are added by schema sync with safe defaults, so no manual migration is needed. Existing coupons do, however, becomeper-servicecounted while historic redemptions carry noservice— read the Migration notes in CHANGELOG.md before upgrading a live install.
