def set_tax_withholding_category(company): accounts = [] abbr = frappe.get_value("Company", company, "abbr") tds_account = frappe.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 = frappe.get_doc(d) doc.flags.ignore_permissions = True doc.flags.ignore_mandatory = True doc.insert() except frappe.DuplicateEntryError: doc = frappe.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 test_duplicate_submission_for_payroll_period(self): declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"[email protected]"}, "name"), "company": "_Test 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() declaration.submit() self.assertEquals(declaration.docstatus, 1) duplicate_declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"[email protected]"}, "name"), "company": "_Test Company", "payroll_period": "_Test Payroll Period", "declarations": [dict(exemption_sub_category = "_Test Sub Category", exemption_category = "_Test Category", amount = 100000) ] }).insert() self.assertRaises(frappe.DocstatusTransitionError, duplicate_declaration.submit) duplicate_declaration.employee = frappe.get_value("Employee", {"user_id":"[email protected]"}, "name") self.assertTrue(duplicate_declaration.submit)
def execute(): sid_no_cetsh = frappe.db.sql("""SELECT name, item_code ,gst_hsn_code, cetsh_number FROM `tabSales Invoice Item` WHERE cetsh_number IS NULL AND gst_hsn_code IS NULL ORDER BY creation""", as_list=1) if sid_no_cetsh: for sid in sid_no_cetsh: sid_doc = frappe.get_doc("Sales Invoice Item", sid[0]) cetsh_number = frappe.get_value("Item", sid[1], "customs_tariff_number") if cetsh_number: frappe.db.set_value("Sales Invoice Item", sid[0], "cetsh_number", cetsh_number) frappe.db.set_value("Sales Invoice Item", sid[0], "gst_hsn_code", cetsh_number) print("Updated CETSH Number and GST HSN Code in Sales Invoice # " \ + sid_doc.parent + " Item No: " + str(sid_doc.idx)) else: print("SI# " + sid_doc.parent + " Item Code: " + sid[1] + \ " At Row No " + str(sid_doc.idx) + \ " Does Not Have CETSH Number Linked") frappe.db.commit() print("Committed Changes") sid_list = frappe.db.sql("""SELECT name, gst_hsn_code, cetsh_number FROM `tabSales Invoice Item` WHERE cetsh_number IS NOT NULL AND gst_hsn_code IS NULL ORDER BY creation""", as_list=1) if sid_list: for sid in sid_list: cetsh_number = frappe.get_value("Sales Invoice Item", sid[0], "cetsh_number") sid_doc = frappe.get_doc("Sales Invoice Item", sid[0]) frappe.db.set_value("Sales Invoice Item", sid[0], "gst_hsn_code", cetsh_number) print("Updated GST HSN Code in SI # " + sid_doc.parent + " Item No: " + str(sid_doc.idx)) frappe.db.commit() print("Committed Changes")
def test_sales_order_for_woocommerece(self): data = {"id":75,"parent_id":0,"number":"74","order_key":"wc_order_5aa1281c2dacb","created_via":"checkout","version":"3.3.3","status":"processing","currency":"INR","date_created":"2018-03-08T12:10:04","date_created_gmt":"2018-03-08T12:10:04","date_modified":"2018-03-08T12:10:04","date_modified_gmt":"2018-03-08T12:10:04","discount_total":"0.00","discount_tax":"0.00","shipping_total":"150.00","shipping_tax":"0.00","cart_tax":"0.00","total":"649.00","total_tax":"0.00","prices_include_tax":False,"customer_id":12,"customer_ip_address":"103.54.99.5","customer_user_agent":"mozilla\\/5.0 (x11; linux x86_64) applewebkit\\/537.36 (khtml, like gecko) chrome\\/64.0.3282.186 safari\\/537.36","customer_note":"","billing":{"first_name":"Tony","last_name":"Stark","company":"Woocommerce","address_1":"Mumbai","address_2":"","city":"Dadar","state":"MH","postcode":"123","country":"IN","email":"[email protected]","phone":"123457890"},"shipping":{"first_name":"Tony","last_name":"Stark","company":"","address_1":"Mumbai","address_2":"","city":"Dadar","state":"MH","postcode":"123","country":"IN"},"payment_method":"cod","payment_method_title":"Cash on delivery","transaction_id":"","date_paid":"","date_paid_gmt":"","date_completed":"","date_completed_gmt":"","cart_hash":"8e76b020d5790066496f244860c4703f","meta_data":[],"line_items":[{"id":80,"name":"Marvel","product_id":56,"variation_id":0,"quantity":1,"tax_class":"","subtotal":"499.00","subtotal_tax":"0.00","total":"499.00","total_tax":"0.00","taxes":[],"meta_data":[],"sku":"","price":499}],"tax_lines":[],"shipping_lines":[{"id":81,"method_title":"Flat rate","method_id":"flat_rate:1","total":"150.00","total_tax":"0.00","taxes":[],"meta_data":[{"id":623,"key":"Items","value":"Marvel × 1"}]}],"fee_lines":[],"coupon_lines":[],"refunds":[]} order(data) self.assertTrue(frappe.get_value("Customer",{"woocommerce_email":"[email protected]"})) self.assertTrue(frappe.get_value("Item",{"woocommerce_id": 56})) self.assertTrue(frappe.get_value("Sales Order",{"woocommerce_id":75}))
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 = frappe.get_value(invoice_type, invoice, 'outstanding_amount') lst.append(frappe._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': frappe.get_value("Payment Entry", payment.reference_name, "party"), 'unadjusted_amount' : float(amount), 'allocated_amount' : min(outstanding_amount, amount) })) amount -= outstanding_amount if lst: from erpnext.accounts.utils import reconcile_against_document try: reconcile_against_document(lst) except: frappe.throw("Exception occurred while reconciling {0}".format(payment.reference_name))
def test_duplicate_entry_for_payroll_period(self): declaration = frappe.get_doc({ "doctype": "Employee Tax Exemption Declaration", "employee": frappe.get_value("Employee", {"user_id":"[email protected]"}, "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":"[email protected]"}, "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":"[email protected]"}, "name") self.assertTrue(duplicate_declaration.insert)
def create_invoice(company, patient, lab_tests, prescriptions): test_ids = json.loads(lab_tests) line_ids = json.loads(prescriptions) if not test_ids and not line_ids: return sales_invoice = frappe.new_doc("Sales Invoice") sales_invoice.customer = frappe.get_value("Patient", patient, "customer") sales_invoice.due_date = getdate() sales_invoice.is_pos = '0' sales_invoice.debit_to = get_receivable_account(company) for line in line_ids: test_code = frappe.get_value("Lab Prescription", line, "test_code") create_item_line(test_code, sales_invoice) for test in test_ids: template = frappe.get_value("Lab Test", test, "template") test_code = frappe.get_value("Lab Test Template", template, "item") create_item_line(test_code, sales_invoice) sales_invoice.set_missing_values() sales_invoice.save() #set invoice in lab test for test in test_ids: frappe.db.set_value("Lab Test", test, "invoice", sales_invoice.name) prescription = frappe.db.get_value("Lab Test", test, "prescription") if prescription: frappe.db.set_value("Lab Prescription", prescription, "invoice", sales_invoice.name) #set invoice in prescription for line in line_ids: frappe.db.set_value("Lab Prescription", line, "invoice", sales_invoice.name) return sales_invoice.name
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 test_set_value(self): todo = frappe.get_doc(dict(doctype='ToDo', description='test')).insert() frappe.set_value('ToDo', todo.name, 'description', 'test 1') self.assertEqual(frappe.get_value('ToDo', todo.name, 'description'), 'test 1') frappe.set_value('ToDo', todo.name, {'description': 'test 2'}) self.assertEqual(frappe.get_value('ToDo', todo.name, 'description'), 'test 2')
def test_payment_days(self): # Holidays not included in working days frappe.db.set_value("HR Settings", None, "include_holidays_in_total_working_days", 0) # set joinng date in the same month self.make_employee("[email protected]") frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "date_of_joining", "2013-01-11") ss = frappe.get_doc("Salary Slip", self.make_employee_salary_slip("[email protected]")) self.assertEquals(ss.total_days_in_month, 27) self.assertEquals(ss.payment_days, 27) # set relieving date in the same month frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "relieving_date", "12-12-2016") frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "status", "Left") self.assertEquals(ss.total_days_in_month, 27) self.assertEquals(ss.payment_days, 27) ss.save() frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "relieving_date", None) frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "status", "Active") # Holidays included in working days frappe.db.set_value("HR Settings", None, "include_holidays_in_total_working_days", 1) self.assertEquals(ss.total_days_in_month, 27) self.assertEquals(ss.payment_days, 27) ss.save()
def make_consulation(): for i in range(3): practitioner = get_random("Healthcare Practitioner") department = frappe.get_value("Healthcare Practitioner", practitioner, "department") patient = get_random("Patient") patient_sex = frappe.get_value("Patient", patient, "sex") encounter = set_encounter(patient, patient_sex, practitioner, department, getdate(), i) encounter.save(ignore_permissions=True)
def make_consulation(): for i in xrange(3): physician = get_random("Physician") department = frappe.get_value("Physician", physician, "department") patient = get_random("Patient") patient_sex = frappe.get_value("Patient", patient, "sex") consultation = set_consultation(patient, patient_sex, physician, department, getdate(), i) consultation.save(ignore_permissions=True)
def test_amount_totals(self): sal_slip = frappe.get_value("Salary Slip", {"employee_name":"[email protected]"}) if not sal_slip: sal_slip = make_salary_slip_from_salary_structure(employee=frappe.get_value("Employee", {"employee_name":"[email protected]"})) self.assertEquals(sal_slip.get("salary_structure"), 'Salary Structure Sample') self.assertEquals(sal_slip.get("earnings")[0].amount, 5000) self.assertEquals(sal_slip.get("deductions")[0].amount, 5000) self.assertEquals(sal_slip.get("deductions")[1].amount, 2500) self.assertEquals(sal_slip.get("total_deduction"), 7500) self.assertEquals(sal_slip.get("net_pay"), 7500)
def get_employees_allowed_ids(employee): allowed_ids = [] status = frappe.get_value("Employee", employee, "status") if status == 'Active': user_id = frappe.get_value("Employee", employee, "user_id") user_id_perm = frappe.get_value("Employee", employee, "create_user_permission") reports_to = frappe.get_value("Employee", employee, "reports_to") if user_id is not None and user_id_perm == 1: allowed_ids.append(user_id) if reports_to: allowed_ids.append(reports_to) return allowed_ids
def get_employee_details(): return [{"employee": frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "base": 25000, "variable": 5000, "idx": 1 }, {"employee": frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "base": 15000, "variable": 100, "idx": 2 } ]
def get_purchase_item(item_code,qty): doc = frappe.new_doc("BOM Costing Purchased Item") doc.item = item_code doc.sort_name = item_code.lower() doc.supplier = frappe.get_value("Item",doc.item,"default_supplier") doc.price_list = frappe.get_value("Item",doc.item,"default_supplier") doc.currency = frappe.get_value("Supplier", doc.supplier,"default_currency") doc.description = frappe.get_value("Item",doc.item,"description") doc.item_name= frappe.get_value("Item",doc.item,"item_name") doc.qty_per_asm= qty doc.idx = None return doc
def add_bank_gl_entries(self, gl_entries): if self.payment_type in ("Pay", "Internal Transfer"): if frappe.get_value("Account", self.paid_from, "report_type") == "Profit and Loss": if self.pl_cost_center: gl_entries.append( self.get_gl_dict({ "account": self.paid_from, "account_currency": self.paid_from_account_currency, "against": self.party if self.payment_type=="Pay" else self.paid_to, "debit_in_account_currency": self.paid_amount, "debit": self.base_paid_amount, "cost_center": self.pl_cost_center }) ) else: frappe.throw("Please select a Cost Center under 'Cost Center (If Applicable)' field") else: gl_entries.append( self.get_gl_dict({ "account": self.paid_from, "account_currency": self.paid_from_account_currency, "against": self.party if self.payment_type=="Pay" else self.paid_to, "credit_in_account_currency": self.paid_amount, "credit": self.base_paid_amount }) ) if self.payment_type in ("Receive", "Internal Transfer"): if frappe.get_value("Account", self.paid_to, "report_type") == "Profit and Loss": if self.pl_cost_center: gl_entries.append( self.get_gl_dict({ "account": self.paid_to, "account_currency": self.paid_to_account_currency, "against": self.party if self.payment_type=="Receive" else self.paid_from, "debit_in_account_currency": self.received_amount, "debit": self.base_received_amount, "cost_center": self.pl_cost_center }) ) else: frappe.throw("Please select a Cost Center under 'Cost Center (If Applicable)' field") else: gl_entries.append( self.get_gl_dict({ "account": self.paid_to, "account_currency": self.paid_to_account_currency, "against": self.party if self.payment_type=="Receive" else self.paid_from, "debit_in_account_currency": self.received_amount, "debit": self.base_received_amount }) )
def set_commodities_info(self, shipment): if self.document in CarrierTracking.allowed_docs_items: doc = frappe.get_doc(self.document, self.document_name) total_qty = 0 for row in doc.items: total_qty += row.get("qty") hsn_doc = frappe.get_doc("GST HSN Code", frappe.get_value('Item', row.get('item_code'), 'customs_tariff_number')) item_doc = frappe.get_doc("Item", row.get("item_code")) country_doc = frappe.get_doc("Country", item_doc.country_of_origin) country_code = country_doc.code commodity_dict = { #"Name":row.get("item_code"), "Description": hsn_doc.description[0:30], "Weight": {"Units": self.uom_mapper.get(self.weight_uom),\ "Value":self.total_weight}, "NumberOfPieces":int(self.total_handling_units), "HarmonizedCode": hsn_doc.name[0:8], "CountryOfManufacture":country_code, "Quantity":int(total_qty), "QuantityUnits":"EA", "UnitPrice":{"Currency":doc.currency, \ "Amount":(doc.grand_total/total_qty) if self.purpose == 'SOLD' \ else (1/total_qty)}, "CustomsValue":{"Currency":doc.currency, "Amount":doc.grand_total \ if self.purpose == 'SOLD' else 1} } shipment.RequestedShipment.CustomsClearanceDetail.Commodities.append(commodity_dict) elif self.document in CarrierTracking.allowed_docs: total_qty = self.total_handling_units desc = "OTHER PRINTED MATTER, INCLUDING PRINTED PICTURES AND PHOTOGRAPHS TRADE \ ADVERTISING MATERIAL, COMMERCIAL CATALOGUES AND THE LIKE : POSTERS, PRINTED" country_doc = frappe.get_doc("Country", frappe.get_value("Address", self.from_address, "country")) country_code = country_doc.code commodity_dict = { #"Name":row.get("item_code"), "Description": desc[0:30], "Weight": {"Units": self.uom_mapper.get(self.weight_uom), "Value":self.total_weight}, "NumberOfPieces":int(self.total_handling_units), "HarmonizedCode": '49111010', "CountryOfManufacture":country_code, "Quantity":int(total_qty), "QuantityUnits":"EA", "UnitPrice":{"Currency":self.currency, "Amount":(self.amount/total_qty)}, "CustomsValue":{"Currency":self.currency, "Amount":self.amount} } shipment.RequestedShipment.CustomsClearanceDetail.Commodities.append(commodity_dict) total_value = self.amount else: frappe.throw("Currently only Booking Shipment is Available vide {}".format(CarrierTracking.allowed_docs)) total_value = self.amount
def get_employee_details(): return [{"employee": frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "base": 25000, "variable": 5000, "from_date": add_months(nowdate(),-1), "idx": 1 }, {"employee": frappe.get_value("Employee", {"employee_name":"[email protected]"}, "name"), "base": 15000, "variable": 100, "from_date": add_months(nowdate(),-1), "idx": 2 } ]
def create_customer(doc): customer_group = frappe.get_value("Selling Settings", None, "customer_group") territory = frappe.get_value("Selling Settings", None, "territory") if not (customer_group and territory): customer_group = "Commercial" territory = "Rest Of The World" frappe.msgprint(_("Please set default customer group and territory in Selling Settings"), alert=True) customer = frappe.get_doc({"doctype": "Customer", "customer_name": doc.name, "customer_group": customer_group, "territory" : territory, "customer_type": "Individual" }).insert(ignore_permissions=True) frappe.db.set_value("Patient", doc.name, "customer", customer.name) frappe.msgprint(_("Customer {0} is created.").format(customer.name), alert=True)
def set_default_role(doc, method): '''Set customer, supplier, student based on email''' if frappe.flags.setting_role or frappe.flags.in_migrate: return contact_name = frappe.get_value('Contact', dict(email_id=doc.email)) if contact_name: contact = frappe.get_doc('Contact', contact_name) for link in contact.links: frappe.flags.setting_role = True if link.link_doctype=='Customer': doc.add_roles('Customer') elif link.link_doctype=='Supplier': doc.add_roles('Supplier') elif frappe.get_value('Student', dict(student_email_id=doc.email)): doc.add_roles('Student')
def make_sales_invoice(source_name, target_doc=None): attended_by = frappe.get_value("Appointment",source_name,"employee") def postprocess(source, target): set_missing_values(source, target) def set_missing_values(source, target): target.is_pos = 1 target.ignore_pricing_rule = 1 [d.update({"emp":attended_by}) for d in target.get("items")] target.run_method("set_missing_values") doclist = get_mapped_doc("Appointment", source_name, { "Appointment": { "doctype": "Sales Invoice", "field_map": { "starts_on":"posting_date" }, "validation": { "status": ["=", "Confirm"] } }, "Services": { "doctype": "Sales Invoice Item", "field_map": { "item": "item_code" }, "add_if_empty": True } }, target_doc, postprocess) return doclist
def set_missing_values(source, target): target.supplier = for_supplier default_price_list = frappe.get_value("Supplier", for_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 test_if_user_is_added(self): ev = frappe.get_doc({ 'doctype': 'Event', 'subject': 'test event for view logs', 'starts_on': '2018-06-04 14:11:00', 'event_type': 'Public' }).insert() frappe.set_user('[email protected]') from frappe.desk.form.load import getdoc # load the form getdoc('Event', ev.name) a = frappe.get_value( doctype="View Log", filters={ "reference_doctype": "Event", "reference_name": ev.name }, fieldname=['viewed_by'] ) self.assertEqual('[email protected]', a) self.assertNotEqual('[email protected]', a)
def validate_warehouse_account(self): '''If perpetual inventory is set, and warehouse is linked, the account balance and stock balance as of now must always match. ''' from erpnext.accounts.utils import get_balance_on from erpnext.stock.utils import get_stock_value_on if not cint(frappe.defaults.get_global_default("auto_accounting_for_stock")): return if self.account_type == "Stock": if self.is_group == 0 and not self.warehouse: frappe.throw(_("Warehouse is mandatory for non group Accounts of type Stock")) if self.warehouse: # company must be same if frappe.get_value('Warehouse', self.warehouse, 'company') != self.company: frappe.throw(_("Warehouse company must be same as Account company")) # balance must be same stock_balance = get_stock_value_on(self.warehouse) if self.is_new(): account_balance = 0.0 else: account_balance = get_balance_on(self.name) if account_balance != stock_balance: frappe.throw(_('Account balance ({0}) and stock value ({1}) must be same')\ .format(fmt_money(account_balance, currency=self.account_currency), fmt_money(stock_balance, currency=self.account_currency))) elif self.warehouse: self.warehouse = None
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": "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 execute(): ''' Fields to move from the item to item defaults child table [ default_warehouse, buying_cost_center, expense_account, selling_cost_center, income_account ] ''' if not frappe.db.has_column('Item', 'default_warehouse'): return frappe.reload_doc('stock', 'doctype', 'item_default') frappe.reload_doc('stock', 'doctype', 'item') if frappe.db.a_row_exists('Item Default'): return companies = frappe.get_all("Company") if len(companies) == 1: try: frappe.db.sql(''' INSERT INTO `tabItem Default` (name, parent, parenttype, parentfield, idx, company, default_warehouse, buying_cost_center, selling_cost_center, expense_account, income_account, default_supplier) SELECT SUBSTRING(SHA2(name,224), 1, 10) as name, name as parent, 'Item' as parenttype, 'item_defaults' as parentfield, 1 as idx, %s as company, default_warehouse, buying_cost_center, selling_cost_center, expense_account, income_account, default_supplier FROM `tabItem`; ''', companies[0].name) except: pass else: item_details = frappe.get_all("Item", fields=["name", "default_warehouse", "buying_cost_center", "expense_account", "selling_cost_center", "income_account"], limit=100) for item in item_details: item_defaults = [] def insert_into_item_defaults(doc_field_name, doc_field_value, company): for d in item_defaults: if d.get("company") == company: d[doc_field_name] = doc_field_value return item_defaults.append({ "company": company, doc_field_name: doc_field_value }) for d in [ ["default_warehouse", "Warehouse"], ["expense_account", "Account"], ["income_account", "Account"], ["buying_cost_center", "Cost Center"], ["selling_cost_center", "Cost Center"] ]: if item.get(d[0]): company = frappe.get_value(d[1], item.get(d[0]), "company", cache=True) insert_into_item_defaults(d[0], item.get(d[0]), company) doc = frappe.get_doc("Item", item.name) doc.extend("item_defaults", item_defaults) for child_doc in doc.item_defaults: child_doc.db_insert()
def update_item_stock(item_code, shopify_settings, bin=None): item = frappe.get_doc("Item", item_code) if item.sync_qty_with_shopify: if not bin: bin = frappe.get_doc("Bin", {"warehouse": shopify_settings.warehouse, "item_code": item_code}) if bin: if not item.shopify_id and not item.variant_of: sync_item_with_shopify(item, shopify_settings.price_list, shopify_settings.warehouse) if item.sync_with_shopify and item.shopify_id and shopify_settings.warehouse == bin.warehouse: if item.variant_of: item_data, resource = get_product_update_dict_and_resource(frappe.get_value("Item", item.variant_of, "shopify_id"), item.shopify_variant_id) else: item_data, resource = get_product_update_dict_and_resource(item.shopify_id, item.shopify_variant_id) item_data["product"]["variants"][0].update({ "inventory_quantity": cint(bin.actual_qty), "inventory_management": "shopify" }) put_request(resource, item_data)
def get_approvers(doctype, txt, searchfield, start, page_len, filters): if not filters.get("employee"): frappe.throw(_("Please select Employee Record first.")) approvers = [] department_details = {} department_list = [] employee_department = filters.get("department") or frappe.get_value("Employee", filters.get("employee"), "department") if employee_department: department_details = frappe.db.get_value("Department", {"name": employee_department}, ["lft", "rgt"], as_dict=True) if department_details: department_list = frappe.db.sql("""select name from `tabDepartment` where lft <= %s and rgt >= %s and disabled=0 order by lft desc""", (department_details.lft, department_details.rgt), as_list = True) if filters.get("doctype") == "Leave Application": parentfield = "leave_approvers" else: parentfield = "expense_approvers" if department_list: for d in department_list: approvers += frappe.db.sql("""select user.name, user.first_name, user.last_name from tabUser user, `tabDepartment Approver` approver where approver.parent = %s and user.name like %s and approver.parentfield = %s and approver.approver=user.name""",(d, "%" + txt + "%", parentfield), as_list=True) return approvers
def update_order(board_name, order): '''Save the order of cards in columns''' board = frappe.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 = frappe.get_value( doctype, {'name': card}, fieldname ) if column != col_name: frappe.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