Update app.py
Browse files
app.py
CHANGED
@@ -665,59 +665,60 @@ def data_gc_tab_out():
|
|
665 |
|
666 |
|
667 |
|
668 |
-
|
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
|
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 +726,19 @@ 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", "
|
733 |
-
"key_pr", "n_con", "canal", "
|
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 +746,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 |
-
|
758 |
-
transformed_data['web_st'] = int(current_web_st) + 1
|
759 |
-
else:
|
760 |
-
transformed_data['web_st'] = 1
|
761 |
-
|
762 |
-
new_messages = transformed_data.get('b_mess', "")
|
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 +768,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 +804,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 +835,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'})
|
@@ -872,8 +845,6 @@ def send_get_request():
|
|
872 |
|
873 |
|
874 |
|
875 |
-
api_bz = "SkrIONpr3ByeSIuEaBhr1bB8u4aBhSJfH8uEpB2rk7rI_ETrn"
|
876 |
-
|
877 |
|
878 |
@app.route('/webhookbz', methods=['POST'])
|
879 |
def webhookbz():
|
@@ -886,10 +857,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,13 +887,23 @@ 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 |
|
@@ -1485,6 +1465,24 @@ mapp_templates = {
|
|
1485 |
|
1486 |
DATABASE_NAME3 = 'data_gc.db'
|
1487 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1488 |
def add_or_update_contact(contact_data):
|
1489 |
conn = sqlite3.connect(DATABASE_NAME3)
|
1490 |
cursor = conn.cursor()
|
@@ -1499,35 +1497,27 @@ def add_or_update_contact(contact_data):
|
|
1499 |
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
|
1500 |
contact_data['data_t'] = msk_now.strftime('%Y-%m-%d %H:%M:%S')
|
1501 |
|
1502 |
-
|
|
|
|
|
1503 |
fields = [
|
1504 |
'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
|
1505 |
'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator',
|
1506 |
-
'pr1', 'pr2', 'pr3', 'pr4', 'pr5', '
|
1507 |
]
|
1508 |
|
1509 |
-
# Устанавливаем значения по умолчанию для отсутствующих полей
|
1510 |
-
for field in fields:
|
1511 |
-
if field not in contact_data:
|
1512 |
-
contact_data[field] = ''
|
1513 |
-
|
1514 |
placeholders = ", ".join([f"{field} = ?" for field in fields])
|
1515 |
|
1516 |
-
cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
|
1517 |
-
contact = cursor.fetchone()
|
1518 |
-
|
1519 |
if contact:
|
1520 |
update_query = f"UPDATE contacts SET {placeholders} WHERE id = ?"
|
1521 |
-
cursor.execute(update_query, (*[contact_data
|
1522 |
else:
|
1523 |
insert_query = f"INSERT INTO contacts ({', '.join(fields)}) VALUES ({', '.join(['?' for _ in fields])})"
|
1524 |
-
cursor.execute(insert_query, tuple(contact_data
|
1525 |
|
1526 |
conn.commit()
|
1527 |
conn.close()
|
1528 |
|
1529 |
-
|
1530 |
-
|
1531 |
@app.route('/add_data_ver_cur', methods=['GET'])
|
1532 |
def add_data_ver_cur():
|
1533 |
global current_curator_index
|
@@ -1540,18 +1530,11 @@ def add_data_ver_cur():
|
|
1540 |
|
1541 |
user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}
|
1542 |
|
1543 |
-
logging.debug(f"Received data: {user_data}")
|
1544 |
-
|
1545 |
if curator_on_off == "1":
|
1546 |
user_data['curator'] = curators[current_curator_index]
|
1547 |
|
1548 |
if veref_on_off == "1":
|
1549 |
-
|
1550 |
-
if not phone_number:
|
1551 |
-
logging.error("Phone number is empty")
|
1552 |
-
return jsonify({'status': 'error', 'message': 'Phone number is empty'}), 400
|
1553 |
-
|
1554 |
-
phone_verification_response = verify_phone_number(phone_number)
|
1555 |
if phone_verification_response is not None:
|
1556 |
user_data['ws_st'] = phone_verification_response
|
1557 |
|
@@ -1559,10 +1542,6 @@ def add_data_ver_cur():
|
|
1559 |
add_or_update_contact(user_data)
|
1560 |
if curator_on_off == "1":
|
1561 |
current_curator_index = (current_curator_index + 1) % len(curators)
|
1562 |
-
|
1563 |
-
# Отправка данных в Google Forms
|
1564 |
-
send_to_google_forms(user_data, gog_url)
|
1565 |
-
|
1566 |
return jsonify({'status': 'success', 'message': f'User added with curator {user_data.get("curator", "not assigned")}'})
|
1567 |
except Exception as e:
|
1568 |
logging.error(f"Error adding user: {e}")
|
@@ -1581,25 +1560,6 @@ def add_data_ver_cur():
|
|
1581 |
|
1582 |
|
1583 |
|
1584 |
-
|
1585 |
-
|
1586 |
-
|
1587 |
-
|
1588 |
-
|
1589 |
-
|
1590 |
-
|
1591 |
-
|
1592 |
-
|
1593 |
-
|
1594 |
-
|
1595 |
-
|
1596 |
-
|
1597 |
-
|
1598 |
-
|
1599 |
-
|
1600 |
-
|
1601 |
-
# Глобальная переменная для управления верификацией
|
1602 |
-
|
1603 |
DATABASE2 = 'data_gc.db'
|
1604 |
|
1605 |
def verify_phone_number(phone_number):
|
@@ -1612,7 +1572,7 @@ def verify_phone_number(phone_number):
|
|
1612 |
return response_body.get('existsWhatsapp', 'false')
|
1613 |
else:
|
1614 |
return "Error"
|
1615 |
-
|
1616 |
def parse_csv_data(data):
|
1617 |
parsed_data = []
|
1618 |
for item in data:
|
@@ -1622,10 +1582,6 @@ def parse_csv_data(data):
|
|
1622 |
parsed_data.append(dict(zip(headers, row)))
|
1623 |
return parsed_data
|
1624 |
|
1625 |
-
def clean_phone_number(phone_number):
|
1626 |
-
# Удаляем все символы, кроме цифр
|
1627 |
-
return re.sub(r'\D', '', phone_number)
|
1628 |
-
|
1629 |
def insert_data(data, verify_phone, add_curator):
|
1630 |
global current_curator_index
|
1631 |
conn = sqlite3.connect(DATABASE2)
|
@@ -1635,10 +1591,7 @@ def insert_data(data, verify_phone, add_curator):
|
|
1635 |
name = row.get('Name', '')
|
1636 |
phone = row.get('Phone', '').lstrip('+')
|
1637 |
email = row.get('Email', '')
|
1638 |
-
data_t = row.get('Date', '').
|
1639 |
-
|
1640 |
-
# Очистка номера телефона
|
1641 |
-
phone = clean_phone_number(phone)
|
1642 |
|
1643 |
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
|
1644 |
user_exists = cursor.fetchone()
|
@@ -1671,9 +1624,6 @@ def insert_data(data, verify_phone, add_curator):
|
|
1671 |
|
1672 |
try:
|
1673 |
cursor.execute(query, values)
|
1674 |
-
# Отправка данных в Google Forms
|
1675 |
-
user_data = dict(zip(columns, values))
|
1676 |
-
send_to_google_forms(user_data, gog_url)
|
1677 |
except Exception as e:
|
1678 |
print(f"Error inserting row: {row}")
|
1679 |
print(f"Error message: {str(e)}")
|
@@ -1703,6 +1653,11 @@ def upload_csv():
|
|
1703 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1704 |
return jsonify({"error": "Invalid file format"}), 400
|
1705 |
|
|
|
|
|
|
|
|
|
|
|
1706 |
@app.route('/upl_csv', methods=['GET'])
|
1707 |
def se_upl_csv():
|
1708 |
api_sys_control = request.args.get('api_sys')
|
@@ -1717,6 +1672,15 @@ def se_upl_csv():
|
|
1717 |
|
1718 |
|
1719 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1720 |
DATABASE = 'data_gc.db'
|
1721 |
|
1722 |
# Функция для очистки номера телефона
|
|
|
665 |
|
666 |
|
667 |
|
668 |
+
DATABASE_NAME = 'data_gc.db'
|
|
|
|
|
669 |
|
|
|
670 |
|
671 |
|
672 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
673 |
|
|
|
674 |
|
675 |
+
def update_or_insert_user(db_name, user_data, mapping_template):
|
|
|
676 |
conn = sqlite3.connect(db_name)
|
677 |
cursor = conn.cursor()
|
678 |
|
679 |
+
# Получение email пользователя из данных
|
680 |
email = user_data.get('email')
|
681 |
if not email:
|
682 |
logging.error(f"User data missing email: {user_data}")
|
683 |
return
|
684 |
|
685 |
logging.debug(f"Processing user with email: {email}")
|
686 |
+
|
687 |
+
# Проверка существования пользователя в базе данных по email
|
688 |
+
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
689 |
user = cursor.fetchone()
|
690 |
logging.debug(f"User found: {user}")
|
691 |
|
692 |
+
# Вынесение увеличения значения web_st в отдельный блок
|
693 |
+
web_st_value = 1 # Инициализация значения web_st
|
694 |
+
if user:
|
695 |
+
# Проверка текущего значения web_st и его инкрементация
|
696 |
+
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
697 |
+
web_st_value = int(current_web_st) + 1
|
698 |
+
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
699 |
+
|
700 |
+
# Обновление значения web_st
|
701 |
+
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
702 |
+
conn.commit()
|
703 |
+
conn.close()
|
704 |
+
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
705 |
+
else:
|
706 |
+
conn.close()
|
707 |
+
logging.debug(f"User {email} not found, proceeding with insert")
|
708 |
+
|
709 |
+
# Открываем соединение снова для остальных операций
|
710 |
+
conn = sqlite3.connect(db_name)
|
711 |
+
cursor = conn.cursor()
|
712 |
|
713 |
+
# Преобразование данных пользователя на основе шаблона сопоставления
|
714 |
transformed_data = {}
|
715 |
for json_key, db_column in mapping_template.items():
|
716 |
value = user_data.get(json_key, "")
|
717 |
+
|
718 |
if isinstance(value, list):
|
719 |
+
# Проверяем тип элементов списка
|
720 |
if all(isinstance(item, str) for item in value):
|
721 |
+
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
722 |
else:
|
723 |
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
724 |
transformed_data[db_column] = ""
|
|
|
726 |
transformed_data[db_column] = str(value)
|
727 |
logging.debug(f"Transformed data: {transformed_data}")
|
728 |
|
729 |
+
# Заполнение обязательных полей значениями по умолчанию
|
730 |
required_fields = [
|
731 |
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
732 |
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
733 |
+
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
734 |
+
"key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
|
735 |
]
|
736 |
for field in required_fields:
|
737 |
if field not in transformed_data:
|
738 |
transformed_data[field] = ""
|
739 |
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
740 |
|
741 |
+
# Обработка номера телефона, если он есть
|
742 |
if 'phone' in user_data:
|
743 |
phone = user_data['phone']
|
744 |
if phone.startswith('+'):
|
|
|
746 |
transformed_data['phone'] = phone
|
747 |
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
748 |
|
749 |
+
# Добавление значения web_st в данные для вставки
|
750 |
+
transformed_data['web_st'] = web_st_value
|
|
|
|
|
|
|
|
|
|
|
|
|
751 |
|
752 |
+
# Обновление данных пользователя в базе данных
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
753 |
if user:
|
754 |
update_query = "UPDATE contacts SET "
|
755 |
update_values = []
|
756 |
for column, value in transformed_data.items():
|
757 |
+
update_query += f"{column} = ?, "
|
758 |
+
update_values.append(value)
|
|
|
759 |
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
760 |
update_values.append(email)
|
761 |
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
|
|
768 |
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
769 |
cursor.execute(insert_query, insert_values)
|
770 |
|
771 |
+
# Подтверждение изменений и закрытие соединения
|
772 |
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
773 |
conn.close()
|
774 |
logging.debug(f"User with email {email} processed successfully")
|
775 |
|
|
|
|
|
|
|
|
|
|
|
|
|
776 |
|
777 |
@app.route('/send_request', methods=['POST'])
|
778 |
def send_request():
|
779 |
token = request.form.get('token')
|
780 |
min_date = request.form.get('minDate')
|
781 |
type = request.form.get('type')
|
782 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}'
|
783 |
|
784 |
response = requests.get(url, headers={'X-Token': token})
|
785 |
|
|
|
804 |
response.raise_for_status() # Проверка на ошибки HTTP
|
805 |
data = response.json()
|
806 |
|
807 |
+
# Убедитесь, что report существует в данных
|
808 |
if data is None or 'report' not in data:
|
809 |
return jsonify({'error': 'No report data found'}), 500
|
810 |
|
811 |
report = data.get('report', {})
|
812 |
messages = data.get('messages', {})
|
813 |
|
814 |
+
# Проверка на None перед исп��льзованием
|
815 |
if report is None:
|
816 |
return jsonify({'error': 'No report data found in the response'}), 500
|
817 |
|
|
|
835 |
user_data['messages'] = user_messages
|
836 |
email = user_data.get('email')
|
837 |
if email and email not in processed_emails:
|
838 |
+
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
839 |
processed_emails.add(email)
|
840 |
|
841 |
return jsonify({'status': 'User data saved successfully'})
|
|
|
845 |
|
846 |
|
847 |
|
|
|
|
|
848 |
|
849 |
@app.route('/webhookbz', methods=['POST'])
|
850 |
def webhookbz():
|
|
|
857 |
|
858 |
if not webinar_id:
|
859 |
return jsonify({'error': 'webinarId is required'}), 400
|
|
|
|
|
|
|
860 |
|
861 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
|
862 |
+
response = requests.get(url, headers={'X-Token': api_key_sys})
|
863 |
|
864 |
if response.status_code == 200:
|
865 |
data = response.json()
|
|
|
887 |
user_data['messages'] = user_messages
|
888 |
email = user_data.get('email')
|
889 |
if email and email not in processed_emails:
|
890 |
+
update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
|
891 |
processed_emails.add(email)
|
892 |
|
893 |
return jsonify({'status': 'User data saved successfully'})
|
894 |
else:
|
895 |
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
896 |
|
897 |
+
|
898 |
+
|
899 |
+
|
900 |
+
|
901 |
+
|
902 |
+
|
903 |
+
|
904 |
+
|
905 |
+
|
906 |
+
|
907 |
|
908 |
|
909 |
|
|
|
1465 |
|
1466 |
DATABASE_NAME3 = 'data_gc.db'
|
1467 |
|
1468 |
+
|
1469 |
+
def verify_phone_number(phone_number):
|
1470 |
+
if verifikation_start == "1":
|
1471 |
+
full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
|
1472 |
+
|
1473 |
+
payload = json.dumps({"phoneNumber": phone_number})
|
1474 |
+
headers = {'Content-Type': 'application/json'}
|
1475 |
+
|
1476 |
+
response = requests.post(full_url_ver, headers=headers, data=payload)
|
1477 |
+
|
1478 |
+
if response.status_code == 200:
|
1479 |
+
response_body = response.json()
|
1480 |
+
return response_body.get('existsWhatsapp', 'false')
|
1481 |
+
else:
|
1482 |
+
return "Error"
|
1483 |
+
else:
|
1484 |
+
return "false"
|
1485 |
+
|
1486 |
def add_or_update_contact(contact_data):
|
1487 |
conn = sqlite3.connect(DATABASE_NAME3)
|
1488 |
cursor = conn.cursor()
|
|
|
1497 |
msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
|
1498 |
contact_data['data_t'] = msk_now.strftime('%Y-%m-%d %H:%M:%S')
|
1499 |
|
1500 |
+
cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
|
1501 |
+
contact = cursor.fetchone()
|
1502 |
+
|
1503 |
fields = [
|
1504 |
'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
|
1505 |
'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator',
|
1506 |
+
'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
|
1507 |
]
|
1508 |
|
|
|
|
|
|
|
|
|
|
|
1509 |
placeholders = ", ".join([f"{field} = ?" for field in fields])
|
1510 |
|
|
|
|
|
|
|
1511 |
if contact:
|
1512 |
update_query = f"UPDATE contacts SET {placeholders} WHERE id = ?"
|
1513 |
+
cursor.execute(update_query, (*[contact_data.get(field, '') for field in fields], contact[0]))
|
1514 |
else:
|
1515 |
insert_query = f"INSERT INTO contacts ({', '.join(fields)}) VALUES ({', '.join(['?' for _ in fields])})"
|
1516 |
+
cursor.execute(insert_query, tuple(contact_data.get(field, '') for field in fields))
|
1517 |
|
1518 |
conn.commit()
|
1519 |
conn.close()
|
1520 |
|
|
|
|
|
1521 |
@app.route('/add_data_ver_cur', methods=['GET'])
|
1522 |
def add_data_ver_cur():
|
1523 |
global current_curator_index
|
|
|
1530 |
|
1531 |
user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}
|
1532 |
|
|
|
|
|
1533 |
if curator_on_off == "1":
|
1534 |
user_data['curator'] = curators[current_curator_index]
|
1535 |
|
1536 |
if veref_on_off == "1":
|
1537 |
+
phone_verification_response = verify_phone_number(user_data.get('phone', ''))
|
|
|
|
|
|
|
|
|
|
|
1538 |
if phone_verification_response is not None:
|
1539 |
user_data['ws_st'] = phone_verification_response
|
1540 |
|
|
|
1542 |
add_or_update_contact(user_data)
|
1543 |
if curator_on_off == "1":
|
1544 |
current_curator_index = (current_curator_index + 1) % len(curators)
|
|
|
|
|
|
|
|
|
1545 |
return jsonify({'status': 'success', 'message': f'User added with curator {user_data.get("curator", "not assigned")}'})
|
1546 |
except Exception as e:
|
1547 |
logging.error(f"Error adding user: {e}")
|
|
|
1560 |
|
1561 |
|
1562 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1563 |
DATABASE2 = 'data_gc.db'
|
1564 |
|
1565 |
def verify_phone_number(phone_number):
|
|
|
1572 |
return response_body.get('existsWhatsapp', 'false')
|
1573 |
else:
|
1574 |
return "Error"
|
1575 |
+
|
1576 |
def parse_csv_data(data):
|
1577 |
parsed_data = []
|
1578 |
for item in data:
|
|
|
1582 |
parsed_data.append(dict(zip(headers, row)))
|
1583 |
return parsed_data
|
1584 |
|
|
|
|
|
|
|
|
|
1585 |
def insert_data(data, verify_phone, add_curator):
|
1586 |
global current_curator_index
|
1587 |
conn = sqlite3.connect(DATABASE2)
|
|
|
1591 |
name = row.get('Name', '')
|
1592 |
phone = row.get('Phone', '').lstrip('+')
|
1593 |
email = row.get('Email', '')
|
1594 |
+
data_t = row.get('Date', '').strip('"')
|
|
|
|
|
|
|
1595 |
|
1596 |
cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
|
1597 |
user_exists = cursor.fetchone()
|
|
|
1624 |
|
1625 |
try:
|
1626 |
cursor.execute(query, values)
|
|
|
|
|
|
|
1627 |
except Exception as e:
|
1628 |
print(f"Error inserting row: {row}")
|
1629 |
print(f"Error message: {str(e)}")
|
|
|
1653 |
return jsonify({"message": "Data uploaded and inserted successfully"})
|
1654 |
return jsonify({"error": "Invalid file format"}), 400
|
1655 |
|
1656 |
+
|
1657 |
+
|
1658 |
+
|
1659 |
+
|
1660 |
+
|
1661 |
@app.route('/upl_csv', methods=['GET'])
|
1662 |
def se_upl_csv():
|
1663 |
api_sys_control = request.args.get('api_sys')
|
|
|
1672 |
|
1673 |
|
1674 |
|
1675 |
+
|
1676 |
+
|
1677 |
+
|
1678 |
+
|
1679 |
+
|
1680 |
+
|
1681 |
+
|
1682 |
+
|
1683 |
+
|
1684 |
DATABASE = 'data_gc.db'
|
1685 |
|
1686 |
# Функция для очистки номера телефона
|