-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock_coupon_server.py
More file actions
150 lines (134 loc) · 5.43 KB
/
Copy pathmock_coupon_server.py
File metadata and controls
150 lines (134 loc) · 5.43 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
#!/usr/bin/env python3
"""
Simple mock coupon service for demonstration purposes
"""
import json
import time
from datetime import datetime, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import uuid
# Mock data storage
coupons = []
# Sample coupons
sample_coupons = [
{
"id": str(uuid.uuid4()),
"code": "WELCOME20",
"name": "Welcome Bonus",
"description": "20% off for new customers",
"type": "WELCOME",
"discountType": "PERCENTAGE",
"discountValue": 20.0,
"minimumOrderAmount": 50.0,
"maximumDiscountAmount": 100.0,
"usageLimit": 1000,
"usageLimitPerUser": 1,
"usageCount": 45,
"validFrom": "2024-01-01T00:00:00",
"validUntil": "2024-12-31T23:59:59",
"isPublic": True,
"status": "ACTIVE",
"createdAt": "2024-01-01T00:00:00",
"updatedAt": "2024-01-01T00:00:00"
},
{
"id": str(uuid.uuid4()),
"code": "FLASH15",
"name": "Flash Sale",
"description": "Limited time 15% discount",
"type": "FLASH_SALE",
"discountType": "PERCENTAGE",
"discountValue": 15.0,
"minimumOrderAmount": 25.0,
"maximumDiscountAmount": 75.0,
"usageLimit": 500,
"usageLimitPerUser": 1,
"usageCount": 234,
"validFrom": "2024-03-01T00:00:00",
"validUntil": "2024-03-31T23:59:59",
"isPublic": True,
"status": "ACTIVE",
"createdAt": "2024-03-01T00:00:00",
"updatedAt": "2024-03-01T00:00:00"
}
]
coupons.extend(sample_coupons)
class CouponHandler(BaseHTTPRequestHandler):
def _set_headers(self, status=200):
self.send_response(status)
self.send_header('Content-type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
self.end_headers()
def do_OPTIONS(self):
self._set_headers()
def do_GET(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
if path == '/api/v1/coupons':
self._set_headers()
response = {
"content": coupons,
"totalElements": len(coupons),
"totalPages": 1,
"size": len(coupons),
"number": 0
}
self.wfile.write(json.dumps(response).encode())
elif path == '/api/v1/coupons/health':
self._set_headers()
self.wfile.write(json.dumps({"status": "UP"}).encode())
else:
self._set_headers(404)
self.wfile.write(json.dumps({"error": "Not found"}).encode())
def do_POST(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
if path == '/api/v1/coupons':
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
try:
coupon_data = json.loads(post_data.decode('utf-8'))
# Create new coupon
new_coupon = {
"id": str(uuid.uuid4()),
"code": coupon_data.get("code"),
"name": coupon_data.get("name"),
"description": coupon_data.get("description", ""),
"type": coupon_data.get("type"),
"discountType": coupon_data.get("discountType"),
"discountValue": coupon_data.get("discountValue"),
"minimumOrderAmount": coupon_data.get("minimumOrderAmount"),
"maximumDiscountAmount": coupon_data.get("maximumDiscountAmount"),
"usageLimit": coupon_data.get("usageLimit"),
"usageLimitPerUser": coupon_data.get("usageLimitPerUser", 1),
"usageCount": 0,
"validFrom": coupon_data.get("validFrom"),
"validUntil": coupon_data.get("validUntil"),
"isPublic": coupon_data.get("isPublic", True),
"allowedUserIds": coupon_data.get("allowedUserIds"),
"applicableCategories": coupon_data.get("applicableCategories"),
"applicableProductIds": coupon_data.get("applicableProductIds"),
"status": "ACTIVE",
"createdAt": datetime.now().isoformat(),
"updatedAt": datetime.now().isoformat()
}
coupons.append(new_coupon)
self._set_headers(201)
self.wfile.write(json.dumps(new_coupon).encode())
except json.JSONDecodeError:
self._set_headers(400)
self.wfile.write(json.dumps({"error": "Invalid JSON"}).encode())
else:
self._set_headers(404)
self.wfile.write(json.dumps({"error": "Not found"}).encode())
def log_message(self, format, *args):
print(f"[{datetime.now()}] {format % args}")
if __name__ == '__main__':
server_address = ('', 8086)
httpd = HTTPServer(server_address, CouponHandler)
print(f"Mock Coupon Service running on port 8086...")
print(f"Access at: http://localhost:8086/api/v1/coupons")
httpd.serve_forever()