def delete_employee(id): errors = [] employee = Employee.find_by_id(id) Employee.delete(id) success = "データベースから社員(" + employee.name + ")を削除しました。" return render_template('result.html', success=success, errors=errors)
def __init__(self, db, user): """ Initialising database and User :param db: :param user: """ self.db = db self.user = user self.employee = Employee(db, user)
def print_body_for_user(self, authenticated_user): db_session = DB_Session_Factory.get_db_session() employee = db_session.query(Employee).get(authenticated_user.email) if employee is None: employee = Employee(authenticated_user.email) reimbursements = [] for reimbursement in db_session.query(Reimbursement).all(): reimbursements.append(reimbursement.dict_representation()) final_output_dict = {"employee": employee.dict_representation(), "reimbursement_policy": reimbursements} print json.dumps(final_output_dict)
def download_employee(): f = StringIO() writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_ALL, lineterminator="\n") writer.writerow([ 'id', '名前', '年齢', '性別', '郵便番号', '都道府県', '住所', '部署名', '入社日', '退社日', '作成日時', '更新日時' ]) employees = Employee.find_all_in_details() for emp in employees: writer.writerow([ emp.id, emp.name, emp.age, emp.gender, emp.zip_cd, emp.pref_name, emp.address, emp.div_name, emp.hired_date, emp.retired_date, emp.created_at, emp.updated_at ]) res = make_response() res.data = f.getvalue() res.headers['Content-Type'] = 'text/csv' res.headers[ 'Content-Disposition'] = 'attachment; filename=employee_list.csv' return res
def register_employee(self, employee_type, username, hash_password, cpf, name, birthday, photo_location, role, condominium_id): try: birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d') employee = Employee(type=employee_type, cpf=cpf, name=name, birthday=birthday, photo_location=photo_location, role=role, condominium_id=condominium_id) employee_user = EmployeeUser(password=hash_password) employee_user._username = Username(username=username) employee.user = employee_user db.session.add(employee) db.session.commit() return employee except exc.IntegrityError as e: db.session.rollback() return None
def save_employee(position, save, obj=None): employee = Employee(password=request.form['password'], first_name=request.form['first_name'], last_name=request.form['last_name'], position=position, telephone=request.form.get('phone_number', ''), mail=request.form.get('mail', ''), salary=request.form.get('salary', '')) if save == 'add': employee.add_employee() elif save == 'edit': obj.edit_employee(password=request.form['password'], first_name=request.form['first_name'], last_name=request.form['last_name'], telephone=request.form.get('phone_number', ''), mail=request.form.get('mail', ''), salary=request.form.get('salary', ''))
def edit_employee(id): employee = Employee.find_by_id(id) divisions = Division.find_all() prefectures = Prefecture.find_all() return render_template('edit_employee.html', employee=employee, divisions=divisions, prefectures=prefectures)
def update_from_soap(self, obj): self.id = str(obj.Id) self.created_at = obj.CreatedAt self.updated_at = obj.UpdatedAt self.name = obj.Name if hasattr(obj, "employees"): self.employees = [Employee().update_from_soap(x) for x in obj.employees] return self
def delete_assistant(employee_id): """ Remove assistant from list(data base) :param employee_id: int GET return list of assistants without removed assistant """ assistant = Employee.get_by_id(employee_id, 'assistant') assistant.delete_employee() flash('Assistant was deleted') return redirect(url_for('employee_controller.list_assistants'))
def show_add_emp_dialog(self): dialog = loadUi("../view/add_emp.ui") dialog.de_hire_date.setDate(datetime.today()) jobs = {str(e.job_id) for e in self.emps} dialog.cb_jobs.addItems(jobs) depts = [d.dept_name for d in self.depts] dialog.cb_depts.addItems(depts) choice = dialog.exec() if choice == 1: idx = dialog.cb_depts.currentIndex() e = Employee(dialog.le_emp_id.text(), dialog.le_emp_name.text(), dialog.le_email.text(), dialog.de_hire_date.date().toString("yyyy-MM-dd"), dialog.cb_jobs.currentText(), dialog.le_salary.text(), self.depts[idx - 1].dept_id) self.emps.append(e) self.load_emps() e.save_to_db()
def update_employee(self, id, first_name, last_name, middle_name): client = Client(self.url, faults=True) try: response = client.service.UpdateEmployee(id, first_name, last_name, middle_name) except WebFault as e: return (False, None, e.fault) employee = Employee().update_from_soap(response) return (True, employee, None)
def list_assistants(): """ GET to generate a list of assistants """ assistants_list = Employee.list_employee('assistant') add = 'employee_controller.add_assistant' edit = 'employee_controller.edit_assistant' delete = 'employee_controller.delete_assistant' return render_template('viewemployee.html', user=user_session(session['user'], session['type']), employee_list=assistants_list, employee='Assistant', add=add, edit=edit, delete=delete)
def create_employee(): errors = [] if not request.form['name']: errors.append('名前は必須です。') cmd_type = request.form['cmd-type'] if cmd_type == 'cancel': return render_template('new_division.html') success = '' age = 0 pref_cd = 0 photo_img = None mimetype = '' div_id = None hired_date = None retired_date = None if not errors: name = request.form['name'] if len(request.form['age']) > 0: age = request.form['age'] gender = request.form['gender'] zip_cd = request.form['zip-cd'] if len(request.form['pref-cd']) > 0: pref_cd = request.form['pref-cd'] address = request.form['address'] if len(request.form['div-id']) > 0: div_id = request.form['div-id'] if len(request.form['hired-date']) > 0: hired_date = request.form['hired-date'] if len(request.form['retired-date']) > 0: retired_date = request.form['retired-date'] if request.files['image-file']: f = request.files['image-file'] photo_img = f.read() mimetype = f.mimetype Employee.insert(name, age, gender, zip_cd, pref_cd, address, div_id, hired_date, retired_date, photo_img, mimetype) success = "社員の登録に成功しました。" return render_template('result.html', success=success, errors=errors)
def get_employee_by_id(self, employee_id): sql = "SELECT * FROM employee where id = %s" cursor = connection.cursor() cursor.execute(sql, [employee_id]) record = cursor.fetchone() cursor.close() if record: return Employee(record[0], record[1], record[2], record[3], float(record[4]), record[5]) else: raise ResourceNotFound( f"Employee record could not be verified with input data.")
def employee_authentication(self, employee): sql = "SELECT * FROM employee where employee_name = %s AND title = %s" cursor = connection.cursor() cursor.execute(sql, (employee.name, employee.title)) record = cursor.fetchone() cursor.close() if record: return Employee(record[0], record[1], record[2], record[3], float(record[4]), record[5]) else: raise ResourceNotFound( f"Employee record could not be verified with input data.")
def edit_assistant(employee_id): """ Edit assistant formula to edit assistant details :param employee_id: int GET return edit assistants formula POST return list of assistants with edited assistant changes saved """ assistant = Employee.get_by_id(employee_id, 'assistant') if request.method == 'POST': save_employee('assistant', 'edit', assistant) flash('Assistant was edited') return redirect(url_for('employee_controller.list_assistants')) return render_template('editemployee.html', user=user_session(session['user'], session['type']), employee=assistant, list='employee_controller.list_assistants')
def print_body_for_user(self, authenticated_user): db_session = DB_Session_Factory.get_db_session() employee = db_session.query(Employee).get(authenticated_user.email) if employee is None: employee = Employee(authenticated_user.email) db_session.add(employee) sys.stderr.write(employee.email) max_amounts = {} for reimbursement in db_session.query(Reimbursement).all(): max_amounts[reimbursement.id] = reimbursement.max_amount error = None if self.requested_gym_reimbursement > max_amounts['gym'] or self.requested_mobile_reimbursement > max_amounts['mobile']: error = "You are asking too much." else: employee.gym = self.requested_gym_reimbursement employee.mobile = self.requested_mobile_reimbursement db_session.commit() final_output_dict = {} if error is not None: final_output_dict['error'] = error else: final_output_dict['status'] = 'ok'; print json.dumps(final_output_dict)
def main_dashboard(self, db, user): """ Main Dashboard :param db: :param user: :return: """ print( 'Welcome to Cab Booking Service!!\nLogin as :\n1 : Admin\n2 : Employee\n3 : Exit' ) while True: try: n = int(input('Enter your choice : ')) break except: print('\n***Only numbers is allowed***\n') if n == 1: admin = Admin(db, user) admin.login() elif n == 2: employee = Employee(db, user) employee.login() else: sys.exit(1)
def post_authentication_employee(): try: print("here") employee = Employee.json_parse(request.json) print(f"name: {employee.name} title: {employee.title}") employee = EmployeeService.employee_authentication(employee) # before returning any data after an employee is verified # need to check if any pending process have taken too long # I decided each manager gets five day to approve or deny # if it is day five and the requester still needs to add info # The claim could be auto-rejected and if the manager requests # addition information on the fifth day I could add one day return jsonify(employee.json()), 202 # accepted except ResourceNotFound as r: return r.message, 404
def find_employees(): div_id = 0 id_from = 0 id_to = 0 if len(request.form['div-id']) > 0: div_id = int(request.form['div-id']) if len(request.form['id-from']) > 0: id_from = int(request.form['id-from']) if len(request.form['id-to']) > 0: id_to = int(request.form['id-to']) kw = request.form['kw'] # TODO: 社員ID範囲チェック employees = Employee.find_by(div_id, id_from, id_to, kw) return render_template('employee_list.html', employees=employees)
def user_session(id, class_name): """Return object with given class name in class_name and id""" if class_name == "Student": return Student.get_by_id(id) elif class_name == "Mentor": return Mentor.get_by_id(id) elif class_name == "Employee": return Employee.get_by_id(id, 'assistant') elif class_name == "Manager": return Manager.get_by_id(id) return None
def __init__(self): QWidget.__init__(self) self.setupUi(self) self.depts = Department.get_all_deps() self.load_depts() self.emps = Employee.get_all_emps() self.load_emps() self.cb_depts.currentIndexChanged.connect(self.filter_emps_by_dept) self.le_search.textChanged.connect(self.filter_emps_by_name) self.bt_add_dept.clicked.connect(self.show_add_dialog) self.bt_del_dept.clicked.connect(self.delete_dept) self.bt_add_emp.clicked.connect(self.show_add_emp_dialog) self.bt_del_emp.clicked.connect(self.delete_emp) self.bt_export.clicked.connect(self.export_data)
def __init__(self): super().__init__() self.setupUi(self) self.depts = Department.get_all_depts() self.load_depts() self.emps = Employee.get_all_emps() self.load_emps() self.sb_depts.currentIndexChanged.connect(self.filter_emps_by_dept) self.le_search.textChanged.connect(self.filter_emps_by_name) self.bt_add_dept.clicked.connect(self.show_add_dept_dialog) self.bt_exit.clicked.connect(app.exit) self.bt_del_dept.clicked.connect(self.delete_dept) self.bt_add_emp.clicked.connect(self.show_add_emp_dialog) self.bt_del_emp.clicked.connect(self.delete_emp) self.pushButton_5.clicked.connect(self.export_data) print()
def init_db(): """ Initializes the database with some starter data. """ from model.department import Department from model.employee import Employee Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create the fixtures engineering = Department(name='Engineering') hr = Department(name='Human Resources') marketing = Department(name='Marketing') db_session.add_all([engineering, hr, marketing]) db_session.add(Employee(name='Peter', salary=50000, department=engineering)) db_session.add(Employee(name='Roy', salary=75000, department=engineering)) db_session.add(Employee(name='Tracy', salary=25000, department=hr)) # Arbitrarily produce data for i in range(50): if i % 3 == 0: db_session.add( Employee(name='George #' + str(i), salary=25000 + i, department=hr)) elif i % 2 == 0: db_session.add( Employee(name='Samuel #' + str(i), salary=60000 - i, department=marketing)) else: db_session.add( Employee(name='Albert #' + str(i), salary=12000 - i, department=engineering)) db_session.commit()
def add_new_employee(self): name, password = self.ui.login_inputs() surname, birth, earnings = self.ui.new_employee_inputs() customer = Employee(self.user, earnings, name, surname, birth) self.dao.save_password_new_person(name, password)
"no_error": "" } def gen_str(symbols, max_len): return "".join( [random.choice(symbols) for _ in range(random.randrange(max_len))]) def random_string(prefix, max_len): symbols = string.ascii_letters + " " return prefix + gen_str(symbols, max_len) test_data = [(Employee(first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=random_string("mn_", 50)), err_map['no_error']), (Employee(first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=""), err_map['no_error']), (Employee(first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=None), err_map['no_error'])] @pytest.mark.parametrize("data", test_data) def test_add_employee(soap, data): (employee, err_msg) = data (found, response, fault) = soap.add_employee(employee.first_name, employee.last_name, employee.middle_name)
def update_employee(*, id, code, name): emp = Employee(code, name) emp.id = id Database.update_employee(emp)
def save_employee(*, code, name): emp = Employee(code, name) Database.save_employee(emp)
class Admin: def __init__(self, db, user): """ Initialising database and User :param db: :param user: """ self.db = db self.user = user self.employee = Employee(db, user) def login(self): """ Login validation and homescreen for Admin :return: """ username = input("Enter username: "******"Enter password: "******"Admin") if not access: print("Username/Password not matched") return name = self.db.get_name(dict, "Admin") print(f"\nWelcome {name}\n") while True: n = input( '\n1: Check total booking\n2: Check booking of an employee\n' '3: Add a cab\n4: Update cab details\n5: Add/Update/Delete Employee\n' '6: Logout\nEnter your choice : ') if n == '1': self.check_total_booking() elif n == '2': self.check_employee_booking() elif n == '3': self.add_cab() elif n == '4': self.update_cab_details() elif n == '5': self.crud_employee() elif n == '6': break else: print('\nWrong Choice!! Try again\n') print("\nLogging out!!\n") time.sleep(.5) def check_total_booking(self): """ Showing total booking record based on date, week, month :return: """ date = input('\nEnter the date in DD-MM-YYYY format: ') while True: try: n = int( input( '\n1: See booking records date-wise\n2: See booking records week-wise' '\n3: See booking records month-wise\nEnter your choice: ' )) break except: print("\n***Only numbers are allowed***\n") if n == 1: record = self.db.get_record_datewise(date) elif n == 2: week_dict = { 1: ('01', '02', '03', '04', '05', '06', '07'), 2: ('08', '09', '10', '11', '12', '13', '14'), 3: ('15', '16', '17', '18', '19', '20', '21'), 4: ('22', '23', '24', '25', '27', '28', '29'), 5: ('30', '31') } week_number = int(int(date[:2]) / 7) + 1 week_list = week_dict[week_number] record = self.db.get_record_weekwise(date[3:], week_list) elif n == 3: record = self.db.get_record_monthwise(date[3:]) if record == []: print('\nNo Travel History Found\n') return print('\n' + tabulate(record, headers=[ 'Employee ID', 'Cab Number', 'Trip Date', 'Time', 'Source Location', 'Destination', 'Status' ], tablefmt='orgtbl') + '\n') def check_employee_booking(self): """ Check total booking record of a employee :return: """ while True: try: employee_id = int(input('\nEnter the employee ID: ')) break except: print("\n***Only numbers are allowed***\n") if not self.db.validate_record_existence(employee_id, 'employee_details'): print(f'\nNo employee found from id -> {employee_id}\n') return travel_history = self.db.get_travel_history(employee_id) if travel_history == []: print('\nNo Travel History Found\n') return print('\n' + tabulate(travel_history, headers=[ 'Cab Number', 'Trip Date', 'Time', 'Source Location', 'Destination', 'Status' ], tablefmt='orgtbl') + '\n') def add_cab(self): """ Adding a new cab :return: """ cab_detail_dict = self.input_cab_details() self.db.insert_cab_details(cab_detail_dict) print('\nNew cab details entered successfully\n') def update_cab_details(self): """ Updating a cab details :return: """ while True: try: cab_id = int( input( 'Enter the cab ID of the cab you want to update details: ' )) break except: print("\n***Only numbers are allowed***\n") if not self.db.validate_record_existence(cab_id, 'cab_details'): print(f'No cab found from id -> {cab_id}') return cab_detail_dict = self.input_cab_details() self.db.update_details(cab_id, cab_detail_dict, 'cab_details') print('\nCab details updated successfully\n') def input_cab_details(self): """ Common function for getting the cab details from user :return: """ cab_number = input('Enter cab number: ') while True: try: seat_capacity = int(input('Enter the seats capacity: ')) break except: print("\n***Only numbers are allowed***\n") locations = { 1: "Koramangala", 2: "HSR", 3: "Bellandur", 4: "Electronic City", 5: "Sarjapur" } for item, value in locations.items(): print(f"{item} : {value}") n = 0 while True: try: n = int( input( 'Enter the routes as in the number specified by them: ' )) break except: print('\n*Only numbers is alllowed*\n') route_num_list = [int(d) for d in str(n)] route = "" for item in route_num_list: route += ":" + locations[item] print(route[1:]) time = input( 'Enter the running time(24hrs, HH:mm format) of the cab comma(,) seperated: ' ) time_list = time.split(',') timing = "" for item in time_list: timing += "-" + item print(timing[1:]) return { 'cab_number': cab_number, 'seat_capacity': seat_capacity, 'seat_available': seat_capacity, 'route': route[1:], 'timing': timing[1:] } def crud_employee(self): """ CRUD operations on employee :return: """ while True: user_choice = input( '\n1: Create Employee\n2: Update Employee\n3: Delete Employee\n' 'Any Other key to Exit\nEnter your choice: ') if user_choice == '1': self.employee.create_member() elif user_choice == '2': self.employee.update_member() elif user_choice == '3': self.employee.delete_member() else: print('') break
def add_employee(*, code, name): employee = Employee(code, name) Database.save_employee(employee)
"not_fount": "is not found", "no_error": "" } def gen_str(symbols, max_len): return "".join([random.choice(symbols) for _ in range(random.randrange(max_len))]) def random_string(prefix, max_len): symbols = string.ascii_letters + " " return prefix + gen_str(symbols, max_len) test_data = [ (Employee(id="5f17fe2949faca0001b68212", first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=random_string("mn_", 50)), err_map['no_error']), (Employee(id="5f17fe2949faca0001b68212", first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=""), err_map['no_error']), (Employee(id="5f17fe2949faca0001b68212", first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=None), err_map['no_error']), (Employee(id="5f17fe2949faca0001b68213", first_name=random_string("fn_", 50), last_name=random_string("ln_", 50), middle_name=""), err_map['not_fount']) ] @pytest.mark.parametrize("data", test_data) def test_update_employee(soap, data): (employee, err_msg) = data (found, response, fault) = soap.update_employee(employee.id, employee.first_name, employee.last_name, employee.middle_name) if found: print("%s" % response) assert response.last_name == employee.last_name assert err_msg == err_map['no_error'] assert response.created_at != response.updated_at
import json from model.person import Person from model.employee import Employee p1 = Person("shajal", 27) p2 = Person("Simon", 27) p3 = Person("Iftekhar", 27) plist = [p1, p2, p3] with open("person_list.json", "w", encoding='utf-8') as f: for p in plist: f.write(p.to_json() + "\n") e1 = Employee("Shajal", 27, 10, 'cse') print(e1.name)