Example #1
0
def import_schedules_to_db(data):
    """
    Writes the schedule data from the json file to the db

    :param data: <dict> Dictionary containing schedule data
    :return: Number of imported schedules
    """
    for row in data:
        s = Schedule(description=row['description'])
        grp = Group.query.filter_by(code=row['group']).first()
        s.group = grp.id
        module = Module.query.filter_by(code=row['module']).first()
        s.module = module.id
        db.session.add(s)
        db.session.commit()

        for item in row['items']:
            si = ScheduleItem(title=item['title'],
                              description=item['description'],
                              start=datetime.strptime(item['start'],
                                                      '%Y-%m-%d %H:%M'),
                              end=datetime.strptime(item['end'],
                                                    '%Y-%m-%d %H:%M'),
                              room=item['room'],
                              schedule=s.id)
            db.session.add(si)
            db.session.commit()
    return str(len(data))
Example #2
0
def create_schedule():
    data = request.get_json() or {}
    data['schedule_area'] = Area.query.filter_by(
        name=data['schedule_area'] or None).first()
    data['schedule_shift'] = Shift.query.filter_by(
        name=data['schedule_shift'] or None).first()
    for time in [
            'start1', 'start2', 'start3', 'start4', 'end1', 'end2', 'end3',
            'end4'
    ]:
        data[time] = dfs(data[time])
    schedule = Schedule.query.filter_by(schedule_area=data['schedule_area'],
                                        schedule_shift=data['schedule_shift'],
                                        name=data['name']).first()
    if schedule:
        s = schedule
    else:
        s = Schedule()
    s.from_dict(data)
    db.session.add(s)
    db.session.commit()
    response = jsonify(s.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_kpi', id=s.id)
    return response
Example #3
0
def index_post(request, user_id, user, pto):
    form = request.POST
    if not form:
        return HttpResponse("No form found")
    err_msg = PaidTimeOff.validate_PTO_form(form)
    if len(err_msg) > 0:
        messages.add_message(request, messages.INFO, err_msg)
    else:
        try:
            date_begin = Schedule.reformat(form['date_begin'])
            date_end = Schedule.reformat(form['date_end'])
            Schedule.objects.create(user=user,
                                    pto=pto,
                                    date_begin=date_begin,
                                    date_end=date_end,
                                    event_name=form['event_name'],
                                    event_type='PTO',
                                    event_desc=form['event_description'],
                                    created_at=timezone.now(),
                                    updated_at=timezone.now())
            messages.add_message(request, messages.INFO,
                                 "Information successfully updated")
        except Exception as e:
            messages.add_message(request, messages.INFO, str(e))
    url = "/users/%s/paid_time_off/" % user_id
    return redirect(url, permanent=False)
def scheduler():
    form = ScheduleForm()
    if form.validate_on_submit():
        # 일정 rawtext 자르고 일정화하기 수행
        ndates, temp = schedule_rawtext_parser(form.rawtext.data) # 위에 함수 만들어놓음

        print("입력된 일정 : ",ndates)
        if len(temp)==3:
            schedule = Schedule(rawtext=form.rawtext.data,period_start=ndates[0],period_end=ndates[1],
                                title=temp[1],body=temp[2], author=current_user)
        elif len(temp)==2:
            schedule = Schedule(rawtext=form.rawtext.data,period_start=ndates[0],period_end=ndates[1],
                                title=temp[1],body=temp[1], author=current_user)
        else :
            flash('일정의 기간, 제목, 내용 순으로 입력하셔야 합니다')
            return redirect(url_for('scheduler'))
        db.session.add(schedule)
        db.session.commit()
        # sleep(2)
        flash('New schedule is updated.')
        return redirect(url_for('scheduler'))
    user = {'username':'******'}
    # 일정 뷰 및 페이지네이션&네비게이션
    page = request.args.get('page',1, type=int)
    schedules = current_user.schedules.order_by(Schedule.period_start.desc()).paginate(
        page, app.config['SCHEDULES_PER_PAGE'], False)
    next_url = url_for('scheduler', page=schedules.next_num) \
        if schedules.has_next else None
    prev_url = url_for('scheduler', page=schedules.prev_num) \
        if schedules.has_prev else None
    return render_template('scheduler.html', title="bright`s home",
        form=form, schedules=schedules.items, next_url=next_url, prev_url=prev_url)
    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 create_new_unaccepted_version(data):
    """
    Creates unaccepted version of existing schedule
    :param data: json with all information for every individual schedule
    """
    if acc_test.check_access(1) is False:
        return redirect(url_for("main.index"))

    unaccepted_schedule = Schedule.query.filter_by(
        name="%s-%s-%s" % (data["main_data"]["year"], data["main_data"]["month"],
                           data["main_data"]["workplace"]), accepted=False).first()

    name = unaccepted_schedule.name
    year = unaccepted_schedule.year
    month = unaccepted_schedule.month
    workplace = unaccepted_schedule.workplace
    hours = unaccepted_schedule.hrs_to_work
    accepted = True
    version = unaccepted_schedule.version + 1
    billing_period = unaccepted_schedule.billing_period
    schedule = Schedule(name=name, year=year, month=month, workplace=workplace, hrs_to_work=hours,
                        accepted=accepted, version=version, billing_period=billing_period)
    db.session.add(schedule)

    ind_schedules_to_db(data, schedule, billing_period)
    db.session.commit()

    for ind_schedule in unaccepted_schedule.ind:
        db.session.delete(ind_schedule)
    db.session.delete(unaccepted_schedule)
    db.session.commit()
Example #7
0
def addschedule():

    if request.method == "POST":

        # get date
        
        wc_date = datetime.strptime(request.form.get('weekCommencementDate'), '%Y-%m-%d').date()
        format_date = datetime.strftime(wc_date, "%d-%m-%Y")

        # make sure user entered a week commencement date
        today_index = date.weekday(wc_date)
        if today_index != 0:
            flash('Unsuccessful. You can only enter a date starting on a Monday.')
            return redirect(url_for('schedule.viewschedule'))
        
        # stop double entry of same wc date
        check = Schedule.query.filter_by(wc_date=wc_date).first()
        print(check)
        if check:
            flash('Unsuccessful. You have already entered a date for that week.')
            return redirect(url_for('schedule.viewschedule'))
        

        # add into database
        schedule = Schedule(wc_date=wc_date, format_date=format_date)
        db.session.add(schedule)
        db.session.commit()

        return redirect(url_for('schedule.viewschedule'))
Example #8
0
    def get_schedule_key(self, schedule):
        """
        Get (or create) the schedule key based on the schedule data

        :param schedule: The schedule data
        :type schedule: app.robot.value_objects.Schedule
        :return: The schedule key
        :rtype: google.appengine.ext.ndb.Key
        """
        key = self.generate_schedule_key(schedule)
        logging.debug("Searching schedule...")
        schedule_model = lru_cache.get(key)
        if schedule_model:
            logging.debug("Found schedule in LRU cache :D")
            raise ndb.Return(ndb.Key(Schedule, key))
        logging.debug("Searching (or even registering) schedule in NDB")
        schedule_model = yield Schedule.get_or_insert_async(
            key,
            hourStart=schedule.hourStart,
            minuteStart=schedule.minuteStart,
            numberOfLessons=schedule.numberOfLessons,
            dayOfWeek=schedule.dayOfWeek,
            room=schedule.room,
            context_options=context_options
        )
        """ type: app.models.Schedule """
        lru_cache[key] = schedule_model
        raise ndb.Return(schedule_model.key)
Example #9
0
def config_schedule(area_name, shift_name, schedule_name):
    area = Area.query.filter_by(name=area_name).first()
    shift = Shift.query.filter_by(name=shift_name).first()
    form = CreateScheduleForm(original_name=schedule_name,
                              area=area,
                              shift=shift)
    if form.validate_on_submit():
        s = Schedule.query.filter_by(name=schedule_name,
                                     id_shift=shift.id).first()
        if not s:
            s = Schedule(name=form.name.data)
            db.session.add(s)
            s.add_area(area)
            s.add_shift(shift)
        s.name = form.name.data
        s.make_times_list(start1=form.start1.data,
                          start2=form.start2.data,
                          start3=form.start3.data,
                          start4=form.start4.data,
                          end1=form.end1.data,
                          end2=form.end2.data,
                          end3=form.end3.data,
                          end4=form.end4.data)
        db.session.commit()
        flash('Successfully added {} schedule for {} {}'.format(
            form.name.data, area.name, shift.name))
        return redirect(
            url_for('main.area_schedules',
                    area_name=area_name,
                    shift_name=shift_name))
    elif request.method == 'GET':
        if schedule_name != 'new':
            s = Schedule.query.filter_by(name=schedule_name,
                                         id_area=area.id,
                                         id_shift=shift.id).first()
            if s:
                form.name.data = s.name
                form.start1.data = s.start1
                form.start2.data = s.start2
                form.start3.data = s.start3
                form.start4.data = s.start4
                form.end1.data = s.end1
                form.end2.data = s.end2
                form.end3.data = s.end3
                form.end4.data = s.end4
    return render_template(tempdir + 'config_schedule.html',
                           title='Edit Schedule',
                           area=area,
                           shift=shift,
                           form=form)
Example #10
0
def update_Schedule(id):
    entity = Schedule.query.get(id)
    if not entity:
        abort(404)
    entity = Schedule(
        date=datetime.datetime.strptime(request.json['date'][:10], "%Y-%m-%d").date(),
        shift_name=request.json['shift_name'],
        employee_id=request.json['employee_id'],
        manager_id=request.json['manager_id'],
        is_in_duty=request.json['is_in_duty'],
        assigned_machine=request.json['assigned_machine'],
        sign_in_at=datetime.datetime.strptime(request.json['sign_in_at'][:10], "%Y-%m-%d").date(),
        sign_out_at=datetime.datetime.strptime(request.json['sign_out_at'][:10], "%Y-%m-%d").date(),
        id=id
    )
    db.session.merge(entity)
    db.session.commit()
    return jsonify(entity.to_dict()), 200
Example #11
0
    def create_schedule(self) -> Schedule:
        """
        :return: returns a Schedule object that has all information about the schedule
        """
        schedule = Schedule()
        for day_index in range(self.get_no_days()):
            """ 
                NOTE: routes_indexes_sorted  consist of indices and not the actual values, the first
                element for example is the index of the route with the lowest number of drivers available   
            """
            routes_indexes_sorted, available_drivers_indexes = self.__get_routes_srt_by_dri_cnt(
                day_index)
            for routes_index in routes_indexes_sorted:
                """ 
                    NOTE: drivers_indexes_sorted  consist of indices and not the actual values, the first
                    element for example is the index of the driver with the lowest score  
                """
                drivers_indexes_sorted = available_drivers_indexes[
                    routes_index]
                shift_index, driver_counter = self.get_no_shifts() - 1, 1
                number_of_drivers = len(drivers_indexes_sorted)
                """
                assigning drivers to the night shift first is important
                because drivers are sorted with their scores and this score
                is based on different things one of them is the number of night
                shifts this driver has been assigned to, so giving the night shift
                drivers with high scores is important 
                """
                while shift_index >= 0 and driver_counter <= number_of_drivers:
                    driver_index = drivers_indexes_sorted[-driver_counter]
                    driver_id = self.get_driver_id_by_index(driver_index)
                    driver_counter += 1

                    if schedule.is_driver_day_used(day_index, driver_id):
                        continue
                    schedule.add_row(driver_id, day_index, routes_index,
                                     shift_index)

                    if shift_index == self.night_shift_index:
                        self.update_driver_used_score(driver_index)
                    shift_index -= 1

        return schedule
Example #12
0
    def post(self):
        schedule = Schedule()

        args = parser.parse_args()
        merge(schedule, args)

        with safe_session(db):
            db.session.add(schedule)

        return {Const.MESSAGE_KEY: '约谈记录成功'}, Const.STATUS_OK
Example #13
0
def managerview():
    """Lets the manager setup the schedule and add Shifts to employees"""
    
    title = "Employee Schedules"
    formLogout = LogoutForm()
    tableForm = scheduleTableForm() 
    scheduleform = managerhomepageForm()
 
    datechosen = date.today() 
    if formLogout.Logout.data and formLogout.is_submitted():
        return redirect(url_for('logout'))  
    if tableForm.goTo.data and request.method == 'POST':
        datechosen = request.form['datebox']
    if scheduleform.Submit.data and scheduleform.is_submitted():
        dateToWork = datetime.date.fromisoformat(request.form['startdate'])
        st = datetime.time.fromisoformat(scheduleform.starttime.data)
        et = datetime.time.fromisoformat(scheduleform.endtime.data)
        empId = int(scheduleform.employees.data)
        s = Schedule( thedates = dateToWork, starttime = st, endtime=et, emp_id = empId, org_id = current_user.organization_id)
        db.session.add(s)
        db.session.commit()
        datechosen = request.form['startdate']
    
    if current_user.manager==False:
        return redirect(url_for('emphomepage'))
    
    
    
    todaysdate = date.today()
    tabledict = {}
    schedules = Schedule.query.filter_by(org_id=current_user.organization_id).filter_by(thedates = datechosen).order_by(Schedule.starttime).all()
    employees = Employee.query.filter_by(organization_id=current_user.organization_id).all()
    employee_list = []
    for employee in employees:
        for schedule in schedules:
            if schedule.emp_id == employee.id:
                tabledict[employee.fname + ' ' + employee.lname] = [schedule.starttime.strftime(format='%H:%M'), schedule.endtime.strftime(format='%H:%M')]
                
        employee_list.append((employee.id, employee.fname +' '+ employee.lname))
    scheduleform.employees.choices = employee_list
    #ts = time(12,30)
    #te = time(16,30)
    #d = date(2019,12,2)
    #S = Schedule(id = 200,thedates = d, starttime = ts, endtime = te, emp_id = 2, org_id = 1 )
    #db.session.add(S)
    #db.session.commit()
    
    return render_template("managerviewsch.html",
                           title=title,
                           formLogout=formLogout,
                           tableForm = tableForm,
                           scheduleform = scheduleform,
                           todaysdate = todaysdate,
                           datechosen = datechosen,
                           tabledict = tabledict)
Example #14
0
def create_Schedule(row):
    schedule = Schedule()
    array = row.split(";")
    date = array[0]

    team1Name = array[1]
    team2Name = array[2]

    team1 = Team()
    team2 = Team()

    datetime_object = datetime.strptime(date, '%d/%m/%Y %H:%M')
    team1.name = team1Name
    team2.name = team2Name

    schedule.scheduled_date = datetime_object
    schedule.home_team = team1
    schedule.visitor_team = team2

    return schedule
def test_all_shifts_assigned(schedule_service, schedule):
    """Test every shift of the day for each route is assigned"""
    for day_index in range(schedule_service.get_no_days()):
        days_col = schedule.get_days_columns()
        is_day = days_col == Schedule.format_day(day_index)
        number_of_shifts = np.sum(is_day)

        no_routes = schedule_service.get_no_routes()
        no_shifts = schedule_service.get_no_shifts()

        assert number_of_shifts == no_routes * no_shifts
Example #16
0
def update_Schedule(id):
    entity = Schedule.query.get(id)
    if not entity:
        abort(404)
    entity = Schedule(
        date=datetime.datetime.strptime(request.json['date'][:10],
                                        "%Y-%m-%d").date(),
        shift_name=request.json['shift_name'],
        employee_id=request.json['employee_id'],
        manager_id=request.json['manager_id'],
        is_in_duty=request.json['is_in_duty'],
        assigned_machine=request.json['assigned_machine'],
        sign_in_at=datetime.datetime.strptime(request.json['sign_in_at'][:10],
                                              "%Y-%m-%d").date(),
        sign_out_at=datetime.datetime.strptime(
            request.json['sign_out_at'][:10], "%Y-%m-%d").date(),
        id=id)
    db.session.merge(entity)
    db.session.commit()
    return jsonify(entity.to_dict()), 200
Example #17
0
def add_schedule():
    form = ScheduleForm()
    if form.validate_on_submit():
        new_schedule = Schedule(flight_number=form.flight_number.data,
                                departure_time=form.departure_time.data,
                                day_week=form.days_week.data,
                                number_seats=form.number_seats.data,
                                route=form.route.data)
        db.session.add(new_schedule)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('add-schedule.html', form=form)
    def test_TaskScheduleTaskWeekMode_ScheduleAndTaskWeekShouldBeDeletedOnTaskDelete(
            self):
        u1 = User(zone=Zone.A, role=Role.SALES_REP)
        o1 = Outlet(zone=Zone.A, rep=u1)
        t1 = Task(outlet=o1,
                  rep=u1,
                  start_date=datetime(2020, 1, 27),
                  end_date=datetime(2020, 1, 30),
                  creator=u1,
                  type=TaskType.CUSTOM,
                  assigner=u1)
        t2 = Task(outlet=o1,
                  rep=u1,
                  start_date=datetime(2020, 1, 27),
                  end_date=datetime(2020, 1, 30),
                  creator=u1,
                  type=TaskType.CUSTOM,
                  assigner=u1)
        w1 = TaskWeek.create_task_weeks(t1)
        w2 = TaskWeek.create_task_weeks(t2)
        s1 = Schedule(rep=u1, task=t1)
        s2 = Schedule(rep=u1, task=t1)
        s3 = Schedule(rep=u1, task=t2)
        s4 = Schedule(rep=u1, task=t2)

        db.session.add_all([u1, o1, t1, t2, s1, s2, s3, s4] + w1 + w2)
        db.session.commit()

        db.session.delete(t1)
        db.session.commit()

        result1 = TaskWeek.query.all()
        result2 = Schedule.query.all()
        result3 = Outlet.query.all()
        result4 = u1.tasks.all()

        self.assertEqual(result1, w2)
        self.assertEqual(result2, [s3, s4])
        self.assertEqual(result3, [o1])
        self.assertEqual(result4, [t2])
Example #19
0
def ScheduleCreate(request):
    # If the request is a POST, check if the fields are valid and the inputs, clean.
    # Save if valid.
    # If the request is not a POST, but a GET, add the initial teacher value
    if request.method == 'POST':
        schedule_create_form = CreateScheduleForm(
            request.POST, initial={'teacher': request.user})

        if schedule_create_form.is_valid():
            new_schedule = Schedule(**schedule_create_form.cleaned_data)
            new_schedule.save()
            return HttpResponseRedirect(reverse(
                'schedule-list'))  # redirects user to the schedule list page
    else:
        schedule_create_form = CreateScheduleForm(
            initial={'teacher': request.user})

    context = {
        'form': schedule_create_form,
    }

    return render(request, 'app/schedule_form.html', context)
Example #20
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])
            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',
        )
Example #21
0
    def test_create_schedule(self):
        """Tests if new schedules can be created"""
        s = Schedule(description='test desc.', module=1)
        db.session.add(s)
        db.session.commit()

        i = ScheduleItem(title='test title',
                         description='test desc.',
                         start=datetime(2009, 10, 1),
                         end=datetime(2010, 10, 1),
                         room='room1',
                         schedule=s.id)
        db.session.add(i)
        db.session.commit()
    def test_ScheduleModel_IsScheduledAvailable_ShouldReturnTrueIfScheduled(
            self):
        u1 = User(zone=Zone.A, role=Role.SALES_REP)
        o1 = Outlet(zone=Zone.A, rep=u1)
        t1 = Task(outlet=o1,
                  rep=u1,
                  creator=u1,
                  type=TaskType.CUSTOM,
                  assigner=u1)
        s1 = Schedule(start=datetime(2021, 1, 27, 4),
                      end=datetime(2021, 1, 27, 7),
                      rep=u1,
                      task=t1)

        db.session.add_all([u1, o1, t1, s1])
        db.session.commit()

        result1 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 2),
                                                 datetime(2021, 1, 27, 8))
        result2 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 2),
                                                 datetime(2021, 1, 27, 3))
        result3 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 4),
                                                 datetime(2021, 1, 27, 8))
        result4 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 5),
                                                 datetime(2021, 1, 27, 8))
        result5 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 5),
                                                 datetime(2021, 1, 27, 7))
        result6 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 5),
                                                 datetime(2021, 1, 27, 6))
        result7 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 7),
                                                 datetime(2021, 1, 27, 8))
        result8 = Schedule.is_schedule_available(u1, datetime(2021, 1, 27, 8),
                                                 datetime(2021, 1, 27, 9))

        self.assertEqual(result1, False)
        self.assertEqual(result2, True)
        self.assertEqual(result3, False)
        self.assertEqual(result4, False)
        self.assertEqual(result5, False)
        self.assertEqual(result6, False)
        self.assertEqual(result7, True)
        self.assertEqual(result8, True)
Example #23
0
    def save_to_db(self):
        if self.id.data:  # edit
            schedule = Schedule.query.get(int(self.id.data))
        else:
            schedule = Schedule()
        schedule.from_time = self.from_time.data
        schedule.to_time = self.to_time.data
        schedule.day = int(self.day.data)
        schedule.message = self.message.data
        schedule.show_id = self.show.data

        db.session.add(schedule)
        db.session.commit()
Example #24
0
    def post(self):
        json_data = request.get_json()
        if not json_data:
            raise RequestException("No input data", 400)
        try:
            data = schedule_schema.load(json_data)
        except ValidationError as err:
            raise RequestException("Invalid input data", 400, err.messages)

        schedule = Schedule.create(**data)
        result = schedule_schema.dump(schedule)
        response = jsonify({
            APIConst.MESSAGE: 'created new schedule',
            APIConst.DATA: result
        })
        return response
def create_unaccepted_version(data):
    """
    Creates new unaccepted schedule
    :param data: json with all information for every individual schedule
    """
    name = "%s-%s-%s" % (data["main_data"]["year"], data["main_data"]["month"], data["main_data"]["workplace"])
    year = int(data["main_data"]["year"])
    month = int(data["main_data"]["month"])
    workplace = data["main_data"]["workplace"]
    hours = data["main_data"]["hours"]
    billing_period = int(data["main_data"]["billing_period"])
    version = int(data["main_data"]["version"])
    schedule = Schedule(name=name, year=year, month=month, workplace=workplace, hrs_to_work=hours,
                        accepted=False, version=version, billing_period=billing_period)
    db.session.add(schedule)

    ind_schedules_to_db(data, schedule, billing_period)
    db.session.commit()
Example #26
0
 def patch(self, id):
     schedule = self.get_resource_with_ids(Schedule, id)
     json_data = request.get_json()
     try:
         data = schedule_patch_schema.load(json_data, partial=True)
     except ValidationError as err:
         raise RequestException("Invalid input data", 400, err.messages)
     try:
         schedule.update(**data)
     except Exception as err:
         raise RequestException(
             payload={APIConst.INPUT: json_data}) from err
     result = schedule_schema.dump(Schedule.get_with_id(schedule.id))
     response = jsonify({
         APIConst.MESSAGE: 'updated schedule {}'.format(id),
         APIConst.DATA: result
     })
     return response
Example #27
0
def optimize(user, tasks, start):
    config = Config()
    config.set_optional_customers(
        tasks.filter(Task.type == TaskType.CUSTOM).all())
    config.set_mandatory_customers(
        tasks.filter(Task.type == TaskType.MANDATORY).all())
    solution = solve(config)

    output = {}
    output['schedule'] = []
    outlets = set()
    output['stats'] = \
    {
        "total_distance": 0.0,
        "total_value": 0.0,
        "num_tasks": 0,
        "num_outlets": 0,
    }
    for day, tasks in solution.items():
        for task in tasks:
            start_date = start + timedelta(days=day,
                                           minutes=task.get('start_time'))
            end_date = start + timedelta(days=day,
                                         minutes=task.get('end_time'))
            user_task = user.tasks.filter(
                Task.id == task.get('task_id')).first()  #task ID
            output['schedule'].append(
                Schedule(start=start_date,
                         end=end_date,
                         rep=user,
                         task=user_task))
            output['stats']['total_distance'] += task.get('travel_time')
            output['stats']['total_value'] += task.get('value')
            output['stats']['num_tasks'] += 1
            outlets.add(task.get('id'))

    output['stats']['num_outlets'] = len(outlets)

    db.session.flush()

    return output
Example #28
0
def create_task():
    form = TaskForm()
    if form.validate_on_submit():
        s_time = form.start_time.data
        e_time = form.end_time.data

        if s_time > e_time:
            flash('Start-Time must be greater than End-Time')
            return redirect(url_for('task.create_task'))
        if s_time < datetime.now():
            flash('Start-Time cannot be in past')
            return redirect(url_for('task.create_task'))
        new_task = Schedule(title=form.title.data,
                            content=form.content.data,
                            start_time=s_time,
                            end_time=e_time,
                            user_id=current_user.id)
        db.session.add(new_task)
        db.session.commit()
        return redirect(url_for('auth.profile'))
    return render_template('newtask.html', form=form)
def create_schedules(schedules):
    """Add schedules, including schedule items, to db"""
    for schedule in schedules:
        s = Schedule(
            description=schedule['description'],
            group=Group.query.filter_by(code=schedule['group']).first().id,
            module=Module.query.filter_by(code=schedule['module']).first().id)
        db.session.add(s)
        db.session.commit()

        for item in schedule['items']:
            si = ScheduleItem(title=item['title'],
                              description=item['description'],
                              start=datetime.strptime(item['start'],
                                                      '%Y-%m-%d %H:%M'),
                              end=datetime.strptime(item['end'],
                                                    '%Y-%m-%d %H:%M'),
                              room=item['room'],
                              schedule=s.id)
            db.session.add(si)
        db.session.commit()
def test_add_schedule_to_db(db):
    dates = date(2019, 12, 25)
    start_time = time(12, 30)
    end_time = time(16, 30)
    employee_id = 1
    organization_id = 1

    sch = Schedule(thedates=dates,
                   starttime=start_time,
                   endtime=end_time,
                   emp_id=employee_id,
                   org_id=organization_id)

    db.session.add(sch)
    assert len(Schedule.query.all()) == 1
    sch_from_db = Schedule.query.get(1)

    assert sch_from_db.thedates == dates
    assert sch_from_db.starttime == start_time
    assert sch_from_db.endtime == end_time
    assert sch_from_db.emp_id == employee_id
    assert sch_from_db.org_id == organization_id
Example #31
0
def set_schedule(
    user_id: int, project_id: int, week: int, hours: int
) -> Optional[Schedule]:
    """
    Logs the number of hours a given user plans to work on a given project for
    a given week. This will override existing values if present.
    :param user_id: The ID of the user that will be logged for these hours.
    :param project_id: The ID of the project on which the suer will work.
    :param week: The week number, where week 0 is the week staring on the 1st
        of January 1AD.
    :param hours: The number of hours to be logged for that week.
    :returns: The schedule created if none existed for that week/project
        combination, the exsting schedule if it was already present, or none if
        either the user_id or project_id did not correspond to this user, or if
        the user is not part of the project.
    """
    session = db.get_session()
    user = session.query(User).filter(User.id == user_id).one_or_none()
    project = session.query(Project).filter(Project.id == project_id).one_or_none()

    if not user or not project:
        return None

    if project not in user.team.projects:
        return None

    schedule = (
        session.query(Schedule)
        .filter(Schedule.project_id == project_id, Schedule.week == week)
        .one_or_none()
    )

    if schedule:
        return schedule

    schedule = Schedule(user=user, project=project, week=week, hours=hours)
    session.add(schedule)
    session.commit()
    return schedule
Example #32
0
    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()
Example #33
0
 def __init__(self, *args, **kwargs):
     super(SelectScheduleForm, self).__init__(*args, **kwargs)
     self.schedule.choices = [('', '选择研修时段')] + [(str(schedule.id), schedule.period.name_time_span) \
         for schedule in Schedule.current_schedules()]