# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

from frappe.utils import flt, getdate

from frappe import _
from frappe.model.mapper import get_mapped_doc
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
import datetime
import re
from erpnext.constants import DOCTYPE_DRAFT, MONTH_NAMES_TO_NUMBER_MAP

APPRAISAL_ANSWERS_LENGTH = 150
MAIL_SENT = 1
class Appraisal(Document):
	def on_update(self):
		if not self.status:
			self.status = "Draft"
		self.validate_existing_appraisal()
		self.validate_answers()
		self.notify_approver()
		self.notify_manager()
		if not self.goals:
			frappe.throw(_("Goals cannot be empty"))

		set_employee_name(self)
		self.calculate_total()

	def get_employee_name(self):
		self.employee_name = frappe.db.get_value("Employee", self.employee, "employee_name")
		return self.employee_name

	def notify_approver(self):
		#                             doctype      name
		parent_doc = frappe.get_doc('Appraisal', self.name)
		args = parent_doc.as_dict()
		recipients = self.team_lead_mail
		sender = dict()
		sender['email'] = frappe.get_doc('User', frappe.session.user).email
		sender['full_name'] = frappe.utils.get_fullname(sender['email'])
		if self.mail_sent_to_tl is 0:
			self.mail_sent_to_tl = MAIL_SENT
			parent_doc.db_set('mail_sent_to_tl', MAIL_SENT, commit=True)
			send_mail(recipients, sender=sender['email'], template="Appraisal Form Verification Template", args=args)
		else:
			pass

	def notify_manager(self):
		parent_doc = frappe.get_doc('Appraisal', self.name)
		args = parent_doc.as_dict()
		recipients = self.get_manager_mail()
		sender = dict()
		sender['email'] = frappe.get_doc('User', frappe.session.user).email
		sender['full_name'] = frappe.utils.get_fullname(sender['email'])
		roles_list =frappe.get_roles(args['employee_mail'])
		if self.mail_sent_to_tl is 1 and int(self.total_tl_score) > 0 and self.mail_sent_to_manager is 0:
			if (('HR User' not in roles_list) and ("Accounts User" not in roles_list) and  ("Projects Manager" not in roles_list) and ("Leave Approver" not in roles_list)) :
				if (self.department == 'Business development - SS') or (self.department != 'Digital Marketing - SS') or (self.department != 'System Admin'):
					self.mail_sent_to_manager = MAIL_SENT
					parent_doc.db_set('mail_sent_to_manager', MAIL_SENT, commit=True)
					send_mail(recipients, sender=sender['email'], template="Appraisal Form Verification Template", args=args)
				else:
					pass
			else:
				pass
		else:
			pass

	def notify_employee(self):
		parent_doc = frappe.get_doc('Appraisal', self.name)
		args = parent_doc.as_dict()
		recipients = self.employee_mail
		sender = dict()
		hr_mail = '[email protected]'
		sender['email'] = frappe.get_doc('User', frappe.session.user).email
		sender['full_name'] = frappe.utils.get_fullname(sender['email'])
		send_mail(recipients, sender=frappe.get_doc('User', frappe.session.user).email, template="Appraisal Form Notification Template", args=args,cc_mail=hr_mail)

	def get_manager_mail(self):
		manager_mail=frappe.db.sql("""select leave_approver from `tabEmployee` where user_id=%s""",self.team_lead_mail,as_list = 1 )
		return manager_mail[0]

	def validate_dates(self):
		appraisal_date = datetime.datetime.strptime(self.start_date, "%Y-%m-%d")
		year = str(appraisal_date.year)
		months_map = MONTH_NAMES_TO_NUMBER_MAP
		quarterly_start_end_dates = {"JAN": {'start_date': year + '-01-01', 'end_date': year + '-03-31'},"APR": {'start_date': year + '-04-01', 'end_date': year + '-06-30'},
									"JUL": {'start_date': year + '-07-01', 'end_date': year + '-09-30'},"OCT": {'start_date': year + '-10-01', 'end_date': year + '-12-31'}}
		if appraisal_date.month >= months_map['JAN'] and appraisal_date.month <= months_map['MAR']:
			return quarterly_start_end_dates['JAN']
		elif appraisal_date.month >= months_map['APR'] and appraisal_date.month <= months_map['JUN']:
			return quarterly_start_end_dates['APR']
		elif appraisal_date.month >= months_map['JUL'] and appraisal_date.month <= months_map['SEPT']:
			return quarterly_start_end_dates['JUL']
		else:
			return quarterly_start_end_dates['OCT']


	def validate_existing_appraisal(self):
		dates = self.validate_dates()
		chk = frappe.db.sql("""select name from `tabAppraisal` where employee=%s
			and (status='Submitted' or status='Completed' or docstatus= %s)
			and ((start_date>=%s and start_date<=%s) and name != %s)""",
			(self.employee,DOCTYPE_DRAFT,dates['start_date'],dates['end_date'],self.name))
		if chk:
			frappe.throw(_("Appraisal {0} created for Employee {1} in the given date range").format(chk[0][0], self.employee_name))

	def validate_answers(self):
		answers_dict = [self.question_1,self.question_2,self.question_3,self.question_4,self.question_5,self.question_6,self.question_7,self.question_8,
						self.question_9,self.question_10,self.question_11]
		question_no=1
		for answers in answers_dict:
			if answers and (len(answers)<APPRAISAL_ANSWERS_LENGTH):
				frappe.throw(_("Length of answer{0} should be greater than 150").format(question_no))
			else:
				question_no=question_no+1
	def calculate_total(self):
		total, total_w  = 0, 0
		for d in self.get('goals'):
			if d.score:
				d.manager_score_earned = flt(d.score) * flt(d.per_weightage) / 100
				total = total + d.manager_score_earned
			total_w += flt(d.per_weightage)

		if int(total_w) != 100:
			frappe.throw(_("Total weightage assigned should be 100%. It is {0}").format(str(total_w) + "%"))

		self.total_score = total

	def on_submit(self):
		frappe.db.set(self, 'status', 'Submitted')
		self.notify_employee()

	def on_cancel(self):
		frappe.db.set(self, 'status', 'Cancelled')

@frappe.whitelist()
def fetch_appraisal_template(source_name, target_doc=None):
	target_doc = get_mapped_doc("Appraisal Template", source_name, {
		"Appraisal Template": {
			"doctype": "Appraisal",
		},
		"Appraisal Template Goal": {
			"doctype": "Appraisal Goal",
		}
	}, target_doc)

	return target_doc

@frappe.whitelist()
def send_appraisal_remainder():
	employee_list = frappe.db.sql("""select user_id from `tabEmployee` where status='active' """,as_dict=1)
	for employee in employee_list:
		recipients = employee['user_id']
		sender = dict()
		sender['email'] = frappe.get_doc('User', frappe.session.user).email
		sender['full_name'] = frappe.utils.get_fullname(sender['email'])
		send_mail(recipients, sender=sender['email'], template="Appraisal Form Remainder Template", args={})

@frappe.whitelist()
def get_questions_fields():
	required_fields = {}
	list_of_fields = frappe.db.sql("""select column_name from Information_schema.columns where Table_name like 'tabAppraisal'""", as_dict=1)
	question_no = 0
	for fields in list_of_fields:
		match = (re.search(r'^question_[0-9]+$', fields["column_name"]))
		if match:
			question_no = question_no + 1
			required_fields["question_"+str(question_no)] = fields["column_name"]
	return required_fields

def check_for_unfilled_appraisal():
	recipients =[]
	cur_date = datetime.date.today()
	current_appraisal_cycle_start_date = str(cur_date.year)+'-'+str(cur_date.month)+'-01'
	employee_list = frappe.db.sql("""select user_id from `tabEmployee` where status='active' """,as_list=1)
	list_of_appraisal_filled_employees = frappe.db.sql("""select employee_mail from `tabAppraisal` where start_date>=%s """%current_appraisal_cycle_start_date,as_dict=1)
	for employee in employee_list:
		if employee not in list_of_appraisal_filled_employees:
			recipients.append(employee[0])
	send_mail(recipients,sender=frappe.get_doc('User', frappe.session.user).email,template="Appraisal Form Notification Template",args={})

def send_mail(recipients,sender,subject=None,message=None,template=None,args=None,cc_mail=None):
	email_template = frappe.get_doc("Email Template", template)
	message = frappe.render_template(email_template.response, args)
	try:
		frappe.sendmail(
			recipients=recipients,
			sender=sender,
			cc=cc_mail,
			subject=email_template.subject,
			message=message,
		)
		frappe.msgprint("Email sent")
	except frappe.OutgoingEmailError:
		pass

@frappe.whitelist()
def check_user_is_in_two_hierarchy_position(employee):
	roles_list = frappe.get_roles(employee)
	check_user = 0
	if (('HR User' in roles_list) or ("Accounts User" in roles_list) or  ("Projects Manager" in roles_list) or ("Leave Approver" in roles_list) or ("System Admin" in roles_list)) :
		check_user = 1
	return check_user
 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling