Ejemplo n.º 1
0
 def put(self, request, pk, format=None):
     customer = self.get_object(pk)
     serializer = CustomerSerializer(customer, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
 def put(self, request, customer_id):
     customer = self.get_object(customer_id)
     serializer = CustomerSerializer(instance=customer, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response({'error': serializer.errors})
Ejemplo n.º 3
0
Archivo: views.py Proyecto: isras/glove
 def put(self, request, pk, format=None):
     customer = self.get_object(pk)
     serializer = CustomerSerializer(customer, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 4
0
 def put(self, request, pk):
     customer = self.get_object(pk)
     serializer = CustomerSerializer(instance=customer, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors,
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 5
0
    def test_successful_request(self):
        serializer = CustomerSerializer(data=self.data)
        self.assertTrue(serializer.is_valid())

        token = Token.objects.create(key="test token", user=self.user)
        self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key)
        response = self.client.post(self.url, self.data, format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Ejemplo n.º 6
0
 def post(self, request, version='v1', format='json'):
     serialized = CustomerSerializer(data=request.data)
     errors = None
     if serialized.is_valid():
         serialized.save()
         return self.get(request)
     else:
         errors = serialized.errors
     return Response(errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 7
0
    def post(self, request):
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            customer = serializer.validated_data
            update_customer_if_is_partner.delay(customer['email'])

            return Response(status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update_credit_card(request):
    """    
    Update the credit card from customer
    """
    logger.debug("Updating credit card")
    if 'credit_card' in request.data:

        if not validate_credit_card(request.data.get('credit_card')):
            logger.error(errors.USR_08.message)
            return errors.handle(errors.USR_08)

        try:
            customer = request.user.customer
            customer.credit_card = request.data.get('credit_card', None)
            customer.save()
            serializer_element = CustomerSerializer(customer)
            logger.debug("Success")
            return Response(serializer_element.data)
        except AttributeError:
            logger.error(errors.USR_10.message)
            return errors.handle(errors.USR_10)
        except Exception as error:
            errors.COM_02.message = str(error)
            logger.error(errors.COM_02.message)
            return errors.handle(errors.COM_02)
    else:
        errors.COM_02.field = 'credit_card'
        logger.error(errors.COM_02.message)
        return errors.handle(errors.COM_02)
Ejemplo n.º 9
0
    def post(self, request):
        logger.debug("Login a customer")
        """Authenticate user through the access_token"""
        serializer = SocialSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        access_token = serializer.data.get("access_token")

        user = FacebookValidation().validate_access_token(access_token)
        username = user.get("name", None)
        email = user.get("email", None)
        try:
            customer = Customer.objects.get(name=username)
        except Customer.DoesNotExist:
            customer = Customer.objects.create_customer(name=username,
                                                        email=email)
        refresh = RefreshToken.for_user(customer)
        serializer_element = CustomerSerializer(customer)
        response = Response(
            {
                "customer": {
                    "schema": serializer_element.data
                },
                "accessToken": "Bearer " + str(refresh.access_token),
                "expires_in": "24h",
            },
            200,
        )
        logger.debug("Success")
        return response
 def get_customer(self, order):
     customer = Customer.objects.filter(id=order.customer_id).first()
     if customer:
         serial_customer = CustomerSerializer(customer)
         return serial_customer.data
     else:
         return None
Ejemplo n.º 11
0
def login(request):
    serializer = CustomerAuthSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data.get('customer')
    serializer = CustomerSerializer(user)
    token, created = Token.objects.get_or_create(user=user)
    return Response({'token': token.key, 'user': serializer.data})
Ejemplo n.º 12
0
 def list(self, request):
     fields = ('name', 'email', 'url')
     customers = Customer.objects.all()
     serializer = CustomerSerializer(customers,
                                     many=True,
                                     context={'request': request},
                                     fields=fields)
     return Response(serializer.data)
Ejemplo n.º 13
0
def customer_list_by_age(request, age):

    customers = Customer.objects.filter(age=age)

    # GET all customers by age
    if request.method == 'GET':
        customers_serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(customers_serializer.data, safe=False)
Ejemplo n.º 14
0
def customer_details(request, pk):

    try:
        customer = Customer.objects.get(pk=pk)
    except Customer.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    # GET customer details
    if request.method == 'GET':
        customer_serializer = CustomerSerializer(customer)
        return JsonResponse(customer_serializer.data)

    # PUT existing customer
    elif request.method == 'PUT':
        customer_data = JSONParser().parse(request)
        customer_serializer = CustomerSerializer(customer, data=customer_data)
        if customer_serializer.is_valid():
            customer_serializer.save()
            return JsonResponse(customer_serializer.data)
        return JsonResponse(customer_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    # DELETE existing customer
    elif request.method == 'DELETE':
        customer.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 15
0
    def update(self, request, *args, **kwargs):
        customer_id = self.kwargs['pk']
        user = self.request.user
        first_name = self.request.data['first_name']
        last_name = self.request.data['last_name']
        email = self.request.data['email']
        company = self.request.data['company']
        phone = self.request.data['phone']
        address = self.request.data['address']
        apartment = self.request.data['apartment']
        city = self.request.data['city']
        country = self.request.data['country']
        region = self.request.data['region']
        postal_code = self.request.data['postal_code']
        image = self.request.data['image']

        customer = Customer.objects.filter(pk=customer_id).first()

        if first_name:
            customer.first_name = first_name
        if last_name:
            customer.last_name = last_name
        if email:
            customer.email = email
        if company:
            customer.company = company
        if phone:
            customer.phone = phone
        if address:
            customer.address = address
        if apartment:
            customer.apartment = apartment
        if city:
            customer.city = city
        if country:
            customer.country = country
        if region:
            customer.region = region
        if postal_code:
            customer.postal_code = postal_code
        if image:
            customer.image = image

        customer.save()
        customer_serializer = CustomerSerializer(customer)

        sio.emit('create_change_customer', {
            'data': {
                'state': 'updated',
                'customer': customer_serializer.data,
                'user': {
                    'email': user.email,
                    'id': user.id
                }
            }
        }, namespace='/test')
        return Response(customer_serializer.data)
Ejemplo n.º 16
0
    def retrieve(self, request, pk, format=None):
        fields = ('name', 'email', 'favorites')
        customer = self.get_object(pk)
        serializer = CustomerSerializer(customer,
                                        context={'request': request},
                                        fields=fields)
        data_response = self.get_data_response(serializer_data=serializer.data)

        return Response(data_response)
Ejemplo n.º 17
0
    def put(self, request):
        customer = request.user

        for field, value in request.data.items():
            setattr(customer, field, value)

        customer.save()
        serializer_element = CustomerSerializer(instance=customer)
        return Response(serializer_element.data, status.HTTP_200_OK)
Ejemplo n.º 18
0
    def create(self, request):
        product_id = request.data.get('product_id')
        if product_id:
            product_id_status = utils.check_product_id(
                request.data.get('product_id'))
            # using false to make it explicit
            if product_id_status is False:
                return Response({"product_id": "This product does not exist."},
                                status.HTTP_400_BAD_REQUEST)

        fields = ('name', 'email', 'url')
        serializer = CustomerSerializer(data=request.data,
                                        context={'request': request},
                                        fields=fields)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 19
0
def customers_without_orders(request):
    try:
        customers = Customer.objects.exclude(
            order__created_at__gt=datetime.datetime(2016, 1, 1))
    except DatabaseError as ex:
        raise ex

    serializer = CustomerSerializer(customers, many=True)

    return Response(data={"data": serializer.data})
Ejemplo n.º 20
0
 def new(self, request):
     try:
         q = request.query_params
         q_d = {k: v[0] if len(v) == 1 else v for k, v in q.lists()}
         customer = Customer(**q_d)
         customer.save()
         return Response(data=CustomerSerializer(customer).data)
     except:
         print(traceback.format_exc())
         return Response(data={"is": "false"})
Ejemplo n.º 21
0
 def get(self, request):
     """
     Get a customer by ID. The customer is getting by token
     """
     customer_id = decode_token_from_request(request)
     if isinstance(request.user, AnonymousUser):
         logger.error(errors.USR_10.message)
         return errors.handle(errors.USR_10)
     customer = Customer.objects.get(customer_id=customer_id)
     serializer_element = CustomerSerializer(customer)
     return Response(serializer_element.data)
Ejemplo n.º 22
0
def customer(request):
    """
    Get a customer by ID. The customer is getting by token
    """
    logger.debug("Getting customer")
    user = request.user
    if isinstance(user, AnonymousUser):
        logger.error(errors.USR_10.message)
        return errors.handle(errors.USR_10)
    serializer_element = CustomerSerializer(user.customer)
    logger.debug("Success")
    return Response(serializer_element.data)
Ejemplo n.º 23
0
    def partial_update(self, request, pk, format=None):
        favorites = request.data.get('favorites')
        product_id_statuses = [
            utils.check_product_id(product_status.get("product_id"))
            for product_status in favorites
        ]

        if not any(product_id_statuses):
            return Response({"product_id": "This product does not exist."},
                            status.HTTP_400_BAD_REQUEST)

        fields = ('name', 'email', 'favorites')
        customer = self.get_object(pk)
        serializer = CustomerSerializer(customer,
                                        data=request.data,
                                        context={'request': request},
                                        fields=fields)
        if serializer.is_valid():
            serializer.save()
            data_response = self.get_data_response(
                serializer_data=serializer.data)
            return Response(data_response)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 24
0
 def post(self, request):
     form_data = request.data.dict()
     user = None
     if 'type' not in form_data:
         return Response(data=json.dumps(
             {'error': 'Login type not specified'}),
                         status=status.HTTP_400_BAD_REQUEST)
     elif form_data.get('type') not in ['admin', 'biller', 'customer']:
         return Response(data=json.dumps(
             {'error': 'Login type inappropriate'}),
                         status=status.HTTP_400_BAD_REQUEST)
     try:
         user = Mywallet.objects.filter(
             (Q(user__email=form_data.get('email', ''))
              | Q(user__username=form_data.get('username', ''))
              | Q(contact_number=form_data.get('contact_number', ''))),
             user__is_active=True,
             user__is_staff=True
             if form_data.get('type') is 'admin' else False,
         ).first()
     except Exception as e:
         Response(data=json.dumps({'error': 'DB error'}),
                  status=status.HTTP_404_NOT_FOUND)
     if user is None:
         user = User.objects.create_user(
             form_data.get('username', ''),
             email=form_data.get('email', ''),
             password=form_data.get('password', ''),
             **{
                 'first_name': form_data.get('first-name', ''),
                 'last_name': form_data.get('last-name', ''),
             })
         if form_data.get('type') == 'biller':
             user.is_active = False
             user.save()
         mywallet_user = Mywallet.objects.create(
             user=user, contact_number=form_data.get('contact_number'))
         if form_data.get('type') == 'admin':
             serializer = MywalletSerializer(mywallet_user)
         elif form_data.get('type') == 'biller':
             serializer = BillerSerializer(
                 Biller.objects.create(biller=mywallet_user))
         elif form_data.get('type') == 'customer':
             serializer = CustomerSerializer(
                 Customer.objects.create(customer=mywallet_user))
         return Response(serializer.data)
     Response(data=json.dumps(
         {'error': 'Username / EmailID already in use'}),
              status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 25
0
    def get(self, request):
        cache_key = 'AllCustomerReport'  # needs to be unique

        data = cache.get(cache_key)  # returns None if no key-value pair
        # print('---->', settings.CACHE_DURATION)
        # print('---->',data)
        print('---->',cache.key_prefix)

        if not data:
            cust = Customer.objects.all()
            # cache_time = settings.CACHE_DURATION
            data = CustomerSerializer(cust, many=True).data
        cache.set(cache_key, data, settings.CACHE_DURATION)

        return Response(data)
Ejemplo n.º 26
0
    def put(self, request):
        customer = request.user
        shipping_id = request.data.get("shipping_region_id", None)

        if shipping_id is None:
            errors.COM_01.message = "The field shipping_region_id is required"
            return errors.handle(errors.COM_01)

        if not isinstance(shipping_id, int):
            return errors.handle(errors.USR_09)
        for field, value in request.data.items():
            setattr(customer, field, value)

        customer.save()
        serializer_element = CustomerSerializer(instance=customer)
        return Response(serializer_element.data, status.HTTP_200_OK)
Ejemplo n.º 27
0
 def get(self, request, user_id=None):
     customer = None
     try:
         if user_id is None:
             customer = self.get_object()
         else:
             customer = self.get_object(user_id)
         if customer is not None:
             serializer = CustomerSerializer(
                 customer,
                 many=True if isinstance(customer, QuerySet) else False)
             return Response(serializer.data)
         return Response(status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         return Response(data=json.dumps({'error': 'Unauthorized'}),
                         status=status.HTTP_404_UNAUTHORIZED)
Ejemplo n.º 28
0
 def post(self, request):
     customer_details = {
         "name": request.data.get("name", None),
         "email": request.data.get("email", None),
         "password": request.data.get("password", None),
     }
     customer_instance = Customer.objects.create_customer(
         **customer_details)
     serializer = CustomerSerializer(instance=customer_instance)
     return Response(
         {
             "customer": serializer.data,
             "accessToken": "",
             "expiresIn": ""
         },
         status=201,
     )
Ejemplo n.º 29
0
 def get_queryset(self):
     customer_id = self.kwargs['pk']
     user = self.request.user
     queryset = Customer.objects.filter(pk=customer_id)
     customer = Customer.objects.filter(pk=customer_id).first()
     customer_serializer = CustomerSerializer(customer)
     sio.emit('create_change_customer', {
         'data': {
             'state': 'deleted',
             'customer': customer_serializer.data,
             'user': {
                 'email': user.email,
                 'id': user.id
             }
         }
     }, namespace='/test')
     return queryset
Ejemplo n.º 30
0
def customer_list(request):
    """
    List all code snippets, or create a new customer.
    """
    if request.method == 'GET':
        customers = Customer.objects.all()
        serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CustomerSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 31
0
def customers(request):
    try:
        customers = Customer.objects.all()
    except Customer.DoesNotExist as e:
        return Response({'error': str(e)})

    if request.method == 'GET':
        serializer = CustomerSerializer(customers, many=True)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = CustomerSerializer(instance=customers, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'error': serializer.errors})