def delete_customer(subject_customer_id): """Deletes a customer""" security.authorize(request) customer = Customer.query.get(subject_customer_id) customer.active = False db.session.commit() return ('', 204)
def delete_user(subject_user_id): """Deletes a user""" security.authorize(request) user = User.query.get(subject_user_id) user.active = False db.session.commit() return ('', 204)
def update_customer(subject_customer_id): """Updates a customer""" security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_customer_input(data) has_contract_end_date = 'contractEndDate' in data and data[ 'contractEndDate'] customer = Customer.query \ .options(joinedload('applications')) \ .get(subject_customer_id) customer.name = data['name'] customer.address = data['address'] if 'address' in data else '' customer.contract_end_date = data[ 'contractEndDate'] if has_contract_end_date else None customer.applications = [Application.query.get(id) for id in data['applications']] \ if 'applications' in data else [] customer.active = data['active'] db.session.commit() return ('', 204)
def update_user(subject_user_id): """Updates a user""" security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_user_input(data, adding=False) has_contract_end_date = 'contractEndDate' in data and data[ 'contractEndDate'] user = User.query.get(subject_user_id) user.firstname = data['firstName'] user.secondname = data['secondName'] if 'secondName' in data else '' user.company_name = data['companyName'] if 'companyName' in data else '' user.company_address = data[ 'companyAddress'] if 'companyAddress' in data else '' user.contract_end_date = data[ 'contractEndDate'] if has_contract_end_date else None user.email = data['workEmail'] user.active = data['active'] user.admin = data['admin'] if 'password' in data and data['password']: hashed_password = security.strong_hash(data['password']) user.password = hashed_password db.session.commit() return ('', 204)
def add_user(): """Adds a new user""" security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_user_input(data, adding=True) hashed_password = security.strong_hash(data['password']) user = User(id=uuid4(), firstname=data['firstName'], secondname=data['secondName'] if 'secondName' in data else '', customer_id=data['customerId'], email=data['workEmail'], password=hashed_password, admin=data['admin'], active=data['active'], unsucessful_login_attemps=0) db.session.add(user) db.session.commit() return ('', 204)
def add_customer(): """Adds a new customer""" security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_customer_input(data) has_contract_end_date = 'contractEndDate' in data and data[ 'contractEndDate'] contract_end_date = data[ 'contractEndDate'] if has_contract_end_date else None customer = Customer(id=uuid4(), name=data['name'], address=data['address'] if 'address' in data else '', contract_end_date=contract_end_date, applications=[Application.query.get(id) for id in data['applications']] \ if 'applications' in data else [], active=data['active']) db.session.add(customer) db.session.commit() return ('', 204)
def fetch_customers(): """Fetches all customers data""" security.authorize(request) customers = Customer.query.order_by(Customer.name).all() return jsonify(list(map(lambda customer: { "id": customer.id, "name": customer.name, "active": customer.active, 'contractEndDate': customer.contract_end_date.isoformat() \ if customer.contract_end_date else None, }, customers)))
def fetch_user(requested_user_id): """Fetches a specific user data""" security.authorize(request) user = User.query.get(requested_user_id) return jsonify({ 'firstName': user.firstname, 'secondName': user.secondname or '', 'customerId': user.customer_id, 'workEmail': user.email, 'active': user.active, "admin": user.admin, })
def fetch(): """Fetches applications""" security.authorize(request) apps = Application.query \ .order_by(Application.name) \ .all() return jsonify( list(map(lambda app: { "id": app.id, "name": app.name, }, apps)))
def fetch_users(): """Fetches all users data""" security.authorize(request) users = User.query.order_by(User.firstname).all() return jsonify( list( map( lambda user: { "id": user.id, "firstName": user.firstname, "secondName": user.secondname, "email": user.email, "customerName": user.customer.name, "active": user.active, }, users)))
def fetch(): """Fetches assumptions settings""" user = security.authorize(request) assumptions = Assumptions.query.filter_by( customer_id=user.customer.id).first() if assumptions is None: return jsonify(None) return jsonify({ "outboundFromUKWithoutInbound": assumptions.outbound_uk_without_inbound, "businessTravellersTreaty3159": assumptions.business_trav_treaty_3159, "businessTravellersTreaty60183": assumptions.business_trav_treaty_60183, "useDeminimusIncidentalWorkdays": 'Y' if assumptions.use_demin_incidental_workdays else 'N', "deminimusIncidentalWorkdays": assumptions.deminimus_incidental_workdays, "useDeminimusEEAA1Workdays": 'Y' if assumptions.use_demin_eeaa1_workdays else 'N', "deminimusEEAA1Workdays": assumptions.deminimus_eeaa1_workdays, "inboundToUKWithoutOutbound": assumptions.inbound_uk_without_outbound, })
def fetch_periods(): """Returns data about traveller data periods""" user = security.authorize(request) periods = TravellerDataPeriod.query \ .join(TravellerDataPeriod.traveller_data) \ .filter_by(customer_id=user.customer.id) \ .order_by(TravellerData.upload_date.desc()) \ .all() return jsonify( list( map( lambda period: { "id": period.id, "from": period.from_date.isoformat(), "to": period.to_date.isoformat(), "travellerData": { "id": period.traveller_data.id, "entryCount": count_travels(period.traveller_data.id), "filename": period.traveller_data.filename, "dateUploaded": period.traveller_data.upload_date.isoformat(), "valid": period.traveller_data.valid, "invalidCount": count_invalid_travels(period.traveller_data.id), "outsidePeriodCount": count_travels_outside_period(period.id), } if period.traveller_data else None, }, periods)))
def add_period(): """Save a new traveller data period""" user = security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') period = data check_periods_input([period]) has_traveller_data = 'travellerData' in period and period['travellerData'] traveller_data_id = period['travellerData'][ 'id'] if has_traveller_data else None db.session.add( TravellerDataPeriod(pk=uuid4(), customer_id=user.customer.id, from_date=period['from'], to_date=period['to'], traveller_data_id=traveller_data_id)) db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return ('', 204)
def save_periods(): """Updates traveller data periods""" user = security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') periods = data check_periods_input(periods) TravellerDataPeriod.query.filter_by(customer_id=user.customer.id).delete() for period in periods: has_traveller_data = 'travellerData' in period and period[ 'travellerData'] traveller_data_id = period['travellerData'][ 'id'] if has_traveller_data else None db.session.add( TravellerDataPeriod(pk=uuid4(), customer_id=user.customer.id, from_date=period['from'], to_date=period['to'], traveller_data_id=traveller_data_id)) db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return ('', 204)
def deactivate_current(): """Deactivates current spreadsheet""" user = security.authorize(request) disable_current_spreadsheets(user.customer.id) db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return ('', 204)
def activate(spreadsheet_id): """Activates an unsaved spreadsheet""" user = security.authorize(request) disable_current_spreadsheets(user.customer.id) spreadsheet = EmployeeSpreadsheet.query \ .options(joinedload('employees')) \ .options(joinedload('employees.arrangements')) \ .filter(EmployeeSpreadsheet.customer_id == user.customer.id) \ .filter(EmployeeSpreadsheet.id == spreadsheet_id) \ .first() if spreadsheet is None: raise InvalidUsage('Spreadsheet not found') spreadsheet.active = True data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_employee_input(data) found_any_duplication = process_employee_changes(spreadsheet, data) db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return jsonify({ "foundAnyDuplication": found_any_duplication, })
def fetch_customer(requested_customer_id): """Fetches a specific customer data""" security.authorize(request) customer = Customer.query \ .options(joinedload('applications')) \ .get(requested_customer_id) has_contract_end_date = customer.contract_end_date contract_end_date = customer.contract_end_date.isoformat( ) if has_contract_end_date else None return jsonify({ 'name': customer.name, 'address': customer.address or '', 'contractEndDate': contract_end_date, 'applications': [app.id for app in customer.applications], 'active': customer.active, })
class AuthRes(Resource): ''' API auth resource, only provides GET access to the current auth state. ''' decorators = [authorize()] def get(self): return json_response(dict(session.items()))
def fetch(): """Fetches countries""" security.authorize(request) query = request.args['query'].lower() if 'query' in request.args else '' countries = Country.query \ .filter(Country.name.ilike('%{0}%'.format(query)) | \ Country.code.ilike(query)) \ .order_by(Country.name) \ .all() return jsonify( list( map(lambda country: { "code": country.code, "name": country.name, }, countries)))
def download(traveller_data_id): """Downloads the spreadsheet data""" user = security.authorize(request) traveller_data = TravellerData.query.get(traveller_data_id) if not traveller_data: raise InvalidUsage('Traveller data not found') elif traveller_data.customer_id != user.customer.id: raise InvalidUsage('Access denied') data = aws.s3download(traveller_data.upload_key) return send_file(data, attachment_filename=traveller_data.filename)
def download(spreadsheet_id): """Downloads the spreadsheet data""" user = security.authorize(request) employee_spreadsheet = EmployeeSpreadsheet.query.get(spreadsheet_id) if not employee_spreadsheet: raise InvalidUsage('Employee Spreadsheet not found') elif employee_spreadsheet.customer_id != user.customer.id: raise InvalidUsage('Access denied') data = aws.s3download(employee_spreadsheet.upload_key) return send_file(data, attachment_filename=employee_spreadsheet.file_name)
class CatalogRes(Resource): ''' API catalog resource, get all catalog data. ''' decorators = [db_session, authorize()] def get(self): obj = { 'categories': Category.select()[:], 'items': Item.select()[:], 'files': File.select()[:] } return json_response(obj, exclude=('blob'))
def info(): """Returns data regarding the attached auth token, like the user first name""" user = security.authorize(request) return jsonify({ 'firstName': user.firstname, 'secondName': user.secondname or '', 'companyName': user.customer.name or '', 'companyAddress': user.customer.address or '', 'contractEndDate': user.customer.contract_end_date.isoformat() \ if user.customer.contract_end_date else None, 'workEmail': user.email, 'admin': user.admin, })
def ignore_employees(): """Ignores multiple employees""" user = security.authorize(request) data = request.get_json() if data is None or not isinstance(data, list): raise InvalidUsage('Invalid data') for employee in data: db.session.add( IgnoredEmployee(pk=uuid4(), customer_id=user.customer.id, traveller_name=employee['travellerName'], employee_id=employee['employeeId'])) db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return ('', 204)
def update(): """Receives company data and stores in the database""" user = security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_input(data) assumptions = Assumptions.query.filter_by( customer_id=user.customer.id).first() if assumptions is None: assumptions = Assumptions( user.customer.id, data['outboundFromUKWithoutInbound'], data['businessTravellersTreaty3159'], data['businessTravellersTreaty60183'], data['useDeminimusIncidentalWorkdays'] == 'Y', data['deminimusIncidentalWorkdays'], data['useDeminimusEEAA1Workdays'] == 'Y', data['deminimusEEAA1Workdays'], data['inboundToUKWithoutOutbound']) db.session.add(assumptions) else: assumptions.outbound_uk_without_inbound = data[ 'outboundFromUKWithoutInbound'] assumptions.business_trav_treaty_3159 = data[ 'businessTravellersTreaty3159'] assumptions.business_trav_treaty_60183 = data[ 'businessTravellersTreaty60183'] assumptions.use_demin_incidental_workdays = data[ 'useDeminimusIncidentalWorkdays'] == 'Y' assumptions.deminimus_incidental_workdays = data[ 'deminimusIncidentalWorkdays'] assumptions.use_demin_eeaa1_workdays = data[ 'useDeminimusEEAA1Workdays'] == 'Y' assumptions.deminimus_eeaa1_workdays = data['deminimusEEAA1Workdays'] assumptions.inbound_uk_without_outbound = data[ 'inboundToUKWithoutOutbound'] db.session.commit() tasks.refresh_employee_travel_history.schedule(user.customer.id) return ('', 204)
def update(): """Receives company data and stores in the database""" user = security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') check_input(data) CompaniesInfo.query.filter_by(customer_id=user.customer.id).delete() # the below instruction cascades automatically to branches Company.query.filter_by(customer_id=user.customer.id).delete() companies_info = CompaniesInfo(user.customer.id, data['branchesOverseas'] == 'Y', data['simplifiedAnnualPayroll'] == 'Y', data['employeesOnAssignmentUK'] == 'Y', data['anyNonTaxableEmployees'] == 'Y') db.session.add(companies_info) if 'companies' in data and isinstance(data['companies'], list): for company_data in data['companies']: company_id = uuid4() company = Company(company_id, user.customer.id, company_data['name'], company_data['paye'], company_data['trackingMethod'], company_data['otherTrackingMethod'], company_data['simplifiedPayroll'], company_data['simplifiedPayrollPaye']) if data['branchesOverseas'] == 'Y': for branch_data in company_data['branches']: branch = Branch(uuid4(), company_id, branch_data['name'], branch_data['country']) company.branches.append(branch) db.session.add(company) db.session.commit() return ('', 204)
def fetch(): """Returns data about employees""" user = security.authorize(request) companies_infos = CompaniesInfo.query.filter_by( customer_id=user.customer.id).first() spreadsheet = EmployeeSpreadsheet.query.filter_by( customer_id=user.customer.id) unsaved = request.args.get('unsaved') == 'true' if not unsaved: spreadsheet = spreadsheet.filter_by(active=True) spreadsheet = spreadsheet.order_by( EmployeeSpreadsheet.upload_date.desc()).first() return jsonify({ "id": spreadsheet.id if spreadsheet else None, "dateOfLastUpload": spreadsheet.upload_date.isoformat() if spreadsheet else None, "fileName": spreadsheet.file_name if spreadsheet else None, "ukEmployees": count_employees(spreadsheet, 1), "overseasBranchEmployees": count_employees(spreadsheet, 2), "ukExpatriates": count_employees(spreadsheet, 3), "ntStaEmployees": count_employees(spreadsheet, 4), "overseasBranchEmployeesEnabled": companies_infos and companies_infos.branches_overseas, "ukExpatriatesEnabled": companies_infos and companies_infos.employees_on_assignment_uk, "ntStaEmployeesEnabled": companies_infos and companies_infos.any_non_taxable_employees, "active": spreadsheet.active if spreadsheet else True, })
def change_password(): """Allows the user to change their password""" user = security.authorize(request) data = request.get_json() if data is None: raise InvalidUsage('Invalid data') errors = [] if not 'current' in data or not data['current']: errors.append('Current password is required') filled_new_password = '******' in data and data['new'] filled_password_confirmation = 'confirmation' in data and data[ 'confirmation'] if not filled_new_password: errors.append('New password is required') elif len(data['new']) < 8 or security.unsafe_password(data['new']): errors.append( 'Your new password should have a minimum length of 8 characters and ' + 'include at least 1 lowercase letter, 1 uppercase letter and 1 number' ) if not filled_password_confirmation: errors.append('Password confirmation is required') if filled_new_password and filled_password_confirmation and data[ 'new'] != data['confirmation']: errors.append('Your new password and the confirmation must match') if errors: raise InvalidUsage(errors) hashed_password = security.strong_hash(data['current']) if not hashed_password == user.password: raise InvalidUsage('Current password is invalid') hashed_new_password = security.strong_hash(data['new']) user.password = hashed_new_password db.session.commit() return ('', 204)
def generate_data_template(): """Generates the template spreadsheet based on answers on the cmpany page""" user = security.authorize(request) companies_infos = CompaniesInfo.query.filter_by( customer_id=user.customer.id).first() book = spreadsheets.open_workbook_template('Employees.xlsx') if companies_infos: if not companies_infos.any_non_taxable_employees: spreadsheets.remove_worksheet(book, 'NT code - STA Employees') if not companies_infos.employees_on_assignment_uk: spreadsheets.remove_worksheet(book, 'UK Expatriate Employees') if not companies_infos.branches_overseas: spreadsheets.remove_worksheet(book, 'Overseas Branch Employees') stream = spreadsheets.get_bytes(book) response = send_file(stream, attachment_filename='Employees.xlsx') response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' response.headers['Pragma'] = 'no-cache' response.headers[ 'Content-Disposition'] = 'attachment; filename=Employees.xlsx' return response
def fetch(): """Fetches company data""" user = security.authorize(request) companies_info = CompaniesInfo.query.filter_by(customer_id=user.customer.id).first() if companies_info is None: return jsonify(None) companies = Company.query.options(joinedload('branches')) \ .filter_by(customer_id=user.customer.id).all() companies_json = [] for company in companies: branches_json = [] for branch in company.branches: branches_json.append({ "name": branch.name, "country": branch.country, }) companies_json.append({ "name": company.name, "paye": company.paye, "trackingMethod": company.tracking_method, "otherTrackingMethod": company.other_tracking_method, "numberOfBranches": len(company.branches), "branches": branches_json, "simplifiedPayroll": company.simplified_payroll, "simplifiedPayrollPaye": company.simplified_payroll_paye, }) return jsonify({ "numberOfCompanies": len(companies), "branchesOverseas": 'Y' if companies_info.branches_overseas else 'N', "companies": companies_json, "simplifiedAnnualPayroll": 'Y' if companies_info.simplified_annual_payroll else 'N', "employeesOnAssignmentUK": 'Y' if companies_info.employees_on_assignment_uk else 'N', "anyNonTaxableEmployees": 'Y' if companies_info.any_non_taxable_employees else 'N', })
def authorize(username, role): return sec.authorize(username, role)