blob: 1499e0a3064977420250d671dffe8826539551e6 [file] [log] [blame]
Nabin Hait2df4d542013-01-29 11:34:39 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17from __future__ import unicode_literals
18import webnotes
Anand Doshi3543f302013-05-24 19:25:01 +053019from webnotes import _, msgprint
20from webnotes.utils import flt, cint
21from setup.utils import get_company_currency, get_price_list_currency
22from utilities.transaction_base import TransactionBase, validate_conversion_rate
23import json
Nabin Hait2df4d542013-01-29 11:34:39 +053024
Nabin Haitbf495c92013-01-30 12:49:08 +053025class AccountsController(TransactionBase):
Saurabh6f753182013-03-20 12:55:28 +053026 def validate(self):
Anand Doshi3543f302013-05-24 19:25:01 +053027 self.set_missing_values(for_validate=True)
28
29 if self.meta.get_field("currency"):
30 self.company_currency = get_company_currency(self.doc.company)
31
32 validate_conversion_rate(self.doc.currency, self.doc.conversion_rate,
33 self.meta.get_label("conversion_rate"), self.doc.company)
34
35 # self.calculate_taxes_and_totals()
Saurabh6f753182013-03-20 12:55:28 +053036 self.validate_value("grand_total", ">=", 0)
Anand Doshi3543f302013-05-24 19:25:01 +053037 self.set_total_in_words()
38
39 def set_price_list_currency(self, buying_or_selling):
40 # TODO - change this, since price list now has only one currency allowed
41 if self.meta.get_field("price_list_name") and self.doc.price_list_name and \
42 not self.doc.price_list_currency:
43 self.doc.fields.update(get_price_list_currency({
44 "price_list_name": self.doc.price_list_name,
45 "use_for": buying_or_selling
46 }))
47
48 def set_missing_item_details(self, get_item_details):
49 """set missing item values"""
50 for item in self.doclist.get({"parentfield": self.fname}):
51 if item.fields.get("item_code"):
52 args = item.fields.copy().update(self.doc.fields)
53 ret = get_item_details(args)
54 for fieldname, value in ret.items():
55 if self.meta.get_field(fieldname, parentfield=self.fname) and \
56 not item.fields.get(fieldname):
57 item.fields[fieldname] = value
58
59 def set_taxes(self, tax_doctype, tax_parentfield, tax_master_field):
60 if not self.meta.get_field(tax_parentfield):
61 return
62
63 if not self.doclist.get({"parentfield": tax_parentfield}):
64 if not self.doc.fields.get(tax_master_field):
65 # get the default tax master
66 self.doc.fields[tax_master_field] = \
67 webnotes.conn.get_value(tax_doctype + " Master", {"is_default": 1})
68
69 if self.doc.fields.get(tax_master_field):
70 from webnotes.model import default_fields
71 tax_master = webnotes.bean(tax_doctype, self.doc.fields.get(tax_master_field))
72
73 for i, tax in enumerate(tax_master.doclist.get({"parentfield": tax_parentfield})):
74 for fieldname in default_fields:
75 tax.fields[fieldname] = None
76
77 tax.fields.update({
78 "doctype": tax_doctype,
79 "parentfield": tax_parentfield,
80 "idx": i+1
81 })
82
83 self.doclist.append(tax)
84
85 def calculate_taxes_and_totals(self):
86 self.doc.conversion_rate = flt(self.doc.conversion_rate)
87
88 # TODO validate conversion rate
89
90 self.item_doclist = self.doclist.get({"parentfield": self.fname})
91 self.tax_doclist = self.doclist.get({"parentfield": self.other_fname})
92
93 self.calculate_item_values()
94 self.initialize_taxes()
95
96 if hasattr(self, "determine_exclusive_rate"):
97 self.determine_exclusive_rate()
98
99 self.calculate_net_total()
100 self.calculate_taxes()
101 self.calculate_totals()
102 self._cleanup()
103
104 # TODO
105 # print format: show net_total_export instead of net_total
106
107 def initialize_taxes(self):
108 for tax in self.tax_doclist:
109 tax.item_wise_tax_detail = {}
110 for fieldname in ["tax_amount", "total",
111 "tax_amount_for_current_item", "grand_total_for_current_item",
112 "tax_fraction_for_current_item", "grand_total_fraction_for_current_item"]:
113 tax.fields[fieldname] = 0.0
114
115 self.validate_on_previous_row(tax)
116 self.validate_inclusive_tax(tax)
117 self.round_floats_in(tax)
118
119 def validate_on_previous_row(self, tax):
120 """
121 validate if a valid row id is mentioned in case of
122 On Previous Row Amount and On Previous Row Total
123 """
124 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
125 (not tax.row_id or cint(tax.row_id) >= tax.idx):
126 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
127 _("Please specify a valid") + " %(row_id_label)s") % {
128 "idx": tax.idx,
129 "taxes_doctype": tax.doctype,
130 "row_id_label": self.meta.get_label("row_id",
131 parentfield=self.other_fname)
132 }, raise_exception=True)
133
134 def validate_inclusive_tax(self, tax):
135 def _on_previous_row_error(row_range):
136 msgprint((_("Row") + " # %(idx)s [%(doctype)s]: " +
137 _("to be included in Item's rate, it is required that: ") +
138 " [" + _("Row") + " # %(row_range)s] " + _("also be included in Item's rate")) % {
139 "idx": tax.idx,
140 "doctype": tax.doctype,
141 "inclusive_label": self.meta.get_label("included_in_print_rate",
142 parentfield=self.other_fname),
143 "charge_type_label": self.meta.get_label("charge_type",
144 parentfield=self.other_fname),
145 "charge_type": tax.charge_type,
146 "row_range": row_range
147 }, raise_exception=True)
148
149 if cint(tax.included_in_print_rate):
150 if tax.charge_type == "Actual":
151 # inclusive tax cannot be of type Actual
152 msgprint((_("Row")
153 + " # %(idx)s [%(doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" "
154 + "cannot be included in Item's rate") % {
155 "idx": tax.idx,
156 "doctype": tax.doctype,
157 "charge_type_label": self.meta.get_label("charge_type",
158 parentfield=self.other_fname),
159 "charge_type": tax.charge_type,
160 }, raise_exception=True)
161 elif tax.charge_type == "On Previous Row Amount" and \
162 not cint(self.tax_doclist[tax.row_id - 1].included_in_print_rate):
163 # referred row should also be inclusive
164 _on_previous_row_error(tax.row_id)
165 elif tax.charge_type == "On Previous Row Total" and \
166 not all([cint(t.included_in_print_rate) for t in self.tax_doclist[:tax.row_id - 1]]):
167 # all rows about the reffered tax should be inclusive
168 _on_previous_row_error("1 - %d" % (tax.row_id,))
169
170 def calculate_taxes(self):
171 for item in self.item_doclist:
172 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
173
174 for i, tax in enumerate(self.tax_doclist):
175 # tax_amount represents the amount of tax for the current step
176 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
177
178 if hasattr(self, "set_item_tax_amount"):
179 self.set_item_tax_amount(item, tax, current_tax_amount)
180
181 # case when net total is 0 but there is an actual type charge
182 # in this case add the actual amount to tax.tax_amount
183 # and tax.grand_total_for_current_item for the first such iteration
184 if tax.charge_type=="Actual" and \
185 not (current_tax_amount or self.doc.net_total or tax.tax_amount):
186 zero_net_total_adjustment = flt(tax.rate, self.precision("tax_amount", tax))
187 current_tax_amount += zero_net_total_adjustment
188
189 # store tax_amount for current item as it will be used for
190 # charge type = 'On Previous Row Amount'
191 tax.tax_amount_for_current_item = current_tax_amount
192
193 # accumulate tax amount into tax.tax_amount
194 tax.tax_amount += current_tax_amount
195
196 # store tax breakup for each item
197 tax.item_wise_tax_detail[item.item_code] = current_tax_amount
198
199 if tax.category:
200 # if just for valuation, do not add the tax amount in total
201 # hence, setting it as 0 for further steps
202 current_tax_amount = 0.0 if (tax.category == "Valuation") else current_tax_amount
203
204 current_tax_amount *= -1.0 if (tax.add_deduct_tax == "Deduct") else 1.0
205
206 # Calculate tax.total viz. grand total till that step
207 # note: grand_total_for_current_item contains the contribution of
208 # item's amount, previously applied tax and the current tax on that item
209 if i==0:
210 tax.grand_total_for_current_item = flt(item.amount +
211 current_tax_amount, self.precision("total", tax))
212
213 else:
214 tax.grand_total_for_current_item = \
215 flt(self.tax_doclist[i-1].grand_total_for_current_item +
216 current_tax_amount, self.precision("total", tax))
217
218 # in tax.total, accumulate grand total of each item
219 tax.total += tax.grand_total_for_current_item
220
221 def get_current_tax_amount(self, item, tax, item_tax_map):
222 tax_rate = self._get_tax_rate(tax, item_tax_map)
223 current_tax_amount = 0.0
224
225 if tax.charge_type == "Actual":
226 # distribute the tax amount proportionally to each item row
227 actual = flt(tax.rate, self.precision("tax_amount", tax))
228 current_tax_amount = (self.doc.net_total
229 and ((item.amount / self.doc.net_total) * actual)
230 or 0)
231 elif tax.charge_type == "On Net Total":
232 current_tax_amount = (tax_rate / 100.0) * item.amount
233 elif tax.charge_type == "On Previous Row Amount":
234 current_tax_amount = (tax_rate / 100.0) * \
235 self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
236 elif tax.charge_type == "On Previous Row Total":
237 current_tax_amount = (tax_rate / 100.0) * \
238 self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
239
240 return flt(current_tax_amount, self.precision("tax_amount", tax))
241
242 def _load_item_tax_rate(self, item_tax_rate):
243 return json.loads(item_tax_rate) if item_tax_rate else {}
244
245 def _get_tax_rate(self, tax, item_tax_map):
246 if item_tax_map.has_key(tax.account_head):
247 return flt(item_tax_map.get(tax.account_head), self.precision("rate", tax))
248 else:
249 return tax.rate
250
251 def _cleanup(self):
252 for tax in self.tax_doclist:
253 for fieldname in ("grand_total_for_current_item",
254 "tax_amount_for_current_item",
255 "tax_fraction_for_current_item",
256 "grand_total_fraction_for_current_item"):
257 if fieldname in tax.fields:
258 del tax.fields[fieldname]
259
260 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail)
261
262 def _set_in_company_currency(self, item, print_field, base_field):
263 """set values in base currency"""
264 item.fields[base_field] = flt((flt(item.fields[print_field],
265 self.precision(print_field, item)) * self.doc.conversion_rate),
266 self.precision(base_field, item))
Saurabh6f753182013-03-20 12:55:28 +0530267
Nabin Hait8c7234f2013-03-11 16:32:33 +0530268 def get_gl_dict(self, args, cancel=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530269 """this method populates the common properties of a gl entry record"""
Anand Doshi1cf73912013-03-15 13:42:31 +0530270 if cancel is None:
271 cancel = (self.doc.docstatus == 2)
272
Nabin Hait2df4d542013-01-29 11:34:39 +0530273 gl_dict = {
274 'company': self.doc.company,
275 'posting_date': self.doc.posting_date,
276 'voucher_type': self.doc.doctype,
277 'voucher_no': self.doc.name,
278 'aging_date': self.doc.fields.get("aging_date") or self.doc.posting_date,
279 'remarks': self.doc.remarks,
Anand Doshi1cf73912013-03-15 13:42:31 +0530280 'is_cancelled': cancel and "Yes" or "No",
Nabin Hait2df4d542013-01-29 11:34:39 +0530281 'fiscal_year': self.doc.fiscal_year,
282 'debit': 0,
283 'credit': 0,
284 'is_opening': self.doc.fields.get("is_opening") or "No",
285 }
286 gl_dict.update(args)
287 return gl_dict
Anand Doshia1d4b782013-02-26 18:09:47 +0530288
Anand Doshi613cb6a2013-02-06 17:33:46 +0530289 def clear_unallocated_advances(self, childtype, parentfield):
290 self.doclist.remove_items({"parentfield": parentfield, "allocated_amount": ["in", [0, None, ""]]})
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530291
Anand Doshi613cb6a2013-02-06 17:33:46 +0530292 webnotes.conn.sql("""delete from `tab%s` where parentfield=%s and parent = %s
293 and ifnull(allocated_amount, 0) = 0""" % (childtype, '%s', '%s'), (parentfield, self.doc.name))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530294
Anand Doshi613cb6a2013-02-06 17:33:46 +0530295 def get_advances(self, account_head, child_doctype, parentfield, dr_or_cr):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530296 res = webnotes.conn.sql("""select t1.name as jv_no, t1.remark,
297 t2.%s as amount, t2.name as jv_detail_no
298 from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
299 where t1.name = t2.parent and t2.account = %s and t2.is_advance = 'Yes'
300 and (t2.against_voucher is null or t2.against_voucher = '')
301 and (t2.against_invoice is null or t2.against_invoice = '')
302 and (t2.against_jv is null or t2.against_jv = '')
303 and t1.docstatus = 1 order by t1.posting_date""" %
304 (dr_or_cr, '%s'), account_head, as_dict=1)
305
306 self.doclist = self.doc.clear_table(self.doclist, parentfield)
307 for d in res:
Anand Doshi613cb6a2013-02-06 17:33:46 +0530308 self.doclist.append({
309 "doctype": child_doctype,
310 "parentfield": parentfield,
311 "journal_voucher": d.jv_no,
312 "jv_detail_no": d.jv_detail_no,
313 "remarks": d.remark,
314 "advance_amount": flt(d.amount),
315 "allocate_amount": 0
Anand Doshia1d4b782013-02-26 18:09:47 +0530316 })
Anand Doshia1d4b782013-02-26 18:09:47 +0530317
Nabin Hait0fc24542013-03-25 11:06:00 +0530318 def get_company_default(self, fieldname):
319 from accounts.utils import get_company_default
320 return get_company_default(self.doc.company, fieldname)
Anand Doshia1d4b782013-02-26 18:09:47 +0530321
322 @property
323 def stock_items(self):
324 if not hasattr(self, "_stock_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530325 self._stock_items = []
326 item_codes = list(set(item.item_code for item in
327 self.doclist.get({"parentfield": self.fname})))
328 if item_codes:
329 self._stock_items = [r[0] for r in webnotes.conn.sql("""select name
330 from `tabItem` where name in (%s) and is_stock_item='Yes'""" % \
331 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait80abad22013-03-19 18:18:52 +0530332
Anand Doshi4a7248e2013-02-27 18:10:30 +0530333 return self._stock_items
334
335 @property
336 def company_abbr(self):
337 if not hasattr(self, "_abbr"):
338 self._abbr = webnotes.conn.get_value("Company", self.doc.company, "abbr")
339
Anand Doshi21f4ea32013-05-10 18:08:32 +0530340 return self._abbr