loan file modification
diff --git a/accounts/doctype/gl_control/gl_control.py b/accounts/doctype/gl_control/gl_control.py
index 5ec8ecd..a346b65 100644
--- a/accounts/doctype/gl_control/gl_control.py
+++ b/accounts/doctype/gl_control/gl_control.py
@@ -12,7 +12,7 @@
 get_value = webnotes.conn.get_value
 in_transaction = webnotes.conn.in_transaction
 convert_to_lists = webnotes.conn.convert_to_lists
-	
+
 # -----------------------------------------------------------------------------------------
 from utilities.transaction_base import TransactionBase
 
@@ -30,11 +30,11 @@
 		#for r in ret:
 		#	inc = get_value('Account','Income - '+r[1], 'balance')
 		#	exp = get_value('Account','Expenses - '+r[1], 'balance')
-		#	pl[r[0]] = flt(flt(inc) - flt(exp))		
+		#	pl[r[0]] = flt(flt(inc) - flt(exp))
 		return {'cl':[r[0] for r in ret]}#, 'pl':pl}
-		
-	def get_company_currency(self,arg=''):			
-		dcc = TransactionBase().get_company_currency(arg)		
+
+	def get_company_currency(self,arg=''):
+		dcc = TransactionBase().get_company_currency(arg)
 		return dcc
 
 	# Get current balance
@@ -91,7 +91,7 @@
 
 		fy = get_defaults()['fiscal_year']
 		parent, parent_acc_name, company, type = arg.split(',')
-		
+
 		# get children account details
 		if type=='Account':
 
@@ -103,7 +103,7 @@
 
 			# remove Decimals
 			for c in cl: c['balance'] = flt(c['balance'])
-			
+
 		# get children cost center details
 		elif type=='Cost Center':
 			if parent=='Root Node':
@@ -111,7 +111,7 @@
 			else:
 				cl = sql("select name,group_or_ledger,cost_center_name from `tabCost Center` where ifnull(parent_cost_center, '')=%s and docstatus != 2 and company_name=%s order by name asc",(parent,company),as_dict=1)
 		return {'parent':parent, 'parent_acc_name':parent_acc_name, 'cl':cl}
-		
+
 	# Add a new account
 	# -----------------
 	def add_ac(self,arg):
@@ -119,14 +119,14 @@
 		ac = Document('Account')
 		for d in arg.keys():
 			ac.fields[d] = arg[d]
-		ac.old_parent = ''			
+		ac.old_parent = ''
 		ac_obj = get_obj(doc=ac)
 		ac_obj.validate()
 		ac_obj.doc.save(1)
 		ac_obj.on_update()
 
 		return ac_obj.doc.name
-	
+
 	# Add a new cost center
 	#----------------------
 	def add_cc(self,arg):
@@ -138,33 +138,33 @@
 		# map company abbr
 		other_info = sql("select company_abbr from `tabCost Center` where name='%s'"%arg['parent_cost_center'])
 		cc.company_abbr = other_info and other_info[0][0] or arg['company_abbr']
-		
+
 		cc_obj = get_obj(doc=cc)
 		cc_obj.validate()
 		cc_obj.doc.save(1)
 		cc_obj.on_update()
 
 		return cc_obj.doc.name
-		
-		
+
+
 	# Get field values from the voucher
 	#------------------------------------------
 	def get_val(self, src, d, parent=None):
-		if not src: 
+		if not src:
 			return None
 		if src.startswith('parent:'):
 			return parent.fields[src.split(':')[1]]
 		elif src.startswith('value:'):
 			return eval(src.split(':')[1])
 		elif src:
-			return d.fields.get(src)	
-			
+			return d.fields.get(src)
+
 	def check_if_in_list(self, le):
 		for e in self.entries:
 			if e.account == le.account and (cstr(e.against_voucher)==cstr(le.against_voucher)) and (cstr(e.against_voucher_type)==cstr(le.against_voucher_type)) and (cstr(e.cost_center)==cstr(le.cost_center)):
 				return [e]
 		return 0
-	
+
 	# Make a dictionary(le) for every gl entry and append to a list(self.entries)
 	#----------------------------------------------------------------------------
 	def make_single_entry(self,parent,d,le_map,cancel, merge_entries):
@@ -176,12 +176,12 @@
 			is_expense_acct = sql("select name from tabAccount where is_pl_account='Yes' and debit_or_credit='Debit' and name=%s",self.get_val(le_map['account'], d, parent))
 			if is_expense_acct and self.get_val(le_map['cost_center'], d, parent):
 				get_obj('Budget Control').check_budget([self.get_val(le_map[k], d, parent) for k in flist if k in ['account','cost_center','debit','credit','posting_date','fiscal_year','company']],cancel)
-			
+
 			# Create new GL entry object and map values
 			le = Document('GL Entry')
 			for k in flist:
 				le.fields[k] = self.get_val(le_map[k], d, parent)
-						
+
 			# if there is already an entry in this account then just add it to that entry
 			same_head = self.check_if_in_list(le)
 			if same_head and merge_entries:
@@ -190,8 +190,8 @@
 				same_head.credit = flt(same_head.credit) + flt(le.credit)
 			else:
 				self.entries.append(le)
-		
-	# Save GL Entries		 
+
+	# Save GL Entries
 	# ----------------
 	def save_entries(self, cancel, adv_adj, update_outstanding):
 		for le in self.entries:
@@ -199,7 +199,7 @@
 			if cancel or flt(le.debit) < 0 or flt(le.credit) < 0:
 				tmp=le.debit
 				le.debit, le.credit = abs(flt(le.credit)), abs(flt(tmp))
-			
+
 
 			le_obj = get_obj(doc=le)
 			# validate except on_cancel
@@ -213,11 +213,11 @@
 			# update total debit / credit
 			self.td += flt(le.debit)
 			self.tc += flt(le.credit)
-			
+
 	# Make Multiple Entries
 	# ---------------------
 	def make_gl_entries(self, doc, doclist, cancel=0, adv_adj = 0, use_mapper='', merge_entries = 1, update_outstanding='Yes'):
-		# get entries	
+		# get entries
 		le_map_list = sql("select * from `tabGL Mapper Detail` where parent = %s", use_mapper or doc.doctype, as_dict=1)
 		self.td, self.tc = 0.0, 0.0
 		for le_map in le_map_list:
@@ -228,10 +228,10 @@
 						self.make_single_entry(doc,d,le_map,cancel, merge_entries)
 			else:
 				self.make_single_entry(None,doc,le_map,cancel, merge_entries)
-				
+
 		# save entries
 		self.save_entries(cancel, adv_adj, update_outstanding)
-		
+
 		# check total debit / credit
 		# Due to old wrong entries (total debit != total credit) some voucher could be cancelled
 		if abs(self.td - self.tc) > 0.001 and not cancel:
@@ -289,7 +289,7 @@
 			add.allocate_amount = 0
 			if table_name == 'Advance Allocation Detail':
 				add.tds_amount = flt(d[4])
-	
+
 	# Clear rows which is not adjusted
 	#-------------------------------------
 	def clear_advances(self, obj,table_name,table_field_name):
@@ -297,7 +297,7 @@
 			if not flt(d.allocated_amount):
 				sql("update `tab%s` set parent = '' where name = '%s' and parent = '%s'" % (table_name, d.name, d.parent))
 				d.parent = ''
-					
+
 	# Update aginst document in journal voucher
 	#------------------------------------------
 	def update_against_document_in_jv(self, obj, table_field_name, against_document_no, against_document_doctype, account_head, dr_or_cr,doctype):
@@ -310,7 +310,7 @@
 
 				# update ref in JV Detail
 				sql("update `tabJournal Voucher Detail` set %s = '%s' where name = '%s'" % (doctype=='Payable Voucher' and 'against_voucher' or 'against_invoice', cstr(against_document_no), d.jv_detail_no))
-				
+
 				# re-submit JV
 				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
 				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj =1)
@@ -319,22 +319,22 @@
 				# cancel JV
 				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children=1)
 				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj = 1)
-				
+
 				# add extra entries
 				self.add_extra_entry(jv_obj, d.journal_voucher, d.jv_detail_no, flt(d.allocated_amount), account_head, doctype, dr_or_cr, against_document_no)
-				
+
 				# re-submit JV
 				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
 				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj = 1)
 			else:
 				msgprint("Allocation amount cannot be greater than advance amount")
 				raise Exception
-	
+
 	# Add extra row in jv detail for unadjusted amount
 	#--------------------------------------------------
 	def add_extra_entry(self,jv_obj,jv,jv_detail_no, allocate, account_head, doctype, dr_or_cr, against_document_no):
 		# get old entry details
-		
+
 		jvd = sql("select %s, cost_center, balance, against_account from `tabJournal Voucher Detail` where name = '%s'" % (dr_or_cr,jv_detail_no))
 		advance = jvd and flt(jvd[0][0]) or 0
 		balance = flt(advance) - flt(allocate)
@@ -351,7 +351,7 @@
 		add.against_account = cstr(jvd[0][3])
 		add.is_advance = 'Yes'
 		add.save(1)
-	
+
 	# check if advance entries are still valid
 	# ----------------------------------------
 	def validate_jv_entry(self, d, account_head, dr_or_cr):
@@ -406,22 +406,23 @@
 		"""
 		vl = sql("""
 			select voucher_type, voucher_no, account, sum(debit) as sum_debit, sum(credit) as sum_credit
-			from `tabGL Entry` 
+			from `tabGL Entry`
 			where is_cancelled='Yes' and creation > %s
 			group by voucher_type, voucher_no, account
 			""", after_date, as_dict=1)
-		
+
 		ac_list = []
 		for v in vl:
 			if v['sum_debit'] != 0 or v['sum_credit'] != 0:
 				ac_list.append(v['account'])
-		
-		fy_list = sql("""select name from `tabFiscal Year` 
-		where (%s between year_start_date and date_sub(date_add(year_start_date,interval 1 year), interval 1 day)) 
-		or year_start_date > %s 
+
+		fy_list = sql("""select name from `tabFiscal Year`
+		where (%s between year_start_date and date_sub(date_add(year_start_date,interval 1 year), interval 1 day))
+		or year_start_date > %s
 		order by year_start_date ASC""", (after_date, after_date))
 
 		for fy in fy_list:
 			fy_obj = get_obj('Fiscal Year', fy[0])
 			for a in set(ac_list):
 				fy_obj.repost(a)
+
diff --git a/accounts/doctype/loan/loan.js b/accounts/doctype/loan/loan.js
index a26df3f..1851a84 100644
--- a/accounts/doctype/loan/loan.js
+++ b/accounts/doctype/loan/loan.js
@@ -8,19 +8,24 @@
 		}
 		cur_frm.refresh();
 	},
+/*	submit:function(doc){
+		data=doc.get_values();
+
+		data['']=
+		$c_obj(make_doclist(dt,dn),'loan_post',data,function(){});
+	},*/
 	refresh: function(doc) {
 		cur_frm.cscript.hide_show_buttons(doc);
 	},
 	hide_show_buttons: function(doc) {
 		if(doc.docstatus==0) {
-			hide_field('Installment Reciept');// show_field('Generate');
+			hide_field('Installment Reciept'); show_field('Generate');
 		} else if (doc.docstatus==1) {
-//			show_field('Installment Reciept'); 
-hide_field('Generate');			
+			show_field('Installment Reciept');hide_field('Generate');
 		}
 	},
 	clear_installments: function(doc) {
-		$.each(getchildren('Loan Installment', doc.name, 'installments', 'Loan'), 
+		$.each(getchildren('Loan Installment', doc.name, 'installments', 'Loan'),
 			function(i, d) {
 				LocalDB.delete_doc('Loan Installment', d.name);
 			}
@@ -40,9 +45,9 @@
 		d.show();
 		d.fields_dict.update.input.onclick = function() {
 			var data = d.get_values();
-			
+
 			if(data) {
-				$c_obj(make_doclist(dt,dn),'loan_post',data,function(){cur_frm.refresh(); d.hide();});
+				$c_obj(make_doclist(dt,dn),'loan_installment_post',data,function(){cur_frm.refresh(); d.hide();});
 			}
 		}
 	}
diff --git a/accounts/doctype/loan/loan.py b/accounts/doctype/loan/loan.py
index adddbc5..9f0bcb5 100644
--- a/accounts/doctype/loan/loan.py
+++ b/accounts/doctype/loan/loan.py
@@ -3,49 +3,46 @@
 from webnotes import msgprint
 from webnotes.utils import get_defaults
 import json
+from accounts.utils import post_jv
 sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, doc, doclist):
 		self.doc, self.doclist = doc, doclist
-		
+
 	def autoname(self):
 		"""
 			Create Loan Id using naming_series pattern
 		"""
 		self.doc.name = make_autoname(self.doc.naming_series+ '.#####')
 
-	def loan_post(self, args):
+	def loan_post(self):
+		data['voucher_type']='Loan Issue'
+		data['naming_series']='JV'
+		data['fiscal_year'] = get_defaults()['fiscal_year'] # To be modified to take care
+		data['company'] = get_defaults()['company']
+		data['debit_account'] = self.doc['receivable_account']
+		data['credit_account'] = self.doc['account']
+		data['amount'] = self.doc.loan_amount
+		jv_name=post_jv(data)
+
+	def loan_installment_post(self, args):
 		"""
 			Posts the loan receipt into Journal Voucher
 		"""
-		data = json.loads(args)
-
-		jv = Document('Journal Voucher')
-		jv.voucher_type = 'Loan Receipt'
-		jv.naming_series = 'JV'
-		jv.voucher_date = data.get('cheque_date')
-		jv.posting_date = data.get('cheque_date')
-		jv.cheque_no = data.get('cheque_number')
-		jv.cheque_date = data.get('cheque_date')
-		jv.fiscal_year = get_defaults()['fiscal_year'] # To be modified to take care
-		jv.company = get_defaults()['company']
-
-		jv.save(1)
-
 		next_inst = sql("select amount,name from `tabLoan Installment` where parent=%s and ifnull(cheque_number,'')='' order by due_date limit 1",self.doc.name)
-		
-		jc = addchild(jv,'entries','Journal Voucher Detail',0)
-		jc.account = data.get('bank_account')
-		jc.debit = next_inst[0][0]
-		jc.save()
 
-		jc = addchild(jv,'entries','Journal Voucher Detail',0)
-		jc.account = self.doc.account
-		jc.credit = next_inst[0][0]
-		jc.save()
+		data = json.loads(args)
+		data['voucher_type']='Loan Receipt'
+		data['naming_series']='JV'
+		data['amount']=next_inst[0][0]
+		data['debit_account']=data.get('bank_account')
+		data['credit_account']=self.doc.account
+		data['fiscal_year']=get_defaults()['fiscal_year']
+		data['company']=get_defaults()['company']
+		jv_name=post_jv(data)
 
-		sql("update `tabLoan Installment` set cheque_number=%s, cheque_date=%s, jv_number=%s where name=%s",(data.get('cheque_number'),data.get('cheque_date'),jv.name,next_inst[0][1]))
+		sql("update `tabLoan Installment` set cheque_number=%s, cheque_date=%s, jv_number=%s where name=%s",(data.get('cheque_number'),data.get('cheque_date'),jv_name,next_inst[0][1]))
 
 		self.doclist = [Document(d.doctype, d.name) for d in self.doclist]
 
diff --git a/accounts/doctype/loan/loan.txt b/accounts/doctype/loan/loan.txt
index 3be82fb..001e1d3 100644
--- a/accounts/doctype/loan/loan.txt
+++ b/accounts/doctype/loan/loan.txt
@@ -5,21 +5,21 @@
 	{
 		'creation': '2011-07-15 10:35:26',
 		'docstatus': 0,
-		'modified': '2011-07-15 15:51:10',
+		'modified': '2011-07-18 12:12:19',
 		'modified_by': 'Administrator',
 		'owner': 'Administrator'
 	},
 
 	# These values are common for all DocType
 	{
-		'_last_update': '1310706327',
+		'_last_update': '1310963215',
 		'colour': 'White:FFF',
 		'doctype': 'DocType',
 		'module': 'Accounts',
 		'name': '__common__',
 		'section_style': 'Simple',
 		'show_in_menu': 0,
-		'version': 12
+		'version': 15
 	},
 
 	# These values are common for all DocField
@@ -92,9 +92,30 @@
 	# DocField
 	{
 		'doctype': 'DocField',
+		'fieldname': 'receivable_account',
+		'fieldtype': 'Link',
+		'idx': 3,
+		'label': 'Receivable Account',
+		'options': 'Account'
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
+		'fieldname': 'invoice',
+		'fieldtype': 'Link',
+		'idx': 4,
+		'label': 'Invoice',
+		'options': 'Receivable Voucher',
+		'reqd': 1
+	},
+
+	# DocField
+	{
+		'doctype': 'DocField',
 		'fieldname': 'loan_amount',
 		'fieldtype': 'Currency',
-		'idx': 3,
+		'idx': 5,
 		'label': 'Loan Amount',
 		'reqd': 1
 	},
@@ -104,7 +125,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'start_date',
 		'fieldtype': 'Date',
-		'idx': 4,
+		'idx': 6,
 		'label': 'Start Date',
 		'reqd': 1
 	},
@@ -114,7 +135,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'no_of_installments',
 		'fieldtype': 'Int',
-		'idx': 5,
+		'idx': 7,
 		'label': 'No of Installments',
 		'reqd': 1
 	},
@@ -124,7 +145,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 6,
+		'idx': 8,
 		'label': 'Generate',
 		'trigger': 'Client'
 	},
@@ -134,7 +155,7 @@
 		'doctype': 'DocField',
 		'fieldname': 'installments',
 		'fieldtype': 'Table',
-		'idx': 7,
+		'idx': 9,
 		'label': 'Installments',
 		'options': 'Loan Installment'
 	},
@@ -145,7 +166,7 @@
 		'colour': 'White:FFF',
 		'doctype': 'DocField',
 		'fieldtype': 'Button',
-		'idx': 8,
+		'idx': 10,
 		'label': 'Installment Reciept'
 	}
 ]
\ No newline at end of file