diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/misc.xml b/.idea/misc.xml index 5179ecd..ddc90b5 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,7 +1,7 @@ - - + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 83ad605..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/tgflaskform.iml b/.idea/tgflaskform.iml index 922d67e..ec63674 100644 --- a/.idea/tgflaskform.iml +++ b/.idea/tgflaskform.iml @@ -1,10 +1,7 @@ - - - - - - - + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 8306744..35eb1dd 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,6 +2,5 @@ - \ No newline at end of file diff --git a/config.ini b/config.ini index 75f4e0c..c14f1ed 100644 --- a/config.ini +++ b/config.ini @@ -1,5 +1,5 @@ [WEB_APP] -PORT = 8083 +PORT = 3103 template_folder = C:\Users\ilyac\PycharmProjects\tgFlaskFormPolimed\webApp\templates environment = test [GOOGLE] diff --git a/webApp/interfaces/pagesController.py b/webApp/interfaces/pagesController.py index 9fb4caa..d3ef8fe 100644 --- a/webApp/interfaces/pagesController.py +++ b/webApp/interfaces/pagesController.py @@ -7,7 +7,7 @@ import json import datetime from config import config import requests - +from datetime import datetime # Авторизация Google API def authorize_google(): @@ -206,6 +206,216 @@ def send_registration_request(): + +@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 diff --git a/webApp/templates/2.0/main_page.pug b/webApp/templates/2.0/main_page.pug index c6607a3..5939787 100644 --- a/webApp/templates/2.0/main_page.pug +++ b/webApp/templates/2.0/main_page.pug @@ -30,7 +30,7 @@ script(type="text/javascript", src="/js/2.0.dashboard.js?q="~randomString()) label.form-label.m-0(for="tel")="Телефон" .row.m-0.p-0.justify-content-between .col-auto.m-0.p-0(style="min-width: 85%;") - input.form-control.tg_input#tel(type="text") + input.form-control.tg_input#tel(type="tel") .col-auto.m-0.p-0 button.btn.btn-danger#clear_tel span.x-icn @@ -46,7 +46,7 @@ script(type="text/javascript", src="/js/2.0.dashboard.js?q="~randomString()) small="(Пожалуйста, проверьте формат ввода)" .my-3.mx-4.primary-field - button.btn.btn-success.float-end.mb-3#form_submit + button.btn.btn-success.float-end.mb-3#form_submit(type="submit") span.spinner-border.spinner-border-sm.me-1.d-none(role="status" aria-hidden="true") span="Подтвердить" @@ -58,4 +58,7 @@ script(type="text/javascript", src="/js/2.0.dashboard.js?q="~randomString()) .my-3.mx-4.primary-field.success_window(style="display: none;") h3="Отлично!" - p="Регистрация завершена. Перейдите в Telegram, чтобы продолжить." \ No newline at end of file + p="Регистрация завершена. Перейдите в Telegram, чтобы продолжить." + + + diff --git a/webApp/templates/2.0/main_page_fns.pug b/webApp/templates/2.0/main_page_fns.pug new file mode 100644 index 0000000..4263151 --- /dev/null +++ b/webApp/templates/2.0/main_page_fns.pug @@ -0,0 +1,102 @@ +include 2.0/application + + + + +link(rel="stylesheet" href="/css/1_model_app.css?q="~randomString()) +link(rel="stylesheet" href="/css/1_model_icons.css?q="~randomString()) +script(type="text/javascript", src="/js/UFMS.js?q="~randomString()) +script(type="text/javascript", src="/js/2.0.dashboard.fns.js?q="~randomString()) + +.enterblock.custom-font.py-5 + .row.mx-auto(style='max-width: 448px; vertical-align: middle; padding-bottom: 120%;') + .col-12.my-md-auto.p-0.card.shadow.rounded-3(style='min-height: 500px;') + .card-body.px-0.pb-0 + h5.mx-4.fw-bold Заказать справку ФНС + input.tg_input#user_id(type="hidden", value=user_id) + + //-.my-3.mx-4.success-field.primary-field + label.form-label.m-0(for="taxpayer_fio") Выберите налогоплательщика + select.form-control.tg_input#taxpayer_fio(name="taxpayer_fio" required) + option(value="") -- Выберите налогоплательщика -- + each user in users + option(value=user) #{user} + + .my-3.mx-4.success-field.primary-field + label.form-label.m-0(for="patient_fio") Выберите пациента, на данный момент можно заказать справку только для налогоплательщика + select.form-control.tg_input#patient_fio(name="patient_fio" required) + option(value="") Выберите пациента + each user in users + option(value=user) #{user} + + .my-3.mx-4.primary-field + button.btn.btn-success.float-end.mb-3#form_submit(type="submit") + span.spinner-border.spinner-border-sm.me-1.d-none(role="status" aria-hidden="true") + span Отправить + + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="fio")='Фамилия Имя Отчество' + input.form-control.tg_input#fio(type="text" name="fio") + small="(Пожалуйста, проверьте правильность данных)" + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="birthdate")='Дата рождения' + input.form-control.tg_input#dob(type="date") + small="(Пожалуйста, проверьте правильность данных)" + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="passport")='Серия и номер паспорта' + input.form-control.tg_input#passport + small="(Пожалуйста, проверьте правильность данных)" + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="passport_date")='Дата выдачи паспорта' + input.form-control.tg_input#passport_date(type="date") + small="(Пожалуйста, проверьте правильность данных)" + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="postal_code")='Код подразделения' + input.form-control.tg_input#postal_code + small="(Пожалуйста, проверьте правильность данных)" + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="passport_issued_by")='Кем выдан паспорт' + select.form-select.tg_input#passport_issued_by(style="") + option(disabled, selected)="Кем выдан паспорт" + small="(Пожалуйста, проверьте правильность данных)" + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="inn")='ИНН' + input.form-control.tg_input#inn(type="text" name="#inn") + small="(Пожалуйста, проверьте правильность данных)" + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0(for="email")='Электронная почта' + input.form-control.tg_input#email(type="text" name="email" value=pct_email) + small="(Пожалуйста, проверьте правильность данных)" + + + .my-3.mx-4.success-field.verification(style="display: none;") + label.form-label.m-0 За какой год выдать данные + .checkbox-container + each year in [2025, 2024, 2023, 2022] + label.checkbox-item + input(type="checkbox" name="god_zapros" value=year) + span= year + button.btn.btn-primary#select-all Выбрать все + + + .my-3.mx-4.primary-field.verification(style="display: none;") + button.btn.btn-success.float-end.mb-3#code_submit + span.spinner-border.spinner-border-sm.me-1.d-none(role="status" aria-hidden="true") + span="Заказать справку" + + .my-3.mx-4.primary-field.success_window(style="display: none;") + h3="Отлично!" + p="Справка заказана." \ No newline at end of file diff --git a/webApp/templates/static/css/1_model_icons.css b/webApp/templates/static/css/1_model_icons.css index 4b6abdf..dc395b7 100644 --- a/webApp/templates/static/css/1_model_icons.css +++ b/webApp/templates/static/css/1_model_icons.css @@ -23,4 +23,17 @@ .m-off::before{ margin: 0px !important; +} + + +.checkbox-container { + display: flex; + flex-direction: column; + gap: 5px; +} + +.checkbox-item { + display: flex; + align-items: center; + gap: 5px; } \ No newline at end of file diff --git a/webApp/templates/static/js/2.0.dashboard.fns.js b/webApp/templates/static/js/2.0.dashboard.fns.js new file mode 100644 index 0000000..a3f5671 --- /dev/null +++ b/webApp/templates/static/js/2.0.dashboard.fns.js @@ -0,0 +1,521 @@ +function show_error(message){ + $('#error_alert').slideDown(500); + $('#success_alert').hide(); + $('#error_alert').delay(5000).slideUp(); + $('#alert_error_text').empty(); + if (message) + $('#alert_error_text').append(message) +} + +function show_success(message){ + $('#success_alert').slideDown(500); + $('#success_alert').delay(5000).slideUp(); + $('#alert_success_text').empty(); + if (message) + $('#alert_success_text').append(message); +} + + + +function validate_length(val, dest_len){ + if(val.length < dest_len){ + return false; + } + return true; +} + + + + + +$(document).ready(function(){ + + $("#postal_code").change(function(){ + $('#passport_issued_by').empty(); + $('#passport_issued_by').append('') + for(i in UFMS_list[$(this).val()]) + { + item = UFMS_list[$(this).val()][i]; + $('#passport_issued_by').append(''); + } +// $('#passport_issued_by').select2("change"); + }); + + $("#select-all").on("click", function() { + $("input[name='god_zapros']").prop("checked", true); + }); + + const validateEmail = (email) => { + return email.match( + /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + ); + }; + + const validate = () => { + const email = $('#email').val(); + if(validateEmail(email)){ + $('#email').parent().removeClass('errors-field').addClass('success-field'); + } else{ + $('#email').parent().removeClass('success-field').addClass('errors-field'); + } + return false; + } + + $('#email').on('input', validate); + + $('#email').on('input', function() { + let input = $(this).val(); + // Разрешаем только буквы, цифры, точки, дефисы и подчеркивания + input = input.replace(/[^a-zA-Z0-9._@-]/g, ''); + // Обновляем поле ввода + $(this).val(input); + }); + + $('body').append(''); + $('body').append(''); + + $('#fio').on('input', function () { + let input = $(this).val(); + + // Убираем все лишние символы, кроме букв и пробелов + input = input.replace(/[^a-zA-Zа-яА-ЯёЁ ]/g, ''); + + // Преобразуем каждое слово, чтобы оно начиналось с заглавной буквы + let formattedInput = input.split(' ').map(word => { + if (word.length > 0) { + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); + } + return ''; // Пустые слова не трогаем + }).join(' '); // Объединяем обратно с пробелами + + // Обновляем поле ввода с отформатированным текстом + $(this).val(formattedInput); + + // Проверяем количество слов + let words = formattedInput.trim().split(/\s+/); // Убираем лишние пробелы + if (words.length < 3 || words.some(word => word.length < 2)) { + $(this).parent().removeClass('success-field').addClass('errors-field'); // Подсветить поле + } else { + $(this).parent().removeClass('errors-field').addClass('success-field'); // Убрать подсветку + } + }); + + + + $('#tel').on('change', function() { + if($(this).val().length != 16){ + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else{ + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + + + // Проверка на дату рождения (не старше 80 лет) + $('#dob').on('change', function() { + const dob = new Date($(this).val()); + const currentDate = new Date(); + const age = currentDate.getFullYear() - dob.getFullYear(); + + // Проверка на возраст (не старше 80 лет) + if (age > 100 || (age === 100 && (currentDate.getMonth() < dob.getMonth() || (currentDate.getMonth() === dob.getMonth() && currentDate.getDate() < dob.getDate())))) { + // Если возраст больше 80 лет, подсвечиваем ячейку как ошибку + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else { + // Если возраст нормален, подсвечиваем ячейку как успешную + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + $('#postal_code').on('input', function() { + let input = $(this).val(); + // Удаляем все символы, кроме цифр + input = input.replace(/\D/g, ''); + // Форматируем ввод в "000-000" только при наличии 4 и более цифр + if (input.length > 3) { + input = input.replace(/(\d{3})(\d{0,3})/, '$1-$2'); + } + // Ограничиваем длину до "000-000" + if (input.length > 7) { + input = input.slice(0, 7); + } + // Обновляем поле ввода + $(this).val(input); + + // Проверка на минимальную длину (не менее 11 символов) + if (input.length < 7) { + // Если введено меньше цифр, показываем ошибку + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else { + // Если введено достаточно цифр, показываем успех + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + + $('#passport').on('input', function() { + let input = $(this).val(); + // Удаляем все символы, кроме цифр + input = input.replace(/\D/g, ''); + // Форматируем ввод в "000-000" только при наличии 4 и более цифр + if (input.length > 4) { + input = input.replace(/(\d{4})(\d{0,4})/, '$1 $2'); + } + // Ограничиваем длину до "000-000" + if (input.length > 11) { + input = input.slice(0, 11); + } + // Обновляем поле ввода + $(this).val(input); + + // Проверка на минимальную длину (не менее 11 символов) + if (input.length < 11) { + // Если введено меньше цифр, показываем ошибку + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else { + // Если введено достаточно цифр, показываем успех + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + $("#inn").attr('maxlength','12'); + $('#inn').on('input', function() { + let input = $(this).val(); + // Убираем все символы, кроме цифр + input = input.replace(/\D/g, ''); + // Ограничиваем длину до 12 символов + if (input.length > 12) { + input = input.slice(0, 12); + } + // Обновляем значение в поле ввода + $(this).val(input); + if (input.length < 12) { + // Если введено меньше цифр, показываем ошибку + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else { + // Если введено достаточно цифр, показываем успех + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + + $('#passport_date').on('change', function() { + const dob = new Date($(this).val()); + const currentDate = new Date(); + const age = currentDate.getFullYear() - dob.getFullYear(); + + // Проверка на возраст (не старше 80 лет) + if (age > 100 || (age === 100 && (currentDate.getMonth() < dob.getMonth() || (currentDate.getMonth() === dob.getMonth() && currentDate.getDate() < dob.getDate())))) { + // Если возраст больше 80 лет, подсвечиваем ячейку как ошибку + $(this).parent().removeClass('success-field').addClass('errors-field'); + } else { + // Если возраст нормален, подсвечиваем ячейку как успешную + $(this).parent().removeClass('errors-field').addClass('success-field'); + } + }); + + + +// function verification(){ +// $("#form_submit").children(".spinner-border").removeClass('d-none'); +// $("#form_submit").attr("disabled", true); +// message = {} + + + +// if(!(validate_length($('#fio').val(), 3))) +// { +// show_error('Введите ФИО', false); +// $("#form_submit").children(".spinner-border").addClass('d-none'); +// $("#form_submit").removeAttr("disabled"); +// return; +// } +// +// if(!(validate_length($('#tel').val(), 16))) +// { +// show_error('Введите Телефон', false); +// $("#form_submit").children(".spinner-border").addClass('d-none'); +// $("#form_submit").removeAttr("disabled"); +// return; +// } +// +// if ($('#dob').val().length !== 10 || new Date().getFullYear() - new Date($('#dob').val()).getFullYear() > 100) { +// show_error('Дата рождения должна быть корректной и возраст не более 80 лет', false); +// $("#form_submit").children(".spinner-border").addClass('d-none'); +// $("#form_submit").removeAttr("disabled"); +// return; +// } +// +// if ($('#dob').val().length !== 10 || new Date().getFullYear() < new Date($('#dob').val()).getFullYear()) { +// show_error('Проверьте дату ввода, вы указали дату больше чем сегодняшняя дата', false); +// $("#form_submit").children(".spinner-border").addClass('d-none'); +// $("#form_submit").removeAttr("disabled"); +// return; +// } + + function verification(){ + $("#form_submit").children(".spinner-border").removeClass('d-none'); + $("#form_submit").attr("disabled", true); + + let message = {}; + $('.tg_input').each(function() { + message[$(this).attr("id")] = $(this).val(); + }); + + show_success("Ваши данные отправлены на проверку."); + + $.ajax({ + type: "POST", + url: "/request_patient", + contentType: "application/json", // <-- Указываем JSON + data: JSON.stringify(message), // <-- Преобразуем объект в JSON + success: function(data) { + console.log(data); + if (data.success) { + $('.primary-field').hide(); + $('.verification').show(); + $('#fio').val(data.fio); + $('#fio').prop('readonly', true); + + $('#dob').val(data.js_formatted_birthdate); + $('#dob').prop('readonly', true); + + $('#passport').val(data.pct_doc_ser + ' ' + data.pct_doc_nom); + + $('#passport_date').val(data.formatted_passport_date); + + $('#postal_code').val(data.pct_doc_org_kod); + + for(i in UFMS_list[data.pct_doc_org_kod]) + { + item = UFMS_list[data.pct_doc_org_kod][i]; + console.log(item.toLowerCase()) + console.log(data.pct_doc_org_name.toLowerCase()) + console.log(item.toLowerCase()==data.pct_doc_org_name.toLowerCase()) + if(item.toLowerCase()==data.pct_doc_org_name.toLowerCase()) + { + $('#passport_issued_by').append(''); + } + else{ + $('#passport_issued_by').append(''); + } + } + + + + + + $('#inn').val(data.pct_inn); + + $('#email').val(data.pct_email); + + } else { + show_error(data.error); + } + $("#form_submit").children(".spinner-border").addClass('d-none'); + $("#form_submit").removeAttr("disabled"); + }, + error: function(jqXHR) { + show_error('Что-то пошло не так'); + $("#form_submit").children(".spinner-border").addClass('d-none'); + $("#form_submit").removeAttr("disabled"); + } + }); + } + + + $("#form_submit").click(function(){ +// show_success("Hello
world"); + verification(); + }); + + $("#code_submit").click(function(){ + + $(this).children(".spinner-border").removeClass('d-none'); + $(this).attr("disabled", true); + message = {} + + + + if(!(validate_length($('#fio').val(), 3))) + { + show_error('Введите ФИО', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if(!(validateEmail($('#email').val()))){ + show_error('Введите корректный Email', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if ($('#dob').val().length !== 10 || new Date().getFullYear() - new Date($('#dob').val()).getFullYear() > 100) { + show_error('Дата рождения должна быть корректной и возраст не более 80 лет', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if ($('#passport_date').val().length !== 10 || (new Date($('#passport_date').val()).getFullYear() - new Date($('#dob').val()).getFullYear()) < 13) { + show_error('Проверьте дату выдачи паспорта, паспорт РФ может быть выдан с 14 лет', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if(!(validate_length($('#postal_code').val(), 7))) + { + show_error('Введите код подразделения', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if(!(validate_length($('#passport').val(), 11))) + { + show_error('Введите серию и номер паспорта', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if($('#passport_issued_by').val() == null){ + show_error("Выберите кем выдан паспорт"); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + if(!(validate_length($('#inn').val(), 12))) + { + show_error('Введите ИНН', false); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + return; + } + + // Добавление значений с чекбоксов (годы) + let selectedYears = []; + $("input[name='god_zapros']:checked").each(function() { + selectedYears.push($(this).val()); + }); + + if (selectedYears.length > 0) { + message['selected_years'] = selectedYears; + } + + $.each($('.tg_input'), function(e) { + message[$(this).prop("id")] = $(this).val(); + }); + + + $.ajax({ + type: "post", + url: "/sending_patient", + processData: false, // tell jQuery not to process the data + contentType: false, // tell jQuery not to set contentType + async: true, + data: JSON.stringify(message), + success: (data) => { + if(data.success==true){ + $('.primary-field').hide(); + $('.verification').hide(); + $('.success_window').show(); + } + else{ + show_error(data.error); + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + } + }, + error:function (jqXHR, exception) { + $(this).children(".spinner-border").addClass('d-none'); + $(this).removeAttr("disabled"); + show_error('Что-то пошло не так', false) + } + }); + }); + + + + + + + + + + + + +// $('.alert-placeholder').mouseenter(function(){ +// var popOverSettings = { +// placement: 'bottom', +// content: $(this).data('content'), +// trigger: 'hover', +// container: this, +// offset: '0' +// } +// $(this).popover(popOverSettings); +// $(this).popover('show'); +// $('.popover').addClass('alert-popover'); +// }); +// $('.alert-placeholder').mouseleave(function(){ +// $('.alert-popover').remove() +// }); + + + + let phoneStr = ''; + let formattedStr = ''; + let deleteMode = false; + const phoneInput = document.querySelector('#tel'); + const defaultFormat = '+7({0}{1}{2}){3}{4}{5}-{6}{7}-{8}{9}'; +// phoneInput.value = formatPhoneString(); + +// phoneInput.addEventListener('keydown', (e) => { +// if (e.key === 'Backspace') +// deleteMode = true; +// else +// deleteMode = false; +// }); +// +// phoneInput.addEventListener('input', (e) => { +// if (deleteMode) { +// phoneInput.value = phoneInput.value; +// phoneStr = parsePhoneString(phoneInput.value.replace("+7", "").replace("-", "")); +// } else { +// if (e.inputType == 'insertText' && !isNaN(parseInt(e.data))) { +// if (phoneStr.length <= 9) +// phoneStr += e.data; +// } +// phoneInput.value = formatPhoneString(); +// } +// }); + + function formatPhoneString() { + let strArr = phoneStr.split(''); + formattedStr = defaultFormat; + for (let i = 0; i < strArr.length; i++) { + formattedStr = formattedStr.replace(`{${i}}`, strArr[i]); + } + + if (formattedStr.indexOf('{') === -1) + { + return formattedStr; + } + else + { + return formattedStr.substring(0, formattedStr.indexOf('{')); + } + } + + function parsePhoneString(str) { + return str.replace(' ', '').replace('(', '').replace(')', '').replace('-', ''); + } +}); + + diff --git a/web_run.py b/web_run.py index af2ed86..94c7e4a 100644 --- a/web_run.py +++ b/web_run.py @@ -5,4 +5,6 @@ from config import config if __name__ == '__main__': webApp.run(debug=True, port=config['WEB_APP']['PORT']) + # webApp.run(host='0.0.0.0', port=5000) + #serve(webApp, host='0.0.0.0', port=config['WEB_APP']['PORT'])