~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/shop/cart/models.py -rw-r--r-- 1.5 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
byceps.services.shop.cart.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from decimal import Decimal
from typing import List, Sequence

from ....util.instances import ReprBuilder

from ..article.models.article import Article as DbArticle


class CartItem:
    """An article with a quantity."""

    def __init__(self, article: DbArticle, quantity: int) -> None:
        if quantity < 1:
            raise ValueError('Quantity must be a positive number.')

        self.article = article
        self.quantity = quantity
        self.line_amount = article.price * quantity

    def __repr__(self) -> str:
        return ReprBuilder(self) \
            .add('article', self.article.item_number) \
            .add_with_lookup('quantity') \
            .add_with_lookup('line_amount') \
            .build()


class Cart:
    """A shopping cart."""

    def __init__(self) -> None:
        self._items: List[CartItem] = []

    def add_item(self, article: DbArticle, quantity: int) -> None:
        item = CartItem(article, quantity)
        self._items.append(item)

    def get_items(self) -> Sequence[CartItem]:
        return self._items

    def calculate_total_amount(self) -> Decimal:
        return sum(item.line_amount for item in self._items)

    def is_empty(self) -> bool:
        return not self._items

    def __repr__(self) -> str:
        item_count = len(self._items)

        return ReprBuilder(self) \
            .add_custom(f'{item_count:d} items') \
            .build()