-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
299 lines (244 loc) · 9.08 KB
/
models.py
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import datetime
from decimal import Decimal
import random
import re
import string
import uuid
from peewee import *
from flask_peewee.utils import get_dictionary_from_model
if __name__ == '__main__':
from shoptet_api.app import db
else:
from app import db
# db = SqliteDatabase('shoptet.db')
# TODO make mapping from shoptet to choices (regex?)
# there will be multiple options merged to one
# ORDER_STATUS_CHOICES = [
# ('new', 'Prijatá'),
# ('prepared', 'Pripravená'),
# ('completed', 'Vybavená'),
# ('cancelled', 'Stornovaná')
# ]
LOG_ENTITIES = [
('user', 'User'),
('order', 'Order'),
('voucher', 'Voucher'),
('system', 'System'),
]
LOG_EVENTS = [
('create', 'Create'),
('read', 'Read'),
('update', 'Update'),
('delete', 'Delete'),
]
ROLES = [
('sysuser', 'System User'),
('admin', 'Admin'),
('wizard', 'Wizard'),
]
class DBModel(Model):
class Meta:
database = db
date_format = '%Y-%m-%d'
time_format = '%H:%M:%S'
datetime_format = ' '.join([date_format, time_format])
create_date = DateTimeField(default=datetime.datetime.now)
write_date = DateTimeField(default=datetime.datetime.now)
def convert_value(self, value):
if isinstance(value, datetime.datetime):
return value.strftime(self.datetime_format)
elif isinstance(value, datetime.date):
return value.strftime(self.date_format)
elif isinstance(value, datetime.time):
return value.strftime(self.time_format)
elif isinstance(value, Model):
return value._pk
elif isinstance(value, (uuid.UUID, Decimal)):
return str(value)
else:
return value
def clean_data(self, data):
for key, value in data.items():
if isinstance(value, dict):
self.clean_data(value)
elif isinstance(value, (list, tuple)):
data[key] = map(self.clean_data, value)
else:
data[key] = self.convert_value(value)
return data
def save(self, *args, **kwargs):
_now = datetime.datetime.now()
self.__data__.update({'write_date': _now})
return super().save(*args, **kwargs)
def serialize(self, fields=None, exclude=None):
data = get_dictionary_from_model(self, fields, exclude)
return self.clean_data(data)
@property
def serialized(self):
# returns all fields
return self.serialize()
class SysUser(DBModel):
username = CharField()
password = CharField()
role = CharField(choices=ROLES, default='sysuser')
class MissingKeyError(BaseException):
pass
check_code_or_email = Check('code is not null or email is not null')
class User(DBModel):
code = CharField(null=True, constraints=[check_code_or_email])
email = CharField(null=True, constraints=[check_code_or_email])
name = CharField(null=True)
street = CharField(null=True)
zip = CharField(null=True)
city = CharField(null=True)
country = CharField(null=True)
phone = CharField(null=True)
registered = BooleanField(default=False)
optin = BooleanField(default=False)
class Shop(DBModel):
name = CharField()
email = CharField(null=True)
image = CharField(null=True)
web = CharField(null=True)
street = CharField(null=True)
zip = CharField(null=True)
city = CharField(null=True)
country = CharField(null=True)
phone = CharField(null=True)
class Order(DBModel):
shop_order_id = IntegerField(null=True)
order_num = CharField(null=True)
price_no_vat = DecimalField()
vat = DecimalField()
total_price = DecimalField()
price_applicable = DecimalField(null=True) # price applicable for loyalty system
discount = DecimalField(null=True) # if any, no loyalty
shipping = CharField(null=True)
shipping_cost = DecimalField(null=True) # this does not count in loyalty system
status = CharField(default='') #choices=ORDER_STATUS_CHOICES)
user_id = ForeignKeyField(User, backref='orders')
open_date = DateTimeField()
close_date = DateTimeField(null=True)
url = CharField(null=True) # used for storing url in eshop for easier access
next_url = CharField(null=True) # url of the next order
closed = BooleanField(default=False)
class OrderLine(DBModel):
order_id = ForeignKeyField(Order, backref='order_lines')
code = CharField(null=True)
description = CharField(default='')
amount = DecimalField()
unit = CharField(null=True)
unit_price = DecimalField()
vat_rate = DecimalField()
total_price = DecimalField()
discount_percent = DecimalField(null=True)
image = CharField(null=True)
def str2d(s, in_format='%Y-%m-%d'):
return datetime.datetime.strptime(s, in_format)
class Voucher(DBModel):
voucher_id = IntegerField()
voucher_code = CharField()
voucher_type = CharField(null=True)
amount = DecimalField(null=True)
valid_from = DateField(null=True)
valid_to = DateField(null=True)
user_id = ForeignKeyField(User, backref='vouchers')
def is_valid(self):
today = datetime.date.today()
before = not self.valid_from or str2d(self.valid_from) <= today
after = not self.valid_to or str2d(self.valid_to) >= today
return before and after
class Credit(DBModel):
user_id = ForeignKeyField(User, backref='users')
credit_date = DateTimeField(default=datetime.datetime.now)
amount = DecimalField(default=0)
order_id = ForeignKeyField(Order, backref='credit', null=True)
voucher_id = ForeignKeyField(Voucher, backref='credit', null=True)
note = CharField(null=True)
class Log(DBModel):
log_time = DateTimeField(default=datetime.datetime.now)
event = CharField(choices=LOG_EVENTS)
model = CharField(null=True)
record = IntegerField(null=True)
user_id = ForeignKeyField(SysUser, backref='logs', null=True)
details = CharField(null=True)
def process_order_line(order_line):
code = order_line.get('code', None)
description = order_line.get('description', '')
amount = Decimal(order_line.get('amount', '0'))
unit = None
unit_price = Decimal(order_line.get('unit_price', '0.00'))
vat_rate = Decimal(order_line.get('vat_rate', '20.0'))
total_price = Decimal(order_line.get('total_vat_including', '0.0'))
image = order_line.get('img')
discount_percent = order_line.get('discount_percent')
return {
'code': code, 'description': description, 'amount': amount, 'unit': unit,
'unit_price': unit_price, 'vat_rate': vat_rate, 'total_price': total_price,
'image': image, 'discount_percent': discount_percent
}
# DATABASE HANDLING
def save_order(order_details, update=True):
uinfo = order_details.get('user_info')
key = next(i for i in ['email', 'code'] if uinfo)
value = uinfo.get(key, None)
user = None
try:
user = User.get(**{key: value})
except User.DoesNotExist:
pass
# if user does not exist, we create a new one
if not user:
char_pool = string.ascii_lowercase+string.ascii_uppercase+string.digits
if not uinfo.get('email') and not uinfo.get('code'):
while True:
random_uid = '__' + ''.join(random.choice(char_pool) for _ in range(16))
if not User.select().where(User.code == random_uid).count():
uinfo['code'] = random_uid
break
user = User(**uinfo)
user.save()
order = None
# shoptet_shop = Shop.get(name='shoptet')
# default_shop_id = shoptet_shop.id if shoptet_shop else None
try:
order = Order.get(order_shop_id=order_details.get('order_shop_id'))
except:
pass # no order found
if order and (not update or order.closed):
return order
_fields = [d for d in Order._meta.fields]
order_keys = {key: value for key, value in order_details.items() if key in _fields}
order_keys.update({k: order_details.get(k) for k in ['order_shop_id', 'order_num']})
order = Order(**order_keys)
order.user_id = user.id
order.save()
# delete orderlines so that we are sure they are always up-to-date
# todo find a way to avoid deleting them (compare line by line)
q = OrderLine.delete().where(OrderLine.order_id == order.id)
q.execute()
for order_line in order_details.get('order_lines', []):
line_dict = process_order_line(order_line)
line_dict.update({'order_id': order.id})
ol = OrderLine(**line_dict)
ol.save()
if order.close_date is not None and re.match('(Vybavená)|(Pripravená)|(Storno)', order.status):
order.closed = True
order.save()
return order
def make_log(**kwargs):
log = Log(**kwargs)
return log.save()
def create_shops():
shop1 = {'name': 'shoptet', 'web': 'www.bio-market.sk'}
shop2 = {'name': 'brick-n-mortar', 'city': 'Gotham'}
for sh in [shop1, shop2]:
s = Shop(**sh)
s.save()
def init_db():
with db:
db.create_tables([SysUser, User, Shop, Order, OrderLine, Voucher, Credit, Log])
if __name__ == '__main__':
init_db()
pass
create_shops()