Ejemplo n.º 1
	def make_gl_entries(self, doc, doclist, cancel=0, adv_adj = 0, use_mapper='', merge_entries = 1, update_outstanding='Yes'):
		self.entries = []
		# get entries
		le_map_list = webnotes.conn.sql("select * from `tabGL Mapper Detail` where parent = %s", use_mapper or doc.doctype, as_dict=1)
		self.td, self.tc = 0.0, 0.0
		for le_map in le_map_list:
			if le_map['table_field']:
				for d in getlist(doclist,le_map['table_field']):
					# purchase_tax_details is the table of other charges in purchase cycle
					if le_map['table_field'] != 'purchase_tax_details' or (le_map['table_field'] == 'purchase_tax_details' and d.fields.get('category') != 'For Valuation'):
						self.make_single_entry(doc,d,le_map,cancel, merge_entries)
				self.make_single_entry(None,doc,le_map,cancel, merge_entries)

		# save entries
		self.save_entries(cancel, adv_adj, update_outstanding)

		# check total debit / credit
		# Due to old wrong entries (total debit != total credit) some voucher could be cancelled
		if abs(self.td - self.tc) > 0.001 and not cancel:
			msgprint("Debit and Credit not equal for this voucher: Diff (Debit) is %s" % (self.td-self.tc))
			raise Exception

		# set as cancelled
		if cancel:
			vt, vn = self.get_val(le_map['voucher_type'],	doc, doc), self.get_val(le_map['voucher_no'],	doc, doc)
			webnotes.conn.sql("update `tabGL Entry` set is_cancelled='Yes' where voucher_type=%s and voucher_no=%s", (vt, vn))
Ejemplo n.º 2
def check_if_expired():
	"""check if account is expired. If expired, do not allow login"""
	import conf
	# check if expires_on is specified
	if not hasattr(conf, 'expires_on'): return
	# check if expired
	from datetime import datetime, date
	expires_on = datetime.strptime(conf.expires_on, '%Y-%m-%d').date()
	if date.today() <= expires_on: return
	# if expired, stop user from logging in
	from webnotes.utils import formatdate
	msg = """Oops! Your subscription expired on <b>%s</b>.<br>""" % formatdate(conf.expires_on)
	if 'System Manager' in webnotes.user.get_roles():
		msg += """Just drop in a mail at <b>[email protected]</b> and
			we will guide you to get your account re-activated."""
		msg += """Just ask your System Manager to drop in a mail at <b>[email protected]</b> and
		we will guide him to get your account re-activated."""
	webnotes.response['message'] = 'Account Expired'
	raise webnotes.AuthenticationError
Ejemplo n.º 3
	def get_balance(self):
		if not getlist(self.doclist,'entries'):
			msgprint("Please enter atleast 1 entry in 'GL Entries' table")
			flag, self.doc.total_debit, self.doc.total_credit = 0, 0, 0
			diff = flt(self.doc.difference, 2)
			# If any row without amount, set the diff on that row
			for d in getlist(self.doclist,'entries'):
				if not d.credit and not d.debit and diff != 0:
					if diff>0:
						d.credit = diff
					elif diff<0:
						d.debit = diff
					flag = 1
			# Set the diff in a new row
			if flag == 0 and diff != 0:
				jd = addchild(self.doc, 'entries', 'Journal Voucher Detail', self.doclist)
				if diff>0:
					jd.credit = abs(diff)
				elif diff<0:
					jd.debit = abs(diff)
			# Set the total debit, total credit and difference
			for d in getlist(self.doclist,'entries'):
				self.doc.total_debit += flt(d.debit, 2)
				self.doc.total_credit += flt(d.credit, 2)

			self.doc.difference = flt(self.doc.total_debit, 2) - flt(self.doc.total_credit, 2)
Ejemplo n.º 4
	def on_update(self):
		# Set default warehouse from pos setting
		if cint(self.doc.is_pos) == 1:
			if cint(self.doc.update_stock) == 1:
				w = self.get_warehouse()
				if w:
					for d in getlist(self.doclist, 'entries'):
						if not d.warehouse:
							d.warehouse = cstr(w)
				self.doclist = self.doc.clear_table(self.doclist, 'packing_details')

			if flt(self.doc.paid_amount) == 0:
				if self.doc.cash_bank_account: 
					webnotes.conn.set(self.doc, 'paid_amount', 
						(flt(self.doc.grand_total) - flt(self.doc.write_off_amount)))
					# show message that the amount is not paid
					webnotes.msgprint("Note: Payment Entry will not be created since 'Cash/Bank Account' was not specified.")

			self.doclist = self.doc.clear_table(self.doclist, 'packing_details')

		webnotes.conn.set(self.doc, 'outstanding_amount', 
			flt(self.doc.grand_total) - flt(self.doc.total_advance) - 
			flt(self.doc.paid_amount) - flt(self.doc.write_off_amount))
Ejemplo n.º 5
def execute_cmd(cmd):
	"""execute a request as python module"""
	method = get_method(cmd)

	# check if whitelisted
	if webnotes.session['user'] == 'Guest':
		if (method not in webnotes.guest_methods):
			webnotes.response['403'] = 1
			raise Exception, 'Not Allowed, %s' % str(method)
		if not method in webnotes.whitelisted:
			webnotes.response['403'] = 1
			webnotes.msgprint('Not Allowed, %s' % str(method))
			raise Exception, 'Not Allowed, %s' % str(method)
	if not webnotes.conn.in_transaction:

	if 'arg' in webnotes.form_dict:
		# direct method call
		ret = method(webnotes.form_dict.get('arg'))
		ret = method()

	# returns with a message
	if ret:
		webnotes.response['message'] = ret

	# update session

	if webnotes.conn.in_transaction:
Ejemplo n.º 6
	def check_mandatory(self):
		""" Check mandatory fields """		
		if not self.doc.from_pr_date or not self.doc.to_pr_date:
			msgprint("Please enter From and To PR Date", raise_exception=1)

		if not self.doc.currency:
			msgprint("Please enter Currency.", raise_exception=1)
Ejemplo n.º 7
	def validate_proj_cust(self):
		"""check for does customer belong to same project as entered.."""
		if self.doc.project_name and self.doc.customer:
			res = webnotes.conn.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
			if not res:
				msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in that project."%(self.doc.customer,self.doc.project_name))
				raise Exception
Ejemplo n.º 8
	def validate_time_logs_are_submitted(self):
		for d in self.doclist.get({"doctype":"Sales Invoice Item"}):
			if d.time_log_batch:
				status = webnotes.conn.get_value("Time Log Batch", d.time_log_batch, "status")
				if status!="Submitted":
					webnotes.msgprint(_("Time Log Batch status must be 'Submitted'") + ":" + d.time_log_batch,
Ejemplo n.º 9
def get_bank_cash_account(mode_of_payment):
	val = webnotes.conn.get_value("Mode of Payment", mode_of_payment, "default_account")
	if not val:
		webnotes.msgprint("Default Bank / Cash Account not set in Mode of Payment: %s. Please add a Default Account in Mode of Payment master." % mode_of_payment)
	return {
		"cash_bank_account": val
Ejemplo n.º 10
def update_add_node(doctype, name, parent, parent_field):
		insert a new node
	from webnotes.utils import now
	n = now()

	# get the last sibling of the parent
	if parent:
		right = webnotes.conn.sql("select rgt from `tab%s` where name='%s'" % (doctype, parent))[0][0]
	else: # root
		right = webnotes.conn.sql("select ifnull(max(rgt),0)+1 from `tab%s` where ifnull(`%s`,'') =''" % (doctype, parent_field))[0][0]
	right = right or 1
	# update all on the right
	webnotes.conn.sql("update `tab%s` set rgt = rgt+2, modified='%s' where rgt >= %s" %(doctype,n,right))
	webnotes.conn.sql("update `tab%s` set lft = lft+2, modified='%s' where lft >= %s" %(doctype,n,right))
	# update index of new node
	if webnotes.conn.sql("select * from `tab%s` where lft=%s or rgt=%s"% (doctype, right, right+1)):
		webnotes.msgprint("Nested set error. Please send mail to support")
		raise Exception

	webnotes.conn.sql("update `tab%s` set lft=%s, rgt=%s, modified='%s' where name='%s'" % (doctype,right,right+1,n,name))
	return right
Ejemplo n.º 11
	def on_trash(self):
		parent = self.doc.fields[self.nsm_parent_field]
		if not parent:
			msgprint(_("Root ") + self.doc.doctype + _(" cannot be deleted."), raise_exception=1)

		parent = ""
Ejemplo n.º 12
	def do_stock_reco(self, is_submit = 1):
			Make stock entry of qty diff, calculate incoming rate to maintain valuation rate.
			If no qty diff, but diff in valuation rate, make (+1,-1) entry to update valuation
		for row in self.data:
			# Get qty as per system
			sys_stock = self.get_system_stock(row[0],row[1])
			# Diff between file and system
			qty_diff = row[2] != '~' and flt(row[2]) - flt(sys_stock['actual_qty']) or 0
			rate_diff = row[3] != '~' and flt(row[3]) - flt(sys_stock['val_rate']) or 0

			# Make sl entry
			if qty_diff:
				self.make_sl_entry(is_submit, row, qty_diff, sys_stock)
			elif rate_diff:
				self.make_sl_entry(is_submit, row, 1, sys_stock)
				sys_stock['val_rate'] = row[3]
				sys_stock['actual_qty'] += 1
				self.make_sl_entry(is_submit, row, -1, sys_stock)

			if is_submit == 1:
				self.add_data_in_CSV(qty_diff, rate_diff)
			msgprint("Stock Reconciliation Completed Successfully...")
Ejemplo n.º 13
	def on_submit(self):
		if self.doc.status != "Approved":
			webnotes.msgprint("""Only Leave Applications with status 'Approved' can be Submitted.""",

		# notify leave applier about approval
Ejemplo n.º 14
	def update_against_document_in_jv(self, obj, table_field_name, against_document_no, against_document_doctype, account_head, dr_or_cr,doctype):
		for d in getlist(obj.doclist, table_field_name):
			self.validate_jv_entry(d, account_head, dr_or_cr)
			if flt(d.advance_amount) == flt(d.allocated_amount):
				# cancel JV
				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children=1)
				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj =1)

				# update ref in JV Detail
				webnotes.conn.sql("update `tabJournal Voucher Detail` set %s = '%s' where name = '%s'" % (doctype=='Purchase Invoice' and 'against_voucher' or 'against_invoice', cstr(against_document_no), d.jv_detail_no))

				# re-submit JV
				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj =1)

			elif flt(d.advance_amount) > flt(d.allocated_amount):
				# cancel JV
				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children=1)
				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj = 1)

				# add extra entries
				self.add_extra_entry(jv_obj, d.journal_voucher, d.jv_detail_no, flt(d.allocated_amount), account_head, doctype, dr_or_cr, against_document_no)

				# re-submit JV
				jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
				get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj = 1)
				msgprint("Allocation amount cannot be greater than advance amount")
				raise Exception
Ejemplo n.º 15
	def send(self):
			* Execute get method
			* Send email to recipients
		if not self.doc.recipient_list: return

		self.sending = True
		result, email_body = self.get()
		recipient_list = self.doc.recipient_list.split("\n")

		# before sending, check if user is disabled or not
		# do not send if disabled
		profile_list = webnotes.conn.sql("SELECT name, enabled FROM tabProfile", as_dict=1)
		for profile in profile_list:
			if profile['name'] in recipient_list and profile['enabled'] == 0:
				del recipient_list[recipient_list.index(profile['name'])]

		from webnotes.utils.email_lib import sendmail
			#webnotes.msgprint('in send')
				sender='[email protected]',
				reply_to='[email protected]',
				subject=self.doc.frequency + ' Digest',
		except Exception, e:
			webnotes.msgprint('There was a problem in sending your email. Please contact [email protected]')
Ejemplo n.º 16
 def set_last_contact_date(self):
   if self.doc.contact_date_ref and self.doc.contact_date_ref != self.doc.contact_date:
     if getdate(self.doc.contact_date_ref) < getdate(self.doc.contact_date):
       msgprint("Contact Date Cannot be before Last Contact Date")
       raise Exception
Ejemplo n.º 17
	def validate_order_type(self):
		valid_types = ["Sales", "Maintenance", "Shopping Cart"]
		if not self.doc.order_type:
			self.doc.order_type = "Sales"
		elif self.doc.order_type not in valid_types:
			msgprint(_(self.meta.get_label("order_type")) + " " + 
				_("must be one of") + ": " + comma_or(valid_types), raise_exception=True)
Ejemplo n.º 18
 def validate_fiscal_year(self):
   fy=sql("select year_start_date from `tabFiscal Year` where name='%s'"%self.doc.fiscal_year)
   ysd=fy and fy[0][0] or ""
   if str(self.doc.transaction_date) < str(ysd) or str(self.doc.transaction_date) > str(yed):
     msgprint("Enquiry Date is not within the Fiscal Year selected")
     raise Exception    
Ejemplo n.º 19
def validate_item_fetch(args, item):
	from stock.utils import validate_end_of_life
	validate_end_of_life(item.name, item.end_of_life)
	# validate company
	if not args.company:
		msgprint(_("Please specify Company"), raise_exception=True)
Ejemplo n.º 20
 def on_cancel(self):
   chk = sql("select t1.name from `tabQuotation` t1, `tabQuotation Detail` t2 where t2.parent = t1.name and t1.docstatus=1 and (t1.status!='Order Lost' and t1.status!='Cancelled') and t2.prevdoc_docname = %s",self.doc.name)
   if chk:
     msgprint("Quotation No. "+cstr(chk[0][0])+" is submitted against this Enquiry. Thus can not be cancelled.")
     raise Exception
     set(self.doc, 'status', 'Cancelled')
Ejemplo n.º 21
	def validate_pos(self):
		if not self.doc.cash_bank_account and flt(self.doc.paid_amount):
			msgprint("Cash/Bank Account is mandatory for POS, for making payment entry")
			raise Exception
		if (flt(self.doc.paid_amount) + flt(self.doc.write_off_amount) - round(flt(self.doc.grand_total), 2))>0.001:
			msgprint("(Paid amount + Write Off Amount) can not be greater than Grand Total")
			raise Exception
Ejemplo n.º 22
	def validate(self):
		if self.doc.standard=="Yes" and webnotes.session.user != "Administrator":
			webnotes.msgprint("Standard Print Format cannot be updated.", raise_exception=1)
		# old_doc_type is required for clearing item cache
		self.old_doc_type = webnotes.conn.get_value('Print Format',
				self.doc.name, 'doc_type')
Ejemplo n.º 23
    def validate_first_entry(self, obj):
        if obj.doc.doctype == "Purchase Invoice":
            supp_acc = obj.doc.credit_to
        elif obj.doc.doctype == "Journal Voucher":
            supp_acc = obj.doc.supplier_account

        if obj.doc.ded_amount:
            # first pv
            first_pv = sql(
                "select posting_date from `tabPurchase Invoice` where credit_to = '%s' and docstatus = 1 and tds_category = '%s' and fiscal_year = '%s' and tds_applicable = 'Yes' and (ded_amount != 0 or ded_amount is not null) order by posting_date asc limit 1"
                % (supp_acc, obj.doc.tds_category, obj.doc.fiscal_year)
            first_pv_date = first_pv and first_pv[0][0] or ""
            # first jv
            first_jv = sql(
                "select posting_date from `tabJournal Voucher` where supplier_account = '%s'and docstatus = 1 and tds_category = '%s' and fiscal_year = '%s' and tds_applicable = 'Yes' and (ded_amount != 0 or ded_amount is not null) order by posting_date asc limit 1"
                % (supp_acc, obj.doc.tds_category, obj.doc.fiscal_year)
            first_jv_date = first_jv and first_jv[0][0] or ""

            # first tds voucher date
            first_tds_date = ""
            if first_pv_date and first_jv_date:
                first_tds_date = first_pv_date < first_jv_date and first_pv_date or first_jv_date
            elif first_pv_date:
                first_tds_date = first_pv_date
            elif first_jv_date:
                first_tds_date = first_jv_date

            if first_tds_date and getdate(obj.doc.posting_date) < first_tds_date:
                    "First tds voucher for this category has been made already. Hence payable voucher cannot be made before posting date of first tds voucher "
                raise Exception
Ejemplo n.º 24
	def get_payables_group(self):
		g = sql("select payables_group from tabCompany where name=%s", self.doc.company)
		g = g and g[0][0] or ''
		if not g:
			msgprint("Update Company master, assign a default group for Payables")
			raise Exception
		return g
Ejemplo n.º 25
	def convert_ledger_to_group(self):
		if self.check_gle_exists():
			msgprint("Cost Center with existing transaction can not be converted to group.", raise_exception=1)
			self.doc.group_or_ledger = 'Group'
			return 1
Ejemplo n.º 26
	def on_submit(self):
		if self.doc.doi_start >= time.strftime("%Y-%m-%d"):
			self.doc.loan_sanction_date = time.strftime("%Y-%m-%d")
		else :
			webnotes.msgprint("DOI Start date is greater than todays date")
			raise Exception
Ejemplo n.º 27
	def create_remarks(self):
		r = []
		if self.doc.cheque_no :
			if self.doc.cheque_date:
				r.append('Via Reference #%s dated %s' % 
					(self.doc.cheque_no, formatdate(self.doc.cheque_date)))
			else :
				msgprint("Please enter Reference date", raise_exception=1)
		for d in getlist(self.doclist, 'entries'):
			if d.against_invoice and d.credit:
				currency = webnotes.conn.get_value("Sales Invoice", d.against_invoice, "currency")
				r.append('%s %s against Invoice: %s' % 
					(cstr(currency), fmt_money(flt(d.credit)), d.against_invoice))
			if d.against_voucher and d.debit:
				bill_no = webnotes.conn.sql("""select bill_no, bill_date, currency 
					from `tabPurchase Invoice` where name=%s""", d.against_voucher)
				if bill_no and bill_no[0][0] and bill_no[0][0].lower().strip() \
						not in ['na', 'not applicable', 'none']:
					r.append('%s %s against Bill %s dated %s' % 
						(cstr(bill_no[0][2]), fmt_money(flt(d.debit)), bill_no[0][0], 
						bill_no[0][1] and formatdate(bill_no[0][1].strftime('%Y-%m-%d')) or ''))
		if self.doc.user_remark:
			r.append("User Remark : %s"%self.doc.user_remark)

		if r:
			self.doc.remark = ("\n").join(r)
			webnotes.msgprint("User Remarks is mandatory", raise_exception=1)
Ejemplo n.º 28
	def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
		res = webnotes.model.meta.get_dt_values(self.doctype,
			'autoname, issingle, istable, name_case', as_dict=1)
		res = res and res[0] or {}
		if new:
			self.fields["__islocal"] = 1

		# add missing parentinfo (if reqd)
		if self.parent and not (self.parenttype and self.parentfield):
		if self.parent and not self.idx:

		# if required, make new
		if self.fields.get('__islocal') and (not res.get('issingle')):
			r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
				make_autoname, keep_timestamps = keep_timestamps)
			if r: 
				return r

			if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
				webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
		# save the values
			check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
Ejemplo n.º 29
	def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0, ignore_no_table = 1, debug=0, ignore_ddl=0):
		      * Execute a `query`, with given `values`
		      * returns as a dictionary if as_dict = 1
		      * returns as a list of lists (with cleaned up dates and decimals) if as_list = 1
		# in transaction validations
		if getattr(defs,'multi_tenant',None):
			query = self.add_multi_tenant_condition(query)
		# execute
			if values!=():
				self._cursor.execute(query, values)
				if debug: webnotes.msgprint(query % values)
				if debug: webnotes.msgprint(query)
		except Exception, e:
			# ignore data definition errors
			if ignore_ddl and e.args[0] in (1146,1054,1091):
				raise e
Ejemplo n.º 30
	def create_auto_indent(self, i , doc_type, doc_name, cur_qty):
		"""	Create indent on reaching reorder level	"""

		indent = Document('Purchase Request')
		indent.transaction_date = nowdate()
		indent.naming_series = 'IDT'
		indent.company = get_defaults()['company']
		indent.fiscal_year = get_defaults()['fiscal_year']
		indent.remark = "This is an auto generated Purchase Request. It was raised because the (actual + ordered + indented - reserved) quantity reaches re-order level when %s %s was created"%(doc_type,doc_name)
		indent_obj = get_obj('Purchase Request',indent.name,with_children=1)
		indent_details_child = addchild(indent_obj.doc,'indent_details','Purchase Request Item',0)
		indent_details_child.item_code = self.doc.item_code
		indent_details_child.uom = self.doc.stock_uom
		indent_details_child.warehouse = self.doc.warehouse
		indent_details_child.schedule_date= add_days(nowdate(),cint(i['lead_time_days']))
		indent_details_child.item_name = i['item_name']
		indent_details_child.description = i['description']
		indent_details_child.item_group = i['item_group']
		indent_details_child.qty = i['re_order_qty'] or (flt(i['re_order_level']) - flt(cur_qty))
		indent_details_child.brand = i['brand']
		indent_obj = get_obj('Purchase Request',indent.name,with_children=1)
		msgprint("Item: " + self.doc.item_code + " is to be re-ordered. Purchase Request %s raised. It was generated from %s %s"%(indent.name,doc_type, doc_name ))