コード例 #1
0
def close_bills(modeladmin, request, queryset, action='close_bills'):
    # Validate bills
    for bill in queryset:
        if not validate_contact(request, bill):
            return False
        if not bill.is_open:
            messages.warning(request, _("Selected bills should be in open state"))
            return False
    SelectSourceFormSet = modelformset_factory(modeladmin.model, form=SelectSourceForm, formset=AdminFormSet, extra=0)
    formset = SelectSourceFormSet(queryset=queryset)
    if request.POST.get('post') == 'generic_confirmation':
        formset = SelectSourceFormSet(request.POST, request.FILES, queryset=queryset)
        if formset.is_valid():
            transactions = []
            for form in formset.forms:
                source = form.cleaned_data['source']
                transaction = form.instance.close(payment=source)
                if transaction:
                    transactions.append(transaction)
            for bill in queryset:
                modeladmin.log_change(request, bill, 'Closed')
            messages.success(request, _("Selected bills have been closed"))
            if transactions:
                num = len(transactions)
                if num == 1:
                    url = change_url(transactions[0])
                else:
                    url = reverse('admin:payments_transaction_changelist')
                    url += 'id__in=%s' % ','.join([str(t.id) for t in transactions])
                context = {
                    'url': url,
                    'num': num,
                }
                message = ungettext(
                    _('<a href="%(url)s">One related transaction</a> has been created') % context,
                    _('<a href="%(url)s">%(num)i related transactions</a> have been created') % context,
                    num)
                messages.success(request, mark_safe(message))
            return
    opts = modeladmin.model._meta
    context = {
        'title': _("Are you sure about closing the following bills?"),
        'content_message': _("Once a bill is closed it can not be further modified.</p>"
                             "<p>Please select a payment source for the selected bills"),
        'action_name': 'Close bills',
        'action_value': action,
        'display_objects': [],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'formset': formset,
        'obj': get_object_from_url(modeladmin, request),
    }
    template = 'admin/orchestra/generic_confirmation.html'
    if action == 'close_send_download_bills':
        template = 'admin/bills/bill/close_send_download_bills.html'
    return render(request, template, context)
コード例 #2
0
ファイル: actions.py プロジェクト: SCORE42/django-orchestra
def close_bills(modeladmin, request, queryset, action='close_bills'):
    # Validate bills
    for bill in queryset:
        if not validate_contact(request, bill):
            return False
        if not bill.is_open:
            messages.warning(request, _("Selected bills should be in open state"))
            return False
    SelectSourceFormSet = modelformset_factory(modeladmin.model, form=SelectSourceForm, formset=AdminFormSet, extra=0)
    formset = SelectSourceFormSet(queryset=queryset)
    if request.POST.get('post') == 'generic_confirmation':
        formset = SelectSourceFormSet(request.POST, request.FILES, queryset=queryset)
        if formset.is_valid():
            transactions = []
            for form in formset.forms:
                source = form.cleaned_data['source']
                transaction = form.instance.close(payment=source)
                if transaction:
                    transactions.append(transaction)
            for bill in queryset:
                modeladmin.log_change(request, bill, 'Closed')
            messages.success(request, _("Selected bills have been closed"))
            if transactions:
                num = len(transactions)
                if num == 1:
                    url = change_url(transactions[0])
                else:
                    url = reverse('admin:payments_transaction_changelist')
                    url += 'id__in=%s' % ','.join([str(t.id) for t in transactions])
                context = {
                    'url': url,
                    'num': num,
                }
                message = ungettext(
                    _('<a href="%(url)s">One related transaction</a> has been created') % context,
                    _('<a href="%(url)s">%(num)i related transactions</a> have been created') % context,
                    num)
                messages.success(request, mark_safe(message))
            return
    opts = modeladmin.model._meta
    context = {
        'title': _("Are you sure about closing the following bills?"),
        'content_message': _("Once a bill is closed it can not be further modified.</p>"
                             "<p>Please select a payment source for the selected bills"),
        'action_name': 'Close bills',
        'action_value': action,
        'display_objects': [],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'formset': formset,
        'obj': get_object_from_url(modeladmin, request),
    }
    template = 'admin/orchestra/generic_confirmation.html'
    if action == 'close_send_download_bills':
        template = 'admin/bills/bill/close_send_download_bills.html'
    return render(request, template, context)
コード例 #3
0
def retry_backend(modeladmin, request, queryset):
    related_operations = queryset.values_list('operations__id', flat=True).distinct()
    related_operations = BackendOperation.objects.filter(pk__in=related_operations)
    related_operations = related_operations.select_related('log__server').prefetch_related('instance')
    if request.POST.get('post') == 'generic_confirmation':
        operations = []
        for operation in related_operations:
            if operation.instance:
                op = Operation.load(operation)
                operations.append(op)
        if not operations:
            messages.warning(request, _("No backend operation has been executed."))
        else:
            logs = Operation.execute(operations)
            message_user(request, logs)
        for backendlog in queryset:
            modeladmin.log_change(request, backendlog, 'Retried')
        return
    opts = modeladmin.model._meta
    display_objects = []
    deleted_objects = []
    for op in related_operations:
        if not op.instance:
            deleted_objects.append(op)
        else:
            context = {
                'backend': op.log.backend,
                'action': op.action,
                'instance': op.instance,
                'instance_url': change_url(op.instance),
                'server': op.log.server,
                'server_url': change_url(op.log.server),
            }
            display_objects.append(mark_safe(
                '%(backend)s.%(action)s(<a href="%(instance_url)s">%(instance)s</a>) @ <a href="%(server_url)s">%(server)s</a>' % context
            ))
    context = {
        'title': _("Are you sure to execute the following backends?"),
        'action_name': _('Retry backend'),
        'action_value': 'retry_backend',
        'display_objects': display_objects,
        'deleted_objects': deleted_objects,
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/orchestration/backends/retry.html', context)
コード例 #4
0
ファイル: actions.py プロジェクト: zeus911/django-orchestra
def set_soa(modeladmin, request, queryset):
    if queryset.filter(top__isnull=False).exists():
        msg = _("Set SOA on subdomains is not possible.")
        modeladmin.message_user(request, msg, messages.ERROR)
        return
    form = SOAForm()
    if request.POST.get('post') == 'generic_confirmation':
        form = SOAForm(request.POST)
        if form.is_valid():
            updates = {
                name: value
                for name, value in form.cleaned_data.items() if value
            }
            change_message = _("SOA set %s") % str(updates)[1:-1]
            for domain in queryset:
                for name, value in updates.items():
                    if name.startswith('clear_'):
                        name = name.replace('clear_', '')
                        value = ''
                    setattr(domain, name, value)
                modeladmin.log_change(request, domain, change_message)
                domain.save()
            num = len(queryset)
            msg = ungettext(
                _("SOA record for one domain has been updated."),
                _("SOA record for %s domains has been updated.") % num, num)
            modeladmin.message_user(request, msg)
            return
    opts = modeladmin.model._meta
    context = {
        'title': _("Set SOA for selected domains"),
        'content_message': '',
        'action_name': _("Set SOA"),
        'action_value': 'set_soa',
        'display_objects':
        [admin_link('__str__')(domain) for domain in queryset],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'form': form,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/orchestra/generic_confirmation.html',
                  context)
コード例 #5
0
ファイル: actions.py プロジェクト: SCORE42/django-orchestra
def set_soa(modeladmin, request, queryset):
    if queryset.filter(top__isnull=False).exists():
        msg = _("Set SOA on subdomains is not possible.")
        modeladmin.message_user(request, msg, messages.ERROR)
        return
    form = SOAForm()
    if request.POST.get('post') == 'generic_confirmation':
        form = SOAForm(request.POST)
        if form.is_valid():
            updates = {name: value for name, value in form.cleaned_data.items() if value}
            change_message = _("SOA set %s") % str(updates)[1:-1]
            for domain in queryset:
                for name, value in updates.items():
                    if name.startswith('clear_'):
                        name = name.replace('clear_', '')
                        value = ''
                    setattr(domain, name, value)
                modeladmin.log_change(request, domain, change_message)
                domain.save()
            num = len(queryset)
            msg = ungettext(
                _("SOA record for one domain has been updated."),
                _("SOA record for %s domains has been updated.") % num,
                num
            )
            modeladmin.message_user(request, msg)
            return
    opts = modeladmin.model._meta
    context = {
        'title': _("Set SOA for selected domains"),
        'content_message': '',
        'action_name': _("Set SOA"),
        'action_value': 'set_soa',
        'display_objects': [admin_link('__str__')(domain) for domain in queryset],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'form': form,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/orchestra/generic_confirmation.html', context)
コード例 #6
0
def update_orders(modeladmin, request, queryset, extra_context=None):
    if not queryset:
        return
    if request.POST.get('post') == 'confirmation':
        num = 0
        services = []
        for service in queryset:
            updates = service.update_orders()
            num += len(updates)
            services.append(str(service.pk))
            modeladmin.log_change(request, service, _("Orders updated"))
        if num == 1:
            url = reverse('admin:orders_order_change',
                          args=(updates[0][0].pk, ))
            msg = _(
                '<a href="%s">One related order</a> has benn updated') % url
        else:
            url = reverse('admin:orders_order_changelist')
            url += '?service__in=%s' % ','.join(services)
            msg = _('<a href="%s">%s related orders</a> have been updated') % (
                url, num)
        modeladmin.message_user(request, mark_safe(msg))
        return
    updates = []
    for service in queryset:
        updates += service.update_orders(commit=False)
    opts = modeladmin.model._meta
    context = {
        'title': _("Update orders will cause the following."),
        'action_name': 'Update orders',
        'action_value': 'update_orders',
        'updates': updates,
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/services/service/update_orders.html',
                  context)
コード例 #7
0
ファイル: actions.py プロジェクト: SCORE42/django-orchestra
def update_orders(modeladmin, request, queryset, extra_context=None):
    if not queryset:
        return
    if request.POST.get('post') == 'confirmation':
        num = 0
        services = []
        for service in queryset:
            updates = service.update_orders()
            num += len(updates)
            services.append(str(service.pk))
            modeladmin.log_change(request, service, _("Orders updated"))
        if num == 1:
            url = reverse('admin:orders_order_change', args=(updates[0][0].pk,))
            msg = _('<a href="%s">One related order</a> has benn updated') % url
        else:
            url = reverse('admin:orders_order_changelist')
            url += '?service__in=%s' % ','.join(services)
            msg = _('<a href="%s">%s related orders</a> have been updated') % (url, num)
        modeladmin.message_user(request, mark_safe(msg))
        return
    updates = []
    for service in queryset:
        updates += service.update_orders(commit=False)
    opts = modeladmin.model._meta
    context = {
        'title': _("Update orders will cause the following."),
        'action_name': 'Update orders',
        'action_value': 'update_orders',
        'updates': updates,
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/services/service/update_orders.html', context)
コード例 #8
0
ファイル: actions.py プロジェクト: SCORE42/django-orchestra
def edit_records(modeladmin, request, queryset):
    selected_ids = queryset.values_list('id', flat=True)
    # Include subodmains
    queryset = queryset.model.objects.filter(
        Q(top__id__in=selected_ids) | Q(id__in=selected_ids)
    ).annotate(
        structured_id=Coalesce('top__id', 'id'),
        structured_name=Concat('top__name', 'name')
    ).order_by('-structured_id', 'structured_name')
    formsets = []
    for domain in queryset.prefetch_related('records'):
        modeladmin_copy = copy.copy(modeladmin)
        modeladmin_copy.model = Record
        prefix = '' if domain.is_top else '&nbsp;'*8
        context = {
            'url': change_url(domain),
            'name': prefix+domain.name,
            'title': '',
        }
        if domain.id not in selected_ids:
            context['name'] += '*'
            context['title'] = _("This subdomain was not explicitly selected "
                                 "but has been automatically added to this list.")
        link = '<a href="%(url)s" title="%(title)s">%(name)s</a>' % context
        modeladmin_copy.verbose_name_plural = mark_safe(link)
        RecordFormSet = modelformset_factory(
            Record, form=RecordForm, formset=RecordEditFormSet, extra=1, can_delete=True)
        formset = RecordFormSet(queryset=domain.records.all(), prefix=domain.id)
        formset.instance = domain
        formset.cls = RecordFormSet
        formsets.append(formset)
    
    if request.POST.get('post') == 'generic_confirmation':
        posted_formsets = []
        all_valid = True
        for formset in formsets:
            instance = formset.instance
            formset = formset.cls(
                request.POST, request.FILES, queryset=formset.queryset, prefix=instance.id)
            formset.instance = instance
            if not formset.is_valid():
                all_valid = False
            posted_formsets.append(formset)
        formsets = posted_formsets
        if all_valid:
            for formset in formsets:
                for form in formset.forms:
                    form.instance.domain_id = formset.instance.id
                formset.save()
                fake_form = AttrDict({
                    'changed_data': False
                })
                change_message = modeladmin.construct_change_message(request, fake_form, [formset])
                modeladmin.log_change(request, formset.instance, change_message)
            num = len(formsets)
            message = ungettext(
                _("Records for one selected domain have been updated."),
                _("Records for %i selected domains have been updated.") % num,
                num)
            modeladmin.message_user(request, message)
            return
    
    opts = modeladmin.model._meta
    context = {
        'title': _("Edit records"),
        'action_name': _("Edit records"),
        'action_value': 'edit_records',
        'display_objects': [],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'formsets': formsets,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/domains/domain/edit_records.html', context)
コード例 #9
0
ファイル: actions.py プロジェクト: zeus911/django-orchestra
def edit_records(modeladmin, request, queryset):
    selected_ids = queryset.values_list('id', flat=True)
    # Include subodmains
    queryset = queryset.model.objects.filter(
        Q(top__id__in=selected_ids) | Q(id__in=selected_ids)).annotate(
            structured_id=Coalesce('top__id', 'id'),
            structured_name=Concat('top__name',
                                   'name')).order_by('-structured_id',
                                                     'structured_name')
    formsets = []
    for domain in queryset.prefetch_related('records'):
        modeladmin_copy = copy.copy(modeladmin)
        modeladmin_copy.model = Record
        prefix = '' if domain.is_top else '&nbsp;' * 8
        context = {
            'url': change_url(domain),
            'name': prefix + domain.name,
            'title': '',
        }
        if domain.id not in selected_ids:
            context['name'] += '*'
            context['title'] = _(
                "This subdomain was not explicitly selected "
                "but has been automatically added to this list.")
        link = '<a href="%(url)s" title="%(title)s">%(name)s</a>' % context
        modeladmin_copy.verbose_name_plural = mark_safe(link)
        RecordFormSet = modelformset_factory(Record,
                                             form=RecordForm,
                                             formset=RecordEditFormSet,
                                             extra=1,
                                             can_delete=True)
        formset = RecordFormSet(queryset=domain.records.all(),
                                prefix=domain.id)
        formset.instance = domain
        formset.cls = RecordFormSet
        formsets.append(formset)

    if request.POST.get('post') == 'generic_confirmation':
        posted_formsets = []
        all_valid = True
        for formset in formsets:
            instance = formset.instance
            formset = formset.cls(request.POST,
                                  request.FILES,
                                  queryset=formset.queryset,
                                  prefix=instance.id)
            formset.instance = instance
            if not formset.is_valid():
                all_valid = False
            posted_formsets.append(formset)
        formsets = posted_formsets
        if all_valid:
            for formset in formsets:
                for form in formset.forms:
                    form.instance.domain_id = formset.instance.id
                formset.save()
                fake_form = AttrDict({'changed_data': False})
                change_message = modeladmin.construct_change_message(
                    request, fake_form, [formset])
                modeladmin.log_change(request, formset.instance,
                                      change_message)
            num = len(formsets)
            message = ungettext(
                _("Records for one selected domain have been updated."),
                _("Records for %i selected domains have been updated.") % num,
                num)
            modeladmin.message_user(request, message)
            return

    opts = modeladmin.model._meta
    context = {
        'title': _("Edit records"),
        'action_name': _("Edit records"),
        'action_value': 'edit_records',
        'display_objects': [],
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'formsets': formsets,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/domains/domain/edit_records.html', context)
コード例 #10
0
def orchestrate(modeladmin, request, queryset):
    operations = set()
    action = Operation.SAVE
    operations = OrderedSet()
    if queryset.model is Route:
        for route in queryset:
            routes = [route]
            backend = route.backend_class
            if action not in backend.actions:
                continue
            for instance in backend.model_class().objects.all():
                if route.matches(instance):
                    operations.add(Operation(backend, instance, action, routes=routes))
    elif queryset.model is Server:
        models = set()
        for server in queryset:
            routes = server.routes.all()
            for route in routes.filter(is_active=True):
                model = route.backend_class.model_class()
                models.add(model)
        querysets = [model.objects.order_by('id') for model in models]
        
        route_cache = {}
        for model in models:
            for instance in model.objects.all():
                manager.collect(instance, action, operations=operations, route_cache=route_cache)
            routes = []
        result = []
        for operation in operations:
            routes = [route for route in operation.routes if route.host in queryset]
            operation.routes = routes
            if routes:
                result.append(operation)
        operations = result
    if not operations:
        messages.warning(request, _("No related operations."))
        return
    
    if request.POST.get('post') == 'generic_confirmation':
        logs = Operation.execute(operations)
        message_user(request, logs)
        for obj in queryset:
            modeladmin.log_change(request, obj, 'Orchestrated')
        return
    
    opts = modeladmin.model._meta
    display_objects = {}
    for operation in operations:
        try:
            display_objects[operation.backend].append(operation)
        except KeyError:
            display_objects[operation.backend] = [operation]
    context = {
        'title': _("Are you sure to execute the following operations?"),
        'action_name': _('Orchestrate'),
        'action_value': 'orchestrate',
        'display_objects': display_objects,
        'queryset': queryset,
        'opts': opts,
        'app_label': opts.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
        'obj': get_object_from_url(modeladmin, request),
    }
    return render(request, 'admin/orchestration/orchestrate.html', context)