DmitrMakeev commited on
Commit
2d1c81c
1 Parent(s): 3a7861c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -97
app.py CHANGED
@@ -1194,106 +1194,9 @@ def se_upl_csv():
1194
 
1195
 
1196
 
1197
- DATABASE2 = 'data_gc.db'
1198
-
1199
- def parse_csv_data(data):
1200
- parsed_data = []
1201
- for item in data:
1202
- for key, value in item.items():
1203
- headers = key.split(';')
1204
- row = value.split(';')
1205
- parsed_data.append(dict(zip(headers, row)))
1206
- return parsed_data
1207
-
1208
- def insert_data(data):
1209
- conn = sqlite3.connect(DATABASE2)
1210
- cursor = conn.cursor()
1211
-
1212
- for row in data:
1213
- # Получение текущего времени в московском часовом поясе
1214
- utc_now = datetime.utcnow()
1215
- msk_tz = pytz.timezone('Europe/Moscow')
1216
- msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
1217
- data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
1218
-
1219
- # Проверка наличия ключей перед их использованием и предоставление значений по умолчанию
1220
- name = row.get('Name', '')
1221
-
1222
- # Удаление ведущего плюсика из номера телефона, если он есть
1223
- phone = row.get('Phone', '').lstrip('+')
1224
-
1225
- email = row.get('Email', '')
1226
- vk_id = row.get('vk_id', '')
1227
- chat_id = row.get('chat_id', '')
1228
- ws_st = row.get('ws_st', '')
1229
- ws_stop = row.get('ws_stop', '')
1230
- web_st = row.get('web_st', 0)
1231
- fin_prog = row.get('fin_prog', 0)
1232
- b_city = row.get('b_city', '')
1233
- b_fin = row.get('b_fin', '')
1234
- b_ban = row.get('b_ban', '')
1235
- b_ign = row.get('b_ign', '')
1236
- b_baners = row.get('b_baners', '')
1237
- b_butt = row.get('b_butt', '')
1238
- b_mess = row.get('b_mess', '')
1239
- shop_st = row.get('shop_st', '')
1240
- curator = row.get('curator', '')
1241
- pr1 = row.get('pr1', '')
1242
- pr2 = row.get('pr2', '')
1243
- pr3 = row.get('pr3', '')
1244
- pr4 = row.get('pr4', '')
1245
- pr5 = row.get('pr5', '')
1246
- ad_url = row.get('ad_url', '')
1247
- key_pr = row.get('key_pr', '')
1248
- n_con = row.get('n_con', '')
1249
- canal = row.get('canal', '')
1250
-
1251
- # Проверка существования пользователя в базе данных по email или телефону
1252
- cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
1253
- user_exists = cursor.fetchone()
1254
-
1255
- # Если пользователь существует, пропускаем вставку
1256
- if user_exists:
1257
- print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
1258
- continue
1259
-
1260
- # Создание динамического SQL-запроса для вставки данных
1261
- columns = ['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']
1262
- values = [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]
1263
-
1264
- placeholders = ', '.join(['?' for _ in columns])
1265
- columns_str = ', '.join(columns)
1266
 
1267
- query = f'''
1268
- INSERT INTO contacts ({columns_str})
1269
- VALUES ({placeholders})
1270
- '''
1271
 
1272
- try:
1273
- cursor.execute(query, values)
1274
- except Exception as e:
1275
- print(f"Error inserting row: {row}")
1276
- print(f"Error message: {str(e)}")
1277
- conn.rollback()
1278
- raise
1279
 
1280
- conn.commit()
1281
- conn.close()
1282
- @app.route('/upload_csv', methods=['POST'])
1283
- def upload_csv():
1284
- if 'file' not in request.files:
1285
- return jsonify({"error": "No file part"}), 400
1286
- file = request.files['file']
1287
- if file.filename == '':
1288
- return jsonify({"error": "No selected file"}), 400
1289
- if file and file.filename.endswith('.csv'):
1290
- stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
1291
- csv_input = csv.DictReader(stream)
1292
- data = [row for row in csv_input]
1293
- parsed_data = parse_csv_data(data)
1294
- insert_data(parsed_data)
1295
- return jsonify({"message": "Data uploaded and inserted successfully"})
1296
- return jsonify({"error": "Invalid file format"}), 400
1297
 
1298
 
1299
 
@@ -1769,6 +1672,133 @@ def add_data_ver_cur():
1769
 
1770
 
1771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1772
 
1773
 
1774
 
 
1194
 
1195
 
1196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1197
 
 
 
 
 
1198
 
 
 
 
 
 
 
 
1199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1200
 
1201
 
1202
 
 
1672
 
1673
 
1674
 
1675
+
1676
+
1677
+
1678
+
1679
+
1680
+
1681
+
1682
+
1683
+
1684
+
1685
+
1686
+
1687
+
1688
+ DATABASE2 = 'data_gc.db'
1689
+ def verify_phone_number2(phone_number):
1690
+ current_curator_index = 0
1691
+ verifikation_start = "1" # Глобальная переменная для управления верификацией
1692
+ curator_on_off = "1" # Глобальная переменная для управления назначением куратора
1693
+ if verifikation_start == "1":
1694
+ full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
1695
+ payload = json.dumps({"phoneNumber": phone_number})
1696
+ headers = {'Content-Type': 'application/json'}
1697
+ response = requests.post(full_url_ver, headers=headers, data=payload)
1698
+ if response.status_code == 200:
1699
+ response_body = response.json()
1700
+ return response_body.get('existsWhatsapp', 'false')
1701
+ else:
1702
+ return "Error"
1703
+ else:
1704
+ return "false"
1705
+
1706
+ def insert_data2(data, template_key):
1707
+ conn = sqlite3.connect(DATABASE2)
1708
+ cursor = conn.cursor()
1709
+
1710
+ mapping_template_cur = mapp_templates.get(template_key, mt_avp)
1711
+
1712
+ for row in data:
1713
+ utc_now = datetime.utcnow()
1714
+ msk_tz = pytz.timezone('Europe/Moscow')
1715
+ msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
1716
+ data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')
1717
+
1718
+ user_data = {mapping_template_cur[key]: row.get(key, "") for key in mapping_template_cur}
1719
+
1720
+ name = user_data.get('name', '')
1721
+ phone = user_data.get('phone', '').lstrip('+')
1722
+ email = user_data.get('email', '')
1723
+
1724
+ if not name or not phone or not email:
1725
+ print(f"Missing required fields in row: {row}. Skipping insert.")
1726
+ continue
1727
+
1728
+ if curator_on_off == "1":
1729
+ user_data['curator'] = curators[current_curator_index]
1730
+ current_curator_index = (current_curator_index + 1) % len(curators)
1731
+
1732
+ if verifikation_start == "1":
1733
+ user_data['ws_st'] = verify_phone_number2(phone)
1734
+
1735
+ user_data['data_t'] = data_t
1736
+
1737
+ fields = [
1738
+ 'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
1739
+ 'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator',
1740
+ 'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t'
1741
+ ]
1742
+
1743
+ placeholders = ', '.join(['?' for _ in fields])
1744
+ columns_str = ', '.join(fields)
1745
+
1746
+ query = f'''
1747
+ INSERT INTO contacts ({columns_str})
1748
+ VALUES ({placeholders})
1749
+ '''
1750
+
1751
+ try:
1752
+ cursor.execute(query, [user_data.get(field, '') for field in fields])
1753
+ except Exception as e:
1754
+ print(f"Error inserting row: {row}")
1755
+ print(f"Error message: {str(e)}")
1756
+ conn.rollback()
1757
+ raise
1758
+
1759
+ conn.commit()
1760
+ conn.close()
1761
+
1762
+ @app.route('/upload_csv', methods=['POST'])
1763
+ def upload_csv():
1764
+ global verifikation_start, curator_on_off
1765
+
1766
+ verifikation_start = request.form.get('verifikation_start', '0')
1767
+ curator_on_off = request.form.get('curator_on_off', '0')
1768
+ template_key = request.form.get('template_key', 'avp')
1769
+
1770
+ if 'file' not in request.files:
1771
+ return jsonify({"error": "No file part"}), 400
1772
+ file = request.files['file']
1773
+ if file.filename == '':
1774
+ return jsonify({"error": "No selected file"}), 400
1775
+ if file and file.filename.endswith('.csv'):
1776
+ stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
1777
+ csv_input = csv.DictReader(stream)
1778
+ data = [row for row in csv_input]
1779
+ insert_data2(data, template_key)
1780
+ return jsonify({"message": "Data uploaded and inserted successfully"})
1781
+ return jsonify({"error": "Invalid file format"}), 400
1782
+
1783
+
1784
+
1785
+
1786
+
1787
+
1788
+
1789
+
1790
+
1791
+
1792
+
1793
+
1794
+
1795
+
1796
+
1797
+
1798
+
1799
+
1800
+
1801
+
1802
 
1803
 
1804