def get_done_bills(self, request, **kwargs): customer = self.get_object() queryset = customer.bills.all() page = self.paginate_queryset(queryset) if page is not None: serializer = BillSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = BillSerializer(queryset, many=True) return Response(serializer.data)
def add_bill(self, request, pk=None): person = self.get_object() serializer = BillSerializer(data=request.data) if serializer.is_valid(): bill_instance = serializer.save() person.bills.add(bill_instance) person.save() return Response(PersonSerializer(person), status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): bill = Bill.objects.get(pk=self.request.data.get('bill', None)) if bill.status != "active": raise PermissionDenied staff = Staff.objects.get(username=request.user.username) if staff.job in self.non_creator: raise PermissionDenied item = self.request.data product_code = item['product'] try: product = Product.objects.get(code=product_code) except ObjectDoesNotExist: raise ValidationError( 'محصولی با کد {} وجود ندارد.'.format(product_code)) amount = item['amount'] end_of_roll_amount = None end_of_roll = item.get('end_of_roll', False) if end_of_roll: end_of_roll_amount = item['end_of_roll_amount'] discount = item.get('discount', 0) BillItem.objects.create(product=product, amount=amount, discount=discount, end_of_roll=end_of_roll, end_of_roll_amount=end_of_roll_amount, bill=bill) serializer = BillSerializer(bill) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def daily_report(self, request): total_benefit, total_discount, total_price, total_final_price, total_items, total_bills = 0, 0, 0, 0, 0, 0 total_cheque_paid, total_cash_paid, total_card_paid, total_paid, reminded_payments = 0, 0, 0, 0, 0 data = {} bills = Bill.objects.filter(close_date__date=datetime.today().date(), status__in=["remained", "done"]) bills_with_reminded_status = bills.filter(status="remained").count() total_bills = bills.count() for bill in bills: total_final_price += bill.final_price total_price += bill.price total_paid += bill.paid total_discount += bill.total_discount total_benefit += bill.profit total_items += bill.items.count() total_cheque_paid += bill.cheque_paid total_cash_paid += bill.cash_paid total_card_paid += bill.card_paid reminded_payments += bill.remaining_payment data['bills_data'] = BillSerializer(bills, many=True).data data['total_profit'] = total_benefit data['total_discount'] = total_discount data['total_price'] = total_price data['total_final_price'] = total_final_price data['total_items'] = total_items data['total_bills'] = total_bills data['total_cheque_paid'] = total_cheque_paid data['total_cash_paid'] = total_cash_paid data['total_card_paid'] = total_card_paid data['total_paid'] = total_paid data['total_reminded_payments'] = reminded_payments data['bills_with_reminded_status'] = bills_with_reminded_status return Response(data)
def list(self, request): subscriber = request.GET.get('subscriber', None) reference = request.GET.get('reference', None) if subscriber is None: message = 'Please enter a subscriber' return Response(message, status=status.HTTP_400_BAD_REQUEST) queryset = Bill.objects.filter(call_start_record__source=subscriber) if reference is not None: try: d = datetime.strptime(reference, '%m/%Y') data = { 'call_end_record__timestamp__year': d.year, 'call_end_record__timestamp__month': d.month } except ValueError as e: message = 'Please enter a valid date fomat %m/%Y' return Response(message, status=status.HTTP_400_BAD_REQUEST) else: now = datetime.now() month = now.month - 1 data = { 'call_end_record__timestamp__year': now.year, 'call_end_record__timestamp__month': month } queryset = queryset.filter(**data) ctx = {'request': request} serializer = BillSerializer(queryset, context=ctx, many=True) return Response(serializer.data)
def update(self, request, *args, **kwargs): bill = self.get_object().bill if bill.seller.username != request.user.username or bill.status != "active": raise PermissionDenied super(BillItemViewSet, self).update(request, *args, **kwargs) serializer = BillSerializer(bill) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers)
def test_retrieve_bills(self): """Test retrieving bills""" res = self.client.get(BILLS_URL) bills = Bill.objects.all() serializer = BillSerializer(bills, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def destroy(self, request, *args, **kwargs): bill = self.get_object().bill bill_item_product = self.get_object().product bill_item_amount = self.get_object().amount if bill.seller.username != request.user.username or bill.status != "active": raise PermissionDenied super(BillItemViewSet, self).destroy(request, *args, **kwargs) bill_item_product.update_stock_amount(-1 * (bill_item_amount + 0.05)) serializer = BillSerializer(bill) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers)
def get_bill_detailed(self, request, pk=None): """ :param request: no special data :param pk: :return: {serialized detailed info about person`s bills} """ person = self.get_object() return Response( BillSerializer(person.bills.all(), many=True).data, status.HTTP_200_OK)
def add_bill(self, request, pk=None): """ :param request: should contain the data in bill serializer format :param pk: :return: Person Serialized format of person instance and errors otherwise """ person = self.get_object() qr = BillService.prepare_data(request.data) bill_info = BillService.get_info(qr) serializer = BillSerializer(data=bill_info) if serializer.is_valid(): bill_instance = serializer.save() person.bills.add(bill_instance) person.save() return Response(PersonSerializer(person).data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def api_create_bill_view(request): bill_post = Bill(owner_id=request.user) account_user = Account.objects.get(email=request.user) if request.method == 'POST': django_statsd.incr('api.createBill') django_statsd.start('api.createBill.time.taken') serializer = BillSerializer(bill_post, data=request.data) data = {} if serializer.is_valid(): categories_list = serializer.validated_data['categories'] if len(categories_list) != len(set(categories_list)): return Response({'response': "Categories must be unique."}, status=status.HTTP_400_BAD_REQUEST) django_statsd.start('api.createBill.db') bill = serializer.save() django_statsd.stop('api.createBill.db') data['response'] = 'successfully added a new bill.' data['uuid_bill_id'] = bill.uuid_bill_id data['created_ts'] = bill.created_ts data['updated_ts'] = bill.updated_ts data['owner_id'] = account_user.uuid_id data['vendor'] = bill.vendor data['bill_date'] = bill.bill_date data['due_date'] = bill.due_date data['amount_due'] = bill.amount_due data['categories'] = bill.categories data['payment_status'] = bill.payment_status logger.info("POST: Added Bill") django_statsd.stop('api.createBill.time.taken') return Response(data, status=status.HTTP_201_CREATED) logger.error("ERROR: Something Happened: %s", serializer.errors) django_statsd.stop('api.createBill.time.taken') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_bills_bycondition(self, request): """ 后台根据条件产看账单 :param request: :return: """ query_param = { 'bill_uuid': request.GET.get('bill_uuid', None), 'user_uuid': request.GET.get('user_uuid', None), 'host_uuid': request.GET.get('host_uuid', None), 'pay_status': request.GET.get('pay_status', None), 'bill_account_time__gte': request.GET.get('bill_account_time__gte', None), 'bill_account_time__lte': request.GET.get('bill_account_time__lte', None) } try: total_bills = Bill.objects.filter(**get_kwargs(query_param)) count = total_bills.count() desc, limit, offset = get_query_paganaiton(request) bills = total_bills.order_by('bill_account_time')[offset:offset + limit] serializer = BillSerializer(bills, many=True) return Response({'content': serializer.data, 'count': count}) except KeyError: return Response({ 'detail': 'key error', 'error_code': '5400' }, status=status.HTTP_400_BAD_REQUEST) except ValueError: return Response({'content': {}, 'count': 0}) except Exception as e: log.error('[bill] views.get_bills_bycondition.e:{}'.format( e.__str__())) return Response( { 'detail:': 'value has an invalid format', 'error_code': '5400' }, status=status.HTTP_400_BAD_REQUEST)
def add_payments(self, request, **kwargs): payment_type = self.request.data.get('type') bill = self.get_object() if payment_type == "cash_card": cash_amount = self.request.data.get('cash_amount', 0) card_amount = self.request.data.get('card_amount', 0) if cash_amount: payment_type = "cash" CustomerPayment.objects.create(create_date=timezone.now(), amount=float(cash_amount), bill=bill, type=payment_type) if card_amount: payment_type = "card" CustomerPayment.objects.create(create_date=timezone.now(), amount=float(card_amount), bill=bill, type=payment_type) elif payment_type == "cheque": amount = self.request.data.get('amount', None) if amount is None: raise ValidationError("مقدار تمیتواند خالی باشد") bank = self.request.data.get('bank') number = self.request.data.get('number') issue_date = self.request.data.get('issue_date', timezone.now().date()) expiry_date = self.request.data.get('expiry_date') cheque = CustomerCheque.objects.create(number=int(number), bank=bank, issue_date=issue_date, expiry_date=expiry_date, amount=int(amount), customer=bill.buyer) CustomerPayment.objects.create(create_date=timezone.now(), cheque=cheque, amount=float(amount), bill=bill, type=payment_type) data = BillSerializer(Bill.objects.get(pk=bill.pk)).data return Response(data, status=status.HTTP_201_CREATED)
def get_bill_detailed(self, request, pk=None): person = self.get_object() return Response(BillSerializer(person.bills.all(), many=True), status.HTTP_200_OK)
def api_get_put_delete_bill_view(request, uuid_bill_id): account_user = Account.objects.get(email=request.user) try: django_statsd.start('api.getBill.DB') bill = Bill.objects.get(uuid_bill_id=uuid_bill_id) if bill.attachment is not None: file = File.objects.get(uuid_file_id=bill.attachment.uuid_file_id) django_statsd.stop('api.getBill.DB') except Bill.DoesNotExist: logger.error("Bill Doesn't Exist") django_statsd.stop('api.getBill.DB') return Response({'response': "Bill doesn't exist."}, status=status.HTTP_404_NOT_FOUND) if bill.owner_id != request.user: logger.error("User Doesn't have permissions") return Response({'response': "You don't have permissions to get/update/delete that bill."}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': django_statsd.incr('api.getBill') django_statsd.start('api.getBill.time.taken') serializer = BillGetSerializer(bill) django_statsd.stop('api.getBill.time.taken') return Response(serializer.data) elif request.method == 'PUT': django_statsd.incr('api.putBill') django_statsd.start('api.putBill.time.taken') serializer = BillSerializer(bill, data=request.data) data = {} if serializer.is_valid(): categories_list = serializer.validated_data['categories'] if len(categories_list) != len(set(categories_list)): return Response({'response': "Categories must be unique."}, status=status.HTTP_400_BAD_REQUEST) django_statsd.start('api.putBill.DB') serializer.save() django_statsd.stop('api.putBill.DB') data['response'] = 'successfully updated a new bill.' data['uuid_bill_id'] = bill.uuid_bill_id data['created_ts'] = bill.created_ts data['updated_ts'] = bill.updated_ts data['owner_id'] = account_user.uuid_id data['vendor'] = bill.vendor data['bill_date'] = bill.bill_date data['due_date'] = bill.due_date data['amount_due'] = bill.amount_due data['categories'] = bill.categories data['payment_status'] = bill.payment_status logger.info("PUT: Update Bill for User") django_statsd.stop('api.putBill.time.taken') return Response(data=data, status=status.HTTP_200_OK) logger.error("ERROR: Something Happened: %s", serializer.errors) django_statsd.stop('api.putBill.time.taken') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': django_statsd.incr('api.deleteBill') django_statsd.start('api.deleteBill.time.taken') if bill.attachment is not None: if 'S3_BUCKET_NAME' in os.environ: django_statsd.start('s3.deleteBill.File.time.taken') bill.attachment.url.delete(save=False) django_statsd.stop('s3.deleteBill.File.time.taken') else: file_path = 'bill/{file_id}-{filename}'.format( file_id=str(file.uuid_file_id), filename=file.file_name ) os.remove(os.path.join(settings.MEDIA_ROOT, file_path)) django_statsd.start('api.deleteBill.DB') operation = bill.delete() django_statsd.stop('api.deleteBill.DB') data = {} if operation: data['response'] = 'successfully deleted a new bill.' logger.info("DELETE: Bill deleted") django_statsd.stop('api.deleteBill.time.taken') return Response(data=data, status=status.HTTP_204_NO_CONTENT)