def auto_status_update_ms(doc, method):
	new = add_years(doc.installation_date, doc.guarantee_period)
	validdate_amc1=add_days(new,-1)
	doc.amc_guarantee_valid_upto_date=validdate_amc1
	new = add_days(new, days=-1)
	if doc.guarantee_period==0:
		doc.amc_guarantee_valid_upto_date=""
		doc.amc_status="N/A"
		frappe.throw("Enter The Guarantee Period")
	else:
		doc.amc_guarantee_valid_upto_date = new

	# if doc.transaction_date
	# 	doc.amc_status = "Untraceable"
	# if date_diff(doc.transaction_date,doc.installation_date)<=365*doc.contract_period:
	# 	doc.amc_status = "N/A"
	if doc.amc_guarantee_valid_upto_date>doc.transaction_date:
		doc.amc_status = "Guarantee"
	else:
		doc.amc_status="Expired"
	
	if doc.amc_start_month:
		guarntee=add_years(doc.amc_start_month,doc.contract_period)
		validdate_amc=add_days(guarntee,-1)
		doc.amc_guarantee_valid_upto_date=validdate_amc
		guarntee = add_days(guarntee, days=-1)
		doc.amc_guarantee_valid_upto_date=guarntee
		doc.amc_status = "AMC"

	if getdate(doc.transaction_date) > getdate(doc.installation_date):
		frappe.throw("Installation Date Should be Greater Than Equal To Transaction Date")
Beispiel #2
0
def calculate_next_due_date(periodicity,
                            start_date=None,
                            end_date=None,
                            last_completion_date=None,
                            next_due_date=None):
    if not start_date and not last_completion_date:
        start_date = frappe.utils.now()

    if last_completion_date and (
        (start_date and last_completion_date > start_date) or not start_date):
        start_date = last_completion_date
    if periodicity == 'Daily':
        next_due_date = add_days(start_date, 1)
    if periodicity == 'Weekly':
        next_due_date = add_days(start_date, 7)
    if periodicity == 'Monthly':
        next_due_date = add_months(start_date, 1)
    if periodicity == 'Yearly':
        next_due_date = add_years(start_date, 1)
    if periodicity == '2 Yearly':
        next_due_date = add_years(start_date, 2)
    if periodicity == 'Quarterly':
        next_due_date = add_months(start_date, 3)
    if end_date and ((start_date and start_date >= end_date) or
                     (last_completion_date
                      and last_completion_date >= end_date) or next_due_date):
        next_due_date = ""
    return next_due_date
Beispiel #3
0
    def validation_from_student_admission(self):

        student_admission = get_student_admission_data(
            self.student_admission, self.program)

        if student_admission and student_admission.min_age and \
                date_diff(nowdate(), add_years(getdate(self.date_of_birth), student_admission.min_age)) < 0:
            frappe.throw(
                _("Not eligible for the admission in this program as per Date Of Birth"))

        if student_admission and student_admission.max_age and \
                date_diff(nowdate(), add_years(getdate(self.date_of_birth), student_admission.max_age)) > 0:
            frappe.throw(
                _("Not eligible for the admission in this program as per Date Of Birth"))
	def prepare_periodical_data(self):
		self.period_wise_data = {}

		from_date = add_years(self.filters.from_date, cint(self.filters.no_of_years) * -1)
		self.period_list = get_period_list(from_date, self.filters.to_date,
			from_date, self.filters.to_date, "Date Range", self.filters.periodicity, ignore_fiscal_year=True)

		order_data = self.get_data_for_forecast() or []

		for entry in order_data:
			key = (entry.item_code, entry.warehouse)
			if key not in self.period_wise_data:
				self.period_wise_data[key] = entry

			period_data = self.period_wise_data[key]
			for period in self.period_list:
				# check if posting date is within the period
				if (entry.posting_date >= period.from_date and entry.posting_date <= period.to_date):
					period_data[period.key] = period_data.get(period.key, 0.0) + flt(entry.get(self.based_on_field))

		for key, value in self.period_wise_data.items():
			list_of_period_value = [value.get(p.key, 0) for p in self.period_list]

			if list_of_period_value:
				total_qty = [1 for d in list_of_period_value if d]
				if total_qty:
					value["avg"] = flt(sum(list_of_period_value)) / flt(sum(total_qty))
Beispiel #5
0
    def validate(self):
        member_name = frappe.get_value('Member',
                                       dict(email=frappe.session.user))

        if not member_name:
            user = frappe.get_doc('User', frappe.session.user)
            member = frappe.get_doc(
                dict(doctype='Member',
                     email=frappe.session.user,
                     member_name=user.get_fullname())).insert(
                         ignore_permissions=True)
            member_name = member.name

        self.member = member_name

        # get last membership (if active)
        last_membership = foundation.get_last_membership()

        if last_membership:
            # if last membership does not expire in 30 days, then do not allow to renew
            if getdate(add_days(last_membership.to_date, -30)) > getdate(
                    nowdate()):
                frappe.throw(
                    _('You can only renew if your membership expires within 30 days'
                      ))

            self.from_date = add_days(last_membership.to_date, 1)
        else:
            self.from_date = nowdate()

        self.to_date = add_years(self.from_date, 1)
Beispiel #6
0
def register(args_data):
    """Register on the hub."""
    try:
        args = json.loads(args_data)
        if frappe.get_all("Hub User",
                          filters={"hub_user_email": args["hub_user_email"]}):
            # Renabling user
            return

        hub_company = frappe.new_doc("Hub Company")
        hub_company.company_name = args["company"]
        for key in ["country"] + seller_fields:
            hub_company.set(key, args[key])
        hub_company.insert(ignore_permissions=True)

        hub_user = frappe.new_doc("Hub User")
        for key in user_profile_fields + seller_fields:
            hub_user.set(key, args[key])
        hub_user.set("company_name", args["company"])
        hub_user.enabled = 1
        hub_user.last_sync_datetime = add_years(now(), -10)
        hub_user.insert(ignore_permissions=True)

        # set created user link for company
        hub_company.hub_user_name = args["hub_user_name"]
        hub_company.save(ignore_permissions=True)

        response = hub_user.as_dict()
        return response

    except:
        print("Server Exception")
        print(frappe.get_traceback())
	def validate(self):
		member_name = frappe.get_value('Member', dict(email=frappe.session.user))

		if not member_name:
			user = frappe.get_doc('User', frappe.session.user)
			member = frappe.get_doc(dict(
				doctype='Member',
				email=frappe.session.user,
				member_name=user.get_fullname()
			)).insert(ignore_permissions=True)
			member_name = member.name

		if self.get("__islocal"):
			self.member = member_name

		# get last membership (if active)
		last_membership = foundation.get_last_membership()

		# if person applied for offline membership
		if last_membership and not frappe.session.user == "Administrator":
			# if last membership does not expire in 30 days, then do not allow to renew
			if getdate(add_days(last_membership.to_date, -30)) > getdate(nowdate()) :
				frappe.throw(_('You can only renew if your membership expires within 30 days'))

			self.from_date = add_days(last_membership.to_date, 1)
		elif frappe.session.user == "Administrator":
			self.from_date = self.from_date
		else:
			self.from_date = nowdate()

		self.to_date = add_years(self.from_date, 1)
Beispiel #8
0
def get_timeline_data(doctype, name):
	'''returns timeline data for the past one year'''
	from frappe.desk.form.load import get_communication_data

	out = {}
	fields = 'creation, count(*)'
	after = add_years(None, -1).strftime('%Y-%m-%d')
	group_by='group by Date(creation)'

	data = get_communication_data(doctype, name, after=after, group_by='group by creation',
		fields='C.creation as creation, count(C.name)',as_dict=False)

	# fetch and append data from Activity Log
	data += frappe.db.sql("""select {fields}
		from `tabActivity Log`
		where (reference_doctype=%(doctype)s and reference_name=%(name)s)
		or (timeline_doctype in (%(doctype)s) and timeline_name=%(name)s)
		or (reference_doctype in ("Quotation", "Opportunity") and timeline_name=%(name)s)
		and status!='Success' and creation > {after}
		{group_by} order by creation desc
		""".format(fields=fields, group_by=group_by, after=after), {
			"doctype": doctype,
			"name": name
		}, as_dict=False)

	timeline_items = dict(data)

	for date, count in iteritems(timeline_items):
		timestamp = get_timestamp(date)
		out.update({ timestamp: count })

	return out
def auto_create_fiscal_year():
    print "Meso"
    for d in frappe.db.sql(
            """select name from `tabFiscal Year` where year_end_date = date_add(current_date, interval 3 day)"""
    ):
        try:
            current_fy = frappe.get_doc("Fiscal Year", d[0])
            print current_fy
            new_fy = frappe.copy_doc(current_fy, ignore_no_copy=False)

            new_fy.year_start_date = add_days(current_fy.year_end_date, 1)
            new_fy.year_end_date = add_years(current_fy.year_end_date, 1)

            start_year = cstr(new_fy.year_start_date.year)
            end_year = cstr(new_fy.year_end_date.year)
            new_fy.year = start_year if start_year == end_year else (
                start_year + "-" + end_year)
            frappe.msgprint(
                str(start_year if start_year == end_year else (start_year +
                                                               "-" +
                                                               end_year)))
            new_fy.insert(ignore_permissions=True)
            #Edited by Maysaa
            frappe.db.set_value(
                "Global Defaults", None, "current_fiscal_year",
                start_year if start_year == end_year else
                (start_year + "-" + end_year))
            global_defaults = frappe.get_doc("Global Defaults")
            global_defaults.check_permission("write")
            global_defaults.on_update()

            # clear cache
            frappe.clear_cache()
        except frappe.NameError:
            pass
Beispiel #10
0
	def get_events(self, remote_objectname, filters, page_length):
		page_token = None
		results = []
		events = {"items": []}
		while True:
			try:
				events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
					singleEvents=False, showDeleted=True, syncToken=self.account.next_sync_token or None).execute()
			except HttpError as err:
				if err.resp.status in [410]:
					events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
						singleEvents=False, showDeleted=True, timeMin=add_years(None, -1).strftime('%Y-%m-%dT%H:%M:%SZ')).execute()
				else:
					frappe.log_error(err.resp, "GCalendar Events Fetch Error")
			for event in events['items']:
				event.update({'account': self.account.name})
				event.update({'calendar_tz': events['timeZone']})
				results.append(event)

			page_token = events.get('nextPageToken')
			if not page_token:
				if events.get('nextSyncToken'):
					frappe.db.set_value("GCalendar Account", self.connector.username, "next_sync_token", events.get('nextSyncToken'))
				break
		return list(results)
Beispiel #11
0
def get_timeline_data(doctype, name):
	'''returns timeline data for the past one year'''
	from frappe.desk.form.load import get_communication_data

	out = {}
	fields = 'date(creation), count(name)'
	after = add_years(None, -1).strftime('%Y-%m-%d')
	group_by='group by date(creation)'

	data = get_communication_data(doctype, name,
		fields=fields, after=after, group_by=group_by, as_dict=False)

	# fetch and append data from Activity Log
	data += frappe.db.sql("""select {fields}
		from `tabActivity Log`
		where reference_doctype="{doctype}" and reference_name="{name}"
		and status!='Success' and creation > {after}
		{group_by} order by creation desc
		""".format(doctype=frappe.db.escape(doctype), name=frappe.db.escape(name), fields=fields,
			group_by=group_by, after=after), as_dict=False)

	timeline_items = dict(data)

	for date, count in iteritems(timeline_items):
		timestamp = get_timestamp(date)
		out.update({ timestamp: count })

	return out
Beispiel #12
0
	def validate(self):
		if not self.member or not frappe.db.exists("Member", self.member):
			member_name = frappe.get_value('Member', dict(email=frappe.session.user))

			if not member_name:
				user = frappe.get_doc('User', frappe.session.user)
				member = frappe.get_doc(dict(
					doctype='Member',
					email=frappe.session.user,
					membership_type=self.membership_type,
					member_name=user.get_fullname()
				)).insert(ignore_permissions=True)
				member_name = member.name

			if self.get("__islocal"):
				self.member = member_name

		# get last membership (if active)
		last_membership = erpnext.get_last_membership()

		# if person applied for offline membership
		if last_membership and not frappe.session.user == "Administrator":
			# if last membership does not expire in 30 days, then do not allow to renew
			if getdate(add_days(last_membership.to_date, -30)) > getdate(nowdate()) :
				frappe.throw(_('You can only renew if your membership expires within 30 days'))

			self.from_date = add_days(last_membership.to_date, 1)
		elif frappe.session.user == "Administrator":
			self.from_date = self.from_date
		else:
			self.from_date = nowdate()

		self.to_date = add_years(self.from_date, 1)
Beispiel #13
0
def get_scorecard_date(period, start_date):
    if period == 'Per Week':
        end_date = getdate(add_days(start_date, 7))
    elif period == 'Per Month':
        end_date = get_last_day(start_date)
    elif period == 'Per Year':
        end_date = add_days(add_years(start_date, 1), -1)
    return end_date
Beispiel #14
0
def get_timeline_data(doctype, name):
	'''returns timeline data for the past one year'''
	from frappe.desk.form.load import get_communication_data
	data = get_communication_data(doctype, name,
		fields = 'unix_timestamp(date(creation)), count(name)',
		after = add_years(None, -1).strftime('%Y-%m-%d'),
		group_by='group by date(creation)', as_dict=False)
	return dict(data)
def auto_status_update_ms(doc, method):
	new = add_years(doc.installation_date, doc.guarantee_period)
	new = add_days(new, days=-1)
	doc.amc_guarantee_valid_upto_date = new

	if doc.transaction_date:
		doc.amc_status = "Untraceable"
	elif date_diff(doc.transaction_date,doc.installation_date)<=365*doc.contract_period:
		doc.amc_status = "N/A"
	elif doc.amc_guarantee_valid_upto_date>doc.transaction_date:
		doc.amc_status = "Guarantee"
	else:
		doc.amc_status="Expired"
	
	if doc.amc_start_month:
		guarntee=add_years(doc.amc_start_month,doc.contract_period)
		guarntee = add_days(guarntee, days=-1)
		doc.amc_guarantee_valid_upto_date=guarntee
		doc.amc_status = "AMC"
	def make_holiday_list(self):
		if not frappe.db.get_value("Holiday List", "Salary Structure Test Holiday List"):
			holiday_list = frappe.get_doc({
				"doctype": "Holiday List",
				"holiday_list_name": "Salary Structure Test Holiday List",
				"from_date": nowdate(),
				"to_date": add_years(nowdate(), 1),
				"weekly_off": "Sunday"
			}).insert()
			holiday_list.get_weekly_off_dates()
			holiday_list.save()
Beispiel #17
0
	def make_holiday_list(self):
		if not frappe.db.get_value("Holiday List", "Salary Slip Test Holiday List"):
			holiday_list = frappe.get_doc({
				"doctype": "Holiday List",
				"holiday_list_name": "Salary Slip Test Holiday List",
				"from_date": nowdate(),
				"to_date": add_years(nowdate(), 1),
				"weekly_off": "Sunday"
			}).insert()	
			holiday_list.get_weekly_off_dates()
			holiday_list.save()
Beispiel #18
0
def get_timeline_data(doctype, name):
    '''returns timeline data for the past one year'''
    from frappe.desk.form.load import get_communication_data
    data = get_communication_data(
        doctype,
        name,
        fields='unix_timestamp(date(creation)), count(name)',
        after=add_years(None, -1).strftime('%Y-%m-%d'),
        group_by='group by date(creation)',
        as_dict=False)
    return dict(data)
Beispiel #19
0
def get_retirement_date(date_of_birth=None):
	ret = {}
	if date_of_birth:
		try:
			retirement_age = int(frappe.db.get_single_value("HR Settings", "retirement_age") or 60)
			dt = add_years(getdate(date_of_birth),retirement_age)
			ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
		except ValueError:
			# invalid date
			ret = {}

	return ret
Beispiel #20
0
def get_retirement_date(date_of_birth=None):
	ret = {}
	if date_of_birth:
		try:
			retirement_age = int(frappe.db.get_single_value("HR Settings", "retirement_age") or 60)
			dt = add_years(getdate(date_of_birth),retirement_age)
			ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
		except ValueError:
			# invalid date
			ret = {}

	return ret
Beispiel #21
0
def add_age_to_filter(filters, doctype, field, date):
	from frappe.utils import now_datetime, add_days, add_months, add_years, get_datetime_str

	if date == "All Time":
		return filters
	today = now_datetime()
	selected_dates = {
	'Last 7 Days': [add_days(today,-6)],
	'Last 30 Days': [add_days(today,-29)],
	'This Month': [add_days(today, -today.day)],
	'Last Month': [add_months(add_days(today, -today.day),-1), add_days(today, -today.day-1)],
	'Last 3 Months': [add_months(add_days(today, -today.day),-3)],
	'This Financial Year': [frappe.db.get_default("year_start_date"),frappe.db.get_default("year_end_date")],
	'Last Financial Year': [add_years(frappe.db.get_default("year_start_date"), -1),
		add_years(frappe.db.get_default("year_end_date"), -1)]
	}[date]

	if len(selected_dates)==2:
		return filters + [[ doctype, field,">", get_datetime_str(selected_dates[0]) ],
			[ doctype, field, "<", get_datetime_str(selected_dates[1]) ]]
	else:
		return filters + [[ doctype, field, ">", get_datetime_str(selected_dates[0]) ]]
Beispiel #22
0
def get_retirement_date_for_gender(date_of_birth=None, gender=None):
    ret = {}
    if date_of_birth and gender:
        try:
            if gender == 'Male':
                retirement_age = int(frappe.db.get_single_value("HR Settings", "retirement_age_for_male") or 60)
            elif gender == 'Female':
                retirement_age = int(frappe.db.get_single_value("HR Settings", "retirement_age_for_female") or 55)
            dt = add_years(getdate(date_of_birth), retirement_age)
            ret = {'date_of_retirement': dt.strftime('%Y-%m-%d')}
        except ValueError:
            # invalid date
            ret = {}

    return ret
Beispiel #23
0
 def validate_admission_age(self):
     student_admission = get_student_admission_data(self.student_admission,
                                                    self.program)
     if student_admission and student_admission.cutoff_birthdate and getdate(
             self.date_of_birth) > getdate(
                 student_admission.cutoff_birthdate):
         frappe.throw(
             _("{0} is not eligible for admission to this program as per date of birth."
               ).format(self.title))
     if student_admission and student_admission.maximum_age and date_diff(
             nowdate(),
             add_years(get_date(self.date_of_birth),
                       student_admission.maximum_age)) > 0:
         frappe.throw(
             _("{0} is not eligible for admission to this program as per date of birth."
               ).format(self.title))
Beispiel #24
0
def get_timeline_data(doctype, name):
	'''returns timeline data for the past one year'''
	from frappe.desk.form.load import get_communication_data

	out = {}
	data = get_communication_data(doctype, name,
		fields = 'date(creation), count(name)',
		after = add_years(None, -1).strftime('%Y-%m-%d'),
		group_by='group by date(creation)', as_dict=False)

	timeline_items = dict(data)

	for date, count in timeline_items.iteritems():
		timestamp = get_timestamp(date)
		out.update({ timestamp: count })

	return out
Beispiel #25
0
def auto_create_fiscal_year():
	for d in frappe.db.sql("""select name from `tabFiscal Year` where year_end_date = date_add(current_date, interval 3 day)"""):
		try:
			current_fy = frappe.get_doc("Fiscal Year", d[0])

			new_fy = frappe.copy_doc(current_fy, ignore_no_copy=False)

			new_fy.year_start_date = add_days(current_fy.year_end_date, 1)
			new_fy.year_end_date = add_years(current_fy.year_end_date, 1)

			start_year = cstr(new_fy.year_start_date.year)
			end_year = cstr(new_fy.year_end_date.year)
			new_fy.year = start_year if start_year==end_year else (start_year + "-" + end_year)

			new_fy.insert(ignore_permissions=True)
		except frappe.NameError:
			pass
Beispiel #26
0
def auto_create_fiscal_year():
	for d in frappe.db.sql("""select name from `tabFiscal Year` where year_end_date = date_add(current_date, interval 3 day)"""):
		try:
			current_fy = frappe.get_doc("Fiscal Year", d[0])

			new_fy = frappe.copy_doc(current_fy, ignore_no_copy=False)

			new_fy.year_start_date = add_days(current_fy.year_end_date, 1)
			new_fy.year_end_date = add_years(current_fy.year_end_date, 1)

			start_year = cstr(new_fy.year_start_date.year)
			end_year = cstr(new_fy.year_end_date.year)
			new_fy.year = start_year if start_year==end_year else (start_year + "-" + end_year)

			new_fy.insert()
		except frappe.NameError:
			pass
def auto_create_fiscal_year():
	for d in frappe.db.sql("""select name from `tabFiscal Year` where year_end_date =(current_date + 3)"""):
		try:
			current_fy = frappe.get_doc("Fiscal Year", d[0])

			new_fy = frappe.copy_doc(current_fy)

			new_fy.year_start_date = add_days(current_fy.year_end_date, 1)
			new_fy.year_end_date = add_years(current_fy.year_end_date, 1)

			start_year = new_fy.year_start_date[:4]
			end_year = new_fy.year_end_date[:4]
			new_fy.year = start_year if start_year==end_year else (start_year + "-" + end_year)

			new_fy.insert()
		except frappe.NameError:
			pass
Beispiel #28
0
def auto_create_fiscal_year():
	for d in frappe.db.sql("""select name from `tabFiscal Year` where year_end_date =(current_date + 3)"""):
		try:
			current_fy = frappe.get_doc("Fiscal Year", d[0])

			new_fy = frappe.copy_doc(current_fy)

			new_fy.year_start_date = add_days(current_fy.year_end_date, 1)
			new_fy.year_end_date = add_years(current_fy.year_end_date, 1)

			start_year = new_fy.year_start_date[:4]
			end_year = new_fy.year_end_date[:4]
			new_fy.year = start_year if start_year==end_year else (start_year + "-" + end_year)

			new_fy.insert()
		except frappe.NameError:
			pass
Beispiel #29
0
def get_timeline_data(doctype, name):
	'''returns timeline data for the past one year'''
	from frappe.desk.form.load import get_communication_data

	out = {}
	data = get_communication_data(doctype, name,
		fields = 'date(creation), count(name)',
		after = add_years(None, -1).strftime('%Y-%m-%d'),
		group_by='group by date(creation)', as_dict=False)

	timeline_items = dict(data)

	for date, count in timeline_items.iteritems():
		timestamp = get_timestamp(date)
		out.update({ timestamp: count })

	return out
Beispiel #30
0
	def validate(self):

		# get last membership (if active)
		last_membership = erpnext.get_last_membership()

		# if person applied for offline membership
		if last_membership and not frappe.session.user == "Administrator":
			# if last membership does not expire in 30 days, then do not allow to renew
			if getdate(add_days(last_membership.to_date, -30)) > getdate(nowdate()) :
				frappe.throw(_('You can only renew if your membership expires within 30 days'))

			self.from_date = add_days(last_membership.to_date, 1)
		elif frappe.session.user == "Administrator":
			self.from_date = self.from_date
		else:
			self.from_date = nowdate()

		self.to_date = add_years(self.from_date, 1)
Beispiel #31
0
	def validate_membership_period(self):
		# get last membership (if active)
		last_membership = erpnext.get_last_membership(self.member)

		# if person applied for offline membership
		if last_membership and not frappe.session.user == "Administrator":
			# if last membership does not expire in 30 days, then do not allow to renew
			if getdate(add_days(last_membership.to_date, -30)) > getdate(nowdate()) :
				frappe.throw(_("You can only renew if your membership expires within 30 days"))

			self.from_date = add_days(last_membership.to_date, 1)
		elif frappe.session.user == "Administrator":
			self.from_date = self.from_date
		else:
			self.from_date = nowdate()

		if frappe.db.get_single_value("Non Profit Settings", "billing_cycle") == "Yearly":
			self.to_date = add_years(self.from_date, 1)
		else:
			self.to_date = add_months(self.from_date, 1)
Beispiel #32
0
    def validate(self):

        # get last membership (if active)
        last_membership = erpnext.get_last_membership()

        # if person applied for offline membership
        if last_membership and not frappe.session.user == "Administrator":
            # if last membership does not expire in 30 days, then do not allow to renew
            if getdate(add_days(last_membership.to_date, -30)) > getdate(
                    nowdate()):
                frappe.throw(
                    _('You can only renew if your membership expires within 30 days'
                      ))

            self.from_date = add_days(last_membership.to_date, 1)
        elif frappe.session.user == "Administrator":
            self.from_date = self.from_date
        else:
            self.from_date = nowdate()

        self.to_date = add_years(self.from_date, 1)
Beispiel #33
0
def validate(doc, method):
    delelte_all_related_practitioner_availability_detail(doc)
    if not doc.repeat_this_event:
        detail_doc = create_practitioner_availability_detail(
            doc, doc.from_date)
        detail_doc.insert(ignore_permissions=True)
    else:
        start_date = doc.from_date
        end_date = doc.repeat_till
        current_date = start_date

        if doc.repeat_on == "Every Year":
            while check_dates(current_date, end_date):
                detail_doc = create_practitioner_availability_detail(
                    doc, current_date)
                detail_doc.insert(ignore_permissions=True)
                current_date = add_years(current_date, 1)

        elif doc.repeat_on == "Every Month":
            while check_dates(current_date, end_date):
                detail_doc = create_practitioner_availability_detail(
                    doc, current_date)
                detail_doc.insert(ignore_permissions=True)
                current_date = add_months(current_date, 1)

        elif doc.repeat_on == "Every Week":
            while check_dates(current_date, end_date):
                detail_doc = create_practitioner_availability_detail(
                    doc, current_date)
                detail_doc.insert(ignore_permissions=True)
                current_date = add_days(current_date, 7)

        elif doc.repeat_on == "Every Day":
            while check_dates(current_date, end_date):
                weekday = get_weekday(current_date)
                if doc.get(weekday):
                    detail_doc = create_practitioner_availability_detail(
                        doc, current_date)
                    detail_doc.insert(ignore_permissions=True)
                current_date = add_days(current_date, 1)
Beispiel #34
0
    def get_events(self, remote_objectname, filters, page_length):
        page_token = None
        results = []
        events = {"items": []}
        while True:
            try:
                events = self.gcalendar.events().list(
                    calendarId=self.account.gcalendar_id,
                    maxResults=page_length,
                    singleEvents=False,
                    showDeleted=True,
                    syncToken=self.account.next_sync_token or None).execute()
            except HttpError as err:
                if err.resp.status in [410]:
                    events = self.gcalendar.events().list(
                        calendarId=self.account.gcalendar_id,
                        maxResults=page_length,
                        singleEvents=False,
                        showDeleted=True,
                        timeMin=add_years(
                            None,
                            -1).strftime('%Y-%m-%dT%H:%M:%SZ')).execute()
                else:
                    frappe.log_error(err.resp, "GCalendar Events Fetch Error")
            for event in events['items']:
                event.update({'account': self.account.name})
                event.update({'calendar_tz': events['timeZone']})
                results.append(event)

            page_token = events.get('nextPageToken')
            if not page_token:
                if events.get('nextSyncToken'):
                    frappe.db.set_value("GCalendar Account",
                                        self.connector.username,
                                        "next_sync_token",
                                        events.get('nextSyncToken'))
                break
        return list(results)
Beispiel #35
0
 def update_item(source, target, source_parent):
     if source.is_maintenance_applicable_cf == 0:
         frappe.msgprint(_(
             'Delivery Note item <b>{0}</b> has no value for <i>Is Maintenance Applicable ?</i>'
         ).format(source.item_code),
                         title='Maintenance Schedule cannot be created.')
         return False
     elif source.is_maintenance_applicable_cf == 1:
         if source.maintenance_for_years_cf < 2:
             frappe.msgprint(_(
                 'Delivery Note item <b>{0}</b> has <i>Maintenance For Years</i> values as <b>{1}</b>. <br> It should be greater than 1.'
             ).format(source.item_code, source.maintenance_for_years_cf),
                             title='Incorrect Maintenance For Years values.'
                             )
             return False
     # + 1
     target.start_date = add_days(source_parent.posting_date, 1)
     target.end_date = add_years(target.start_date,
                                 source.maintenance_for_years_cf)
     target.periodicity = 'Yearly'
     target.no_of_visits = source.maintenance_for_years_cf
     target.serial_no = source.serial_no
     target.sales_person = sales_person_name or 'Sales Team'
Beispiel #36
0
Datei: api.py Projekt: frappe/iff
def create_member(customer_id, plan, pan=None):
    client = get_client()
    customer = frappe._dict(client.customer.fetch(customer_id))

    # defaults
    today = getdate()
    plan = frappe.db.exists("Membership Type", {"razorpay_plan_id": plan})

    member = frappe.new_doc("Member")
    member.update({
        "member_name": customer.name,
        "membership_type": plan,
        "pan_number": pan,
        "email_id": customer.email,
        "contact": customer.contact,
        "customer_id": customer_id,
        "subscription_activated": 1,
        "token_status": "Initiated",
        "subscription_start": today,
        "subscription_end": add_years(today, 2),
    })
    member.insert(ignore_permissions=True)

    return member.name
Beispiel #37
0
from frappe.model.document import Document
from frappe.utils.user import get_enabled_system_users
from frappe.desk.reportview import get_filters_cond
from frappe.utils import (getdate, cint, add_months, date_diff, add_days,
                          add_years, nowdate, get_datetime_str, cstr,
                          get_datetime, now_datetime, format_datetime)
from frappe.utils.background_jobs import enqueue

from erpnext.hr.doctype.employee.employee import get_employee_emails

weekdays = [
    "monday", "tuesday", "wednesday", "thursday", "friday", "saturday",
    "sunday"
]
max_repeat_till = add_years(nowdate(), 1)


class vBookingEvent(Document):
    def validate(self):

        self.employee_emails = ', '.join(
            get_employee_emails([d.employee for d in self.employees]))

        if not self.starts_on:
            self.starts_on = now_datetime()

        if self.starts_on and self.ends_on and get_datetime(
                self.starts_on) > get_datetime(self.ends_on):
            frappe.msgprint(frappe._("Event end must be after start"),
                            raise_exception=True)
Beispiel #38
0
def add_year(date):
	return utils.add_years(date, 1)
Beispiel #39
0
def set_salary_structure_for_all(doc):
    employees = frappe.get_list(
        "Employee", filters={"status": "Active"}, fields=["*"])
    for emp in employees:
        ss = frappe.get_doc({
            "name":
            emp.employee_name,
            "doctype":
            "Salary Structure",
            "company":
            doc.company,
            "is_active":
            "Yes",
            "payroll_frequency":
            "Monthly",
            "is_default":
            "Yes",
            "payment_account":
            get_default_payroll_payable_account(doc),
            "employees": [{
                "docstatus": 0,
                "doctype": "Salary Structure Employee",
                "name": "New Salary Structure Employee 1",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "parent": "New Salary Structure 1",
                "parentfield": "employees",
                "parenttype": "Salary Structure",
                "idx": 1,
                "company": doc.company,
                "employee_name": emp.employee_name,
                "employee": emp.name,
                "from_date": today(),
                "base": 0,
                "to_date": add_years(today(), 1)
            }],
            "earnings": [{
                "docstatus": 0,
                "doctype": "Salary Detail",
                "name": "New Salary Detail 1",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "amount_based_on_formula": 1,
                "parent": "New Salary Structure 1",
                "parentfield": "earnings",
                "parenttype": "Salary Structure",
                "idx": 1,
                "__unedited": 0,
                "abbr": "B",
                "salary_component": "Basic",
                "amount": 0
            }, {
                "docstatus": 0,
                "doctype": "Salary Detail",
                "name": "New Salary Detail 2",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "amount_based_on_formula": 1,
                "parent": "New Salary Structure 1",
                "parentfield": "earnings",
                "parenttype": "Salary Structure",
                "idx": 2,
                "__unedited": 0,
                "abbr": "H",
                "salary_component": "Housing",
                "formula": "B * .25"
            }, {
                "docstatus": 0,
                "doctype": "Salary Detail",
                "name": "New Salary Detail 3",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "amount_based_on_formula": 1,
                "parent": "New Salary Structure 1",
                "parentfield": "earnings",
                "parenttype": "Salary Structure",
                "idx": 2,
                "__unedited": 0,
                "abbr": "TA",
                "salary_component": "Transportation",
                "formula": "B * .10"
            }],
            "deductions": [{
                "docstatus": 0,
                "doctype": "Salary Detail",
                "name": "New Salary Detail 5",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "amount_based_on_formula": 1,
                "parent": "New Salary Structure 1",
                "parentfield": "deductions",
                "parenttype": "Salary Structure",
                "idx": 1,
                "__unedited": 0,
                "abbr": "GOSI",
                "salary_component": "GOSI",
                "formula": "B *.09"
            }, {
                "docstatus": 0,
                "doctype": "Salary Detail",
                "name": "New Salary Detail 6",
                "__islocal": 1,
                "__unsaved": 1,
                "owner": frappe.session.user,
                "amount_based_on_formula": 1,
                "parent": "New Salary Structure 1",
                "parentfield": "deductions",
                "parenttype": "Salary Structure",
                "idx": 2,
                "__unedited": 0,
                "abbr": "SAND",
                "salary_component": "SAND",
                "formula": "B *.01"
            }]
        }).insert()
    frappe.msgprint(_("Salary Structure is added to all Employees"))