forked from django-oscar/django-oscar-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_sample_coupons.py
More file actions
170 lines (146 loc) · 6.49 KB
/
Copy pathcreate_sample_coupons.py
File metadata and controls
170 lines (146 loc) · 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python
"""
Create sample coupons/vouchers with various conditions and configurations.
Generates 15 different voucher examples demonstrating all features.
"""
import os
import sys
import django
from datetime import datetime, timedelta
from django.utils import timezone
sys.path.insert(0, os.path.join(os.getcwd(), 'sandbox'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.sandbox')
django.setup()
from oscar.apps.voucher.models import Voucher
from oscar.apps.offer.models import ConditionalOffer, Benefit, Condition, Range
from oscar.apps.catalogue.models import Product
from django.contrib.auth.models import User
print("=" * 80)
print("CREATING 15 SAMPLE COUPONS WITH VARIOUS CONDITIONS")
print("=" * 80)
# Get or create ranges
all_products_range, _ = Range.objects.get_or_create(
name='All products',
defaults={'includes_all_products': True}
)
# Helper function to create voucher with offer
def create_voucher_with_offer(code, description, benefit_type, benefit_value,
condition_type, condition_value, range_obj=None):
"""Create a voucher with associated offer, benefit, and condition"""
try:
# Use all products range if none provided
if range_obj is None:
range_obj = all_products_range
# Create voucher
voucher, created = Voucher.objects.get_or_create(
code=code,
defaults={
'name': description,
'usage': Voucher.MULTI_USE,
'num_basket_additions': 1000,
'start_datetime': timezone.now(),
'end_datetime': timezone.now() + timedelta(days=365),
}
)
if not created:
print(f"⚠️ Voucher {code} already exists")
return voucher
# Create benefit with proper range - use defaults filter to allow duplicates
benefit, _ = Benefit.objects.get_or_create(
type=benefit_type,
value=benefit_value,
range=range_obj,
)
# Create condition with proper range - filter by all fields for uniqueness
# Use filter instead of get_or_create to avoid issues with multiple conditions
conditions = Condition.objects.filter(
type=condition_type,
value=condition_value,
range=range_obj
)
if conditions.exists():
condition = conditions.first()
else:
condition = Condition.objects.create(
type=condition_type,
value=condition_value,
range=range_obj,
)
# Create conditional offer
offer, _ = ConditionalOffer.objects.get_or_create(
name=f"{code} Offer",
defaults={
'offer_type': ConditionalOffer.SITE,
'benefit': benefit,
'condition': condition,
'priority': 0,
'exclusive': False,
'status': ConditionalOffer.OPEN,
'description': description,
}
)
# Link voucher to offer
if offer not in voucher.offers.all():
voucher.offers.add(offer)
print(f"✅ Created voucher: {code:20s} - {description}")
return voucher
except Exception as e:
print(f"❌ Error creating {code}: {e}")
return None
# Get some products
products = list(Product.objects.all()[:5])
if not products:
print("⚠️ No products found. Make sure you've loaded fixtures.")
sys.exit(1)
print(f"\nFound {len(products)} products in database")
print()
# 1. Percentage discounts (all products)
print("1️⃣ PERCENTAGE DISCOUNTS (All Products)")
print("-" * 80)
create_voucher_with_offer('SAVE10', 'Save 10% on everything', Benefit.PERCENTAGE, 10, Condition.VALUE, 0)
create_voucher_with_offer('SUMMER20', 'Summer sale - 20% off', Benefit.PERCENTAGE, 20, Condition.VALUE, 0)
create_voucher_with_offer('BIGSAVE30', 'Big sale - 30% off', Benefit.PERCENTAGE, 30, Condition.VALUE, 0)
create_voucher_with_offer('FLASH15', 'Flash sale - 15% off', Benefit.PERCENTAGE, 15, Condition.VALUE, 0)
create_voucher_with_offer('BLACKFRI50', 'Black Friday - 50% off', Benefit.PERCENTAGE, 50, Condition.VALUE, 0)
# 2. Fixed amount discounts (all products)
print("\n2️⃣ FIXED AMOUNT DISCOUNTS (All Products)")
print("-" * 80)
create_voucher_with_offer('SAVE10DOLLARS', 'Save $10 on purchases', Benefit.FIXED, 10, Condition.VALUE, 0)
create_voucher_with_offer('WELCOME5', 'Welcome discount - $5 off', Benefit.FIXED, 5, Condition.VALUE, 0)
create_voucher_with_offer('MEGA25', 'Mega discount - $25 off', Benefit.FIXED, 25, Condition.VALUE, 0)
# 3. Minimum purchase requirements
print("\n3️⃣ MINIMUM PURCHASE REQUIREMENTS")
print("-" * 80)
create_voucher_with_offer('MIN50SAVE10', '$10 off orders $50+', Benefit.FIXED, 10, Condition.VALUE, 50)
create_voucher_with_offer('MIN100PERC15', '15% off orders $100+', Benefit.PERCENTAGE, 15, Condition.VALUE, 100)
# 4. VIP & Loyalty coupons
print("\n4️⃣ VIP & LOYALTY COUPONS")
print("-" * 80)
create_voucher_with_offer('VIP35', 'VIP member - 35% off', Benefit.PERCENTAGE, 35, Condition.VALUE, 0)
create_voucher_with_offer('LOYALTY12', 'Loyalty reward - 12% off', Benefit.PERCENTAGE, 12, Condition.VALUE, 0)
create_voucher_with_offer('BIRTHDAY20', 'Birthday special - 20% off', Benefit.PERCENTAGE, 20, Condition.VALUE, 0)
# 5. Seasonal & Limited-time offers
print("\n5️⃣ SEASONAL & LIMITED-TIME OFFERS")
print("-" * 80)
create_voucher_with_offer('NEWYEAR2026', 'New Year 2026 - 25% off', Benefit.PERCENTAGE, 25, Condition.VALUE, 0)
create_voucher_with_offer('CYBERMON40', 'Cyber Monday - 40% off', Benefit.PERCENTAGE, 40, Condition.VALUE, 0)
print()
print("=" * 80)
print("📊 SUMMARY")
print("=" * 80)
print()
active_vouchers = Voucher.objects.filter(end_datetime__gte=timezone.now()).order_by('code')
print(f"✅ Total Active Vouchers: {active_vouchers.count()}")
print()
for voucher in active_vouchers:
print(f" • {voucher.code:20s} - {voucher.name}")
if voucher.offers.exists():
offer = voucher.offers.first()
if offer.benefit and offer.condition:
benefit_display = f"{offer.benefit.get_type_display()}: {offer.benefit.value}"
condition_display = f"{offer.condition.get_type_display()}: {offer.condition.value}"
print(f" └─ Benefit: {benefit_display:30s} | Condition: {condition_display}")
print()
print("=" * 80)
print("✅ All coupons created successfully!")
print("=" * 80)