DmitrMakeev commited on
Commit
24ca449
1 Parent(s): 0465507

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -52
app.py CHANGED
@@ -747,70 +747,94 @@ def update_or_insert_user(db_name, user_data, mapping_template, gog_url):
747
 
748
  logging.debug(f"Processing user with email: {email}")
749
 
750
- # Проверка существующих данных
751
- cursor.execute("SELECT * FROM contacts WHERE email = ?", (email,))
752
  user = cursor.fetchone()
753
- current_values = dict(zip([column[0] for column in cursor.description], user)) if user else {}
754
 
755
- # Обработка данных
756
- transformed_data = transform_data(user_data, mapping_template)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
757
 
758
- # Сравнение и подготовка данных
759
- final_data = prepare_final_data(transformed_data, current_values)
760
-
761
- # Обновление или вставка данных в базу данных
762
  if user:
763
- update_database(cursor, final_data, email)
 
 
 
 
 
 
 
 
 
764
  else:
765
- insert_into_database(cursor, final_data)
 
 
 
 
 
766
 
767
  conn.commit()
768
  conn.close()
769
-
770
  logging.debug(f"User with email {email} processed successfully")
771
 
772
  # Отправка данных в Google Forms
773
- send_to_google_forms(final_data, gog_url)
774
 
775
- def transform_data(user_data, mapping_template):
776
- # Трансформация данных
777
- transformed_data = {}
778
- for json_key, db_column in mapping_template.items():
779
- value = user_data.get(json_key, "")
780
- transformed_data[db_column] = str(value)
781
- return transformed_data
782
-
783
- def prepare_final_data(transformed_data, current_values):
784
- # Подготовка окончательных данных
785
- for column in ['web_st', 'ws_st']: # Пример столбцов для обработки
786
- if column in transformed_data:
787
- transformed_data[column] = handle_special_cases(column, transformed_data, current_values)
788
- return transformed_data
789
-
790
- def handle_special_cases(column, transformed_data, current_values):
791
- # Логика обработки особых случаев
792
- if column == 'web_st':
793
- return int(current_values.get(column, 0)) + 1
794
- return transformed_data[column]
795
-
796
- def update_database(cursor, final_data, email):
797
- # Обновление данных
798
- update_query = "UPDATE contacts SET "
799
- update_values = []
800
- for column, value in final_data.items():
801
- update_query += f"{column} = ?, "
802
- update_values.append(value)
803
- update_query = update_query.rstrip(", ") + " WHERE email = ?"
804
- update_values.append(email)
805
- cursor.execute(update_query, update_values)
806
-
807
- def insert_into_database(cursor, final_data):
808
- # Вставка данных
809
- columns = ', '.join(final_data.keys())
810
- placeholders = ', '.join('?' for _ in final_data)
811
- insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
812
- insert_values = list(final_data.values())
813
- cursor.execute(insert_query, insert_values)
814
 
815
 
816
 
 
747
 
748
  logging.debug(f"Processing user with email: {email}")
749
 
750
+ cursor.execute("SELECT web_st, ws_st, b_mess FROM contacts WHERE email = ?", (email,))
 
751
  user = cursor.fetchone()
752
+ logging.debug(f"User found: {user}")
753
 
754
+ current_web_st = user[0] if user else None
755
+ current_ws_st = user[1] if user else None
756
+ current_messages = user[2] if user else ""
757
+ logging.debug(f"Current web_st: {current_web_st}, current_ws_st: {current_ws_st}, current_messages: {current_messages}")
758
+
759
+ transformed_data = {}
760
+ for json_key, db_column in mapping_template.items():
761
+ value = user_data.get(json_key, "")
762
+ if isinstance(value, list):
763
+ if all(isinstance(item, str) for item in value):
764
+ transformed_data[db_column] = "; ".join(value)
765
+ else:
766
+ logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
767
+ transformed_data[db_column] = ""
768
+ else:
769
+ transformed_data[db_column] = str(value)
770
+ logging.debug(f"Transformed data: {transformed_data}")
771
+
772
+ required_fields = [
773
+ "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
774
+ "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
775
+ "shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "gc_url",
776
+ "key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
777
+ ]
778
+ for field in required_fields:
779
+ if field not in transformed_data:
780
+ transformed_data[field] = ""
781
+ logging.debug(f"Transformed data after adding required fields: {transformed_data}")
782
+
783
+ if 'phone' in user_data:
784
+ phone = user_data['phone']
785
+ if phone.startswith('+'):
786
+ phone = phone[1:]
787
+ transformed_data['phone'] = phone
788
+ logging.debug(f"Transformed data after phone processing: {transformed_data}")
789
+
790
+ # Столбцы, которые не нужно перезаписывать
791
+ no_overwrite_columns = ['ws_st', 'curator'] # Добавляйте сюда столбцы
792
+
793
+ # Проверяем наличие ws_st в базе данных и не перезаписываем его, если оно уже существует
794
+ if current_ws_st is not None and current_ws_st != "":
795
+ transformed_data['ws_st'] = current_ws_st
796
+ else:
797
+ transformed_data['ws_st'] = user_data.get('ws_st', "")
798
+
799
+ # Увеличиваем значение web_st на 1, если пользователь уже существует в базе данных
800
+ if current_web_st is not None and current_web_st != "":
801
+ transformed_data['web_st'] = int(current_web_st) + 1
802
+ else:
803
+ transformed_data['web_st'] = 1
804
+
805
+ new_messages = transformed_data.get('b_mess', "")
806
+ if current_messages:
807
+ transformed_data['b_mess'] = current_messages + "; " + new_messages
808
+ else:
809
+ transformed_data['b_mess'] = new_messages
810
+ logging.debug(f"Transformed data after message processing: {transformed_data}")
811
 
 
 
 
 
812
  if user:
813
+ update_query = "UPDATE contacts SET "
814
+ update_values = []
815
+ for column, value in transformed_data.items():
816
+ if column not in no_overwrite_columns:
817
+ update_query += f"{column} = ?, "
818
+ update_values.append(value)
819
+ update_query = update_query.rstrip(", ") + " WHERE email = ?"
820
+ update_values.append(email)
821
+ logging.debug(f"Update query: {update_query} with values: {update_values}")
822
+ cursor.execute(update_query, update_values)
823
  else:
824
+ columns = ', '.join(transformed_data.keys())
825
+ placeholders = ', '.join('?' for _ in transformed_data)
826
+ insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
827
+ insert_values = list(transformed_data.values())
828
+ logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
829
+ cursor.execute(insert_query, insert_values)
830
 
831
  conn.commit()
832
  conn.close()
 
833
  logging.debug(f"User with email {email} processed successfully")
834
 
835
  # Отправка данных в Google Forms
836
+ send_to_google_forms(transformed_data, gog_url)
837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838
 
839
 
840