DmitrMakeev
commited on
Commit
•
b102253
1
Parent(s):
721c487
Update app.py
Browse files
app.py
CHANGED
@@ -655,69 +655,60 @@ def data_gc_tab_out():
|
|
655 |
|
656 |
|
657 |
|
|
|
658 |
|
659 |
|
660 |
|
661 |
|
662 |
|
663 |
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
forms = "formResponse"
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
gog_url = "https://docs.google.com/forms/d/e/1FAIpQLSc-JbmXvgpgGq6KrkXsYSsfMACVMyIDnNqrHy6jImGeSRcpiQ/formResponse?usp=pp_url&entry.1556100878={name}&entry.1477412341={email}&entry.1634985541={phone}&entry.1736544219={vk_id}&entry.62153872={chat_id}&entry.1913752768={ws_st}&entry.1768186232={ws_stop}&entry.1198983592={web_st}&entry.994770784={fin_prog}&entry.910932310={b_city}&entry.1923801792={b_fin}&entry.2005444720={b_ban}&entry.741087361={b_ign}&entry.1316159837={b_baners}&entry.355123557={b_butt}&entry.395996312={b_mess}&entry.646571729={shop_st}&entry.578527800={curator}&entry.1936838964={pr1}&entry.1375537366={pr2}&entry.1249356084={pr3}&entry.752547226={pr4}&entry.704766458={pr5}&entry.1837661={gc_url}&entry.398837750={key_pr}&entry.225564240={n_con}&entry.1642320872={canal}&entry.1581826411={data_t}&entry.311131724={utm_source}&entry.1904279859={utm_medium}&entry.740234546={utm_campaign}&entry.880981295={utm_term}&entry.431306383={utm_content}"
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
DATABASE_NAME = 'data_gc.db'
|
677 |
-
def send_to_google_forms(user_data, gog_url):
|
678 |
-
# Формирование URL с параметрами
|
679 |
-
url = gog_url.format(**user_data)
|
680 |
-
|
681 |
-
# Отправка POST-запроса
|
682 |
-
response = requests.post(url)
|
683 |
-
|
684 |
-
if response.status_code == 200:
|
685 |
-
logging.debug(f"Data sent to Google Forms successfully for user: {user_data.get('email')}")
|
686 |
-
else:
|
687 |
-
logging.error(f"Failed to send data to Google Forms for user: {user_data.get('email')}. Response: {response.text}")
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
692 |
-
# Подключение к базе данных
|
693 |
conn = sqlite3.connect(db_name)
|
694 |
cursor = conn.cursor()
|
695 |
|
696 |
-
# Получение email пользователя
|
697 |
email = user_data.get('email')
|
698 |
if not email:
|
699 |
logging.error(f"User data missing email: {user_data}")
|
700 |
return
|
701 |
|
702 |
logging.debug(f"Processing user with email: {email}")
|
703 |
-
|
704 |
-
#
|
705 |
-
cursor.execute("SELECT web_st
|
706 |
user = cursor.fetchone()
|
707 |
logging.debug(f"User found: {user}")
|
708 |
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
713 |
|
714 |
-
#
|
|
|
|
|
|
|
|
|
715 |
transformed_data = {}
|
716 |
for json_key, db_column in mapping_template.items():
|
717 |
value = user_data.get(json_key, "")
|
|
|
718 |
if isinstance(value, list):
|
|
|
719 |
if all(isinstance(item, str) for item in value):
|
720 |
-
transformed_data[db_column] = "; ".join(value)
|
721 |
else:
|
722 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
723 |
transformed_data[db_column] = ""
|
@@ -725,19 +716,21 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
725 |
transformed_data[db_column] = str(value)
|
726 |
logging.debug(f"Transformed data: {transformed_data}")
|
727 |
|
728 |
-
#
|
|
|
729 |
required_fields = [
|
730 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
731 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
732 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "gc_url",
|
733 |
"key_pr", "n_con", "canal", "data_on", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc'
|
734 |
]
|
|
|
735 |
for field in required_fields:
|
736 |
if field not in transformed_data:
|
737 |
transformed_data[field] = ""
|
738 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
739 |
|
740 |
-
# Обработка номера
|
741 |
if 'phone' in user_data:
|
742 |
phone = user_data['phone']
|
743 |
if phone.startswith('+'):
|
@@ -745,35 +738,16 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
745 |
transformed_data['phone'] = phone
|
746 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
747 |
|
748 |
-
#
|
749 |
-
|
750 |
-
|
751 |
-
# Проверка и подготовка значений столбцов
|
752 |
-
if current_ws_st is not None and current_ws_st != "":
|
753 |
-
transformed_data['ws_st'] = current_ws_st
|
754 |
-
else:
|
755 |
-
transformed_data['ws_st'] = user_data.get('ws_st', "")
|
756 |
-
|
757 |
-
if current_web_st is not None and current_web_st != "":
|
758 |
-
transformed_data['web_st'] = int(current_web_st) + 1
|
759 |
-
else:
|
760 |
-
transformed_data['web_st'] = 1
|
761 |
|
762 |
-
|
763 |
-
if current_messages:
|
764 |
-
transformed_data['b_mess'] = current_messages + "; " + new_messages
|
765 |
-
else:
|
766 |
-
transformed_data['b_mess'] = new_messages
|
767 |
-
logging.debug(f"Transformed data after message processing: {transformed_data}")
|
768 |
-
|
769 |
-
# Запись данных в базу данных
|
770 |
if user:
|
771 |
update_query = "UPDATE contacts SET "
|
772 |
update_values = []
|
773 |
for column, value in transformed_data.items():
|
774 |
-
|
775 |
-
|
776 |
-
update_values.append(value)
|
777 |
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
778 |
update_values.append(email)
|
779 |
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
@@ -786,29 +760,18 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
|
|
786 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
787 |
cursor.execute(insert_query, insert_values)
|
788 |
|
|
|
789 |
conn.commit()
|
790 |
-
|
791 |
-
# Извлечение обновленных данных из базы данных
|
792 |
-
cursor.execute("SELECT * FROM contacts WHERE email = ?", (email,))
|
793 |
-
updated_user = cursor.fetchone()
|
794 |
-
updated_data = dict(zip([column[0] for column in cursor.description], updated_user))
|
795 |
-
|
796 |
conn.close()
|
797 |
logging.debug(f"User with email {email} processed successfully")
|
798 |
|
799 |
-
# Отправка данных в Google Forms
|
800 |
-
send_to_google_forms(updated_data, gog_url)
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
|
806 |
@app.route('/send_request', methods=['POST'])
|
807 |
def send_request():
|
808 |
token = request.form.get('token')
|
809 |
min_date = request.form.get('minDate')
|
810 |
type = request.form.get('type')
|
811 |
-
url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}
|
812 |
|
813 |
response = requests.get(url, headers={'X-Token': token})
|
814 |
|
@@ -833,12 +796,14 @@ def send_get_request():
|
|
833 |
response.raise_for_status() # Проверка на ошибки HTTP
|
834 |
data = response.json()
|
835 |
|
|
|
836 |
if data is None or 'report' not in data:
|
837 |
return jsonify({'error': 'No report data found'}), 500
|
838 |
|
839 |
report = data.get('report', {})
|
840 |
messages = data.get('messages', {})
|
841 |
|
|
|
842 |
if report is None:
|
843 |
return jsonify({'error': 'No report data found in the response'}), 500
|
844 |
|
@@ -862,7 +827,7 @@ def send_get_request():
|
|
862 |
user_data['messages'] = user_messages
|
863 |
email = user_data.get('email')
|
864 |
if email and email not in processed_emails:
|
865 |
-
update_or_insert_user(DATABASE_NAME, user_data, mapping_template
|
866 |
processed_emails.add(email)
|
867 |
|
868 |
return jsonify({'status': 'User data saved successfully'})
|
@@ -870,10 +835,8 @@ def send_get_request():
|
|
870 |
except requests.exceptions.RequestException as e:
|
871 |
return jsonify({'error': f'API request failed: {str(e)}'}), 500
|
872 |
|
873 |
-
|
874 |
-
|
875 |
api_bz = "SkrIONpr3ByeSIuEaBhr1bB8u4aBhSJfH8uEpB2rk7rI_ETrn"
|
876 |
-
|
877 |
|
878 |
@app.route('/webhookbz', methods=['POST'])
|
879 |
def webhookbz():
|
@@ -886,10 +849,9 @@ def webhookbz():
|
|
886 |
|
887 |
if not webinar_id:
|
888 |
return jsonify({'error': 'webinarId is required'}), 400
|
889 |
-
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
|
890 |
-
|
891 |
-
response = requests.get(url, headers={'X-Token': api_bz})
|
892 |
|
|
|
|
|
893 |
|
894 |
if response.status_code == 200:
|
895 |
data = response.json()
|
@@ -917,14 +879,13 @@ def webhookbz():
|
|
917 |
user_data['messages'] = user_messages
|
918 |
email = user_data.get('email')
|
919 |
if email and email not in processed_emails:
|
920 |
-
update_or_insert_user(DATABASE_NAME, user_data, mapping_template
|
921 |
processed_emails.add(email)
|
922 |
|
923 |
return jsonify({'status': 'User data saved successfully'})
|
924 |
else:
|
925 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
926 |
|
927 |
-
|
928 |
|
929 |
|
930 |
|
@@ -935,6 +896,23 @@ def webhookbz():
|
|
935 |
|
936 |
|
937 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
938 |
|
939 |
|
940 |
|
|
|
655 |
|
656 |
|
657 |
|
658 |
+
DATABASE_NAME = 'data_gc.db'
|
659 |
|
660 |
|
661 |
|
662 |
|
663 |
|
664 |
|
665 |
+
def update_or_insert_user(db_name, user_data, mapping_template):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
666 |
conn = sqlite3.connect(db_name)
|
667 |
cursor = conn.cursor()
|
668 |
|
669 |
+
# Получение email пользователя из данных
|
670 |
email = user_data.get('email')
|
671 |
if not email:
|
672 |
logging.error(f"User data missing email: {user_data}")
|
673 |
return
|
674 |
|
675 |
logging.debug(f"Processing user with email: {email}")
|
676 |
+
|
677 |
+
# Проверка существования пользователя в базе данных по email
|
678 |
+
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
679 |
user = cursor.fetchone()
|
680 |
logging.debug(f"User found: {user}")
|
681 |
|
682 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
683 |
+
web_st_value = 1 # Инициализация значения web_st
|
684 |
+
if user:
|
685 |
+
# Проверка текущего значения web_st и его инкрементация
|
686 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
687 |
+
web_st_value = int(current_web_st) + 1
|
688 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
689 |
+
|
690 |
+
# Обновление значения web_st
|
691 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
692 |
+
conn.commit()
|
693 |
+
conn.close()
|
694 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
695 |
+
else:
|
696 |
+
conn.close()
|
697 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
698 |
|
699 |
+
# Открываем соединение снова для остальных операций
|
700 |
+
conn = sqlite3.connect(db_name)
|
701 |
+
cursor = conn.cursor()
|
702 |
+
|
703 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
704 |
transformed_data = {}
|
705 |
for json_key, db_column in mapping_template.items():
|
706 |
value = user_data.get(json_key, "")
|
707 |
+
|
708 |
if isinstance(value, list):
|
709 |
+
# Проверяем тип элементов списка
|
710 |
if all(isinstance(item, str) for item in value):
|
711 |
+
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
712 |
else:
|
713 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
714 |
transformed_data[db_column] = ""
|
|
|
716 |
transformed_data[db_column] = str(value)
|
717 |
logging.debug(f"Transformed data: {transformed_data}")
|
718 |
|
719 |
+
# Заполнение обязательных полей значениями по умолчанию
|
720 |
+
|
721 |
required_fields = [
|
722 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
723 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
724 |
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "gc_url",
|
725 |
"key_pr", "n_con", "canal", "data_on", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gcpc'
|
726 |
]
|
727 |
+
|
728 |
for field in required_fields:
|
729 |
if field not in transformed_data:
|
730 |
transformed_data[field] = ""
|
731 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
732 |
|
733 |
+
# Обработка номера телефона, если он есть
|
734 |
if 'phone' in user_data:
|
735 |
phone = user_data['phone']
|
736 |
if phone.startswith('+'):
|
|
|
738 |
transformed_data['phone'] = phone
|
739 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
740 |
|
741 |
+
# Добавление значения web_st в данные для вставки
|
742 |
+
transformed_data['web_st'] = web_st_value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
743 |
|
744 |
+
# Обновление данных пользователя в базе данных
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
745 |
if user:
|
746 |
update_query = "UPDATE contacts SET "
|
747 |
update_values = []
|
748 |
for column, value in transformed_data.items():
|
749 |
+
update_query += f"{column} = ?, "
|
750 |
+
update_values.append(value)
|
|
|
751 |
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
752 |
update_values.append(email)
|
753 |
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
|
|
760 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
761 |
cursor.execute(insert_query, insert_values)
|
762 |
|
763 |
+
# Подтверждение изменений и закрытие соединения
|
764 |
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
765 |
conn.close()
|
766 |
logging.debug(f"User with email {email} processed successfully")
|
767 |
|
|
|
|
|
|
|
|
|
|
|
|
|
768 |
|
769 |
@app.route('/send_request', methods=['POST'])
|
770 |
def send_request():
|
771 |
token = request.form.get('token')
|
772 |
min_date = request.form.get('minDate')
|
773 |
type = request.form.get('type')
|
774 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}'
|
775 |
|
776 |
response = requests.get(url, headers={'X-Token': token})
|
777 |
|
|
|
796 |
response.raise_for_status() # Проверка на ошибки HTTP
|
797 |
data = response.json()
|
798 |
|
799 |
+
# Убедитесь, что report существует в данных
|
800 |
if data is None or 'report' not in data:
|
801 |
return jsonify({'error': 'No report data found'}), 500
|
802 |
|
803 |
report = data.get('report', {})
|
804 |
messages = data.get('messages', {})
|
805 |
|
806 |
+
# Проверка на None перед использованием
|
807 |
if report is None:
|
808 |
return jsonify({'error': 'No report data found in the response'}), 500
|
809 |
|
|
|
827 |
user_data['messages'] = user_messages
|
828 |
email = user_data.get('email')
|
829 |
if email and email not in processed_emails:
|
830 |
+
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
831 |
processed_emails.add(email)
|
832 |
|
833 |
return jsonify({'status': 'User data saved successfully'})
|
|
|
835 |
except requests.exceptions.RequestException as e:
|
836 |
return jsonify({'error': f'API request failed: {str(e)}'}), 500
|
837 |
|
|
|
|
|
838 |
api_bz = "SkrIONpr3ByeSIuEaBhr1bB8u4aBhSJfH8uEpB2rk7rI_ETrn"
|
839 |
+
|
840 |
|
841 |
@app.route('/webhookbz', methods=['POST'])
|
842 |
def webhookbz():
|
|
|
849 |
|
850 |
if not webinar_id:
|
851 |
return jsonify({'error': 'webinarId is required'}), 400
|
|
|
|
|
|
|
852 |
|
853 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
|
854 |
+
response = requests.get(url, headers={'X-Token': api_key_sys})
|
855 |
|
856 |
if response.status_code == 200:
|
857 |
data = response.json()
|
|
|
879 |
user_data['messages'] = user_messages
|
880 |
email = user_data.get('email')
|
881 |
if email and email not in processed_emails:
|
882 |
+
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
883 |
processed_emails.add(email)
|
884 |
|
885 |
return jsonify({'status': 'User data saved successfully'})
|
886 |
else:
|
887 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
888 |
|
|
|
889 |
|
890 |
|
891 |
|
|
|
896 |
|
897 |
|
898 |
|
899 |
+
|
900 |
+
|
901 |
+
|
902 |
+
|
903 |
+
|
904 |
+
|
905 |
+
|
906 |
+
|
907 |
+
|
908 |
+
|
909 |
+
|
910 |
+
|
911 |
+
|
912 |
+
|
913 |
+
|
914 |
+
|
915 |
+
|
916 |
|
917 |
|
918 |
|