def add_reservation(start, end, reservation):
        day = start.day

        used_days[day] = True

        end += timedelta(microseconds=1)
        start, end = start.strftime("%H:%M"), end.strftime("%H:%M")

        context = resources[utils.string_uuid(reservation.resource)]

        if reservation.status == u"approved":
            rightside_urls = [(_(u"Delete"), reservation_urls.revoke_all_url(reservation.token, context))]
        elif reservation.status == u"pending":
            rightside_urls = [
                (_(u"Approve"), reservation_urls.approve_all_url(reservation.token, context)),
                (_(u"Deny"), reservation_urls.deny_all_url(reservation.token, context)),
            ]
        else:
            raise NotImplementedError

        reservation_lists = report[day][utils.string_uuid(reservation.resource)]
        reservation_lists[reservation.status].append(
            dict(
                start=start,
                end=end,
                email=reservation.email,
                data=reservation.data,
                timespans=json_timespans(start, end),
                rightside_urls=rightside_urls,
                token=reservation.token,
                quota=utils.get_reservation_quota_statement(reservation.quota),
                resource=context,
            )
        )
Example #2
0
    def add_reservation(start, end, reservation):
        day = start.day

        used_days[day] = True

        end += timedelta(microseconds=1)

        start = modules.calendar.to_timezone(start, timezone=timezone)
        end = modules.calendar.to_timezone(end, timezone=timezone)

        start = utils.localize_date(start, time_only=True)
        end = utils.localize_date(end, time_only=True)

        context = resources[utils.string_uuid(reservation.resource)]

        reservation_lists = report[day][utils.string_uuid(
            reservation.resource
        )]
        reservation_lists[reservation.status].append(
            dict(
                start=start,
                end=end,
                email=reservation.email,
                data=reservation.data,
                timespans=json_timespans(start, end),
                id=reservation.id,
                token=reservation.token,
                quota=utils.get_reservation_quota_statement(reservation.quota),
                resource=context,
            )
        )
    def add_reservation(start, end, reservation):
        day = start.day

        used_days[day] = True

        end += timedelta(microseconds=1)

        start = sedate.to_timezone(start, timezone=timezone)
        end = sedate.to_timezone(end, timezone=timezone)

        start = utils.localize_date(start, time_only=True)
        end = utils.localize_date(end, time_only=True)

        context = resources[utils.string_uuid(reservation.resource)]

        reservation_lists = report[day][utils.string_uuid(
            reservation.resource
        )]
        reservation_lists[reservation.status].append(
            dict(
                start=start,
                end=end,
                email=reservation.email,
                data=reservation.data,
                timespans=json_timespans(start, end),
                id=reservation.id,
                token=reservation.token,
                quota=utils.get_reservation_quota_statement(reservation.quota),
                resource=context,
            )
        )
    def test_reservations_export(self):
        self.login_manager()

        resource = self.create_resource()
        sc = resource.scheduler()

        start = datetime(2012, 2, 1, 12, 0)
        end = datetime(2012, 2, 1, 16, 0)
        dates = (start, end)

        reservation_email = u'*****@*****.**'
        sc.allocate(dates, approve_manually=False, quota=2)[0]

        token1 = sc.reserve(reservation_email,
                            dates,
                            data=utils.mock_data_dictionary({
                                'stop': u'hammertime!',
                                'bust': u'a move!'
                            }))

        token2 = sc.reserve(reservation_email,
                            dates,
                            data=utils.mock_data_dictionary({
                                'never': u'gonna',
                                'give': u'you up'
                            }))

        dataset = exports.reservations.dataset({resource.uuid(): resource},
                                               'en')

        self.assertEqual(len(dataset), 2)
        self.assertEqual(len(dataset.headers), 11 + 4)

        self.assertEqual(dataset.dict[0]['Token'], utils.string_uuid(token1))
        self.assertEqual(dataset.dict[0]['Mocktest.stop'], u'hammertime!')
        self.assertEqual(dataset.dict[0]['Mocktest.bust'], u'a move!')
        self.assertEqual(dataset.dict[0]['Mocktest.never'], None)
        self.assertEqual(dataset.dict[0]['Mocktest.give'], None)

        self.assertEqual(dataset.dict[1]['Token'], utils.string_uuid(token2))
        self.assertEqual(dataset.dict[1]['Mocktest.stop'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.bust'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.never'], u'gonna')
        self.assertEqual(dataset.dict[1]['Mocktest.give'], u'you up')

        # just make sure these don't raise exceptions
        dataset.xls
        dataset.json
        dataset.csv
Example #5
0
    def events(self, daterange=None, uuids=None):
        """ Returns the events for the overview. """

        start, end = daterange or self.range
        if not all((start, end)):
            return []

        events = []

        uuids = uuids or self.uuids()
        queries = get_queries(uuids)
        days = queries.availability_by_day(start, end, uuids)

        for day, result in days.items():

            event_start = datetime(day.year, day.month, day.day, 0, 0)
            event_end = event_start + timedelta(days=+1, microseconds=-1)

            availability, resources = result
            events.append(
                dict(start=event_start.isoformat(),
                     end=event_end.isoformat(),
                     title=u'',
                     uuids=[utils.string_uuid(r) for r in resources],
                     className=utils.event_class(availability)))

        return events
Example #6
0
    def events(self, daterange=None, uuids=None):
        """ Returns the events for the overview. """

        start, end = daterange or self.range
        if not all((start, end)):
            return []

        events = []

        uuids = uuids or self.uuids()
        queries = get_queries(uuids)
        days = queries.availability_by_day(start, end, uuids)

        for day, result in days.items():

            event_start = datetime(day.year, day.month, day.day, 0, 0)
            event_end = event_start + timedelta(days=+1, microseconds=-1)

            availability, resources = result
            events.append(dict(
                start=event_start.isoformat(),
                end=event_end.isoformat(),
                title=u'',
                uuids=[utils.string_uuid(r) for r in resources],
                className=utils.event_class(availability)
            ))

        return events
Example #7
0
    def events(self):
        """ Returns the events for the overview. """

        start, end = self.range
        if not all((start, end)):
            return []

        events = []

        uuids = self.uuids()

        is_exposed = exposure.for_allocations(self.context, uuids)

        days = db.availability_by_day(start, end, uuids, is_exposed)
        for day, result in days.items():

            event_start = datetime(day.year, day.month, day.day, 0, 0)
            event_end = event_start + timedelta(days=+1, microseconds=-1)

            availability, resources = result
            events.append(
                dict(start=event_start.isoformat(),
                     end=event_end.isoformat(),
                     title=u'',
                     uuids=[utils.string_uuid(r) for r in resources],
                     className=utils.event_class(availability)))

        return events
Example #8
0
    def scheduler(self, language=None):
        uuid = utils.string_uuid(self.uuid())
        is_exposed = exposure.for_allocations(self, [uuid])

        return db.Scheduler(
            self.uuid(), is_exposed=is_exposed, language=language
        )
    def events(self):
        """ Returns the events for the overview. """

        start, end = self.range
        if not all((start, end)):
            return []

        events = []

        uuids = self.uuids()

        is_exposed = exposure.for_allocations(self.context, uuids)

        days = db.availability_by_day(start, end, uuids, is_exposed)
        for day, result in days.items():

            event_start = datetime(day.year, day.month, day.day, 0, 0)
            event_end = event_start + timedelta(days=+1, microseconds=-1)

            availability, resources = result
            events.append(dict(
                start=event_start.isoformat(),
                end=event_end.isoformat(),
                title=u'',
                uuids=[utils.string_uuid(r) for r in resources],
                className=utils.event_class(availability)
            ))

        return events
    def add_reservation(start, end, reservation):
        day = start.day

        used_days[day] = True

        end += timedelta(microseconds=1)
        start, end = start.strftime('%H:%M'), end.strftime('%H:%M')

        context = resources[utils.string_uuid(reservation.resource)]

        if reservation.status == u'approved':
            rightside_urls = [(
                _(u'Delete'),
                reservation_urls.revoke_all_url(reservation.token, context)
            )]
        elif reservation.status == u'pending':
            rightside_urls = [
                (
                    _(u'Approve'),
                    reservation_urls.approve_all_url(
                        reservation.token, context
                    )
                ),
                (
                    _(u'Deny'),
                    reservation_urls.deny_all_url(reservation.token, context)
                ),
            ]
        else:
            raise NotImplementedError

        reservation_lists = report[day][utils.string_uuid(
            reservation.resource
        )]
        reservation_lists[reservation.status].append(
            dict(
                start=start,
                end=end,
                email=reservation.email,
                data=reservation.data,
                timespans=json_timespans(start, end),
                rightside_urls=rightside_urls,
                token=reservation.token,
                quota=utils.get_reservation_quota_statement(reservation.quota),
                resource=context
            )
        )
Example #11
0
    def highlight_group(self):
        """ Returns the group id to highlight when hovering over any result.
        As there is no reservation view with multiple groups, only one result
        can be returned.

        """
        group = getattr(self, 'group', '')
        return group and utils.string_uuid(self.group) or u''
Example #12
0
    def highlight_group(self):
        """ Returns the group id to highlight when hovering over any result.
        As there is no reservation view with multiple groups, only one result
        can be returned.

        """
        group = getattr(self, "group", "")
        return group and utils.string_uuid(self.group) or u""
Example #13
0
    def scheduler(self, language=None):
        uuid = utils.string_uuid(self.uuid())

        libres_util = getUtility(ILibresUtility)
        libres_util.context.set_service(
            'exposure',
            lambda ctx: LibresExposure(exposure.for_allocations([uuid])))

        return libres_util.scheduler(uuid, settings.timezone().zone)
Example #14
0
    def scheduler(self, language=None):
        uuid = utils.string_uuid(self.uuid())

        libres_util = getUtility(ILibresUtility)
        libres_util.context.set_service(
            'exposure',
            lambda ctx: LibresExposure(exposure.for_allocations([uuid]))
        )

        return libres_util.scheduler(uuid, settings.timezone().zone)
Example #15
0
    def highlight_group(self):
        """ Returns the group id to highlight when hovering over any result.
        As there is no reservation view with multiple groups, only one result
        can be returned.

        """
        if hasattr(self, 'group'):
            if utils.is_uuid(self.group):
                return utils.string_uuid(self.group)
        return u''
Example #16
0
    def highlight_group(self):
        """ Returns the group id to highlight when hovering over any result.
        As there is no reservation view with multiple groups, only one result
        can be returned.

        """
        if hasattr(self, 'group'):
            if utils.is_uuid(self.group):
                return utils.string_uuid(self.group)
        return u''
    def test_reservations_export(self):
        self.login_manager()

        resource = self.create_resource()
        sc = resource.scheduler()

        start = datetime(2012, 2, 1, 12, 0)
        end = datetime(2012, 2, 1, 16, 0)
        dates = (start, end)

        reservation_email = u"*****@*****.**"
        sc.allocate(dates, approve_manually=False, quota=2)[0]

        token1 = sc.reserve(
            reservation_email, dates, data=utils.mock_data_dictionary({"stop": u"hammertime!", "bust": u"a move!"})
        )

        token2 = sc.reserve(
            reservation_email, dates, data=utils.mock_data_dictionary({"never": u"gonna", "give": u"you up"})
        )

        dataset = exports.reservations.dataset({resource.uuid(): resource}, "en")

        self.assertEqual(len(dataset), 2)
        self.assertEqual(len(dataset.headers), 11 + 4)

        self.assertEqual(dataset.dict[0]["Token"], utils.string_uuid(token1))
        self.assertEqual(dataset.dict[0]["Mocktest.stop"], u"hammertime!")
        self.assertEqual(dataset.dict[0]["Mocktest.bust"], u"a move!")
        self.assertEqual(dataset.dict[0]["Mocktest.never"], None)
        self.assertEqual(dataset.dict[0]["Mocktest.give"], None)

        self.assertEqual(dataset.dict[1]["Token"], utils.string_uuid(token2))
        self.assertEqual(dataset.dict[1]["Mocktest.stop"], None)
        self.assertEqual(dataset.dict[1]["Mocktest.bust"], None)
        self.assertEqual(dataset.dict[1]["Mocktest.never"], u"gonna")
        self.assertEqual(dataset.dict[1]["Mocktest.give"], u"you up")

        # just make sure these don't raise exceptions
        dataset.xls
        dataset.json
        dataset.csv
Example #18
0
def for_resources(resources):
    """Returns a function which takes a resource (object or uuid) and
    returns true if it is visible to the current user.

    """

    visible_resources = []

    for r in resources:
        if checkPermission('zope2.View', r):
            visible_resources.append(string_uuid(r))

    def is_exposed(resource):
        return string_uuid(resource) in visible_resources

    return is_exposed
Example #19
0
    def resources(self):
        """ Returns a list of resources contained in the reservations. The
        result is a set of uuid strings (without hyphens).

        """
        return set(utils.string_uuid(r.resource) for r in self.reservations())
Example #20
0
def dataset(resources,
            language,
            year,
            month,
            transform_record=None,
            compact=False):
    """ Takes a list of resources and returns a tablib dataset filled with
    all reservations of these resources. The json data of the reservations
    is filled using a single column for each type (form + field).

    transform_record is called before each record is added to the dataset. It
    allows for changes to the dataset, which is hard otherwise because the
    records are stored as tuples in the dataset and not meant to be changed.

    If compact is True, whole day group reservations spanning multiple days
    are merged into one using utils.unite_dates.

    """

    translator = Translator(language)
    reservations = fetch_records(resources, year, month)

    # create the headers
    headers = translator.translate(basic_headers())
    dataheaders = additional_headers(reservations)
    headers.extend(dataheaders)

    # use dataview for display info helper view (yep, could be nicer)
    dataview = ReservationDataView()

    # for each reservation get a record per timeslot (which is a single slot
    # for reservations targeting an allocation and n slots for a reservation
    # targeting a group)
    records = []
    for r in reservations:

        token = utils.string_uuid(r.token)
        resource = resources[utils.string_uuid(r.resource)]

        if compact:
            timespans = utils.unite_dates(r.timespans())
        else:
            timespans = r.timespans()

        for start, end in timespans:
            record = [
                get_parent_title(resource),
                resource.title,
                token,
                r.email,
                start,
                end,
                utils.whole_day(start, end),
                _(r.status.capitalize()),
                r.quota,
                r.created,
                r.modified and r.modified or None,
            ]
            record.extend(
                additional_columns(r, dataheaders,
                                   dataview.display_reservation_data))

            if callable(transform_record):
                transform_record(record)

            translator.translate(record)
            records.append(record)

    # put the results in a tablib dataset
    return generate_dataset(headers, records)
Example #21
0
    def resources(self):
        """ Returns a list of resources contained in the reservations. The
        result is a set of uuid strings (without hyphens).

        """
        return set(utils.string_uuid(r.resource) for r in self.reservations())
Example #22
0
 def string_uuid(self):
     return utils.string_uuid(self.uuid())
 def transform_uuid(target):
     if utils.is_uuid(target):
         return utils.string_uuid(target)
     else:
         return target
    def test_reservations_export(self):
        self.login_manager()

        resource = self.create_resource()
        sc = resource.scheduler()

        start = datetime(2012, 2, 1, 12, 0, tzinfo=timezone('UTC'))
        end = datetime(2012, 2, 1, 16, 0, tzinfo=timezone('UTC'))
        some_date = datetime(2014, 1, 30, 13, 37, tzinfo=timezone('UTC'))
        dates = (start, end)

        sc.allocate(dates, approve_manually=False, quota=2)[0]

        token1 = sc.reserve(
            u'*****@*****.**', dates,
            data=utils.mock_data_dictionary(
                {
                    'stop': u'hammertime!',
                    'bust': u'a move!',
                    'when': some_date
                }
            )
        )

        token2 = sc.reserve(
            u'*****@*****.**', dates,
            data=utils.mock_data_dictionary(
                {
                    'never': u'gonna',
                    'give': u'you up',
                    'when': some_date
                }
            )
        )

        dataset = exports.reservations.dataset(
            {resource.uuid(): resource}, 'en', 'all', 'all'
        )

        self.assertEqual(len(dataset), 2)

        existing_columns = 11
        token_1_unique = 2
        token_2_unique = 2
        token_common = 1

        self.assertEqual(
            len(dataset.headers),
            existing_columns + token_1_unique + token_2_unique + token_common
        )

        self.assertEqual(dataset.dict[0]['Token'], utils.string_uuid(token1))
        self.assertEqual(dataset.dict[0]['Mocktest.stop'], u'hammertime!')
        self.assertEqual(dataset.dict[0]['Mocktest.bust'], u'a move!')
        self.assertEqual(dataset.dict[0]['Mocktest.never'], None)
        self.assertEqual(dataset.dict[0]['Mocktest.give'], None)

        self.assertEqual(dataset.dict[1]['Token'], utils.string_uuid(token2))
        self.assertEqual(dataset.dict[1]['Mocktest.stop'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.bust'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.never'], u'gonna')
        self.assertEqual(dataset.dict[1]['Mocktest.give'], u'you up')

        self.assertEqual(dataset.dict[0]['Start'], start)
        self.assertEqual(dataset.dict[1]['Start'], start)
        self.assertEqual(dataset.dict[0]['End'], end)
        self.assertEqual(dataset.dict[1]['End'], end)

        self.assertEqual(dataset.dict[0]['Mocktest.when'], some_date)
        self.assertEqual(dataset.dict[1]['Mocktest.when'], some_date)

        # just make sure these don't raise exceptions
        for format in ('xls', 'xlsx', 'json', 'csv'):
            transform_record = lambda r: prepare_record(r, format)
            dataset = exports.reservations.dataset(
                {resource.uuid(): resource},
                'en', 'all', 'all', transform_record
            )
            getattr(dataset, format)
Example #25
0
    def test_reservations_export(self):
        self.login_manager()

        resource = self.create_resource()
        sc = resource.scheduler()

        start = datetime(2012, 2, 1, 12, 0, tzinfo=timezone('UTC'))
        end = datetime(2012, 2, 1, 16, 0, tzinfo=timezone('UTC'))
        some_date = datetime(2014, 1, 30, 13, 37, tzinfo=timezone('UTC'))
        dates = (start, end)

        sc.allocate(dates, approve_manually=False, quota=2)[0]

        token1 = sc.reserve(u'*****@*****.**',
                            dates,
                            data=utils.mock_data_dictionary({
                                'stop': u'hammertime!',
                                'bust': u'a move!',
                                'when': some_date
                            }))

        token2 = sc.reserve(u'*****@*****.**',
                            dates,
                            data=utils.mock_data_dictionary({
                                'never': u'gonna',
                                'give': u'you up',
                                'when': some_date
                            }))

        dataset = exports.reservations.dataset({resource.uuid(): resource},
                                               'en', 'all', 'all')

        self.assertEqual(len(dataset), 2)

        existing_columns = 11
        token_1_unique = 2
        token_2_unique = 2
        token_common = 1

        self.assertEqual(
            len(dataset.headers),
            existing_columns + token_1_unique + token_2_unique + token_common)

        self.assertEqual(dataset.dict[0]['Token'], utils.string_uuid(token1))
        self.assertEqual(dataset.dict[0]['Mocktest.stop'], u'hammertime!')
        self.assertEqual(dataset.dict[0]['Mocktest.bust'], u'a move!')
        self.assertEqual(dataset.dict[0]['Mocktest.never'], None)
        self.assertEqual(dataset.dict[0]['Mocktest.give'], None)

        self.assertEqual(dataset.dict[1]['Token'], utils.string_uuid(token2))
        self.assertEqual(dataset.dict[1]['Mocktest.stop'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.bust'], None)
        self.assertEqual(dataset.dict[1]['Mocktest.never'], u'gonna')
        self.assertEqual(dataset.dict[1]['Mocktest.give'], u'you up')

        self.assertEqual(dataset.dict[0]['Start'], start)
        self.assertEqual(dataset.dict[1]['Start'], start)
        self.assertEqual(dataset.dict[0]['End'], end)
        self.assertEqual(dataset.dict[1]['End'], end)

        self.assertEqual(dataset.dict[0]['Mocktest.when'], some_date)
        self.assertEqual(dataset.dict[1]['Mocktest.when'], some_date)

        # just make sure these don't raise exceptions
        for format in ('xls', 'xlsx', 'json', 'csv'):
            transform_record = lambda r: prepare_record(r, format)
            dataset = exports.reservations.dataset({resource.uuid(): resource},
                                                   'en', 'all', 'all',
                                                   transform_record)
            getattr(dataset, format)
 def transform_uuid(target):
     if utils.is_uuid(target):
         return utils.string_uuid(target)
     else:
         return target
Example #27
0
 def is_exposed(resource):
     return string_uuid(resource) in visible_resources
def dataset(resources, language, compact=False):
    """ Takes a list of resources and returns a tablib dataset filled with
    all reservations of these resources. The json data of the reservations
    is filled using a single column for each type (form + field).

    If compact is True, whole day group reservations spanning multiple days
    are merged into one using utils.unite_dates.

    """

    translator = Translator(language)
    reservations = fetch_records(resources)

    # create the headers
    headers = translator.translate(basic_headers())
    dataheaders = additional_headers(reservations)
    headers.extend(dataheaders)

    # use dataview for display info helper view (yep, could be nicer)
    dataview = ReservationDataView()

    # for each reservation get a record per timeslot (which is a single slot
    # for reservations targeting an allocation and n slots for a reservation
    # targeting a group)
    records = []
    for r in reservations:

        token = utils.string_uuid(r.token)
        resource = resources[utils.string_uuid(r.resource)]

        if compact:
            timespans = utils.unite_dates(r.timespans())
        else:
            timespans = r.timespans()

        datetime_format = '%Y-%m-%d %H:%M'

        for start, end in timespans:
            record = [
                get_parent_title(resource),
                resource.title,
                token,
                r.email,
                start.strftime(datetime_format),
                end.strftime(datetime_format),
                dataview.display_reservation_data(utils.whole_day(start, end)),
                _(r.status.capitalize()),
                r.quota,
                r.created.strftime(datetime_format),
                r.modified and r.modified.strftime(datetime_format) or None,
            ]
            record.extend(
                additional_columns(
                    r, dataheaders, dataview.display_reservation_data
                )
            )

            translator.translate(record)
            records.append(record)

    # put the results in a tablib dataset
    return generate_dataset(headers, records)