Exemple #1
0
def generate_cancellation(invoice: Invoice, trigger_pdf=True):
    if invoice.canceled:
        raise ValueError("Invoice should not be canceled twice.")
    cancellation = modelcopy(invoice)
    cancellation.pk = None
    cancellation.invoice_no = None
    cancellation.prefix = None
    cancellation.refers = invoice
    cancellation.is_cancellation = True
    cancellation.date = timezone.now().date()
    cancellation.payment_provider_text = ''
    cancellation.file = None
    with language(invoice.locale, invoice.event.settings.region):
        cancellation.invoice_from = invoice.event.settings.get(
            'invoice_address_from')
        cancellation.invoice_from_name = invoice.event.settings.get(
            'invoice_address_from_name')
        cancellation.invoice_from_zipcode = invoice.event.settings.get(
            'invoice_address_from_zipcode')
        cancellation.invoice_from_city = invoice.event.settings.get(
            'invoice_address_from_city')
        cancellation.invoice_from_country = invoice.event.settings.get(
            'invoice_address_from_country')
        cancellation.invoice_from_tax_id = invoice.event.settings.get(
            'invoice_address_from_tax_id')
        cancellation.invoice_from_vat_id = invoice.event.settings.get(
            'invoice_address_from_vat_id')
    cancellation.save()

    cancellation = build_cancellation(cancellation)
    if trigger_pdf:
        invoice_pdf(cancellation.pk)
    return cancellation
Exemple #2
0
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        if self.copy_from:
            i = modelcopy(self.copy_from)
            i.pk = None
            kwargs['instance'] = i
            kwargs.setdefault('initial', {})
        return kwargs
Exemple #3
0
 def get_form_kwargs(self):
     kwargs = super().get_form_kwargs()
     kwargs['event'] = self.request.event
     if self.copy_from:
         i = modelcopy(self.copy_from)
         i.pk = None
         kwargs['instance'] = i
     else:
         kwargs['instance'] = SubEvent(event=self.request.event)
     return kwargs
Exemple #4
0
 def get_form_kwargs(self):
     kwargs = super().get_form_kwargs()
     kwargs['event'] = self.request.event
     if self.copy_from:
         i = modelcopy(self.copy_from)
         i.pk = None
         kwargs['instance'] = i
     else:
         kwargs['instance'] = SubEvent(event=self.request.event)
     return kwargs
Exemple #5
0
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        if self.copy_from:
            i = modelcopy(self.copy_from)
            i.pk = None
            kwargs['instance'] = i
        else:
            kwargs['instance'] = ItemCategory(event=self.request.event)
        return kwargs
Exemple #6
0
    def __init__(self, **kwargs):
        self.instance = kwargs.get('instance', None)
        self.event = kwargs.get('event')
        items = kwargs.pop(
            'items', None) or self.event.items.prefetch_related('variations')
        self.original_instance = modelcopy(
            self.instance) if self.instance else None
        initial = kwargs.get('initial', {})
        if self.instance and self.instance.pk:
            initial['itemvars'] = [
                str(i.pk) for i in self.instance.items.all()
            ] + [
                '{}-{}'.format(v.item_id, v.pk)
                for v in self.instance.variations.all()
            ]
        kwargs['initial'] = initial
        super().__init__(**kwargs)

        choices = []
        for item in items:
            if len(item.variations.all()) > 0:
                for v in item.variations.all():
                    choices.append(
                        ('{}-{}'.format(item.pk,
                                        v.pk), '{} – {}'.format(item,
                                                                v.value)))
            else:
                choices.append(('{}'.format(item.pk), str(item)))

        self.fields['itemvars'] = forms.MultipleChoiceField(
            label=_('Products'),
            required=False,
            choices=choices,
            widget=forms.CheckboxSelectMultiple)

        if self.event.has_subevents:
            self.fields['subevent'].queryset = self.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': self.event.slug,
                                'organizer': self.event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'Date')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
            self.fields['subevent'].required = True
        else:
            del self.fields['subevent']
Exemple #7
0
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        if self.copy_from:
            i = modelcopy(self.copy_from)
            i.pk = None
            i.redeemed = 0
            kwargs['instance'] = i
        else:
            kwargs['instance'] = Voucher(event=self.request.event)
        return kwargs
Exemple #8
0
 def save(self, event, *args, **kwargs):
     objs = []
     for code in self.cleaned_data['codes']:
         obj = modelcopy(self.instance)
         obj.event = event
         obj.code = code
         data = dict(self.cleaned_data)
         data['code'] = code
         data['bulk'] = True
         del data['codes']
         objs.append(obj)
     Voucher.objects.bulk_create(objs)
     return objs
Exemple #9
0
 def save(self, event, *args, **kwargs):
     objs = []
     for code in self.cleaned_data['codes']:
         obj = modelcopy(self.instance)
         obj.event = event
         obj.code = code
         data = dict(self.cleaned_data)
         data['code'] = code
         data['bulk'] = True
         del data['codes']
         objs.append(obj)
     Voucher.objects.bulk_create(objs)
     return objs
Exemple #10
0
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        if self.copy_from:
            i = modelcopy(self.copy_from)
            i.pk = None
            kwargs['instance'] = i
            kwargs.setdefault('initial', {})
            kwargs['initial']['itemvars'] = [str(i.pk) for i in self.copy_from.items.all()] + [
                '{}-{}'.format(v.item_id, v.pk) for v in self.copy_from.variations.all()
            ]
        else:
            kwargs['instance'] = Quota(event=self.request.event)
        return kwargs
Exemple #11
0
 def get_form_kwargs(self):
     kwargs = super().get_form_kwargs()
     kwargs['event'] = self.request.event
     initial = kwargs.get('initial', {})
     if self.copy_from:
         i = modelcopy(self.copy_from)
         i.pk = None
         kwargs['instance'] = i
     else:
         kwargs['instance'] = SubEvent(event=self.request.event)
         initial['location'] = self.request.event.location
         initial['geo_lat'] = self.request.event.geo_lat
         initial['geo_lon'] = self.request.event.geo_lon
     kwargs['initial'] = initial
     return kwargs
Exemple #12
0
def generate_cancellation(invoice: Invoice, trigger_pdf=True):
    cancellation = modelcopy(invoice)
    cancellation.pk = None
    cancellation.invoice_no = None
    cancellation.prefix = None
    cancellation.refers = invoice
    cancellation.is_cancellation = True
    cancellation.date = timezone.now().date()
    cancellation.payment_provider_text = ''
    cancellation.file = None
    cancellation.save()

    cancellation = build_cancellation(cancellation)
    if trigger_pdf:
        invoice_pdf(cancellation.pk)
    return cancellation
Exemple #13
0
def generate_cancellation(invoice: Invoice, trigger_pdf=True):
    cancellation = modelcopy(invoice)
    cancellation.pk = None
    cancellation.invoice_no = None
    cancellation.prefix = None
    cancellation.refers = invoice
    cancellation.is_cancellation = True
    cancellation.date = timezone.now().date()
    cancellation.payment_provider_text = ''
    cancellation.file = None
    cancellation.save()

    cancellation = build_cancellation(cancellation)
    if trigger_pdf:
        invoice_pdf(cancellation.pk)
    return cancellation
Exemple #14
0
 def save(self, event, *args, **kwargs):
     objs = []
     for code in self.cleaned_data['codes']:
         obj = modelcopy(self.instance)
         obj.event = event
         obj.code = code
         try:
             obj.seat = self.cleaned_data['seats'].pop()
             obj.item = obj.seat.product
         except IndexError:
             pass
         data = dict(self.cleaned_data)
         data['code'] = code
         data['bulk'] = True
         del data['codes']
         objs.append(obj)
     Voucher.objects.bulk_create(objs)
     return objs
Exemple #15
0
def generate_cancellation(invoice: Invoice, trigger_pdf=True):
    if invoice.canceled:
        raise ValueError("Invoice should not be canceled twice.")
    cancellation = modelcopy(invoice)
    cancellation.pk = None
    cancellation.invoice_no = None
    cancellation.prefix = None
    cancellation.refers = invoice
    cancellation.is_cancellation = True
    cancellation.date = timezone.now().date()
    cancellation.payment_provider_text = ''
    cancellation.file = None
    cancellation.save()

    cancellation = build_cancellation(cancellation)
    if trigger_pdf:
        invoice_pdf(cancellation.pk)
    return cancellation
Exemple #16
0
    def __init__(self, **kwargs):
        self.instance = kwargs.get('instance', None)
        self.event = kwargs.get('event')
        items = kwargs.pop('items', None) or self.event.items.prefetch_related('variations')
        self.original_instance = modelcopy(self.instance) if self.instance else None
        initial = kwargs.get('initial', {})
        if self.instance and self.instance.pk:
            initial['itemvars'] = [str(i.pk) for i in self.instance.items.all()] + [
                '{}-{}'.format(v.item_id, v.pk) for v in self.instance.variations.all()
            ]
        kwargs['initial'] = initial
        super().__init__(**kwargs)

        choices = []
        for item in items:
            if len(item.variations.all()) > 0:
                for v in item.variations.all():
                    choices.append(('{}-{}'.format(item.pk, v.pk), '{} – {}'.format(item, v.value)))
            else:
                choices.append(('{}'.format(item.pk), str(item)))

        self.fields['itemvars'] = forms.MultipleChoiceField(
            label=_('Products'),
            required=False,
            choices=choices,
            widget=forms.CheckboxSelectMultiple
        )

        if self.event.has_subevents:
            self.fields['subevent'].queryset = self.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2': 'event',
                    'data-select2-url': reverse('control:event.subevents.select2', kwargs={
                        'event': self.event.slug,
                        'organizer': self.event.organizer.slug,
                    }),
                    'data-placeholder': pgettext_lazy('subevent', 'Date')
                }
            )
            self.fields['subevent'].widget.choices = self.fields['subevent'].choices
            self.fields['subevent'].required = True
        else:
            del self.fields['subevent']
Exemple #17
0
 def save(self, event, *args, **kwargs):
     objs = []
     for code in self.cleaned_data['codes']:
         obj = modelcopy(self.instance)
         obj.event = event
         obj.code = code
         try:
             obj.seat = self.cleaned_data['seats'].pop()
             obj.item = obj.seat.product
         except IndexError:
             pass
         data = dict(self.cleaned_data)
         data['code'] = code
         data['bulk'] = True
         del data['codes']
         objs.append(obj)
     Voucher.objects.bulk_create(objs)
     objs = []
     for v in event.vouchers.filter(code__in=self.cleaned_data['codes']):
         # We need to query them again as bulk_create does not fill in .pk values on databases
         # other than PostgreSQL
         objs.append(v)
     return objs
Exemple #18
0
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        initial = kwargs.get('initial')
        if instance:
            self.initial_instance_data = modelcopy(instance)
            try:
                if instance.variation:
                    initial['itemvar'] = '%d-%d' % (instance.item.pk, instance.variation.pk)
                elif instance.item:
                    initial['itemvar'] = str(instance.item.pk)
                elif instance.quota:
                    initial['itemvar'] = 'q-%d' % instance.quota.pk
            except Item.DoesNotExist:
                pass
        else:
            self.initial_instance_data = None
        super().__init__(*args, **kwargs)

        if instance.event.has_subevents:
            self.fields['subevent'].queryset = instance.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2': 'event',
                    'data-select2-url': reverse('control:event.subevents.select2', kwargs={
                        'event': instance.event.slug,
                        'organizer': instance.event.organizer.slug,
                    }),
                    'data-placeholder': pgettext_lazy('subevent', 'Date')
                }
            )
            self.fields['subevent'].widget.choices = self.fields['subevent'].choices
            self.fields['subevent'].required = False
        elif 'subevent':
            del self.fields['subevent']

        choices = []
        if 'itemvar' in initial or (self.data and 'itemvar' in self.data):
            iv = self.data.get('itemvar') or initial.get('itemvar', '')
            if iv.startswith('q-'):
                q = self.instance.event.quotas.get(pk=iv[2:])
                choices.append(('q-%d' % q.pk, _('Any product in quota "{quota}"').format(quota=q)))
            elif '-' in iv:
                itemid, varid = iv.split('-')
                i = self.instance.event.items.get(pk=itemid)
                v = i.variations.get(pk=varid)
                choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (str(i), v.value)))
            elif iv:
                i = self.instance.event.items.get(pk=iv)
                if i.variations.exists():
                    choices.append((str(i.pk), _('{product} – Any variation').format(product=i)))
                else:
                    choices.append((str(i.pk), str(i)))

        self.fields['itemvar'].choices = choices
        self.fields['itemvar'].widget = Select2ItemVarQuota(
            attrs={
                'data-model-select2': 'generic',
                'data-select2-url': reverse('control:event.vouchers.itemselect2', kwargs={
                    'event': instance.event.slug,
                    'organizer': instance.event.organizer.slug,
                }),
                'data-placeholder': ''
            }
        )
        self.fields['itemvar'].widget.choices = self.fields['itemvar'].choices
        self.fields['itemvar'].required = True
Exemple #19
0
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        initial = kwargs.get('initial')
        if instance:
            self.initial_instance_data = modelcopy(instance)
            try:
                if instance.variation:
                    initial['itemvar'] = '%d-%d' % (instance.item.pk,
                                                    instance.variation.pk)
                elif instance.item:
                    initial['itemvar'] = str(instance.item.pk)
                elif instance.quota:
                    initial['itemvar'] = 'q-%d' % instance.quota.pk
            except Item.DoesNotExist:
                pass
        else:
            self.initial_instance_data = None
        super().__init__(*args, **kwargs)

        if instance.event.has_subevents:
            self.fields['subevent'].queryset = instance.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': instance.event.slug,
                                'organizer': instance.event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'Date')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
            self.fields['subevent'].required = False
        elif 'subevent':
            del self.fields['subevent']

        choices = []
        if 'itemvar' in initial or (self.data and 'itemvar' in self.data):
            iv = self.data.get('itemvar') or initial.get('itemvar', '')
            if iv.startswith('q-'):
                q = self.instance.event.quotas.get(pk=iv[2:])
                choices.append(
                    ('q-%d' % q.pk,
                     _('Any product in quota "{quota}"').format(quota=q)))
            elif '-' in iv:
                itemid, varid = iv.split('-')
                i = self.instance.event.items.get(pk=itemid)
                v = i.variations.get(pk=varid)
                choices.append(
                    ('%d-%d' % (i.pk, v.pk), '%s – %s' % (str(i), v.value)))
            elif iv:
                i = self.instance.event.items.get(pk=iv)
                if i.variations.exists():
                    choices.append(
                        (str(i.pk),
                         _('{product} – Any variation').format(product=i)))
                else:
                    choices.append((str(i.pk), str(i)))

        self.fields['itemvar'].choices = choices
        self.fields['itemvar'].widget = Select2ItemVarQuota(
            attrs={
                'data-model-select2':
                'generic',
                'data-select2-url':
                reverse('control:event.vouchers.itemselect2',
                        kwargs={
                            'event': instance.event.slug,
                            'organizer': instance.event.organizer.slug,
                        }),
                'data-placeholder':
                ''
            })
        self.fields['itemvar'].widget.choices = self.fields['itemvar'].choices
        self.fields['itemvar'].required = True
Exemple #20
0
    def async_form_valid(self, task, form):
        lockfn = NoLockManager
        if form.data.get('block_quota'):
            lockfn = self.request.event.lock
        batch_size = 500
        total_num = 1  # will be set later

        def set_progress(percent):
            if not task.request.called_directly:
                task.update_state(
                    state='PROGRESS',
                    meta={'value': percent}
                )

        def process_batch(batch_vouchers, voucherids):
            Voucher.objects.bulk_create(batch_vouchers)
            if not connection.features.can_return_rows_from_bulk_insert:
                batch_vouchers = list(self.request.event.vouchers.filter(code__in=[v.code for v in batch_vouchers]))

            log_entries = []
            for v in batch_vouchers:
                voucherids.append(v.pk)
                data = dict(form.cleaned_data)
                data['code'] = code
                data['bulk'] = True
                del data['codes']
                log_entries.append(
                    v.log_action('pretix.voucher.added', data=data, user=self.request.user, save=False)
                )
            LogEntry.objects.bulk_create(log_entries)
            form.post_bulk_save(batch_vouchers)
            batch_vouchers.clear()
            set_progress(len(voucherids) / total_num * (50. if form.cleaned_data['send'] else 100.))

        voucherids = []
        with lockfn(), transaction.atomic():
            if not form.is_valid():
                raise ValidationError(form.errors)
            total_num = len(form.cleaned_data['codes'])

            batch_vouchers = []
            for code in form.cleaned_data['codes']:
                if len(batch_vouchers) > batch_size:
                    process_batch(batch_vouchers, voucherids)

                obj = modelcopy(form.instance, code=None)
                obj.event = self.request.event
                obj.code = code
                try:
                    obj.seat = form.cleaned_data['seats'].pop()
                    obj.item = obj.seat.product
                except IndexError:
                    pass
                batch_vouchers.append(obj)

            process_batch(batch_vouchers, voucherids)

        if form.cleaned_data['send']:
            vouchers_send(
                event=self.request.event,
                vouchers=voucherids,
                subject=form.cleaned_data['send_subject'],
                message=form.cleaned_data['send_message'],
                recipients=[r._asdict() for r in form.cleaned_data['send_recipients']],
                user=self.request.user.pk,
                progress=lambda p: set_progress(50. + p * 50.)
            )