def check_image_evaluation(self, image, show_history=False, detail=False, tag=None, policy=None):

itype, _, image_digest = self._discover_inputimage(image)<EOL>if not image_digest:<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>if not tag and itype != '<STR_LIT>':<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>thetag = tag if tag else image<EOL>url = "<STR_LIT>"<EOL>url = url.format(<EOL>base_url=self.url,<EOL>image_digest=image_digest,<EOL>history=str(show_history).lower(),<EOL>detail=str(detail).lower(),<EOL>tag=thetag,<EOL>policy_id=("<STR_LIT>" % policy) if policy else "<STR_LIT>")<EOL>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Check the latest policy evaluation for an image

        **Arguments**
            - image: Input image can be in the following formats: registry/repo:tag
            - show_history: Show all previous policy evaluations
            - detail: Show detailed policy evaluation report
            - tag: Specify which TAG is evaluated for a given image ID or Image Digest
            - policy: Specify which POLICY to use for evaluate (defaults currently active policy)

        **Success Return Value**
            A JSON object representing the evaluation status.


def add_registry(self, registry, registry_user, registry_pass, insecure=False, registry_type="<STR_LIT>", validate=True):

registry_types = ['<STR_LIT>', '<STR_LIT>']<EOL>if registry_type and registry_type not in registry_types:<EOL><INDENT>return [False, "<STR_LIT>" + str(registry_types)]<EOL><DEDENT>if self._registry_string_is_valid(registry):<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>if not registry_type:<EOL><INDENT>registry_type = self._get_registry_type(registry)<EOL><DEDENT>payload = {<EOL>'<STR_LIT>': registry,<EOL>'<STR_LIT>': registry_user,<EOL>'<STR_LIT>': registry_pass,<EOL>'<STR_LIT>': registry_type,<EOL>'<STR_LIT>': not insecure}<EOL>url = "<STR_LIT>".format(<EOL>base_url=self.url,<EOL>validate=validate)<EOL>res = requests.post(url, data=json.dumps(payload), headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Add image registry

        **Arguments**
            - registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
            - registry_user: Username
            - registry_pass: Password
            - insecure: Allow connection to registry without SSL cert checks (ex: if registry uses a self-signed SSL certificate)
            - registry_type: Specify the registry type. 'docker_v2' and 'awsecr' are supported (default='docker_v2')
            - validate: If set to 'False' will not attempt to validate registry/creds on registry add

        **Success Return Value**
            A JSON object representing the registry.


def update_registry(self, registry, registry_user, registry_pass, insecure=False, registry_type="<STR_LIT>", validate=True):

if self._registry_string_is_valid(registry):<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>payload = {<EOL>'<STR_LIT>': registry,<EOL>'<STR_LIT>': registry_user,<EOL>'<STR_LIT>': registry_pass,<EOL>'<STR_LIT>': registry_type,<EOL>'<STR_LIT>': not insecure}<EOL>url = "<STR_LIT>".format(<EOL>base_url=self.url,<EOL>registry=registry,<EOL>validate=validate)<EOL>res = requests.put(url, data=json.dumps(payload), headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Update an existing image registry.

        **Arguments**
            - registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
            - registry_user: Username
            - registry_pass: Password
            - insecure: Allow connection to registry without SSL cert checks (ex: if registry uses a self-signed SSL certificate)
            - registry_type: Specify the registry type. 'docker_v2' and 'awsecr' are supported (default='docker_v2')
            - validate: If set to 'False' will not attempt to validate registry/creds on registry add

        **Success Return Value**
            A JSON object representing the registry.


<EOL>if re.match("<STR_LIT>", registry):<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>url = self.url + "<STR_LIT>" + registry<EOL>res = requests.delete(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Delete an existing image registry

        **Arguments**
            - registry: Full hostname/port of registry. Eg. myrepo.example.com:5000


url = self.url + "<STR_LIT>"<EOL>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            List all current image registries

        **Arguments**
            - None

        **Success Return Value**
            A JSON object representing the list of registries.


if self._registry_string_is_valid(registry):<EOL><INDENT>return [False, "<STR_LIT>"]<EOL><DEDENT>url = self.url + "<STR_LIT>" + registry<EOL>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Find the registry and return its json description

        **Arguments**
            - registry: Full hostname/port of registry. Eg. myrepo.example.com:5000

        **Success Return Value**
            A JSON object representing the registry.


def add_policy(self, name, rules, comment="<STR_LIT>", bundleid=None):

policy = {<EOL>'<STR_LIT:name>': name,<EOL>'<STR_LIT>': comment,<EOL>'<STR_LIT>': rules,<EOL>'<STR_LIT:version>': '<STR_LIT>'<EOL>}<EOL>if bundleid:<EOL><INDENT>policy['<STR_LIT>'] = bundleid<EOL><DEDENT>url = self.url + '<STR_LIT>'<EOL>data = json.dumps(policy)<EOL>res = requests.post(url, headers=self.hdrs, data=data, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Create a new policy

        **Arguments**
            - name: The name of the policy.
            - rules: A list of Anchore PolicyRule elements (while creating/updating a policy, new rule IDs will be created backend side)
            - comment: A human-readable description.
            - bundleid: Target bundle. If not specified, the currently active bundle will be used.

        **Success Return Value**
            A JSON object containing the policy description.


url = self.url + '<STR_LIT>'<EOL>if bundleid:<EOL><INDENT>url += '<STR_LIT>' + bundleid<EOL><DEDENT>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            List the current set of scanning policies.

        **Arguments**
            - bundleid: Target bundle. If not specified, the currently active bundle will be used.

        **Success Return Value**
            A JSON object containing the list of policies.


def get_policy(self, policyid, bundleid=None):

url = self.url + '<STR_LIT>' + policyid<EOL>if bundleid:<EOL><INDENT>url += '<STR_LIT>' + bundleid<EOL><DEDENT>

**Description**
            Retrieve the policy with the given id in the targeted policy bundle

        **Arguments**
            - policyid: Unique identifier associated with this policy.
            - bundleid: Target bundle. If not specified, the currently active bundle will be used.

        **Success Return Value**
            A JSON object containing the policy description.


def update_policy(self, policyid, policy_description):

url = self.url + '<STR_LIT>' + policyid<EOL>data = json.dumps(policy_description)<EOL>res = requests.put(url, headers=self.hdrs, data=data, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Update the policy with the given id

        **Arguments**
            - policyid: Unique identifier associated with this policy.
            - policy_description: A dictionary with the policy description.

        **Success Return Value**
            A JSON object containing the policy description.


def delete_policy(self, policyid, bundleid=None):

url = self.url + '<STR_LIT>' + policyid<EOL>if bundleid:<EOL><INDENT>url += '<STR_LIT>' + bundleid<EOL><DEDENT>res = requests.delete(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.text]<EOL>

**Description**
            Delete the policy with the given id in the targeted policy Bundle

        **Arguments**
            - policyid: Unique identifier associated with this policy.
            - policy_description: A dictionary with the policy description.


def add_alert(self, name, description=None, scope="<STR_LIT>", triggers={'<STR_LIT>': True, '<STR_LIT>': True},<EOL>enabled=False, notification_channels=[]):

alert = {<EOL>'<STR_LIT:name>': name,<EOL>'<STR_LIT:description>': description,<EOL>'<STR_LIT>': triggers,<EOL>'<STR_LIT>': scope,<EOL>'<STR_LIT>': enabled,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': notification_channels,<EOL>}<EOL>url = self.url + '<STR_LIT>'<EOL>data = json.dumps(alert)<EOL>res = requests.post(url, headers=self.hdrs, data=data, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Create a new alert

        **Arguments**
            - name: The name of the alert.
            - description: The descprition of the alert.
            - scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: 'host.domain = "example.com" and container.image != "alpine:latest"')
            - tiggers: A dict {str: bool} indicating wich triggers should be enabled/disabled. (default: {'failed': True, 'unscanned': True})
            - enabled: Whether this alert should actually be applied.
            - notification_channels: A list of notification channel ids.

        **Success Return Value**
            A JSON object containing the alert description.


def list_alerts(self, limit=None, cursor=None):

url = self.url + '<STR_LIT>'<EOL>if limit:<EOL><INDENT>url += '<STR_LIT>' + str(limit)<EOL>if cursor:<EOL><INDENT>url += '<STR_LIT>' + cursor<EOL><DEDENT><DEDENT>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            List the current set of scanning alerts.

        **Arguments**
            - limit: Maximum number of alerts in the response.
            - cursor: An opaque string representing the current position in the list of alerts. It's provided in the 'responseMetadata' of the list_alerts response.

        **Success Return Value**
            A JSON object containing the list of alerts.


url = self.url + '<STR_LIT>' + alertid<EOL>res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Retrieve the scanning alert with the given id

        **Arguments**
            - alertid: Unique identifier associated with this alert.

        **Success Return Value**
            A JSON object containing the alert description.


def update_alert(self, alertid, alert_description):

url = self.url + '<STR_LIT>' + alertid<EOL>data = json.dumps(alert_description)<EOL>res = requests.put(url, headers=self.hdrs, data=data, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            Update the alert with the given id

        **Arguments**
            - alertid: Unique identifier associated with this alert.
            - alert_description: A dictionary with the alert description.

        **Success Return Value**
            A JSON object containing the alert description.


url = self.url + '<STR_LIT>' + policyid<EOL>res = requests.delete(url, headers=self.hdrs, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.text]<EOL>

**Description**
            Delete the alert with the given id

        **Arguments**
            - alertid: Unique identifier associated with this alert.


def activate_subscription(self, subscription_type, subscription_key):

return self._update_subscription(subscription_type, subscription_key, True)<EOL>

**Description**
            Activate a subscription

        **Arguments**
            - subscription_type: Type of subscription. Valid options:
                - 'tag_update': Receive notification when new image is pushed
                - 'policy_eval': Receive notification when image policy status changes
                - 'vuln_update': Receive notification when vulnerabilities are added, removed or modified
            - subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest


def deactivate_subscription(self, subscription_type, subscription_key):

return self._update_subscription(subscription_type, subscription_key, False)<EOL>

**Description**
            Deactivate a subscription

        **Arguments**
            - subscription_type: Type of subscription. Valid options:
                - 'tag_update': Receive notification when new image is pushed
                - 'policy_eval': Receive notification when image policy status changes
                - 'vuln_update': Receive notification when vulnerabilities are added, removed or modified
            - subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest


**Description**
            List all subscriptions

        **Arguments**
            - None

        **Success Return Value**
            A JSON object representing the list of subscriptions.


def list_runtime(self, scope="<STR_LIT>", skip_policy_evaluation=True, start_time=None, end_time=None):

containers = {<EOL>'<STR_LIT>': scope,<EOL>'<STR_LIT>': skip_policy_evaluation<EOL>}<EOL>if start_time or end_time:<EOL><INDENT>containers['<STR_LIT:time>'] = {}<EOL>containers['<STR_LIT:time>']['<STR_LIT>'] = int(start_time * <NUM_LIT>) if start_time else <NUM_LIT:0><EOL>end_time = end_time if end_time else time.time()<EOL>containers['<STR_LIT:time>']['<STR_LIT:to>'] = int(end_time * <NUM_LIT>)<EOL><DEDENT>url = self.url + '<STR_LIT>'<EOL>data = json.dumps(containers)<EOL>res = requests.post(url, headers=self.hdrs, data=data, verify=self.ssl_verify)<EOL>if not self._checkResponse(res):<EOL><INDENT>return [False, self.lasterr]<EOL><DEDENT>return [True, res.json()]<EOL>

**Description**
            List runtime containers

        **Arguments**
            - scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: 'host.domain = "example.com" and container.image != "alpine:latest"')
            - skip_policy_evaluation: If true, no policy evaluations will be triggered for the images.
            - start_time: Start of the time range (integer of unix time).
            - end_time: End of the time range (integer of unix time).

        **Success Return Value**
            A JSON object representing the list of runtime containers.


def send_email(self, to, kind, **kwargs):

return __send_email__(self.template_prefix, to, kind, **kwargs)<EOL>

Sends an e-mail to the given address.

        to: The address
        kind: the ID for an e-mail kind; it should point to a subdirectory of
            self.template_prefix containing subject.txt and message.html, which
            are django templates for the subject and HTML message respectively.

        context: a context for rendering the e-mail.


length = <NUM_LIT:6><EOL>chars = string.uppercase + string.digits[<NUM_LIT:1>:]<EOL>return get_random_string(length=length, allowed_chars=chars)<EOL>

Generates an access code for users' payments as well as their
    fulfilment code for check-in.
    The access code will 4 characters long, which allows for 1,500,625
    unique codes, which really should be enough for anyone.


ntcls.__new__.__defaults__ = (<EOL>(None,) * len(ntcls._fields)<EOL>)<EOL>return ntcls<EOL>

Takes a namedtuple derivative and makes all of the arguments optional.


NOT_EVALUATED = object()<EOL>retval = [NOT_EVALUATED]<EOL>def evaluate():<EOL><INDENT>if retval[<NUM_LIT:0>] is NOT_EVALUATED:<EOL><INDENT>retval[<NUM_LIT:0>] = function(*args, **kwargs)<EOL><DEDENT>return retval[<NUM_LIT:0>]<EOL><DEDENT>return evaluate<EOL>

Produces a callable so that functions can be lazily evaluated in
    templates.

    Arguments:

        function (callable): The function to call at evaluation time.

        args: Positional arguments, passed directly to ``function``.

        kwargs: Keyword arguments, passed directly to ``function``.

    Return:

        callable: A callable that will evaluate a call to ``function`` with
            the specified arguments.


dot = name.rindex("<STR_LIT:.>")<EOL>mod_name, property_name = name[:dot], name[dot + <NUM_LIT:1>:]<EOL>__import__(mod_name)<EOL>return getattr(sys.modules[mod_name], property_name)<EOL>

Returns the named object.

    Arguments:
        name (str): A string of form `package.subpackage.etc.module.property`.
            This function will import `package.subpackage.etc.module` and
            return `property` from that module.


out = []<EOL>try:<EOL><INDENT>discount_effects = obj.voucherdiscount.effects()<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>discount_effects = None<EOL><DEDENT>try:<EOL><INDENT>enabling_effects = obj.voucherflag.effects()<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>enabling_effects = None<EOL><DEDENT>if discount_effects:<EOL><INDENT>out.append("<STR_LIT>" + str(list(discount_effects)))<EOL><DEDENT>if enabling_effects:<EOL><INDENT>out.append("<STR_LIT>" + str(list(enabling_effects)))<EOL><DEDENT>return "<STR_LIT:\n>".join(out)<EOL>

List the effects of the voucher in the admin.


def set_quantity(self, product, quantity, batched=False):

self.set_quantities(((product, quantity),))<EOL>

Sets the _quantity_ of the given _product_ in the cart to the given
        _quantity_.


def add_to_cart(self, product, quantity):

try:<EOL><INDENT>product_item = commerce.ProductItem.objects.get(<EOL>cart=self.cart,<EOL>product=product)<EOL>old_quantity = product_item.quantity<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>old_quantity = <NUM_LIT:0><EOL><DEDENT>self.set_quantity(product, old_quantity + quantity)<EOL>

Adds _quantity_ of the given _product_ to the cart. Raises
        ValidationError if constraints are violated.


def pay(self, reference, amount, pre_validate=True):

Testing method for simulating an invoice paymenht by the given
        amount.


Creates two proposals:

        - User 1 will be presenter
        - User 2 will be an additional presenter

        Each proposal is of a different ProposalKind.


Adds flag -- PROD_1 is not available unless user is a primary
        presenter of a KIND_1


Adds flag -- PROD_1 is not available unless user is a primary
        presenter of a KIND_2


flag = conditions.ProductFlag.objects.create(<EOL>description="<STR_LIT>",<EOL>condition=condition,<EOL>)<EOL>flag.products.add(cls.PROD_1)<EOL>flag.enabling_products.add(cls.PROD_2)<EOL>

Adds a product flag condition: adding PROD_1 to a cart is
        predicated on adding PROD_2 beforehand.


flag = conditions.ProductFlag.objects.create(<EOL>description="<STR_LIT>",<EOL>condition=condition,<EOL>)<EOL>flag.categories.add(cls.CAT_1)<EOL>flag.enabling_products.add(cls.PROD_3)<EOL>

Adds a product flag condition that operates on a category:
        adding an item from CAT_1 is predicated on adding PROD_3 beforehand


flag = conditions.CategoryFlag.objects.create(<EOL>description="<STR_LIT>",<EOL>condition=condition,<EOL>enabling_category=cls.CAT_2,<EOL>)<EOL>flag.products.add(cls.PROD_1)<EOL>

Adds a category flag condition: adding PROD_1 to a cart is
        predicated on adding an item from CAT_2 beforehand.


groups = []<EOL>products = [cls.PROD_1, cls.PROD_2]<EOL>for i, product in enumerate(products):<EOL><INDENT>group = Group.objects.create(name="<STR_LIT>" + str(i))<EOL>flag = conditions.GroupMemberFlag.objects.create(<EOL>description="<STR_LIT>" + str(i),<EOL>condition=conditions.FlagBase.ENABLE_IF_TRUE,<EOL>)<EOL>flag.group.add(group)<EOL>flag.products.add(product)<EOL>groups.append(group)<EOL><DEDENT>cls.GROUP_1 = groups[<NUM_LIT:0>]<EOL>cls.GROUP_2 = groups[<NUM_LIT:1>]<EOL>

Creates cls.GROUP_1, and restricts cls.PROD_1 only to users who are
        members of the group. Likewise GROUP_2 and PROD_2


<EOL>def _report(view):<EOL><INDENT>report_view = ReportView(view, title, form_type)<EOL>report_view = user_passes_test(views._staff_only)(report_view)<EOL>report_view = wraps(view)(report_view)<EOL>_all_report_views.append(report_view)<EOL>return report_view<EOL><DEDENT>return _report<EOL>

Decorator that converts a report view function into something that
    displays a Report.

    Arguments:
        title (str):
            The title of the report.
        form_type (Optional[forms.Form]):
            A form class that can make this report display things. If not
            supplied, no form will be displayed.


return list(_all_report_views)<EOL>

Returns all the views that have been registered with @report


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Arguments:
    content_type (str): The content-type for the output format of this
    report.

Returns:
    An iterator, which yields each row of the data. Each row should
    be an iterable containing the cells, rendered appropriately for
    content_type.


def _linked_text(self, content_type, address, text):

if content_type == "<STR_LIT>":<EOL><INDENT>return Report._html_link(address, text)<EOL><DEDENT>else:<EOL><INDENT>return text<EOL><DEDENT>

Returns:
    an HTML linked version of text, if the content_type for this report
    is HTMLish, otherwise, the text.


return self._title<EOL>


return self._headings<EOL>


for row in self._data:<EOL><INDENT>yield [<EOL>self.cell_text(content_type, i, cell)<EOL>for i, cell in enumerate(row)<EOL>]<EOL><DEDENT>


self._title = title<EOL>self._links = links<EOL>

Arguments:
    links ([tuple, ...]): a list of 2-tuples:
        (url, link_text)


def __init__(self, inner_view, title, form_type):

<EOL>self.inner_view = inner_view<EOL>self.title = title<EOL>self.form_type = form_type<EOL>

Arguments:
    inner_view: Callable that returns either a Report or a sequence of
        Report objects.

    title: The title that appears at the top of all of the reports.

    form_type: A Form class that can be used to query the report.


<EOL>if self.form_type is not None:<EOL><INDENT>form = self.form_type(request.GET)<EOL>form.is_valid()<EOL><DEDENT>else:<EOL><INDENT>form = None<EOL><DEDENT>return form<EOL>

Creates an instance of self.form_type using request.GET


@classmethod<EOL><INDENT>def wrap_reports(cls, reports, content_type):<DEDENT>

reports = [<EOL>_ReportTemplateWrapper(content_type, report)<EOL>for report in reports<EOL>]<EOL>return reports<EOL>

Wraps the reports in a _ReportTemplateWrapper for the given
        content_type -- this allows data to be returned as HTML links, for
        instance.


renderers = {<EOL>"<STR_LIT>": self._render_as_csv,<EOL>"<STR_LIT>": self._render_as_html,<EOL>None: self._render_as_html,<EOL>}<EOL>render = renderers[data.content_type]<EOL>return render(data)<EOL>

Renders the reports based on data.content_type's value.

        Arguments:
            data (ReportViewRequestData): The report data. data.content_type
                is used to determine how the reports are rendered.

        Returns:
            HTTPResponse: The rendered version of the report.


return [<EOL>sales_payment_summary(),<EOL>items_sold(),<EOL>payments(),<EOL>credit_note_refunds(),<EOL>]<EOL>

Shows the summary of sales, and the full history of payments and
    refunds into the system.


data = None<EOL>headings = None<EOL>line_items = commerce.LineItem.objects.filter(<EOL>invoice__status=commerce.Invoice.STATUS_PAID,<EOL>).select_related("<STR_LIT>")<EOL>line_items = line_items.order_by(<EOL>"<STR_LIT>", "<STR_LIT:description>",<EOL>).values(<EOL>"<STR_LIT>", "<STR_LIT:description>",<EOL>).annotate(<EOL>total_quantity=Sum("<STR_LIT>"),<EOL>)<EOL>headings = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>data = []<EOL>total_income = <NUM_LIT:0><EOL>for line in line_items:<EOL><INDENT>cost = line["<STR_LIT>"] * line["<STR_LIT>"]<EOL>data.append([<EOL>line["<STR_LIT:description>"], line["<STR_LIT>"],<EOL>line["<STR_LIT>"], cost,<EOL>])<EOL>total_income += cost<EOL><DEDENT>data.append([<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", total_income,<EOL>])<EOL>return ListReport("<STR_LIT>", headings, data)<EOL>

Summarises the items sold and discounts granted for a given set of
    products, or products from categories.


def value_or_zero(aggregate, key):<EOL><INDENT>return aggregate[key] or <NUM_LIT:0><EOL><DEDENT>def sum_amount(payment_set):<EOL><INDENT>a = payment_set.values("<STR_LIT>").aggregate(total=Sum("<STR_LIT>"))<EOL>return value_or_zero(a, "<STR_LIT>")<EOL><DEDENT>headings = ["<STR_LIT>", "<STR_LIT>"]<EOL>data = []<EOL>sales = commerce.LineItem.objects.filter(<EOL>invoice__status=commerce.Invoice.STATUS_PAID,<EOL>).values(<EOL>"<STR_LIT>", "<STR_LIT>"<EOL>).aggregate(<EOL>total=Sum(F("<STR_LIT>") * F("<STR_LIT>"), output_field=CURRENCY()),<EOL>)<EOL>sales = value_or_zero(sales, "<STR_LIT>")<EOL>all_payments = sum_amount(commerce.PaymentBase.objects.all())<EOL>all_credit_notes = <NUM_LIT:0> - sum_amount(commerce.CreditNote.objects.all())<EOL>unclaimed_credit_notes = <NUM_LIT:0> - sum_amount(commerce.CreditNote.unclaimed())<EOL>claimed_credit_notes = sum_amount(<EOL>commerce.CreditNoteApplication.objects.all()<EOL>)<EOL>refunded_credit_notes = <NUM_LIT:0> - sum_amount(commerce.CreditNote.refunded())<EOL>data.append(["<STR_LIT>", sales])<EOL>data.append(["<STR_LIT>", all_payments])<EOL>data.append(["<STR_LIT>", sales - all_payments])<EOL>data.append(["<STR_LIT>", all_credit_notes])<EOL>data.append(["<STR_LIT>", claimed_credit_notes])<EOL>data.append(["<STR_LIT>", refunded_credit_notes])<EOL>data.append(["<STR_LIT>", unclaimed_credit_notes])<EOL>data.append([<EOL>"<STR_LIT>",<EOL>all_credit_notes - claimed_credit_notes -<EOL>refunded_credit_notes - unclaimed_credit_notes<EOL>])<EOL>return ListReport("<STR_LIT>", headings, data)<EOL>


payments = commerce.PaymentBase.objects.all()<EOL>return QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>"],<EOL>payments,<EOL>link_view=views.invoice,<EOL>)<EOL>

Shows the history of payments into the system


notes_refunded = commerce.CreditNote.refunded()<EOL>return QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>"],<EOL>notes_refunded,<EOL>link_view=views.credit_note,<EOL>)<EOL>

Shows all of the credit notes that have been generated.


@report_view("<STR_LIT>", form_type=forms.ProductAndCategoryForm)<EOL>def product_status(request, form):

products = form.cleaned_data["<STR_LIT>"]<EOL>categories = form.cleaned_data["<STR_LIT>"]<EOL>items = commerce.ProductItem.objects.filter(<EOL>Q(product__in=products) | Q(product__category__in=categories),<EOL>).select_related("<STR_LIT>", "<STR_LIT>")<EOL>items = group_by_cart_status(<EOL>items,<EOL>["<STR_LIT>", "<STR_LIT>"],<EOL>["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>)<EOL>headings = [<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>]<EOL>data = []<EOL>for item in items:<EOL><INDENT>data.append([<EOL>"<STR_LIT>" % (<EOL>item["<STR_LIT>"], item["<STR_LIT>"]<EOL>),<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>])<EOL><DEDENT>return ListReport("<STR_LIT>", headings, data)<EOL>

Summarises the inventory status of the given items, grouping by
    invoice status.


@report_view("<STR_LIT>", form_type=forms.DiscountForm)<EOL>def discount_status(request, form):

discounts = form.cleaned_data["<STR_LIT>"]<EOL>items = commerce.DiscountItem.objects.filter(<EOL>Q(discount__in=discounts),<EOL>).select_related("<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>items = group_by_cart_status(<EOL>items,<EOL>["<STR_LIT>"],<EOL>["<STR_LIT>", "<STR_LIT>"],<EOL>)<EOL>headings = [<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>]<EOL>data = []<EOL>for item in items:<EOL><INDENT>data.append([<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>item["<STR_LIT>"],<EOL>])<EOL><DEDENT>return ListReport("<STR_LIT>", headings, data)<EOL>

Summarises the usage of a given discount.


@report_view("<STR_LIT>", form_type=forms.ProductAndCategoryForm)<EOL>def product_line_items(request, form):

products = form.cleaned_data["<STR_LIT>"]<EOL>categories = form.cleaned_data["<STR_LIT>"]<EOL>invoices = commerce.Invoice.objects.filter(<EOL>(<EOL>Q(lineitem__product__in=products) |<EOL>Q(lineitem__product__category__in=categories)<EOL>),<EOL>status=commerce.Invoice.STATUS_PAID,<EOL>).select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT:user>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>).order_by("<STR_LIT>")<EOL>headings = [<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'<EOL>]<EOL>data = []<EOL>for invoice in invoices:<EOL><INDENT>for item in invoice.cart.productitem_set.all():<EOL><INDENT>if item.product in products or item.product.category in categories:<EOL><INDENT>output = []<EOL>output.append(invoice.id)<EOL>output.append(invoice.issue_time.strftime('<STR_LIT>'))<EOL>output.append(<EOL>invoice.user.attendee.attendeeprofilebase.attendee_name()<EOL>)<EOL>output.append(item.quantity)<EOL>output.append(item.product)<EOL>cart = invoice.cart<EOL>if cart.status == commerce.Cart.STATUS_PAID:<EOL><INDENT>output.append('<STR_LIT>')<EOL><DEDENT>elif cart.status == commerce.Cart.STATUS_ACTIVE:<EOL><INDENT>output.append('<STR_LIT>')<EOL><DEDENT>elif cart.status == commerce.Cart.STATUS_RELEASED:<EOL><INDENT>output.append('<STR_LIT>')<EOL><DEDENT>data.append(output)<EOL><DEDENT><DEDENT><DEDENT>return ListReport("<STR_LIT>", headings, data)<EOL>

Shows each product line item from invoices, including their date and
    purchashing customer.


@report_view("<STR_LIT>", form_type=forms.ProductAndCategoryForm)<EOL>def paid_invoices_by_date(request, form):

products = form.cleaned_data["<STR_LIT>"]<EOL>categories = form.cleaned_data["<STR_LIT>"]<EOL>invoices = commerce.Invoice.objects.filter(<EOL>(<EOL>Q(lineitem__product__in=products) |<EOL>Q(lineitem__product__category__in=categories)<EOL>),<EOL>status=commerce.Invoice.STATUS_PAID,<EOL>)<EOL>payments = commerce.PaymentBase.objects.all()<EOL>payments = payments.filter(<EOL>invoice__in=invoices,<EOL>)<EOL>payments = payments.order_by("<STR_LIT>")<EOL>invoice_max_time = payments.values("<STR_LIT>").annotate(<EOL>max_time=Max("<STR_LIT:time>")<EOL>)<EOL>zero_value_invoices = invoices.filter(value=<NUM_LIT:0>)<EOL>times = itertools.chain(<EOL>(line["<STR_LIT>"] for line in invoice_max_time),<EOL>(invoice.issue_time for invoice in zero_value_invoices),<EOL>)<EOL>by_date = collections.defaultdict(int)<EOL>for time in times:<EOL><INDENT>date = datetime.datetime(<EOL>year=time.year, month=time.month, day=time.day<EOL>)<EOL>by_date[date] += <NUM_LIT:1><EOL><DEDENT>data = [(date_, count) for date_, count in sorted(by_date.items())]<EOL>data = [(date_.strftime("<STR_LIT>"), count) for date_, count in data]<EOL>return ListReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:date>", "<STR_LIT:count>"],<EOL>data,<EOL>)<EOL>

Shows the number of paid invoices containing given products or
    categories per day.


notes = commerce.CreditNote.objects.all().select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>return QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT:status>", "<STR_LIT:value>"],<EOL>notes,<EOL>headings=["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>link_view=views.credit_note,<EOL>)<EOL>

Shows all of the credit notes in the system.


invoices = commerce.Invoice.objects.all().order_by("<STR_LIT:status>", "<STR_LIT:id>")<EOL>return QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT:value>", "<STR_LIT>"],<EOL>invoices,<EOL>headings=["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>link_view=views.invoice,<EOL>)<EOL>

Shows all of the invoices in the system.


@report_view("<STR_LIT>", form_type=forms.UserIdForm)<EOL>def attendee(request, form, user_id=None):

if user_id is None and form.cleaned_data["<STR_LIT:user>"] is not None:<EOL><INDENT>user_id = form.cleaned_data["<STR_LIT:user>"]<EOL><DEDENT>if user_id is None:<EOL><INDENT>return attendee_list(request)<EOL><DEDENT>attendee = people.Attendee.objects.get(user__id=user_id)<EOL>name = attendee.attendeeprofilebase.attendee_name()<EOL>reports = []<EOL>profile_data = []<EOL>try:<EOL><INDENT>profile = people.AttendeeProfileBase.objects.get_subclass(<EOL>attendee=attendee<EOL>)<EOL>fields = profile._meta.get_fields()<EOL><DEDENT>except people.AttendeeProfileBase.DoesNotExist:<EOL><INDENT>fields = []<EOL><DEDENT>exclude = set(["<STR_LIT>", "<STR_LIT:id>"])<EOL>for field in fields:<EOL><INDENT>if field.name in exclude:<EOL><INDENT>continue<EOL><DEDENT>if not hasattr(field, "<STR_LIT>"):<EOL><INDENT>continue  <EOL><DEDENT>value = getattr(profile, field.name)<EOL>if isinstance(field, models.ManyToManyField):<EOL><INDENT>value = "<STR_LIT:U+002CU+0020>".join(str(i) for i in value.all())<EOL><DEDENT>profile_data.append((field.verbose_name, value))<EOL><DEDENT>cart = CartController.for_user(attendee.user)<EOL>reservation = cart.cart.reservation_duration + cart.cart.time_last_updated<EOL>profile_data.append(("<STR_LIT>", reservation))<EOL>reports.append(ListReport("<STR_LIT>", ["<STR_LIT>", "<STR_LIT>"], profile_data))<EOL>links = []<EOL>links.append((<EOL>reverse(views.badge, args=[user_id]),<EOL>"<STR_LIT>",<EOL>))<EOL>links.append((<EOL>reverse(views.amend_registration, args=[user_id]),<EOL>"<STR_LIT>",<EOL>))<EOL>links.append((<EOL>reverse(views.extend_reservation, args=[user_id]),<EOL>"<STR_LIT>",<EOL>))<EOL>reports.append(Links("<STR_LIT>" + name, links))<EOL>ic = ItemController(attendee.user)<EOL>reports.append(ListReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT>"],<EOL>[(pq.product, pq.quantity) for pq in ic.items_purchased()],<EOL>))<EOL>reports.append(ListReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT>"],<EOL>[(pq.product, pq.quantity) for pq in ic.items_pending()],<EOL>))<EOL>invoices = commerce.Invoice.objects.filter(<EOL>user=attendee.user,<EOL>)<EOL>reports.append(QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT:value>"],<EOL>invoices,<EOL>headings=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>link_view=views.invoice,<EOL>))<EOL>credit_notes = commerce.CreditNote.objects.filter(<EOL>invoice__user=attendee.user,<EOL>).select_related("<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>reports.append(QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>", "<STR_LIT:status>", "<STR_LIT:value>"],<EOL>credit_notes,<EOL>link_view=views.credit_note,<EOL>))<EOL>payments = commerce.PaymentBase.objects.filter(<EOL>invoice__user=attendee.user,<EOL>).select_related("<STR_LIT>")<EOL>reports.append(QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>"],<EOL>payments,<EOL>link_view=views.invoice,<EOL>))<EOL>return reports<EOL>

Returns a list of all manifested attendees if no attendee is specified,
    else displays the attendee manifest.


attendees = people.Attendee.objects.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT:user>",<EOL>)<EOL>profiles = AttendeeProfile.objects.filter(<EOL>attendee__in=attendees<EOL>).select_related(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>)<EOL>profiles_by_attendee = dict((i.attendee, i) for i in profiles)<EOL>attendees = attendees.annotate(<EOL>has_registered=Count(<EOL>Q(user__invoice__status=commerce.Invoice.STATUS_PAID)<EOL>),<EOL>)<EOL>headings = [<EOL>"<STR_LIT>", "<STR_LIT:Name>", "<STR_LIT>", "<STR_LIT>",<EOL>]<EOL>data = []<EOL>for a in attendees:<EOL><INDENT>data.append([<EOL>a.user.id,<EOL>(profiles_by_attendee[a].attendee_name()<EOL>if a in profiles_by_attendee else "<STR_LIT>"),<EOL>a.user.email,<EOL>a.has_registered > <NUM_LIT:0>,<EOL>])<EOL><DEDENT>data.sort(key=lambda a: (-a[<NUM_LIT:3>], a[<NUM_LIT:0>]))<EOL>return AttendeeListReport("<STR_LIT>", headings, data, link_view=attendee)<EOL>


@report_view(<EOL>"<STR_LIT>",<EOL>form_type=forms.mix_form(<EOL>forms.ProductAndCategoryForm, ProfileForm, forms.GroupByForm<EOL>),<EOL>)<EOL>def attendee_data(request, form, user_id=None):

status_display = {<EOL>commerce.Cart.STATUS_ACTIVE: "<STR_LIT>",<EOL>commerce.Cart.STATUS_PAID: "<STR_LIT>",<EOL>commerce.Cart.STATUS_RELEASED: "<STR_LIT>",<EOL>}<EOL>output = []<EOL>by_category = (<EOL>form.cleaned_data["<STR_LIT>"] == forms.GroupByForm.GROUP_BY_CATEGORY)<EOL>products = form.cleaned_data["<STR_LIT>"]<EOL>categories = form.cleaned_data["<STR_LIT>"]<EOL>fields = form.cleaned_data["<STR_LIT>"]<EOL>name_field = AttendeeProfile.name_field()<EOL>items = commerce.ProductItem.objects.filter(<EOL>Q(product__in=products) | Q(product__category__in=categories),<EOL>).exclude(<EOL>cart__status=commerce.Cart.STATUS_RELEASED<EOL>).select_related(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>).order_by("<STR_LIT>")<EOL>links = []<EOL>invoice_mailout = reverse(views.invoice_mailout, args=[])<EOL>invoice_mailout += "<STR_LIT:?>" + request.META["<STR_LIT>"]<EOL>links += [<EOL>(invoice_mailout + "<STR_LIT>", "<STR_LIT>",),<EOL>(invoice_mailout + "<STR_LIT>", "<STR_LIT>",),<EOL>]<EOL>if items.count() > <NUM_LIT:0>:<EOL><INDENT>output.append(Links("<STR_LIT>", links))<EOL><DEDENT>related_fields = set(<EOL>field for field in fields<EOL>if isinstance(AttendeeProfile._meta.get_field(field), RelatedField)<EOL>)<EOL>profiles = AttendeeProfile.objects.filter(<EOL>attendee__user__cart__productitem__in=items<EOL>).select_related("<STR_LIT>").prefetch_related(*related_fields)<EOL>by_user = {}<EOL>for profile in profiles:<EOL><INDENT>by_user[profile.attendee.user] = profile<EOL><DEDENT>cart = "<STR_LIT>"<EOL>cart_status = cart + "<STR_LIT>"  <EOL>product = cart + "<STR_LIT>"<EOL>product_name = product + "<STR_LIT>"<EOL>category = product + "<STR_LIT>"<EOL>category_name = category + "<STR_LIT>"<EOL>if by_category:<EOL><INDENT>grouping_fields = (category, category_name)<EOL>order_by = (category, )<EOL>first_column = "<STR_LIT>"<EOL>group_name = lambda i: "<STR_LIT:%s>" % (i[category_name], )  <EOL><DEDENT>else:<EOL><INDENT>grouping_fields = (product, product_name, category_name)<EOL>order_by = (category, )<EOL>first_column = "<STR_LIT>"<EOL>group_name = lambda i: "<STR_LIT>" % (i[category_name], i[product_name])  <EOL><DEDENT>for field in fields:<EOL><INDENT>concrete_field = AttendeeProfile._meta.get_field(field)<EOL>field_verbose = concrete_field.verbose_name<EOL>if field in related_fields:<EOL><INDENT>all_ids = profiles.order_by(field).values(field)<EOL>all_ids = [i[field] for i in all_ids if i[field] is not None]<EOL>model = concrete_field.related_model<EOL>all_objects = model.objects.filter(id__in=all_ids)<EOL>all_objects_by_id = dict((i.id, i) for i in all_objects)<EOL>def display_field(value):<EOL><INDENT>if value in all_objects_by_id:<EOL><INDENT>return all_objects_by_id[value]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>def display_field(value):<EOL><INDENT>return value<EOL><DEDENT><DEDENT>status_count = lambda status: Case(When(  <EOL>attendee__user__cart__status=status,<EOL>then=Value(<NUM_LIT:1>),<EOL>),<EOL>default=Value(<NUM_LIT:0>),<EOL>output_field=models.fields.IntegerField(),<EOL>)<EOL>paid_count = status_count(commerce.Cart.STATUS_PAID)<EOL>unpaid_count = status_count(commerce.Cart.STATUS_ACTIVE)<EOL>groups = profiles.order_by(<EOL>*(order_by + (field, ))<EOL>).values(<EOL>*(grouping_fields + (field, ))<EOL>).annotate(<EOL>paid_count=Sum(paid_count),<EOL>unpaid_count=Sum(unpaid_count),<EOL>)<EOL>output.append(ListReport(<EOL>"<STR_LIT>" % field_verbose,<EOL>[first_column, field_verbose, "<STR_LIT>", "<STR_LIT>"],<EOL>[<EOL>(<EOL>group_name(group),<EOL>display_field(group[field]),<EOL>group["<STR_LIT>"] or <NUM_LIT:0>,<EOL>group["<STR_LIT>"] or <NUM_LIT:0>,<EOL>)<EOL>for group in groups<EOL>],<EOL>))<EOL><DEDENT>field_names = [<EOL>AttendeeProfile._meta.get_field(field).verbose_name for field in fields<EOL>]<EOL>def display_field(profile, field):<EOL><INDENT>field_type = AttendeeProfile._meta.get_field(field)<EOL>attr = getattr(profile, field)<EOL>if isinstance(field_type, models.ManyToManyField):<EOL><INDENT>return [str(i) for i in attr.all()] or "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return attr<EOL><DEDENT><DEDENT>headings = ["<STR_LIT>", "<STR_LIT:Name>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>headings.extend(field_names)<EOL>data = []<EOL>for item in items:<EOL><INDENT>profile = by_user[item.cart.user]<EOL>line = [<EOL>item.cart.user.id,<EOL>getattr(profile, name_field),<EOL>profile.attendee.user.email,<EOL>item.product,<EOL>status_display[item.cart.status],<EOL>] + [<EOL>display_field(profile, field) for field in fields<EOL>]<EOL>data.append(line)<EOL><DEDENT>output.append(AttendeeListReport(<EOL>"<STR_LIT>", headings, data,<EOL>link_view=attendee<EOL>))<EOL>return output<EOL>

Lists attendees for a given product/category selection along with
    profile data.


kinds = form.cleaned_data["<STR_LIT>"]<EOL>presentations = schedule_models.Presentation.objects.filter(<EOL>proposal_base__kind__in=kinds,<EOL>).exclude(<EOL>cancelled=True,<EOL>)<EOL>users = User.objects.filter(<EOL>Q(speaker_profile__presentations__in=presentations) |<EOL>Q(speaker_profile__copresentations__in=presentations)<EOL>)<EOL>paid_carts = commerce.Cart.objects.filter(status=commerce.Cart.STATUS_PAID)<EOL>paid_carts = Case(<EOL>When(cart__in=paid_carts, then=Value(<NUM_LIT:1>)),<EOL>default=Value(<NUM_LIT:0>),<EOL>output_field=models.IntegerField(),<EOL>)<EOL>users = users.annotate(paid_carts=Sum(paid_carts))<EOL>users = users.order_by("<STR_LIT>")<EOL>return QuerysetReport(<EOL>"<STR_LIT>",<EOL>["<STR_LIT:id>", "<STR_LIT>", "<STR_LIT:email>", "<STR_LIT>"],<EOL>users,<EOL>link_view=attendee,<EOL>)<EOL>return []<EOL>

Shows registration status for speakers with a given proposal kind.


products = form.cleaned_data["<STR_LIT>"]<EOL>categories = form.cleaned_data["<STR_LIT>"]<EOL>line_items = (<EOL>Q(lineitem__product__in=products) |<EOL>Q(lineitem__product__category__in=categories)<EOL>)<EOL>invoices = commerce.Invoice.objects.filter(<EOL>line_items,<EOL>status=commerce.Invoice.STATUS_PAID,<EOL>).select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT:user>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>)<EOL>users = set(i.user for i in invoices)<EOL>carts = commerce.Cart.objects.filter(<EOL>user__in=users<EOL>)<EOL>items = commerce.ProductItem.objects.filter(<EOL>cart__in=carts<EOL>).select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>).order_by("<STR_LIT>", "<STR_LIT>")<EOL>users = {}<EOL>for item in items:<EOL><INDENT>cart = item.cart<EOL>if cart.user not in users:<EOL><INDENT>users[cart.user] = {"<STR_LIT>": [], "<STR_LIT>": [], "<STR_LIT>": []}<EOL><DEDENT>items = users[cart.user]<EOL>if cart.status == commerce.Cart.STATUS_ACTIVE:<EOL><INDENT>items["<STR_LIT>"].append(item)<EOL><DEDENT>elif cart.status == commerce.Cart.STATUS_PAID:<EOL><INDENT>items["<STR_LIT>"].append(item)<EOL><DEDENT>elif cart.status == commerce.Cart.STATUS_RELEASED:<EOL><INDENT>items["<STR_LIT>"].append(item)<EOL><DEDENT><DEDENT>users_by_name = list(users.keys())<EOL>users_by_name.sort(key=(<EOL>lambda i: i.attendee.attendeeprofilebase.attendee_name().lower()<EOL>))<EOL>headings = ["<STR_LIT>", "<STR_LIT:Name>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>def format_items(item_list):<EOL><INDENT>strings = [<EOL>'<STR_LIT>' % (item.quantity, str(item.product))<EOL>for item in item_list<EOL>]<EOL>return "<STR_LIT>".join(strings)<EOL><DEDENT>output = []<EOL>for user in users_by_name:<EOL><INDENT>items = users[user]<EOL>output.append([<EOL>user.id,<EOL>user.attendee.attendeeprofilebase.attendee_name(),<EOL>format_items(items["<STR_LIT>"]),<EOL>format_items(items["<STR_LIT>"]),<EOL>format_items(items["<STR_LIT>"]),<EOL>])<EOL><DEDENT>return ListReport("<STR_LIT>", headings, output)<EOL>

Produces the registration manifest for people with the given product
type.


bases = tuple(a)<EOL>return type("<STR_LIT>", bases, {})<EOL>

Creates a new form class out of all the supplied forms


fields = model._meta.get_fields()<EOL>choices = []<EOL>for field in fields:<EOL><INDENT>if hasattr(field, "<STR_LIT>"):<EOL><INDENT>choices.append((field.name, field.verbose_name))<EOL><DEDENT><DEDENT>class ModelFieldsForm(forms.Form):<EOL><INDENT>fields = forms.MultipleChoiceField(<EOL>choices=choices,<EOL>required=False,<EOL>)<EOL><DEDENT>return ModelFieldsForm<EOL>

Creates a form for specifying fields from a model to display.


try:<EOL><INDENT>return context["<STR_LIT:user>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>return context.request.user<EOL><DEDENT>

Returns either context.user or context.request.user if the former is
    not defined.


return CategoryController.available_categories(user_for_context(context))<EOL>

Gets all of the currently available products.

    Returns:
        [models.inventory.Category, ...]: A list of all of the categories that
            have Products that the current user can reserve.


user = user_for_context(context)<EOL>categories_available = set(CategoryController.available_categories(user))<EOL>items = ItemController(user).items_pending_or_purchased()<EOL>categories_held = set()<EOL>for product, quantity in items:<EOL><INDENT>categories_held.add(product.category)<EOL><DEDENT>return categories_available - categories_held<EOL>

Adds the categories that the user does not currently have.


notes = commerce.CreditNote.unclaimed().filter(<EOL>invoice__user=user_for_context(context),<EOL>)<EOL>ret = notes.values("<STR_LIT>").aggregate(Sum("<STR_LIT>"))["<STR_LIT>"] or <NUM_LIT:0><EOL>return <NUM_LIT:0> - ret<EOL>

Calculates the sum of unclaimed credit from this user's credit notes.

    Returns:
        Decimal: the sum of the values of unclaimed credit notes for the
            current user.


return commerce.Invoice.objects.filter(user=user_for_context(context))<EOL>

Returns:
    [models.commerce.Invoice, ...]: All of the current user's invoices.


return ItemController(user_for_context(context)).items_pending()<EOL>

Gets all of the items that the user from this context has reserved.

    The user will be either `context.user`, and `context.request.user` if
    the former is not defined.


return ItemController(user_for_context(context)).items_purchased(<EOL>category=category<EOL>)<EOL>

Returns the items purchased for this user.

    The user will be either `context.user`, and `context.request.user` if
    the former is not defined.


return sum(i.quantity for i in items_purchased(context, category))<EOL>

Returns the number of items purchased for this user (sum of quantities).

    The user will be either `context.user`, and `context.request.user` if
    the former is not defined.


user = user_for_context(context)<EOL>if hasattr(user, "<STR_LIT>") and user.attendee.completed_registration:<EOL><INDENT>return None<EOL><DEDENT>ticket_category = settings.TICKET_PRODUCT_CATEGORY<EOL>categories = available_categories(context)<EOL>return ticket_category not in [cat.id for cat in categories]<EOL>

If the current user is unregistered, returns True if there are no
    products in the TICKET_PRODUCT_CATEGORY that are available to that user.

    If there *are* products available, the return False.

    If the current user *is* registered, then return None (it's not a
    pertinent question for people who already have a ticket).


try:<EOL><INDENT>tag_name, template_name = token.split_contents()<EOL><DEDENT>except ValueError:<EOL><INDENT>raise template.TemplateSyntaxError("<STR_LIT>" % token.contents.split()[<NUM_LIT:0>])<EOL><DEDENT>return IncludeNode(template_name)<EOL>

Usage: {% include_if_exists "head.html" %}

    This will fail silently if the template doesn't exist. If it does, it will
    be rendered with the current context.

    From: https://djangosnippets.org/snippets/2058/


return str(arg1) + str(arg2)<EOL>


PAGE_PROFILE = <NUM_LIT:1><EOL>PAGE_TICKET = <NUM_LIT:2><EOL>PAGE_PRODUCTS = <NUM_LIT:3><EOL>PAGE_PRODUCTS_MAX = <NUM_LIT:4><EOL>TOTAL_PAGES = <NUM_LIT:4><EOL>ticket_category = inventory.Category.objects.get(<EOL>id=settings.TICKET_PRODUCT_CATEGORY<EOL>)<EOL>cart = CartController.for_user(request.user)<EOL>attendee = people.Attendee.get_instance(request.user)<EOL>if attendee.completed_registration:<EOL><INDENT>return redirect(review)<EOL><DEDENT>has_profile = hasattr(attendee, "<STR_LIT>")<EOL>if not has_profile:<EOL><INDENT>max_page = PAGE_PROFILE<EOL>redirect_page = PAGE_PROFILE<EOL><DEDENT>else:<EOL><INDENT>products = inventory.Product.objects.filter(<EOL>productitem__cart=cart.cart<EOL>)<EOL>products = products.filter(category=ticket_category)<EOL>if products.count() == <NUM_LIT:0>:<EOL><INDENT>max_page = PAGE_TICKET<EOL>redirect_page = PAGE_TICKET<EOL><DEDENT>else:<EOL><INDENT>max_page = PAGE_PRODUCTS_MAX<EOL>redirect_page = PAGE_PRODUCTS<EOL><DEDENT><DEDENT>if page_number is None or int(page_number) > max_page:<EOL><INDENT>return redirect("<STR_LIT>", redirect_page)<EOL><DEDENT>page_number = int(page_number)<EOL>next_step = redirect("<STR_LIT>", page_number + <NUM_LIT:1>)<EOL>with BatchController.batch(request.user):<EOL><INDENT>available = ProductController.available_products(<EOL>request.user, category=ticket_category<EOL>)<EOL>if not available:<EOL><INDENT>messages.error(request, "<STR_LIT>")<EOL>return redirect("<STR_LIT>")<EOL><DEDENT>sections = []<EOL>if page_number == PAGE_PROFILE:<EOL><INDENT>title = "<STR_LIT>"<EOL>sections = _guided_registration_profile_and_voucher(request)<EOL><DEDENT>elif page_number == PAGE_TICKET:<EOL><INDENT>title = "<STR_LIT>"<EOL>sections = _guided_registration_products(<EOL>request, GUIDED_MODE_TICKETS_ONLY<EOL>)<EOL><DEDENT>elif page_number == PAGE_PRODUCTS:<EOL><INDENT>title = "<STR_LIT>"<EOL>sections = _guided_registration_products(<EOL>request, GUIDED_MODE_ALL_ADDITIONAL<EOL>)<EOL><DEDENT>elif page_number == PAGE_PRODUCTS_MAX:<EOL><INDENT>title = "<STR_LIT>"<EOL>sections = _guided_registration_products(<EOL>request, GUIDED_MODE_EXCLUDE_COMPLETE<EOL>)<EOL><DEDENT>if not sections:<EOL><INDENT>attendee.completed_registration = True<EOL>attendee.save()<EOL>return redirect("<STR_LIT>")<EOL><DEDENT>if sections and request.method == "<STR_LIT:POST>":<EOL><INDENT>for section in sections:<EOL><INDENT>if section.form.errors:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return next_step<EOL><DEDENT><DEDENT><DEDENT>data = {<EOL>"<STR_LIT>": page_number,<EOL>"<STR_LIT>": sections,<EOL>"<STR_LIT:title>": title,<EOL>"<STR_LIT>": TOTAL_PAGES,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

Goes through the registration process in order, making sure user sees
    all valid categories.

    The user must be logged in to see this view.

    Parameter:
        page_number:
            1) Profile form (and e-mail address?)
            2) Ticket type
            3) Remaining products
            4) Mark registration as complete

    Returns:
        render: Renders ``registrasion/guided_registration.html``,
            with the following data::

                {
                    "current_step": int(),  # The current step in the
                                            # registration
                    "sections": sections,   # A list of
                                            # GuidedRegistrationSections
                    "title": str(),         # The title of the page
                    "total_steps": int(),   # The total number of steps
                }


return render(<EOL>request,<EOL>"<STR_LIT>",<EOL>{},<EOL>)<EOL>


form, handled = _handle_profile(request, "<STR_LIT>")<EOL>if handled and not form.errors:<EOL><INDENT>messages.success(<EOL>request,<EOL>"<STR_LIT>",<EOL>)<EOL>return redirect("<STR_LIT>")<EOL><DEDENT>data = {<EOL>"<STR_LIT>": form,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

View for editing an attendee's profile

    The user must be logged in to edit their profile.

    Returns:
        redirect or render:
            In the case of a ``POST`` request, it'll redirect to ``dashboard``,
            or otherwise, it will render ``registrasion/profile_form.html``
            with data::

                {
                    "form": form,  # Instance of ATTENDEE_PROFILE_FORM.
                }


attendee = people.Attendee.get_instance(request.user)<EOL>try:<EOL><INDENT>profile = attendee.attendeeprofilebase<EOL>profile = people.AttendeeProfileBase.objects.get_subclass(<EOL>pk=profile.id,<EOL>)<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>profile = None<EOL><DEDENT>try:<EOL><INDENT>speaker_profile = request.user.speaker_profile<EOL>speaker_name = speaker_profile.name<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>speaker_name = None<EOL><DEDENT>name_field = ProfileForm.Meta.model.name_field()<EOL>initial = {}<EOL>if profile is None and name_field is not None:<EOL><INDENT>initial[name_field] = speaker_name<EOL><DEDENT>form = ProfileForm(<EOL>request.POST or None,<EOL>initial=initial,<EOL>instance=profile,<EOL>prefix=prefix<EOL>)<EOL>handled = True if request.POST else False<EOL>if request.POST and form.is_valid():<EOL><INDENT>form.instance.attendee = attendee<EOL>form.save()<EOL><DEDENT>return form, handled<EOL>

Returns a profile form instance, and a boolean which is true if the
    form was handled.


PRODUCTS_FORM_PREFIX = "<STR_LIT>"<EOL>VOUCHERS_FORM_PREFIX = "<STR_LIT>"<EOL>v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)<EOL>voucher_form, voucher_handled = v<EOL>category_id = int(category_id)  <EOL>category = inventory.Category.objects.get(pk=category_id)<EOL>with BatchController.batch(request.user):<EOL><INDENT>products = ProductController.available_products(<EOL>request.user,<EOL>category=category,<EOL>)<EOL>if not products:<EOL><INDENT>messages.warning(<EOL>request,<EOL>(<EOL>"<STR_LIT>" +<EOL>category.name<EOL>),<EOL>)<EOL>return redirect("<STR_LIT>")<EOL><DEDENT>p = _handle_products(request, category, products, PRODUCTS_FORM_PREFIX)<EOL>products_form, discounts, products_handled = p<EOL><DEDENT>if request.POST and not voucher_handled and not products_form.errors:<EOL><INDENT>if products_form.has_changed():<EOL><INDENT>messages.success(<EOL>request,<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT>return redirect(review)<EOL><DEDENT>data = {<EOL>"<STR_LIT>": category,<EOL>"<STR_LIT>": discounts,<EOL>"<STR_LIT>": products_form,<EOL>"<STR_LIT>": voucher_form,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

Form for selecting products from an individual product category.

    Arguments:
        category_id (castable to int): The id of the category to display.

    Returns:
        redirect or render:
            If the form has been sucessfully submitted, redirect to
            ``dashboard``. Otherwise, render
            ``registrasion/product_category.html`` with data::

                {
                    "category": category,         # An inventory.Category for
                                                  # category_id
                    "discounts": discounts,       # A list of
                                                  # DiscountAndQuantity
                    "form": products_form,        # A form for selecting
                                                  # products
                    "voucher_form": voucher_form, # A form for entering a
                                                  # voucher code
                }


VOUCHERS_FORM_PREFIX = "<STR_LIT>"<EOL>v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)<EOL>voucher_form, voucher_handled = v<EOL>if voucher_handled:<EOL><INDENT>messages.success(request, "<STR_LIT>")<EOL>return redirect("<STR_LIT>")<EOL><DEDENT>data = {<EOL>"<STR_LIT>": voucher_form,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

A view *just* for entering a voucher form.


def _handle_products(request, category, products, prefix):

current_cart = CartController.for_user(request.user)<EOL>ProductsForm = forms.ProductsForm(category, products)<EOL>items = commerce.ProductItem.objects.filter(<EOL>product__in=products,<EOL>cart=current_cart.cart,<EOL>).select_related("<STR_LIT>")<EOL>quantities = []<EOL>seen = set()<EOL>for item in items:<EOL><INDENT>quantities.append((item.product, item.quantity))<EOL>seen.add(item.product)<EOL><DEDENT>zeros = set(products) - seen<EOL>for product in zeros:<EOL><INDENT>quantities.append((product, <NUM_LIT:0>))<EOL><DEDENT>products_form = ProductsForm(<EOL>request.POST or None,<EOL>product_quantities=quantities,<EOL>prefix=prefix,<EOL>)<EOL>if request.method == "<STR_LIT:POST>" and products_form.is_valid():<EOL><INDENT>if products_form.has_changed():<EOL><INDENT>_set_quantities_from_products_form(products_form, current_cart)<EOL><DEDENT>if category.required:<EOL><INDENT>carts = commerce.Cart.objects.filter(user=request.user)<EOL>items = commerce.ProductItem.objects.filter(<EOL>product__category=category,<EOL>cart=carts,<EOL>)<EOL>if len(items) == <NUM_LIT:0>:<EOL><INDENT>products_form.add_error(<EOL>None,<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT><DEDENT><DEDENT>handled = False if products_form.errors else True<EOL>discounts = util.lazy(<EOL>DiscountController.available_discounts,<EOL>request.user,<EOL>[],<EOL>products,<EOL>)<EOL>return products_form, discounts, handled<EOL>

Handles a products list form in the given request. Returns the
    form instance, the discounts applicable to this form, and whether the
    contents were handled.


voucher_form = forms.VoucherForm(request.POST or None, prefix=prefix)<EOL>current_cart = CartController.for_user(request.user)<EOL>if (voucher_form.is_valid() and<EOL>voucher_form.cleaned_data["<STR_LIT>"].strip()):<EOL><INDENT>voucher = voucher_form.cleaned_data["<STR_LIT>"]<EOL>voucher = inventory.Voucher.normalise_code(voucher)<EOL>if len(current_cart.cart.vouchers.filter(code=voucher)) > <NUM_LIT:0>:<EOL><INDENT>handled = False<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>current_cart.apply_voucher(voucher)<EOL><DEDENT>except Exception as e:<EOL><INDENT>voucher_form.add_error("<STR_LIT>", e)<EOL><DEDENT>handled = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>handled = False<EOL><DEDENT>return (voucher_form, handled)<EOL>

Handles a voucher form in the given request. Returns the voucher
    form instance, and whether the voucher code was handled.


if user_id is not None:<EOL><INDENT>if request.user.is_staff:<EOL><INDENT>user = User.objects.get(id=int(user_id))<EOL><DEDENT>else:<EOL><INDENT>raise Http404()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>user = request.user<EOL><DEDENT>current_cart = CartController.for_user(user)<EOL>if "<STR_LIT>" in request.GET and request.GET["<STR_LIT>"] == "<STR_LIT:true>":<EOL><INDENT>current_cart.fix_simple_errors()<EOL><DEDENT>try:<EOL><INDENT>current_invoice = InvoiceController.for_cart(current_cart.cart)<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>return _checkout_errors(request, ve)<EOL><DEDENT>return redirect("<STR_LIT>", current_invoice.invoice.id)<EOL>

Runs the checkout process for the current cart.

    If the query string contains ``fix_errors=true``, Registrasion will attempt
    to fix errors preventing the system from checking out, including by
    cancelling expired discounts and vouchers, and removing any unavailable
    products.

    Arguments:
        user_id (castable to int):
            If the requesting user is staff, then the user ID can be used to
            run checkout for another user.
    Returns:
        render or redirect:
            If the invoice is generated successfully, or there's already a
            valid invoice for the current cart, redirect to ``invoice``.
            If there are errors when generating the invoice, render
            ``registrasion/checkout_errors.html`` with the following data::

                {
                    "error_list", [str, ...]  # The errors to display.
                }


invoices = commerce.Invoice.objects.filter(<EOL>user__attendee__access_code=access_code,<EOL>).order_by("<STR_LIT>")<EOL>if not invoices:<EOL><INDENT>raise Http404()<EOL><DEDENT>unpaid = invoices.filter(status=commerce.Invoice.STATUS_UNPAID)<EOL>paid = invoices.filter(status=commerce.Invoice.STATUS_PAID)<EOL>if unpaid:<EOL><INDENT>invoice = unpaid[<NUM_LIT:0>]  <EOL><DEDENT>elif paid:<EOL><INDENT>invoice = paid[<NUM_LIT:0>]  <EOL><DEDENT>else:<EOL><INDENT>invoice = invoices[<NUM_LIT:0>]  <EOL><DEDENT>return redirect("<STR_LIT>", invoice.id, access_code)<EOL>

Redirects to an invoice for the attendee that matches the given access
    code, if any.

    If the attendee has multiple invoices, we use the following tie-break:

    - If there's an unpaid invoice, show that, otherwise
    - If there's a paid invoice, show the most recent one, otherwise
    - Show the most recent invoid of all

    Arguments:

        access_code (castable to int): The access code for the user whose
            invoice you want to see.

    Returns:
        redirect:
            Redirect to the selected invoice for that user.

    Raises:
        Http404: If the user has no invoices.


def invoice(request, invoice_id, access_code=None):

current_invoice = InvoiceController.for_id_or_404(invoice_id)<EOL>if not current_invoice.can_view(<EOL>user=request.user,<EOL>access_code=access_code,<EOL>):<EOL><INDENT>raise Http404()<EOL><DEDENT>data = {<EOL>"<STR_LIT>": current_invoice.invoice,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

Displays an invoice.

    This view is not authenticated, but it will only allow access to either:
    the user the invoice belongs to; staff; or a request made with the correct
    access code.

    Arguments:

        invoice_id (castable to int): The invoice_id for the invoice you want
            to view.

        access_code (Optional[str]): The access code for the user who owns
            this invoice.

    Returns:
        render:
            Renders ``registrasion/invoice.html``, with the following
            data::

                {
                    "invoice": models.commerce.Invoice(),
                }

    Raises:
        Http404: if the current user cannot view this invoice and the correct
            access_code is not provided.


return user.is_staff<EOL>


category = request.GET.getlist("<STR_LIT>", [])<EOL>product = request.GET.getlist("<STR_LIT>", [])<EOL>status = request.GET.get("<STR_LIT:status>")<EOL>form = forms.InvoicesWithProductAndStatusForm(<EOL>request.POST or None,<EOL>category=category,<EOL>product=product,<EOL>status=status,<EOL>)<EOL>if form.is_valid():<EOL><INDENT>response = HttpResponse()<EOL>response["<STR_LIT:Content-Type>"] = "<STR_LIT>"<EOL>response["<STR_LIT>"] = '<STR_LIT>'<EOL>z = zipfile.ZipFile(response, "<STR_LIT:w>")<EOL>for invoice in form.cleaned_data["<STR_LIT>"]:<EOL><INDENT>user = invoice.user<EOL>badge = render_badge(user)<EOL>z.writestr("<STR_LIT>" % user.id, badge.encode("<STR_LIT:utf-8>"))<EOL><DEDENT>return response<EOL><DEDENT>data = {<EOL>"<STR_LIT>": form,<EOL>}<EOL>return render(request, "<STR_LIT>", data)<EOL>

Either displays a form containing a list of users with badges to
    render, or returns a .zip file containing their badges.


data = {<EOL>"<STR_LIT:user>": user,<EOL>}<EOL>t = loader.get_template('<STR_LIT>')<EOL>return t.render(data)<EOL>


types = list(ConditionController._controllers())<EOL>flagtypes = [i for i in types if issubclass(i, conditions.FlagBase)]<EOL>all_subsets = []<EOL>for flagtype in flagtypes:<EOL><INDENT>flags = flagtype.objects.all()<EOL>ctrl = ConditionController.for_type(flagtype)<EOL>flags = ctrl.pre_filter(flags, user)<EOL>all_subsets.append(flags)<EOL><DEDENT>return list(itertools.chain(*all_subsets))<EOL>

Returns:
    Sequence[flagbase]: All flags that passed the filter function.


cls._enter_batch_context(user)<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>cls._exit_batch_context(user)<EOL><DEDENT>

Marks the entry point for a batch for the given user.


@functools.wraps(func)<EOL>def f(*a):<EOL><INDENT>for arg in a:<EOL><INDENT>if isinstance(arg, User):<EOL><INDENT>user = arg<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>func_key = (func, tuple(a))<EOL>cache = cls.get_cache(user)<EOL>if func_key not in cache:<EOL><INDENT>cache[func_key] = func(*a)<EOL><DEDENT>return cache[func_key]<EOL><DEDENT>return f<EOL>

Decorator that stores the result of the stored function in the
        user's results cache until the batch completes. Keyword arguments are
        not yet supported.

        Arguments:
            func (callable(*a)): The function whose results we want
                to store. The positional arguments, ``a``, are used as cache
                keys.

        Returns:
            callable(*a): The memosing version of ``func``.


cache = {}<EOL>cache[cls._NESTING_KEY] = <NUM_LIT:0><EOL>return cache<EOL>


@classmethod<EOL><INDENT>def available_categories(cls, user, products=AllProducts):<DEDENT>

<EOL>from .product import ProductController<EOL>if products is AllProducts:<EOL><INDENT>products = inventory.Product.objects.all().select_related(<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT>available = ProductController.available_products(<EOL>user,<EOL>products=products,<EOL>)<EOL>return sorted(set(i.category for i in available), key=attrgetter("<STR_LIT>"))<EOL>

Returns the categories available to the user. Specify `products` if
        you want to restrict to just the categories that hold the specified
        products, otherwise it'll do all.


categories = inventory.Category.objects.all()<EOL>cart_filter = (<EOL>Q(product__productitem__cart__user=user) &<EOL>Q(product__productitem__cart__status=commerce.Cart.STATUS_PAID)<EOL>)<EOL>quantity = When(<EOL>cart_filter,<EOL>then='<STR_LIT>'<EOL>)<EOL>quantity_or_zero = Case(<EOL>quantity,<EOL>default=Value(<NUM_LIT:0>),<EOL>)<EOL>remainder = Case(<EOL>When(limit_per_user=None, then=Value(<NUM_LIT>)),<EOL>default=F('<STR_LIT>') - Sum(quantity_or_zero),<EOL>)<EOL>categories = categories.annotate(remainder=remainder)<EOL>return dict((cat.id, cat.remainder) for cat in categories)<EOL>

Return:
    Mapping[int->int]: A dictionary that maps the category ID to the
    user's remainder for that category.


@classmethod<EOL><INDENT>def available_discounts(cls, user, categories, products):<DEDENT>

filtered_clauses = cls._filtered_clauses(user)<EOL>categories = set(categories)<EOL>products = set(products)<EOL>product_categories = set(product.category for product in products)<EOL>all_categories = categories | product_categories<EOL>filtered_clauses = (<EOL>clause for clause in filtered_clauses<EOL>if hasattr(clause, '<STR_LIT>') and clause.product in products or<EOL>hasattr(clause, '<STR_LIT>') and clause.category in all_categories<EOL>)<EOL>discounts = []<EOL>accepted_discounts = set()<EOL>failed_discounts = set()<EOL>for clause in filtered_clauses:<EOL><INDENT>discount = clause.discount<EOL>cond = ConditionController.for_condition(discount)<EOL>past_use_count = clause.past_use_count<EOL>if past_use_count >= clause.quantity:<EOL><INDENT>pass<EOL><DEDENT>elif discount not in failed_discounts:<EOL><INDENT>is_accepted = discount in accepted_discounts<EOL>if is_accepted or cond.is_met(user, filtered=True):<EOL><INDENT>discounts.append(DiscountAndQuantity(<EOL>discount=discount,<EOL>clause=clause,<EOL>quantity=clause.quantity - past_use_count,<EOL>))<EOL>accepted_discounts.add(discount)<EOL><DEDENT>else:<EOL><INDENT>failed_discounts.add(discount)<EOL><DEDENT><DEDENT><DEDENT>return discounts<EOL>

Returns all discounts available to this user for the given
        categories and products. The discounts also list the available quantity
        for this user, not including products that are pending purchase.


types = list(ConditionController._controllers())<EOL>discounttypes = [<EOL>i for i in types if issubclass(i, conditions.DiscountBase)<EOL>]<EOL>product_clauses = conditions.DiscountForProduct.objects.all()<EOL>product_clauses = product_clauses.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>category_clauses = conditions.DiscountForCategory.objects.all()<EOL>category_clauses = category_clauses.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>all_subsets = []<EOL>for discounttype in discounttypes:<EOL><INDENT>discounts = discounttype.objects.all()<EOL>ctrl = ConditionController.for_type(discounttype)<EOL>discounts = ctrl.pre_filter(discounts, user)<EOL>all_subsets.append(discounts)<EOL><DEDENT>filtered_discounts = list(itertools.chain(*all_subsets))<EOL>from_filter = dict((i.id, i) for i in filtered_discounts)<EOL>clause_sets = (<EOL>product_clauses.filter(discount__in=filtered_discounts),<EOL>category_clauses.filter(discount__in=filtered_discounts),<EOL>)<EOL>clause_sets = (<EOL>cls._annotate_with_past_uses(i, user) for i in clause_sets<EOL>)<EOL>discount_clauses = set(itertools.chain(*clause_sets))<EOL>for clause in discount_clauses:<EOL><INDENT>clause.discount = from_filter[clause.discount.id]<EOL><DEDENT>return discount_clauses<EOL>

Returns:
    Sequence[DiscountForProduct | DiscountForCategory]: All clauses
    that passed the filter function.


@classmethod<EOL><INDENT>def _annotate_with_past_uses(cls, queryset, user):<DEDENT>

if queryset.model == conditions.DiscountForCategory:<EOL><INDENT>matches = (<EOL>Q(category=F('<STR_LIT>'))<EOL>)<EOL><DEDENT>elif queryset.model == conditions.DiscountForProduct:<EOL><INDENT>matches = (<EOL>Q(product=F('<STR_LIT>'))<EOL>)<EOL><DEDENT>in_carts = (<EOL>Q(discount__discountitem__cart__user=user) &<EOL>Q(discount__discountitem__cart__status=commerce.Cart.STATUS_PAID)<EOL>)<EOL>past_use_quantity = When(<EOL>in_carts & matches,<EOL>then="<STR_LIT>",<EOL>)<EOL>past_use_quantity_or_zero = Case(<EOL>past_use_quantity,<EOL>default=Value(<NUM_LIT:0>),<EOL>)<EOL>queryset = queryset.annotate(<EOL>past_use_count=Sum(past_use_quantity_or_zero)<EOL>)<EOL>return queryset<EOL>

Annotates the queryset with a usage count for that discount claus
        by the given user.


@classmethod<EOL><INDENT>def generate_from_invoice(cls, invoice, value):<DEDENT>

credit_note = commerce.CreditNote.objects.create(<EOL>invoice=invoice,<EOL>amount=<NUM_LIT:0>-value,  <EOL>reference="<STR_LIT>",<EOL>)<EOL>credit_note.reference = "<STR_LIT>" % credit_note.id<EOL>credit_note.save()<EOL>return cls(credit_note)<EOL>

Generates a credit note of the specified value and pays it against
        the given invoice. You need to call InvoiceController.update_status()
        to set the status correctly, if appropriate.


<EOL>from .invoice import InvoiceController<EOL>inv = InvoiceController(invoice)<EOL>inv.validate_allowed_to_pay()<EOL>commerce.CreditNoteApplication.objects.create(<EOL>parent=self.credit_note,<EOL>invoice=invoice,<EOL>amount=self.credit_note.value,<EOL>reference="<STR_LIT>" % self.credit_note.id,<EOL>)<EOL>inv.update_status()<EOL>

Applies the total value of this credit note to the specified
        invoice. If this credit note overpays the invoice, a new credit note
        containing the residual value will be created.

        Raises ValidationError if the given invoice is not allowed to be
        paid.


<EOL>from .invoice import InvoiceController<EOL>assert(percentage >= <NUM_LIT:0> and percentage <= <NUM_LIT:100>)<EOL>cancellation_fee = self.credit_note.value * percentage / <NUM_LIT:100><EOL>due = datetime.timedelta(days=<NUM_LIT:1>)<EOL>item = [("<STR_LIT>", cancellation_fee)]<EOL>invoice = InvoiceController.manual_invoice(<EOL>self.credit_note.invoice.user, due, item<EOL>)<EOL>if not invoice.is_paid:<EOL><INDENT>self.apply_to_invoice(invoice)<EOL><DEDENT>return InvoiceController(invoice)<EOL>

Generates an invoice with a cancellation fee, and applies
        credit to the invoice.

        percentage (Decimal): The percentage of the credit note to turn into
        a cancellation fee. Must be 0 <= percentage <= 100.


@functools.wraps(func)<EOL>def inner(self, *a, **k):<EOL><INDENT>self._fail_if_cart_is_not_active()<EOL>with transaction.atomic():<EOL><INDENT>with BatchController.batch(self.cart.user):<EOL><INDENT>memoised = self.for_user(self.cart.user)<EOL>memoised._modified_by_batch = True<EOL>return func(self, *a, **k)<EOL><DEDENT><DEDENT><DEDENT>return inner<EOL>

Decorator that makes the wrapped function raise ValidationError
    if we're doing something that could modify the cart.

    It also wraps the execution of this function in a database transaction,
    and marks the boundaries of a cart operations batch.


try:<EOL><INDENT>existing = commerce.Cart.objects.get(<EOL>user=user,<EOL>status=commerce.Cart.STATUS_ACTIVE,<EOL>)<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>existing = commerce.Cart.objects.create(<EOL>user=user,<EOL>time_last_updated=timezone.now(),<EOL>reservation_duration=datetime.timedelta(),<EOL>)<EOL><DEDENT>return cls(existing)<EOL>

Returns the user's current cart, or creates a new cart
        if there isn't one ready yet.


time = timezone.now()<EOL>time_elapsed_since_updated = (time - self.cart.time_last_updated)<EOL>residual = self.cart.reservation_duration - time_elapsed_since_updated<EOL>reservations = [datetime.timedelta(<NUM_LIT:0>), residual]<EOL>if len(self.cart.vouchers.all()) >= <NUM_LIT:1>:<EOL><INDENT>reservations.append(inventory.Voucher.RESERVATION_DURATION)<EOL><DEDENT>items = commerce.ProductItem.objects.filter(cart=self.cart)<EOL>agg = items.aggregate(Max("<STR_LIT>"))<EOL>product_max = agg["<STR_LIT>"]<EOL>if product_max is not None:<EOL><INDENT>reservations.append(product_max)<EOL><DEDENT>self.cart.time_last_updated = time<EOL>self.cart.reservation_duration = max(reservations)<EOL>

Updates the cart's time last updated value, which is used to
        determine whether the cart has reserved the items and discounts it
        holds.


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._end_batch()<EOL><DEDENT>

Calls ``_end_batch`` if a modification has been performed in the
        previous batch.


self.cart.refresh_from_db()<EOL>self._recalculate_discounts()<EOL>self._autoextend_reservation()<EOL>self.cart.revision += <NUM_LIT:1><EOL>self.cart.save()<EOL>

Performs operations that occur occur at the end of a batch of
        product changes/voucher applications etc.

        You need to call this after you've finished modifying the user's cart.
        This is normally done by wrapping a block of code using
        ``operations_batch``.


self.validate_cart()<EOL>cart = self.cart<EOL>cart.refresh_from_db()<EOL>elapsed = (timezone.now() - cart.time_last_updated)<EOL>if cart.reservation_duration - elapsed > timedelta:<EOL><INDENT>return<EOL><DEDENT>cart.time_last_updated = timezone.now()<EOL>cart.reservation_duration = timedelta<EOL>cart.save()<EOL>

Extends the reservation on this cart by the given timedelta.
        This can only be done if the current state of the cart is valid (i.e
        all items and discounts in the cart are still available.)

        Arguments:
            timedelta (timedelta): The amount of time to extend the cart by.
                The resulting reservation_duration will be now() + timedelta,
                unless the requested extension is *LESS* than the current
                reservation deadline.


items_in_cart = commerce.ProductItem.objects.filter(cart=self.cart)<EOL>items_in_cart = items_in_cart.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>product_quantities = list(product_quantities)<EOL>all_product_quantities = dict(itertools.chain(<EOL>((i.product, i.quantity) for i in items_in_cart.all()),<EOL>product_quantities,<EOL>)).items()<EOL>products = set(product for product, q in product_quantities)<EOL>try:<EOL><INDENT>self._test_limits(all_product_quantities)<EOL><DEDENT>except CartValidationError as ve:<EOL><INDENT>for ve_field in ve.error_list:<EOL><INDENT>product, message = ve_field.message<EOL>if product in products:<EOL><INDENT>raise ve<EOL><DEDENT><DEDENT><DEDENT>new_items = []<EOL>products = []<EOL>for product, quantity in product_quantities:<EOL><INDENT>products.append(product)<EOL>if quantity == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>item = commerce.ProductItem(<EOL>cart=self.cart,<EOL>product=product,<EOL>quantity=quantity,<EOL>)<EOL>new_items.append(item)<EOL><DEDENT>to_delete = (<EOL>Q(quantity=<NUM_LIT:0>) |<EOL>Q(product__in=products)<EOL>)<EOL>items_in_cart.filter(to_delete).delete()<EOL>commerce.ProductItem.objects.bulk_create(new_items)<EOL>

Sets the quantities on each of the products on each of the
        products specified. Raises an exception (ValidationError) if a limit
        is violated. `product_quantities` is an iterable of (product, quantity)
        pairs.


<EOL>voucher = inventory.Voucher.objects.get(code=voucher_code.upper())<EOL>if voucher in self.cart.vouchers.all():<EOL><INDENT>return<EOL><DEDENT>self._test_voucher(voucher)<EOL>self.cart.vouchers.add(voucher)<EOL>

Applies the voucher with the given code to this cart.


cart = self.cart<EOL>user = self.cart.user<EOL>errors = []<EOL>try:<EOL><INDENT>self._test_vouchers(self.cart.vouchers.all())<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>errors.append(ve)<EOL><DEDENT>items = commerce.ProductItem.objects.filter(cart=cart)<EOL>items = items.select_related("<STR_LIT>", "<STR_LIT>")<EOL>product_quantities = list((i.product, i.quantity) for i in items)<EOL>try:<EOL><INDENT>self._test_limits(product_quantities)<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>self._append_errors(errors, ve)<EOL><DEDENT>try:<EOL><INDENT>self._test_required_categories()<EOL><DEDENT>except ValidationError as ve:<EOL><INDENT>self._append_errors(errors, ve)<EOL><DEDENT>products = [i.product for i in items]<EOL>discounts_with_quantity = DiscountController.available_discounts(<EOL>user,<EOL>[],<EOL>products,<EOL>)<EOL>discounts = set(i.discount.id for i in discounts_with_quantity)<EOL>discount_items = commerce.DiscountItem.objects.filter(cart=cart)<EOL>for discount_item in discount_items:<EOL><INDENT>discount = discount_item.discount<EOL>if discount.id not in discounts:<EOL><INDENT>errors.append(<EOL>ValidationError("<STR_LIT>")<EOL>)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise ValidationError(errors)<EOL><DEDENT>

Determines whether the status of the current cart is valid;
        this is normally called before generating or paying an invoice


<EOL>to_remove = []<EOL>for voucher in self.cart.vouchers.all():<EOL><INDENT>try:<EOL><INDENT>self._test_voucher(voucher)<EOL><DEDENT>except ValidationError:<EOL><INDENT>to_remove.append(voucher)<EOL><DEDENT><DEDENT>for voucher in to_remove:<EOL><INDENT>self.cart.vouchers.remove(voucher)<EOL><DEDENT>items = commerce.ProductItem.objects.filter(cart=self.cart)<EOL>items = items.select_related("<STR_LIT>")<EOL>products = set(i.product for i in items)<EOL>available = set(ProductController.available_products(<EOL>self.cart.user,<EOL>products=products,<EOL>))<EOL>not_available = products - available<EOL>zeros = [(product, <NUM_LIT:0>) for product in not_available]<EOL>self.set_quantities(zeros)<EOL>

This attempts to fix the easy errors raised by ValidationError.
        This includes removing items from the cart that are no longer
        available, recalculating all of the discounts, and removing voucher
        codes that are no longer available.


<EOL>commerce.DiscountItem.objects.filter(cart=self.cart).delete()<EOL>product_items = self.cart.productitem_set.all().select_related(<EOL>"<STR_LIT>", "<STR_LIT>"<EOL>).order_by("<STR_LIT>")<EOL>products = [i.product for i in product_items]<EOL>discounts = DiscountController.available_discounts(<EOL>self.cart.user,<EOL>[],<EOL>products,<EOL>)<EOL>for item in product_items:<EOL><INDENT>self._add_discount(item.product, item.quantity, discounts)<EOL><DEDENT>

Calculates all of the discounts available for this product.


def _add_discount(self, product, quantity, discounts):

def matches(discount):<EOL><INDENT>'''<STR_LIT>'''<EOL>if isinstance(discount.clause, conditions.DiscountForCategory):<EOL><INDENT>return discount.clause.category == product.category<EOL><DEDENT>else:<EOL><INDENT>return discount.clause.product == product<EOL><DEDENT><DEDENT>def value(discount):<EOL><INDENT>'''<STR_LIT>'''<EOL>if discount.clause.percentage is not None:<EOL><INDENT>return discount.clause.percentage * product.price<EOL><DEDENT>else:<EOL><INDENT>return discount.clause.price<EOL><DEDENT><DEDENT>discounts = [i for i in discounts if matches(i)]<EOL>discounts.sort(key=value)<EOL>for candidate in reversed(discounts):<EOL><INDENT>if quantity == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>elif candidate.quantity == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>discount_item = commerce.DiscountItem.objects.create(<EOL>product=product,<EOL>cart=self.cart,<EOL>discount=candidate.discount,<EOL>quantity=quantity,<EOL>)<EOL>ours = discount_item.quantity<EOL>allowed = candidate.quantity<EOL>if ours > allowed:<EOL><INDENT>discount_item.quantity = allowed<EOL>discount_item.save()<EOL>quantity = ours - allowed<EOL><DEDENT>else:<EOL><INDENT>quantity = <NUM_LIT:0><EOL><DEDENT>candidate.quantity -= discount_item.quantity<EOL><DEDENT>

Applies the best discounts on the given product, from the given
        discounts.


@classmethod<EOL><INDENT>def available_products(cls, user, category=None, products=None):<DEDENT>

if category is None and products is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if category is not None:<EOL><INDENT>all_products = inventory.Product.objects.filter(category=category)<EOL>all_products = all_products.select_related("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>all_products = []<EOL><DEDENT>if products is not None:<EOL><INDENT>all_products = set(itertools.chain(all_products, products))<EOL><DEDENT>category_remainders = CategoryController.user_remainders(user)<EOL>product_remainders = ProductController.user_remainders(user)<EOL>passed_limits = set(<EOL>product<EOL>for product in all_products<EOL>if category_remainders[product.category.id] > <NUM_LIT:0><EOL>if product_remainders[product.id] > <NUM_LIT:0><EOL>)<EOL>failed_and_messages = FlagController.test_flags(<EOL>user, products=passed_limits<EOL>)<EOL>failed_conditions = set(i[<NUM_LIT:0>] for i in failed_and_messages)<EOL>out = list(passed_limits - failed_conditions)<EOL>out.sort(key=lambda product: product.order)<EOL>return out<EOL>

Returns a list of all of the products that are available per
        flag conditions from the given categories.


products = inventory.Product.objects.all()<EOL>cart_filter = (<EOL>Q(productitem__cart__user=user) &<EOL>Q(productitem__cart__status=commerce.Cart.STATUS_PAID)<EOL>)<EOL>quantity = When(<EOL>cart_filter,<EOL>then='<STR_LIT>'<EOL>)<EOL>quantity_or_zero = Case(<EOL>quantity,<EOL>default=Value(<NUM_LIT:0>),<EOL>)<EOL>remainder = Case(<EOL>When(limit_per_user=None, then=Value(<NUM_LIT>)),<EOL>default=F('<STR_LIT>') - Sum(quantity_or_zero),<EOL>)<EOL>products = products.annotate(remainder=remainder)<EOL>return dict((product.id, product.remainder) for product in products)<EOL>

Return:
    Mapping[int->int]: A dictionary that maps the product ID to the
    user's remainder for that product.


def _items(self, cart_status, category=None):

if not isinstance(cart_status, Iterable):<EOL><INDENT>cart_status = [cart_status]<EOL><DEDENT>status_query = (<EOL>Q(productitem__cart__status=status) for status in cart_status<EOL>)<EOL>in_cart = Q(productitem__cart__user=self.user)<EOL>in_cart = in_cart & reduce(operator.__or__, status_query)<EOL>quantities_in_cart = When(<EOL>in_cart,<EOL>then="<STR_LIT>",<EOL>)<EOL>quantities_or_zero = Case(<EOL>quantities_in_cart,<EOL>default=Value(<NUM_LIT:0>),<EOL>)<EOL>products = inventory.Product.objects<EOL>if category:<EOL><INDENT>products = products.filter(category=category)<EOL><DEDENT>products = products.select_related("<STR_LIT>")<EOL>products = products.annotate(quantity=Sum(quantities_or_zero))<EOL>products = products.filter(quantity__gt=<NUM_LIT:0>)<EOL>out = []<EOL>for prod in products:<EOL><INDENT>out.append(ProductAndQuantity(prod, prod.quantity))<EOL><DEDENT>return out<EOL>

Aggregates the items that this user has purchased.

        Arguments:
            cart_status (int or Iterable(int)): etc
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.


status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]<EOL>return self._items(status)<EOL>

Returns the items that this user has purchased or has pending.


return self._items(commerce.Cart.STATUS_PAID, category=category)<EOL>

Aggregates the items that this user has purchased.

        Arguments:
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.


return self._items(commerce.Cart.STATUS_ACTIVE)<EOL>

Gets all of the items that the user has reserved, but has not yet
        paid for.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs for the
                items that the user has not yet paid for.


return self._items(commerce.Cart.STATUS_RELEASED)<EOL>

Gets all of the items that the user previously paid for, but has
        since refunded.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs for the
                items that the user has not yet paid for.


@classmethod<EOL><INDENT>def pre_filter(cls, queryset, user):<DEDENT>

<EOL>return queryset<EOL>

Returns only the flag conditions that might be available for this
        user. It should hopefully reduce the number of queries that need to be
        executed to determine if a flag is met.

        If this filtration implements the same query as is_met, then you should
        be able to implement ``is_met()`` in terms of this.

        Arguments:

            queryset (Queryset[c]): The canditate conditions.

            user (User): The user for whom we're testing these conditions.

        Returns:
            Queryset[c]: A subset of the conditions that pass the pre-filter
                test for this user.


cls = type(self.condition)<EOL>qs = cls.objects.filter(pk=self.condition.id)<EOL>return self.condition in self.pre_filter(qs, user)<EOL>

Returns true if the condition passes the filter


def user_quantity_remaining(self, user, filtered=False):

return _BIG_QUANTITY if self.is_met(user, filtered) else <NUM_LIT:0><EOL>

Returns the number of items covered by this flag condition the
        user can add to the current cart. This default implementation returns
        a big number if is_met() is true, otherwise 0.

        Either this method, or is_met() must be overridden in subclasses.


return self.user_quantity_remaining(user, filtered) > <NUM_LIT:0><EOL>

Returns True if this flag condition is met, otherwise returns
        False.

        Either this method, or user_quantity_remaining() must be overridden
        in subclasses.

        Arguments:

            user (User): The user for whom this test must be met.

            filter (bool): If true, this condition was part of a queryset
                returned by pre_filter() for this user.


if filtered:<EOL><INDENT>return True  <EOL><DEDENT>return self.passes_filter(user)<EOL>

Returns True if this flag condition is met, otherwise returns
        False. It determines if the condition is met by calling pre_filter
        with a queryset containing only self.condition.


def user_quantity_remaining(self, user, filtered=True):

if filtered:<EOL><INDENT>if hasattr(self.condition, "<STR_LIT>"):<EOL><INDENT>return self.condition.remainder<EOL><DEDENT><DEDENT>qs = type(self.condition).objects.filter(pk=self.condition.id)<EOL>qs = self.pre_filter(qs, user)<EOL>if len(qs) > <NUM_LIT:0>:<EOL><INDENT>return qs[<NUM_LIT:0>].remainder<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

returns 0 if the date range is violated, otherwise, it will return
        the quantity remaining under the stock limit.

        The filter for this condition must add an annotation called "remainder"
        in order for this to work.


@classmethod<EOL><INDENT>def pre_filter(self, queryset, user):<DEDENT>

in_user_carts = Q(<EOL>enabling_category__product__productitem__cart__user=user<EOL>)<EOL>released = commerce.Cart.STATUS_RELEASED<EOL>in_released_carts = Q(<EOL>enabling_category__product__productitem__cart__status=released<EOL>)<EOL>queryset = queryset.filter(in_user_carts)<EOL>queryset = queryset.exclude(in_released_carts)<EOL>return queryset<EOL>

Returns all of the items from queryset where the user has a
        product from a category invoking that item's condition in one of their
        carts.


in_user_carts = Q(enabling_products__productitem__cart__user=user)<EOL>released = commerce.Cart.STATUS_RELEASED<EOL>paid = commerce.Cart.STATUS_PAID<EOL>active = commerce.Cart.STATUS_ACTIVE<EOL>in_released_carts = Q(<EOL>enabling_products__productitem__cart__status=released<EOL>)<EOL>not_in_paid_or_active_carts = ~(<EOL>Q(enabling_products__productitem__cart__status=paid) |<EOL>Q(enabling_products__productitem__cart__status=active)<EOL>)<EOL>queryset = queryset.filter(in_user_carts)<EOL>queryset = queryset.exclude(<EOL>in_released_carts & not_in_paid_or_active_carts<EOL>)<EOL>return queryset<EOL>

Returns all of the items from queryset where the user has a
        product invoking that item's condition in one of their carts.


now = timezone.now()<EOL>queryset = queryset.filter(Q(start_time=None) | Q(start_time__lte=now))<EOL>queryset = queryset.filter(Q(end_time=None) | Q(end_time__gte=now))<EOL>quantity_or_zero = self._calculate_quantities(user)<EOL>remainder = Case(<EOL>When(limit=None, then=Value(_BIG_QUANTITY)),<EOL>default=F("<STR_LIT>") - Sum(quantity_or_zero),<EOL>)<EOL>queryset = queryset.annotate(remainder=remainder)<EOL>queryset = queryset.filter(remainder__gt=<NUM_LIT:0>)<EOL>return queryset<EOL>

Returns all of the items from queryset where the date falls into
        any specified range, but not yet where the stock limit is not yet
        reached.


return queryset.filter(voucher__cart__user=user)<EOL>

Returns all of the items from queryset where the user has entered
        a voucher that invokes that item's condition in one of their carts.


<EOL>queryset = queryset.filter(<EOL>proposal_kind__proposalbase__presentation__cancelled=False<EOL>)<EOL>u = user<EOL>user_is_presenter = Q(<EOL>is_presenter=True,<EOL>proposal_kind__proposalbase__presentation__speaker__user=u,<EOL>)<EOL>user_is_copresenter = Q(<EOL>is_copresenter=True,<EOL>proposal_kind__proposalbase__presentation__additional_speakers__user=u,  <EOL>)<EOL>return queryset.filter(user_is_presenter | user_is_copresenter)<EOL>

Returns all of the items from queryset which are enabled by a user
        being a presenter or copresenter of a non-cancelled proposal.


@classmethod<EOL><INDENT>def pre_filter(self, conditions, user):<DEDENT>

return conditions.filter(group__in=user.groups.all())<EOL>

Returns all of the items from conditions which are enabled by a
        user being member of a Django Auth Group.


cart.refresh_from_db()<EOL>try:<EOL><INDENT>invoice = commerce.Invoice.objects.exclude(<EOL>status=commerce.Invoice.STATUS_VOID,<EOL>).get(<EOL>cart=cart,<EOL>cart_revision=cart.revision,<EOL>)<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>cart_controller = CartController(cart)<EOL>cart_controller.validate_cart()  <EOL>cls.update_old_invoices(cart)<EOL>invoice = cls._generate_from_cart(cart)<EOL><DEDENT>return cls(invoice)<EOL>

Returns an invoice object for a given cart at its current revision.
        If such an invoice does not exist, the cart is validated, and if valid,
        an invoice is generated.


@classmethod<EOL><INDENT>@transaction.atomic<EOL>def manual_invoice(cls, user, due_delta, description_price_pairs):<DEDENT>

line_items = []<EOL>for description, price in description_price_pairs:<EOL><INDENT>line_item = commerce.LineItem(<EOL>description=description,<EOL>quantity=<NUM_LIT:1>,<EOL>price=Decimal(price),<EOL>product=None,<EOL>)<EOL>line_items.append(line_item)<EOL><DEDENT>min_due_time = timezone.now() + due_delta<EOL>return cls._generate(user, None, min_due_time, line_items)<EOL>

Generates an invoice for arbitrary items, not held in a user's
        cart.

        Arguments:
            user (User): The user the invoice is being generated for.
            due_delta (datetime.timedelta): The length until the invoice is
                due.
            description_price_pairs ([(str, long or Decimal), ...]): A list of
                pairs. Each pair consists of the description for each line item
                and the price for that line item. The price will be cast to
                Decimal.

        Returns:
            an Invoice.


cart.refresh_from_db()<EOL>product_items = commerce.ProductItem.objects.filter(cart=cart)<EOL>product_items = product_items.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>product_items = product_items.order_by(<EOL>"<STR_LIT>", "<STR_LIT>"<EOL>)<EOL>if len(product_items) == <NUM_LIT:0>:<EOL><INDENT>raise ValidationError("<STR_LIT>")<EOL><DEDENT>discount_items = commerce.DiscountItem.objects.filter(cart=cart)<EOL>discount_items = discount_items.select_related(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL>def format_product(product):<EOL><INDENT>return "<STR_LIT>" % (product.category.name, product.name)<EOL><DEDENT>def format_discount(discount, product):<EOL><INDENT>description = discount.description<EOL>return "<STR_LIT>" % (description, format_product(product))<EOL><DEDENT>line_items = []<EOL>for item in product_items:<EOL><INDENT>product = item.product<EOL>line_item = commerce.LineItem(<EOL>description=format_product(product),<EOL>quantity=item.quantity,<EOL>price=product.price,<EOL>product=product,<EOL>)<EOL>line_items.append(line_item)<EOL><DEDENT>for item in discount_items:<EOL><INDENT>line_item = commerce.LineItem(<EOL>description=format_discount(item.discount, item.product),<EOL>quantity=item.quantity,<EOL>price=cls.resolve_discount_value(item) * -<NUM_LIT:1>,<EOL>product=item.product,<EOL>)<EOL>line_items.append(line_item)<EOL><DEDENT>min_due_time = cart.reservation_duration + cart.time_last_updated<EOL>return cls._generate(cart.user, cart, min_due_time, line_items)<EOL>

Generates an invoice for the given cart.


<EOL>invoices = commerce.Invoice.objects.filter(<EOL>user=invoice.user,<EOL>status=commerce.Invoice.STATUS_UNPAID,<EOL>)<EOL>if invoices.count() > <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>notes = commerce.CreditNote.unclaimed().filter(<EOL>invoice__user=invoice.user<EOL>)<EOL>for note in notes:<EOL><INDENT>try:<EOL><INDENT>CreditNoteController(note).apply_to_invoice(invoice)<EOL><DEDENT>except ValidationError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>invoice.refresh_from_db()<EOL>

Applies the user's credit notes to the given invoice on creation.


def can_view(self, user=None, access_code=None):

if user == self.invoice.user:<EOL><INDENT>return True<EOL><DEDENT>if user.is_staff:<EOL><INDENT>return True<EOL><DEDENT>if self.invoice.user.attendee.access_code == access_code:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Returns true if the accessing user is allowed to view this invoice,
        or if the given access code matches this invoice's user's access code.


self.invoice.refresh_from_db()<EOL>if self.invoice.cart:<EOL><INDENT>self.invoice.cart.refresh_from_db()<EOL><DEDENT>

Refreshes the underlying invoice and cart objects.


self._refresh()<EOL>if not self.invoice.is_unpaid:<EOL><INDENT>raise ValidationError("<STR_LIT>")<EOL><DEDENT>if not self.invoice.cart:<EOL><INDENT>return<EOL><DEDENT>if not self._invoice_matches_cart():<EOL><INDENT>raise ValidationError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>CartController(self.invoice.cart).validate_cart()<EOL>

Passes cleanly if we're allowed to pay, otherwise raise
        a ValidationError.


old_status = self.invoice.status<EOL>total_paid = self.invoice.total_payments()<EOL>num_payments = commerce.PaymentBase.objects.filter(<EOL>invoice=self.invoice,<EOL>).count()<EOL>remainder = self.invoice.value - total_paid<EOL>if old_status == commerce.Invoice.STATUS_UNPAID:<EOL><INDENT>if remainder <= <NUM_LIT:0>:<EOL><INDENT>self._mark_paid()<EOL><DEDENT>elif total_paid == <NUM_LIT:0> and num_payments > <NUM_LIT:0>:<EOL><INDENT>self._mark_void()<EOL><DEDENT><DEDENT>elif old_status == commerce.Invoice.STATUS_PAID:<EOL><INDENT>if remainder > <NUM_LIT:0>:<EOL><INDENT>self._mark_refunded()<EOL><DEDENT><DEDENT>elif old_status == commerce.Invoice.STATUS_REFUNDED:<EOL><INDENT>pass<EOL><DEDENT>elif old_status == commerce.Invoice.STATUS_VOID:<EOL><INDENT>pass<EOL><DEDENT>residual = <NUM_LIT:0><EOL>if self.invoice.is_paid:<EOL><INDENT>if remainder < <NUM_LIT:0>:<EOL><INDENT>residual = <NUM_LIT:0> - remainder<EOL><DEDENT><DEDENT>elif self.invoice.is_void or self.invoice.is_refunded:<EOL><INDENT>residual = total_paid<EOL><DEDENT>if residual != <NUM_LIT:0>:<EOL><INDENT>CreditNoteController.generate_from_invoice(self.invoice, residual)<EOL><DEDENT>self.email_on_invoice_change(<EOL>self.invoice,<EOL>old_status,<EOL>self.invoice.status,<EOL>)<EOL>

Updates the status of this invoice based upon the total
        payments.


cart = self.invoice.cart<EOL>if cart:<EOL><INDENT>cart.status = commerce.Cart.STATUS_PAID<EOL>cart.save()<EOL><DEDENT>self.invoice.status = commerce.Invoice.STATUS_PAID<EOL>self.invoice.save()<EOL>

Marks the invoice as paid, and updates the attached cart if
        necessary.


self._release_cart()<EOL>self.invoice.status = commerce.Invoice.STATUS_REFUNDED<EOL>self.invoice.save()<EOL>

Marks the invoice as refunded, and updates the attached cart if
        necessary.


self.invoice.status = commerce.Invoice.STATUS_VOID<EOL>self.invoice.save()<EOL>