def get(self, request): pk = Operations.get_id(self, request) seller = self.get_object(pk) queryset = Sale.objects.filter(seller=seller) serializer = SellerFooterSerializer(queryset, context={'seller': seller}) return Response(serializer.data)
def post(self, request): client = Operations.get_id(self, request) data = request.data if 'email_receiver' in data: email_receiver = data['email_receiver'] else: raise serializers.ValidationError({'email_receiver': [self.required]}) if 'acquired_plan' in data: acquired_plan = data['acquired_plan'] else: raise serializers.ValidationError({'acquired_plan': [self.required]}) client_plan = QueryPlansClient.objects.filter(client=client, acquired_plan=acquired_plan, empower=True) if client_plan: # El correo si movimientos a realizar query_manage = QueryPlansManage.objects.filter(email_receiver=email_receiver, acquired_plan=acquired_plan, type_operation=3) if query_manage: # Borramos referencias a ese cliente query_manage.delete() empower_obj = QueryPlansClient.objects.filter(client__email_exact=email_receiver, acquired_plan=acquired_plan) empower_obj.delete() #BORRAR DE PLAN CHOSEN FIREBASSE else: raise Http404 return Response({}) else: raise serializers.ValidationError({self.not_permission})
def put(self, request, pk): """Elegir el plan requrido y desactivar los demas.""" client_id = Operations.get_id(self, request) data = request.data plan = self.get_object(pk) try: plan_client = QueryPlansClient.objects.get(client=client_id, acquired_plan=plan.id) # import pdb; pdb.set_trace() except QueryPlansClient.DoesNotExist: raise Http404 # valido el plan que se desea activar if (plan.is_active is True and plan_client.client_id == client_id and plan.expiration_date >= datetime.now().date()): # Activar Plan serializer = QueryPlansClientSerializer(plan_client, data, partial=True) if serializer.is_valid(): serializer.save() if 'test' not in sys.argv: # sincronizo en pyrebase plan_chosen = get_query_set_plan() plan_active = plan_chosen.filter(queryplansclient__client=client_id, is_active=True, queryplansclient__is_chosen=True) serializer_plan_acquired = QueryPlansAcquiredSerializer(plan_active[0]) pyrebase.chosen_plan(client_id, serializer_plan_acquired.data) result_data = serializer_plan_acquired.data else: result_data = {} return Response(result_data) else: return Response(serializer.errors, HTTP_400_BAD_REQUEST) raise Http404
def get(self, request, pk): """Listado de queries y sus respectivos mensajes para un especialista.""" category = self.get_object(pk) client = Operations.get_id(self, request) if not client: raise Http404 queryset = Message.objects.values('id', 'code', 'message', 'created_at', 'msg_type', 'viewed', 'query_id', 'query__client_id', 'message_reference', 'specialist_id', 'content_type', 'file_url', 'file_preview_url', 'query__specialist_id', 'uploaded')\ .annotate(title=F('query__title',), status=F('query__status',), qualification=F('query__qualification',), category_id=F('query__category_id',),\ group_status=F('group__status',))\ .filter(query__client_id=client, query__category_id=category)\ .order_by('-created_at') serializer = ChatMessageSerializer(queryset, many=True) # pagination page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) return Response(serializer.data)
def put(self, request, pk): """Listado de queries y sus respectivos mensajes para un especialista.""" specialist = Operations.get_id(self, request) try: query = Query.objects.get(pk=pk, status__lt=3, specialist=specialist) except Query.DoesNotExist: raise Http404 data = {} data["status"] = 1 data["specialist"] = request.data["specialist"] specialist_asoc_id = data["specialist"] serializer = QueryDeriveSerializer(query, data=data) if serializer.is_valid(): serializer.save() qset_spec = Specialist.objects.filter(pk=specialist_asoc_id) dict_pending = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] if 'test' not in sys.argv: lista = list(serializer.data['message'].values()) body = get_body(lista[-1]["fileType"], lista[-1]["message"]) data_notif_push = { "title": serializer.data['displayName'], "body": body, "sub_text": "", "ticker": serializer.data["obj_query"]["title"], "badge": badge_count, "icon": serializer.data['photo'], "client_id": serializer.data['client'], "type": Params.TYPE_NOTIF["query_derived"], "category_id": serializer.data['category'], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "query_id": serializer.data["query_id"] } # envio de notificacion push Notification.fcm_send_data(user_id=specialist_asoc_id, data=data_notif_push) pyrebase.updateStatusQueryDerive(specialist, data["specialist"], query) room_channel = str(query.client.id) + '-' + str( query.category.id) Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 2, "query": pk, "data": { "specialist": data["specialist"] } }) }) return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def get(self, request): """Devolver Planes.""" user_id = Operations.get_id(self, request) qs = QueryPlansAcquired.objects.filter(queryplansclient__client=user_id) # import pdb; pdb.set_trace() plans = PlanStatusSerializer(qs, context={"client": user_id}) return Response(plans.data)
def post(self, request): """metodo para crear compra.""" # user_id = Operations.get_id(self, request) data = request.data user_id = Operations.get_id(self, request) if request.user.role_id == 4: # Si es vendedor, se usa su id como el que efectuo la venta if 'latitude' in data: latitude = data["latitude"] else: raise serializers.ValidationError( {'latitude': [self.required]}) if 'longitude' in data: longitude = data["longitude"] else: raise serializers.ValidationError( {'longitude': [self.required]}) # Si es vendedor, se usa su id como el que efectuo la venta data['seller'] = user_id elif request.user.role_id == 1 or request.user.role_id == 2: # si se trata de un administrador o cliente, la venta la habra efectuado el vendedor asignado data['seller'] = Client.objects.get( pk=data['client']).seller_assigned.id serializer_client = ContactToClientSerializer(data=data) if serializer_client.is_valid(): serializer_client.save() data['client'] = serializer_client.data['client_id'] # Categorias para usuario pyrebase pyrebase.createCategoriesLisClients(data['client']) else: return Response(serializer_client.errors, status.HTTP_400_BAD_REQUEST) serializer = SaleSerializer(data=data, context=data) if serializer.is_valid(): serializer.save() contact = SellerContact.objects.get(client_id=data['client']) if is_assigned(contact=contact): if 'latitude' in data: contact.latitude = data['latitude'] if 'longitude' in data: contact.longitude = data['longitude'] contact.is_assigned = False contact.save() if request.user.role_id == 4: generate_visit_new_sale(data, contact, serializer.data["id"], data["products"][0]["is_billable"]) return Response(serializer.data, status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def get(self, request, pk): """Devolver Planes.""" duct = {} user_id = Operations.get_id(self, request) result = self.can_receive_contact(user_id, pk) if result: return Response({"status": self.affirmative}, status.HTTP_200_OK) else: return Response({"status": self.denied}, status.HTTP_400_BAD_REQUEST)
def list(self, request): """Listado de Matchs.""" user_id = Operations.get_id(self, request) queryset = Match.objects.filter(specialist=user_id) # pagination page = self.paginate_queryset(queryset) if page is not None: serializer = MatchListSpecialistSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = MatchListSpecialistSerializer(page, many=True) return Response(serializer.data)
def get(self, request): pk = Operations.get_id(self, request) specialist = self.get_object(pk) queryset = Query.objects.filter(specialist=specialist) serializer = SpecialistFooterSerializer(queryset, context={ 'category': specialist.category, 'specialist': specialist }) return Response(serializer.data)
def get(self, request): """Funcion devolver data segun rol.""" user_id = Operations.get_id(self, request) if request.user.role_id == Params.ROLE_CLIENT: queryset = Client.objects.filter(pk=user_id) serializer = NotificationClientSerializer(queryset) return Response(serializer.data) elif request.user.role_id == Params.ROLE_SPECIALIST: queryset = Specialist.objects.filter(pk=user_id) serializer = NotificationSpecialistSerializer(queryset) return Response(serializer.data) else: return Response({"response": 0})
def get(self, request): """Obtener la lista con todos los planes del cliente.""" pk = Operations.get_id(self, request) plan = self.get_object(pk) # paginacion page = self.paginate_queryset(plan) if page is not None: serializer = QueryPlansAcquiredSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = QueryPlansAcquiredSerializer(plan, many=True) return Response(serializer.data)
def put(self, request, pk): """Match para un especialista.""" specialist = Operations.get_id(self, request) try: match = Match.objects.get(pk=pk, status=1, specialist=specialist) except Match.DoesNotExist: raise Http404 data = request.data data["status"] = 2 serializer = MatchAcceptSerializer(match, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def get(self, request, pk): """Obtener la lista con todos los planes del cliente.""" client = Operations.get_id(self, request) plan = QueryPlansAcquired.objects.filter(pk=pk, queryplansclient__client=client).values('id', 'plan_name', 'queryplansclient__is_chosen', 'is_active', 'status', 'validity_months', 'query_quantity', 'queries_to_pay', 'activation_date', 'available_queries', 'expiration_date', 'queryplansclient__transfer', 'queryplansclient__share', 'queryplansclient__empower', 'queryplansclient__owner').annotate( is_chosen=F('queryplansclient__is_chosen'), price=F('sale_detail__price'), sale=F('sale_detail__sale'), is_fee=F('sale_detail__sale__is_fee')) if plan: serializer = QueryPlansAcquiredDetailSerializer(plan[0], partial=True) return Response(serializer.data) else: raise Http404
def get(self, request): """Devolver Planes.""" duct = {} user_id = Operations.get_id(self, request) q_plans = QueryPlans.objects.filter(is_active=True, is_promotional=True) hoy = datetime.now() try: prom = SellerNonBillablePlans.objects.get(seller_id=user_id, number_month=hoy.month, number_year=hoy.year) duct["quantity"] = prom.quantity except SellerNonBillablePlans.DoesNotExist: duct["quantity"] = 0 plans = QueryPlansSerializer(q_plans, many=True) duct["plans"] = plans.data return Response(duct)
def get(self, request): client_id = Operations.get_id(self, request) data = request.query_params response = {} if 'acquired_plan' in data: acquired_plan = data['acquired_plan'] else: raise serializers.ValidationError({'acquired_plan': [self.required]}) if 'email_receiver' in data: email_receiver = data['email_receiver'] else: raise serializers.ValidationError({'email_receiver': [self.required]}) if 'type_operation' in data: type_operation = int(data['type_operation']) else: raise serializers.ValidationError({'type_operation': [self.required]}) # No realizar operacion a sigo mismo try: sender = Client.objects.get(pk=client_id) except Client.DoesNotExist: raise serializers.ValidationError({'credentials': [self.invalid]}) # Traer cliente by email si existe! try: receiver = Client.objects.get(email_exact=email_receiver) except Client.DoesNotExist: receiver = None checker = CheckEmailOperationPlan(type_operation, email_receiver, acquired_plan, sender, receiver) if not checker.is_valid(): raise serializers.ValidationError(checker.errors[0]) # Cliente no existe pero puede ser facultado, compartido, transferido if not receiver: raise Http404 return Response(response)
def post(self, request): """crear compra.""" data = request.data user_id = Operations.get_id(self, request) if "monthly_fee" in data: try: mfee = MonthlyFee.objects.get(pk=data["monthly_fee"]) data["file_url"] = mfee.sale.file_url data["file_preview_url"] = mfee.sale.file_preview_url except Match.DoesNotExist: data["file_url"] = "" data["file_preview_url"] = "" logger.warning("no file_url para fee:" + mfee.id) serializer = PaymentSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def list(self, request): """List.""" user_id = Operations.get_id(self, request) if not user_id: raise Http404 # Se hace un subquery para traer los ultimos msjs. q_query = Query.objects.values('message__created_at')\ .filter(client_id=user_id, message__msg_type='q')\ .order_by('-message__created_at') # Se realiza la consulta tomando como subconsulta la consulta anterior queryset = Category.objects.annotate(fecha=Subquery(q_query.values('message__created_at') .filter(category_id=OuterRef('pk'))[:1]))\ .order_by(F('fecha').desc()) serializer = QueryListClientSerializer(queryset, context={'user': request.user}, many=True) return Response(serializer.data)
def put(self, request, pk): """Listado de queries y sus respectivos mensajes para un especialista.""" specialist = Operations.get_id(self, request) try: query = Query.objects.get(pk=pk, status=1, specialist=specialist) except Query.DoesNotExist: raise Http404 data = {} data["status"] = 2 serializer = QueryAcceptSerializer(query, data=data) if serializer.is_valid(): serializer.save() if 'test' not in sys.argv: room = query.message_set.last().room pyrebase.updateStatusQueryAccept(specialist, query.client.id, pk, room) room_channel = str(query.client.id) + '-' + str( query.category.id) Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 2, "query": pk, "data": { "status": data["status"] } }) }) # Traemos todas las consultas pendientes por tomar accion por asignadas # a este especialista # msgs_pendings = Query.objects.filter(status=1, specialist=specialist) return Response({}, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def post(self, request): """Actualizar mensajes de categoria.""" user_id = Operations.get_id(self, request) category = request.data["category_id"] queries = Query.objects.filter(category=category, client=user_id, status=3) for query in queries: msgs = query.message_set.all() # import pdb; pdb.set_trace() if 'test' not in sys.argv: pyrebase.update_status_query(query.id, {"status": 4}, msgs.last().room) # import pdb; pdb.set_trace() for ms in msgs: GroupMessage.objects.filter(message__id=ms.id).update(status=2) # import pdb; pdb.set_trace() if 'test' not in sys.argv: pyrebase.update_status_group_messages(msgs, 2) room_channel = str(query.client.id) + '-' + str( query.category.id) Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 2, "query": query.id, "data": { "status": 4 } }) }) success = queries.update(status=4) if success: return Response({}, status.HTTP_200_OK) return Response({}, status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): """Redefinido put""" specialist = Operations.get_id(self, request) try: match = Match.objects.get(pk=pk, status=1, specialist=specialist) except Match.DoesNotExist: raise Http404 data = request.data data["status"] = 3 serializer = MatchDeclineSerializer(match, data=data) if serializer.is_valid(): serializer.save() if 'test' not in sys.argv: client_id = serializer.data["client"] qset_client = Client.objects.filter(pk=client_id) dict_pending = NotificationClientSerializer(qset_client).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] data_notif_push = { "title": serializer.data['display_name'], "body": serializer.data["subject"], "sub_text": "", "ticker": serializer.data["declined_motive"], "badge": badge_count, "icon": serializer.data['photo'], "type": Params.TYPE_NOTIF["match_declined"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "match_id": serializer.data["id"] } # envio de notificacion push Notification.fcm_send_data(user_id=client_id, data=data_notif_push) return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def get(self, request, pk): client = Operations.get_id(self, request) data = request.data manage_data = QueryPlansManage.objects.values('email_receiver', 'status','type_operation', 'receiver', 'new_acquired_plan' ).annotate(available_queries = F('new_acquired_plan__available_queries',), query_quantity = F('new_acquired_plan__query_quantity',), first_name = F('receiver__first_name',), last_name = F('receiver__last_name',), business_name = F('receiver__business_name',), type_client = F('receiver__type_client',), photo = F('receiver__photo',)).filter( Q(type_operation=2) | Q(type_operation=3) ).filter(acquired_plan = pk).distinct().order_by('-type_operation') # paginacion page = self.paginate_queryset(manage_data) if page is not None: serializer = QueryPlansManageSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = QueryPlansManageSerializer(manage_data, many=True) return Response(serializer.data)
def post(self, request): """Enviar data.""" data = request.data client_id = Operations.get_id(self, request) if "category" in data: category = int(data["category"]) else: raise serializers.ValidationError({'category': [self.required]}) # Traer los mensajes que no han sido leidos y son respuestass del especialista mesgs_res = Message.objects.filter(viewed=False, msg_type='a', query__client=client_id, query__category=category) if mesgs_res: mesgs_res.update(viewed=1) # if 'test' not in sys.argv: #NO ACTUALIZAMOS CHAT # pyrebase.set_message_viewed(mesgs_res) if 'test' not in sys.argv: pyrebase.categories_db(client_id, category) return Response({}, status.HTTP_200_OK)
def put(self, request, pk): """Listado de queries y sus respectivos mensajes para un especialista.""" specialist = Operations.get_id(self, request) try: # Queris status menor a 3 query = Query.objects.get(pk=pk, status__lt=3, specialist=specialist) except Query.DoesNotExist: raise Http404 try: main_specialist = Specialist.objects.get(category=query.category, type_specialist='m') except Specialist.DoesNotExist: raise Http404 context = {} context["status"] = 1 context["specialist"] = main_specialist context["specialist_declined"] = specialist main_specialist_id = main_specialist.id serializer = QueryDeclineSerializer(query, data=request.data, context=context) if serializer.is_valid(): serializer.save() qset_spec = Specialist.objects.filter(pk=main_specialist_id) dict_pending = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] ser = DeclineReprSerializer(query) if 'test' not in sys.argv: data_notif_push = { "title": ser.data['displayName'], "body": ser.data["motive"], "sub_text": "", "ticker": ser.data["motive"], "badge": badge_count, "icon": ser.data['photo'], "type": Params.TYPE_NOTIF["query_declined"], "client_id": ser.data['client'], "category_id": ser.data["category"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "query_id": ser.data["query_id"] } pyrebase.updateStatusQueryDerive(specialist, main_specialist_id, query) # envio de notificacion push Notification.fcm_send_data(user_id=main_specialist_id, data=data_notif_push) room_channel = str(query.client.id) + '-' + str( query.category.id) Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 2, "query": pk, "data": { "specialist": main_specialist_id } }) }) return Response(ser.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): """Actualizar consulta.""" query = self.get_object(pk) user_id = Operations.get_id(self, request) if not user_id: raise Http404 data = request.data # No utilizamos partial=True, ya que solo actualizamos mensaje serializer = ReQuerySerializer(query, data) if serializer.is_valid(): serializer.save() lista = list(serializer.data['message'].values()) client_id = serializer.data["client_id"] category_id = serializer.data["category"] specialist_id = serializer.data["specialist_id"] # Actualizamos el nodo de mensajes segun su sala if 'test' not in sys.argv: pyrebase.chat_firebase_db(serializer.data["message"], serializer.data["room"]) # Actualizamos el listado de especialidades en Firebase if 'test' not in sys.argv: pyrebase.categories_db(user_id, category_id, lista[-1]["timeMessage"]) # sala es el cliente_id y su la categoria del especialista room_channel = str(query.client.id) + '-' + str(category_id) # Se envian el query y sus mensajes por channels Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 1, "query": serializer.data["obj_query"]["title"], "status": serializer.data["obj_query"]["status"], "specialist": serializer.data["specialist_id"], "messages": lista }) }) # actualizo el querycurrent del listado de mensajes for li in lista: if li['messageReference'] is not None and li[ 'messageReference'] != 0: ms_ref = li['messageReference'] gp = GroupMessage.objects.get(message__id=ms_ref) msgs = gp.message_set.all() qset_spec = Specialist.objects.filter(pk=specialist_id) dict_pending = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] if 'test' not in sys.argv: us = User.objects.get(pk=user_id) if us.nick == '': displayname = us.first_name + ' ' + us.last_name else: displayname = us.nick # crea data de notificacion push body = get_body(lista[-1]["fileType"], lista[-1]["message"]) data_notif_push = { "title": displayname, "body": body, "sub_text": "", "ticker": serializer.data["obj_query"]["title"], "badge": badge_count, "icon": us.photo, "client_id": user_id, "type": Params.TYPE_NOTIF["query_requery"], "category_id": category_id, "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "query_id": serializer.data["query_id"] } pyrebase.update_status_group_messages(msgs, gp.status) # envio de notificacion push Notification.fcm_send_data(user_id=specialist_id, data=data_notif_push) requeries = serializer.data['obj_query']['availableRequeries'] data_update = { "status": query.status, "availableRequeries": requeries } if 'test' not in sys.argv: pyrebase.update_status_query(query.id, data_update, serializer.data["room"]) data = { 'status': 2, 'date': lista[-1]["timeMessage"], 'message': lista[-1]["message"] } if 'test' not in sys.argv: pyrebase.update_status_query_current_list( specialist_id, client_id, data) return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def post(self, request): """Metodo para Crear consulta.""" # Devolvemos el id del usuario user_id = Operations.get_id(self, request) # label = 1 if not user_id: raise Http404 data = request.data # tomamos del token el id de usuario (cliente en este caso) data["client"] = user_id serializer = QuerySerializer(data=data) if serializer.is_valid(): serializer.save() category = serializer.data["category"] lista = list(serializer.data['message'].values()) # Se actualiza la base de datos de firebase para el mensaje if 'test' not in sys.argv: pyrebase.node_query(serializer.data["obj_query"], serializer.data["query_id"], serializer.data["room"]) pyrebase.chat_firebase_db(serializer.data["message"], serializer.data["room"]) # Se actualiza la base de datos de firebase listado # de sus especialidades if 'test' not in sys.argv: pyrebase.categories_db(user_id, category, lista[-1]["timeMessage"]) data_set = SpecialistMessageList_sp.search(2, user_id, category, 0, "") serializer_tmp = SpecialistMessageListCustomSerializer(data_set, many=True) # Se devuelve las ultimas consultas pendientes por responder # por cliente # Primer una subconsulta para buscar el ultimo registro de mensaje mess = Message.objects.filter(query=OuterRef("pk"))\ .order_by('-created_at')[:1] # Luego se busca el titulo y su id de la consulta specialist_id = serializer_tmp.data[0]['specialist'] data_queries = Query.objects.values('id', 'title', 'status', 'specialist')\ .annotate( message=Subquery( mess.values('message')))\ .annotate( date_at=Subquery( mess.values('created_at')))\ .filter(client=user_id, specialist=specialist_id, status=1)\ .annotate(count=Count('id'))\ .order_by('-message__created_at') query_pending = PendingQueriesSerializer(data_queries, many=True) lista_d = { Params.PREFIX['query'] + str(l['id']): l for l in query_pending.data } # determino el total de consultas pendientes (status 1 o 2) # y matchs por responder o pagar qset_spec = Specialist.objects.filter(pk=specialist_id) dict_pending = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] if 'test' not in sys.argv: # crea data de notificacion push body = get_body(lista[-1]["fileType"], lista[-1]["message"]) data_notif_push = { "title": serializer_tmp.data[0]['displayName'], "body": body, "sub_text": "", "ticker": serializer.data["obj_query"]["title"], "badge": badge_count, "icon": serializer_tmp.data[0]['photo'], "client_id": user_id, "category_id": category, "type": Params.TYPE_NOTIF["query_new"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "query_id": serializer.data["query_id"] } # crea nodo de listado de mensajes pyrebase.createListMessageClients(serializer_tmp.data, serializer.data["query_id"], serializer.data["status"], user_id, specialist_id, queries_list=lista_d) # envio de notificacion push Notification.fcm_send_data(user_id=specialist_id, data=data_notif_push) # -- Aca una vez creada la data, cargar el mensaje directo a # -- la sala de chat en channels (usando Groups) room_channel = str(user_id) + '-' + str( serializer.data["category"]) # Se envian el query y sus mensajes por channels Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 1, "query": serializer.data["obj_query"]["title"], "status": serializer.data["obj_query"]["status"], "specialist": specialist_id, "messages": lista }) }) return Response(serializer.data, status.HTTP_201_CREATED) else: return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def post(self, request): """Metodo para Solicitar Match.""" # Devolvemos el id del usuario data = request.data user_id = Operations.get_id(self, request) context_data = {} if request.user.role_id == 4: # Si es vendedor, se usa su id como el que efectuo la venta if 'latitude' in data: latitude = data["latitude"] else: raise serializers.ValidationError( {'latitude': [self.required]}) if 'longitude' in data: longitude = data["longitude"] else: raise serializers.ValidationError( {'longitude': [self.required]}) if request.user.role_id == 2: data["client"] = user_id context_data["seller"] = Client.objects.get( pk=user_id).seller_assigned.id elif (request.user.role_id == 4 or request.user.role_id == 1) and "client_id" in data and data["client_id"]: data["client"] = data["client_id"] context_data["seller"] = Client.objects.get( pk=data["client"]).seller_assigned.id elif (request.user.role_id == 4 or request.user.role_id == 1) and "email_exact" in data and data["email_exact"]: email_exact = data["email_exact"] if request.user.role_id == 4: data["seller"] = user_id else: try: data["seller"] = SellerContact.objects.get( email_exact=email_exact).seller.id except SellerContact.DoesNotExist: pass if "seller" in data and "email_exact" in data: serializer_client = ContactToClientSerializer(data=data) if serializer_client.is_valid(): serializer_client.save() data["client"] = serializer_client.data["client_id"] context_data["seller"] = data["seller"] # categorias firebase para el cliente pyrebase.createCategoriesLisClients(data["client"]) # Cliente que hace match es requerido if "client" not in data: raise serializers.ValidationError({"client": _("required")}) if 'file' in data: if data["file"] is None: del data["file"] # import pdb; pdb.set_trace() serializer = MatchSerializer(data=data, context=context_data) if serializer.is_valid(): serializer.save() contact = SellerContact.objects.get(client_id=data['client']) if is_assigned(contact=contact): if 'latitude' in data: contact.latitude = data['latitude'] if 'longitude' in data: contact.longitude = data['longitude'] contact.is_assigned = False contact.save() if 'test' not in sys.argv: specialist_id = serializer.data["specialist"] # determino el total de consultas pendientes (status 1 o 2) # y matchs por responder o pagar qset_spec = Specialist.objects.filter(pk=specialist_id) dict_pending = NotificationSpecialistSerializer(qset_spec).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] data_notif_push = { "title": str(serializer.data['display_name']), "body": serializer.data["subject"], "sub_text": "", "ticker": serializer.data["subject"], "badge": badge_count, "icon": serializer.data['photo'], "type": Params.TYPE_NOTIF["match_new"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "match_id": serializer.data["id"] } # envio de notificacion push Notification.fcm_send_data(user_id=specialist_id, data=data_notif_push) if request.user.role_id == 4: generate_visit_new_sale(data, contact, serializer.data["id"], True) return Response(serializer.data, status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def post(self, request): """Obtener la lista con todos los planes del cliente.""" client = Operations.get_id(self, request) data = request.data if not 'acquired_plan' in data: raise serializers.ValidationError({'acquired_plan': [self.required]}) if not 'email_receiver' in data: raise serializers.ValidationError({'email_receiver': [self.required]}) # Traer al cliente try: sender = Client.objects.get(pk=client) except Client.DoesNotExist: raise Http404 # Traer informacion del plan y de los permisos del plan try: acquired_plan = QueryPlansAcquired.objects.get(pk=data['acquired_plan'], queryplansclient__client=client, queryplansclient__transfer=True) acquired_plan_client = QueryPlansClient.objects.get(acquired_plan=acquired_plan, client=client) except QueryPlansAcquired.DoesNotExist: raise Http404 # Traemos a receptor si existe email_receiver = data['email_receiver'] try: receiver = Client.objects.get(email_exact=email_receiver) status_transfer = 1 qset_client = Client.objects.filter(pk=receiver.id) except Client.DoesNotExist: receiver = None status_transfer = 3 checker = CheckEmailOperationPlan(1, email_receiver, acquired_plan, sender, receiver) if not checker.is_valid(): raise serializers.ValidationError(checker.errors[0]) data_transfer = { 'type_operation': 1, # transferencia 'status': status_transfer, 'acquired_plan': acquired_plan.id, 'new_acquired_plan': None, 'sender': client, 'receiver': receiver, 'email_receiver': email_receiver } data_context = {} data_context['client_receiver'] = { 'is_chosen': False, 'owner': True, 'transfer': True, 'share': True, 'empower': True, 'status': status_transfer, 'acquired_plan': acquired_plan, 'client': receiver } data_context['client_sender'] = { 'acquired_plan': acquired_plan.id, 'client': client } is_chosen_plan = acquired_plan_client.is_chosen serializer = QueryPlansTransferSerializer(data=data_transfer, context=data_context) if serializer.is_valid(): if 'test' not in sys.argv: # Si el plan estaba escogido por el anterior cliente if is_chosen_plan: pyrebase.delete_actual_plan_client(client) mail = BasicEmailAmazon(subject=str(self.subject), to=email_receiver, template='email/transfer') if receiver is not None: arguments = {'message':self.default_message, 'link':WEB_HOST} else: arguments = {'message':REGISTRATION_MESSAGE, 'link':REGISTER_LINK} mail.sendmail(args=arguments) if status_transfer == 1: dict_pending = NotificationClientSerializer(qset_client).data badge_count = dict_pending["queries_pending"] + dict_pending["match_pending"] data_notif_push = { "title": "Se te ha transferido un plan", "body": display_client_name(sender), "sub_text": "", "ticker": "", "badge": badge_count, "icon": sender.photo, "plan_id": acquired_plan.id, "type": Params.TYPE_NOTIF["plan"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"] } # envio de notificacion push Notification.fcm_send_data(user_id=receiver.id, data=data_notif_push) serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): """Actualiza la consulta.""" query = self.get_object(pk) user_id = Operations.get_id(self, request) # label = 1 if not user_id: raise Http404 data = request.data # tomamos del token el id de usuario (especialista en este caso) spec = Specialist.objects.get(pk=user_id) # No utilizamos partial=True, ya que solo actualizamos mensaje serializer = QueryResponseSerializer(query, data, context={'specialist': spec}) if serializer.is_valid(): serializer.save() lista = list(serializer.data['message'].values()) client_id = serializer.data["client_id"] category_id = serializer.data["category"] cat = Category.objects.get(pk=category_id) if 'test' not in sys.argv: # Actualizamos el nodo de mensajes segun su sala pyrebase.chat_firebase_db(serializer.data["message"], serializer.data["room"]) # Actualizamos el listado de especialidades en Firebase pyrebase.categories_db(client_id, category_id, lista[-1]["timeMessage"]) # sala es el cliente_id y su la categoria del especialista room_channel = str(query.client.id) + '-' + str(category_id) # Se envian el query y sus mensajes por channels Group('chat-' + str(room_channel)).send({ 'text': json.dumps({ "eventType": 1, "query": serializer.data["obj_query"]["title"], "status": serializer.data["obj_query"]["status"], "specialist": user_id, "messages": lista }) }) for row in lista: if row['messageReference'] is not None and row[ 'messageReference'] != 0: ms_ref = row['messageReference'] group = GroupMessage.objects.get(message__id=ms_ref) msgs = group.message_set.all() # determino el total de consultas pendientes (status 3 o 5) # y matchs por pagar (status 4) qset_client = Client.objects.filter(pk=client_id) dict_pending = NotificationClientSerializer(qset_client).data badge_count = dict_pending["queries_pending"] + dict_pending[ "match_pending"] if 'test' not in sys.argv: pyrebase.update_status_group_messages(msgs, group.status) body = get_body(lista[-1]["fileType"], lista[-1]["message"]) data_fcm = { "title": ugettext(cat.name), "body": body, "sub_text": ugettext(cat.name), "ticker": query.title, "icon": cat.image, "badge": badge_count, "client_id": query.client.id, "type": Params.TYPE_NOTIF["query_answer"], "category_id": category_id, "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"], "query_id": query.id } Notification.fcm_send_data(user_id=client_id, data=data_fcm) requeries = query.available_requeries data_update = { "status": query.status, "availableRequeries": requeries } if 'test' not in sys.argv: pyrebase.update_status_query(query_id=query.id, data=data_update, room=serializer.data["room"]) # actualizo el querycurrent del listado de mensajes data = { 'status': query.status, 'date': lista[-1]["timeMessage"], 'message': lista[-1]["message"] } if 'test' not in sys.argv: pyrebase.update_status_query_current_list( user_id, client_id, data) return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
def post(self, request): """Obtener la lista con todos los planes del cliente.""" client = Operations.get_id(self, request) data = request.data if not 'acquired_plan' in data: raise serializers.ValidationError({'acquired_plan': [self.required]}) if 'client' in data: clients = data['client'] if type(clients) is str: clients = json.loads(clients) if type(clients) is not list: raise serializers.ValidationError({'client': [self.required]}) try: acquired_plan = QueryPlansAcquired.objects.get(pk=data['acquired_plan'], queryplansclient__client=client, queryplansclient__empower=True) except QueryPlansAcquired.DoesNotExist: raise Http404 try: client_obj = Client.objects.get(pk=client) except Client.DoesNotExist: raise Http404 errors = {} serializer_data = {} for client_data in clients: email_receiver = receiver = None # Validamos si enviar el correo del cliente if 'email_receiver' in client_data: email_receiver = client_data['email_receiver'] else: continue # Traer cliente by email si existe! try: receiver = Client.objects.get(email_exact=email_receiver) status_transfer = 1 qset_client = Client.objects.filter(pk=receiver.id) except Client.DoesNotExist: status_transfer = 3 receiver = None checker = CheckEmailOperationPlan(3, email_receiver, acquired_plan, client_obj, receiver) if not checker.is_valid(): errors[email_receiver] = checker.errors continue # Data del plan a Manejar data_manage = { 'type_operation': 3, # Facultar 'status': status_transfer, 'acquired_plan': acquired_plan.id, 'new_acquired_plan': None, 'sender': client, 'receiver': receiver, 'email_receiver': email_receiver } # Data de conexto para el cliente que recive plan data_context = {} data_context['client_receiver'] = { 'is_chosen': False, 'owner': False, 'transfer': False, 'share': True, 'empower': False, 'status': status_transfer, 'acquired_plan': acquired_plan, 'client': receiver } serializer = QueryPlansEmpowerSerializer(data=data_manage, context=data_context) if serializer.is_valid(): serializer_data[email_receiver] = serializer else: errors[email_receiver] = serializer.errors # Se retornan los errores que se acumularon if errors: return Response(errors, status=status.HTTP_400_BAD_REQUEST) else: # Para cada uno de los correos guardados for email_receiver in serializer_data: # Ejecutamos el serializer serializer_data[email_receiver].save() receiver_id = serializer_data[email_receiver].data["receiver"] if 'test' not in sys.argv: # Envio de correos notificacion mail = BasicEmailAmazon(subject=str(self.subject), to=email_receiver, template='email/empower') if receiver is not None: arguments = {'message':self.default_message, 'link':WEB_HOST} else: arguments = {'message':REGISTRATION_MESSAGE, 'link':REGISTER_LINK} mail.sendmail(args=arguments) if status_transfer == 1: dict_pending = NotificationClientSerializer(qset_client).data badge_count = dict_pending["queries_pending"] + dict_pending["match_pending"] data_notif_push = { "title": "Se te ha facultado un plan", "body": display_client_name(client_obj), "sub_text": "", "ticker": "", "badge": badge_count, "icon": client_obj.photo, "plan_id": acquired_plan.id, "type": Params.TYPE_NOTIF["plan"], "queries_pending": dict_pending["queries_pending"], "match_pending": dict_pending["match_pending"] } # envio de notificacion push Notification.fcm_send_data(user_id=receiver_id, data=data_notif_push) return Response({})