DmitrMakeev commited on
Commit
0465507
·
verified ·
1 Parent(s): f268662

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -77
app.py CHANGED
@@ -747,95 +747,71 @@ 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
  cursor.execute("SELECT * FROM contacts WHERE email = ?", (email,))
751
  user = cursor.fetchone()
752
- logging.debug(f"User found: {user}")
753
 
754
- if user:
755
- # Get current values from the database
756
- current_values = dict(zip([col[0] for col in cursor.description], user))
757
- else:
758
- current_values = {}
759
 
760
- transformed_data = {}
761
- for json_key, db_column in mapping_template.items():
762
- value = user_data.get(json_key, "")
763
- if isinstance(value, list):
764
- if all(isinstance(item, str) for item in value):
765
- transformed_data[db_column] = "; ".join(value)
766
- else:
767
- logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
768
- transformed_data[db_column] = ""
769
- else:
770
- transformed_data[db_column] = str(value)
771
-
772
- logging.debug(f"Transformed data: {transformed_data}")
773
-
774
- # Ensure required fields are present
775
- required_fields = [
776
- "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
777
- "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
778
- "shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "gc_url",
779
- "key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
780
- ]
781
- for field in required_fields:
782
- if field not in transformed_data:
783
- transformed_data[field] = ""
784
- logging.debug(f"Transformed data after adding required fields: {transformed_data}")
785
-
786
- # Handle phone formatting
787
- if 'phone' in user_data:
788
- phone = user_data['phone']
789
- if phone.startswith('+'):
790
- phone = phone[1:]
791
- transformed_data['phone'] = phone
792
- logging.debug(f"Transformed data after phone processing: {transformed_data}")
793
-
794
- # Update or set the `ws_st` value, but do not update it if it exists
795
- transformed_data['ws_st'] = current_values.get('ws_st', "")
796
-
797
- # Increment `web_st` value
798
- if current_values.get('web_st'):
799
- transformed_data['web_st'] = int(current_values['web_st']) + 1
800
- else:
801
- transformed_data['web_st'] = 1
802
-
803
- # Update `b_mess` field
804
- new_messages = transformed_data.get('b_mess', "")
805
- if current_values.get('b_mess'):
806
- transformed_data['b_mess'] = current_values['b_mess'] + "; " + new_messages
807
- else:
808
- transformed_data['b_mess'] = new_messages
809
-
810
- # Prepare SQL statements
811
  if user:
812
- update_query = "UPDATE contacts SET "
813
- update_values = []
814
- columns_to_update = []
815
- for column, value in transformed_data.items():
816
- if column not in ['curator', 'ws_st'] and value != current_values.get(column, ""): # Exclude `curator` and `ws_st`, and only update if value has changed
817
- update_query += f"{column} = ?, "
818
- update_values.append(value)
819
- columns_to_update.append(column)
820
- update_query = update_query.rstrip(", ") + " WHERE email = ?"
821
- update_values.append(email)
822
- logging.debug(f"Columns to be updated: {columns_to_update}")
823
- logging.debug(f"Update query: {update_query} with values: {update_values}")
824
- cursor.execute(update_query, update_values)
825
  else:
826
- columns = ', '.join(transformed_data.keys())
827
- placeholders = ', '.join('?' for _ in transformed_data)
828
- insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
829
- insert_values = list(transformed_data.values())
830
- logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
831
- cursor.execute(insert_query, insert_values)
832
 
833
  conn.commit()
834
  conn.close()
 
835
  logging.debug(f"User with email {email} processed successfully")
836
 
837
  # Отправка данных в Google Forms
838
- send_to_google_forms(transformed_data, gog_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
839
 
840
 
841
 
 
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
 
817