-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.py
193 lines (154 loc) · 6.58 KB
/
handler.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
import re
import datetime
import const
from dbhelper import DBHelper
from answerer import Answerer
class Handler(object):
""" Класс для обработки сообщений пользователя"""
@staticmethod
def filter_request(message): # pragma: no cover
""" Определение запроса пользователя из текста сообщения """
if Handler.valid_text(const.reg_exp_dict["user data"], message.text):
answer = Handler.set_update_user_data(message.text,
message.from_user.id,
message.from_user.first_name,
message.from_user.last_name)
elif Handler.valid_text(const.reg_exp_dict["product_by_name"], message.text):
answer = Handler.add_product_by_name(message.text, message.from_user.id)
elif Handler.valid_text(const.reg_exp_dict["product_by_id"], message.text):
answer = Handler.add_product_by_id(message.text, message.from_user.id)
elif Handler.valid_text(const.reg_exp_dict["day"], message.text):
answer = Handler.stat_day(message)
elif Handler.valid_text(const.reg_exp_dict["period"], message.text):
answer = Handler.stat_period(message)
else:
answer = Answerer.unknow_command()
return answer
@staticmethod # pragma: no cover
def valid_text(pattern, text):
res = re.match(pattern, text)
if res:
return True
return False
@staticmethod
def set_update_user_data(text, id, first_name, last_name):
""" Метод для выделения данных пользователя из сообщения, их проверки и выполнения запроса к БД"""
data = text.strip().split(',')
try:
sex = data[0].lower()
age = int(data[1])
height = int(data[2])
weight = int(data[3])
except ValueError:
return Answerer.data_processing_error()
if age > const.MAX_AGE:
return Answerer.incorrect_data() + Answerer.max_age()
if height > const.MAX_HEIGHT:
return Answerer.incorrect_data() + Answerer.max_height()
if weight > const.MAX_WEIGHT:
return Answerer.incorrect_data() + Answerer.max_weight()
data = {
"id": id,
"first_name": first_name,
"second_name": last_name,
"sex": sex,
"age": age,
"height": height,
"weight": weight
}
db = DBHelper()
answer = db.set_update_user_data(data)
return answer
@staticmethod
def add_product_by_name(text, id):
""" Метод для выделения данных о продукте, их проверки и выполнения запроса к БД"""
data = text.strip().split(':')
try:
product = (data[0].strip()[0].upper() + data[0].strip()[1:])
mass = int(data[1])
except ValueError:
return Answerer.data_processing_error()
if mass > const.MAX_PRODUCT_MASS:
return Answerer.incorrect_data() + Answerer.max_product_mass()
data = {
"id": id,
"product_name": product,
"product_id": None,
"mass": mass
}
db = DBHelper()
answer = db.add_product(data)
return answer
@staticmethod
def add_product_by_id(text, id):
""" Метод для выделения данных о продукте, их проверки и выполнения запроса к БД"""
data = text.strip().split(':')
try:
product_id = int(data[0][1:])
mass = int(data[1])
except ValueError:
return Answerer.data_processing_error()
if mass > const.MAX_PRODUCT_MASS:
return Answerer.incorrect_data() + Answerer.max_product_mass()
# Запрос к базе данных
data = {
"id": id,
"product_name": None,
"product_id": product_id,
"mass": mass
}
db = DBHelper()
answer = db.add_product(data, by_id=True)
return answer
@staticmethod
def is_correct_day(day, month, year): # pragma: no cover
if day < 1 or day > 31 or month < 1 or month > 12:
return False
try:
if datetime.date(year, month, day) > datetime.date.today():
return False
except ValueError:
return False
return True
@staticmethod
def stat_day(message): # pragma: no cover
""" Метод для выделения даты из сообщения, ее проверки и выполнения запроса к БД """
data = message.text.split('.')
try:
day = int(data[0])
month = int(data[1])
year = int(data[2])
except ValueError:
return Answerer.data_processing_error()
if not Handler.is_correct_day(day, month, year):
return Answerer.incorrect_date()
data = {
"id": message.from_user.id,
"date": data[2] + "-" + data[1] + "-" + data[0]
}
db = DBHelper()
answer = db.get_stat_day(data)
return answer
@staticmethod
def stat_period(message): # pragma: no cover
""" Метод для выделения интервала дат из сообщения, их проверки и выполнения запроса к БД """
data = message.text.split('-')
date1, date2 = data[0].split('.'), data[1].split('.')
try:
day1, day2 = int(date1[0]), int(date2[0])
month1, month2 = int(date1[1]), int(date2[1])
year1, year2 = int(date1[2]), int(date2[2])
except ValueError:
return Answerer.data_processing_error()
if not Handler.is_correct_day(day1, month1, year1) or not Handler.is_correct_day(day2, month2, year2):
return Answerer.incorrect_date()
if not(datetime.date(year1, month1, day1) < datetime.date(year2, month2, day2)):
return Answerer.incorrect_period()
data = {
"id": message.from_user.id,
"date1": date1[2].strip() + "-" + date1[1] + "-" + date1[0],
"date2": date2[2] + "-" + date2[1] + "-" + date2[0].strip()
}
db = DBHelper()
answer = db.get_stat_period(data)
return answer