DmitrMakeev commited on
Commit
53aaeaa
1 Parent(s): e0ca124

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -131
app.py CHANGED
@@ -1627,155 +1627,78 @@ def gc_forms():
1627
 
1628
 
1629
 
1630
- def add_or_update_contact(db_name, contact_data):
1631
- conn = sqlite3.connect(db_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1632
  cursor = conn.cursor()
1633
-
1634
  email = contact_data.get('email')
1635
  if not email:
1636
  logging.error(f"Missing email in contact data: {contact_data}")
1637
  return
1638
-
1639
  cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
1640
  contact = cursor.fetchone()
1641
-
1642
- transformed_data = {}
1643
- for field in ["name", "phone", "email", "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog", "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess", "shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url", "key_pr", "n_con", "canal", "data_t"]:
1644
- value = contact_data.get(field, "")
1645
- if isinstance(value, list) or isinstance(value, dict):
1646
- transformed_data[field] = json.dumps(value)
1647
- else:
1648
- transformed_data[field] = str(value)
1649
 
1650
  if contact:
1651
- update_query = """
1652
- UPDATE contacts SET
1653
- name = ?, phone = ?, email = ?, vk_id = ?, chat_id = ?, ws_st = ?, ws_stop = ?,
1654
- web_st = ?, fin_prog = ?, b_city = ?, b_fin = ?, b_ban = ?, b_ign = ?, b_baners = ?,
1655
- b_butt = ?, b_mess = ?, shop_st = ?, curator = ?, pr1 = ?, pr2 = ?, pr3 = ?, pr4 = ?,
1656
- pr5 = ?, ad_url = ?, key_pr = ?, n_con = ?, canal = ?, data_t = ?
1657
- WHERE id = ?
1658
- """
1659
- cursor.execute(update_query, (
1660
- transformed_data["name"], transformed_data["phone"], transformed_data["email"], transformed_data["vk_id"], transformed_data["chat_id"],
1661
- transformed_data["ws_st"], transformed_data["ws_stop"], transformed_data["web_st"], transformed_data["fin_prog"], transformed_data["b_city"],
1662
- transformed_data["b_fin"], transformed_data["b_ban"], transformed_data["b_ign"], transformed_data["b_baners"], transformed_data["b_butt"],
1663
- transformed_data["b_mess"], transformed_data["shop_st"], transformed_data["curator"], transformed_data["pr1"], transformed_data["pr2"],
1664
- transformed_data["pr3"], transformed_data["pr4"], transformed_data["pr5"], transformed_data["ad_url"], transformed_data["key_pr"],
1665
- transformed_data["n_con"], transformed_data["canal"], transformed_data["data_t"], contact[0]
1666
- ))
1667
  else:
1668
- insert_query = """
1669
- INSERT INTO contacts (name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, b_city, b_fin,
1670
- b_ban, b_ign, b_baners, b_butt, b_mess, shop_st, curator, pr1, pr2, pr3, pr4, pr5, ad_url,
1671
- key_pr, n_con, canal, data_t)
1672
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1673
- """
1674
- cursor.execute(insert_query, (
1675
- transformed_data["name"], transformed_data["phone"], transformed_data["email"], transformed_data["vk_id"], transformed_data["chat_id"],
1676
- transformed_data["ws_st"], transformed_data["ws_stop"], transformed_data["web_st"], transformed_data["fin_prog"], transformed_data["b_city"],
1677
- transformed_data["b_fin"], transformed_data["b_ban"], transformed_data["b_ign"], transformed_data["b_baners"], transformed_data["b_butt"],
1678
- transformed_data["b_mess"], transformed_data["shop_st"], transformed_data["curator"], transformed_data["pr1"], transformed_data["pr2"],
1679
- transformed_data["pr3"], transformed_data["pr4"], transformed_data["pr5"], transformed_data["ad_url"], transformed_data["key_pr"],
1680
- transformed_data["n_con"], transformed_data["canal"], transformed_data["data_t"]
1681
- ))
1682
-
1683
  conn.commit()
1684
  conn.close()
1685
 
1686
-
1687
  @app.route('/add_data_ver', methods=['GET'])
1688
  def add_data_ver():
1689
- try:
1690
- api_sys_control = request.args.get('api_sys')
1691
-
1692
- if api_sys_control != api_key_sys:
1693
- return "err api key", 200
1694
-
1695
- name = request.args.get('name')
1696
- phone = request.args.get('phone')
1697
- email = request.args.get('email')
1698
- pr1 = request.args.get('pr1', '')
1699
- pr2 = request.args.get('pr2', '')
1700
- pr3 = request.args.get('pr3', '')
1701
- pr4 = request.args.get('pr4', '')
1702
- pr5 = request.args.get('pr5', '')
1703
- canal = request.args.get('canal', '')
1704
-
1705
- if not name or not phone or not email:
1706
- return "Parameters 'name', 'phone', and 'email' are required.", 400
1707
-
1708
- # Clean up phone number by removing any leading plus sign
1709
- if phone.startswith('+'):
1710
- phone = phone[1:]
1711
-
1712
- ws_statys = verify_phone_number(phone)
1713
-
1714
- utc_now = datetime.utcnow()
1715
- msk_tz = pytz.timezone('Europe/Moscow')
1716
- msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
1717
- data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
1718
-
1719
- user_data = {
1720
- "name": name,
1721
- "phone": phone,
1722
- "email": email,
1723
- "ws_st": ws_statys,
1724
- "pr1": pr1,
1725
- "pr2": pr2,
1726
- "pr3": pr3,
1727
- "pr4": pr4,
1728
- "pr5": pr5,
1729
- "canal": canal,
1730
- "data_t": data_t,
1731
- "vk_id": "",
1732
- "chat_id": "",
1733
- "ws_stop": "",
1734
- "web_st": 0,
1735
- "fin_prog": 0,
1736
- "b_city": "",
1737
- "b_fin": "",
1738
- "b_ban": "",
1739
- "b_ign": "",
1740
- "b_baners": "",
1741
- "b_butt": "",
1742
- "b_mess": "",
1743
- "shop_st": "",
1744
- "curator": "",
1745
- "ad_url": "",
1746
- "key_pr": "",
1747
- "n_con": ""
1748
- }
1749
-
1750
- for db_name in DATABASES:
1751
- conn = sqlite3.connect(db_name)
1752
- cursor = conn.cursor()
1753
- cursor.execute('SELECT * FROM contacts WHERE phone = ? OR email = ?', (phone, email))
1754
- existing_contact = cursor.fetchone()
1755
-
1756
- if existing_contact:
1757
- update_query = "UPDATE contacts SET "
1758
- update_values = []
1759
- for column, value in user_data.items():
1760
- update_query += f"{column} = ?, "
1761
- update_values.append(value)
1762
- update_query = update_query.rstrip(", ") + " WHERE phone = ? OR email = ?"
1763
- update_values.extend([phone, email])
1764
- cursor.execute(update_query, update_values)
1765
- else:
1766
- columns = ', '.join(user_data.keys())
1767
- placeholders = ', '.join('?' for _ in user_data)
1768
- insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
1769
- insert_values = list(user_data.values())
1770
- cursor.execute(insert_query, insert_values)
1771
 
1772
- conn.commit()
1773
- conn.close()
 
1774
 
1775
- return f"Contact updated/added: {name} - {phone} - {email}", 200
 
 
1776
  except Exception as e:
1777
- print(f"Error adding/updating contact: {e}")
1778
- return "Internal Server Error", 500
1779
 
1780
 
1781
 
 
1627
 
1628
 
1629
 
1630
+ # Функция для верификации номера телефона
1631
+ def verify_phone_number(phone_number):
1632
+
1633
+
1634
+ if verifikation_start == "1":
1635
+
1636
+ full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
1637
+
1638
+ payload = json.dumps({
1639
+ "phoneNumber": phone_number
1640
+ })
1641
+ headers = {
1642
+ 'Content-Type': 'application/json'
1643
+ }
1644
+
1645
+ response = requests.post(full_url_ver, headers=headers, data=payload)
1646
+
1647
+ if response.status_code == 200:
1648
+ result = response.json()
1649
+ return result # Вернуть весь ответ, как есть
1650
+ else:
1651
+ return {"existsWhatsapp": False}
1652
+ else:
1653
+ return {"existsWhatsapp": False}
1654
+
1655
+
1656
+ # Функция для добавления или обновления контакта в базе данных
1657
+ def add_or_update_contact(contact_data):
1658
+ conn = sqlite3.connect(DATABASE_NAME)
1659
  cursor = conn.cursor()
1660
+
1661
  email = contact_data.get('email')
1662
  if not email:
1663
  logging.error(f"Missing email in contact data: {contact_data}")
1664
  return
1665
+
1666
  cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
1667
  contact = cursor.fetchone()
1668
+
1669
+ fields = ["name", "phone", "email", "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog", "b_city",
1670
+ "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess", "shop_st", "curator", "pr1", "pr2",
1671
+ "pr3", "pr4", "pr5", "ad_url", "key_pr", "n_con", "canal", "data_t"]
1672
+ transformed_data = {field: contact_data.get(field, "") for field in fields}
 
 
 
1673
 
1674
  if contact:
1675
+ update_query = "UPDATE contacts SET " + ", ".join([f"{field} = ?" for field in fields]) + " WHERE id = ?"
1676
+ cursor.execute(update_query, (*transformed_data.values(), contact[0]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1677
  else:
1678
+ insert_query = "INSERT INTO contacts (" + ", ".join(fields) + ") VALUES (" + ", ".join(["?" for _ in fields]) + ")"
1679
+ cursor.execute(insert_query, tuple(transformed_data.values()))
1680
+
 
 
 
 
 
 
 
 
 
 
 
 
1681
  conn.commit()
1682
  conn.close()
1683
 
 
1684
  @app.route('/add_data_ver', methods=['GET'])
1685
  def add_data_ver():
1686
+ contact_data = {
1687
+ 'name': request.args.get('name'),
1688
+ 'phone': request.args.get('phone'),
1689
+ 'email': request.args.get('email')
1690
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1691
 
1692
+ phone_verification_response = verify_phone_number(contact_data['phone'])
1693
+ if phone_verification_response is not None:
1694
+ contact_data['phone_verification'] = phone_verification_response # Сохраняем полный ответ в данных контакта
1695
 
1696
+ try:
1697
+ add_or_update_contact(contact_data)
1698
+ return jsonify({'status': 'success'})
1699
  except Exception as e:
1700
+ logging.error(f"Error adding/updating contact: {e}")
1701
+ return jsonify({'status': 'error', 'message': str(e)}), 500
1702
 
1703
 
1704