You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
421 lines
19 KiB
421 lines
19 KiB
from flask import abort, request, render_template, url_for, jsonify |
|
from webApp import * |
|
from webApp import webApp |
|
import gspread |
|
from oauth2client.service_account import ServiceAccountCredentials |
|
import json |
|
import datetime |
|
from config import config |
|
import requests |
|
from datetime import datetime |
|
|
|
# Авторизация Google API |
|
def authorize_google(): |
|
# google_json = {} |
|
# for key in config["GOOGLE"].keys(): |
|
# google_json[key] = config["GOOGLE"][key] |
|
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] |
|
creds = ServiceAccountCredentials.from_json_keyfile_name("botforclinic-436512-0c117dd103a8.json", scope) |
|
# creds = ServiceAccountCredentials.from_json_keyfile_dict(google_json, scope) |
|
client = gspread.authorize(creds) |
|
return client |
|
|
|
def find_patients(data): |
|
""" |
|
Поиск пациента в таблице по данным. |
|
""" |
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
records = sheet.get_all_records() # Получаем все строки таблицы |
|
print(data) |
|
for i, record in enumerate(records, start=2): # Нумерация строк Google Таблицы начинается с 2 |
|
try: |
|
print(str(record.get("Telegram ID", "")).strip(), str(record.get("ФИО", "")).strip().lower(), str(record.get("Дата рождения", "")).strip(), str(record.get("Номер телефона", "")).strip()) |
|
print(str(data.get("user_id", "")).strip(), str(data.get("fio", "")).strip().lower(), str(data.get("dob", "")).strip(), str(data.get("tel", "")).strip()) |
|
if ( |
|
str(record.get("Telegram ID", "")).strip() == str(data.get("user_id", "")).strip() and |
|
str(record.get("ФИО", "")).strip().lower() == str(data.get("fio", "")).strip().lower() and |
|
str(record.get("Дата рождения", "")).strip() == str(data.get("dob", "")).strip() and |
|
str(record.get("Номер телефона", "")).strip() == str(data.get("tel", "")).strip() |
|
): |
|
return i, record # Возвращаем номер строки и запись |
|
except Exception as e: |
|
print(f"Ошибка при сравнении записи: {e}") |
|
continue |
|
|
|
return None, None |
|
|
|
|
|
@webApp.route('/form_submit', methods=['POST']) |
|
def form_submit(): |
|
""" |
|
Обработка данных формы и обновление записи в Google Таблице. |
|
""" |
|
try: |
|
data = json.loads(request.data) |
|
data['current_time'] = datetime.datetime.now().strftime("%d.%m.%Y, %H:%M") |
|
|
|
# Поиск пациента |
|
row_number, patient_row = find_patients(data) |
|
if not patient_row: |
|
return jsonify({'success': False, 'error': "Пациент не найден"}) |
|
|
|
# Проверка кода верификации |
|
expected_code = str(patient_row.get("Верификация", "")).strip() |
|
received_code = str(data.get("verification_code", "")).strip() |
|
if expected_code != received_code: |
|
return jsonify({'success': False, 'error': "Код верификации не совпадает"}) |
|
|
|
# Обновление записи в таблице |
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
|
|
# Определяем динамический столбец по заголовкам |
|
headers = sheet.row_values(1) |
|
verification_col = headers.index("Верификация") + 1 # Столбцы нумеруются с 1 |
|
sheet.update_cell(row_number, verification_col, "Пройдена") |
|
|
|
return jsonify({'success': True}) |
|
|
|
except KeyError as e: |
|
print(f"Ключ отсутствует в данных: {e}") |
|
return jsonify({'success': False, 'error': f"Некорректные данные: {e}"}) |
|
|
|
except Exception as e: |
|
print(f"Ошибка при обработке формы: {e}") |
|
return jsonify({'success': False, 'error': str(e)}) |
|
|
|
|
|
|
|
|
|
@webApp.route('/tel_verification', methods=['POST']) |
|
def send_registration_request(): |
|
raw_data = json.loads(request.data) |
|
""" |
|
Блок записи в Полимед |
|
""" |
|
try: |
|
HEADER = { |
|
"Content-Type": "application/json" |
|
} |
|
|
|
# Разделение ФИО на части |
|
fio = raw_data.get("fio", "") |
|
parts = fio.split(" ") |
|
if len(parts) < 3: |
|
return jsonify({'success': False, "error": "ФИО должно содержать 3 слова"}) |
|
|
|
first_name = parts[1] |
|
middle_name = " ".join(parts[2:]) |
|
last_name = parts[0] |
|
|
|
# Обработка номера телефона |
|
raw_phone = raw_data.get("tel", "") |
|
formatted_phone = ''.join(filter(str.isdigit, raw_phone)) |
|
if formatted_phone.startswith("7"): |
|
formatted_phone = formatted_phone |
|
|
|
# Обработка даты рождения |
|
dob = raw_data.get("dob", "") |
|
if not dob: |
|
return jsonify({'success': False, "error": "Дата рождения отсутствует"}) |
|
birth_year = dob.split("-")[0] # Предполагается формат "YYYY-MM-DD" |
|
|
|
# Данные для отправки в сервер Полимед |
|
data = { |
|
"telegram_id": raw_data.get("user_id"), |
|
"first_name": first_name, |
|
"second_name": middle_name, |
|
"last_name": last_name, |
|
"mobile_phone": formatted_phone, |
|
"birthday": birth_year |
|
} |
|
|
|
print("Отправляемые данные на сервер:", data) |
|
response = requests.post("http://192.168.1.10:8080/AppFindPac", headers=HEADER, json=data) |
|
|
|
if response.status_code == 200: |
|
result = response.json() |
|
print("Результат JSON:", result) |
|
if result.get('result', None): |
|
if result.get('result', None) == 'OK': |
|
# return jsonify({'success': True, 'message': "Скоро вам позвонят!"}) |
|
pass |
|
else: |
|
return jsonify({'success': False, "error": "Пользователь не найден среди пациентов клиники. <br> Если у Вас возникли вопросы по регистрации, Вы можете связаться с нами в рабочие часы по телефону: +7 (342)207-03-03."}) |
|
else: |
|
return jsonify({'success': False, "error": "Ошибка формата запроса"}) |
|
else: |
|
print(f"Ошибка при отправке данных. Статус-код: {response.status_code}") |
|
return jsonify({'success': False, "error": "Ошибка отправки данных в Полимед"}) |
|
|
|
except Exception as e: |
|
print(f"Ошибка обработки данных для Полимед: {e}") |
|
return jsonify({'success': False, "error": "Ошибка обработки данных для Полимед"}) |
|
""" |
|
Блок верификации через SMS |
|
""" |
|
try: |
|
url = "https://sms.ru/code/call" |
|
api_key = "2ED72E61-76C8-5637-3587-2792D47B698C" |
|
|
|
# Отправка запроса на вызов с кодом верификации |
|
response = requests.post(url, data={"phone": formatted_phone, "api_id": api_key}) |
|
print(response) |
|
json_data = response.json() |
|
|
|
verification_code = None |
|
current_time = datetime.datetime.now().strftime("%d.%m.%Y, %H:%M") |
|
|
|
# Авторизация и доступ к таблице |
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
|
|
# Проверка успешного получения кода |
|
if json_data and json_data["status"] == "OK": |
|
verification_code = json_data.get("code") |
|
|
|
# Поиск пациента |
|
row_number, patient_row = find_patients(raw_data) |
|
if patient_row: |
|
# Обновление записи в таблице |
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
|
|
# Определяем динамический столбец по заголовкам |
|
headers = sheet.row_values(1) |
|
verification_col = headers.index("Верификация") + 1 # Столбцы нумеруются с 1 |
|
sheet.update_cell(row_number, verification_col, verification_code) |
|
|
|
else: |
|
# Записываем данные и код верификации в таблицу |
|
sheet.append_row([ |
|
fio, |
|
raw_phone, |
|
dob, |
|
raw_data.get("user_id"), # Telegram ID пользователя |
|
current_time, # Время отправки данных |
|
verification_code # Код верификации |
|
]) |
|
print(f"Код верификации, отправленный пользователю: {verification_code}") |
|
return jsonify({'success': True}) |
|
else: |
|
print("Звонок не может быть выполнен.") |
|
print("Текст ошибки:", json_data.get("status_text")) |
|
return jsonify({'success': False, "error": "Если звонок не поступил, это может быть связано с временными работами на сервере. <br> Пожалуйста, попробуйте зарегистрироваться позже!"}) |
|
|
|
except Exception as e: |
|
print(f"Ошибка при обработке SMS верификации: {e}") |
|
return jsonify({'success': False, "error": "Если звонок не поступил, это может быть связано с временными работами на сервере. <br> Пожалуйста, попробуйте зарегистрироваться позже!"}) |
|
|
|
|
|
|
|
|
|
@webApp.route('/request_patient', methods=['POST']) |
|
def request_patient_information(): |
|
try: |
|
|
|
|
|
|
|
data = request.get_json() |
|
print(data) |
|
user_id = data.get('user_id') |
|
# taxpayer_fio = data.get('taxpayer_fio') |
|
patient_fio = data.get('patient_fio') |
|
|
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
records = sheet.get_all_values() |
|
|
|
# Получаем список всех людей с таким user_id |
|
birthday_users = [datetime.strptime(row[2], "%Y-%m-%d").strftime("%Y-%m-%dT00:00:00.000Z") for row in records[1:] if row[0] == patient_fio] |
|
print(birthday_users) |
|
|
|
|
|
if not user_id or not patient_fio: #or not taxpayer_fio |
|
return "Ошибка: Не выбраны налогоплательщик и пациент", 400 |
|
|
|
payload = { |
|
"telegram_id": int(user_id), |
|
"first_name": patient_fio.split()[1] if len(patient_fio.split()) > 1 else "", |
|
"second_name": patient_fio.split()[2] if len(patient_fio.split()) > 2 else "", |
|
"last_name": patient_fio.split()[0], |
|
"pac_poluchat": "True", |
|
"poluchat_status": "", |
|
"birthday": birthday_users[0] if birthday_users else None |
|
} |
|
print(payload) |
|
headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"} |
|
url = "http://192.168.1.10:8081/AppZaprSvedPac" |
|
response = requests.post(url, json=payload, headers=headers) |
|
|
|
if response.status_code == 200: |
|
print("Ответ:", response.text) |
|
result = response.json |
|
print(result) |
|
try: |
|
result = response.json() |
|
except: |
|
result = {} |
|
|
|
js_formatted_birthdate = ( |
|
datetime.strptime(result.get("pct_birthday", ""), "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d") |
|
if result.get("pct_birthday") else "") |
|
|
|
formatted_birthdate = ( |
|
datetime.strptime(result.get("pct_birthday", ""), "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%d.%m.%Y") |
|
if result.get("pct_birthday") else "") |
|
|
|
formatted_passport_date = ( |
|
datetime.strptime(result.get("pct_doc_date", ""), "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%d.%m.%Y") |
|
if result.get("pct_doc_date") else "") |
|
|
|
return jsonify( |
|
user_id=user_id, |
|
fio=patient_fio, |
|
server_data=result, |
|
formatted_birthdate=formatted_birthdate, |
|
js_formatted_birthdate=js_formatted_birthdate, |
|
formatted_passport_date=formatted_passport_date, |
|
pct_doc_ser=result.get('pct_doc_ser', ''), |
|
pct_doc_nom=result.get('pct_doc_nom', ''), |
|
pct_inn=result.get('pct_inn', ''), |
|
pct_email=result.get('pct_email', ''), |
|
pct_doc_org_kod=result.get('pct_doc_org_kod', ''), |
|
pct_doc_org_name=result.get('pct_doc_org_name', ''), |
|
success = True |
|
) |
|
else: |
|
return f"Ошибка: {response.status_code} - {response.text}", 500 |
|
except Exception as e: |
|
return f"Произошла ошибка: {e}", 500 |
|
|
|
|
|
|
|
@webApp.route('/sending_patient', methods=['POST']) |
|
def sending_patient_data(): |
|
try: |
|
raw_data = json.loads(request.data) |
|
|
|
print(raw_data) |
|
|
|
# Разделение ФИО |
|
fio = raw_data.get("fio", "") |
|
parts = fio.split(" ") |
|
if len(parts) < 3: |
|
return jsonify({'success': False, "error": "ФИО должно содержать 3 слова"}), 400 # Код 400 - ошибка клиента |
|
|
|
first_name = parts[1] |
|
middle_name = " ".join(parts[2:]) |
|
last_name = parts[0] |
|
passport = raw_data.get("passport", "") |
|
part = passport.split(" ") |
|
pct_doc_ser = part[0] |
|
plc_doc_nom = part[1] |
|
# Обработка даты рождения |
|
dob = raw_data.get("dob", "") |
|
if dob: |
|
# Преобразуем формат из 2016-09-25 в datetime объект |
|
date_obje = datetime.strptime(dob, "%Y-%m-%d") |
|
|
|
# Преобразуем datetime объект в строку в формате ISO 8601 |
|
pct_birthday = date_obje.strftime("%Y-%m-%dT%H:%M:%S.000Z") |
|
pct_inn = raw_data.get("inn", "") |
|
formatted_date = raw_data.get("passport_date", "") |
|
# Преобразуем строку в объект datetime |
|
if formatted_date: |
|
# Преобразуем формат из 2016-09-25 в datetime объект |
|
date_obj = datetime.strptime(formatted_date, "%Y-%m-%d") |
|
|
|
# Преобразуем datetime объект в строку в формате ISO 8601 |
|
plc_doc_date = date_obj.strftime("%Y-%m-%dT%H:%M:%S.000Z") |
|
plc_doc_org_name = raw_data.get("passport_issued_by", "") |
|
plc_doc_org_kod = raw_data.get("postal_code", "") |
|
pct_email = raw_data.get("email", "") |
|
# Извлекаем список выбранных годов |
|
selected_years = raw_data.get('selected_years', []) |
|
|
|
if selected_years: |
|
# Преобразуем элементы в целые числа |
|
selected_years = list(map(int, selected_years)) |
|
|
|
# Находим минимальный и максимальный год |
|
year_beg_spr = min(selected_years) |
|
year_end_spr = max(selected_years) |
|
|
|
# Если выбран только один год, то обе переменные будут одинаковыми |
|
if year_beg_spr == year_end_spr: |
|
year_end_spr = year_beg_spr |
|
|
|
# Теперь у нас есть year_beg_spr и year_end_spr |
|
print("Минимальный год:", year_beg_spr) |
|
print("Максимальный год:", year_end_spr) |
|
|
|
|
|
# Формируем данные для отправки |
|
data1 = { |
|
"telegram_id": raw_data.get("user_id"), |
|
"pct_first_name": first_name, |
|
"pct_second_name": middle_name, |
|
"pct_last_name": last_name, |
|
"pct_birthday": pct_birthday, |
|
"pct_inn": pct_inn, |
|
"pct_doc_type": "Паспорт", |
|
"pct_doc_ind": 1, |
|
"pct_doc_ser": pct_doc_ser, |
|
"pct_doc_nom": plc_doc_nom, |
|
"pct_doc_date": plc_doc_date, |
|
"pct_doc_org_name": plc_doc_org_name, |
|
"pct_doc_org_kod": plc_doc_org_kod, |
|
"pac_poluchat": "True", |
|
"pct_email": pct_email, |
|
"year_beg_spr": year_beg_spr, |
|
"year_end_spr": year_end_spr |
|
} |
|
|
|
print("Отправляемые данные:", data1) |
|
|
|
# Успешный ответ |
|
HEADER = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"} |
|
try: |
|
response = requests.post("http://192.168.1.10:8081/AppSaveSvedPac", headers=HEADER, json=data1, timeout=5) |
|
print("Ответ сервера:", response.text) # вдруг сервер всё же что-то вернёт |
|
if response.status_code == 200: |
|
return jsonify({'success': True}) |
|
else: |
|
return jsonify({'success': False, 'error': f'Сервер вернул статус {response.status_code}'}), 500 |
|
|
|
except requests.exceptions.RequestException as e: |
|
return jsonify({'success': False, 'error': f'Ошибка соединения: {str(e)}'}), 500 |
|
|
|
except Exception as e: |
|
print(f"Ошибка: {e}") |
|
return jsonify({'success': False, 'error': str(e)}), 500 |
|
|
|
|
|
|
|
|
|
|
|
@webApp.route('/') |
|
def main_page_2_0(): |
|
return render_template('2.0/main_page.pug', user_id=request.args.get('user_id', None)) |
|
|
|
|
|
|
|
@webApp.route('/fns') |
|
def main_page_2_0_fns(): |
|
try: |
|
user_id = request.args.get('user_id') |
|
if not user_id: |
|
return "Ошибка: не передан user_id", 400 |
|
|
|
sheet = authorize_google().open("Пациенты клиники").sheet1 |
|
records = sheet.get_all_values() |
|
|
|
# Получаем список всех людей с таким user_id |
|
matching_users = [row[0] for row in records[1:] if row[3] == user_id] |
|
matching_users = sum(matching_users, []) if any(isinstance(i, list) for i in matching_users) else matching_users |
|
|
|
print(matching_users) |
|
|
|
if not matching_users: |
|
return "Ошибка: пользователь не найден", 404 |
|
|
|
return render_template('2.0/main_page_fns.pug', user_id=user_id, users=matching_users) |
|
except Exception as e: |
|
return f"Произошла ошибка: {e}", 500
|
|
|