Skip to content

Commit

Permalink
Merge pull request #3902 from mikhailprivalov/hospitalSendResult
Browse files Browse the repository at this point in the history
get direction to send after deferred time confirm
  • Loading branch information
Wellheor1 authored Jun 7, 2024
2 parents 4ead50a + 998a65a commit 931f001
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 3 deletions.
13 changes: 10 additions & 3 deletions api/directions/sql_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,20 +463,27 @@ def get_type_confirm_direction(directions_tuple):
return rows


def get_confirm_direction_by_hospital(hospitals, d_start, d_end):
def get_confirm_direction_by_hospital(hospitals, d_start, d_end, email_with_results_sent_is_false='-1'):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT
DISTINCT (directions_napravleniya.id) as direction,
directions_napravleniya.hospital_id as hospital,
directions_napravleniya.email_with_results_sent
directions_napravleniya.email_with_results_sent,
directions_napravleniya.last_confirmed_at
FROM directions_napravleniya
WHERE directions_napravleniya.hospital_id in %(hospitals)s and
directions_napravleniya.last_confirmed_at AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
AND
CASE WHEN %(email_with_results_sent_is_false)s != '-1' THEN
directions_napravleniya.email_with_results_sent = false
WHEN %(email_with_results_sent_is_false)s = '-1' THEN
directions_napravleniya.id IS NOT NULL
END
ORDER BY directions_napravleniya.hospital_id
""",
params={'hospitals': hospitals, 'd_start': d_start, 'd_end': d_end, 'tz': TIME_ZONE},
params={'hospitals': hospitals, 'd_start': d_start, 'd_end': d_end, 'tz': TIME_ZONE, 'email_with_results_sent_is_false': email_with_results_sent_is_false},
)
rows = namedtuplefetchall(cursor)
return rows
Expand Down
7 changes: 7 additions & 0 deletions hospitals/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class Hospitals(models.Model):
title_stamp_executor = models.CharField(max_length=255, blank=True, null=True, default=None, help_text="Ссылка на заголовок Исполнителя - клеше")
title_stamp_customer = models.CharField(max_length=255, blank=True, null=True, default=None, help_text="Ссылка на заголовок Закачика - клеше")
acronym_title = models.CharField(max_length=128, blank=True, default='', help_text="Акроним (Аббревиатура) наименование", db_index=True)
send_result_after_time_min = models.PositiveSmallIntegerField(default=0, blank=True, null=True, verbose_name="Время (мин) отправки результатов")

@staticmethod
def get_default_hospital() -> Optional['Hospitals']:
Expand Down Expand Up @@ -111,6 +112,12 @@ def send_email_with_pdf_file(self, subject, message, file, to=None):
email.attach(file.name, file.read(), 'application/pdf')
email.send()

@staticmethod
def hospitals_need_send_result_mail():
return [
{"id": i.pk, "mail": i.email, "send_after_time_min": i.send_result_after_time_min} for i in Hospitals.objects.filter(need_send_result=True, email__isnull=False).exclude(email="")
]

def __str__(self):
return f"{self.short_title}{self.code_tfoms}"

Expand Down
Empty file.
6 changes: 6 additions & 0 deletions integration_framework/send_messages/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import views

urlpatterns = [
path('get-directions-for-mail-send', views.get_directions_for_mail_send),
]
34 changes: 34 additions & 0 deletions integration_framework/send_messages/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from dateutil.relativedelta import relativedelta
from rest_framework.response import Response

from api.directions.sql_func import get_confirm_direction_by_hospital
from appconf.manager import SettingManager
from hospitals.models import Hospitals
from laboratory.utils import current_time, TZ
from rest_framework.decorators import api_view


@api_view()
def get_directions_for_mail_send(request):
if not hasattr(request.user, "hospitals"):
return Response({"ok": False, "message": "Некорректный auth токен"})

days_ago = SettingManager.get("days_before_hosp", default="30", default_type="i")
d_end_time = current_time()
d_start_time = d_end_time + relativedelta(days=-days_ago)

d_end = d_end_time.strftime("%Y-%m-%d %H:%M:%S")
d_start = d_start_time.strftime("%Y-%m-%d %H:%M:%S")

hospital_send_mail = Hospitals.hospitals_need_send_result_mail()
hospitals_ids = tuple([i.get("id") for i in hospital_send_mail])
result = get_confirm_direction_by_hospital(hospitals_ids, d_start, d_end, email_with_results_sent_is_false="1")
hosp_structure_by_id = {k.get("id"): {"send_after_time_min": k.get("send_after_time_min"), "mail": k.get("mail"), "dirs": []} for k in hospital_send_mail}

for r in result:
last_confirm_time = r.last_confirmed_at.astimezone(TZ)
after_time_approve_send = last_confirm_time + relativedelta(minutes=hosp_structure_by_id[r.hospital]["send_after_time_min"])
if after_time_approve_send < d_end_time:
hosp_structure_by_id[r.hospital]["dirs"].append(r.direction)

return Response(hosp_structure_by_id)
1 change: 1 addition & 0 deletions integration_framework/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,6 @@
path('client/results', views.client_results_list),
path('client/fcm', views.client_fcm),
path('researches/', include('integration_framework.researches.urls')),
path('send-messages/', include('integration_framework.send_messages.urls')),
path('employees/', include('integration_framework.employees.urls')),
]

0 comments on commit 931f001

Please sign in to comment.