Răsfoiți Sursa

add provider and service tariff

Староверов Данила Андреевич 1 an în urmă
părinte
comite
29acffcf14

+ 44 - 1
SharixAdmin/forms.py

@@ -1,4 +1,6 @@
 from django.contrib.auth.forms import AuthenticationForm
+
+from metaservicesynced.models import Service
 from .models import SharixUser
 from django import forms
 
@@ -12,4 +14,45 @@ class LoginUserForm(AuthenticationForm):
 
     class Meta:
         model = SharixUser
-        fields = ['username', 'password']
+        fields = ['username', 'password']
+
+class ServiceTariffUpdateForm(forms.ModelForm):
+    def __init__(self, *args, **kwargs):
+        super(ServiceTariffUpdateForm, self).__init__(*args, **kwargs)
+        # Добавляет стиль бутстрапа form-control всем полям таблицы если у них нет своих стилей
+        for field in iter(self.fields):
+            if 'class' not in self.fields[field].widget.attrs:
+                self.fields[field].widget.attrs.update({'class':'form-control'})
+
+    class Meta:
+        model = Service
+        fields = ['status','ticket_status','servicetype_id','id_provider',
+                  'resource_id','requirements','price_alg','price_km','price_min','price_amount','service_status',
+                  'is_global','is_visible']
+        widgets = {
+            'status': forms.TextInput(attrs={'readonly': True}, ),
+            'ticket_status': forms.TextInput(attrs={'readonly': True}),
+            
+            'servicetype_id': forms.Select(attrs={'class': 'form-select'}),
+            'id_provider': forms.Select(attrs={'class': 'form-select'}),
+            'resource_id': forms.Select(attrs={'class': 'form-select'}),
+        }
+
+class ServiceTariffCreateForm(forms.ModelForm):
+    def __init__(self, *args, **kwargs):
+        super(ServiceTariffCreateForm, self).__init__(*args, **kwargs)
+        # Добавляет стиль бутстрапа form-control всем полям таблицы если у них нет своих стилей
+        for field in iter(self.fields):
+            if 'class' not in self.fields[field].widget.attrs:
+                self.fields[field].widget.attrs.update({'class':'form-control'})
+    
+    class Meta:
+        model = Service
+        fields = '__all__'
+
+        widgets = {
+            'servicetype_id': forms.Select(attrs={'class': 'form-select'}),
+            'id_provider': forms.Select(attrs={'class': 'form-select'}),
+            'resource_id': forms.Select(attrs={'class': 'form-select'}),
+            'ticket_status': forms.Select(attrs={'class': 'form-select'}),
+        }

+ 43 - 1
SharixAdmin/tables.py

@@ -1,6 +1,7 @@
 import django_tables2 as tables
 from .models import *
 from django.utils.html import format_html
+from metaservicesynced.models import *
 
 class TransactionsWalletTable(tables.Table):
     # id = tables.Column(order_by=True)
@@ -25,4 +26,45 @@ class TransactionsWalletTable(tables.Table):
         return format_html("<a href='{}'>{}</a>", record.get_absolute_url(), value)
         
 
-    
+class ProviderTable(tables.Table):
+
+    id = tables.Column(verbose_name='ID', attrs={"td":{"width":"5%"}})
+    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='Статус', 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 = Provider
+        attrs = {"class": "table table-layout-fixed"}
+        exclude = ('type','company_id','id_metaservice', 'requirements', 
+                   'ticket_status', 'location_type', 'default_location', 
+                   '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-provider-id="{}">', record.id)
+        else:
+            return format_html('<input class="form-check-input status-toggle" type="checkbox" id="flexCheckDefault" data-provider-id="{}">', record.id)
+
+class ServiceTariffTable(tables.Table):
+
+    id = tables.Column(verbose_name='ID', attrs={"td":{"width":"5%"}})
+    servicetype_id = tables.LinkColumn('service_tariff/edit/', verbose_name='Название тарифа', text = lambda record: record.servicetype_id.caption,
+        args=[tables.A('pk')], attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
+    ticket_status = tables.Column(verbose_name='Название схемы услуги', attrs={'th':{'scope':'col'}, "td":{"width":"20%"}}) 
+    check = tables.BooleanColumn(verbose_name='Активность', orderable=False, attrs={'th':{'scope':'col'}, "td":{"width":"20%"}})
+
+
+    class Meta:
+        model = Service
+        attrs = {"class": "table table-layout-fixed"}
+        exclude = ('resource_id','id_provider','price_alg',
+                   'price_min','price_amount','id_metaservice', 
+                   'requirements', 'service_status', 'price_km',
+                   'is_global', 'is_visible','status')
+
+    def render_check(self, value, record):
+        if record.status == 'active':
+            return format_html('<input class="form-check-input status-toggle" disabled  checked type="checkbox"')
+        else:
+            return format_html('<input class="form-check-input status-toggle" disabled  type="checkbox"')

+ 38 - 0
SharixAdmin/templates/SharixAdmin/provider.html

@@ -0,0 +1,38 @@
+{% extends 'SharixAdmin/index.html' %}
+{% load render_table from django_tables2 %}
+
+{% block contenthome %}
+    <h1 >{{ title }}</h1>
+
+    <div class="container text-center mt-2">
+      {% render_table table %}
+    </div>
+    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+    <script>
+      // Запрос на изменения статуса исполнителя
+      $('.status-toggle').change(function() {
+        var provider_id = $(this).data('provider-id');
+        var new_status = $(this).prop('checked') ? 'active' : 'deactivated';
+        $.ajax({
+          url: '{% url "provider/change_status" %}',
+          type: 'POST',
+          data: {
+            'provider_id': provider_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 %}

+ 48 - 0
SharixAdmin/templates/SharixAdmin/service_tariff.html

@@ -0,0 +1,48 @@
+{% extends 'SharixAdmin/index.html' %}
+{% load render_table from django_tables2 %}
+
+{% block contenthome %}
+    <h1 >{{ title }}</h1>
+    <div class="container text-center mt-2">
+          {% render_table table %}
+
+          {% comment %} {% if table.page %}
+            <nav aria-label="...">
+              <ul class="pagination">
+                {% if table.page.has_previous %}
+                <li class="page-item">
+                  <a class="page-link" href="?page={{ table.page.previous_page_number }}" tabindex="-1">Previous</a>
+                </li>
+                {% else %}
+                <li class="page-item disabled">
+                  <span class="page-link">Previous</span>
+                </li>
+                {% endif %}
+                {% for page in table.page_range %}
+                  {% if page == table.page.number %}
+                  <li class="page-item active">
+                    <span class="page-link">{{ page }} <span class="sr-only">(current)</span></span>
+                  </li>
+                  {% else %}
+                  <li class="page-item">
+                    <a class="page-link" href="?page={{page }}">{{ page }}</a>
+                  </li>
+                  {% endif %}
+                {% endfor %}
+                {% if table.page.has_next %}
+                <li class="page-item">
+                  <a class="page-link" href="?page={{ table.page.next_page_number }}">Next</a>
+                </li>
+                {% else %}
+                <li class="page-item disabled">
+                  <span class="page-link">Next</span>
+                </li>
+                {% endif %}
+              </ul>
+            </nav>
+          {% endif %} {% endcomment %}
+    </div>
+    <div class="container text-end mt-2">
+      <a class="btn btn-primary" href="/service_tariff/add">Добавить</a>
+    </div>
+{% endblock contenthome %}

+ 21 - 0
SharixAdmin/templates/SharixAdmin/service_tariff_form.html

@@ -0,0 +1,21 @@
+{% extends 'SharixAdmin/index.html' %}
+
+{% block contenthome %}
+<h1 class="mb-4">{{ title }}</h1>
+<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="apply" value="Отправить" />
+    </div>
+</form>
+{% endblock %}

+ 8 - 0
SharixAdmin/urls.py

@@ -20,6 +20,14 @@ urlpatterns = [
     path('balance/', balance, name='balance'),
     path('test/', testPage, name='test-page'),
     
+    path('provider/', login_required(ProviderListView.as_view()), name='provider'),
+    path('provider/change_status/', change_provider_status, name='provider/change_status'),
+
+    path('service_tariff/', login_required(ServiceTariffListView.as_view()), name='service_tariff'),
+    path('service_tariff/add/', login_required(ServiceTariffCreate.as_view()), name='service_tariff/add/'),
+    path('service_tariff/edit/<int:pk>', login_required(ServiceTariffUpdateView.as_view()), name='service_tariff/edit/'),
+
+
     #path('v1/auth/', include('djoser.urls')),
     path('auth/', include('djoser.urls.authtoken'), name='auth'),
     path('platform/api/', include(router.urls), name="sharix-api"),

+ 77 - 2
SharixAdmin/views.py

@@ -1,16 +1,18 @@
 
 import json
 from django.shortcuts import render
-from django.http import HttpResponseRedirect, HttpResponse
+from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
 from django.contrib.auth.views import LoginView
 from django.urls import reverse_lazy, resolve, reverse
 from django.contrib.auth.decorators import login_required
+from django_tables2 import SingleTableView
 from .forms import *
 from SharixAdmin.models import *
 from django.contrib.auth import logout
 from django.db.models import Q
 from .tables import *
 from django import template
+from django.views.generic.edit import UpdateView, CreateView
 # Create your views here.
 
 
@@ -103,6 +105,8 @@ menu = [
     {'title':'Сотрудничество',          'link':'test-page', 'sel':'sotrud'},
     {'title':'Техподдержка',            'link':'test-page', 'sel':'gear'},
     {'title':'Мои заявки',              'link':'tickets', 'sel':'tikets'},
+    {'title':'Исполнители',             'link':'provider', 'sel':'people'},
+    {'title':'Тарифы услуг',            'link':'service_tariff', 'sel':'person'},
 ]
 
 def get_context(request, page_context) -> dict:
@@ -115,7 +119,78 @@ def get_context(request, page_context) -> dict:
     return context
 
 
-
+@login_required
+def change_provider_status(request):
+    if request.method == 'POST':
+        provider_id = request.POST.get('provider_id')
+        new_status = request.POST.get('new_status')
+        
+        provider = Provider.objects.get(pk=provider_id)
+        provider.status = new_status
+        provider.save()
+        return JsonResponse({'status': 'success'})
+    else:
+        return JsonResponse({'status': 'error'})
+
+class ServiceTariffUpdateView(UpdateView):
+    model = Service
+    form_class = ServiceTariffUpdateForm
+    template_name = "SharixAdmin/service_tariff_form.html"
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update(get_context(self.request, {
+            'title': 'Тарифы услуг',
+            'object': self.object,
+        }))
+        return context
+    
+    def get_success_url(self):
+        return reverse('service_tariff')
+
+class ServiceTariffCreate(CreateView):
+    model = Service
+    form_class = ServiceTariffCreateForm
+    template_name = "SharixAdmin/service_tariff_form.html"
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update(get_context(self.request, {
+            'title': 'Тарифы услуг',
+            'object': self.object,
+        }))
+        return context
+    
+    def get_success_url(self):
+        return reverse('service_tariff')
+
+class ProviderListView(SingleTableView):
+    table_class = ProviderTable
+    queryset = Provider.objects.all()
+    template_name = 'SharixAdmin/provider.html'
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update(get_context(self.request, {
+            'title': 'Исполнители',
+            'object_list': context['object_list'],
+        }))
+        return context
+
+class ServiceTariffListView(SingleTableView):
+    table_class = ServiceTariffTable
+    queryset = Service.objects.all()
+    template_name = 'SharixAdmin/service_tariff.html'
+    # paginate_by = 2
+
+
+    def get_context_data(self, **kwargs):
+        context = super().get_context_data(**kwargs)
+        context.update(get_context(self.request, {
+            'title': 'Тарифы услуг',
+            'object_list': context['object_list'],
+        }))
+        return context
 
 #Shema views
 @login_required