def load(self, data, many=None, partial=None): de_data = super().load(data, many=many, partial=partial) de_data = [de_data] if not many else de_data for de_data_item in de_data: option_class, option_name = de_data_item['repeat_option'].split( '.') de_data_item['repeat_option'] = eval(option_class)[option_name] base_time_slot_dicts = de_data_item.get('base_time_slots') if base_time_slot_dicts is not None: base_slots = [] for base_slot_dict in base_time_slot_dicts: base_slot = TimeSlot.create(commit=False, **base_slot_dict) base_slots.append(base_slot) de_data_item['base_time_slots'] = base_slots repeat_time_slot_dicts = de_data_item.get('repeat_time_slots', []) if repeat_time_slot_dicts is not None: repeat_slots = [] for repeat_slot_dict in repeat_time_slot_dicts: repeat_slot = TimeSlot.create(commit=False, **repeat_slot_dict) repeat_slots.append(repeat_slot) de_data_item['repeat_time_slots'] = repeat_slots return de_data if many else de_data[0]
def test_schedule(self): with self.app.app_context(): ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59), duration=30) ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59), duration=60) end_at = datetime(2018, 3, 14, 9, 59, 59) schedule = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts1, ts0]) self.db.session.add(schedule) self.db.session.commit() EXPECTED_SLOTS = [ REPEATTIMESLOt(base_time_slot=ts0, repeat_num=0, repeat_option=RepeatOption.WEEKLY), RepeatTimeSlot(base_time_slot=ts1, repeat_num=0, repeat_option=RepeatOption.WEEKLY), RepeatTimeSlot(base_time_slot=ts0, repeat_num=1, repeat_option=RepeatOption.WEEKLY), RepeatTimeSlot(base_time_slot=ts1, repeat_num=1, repeat_option=RepeatOption.WEEKLY), RepeatTimeSlot(base_time_slot=ts0, repeat_num=2, repeat_option=RepeatOption.WEEKLY), ] # for rts in expected_slots: # rts._start_at = rts.start_at calculated_slots = schedule.get_repeat_time_slots() print(calculated_slots) assert len(calculated_slots) == len(expected_slots) for (ts, exp_ts) in zip(calculated_slots, expected_slots): assert (ts.start_at == exp_ts.start_at and ts.base_time_slot.duration == exp_ts.base_time_slot.duration) schedule.repeat_time_slots = expected_slots db.session.add(schedule) db.session.commit() # print(expected_slots[0].start_at, expected_slots[1].start_at) # print(schedule.repeat_time_slots[0].start_at, # schedule.repeat_time_slots[1].start_at) schedule.repeat_time_slots[0].repeat_num = 10 for ts in schedule.repeat_time_slots: print(ts.start_at) db.session.add(schedule.repeat_time_slots[0]) db.session.commit() for ts in schedule.repeat_time_slots: print(ts.start_at)
def test_schedule(self): with self.app.app_context(): ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59), duration=30) ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59), duration=60) end_at = datetime(2018, 3, 14, 9, 59, 59) schedule = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts1, ts0]) db.session.add(schedule) db.session.commit() rp = self.test_client.get('/api/v1/timeslots/1,2') # print_json(rp.data) rp = self.test_client.get('/api/v1/schedules/1') # print_json(rp.data) ts2_dict = dict(start_at=datetime(2018, 12, 27, 11, 59, 59).isoformat(), duration=30) ts3_dict = dict(start_at=datetime(2018, 12, 28, 11, 59, 59).isoformat(), duration=60) end_at_str = datetime(2019, 1, 20, 9, 59, 59).isoformat() rp = self.test_client.post( '/api/v1/schedules', data=json.dumps( dict( repeat_option=str(RepeatOption.WEEKLY), repeat_end_at=end_at_str, base_time_slots=[ts2_dict, ts3_dict], )), content_type='application/json', ) # print_json(rp.data) end_at_str = datetime(2019, 2, 20, 9, 59, 59).isoformat() rp = self.test_client.patch( '/api/v1/schedules/2', data=json.dumps( dict( repeat_option=str(RepeatOption.WEEKLY), repeat_end_at=end_at_str, # base_time_slots=[ts2_dict, ts3_dict], )), content_type='application/json', )
def loaddb_sessions(filename): """ Populates the database with sessions and session-related relationships from a yml file. Requires loaddb_games and loaddb_users """ sessions = yaml.safe_load(open(filename)) # premier tour de boucle, creation des sessions et des timeslots dico_timeslots = dict() # k=session_yml_id, v=timeslot_object dico_sessions = dict() # k=session_yml_id, v=session_object for id, s in sessions.items(): session_object = Session(nb_players_required=s["nb_players_required"], notifactions_sent=s["notifactions_sent"], confirmed=s["confirmed"], timeout=s["timeout"], archived=s["archived"]) db.session.add(session_object) dico_sessions[id] = session_object timeslot = s["timeslot"] timeslot_object = TimeSlot(beginning=timeslot["beginning"], end=timeslot["end"], day=timeslot["day"]) db.session.add(timeslot_object) dico_timeslots[id] = timeslot_object db.session.commit() # deuxieme tour de boucle, ajout des relations SessionXTimeslot, SessionXGame et SessionXUser for id, s in sessions.items(): session_object = dico_sessions[id] session_object.timeslot_id = dico_timeslots[id].id load_relationship(s, 'session_id', session_object.id, 'games', Use, Game.from_title, 'game_id', ['expected_time'], 'title') load_relationship(s, 'session_id', session_object.id, 'players', Play, User.from_username, 'user_id', ['confirmed', 'won'], 'username') db.session.commit()
def timeslots(request): if request.method == 'GET': slots = TimeSlot.objects.order_by("-date", "-start_time") # If the method is get, then just display the suggestion page return render(request, 'professor_view/add_time_slots.html', { 'title': 'Add time slot', "timeslots": slots }) else: # slots = json.loads(request.POST.get("slots", "")) startTimes = request.POST.getlist("startTimes[]") endTimes = request.POST.getlist("endTimes[]") professor_email = request.POST.get("professor_email") prof = None try: prof = Professor.objects.get(email=professor_email) except Professor.DoesNotExist: return JsonResponse({'result': "Erro"}) date = request.POST.get("date") professor_name = request.user.first_name + " " + request.user.last_name if prof != None: professor_name = prof.title + " " + professor_name for i in range(len(startTimes)): start = startTimes[i] end = endTimes[i] timeslot = TimeSlot() timeslot.save_data(professor_name, professor_email, start, end, date) timeslot.save() return JsonResponse({'result': 'Ok'})
def create_db_entries(self): with self.app.app_context(): d0 = Dependent(first_name='adela', last_name='zhu') d1 = Dependent(first_name='dudu', last_name='du') u0 = User(username='******', email='*****@*****.**', first_name='zack', last_name='zhu') u0.dependents = [d0, d1] u1 = User(username='******', email='*****@*****.**', first_name='shirly', last_name='zheng') ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59), duration=30) ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59), duration=60) end_at = datetime(2018, 3, 14, 9, 59, 59) schedule = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts1, ts0]) c0 = Class(creator=u0, title='english class', description='learn english', duration=60) addr0 = Address(primary_street='12345 ABC st', city='XYZ', state='FL', zipcode='12345', country='USA', creator=u0) cs0 = ClassSession(parent_class=c0, creator=u0, schedule=schedule) self.db.session.add_all([u0, u1, schedule, c0, cs0, addr0]) self.db.session.commit()
def post(self): json_data = request.get_json() if not json_data: raise RequestException("No input data", 400) try: data = timeslot_schema.load(json_data) except ValidationError as err: raise RequestException("Invalid input data", 400, err.messages) timeslot = TimeSlot.create(**data) result = timeslot_schema.dump(timeslot) response = jsonify({ APIConst.MESSAGE: 'created new timeslot', APIConst.DATA: result }) return response
def delete_appointment(request, id): app = Appointment.objects.get(id=id) app.delete() slot = TimeSlot() slot.save_data(app.professor_name, app.professor_email, app.start_time, app.end_time, app.date) slot.save() return redirect('/all_appointments/')
def add_session_form(form): """ Create the new objects related to the new organized session :return: if the session can be added, return the id of the session, else return False """ date = form.day.data timeB = form.timeB.data timeE = form.timeE.data is_ok = True # check format day if date is None: is_ok = False flash("Le format de la date ne correspond pas à AAAA-MM-JJ et/ou le numéro du mois (1-12) et/ou du jour(1-29/30/31 selon le mois) est incorrecte", "warning") # check format timeB if timeB is None: is_ok = False flash("Le format de l'heure de début ne correspond pas à HH:MM, et/ou le numéro de l'heure (0-23) et/ou le nombre de minutes (0-59) est incorecte", "warning") # check format timeE if timeE is None: is_ok = False flash("Le format de l'heure de fin ne correspond pas à HH:MM, et/ou le numéro de l'heure (0-23) et/ou le nombre de minutes (0-59) est incorecte", "warning") if is_ok: timeB.replace(second=0) timeE.replace(second=0) datetimeform = date.isoformat()+"T"+timeB.strftime('%H:%M:%S') actual = datetime.datetime.now().replace(microsecond = 0).isoformat() #give a string in ISO 8601 : "YYYY-MM-DDTHH:MM:SS" if actual > datetimeform: is_ok = False flash("Vous ne pouvez pas créer une session pour une date antérieur à aujoud'hui", "warning") return False else: timeout = datetime.date(year=date.year, month=date.month, day=date.day+2) timeslot = TimeSlot(timeB.strftime('%H:%M:%S'), timeE.strftime('%H:%M:%S'), date.isoformat()) # timeslot.add_to_db() session = Session(0,timeout.strftime('%Y-%m-%d %H:%M:%S'),1) # session.add_to_db() return session.id
def patch(self, id): timeslot = self.get_resource_with_ids(TimeSlot, id) json_data = request.get_json() try: data = timeslot_patch_schema.load(json_data, partial=True) except ValidationError as err: raise RequestException("Invalid input data", 400, err.messages) try: timeslot.update(**data) except Exception as err: raise RequestException( payload={APIConst.INPUT: json_data}) from err result = timeslot_schema.dump(TimeSlot.get_with_id(timeslot.id)) response = jsonify({ APIConst.MESSAGE: 'updated timeslot {}'.format(id), APIConst.DATA: result }) return response
def add_time_slot(self, order, start, end): one_time_slot = TimeSlot(order=order, start=start, end=end) one_time_slot.save()
def create_vars(self): self.a1 = Address(line1='1234 MB 1234', line2='3700 Spruce St', city='Philadelphia', state='PA', zip_code='14109') self.a2 = Address(line1='4567 MB 1234', line2='3600 Spruce St', city='Philadelphia', state='PA', zip_code='14109') self.timeslots_list = \ [TimeSlot(day_of_week = 0, start_time = time(8,0), end_time = time(18,30)), TimeSlot(day_of_week = 1, start_time = time(7,0), end_time = time(19,30)), TimeSlot(day_of_week = 2, start_time = time(7,30), end_time = time(18,30)), TimeSlot(day_of_week = 3, start_time = time(8,0), end_time = time(19,30)), TimeSlot(day_of_week = 4, start_time = time(10,0), end_time = time(15,30)), TimeSlot(day_of_week = 5, start_time = time(8,15), end_time = time(18,45)), TimeSlot(day_of_week = 6, start_time = time(9,0), end_time = time(20,45))] self.timeslots_list2 = \ [TimeSlot(day_of_week = 0, start_time = time(8,0), end_time = time(18,30)), TimeSlot(day_of_week = 1, start_time = time(7,0), end_time = time(19,30)), TimeSlot(day_of_week = 3, start_time = time(8,0), end_time = time(19,30)), TimeSlot(day_of_week = 4, start_time = time(10,0), end_time = time(15,30)), TimeSlot(day_of_week = 5, start_time = time(8,15), end_time = time(18,45)), TimeSlot(day_of_week = 6, start_time = time(9,0), end_time = time(20,45))] self.desc = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sem neque, vehicula ac nisl at, porta porttitor enim. Suspendisse nibh eros, pulvinar nec risus a, dignissim efficitur diam. Phasellus vestibulum posuere ex, vel hendrerit turpis molestie sit amet. Nullam ornare magna quis urna sodales, vel iaculis purus consequat. Mauris laoreet enim ipsum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla facilisi. In et dui ante. Morbi elementum dolor ligula, et mollis magna interdum non. Mauris ligula mi, mattis at ex ut, pellentesque porttitor elit. Integer volutpat elementum tristique. Ut interdum, mauris a feugiat euismod, tortor.""" self.u1 = User(email='*****@*****.**', password='******', first_name='Ben', last_name='Sandler', roles=[Role(name='User')], is_enabled=True) self.u2 = User(email='*****@*****.**', password='******', first_name='Steve', last_name='Smith', roles=[Role(name='User')], is_enabled=True) self.u3 = User( email='*****@*****.**', password='******', first_name='Sarah', last_name='Smith', roles=[Role(name='Admin')], is_enabled=True) self.p1 = PhoneNumber(number='1234567898') self.p2 = PhoneNumber(number='9876543215')
def setUp(self): self.assertTrue(settings.FAKE_SMS_SERVER) # 创建老师 teacher_user = User.objects.create(username=self.teacher_name) teacher_user.password = make_password(self.teacher_password, self.teacher_salt) teacher_user.email = self.teacher_email teacher_user.save() profile = Profile(user=teacher_user, phone=self.teacher_phone) profile.save() teacher = Teacher(user=teacher_user) teacher.save() teacher_group = Group.objects.get(name="老师") teacher_user.groups.add(teacher_group) teacher_user.save() profile.save() teacher.save() teacher_account = Account(user=teacher_user) teacher_account.save() # 为老师创建能力 grade = Grade.objects.get(name="高三") subject = Subject.objects.get(name="英语") ability = Ability.objects.get(grade=grade, subject=subject) teacher.abilities.add(ability) # 设置面试记录 teacher.status = Teacher.INTERVIEW_OK teacher.status_confirm = True # 设置性别 profile.gender = "f" profile.save() # 设置区域 other_region = Region.objects.get(name="其他") teacher.region = other_region # 设置老师级别 teacher_level = Level.objects.all()[0] teacher.level = teacher_level # 为老师创建对应价格 price = Price(region=other_region, ability=ability, level=teacher_level, price=1, salary=2, commission_percentage=3) price.save() # 设置老师名称 teacher.name = self.teacher_name teacher.save() # 创建家长 parent_user = User.objects.create(username=self.parent_name) parent_user.password = make_password(self.parent_password, self.parent_salt) parent_user.email = self.parent_email parent_user.save() parent_profile = Profile(user=parent_user, phone=self.parent_phone) parent_profile.save() parent_group = Group.objects.get(name="家长") parent_user.groups.add(parent_group) parent_user.save() parent_profile.save() parent = Parent(user=parent_user) parent.save() # 创建订单 school = School(name="逗比中学", address="逗比路", region=Region.objects.get(name="其他"), center=True, longitude=0, latitude=0, opened=False) school.save() school.init_prices() # 为老师添加学校 teacher.schools.add(school) order = Order(parent=parent, teacher=teacher, school=school, grade=Grade.objects.get(name="一年级"), subject=Subject.objects.get(name="数学"), coupon=None, price=200, hours=50, total=100, paid_at=make_aware(datetime.datetime.now()), status=Order.PAID) order.save() # 创建订单里的课程 one_time_slot = TimeSlot( order=order, start=make_aware(datetime.datetime(2016, 1, 1, 8, 0, 0)), end=make_aware(datetime.datetime(2016, 1, 1, 10, 0, 0))) one_time_slot.save() one_time_slot = TimeSlot( order=order, start=make_aware(datetime.datetime(2015, 12, 30, 15, 0, 0)), end=make_aware(datetime.datetime(2015, 12, 30, 17, 0, 0))) one_time_slot.save() one_time_slot = TimeSlot( order=order, start=make_aware(datetime.datetime(2015, 12, 20, 11, 0, 0)), end=make_aware(datetime.datetime(2015, 12, 20, 12, 0, 0))) one_time_slot.save() # 检查订单的数目是否正确 order = Order.objects.get(teacher=teacher) self.assertEqual(3, len(order.timeslot_set.filter(deleted=False)))
def create_booking(current_user=None): data = request.get_json() start_time = data['datetime'] # 900 * 1000 is 15 minutes end_time = start_time + 900 * 1000 # check if input time clashes with existing timeslot clash = TimeSlot.query.filter(TimeSlot.vet_id == data['vetId'], TimeSlot.start_time <= start_time, TimeSlot.end_time >= end_time).first() if clash: return jsonify({'message': 'Conflict with existing bookings'}), 400 # check if input time is within vet working hours start_datetime = datetime.datetime.fromtimestamp(start_time / 1e3) weekday = get_weekday(start_datetime) vet_working_hours = VetSchedule.query.filter( VetSchedule.day_of_week == weekday).first() if vet_working_hours is None: return jsonify({'message': 'Vet is not working on this day'}), 400 vet_on_duty = check_vet_on_duty(start_datetime, vet_working_hours) if not vet_on_duty: return jsonify({'message': 'Not within vet working hour'}), 400 # add booking to db new_time_slot = TimeSlot(start_time=start_time, end_time=end_time, vet_id=data['vetId']) db.session.add(new_time_slot) db.session.flush() db.session.refresh(new_time_slot) if current_user: pet_owner = PetOwner.query.filter_by(user_id=current_user.uid).first() pet_owner_id = pet_owner.id pet_id = data['petId'] # create PetOwner and Pet row for guest else: pet_owner = PetOwner(phone=data['phone'], email=data['email']) animal_type = AnimalType.query.filter_by( name=data['animalType']).first() db.session.add(pet_owner) db.session.flush() db.session.refresh(pet_owner) pet = Pet(animal_id=animal_type.id, owner_id=pet_owner.id) db.session.add(pet) db.session.flush() db.session.refresh(pet) pet_owner_id = pet_owner.id pet_id = pet.id vet = Vet.query.filter_by(id=data['vetId']).first() new_booking = Booking(pet_id=pet_id, owner_id=pet_owner_id, time_slot_id=new_time_slot.id, vet_id=data['vetId'], clinic_id=vet.clinic[0].id) db.session.add(new_booking) db.session.commit() booking = Booking.query.filter_by(time_slot_id=new_time_slot.id).first() return jsonify({ 'message': 'New booking created!', 'bookingNumber': booking.booking_number })
def test_class(self): with self.app.app_context(): d0 = Dependent(first_name='adela', last_name='zhu') u0 = User(username='******', email='*****@*****.**', first_name='zack', last_name='zhu') u0.dependents.append(d0) u1 = User(username='******', email='*****@*****.**', first_name='zerg', last_name='zerg') ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59), duration=30) ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59), duration=60) end_at = datetime(2018, 3, 14, 9, 59, 59) schedule = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts1, ts0]) db.session.add_all([u0, u1, schedule]) db.session.commit() address_dicts = [ dict(creator_id=1, primary_street='789 WWWW LN', city='XYZ', state='FL', zipcode='12345', country='USA'), dict(creator_id=1, primary_street='123 ABC LN', city='XYZ', state='CA', zipcode='11111', country='CHINA'), ] rp = self.test_client.post( '/api/v1/classes', data=json.dumps( dict(title='swimming class', description='simply the best', duration=60, num_of_lessons_per_session=10, capacity=2, min_age=5, creator_id=1, locations=address_dicts)), content_type='application/json', ) # print_json(rp.data) rp = self.test_client.get('/api/v1/classes/1') # print_json(rp.data) rp = self.test_client.patch( '/api/v1/classes/1', data=json.dumps( dict( title='swimming class', description='simply the best', duration=60, num_of_lessons_per_session=10, capacity=2, min_age=5, creator_id=1, # locations=[{'id': 2}] )), content_type='application/json', ) # print_json(rp.data) rp = self.test_client.post( '/api/v1/class-sessions', data=json.dumps(dict( class_id=1, creator_id=1, schedule_id=1, )), content_type='application/json', ) # print_json(rp.data) ts2_dict = dict(start_at=datetime(2018, 12, 27, 11, 59, 59).isoformat(), duration=30) ts3_dict = dict(start_at=datetime(2018, 12, 28, 11, 59, 59).isoformat(), duration=60) end_at_str = datetime(2019, 1, 20, 9, 59, 59).isoformat() rp = self.test_client.post( '/api/v1/schedules', data=json.dumps( dict( repeat_option=str(RepeatOption.WEEKLY), repeat_end_at=end_at_str, base_time_slots=[ts2_dict, ts3_dict], )), content_type='application/json', ) # print_json(rp.data) rp = self.test_client.patch( '/api/v1/class-sessions/1', data=json.dumps(dict( class_id=2, creator_id=2, schedule_id=2, )), content_type='application/json', )
def test_class(self): with self.app.app_context(): u0 = User(username='******', email='*****@*****.**', first_name='zack', last_name='zhu') c0 = Class(title='swimming class') c1 = Class(title='soccer class') u0.created_classes.append(c0) u0.created_classes.append(c1) db.session.add(u0) db.session.commit() assert c0.creator == u0 cs0 = ClassSession(class_id=c0.id, creator_id=u0.id) ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59), duration=30) ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59), duration=60) end_at = datetime(2018, 3, 14, 9, 59, 59) sch0 = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts0, ts1]) cs0.schedule = sch0 self.db.session.add(cs0) self.db.session.commit() tl0 = TemplateLesson(class_session_id=cs0.id, time_slot=ts0) tl1 = TemplateLesson(class_session_id=cs0.id, time_slot=ts1) cs0.template_lessons = [tl0, tl1] lessons = cs0.create_lessons() # db.session.add_all(lessons) # db.session.commit() l0 = Lesson(class_session=cs0) print(l0.type) # [cs0.lessons.append(l) for l in lessons] # cs0.lessons.append(l0) cs0.lessons = lessons + [l0] self.db.session.add(cs0) self.db.session.commit() print(cs0.template_lessons[:]) print(cs0.lessons[0].type) exit() cs1 = ClassSession(class_id=c1.id, creator_id=u0.id) ts2 = TimeSlot(start_at=datetime(2018, 12, 27, 11, 59, 59), duration=30) ts3 = TimeSlot(start_at=datetime(2018, 12, 28, 11, 59, 59), duration=60) end_at = datetime(2019, 1, 20, 9, 59, 59) sch1 = Schedule(repeat_option=RepeatOption.WEEKLY, repeat_end_at=end_at, base_time_slots=[ts2, ts3]) cs1.schedule = sch1 tl2 = TemplateLesson(class_session_id=cs1.id, time_slot=ts2) tl3 = TemplateLesson(class_session_id=cs1.id, time_slot=ts3) cs1.template_lessons = [tl2, tl3] lessons = cs1.create_lessons() self.db.session.add(cs1) self.db.session.commit() print(cs1.template_lessons[:]) print(cs1.lessons[:]) print(self.db.session.query(Lesson).all())