-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
148 lines (127 loc) · 4.28 KB
/
server.py
File metadata and controls
148 lines (127 loc) · 4.28 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
#!/usr/bin/env python3
import socket
import pickle
from tinydb import TinyDB
from datetime import datetime, date
from tinydb.operations import increment
from configs.constants import PORT, HOST
couponDB = TinyDB("database/coupon.json")
productDB = TinyDB("database/product.json")
accountDB = TinyDB("database/account.json")
transationDB = TinyDB("database/transaction.json")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
socket_client, (host, port) = server.accept()
print(f'🚀 Server is now running on port {PORT} 🚀')
while True:
data = socket_client.recv(1024)
if not data: break
response = pickle.loads(data)
if response["type"] == "createTransaction":
balance = response["balance"]
coupon = response["coupon"]
couponID = response["couponID"]
subtotal = response["subtotal"]
cart = response["cart"]
paymentType = response["paymentType"]
subtotal = subtotal - (subtotal * (int(coupon[4:]) / 100)) if coupon else subtotal
# Calculate the new card payment balance and return the changes if payment method is cash.
newBalance = balance - subtotal
# Proceed if user user has enough money
if subtotal <= balance:
# Decrement stock
for product in cart.values():
productDB.update({
"quantity": product["quantity"] - product["amount"]
}, doc_ids=[product["id"]])
# Update Balance
if paymentType == "card":
accountDB.update({ "balance": round(newBalance, 2) }, doc_ids=[1])
# Delete coupon
if coupon:
couponDB.remove(doc_ids=[couponID])
# Log trasaction
transactionID = transationDB.insert({
"timestamp": str(date.today()),
"subtotal": round(response["subtotal"], 2),
"coupon": coupon,
"discount": round(subtotal * (int(coupon[4:]) / 100) if coupon else 0, 2),
"cart": cart,
"change": round(newBalance, 2)
})
socket_client.send(pickle.dumps({
"success": True,
"balance": round(newBalance, 2),
"products": productDB.all(),
"transactionID": transactionID
}))
else:
socket_client.send(pickle.dumps({
"success": False,
"message": "Not Enough\nMoney"
}))
if response["type"] == "getCoupons":
coupons = couponDB.all()
data = {}
if coupons:
data = {
"success": True,
"message": None,
"size": len(coupons),
"coupons": coupons
}
else:
data = {
"success": False,
"message": "You don't have any coupons with you. Play the lottery to increase your chances of winning.",
"size": 0,
"coupons": []
}
socket_client.send(pickle.dumps(data))
if response["type"] == "getInventory":
products = productDB.all()
labels = []
sizes = []
colors = []
# arguments required for matlibplot library
# When the stock is low, it is red; when it is moderately low, it is orange; and when the stock is under control, it is green.
for product in productDB:
labels.append(product["name"])
sizes.append(product["quantity"])
if product["quantity"] < 10:
colors.append("red")
elif product["quantity"] in range(10, 20):
colors.append("orange")
else:
colors.append("#55b70b")
data = {}
if products:
data = {
"success": True,
"message": None,
"labels": tuple(labels),
"sizes": sizes,
"colors": colors
}
else:
data = {
"success": False,
"message": "Can't fetch inventory",
"labels": labels,
"sizes": sizes,
"colors": colors
}
socket_client.send(pickle.dumps(data))
if response["type"] == "updateAccountBalance":
success = accountDB.update({"balance": round(response["newBalance"], 2)}, doc_ids=[1])
socket_client.send(pickle.dumps({ "success": True if success else False }))
if response["type"] == "updateTicketBalance":
success = accountDB.update(increment("lotteryTickets"), doc_ids=[1])
socket_client.send(pickle.dumps({ "success": True if success else False }))
if response["type"] == "generateCoupon":
today = datetime.now()
couponDB.insert({
'coupon': response["coupon"],
'timestamp': str(today)
})