This commit is contained in:
Alex committed 2024-04-19 13:53:25 +03:00
1 parent 631cecc8cd
commit 2aeb3ef513
8 files changed
+158 -105

No files matched your search

+10 -7
View File
@@ -1,13 +1,16 @@
from django.contrib import admin
from .models import SafetyFile
from .models import SafetyFile, SafetyType, SafetyDocumentCategory
# Register your models here.
class SafetyFileAdmin(admin.ModelAdmin):
list_display = ('name', 'chapter_id', 'category_id', 'sign_date', 'formainpage')
list_editable = ('sign_date', 'category_id', 'formainpage')
list_filter = ('name', 'sign_date', 'category_id',)
fields = ('name', 'url', 'chapter_id', 'category_id', 'sign_date', 'formainpage')
admin.site.register(SafetyFile, SafetyFileAdmin)
list_display = ('name', 'chapter', 'category', 'sign_date', 'formainpage')
list_editable = ('sign_date', 'category', 'formainpage')
list_filter = ('name', 'sign_date', 'category',)
fields = ('name', 'url', 'chapter', 'category', 'sign_date', 'formainpage')
admin.site.register(SafetyType)
admin.site.register(SafetyDocumentCategory)
admin.site.register(SafetyFile, SafetyFileAdmin)
+12 -28
View File
@@ -1,42 +1,26 @@
from django.db import models
from enum import Enum
# Create your models here.
class EnumChoice(Enum):
@classmethod
def get_choices(cls):
return [(enum_.name, enum_.value) for enum_ in cls]
class SafetyDocumentCategory(models.Model):
name = models.CharField(max_length=255)
class SafetyChapter(EnumChoice):
fire_safety = "Пожарная безопасность"
information_safety = "Информационная безопасность"
occupational_safety = "Охрана труда"
access_mode = "Пропускной и внутриобъектовый режим"
civil_defense = "Гражданская оборона"
state_secrets = "Защита гостайны"
military_registration = "Мобилизационная подготовка и воинский учет"
def __str__(self):
return str(self.name)
class SafetyDocumentCategory(EnumChoice):
regulations = "Нормативные документы"
instructions = "Инструкции"
orders = "Приказы"
provisions = "Положения"
educational_materials = "Учебные материалы"
laws = "Законы"
decrees = "Указы"
resolutions = "Постановления"
thematic_materials = "Тематические материалы"
methodological_materials = "Методологические материалы"
evacuation_plan = 'План эвакуации'
class SafetyType(models.Model):
name = models.CharField(max_length=255)
path = models.CharField(max_length=255, null=True)
def __str__(self):
return str(self.name)
# Общая модель для раздела "Безопасность"
class SafetyFile(models.Model):
name = models.CharField(verbose_name='Имя документа', max_length=255)
url = models.FileField(verbose_name='Путь до файла',upload_to='safety')
chapter_id = models.CharField(verbose_name='Раздел', max_length=255, blank=False, db_index=True, choices=SafetyChapter.get_choices())
category_id = models.CharField(verbose_name='Категория документа', max_length=255, blank=False, db_index=True, choices=SafetyDocumentCategory.get_choices())
chapter = models.ForeignKey('SafetyType', models.DO_NOTHING, null=True, verbose_name='Раздел', related_name="type_file")
category = models.ForeignKey('SafetyDocumentCategory', models.DO_NOTHING, null=True, verbose_name='Категория документа')
formainpage = models.BooleanField(default=False, verbose_name="Основная информация")
sign_date = models.DateField(verbose_name='Дата документа')
created_at = models.DateTimeField(verbose_name='Дата загрузки файла', auto_now_add=True)
+38 -5
View File
@@ -1,10 +1,43 @@
from rest_framework import serializers
from .models import *
from django.db.models import Count
class OneFileSerializer(serializers.ModelSerializer):
class Meta:
model = SafetyFile
fields = '__all__'
class SafetyTypeSerializer(serializers.ModelSerializer):
class Meta:
model = SafetyType
fields = '__all__'
class SafetyFileSerializer(serializers.ModelSerializer):
chapter_name = serializers.CharField(source='get_chapter_id_display')
category_name = serializers.CharField(source='get_category_id_display')
# chapter_name = serializers.CharField(source='get_chapter_id_display')
# category_name = serializers.CharField(source='get_category_id_display')
categories = serializers.SerializerMethodField('get_categories')
class Meta:
model = SafetyFile
fields = '__all__'
model = SafetyType
fields = '__all__'
def get_categories(self, obj):
files = obj.type_file.all().order_by('category__name')
categories = files.values("category","category__name").distinct()
for x in files:
for y in categories:
if 'files' not in y.keys():
y['files'] = []
if x.category.id == y['category']:
y['files'].append(OneFileSerializer(x).data)
return categories
+1
View File
@@ -4,6 +4,7 @@ from rest_framework.routers import DefaultRouter
from .views import *
urlpatterns = [
path('gettypes/', SafetyTypeAPIView.as_view(), name="SafetyTypeAPIView"),
path('files/', SafetyFileAPIView.as_view(), name='safety_files'),
path('responsibility/', SafetyResponsebilityAPIView.as_view(), name='responsibility'),
path('committee_files/', CommitteeFilesAPIView.as_view(), name='committee_files')
+10 -22
View File
@@ -1,5 +1,6 @@
from itertools import groupby
from django.db.models import Count
from rest_framework.generics import ListAPIView
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
@@ -9,30 +10,17 @@ from userauth.serializers import *
from userauth.models import *
# Create your views here.
class SafetyTypeAPIView(ListAPIView):
def get(self, request):
chapters = SafetyType.objects.annotate(Count("type_file")).filter(type_file__count__gt=0)
return Response(SafetyTypeSerializer(chapters, many=True).data)
class SafetyFileAPIView(APIView):
def get(self, request):
chapters = self.request.query_params.get('chapter_id', 1)
all_file = SafetyFile.objects.filter(chapter_id=chapters).order_by('chapter_id', 'category_id').all()
serializer_for_file = SafetyFileSerializer(instance=all_file, many=True)
data = []
for (chapter_id, chapter_name), row in groupby(serializer_for_file.data, lambda x: (x['chapter_id'], x['chapter_name'])):
chapter = {
'id': chapter_id,
'name': chapter_name,
'categories': []
}
data.append(chapter)
for (category_id, category_name), files in groupby(row, lambda x: (x['category_id'], x['category_name'])):
chapter['categories'].append({
'id': category_id,
'name': category_name,
'files': [file for file in files]
})
return Response(data)
chapters = self.request.query_params.get('chapter', "fire_safety")
safety_group = SafetyType.objects.get(path=chapters)
return Response(SafetyFileSerializer(safety_group).data)
class SafetyResponsebilityAPIView(APIView):
+23 -14
View File
@@ -295,7 +295,7 @@ import { useTheme } from "vuetify";
import AuthForm from '@/components/UI/Auth-form.vue'
import OnlineUsers from '@/components/UI/fiousercard/onlineUsers.vue'
import CardLike from '@/components/cardLike.vue'
import { clearAxios } from '@/utils/axios-api'
import { axiosApiInstance, clearAxios } from '@/utils/axios-api'
import { baseURL } from '@/utils/axios-api'
import VcardUser from '@/components/UI/fiousercard/vcardUser.vue'
@@ -378,7 +378,7 @@ export default {
// ]
const navigations = [
const navigations = ref([
{
name: 'Структура',
@@ -421,16 +421,6 @@ export default {
ico: 'mdi-newspaper',
path: "/news"
},
{
name: 'Безопасность',
ico: 'mdi-security',
submenu: [
{
name: 'Пожарная безопасность',
path: "/fire_safety"
},
]
},
{
name: 'О портале',
ico: 'mdi-information-variant',
@@ -453,8 +443,8 @@ export default {
// ico: 'mdi-cake-variant',
// path: "/fnshol"
// }
]
])
const imageSrc = computed(() => {
return new URL(`@/assets/FNS-logo-xs.png`, import.meta.url).href;
})
@@ -464,7 +454,26 @@ export default {
// feedalert.value=true
}
const getSafetyChapter = () => {
axiosApiInstance.get('api/safety/gettypes/').then(response => {
response.data.forEach(item => {
if(!item.path.startsWith('/')) {
item.path = '/' + item.path
}
});
if (response.data.length > 0) {
let safetyMenu = {
name: 'Безопасность',
ico: 'mdi-security',
submenu: response.data
}
navigations.value.splice(5, 0, safetyMenu)
}
})
}
getSafetyChapter()
return {
theme,
+1 -1
View File
@@ -75,7 +75,7 @@ const routes = [
}
},
{
path: '/:chapter_id',
path: '/:chapter',
component: () => import('@/views/safety/ChaptersSafety.vue'),
meta: {
title: "Разделы безопасности",
+63 -28
View File
@@ -22,28 +22,62 @@
<v-window-item value="document" class="h-100">
<v-row no-gutters class="gap h-100 ">
<v-col lg="6">
<v-card class="h-100 flex-column d-flex gap">
<v-card class="h-100 flex-column d-flex gap ">
<v-row class="ma-0 my-3 overflow-auto h-0 pb-1">
<v-card v-for="item in safetyData" :key="item.id" class="overflow-y-auto flex-grow-1 flex-shrink-1 h-100">
<v-card-title>{{ item.name }}</v-card-title>
<v-container
v-for="category in item.categories"
:key="item.id + category.id"
:fluid="true"
<v-card class="overflow-y-auto flex-grow-1 flex-shrink-1 h-100">
<v-card-title>{{ safetyData.name }}</v-card-title>
<v-expansion-panels
flat
>
<v-expansion-panel
elevation=0
v-for="category in safetyData.categories"
:key="category.id"
class="py-0">
<v-card-actions v-if="category.id != 'evacuation_plan'">
<v-expansion-panel-title class="font-weight-medium">{{ category.category__name }}</v-expansion-panel-title>
<v-expansion-panel-text>
<div v-for="file in category.files" :key="file.id" class="overflow-y-auto d-flex justify-space-between">
<div
class="cursor-pointer"
@click="openPDF(file.url), loading=true">
{{ file.name }}
</div>
<div>
<v-btn size="small" variant="text" icon="mdi-file-pdf-box" color="red" @click="openPDF(file.url), loading=true"></v-btn>
<v-btn size="small" variant="text" icon='mdi-file-download-outline' color="green" @click="downloadItem(burl + file.url, file.name)"></v-btn>
</div>
</div>
</v-expansion-panel-text>
<!-- <v-card-actions v-if="category.id != 'evacuation_plan'">
<v-btn
@click="showMore[item.id + category.id] = !showMore[item.id + category.id]"
@click="showMore[ category.id] = !showMore[category.id]"
variant="text">
{{ category.name }}
</v-btn>
{{ category.category__name }}
</v-btn>
<v-btn
:icon="showMore[item.id + category.id] ? 'mdi-chevron-up' : 'mdi-chevron-down'"
@click="showMore[item.id + category.id] = !showMore[item.id + category.id]">
:icon="showMore[ category.id] ? 'mdi-chevron-up' : 'mdi-chevron-down'"
@click="showMore[category.id] = !showMore[ category.id]">
</v-btn>
</v-card-actions>
<v-expand-transition>
<div v-show="showMore[item.id + category.id]">
</v-card-actions>-->
<!-- <v-expand-transition>
<div v-show="showMore[ category.id]">
<v-card-actions v-for="file in category.files" :key="file.id" class="overflow-y-auto">
<v-card-text
class="cursor-pointer"
@@ -54,12 +88,13 @@
<v-btn icon='mdi-file-download-outline' color="green" @click="downloadItem(burl + file.url, file.name)"></v-btn>
</v-card-actions>
</div>
</v-expand-transition>
</v-container>
</v-expand-transition> -->
</v-expansion-panel>
</v-expansion-panels>
</v-card>
</v-row>
<v-row class="ma-0 overflow-auto h-0">
<v-card class="overflow-y-auto flex-grow-1 flex-shrink-1 h-100">
<v-card class="overflow-y-auto flex-grow-1 h-100">
<v-card-title>{{ responsibilityData.name }}</v-card-title>
<v-container
v-for="file in responsibilityData.files"
@@ -137,12 +172,12 @@ const route = useRoute();
// Вынес запрос в отдельную функцию, чтобы избежать дублирования одного и того же запроса на сервер.
function getSafety() {
axiosApiInstance.get(`api/safety/files/?chapter_id=${route.params.chapter_id}`).then(result => {
axiosApiInstance.get(`api/safety/files/?chapter=${route.params.chapter}`).then(result => {
safetyData.value = result.data
console.log(safetyData.value);
// console.log(safetyData.value);
loading.value=true
pdfSource.value =burl + safetyData.value[0].categories[1].files[0].url
console.log(safetyData.value);
pdfSource.value =burl + safetyData.value.categories[0].files[0].url
// console.log(safetyData.value);
})
}
@@ -150,7 +185,7 @@ const formainpage = computed({
get() {
let arr=[]
if(safetyData.value.length>0){
safetyData.value[0].categories.forEach(element => {
safetyData.value.categories.forEach(element => {
element.files.forEach((e)=>{
if(e.formainpage==true){
arr.push(e)}
@@ -172,10 +207,10 @@ getResponsibility()
onBeforeMount(() => getSafety());
// Проверяем по ID на какой категории срабатывает клик на раскрытии/скрытии, чтобы избежать срабатывания у всех категорий одновременно
showMore.value = safetyData.value.reduce((acc, value) => {
acc[value.id] = false
return acc
}, {});
// showMore.value = safetyData.value.reduce((acc, value) => {
// acc[value.id] = false
// return acc
// }, {});
const downloadItem = (url, fileName) => {
axiosApiInstance.get(url, {responseType: 'blob'})