def update_payment_entry(self, payment): lst = [] invoices = payment.invoices.strip().split(',') if (len(invoices) == 0): return amount = float(abs(payment.amount)) for invoice_entry in invoices: if (not invoice_entry.strip()): continue invs = invoice_entry.split('|') invoice_type, invoice = invs[0], invs[1] outstanding_amount = dataent.get_value(invoice_type, invoice, 'outstanding_amount') lst.append(dataent._dict({ 'voucher_type': payment.reference_type, 'voucher_no' : payment.reference_name, 'against_voucher_type' : invoice_type, 'against_voucher' : invoice, 'account' : payment.account, 'party_type': payment.party_type, 'party': dataent.get_value("Payment Entry", payment.reference_name, "party"), 'unadjusted_amount' : float(amount), 'allocated_amount' : min(outstanding_amount, amount) })) amount -= outstanding_amount if lst: from epaas.accounts.utils import reconcile_against_document try: reconcile_against_document(lst) except: dataent.throw(_("Exception occurred while reconciling {0}".format(payment.reference_name)))
def set_price_list(out, party, party_type, given_price_list, pos=None): # price list price_list = get_permitted_documents('Price List') if price_list: price_list = price_list[0] elif pos and party_type == 'Customer': customer_price_list = dataent.get_value('Customer', party.name, 'default_price_list') if customer_price_list: price_list = customer_price_list else: pos_price_list = dataent.get_value('POS Profile', pos, 'selling_price_list') price_list = pos_price_list or given_price_list else: price_list = get_default_price_list(party) or given_price_list if price_list: out.price_list_currency = dataent.db.get_value("Price List", price_list, "currency", cache=True) out["selling_price_list" if party.doctype == "Customer" else "buying_price_list"] = price_list
def test_salary_slip_with_holidays_excluded(self): no_of_days = self.get_no_of_days() dataent.db.set_value("HR Settings", None, "include_holidays_in_total_working_days", 0) make_employee("*****@*****.**") dataent.db.set_value( "Employee", dataent.get_value("Employee", {"employee_name": "*****@*****.**"}, "name"), "relieving_date", None) dataent.db.set_value( "Employee", dataent.get_value("Employee", {"employee_name": "*****@*****.**"}, "name"), "status", "Active") ss = make_employee_salary_slip("*****@*****.**", "Monthly") self.assertEqual(ss.total_working_days, no_of_days[0] - no_of_days[1]) self.assertEqual(ss.payment_days, no_of_days[0] - no_of_days[1]) self.assertEqual(ss.earnings[0].amount, 50000) self.assertEqual(ss.earnings[0].default_amount, 50000) self.assertEqual(ss.earnings[1].amount, 3000) self.assertEqual(ss.deductions[0].amount, 5000) self.assertEqual(ss.deductions[1].amount, 5000) self.assertEqual(ss.gross_pay, 78000) self.assertEqual(ss.net_pay, 67418.0)
def test_new_employee_creation(self): transfer = dataent.get_doc({ "doctype": "Employee Transfer", "employee": dataent.get_value("Employee", {"user_id": "*****@*****.**"}, "name"), "create_new_employee_id": 1, "transfer_date": getdate(), "transfer_details": [{ "property": "Designation", "current": "Software Developer", "new": "Project Manager", "fieldname": "designation" }] }).insert() transfer.submit() self.assertTrue(transfer.new_employee_id) self.assertEqual( dataent.get_value("Employee", transfer.new_employee_id, "status"), "Active") self.assertEqual( dataent.get_value("Employee", transfer.employee, "status"), "Left")
def test_duplicate_entry_for_payroll_period(self): declaration = dataent.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": dataent.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": epaas.get_default_company(), "payroll_period": "_Test Payroll Period", "declarations": [ dict(exemption_sub_category = "_Test Sub Category", exemption_category = "_Test Category", amount = 100000), dict(exemption_sub_category = "_Test1 Sub Category", exemption_category = "_Test Category", amount = 50000), ] }).insert() duplicate_declaration = dataent.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": dataent.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": epaas.get_default_company(), "payroll_period": "_Test Payroll Period", "declarations": [ dict(exemption_sub_category = "_Test Sub Category", exemption_category = "_Test Category", amount = 100000) ] }) self.assertRaises(DuplicateDeclarationError, duplicate_declaration.insert) duplicate_declaration.employee = dataent.get_value("Employee", {"user_id":"*****@*****.**"}, "name") self.assertTrue(duplicate_declaration.insert)
def set_tax_withholding_category(company): accounts = [] abbr = dataent.get_value("Company", company, "abbr") tds_account = dataent.get_value("Account", 'TDS Payable - {0}'.format(abbr), 'name') if company and tds_account: accounts = [dict(company=company, account=tds_account)] fiscal_year = get_fiscal_year(today(), company=company)[0] docs = get_tds_details(accounts, fiscal_year) for d in docs: try: doc = dataent.get_doc(d) doc.flags.ignore_permissions = True doc.flags.ignore_mandatory = True doc.insert() except dataent.DuplicateEntryError: doc = dataent.get_doc("Tax Withholding Category", d.get("name")) doc.append("accounts", accounts[0]) # if fiscal year don't match with any of the already entered data, append rate row fy_exist = [k for k in doc.get('rates') if k.get('fiscal_year')==fiscal_year] if not fy_exist: doc.append("rates", d.get('rates')[0]) doc.save()
def make_consulation(): for i in range(3): practitioner = get_random("Healthcare Practitioner") department = dataent.get_value("Healthcare Practitioner", practitioner, "department") patient = get_random("Patient") patient_sex = dataent.get_value("Patient", patient, "sex") encounter = set_encounter(patient, patient_sex, practitioner, department, getdate(), i) encounter.save(ignore_permissions=True)
def test_set_value(self): todo = dataent.get_doc(dict(doctype='ToDo', description='test')).insert() dataent.set_value('ToDo', todo.name, 'description', 'test 1') self.assertEqual(dataent.get_value('ToDo', todo.name, 'description'), 'test 1') dataent.set_value('ToDo', todo.name, {'description': 'test 2'}) self.assertEqual(dataent.get_value('ToDo', todo.name, 'description'), 'test 2')
def set_missing_values(source, target): target.supplier = supplier target.apply_discount_on = "" target.additional_discount_percentage = 0.0 target.discount_amount = 0.0 default_price_list = dataent.get_value("Supplier", supplier, "default_price_list") if default_price_list: target.buying_price_list = default_price_list if any(item.delivered_by_supplier == 1 for item in source.items): if source.shipping_address_name: target.shipping_address = source.shipping_address_name target.shipping_address_display = source.shipping_address else: target.shipping_address = source.customer_address target.shipping_address_display = source.address_display target.customer_contact_person = source.contact_person target.customer_contact_display = source.contact_display target.customer_contact_mobile = source.contact_mobile target.customer_contact_email = source.contact_email else: target.customer = "" target.customer_name = "" target.run_method("set_missing_values") target.run_method("calculate_taxes_and_totals")
def invoice_appointment(appointment_doc): if not appointment_doc.name: return False sales_invoice = dataent.new_doc("Sales Invoice") sales_invoice.customer = dataent.get_value("Patient", appointment_doc.patient, "customer") sales_invoice.appointment = appointment_doc.name sales_invoice.due_date = getdate() sales_invoice.is_pos = True sales_invoice.company = appointment_doc.company sales_invoice.debit_to = get_receivable_account(appointment_doc.company) item_line = sales_invoice.append("items") service_item, practitioner_charge = service_item_and_practitioner_charge(appointment_doc) item_line.item_code = service_item item_line.description = "Consulting Charges: " + appointment_doc.practitioner item_line.income_account = get_income_account(appointment_doc.practitioner, appointment_doc.company) item_line.rate = practitioner_charge item_line.amount = practitioner_charge item_line.qty = 1 item_line.reference_dt = "Patient Appointment" item_line.reference_dn = appointment_doc.name payments_line = sales_invoice.append("payments") payments_line.mode_of_payment = appointment_doc.mode_of_payment payments_line.amount = appointment_doc.paid_amount sales_invoice.set_missing_values(for_validate = True) sales_invoice.save(ignore_permissions=True) sales_invoice.submit() dataent.msgprint(_("Sales Invoice {0} created as paid".format(sales_invoice.name)), alert=True)
def update_order(board_name, order): '''Save the order of cards in columns''' board = dataent.get_doc('Kanban Board', board_name) doctype = board.reference_doctype fieldname = board.field_name order_dict = json.loads(order) updated_cards = [] for col_name, cards in iteritems(order_dict): order_list = [] for card in cards: column = dataent.get_value( doctype, {'name': card}, fieldname ) if column != col_name: dataent.set_value(doctype, card, fieldname, col_name) updated_cards.append(dict( name=card, column=col_name )) for column in board.columns: if column.column_name == col_name: column.order = json.dumps(cards) board.save() return board, updated_cards
def execute(): dataent.reload_doctype("Purchase Order") dataent.reload_doctype("Purchase Order Item") if not dataent.db.has_column("Purchase Order", "delivered_by_supplier"): return for po in dataent.get_all("Purchase Order", filters={"delivered_by_supplier": 1}, fields=["name"]): purchase_order = dataent.get_doc("Purchase Order", po) for item in purchase_order.items: if item.prevdoc_doctype == "Sales Order": delivered_by_supplier = dataent.get_value( "Sales Order Item", item.prevdoc_detail_docname, "delivered_by_supplier") if delivered_by_supplier: dataent.db.sql( """update `tabPurchase Order Item` set delivered_by_supplier=1, billed_amt=amount, received_qty=qty where name=%s """, item.name) update_per_received(purchase_order) update_per_billed(purchase_order)
def get_name_translation(self): '''Get translation object if exists of current doctype name in the default language''' return dataent.get_value('Translation', { 'source_name': self.doc_type, 'language': dataent.local.lang or 'en' }, ['name', 'target_name'], as_dict=True)
def get_payment_account(): return dataent.get_value( 'Account', { 'account_type': 'Cash', 'company': epaas.get_default_company(), 'is_group': 0 }, "name")
def on_submit(self): if not self.leave_allocation: self.leave_allocation = self.get_leave_allocation() additional_salary = dataent.new_doc("Additional Salary") additional_salary.company = dataent.get_value("Employee", self.employee, "company") additional_salary.employee = self.employee additional_salary.salary_component = dataent.get_value("Leave Type", self.leave_type, "earning_component") additional_salary.payroll_date = self.encashment_date additional_salary.amount = self.encashment_amount additional_salary.submit() self.db_set("additional_salary", additional_salary.name) # Set encashed leaves in Allocation dataent.db.set_value("Leave Allocation", self.leave_allocation, "total_leaves_encashed", dataent.db.get_value('Leave Allocation', self.leave_allocation, 'total_leaves_encashed') + self.encashable_days)
def get_invoice(table): '''returns the active invoice linked to the given table''' invoice_name = dataent.get_value('Sales Invoice', dict(restaurant_table=table, docstatus=0)) restaurant, menu_name = get_restaurant_and_menu_name(table) if invoice_name: invoice = dataent.get_doc('Sales Invoice', invoice_name) else: invoice = dataent.new_doc('Sales Invoice') invoice.naming_series = dataent.db.get_value('Restaurant', restaurant, 'invoice_series_prefix') invoice.is_pos = 1 default_customer = dataent.db.get_value('Restaurant', restaurant, 'default_customer') if not default_customer: dataent.throw( _('Please set default customer in Restaurant Settings')) invoice.customer = default_customer invoice.taxes_and_charges = dataent.db.get_value('Restaurant', restaurant, 'default_tax_template') invoice.selling_price_list = dataent.db.get_value( 'Price List', dict(restaurant_menu=menu_name, enabled=1)) return invoice
def set_route(self): '''Set route from category and title if missing''' if not self.route: self.route = '/'.join([ dataent.get_value('Help Category', self.category, 'route'), self.scrub(self.title) ])
def get_conditions(filters, date_field): conditions = [""] values = [] for field in ["company", "customer", "territory"]: if filters.get(field): conditions.append("dt.{0}=%s".format(field)) values.append(filters[field]) if filters.get("sales_person"): lft, rgt = dataent.get_value("Sales Person", filters.get("sales_person"), ["lft", "rgt"]) conditions.append( "exists(select name from `tabSales Person` where lft >= {0} and rgt <= {1} and name=st.sales_person)" .format(lft, rgt)) if filters.get("from_date"): conditions.append("dt.{0}>=%s".format(date_field)) values.append(filters["from_date"]) if filters.get("to_date"): conditions.append("dt.{0}<=%s".format(date_field)) values.append(filters["to_date"]) items = get_items(filters) if items: conditions.append("dt_item.item_code in (%s)" % ', '.join(['%s'] * len(items))) values += items return " and ".join(conditions), values
def validate(self): self.title = " ".join(filter(None, [self.first_name, self.middle_name, self.last_name])) if self.student_applicant: self.check_unique() self.update_applicant_status() if dataent.get_value("Student", self.name, "title") != self.title: self.update_student_name_in_linked_doctype()
def return_link_expired_page(doc, doc_workflow_state): dataent.respond_as_web_page( _("Link Expired"), _("Document {0} has been set to state {1} by {2}".format( dataent.bold(doc.get('name')), dataent.bold(doc_workflow_state), dataent.bold( dataent.get_value('User', doc.get("modified_by"), 'full_name')))), indicator_color='blue')
def check_customer_or_supplier(): if dataent.session.user: contact_name = dataent.get_value("Contact", {"email_id": dataent.session.user}) if contact_name: contact = dataent.get_doc('Contact', contact_name) for link in contact.links: if link.link_doctype in ('Customer', 'Supplier'): return link.link_doctype, link.link_name return 'Customer', None
def get_child_assessment_groups(assessment_group): assessment_groups = [] group_type = dataent.get_value("Assessment Group", assessment_group, "is_group") if group_type: from dataent.desk.treeview import get_children assessment_groups = [d.get("value") for d in get_children("Assessment Group", assessment_group) if d.get("value") and not d.get("expandable")] else: assessment_groups = [assessment_group] return assessment_groups
def validate_docevent(self): if self.webhook_doctype: is_submittable = dataent.get_value("DocType", self.webhook_doctype, "is_submittable") if not is_submittable and self.webhook_docevent in [ "on_submit", "on_cancel", "on_update_after_submit" ]: dataent.throw( _("DocType must be Submittable for the selected Doc Event") )
def get_context(context): redirect_to = dataent.local.request.args.get("redirect-to") if dataent.session.user != "Guest": if not redirect_to: redirect_to = "/" if dataent.session.data.user_type=="Website User" else "/desk" dataent.local.flags.redirect_location = redirect_to raise dataent.Redirect # get settings from site config context.no_header = True context.for_test = 'login.html' context["title"] = "Login" context["provider_logins"] = [] context["disable_signup"] = dataent.utils.cint(dataent.db.get_value("Website Settings", "Website Settings", "disable_signup")) providers = [i.name for i in dataent.get_all("Social Login Key", filters={"enable_social_login":1})] for provider in providers: client_id, base_url = dataent.get_value("Social Login Key", provider, ["client_id", "base_url"]) client_secret = get_decrypted_password("Social Login Key", provider, "client_secret") icon = get_icon_html(dataent.get_value("Social Login Key", provider, "icon"), small=True) if (get_oauth_keys(provider) and client_secret and client_id and base_url): context.provider_logins.append({ "name": provider, "provider_name": dataent.get_value("Social Login Key", provider, "provider_name"), "auth_url": get_oauth2_authorize_url(provider, redirect_to), "icon": icon }) context["social_login"] = True ldap_settings = LDAPSettings.get_ldap_client_settings() context["ldap_settings"] = ldap_settings login_name_placeholder = [_("Email address")] if dataent.utils.cint(dataent.get_system_settings("allow_login_using_mobile_number")): login_name_placeholder.append(_("Mobile number")) if dataent.utils.cint(dataent.get_system_settings("allow_login_using_user_name")): login_name_placeholder.append(_("Username")) context['login_name_placeholder'] = ' {0} '.format(_('or')).join(login_name_placeholder) return context
def link_customer_and_address(raw_billing_data,customer_status): if customer_status == 0: # create customer = dataent.new_doc("Customer") address = dataent.new_doc("Address") if customer_status == 1: # Edit customer_woo_com_email = raw_billing_data.get("email") customer = dataent.get_doc("Customer",{"woocommerce_email": customer_woo_com_email}) old_name = customer.customer_name full_name = str(raw_billing_data.get("first_name"))+ " "+str(raw_billing_data.get("last_name")) customer.customer_name = full_name customer.woocommerce_email = str(raw_billing_data.get("email")) customer.save() dataent.db.commit() if customer_status == 1: dataent.rename_doc("Customer", old_name, full_name) address = dataent.get_doc("Address",{"woocommerce_email":customer_woo_com_email}) customer = dataent.get_doc("Customer",{"woocommerce_email": customer_woo_com_email}) address.address_line1 = raw_billing_data.get("address_1", "Not Provided") address.address_line2 = raw_billing_data.get("address_2", "Not Provided") address.city = raw_billing_data.get("city", "Not Provided") address.woocommerce_email = str(raw_billing_data.get("email")) address.address_type = "Shipping" address.country = dataent.get_value("Country", filters={"code":raw_billing_data.get("country", "IN").lower()}) address.state = raw_billing_data.get("state") address.pincode = str(raw_billing_data.get("postcode")) address.phone = str(raw_billing_data.get("phone")) address.email_id = str(raw_billing_data.get("email")) address.append("links", { "link_doctype": "Customer", "link_name": customer.customer_name }) address.save() dataent.db.commit() if customer_status == 1: address = dataent.get_doc("Address",{"woocommerce_email":customer_woo_com_email}) old_address_title = address.name new_address_title = customer.customer_name+"-billing" address.address_title = customer.customer_name address.save() dataent.rename_doc("Address",old_address_title,new_address_title) dataent.db.commit()
def remove(doctype, role, permlevel): dataent.only_for("System Manager") setup_custom_perms(doctype) name = dataent.get_value('Custom DocPerm', dict(parent=doctype, role=role, permlevel=permlevel)) dataent.db.sql('delete from `tabCustom DocPerm` where name=%s', name) if not dataent.get_all('Custom DocPerm', dict(parent=doctype)): dataent.throw(_('There must be atleast one permission rule.'), title=_('Cannot Remove')) validate_permissions_for_doctype(doctype, for_remove=True)
def make_appointment(): i = 1 while i <= 4: practitioner = get_random("Healthcare Practitioner") department = dataent.get_value("Healthcare Practitioner", practitioner, "department") patient = get_random("Patient") patient_sex = dataent.get_value("Patient", patient, "sex") appointment = dataent.new_doc("Patient Appointment") startDate = datetime.datetime.now() for x in random_date(startDate, 0): appointment_datetime = x appointment.appointment_datetime = appointment_datetime appointment.appointment_time = appointment_datetime appointment.appointment_date = appointment_datetime appointment.patient = patient appointment.patient_sex = patient_sex appointment.practitioner = practitioner appointment.department = department appointment.save(ignore_permissions=True) i += 1
def set_default_role(doc, method): '''Set customer, supplier, student, guardian based on email''' if dataent.flags.setting_role or dataent.flags.in_migrate: return roles = dataent.get_roles(doc.name) contact_name = dataent.get_value('Contact', dict(email_id=doc.email)) if contact_name: contact = dataent.get_doc('Contact', contact_name) for link in contact.links: dataent.flags.setting_role = True if link.link_doctype == 'Customer' and 'Customer' not in roles: doc.add_roles('Customer') elif link.link_doctype == 'Supplier' and 'Supplier' not in roles: doc.add_roles('Supplier') elif dataent.get_value('Student', dict( student_email_id=doc.email)) and 'Student' not in roles: doc.add_roles('Student') elif dataent.get_value('Guardian', dict( email_address=doc.email)) and 'Guardian' not in roles: doc.add_roles('Guardian')
def calculate_std_hours(self): std_working_hours = dataent.get_value("Company", self.company, 'standard_working_hours') for time in self.time_logs: if time.from_time and time.to_time: if flt(std_working_hours) > 0: time.hours = flt(std_working_hours) * date_diff( time.to_time, time.from_time) else: if not time.hours: time.hours = time_diff_in_hours( time.to_time, time.from_time)
def set_tds_account(docs, company): abbr = dataent.get_value("Company", company, "abbr") parent_account = dataent.db.get_value("Account", filters = {"account_name": "Duties and Taxes", "company": company}) if parent_account: docs.extend([ { "doctype": "Account", "account_name": "TDS Payable", "account_type": "Tax", "parent_account": parent_account, "company": company } ])