Developing Discount and Promotion System for E-commerce
Discount system — not just "crossed-out price". It's engine managing multi-level rules: promotional pricing, volume discounts, timed sales, combined conditions. Poor implementation causes rule conflicts, incorrect totals, margin leaks. Takes 5–9 business days.
Discount Types and Priority
Multiple discount types coexist. Application order critical:
-
Product sale price (
sale_priceat SKU level) — baseline, always applied - Category discount — percent on all products in period
- Volume discount — price drops buying N units
- User segment discount — VIP clients, wholesalers
- Promo code — on top of applied discounts (or instead — depends on rule)
Stacking defined per promotion: exclusive (no mixing), stackable (sums), override (cancels others).
Promotion Data Model
CREATE TABLE promotions (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
type VARCHAR(30) NOT NULL,
priority INT DEFAULT 0,
stackable BOOLEAN DEFAULT FALSE,
conditions JSONB DEFAULT '{}',
actions JSONB DEFAULT '{}',
starts_at TIMESTAMP,
ends_at TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE
);
conditions and actions in JSONB allow arbitrary rules without schema changes:
{
"conditions": {
"min_qty": 3,
"product_ids": [101, 102, 103],
"user_segments": ["wholesale"]
},
"actions": {
"type": "percent_discount",
"value": 15,
"applies_to": "matching_items"
}
}
Discount Engine
Class DiscountEngine applies rules sequentially:
class DiscountEngine {
private array $rules = [];
public function __construct(Collection $activePromotions) {
foreach ($activePromotions->sortByDesc('priority') as $promo) {
$this->rules[] = PromotionRuleFactory::make($promo);
}
}
public function apply(Cart $cart): DiscountResult {
$result = new DiscountResult($cart);
foreach ($this->rules as $rule) {
if (!$rule->matches($cart)) continue;
if (!$rule->isStackable() && $result->hasDiscount()) continue;
$result->addDiscount($rule->calculate($cart));
if ($rule->isExclusive()) break;
}
return $result;
}
}
Volume Pricing
Step prices by quantity — common B2C and B2B request:
class VolumePricingRule implements PromotionRule {
public function calculate(Cart $cart): array {
$discounts = [];
foreach ($cart->items as $item) {
$tier = $this->getTier($item->product_id, $item->quantity);
if ($tier) {
$discounts[] = [
'item_id' => $item->id,
'amount' => ($item->price - $tier->price) * $item->quantity,
'label' => "Volume discount (×{$item->quantity})",
];
}
}
return $discounts;
}
private function getTier(int $productId, int $qty): ?VolumeTier {
return VolumeTier::where('product_id', $productId)
->where('min_qty', '<=', $qty)
->orderByDesc('min_qty')
->first();
}
}
Timed Sales with Countdown
For "hot" deals frontend shows countdown timer. Current sale price sent with end time:
interface PriceData {
regular_price: number;
sale_price: number | null;
sale_ends_at: string | null;
}
Timer component:
const SaleTimer = ({ endsAt }: { endsAt: string }) => {
const [remaining, setRemaining] = useState(differenceInSeconds(parseISO(endsAt), new Date()));
useEffect(() => {
const interval = setInterval(() => {
setRemaining(prev => Math.max(0, prev - 1));
}, 1000);
return () => clearInterval(interval);
}, []);
const hours = Math.floor(remaining / 3600);
const minutes = Math.floor((remaining % 3600) / 60);
const seconds = remaining % 60;
return (
<div className="flex gap-1 font-mono text-red-600">
<span>{String(hours).padStart(2, '0')}</span>:
<span>{String(minutes).padStart(2, '0')}</span>:
<span>{String(seconds).padStart(2, '0')}</span>
</div>
);
};
BOGO (Buy One Get One)
"Buy 2 get 1 free" implemented as separate rule:
class BogoRule implements PromotionRule {
public function calculate(Cart $cart): array {
$qualifying = $cart->items->filter(fn($i) => in_array($i->product_id, $this->productIds));
$totalQty = $qualifying->sum('quantity');
$freeQty = intdiv($totalQty, $this->buyQty);
$cheapestPrice = $qualifying->min('price');
return [['amount' => $cheapestPrice * $freeQty, 'label' => '2+1 Promotion']];
}
}
Discount Display
- Crossed original price next to sale price
- Badge "−20%" or "−500 ₽" depending on type
- For volume pricing — tier table on product card
- "Sales only" filter in catalog — SQL
WHERE sale_price IS NOT NULL AND sale_ends_at > NOW()
Promotion Scheduler
Auto start/end via Laravel Scheduler:
$schedule->command('promotions:activate')->everyMinute();
$schedule->command('promotions:expire')->everyMinute();
On activate, price cache invalidated. For large catalogs (10k+ SKU) via queue, not sync.
Reporting
Admin shows per promotion: application count, total discounts, conversion with/without, top products by revenue. Minimum data for effectiveness assessment.







