Exemplo n.º 1
0
    def reservation_data(self):
        """ Prepares data to be shown in the my reservation's table """
        reservations = []

        for reservation in self.reservations():
            resource = utils.get_resource_by_uuid(reservation.resource)

            if resource is None:
                log.warn('Invalid UUID %s' % str(reservation.resource))
                continue

            resource = resource.getObject()

            data = {}

            data['title'] = utils.get_resource_title(resource)

            timespans = []
            for start, end in reservation.timespans():
                timespans.append(u'◆ ' + utils.display_date(start, end))

            data['time'] = '<br />'.join(timespans)
            data['quota'] = utils.get_reservation_quota_statement(
                reservation.quota
            ) if reservation.quota > 1 else u''

            data['url'] = resource.absolute_url()
            data['remove-url'] = ''.join((
                resource.absolute_url(),
                '/your-reservations?remove=',
                reservation.token.hex
            ))
            reservations.append(data)

        return reservations
Exemplo n.º 2
0
    def infoblocks(self):
        blocks = []

        for resource in self.resources.values():
            text = (getattr(resource, 'thank_you_text', None) or u'').strip()

            if text:
                blocks.append((utils.get_resource_title(resource), text))

        return blocks
Exemplo n.º 3
0
    def infoblocks(self):
        blocks = []

        for resource in self.resources.values():
            text = (getattr(resource, 'thank_you_text', None) or u'').strip()

            if text:
                blocks.append((utils.get_resource_title(resource), text))

        return blocks
Exemplo n.º 4
0
def send_reservations_confirmed(reservations, language):
    sender = utils.get_site_email_sender()

    if not sender:
        log.warn('Cannot send email as no sender is configured')
        return

    # load resources
    resources = dict()
    for reservation in reservations:

        if not reservation.resource in resources:
            resources[reservation.resource] = utils.get_resource_by_uuid(
                reservation.resource
            ).getObject()

            if not resources[reservation.resource]:
                log.warn('Cannot send email as the resource does not exist')
                return

    # send reservations grouped by reservee email
    groupkey = lambda r: r.email
    by_recipient = groupby(sorted(reservations, key=groupkey), key=groupkey)

    for recipient, grouped_reservations in by_recipient:

        lines = []

        for reservation in grouped_reservations:

            resource = resources[reservation.resource]

            prefix = '' if reservation.autoapprovable else '* '
            lines.append(prefix + utils.get_resource_title(resource))

            for start, end in reservation.timespans():
                lines.append(utils.display_date(start, end))

            lines.append('')

        # differs between resources
        subject, body = get_email_content(
            resource, 'reservation_received', language
        )

        mail = ReservationMail(
            resource, reservation,
            sender=sender,
            recipient=recipient,
            subject=subject,
            body=body,
            reservations=lines[:-1]
        )

        send_mail(resource, mail)
Exemplo n.º 5
0
def send_reservations_confirmed(reservations, language):

    sender = utils.get_site_email_sender()

    if not sender:
        log.warn('Cannot send email as no sender is configured')
        return

    # load resources
    resources = load_resources(reservations)

    # send reservations grouped by reservee email
    groupkey = lambda r: r.email
    by_recipient = groupby(sorted(reservations, key=groupkey), key=groupkey)

    for recipient, grouped_reservations in by_recipient:

        lines = []

        for reservation in combine_reservations(grouped_reservations):

            resource = resources[reservation.resource]

            prefix = '' if reservation.autoapprovable else '* '
            title_prefix = '{}x '.format(reservation.quota)
            lines.append(
                prefix + utils.get_resource_title(resource, title_prefix)
            )

            for start, end in reservation.timespans():
                lines.append(utils.display_date(start, end))

            lines.append('')

        # differs between resources
        subject, body = get_email_content(
            resource, 'reservation_received', language
        )

        mail = ReservationMail(
            resource, reservation,
            sender=sender,
            recipient=recipient,
            subject=subject,
            body=body,
            reservations=lines[:-1]
        )

        if may_send_mail(resource, mail, intended_for_admin=False):
            send_mail(resource, mail)
Exemplo n.º 6
0
def send_reservations_confirmed(reservations, language):

    sender = utils.get_site_email_sender()

    if not sender:
        log.warn('Cannot send email as no sender is configured')
        return

    # load resources
    resources = load_resources(reservations)

    # send reservations grouped by reservee email
    groupkey = lambda r: r.email
    by_recipient = groupby(sorted(reservations, key=groupkey), key=groupkey)

    for recipient, grouped_reservations in by_recipient:

        lines = []

        for reservation in combine_reservations(grouped_reservations):

            resource = resources[reservation.resource]

            prefix = '' if reservation.autoapprovable else '* '
            title_prefix = '{}x '.format(reservation.quota)
            lines.append(prefix +
                         utils.get_resource_title(resource, title_prefix))

            for start, end in reservation.timespans():
                lines.append(utils.display_date(start, end))

            lines.append('')

        # differs between resources
        subject, body = get_email_content(resource, 'reservation_received',
                                          language)

        mail = ReservationMail(resource,
                               reservation,
                               sender=sender,
                               recipient=recipient,
                               subject=subject,
                               body=body,
                               reservations=lines[:-1])

        if may_send_mail(resource, mail, intended_for_admin=False):
            send_mail(resource, mail)
Exemplo n.º 7
0
    def build_your_reservations(
        self, reservations
    ):
        """ Prepares the given reservations to be shown in the
        your-reservations macro.

        """
        result = []

        for reservation in reservations:
            resource = utils.get_resource_by_uuid(reservation.resource)

            if resource is None:
                log.warn('Invalid UUID %s' % str(reservation.resource))
                continue

            resource = resource.getObject()

            data = {}

            data['token'] = reservation.token
            data['title'] = utils.get_resource_title(resource)

            timespans = []
            for start, end in reservation.timespans():
                timespans.append(utils.display_date(start, end))

            data['time'] = '<ul class="dense"><li>{}</li></ul>'.format(
                '</li><li>'.join(timespans)
            )
            data['quota'] = utils.get_reservation_quota_statement(
                reservation.quota
            ) if reservation.quota > 1 else u''

            data['url'] = resource.absolute_url()
            data['remove-url'] = ''.join((
                resource.absolute_url(),
                '/your-reservations?remove=',
                reservation.token.hex
            ))
            result.append(data)

        return result
Exemplo n.º 8
0
    def build_your_reservations(self, reservations):
        """ Prepares the given reservations to be shown in the
        your-reservations macro.

        """
        result = []

        for reservation in reservations:
            resource = utils.get_resource_by_uuid(reservation.resource)

            if resource is None:
                log.warn('Invalid UUID %s' % str(reservation.resource))
                continue

            resource = resource.getObject()

            data = {}

            data['token'] = reservation.token
            data['title'] = utils.get_resource_title(resource)

            timespans = []
            for start, end in reservation.timespans():
                timespans.append(utils.display_date(start, end))

            data['time'] = '<ul class="dense"><li>{}</li></ul>'.format(
                '</li><li>'.join(timespans))
            data['quota'] = utils.get_reservation_quota_statement(
                reservation.quota) if reservation.quota > 1 else u''

            data['url'] = resource.absolute_url()
            data['remove-url'] = ''.join(
                (resource.absolute_url(), '/your-reservations?remove=',
                 reservation.token.hex))
            result.append(data)

        return result
Exemplo n.º 9
0
 def title(self, resource):
     return utils.get_resource_title(resource)
Exemplo n.º 10
0
def monthly_report(year, month, resources, reservations='*'):

    schedulers, titles = dict(), dict()

    for uuid in resources.keys():
        schedulers[uuid] = db.Scheduler(uuid)
        titles[uuid] = utils.get_resource_title(resources[uuid])

    # this order is used for every day in the month
    ordered_uuids = [i[0] for i in sorted(titles.items(), key=lambda i: i[1])]

    # build the hierarchical structure of the report data
    report = utils.OrderedDict()
    last_day = 28

    for d in sorted((d for d in calendar.itermonthdates(year, month))):
        if not d.month == month:
            continue

        day = d.day
        last_day = max(last_day, day)
        report[day] = utils.OrderedDict()

        for uuid in ordered_uuids:
            report[day][uuid] = dict()
            report[day][uuid][u'title'] = titles[uuid]
            report[day][uuid][u'approved'] = list()
            report[day][uuid][u'pending'] = list()
            report[day][uuid][u'url'] = resources[uuid].absolute_url()
            report[day][uuid][u'lists'] = {
                u'approved': _(u'Approved'),
                u'pending': _(u'Pending'),
            }

    # gather the reservations with as much bulk loading as possible
    period_start = date(year, month, 1)
    period_end = date(year, month, last_day)

    # get a list of relevant allocations in the given period
    query = Session.query(Allocation)
    query = query.filter(period_start <= Allocation._start)
    query = query.filter(Allocation._start <= period_end)
    query = query.filter(Allocation.resource == Allocation.mirror_of)
    query = query.filter(Allocation.resource.in_(resources.keys()))

    allocations = query.all()

    # quit if there are no allocations at this point
    if not allocations:
        return {}

    # store by group as it will be needed multiple times over later
    groups = dict()
    for allocation in allocations:
        groups.setdefault(allocation.group, list()).append(allocation)

    # using the groups get the relevant reservations
    query = Session.query(Reservation)
    query = query.filter(Reservation.target.in_(groups.keys()))

    if reservations != '*':
        query = query.filter(Reservation.token.in_(reservations))

    query = query.order_by(Reservation.status)

    reservations = query.all()
    reservation_urls = ReservationUrls()

    @utils.memoize
    def json_timespans(start, end):
        return json.dumps([dict(start=start, end=end)])

    used_days = dict([(i, False) for i in range(1, 32)])

    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
            )
        )

    for reservation in reservations:
        if reservation.target_type == u'allocation':
            add_reservation(reservation.start, reservation.end, reservation)
        else:
            for allocation in groups[reservation.target]:
                add_reservation(allocation.start, allocation.end, reservation)

    # remove unused days
    for day in report:
        if not used_days[day]:
            del report[day]

    return report
Exemplo n.º 11
0
def monthly_report(year, month, resources, reservations='*'):

    titles = dict()

    for uuid in resources.keys():
        titles[uuid] = utils.get_resource_title(resources[uuid])

    # timezone of the report
    timezone = settings.timezone()

    # this order is used for every day in the month
    ordered_uuids = [i[0] for i in sorted(titles.items(), key=lambda i: i[1])]

    # build the hierarchical structure of the report data
    report = utils.OrderedDict()
    last_day = 28

    for d in sorted((d for d in calendar.itermonthdates(year, month))):
        if not d.month == month:
            continue

        day = d.day
        last_day = max(last_day, day)
        report[day] = utils.OrderedDict()

        for uuid in ordered_uuids:
            report[day][uuid] = dict()
            report[day][uuid][u'title'] = titles[uuid]
            report[day][uuid][u'approved'] = list()
            report[day][uuid][u'pending'] = list()
            report[day][uuid][u'url'] = resources[uuid].absolute_url()
            report[day][uuid][u'lists'] = {
                u'approved': _(u'Approved'),
                u'pending': _(u'Pending'),
            }

    # gather the reservations with as much bulk loading as possible
    period_start = datetime(year, month, 1, tzinfo=timezone)
    period_end = datetime(year, month, last_day, tzinfo=timezone)
    period_end += timedelta(days=1, microseconds=-1)

    # get a list of relevant allocations in the given period
    query = Session().query(Allocation)
    query = query.filter(period_start <= Allocation._start)
    query = query.filter(Allocation._start <= period_end)
    query = query.filter(Allocation.resource == Allocation.mirror_of)
    query = query.filter(Allocation.resource.in_(resources.keys()))

    allocations = query.all()

    # quit if there are no allocations at this point
    if not allocations:
        return {}

    # store by group as it will be needed multiple times over later
    groups = dict()
    for allocation in allocations:
        groups.setdefault(allocation.group, list()).append(allocation)

    # using the groups get the relevant reservations
    query = Session().query(Reservation)
    query = query.filter(Reservation.target.in_(groups.keys()))

    if reservations != '*':
        query = query.filter(Reservation.token.in_(reservations))

    query = query.order_by(Reservation.status)

    reservations = query.all()

    @utils.memoize
    def json_timespans(start, end):
        return json.dumps([dict(start=start, end=end)])

    used_days = dict([(i, False) for i in range(1, 32)])
    timezone = settings.timezone()

    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,
            )
        )

    for reservation in reservations:
        if reservation.target_type == u'allocation':
            add_reservation(reservation.start, reservation.end, reservation)
        else:
            for allocation in groups[reservation.target]:
                add_reservation(allocation.start, allocation.end, reservation)

    # remove unused days
    for day in report:
        if not used_days[day]:
            del report[day]

    return report
Exemplo n.º 12
0
def monthly_report(year, month, resources, reservations="*"):

    schedulers, titles = dict(), dict()

    for uuid in resources.keys():
        schedulers[uuid] = db.Scheduler(uuid)
        titles[uuid] = utils.get_resource_title(resources[uuid])

    # this order is used for every day in the month
    ordered_uuids = [i[0] for i in sorted(titles.items(), key=lambda i: i[1])]

    # build the hierarchical structure of the report data
    report = utils.OrderedDict()
    last_day = 28

    for d in sorted((d for d in calendar.itermonthdates(year, month))):
        if not d.month == month:
            continue

        day = d.day
        last_day = max(last_day, day)
        report[day] = utils.OrderedDict()

        for uuid in ordered_uuids:
            report[day][uuid] = dict()
            report[day][uuid][u"title"] = titles[uuid]
            report[day][uuid][u"approved"] = list()
            report[day][uuid][u"pending"] = list()
            report[day][uuid][u"url"] = resources[uuid].absolute_url()
            report[day][uuid][u"lists"] = {u"approved": _(u"Approved"), u"pending": _(u"Pending")}

    # gather the reservations with as much bulk loading as possible
    period_start = date(year, month, 1)
    period_end = date(year, month, last_day)

    # get a list of relevant allocations in the given period
    query = Session.query(Allocation)
    query = query.filter(period_start <= Allocation._start)
    query = query.filter(Allocation._start <= period_end)
    query = query.filter(Allocation.resource == Allocation.mirror_of)
    query = query.filter(Allocation.resource.in_(resources.keys()))

    allocations = query.all()

    # quit if there are no allocations at this point
    if not allocations:
        return {}

    # store by group as it will be needed multiple times over later
    groups = dict()
    for allocation in allocations:
        groups.setdefault(allocation.group, list()).append(allocation)

    # using the groups get the relevant reservations
    query = Session.query(Reservation)
    query = query.filter(Reservation.target.in_(groups.keys()))

    if reservations != "*":
        query = query.filter(Reservation.token.in_(reservations))

    query = query.order_by(Reservation.status)

    reservations = query.all()
    reservation_urls = ReservationUrls()

    @utils.memoize
    def json_timespans(start, end):
        return json.dumps([dict(start=start, end=end)])

    used_days = dict([(i, False) for i in range(1, 32)])

    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,
            )
        )

    for reservation in reservations:
        if reservation.target_type == u"allocation":
            add_reservation(reservation.start, reservation.end, reservation)
        else:
            for allocation in groups[reservation.target]:
                add_reservation(allocation.start, allocation.end, reservation)

    # remove unused days
    for day in report:
        if not used_days[day]:
            del report[day]

    return report
Exemplo n.º 13
0
    def __init__(self, resource, reservation, **kwargs):
        for k, v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)

        # get information for the body/subject string

        p = dict()
        is_needed = lambda key: key in self.subject or key in self.body

        # title of the resource
        if is_needed('resource'):
            p['resource'] = utils.get_resource_title(resource)

        # reservation email
        if is_needed('reservation_mail'):
            p['reservation_mail'] = reservation.email

        # a list of reservations
        if is_needed('reservations'):
            p['reservations'] = u'\n'.join(self.reservations)

        # a list of dates
        if is_needed('dates'):
            p['dates'] = self.get_date_parameters(reservation)

        # tabbed reservation data
        if is_needed('data'):
            data = reservation.data
            lines = []
            for key in self.sort_reservation_data(data):
                interface = data[key]

                lines.append(safe_unicode(interface['desc']))
                for value in self.sort_reservation_data_values(interface['values']):
                    description = translate(value['desc'],
                                            context=resource.REQUEST,
                                            domain='seantis.reservation')
                    description = safe_unicode(description)
                    val = safe_unicode(
                        self.display_reservation_data(value['value'])
                    )
                    lines.append((u'\t{}: {}'.format(description, val))
                )

            p['data'] = u'\n'.join(lines)

        # approval link
        if is_needed('approval_link'):
            p['approval_link'] = self.approve_all_url(
                reservation.token, resource
            )

        # denial link
        if is_needed('denial_link'):
            p['denial_link'] = self.deny_all_url(reservation.token, resource)

        # cancel link
        if is_needed('cancel_link'):
            p['cancel_link'] = self.revoke_all_url(reservation.token, resource)

        # revocation reason
        if is_needed('reason'):
            p['reason'] = self.revocation_reason

        self.parameters = p
Exemplo n.º 14
0
 def resource_title(self):
     return utils.get_resource_title(self)
Exemplo n.º 15
0
 def resource_title(self):
     return utils.get_resource_title(self)
Exemplo n.º 16
0
    def __init__(self, resource, reservation, **kwargs):
        for k, v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)

        # get information for the body/subject string

        p = dict()
        is_needed = lambda key: key in self.subject or key in self.body

        # title of the resource
        if is_needed('resource'):
            p['resource'] = utils.get_resource_title(resource)

        # reservation email
        if is_needed('reservation_mail'):
            p['reservation_mail'] = reservation.email

        # a list of reservations
        if is_needed('reservations'):
            p['reservations'] = '\n'.join(self.reservations)

        # a list of dates
        if is_needed('dates'):
            lines = []
            dates = sorted(reservation.timespans(), key=lambda i: i[0])
            for start, end in dates:
                lines.append(utils.display_date(start, end))

            p['dates'] = '\n'.join(lines)

        # reservation quota
        if is_needed('quota'):
            p['quota'] = reservation.quota

        # tabbed reservation data
        if is_needed('data'):
            data = reservation.data
            lines = []
            for key in self.sort_reservation_data(data):
                interface = data[key]

                lines.append(interface['desc'])
                sorted_values = self.sort_reservation_data_values(
                    interface['values']
                )

                for value in sorted_values:
                    lines.append(
                        '\t' + value['desc'] + ': ' +
                        six.text_type(
                            self.display_reservation_data(value['value'])
                        )
                    )

            p['data'] = '\n'.join(lines)

        if is_needed('reservation_link'):
            p['reservation_link'] = self.show_all_url(
                reservation.token, resource
            )

        # approval link
        if is_needed('approval_link'):
            p['approval_link'] = self.approve_all_url(
                reservation.token, resource
            )

        # denial link
        if is_needed('denial_link'):
            p['denial_link'] = self.deny_all_url(reservation.token, resource)

        # cancel link
        if is_needed('cancel_link'):
            p['cancel_link'] = self.revoke_all_url(reservation.token, resource)

        # revocation reason
        if is_needed('reason'):
            p['reason'] = self.reason

        # old time
        if is_needed('old_time'):
            p['old_time'] = utils.display_date(*self.old_time)

        # new time
        if is_needed('new_time'):
            p['new_time'] = utils.display_date(*self.new_time)

        self.parameters = p
Exemplo n.º 17
0
    def __init__(self, resource, reservation, **kwargs):
        for k, v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)

        # get information for the body/subject string

        p = dict()
        is_needed = lambda key: key in self.subject or key in self.body

        # title of the resource
        if is_needed('resource'):
            p['resource'] = utils.get_resource_title(resource)

        # reservation email
        if is_needed('reservation_mail'):
            p['reservation_mail'] = reservation.email

        # a list of reservations
        if is_needed('reservations'):
            p['reservations'] = '\n'.join(self.reservations)

        # a list of dates
        if is_needed('dates'):
            lines = []
            dates = sorted(reservation.timespans(), key=lambda i: i[0])
            for start, end in dates:
                lines.append(utils.display_date(start, end))

            p['dates'] = '\n'.join(lines)

        # reservation quota
        if is_needed('quota'):
            p['quota'] = reservation.quota

        # tabbed reservation data
        if is_needed('data'):
            data = reservation.data
            lines = []
            for key in self.sort_reservation_data(data):
                interface = data[key]

                lines.append(interface['desc'])
                sorted_values = self.sort_reservation_data_values(
                    interface['values'])

                for value in sorted_values:
                    lines.append('\t' + value['desc'] + ': ' + six.text_type(
                        self.display_reservation_data(value['value'])))

            p['data'] = '\n'.join(lines)

        if is_needed('reservation_link'):
            p['reservation_link'] = self.show_all_url(reservation.token,
                                                      resource)

        # approval link
        if is_needed('approval_link'):
            p['approval_link'] = self.approve_all_url(reservation.token,
                                                      resource)

        # denial link
        if is_needed('denial_link'):
            p['denial_link'] = self.deny_all_url(reservation.token, resource)

        # cancel link
        if is_needed('cancel_link'):
            p['cancel_link'] = self.revoke_all_url(reservation.token, resource)

        # revocation reason
        if is_needed('reason'):
            p['reason'] = self.reason

        # old time
        if is_needed('old_time'):
            p['old_time'] = utils.display_date(*self.old_time)

        # new time
        if is_needed('new_time'):
            p['new_time'] = utils.display_date(*self.new_time)

        self.parameters = p
Exemplo n.º 18
0
 def resource_title(self, uuid):
     if not uuid in self.titles:
         self.titles[uuid] = utils.get_resource_title(self.resources[uuid])
     
     return self.titles[uuid]