DmitrMakeev
commited on
Commit
•
f45c287
1
Parent(s):
81bb96f
Update app.py
Browse files
app.py
CHANGED
@@ -624,13 +624,106 @@ DATABASE_NAME = 'data_gc.db'
|
|
624 |
|
625 |
|
626 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
627 |
|
628 |
|
629 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
630 |
conn = sqlite3.connect(db_name)
|
631 |
cursor = conn.cursor()
|
632 |
|
633 |
-
# Получение email пользователя из данных
|
634 |
email = user_data.get('email')
|
635 |
if not email:
|
636 |
logging.error(f"User data missing email: {user_data}")
|
@@ -638,25 +731,20 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
638 |
|
639 |
logging.debug(f"Processing user with email: {email}")
|
640 |
|
641 |
-
# Проверка существования пользователя в базе данных по email
|
642 |
cursor.execute("SELECT web_st, b_mess FROM contacts WHERE email = ?", (email,))
|
643 |
user = cursor.fetchone()
|
644 |
logging.debug(f"User found: {user}")
|
645 |
|
646 |
-
|
647 |
-
|
648 |
-
current_messages = "" # Инициализация текущих сообщений
|
649 |
if user:
|
650 |
-
# Проверка текущего значения web_st и его инкрементация
|
651 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
652 |
web_st_value = int(current_web_st) + 1
|
653 |
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
654 |
|
655 |
-
# Получение текущих сообщений
|
656 |
current_messages = user[1] if user[1] is not None else ""
|
657 |
logging.debug(f"Current messages: {current_messages}")
|
658 |
|
659 |
-
# Обновление значения web_st
|
660 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
661 |
conn.commit()
|
662 |
conn.close()
|
@@ -665,19 +753,16 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
665 |
conn.close()
|
666 |
logging.debug(f"User {email} not found, proceeding with insert")
|
667 |
|
668 |
-
# Открываем соединение снова для остальных операций
|
669 |
conn = sqlite3.connect(db_name)
|
670 |
cursor = conn.cursor()
|
671 |
|
672 |
-
# Преобразование данных пользователя на основе шаблона сопоставления
|
673 |
transformed_data = {}
|
674 |
-
for json_key, db_column in
|
675 |
value = user_data.get(json_key, "")
|
676 |
|
677 |
if isinstance(value, list):
|
678 |
-
# Проверяем тип элементов списка
|
679 |
if all(isinstance(item, str) for item in value):
|
680 |
-
transformed_data[db_column] = "; ".join(value)
|
681 |
else:
|
682 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
683 |
transformed_data[db_column] = ""
|
@@ -685,61 +770,55 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
685 |
transformed_data[db_column] = str(value)
|
686 |
logging.debug(f"Transformed data: {transformed_data}")
|
687 |
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
transformed_data
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
transformed_data
|
715 |
-
|
716 |
-
transformed_data
|
717 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
718 |
|
719 |
-
# Обновление данных пользователя в базе данных
|
720 |
-
if user:
|
721 |
-
update_query = "UPDATE contacts SET "
|
722 |
-
update_values = []
|
723 |
-
for column, value in transformed_data.items():
|
724 |
-
update_query += f"{column} = ?, "
|
725 |
-
update_values.append(value)
|
726 |
-
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
727 |
-
update_values.append(email)
|
728 |
-
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
729 |
-
cursor.execute(update_query, update_values)
|
730 |
-
else:
|
731 |
-
columns = ', '.join(transformed_data.keys())
|
732 |
-
placeholders = ', '.join('?' for _ in transformed_data)
|
733 |
-
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
734 |
-
insert_values = list(transformed_data.values())
|
735 |
-
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
736 |
-
cursor.execute(insert_query, insert_values)
|
737 |
-
|
738 |
-
# Подтверждение изменений и закрытие соединения
|
739 |
conn.commit()
|
740 |
conn.close()
|
741 |
logging.debug(f"User with email {email} processed successfully")
|
742 |
|
|
|
|
|
743 |
|
744 |
@app.route('/send_request', methods=['POST'])
|
745 |
def send_request():
|
@@ -757,9 +836,6 @@ def send_request():
|
|
757 |
else:
|
758 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
759 |
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
@app.route('/send_get_request', methods=['GET'])
|
764 |
def send_get_request():
|
765 |
token = request.args.get('token')
|
@@ -768,17 +844,15 @@ def send_get_request():
|
|
768 |
|
769 |
try:
|
770 |
response = requests.get(url, headers={'X-Token': token})
|
771 |
-
response.raise_for_status()
|
772 |
data = response.json()
|
773 |
|
774 |
-
# Убедитесь, что report существует в данных
|
775 |
if data is None or 'report' not in data:
|
776 |
return jsonify({'error': 'No report data found'}), 500
|
777 |
|
778 |
report = data.get('report', {})
|
779 |
messages = data.get('messages', {})
|
780 |
|
781 |
-
# Проверка на None перед использованием
|
782 |
if report is None:
|
783 |
return jsonify({'error': 'No report data found in the response'}), 500
|
784 |
|
@@ -810,9 +884,6 @@ def send_get_request():
|
|
810 |
except requests.exceptions.RequestException as e:
|
811 |
return jsonify({'error': f'API request failed: {str(e)}'}), 500
|
812 |
|
813 |
-
|
814 |
-
|
815 |
-
|
816 |
@app.route('/webhookbz', methods=['POST'])
|
817 |
def webhookbz():
|
818 |
api_sys_control = request.args.get('api_sys')
|
@@ -875,6 +946,11 @@ def webhookbz():
|
|
875 |
|
876 |
|
877 |
|
|
|
|
|
|
|
|
|
|
|
878 |
|
879 |
|
880 |
|
|
|
624 |
|
625 |
|
626 |
|
627 |
+
# URL Google Формы как переменная
|
628 |
+
GOOGLE_FORM_URL = (
|
629 |
+
"https://docs.google.com/formResponse/d/e/1FAIpQLSc-JbmXvgpgGq6KrkXsYSsfMACVMyIDnNqrHy6jImGeSRcpiQ/formResponse"
|
630 |
+
"?usp=pp_url&entry.1556100878={name}&entry.1477412341={email}&entry.1634985541={phone}&entry.1736544219={vk_id}"
|
631 |
+
"&entry.62153872={chat_id}&entry.1913752768={ws_st}&entry.1768186232={ws_stop}&entry.1198983592={web_st}"
|
632 |
+
"&entry.994770784={fin_prog}&entry.910932310={b_city}&entry.1923801792={b_fin}&entry.2005444720={b_ban}"
|
633 |
+
"&entry.741087361={b_ign}&entry.1316159837={b_baners}&entry.355123557={b_butt}&entry.395996312={b_mess}"
|
634 |
+
"&entry.646571729={shop_st}&entry.578527800={curator}&entry.1936838964={pr1}&entry.1375537366={pr2}"
|
635 |
+
"&entry.1249356084={pr3}&entry.752547226={pr4}&entry.704766458={pr5}&entry.1837661={gc_url}&entry.398837750={key_pr}"
|
636 |
+
"&entry.225564240={n_con}&entry.1642320872={canal}&entry.1581826411={data_t}&entry.311131724={utm_source}"
|
637 |
+
"&entry.1904279859={utm_medium}&entry.740234546={utm_campaign}&entry.880981295={utm_term}&entry.431306383={utm_content}"
|
638 |
+
)
|
639 |
+
|
640 |
+
# Определяем шаблон для маппинга
|
641 |
+
mapping_template_log = {
|
642 |
+
'name': 'name',
|
643 |
+
'email': 'email',
|
644 |
+
'phone': 'phone',
|
645 |
+
'vk_id': 'vk_id',
|
646 |
+
'chat_id': 'chat_id',
|
647 |
+
'ws_st': 'ws_st',
|
648 |
+
'ws_stop': 'ws_stop',
|
649 |
+
'web_st': 'web_st',
|
650 |
+
'fin_prog': 'fin_prog',
|
651 |
+
'b_city': 'b_city',
|
652 |
+
'b_fin': 'b_fin',
|
653 |
+
'b_ban': 'b_ban',
|
654 |
+
'b_ign': 'b_ign',
|
655 |
+
'b_baners': 'b_baners',
|
656 |
+
'b_butt': 'b_butt',
|
657 |
+
'b_mess': 'b_mess',
|
658 |
+
'shop_st': 'shop_st',
|
659 |
+
'curator': 'curator',
|
660 |
+
'pr1': 'pr1',
|
661 |
+
'pr2': 'pr2',
|
662 |
+
'pr3': 'pr3',
|
663 |
+
'pr4': 'pr4',
|
664 |
+
'pr5': 'pr5',
|
665 |
+
'gc_url': 'gc_url',
|
666 |
+
'key_pr': 'key_pr',
|
667 |
+
'n_con': 'n_con',
|
668 |
+
'canal': 'canal',
|
669 |
+
'data_t': 'data_t',
|
670 |
+
'utm_source': 'utm_source',
|
671 |
+
'utm_medium': 'utm_medium',
|
672 |
+
'utm_campaign': 'utm_campaign',
|
673 |
+
'utm_term': 'utm_term',
|
674 |
+
'utm_content': 'utm_content'
|
675 |
+
}
|
676 |
|
677 |
|
678 |
+
|
679 |
+
def send_data_to_google_form(data):
|
680 |
+
# Используем переменную GOOGLE_FORM_URL для формирования ссылки
|
681 |
+
google_form_url = GOOGLE_FORM_URL.format(
|
682 |
+
name=data.get('name', ''),
|
683 |
+
email=data.get('email', ''),
|
684 |
+
phone=data.get('phone', ''),
|
685 |
+
vk_id=data.get('vk_id', ''),
|
686 |
+
chat_id=data.get('chat_id', ''),
|
687 |
+
ws_st=data.get('ws_st', ''),
|
688 |
+
ws_stop=data.get('ws_stop', ''),
|
689 |
+
web_st=data.get('web_st', ''),
|
690 |
+
fin_prog=data.get('fin_prog', ''),
|
691 |
+
b_city=data.get('b_city', ''),
|
692 |
+
b_fin=data.get('b_fin', ''),
|
693 |
+
b_ban=data.get('b_ban', ''),
|
694 |
+
b_ign=data.get('b_ign', ''),
|
695 |
+
b_baners=data.get('b_baners', ''),
|
696 |
+
b_butt=data.get('b_butt', ''),
|
697 |
+
b_mess=data.get('b_mess', ''),
|
698 |
+
shop_st=data.get('shop_st', ''),
|
699 |
+
curator=data.get('curator', ''),
|
700 |
+
pr1=data.get('pr1', ''),
|
701 |
+
pr2=data.get('pr2', ''),
|
702 |
+
pr3=data.get('pr3', ''),
|
703 |
+
pr4=data.get('pr4', ''),
|
704 |
+
pr5=data.get('pr5', ''),
|
705 |
+
gc_url=data.get('gc_url', ''),
|
706 |
+
key_pr=data.get('key_pr', ''),
|
707 |
+
n_con=data.get('n_con', ''),
|
708 |
+
canal=data.get('canal', ''),
|
709 |
+
data_t=data.get('data_t', ''),
|
710 |
+
utm_source=data.get('utm_source', ''),
|
711 |
+
utm_medium=data.get('utm_medium', ''),
|
712 |
+
utm_campaign=data.get('utm_campaign', ''),
|
713 |
+
utm_term=data.get('utm_term', ''),
|
714 |
+
utm_content=data.get('utm_content', '')
|
715 |
+
)
|
716 |
+
|
717 |
+
response = requests.post(google_form_url)
|
718 |
+
if response.status_code != 200:
|
719 |
+
logging.error(f"Failed to send data to Google Form: {response.status_code}, {response.text}")
|
720 |
+
else:
|
721 |
+
logging.info(f"Data sent to Google Form successfully: {response.status_code}")
|
722 |
+
|
723 |
+
def update_or_insert_user(db_name, user_data, mapping_template_log):
|
724 |
conn = sqlite3.connect(db_name)
|
725 |
cursor = conn.cursor()
|
726 |
|
|
|
727 |
email = user_data.get('email')
|
728 |
if not email:
|
729 |
logging.error(f"User data missing email: {user_data}")
|
|
|
731 |
|
732 |
logging.debug(f"Processing user with email: {email}")
|
733 |
|
|
|
734 |
cursor.execute("SELECT web_st, b_mess FROM contacts WHERE email = ?", (email,))
|
735 |
user = cursor.fetchone()
|
736 |
logging.debug(f"User found: {user}")
|
737 |
|
738 |
+
web_st_value = 1
|
739 |
+
current_messages = ""
|
|
|
740 |
if user:
|
|
|
741 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
742 |
web_st_value = int(current_web_st) + 1
|
743 |
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
744 |
|
|
|
745 |
current_messages = user[1] if user[1] is not None else ""
|
746 |
logging.debug(f"Current messages: {current_messages}")
|
747 |
|
|
|
748 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
749 |
conn.commit()
|
750 |
conn.close()
|
|
|
753 |
conn.close()
|
754 |
logging.debug(f"User {email} not found, proceeding with insert")
|
755 |
|
|
|
756 |
conn = sqlite3.connect(db_name)
|
757 |
cursor = conn.cursor()
|
758 |
|
|
|
759 |
transformed_data = {}
|
760 |
+
for json_key, db_column in mapping_template_log.items():
|
761 |
value = user_data.get(json_key, "")
|
762 |
|
763 |
if isinstance(value, list):
|
|
|
764 |
if all(isinstance(item, str) for item in value):
|
765 |
+
transformed_data[db_column] = "; ".join(value)
|
766 |
else:
|
767 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
768 |
transformed_data[db_column] = ""
|
|
|
770 |
transformed_data[db_column] = str(value)
|
771 |
logging.debug(f"Transformed data: {transformed_data}")
|
772 |
|
773 |
+
insert_query = f"""
|
774 |
+
INSERT INTO contacts (name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, b_city, b_fin, b_ban, b_ign, b_baners, b_butt, b_mess, shop_st, curator, pr1, pr2, pr3, pr4, pr5, gc_url, key_pr, n_con, canal, data_t, utm_source, utm_medium, utm_campaign, utm_term, utm_content)
|
775 |
+
VALUES (:name, :phone, :email, :vk_id, :chat_id, :ws_st, :ws_stop, :web_st, :fin_prog, :b_city, :b_fin, :b_ban, :b_ign, :b_baners, :b_butt, :b_mess, :shop_st, :curator, :pr1, :pr2, :pr3, :pr4, :pr5, :gc_url, :key_pr, :n_con, :canal, :data_t, :utm_source, :utm_medium, :utm_campaign, :utm_term, :utm_content)
|
776 |
+
"""
|
777 |
+
|
778 |
+
insert_values = {
|
779 |
+
'name': transformed_data.get('name', ''),
|
780 |
+
'phone': transformed_data.get('phone', ''),
|
781 |
+
'email': transformed_data.get('email', ''),
|
782 |
+
'vk_id': transformed_data.get('vk_id', ''),
|
783 |
+
'chat_id': transformed_data.get('chat_id', ''),
|
784 |
+
'ws_st': transformed_data.get('ws_st', ''),
|
785 |
+
'ws_stop': transformed_data.get('ws_stop', ''),
|
786 |
+
'web_st': transformed_data.get('web_st', ''),
|
787 |
+
'fin_prog': transformed_data.get('fin_prog', ''),
|
788 |
+
'b_city': transformed_data.get('b_city', ''),
|
789 |
+
'b_fin': transformed_data.get('b_fin', ''),
|
790 |
+
'b_ban': transformed_data.get('b_ban', ''),
|
791 |
+
'b_ign': transformed_data.get('b_ign', ''),
|
792 |
+
'b_baners': transformed_data.get('b_baners', ''),
|
793 |
+
'b_butt': transformed_data.get('b_butt', ''),
|
794 |
+
'b_mess': transformed_data.get('b_mess', ''),
|
795 |
+
'shop_st': transformed_data.get('shop_st', ''),
|
796 |
+
'curator': transformed_data.get('curator', ''),
|
797 |
+
'pr1': transformed_data.get('pr1', ''),
|
798 |
+
'pr2': transformed_data.get('pr2', ''),
|
799 |
+
'pr3': transformed_data.get('pr3', ''),
|
800 |
+
'pr4': transformed_data.get('pr4', ''),
|
801 |
+
'pr5': transformed_data.get('pr5', ''),
|
802 |
+
'gc_url': transformed_data.get('gc_url', ''),
|
803 |
+
'key_pr': transformed_data.get('key_pr', ''),
|
804 |
+
'n_con': transformed_data.get('n_con', ''),
|
805 |
+
'canal': transformed_data.get('canal', ''),
|
806 |
+
'data_t': transformed_data.get('data_t', ''),
|
807 |
+
'utm_source': transformed_data.get('utm_source', ''),
|
808 |
+
'utm_medium': transformed_data.get('utm_medium', ''),
|
809 |
+
'utm_campaign': transformed_data.get('utm_campaign', ''),
|
810 |
+
'utm_term': transformed_data.get('utm_term', ''),
|
811 |
+
'utm_content': transformed_data.get('utm_content', '')
|
812 |
+
}
|
813 |
+
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
814 |
+
cursor.execute(insert_query, insert_values)
|
815 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
816 |
conn.commit()
|
817 |
conn.close()
|
818 |
logging.debug(f"User with email {email} processed successfully")
|
819 |
|
820 |
+
# Отправляем данные в Google Форму после обновления/вставки
|
821 |
+
send_data_to_google_form(transformed_data)
|
822 |
|
823 |
@app.route('/send_request', methods=['POST'])
|
824 |
def send_request():
|
|
|
836 |
else:
|
837 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
838 |
|
|
|
|
|
|
|
839 |
@app.route('/send_get_request', methods=['GET'])
|
840 |
def send_get_request():
|
841 |
token = request.args.get('token')
|
|
|
844 |
|
845 |
try:
|
846 |
response = requests.get(url, headers={'X-Token': token})
|
847 |
+
response.raise_for_status()
|
848 |
data = response.json()
|
849 |
|
|
|
850 |
if data is None or 'report' not in data:
|
851 |
return jsonify({'error': 'No report data found'}), 500
|
852 |
|
853 |
report = data.get('report', {})
|
854 |
messages = data.get('messages', {})
|
855 |
|
|
|
856 |
if report is None:
|
857 |
return jsonify({'error': 'No report data found in the response'}), 500
|
858 |
|
|
|
884 |
except requests.exceptions.RequestException as e:
|
885 |
return jsonify({'error': f'API request failed: {str(e)}'}), 500
|
886 |
|
|
|
|
|
|
|
887 |
@app.route('/webhookbz', methods=['POST'])
|
888 |
def webhookbz():
|
889 |
api_sys_control = request.args.get('api_sys')
|
|
|
946 |
|
947 |
|
948 |
|
949 |
+
|
950 |
+
|
951 |
+
|
952 |
+
|
953 |
+
|
954 |
|
955 |
|
956 |
|