~homeworkprod/byceps

ref: 87b31ba68669551f699c7d12cf18401663b2d043 byceps/byceps/services/shop/cart/models.py -rw-r--r-- 1.6 KiB
87b31ba6 — Jochen Kupperschmidt Fix type errors 6 months 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
61
"""
byceps.services.shop.cart.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from decimal import Decimal
from typing import Sequence

from ....util.instances import ReprBuilder

from ..article.transfer.models import Article


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

    def __init__(self, article: Article, 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: Article, 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()