Bläddra i källkod

create task_manegement

kateshev14 5 månader sedan
förälder
incheckning
390729a13d

+ 20 - 3
SharixAdmin/forms/service.py

@@ -1,6 +1,6 @@
 from django import forms
 from dbsynce.models import ServiceType, Service, Company
-from webservice_running.models import Comments
+from webservice_running.models import Comments, Tasks
 from django.contrib.auth import get_user_model
 
 
@@ -94,7 +94,7 @@ class ServiceTypeCreateForm(forms.ModelForm):
         }
 
 class CommentsCreateForm(forms.ModelForm):
-    description = forms.CharField(label="Описание")
+    task_description = forms.CharField(label="Описание задачи")
     is_global = forms.BooleanField(label="Доступно во всех сервисах", required=False)
     is_visible = forms.BooleanField(label="Доступно для планирования цепочек во всех сервисах", required=False)
 
@@ -108,7 +108,24 @@ class CommentsCreateForm(forms.ModelForm):
 
         widgets = {
 
-        }        
+        }   
+        
+class TasksCreateForm(forms.ModelForm):
+    description = forms.CharField(label="Описание")
+    is_global = forms.BooleanField(label="Доступно во всех сервисах", required=False)
+    is_visible = forms.BooleanField(label="Доступно для планирования цепочек во всех сервисах", required=False)
+
+    def __init__(self, *args, **kwargs):
+        super(TasksCreateForm, self).__init__(*args, **kwargs)
+    class Meta:
+        model = Tasks
+        fields = ['task_description','repr_id','user_id','dead_line',
+                  'ticket_status', 'id_metaservice',
+                  'is_global','is_visible',]
+
+        widgets = {
+
+        }               
 
 
 class ServiceInformationUpdateForm(forms.ModelForm):

+ 27 - 21
SharixAdmin/tables.py

@@ -49,27 +49,7 @@ class PartnersTable(tables.Table):
         else:
             return format_html('<input class="form-check-input status-toggle" type="checkbox" id="flexCheckDefault" data-partners-id="{}">', record.id)
 
-class TaskTable(tables.Table):
-    id = tables.Column(verbose_name=_('ID'), attrs={"td":{"width":"5%"}})
-    legal_name = tables.Column(verbose_name=_('Legal entity'), attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
-    repr_id = tables.Column(accessor='repr_id.full_name', order_by=('repr_id.first_name', 'repr_id.last_name'), verbose_name=_('Responsible'), attrs={"td":{"width":"15%"}})
-   
-    status = tables.Column(verbose_name=_('Status'), attrs={'th':{'scope':'col'}, "td":{"width":"20%"}}) 
-    check = tables.BooleanColumn(verbose_name='', attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
-    # paginate_by = 10
-    class Meta:
-        model = Company
-        attrs = {"class": "table table-layout-fixed"}
-        exclude = ('inn','kpp','ogrn', 'bank_name', 
-                   'bik', 'ks', 'rs', 
-                   'address', 'requirements', 
-                   'id_metaservice', 'is_global', 'is_visible', 'ticket_status')
 
-    def render_check(self, value, record):
-        if record.status == 'active':
-            return format_html('<input class="form-check-input status-toggle" checked type="checkbox" id="flexCheckDefault" data-partners-id="{}">', record.id)
-        else:
-            return format_html('<input class="form-check-input status-toggle" type="checkbox" id="flexCheckDefault" data-partners-id="{}">', record.id)
 
 class ResourceTable(tables.Table):
 
@@ -161,7 +141,33 @@ class ServiceTypeTable(tables.Table):
         
     # def render_name_operation(self, value, record):
     #     return format_html("<a href='{}'>{}</a>", record.get_absolute_url(), value)
-   
+    
+class TasksTable(tables.Table):
+
+    id = tables.Column(verbose_name=_('ID'), attrs={"td":{"width":"5%"}})
+    task_description = tables.Column(verbose_name=_('Задача'), attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
+    dead_line = tables.Column(verbose_name=_('Дата'), attrs={"td":{"width":"10%"}})
+    repr_id = tables.Column(accessor='repr_id.full_name', order_by=('repr_id.first_name', 'repr_id.last_name'), verbose_name=_('Ответственный'), attrs={"td":{"width":"15%"}})
+    user_id = tables.Column(accessor='user_id.full_name', order_by=('user_id.first_name', 'user_id.last_name'), verbose_name=_('Исполнитель'), attrs={"td":{"width":"15%"}})
+    status = tables.Column(verbose_name=_('Status'), attrs={'th':{'scope':'col'}, "td":{"width":"20%"}}) 
+    check = tables.BooleanColumn(verbose_name='', attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
+    edit = tables.LinkColumn('tech_support/edit/', verbose_name='', orderable=False, text = "E",
+        args=[tables.A('pk')], attrs={'th':{'scope':'col'}, "td":{"class":"edit_col"}})
+    delete = tables.LinkColumn('tech_support/delete/', verbose_name='', orderable=False, text = "D",
+        args=[tables.A('pk')], attrs={'th':{'scope':'col'}, "td":{"class":"delete_col"}})
+    
+    class Meta:
+        model = Tasks
+        attrs = {"class": "table table-layout-fixed text-start"}
+        exclude = ('ticket_status', 'id_metaservice',
+                   'is_global', 'is_visible')
+        
+    def render_check(self, value, record):
+        if record.status == 'active':
+            return format_html('<input class="form-check-input status-toggle" checked type="checkbox" id="flexCheckDefault" data-tasks-id="{}">', record.id)
+        else:
+            return format_html('<input class="form-check-input status-toggle" type="checkbox" id="flexCheckDefault" data-tasks-id="{}">', record.id)   
+        
 class CommentsTable(tables.Table):
 
     id = tables.Column( attrs={"td":{"width":"50px"}})

+ 16 - 13
SharixAdmin/templates/SharixAdmin/index.html

@@ -218,6 +218,7 @@
           </div>
         </a>
       </li>
+      
       <li class="nav-item">
         <a href="{% url 'task_management' %}" class="nav-link {% if current_page == "task_management" %}active rounded{% endif %}">
           <div class="link d-flex align-items-center">
@@ -250,19 +251,21 @@
       </li>
       {% else %}
       <li class="nav-item">
-        <a href="{% url 'service_information-add' %}" class="nav-link {% if current_page == "service_info" %}active rounded{% endif %}">
-          <div class="link d-flex align-items-center">
-            <img
-              class="nav-img"
-              src="
-                {% if current_page == "service_info" %}
-                  {% static 'SharixAdmin/img/menu/person_w.svg' %}
-                {% else %}
-                  {% static 'SharixAdmin/img/menu/person.svg' %}
-                {% endif %}">
-            <span class="menu-bar-label">Информация о сервисе</span>
-          </div>
-        </a>
+        <li class="nav-item">
+          <a href="{% url 'partner_detail' %}" class="nav-link {% if current_page == 'partner' %}active rounded{% endif %}">
+            <div class="link d-flex align-items-center">
+              <img
+                class="nav-img"
+                src="
+                  {% if current_page == 'partner' %}
+                    {% static 'SharixAdmin/img/menu/person_w.svg' %}
+                  {% else %}
+                    {% static 'SharixAdmin/img/menu/person.svg' %}
+                  {% endif %}">
+              <span class="menu-bar-label">О компании</span>
+            </div>
+          </a>
+        </li>
       </li>
       <li class="nav-item">
         <a href="{% url 'payment_way' %}" class="nav-link {% if current_page == "payment_way" %}active rounded{% endif %}">

+ 10 - 7
SharixAdmin/templates/SharixAdmin/partners.html

@@ -1,16 +1,19 @@
 {% extends 'SharixAdmin/index.html' %}
 {% load render_table from django_tables2 %}
 
+
 {% block contenthome %}
-<div class="container">
-    <p class="description_service">Управление партнерскими отношениями. Администраторы могут просматривать информацию о текущих партнерах, 
-      добавлять новых партнеров, управлять условиями сотрудничества и менять статус партнера. 
-      Кроме того, здесь имеется сортировка, позволяющая администратору легко настроить поиск в соответствии с предпочтениями.</p>
+
+  <p class="description_service">Управление партнерскими отношениями. Администраторы могут просматривать информацию о текущих партнерах, 
+    добавлять новых партнеров, управлять условиями сотрудничества и менять статус партнера. 
+    Кроме того, здесь имеется сортировка, позволяющая администратору легко настроить поиск в соответствии с предпочтениями.</p>
 
 
-  <div class="container text-center mt-2">
-    {% render_table table %}
-  </div>
+    <div class="row justify-content-start">
+      <div class="maintable" id="maintable">
+        {% render_table table %}
+      </div>     
+    </div>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
     // Запрос на изменения статуса партнера

+ 32 - 3
SharixAdmin/templates/SharixAdmin/task_management.html

@@ -1,17 +1,46 @@
 {% extends 'SharixAdmin/index.html' %}
 {% load render_table from django_tables2 %}
+{% load i18n %}
+{% load static %}
 
 {% block contenthome %}
-<div class="container">
+  <div class="container">
     <p class="description_service">Просмотр всех текущих задач и управление ими, назначая исполнителей или изменяя сроки выполнения. 
       Администраторы могут создавать новые задачи, редактировать уже существующие и удалять ненужные задачи. 
       Здесь также можно просматривать статус выполнения задач и отслеживать их прогресс.</p>
-
+  </div>  
     <div class="container text-center mt-2">
       {% render_table table %}
     </div>
+    <div class="container text-end mt-2">
+      <a class="btn btn-primary" id="bord" href="/task_management/add">{% trans 'Add' %}</a>
+    </div>
     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
-</div>    
+    <script>
+      // Запрос на изменения статуса исполнителя
+      $('.status-toggle').change(function() {
+        var tasks_id = $(this).data('tasks-id');
+        var new_status = $(this).prop('checked') ? 'active' : 'deactivated';
+        $.ajax({
+          url: '{% url "tasks/change_status" %}',
+          type: 'POST',
+          data: {
+            'tasks_id': tasks_id,
+            'new_status': new_status,
+            'csrfmiddlewaretoken': '{{ csrf_token }}'
+          },
+          success: function(response) {
+            var scrollTop = window.pageYOffset;
+            location.reload();
+            window.scrollTo(0, scrollTop);
+          },
+          error: function(xhr, status, error) {
+            console.log(xhr.responseText);
+          }
+        });
+      });
+    </script>
+  
 
     
 {% endblock contenthome %}

+ 14 - 0
SharixAdmin/templates/SharixAdmin/task_management_delete.html

@@ -0,0 +1,14 @@
+{% extends 'SharixAdmin/index.html' %}
+{% load i18n %}
+
+{% block contenthome %}
+<form method="post">
+    {% csrf_token %}
+    <div class="container m-2">
+        <p>{% blocktrans %}Are you sure you want to delete \"%(object.caption)s\"?{% endblocktrans %}</p>
+    </div>
+    <div class="text-center mt-2 mb-5">
+        <input class="btn btn-primary center" type="submit" name="apply" value="{% trans 'Delete' %}"/>
+    </div>
+</form>
+{% endblock %}

+ 23 - 0
SharixAdmin/templates/SharixAdmin/task_management_form.html

@@ -0,0 +1,23 @@
+{% extends 'SharixAdmin/index.html' %}
+{% load i18n %}
+
+{% block contenthome %}
+<div class="container">
+<form method="post" style="overflow: auto">
+    {% csrf_token %}
+    <div class="container m-2">
+        {% for field in form %}
+        {{field.errors}}
+        <div class="row">
+            {{field.label_tag}}
+            {{field}}
+            <p class="fs-6 fst-italic">{{field.help_text|truncatewords:20}}</p>
+        </div>
+        {% endfor %}
+    </div>
+    <div class="text-center mt-2 mb-5">
+        <input class="btn btn-primary center" type="Submit" name="submit" value="{% trans 'Save' %}"/>
+    </div>
+</form>
+</div>
+{% endblock %}

+ 0 - 1
SharixAdmin/templates/SharixAdmin/tech_support.html

@@ -14,7 +14,6 @@
   }
 </style>
 
-<h1 class="mainHeader">{{ title }}</h1>
 <p class="description_service">Помощь пользователям в решении возможных проблем и вопросов, 
   связанных с использованием услуг. Здесь можно отслеживать статус комментариев и удалять их, если они больше не нужны.</p>
       <div class="row justify-content-start">

+ 0 - 1
SharixAdmin/templates/SharixAdmin/tech_support_delete.html

@@ -2,7 +2,6 @@
 {% load i18n %}
 
 {% block contenthome %}
-<h1 class="mainHeader">{{ title }}</h1>
 <form method="post">
     {% csrf_token %}
     <div class="container m-2">

+ 0 - 1
SharixAdmin/templates/SharixAdmin/tech_support_form.html

@@ -3,7 +3,6 @@
 
 {% block contenthome %}
 <div class="container">
-<h1 class="mainHeader">{{ title }}</h1>
 <form method="post" style="overflow: auto">
     {% csrf_token %}
     <div class="container m-2">

+ 3 - 0
SharixAdmin/urls.py

@@ -35,7 +35,10 @@ urlpatterns = [
     path('account/delete/<int:pk>/', login_required(AccountDelete.as_view()), name='account/delete/'),
     path('account/edit/<int:pk>/', login_required(AccountUpdateView.as_view()), name='account/edit/'),
 
+    path('tasks/change_status/', change_tasks_status, name='tasks/change_status'),
     path('task_management/', login_required(TaskListView.as_view()), name='task_management'),
+    path('task_management/add/', login_required(TaskCreate.as_view()), name='task_management/add/'),
+    path('task_management/edit/<int:pk>', login_required(TasksUpdateView.as_view()), name='task_management/edit/'),
     
     path('comments/', login_required(CommentsListView.as_view()), name='comments'),
     path('comments/change_status/', change_comments_status, name='comments/change_status'),

+ 93 - 10
SharixAdmin/views/task_management.py

@@ -1,43 +1,126 @@
 from django_tables2 import SingleTableView
 from django.contrib.auth.mixins import UserPassesTestMixin
-from SharixAdmin.tables import TaskTable
+from django.views.generic.edit import UpdateView, CreateView, DeleteView
+from SharixAdmin.tables import TasksTable
 from django.contrib.auth.decorators import login_required
 from webservice_running.models import Tasks
+from SharixAdmin.forms import TasksCreateForm
 from django.http import JsonResponse
+from django.urls import reverse
 from SharixAdmin.utils import group_required
 from django.utils.translation import gettext as _
 
+from .base import BaseView
 
-class TaskListView(UserPassesTestMixin, SingleTableView):
-    table_class = TaskTable
+class TaskCreate(UserPassesTestMixin, CreateView):
+    model = Tasks
+    form_class = TasksCreateForm
+    template_name = "SharixAdmin/task_management_form.html"
+
+    page_title = _('Управление задачами')
+    page_name = 'task_management'
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update({
+            'object': self.object,
+        })
+        return context
+    
+    def get_success_url(self):
+        return reverse('task_management')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
+    
+
+class TaskListView(UserPassesTestMixin, BaseView, SingleTableView):
+    table_class = TasksTable
     queryset = Tasks.objects.all()
     template_name = 'SharixAdmin/task_management.html'
 
+    page_title = _('Управление задачами')
+    page_name = 'task_management'
+
     def get_context_data(self, **kwargs):
         context = super().get_context_data(**kwargs)
         context.update({
-            'title': _('Управление задачами'),
             'object_list': context['object_list'],
-            'current_page': "task_management"
         })
         return context
     
+    
+    def testing(self, queryset, is_descending):
+        queryset = queryset.annotate.order_by("-" if is_descending else "")
+        return (queryset, True)
+
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+
+class TasksUpdateView(UserPassesTestMixin, UpdateView):
+    model = Tasks
+    form_class = TasksCreateForm
+    template_name = "SharixAdmin/task_management_form.html"
+    
+    page_title = _('Управление задачами')
+    page_name = 'task_management'
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update({
+            'object': self.object,
+        })
+        return context
+    
+    
     def test_func(self) -> bool or None:
         group_names = ('METASERVICE-ADMIN')
         if bool(self.request.user.groups.filter(name=group_names)) or self.request.user.is_superuser:
             return True
         return False
+    
+    def get_success_url(self):
+        return reverse('task_management')
+
+class TasksDelete(UserPassesTestMixin, DeleteView):
+    model = Tasks
+    template_name = "SharixAdmin/task_management_delete.html"
+
+    page_title = _('Управление задачами')
+    page_name = 'task_management'
 
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update({
+            'object': self.object,
+        })
+        return context
+    
+    def get_success_url(self):
+        return reverse('task_management')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 
 @login_required
 @group_required('METASERVICE-ADMIN')
-def change_partners_status(request):
+def change_tasks_status(request):
     if request.method == 'POST':
-        partners_id = request.POST.get('partners_id')
+        task_id = request.POST.get('task_id')
         new_status = request.POST.get('new_status')
-        partners = Tasks.objects.get(pk=partners_id)
-        partners.status = new_status
-        partners.save()
+        tasks = Tasks.objects.get(pk=task_id)
+        tasks.status = new_status
+        tasks.save()
         return JsonResponse({'status': 'success'})
     else:
         return JsonResponse({'status': 'error'})