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