blob: 2c0eaefd30e006389e9258ce3a58ab7c0d26177b [file] [log] [blame]
Nabin Hait9d0f6362013-01-07 18:51:11 +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
17import webnotes
18from webnotes import msgprint, _
19import json
20from webnotes.utils import flt
21
22def validate_end_of_life(item_code, end_of_life=None, verbose=1):
23 if not end_of_life:
24 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
25
26 from webnotes.utils import getdate, now_datetime, formatdate
27 if end_of_life and getdate(end_of_life) > now_datetime().date():
28 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
29 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
30 "in Item master") % {
31 "item_code": item_code,
32 "date": formatdate(end_of_life),
33 "end_of_life_label": webnotes.get_label("Item", "end_of_life")
34 }
35
36 _msgprint(msg, verbose)
37
38def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
39 if not is_stock_item:
40 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
41
42 if is_stock_item != "Yes":
43 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
44 "item_code": item_code,
45 }
46
47 _msgprint(msg, verbose)
48
49def validate_cancelled_item(item_code, docstatus=None, verbose=1):
50 if docstatus is None:
51 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
52
53 if docstatus == 2:
54 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
55 "item_code": item_code,
56 }
57
58 _msgprint(msg, verbose)
59
60def _msgprint(msg, verbose):
61 if verbose:
62 msgprint(msg, raise_exception=True)
63 else:
64 raise webnotes.ValidationError, msg
65
66def get_previous_sle(args):
67 """
68 get the last sle on or before the current time-bucket,
69 to get actual qty before transaction, this function
70 is called from various transaction like stock entry, reco etc
Nabin Hait902e8602013-01-08 18:29:24 +053071
72 args = {
73 "item_code": "ABC",
74 "warehouse": "XYZ",
75 "posting_date": "2012-12-12",
76 "posting_time": "12:00",
77 "sle": "name of reference Stock Ledger Entry"
78 }
Nabin Hait9d0f6362013-01-07 18:51:11 +053079 """
Nabin Hait26d46552013-01-09 15:23:05 +053080 if not args.get("posting_date"): args["posting_date"] = "1900-01-01"
81 if not args.get("posting_time"): args["posting_time"] = "12:00"
82 if not args.get("sle"): args["sle"] = ""
Nabin Hait9d0f6362013-01-07 18:51:11 +053083
Nabin Hait26d46552013-01-09 15:23:05 +053084 sle = webnotes.conn.sql("""
Nabin Hait9d0f6362013-01-07 18:51:11 +053085 select * from `tabStock Ledger Entry`
86 where item_code = %(item_code)s
87 and warehouse = %(warehouse)s
88 and ifnull(is_cancelled, 'No') = 'No'
89 and name != %(sle)s
90 and timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)
91 order by timestamp(posting_date, posting_time) desc, name desc
92 limit 1
93 """, args, as_dict=1)
94
95 return sle and sle[0] or {}
96
97def get_incoming_rate(args):
98 """Get Incoming Rate based on valuation method"""
99
100 in_rate = 0
101 if args.get("serial_no"):
102 in_rate = get_avg_purchase_rate(args.get("serial_no"))
103 elif args.get("bom_no"):
104 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
105 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
106 in_rate = result and flt(result[0][0]) or 0
107 else:
108 valuation_method = get_valuation_method(args.get("item_code"))
109 previous_sle = get_previous_sle(args)
110 if valuation_method == 'FIFO':
111 # get rate based on the last item value?
112 if args.get("qty"):
113 if not previous_sle:
114 return 0.0
115 stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
116 in_rate = stock_queue and get_fifo_rate(stock_queue) or 0
117 elif valuation_method == 'Moving Average':
118 in_rate = previous_sle.get('valuation_rate') or 0
119 return in_rate
120
121def get_avg_purchase_rate(serial_nos):
122 """get average value of serial numbers"""
123
124 serial_nos = get_valid_serial_nos(serial_nos)
125 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
126 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
127 tuple(serial_nos))[0][0])
128
129def get_valuation_method(item_code):
130 """get valuation method from item or default"""
131 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
132 if not val_method:
133 from webnotes.utils import get_defaults
134 val_method = get_defaults().get('valuation_method', 'FIFO')
135 return val_method
136
137def get_fifo_rate(stock_queue):
138 """get FIFO (average) Rate from Stack"""
139 if not stock_queue:
140 return 0.0
141
142 total = sum(f[0] for f in stock_queue)
143 return total and sum(f[0] * f[1] for f in stock_queue) / flt(total) or 0.0
144
145def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
146 """split serial nos, validate and return list of valid serial nos"""
147 # TODO: remove duplicates in client side
148 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
149
150 valid_serial_nos = []
151 for val in serial_nos:
152 if val:
153 val = val.strip()
154 if val in valid_serial_nos:
155 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
156 else:
157 valid_serial_nos.append(val)
158
159 if qty and len(valid_serial_nos) != abs(qty):
160 msgprint("Please enter serial nos for "
161 + cstr(abs(qty)) + " quantity against item code: " + item_code,
162 raise_exception=1)
163
164 return valid_serial_nos