DmitrMakeev
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -792,137 +792,63 @@ def update_or_insert_user(db_name, user_data, mapping_template):
|
|
792 |
conn = sqlite3.connect(db_name)
|
793 |
cursor = conn.cursor()
|
794 |
|
795 |
-
# Получение email пользователя из данных
|
796 |
email = user_data.get('email')
|
797 |
if not email:
|
798 |
logging.error(f"User data missing email: {user_data}")
|
799 |
return
|
800 |
|
801 |
-
logging.debug(f"Processing user with email: {email}")
|
802 |
-
|
803 |
-
# Проверка существования пользователя в базе данных по email
|
804 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
805 |
user = cursor.fetchone()
|
806 |
-
logging.debug(f"User found: {user}")
|
807 |
|
808 |
-
|
809 |
-
web_st_value = 1 # Инициализация значения web_st
|
810 |
if user:
|
811 |
-
# Проверка текущего значения web_st и его инкрементация
|
812 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
813 |
web_st_value = int(current_web_st) + 1
|
814 |
-
logging.debug(f"Calculated web_st_value: {web_st_value}")
|
815 |
-
|
816 |
-
# Обновление значения web_st
|
817 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
818 |
-
conn.commit()
|
819 |
-
conn.close()
|
820 |
-
logging.debug(f"User {email} web_st updated to {web_st_value}")
|
821 |
-
else:
|
822 |
-
conn.close()
|
823 |
-
logging.debug(f"User {email} not found, proceeding with insert")
|
824 |
-
|
825 |
-
# Открываем соединение снова для остальных операций
|
826 |
-
conn = sqlite3.connect(db_name)
|
827 |
-
cursor = conn.cursor()
|
828 |
-
|
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 |
-
# Проверяем тип элементов списка
|
836 |
-
if all(isinstance(item, str) for item in value):
|
837 |
-
transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
|
838 |
-
else:
|
839 |
-
logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
|
840 |
-
transformed_data[db_column] = ""
|
841 |
-
else:
|
842 |
-
transformed_data[db_column] = str(value)
|
843 |
-
logging.debug(f"Transformed data: {transformed_data}")
|
844 |
-
|
845 |
-
# Заполнение обязательных полей значениями по умолчанию
|
846 |
-
required_fields = [
|
847 |
-
"vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
|
848 |
-
"b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
|
849 |
-
"shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
|
850 |
-
"key_pr", "n_con", "canal", "data_t"
|
851 |
-
]
|
852 |
-
for field in required_fields:
|
853 |
-
if field not in transformed_data:
|
854 |
-
transformed_data[field] = ""
|
855 |
-
logging.debug(f"Transformed data after adding required fields: {transformed_data}")
|
856 |
-
|
857 |
-
# Обработка номера телефона, если он есть
|
858 |
-
if 'phone' in user_data:
|
859 |
-
phone = user_data['phone']
|
860 |
-
if phone.startswith('+'):
|
861 |
-
phone = phone[1:]
|
862 |
-
transformed_data['phone'] = phone
|
863 |
-
logging.debug(f"Transformed data after phone processing: {transformed_data}")
|
864 |
-
|
865 |
-
# Добавление значения web_st в данные для вставки
|
866 |
-
transformed_data['web_st'] = web_st_value
|
867 |
-
|
868 |
-
# Обновление данных пользователя в базе данных
|
869 |
-
if user:
|
870 |
-
update_query = "UPDATE contacts SET "
|
871 |
-
update_values = []
|
872 |
-
for column, value in transformed_data.items():
|
873 |
-
update_query += f"{column} = ?, "
|
874 |
-
update_values.append(value)
|
875 |
-
update_query = update_query.rstrip(", ") + " WHERE email = ?"
|
876 |
-
update_values.append(email)
|
877 |
-
logging.debug(f"Update query: {update_query} with values: {update_values}")
|
878 |
-
cursor.execute(update_query, update_values)
|
879 |
else:
|
|
|
|
|
880 |
columns = ', '.join(transformed_data.keys())
|
881 |
placeholders = ', '.join('?' for _ in transformed_data)
|
882 |
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
883 |
-
|
884 |
-
logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
|
885 |
-
cursor.execute(insert_query, insert_values)
|
886 |
|
887 |
-
# Подтверждение изменений и закрытие соединения
|
888 |
conn.commit()
|
889 |
conn.close()
|
890 |
-
logging.debug(f"User with email {email} processed successfully")
|
891 |
-
|
892 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
893 |
|
894 |
@app.route('/send_get_request', methods=['GET'])
|
895 |
def send_get_request():
|
896 |
token = request.args.get('token')
|
897 |
-
|
898 |
-
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={
|
899 |
|
900 |
response = requests.get(url, headers={'X-Token': token})
|
901 |
|
902 |
if response.status_code == 200:
|
903 |
data = response.json()
|
904 |
-
|
905 |
-
|
906 |
-
messages = data.get('messages', {})
|
907 |
-
|
908 |
-
report_json_str = report.get('report', '{}')
|
909 |
-
try:
|
910 |
-
report_json = json.loads(report_json_str)
|
911 |
-
except json.JSONDecodeError:
|
912 |
-
report_json = {}
|
913 |
-
|
914 |
-
messages_json_str = report.get('messages', '{}')
|
915 |
-
try:
|
916 |
-
messages_json = json.loads(messages_json_str)
|
917 |
-
except json.JSONDecodeError:
|
918 |
-
messages_json = {}
|
919 |
-
|
920 |
users_meta = report_json.get('usersMeta', {})
|
921 |
|
922 |
-
# Обновление или добавление каждого пользователя в базу данных
|
923 |
processed_emails = set()
|
924 |
for user_id, user_data in users_meta.items():
|
925 |
-
# Получаем только сообщения для текущего пользователя
|
926 |
user_messages = messages_json.get(user_id, [])
|
927 |
user_data['messages'] = user_messages
|
928 |
email = user_data.get('email')
|
|
|
792 |
conn = sqlite3.connect(db_name)
|
793 |
cursor = conn.cursor()
|
794 |
|
|
|
795 |
email = user_data.get('email')
|
796 |
if not email:
|
797 |
logging.error(f"User data missing email: {user_data}")
|
798 |
return
|
799 |
|
|
|
|
|
|
|
800 |
cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
|
801 |
user = cursor.fetchone()
|
|
|
802 |
|
803 |
+
web_st_value = 1
|
|
|
804 |
if user:
|
|
|
805 |
current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
|
806 |
web_st_value = int(current_web_st) + 1
|
|
|
|
|
|
|
807 |
cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
808 |
else:
|
809 |
+
transformed_data = {db_column: str(user_data.get(json_key, "")) for json_key, db_column in mapping_template.items()}
|
810 |
+
transformed_data['web_st'] = web_st_value
|
811 |
columns = ', '.join(transformed_data.keys())
|
812 |
placeholders = ', '.join('?' for _ in transformed_data)
|
813 |
insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
|
814 |
+
cursor.execute(insert_query, list(transformed_data.values()))
|
|
|
|
|
815 |
|
|
|
816 |
conn.commit()
|
817 |
conn.close()
|
|
|
|
|
818 |
|
819 |
+
@app.route('/send_request', methods=['POST'])
|
820 |
+
def send_request():
|
821 |
+
token = request.form.get('token')
|
822 |
+
min_date = request.form.get('minDate')
|
823 |
+
limit = request.form.get('limit', '20')
|
824 |
+
webinar_type = request.form.get('type', 'LiveWebinars')
|
825 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&limit={limit}&type={webinar_type}'
|
826 |
+
|
827 |
+
response = requests.get(url, headers={'X-Token': token})
|
828 |
+
|
829 |
+
if response.status_code == 200:
|
830 |
+
data = response.json()
|
831 |
+
webinar_ids = [item['webinarId'] for item in data['list']]
|
832 |
+
return jsonify(webinar_ids)
|
833 |
+
else:
|
834 |
+
return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
|
835 |
|
836 |
@app.route('/send_get_request', methods=['GET'])
|
837 |
def send_get_request():
|
838 |
token = request.args.get('token')
|
839 |
+
webinar_id = request.args.get('webinarId')
|
840 |
+
url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
|
841 |
|
842 |
response = requests.get(url, headers={'X-Token': token})
|
843 |
|
844 |
if response.status_code == 200:
|
845 |
data = response.json()
|
846 |
+
report_json = json.loads(data.get('report', {}).get('report', '{}'))
|
847 |
+
messages_json = json.loads(data.get('report', {}).get('messages', '{}'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
848 |
users_meta = report_json.get('usersMeta', {})
|
849 |
|
|
|
850 |
processed_emails = set()
|
851 |
for user_id, user_data in users_meta.items():
|
|
|
852 |
user_messages = messages_json.get(user_id, [])
|
853 |
user_data['messages'] = user_messages
|
854 |
email = user_data.get('email')
|