def make_badge_seen(): # # makes the bage as seen # try: # get request data and badge data = request.get_json() badge = data.get('badge') if badge is None: raise Exception('Badge data not found in request') ###### DEUG OUTPUT print("\n**** Badge Seen:") import json print(json.dumps(data, indent=2)) # find badge in user badges userBadge = list(filter(lambda x: filter_badge(x, badge), auth.current_user().badges)) if len(userBadge) == 0: raise Exception(f"Badge Type {badge.get('type')} not found in user's badges") # update badge instance userBadge[0].set_seen() # return updated lit of badges return jsonify([badge.to_json() for badge in auth.current_user().badges]), 200 except Exception as e: current_app.logger.exception(f'Making Gamification Badge seen fails: Badge={badge}\n{e}') return jsonify({'error': 'Bad Request'}), 400
def notifications(): user = auth.current_user() toast = db.session.query(ToastNotifications).filter_by( seen_at=None).filter_by(user_id=user.id).filter_by( company_id=user.company_id).first() if toast: if toast.type == "badge": badge = db.session.query(GamificationBadge).filter_by( id=toast.message).first() if badge: messenger.announce_badge(badge=badge, duration=5000) else: logger.info(f"Badge id {str(toast.message)} not found.") else: msg = json.dumps({ 'text': toast.message, 'autoHideDuration': toast.duration, 'variant': toast.type, 'anchorOrigin': { 'horizontal': toast.horizontal, 'vertical': toast.vertical, } }) messenger.announce(f'data: {msg}\n\n') toast.set_seen() return Response(response=f"New Notifications found", status=200) return Response(response=f"No Notification", status=200)
def new_activity(): # # create new activity # # get post data data = request.get_json() # get policy and create activity try: # get policy from app store policy = current_app.config['POLICIES'].get(data['id']) if policy is None: raise Exception(f'Policy {data["id"]} is absent in PoLZy storage') # load user and its relationships user = auth.current_user() user.company.company # save activity to DB activity = Activity.new(data, policy, user) # execute activity result = policy.executeActivity(data['activity']) # update activity status activity.finish('OK' if result else 'Failed') if result: # update policy update_policy = policy_factory().update(policy, deepcopy(user)) current_app.config['POLICIES'][policy.UUID] = update_policy current_app.logger.info( f"Policy={update_policy.number}, Stage={update_policy.stage}, lang={update_policy.language}" ) # check if activity returns not bool result if result is not True: return jsonify(result), 200 result = update_policy.parseToFrontend() update_achievement() return jsonify(result), 200 if result is None: # activity execution not implemented return jsonify({ 'id': policy.UUID, 'activity': activity.type, 'status': 'not implemented', }), 409 except Exception as e: current_app.logger.exception( f'Execution activity {data.get("name")} for policy {data["id"]} faild: {e}' ) return jsonify({'error': 'Bad Request'}), 400 return jsonify({ 'id': str(activity.id), 'status': 'Failed', }), 400
def get_policy(policy_number, effective_date=None): # # fetches a Policy by policy_number & effective_data # and returns it # policy_date = effective_date or str(date.today()) try: # load user and its relationships user = auth.current_user() user.company.company # create policy policy = policy_factory().create( policy_number, policy_date, deepcopy(user), ) current_app.logger.info( f"Policy={policy_number}, Stage={policy.stage}, lang={policy.language}" ) # create policy activity Activity.read_policy(policy_number, policy_date, user) # store policy to app and return as json object current_app.config['POLICIES'][policy.UUID] = policy result = policy.parseToFrontend() return jsonify(result), 200 except Exception as e: current_app.logger.exception( f'Fetch policy {policy_number} {policy_date} failed: {e}') return jsonify({'error': str(e)}), 400
def new_antrag(product_type): # # creates an Antrag by product_type # and returns it to frontend # try: # load user and its relationships user = auth.current_user() user.company.company # create antrag instance antrag = antrag_factory().create(product_type, deepcopy(user)) # store antrag to app and return as json object current_app.config['ANTRAGS'][antrag.uuid] = antrag result = antrag.parseToFrontend() #return jsonify(result), 200 response = zip_response(result) return response, 200 except Exception as e: current_app.logger.exception( f'Initialization of antrag instance {product_type} failed: {e}') return jsonify({'error': f'Initialization of antrag instance failed'}), 400
def user_permissions(): # get request data try: data = request.get_json() # get company id company_id = data.get('id') if company_id is None: current_app.logger.warning( f'Payload does not contain company id. Payload: {data}') raise Exception('Payload does not contain company id') # update company user = auth.current_user() company_details = user.set_company(company_id=company_id) return jsonify({ 'permissions': permissions(user), 'company': company_details, }), 200 except Exception as e: print(e) from polzyFunctions.GlobalConstants import logger logger.critical(f"Error: {e}", stack_info=True) return {'error': f'Failed to set company: {e}'}, 400
def loadLatestRecords(antrag_id): # preventing duplication of the antrag instance if antrag_id in current_app.config['ANTRAGS']: return {'error': 'Antrag is already active'}, 409 # get antrag record by id antrag_record = AntragActivityRecords.getLatest(antrag_id) if antrag_record is None: return jsonify({'error': f'No record found of antrag {antrag_id}'}), 404 # load user with company relationships user = auth.current_user() user.company.company # load antrag instance from the record and store it within the app antrag = antrag_factory().load( antrag_record, deepcopy(user), ) current_app.config['ANTRAGS'][antrag.uuid] = antrag # return antrag json result = antrag.parseToFrontend() response = zip_response(result) return response, 200
def get_admin_data(): # returns admin data for companies where current user is admin try: result = auth.current_user().get_admin_json() return jsonify(result), 200 except Exception as e: current_app.logger.warning(f'Failed to get admin data: {e}') return {'error': 'Failed to fetch data'}, 400
def badges(): # # returns list of all user badges # try: badges = [badge.to_json() for badge in auth.current_user().badges] return jsonify(badges), 200 except Exception as e: current_app.logger.exception(f'Faild to get Gamification Badges: {e}') return jsonify({'error': 'Bad Request'}), 400
def rankings(): # # returns user's rankings # try: return jsonify(HitList().deriveUserRanking(auth.current_user())), 200 except Exception as e: current_app.logger.exception(f"Faild to get user's gamification rankings: {e}") return jsonify({'error': 'Bad Request'}), 400
def get_antrag_products(): # # returns all products that available for current user # try: # get all stages product_list = antrag_products().getAllAvailableProducts( auth.current_user()) return jsonify(product_list), 200 except Exception as e: current_app.logger.exception(f"Error during get_antrag_products: {e}") return jsonify({'error': f'Failed to get antrag products'}), 400
def upload(parent_id=None, file_type=None): # get file file = request.files.get('file') if file is None: return jsonify({'error': 'Request does not contain dataFile'}), 400 # save file try: user = auth.current_user() filename_parts = (str(uuid4()), file.filename.split('.')[-1]) path_to_file = os.path.join(current_app.config['UPLOADS'], '.'.join(filename_parts)) file.save(path_to_file) # create file instance in db file_db = models.File.new( user=auth.current_user(), id=filename_parts[0], filename=file.filename, parent_id=parent_id, file_type=file_type, ) return {'OK': f'File {file_db.filename} saved with id {file_db.id}'}, 200 except Exception as error: current_app.logger.error(f'Failed to upload file "{file.filename}" by {user}: {error}.') return jsonify({'error': 'File upload failed'}), 400
def getSearchStringFromRecords(): data = request.get_json() # supplying current user to get records of current user & company found_antrags = AntragActivityRecords.getSearchString( auth.current_user(), data.get("value")) results = [ { 'id': instance.antrag_id, 'label': instance.get_label( ), # 'get_label' method should be adjusted to proper render results } for instance in found_antrags ] if found_antrags else [] return jsonify(results), 200
def manage_user(action): # # manage user in company # <action> should be one of: # - add -> add user to company # - edit -> edit user roles in company # - remove -> remove user from company # try: # validate action if not action in ['add', 'edit', 'remove']: raise Exception(f"Action '{action}' is not supported") # get request data data = request.get_json() # check for required fields in data if data.get('companyId') is None: raise Exception('Company ID is not defined in request') if data.get('email') is None: raise Exception('User e-mail is not defined in request') # roles are required by 'add' and 'edit' actions if (action in ['add', 'edit']) and (data.get('roles') is None): raise Exception( f'User roles are not defined in request. Required for action: {action}' ) # get company from db company = Company.query.get(data['companyId']) if company is None: raise Exception(f'Company with ID {data["companyId"]} not found') # get user from db user = User.query.filter_by(email=data['email']).first() # check if user exists if user is None: # create user for action 'add' if action == 'add': user = User(email=data['email']) db.session.add(user) # raise UserNotFound else: raise Exception(f'User {data["email"]} not found') # get or create user to company association if action in ['edit', 'remove']: # get user_to_company = UserToCompany.query.filter( and_( UserToCompany.company == company, UserToCompany.user == user, )).first() if user_to_company is None: raise Exception( f'User {data["email"]} not found in company {data["companyId"]}' ) else: # create user_to_company = UserToCompany( user=user, company=company, ) db.session.add(user_to_company) # set user roles and attributes if action in ['add', 'edit']: # roles roles = [] for name, value in data['roles'].items(): if value: # get role role = Role.query.filter_by(name=name).first() if role is None: raise Exception(f"Role '{name}' not found") roles.append(role) # update user roles user_to_company.roles = roles # attributes if not data.get('attributes') is None: user_to_company.attributes = data['attributes'] # remove user from company else: db.session.delete(user_to_company) # commit changes try: db.session.commit() except Exception as ex: logger.critical(f"Exception while committing changes to db: {ex}") db.session.rollback() # return updated admin data return jsonify(auth.current_user().get_admin_json()), 200 except Exception as e: db.session.rollback() current_app.logger.warning( f"Failed to execute action '{action}'\nPayload: {request.get_json()}\nException: {e}" ) return {'error': str(e)}, 400
def manage_child_company(action): # # manage child companies # <action> should be one of: # - add -> add user to company # - edit -> edit user roles in company # - remove -> remove user from company # try: # validate action if not action in ['add', 'edit', 'remove']: raise Exception(f"Action '{action}' is not supported") # get request data data = request.get_json() # check for required fields in data if data.get('parentCompanyId') is None: raise Exception('Parent company ID is not defined in request') if data.get('childCompanyId') is None: raise Exception('Child company ID is not defined in request') if action == 'edit' and data.get('attributes') is None: raise Exception( f'Attributes are not defined in request. Required for action: {action}' ) # get companies from db parent_company = Company.query.get(data['parentCompanyId']) if parent_company is None: raise Exception( f'Company with ID {data["parentCompanyId"]} not found') child_company = Company.query.get(data['childCompanyId']) if child_company is None: raise Exception( f'Company with ID {data["childCompanyId"]} not found') # get company-to-company association company_company = CompanyToCompany.query.filter( and_( CompanyToCompany.parent == parent_company, CompanyToCompany.child == child_company, )).first() if company_company is None: raise Exception( f'Company ID {data["parentCompanyId"]} does not have child company ID {data["childCompanyId"]}' ) # update attributes if action == 'edit': company_company.attributes = data['attributes'] if action == 'remove': db.session.delete(company_company) # commit changes try: db.session.commit() except Exception as ex: print(f"Exception while committing changes in db: {ex}") db.session.rollback() # return updated admin data return jsonify(auth.current_user().get_admin_json()), 200 except Exception as e: db.session.rollback() current_app.logger.warning( f"Failed to execute action '{action}'\nPayload: {request.get_json()}\nException: {e}" ) return {'error': str(e)}, 400