Exemplo n.º 1
0
        def validate_compoff(self):
    		if self.doc.leave_type=='Compensatory Off':
    			if not self.doc.worked_day:
    						webnotes.msgprint( (" Please enter worked day for applying 'Compensatory Off'"),raise_exception=1)
    			#webnotes.errprint("co")
    			ss=self.get_total_leave_days()
    			#webnotes.msgprint(ss['total_leave_days'])
    			if ss['total_leave_days']==1.0:
    				if len(self.doc.worked_day)!=10:
    					webnotes.msgprint( ("Sorry...! Entered worked day is invalid.."),raise_exception=1)	
    				else:
    					dd=date_diff(self.doc.to_date, self.doc.worked_day)
                        		if dd>30:
                    				webnotes.msgprint( ("Sorry...! 'Compensatory Off' is valid only for 30 days."),raise_exception=1)
                	elif ss['total_leave_days']>=1.0:
                     		#webnotes.errprint(self.doc.worked_day)
                     		yy=self.doc.worked_day.split(',')
                     		#webnotes.msgprint(yy)
                     		webnotes.errprint(cint(ss['total_leave_days']))
                     		if len(yy)< cint(ss['total_leave_days']):
                    			webnotes.msgprint( ("Sorry...! Worked Days entered are ("+cstr(len(yy))+") less than total applied leave days ("+cstr(ss['total_leave_days'])+")."),raise_exception=1)
                     		for y in yy:
                     			#webnotes.msgprint(y)
                     			dd=date_diff(self.doc.to_date,y)
                     			if dd>30:
						webnotes.msgprint( ("Sorry...! 'Compensatory Off' is valid only for 30 days."),raise_exception=1)            
				webnotes.errprint(len(yy))
Exemplo n.º 2
0
def execute(filters=None):

    columns = get_columns()
    item_details = get_fifo_queue(filters)
    to_date = filters["to_date"]
    data = []
    for item, item_dict in item_details.items():
        fifo_queue = item_dict["fifo_queue"]
        details = item_dict["details"]
        if not fifo_queue:
            continue

        average_age = get_average_age(fifo_queue, to_date)
        earliest_age = date_diff(to_date, fifo_queue[0][1])
        latest_age = date_diff(to_date, fifo_queue[-1][1])

        data.append(
            [
                item,
                details.item_name,
                details.description,
                details.item_group,
                details.brand,
                average_age,
                earliest_age,
                latest_age,
                details.stock_uom,
            ]
        )

    return columns, data
Exemplo n.º 3
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.bean import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
	
	invoice_period_from_date = get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount)
	
	# get last day of the month to maintain period if the from date is first day of its own month 
	# and to date is the last day of its own month
	if (cstr(get_first_day(ref_wrapper.doc.invoice_period_from_date)) == \
			cstr(ref_wrapper.doc.invoice_period_from_date)) and \
		(cstr(get_last_day(ref_wrapper.doc.invoice_period_to_date)) == \
			cstr(ref_wrapper.doc.invoice_period_to_date)):
		invoice_period_to_date = get_last_day(get_next_date(ref_wrapper.doc.invoice_period_to_date,
			mcount))
	else:
		invoice_period_to_date = get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount)
	
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
		"invoice_period_from_date": invoice_period_from_date,
		"invoice_period_to_date": invoice_period_to_date,
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Exemplo n.º 4
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.bean import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
	
	invoice_period_from_date = get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount)
	
	# get last day of the month to maintain period if the from date is first day of its own month 
	# and to date is the last day of its own month
	if (cstr(get_first_day(ref_wrapper.doc.invoice_period_from_date)) == \
			cstr(ref_wrapper.doc.invoice_period_from_date)) and \
		(cstr(get_last_day(ref_wrapper.doc.invoice_period_to_date)) == \
			cstr(ref_wrapper.doc.invoice_period_to_date)):
		invoice_period_to_date = get_last_day(get_next_date(ref_wrapper.doc.invoice_period_to_date,
			mcount))
	else:
		invoice_period_to_date = get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount)
	
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
		"invoice_period_from_date": invoice_period_from_date,
		"invoice_period_to_date": invoice_period_to_date,
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Exemplo n.º 5
0
def make_new_invoice(ref_wrapper):
	from webnotes.model.wrapper import clone
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
	
	today = nowdate()
	
	new_invoice.doc.fields.update({
		"posting_date": today,
		"aging_date": today,
		
		"due_date": add_days(today, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
			
		"invoice_period_from_date": \
			get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount),
			
		"invoice_period_to_date": \
			get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount),
		
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Exemplo n.º 6
0
def create_new_invoice(prev_rv):
    # clone rv
    new_rv = clone(prev_rv)

    mdict = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
    mcount = mdict[prev_rv.doc.recurring_type]

    # update new rv

    new_rv.doc.posting_date = new_rv.doc.next_date
    new_rv.doc.aging_date = new_rv.doc.next_date
    new_rv.doc.due_date = add_days(
        new_rv.doc.next_date,
        cint(date_diff(prev_rv.doc.due_date, prev_rv.doc.posting_date)))
    new_rv.doc.invoice_period_from_date = get_next_date(
        new_rv.doc.invoice_period_from_date, mcount)
    new_rv.doc.invoice_period_to_date = get_next_date(
        new_rv.doc.invoice_period_to_date, mcount)
    new_rv.doc.owner = prev_rv.doc.owner
    new_rv.doc.save()

    # submit and after submit
    new_rv.submit()
    new_rv.update_after_submit()

    return new_rv
  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))
Exemplo n.º 8
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.wrapper import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
		
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
			
		"invoice_period_from_date": \
			get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount),
			
		"invoice_period_to_date": \
			get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount),
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Exemplo n.º 9
0
def sent_reminder_task():
	task_list = sql("""
		select subject, allocated_to, project, exp_start_date, exp_end_date,
			priority, status, name, senders_name, opening_date, review_date, description 
		from tabTask
		where task_email_notify=1 
			and sent_reminder=0 
			and status='Open' 
			and exp_start_date is not null""",as_dict=1)
	for i in task_list:		
		if date_diff(i['exp_start_date'],nowdate()) ==2:
			msg2="""<h2>Two days to complete: %(name)s</h2>
			<p>This is a reminder for the task %(name)s has been assigned to you 
				by %(senders_name)s on %(opening_date)s</p>
			<p><b>Subject:</b> %(subject)s </p>
			<p><b>Project:</b> %(project)s</p>
			<p><b>Expected Start Date:</b> %(exp_start_date)s</p>
			<p><b>Expected End Date:</b> %(exp_end_date)s</p>
			<p><b>Review Date:</b> %(review_date)s</p>
			<p><b>Details:</b> %(description)s</p>
			<p>If you have already completed this task, please update the system</p>
			<p>Good Luck!</p>
			<p>(This notification is autogenerated)</p>""" % i
			sendmail(i['allocated_to'], sender='*****@*****.**', msg=msg2,send_now=1, \
				subject='A task has been assigned')
			sql("update `tabTask` set sent_reminder='1' where name='%(name)s' and allocated_to= '%(allocated_to)s'" % i)	
Exemplo n.º 10
0
def sent_reminder_task():
    task_list = sql("""
		select subject, allocated_to, project, exp_start_date, exp_end_date,
			priority, status, name, senders_name, opening_date, review_date, description 
		from tabTask
		where task_email_notify=1 
			and sent_reminder=0 
			and status='Open' 
			and exp_start_date is not null""",
                    as_dict=1)
    for i in task_list:
        if date_diff(i['exp_start_date'], nowdate()) == 2:
            msg2 = """<h2>Two days to complete: %(name)s</h2>
			<p>This is a reminder for the task %(name)s has been assigned to you 
				by %(senders_name)s on %(opening_date)s</p>
			<p><b>Subject:</b> %(subject)s </p>
			<p><b>Project:</b> %(project)s</p>
			<p><b>Expected Start Date:</b> %(exp_start_date)s</p>
			<p><b>Expected End Date:</b> %(exp_end_date)s</p>
			<p><b>Review Date:</b> %(review_date)s</p>
			<p><b>Details:</b> %(description)s</p>
			<p>If you have already completed this task, please update the system</p>
			<p>Good Luck!</p>
			<p>(This notification is autogenerated)</p>""" % i
            sendmail(i['allocated_to'], sender='*****@*****.**', msg=msg2,send_now=1, \
             subject='A task has been assigned')
            sql("update `tabTask` set sent_reminder='1' where name='%(name)s' and allocated_to= '%(allocated_to)s'"
                % i)
Exemplo n.º 11
0
def make_new_invoice(ref_wrapper, posting_date):
    from webnotes.model.wrapper import clone
    from accounts.utils import get_fiscal_year
    new_invoice = clone(ref_wrapper)

    mcount = month_map[ref_wrapper.doc.recurring_type]

    new_invoice.doc.fields.update({
     "posting_date": posting_date,
     "aging_date": posting_date,

     "due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
      ref_wrapper.doc.posting_date))),

     "invoice_period_from_date": \
      get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount),

     "invoice_period_to_date": \
      get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount),
     "fiscal_year": get_fiscal_year(posting_date)[0],
     "owner": ref_wrapper.doc.owner,
    })

    new_invoice.submit()

    return new_invoice
Exemplo n.º 12
0
def get_average_age(fifo_queue, to_date):
    batch_age = age_qty = total_qty = 0.0
    for batch in fifo_queue:
        batch_age = date_diff(to_date, batch[1])
        age_qty += batch_age * batch[0]
        total_qty += batch[0]

    return (age_qty / total_qty) if total_qty else 0.0
Exemplo n.º 13
0
def get_average_age(fifo_queue, to_date):
	batch_age = age_qty = total_qty = 0.0
	for batch in fifo_queue:
		batch_age = date_diff(to_date, batch[1])
		age_qty += batch_age * batch[0]
		total_qty += batch[0]
	
	return (age_qty / total_qty) if total_qty else 0.0
Exemplo n.º 14
0
	def last_sync(self):
		from webnotes.utils import today,date_diff, cint
		last_sync_date = webnotes.conn.get_value('Global Defaults', None, 'last_sync_date',debug=1)
		print last_sync_date
		if last_sync_date:
			if cint(webnotes.conn.get_value('Global Defaults', None, 'must_sync_after')) < date_diff(today(), last_sync_date):
				return False
		return True
Exemplo n.º 15
0
 def get_total_leave_days(self):
     """Calculates total leave days based on input and holidays"""
     ret = {'total_leave_days': 0.5}
     if not self.doc.half_day:
         tot_days = date_diff(self.doc.to_date, self.doc.from_date) + 1
         holidays = self.get_holidays()
         ret = {'total_leave_days': flt(tot_days) - flt(holidays)}
     return ret
Exemplo n.º 16
0
 def get_total_leave_days(self):
     """Calculates total leave days based on input and holidays"""
     ret = {"total_leave_days": 0.5}
     if not self.doc.half_day:
         tot_days = date_diff(self.doc.to_date, self.doc.from_date) + 1
         holidays = self.get_holidays()
         ret = {"total_leave_days": flt(tot_days) - flt(holidays)}
     return ret
Exemplo n.º 17
0
 def validate_compoff(self):
     if self.doc.leave_type == 'Compensatory Off':
         if not self.doc.worked_day:
             webnotes.msgprint(
                 (" Please enter worked day for applying 'Compensatory Off'"
                  ),
                 raise_exception=1)
         #webnotes.errprint("co")
         ss = self.get_total_leave_days()
         #webnotes.msgprint(ss['total_leave_days'])
         if ss['total_leave_days'] == 1.0:
             if len(self.doc.worked_day) != 10:
                 webnotes.msgprint(
                     ("Sorry...! Entered worked day is invalid.."),
                     raise_exception=1)
             else:
                 dd = date_diff(self.doc.to_date, self.doc.worked_day)
                 if dd > 30:
                     webnotes.msgprint((
                         "Sorry...! 'Compensatory Off' is valid only for 30 days."
                     ),
                                       raise_exception=1)
         elif ss['total_leave_days'] >= 1.0:
             #webnotes.errprint(self.doc.worked_day)
             yy = self.doc.worked_day.split(',')
             #webnotes.msgprint(yy)
             webnotes.errprint(cint(ss['total_leave_days']))
             if len(yy) < cint(ss['total_leave_days']):
                 webnotes.msgprint(
                     ("Sorry...! Worked Days entered are (" +
                      cstr(len(yy)) +
                      ") less than total applied leave days (" +
                      cstr(ss['total_leave_days']) + ")."),
                     raise_exception=1)
             for y in yy:
                 #webnotes.msgprint(y)
                 dd = date_diff(self.doc.to_date, y)
                 if dd > 30:
                     webnotes.msgprint((
                         "Sorry...! 'Compensatory Off' is valid only for 30 days."
                     ),
                                       raise_exception=1)
             webnotes.errprint(len(yy))
 def calc_days(self):
   if self.doc.billing_cycle_date:
     next_bill_month = cint(nowdate().split('-')[1])
     if cint(nowdate().split('-')[2]) > cint(self.doc.billing_cycle_date.split('-')[2]):
       next_bill_month = cint(nowdate().split('-')[1]) + 1
     next_bill_year = nowdate().split('-')[0]
     if next_bill_month > 12:
       next_bill_month = next_bill_month % 12
       next_bill_year += 1
     self.next_bill_sdate = cstr(next_bill_year)+'-'+cstr(next_bill_month)+'-'+(self.calc_next_day(next_bill_year,next_bill_month))
     #msgprint("next_bill_month :::" + self.next_bill_sdate)
     return date_diff(self.next_bill_sdate, nowdate())
Exemplo n.º 19
0
def execute(filters=None):

    columns = get_columns()
    item_details = get_fifo_queue(filters)
    to_date = filters["to_date"]
    data = []
    for item, item_dict in item_details.items():
        fifo_queue = item_dict["fifo_queue"]
        details = item_dict["details"]
        if not fifo_queue: continue

        average_age = get_average_age(fifo_queue, to_date)
        earliest_age = date_diff(to_date, fifo_queue[0][1])
        latest_age = date_diff(to_date, fifo_queue[-1][1])

        data.append([
            item, details.item_name, details.description, details.item_group,
            details.brand, average_age, earliest_age, latest_age,
            details.stock_uom
        ])

    return columns, data
Exemplo n.º 20
0
def create_new_invoice(prev_rv):
	# clone rv
	new_rv = clone(prev_rv)

	# update new rv 

	new_rv.doc.posting_date = new_rv.doc.next_date
	new_rv.doc.aging_date = new_rv.doc.next_date
	new_rv.doc.due_date = add_days(new_rv.doc.next_date, cint(date_diff(prev_rv.doc.due_date, prev_rv.doc.posting_date)))
	new_rv.doc.owner = prev_rv.doc.owner
	new_rv.doc.save()

	# submit and after submit
	new_rv.submit()
	new_rv.update_after_submit()

	return new_rv
 def trial_payment_reminders(self):
   if cint(self.doc.is_trial_account)==1:
     # Trial Period Expiry
     trial_end_date = add_days(self.doc.account_start_date, 30)
     days = date_diff(trial_end_date, nowdate())
     # check if trial period has expired
     if days < 10 and days >= 0 and has_common(['System Manager'],webnotes.user.get_roles()):
       return "Your Trial Period expires on '%s'. Please buy credits online using Manage Account." % (formatdate(trial_end_date))
     
     # trial period has already expired
     elif days < 0 and days >= -6:
       extended_days = 7 + days
       return "Your Trial Period has expired on %s. However, your account will be live for %s days. Please contact your System Manager to buy credits." % (formatdate(trial_end_date),cstr(extended_days))
     elif not has_common(['Administrator'],webnotes.user.get_roles()) and days < -6:
       return "Stopped"
   
   # Account is not a trial account
   else:
     return self.account_expiry_reminder()
Exemplo n.º 22
0
def create_new_invoice(prev_rv):
	# clone rv
	new_rv = clone(prev_rv)

	# update new rv 

	new_rv.doc.posting_date = new_rv.doc.next_date
	new_rv.doc.aging_date = new_rv.doc.next_date
	new_rv.doc.due_date = add_days(new_rv.doc.next_date, cint(date_diff(prev_rv.doc.due_date, prev_rv.doc.posting_date)))
	new_rv.doc.invoice_period_from_date = get_next_month_date(new_rv.doc.invoice_period_from_date)
	new_rv.doc.invoice_period_to_date = get_next_month_date(new_rv.doc.invoice_period_to_date)
	new_rv.doc.owner = prev_rv.doc.owner
	new_rv.doc.save()

	# submit and after submit
	new_rv.submit()
	new_rv.update_after_submit()

	return new_rv
Exemplo n.º 23
0
def create_new_invoice(prev_rv):
	# clone rv
	new_rv = clone(prev_rv)

	mdict = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
	mcount = mdict[prev_rv.doc.recurring_type]

	# update new rv 

	new_rv.doc.posting_date = new_rv.doc.next_date
	new_rv.doc.aging_date = new_rv.doc.next_date
	new_rv.doc.due_date = add_days(new_rv.doc.next_date, cint(date_diff(prev_rv.doc.due_date, prev_rv.doc.posting_date)))
	new_rv.doc.invoice_period_from_date = get_next_date(new_rv.doc.invoice_period_from_date, mcount)
	new_rv.doc.invoice_period_to_date = get_next_date(new_rv.doc.invoice_period_to_date, mcount)
	new_rv.doc.owner = prev_rv.doc.owner
	new_rv.doc.save()

	# submit and after submit
	new_rv.submit()
	new_rv.update_after_submit()

	return new_rv
Exemplo n.º 24
0
class LoginManager:
    def __init__(self):
        if webnotes.form_dict.get('cmd') == 'login':
            # clear cache
            webnotes.clear_cache(user=webnotes.form_dict.get('usr'))

            self.authenticate()
            self.post_login()
            info = webnotes.conn.get_value(
                "Profile",
                self.user, ["user_type", "first_name", "last_name"],
                as_dict=1)
            if info.user_type == "Website User":
                webnotes._response.set_cookie("system_user", "no")
                webnotes.response["message"] = "No App"
            else:
                webnotes._response.set_cookie("system_user", "yes")
                webnotes.response['message'] = 'Logged In'

            full_name = " ".join(
                filter(None, [info.first_name, info.last_name]))
            webnotes.response["full_name"] = full_name
            webnotes._response.set_cookie("full_name", full_name)
            webnotes._response.set_cookie("user_id", self.user)

    def post_login(self):
        self.run_trigger()
        self.validate_ip_address()
        self.validate_hour()

    def authenticate(self, user=None, pwd=None):
        # return True

        if self.check_uuid():
            if self.last_sync():
                if self.is_active():
                    if not (user and pwd):
                        user, pwd = webnotes.form_dict.get(
                            'usr'), webnotes.form_dict.get('pwd')
                    if not (user and pwd):
                        self.fail('Incomplete login details')

                    self.check_if_enabled(user)
                    self.user = self.check_password(user, pwd)
                else:
                    self.fail('Your Account has been deactivated ')
            else:
                self.fail('Need to sync first')
        else:
            self.fail("Hardware verification failed")

    def check_uuid(self):
        if webnotes.conn.get_value('Global Defaults', None, 'default_company'):
            salted_uuid = webnotes.conn.get_value("Global Defaults", None,
                                                  "uuid")
            salt = webnotes.conn.get_value("Global Defaults", None, "salt")

            from setup.page.setup_wizard.setup_wizard import encrypt_uuid

            digest = encrypt_uuid(salt)
            if salted_uuid == digest:
                return True
            return False
        else:
            return True

    def decrypt(self, key, encryped):
        msg = []
        for i, c in enumerate(encryped):
            key_c = ord(key[i % len(key)])
            enc_c = ord(c)
            msg.append(chr((enc_c - key_c) % 127))
        return ''.join(msg)

    def last_sync(self):
        from webnotes.utils import today, date_diff, cint
        import os.path

        last_sync_date = ''
        if cstr(
                webnotes.conn.get_value('Global Defaults', None,
                                        'db_sync_flag')) == 'Yes':
            file_path = os.path.join(get_base_path(), "public")
            f2 = file_path + '/' + "dbsync.txt"
            if os.path.exists(f2):
                for line in open(f2, "r"):
                    msg, key = line.split(",")
                    decrypt = self.decrypt(key, msg)
                    try:
                        last_sync_date = getdate(decrypt)
                    except Exception, e:
                        self.fail(
                            'There are some manual interpretation with system file.Please Sync to continue'
                        )

        # last_sync_date='2014-11-07'

        adm_creation = cstr(
            webnotes.conn.get_value("Profile", 'Administrator',
                                    'creation')).split(" ")[0]

        if date_diff(today(), getdate(adm_creation)) > 1:
            return False

        if last_sync_date:
            must_sync_after = webnotes.conn.get_value('Global Defaults', None,
                                                      'must_sync_after')
            must_sync = cint(must_sync_after) if must_sync_after else 30

            if must_sync < date_diff(today(), last_sync_date):
                return False

        return True
Exemplo n.º 25
0
def get_events(start, end, user=None, for_reminder=False):
    if not user:
        user = webnotes.session.user
    roles = webnotes.get_roles(user)
    events = webnotes.conn.sql("""select name, subject, description,
		starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on,
		monday, tuesday, wednesday, thursday, friday, saturday, sunday, patient, service
		from tabEvent where ((
			(date(starts_on) between date('%(start)s') and date('%(end)s'))
			or (date(ends_on) between date('%(start)s') and date('%(end)s'))
			or (date(starts_on) <= date('%(start)s') and date(ends_on) >= date('%(end)s'))
		) or (
			date(starts_on) <= date('%(start)s') and ifnull(repeat_this_event,0)=1 and
			ifnull(repeat_till, "3000-01-01") > date('%(start)s')
		))
		%(reminder_condition)s
		and (event_type='Public' or owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		order by starts_on""" % {
        "start":
        start,
        "end":
        end,
        "reminder_condition":
        "and ifnull(send_reminder,0)=1" if for_reminder else "",
        "user":
        user,
        "roles":
        "', '".join(roles)
    },
                               as_dict=1)

    # process recurring events
    start = start.split(" ")[0]
    end = end.split(" ")[0]
    add_events = []
    remove_events = []

    def add_event(e, date):
        new_event = e.copy()
        new_event.starts_on = date + " " + e.starts_on.split(" ")[1]
        if e.ends_on:
            new_event.ends_on = date + " " + e.ends_on.split(" ")[1]
        add_events.append(new_event)

    for e in events:
        if e.repeat_this_event:
            event_start, time_str = e.starts_on.split(" ")
            if e.repeat_on == "Every Year":
                start_year = cint(start.split("-")[0])
                end_year = cint(end.split("-")[0])
                event_start = "-".join(event_start.split("-")[1:])

                # repeat for all years in period
                for year in range(start_year, end_year + 1):
                    date = str(year) + "-" + event_start
                    if date >= start and date <= end:
                        add_event(e, date)

                remove_events.append(e)

            if e.repeat_on == "Every Month":
                date = start.split("-")[0] + "-" + start.split(
                    "-")[1] + "-" + event_start.split("-")[2]

                # last day of month issue, start from prev month!
                try:
                    getdate(date)
                except ValueError:
                    date = date.split("-")
                    date = date[0] + "-" + str(cint(date[1]) -
                                               1) + "-" + date[2]

                start_from = date
                for i in xrange(int(date_diff(end, start) / 30) + 3):
                    if date >= start and date <= end and date >= event_start:
                        add_event(e, date)
                    date = add_months(start_from, i + 1)

                remove_events.append(e)

            if e.repeat_on == "Every Week":
                weekday = getdate(event_start).weekday()
                # monday is 0
                start_weekday = getdate(start).weekday()

                # start from nearest weeday after last monday
                date = add_days(start, weekday - start_weekday)

                for cnt in xrange(int(date_diff(end, start) / 7) + 3):
                    if date >= start and date <= end and date >= event_start:
                        add_event(e, date)

                    date = add_days(date, 7)

                remove_events.append(e)

            if e.repeat_on == "Every Day":
                for cnt in xrange(date_diff(end, start) + 1):
                    date = add_days(start, cnt)
                    if date >= event_start and date <= end \
                     and e[weekdays[getdate(date).weekday()]]:
                        add_event(e, date)
                remove_events.append(e)

    for e in remove_events:
        events.remove(e)

    events = events + add_events

    for e in events:
        # remove weekday properties (to reduce message size)
        for w in weekdays:
            del e[w]

    return events
Exemplo n.º 26
0
def get_dates(args):
    """get list of dates in between from date and to date"""
    no_of_days = date_diff(add_days(args["to_date"], 1), args["from_date"])
    dates = [add_days(args["from_date"], i) for i in range(0, no_of_days)]
    return dates
Exemplo n.º 27
0
 def get_total_leave_days(self):
   tot_days = date_diff(self.doc.to_date, self.doc.from_date) + 1
   holidays = self.get_holidays()
   ret = {'total_leave_days':flt(tot_days)-flt(holidays)}
   return str(ret)
Exemplo n.º 28
0
def get_events(start, end, user=None, for_reminder=False):
	if not user:
		user = webnotes.session.user
	roles = webnotes.get_roles(user)
	events = webnotes.conn.sql("""select name, subject, description,
		starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on,
		monday, tuesday, wednesday, thursday, friday, saturday, sunday
		from tabEvent where ((
			(date(starts_on) between date('%(start)s') and date('%(end)s'))
			or (date(ends_on) between date('%(start)s') and date('%(end)s'))
			or (date(starts_on) <= date('%(start)s') and date(ends_on) >= date('%(end)s'))
		) or (
			date(starts_on) <= date('%(start)s') and ifnull(repeat_this_event,0)=1 and
			ifnull(repeat_till, "3000-01-01") > date('%(start)s')
		))
		%(reminder_condition)s
		and (event_type='Public' or owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		order by starts_on""" % {
			"start": start,
			"end": end,
			"reminder_condition": "and ifnull(send_reminder,0)=1" if for_reminder else "",
			"user": user,
			"roles": "', '".join(roles)
		}, as_dict=1)
			
	# process recurring events
	start = start.split(" ")[0]
	end = end.split(" ")[0]
	add_events = []
	remove_events = []
	
	def add_event(e, date):
		new_event = e.copy()
		new_event.starts_on = date + " " + e.starts_on.split(" ")[1]
		if e.ends_on:
			new_event.ends_on = date + " " + e.ends_on.split(" ")[1]
		add_events.append(new_event)
	
	for e in events:
		if e.repeat_this_event:
			event_start, time_str = e.starts_on.split(" ")
			if e.repeat_on=="Every Year":
				start_year = cint(start.split("-")[0])
				end_year = cint(end.split("-")[0])
				event_start = "-".join(event_start.split("-")[1:])
				
				# repeat for all years in period
				for year in range(start_year, end_year+1):
					date = str(year) + "-" + event_start
					if date >= start and date <= end:
						add_event(e, date)
						
				remove_events.append(e)

			if e.repeat_on=="Every Month":
				date = start.split("-")[0] + "-" + start.split("-")[1] + "-" + event_start.split("-")[2]
				
				# last day of month issue, start from prev month!
				try:
					getdate(date)
				except ValueError:
					date = date.split("-")
					date = date[0] + "-" + str(cint(date[1]) - 1) + "-" + date[2]
					
				start_from = date
				for i in xrange(int(date_diff(end, start) / 30) + 3):
					if date >= start and date <= end and date >= event_start:
						add_event(e, date)
					date = add_months(start_from, i+1)

				remove_events.append(e)

			if e.repeat_on=="Every Week":
				weekday = getdate(event_start).weekday()
				# monday is 0
				start_weekday = getdate(start).weekday()
				
				# start from nearest weeday after last monday
				date = add_days(start, weekday - start_weekday)
				
				for cnt in xrange(int(date_diff(end, start) / 7) + 3):
					if date >= start and date <= end and date >= event_start:
						add_event(e, date)

					date = add_days(date, 7)
				
				remove_events.append(e)

			if e.repeat_on=="Every Day":				
				for cnt in xrange(date_diff(end, start) + 1):
					date = add_days(start, cnt)
					if date >= event_start and date <= end \
						and e[weekdays[getdate(date).weekday()]]:
						add_event(e, date)
				remove_events.append(e)

	for e in remove_events:
		events.remove(e)
		
	events = events + add_events
	
	for e in events:
		# remove weekday properties (to reduce message size)
		for w in weekdays:
			del e[w]
			
	return events
Exemplo n.º 29
0
def get_dates(args):
    """get list of dates in between from date and to date"""
    no_of_days = date_diff(add_days(args["to_date"], 1), args["from_date"])
    dates = [add_days(args["from_date"], i) for i in range(0, no_of_days)]
    return dates