示例#1
0
文件: setup.py 项目: ci2014/erpnext
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":"*****@*****.**"}, "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":"*****@*****.**"}, "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":"*****@*****.**"}, "name")
		self.assertTrue(duplicate_declaration.submit)
示例#3
0
	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":"*****@*****.**","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":"*****@*****.**"}))
		self.assertTrue(frappe.get_value("Item",{"woocommerce_id": 56}))
		self.assertTrue(frappe.get_value("Sales Order",{"woocommerce_id":75}))
示例#4
0
	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 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")
示例#6
0
	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("*****@*****.**")
		frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "name"), "date_of_joining", "2013-01-11")
		
		ss = frappe.get_doc("Salary Slip",
			self.make_employee_salary_slip("*****@*****.**"))

		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":"*****@*****.**"}, "name"), "relieving_date", "12-12-2016")
		frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "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":"*****@*****.**"}, "name"), "relieving_date", None)
		frappe.db.set_value("Employee", frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "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 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)
示例#8
0
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 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))
示例#11
0
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)
示例#12
0
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":"*****@*****.**"})
		if not sal_slip:
			sal_slip = make_salary_slip_from_salary_structure(employee=frappe.get_value("Employee", {"employee_name":"*****@*****.**"}))
			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)
示例#14
0
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
示例#15
0
def get_employee_details():
	return [{"employee": frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "name"),
			"base": 25000,
			"variable": 5000,
			"idx": 1
			},
			{"employee": frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "name"),
			 "base": 15000,
			 "variable": 100,
			 "idx": 2
			}
		]
示例#16
0
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
示例#17
0
	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 get_employee_details():
	return [{"employee": frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "name"),
			"base": 25000,
			"variable": 5000,
			"from_date": add_months(nowdate(),-1),
			"idx": 1
			},
			{"employee": frappe.get_value("Employee", {"employee_name":"*****@*****.**"}, "name"),
			 "base": 15000,
			 "variable": 100,
			 "from_date": add_months(nowdate(),-1),
			 "idx": 2
			}
		]
	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
示例#20
0
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')
示例#21
0
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)
示例#22
0
	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('*****@*****.**')

		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('*****@*****.**', a)
		self.assertNotEqual('*****@*****.**', a)
示例#23
0
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
示例#24
0
	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 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()
示例#26
0
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
示例#27
0
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)
示例#28
0
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
示例#29
0
	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
示例#30
0
	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 get_data(filters):
    # prepare columns
    columns = [{
        'fieldname': 'description',
        'fieldtype': 'Data',
        'label': _("Description"),
        'width': 150
    }]

    components = frappe.db.sql("""
        SELECT 
            `name`, 
            `salary_component_abbr` AS `abbr`
        FROM `tabSalary Component`
        WHERE `disabled` = 0
        ORDER BY `type` DESC;""",
                               as_dict=True)

    from_date = frappe.get_value("Fiscal Year", filters.fiscal_year,
                                 "year_start_date")
    to_date = frappe.get_value("Fiscal Year", filters.fiscal_year,
                               "year_end_date")

    # prepare rows
    data = []

    for c in components:
        data.append({'description': c['name'], 'auto': 1, 'total': 0})
    data.append({'description': _("Net Total"), 'auto': 0, 'total': 0})

    salary_slips = frappe.db.sql("""
        SELECT `name` 
        FROM `tabSalary Slip`
        WHERE `docstatus` = 1
          AND `employee` = "{employee}"
          AND `posting_date` >= "{from_date}"
          AND `posting_date` <= "{to_date}"
        ORDER BY `posting_date` ASC;""".format(employee=filters.employee,
                                               from_date=from_date,
                                               to_date=to_date),
                                 as_dict=True)

    for s in range(0, len(salary_slips)):
        salary_slip = frappe.get_doc("Salary Slip", salary_slips[s]['name'])

        # extend columns
        columns.append({
            'fieldname': 'col{0}'.format(s),
            'fieldtype': 'Currency',
            'label': salary_slip.posting_date,
            'width': 90
        })

        for e in salary_slip.earnings:
            for d in data:
                if d['description'] == e.salary_component:
                    d['col{0}'.format(s)] = e.amount
                    d['total'] += e.amount
                    break

        for u in salary_slip.deductions:
            for d in data:
                if d['description'] == u.salary_component:
                    d['col{0}'.format(s)] = (-1) * u.amount
                    d['total'] -= u.amount
                    break

        data[-1]['col{0}'.format(s)] = salary_slip.net_pay
        data[-1]['total'] += salary_slip.net_pay
    # extend columns
    columns.append({
        'fieldname': 'total',
        'fieldtype': 'Currency',
        'label': _("Total"),
        'width': 90
    })

    return columns, data
示例#32
0
 def validate_loan_type(self):
     company = frappe.get_value("Loan Type", self.loan_type, "company")
     if company != self.company:
         frappe.throw(
             _("Please select Loan Type for company {0}").format(
                 frappe.bold(self.company)))
示例#33
0
def get_data(filters):
    if type(filters) is str:
        filters = ast.literal_eval(filters)
    else:
        filters = dict(filters)
    # get additional conditions
    conditions = ""
    if 'stickmaschine' in filters and filters['stickmaschine']:
        conditions += """ AND `tabWork Order`.`stickmaschine` = "{0}" """.format(
            filters['stickmaschine'])
    if 'from_date' in filters and filters['from_date']:
        conditions += """ AND (`tabWork Order`.`planned_start_date` >= '{from_date}' OR `tabWork Order`.`planned_start_date` IS NULL)""".format(
            from_date=filters['from_date'])
    if 'to_date' in filters and filters['to_date']:
        conditions += """ AND (`tabWork Order`.`planned_start_date` <= '{to_date}' OR `tabWork Order`.`planned_start_date` IS NULL)""".format(
            to_date=filters['to_date'])
    if 'item' in filters and filters['item']:
        conditions += """ AND `tabWork Order`.`production_item` LIKE '%{item}%'""".format(
            item=filters['item'])
    if 'sales_order' in filters and filters['sales_order']:
        conditions += """ AND `tabWork Order`.`sales_order` = '{sales_order}'""".format(
            sales_order=filters['sales_order'])
    # get shift hours
    company = frappe.defaults.get_global_default('company')
    hours_per_shift = frappe.get_value('Company', company, 'h_pro_schicht')

    # prepare query
    sql_query = """SELECT
         `tabWork Order`.`name` AS `work_order`,
         IFNULL(`tabWork Order`.`sales_order`, "-") AS `sales_order`,
         `tabWork Order`.`status` AS `status`, 
         IFNULL(`tabSales Order`.`customer`, "-") AS `customer`,
         IFNULL(`tabSales Order`.`customer_name`, "-") AS `customer_name`,
         `tabSales Order`.`delivery_Date` AS `delivery_date`,
         `tabWork Order`.`planned_start_date` AS `start_date`,
         `tabWork Order`.`expected_delivery_date` AS `end_date`,
         `tabWork Order`.`stickmaschine` AS `stickmaschine`,
         `tabWork Order`.`production_item` AS `item`,
         `tabWork Order`.`qty` AS `qty`,
         (SELECT CONCAT(ROUND(`tabSales Order Item`.`anzahl`, 0), " x ", ROUND(`tabSales Order Item`.`verkaufseinheit`, 1), " ", `tabSales Order Item`.`uom`) 
            FROM `tabSales Order Item`
            WHERE `tabSales Order Item`.`item_code` = `tabItem`.`item_code`
              AND `tabSales Order Item`.`parent` = `tabWork Order`.`sales_order`
            LIMIT 1) AS `qty_full`,
         `tabWork Order`.`stock_uom` AS `uom`,
         `tabDessin`.`stickrapport` AS `stickrapport`,
         IFNULL(`tabWork Order`.`stoff`, "-") AS `stoff`,
         IFNULL(`tabWork Order`.`garn`, "-") AS `garn`,
         IFNULL(`tabWork Order`.`pailletten`, "-") AS `pailletten`,
         IFNULL(`tabWork Order`.`monofil`, "-") AS `monofil`,
         IFNULL(`tabWork Order`.`bobinen`, "-") AS `bobinen`,
         IFNULL(`tabWork Order`.`anmerkung`, "-") AS `anmerkung`,
         `tabStickmaschine`.`ktm_per_h` AS `ktm_per_h`,
         `tabStickmaschine`.`next_maintenance_date` AS `next_maintenance_date`,
         `tabDessin`.`gesamtmeter` AS `ktm`,
         (`tabWork Order`.`qty` / `tabStickmaschine`.`m_per_cp`) * `tabDessin`.`gesamtmeter` AS `ktm_total`,
         (((`tabWork Order`.`qty` / `tabStickmaschine`.`m_per_cp`) * `tabDessin`.`gesamtmeter`) / IFNULL(`tabStickmaschine`.`ktm_per_h`, 1)) AS `h_total`,
         ((((`tabWork Order`.`qty` / `tabStickmaschine`.`m_per_cp`) * `tabDessin`.`gesamtmeter`) / IFNULL(`tabStickmaschine`.`ktm_per_h`, 1)) / {hours_per_shift}) AS `schicht`,
         IF (`tabWork Order`.`status` = 'In Process', '-', 
          (SELECT 
           IF(SUM(IF(`tWOI`.`required_qty` <= (`tWOI`.`available_qty_at_source_warehouse` + `tWOI`.`available_qty_at_wip_warehouse`), 1, 0)) / COUNT(`tWOI`.`item_code`) = 1, "<span style='color:green;'>&cir; OK</span>", "<span style='color: red;'>&squf; NOK</span>")
           FROM `tabWork Order Item` AS `tWOI`
           WHERE `tWOI`.`parent` = `tabWork Order`.`name`)) AS `ready`
        FROM `tabWork Order`
        LEFT JOIN `tabItem` ON `tabItem`.`item_code` = `tabWork Order`.`production_item`
        LEFT JOIN `tabDessin` ON `tabDessin`.`name` = `tabItem`.`dessin`
        LEFT JOIN `tabSales Order` ON `tabSales Order`.`name` = `tabWork Order`.`sales_order`
        LEFT JOIN `tabStickmaschine` ON `tabWork Order`.`stickmaschine` = `tabStickmaschine`.`name`
        WHERE 
          `tabWork Order`.`docstatus` < 2
          AND `tabWork Order`.`status` NOT IN ("Completed", "Stopped")
          {conditions}
        ORDER BY `tabWork Order`.`stickmaschine` ASC, `tabWork Order`.`planned_start_date` ASC, `tabWork Order`.`expected_delivery_date` ASC;
      """.format(conditions=conditions, hours_per_shift=hours_per_shift)

    data = frappe.db.sql(sql_query, as_dict=1)

    # compute indent
    previous_so = None
    row_idx = 0
    header_row_idx = 0
    for row in data:
        if row['sales_order'] == previous_so:
            row['indent'] = 1
        else:
            row['indent'] = 0
            header_row_idx = row_idx
        previous_so = row['sales_order']
        row_idx += 1

        # mark material status
        if "NOK" in row['ready']:
            if "background" not in data[header_row_idx]['ready']:
                data[header_row_idx][
                    'ready'] = "<span style='background-color: yellow; '>{0}</span>".format(
                        data[header_row_idx]['ready'])
    return data
示例#34
0
def execute():

	# Create a penalty account for loan types

	frappe.reload_doc('loan_management', 'doctype', 'loan_type')
	frappe.reload_doc('loan_management', 'doctype', 'loan')
	frappe.reload_doc('loan_management', 'doctype', 'repayment_schedule')
	frappe.reload_doc('loan_management', 'doctype', 'process_loan_interest_accrual')
	frappe.reload_doc('loan_management', 'doctype', 'loan_repayment')
	frappe.reload_doc('loan_management', 'doctype', 'loan_repayment_detail')
	frappe.reload_doc('loan_management', 'doctype', 'loan_interest_accrual')
	frappe.reload_doc('accounts', 'doctype', 'gl_entry')
	frappe.reload_doc('accounts', 'doctype', 'journal_entry_account')

	updated_loan_types = []
	loans_to_close = []

	# Update old loan status as closed
	if frappe.db.has_column('Repayment Schedule', 'paid'):
		loans_list = frappe.db.sql("""SELECT distinct parent from `tabRepayment Schedule`
			where paid = 0 and docstatus = 1""", as_dict=1)

		loans_to_close = [d.parent for d in loans_list]

	if loans_to_close:
		frappe.db.sql("UPDATE `tabLoan` set status = 'Closed' where name not in (%s)" % (', '.join(['%s'] * len(loans_to_close))), tuple(loans_to_close))

	loans = frappe.get_all('Loan', fields=['name', 'loan_type', 'company', 'status', 'mode_of_payment',
		'applicant_type', 'applicant', 'loan_account', 'payment_account', 'interest_income_account'],
		filters={'docstatus': 1, 'status': ('!=', 'Closed')})

	for loan in loans:
		# Update details in Loan Types and Loan
		loan_type_company = frappe.db.get_value('Loan Type', loan.loan_type, 'company')
		loan_type = loan.loan_type

		group_income_account = frappe.get_value('Account', {'company': loan.company,
			'is_group': 1, 'root_type': 'Income', 'account_name': _('Indirect Income')})

		if not group_income_account:
			group_income_account = frappe.get_value('Account', {'company': loan.company,
				'is_group': 1, 'root_type': 'Income'})

		penalty_account = create_account(company=loan.company, account_type='Income Account',
			account_name='Penalty Account', parent_account=group_income_account)

		# Same loan type used for multiple companies
		if loan_type_company and loan_type_company != loan.company:
			# get loan type for appropriate company
			loan_type_name = frappe.get_value('Loan Type', {'company': loan.company,
				'mode_of_payment': loan.mode_of_payment, 'loan_account': loan.loan_account,
				'payment_account': loan.payment_account, 'interest_income_account': loan.interest_income_account,
				'penalty_income_account': loan.penalty_income_account}, 'name')

			if not loan_type_name:
				loan_type_name = create_loan_type(loan, loan_type_name, penalty_account)

			# update loan type in loan
			frappe.db.sql("UPDATE `tabLoan` set loan_type = %s where name = %s", (loan_type_name,
				loan.name))

			loan_type = loan_type_name
			if loan_type_name not in updated_loan_types:
				updated_loan_types.append(loan_type_name)

		elif not loan_type_company:
			loan_type_doc = frappe.get_doc('Loan Type', loan.loan_type)
			loan_type_doc.is_term_loan = 1
			loan_type_doc.company = loan.company
			loan_type_doc.mode_of_payment = loan.mode_of_payment
			loan_type_doc.payment_account = loan.payment_account
			loan_type_doc.loan_account = loan.loan_account
			loan_type_doc.interest_income_account = loan.interest_income_account
			loan_type_doc.penalty_income_account = penalty_account
			loan_type_doc.submit()
			updated_loan_types.append(loan.loan_type)
			loan_type = loan.loan_type

		if loan_type in updated_loan_types:
			if loan.status == 'Fully Disbursed':
				status = 'Disbursed'
			elif loan.status == 'Repaid/Closed':
				status = 'Closed'
			else:
				status = loan.status

			frappe.db.set_value('Loan', loan.name, {
				'is_term_loan': 1,
				'penalty_income_account': penalty_account,
				'status': status
			})

			process_loan_interest_accrual_for_term_loans(posting_date=nowdate(), loan_type=loan_type,
				loan=loan.name)


			if frappe.db.has_column('Repayment Schedule', 'paid'):
				total_principal, total_interest = frappe.db.get_value('Repayment Schedule', {'paid': 1, 'parent': loan.name},
					['sum(principal_amount) as total_principal', 'sum(interest_amount) as total_interest'])

				accrued_entries = get_accrued_interest_entries(loan.name)
				for entry in accrued_entries:
					interest_paid = 0
					principal_paid = 0

					if total_interest > entry.interest_amount:
						interest_paid = entry.interest_amount
					else:
						interest_paid = total_interest

					if total_principal > entry.payable_principal_amount:
						principal_paid = entry.payable_principal_amount
					else:
						principal_paid = total_principal

					frappe.db.sql(""" UPDATE `tabLoan Interest Accrual`
						SET paid_principal_amount = `paid_principal_amount` + %s,
							paid_interest_amount = `paid_interest_amount` + %s
						WHERE name = %s""",
						(principal_paid, interest_paid, entry.name))

					total_principal -= principal_paid
					total_interest -= interest_paid
示例#35
0
def get_default_customer():
    customer = frappe.get_value('ERPNextSwiss Settings',
                                'ERPNextSwiss Settings', 'default_customer')
    return {'customer': customer or ""}
示例#36
0
def get_duration(appointment_type):
    duration = frappe.get_value("Appointment Type", appointment_type,
                                "default_duration")
    return duration
示例#37
0
def create_journal_entry_bts(bank_transaction_name,
                             reference_number=None,
                             reference_date=None,
                             posting_date=None,
                             entry_type=None,
                             second_account=None,
                             mode_of_payment=None,
                             party_type=None,
                             party=None,
                             allow_edit=None):
    # Create a new journal entry based on the bank transaction
    bank_transaction = frappe.db.get_values(
        "Bank Transaction",
        bank_transaction_name,
        fieldname=["name", "deposit", "withdrawal", "bank_account"],
        as_dict=True)[0]
    company_account = frappe.get_value("Bank Account",
                                       bank_transaction.bank_account,
                                       "account")
    account_type = frappe.db.get_value("Account", second_account,
                                       "account_type")
    if account_type in ["Receivable", "Payable"]:
        if not (party_type and party):
            frappe.throw(
                _("Party Type and Party is required for Receivable / Payable account {0}"
                  ).format(second_account))
    accounts = []
    # Multi Currency?
    accounts.append({
        "account":
        second_account,
        "credit_in_account_currency":
        bank_transaction.deposit if bank_transaction.deposit > 0 else 0,
        "debit_in_account_currency":
        bank_transaction.withdrawal if bank_transaction.withdrawal > 0 else 0,
        "party_type":
        party_type,
        "party":
        party,
    })

    accounts.append({
        "account":
        company_account,
        "bank_account":
        bank_transaction.bank_account,
        "credit_in_account_currency":
        bank_transaction.withdrawal if bank_transaction.withdrawal > 0 else 0,
        "debit_in_account_currency":
        bank_transaction.deposit if bank_transaction.deposit > 0 else 0,
    })

    company = frappe.get_value("Account", company_account, "company")

    journal_entry_dict = {
        "voucher_type": entry_type,
        "company": company,
        "posting_date": posting_date,
        "cheque_date": reference_date,
        "cheque_no": reference_number,
        "mode_of_payment": mode_of_payment
    }
    journal_entry = frappe.new_doc('Journal Entry')
    journal_entry.update(journal_entry_dict)
    journal_entry.set("accounts", accounts)

    if allow_edit:
        return journal_entry

    journal_entry.insert()
    journal_entry.submit()

    if bank_transaction.deposit > 0:
        paid_amount = bank_transaction.deposit
    else:
        paid_amount = bank_transaction.withdrawal

    vouchers = json.dumps([{
        "payment_doctype": "Journal Entry",
        "payment_name": journal_entry.name,
        "amount": paid_amount
    }])

    return reconcile_vouchers(bank_transaction.name, vouchers)
示例#38
0
 def create_item(self):
     # create new item
     new_item = frappe.get_doc({
         'doctype': 'Item',
         'item_name': self.bezeichnung,
         'item_code': self.name,
         'item_group': 'Stickereien',
         'is_stock_item': 1,
         'stock_uom': 'm',
         'dessin': self.dessin,
         'bemusterung': self.name,
         'farbe': self.farbe,
         'komposition': self.komposition,
         'pflegesymbole': self.pflegesymbole,
         'stoffbreite_von': self.stoffbreite_von,
         'stoffbreite_bis': self.stoffbreite_bis,
         'fertigbreite_von': self.fertigbreite_von,
         'fertigbreite_bis': self.fertigbreite_bis,
         'country_of_origin': self.country_of_origin,
         'customs_tariff_number': self.customs_tariff_number,
         't_min_menge': self.minimalmenge,
         'weight_uom': 'g',
         'weight_per_unit': (self.gewicht * 1000),
         'gewicht': (self.gewicht * 1000),
         'is_sales_item': 1,
         'd_stoffe': self.d_stoffe,
         'd_pailletten': self.d_pailletten,
         'd_applikationen': self.d_applikationen,
         'd_prints': self.d_prints
     })
     for k in self.komposition:
         row = new_item.append('komposition', {
             'anteil': k.anteil,
             'material': k.material
         })
     for p in self.pflegesymbole:
         row = new_item.append('pflegesymbole',
                               {'pflegesymbol': p.pflegesymbol})
     for s in self.stickmaschine:
         row = new_item.append('stickmaschine',
                               {'stickmaschine': s.stickmaschine})
     # set default warehouse
     if "Nigeria" in (self.kollektion or ""):
         row = new_item.append('item_defaults',
                               {'default_warehouse': "Africa Shop - HOH"})
     else:
         row = new_item.append(
             'item_defaults',
             {'default_warehouse': "Fertigerzeugnisse - HOH"})
     # insert
     item = new_item.insert()
     # create new item price record
     price_list = frappe.get_value("Selling Settings", "Selling Settings",
                                   "selling_price_list")
     new_item_price = frappe.get_doc({
         'doctype': 'Item Price',
         'item_code': item.item_code,
         'uom': 'm',
         'price_list': price_list,
         'price_list_rate': self.rate
     })
     new_item_price.insert()
     # create new BOM
     new_bom = frappe.get_doc({
         'doctype': 'BOM',
         'item': item.item_code,
         'quantity': 1,
         'is_active': 1,
         'is_default': 1,
         'allow_same_item_multiple_times': 1,
         'uom': new_item.stock_uom
     })
     for i in self.items:
         row = new_bom.append(
             'items', {
                 'item_code': i.item_code,
                 'qty': i.qty,
                 'uom': i.stock_uom,
                 'rate': i.valuation_rate
             })
     bom = new_bom.insert()
     bom.submit()  # auto submit BOM
     # create reference
     self.item = item.name
     self.save()
     # write changes
     frappe.db.commit()
     # return item code
     return item.name
示例#39
0
	def get_name_based_on_parent_folder(self):
		if self.folder:
			path = get_breadcrumbs(self.folder)
			folder_name = frappe.get_value("File", self.folder, "file_name")
			return "/".join([d.file_name for d in path] + [folder_name, self.file_name])
示例#40
0
def _get_party_details(party=None,
                       account=None,
                       party_type="Customer",
                       company=None,
                       posting_date=None,
                       bill_date=None,
                       price_list=None,
                       currency=None,
                       doctype=None,
                       ignore_permissions=False,
                       fetch_payment_terms_template=True,
                       party_address=None,
                       company_address=None,
                       shipping_address=None,
                       pos_profile=None):
    party_details = frappe._dict(
        set_account_and_due_date(party, account, party_type, company,
                                 posting_date, bill_date, doctype))
    party = party_details[party_type.lower()]

    if not ignore_permissions and not (
            frappe.has_permission(party_type, "read", party)
            or frappe.has_permission(party_type, "select", party)):
        frappe.throw(
            _("Not permitted for {0}").format(party), frappe.PermissionError)

    party = frappe.get_doc(party_type, party)
    currency = party.default_currency if party.get(
        "default_currency") else get_company_currency(company)

    party_address, shipping_address = set_address_details(
        party_details, party, party_type, doctype, company, party_address,
        company_address, shipping_address)
    set_contact_details(party_details, party, party_type)
    set_other_values(party_details, party, party_type)
    set_price_list(party_details, party, party_type, price_list, pos_profile)

    party_details["tax_category"] = get_address_tax_category(
        party.get("tax_category"), party_address,
        shipping_address if party_type != "Supplier" else party_address)

    if not party_details.get("taxes_and_charges"):
        party_details["taxes_and_charges"] = set_taxes(
            party.name,
            party_type,
            posting_date,
            company,
            customer_group=party_details.customer_group,
            supplier_group=party_details.supplier_group,
            tax_category=party_details.tax_category,
            billing_address=party_address,
            shipping_address=shipping_address)

    if fetch_payment_terms_template:
        party_details["payment_terms_template"] = get_payment_terms_template(
            party.name, party_type, company)

    if not party_details.get("currency"):
        party_details["currency"] = currency

    # sales team
    if party_type == "Customer":
        party_details["sales_team"] = [{
            "sales_person":
            d.sales_person,
            "allocated_percentage":
            d.allocated_percentage or None
        } for d in party.get("sales_team")]

    # supplier tax withholding category
    if party_type == "Supplier" and party:
        party_details["supplier_tds"] = frappe.get_value(
            party_type, party.name, "tax_withholding_category")

    return party_details
示例#41
0
def make_lab_test():
	physician = get_random("Physician")
	patient = get_random("Patient")
	patient_sex = frappe.get_value("Patient", patient, "sex")
	template = get_random("Lab Test Template")
	set_lab_test(patient, patient_sex, physician, template)
示例#42
0
def make_stock_entry(**args):
    '''Helper function to make a Stock Entry

	:item_code: Item to be moved
	:qty: Qty to be moved
	:company: Company Name (optional)
	:from_warehouse: Optional
	:to_warehouse: Optional
	:rate: Optional
	:serial_no: Optional
	:batch_no: Optional
	:posting_date: Optional
	:posting_time: Optional
	:purpose: Optional
	:do_not_save: Optional flag
	:do_not_submit: Optional flag
	'''
    def process_serial_numbers(serial_nos_list):
        serial_nos_list = [
            '\n'.join(serial_num['serial_no'] for serial_num in serial_nos_list
                      if serial_num.serial_no)
        ]

        uniques = list(set(serial_nos_list[0].split('\n')))

        return '\n'.join(uniques)

    s = frappe.new_doc("Stock Entry")
    args = frappe._dict(args)

    if args.posting_date or args.posting_time:
        s.set_posting_time = 1

    if args.posting_date:
        s.posting_date = args.posting_date
    if args.posting_time:
        s.posting_time = args.posting_time
    if args.inspection_required:
        s.inspection_required = args.inspection_required

    # map names
    if args.from_warehouse:
        args.source = args.from_warehouse
    if args.to_warehouse:
        args.target = args.to_warehouse
    if args.item_code:
        args.item = args.item_code
    if args.apply_putaway_rule:
        s.apply_putaway_rule = args.apply_putaway_rule

    if isinstance(args.qty, string_types):
        if '.' in args.qty:
            args.qty = flt(args.qty)
        else:
            args.qty = cint(args.qty)

    # purpose
    if not args.purpose:
        if args.source and args.target:
            s.purpose = "Material Transfer"
        elif args.source:
            s.purpose = "Material Issue"
        else:
            s.purpose = "Material Receipt"
    else:
        s.purpose = args.purpose

    # company
    if not args.company:
        if args.source:
            args.company = frappe.db.get_value('Warehouse', args.source,
                                               'company')
        elif args.target:
            args.company = frappe.db.get_value('Warehouse', args.target,
                                               'company')

    # set vales from test
    if frappe.flags.in_test:
        if not args.company:
            args.company = '_Test Company'
        if not args.item:
            args.item = '_Test Item'

    s.company = args.company or erpnext.get_default_company()
    s.purchase_receipt_no = args.purchase_receipt_no
    s.delivery_note_no = args.delivery_note_no
    s.sales_invoice_no = args.sales_invoice_no
    s.is_opening = args.is_opening or "No"
    if not args.cost_center:
        args.cost_center = frappe.get_value('Company', s.company,
                                            'cost_center')

    if not args.expense_account and s.is_opening == "No":
        args.expense_account = frappe.get_value('Company', s.company,
                                                'stock_adjustment_account')

    # We can find out the serial number using the batch source document
    serial_number = args.serial_no

    if not args.serial_no and args.qty and args.batch_no:
        serial_number_list = frappe.get_list(doctype='Stock Ledger Entry',
                                             fields=['serial_no'],
                                             filters={
                                                 'batch_no': args.batch_no,
                                                 'warehouse':
                                                 args.from_warehouse
                                             })
        serial_number = process_serial_numbers(serial_number_list)

    args.serial_no = serial_number

    s.append(
        "items", {
            "item_code": args.item,
            "s_warehouse": args.source,
            "t_warehouse": args.target,
            "qty": args.qty,
            "basic_rate": args.rate or args.basic_rate,
            "conversion_factor": args.conversion_factor or 1.0,
            "transfer_qty": flt(args.qty) *
            (flt(args.conversion_factor) or 1.0),
            "serial_no": args.serial_no,
            'batch_no': args.batch_no,
            'cost_center': args.cost_center,
            'expense_account': args.expense_account
        })

    s.set_stock_entry_type()
    if not args.do_not_save:
        s.insert()
        if not args.do_not_submit:
            s.submit()
    return s
示例#43
0
def validate_work_order(work_order):
    if flt(work_order.min_work_ord_qty) > flt(work_order.qty):
        frappe.throw("Minimum Work Order Qty Should " +
                     flt(work_order.min_work_ord_qty))
    if work_order.category and work_order.category == "Assembly" and int(
            work_order.qty) != 1:
        frappe.throw("For Assembly Qty To Manufacture must be 1")
    bom_qty = frappe.db.get_value("BOM", work_order.bom_no, "quantity")
    for raw in work_order.operations:
        setup_time = frappe.get_value("BOM Operation", {
            "parent": raw.bom,
            "operation": raw.operation
        }, "setup_time")
        pni_programme_cycle_time = frappe.get_value(
            "BOM Operation", {
                "parent": raw.bom,
                "operation": raw.operation
            }, "pni_programme_cycle_time")
        time_in_mins = frappe.get_value("BOM Operation", {
            "parent": raw.bom,
            "operation": raw.operation
        }, "time_in_mins")
        raw.setup_time = setup_time
        raw.pni_programme_cycle_time = pni_programme_cycle_time
        raw.time_in_mins = (flt(pni_programme_cycle_time) *
                            flt(work_order.qty)) + flt(setup_time)

        raw.instructions_wo = frappe.get_value("BOM Operation", {
            "parent": raw.bom,
            "operation": raw.operation
        }, "instructions")
    update_time(work_order)
    if work_order.keep_closed and work_order.status != "Stopped":
        frappe.throw("Can't be open this Work Order")
    if not work_order.pni_work_order_operations and work_order.bom_no:
        bom_doc = frappe.get_doc("BOM", work_order.bom_no)
        for raw in bom_doc.pni_bom_operation:
            work_order.append(
                "pni_work_order_operations", {
                    "operation1": raw.operation1,
                    "workstation1": raw.workstation1,
                    "description1": raw.description1,
                    "department1": raw.department1,
                    "hour_rate1": raw.hour_rate1,
                    "setup_time1": raw.setup_time1,
                    "pni_programme_cycle_time1": raw.pni_programme_cycle_time1,
                    "time_in_mins1": raw.time_in_mins1,
                    "batch_size1": raw.batch_size1,
                    "operating_cost1": raw.operating_cost1,
                    "base_hour_rate1": raw.base_hour_rate1,
                    "base_operating_cost1": raw.base_operating_cost1,
                    "image1": raw.image1,
                    "source_warehouse1": raw.source_warehouse1,
                    "target_warehouse1": raw.target_warehouse1,
                    "instruction": raw.instruction,
                    "bom": bom_doc.name,
                    "setup_rejection_qty": raw.setup_rejection_qty,
                    "rework_qty": raw.rework_qty,
                    "completed_qty": raw.completed_qty
                })
    for raw in work_order.pni_work_order_operations:
        raw.time_in_mins1 = (flt(raw.pni_programme_cycle_time1) *
                             flt(work_order.qty)) + flt(raw.setup_time1)
示例#44
0
    def test_serial_no_based_delivery(self):
        frappe.set_value("Stock Settings", None,
                         "automatically_set_serial_nos_based_on_fifo", 1)
        from erpnext.stock.doctype.item.test_item import make_item
        item = make_item(
            "_Reserved_Serialized_Item", {
                "is_stock_item":
                1,
                "maintain_stock":
                1,
                "has_serial_no":
                1,
                "serial_no_series":
                "SI.####",
                "valuation_rate":
                500,
                "item_defaults": [{
                    "default_warehouse": "_Test Warehouse - _TC",
                    "company": "_Test Company"
                }]
            })
        frappe.db.sql("""delete from `tabSerial No` where item_code=%s""",
                      (item.item_code))
        make_item(
            "_Test Item A", {
                "maintain_stock":
                1,
                "valuation_rate":
                100,
                "item_defaults": [{
                    "default_warehouse": "_Test Warehouse - _TC",
                    "company": "_Test Company"
                }]
            })
        make_item(
            "_Test Item B", {
                "maintain_stock":
                1,
                "valuation_rate":
                200,
                "item_defaults": [{
                    "default_warehouse": "_Test Warehouse - _TC",
                    "company": "_Test Company"
                }]
            })
        from erpnext.manufacturing.doctype.production_plan.test_production_plan import make_bom
        make_bom(item=item.item_code,
                 rate=1000,
                 raw_materials=['_Test Item A', '_Test Item B'])

        so = make_sales_order(
            **{
                "item_list": [{
                    "item_code": item.item_code,
                    "ensure_delivery_based_on_produced_serial_no": 1,
                    "qty": 1,
                    "rate": 1000
                }]
            })
        so.submit()
        from erpnext.manufacturing.doctype.work_order.test_work_order import \
         make_wo_order_test_record
        work_order = make_wo_order_test_record(item=item.item_code,
                                               qty=1,
                                               do_not_save=True)
        work_order.fg_warehouse = "_Test Warehouse - _TC"
        work_order.sales_order = so.name
        work_order.submit()
        make_stock_entry(item_code=item.item_code,
                         target="_Test Warehouse - _TC",
                         qty=1)
        item_serial_no = frappe.get_doc("Serial No",
                                        {"item_code": item.item_code})
        from erpnext.manufacturing.doctype.work_order.work_order import \
         make_stock_entry as make_production_stock_entry
        se = frappe.get_doc(
            make_production_stock_entry(work_order.name, "Manufacture", 1))
        se.submit()
        reserved_serial_no = se.get("items")[2].serial_no
        serial_no_so = frappe.get_value("Serial No", reserved_serial_no,
                                        "sales_order")
        self.assertEqual(serial_no_so, so.name)
        dn = make_delivery_note(so.name)
        dn.save()
        self.assertEqual(reserved_serial_no, dn.get("items")[0].serial_no)
        item_line = dn.get("items")[0]
        item_line.serial_no = item_serial_no.name
        self.assertRaises(frappe.ValidationError, dn.submit)
        item_line = dn.get("items")[0]
        item_line.serial_no = reserved_serial_no
        self.assertTrue(dn.submit)
        dn.load_from_db()
        dn.cancel()
        si = make_sales_invoice(so.name)
        si.update_stock = 1
        si.save()
        self.assertEqual(si.get("items")[0].serial_no, reserved_serial_no)
        item_line = si.get("items")[0]
        item_line.serial_no = item_serial_no.name
        self.assertRaises(frappe.ValidationError, dn.submit)
        item_line = si.get("items")[0]
        item_line.serial_no = reserved_serial_no
        self.assertTrue(si.submit)
        si.submit()
        si.load_from_db()
        si.cancel()
        si = make_sales_invoice(so.name)
        si.update_stock = 0
        si.submit()
        from erpnext.accounts.doctype.sales_invoice.sales_invoice import \
         make_delivery_note as make_delivery_note_from_invoice
        dn = make_delivery_note_from_invoice(si.name)
        dn.save()
        dn.submit()
        self.assertEqual(dn.get("items")[0].serial_no, reserved_serial_no)
        dn.load_from_db()
        dn.cancel()
        si.load_from_db()
        si.cancel()
        se.load_from_db()
        se.cancel()
        self.assertFalse(
            frappe.db.exists("Serial No", {"sales_order": so.name}))
示例#45
0
def create_payment_entry_bts(bank_transaction_name,
                             reference_number=None,
                             reference_date=None,
                             party_type=None,
                             party=None,
                             posting_date=None,
                             mode_of_payment=None,
                             project=None,
                             cost_center=None,
                             allow_edit=None):
    # Create a new payment entry based on the bank transaction
    bank_transaction = frappe.db.get_values(
        "Bank Transaction",
        bank_transaction_name,
        fieldname=["name", "unallocated_amount", "deposit", "bank_account"],
        as_dict=True)[0]
    paid_amount = bank_transaction.unallocated_amount
    payment_type = "Receive" if bank_transaction.deposit > 0 else "Pay"

    company_account = frappe.get_value("Bank Account",
                                       bank_transaction.bank_account,
                                       "account")
    company = frappe.get_value("Account", company_account, "company")
    payment_entry_dict = {
        "company": company,
        "payment_type": payment_type,
        "reference_no": reference_number,
        "reference_date": reference_date,
        "party_type": party_type,
        "party": party,
        "posting_date": posting_date,
        "paid_amount": paid_amount,
        "received_amount": paid_amount
    }
    payment_entry = frappe.new_doc("Payment Entry")

    payment_entry.update(payment_entry_dict)

    if mode_of_payment:
        payment_entry.mode_of_payment = mode_of_payment
    if project:
        payment_entry.project = project
    if cost_center:
        payment_entry.cost_center = cost_center
    if payment_type == "Receive":
        payment_entry.paid_to = company_account
    else:
        payment_entry.paid_from = company_account

    payment_entry.validate()

    if allow_edit:
        return payment_entry

    payment_entry.insert()

    payment_entry.submit()
    vouchers = json.dumps([{
        "payment_doctype": "Payment Entry",
        "payment_name": payment_entry.name,
        "amount": paid_amount
    }])
    return reconcile_vouchers(bank_transaction.name, vouchers)
示例#46
0
    def validate(self):

        unit_pcost = 0
        total_time = 0
        unit_acost = 0
        self.master_item = frappe.get_value("BOM", self.master_bom, "item")
        self.description = frappe.get_value("Item", self.master_item,
                                            "description")
        self.currency = frappe.get_value("Company", self.company,
                                         "default_currency")

        bom_doc = frappe.get_doc("BOM", self.master_bom)

        item_list = []

        for purchased in self.items:
            item_list.append(purchased.item)

        for exp_item in bom_doc.exploded_items:
            if not exp_item.item_code in item_list:

                doc = frappe.new_doc("BOM Costing Purchased Item", bom_doc,
                                     "items")
                doc.item = exp_item.item_code
                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 = exp_item.description
                doc.item_name = exp_item.item_name
                doc.qty_per_asm = exp_item.qty
                doc.idx = None
                self.append("items", doc)

        for purchased in self.items:
            purchased.qty = self.quantity * purchased.qty_per_asm
            purchased.purchase_rate = get_item_price(purchased, self.company)
            if not purchased.taxes:
                purchased.taxes = 0
            if not purchased.freight:
                purchased.freight = 0

            fields = ["purchase_rate", "taxes", "freight"]
            from_currency = purchased.currency
            to_currency = self.currency
            conversion_rate = get_exchange_rate(from_currency, to_currency)
            if not conversion_rate:
                conversion_rate = 0
            #frappe.msgprint(conversion_rate)
            for f in fields:

                val = flt(
                    flt(purchased.get(f), purchased.precision(f)) *
                    conversion_rate, purchased.precision("base_" + f))
                purchased.set("base_" + f, val)

            purchased.unit_price = purchased.purchase_rate + purchased.taxes + purchased.freight
            purchased.base_unit_price = purchased.base_purchase_rate + purchased.base_taxes + purchased.base_freight
            purchased.total_price = purchased.base_unit_price * purchased.qty_per_asm
            unit_pcost = unit_pcost + (purchased.base_unit_price *
                                       purchased.qty_per_asm)

        bom_list = [self.master_bom]
        bom_list = get_boms_list(self.master_bom, bom_list)

        bom_operations = []
        for bo in self.operations:
            bom_operations.append(bo.bom)

            if bo.bom in bom_list:
                #Update the BOM operation
                child_operation = get_bom_operation(bo.bom)
                bo.minutes = child_operation.minutes
                bo.num_operators = child_operation.num_operators
                bo.total_cost = child_operation.total_cost
                bo.operations = child_operation.operations

        for boma in bom_list:
            if not boma in bom_operations:

                child_operation = get_bom_operation(boma)
                self.append("operations", child_operation)

        for ops in self.operations:
            total_time = total_time + ops.minutes
            unit_acost = unit_acost + ops.total_cost

        self.assembly_time = total_time
        self.assembly_cost = unit_acost

        self.purchased_cost = unit_pcost
        self.unit_cost = self.purchased_cost + self.assembly_cost
        self.total_cost = self.quantity * self.unit_cost
示例#47
0
def get_payable_account(company=None):
    if not company:
        company = get_first_company()
    account = frappe.get_value('Company', company, 'default_payable_account')
    return {'account': account or ""}
示例#48
0
def make_payment_entry(method="callback", **kwargs):
    for key, value in kwargs.items():
        nmb_doc = value
        doc_info = get_fee_info(nmb_doc.reference)
        accounts = get_fees_default_accounts(doc_info["company"])

        nmb_amount = flt(nmb_doc.amount)
        frappe.flags.ignore_account_permission = True
        if doc_info["doctype"] == "Fees":
            if method == "callback":
                frappe.set_user("Administrator")
            fees_name = doc_info["name"]
            bank_reference = frappe.get_value("Fees", fees_name,
                                              "bank_reference")
            if bank_reference == nmb_doc.reference:
                payment_entry = get_payment_entry("Fees",
                                                  fees_name,
                                                  party_amount=nmb_amount)
                payment_entry.update({
                    "reference_no":
                    nmb_doc.reference,
                    "reference_date":
                    nmb_doc.timestamp,
                    "remarks":
                    "Payment Entry against {0} {1} via NMB Bank Payment {2}".
                    format("Fees", fees_name, nmb_doc.reference),
                    "paid_to":
                    accounts["bank"],
                })
                payment_entry.flags.ignore_permissions = True
                # payment_entry.references = []
                # payment_entry.set_missing_values()
                payment_entry.save()
                payment_entry.submit()
            return nmb_doc

        elif doc_info["doctype"] == "Student Applicant Fees":
            doc = frappe.get_doc("Student Applicant Fees", doc_info["name"])
            if not doc.callback_token == nmb_doc.fees_token:
                return
            # Below remarked after introducing VFD in AV solutions
            # jl_rows = []
            # debit_row = dict(
            #     account=accounts["bank"],
            #     debit_in_account_currency=nmb_amount,
            #     account_currency=accounts["currency"],
            #     cost_center=doc.cost_center,
            # )
            # jl_rows.append(debit_row)

            # credit_row_1 = dict(
            #     account=accounts["income"],
            #     credit_in_account_currency=nmb_amount,
            #     account_currency=accounts["currency"],
            #     cost_center=doc.cost_center,
            # )
            # jl_rows.append(credit_row_1)

            # user_remark = (
            #     "Journal Entry against {0} {1} via NMB Bank Payment {2}".format(
            #         "Student Applicant Fees", doc_info["name"], nmb_doc.reference
            #     )
            # )
            # jv_doc = frappe.get_doc(
            #     dict(
            #         doctype="Journal Entry",
            #         posting_date=nmb_doc.timestamp,
            #         accounts=jl_rows,
            #         company=doc.company,
            #         multi_currency=0,
            #         user_remark=user_remark,
            #     )
            # )

            # jv_doc.flags.ignore_permissions = True
            # frappe.flags.ignore_account_permission = True
            # jv_doc.save()
            # jv_doc.submit()
            # jv_url = frappe.utils.get_url_to_form(jv_doc.doctype, jv_doc.name)
            # si_msgprint = "Journal Entry Created <a href='{0}'>{1}</a>".format(
            #     jv_url, jv_doc.name
            # )
            # frappe.msgprint(_(si_msgprint))
            frappe.db.set_value("Student Applicant", doc.student,
                                "application_status", "Approved")
            return nmb_doc
示例#49
0
def get_context(context):
	"""This is a controller extension for erpnext.templates.pages.cart"""

	context["no_cache"] = 1

	settings = frappe.db.get("Awc Settings")
	awc_session = get_awc_session()
	customer = get_current_customer()

	context["countries"] = [ x for x in frappe.get_list("Country", fields=["country_name", "name"], ignore_permissions=1) ]

	default_country = frappe.get_value("System Settings", "System Settings", "country")
	default_country_doc = next((x for x in context["countries"] if x.name == default_country), None)

	if frappe.session.user != "Guest":
		address_links = frappe.get_all("Dynamic Link", filters={"link_name" : customer.name}, fields=["parent"])
		addresses = []
		for address in address_links:
			addresses.extend(frappe.get_all("Address", filters={"name" : address.parent, "disabled" : False}, fields="*"))
		context['addresses'] = addresses

		customer_info = frappe.db.get_values("Customer", customer.name, ["has_shipping_account", "fedex_account_number"])[0]
		context["customer_info"] = {
			"has_shipping_acc": customer_info[0],
			"fedex_acc_number": customer_info[1]
		}

	country_idx = context["countries"].index(default_country_doc)
	context["countries"].pop(country_idx)
	context["countries"] = [default_country_doc] + context["countries"]

	context["shipping_rate_api"] = frappe.get_hooks("shipping_rate_api")[0]
	context["selected_customer"] = awc_session.get("selected_customer")

	# ensures clearing address and method selection when visiting checkout page as
	# shipping address widget won't pre-select them.
	awc.reset_shipping(None, awc_session=awc_session, customer=customer)

	# remove? shipping is essential here anyways
	context.shipping_enabled = 1 if settings.awc_shipping_enabled else 0

	related_items = []
	skus_in_cart = []
	# build upsell sku list using or building cache if necessary
	for item in awc_session.get("cart", {}).get("items", []):
		# build cart sku list to dedup later
		skus_in_cart += [item.get("sku")]

		# fetches related items to this sku
		item_related_items = awc.get_related_products_by_sku(
			item.get("sku"), awc_session=awc_session, customer=customer)

		# quick list deduping
		related_items = related_items + list(set(item_related_items) - set(related_items))

	# builds upsell item objects using cache if necessary
	upsell = []
	for sku in related_items:
		if sku not in skus_in_cart:
			# fetches product data to build upsell widget
			product_response = awc.get_product_by_sku(sku, awc_session=awc_session)
			if product_response.get("success"):
				upsell += [product_response.get("data")]

	# upsell widget data is made available to the context here
	context["upsell"] = dict(related_products=upsell)

	# flag to display login form
	context.is_logged = awc.is_logged_in()
	login.apply_context(context)

	if frappe.response.get("awc_alert"):
		context["awc_alert"] = frappe.response.get("awc_alert")


	if context.is_logged:
		# load gateway provider into context
		gateway_provider = frappe.get_hooks('awc_gateway_form_provider')
		if gateway_provider and len(gateway_provider) > 0:
			context['gateway_provider'] = frappe.call(gateway_provider[0], context=dict(
				use_address_same_as=1,
				address_same_as_label="Same as Shipping Address",
				address_same_as_source="#awc-shipping-form"
			))

	return context
示例#50
0
	def process_doc(self, doc):
		id_field = get_id_field(self.doctype)
		if frappe.get_value(self.doctype, doc.get(id_field.fieldname), "name"):
			self.update_record(doc)
		else:
			self.insert_record(doc)
示例#51
0
    def validate_unpledge_qty(self):
        from erpnext.loan_management.doctype.loan_security_shortfall.loan_security_shortfall import get_ltv_ratio

        pledge_qty_map = get_pledged_security_qty(self.loan)

        ltv_ratio_map = frappe._dict(
            frappe.get_all("Loan Security Type",
                           fields=["name", "loan_to_value_ratio"],
                           as_list=1))

        loan_security_price_map = frappe._dict(
            frappe.get_all("Loan Security Price",
                           fields=["loan_security", "loan_security_price"],
                           filters={
                               "valid_from": ("<=", get_datetime()),
                               "valid_upto": (">=", get_datetime())
                           },
                           as_list=1))

        loan_details = frappe.get_value(
            "Loan",
            self.loan, [
                'total_payment', 'total_principal_paid',
                'total_interest_payable', 'written_off_amount',
                'disbursed_amount', 'status'
            ],
            as_dict=1)

        if loan_details.status == 'Disbursed':
            pending_principal_amount = flt(loan_details.total_payment) - flt(loan_details.total_interest_payable) \
                - flt(loan_details.total_principal_paid) - \
                flt(loan_details.written_off_amount)
        else:
            pending_principal_amount = flt(loan_details.disbursed_amount) - flt(loan_details.total_interest_payable) \
                - flt(loan_details.total_principal_paid) - \
                flt(loan_details.written_off_amount)

        security_value = 0
        unpledge_qty_map = {}
        ltv_ratio = 0

        for security in self.securities:
            pledged_qty = pledge_qty_map.get(security.loan_security, 0)
            if security.qty > pledged_qty:
                msg = _("Row {0}: {1} {2} of {3} is pledged against Loan {4}."
                        ).format(security.idx, pledged_qty, security.uom,
                                 frappe.bold(security.loan_security),
                                 frappe.bold(self.loan))
                msg += "<br>"
                msg += _("You are trying to unpledge more.")
                frappe.throw(msg, title=_("Loan Security Unpledge Error"))

            unpledge_qty_map.setdefault(security.loan_security, 0)
            unpledge_qty_map[security.loan_security] += security.qty

        for security in pledge_qty_map:
            if not ltv_ratio:
                ltv_ratio = get_ltv_ratio(security)

            qty_after_unpledge = pledge_qty_map.get(
                security, 0) - unpledge_qty_map.get(security, 0)
            current_price = loan_security_price_map.get(security)
            security_value += qty_after_unpledge * current_price

        if not security_value and flt(pending_principal_amount, 2) > 0:
            self._throw(security_value, pending_principal_amount, ltv_ratio)

        if security_value and flt(
                pending_principal_amount / security_value) * 100 > ltv_ratio:
            self._throw(security_value, pending_principal_amount, ltv_ratio)
示例#52
0
def get_default_supplier():
    supplier = frappe.get_value('ERPNextSwiss Settings',
                                'ERPNextSwiss Settings', 'default_supplier')
    return {'supplier': supplier or ""}
示例#53
0
    def test_payment_days(self):
        no_of_days = self.get_no_of_days()
        # Holidays not included in working days
        frappe.db.set_value("HR Settings", None,
                            "include_holidays_in_total_working_days", 1)

        # set joinng date in the same month
        self.make_employee("*****@*****.**")
        if getdate(nowdate()).day >= 15:
            date_of_joining = getdate(add_days(nowdate(), -10))
            relieving_date = getdate(add_days(nowdate(), -10))
        elif getdate(nowdate()).day < 15 and getdate(nowdate()).day >= 5:
            date_of_joining = getdate(add_days(nowdate(), -3))
            relieving_date = getdate(add_days(nowdate(), -3))
        elif getdate(nowdate()).day < 5 and not getdate(nowdate()).day == 1:
            date_of_joining = getdate(add_days(nowdate(), -1))
            relieving_date = getdate(add_days(nowdate(), -1))
        elif getdate(nowdate()).day == 1:
            date_of_joining = getdate(nowdate())
            relieving_date = getdate(nowdate())

        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "date_of_joining", date_of_joining)
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "relieving_date", None)
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "status", "Active")

        ss = frappe.get_doc(
            "Salary Slip",
            self.make_employee_salary_slip("*****@*****.**",
                                           "Monthly"))

        self.assertEquals(ss.total_working_days, no_of_days[0])
        self.assertEquals(ss.payment_days,
                          (no_of_days[0] - getdate(date_of_joining).day + 1))

        # set relieving date in the same month
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "date_of_joining",
            (add_days(nowdate(), -60)))
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "relieving_date", relieving_date)
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "status", "Left")
        ss.save()

        self.assertEquals(ss.total_working_days, no_of_days[0])
        self.assertEquals(ss.payment_days, getdate(relieving_date).day)

        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "relieving_date", None)
        frappe.db.set_value(
            "Employee",
            frappe.get_value("Employee",
                             {"employee_name": "*****@*****.**"},
                             "name"), "status", "Active")
示例#54
0
	def on_submit(self):
		default_payable_account = frappe.get_value('Company',self.company,'default_payable_account')
		stock_received_but_not_billed = frappe.get_value('Company',self.company,'stock_received_but_not_billed')
		make_gl_entry(self,stock_received_but_not_billed,self.total_amount,flt(0))
		make_gl_entry(self,default_payable_account,flt(0),self.total_amount)
示例#55
0
文件: api.py 项目: asoral/recruitment
def create_closure(doc, method):
    if doc.pending_for == 'Proposed PSL':
        if doc.original_documents:
            for docs in doc.original_documents:
                docslist = frappe.db.get_value(
                    "Original Documents", {"name": docs.name})
        closure_id = frappe.db.get_value("Closure", {"candidate": doc.name})
        # interview = frappe.db.get("Candidate", docs.candidate)
        # if interview:
        #     interview_date = interview.interview_date
        project = frappe.get_doc("Project", doc.project)
        task = frappe.db.get_value("Task", doc.task, "subject")
        ca_executive = frappe.db.get_value(
            "Customer", doc.customer, "customer_owner__cpc")
        territory = frappe.db.get_value("Customer", doc.customer, "territory")
        payment_terms = project.payment_terms
        dle = ca_executive = source_executive = ''
        tl = ''
        bu = ''
        department = ''
        if doc.user:
            executive = frappe.db.get("Employee", {"user_id": doc.user})
            if executive:
                source_executive = executive.user_id
                department = executive.department
                bu = frappe.get_value("Employee", executive, 'business_unit')
                tl = frappe.db.get_value(
                    "Employee", executive.reports_to, "user_id")
        if closure_id:
            closure = frappe.get_doc("Closure", closure_id)
        else:
            closure = frappe.new_doc("Closure")
        closure.update({
            "customer": doc.customer,
            "territory": territory,
            "project": doc.project,
            "payment_terms": payment_terms,
            "task": doc.task,
            "candidate": doc.name,
            "name1": doc.given_name,
            "designation": task,
            "contact_no": doc.mobile,
            "current_location": doc.current_location,
            "passport_no": doc.passport_no,
            "ecr_status": doc.ecr_status,
            "associate_name": doc.associate_name,
            "associate": doc.associate,
            "associate_contact_no": doc.contact_no,
            "expiry_date": doc.expiry_date,
            "date_of_issue": doc.issued_date,
            "place_of_issue": doc.place_of_issue,
            "cr_executive": project.cpc,
            "ca_executive": ca_executive,
            "business_unit": bu,
            "department": department,
            "division": doc.division,
            "source_executive": source_executive,
            "selection_date": doc.interview_date,
            "tl": tl,
            "degree": doc.degree,
            "specialization": doc.specialization,
            "yop": doc.yop,
            "basic": doc.basic,
            "food": doc.food,
            "other_allowances": doc.other_allowances,
            "dob": doc.dob
        })
        if doc.irf:
            closure.update({"irf": doc.irf})
        if doc.candidate_image:
            closure.update({"photo": doc.candidate_image})
        if doc.passport:
            closure.update({"passport": doc.passport})
        if doc.candidate_payment_applicable and flt(doc.candidate_sc) > 0:
            closure.update({
                "candidate_payment_applicable": 1,
                "candidate_sc": doc.candidate_sc
            })
        closure.save(ignore_permissions=True)
示例#56
0
def get_intermediate_account():
    account = frappe.get_value('ERPNextSwiss Settings',
                               'ERPNextSwiss Settings', 'intermediate_account')
    return {'account': account or ""}
示例#57
0
 def __get_uom(self, device_type):
     item_code = frappe.get_value('Cell Station Device Type', device_type,
                                  'type_item')
     return frappe.get_value("Stock Item", item_code, "stock_uom")
示例#58
0
def get_context(context):
    """This is a controller extension for erpnext.templates.pages.cart"""

    context["no_cache"] = 1

    settings = frappe.db.get("Awc Settings")
    awc_session = get_awc_session()

    context["countries"] = [
        x for x in frappe.get_list(
            "Country", fields=["country_name", "name"], ignore_permissions=1)
    ]

    default_country = frappe.get_value("System Settings", "System Settings",
                                       "country")
    default_country_doc = next(
        (x for x in context["countries"] if x.name == default_country), None)

    if frappe.session.user != "Guest":
        address_links = frappe.get_all(
            "Dynamic Link",
            filters={"link_name": get_current_customer().name},
            fields=["parent"])
        addresses = []
        for address in address_links:
            addresses.extend(
                frappe.get_all("Address",
                               filters={
                                   "name": address.parent,
                                   "disabled": False
                               },
                               fields="*"))
        context['addresses'] = addresses

    if frappe.session.user != "Guest":
        customer_info = frappe.db.get_values(
            "Customer",
            get_current_customer().name,
            ["has_shipping_account", "fedex_account_number"])[0]
        context["customer_info"] = {
            "has_shipping_acc": customer_info[0],
            "fedex_acc_number": customer_info[1]
        }

    country_idx = context["countries"].index(default_country_doc)
    context["countries"].pop(country_idx)
    context["countries"] = [default_country_doc] + context["countries"]

    context["shipping_rate_api"] = frappe.get_hooks("shipping_rate_api")[0]
    context["selected_customer"] = awc_session.get("selected_customer")

    # remove? shipping is essential here anyways
    context.shipping_enabled = 1 if settings.awc_shipping_enabled else 0

    # flag to display login form
    context.is_logged = awc.is_logged_in()
    login.apply_context(context)

    if context.is_logged:
        # load gateway provider into context
        gateway_provider = frappe.get_hooks('awc_gateway_form_provider')
        if gateway_provider and len(gateway_provider) > 0:
            context['gateway_provider'] = frappe.call(
                gateway_provider[0],
                context=dict(use_address_same_as=1,
                             address_same_as_label="Same as Shipping Address",
                             address_same_as_source="#awc-shipping-form"))

    awc.reset_shipping()

    return context
示例#59
0
def work():
	frappe.set_user(frappe.db.get_global('demo_hr_user'))
	year, month = frappe.flags.current_date.strftime("%Y-%m").split("-")
	mark_attendance()
	make_leave_application()

	# process payroll
	if not frappe.db.sql('select name from `tabSalary Slip` where month(adddate(start_date, interval 1 month))=month(curdate())'):
		# process payroll for previous month
		process_payroll = frappe.get_doc("Process Payroll", "Process Payroll")
		process_payroll.company = frappe.flags.company
		process_payroll.payroll_frequency = 'Monthly'

		# select a posting date from the previous month
		process_payroll.posting_date = get_last_day(getdate(frappe.flags.current_date) - datetime.timedelta(days=10))
		process_payroll.payment_account = frappe.get_value('Account', {'account_type': 'Cash', 'company': erpnext.get_default_company(),'is_group':0}, "name")

		process_payroll.set_start_end_dates()

		# based on frequency
		process_payroll.salary_slip_based_on_timesheet = 0
		process_payroll.create_salary_slips()
		process_payroll.submit_salary_slips()
		process_payroll.make_accural_jv_entry()
		# process_payroll.make_journal_entry(reference_date=frappe.flags.current_date,
		# 	reference_number=random_string(10))

		process_payroll.salary_slip_based_on_timesheet = 1
		process_payroll.create_salary_slips()
		process_payroll.submit_salary_slips()
		process_payroll.make_accural_jv_entry()
		# process_payroll.make_journal_entry(reference_date=frappe.flags.current_date,
		# 	reference_number=random_string(10))

	if frappe.db.get_global('demo_hr_user'):
		make_timesheet_records()

		#expense claim
		expense_claim = frappe.new_doc("Expense Claim")
		expense_claim.extend('expenses', get_expenses())
		expense_claim.employee = get_random("Employee")
		expense_claim.company = frappe.flags.company
		expense_claim.payable_account = get_payable_account(expense_claim.company)
		expense_claim.posting_date = frappe.flags.current_date
		expense_claim.exp_approver = filter((lambda x: x[0] != 'Administrator'), get_expense_approver(None, '', None, 0, 20, None))[0][0]
		expense_claim.insert()

		rand = random.random()

		if rand < 0.4:
			expense_claim.approval_status = "Approved"
			update_sanctioned_amount(expense_claim)
			expense_claim.submit()

			if random.randint(0, 1):
				#make journal entry against expense claim
				je = frappe.get_doc(make_bank_entry("Expense Claim", expense_claim.name))
				je.posting_date = frappe.flags.current_date
				je.cheque_no = random_string(10)
				je.cheque_date = frappe.flags.current_date
				je.flags.ignore_permissions = 1
				je.submit()

		elif rand < 0.2:
			expense_claim.approval_status = "Rejected"
			expense_claim.submit()
示例#60
0
def get_basic_details(args, item, overwrite_warehouse=True):
    """
	:param args: {
			"item_code": "",
			"warehouse": None,
			"customer": "",
			"conversion_rate": 1.0,
			"selling_price_list": None,
			"price_list_currency": None,
			"price_list_uom_dependant": None,
			"plc_conversion_rate": 1.0,
			"doctype": "",
			"name": "",
			"supplier": None,
			"transaction_date": None,
			"conversion_rate": 1.0,
			"buying_price_list": None,
			"is_subcontracted": "Yes" / "No",
			"ignore_pricing_rule": 0/1
			"project": "",
			barcode: "",
			serial_no: "",
			currency: "",
			update_stock: "",
			price_list: "",
			company: "",
			order_type: "",
			is_pos: "",
			project: "",
			qty: "",
			stock_qty: "",
			conversion_factor: ""
		}
	:param item: `item_code` of Item object
	:return: frappe._dict
	"""

    if not item:
        item = frappe.get_doc("Item", args.get("item_code"))

    if item.variant_of:
        item.update_template_tables()

    item_defaults = get_item_defaults(item.name, args.company)
    item_group_defaults = get_item_group_defaults(item.name, args.company)
    brand_defaults = get_brand_defaults(item.name, args.company)

    defaults = frappe._dict({
        'item_defaults': item_defaults,
        'item_group_defaults': item_group_defaults,
        'brand_defaults': brand_defaults
    })

    warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)

    if args.get('doctype') == "Material Request" and not args.get(
            'material_request_type'):
        args['material_request_type'] = frappe.db.get_value(
            'Material Request',
            args.get('name'),
            'material_request_type',
            cache=True)

    expense_account = None

    if args.get('doctype') == 'Purchase Invoice' and item.is_fixed_asset:
        from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
        expense_account = get_asset_category_account(
            fieldname="fixed_asset_account",
            item=args.item_code,
            company=args.company)

    #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
    if not args.get('uom'):
        if args.get('doctype') in sales_doctypes:
            args.uom = item.sales_uom if item.sales_uom else item.stock_uom
        elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
         (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
            args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
        else:
            args.uom = item.stock_uom

    out = frappe._dict({
        "item_code":
        item.name,
        "item_name":
        item.item_name,
        "description":
        cstr(item.description).strip(),
        "image":
        cstr(item.image).strip(),
        "warehouse":
        warehouse,
        "income_account":
        get_default_income_account(args, item_defaults, item_group_defaults,
                                   brand_defaults),
        "expense_account":
        expense_account or get_default_expense_account(
            args, item_defaults, item_group_defaults, brand_defaults),
        "cost_center":
        get_default_cost_center(args, item_defaults, item_group_defaults,
                                brand_defaults),
        'has_serial_no':
        item.has_serial_no,
        'has_batch_no':
        item.has_batch_no,
        "batch_no":
        args.get("batch_no"),
        "uom":
        args.uom,
        "min_order_qty":
        flt(item.min_order_qty) if args.doctype == "Material Request" else "",
        "qty":
        flt(args.qty) or 1.0,
        "stock_qty":
        flt(args.qty) or 1.0,
        "price_list_rate":
        0.0,
        "base_price_list_rate":
        0.0,
        "rate":
        0.0,
        "base_rate":
        0.0,
        "amount":
        0.0,
        "base_amount":
        0.0,
        "net_rate":
        0.0,
        "net_amount":
        0.0,
        "discount_percentage":
        0.0,
        "supplier":
        get_default_supplier(args, item_defaults, item_group_defaults,
                             brand_defaults),
        "update_stock":
        args.get("update_stock")
        if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
        "delivered_by_supplier":
        item.delivered_by_supplier
        if args.get("doctype") in ["Sales Order", "Sales Invoice"] else 0,
        "is_fixed_asset":
        item.is_fixed_asset,
        "weight_per_unit":
        item.weight_per_unit,
        "weight_uom":
        item.weight_uom,
        "last_purchase_rate":
        item.last_purchase_rate
        if args.get("doctype") in ["Purchase Order"] else 0,
        "transaction_date":
        args.get("transaction_date")
    })

    if item.get("enable_deferred_revenue") or item.get(
            "enable_deferred_expense"):
        out.update(calculate_service_end_date(args, item))

    # calculate conversion factor
    if item.stock_uom == args.uom:
        out.conversion_factor = 1.0
    else:
        out.conversion_factor = args.conversion_factor or \
         get_conversion_factor(item.name, args.uom).get("conversion_factor")

    args.conversion_factor = out.conversion_factor
    out.stock_qty = out.qty * out.conversion_factor

    # calculate last purchase rate
    if args.get('doctype') in purchase_doctypes:
        from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
        out.last_purchase_rate = item_last_purchase_rate(
            args.name, args.conversion_rate, item.name, out.conversion_factor)

    # if default specified in item is for another company, fetch from company
    for d in [["Account", "income_account", "default_income_account"],
              ["Account", "expense_account", "default_expense_account"],
              ["Cost Center", "cost_center", "cost_center"],
              ["Warehouse", "warehouse", ""]]:
        if not out[d[1]]:
            out[d[1]] = frappe.get_cached_value('Company', args.company,
                                                d[2]) if d[2] else None

    for fieldname in ("item_name", "item_group", "barcodes", "brand",
                      "stock_uom"):
        out[fieldname] = item.get(fieldname)

    if args.get("manufacturer"):
        part_no = get_item_manufacturer_part_no(args.get("item_code"),
                                                args.get("manufacturer"))
        if part_no:
            out["manufacturer_part_no"] = part_no
        else:
            out["manufacturer_part_no"] = None
            out["manufacturer"] = None
    else:
        out["manufacturer"], out["manufacturer_part_no"] = frappe.get_value(
            "Item", item.name,
            ["default_item_manufacturer", "default_manufacturer_part_no"])

    child_doctype = args.doctype + ' Item'
    meta = frappe.get_meta(child_doctype)
    if meta.get_field("barcode"):
        update_barcode_value(out)

    return out