DmitrMakeev commited on
Commit
99480f2
·
verified ·
1 Parent(s): 90eb70e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -25
app.py CHANGED
@@ -786,14 +786,23 @@ DATABASE_NAME = 'data_gc.db'
786
 
787
 
788
 
 
 
789
 
 
790
 
 
 
 
 
 
 
 
791
 
792
  def update_or_insert_user(db_name, user_data, mapping_template):
793
  conn = sqlite3.connect(db_name)
794
  cursor = conn.cursor()
795
 
796
- # Получение email пользователя из данных
797
  email = user_data.get('email')
798
  if not email:
799
  logging.error(f"User data missing email: {user_data}")
@@ -801,20 +810,16 @@ def update_or_insert_user(db_name, user_data, mapping_template):
801
 
802
  logging.debug(f"Processing user with email: {email}")
803
 
804
- # Проверка существования пользователя в базе данных по email
805
  cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
806
  user = cursor.fetchone()
807
  logging.debug(f"User found: {user}")
808
 
809
- # Вынесение увеличения значения web_st в отдельный блок
810
- web_st_value = 1 # Инициализация значения web_st
811
  if user:
812
- # Проверка текущего значения web_st и его инкрементация
813
  current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
814
  web_st_value = int(current_web_st) + 1
815
  logging.debug(f"Calculated web_st_value: {web_st_value}")
816
 
817
- # Обновление значения web_st
818
  cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
819
  conn.commit()
820
  conn.close()
@@ -823,19 +828,16 @@ def update_or_insert_user(db_name, user_data, mapping_template):
823
  conn.close()
824
  logging.debug(f"User {email} not found, proceeding with insert")
825
 
826
- # Открываем соединение снова для остальных операций
827
  conn = sqlite3.connect(db_name)
828
  cursor = conn.cursor()
829
 
830
- # Преобразование данных пользователя на основе шаблона сопоставления
831
  transformed_data = {}
832
  for json_key, db_column in mapping_template.items():
833
  value = user_data.get(json_key, "")
834
 
835
  if isinstance(value, list):
836
- # Проверяем тип элементов списка
837
  if all(isinstance(item, str) for item in value):
838
- transformed_data[db_column] = "; ".join(value) # Сохраняем сообщения в строку
839
  else:
840
  logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
841
  transformed_data[db_column] = ""
@@ -843,7 +845,6 @@ def update_or_insert_user(db_name, user_data, mapping_template):
843
  transformed_data[db_column] = str(value)
844
  logging.debug(f"Transformed data: {transformed_data}")
845
 
846
- # Заполнение обязательных полей значениями по умолчанию
847
  required_fields = [
848
  "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
849
  "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
@@ -855,7 +856,6 @@ def update_or_insert_user(db_name, user_data, mapping_template):
855
  transformed_data[field] = ""
856
  logging.debug(f"Transformed data after adding required fields: {transformed_data}")
857
 
858
- # Обработка номера телефона, если он есть
859
  if 'phone' in user_data:
860
  phone = user_data['phone']
861
  if phone.startswith('+'):
@@ -863,10 +863,8 @@ def update_or_insert_user(db_name, user_data, mapping_template):
863
  transformed_data['phone'] = phone
864
  logging.debug(f"Transformed data after phone processing: {transformed_data}")
865
 
866
- # Добавление значения web_st в данные для вставки
867
  transformed_data['web_st'] = web_st_value
868
 
869
- # Обновление данных пользователя в базе данных
870
  if user:
871
  update_query = "UPDATE contacts SET "
872
  update_values = []
@@ -885,12 +883,10 @@ def update_or_insert_user(db_name, user_data, mapping_template):
885
  logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
886
  cursor.execute(insert_query, insert_values)
887
 
888
- # Подтверждение изменений и закрытие соединения
889
  conn.commit()
890
  conn.close()
891
  logging.debug(f"User with email {email} processed successfully")
892
 
893
-
894
  @app.route('/send_request', methods=['POST'])
895
  def send_request():
896
  token = request.form.get('token')
@@ -907,9 +903,6 @@ def send_request():
907
  else:
908
  return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
909
 
910
-
911
-
912
-
913
  @app.route('/send_get_request', methods=['GET'])
914
  def send_get_request():
915
  token = request.args.get('token')
@@ -918,17 +911,15 @@ def send_get_request():
918
 
919
  try:
920
  response = requests.get(url, headers={'X-Token': token})
921
- response.raise_for_status() # Проверка на ошибки HTTP
922
  data = response.json()
923
 
924
- # Убедитесь, что report существует в данных
925
  if data is None or 'report' not in data:
926
  return jsonify({'error': 'No report data found'}), 500
927
 
928
  report = data.get('report', {})
929
  messages = data.get('messages', {})
930
 
931
- # Проверка на None перед использованием
932
  if report is None:
933
  return jsonify({'error': 'No report data found in the response'}), 500
934
 
@@ -960,9 +951,6 @@ def send_get_request():
960
  except requests.exceptions.RequestException as e:
961
  return jsonify({'error': f'API request failed: {str(e)}'}), 500
962
 
963
-
964
-
965
-
966
  @app.route('/webhookbz', methods=['POST'])
967
  def webhookbz():
968
  api_sys_control = request.args.get('api_sys')
 
786
 
787
 
788
 
789
+ verifikation_start = "1" # Глобальная переменная для управления верификацией
790
+ curator_on_off = "1" # Глобальная переменная для управления назначением куратора
791
 
792
+ current_curator_index = 0
793
 
794
+ def verify_phone_number(phone_number):
795
+ if verifikation_start == "1":
796
+ # Здесь должен быть ваш код для верификации номера телефона
797
+ # Например, вызов внешнего API для проверки наличия WhatsApp
798
+ return "true" # Заглушка для примера
799
+ else:
800
+ return "false"
801
 
802
  def update_or_insert_user(db_name, user_data, mapping_template):
803
  conn = sqlite3.connect(db_name)
804
  cursor = conn.cursor()
805
 
 
806
  email = user_data.get('email')
807
  if not email:
808
  logging.error(f"User data missing email: {user_data}")
 
810
 
811
  logging.debug(f"Processing user with email: {email}")
812
 
 
813
  cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
814
  user = cursor.fetchone()
815
  logging.debug(f"User found: {user}")
816
 
817
+ web_st_value = 1
 
818
  if user:
 
819
  current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
820
  web_st_value = int(current_web_st) + 1
821
  logging.debug(f"Calculated web_st_value: {web_st_value}")
822
 
 
823
  cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
824
  conn.commit()
825
  conn.close()
 
828
  conn.close()
829
  logging.debug(f"User {email} not found, proceeding with insert")
830
 
 
831
  conn = sqlite3.connect(db_name)
832
  cursor = conn.cursor()
833
 
 
834
  transformed_data = {}
835
  for json_key, db_column in mapping_template.items():
836
  value = user_data.get(json_key, "")
837
 
838
  if isinstance(value, list):
 
839
  if all(isinstance(item, str) for item in value):
840
+ transformed_data[db_column] = "; ".join(value)
841
  else:
842
  logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
843
  transformed_data[db_column] = ""
 
845
  transformed_data[db_column] = str(value)
846
  logging.debug(f"Transformed data: {transformed_data}")
847
 
 
848
  required_fields = [
849
  "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
850
  "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
 
856
  transformed_data[field] = ""
857
  logging.debug(f"Transformed data after adding required fields: {transformed_data}")
858
 
 
859
  if 'phone' in user_data:
860
  phone = user_data['phone']
861
  if phone.startswith('+'):
 
863
  transformed_data['phone'] = phone
864
  logging.debug(f"Transformed data after phone processing: {transformed_data}")
865
 
 
866
  transformed_data['web_st'] = web_st_value
867
 
 
868
  if user:
869
  update_query = "UPDATE contacts SET "
870
  update_values = []
 
883
  logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
884
  cursor.execute(insert_query, insert_values)
885
 
 
886
  conn.commit()
887
  conn.close()
888
  logging.debug(f"User with email {email} processed successfully")
889
 
 
890
  @app.route('/send_request', methods=['POST'])
891
  def send_request():
892
  token = request.form.get('token')
 
903
  else:
904
  return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
905
 
 
 
 
906
  @app.route('/send_get_request', methods=['GET'])
907
  def send_get_request():
908
  token = request.args.get('token')
 
911
 
912
  try:
913
  response = requests.get(url, headers={'X-Token': token})
914
+ response.raise_for_status()
915
  data = response.json()
916
 
 
917
  if data is None or 'report' not in data:
918
  return jsonify({'error': 'No report data found'}), 500
919
 
920
  report = data.get('report', {})
921
  messages = data.get('messages', {})
922
 
 
923
  if report is None:
924
  return jsonify({'error': 'No report data found in the response'}), 500
925
 
 
951
  except requests.exceptions.RequestException as e:
952
  return jsonify({'error': f'API request failed: {str(e)}'}), 500
953
 
 
 
 
954
  @app.route('/webhookbz', methods=['POST'])
955
  def webhookbz():
956
  api_sys_control = request.args.get('api_sys')