Exemplo n.º 1
0
def process_exception_list(temp_exceptions):
    new_temp_exceptions = [[] for _ in range(len(temp_exceptions))]

    for i in range(0, len(temp_exceptions)):
        print("--new i---")
        for j in range(0, len(temp_exceptions[i])):

            if j == 0:
                new_temp_exceptions[i].append(temp_exceptions[i][j])

            else:
                no_intersection = True
                for k in range(0, len(new_temp_exceptions[i])):

                    date_range1 = DateTimeRange(
                        str(temp_exceptions[i][j][0:19]),
                        str(temp_exceptions[i][j][22:41]))
                    date_range2 = DateTimeRange(
                        str(new_temp_exceptions[i][k][0:19]),
                        str(new_temp_exceptions[i][k][22:41]))

                    if date_range1.is_intersection(date_range2):
                        new_range = date_range1.intersection(date_range2)
                        new_temp_exceptions[i][k] = str(new_range).replace(
                            "T", " ")
                        no_intersection = False
                if no_intersection:
                    new_temp_exceptions[i].append(temp_exceptions[i][j])

    for i in range(0, len(new_temp_exceptions)):
        for j in range(0, len(new_temp_exceptions[i])):
            if str(new_temp_exceptions[i][j][0:19]) == str(
                    new_temp_exceptions[i][j][22:41]):
                new_temp_exceptions[i].remove(new_temp_exceptions[i][j])
    return new_temp_exceptions
Exemplo n.º 2
0
def parseIbHours(ibHours, tz):
    if not isinstance(ibHours, str):
        fatal.errorAndExit('trading hours is a string')
    openHours = []
    # '20200427:0930-20200427:1600;20200428:0930-20200428:1600'
    ranges = ibHours.split(';')
    m = re.compile('.*:CLOSED')
    for range_ in ranges:
        if range_ == '':
            continue
        if m.match(range_):  # skip closed days
            continue
        ts = range_.split('-')
        if len(ts) != 2:
            fatal.errorAndExit(
                'only two timestamps per range: {}     {}'.format(ts, ibHours))
        start = tz.localize(datetime.strptime(
            ts[0], '%Y%m%d:%H%M')).astimezone(pytz.utc)
        end = tz.localize(datetime.strptime(ts[1], '%Y%m%d:%H%M')).astimezone(
            pytz.utc)
        r = DateTimeRange(start, end)
        if not r.is_valid_timerange():
            fatal.errorAndExit('should get a valid timerange')
        openHours.append(r)
    logging.debug('openHours: %s', openHours)
    return openHours
Exemplo n.º 3
0
    def configure_and_execute_overlap_test(self, schedule_get_all_mock,
                                           start_reprocess_time,
                                           end_reprocess_time):

        self.configure_schedules_mock(schedule_get_all_mock,
                                      start_reprocess_time, end_reprocess_time)

        scheduling_range = DateTimeRange(
            tzutils.utc_to_local(self.start_reprocess_time),
            tzutils.utc_to_local(self.end_reprocess_time))
        scheduled_range = DateTimeRange(
            tzutils.local_to_utc(start_reprocess_time),
            tzutils.local_to_utc(end_reprocess_time))
        expected_message = \
            "400 Bad Request: Cannot schedule a reprocessing for scope " \
            "[toStringMock] for reprocessing time [%s], because it already " \
            "has a schedule for a similar time range [%s]." \
            % (scheduling_range, scheduled_range)

        expected_message = re.escape(expected_message)

        self.assertRaisesRegex(
            http_exceptions.BadRequest, expected_message,
            self.endpoint.validate_reprocessing_schedules_overlaps,
            self.generate_all_scopes_object(), self.end_reprocess_time,
            self.start_reprocess_time)

        schedule_get_all_mock.assert_called_with(
            identifier=[self.scope_ids[0]])
Exemplo n.º 4
0
def hours_validator(period):
    """ Validates that the received time period is in the
        following format: `'HH:MM-HH:MM'`
    """
    time_points = period.split('-')
    if len(time_points) != 2:
        error = "Working hours period should be separated by '-'"
        raise ValidationError(error)

    for time in time_points:
        time_check = time.split(':')
        if len(time_check) != 2:
            raise ValidationError('Time format is not HH:MM')
        if int(time_check[0]) not in range(0, 24) or \
                int(time_check[1]) not in range(0, 60):
            raise ValidationError('Time format is not HH:MM')

    # Checks whether there is no time inversion in the input range
    today = date.today()
    range_start = datetime.strptime(time_points[0], '%H:%M').time()
    range_end = datetime.strptime(time_points[1], '%H:%M').time()
    range_start_dt = datetime.combine(today, range_start)
    range_end_dt = datetime.combine(today, range_end)
    output_range = DateTimeRange(range_start_dt, range_end_dt)
    try:
        output_range.validate_time_inversion()
    except ValueError:
        raise ValidationError(f'Time inversion identified: "{period}"')
Exemplo n.º 5
0
def check_if_rent_is_possible(centre_id,
                              gear_id,
                              rent_amount,
                              rent_start,
                              rent_end,
                              max_rent,
                              session=None):
    rent_start = datetime.datetime.strptime(rent_start,
                                            '%Y-%m-%dT%H:%M:%S.%fZ')
    rent_end = datetime.datetime.strptime(rent_end, '%Y-%m-%dT%H:%M:%S.%fZ')
    all_rents = session.query(GearRental).filter_by(
        centre_id=centre_id,
        gear_id=gear_id).filter(GearRental.rent_end > rent_start,
                                GearRental.rent_start < rent_end,
                                GearRental.rent_status != -1).all()
    iter_start = rent_start
    while iter_start <= rent_end:
        total_number_of_rented_gear = 0
        iter_start_with_delta = iter_start + datetime.timedelta(minutes=15)
        timerange = DateTimeRange(iter_start, iter_start_with_delta)
        for rent in all_rents:
            rent_time_range = DateTimeRange(rent.rent_start, rent.rent_end)
            if timerange.intersection(rent_time_range):
                total_number_of_rented_gear += rent.rent_amount
        if total_number_of_rented_gear + rent_amount > max_rent:
            return False
        iter_start = iter_start_with_delta
    return True
Exemplo n.º 6
0
    def is_cache_available(self, cache_file_path):
        if not cache_file_path.isfile():
            logger.debug("cache not found: {}".format(cache_file_path))
            return False

        try:
            dtr = DateTimeRange(datetime.fromtimestamp(cache_file_path.mtime),
                                datetime.now())
        except OSError:
            return False

        if not dtr.is_valid_timerange():
            return False

        cache_elapsed = CacheTime(dtr.get_timedelta_second())
        cache_msg = "path={path}, lifetime={lifetime:.1f}h, elapsed={elapsed:.1f}h".format(
            path=cache_file_path,
            lifetime=self.__cache_lifetime.hour,
            elapsed=cache_elapsed.hour)

        if cache_elapsed < self.__cache_lifetime:
            logger.debug("cache available: {}".format(cache_msg))
            return True

        logger.debug("cache expired: {}".format(cache_msg))

        return False
Exemplo n.º 7
0
class TestDateTimeRange_truncate:
    @pytest.mark.parametrize(
        ["value", "expected"],
        [
            [0, DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME)],
            [
                10,
                DateTimeRange("2015-03-22 10:00:30" + TIMEZONE,
                              "2015-03-22 10:09:30" + TIMEZONE)
            ],
        ],
    )
    def test_normal(self, datetimerange_normal, value, expected):
        datetimerange_normal.truncate(value)
        assert datetimerange_normal == expected

    @pytest.mark.parametrize(["value", "expected"], [[-10, ValueError]])
    def test_exception(self, datetimerange_normal, value, expected):
        with pytest.raises(expected):
            datetimerange_normal.truncate(value)

    @pytest.mark.parametrize(["value"], [[10]])
    def test_null(self, datetimerange_null_start, value):
        with pytest.raises(TypeError):
            datetimerange_null_start.truncate(value)
Exemplo n.º 8
0
def test_change_record_data():
    start_datetime = datetime.datetime(year=2020, month=1, day=1)
    schedule = Schedule(start_datetime, duration=3600)

    _range = DateTimeRange(start_datetime,
                           start_datetime + datetime.timedelta(minutes=1))
    assert schedule.add_record('OLD TYPE', _range)

    assert len(schedule.records) == 1
    assert 'data' in schedule.records[-1]
    assert schedule.records[-1]['data'] is None

    existed_record = schedule.records[-1]

    new_range = DateTimeRange(start_datetime,
                              start_datetime + datetime.timedelta(minutes=2))
    new_record = {
        'type': 'NEW TYPE',
        'range': new_range,
        'data': {
            'key': 'val'
        }
    }
    assert schedule.change_record(existed_record, new_record)

    assert 'data' in schedule.records[-1]
    assert schedule.records[-1]['data'] == {'key': 'val'}
Exemplo n.º 9
0
 def test_normal(
         self, start, start_format, end, end_format,
         separator, is_output_elapse, expected):
     dtr = DateTimeRange(start, end, start_format, end_format)
     dtr.separator = separator
     dtr.is_output_elapse = is_output_elapse
     assert str(dtr) == expected
Exemplo n.º 10
0
class TestDateTimeRange_set_time_range:
    @pytest.mark.parametrize(
        ["start", "end", "expected"],
        [
            [
                START_DATETIME_TEXT,
                END_DATETIME_TEXT,
                DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME),
            ],
            [None, None, DateTimeRange(None, None)],
        ],
    )
    def test_normal(self, start, end, expected):
        dtr = DateTimeRange()
        dtr.set_time_range(start, end)
        assert dtr == expected

    @pytest.mark.parametrize(
        ["start", "end", "expected"],
        [
            ["invalid time string", END_DATETIME_TEXT, ValueError],
            [START_DATETIME_TEXT, "invalid time string", ValueError],
            ["invalid time string", "invalid time string", ValueError],
        ],
    )
    def test_exception(self, start, end, expected):
        dtr = DateTimeRange()
        with pytest.raises(expected):
            dtr.set_time_range(start, end)
Exemplo n.º 11
0
    def horarios_futuros(self, data, solicitante):
        quando = self.solicitacao_futura(solicitante)
        if quando is not None:
            inicio = localtime(quando.inicio).strftime('%d/%m/%Y às %H:%M')
            raise Exception(
                f"Você já tem uma solicitação prevista para {inicio} na situação {quando.status}"
            )

        if not (max(self.inicio, date.today()) <= data.date() <= self.fim):
            raise Exception(
                f"A data deve ser entre {self.inicio} e {self.fim}, mas você informou a data {data}."
            )

        result = []
        for vaga in self.vaga_set.filter(dia=data.weekday()):
            time_range = DateTimeRange(datetime.combine(data, vaga.inicio),
                                       datetime.combine(data, vaga.fim))
            for dt in time_range.range(timedelta(minutes=self.janela)):
                if make_aware(dt) > now():
                    quantidade = Solicitacao.objects.filter(
                        agenda=self,
                        inicio=dt,
                        status__in=[
                            Solicitacao.Status.DEFERIDO,
                            Solicitacao.Status.SOLICITADO
                        ]).count()
                    if quantidade < vaga.atendimentos:
                        result.append(dt)
        return result[:-1]
Exemplo n.º 12
0
class Test_DateTimeRange_hash(object):
    @pytest.mark.parametrize(
        ["value", "expected"],
        [
            [
                DateTimeRange("2015-03-22T10:00:00+0900",
                              "2015-03-22T10:10:00+0900"),
                ("2015-03-22T10:00:00+0900", "2015-03-22T10:10:00+0900"),
            ],
        ],
    )
    def test_normal(self, value, expected):
        assert hash(value) == expected

    @pytest.mark.parametrize(
        ["value", "expected"],
        [
            [
                DateTimeRange(),
                ("NaT", "NaT"),
            ],
        ],
    )
    def test_null(self, value, expected):
        assert hash(value) == expected
Exemplo n.º 13
0
 def clean(self):
     cleaned_data = super().clean()
     # get value
     staff = cleaned_data.get('staff')
     start_date = cleaned_data.get("start_date")
     end_date = cleaned_data.get("end_date")
     # check if start_date is before end_date else raise error
     if start_date > end_date:
         raise forms.ValidationError(
             _('The start date must be before the end date.'),
             code='invalid')
     # create a range from form
     form_absence_range = DateTimeRange(start_date, end_date)
     # get absences
     absences = Absence.objects.filter(
         start_date__lte=end_date,
         end_date__gte=start_date,
         staff_id=staff.id).exclude(pk=self.instance.pk)
     for absence in absences:
         # create a range absence
         absence_range = DateTimeRange(absence.start_date, absence.end_date)
         # if form range is intersection with absence range raise error
         if form_absence_range.is_intersection(absence_range):
             raise forms.ValidationError(
                 _('An absence already exists on these dates.'),
                 code='invalid')
     return cleaned_data
Exemplo n.º 14
0
def merge_schedules(players: Dict[str, List[DateTimeRange]], required: int,
                    start: datetime) -> Dict[datetime, List[Set[str]]]:
    """Merge individual schedules to time slots where people are free.

    Takes a mapping of people's availability and returns a mapping of
    blocks of time (by the start time) to players free in that block.

    E.g. if Jon is free at 12-2pm and Neel is free from 1-2pm and blocks
    are 30 minutes, then return a dictionary of 4 times, with the first
    2 time blocks mapping to (Jon) and the second two to (Jon, Neel).
    """
    if not start:
        start = datetime.now(timezone("Europe/London")).replace(minute=0,
                                                                second=0,
                                                                microsecond=0)
    candidates = DateTimeRange(start, start + timedelta(days=14))

    potentials = defaultdict(list)

    for candidate_times in candidates.range(timedelta(minutes=MINUTES)):
        candidate_players = []
        for player, timeranges in players.items():
            for timerange in timeranges:
                if timerange.start_datetime <= candidate_times < timerange.end_datetime:
                    candidate_players.append(player)

        for combination_length in range(required, len(candidate_players) + 1):
            combos = combinations(candidate_players, combination_length)
            potentials[candidate_times].extend(combos)

    return potentials
Exemplo n.º 15
0
def find_times(players: Dict[str, List[DateTimeRange]],
               required: int,
               start=None) -> Dict[FrozenSet[str], List[DateTimeRange]]:

    schedules = merge_schedules(players, required, start)
    potentials = defaultdict(list)

    for viable_time, player_sets in schedules.items():
        for player_set in player_sets:

            current_players = frozenset(player_set)
            if len(current_players) < required:
                continue

            if not potentials[current_players]:
                potentials[current_players].append(DateTimeRange(viable_time))

            current_time = potentials[current_players][-1]

            if (viable_time - current_time.start_datetime
                ).total_seconds() <= MINUTES * 60:
                current_time.set_end_datetime(viable_time)
            elif (viable_time -
                  current_time.end_datetime).total_seconds() <= MINUTES * 60:
                current_time.set_end_datetime(viable_time)
            else:
                potentials[current_players].append(DateTimeRange(viable_time))

    for time_ranges in potentials.values():
        for time_range in time_ranges:
            time_range.set_end_datetime(time_range.end_datetime +
                                        timedelta(minutes=MINUTES))

    return potentials
Exemplo n.º 16
0
def update_appointments(id:int):
    print(f'{id}')
    record_id = int(id)
    record = Appointment.query.filter_by(id=record_id).first()
    print(request.json)
    if record:
        date = request.json['date']
        time_from = request.json['time_from']
        time_to = request.json['time_to']

        if date == '' or time_from == '' or time_to == '':
            return jsonify(message='date and time cannot be blank'), 406

        try:
            date_time_from = datetime.datetime.strptime(f'{date}T{time_from}', '%Y-%m-%dT%H:%M:%S')
            date_time_to = datetime.datetime.strptime(f'{date}T{time_to}', '%Y-%m-%dT%H:%M:%S')
        except:
            date_time_from = datetime.datetime.strptime(f'{date}T{time_from}', '%Y-%m-%dT%H:%M')
            date_time_to = datetime.datetime.strptime(f'{date}T{time_to}', '%Y-%m-%dT%H:%M')

        recieved_dates = DateTimeRange(f'{date}T{time_from}', f'{date}T{time_to}')

        ## any booking for the past dates or time cannot be accomodated.
        if datetime.datetime.now() > date_time_from:
            return jsonify(message='Any booking for the past dates or time cannot be accomodated'), 406
        if date_time_from > date_time_to:
            return jsonify(message='Any booking for the past dates or time cannot be accomodated'), 406

        ## booking are'nt allowed during sunday
        if datetime.datetime.strptime(date, '%Y-%m-%d').weekday() == 6:
            return jsonify(message='Sorry appointments are only allowed from Monday to Saturday'), 406

        ## bookings only allowed during opening-hourse
        opening_hours = DateTimeRange(f'{date}T09:00', f'{date}T17:00')
        if (recieved_dates in opening_hours) == False:
            return jsonify(message='Appointments are only allowed from 9:00AM - 5:00PM'), 406

        ## check for conflicting booking records
        success_message = 'You added a new record!'
        datas = Appointment.query.all()
        if datas:
            for data in datas:

                data_dates = DateTimeRange(str(data.date_time_from).replace(' ', 'T'),
                                           str(data.date_time_to).replace(' ', 'T'))
                if data_dates.is_intersection(recieved_dates):
                    if data.id != record_id:
                        return jsonify(message='There is a conflict between your schedule'), 409

        ## update records to the database
        record.first_name = request.json['first_name']
        record.last_name = request.json['last_name']
        record.comments = request.json['comments']
        record.date_time_from = date_time_from
        record.date_time_to = date_time_to

        db.session.commit()
        return jsonify(message="You updated a record"), 202
    else:
        return jsonify(message="record cannot be found!"), 404
Exemplo n.º 17
0
class TestDateTimeRange_add:
    @pytest.mark.parametrize(
        ["value", "add_value", "expected"],
        [
            [
                DateTimeRange("2015-03-22T10:00:00+0900",
                              "2015-03-22T10:10:00+0900"),
                timedelta(seconds=10 * 60),
                DateTimeRange("2015-03-22T10:10:00+0900",
                              "2015-03-22T10:20:00+0900"),
            ],
            [
                DateTimeRange("2015-03-22T10:00:00", "2015-03-22T10:10:00"),
                timedelta(seconds=-10 * 60),
                DateTimeRange("2015-03-22T09:50:00", "2015-03-22T10:00:00"),
            ],
        ],
    )
    def test_normal(self, value, add_value, expected):
        new_datetimerange = value + add_value

        assert new_datetimerange == expected

    @pytest.mark.parametrize(
        ["value", "expected"],
        [["2015-03-22T10:10:00+0900", TypeError], [1, TypeError],
         [None, TypeError]],
    )
    def test_exception(self, datetimerange_normal, value, expected):
        with pytest.raises(TypeError):
            datetimerange_normal + value

    def test_null(self, datetimerange_null):
        with pytest.raises(TypeError):
            datetimerange_null + timedelta(seconds=10 * 60)
Exemplo n.º 18
0
    def create(self, request, *args, **kwargs):
        u = {'user': 1}
        data = request.data
        data.update(u)
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        # Get submitted dates and property id
        startDate = self.request.data.get('startDate')
        endDate = self.request.data.get('endDate')
        propId = self.request.data.get('property')

        # retrieve list of bookings for this property
        bookingsList = self.queryset.filter(property_id=propId)
        # Create date range from request
        inserted_range = DateTimeRange(startDate, endDate)

        # Compare ranges for booking overlaps
        for booking in bookingsList:
            booking_range = DateTimeRange(booking.startDate, booking.endDate)
            if inserted_range.is_intersection(booking_range):
                return Response(status=status.HTTP_400_BAD_REQUEST)

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data,
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Exemplo n.º 19
0
 def test_normal(
     self, start, start_format, end, end_format, separator, is_output_elapse, expected
 ):
     dtr = DateTimeRange(start, end, start_format, end_format)
     dtr.separator = separator
     dtr.is_output_elapse = is_output_elapse
     assert str(dtr) == expected
Exemplo n.º 20
0
class TestDateTimeRange_validate_time_inversion:
    @pytest.mark.parametrize(
        ["value"],
        [
            [DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME)],
            [DateTimeRange(TEST_START_DATETIME, TEST_START_DATETIME)],
        ],
    )
    def test_normal(self, value):
        value.validate_time_inversion()

    def test_inversion(self, datetimerange_inversion):
        with pytest.raises(ValueError):
            datetimerange_inversion.validate_time_inversion()

    @pytest.mark.parametrize(
        ["value"],
        [
            [DateTimeRange(None, None)],
            [DateTimeRange(None, TEST_END_DATETIME)],
            [DateTimeRange(TEST_START_DATETIME, None)],
        ],
    )
    def test_exception(self, value):
        with pytest.raises(TypeError):
            value.validate_time_inversion()
Exemplo n.º 21
0
def update_training_for_staff_after_absence(sender, instance, **kwargs):
    if instance.abs_type.abbr == "FOR":
        absence_range = instance.datetime_range
        old_absence_start_date = instance.tracker.previous("start_date")
        old_absence_end_date = instance.tracker.previous("end_date")
        old_absence_range = DateTimeRange(old_absence_start_date,
                                          old_absence_end_date)

        years = []
        rt = RightTraining.objects.first()
        if rt:
            for value in absence_range.range(datetime.timedelta(days=1)):
                if value.month in range(rt.start_month, 13):
                    year = value.year
                else:
                    year = value.year - 1
                if year not in years:
                    years.append(year)
            if old_absence_start_date and old_absence_end_date:
                for value in old_absence_range.range(
                        datetime.timedelta(days=1)):
                    if value.month in range(rt.start_month, 13):
                        year = value.year
                    else:
                        year = value.year - 1
                    if year not in years:
                        years.append(year)

            call_command('update_training',
                         years=years,
                         staffs=[instance.staff.id])
Exemplo n.º 22
0
def generate_timestamp(start_datetime, sampling_rate, signal_length):
    """

    Parameters
    ----------
    start_datetime :
        
    sampling_rate : float
        
    signal_length : int
        

    Returns
    -------
    list : list of timestamps with length equal to signal_length.
    """
    number_of_seconds = (signal_length - 1)/sampling_rate
    if start_datetime is None:
        start_datetime = dt.datetime.now()
    end_datetime = start_datetime + dt.timedelta(seconds=number_of_seconds)
    time_range = DateTimeRange(start_datetime, end_datetime)
    timestamps = []
    for value in time_range.range(dt.timedelta(seconds=1/sampling_rate)):
        timestamps.append(value)
    if len(timestamps) != signal_length:
        raise Exception("Timestamp series generated is not valid, please "
                        "check sampling rate.")
    return timestamps
Exemplo n.º 23
0
 def test_exception(self, start, start_format, end, end_format, separator,
                    is_output_elapse, expected):
     dtr = DateTimeRange(start, end, start_format, end_format)
     dtr.separator = separator
     dtr.is_output_elapse = is_output_elapse
     with pytest.raises(expected):
         str(dtr)
Exemplo n.º 24
0
def datetimerange_inversion():
    value = DateTimeRange(
        TEST_END_DATETIME, TEST_START_DATETIME)
    value.start_time_format = ISO_TIME_FORMAT
    value.end_time_format = ISO_TIME_FORMAT

    return value
def test_get_records_wrong_range():
    start_datetime = datetime.datetime(year=2020, month=1, day=1)
    schedule = Schedule(start_datetime, duration=3600)

    range_1 = DateTimeRange(start_datetime,
                            start_datetime + datetime.timedelta(minutes=1))
    schedule.add_record('TYPE_1', range_1)

    range_2 = DateTimeRange(start_datetime + datetime.timedelta(minutes=1),
                            start_datetime + datetime.timedelta(minutes=2))
    schedule.add_record('TYPE_1', range_2)

    assert len(schedule.records) == 2

    required_range = DateTimeRange(
        start_datetime + datetime.timedelta(minutes=3),
        start_datetime + datetime.timedelta(minutes=4))

    records = schedule.get_records_in_range(required_range)
    assert len(records) == 0

    required_range = DateTimeRange(
        start_datetime + datetime.timedelta(minutes=2),
        start_datetime + datetime.timedelta(minutes=3))
    records = schedule.get_records_in_range(required_range)
    assert len(records) == 0
Exemplo n.º 26
0
 def test_exception(
         self, start, start_format, end, end_format,
         separator, is_output_elapse, expected):
     dtr = DateTimeRange(start, end, start_format, end_format)
     dtr.separator = separator
     dtr.is_output_elapse = is_output_elapse
     with pytest.raises(expected):
         str(dtr)
Exemplo n.º 27
0
def test_reservation_may_be_requested_right_after_previous_one(resource):
    resource.reserve(
        DateTimeRange('2020-03-01 10:00:00', '2020-03-01 12:00:00'))

    resource.reserve(
        DateTimeRange('2020-03-01 12:00:00', '2020-03-01 14:00:00'))

    assert len(resource.get_reserved_periods()) == 2
Exemplo n.º 28
0
    def test_normal(self):
        value = DateTimeRange("2015-03-22T10:10:00+0900",
                              "2015-03-22T10:20:00+0900")
        expected = DateTimeRange("2015-03-22T10:00:00+0900",
                                 "2015-03-22T10:10:00+0900")

        value -= timedelta(seconds=10 * 60)
        assert value == expected
Exemplo n.º 29
0
def beli_kamar(id_kamar):
    if islogin():
        status = True
        d_checkin = request.form['checkin']
        d_checkout = request.form['checkout']
        d_kamar = kamar.get(kamar.id == id_kamar)
        d_nama = request.form['nama']
        d_ktp = request.form['ktp']

        d_checkin = datetime.datetime.strptime(d_checkin, '%Y-%m-%d')
        d_checkout = datetime.datetime.strptime(d_checkout, '%Y-%m-%d')

        # cek
        d_transaksi = transaksi.select().where(
            (transaksi.selesai == False) & (transaksi.id_kamar == id_kamar))
        if d_transaksi.exists():
            for data in d_transaksi:
                d_checkin_d = datetime.datetime(data.checkin.year,
                                                data.checkin.month,
                                                data.checkin.day, 0, 0)
                d_checkout_d = datetime.datetime(data.checkout.year,
                                                 data.checkout.month,
                                                 data.checkout.day, 0, 0)

                checkin_now = datetime.datetime(d_checkin.year,
                                                d_checkin.month, d_checkin.day,
                                                0, 0)
                checkout_now = datetime.datetime(d_checkout.year,
                                                 d_checkout.month,
                                                 d_checkout.day, 0, 0)

                time_range = DateTimeRange(checkin_now, checkout_now)
                for date in time_range.range(datetime.timedelta(days=1)):
                    check = date
                    if d_checkin_d == check or d_checkout_d == check:
                        status = False

        if status == True:
            lama_menginap = datetime.datetime(
                d_checkout.year, d_checkout.month,
                d_checkout.day, 0, 0) - datetime.datetime(
                    d_checkin.year, d_checkin.month, d_checkin.day, 0, 0)

            d_total_harga = int(lama_menginap.days) * int(d_kamar.harga)

            transaksi.create(id_user=session['iduser'],
                             id_kamar=id_kamar,
                             nama_pemesan=d_nama,
                             no_ktp=d_ktp,
                             checkin=d_checkin,
                             checkout=d_checkout,
                             total_harga=d_total_harga,
                             waktu_transaksi=datetimenow())
            return redirect(url_for('index'))
        return redirect(url_for('index'))
    return redirect(url_for('index'))
Exemplo n.º 30
0
def test_reservation_cant_overlap_with_previous_ones(resource):
    # given
    resource.reserve(
        DateTimeRange('2020-03-01 10:00:00', '2020-03-01 12:00:00'))

    # when
    result = resource.reserve(
        DateTimeRange('2020-03-01 10:00:00', '2020-03-01 12:00:00'))

    assert not result.is_success()
Exemplo n.º 31
0
class TestDateTimeRange_split:
    @pytest.mark.parametrize(
        ["dtr", "separator", "expected"],
        [
            [
                DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME),
                "2015-03-22 10:05:00" + TIMEZONE,
                [
                    DateTimeRange(TEST_START_DATETIME,
                                  "2015-03-22 10:05:00" + TIMEZONE),
                    DateTimeRange("2015-03-22 10:05:00" + TIMEZONE,
                                  TEST_END_DATETIME),
                ],
            ],
            [
                DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME),
                "2015-03-22 09:59:59" + TIMEZONE,
                [DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME)],
            ],
            [
                DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME),
                TEST_START_DATETIME,
                [DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME)],
            ],
            [
                DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME),
                END_DATETIME_TEXT,
                [DateTimeRange(TEST_START_DATETIME, TEST_END_DATETIME)],
            ],
        ],
    )
    def test_normal(self, dtr, separator, expected):
        assert dtr.split(separator) == expected
Exemplo n.º 32
0
def add_appointment():
    date = request.json['date']
    time_from = request.json['time_from']
    time_to = request.json['time_to']

    if date == '' or time_from == '' or time_to == '':
        return jsonify(message='date and time cannot be blank'),406

    date_time_from = datetime.datetime.strptime(f'{date}-{time_from}','%Y-%m-%d-%H:%M')
    date_time_to = datetime.datetime.strptime(f'{date}-{time_to}','%Y-%m-%d-%H:%M')
    recieved_dates = DateTimeRange(f'{date}T{time_from}', f'{date}T{time_to}')

    ## any booking for the past dates or time cannot be accomodated.
    if datetime.datetime.now() > date_time_from:
        return jsonify(message='Any booking for the past dates or time cannot be accomodated'),406
    if date_time_from > date_time_to:
        return jsonify(message='Any booking for the past dates or time cannot be accomodated'), 406

    ## booking are'nt allowed during sunday
    if datetime.datetime.strptime(date,'%Y-%m-%d').weekday() == 6:
        return jsonify(message='Sorry appointments are only allowed from Monday to Saturday'),406

    ## bookings only allowed during opening-hourse
    opening_hours = DateTimeRange(f'{date}T09:00', f'{date}T17:00')
    if (recieved_dates in opening_hours) == False:
        return jsonify(message='Appointments are only allowed from 9:00AM - 5:00PM'),406

    ## check for conflicting booking records
    success_message = 'You added a new record!'
    datas = Appointment.query.all()
    if datas:
        for data in datas:
            data_dates = DateTimeRange(str(data.date_time_from).replace(' ','T'),str(data.date_time_to).replace(' ','T'))
            if data_dates.is_intersection(recieved_dates):
                return jsonify(message='There is a conflict between your schedule'),409

    ## adding records to the database
    first_name = request.json['first_name']
    last_name = request.json['last_name']
    comments = request.json['comments']
    print(first_name, last_name, comments)

    new_appointment = Appointment(
        first_name=first_name,
        last_name=last_name,
        comments=comments,
        date_time_from=date_time_from,
        date_time_to=date_time_to
    )

    db.session.add(new_appointment)
    db.session.commit()

    return jsonify(message=success_message),201
def saveDateRange(start, end):
    givenRange = DateTimeRange(start, end)

    tables = ['Jobs', 'ReviewJobs']
    for table in tables:
        data = []
        query = 'SELECT * FROM ' + table
        cur.execute(query)
        results = [list(each) for each in cur.fetchall()]

        for job in results:
            dateRange = job[15]
            d = [each.lstrip().rstrip() for each in dateRange.split("-")]

            s = d[0].split("/")
            startFormat = str(int(s[2]) + 2000) + "/" + s[1] + "/" + s[0]

            inRange = False

            if len(d) > 1:
                e = d[1].split("/")
                endFormat = str(int(e[2]) + 2000) + "/" + e[1] + "/" + e[0]

                tableRange = DateTimeRange(startFormat, endFormat)



                for day in tableRange.range(relativedelta(days=1)):
                    if day in givenRange:
                        inRange = True

            else:
                inRange = startFormat in givenRange

            if inRange:
                data.append(job)

        columnNames = names.get(table)

        file = "Date Range for " + table + " from " + start.replace("/", "-") + " to " + end.replace("/", "-") + ".csv"

        if len(data) > 0:
            data.insert(0, columnNames)
            data.insert(1, [])

            for i in range(len(data)):
                line = data[i]
                if (i == 0):
                    open(file, 'w+').close()
                with open(file, 'a', newline='') as fp:
                    a = csv.writer(fp, delimiter=',')
                    line = [line]
                    a.writerows(line)
Exemplo n.º 34
0
    def test_normal(self, value, timezone, expected):
        dtr = DateTimeRange(TEST_END_DATETIME, TEST_END_DATETIME)
        dtr.set_start_datetime(value, timezone=timezone)

        assert dtr.start_datetime == expected
Exemplo n.º 35
0
def datetimerange_null():
    value = DateTimeRange(None, None)
    value.time_format = None
    value.end_time_format = None

    return value
Exemplo n.º 36
0
def datetimerange_null_start():
    value = DateTimeRange(None, TEST_END_DATETIME)
    value.time_format = None
    value.end_time_format = ISO_TIME_FORMAT

    return value
Exemplo n.º 37
0
 def test_exception(self, start, end, expected):
     dtr = DateTimeRange()
     with pytest.raises(expected):
         dtr.set_time_range(start, end)
Exemplo n.º 38
0
 def test_normal(self, start, end, expected):
     dtr = DateTimeRange()
     dtr.set_time_range(start, end)
     assert dtr == expected
Exemplo n.º 39
0
 def test_normal(self, value, expected):
     dtr = DateTimeRange(TEST_END_DATETIME, TEST_END_DATETIME)
     dtr.set_end_datetime(value)
     assert dtr.end_datetime == expected