def test_user_and_room_with_many_schedules(self): new_user = User(name="Luiza") db.session.add(new_user) new_room = Room(name="Room") db.session.add(new_room) first_schedule = Schedule(date=datetime(2018, 10, 12), user=new_user, room=new_room) db.session.add(first_schedule) second_schedule = Schedule(date=datetime(2018, 10, 13), user=new_user, room=new_room) db.session.add(second_schedule) db.session.commit() user = User.query.one() room = Room.query.one() self.assertEqual(len(user.schedules), 2) self.assertEqual(len(room.schedules), 2) self.assertEqual(user.schedules[0].date, datetime(2018, 10, 12).date()) self.assertEqual(user.schedules[1].date, datetime(2018, 10, 13).date()) self.assertEqual(room.schedules[0].date, datetime(2018, 10, 12).date()) self.assertEqual(room.schedules[1].date, datetime(2018, 10, 13).date())
def get(self): args = self.parser.parse_args() params = {k: v for k, v in args.items() if v is not None} # Return all user's schedules return Schedule.get_all(params)
def delete(self, schedule_id): # Delete schedule success = Schedule.delete_by_id(schedule_id) if not success: abort(404) return {'result': True}
def get(self, schedule_id): # Get schedule by id schedule = Schedule.get_by_id(schedule_id) if schedule is None: abort(404) # Return user return schedule
def create_schedule(cid): course = Course.query.filter_by(cid=cid).first_or_404() form = ScheduleCreateForm().validate_for_api() with db.auto_commit(): schedule = Schedule(week=form.week.data, topic=form.topic.data, reference=form.reference.data, course_id=course.cid, additional_info=form.additional_info.data, datetime=form.datetime.data) resources = CourseResource.query.filter( CourseResource.id.in_(form.resource_ids.data)).all() schedule.resources = resources assignments = Assignment.query.filter( Assignment.id.in_(form.assignment_ids.data)).all() schedule.assignments = assignments db.session.add(schedule) return Success()
def post(self, cleaner_id): # Validate cleaner if Cleaner.get_by_id(cleaner_id) is None: abort(404, 'Cleaner not found') # Create new schedule args = self.parser_post.parse_args() if args['year'] is None: args['year'] = date.today().year schedule = Schedule(cleaner_id=cleaner_id, year=args['year'], week=args['week'], day_of_week=args['day_of_week'], start_time=args['start_time'], end_time=args['end_time']) # Persist and return schedule schedule.persist() return schedule, 201
def create(self, payloads): self.model_schedule = Schedule() self.model_schedule.stage_id = payloads['stage_id'] self.model_schedule.event_id = payloads['event_id'] self.model_schedule.time_start = datetime.datetime.strptime( payloads['time_start'], "%Y-%m-%d %H:%M:%S.%f") self.model_schedule.time_end = datetime.datetime.strptime( payloads['time_end'], "%Y-%m-%d %H:%M:%S.%f") db.session.add(self.model_schedule) try: db.session.commit() data = self.model_schedule included = self.get_includes(data) return { 'error': False, 'data': data.as_dict(), 'included': included } except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data}
def post(self): args = get_args() if check_schedule(args): return response("There is a conflict in schedule", 409) schedule = Schedule() fill_schedule(schedule, args) schedule.active = True schedule.lastUpdate = datetime.now() schedule.update() return schema.dump(schedule).data, 201
def test_common(self): new_user = User(name="Luiza") db.session.add(new_user) new_room = Room(name="Room") db.session.add(new_room) new_schedule = Schedule(date=datetime(2018, 10, 12), user=new_user, room=new_room) db.session.add(new_schedule) db.session.commit() schedule = Schedule.query.one() self.assertEqual(schedule.date, datetime(2018, 10, 12).date()) self.assertEqual(schedule.user.name, "Luiza") self.assertEqual(schedule.room.name, "Room")
def put(self, schedule_id): # Get schedule by id schedule = Schedule.get_by_id(schedule_id) if schedule is None: abort(404) # Update schedule fields args = self.parser.parse_args() schedule.year = assign(args['year'], schedule.year) schedule.week = assign(args['week'], schedule.week) schedule.day_of_week = assign(args['day_of_week'], schedule.day_of_week) schedule.start_time = assign(args['start_time'], schedule.start_time) schedule.end_time = assign(args['end_time'], schedule.end_time) # Persist changes and return schedule schedule.persist() return schedule
def create_schedule(self, date, user_name, room_name, description): current_app.logger.info("Trying to create a new schedule to date: {}.".format(str(date))) try: date = datetime.strptime(date, "%Y-%m-%d") except ValueError as error: current_app.logger.warning( "Problem with date parser when create a new schedule. The date is: {} ".format(str(date)) ) raise error user = self.user_controller.get_user_by_name(user_name) if not user: current_app.logger.warning("User {} not found when trying to create a new schedule.".format(user_name)) raise UserNotFoundError() room = self.room_controller.get_room_by_name(room_name) if not room: current_app.logger.warning("Room {} not found when trying to create a new schedule.".format(room_name)) raise RoomNotFoundError() schedule = Schedule(date=date, user=user, room=room, description=description) db.session.add(schedule) db.session.commit() current_app.logger.info("Schedule create.")
def schedule_create(): jsonData = request.get_json() with db.auto_commit(): schedule = Schedule() schedule.league_id = jsonData['league_id'] schedule.schedule_process = jsonData['schedule_process'] schedule.schedule_team_a = jsonData['schedule_team_a'] schedule.schedule_team_b = jsonData['schedule_team_b'] schedule.schedule_support_a = jsonData['schedule_support_a'] schedule.schedule_support_b = jsonData['schedule_support_b'] schedule.schedule_score_a = jsonData['schedule_score_a'] schedule.schedule_score_b = jsonData['schedule_score_b'] schedule.schedule_location = jsonData['schedule_location'] schedule.schedule_time = jsonData['schedule_time'] schedule.schedule_judge = jsonData['schedule_judge'] schedule.schedule_status = jsonData['schedule_status'] schedule.schedule_turn_name = jsonData['schedule_turn_name'] db.session.add(schedule) return Success(msg='新增赛事成功')
def upload_image(user_id): """ Accept an schedule with info and image""" image = request.files['file'] header = image.headers['Content-Type'] parsed_header = parse_options_header(header) blob_key_str = parsed_header[1]['blob-key'] store_user_id = request.form.get('store_user_id') store_name = request.form.get('store_name') dep_name = request.form.get('dep_name') upload_user_id = request.form.get('upload_user_id') year = request.form.get('year', type=int) week = request.form.get('week', type=int) week_offset = request.form.get('week_offset', type=int) store = StoreDepartment.get(store_user_id, store_name, dep_name) if not store: # Setup store not found error code = Errors.store_not_found desc = 'Upload Failed: Store Not Found.' return jsonify(code=code, desc=desc) account = Account.get(user_id) if not account: # Setup store not found error code = Errors.account_not_found desc = 'Upload Failed: Account Not Found.' return jsonify(code=code, desc=desc) schedule = store.has_schedule(upload_user_id, year, week, week_offset) if schedule: # Update schedule schedule.image_blob = blobstore.BlobKey(blob_key_str) schedule.upload_user_id = user_id schedule.user_name = account.user_name schedule.put() # Setup results code = 0 desc = 'Upload Successful. Store Updated' else: # No schedule found so make new one and add to store schedule = Schedule(parent=store.key, upload_user_id=user_id, user_name=account.user_name, year=year, week=week, week_offset=week_offset, image_blob=blobstore.BlobKey(blob_key_str)) schedule.put() store.schedules.append(schedule.key) store.put() # Setup results code = 0 desc = 'Upload Successful' return jsonify(code=code, desc=desc)
class ScheduleService(): def get(self): schedules = db.session.query(Schedule).order_by( Schedule.time_start.asc()).all() results = [] for schedule in schedules: data = schedule.as_dict() event = schedule.event user = event.user stage = schedule.stage if event.type == 'discuss panel': _result = [] _speaker = [] pes = db.session.query(PanelEvent).filter_by( event_id=event.id).all() for pe in pes: _result.append(pe.user.include_photos().as_dict()) speaker = db.session.query(Speaker).filter_by( user_id=pe.user_id).first() _speaker.append(speaker.as_dict()) data['user'] = _result for n in range(0, len(data['user'])): data['user'][n]['speaker'] = _speaker[n] else: data['user'] = user.include_photos().as_dict() if user else {} data['event'] = event.as_dict() if event else {} data['stage'] = stage.as_dict() if stage else {} speaker = None if event.type != 'discuss panel': if data['user'] and data['user']['role_id'] == 4: speaker = db.session.query(Speaker).filter_by( user_id=data['user']['id']).first() data['speaker'] = speaker.as_dict() if speaker else {} results.append(data) return { 'error': False, 'data': results, 'message': 'Schedules retrieved succesfully', 'included': {} } def filter(self, param): schedules = self.get()['data'] results = [] day1 = [] day2 = [] day3 = [] for schedule in schedules: if schedule['event'] is not None and EVENT_DATES['1'] in schedule[ 'time_start']: day1.append(schedule) elif schedule['event'] is not None and EVENT_DATES[ '2'] in schedule['time_start']: day2.append(schedule) elif schedule['event'] is not None and EVENT_DATES[ '3'] in schedule['time_start']: day3.append(schedule) response = ResponseBuilder() if param == 'day-1': results = day1 elif param == 'day-2': results = day2 elif param == 'day-3': results = day3 else: results.append(day1) results.append(day2) results.append(day3) result = response.set_data(results).build() return result def show(self, id): schedule = db.session.query(Schedule).filter_by(id=id).first() data = schedule.as_dict() event = schedule.event data['event'] = event.as_dict() if event.type == 'discuss panel': _result_user = [] _result_speaker = [] pes = db.session.query(PanelEvent).filter_by( event_id=event.id).all() for pe in pes: user = pe.user.include_photos().as_dict() speaker = db.session.query(Speaker).filter_by( user_id=pe.user.id).first() user['speaker'] = speaker.as_dict() _result_user.append(user) data['user'] = _result_user elif event.type != 'other': data['user'] = event.user.include_photos().as_dict() # add includes if schedule is None: return { 'error': True, 'data': None, 'message': 'Schedule not found' } return { 'error': False, 'data': data, 'message': 'Schedule retrieved successfully', } def create(self, payloads): self.model_schedule = Schedule() self.model_schedule.stage_id = payloads['stage_id'] self.model_schedule.event_id = payloads['event_id'] self.model_schedule.time_start = datetime.datetime.strptime( payloads['time_start'], "%Y-%m-%d %H:%M:%S.%f") self.model_schedule.time_end = datetime.datetime.strptime( payloads['time_end'], "%Y-%m-%d %H:%M:%S.%f") db.session.add(self.model_schedule) try: db.session.commit() data = self.model_schedule included = self.get_includes(data) return { 'error': False, 'data': data.as_dict(), 'included': included } except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data} def update(self, payloads, id): try: self.model_schedule = db.session.query(Schedule).filter_by(id=id) self.model_schedule.update({ 'event_id': payloads['event_id'], 'stage_id': payloads['stage_id'], 'time_start': datetime.datetime.strptime(payloads['time_start'], "%Y-%m-%d %H:%M:%S.%f"), 'time_end': datetime.datetime.strptime(payloads['time_end'], "%Y-%m-%d %H:%M:%S.%f"), 'updated_at': datetime.datetime.now() }) db.session.commit() data = self.model_schedule.first() included = self.get_includes(data) return { 'error': False, 'data': data.as_dict(), 'included': included } except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data} def delete(self, id): self.model_schedule = db.session.query(Schedule).filter_by(id=id) if self.model_schedule.first() is not None: # delete row self.model_schedule.delete() db.session.commit() return {'error': False, 'data': None} else: data = 'data not found' return {'error': True, 'data': data} def get_includes(self, schedules): included = [] if isinstance(schedules, list): for schedule in schedules: temp = {} temp['event'] = schedule.event.as_dict() temp['stage'] = schedule.stage.as_dict() temp['user'] = schedule.event.user.as_dict( ) if schedule.event.user else None included.append(temp) else: temp = {} temp['event'] = schedules.event.as_dict() temp['stage'] = schedules.stage.as_dict() temp['user'] = schedules.event.user.as_dict( ) if schedules.event.user else None included.append(temp) return included
User.query.delete() user = User(name="uName", email="*****@*****.**", uid="000000000", userType=UserTypesEnum.PROFESSOR) user.add(user) print("User ID {}\n".format(user.id)) room = Room() room.name = "E003" roomUser = RoomUser() roomUser.user = user room.users.append(roomUser) room.active = True room.add(room) print("Room ID {}\n".format(room.id)) schedule = Schedule() schedule.room = room schedule.userType = UserTypesEnum.PROFESSOR schedule.dayOfWeek = DaysOfWeekEnum.MONDAY schedule.beginTime = datetime.now().hour schedule.endTime = datetime.now().hour schedule.lastUpdate = datetime.now() schedule.active = True schedule.add(schedule) print("Schedule ID {}\n".format(schedule.id))
def get(self, cleaner_id): args = self.parser_get.parse_args() params = {k: v for k, v in args.items() if v is not None} return Schedule.get_all_by_cleaner(cleaner_id, params)
def get_all_schedules(): schedules = Schedule.query().fetch() schedules = [s.to_dict_images() for s in schedules] return sort_schedules(schedules, None)