Example #1
0
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
	if 'System Manager' in webnotes.user.roles:
		webnotes.response['server_messages'] = """Oops! \
			Your subscription expired on <b>%s</b>.
			
			Nothing catastrophic.
			
			Just drop in a mail at <b>[email protected]</b> and \
			we will guide you to get your account re-activated.""" % formatdate(conf.expires_on)
	else:
		webnotes.response['server_messages'] = """Oops! \
			Your subscription expired on <b>%s</b>.
			
			Nothing catastrophic.
					
			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.""" % formatdate(conf.expires_on)
	
	webnotes.response['message'] = 'Account Expired'
	raise webnotes.AuthenticationError
Example #2
0
	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)
		else:
			webnotes.msgprint("User Remarks is mandatory", raise_exception=1)
	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)
		else:
			webnotes.msgprint("User Remarks is mandatory", raise_exception=1)
Example #4
0
	def get_msg_html(self, out):
		with_value = [o[1] for o in out if o[0]]
		
		if with_value:
			with_value = "\n".join(with_value)
		else:
			with_value = "<p>There were no updates in the items selected for this digest.</p>"
		
		# seperate out no value items
		no_value = [o[1] for o in out if not o[0]]
		if no_value:
			no_value = """<h4>No Updates For:</h4>""" + "\n".join(no_value)
		
		date = self.doc.frequency == "Daily" and formatdate(self.from_date) or \
			"%s to %s" % (formatdate(self.from_date), formatdate(self.to_date))
		
		msg = digest_template % {
				"digest": self.doc.frequency + " Digest",
				"date": date,
				"company": self.doc.company,
				"with_value": with_value,
				"no_value": no_value or ""
			}
		
		return msg
Example #5
0
    def get_msg_html(self, out):
        with_value = "\n".join([o[1] for o in out if o[0]])

        # seperate out no value items
        no_value = [o[1] for o in out if not o[0]]
        if no_value:
            no_value = """<hr><h4>No Updates For:</h4><br>""" + "\n".join(
                no_value)

        date = self.doc.frequency == "Daily" and formatdate(self.from_date) or \
         "%s to %s" % (formatdate(self.from_date), formatdate(self.to_date))

        msg = """<h2>%(digest)s</h2>
			<p style='color: grey'>%(date)s</p>
			<h4>%(company)s</h4>
			<hr>
			%(with_value)s
			%(no_value)s""" % {
            "digest": self.doc.frequency + " Digest",
            "date": date,
            "company": self.doc.company,
            "with_value": with_value,
            "no_value": no_value or ""
        }

        return msg
Example #6
0
    def validate_leave_overlap(self):
        for d in sql(
            """select name, leave_type, posting_date, from_date, to_date 
			from `tabLeave Application` 
			where 
			(from_date <= %(to_date)s and to_date >= %(from_date)s)
			and employee = %(employee)s
			and docstatus = 1 
			and name != %(name)s""",
            self.doc.fields,
            as_dict=1,
        ):

            msgprint(
                "Employee : %s has already applied for %s between %s and %s on %s. Please refer Leave Application : %s"
                % (
                    self.doc.employee,
                    cstr(d["leave_type"]),
                    formatdate(d["from_date"]),
                    formatdate(d["to_date"]),
                    formatdate(d["posting_date"]),
                    d["name"],
                ),
                raise_exception=1,
            )
Example #7
0
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
    if 'System Manager' in webnotes.user.roles:
        webnotes.response['server_messages'] = """Oops! \
			Your subscription expired on <b>%s</b>.
			
			Nothing catastrophic.
			
			Just drop in a mail at <b>[email protected]</b> and \
			we will guide you to get your account re-activated.""" % formatdate(
            conf.expires_on)
    else:
        webnotes.response['server_messages'] = """Oops! \
			Your subscription expired on <b>%s</b>.
			
			Nothing catastrophic.
					
			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.""" % formatdate(
            conf.expires_on)

    webnotes.response['message'] = 'Account Expired'
    raise webnotes.AuthenticationError
Example #8
0
    def get_msg_html(self, out):
        with_value = [o[1] for o in out if o[0]]

        if with_value:
            with_value = "\n".join(with_value)
        else:
            with_value = "<p>There were no updates in the items selected for this digest.</p>"

        # seperate out no value items
        no_value = [o[1] for o in out if not o[0]]
        if no_value:
            no_value = """<hr><h4>No Updates For:</h4><br>""" + "\n".join(
                no_value)

        date = self.doc.frequency == "Daily" and formatdate(self.from_date) or \
         "%s to %s" % (formatdate(self.from_date), formatdate(self.to_date))

        msg = digest_template % {
            "digest": self.doc.frequency + " Digest",
            "date": date,
            "company": self.doc.company,
            "with_value": with_value,
            "no_value": no_value or ""
        }

        return msg
Example #9
0
    def validate_leave_overlap(self):
        if not self.doc.name:
            self.doc.name = "New Leave Application"

        for d in webnotes.conn.sql(
            """select name, leave_type, posting_date, 
			from_date, to_date 
			from `tabLeave Application` 
			where 
			employee = %(employee)s
			and docstatus < 2
			and status in ("Open", "Approved")
			and (from_date between %(from_date)s and %(to_date)s 
				or to_date between %(from_date)s and %(to_date)s
				or %(from_date)s between from_date and to_date)
			and name != %(name)s""",
            self.doc.fields,
            as_dict=1,
        ):

            msgprint(
                'Employee : %s has already applied for %s between %s and %s on %s. Please refer Leave Application : <a href="#Form/Leave Application/%s">%s</a>'
                % (
                    self.doc.employee,
                    cstr(d["leave_type"]),
                    formatdate(d["from_date"]),
                    formatdate(d["to_date"]),
                    formatdate(d["posting_date"]),
                    d["name"],
                    d["name"],
                ),
                raise_exception=OverlapError,
            )
Example #10
0
	def get_msg_html(self, out):
		with_value = "\n".join([o[1] for o in out if o[0]])
		
		# seperate out no value items
		no_value = [o[1] for o in out if not o[0]]
		if no_value:
			no_value = """<hr><h4>No Updates For:</h4><br>""" + "\n".join(no_value)
		
		date = self.doc.frequency == "Daily" and formatdate(self.from_date) or \
			"%s to %s" % (formatdate(self.from_date), formatdate(self.to_date))
		
		msg = """<h2>%(digest)s</h2>
			<p style='color: grey'>%(date)s</p>
			<h4>%(company)s</h4>
			<hr>
			%(with_value)s
			%(no_value)s""" % {
				"digest": self.doc.frequency + " Digest",
				"date": date,
				"company": self.doc.company,
				"with_value": with_value,
				"no_value": no_value or ""
			}
		
		return msg
    def upload_accounts_transactions(self):
        import csv

        data = csv.reader(self.get_csv_data().splitlines())

        abbr = sql("select concat(' - ',abbr) as abbr from tabCompany where name=%s", self.doc.company)
        updated = 0
        jv_name = ""
        # 		jv = Document('Journal Voucher')
        global line, jv, name, jv_go
        for line in data:
            if len(line) >= 7:  # Minimum no of fields
                if line[3] != jv_name:  # Create JV
                    if jv_name != "":
                        jv_go = get_obj("Journal Voucher", name, with_children=1)
                        jv_go.validate()
                        jv_go.on_submit()

                    jv_name = line[3]
                    jv = Document("Journal Voucher")
                    jv.voucher_type = line[0]
                    jv.naming_series = line[1]
                    jv.voucher_date = formatdate(line[2])
                    jv.posting_date = formatdate(line[2])
                    # 					jv.name = line[3]
                    jv.fiscal_year = self.doc.fiscal_year
                    jv.company = self.doc.company
                    jv.remark = len(line) == 8 and line[3] + " " + line[7] or line[3] + " Uploaded Record"
                    jv.docstatus = 1
                    jv.save(1)
                    name = jv.name

                    jc = addchild(jv, "entries", "Journal Voucher Detail", 0)
                    jc.account = line[4] + abbr[0][0]
                    jc.cost_center = len(line) == 9 and line[8] or self.doc.default_cost_center
                    if line[5] != "":
                        jc.debit = line[5]
                    else:
                        jc.credit = line[6]
                    jc.save()

                else:  # Create JV Child
                    jc = addchild(jv, "entries", "Journal Voucher Detail", 0)
                    jc.account = line[4] + abbr[0][0]
                    jc.cost_center = len(line) == 9 and line[8] or self.doc.default_cost_center
                    if line[5] != "":
                        jc.debit = line[5]
                    else:
                        jc.credit = line[6]
                    jc.save()
            else:
                msgprint("[Ignored] Incorrect format: %s" % str(line))
        if jv_name != "":
            jv_go = get_obj("Journal Voucher", name, with_children=1)
            jv_go.validate()
            jv_go.on_submit()

        msgprint("<b>%s</b> items updated" % updated)
Example #12
0
 def validate_bill_no(self):
     if self.doc.bill_no and self.doc.bill_no.lower().strip() not in ["na", "not applicable", "none"]:
         b_no = sql(
             "select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` where bill_no = '%s' and credit_to = '%s' and docstatus = 1 and name != '%s' "
             % (self.doc.bill_no, self.doc.credit_to, self.doc.name)
         )
         if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
             msgprint(
                 "Please check you have already booked expense against Bill No. %s in Purchase Invoice %s"
                 % (cstr(b_no[0][0]), cstr(b_no[0][1]))
             )
             raise Exception, "Validation Error"
         if not self.doc.remarks:
             self.doc.remarks = (
                 (self.doc.remarks or "")
                 + "\n"
                 + ("Against Bill %s dated %s" % (self.doc.bill_no, formatdate(self.doc.bill_date)))
             )
             if self.doc.ded_amount:
                 self.doc.remarks = (
                     (self.doc.remarks or "")
                     + "\n"
                     + ("Grand Total: %s, Tax Deduction Amount: %s" % (self.doc.grand_total, self.doc.ded_amount))
                 )
     else:
         if not self.doc.remarks:
             self.doc.remarks = "No Remarks"
Example #13
0
	def convert_to_simple_type(self, v, formatted=0):
		from webnotes.utils import formatdate, fmt_money

		if isinstance(v, (datetime.date, datetime.timedelta, datetime.datetime, long)):
			if isinstance(v, datetime.date):
				v = unicode(v)
				if formatted:
					v = formatdate(v)
		
			# time
			elif isinstance(v, (datetime.timedelta, datetime.datetime)):
				v = unicode(v)
				
			# long
			elif isinstance(v, long): 
				v=int(v)

		# convert to strings... (if formatted)
		if formatted:
			if isinstance(v, float):
				v=fmt_money(v)
			elif isinstance(v, int):
				v = unicode(v)

		return v
Example #14
0
    def convert_to_simple_type(self, v, formatted=0):
        import datetime
        from webnotes.utils import formatdate, fmt_money

        # date
        if type(v) == datetime.date:
            v = str(v)
            if formatted:
                v = formatdate(v)

        # time
        elif type(v) == datetime.timedelta:
            h = int(v.seconds / 60 / 60)
            v = str(h) + ':' + str(v.seconds / 60 - h * 60)
            if v[1] == ':':
                v = '0' + v

        # datetime
        elif type(v) == datetime.datetime:
            v = str(v)

        # long
        elif type(v) == long:
            v = int(v)

        # convert to strings... (if formatted)
        if formatted:
            if type(v) == float:
                v = fmt_money(v)
            if type(v) == int:
                v = str(v)

        return v
Example #15
0
    def validate_block_days(self):
        from_date = getdate(self.doc.from_date)
        to_date = getdate(self.doc.to_date)

        department = webnotes.conn.get_value("Employee", self.doc.employee, "department")
        if department:
            block_list = webnotes.conn.get_value("Department", department, "holiday_block_list")
            if block_list:
                if self.is_user_in_allow_list(block_list):
                    return
                for d in webnotes.conn.sql(
                    """select block_date, reason from
					`tabHoliday Block List Date` where parent=%s""",
                    block_list,
                    as_dict=1,
                ):
                    block_date = getdate(d.block_date)
                    if block_date > from_date and block_date < to_date:
                        webnotes.msgprint(
                            _("You cannot apply for a leave on the following date because it is blocked")
                            + ": "
                            + formatdate(d.block_date)
                            + _(" Reason: ")
                            + d.reason
                        )
                        raise LeaveDayBlockedError
Example #16
0
	def create_remarks(self):
		r = []
		if self.doc.cheque_no :
			if self.doc.cheque_date:
				r.append('Via cheque #%s dated %s' % (self.doc.cheque_no, formatdate(self.doc.cheque_date)))
			else :
				msgprint("Please enter cheque date")
				raise Exception
		
		for d in getlist(self.doclist, 'entries'):
			if d.against_invoice and d.credit:
				currency = sql("select currency from `tabSales Invoice` where name = '%s'" % d.against_invoice)
				currency = currency and currency[0][0] or ''
				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 = 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']:
					bill_no = bill_no and bill_no[0]
					r.append('%s %s against Bill %s dated %s' % (bill_no[2] and cstr(bill_no[2]) or '', fmt_money(flt(d.debit)), bill_no[0], bill_no[1] and formatdate(bill_no[1].strftime('%Y-%m-%d')) or ''))
		if self.doc.ded_amount:
			r.append("TDS Amount: %s" % self.doc.ded_amount)
	
		if self.doc.user_remark:
			r.append("User Remark : %s"%self.doc.user_remark)

		if r:
			self.doc.remark = ("\n").join(r)
Example #17
0
	def convert_to_simple_type(self, v, formatted=0):
		import datetime
		from webnotes.utils import formatdate, fmt_money

		# date
		if type(v)==datetime.date:
			v = unicode(v)
			if formatted:
				v = formatdate(v)
		
		# time	
		elif type(v)==datetime.timedelta:
			v = unicode(v)
		
		# datetime
		elif type(v)==datetime.datetime:
			v = unicode(v)
		
		# long
		elif type(v)==long: 
			v=int(v)
		
		# convert to strings... (if formatted)
		if formatted:
			if type(v)==float:
				v=fmt_money(v)
			if type(v)==int:
				v=str(v)
		
		return v
Example #18
0
def get_transaction_list(doctype, start, additional_fields=None):
	# find customer id
	customer = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user}, 
		"customer")
	
	if customer:
		if additional_fields:
			additional_fields = ", " + ", ".join(("`%s`" % f for f in additional_fields))
		else:
			additional_fields = ""
			
		transactions = webnotes.conn.sql("""select name, creation, currency, grand_total_export
			%s
			from `tab%s` where customer=%s and docstatus=1
			order by creation desc
			limit %s, 20""" % (additional_fields, doctype, "%s", "%s"), 
			(customer, cint(start)), as_dict=True)
		for doc in transactions:
			items = webnotes.conn.sql_list("""select item_name
				from `tab%s Item` where parent=%s limit 6""" % (doctype, "%s"), doc.name)
			doc.items = ", ".join(items[:5]) + ("..." if (len(items) > 5) else "")
			doc.creation = formatdate(doc.creation)
		return transactions
	else:
		return []
Example #19
0
def get_transaction_list(doctype, start):
    # find customer id
    customer = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user}, "customer")

    if customer:
        transactions = webnotes.conn.sql(
            """select name, creation, currency, grand_total_export 
			from `tab%s` where customer=%s and docstatus=1
			order by creation desc
			limit %s, 20"""
            % (doctype, "%s", "%s"),
            (customer, cint(start)),
            as_dict=True,
        )
        for doc in transactions:
            doc.items = ", ".join(
                webnotes.conn.sql_list(
                    """select item_name
				from `tab%s Item` where parent=%s limit 5"""
                    % (doctype, "%s"),
                    doc.name,
                )
            )
            doc.creation = formatdate(doc.creation)
        return transactions
    else:
        return []
Example #20
0
	def convert_to_simple_type(self, v, formatted=0):
		from webnotes.utils import formatdate, fmt_money

		if isinstance(v, (datetime.date, datetime.timedelta, datetime.datetime, long)):
			if isinstance(v, datetime.date):
				v = unicode(v)
				if formatted:
					v = formatdate(v)
		
			# time
			elif isinstance(v, (datetime.timedelta, datetime.datetime)):
				v = unicode(v)
				
			# long
			elif isinstance(v, long): 
				v=int(v)

		# convert to strings... (if formatted)
		if formatted:
			if isinstance(v, float):
				v=fmt_money(v)
			elif isinstance(v, int):
				v = unicode(v)

		return v
Example #21
0
	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
		
		for d in getlist(self.doclist, 'entries'):
			if d.against_invoice and d.credit:
				currency = sql("select currency from `tabSales Invoice` where name = '%s'" % d.against_invoice)
				currency = currency and currency[0][0] or ''
				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 = 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']:
					bill_no = bill_no and bill_no[0]
					r.append('%s %s against Bill %s dated %s' % (bill_no[2] and cstr(bill_no[2]) or '', fmt_money(flt(d.debit)), bill_no[0], bill_no[1] and formatdate(bill_no[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)
Example #22
0
def check_if_expired():
    """check if account is expired. If expired, do not allow login"""
    from webnotes import conf

    # check if expires_on is specified
    if not "expires_on" in conf:
        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."""
    else:
        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.msgprint(msg)

    webnotes.response["message"] = "Account Expired"
    raise webnotes.AuthenticationError
Example #23
0
def check_if_expired():
    """check if account is expired. If expired, do not allow login"""
    from webnotes import conf
    # check if expires_on is specified
    if not 'expires_on' in conf: 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."""
    else:
        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.msgprint(msg)

    webnotes.response['message'] = 'Account Expired'
    raise webnotes.AuthenticationError
Example #24
0
def datetime_in_user_format(date_time):
    if not date_time:
        return ""
    if isinstance(date_time, basestring):
        date_time = get_datetime(date_time)
    from webnotes.utils import formatdate
    return formatdate(date_time.date()) + " " + date_time.strftime("%H:%M")
Example #25
0
def get_transaction_list(doctype, start, additional_fields=None):
    # find customer id
    customer = webnotes.conn.get_value("Contact",
                                       {"email_id": webnotes.session.user},
                                       "customer")

    if customer:
        if additional_fields:
            additional_fields = ", " + ", ".join(
                ("`%s`" % f for f in additional_fields))
        else:
            additional_fields = ""

        transactions = webnotes.conn.sql(
            """select name, creation, currency, grand_total_export
			%s
			from `tab%s` where customer=%s and docstatus=1
			order by creation desc
			limit %s, 20""" % (additional_fields, doctype, "%s", "%s"),
            (customer, cint(start)),
            as_dict=True)
        for doc in transactions:
            items = webnotes.conn.sql_list(
                """select item_name
				from `tab%s Item` where parent=%s limit 6""" % (doctype, "%s"), doc.name)
            doc.items = ", ".join(items[:5]) + ("..." if
                                                (len(items) > 5) else "")
            doc.creation = formatdate(doc.creation)
        return transactions
    else:
        return []
Example #26
0
	def convert_to_simple_type(self, v, formatted=0):
		import datetime
		from webnotes.utils import formatdate, fmt_money

		# date
		if type(v)==datetime.date:
			v = str(v)
			if formatted:
				v = formatdate(v)
		
		# time	
		elif type(v)==datetime.timedelta:
			h = int(v.seconds/60/60)
			v = str(h) + ':' + str(v.seconds/60 - h*60)
			if v[1]==':': 
				v='0'+v
		
		# datetime
		elif type(v)==datetime.datetime:
			v = str(v)
		
		# long
		elif type(v)==long: 
			v=int(v)
		
		# convert to strings... (if formatted)
		if formatted:
			if type(v)==float:
				v=fmt_money(v)
			if type(v)==int:
				v=str(v)
		
		return v
Example #27
0
def datetime_in_user_format(date_time):
	if not date_time:
		return ""
	if isinstance(date_time, basestring):
		date_time = get_datetime(date_time)
	from webnotes.utils import formatdate
	return formatdate(date_time.date()) + " " + date_time.strftime("%H:%M")
Example #28
0
def validate_fiscal_year(date, fiscal_year, label="Date"):
    years = [f[0] for f in get_fiscal_years(date, label=label)]
    if fiscal_year not in years:
        webnotes.msgprint(
            ("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + ": '%(fiscal_year)s'")
            % {"label": label, "posting_date": formatdate(date), "fiscal_year": fiscal_year},
            raise_exception=1,
        )
Example #29
0
def get_emails(start=0):
	emails = webnotes.conn.sql("""select name, subject, status, creation 
		from `tabEmail Inbox` where raised_by=%s 
		order by modified desc
		limit %s, 20""", (webnotes.session.user, cint(start)), as_dict=True)
	for t in emails:
		t.creation = formatdate(t.creation)
	
	return emails
Example #30
0
	def validate_fiscal_year(self, fiscal_year, transaction_date, label):
		from accounts.utils import get_fiscal_year
		if get_fiscal_year(transaction_date)[0] != fiscal_year:
			msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
				": '%(fiscal_year)s'") % {
					"label": label,
					"posting_date": formatdate(transaction_date),
					"fiscal_year": fiscal_year
				}, raise_exception=1)
Example #31
0
def get_tickets(start=0):
	tickets = webnotes.conn.sql("""select name, subject, status, creation 
		from `tabSupport Ticket` where raised_by=%s 
		order by modified desc
		limit %s, 20""", (webnotes.session.user, cint(start)), as_dict=True)
	for t in tickets:
		t.creation = formatdate(t.creation)
	
	return tickets
Example #32
0
def get_tickets(start=0):
	tickets = webnotes.conn.sql("""select name, subject, status, creation 
		from `tabSupport Ticket` where raised_by=%s 
		order by modified desc
		limit %s, 20""", (webnotes.session.user, cint(start)), as_dict=True)
	for t in tickets:
		t.creation = formatdate(t.creation)
	
	return tickets
Example #33
0
	def validate_fiscal_year(self, fiscal_year, transaction_date, label):
		from accounts.utils import get_fiscal_year
		if get_fiscal_year(transaction_date)[0] != fiscal_year:
			msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
				": '%(fiscal_year)s'") % {
					"label": label,
					"posting_date": formatdate(transaction_date),
					"fiscal_year": fiscal_year
				}, raise_exception=1)
Example #34
0
def validate_fiscal_year(date, fiscal_year, label="Date"):
	years = [f[0] for f in get_fiscal_years(date)]
	if fiscal_year not in years:
		webnotes.msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
			": '%(fiscal_year)s'") % {
				"label": label,
				"posting_date": formatdate(date),
				"fiscal_year": fiscal_year
			}, raise_exception=1)
Example #35
0
    def validate_leave_overlap(self):
        for d in sql(
                """select name, leave_type, posting_date, from_date, to_date 
			from `tabLeave Application` 
			where 
			(from_date <= %(to_date)s and to_date >= %(from_date)s)
			and employee = %(employee)s
			and docstatus = 1 
			and name != %(name)s""",
                self.doc.fields,
                as_dict=1):

            msgprint(
                "Employee : %s has already applied for %s between %s and %s on %s. Please refer Leave Application : %s"
                % (self.doc.employee, cstr(d['leave_type']),
                   formatdate(d['from_date']), formatdate(d['to_date']),
                   formatdate(d['posting_date']), d['name']),
                raise_exception=1)
Example #36
0
def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
	# if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
	cond = ""
	if fiscal_year:
		cond = "name = '%s'" % fiscal_year
	else:
		cond = "'%s' >= year_start_date and '%s' <= year_end_date" % \
			(date, date)
	fy = webnotes.conn.sql("""select name, year_start_date, year_end_date
		from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
	
	if not fy:
		error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date))
		error_msg = """{msg}: {date}""".format(msg=_("Fiscal Year does not exist for date"), 
			date=formatdate(date))
		if verbose: webnotes.msgprint(error_msg)
		raise FiscalYearError, error_msg
	
	return fy
	def show_block_day_warning(self):
		from hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates		

		block_dates = get_applicable_block_dates(self.doc.from_date, self.doc.to_date, 
			self.doc.employee, self.doc.company, all_lists=True)
			
		if block_dates:
			webnotes.msgprint(_("Warning: Leave application contains following block dates") + ":")
			for d in block_dates:
				webnotes.msgprint(formatdate(d.block_date) + ": " + d.reason)
Example #38
0
	def show_block_day_warning(self):
		from hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates		

		block_dates = get_applicable_block_dates(self.doc.from_date, self.doc.to_date, 
			self.doc.employee, self.doc.company, all_lists=True)
			
		if block_dates:
			webnotes.msgprint(_("Warning: Leave application contains following block dates") + ":")
			for d in block_dates:
				webnotes.msgprint(formatdate(d.block_date) + ": " + d.reason)
Example #39
0
    def get_next_sending(self):
        import datetime

        start_date, end_date = self.get_start_end_dates()

        send_date = end_date + datetime.timedelta(days=1)

        from webnotes.utils import formatdate
        str_date = formatdate(str(send_date))

        self.doc.next_send = str_date + " at midnight"

        return send_date
Example #40
0
	def validate_block_days(self):
		from hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates

		block_dates = get_applicable_block_dates(self.doc.from_date, self.doc.to_date, 
			self.doc.employee, self.doc.company)
			
		if block_dates:
			webnotes.msgprint(_("Following dates are blocked for Leave") + ":")
			for d in block_dates:
				webnotes.msgprint(formatdate(d.block_date) + ": " + d.reason)
				
			if self.doc.status == "Approved":
				raise LeaveDayBlockedError
Example #41
0
	def get_next_sending(self):
		import datetime
		
		start_date, end_date = self.get_start_end_dates()
		
		send_date = end_date + datetime.timedelta(days=1)
		
		from webnotes.utils import formatdate
		str_date = formatdate(str(send_date))

		self.doc.next_send = str_date + " at midnight"

		return send_date
Example #42
0
    def get_next_sending(self):
        from_date, to_date = self.get_from_to_date()

        send_date = to_date + timedelta(days=1)

        if self.doc.frequency == "Daily":
            next_send_date = send_date + timedelta(days=1)
        elif self.doc.frequency == "Weekly":
            next_send_date = send_date + timedelta(weeks=1)
        else:
            next_send_date = send_date + relativedelta(months=1)
        self.doc.next_send = formatdate(next_send_date) + " at midnight"

        return send_date
Example #43
0
	def get_next_sending(self):
		from_date, to_date = self.get_from_to_date()

		send_date = to_date + timedelta(days=1)
		
		if self.doc.frequency == "Daily":
			next_send_date = send_date + timedelta(days=1)
		elif self.doc.frequency == "Weekly":
			next_send_date = send_date + timedelta(weeks=1)
		else:
			next_send_date = send_date + relativedelta(months=1)
		self.doc.next_send = formatdate(next_send_date) + " at midnight"
		
		return send_date
Example #44
0
File: bin.py Project: alvz/erpnext
	def send_email_notification(self, doc_type, doc_name, bean):
		""" Notify user about auto creation of indent"""
		
		from webnotes.utils.email_lib import sendmail
		email_list=[d[0] for d in sql("""select distinct r.parent from tabUserRole r, tabProfile p
			where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
			and r.role in ('Purchase Manager','Material Manager') 
			and p.name not in ('Administrator', 'All', 'Guest')""")]
		
		msg="""A new Material Request has been raised for Item: %s and Warehouse: %s \
			on %s due to %s: %s. See %s: %s """ % (self.doc.item_code, self.doc.warehouse,
				formatdate(), doc_type, doc_name, bean.doc.doctype, 
				get_url_to_form(bean.doc.doctype, bean.doc.name))
		
		sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
Example #45
0
def get_fiscal_years(date, verbose=1):
	# if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
	fy = webnotes.conn.sql("""select name, year_start_date, 
		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
			as year_end_date
		from `tabFiscal Year`
		where %s >= year_start_date and %s < adddate(year_start_date, interval 1 year)
		order by year_start_date desc""", (date, date))
	
	if not fy:
		error_msg = """%s not in any Fiscal Year""" % formatdate(date)
		if verbose: webnotes.msgprint(error_msg)
		raise FiscalYearError, error_msg
	
	return fy
Example #46
0
def validate_end_of_life(item_code, end_of_life=None, verbose=1):
	if not end_of_life:
		end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
	
	from webnotes.utils import getdate, now_datetime, formatdate
	if end_of_life and getdate(end_of_life) > now_datetime().date():
		msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
			" %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
			"in Item master") % {
				"item_code": item_code,
				"date": formatdate(end_of_life),
				"end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
			}
		
		_msgprint(msg, verbose)
Example #47
0
def validate_end_of_life(item_code, end_of_life=None, verbose=1):
    if not end_of_life:
        end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")

    from webnotes.utils import getdate, now_datetime, formatdate
    if end_of_life and getdate(end_of_life) <= now_datetime().date():
        msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
         " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
         "in Item master") % {
          "item_code": item_code,
          "date": formatdate(end_of_life),
          "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
         }

        _msgprint(msg, verbose)
Example #48
0
def get_fiscal_years(date, verbose=1):
	# if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
	fy = webnotes.conn.sql("""select name, year_start_date, 
		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
			as year_end_date
		from `tabFiscal Year`
		where %s >= year_start_date and %s < adddate(year_start_date, interval 1 year)
		order by year_start_date desc""", (date, date))
	
	if not fy:
		error_msg = """%s not in any Fiscal Year""" % formatdate(date)
		if verbose: webnotes.msgprint(error_msg)
		raise FiscalYearError, error_msg
	
	return fy
Example #49
0
    def validate_leave_overlap(self):
        if not self.doc.name:
            self.doc.name = "New Leave Application"

        for d in webnotes.conn.sql("""select name, leave_type, posting_date, 
			from_date, to_date 
			from `tabLeave Application` 
			where 
			employee = %(employee)s
			and docstatus < 2
			and status in ("Open", "Approved")
			and (from_date between %(from_date)s and %(to_date)s 
				or to_date between %(from_date)s and %(to_date)s
				or %(from_date)s between from_date and to_date)
			and name != %(name)s""",
                                   self.doc.fields,
                                   as_dict=1):

            msgprint(
                "Employee : %s has already applied for %s between %s and %s on %s. Please refer Leave Application : <a href=\"#Form/Leave Application/%s\">%s</a>"
                % (self.doc.employee, cstr(d['leave_type']),
                   formatdate(d['from_date']), formatdate(d['to_date']),
                   formatdate(d['posting_date']), d['name'], d['name']),
                raise_exception=OverlapError)
Example #50
0
	def date_diff_list(self):
		import datetime
		#get from date 
		att_fr_date = self.doc.att_fr_date and self.doc.att_fr_date or ''
		
		#get to date
		att_to_date = self.doc.att_to_date and self.doc.att_to_date or ''

		if att_to_date:
			r = (getdate(self.doc.att_to_date)+datetime.timedelta(days=1)-getdate(self.doc.att_fr_date)).days
		else:
			r = 1
		dateList = [getdate(self.doc.att_fr_date)+datetime.timedelta(days=i) for i in range(0,r)]
		dt=([formatdate(cstr(date)) for date in dateList])
		
		return dt
Example #51
0
	def validate_bill_no(self):
		if self.doc.bill_no and self.doc.bill_no.lower().strip() \
				not in ['na', 'not applicable', 'none']:
			b_no = webnotes.conn.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` 
				where bill_no = %s and credit_to = %s and docstatus = 1 and name != %s""", 
				(self.doc.bill_no, self.doc.credit_to, self.doc.name))
			if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
				msgprint("Please check you have already booked expense against Bill No. %s \
					in Purchase Invoice %s" % (cstr(b_no[0][0]), cstr(b_no[0][1])), 
					raise_exception=1)
					
			if not self.doc.remarks and self.doc.bill_date:
				self.doc.remarks = (self.doc.remarks or '') + "\n" + ("Against Bill %s dated %s" 
					% (self.doc.bill_no, formatdate(self.doc.bill_date)))

		if not self.doc.remarks:
			self.doc.remarks = "No Remarks"
Example #52
0
def get_transaction_list(doctype, start):
	# find customer id
	customer = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user}, 
		"customer")
		
	if customer:
		transactions = webnotes.conn.sql("""select name, creation, currency, grand_total_export 
			from `tab%s` where customer=%s and docstatus=1
			order by creation desc
			limit %s, 20""" % (doctype, "%s", "%s"), (customer, cint(start)), as_dict=True)
		for doc in transactions:
			doc.items = ", ".join(webnotes.conn.sql_list("""select item_name
				from `tab%s Item` where parent=%s limit 5""" % (doctype, "%s"), doc.name))
			doc.creation = formatdate(doc.creation)
		return transactions
	else:
		return []
Example #53
0
    def convert_to_simple_type(self, v, formatted=0):
        try:
            import decimal  # for decimal Python 2.5 onwards
        except:
            pass
        import datetime
        from webnotes.utils import formatdate, fmt_money

        # date
        if type(v) == datetime.date:
            v = str(v)
            if formatted:
                v = formatdate(v)

        # time
        elif type(v) == datetime.timedelta:
            h = int(v.seconds / 60 / 60)
            v = str(h) + ':' + str(v.seconds / 60 - h * 60)
            if v[1] == ':':
                v = '0' + v

        # datetime
        elif type(v) == datetime.datetime:
            v = str(v)

        # long
        elif type(v) == long:
            v = int(v)

        # decimal
        try:
            if type(v) == decimal.Decimal:
                v = float(v)
        except:
            pass

        # convert to strings... (if formatted)
        if formatted:
            if type(v) == float:
                v = fmt_money(v)
            if type(v) == int:
                v = str(v)

        return v
Example #54
0
 def validate_bill_no(self):
     if self.doc.bill_no and self.doc.bill_no.lower().strip() not in [
             'na', 'not applicable', 'none'
     ]:
         b_no = sql(
             "select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` where bill_no = '%s' and credit_to = '%s' and docstatus = 1 and name != '%s' "
             % (self.doc.bill_no, self.doc.credit_to, self.doc.name))
         if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
             msgprint(
                 "Please check you have already booked expense against Bill No. %s in Purchase Invoice %s"
                 % (cstr(b_no[0][0]), cstr(b_no[0][1])))
             raise Exception, "Validation Error"
         if not self.doc.remarks:
             self.doc.remarks = (self.doc.remarks or '') + "\n" + (
                 "Against Bill %s dated %s" %
                 (self.doc.bill_no, formatdate(self.doc.bill_date)))
             if self.doc.ded_amount:
                 self.doc.remarks = (self.doc.remarks or '') + "\n" + (
                     "Grand Total: %s, Tax Deduction Amount: %s" %
                     (self.doc.grand_total, self.doc.ded_amount))
     else:
         if not self.doc.remarks:
             self.doc.remarks = "No Remarks"
Example #55
0
    def validate_due_date(self, posting_date, due_date):
        credit_days = (self.doc.credit_days or webnotes.conn.get_value(
            "Company", self.doc.company, "credit_days"))
        if credit_days is None:
            return

        posting_date, due_date = getdate(posting_date), getdate(due_date)
        diff = (due_date - posting_date).days

        if diff < 0:
            webnotes.throw(_("Due Date cannot be before Posting Date"))
        elif diff > credit_days:
            is_credit_controller = webnotes.conn.get_value(
                "Accounts Settings", None,
                "credit_controller") in webnotes.user.get_roles()

            if is_credit_controller:
                msgprint(
                    _("Note: Due Date exceeds the allowed credit days by {0} day(s)"
                      ).format(diff - credit_days))
            else:
                max_due_date = formatdate(add_days(posting_date, credit_days))
                webnotes.throw(
                    _("Due Date cannot be after {0}").format(max_due_date))
Example #56
0
    def get_standard_body(self, result):
        """
			Generate email body depending on the result
		"""
        from webnotes.utils import fmt_money
        from webnotes.model.doc import Document
        company = Document('Company', self.doc.company)
        currency = company.default_currency

        def table(args):
            table_body = ""
            if isinstance(args['body'], basestring):
                table_body = """\
					<tbody><tr>
						<td style='padding: 5px; font-size: 24px; \
						font-weight: bold; background: #F7F7F5'>""" + \
                 args['body'] + \
                 """\
						</td>
					</tr></tbody>"""

            elif isinstance(args['body'], list):
                body_rows = []
                for rows in args['body']:
                    for r in rows:
                        body_rows.append("""\
							<tr>
								<td style='padding: 5px; font-size: 24px; \
								font-weight: bold; background: #F7F7F5'>""" \
                          + r + """\
								</td>
							</tr>""")

                    body_rows.append(
                        "<tr><td style='background: #F7F7F5'><br></td></tr>")

                table_body = "<tbody>" + "".join(body_rows) + "</tbody>"

            table_head = """\
				<thead><tr>
					<td style='padding: 5px; background: #D8D8D4; font-size: 16px; font-weight: bold'>""" \
              + args['head'] + """\
					</td>
				</tr></thead>"""

            return "<table style='border-collapse: collapse; width: 100%;'>" \
             + table_head \
             + table_body \
             + "</table>"

        currency_amount_str = "<span style='color: grey; font-size: 12px'>%s</span> %s"

        body_dict = {

         'invoiced_amount': {
          'table': result.get('invoiced_amount') and \
           table({
            'head': 'Invoiced Amount',
            'body': currency_amount_str \
             % (currency, fmt_money(result['invoiced_amount'].get('debit')))
           }),
          'idx': 300,
          'value': result.get('invoiced_amount') and result['invoiced_amount'].get('debit')
         },

         'payables': {
          'table': result.get('payables') and \
           table({
            'head': 'Payables',
            'body': currency_amount_str \
             % (currency, fmt_money(result['payables'].get('credit')))
           }),
          'idx': 200,
          'value': result.get('payables') and result['payables'].get('credit')
         },

         'collections': {
          'table': result.get('collections') and \
           table({
            'head': 'Collections',
            'body': currency_amount_str \
             % (currency, fmt_money(result['collections'].get('credit')))
           }),
          'idx': 301,
          'value': result.get('collections') and result['collections'].get('credit')
         },

         'payments': {
          'table': result.get('payments') and \
           table({
            'head': 'Payments',
            'body': currency_amount_str \
             % (currency, fmt_money(result['payments'].get('debit')))
           }),
          'idx': 201,
          'value': result.get('payments') and result['payments'].get('debit')
         },

         'income': {
          'table': result.get('income') and \
           table({
            'head': 'Income',
            'body': currency_amount_str \
             % (currency, fmt_money(result['income'].get('value')))
           }),
          'idx': 302,
          'value': result.get('income') and result['income'].get('value')
         },

         'income_year_to_date': {
          'table': result.get('income_year_to_date') and \
           table({
            'head': 'Income Year To Date',
            'body': currency_amount_str \
             % (currency, fmt_money(result['income_year_to_date'].get('value')))
           }),
          'idx': 303,
          'value': result.get('income_year_to_date') and \
            result['income_year_to_date'].get('value')
         },

         'expenses_booked': {
          'table': result.get('expenses_booked') and \
           table({
            'head': 'Expenses Booked',
            'body': currency_amount_str \
             % (currency, fmt_money(result['expenses_booked'].get('value')))
           }),
          'idx': 202,
          'value': result.get('expenses_booked') and result['expenses_booked'].get('value')
         },

         'bank_balance': {
          'table': result.get('bank_balance') and \
           table({
            'head': 'Bank Balance',
            'body': [
             [
              "<span style='font-size: 16px; font-weight: normal'>%s</span>" \
               % bank['name'],
              currency_amount_str % (currency, fmt_money(bank.get('value')))
             ] for bank in (isinstance(result['bank_balance'], list) and \
              result['bank_balance'] or \
              [result['bank_balance']])
            ]
           }),
          'idx': 0,
          'value': 0.1
         },

         'new_leads': {
          'table': result.get('new_leads') and \
           table({
            'head': 'New Leads',
            'body': '%s' % result['new_leads'].get('count')
           }),
          'idx': 100,
          'value': result.get('new_leads') and result['new_leads'].get('count')
         },

         'new_enquiries': {
          'table': result.get('new_enquiries') and \
           table({
            'head': 'New Enquiries',
            'body': '%s' % result['new_enquiries'].get('count')
           }),
          'idx': 101,
          'value': result.get('new_enquiries') and result['new_enquiries'].get('count')
         },

         'new_quotations': {
          'table': result.get('new_quotations') and \
           table({
            'head': 'New Quotations',
            'body': '%s' % result['new_quotations'].get('count')
           }),
          'idx': 102,
          'value': result.get('new_quotations') and result['new_quotations'].get('count')
         },

         'new_sales_orders': {
          'table': result.get('new_sales_orders') and \
           table({
            'head': 'New Sales Orders',
            'body': '%s' % result['new_sales_orders'].get('count')
           }),
          'idx': 103,
          'value': result.get('new_sales_orders') and result['new_sales_orders'].get('count')
         },

         'new_purchase_orders': {
          'table': result.get('new_purchase_orders') and \
           table({
            'head': 'New Purchase Orders',
            'body': '%s' % result['new_purchase_orders'].get('count')
           }),
          'idx': 104,
          'value': result.get('new_purchase_orders') and \
            result['new_purchase_orders'].get('count')
         },

         'new_transactions': {
          'table': result.get('new_transactions') and \
           table({
            'head': 'New Transactions',
            'body': '%s' % result['new_transactions'].get('count')
           }),
          'idx': 105,
          'value': result.get('new_transactions') and result['new_transactions'].get('count')
         }

         #'stock_below_rl':
        }

        table_list = []

        # Sort these keys depending on idx value
        bd_keys = sorted(body_dict, key=lambda x: \
         (-webnotes.utils.flt(body_dict[x]['value']), body_dict[x]['idx']))

        new_section = False

        for k in bd_keys:
            if self.doc.fields[k]:
                if k in result:
                    if not body_dict[k].get('value') and not new_section:
                        if len(table_list) % 2 != 0:
                            table_list.append("")
                        table_list.append("<hr />")
                        table_list.append("<hr />")
                        new_section = True
                    table_list.append(body_dict[k]['table'])
                elif k in ['collections', 'payments']:
                    table_list.append(\
                     "<div style='font-size: 16px; color: grey'>[" + \
                      k.capitalize() + \
                      "]<br />Missing: Account of type 'Bank or Cash'\
						</div>"                            )
                elif k == 'bank_balance':
                    table_list.append(\
                     "<div style='font-size: 16px; color: grey'>[" + \
                      "Bank Balance" + \
                      "]<br />Alert: GL Entry not found for Account of type 'Bank or Cash'\
						</div>"                            )

        i = 0
        result = []
        op_len = len(table_list)
        while (True):
            if i >= op_len:
                break
            elif (op_len - i) == 1:
                result.append("""\
					<tr>
						<td style='width: 50%%; vertical-align: top;'>%s</td>
						<td></td>
					</tr>""" % (table_list[i]))
            else:
                result.append("""\
					<tr>
						<td style='width: 50%%; vertical-align: top;'>%s</td>
						<td>%s</td>
					</tr>""" % (table_list[i], table_list[i + 1]))

            i = i + 2

        from webnotes.utils import formatdate
        start_date, end_date = self.get_start_end_dates()
        digest_daterange = self.doc.frequency=='Daily' \
         and formatdate(str(start_date)) \
         or (formatdate(str(start_date)) + " to " + (formatdate(str(end_date))))

        email_body = """
			<div style='width: 100%%'>
				<div style='padding: 10px; margin: auto; text-align: center; line-height: 80%%'>
					<p style='font-weight: bold; font-size: 24px'>%s</p>
					<p style='font-size: 16px; color: grey'>%s</p>
					<p style='font-size: 20px; font-weight: bold'>%s</p>
				</div>
				<table cellspacing=15 style='width: 100%%'>""" \
           % ((self.doc.frequency + " Digest"), \
            digest_daterange, self.doc.company) \
          + "".join(result) + """\
				</table><br><p></p>
			</div>"""

        return email_body
    def upload_accounts_transactions(self):
        import csv
        data = csv.reader(self.get_csv_data().splitlines())

        abbr = sql(
            "select concat(' - ',abbr) as abbr from tabCompany where name=%s",
            self.doc.company)
        updated = 0
        jv_name = ''
        #		jv = Document('Journal Voucher')
        global line, jv, name, jv_go
        for line in data:
            if len(line) >= 7:  #Minimum no of fields
                if line[3] != jv_name:  #Create JV
                    if jv_name != '':
                        jv_go = get_obj('Journal Voucher',
                                        name,
                                        with_children=1)
                        jv_go.validate()
                        jv_go.on_submit()

                    jv_name = line[3]
                    jv = Document('Journal Voucher')
                    jv.voucher_type = line[0]
                    jv.naming_series = line[1]
                    jv.voucher_date = formatdate(line[2])
                    jv.posting_date = formatdate(line[2])
                    #					jv.name = line[3]
                    jv.fiscal_year = self.doc.fiscal_year
                    jv.company = self.doc.company
                    jv.remark = len(line) == 8 and line[3] + ' ' + line[
                        7] or line[3] + ' Uploaded Record'
                    jv.docstatus = 1
                    jv.save(1)
                    name = jv.name

                    jc = addchild(jv, 'entries', 'Journal Voucher Detail', 0)
                    jc.account = line[4] + abbr[0][0]
                    jc.cost_center = len(
                        line) == 9 and line[8] or self.doc.default_cost_center
                    if line[5] != '':
                        jc.debit = line[5]
                    else:
                        jc.credit = line[6]
                    jc.save()

                else:  #Create JV Child
                    jc = addchild(jv, 'entries', 'Journal Voucher Detail', 0)
                    jc.account = line[4] + abbr[0][0]
                    jc.cost_center = len(
                        line) == 9 and line[8] or self.doc.default_cost_center
                    if line[5] != '':
                        jc.debit = line[5]
                    else:
                        jc.credit = line[6]
                    jc.save()
            else:
                msgprint("[Ignored] Incorrect format: %s" % str(line))
        if jv_name != '':
            jv_go = get_obj('Journal Voucher', name, with_children=1)
            jv_go.validate()
            jv_go.on_submit()

        msgprint("<b>%s</b> items updated" % updated)
Example #58
0
    def get_standard_body(self, result):
        """
			Generate email body depending on the result
		"""
        from webnotes.utils import fmt_money
        from webnotes.model.doc import Document
        company = Document('Company', self.doc.company)
        currency = company.default_currency

        def table(args):
            table_body = ""

            if isinstance(args['body'], basestring):
                return """<p>%(head)s: <span style='font-size: 110%%; font-weight: bold;'>%(body)s</span></p>""" % args
            else:
                return ("""<p>%(head)s:</p> """ % args) +\
                  "".join(map(lambda b: "<p style='margin-left: 17px;'>%s</p>" % b, args['body']))

        currency_amount_str = "<span style='color: grey;'>%s</span> %s"

        body_dict = {

         'invoiced_amount': {
          'table': result.get('invoiced_amount') and \
           table({
            'head': 'Invoiced Amount',
            'body': currency_amount_str \
             % (currency, fmt_money(result['invoiced_amount'].get('debit')))
           }),
          'idx': 300,
          'value': result.get('invoiced_amount') and result['invoiced_amount'].get('debit')
         },

         'payables': {
          'table': result.get('payables') and \
           table({
            'head': 'Payables',
            'body': currency_amount_str \
             % (currency, fmt_money(result['payables'].get('credit')))
           }),
          'idx': 200,
          'value': result.get('payables') and result['payables'].get('credit')
         },

         'collections': {
          'table': result.get('collections') and \
           table({
            'head': 'Collections',
            'body': currency_amount_str \
             % (currency, fmt_money(result['collections'].get('credit')))
           }),
          'idx': 301,
          'value': result.get('collections') and result['collections'].get('credit')
         },

         'payments': {
          'table': result.get('payments') and \
           table({
            'head': 'Payments',
            'body': currency_amount_str \
             % (currency, fmt_money(result['payments'].get('debit')))
           }),
          'idx': 201,
          'value': result.get('payments') and result['payments'].get('debit')
         },

         'income': {
          'table': result.get('income') and \
           table({
            'head': 'Income',
            'body': currency_amount_str \
             % (currency, fmt_money(result['income'].get('value')))
           }),
          'idx': 302,
          'value': result.get('income') and result['income'].get('value')
         },

         'income_year_to_date': {
          'table': result.get('income_year_to_date') and \
           table({
            'head': 'Income Year To Date',
            'body': currency_amount_str \
             % (currency, fmt_money(result['income_year_to_date'].get('value')))
           }),
          'idx': 303,
          'value': result.get('income_year_to_date') and \
            result['income_year_to_date'].get('value')
         },

         'expenses_booked': {
          'table': result.get('expenses_booked') and \
           table({
            'head': 'Expenses Booked',
            'body': currency_amount_str \
             % (currency, fmt_money(result['expenses_booked'].get('value')))
           }),
          'idx': 202,
          'value': result.get('expenses_booked') and result['expenses_booked'].get('value')
         },

         'bank_balance': {
          'table': result.get('bank_balance') and \
           table({
            'head': 'Bank / Cash Balance',
            'body': [(bank['name'] + ": <span style='font-size: 110%%; font-weight: bold;'>" \
               + currency_amount_str % \
               (currency, fmt_money(bank.get('value'))) + '</span>')
             for bank in (isinstance(result['bank_balance'], list) and \
              result['bank_balance'] or \
              [result['bank_balance']])
            ]
           }),
          'idx': 0,
          'value': 0.1
         },

         'new_leads': {
          'table': result.get('new_leads') and \
           table({
            'head': 'New Leads',
            'body': '%s' % result['new_leads'].get('count')
           }),
          'idx': 100,
          'value': result.get('new_leads') and result['new_leads'].get('count')
         },

         'new_enquiries': {
          'table': result.get('new_enquiries') and \
           table({
            'head': 'New Enquiries',
            'body': '%s' % result['new_enquiries'].get('count')
           }),
          'idx': 101,
          'value': result.get('new_enquiries') and result['new_enquiries'].get('count')
         },

         'new_quotations': {
          'table': result.get('new_quotations') and \
           table({
            'head': 'New Quotations',
            'body': '%s' % result['new_quotations'].get('count')
           }),
          'idx': 102,
          'value': result.get('new_quotations') and result['new_quotations'].get('count')
         },

         'new_sales_orders': {
          'table': result.get('new_sales_orders') and \
           table({
            'head': 'New Sales Orders',
            'body': '%s' % result['new_sales_orders'].get('count')
           }),
          'idx': 103,
          'value': result.get('new_sales_orders') and result['new_sales_orders'].get('count')
         },

         'new_purchase_orders': {
          'table': result.get('new_purchase_orders') and \
           table({
            'head': 'New Purchase Orders',
            'body': '%s' % result['new_purchase_orders'].get('count')
           }),
          'idx': 104,
          'value': result.get('new_purchase_orders') and \
            result['new_purchase_orders'].get('count')
         },

         'new_transactions': {
          'table': result.get('new_transactions') and \
           table({
            'head': 'New Transactions',
            'body': '%s' % result['new_transactions'].get('count')
           }),
          'idx': 105,
          'value': result.get('new_transactions') and result['new_transactions'].get('count')
         }

         #'stock_below_rl':
        }

        table_list = []

        # Sort these keys depending on idx value
        bd_keys = sorted(body_dict, key=lambda x: \
         (-webnotes.utils.flt(body_dict[x]['value']), body_dict[x]['idx']))

        new_section = False

        def set_new_section(new_section):
            if not new_section:
                table_list.append("<hr /><h4>No Updates For:</h4><br>")
                new_section = True
            return new_section

        for k in bd_keys:
            if self.doc.fields[k]:
                if k in result:
                    if not body_dict[k].get('value') and not new_section:
                        new_section = set_new_section(new_section)
                    table_list.append(body_dict[k]['table'])
                elif k in ['collections', 'payments']:
                    new_section = set_new_section(new_section)
                    table_list.append(\
                     "<p>[" + \
                      k.capitalize() + \
                      "]<br />Missing: Account of type 'Bank or Cash'\
						</p>"                          )
                elif k == 'bank_balance':
                    new_section = set_new_section(new_section)
                    table_list.append(\
                     "<p>[" + \
                      "Bank Balance" + \
                      "]<br />Alert: GL Entry not found for Account of type 'Bank or Cash'\
						</p>"                          )

        from webnotes.utils import formatdate
        start_date, end_date = self.get_start_end_dates()
        digest_daterange = self.doc.frequency=='Daily' \
         and formatdate(str(start_date)) \
         or (formatdate(str(start_date)) + " to " + (formatdate(str(end_date))))

        email_body = """
					<h2>%s</h2>
					<p style='color: grey'>%s</p>
					<h4>%s</h4>
					<hr>
				""" \
           % ((self.doc.frequency + " Digest"), \
            digest_daterange, self.doc.company) \
          + "".join(table_list) + """\
				<br><p></p>
			"""

        return email_body