DmitrMakeev
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -787,53 +787,53 @@ def send_request():
|
|
787 |
|
788 |
|
789 |
DATABASE_NAME = 'data_gc.db'
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
797 |
conn = sqlite3.connect(db_name)
|
798 |
cursor = conn.cursor()
|
799 |
|
|
|
800 |
email = user_data.get('email')
|
801 |
if not email:
|
802 |
logging.error(f"User data missing email: {user_data}")
|
803 |
return
|
804 |
|
805 |
logging.debug(f"Processing user with email: {email}")
|
806 |
-
|
807 |
-
|
|
|
808 |
user = cursor.fetchone()
|
809 |
logging.debug(f"User found: {user}")
|
810 |
|
|
|
811 |
web_st_value = 1 # Инициализация значения web_st
|
812 |
-
b_fin_value = "0" # Инициализация значения b_fin в виде строки
|
813 |
if user:
|
814 |
-
|
815 |
-
|
816 |
-
|
817 |
-
web_st_value
|
818 |
-
if user_data.get('finished') == "True":
|
819 |
-
b_fin_value = str(current_b_fin + 1)
|
820 |
-
else:
|
821 |
-
b_fin_value = str(current_b_fin)
|
822 |
-
logging.debug(f"Calculated web_st_value: {web_st_value}, b_fin_value: {b_fin_value}")
|
823 |
|
824 |
-
|
|
|
825 |
conn.commit()
|
826 |
-
|
|
|
827 |
else:
|
|
|
828 |
logging.debug(f"User {email} not found, proceeding with insert")
|
829 |
|
|
|
|
|
|
|
|
|
|
|
830 |
transformed_data = {}
|
831 |
for json_key, db_column in mapping_template.items():
|
832 |
value = user_data.get(json_key, "")
|
833 |
|
834 |
if isinstance(value, list):
|
|
|
835 |
if all(isinstance(item, str) for item in value):
|
836 |
-
transformed_data[db_column] = "; ".join(value)
|
837 |
else:
|
838 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
839 |
transformed_data[db_column] = ""
|
@@ -841,6 +841,7 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
841 |
transformed_data[db_column] = str(value)
|
842 |
logging.debug(f"Transformed data: {transformed_data}")
|
843 |
|
|
|
844 |
required_fields = [
|
845 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
846 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
@@ -852,6 +853,7 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
852 |
transformed_data[field] = ""
|
853 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
854 |
|
|
|
855 |
if 'phone' in user_data:
|
856 |
phone = user_data['phone']
|
857 |
if phone.startswith('+'):
|
@@ -859,9 +861,10 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
859 |
transformed_data['phone'] = phone
|
860 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
861 |
|
862 |
-
|
863 |
-
transformed_data['
|
864 |
|
|
|
865 |
if user:
|
866 |
update_query = "UPDATE contacts SET "
|
867 |
update_values = []
|
@@ -880,13 +883,13 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
880 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
881 |
cursor.execute(insert_query, insert_values)
|
882 |
|
|
|
883 |
conn.commit()
|
884 |
conn.close()
|
885 |
logging.debug(f"User with email {email} processed successfully")
|
886 |
|
887 |
|
888 |
|
889 |
-
|
890 |
@app.route('/send_get_request', methods=['GET'])
|
891 |
def send_get_request():
|
892 |
token = request.args.get('token')
|
@@ -931,6 +934,7 @@ def send_get_request():
|
|
931 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
932 |
|
933 |
|
|
|
934 |
@app.route('/webhookbz', methods=['POST'])
|
935 |
def webhookbz():
|
936 |
api_sys_control = request.args.get('api_sys')
|
|
|
787 |
|
788 |
|
789 |
DATABASE_NAME = 'data_gc.db'
|
|
|
|
|
|
|
|
|
|
|
|
|
790 |
def update_or_insert_user(db_name, user_data, mapping_template):
|
791 |
conn = sqlite3.connect(db_name)
|
792 |
cursor = conn.cursor()
|
793 |
|
794 |
+
# Получение email пользователя из данных
|
795 |
email = user_data.get('email')
|
796 |
if not email:
|
797 |
logging.error(f"User data missing email: {user_data}")
|
798 |
return
|
799 |
|
800 |
logging.debug(f"Processing user with email: {email}")
|
801 |
+
|
802 |
+
# Проверка существования пользователя в базе данных по email
|
803 |
+
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
804 |
user = cursor.fetchone()
|
805 |
logging.debug(f"User found: {user}")
|
806 |
|
807 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
808 |
web_st_value = 1 # Инициализация значения web_st
|
|
|
809 |
if user:
|
810 |
+
# Проверка текущего значения web_st и его инкрементация
|
811 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
812 |
+
web_st_value = int(current_web_st) + 1
|
813 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
|
|
|
|
|
|
|
|
|
|
814 |
|
815 |
+
# Обновление значения web_st
|
816 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
817 |
conn.commit()
|
818 |
+
conn.close()
|
819 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
820 |
else:
|
821 |
+
conn.close()
|
822 |
logging.debug(f"User {email} not found, proceeding with insert")
|
823 |
|
824 |
+
# Открываем соединение снова для остальных операций
|
825 |
+
conn = sqlite3.connect(db_name)
|
826 |
+
cursor = conn.cursor()
|
827 |
+
|
828 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
829 |
transformed_data = {}
|
830 |
for json_key, db_column in mapping_template.items():
|
831 |
value = user_data.get(json_key, "")
|
832 |
|
833 |
if isinstance(value, list):
|
834 |
+
# Проверяем тип элементов списка
|
835 |
if all(isinstance(item, str) for item in value):
|
836 |
+
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
837 |
else:
|
838 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
839 |
transformed_data[db_column] = ""
|
|
|
841 |
transformed_data[db_column] = str(value)
|
842 |
logging.debug(f"Transformed data: {transformed_data}")
|
843 |
|
844 |
+
# Заполнение обязательных полей значениями по умолчанию
|
845 |
required_fields = [
|
846 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
847 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
|
|
853 |
transformed_data[field] = ""
|
854 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
855 |
|
856 |
+
# Обработка номера телефона, если он есть
|
857 |
if 'phone' in user_data:
|
858 |
phone = user_data['phone']
|
859 |
if phone.startswith('+'):
|
|
|
861 |
transformed_data['phone'] = phone
|
862 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
863 |
|
864 |
+
# Добавление значения web_st в данные для вставки
|
865 |
+
transformed_data['web_st'] = web_st_value
|
866 |
|
867 |
+
# Обновление данных пользователя в базе данных
|
868 |
if user:
|
869 |
update_query = "UPDATE contacts SET "
|
870 |
update_values = []
|
|
|
883 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
884 |
cursor.execute(insert_query, insert_values)
|
885 |
|
886 |
+
# Подтверждение изменений и закрытие соединения
|
887 |
conn.commit()
|
888 |
conn.close()
|
889 |
logging.debug(f"User with email {email} processed successfully")
|
890 |
|
891 |
|
892 |
|
|
|
893 |
@app.route('/send_get_request', methods=['GET'])
|
894 |
def send_get_request():
|
895 |
token = request.args.get('token')
|
|
|
934 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
935 |
|
936 |
|
937 |
+
|
938 |
@app.route('/webhookbz', methods=['POST'])
|
939 |
def webhookbz():
|
940 |
api_sys_control = request.args.get('api_sys')
|