Skip to content

Commit

Permalink
Merge pull request #697 from xzzy/master
Browse files Browse the repository at this point in the history
Mooring Bug Fixes
  • Loading branch information
ropable committed Sep 18, 2019
2 parents 357c735 + a4bafbc commit 5ae6535
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 29 deletions.
2 changes: 1 addition & 1 deletion ledger/order/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ class OrderAdmin(OrderAdmin):
readonly_fields = ('number', 'total_incl_tax', 'total_excl_tax',
'shipping_incl_tax', 'shipping_excl_tax',)
inlines = [LineInline]

search_fields = ('number','user__email',)
admin.site.register(Order, OrderAdmin)
7 changes: 4 additions & 3 deletions ledger/payments/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ class CashAdmin(admin.ModelAdmin):

@admin.register(models.Invoice)
class InvoiceAdmin(admin.ModelAdmin):
list_display = ('reference','order','payment_status','settlement_date')
list_display = ('reference','order','payment_status','settlement_date','amount', 'system','created' )
search_fields = ('reference',)

list_filter = ('system'),

@admin.register(models.InvoiceBPAY)
class InvoiceBpayAdmin(admin.ModelAdmin):
pass
Expand Down Expand Up @@ -113,7 +114,7 @@ class OracleParserAdmin(admin.ModelAdmin):
@admin.register(models.OracleInterface)
class OracleInterfaceAdmin(admin.ModelAdmin):
list_display = ['activity_name','amount','status','receipt_number','receipt_date','source','method']

search_fields = ('source','receipt_number')
class OracleInterfaceRecipientInline(admin.TabularInline):
model = models.OracleInterfaceRecipient
extra = 1
Expand Down
71 changes: 59 additions & 12 deletions mooring/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
from mooring import utils
from mooring.helpers import can_view_campground, is_inventory, is_admin, is_payment_officer
from datetime import datetime,timedelta, date
from decimal import Decimal
from decimal import Decimal
from ledger.payments.utils import systemid_check, update_payments
from mooring.context_processors import mooring_url, template_context
from mooring.models import (MooringArea,
District,
Expand Down Expand Up @@ -1920,6 +1921,8 @@ def retrieve(self, request, pk=None, ratis_id=None, format=None, show_all=False)
# compare old and new booking for changes
if hashlib.md5(str(current_booking_obj)).hexdigest() == hashlib.md5(str(old_booking_obj)).hexdigest():
booking_changed = False
if utils.check_mooring_admin_access(request) is True:
booking_changed = True

availability = utils.get_campsite_availability(sites_qs, start_date, end_date, ongoing_booking, request)

Expand Down Expand Up @@ -2884,8 +2887,13 @@ def list(self, request, *args, **kwargs):
# inv = AdmissionsBookingInvoice.objects.filter(admissions_booking=ad)
# inv = [adi.invoice_reference,]


r.update({'invoice_ref': inv, 'in_future': ad.in_future, 'part_booking': ad.part_booking})
future_or_admin = False
if request.user.groups.filter(name__in=['Mooring Admin']).exists():
future_or_admin = True
else:
future_or_admin = ad.in_future

r.update({'invoice_ref': inv, 'in_future': future_or_admin, 'part_booking': ad.part_booking})
if(r['customer']):
name = ad.customer.first_name + " " + ad.customer.last_name
email = ad.customer.email
Expand Down Expand Up @@ -4402,36 +4410,75 @@ def post(self, request, *args, **kwargs):
money_from_json = json.loads(money_from)
money_to_json = json.loads(money_to)
bpoint_trans_split_json = json.loads(bpoint_trans_split)
lines = []
failed_refund = False

json_obj = {'found': False, 'code': money_from, 'money_to': money_to, 'failed_refund': failed_refund}

for mf in money_from_json:
if Decimal(mf['line-amount']) > 0:
money_from_total = (Decimal(mf['line-amount']) - Decimal(mf['line-amount']) - Decimal(mf['line-amount']))
lines.append({'ledger_description':str(mf['line-text']),"quantity":1,"price_incl_tax":money_from_total,"oracle_code":str(mf['oracle-code']), 'line_status': 3})


lines = []
if int(refund_method) == 1:
lines = []
for mf in money_from_json:
if Decimal(mf['line-amount']) > 0:
money_from_total = (Decimal(mf['line-amount']) - Decimal(mf['line-amount']) - Decimal(mf['line-amount']))
lines.append({'ledger_description':str(mf['line-text']),"quantity":1,"price_incl_tax":money_from_total,"oracle_code":str(mf['oracle-code']), 'line_status': 3})

for bp_txn in bpoint_trans_split_json:
bpoint_id = BpointTransaction.objects.get(txn_number=bp_txn['txn_number'])
info = {'amount': Decimal('{:.2f}'.format(float(bp_txn['line-amount']))), 'details' : 'Refund via system'}
if info['amount'] > 0:
lines.append({'ledger_description':str("Temp fund transfer "+bp_txn['txn_number']),"quantity":1,"price_incl_tax":Decimal('{:.2f}'.format(float(bp_txn['line-amount']))),"oracle_code":str(settings.UNALLOCATED_ORACLE_CODE), 'line_status': 1})


order = utils.allocate_refund_to_invoice(request, booking, lines, invoice_text=None, internal=False, order_total='0.00',user=booking.customer)
new_invoice = Invoice.objects.get(order_number=order.number)
update_payments(new_invoice.reference)
#order = utils.allocate_refund_to_invoice(request, booking, lines, invoice_text=None, internal=False, order_total='0.00',user=booking.customer)
#new_order = Order.objects.get(basket=basket)
#new_invoice = Invoice.objects.get(order_number=order.number)

for bp_txn in bpoint_trans_split_json:
bpoint_id = BpointTransaction.objects.get(txn_number=bp_txn['txn_number'])
info = {'amount': Decimal('{:.2f}'.format(float(bp_txn['line-amount']))), 'details' : 'Refund via system'}
refund = None
lines = []
if info['amount'] > 0:
lines = []
#lines.append({'ledger_description':str("Temp fund transfer "+bp_txn['txn_number']),"quantity":1,"price_incl_tax":Decimal('{:.2f}'.format(float(bp_txn['line-amount']))),"oracle_code":str(settings.UNALLOCATED_ORACLE_CODE), 'line_status': 1})


try:

bpoint_money_to = (Decimal('{:.2f}'.format(float(bp_txn['line-amount']))) - Decimal('{:.2f}'.format(float(bp_txn['line-amount']))) - Decimal('{:.2f}'.format(float(bp_txn['line-amount']))))
lines.append({'ledger_description':str("Payment Gateway Refund to "+bp_txn['txn_number']),"quantity":1,"price_incl_tax": bpoint_money_to,"oracle_code":str(settings.UNALLOCATED_ORACLE_CODE), 'line_status': 3})
bpoint = BpointTransaction.objects.get(txn_number=bp_txn['txn_number'])
refund = bpoint.refund(info,request.user)
except:
failed_refund = True
bpoint_failed_amount = Decimal(bp_txn['line-amount'])
lines = []
lines.append({'ledger_description':str("Refund failed for txn "+bp_txn['txn_number']),"quantity":1,"price_incl_tax":bpoint_failed_amount,"oracle_code":str(settings.UNALLOCATED_ORACLE_CODE), 'line_status': 1})
order = utils.allocate_refund_to_invoice(request, booking, lines, invoice_text=None, internal=False, order_total='0.00',user=booking.customer)
new_invoice = Invoice.objects.get(order_number=order.number)
bpoint_refund = BpointTransaction.objects.get(txn_number=refund)
bpoint_refund.crn1 = new_invoice.reference
bpoint_refund.save()
update_payments(new_invoice.reference)


else:
lines = []
for mf in money_from_json:
if Decimal(mf['line-amount']) > 0:
money_from_total = (Decimal(mf['line-amount']) - Decimal(mf['line-amount']) - Decimal(mf['line-amount']))
lines.append({'ledger_description':str(mf['line-text']),"quantity":1,"price_incl_tax":money_from_total,"oracle_code":str(mf['oracle-code']), 'line_status': 3})


for mt in money_to_json:
lines.append({'ledger_description':mt['line-text'],"quantity":1,"price_incl_tax":mt['line-amount'],"oracle_code":mt['oracle-code'], 'line_status': 1})

utils.allocate_refund_to_invoice(request, booking, lines, invoice_text=None, internal=False, order_total='0.00',user=booking.customer)
order = utils.allocate_refund_to_invoice(request, booking, lines, invoice_text=None, internal=False, order_total='0.00',user=booking.customer)
new_invoice = Invoice.objects.get(order_number=order.number)
update_payments(new_invoice.reference)

json_obj['failed_refund'] = failed_refund

return Response(json_obj)
Expand Down
14 changes: 13 additions & 1 deletion mooring/emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
from confy import env
from django.template import Context
from ledger.accounts.models import Document
from django.contrib.auth.models import Group
from ledger.accounts.models import EmailUser

import datetime
import hashlib

Expand Down Expand Up @@ -392,6 +395,10 @@ def send_refund_failure_email_admissions(booking, context_processor):
to = settings.NON_PROD_EMAIL
sendHtmlEmail([to],subject,context,template,cc,bcc,from_email,template_group,attachments=None)
else:
pa = Group.objects.get(name='Payments Officers')
ma = Group.objects.get(name="Mooring Admin")
user_list = EmailUser.objects.filter(groups__in=[ma,]).distinct()

for u in user_list:
to = u.email
sendHtmlEmail([to],subject,context,template,cc,bcc,from_email,template_group,attachments=None)
Expand Down Expand Up @@ -434,6 +441,11 @@ def send_refund_failure_email(booking, context_processor):
to = settings.NON_PROD_EMAIL
sendHtmlEmail([to],subject,context,template,cc,bcc,from_email,template_group,attachments=None)
else:

pa = Group.objects.get(name='Payments Officers')
ma = Group.objects.get(name="Mooring Admin")
user_list = EmailUser.objects.filter(groups__in=[ma,]).distinct()

for u in user_list:
to = u.email
sendHtmlEmail([to],subject,context,template,cc,bcc,from_email,template_group,attachments=None)
Expand Down Expand Up @@ -488,7 +500,7 @@ def send_refund_failure_email_old(booking):

pa = Group.objects.get(name='Payments Officers')
ma = Group.objects.get(name="Mooring Admin")
user_list = EmailUser.objects.filter(groups__in=[pa,ma]).distinct()
user_list = EmailUser.objects.filter(groups__in=[ma,]).distinct()

### REMOVE ###
for u in user_list:
Expand Down
2 changes: 1 addition & 1 deletion mooring/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def booking_refunds(start,end):
def booking_bpoint_settlement_report(_date):
try:
bpoint, cash = [], []
bpoint.extend([x for x in BpointTransaction.objects.filter(created__date=_date,response_code=0,crn1__startswith='0516').exclude(crn1__endswith='_test')])
bpoint.extend([x for x in BpointTransaction.objects.filter(settlement_date=_date,response_code=0,crn1__startswith='0516').exclude(crn1__endswith='_test')])
cash = CashTransaction.objects.filter(created__date=_date,invoice__reference__startswith='0516').exclude(type__in=['move_out','move_in'])

strIO = StringIO()
Expand Down
2 changes: 1 addition & 1 deletion mooring/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,5 @@
os.environ['UPDATE_PAYMENT_ALLOCATION'] = 'True'
UNALLOCATED_ORACLE_CODE = 'NNP449 GST'


DATA_UPLOAD_MAX_NUMBER_FIELDS = 10240
#os.environ.setdefault("UPDATE_PAYMENT_ALLOCATION", True)
4 changes: 2 additions & 2 deletions mooring/templates/mooring/booking/booking_view.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<div class="well">
<div class="row"><div class="col-sm-12">
<div class="row"><div class="col-sm-12" style='display: none;'>
<h3 class="text-primary">{{ booking.mooringarea.name }}, {{ booking.mooringarea.park.name }}</h3>
</div></div>
<div class="row">
Expand All @@ -9,7 +9,7 @@ <h3 class="text-primary">{{ booking.mooringarea.name }}, {{ booking.mooringarea.
{% endif %}
</div>
<div class="col-sm-9">
<div class="row">
<div class="row" style='display: none;'>
<div class="col-sm-4">
<b>Mooring:</b>
</div>
Expand Down
2 changes: 1 addition & 1 deletion mooring/templates/mooring/booking/cancel_completed.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<div class="row"><div class="col-sm-12">
<h2>Cancellation Completed</h2>
<p>A confirmation email has been sent to {{ booking.customer.email }}. </p>
<p>For any refund details please refer to the email send to {{ booking.customer.email }}. </p>
<p>For any refund details please refer to the email sent to {{ booking.customer.email }}. </p>
</div></div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion mooring/templates/mooring/booking/success.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<div class="row"><div class="col-sm-12">
<h2>Success!</h2>
<p>A confirmation email has been sent to {{ booking.customer.email }}. </p>
<p>For any refund details please refer to the email send to {{ booking.customer.email }}. </p>
<p>For any refund details please refer to the email sent to {{ booking.customer.email }}. </p>
<p>&nbsp;</p>
<p>Please click <a href="{{EXPLORE_PARKS_SEARCH}}">here</a> if you want to make another booking.</p>

Expand Down
2 changes: 1 addition & 1 deletion mooring/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ def calculate_price_booking_change(old_booking, new_booking,overide_change_fees=
adjustment_fee = float(ob.amount) + adjustment_fee
description = 'Mooring {} ({} - {})'.format(ob.campsite.mooringarea.name,ob.from_dt.astimezone(pytimezone('Australia/Perth')).strftime('%d/%m/%Y %H:%M %p'),ob.to_dt.astimezone(pytimezone('Australia/Perth')).strftime('%d/%m/%Y %H:%M %p'))
# change_fees.append({'additional_fees': 'true', 'description': 'Adjustment - '+description ,'amount': str(adjustment_fee - adjustment_fee - adjustment_fee), 'oracle_code': str(ob.campsite.mooringarea.oracle_code), 'mooring_group': mooring_group})
change_fees.append({'additional_fees': 'true', 'description': 'Adjustment - '+description ,'amount': str(format(adjustment_fee - adjustment_fee - adjustment_fee, '.2f')), 'oracle_code': str(ob.campsite.mooringarea.oracle_code), 'mooring_group': mooring_group, 'line_status': 2})
change_fees.append({'additional_fees': 'true', 'description': 'Adjustment - '+description ,'amount': str(format(adjustment_fee - adjustment_fee - adjustment_fee, '.2f')), 'oracle_code': str(ob.campsite.mooringarea.oracle_code), 'mooring_group': mooring_group, 'line_status': 3})

return change_fees

Expand Down
19 changes: 14 additions & 5 deletions mooring/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,13 +443,18 @@ def get(self, request, *args, **kwargs):
booking_id = kwargs['pk']
booking = None
booking_total = Decimal('0.00')
overide_cancel_fees=False
if request.user.is_staff or request.user.is_superuser or AdmissionsBooking.objects.filter(customer=request.user,pk=booking_id).count() == 1:
booking = AdmissionsBooking.objects.get(pk=booking_id)
if booking.booking_type == 4:
print ("ADMISSIONS BOOKING HAS BEEN CANCELLED")
return HttpResponseRedirect(reverse('home'))

booking_cancellation_fees = utils.calculate_price_admissions_cancel(booking, [])

if request.user.groups.filter(name__in=['Mooring Admin']).exists():
overide_cancel_fees=True

booking_cancellation_fees = utils.calculate_price_admissions_cancel(booking, [], overide_cancel_fees)
booking_total = booking_total + sum(Decimal(i['amount']) for i in booking_cancellation_fees)
basket = {}
return render(request, self.template_name, {'booking': booking,'basket': basket, 'booking_fees': booking_cancellation_fees, 'booking_total': booking_total, 'booking_total_positive': booking_total - booking_total - booking_total })
Expand All @@ -463,15 +468,19 @@ def post(self, request, *args, **kwargs):
invoice = None
refund = None
failed_refund = False

overide_cancel_fees=False

if request.user.is_staff or request.user.is_superuser or AdmissionsBooking.objects.filter(customer=request.user,pk=booking_id).count() == 1:
booking = AdmissionsBooking.objects.get(pk=booking_id)
if booking.booking_type == 4:
print ("ADMISSIONS BOOKING HAS BEEN CANCELLED")
return HttpResponseRedirect(reverse('home'))

if request.user.groups.filter(name__in=['Mooring Admin']).exists():
overide_cancel_fees=True

bpoint_id = self.get_booking_info(self, request, *args, **kwargs)
booking_cancellation_fees = utils.calculate_price_admissions_cancel(booking, [])
booking_cancellation_fees = utils.calculate_price_admissions_cancel(booking, [], overide_cancel_fees)
booking_total = booking_total + sum(Decimal(i['amount']) for i in booking_cancellation_fees)
# booking_total = Decimal('{:.2f}'.format(float(booking_total - booking_total - booking_total)))

Expand Down Expand Up @@ -1272,11 +1281,11 @@ def post(self, request, *args, **kwargs):
to_dt = local_dt.replace(microsecond=booking.departure.microsecond)
to_date_converted = to_dt.date()
# generate invoice
reservation = u"Reservation for {} from {} to {} at {}".format(
reservation = u"Reservation for {} from {} to {} ".format(
u'{} {}'.format(booking.customer.first_name, booking.customer.last_name),
from_date_converted,
to_date_converted,
booking.mooringarea.name
#booking.mooringarea.name
)

logger.info('{} built booking {} and handing over to payment gateway'.format('User {} with id {}'.format(booking.customer.get_full_name(),booking.customer.id) if booking.customer else 'An anonymous user',booking.id))
Expand Down

0 comments on commit 5ae6535

Please sign in to comment.