예제 #1
0
def create_invoice(booking, payment_method='bpay'):
    """
    This will create and invoice and order from a basket bypassing the session
    and payment bpoint code constraints.
    """
    from ledger.checkout.utils import createCustomBasket
    from ledger.payments.invoice.utils import CreateInvoiceBasket
    from ledger.accounts.models import EmailUser
    from decimal import Decimal

    products = Booking.objects.last().as_line_items
    user = EmailUser.objects.get(email=booking.proposal.applicant_email)

    if payment_method == 'monthly_invoicing':
        invoice_text = 'Monthly Payment Invoice'
    elif payment_method == 'bpay':
        invoice_text = 'BPAY Payment Invoice'
    else:
        invoice_text = 'Payment Invoice'

    basket = createCustomBasket(products, user, settings.PAYMENT_SYSTEM_ID)
    order = CreateInvoiceBasket(
        payment_method=payment_method,
        system=settings.PAYMENT_SYSTEM_PREFIX).create_invoice_and_order(
            basket, 0, None, None, user=user, invoice_text=invoice_text)

    return order
예제 #2
0
def create_invoice(sanction_outcome, payment_method='bpay'):
    """
    This will create and invoice and order from a basket bypassing the session
    and payment bpoint code constraints.
    """
    from ledger.checkout.utils import createCustomBasket
    from ledger.payments.invoice.utils import CreateInvoiceBasket

    products = sanction_outcome.as_line_items
    user = sanction_outcome.get_offender()[0]
    invoice_text = 'Payment Invoice'

    basket = createCustomBasket(products, user, settings.WC_PAYMENT_SYSTEM_ID)
    order = CreateInvoiceBasket(
        payment_method=payment_method,
        system=settings.WC_PAYMENT_SYSTEM_PREFIX).create_invoice_and_order(
            basket, 0, None, None, user=user, invoice_text=invoice_text)

    return order
예제 #3
0
def create_application_invoice(application, payment_method='cc'):
    '''
    This will create and invoice and order from a basket bypassing the session
    and payment bpoint code constraints.
    '''
    from wildlifecompliance.components.applications.services import (
        ApplicationService, )
    from ledger.checkout.utils import createCustomBasket
    from ledger.payments.invoice.utils import CreateInvoiceBasket

    products = ApplicationService.get_product_lines(application)
    user = application.submitter
    invoice_text = 'Payment Invoice'

    basket = createCustomBasket(products, user, settings.WC_PAYMENT_SYSTEM_ID)
    order = CreateInvoiceBasket(
        payment_method=payment_method,
        system=settings.WC_PAYMENT_SYSTEM_PREFIX).create_invoice_and_order(
            basket, 0, None, None, user=user, invoice_text=invoice_text)

    return order
예제 #4
0
def test_create_invoice(payment_method='bpay'):
    """
    This will create and invoice and order from a basket bypassing the session
    and payment bpoint code constraints.

    To test:
        from ledger.payments.invoice.utils import test_create_invoice


        from ledger.checkout.utils import createCustomBasket
        from ledger.payments.invoice.utils import CreateInvoiceBasket
        from decimal import Decimal

        products = [{u'oracle_code': u'ABC123 GST', u'price_incl_tax': Decimal('10.00'), u'price_excl_tax': Decimal('9.090909090909'), u'ledger_description': u'Booking Date 2019-09-24: Neale Junction Nature Reserve - 2019-09-24 - Adult', u'quantity': 1}]
        or
        products = Booking.objects.last().as_line_items

        user = EmailUser.objects.get(email__icontains='walter.genuit@dbca')
        payment_method = 'bpay' (or 'monthly_invoicing')

        basket  = createCustomBasket(products, user, 'S557', bpay_allowed=True, monthly_invoicing_allowed=True)
        order = CreateInvoiceBasket(payment_method='bpay', system='0557').create_invoice_and_order(basket, 0, None, None, user=user, invoice_text='CIB7')

        Invoice.objects.get(order_number=order.number)
        <Invoice: Invoice #05572188633>

        To view:
            http://localhost:8499/ledger/payments/invoice/05572188633

    """
    from ledger.checkout.utils import createCustomBasket
    from ledger.payments.invoice.utils import CreateInvoiceBasket
    from ledger.accounts.models import EmailUser
    from decimal import Decimal

    products = [{
        'oracle_code': 'ABC123 GST',
        'price_incl_tax': Decimal('10.00'),
        'price_excl_tax': Decimal('9.090909090909'),
        'ledger_description':
        'Booking Date 2019-09-24: Neale Junction Nature Reserve - 2019-09-24 - Adult',
        'quantity': 1
    }]
    #products = Booking.objects.last().as_line_items

    user = EmailUser.objects.get(email='*****@*****.**')
    #payment_method = 'bpay'
    payment_method = 'monthly_invoicing'

    basket = createCustomBasket(products, user, 'S557')
    order = CreateInvoiceBasket(payment_method=payment_method,
                                system='0557').create_invoice_and_order(
                                    basket,
                                    0,
                                    None,
                                    None,
                                    user=user,
                                    invoice_text='CIB7')
    print 'Created Order: {}'.format(order.number)
    print 'Created Invoice: {}'.format(
        Invoice.objects.get(order_number=order.number))

    return order
    def handle(self, *args, **options):
        try:
            # Determine the start and end date of the annual site fee, for which the invoices should be issued
            today_now_local = datetime.datetime.now(pytz.timezone(TIME_ZONE))
            today_date_local = today_now_local.date()
            period_start_date, period_end_date = get_annual_rental_fee_period(
                today_date_local)

            # Retrieve annual site fee period object for the period calculated above
            # This period should not overwrap the existings, otherwise you will need a refund
            annual_rental_fee_period, created = AnnualRentalFeePeriod.objects.get_or_create(
                period_start_date=period_start_date,
                period_end_date=period_end_date)

            # Retrieve the licences which will be valid within the current annual site fee period
            approval_qs = get_approvals(annual_rental_fee_period)

            # Issue the annual site fee invoices per approval per annual_rental_fee_period
            errors = []
            updates = []
            for approval in approval_qs:
                try:
                    with transaction.atomic():
                        # apiary_sites_to_be_charged = get_apiary_sites_to_be_charged(approval, annual_rental_fee_period)
                        apiary_sites_to_be_charged = ApiarySite.objects.filter(
                            id__in=(ApiarySiteOnApproval.objects.filter(
                                approval=approval,
                                site_status__in=(
                                    SITE_STATUS_CURRENT,
                                    SITE_STATUS_SUSPENDED,
                                )).values_list('apiary_site_id', flat=True)))

                        if apiary_sites_to_be_charged.count() > 0:
                            # invoice, details_dict = create_other_invoice_for_annual_rental_fee(approval, today_now_local, (period_start_date, period_end_date), apiary_sites_to_be_charged)
                            line_items, apiary_sites_charged, invoice_period = generate_line_items_for_annual_rental_fee(
                                approval, today_now_local,
                                (annual_rental_fee_period.period_start_date,
                                 annual_rental_fee_period.period_end_date),
                                apiary_sites_to_be_charged)

                            if line_items:
                                with transaction.atomic():
                                    try:
                                        logger.info(
                                            'Creating filming fee invoice')

                                        basket = createCustomBasket(
                                            line_items, approval.
                                            relevant_applicant_email_user,
                                            PAYMENT_SYSTEM_ID)
                                        order = CreateInvoiceBasket(
                                            payment_method='other',
                                            system=PAYMENT_SYSTEM_PREFIX
                                        ).create_invoice_and_order(
                                            basket,
                                            0,
                                            None,
                                            None,
                                            user=approval.
                                            relevant_applicant_email_user,
                                            invoice_text='Payment Invoice')
                                        invoice = Invoice.objects.get(
                                            order_number=order.number)

                                        line_items = make_serializable(
                                            line_items
                                        )  # Make line items serializable to store in the JSONField
                                        annual_rental_fee = AnnualRentalFee.objects.create(
                                            approval=approval,
                                            annual_rental_fee_period=
                                            annual_rental_fee_period,
                                            invoice_reference=invoice.
                                            reference,
                                            invoice_period_start_date=
                                            invoice_period[0],
                                            invoice_period_end_date=
                                            invoice_period[1],
                                            lines=line_items,
                                        )

                                        updates.append(annual_rental_fee.
                                                       invoice_reference)
                                    except Exception as e:
                                        err_msg = 'Failed to create annual site fee confirmation'
                                        logger.error('{}\n{}'.format(
                                            err_msg, str(e)))
                                        errors.append(err_msg)

                                # Store the apiary sites which the invoice created above has been issued for
                                for apiary_site in apiary_sites_to_be_charged:
                                    annual_rental_fee_apiary_site = AnnualRentalFeeApiarySite(
                                        apiary_site=apiary_site,
                                        annual_rental_fee=annual_rental_fee)
                                    annual_rental_fee_apiary_site.save()

                                # TODO: Attach the invoice and send emails
                                #   update invoice_sent attribute of the annual_rental_fee obj?
                                email_data = send_annual_rental_fee_awaiting_payment_confirmation(
                                    approval, annual_rental_fee, invoice)

                                # TODO: Add comms log

                except Exception as e:
                    err_msg = 'Failed to send an annual site fee invoice for the approval {}'.format(
                        approval.lodgement_number)
                    logger.error('{}\n{}'.format(err_msg, str(e)))
                    errors.append(err_msg)

        except Exception as e:
            err_msg = 'Error command {}'.format(__name__)
            logger.error('{}\n{}'.format(err_msg, str(e)))
            errors.append(err_msg)

        cmd_name = __name__.split('.')[-1].replace('_', ' ').upper()
        err_str = '<strong style="color: red;">Errors: {}</strong>'.format(
            len(errors)
        ) if len(
            errors) > 0 else '<strong style="color: green;">Errors: 0</strong>'
        msg = '<p>{} completed. {}. IDs updated: {}.</p>'.format(
            cmd_name, err_str, updates)
        logger.info(msg)
        print(
            msg)  # will redirect to cron_tasks.log file, by the parent script
예제 #6
0
    def post(self, request, *args, **kwargs):
        try:
            context_processor = template_context(request)
            application_fee = ApplicationFee.objects.get(pk=request.session['cols_app_invoice']) if 'cols_app_invoice' in request.session else None
            proposal = application_fee.proposal

            try:
                recipient = proposal.applicant.email
                submitter = proposal.applicant
            except:
                recipient = proposal.submitter.email
                submitter = proposal.submitter

            if request.user.is_staff or request.user.is_superuser or ApplicationFee.objects.filter(pk=application_fee.id).count() == 1:
                invoice = None
                #basket = get_basket(request)
                basket = request.basket

                # here we are manually creating an order and invoice from the basket - by-passing credit card payment screen.
                ## commenting below lines and using CreateInvoiceBasket because basket created in previous view
                #order_response = place_order_submission(request)
                #order = Order.objects.get(basket=basket, user=submitter)

                order = CreateInvoiceBasket(payment_method='other', system=settings.PAYMENT_SYSTEM_PREFIX).create_invoice_and_order(basket, 0, None, None, user=request.user, invoice_text='Application Fee')
                invoice = Invoice.objects.get(order_number=order.number)
                fee_inv, created = ApplicationFeeInvoice.objects.get_or_create(application_fee=application_fee, invoice_reference=invoice.reference)

                if fee_inv:
                    application_fee.payment_type = ApplicationFee.PAYMENT_TYPE_ZERO
                    application_fee.expiry_time = None

                    proposal = proposal_submit(proposal, request)
                    if proposal and (invoice.payment_status == 'paid' or invoice.payment_status == 'over_paid'):
                        proposal.fee_invoice_reference = invoice.reference
                        proposal.save()
                        proposal.reset_application_discount(request.user)
                    else:
                        logger.error('Invoice payment status is {}'.format(invoice.payment_status))
                        raise

                    application_fee.save()
                    request.session['cols_last_app_invoice'] = application_fee.id
                    delete_session_application_invoice(request.session)

                    send_application_fee_invoice_tclass_email_notification(request, proposal, invoice, recipients=[recipient])

                context = {
                    'proposal': proposal,
                    'submitter': submitter,
                    'fee_invoice': fee_inv,

                    'basket': basket,
                    'lines': request.basket.lines.all(),
                    'line_details': 'N/A', #request.POST['payment'],
                    'proposal_id': proposal.id,
                    'payment_method': 'N/A',
                }

                return render(request, self.template_name, context)
            else:
                return HttpResponseRedirect(reverse('home'))

        except Exception as e:
            return redirect('home')