You are on page 1of 20

<!

doctype html>
{% load static %}
<html class="no-js" lang="en">

<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Inicio - Mi Oficina</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="{% static 'assets/images/icon/favicon.ico'
%}">
<link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/font-awesome.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/themify-icons.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/metisMenu.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/owl.carousel.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/slicknav.min.css' %}">
<!-- amchart css -->
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css"
type="text/css" media="all"/>
<!-- others css -->
<link rel="stylesheet" href="{% static 'assets/css/typography.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/default-css.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/responsive.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/select2.full.css' %}">
<link rel="stylesheet" href="{% static 'assets/sweet-alert2/sweetalert2.min.css' %} ">

<!-- modernizr css -->


<script src="{% static 'assets/js/vendor/modernizr-2.8.3.min.js' %} "></script>
<!-- Start datatable css -->
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
<!-- Include external CSS. -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-
awesome.min.css" rel="stylesheet"
type="text/css"/>

{% block style %}
{% endblock %}
</head>

<body class="body-bg">
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a
href="http://browsehappy.com/">upgrade
your browser</a> to improve your experience.</p>
<![endif]-->
<!-- preloader area start -->
<div id="preloader">
<div class="loader"></div>
</div>
<!-- preloader area end -->
<!-- main wrapper start -->
<div class="horizontal-main-wrapper">
<!-- main header area start -->
{% include 'base_navbar_header.html' %}
<!-- main header area end -->
<!-- header area start -->
{% include 'base_navbar.html' %}
<!-- header area end -->

<!-- page title area end -->


<div class="main-content-inner">
<div class="container">
{% block container %}
{% endblock %}
</div>
</div>
<!-- main content area end -->
<!-- footer area start-->
<footer>
<div class="footer-area">
<p>© Copyright 2022. Todos los derechos reservados. <b>Mi Oficina</b></p>
</div>
</footer>
<!-- footer area end-->
</div>
<!-- main wrapper start -->
<!-- jquery latest version -->
<script src="{% static 'assets/js/vendor/jquery-2.2.4.min.js' %}"></script>
<!-- bootstrap 4 js -->
<script src="{% static 'assets/js/popper.min.js' %}"></script>
<script src="{% static 'assets/js/bootstrap.min.js' %}"></script>
<script src="{% static 'assets/js/owl.carousel.min.js' %}"></script>
<script src="{% static 'assets/js/metisMenu.min.js' %}"></script>
<script src="{% static 'assets/js/jquery.slimscroll.min.js' %}"></script>
<script src="{% static 'assets/js/jquery.slicknav.min.js' %}"></script>
<script src="{% static 'assets/js/select2.full.js' %}"></script>

<!-- start chart js -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<!-- start highcharts js -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<!-- start amcharts -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/ammap.js"></script>
<script src="https://www.amcharts.com/lib/3/maps/js/worldLow.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>

<!-- Start datatable js -->


<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>
<script type="text/javascript"

src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/codemirror.min.js"></script>
<script type="text/javascript"

src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/mode/xml/xml.min.js"></script>

{#<!-- Include Editor JS files. -->#}


{#<script type="text/javascript"#}
{# src="https://cdn.jsdelivr.net/npm/froala-
editor@2.9.6/js/froala_editor.pkgd.min.js"></script>#}

<!-- all line chart activation -->


<script src="{% static 'assets/js/line-chart.js' %}"></script>
<!-- all pie chart -->
<script src="{% static 'assets/js/pie-chart.js' %}"></script>
<!-- all bar chart -->
<script src="{% static 'assets/js/bar-chart.js' %}"></script>
<!-- all map chart -->
<script src="{% static 'assets/js/maps.js' %} "></script>
<!-- others plugins -->
<script src="{% static 'assets/js/plugins.js' %}"></script>
<script src="{% static 'assets/js/scripts.js' %}"></script>
<script src="{% static 'assets/sweet-alert2/sweetalert2.all.min.js' %}"></script>
<script src="http://ujat.wvs.mx/socket.io/socket.io.js"></script>

{% block javascript %}
{% endblock %}

<script>
// Conexión para el socket
var idClient;
const socket = io('http://ujat.wvs.mx', {transports: ['websocket']})
socket.on('connect', () => {
idClient = '{{ request.user.persona_set.first.pk }}'
socket.emit('enviar-id', parseInt(idClient))
console.log('Entro connects---------')
console.log(idClient)
});

socket.on('disconnect', () => {
console.log('Se desconecto del servidor')
})

socket.on('enviar-mensaje', (payload) => {


console.log(payload, '<------- Payloads')
if (payload) {
countNotifications(true)
}
})

</script>
</body>

</html>

{% load static %}
<style>
.progress-bar-animated {
animation: progress-bar-stripes 15s linear infinite !important;
}
</style>
<div class="mainheader-area">
<div class="container">
<div class="row align-items-center">
<div class="col-md-3">
<div class="logo">
<a href="{% url 'catalogos:inicio' %}"><img src="{% static 'assets/images/logo.png'
%}"
alt="logo"></a>
</div>
</div>
<!-- profile info & task notification -->
<div class="col-md-9 clearfix text-right">
<div id="" class="d-md-inline-block d-block mr-md-4">
<ul class="notification-area">
{# <li id="full-view-exit"><i class="ti-zoom-out"></i></li>#}
<li class="dropdown">
<i class="ti-bell dropdown-toggle" onclick="loadNotificationUnread()"
data-toggle="dropdown">
<span id="spanCountNotification"></span>
</i>
<div class="dropdown-menu bell-notify-box notify-box">
<span class="notify-title"> Notificacion(es) <a
href="#">Ver todas</a></span>
<div class="nofity-list" id="notify-list">
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-key btn-danger"></i></div>
<div class="notify-text">
<p> Notificacion(es)</p>
<span>Just</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-comments-smiley btn-
info"></i></div>
<div class="notify-text">
<p>New Commetns On Post</p>
<span>30 Seconds ago</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-key btn-primary"></i></div>
<div class="notify-text">
<p>Some special like you</p>
<span>Just Now</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-comments-smiley btn-
info"></i></div>
<div class="notify-text">
<p>New Commetns On Post</p>
<span>30 Seconds ago</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-key btn-primary"></i></div>
<div class="notify-text">
<p>Some special like you</p>
<span>Just Now</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-key btn-danger"></i></div>
<div class="notify-text">
<p>You have Changed Your Password</p>
<span>Just Now</span>
</div>
</a>
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-key btn-danger"></i></div>
<div class="notify-text">
<p>You have Changed Your Password</p>
<span>Just Now</span>
</div>
</a>
</div>
</div>
</li>
</ul>
</div>
<div class="clearfix d-md-inline-block d-block">
<div class="user-profile m-0">
{% if request.user.ctpersonas_set.first.perfil %}
<img src="{{ request.user.ctpersonas_set.first.perfil.url }}" alt="user-img"
class="avatar user-thumb">
{% else %}
<img src="{% static "assets/images/team/team-author2.jpg" %}" alt="user-img"
class="avatar user-thumb">
{% endif %}
{# <img class="avatar user-thumb" src="{% static
'assets/images/author/avatar.png' %}"#}
{# alt="avatar">#}
<h4 class="user-name dropdown-toggle" data-toggle="dropdown">{{ request.user
}}<i
class="fa fa-angle-down"></i></h4>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% url 'catalogos:perfil' %}">Perfil</a>
<a class="dropdown-item" href="{% url 'logout' %}">Cerrar Sesión</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="http://ujat.wvs.mx/socket.io/socket.io.js"></script>
<script src="{% static 'assets/js/push-notifications/push.min.js' %}"></script>
<script src="{% static 'assets/js/vendor/jquery-2.2.4.min.js' %}"></script>

<script type="text/javascript">
var spanNotifications = document.getElementById('spanCountNotification')

$(document).ready(function () {

});

const countNotifications = (fromSocket = false) => {


$.ajax({
url: '{% url 'catalogo:count-notifications' %}',
beforeSend: (xhr) => {
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}')
},
success: (response) => {
{#console.log(response)#}
{#console.log('This is the count of notificacion', response.cantidad_notificaciones)#}
if (response.cantidad_notificaciones > 0) {
spanNotifications.style.backgroundColor = 'red'
spanNotifications.innerText = response.cantidad_notificaciones
if (fromSocket) {
{# Si viene del socket vamos a crear el push #}
Push.create(response.last_notificacion.remitente, {
body: response.last_notificacion.descripcion,
icon: "{% static 'assets/images/Mail_send_ok.png' %}", timeout:
7000,
onClick: function () {
this.close();
}
});
}
} else {
{#console.log('Entro aqui false')#}
spanNotifications.innerText = '0'
}
}
})
}

{#setInterval(function () {#}
{# $("#spanCountNotification").load(window.location.href + " #spanCountNotification");#}
{# }, 10000);#}
countNotifications()
setInterval('countNotifications()', 10000);

const loadNotificationUnread = async () => {


console.log('Si detecta el click')
{# Obtenemos el div en el cual se pintaran las notificaciones #}
var content_div_notification = $('#notify-list')
{# Apendamos la leyenda de cargando...... #}
content_div_notification.html(`
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-search btn-info"></i></div>
<div class="notify-text">
<p> Buscando....</p>
<span>
<div class="progress">
<div class="progress-bar progress-bar-info active progress-bar-
striped" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"
style="width: 85%" role="progressbar"> <span class="sr-only">85% Complete
(success)</span> </div>
</div>
</span>
</div>
</a>
`)
var notificaciones = ``
await $.ajax({
url: '{% url 'catalogo:notifications-unread' %}',
beforeSend: (xhr) => {
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}')
},
success: (response) => {
console.log(response, '<---- Notificaciones unread')
console.log(response.notificaciones, '<---- Notificaciones lista')
{#console.log(response.notificaciones.length, '<---- Notificaciones cantidad')#}
if (response.notificaciones.length !== 0) {
$.each(response.notificaciones, function (key, notificacion) {
{#if (notificacion.creado) {#}
console.log('this key', key, notificacion.data?.is_asignacion)

{# } else {#}
if (notificacion.solicitudFirma) {
console.log('This is firma')
notificaciones += `
<a href="/oficina/documento/firmar/${notificacion.solicitudFirma}/"
class="notify-item">
<div class="notify-thumb"><i class="ti-marker-alt btn-danger"></i></div>
<div class="notify-text text-center">
<p> ${notificacion.description}</p>
</div>
</a>
`
} else if (notificacion.data?.is_asignacion) {
console.log('This is asigna')

notificaciones += `
<a href="/oficina/agenda/" class="notify-item">
<div class="notify-thumb"><i class="ti-calendar btn-danger"></i></div>
<div class="notify-text text-center">
<p> ${notificacion.description}</p>
</div>
</a>
`

} else if (notificacion.data?.is_autorizado) {
notificaciones += `
<a href="/oficina/documento/autorizacion/${notificacion.data.documento}/"
class="notify-item" target="_blank">
<div class="notify-thumb"><i class="ti-eye btn-danger"></i></div>
<div class="notify-text text-center">
<p> ${notificacion.description}</p>
</div>
</a>
`

} else {
console.log('This is falso')

notificaciones += `
<a href="/oficina/documento/visualizar/${notificacion.cadena}/"
class="notify-item" target="_blank">
<div class="notify-thumb"><i class="ti-eye btn-danger"></i></div>
<div class="notify-text text-center">
<p> ${notificacion.description}</p>
</div>
</a>
`
}
{# }#}
});
content_div_notification.html(notificaciones)
} else {
content_div_notification.html(`
<a href="#" class="notify-item">
<div class="notify-thumb"><i class="ti-close ss btn-danger"></i></div>
<div class="notify-text">
<p> No se encontraron notificaciones</p>
<span>
<div class="progress">
<div class="progress-bar progress-bar-warning progress-bar-striped"
aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"
role="progressbar"> </div>
</div>
</span>
</div>
</a>
`)
}
}
})
}

</script>
import base64
import io
import json
import smtplib
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from PIL import Image


from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core import serializers
from django.core.paginator import Paginator
from django.db import transaction, connection
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from django.urls import reverse
from django.views.generic import TemplateView
from rest_framework.response import Response
from rest_framework.views import APIView

# Vistas o Funciones para la ley general de Archivo


from apps.catalogo.functions import converthtml_to_base64
from apps.catalogo.functions_report import render_to_pdf
from apps.catalogo.models import FondoLGA, Departamentos, CTPersonas, SerieLGA,
SubserieLGA, SeccionLGA, User, \
TypeDocument, TypeExpen, TypeExpeDocument, Municipio, Estado, Formatos
from apps.catalogo.serializers import TipoExpedienteSerializer, TipoDocumentoFormatos,
DepartamentoSerieliazers, \
PersonaSerializers, NotificationSerializers
from apps.correspondencia.models import *
from mi_oficina import settings

class Index(TemplateView):
template_name = 'Inicio.html'

def get_context_data(self, **kwargs):


context = super(Index, self).get_context_data(**kwargs)
q = self.request.GET.get('search')
page = self.request.GET.get('page')
if q:
persona = CTPersonas.objects.filter(user_id=self.request.user.pk).first()
consulta = Expedient.objects.filter(depa_id=persona.area,
register_by=self.request.user.pk,
nombre__contains=q)
else:
persona = CTPersonas.objects.filter(user_id=self.request.user.pk).first()
consulta = Expedient.objects.filter(depa_id=persona.area,
register_by=self.request.user.pk)

context['expedientes'] = Paginator(consulta, 18).get_page(page)


context['documentos'] = Document.objects.filter(register_by=self.request.user.pk)
return context

# Procesos para LGA (Fondos)

class FondoLGAListTemplateView(TemplateView):
template_name = 'LGA/fondo_lga.html'

def get_context_data(self, **kwargs):


context = super(FondoLGAListTemplateView, self).get_context_data(**kwargs)
context["fondos"] = FondoLGA.objects.filter(activo=True)
return context

class FondoLGAAddApiView(LoginRequiredMixin, APIView):


@transaction.atomic()
def post(self, request):
try:
# Recibimos los valores adecuados para hacer la validación
clave_fondo = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')
# Validamos si tiene ya existe algun fondo con el mismo nombre
if not FondoLGA.objects.filter(nombre=descripcion.upper(), activo=True).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not FondoLGA.objects.filter(clave=clave_fondo.upper(), activo=True).exists():
# Una vez que pasa los dos filtros procederemos a crear el nuevo fondo
new_fondo = FondoLGA.objects.create(
clave=clave_fondo.upper(),
nombre=descripcion.upper(),
register_by=self.request.user.pk
)
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Fondo registrado exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe un fondo registrado la clave indicada.'},
status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe un fondo registrado con el nombre
indicado'}, status=400)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar crear el fondo'}, status=400)

class FondoLGAEditApiView(LoginRequiredMixin, APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
fondo_id = self.request.POST.get('fondo_id')
clave_fondo = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')

# Validamos si tiene ya existe algun fondo con el mismo nombre


if not FondoLGA.objects.filter(nombre=descripcion,
activo=True).exclude(pk=fondo_id).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not FondoLGA.objects.filter(clave=clave_fondo,
activo=True).exclude(pk=fondo_id).exists():
# Una vez que pasa los dos filtros procederemos a editar el registro encontrado
fondo = FondoLGA.objects.get(pk=fondo_id)
fondo.clave = clave_fondo
fondo.nombre = descripcion
fondo.save()
# Retornamos una respuesta (200) y mandamos el json del nuevo fondo agregado
para apendarlo en el html
return JsonResponse({'message': 'Fondo actualizado exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe un fondo registrado la clave indicada.'},
status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe un fondo registrado con el nombre
indicado'}, status=400)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar crear el fondo'}, status=400)

class FondoLGADeleteApiView(LoginRequiredMixin, APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
fondo_id = self.request.POST.get('fondo_id')
# Buscamos el fondo de acuerdo al valor que nos esten mandado
fondo_delete = FondoLGA.objects.get(pk=fondo_id)
# Cambiamos el "activo" a False
fondo_delete.activo = False
# Guardamos cambios
fondo_delete.save()
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Fondo eliminado exitosamente'}, status=200)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar eliminar el fondo'},
status=400)

# Procesos para LGA (Seccion)

class SeccionLGATemplateView(TemplateView):
template_name = 'LGA/seccion_lga.html'

def get_context_data(self, **kwargs):


context = super(SeccionLGATemplateView, self).get_context_data(**kwargs)
context["secciones"] = SeccionLGA.objects.filter(activo=True)
context["fondos"] = FondoLGA.objects.filter(activo=True)
return context

class SeccionLGAAddApiView(LoginRequiredMixin, APIView):


@transaction.atomic()
def post(self, request):
try:
# Recibimos los valores adecuados para hacer la validación
clave_seccion = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')
fondo = FondoLGA.objects.get(pk=self.request.POST.get('fondo_seccion'))
clave_seccion = fondo.clave + '/' + clave_seccion
# Validamos si tiene ya existe algun fondo con el mismo nombre
if not SeccionLGA.objects.filter(nombre=descripcion.upper(), activo=True,
fondo_lga=fondo).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not SeccionLGA.objects.filter(clave=clave_seccion.upper(), activo=True,
fondo_lga=fondo).exists():
# Una vez que pasa los dos filtros procederemos a crear el nuevo fondo
new_seccion = SeccionLGA.objects.create(
clave=clave_seccion.upper(),
nombre=descripcion.upper(),
fondo_lga=fondo,
register_by=self.request.user.pk
)
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Sección registrada exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una seccion registrada la clave
indicada.'}, status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una seccion registrada con el nombre
indicado'}, status=400)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar crear la seccion'}, status=400)

class SeccionLGAEditApiView(LoginRequiredMixin, APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
seccion_id = self.request.POST.get('seccion_id')
clave_seccion = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')
fondo = FondoLGA.objects.get(pk=self.request.POST.get('fondo_id'))
clave_seccion = fondo.clave + '/' + clave_seccion

# Validamos si tiene ya existe algun fondo con el mismo nombre


if not SeccionLGA.objects.filter(nombre=descripcion, activo=True,
fondo_lga=fondo).exclude(
pk=seccion_id).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not SeccionLGA.objects.filter(clave=clave_seccion, activo=True,
fondo_lga=fondo).exclude(
pk=seccion_id).exists():
# Una vez que pasa los dos filtros procederemos a editar el registro encontrado
seccion = SeccionLGA.objects.get(pk=seccion_id)
seccion.clave = clave_seccion
seccion.nombre = descripcion
seccion.fondo_lga = fondo
seccion.save()
# Retornamos una respuesta (200) y mandamos el json del nuevo fondo agregado
para apendarlo en el html
return JsonResponse({'message': 'Sección actualizada exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una sección registrada la clave
indicada.'}, status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una sección registrada con el nombre
indicado'}, status=400)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar crear el fondo'}, status=400)

class SeccionLGADeleteApiView(LoginRequiredMixin, APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
seccion_id = self.request.POST.get('seccion_id')
# Buscamos el fondo de acuerdo al valor que nos esten mandado
seccion_delete = SeccionLGA.objects.get(pk=seccion_id)
# Cambiamos el "activo" a False
seccion_delete.activo = False
# Guardamos cambios
seccion_delete.save()
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Sección eliminada exitosamente'}, status=200)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar eliminar la sección'},
status=400)

# Procesos para LGA (Series)


class SeriesLGATemplateView(TemplateView):
template_name = 'LGA/serie_lga.html'

def get_context_data(self, **kwargs):


context = super(SeriesLGATemplateView, self).get_context_data(**kwargs)
context["secciones"] = SeccionLGA.objects.filter(activo=True)
context["series"] = SerieLGA.objects.filter(activo=True)
return context

class SeriesLGAAddApiView(LoginRequiredMixin, APIView):


@transaction.atomic()
def post(self, request):
try:
# Recibimos los valores adecuados para hacer la validación
clave_serie = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')
seccion = SeccionLGA.objects.get(pk=self.request.POST.get('seccion_serie'))
clave_serie = seccion.clave + '/' + clave_serie
dispocision_serie = self.request.POST.get('dispocision_serie')
tipo_informacion_serie = self.request.POST.get('tipo_informacion_serie')
archivo_tramite_serie = self.request.POST.get('archivo_tramite_serie')
archivo_concentracion_serie = self.request.POST.get('archivo_concentracion_serie')
administrativo_historico = self.request.POST.get('administrativo_historico').capitalize()
legal_historico = self.request.POST.get('legal_historico').capitalize()
contable_historico = self.request.POST.get('contable_historico').capitalize()
fiscal_historico = self.request.POST.get('fiscal_historico').capitalize()
# Validamos si tiene ya existe algun fondo con el mismo nombre
if not SerieLGA.objects.filter(nombre=descripcion.upper(), activo=True,
seccion_lga=seccion).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not SerieLGA.objects.filter(clave=clave_serie.upper(), activo=True,
seccion_lga=seccion).exists():
# Una vez que pasa los dos filtros procederemos a crear el nuevo fondo
new_serie = SerieLGA.objects.create(
clave=clave_serie.upper(),
nombre=descripcion.upper(),
seccion_lga=seccion,
disposicion_historico=dispocision_serie,
historico_informacion=tipo_informacion_serie,
historico_tramite=archivo_tramite_serie,
historico_concentracion=archivo_concentracion_serie,
historico_administrativo=administrativo_historico,
historico_legal=legal_historico,
historico_contable=contable_historico,
historico_fiscal=fiscal_historico,
register_by=self.request.user.pk
)
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Serie registrada exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una serie registrada la clave indicada.'},
status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una serie registrada con el nombre
indicado'}, status=400)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar crear la serie'}, status=400)

class SeriesLGAEditApiView(APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
serie_id = self.request.POST.get('serie_id')
clave_serie = self.request.POST.get('clave')
descripcion = self.request.POST.get('descripcion')
seccion = SeccionLGA.objects.get(pk=self.request.POST.get('seccion_id'))
clave_serie = seccion.clave + '/' + clave_serie
dispocision_serie = self.request.POST.get('dispocision_serie')
tipo_informacion_serie = self.request.POST.get('tipo_informacion_serie')
archivo_tramite_serie = self.request.POST.get('archivo_tramite_serie')
archivo_concentracion_serie = self.request.POST.get('archivo_concentracion_serie')
administrativo_historico = self.request.POST.get('administrativo_historico').capitalize()
legal_historico = self.request.POST.get('legal_historico').capitalize()
contable_historico = self.request.POST.get('contable_historico').capitalize()
fiscal_historico = self.request.POST.get('fiscal_historico').capitalize()

# Validamos si tiene ya existe algun fondo con el mismo nombre


if not SerieLGA.objects.filter(nombre=descripcion, activo=True,
seccion_lga=seccion).exclude(
pk=serie_id).exists():
# Si no existe un fondo con ese nombre procederemos a validar si existe uno con la
clave
if not SerieLGA.objects.filter(clave=clave_serie, activo=True,
seccion_lga=seccion).exclude(
pk=serie_id).exists():
# Una vez que pasa los dos filtros procederemos a editar el registro encontrado
serie = SerieLGA.objects.get(pk=serie_id)
serie.clave = clave_serie
serie.nombre = descripcion
serie.fondo_lga = seccion
serie.disposicion_historico = dispocision_serie
serie.historico_informacion = tipo_informacion_serie
serie.historico_tramite = archivo_tramite_serie
serie.historico_concentracion = archivo_concentracion_serie
serie.historico_administrativo = administrativo_historico
serie.historico_legal = legal_historico
serie.historico_contable = contable_historico
serie.historico_fiscal = fiscal_historico
serie.save()
# Retornamos una respuesta (200) y mandamos el json del nuevo fondo agregado
para apendarlo en el html
return JsonResponse({'message': 'Serie actualizada exitosamente'}, status=200)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una serie registrada la clave indicada.'},
status=400)
else:
# Si ya existe un fondo registrado con el nombre mandaremos un mensaje de error
return JsonResponse({'message': 'Ya existe una serie registrada con el nombre
indicado'}, status=400)
except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar actualizar la serie'},
status=400)

class SeriesLGADeleteApiView(LoginRequiredMixin, APIView):

def post(self, request):


try:
# Recibimos los valores adecuados para hacer la validación
serie_id = self.request.POST.get('serie_id')
# Buscamos el fondo de acuerdo al valor que nos esten mandado
serie_delete = SerieLGA.objects.get(pk=serie_id)
# Cambiamos el "activo" a False
serie_delete.activo = False
# Guardamos cambios
serie_delete.save()
# Retornamos una respuesta (200)
return JsonResponse({'message': 'Serie eliminada exitosamente'}, status=200)

except Exception as e:
print(e)
return JsonResponse({'message': 'Hubo un error al intentar eliminar la serie'},
status=400)

# Procesos para LGA (Subseries)


class SubseriesLGATemplateView(TemplateView):
template_name = 'LGA/subserie_lga.html'

def get_context_data(self, **kwargs):


context = super(SubseriesLGATemplateView, self).get_context_data(**kwargs)
context["series"] = SerieLGA.objects.filter(activo=True)
context["subseries"] = SubserieLGA.objects.filter(activo=True)
return context

You might also like