Skip to content

Commit

Permalink
Merge 0808059 into 218eedc
Browse files Browse the repository at this point in the history
  • Loading branch information
rayrayndwiga committed Nov 29, 2017
2 parents 218eedc + 0808059 commit c495894
Show file tree
Hide file tree
Showing 5 changed files with 175 additions and 99 deletions.
31 changes: 31 additions & 0 deletions ledger/order/migrations/0009_auto_20171129_1301.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-11-29 05:01
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('order', '0008_auto_20170920_1618'),
]

operations = [
migrations.AlterField(
model_name='line',
name='deduction_details',
field=django.contrib.postgres.fields.jsonb.JSONField(db_index=True, default={b'bpay': {}, b'card': {}, b'cash': {}}),
),
migrations.AlterField(
model_name='line',
name='payment_details',
field=django.contrib.postgres.fields.jsonb.JSONField(db_index=True, default={b'bpay': {}, b'card': {}, b'cash': {}}),
),
migrations.AlterField(
model_name='line',
name='refund_details',
field=django.contrib.postgres.fields.jsonb.JSONField(db_index=True, default={b'bpay': {}, b'card': {}, b'cash': {}}),
),
]
6 changes: 3 additions & 3 deletions ledger/order/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ class Line(CoreAbstractLine):
partner_name = models.CharField(
_("Partner name"), max_length=128, blank=True,null=True)
partner_sku = models.CharField(_("Partner SKU"), max_length=128,null=True)
payment_details = JSONField(default=DEFAULT_PAYMENT)
refund_details = JSONField(default=DEFAULT_PAYMENT)
deduction_details = JSONField(default=DEFAULT_PAYMENT)
payment_details = JSONField(db_index=True,default=DEFAULT_PAYMENT)
refund_details = JSONField(db_index=True,default=DEFAULT_PAYMENT)
deduction_details = JSONField(db_index=True,default=DEFAULT_PAYMENT)

@property
def paid(self):
Expand Down
211 changes: 124 additions & 87 deletions ledger/payments/reports.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from six.moves import StringIO
import csv
import pytz
from datetime import timedelta
from datetime import timedelta,datetime
from decimal import Decimal as D
from ledger.payments.models import Invoice, CashTransaction, BpointTransaction, BpayTransaction
from ledger.order.models import Line

PERTH_TIMEZONE = pytz.timezone('Australia/Perth')

Expand All @@ -16,7 +17,6 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
invoices = []
invoice_list = []
dates, banked_dates = [], []
parsed_invoices = {}
date_amounts, banked_date_amounts = [], []
items = []
oracle_codes = {}
Expand Down Expand Up @@ -105,10 +105,10 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
# Loop through the payments and not the invoices
for i in invoices:
# Add items of invoice if not in list

if i.order:# and not i.voided:
if i.reference not in parsed_invoices.keys():
parsed_invoices[i.reference] = {'amount':i.amount,'paid':i.payment_amount,'refunded':i.refundable_amount}
for x in i.order.lines.all():
lines = i.order.lines.all()
for x in lines:
#print((i, i.__dict__, x, x.oracle_code))
item_date_amounts, banked_item_dates_amounts = [], []
for d in dates:
Expand Down Expand Up @@ -194,7 +194,7 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
for k,v in payment_details["cash"].items():
c = CashTransaction.objects.get(id=int(k))
source = c.source
if source in ['cash','cheque','money_order']:
if source in set(['cash','cheque','money_order']):
if c.created.strftime(date_format) == d.get('date'):
banked_oracle_codes[code][date_amount_index]['amounts'][source] += D(v)
item[source] += D(v)
Expand All @@ -203,7 +203,7 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
for k,v in refund_details["cash"].items():
c = CashTransaction.objects.get(id=int(k))
source = c.source
if source in ['cash','cheque','money_order']:
if source in set(['cash','cheque','money_order']):
if c.created.strftime(date_format) == d.get('date'):
banked_oracle_codes[code][date_amount_index]['amounts'][source] -= D(v)
item[source] -= D(v)
Expand All @@ -212,7 +212,7 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
for k,v in deduction_details["cash"].items():
c = CashTransaction.objects.get(id=int(k))
source = c.source
if source in ['cash','cheque','money_order']:
if source in set(['cash','cheque','money_order']):
if c.created.strftime(date_format) == d.get('date'):
banked_oracle_codes[code][date_amount_index]['amounts'][source] -= D(v)
item[source] -= D(v)
Expand Down Expand Up @@ -352,83 +352,120 @@ def generate_items_csv(system,start,end,banked_start,banked_end,region=None,dist
def generate_trans_csv(system,start,end,region=None,district=None):
# Get invoices matching the system and date range
strIO = None
invoices = Invoice.objects.filter(system=system)
if invoices:
strIO = StringIO()
fieldnames = ['Created','Settlement Date', 'Payment Method', 'Transaction Type', 'Amount', 'Approved', 'Source', 'Product Names',
'Product Codes', 'Invoice']
writer = csv.DictWriter(strIO, fieldnames=fieldnames)
writer.writeheader()
for i in invoices:
items = item_codes = bpay = bpoint = cash = None
item_names = []
oracle_codes = []
# Get all items for this invoice
if i.order:
items = i.order.lines.all().values('title', 'oracle_code')
for item in items:
item_names.append(item.get('title'))
code = item.get('oracle_code')
if not code: code = 'N\A'
oracle_codes.append(code)
item_names = '|'.join(item_names)
oracle_codes = '|'.join(oracle_codes)
# Get all transactions for this invoice
'''params = {
'created__gte':start,
'created__lte': end
}'''
cash = i.cash_transactions.filter(created__gte=start, created__lte=end, district=district)
if not district:
bpoint = i.bpoint_transactions.filter(settlement_date__gte=start, settlement_date__lte=end).exclude(crn1__endswith='_test')
bpay = i.bpay_transactions.filter(p_date__gte=start, p_date__lte=end)
# Write out the cash transactions
for c in cash:
if c.type not in ['move_in','move_out']:
cash_info = {
'Created': c.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': c.created.strftime('%d/%m/%Y'),
'Invoice': c.invoice.reference,
'Payment Method': 'Cash',
'Transaction Type': c.type.lower(),
'Amount': c.amount if c.type not in ['refund','move_out'] else '-{}'.format(c.amount),
'Approved': 'True',
'Source': c.source,
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(cash_info)
if not district:
# Write out all bpay transactions
for b in bpay:
bpay_info = {
'Created': b.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': b.p_date.strftime('%d/%m/%Y'),
'Invoice': b.crn,
'Payment Method': 'BPAY',
'Transaction Type': b.get_p_instruction_code_display(),
'Amount': b.amount if b.p_instruction_code == '05' and b.type == '399' else '-{}'.format(b.amount),
'Approved': b.approved,
'Source': 'N/A',
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(bpay_info)
# Write out all bpoint transactions
for bpt in bpoint:
bpoint_info = {
'Created': bpt.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': bpt.settlement_date.strftime('%d/%m/%Y'),
'Invoice': bpt.crn1,
'Payment Method': 'BPOINT',
'Transaction Type': bpt.action.lower(),
'Amount': bpt.amount if bpt.action not in ['refund'] else '-{}'.format(bpt.amount),
'Approved': bpt.approved,
'Source': 'N/A',
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(bpoint_info)
strIO.flush()
strIO.seek(0)
invoices = []

cash = None
bpoint = None
bpay = None

# Get all transactions
cash = CashTransaction.objects.filter(created__gte=start, created__lte=end,district=district,invoice__system=system).order_by('-created')
bpoint = BpointTransaction.objects.filter(settlement_date__gte=start, settlement_date__lte=end,crn1__startswith=system).order_by('-created').exclude(crn1__endswith='_test')
bpay = BpayTransaction.objects.filter(p_date__gte=start, p_date__lte=end,crn__startswith=system).order_by('-created')

# Print the header
strIO = StringIO()
fieldnames = ['Created','Settlement Date', 'Payment Method', 'Transaction Type', 'Amount', 'Approved', 'Source', 'Product Names',
'Product Codes', 'Invoice']
writer = csv.DictWriter(strIO, fieldnames=fieldnames)
writer.writeheader()

# Iterate through transactions
for c in cash:
i = c.invoice
items = item_codes = None
item_names = []
oracle_codes = []
# Get all items for this invoice
if i.order:
items = i.order.lines.all().values('title', 'oracle_code')
for item in items:
item_names.append(item.get('title'))
code = item.get('oracle_code')
if not code: code = 'N\A'
oracle_codes.append(code)
item_names = '|'.join(item_names)
oracle_codes = '|'.join(oracle_codes)


if c.type not in ['move_in','move_out']:
cash_info = {
'Created': c.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': c.created.strftime('%d/%m/%Y'),
'Invoice': c.invoice.reference,
'Payment Method': 'Cash',
'Transaction Type': c.type.lower(),
'Amount': c.amount if c.type not in ['refund','move_out'] else '-{}'.format(c.amount),
'Approved': 'True',
'Source': c.source,
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(cash_info)
if not district:
# Write out all bpay transactions
if bpay:
for b in bpay:
i = Invoice.objects.get(reference=b.crn)
items = item_codes = None
item_names = []
oracle_codes = []
# Get all items for this invoice
if i.order:
items = i.order.lines.all().values('title', 'oracle_code')
for item in items:
item_names.append(item.get('title'))
code = item.get('oracle_code')
if not code: code = 'N\A'
oracle_codes.append(code)
item_names = '|'.join(item_names)
oracle_codes = '|'.join(oracle_codes)

bpay_info = {
'Created': b.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': b.p_date.strftime('%d/%m/%Y'),
'Invoice': b.crn,
'Payment Method': 'BPAY',
'Transaction Type': b.get_p_instruction_code_display(),
'Amount': b.amount if b.p_instruction_code == '05' and b.type == '399' else '-{}'.format(b.amount),
'Approved': b.approved,
'Source': 'N/A',
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(bpay_info)
# Write out all bpoint transactions
if bpoint:
for bpt in bpoint:
i = Invoice.objects.get(reference=bpt.crn1)
items = item_codes = None
item_names = []
oracle_codes = []
# Get all items for this invoice
if i.order:
items = i.order.lines.all().values('title', 'oracle_code')
for item in items:
item_names.append(item.get('title'))
code = item.get('oracle_code')
if not code: code = 'N\A'
oracle_codes.append(code)
item_names = '|'.join(item_names)
oracle_codes = '|'.join(oracle_codes)

bpoint_info = {
'Created': bpt.created.astimezone(PERTH_TIMEZONE).strftime('%d/%m/%Y %H:%M:%S'),
'Settlement Date': bpt.settlement_date.strftime('%d/%m/%Y'),
'Invoice': bpt.crn1,
'Payment Method': 'BPOINT',
'Transaction Type': bpt.action.lower(),
'Amount': bpt.amount if bpt.action not in ['refund'] else '-{}'.format(bpt.amount),
'Approved': bpt.approved,
'Source': 'N/A',
'Product Names': item_names,
'Product Codes': oracle_codes
}
writer.writerow(bpoint_info)

strIO.flush()
strIO.seek(0)
return strIO
9 changes: 4 additions & 5 deletions ledger/payments/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def addToInterface(date,oracle_codes,system,override):
status_date = today
)
new_codes[k] = remainder_amount
if system.deduct_percentage and deduction_code.amount > 0:
if system.deduct_percentage and deduction_code.amount != 0:
deduction_code.save()
new_codes[deduction_code.activity_name] = deduction_code.amount
return new_codes
Expand All @@ -343,7 +343,7 @@ def oracle_parser(date,system,system_name,override=False):
op,created = OracleParser.objects.get_or_create(date_parsed=date)
bpoint_txns = []
bpay_txns = []
bpoint_txns.extend([x for x in BpointTransaction.objects.filter(settlement_date=date,response_code=0)])
bpoint_txns.extend([x for x in BpointTransaction.objects.filter(settlement_date=date,response_code=0).exclude(crn1__endswith='_test')])
bpay_txns.extend([x for x in BpayTransaction.objects.filter(p_date__contains=date, service_code=0)])
# Get the required invoices
for b in bpoint_txns:
Expand Down Expand Up @@ -378,7 +378,7 @@ def oracle_parser(date,system,system_name,override=False):
code = i.oracle_code
item_id = i.id
# Check previous parser results for this invoice
previous_invoices = OracleParserInvoice.objects.filter(reference=invoice.reference)
previous_invoices = OracleParserInvoice.objects.filter(reference=invoice.reference,parser__date_parsed=date)
code_paid_amount = D('0.0')
code_refunded_amount = D('0.0')
code_deducted_amount = D('0.0')
Expand All @@ -390,8 +390,7 @@ def oracle_parser(date,system,system_name,override=False):
code_paid_amount += D(p_item['payment'])
code_refunded_amount += D(p_item['refund'])
code_deducted_amount += D(p_item['deductions'])

# Deal with the current txn
# Deal with the current item
# Payments
paid_amount = D('0.0')
for k,v in i.payment_details['bpay'].items():
Expand Down
17 changes: 13 additions & 4 deletions wildlifelicensing/apps/dashboard/views/officer.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,24 +300,33 @@ def _render_action_column(obj):
discarded = obj.processing_status == 'discarded'
declined = obj.processing_status == 'declined'

action = ''
if obj.processing_status == 'ready_for_conditions':
return '<a href="{0}">Enter Conditions</a>'.format(
action += '<a href="{0}">Enter Conditions</a>'.format(
reverse('wl_applications:enter_conditions', args=[obj.pk]),
)
elif obj.processing_status == 'ready_to_issue':
return '<a href="{0}">Issue Licence</a>'.format(
action += '<a href="{0}">Issue Licence</a>'.format(
reverse('wl_applications:issue_licence', args=[obj.pk]),
)
elif any([issued, discarded, declined]):
return '<a href="{0}">{1}</a>'.format(
action += '<a href="{0}">{1}</a>'.format(
reverse('wl_applications:view_application_officer', args=[obj.pk]),
'View (read-only)'
)
else:
return '<a href="{0}">Process</a>'.format(
action += '<a href="{0}">Process</a>'.format(
reverse('wl_applications:process', args=[obj.pk]),
)

if obj.invoice_reference:
url = '{}?invoice={}'.format(reverse('payments:invoice-payment'),obj.invoice_reference)
action += '<br \><a target="_blank" href="{0}"> View Payment</a>'.format(
url
)

return action

def get_initial_queryset(self):
return Application.objects.exclude(processing_status__in=['draft', 'temp']).exclude(customer_status='temp')

Expand Down

0 comments on commit c495894

Please sign in to comment.