示例#1
0
def pod_archive_data(request):
    booking_ids = manual_booking_id_list(username=request.user.username,
                                         user_group_list=request.user.groups.values_list('name', flat=True))
    start = to_int(request.GET.get('start'))
    end = start + to_int(request.GET.get('length'))
    if request.GET.get('search[value]'):
        search_value = request.GET.get('search[value]')
        pod_files = PODFile.objects.filter(booking_id__in=booking_ids).filter(
            Q(booking__booking_id__icontains=search_value) | Q(
                booking__lr_numbers__lr_number__icontains=search_value) | Q(
                uploaded_by__profile__name=search_value)).order_by('-id')
    else:
        pod_files = PODFile.objects.filter(booking_id__in=booking_ids).order_by('-id')
    data = []
    for pod in pod_files[start:end if end != -1 else pod_files.count()]:
        data.append([
            pod.created_on.strftime('%d-%b-%Y %H:%M'),
            pod.uploaded_by.profile.name if pod.uploaded_by else '',
            pod.booking.booking_id if pod.booking else '',
            pod.lr_number.lr_number if pod.lr_number else '',
            format_html('''<a href="{}" download><i class="fa fa-download" aria-hidden="true"></i></a>''',
                        pod.s3_upload.public_url() if pod.s3_upload else '')
        ])
    data = {
        "draw": to_int(request.GET.get('draw')),
        "recordsTotal": pod_files.count(),
        "recordsFiltered": pod_files.count(),
        "data": data
    }
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#2
0
def unverified_documents_data(request):
    start = to_int(request.GET.get('start'))
    end = start + to_int(request.GET.get('length'))
    s3_uploads = S3Upload.objects.filter(
        Q(verified=False)
        & (Q(filename__iendswith='.jpg') | Q(filename__iendswith='.jpeg')
           | Q(filename__iendswith='.png'))).order_by('-uploaded_on')
    data = []
    for s3 in s3_uploads[start:end]:
        data.append([
            s3.uploaded_on.strftime('%d-%b-%Y') if s3.uploaded_on else '',
            s3.folder, s3.filename,
            format_html(
                '''<a href="{}"><i class="fa fa-image" style="font-size: 24px"  aria-hidden="true"></i></a>''',
                s3.public_url()),
            format_html(
                '''<form action="/team/verify-documents/" method="GET">   
                        <input type="hidden" name="s3_upload_id" value="{}">
                        <button type="submit" class="btn btn-success" name="accept_choice" value="accept"><i style="font-size: 24px" 
                        class="fa fa-check-circle"></i></button> 
                        <button type="submit" class="btn btn-danger" name="accept_choice" value="reject"><i
                        style="font-size: 24px" class="fa fa-times-circle"></i></button>
                    </form>''', s3.id)
        ])
    data = {
        "draw": to_int(request.GET.get('draw')),
        "recordsTotal": s3_uploads.count(),
        "recordsFiltered": s3_uploads.count(),
        "data": data
    }
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#3
0
def save_additional_charges(request, booking):
    booking.loading_charge = to_int(request.POST.get('loading_charge'))
    booking.unloading_charge = to_int(request.POST.get('unloading_charge'))
    booking.detention_charge = to_int(request.POST.get('detention_charge'))
    booking.additional_charges_for_owner = to_int(
        request.POST.get('additional_charges_for_owner'))
    booking.note_for_additional_owner_charges = request.POST.get(
        'note_for_additional_owner_charges')
    booking.save()
示例#4
0
def save_vendor_deduction(request, booking):
    booking.commission = to_int(request.POST.get('commission'))
    booking.lr_cost = to_int(request.POST.get('lr_cost'))
    booking.deduction_for_advance = to_int(
        request.POST.get('deduction_for_advance'))
    booking.deduction_for_balance = to_int(
        request.POST.get('deduction_for_balance'))
    booking.other_deduction = to_int(request.POST.get('other_deduction'))
    booking.remarks_about_deduction = request.POST.get(
        'remarks_about_deduction')
    booking.save()
示例#5
0
def save_rate_details(request, booking):
    booking.loaded_weight = to_float(request.POST.get('loaded_weight'))
    booking.supplier_charged_weight = to_float(
        request.POST.get('supplier_charged_weight'))
    booking.supplier_rate = to_int(request.POST.get('supplier_rate'))
    booking.total_amount_to_owner = to_int(
        request.POST.get('total_amount_to_owner'))
    if EMP_GROUP1 in request.user.groups.values_list(
            'name',
            flat=True) or EMP_GROUP2 in request.user.groups.values_list(
                'name', flat=True):
        booking.charged_weight = to_float(request.POST.get('charged_weight'))
        booking.party_rate = to_int(request.POST.get('party_rate'))
        booking.total_amount_to_company = to_int(
            request.POST.get('total_amount_to_party'))
        booking.refund_amount = to_int(request.POST.get('refundable_amount'))
        booking.additional_charges_for_company = to_int(
            request.POST.get('additional_charges_for_company'))
        booking.deductions_for_company = to_int(
            request.POST.get('deductions_for_company'))
        booking.invoice_remarks_for_deduction_discount = request.POST.get(
            'invoice_remarks_for_deduction_discount')
        booking.advance_amount_from_company = request.POST.get(
            'advance_from_company')
        booking.invoice_remarks_for_additional_charges = request.POST.get(
            'invoice_remarks_for_additional_charges')
        booking.tds_deducted_amount = to_int(
            request.POST.get('tds_deducted_amount'))
    return booking
示例#6
0
def get_lr_data(booking):
    char_fields = ['consignor_name', 'consignor_address', 'consignor_pin', 'consignor_phone',
                   'consignor_gstin', 'consignee_name', 'consignee_address', 'consignee_pin',
                   'consignee_phone', 'consignee_gstin', 'billing_type',
                   'road_permit_number', 'party_invoice_number', 'party_invoice_amount', 'number_of_package',
                   'material', 'insurance_provider', 'insurance_policy_number', 'insurance_risk',
                   'gst_liability', 'driver_phone', 'driver_dl_number']
    text_fields = []
    date_fields = ['shipment_date', 'party_invoice_date', 'insurance_date', 'driver_dl_validity',
                   'billing_invoice_date']
    datetime_fields = []
    data = {}
    for prop in char_fields:
        data[prop] = '' if not getattr(booking, prop, '') else getattr(booking, prop, '')
    for prop in date_fields:
        data[prop] = display_date_format(getattr(booking, prop, ''))
    for prop in datetime_fields:
        data[prop] = display_datetime_format(getattr(booking, prop, ''))
    data['transiq'] = get_company_data()
    data['driver_dl_number'] = '' if not booking.driver_dl_number else booking.driver_dl_number
    data['from_city'] = '' if not isinstance(booking.from_city_fk, City) else booking.from_city_fk.name
    data['lorry_number'] = '' if not isinstance(booking.supplier_vehicle, Vehicle) else booking.supplier_vehicle.number()
    data['to_city'] = '' if not isinstance(booking.to_city_fk, City) else booking.to_city_fk.name
    data['consignor_city'] = '' if not isinstance(booking.consignor_city_fk, City) else booking.consignor_city_fk.name
    data['consignee_city'] = '' if not isinstance(booking.consignee_city_fk, City) else booking.consignee_city_fk.name
    data['driver_phone'] = booking.driver_phone if booking.driver_phone else ''
    if isinstance(booking.source_office, AahoOffice):
        branch = AahoOffice.objects.get(id=booking.source_office.id)
        branch_name = branch.branch.name if branch.branch else ''
    else:
        branch_name = ''
    data['branch'] = branch_name
    data['delivery_office'] = ''

    if to_int(data['party_invoice_amount']) == 0:
        data['party_invoice_amount'] = ''
    else:
        data['party_invoice_amount'] = '' if to_int(data['party_invoice_amount']) == 0 else to_int(
            data['party_invoice_amount'])

    if booking.insured_amount < 1:
        data['insurance_amount'] = ''

    office_id = '' if not booking.source_office else booking.source_office.id
    office_address, office_phone = aaho_office_details(office_id=office_id)
    data['office_id'] = office_id
    data['office_address'] = office_address
    data['office_phone'] = office_phone
    data['is_print_payment_mode_instruction'] = booking.is_print_payment_mode_instruction
    return data
示例#7
0
def save_rate_details(request, booking):
    booking.loaded_weight = to_float(request.POST.get('loaded_weight'))
    booking.supplier_charged_weight = to_float(
        request.POST.get('supplier_charged_weight'))
    if EMP_GROUP1 in request.user.groups.values_list(
            'name',
            flat=True) or EMP_GROUP2 in request.user.groups.values_list(
                'name', flat=True):
        booking.party_rate = to_int(request.POST.get('party_rate'))
        booking.total_amount_to_company = to_int(
            request.POST.get('total_amount_to_party'))
        booking.charged_weight = to_float(request.POST.get('charged_weight'))
    booking.supplier_rate = to_int(request.POST.get('supplier_rate'))
    booking.total_amount_to_owner = to_int(
        request.POST.get('total_amount_to_owner'))
    booking.save()
示例#8
0
def full_booking_multi_invoice_booking_data(request):
    rows = to_int(request.GET.get('page'))
    search_value = request.GET.get('search')
    exclude_kwargs = Q(booking_status__iexact='cancelled') | Q(
        deleted=True) | Q(booking_id__istartswith='AB') | Q(
            booking_id__istartswith='BROKER')
    bookings = ManualBooking.objects.filter(
        Q(invoice_status__iexact='no_invoice')).exclude(
            exclude_kwargs).order_by('-id', '-shipment_date')
    if search_value:
        bookings = ManualBooking.objects.filter(
            Q(invoice_status__iexact='no_invoice')
            & (Q(booking_id__icontains=search_value)
               | Q(id__in=LrNumber.objects.filter(
                   lr_number__icontains=search_value).values_list(
                       'booking__id', flat=True)))).exclude(
                           exclude_kwargs).order_by('-id', '-shipment_date')
    data = []
    user_group = request.user.groups.values_list('name', flat=True)[0]
    if EMP_GROUP2 == user_group or EMP_GROUP3 == user_group:
        bookings = bookings.exclude(billing_type='contract')
    for booking in bookings[:rows]:
        data.append({
            'id':
            booking.id,
            'text':
            '{}( {} )'.format(
                booking.booking_id, ', '.join(
                    booking.lr_numbers.values_list('lr_number', flat=True)))
            if booking.lr_numbers.exists() else booking.booking_id
        })
    data = {'results': data}
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#9
0
def update_inward_payment(booking_id_list,
                          payment_id,
                          received_from,
                          amount,
                          payment_mode,
                          remarks,
                          date,
                          invoice_number,
                          trn,
                          tds_amount=0):
    manual_bookings = ManualBooking.objects.filter(id__in=booking_id_list)
    payment = InWardPayment.objects.get(id=payment_id)
    payment.received_from = received_from
    payment.tds = tds_amount
    payment.actual_amount = amount
    payment.payment_mode = payment_mode
    payment.remarks = remarks
    payment.payment_date = django_date_format(date)
    payment.invoice_number = invoice_number
    payment.trn = trn
    payment.save()
    for value in payment.booking_id.all():
        value.total_in_ward_amount -= to_int(amount)
        value.tds_deducted_amount += int(float(tds_amount))
        value.save()
    payment.booking_id.clear()
    for booking in manual_bookings:
        payment.booking_id.add(booking)
    for booking in manual_bookings:
        update_inward_payments(booking)
示例#10
0
def in_ward_payments(request):
    if request.method == 'POST':
        payment = InWardPayment.objects.create(
            received_from=request.POST.get('received_from'),
            actual_amount=request.POST.get('actual_amount'),
            payment_mode=request.POST.get('payment_mode'),
            remarks=request.POST.get('remarks'),
            payment_date=django_date_format(
                request.POST.get('inward_payment_date')),
            invoice_number=request.POST.get('invoice_number'),
            created_by=User.objects.get(username=request.user.username))
        booking_id_list = request.POST.getlist('booking_id[]')
        for booking_id in booking_id_list:
            manual_booking_id = ManualBooking.objects.get(
                booking_id=booking_id)
            in_ward_payment = InWardPayment.objects.filter(
                booking_id=manual_booking_id)
            amount = 0
            for value in in_ward_payment:
                amount += value.actual_amount
            amount += to_int(float(request.POST.get('actual_amount')))
            manual_booking_id.total_in_ward_amount = amount
            manual_booking_id.save()
            payment.booking_id.add(manual_booking_id)
            update_inward_payments(manual_booking_id)
示例#11
0
def send_customer_welcome_email(sme_id):
    sme = get_or_none(Sme, id=sme_id)
    if not isinstance(sme, Sme):
        return
    client = get_client()
    s3_obj1 = client.get_object(Bucket='aahodocuments',
                                Key='company_docs/PAN Card.jpg')
    s3_obj2 = client.get_object(
        Bucket='aahodocuments',
        Key='company_docs/Trans IQ TDS Declaration FY18-19.pdf')
    s3_obj3 = client.get_object(
        Bucket='aahodocuments',
        Key='company_docs/Udyog Aadhaar Acknowledgement.xps')

    subject = 'Welcome to Aaho Trucking!'
    body = get_template(
        'team/emails/customer_welcome_email_template.html').render(
            context={'customer_cp': to_int(sme.credit_period)})

    email = EmailMessage(subject, body, to=[sme.sme_email])
    email.content_subtype = 'html'
    email.attach('PAN Card.jpg', s3_obj1['Body'].read(), "application/jpeg")
    email.attach('Trans IQ TDS Declaration FY18-19.pdf',
                 s3_obj2['Body'].read(), "application/pdf")
    email.attach('Udyog Aadhaar Acknowledgement.xps', s3_obj3['Body'].read(),
                 "application/oxps")

    if settings.ENABLE_MAIL and not settings.TESTING:
        email.send()
示例#12
0
def invoices_summary_data(request):
    invoices_summary = InvoiceSummary.objects.exclude(deleted=True).order_by(
        '-id', '-datetime')
    start = to_int(request.GET.get('start'))
    end = start + to_int(request.GET.get('length'))
    if request.GET.get('search[value]'):
        search_value = request.GET.get('search[value]').strip()
        invoices_summary = InvoiceSummary.objects.exclude(deleted=True).filter(
            Q(s3_upload__filename__icontains=search_value)).order_by(
                '-id', '-datetime')
        try:
            search_value = int(search_value)
            invoices_summary = InvoiceSummary.objects.exclude(
                deleted=True).filter(
                    Q(s3_upload__filename__icontains=search_value)
                    | Q(id=search_value)).order_by('-id', '-datetime')
        except ValueError:
            invoices_summary = InvoiceSummary.objects.exclude(
                deleted=True).filter(
                    Q(s3_upload__filename__icontains=search_value)).order_by(
                        '-id', '-datetime')
    data = []
    for row in invoices_summary[start:end if end != -1 else invoices_summary.
                                count()]:
        data.append([
            row.datetime.strftime('%d-%b-%Y') if row.datetime else '', row.id,
            row.ref_number,
            '<br>'.join(row.booking.values_list('booking_id', flat=True)),
            '<br>'.join([
                '<br>'.join(
                    booking.lr_numbers.values_list('lr_number', flat=True))
                for booking in row.booking.all()
            ]),
            format_html(
                '''<a href="{}" download><i class="fa fa-download" aria-hidden="true"></i></a>''',
                row.s3_upload.public_url() if row.s3_upload else ''),
            row.s3_upload.filename if row.s3_upload else ''
        ])
    data = {
        "draw": to_int(request.GET.get('draw')),
        "recordsTotal": invoices_summary.count(),
        "recordsFiltered": invoices_summary.count(),
        "data": data
    }
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#13
0
def save_updated_out_ward_payment(request):
    booking_id_list = request.POST.getlist('booking_id[]')
    payment_id = OutWardPayment.objects.get(id=request.POST.get('payment_id'))
    old_amount = str(to_int(payment_id.actual_amount))
    new_amount = str(to_int(request.POST.get('actual_amount')))
    payment_id.paid_to = request.POST.get('paid_to')
    payment_id.actual_amount = request.POST.get('actual_amount')
    payment_id.remarks = request.POST.get('remarks')
    payment_id.payment_date = django_date_format(
        request.POST.get('outward_payment_date'))
    payment_id.invoice_number = request.POST.get('invoice_number')
    payment_id.fuel_card = None if not request.POST.get(
        'fuel_card_number') else FuelCard.objects.get(
            id=request.POST.get('fuel_card_number'))
    # save_outward_payment__mode(request, payment_id)
    if payment_id.payment_mode not in [
            'neft', 'rtgs', 'hdfc_internal_account'
    ]:
        payment_id.status = 'paid'
        payment_id.save()
    for value in payment_id.booking_id.all():
        value.total_out_ward_amount -= to_int(
            request.POST.get('actual_amount'))
        value.save()
    payment_id.booking_id.clear()
    booking_id = ''
    for value in booking_id_list:
        manual_booking_id = ManualBooking.objects.get(booking_id=value)
        payment_id.booking_id.add(manual_booking_id)
        out_ward_payment = OutWardPayment.objects.filter(
            booking_id=manual_booking_id).exclude(is_refund_amount=True)
        amount = 0
        for value in out_ward_payment:
            amount += value.actual_amount
        if manual_booking_id.total_amount_to_owner > amount:
            manual_booking_id.outward_payment_status = 'partial'
        elif manual_booking_id.total_amount_to_owner == amount:
            manual_booking_id.outward_payment_status = 'complete'
        elif manual_booking_id.total_amount_to_owner < amount:
            manual_booking_id.outward_payment_status = 'excess'
        manual_booking_id.total_out_ward_amount = amount
        booking_id = manual_booking_id.booking_id
        manual_booking_id.save()
        email_updated_outward_payment(request, booking_id, payment_id,
                                      old_amount, new_amount)
示例#14
0
def get_booking_id():
    try:
        booking = ManualBooking.objects.filter(
            Q(booking_id__istartswith='AH')
            | Q(booking_id__istartswith='AAHO')).latest('created_on')
        id = str(booking.booking_id)
        temp = to_int(id[4:]) + 1
        booking_id = id[0:4] + '{0:05d}'.format(temp)
    except ManualBooking.DoesNotExist:
        booking_id = 'AAHO00001'
    return booking_id
示例#15
0
def supplier_payment_receipt_data(request):
    booking_ids = manual_booking_id_list(username=request.user.username,
                                         user_group_list=request.user.groups.values_list('name', flat=True))
    start = to_int(request.GET.get('start'))
    end = start + to_int(request.GET.get('length'))
    if request.GET.get('search[value]'):
        search_value = request.GET.get('search[value]')
        if LrNumber.objects.filter(lr_number__icontains=search_value).exists():
            booking_ids = LrNumber.objects.filter(lr_number__icontains=search_value).values_list('booking__id')
            payment_receipts = OutWardPaymentBill.objects.filter(
                booking__in=ManualBooking.objects.filter(Q(id__in=booking_ids))).order_by('-id')
        else:
            payment_receipts = OutWardPaymentBill.objects.filter(booking_id__in=booking_ids).filter(
                Q(booking__booking_id__icontains=search_value) | Q(bill_number__icontains=search_value)).order_by('-id')
    else:
        payment_receipts = OutWardPaymentBill.objects.filter(booking_id__in=booking_ids).order_by('-id')
    data = []
    for receipt in payment_receipts[start:end if end != -1 else payment_receipts.count()]:
        data.append([
            receipt.bill_date.strftime('%d-%b-%Y'),
            '{}-{}'.format('OPB', receipt.bill_number),
            format_html('''<a href="{}" download><i class="fa fa-download" aria-hidden="true"></i></a>''',
                        S3Upload.objects.filter(filename__istartswith='{}-{}'.format('OPB', receipt.bill_number),
                                                filename__iendswith='.pdf').last().public_url()) if S3Upload.objects.filter(
                filename__istartswith='{}-{}'.format('OPB', receipt.bill_number),
                filename__iendswith='.pdf').exists() else '',
            receipt.booking.booking_id if receipt.booking else '',
            '<br>'.join(receipt.booking.lr_numbers.values_list('lr_number', flat=True)) if receipt.booking else '',
            '<br>'.join([payment.payment_date.strftime('%d-%b-%Y') if payment.payment_date else '' for payment in
                         receipt.outward_pmt.all()]),
            '<br>'.join([str(to_int(payment.actual_amount)) for payment in receipt.outward_pmt.all()]),
            '<br>'.join([payment.get_payment_mode_display() for payment in receipt.outward_pmt.all()]),
            str(to_int(receipt.amount))
        ])
    data = {
        "draw": to_int(request.GET.get('draw')),
        "recordsTotal": payment_receipts.count(),
        "recordsFiltered": payment_receipts.count(),
        "data": data
    }
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#16
0
def supplier_booking_data(bookings):
    data = []
    for booking in bookings:
        if to_int(booking.total_amount_to_owner - booking.total_out_ward_amount) != 0:
            data.append(
                {
                    'status': 'unpaid',
                    'lr_number': '\n'.join(booking.lr_numbers.values_list('lr_number',
                                                                          flat=True)) if booking.lr_numbers.exists() else booking.booking_id,
                    'paid': to_int(booking.total_out_ward_amount),
                    'transaction_id': booking.id,
                    'id': booking.id,
                    'vehicle_number': display_format(booking.lorry_number),
                    'source_city': booking.from_city,
                    'destination_city': booking.to_city,
                    'amount': to_int(booking.total_amount_to_owner),
                    'shipment_date': booking.shipment_date.strftime('%d-%b-%Y'),
                    'balance': to_int(booking.total_amount_to_owner - booking.total_out_ward_amount),
                    'booking_id': booking.booking_id,
                    'pod_status': booking.pod_status,
                    'pod_docs': [
                        {'url': pod.s3_url if pod.s3_url else pod.s3_upload.public_url(),
                         'thumb_url': pod.s3_thumb_url if pod.s3_thumb_url else pod.s3_upload.public_url(),
                         'lr_number': pod.lr_number.lr_number if pod.lr_number else ''} for pod in
                        booking.podfile_set.all()
                    ]
                }
            )
        else:
            data.append(
                {
                    'status': 'paid',
                    'lr_number': '\n'.join(booking.lr_numbers.values_list('lr_number',
                                                                          flat=True)) if booking.lr_numbers.exists() else booking.booking_id,
                    'paid': to_int(booking.total_out_ward_amount),
                    'id': booking.id,
                    'transaction_id': booking.id,
                    'booking_id': booking.booking_id,
                    'vehicle_number': display_format(booking.lorry_number),
                    'source_city': booking.from_city,
                    'destination_city': booking.to_city,
                    'amount': to_int(booking.total_amount_to_owner),
                    'shipment_date': booking.shipment_date.strftime('%d-%b-%Y'),
                    'balance': to_int(booking.total_amount_to_owner - booking.total_out_ward_amount),
                    'final_payment_date': final_payment_date(booking=booking),
                    'pod_status': booking.pod_status,
                    'pod_docs': [
                        {'url': pod.s3_url if pod.s3_url else pod.s3_upload.public_url(),
                         'thumb_url': pod.s3_thumb_url if pod.s3_thumb_url else pod.s3_upload.public_url(),
                         'lr_number': pod.lr_number.lr_number if pod.lr_number else ''} for pod in
                        booking.podfile_set.all()
                    ]
                }
            )
    return data
示例#17
0
def team_booking_data(request, vehicle_id):
    print(request.data)
    if to_int(vehicle_id) != 9999999 and isinstance(get_or_none(Vehicle, id=vehicle_id), Vehicle):
        vehicle = get_or_none(Vehicle, id=vehicle_id)
        bookings = ManualBooking.objects.filter(
            lorry_number__in=[display_format(compare_format(vehicle.vehicle_number))]).exclude(
            booking_status__icontains='cancelled').order_by('-shipment_date')
    else:
        broker = Broker.objects.get(name=User.objects.get(username=request.user.username))
        bookings = ManualBooking.objects.filter(supplier=broker,
                                                shipment_date__gte=datetime(2017, 12, 1).date()).exclude(
            booking_status__icontains='cancelled').order_by('-shipment_date')
    return json_response({'status': 'success', 'data': supplier_booking_data(bookings=bookings)})
示例#18
0
def register_vehicle(request):
    if Vehicle.objects.filter(vehicle_number=compare_format(
            request.POST.get('vehicle_number'))).exists():
        return json_error_response(msg="Vehicle Already Exists", status=409)
    owner = get_or_none(Owner,
                        id=int_or_none(request.POST.get('owner_id', None)))
    vehicle = Vehicle.objects.create(
        owner=owner,
        vehicle_number=compare_format(request.POST.get('vehicle_number')),
        rc_number=request.POST.get('rc_number'),
        permit=request.POST.get('permit_number'),
        permit_validity=django_date_format(
            request.POST.get('permit_validity')),
        permit_type=request.POST.get('permit_type'),
        vehicle_type=get_or_none(VehicleCategory,
                                 id=int_or_none(
                                     request.POST.get('vehicle_category'))),
        vehicle_capacity=to_int(request.POST.get('exact_vehicle_capacity')),
        body_type=request.POST.get('vehicle_body_type'),
        vehicle_model=request.POST.get('vehicle_model'),
        chassis_number=request.POST.get('chassis_number'),
        engine_number=request.POST.get('engine_number'),
        insurer=request.POST.get('insurer'),
        insurance_number=request.POST.get('insurance_number'),
        insurance_validity=django_date_format(
            request.POST.get('insurance_validity')),
        registration_year=None if not request.POST.get('registration_year')
        else django_date_format('01-Jan-' +
                                request.POST.get('registration_year').strip()),
        registration_validity=django_date_format(
            request.POST.get('registration_validity')),
        fitness_certificate_number=request.POST.get(
            'fitness_certificate_number'),
        fitness_certificate_issued_on=django_date_format(
            request.POST.get('fitness_certificate_issued_on')),
        fitness_certificate_validity_date=django_date_format(
            request.POST.get('fitness_certificate_validity')),
        puc_certificate_number=request.POST.get('puc_certificate_number'),
        puc_certificate_issued_on=django_date_format(
            request.POST.get('puc_certificate_issued_on')),
        puc_certificate_validity_date=django_date_format(
            request.POST.get('puc_certificate_validity')),
        gps_enabled=False if request.POST.get('gps_enable') == 'no' else True,
        changed_by=request.user)
    if owner:
        create_broker_owner(owner=owner)
        broker = Broker.objects.get(name=owner.name)
        update_broker_vehicle(broker=broker, vehicle=vehicle)
    return json_success_response(msg="Success")
示例#19
0
def update_outward_payment(booking_id_list, paid_to, amount, remarks, date,
                           fuel_card, payment_mode, payment_id):
    manual_bookings = ManualBooking.objects.filter(id__in=booking_id_list)
    payment = OutWardPayment.objects.get(id=payment_id)
    old_amount = str(to_int(payment.actual_amount))
    payment.paid_to = paid_to
    payment.actual_amount = amount
    payment.remarks = remarks
    payment.payment_mode = payment_mode
    payment.payment_date = django_date_format(date)
    payment.fuel_card = fuel_card_obj(card_id=fuel_card)
    payment.lorry_number = ', '.join(
        manual_bookings.values_list('lorry_number', flat=True))
    payment.save()
    for value in payment.booking_id.all():
        value.total_out_ward_amount -= to_int(amount)
        value.save()
    payment.booking_id.clear()
    for booking in manual_bookings:
        payment.booking_id.add(booking)
        email_updated_outward_payment(booking.booking_id, payment_id,
                                      old_amount, str(to_int(amount)))
    for booking in manual_bookings:
        update_outward_payments(booking)
示例#20
0
def invoice_number_data(request):
    rows = to_int(request.GET.get('page'))
    invoices = Invoice.objects.exclude(Q(deleted=True))

    search_value = request.GET.get('search')
    if search_value:
        invoices = Invoice.objects.filter(
            invoice_number__icontains=search_value).exclude(deleted=True)
    data = []
    for invoice in invoices[:rows]:
        data.append({
            'id': invoice.id,
            'text': '{}'.format(invoice.invoice_number)
        })
    data = {'results': data}
    return HttpResponse(json.dumps(data), content_type='application/json')
示例#21
0
def email_outward_payment(payment):
    booking_data = payment.booking_id.all().first()
    booking_id = '' if not booking_data else booking_data.booking_id
    paid_to = payment.paid_to
    actual_amount = payment.actual_amount
    payment_mode = payment.payment_mode
    remarks = payment.remarks
    payment_date = 'Not Available' if not payment.payment_date else payment.payment_date.strftime(
        '%d-%b-%Y')
    lr_number = ''
    for value in booking_data.lr_numbers.all():
        lr_number += value.lr_number + ', '
    lr_number = lr_number[:-2]
    subject = "New Outward Payment for " + booking_id
    prior_amount_data = OutWardPayment.objects.filter(booking_id=booking_data)
    paid_amount = 0
    for value in prior_amount_data:
        paid_amount += value.actual_amount
    paid_amount = to_int(paid_amount)
    if payment.bank_account:
        body = "LR No(s)    : " + lr_number + '\nPaid To      : ' + payment.paid_to + '\nAccount Holder Name: ' + payment.bank_account.account_holder_name + '\nAmount      : ' + actual_amount + '\nMode         : ' + payment_mode + "\nDate           : " + payment_date + "\nRemarks    : " + remarks + "\n\n" + "Payments made for " + booking_id + ": Rs. " + str(
            paid_amount
        ) + "\nTotal amount to owner for " + booking_id + ": Rs. " + str(
            booking_data.total_amount_to_owner)
    elif payment.fuel_card:
        body = "LR No(s)    : " + lr_number + '\nPaid To      : ' + paid_to + '\nFuel Card Number: ' + payment.fuel_card.card_number + '\nAmount      : ' + actual_amount + '\nMode         : ' + payment_mode + "\nDate           : " + payment_date + "\nRemarks    : " + remarks + "\n\n" + "Payments made for " + booking_id + ": Rs. " + str(
            paid_amount
        ) + "\nTotal amount to owner for " + booking_id + ": Rs. " + str(
            booking_data.total_amount_to_owner)
    else:
        body = "LR No(s)    : " + str(lr_number) + '\nPaid To      : ' + str(
            paid_to
        ) + '\nAmount      : ' + actual_amount + '\nMode         : ' + payment.get_payment_mode_display(
        ) + "\nDate           : " + payment_date + "\nRemarks    : " + str(
            remarks) + "\n\n" + "Payments made for " + str(
                booking_id) + ": Rs. " + str(
                    paid_amount) + "\nTotal amount to owner for " + str(
                        booking_id) + ": Rs. " + str(
                            booking_data.total_amount_to_owner)

    to_email_list = get_email_list(booking_data)
    email = EmailMessage(subject,
                         body,
                         'AAHO OUTWARD PAYMENT',
                         to=to_email_list)
    if settings.ENABLE_MAIL and not settings.TESTING:
        email.send()
示例#22
0
def update_vehicle(request):
    vehicle = Vehicle.objects.get(
        id=int_or_none(request.POST.get('vehicle_id')))
    vehicle.owner = get_or_none(Owner,
                                id=int_or_none(
                                    request.POST.get('owner_id', None)))
    vehicle.vehicle_number = compare_format(request.POST.get('vehicle_number'))
    vehicle.rc_number = request.POST.get('rc_number')
    vehicle.permit = request.POST.get('permit_number')
    vehicle.permit_validity = django_date_format(
        request.POST.get('permit_validity'))
    vehicle.permit_type = request.POST.get('permit_type')
    vehicle.vehicle_type = get_or_none(
        VehicleCategory, id=int_or_none(request.POST.get('vehicle_category')))
    vehicle.vehicle_capacity = to_int(
        request.POST.get('exact_vehicle_capacity'))
    vehicle.body_type = request.POST.get('vehicle_body_type')
    vehicle.vehicle_model = request.POST.get('vehicle_model')
    vehicle.chassis_number = request.POST.get('chassis_number')
    vehicle.engine_number = request.POST.get('engine_number')
    vehicle.insurer = request.POST.get('insurer')
    vehicle.insurance_number = request.POST.get('insurance_number')
    vehicle.insurance_validity = django_date_format(
        request.POST.get('insurance_validity'))
    vehicle.registration_year = None if not request.POST.get(
        'registration_year') else django_date_format(
            '01-Jan-' + request.POST.get('registration_year').strip())
    vehicle.registration_validity = django_date_format(
        request.POST.get('registration_validity'))
    vehicle.fitness_certificate_number = request.POST.get(
        'fitness_certificate_number')
    vehicle.fitness_certificate_issued_on = django_date_format(
        request.POST.get('fitness_certificate_issued_on'))
    vehicle.fitness_certificate_validity_date = django_date_format(
        request.POST.get('fitness_certificate_validity'))
    vehicle.puc_certificate_number = request.POST.get('puc_certificate_number')
    vehicle.puc_certificate_issued_on = django_date_format(
        request.POST.get('puc_certificate_issued_on'))
    vehicle.puc_certificate_validity_date = django_date_format(
        request.POST.get('puc_certificate_validity'))
    vehicle.gps_enabled = False if request.POST.get(
        'gps_enable') == 'no' else True
    vehicle.changed_by = request.user
    vehicle.save()
    return json_success_response("success")
示例#23
0
def email_updated_outward_payment(request, booking_id, payment, old_amount,
                                  new_amount):
    booking_data = ManualBooking.objects.get(booking_id=booking_id)
    paid_to = request.POST.get('paid_to')
    payment_mode = request.POST.get('outward_payment_mode')
    remarks = request.POST.get('remarks')
    payment_date = django_date_format(
        request.POST.get('outward_payment_date')).strftime('%d-%b-%Y')
    lr = ''
    for value in booking_data.lr_numbers.all():
        lr += value.lr_number + ', '
    subject = "Updated Outward Payment for " + booking_data.booking_id
    prior_amount_data = OutWardPayment.objects.filter(booking_id=booking_data)
    paid_amount = 0
    for value in prior_amount_data:
        paid_amount += value.actual_amount
    paid_amount = to_int(paid_amount)
    if payment.bank_account:
        body = "LR No(s)    : " + lr + '\nPaid To      : ' + payment.paid_to + '\nAccount Holder Name: ' + payment.bank_account.account_holder_name + '\nPrevious Amount      : ' + old_amount + '\nUpdated Amount      : ' + new_amount + '\nMode         : ' + payment_mode + "\nDate           : " + payment_date + "\nRemarks    : " + remarks + "\n\n" + "Payments made for " + booking_id + ": Rs. " + str(
            paid_amount
        ) + "\nTotal amount to owner for " + booking_id + ": Rs. " + str(
            booking_data.total_amount_to_owner)
    elif payment.fuel_card:
        body = "LR No(s)    : " + lr + '\nPaid To      : ' + paid_to + '\nFuel Card Number: ' + payment.fuel_card.card_number + '\nPrevious Amount      : ' + old_amount + '\nUpdated Amount      : ' + new_amount + '\nMode         : ' + payment_mode + "\nDate           : " + payment_date + "\nRemarks    : " + remarks + "\n\n" + "Payments made for " + booking_id + ": Rs. " + str(
            paid_amount
        ) + "\nTotal amount to owner for " + booking_id + ": Rs. " + str(
            booking_data.total_amount_to_owner)
    else:
        body = "LR No(s)    : " + lr + '\nPaid To      : ' + paid_to + '\nPrevious Amount      : ' + old_amount + '\nUpdated Amount      : ' + new_amount + '\nMode         : ' + payment.get_payment_mode_display(
        ) + "\nDate           : " + payment_date + "\nRemarks    : " + remarks + "\n\n" + "Payments made for " + booking_id + ": Rs. " + str(
            paid_amount
        ) + "\nTotal amount to owner for " + booking_id + ": Rs. " + str(
            booking_data.total_amount_to_owner)

    to_email_list = get_email_list(booking_data)
    email = EmailMessage(subject,
                         body,
                         'AAHO UPDATED OUTWARD PAYMENT',
                         to=to_email_list)
    if settings.ENABLE_MAIL and not settings.TESTING:
        email.send()
示例#24
0
def multiply_integers(num1, num2):
    return to_int(num1) * to_int(num2)
示例#25
0
def subtract_intgers(num1, num2):
    return to_int(num1) - to_int(num2)
示例#26
0
def mb_vehicle_trip_data(request):
    data = request.data
    vehicle_id = int_or_none(data.get('vehicleId', None))
    if vehicle_id:
        vehicle = int_or_none(get_or_none(Vehicle, id=vehicle_id))
        if not vehicle:
            return json_error_response(
                'Vehicle with id=%s does not exist' % vehicle_id, 404)
        else:
            data = []
            for booking in ManualBooking.objects.filter(lorry_number__in=[
                    display_format(compare_format(vehicle.vehicle_number))
            ]).order_by('-shipment_date'):
                if to_int(booking.total_amount_to_owner -
                          booking.total_out_ward_amount) != 0:
                    data.append({
                        'status':
                        'unpaid',
                        'lr_number':
                        '\n'.join(
                            booking.lr_numbers.values_list('lr_number',
                                                           flat=True)),
                        'paid':
                        to_int(booking.total_out_ward_amount),
                        'id':
                        booking.id,
                        'total_vehicle_requested':
                        None,
                        'vehicle_number':
                        display_format(booking.lorry_number),
                        'source_city':
                        booking.from_city,
                        'destination_city':
                        booking.to_city,
                        'amount':
                        to_int(booking.total_amount_to_owner),
                        'shipment_date':
                        booking.shipment_date.strftime('%d-%b-%Y'),
                        'balance':
                        to_int(booking.total_amount_to_owner -
                               booking.total_out_ward_amount),
                        'transaction_id':
                        booking.booking_id
                    })
                else:
                    data.append({
                        'status':
                        'paid',
                        'lr_number':
                        '\n'.join(
                            booking.lr_numbers.values_list('lr_number',
                                                           flat=True)),
                        'paid':
                        to_int(booking.total_out_ward_amount),
                        'id':
                        booking.id,
                        'total_vehicle_requested':
                        None,
                        'vehicle_number':
                        display_format(booking.lorry_number),
                        'source_city':
                        booking.from_city,
                        'destination_city':
                        booking.to_city,
                        'amount':
                        to_int(booking.total_amount_to_owner),
                        'shipment_date':
                        booking.shipment_date.strftime('%d-%b-%Y'),
                        'balance':
                        to_int(booking.total_amount_to_owner -
                               booking.total_out_ward_amount),
                        'final_payment_date':
                        final_payment_date(booking=booking),
                        'transaction_id':
                        booking.booking_id
                    })
            return json_response({'status': 'success', 'data': data})
示例#27
0
def get_today_payments():
    outward = OutWardPayment.objects.filter(
        payment_date=datetime.today().date()).exclude(
            bank_account=None).exclude(status='paid')
    payment_list = []
    for payment in outward:
        data = []
        if payment.payment_mode == 'neft':
            mode = 'N'
        elif payment.payment_mode == 'rtgs':
            mode = 'R'
        elif payment.payment_mode == 'imps':
            mode = 'M'
        elif payment.payment_mode == 'hdfc_internal_account':
            mode = 'I'
        else:
            mode = 'I'
        data.append(mode)
        data.append(payment.bank_account.beneficiary_code[:14] if payment.
                    bank_account else '')
        data.append(payment.bank_account.account_number if payment.
                    bank_account else '')
        data.append(str(to_int(payment.actual_amount)))
        data.append(payment.bank_account.account_holder_name if payment.
                    bank_account else '')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        booking_full = payment.booking_id.filter(
            Q(booking_id__istartswith='AH')
            | Q(booking_id__istartswith='AAHO')).first()
        booking_commission = payment.booking_id.filter(
            Q(booking_id__istartswith='AB')
            | Q(booking_id__istartswith='BROKER')).first()
        if booking_full:
            lr_number = booking_full.lr_numbers.all().first().lr_number
            narration = lr_number + payment.bank_account.beneficiary_code if payment.bank_account else ''
        elif booking_commission:
            narration = booking_commission.booking_id + payment.bank_account.beneficiary_code if payment.bank_account else ''
        else:
            narration = ''
        data.append(narration[:20])
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append('')
        data.append(str(payment.payment_date.strftime('%d/%m/%Y')))
        data.append('')
        data.append(payment.bank_account.ifsc if payment.bank_account else '')
        data.append('')
        data.append('')
        data.append('')
        time = (payment.created_on + timedelta(hours=5, minutes=30)).time()
        # if dt.time(0, 0) <= time < dt.time(17, 20):
        payment_list.append(data)
        payment.status = 'paid'
        payment.save()

    df = pd.DataFrame(payment_list)
    string_io = StringIO()
    df.to_csv(string_io, index=False, header=False)
    content = string_io.getvalue() or '\n'

    date = timezone.now().date()
    new_file_name = PaymentFile.get_next_file_name(date=date)

    dl_url = create_payment_file(new_file_name, date, content)

    task = TaskEmail.objects.get(task_id=4, office_id=1)
    email_id_list = list(
        task.employee.values_list('username__profile__email', flat=True))
    send_payment_file_email(new_file_name, dl_url, email_id_list)

    return dl_url
示例#28
0
def team_booking_data(request):
    broker = Broker.objects.get(name=User.objects.get(
        username=request.user.username))
    broker_vehicle = BrokerVehicle.objects.filter(broker=broker).values_list(
        'vehicle__vehicle_number', flat=True)
    vehicles = [display_format(vehicle) for vehicle in broker_vehicle]
    data = []
    for booking in ManualBooking.objects.filter(
            lorry_number__in=vehicles,
            shipment_date__gte=datetime.now().date() -
            timedelta(days=90)).exclude(booking_status__icontains='cancelled'
                                        ).order_by('-shipment_date'):
        if to_int(booking.total_amount_to_owner -
                  booking.total_out_ward_amount) != 0:
            data.append({
                'status':
                'unpaid',
                'lr_number':
                '\n'.join(
                    booking.lr_numbers.values_list('lr_number', flat=True)),
                'paid':
                to_int(booking.total_out_ward_amount),
                'id':
                booking.id,
                'total_vehicle_requested':
                None,
                'vehicle_number':
                display_format(booking.lorry_number),
                'source_city':
                booking.from_city,
                'destination_city':
                booking.to_city,
                'amount':
                to_int(booking.total_amount_to_owner),
                'shipment_date':
                booking.shipment_date.strftime('%d-%b-%Y'),
                'balance':
                to_int(booking.total_amount_to_owner -
                       booking.total_out_ward_amount),
                'transaction_id':
                booking.booking_id,
                'pod_status':
                booking.pod_status
            })
        else:
            data.append({
                'status':
                'paid',
                'lr_number':
                '\n'.join(
                    booking.lr_numbers.values_list('lr_number', flat=True)),
                'paid':
                to_int(booking.total_out_ward_amount),
                'id':
                booking.id,
                'total_vehicle_requested':
                None,
                'vehicle_number':
                display_format(booking.lorry_number),
                'source_city':
                booking.from_city,
                'destination_city':
                booking.to_city,
                'amount':
                to_int(booking.total_amount_to_owner),
                'shipment_date':
                booking.shipment_date.strftime('%d-%b-%Y'),
                'balance':
                to_int(booking.total_amount_to_owner -
                       booking.total_out_ward_amount),
                'final_payment_date':
                final_payment_date(booking=booking),
                'transaction_id':
                booking.booking_id,
                'pod_status':
                booking.pod_status
            })
    return json_response({'status': 'success', 'data': data})
示例#29
0
def update_commission_booking(request):
    try:
        booking = ManualBooking.objects.get(
            booking_id=request.POST.get('booking_id'))
    except ManualBooking.DoesNotExist:
        booking = ManualBooking.objects.get(id=request.POST.get('booking_id'))
    # Basic Details
    booking.billing_type = request.POST.get('billing_type')
    booking.number_of_package = request.POST.get('number_of_package')
    booking.material = request.POST.get('material')
    booking.from_city = request.POST.get('from_city')
    booking.to_city = request.POST.get('to_city')
    booking.lorry_number = request.POST.get('lorry_number')
    vehicle_category = get_or_none(VehicleCategory,
                                   id=request.POST.get('vehicle_category_id'))
    booking.type_of_vehicle = None if not vehicle_category else vehicle_category.name(
    )
    booking.loading_points = request.POST.get('loading_points')
    booking.unloading_points = request.POST.get('unloading_points')
    # booking.supplier = get_or_none(Broker, id=request.POST.get('supplier_id'))
    # booking.owner = get_or_none(Owner, id=request.POST.get('truck_owner_id'))
    booking.driver = get_or_none(Driver,
                                 id=request.POST.get('truck_driver_id'))

    # rate details
    booking.loaded_weight = to_float(request.POST.get('loaded_weight'))
    booking.supplier_charged_weight = to_float(
        request.POST.get('supplier_charged_weight'))
    booking.supplier_rate = to_int(request.POST.get('supplier_rate'))

    # additional charges
    booking.loading_charge = to_int(request.POST.get('loading_charge'))
    booking.unloading_charge = to_int(request.POST.get('unloading_charge'))
    booking.detention_charge = to_int(request.POST.get('detention_charge'))
    booking.additional_charges_for_owner = to_int(
        request.POST.get('additional_charges_for_owner'))
    booking.note_for_additional_owner_charges = request.POST.get(
        'note_for_additional_owner_charges')

    # deduction for vendor
    booking.commission = to_int(request.POST.get('commission'))
    booking.lr_cost = to_int(request.POST.get('lr_cost'))
    booking.deduction_for_advance = to_int(
        request.POST.get('deduction_for_advance'))
    booking.deduction_for_balance = to_int(
        request.POST.get('deduction_for_balance'))
    booking.other_deduction = to_int(request.POST.get('other_deduction'))
    booking.remarks_about_deduction = request.POST.get(
        'remarks_about_deduction')

    # total amount
    booking.total_amount_to_owner = to_int(
        request.POST.get('total_amount_to_owner'))
    booking.total_amount_to_company = to_int(
        request.POST.get('total_amount_to_party'))

    if not EMP_GROUP3 in request.user.groups.values_list('name', flat=True):
        # invoice details
        booking.additional_charges_for_company = to_int(
            request.POST.get('additional_charges_for_company'))
        booking.invoice_remarks_for_additional_charges = request.POST.get(
            'invoice_remarks_for_additional_charges')
        booking.deductions_for_company = to_int(
            request.POST.get('deductions_for_company'))
        booking.invoice_remarks_for_deduction_discount = request.POST.get(
            'invoice_remarks_for_deduction_discount')
        booking.advance_amount_from_company = to_int(
            request.POST.get('advance_from_company'))
        booking.tds_deducted_amount = to_int(
            request.POST.get('tds_deducted_amount'))

        # Rate Details
        booking.charged_weight = to_float(request.POST.get('charged_weight'))
        booking.party_rate = to_int(request.POST.get('party_rate'))

    # status update
    booking.pod_status = request.POST.get('pod_status')
    booking.invoice_status = request.POST.get('invoice_status')
    booking.save()
    Vehicle.objects.filter(
        vehicle_number=compare_format(booking.lorry_number)).update(
            vehicle_type=vehicle_category)
    update_inward_payments(booking)
    update_outward_payments(booking)
    update_invoice_status(booking)
    return booking
示例#30
0
def invoices_data(request):
    start = to_int(request.GET.get('start'))
    end = start + to_int(request.GET.get('length'))
    booking_ids = manual_booking_id_list(
        username=request.user.username,
        user_group_list=request.user.groups.values_list('name', flat=True))
    user_group = request.user.groups.values_list('name', flat=True)[0]
    if user_group == EMP_GROUP2 or user_group == EMP_GROUP3:
        bookings = ManualBooking.objects.filter(id__in=booking_ids).exclude(
            billing_type='contract').exclude(
                booking_status__iexact='cancelled')
    else:
        bookings = ManualBooking.objects.filter(id__in=booking_ids).exclude(
            booking_status__iexact='cancelled')
    if request.GET.get('search[value]'):
        search_value = request.GET.get('search[value]').strip()
        invoices = Invoice.objects.filter(
            bookings__in=ManualBooking.objects.filter(
                Q(id__in=booking_ids)
                & (Q(booking_id__icontains=search_value)
                   | Q(lorry_number__icontains=search_value))))
        if invoices.exists():
            invoices = invoices
        else:
            try:
                search_value = int(search_value)
                search_kwargs = Q(total_amount=search_value)
                invoices = Invoice.objects.filter(
                    bookings__in=bookings).filter(search_kwargs).order_by(
                        '-date').distinct()
            except ValueError:
                if LrNumber.objects.filter(
                        lr_number__icontains=search_value).exists():
                    booking_ids = LrNumber.objects.filter(
                        lr_number__icontains=search_value).values_list(
                            'booking__id')
                    invoices = Invoice.objects.filter(
                        bookings__in=bookings).order_by('-date').distinct()
                else:
                    search_kwargs = Q(
                        company_name__icontains=search_value) | Q(
                            invoice_number__icontains=search_value)
                    invoices = Invoice.objects.filter(
                        bookings__in=bookings).filter(search_kwargs).order_by(
                            '-date').distinct()
    else:
        invoices = Invoice.objects.filter(
            bookings__in=bookings).order_by('-date').distinct()

    data = []
    for inv in invoices[start:end if end != -1 else invoices.count()]:
        data.append([
            inv.date.strftime('%d-%b-%Y') if inv.date else '',
            inv.invoice_number, inv.company_name,
            '<br>'.join(inv.bookings.values_list('booking_id', flat=True)),
            '<br>'.join([
                '<br>'.join(
                    booking.lr_numbers.values_list('lr_number', flat=True))
                for booking in inv.bookings.all()
            ]),
            to_int(inv.total_amount),
            '-' if not inv.s3_upload else format_html(
                '''<a href="{}" download><i class="fa fa-download" aria-hidden="true"></i></a>''',
                inv.s3_upload.public_url())
        ])
    data = {
        "draw": to_int(request.GET.get('draw')),
        "recordsTotal": invoices.count(),
        "recordsFiltered": invoices.count(),
        "data": data
    }
    return HttpResponse(json.dumps(data), content_type='application/json')