Journal working fully along with Payment.

This commit is contained in:
unknown 2012-08-23 22:30:27 +05:30
parent d7789642c1
commit e580e6d2da
8 changed files with 169 additions and 267 deletions

View File

@ -17,3 +17,15 @@ overlord_filter.filter('posted', function () {
return input == true ? 'Posted' : 'Post';
};
});
overlord_filter.filter('journalDebit', function () {
return function (input, debit) {
var list = [];
for (var i = 0, l = input.length; i < l; i++) {
if (input[i].Debit === debit) {
list.push(input[i]);
}
}
return list;
};
});

View File

@ -15,18 +15,27 @@
}
}
if (i >= l) {
this.voucher.Journals.push({Debit:$scope.debit, Amount:$scope.amount, Ledger:{LedgerID:$scope.id, Name:$scope.name}});
this.voucher.Journals.push({Debit:$scope.debit, Amount:Number($scope.amount), Ledger:{LedgerID:$scope.id, Name:$scope.name}});
}
delete $scope.amount;
delete $scope.id;
delete $scope.name;
$('#txtLedger').focus();
};
$scope.removeJournal = function (journal) {
var index = this.voucher.Journals.indexOf(journal);
this.voucher.Journals.splice(index, 1);
};
$scope.$watch('voucher.Journals', function (journals, oldValue) {
var amount = 0;
for (var i = 0, l = journals.length; i < l; i++) {
amount += (Number(journals[i].Amount) * parseInt(journals[i].Debit));
}
$scope.amount = Math.abs(amount);
}, true);
$scope.save = function () {
save_voucher($scope);
};

View File

@ -1,184 +1,54 @@
var Journal = Backbone.Model.extend({
url:add_journal_url
});
var Journals = Backbone.Collection.extend({
model:Journal
});
var DropDownInput = Backbone.View.extend({
events:{
'change #ddlLedger':'ddlLedgerChanged'
},
initialize:function () {
this.collection.on('add change remove', this.updateDdl, this);
},
ddlLedgerChanged:function (e) {
var list = this.collection.where({Debit:-1});
if (list.length != 1) {
showSimpleError("Too many or too little credit journals");
}
var ddl = list[0];
var ledger = ddl.get("Ledger");
ledger.LedgerID = $('#ddlLedger').val();
ddl.set("Ledger", ledger);
},
updateDdl:function (status) {
var row = status.toJSON();
if (row.Debit == -1) {
$('#ddlLedger').val(row.Ledger.LedgerID);
} else {
var totalAmount = 0;
$.each(this.collection.where({Debit:1}), function (index, item) {
totalAmount += item.get('Amount');
});
var list = this.collection.where({Debit:-1});
if (list.length != 1) {
showSimpleError("Too many or too little credit journals");
function PaymentCtrl($scope, save_voucher, delete_voucher, post_voucher) {
$scope.addJournal = function () {
for (var i = 0, l = this.voucher.Journals.length; i < l; i++) {
if (this.voucher.Journals[i].Ledger.LedgerID === $scope.id) {
var amount = (this.voucher.Journals[i].Debit * this.voucher.Journals[i].Amount) + (parseInt($scope.debit) * Number($scope.amount));
if (amount < 0) {
this.voucher.Journals[i].Debit = -1;
this.voucher.Journals[i].Amount = amount * -1;
} else {
this.voucher.Journals[i].Debit = 1;
this.voucher.Journals[i].Amount = amount;
}
break;
}
var ddl = list[0];
ddl.set("Amount", totalAmount);
}
}
});
var GetFromInput = Backbone.View.extend({
events:{
'click #btnAdd':'addJournal',
'keypress #txtAmount':'addOnEnter'
},
initialize:function () {
this.collection.on('add', this.clearInput, this);
this.collection.on('change', this.clearInput, this);
},
addJournal:function (e) {
e.preventDefault();
var journal = new Journal();
journal.save({
debit:1,
ledgerString:this.$('#txtLedger').val(),
amount:this.$('#txtAmount').val() },
{
wait:true,
success:$.proxy(function (model, response) {
var newModel = model.toJSON();
var found = null;
this.collection.each(function (item) {
var itemJson = item.toJSON();
if (itemJson.Ledger.LedgerID == newModel.Ledger.LedgerID) {
found = item;
}
});
if (found == null) {
this.collection.add(model);
} else {
var foundJson = found.toJSON();
var amount = (foundJson.Debit * foundJson.Amount) + (newModel.Debit * newModel.Amount);
if (amount < 0) {
found.set({Debit:-1, Amount:amount * -1});
} else {
found.set({Debit:1, Amount:amount});
}
}
}, this)});
},
addOnEnter:function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
e.preventDefault();
this.addJournal(e);
if (i >= l) {
this.voucher.Journals.push({Debit:1, Amount:Number($scope.amount), Ledger:{LedgerID:$scope.id, Name:$scope.name}});
}
},
clearInput:function () {
this.$('#txtLedger').val("");
this.$('#txtAmount').val("");
this.$('#txtLedger').focus();
}
});
delete $scope.amount;
delete $scope.id;
delete $scope.name;
$('#txtLedger').focus();
};
$scope.removeJournal = function (journal) {
var index = this.voucher.Journals.indexOf(journal);
this.voucher.Journals.splice(index, 1);
};
var ShowTable = Backbone.View.extend({
events:{
'click .Journal button':'removeJournal'
},
initialize:function () {
this.collection.on('add', this.addRow, this);
this.collection.on('remove', this.removeRow, this);
this.collection.on('change', this.changeRow, this);
this.collection.on('reset', this.resetRows, this);
},
removeJournal:function (ev) {
ev.preventDefault();
var cid = $(ev.target).closest("tr").attr("id");
this.collection.remove(this.collection.getByCid(cid))
},
removeRow:function (options) {
$('.Journal#' + options.cid).remove();
},
addRow:function (status) {
var row = status.toJSON();
row.cid = status.cid;
if (row.Debit == 1) {
var rowString = rowTemplate.render(row);
$(this.el).append(rowString);
}
},
changeRow:function (status) {
var row = status.toJSON();
row.cid = status.cid;
if (row.Debit == 1) {
var rowString = rowTemplate.render(row);
$('.Journal#' + status.cid).replaceWith(rowString);
}
},
resetRows:function (status) {
$(this.el).empty();
var rows;
this.collection.each(function (item) {
var row = item.toJSON();
row.cid = status.cid;
if (row.Debit == 1) {
var rowString = rowTemplate.render(row);
rows += rowString;
$scope.$watch('voucher.Journals', function (journals, oldValue) {
var amount = 0;
for (var i = 0, l = journals.length; i < l; i++) {
if (journals[i].Debit === -1) {
var creditJournal = journals[i];
} else {
amount += Number(journals[i].Amount);
}
});
$(this.el).append(rows);
}
});
}
if (creditJournal.Amount !== amount) {
creditJournal.Amount = amount;
}
}, true);
var SyncJournals = Backbone.View.extend({
initialize:function () {
this.collection.on('add remove change', this.updateVoucher, this);
this.model.on('destroy', this.updateJournals, this);
},
updateVoucher:function (status) {
this.model.set('Journals', this.collection.toJSON());
},
updateJournals:function (status) {
this.collection.reset();
this.collection.add(default_journal);
this.model.set('Journals', this.collection.toJSON());
}
});
$scope.save = function () {
save_voucher($scope);
};
var ShowFooter = Backbone.View.extend({
initialize:function () {
this.collection.on('add remove change', this.footerShow, this);
},
footerShow:function (status) {
var totalAmount = 0;
$.each(this.collection.where({Debit:1}), function (index, item) {
totalAmount += parseInt(item.get('Amount'));
});
$scope.delete = function () {
delete_voucher($scope);
};
var rowString = '<tr ><td class="JournalID hide"></td><td class="LedgerID hide"></td></td><td class="Name">' + 'Total' +
'</td><td class="Amount">' + totalAmount +
'</td><td class="Delete"></td></tr>';
this.$('#txtLedgerAmount').val(totalAmount);
var $table = this.$('#tfootMain')
$table.html(rowString);
}
});
$scope.post = function () {
post_voucher($scope);
};
}

View File

@ -9,7 +9,6 @@
<script type="text/javascript">
overlord.run(['$rootScope', function ($rootScope) {
$rootScope.voucher = ${json_voucher};
$rootScope.saveUrl = '${request.route_url('post_voucher', id = id)}';
$rootScope.toasts = [];
$rootScope.auth = {
perms:${perms},

View File

@ -2,98 +2,92 @@
<%inherit file="../base.mako"/>
<%block name="header">
<script type="text/javascript">
const add_journal_url = '${request.route_url('services_ledger_add_journal')}';
const post_url = '${request.route_url('post_voucher', id = id)}'
const delete_url = '${request.route_url('delete_voucher', id = id)}'
var rowTemplate = Hogan.compile('<tr class="Journal" id="{{cid}}"><td class="JournalID hide">{{JournalID}}</td>' +
'<td class="LedgerID hide">{{Ledger.LedgerID}}</td>' +
'<td class="Name">{{Ledger.Name}}</td><td data-column="Amount" class="Amount Editable">{{Amount}}</td>' +
'<td class="Delete"><button class="subtract">Delete</button></td></tr>');
var ddlTemplate = Hogan.compile('{{#list}}<option value="{{id}}">{{name}}</option>{{/list}}');
const default_journal = '${default_journal}';
</script>
${h.ScriptLink(request, 'payment.js')}
${h.ScriptLink(request, 'voucher.js')}
<script type="text/javascript">
overlord.run(['$rootScope', function ($rootScope) {
$rootScope.voucher = ${json_voucher};
$rootScope.toasts = [];
$rootScope.ledgers = ${ledgers};
$rootScope.auth = {
perms:${perms},
isUserInRole:function (role) {
return $rootScope.auth.perms.indexOf(role) !== -1;
}
};
}]);
</script>
<script type="text/javascript">
$(document).ready(function () {
AutoComplete('#txtLedger', '${request.route_url('services_ledger_list')}');
$('#txtDate').datepicker({ dateFormat:'dd-M-yy' });
$('#ddlLedger').html(ddlTemplate.render({list:${ledgers}}))
var voucher = new Voucher();
var journals = new Journals();
new GetFromInput({ el:$('#add'), collection:journals });
new ShowTable({ el:$('#tbodyMain'), collection:journals });
new ShowFooter({ el:'body', collection:journals });
new ShowAmountBox({ el:$('#tbodyMain'), collection:journals });
new VoucherView({ el:'body', model:voucher });
new VoucherOps({ el:'body', model:voucher });
new SyncJournals({el:'', model:voucher, collection:journals});
new DropDownInput({el:'#ddlGroup', collection:journals});
window.perms = new Perms();
new RolesView({el:$(".form-actions"), perms:perms, voucher:voucher});
voucher.set(${json_voucher});
journals.add(voucher.get('Journals'));
backboneRoles(['EditPosted', 'PostTransactions', 'Payment Delete', 'Payment Create', 'Payment Update']);
$('#txtLedger').focus();
});
</script>
</%block>
<%block name="content">
<form method="post" autocomplete="off" class="form-horizontal">
<form method="post" autocomplete="off" class="form-horizontal" ng-controller="PaymentCtrl">
${h.CsrfToken(request.session)}
${h.HiddenInput('VoucherID')}
${h.HiddenInput('Posted')}
<div class="control-group">
${h.Label('Code', 'txtCode', 'control-label')}
<div class="controls">
${h.TextInput('txtCode', css_class = 'non-search-box', placeholder='(Auto)', disabled='disabled')}
</div>
</div>
<div class="control-group">
${h.Label('Date', 'txtDate', 'control-label')}
<div class="controls">
${h.TextInput('txtDate', css_class = 'non-search-box', autocomplete='off')}
</div>
</div>
<div class="control-group" id="ddlGroup">
${h.Label('From', 'ddlLedger', 'control-label')}
<div class="controls">
<select id="ddlLedger" class="select-box"> </select>
${h.TextInput('txtLedgerAmount', autocomplete='off', placeholder='Amount')}
${h.HiddenInput('txtJournalID')}
</div>
</div>
<div class="control-group" id="add">
${h.Label('Ledger', 'txtLedger', 'control-label')}
<div class="controls">
<input type="text" id="txtLedger" class="search-box" autocomplete="off" placeholder="Ledger"/>
<label for="txtCode" class="control-label">Code</label>
<div class="input-prepend">
<span class="add-on">₹</span>
${h.TextInput('txtAmount', css_class = 'span2', autocomplete='off', placeholder='Amount')}
</div>
${h.SubmitButton('btnAdd', 'Add', 'btn btn-success icon-plus-sign')}
<div class="controls">
<input type="text" id="txtCode" class="non-search-box" disabled="disabled" ng-model="voucher.Code"/>
</div>
</div>
<div class="control-group">
${h.Label('', 'gvGrid', 'control-label')}
<label for="txtDate" class="control-label">Date</label>
<div class="controls">
<datepicker id="txtDate" model="voucher" prop="Date" ng-model="voucher.Date"></datepicker>
</div>
</div>
<div class="control-group" ng-repeat="journal in voucher.Journals | journalDebit:-1">
<label for="ddlLedger" class="control-label">From</label>
<div class="controls">
<select id="ddlLedger" class="select-box" ng-model="journal.Ledger.LedgerID" ng-options="l.LedgerID as l.Name for l in ledgers"> </select>
<div class=" input-prepend">
<span class="add-on">₹</span>
<input type="text" id="txtLedgerAmount" class="span2" autocomplete="off"
placeholder="Amount" ng-model="journal.Amount"/>
</div>
</div>
</div>
<div class=" control-group" id="add">
<label for="txtLedger" class="control-label">Add</label>
<div class="controls">
<autocomplete id="txtLedger" url="${request.route_url('services_ledger_id_list')}" selname="name"
selid="id" ng-model="name"></autocomplete>
<div class=" input-prepend">
<span class="add-on">₹</span>
<input type="text" id="txtAmount" class="span2" autocomplete="off"
placeholder="Amount" ng-model="amount"/>
</div>
<button class="btn btn-success" ng-click="addJournal()">Add</button>
</div>
</div>
<div class="control-group">
<label for="gvGrid" class="control-label"></label>
<div class="controls">
<table id="gvGrid" class="clean-table">
<thead>
<tr>
<th class="JournalID hide">JournalID</th>
<th class="LedgerID hide">LedgerID</th>
<th class="Name">Name</th>
<th class="Amount">Amount</th>
<th class="Delete">Delete</th>
</tr>
</thead>
<tbody id="tbodyMain">
<tr class="Journal" ng-repeat="journal in voucher.Journals | journalDebit:1">
<td class="Name">{{journal.Ledger.Name}}</td>
<td data-column="Amount" class="Amount Editable">{{journal.Amount}}</td>
<td class="Delete">
<button ng-click="removeJournal(journal)">Delete</button>
</td>
</tr>
</tbody>
<tfoot id="tfootMain">
</tfoot>
@ -101,16 +95,32 @@
</div>
</div>
<div class="control-group">
${h.Label('Narration', 'txtNarration', 'control-label')}
<label for="txtNarration" class="control-label">Narration</label>
<div class="controls">
<textarea rows="2" cols="20" id="txtNarration" class="non-search-box"></textarea>
<textarea rows="2" cols="20" id="txtNarration"
class="non-search-box" ng-model="voucher.Narration"></textarea>
</div>
</div>
<div class="form-actions">
${h.SubmitButton('btnSave', 'Save', 'btn btn-primary')}
${h.SubmitButton('btnUpdate', 'Update', 'btn-primary')}
${h.SubmitButton('btnPost', 'Post', 'btn btn-inverse')}
${h.SubmitButton('btnDelete', 'Delete', 'btn btn-danger')}
<button class="btn btn-primary" ng-click="save()" ng-hide="voucher.Code != '(Auto)'"
ng-disabled="!auth.isUserInRole('Payment Create')">Save
</button>
<button class="btn btn-primary" ng-click="save()" ng-hide="voucher.Code == '(Auto)'"
ng-disabled="!auth.isUserInRole('Payment Update') || (voucher.Posted && !auth.isUserInRole('EditPosted'))">
Update
</button>
<button class="btn btn-inverse" ng-click="post()" ng-hide="voucher.Code == '(Auto)'"
ng-disabled="voucher.Posted || !auth.isUserInRole('PostTransactions')">{{voucher.Posted | posted}}
</button>
<button class="btn btn-danger" ng-click="delete()" ng-hide="voucher.Code == '(Auto)'"
ng-disabled="!auth.isUserInRole('Payment Delete') || (voucher.Posted && !auth.isUserInRole('EditPosted'))">
Delete
</button>
</div>
<div class="row-fluid">
Created on {{voucher.CreationDate}} and Last Edited on {{voucher.LastEditDate}} by {{voucher.User}}. Posted
by {{voucher.Poster}}
</div>
</form>
</%block>

View File

@ -37,10 +37,10 @@ def ledger_list_by_type(type):
list = []
if type is None:
for item in LedgerBase.list():
list.append({'id': str(item.id), 'name': item.name})
list.append({'LedgerID': str(item.id), 'Name': item.name})
else:
for item in LedgerBase.list_by_type(type):
list.append({'id': str(item.id), 'name': item.name})
list.append({'LedgerID': str(item.id), 'Name': item.name})
return list

View File

@ -34,8 +34,8 @@ def journal_get(request):
json_voucher = Literal(json.dumps(voucher_info(voucher)))
return {'title': 'Hops n Grains - Journal Entry',
'id': id,
'json_voucher': json_voucher,
'perms': perms}
'perms': perms,
'json_voucher': json_voucher}
def voucher_info(voucher):
@ -73,13 +73,11 @@ def journal_post(request):
def create_voucher(json, user):
dt = datetime.datetime.strptime(json['Date'], '%d-%b-%Y')
voucher = Voucher(date=dt, narration=json['Narration'], user_id=user.id,
type=VoucherType.by_name('Journal'), posted=False)
voucher = Voucher(date=dt, narration=json['Narration'], user_id=user.id, type=VoucherType.by_name('Journal'),
posted=False)
for item in json['Journals']:
ledger = LedgerBase.by_id(uuid.UUID(item['Ledger']['LedgerID']))
journal_id = uuid.UUID(item['JournalID'])
if uuid.UUID('00000000-0000-0000-0000-000000000000') == journal_id:
journal_id = None
journal_id = uuid.UUID(item['JournalID']) if 'JournalID' in item else None
voucher.journals.append(
Journal(id=journal_id, amount=Decimal(item['Amount']), debit=int(item['Debit']), ledger_id=ledger.id,
cost_center_id=ledger.costcenter_id))

View File

@ -26,31 +26,37 @@ from brewman.views.transactions import session_current_date
permission='Payment Create')
def journal_get(request):
id = request.matchdict.get('id', None)
perms = Literal(json.dumps(request.session['perms']))
ledgers = Literal(json.dumps(ledger_list_by_type(1)))
default_journal = Literal(
json.dumps({'Ledger': {'LedgerID': 'ed2341bb-80b8-9649-90db-f9aaca183bb3'}, 'Amount': 0, 'Debit': -1}))
if id is None:
json_voucher = Literal(json.dumps({'Date': session_current_date(request), 'Posted': True, 'Narration': "",
'Journals': [{'JournalID': '00000000-0000-0000-0000-000000000000',
'Ledger': {'LedgerID': 'ed2341bb-80b8-9649-90db-f9aaca183bb3'},
'Ledger': {'LedgerID': 'ed2341bb-80b8-9649-90db-f9aaca183bb3',
'Name': 'Cash in Hand'},
'Amount': 0, 'Debit': -1}]}))
else:
voucher = Voucher.by_id(uuid.UUID(id))
json_voucher = Literal(json.dumps(voucher_info(voucher)))
return {'title': 'Hops n Grains - Payment Entry',
'id': id,
'perms': perms,
'ledgers': ledgers,
'default_journal': default_journal,
'json_voucher': json_voucher}
def voucher_info(voucher):
json_voucher = {'VoucherID': str(voucher.id), 'Date': voucher.date.strftime('%d-%b-%Y'), 'Posted': voucher.posted,
'Code': voucher.code, 'Narration': voucher.narration, 'Journals': []}
'Code': voucher.code, 'Narration': voucher.narration, 'Journals': [],
'CreationDate': voucher.creation_date.strftime('%d-%b-%Y %H:%M'),
'LastEditDate': voucher.last_edit_date.strftime('%d-%b-%Y %H:%M'), 'User': voucher.user.name,
'Poster': voucher.poster.name if voucher.posted else ''}
for item in voucher.journals:
json_voucher['Journals'].append({'JournalID': str(item.id), 'Debit': item.debit, 'Amount': str(item.amount),
'Ledger': {'LedgerID': str(item.ledger.id), 'Name': item.ledger.name}})
return json_voucher
@view_config(request_method='POST', route_name='payment_id', renderer='json', xhr=True, permission='Payment Update')
@view_config(request_method='POST', route_name='payment', renderer='json', xhr=True, permission='Payment Create')
def journal_post(request):
@ -77,9 +83,7 @@ def create_voucher(json, user):
type=VoucherType.by_name('Payment'), posted=False)
for item in json['Journals']:
ledger = LedgerBase.by_id(uuid.UUID(item['Ledger']['LedgerID']))
journal_id = uuid.UUID(item['JournalID'])
if uuid.UUID('00000000-0000-0000-0000-000000000000') == journal_id:
journal_id = None
journal_id = uuid.UUID(item['JournalID']) if 'JournalID' in item else None
voucher.journals.append(
Journal(id=journal_id, amount=Decimal(item['Amount']), debit=int(item['Debit']), ledger_id=ledger.id,
cost_center_id=ledger.costcenter_id))
@ -101,7 +105,7 @@ def update_voucher(id, json, user):
found = False
for i in range(len(newJournals), 0, -1):
j = newJournals[i - 1]
if item.id == uuid.UUID(j['JournalID']):
if 'JournalID' in j and item.id == uuid.UUID(j['JournalID']):
ledger = LedgerBase.by_id(uuid.UUID(j['Ledger']['LedgerID']))
found = True
item.debit = int(j['Debit'])