def test_duplicate_entry_for_payroll_period(self): declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": erpnext.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 = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": erpnext.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 = frappe.get_value("Employee", {"user_id":"*****@*****.**"}, "name") self.assertTrue(duplicate_declaration.insert)
def work(): frappe.set_user(frappe.db.get_global('demo_manufacturing_user')) from erpnext.projects.doctype.timesheet.timesheet import OverlapError ppt = frappe.get_doc("Production Planning Tool", "Production Planning Tool") ppt.company = erpnext.get_default_company() ppt.use_multi_level_bom = 1 ppt.get_items_from = "Sales Order" ppt.purchase_request_for_warehouse = "Stores - WPL" ppt.run_method("get_open_sales_orders") ppt.run_method("get_items") ppt.run_method("raise_production_orders") ppt.run_method("raise_material_requests") frappe.db.commit() # submit production orders for pro in frappe.db.get_values("Production Order", {"docstatus": 0}, "name"): b = frappe.get_doc("Production Order", pro[0]) b.wip_warehouse = "Work in Progress - WPL" b.submit() frappe.db.commit() # submit material requests for pro in frappe.db.get_values("Material Request", {"docstatus": 0}, "name"): b = frappe.get_doc("Material Request", pro[0]) b.submit() frappe.db.commit() # stores -> wip if random.random() < 0.3: for pro in query_report.run("Open Production Orders")["result"][:how_many("Stock Entry for WIP")]: make_stock_entry_from_pro(pro[0], "Material Transfer for Manufacture") # wip -> fg if random.random() < 0.3: for pro in query_report.run("Production Orders in Progress")["result"][:how_many("Stock Entry for FG")]: make_stock_entry_from_pro(pro[0], "Manufacture") for bom in frappe.get_all('BOM', fields=['item'], filters = {'with_operations': 1}): pro_order = make_prod_order_test_record(item=bom.item, qty=2, source_warehouse="Stores - WPL", wip_warehouse = "Work in Progress - WPL", fg_warehouse = "Stores - WPL", company = erpnext.get_default_company(), stock_uom = frappe.db.get_value('Item', bom.item, 'stock_uom'), planned_start_date = frappe.flags.current_date) # submit time logs for timesheet in frappe.get_all("Timesheet", ["name"], {"docstatus": 0, "production_order": ("!=", ""), "to_time": ("<", frappe.flags.current_date)}): timesheet = frappe.get_doc("Timesheet", timesheet.name) try: timesheet.submit() frappe.db.commit() except OverlapError: pass except WorkstationHolidayError: pass
def work(): if random.random() < 0.3: return frappe.set_user(frappe.db.get_global('demo_manufacturing_user')) if not frappe.get_all('Sales Order'): return from erpnext.projects.doctype.timesheet.timesheet import OverlapError ppt = frappe.new_doc("Production Plan") ppt.company = erpnext.get_default_company() # ppt.use_multi_level_bom = 1 #refactored ppt.get_items_from = "Sales Order" # ppt.purchase_request_for_warehouse = "Stores - WPL" # refactored ppt.run_method("get_open_sales_orders") if not ppt.get("sales_orders"): return ppt.run_method("get_items") ppt.run_method("raise_material_requests") ppt.save() ppt.submit() ppt.run_method("raise_work_orders") frappe.db.commit() # submit work orders for pro in frappe.db.get_values("Work Order", {"docstatus": 0}, "name"): b = frappe.get_doc("Work Order", pro[0]) b.wip_warehouse = "Work in Progress - WPL" b.submit() frappe.db.commit() # submit material requests for pro in frappe.db.get_values("Material Request", {"docstatus": 0}, "name"): b = frappe.get_doc("Material Request", pro[0]) b.submit() frappe.db.commit() # stores -> wip if random.random() < 0.4: for pro in query_report.run("Open Work Orders")["result"][:how_many("Stock Entry for WIP")]: make_stock_entry_from_pro(pro[0], "Material Transfer for Manufacture") # wip -> fg if random.random() < 0.4: for pro in query_report.run("Work Orders in Progress")["result"][:how_many("Stock Entry for FG")]: make_stock_entry_from_pro(pro[0], "Manufacture") for bom in frappe.get_all('BOM', fields=['item'], filters = {'with_operations': 1}): pro_order = make_wo_order_test_record(item=bom.item, qty=2, source_warehouse="Stores - WPL", wip_warehouse = "Work in Progress - WPL", fg_warehouse = "Stores - WPL", company = erpnext.get_default_company(), stock_uom = frappe.db.get_value('Item', bom.item, 'stock_uom'), planned_start_date = frappe.flags.current_date) # submit job card if random.random() < 0.4: submit_job_cards()
def setup_mode_of_payment(): company_abbr = frappe.db.get_value("Company", erpnext.get_default_company(), "abbr") account_dict = {'Cash': 'Cash - '+ company_abbr , 'Bank': 'National Bank - '+ company_abbr} for payment_mode in frappe.get_all('Mode of Payment', fields = ["name", "type"]): if payment_mode.type: mop = frappe.get_doc('Mode of Payment', payment_mode.name) mop.append('accounts', { 'company': erpnext.get_default_company(), 'default_account': account_dict.get(payment_mode.type) }) mop.save(ignore_permissions=True)
def setup_account_to_expense_type(): company_abbr = frappe.db.get_value("Company", erpnext.get_default_company(), "abbr") expense_types = [{'name': _('Calls'), "account": "Sales Expenses - "+ company_abbr}, {'name': _('Food'), "account": "Entertainment Expenses - "+ company_abbr}, {'name': _('Medical'), "account": "Utility Expenses - "+ company_abbr}, {'name': _('Others'), "account": "Miscellaneous Expenses - "+ company_abbr}, {'name': _('Travel'), "account": "Travel Expenses - "+ company_abbr}] for expense_type in expense_types: doc = frappe.get_doc("Expense Claim Type", expense_type["name"]) doc.append("accounts", { "company" : erpnext.get_default_company(), "default_account" : expense_type["account"] }) doc.save(ignore_permissions=True)
def make_salary_structure(salary_structure, payroll_frequency, employee=None, dont_submit=False, other_details=None, test_tax=False): if test_tax: frappe.db.sql("""delete from `tabSalary Structure` where name=%s""",(salary_structure)) if not frappe.db.exists('Salary Structure', salary_structure): details = { "doctype": "Salary Structure", "name": salary_structure, "company": erpnext.get_default_company(), "earnings": make_earning_salary_component(test_tax=test_tax), "deductions": make_deduction_salary_component(test_tax=test_tax), "payroll_frequency": payroll_frequency, "payment_account": get_random("Account") } if other_details and isinstance(other_details, dict): details.update(other_details) salary_structure_doc = frappe.get_doc(details).insert() if not dont_submit: salary_structure_doc.submit() else: salary_structure_doc = frappe.get_doc("Salary Structure", salary_structure) if employee and not frappe.db.get_value("Salary Structure Assignment", {'employee':employee, 'docstatus': 1}) and salary_structure_doc.docstatus==1: create_salary_structure_assignment(employee, salary_structure) return salary_structure_doc
def sync_warehouse(biotrack_data): name = frappe.get_value( 'Warehouse', { 'external_id': biotrack_data.get('roomid') } ) if name: warehouse = frappe.get_doc('Warehouse', name) if not (frappe.flags.force_sync or False) and warehouse.external_transaction_id == biotrack_data.get( "transactionid"): return False else: warehouse = frappe.new_doc('Warehouse') account = frappe.get_value("BioTrack Settings", None, "inventory_room_parent_account") warehouse.update({ 'company': get_default_company(), "create_account_under": account, 'external_id': biotrack_data.get('roomid'), }) warehouse.update({ "warehouse_name": biotrack_data.get("name"), "external_transaction_id": biotrack_data.get("transactionid"), "quarantine": biotrack_data.get("quarantine") or 0, "disabled": biotrack_data.get("deleted"), }) warehouse.save(ignore_permissions=True) frappe.db.commit() return True
def complete_setup(domain='Manufacturing'): print "Complete Setup..." from frappe.desk.page.setup_wizard.setup_wizard import setup_complete if not frappe.get_all('Company', limit=1): setup_complete({ "full_name": "Test User", "email": "*****@*****.**", "company_tagline": 'Awesome Products and Services', "password": "******", "fy_start_date": "2015-01-01", "fy_end_date": "2015-12-31", "bank_account": "National Bank", "domain": domain, "company_name": data.get(domain).get('company_name'), "chart_of_accounts": "Standard", "company_abbr": ''.join([d[0] for d in data.get(domain).get('company_name').split()]).upper(), "currency": 'USD', "timezone": 'America/New_York', "country": 'United States', "language": "english" }) company = erpnext.get_default_company() if company: company_doc = frappe.get_doc("Company", company) company_doc.db_set('default_payroll_payable_account', frappe.db.get_value('Account', dict(account_name='Payroll Payable')))
def get_appropriate_company(filters): if filters.get('company'): company = filters['company'] else: company = get_default_company() return company
def setUp(self): self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Structure Test Holiday List") make_earning_salary_component(["Basic Salary", "Special Allowance", "HRA"]) make_deduction_salary_component(["Professional Tax", "TDS"]) make_employee("*****@*****.**") make_employee("*****@*****.**")
def create_delivery_trip(contact=None): if not contact: contact = get_contact_and_address("_Test Customer") delivery_trip = frappe.new_doc("Delivery Trip") delivery_trip.update({ "doctype": "Delivery Trip", "company": erpnext.get_default_company(), "departure_time": add_days(now_datetime(), 5), "driver": frappe.db.get_value('Driver', {"full_name": "Newton Scmander"}), "vehicle": "JB 007", "delivery_stops": [{ "customer": "_Test Customer", "address": contact.shipping_address.parent, "contact": contact.contact_person.parent }, { "customer": "_Test Customer", "address": contact.shipping_address.parent, "contact": contact.contact_person.parent }] }) delivery_trip.insert() return delivery_trip
def sync_plant_room(biotrack_data): name = frappe.db.sql("SELECT name FROM `tabPlant Room` WHERE plant_room_name=%(plant_room_name)s OR bio_id=%(bio_id)s", { "plant_room_name": biotrack_data.get("name"), "bio_id": biotrack_data.get("roomid") } , as_dict=True) if name: doc = frappe.get_doc("Plant Room", name[0]) if doc.get("bio_transactionid") == biotrack_data.get("transactionid"): return False else: doc = frappe.get_doc({"doctype": "Plant Room", "company": get_default_company()}) doc.update({ "plant_room_name": biotrack_data.get("name"), "bio_name": biotrack_data.get("name"), "bio_id": biotrack_data.get("roomid"), "bio_transactionid": biotrack_data.get("transactionid"), "disabled": biotrack_data.get("deleted"), }) doc.save(ignore_permissions=True) frappe.db.commit() return True
def make_employee(self, user): if not frappe.db.get_value("User", user): frappe.get_doc({ "doctype": "User", "email": user, "first_name": user, "new_password": "******", "roles": [{"doctype": "Has Role", "role": "Employee"}] }).insert() if not frappe.db.get_value("Employee", {"user_id": user}): employee = frappe.get_doc({ "doctype": "Employee", "naming_series": "EMP-", "employee_name": user, "company": erpnext.get_default_company(), "user_id": user, "date_of_birth": "1990-05-08", "date_of_joining": "2013-01-01", "department": frappe.get_all("Department", fields="name")[0].name, "gender": "Female", "company_email": user, "prefered_contact_email": "Company Email", "prefered_email": user, "status": "Active", "employment_type": "Intern" }).insert() return employee.name else: return frappe.get_value("Employee", {"employee_name":user}, "name")
def _reorder_item(): material_requests = {"Purchase": {}, "Transfer": {}} warehouse_company = frappe._dict(frappe.db.sql("""select name, company from `tabWarehouse` where disabled=0""")) default_company = (erpnext.get_default_company() or frappe.db.sql("""select name from tabCompany limit 1""")[0][0]) items_to_consider = frappe.db.sql_list("""select name from `tabItem` item where is_stock_item=1 and has_variants=0 and disabled=0 and (end_of_life is null or end_of_life='0000-00-00' or end_of_life > %(today)s) and (exists (select name from `tabItem Reorder` ir where ir.parent=item.name) or (variant_of is not null and variant_of != '' and exists (select name from `tabItem Reorder` ir where ir.parent=item.variant_of)) )""", {"today": nowdate()}) if not items_to_consider: return item_warehouse_projected_qty = get_item_warehouse_projected_qty(items_to_consider) def add_to_material_request(item_code, warehouse, reorder_level, reorder_qty, material_request_type): if warehouse not in warehouse_company: # a disabled warehouse return reorder_level = flt(reorder_level) reorder_qty = flt(reorder_qty) # projected_qty will be 0 if Bin does not exist projected_qty = flt(item_warehouse_projected_qty.get(item_code, {}).get(warehouse)) if (reorder_level or reorder_qty) and projected_qty < reorder_level: deficiency = reorder_level - projected_qty if deficiency > reorder_qty: reorder_qty = deficiency company = warehouse_company.get(warehouse) or default_company material_requests[material_request_type].setdefault(company, []).append({ "item_code": item_code, "warehouse": warehouse, "reorder_qty": reorder_qty }) for item_code in items_to_consider: item = frappe.get_doc("Item", item_code) if item.variant_of and not item.get("reorder_levels"): item.update_template_tables() if item.get("reorder_levels"): for d in item.get("reorder_levels"): add_to_material_request(item_code, d.warehouse, d.warehouse_reorder_level, d.warehouse_reorder_qty, d.material_request_type) if material_requests: return create_material_request(material_requests)
def setUp(self): for dt in ["Salary Slip", "Salary Structure", "Salary Structure Assignment"]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Structure Test Holiday List") make_employee("*****@*****.**") make_employee("*****@*****.**")
def get_salary_component_account(sal_comp): company = erpnext.get_default_company() sal_comp = frappe.get_doc("Salary Component", sal_comp) if not sal_comp.get("accounts"): sal_comp.append("accounts", { "company": company, "default_account": create_account(company) }) sal_comp.save()
def make_timesheet_for_projects(current_date ): for data in frappe.get_all("Task", ["name", "project"], {"status": "Open", "exp_end_date": ("<", current_date)}): employee = get_random("Employee") ts = make_timesheet(employee, simulate = True, billable = 1, company = erpnext.get_default_company(), activity_type=get_random("Activity Type"), project=data.project, task =data.name) if flt(ts.total_billable_amount) > 0.0: make_sales_invoice_for_timesheet(ts.name) frappe.db.commit()
def test_payroll_entry(self): # pylint: disable=no-self-use for data in frappe.get_all('Salary Component', fields = ["name"]): if not frappe.db.get_value('Salary Component Account', {'parent': data.name, 'company': erpnext.get_default_company()}, 'name'): get_salary_component_account(data.name) if not frappe.db.get_value("Salary Slip", {"start_date": "2016-11-01", "end_date": "2016-11-30"}): make_payroll_entry()
def execute(filters=None): columns, data = [], [] if filters.get('fiscal_year'): company = erpnext.get_default_company() period_list = get_period_list(filters.get('fiscal_year'), filters.get('fiscal_year'),"Monthly", company) columns=get_columns() data=get_log_data(filters) chart=get_chart_data(data,period_list) return columns, data, None, chart
def make_quotation(domain): # get open opportunites opportunity = get_random("Opportunity", {"status": "Open", "with_items": 1}) if opportunity: from erpnext.crm.doctype.opportunity.opportunity import make_quotation qtn = frappe.get_doc(make_quotation(opportunity)) qtn.insert() frappe.db.commit() qtn.submit() frappe.db.commit() else: # make new directly # get customer, currency and exchange_rate customer = get_random("Customer") company_currency = frappe.get_cached_value('Company', erpnext.get_default_company(), "default_currency") party_account_currency = get_party_account_currency("Customer", customer, erpnext.get_default_company()) if company_currency == party_account_currency: exchange_rate = 1 else: exchange_rate = get_exchange_rate(party_account_currency, company_currency, args="for_selling") qtn = frappe.get_doc({ "creation": frappe.flags.current_date, "doctype": "Quotation", "quotation_to": "Customer", "customer": customer, "currency": party_account_currency or company_currency, "conversion_rate": exchange_rate, "order_type": "Sales", "transaction_date": frappe.flags.current_date, }) add_random_children(qtn, "items", rows=3, randomize = { "qty": (1, 5), "item_code": ("Item", {"has_variants": "0", "is_fixed_asset": 0, "domain": domain}) }, unique="item_code") qtn.insert() frappe.db.commit() qtn.submit() frappe.db.commit()
def setUp(self): make_earning_salary_component(["Basic Salary", "Special Allowance", "HRA"]) make_deduction_salary_component(["Professional Tax", "TDS"]) for dt in ["Leave Application", "Leave Allocation", "Salary Slip"]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Slip Test Holiday List")
def setUp(self): make_earning_salary_component(setup=True) make_deduction_salary_component(setup=True) for dt in ["Leave Application", "Leave Allocation", "Salary Slip"]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Slip Test Holiday List") frappe.db.set_value("HR Settings", None, "email_salary_slip_to_employee", 0)
def test_process_payroll(self): month = "11" fiscal_year = "_Test Fiscal Year 2016" for data in frappe.get_all('Salary Component', fields = ["name"]): if not frappe.db.get_value('Salary Component Account', {'parent': data.name, 'company': erpnext.get_default_company()}, 'name'): get_salary_component_account(data.name) payment_account = frappe.get_value('Account', {'account_type': 'Cash', 'company': erpnext.get_default_company(),'is_group':0}, "name") if not frappe.db.get_value("Salary Slip", {"start_date": "2016-11-01", "end_date": "2016-11-30"}): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = erpnext.get_default_company() process_payroll.start_date = "2016-11-01" process_payroll.end_date = "2016-11-30" process_payroll.payment_account = payment_account process_payroll.posting_date = nowdate() process_payroll.payroll_frequency = "Monthly" process_payroll.create_salary_slips() process_payroll.submit_salary_slips() if process_payroll.get_sal_slip_list(ss_status = 1): r = process_payroll.make_payment_entry()
def create_additional_salary(employee, payroll_period, amount): salary_date = add_months(payroll_period.start_date, random.randint(0, 11)) frappe.get_doc({ "doctype": "Additional Salary", "employee": employee, "company": erpnext.get_default_company(), "salary_component": "Perfomance Bonus", "payroll_date": salary_date, "amount": amount, "type": "Earning" }).submit() return salary_date
def make_holiday_list(self): fiscal_year = get_fiscal_year(nowdate(), company=erpnext.get_default_company()) 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": fiscal_year[1], "to_date": fiscal_year[2], "weekly_off": "Sunday" }).insert() holiday_list.get_weekly_off_dates() holiday_list.save()
def test_payroll_entry(self): # pylint: disable=no-self-use company = erpnext.get_default_company() for data in frappe.get_all('Salary Component', fields = ["name"]): if not frappe.db.get_value('Salary Component Account', {'parent': data.name, 'company': company}, 'name'): get_salary_component_account(data.name) employee = frappe.db.get_value("Employee", {'company': company}) make_salary_structure("_Test Salary Structure", "Monthly", employee) dates = get_start_end_dates('Monthly', nowdate()) if not frappe.db.get_value("Salary Slip", {"start_date": dates.start_date, "end_date": dates.end_date}): make_payroll_entry(start_date=dates.start_date, end_date=dates.end_date)
def make_salary_structure(sal_struct): if not frappe.db.exists('Salary Structure', sal_struct): frappe.get_doc({ "doctype": "Salary Structure", "name": sal_struct, "company": erpnext.get_default_company(), "employees": get_employee_details(), "earnings": get_earnings_component(), "deductions": get_deductions_component(), "payroll_frequency": "Monthly", "payment_account": frappe.get_value('Account', {'account_type': 'Cash', 'company': erpnext.get_default_company(),'is_group':0}, "name") }).insert() return sal_struct
def setup_employee(): frappe.db.set_value("HR Settings", None, "emp_created_by", "Naming Series") frappe.db.commit() for d in frappe.get_all('Salary Component'): salary_component = frappe.get_doc('Salary Component', d.name) salary_component.append('accounts', dict( company=erpnext.get_default_company(), default_account=frappe.get_value('Account', dict(account_name=('like', 'Salary%'))) )) salary_component.save() import_json('Employee')
def make_salary_structure(sal_struct): if not frappe.db.exists('Salary Structure', sal_struct): frappe.get_doc({ "doctype": "Salary Structure", "name": sal_struct, "company": erpnext.get_default_company(), "from_date": nowdate(), "employees": get_employee_details(), "earnings": get_earnings_component(), "deductions": get_deductions_component(), "payment_account": get_random("Account") }).insert() return sal_struct
def create_payroll_period(): if not frappe.db.exists("Payroll Period", "_Test Payroll Period"): from datetime import date payroll_period = frappe.get_doc(dict( doctype = 'Payroll Period', name = "_Test Payroll Period", company = erpnext.get_default_company(), start_date = date(date.today().year, 1, 1), end_date = date(date.today().year, 12, 31) )).insert() return payroll_period else: return frappe.get_doc("Payroll Period", "_Test Payroll Period")
def make_employee(self, user): if not frappe.db.get_value("User", user): frappe.get_doc({ "doctype": "User", "email": user, "first_name": user, "new_password": "******", "user_roles": [{ "doctype": "UserRole", "role": "Employee" }] }).insert() if not frappe.db.get_value("Employee", {"user_id": user}): frappe.get_doc({ "doctype": "Employee", "naming_series": "EMP-", "employee_name": user, "company": erpnext.get_default_company(), "user_id": user, "date_of_birth": "1990-05-08", "date_of_joining": "2013-01-01", "department": frappe.get_all("Department", fields="name")[0].name, "gender": "Female", "company_email": user, "prefered_contact_email": "Company Email", "prefered_email": user, "status": "Active", "employment_type": "Intern" }).insert()
def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no, allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True): # Get valuation rate from last sle for the same item and warehouse if not company: company = erpnext.get_default_company() last_valuation_rate = frappe.db.sql("""select valuation_rate from `tabStock Ledger Entry` where item_code = %s AND warehouse = %s AND valuation_rate >= 0 AND NOT (voucher_no = %s AND voucher_type = %s) order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type)) if not last_valuation_rate: # Get valuation rate from last sle for the item against any warehouse last_valuation_rate = frappe.db.sql("""select valuation_rate from `tabStock Ledger Entry` where item_code = %s AND valuation_rate > 0 AND NOT(voucher_no = %s AND voucher_type = %s) order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, voucher_no, voucher_type)) if last_valuation_rate: return flt(last_valuation_rate[0][0]) # as there is previous records, it might come with zero rate # If negative stock allowed, and item delivered without any incoming entry, # system does not found any SLE, then take valuation rate from Item valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate") if not valuation_rate: # try Item Standard rate valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate") if not valuation_rate: # try in price list valuation_rate = frappe.db.get_value('Item Price', dict(item_code=item_code, buying=1, currency=currency), 'price_list_rate') if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \ and cint(erpnext.is_perpetual_inventory_enabled(company)): frappe.local.message_log = [] frappe.throw(_("Valuation rate not found for the Item {0}, which is required to do accounting entries for {1} {2}. If the item is transacting as a zero valuation rate item in the {1}, please mention that in the {1} Item table. Otherwise, please create an incoming stock transaction for the item or mention valuation rate in the Item record, and then try submiting/cancelling this entry").format(item_code, voucher_type, voucher_no)) return valuation_rate
def get_columns(filters): if filters.get("presentation_currency"): currency = filters["presentation_currency"] else: if filters.get("company"): currency = get_company_currency(filters["company"]) else: company = get_default_company() currency = get_company_currency(company) columns = [{ "label": _("Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 90 }, { "label": _("Description"), "fieldname": "account", "fieldtype": "Link", "options": "Account", "width": 180 }, { "label": _("Document"), "fieldname": "voucher_type", "width": 120 }, { "label": _("Document No"), "fieldname": "voucher_no", "fieldtype": "Dynamic Link", "options": "voucher_type", "width": 180 }, { "label": _("Debit ({0})".format(currency)), "fieldname": "debit", "fieldtype": "Float", "width": 100 }, { "label": _("Credit ({0})".format(currency)), "fieldname": "credit", "fieldtype": "Float", "width": 100 }, { "label": _(" Account Balance ({0})".format(currency)), "fieldname": "balance", "fieldtype": "Float", "width": 180 }] return columns
def complete_setup(domain='Manufacturing'): print "Complete Setup..." from frappe.desk.page.setup_wizard.setup_wizard import setup_complete if not frappe.get_all('Company', limit=1): setup_complete({ "full_name": "Test User", "email": "*****@*****.**", "company_tagline": 'Awesome Products and Services', "password": "******", "fy_start_date": "2015-01-01", "fy_end_date": "2015-12-31", "bank_account": "National Bank", "domain": domain, "company_name": data.get(domain).get('company_name'), "chart_of_accounts": "Standard", "company_abbr": ''.join([ d[0] for d in data.get(domain).get('company_name').split() ]).upper(), "currency": 'USD', "timezone": 'America/New_York', "country": 'United States', "language": "english" }) company = erpnext.get_default_company() if company: company_doc = frappe.get_doc("Company", company) company_doc.db_set( 'default_payroll_payable_account', frappe.db.get_value('Account', dict(account_name='Payroll Payable')))
def create_exemption_declaration(employee, payroll_period): create_exemption_category() declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": employee, "payroll_period": payroll_period, "company": erpnext.get_default_company(), "currency": erpnext.get_default_currency() }) declaration.append( "declarations", { "exemption_sub_category": "_Test Sub Category", "exemption_category": "_Test Category", "amount": 100000 }) declaration.submit()
def setUp(self): make_earning_salary_component(setup=True, company_list=["_Test Company"]) make_deduction_salary_component(setup=True, company_list=["_Test Company"]) for dt in ["Leave Application", "Leave Allocation", "Salary Slip"]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Slip Test Holiday List") frappe.db.set_value("HR Settings", None, "email_salary_slip_to_employee", 0)
def total_sales(): company = erpnext.get_default_company() start_date = frappe.db.sql( """select min(posting_date) from `tabSales Invoice` where company = %s""", (company))[0][0] or today() custom_filter = { 'from_date': start_date, 'to_date': today(), 'company': company } report = frappe.get_doc('Report', "Sales Register") columns, data = report.get_data(filters=custom_filter, as_dict=True) sales_abbr = "Sales - {}".format( frappe.db.get_value('Company', company, 'abbr')) list_of_total_sales = [i[sales_abbr] for i in data if sales_abbr in i] return 'Total Sales', list_of_total_sales[-1]
def setUp(self): for dt in [ "Salary Slip", "Salary Structure", "Salary Structure Assignment" ]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value( "Company", erpnext.get_default_company(), "default_holiday_list", "Salary Structure Test Holiday List", ) make_employee("*****@*****.**") make_employee("*****@*****.**")
def test_duplicate_category_in_declaration(self): declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": erpnext.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 = "_Test Sub Category", exemption_category = "_Test Category", amount = 50000) ] }) self.assertRaises(frappe.ValidationError, declaration.save)
def test_process_payroll(self): month = "11" fiscal_year = "_Test Fiscal Year 2016" for data in frappe.get_all('Salary Component', fields=["name"]): if not frappe.db.get_value('Salary Component Account', { 'parent': data.name, 'company': erpnext.get_default_company() }, 'name'): get_salary_component_account(data.name) if not frappe.db.get_value("Salary Slip", { "start_date": "2016-11-01", "end_date": "2016-11-30" }): make_process_payroll()
def simulate(): runs_for = frappe.flags.runs_for or 150 frappe.flags.company = erpnext.get_default_company() frappe.flags.mute_emails = True if not frappe.flags.start_date: # start date = 100 days back frappe.flags.start_date = frappe.utils.add_days( frappe.utils.nowdate(), -1 * runs_for) current_date = frappe.utils.getdate(frappe.flags.start_date) # continue? demo_last_date = frappe.db.get_global('demo_last_date') if demo_last_date: current_date = frappe.utils.add_days(demo_last_date, 1) # run till today if not runs_for: runs_for = frappe.utils.date_diff(frappe.utils.nowdate(), current_date) # runs_for = 100 for i in xrange(runs_for): sys.stdout.write("\rSimulating {0}".format( current_date.strftime("%Y-%m-%d"))) sys.stdout.flush() frappe.flags.current_date = current_date if current_date.weekday() in (5, 6): current_date = frappe.utils.add_days(current_date, 1) continue hr.work() sales.work() purchase.work() manufacturing.work() stock.work() accounts.work() projects.run_projects(current_date) # run_stock() # run_accounts() # run_projects() # run_messages() current_date = frappe.utils.add_days(current_date, 1) frappe.db.commit()
def simulate(domain='Healthcare', days=100): runs_for = frappe.flags.runs_for or days frappe.flags.company = erpnext.get_default_company() frappe.flags.mute_emails = True if not frappe.flags.start_date: # start date = 100 days back frappe.flags.start_date = frappe.utils.add_days( frappe.utils.nowdate(), -1 * runs_for) current_date = frappe.utils.getdate(frappe.flags.start_date) # continue? demo_last_date = frappe.db.get_global('demo_last_date') if demo_last_date: current_date = frappe.utils.add_days( frappe.utils.getdate(demo_last_date), 1) # run till today if not runs_for: runs_for = frappe.utils.date_diff(frappe.utils.nowdate(), current_date) # runs_for = 100 fixed_asset.work() for i in range(runs_for): sys.stdout.write("\rSimulating {0}: Day {1}".format( current_date.strftime("%Y-%m-%d"), i)) sys.stdout.flush() frappe.flags.current_date = current_date if current_date.weekday() in (5, 6): current_date = frappe.utils.add_days(current_date, 1) continue try: hr.work() purchase.work() stock.work() accounts.work() projects.run_projects(current_date) sales.work(domain) # run_messages() except: frappe.db.set_global('demo_last_date', current_date) raise finally: current_date = frappe.utils.add_days(current_date, 1) frappe.db.commit()
def get_last_buying_rate(item_code, currency=None, supplier=None, company=None): if not company: company = get_default_company() if not currency: currency = get_company_currency(company) item_code = "'{0}'".format(item_code) currency = "'{0}'".format(currency) if supplier: conditions = " and SI.customer = '%s'" % supplier else: conditions = "" query = """ SELECT max(SI.posting_date) as MaxDate FROM `tabPurchase Invoice` AS SI INNER JOIN `tabPurchase Invoice Item` AS SIT ON SIT.parent = SI.name WHERE SIT.item_code = {0} AND SI.docstatus= 1 AND SI.currency = {2} AND SI.is_return != 1 AND SI.company = '{3}' {1}""".format(item_code, conditions, currency, company) items_list = frappe.db.sql(query, as_dict=True) date = str(items_list[0]["MaxDate"]) query2 = """ SELECT SI.name, SI.posting_date, SI.supplier, SIT.item_code, SIT.qty, SIT.rate FROM `tabPurchase Invoice` AS SI INNER JOIN `tabPurchase Invoice Item` AS SIT ON SIT.parent = SI.name WHERE SIT.item_code = {0} AND SI.docstatus= 1 AND SI.posting_date= '{4}' AND SI.currency = {2} AND SI.is_return != 1 AND SI.company = '{3}' {1}""".format(item_code, conditions, currency, company, date) items_rate = frappe.db.sql(query2, as_dict=True) if items_rate and len(items_rate) > 0: return items_rate[0]["rate"] else: return 0
def setup_salary_structure(employees, salary_slip_based_on_timesheet=0): ss = frappe.new_doc('Salary Structure') ss.name = "Sample Salary Structure - " + random_string(5) ss.salary_slip_based_on_timesheet = salary_slip_based_on_timesheet if salary_slip_based_on_timesheet: ss.salary_component = 'Basic' ss.hour_rate = flt(random.random() * 10, 2) else: ss.payroll_frequency = 'Monthly' ss.payment_account = frappe.get_value( 'Account', { 'account_type': 'Cash', 'company': erpnext.get_default_company(), 'is_group': 0 }, "name") ss.append( 'earnings', { 'salary_component': 'Basic', "abbr": 'B', 'formula': 'base*.2', 'amount_based_on_formula': 1, "idx": 1 }) ss.append( 'deductions', { 'salary_component': 'Income Tax', "abbr": 'IT', 'condition': 'base > 10000', 'formula': 'base*.1', "idx": 1 }) ss.insert() ss.submit() for e in employees: sa = frappe.new_doc("Salary Structure Assignment") sa.employee = e.name sa.salary_structure = ss.name sa.from_date = "2015-01-01" sa.base = random.random() * 10000 sa.insert() sa.submit() return ss
def setup_holiday_list(): """Setup Holiday List for the current year""" year = now_datetime().year holiday_list = frappe.get_doc({ "doctype": "Holiday List", "holiday_list_name": str(year), "from_date": "{0}-01-01".format(year), "to_date": "{0}-12-31".format(year), }) holiday_list.insert() holiday_list.weekly_off = "Saturday" holiday_list.get_weekly_off_dates() holiday_list.weekly_off = "Sunday" holiday_list.get_weekly_off_dates() holiday_list.save() frappe.set_value("Company", erpnext.get_default_company(), "default_holiday_list", holiday_list.name)
def make_payroll_entry(**args): args = frappe._dict(args) payroll_entry = frappe.new_doc("Payroll Entry") payroll_entry.company = args.company or erpnext.get_default_company() payroll_entry.start_date = args.start_date or "2016-11-01" payroll_entry.end_date = args.end_date or "2016-11-30" payroll_entry.payment_account = get_payment_account() payroll_entry.posting_date = nowdate() payroll_entry.payroll_frequency = "Monthly" payroll_entry.branch = args.branch or None payroll_entry.create_salary_slips() payroll_entry.submit_salary_slips() if payroll_entry.get_sal_slip_list(ss_status = 1): payroll_entry.make_payment_entry() return payroll_entry
def setup_test(): make_earning_salary_component(setup=True, company_list=["_Test Company"]) make_deduction_salary_component(setup=True, company_list=["_Test Company"]) for dt in ["Leave Application", "Leave Allocation", "Salary Slip", "Attendance", "Additional Salary"]: frappe.db.sql("delete from `tab%s`" % dt) make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company( ), "default_holiday_list", "Salary Slip Test Holiday List") frappe.db.set_value("Payroll Settings", None, "email_salary_slip_to_employee", 0) frappe.db.set_value('HR Settings', None, 'leave_status_notification_template', None) frappe.db.set_value('HR Settings', None, 'leave_approval_notification_template', None)
def total_collection(): company = erpnext.get_default_company() start_date = frappe.db.sql( """select min(posting_date) from `tabSales Invoice` where company = %s""", (company))[0][0] or today() end_date = today() custom_filter = { 'from_date': start_date, 'to_date': end_date, 'company': company } report = frappe.get_doc('Report', "Sales Payment Summary") columns, data = report.get_data(filters=custom_filter, as_dict=True) sales_abbr = "Sales - {}".format( frappe.db.get_value('Company', company, 'abbr')) list_of_total_payments = [i["Payments"] for i in data if "Payments" in i] return 'Total Collection', list_of_total_payments[-1]
def create_holiday_list(): holiday_list = 'Test Holiday List for Student' today = getdate() if not frappe.db.exists('Holiday List', holiday_list): frappe.get_doc( dict(doctype='Holiday List', holiday_list_name=holiday_list, from_date=add_months(today, -6), to_date=add_months(today, 6), holidays=[ dict(holiday_date=add_days(today, 1), description='Test') ])).insert() company = get_default_company() or frappe.get_all('Company')[0].name frappe.db.set_value('Company', company, 'default_holiday_list', holiday_list) return holiday_list
def make_process_payroll(**args): args = frappe._dict(args) process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = erpnext.get_default_company() process_payroll.start_date = args.start_date or "2016-11-01" process_payroll.end_date = args.end_date or "2016-11-30" process_payroll.payment_account = get_payment_account() process_payroll.posting_date = nowdate() process_payroll.payroll_frequency = "Monthly" process_payroll.branch = args.branch or None process_payroll.create_salary_slips() process_payroll.submit_salary_slips() if process_payroll.get_sal_slip_list(ss_status=1): r = process_payroll.make_payment_entry() return process_payroll
def update_value_in_dict(data, key, gle): if filters.get("company"): currency = get_company_currency(filters["company"]) else: company = get_default_company() currency = get_company_currency(company) #if currency!=gle.account_currency: #else: #frappe.msgprint("gle={0}".format(gle.account_currency)) data[key].debit += flt(gle.debit) data[key].credit += flt(gle.credit) data[key].debit_in_account_currency += flt(gle.debit_in_account_currency) data[key].credit_in_account_currency += flt(gle.credit_in_account_currency) if data[key].against_voucher and gle.against_voucher: data[key].against_voucher += ', ' + gle.against_voucher
def create_salary_structure_assignment(employee, salary_structure, from_date=None, company=None, currency=erpnext.get_default_currency(), payroll_period=None): if frappe.db.exists("Salary Structure Assignment", {"employee": employee}): frappe.db.sql( """delete from `tabSalary Structure Assignment` where employee=%s""", (employee)) if not payroll_period: payroll_period = create_payroll_period() income_tax_slab = frappe.db.get_value("Income Tax Slab", {"currency": currency}) if not income_tax_slab: income_tax_slab = create_tax_slab(payroll_period, allow_tax_exemption=True, currency=currency) salary_structure_assignment = frappe.new_doc("Salary Structure Assignment") salary_structure_assignment.employee = employee salary_structure_assignment.base = 50000 salary_structure_assignment.variable = 5000 if not from_date: from_date = get_first_day(nowdate()) joining_date = frappe.get_cached_value("Employee", employee, "date_of_joining") if date_diff(joining_date, from_date) > 0: from_date = joining_date salary_structure_assignment.from_date = from_date salary_structure_assignment.salary_structure = salary_structure salary_structure_assignment.currency = currency salary_structure_assignment.payroll_payable_account = get_payable_account( company) salary_structure_assignment.company = company or erpnext.get_default_company( ) salary_structure_assignment.save(ignore_permissions=True) salary_structure_assignment.income_tax_slab = income_tax_slab salary_structure_assignment.submit() return salary_structure_assignment
def test_exemption_amount(self): declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"*****@*****.**"}, "name"), "company": erpnext.get_default_company(), "payroll_period": "_Test Payroll Period", "declarations": [ dict(exemption_sub_category = "_Test Sub Category", exemption_category = "_Test Category", amount = 80000), dict(exemption_sub_category = "_Test1 Sub Category", exemption_category = "_Test Category", amount = 60000), ] }).insert() self.assertEqual(declaration.total_exemption_amount, 100000)
def simulate(days=100): print("Running Simulation...") runs_for = frappe.flags.runs_for or days frappe.flags.company = erpnext.get_default_company() frappe.flags.mute_emails = True if not frappe.flags.start_date: # start date = 100 days back frappe.flags.start_date = frappe.utils.add_days( frappe.utils.nowdate(), -1 * runs_for) current_date = frappe.utils.getdate(frappe.flags.start_date) # continue? demo_last_date = frappe.db.get_global('demo_last_date') if demo_last_date: current_date = frappe.utils.add_days( frappe.utils.getdate(demo_last_date), 1) # run till today if not runs_for: runs_for = frappe.utils.date_diff(frappe.utils.nowdate(), current_date) # runs_for = 100 for i in range(runs_for): sys.stdout.write("\rSimulating {0}: Day {1}".format( current_date.strftime("%Y-%m-%d"), i)) sys.stdout.flush() frappe.flags.current_date = current_date if current_date.weekday() in (5, 6): current_date = frappe.utils.add_days(current_date, 1) continue try: projects.run_projects(current_date) sales.run() # TODO: Add purchases with inventory items #purchases.run() accounts.run() bookings.run() except: frappe.db.set_global('demo_last_date', current_date) raise finally: current_date = frappe.utils.add_days(current_date, 1) frappe.db.commit()
def make_leave_application(employee, from_date, to_date, leave_type, company=None): leave_application = frappe.get_doc( dict(doctype='Leave Application', employee=employee, leave_type=leave_type, from_date=from_date, to_date=to_date, company=company or erpnext.get_default_company() or "_Test Company", docstatus=1, status="Approved", leave_approver='*****@*****.**')) leave_application.submit()
def setUp(self): make_salary_component( ["Basic Salary", "Allowance", "HRA", "Professional Tax", "TDS"]) for dt in ["Leave Application", "Leave Allocation", "Salary Slip"]: frappe.db.sql("delete from `tab%s`" % dt) self.make_holiday_list() frappe.db.set_value("Company", erpnext.get_default_company(), "default_holiday_list", "Salary Slip Test Holiday List") from erpnext.hr.doctype.leave_application.test_leave_application import _test_records as leave_applications la = frappe.copy_doc(leave_applications[2]) la.insert() la.status = "Approved" la.submit()
def boot_session(bootinfo): """boot session - send website info if guest""" bootinfo.custom_css = frappe.db.get_value('Style Settings', None, 'custom_css') or '' bootinfo.website_settings = frappe.get_doc('Website Settings') if frappe.session['user'] != 'Guest': update_page_info(bootinfo) load_country_and_currency(bootinfo) bootinfo.sysdefaults.territory = frappe.db.get_single_value( 'Selling Settings', 'territory') bootinfo.sysdefaults.customer_group = frappe.db.get_single_value( 'Selling Settings', 'customer_group') bootinfo.sysdefaults.allow_stale = cint( frappe.db.get_single_value('Accounts Settings', 'allow_stale')) bootinfo.sysdefaults.quotation_valid_till = cint( frappe.db.get_single_value('Selling Settings', 'default_valid_till')) bootinfo.sysdefaults.default_bank_account_name = frappe.db.get_value( "Bank Account", { "is_default": 1, "is_company_account": 1, "company": get_default_company() }, "name") # if no company, show a dialog box to create a new company bootinfo.customer_count = frappe.db.sql( """SELECT count(*) FROM `tabCustomer`""")[0][0] if not bootinfo.customer_count: bootinfo.setup_complete = frappe.db.sql("""SELECT `name` FROM `tabCompany` LIMIT 1""") and 'Yes' or 'No' bootinfo.docs += frappe.db.sql( """select name, default_currency, cost_center, default_selling_terms, default_buying_terms, default_letter_head, default_bank_account, enable_perpetual_inventory, country from `tabCompany`""", as_dict=1, update={"doctype": ":Company"}) party_account_types = frappe.db.sql( """ select name, ifnull(account_type, '') from `tabParty Type`""") bootinfo.party_account_types = frappe._dict(party_account_types)
def autoname(item, method=None): """ Item Code = a + b + c + d + e, where a = abbreviated Company; all caps. b = abbreviated Brand; all caps. c = abbreviated Item Group; all caps. d = abbreviated Item Name; all caps. e = variant ID number; has to be incremented. """ if not frappe.db.get_single_value("Stock Settings", "autoname_item"): return # Get abbreviations item_group_abbr = get_abbr(item.item_group) item_name_abbr = get_abbr(item.item_name, 3) default_company = get_default_company() if default_company: company_abbr = get_company_default(default_company, "abbr") brand_abbr = get_abbr(item.brand, max_length=len(company_abbr)) brand_abbr = brand_abbr if company_abbr != brand_abbr else None params = list( filter( None, [company_abbr, brand_abbr, item_group_abbr, item_name_abbr])) item_code = "-".join(params) else: brand_abbr = get_abbr(item.brand) params = list( filter(None, [brand_abbr, item_group_abbr, item_name_abbr])) item_code = "-".join(params) # Get count count = len( frappe.get_all("Item", filters={"name": ["like", "%{}%".format(item_code)]})) if count > 0: item_code = "-".join([item_code, cstr(count + 1)]) # Set item document name item.name = item.item_code = item_code if not method: return item.item_code
def make_timesheet_for_projects(current_date): for data in frappe.get_all("Task", ["name", "project"], { "status": "Open", "exp_end_date": ("<", current_date) }): employee = get_random("Employee") ts = make_timesheet(employee, simulate=True, billable=1, company=erpnext.get_default_company(), activity_type=get_random("Activity Type"), project=data.project, task=data.name) if flt(ts.total_billable_amount) > 0.0: make_sales_invoice_for_timesheet(ts.name) frappe.db.commit()
def create_item(shopify_item, warehouse, has_variant=0, attributes=None,variant_of=None): item_dict = { "doctype": "Item", "shopify_product_id": shopify_item.get("id"), "shopify_variant_id": shopify_item.get("variant_id"), "variant_of": variant_of, "sync_with_shopify": 1, "is_stock_item": 1, "item_code": cstr(shopify_item.get("item_code")) or cstr(shopify_item.get("id")), "item_name": shopify_item.get("title", '').strip(), "description": shopify_item.get("body_html") or shopify_item.get("title"), "shopify_description": shopify_item.get("body_html") or shopify_item.get("title"), "item_group": get_item_group(shopify_item.get("product_type")), "has_variants": has_variant, "attributes":attributes or [], "stock_uom": shopify_item.get("uom") or _("Nos"), "stock_keeping_unit": shopify_item.get("sku") or get_sku(shopify_item), "default_warehouse": warehouse, "image": get_item_image(shopify_item), "weight_uom": shopify_item.get("weight_unit"), "weight_per_unit": shopify_item.get("weight"), "default_supplier": get_supplier(shopify_item), "item_defaults": [ { "company": get_default_company() } ] } if not is_item_exists(item_dict, attributes, variant_of=variant_of): item_details = get_item_details(shopify_item) name = '' if not item_details: new_item = frappe.get_doc(item_dict) new_item.insert(ignore_permissions=True, ignore_mandatory=True) name = new_item.name if not name: name = item_details.name if not has_variant: add_to_price_list(shopify_item, name) frappe.db.commit()