История посещений, отображение чеков за несколько месяцев

This commit is contained in:
zakhy 2025-03-08 17:10:18 +07:00
parent 9d51e84a9c
commit 4b50fb6f91
4 changed files with 138 additions and 24 deletions

View File

@ -0,0 +1,48 @@
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link type="image/x-icon" href="{% static 'report/img/diagram.png' %}" rel="shortcut icon">
<link type="Image/x-icon" href="{% static 'report/img/diagram.png' %}" rel="icon">
<link rel="stylesheet" href="{% static 'bootstrap/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'flatpickr/flatpickr.min.css' %}">
<link rel="stylesheet" href="{% static 'flatpickr/theme.css' %}">
<link href="{% static 'fontawesomefree/css/fontawesome.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'fontawesomefree/css/fontawesome.min.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'fontawesomefree/css/brands.css' %}" rel="stylesheet" type="text/css">
<link href="{% static 'fontawesomefree/css/solid.css' %}" rel="stylesheet" type="text/css">
<title>История посещений</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<div class="card mt-3">
<h5 class="card-header">История посещений</h5>
<div class="card-body">
{% for object in object_list %}
<div class="d-flex align-items-center mb-3" style="gap: 15px"><i class="fas fa-video"></i><a href="{{ object.file.url }}" class="ml-2">{{ object.uploaded_at }}</a></div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@ -76,11 +76,16 @@
<div class="p-3">
{% for accessed in report_data.accessed %}
<h5>{{ accessed.name }}</h5>
<p><b>Количество посещений: </b> {{ accessed.visits_count }}/{{ required_count }}</p>
<p>
<b>Количество посещений: </b>
<a href="{% url 'report:circle_history' accessed.id %}?date_start={{ date_start }}&date_end={{ date_end }}">{{ accessed.visits_count }}/{{ required_count }}</a>
</p>
<a href="{{ accessed.contract }}" class="btn btn-outline-primary">Договор</a>
<a href="{{ accessed.cheque }}" class="btn btn-outline-primary">Чек</a>
{% for cheque in accessed.cheques %}
<a href="{{ cheque.url }}" class="btn btn-outline-primary">Чек
за {{ cheque.month }}</a>
{% endfor %}
<hr>
{% endfor %}
</div>
<h4 class="mb-3 p-3"

View File

@ -1,9 +1,10 @@
from django.urls import path
from report.views import ReportView
from report.views import ReportView, CircleHistoryView
app_name = 'report'
urlpatterns = [
path('', ReportView.as_view(), name='report')
path('', ReportView.as_view(), name='report'),
path('circle_history/<int:pk>/', CircleHistoryView.as_view(), name='circle_history')
]

View File

@ -1,7 +1,9 @@
import datetime
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.utils.timezone import now
from django.views.generic import FormView
from django.views.generic import FormView, TemplateView, ListView
from bot.models.cheque import Cheque
from bot.models.circle import Circle
@ -10,6 +12,12 @@ from bot.models.user_state import UserState
from report.forms.form_report import ReportForm
from settings.models import Settings
months_names = {
'01': 'Январь', '02': 'Февраль', '03': 'Март', '04': 'Апрель',
'05': 'Май', '06': 'Июнь', '07': 'Июль', '08': 'Август',
'09': 'Сентябрь', '10': 'Октябрь', '11': 'Ноябрь', '12': 'Декабрь'
}
class ReportView(LoginRequiredMixin, FormView):
template_name = 'report/report.html'
@ -29,7 +37,6 @@ class ReportView(LoginRequiredMixin, FormView):
context['date_start'] = date_start.strftime("%d.%m.%Y")
context['date_end'] = date_end.strftime("%d.%m.%Y")
context["required_count"] = required_count
# Передаем форму обратно для повторного заполнения
context['form'] = form
return render(self.request, self.template_name, context)
@ -40,11 +47,15 @@ class ReportView(LoginRequiredMixin, FormView):
host_url = Settings.get_setting("HOST_URL", "http://localhost:8000")
report = {"accessed": [], "not_accessed": []}
months_names = {
'01': 'январь', '02': 'февраль', '03': 'март', '04': 'апрель',
'05': 'май', '06': 'июнь', '07': 'июль', '08': 'август',
'09': 'сентябрь', '10': 'октябрь', '11': 'ноябрь', '12': 'декабрь'
}
users = UserState.objects.all()
for user in users:
# Отсеиваем
if not user.is_registered:
if user.name is None:
continue
@ -55,13 +66,13 @@ class ReportView(LoginRequiredMixin, FormView):
continue
user_has_contract = Contract.objects.filter(user=user).exists()
if not user_has_contract:
report['not_accessed'].append({
"name": user.get_name(),
"reason": "Не отправил договор"
})
continue
user_circles_count = Circle.objects.filter(
uploaded_at__gte=start_date,
uploaded_at__lte=end_date,
@ -69,36 +80,85 @@ class ReportView(LoginRequiredMixin, FormView):
if user_circles_count < required_count:
report['not_accessed'].append({
"name": user.get_name(),
"reason":
f"Количество посещений: {user_circles_count}/{required_count}"
"reason": f"Количество посещений: {user_circles_count}/{required_count}"
})
continue
try:
latest_cheque = Cheque.objects.filter(
uploaded_at__gte=start_date,
user=user).latest("uploaded_at")
except Cheque.DoesNotExist:
# Получаем все чеки в диапазоне дат
cheques = Cheque.objects.filter(
user=user,
uploaded_at__gte=start_date,
uploaded_at__lte=end_date
)
if not cheques.exists():
existent_cheque = Cheque.objects.filter(user=user).order_by(
"uploaded_at").last()
if existent_cheque is not None:
report['not_accessed'].append({
"name": user.get_name(),
"reason":
f"Нет чека за месяц: последний чек"
f"от {existent_cheque.uploaded_at.strftime('%d.%m.%Y')})"
"reason": f"Нет чека за период: последний чек от "
f"{existent_cheque.uploaded_at.strftime('%d.%m.%Y')}"
})
else:
report['not_accessed'].append({
"reason": user.get_name(),
"text": "Нет чека за месяц"
"name": user.get_name(),
"reason": "Нет чека за период"
})
continue
# Добавляем в отчет
# Группируем чеки по месяцам, берем последний в каждом месяце
cheques_by_month = {}
for cheque in cheques:
month_key = cheque.uploaded_at.strftime('%Y-%m')
if month_key not in cheques_by_month or \
cheque.uploaded_at > cheques_by_month[
month_key].uploaded_at:
cheques_by_month[month_key] = cheque
latest_contract = Contract.objects.latest('uploaded_at')
report["accessed"].append({
"id": user.id,
"name": user.get_name(),
"visits_count": user_circles_count,
"contract": f'{host_url}{latest_contract.file.url}',
"cheque": f'{host_url}{latest_cheque.file.url}'
"cheques": [
{
"month": f"{months_names[cheque.uploaded_at.strftime('%m')]} "
f"{cheque.uploaded_at.strftime('%Y')}",
"url": f'{host_url}{cheque.file.url}'
}
for cheque in cheques_by_month.values()
]
})
return report
class CircleHistoryView(ListView):
template_name = "report/circle_history.html"
model = Circle # Указываем модель
def get_queryset(self):
date_start = self.request.GET.get("date_start")
date_end = self.request.GET.get("date_end")
user_id = self.kwargs.get('pk')
# Исправленное условие
if not date_start or not date_end or not user_id:
return []
try:
start_date = datetime.datetime.strptime(date_start, "%d.%m.%Y")
end_date = datetime.datetime.strptime(date_end, "%d.%m.%Y")
except ValueError:
return []
circles_by_range = Circle.objects.filter(
user_id=user_id,
uploaded_at__gte=start_date,
uploaded_at__lte=end_date
)
# Отладочный вывод
return circles_by_range