se modifica estructura de base de datos

develop/Rodrigo/Backend
Francisco Sandoval 2023-08-27 11:08:46 -04:00
parent 0f00441d12
commit 53849df320
10 changed files with 206 additions and 111 deletions

View File

@ -62,20 +62,33 @@ class Funcionario(models.Model):
class GtfsCalendar(models.Model): class GtfsCalendar(models.Model):
id_linea = models.CharField(primary_key=True, max_length=150) service_id = models.CharField(primary_key=True, max_length=150)
monday = models.BooleanField(blank=True, null=True) monday = models.BooleanField(blank=True, null=True)
tuesday = models.BooleanField(blank=True, null=True) tuesday = models.BooleanField(blank=True, null=True)
wednesday = models.BooleanField(blank=True, null=True) wednesday = models.BooleanField(blank=True, null=True)
thursday = models.BooleanField(blank=True, null=True) thursday = models.BooleanField(blank=True, null=True)
friday = models.BooleanField(blank=True, null=True) friday = models.BooleanField(blank=True, null=True)
salurday = models.BooleanField(blank=True, null=True) saturday = models.BooleanField(blank=True, null=True)
sunday = models.BooleanField(blank=True, null=True) sunday = models.BooleanField(blank=True, null=True)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
db_table = 'gtfs_calendar' db_table = 'gtfs_calendar'
class GtfsCalendarDates(models.Model):
service_id = models.DecimalField(primary_key=True, max_digits=8, decimal_places=0) # The composite primary key (service_id, date) found, that is not supported. The first column is selected.
date = models.CharField(max_length=10)
exception_type = models.DecimalField(max_digits=2, decimal_places=0, blank=True, null=True)
class Meta:
managed = False
db_table = 'gtfs_calendar_dates'
unique_together = (('service_id', 'date'),)
class GtfsFrequencie(models.Model): class GtfsFrequencie(models.Model):
id_trip = models.ForeignKey('GtfsTrips', models.DO_NOTHING, db_column='id_trip', blank=True, null=True) id_trip = models.ForeignKey('GtfsTrips', models.DO_NOTHING, db_column='id_trip', blank=True, null=True)
start_time = models.TimeField(blank=True, null=True) start_time = models.TimeField(blank=True, null=True)
@ -89,7 +102,7 @@ class GtfsFrequencie(models.Model):
class GtfsRouteType(models.Model): class GtfsRouteType(models.Model):
id_route_type = models.IntegerField(primary_key=True) id_route_type = models.DecimalField(primary_key=True, max_digits=2, decimal_places=0)
descripcion = models.CharField(max_length=100, blank=True, null=True) descripcion = models.CharField(max_length=100, blank=True, null=True)
class Meta: class Meta:
@ -97,43 +110,18 @@ class GtfsRouteType(models.Model):
db_table = 'gtfs_route_type' db_table = 'gtfs_route_type'
class GtfsRoutes(models.Model):
id_routes = models.IntegerField(primary_key=True)
id_operador = models.ForeignKey('Operador', models.DO_NOTHING, db_column='id_operador', blank=True, null=True)
id_route_type = models.ForeignKey(GtfsRouteType, models.DO_NOTHING, db_column='id_route_type', blank=True, null=True)
short_name = models.CharField(max_length=100, blank=True, null=True)
long_name = models.CharField(max_length=300, blank=True, null=True)
descripcion = models.CharField(max_length=500, blank=True, null=True)
route_color = models.CharField(max_length=6, blank=True, null=True)
route_text_color = models.CharField(max_length=6, blank=True, null=True)
route_sort_order = models.IntegerField(blank=True, null=True)
route_id = models.IntegerField(blank=True, null=True)
agency_id = models.CharField(max_length=50, blank=True, null=True)
route_short_name = models.CharField(max_length=50, blank=True, null=True)
route_long_name = models.CharField(max_length=50, blank=True, null=True)
route_desc = models.CharField(max_length=50, blank=True, null=True)
route_type = models.IntegerField(blank=True, null=True)
route_url = models.CharField(max_length=50, blank=True, null=True)
class Meta:
managed = False
db_table = 'gtfs_routes'
class GtfsShape(models.Model): class GtfsShape(models.Model):
id_shape = models.DecimalField(max_digits=18, decimal_places=0) id_shape = models.DecimalField(max_digits=18, decimal_places=0)
shape_pt_lat = models.FloatField(blank=True, null=True) shape_pt_lat = models.FloatField(blank=True, null=True)
shape_pt_lon = models.FloatField(blank=True, null=True) shape_pt_lon = models.FloatField(blank=True, null=True)
shape_pt_sequence = models.IntegerField(blank=True, null=True) shape_pt_sequence = models.IntegerField(blank=True, null=True)
shaoe_dist_traveled = models.FloatField(blank=True, null=True) shape_dist_traveled = models.FloatField(blank=True, null=True)
id_gtfs_pk = models.AutoField(primary_key=True)
class Meta: class Meta:
managed = False managed = False
db_table = 'gtfs_shape' db_table = 'gtfs_shape'
unique_together = (('id_shape','shape_pt_sequence'),) unique_together = (('id_shape', 'shape_dist_traveled'),)
def __str__(self):
return f"{self.id_shape}-{self.shape_pt_sequence}"
class GtfsStopTimes(models.Model): class GtfsStopTimes(models.Model):
@ -151,13 +139,14 @@ class GtfsStopTimes(models.Model):
class GtfsTrips(models.Model): class GtfsTrips(models.Model):
id_trip = models.CharField(primary_key=True, max_length=150) id_trip = models.CharField(primary_key=True, max_length=150)
id_routes = models.ForeignKey(GtfsRoutes, models.DO_NOTHING, db_column='id_routes', blank=True, null=True)
id_linea = models.CharField(max_length=150, blank=True, null=True) id_linea = models.CharField(max_length=150, blank=True, null=True)
id_shapes = models.IntegerField(blank=True, null=True) id_shape = models.IntegerField(blank=True, null=True)
id_trip_regreso = models.ForeignKey('self', models.DO_NOTHING, db_column='id_trip_regreso', blank=True, null=True) id_trip_regreso = models.ForeignKey('self', models.DO_NOTHING, db_column='id_trip_regreso', blank=True, null=True)
trip_headsign = models.CharField(max_length=100, blank=True, null=True) trip_headsign = models.CharField(max_length=100, blank=True, null=True)
short_name = models.CharField(max_length=100, blank=True, null=True) trip_short_name = models.CharField(max_length=100, blank=True, null=True)
direccion_id = models.IntegerField(blank=True, null=True) direction_id = models.IntegerField(blank=True, null=True)
service_id = models.DecimalField(max_digits=8, decimal_places=0, blank=True, null=True, db_comment='de calendario')
block_id = models.CharField(max_length=50, blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
@ -165,16 +154,15 @@ class GtfsTrips(models.Model):
class Linea(models.Model): class Linea(models.Model):
id_linea = models.CharField(max_length=150) id_linea = models.CharField(max_length=150, primary_key=True)
service_id = models.CharField(max_length=150, blank=True, null=True) id_operador = models.ForeignKey('Operador', models.DO_NOTHING, db_column='id_operador', blank=True, null=True)
trip_id = models.CharField(primary_key=True, max_length=150, blank=False, null=False) route_short_name = models.CharField(max_length=150, blank=True, null=True)
trip_headsign = models.CharField(max_length=150, blank=True, null=True) route_desc = models.CharField(max_length=150, blank=True, null=True)
trip_short_name = models.CharField(max_length=150, blank=True, null=True) route_type = models.ForeignKey(GtfsRouteType, models.DO_NOTHING, db_column='route_type', blank=True, null=True)
direction_id = models.CharField(max_length=150, blank=True, null=True) route_url = models.CharField(max_length=150, blank=True, null=True)
block_id = models.CharField(max_length=150, blank=True, null=True) route_color = models.CharField(max_length=150, blank=True, null=True)
shape_id = models.CharField(max_length=150, blank=True, null=True) route_text_color = models.CharField(max_length=150, blank=True, null=True)
wheelchair_accessible = models.CharField(max_length=150, blank=True, null=True) route_long_name = models.CharField(max_length=200, blank=True, null=True)
bikes_allowed = models.CharField(max_length=150, blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
@ -186,6 +174,11 @@ class Operador(models.Model):
id_region = models.ForeignKey('Region', models.DO_NOTHING, db_column='id_region', blank=True, null=True) id_region = models.ForeignKey('Region', models.DO_NOTHING, db_column='id_region', blank=True, null=True)
vigente = models.BooleanField(blank=True, null=True) vigente = models.BooleanField(blank=True, null=True)
nombre_operador = models.CharField(max_length=150, blank=True, null=True) nombre_operador = models.CharField(max_length=150, blank=True, null=True)
agency_url = models.CharField(max_length=200, blank=True, null=True)
agency_timezone = models.CharField(max_length=200, blank=True, null=True)
agency_lang = models.CharField(max_length=50, blank=True, null=True)
agency_phone = models.CharField(max_length=50, blank=True, null=True)
agency_fare_url = models.CharField(max_length=50, blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
@ -202,6 +195,12 @@ class Paradero(models.Model):
stop_desc = models.CharField(max_length=300, blank=True, null=True) stop_desc = models.CharField(max_length=300, blank=True, null=True)
stop_lat = models.FloatField(blank=True, null=True) stop_lat = models.FloatField(blank=True, null=True)
stop_lon = models.FloatField(blank=True, null=True) stop_lon = models.FloatField(blank=True, null=True)
zone_id = models.CharField(max_length=200, blank=True, null=True)
stop_url = models.CharField(max_length=200, blank=True, null=True)
location_type = models.CharField(max_length=200, blank=True, null=True)
parent_station = models.CharField(max_length=200, blank=True, null=True)
stop_timezonene_id = models.CharField(max_length=200, blank=True, null=True)
wheelchair_boarding = models.DecimalField(max_digits=2, decimal_places=0, blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
@ -333,10 +332,10 @@ class TipoVehiculo(models.Model):
class Usuario(models.Model): class Usuario(models.Model):
login = models.CharField(primary_key=True, max_length=20) login = models.CharField(primary_key=True, max_length=60)
rut = models.ForeignKey(Persona, models.DO_NOTHING, db_column='rut', blank=True, null=True) rut = models.ForeignKey(Persona, models.DO_NOTHING, db_column='rut', blank=True, null=True)
clave = models.CharField(max_length=20, blank=True, null=True)
vigente = models.BooleanField(blank=True, null=True) vigente = models.BooleanField(blank=True, null=True)
superuser = models.BooleanField(blank=True, null=True)
class Meta: class Meta:
managed = False managed = False
@ -356,6 +355,18 @@ class Usuario(models.Model):
super().save(*args, **kwargs) super().save(*args, **kwargs)
class UsuarioClave(models.Model):
login = models.OneToOneField(Usuario, models.DO_NOTHING, db_column='login', primary_key=True)
clave = models.CharField(max_length=60, blank=True, null=True)
clave_anterior = models.CharField(max_length=60, blank=True, null=True)
fecha_modificacion = models.DateField(blank=True, null=True)
codigo = models.DecimalField(max_digits=8, decimal_places=0, blank=True, null=True)
class Meta:
managed = False
db_table = 'usuario_clave'
class UsuarioRol(models.Model): class UsuarioRol(models.Model):
login = models.ForeignKey(Usuario, models.DO_NOTHING, db_column='login', blank=True, null=True) login = models.ForeignKey(Usuario, models.DO_NOTHING, db_column='login', blank=True, null=True)
id_rol = models.ForeignKey(Rol, models.DO_NOTHING, db_column='id_rol', blank=True, null=True) id_rol = models.ForeignKey(Rol, models.DO_NOTHING, db_column='id_rol', blank=True, null=True)

View File

@ -54,6 +54,11 @@ class ParaderoSerializer(serializers.ModelSerializer):
model = models.Paradero model = models.Paradero
fields = '__all__' fields = '__all__'
class OperadorSerializer(serializers.ModelSerializer):
class Meta:
model = models.Operador
fields = '__all__'
class LineaSerializer(serializers.ModelSerializer): class LineaSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = models.Linea model = models.Linea

View File

@ -2,7 +2,7 @@ from django.urls import path, include
from rest_framework import routers from rest_framework import routers
# from api import views # from api import views
from api.views import usuario, auth, aplicacion, tipo, persona, comuna, region, paradero from api.views import usuario, auth, aplicacion, tipo, persona, comuna, region, paradero
from api.views import mapa, linea from api.views import mapa, linea, operador
router = routers.DefaultRouter() router = routers.DefaultRouter()
router.register('aplicaciones', aplicacion.AplicacionViewSet) router.register('aplicaciones', aplicacion.AplicacionViewSet)
@ -17,6 +17,7 @@ router.register('comunas', comuna.ComunaViewSet)
router.register('regiones', region.RegionViewSet) router.register('regiones', region.RegionViewSet)
router.register('paraderos', paradero.ParaderoViewSet) router.register('paraderos', paradero.ParaderoViewSet)
router.register('lineas', linea.LineaViewSet) router.register('lineas', linea.LineaViewSet)
router.register('operadores', operador.OperadorViewSet)
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path('', include(router.urls)),

View File

@ -10,6 +10,7 @@ from decouple import config
import json import json
import jwt import jwt
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging
private_key = config('SECRET_JWT') private_key = config('SECRET_JWT')
@ -21,6 +22,8 @@ private_key = config('SECRET_JWT')
def jwt_login(request): def jwt_login(request):
if request.method == 'POST': if request.method == 'POST':
count = models.Usuario.objects.filter(vigente = True).count() count = models.Usuario.objects.filter(vigente = True).count()
logging.error(f'count usuario vigente = {count}')
# validar username y password # validar username y password
input = json.loads(request.body) input = json.loads(request.body)
username = input['username'] username = input['username']
@ -35,7 +38,9 @@ def jwt_login(request):
if not usuario: if not usuario:
return HttpResponse('Acceso no valido', status=400) return HttpResponse('Acceso no valido', status=400)
if usuario['clave'] != password: if username != '0':
clave = models.UsuarioClave.objects.filter(login = username).first()
if not clave or clave.clave != password:
return HttpResponse('Acceso no valido', status=400) return HttpResponse('Acceso no valido', status=400)
ahora = datetime.utcnow() ahora = datetime.utcnow()

View File

@ -7,11 +7,3 @@ from .. import models, serializers
class LineaViewSet(viewsets.ModelViewSet): class LineaViewSet(viewsets.ModelViewSet):
queryset = models.Linea.objects.all() queryset = models.Linea.objects.all()
serializer_class = serializers.LineaSerializer serializer_class = serializers.LineaSerializer
@action(detail=False, methods=['GET'])
def servicios(self, request):
distinct_values = models.Linea.objects \
.values('id_linea', 'service_id', 'direction_id', 'trip_headsign') \
.order_by('id_linea', 'service_id', 'direction_id') \
.distinct()
return Response(distinct_values)

View File

@ -3,7 +3,7 @@ from django.http import JsonResponse
from rest_framework.decorators import action, api_view, schema from rest_framework.decorators import action, api_view, schema
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from ..models import Paradero, ParaderoImagen from ..models import Paradero, ParaderoImagen
from ..models import Linea, GtfsShape from ..models import Linea, GtfsShape, GtfsTrips
from .paradero import url_image_paradero from .paradero import url_image_paradero
from logging import error from logging import error
@ -44,22 +44,20 @@ def paraderos(request):
@api_view(['GET']) @api_view(['GET'])
def rutas(request): def rutas(request):
id_linea = request.GET.get('id_linea') id_linea = request.GET.get('id_linea')
service_id = request.GET.get('service_id')
direction_id = request.GET.get('direction_id')
linea = Linea.objects \ sectores = GtfsTrips.objects.filter(id_linea = id_linea).all()
.filter(id_linea = id_linea, service_id = service_id, direction_id = direction_id) \ data = []
.values('shape_id') \ for s in sectores:
.first() rutas = GtfsShape.objects.filter(id_shape = s.id_shape).order_by('shape_pt_sequence')
for r in rutas:
rutas = [] data.append({
if linea: 'shape_pt_lat': r.shape_pt_lat,
rutas = GtfsShape.objects \ 'shape_pt_lon': r.shape_pt_lon,
.filter(id_shape = linea['shape_id']) \ 'shape_pt_sequence': r.shape_pt_sequence
.order_by('shape_pt_sequence') \ })
.values('shape_pt_lat','shape_pt_lon','shape_pt_sequence') data_ordenada = sorted(data, key=lambda k: k['shape_pt_sequence'])
return JsonResponse({ return JsonResponse({
'google_api_key': google_api_key, 'google_api_key': google_api_key,
'positions': list(rutas) 'positions': data_ordenada
}) })

View File

@ -0,0 +1,9 @@
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
from .. import models, serializers
class OperadorViewSet(viewsets.ModelViewSet):
queryset = models.Operador.objects.all()
serializer_class = serializers.OperadorSerializer

View File

@ -7,6 +7,8 @@ from rest_framework.response import Response
from .. import models, schemas, serializers from .. import models, schemas, serializers
import json import json
import datetime
import logging
class UsuarioViewSet(viewsets.ModelViewSet): class UsuarioViewSet(viewsets.ModelViewSet):
queryset = models.Usuario.objects.all() queryset = models.Usuario.objects.all()
@ -51,11 +53,83 @@ class UsuarioViewSet(viewsets.ModelViewSet):
usuario = models.Usuario( usuario = models.Usuario(
rut = persona, rut = persona,
login = input['login'], login = input['login'],
clave = input['clave'],
vigente = input.get('vigente', False), vigente = input.get('vigente', False),
) )
usuario.save() usuario.save()
logging.error(f'clave = {input["clave"]}')
if input['clave']:
logging.error('Modificar clave de usuario')
clave = models.UsuarioClave.objects.filter(login = usuario.login).first()
if clave:
logging.error('Clave Usuario ya existe')
clave.clave_anterior = clave.clave
clave.clave = input['clave']
clave.fecha_modificacion = datetime.datetime.now()
clave.save()
else:
logging.error('Clave Usuario se creará')
clave = models.UsuarioClave(
login = usuario.login,
clave = input['clave'],
fecha_modificacion = datetime.datetime.now()
)
clave.save()
return Response({
'rut': persona.rut,
'dv': persona.dv,
'nombres': persona.nombres,
'apellido_a': persona.apellido_a,
'apellido_b': persona.apellido_b,
'email': persona.email,
'login': usuario.login,
'vigente': usuario.vigente,
})
except ValueError as e:
transaction.rollback()
return HttpResponse(str(e), status = 400)
except Exception as e:
transaction.rollback()
print(e)
return HttpResponse(str(e), status = 500)
def update(self, request, *args, **kwargs):
input = json.loads(request.body)
logging.error(input)
try:
pk = input['rut']
with transaction.atomic():
# validaciones se realiza a nivel del model
persona = models.Persona.objects.filter(rut = pk).first()
usuario = models.Usuario.objects.filter(rut = pk).first()
usuario.vigente = input.get('vigente', False)
usuario.save()
logging.error(f'clave = {input["clave"]}')
if input['clave']:
logging.error('Modificar clave de usuario')
clave = models.UsuarioClave.objects.filter(login = usuario.login).first()
if clave:
logging.error('Clave Usuario ya existe')
clave.clave_anterior = clave.clave
clave.clave = input['clave']
clave.fecha_modificacion = datetime.datetime.now()
clave.save()
else:
logging.error('Clave Usuario se creará')
clave = models.UsuarioClave(
login = usuario,
clave = input['clave'],
fecha_modificacion = datetime.datetime.now()
)
clave.save()
return Response({ return Response({
'rut': persona.rut, 'rut': persona.rut,
'dv': persona.dv, 'dv': persona.dv,

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>...</title> <title>...</title>
<script type="module" crossorigin src="/assets/index-b482aa7b.js"></script> <script type="module" crossorigin src="/assets/index-a084edd6.js"></script>
<link rel="stylesheet" href="/assets/index-2d1bb0fd.css"> <link rel="stylesheet" href="/assets/index-2d1bb0fd.css">
</head> </head>
<body> <body>