DmitrMakeev
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -723,44 +723,57 @@ gog_url = "https://docs.google.com/forms/d/e/1FAIpQLSc-JbmXvgpgGq6KrkXsYSsfMACVM
|
|
723 |
|
724 |
DATABASE_NAME = 'data_gc.db'
|
725 |
|
726 |
-
def
|
727 |
-
# Формирование URL с параметрами
|
728 |
-
url = gog_url.format(**user_data)
|
729 |
-
|
730 |
-
# Отправка POST-запроса
|
731 |
-
response = requests.post(url)
|
732 |
-
|
733 |
-
if response.status_code == 200:
|
734 |
-
logging.debug(f"Data sent to Google Forms successfully for user: {user_data.get('email')}")
|
735 |
-
else:
|
736 |
-
logging.error(f"Failed to send data to Google Forms for user: {user_data.get('email')}. Response: {response.text}")
|
737 |
-
|
738 |
-
|
739 |
-
def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
740 |
conn = sqlite3.connect(db_name)
|
741 |
cursor = conn.cursor()
|
742 |
|
|
|
743 |
email = user_data.get('email')
|
744 |
if not email:
|
745 |
logging.error(f"User data missing email: {user_data}")
|
746 |
return
|
747 |
|
748 |
logging.debug(f"Processing user with email: {email}")
|
749 |
-
|
750 |
-
|
|
|
751 |
user = cursor.fetchone()
|
752 |
logging.debug(f"User found: {user}")
|
753 |
|
754 |
-
|
755 |
-
|
756 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
757 |
|
|
|
758 |
transformed_data = {}
|
759 |
for json_key, db_column in mapping_template.items():
|
760 |
value = user_data.get(json_key, "")
|
|
|
761 |
if isinstance(value, list):
|
|
|
762 |
if all(isinstance(item, str) for item in value):
|
763 |
-
transformed_data[db_column] = "; ".join(value)
|
764 |
else:
|
765 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
766 |
transformed_data[db_column] = ""
|
@@ -768,10 +781,11 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
768 |
transformed_data[db_column] = str(value)
|
769 |
logging.debug(f"Transformed data: {transformed_data}")
|
770 |
|
|
|
771 |
required_fields = [
|
772 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
773 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
774 |
-
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "
|
775 |
"key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
|
776 |
]
|
777 |
for field in required_fields:
|
@@ -779,6 +793,7 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
779 |
transformed_data[field] = ""
|
780 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
781 |
|
|
|
782 |
if 'phone' in user_data:
|
783 |
phone = user_data['phone']
|
784 |
if phone.startswith('+'):
|
@@ -786,25 +801,16 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
786 |
transformed_data['phone'] = phone
|
787 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
788 |
|
789 |
-
#
|
790 |
-
|
|
|
|
|
|
|
791 |
transformed_data['ws_st'] = current_ws_st
|
792 |
else:
|
793 |
transformed_data['ws_st'] = user_data.get('ws_st', "")
|
794 |
|
795 |
-
#
|
796 |
-
if current_web_st is not None:
|
797 |
-
transformed_data['web_st'] = int(current_web_st) + 1
|
798 |
-
else:
|
799 |
-
transformed_data['web_st'] = 1
|
800 |
-
|
801 |
-
new_messages = transformed_data.get('b_mess', "")
|
802 |
-
if current_messages:
|
803 |
-
transformed_data['b_mess'] = current_messages + "; " + new_messages
|
804 |
-
else:
|
805 |
-
transformed_data['b_mess'] = new_messages
|
806 |
-
logging.debug(f"Transformed data after message processing: {transformed_data}")
|
807 |
-
|
808 |
if user:
|
809 |
update_query = "UPDATE contacts SET "
|
810 |
update_values = []
|
@@ -823,13 +829,11 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
823 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
824 |
cursor.execute(insert_query, insert_values)
|
825 |
|
|
|
826 |
conn.commit()
|
827 |
conn.close()
|
828 |
logging.debug(f"User with email {email} processed successfully")
|
829 |
|
830 |
-
# Отправка данных в Google Forms
|
831 |
-
send_to_google_forms(transformed_data, gog_url)
|
832 |
-
|
833 |
|
834 |
@app.route('/send_request', methods=['POST'])
|
835 |
def send_request():
|
|
|
723 |
|
724 |
DATABASE_NAME = 'data_gc.db'
|
725 |
|
726 |
+
def update_or_insert_user(db_name, user_data, mapping_template):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
727 |
conn = sqlite3.connect(db_name)
|
728 |
cursor = conn.cursor()
|
729 |
|
730 |
+
# Получение email пользователя из данных
|
731 |
email = user_data.get('email')
|
732 |
if not email:
|
733 |
logging.error(f"User data missing email: {user_data}")
|
734 |
return
|
735 |
|
736 |
logging.debug(f"Processing user with email: {email}")
|
737 |
+
|
738 |
+
# Проверка существования пользователя в базе данных по email
|
739 |
+
cursor.execute("SELECT web_st, ws_st FROM contacts WHERE email = ?", (email,))
|
740 |
user = cursor.fetchone()
|
741 |
logging.debug(f"User found: {user}")
|
742 |
|
743 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
744 |
+
web_st_value = 1 # Инициализация значения web_st
|
745 |
+
current_ws_st = None
|
746 |
+
if user:
|
747 |
+
# Проверка текущего значения web_st и его инкрементация
|
748 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
749 |
+
web_st_value = int(current_web_st) + 1
|
750 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
751 |
+
|
752 |
+
# Получение текущего значения ws_st
|
753 |
+
current_ws_st = user[1] if user[1] is not None and user[1] != "" else None
|
754 |
+
|
755 |
+
# Обновление значения web_st
|
756 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
757 |
+
conn.commit()
|
758 |
+
conn.close()
|
759 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
760 |
+
else:
|
761 |
+
conn.close()
|
762 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
763 |
+
|
764 |
+
# Открываем соединение снова для остальных операций
|
765 |
+
conn = sqlite3.connect(db_name)
|
766 |
+
cursor = conn.cursor()
|
767 |
|
768 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
769 |
transformed_data = {}
|
770 |
for json_key, db_column in mapping_template.items():
|
771 |
value = user_data.get(json_key, "")
|
772 |
+
|
773 |
if isinstance(value, list):
|
774 |
+
# Проверяем тип элементов списка
|
775 |
if all(isinstance(item, str) for item in value):
|
776 |
+
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
777 |
else:
|
778 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
779 |
transformed_data[db_column] = ""
|
|
|
781 |
transformed_data[db_column] = str(value)
|
782 |
logging.debug(f"Transformed data: {transformed_data}")
|
783 |
|
784 |
+
# Заполнение обязательных полей значениями по умолчанию
|
785 |
required_fields = [
|
786 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
787 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
788 |
+
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
789 |
"key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
|
790 |
]
|
791 |
for field in required_fields:
|
|
|
793 |
transformed_data[field] = ""
|
794 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
795 |
|
796 |
+
# Обработка номера телефона, если он есть
|
797 |
if 'phone' in user_data:
|
798 |
phone = user_data['phone']
|
799 |
if phone.startswith('+'):
|
|
|
801 |
transformed_data['phone'] = phone
|
802 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
803 |
|
804 |
+
# Добавление значения web_st в данные для вставки
|
805 |
+
transformed_data['web_st'] = web_st_value
|
806 |
+
|
807 |
+
# Проверка наличия ws_st в базе данных и не перезаписываем его, если оно уже существует
|
808 |
+
if current_ws_st is not None:
|
809 |
transformed_data['ws_st'] = current_ws_st
|
810 |
else:
|
811 |
transformed_data['ws_st'] = user_data.get('ws_st', "")
|
812 |
|
813 |
+
# Обновление данных пользователя в базе данных
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
814 |
if user:
|
815 |
update_query = "UPDATE contacts SET "
|
816 |
update_values = []
|
|
|
829 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
830 |
cursor.execute(insert_query, insert_values)
|
831 |
|
832 |
+
# Подтверждение изменений и закрытие соединения
|
833 |
conn.commit()
|
834 |
conn.close()
|
835 |
logging.debug(f"User with email {email} processed successfully")
|
836 |
|
|
|
|
|
|
|
837 |
|
838 |
@app.route('/send_request', methods=['POST'])
|
839 |
def send_request():
|