blob: b3bf26af136071b9bbb7b2733feee899b9f17c08 [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 """
80 if not args.get("posting_date"):
81 args["posting_date"] = "1900-01-01"
82 if not args.get("posting_time"):
83 args["posting_time"] = "12:00"
84
85 sle = sql("""
86 select * from `tabStock Ledger Entry`
87 where item_code = %(item_code)s
88 and warehouse = %(warehouse)s
89 and ifnull(is_cancelled, 'No') = 'No'
90 and name != %(sle)s
91 and timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)
92 order by timestamp(posting_date, posting_time) desc, name desc
93 limit 1
94 """, args, as_dict=1)
95
96 return sle and sle[0] or {}
97
98def get_incoming_rate(args):
99 """Get Incoming Rate based on valuation method"""
100
101 in_rate = 0
102 if args.get("serial_no"):
103 in_rate = get_avg_purchase_rate(args.get("serial_no"))
104 elif args.get("bom_no"):
105 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
106 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
107 in_rate = result and flt(result[0][0]) or 0
108 else:
109 valuation_method = get_valuation_method(args.get("item_code"))
110 previous_sle = get_previous_sle(args)
111 if valuation_method == 'FIFO':
112 # get rate based on the last item value?
113 if args.get("qty"):
114 if not previous_sle:
115 return 0.0
116 stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
117 in_rate = stock_queue and get_fifo_rate(stock_queue) or 0
118 elif valuation_method == 'Moving Average':
119 in_rate = previous_sle.get('valuation_rate') or 0
120 return in_rate
121
122def get_avg_purchase_rate(serial_nos):
123 """get average value of serial numbers"""
124
125 serial_nos = get_valid_serial_nos(serial_nos)
126 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
127 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
128 tuple(serial_nos))[0][0])
129
130def get_valuation_method(item_code):
131 """get valuation method from item or default"""
132 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
133 if not val_method:
134 from webnotes.utils import get_defaults
135 val_method = get_defaults().get('valuation_method', 'FIFO')
136 return val_method
137
138def get_fifo_rate(stock_queue):
139 """get FIFO (average) Rate from Stack"""
140 if not stock_queue:
141 return 0.0
142
143 total = sum(f[0] for f in stock_queue)
144 return total and sum(f[0] * f[1] for f in stock_queue) / flt(total) or 0.0
145
146def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
147 """split serial nos, validate and return list of valid serial nos"""
148 # TODO: remove duplicates in client side
149 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
150
151 valid_serial_nos = []
152 for val in serial_nos:
153 if val:
154 val = val.strip()
155 if val in valid_serial_nos:
156 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
157 else:
158 valid_serial_nos.append(val)
159
160 if qty and len(valid_serial_nos) != abs(qty):
161 msgprint("Please enter serial nos for "
162 + cstr(abs(qty)) + " quantity against item code: " + item_code,
163 raise_exception=1)
164
165 return valid_serial_nos