Spaces:
test-sj-crm
/
Runtime error

DmitrMakeev commited on
Commit
f158535
·
verified ·
1 Parent(s): 9cae9b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -91
app.py CHANGED
@@ -764,21 +764,6 @@ def data_gc_tab_out():
764
 
765
 
766
 
767
- @app.route('/send_request', methods=['POST'])
768
- def send_request():
769
- token = request.form.get('token')
770
- min_date = request.form.get('minDate')
771
- type = request.form.get('type')
772
- url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}'
773
-
774
- response = requests.get(url, headers={'X-Token': token})
775
-
776
- if response.status_code == 200:
777
- data = response.json()
778
- webinar_ids = [item['webinarId'] for item in data['list']]
779
- return jsonify(webinar_ids)
780
- else:
781
- return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
782
 
783
 
784
 
@@ -801,51 +786,14 @@ DATABASE_NAME = 'data_gc.db'
801
 
802
 
803
 
804
- verifikation_start = "1" # Глобальная переменная для управления верификацией
805
- curator_on_off = "1" # Глобальная переменная для управления назначением куратора
806
-
807
- current_curator_index = 0
808
-
809
-
810
- verifikation_start = "1" # Глобальная переменная для управления верификацией
811
- curator_on_off = "1" # Глобальная переменная для управления назначением куратора
812
- current_curator_index = 0
813
- curators = ["Curator1", "Curator2", "Curator3"] # Список кураторов
814
-
815
-
816
 
817
- mapping_template = {
818
- "name": "name",
819
- "phone": "phone",
820
- "email": "email",
821
- "b_city": "b_city",
822
- "b_fin": "b_fin",
823
- "b_ban": "b_ban",
824
- "b_ign": "b_ign",
825
- "b_baners": "b_baners",
826
- "b_butt": "b_butt",
827
- "b_mess": "b_mess"
828
- # Добавьте все необходимые поля для маппинга
829
- }
830
 
831
- def verify_phone_number_biz(phone_number):
832
- full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
833
- payload = {"phoneNumber": phone_number}
834
- headers = {'Content-Type': 'application/json'}
835
- try:
836
- response = requests.post(full_url_ver, headers=headers, json=payload)
837
- response.raise_for_status()
838
- response_body = response.json()
839
- logging.debug(f"Phone verification response: {response_body}")
840
- return response_body.get('existsWhatsapp', 'false')
841
- except requests.RequestException as e:
842
- logging.error(f"Error during phone verification: {str(e)}")
843
- return "Error"
844
 
845
- def update_or_insert_user_biz(db_name, user_data, mapping_template):
846
  conn = sqlite3.connect(db_name)
847
  cursor = conn.cursor()
848
 
 
849
  email = user_data.get('email')
850
  if not email:
851
  logging.error(f"User data missing email: {user_data}")
@@ -853,29 +801,41 @@ def update_or_insert_user_biz(db_name, user_data, mapping_template):
853
 
854
  logging.debug(f"Processing user with email: {email}")
855
 
 
856
  cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
857
  user = cursor.fetchone()
858
  logging.debug(f"User found: {user}")
859
 
860
- web_st_value = 1
 
861
  if user:
 
862
  current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
863
  web_st_value = int(current_web_st) + 1
864
  logging.debug(f"Calculated web_st_value: {web_st_value}")
865
 
 
866
  cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
867
  conn.commit()
 
868
  logging.debug(f"User {email} web_st updated to {web_st_value}")
869
  else:
 
870
  logging.debug(f"User {email} not found, proceeding with insert")
871
 
 
 
 
 
 
872
  transformed_data = {}
873
  for json_key, db_column in mapping_template.items():
874
  value = user_data.get(json_key, "")
875
 
876
  if isinstance(value, list):
 
877
  if all(isinstance(item, str) for item in value):
878
- transformed_data[db_column] = "; ".join(value)
879
  else:
880
  logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
881
  transformed_data[db_column] = ""
@@ -883,6 +843,7 @@ def update_or_insert_user_biz(db_name, user_data, mapping_template):
883
  transformed_data[db_column] = str(value)
884
  logging.debug(f"Transformed data: {transformed_data}")
885
 
 
886
  required_fields = [
887
  "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
888
  "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
@@ -894,6 +855,7 @@ def update_or_insert_user_biz(db_name, user_data, mapping_template):
894
  transformed_data[field] = ""
895
  logging.debug(f"Transformed data after adding required fields: {transformed_data}")
896
 
 
897
  if 'phone' in user_data:
898
  phone = user_data['phone']
899
  if phone.startswith('+'):
@@ -901,25 +863,10 @@ def update_or_insert_user_biz(db_name, user_data, mapping_template):
901
  transformed_data['phone'] = phone
902
  logging.debug(f"Transformed data after phone processing: {transformed_data}")
903
 
 
904
  transformed_data['web_st'] = web_st_value
905
 
906
- # Верификация номера телефона
907
- if 'phone' in user_data and verifikation_start == "1":
908
- phone_verification_result = verify_phone_number_biz(transformed_data['phone'])
909
- logging.debug(f"Phone verification result for {email}: {phone_verification_result}")
910
- if phone_verification_result == "true":
911
- transformed_data['ws_st'] = "True"
912
- else:
913
- transformed_data['ws_st'] = "False"
914
- logging.debug(f"Transformed data after phone verification: {transformed_data}")
915
-
916
- # Назначение куратора
917
- if curator_on_off == "1":
918
- global current_curator_index
919
- transformed_data['curator'] = curators[current_curator_index]
920
- current_curator_index = (current_curator_index + 1) % len(curators)
921
- logging.debug(f"Curator assigned for {email}: {transformed_data['curator']}")
922
-
923
  if user:
924
  update_query = "UPDATE contacts SET "
925
  update_values = []
@@ -938,27 +885,50 @@ def update_or_insert_user_biz(db_name, user_data, mapping_template):
938
  logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
939
  cursor.execute(insert_query, insert_values)
940
 
 
941
  conn.commit()
942
  conn.close()
943
  logging.debug(f"User with email {email} processed successfully")
944
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
945
  @app.route('/send_get_request', methods=['GET'])
946
- def send_get_request_biz():
947
  token = request.args.get('token')
948
  webinarId = request.args.get('webinarId')
949
  url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
950
 
951
  try:
952
  response = requests.get(url, headers={'X-Token': token})
953
- response.raise_for_status()
954
  data = response.json()
955
 
 
956
  if data is None or 'report' not in data:
957
  return jsonify({'error': 'No report data found'}), 500
958
 
959
  report = data.get('report', {})
960
  messages = data.get('messages', {})
961
 
 
962
  if report is None:
963
  return jsonify({'error': 'No report data found in the response'}), 500
964
 
@@ -982,7 +952,7 @@ def send_get_request_biz():
982
  user_data['messages'] = user_messages
983
  email = user_data.get('email')
984
  if email and email not in processed_emails:
985
- update_or_insert_user_biz(DATABASE_NAME, user_data, mapping_template)
986
  processed_emails.add(email)
987
 
988
  return jsonify({'status': 'User data saved successfully'})
@@ -993,6 +963,61 @@ def send_get_request_biz():
993
 
994
 
995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
996
 
997
 
998
 
@@ -1843,7 +1868,6 @@ function mySuccessFunction(form) {
1843
  if (form instanceof jQuery) {
1844
  form = form.get(0);
1845
  }
1846
-
1847
 
1848
  var obj = {};
1849
  var inputs = form.elements;
@@ -1854,16 +1878,13 @@ function mySuccessFunction(form) {
1854
  obj[input.name] = input.value;
1855
  }
1856
  });
1857
-
1858
 
1859
  var email = obj["Email"] || "";
1860
  var phone = obj["Phone"] || "";
1861
  var name = obj["Name"] || "";
1862
-
1863
  console.log("name:", name);
1864
  console.log("email:", email);
1865
  console.log("phone:", phone);
1866
-
1867
 
1868
  var urlParams = new URLSearchParams(window.location.search);
1869
  var utm_source = urlParams.get('utm_source') || "0";
@@ -1872,9 +1893,6 @@ function mySuccessFunction(form) {
1872
  var utm_content = urlParams.get('utm_content') || "0";
1873
  var utm_term = urlParams.get('utm_term') || "0";
1874
  var gcpc = urlParams.get('gcpc') || "0";
1875
-
1876
-
1877
-
1878
  var redirectUrl;
1879
  if (form.id === formId1) {
1880
  redirectUrl = new URL(redirectUrl1);
@@ -1886,8 +1904,6 @@ function mySuccessFunction(form) {
1886
  console.error('Неизвестный ID формы:', form.id);
1887
  return;
1888
  }
1889
-
1890
-
1891
  var queryString = '?ups=' + encodeURIComponent(ups);
1892
  queryString += '&name=' + encodeURIComponent(name);
1893
  queryString += '&email=' + encodeURIComponent(email);
@@ -1898,20 +1914,14 @@ function mySuccessFunction(form) {
1898
  queryString += '&utm_content=' + encodeURIComponent(utm_content);
1899
  queryString += '&utm_term=' + encodeURIComponent(utm_term);
1900
  queryString += '&gcpc=' + encodeURIComponent(gcpc);
1901
-
1902
-
1903
  console.log('Сформированный URL:', redirectUrl.toString() + queryString);
1904
-
1905
-
1906
  window.open(redirectUrl.toString() + queryString, '_blank');
1907
  }
1908
-
1909
  if (document.readyState !== 'loading') {
1910
  us_sendFormAfterSuccess();
1911
  } else {
1912
  document.addEventListener('DOMContentLoaded', us_sendFormAfterSuccess);
1913
  }
1914
-
1915
  function us_sendFormAfterSuccess() {
1916
  var forms = document.querySelectorAll('.js-form-proccess');
1917
  Array.prototype.forEach.call(forms, function(form) {
 
764
 
765
 
766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
 
768
 
769
 
 
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
 
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()
821
  logging.debug(f"User {email} web_st updated to {web_st_value}")
822
  else:
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
  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
  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
  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
  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')
897
+ min_date = request.form.get('minDate')
898
+ type = request.form.get('type')
899
+ url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}'
900
+
901
+ response = requests.get(url, headers={'X-Token': token})
902
+
903
+ if response.status_code == 200:
904
+ data = response.json()
905
+ webinar_ids = [item['webinarId'] for item in data['list']]
906
+ return jsonify(webinar_ids)
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')
916
  webinarId = request.args.get('webinarId')
917
  url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'
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
 
 
952
  user_data['messages'] = user_messages
953
  email = user_data.get('email')
954
  if email and email not in processed_emails:
955
+ update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
956
  processed_emails.add(email)
957
 
958
  return jsonify({'status': 'User data saved successfully'})
 
963
 
964
 
965
 
966
+ @app.route('/webhookbz', methods=['POST'])
967
+ def webhookbz():
968
+ api_sys_control = request.args.get('api_sys')
969
+ if api_sys_control != api_key_sys:
970
+ return "EUR 22", 200
971
+
972
+ data = request.json
973
+ webinar_id = data.get('webinarId')
974
+
975
+ if not webinar_id:
976
+ return jsonify({'error': 'webinarId is required'}), 400
977
+
978
+ url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
979
+ response = requests.get(url, headers={'X-Token': api_key_sys})
980
+
981
+ if response.status_code == 200:
982
+ data = response.json()
983
+
984
+ report = data.get('report', {})
985
+ messages = data.get('messages', {})
986
+
987
+ report_json_str = report.get('report', '{}')
988
+ try:
989
+ report_json = json.loads(report_json_str)
990
+ except json.JSONDecodeError:
991
+ report_json = {}
992
+
993
+ messages_json_str = report.get('messages', '{}')
994
+ try:
995
+ messages_json = json.loads(messages_json_str)
996
+ except json.JSONDecodeError:
997
+ messages_json = {}
998
+
999
+ users_meta = report_json.get('usersMeta', {})
1000
+
1001
+ processed_emails = set()
1002
+ for user_id, user_data in users_meta.items():
1003
+ user_messages = messages_json.get(user_id, [])
1004
+ user_data['messages'] = user_messages
1005
+ email = user_data.get('email')
1006
+ if email and email not in processed_emails:
1007
+ update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
1008
+ processed_emails.add(email)
1009
+
1010
+ return jsonify({'status': 'User data saved successfully'})
1011
+ else:
1012
+ return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code
1013
+
1014
+
1015
+
1016
+
1017
+
1018
+
1019
+
1020
+
1021
 
1022
 
1023
 
 
1868
  if (form instanceof jQuery) {
1869
  form = form.get(0);
1870
  }
 
1871
 
1872
  var obj = {};
1873
  var inputs = form.elements;
 
1878
  obj[input.name] = input.value;
1879
  }
1880
  });
 
1881
 
1882
  var email = obj["Email"] || "";
1883
  var phone = obj["Phone"] || "";
1884
  var name = obj["Name"] || "";
 
1885
  console.log("name:", name);
1886
  console.log("email:", email);
1887
  console.log("phone:", phone);
 
1888
 
1889
  var urlParams = new URLSearchParams(window.location.search);
1890
  var utm_source = urlParams.get('utm_source') || "0";
 
1893
  var utm_content = urlParams.get('utm_content') || "0";
1894
  var utm_term = urlParams.get('utm_term') || "0";
1895
  var gcpc = urlParams.get('gcpc') || "0";
 
 
 
1896
  var redirectUrl;
1897
  if (form.id === formId1) {
1898
  redirectUrl = new URL(redirectUrl1);
 
1904
  console.error('Неизвестный ID формы:', form.id);
1905
  return;
1906
  }
 
 
1907
  var queryString = '?ups=' + encodeURIComponent(ups);
1908
  queryString += '&name=' + encodeURIComponent(name);
1909
  queryString += '&email=' + encodeURIComponent(email);
 
1914
  queryString += '&utm_content=' + encodeURIComponent(utm_content);
1915
  queryString += '&utm_term=' + encodeURIComponent(utm_term);
1916
  queryString += '&gcpc=' + encodeURIComponent(gcpc);
 
 
1917
  console.log('Сформированный URL:', redirectUrl.toString() + queryString);
 
 
1918
  window.open(redirectUrl.toString() + queryString, '_blank');
1919
  }
 
1920
  if (document.readyState !== 'loading') {
1921
  us_sendFormAfterSuccess();
1922
  } else {
1923
  document.addEventListener('DOMContentLoaded', us_sendFormAfterSuccess);
1924
  }
 
1925
  function us_sendFormAfterSuccess() {
1926
  var forms = document.querySelectorAll('.js-form-proccess');
1927
  Array.prototype.forEach.call(forms, function(form) {