class ExamDetail(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) def get(self, id): print("==> In Python GET /exams/<id>/ endpoint") csr = CSR.find_by_username(g.oidc_token_info['username']) try: exam = Exam.query.filter_by(exam_id=id).first() if not (exam.office_id == csr.office_id or csr.liaison_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!" }, 403 result = self.exam_schema.dump(exam) return {'exam': result.data, 'errors': result.errors}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {'message': 'API is down'}, 500
class ExamBcmpPost(Resource): exam_schema = ExamSchema() bcmp_service = BCMPService() @oidc.accept_token(require_token=True) @api_call_with_retry def post(self): csr = CSR.find_by_username(g.oidc_token_info['username']) json_data = request.get_json() if 'bookdata' in json_data.keys(): booking = json_data["bookdata"] else: booking = None exam, warning = self.exam_schema.load(json_data) if warning: logging.warning("WARNING: %s", warning) return {"message": warning}, 422 if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 formatted_data = ExamPost.format_data(self, json_data, exam) exam = formatted_data["exam"] invigilator = None if exam.invigilator_id: invigilator = Invigilator.query.filter_by( invigilator_id=exam.invigilator_id).first() bcmp_response = None if json_data["ind_or_group"] == "individual": exam_fees = json_data["fees"] logging.info("Creating individual pesticide exam") bcmp_response = self.bcmp_service.create_individual_exam( exam, exam_fees, invigilator, formatted_data["pesticide_office"], g.oidc_token_info) else: logging.info("Creating Group pesticide exam") bcmp_response = self.bcmp_service.create_group_exam_bcmp( exam, booking, formatted_data["candidates_list_bcmp"], invigilator, formatted_data["pesticide_office"], g.oidc_token_info) if bcmp_response: return {"bcmp_job_id": bcmp_response['jobId'], "errors": {}}, 201 else: return { "message": "create_group_exam_bcmp failed", "error": bcmp_response }, 403
class ExamDetail(Resource): exam_schema = ExamSchema() @jwt.has_one_of_roles([Role.internal_user.value]) def get(self, id): csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) try: exam = Exam.query.filter_by(exam_id=id).first() if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!" }, 403 result = self.exam_schema.dump(exam) return { 'exam': result, 'errors': self.exam_schema.validate(exam) }, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {'message': 'API is down'}, 500
class ExamPost(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) @api_call_with_retry def post(self): csr = CSR.find_by_username(g.oidc_token_info['username']) json_data = request.get_json() exam, warning = self.exam_schema.load(json_data) if warning: logging.warning("WARNING: %s", warning) return {"message": warning}, 422 if exam.office_id == csr.office_id or csr.role.role_code == "LIAISON": db.session.add(exam) db.session.commit() result = self.exam_schema.dump(exam) return {"exam": result.data, "errors": result.errors}, 201 else: return {"The Exam Office ID and CSR Office ID do not match!"}, 403
class ExamPut(Resource): exam_schema = ExamSchema() @jwt.has_one_of_roles([Role.internal_user.value]) @api_call_with_retry def put(self, id): csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) json_data = request.get_json() if not json_data: return {"message": "No input data received for updating an exam"} # TODO Deleted date filter original exam = Exam.query.filter_by(exam_id=id).first_or_404() if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 exam = self.exam_schema.load(json_data, instance=exam, partial=True) warning = self.exam_schema.validate(json_data) if warning: logging.warning("WARNING: %s", warning) return {"message": warning}, 422 db.session.add(exam) db.session.commit() result = self.exam_schema.dump(exam) return {"exam": result, "errors": self.exam_schema.validate(exam)}, 201
class ExamPut(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) @api_call_with_retry def put(self, id): csr = CSR.find_by_username(g.oidc_token_info['username']) json_data = request.get_json() if not json_data: return {"message": "No input data received for updating an exam"} exam = Exam.query.filter_by(exam_id=id).first_or_404() if not (exam.office_id == csr.office_id or csr.role.role_code == "LIAISON"): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 exam, warning = self.exam_schema.load(json_data, instance=exam, partial=True) if warning: logging.warning("WARNING: %s", warning) return {"message": warning}, 422 db.session.add(exam) db.session.commit() result = self.exam_schema.dump(exam) return {"exam": result.data, "errors": result.data}, 201
class ExamList(Resource): exam_schema = ExamSchema(many=True) @oidc.accept_token(require_token=True) def get(self): try: csr = CSR.find_by_username(g.oidc_token_info['username']) exams = Exam.query.filter( Exam.deleted_date.is_(None)).filter_by(office_id=csr.office_id) search_kwargs = {} if request.args: for key in request.args: if hasattr(Exam, key): search_kwargs[key] = request.args.get(key) exams = exams.filter_by(**search_kwargs) result = self.exam_schema.dump(exams) return {'exams': result.data, 'errors': result.errors}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {"message": "api is down"}, 500
class CsrSelf(Resource): csr_schema = CSRSchema() citizen_schema = CitizenSchema(many=True) exam_schema = ExamSchema(many=True) exam_type_schema = ExamTypeSchema() @oidc.accept_token(require_token=True) def get(self): try: csr = CSR.find_by_username(g.oidc_token_info['username']) if not csr: return {'Message': 'User Not Found'}, 404 db.session.add(csr) active_sr_state = SRState.get_state_by_name("Active") today = datetime.now() active_citizens = Citizen.query \ .join(Citizen.service_reqs) \ .filter_by(sr_state_id=active_sr_state.sr_state_id) \ .join(ServiceReq.periods) \ .filter_by(csr_id=csr.csr_id) \ .filter(Period.time_end.is_(None)) individual_exams = Exam.query \ .filter_by(office_id=csr.office_id) \ .filter(Exam.exam_returned_date.is_(None), Exam.expiry_date <= today, Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .filter(ExamType.group_exam_ind == 0).count() group_exams = Exam.query \ .filter_by(office_id=csr.office_id) \ .filter(Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .filter(ExamType.group_exam_ind == 1) \ .join(Booking, Exam.booking_id == Booking.booking_id) \ .filter(Booking.invigilator_id.is_(None))\ .filter(Booking.sbc_staff_invigilated == 0).count() result = self.csr_schema.dump(csr) active_citizens = self.citizen_schema.dump(active_citizens) return { 'csr': result.data, 'individual_exams': individual_exams, 'group_exams': group_exams, 'active_citizens': active_citizens.data, 'errors': result.errors } except exc.SQLAlchemyError as e: print(e) return {'message': 'API is down'}, 500
class ExamList(Resource): exam_schema = ExamSchema(many=True) @jwt.has_one_of_roles([Role.internal_user.value]) def get(self): try: csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) ninety_day_filter = datetime.now() - timedelta(days=90) if csr.ita2_designate == 1: if request.args and request.args.get("office_number"): exams = Exam.query.filter(Exam.deleted_date.is_(None)) \ .filter(or_(Exam.exam_returned_date.is_(None), Exam.exam_returned_date > ninety_day_filter)) \ .join(Exam.office, aliased=True) \ .filter_by(office_number=request.args.get("office_number")) \ .order_by(desc(Exam.exam_id)) else: exams = Exam.query.filter(Exam.deleted_date.is_(None)) \ .filter(or_(Exam.exam_returned_date.is_(None), Exam.exam_returned_date > ninety_day_filter)) \ .order_by(desc(Exam.exam_id)) else: exams = Exam.query.filter(Exam.deleted_date.is_(None))\ .filter_by(office_id=csr.office_id)\ .filter(or_(Exam.exam_returned_date.is_(None), Exam.exam_returned_date > ninety_day_filter))\ .order_by(desc(Exam.exam_id)) search_kwargs = {} if request.args: for key in request.args: if hasattr(Exam, key): search_kwargs[key] = request.args.get(key) exams = exams.filter_by(**search_kwargs) result = self.exam_schema.dump(exams) return { 'exams': result, 'errors': self.exam_schema.validate(exams) }, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {"message": "api is down"}, 500
class ExamList(Resource): bcmp_service = BCMPService() exam_schema = ExamSchema() @jwt.requires_auth def post(self): csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) try: exams = Exam.query.filter_by(upload_received_ind=0).filter( Exam.bcmp_job_id.isnot(None)) bcmp_response = self.bcmp_service.bulk_check_exam_status(exams) job_ids = [] for job in bcmp_response["jobs"]: if job["jobStatus"] == "RESPONSE_UPLOADED": job_ids.append(job["jobId"]) my_print("job_ids to update: ") my_print(job_ids) exams_tobe_updated = None if len(job_ids) != 0: exams_tobe_updated = Exam.query.filter( Exam.bcmp_job_id.in_(job_ids)) for exam in exams_tobe_updated: exam_upd = self.exam_schema.load( {'upload_received_ind': 1}, instance=exam, partial=True) db.session.add(exam_upd) try: db.session.commit() except: db.session.rollback() raise return {"exams_updated": exams_tobe_updated}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {'message': 'API is down'}, 500
class ExamDetail(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) def get(self, id): csr = CSR.find_by_username(g.oidc_token_info['username']) try: exam = Exam.query.filter_by(exam_id=id, office_id=csr.office_id).first() result = self.exam_schema.dump(exam) return {'exam': result.data, 'errors': result.errors}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {'message': 'API is down'}, 500
class ExamDelete(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) def delete(self, id): csr = CSR.find_by_username(g.oidc_token_info['username']) exam = Exam.query.filter_by(exam_id=id).first_or_404() if not (exam.office_id == csr.office_id or csr.liaison_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 exam.deleted_date = datetime.now() db.session.add(exam) db.session.commit() return {}, 204
class ExamDelete(Resource): exam_schema = ExamSchema() @jwt.has_one_of_roles([Role.internal_user.value]) def delete(self, id): csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) exam = Exam.query.filter_by(exam_id=id).first_or_404() if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 exam.deleted_date = datetime.now() db.session.add(exam) db.session.commit() return {}, 204
class ExamEventIDDetail(Resource): exam_schema = ExamSchema() @oidc.accept_token(require_token=True) def get(self, id): try: exam = Exam.query.filter_by(event_id=str(id)).all() if not exam: return {'message': False}, 200 else: return {'message': True}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {"message": "API is down"}, 500
class ExamEventIDDetail(Resource): exam_schema = ExamSchema() @jwt.has_one_of_roles([Role.internal_user.value]) def get(self, id): try: exam = Exam.query.filter_by(event_id=str(id)).all() if not exam: return {'message': False}, 200 else: return {'message': True}, 200 except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {"message": "API is down"}, 500
class ExamList(Resource): exam_schema = ExamSchema(many=True) office_schema = OfficeSchema(many=True) timezone_schema = TimezoneSchema(many=True) @oidc.accept_token(require_token=True) @has_any_role(roles=[Role.internal_user.value]) def get(self): try: csr = CSR.find_by_username(g.oidc_token_info['username']) is_designate = csr.finance_designate start_param = request.args.get("start_date") end_param = request.args.get("end_date") exam_type = request.args.get("exam_type") validate_params(start_param, end_param) try: start_date = datetime.strptime(request.args['start_date'], "%Y-%m-%d") end_date = datetime.strptime(request.args['end_date'], "%Y-%m-%d") except ValueError as err: print(err) return {"message", "Unable to return date time string"}, 422 # Code for UTC time. csr_office = Office.query.filter( Office.office_id == csr.office_id).first() csr_timezone = Timezone.query.filter( Timezone.timezone_id == csr_office.timezone_id).first() csr_timename = csr_timezone.timezone_name timezone = pytz.timezone(csr_timename) start_local = timezone.localize(start_date) end_date += timedelta(days=1) end_local = timezone.localize(end_date) exams = Exam.query.join(Booking, Exam.booking_id == Booking.booking_id) \ .filter(Booking.start_time >= start_local) \ .filter(Booking.start_time < end_local) \ .join(Room, Booking.room_id == Room.room_id, isouter=True) \ .join(Office, Booking.office_id == Office.office_id) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) if exam_type == 'all_bookings': non_exams = Booking.query.join(Exam, Booking.booking_id == Exam.booking_id, isouter=True) \ .filter(Booking.start_time >= start_local) \ .filter(Booking.start_time < end_local) \ .filter(Exam.booking_id.is_(None)) \ .join(Room, Booking.room_id == Room.room_id, isouter=True) \ .join(Office, Booking.office_id == Office.office_id) \ if not is_designate: exams = exams.filter(Booking.office_id == csr.office_id) if exam_type == 'all_bookings': non_exams = non_exams.filter( Booking.office_id == csr.office_id) if exam_type == 'ita': exams = exams.filter(ExamType.ita_ind == 1) elif exam_type == 'all_non_ita': exams = exams.filter(ExamType.ita_ind == 0) dest = io.StringIO() out = csv.writer(dest) out.writerow([ 'Office Name', 'Exam Type', 'Exam ID', 'Exam Name', 'Examinee Name', 'Event ID', 'Room Name', 'Invigilator Name(s)', 'Shadow Invigilator Name', 'SBC Invigilator', 'Start Time', 'End Time', 'Booking ID', 'Booking Name', 'Number Of Students', 'Exam Received', 'Exam Written', 'Exam Returned', 'Notes', 'Collect Fees' ]) keys = [ "office_name", "exam_type_name", "exam_id", "exam_name", "examinee_name", "event_id", "room_name", "invigilator_names", "shadow_invigilator_id", "sbc_staff_invigilated", "start_time", "end_time", "booking_id", "booking_name", "number_of_students", "exam_received_date", "exam_written_ind", "exam_returned_date", "notes", "fees" ] exam_keys = [ "exam_id", "exam_name", "examinee_name", "event_id", "number_of_students", "notes", ] booking_keys = [ "start_time", "end_time", "booking_id", "booking_name" ] non_exam_keys = [ "exam_name", "notes", ] for exam in exams: row = [] if exam.booking.shadow_invigilator_id: shadow_invigilator_id = exam.booking.shadow_invigilator_id else: shadow_invigilator_id = None try: for key in keys: if key == "room_name": write_room(row, exam) elif key == "invigilator_names": write_invigilator(row, exam) elif key == "shadow_invigilator_id": write_shadow_invigilator(row, shadow_invigilator_id) elif key == "sbc_staff_invigilated": write_sbc(row, exam) elif key == "exam_received_date": write_exam_received(row, exam) elif key == "exam_written_ind": write_exam_written(row, exam) elif key == "exam_returned_date": write_exam_returned(row, exam) elif key == "office_name": row.append(getattr(exam.office, key)) elif key == "exam_type_name": row.append(getattr(exam.exam_type, key)) elif key in booking_keys: value = getattr(exam.booking, key) if isinstance(value, datetime): row.append('="' + localize_time(value, timezone) + '"') else: row.append(value) elif key in exam_keys: row.append(getattr(exam, key)) elif key == "fees": row.append("") out.writerow(row) except AttributeError as error: logging.error(error, exc_info=True) return { "message": "Issue writing row to CSV ", "key": key }, 500 if exam_type == 'all_bookings': for non_exam in non_exams: row = [] try: for key in keys: if key == "room_name": write_booking_room(row, non_exam) elif key == "invigilator_names": row.append("") elif key == "shadow_invigilator_id": row.append("") elif key == "sbc_staff_invigilated": row.append("") elif key == "exam_received_date": row.append("") elif key == "exam_written_ind": row.append("") elif key == "exam_returned_date": row.append("") elif key == "office_name": row.append(getattr(non_exam.office, key)) elif key == "exam_type_name": row.append("Non Exam Booking") elif key in booking_keys: value = getattr(non_exam, key) if isinstance(value, datetime): row.append('="' + localize_time(value, timezone) + '"') else: row.append(value) elif key in non_exam_keys: which_non_exam_key(non_exam, row, key) elif key == "exam_id": row.append("") elif key == "exam_name": row.append("") elif key == "examinee_name": row.append("") elif key == "event_id": row.append("") elif key == "fees": which_non_exam_key(non_exam, row, key) elif key == "number_of_students": row.append("") elif key == "exam_received_ind": row.append("") out.writerow(row) except AttributeError as error: logging.error(error, exc_info=True) return { "message": "Issue writing row to CSV ", "key": key }, 500 output = make_response(dest.getvalue()) output.headers[ "Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return output except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {"message": "api is down"}, 500
class CsrSelf(Resource): csr_schema = CSRSchema() citizen_schema = CitizenSchema(many=True) exam_schema = ExamSchema(many=True) exam_type_schema = ExamTypeSchema() timezone = pytz.timezone("US/Pacific") back_office_display = application.config['BACK_OFFICE_DISPLAY'] recurring_feature_flag = application.config['RECURRING_FEATURE_FLAG'] @oidc.accept_token(require_token=True) @api_call_with_retry def get(self): try: csr = CSR.find_by_username(g.oidc_token_info['username']) if not csr: return {'Message': 'User Not Found'}, 404 db.session.add(csr) active_sr_state = SRState.get_state_by_name("Active") today = datetime.now() start_date = self.timezone.localize(today) active_citizens = Citizen.query \ .join(Citizen.service_reqs) \ .filter_by(sr_state_id=active_sr_state.sr_state_id) \ .join(ServiceReq.periods) \ .filter_by(csr_id=csr.csr_id) \ .filter(Period.time_end.is_(None)) individual_exams = Exam.query \ .filter_by(office_id=csr.office_id) \ .filter(Exam.exam_returned_date.is_(None), Exam.expiry_date <= today, Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .filter(ExamType.group_exam_ind == 0).count() individual_exams_past_schedule = Exam.query \ .join(Booking, Exam.booking_id == Booking.booking_id)\ .filter(Booking.start_time < start_date)\ .filter_by(office_id=csr.office_id) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .filter(ExamType.group_exam_ind == 0).count() group_exams = Exam.query \ .filter_by(office_id=csr.office_id) \ .filter(Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .filter(ExamType.group_exam_ind == 1) \ .join(Booking, Exam.booking_id == Booking.booking_id) \ .filter(Booking.sbc_staff_invigilated == 0).count() #.filter(Booking.invigilator_id.is_(None))\ TODO: Update this plz group_attention = Exam.query \ .filter_by(office_id=csr.office_id)\ .filter(Exam.deleted_date.is_(None))\ .filter(Exam.exam_returned_date.is_(None))\ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id)\ .filter(ExamType.group_exam_ind == 1)\ .join(Booking, Exam.booking_id == Booking.booking_id)\ .filter(Booking.start_time < start_date).count() if group_attention > 0 and individual_exams > 0: group_attention += individual_exams result = self.csr_schema.dump(csr) active_citizens = self.citizen_schema.dump(active_citizens) return {'csr': result.data, 'individual_exams': individual_exams, 'individual_exams_past_schedule': individual_exams_past_schedule, 'group_exams': group_exams, 'group_individual_attention': group_attention, 'active_citizens': active_citizens.data, 'back_office_display': self.back_office_display, 'recurring_feature_flag': self.recurring_feature_flag, 'errors': result.errors} except exc.SQLAlchemyError as e: print(e) return {'message': 'API is down'}, 500
class CsrSelf(Resource): csr_schema = CSRSchema() citizen_schema = CitizenSchema(many=True) exam_schema = ExamSchema(many=True) exam_type_schema = ExamTypeSchema() timezone = pytz.timezone("US/Pacific") back_office_display = application.config['BACK_OFFICE_DISPLAY'] recurring_feature_flag = application.config['RECURRING_FEATURE_FLAG'] @api_call_with_retry @jwt.has_one_of_roles([Role.internal_user.value]) def get(self): try: # print('====> ATTENTION NEEDED') csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) if not csr: return {'Message': 'User Not Found'}, 404 db.session.add(csr) active_sr_state = SRState.get_state_by_name("Active") today = datetime.now() start_date = self.timezone.localize(today).date() # print('====> ATTENTION NEEDED==>start_Date',start_date) active_citizens = Citizen.query \ .join(Citizen.service_reqs) \ .filter_by(sr_state_id=active_sr_state.sr_state_id) \ .join(ServiceReq.periods) \ .filter_by(csr_id=csr.csr_id) \ .filter(Period.time_end.is_(None)) # Get a list of all current exams for the office. office_exams = Exam.query \ .filter(Exam.office_id == csr.office_id, \ Exam.exam_returned_date.is_(None), \ Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .outerjoin(Booking, Exam.booking_id == Booking.booking_id) \ .outerjoin(Booking.booking_invigilators, Booking.booking_id == Booking.booking_invigilators.c.invigilator_id) \ .all() # Default condition ... attention is not needed for any exam. attention_needed = False # Check for attention needed, individual exam. individual = [] for exam in office_exams: if exam.exam_type.group_exam_ind == 0: # print('====> INDIVIDUAL EXAM CHECKS',exam.exam_name) if exam.booking is not None: # print('====> EXAM BOOKING IS NOT NONE') # print('====> EXAM.BOOKING==>start_Date', start_date) # print('====> EXAM.BOOKING==>exam.booking.start_time', exam.booking.start_time) attention_needed = attention_needed or exam.booking.start_time.date( ) < start_date # print('====> ATTENTION NEEDED',attention_needed) if exam.expiry_date is not None: # print('====> EXPIRY IS NOT NONE') # print('====> EXAM.BOOKING==>start_Date', start_date) # print('====> EXAM.BOOKING==>exam.expiry_date', exam.expiry_date) attention_needed = attention_needed or exam.expiry_date.date( ) < start_date # print('====> ATTENTION NEEDED', attention_needed) if exam.is_pesticide and exam.exam_received_date is None: # print('====> PESTICIDE AND NOT RECEIVED') attention_needed = True # print('====> ATTENTION NEEDED', attention_needed) if exam.exam_returned_date is not None: # print('====> exam.exam_returned_date') attention_needed = False # print('====> ATTENTION NEEDED', attention_needed) if attention_needed: individual.append(exam) # Only do further checks if attention not already needed. group = [] if not attention_needed: for exam in office_exams: if exam.exam_type.group_exam_ind == 1: # print('====> GROUP EXAM CHECKS',exam.exam_name) if exam.booking is not None: # print('====> ATTENTION NEEDED==>start_Date', start_date) # print('====> EXAM.BOOKING==>exam.booking.start_time', exam.booking.start_time) attention_needed = attention_needed or exam.booking.start_time.date( ) < start_date # print('====> ATTENTION NEEDED', attention_needed) if exam.expiry_date is not None: # print('====> EXPIRY IS NOT NONE') # print('====> EXAM.BOOKING==>start_Date', start_date) # print('====> EXAM.BOOKING==>exam.expiry_date', exam.expiry_date) attention_needed = attention_needed or exam.expiry_date.date( ) < start_date # print('====> ATTENTION NEEDED', attention_needed) if exam.booking is not None and exam.number_of_students is not None: # print('====> exam.number_of_students IS NOT NONE') # print('====> EXAM.BOOKING==>exam.number_of_students', exam.number_of_students) # print('====> EXAM.BOOKING==>len(exam.booking.invigilators', len(exam.booking.invigilators)) attention_needed = attention_needed or ( len(exam.booking.invigilators) < 1 and exam.number_of_students < 25) attention_needed = attention_needed or ( len(exam.booking.invigilators) < 2 and exam.number_of_students > 24) # print('====> ATTENTION NEEDED', attention_needed) if exam.is_pesticide and exam.exam_received_date is None: # print('====> PESTICIDE AND NOT RECEIVED') attention_needed = True # print('====> ATTENTION NEEDED', attention_needed) if exam.exam_returned_date is not None: attention_needed = False # print('====> ATTENTION NEEDED', attention_needed) if attention_needed: group.append(exam) result = self.csr_schema.dump(csr) active_citizens = self.citizen_schema.dump(active_citizens) return { 'csr': result, 'attention_needed': attention_needed, 'active_citizens': active_citizens, 'back_office_display': self.back_office_display, 'recurring_feature_flag': self.recurring_feature_flag, 'errors': self.csr_schema.validate(csr) } except exc.SQLAlchemyError as e: print(e) return {'message': 'API is down'}, 500
class ExamPost(Resource): exam_schema = ExamSchema() bcmp_service = BCMPService() @jwt.has_one_of_roles([Role.internal_user.value]) @api_call_with_retry def post(self): is_bcmp_req = True if request.args.get('bcmp_pesticide') else False my_print("is_bcmp_req: ") my_print(is_bcmp_req) csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) json_data = request.get_json() exam = self.exam_schema.load(json_data) warning = self.exam_schema.validate(json_data) my_print("json_data: ") my_print(json_data) if warning: logging.warning("WARNING: %s", warning) return {"message": warning}, 422 if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!"}, 403 if exam.is_pesticide: formatted_data = self.format_data(json_data, exam) exam = formatted_data["exam"] job = self.bcmp_service.check_exam_status(exam) my_print(job) if job and job['jobProperties'] and job['jobProperties']['JOB_ID']: exam.event_id = job['jobProperties']['JOB_ID'] db.session.add(exam) db.session.commit() result = self.exam_schema.dump(exam) return {"exam": result, "errors": self.exam_schema.validate(exam)}, 201 ## formating data to save on bcmp def format_data(self, json_data, exam): candidates_list_bcmp = [] pesticide_office = None if json_data["sbc_managed"] == "sbc": pesticide_office = Office.query.filter_by(office_id=exam.office_id).first() else: pesticide_office = Office.query.filter_by(office_name="Pesticide Offsite").first() exam.office_id = pesticide_office.office_id if json_data["ind_or_group"] == "individual": exam_type = ExamType.query.filter_by(exam_type_id=exam.exam_type_id).first() if not exam_type: exam_type = ExamType.query.filter_by(pesticide_exam_ind=1, group_exam_ind=1).first() exam.exam_type = exam_type else: logging.info("For Group Exams") exam_type = ExamType.query.filter_by(exam_type_name="Group Environment Exam").first() if exam_type: exam.exam_type_id = exam_type.exam_type_id exam.exam_type = exam_type if json_data["candidates"]: candidates = json_data["candidates"] candidates_list = [] for candidate in candidates: candidate_temp = {} candidate_temp["examinee_name"] = candidate["name"] candidate_temp["examinee_email"] = candidate["email"] candidate_temp["exam_type_id"] = candidate["exam_type_id"] candidate_temp["fees"] = candidate["fees"] candidate_temp["payee_ind"] = 1 if (candidate["billTo"] == "candidate") else 0 candidate_temp["receipt"] = candidate["receipt"] candidate_temp["receipt_number"] = candidate["receipt"] candidate_temp["payee_name"] = candidate["payeeName"] candidate_temp["payee_email"] = candidate["payeeEmail"] candidates_list.append(candidate_temp) # for bcmp service candidates_bcmp = copy.deepcopy(candidate_temp) exam_type = ExamType.query.filter_by(exam_type_id=candidate["exam_type_id"]).first() if exam_type.exam_type_name: candidates_bcmp["exam_type"] = exam_type.exam_type_name candidates_list_bcmp.append(candidates_bcmp) exam.candidates_list = candidates_list return { 'exam': exam, 'candidates_list_bcmp': candidates_list_bcmp, 'pesticide_office': pesticide_office, }
class CsrSelf(Resource): csr_schema = CSRSchema() citizen_schema = CitizenSchema(many=True) exam_schema = ExamSchema(many=True) exam_type_schema = ExamTypeSchema() timezone = pytz.timezone("US/Pacific") back_office_display = application.config['BACK_OFFICE_DISPLAY'] recurring_feature_flag = application.config['RECURRING_FEATURE_FLAG'] @oidc.accept_token(require_token=True) @api_call_with_retry def get(self): try: csr = CSR.find_by_username(g.oidc_token_info['username']) if not csr: return {'Message': 'User Not Found'}, 404 db.session.add(csr) active_sr_state = SRState.get_state_by_name("Active") today = datetime.now() start_date = self.timezone.localize(today) active_citizens = Citizen.query \ .join(Citizen.service_reqs) \ .filter_by(sr_state_id=active_sr_state.sr_state_id) \ .join(ServiceReq.periods) \ .filter_by(csr_id=csr.csr_id) \ .filter(Period.time_end.is_(None)) # Get a list of all current exams for the office. office_exams = Exam.query \ .filter(Exam.office_id == csr.office_id, \ Exam.exam_returned_date.is_(None), \ Exam.deleted_date.is_(None)) \ .join(ExamType, Exam.exam_type_id == ExamType.exam_type_id) \ .outerjoin(Booking, Exam.booking_id == Booking.booking_id) \ .outerjoin(Booking.booking_invigilators, Booking.booking_id == Booking.booking_invigilators.c.invigilator_id) \ .all() # Default condition ... attention is not needed for any exam. attention_needed = False # Check for attention needed, individual exam. individual = [] for exam in office_exams: if exam.exam_type.group_exam_ind == 0: if exam.booking is not None: attention_needed = attention_needed or exam.booking.start_time < start_date if exam.expiry_date is not None: attention_needed = attention_needed or exam.expiry_date < start_date if exam.exam_returned_date is not None: attention_needed = False if attention_needed: individual.append(exam) # Only do further checks if attention not already needed. group = [] if not attention_needed: for exam in office_exams: if exam.exam_type.group_exam_ind == 1: attention_needed = attention_needed or exam.booking.start_time < start_date if exam.expiry_date is not None: attention_needed = attention_needed or exam.expiry_date < start_date if exam.booking is not None and exam.number_of_students is not None: attention_needed = attention_needed or exam.booking.start_time < start_date attention_needed = attention_needed or (len(exam.booking.invigilators) < 1 and exam.number_of_students < 25) attention_needed = attention_needed or (len(exam.booking.invigilators) < 2 and exam.number_of_students > 24) if exam.exam_returned_date is not None: attention_needed = False if attention_needed: group.append(exam) result = self.csr_schema.dump(csr) active_citizens = self.citizen_schema.dump(active_citizens) return {'csr': result.data, 'attention_needed': attention_needed, 'active_citizens': active_citizens.data, 'back_office_display': self.back_office_display, 'recurring_feature_flag': self.recurring_feature_flag, 'errors': result.errors} except exc.SQLAlchemyError as e: print(e) return {'message': 'API is down'}, 500