Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def shot_statistics(live_server, organizer, event, logged_in_client):
event.plugins += ',pretix.plugins.statistics'
event.save()
eb = event.items.create(name=_('Early-bird ticket'), default_price=23, admission=True)
regular = event.items.create(name=_('Regular ticket'), default_price=26, admission=True)
for day in range(30):
d = now() - timedelta(days=day)
num = max(0, random.randint(25, 45) - day)
for l in range(num):
order = event.orders.create(
status=Order.STATUS_PAID,
email='admin@localhost',
expires=now(),
datetime=d,
total=Decimal("23"),
locale='en'
)
if day > 15:
order.positions.create(
item=eb, price=Decimal('23.00')
)
else:
order.positions.create(
item=regular, price=Decimal('26.00')
)
logged_in_client.get(live_server.url + '/control/event/{}/{}/statistics/'.format(
def iterate_positions(self, form_data: dict):
tz = pytz.timezone(self.event.settings.timezone)
qs = OrderPosition.objects.filter(
order__event=self.event,
).select_related(
'order', 'order__invoice_address', 'item', 'variation',
'voucher', 'tax_rule'
).prefetch_related(
'answers', 'answers__question'
)
if form_data['paid_only']:
qs = qs.filter(order__status=Order.STATUS_PAID)
headers = [
_('Order code'),
_('Position ID'),
_('Status'),
_('Email'),
_('Order date'),
]
if self.event.has_subevents:
headers.append(pgettext('subevent', 'Date'))
headers.append(_('Start date'))
headers.append(_('End date'))
headers += [
_('Product'),
_('Variation'),
_('Price'),
def _redirect_to_order(self):
if self.request.session.get('payment_stripe_order_secret') != self.order.secret and self.payment.provider != 'stripe_ideal':
messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
'in your emails to continue.'))
return redirect(eventreverse(self.request.event, 'presale:event.index'))
return redirect(eventreverse(self.request.event, 'presale:event.order', kwargs={
'order': self.order.code,
'secret': self.order.secret
}) + ('?paid=yes' if self.order.status == Order.STATUS_PAID else ''))
'payer': trans.payer,
'trans_id': trans.pk
})
)
trans.state = BankTransaction.STATE_VALID
trans.save()
return JsonResponse({
'status': 'ok',
})
else:
return JsonResponse({
'status': 'error',
'message': _('Negative amount but refund can\'t be logged, please create manual refund first.')
})
if trans.order.status == Order.STATUS_PAID:
return JsonResponse({
'status': 'error',
'message': _('The order is already marked as paid.')
})
elif trans.order.status == Order.STATUS_CANCELED:
return JsonResponse({
'status': 'error',
'message': _('The order has already been canceled.')
})
p = trans.order.payments.get_or_create(
amount=trans.amount,
provider='banktransfer',
state__in=(OrderPayment.PAYMENT_STATE_CREATED, OrderPayment.PAYMENT_STATE_PENDING),
defaults={
'state': OrderPayment.PAYMENT_STATE_CREATED,
if fdata.get('status') == 'overpaid':
qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True)
qs = qs.filter(
Q(~Q(status=Order.STATUS_CANCELED) & Q(pending_sum_t__lt=0))
| Q(Q(status=Order.STATUS_CANCELED) & Q(pending_sum_rc__lt=0))
)
elif fdata.get('status') == 'pendingpaid':
qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True)
qs = qs.filter(
Q(status__in=(Order.STATUS_EXPIRED, Order.STATUS_PENDING)) & Q(pending_sum_t__lte=0)
& Q(require_approval=False)
)
elif fdata.get('status') == 'underpaid':
qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True)
qs = qs.filter(
status=Order.STATUS_PAID,
pending_sum_t__gt=0
)
elif fdata.get('status') == 'pa':
qs = qs.filter(
status=Order.STATUS_PENDING,
require_approval=True
)
elif fdata.get('status') == 'testmode':
qs = qs.filter(
testmode=True
)
elif fdata.get('status') == 'cp':
s = OrderPosition.objects.filter(
order=OuterRef('pk')
)
qs = qs.annotate(
'name': _('Break-even'),
'total': 10000,
'amount': 435,
'description': ''
},
{
'name': _('We can have a party'),
'total': 20000,
'amount': 435,
'description': ''
}
])
for day in range(30):
d = now() - timedelta(days=day)
order = event.orders.create(
status=Order.STATUS_PAID,
email='admin@localhost',
expires=now(),
datetime=d,
total=Decimal("23"),
locale='en'
)
order.payments.create(
provider='banktransfer',
amount=order.total,
payment_date=d,
state=OrderPayment.PAYMENT_STATE_CONFIRMED
)
num = max(0, random.randint(25, 45) - day)
for l in range(num):
if day > 15:
order.positions.create(
f._calculate_tax()
f.save()
else:
f = OrderFee(**fee_data)
f.order = order
f._calculate_tax()
f.save()
order.total += sum([f.value for f in order.fees.all()])
order.save(update_fields=['total'])
if order.total == Decimal('0.00') and validated_data.get('status') == Order.STATUS_PAID and not payment_provider:
payment_provider = 'free'
if order.total == Decimal('0.00') and validated_data.get('status') != Order.STATUS_PAID:
order.status = Order.STATUS_PAID
order.save()
order.payments.create(
amount=order.total, provider='free', state=OrderPayment.PAYMENT_STATE_CONFIRMED,
payment_date=now()
)
elif payment_provider == "free" and order.total != Decimal('0.00'):
raise ValidationError('You cannot use the "free" payment provider for non-free orders.')
elif validated_data.get('status') == Order.STATUS_PAID:
if not payment_provider:
raise ValidationError('You cannot create a paid order without a payment provider.')
order.payments.create(
amount=order.total,
provider=payment_provider,
info=payment_info,
payment_date=payment_date,
state=OrderPayment.PAYMENT_STATE_CONFIRMED
def render_invoice_text(self, order: Order, payment: OrderPayment) -> str:
"""
This is called when an invoice for an order with this payment provider is generated.
The default implementation returns the content of the _invoice_text configuration
variable (an I18nString), or an empty string if unconfigured. For paid orders, the
default implementation always renders a string stating that the invoice is already paid.
"""
if order.status == Order.STATUS_PAID:
return pgettext_lazy('invoice', 'The payment for this invoice has already been received.')
return self.settings.get('_invoice_text', as_type=LazyI18nString, default='')
def render_invoice_text(self, order: Order, payment: OrderPayment) -> str:
if order.status == Order.STATUS_PAID:
if payment.info_data.get('id', None):
return '{}\r\n{}: {}\r\n{}: {}'.format(
_('The payment for this invoice has already been received.'),
_('PayPal payment ID'),
payment.info_data['id'],
_('PayPal sale ID'),
payment.info_data['transactions'][0]['related_resources'][0]['sale']['id']
)
else:
return super().render_invoice_text(order, payment)
return self.settings.get('_invoice_text', as_type=LazyI18nString, default='')
'item_short': item_names[item] if len(item_names[item]) < 15 else (item_names[item][:15] + "…"),
'ordered': cnt,
'paid': num_paid.get(item, 0)
} for item, cnt in num_ordered.items()
])
cache.set('statistics_obp_data' + ckey, ctx['obp_data'])
ctx['rev_data'] = cache.get('statistics_rev_data' + ckey)
if not ctx['rev_data']:
rev_by_day = {}
if subevent:
for o in OrderPosition.objects.annotate(
payment_date=Subquery(op_date, output_field=DateTimeField())
).filter(order__event=self.request.event,
subevent=subevent,
order__status=Order.STATUS_PAID,
payment_date__isnull=False).values('payment_date', 'price'):
day = o['payment_date'].astimezone(tz).date()
rev_by_day[day] = rev_by_day.get(day, 0) + o['price']
else:
for o in Order.objects.annotate(
payment_date=Subquery(p_date, output_field=DateTimeField())
).filter(event=self.request.event,
status=Order.STATUS_PAID,
payment_date__isnull=False).values('payment_date', 'total'):
day = o['payment_date'].astimezone(tz).date()
rev_by_day[day] = rev_by_day.get(day, 0) + o['total']
data = []
total = 0
for d in dateutil.rrule.rrule(
dateutil.rrule.DAILY,