blob: 5b716fcc530b95463a7431f8742b01e80b10625f [file] [log] [blame]
Rushabh Mehta3966f1d2012-02-23 12:35:32 +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
Anand Doshi486f9df2012-07-19 13:40:31 +053017from __future__ import unicode_literals
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053018import webnotes
Anand Doshi1dde46a2013-05-15 21:15:57 +053019from webnotes import msgprint, _
Anand Doshiee3d5cc2013-03-13 12:58:54 +053020from webnotes.utils import load_json, cstr, flt, now_datetime
Anand Doshi0fd99e72012-11-30 16:38:04 +053021from webnotes.model.doc import addchild
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053022
Anand Doshi756dca72013-01-15 18:39:21 +053023from webnotes.model.controller import DocListController
24
25class TransactionBase(DocListController):
Anand Doshiedc5f2e2013-04-26 17:21:49 +053026 def get_default_address_and_contact(self, party_type):
27 """get a dict of default field values of address and contact for a given party type
28 party_type can be one of: customer, supplier"""
29 ret = {}
30
31 # {customer: self.doc.fields.get("customer")}
32 args = {party_type: self.doc.fields.get(party_type)}
33
34 address_text, address_name = self.get_address_text(**args)
35 ret.update({
36 # customer_address
37 (party_type + "_address"): address_name,
38 "address_display": address_text
39 })
40 ret.update(self.get_contact_text(**args))
41 return ret
42
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053043 # Get Customer Default Primary Address - first load
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053044 def get_default_customer_address(self, args=''):
45 address_text, address_name = self.get_address_text(customer=self.doc.customer)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053046 self.doc.customer_address = address_name or ''
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053047 self.doc.address_display = address_text or ''
Anand Doshiae30e012012-10-26 15:01:22 +053048 self.doc.fields.update(self.get_contact_text(customer=self.doc.customer))
Nabin Hait239e7902012-04-20 10:25:03 +053049
Nabin Hait84d73102012-02-14 15:13:21 +053050 if args != 'onload':
Nabin Hait239e7902012-04-20 10:25:03 +053051 self.get_customer_details(self.doc.customer)
Nabin Hait84d73102012-02-14 15:13:21 +053052 self.get_sales_person(self.doc.customer)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053053
54 # Get Customer Default Shipping Address - first load
55 # -----------------------
56 def get_default_customer_shipping_address(self, args=''):
57 address_text, address_name = self.get_address_text(customer=self.doc.customer,is_shipping_address=1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053058 self.doc.customer_address = address_name or ''
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053059 self.doc.address_display = address_text or ''
Anand Doshiae30e012012-10-26 15:01:22 +053060 self.doc.fields.update(self.get_contact_text(customer=self.doc.customer))
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053061
Nabin Hait84d73102012-02-14 15:13:21 +053062 if self.doc.doctype != 'Quotation' and args != 'onload':
Nabin Hait239e7902012-04-20 10:25:03 +053063 self.get_customer_details(self.doc.customer)
Nabin Hait84d73102012-02-14 15:13:21 +053064 self.get_sales_person(self.doc.customer)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053065
66 # Get Customer Address
67 # -----------------------
68 def get_customer_address(self, args):
69 args = load_json(args)
70 address_text, address_name = self.get_address_text(address_name=args['address'])
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053071 ret = {
72 'customer_address' : address_name,
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053073 'address_display' : address_text,
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053074 }
Anand Doshiae30e012012-10-26 15:01:22 +053075
76 ret.update(self.get_contact_text(contact_name=args['contact']))
77
Nabin Hait06c4de82011-08-16 16:38:11 +053078 return ret
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053079
80 # Get Address Text
81 # -----------------------
82 def get_address_text(self, customer=None, address_name=None, supplier=None, is_shipping_address=None):
83 if customer:
84 cond = customer and 'customer="%s"' % customer or 'name="%s"' % address_name
85 elif supplier:
86 cond = supplier and 'supplier="%s"' % supplier or 'name="%s"' % address_name
87 else:
88 cond = 'name="%s"' % address_name
89
90 if is_shipping_address:
Nabin Hait7f599132012-09-26 13:10:37 +053091 details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone, fax from `tabAddress` where %s and docstatus != 2 order by is_shipping_address desc, is_primary_address desc limit 1" % cond, as_dict = 1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053092 else:
Nabin Hait65353652012-03-21 17:07:42 +053093 details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone, fax from `tabAddress` where %s and docstatus != 2 order by is_primary_address desc limit 1" % cond, as_dict = 1)
Anand Doshiedc5f2e2013-04-26 17:21:49 +053094
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053095 extract = lambda x: details and details[0] and details[0].get(x,'') or ''
Anand Doshi3e157ec2013-03-01 17:55:37 +053096 address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),('\n','state'),(' ','pincode'),('\n','country'),('\nPhone: ','phone'),('\nFax: ', 'fax')]
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +053097 address_display = ''.join([a[0]+extract(a[1]) for a in address_fields if extract(a[1])])
98 if address_display.startswith('\n'): address_display = address_display[1:]
99
100 address_name = details and details[0]['name'] or ''
101 return address_display, address_name
102
103 # Get Contact Text
104 # -----------------------
105 def get_contact_text(self, customer=None, contact_name=None, supplier=None):
106 if customer:
107 cond = customer and 'customer="%s"' % customer or 'name="%s"' % contact_name
108 elif supplier:
109 cond = supplier and 'supplier="%s"' % supplier or 'name="%s"' % contact_name
110 else:
111 cond = 'name="%s"' % contact_name
112
Anand Doshi74d1b652012-01-27 12:25:09 +0530113 details = webnotes.conn.sql("select name, first_name, last_name, email_id, phone, mobile_no, department, designation from `tabContact` where %s and docstatus != 2 order by is_primary_contact desc limit 1" % cond, as_dict = 1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530114
115 extract = lambda x: details and details[0] and details[0].get(x,'') or ''
Anand Doshi97bd3662012-01-17 14:22:09 +0530116 contact_fields = [('','first_name'),(' ','last_name')]
117 contact_display = ''.join([a[0]+cstr(extract(a[1])) for a in contact_fields if extract(a[1])])
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530118 if contact_display.startswith('\n'): contact_display = contact_display[1:]
119
Anand Doshiae30e012012-10-26 15:01:22 +0530120 return {
121 "contact_display": contact_display,
122 "contact_person": details and details[0]["name"] or "",
123 "contact_email": details and details[0]["email_id"] or "",
124 "contact_mobile": details and details[0]["mobile_no"] or "",
125 "contact_designation": details and details[0]["designation"] or "",
126 "contact_department": details and details[0]["department"] or "",
127 }
128
Anand Doshif2f5c942012-07-18 20:13:52 +0530129 def get_customer_details(self, name):
130 """
131 Get customer details like name, group, territory
132 and other such defaults
133 """
134 customer_details = webnotes.conn.sql("""\
135 select
136 customer_name, customer_group, territory,
137 default_sales_partner, default_commission_rate, default_currency,
138 default_price_list
139 from `tabCustomer`
140 where name = %s and docstatus < 2""", name, as_dict=1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530141 if customer_details:
Anand Doshif2f5c942012-07-18 20:13:52 +0530142 for f in ['customer_name', 'customer_group', 'territory']:
143 self.doc.fields[f] = customer_details[0][f] or self.doc.fields.get(f)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530144
Anand Doshif2f5c942012-07-18 20:13:52 +0530145 # fields prepended with default in Customer doctype
146 for f in ['sales_partner', 'commission_rate', 'currency']:
147 self.doc.fields[f] = customer_details[0]["default_%s" % f] or self.doc.fields.get(f)
148
149 # optionally fetch default price list from Customer Group
150 self.doc.price_list_name = (customer_details[0]['default_price_list']
151 or webnotes.conn.get_value('Customer Group', self.doc.customer_group,
152 'default_price_list')
153 or self.doc.fields.get('price_list_name'))
154
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530155 # Get Customer Shipping Address
156 # -----------------------
157 def get_shipping_address(self, name):
Nabin Hait7f599132012-09-26 13:10:37 +0530158 details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where customer = '%s' and docstatus != 2 order by is_shipping_address desc, is_primary_address desc limit 1" %(name), as_dict = 1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530159
160 extract = lambda x: details and details[0] and details[0].get(x,'') or ''
161 address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','phone')]
162 address_display = ''.join([a[0]+extract(a[1]) for a in address_fields if extract(a[1])])
163 if address_display.startswith('\n'): address_display = address_display[1:]
164
165 ret = {
166 'shipping_address_name' : details and details[0]['name'] or '',
167 'shipping_address' : address_display
168 }
Nabin Hait06c4de82011-08-16 16:38:11 +0530169 return ret
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530170
171 # Get Lead Details
172 # -----------------------
173 def get_lead_details(self, name):
Anand Doshib7af3d02013-03-07 12:17:52 +0530174 details = webnotes.conn.sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, phone, mobile_no, email_id, company_name from `tabLead` where name = '%s'" %(name), as_dict = 1)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530175
176 extract = lambda x: details and details[0] and details[0].get(x,'') or ''
177 address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','contact_no')]
178 address_display = ''.join([a[0]+extract(a[1]) for a in address_fields if extract(a[1])])
179 if address_display.startswith('\n'): address_display = address_display[1:]
180
181 ret = {
Nabin Hait1e3fc882013-04-02 18:13:20 +0530182 'contact_display' : extract('lead_name'),
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530183 'address_display' : address_display,
184 'territory' : extract('territory'),
185 'contact_mobile' : extract('mobile_no'),
Nabin Hait9ff92362012-03-20 16:44:15 +0530186 'contact_email' : extract('email_id'),
Nabin Hait1e3fc882013-04-02 18:13:20 +0530187 'customer_name' : extract('company_name') or extract('lead_name')
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530188 }
Nabin Hait06c4de82011-08-16 16:38:11 +0530189 return ret
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530190
191
192 # Get Supplier Default Primary Address - first load
193 # -----------------------
194 def get_default_supplier_address(self, args):
Anand Doshi923d41d2013-05-28 17:23:36 +0530195 if isinstance(args, basestring):
196 args = load_json(args)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530197 address_text, address_name = self.get_address_text(supplier=args['supplier'])
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530198 ret = {
199 'supplier_address' : address_name,
200 'address_display' : address_text,
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530201 }
Anand Doshiae30e012012-10-26 15:01:22 +0530202 ret.update(self.get_contact_text(supplier=args['supplier']))
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530203 ret.update(self.get_supplier_details(args['supplier']))
Nabin Hait06c4de82011-08-16 16:38:11 +0530204 return ret
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530205
206 # Get Supplier Address
207 # -----------------------
208 def get_supplier_address(self, args):
209 args = load_json(args)
210 address_text, address_name = self.get_address_text(address_name=args['address'])
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530211 ret = {
212 'supplier_address' : address_name,
Anand Doshif2f5c942012-07-18 20:13:52 +0530213 'address_display' : address_text,
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530214 }
Anand Doshiae30e012012-10-26 15:01:22 +0530215 ret.update(self.get_contact_text(contact_name=args['contact']))
Nabin Hait06c4de82011-08-16 16:38:11 +0530216 return ret
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530217
218 # Get Supplier Details
219 # -----------------------
Anand Doshif2f5c942012-07-18 20:13:52 +0530220 def get_supplier_details(self, name):
221 supplier_details = webnotes.conn.sql("""\
222 select supplier_name, default_currency
223 from `tabSupplier`
224 where name = %s and docstatus < 2""", name, as_dict=1)
225 if supplier_details:
226 return {
227 'supplier_name': (supplier_details[0]['supplier_name']
228 or self.doc.fields.get('supplier_name')),
229 'currency': (supplier_details[0]['default_currency']
230 or self.doc.fields.get('currency')),
231 }
232 else:
233 return {}
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530234
235 # Get Sales Person Details of Customer
236 # ------------------------------------
237 def get_sales_person(self, name):
Anand Doshi8ae5ba92012-06-25 20:05:35 +0530238 self.doclist = self.doc.clear_table(self.doclist,'sales_team')
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530239 idx = 0
Anand Doshi74d1b652012-01-27 12:25:09 +0530240 for d in webnotes.conn.sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % name):
Anand Doshif5d90ab2012-12-24 17:02:38 +0530241 ch = addchild(self.doc, 'sales_team', 'Sales Team', self.doclist)
Pratik Vyasc1e6e4c2011-06-08 14:37:15 +0530242 ch.sales_person = d and cstr(d[0]) or ''
243 ch.allocated_percentage = d and flt(d[1]) or 0
244 ch.allocated_amount = d and flt(d[2]) or 0
245 ch.incentives = d and flt(d[3]) or 0
246 ch.idx = idx
247 idx += 1
Nabin Hait41cc3272012-04-30 14:36:18 +0530248
Rushabh Mehta35c017a2012-11-30 10:57:28 +0530249 def load_notification_message(self):
250 dt = self.doc.doctype.lower().replace(" ", "_")
251 if int(webnotes.conn.get_value("Notification Control", None, dt) or 0):
252 self.doc.fields["__notification_message"] = \
253 webnotes.conn.get_value("Notification Control", None, dt + "_message")
254
Rushabh Mehtac4e7b682012-11-26 18:18:10 +0530255 def add_communication_list(self):
256 # remove communications if present
257 self.doclist = webnotes.doclist(self.doclist).get({
258 "doctype": ["!=", "Communcation"]})
259
260 comm_list = webnotes.conn.sql("""select * from tabCommunication
261 where %s=%s order by modified desc limit 20""" \
262 % (self.doc.doctype.replace(" ", "_").lower(), "%s"),
263 self.doc.name, as_dict=1)
264
265 [d.update({"doctype":"Communication"}) for d in comm_list]
266
267 self.doclist.extend(webnotes.doclist([webnotes.doc(fielddata=d) \
Anand Doshiee3d5cc2013-03-13 12:58:54 +0530268 for d in comm_list]))
269
270 def validate_posting_time(self):
271 if not self.doc.posting_time:
Anand Doshiacec0222013-03-26 12:33:43 +0530272 self.doc.posting_time = now_datetime().strftime('%H:%M:%S')
Anand Doshi1dde46a2013-05-15 21:15:57 +0530273
274def validate_conversion_rate(currency, conversion_rate, conversion_rate_label, company):
275 """common validation for currency and price list currency"""
276 if conversion_rate == 0:
277 msgprint(conversion_rate_label + _(' cannot be 0'), raise_exception=True)
278
279 company_currency = webnotes.conn.get_value("Company", company, "default_currency")
280
281 # parenthesis for 'OR' are necessary as we want it to evaluate as
282 # mandatory valid condition and (1st optional valid condition
283 # or 2nd optional valid condition)
284 valid_conversion_rate = (conversion_rate and
285 ((currency == company_currency and conversion_rate == 1.00)
286 or (currency != company_currency and conversion_rate != 1.00)))
287
288 if not valid_conversion_rate:
289 msgprint(_('Please enter valid ') + conversion_rate_label + (': ')
290 + ("1 %s = [?] %s" % (currency, company_currency)),
291 raise_exception=True)
292
293def validate_item_fetch(args, item):
294 from stock.utils import validate_end_of_life
295 validate_end_of_life(item.name, item.end_of_life)
296
297 # validate company
298 if not args.company:
299 msgprint(_("Please specify Company"), raise_exception=True)
300
Anand Doshif3096132013-05-21 19:35:06 +0530301def validate_currency(args, item, meta=None):
Anand Doshifc777182013-05-27 19:29:07 +0530302 from webnotes.model.meta import get_field_precision
Anand Doshif3096132013-05-21 19:35:06 +0530303 if not meta:
304 meta = webnotes.get_doctype(args.doctype)
Anand Doshifc777182013-05-27 19:29:07 +0530305
Anand Doshif3096132013-05-21 19:35:06 +0530306 # validate conversion rate
Anand Doshi1dde46a2013-05-15 21:15:57 +0530307 if meta.get_field("currency"):
Anand Doshi1dde46a2013-05-15 21:15:57 +0530308 validate_conversion_rate(args.currency, args.conversion_rate,
309 meta.get_label("conversion_rate"), args.company)
Anand Doshifc777182013-05-27 19:29:07 +0530310
311 # round it
312 args.conversion_rate = flt(args.conversion_rate,
313 get_field_precision(meta.get_field("conversion_rate"), args))
Anand Doshi1dde46a2013-05-15 21:15:57 +0530314
Anand Doshif3096132013-05-21 19:35:06 +0530315 # validate price list conversion rate
316 if meta.get_field("price_list_currency") and args.price_list_name and \
317 args.price_list_currency:
318 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
Anand Doshifc777182013-05-27 19:29:07 +0530319 meta.get_label("plc_conversion_rate"), args.company)
320
321 # round it
322 args.plc_conversion_rate = flt(args.plc_conversion_rate,
323 get_field_precision(meta.get_field("plc_conversion_rate"), args))
324
325