예제 #1
0
    def get_date_from_to_queryset(self, date_from, date_to, queryset=None):
        """
        Get a ``QuerySet`` of ``ProductReview`` items that match the time
        frame specified by *date_from* and *date_to*. Both parameters are
        expected to be in ``datetime`` format with *date_from* < *date_to*.
        If *queryset* is specified, it will be filtered according to the
        given dates. Otherwise, a new queryset for all ``ProductReview``
        items is created.
        """
        if not queryset:
            self.model.objects.all()

        if date_from and date_to:
            # Add 24 hours to make search inclusive
            date_to = date_to + datetime.timedelta(days=1)
            queryset = queryset.filter(date_created__gte=date_from).filter(
                date_created__lt=date_to)
            self.desc_ctx['date_filter'] = _(
                " created between %(start_date)s and %(end_date)s") % {
                    'start_date': format_date(date_from),
                    'end_date': format_date(date_to)
                }
        elif date_from:
            queryset = queryset.filter(date_created__gte=date_from)
            self.desc_ctx['date_filter'] = _(
                " created after %s") % format_date(date_from)
        elif date_to:
            # Add 24 hours to make search inclusive
            date_to = date_to + datetime.timedelta(days=1)
            queryset = queryset.filter(date_created__lt=date_to)
            self.desc_ctx['date_filter'] = _(
                " created before %s") % format_date(date_to)

        return queryset
예제 #2
0
    def get_date_from_to_queryset(self, date_from, date_to, queryset=None):
        """
        Get a ``QuerySet`` of ``ProductReview`` items that match the time
        frame specified by *date_from* and *date_to*. Both parameters are
        expected to be in ``datetime`` format with *date_from* < *date_to*.
        If *queryset* is specified, it will be filtered according to the
        given dates. Otherwise, a new queryset for all ``ProductReview``
        items is created.
        """
        if not queryset:
            self.model.objects.all()

        if date_from and date_to:
            # Add 24 hours to make search inclusive
            date_to = date_to + datetime.timedelta(days=1)
            queryset = queryset.filter(
                date_created__gte=date_from
            ).filter(
                date_created__lt=date_to
            )
            self.desc_ctx['date_filter'] = _(" created between %(start_date)s and %(end_date)s") % {
                'start_date': format_date(date_from),
                'end_date': format_date(date_to)
            }
        elif date_from:
            queryset = queryset.filter(date_created__gte=date_from)
            self.desc_ctx['date_filter'] =  _(" created after %s") % format_date(date_from)
        elif date_to:
            # Add 24 hours to make search inclusive
            date_to = date_to + datetime.timedelta(days=1)
            queryset = queryset.filter(date_created__lt=date_to)
            self.desc_ctx['date_filter'] = _(" created before %s") % format_date(date_to)

        return queryset
예제 #3
0
 def local_display(self):
     start = format_date(self.date_start, "D d N Y - H:i")
     end = None
     if self.date_start.date() == self.date_end.date():
         end = format_date(self.date_end, "H:i")
     else:
         end = format_date(self.date_end, "D d N Y - H:i")
     return f"{start} à {end}"
예제 #4
0
    def get_desc_context(self, data=None):
        """Update the title that describes the queryset"""
        desc_ctx = {
            'main_filter': _('All orders'),
            'name_filter': '',
            'title_filter': '',
            'upc_filter': '',
            'sku_filter': '',
            'date_filter': '',
            'voucher_filter': '',
            'payment_filter': '',
            'status_filter': '',
        }

        if 'order_status' in self.request.GET:
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                desc_ctx['main_filter'] = _("Orders without an order status")
            else:
                desc_ctx['main_filter'] = _("Orders with status '%s'") % status
        if data is None:
            return desc_ctx

        if data['order_number']:
            desc_ctx['main_filter'] = _('Orders with number starting with "%s"') % data['order_number']

        if data['name']:
            desc_ctx['name_filter'] = _(" with customer name matching '%s'") % data['name']

        if data['product_title']:
            desc_ctx['title_filter'] = _(" including an item with title matching '%s'") % data['product_title']

        if data['upc']:
            desc_ctx['upc_filter'] = _(" including an item with UPC '%s'") % data['upc']

        if data['partner_sku']:
            desc_ctx['upc_filter'] = _(" including an item with ID '%s'") % data['partner_sku']

        if data['date_from'] and data['date_to']:
            desc_ctx['date_filter'] = _(" placed between %(start_date)s and %(end_date)s") % {
                'start_date': format_date(data['date_from']),
                'end_date': format_date(data['date_to'])}
        elif data['date_from']:
            desc_ctx['date_filter'] = _(" placed since %s") % format_date(data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            desc_ctx['date_filter'] = _(" placed before %s") % format_date(data['date_to'])

        if data['voucher']:
            desc_ctx['voucher_filter'] = _(" using voucher '%s'") % data['voucher']

        if data['payment_method']:
            desc_ctx['payment_filter'] = _(" paid for by %s") % data['payment_method']

        if data['status']:
            desc_ctx['status_filter'] = _(" with status %s") % data['status']

        return desc_ctx
예제 #5
0
 def item_title(self, item):
     if isinstance(item, VoteQuestion):
         return "Vote #%s (%s)" % (item.number, item.get_result_display())
     else:
         return "%(name)s (%(party)s%(date)s)" % {
             'name': item.name_info['display_name'],
             'party': item.member.party.short_name + '; ' if item.member else '',
             'date': format_date(item.time, "F jS"),
         }
예제 #6
0
 def fill_legal_notice(self):
     # Legal notices
     if self.invoice_base.current_revision.quotation_validity:
         self.spacer()
         self.start_keeptogether()
         self.p(_("Valid until %(quotation_validity)s") % {
             'quotation_validity': format_date(self.invoice_base.current_revision.quotation_validity, 'DATE_FORMAT')
         })
         self.end_keeptogether()
예제 #7
0
 def fill_legal_notice(self):
     # Legal notices
     if self.invoice_base.current_revision.quotation_validity:
         self.spacer()
         self.start_keeptogether()
         self.p(_("Valid until %(quotation_validity)s") % {
             'quotation_validity': format_date(self.invoice_base.current_revision.quotation_validity, 'DATE_FORMAT')
         })
         self.spacer()
         self.p(_('Signature and stamp preceded by "Valid for agreement"'), self.style['Bold'])
         self.end_keeptogether()
예제 #8
0
    def fill_description(self):
        """
        Fills the description:

        - Quotation reference
        - Dates
        - (Customer reference)
        """
        self.table([[
            ' '.join([unicode(self.invoice_base.RECORD_NAME).upper(), self.invoice_base.reference]),
            format_date(self.invoice_base.current_revision.quotation_date, 'DATE_FORMAT')
        ]], self.settings.page_size.scaled_width((12*cm, 5*cm)), style=self.style['InvoiceBaseReferencesTable'])
예제 #9
0
    def fill_description(self):
        """
        Fills the description:

        - Invoice reference
        - Dates
        - (Customer reference)
        """
        reference = pgettext('reference', 'Undefined') if getattr(self.invoice_base, 'has_temporary_reference', None) else self.invoice_base.reference
        self.table([[
            ' '.join([unicode(self.invoice_base.RECORD_NAME).upper(), reference]),
            format_date(self.invoice_base.current_revision.invoicing_date, 'DATE_FORMAT')
        ]], self.settings.page_size.scaled_width((12*cm, 5*cm)), style=self.style['InvoiceBaseReferencesTable'])
예제 #10
0
 def decorator(request, *args, **kwargs):
     ban = get_request_ip_ban(request)
     if ban:
         default_message = _("Your IP address has been banned.")
         ban_message = ban.get('message') or default_message
         if ban.get('valid_until'):
             ban_expires = format_date(ban['valid_until'])
             expiration_message = _("This ban will expire on %(date)s.")
             expiration_message = expiration_message % {'date': ban_expires}
             ban_message = '%s\n\n%s' % (ban_message, expiration_message)
         raise PermissionDenied(ban_message)
     else:
         return f(request, *args, **kwargs)
예제 #11
0
파일: models.py 프로젝트: LinTek/sof15
 def pretty_start_end(self):
     tz = get_current_timezone()
     start = self.start.astimezone(tz)
     end = self.end.astimezone(tz)
     time_format = "H:i"
     date_format = "d b"
     if start.date() == end.date():
         return '{0} {1} – {2}'.format(format_date(start, date_format), format_date(start, time_format),
                                       format_date(end, time_format))
     return '{0} {1} – {2} {3}'.format(format_date(start, date_format), format_date(start, time_format),
                                       format_date(end, date_format), format_date(end, time_format))
예제 #12
0
파일: decorators.py 프로젝트: dahito/Misago
 def decorator(request, *args, **kwargs):
     ban = get_request_ip_ban(request)
     if ban:
         default_message = _("Your IP address has been banned.")
         ban_message = ban.get('message') or default_message
         if ban.get('valid_until'):
             ban_expires = format_date(ban['valid_until'])
             expiration_message = _("This ban will expire on %(date)s.")
             expiration_message = expiration_message % {'date': ban_expires}
             ban_message = '%s\n\n%s' % (ban_message, expiration_message)
         raise PermissionDenied(ban_message)
     else:
         return f(request, *args, **kwargs)
예제 #13
0
def allow_lift_ban(user, target):
    if not user.acl_cache['can_lift_bans']:
        raise PermissionDenied(_("You can't lift bans."))
    ban = get_user_ban(target)
    if not ban:
        raise PermissionDenied(_("This user is not banned."))
    if user.acl_cache['max_lifted_ban_length']:
        expiration_limit = timedelta(days=user.acl_cache['max_lifted_ban_length'])
        lift_cutoff = (timezone.now() + expiration_limit).date()
        if not ban.valid_until:
            raise PermissionDenied(_("You can't lift permanent bans."))
        elif ban.valid_until > lift_cutoff:
            message = _("You can't lift bans that expire after %(expiration)s.")
            raise PermissionDenied(message % {'expiration': format_date(lift_cutoff)})
예제 #14
0
파일: moderation.py 프로젝트: rafalp/Misago
def allow_lift_ban(user_acl, target):
    if not user_acl["can_lift_bans"]:
        raise PermissionDenied(_("You can't lift bans."))
    ban = get_user_ban(target, user_acl["cache_versions"])
    if not ban:
        raise PermissionDenied(_("This user is not banned."))
    if user_acl["max_lifted_ban_length"]:
        expiration_limit = timedelta(days=user_acl["max_lifted_ban_length"])
        lift_cutoff = (timezone.now() + expiration_limit).date()
        if not ban.valid_until:
            raise PermissionDenied(_("You can't lift permanent bans."))
        elif ban.valid_until > lift_cutoff:
            message = _("You can't lift bans that expire after %(expiration)s.")
            raise PermissionDenied(message % {"expiration": format_date(lift_cutoff)})
예제 #15
0
def allow_lift_ban(user, target):
    if not user.acl['can_lift_bans']:
        raise PermissionDenied(_("You can't lift bans."))
    ban = get_user_ban(target)
    if not ban:
        raise PermissionDenied(_("This user is not banned."))
    if user.acl['max_lifted_ban_length']:
        expiration_limit = timedelta(days=user.acl['max_lifted_ban_length'])
        lift_cutoff = (timezone.now() + expiration_limit).date()
        if not ban.valid_until:
            raise PermissionDenied(_("You can't lift permanent bans."))
        elif ban.valid_until > lift_cutoff:
            message = _("You can't lift bans that "
                        "expire after %(expiration)s.")
            message = message % {'expiration': format_date(lift_cutoff)}
            raise PermissionDenied(message)
예제 #16
0
    def download_selected_orders(self, request, orders):
        response = HttpResponse(mimetype='text/csv')
        response[
            'Content-Disposition'] = 'attachment; filename=%s' % self.get_download_filename(
                request)
        writer = CsvUnicodeWriter(response, delimiter=',')

        meta_data = (
            ('number', _('Order number')),
            ('value', _('Order value')),
            ('date', _('Date of purchase')),
            ('num_items', _('Number of items')),
            ('status', _('Order status')),
            ('customer', _('Customer email address')),
            ('shipping_address', _('Shipping address')),
            ('billing_address', _('Billing address')),
        )
        columns = SortedDict()
        for k, v in meta_data:
            columns[k] = v

        writer.writerow(columns.values())
        for order in orders:
            row = columns.copy()
            row['number'] = order.number
            row['value'] = order.total_incl_tax
            row['date'] = format_date(order.date_placed, 'DATETIME_FORMAT')
            row['num_items'] = order.num_items
            row['status'] = order.status
            row['customer'] = order.email

            if order.shipping_address:
                row['shipping_address'] = order.shipping_address
            else:
                row['shipping_address'] = ''
            if order.billing_address:
                row['billing_address'] = order.billing_address
            else:
                row['billing_address'] = ''

            encoded_values = [
                unicode(value).encode('utf8') for value in row.values()
            ]
            writer.writerow(encoded_values)
        return response
예제 #17
0
    def deliver(self, file_list, target_url, row=None):
        """
        Deliver file(s) to destination.

        `configuration_root` is used to keep the files tree.
        """

        ok = True
        max_ = settings.CARRIER_PIGEON_MAX_PUSH_ATTEMPTS

        for f in file_list:

            # --- 1. Send file

            sent = False
            for push_att_num in xrange(max_):
                logger.debug(u"'%s': push attempt #%s" % (f, push_att_num + 1))
                try:
                    sent = self._send_file(f, target_url, row)
                    break
                except Exception, ex:
                    pass

            # --- 2. Log delivery feedback

            now = format_date(datetime.now(), settings.DATETIME_FORMAT)

            if sent:
                feedback = u"[%s] '%s': push SUCCESS" % (now, f)
                logger.info(feedback)
            else:
                feedback = u"[%s] '%s': push ERROR: %s TARGET: %s" % (
                    now, f, ex, target_url.domain
                )
                logger.error(feedback)
                ok = False

            if row:
                row.message = feedback
                row.status = ItemToPush.STATUS.PUSHED if sent \
                    else ItemToPush.STATUS.SEND_ERROR
                row.save()
예제 #18
0
 def fill_legal_notice(self):
     # Legal notices
     if self.invoice_base.current_revision.custom_payment_conditions:
         self.p(_("Payment conditions: %(custom_payment_conditions)s") % {
             'custom_payment_conditions': self.invoice_base.current_revision.custom_payment_conditions
         })
     else:
         self.p(_("Payment due date on %(due_date)s") % {
             'due_date': format_date(self.invoice_base.current_revision.due_date, 'DATE_FORMAT')
         })
     pt_dict = dict(PAYMENT_TYPES)
     invoicing_settings = self.invoice_base.tenant.tenant_settings.invoicing
     self.p(_("Accepted payment methods: %(accepted_payment_methods)s") % {
         'accepted_payment_methods': u', '.join([unicode(pt_dict.get(pt, pt)).lower() for pt in invoicing_settings.accepted_payment_types])
     })
     if invoicing_settings.late_fee_rate:
         self.p(_("Late fee rate: %(late_fee_rate)s") % {
             'late_fee_rate': u'{0:.2%}'.format(invoicing_settings.late_fee_rate)
         })
     else:
         self.p(_("Late fee at the legal rate"))
예제 #19
0
    def download_selected_orders(self, request, orders):
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s' % self.get_download_filename(request)
        writer = CsvUnicodeWriter(response, delimiter=',')

        meta_data = (('number', _('Order number')),
                     ('value', _('Order value')),
                     ('date', _('Date of purchase')),
                     ('num_items', _('Number of items')),
                     ('status', _('Order status')),
                     ('customer', _('Customer email address')),
                     ('shipping_address_name', _('Deliver to name')),
                     ('billing_address_name', _('Bill to name')),
                     )
        columns = SortedDict()
        for k, v in meta_data:
            columns[k] = v

        writer.writerow(columns.values())
        for order in orders:
            row = columns.copy()
            row['number'] = order.number
            row['value'] = order.total_incl_tax
            row['date'] = format_date(order.date_placed, 'DATETIME_FORMAT')
            row['num_items'] = order.num_items
            row['status'] = order.status
            row['customer'] = order.email
            if order.shipping_address:
                row['shipping_address_name'] = order.shipping_address.name()
            else:
                row['shipping_address_name'] = ''
            if order.billing_address:
                row['billing_address_name'] = order.billing_address.name()
            else:
                row['billing_address_name'] = ''

            # encoded_values = [unicode(value).encode('utf8') for value in row.values()]
            encoded_values = [str(value) for value in row.values()]
            writer.writerow(encoded_values)
        return response
예제 #20
0
    def deliver(self, file_list, target_url, row=None):
        """
        Deliver file(s) to destination.

        `configuration_root` is used to keep the files tree.
        """

        ok = True
        max_ = settings.CARRIER_PIGEON_MAX_PUSH_ATTEMPTS

        for f in file_list:

            # --- 1. Send file

            sent = False
            for push_att_num in xrange(max_):
                logger.debug(u"'%s': push attempt #%s" % (f, push_att_num + 1))
                try:
                    sent = self._send_file(f, target_url, row)
                    break
                except Exception, ex:
                    pass

            # --- 2. Log delivery feedback

            now = format_date(datetime.now(), settings.DATETIME_FORMAT)

            if sent:
                feedback = u"[%s] '%s': push SUCCESS" % (now, f)
                logger.info(feedback)
            else:
                feedback = u"[%s] '%s': push ERROR: %s" % (now, f, ex)
                logger.error(feedback)
                ok = False

            if row:
                row.message = feedback
                row.status = ItemToPush.STATUS.PUSHED if sent \
                    else ItemToPush.STATUS.SEND_ERROR
                row.save()
예제 #21
0
파일: auth.py 프로젝트: qhhonx/Misago
    def confirm_user_not_banned(self, user):
        self.user_ban = get_user_ban(user)
        if self.user_ban:
            if self.user_ban.valid_until:
                if self.user_ban.user_message:
                    message = _("%(user)s, your account is "
                                "banned until %(date)s for:")
                else:
                    message = _("%(user)s, your account "
                                "is banned until %(date)s.")
                date_format = {'date': format_date(self.user_ban.valid_until)}
                message = message % date_format
            else:
                if self.user_ban.user_message:
                    message = _("%(user)s, your account is banned for:")
                else:
                    message = _("%(user)s, your account is banned.")

            raise ValidationError(
                message % {'user': self.user_cache.username},
                code='banned',
            )
예제 #22
0
파일: auth.py 프로젝트: dahito/Misago
    def confirm_user_not_banned(self, user):
        self.user_ban = get_user_ban(user)
        if self.user_ban:
            if self.user_ban.valid_until:
                if self.user_ban.user_message:
                    message = _("%(user)s, your account is "
                                "banned until %(date)s for:")
                else:
                    message = _("%(user)s, your account "
                                "is banned until %(date)s.")
                date_format = {'date': format_date(self.user_ban.valid_until)}
                message = message % date_format
            else:
                if self.user_ban.user_message:
                    message = _("%(user)s, your account is banned for:")
                else:
                    message = _("%(user)s, your account is banned.")

            raise ValidationError(
                message % {'user': self.user_cache.username},
                code='banned',
            )
예제 #23
0
    def get_context_data(self, **kwargs):

        context = super(Dashboard, self).get_context_data(**kwargs)

        # Warn the user if we don't have an available Launch Window
        has_one_window = False
        next_window = None
        launch_windows = LaunchWindow.objects.all()

        for window in launch_windows:
            current_date = datetime.now()

            next_window = croniter(window.cron_format,
                                   current_date).get_next(datetime)
            if (next_window - datetime.now()).seconds < 61:
                has_one_window = True
                break

        if not has_one_window and launch_windows.exists():
            messages.add_message(
                self.request, messages.ERROR,
                'No available Launch Windows! Next window on %s @ %s' %
                (format_date(next_window), format_time(next_window)))

        # Deployment Stats Data
        # Build pie chart data to show % projects deployed successfully
        deployments = Deployment.active_records.order_by('status').values(
            'status').annotate(count=Count('id'))
        items = [['string', 'number']] + [[item['status'], item['count']]
                                          for item in deployments]
        context['pie_chart'] = PieChart(SimpleDataSource(items),
                                        width='100%',
                                        height=300,
                                        options={'title': ''})

        # Deployment History Data
        # Get all projects with the days they were deployed and the count of the deploys on each day
        chart_data = []

        projects = list(Project.active_records.all())
        if len(projects) == 0:
            return context

        deploys = list(
            Deployment.objects.select_related('stage').order_by(
                'date_created'))

        # Get the date range for all the deployments ever done
        start_date = (timezone.now() - timedelta(days=60)).date()
        end_date = timezone.now().date()

        # Step through each day and create an array of deployment counts from each project
        # this would be much easier if we could aggregate by day.
        # once we can use django 1.7, we could write a __date transform. Then it would work.
        for day in range(-1, (end_date - start_date).days + 1):
            date = start_date + timedelta(days=day)
            if day == -1:
                data = ['Day']
            else:
                data = [date.strftime('%m/%d')]

            for project in projects:
                if day == -1:
                    data.append(project.name)
                    continue

                count = 0
                for d in deploys:
                    if d.stage.project_id == project.pk and d.date_created.date(
                    ) == date:
                        count += 1

                data.append(count)

            chart_data.append(data)

        context['line_chart'] = LineChart(SimpleDataSource(chart_data),
                                          width='100%',
                                          height=300,
                                          options={'title': ''})

        return context
예제 #24
0
def datetime(value, arg=None):
    if tools.StringEmpty(arg):
        arg = 'DATETIME_FORMAT'
    return format_date(value, arg=arg)
예제 #25
0
def get_toets_table(
    leerjaar: int,
    vak: Vak,
    toetsweek_periodes: Dict[int, List[int]],
    toetsweken: List[int],
    weging: Optional[Tuple[str, str]],
) -> List[List[str]]:
    header = [
        "Code",
        "Onderwerp/Omschrijving",
        "Domein",
        "Periode",
        "Week",
        "Soort werk",
        "Tijd\n(min)",
    ]

    if leerjaar in HIDE_DOMEIN:
        header.remove("Domein")

    if leerjaar in R4_LEERJAREN:
        header.append("Weging R4")

    if weging is not None:
        header.append(weging[0])

    rows = []

    for toets in vak.toetsen:
        periode = toets.periode
        week = toets.week or ""

        if toets.week in toetsweken:
            periode = f"{periode} (tw)"
            week = "/".join(
                [str(wk) for wk in toetsweek_periodes[toets.periode]])

        if toets.inleverdatum:
            formatted = format_date(toets.inleverdatum, "j F Y")
            inleverdatum = f"inleverdatum: {formatted}"
        elif toets.datum:
            formatted = format_date(toets.datum, "j F Y")
            inleverdatum = f"datum: {formatted}"
        else:
            inleverdatum = ""

        soort_werk = (toets.soortwerk.naam
                      if toets.soortwerk and toets.soortwerk.id != 12 else "")
        row = [
            toets.code,
            Omschrijving(
                content=clean_text(toets.omschrijving),
                inleverdatum=inleverdatum,
                voetnoot=toets.voetnoot,
            ),
            periode or "",
            week,
            soort_werk,
            toets.tijd or "",
        ]

        if leerjaar not in HIDE_DOMEIN:
            row.insert(2, toets.domein or "")

        if leerjaar in R4_LEERJAREN:
            row.append(toets.weging_r4 or "")

        if weging is not None:
            row.append(getattr(toets, weging[1]) or "")

        assert len(row) == len(header), "Header and row columns mismatch"
        rows.append(row)

    return [header] + rows
예제 #26
0
    def fill(self):
        from django.template.defaultfilters import date as format_date, floatformat
        from reportlab.platypus.flowables import Image
        from core.pdf.utils import Paragraph
        from invoicing import currency_format

        # Sender frame
        # Sender identity
        sender_paragraphs = []
        if self.invoice_base.current_revision.sender:
            sender_paragraphs.append(
                Paragraph(self.invoice_base.current_revision.sender,
                          self.style['Small']))
        sender_paragraphs.append(
            Paragraph(self.invoice_base.tenant.name, self.style['Small']))
        if self.invoice_base.current_revision.sender_address:
            sender_paragraphs.append(
                Paragraph(
                    u'\n'.join(self.invoice_base.current_revision.
                               sender_address.get_formatted()),
                    self.style['Small']))
        # Add layout table if logo or paragraphs
        if self.invoice_base.tenant.logo_cache:
            logo = Image(self.invoice_base.tenant.logo_cache)
            logo_width, logo_height = logo._restrictSize(50 * mm, 20 * mm)
            self.table([[logo, sender_paragraphs]],
                       (logo_width + 4 * mm, None),
                       self.style['LayoutTable'],
                       rowHeights=(20 * mm, ))
        else:
            for paragraph in sender_paragraphs:
                self.append(paragraph)

        # Billing address frame
        self.next_frame()
        if self.invoice_base.current_revision.contact:
            self.p(self.invoice_base.current_revision.contact.get_full_name(
                upper_name=True),
                   style=self.style['Address'])
        if self.invoice_base.current_revision.organization:
            self.p(
                self.invoice_base.current_revision.organization.corporate_name,
                style=self.style['Address'])
        if self.invoice_base.current_revision.billing_address:
            self.p(u'\n'.join(self.invoice_base.current_revision.
                              billing_address.get_formatted()),
                   style=self.style['Address'])

        # Delivery address frame
        self.next_frame()
        if self.invoice_base.current_revision.contact:
            self.p(self.invoice_base.current_revision.contact.get_full_name(
                upper_name=True),
                   style=self.style['Address'])
        if self.invoice_base.current_revision.organization:
            self.p(
                self.invoice_base.current_revision.organization.corporate_name,
                style=self.style['Address'])
        if self.invoice_base.current_revision.delivery_address:
            self.p(u'\n'.join(self.invoice_base.current_revision.
                              delivery_address.get_formatted()),
                   style=self.style['Address'])

        # Rest of the report
        self.next_frame()
        invoice_reference = pgettext('date', 'Undefined') if getattr(
            self.invoice_base, 'has_temporary_reference',
            None) else self.invoice_base.reference
        self.table([[
            ' '.join([
                unicode(self.invoice_base.RECORD_NAME).upper(),
                invoice_reference
            ]),
            format_date(self.invoice_base.current_revision.invoicing_date,
                        'DATE_FORMAT')
        ]], (12 * cm, 5 * cm),
                   style=self.style['InvoiceBaseReferencesTable'])

        self.spacer()
        rows = [[
            pgettext('table-headers', 'Description'),
            pgettext('table-headers', 'Qty'),
            pgettext('table-headers', 'Unit price (excl. tax)'),
            pgettext('table-headers', 'Tax'),
            pgettext('table-headers', 'Total (excl. tax)')
        ]]
        for item in self.invoice_base.current_revision.line_items:
            rows.append([
                item.description,
                floatformat(item.quantity, -2),
                currency_format(item.unit_price),
                '{0:.2%}'.format(item.tax.rate),
                currency_format(
                    item.total_price,
                    self.invoice_base.current_revision.currency.symbol)
            ])
        col_widths = (85 * mm, 20 * mm, 20 * mm, 20 * mm, 25 * mm)
        self.table(rows,
                   col_widths,
                   repeatRows=1,
                   style=self.style['InvoiceBaseItemsTable'])

        self.spacer()
        rows = [[
            _('TOTAL (excl. tax)'),
            currency_format(self.invoice_base.sub_total,
                            self.invoice_base.current_revision.currency.symbol)
        ]]
        for tax in self.invoice_base.taxes_amounts:
            rows.append([
                '%(tax_name)s (%(tax_rate)s)' % {
                    'tax_name': tax.get('name'),
                    'tax_rate': '{0:.2%}'.format(tax.get('rate'))
                },
                currency_format(
                    tax.get('amount'),
                    self.invoice_base.current_revision.currency.symbol)
            ])
        rows.append([
            _('TOTAL (incl. tax)'),
            currency_format(self.invoice_base.amount,
                            self.invoice_base.current_revision.currency.symbol)
        ])
        col_widths = (None, 25 * mm)
        self.start_keeptogether()
        self.table(rows,
                   col_widths,
                   hAlign='RIGHT',
                   style=self.style['InvoiceBaseSummaryTable'])
        self.end_keeptogether()

        # Legal notices
        self.spacer()
        self.start_keeptogether()
        if self.invoice_base.is_quotation():
            self.p(
                _("Valid until %(quotation_validity)s") % {
                    'quotation_validity':
                    format_date(
                        self.invoice_base.current_revision.quotation_validity,
                        'DATE_FORMAT')
                })
        elif self.invoice_base.is_purchase_order():
            if self.invoice_base.group.quotation:
                self.p(
                    _("Refers to quotation %(quotation_reference)s") % {
                        'quotation_reference':
                        self.invoice_base.group.quotation.reference
                    })
            else:
                self.p('')
        elif self.invoice_base.is_invoice(
        ) or self.invoice_base.is_down_payment_invoice():
            if self.invoice_base.current_revision.custom_payment_conditions:
                self.p(
                    _("Payment conditions: %(custom_payment_conditions)s") % {
                        'custom_payment_conditions':
                        self.invoice_base.current_revision.
                        custom_payment_conditions
                    })
            else:
                self.p(
                    _("Payment due date on %(due_date)s") % {
                        'due_date':
                        format_date(
                            self.invoice_base.current_revision.due_date,
                            'DATE_FORMAT')
                    })
            pt_dict = dict(PAYMENT_TYPES)
            invoicing_settings = self.invoice_base.tenant.tenant_settings.invoicing
            self.p(
                _("Accepted payment methods: %(accepted_payment_methods)s") % {
                    'accepted_payment_methods':
                    u', '.join([
                        unicode(pt_dict.get(pt, pt)).lower()
                        for pt in invoicing_settings.accepted_payment_types
                    ])
                })
            if invoicing_settings.late_fee_rate:
                self.p(
                    _("Late fee rate: %(late_fee_rate)s") % {
                        'late_fee_rate':
                        u'{0:.2%}'.format(invoicing_settings.late_fee_rate)
                    })
            else:
                self.p(_("Late fee at the legal rate"))
        elif self.invoice_base.is_credit_note():
            self.p(
                _("Refers to invoice %(invoice_reference)s") % {
                    'invoice_reference':
                    self.invoice_base.group.invoice.reference
                })
        else:
            self.p('')
        self.end_keeptogether()

        # Registration information
        self.next_frame()
        registration_info_parts = [
            self.invoice_base.tenant.name
        ] + self.invoice_base.tenant.registration_info.get_list()
        self.p(u' - '.join(registration_info_parts),
               style=self.style['Smaller'])

        # Metadata
        if self.invoice_base.issuer:
            self.doc.author = self.invoice_base.issuer.get_full_name()
        if self.invoice_base.reference:
            document_name = ' '.join([
                unicode(self.invoice_base.RECORD_NAME).upper(),
                self.invoice_base.reference
            ])
            self.doc.title = document_name
            self.doc.subject = document_name
        self.doc.creator = self.invoice_base.tenant.name
        self.doc.keywords = self.invoice_base.keywords
예제 #27
0
    def get_queryset(self):
        """
        Build the queryset for this list and also update the title that 
        describes the queryset
        """
        queryset = self.model.objects.all().order_by('-date_placed')
        self.description = self.base_description

        # Look for shortcut query filters
        if 'order_status' in self.request.GET:
            self.form = self.form_class()
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                self.description = "Orders without an order status"
                status = None
            else:
                self.description = "Orders with status '%s'" % status
            return self.model.objects.filter(status=status)

        if 'order_number' not in self.request.GET:
            self.form = self.form_class()
            return queryset

        self.form = self.form_class(self.request.GET)
        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data['order_number']:
            queryset = self.model.objects.filter(number__istartswith=data['order_number'])
            self.description = 'Orders with number starting with "%s"' % data['order_number']

        if data['name']:
            # If the value is two words, then assume they are first name and last name
            parts = data['name'].split()
            if len(parts) == 2:
                queryset = queryset.filter(Q(user__first_name__istartswith=parts[0]) |
                                           Q(user__last_name__istartswith=parts[1])).distinct()
            else:
                queryset = queryset.filter(Q(user__first_name__istartswith=data['name']) |
                                           Q(user__last_name__istartswith=data['name'])).distinct()
            self.description += " with customer name matching '%s'" % data['name']

        if data['product_title']:
            queryset = queryset.filter(lines__title__istartswith=data['product_title']).distinct()
            self.description += " including an item with title matching '%s'" % data['product_title']

        if data['product_id']:
            queryset = queryset.filter(Q(lines__upc=data['product_id']) |
                                       Q(lines__product_id=data['product_id'])).distinct()
            self.description += " including an item with ID '%s'" % data['product_id']

        if data['date_from'] and data['date_to']:
            # Add 24 hours to make search inclusive
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__gte=data['date_from']).filter(date_placed__lt=date_to)
            self.description += " placed between %s and %s" % (format_date(data['date_from']), format_date(data['date_to']))
        elif data['date_from']:
            queryset = queryset.filter(date_placed__gte=data['date_from'])
            self.description += " placed since %s" % format_date(data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__lt=date_to)
            self.description += " placed before %s" % format_date(data['date_to'])

        if data['voucher']:
            queryset = queryset.filter(discounts__voucher_code=data['voucher']).distinct()
            self.description += " using voucher '%s'" % data['voucher']

        if data['payment_method']:
            queryset = queryset.filter(sources__source_type__code=data['payment_method']).distinct()
            self.description += " paid for by %s" % data['payment_method']

        if data['status']:
            queryset = queryset.filter(status=data['status'])
            self.description += " with status %s" % data['status']

        return queryset
예제 #28
0
    def get_context_data(self, **kwargs):

        context = super(Dashboard, self).get_context_data(**kwargs)

        # Warn the user if we don't have an available Launch Window
        has_one_window = False
        next_window = None
        launch_windows = LaunchWindow.objects.all()

        for window in launch_windows:
            current_date = datetime.now()

            next_window = croniter(window.cron_format, current_date).get_next(datetime)
            if (next_window - datetime.now()).seconds < 61:
                has_one_window = True
                break

        if not has_one_window and launch_windows.exists():
            messages.add_message(self.request, messages.ERROR,
                'No available Launch Windows! Next window on %s @ %s' % (format_date(next_window), format_time(next_window)))

        # Deployment Stats Data
        # Build pie chart data to show % projects deployed successfully
        deployments = Deployment.active_records.order_by('status').values('status').annotate(count=Count('id'))
        items = [['string', 'number']] + [
            [item['status'], item['count']] for item in deployments
        ]
        context['pie_chart'] = PieChart(SimpleDataSource(items), width='100%', height=300, options={'title': ''})

        # Deployment History Data
        # Get all projects with the days they were deployed and the count of the deploys on each day
        chart_data = []

        projects = list(Project.active_records.all())
        if len(projects) == 0:
            return context

        deploys = list(Deployment.objects.select_related('stage').order_by('date_created'))

        # Get the date range for all the deployments ever done
        start_date = (timezone.now() - timedelta(days=60)).date()
        end_date = timezone.now().date()

        # Step through each day and create an array of deployment counts from each project
        # this would be much easier if we could aggregate by day.
        # once we can use django 1.7, we could write a __date transform. Then it would work.
        for day in range(-1, (end_date - start_date).days + 1):
            date = start_date + timedelta(days=day)
            if day == -1:
                data = ['Day']
            else:
                data = [date.strftime('%m/%d')]

            for project in projects:
                if day == -1:
                    data.append(project.name)
                    continue

                count = 0
                for d in deploys:
                    if d.stage.project_id == project.pk and d.date_created.date() == date:
                        count += 1

                data.append(count)

            chart_data.append(data)

        context['line_chart'] = LineChart(SimpleDataSource(chart_data), width='100%', height=300, options={'title': ''})

        return context
예제 #29
0
    def fill(self):
        from django.template.defaultfilters import date as format_date, floatformat
        from reportlab.platypus.flowables import Image
        from core.pdf.utils import Paragraph
        from invoicing import currency_format

        # Sender frame
        # Sender identity
        sender_paragraphs = []
        if self.invoice_base.current_revision.sender:
            sender_paragraphs.append(Paragraph(self.invoice_base.current_revision.sender, self.style['Small']))
        sender_paragraphs.append(Paragraph(self.invoice_base.tenant.name, self.style['Small']))
        if self.invoice_base.current_revision.sender_address:
            sender_paragraphs.append(Paragraph(u'\n'.join(self.invoice_base.current_revision.sender_address.get_formatted()), self.style['Small']))
        # Add layout table if logo or paragraphs
        if self.invoice_base.tenant.logo_cache:
            logo = Image(self.invoice_base.tenant.logo_cache)
            logo_width, logo_height = logo._restrictSize(50 * mm, 20 * mm)
            self.table(
                [[logo, sender_paragraphs]],
                (logo_width + 4 * mm, None),
                self.style['LayoutTable'],
                rowHeights=(20 * mm,)
            )
        else:
            for paragraph in sender_paragraphs:
                self.append(paragraph)

        # Billing address frame
        self.next_frame()
        if self.invoice_base.current_revision.contact:
            self.p(self.invoice_base.current_revision.contact.get_full_name(upper_name=True), style=self.style['Address'])
        if self.invoice_base.current_revision.organization:
            self.p(self.invoice_base.current_revision.organization.corporate_name, style=self.style['Address'])
        if self.invoice_base.current_revision.billing_address:
            self.p(u'\n'.join(self.invoice_base.current_revision.billing_address.get_formatted()), style=self.style['Address'])

        # Delivery address frame
        self.next_frame()
        if self.invoice_base.current_revision.contact:
            self.p(self.invoice_base.current_revision.contact.get_full_name(upper_name=True), style=self.style['Address'])
        if self.invoice_base.current_revision.organization:
            self.p(self.invoice_base.current_revision.organization.corporate_name, style=self.style['Address'])
        if self.invoice_base.current_revision.delivery_address:
            self.p(u'\n'.join(self.invoice_base.current_revision.delivery_address.get_formatted()), style=self.style['Address'])

        # Rest of the report
        self.next_frame()
        invoice_reference = pgettext('date', 'Undefined') if getattr(self.invoice_base, 'has_temporary_reference', None) else self.invoice_base.reference
        self.table([[
            ' '.join([unicode(self.invoice_base.RECORD_NAME).upper(), invoice_reference]),
            format_date(self.invoice_base.current_revision.invoicing_date, 'DATE_FORMAT')
        ]], (12 * cm, 5 * cm), style=self.style['InvoiceBaseReferencesTable'])

        self.spacer()
        rows = [[
            pgettext('table-headers', 'Description'),
            pgettext('table-headers', 'Qty'),
            pgettext('table-headers', 'Unit price (excl. tax)'),
            pgettext('table-headers', 'Tax'),
            pgettext('table-headers', 'Total (excl. tax)')
        ]]
        for item in self.invoice_base.current_revision.line_items:
            rows.append([
                item.description,
                floatformat(item.quantity, -2),
                currency_format(item.unit_price),
                '{0:.2%}'.format(item.tax.rate),
                currency_format(item.total_price, self.invoice_base.current_revision.currency.symbol)
            ])
        col_widths = (85 * mm, 20 * mm, 20 * mm, 20 * mm, 25 * mm)
        self.table(rows, col_widths, repeatRows=1, style=self.style['InvoiceBaseItemsTable'])

        self.spacer()
        rows = [[
            _('TOTAL (excl. tax)'),
            currency_format(self.invoice_base.sub_total, self.invoice_base.current_revision.currency.symbol)
        ]]
        for tax in self.invoice_base.taxes_amounts:
            rows.append([
                '%(tax_name)s (%(tax_rate)s)' % {
                    'tax_name': tax.get('name'),
                    'tax_rate': '{0:.2%}'.format(tax.get('rate'))
                },
                currency_format(tax.get('amount'), self.invoice_base.current_revision.currency.symbol)
            ])
        rows.append([
            _('TOTAL (incl. tax)'),
            currency_format(self.invoice_base.amount, self.invoice_base.current_revision.currency.symbol)
        ])
        col_widths = (None, 25 * mm)
        self.start_keeptogether()
        self.table(rows, col_widths, hAlign='RIGHT', style=self.style['InvoiceBaseSummaryTable'])
        self.end_keeptogether()

        # Legal notices
        self.spacer()
        self.start_keeptogether()
        if self.invoice_base.is_quotation():
            self.p(_("Valid until %(quotation_validity)s") % {
                'quotation_validity': format_date(self.invoice_base.current_revision.quotation_validity, 'DATE_FORMAT')
            })
        elif self.invoice_base.is_purchase_order():
            if self.invoice_base.group.quotation:
                self.p(_("Refers to quotation %(quotation_reference)s") % {
                    'quotation_reference': self.invoice_base.group.quotation.reference
                })
            else:
                self.p('')
        elif self.invoice_base.is_invoice() or self.invoice_base.is_down_payment_invoice():
            if self.invoice_base.current_revision.custom_payment_conditions:
                self.p(_("Payment conditions: %(custom_payment_conditions)s") % {
                    'custom_payment_conditions': self.invoice_base.current_revision.custom_payment_conditions
                })
            else:
                self.p(_("Payment due date on %(due_date)s") % {
                    'due_date': format_date(self.invoice_base.current_revision.due_date, 'DATE_FORMAT')
                })
            pt_dict = dict(PAYMENT_TYPES)
            invoicing_settings = self.invoice_base.tenant.tenant_settings.invoicing
            self.p(_("Accepted payment methods: %(accepted_payment_methods)s") % {
                'accepted_payment_methods': u', '.join([unicode(pt_dict.get(pt, pt)).lower() for pt in invoicing_settings.accepted_payment_types])
            })
            if invoicing_settings.late_fee_rate:
                self.p(_("Late fee rate: %(late_fee_rate)s") % {
                    'late_fee_rate': u'{0:.2%}'.format(invoicing_settings.late_fee_rate)
                })
            else:
                self.p(_("Late fee at the legal rate"))
        elif self.invoice_base.is_credit_note():
            self.p(_("Refers to invoice %(invoice_reference)s") % {
                'invoice_reference': self.invoice_base.group.invoice.reference
            })
        else:
            self.p('')
        self.end_keeptogether()

        # Registration information
        self.next_frame()
        registration_info_parts = [self.invoice_base.tenant.name] + self.invoice_base.tenant.registration_info.get_list()
        self.p(u' - '.join(registration_info_parts), style=self.style['Smaller'])

        # Metadata
        if self.invoice_base.issuer:
            self.doc.author = self.invoice_base.issuer.get_full_name()
        if self.invoice_base.reference:
            document_name = ' '.join([
                unicode(self.invoice_base.RECORD_NAME).upper(),
                self.invoice_base.reference
            ])
            self.doc.title = document_name
            self.doc.subject = document_name
        self.doc.creator = self.invoice_base.tenant.name
        self.doc.keywords = self.invoice_base.keywords
예제 #30
0
    def get_queryset(self):
        """
        Build the queryset for this list and also update the title that
        describes the queryset
        """
        queryset = self.model.objects.all().order_by('-date_placed')
        queryset = self.sort_queryset(queryset)
        desc_ctx = {
            'main_filter': _('All orders'),
            'name_filter': '',
            'title_filter': '',
            'upc_filter': '',
            'sku_filter': '',
            'date_filter': '',
            'voucher_filter': '',
            'payment_filter': '',
            'status_filter': '',
        }

        # Look for shortcut query filters
        if 'order_status' in self.request.GET:
            self.form = self.form_class()
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                desc_ctx['main_filter'] = _("Orders without an order status")
                status = None
            else:
                desc_ctx['main_filter'] = _("Orders with status '%s'") % status
            self.description = self.desc_template % desc_ctx
            return self.model.objects.filter(status=status)

        if 'order_number' not in self.request.GET:
            self.description = self.desc_template % desc_ctx
            self.form = self.form_class()
            return queryset

        self.form = self.form_class(self.request.GET)
        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data['order_number']:
            queryset = self.model.objects.filter(
                number__istartswith=data['order_number'])
            desc_ctx['main_filter'] = _(
                'Orders with number starting with "%s"') % data['order_number']

        if data['name']:
            # If the value is two words, then assume they are first name and last name
            parts = data['name'].split()
            if len(parts) == 2:
                queryset = queryset.filter(
                    Q(user__first_name__istartswith=parts[0])
                    | Q(user__last_name__istartswith=parts[1])).distinct()
            else:
                queryset = queryset.filter(
                    Q(user__first_name__istartswith=data['name'])
                    | Q(user__last_name__istartswith=data['name'])).distinct()
            desc_ctx['name_filter'] = _(
                " with customer name matching '%s'") % data['name']

        if data['product_title']:
            queryset = queryset.filter(
                lines__title__istartswith=data['product_title']).distinct()
            desc_ctx['title_filter'] = _(
                " including an item with title matching '%s'"
            ) % data['product_title']

        if data['upc']:
            queryset = queryset.filter(lines__upc=data['upc'])
            desc_ctx['upc_filter'] = _(
                " including an item with UPC '%s'") % data['upc']

        if data['partner_sku']:
            queryset = queryset.filter(lines__partner_sku=data['partner_sku'])
            desc_ctx['upc_filter'] = _(
                " including an item with ID '%s'") % data['partner_sku']

        if data['date_from'] and data['date_to']:
            # Add 24 hours to make search inclusive
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(
                date_placed__gte=data['date_from']).filter(
                    date_placed__lt=date_to)
            desc_ctx['date_filter'] = _(
                " placed between %(start_date)s and %(end_date)s") % {
                    'start_date': format_date(data['date_from']),
                    'end_date': format_date(data['date_to'])
                }
        elif data['date_from']:
            queryset = queryset.filter(date_placed__gte=data['date_from'])
            desc_ctx['date_filter'] = _(" placed since %s") % format_date(
                data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__lt=date_to)
            desc_ctx['date_filter'] = _(" placed before %s") % format_date(
                data['date_to'])

        if data['voucher']:
            queryset = queryset.filter(
                discounts__voucher_code=data['voucher']).distinct()
            desc_ctx['voucher_filter'] = _(
                " using voucher '%s'") % data['voucher']

        if data['payment_method']:
            queryset = queryset.filter(
                sources__source_type__code=data['payment_method']).distinct()
            desc_ctx['payment_filter'] = _(
                " paid for by %s") % data['payment_method']

        if data['status']:
            queryset = queryset.filter(status=data['status'])
            desc_ctx['status_filter'] = _(" with status %s") % data['status']

        self.description = self.desc_template % desc_ctx
        return queryset
예제 #31
0
    def get_desc_context(self, data=None):
        """Update the title that describes the queryset"""
        desc_ctx = {
            'main_filter': _('All orders'),
            'name_filter': '',
            'title_filter': '',
            'upc_filter': '',
            'sku_filter': '',
            'date_filter': '',
            'voucher_filter': '',
            'payment_filter': '',
            'status_filter': '',
        }

        if 'order_status' in self.request.GET:
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                desc_ctx['main_filter'] = _("Orders without an order status")
            else:
                desc_ctx['main_filter'] = _("Orders with status '%s'") % status
        if data is None:
            return desc_ctx

        if data['order_number']:
            desc_ctx['main_filter'] = _(
                'Orders with number starting with "%s"') % data['order_number']

        if data['name']:
            desc_ctx['name_filter'] = _(
                " with customer name matching '%s'") % data['name']

        if data['product_title']:
            desc_ctx['title_filter'] = _(
                " including an item with title matching '%s'"
            ) % data['product_title']

        if data['upc']:
            desc_ctx['upc_filter'] = _(
                " including an item with UPC '%s'") % data['upc']

        if data['partner_sku']:
            desc_ctx['upc_filter'] = _(
                " including an item with ID '%s'") % data['partner_sku']

        if data['date_from'] and data['date_to']:
            desc_ctx['date_filter'] = _(
                " placed between %(start_date)s and %(end_date)s") % {
                    'start_date': format_date(data['date_from']),
                    'end_date': format_date(data['date_to'])
                }
        elif data['date_from']:
            desc_ctx['date_filter'] = _(" placed since %s") % format_date(
                data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            desc_ctx['date_filter'] = _(" placed before %s") % format_date(
                data['date_to'])

        if data['voucher']:
            desc_ctx['voucher_filter'] = _(
                " using voucher '%s'") % data['voucher']

        if data['payment_method']:
            desc_ctx['payment_filter'] = _(
                " paid for by %s") % data['payment_method']

        if data['status']:
            desc_ctx['status_filter'] = _(" with status %s") % data['status']

        return desc_ctx
예제 #32
0
    def get_queryset(self):
        """
        Build the queryset for this list and also update the title that
        describes the queryset
        """
        queryset = self.model.objects.all().order_by('-date_placed')
        queryset = self.sort_queryset(queryset)
        desc_ctx = {
            'main_filter': _('All orders'),
            'name_filter': '',
            'title_filter': '',
            'upc_filter': '',
            'sku_filter': '',
            'date_filter': '',
            'voucher_filter': '',
            'payment_filter': '',
            'status_filter': '',
        }

        # Look for shortcut query filters
        if 'order_status' in self.request.GET:
            self.form = self.form_class()
            status = self.request.GET['order_status']
            if status.lower() == 'none':
                desc_ctx['main_filter'] = _("Orders without an order status")
                status = None
            else:
                desc_ctx['main_filter'] = _("Orders with status '%s'") % status
            self.description = self.desc_template % desc_ctx
            return self.model.objects.filter(status=status)

        if 'order_number' not in self.request.GET:
            self.description = self.desc_template % desc_ctx
            self.form = self.form_class()
            return queryset

        self.form = self.form_class(self.request.GET)
        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data['order_number']:
            queryset = self.model.objects.filter(number__istartswith=data['order_number'])
            desc_ctx['main_filter'] = _('Orders with number starting with "%s"') % data['order_number']

        if data['name']:
            # If the value is two words, then assume they are first name and last name
            parts = data['name'].split()
            if len(parts) == 2:
                queryset = queryset.filter(Q(user__first_name__istartswith=parts[0]) |
                                           Q(user__last_name__istartswith=parts[1])).distinct()
            else:
                queryset = queryset.filter(Q(user__first_name__istartswith=data['name']) |
                                           Q(user__last_name__istartswith=data['name'])).distinct()
            desc_ctx['name_filter'] = _(" with customer name matching '%s'") % data['name']

        if data['product_title']:
            queryset = queryset.filter(lines__title__istartswith=data['product_title']).distinct()
            desc_ctx['title_filter'] = _(" including an item with title matching '%s'") % data['product_title']

        if data['upc']:
            queryset = queryset.filter(lines__upc=data['upc'])
            desc_ctx['upc_filter'] = _(" including an item with UPC '%s'") % data['upc']

        if data['partner_sku']:
            queryset = queryset.filter(lines__partner_sku=data['partner_sku'])
            desc_ctx['upc_filter'] = _(" including an item with ID '%s'") % data['partner_sku']

        if data['date_from'] and data['date_to']:
            # Add 24 hours to make search inclusive
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__gte=data['date_from']).filter(date_placed__lt=date_to)
            desc_ctx['date_filter'] = _(" placed between %(start_date)s and %(end_date)s") % {
                'start_date': format_date(data['date_from']),
                'end_date': format_date(data['date_to'])}
        elif data['date_from']:
            queryset = queryset.filter(date_placed__gte=data['date_from'])
            desc_ctx['date_filter'] = _(" placed since %s") % format_date(data['date_from'])
        elif data['date_to']:
            date_to = data['date_to'] + datetime.timedelta(days=1)
            queryset = queryset.filter(date_placed__lt=date_to)
            desc_ctx['date_filter'] = _(" placed before %s") % format_date(data['date_to'])

        if data['voucher']:
            queryset = queryset.filter(discounts__voucher_code=data['voucher']).distinct()
            desc_ctx['voucher_filter'] = _(" using voucher '%s'") % data['voucher']

        if data['payment_method']:
            queryset = queryset.filter(sources__source_type__code=data['payment_method']).distinct()
            desc_ctx['payment_filter'] = _(" paid for by %s") % data['payment_method']

        if data['status']:
            queryset = queryset.filter(status=data['status'])
            desc_ctx['status_filter'] = _(" with status %s") % data['status']

        return queryset
예제 #33
0
    def get_context_data(self, **kwargs):

        context = super(Dashboard, self).get_context_data(**kwargs)

        # Warn the user if we don't have an available Launch Window
        has_one_window = False
        next_window = None
        launch_windows = LaunchWindow.objects.all()

        for window in launch_windows:
            current_date = datetime.now()

            next_window = croniter(window.cron_format, current_date).get_next(datetime)
            if (next_window - datetime.now()).seconds < 61:
                has_one_window = True
                break

        if not has_one_window and launch_windows.exists():
            messages.add_message(self.request, messages.ERROR,
                'No available Launch Windows! Next window on %s @ %s' % (format_date(next_window), format_time(next_window)))

        # Get the deployments and projects and bail if we don't have any
        deploys = list(Deployment.objects.order_by('date_created'))
        if len(deploys) == 0:
            return context

        projects = list(Project.active_records.all())
        if len(projects) == 0:
            return context

        # Deployment Stats Data
        # Build pie chart data to show % projects deployed successfully
        deployments = Deployment.active_records.order_by('status').values('status').annotate(count=Count('id'))
        items = [
            [item['status'], item['count']] for item in deployments
        ]
        context['pie_chart_data'] = json.dumps(items)

        # Deployment History Data
        # Get all projects with the days they were deployed and the count of the deploys on each day
        chart_data = []

        # If we're using postgres do this with one query, otherwise pound the db with the ORM.
        if connection.vendor == 'postgresql':
            # I couldn't figure out how to do this in the ORM with a Group By... here's a postgres version.
            # If you're smarter than me, and can fix this, please do.
            cursor = connection.cursor()
            cursor.execute("""
            SELECT project.name as project_name
            , date_trunc('day', deployment.date_created) as deploy_date
            , COUNT(date_trunc('day', deployment.date_created)) as deploy_count
            FROM "projects_project" as project
            LEFT JOIN "projects_stage" as stage ON ( project."id" = stage."project_id" )
            LEFT JOIN "projects_deployment" as deployment ON ( stage."id" = deployment."stage_id" )
            GROUP BY project.name, date_trunc('day', deployment.date_created)
            ORDER BY date_trunc('day', deployment.date_created), project.name
            """)

            rows = cursor.fetchall()

            # Get a distinct list of projects from our results
            project_names = []
            previous_project = ''
            for row in rows:
                if row[0] == previous_project:
                    continue
                previous_project = row[0]
                project_names.append(row[0])

            # Convert the sql results into a dictionary indexed by project and date (this makes the next step easier)
            project_deployment_data = {}
            for project in project_names:
                project_deployment_data[project] = {}
                for row in rows:
                    if project == row[0] and row[1] is not None:
                        project_deployment_data[project][row[1].strftime('%m/%d')] = row[2]

            # Build the google chart data using the project and date dictionary
            # We need an array for each day that has the deployment counts for each project
            deploy_day = None
            for row in rows:
                # If we have a project w/ no deployments, keep going
                if row[1] is None:
                    continue

                # If we already processed this day, keep going
                if row[1] == deploy_day:
                    continue

                # Process this day for each project
                deploy_day = row[1].strftime('%m/%d')
                daily_counts = [deploy_day]
                for project in project_names:
                    daily_counts.append(project_deployment_data[project].get(deploy_day, 0))

                chart_data.append(daily_counts)

            chart_data = [['Day'] + project_names] + chart_data

        else:
            # Get the date range for all the deployments ever done
            start_date = deploys[0].date_created
            end_date = deploys[len(deploys)-1].date_created

            # Step through each day and create an array of deployment counts from each project
            for day in range(-1, (end_date.date() - start_date.date()).days + 1):
                date = start_date + timedelta(days=day)
                if day == -1:
                    data = ['Day']
                else:
                    data = [date.strftime('%m/%d')]

                for project in projects:
                    if day == -1:
                        data.append(project.name)
                        continue

                    range_ = (date.date(), date.date() + timedelta(days=1))
                    # Nested ORM Call... not good.
                    data.append(Deployment.objects.select_related('stage').filter(stage__project_id=project.pk, date_created__range=range_).count())

                chart_data.append(data)

        context['chart_data'] = json.dumps(chart_data)

        return context