def post(self): premio_json = request.get_json() # print(premio_json) premio = premio_schema.load(premio_json) try: p = PremioModel() if "nombre" in premio: p.nombre = premio["nombre"] if "puntos" in premio: p.puntos = premio["puntos"] if "codigo_barras" in premio: p.codigo_barras = premio["codigo_barras"] if "codigo_qr" in premio: p.codigo_qr = premio["codigo_qr"] if "imagen_icon" in premio: p.imagen_icon = premio["imagen_icon"] if "imagen_display" in premio: p.imagen_display = premio["imagen_display"] if "vidas" in premio: p.vidas = premio["vidas"] if "fecha_creacion" in premio: p.fecha_creacion = premio["fecha_creacion"] else: p.fecha_creacion = dt.datetime.now() if "fecha_vencimiento" in premio: p.fecha_vencimiento = premio["fecha_vencimiento"] # if "fecha_redencion" in premio: # p.fecha_redencion=premio["fecha_redencion"] # if "id_participante" in premio: # p.id_participante=premio["id_participante"] p.save() # Enviar a todos los participantes for participante in ParticipanteModel.objects.all(): premio = PremioParticipanteModel( id_premio=p._id, id_participante=participante._id, fecha_creacion=p.fecha_creacion, # fechas_redencion = [], estado=0).save() except ValidationError as exc: p.delete() print(exc.message) return { "message": "No se pudo crear el nuevo premio o enviar a los participantes solicitados." } return { 'message': "Premio creado", 'ObjectId': PremioSchema(only=("_id", )).dump(p) }, 200
def get(self, id): p = PremioModel.find_by_id(id) if not p: return {"message": "No se encontro el premio"}, 404 return PremioSchema(only=( "_id", "nombre", "puntos", "codigo_barras", "codigo_qr", "imagen_icon", "imagen_display", "fecha_creacion", "fecha_vigencia", "vidas", # "fechas_redencion", # "id_producto", # "id_participante" )).dump(p)
def put(self, id, accion): if accion == 'ninguna': n = NotificacionTemplateModel.find_by_id(id) if not n: return {"message": "No se encontro la notificación!"}, 404 noti_json = request.get_json() # pprint(noti_json["notificacion"]) noti = not_schema_template.load(noti_json["notificacion"]) try: if "tipo_notificacion" in noti: n.tipo_notificacion=noti["tipo_notificacion"] if "imagenIcon" in noti: n.imagenIcon=noti["imagenIcon"] if "titulo" in noti: n.titulo=noti["titulo"] if "fecha" in noti: n.fecha=noti["fecha"] if "bar_text" in noti: n.bar_text=noti["bar_text"] if "mensaje" in noti: n.mensaje=noti["mensaje"] if "link" in noti: n.link=noti["link"] n.save() except ValidationError as exc: print(exc.message) return {"message": "No se pudo actualizar la notificación."}, 404 return {"notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link", )).dump(n)}, 200 # /admin/notificaciones/<string:id> patch! ya existe! elif accion == 'premio': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro la notificacion"}, 404 noti_json = request.get_json() # pprint(noti_json["notificacion"]) noti = not_schema_template.load(noti_json["notificacion"]) # pprint(noti) try: if "tipo_notificacion" in noti: n.tipo_notificacion=noti["tipo_notificacion"] if "imagenIcon" in noti: n.imagenIcon=noti["imagenIcon"] if "titulo" in noti: n.titulo=noti["titulo"] if "fecha" in noti: n.fecha=noti["fecha"] if "bar_text" in noti: n.bar_text=noti["bar_text"] if "mensaje" in noti: n.mensaje=noti["mensaje"] if "link" in noti: n.link=noti["link"] # link no se debe actualizar, pero bueno! jaja n.save() except ValidationError as exc: print(exc.message) return {"message": "No se pudo actualizar la notificación."}, 404 p = PremioModel.find_by_id(n.link) if not p: return {"message": "No se encontro el premio"}, 404 # p_req = request.get_json() # pprint(p_req) premio = premio_schema.load(noti_json["premio"]) # pprint(p_req["premio"]) pprint(premio) try: if "nombre" in premio: p.nombre = premio["nombre"] if "puntos" in premio: p.puntos = premio["puntos"] if "codigo_barras" in premio: p.codigo_barras = premio["codigo_barras"] if "codigo_qr" in premio: p.codigo_barras = premio["codigo_barras"] if "imagen_icon" in premio: p.imagen_icon = premio["imagen_icon"] if "imagen_display" in premio: p.imagen_icon = premio["imagen_icon"] if "fecha_creacion" in premio: p.imagen_icon = premio["imagen_icon"] if "fecha_vigencia" in premio: p.fecha_vigencia = premio["fecha_vigencia"] if "fecha_redencion" in premio: p.fecha_redencion = premio["fecha_redencion"] p.save() except ValidationError as exc: print(exc.message) return {"message": "No se pudo actualizar el premio."}, 400 return {"notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link", )).dump(n), "premio": PremioSchema( only=( "_id", "nombre", "puntos", "codigo_barras", "codigo_qr", "imagen_icon", "imagen_display", "fecha_creacion", "fecha_vigencia", # "fecha_redencion", # "id_producto", "id_participante" )).dump(p) }, 200 elif accion == 'encuesta': n = NotificacionTemplateModel.find_by_id(id) if not n: return {"message": "No se encontro la notificación!"}, 404 e = EncuestaModel.find_by_id(n.link) if not e: return {"message": "No se encontro la encuesta"}, 404 noti_json = request.get_json() noti = not_schema_template.load(noti_json["notificacion"]) # encuesta_json = request.get_json() encuesta = EncuestaSchema().load(noti_json["encuesta"]) try: if "tipo_notificacion" in noti: n.tipo_notificacion=noti["tipo_notificacion"] if "imagenIcon" in noti: n.imagenIcon=noti["imagenIcon"] if "titulo" in noti: n.titulo=noti["titulo"] if "fecha" in noti: n.fecha=noti["fecha"] if "bar_text" in noti: n.bar_text=noti["bar_text"] if "mensaje" in noti: n.mensaje=noti["mensaje"] if "link" in noti: n.link=noti["link"] # Encuesta if "titulo" in encuesta: e.titulo=encuesta["titulo"] if "categoria" in encuesta: e.categoria=encuesta["categoria"] e.fecha_creacion=dt.datetime.now() if "metrica" in encuesta: e.metrica=encuesta["metrica"] if "puntos" in encuesta: e.puntos=encuesta["puntos"] if "paginas" in encuesta: e.paginas=encuesta["paginas"] pprint(e.paginas) # for pagina in e.paginas: # print(1) e.save() n.save() except ValidationError as exc: print(exc.message) return {"message": "No se pudo actualizar la notificación."}, 404 return { "notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link" )).dump(n), "encuesta": EncuestaSchema( only=( "_id", "titulo", "categoria", "fecha_creacion", "fecha_respuesta", "metrica", "puntos", "paginas", )).dump(e) }, 200
def get(self, id, accion): if accion == 'ninguna': n = NotificacionTemplateModel.find_by_id(id) if not n: return {"message": "No se encontro la notificación"}, 404 return {"notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link", "filtros" )).dump(n)}, 200 elif accion == 'premio': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro el premio"}, 404 p = PremioModel.find_by_id(n.link) if not p: return {"message": "No se encontro el premio"}, 404 return {"notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link", "filtros" )).dump(n), "premio": PremioSchema( only=( "_id", "nombre", "puntos", "codigo_barras", "codigo_qr", "imagen_icon", "imagen_display", "fecha_creacion", "fecha_vigencia", # "fecha_redencion", # "id_producto", "id_participante" )).dump(p) }, 200 elif accion == 'encuesta': n = NotificacionTemplateModel.find_by_id(id) pprint(n) if not n: return {"message": "No se encontro la notificacion"}, 404 en = EncuestaModel.find_by_id(n.link) if not en: return {"message": "No se encontro la encuesta"}, 404 return { "notificacion": NotificacionTemplateSchema( only=( "_id", "titulo", "mensaje", "fecha", "imagenIcon", "bar_text", "tipo_notificacion", "link", "filtros" )).dump(n), "encuesta": EncuestaSchema( only=( "_id", "titulo", "categoria", "fecha_creacion", "fecha_respuesta", "metrica", "puntos", "paginas", )).dump(en) }, 200
from models.premio import PremioModel, PremioParticipanteModel from models.encuesta import EncuestaModel, EncuestaPaginaModel, EncuestaOpcionesModel, ParticipantesEncuestaModel from schemas.encuesta import EncuestaSchema, EncuestaPaginaSchema, EncuestaOpcionesSchema, ParticipanteEncuestaSchema from schemas.notificacion import NotificacionSchema, NotificacionTemplateSchema from schemas.premio import PremioSchema, PremioParticipanteSchema from models.notificacion import NotificacionModel, NotificacionTemplateModel from marshmallow import pprint not_schema = NotificacionSchema() not_schemas_template = NotificacionTemplateSchema(many=True) not_schema_template = NotificacionTemplateSchema() not_schemas = NotificacionSchema(many=True) premio_schema = PremioSchema() # Establish a connection to the database. connect("mongodb://localhost:27017/ej1") class NotificacionList(Resource): #Devolver aquellas en el estado sin eliminar @classmethod def get(self, id): #Participante id = part_id try: """ Dependiendo del id que se consulta Pymodm genera una respuesta específica:
def get(self, id): # Obtener los ids de los templates de los premios que poseé un participante participante_premios = PremioParticipanteModel.find_by_id_participante_vigentes( id) premios_no_quemados = [] # INTEGRACION DE PREMIO DE NIVEL CERO(0) O NIVEL DE BIENVENIDA # participante = ParticipanteModel.find_by_id(id) # puntos = participante.saldo # if puntos == 0: # level0 = TarjetaPuntosTemplateModel.get_level(0) # if level0: # # Lev is id notificacion # for level_id in level0: # notif0 = TarjetaPuntosTemplateModel.find_by_id(level_id) # # if lev.link and lev.link != "null": # notif0 = NotificacionTemplateModel.find_by_id(notif0.id_notificacion) # if notif0: # premio0 = None # if notif0.tipo_notificacion == "premio": # if notif0: # notif = NotificacionModel(id_participante=id, id_notificacion=str(notif0._id), estado=0) # if notif0.link: # premio0 = PremioParticipanteModel(id_participante=id, id_premio=notif0.link, estado=0).save() # if notif0.tipo_notificacion == "encuesta": # pass # if notif0.tipo_notificacion == "ninguna": # pass # if premio0: # premios_no_quemados.append(notif0) # # INTEGRACION del sistema de premios: Se debe verificar si tiene premios por # # nivel aunque no tenga premios que no son de nivel # # 1. Buscar al participante # participante = ParticipanteModel.find_by_id(id) # # 2. Obtener los puntos del participante # puntos = participante.saldo # # 3. Obtener los niveles del participante # niveles = None # if puntos: # niveles = TarjetaPuntosTemplateModel.get_level_vigentes(puntos) # if niveles: # for nivl in niveles: # # 4. Obtener los Notificacion -> premios de los niveles # if nivl.id_notificacion: # notif = NotificacionTemplateModel.find_by_id(nivl.id_notificacion) # if notif and notif.link and notif.link != "null" and notif.tipo_notificacion == 'premio': # # 5. Obtener los premios de los niveles # premio_nivel = find_by_id(notif.link) # if premio_nivel: # if not participante_premios and not niveles_premios: if not participante_premios: return { 'message': f"El participante con el id: { id }, no posee ningún premio" }, 404 # Filtrar los premios que ya han sido quemados, es decir, agotaron sus vidas (fechas_redencion) for pp in participante_premios: # Old method: Por estado {0,1} # if not len(pp.fechas_redencion) > 0: # premios_no_quemados.append(pp) #- Verificar los premios con vidas con los que dispone el participante ptemplate = PremioModel.find_by_id(pp.id_premio) if ptemplate and ptemplate.vidas: if not len(pp.fechas_redencion) > ptemplate.vidas: premios_no_quemados.append(pp) #- # try: # pp.delete() # except (e): # print("No se pudo filtrar los premio quemados, Error: {}".format(e)) if len(premios_no_quemados) == 0: return { 'message': f"El participante con el id: { id }, no posee ningún premio" }, 404 premios = [] for premio in premios_no_quemados: # Obtener el template de cada premio if premio.id_premio and premio.id_premio != 'null': premio_template = PremioModel.find_by_id(premio.id_premio) if premio_template: premios.append(premio_template) premio_template._id = premio._id # # Obtener los premios del participante por el sistema de puntos Niveles # # Obtener el participante # p = ParticipanteModel.find_by_id(id) # if not p: # return {"message": "No se encontro el participante buscado"}, 404 # premios_nivel = TarjetaPuntosTemplateModel.get_level(p.saldo) # for nivel_id in premios_nivel: # # Obtener el template de cada premio # nivel = TarjetaPuntosTemplateModel.find_by_id(nivel_id) # if nivel: # print(nivel_id) # print(len(premios_nivel)) # notif = NotificacionTemplateModel.find_by_id(nivel.id_notificacion) # if notif: # if notif.link and notif.link != "null": # # print(type(notif.link)) # premio_template = PremioModel.find_by_id(notif.link) # if premio_template: # premios.append(premio_template) return { "Premios": PremioSchema( only=( "_id", "nombre", "puntos", "codigo_barras", "codigo_qr", "imagen_icon", "imagen_display", "fecha_creacion", # "fecha_vigencia", # "id_producto", "id_participante", "vidas"), many=True).dump(premios), }, 200
import dateutil.parser from models.premio import PremioModel, PremioParticipanteModel from models.participante import ParticipanteModel from models.producto import CatalogoModel from models.tarjeta import TarjetaPuntosTemplateModel, TarjetaPuntosModel from models.notificacion import NotificacionTemplateModel, NotificacionModel from schemas.premio import PremioSchema, PremioParticipanteSchema from schemas.participante import ParticipanteSchema from schemas.producto import CatalogoSchema from marshmallow import pprint participante_schema = ParticipanteSchema() premio_schema = PremioSchema() premio_schemas = PremioSchema(many=True) # Establish a connection to the database. connect("mongodb://localhost:27017/ej1") # TODO: Separar en una nueva clase los id de los participantes # que reciben la notificacion y la fecha de quemado # TODO: Aplicar metodos de segmentación # TODO: Puntos variables, diversos tipos de bonificación # # ANTIGUO # class PremioList(Resource): # @classmethod # def get(self, id): # part_id = ObjectId(id) # try: