示例#1
0
	def get_current_tax_fraction(self, tax, item_tax_map):
		"""
			Get tax fraction for calculating tax exclusive amount
			from tax inclusive amount
		"""
		current_tax_fraction = 0
		
		if cint(tax.included_in_print_rate):
			tax_rate = self._get_tax_rate(tax, item_tax_map)
			
			if tax.charge_type == "On Net Total":
				current_tax_fraction = tax_rate / 100.0
			
			elif tax.charge_type == "On Previous Row Amount":
				current_tax_fraction = (tax_rate / 100.0) * \
					self.tax_doclist[cint(tax.row_id) - 1]\
						.tax_fraction_for_current_item
			
			elif tax.charge_type == "On Previous Row Total":
				current_tax_fraction = (tax_rate / 100.0) * \
					self.tax_doclist[cint(tax.row_id) - 1]\
						.grand_total_fraction_for_current_item
						
			# print tax.account_head, tax_rate, current_tax_fraction

		return current_tax_fraction
示例#2
0
    def validate_return_reference_doc(self):
        """validate item with reference doc"""
        ref = get_return_doclist_and_details(self.doc.fields)

        if ref.doclist:
            # validate docstatus
            if ref.doclist[0].docstatus != 1:
                webnotes.msgprint(
                    _(ref.doclist[0].doctype) + ' "' + ref.doclist[0].name + '": ' + _("Status should be Submitted"),
                    raise_exception=webnotes.InvalidStatusError,
                )

                # update stock check
            if ref.doclist[0].doctype == "Sales Invoice" and (
                cint(ref.doclist[0].is_pos) != 1 or cint(ref.doclist[0].update_stock) != 1
            ):
                webnotes.msgprint(
                    _(ref.doclist[0].doctype)
                    + ' "'
                    + ref.doclist[0].name
                    + '": '
                    + _("Is POS and Update Stock should be checked."),
                    raise_exception=NotUpdateStockError,
                )

                # posting date check
            ref_posting_datetime = "%s %s" % (
                cstr(ref.doclist[0].posting_date),
                cstr(ref.doclist[0].posting_time) or "00:00:00",
            )
            this_posting_datetime = "%s %s" % (cstr(self.doc.posting_date), cstr(self.doc.posting_time))
            if this_posting_datetime < ref_posting_datetime:
                from webnotes.utils.dateutils import datetime_in_user_format

                webnotes.msgprint(
                    _("Posting Date Time cannot be before") + ": " + datetime_in_user_format(ref_posting_datetime),
                    raise_exception=True,
                )

            stock_items = get_stock_items_for_return(ref.doclist, ref.parentfields)
            already_returned_item_qty = self.get_already_returned_item_qty(ref.fieldname)

            for item in self.doclist.get({"parentfield": "mtn_details"}):
                # validate if item exists in the ref doclist and that it is a stock item
                if item.item_code not in stock_items:
                    msgprint(
                        _("Item")
                        + ': "'
                        + item.item_code
                        + _('" does not exist in ')
                        + ref.doclist[0].doctype
                        + ": "
                        + ref.doclist[0].name,
                        raise_exception=webnotes.DoesNotExistError,
                    )

                    # validate quantity <= ref item's qty - qty already returned
                ref_item = ref.doclist.getone({"item_code": item.item_code})
                returnable_qty = ref_item.qty - flt(already_returned_item_qty.get(item.item_code))
                self.validate_value("transfer_qty", "<=", returnable_qty, item, raise_exception=StockOverReturnError)
示例#3
0
	def validate(self):
		self.so_dn_required()
		self.validate_proj_cust()
		sales_com_obj = get_obj('Sales Common')
		sales_com_obj.check_stop_sales_order(self)
		sales_com_obj.check_active_sales_items(self)
		sales_com_obj.check_conversion_rate(self)
		sales_com_obj.validate_max_discount(self, 'entries')	 #verify whether rate is not greater than tolerance
		sales_com_obj.get_allocated_sum(self)	# this is to verify that the allocated % of sales persons is 100%
		sales_com_obj.validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
		self.validate_customer()
		self.validate_customer_account()
		self.validate_debit_acc()
		self.validate_fixed_asset_account()
		self.add_remarks()
		if cint(self.doc.is_pos):
			self.validate_pos()
			self.validate_write_off_account()
			if cint(self.doc.update_stock):
				sl = get_obj('Stock Ledger')
				sl.validate_serial_no(self, 'entries')
				sl.validate_serial_no(self, 'packing_details')
				self.validate_item_code()
				self.update_current_stock()
				self.validate_delivery_note()
		self.set_in_words()
		if not self.doc.is_opening:
			self.doc.is_opening = 'No'
		self.set_aging_date()
		self.clear_advances()
		self.set_against_income_account()
		self.validate_c_form()
		self.validate_recurring_invoice()
示例#4
0
	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.make_packing_list()
			else:
				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)))
				else:
					# show message that the amount is not paid
					webnotes.conn.set(self.doc,'paid_amount',0)
					webnotes.msgprint("Note: Payment Entry will not be created since 'Cash/Bank Account' was not specified.")

		else:
			self.doclist = self.doc.clear_table(self.doclist, 'packing_details')
			webnotes.conn.set(self.doc,'paid_amount',0)

		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))
示例#5
0
	def prepare(self):
		if not self.doc.font_size:
			self.doc.font_size = '13px'
			
		self.doc.small_font_size = cstr(cint(self.doc.font_size[:-2])-2) + 'px'
		self.doc.page_border = cint(self.doc.page_border)
		
		fonts = []
		if self.doc.google_web_font_for_heading:
			fonts.append(self.doc.google_web_font_for_heading)
		if self.doc.google_web_font_for_text:
			fonts.append(self.doc.google_web_font_for_text)
			
		fonts = list(set(fonts))
		
		if self.doc.heading_text_as:
			self.doc.heading_text_style = {
				"UPPERCASE": "uppercase",
				"Title Case":"capitalize",
				"lowercase": "lowercase"
			}.get(self.doc.heading_text_as) or ""
		
		self.doc.at_import = ""
		for f in fonts:
			self.doc.at_import += "\n@import url(https://fonts.googleapis.com/css?family=%s:400,700);" % f.replace(" ", "+")
示例#6
0
	def calculate_ded_total(self):
		self.doc.total_deduction = 0
		qry=webnotes.conn.sql(" select name from `tabEmployee Loan` where employee_id=%s", self.doc.employee ,as_list=1)
		#webnotes.errprint(qry)
		r=0
		if len(qry)!=0:
			qr=webnotes.conn.sql("select date_of_installment from `tabLoan Installment Details` where parent=%s",qry[0][0],as_list=1)
			for i in qr:
				t=getdate(i[0]).month
				if t == cint(self.doc.month):
					q=webnotes.conn.sql("select amount_to_be_paid from `tabLoan Installment Details` where date_of_installment=%s and parent=%s",(getdate(i[0]),qry[0][0]),as_list=1)
					w=webnotes.conn.sql("Update `tabLoan Installment Details` set status='Paid' where date_of_installment=%s",getdate(i[0]))
					#webnotes.errprint(q)
					r=q[0][0]
					self.doc.loan_amount=r
		m=0.0
		for d in getlist(self.doclist, 'deduction_details'):
			if cint(d.d_depends_on_lwp) == 1:
				d.d_modified_amount = _round(flt(d.d_amount) * flt(self.doc.payment_days) 
					/ cint(self.doc.total_days_in_month), 2)
			elif not self.doc.payment_days:
				d.d_modified_amount = 0
			else:
				d.d_modified_amount = d.d_amount
			m+=flt(d.d_modified_amount)	
		#m+=flt(d.d_modified_amount)
		self.doc.total_deduction= m+flt(r)
	def validate(self):
		super(DocType, self).validate()
		self.validate_posting_time()
		self.so_dn_required()
		self.validate_proj_cust()
		self.validate_with_previous_doc()
		self.validate_uom_is_integer("stock_uom", "qty")
		self.check_stop_sales_order("sales_order")
		self.validate_customer_account()
		self.validate_debit_acc()
		self.validate_fixed_asset_account()
		self.clear_unallocated_advances("Sales Invoice Advance", "advance_adjustment_details")
		self.add_remarks()

		if cint(self.doc.is_pos):
			self.validate_pos()
			self.validate_write_off_account()

		if cint(self.doc.update_stock):
			self.validate_item_code()
			self.update_current_stock()
			self.validate_delivery_note()

		if not self.doc.is_opening:
			self.doc.is_opening = 'No'

		self.set_aging_date()
		self.set_against_income_account()
		self.validate_c_form()
		self.validate_time_logs_are_submitted()
		self.validate_recurring_invoice()
		self.validate_multiple_billing("Delivery Note", "dn_detail", "export_amount", 
			"delivery_note_details")
示例#8
0
	def on_submit(self):
		if cint(self.doc.is_pos) == 1:
			if cint(self.doc.update_stock) == 1:
				sl_obj = get_obj("Stock Ledger")
				sl_obj.validate_serial_no_warehouse(self, 'entries')
				sl_obj.validate_serial_no_warehouse(self, 'packing_details')
				
				sl_obj.update_serial_record(self, 'entries', is_submit = 1, is_incoming = 0)
				sl_obj.update_serial_record(self, 'packing_details', is_submit = 1, is_incoming = 0)
				
				self.update_stock_ledger(update_stock=1)
		else:
			# Check for Approving Authority
			if not self.doc.recurring_id:
				get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)

		self.check_prev_docstatus()
		get_obj("Sales Common").update_prevdoc_detail(1,self)
		
		# this sequence because outstanding may get -ve		
		self.make_gl_entries()

		if not cint(self.doc.is_pos) == 1:
			self.update_against_document_in_jv()

		self.update_c_form()
		
		self.convert_to_recurring()
 def calc_next_day(self, next_year, next_month):
   bill_cycle_day = cstr(self.doc.billing_cycle_date).split('-')[2]
   if cint(next_month) == 2 and next_year%4==0 and (next_year%100!=0 or next_year%400==0) and cint(bill_cycle_day) > 28:
     bill_cycle_day = '28'
   elif cint(bill_cycle_day) == 31 and cint(next_month) in (4,6,9,11):
     bill_cycle_day = '30'
   return bill_cycle_day
示例#10
0
	def on_submit(self):
		if cint(self.doc.update_stock) == 1:			
			self.update_stock_ledger(update_stock=1)
			self.update_serial_nos()
		else:
			# Check for Approving Authority
			if not self.doc.recurring_id:
				get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, 
				 	self.doc.company, self.doc.grand_total, self)
				
		self.set_buying_amount()
		self.check_prev_docstatus()
		
		self.update_status_updater_args()
		self.update_prevdoc_status()
		
		# this sequence because outstanding may get -ve
		self.make_gl_entries()

		if not cint(self.doc.is_pos) == 1:
			self.update_against_document_in_jv()

		self.update_c_form()
		self.update_time_log_batch(self.doc.name)
		self.convert_to_recurring()
  def account_expiry_reminder(self):
    import webnotes.utils
    from datetime import datetime
    # Payment Reminder in case of not enough balance
    cr_reqd = cint(self.doc.total_users)
    days_left = cint(self.calc_days())
    # check if account balance is sufficient
    if cint(self.doc.credit_balance)<(cr_reqd):
      
      # Difference between last payment date and current date
      if self.doc.last_deduction_date: last_payment = date_diff(nowdate(),self.doc.last_deduction_date)
      else: last_payment = -1

      # 7 days extension
      remaining_days = days_left - 24
      if last_payment > 30 or last_payment == -1:
        if remaining_days < 8 and remaining_days >= 1:
          return "Your account will be de-activated in " + cstr(remaining_days) + " days. Please contact your System Manager to buy credits."
        elif remaining_days==0:
          return "Your account will be disabled from tomorrow. Please contact your System Manager to buy credits."
        elif not has_common(['Administrator'],webnotes.user.get_roles()):
          return "Stopped"

      # check if user account is extended for seven days
      if cint(self.doc.is_trial_account)==0:
        if days_left < 10 and days_left >= 0:
          return "You have only %s Credits in your account. Buy credits before %s." % (cint(self.doc.credit_balance),formatdate(self.next_bill_sdate))
示例#12
0
	def get_details_for_packing(self):
		"""
			Returns
			* 'Delivery Note Items' query result as a list of dict
			* Item Quantity dict of current packing slip doc
			* No. of Cases of this packing slip
		"""
		item_codes = ", ".join([('"' + d.item_code + '"') for d in
			self.doclist])
		
		items = [d.item_code for d in self.doclist.get({"parentfield": "item_details"})]
		
		if not item_codes: webnotes.msgprint("No Items to Pack",
				raise_exception=1)
		
		# gets item code, qty per item code, latest packed qty per item code and stock uom
		res = webnotes.conn.sql("""select item_code, ifnull(sum(qty), 0) as qty,
			(select sum(ifnull(psi.qty, 0) * (abs(ps.to_case_no - ps.from_case_no) + 1))
				from `tabPacking Slip` ps, `tabPacking Slip Item` psi
				where ps.name = psi.parent and ps.docstatus = 1
				and ps.delivery_note = dni.parent and psi.item_code=dni.item_code)
					as packed_qty,
			stock_uom
			from `tabDelivery Note Item` dni
			where parent=%s and item_code in (%s)
			group by item_code""" % ("%s", ", ".join(["%s"]*len(items))),
			tuple([self.doc.delivery_note] + items), as_dict=1)
			
		ps_item_qty = dict([[d.item_code, d.qty] for d in self.doclist])

		no_of_cases = cint(self.doc.to_case_no) - cint(self.doc.from_case_no) + 1

		return res, ps_item_qty, no_of_cases
示例#13
0
	def cal_tax(self, ocd, prd, rate, net_total, oc):
		tax_amount = 0
		if ocd[oc].charge_type == 'Actual':
			value = flt(flt(rate) / flt(net_total))
			return flt(flt(value) * flt(prd.amount))
			
		elif ocd[oc].charge_type == 'On Net Total':
			return flt(flt(rate) * flt(prd.amount) / 100)
			
		elif ocd[oc].charge_type == 'On Previous Row Amount':
			
			row_no = cstr(ocd[oc].row_id)
			row = (row_no).split("+")
			for r in range(0, len(row.length)):
				id = cint(row[r])
				tax_amount += flt((flt(rate) * flt(ocd[id-1].total_amount) / 100))
			row_id = row_no.find("/")
			if row_id != -1:
				rate = ''
				row = (row_no).split("/")
				
				id1 = cint(row[0])
				id2 = cint(row[1])
				tax_amount = flt(flt(ocd[id1-1].total_amount) / flt(ocd[id2-1].total_amount))
				
			return tax_amount
示例#14
0
	def test_5_make_autoname(self):
		new_name = doc.make_autoname(self.test_doc.name,self.test_doc.parenttype)
		last_name = testlib.test_conn.sql("select name from `tab%s` order by name desc limit 1"%testlib.test_doctype)		
		if not last_name:
			last_name = '0'
		webnotes.conn.commit()
		assert (cint(new_name[get_num_start_pos(new_name):])) - cint(last_name[get_num_start_pos(last_name):])
示例#15
0
	def validate_value(self, fieldname, condition, val2, doc=None, raise_exception=None):
		"""check that value of fieldname should be 'condition' val2
			else throw exception"""
		if not doc:
			doc = self.doc
		
		df = self.meta.get_field(fieldname, parent=doc.doctype)
		
		val1 = doc.fields.get(fieldname)
		
		if df.fieldtype in ("Currency", "Float"):
			val1 = flt(val1, self.precision(df.fieldname, doc.parentfield or None))
			val2 = flt(val2, self.precision(df.fieldname, doc.parentfield or None))
		elif df.fieldtype in ("Int", "Check"):
			val1 = cint(val1)
			val2 = cint(val2)
		
		if not webnotes.compare(val1, condition, val2):
			msg = _("Error") + ": "
			if doc.parentfield:
				msg += _("Row") + (" # %d: " % doc.idx)
			
			msg += _(self.meta.get_label(fieldname, parent=doc.doctype)) \
				+ " " + error_condition_map.get(condition, "") + " " + cstr(val2)
			
			# raise passed exception or True
			msgprint(msg, raise_exception=raise_exception or True)
示例#16
0
	def set_pos_fields(self, for_validate=False):
		"""Set retail related fields from pos settings"""
		if cint(self.doc.is_pos) != 1:
			return
		
		from selling.utils import get_pos_settings, apply_pos_settings	
		pos = get_pos_settings(self.doc.company)
			
		if pos:
			if not for_validate and not self.doc.customer:
				self.doc.customer = pos.customer
				self.set_customer_defaults()

			for fieldname in ('territory', 'naming_series', 'currency', 'charge', 'letter_head', 'tc_name',
				'selling_price_list', 'company', 'select_print_heading', 'cash_bank_account'):
					if (not for_validate) or (for_validate and not self.doc.fields.get(fieldname)):
						self.doc.fields[fieldname] = pos.get(fieldname)
						
			if not for_validate:
				self.doc.update_stock = cint(pos.get("update_stock"))

			# set pos values in items
			for item in self.doclist.get({"parentfield": "entries"}):
				if item.fields.get('item_code'):
					for fieldname, val in apply_pos_settings(pos, item.fields).items():
						if (not for_validate) or (for_validate and not item.fields.get(fieldname)):
							item.fields[fieldname] = val

			# fetch terms	
			if self.doc.tc_name and not self.doc.terms:
				self.doc.terms = webnotes.conn.get_value("Terms and Conditions", self.doc.tc_name, "terms")
			
			# fetch charges
			if self.doc.charge and not len(self.doclist.get({"parentfield": "other_charges"})):
				self.set_taxes("other_charges", "charge")
示例#17
0
	def validate(self):
		super(DocType, self).validate()
		
		self.so_dn_required()
		self.validate_proj_cust()
		sales_com_obj = get_obj('Sales Common')
		sales_com_obj.check_stop_sales_order(self)
		sales_com_obj.check_active_sales_items(self)
		sales_com_obj.check_conversion_rate(self)
		sales_com_obj.validate_max_discount(self, 'entries')
		sales_com_obj.get_allocated_sum(self)
		sales_com_obj.validate_fiscal_year(self.doc.fiscal_year, 
			self.doc.posting_date,'Posting Date')
		self.validate_customer()
		self.validate_customer_account()
		self.validate_debit_acc()
		self.validate_fixed_asset_account()
		self.clear_unallocated_advances("Sales Invoice Advance", "advance_adjustment_details")
		self.add_remarks()
		if cint(self.doc.is_pos):
			self.validate_pos()
			self.validate_write_off_account()
			if cint(self.doc.update_stock):
				sl = get_obj('Stock Ledger')
				sl.validate_serial_no(self, 'entries')
				sl.validate_serial_no(self, 'packing_details')
				self.validate_item_code()
				self.update_current_stock()
				self.validate_delivery_note()
		if not self.doc.is_opening:
			self.doc.is_opening = 'No'
		self.set_aging_date()
		self.set_against_income_account()
		self.validate_c_form()
		self.validate_recurring_invoice()
示例#18
0
	def update_parent_info(self):
		idx_map = {}
		is_local = cint(self.doc.fields.get("__islocal"))
		
		if not webnotes.flags.in_import:
			parentfields = [d.fieldname for d in self.meta.get({"doctype": "DocField", "fieldtype": "Table"})]
			
		for i, d in enumerate(self.doclist[1:]):
			if d.parentfield:
				if not webnotes.flags.in_import:
					if not d.parentfield in parentfields:
						webnotes.msgprint("Bad parentfield %s" % d.parentfield, 
							raise_exception=True)
				d.parenttype = self.doc.doctype
				d.parent = self.doc.name
			if not d.idx:
				d.idx = idx_map.setdefault(d.parentfield, 0) + 1
			else:
				d.idx = cint(d.idx)
			if is_local:
				# if parent is new, all children should be new
				d.fields["__islocal"] = 1
				d.name = None
			
			idx_map[d.parentfield] = d.idx
示例#19
0
	def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
		# get defaults from control panel
		try:
			es = webnotes.doc('Email Settings','Email Settings')
		except webnotes.DoesNotExistError:
			es = None
		
		self._sess = None
		if server:
			self.server = server
			self.port = port
			self.use_ssl = cint(use_ssl)
			self.login = login
			self.password = password
		elif es and es.outgoing_mail_server:
			self.server = es.outgoing_mail_server
			self.port = es.mail_port
			self.use_ssl = cint(es.use_ssl)
			self.login = es.mail_login
			self.password = es.mail_password
			self.always_use_login_id_as_sender = es.always_use_login_id_as_sender
		else:
			self.server = webnotes.conf.get("mail_server") or ""
			self.port = webnotes.conf.get("mail_port") or None
			self.use_ssl = cint(webnotes.conf.get("use_ssl") or 0)
			self.login = webnotes.conf.get("mail_login") or ""
			self.password = webnotes.conf.get("mail_password") or ""
示例#20
0
	def make_gl_entries(self):
		from accounts.general_ledger import make_gl_entries, merge_similar_entries
		
		gl_entries = []
		
		self.make_customer_gl_entry(gl_entries)
	
		self.make_tax_gl_entries(gl_entries)
		
		self.make_item_gl_entries(gl_entries)
		
		# merge gl entries before adding pos entries
		gl_entries = merge_similar_entries(gl_entries)
						
		self.make_pos_gl_entries(gl_entries)
		
		update_outstanding = cint(self.doc.is_pos) and self.doc.write_off_account and 'No' or 'Yes'
		
		if gl_entries:
			make_gl_entries(gl_entries, cancel=(self.doc.docstatus == 2), 
				update_outstanding=update_outstanding, merge_entries=False)
				
			if cint(webnotes.defaults.get_global_default("auto_accounting_for_stock")) \
					and cint(self.doc.update_stock):
				self.update_gl_entries_after()
示例#21
0
	def validate_inclusive_tax(self, tax):
		def _on_previous_row_error(row_range):
			msgprint((_("Row") + " # %(idx)s [%(doctype)s]: " +
				_("to be included in Item's rate, it is required that: ") +
				" [" + _("Row") + " # %(row_range)s] " + _("also be included in Item's rate")) % {
					"idx": tax.idx,
					"doctype": tax.doctype,
					"inclusive_label": self.meta.get_label("included_in_print_rate",
						parentfield=self.other_fname),
					"charge_type_label": self.meta.get_label("charge_type",
						parentfield=self.other_fname),
					"charge_type": tax.charge_type,
					"row_range": row_range
				}, raise_exception=True)
		
		if cint(tax.included_in_print_rate):
			if tax.charge_type == "Actual":
				# inclusive tax cannot be of type Actual
				msgprint((_("Row") 
					+ " # %(idx)s [%(doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" " 
					+ "cannot be included in Item's rate") % {
						"idx": tax.idx,
						"doctype": tax.doctype,
						"charge_type_label": self.meta.get_label("charge_type",
							parentfield=self.other_fname),
						"charge_type": tax.charge_type,
					}, raise_exception=True)
			elif tax.charge_type == "On Previous Row Amount" and \
					not cint(self.tax_doclist[tax.row_id - 1].included_in_print_rate):
				# referred row should also be inclusive
				_on_previous_row_error(tax.row_id)
			elif tax.charge_type == "On Previous Row Total" and \
					not all([cint(t.included_in_print_rate) for t in self.tax_doclist[:tax.row_id - 1]]):
				# all rows about the reffered tax should be inclusive
				_on_previous_row_error("1 - %d" % (tax.row_id,))
示例#22
0
	def get_current_tax_amount(self, item, tax, item_tax_map):
		tax_rate = self._get_tax_rate(tax, item_tax_map)
		current_tax_amount = 0.0

		if tax.charge_type == "Actual":
			# distribute the tax amount proportionally to each item row
			actual = flt(tax.rate, self.precision("tax_amount", tax))
			current_tax_amount = (self.doc.net_total
				and ((item.amount / self.doc.net_total) * actual)
				or 0)
		elif tax.charge_type == "On Net Total":
			current_tax_amount = (tax_rate / 100.0) * item.amount
		elif tax.charge_type == "On Previous Row Amount":
			current_tax_amount = (tax_rate / 100.0) * \
				self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
		elif tax.charge_type == "On Previous Row Total":
			current_tax_amount = (tax_rate / 100.0) * \
				self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
		
		current_tax_amount = flt(current_tax_amount, self.precision("tax_amount", tax))
		
		# store tax breakup for each item
		key = item.item_code or item.item_name
		if tax.item_wise_tax_detail.get(key):
			item_wise_tax_amount = tax.item_wise_tax_detail[key][1] + current_tax_amount
			tax.item_wise_tax_detail[key] = [tax_rate, item_wise_tax_amount]
		else:
			tax.item_wise_tax_detail[key] = [tax_rate, current_tax_amount]

		return current_tax_amount
示例#23
0
	def validate(self):
		previous_auto_inventory_accounting = cint(webnotes.conn.get_value("Global Defaults", None,
			"auto_inventory_accounting"))
		if cint(self.doc.auto_inventory_accounting) != previous_auto_inventory_accounting:
			from accounts.utils import create_stock_in_hand_jv
			create_stock_in_hand_jv(reverse = \
				cint(self.doc.auto_inventory_accounting) < previous_auto_inventory_accounting)
示例#24
0
	def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
		import webnotes.model.doc
		from webnotes.utils import cint

		# get defaults from control panel
		es = webnotes.model.doc.Document('Email Settings','Email Settings')
		
		self._sess = None
		if server:
			self.server = server
			self.port = port
			self.use_ssl = cint(use_ssl)
			self.login = login
			self.password = password
		elif es.outgoing_mail_server:
			self.server = es.outgoing_mail_server
			self.port = es.mail_port
			self.use_ssl = cint(es.use_ssl)
			self.login = es.mail_login
			self.password = es.mail_password
		else:
			self.server = getattr(conf, "mail_server", "")
			self.port = getattr(conf, "mail_port", None)
			self.use_ssl = cint(getattr(conf, "use_ssl", 0))
			self.login = getattr(conf, "mail_login", "")
			self.password = getattr(conf, "mail_password", "")
示例#25
0
 def validate(self):
     self.so_dn_required()
     # self.dn_required()
     self.validate_proj_cust()
     sales_com_obj = get_obj("Sales Common")
     sales_com_obj.check_stop_sales_order(self)
     sales_com_obj.check_active_sales_items(self)
     sales_com_obj.check_conversion_rate(self)
     sales_com_obj.validate_max_discount(self, "entries")  # verify whether rate is not greater than tolerance
     sales_com_obj.get_allocated_sum(self)  # this is to verify that the allocated % of sales persons is 100%
     sales_com_obj.validate_fiscal_year(self.doc.fiscal_year, self.doc.posting_date, "Posting Date")
     self.validate_customer()
     self.validate_debit_to_acc()
     self.validate_debit_acc()
     self.validate_fixed_asset_account()
     self.add_remarks()
     if cint(self.doc.is_pos):
         self.validate_pos()
         self.validate_write_off_account()
         if cint(self.doc.update_stock):
             get_obj("Stock Ledger").validate_serial_no(self, "entries")
             self.validate_item_code()
             self.update_current_stock()
     self.set_in_words()
     if not self.doc.is_opening:
         self.doc.is_opening = "No"
     self.set_aging_date()
     self.clear_advances()
     # Set against account
     self.set_against_income_account()
     self.validate_c_form()
	def get_children(self, arg='', only_type='', in_roles=[]):

		type_cond = only_type and (" and menu_item_type='%s'" % only_type) or ''
		
		import webnotes
		roles = webnotes.user.get_roles()
		all_read = webnotes.user.can_get_report
			
		cl = sql("select name, menu_item_label, menu_item_type, link_id, link_content, has_children, icon, `order`, criteria_name, doctype_fields, onload from `tabMenu Item` where ifnull(disabled,'No')!='Yes' and ifnull(parent_menu_item,'')='%s' %s order by `order` asc" % (arg, type_cond), as_dict=1)
		ol = []
		for c in cl:
			c['has_children'] = cint(c['has_children'])
			c['order'] = cint(c['order'])
			for k in c.keys(): 
				if c[k]==None: c[k] = ''

			# check permission
			if c['menu_item_type'] in ('DocType','Single','Report'):
				if c['link_id'] in all_read:
					ol.append(c)
			elif c['menu_item_type']=='Page':
				# page
				if c['link_id'].startswith('_'):
					ol.append(c)
				elif has_common([r[0] for r in sql("select role from `tabPage Role` where parent=%s", c['link_id'])], roles):
					ol.append(c)
			elif cstr(c['menu_item_type'])=='':
				# sections
				if has_common([r[0] for r in sql("select role from `tabMenu Item Role` where parent=%s", c['name'])], roles):
					ol.append(c)
			else:
				ol.append(c)
		
		return ol
示例#27
0
	def get_leave_details(self, lwp=None):
		if not self.doc.fiscal_year:
			self.doc.fiscal_year = webnotes.get_default("fiscal_year")
		if not self.doc.month:
			self.doc.month = "%02d" % getdate(nowdate()).month
			
		m = get_obj('Salary Manager').get_month_details(self.doc.fiscal_year, self.doc.month)
		holidays = self.get_holidays_for_employee(m)
		
		if not cint(webnotes.conn.get_value("HR Settings", "HR Settings",
			"include_holidays_in_total_working_days")):
				m["month_days"] -= len(holidays)
				if m["month_days"] < 0:
					msgprint(_("Bummer! There are more holidays than working days this month."),
						raise_exception=True)
			
		if not lwp:
			lwp = self.calculate_lwp(holidays, m)
		self.doc.total_days_in_month = m['month_days']
		self.doc.leave_without_pay = lwp
		payment_days = flt(self.get_payment_days(m)) - flt(lwp)
		self.doc.payment_days = payment_days > 0 and payment_days or 0
		
		ss="select DATEDIFF(NOW(),(select date_of_joining from tabEmployee where name='"+self.doc.employee+"'))/365 from tabEmployee where name='"+self.doc.employee+"' and status='Left' and DATEDIFF(CURDATE(), (select relieving_date from tabEmployee where name='"+self.doc.employee+"')) <=31  and DATEDIFF(NOW(),(select date_of_joining from tabEmployee where name='"+self.doc.employee+"'))/365 >5"
		# webnotes.errprint(ss)
		res=webnotes.conn.sql(ss)
		# webnotes.errprint(res)
		if res:
                    lst_sal_qry="select net_pay from `tabSalary Slip` where employee='"+self.doc.employee+"' order by creation desc limit 1"
		    # webnotes.errprint(lst_sal_qry)
		    lst_sal=webnotes.conn.sql(lst_sal_qry)
		    grp_amt=(cint(lst_sal[0][0])* cint(res[0][0]))/27
		    # webnotes.errprint(grp_amt)
		    self.doc.grauity_amount=grp_amt		
示例#28
0
	def cal_tax(self, ocd, prd, rate, net_total, oc):
		""" Calculates tax amount for one item"""
		tax_amount = 0
		if ocd[oc].charge_type == 'Actual':
			tax_amount = flt(rate) * flt(prd.amount) / flt(net_total)
		elif ocd[oc].charge_type == 'On Net Total':
			tax_amount = flt(rate) * flt(prd.amount) / 100		
		elif ocd[oc].charge_type == 'On Previous Row Amount':			
			row_no = cstr(ocd[oc].row_id)
			row = row_no.split("+")
			for r in range(0, len(row)):
				id = cint(row[r])
				tax_amount += flt((flt(rate) * flt(ocd[id-1].total_amount) / 100))
			row_id = row_no.find("/")
			if row_id != -1:
				rate = ''
				row = (row_no).split("/")				
				id1 = cint(row[0])
				id2 = cint(row[1])
				tax_amount = flt(flt(ocd[id1-1].total_amount) / flt(ocd[id2-1].total_amount))
		elif ocd[oc].charge_type == 'On Previous Row Total':
			row = cint(ocd[oc].row_id)
			if ocd[row-1].add_deduct_tax == 'Add':
			  tax_amount = flt(rate) * (flt(ocd[row-1].total_tax_amount)+flt(ocd[row-1].total_amount)) / 100
			elif ocd[row-1].add_deduct_tax == 'Deduct':
			  tax_amount = flt(rate) * (flt(ocd[row-1].total_tax_amount)-flt(ocd[row-1].total_amount)) / 100
		
		return tax_amount  
示例#29
0
 def get_weekdates(self,lst):
   from datetime import date, timedelta
 
   d = dt = self.make_date(lst)
   date_lst = [[1,cstr(d.strftime("%d/%m/%y"))]]
   week=flag =1
   j=1
   last_day = sql("select last_day('%s')"%d)[0][0]
   lst_m = cint(lst.split(',')[0])
   for i in range(2,8):
     f=0
     if(dt < last_day):
       #if(d.weekday()>4):
       #d = d+timedelta(7-d.weekday()) 
       #else:
       d = d - timedelta(d.weekday()-1)
       dlt = timedelta(days = (week-1)*7)
       dt = d + dlt + timedelta(days=6)
       
       if(cint(sql("select month('%s')"%dt)[0][0]) == lst_m and dt!=last_day):
         for k in date_lst:      
           if(cstr(dt.strftime("%d/%m/%y")) == k[1]):
             f = 1
         if f == 0:   
           date_lst.append([i,cstr(dt.strftime("%d/%m/%y"))])
         
       elif(dt==last_day and flag ==1):
         date_lst.append([i,cstr(last_day.strftime("%d/%m/%y"))])
         flag = 0
     
       elif(flag == 1):
         date_lst.append([i,cstr(last_day.strftime("%d/%m/%y"))])
       week += 1
      
   return date_lst and date_lst or ''
示例#30
0
    def make_item_gl_entries(self, gl_entries):
        # income account gl entries
        for item in self.doclist.get({"parentfield": "entries"}):
            if flt(item.amount):
                gl_entries.append(
                    self.get_gl_dict(
                        {
                            "account": item.income_account,
                            "against": self.doc.debit_to,
                            "credit": item.amount,
                            "remarks": self.doc.remarks,
                            "cost_center": item.cost_center,
                        }
                    )
                )

                # expense account gl entries
        if (
            cint(webnotes.defaults.get_global_default("auto_inventory_accounting"))
            and cint(self.doc.is_pos)
            and cint(self.doc.update_stock)
        ):

            for item in self.doclist.get({"parentfield": "entries"}):
                self.check_expense_account(item)

                if item.buying_amount:
                    gl_entries += self.get_gl_entries_for_stock(
                        item.expense_account, -1 * item.buying_amount, cost_center=item.cost_center
                    )
示例#31
0
    def set_next_date(self):
        """ Set next date on which auto invoice will be created"""
        if not self.doc.repeat_on_day_of_month:
            msgprint("""Please enter 'Repeat on Day of Month' field value. 
				The day of the month on which auto invoice 
				will be generated e.g. 05, 28 etc.""",
                     raise_exception=1)

        next_date = get_next_date(self.doc.posting_date,
                                  month_map[self.doc.recurring_type],
                                  cint(self.doc.repeat_on_day_of_month))

        webnotes.conn.set(self.doc, 'next_date', next_date)
示例#32
0
def has_permission(doctype, ptype="read", refdoc=None):
    """check if user has permission"""
    from webnotes.utils import cint

    if session.user == "Administrator" or conn.get_value(
            "DocType", doctype, "istable") == 1:
        return True

    meta = get_doctype(doctype)

    # get user permissions
    user_roles = get_roles()
    perms = [
        p for p in meta.get({"doctype": "DocPerm"})
        if cint(p.get(ptype)) == 1 and cint(p.permlevel) == 0 and (
            p.role == "All" or p.role in user_roles)
    ]

    if refdoc:
        return has_match(meta, perms, refdoc)
    else:
        return perms and True or False
示例#33
0
 def update_series_start(self):
     if self.doc.prefix:
         ser_det = sql("select name from `tabSeries` where name = %s",
                       self.doc.prefix)
         if ser_det:
             sql("update `tabSeries` set current = '%s' where name = '%s'" %
                 (self.doc.starts_from - 1, self.doc.prefix))
         else:
             sql("insert into tabSeries (name, current) values (%s,%s)",
                 (cstr(self.doc.prefix), cint(self.doc.starts_from) - 1))
         msgprint("Series Updated Successfully")
     else:
         msgprint("Please select prefix first")
示例#34
0
    def check_eligible(self, person, person_allocated_amt):
        if self.fiscal_year:
            target_amt_percent = self.target_all_details(
                person, (self.fiscal_year)[0][0],
                self.months.get(cint(self.from_date(self.quater_month).month)))
            if target_amt_percent:
                for amt in target_amt_percent:
                    quater_target_amount = flt(amt[0]) * flt(amt[1]) / flt(100)
                    percent = flt(person_allocated_amt) / flt(
                        quater_target_amount) * 100
                    if percent >= 75:
                        webnotes.conn.sql(
                            """update `tabSales Team` set eligible='True',fiscal_year='%s',quater='%s' where sales_person='%s' 
							and parent in (select name from `tabSales Order` where transaction_date between '%s' and '%s') and docstatus=1"""
                            %
                            ((self.fiscal_year)[0][0],
                             self.months.get(
                                 cint(self.from_date(
                                     self.quater_month).month)), person,
                             self.from_date(
                                 self.quater_month), self.to_date()))
                        webnotes.conn.sql("commit")
示例#35
0
	def validate_warehouse_account(self):
		if not cint(webnotes.defaults.get_global_default("auto_accounting_for_stock")):
			return
			
		if self.doc.account_type == "Warehouse":
			old_warehouse = cstr(webnotes.conn.get_value("Account", self.doc.name, "master_name"))
			if old_warehouse != cstr(self.doc.master_name):
				if old_warehouse:
					self.validate_warehouse(old_warehouse)
				if self.doc.master_name:
					self.validate_warehouse(self.doc.master_name)
				else:
					webnotes.throw(_("Master Name is mandatory if account type is Warehouse"))
示例#36
0
    def check_level_zero_is_set(d):
        if cint(d.permlevel) > 0 and d.role != 'All':
            if not permissions.get({"role": d.role, "permlevel": 0}):
                webnotes.msgprint(
                    get_txt(d) +
                    " Higher level permissions are meaningless if level 0 permission is not set.",
                    raise_exception=True)

            if d.create or d.submit or d.cancel or d.amend or d.match:
                webnotes.msgprint(
                    "Create, Submit, Cancel, Amend, Match has no meaning at level "
                    + d.permlevel,
                    raise_exception=True)
示例#37
0
	def get_current_tax_fraction(self, tax, item_tax_map):
		"""
			Get tax fraction for calculating tax exclusive amount
			from tax inclusive amount
		"""
		current_tax_fraction = 0
		
		if cint(tax.included_in_print_rate):
			tax_rate = self._get_tax_rate(tax, item_tax_map)
			
			if tax.charge_type == "On Net Total":
				current_tax_fraction = tax_rate / 100.0
			
			elif tax.charge_type == "On Previous Row Amount":
				current_tax_fraction = (tax_rate / 100.0) * \
					self.tax_doclist[cint(tax.row_id) - 1].tax_fraction_for_current_item
			
			elif tax.charge_type == "On Previous Row Total":
				current_tax_fraction = (tax_rate / 100.0) * \
					self.tax_doclist[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
						
		return current_tax_fraction
示例#38
0
	def on_submit(self):
		if cint(self.doc.is_pos) == 1:
			if cint(self.doc.update_stock) == 1:
				sl_obj = get_obj("Stock Ledger")
				sl_obj.validate_serial_no_warehouse(self, 'entries')
				sl_obj.update_serial_record(self, 'entries', is_submit = 1, is_incoming = 0)
				self.pos_update_stock()
		else:
			self.check_prev_docstatus()
			get_obj("Sales Common").update_prevdoc_detail(1,self)

			# Check for Approving Authority
			if not self.doc.recurring_id:
				get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)

		# this sequence because outstanding may get -ve		
		self.make_gl_entries()

		if not cint(self.doc.is_pos) == 1:
			self.update_against_document_in_jv()

		self.update_c_form()
示例#39
0
	def validate_expense_account(self):
		if not cint(webnotes.defaults.get_global_default("auto_accounting_for_stock")):
			return
			
		if not self.doc.expense_account:
			msgprint(_("Please enter Expense Account"), raise_exception=1)
		elif not webnotes.conn.sql("""select * from `tabStock Ledger Entry`"""):
			if webnotes.conn.get_value("Account", self.doc.expense_account, 
					"is_pl_account") == "Yes":
				msgprint(_("""Expense Account can not be a PL Account, as this stock \
					reconciliation is an opening entry. \
					Please select 'Temporary Account (Liabilities)' or relevant account"""), 
					raise_exception=1)
示例#40
0
	def make_gl_entries(self):
		if not cint(webnotes.defaults.get_global_default("auto_inventory_accounting")):
			return
		
		if not self.doc.expense_account:
			msgprint(_("Please enter Expense Account"), raise_exception=1)
			
		from accounts.general_ledger import make_gl_entries
				
		gl_entries = self.get_gl_entries_for_stock(self.doc.expense_account, 
			self.doc.stock_value_difference)
		if gl_entries:
			make_gl_entries(gl_entries, cancel=self.doc.docstatus == 2)
示例#41
0
 def getseries(self, key, digits, doctype=''):
     current = webnotes.conn.sql(
         "select `current` from `tabSeries` where name='GID' for update")
     if current and current[0][0] is not None:
         current = current[0][0]
         webnotes.conn.sql(
             "update tabSeries set current = current+1 where name='GID'")
         current = cint(current) + 1
     else:
         webnotes.conn.sql(
             "insert into tabSeries (name, current) values ('GID', 1)")
         current = 1
     return ('%0' + str(digits) + 'd') % current
示例#42
0
	def set_total_in_words(self):
		from webnotes.utils import money_in_words
		company_currency = get_company_currency(self.doc.company)
		
		disable_rounded_total = cint(webnotes.conn.get_value("Global Defaults", None, 
			"disable_rounded_total"))
			
		if self.meta.get_field("in_words"):
			self.doc.in_words = money_in_words(disable_rounded_total and 
				self.doc.grand_total or self.doc.rounded_total, company_currency)
		if self.meta.get_field("in_words_export"):
			self.doc.in_words_export = money_in_words(disable_rounded_total and 
				self.doc.grand_total_export or self.doc.rounded_total_export, self.doc.currency)
示例#43
0
def getlist(doclist, field):
    """
   Filter a list of records for a specific field from the full doclist

   Example::

     # find all phone call details
     dl = getlist(self.doclist, 'contact_updates')
     pl = []
     for d in dl:
       if d.type=='Phone':
         pl.append(d)
	"""
    from webnotes.utils import cint
    l = []
    for d in doclist:
        if d.parentfield == field:
            l.append(d)

    l.sort(lambda a, b: cint(a.idx) - cint(b.idx))

    return l
示例#44
0
 def on_update(self):
     sp = webnotes.conn.get_value('Sales Person',
                                  {'employee': self.doc.employee}, 'name')
     if sp:
         sp_vp = webnotes.conn.sql(
             "select name,variable_pay from `tabSales Person Variable Pay` where sales_person='%s' and fiscal_year='%s' and month='%s' and status='False'"
             % (sp, self.doc.fiscal_year, self.doc.month),
             as_list=1)
         if sp_vp:
             self.doc.gross_pay = cstr(
                 cint(self.doc.gross_pay) + cint(sp_vp[0][1]))
             self.doc.net_pay = cstr(
                 cint(self.doc.net_pay) + cint(sp_vp[0][1]))
             self.doc.variable_pay = cstr(sp_vp[0][1])
             self.doc.save()
             webnotes.conn.sql(
                 "update `tabSalary Slip Earning` set e_amount='%s',e_modified_amount='%s' where e_type='Variable Pay' and parent='%s'"
                 % (self.doc.variable_pay, self.doc.variable_pay,
                    self.doc.name))
             webnotes.conn.sql(
                 "Update `tabSales Person Variable Pay` set status='True' where name ='%s'"
                 % (sp_vp[0][0]))
示例#45
0
	def precision(self, fieldname, parentfield=None):
		parentfield = self._process(parentfield)
		
		if not hasattr(self, "_precision"):
			self._precision = webnotes._dict({
				"default": cint(webnotes.conn.get_default("float_precision")) or 3,
				"options": {}
			})
		
		if self._precision.setdefault(parentfield or "main", {}).get(fieldname) is None:
			df = self.meta.get_field(fieldname, parentfield=parentfield)
			
			if df.fieldtype == "Currency" and df.options and not self._precision.options.get(df.options):
				self._precision.options[df.options] = get_field_precision(df, self.doc)
			
			if df.fieldtype == "Currency":
				self._precision[parentfield or "main"][fieldname] = cint(self._precision.options.get(df.options)) or \
					self._precision.default
			elif df.fieldtype == "Float":
				self._precision[parentfield or "main"][fieldname] = self._precision.default
		
		return self._precision[parentfield or "main"][fieldname]
示例#46
0
 def calculate_ded_total(self):
     self.doc.total_deduction = 0
     qry = webnotes.conn.sql(
         " select name from `tabEmployee Loan` where employee_id=%s",
         self.doc.employee,
         as_list=1)
     #webnotes.errprint(qry)
     r = 0
     if len(qry) != 0:
         qr = webnotes.conn.sql(
             "select date_of_installment from `tabLoan Installment Details` where parent=%s",
             qry[0][0],
             as_list=1)
         for i in qr:
             t = getdate(i[0]).month
             if t == cint(self.doc.month):
                 q = webnotes.conn.sql(
                     "select amount_to_be_paid from `tabLoan Installment Details` where date_of_installment=%s and parent=%s",
                     (getdate(i[0]), qry[0][0]),
                     as_list=1)
                 w = webnotes.conn.sql(
                     "Update `tabLoan Installment Details` set status='Paid' where date_of_installment=%s",
                     getdate(i[0]))
                 #webnotes.errprint(q)
                 r = q[0][0]
                 self.doc.loan_amount = r
     m = 0.0
     for d in getlist(self.doclist, 'deduction_details'):
         if cint(d.d_depends_on_lwp) == 1:
             d.d_modified_amount = _round(
                 flt(d.d_amount) * flt(self.doc.payment_days) /
                 cint(self.doc.total_days_in_month), 2)
         elif not self.doc.payment_days:
             d.d_modified_amount = 0
         else:
             d.d_modified_amount = d.d_amount
         m += flt(d.d_modified_amount)
     #m+=flt(d.d_modified_amount)
     self.doc.total_deduction = m + flt(r)
示例#47
0
    def get_leave_details(self, lwp=None):
        if not self.doc.fiscal_year:
            self.doc.fiscal_year = webnotes.get_default("fiscal_year")
        if not self.doc.month:
            self.doc.month = "%02d" % getdate(nowdate()).month

        m = get_obj('Salary Manager').get_month_details(
            self.doc.fiscal_year, self.doc.month)
        holidays = self.get_holidays_for_employee(m)

        if not cint(
                webnotes.conn.get_value(
                    "HR Settings", "HR Settings",
                    "include_holidays_in_total_working_days")):
            m["month_days"] -= len(holidays)
            if m["month_days"] < 0:
                msgprint(_(
                    "Bummer! There are more holidays than working days this month."
                ),
                         raise_exception=True)

        if not lwp:
            lwp = self.calculate_lwp(holidays, m)
        self.doc.total_days_in_month = m['month_days']
        self.doc.leave_without_pay = lwp
        payment_days = flt(self.get_payment_days(m)) - flt(lwp)
        self.doc.payment_days = payment_days > 0 and payment_days or 0

        ss = "select DATEDIFF(NOW(),(select date_of_joining from tabEmployee where name='" + self.doc.employee + "'))/365 from tabEmployee where name='" + self.doc.employee + "' and status='Left' and DATEDIFF(CURDATE(), (select relieving_date from tabEmployee where name='" + self.doc.employee + "')) <=31  and DATEDIFF(NOW(),(select date_of_joining from tabEmployee where name='" + self.doc.employee + "'))/365 >5"
        # webnotes.errprint(ss)
        res = webnotes.conn.sql(ss)
        # webnotes.errprint(res)
        if res:
            lst_sal_qry = "select net_pay from `tabSalary Slip` where employee='" + self.doc.employee + "' order by creation desc limit 1"
            # webnotes.errprint(lst_sal_qry)
            lst_sal = webnotes.conn.sql(lst_sal_qry)
            grp_amt = (cint(lst_sal[0][0]) * cint(res[0][0])) / 27
            # webnotes.errprint(grp_amt)
            self.doc.grauity_amount = grp_amt
示例#48
0
	def make_gl_entries(self, update_gl_entries_after=True):
		if self.doc.docstatus == 2:
			delete_gl_entries(voucher_type=self.doc.doctype, voucher_no=self.doc.name)
			
		if cint(webnotes.defaults.get_global_default("auto_accounting_for_stock")):
			warehouse_account = self.get_warehouse_account()
		
			if self.doc.docstatus==1:
				gl_entries = self.get_gl_entries(warehouse_account)
				make_gl_entries(gl_entries)

			if update_gl_entries_after:
				self.update_gl_entries_after(warehouse_account)
示例#49
0
    def autoname(self):
        self.doc.name = self.doc.criteria_name.lower().replace('(','').replace(')', '')\
         .replace('.','').replace(',','').replace('"', '').replace("'",'').replace(' ', '_')\
         .replace('/', '-')

        # for duplicates
        if webnotes.conn.sql(
                "select name from `tabSearch Criteria` where name = %s",
                self.doc.name):
            m = webnotes.conn.sql(
                "select name from `tabSearch Criteria` where name like '%s%%' order by name desc limit 1"
                % self.doc.name)[0][0]
            self.doc.name = self.doc.name + str(cint(m[-1]) + 1)
示例#50
0
    def set_remember_me(self):
        from webnotes.utils import cint

        if not cint(webnotes.form_dict.get('remember_me')): return

        remember_days = webnotes.conn.get_value('Control Panel', None,
                                                'remember_for_days') or 7

        import datetime
        expires = datetime.datetime.now() + \
           datetime.timedelta(days=remember_days)

        webnotes._response.set_cookie["remember_me"] = 1
示例#51
0
    def get_details_for_packing(self):
        """
			Returns
			* 'Delivery Note Items' query result as a list of dict
			* Item Quantity dict of current packing slip doc
			* No. of Cases of this packing slip
		"""
        item_codes = ", ".join([('"' + d.item_code + '"')
                                for d in self.doclist])

        items = [
            d.item_code
            for d in self.doclist.get({"parentfield": "item_details"})
        ]

        if not item_codes:
            webnotes.msgprint("No Items to Pack", raise_exception=1)

        # gets item code, qty per item code, latest packed qty per item code and stock uom
        res = webnotes.conn.sql(
            """select item_code, ifnull(sum(qty), 0) as qty,
			(select sum(ifnull(psi.qty, 0) * (abs(ps.to_case_no - ps.from_case_no) + 1))
				from `tabPacking Slip` ps, `tabPacking Slip Item` psi
				where ps.name = psi.parent and ps.docstatus = 1
				and ps.delivery_note = dni.parent and psi.item_code=dni.item_code)
					as packed_qty,
			stock_uom
			from `tabDelivery Note Item` dni
			where parent=%s and item_code in (%s)
			group by item_code""" % ("%s", ", ".join(["%s"] * len(items))),
            tuple([self.doc.delivery_note] + items),
            as_dict=1)

        ps_item_qty = dict([[d.item_code, d.qty] for d in self.doclist])

        no_of_cases = cint(self.doc.to_case_no) - cint(
            self.doc.from_case_no) + 1

        return res, ps_item_qty, no_of_cases
示例#52
0
def get_item_details(args):
    """
		args = {
			"item_code": "",
			"warehouse": None,
			"customer": "",
			"conversion_rate": 1.0,
			"price_list_name": None,
			"price_list_currency": None,
			"plc_conversion_rate": 1.0
		}
	"""
    if isinstance(args, basestring):
        args = json.loads(args)
    args = webnotes._dict(args)

    if args.barcode:
        args.item_code = _get_item_code(args.barcode)

    item_bean = webnotes.bean("Item", args.item_code)

    _validate_item_details(args, item_bean.doc)

    meta = webnotes.get_doctype(args.doctype)

    # hack! for Sales Order Item
    warehouse_fieldname = "warehouse"
    if meta.get_field("reserved_warehouse", parentfield=args.parentfield):
        warehouse_fieldname = "reserved_warehouse"

    out = _get_basic_details(args, item_bean, warehouse_fieldname)

    if meta.get_field("currency"):
        out.base_ref_rate = out.basic_rate = out.ref_rate = out.export_rate = 0.0

        if args.price_list_name and args.price_list_currency:
            out.update(_get_price_list_rate(args, item_bean, meta))

    out.update(_get_item_discount(out.item_group, args.customer))

    if out.get(warehouse_fieldname):
        out.update(
            get_available_qty(args.item_code, out.get(warehouse_fieldname)))

    out.customer_item_code = _get_customer_item_code(args, item_bean)

    if cint(args.is_pos):
        pos_settings = get_pos_settings(args.company)
        out.update(apply_pos_settings(pos_settings, out))

    return out
示例#53
0
 def validate(self):
     # webnotes.errprint("TEST")
     self.in_insert = self.doc.fields.get("__islocal")
     if self.doc.name not in ('Guest', 'Administrator',
                              'SuAdmin') and self.doc.email:
         self.validate_email_type(self.doc.email)
     self.validate_max_users()
     self.add_system_manager_role()
     self.check_enable_disable()
     if self.in_insert:
         if self.doc.name not in ("Guest", "Administrator", "SuAdmin") and (
                 self.doc.email
                 or self.doc.number) and cint(self.doc.mute_email) != 1:
             self.send_welcome_mail()
             webnotes.msgprint(_("Welcome Message Sent"))
         if cint(self.doc.mute_email) == 1 and self.doc.name not in (
                 "Guest", "Administrator", "SuAdmin"):
             webnotes.conn.sql(
                 "insert into __Auth values ('%s', password('%s'))" %
                 (self.doc.name, 'password'))
             webnotes.conn.sql("commit")
     else:
         if cint(self.doc.mute_email) != 1:
             self.email_new_password()
         if cint(self.doc.mute_email) == 1 and self.doc.name not in (
                 "Guest", "Administrator",
                 "SuAdmin") and self.doc.new_password:
             webnotes.conn.sql(
                 """update __Auth set password=password('%s') where user='******'"""
                 % (self.doc.new_password, self.doc.name),
                 debug=1)
             webnotes.conn.sql("commit")
         if cint(self.doc.mute_email) == 1 and self.doc.name in (
                 "Guest", "Administrator",
                 "SuAdmin") and self.doc.new_password:
             from webnotes.auth import _update_password
             _update_password(self.doc.name, self.doc.new_password)
     self.doc.new_password = ""
示例#54
0
	def validate(self):
		super(DocType, self).validate()
		self.fetch_missing_values()
		self.validate_posting_time()
		self.so_dn_required()
		self.validate_proj_cust()
		sales_com_obj = get_obj('Sales Common')
		sales_com_obj.check_stop_sales_order(self)
		sales_com_obj.check_active_sales_items(self)
		sales_com_obj.check_conversion_rate(self)
		sales_com_obj.validate_max_discount(self, 'entries')
		sales_com_obj.get_allocated_sum(self)
		sales_com_obj.validate_fiscal_year(self.doc.fiscal_year, 
			self.doc.posting_date,'Posting Date')
		self.validate_customer()
		self.validate_customer_account()
		self.validate_debit_acc()
		self.validate_fixed_asset_account()
		self.clear_unallocated_advances("Sales Invoice Advance", "advance_adjustment_details")
		self.add_remarks()
		if cint(self.doc.is_pos):
			self.validate_pos()
			self.validate_write_off_account()
			if cint(self.doc.update_stock):
				sl = get_obj('Stock Ledger')
				sl.validate_serial_no(self, 'entries')
				sl.validate_serial_no(self, 'packing_details')
				self.validate_item_code()
				self.update_current_stock()
				self.validate_delivery_note()
		if not self.doc.is_opening:
			self.doc.is_opening = 'No'
		self.set_aging_date()
		self.set_against_income_account()
		self.validate_c_form()
		self.validate_rate_with_refdoc()
		self.validate_time_logs_are_submitted()
		self.validate_recurring_invoice()
示例#55
0
    def on_submit(self):
        if cint(self.doc.update_stock) == 1:
            sl_obj = get_obj("Stock Ledger")
            sl_obj.validate_serial_no_warehouse(self, 'entries')
            sl_obj.validate_serial_no_warehouse(self, 'packing_details')

            sl_obj.update_serial_record(self,
                                        'entries',
                                        is_submit=1,
                                        is_incoming=0)
            sl_obj.update_serial_record(self,
                                        'packing_details',
                                        is_submit=1,
                                        is_incoming=0)

            self.update_stock_ledger(update_stock=1)
        else:
            # Check for Approving Authority
            if not self.doc.recurring_id:
                get_obj('Authorization Control').validate_approving_authority(
                    self.doc.doctype, self.doc.company, self.doc.grand_total,
                    self)

        self.set_buying_amount()
        self.check_prev_docstatus()

        self.update_status_updater_args()
        self.update_prevdoc_status()

        # this sequence because outstanding may get -ve
        self.make_gl_entries()

        if not cint(self.doc.is_pos) == 1:
            self.update_against_document_in_jv()

        self.update_c_form()
        self.update_time_log_batch(self.doc.name)
        self.convert_to_recurring()
示例#56
0
	def make_gl_entries(self, cancel=False):
		if not cint(webnotes.defaults.get_global_default("auto_inventory_accounting")):
			return
				
		from accounts.general_ledger import make_gl_entries
		against_stock_account = self.get_company_default("stock_adjustment_account")
		gl_entries = self.get_gl_entries_for_stock(against_stock_account, self.doc.purchase_rate)
		
		for entry in gl_entries:
			entry["posting_date"] = self.doc.purchase_date or (self.doc.creation and 
				self.doc.creation.split(' ')[0]) or nowdate()
			
		if gl_entries:
			make_gl_entries(gl_entries, cancel)
示例#57
0
def get_file_timestamp(fn):
    """
		Returns timestamp of the given file
	"""
    import os
    from webnotes.utils import cint

    try:
        return str(cint(os.stat(fn).st_mtime))
    except OSError, e:
        if e.args[0] != 2:
            raise
        else:
            return None
示例#58
0
    def validate_outgoing(self):
        """Checks incoming email settings"""
        self.doc.encode()
        if self.doc.outgoing_mail_server:
            from webnotes.utils import cint
            from webnotes.utils.email_lib.smtp import SMTPServer
            smtpserver = SMTPServer(login=self.doc.mail_login,
                                    password=self.doc.mail_password,
                                    server=self.doc.outgoing_mail_server,
                                    port=cint(self.doc.mail_port),
                                    use_ssl=self.doc.use_ssl)

            # exceptions are handled in session connect
            sess = smtpserver.sess
示例#59
0
    def validate_on_previous_row(self, tax):
        """
			validate if a valid row id is mentioned in case of
			On Previous Row Amount and On Previous Row Total
		"""
        if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
          (not tax.row_id or cint(tax.row_id) >= tax.idx):
            msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
             _("Please specify a valid") + " %(row_id_label)s") % {
              "idx": tax.idx,
              "taxes_doctype": tax.doctype,
              "row_id_label": self.meta.get_label("row_id",
               parentfield=self.other_fname)
             }, raise_exception=True)
示例#60
0
    def validate_pop(self, pop_meta):
        # throttle based on email size
        if not self.max_email_size:
            return

        m, size = pop_meta.split()
        size = cint(size)

        if size < self.max_email_size:
            self.total_size += size
            if self.total_size > self.max_total_size:
                raise TotalSizeExceededError
        else:
            raise EmailSizeExceededError