def get_healthcare_service_unit():
	service_unit = get_random("Healthcare Service Unit", filters={"inpatient_occupancy": 1})
	if not service_unit:
		service_unit = frappe.new_doc("Healthcare Service Unit")
		service_unit.healthcare_service_unit_name = "Test Service Unit Ip Occupancy"
		service_unit.service_unit_type = get_service_unit_type()
		service_unit.inpatient_occupancy = 1
		service_unit.occupancy_status = "Vacant"
		service_unit.is_group = 0
		service_unit_parent_name = frappe.db.exists({
				"doctype": "Healthcare Service Unit",
				"healthcare_service_unit_name": "All Healthcare Service Units",
				"is_group": 1
				})
		if not service_unit_parent_name:
			parent_service_unit = frappe.new_doc("Healthcare Service Unit")
			parent_service_unit.healthcare_service_unit_name = "All Healthcare Service Units"
			parent_service_unit.is_group = 1
			parent_service_unit.save(ignore_permissions = True)
			service_unit.parent_healthcare_service_unit = parent_service_unit.name
		else:
			service_unit.parent_healthcare_service_unit = service_unit_parent_name[0][0]
		service_unit.save(ignore_permissions = True)
		return service_unit.name
	return service_unit
Example #2
0
	def test_production_order(self):
		bom_no = frappe.db.get_value("BOM", {"item": "_Test FG Item 2",
			"is_default": 1, "docstatus": 1})

		production_order = frappe.new_doc("Production Order")
		production_order.update({
			"company": "_Test Company",
			"fg_warehouse": "_Test Warehouse 1 - _TC",
			"production_item": "_Test FG Item 2",
			"bom_no": bom_no,
			"qty": 1.0,
			"stock_uom": "Nos",
			"wip_warehouse": "_Test Warehouse - _TC"
		})
		production_order.insert()
		production_order.submit()

		self._insert_material_receipt()

		stock_entry = frappe.new_doc("Stock Entry")
		stock_entry.update({
			"purpose": "Manufacture",
			"production_order": production_order.name,
			"bom_no": bom_no,
			"fg_completed_qty": "1",
			"total_fixed_cost": 1000
		})
		stock_entry.get_items()
		fg_rate = [d.amount for d in stock_entry.get("mtn_details") if d.item_code=="_Test FG Item 2"][0]
		self.assertEqual(fg_rate, 1200.00)
		fg_rate = [d.amount for d in stock_entry.get("mtn_details") if d.item_code=="_Test Item"][0]
		self.assertEqual(fg_rate, 100.00)
Example #3
0
def create_plan():
	if not frappe.db.exists('Subscription Plan', '_Test Plan Name'):
		plan = frappe.new_doc('Subscription Plan')
		plan.plan_name = '_Test Plan Name'
		plan.item = '_Test Non Stock Item'
		plan.price_determination = "Fixed rate"
		plan.cost = 900
		plan.billing_interval = 'Month'
		plan.billing_interval_count = 1
		plan.insert()

	if not frappe.db.exists('Subscription Plan', '_Test Plan Name 2'):
		plan = frappe.new_doc('Subscription Plan')
		plan.plan_name = '_Test Plan Name 2'
		plan.item = '_Test Non Stock Item'
		plan.price_determination = "Fixed rate"
		plan.cost = 1999
		plan.billing_interval = 'Month'
		plan.billing_interval_count = 1
		plan.insert()

	if not frappe.db.exists('Subscription Plan', '_Test Plan Name 3'):
		plan = frappe.new_doc('Subscription Plan')
		plan.plan_name = '_Test Plan Name 3'
		plan.item = '_Test Non Stock Item'
		plan.price_determination = "Fixed rate"
		plan.cost = 1999
		plan.billing_interval = 'Day'
		plan.billing_interval_count = 14
		plan.insert()
Example #4
0
def get_default_outgoing_email_account(raise_exception_not_set=True):
	email_account = _get_email_account({"enable_outgoing": 1, "default_outgoing": 1})

	if not email_account and frappe.conf.get("mail_server"):
		# from site_config.json
		email_account = frappe.new_doc("Email Account")
		email_account.update({
			"smtp_server": frappe.conf.get("mail_server"),
			"smtp_port": frappe.conf.get("mail_port"),
			"use_tls": cint(frappe.conf.get("use_ssl") or 0),
			"email_id": frappe.conf.get("mail_login"),
			"password": frappe.conf.get("mail_password"),
			"sender": frappe.conf.get("auto_email_id", "*****@*****.**")
		})
		email_account.from_site_config = True

	if not email_account and not raise_exception_not_set:
		return None

	if frappe.are_emails_muted():
		# create a stub
		email_account = frappe.new_doc("Email Account")
		email_account.update({
			"sender": "*****@*****.**"
		})

	return email_account
def execute():
	warehouse = frappe.db.sql("""select name, email_id, phone_no, mobile_no, address_line_1,
		address_line_2, city, state, pin from `tabWarehouse` where ifnull(address_line_1, '') != '' 
		or ifnull(mobile_no, '') != '' 
		or ifnull(email_id, '') != '' """, as_dict=1)

	for d in warehouse:
		try:
			address = frappe.new_doc('Address')
			address.name = d.name
			address.address_title = d.name
			address.address_line1 = d.address_line_1
			address.city = d.city
			address.state = d.state
			address.pincode = d.pin
			address.db_insert()
			address.append('links',{'link_doctype':'Warehouse','link_name':d.name})
			address.links[0].db_insert()
			if d.name and (d.email_id or d.mobile_no or d.phone_no):
				contact = frappe.new_doc('Contact')
				contact.name = d.name
				contact.first_name = d.name
				contact.mobile_no = d.mobile_no
				contact.email_id = d.email_id
				contact.phone = d.phone_no
				contact.db_insert()
				contact.append('links',{'link_doctype':'Warehouse','link_name':d.name})
				contact.links[0].db_insert()
		except frappe.DuplicateEntryError:
			pass
	def update_attendance(self):
		if self.status == "Approved":
			attendance = frappe.db.sql("""select name from `tabAttendance` where employee = %s\
				and (attendance_date between %s and %s) and docstatus < 2""",(self.employee, self.from_date, self.to_date), as_dict=1)

			if attendance:
				for d in attendance:
					doc = frappe.get_doc("Attendance", d.name)
					if getdate(self.half_day_date) == doc.attendance_date:
						status = "Half Day"
					else:
						status = "On Leave"
					frappe.db.sql("""update `tabAttendance` set status = %s, leave_type = %s\
						where name = %s""",(status, self.leave_type, d.name))

			elif self.from_date <= nowdate():
				for dt in daterange(getdate(self.from_date), getdate(self.to_date)):
					date = dt.strftime("%Y-%m-%d")
					if not date == self.half_day_date:
						doc = frappe.new_doc("Attendance")
						doc.employee = self.employee
						doc.attendance_date = date
						doc.company = self.company
						doc.status = "On Leave"
						doc.leave_type = self.leave_type
						doc.submit()
					else:
						doc = frappe.new_doc("Attendance")
						doc.employee = self.employee
						doc.attendance_date = date
						doc.company = self.company
						doc.status = "Half Day"
						doc.leave_type = self.leave_type
						doc.submit()
Example #7
0
	def test_fee_validity(self):
		patient = get_random("Patient")
		physician = get_random("Physician")

		if not patient:
			patient = frappe.new_doc("Patient")
			patient.patient_name = "Test Patient"
			patient.sex = "Male"
			patient.save(ignore_permissions=True)
			patient = patient.name

		if not physician:
			physician = frappe.new_doc("Physician")
			physician.first_name = "Amit Jain"
			physician.save(ignore_permissions=True)
			physician = physician.name

		frappe.db.set_value("Healthcare Settings", None, "max_visit", 2)
		frappe.db.set_value("Healthcare Settings", None, "valid_days", 7)

		appointment = create_appointment(patient, physician, nowdate())
		invoice = frappe.db.get_value("Patient Appointment", appointment.name, "sales_invoice")
		self.assertEqual(invoice, None)
		create_invoice(frappe.defaults.get_global_default("company"), physician, patient, appointment.name, appointment.appointment_date)
		appointment = create_appointment(patient, physician, add_days(nowdate(), 4))
		invoice = frappe.db.get_value("Patient Appointment", appointment.name, "sales_invoice")
		self.assertTrue(invoice)
		appointment = create_appointment(patient, physician, add_days(nowdate(), 5))
		invoice = frappe.db.get_value("Patient Appointment", appointment.name, "sales_invoice")
		self.assertEqual(invoice, None)
		appointment = create_appointment(patient, physician, add_days(nowdate(), 10))
		invoice = frappe.db.get_value("Patient Appointment", appointment.name, "sales_invoice")
		self.assertEqual(invoice, None)
Example #8
0
def get_customer(user=None):
	if not user:
		user = frappe.session.user

	customer = frappe.db.get_value("Contact", {"email_id": user}, "customer")
	if customer:
		return frappe.get_doc("Customer", customer)

	else:
		customer = frappe.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})
		customer.insert(ignore_permissions=True)

		contact = frappe.new_doc("Contact")
		contact.update({
			"customer": customer.name,
			"first_name": fullname,
			"email_id": user
		})
		contact.insert(ignore_permissions=True)

		return customer
Example #9
0
def execute():
	frappe.reload_doc("accounts", "doctype", "tax_rule")

	customers = frappe.db.sql("""select name, default_taxes_and_charges from tabCustomer where
		ifnull(default_taxes_and_charges, '') != '' """, as_dict=1)

	for d in customers:
		if not frappe.db.sql("select name from `tabTax Rule` where customer=%s", d.name):
			tr = frappe.new_doc("Tax Rule")
			tr.tax_type = "Sales"
			tr.customer = d.name
			tr.sales_tax_template = d.default_taxes_and_charges
			tr.save()


	suppliers = frappe.db.sql("""select name, default_taxes_and_charges from tabSupplier where
		ifnull(default_taxes_and_charges, '') != '' """, as_dict=1)

	for d in suppliers:
		if not frappe.db.sql("select name from `tabTax Rule` where supplier=%s", d.name):
			tr = frappe.new_doc("Tax Rule")
			tr.tax_type = "Purchase"
			tr.supplier = d.name
			tr.purchase_tax_template = d.default_taxes_and_charges
			tr.save()
def send_sms1(numbers,msg,user):
	import math
	num=json.loads(numbers)
	i = datetime.datetime.now()
	today=datetime.date.today()
	if msg:		
		counter = frappe.db.sql("select sms_credits from `tabUser` where name='%s'"%(user),as_list=1)
		sms_len = math.ceil(len(msg)/160.0)
		count = len(num)*cint(sms_len)
		if counter and count<=cint(counter[0][0]):
			credit_count = counter[0][0] - count
			send_sms(num, cstr(msg))
			log = frappe.new_doc("SMS Log")
			log.sender_name = user
			log.sent_on = today
			log.receiver_list = numbers
			log.message = msg
			log.sms_sending_status = 'SMS Sent Successfully'
			log.insert()
			frappe.db.sql("update `tabUser` set sms_credits='%s' where name='%s'"%(credit_count,user))
			frappe.db.commit()
			frappe.msgprint(_("SMS Sent Successfully..."))
		else:
			log = frappe.new_doc("SMS Log")
			log.sender_name = user
			log.sent_on = today
			log.receiver_list = numbers
			log.message = msg
			log.sms_sending_status = 'Sending Fail'
			log.insert(ignore_permissions=True)
			frappe.db.commit()
			frappe.throw(_("SMS credit is not available for sending SMS, Sending fail..!"))
	else:
		frappe.throw(_("Message should not be blank,Please enter text message..."))
Example #11
0
	def test_merge_account(self):
		if not frappe.db.exists("Account", "Current Assets - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Current Assets"
			acc.is_group = 1
			acc.parent_account = "Application of Funds (Assets) - _TC"
			acc.company = "_Test Company"
			acc.insert()
		if not frappe.db.exists("Account", "Securities and Deposits - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Securities and Deposits"
			acc.parent_account = "Current Assets - _TC"
			acc.is_group = 1
			acc.company = "_Test Company"
			acc.insert()
		if not frappe.db.exists("Account", "Earnest Money - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Earnest Money"
			acc.parent_account = "Securities and Deposits - _TC"
			acc.company = "_Test Company"
			acc.insert()
		if not frappe.db.exists("Account", "Cash In Hand - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Cash In Hand"
			acc.is_group = 1
			acc.parent_account = "Current Assets - _TC"
			acc.company = "_Test Company"
			acc.insert()
		if not frappe.db.exists("Account", "Accumulated Depreciation - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Accumulated Depreciation"
			acc.parent_account = "Fixed Assets - _TC"
			acc.company = "_Test Company"
			acc.insert()

		doc = frappe.get_doc("Account", "Securities and Deposits - _TC")
		parent = frappe.db.get_value("Account", "Earnest Money - _TC", "parent_account")

		self.assertEqual(parent, "Securities and Deposits - _TC")

		merge_account("Securities and Deposits - _TC", "Cash In Hand - _TC", doc.is_group, doc.root_type, doc.company)
		parent = frappe.db.get_value("Account", "Earnest Money - _TC", "parent_account")

		# Parent account of the child account changes after merging
		self.assertEqual(parent, "Cash In Hand - _TC")

		# Old account doesn't exist after merging
		self.assertFalse(frappe.db.exists("Account", "Securities and Deposits - _TC"))

		doc = frappe.get_doc("Account", "Current Assets - _TC")

		# Raise error as is_group property doesn't match
		self.assertRaises(frappe.ValidationError, merge_account, "Current Assets - _TC",\
			"Accumulated Depreciation - _TC", doc.is_group, doc.root_type, doc.company)

		doc = frappe.get_doc("Account", "Capital Stock - _TC")

		# Raise error as root_type property doesn't match
		self.assertRaises(frappe.ValidationError, merge_account, "Capital Stock - _TC",\
			"Softwares - _TC", doc.is_group, doc.root_type, doc.company)
Example #12
0
def get_party(user=None):
	if not user:
		user = frappe.session.user

	contact_name = frappe.db.get_value("Contact", {"email_id": user})
	party = None

	if contact_name:
		contact = frappe.get_doc('Contact', contact_name)
		if contact.links:
			party_doctype = contact.links[0].link_doctype
			party = contact.links[0].link_name

	cart_settings = frappe.get_doc("Shopping Cart Settings")

	debtors_account = ''

	if cart_settings.enable_checkout:
		debtors_account = get_debtors_account(cart_settings)

	if party:
		return frappe.get_doc(party_doctype, party)

	else:
		if not cart_settings.enabled:
			frappe.local.flags.redirect_location = "/contact"
			raise frappe.Redirect
		customer = frappe.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})

		if debtors_account:
			customer.update({
				"accounts": [{
					"company": cart_settings.company,
					"account": debtors_account
				}]
			})

		customer.flags.ignore_mandatory = True
		customer.insert(ignore_permissions=True)

		contact = frappe.new_doc("Contact")
		contact.update({
			"first_name": fullname,
			"email_id": user
		})
		contact.append('links', dict(link_doctype='Customer', link_name=customer.name))
		contact.flags.ignore_mandatory = True
		contact.insert(ignore_permissions=True)

		return customer
Example #13
0
    def test_reschedule_dependent_task(self):
        task1 = frappe.new_doc("Task")
        task1.update(
            {"status": "Open", "subject": "_Test Task 1", "exp_start_date": "2015-1-1", "exp_end_date": "2015-1-10"}
        )
        task1.save()

        task2 = frappe.new_doc("Task")
        task2.update(
            {
                "status": "Open",
                "subject": "_Test Task 2",
                "exp_start_date": "2015-1-11",
                "exp_end_date": "2015-1-15",
                "depends_on": [{"task": task1.name}],
            }
        )
        task2.save()

        task3 = frappe.new_doc("Task")
        task3.update(
            {
                "status": "Open",
                "subject": "_Test Task 3",
                "exp_start_date": "2015-1-16",
                "exp_end_date": "2015-1-18",
                "depends_on": [{"task": task2.name}],
            }
        )
        task3.save()

        task1.update({"exp_end_date": "2015-1-20"})
        task1.save()

        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_start_date"), getdate("2015-1-21"))
        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_end_date"), getdate("2015-1-25"))

        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_start_date"), getdate("2015-1-26"))
        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_end_date"), getdate("2015-1-28"))

        time_log = frappe.new_doc("Time Log")
        time_log.update({"from_time": "2015-1-1", "to_time": "2015-1-20", "task": task1.name})
        time_log.submit()

        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_start_date"), getdate("2015-1-21"))
        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_end_date"), getdate("2015-1-25"))

        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_start_date"), getdate("2015-1-26"))
        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_end_date"), getdate("2015-1-28"))

        time_log.cancel()

        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_start_date"), getdate("2015-1-21"))
        self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_end_date"), getdate("2015-1-25"))

        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_start_date"), getdate("2015-1-26"))
        self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_end_date"), getdate("2015-1-28"))
Example #14
0
def create(kind, owner, users = None, name = None):
	authenticate(owner)

	users  = safe_json_loads(users)
	create = True

	if kind == 'Visitor':
		room = squashify(frappe.db.sql("""
			SELECT name
			FROM   `tabChat Room`
			WHERE  owner = "{owner}"
		""".format(owner = owner), as_dict = True))

		if room:
			room   = frappe.get_doc('Chat Room', room.name)
			create = False

	if create:
		room  		   = frappe.new_doc('Chat Room')
		room.type 	   = kind
		room.owner	   = owner
		room.room_name = name

	dusers = [ ]

	if kind != 'Visitor':
		if users:
			users  = listify(users)
			for user in users:
				duser 	   = frappe.new_doc('Chat Room User')
				duser.user = user
				dusers.append(duser)

			room.users = dusers
	else:
		dsettings	   = frappe.get_single('Website Settings')
		room.room_name = dsettings.chat_room_name

		users          = [user for user in room.users] if hasattr(room, 'users') else [ ]

		for user in dsettings.chat_operators:
			if user.user not in users:
				# appending user to room.users will remove the user from chat_operators
				# this is undesirable, create a new Chat Room User instead
				chat_room_user = {"doctype": "Chat Room User", "user": user.user}
				room.append('users', chat_room_user)

	room.save(ignore_permissions = True)

	room  = get(owner, rooms = room.name)
	users = [room.owner] + [u for u in room.users]

	for u in users:
		frappe.publish_realtime('frappe.chat.room:create', room, user = u, after_commit = True)

	return room
Example #15
0
def create_popup(caller_number, agent_id, call_id):
	#return caller_number

	caller_number_processed = process_mobile_no(caller_number)

	ld = None

	ld_name = frappe.db.get_value("Lead", {"mobile_no": caller_number_processed}, "name") # frappe.get_all("Lead", fields=["*"], filters={"mobile_no": caller_number_processed})

	if not ld_name:
		#Create stub lead if lead is not found.
		ld = frappe.new_doc("Lead")
		ld.mobile_no = caller_number_processed
		ld.lead_name = "New Lead ({m})".format(m=caller_number)

		#Set mandatory custom fields.
		ld.first_name = "New Lead ({m})".format(m=caller_number)
		ld.awfis_mobile_no = caller_number_processed
		ld.source = "Other"
		ld.awfis_lead_territory = "All Territories"

		ld.insert(ignore_permissions=True)
		frappe.db.commit()
	else:
		ld = frappe.get_doc("Lead", ld_name)


	#Make popup content.
	lead_fields = {"mobile_no": caller_number,
			"lead_name": ld.lead_name,
			"company_name": ld.company_name,
			"name": ld.name,
			"call_timestamp": frappe.utils.datetime.datetime.strftime(frappe.utils.datetime.datetime.today(), '%d/%m/%Y %H:%M:%S'),
			"call_id": call_id}

	popup_content = frappe.render_template("awfis_erpnext/templates/lead_info.html", lead_fields)

	#Create a notification.
	notif = frappe.new_doc("Communication")
	notif.subject = "Incoming Call {m}".format(m=caller_number)
	notif.communication_type = "Communication"
	notif.content = popup_content #, {"communication_type": "Notification", "content": popup_content})
	notif.status = "Linked"
	notif.sent_or_received = "Sent"
	notif.reference_doctype = "Lead"
	notif.reference_name = ld.name

	notif.insert(ignore_permissions=True)
	frappe.db.commit()

	#Display the actual popup to all sales users.
	#Display popup to agent
	# for u in frappe.get_all("User", fields=['name'], filters={"role": "Sales User"}):
	# 	frappe.async.publish_realtime(event="msgprint", message=popup_content, user=u.name)

	frappe.async.publish_realtime(event="msgprint", message=popup_content, user=agent_id)
Example #16
0
def update_used_quotation(quotation):
	if not frappe.db.get_value("Quotation Used",{"quotation":quotation},"quotation"):
		uq=frappe.new_doc('Used Quotation')
		uq.save(ignore_permissions=True)
		qu=frappe.new_doc('Quotation Used')
		qu.quotation=quotation
		qu.parentfield='quotation_used'
		qu.parenttype='Used Quotation'
		qu.parent=uq.name
		qu.save(ignore_permissions=True)
Example #17
0
def update_used(sales_order):
	if not frappe.db.get_value("Sales Order Used",{"sales_order":sales_order},"sales_order"):
		uso=frappe.new_doc('Used Sales Order')
		uso.save(ignore_permissions=True)
		sopo=frappe.new_doc('Sales Order Used')
		sopo.sales_order=sales_order
		sopo.parentfield='sales_order_used'
		sopo.parenttype='Used Sales Order'
		sopo.parent=uso.name
		sopo.save(ignore_permissions=True)
Example #18
0
def get_mapped_doc(from_doctype, from_docname, table_maps, target_doc=None,
		postprocess=None, ignore_permissions=False):

	source_doc = frappe.get_doc(from_doctype, from_docname)

	if not ignore_permissions:
		if not source_doc.has_permission("read"):
			source_doc.raise_no_permission_to("read")

	# main
	if not target_doc:
		target_doc = frappe.new_doc(table_maps[from_doctype]["doctype"])
	elif isinstance(target_doc, basestring):
		target_doc = frappe.get_doc(json.loads(target_doc))

	if not target_doc.has_permission("create"):
		target_doc.raise_no_permission_to("create")

	map_doc(source_doc, target_doc, table_maps[source_doc.doctype])

	row_exists_for_parentfield = {}

	# children
	for df in source_doc.meta.get_table_fields():
		source_child_doctype = df.options
		table_map = table_maps.get(source_child_doctype)
		if table_map:
			for source_d in source_doc.get(df.fieldname):
				if "condition" in table_map:
					if not table_map["condition"](source_d):
						continue

				target_child_doctype = table_map["doctype"]
				target_parentfield = target_doc.get_parentfield_of_doctype(target_child_doctype)

				# does row exist for a parentfield?
				if df.fieldname not in row_exists_for_parentfield:
					row_exists_for_parentfield[target_parentfield] = (True
						if target_doc.get(target_parentfield) else False)

				if table_map.get("add_if_empty") and row_exists_for_parentfield.get(target_parentfield):
					continue

				if table_map.get("filter") and table_map.get("filter")(source_d):
					continue

				target_d = frappe.new_doc(target_child_doctype, target_doc, target_parentfield)
				map_doc(source_d, target_d, table_map, source_doc)
				target_d.idx = None
				target_doc.append(target_parentfield, target_d)

	if postprocess:
		postprocess(source_doc, target_doc)

	return target_doc
Example #19
0
	def test_retain_sample(self):
		from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
		from erpnext.stock.doctype.batch.batch import get_batch_qty
		
		create_warehouse("Test Warehouse for Sample Retention")
		frappe.db.set_value("Stock Settings", None, "sample_retention_warehouse", "Test Warehouse for Sample Retention - _TC")
		
		item = frappe.new_doc("Item")
		item.item_code = "Retain Sample Item"
		item.item_name = "Retain Sample Item"
		item.description = "Retain Sample Item"
		item.item_group = "All Item Groups"
		item.is_stock_item = 1
		item.has_batch_no = 1
		item.create_new_batch = 1
		item.retain_sample = 1
		item.sample_quantity = 4
		item.save()

		receipt_entry = frappe.new_doc("Stock Entry")
		receipt_entry.company = "_Test Company"
		receipt_entry.purpose = "Material Receipt"
		receipt_entry.append("items", {
			"item_code": item.item_code,
			"t_warehouse": "_Test Warehouse - _TC",
			"qty": 40,
			"basic_rate": 12,
			"cost_center": "_Test Cost Center - _TC",
			"sample_quantity": 4
		})
		receipt_entry.insert()
		receipt_entry.submit()

		retention_data = move_sample_to_retention_warehouse(receipt_entry.company, receipt_entry.get("items"))
		retention_entry = frappe.new_doc("Stock Entry")
		retention_entry.company = retention_data.company
		retention_entry.purpose = retention_data.purpose
		retention_entry.append("items", {
			"item_code": item.item_code,
			"t_warehouse": "Test Warehouse for Sample Retention - _TC",
			"s_warehouse": "_Test Warehouse - _TC",
			"qty": 4,
			"basic_rate": 12,
			"cost_center": "_Test Cost Center - _TC",
			"batch_no": receipt_entry.get("items")[0].batch_no
		})
		retention_entry.insert()
		retention_entry.submit()

		qty_in_usable_warehouse = get_batch_qty(receipt_entry.get("items")[0].batch_no, "_Test Warehouse - _TC", "_Test Item")
		qty_in_retention_warehouse = get_batch_qty(receipt_entry.get("items")[0].batch_no, "Test Warehouse for Sample Retention - _TC", "_Test Item")
		
		self.assertEquals(qty_in_usable_warehouse, 36)
		self.assertEquals(qty_in_retention_warehouse, 4)
def link_customer_and_address(raw_billing_data,customer_status):

	if customer_status == 0:
		# create
		customer = frappe.new_doc("Customer")
		address = frappe.new_doc("Address")

	if customer_status == 1:
		# Edit
		customer_woo_com_email = raw_billing_data.get("email")
		customer = frappe.get_doc("Customer",{"woocommerce_email": customer_woo_com_email})
		old_name = customer.customer_name

	full_name = str(raw_billing_data.get("first_name"))+ " "+str(raw_billing_data.get("last_name"))
	customer.customer_name = full_name
	customer.woocommerce_email = str(raw_billing_data.get("email"))
	customer.save()
	frappe.db.commit()

	if customer_status == 1:
		frappe.rename_doc("Customer", old_name, full_name)
		address = frappe.get_doc("Address",{"woocommerce_email":customer_woo_com_email})
		customer = frappe.get_doc("Customer",{"woocommerce_email": customer_woo_com_email})

	address.address_line1 = raw_billing_data.get("address_1", "Not Provided")
	address.address_line2 = raw_billing_data.get("address_2", "Not Provided")
	address.city = raw_billing_data.get("city", "Not Provided")
	address.woocommerce_email = str(raw_billing_data.get("email"))
	address.address_type = "Shipping"
	address.country = frappe.get_value("Country", filters={"code":raw_billing_data.get("country", "IN").lower()})
	address.state =  raw_billing_data.get("state")
	address.pincode =  str(raw_billing_data.get("postcode"))
	address.phone = str(raw_billing_data.get("phone"))
	address.email_id = str(raw_billing_data.get("email"))

	address.append("links", {
		"link_doctype": "Customer",
		"link_name": customer.customer_name
	})

	address.save()
	frappe.db.commit()

	if customer_status == 1:

		address = frappe.get_doc("Address",{"woocommerce_email":customer_woo_com_email})
		old_address_title = address.name
		new_address_title = customer.customer_name+"-billing"
		address.address_title = customer.customer_name
		address.save()

		frappe.rename_doc("Address",old_address_title,new_address_title)

	frappe.db.commit()
def execute():
	# Update Social Logins in User
	run_patch()

	# Create Social Login Key(s) from Social Login Keys
	frappe.reload_doc("integrations", "doctype", "social_login_key", force=True)

	if not frappe.db.exists('DocType', 'Social Login Keys'):
		return

	social_login_keys = frappe.get_doc("Social Login Keys", "Social Login Keys")
	if social_login_keys.get("facebook_client_id") or social_login_keys.get("facebook_client_secret"):
		facebook_login_key = frappe.new_doc("Social Login Key")
		facebook_login_key.get_social_login_provider("Facebook", initialize=True)
		facebook_login_key.social_login_provider = "Facebook"
		facebook_login_key.client_id = social_login_keys.get("facebook_client_id")
		facebook_login_key.client_secret = social_login_keys.get("facebook_client_secret")
		if not (facebook_login_key.client_secret and facebook_login_key.client_id):
			facebook_login_key.enable_social_login = 0
		facebook_login_key.save()

	if social_login_keys.get("frappe_server_url"):
		frappe_login_key = frappe.new_doc("Social Login Key")
		frappe_login_key.get_social_login_provider("Frappe", initialize=True)
		frappe_login_key.social_login_provider = "Frappe"
		frappe_login_key.base_url = social_login_keys.get("frappe_server_url")
		frappe_login_key.client_id = social_login_keys.get("frappe_client_id")
		frappe_login_key.client_secret = social_login_keys.get("frappe_client_secret")
		if not (frappe_login_key.client_secret and frappe_login_key.client_id and frappe_login_key.base_url):
			frappe_login_key.enable_social_login = 0
		frappe_login_key.save()

	if social_login_keys.get("github_client_id") or social_login_keys.get("github_client_secret"):
		github_login_key = frappe.new_doc("Social Login Key")
		github_login_key.get_social_login_provider("GitHub", initialize=True)
		github_login_key.social_login_provider = "GitHub"
		github_login_key.client_id = social_login_keys.get("github_client_id")
		github_login_key.client_secret = social_login_keys.get("github_client_secret")
		if not (github_login_key.client_secret and github_login_key.client_id):
			github_login_key.enable_social_login = 0
		github_login_key.save()

	if social_login_keys.get("google_client_id") or social_login_keys.get("google_client_secret"):
		google_login_key = frappe.new_doc("Social Login Key")
		google_login_key.get_social_login_provider("Google", initialize=True)
		google_login_key.social_login_provider = "Google"
		google_login_key.client_id = social_login_keys.get("google_client_id")
		google_login_key.client_secret = social_login_keys.get("google_client_secret")
		if not (google_login_key.client_secret and google_login_key.client_id):
			google_login_key.enable_social_login = 0
		google_login_key.save()

	frappe.delete_doc("DocType", "Social Login Keys")
Example #22
0
	def test_reschedule_dependent_task(self):
		task1 =  frappe.new_doc('Task')
		task1.update({
			"status": "Open",
			"subject": "_Test Task 1",
			"project": "_Test Project",
			"exp_start_date": "2015-1-1",
			"exp_end_date": "2015-1-10"
		})
		task1.save()

		task2 =  frappe.new_doc('Task')
		task2.update({
			"status": "Open",
			"subject": "_Test Task 2",
			"project": "_Test Project",
			"exp_start_date": "2015-1-11",
			"exp_end_date": "2015-1-15",
			"depends_on":[
				{
					"task": task1.name,
					"project": "_Test Project"
				}
			]
		})
		task2.save()

		task3 =  frappe.new_doc('Task')
		task3.update({
			"status": "Open",
			"subject": "_Test Task 3",
			"project": "_Test Project",
			"exp_start_date": "2015-1-16",
			"exp_end_date": "2015-1-18",
			"depends_on":[
				{
					"task": task2.name,
					"project": "_Test Project"
				}
			]
		})
		task3.save()

		task1.update({
			"exp_end_date": "2015-1-20"
		})
		task1.save()

		self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_start_date"), getdate('2015-1-21'))
		self.assertEqual(frappe.db.get_value("Task", task2.name, "exp_end_date"), getdate('2015-1-25'))

		self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_start_date"), getdate('2015-1-26'))
		self.assertEqual(frappe.db.get_value("Task", task3.name, "exp_end_date"), getdate('2015-1-28'))
Example #23
0
def get_party(user=None):
	if not user:
		user = frappe.session.user

	party = frappe.db.get_value("Contact", {"email_id": user}, ["customer", "supplier"], as_dict=1)
	if party:
		party_doctype = 'Customer' if party.customer else 'Supplier'
		party = party.customer or party.supplier

	cart_settings = frappe.get_doc("Shopping Cart Settings")

	debtors_account = ''

	if cart_settings.enable_checkout:
		debtors_account = get_debtors_account(cart_settings)

	if party:
		return frappe.get_doc(party_doctype, party)

	else:
		if not cart_settings.enabled:
			return None
		customer = frappe.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})

		if debtors_account:
			customer.update({
				"accounts": [{
					"company": cart_settings.company,
					"account": debtors_account
				}]
			})

		customer.flags.ignore_mandatory = True
		customer.insert(ignore_permissions=True)

		contact = frappe.new_doc("Contact")
		contact.update({
			"customer": customer.name,
			"first_name": fullname,
			"email_id": user
		})
		contact.flags.ignore_mandatory = True
		contact.insert(ignore_permissions=True)

		return customer
Example #24
0
def make_opportunity(buyer_name, email_id):
	buyer_name = "HUB-" + buyer_name

	if not frappe.db.exists('Lead', {'email_id': email_id}):
		lead = frappe.new_doc("Lead")
		lead.lead_name = buyer_name
		lead.email_id = email_id
		lead.save(ignore_permissions=True)

	o = frappe.new_doc("Opportunity")
	o.enquiry_from = "Lead"
	o.lead = frappe.get_all("Lead", filters={"email_id": email_id}, fields = ["name"])[0]["name"]
	o.save(ignore_permissions=True)
Example #25
0
    def test_circular_reference(self):

        task1 = frappe.new_doc("Task")
        task1.update(
            {"status": "Open", "subject": "_Test Task 1", "exp_start_date": "2015-1-1", "exp_end_date": "2015-1-10"}
        )
        task1.save()

        task2 = frappe.new_doc("Task")
        task2.update(
            {
                "status": "Open",
                "subject": "_Test Task 2",
                "exp_start_date": "2015-1-11",
                "exp_end_date": "2015-1-15",
                "depends_on": [{"task": task1.name}],
            }
        )
        task2.save()

        task3 = frappe.new_doc("Task")
        task3.update(
            {
                "status": "Open",
                "subject": "_Test Task 2",
                "exp_start_date": "2015-1-11",
                "exp_end_date": "2015-1-15",
                "depends_on": [{"task": task2.name}],
            }
        )
        task3.save()

        task1.append("depends_on", {"task": task3.name})
        self.assertRaises(CircularReferenceError, task1.save)

        task1.set("depends_on", [])
        task1.save()

        task4 = frappe.new_doc("Task")
        task4.update(
            {
                "status": "Open",
                "subject": "_Test Task 1",
                "exp_start_date": "2015-1-1",
                "exp_end_date": "2015-1-15",
                "depends_on": [{"task": task1.name}],
            }
        )
        task4.save()

        task3.append("depends_on", {"task": task4.name})
Example #26
0
def create_customer(order_json):
	order_customer_name = ""

	if not("BuyerName" in order_json):
		order_customer_name = "Buyer - " + order_json.AmazonOrderId
	else:
		order_customer_name = order_json.BuyerName

	existing_customer_name = frappe.db.get_value("Customer",
			filters={"name": order_customer_name}, fieldname="name")

	if existing_customer_name:
		filters = [
				["Dynamic Link", "link_doctype", "=", "Customer"],
				["Dynamic Link", "link_name", "=", existing_customer_name],
				["Dynamic Link", "parenttype", "=", "Contact"]
			]

		existing_contacts = frappe.get_list("Contact", filters)

		if existing_contacts:
			pass
		else:
			new_contact = frappe.new_doc("Contact")
			new_contact.first_name = order_customer_name
			new_contact.append('links', {
				"link_doctype": "Customer",
				"link_name": existing_customer_name
			})
			new_contact.insert()

		return existing_customer_name
	else:
		mws_customer_settings = frappe.get_doc("Amazon MWS Settings")
		new_customer = frappe.new_doc("Customer")
		new_customer.customer_name = order_customer_name
		new_customer.customer_group = mws_customer_settings.customer_group
		new_customer.territory = mws_customer_settings.territory
		new_customer.customer_type = mws_customer_settings.customer_type
		new_customer.save()

		new_contact = frappe.new_doc("Contact")
		new_contact.first_name = order_customer_name
		new_contact.append('links', {
			"link_doctype": "Customer",
			"link_name": new_customer.name
		})

		new_contact.insert()

		return new_customer.name
Example #27
0
	def _set_defaults(self):
		if frappe.flags.in_import:
			return

		new_doc = frappe.new_doc(self.doctype, as_dict=True)
		self.update_if_missing(new_doc)

		# children
		for df in self.meta.get_table_fields():
			new_doc = frappe.new_doc(df.options, as_dict=True)
			value = self.get(df.fieldname)
			if isinstance(value, list):
				for d in value:
					d.update_if_missing(new_doc)
Example #28
0
	def on_update(self):
		# pass
		usr_id=frappe.db.sql("select name from `tabUser` where name='%s'"%(self.email_id),as_list=1)
		if self.flag=='not' and self.email_id:
			# frappe.errprint("user creation")
			# if  self.member_designation=='PCF Leader':
			# 	c_user = self.pcf
			# 	r_user = '******'
			# 	perm = 'PCFs'
			# elif self.member_designation=='Sr.Cell Leader':
			# 	c_user = self.senior_cell
			# 	r_user = '******'
			# 	perm = 'Senior Cells'
			# elif self.member_designation=='Cell Leader':
			# 	c_user = self.cell
			# 	r_user = '******'
			# 	perm = 'Cells'
			# elif self.member_designation=='Member':
			# 	c_user = self.name
			# 	r_user = '******'
			# 	perm = 'Member'
			# elif self.member_designation=='Bible Study Class Teacher':
			# 	c_user = self.church
			# 	r_user = '******'
			# 	perm = 'Churches'

			if not usr_id:
				u = frappe.new_doc("User")
				u.email=self.email_id
				u.first_name = self.member_name
				u.new_password = '******'
				frappe.flags.mute_emails = False
				u.insert()
				frappe.flags.mute_emails = True
			r=frappe.new_doc("UserRole")
			r.parent=self.email_id
			r.parentfield='user_roles'
			r.parenttype='User'
			r.role='Member'
			r.insert()
			v = frappe.new_doc("DefaultValue")
			v.parentfield = 'system_defaults'
			v.parenttype = 'User Permission'
			v.parent = self.email_id
			v.defkey = 'Member'
			v.defvalue = self.name 
			v.insert()
			frappe.db.sql("update `tabMember` set flag='SetPerm' where name='%s'"%(self.name))
			frappe.db.commit()
			self.user_id = self.email_id
def execute():
	leave_app_list = frappe.db.sql("""SELECT name FROM `tabLeave Application` 
		WHERE docstatus = 1 AND status = 'Approved'
		ORDER BY name ASC""", as_list=1)
	for leave_app in leave_app_list:
		print("Checking for Leave Application " + leave_app[0])
		la_doc = frappe.get_doc("Leave Application", leave_app[0])
		att_list = frappe.db.sql("""SELECT name FROM `tabAttendance` 
			WHERE docstatus = 1 AND employee ='%s' AND attendance_date BETWEEN '%s' AND '%s'"""%(la_doc.employee, \
				la_doc.from_date, la_doc.to_date), as_list=1)
		if att_list:
			for att in att_list:
				status = frappe.db.get_value("Attendance", att[0], "status")
				if status != 'On Leave':
					if status == 'Half Day':
						if la_doc.total_leave_days != 0.5:
							print('Half Day Error for ' + att[0] + ' and Leave App ' + leave_app[0])
					else:
						print('Error for ' + att[0] + ' and Leave App ' + leave_app[0])
		else:
			leave_days = la_doc.total_leave_days
			for lday in range(int(leave_days)):
				shift_request = frappe.db.sql("""SELECT name FROM `tabShift Assignment` 
					WHERE employee = '%s' AND docstatus = 1 AND `date` = '%s'"""%\
					(la_doc.employee, add_days(la_doc.from_date, lday)),as_list=1)

				if not shift_request:
					new_sr = frappe.new_doc("Shift Assignment")
					new_sr.employee = la_doc.employee
					new_sr.company = la_doc.company
					new_sr.shift_type = 'General Shift G-Shift With In and Out'
					new_sr.date = add_days(la_doc.from_date, lday)
					new_sr.docstatus = 1
					new_sr.insert()
					print("Added Shift Request " + str(new_sr.name) + " for Employee " + \
						la_doc.employee + " with Name: " + str(la_doc.employee_name))
					frappe.db.commit()

				new_att = frappe.new_doc("Attendance")
				new_att.docstatus = 1
				new_att.employee = la_doc.employee
				new_att.attendance_date = add_days(la_doc.from_date, lday)
				if la_doc.total_leave_days == int(la_doc.total_leave_days):
					new_att.status = 'On Leave'
				new_att.company = la_doc.company
				new_att.department = la_doc.department
				new_att.insert()
				print('Added Attendance for Employee ' + la_doc.employee + ' Name: ' + str(la_doc.employee_name) + ' for Leave Application ' + la_doc.name)
			frappe.db.commit()
Example #30
0
	def test_fee_validity(self):
		frappe.db.sql("""delete from `tabPatient Appointment`""")
		frappe.db.sql("""delete from `tabFee Validity`""")
		patient = get_random("Patient")
		practitioner = get_random("Healthcare Practitioner")
		department = get_random("Medical Department")

		if not patient:
			patient = frappe.new_doc("Patient")
			patient.patient_name = "_Test Patient"
			patient.sex = "Male"
			patient.save(ignore_permissions=True)
			patient = patient.name

		if not department:
			medical_department = frappe.new_doc("Medical Department")
			medical_department.department = "_Test Medical Department"
			medical_department.save(ignore_permissions=True)
			department = medical_department.name

		if not practitioner:
			practitioner = frappe.new_doc("Healthcare Practitioner")
			practitioner.first_name = "_Test Healthcare Practitioner"
			practitioner.department = department
			practitioner.save(ignore_permissions=True)
			practitioner = practitioner.name



		frappe.db.set_value("Healthcare Settings", None, "max_visit", 2)
		frappe.db.set_value("Healthcare Settings", None, "valid_days", 7)

		appointment = create_appointment(patient, practitioner, nowdate(), department)
		invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced")
		self.assertEqual(invoiced, 0)

		invoice_appointment(appointment)

		appointment = create_appointment(patient, practitioner, add_days(nowdate(), 4), department)
		invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced")
		self.assertTrue(invoiced)

		appointment = create_appointment(patient, practitioner, add_days(nowdate(), 5), department)
		invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced")
		self.assertEqual(invoiced, 0)

		appointment = create_appointment(patient, practitioner, add_days(nowdate(), 10), department)
		invoiced = frappe.db.get_value("Patient Appointment", appointment.name, "invoiced")
		self.assertEqual(invoiced, 0)
Example #31
0
    def on_submit(self):

        mlog_url = get_url_to_form('Maintenance Log', self.name)
        idx = mlog_url.find("/desk#")
        mlog_link = mlog_url[:idx] + ":8081" + mlog_url[idx:]
        content = "Maintenance Log No. - <b><a href='{url}'>{name}</a></b><br>Creation Date: {date} :-<p><b>Service Parts: </b></p><ol>".format(
            url=mlog_link, name=self.name, date=self.get_formatted('date'))

        for d in self.service_detail:
            content += "<li>"
            content += "Part Name: <b>" + d.service_item + "</b><br>"
            content += "Service Type: <b>" + d.type + "</b><br>"
            content += "Service Charge: <b>" + d.get_formatted(
                'service_charge') + "</b><br>"

            part_content = "Maintenance Log No. - <b><a href='{url}'>{name}</a></b><br>Creation Date: {date}:-".format(
                url=mlog_link.replace('localhost', 'localhost:8081'),
                name=self.name,
                date=self.get_formatted('date'))

            if d.type == "Change at Garage":
                truck_part_url = get_url_to_form("Truck Parts Inventory",
                                                 d.new_part_link)
                idx = truck_part_url.find("/desk#")
                truck_part_link = truck_part_url[:
                                                 idx] + ":8081" + truck_part_url[
                                                     idx:]
                content += "New Part Log: <b><a href='{url}'>{name}</a></b><br>".format(
                    url=truck_part_link, name=d.new_part_link)
                content += "New Part Rate: <b>{rate}</b><br>".format(
                    rate=d.purchase_rate)

            part_content += "<p>Type: " + d.type + "</p>"
            part_content += "<p>Service Charge: " + d.get_formatted(
                'service_charge') + "</p>"

            content += "</li>"

            com = new_doc("Communication")
            com.subject = self.name
            com.content = part_content
            com.communication_type = "Comment"
            com.comment_type = "Comment"
            com.reference_doctype = "Truck Parts Inventory"
            com.reference_name = d.part_no
            com.user = frappe.session.user
            com.save(ignore_permissions=True)
            db.commit()

        content += "</ol>"

        if self.consumable_details:
            content += "<p><b>Consumable Service: </b></p><ol>"

            for row in self.consumable_details:
                content += "<li>"
                content += "Item Code: <b>" + row.item_code + "</b><br>"
                content += "User Qty: <b>" + row.get_formatted(
                    'used_qty') + " " + row.uom + "</b><br>"

                if row.from_inventory:
                    cost = flt(row.service_cost)
                else:
                    cost = flt(row.amount) + flt(row.service_cost)

                content += "Cost: <b>" + str(cost) + "</b><br></li>"

            content += "</ol>"

        if self.other_service_charge:
            content += "<p>Other Service Charge: " + self.get_formatted(
                'other_service_charge') + "</p>"

        content += "<p>Total Service Bill: " + self.get_formatted(
            'total_service_bill') + "</p>"

        com = new_doc("Communication")
        com.subject = self.name
        com.content = content
        com.communication_type = "Comment"
        com.comment_type = "Comment"
        com.reference_doctype = "Truck Master"
        com.reference_name = self.truck_no
        com.user = frappe.session.user
        com.save(ignore_permissions=True)
        db.commit()
Example #32
0
def make_timesheet(production_order):
	timesheet = frappe.new_doc("Timesheet")
	timesheet.employee = ""
	timesheet.production_order = production_order
	return timesheet
    def insert_work_history(self):
        employee = frappe.get_doc('Employee', {'name': self.employee})
        iwh = employee.get("internal_work_history")
        if iwh:
            from_date = add_days(iwh[-1].to_date, 1)
        else:
            from_date = employee.date_of_joining
        # salary_structer_list = frappe.get_list("Salary Structure", fields=["name"],filters ={'employee' : employee.name,'is_active':'Yes'})
        # if salary_structer_list:
        #   salary_structer = frappe.get_doc('Salary Structure Employee',{'employee' : employee.name,'is_active':'Yes'} )
        #   salary_structer.grade =self.new_grade if self.new_grade else salary_structer.grade
        #   salary_structer.main_payment =self.main_payment if self.main_payment else salary_structer.main_payment
        #   salary_structer.total_earning =self.total_earning if self.total_earning else salary_structer.total_earning
        #   salary_structer.total_deduction =self.total_deduction if self.total_deduction else salary_structer.total_deduction
        #   salary_structer.net_pay =self.net_pay if self.net_pay else salary_structer.net_pay

        #   # doc.set("packed_items", [])
        #   if self.earnings != []:
        #       salary_structer.set("earnings", [])
        #       for d in self.earnings:
        #           salary_structer.append("earnings", d)
        #   if self.deductions != [] :
        #       salary_structer.set("deductions", [])
        #       for d in self.deductions:
        #           salary_structer.append("deductions", d)

        #   salary_structer.save(ignore_permissions=True)
        # else :
        #   frappe.throw(_("Add Salary Structer for Employee")+"<a href='#List/Salary Structure'>"+_("Salary Structure")+"</a>")

        # old_jo = employee.job_opening
        # jo_list = frappe.get_list("Job Opening", fields=["name"],filters ={'name' : employee.job_opening})
        # if jo_list:
        #   jo = frappe.get_doc('Job Opening',{'name' : employee.job_opening} )
        #   jo.status ='Open'
        #   jo.save()

        old_work_start_date = employee.date_of_joining
        employee.grade = self.new_grade if self.new_grade else employee.grade
        employee.employment_type = self.new_employment_type if self.new_employment_type else employee.employment_type
        # employee.department=self.new_department if self.new_department else employee.department
        employee.designation = self.new_designation if self.new_designation else employee.designation
        employee.level = self.new_level if self.new_level else employee.level
        employee.branch = self.new_branch if self.new_branch else employee.branch
        # employee.job_opening = self.job_opening if self.job_opening else employee.job_opening
        # employee.date_of_joining= self.due_date if self.due_date else employee.date_of_joining
        # employee.work_start_date_hijri = self.due_date if self.due_date else employee.work_start_date
        # employee.scheduled_confirmation_date = self.due_date if self.due_date else employee.scheduled_confirmation_date
        # employee.scheduled_confirmation_date_hijri = self.due_date if self.due_date else employee.scheduled_confirmation_date
        employee.save()

        # jo1_list = frappe.get_list("Job Opening", fields=["name"],filters ={'name' : self.job_opening})
        # if jo1_list:
        #   jo1 = frappe.get_doc('Job Opening',{'name' : self.job_opening} )
        #   jo1.status ='Closed'
        #   jo1.save()

        old_work = frappe.new_doc(u'Employee Internal Work History', employee,
                                  u'internal_work_history')
        old_work.update(
            {
                "branch": self.branch,
                "department": self.department,
                "designation": self.designation,
                "grade": self.grade,
                "employment_type": self.employment_type,
                "level": self.level,
                "from_date": from_date,
                "to_date": add_days(self.due_date, -1)
            }
            # {
            #   "type":"Promotion",
            #   "branch": self.branch,
            #   "department":  self.department,
            #   "designation":self.designation,
            #   "grade_old": self.grade,
            #   # "job_opening":old_jo,
            #   "employment_type":self.employment_type,
            #   "new_branch": self.new_branch,
            #   "new_level": self.new_level,
            #   "new_department":  self.new_department,
            #   "new_designation":self.new_designation,
            #   "new_grade": self.new_grade,
            #   "new_employment_type":self.new_employment_type,
            #   # "new_job_opening":self.job_opening,
            #   "work_start_date":old_work_start_date,
            #   # "from_date": employee.    _confirmation_date,
            #   "to_date": self.due_date,
            #   "administrative_decision":self.name
            # }
        )
        old_work.insert()
Example #34
0
def make_payment_entry(si_dn, to_dn):

    si_doc = frappe.get_doc("Sales Invoice", si_dn)
    to_doc = frappe.get_doc("Trip Order", to_dn)
    #	child_doc_name = frappe.db.get_value('Taxi Hops', {'parent': dn}, 'name')
    #	child_doc = frappe.get_doc('Taxi Hops', child_doc_name)

    #	ToTheDestination =  frappe.db.sql("""
    #                select `to`, selected_metric, waiting, ozw, hop_price from `tabTaxi Hops` where parent like %(trip_dn)s order by idx""", {"trip_dn": dn})
    #		in (select name from `tabSalary Slip`
    #                where employee in (select employee from tabEmployee where board_member like %(brd_member)s)
    #                and start_date >= %(from_date)s and end_date <= %(end_period)s and status = 'Submitted')
    #                and abbr = 'PFCSS'
    #                """, {"brd_member": "Yes", "from_date": from_period, "end_period": to_period}, as_dict=True)

    #	make_property_setter('Sales Invoice Item', "waiting", "in_list_view", 1, "Check")
    #	make_property_setter('Sales Invoice Item', "item_code", "columns", 2, "Int")
    pe = frappe.new_doc("Payment Entry")
    pe.company = si_doc.company
    pe.posting_date = nowdate()
    pe.party_type = "Customer"
    pe.mode_of_payment = "Cash"
    pe.party = si_doc.customer
    pe.party_name = pe.party
    pe.party_balance = get_balance_on(party_type="Customer", party=pe.party)
    pe.paid_from = get_party_account("Customer", pe.party, si_doc.company)
    pe.paid_from_account_balance = get_balance_on(pe.paid_from,
                                                  date=pe.posting_date)
    from erpnext.accounts.doctype.sales_invoice.sales_invoice import get_bank_cash_account
    #	pe.paid_to = get_bank_cash_account(pe.mode_of_payment, pe.company)['account']
    pe.paid_to = frappe.db.get_value('Employee',
                                     {'name': to_doc.assigned_driver},
                                     'money_collection_account')
    pe.paid_to_account_balance = get_balance_on(pe.paid_to,
                                                date=pe.posting_date)
    #	pe.paid_to = frappe.db.get_value("Mode of Payment Account", {"parent": pe.mode_of_payment, "company": pe.company}, "default_account")
    pe.paid_from_account_currency = "LBP"
    pe.paid_to_account_currency = "LBP"
    #	pe.source_exchange_rate = 1.0
    pe.paid_amount = to_doc.cash_amount + to_doc.money_collection
    pe.received_amount = pe.paid_amount
    pe.allocate_payment_amount = 1
    pe.title = si_doc.customer

    pe.append(
        "references", {
            "reference_doctype": "Sales Invoice",
            "reference_name": si_dn,
            "due_date": si_doc.get("due_date"),
            "total_amount": si_doc.grand_total,
            "outstanding_amount": si_doc.outstanding_amount,
            "allocated_amount": to_doc.cash_amount
        })

    if to_doc.money_collection > 0:

        from erpnext.accounts.doctype.payment_entry.payment_entry import get_outstanding_reference_documents

        args = {
            "posting_date": pe.posting_date,
            "company": pe.company,
            "party_type": pe.party_type,
            "payment_type": pe.payment_type,
            "party": pe.party,
            "party_account": pe.paid_from
        }
        outstanding_docs = []
        outstanding_docs = get_outstanding_reference_documents(args)

        frappe.msgprint(_("Outstanding are: {0}").format(outstanding_docs))
        frappe.msgprint(_("Outstanding are: {0}").format(outstanding_docs[0]))
        frappe.msgprint(_("Outstanding are: {0}").format(outstanding_docs[1]))
        frappe.msgprint(
            _("Outstanding are: {0}").format(outstanding_docs[0]["due_date"]))
        frappe.msgprint(
            _("Outstanding are: {0}").format(len(outstanding_docs)))

        _money_collection = to_doc.money_collection

        for d in outstanding_docs:

            if d.voucher_no != si_dn and d.voucher_type == "Sales Invoice":

                if _money_collection > d.outstanding_amount:
                    outstanding = d.outstanding_amount
                    _money_collection = _money_collection - d.outstanding_amount
                else:
                    outstanding = _money_collection
                    _money_collection = 0
                pe.append(
                    "references", {
                        "reference_doctype": "Sales Invoice",
                        "reference_name": d.voucher_no,
                        "due_date": d.due_date,
                        "total_amount": d.invoice_amount,
                        "outstanding_amount": d.outstanding_amount,
                        "allocated_amount": outstanding
                    })
            if _money_collection == 0:
                break

    total_allocated_amount, base_total_allocated_amount = 0, 0

    for d in pe.get("references"):
        if d.allocated_amount:
            total_allocated_amount += flt(d.allocated_amount)

    pe.total_allocated_amount = abs(total_allocated_amount)
    pe.base_total_allocated_amount = pe.total_allocated_amount

    #	pe.type_of_order = "Trip Order"
    #	pe.posting_date = nowdate()

    #	for r in ToTheDestination:

    #		frappe.db.sql("""
    #                update `tabItem Price` set price_list_rate = %s where item_code = %s and selling = '1'""", (r[4], r[0]))
    #		frappe.db.commit()
    #		frappe.msgprint(_("The result of For Loop are: {0}"). format(r[0]))
    #		waiting = str(r[2])
    #		waiting = "0:00:00"
    #		frappe.msgprint(_("Waiting is: {0}"). format(waiting))
    #		frappe.msgprint(_("OZY is: {0}"). format(r[3]))
    #		frappe.msgprint(_("Hop Price: {0}"). format(r[4]))

    #		if waiting !="0:00:00":
    #			note = "waiting= " + r[2]
    #			note = "waiting=" + waiting
    #			if int(r[3]) == 1:
    #				note = "ozw&" + note
    #		elif int(r[3]) == 1:
    #				note = "ozw"
    #		else:
    #			note = ""

    #		frappe.msgprint(_("Note shape is: {0}"). format(note))
    #		pe.append("items", {
    #                	"item_code": r[0],
    #                	"qty": "1",
    #			"rate": r[4],
    #			"price_list_rate": r[4],
    #			"rate": "80000",
    #			"note": note,
    #                	"income_account": "Sales - GHYD",
    #                	"item_name": r[0],
    #                	"uom": "Unit",
    #                	"cost_center": "Main - GHYD",
    #                	"description": r[0],
    #                	"expense_account": "Cost of Goods Sold - GHYD"
    #        	})

    #        si.append("items", {
    #                "item_code": "IPCCE",
    #                "qty": "1",
    #		"income_account": "Sales - GHYD",
    #		"item_name": "IPCCE",
    #		"uom": "Unit",
    #		"cost_center": "Main - GHYD",
    #		"description": "IPCCE",
    #		"expense_account": "Cost of Goods Sold - GHYD"
    #        })

    #	frappe.msgprint(_("The To's are: {0}"). format(ToTheDestination[0]))
    #	frappe.msgprint(_("The Taxi Hops Child Name is: {0}"). format(child_doc_name))

    #	pe.flags.ignore_validate = True
    #	pe.flags.ignore_permissions = True
    pe.save()
    pe.submit()

    return pe
    def on_submit(self):
        se = frappe.new_doc("Stock Entry")
        se.purpose = "Repack"
        se.set_posting_time = 1
        se.posting_date = self.date
        se.posting_time = self.posting_time
        se.from_ball_mill = 1
        for row in self.items:
            se.append(
                'items', {
                    'item_code': row.item_name,
                    's_warehouse': row.source_warehouse,
                    'batch_no': row.batch_no,
                    'basic_rate': row.basic_rate,
                    'basic_amount': row.basic_amount,
                    'qty': row.quantity,
                })

        for d in self.packaging:
            se.append(
                'items', {
                    'item_code': self.product_name,
                    't_warehouse': self.warehouse,
                    'qty': d.qty,
                    'packaging_material': d.packaging_material,
                    'packing_size': d.packing_size,
                    'no_of_packages': d.no_of_packages,
                    'lot_no': d.lot_no,
                    'concentration': self.concentration,
                    'basic_rate': self.per_unit_amount,
                    'valuation_rate': self.per_unit_amount,
                    'basic_amount': flt(d.qty * self.per_unit_amount)
                })

        try:
            se.save()
            se.submit()
        except Exception as e:
            frappe.throw(str(e))
        else:
            self.db_set('stock_entry', se.name)

        for row in self.packaging:
            batch = frappe.db.sql("""
				SELECT sed.batch_no from `tabStock Entry` se LEFT JOIN `tabStock Entry Detail` sed on (se.name = sed.parent)
				WHERE 
					se.name = '{name}'
					and (sed.t_warehouse != '' or sed.t_warehouse IS NOT NULL) 
					and sed.qty = {qty}
					and sed.packaging_material = '{packaging_material}'
					and sed.packing_size = '{packing_size}'
					and sed.no_of_packages = {no_of_packages}""".format(
                name=se.name,
                qty=row.qty,
                packaging_material=row.packaging_material,
                packing_size=row.packing_size,
                no_of_packages=row.no_of_packages,
            ))[0][0] or ''

            if batch:
                row.db_set('batch_no', batch)
                frappe.db.set_value("Batch", batch, 'customer',
                                    self.customer_name)
                if self.lot_no:
                    frappe.db.set_value("Batch", batch, 'sample_ref_no',
                                        self.lot_no)

        frappe.db.commit()
Example #36
0
def accept(web_form, data, docname=None, for_payment=False):
    '''Save the web form'''
    data = frappe._dict(json.loads(data))
    for_payment = frappe.parse_json(for_payment)

    files = []
    files_to_delete = []

    web_form = frappe.get_doc("Web Form", web_form)

    if data.name and not web_form.allow_edit:
        frappe.throw(_("You are not allowed to update this Web Form Document"))

    frappe.flags.in_web_form = True
    meta = frappe.get_meta(data.doctype)

    if docname:
        # update
        doc = frappe.get_doc(data.doctype, docname)
    else:
        # insert
        doc = frappe.new_doc(data.doctype)

    # set values
    for field in web_form.web_form_fields:
        fieldname = field.fieldname
        df = meta.get_field(fieldname)
        value = data.get(fieldname, None)

        if df and df.fieldtype in ('Attach', 'Attach Image'):
            if value and 'data:' and 'base64' in value:
                files.append((fieldname, value))
                if not doc.name:
                    doc.set(fieldname, '')
                continue

            elif not value and doc.get(fieldname):
                files_to_delete.append(doc.get(fieldname))

        doc.set(fieldname, value)

    if for_payment:
        web_form.validate_mandatory(doc)
        doc.run_method('validate_payment')

    if doc.name:
        if has_web_form_permission(doc.doctype, doc.name, "write"):
            doc.save(ignore_permissions=True)
        else:
            # only if permissions are present
            doc.save()

    else:
        # insert
        if web_form.login_required and frappe.session.user == "Guest":
            frappe.throw(_("You must login to submit this form"))

        ignore_mandatory = True if files else False

        doc.insert(ignore_permissions=True, ignore_mandatory=ignore_mandatory)

    # add files
    if files:
        for f in files:
            fieldname, filedata = f

            # remove earlier attached file (if exists)
            if doc.get(fieldname):
                remove_file_by_url(doc.get(fieldname),
                                   doctype=doc.doctype,
                                   name=doc.name)

            # save new file
            filename, dataurl = filedata.split(',', 1)
            _file = frappe.get_doc({
                "doctype": "File",
                "file_name": filename,
                "attached_to_doctype": doc.doctype,
                "attached_to_name": doc.name,
                "content": dataurl,
                "decode": True
            })
            _file.save()

            # update values
            doc.set(fieldname, _file.file_url)

        doc.save(ignore_permissions=True)

    if files_to_delete:
        for f in files_to_delete:
            if f:
                remove_file_by_url(doc.get(fieldname),
                                   doctype=doc.doctype,
                                   name=doc.name)

    frappe.flags.web_form_doc = doc

    if for_payment:
        return web_form.get_payment_gateway_url(doc)
    else:
        return doc
 def make_program_enrollment(self):
     if not self.follow_up:
         program_enrollment = frappe.new_doc("Program Enrollment")
         program_enrollment.update({
             "student": self.student,
             "student_name": self.student_name,
             "academic_year": self.academic_year,
             "academic_term": self.academic_term,
             "program": self.program,
             "percent": self.percent,
             "student_group": self.student_group,
             "company": self.company,
             "course_application": self.name,
             "course_level": self.course_level,
             "price": self.course_level_price,
             "application": "Course"
         })
         #Link Materials
         course = frappe.get_doc("Course", {"name": self.course_level})
         for m in course.materials:
             if frappe.get_value("Item Price", {
                     "item_code": m.materials,
                     "price_list": "Standard Selling"
             }, "price_list_rate"):
                 price = frappe.get_value("Item Price", {
                     "item_code": m.materials,
                     "price_list": "Standard Selling"
                 }, "price_list_rate")
             else:
                 price = 0
             commission_rate = frappe.get_value("Item",
                                                {"name": m.materials},
                                                "commission_rate")
             program_enrollment.append(
                 "program_sales_invoice", {
                     "item": m.materials,
                     "price": price,
                     "commission_rate": commission_rate,
                     "commission_amount": price * commission_rate
                 })
         program_enrollment.append("courses", {"course": self.course_level})
         program_enrollment.save()
         program_enrollment_msg = frappe.get_doc(
             "Program Enrollment", {"course_application": self.name})
         link = [
             """<a href=desk#Form/Program%20Enrollment/{0}>{0}</a>""".
             format(program_enrollment_msg.name)
         ]
         frappe.msgprint(
             _("Program Enrollment Created - {0} As a Draft.").format(
                 comma_and(link)))
     else:
         for d in self.follow_up:
             if not d.sales_person:
                 frappe.throw("Please Enter Sales Person In Follow UP")
             else:
                 user = frappe.get_doc("User",
                                       {"name": frappe.session.user})
                 if not user.sales_person:
                     frappe.throw(
                         _("User {0} Missing Field Sales Person").format(
                             user.name))
                 else:
                     self.mpe = 1
     if self.mpe:
         program_enrollment = frappe.new_doc("Program Enrollment")
         program_enrollment.student = self.student
         program_enrollment.student_name = self.student_name
         program_enrollment.academic_year = self.academic_year
         program_enrollment.academic_term = self.academic_term
         program_enrollment.follow_up = self.follow_up
         program_enrollment.program = self.program
         program_enrollment.percent = self.percent
         program_enrollment.student_group = self.student_group
         program_enrollment.company = self.company
         program_enrollment.course_application = self.name
         program_enrollment.course_level = self.course_level
         program_enrollment.price = self.course_level_price,
         program_enrollment.application = "Course"
         program_enrollment.append("courses", {"course": self.course_level})
         #Link Materials
         course = frappe.get_doc("Course", {"name": self.course_level})
         for m in course.materials:
             if frappe.get_value("Item Price", {
                     "item_code": m.materials,
                     "price_list": "Standard Selling"
             }, "price_list_rate"):
                 price = frappe.get_value("Item Price", {
                     "item_code": m.materials,
                     "price_list": "Standard Selling"
                 }, "price_list_rate")
             else:
                 price = 0
             commission_rate = frappe.get_value("Item",
                                                {"name": m.materials},
                                                "commission_rate")
             program_enrollment.append(
                 "program_sales_invoice", {
                     "item": m.materials,
                     "price": price,
                     "commission_rate": commission_rate,
                     "commission_amount": price * commission_rate
                 })
         program_enrollment.save()
         program_enrollment_msg = frappe.get_doc(
             "Program Enrollment", {"course_application": self.name})
         link = [
             """<a href=desk#Form/Program%20Enrollment/{0}>{0}</a>""".
             format(program_enrollment_msg.name)
         ]
         frappe.msgprint(
             _("Program Enrollment Created - {0} As a Draft").format(
                 comma_and(link)))
Example #38
0
def create_error_log(call, error_code, error):
    doc = frappe.new_doc("Lazada Connector Error Log")
    doc.call = call
    doc.error_code = error_code
    doc.error_log = error
    doc.insert(ignore_permissions=True)
Example #39
0
def get_payment_entry(dt, dn, party_amount=None, bank_account=None, bank_amount=None):
	doc = frappe.get_doc(dt, dn)
	if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) > 0:
		frappe.throw(_("Can only make payment against unbilled {0}").format(dt))

	if dt in ("Sales Invoice", "Sales Order"):
		party_type = "Customer"
	elif dt in ("Purchase Invoice", "Purchase Order"):
		party_type = "Supplier"
	elif dt in ("Expense Claim", "Employee Advance"):
		party_type = "Employee"
	elif dt in ("Fees"):
		party_type = "Student"

	# party account
	if dt == "Sales Invoice":
		party_account = get_party_account_based_on_invoice_discounting(dn) or doc.debit_to
	elif dt == "Purchase Invoice":
		party_account = doc.credit_to
	elif dt == "Fees":
		party_account = doc.receivable_account
	elif dt == "Employee Advance":
		party_account = doc.advance_account
	elif dt == "Expense Claim":
		party_account = doc.payable_account
	else:
		party_account = get_party_account(party_type, doc.get(party_type.lower()), doc.company)

	party_account_currency = doc.get("party_account_currency") or get_account_currency(party_account)

	# payment type
	if (dt == "Sales Order" or (dt in ("Sales Invoice", "Fees") and doc.outstanding_amount > 0)) \
		or (dt=="Purchase Invoice" and doc.outstanding_amount < 0):
			payment_type = "Receive"
	else:
		payment_type = "Pay"

	# amounts
	grand_total = outstanding_amount = 0
	if party_amount:
		grand_total = outstanding_amount = party_amount
	elif dt in ("Sales Invoice", "Purchase Invoice"):
		if party_account_currency == doc.company_currency:
			grand_total = doc.base_rounded_total or doc.base_grand_total
		else:
			grand_total = doc.rounded_total or doc.grand_total
		outstanding_amount = doc.outstanding_amount
	elif dt in ("Expense Claim"):
		grand_total = doc.total_sanctioned_amount
		outstanding_amount = doc.total_sanctioned_amount \
			- doc.total_amount_reimbursed - flt(doc.total_advance_amount)
	elif dt == "Employee Advance":
		grand_total = doc.advance_amount
		outstanding_amount = flt(doc.advance_amount) - flt(doc.paid_amount)
	elif dt == "Fees":
		grand_total = doc.grand_total
		outstanding_amount = doc.outstanding_amount
	else:
		if party_account_currency == doc.company_currency:
			grand_total = flt(doc.get("base_rounded_total") or doc.base_grand_total)
		else:
			grand_total = flt(doc.get("rounded_total") or doc.grand_total)
		outstanding_amount = grand_total - flt(doc.advance_paid)

	# bank or cash
	bank = get_default_bank_cash_account(doc.company, "Bank", mode_of_payment=doc.get("mode_of_payment"),
		account=bank_account)

	paid_amount = received_amount = 0
	if party_account_currency == bank.account_currency:
		paid_amount = received_amount = abs(outstanding_amount)
	elif payment_type == "Receive":
		paid_amount = abs(outstanding_amount)
		if bank_amount:
			received_amount = bank_amount
	else:
		received_amount = abs(outstanding_amount)
		if bank_amount:
			paid_amount = bank_amount

	pe = frappe.new_doc("Payment Entry")
	pe.payment_type = payment_type
	pe.company = doc.company
	pe.cost_center = doc.get("cost_center")
	pe.posting_date = nowdate()
	pe.mode_of_payment = doc.get("mode_of_payment")
	pe.party_type = party_type
	pe.party = doc.get(scrub(party_type))
	pe.contact_person = doc.get("contact_person")
	pe.contact_email = doc.get("contact_email")
	pe.ensure_supplier_is_not_blocked()

	pe.paid_from = party_account if payment_type=="Receive" else bank.account
	pe.paid_to = party_account if payment_type=="Pay" else bank.account
	pe.paid_from_account_currency = party_account_currency \
		if payment_type=="Receive" else bank.account_currency
	pe.paid_to_account_currency = party_account_currency if payment_type=="Pay" else bank.account_currency
	pe.paid_amount = paid_amount
	pe.received_amount = received_amount
	pe.letter_head = doc.get("letter_head")

	if pe.party_type in ["Customer", "Supplier"]:
		bank_account = get_party_bank_account(pe.party_type, pe.party)
		pe.set("bank_account", bank_account)
		pe.set_bank_account_data()

	# only Purchase Invoice can be blocked individually
	if doc.doctype == "Purchase Invoice" and doc.invoice_is_blocked():
		frappe.msgprint(_('{0} is on hold till {1}'.format(doc.name, doc.release_date)))
	else:
		pe.append("references", {
			'reference_doctype': dt,
			'reference_name': dn,
			"bill_no": doc.get("bill_no"),
			"due_date": doc.get("due_date"),
			'total_amount': grand_total,
			'outstanding_amount': outstanding_amount,
			'allocated_amount': outstanding_amount
		})

	pe.setup_party_account_field()
	pe.set_missing_values()
	if party_account and bank:
		pe.set_exchange_rate()
		pe.set_amounts()
	return pe
Example #40
0
def make_test_doc():
    d = frappe.new_doc('ToDo')
    d.description = 'Test'
    d.save()
    return d.doctype, d.name
Example #41
0
def fetch_att():
    from_date = (datetime.strptime('2019-02-26', '%Y-%m-%d')).date()
    to_date = (datetime.strptime('2019-02-26', '%Y-%m-%d')).date()
    for preday in daterange(from_date, to_date):
        day = preday.strftime("%d%m%Y")
        exc = frappe.db.get_list("Auto Present Employees", fields=['employee'])
        auto_present_list = []
        for e in exc:
            auto_present_list.append(e.employee)
        employees = frappe.get_all('Employee', {'status': 'Active'})
        for emp in employees:
            if emp.name in auto_present_list:
                doc = frappe.get_doc("Employee", emp.name)
                attendance = frappe.db.exists("Attendance", {
                    "employee": doc.employee,
                    "attendance_date": preday
                })
                if attendance:
                    frappe.db.set_value("Attendance", attendance, "status",
                                        "Present")
                    frappe.db.commit()
                else:
                    attendance = frappe.new_doc("Attendance")
                    attendance.employee = doc.employee
                    attendance.employee_name = doc.employee_name
                    attendance.status = "Present"
                    attendance.attendance_date = preday
                    # attendance.company = doc.company
                    attendance.working_shift = frappe.get_value(
                        "Employee", emp.name, "working_shift"),
                    attendance.late_in = "00:00:00"
                    attendance.work_time = "00:00:00"
                    attendance.early_out = "00:00:00"
                    attendance.overtime = "00:00:00"
                    attendance.save(ignore_permissions=True)
                    attendance.submit()
                    frappe.db.commit()
            else:
                url = 'http://182.72.89.102/cosec/api.svc/v2/attendance-daily?action=get;field-name=userid,ProcessDate,firsthalf,\
                        secondhalf,punch1,punch2,workingshift,shiftstart,shiftend,latein,earlyout,worktime,overtime;date-range=%s-%s;range=user;id=%s;format=xml' % (
                    day, day, emp.name)
                r = requests.get(url, auth=('sa', 'matrixx'))
                if "No records found" in r.content:
                    attendance_id = frappe.db.exists(
                        "Attendance", {
                            "employee": emp.name,
                            "attendance_date": preday,
                            "docstatus": 1
                        })
                    if attendance_id:
                        pass
                    else:
                        attendance = frappe.new_doc("Attendance")
                        attendance.update({
                            "employee":
                            emp.name,
                            "attendance_date":
                            preday,
                            "status":
                            'Absent',
                            "late_in":
                            "0:00:00",
                            "early_out":
                            "0:00:00",
                            "working_shift":
                            frappe.get_value("Employee", emp.name,
                                             "working_shift"),
                            "work_time":
                            "0:00:00",
                            "overtime":
                            "0:00:00"
                        })
                        attendance.save(ignore_permissions=True)
                        attendance.submit()
                        frappe.db.commit()
                else:
                    if not "failed: 0010102003" in r.content:
                        root = ET.fromstring(r.content)
                        for att in root.findall('attendance-daily'):
                            userid = att.find('UserID').text
                            in_time = att.find('Punch1').text
                            out_time = att.find('Punch2').text
                            first_half_status = att.find('firsthalf').text
                            second_half_status = att.find('secondhalf').text
                            date = datetime.strptime(
                                (att.find('ProcessDate').text.replace(
                                    "/", "")), "%d%m%Y").date()
                            date_f = date.strftime("%Y-%m-%d")
                            if flt(att.find('WorkTime').text) > 1440:
                                work_time = timedelta(minutes=flt('1400'))
                            else:
                                work_time = timedelta(
                                    minutes=flt(att.find('WorkTime').text))
                            over_time = timedelta(
                                minutes=flt(att.find('Overtime').text))
                            late_in = timedelta(
                                minutes=flt(att.find('LateIn').text))
                            early_out = timedelta(
                                minutes=flt(att.find('EarlyOut').text))
                            working_shift = att.find('WorkingShift').text
                            attendance_id = frappe.db.exists(
                                "Attendance", {
                                    "employee": emp.name,
                                    "attendance_date": date_f,
                                    "docstatus": 1
                                })

                            if out_time:
                                out_time_f = datetime.strptime(
                                    out_time, "%d/%m/%Y %H:%M:%S")
                            if in_time:
                                in_time_f = datetime.strptime(
                                    in_time, "%d/%m/%Y %H:%M:%S")
                            if in_time and out_time:
                                work_time = out_time_f - in_time_f
                            wt_seconds = work_time.total_seconds() // 60
                            if wt_seconds > 1440:
                                work_time = timedelta(minutes=flt('1400'))

                            if work_time >= timedelta(hours=4):
                                if work_time < timedelta(hours=7, minutes=45):
                                    status = 'Half Day'
                                else:
                                    status = 'Present'
                            else:
                                status = 'Absent'

                            # print userid
                            # print in_time
                            # print out_time
                            # print work_time
                            # print day
                            if attendance_id:
                                attendance = frappe.get_doc(
                                    "Attendance", attendance_id)
                                attendance.out_time = out_time
                                attendance.in_time = in_time
                                attendance.status = status
                                attendance.first_half_status = first_half_status
                                attendance.second_half_status = second_half_status
                                attendance.late_in = late_in
                                attendance.early_out = early_out
                                attendance.working_shift = working_shift
                                attendance.work_time = work_time
                                attendance.overtime = over_time
                                attendance.db_update()
                                frappe.db.commit()
                            else:
                                attendance = frappe.new_doc("Attendance")
                                attendance.update({
                                    "employee": emp.name,
                                    "attendance_date": date_f,
                                    "status": status,
                                    "in_time": in_time,
                                    "late_in": late_in,
                                    "early_out": early_out,
                                    "working_shift": working_shift,
                                    "out_time": out_time,
                                    "work_time": work_time,
                                    "overtime": over_time
                                })
                                attendance.save(ignore_permissions=True)
                                attendance.submit()
                                frappe.db.commit()
def create_attribut(name):
    igroup = frappe.new_doc("Item Attribute")
    igroup.attribute_name = name
    igroup.insert(ignore_permissions=True)
Example #43
0
    def make_accrual_jv_entry(self):
        self.check_permission('write')
        earnings = self.get_salary_component_total(
            component_type="earnings") or {}
        deductions = self.get_salary_component_total(
            component_type="deductions") or {}
        default_payroll_payable_account = self.get_default_payroll_payable_account(
        )
        loan_details = self.get_loan_details()
        jv_name = ""
        precision = frappe.get_precision("Journal Entry Account",
                                         "debit_in_account_currency")

        if earnings or deductions:
            journal_entry = frappe.new_doc('Journal Entry')
            journal_entry.voucher_type = 'Journal Entry'
            journal_entry.user_remark = _('Accrual Journal Entry for salaries from {0} to {1}')\
             .format(self.start_date, self.end_date)
            journal_entry.company = self.company
            journal_entry.posting_date = self.posting_date

            accounts = []
            payable_amount = 0

            # Earnings
            for acc, amount in earnings.items():
                payable_amount += flt(amount, precision)
                accounts.append({
                    "account":
                    acc,
                    "debit_in_account_currency":
                    flt(amount, precision),
                    "cost_center":
                    self.cost_center,
                    "project":
                    self.project
                })

            # Deductions
            for acc, amount in deductions.items():
                payable_amount -= flt(amount, precision)
                accounts.append({
                    "account":
                    acc,
                    "credit_in_account_currency":
                    flt(amount, precision),
                    "cost_center":
                    self.cost_center,
                    "project":
                    self.project
                })

            # Loan
            for data in loan_details:
                accounts.append({
                    "account":
                    data.loan_account,
                    "credit_in_account_currency":
                    data.principal_amount
                })

                if data.interest_amount and not data.interest_income_account:
                    frappe.throw(
                        _("Select interest income account in loan {0}").format(
                            data.loan))

                if data.interest_income_account and data.interest_amount:
                    accounts.append({
                        "account": data.interest_income_account,
                        "credit_in_account_currency": data.interest_amount,
                        "cost_center": self.cost_center,
                        "project": self.project
                    })
                payable_amount -= flt(data.total_payment, precision)

            # Payable amount
            accounts.append({
                "account":
                default_payroll_payable_account,
                "credit_in_account_currency":
                flt(payable_amount, precision)
            })

            journal_entry.set("accounts", accounts)
            journal_entry.title = default_payroll_payable_account
            journal_entry.save()

            try:
                journal_entry.submit()
                jv_name = journal_entry.name
                self.update_salary_slip_status(jv_name=jv_name)
            except Exception as e:
                frappe.msgprint(e)

        return jv_name
Example #44
0
def make_salary_slip(source_name, target_doc=None):
    target = frappe.new_doc("Salary Slip")
    set_missing_values(source_name, target)
    target.run_method("get_emp_and_leave_details")

    return target
Example #45
0
def get_payment_entry(ref_doc, args):
    cost_center = frappe.db.get_value("Company", ref_doc.company,
                                      "cost_center")
    exchange_rate = 1
    if args.get("party_account"):
        exchange_rate = get_exchange_rate(args.get("party_account"),
                                          args.get("party_account_currency"),
                                          ref_doc.company, ref_doc.doctype,
                                          ref_doc.name)

    je = frappe.new_doc("Journal Entry")
    je.update({
        "voucher_type": "Bank Entry",
        "company": ref_doc.company,
        "remark": args.get("remarks")
    })

    party_row = je.append("accounts", {
     "account": args.get("party_account"),
     "party_type": args.get("party_type"),
     "party": ref_doc.get(args.get("party_type").lower()),
     "cost_center": cost_center,
     "account_type": frappe.db.get_value("Account", args.get("party_account"), "account_type"),
     "account_currency": args.get("party_account_currency") or \
      get_account_currency(args.get("party_account")),
     "balance": get_balance_on(args.get("party_account")),
     "party_balance": get_balance_on(party=args.get("party"), party_type=args.get("party_type")),
     "exchange_rate": exchange_rate,
     args.get("amount_field_party"): args.get("amount"),
     "is_advance": args.get("is_advance"),
     "reference_type": ref_doc.doctype,
     "reference_name": ref_doc.name
    })

    bank_row = je.append("accounts")

    #make it bank_details
    bank_account = get_default_bank_cash_account(
        ref_doc.company, "Bank", account=args.get("bank_account"))
    if bank_account:
        bank_row.update(bank_account)
        bank_row.exchange_rate = get_exchange_rate(
            bank_account["account"], bank_account["account_currency"],
            ref_doc.company)

    bank_row.cost_center = cost_center

    amount = args.get("debit_in_account_currency") or args.get("amount")

    if bank_row.account_currency == args.get("party_account_currency"):
        bank_row.set(args.get("amount_field_bank"), amount)
    else:
        bank_row.set(args.get("amount_field_bank"), amount * exchange_rate)

    # set multi currency check
    if party_row.account_currency != ref_doc.company_currency \
     or (bank_row.account_currency and bank_row.account_currency != ref_doc.company_currency):
        je.multi_currency = 1

    je.set_amounts_in_company_currency()
    je.set_total_debit_credit()

    return je if args.get("journal_entry") else je.as_dict()
Example #46
0
def get_pos_data():
    doc = frappe.new_doc('Sales Invoice')
    doc.is_pos = 1
    pos_profile = get_pos_profile(doc.company) or {}
    if not pos_profile:
        frappe.throw(_("POS Profile is required to use Point-of-Sale"))

    if not doc.company:
        doc.company = pos_profile.get('company')

    doc.update_stock = pos_profile.get('update_stock')

    if pos_profile.get('name'):
        pos_profile = frappe.get_doc('POS Profile', pos_profile.get('name'))
        pos_profile.validate()

    company_data = get_company_data(doc.company)
    update_pos_profile_data(doc, pos_profile, company_data)
    update_multi_mode_option(doc, pos_profile)
    default_print_format = pos_profile.get('print_format') or "Point of Sale"
    print_template = frappe.db.get_value('Print Format', default_print_format,
                                         'html')
    items_list = get_items_list(pos_profile, doc.company)
    customers = get_customers_list(pos_profile)

    doc.plc_conversion_rate = update_plc_conversion_rate(doc, pos_profile)

    return {
        'doc':
        doc,
        'default_customer':
        pos_profile.get('customer'),
        'items':
        items_list,
        'item_groups':
        get_item_groups(pos_profile),
        'customers':
        customers,
        'address':
        get_customers_address(customers),
        'contacts':
        get_contacts(customers),
        'serial_no_data':
        get_serial_no_data(pos_profile, doc.company),
        'batch_no_data':
        get_batch_no_data(),
        'barcode_data':
        get_barcode_data(items_list),
        'tax_data':
        get_item_tax_data(),
        'price_list_data':
        get_price_list_data(doc.selling_price_list, doc.plc_conversion_rate),
        'customer_wise_price_list':
        get_customer_wise_price_list(),
        'bin_data':
        get_bin_data(pos_profile),
        'pricing_rules':
        get_pricing_rule_data(doc),
        'print_template':
        print_template,
        'pos_profile':
        pos_profile,
        'meta':
        get_meta()
    }
Example #47
0
def remove_abos_on_case_ok(case1,
                           case2,
                           case3,
                           case4,
                           winter_ed=0,
                           feb_ed=0,
                           mar_ed=0,
                           apr_ed=0,
                           may_ed=0,
                           jun_ed=0,
                           summer_ed=0,
                           sept_ed=0,
                           okt_ed=0,
                           nov_ed=0):
    import json
    if isinstance(case1, basestring):
        case1 = json.loads(case1)
    if isinstance(case2, basestring):
        case2 = json.loads(case2)
    if isinstance(case3, basestring):
        case3 = json.loads(case3)
    if isinstance(case4, basestring):
        case4 = json.loads(case4)
    #frappe.throw(str(kunden))
    #idx = 1
    for kunde in case1:
        #frappe.publish_realtime('remove_all_abos_task', {"progress": [idx, len(kunden)]}, user=frappe.session.user)
        #idx = idx + 1
        abos = frappe.db.sql(
            """SELECT `name` FROM `tabPflanzenfreund Abo` WHERE `customer` = '{kunde}' AND `docstatus` = 1 AND `abo_type` IN ('Gratis-Abo', 'VIP-Abo', 'Kundenkarten-Abo (KK)', 'Kunden-Abo (OK)')"""
            .format(kunde=kunde),
            as_dict=True)
        for _abo in abos:
            abo = frappe.get_doc("Pflanzenfreund Abo", _abo.name)
            abo.cancel()

    for kunde in case2:
        #frappe.publish_realtime('remove_all_abos_task', {"progress": [idx, len(kunden)]}, user=frappe.session.user)
        #idx = idx + 1
        abos = frappe.db.sql(
            """SELECT `name` FROM `tabPflanzenfreund Abo` WHERE `customer` = '{kunde}' AND `docstatus` = 1 AND `abo_type` = 'Kunden-Abo (OK)'"""
            .format(kunde=kunde),
            as_dict=True)
        for _abo in abos:
            abo = frappe.get_doc("Pflanzenfreund Abo", _abo.name)
            abo.cancel()

    #ANLAGE KK ABO!!!!
    for kunde in case3:
        adresse = frappe.db.sql(
            """SELECT `parent` FROM `tabDynamic Link` WHERE `parenttype` = 'Address' AND `parentfield` = 'links' AND `idx` = '1' AND `link_doctype` = 'Customer' AND `link_name` = '{kunde}'"""
            .format(kunde=kunde),
            as_list=True)[0][0]
        abo = frappe.new_doc("Pflanzenfreund Abo")
        abo.update({
            "customer": kunde,
            "customer_address": adresse,
            "abo_type": "Kunden-Abo (OK)",
            "start_date": today(),
            "set_ed_manual": 1,
            "winter_ed": winter_ed,
            "feb_ed": feb_ed,
            "mar_ed": mar_ed,
            "apr_ed": apr_ed,
            "may_ed": may_ed,
            "jun_ed": jun_ed,
            "summer_ed": summer_ed,
            "sept_ed": sept_ed,
            "oct_ed": okt_ed,
            "nov_ed": nov_ed
        })
        abo.insert(ignore_permissions=True)
        abo.submit()

    for kunde in case4:
        #frappe.publish_realtime('remove_all_abos_task', {"progress": [idx, len(kunden)]}, user=frappe.session.user)
        #idx = idx + 1
        abos = frappe.db.sql(
            """SELECT `name` FROM `tabPflanzenfreund Abo` WHERE `customer` = '{kunde}' AND `docstatus` = 1 AND `abo_type` = 'Kundenkarten-Abo (KK)'"""
            .format(kunde=kunde),
            as_dict=True)
        for _abo in abos:
            abo = frappe.get_doc("Pflanzenfreund Abo", _abo.name)
            abo.cancel()
    return "OK"
Example #48
0
def setup_warehouse():
	w = frappe.new_doc('Warehouse')
	w.warehouse_name = 'Supplier'
	w.insert()
Example #49
0
def print_via_printnode(action, **kwargs):
    settings = frappe.get_doc("Print Node Settings", "Print Node Settings")
    if not settings.api_key:
        frappe.throw(
            _("Your Print Node API Key is not configured in Print Node Settings"
              ))
    if not frappe.db.exists("Print Node Action", action):
        frappe.throw(
            _("Unable to find an action in Print settings to execute this print"
              ))
    else:
        action = frappe.get_doc("Print Node Action", action)

    if action.get("capabilities"):
        print_settings = json.loads(action.capabilities)
    else:
        print_settings = {}

    if 'collate' in print_settings:
        print_settings['collate'] = bool(print_settings['collate'])

    printer = frappe.db.get_value("Print Node Hardware", action.printer,
                                  "hw_id")

    gateway = Gateway(apikey=settings.api_key)

    if action.printable_type == "Print Format":
        print_content = get_print_content(
            action.print_format if not action.use_standard else "Standard",
            kwargs.get("doctype"), kwargs.get("docname"),
            action.is_xml_esc_pos, action.is_raw_text)
        raw = action.is_xml_esc_pos or action.is_raw_text
        gateway.PrintJob(printer=int(printer),
                         job_type="raw" if raw else "pdf",
                         title=action.action,
                         base64=print_content,
                         options=print_settings)
    else:
        print_content = b64encode(get_file(kwargs.get("filename", ""))[1])
        gateway.PrintJob(
            printer=int(printer),
            job_type="pdf"
            if kwargs.get("filename", "").lower().endswith(".pdf") else "raw",
            base64=print_content,
            options=print_settings)

    job = frappe.new_doc("Print Node Job").update({
        "print_node_action":
        action.name,
        "printer_id":
        action.printer,
        "print_type":
        "File" if action.printable_type == "Attachment" else "Print Format",
        "file_link":
        kwargs.get("filename"),
        "print_format":
        action.print_format if not action.use_standard else "Standard",
        "ref_type":
        kwargs.get("doctype"),
        "ref_name":
        kwargs.get("docname"),
        "is_xml_esc_pos":
        action.is_xml_esc_pos,
        "is_raw_text":
        action.is_raw_text,
        "print_job_name":
        action.action,
        "copies":
        print_settings.get('copies', 1),
        "job_owner":
        frappe.local.session.user,
        "print_timestamp":
        now_datetime()
    })
    job.flags.ignore_permissions = True
    job.flags.ignore_links = True
    job.flags.ignore_validate = True
    job.insert()
Example #50
0
    def sync_tasks(self):
        """sync tasks and remove table"""
        if not hasattr(self, "deleted_task_list"):
            self.set("deleted_task_list", [])

        if self.flags.dont_sync_tasks: return
        task_names = []

        existing_task_data = {}

        fields = [
            "title", "status", "start_date", "end_date", "description",
            "task_weight", "task_id"
        ]
        exclude_fieldtype = [
            "Button", "Column Break", "Section Break", "Table", "Read Only",
            "Attach", "Attach Image", "Color", "Geolocation", "HTML", "Image"
        ]

        custom_fields = frappe.get_all(
            "Custom Field", {
                "dt": "Project Task",
                "fieldtype": ("not in", exclude_fieldtype)
            }, "fieldname")

        for d in custom_fields:
            fields.append(d.fieldname)

        for d in frappe.get_all('Project Task',
                                fields=fields,
                                filters={'parent': self.name}):
            existing_task_data.setdefault(d.task_id, d)

        for t in self.tasks:
            if t.task_id:
                task = frappe.get_doc("Task", t.task_id)
            else:
                task = frappe.new_doc("Task")
                task.project = self.name

            if not t.task_id or self.is_row_updated(t, existing_task_data,
                                                    fields):
                task.update({
                    "subject": t.title,
                    "status": t.status,
                    "exp_start_date": t.start_date,
                    "exp_end_date": t.end_date,
                    "description": t.description,
                    "task_weight": t.task_weight
                })

                self.map_custom_fields(t, task, custom_fields)

                task.flags.ignore_links = True
                task.flags.from_project = True
                task.flags.ignore_feed = True

                if t.task_id:
                    task.update({
                        "modified_by": frappe.session.user,
                        "modified": now()
                    })

                    task.run_method("validate")
                    task.db_update()
                else:
                    task.save(ignore_permissions=True)
                task_names.append(task.name)
            else:
                task_names.append(task.name)

        # delete
        for t in frappe.get_all("Task", ["name"], {
                "project": self.name,
                "name": ("not in", task_names)
        }):
            self.deleted_task_list.append(t.name)
Example #51
0
def make_purchase_receipt(**args):
    if not frappe.db.exists('Location', 'Test Location'):
        frappe.get_doc({
            'doctype': 'Location',
            'location_name': 'Test Location'
        }).insert()

    frappe.db.set_value("Buying Settings", None, "allow_multiple_items", 1)
    pr = frappe.new_doc("Purchase Receipt")
    args = frappe._dict(args)
    pr.posting_date = args.posting_date or today()
    if args.posting_time:
        pr.posting_time = args.posting_time
    if args.posting_date or args.posting_time:
        pr.set_posting_time = 1
    pr.company = args.company or "_Test Company"
    pr.supplier = args.supplier or "_Test Supplier"
    pr.is_subcontracted = args.is_subcontracted or "No"
    pr.supplier_warehouse = args.supplier_warehouse or "_Test Warehouse 1 - _TC"
    pr.currency = args.currency or "INR"
    pr.is_return = args.is_return
    pr.return_against = args.return_against
    qty = args.qty or 5
    received_qty = args.received_qty or qty
    rejected_qty = args.rejected_qty or flt(received_qty) - flt(qty)

    item_code = args.item or args.item_code or "_Test Item"
    uom = args.uom or frappe.db.get_value("Item", item_code,
                                          "stock_uom") or "_Test UOM"
    pr.append(
        "items", {
            "item_code":
            item_code,
            "warehouse":
            args.warehouse or "_Test Warehouse - _TC",
            "qty":
            qty,
            "received_qty":
            received_qty,
            "rejected_qty":
            rejected_qty,
            "rejected_warehouse":
            args.rejected_warehouse or "_Test Rejected Warehouse - _TC"
            if rejected_qty != 0 else "",
            "rate":
            args.rate if args.rate != None else 50,
            "conversion_factor":
            args.conversion_factor or 1.0,
            "serial_no":
            args.serial_no,
            "stock_uom":
            args.stock_uom or "_Test UOM",
            "uom":
            uom,
            "cost_center":
            args.cost_center
            or frappe.get_cached_value('Company', pr.company, 'cost_center'),
            "asset_location":
            args.location or "Test Location"
        })

    if args.get_multiple_items:
        pr.items = []
        for item in get_items(warehouse=args.warehouse,
                              cost_center=args.cost_center
                              or frappe.get_cached_value(
                                  'Company', pr.company, 'cost_center')):
            pr.append("items", item)

    if args.get_taxes_and_charges:
        for tax in get_taxes():
            pr.append("taxes", tax)

    if not args.do_not_save:
        pr.insert()
        if not args.do_not_submit:
            pr.submit()
    return pr
Example #52
0
 def save_version(self):
     '''Save version info'''
     version = frappe.new_doc('Version')
     if version.set_diff(self._doc_before_save, self):
         version.insert(ignore_permissions=True)
Example #53
0
def make_sales_invoice(dt, dn):

    doc = frappe.get_doc(dt, dn)
    if not frappe.db.get_value('Employee', {'name': doc.assigned_driver},
                               'money_collection_account'):
        frappe.throw(
            _("Money Collection Account need to be set for Employee: {0} of the ID: {1}"
              ).format(doc.driver_name, doc.assigned_driver))

    si_dn = frappe.db.get_value('Sales Invoice Item', {'trip_order': dn},
                                'parent')
    if si_dn:
        return frappe.get_doc("Sales Invoice", si_dn)

#	doc = frappe.get_doc(dt, dn)
    child_doc_name = frappe.db.get_value('Taxi Hops', {'parent': dn}, 'name')
    child_doc = frappe.get_doc('Taxi Hops', child_doc_name)

    ToTheDestination = frappe.db.sql(
        """
                select name, `to`, selected_metric, waiting, ozw, hop_price from `tabTaxi Hops` where parent like %(trip_dn)s order by idx""",
        {"trip_dn": dn})
    #		in (select name from `tabSalary Slip`
    #                where employee in (select employee from tabEmployee where board_member like %(brd_member)s)
    #                and start_date >= %(from_date)s and end_date <= %(end_period)s and status = 'Submitted')
    #                and abbr = 'PFCSS'
    #                """, {"brd_member": "Yes", "from_date": from_period, "end_period": to_period}, as_dict=True)

    #	make_property_setter('Sales Invoice Item', "waiting", "in_list_view", 1, "Check")
    #	make_property_setter('Sales Invoice Item', "item_code", "columns", 2, "Int")

    #        si_dn = frappe.db.get_value('Sales Invoice Item', {'trip_order': dn}, 'parent')
    #        if si_dn:
    #                si = frappe.get_doc("Sales Invoice", si_dn)
    #	else:
    si = frappe.new_doc("Sales Invoice")
    si.customer = doc.customer
    si.title = doc.customer
    si.type_of_order = "Trip Order"
    si.due_date = nowdate()

    for r in ToTheDestination:

        frappe.db.sql(
            """
                update `tabItem Price` set price_list_rate = %s where item_code = %s and selling = '1'""",
            (r[5], r[1]))
        frappe.db.commit()
        #		frappe.msgprint(_("The result of For Loop are: {0}"). format(r[0]))
        waiting = str(r[3])
        #		waiting = "0:00:00"
        #		frappe.msgprint(_("Waiting is: {0}"). format(waiting))
        #		frappe.msgprint(_("OZY is: {0}"). format(r[3]))
        #		frappe.msgprint(_("Hop Price: {0}"). format(r[4]))

        if waiting != "0:00:00":
            #			note = "waiting= " + r[2]
            note = "waiting=" + waiting
            if int(r[4]) == 1:
                note = "ozw&" + note
        elif int(r[4]) == 1:
            note = "ozw"
        else:
            note = ""

#		frappe.msgprint(_("Note shape is: {0}"). format(note))
        si.append(
            "items",
            {
                "item_code": r[1],
                "qty": "1",
                "rate": r[5],
                "price_list_rate": r[5],
                #			"rate": "80000",
                "note": note,
                "income_account": "Sales - GHYD",
                "item_name": r[1],
                "uom": "Unit",
                "cost_center": "Main - GHYD",
                "description": r[1],
                "to_detail": r[0],
                "trip_order": dn,
                "expense_account": "Cost of Goods Sold - GHYD"
            })

        si.additional_discount_percentage = doc.discounted_percentage


#        si.append("items", {
#                "item_code": "IPCCE",
#                "qty": "1",
#		"income_account": "Sales - GHYD",
#		"item_name": "IPCCE",
#		"uom": "Unit",
#		"cost_center": "Main - GHYD",
#		"description": "IPCCE",
#		"expense_account": "Cost of Goods Sold - GHYD"
#        })

#	frappe.msgprint(_("The To's are: {0}"). format(ToTheDestination[0]))
#	frappe.msgprint(_("The Taxi Hops Child Name is: {0}"). format(child_doc_name))

    si.save()
    si.submit()

    return si
 def make_salary_structure(self):
     ss_list = frappe.db.sql(
         """select parent from `tabSalary Structure Employee` where 
         employee = '{0}' and parenttype = 'Salary Structure'""".format(
             self.employee),
         as_dict=True)
     for ss in ss_list:
         if ss_list:
             salary_info = self.get_salary_slip_data()
             old_ss = frappe.get_doc("Salary Structure", {
                 "name": ss.parent,
                 "is_active": "Yes"
             })
             new_ss = frappe.new_doc("Salary Structure")
             new_ss.name = make_autoname("Promotion-" + self.employee +
                                         '-.####')
             employee_info = {
                 "employee": self.employee,
                 "grade": self.new_grade,
                 "level": self.new_level,
                 "from_date": self.due_date,
                 "base": self.new_base
             }
             new_ss.set("earnings", old_ss.get("earnings"))
             earnings = []
             deductions = []
             for old_earnings in old_ss.get("earnings"):
                 earning = {
                     "salary_component": old_earnings.salary_component,
                     "condition": old_earnings.condition,
                     "formula": old_earnings.formula,
                     "amount_based_on_formula":
                     old_earnings.amount_based_on_formula,
                     "amount": old_earnings.amount,
                     "depends_on_lwp": old_earnings.depends_on_lwp,
                     "default_amount": old_earnings.default_amount
                 }
                 earnings.append(earnings)
             for old_deduction in old_ss.get("deductions"):
                 deduction = {
                     "salary_component": old_deduction.salary_component,
                     "condition": old_deduction.condition,
                     "formula": old_deduction.formula,
                     "amount_based_on_formula": 0,
                     "amount": old_deduction.amount,
                     "depends_on_lwp": old_deduction.depends_on_lwp,
                     "default_amount": old_deduction.default_amount
                 }
                 if old_deduction.salary_component == "GOSI":
                     # new_gosi = dict(old_deduction)
                     deduction["formula"] = "(B+H)*.1"
                     deduction["amount_based_on_formula"] = 0
                     for component in salary_info["deductions"]:
                         if component.salary_component == "GOSI":
                             deduction["amount"] = component.amount
                 deductions.append(deduction)
             new_ss.set("employees", [employee_info])
             new_ss.set("deductions", deductions)
             if getdate(self.due_date) > getdate(nowdate()):
                 new_ss.is_active = "No"
             new_ss.payment_account = old_ss.payment_account
             new_ss.save(ignore_permissions=True)
Example #55
0
def create(kind, owner, users=None, name=None):
    authenticate(owner)

    users = safe_json_loads(users)
    create = True

    if kind == 'Visitor':
        room = squashify(
            frappe.db.sql("""
			SELECT name
			FROM   `tabChat Room`
			WHERE  owner = "{owner}"
		""".format(owner=owner),
                          as_dict=True))

        if room:
            room = frappe.get_doc('Chat Room', room.name)
            create = False

    if create:
        room = frappe.new_doc('Chat Room')
        room.type = kind
        room.owner = owner
        room.room_name = name

    dusers = []

    if kind != 'Visitor':
        if users:
            users = listify(users)
            for user in users:
                duser = frappe.new_doc('Chat Room User')
                duser.user = user
                dusers.append(duser)

            room.users = dusers
    else:
        dsettings = frappe.get_single('Website Settings')
        room.room_name = dsettings.chat_room_name

        users = [user for user in room.users] if hasattr(room, 'users') else []

        for user in dsettings.chat_operators:
            if user.user not in users:
                # appending user to room.users will remove the user from chat_operators
                # this is undesirable, create a new Chat Room User instead
                chat_room_user = {
                    "doctype": "Chat Room User",
                    "user": user.user
                }
                room.append('users', chat_room_user)

    room.save(ignore_permissions=True)

    room = get(owner, rooms=room.name)
    users = [room.owner] + [u for u in room.users]

    for u in users:
        frappe.publish_realtime('frappe.chat.room:create',
                                room,
                                user=u,
                                after_commit=True)

    return room
Example #56
0
    def before_submit(self):
        for d in self.service_detail:
            if d.type == "Change from Inventory" or d.type == "Change at Garage":
                old_part = get_doc("Truck Parts Inventory", d.part_no)
                old_part.part_status = "Available"
                old_part.truck_no = ""
                old_part.warehouse = d.warehouse
                old_part.save()

                if d.type == "Change from Inventory":
                    if not d.new_part_no:
                        throw(
                            _("Please provide New Part No. in row %d" % d.idx))

                    update_part = get_doc("Truck Parts Inventory",
                                          d.new_part_no)
                    update_part.part_status = "In Use"
                    update_part.truck_no = self.truck_no
                    update_part.save()
                else:
                    if not d.serial_number:
                        throw(
                            _("Please provide serial number in row %d" %
                              d.idx))
                    elif not d.part_company:
                        throw(
                            _("Please provide part company in row %d" % d.idx))
                    elif not d.purchase_rate:
                        throw(
                            _("Please provide purchase rate in row %d" %
                              d.idx))
                    elif not d.purchase_date:
                        throw(
                            _("Please provide purchase date in row %d" %
                              d.idx))
                    elif not d.new_part_link:
                        inventory = new_doc("Truck Parts Inventory")
                        inventory.truck_part = d.service_item
                        inventory.part_company = d.part_company
                        inventory.warehouse = d.warehouse
                        inventory.purchase_through = "Maintenance Log"
                        inventory.ref_link = self.name
                        inventory.purchase_rate = d.purchase_rate
                        inventory.purchase_date = d.purchase_date
                        inventory.serial_number = d.serial_number
                        inventory.title = d.service_item + "-" + d.serial_number
                        inventory.part_status = "In Use"
                        inventory.truck_no = self.truck_no
                        inventory.save()
                        d.new_part_link = inventory.name

                db.commit()

        stock_entry = None
        cost_center = db.get_value("Company", self.company, "cost_center")
        for d in self.consumable_details:
            if d.from_inventory:
                if not d.warehouse:
                    throw(
                        _("Please provide warehouse in row %d of Consumable Service Table"
                          % d.idx))
                else:
                    if not stock_entry:
                        stock_entry = new_doc("Stock Entry")
                        stock_entry.company = self.company
                        stock_entry.purpose = "Material Issue"
                        stock_entry.append(
                            "items", {
                                "s_warehouse": d.warehouse,
                                "item_code": d.item_code,
                                "qty": d.used_qty,
                                "expense_account": self.expense_account,
                                "cost_center": cost_center
                            })
                    else:
                        stock_entry.append(
                            "items", {
                                "s_warehouse": d.warehouse,
                                "item_code": d.item_code,
                                "qty": d.used_qty,
                                "expense_account": self.expense_account,
                                "cost_center": cost_center
                            })

        if stock_entry:
            stock_entry.save()
            stock_entry.submit()
            db.commit()
            url = get_url_to_form("Stock Entry", stock_entry.name)
            idx = url.find("/desk#")
            stock_entry_url = url[:idx] + ":8081" + url[idx:]
            link = "<b><a href='{url}'>{name}</a></b>".format(
                url=stock_entry_url, name=stock_entry.name)
            msgprint(_("New Stock Entry {0} created!".format(link)),
                     title="Success",
                     indicator='green')
Example #57
0
def make_cancelled_gl_entry(entry):
    gl_entry = frappe.new_doc('GL Entry')
    gl_entry.update(entry)
    gl_entry.insert()
    gl_entry.submit()
    def make_journal_entry(self,
                           account1,
                           account2,
                           amount,
                           action_status,
                           posting_date=None,
                           party_type=None,
                           party=None,
                           cost_center=None,
                           save=True,
                           submit=False):
        cost_center_project = cost_center
        if self.project:
            cost_center_project = frappe.db.get_value("Project", self.project,
                                                      "cost_center")
        jv = frappe.new_doc("Journal Entry")
        jv.posting_date = posting_date or nowdate()
        jv.company = self.company
        jv.cheque_no = self.cheque_no
        jv.cheque_date = self.cheque_date
        jv.user_remark = self.remarks or "Cheque Transaction"
        jv.multi_currency = 0
        jv.set("accounts", [{
            "account":
            account1,
            "party_type":
            party_type if (action_status == "Cheque Cancelled"
                           or action_status == "Cheque Rejected") else None,
            "party":
            party if action_status == "Cheque Cancelled" else None,
            "cost_center":
            cost_center_project,
            "project":
            self.project,
            "debit_in_account_currency":
            amount if amount > 0 else 0,
            "credit_in_account_currency":
            abs(amount) if amount < 0 else 0
        }, {
            "account":
            account2,
            "party_type":
            party_type if action_status == "Cheque Received" else None,
            "party":
            party if action_status == "Cheque Received" else None,
            "cost_center":
            cost_center_project,
            "project":
            self.project,
            "credit_in_account_currency":
            amount if amount > 0 else 0,
            "debit_in_account_currency":
            abs(amount) if amount < 0 else 0
        }])
        if save or submit:
            jv.insert(ignore_permissions=True)

            if submit:
                jv.submit()

        self.append(
            "status_history", {
                "status": action_status,
                "transaction_date": nowdate(),
                "transaction_posting_date": posting_date or nowdate(),
                "bank": self.deposit_account,
                "debit_account": account1,
                "credit_account": account2,
                "journal_entry": jv.name
            })
        self.bank_changed = 1
        self.update_status(action_status)
        self.submit()
        frappe.db.commit()
        message = """<a href="#Form/Journal Entry/%s" target="_blank">%s</a>""" % (
            jv.name, jv.name)
        msgprint(_("Journal Entry {0} created").format(comma_and(message)))
        #message = _("Journal Entry {0} created").format(comma_and(message))

        return message
Example #59
0
    def make_accrual_jv_entry(self):
        self.check_permission('write')
        earnings = self.get_salary_component_total(
            component_type="earnings") or {}
        deductions = self.get_salary_component_total(
            component_type="deductions") or {}
        payroll_payable_account = self.payroll_payable_account
        jv_name = ""
        precision = frappe.get_precision("Journal Entry Account",
                                         "debit_in_account_currency")

        if earnings or deductions:
            journal_entry = frappe.new_doc('Journal Entry')
            journal_entry.voucher_type = 'Journal Entry'
            journal_entry.user_remark = _('Accrual Journal Entry for salaries from {0} to {1}')\
             .format(self.start_date, self.end_date)
            journal_entry.company = self.company
            journal_entry.posting_date = self.posting_date

            accounts = []
            currencies = []
            payable_amount = 0
            multi_currency = 0
            company_currency = erpnext.get_company_currency(self.company)

            # Earnings
            for acc_cc, amount in earnings.items():
                exchange_rate, amt = self.get_amount_and_exchange_rate_for_journal_entry(
                    acc_cc[0], amount, company_currency, currencies)
                payable_amount += flt(amount, precision)
                accounts.append({
                    "account":
                    acc_cc[0],
                    "debit_in_account_currency":
                    flt(amt, precision),
                    "exchange_rate":
                    flt(exchange_rate),
                    "party_type":
                    '',
                    "cost_center":
                    acc_cc[1] or self.cost_center,
                    "project":
                    self.project
                })

            # Deductions
            for acc_cc, amount in deductions.items():
                exchange_rate, amt = self.get_amount_and_exchange_rate_for_journal_entry(
                    acc_cc[0], amount, company_currency, currencies)
                payable_amount -= flt(amount, precision)
                accounts.append({
                    "account":
                    acc_cc[0],
                    "credit_in_account_currency":
                    flt(amt, precision),
                    "exchange_rate":
                    flt(exchange_rate),
                    "cost_center":
                    acc_cc[1] or self.cost_center,
                    "party_type":
                    '',
                    "project":
                    self.project
                })

            # Payable amount
            exchange_rate, payable_amt = self.get_amount_and_exchange_rate_for_journal_entry(
                payroll_payable_account, payable_amount, company_currency,
                currencies)
            accounts.append({
                "account":
                payroll_payable_account,
                "credit_in_account_currency":
                flt(payable_amt, precision),
                "exchange_rate":
                flt(exchange_rate),
                "party_type":
                '',
                "cost_center":
                self.cost_center
            })

            journal_entry.set("accounts", accounts)
            if len(currencies) > 1:
                multi_currency = 1
            journal_entry.multi_currency = multi_currency
            journal_entry.title = payroll_payable_account
            journal_entry.save()

            try:
                journal_entry.submit()
                jv_name = journal_entry.name
                self.update_salary_slip_status(jv_name=jv_name)
            except Exception as e:
                if type(e) in (str, list, tuple):
                    frappe.msgprint(e)
                raise

        return jv_name
Example #60
0
def create_delivery_note(source_name, target_doc=None):
    pick_list = frappe.get_doc('Pick List', source_name)
    validate_item_locations(pick_list)

    sales_orders = [
        d.sales_order for d in pick_list.locations if d.sales_order
    ]
    sales_orders = set(sales_orders)

    delivery_note = None
    for sales_order in sales_orders:
        delivery_note = create_delivery_note_from_sales_order(
            sales_order, delivery_note, skip_item_mapping=True)

    # map rows without sales orders as well
    if not delivery_note:
        delivery_note = frappe.new_doc("Delivery Note")

    item_table_mapper = {
        'doctype':
        'Delivery Note Item',
        'field_map': {
            'rate': 'rate',
            'name': 'so_detail',
            'parent': 'against_sales_order',
        },
        'condition':
        lambda doc: abs(doc.delivered_qty) < abs(doc.qty) and doc.
        delivered_by_supplier != 1
    }

    item_table_mapper_without_so = {
        'doctype': 'Delivery Note Item',
        'field_map': {
            'rate': 'rate',
            'name': 'name',
            'parent': '',
        }
    }

    for location in pick_list.locations:
        if location.sales_order_item:
            sales_order_item = frappe.get_cached_doc(
                'Sales Order Item', {'name': location.sales_order_item})
        else:
            sales_order_item = None

        source_doc, table_mapper = [sales_order_item, item_table_mapper] if sales_order_item \
         else [location, item_table_mapper_without_so]

        dn_item = map_child_doc(source_doc, delivery_note, table_mapper)

        if dn_item:
            dn_item.warehouse = location.warehouse
            dn_item.qty = flt(
                location.picked_qty) / (flt(location.conversion_factor) or 1)
            dn_item.batch_no = location.batch_no
            dn_item.serial_no = location.serial_no

            update_delivery_note_item(source_doc, dn_item, delivery_note)

    set_delivery_note_missing_values(delivery_note)

    delivery_note.pick_list = pick_list.name
    delivery_note.customer = pick_list.customer if pick_list.customer else None

    return delivery_note