def test_create_subscription_with_trial_with_correct_period(self):
		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.trial_period_start = nowdate()
		subscription.trial_period_end = add_days(nowdate(), 30)
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()

		self.assertEqual(subscription.trial_period_start, nowdate())
		self.assertEqual(subscription.trial_period_end, add_days(nowdate(), 30))
		self.assertEqual(subscription.trial_period_start, subscription.current_invoice_start)
		self.assertEqual(subscription.trial_period_end, subscription.current_invoice_end)
		self.assertEqual(subscription.invoices, [])
		self.assertEqual(subscription.status, 'Trialling')

		subscription.delete()
Exemple #2
0
    def process_for_active(self):
        """
		Called by `process` if the status of the `Subscription` is 'Active'.

		The possible outcomes of this method are:
		1. Generate a new invoice
		2. Change the `Subscription` status to 'Past Due Date'
		3. Change the `Subscription` status to 'Cancelled'
		"""

        if not self.is_current_invoice_generated(
                self.current_invoice_start, self.current_invoice_end) and (
                    self.is_postpaid_to_invoice()
                    or self.is_prepaid_to_invoice()):

            prorate = frappe.db.get_single_value("Subscription Settings",
                                                 "prorate")
            self.generate_invoice(prorate)

        if getdate() > getdate(
                self.current_invoice_end) and self.is_prepaid_to_invoice():
            self.update_subscription_period(
                add_days(self.current_invoice_end, 1))

        if self.cancel_at_period_end and getdate() > getdate(
                self.current_invoice_end):
            self.cancel_subscription_at_period_end()
Exemple #3
0
	def process_for_past_due_date(self):
		"""
		Called by `process` if the status of the `Subscription` is 'Past Due Date'.

		The possible outcomes of this method are:
		1. Change the `Subscription` status to 'Active'
		2. Change the `Subscription` status to 'Cancelled'
		3. Change the `Subscription` status to 'Unpaid'
		"""
		current_invoice = self.get_current_invoice()
		if not current_invoice:
			frappe.throw(_('Current invoice {0} is missing'.format(current_invoice.invoice)))
		else:
			if not self.has_outstanding_invoice():
				self.status = 'Active'
			else:
				self.set_status_grace_period()

			if getdate() > getdate(self.current_invoice_end):
				self.update_subscription_period(add_days(self.current_invoice_end, 1))

			# Generate invoices periodically even if current invoice are unpaid
			if self.generate_new_invoices_past_due_date and not self.is_current_invoice_generated() and (self.is_postpaid_to_invoice()
				or self.is_prepaid_to_invoice()):
				prorate = frappe.db.get_single_value('Subscription Settings', 'prorate')
				self.generate_invoice(prorate)
Exemple #4
0
	def test_subscription_is_past_due_doesnt_change_within_grace_period(self):
		settings = frappe.get_single("Subscription Settings")
		grace_period = settings.grace_period
		settings.grace_period = 1000
		settings.save()

		subscription = frappe.new_doc("Subscription")
		subscription.party_type = "Customer"
		subscription.party = "_Test Customer"
		subscription.append("plans", {"plan": "_Test Plan Name", "qty": 1})
		subscription.start_date = add_days(nowdate(), -1000)
		subscription.insert()
		subscription.process()  # generate first invoice

		self.assertEqual(subscription.status, "Past Due Date")

		subscription.process()
		# Grace period is 1000 days so status should remain as Past Due Date
		self.assertEqual(subscription.status, "Past Due Date")

		subscription.process()
		self.assertEqual(subscription.status, "Past Due Date")

		subscription.process()
		self.assertEqual(subscription.status, "Past Due Date")

		settings.grace_period = grace_period
		settings.save()
		subscription.delete()
Exemple #5
0
    def test_subscription_is_past_due_doesnt_change_within_grace_period(self):
        settings = frappe.get_single('Subscription Settings')
        grace_period = settings.grace_period
        settings.grace_period = 1000
        settings.save()

        subscription = frappe.new_doc('Subscription')
        subscription.party_type = 'Customer'
        subscription.party = '_Test Customer'
        subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
        subscription.start_date = add_days(nowdate(), -1000)
        subscription.insert()
        subscription.process()  # generate first invoice

        self.assertEqual(subscription.status, 'Past Due Date')

        subscription.process()
        # Grace period is 1000 days so status should remain as Past Due Date
        self.assertEqual(subscription.status, 'Past Due Date')

        subscription.process()
        self.assertEqual(subscription.status, 'Past Due Date')

        subscription.process()
        self.assertEqual(subscription.status, 'Past Due Date')

        settings.grace_period = grace_period
        settings.save()
        subscription.delete()
Exemple #6
0
def checkin_alerts():
    # yesterday = add_days(today(),-2)
    yesterday = add_days(datetime.datetime.today(), -17).date()
    current_month = yesterday.month
    late_checkins = frappe.db.sql(
        "select employee from `tabEmployee Checkin` where date(time) = '%s' and time(time) > '09:35:00' "
        % (yesterday),
        as_dict=True)
    frappe.errprint(late_checkins)
    if late_checkins:
        for emp in late_checkins:
            apid = frappe.db.exists('Attendance Permission', {
                'employee': emp.employee,
                'month': current_month
            })
            print(emp)
            if apid:
                pc = frappe.get_value('Attendance Permission', apid,
                                      'permission_count')
                if pc < 3:
                    #adding permission
                    ap = frappe.get_doc('Attendance Permission', apid)
                    ap.update({'permission_count': pc + 1})
                    ap.save(ignore_permissions=True)
                    frappe.db.commit()

                    lp = frappe.db.exists(
                        'Leave Application', {
                            'employee': emp.employee,
                            'from_date': yesterday,
                            'to_date': yesterday
                        })
                    if lap:
                        pass
                else:
                    lw = frappe.new_doc('Leave Application')
                    lw.update({
                        'employee':
                        emp.employee,
                        'leave_type':
                        "Leave Without Pay",
                        'from_date':
                        yesterday,
                        'to_date':
                        yesterday,
                        'description':
                        'Auto marked as LWP due to Exceed Monthly Permission Limit'
                    })
                    lw.save(ignore_permissions=True)
                    frappe.db.commit()

            else:
                ap = frappe.new_doc('Attendance Permission')
                ap.update({
                    'employee': emp.employee,
                    'month': current_month,
                    'permission_count': 1
                })
                ap.save(ignore_permissions=True)
                frappe.db.commit()
Exemple #7
0
	def test_create_subscription_with_trial_with_correct_period(self):
		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.trial_period_start = nowdate()
		subscription.trial_period_end = add_days(nowdate(), 30)
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()

		self.assertEqual(subscription.trial_period_start, nowdate())
		self.assertEqual(subscription.trial_period_end, add_days(nowdate(), 30))
		self.assertEqual(subscription.trial_period_start, subscription.current_invoice_start)
		self.assertEqual(subscription.trial_period_end, subscription.current_invoice_end)
		self.assertEqual(subscription.invoices, [])
		self.assertEqual(subscription.status, 'Trialling')

		subscription.delete()
Exemple #8
0
def handle_timesheet(user,
                     doctype,
                     reference,
                     time,
                     bemerkung='',
                     date=nowdate()):
    _date = getdate(date)
    latest_date = getdate(add_days(nowdate(), -7))
    if _date < latest_date:
        frappe.throw(
            "Sie können maximal 7 Tage in die Vergangenheit buchungen vornehmen."
        )
    user = frappe.db.sql(
        """SELECT `name` FROM `tabEmployee` WHERE `user_id` = '{user}'""".
        format(user=user),
        as_list=True)
    if not user:
        frappe.throw("Es wurde kein Mitarbeiterstamm gefunden!")
    else:
        user = user[0][0]
    if not time:
        time = 0.000
    else:
        time = float(time)
    ts = check_if_timesheet_exist(user, date)
    if ts == 'gebucht':
        frappe.throw("Das Timesheet vom {datum} ist bereits verbucht.".format(
            date=date))
    elif ts == 'neuanlage':
        create_timesheet(user, doctype, reference, time, bemerkung, date)
    else:
        update_timesheet(ts, time, doctype, reference, user, bemerkung, date)
Exemple #9
0
def lwp_alert():
    yesterday = add_days(today(), -19)
    employees = frappe.get_all('Employee', {'status': 'Active'},
                               ['name', 'employee_name', 'employee'])
    for emp in employees:
        lc = frappe.db.sql(
            "select employee from `tabEmployee Checkin` where date(time) = '%s' and employee = '%s'"
            % (yesterday, emp.name),
            as_dict=True)
        lap = frappe.db.exists('Leave Application', {
            'employee': emp.employee,
            'from_date': yesterday,
            'to_date': yesterday
        })
        if lap:
            pass
        if len(lc) < 2:
            lp = frappe.new_doc('Leave Application')
            lp.update({
                'employee':
                emp.employee,
                'leave_type':
                "Leave Without Pay",
                'from_date':
                yesterday,
                'to_date':
                yesterday,
                'description':
                'Auto marked as LWP due to not responding Miss Punch Alert'
            })
            lp.save()
            frappe.db.commit()
Exemple #10
0
	def create_invoice(self, prorate):
		"""
		Creates a `Sales Invoice`, submits it and returns it
		"""
		invoice = frappe.new_doc('Sales Invoice')
		invoice.set_posting_time = 1
		invoice.posting_date = self.current_invoice_start
		invoice.customer = self.customer

		## Add dimesnions in invoice for subscription:
		accounting_dimensions = get_accounting_dimensions()

		for dimension in accounting_dimensions:
			if self.get(dimension):
				invoice.update({
					dimension: self.get(dimension)
				})

		# Subscription is better suited for service items. I won't update `update_stock`
		# for that reason
		items_list = self.get_items_from_plans(self.plans, prorate)
		for item in items_list:
			invoice.append('items',	item)

		# Taxes
		if self.tax_template:
			invoice.taxes_and_charges = self.tax_template
			invoice.set_taxes()

		# Due date
		if self.days_until_due:
			invoice.append(
				'payment_schedule',
				{
					'due_date': add_days(self.current_invoice_end, cint(self.days_until_due)),
					'invoice_portion': 100
				}
			)

		# Discounts
		if self.additional_discount_percentage:
			invoice.additional_discount_percentage = self.additional_discount_percentage

		if self.additional_discount_amount:
			invoice.discount_amount = self.additional_discount_amount

		if self.additional_discount_percentage or self.additional_discount_amount:
			discount_on = self.apply_additional_discount
			invoice.apply_discount_on = discount_on if discount_on else 'Grand Total'

		# Subscription period
		invoice.from_date = self.current_invoice_start
		invoice.to_date = self.current_invoice_end

		invoice.flags.ignore_mandatory = True
		invoice.save()
		invoice.submit()

		return invoice
Exemple #11
0
	def before_save(self):
		has_expiry_date, shelf_life_in_days = frappe.db.get_value('Item', self.item, ['has_expiry_date', 'shelf_life_in_days'])
		if not self.expiry_date and has_expiry_date and shelf_life_in_days:
			self.expiry_date = add_days(self.manufacturing_date, shelf_life_in_days)

		if has_expiry_date and not self.expiry_date:
			frappe.throw(_('Expiry date is mandatory for selected item'))
			frappe.msgprint(_('Set items shelf life in days, to set expiry based on manufacturing_date plus self life'))
Exemple #12
0
	def before_save(self):
		has_expiry_date, shelf_life_in_days = frappe.db.get_value('Item', self.item, ['has_expiry_date', 'shelf_life_in_days'])
		if not self.expiry_date and has_expiry_date and shelf_life_in_days:
			self.expiry_date = add_days(self.manufacturing_date, shelf_life_in_days)

		if has_expiry_date and not self.expiry_date:
			frappe.throw(_('Expiry date is mandatory for selected item'))
			frappe.msgprint(_('Set items shelf life in days, to set expiry based on manufacturing_date plus self life'))
Exemple #13
0
 def convert_interest_to_principal(self, posting_date, cancel=0, adv_adj=0):
     periods = get_billing_periods(self.name, add_days(posting_date, -1), 1)
     if len(periods) != 1:
         return None
     amount = periods[0].get('interest')
     late_amount = amount * self.rate_of_late_charges / 100
     if amount:
         billing_period = periods[0].get('as_text')
         self.posting_date = posting_date
         gl_entries = [
             self.get_gl_dict({
                 'account': self.interest_receivable_account,
                 'credit': amount,
                 'party_type': 'Customer',
                 'party': self.customer,
                 'against': self.loan_account,
                 'period': billing_period,
             }),
             self.get_gl_dict({
                 'account':
                 self.loan_account,
                 'debit':
                 amount,
                 'against':
                 self.interest_receivable_account,
                 'remarks':
                 'Converted to principal for: {}'.format(billing_period),
             })
         ]
         if self.rate_of_late_charges:
             late_amount = amount * self.rate_of_late_charges / 100
             gl_entries.append(
                 self.get_gl_dict({
                     'account':
                     self.interest_income_account,
                     'credit':
                     late_amount,
                     'against':
                     self.customer,
                     'cost_center':
                     frappe.db.get_value('Loan Settings', None,
                                         'cost_center'),
                     'remarks':
                     'Late charges for period: {}'.format(billing_period),
                 }))
             gl_entries.append(
                 self.get_gl_dict({
                     'account':
                     self.loan_account,
                     'debit':
                     late_amount,
                     'against':
                     self.interest_receivable_account,
                     'remarks':
                     'Converted to principal for: {}'.format(
                         billing_period),
                 }))
         make_gl_entries(gl_entries, cancel=cancel, adv_adj=adv_adj)
Exemple #14
0
    def test_create_subscription_trial_with_wrong_dates(self):
        subscription = frappe.new_doc('Subscription')
        subscription.subscriber = '_Test Customer'
        subscription.trial_period_end = nowdate()
        subscription.trial_period_start = add_days(nowdate(), 30)
        subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})

        self.assertRaises(frappe.ValidationError, subscription.save)
        subscription.delete()
Exemple #15
0
 def validate_subscription_period(self):
     if self.trial_period_start and getdate(
             self.trial_period_end) >= getdate(
                 self.current_invoice_end) and not self.is_trial():
         self.update_subscription_period(add_days(self.trial_period_end, 1))
     elif self.is_new_subscription():
         self.update_subscription_period(self.start)
     elif self.has_invoice_for_period():
         self.update_subscription_period(self.current_invoice_start)
	def test_create_subscription_trial_with_wrong_dates(self):
		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.trial_period_end = nowdate()
		subscription.trial_period_start = add_days(nowdate(), 30)
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})

		self.assertRaises(frappe.ValidationError, subscription.save)
		subscription.delete()
def berechnung_anzahl_mo_bis_fr(von, bis):
    anzahl_mo_bis_fr = 0
    _von = getdate(von)
    _bis = getdate(bis)
    while _von <= _bis:
        if _von.weekday() < 5:
            anzahl_mo_bis_fr += 1
        _von = add_days(_von, 1)
    return anzahl_mo_bis_fr
Exemple #18
0
	def test_create_subscription_trial_with_wrong_dates(self):
		subscription = frappe.new_doc("Subscription")
		subscription.party_type = "Customer"
		subscription.party = "_Test Customer"
		subscription.trial_period_end = nowdate()
		subscription.trial_period_start = add_days(nowdate(), 30)
		subscription.append("plans", {"plan": "_Test Plan Name", "qty": 1})

		self.assertRaises(frappe.ValidationError, subscription.save)
		subscription.delete()
Exemple #19
0
	def is_past_grace_period(self):
		"""
		Returns `True` if the grace period for the `Subscription` has passed
		"""
		current_invoice = self.get_current_invoice()
		if self.current_invoice_is_past_due(current_invoice):
			subscription_settings = frappe.get_single('Subscription Settings')
			grace_period = cint(subscription_settings.grace_period)

			return getdate(nowdate()) > add_days(current_invoice.due_date, grace_period)
Exemple #20
0
def auto_ts_submit():
    #************************************************************************************
    #overwrite the time_log overlap validation of timesheet and the on_submit validation
    overwrite_ts_validation()
    overwrite_ts_on_submit()
    #************************************************************************************

    # correct twh:
    ts_list = frappe.db.sql(
        """SELECT `name` FROM `tabTimesheet` WHERE `docstatus` = 0 AND `start_date` < '{last_week}'"""
        .format(last_week=add_days(nowdate(), -7)),
        as_dict=True)
    for _ts in ts_list:
        ts = frappe.get_doc("Timesheet", _ts.name)
        arbeitszeit = 0
        for log in ts.time_logs:
            if log.activity_type == "Arbeitszeit":
                arbeitszeit += log.hours
            if log.activity_type == "Pause":
                arbeitszeit -= log.hours
        ts.twh = arbeitszeit
        try:
            ts.save()
        except:
            continue

    # check and submit ts:
    ts_list = frappe.db.sql(
        """SELECT `name` FROM `tabTimesheet` WHERE `docstatus` = 0 AND `start_date` < '{last_week}'"""
        .format(last_week=add_days(nowdate(), -7)),
        as_dict=True)
    for _ts in ts_list:
        ts = frappe.get_doc("Timesheet", _ts.name)
        ruckmeldungen = 0
        arbeitszeit = 0
        for log in ts.time_logs:
            if log.activity_type != "Pause" and log.activity_type != "Arbeitszeit":
                ruckmeldungen += log.hours
        if ruckmeldungen <= ts.twh:
            try:
                ts.submit()
            except:
                continue
Exemple #21
0
	def is_past_grace_period(self):
		"""
		Returns `True` if the grace period for the `Subscription` has passed
		"""
		current_invoice = self.get_current_invoice()
		if self.current_invoice_is_past_due(current_invoice):
			subscription_settings = frappe.get_single('Subscription Settings')
			grace_period = cint(subscription_settings.grace_period)

			return getdate(nowdate()) > add_days(current_invoice.due_date, grace_period)
Exemple #22
0
    def process(self):
        if self.cancellation_date and self.period_has_passed(
                add_days(self.cancellation_date, -1)):
            self.cancel_subscription()

        if self.status == 'Active':
            if not (self.payment_gateway and self.payment_gateway_reference):
                self.process_active_subscription()
        elif self.status == 'Trial':
            self.set_subscription_status()
Exemple #23
0
    def test_create_subscription_multi_with_different_billing_fails(self):
        subscription = frappe.new_doc('Subscription')
        subscription.subscriber = '_Test Customer'
        subscription.trial_period_end = nowdate()
        subscription.trial_period_start = add_days(nowdate(), 30)
        subscription.append('plans', {'plan': '_Test Plan Name'})
        subscription.append('plans', {'plan': '_Test Plan Name 3'})

        self.assertRaises(frappe.ValidationError, subscription.save)
        subscription.delete()
Exemple #24
0
	def before_save(self):
		has_expiry_date, shelf_life_in_days = frappe.db.get_value('Item', self.item, ['has_expiry_date', 'shelf_life_in_days'])
		if not self.expiry_date and has_expiry_date and shelf_life_in_days:
			self.expiry_date = add_days(self.manufacturing_date, shelf_life_in_days)

		if has_expiry_date and not self.expiry_date:
			frappe.throw(msg=_("Please set {0} for Batched Item {1}, which is used to set {2} on Submit.") \
				.format(frappe.bold("Shelf Life in Days"),
					get_link_to_form("Item", self.item),
					frappe.bold("Batch Expiry Date")),
				title=_("Expiry Date Mandatory"))
Exemple #25
0
def execute(filters=None):
    data = []
    columns = [{
        "label": _("Sales Order"),
        "fieldname": "sales_order",
        "fieldtype": "Link",
        "options": "Sales Order"
    }, {
        "label": _("Customer"),
        "fieldname": "customer",
        "fieldtype": "Link",
        "options": "Customer"
    }, {
        "label": _("Customer Name"),
        "fieldname": "customer_name",
        "fieldtype": "Data"
    }, {
        "label": _("Liefertermin"),
        "fieldname": "liefertermin",
        "fieldtype": "Date"
    }, {
        "label": _("Vorlaufzeit Versand"),
        "fieldname": "vorlaufzeit",
        "fieldtype": "Int"
    }, {
        "label": _("Versanddatum"),
        "fieldname": "versanddatum",
        "fieldtype": "Date"
    }]

    sales_order_to_deliver = frappe.db.sql(
        """SELECT `name` FROM `tabSales Order` WHERE `per_delivered` < 100 AND `docstatus` = 1""",
        as_dict=True)
    for so in sales_order_to_deliver:
        _data = []
        _data.append(so.name)

        so_detail = frappe.get_doc("Sales Order", so.name)
        _data.append(so_detail.customer)
        _data.append(so_detail.customer_name)
        _data.append(so_detail.delivery_date)

        customer = frappe.get_doc("Customer", so_detail.customer)
        _data.append(customer.vorlaufzeit_versand)

        vorlaufzeit_versand_negativ = customer.vorlaufzeit_versand * -1
        versanddatum = add_days(so_detail.delivery_date,
                                vorlaufzeit_versand_negativ)
        _data.append(versanddatum)

        data.append(_data)

    return columns, data
Exemple #26
0
def send_email_to_manager():
    """
    Send email to the manager
    :return:
    """
    use_daily_email = frappe.db.get_single_value('POS Bahrain Settings',
                                                 'use_daily_email')

    if not use_daily_email:
        return

    manager_email = frappe.db.get_single_value('POS Bahrain Settings',
                                               'manager_email')

    if not manager_email:
        frappe.throw(
            _('Manager email not set. Set it at POS Bahrain Settings.'))

    yesterday_date = add_days(frappe.utils.nowdate(), -1)

    filters = {
        'company': frappe.defaults.get_user_default("company"),
        'from_date': yesterday_date,
        'to_date': yesterday_date,
        'group_by': 'Invoice'
    }

    report = frappe.get_doc('Report', 'Gross Profit')
    columns, data = report.get_data(limit=100, filters=filters, as_dict=True)

    columns.insert(0, frappe._dict(fieldname='idx', label='', width='30px'))
    for i in range(len(data)):
        data[i]['idx'] = i + 1

    html = frappe.render_template(
        'frappe/templates/emails/auto_email_report.html', {
            'title': 'Gross Profit',
            'description': 'Daily Gross Profit',
            'columns': columns,
            'data': data,
            'report_name': 'Gross Profit'
        })

    frappe.sendmail(recipients=[manager_email],
                    subject='Gross Profit Daily',
                    message=_('See attachments below'),
                    attachments=[{
                        'fname':
                        'gross_profit_daily.pdf',
                        'fcontent':
                        get_pdf(html, {'orientation': 'Landscape'})
                    }])
 def validate_travel_dates(self):
     date = None
     line = 0
     for item in self.get("items"):
         line = line + 1
         if date is None:
             if item.halt == 1:
                 date = item.till_date
             else:
                 date = item.date
         else:
             if item.date != add_days(date, 1):
                 frappe.throw(
                     str(item.date) + " on line " + str(line) +
                     " might be wrongly typed. It should have been " +
                     str(add_days(date, 1)) +
                     ". Kindly check and submit again")
             else:
                 if item.halt == 1:
                     date = item.till_date
                 else:
                     date = item.date
Exemple #28
0
	def create_invoice(self, prorate):
		"""
		Creates a `Sales Invoice`, submits it and returns it
		"""
		invoice = frappe.new_doc('Sales Invoice')
		invoice.set_posting_time = 1
		invoice.posting_date = self.current_invoice_start
		invoice.customer = self.customer
		if self.company:
			invoice.company = self.company

		# Subscription is better suited for service items. I won't update `update_stock`
		# for that reason
		items_list = self.get_items_from_plans(self.plans, prorate)
		for item in items_list:
			invoice.append('items',	item)

		# Taxes
		if self.tax_template:
			invoice.taxes_and_charges = self.tax_template
			invoice.set_taxes()

		# Due date
		invoice.append(
			'payment_schedule',
			{
				'due_date': add_days(self.current_invoice_end, cint(self.days_until_due)),
				'invoice_portion': 100
			}
		)

		# Discounts
		if self.additional_discount_percentage:
			invoice.additional_discount_percentage = self.additional_discount_percentage

		if self.additional_discount_amount:
			invoice.discount_amount = self.additional_discount_amount

		if self.additional_discount_percentage or self.additional_discount_amount:
			discount_on = self.apply_additional_discount
			invoice.apply_additional_discount = discount_on if discount_on else 'Grand Total'

		# Subscription period
		invoice.from_date = self.current_invoice_start
		invoice.to_date = self.current_invoice_end

		invoice.flags.ignore_mandatory = True
		invoice.save()
		invoice.submit()

		return invoice
Exemple #29
0
    def is_current_invoice_generated(self,
                                     _current_start_date=None,
                                     _current_end_date=None):
        invoice = self.get_current_invoice()

        if not (_current_start_date and _current_end_date):
            _current_start_date, _current_end_date = self.update_subscription_period(
                date=add_days(self.current_invoice_end, 1), return_date=True)

        if invoice and getdate(_current_start_date) <= getdate(
                invoice.posting_date) <= getdate(_current_end_date):
            return True

        return False
Exemple #30
0
	def set_current_invoice_start(self, date=None):
		"""
		This sets the date of the beginning of the current billing period.
		If the `date` parameter is not given , it will be automatically set as today's
		date.
		"""
		if self.is_new_subscription() and self.trial_period_end and getdate(self.trial_period_end) > getdate(self.start_date):
			self.current_invoice_start = add_days(self.trial_period_end, 1)
		elif self.trial_period_start and self.is_trialling():
			self.current_invoice_start = self.trial_period_start
		elif date:
			self.current_invoice_start = date
		else:
			self.current_invoice_start = nowdate()
Exemple #31
0
def create_invoice(mitgliedschaft):
    mitgliedschaft = frappe.get_doc("Mitgliedschaft", mitgliedschaft)
    zahlungsziel = add_days(
        today(),
        frappe.get_doc("Einstellungen").rechnungslauf_zahlungsfrist)
    if mitgliedschaft.rechnung_an_dritte == 1:
        kunde = mitgliedschaft.rechnungsempfaenger
        customer = frappe.get_doc("Customer", mitgliedschaft.mitglied)
        beschreibung = frappe.utils.get_datetime(
            mitgliedschaft.start).strftime(
                '%d.%m.%Y') + " - " + frappe.utils.get_datetime(
                    mitgliedschaft.ende).strftime(
                        '%d.%m.%Y'
                    ) + "<br>Mitgliedschaftsinhaber: " + customer.customer_name
    else:
        kunde = mitgliedschaft.mitglied
        beschreibung = frappe.utils.get_datetime(
            mitgliedschaft.start).strftime(
                '%d.%m.%Y') + " - " + frappe.utils.get_datetime(
                    mitgliedschaft.ende).strftime('%d.%m.%Y')
    invoice = frappe.get_doc({
        "doctype":
        "Sales Invoice",
        "customer":
        kunde,
        "company":
        "Gönnerverein",
        "due_date":
        zahlungsziel,
        "items": [{
            "item_code": mitgliedschaft.mitgliedschafts_typ,
            "qty": 1,
            "description": beschreibung,
            "cost_center": "Main - GöV"
        }]
    })
    invoice.insert()

    referencenumber = "974554" + mitgliedschaft.mitglied.split("-")[
        2] + "0000" + invoice.name.split("-")[1] + invoice.name.split("-")[2]
    invoice.update({
        "esr_reference":
        esr.get_reference_number(referencenumber),
        "esr_code":
        esr.generateCodeline(invoice.grand_total, referencenumber, "012000272")
    })
    invoice.save(ignore_permissions=True)

    return invoice.name
    def before_save(self):
        vorlauf = frappe.get_doc("Einstellungen").rechnungslauf_vorlauf
        datum_inkl_vorlauf = add_days(self.datum, vorlauf)
        ablaufende_mitgliedschaften = frappe.db.sql(
            """SELECT `name`, `customer`, `mitgliedschafts_typ`, `ende` FROM `tabMitgliedschaft` WHERE `ende` <= '{datum_inkl_vorlauf}'
														AND `not_renew` = 0
														AND `name` NOT IN (SELECT `mitgliedschaft` FROM `tabAuslaufende Mitgliedschaften`) LIMIT 500"""
            .format(datum_inkl_vorlauf=datum_inkl_vorlauf),
            as_dict=True)
        for mitglied in ablaufende_mitgliedschaften:
            row = self.append('auslaufende_mitgliedschaften', {})
            row.mitgliedschaft = mitglied.name
            row.kunde = mitglied.customer
            row.type = mitglied.mitgliedschafts_typ
            row.ende = mitglied.ende
def post_casual_leaves():
	date = add_days(frappe.utils.nowdate(), 10)
	start = get_year_start_date(date);
	end = get_year_end_date(date);
	employees = frappe.db.sql("select name, employee_name from `tabEmployee` where status = 'Active' and employment_type in (\'Regular employees\', \'Contract\')", as_dict=True)
	for e in employees:
		la = frappe.new_doc("Leave Allocation")
		la.employee = e.name
		la.employee_name = e.employee_name
		la.leave_type = "Casual Leave"
		la.from_date = str(start)
		la.to_date = str(end)
		la.carry_forward = cint(0)
		la.new_leaves_allocated = flt(10)
		la.submit()
Exemple #34
0
def execute(filters=None):
	column = [
			_("Transaction Date") + ":Date:150",
			_("Document ID") + ":Link/Utility Sale:90",
			_("Customer") + ":Link/Customer:120",
			_("Utility Item") + ":Link/Utility Item:120",
			_("Wallet Provider") + ":Link/Supplier:120",
			_("Amount") + ":Currency/currency:90",
			_("Expense") + ":Currency/currency:90",
			_("Charges") + ":Currency/currency:90",
			_("Total") + ":Currency/currency:90",
			_("Outstanding") + ":Currency/currency:90",
			_("Unique No") + "::90",
			_("Voucher Code") + "::180",
			_("Phone") + "::90",
		]
	cond = ["ut.docstatus = 1"]
	if filters:
		if filters.get('from_date'):
			cond.append("ut.transaction_date >= '%s'" % filters.get('from_date'))
		if filters.get('to_date'):
			cond.append("ut.transaction_date < '%s'" % add_days(filters.get('to_date'), 1))
		if filters.get('utility_item'):
			cond.append("ut.utility_item = '%s'" % filters.get('utility_item'))
		if filters.get('wallet_provider'):
			cond.append("ut.wallet_provider = '%s'" % filters.get('wallet_provider'))
	data = frappe.db.sql("""
		SELECT
			ut.transaction_date,
			ut.name,
			ut.customer,
			ut.utility_item,
			ut.wallet_provider,
			ut.amount,
			ut.sale_expense_rate * ut.amount / 100 AS sale_expense_amount,
			ut.charges - (SELECT sale_expense_amount),
			ut.total,
			ut.total-ut.paid_amount,
			ut.unique_no,
			ut.voucher_no,
			at.phone
		FROM `tabUtility Sale` AS ut
		LEFT JOIN `tabDynamic Link` AS dt ON dt.link_name = ut.customer
		LEFT JOIN `tabAddress` AS at ON dt.parent = at.name
		WHERE {}
		ORDER BY ut.transaction_date
	""".format(" and ".join(cond)))
	return column, data
Exemple #35
0
def make_orientation_meeting(doc, method):
    """Create Orintate"""
    meeting = frappe.get_doc({
        "doctype":
        "Meeting",
        "title":
        "Orientation for {0}".format(doc.first_name),
        "date":
        add_days(nowdate(), 1),
        "from_time":
        "09:00",
        "to_time":
        "09:30",
    })
    print("hello")
    print(meeting)
Exemple #36
0
def previous_mark_att():
    nowday = add_days(nowdate(), -1)
    from_date = get_first_day(nowday)
    to_date = get_last_day(nowday)
    frappe.errprint(from_date)
    frappe.errprint(to_date)
    checkins = frappe.db.sql(
        """select * from `tabEmployee Checkin` where skip_auto_attendance = 0 and date(time) between '%s' and '%s' order by time """
        % (from_date, to_date),
        as_dict=1)
    if checkins:
        for c in checkins:
            att = mark_attendance_from_checkin(c.name, c.employee, c.time)
            if att:
                frappe.db.set_value("Employee Checkin", c.name,
                                    "skip_auto_attendance", "1")
	def validate_travel_dates(self):
		date = None
		line = 0
		for item in self.get("items"):
			line = line + 1
			if date is None:
				if item.halt == 1:
					date = item.till_date
				else:
					date = item.date
			else:
				if item.date != add_days(date, 1):
					frappe.throw(str(item.date) + " on line " + str(line) + " might be wrongly typed. It should have been " + str(add_days(date, 1)) + ". Kindly check and submit again")
				else:
					if item.halt == 1:
						date = item.till_date
					else:
						date = item.date
Exemple #38
0
	def process_for_past_due_date(self):
		"""
		Called by `process` if the status of the `Subscription` is 'Past Due Date'.

		The possible outcomes of this method are:
		1. Change the `Subscription` status to 'Active'
		2. Change the `Subscription` status to 'Cancelled'
		3. Change the `Subscription` status to 'Unpaid'
		"""
		current_invoice = self.get_current_invoice()
		if not current_invoice:
			frappe.throw(_('Current invoice {0} is missing'.format(current_invoice.invoice)))
		else:
			if self.is_not_outstanding(current_invoice):
				self.status = 'Active'
				self.update_subscription_period(add_days(self.current_invoice_end, 1))
			else:
				self.set_status_grace_period()