Exemple #1
0
def send_daily_linewise_report():
    custom_filter = {'date': add_days(today(), -1)}
    report = frappe.get_doc('Report', "Linewise Count")
    columns, data = report.get_data(limit=100,
                                    filters=custom_filter,
                                    as_dict=True)
    spreadsheet_data = get_spreadsheet_data(columns, data)
    xlsx_file = make_xlsx(spreadsheet_data, "Attendance")
    data = xlsx_file.getvalue()
    attachments = [{
        'fname': add_days(today(), -1) + '.xlsx',
        'fcontent': data
    }]
    frappe.sendmail(
        recipients=[
            '*****@*****.**', '*****@*****.**',
            '*****@*****.**', '*****@*****.**',
            '*****@*****.**', '*****@*****.**'
        ],
        subject='Employee Attendance Report - ' +
        formatdate(add_days(today(), -1)),
        message=
        'Kindly find the attached Excel Sheet of Linewise Count Report of' +
        formatdate(add_days(today(), -1)),
        attachments=attachments)
Exemple #2
0
def get_interest(loan=None, start_date=today(), end_date=today()):
    '''Get interest amount'''
    if not loan:
        return None
    owed_amount = 0

    principal = get_outstanding_principal(loan, end_date)
    rate, slab = frappe.get_value('Loan', loan,
                                  ['rate_of_interest', 'calculation_slab'])
    if slab:
        principal = math.ceil(principal / slab) * slab
        owed_amount = principal * rate / 100.0

    period = '{} - {}'.format(start_date, end_date)
    interest_receivable_account = frappe.get_value(
        'Loan', loan, 'interest_receivable_account')

    conds = [
        "account = '{}'".format(interest_receivable_account),
        "period = '{}'".format(period),
        "against_voucher_type = 'Loan'",
        "against_voucher = '{}'".format(loan),
    ]

    paid_amount = frappe.db.sql("""
			SELECT
				sum(credit) as paid
			FROM `tabGL Entry`
			WHERE {}
		""".format(" AND ".join(conds)))[0][0] or 0

    amount = owed_amount - paid_amount

    return amount if amount > 0 else 0
Exemple #3
0
def get_interest(loan=None,
                 start_date=today(),
                 end_date=today(),
                 actual=False):
    '''Get interest amount'''
    if not loan:
        return None

    principal = get_outstanding_principal(loan, end_date)
    rate, slab = frappe.get_value('Loan', loan,
                                  ['rate_of_interest', 'calculation_slab'])
    if slab:
        principal = math.ceil(principal / slab) * slab
    interest = principal * rate / 100.0
    if actual:
        return interest

    period = '{} - {}'.format(start_date, end_date)
    billed_amount = billed_interest(loan, period)
    paid_amount = paid_interest(loan, period)
    converted = converted_interest(loan, period)

    if interest > billed_amount:
        return interest - paid_amount - converted
    return billed_amount - paid_amount - converted
Exemple #4
0
def make_cond(validity_list):
    cond_list = []
    for param in validity_list:
        if 'from_date' in param:
            cond_list.append(" %s <= '%s' " % (param, today()))
        if 'to_date' in param:
            cond_list.append(" %s >= '%s' " % (param, today()))
        if 'start_time' in param:
            cond_list.append(" %s <= '%s' " % (param, nowtime()))
        if 'end_time' in param:
            cond_list.append(" %s >= '%s' " % (param, nowtime()))

    return ' and ' + ' and '.join(cond_list)
Exemple #5
0
def make_cond(validity_list):
	cond_list = []
	for param in validity_list:
		if 'from_date' in param:
			cond_list.append(" %s <= '%s' "%(param, today()))
		if 'to_date' in param:
			cond_list.append(" %s >= '%s' "%(param, today()))
		if 'start_time' in param:
			cond_list.append(" %s <= '%s' "%(param, nowtime()))
		if 'end_time' in param:
			cond_list.append(" %s >= '%s' "%(param, nowtime()))
			
	return ' and ' + ' and '.join(cond_list)
Exemple #6
0
def validate(doc,method):
	email_validation(doc)
	validate_link_fileds(doc)
# 	validate_issue(doc)
	# machine_reading=""
	for d in doc.get("current_reading"):
		# machine_reading=d.machine_reading
		d.total=( int(d.get('reading') or 0)  + int(d.get('reading_2') or 0))
		if d.idx>1:
			frappe.throw("More than one row not allowed")
	if doc.status=="Closed":
		for t in frappe.get_all('Task',filters={'issue':doc.name},fields=['name','status']):
			if t.status != 'Completed':
				frappe.throw("Please Complete <b>Issue '{0}'</b>".format(t.name))
		if len(frappe.get_all('Task',filters={'issue':doc.name},fields=['name','status']))==0:
			if doc.get('current_reading') and len(doc.get('current_reading'))==0:
				frappe.throw("Please add Asset readings before closing issue")
	last_reading=today()
	if doc.asset and len(doc.get("last_readings"))==0:
		# doc.set("last_readings", [])
		fltr={"project":doc.project,"asset":doc.asset,"reading_date":("<=",last_reading)}
		# if machine_reading:
		# 	fltr.update({"name":("!=",machine_reading)})
		for d in frappe.get_all("Machine Reading",filters=fltr,fields=["name","reading_date","asset","black_and_white_reading","colour_reading","total","machine_type"],limit=1,order_by="reading_date desc,name desc"):
			doc.append("last_readings", {
				"date" : d.get('reading_date'),
				"type" : d.get('machine_type'),
				"asset":d.get('asset'),
				"reading":d.get('black_and_white_reading'),
				"reading_2":d.get('colour_reading'),
				"total":( int(d.get('black_and_white_reading') or 0)  + int(d.get('colour_reading') or 0))
				})
Exemple #7
0
def calculate_wages():
    day = add_days(today(), -1)
    # day = '2018-03-04'
    for line in frappe.get_list("Line"):
        att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and line=%s and attendance_date= %s""",
            (line["name"], day),
            as_dict=1)
        for present in att:
            present_days = present.count

        att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Absent' and line=%s and attendance_date= %s""",
            (line["name"], day),
            as_dict=1)
        for absent in att:
            absent_days = absent.count

        wm = frappe.new_doc("Wage Monitor")
        wm.date = day
        wm.line = line["name"]
        wm.present = present_days
        wm.absent = absent_days
        wm.wage = '452'
        wm.calculated_wages = flt(wm.wage) * flt(wm.present)
        wm.save(ignore_permissions=True)
Exemple #8
0
def get_employees_who_have_anniversary_today():
    """Get Employee properties whose work Anniversary is today."""
    return frappe.db.sql("""select name, personal_email, company_email, user_id, employee_name,
        date_of_joining from tabEmployee where day(date_of_joining) = day(%(date)s)
        and month(date_of_joining) = month(%(date)s)
        and employment_type != 'Contract'
        and status = 'Active'""", {"date": today()}, as_dict=True)
Exemple #9
0
def get_available_qty(args, order="desc", limit=1, debug=False):
    """get stock ledger entries filtered by specific posting datetime conditions"""

    conditions = "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"

    if not args.get("posting_date"):
        args["posting_date"] = today()
    if not args.get("posting_time"):
        args["posting_time"] = nowtime()

    result = frappe.db.sql(
        """select qty_after_transaction available_qty from `tabStock Ledger Entry` sle
		inner join `tabItem` i on i.name = sle.item_code
		where warehouse = %%(warehouse)s
		and item_group = %%(item_group)s
		and %(conditions)s
		and ifnull(is_cancelled, 'No')='No'
		order by timestamp(posting_date, posting_time) %(order)s, sle.name %(order)s
		%(limit)s""" % {
            "conditions": conditions,
            "limit": limit and "limit {0}".format(limit) or "",
            "order": order
        },
        args,
        as_dict=1,
        debug=debug)

    f = result and result[0] or {}
    return f.get("available_qty", 0)
Exemple #10
0
def creat_new_anfrage(mitgliedschaft=None,
                      kontakt=None,
                      adresse=None,
                      kunde=None):
    #creat new anfrage
    anfrage = frappe.get_doc({"doctype": "Anfrage", "datum": today()})

    anfrage.insert(ignore_permissions=True)

    #If mitgliedschaft available, set link
    if mitgliedschaft:
        anfrage.update({'mitgliedschaft': mitgliedschaft})
        anfrage.save()

    #If adresse available, set link
    if adresse:
        anfrage.update({'patienten_adresse': adresse})
        anfrage.save()

    #If kontakt available, set link
    if kontakt:
        anfrage.update({'patienten_kontakt': kontakt})
        anfrage.save()

    #If kunde available, set link
    if kunde:
        anfrage.update({'patient': kunde})
        anfrage.save()

    return anfrage.name
def _get_tenant_dues(filters):
    """
    Get due invoices during the day
    :return:
    """
    clauses = _get_clauses(filters)
    return frappe.db.sql(
        """
            SELECT
                rci.name,
                rci.invoice_date,
                rci.description,
                rci.parent,
                rc.rental_amount,
                rc.advance_paid_amount,
                rc.tenant,
                rc.property
            FROM `tabRental Contract Item` rci
            INNER JOIN `tabRental Contract` rc
            ON rci.parent = rc.name
            WHERE rc.docstatus = 1 
            AND rci.is_invoice_created = 0
            {clauses}
        """.format(
            clauses="AND " + clauses if clauses else ""
        ),
        {**filters, "now": get_last_day(today())},
        as_dict=True,
    )
Exemple #12
0
def update_att_a():
    day = today()
    att_ids = frappe.get_list('Attendance',
                              filters={
                                  "shift": "A",
                                  "docstatus": 0,
                                  "attendance_date": day
                              })
    for att_id in att_ids:
        if att_id:
            att = frappe.get_doc("Attendance", att_id)
            if att and att.in_time:
                in_time_f = datetime.strptime(att.in_time, '%H:%M:%S')
                in_time = in_time_f.strftime("%H:%M:%S")
                if in_time >= '07:45:00' and in_time <= '09:45:00':
                    status = check_permission(att.employee,
                                              att.attendance_date, att.in_time)
                    if status:
                        att.update({
                            "status": "Present",
                            "permission_status": status
                        })
                        att.save(ignore_permissions=True)
                        att.submit()
                        frappe.db.commit()
Exemple #13
0
def get_available_qty(args, order="desc", limit=1, debug=False):
	"""get stock ledger entries filtered by specific posting datetime conditions"""

	conditions = "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"

	if not args.get("posting_date"):
		args["posting_date"] = today()
	if not args.get("posting_time"):
		args["posting_time"] = nowtime()

	result = frappe.db.sql("""select qty_after_transaction available_qty from `tabStock Ledger Entry` sle
		inner join `tabItem` i on i.name = sle.item_code
		where warehouse = %%(warehouse)s
		and item_group = %%(item_group)s
		and %(conditions)s
		and ifnull(is_cancelled, 'No')='No'
		order by timestamp(posting_date, posting_time) %(order)s, sle.name %(order)s
		%(limit)s""" % {
			"conditions": conditions,
			"limit": limit and "limit {0}".format(limit) or "",
			"order": order
		}, args, as_dict=1, debug=debug)

	f = result and result[0] or {}
	return f.get("available_qty", 0)
Exemple #14
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 #15
0
def update_leave_application():
    day = add_days(today(), -1)
    employees = frappe.get_all('Employee', filters={"status": "Active"})
    for employee in employees:
        lwp = get_leave(employee.name, day)
        if lwp:
            pass
        else:
            query = """SELECT emp.name FROM `tabAttendance` att, `tabEmployee` emp
                       WHERE att.employee = emp.name AND att.status = 'Absent' AND att.attendance_date = '%s'""" % (day)
            absent_emp = frappe.db.sql(query, as_dict=True)
            if employee in absent_emp:
                leave_approvers = [l.leave_approver for l in frappe.db.sql("""select leave_approver from `tabEmployee Leave Approver` where parent = %s""",
                                                                           (employee.name), as_dict=True)]
                lap = frappe.new_doc("Leave Application")
                lap.leave_type = "Leave Without Pay"
                lap.status = "Approved"
                lap.follow_via_email = 0
                lap.description = "Absent Auto Marked"
                lap.from_date = day
                lap.to_date = day
                lap.employee = employee.name
                if leave_approvers:
                    lap.leave_approver = leave_approvers[0]
                else:
                    lap.leave_approver = "Administrator"
                lap.posting_date = day
                lap.company = frappe.db.get_value(
                    "Employee", employee.name, "company")
                lap.save(ignore_permissions=True)
                lap.submit()
                frappe.db.commit()
Exemple #16
0
def emp_ot():
    day = add_days(today(), -1)
    for day in days:
        holiday = frappe.get_list("Holiday List",
                                  filters={'holiday_date': day})
        if holiday:
            attendance_list = frappe.get_list("Attendance",
                                              filters={
                                                  "attendance_date": day,
                                                  "status": "Present",
                                                  "employment_type": "Operator"
                                              })
            for attendance in attendance_list:
                att = frappe.get_doc("Attendance", attendance)
                from_time = str(att.attendance_date) + " " + att.in_time
                from_time_f = datetime.strptime(from_time, '%Y-%m-%d %H:%M:%S')
                to_time = str(att.attendance_date) + " " + att.out_time
                to_time_f = datetime.strptime(to_time, '%Y-%m-%d %H:%M:%S')
                ts = frappe.new_doc("Timesheet")
                ts.company = att.company
                ts.employee = att.employee
                ts.start_date = att.attendance_date
                ts.end_date = att.attendance_date
                ts.note = "Holiday OT"
                ts.append(
                    "time_logs", {
                        "activity_type": "OT",
                        "hours": att.total_working_hours,
                        "from_time": from_time_f,
                        "to_time": to_time_f
                    })
                ts.save(ignore_permissions=True)
                frappe.db.commit()
Exemple #17
0
def _create_invoice(abo):
    abo = frappe.get_doc("mp Abo", abo)

    new_sinv = frappe.get_doc({
        "doctype":
        "Sales Invoice",
        "set_posting_time":
        1,
        "posting_date":
        today(),
        "posting_time":
        "00:00:00",
        "customer":
        abo.invoice_recipient,
        "customer_address":
        abo.recipient_address,
        "contact_person":
        abo.recipient_contact,
        "items": [{
            "item_code":
            frappe.db.get_single_value('mp Abo Settings', 'jahres_abo'),
            "qty":
            abo.magazines_qty_total
        }]
    })
    new_sinv.insert()
    new_sinv.submit()
    frappe.db.commit()

    return new_sinv.name
 def postproc(source, target):
     interest_income_account, interest_receivable_account, loan_account = frappe.get_value(
         'Loan Settings', None, [
             'interest_income_account', 'interest_receivable_account',
             'loan_account'
         ])
     target.update({
         'loan_no':
         loan_no,
         'posting_date':
         today(),
         'loan_principal':
         source.amount,
         'loan_account':
         loan_account,
         'interest_income_account':
         interest_income_account,
         'interest_receivable_account':
         interest_receivable_account,
     })
     recovery_frequency, day, billing_day = frappe.get_value(
         'Loan Plan', loan_application.loan_plan,
         ['recovery_frequency', 'day', 'billing_day'])
     billing_date = getdate(
         target.posting_date).replace(day=billing_day)
     if date_diff(billing_date, target.posting_date) < 0:
         if recovery_frequency == 'Weekly':
             add_days(billing_date, 7)
         elif recovery_frequency == 'Monthly':
             add_months(billing_date, 1)
     target.update({'billing_date': billing_date})
Exemple #19
0
 def reverse_cm(self):
     je = frappe.new_doc("Journal Entry")
     if not self.company:
         je.company = frappe.db.get_single_value("Global Defaults",
                                                 "default_company")
         self.company = je.company
     else:
         je.company = self.company
     je.voucher_type = "Credit Note"
     je.posting_date = today()
     je.cheque_date = today()
     je.cheque_no = "Cancellation of " + self.name + " from " + self.invoice
     je.append(
         "accounts",
         {
             "account":
             frappe.db.get_value("Company", je.company,
                                 "default_receivable_account"),  # Default
             "party_type":
             "Customer",
             "party":
             self.customer,
             "credit_in_account_currency":
             0,
             "debit_in_account_currency":
             self.amount,
             "is_advance":
             "No"
         })
     je.append(
         "accounts",
         {
             "account":
             frappe.db.get_value("Company", je.company,
                                 "default_income_account"),  # Default
             "credit_in_account_currency":
             self.amount,
             "debit_in_account_currency":
             0,
             "is_advance":
             "No"
         })
     je.remark = "Credit Memo (" + self.name + ") "
     je.save()
     self.journal_entry = je.name
     je.submit()
     frappe.db.commit()
Exemple #20
0
def calculate_wages():
    day = add_days(today(), -1)
    # day = '2018-03-04'
    for line in frappe.get_list("Line",fields=['name','roll','roll_b','roll_c','roll_g']):
        a_att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and shift='A' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for a in a_att:
            shift_a = a.count

        b_att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and shift='B' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for b in b_att:
            shift_b = b.count

        g_att = frappe.db.sql("""select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and shift='G' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for g in g_att:
            shift_g = g.count

        c_att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and shift='C' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for c in c_att:
            shift_c = c.count

        att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Present' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for present in att:
            present_days = present.count

        att = frappe.db.sql(
            """select count(*) as count from `tabAttendance` where
                        docstatus=1 and status='Absent' and line=%s and attendance_date= %s""", (line["name"], day), as_dict=1)
        for absent in att:
            absent_days = absent.count

        wm = frappe.new_doc("Wage Monitor")
        wm.date = day
        wm.line = line["name"]
        wm.roll_a = line["roll"]
        wm.roll_b = line["roll_b"]
        wm.roll_g = line["roll_g"]
        wm.roll_c = line["roll_c"]
        wm.shift_a = shift_a
        wm.shift_b = shift_b
        wm.shift_c = shift_c
        wm.shift_g = shift_g
        wm.a_absent = line["roll"] - shift_a
        wm.b_absent = line["roll_b"] - shift_b
        wm.c_absent = line["roll_c"] - shift_c
        wm.g_absent = line["roll_g"] - shift_g
        wm.present = present_days
        wm.absent = wm.a_absent + wm.b_absent + wm.c_absent + wm.g_absent
        wm.wage = '464'
        wm.calculated_wages = flt(wm.wage) * flt(wm.present)
        wm.save(ignore_permissions=True)
Exemple #21
0
def get_employees_wedding_anniversary_today():
    """Get Employee properties whose birthday is today."""
    return frappe.db.sql(
        """select name, personal_email, company_email, user_id, employee_name
		from tabEmployee where day(date_of_marriage) = day(%(date)s)
		and month(date_of_marriage) = month(%(date)s)
		and status = 'Active'""", {"date": today()},
        as_dict=True)
Exemple #22
0
def make_maintenance_schedule():
    ms = frappe.new_doc("Maintenance Schedule")
    ms.company = "_Test Company"
    ms.customer = "_Test Customer"
    ms.transaction_date = today()

    ms.append(
        "items", {
            "item_code": "_Test Item",
            "start_date": today(),
            "periodicity": "Weekly",
            "no_of_visits": 4,
            "sales_person": "Sales Team",
        })
    ms.insert(ignore_permissions=True)

    return ms
Exemple #23
0
def send_daily_report():
    custom_filter = {'date': add_days(today(), -1)}
    report = frappe.get_doc('Report', "Employee Day Attendance Report")
    columns, data = report.get_data(limit=500 or 500,
                                    filters=custom_filter,
                                    as_dict=True)
    html = frappe.render_template('frappe/templates/includes/print_table.html',
                                  {
                                      'columns': columns,
                                      'data': data
                                  })
    frappe.sendmail(recipients=[
        '*****@*****.**', '*****@*****.**', '*****@*****.**'
    ],
                    subject='Employee Attendance Report - ' +
                    formatdate(add_days(today(), -1)),
                    message=html)
def set_desdoc_relevant(name, relevant):
	relevant = int(relevant)
	date = today() if relevant else '0001-01-01'
	doc = frappe.get_doc('DC_PLC_Product_Summary', name)
	doc.rel_check_desdoc = relevant
	doc.rel_date_desdoc = date
	doc.save()

	return {'date': date, 'check': relevant}
Exemple #25
0
def successful_login(login_manager):
    with open(frappe.get_site_path('quota.json')) as jsonfile:
        parsed = json.load(jsonfile)

    valid_till = parsed['valid_till']
    diff = date_diff(valid_till, today())
    if diff < 0:
        frappe.throw(_("You site is suspended. Please contact Sales"),
                     frappe.AuthenticationError)
Exemple #26
0
def set_inactive_status():
    abos = frappe.db.sql(
        """SELECT `name` FROM `tabmp Abo` WHERE `status` = 'Actively terminated' AND `end_date` < '{today}'"""
        .format(today=today()),
        as_dict=True)
    for _abo in abos:
        abo = frappe.get_doc("mp Abo", _abo.name)
        abo.status = "Inactive"
        abo.save()
Exemple #27
0
def removeduplicateatt():
    get_att = frappe.db.sql("""SELECT name FROM `tabAttendance` WHERE attendance_date = %s GROUP BY employee
                    HAVING COUNT(employee) >1""",(today()),as_dict=1)
    if get_att:                 
        for att in get_att:                 
            obj = frappe.get_doc("Attendance",att["name"])
            obj.db_set("docstatus", 2)
            frappe.delete_doc("Attendance", obj.name)
            frappe.db.commit()
        removeduplicateatt()    
Exemple #28
0
def Lead_age():
    query = """select * from `Lead` """
    lead = frappe.db.sql(query, as_dict=1)
    for l in lead:
        date = today()
        ldate = l.create_on
        print(date)
        print(ldate)
        age = date_diff(date - ldate)
        frappe.db.set_value("Lead", l.name, "lead_age", age)
Exemple #29
0
	def test_site_expiry(self):
		update_limits({'expiry': add_to_date(today(), days=-1)})
		frappe.local.conf = _dict(frappe.get_site_config())

		frappe.db.commit()

		res = requests.post(get_url(), params={'cmd': 'login', 'usr': '******', 'pwd': 'testpassword',
			'device': 'desktop'})

		# While site is expired status code returned is 417 Failed Expectation
		self.assertEqual(res.status_code, 417)

		clear_limit("expiry")
		frappe.local.conf = _dict(frappe.get_site_config())
Exemple #30
0
def create_point_transaction(ref_link, ref_name, inv, tran_type, points, rule_details=None):
	if points != 0:
		tran = frappe.new_doc("Point Transaction")
		tran.ref_link = ref_link
		tran.ref_name = ref_name	
		tran.date = today()
		tran.type = tran_type
		tran.points = cint(points) * 1 if tran_type == 'Earned' else -1 * cint(points)
		if rule_details: 
			tran.valied_upto = add_months(nowdate(), cint(rule_details.get('valid_upto'))) 
		tran.invoice_number = inv
		tran.rule_details = cstr(rule_details)
		tran.docstatus = 1
		tran.insert()
Exemple #31
0
    def test_site_expiry(self):
        update_limits({"expiry": add_to_date(today(), days=-1)})
        frappe.local.conf = _dict(frappe.get_site_config())

        frappe.db.commit()

        res = requests.post(
            get_url(), params={"cmd": "login", "usr": "******", "pwd": "testpassword", "device": "desktop"}
        )

        # While site is expired status code returned is 417 Failed Expectation
        self.assertEqual(res.status_code, 417)

        clear_limit("expiry")
        frappe.local.conf = _dict(frappe.get_site_config())
Exemple #32
0
	def test_site_expiry(self):
		user = frappe.get_doc('User', '*****@*****.**')
		user.enabled = 1
		user.new_password = '******'
		user.save()

		update_limits({'expiry': add_to_date(today(), days=-1), 'support_email': '*****@*****.**'})
		frappe.local.conf = _dict(frappe.get_site_config())

		frappe.db.commit()

		res = requests.post(get_url(), params={'cmd': 'login', 'usr':
			'******', 'pwd': 'Eastern_43A1W', 'device': 'desktop'})

		# While site is expired status code returned is 417 Failed Expectation
		self.assertEqual(res.status_code, 417)

		clear_limit("expiry")
		frappe.local.conf = _dict(frappe.get_site_config())
def create_jv(voucher_details, earned_redeemed_points, debit_to, credit_to, adj_outstanding=False):
	"""
		Here we create Journal Voucher for two purpose, 
		1. Earned Point Allocation
		2. Redeemed Point Withdrawal

		For Earned Point Allocation: debit_to = customer's account and credit_to = company's account
		For Redeemed Point Withdrawal: debit_to = company's account and debit_to = customer's account
	"""

	jv = frappe.new_doc("Journal Voucher")
	jv.naming_series = 'JV-'
	jv.voucher_type = 'Journal Entry'
	jv.posting_date = today()
	jv.user_remark = "Loyalty Points: %s "%voucher_details.name
	jv.save()

	jvd = frappe.new_doc("Journal Voucher Detail")
	jvd.account = debit_to
	jvd.debit = earned_redeemed_points
	jvd.cost_center = frappe.db.get_value('Company', voucher_details.company, 'cost_center')
	jvd.is_advance = 'No'
	jvd.parentfield = 'entries'
	jvd.parenttype = 'Journal Voucher'
	jvd.parent = jv.name
	jvd.save()

	jvd1 = frappe.new_doc("Journal Voucher Detail")
	jvd1.account = credit_to
	jvd1.credit = earned_redeemed_points
	jvd1.cost_center = frappe.db.get_value('Company', voucher_details.company, 'cost_center')
	jvd1.is_advance = 'No'
	jvd1.parentfield = 'entries'
	jvd1.parenttype = 'Journal Voucher'
	jvd1.against_invoice = voucher_details.name if adj_outstanding else ""
	jvd1.parent = jv.name
	jvd1.save()

	ujv = frappe.get_doc("Journal Voucher", jv.name)
	ujv.total_credit  = jv.total_debit = earned_redeemed_points
	ujv.submit()
Exemple #34
0
	def get_item_count(filters):
		filters.update({"is_stock_item": 1, "disabled": 0})
		conditions, values = frappe.db.build_conditions(filters)

		end_of_life = """(tabItem.end_of_life > %(today)s or ifnull(tabItem.end_of_life, '0000-00-00')='0000-00-00')""" % {"today": today()}
		return frappe.db.sql("""select count(*)
						from `tabItem`
						where %s and %s"""
							 % (end_of_life, conditions), values)[0][0]