diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..3851d83a 100644 --- a/src/part2/cart.py +++ b/src/part2/cart.py @@ -11,8 +11,8 @@ from typing import Final -from .crud import read_product, update_product # noqa: F401 -from .storage import ( # noqa: F401 +from .crud import read_product, update_product +from .storage import ( NAME_INDEX, PRICE_INDEX, QUANTITY_INDEX, @@ -22,9 +22,16 @@ type CartLine = tuple[int, int] -# TODO: задайте позиции полей внутри кортежа CartLine + LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 + + +def find_cart_line(cart: list[CartLine], product_id: int) -> CartLine | None: + for line in cart: + if line[LINE_PRODUCT_ID_INDEX] == product_id: + return line + return None def add_to_cart( @@ -33,28 +40,33 @@ def add_to_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from the store into ``cart``. - - The product is looked up in ``storage``. If it is missing, a message is - printed (by :func:`~src.part2.crud.read_product`) and nothing - changes. If the store holds fewer units than requested, an explanatory - message is printed and nothing changes. Otherwise the store record is - decremented by ``quantity`` and the cart line for ``product_id`` gains - ``quantity`` units -- a new line is created when the cart had none. - - Args: - storage: The product store to draw stock from; modified in place on - success. - cart: The cart to add the units to; modified in place on success. - product_id: The identifier of the product to add. - quantity: Number of units to move into the cart. - - Returns: - The cart line for ``product_id`` after the addition, or ``None`` - when the product is unknown or the store cannot cover the request. - """ - # TODO: реализуйте функцию - return (0, 0) + product = read_product(storage, product_id) + if product is None: + return None + + in_stock = product[QUANTITY_INDEX] + if in_stock < quantity: + print( + f"not enough stock for product {product_id}: " + f"{in_stock} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], in_stock - quantity), + ) + + line = find_cart_line(cart, product_id) + if line is None: + new_line = (product_id, quantity) + cart.append(new_line) + return new_line + + new_line = (product_id, line[LINE_QUANTITY_INDEX] + quantity) + cart[cart.index(line)] = new_line + return new_line def remove_from_cart( @@ -63,27 +75,34 @@ def remove_from_cart( product_id: int, quantity: int, ) -> CartLine | None: - """Move ``quantity`` units of ``product_id`` from ``cart`` back to the store. - - The cart line for ``product_id`` is looked up. If there is none, a - message is printed and nothing changes. If the line holds fewer units - than requested, an explanatory message is printed and nothing changes. - Otherwise the cart line loses ``quantity`` units -- the line is dropped - when it reaches zero -- and the store record gains ``quantity`` units - back. - - Args: - storage: The product store to return stock to; modified in place on - success. - cart: The cart to take the units from; modified in place on - success. - product_id: The identifier of the product to remove. - quantity: Number of units to move back into the store. - - Returns: - The cart line for ``product_id`` after the removal (a quantity of - zero means the line was dropped), or ``None`` when the cart has no - line for the product or holds too few units. - """ - # TODO: реализуйте функцию - return (0, 0) + line = find_cart_line(cart, product_id) + if line is None: + print(f"product {product_id} is not in the cart") + return None + + in_cart = line[LINE_QUANTITY_INDEX] + if in_cart < quantity: + print( + f"cart holds only {in_cart} unit(s) of product {product_id}, " + f"cannot remove {quantity}" + ) + return None + + product = read_product(storage, product_id) + if product is None: + return None + + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], product[QUANTITY_INDEX] + quantity), + ) + + remaining = in_cart - quantity + if remaining == 0: + cart.remove(line) + return (product_id, 0) + + new_line = (product_id, remaining) + cart[cart.index(line)] = new_line + return new_line diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..6c0ad070 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -14,66 +14,42 @@ from decimal import Decimal -from .storage import ( # noqa: F401 +from .storage import ( NAME_INDEX, PRODUCT_ID_INDEX, PRODUCT_ID_MIN, Product, ) -from .utils import normalize_price # noqa: F401 +from .utils import normalize_price def generate_product_id(storage: list[Product]) -> int: - """Choose the identifier for the next product added to ``storage``. - - Args: - storage: The product store to inspect. - - Returns: - One past the greatest identifier currently held in ``storage``, or - :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is - empty. - """ - # TODO: реализуйте функцию - return 0 + if not storage: + return PRODUCT_ID_MIN + return max(p[PRODUCT_ID_INDEX] for p in storage) + 1 def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: - """Append a new product to ``storage`` and return its new identifier. + name, price, quantity = fields - Args: - storage: The product store to append to; modified in place on - success. - fields: A ``(name, price, quantity)`` tuple describing the product. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. + for product in storage: + if product[NAME_INDEX] == name: + print(f"product name '{name}' is already taken") + return None - Returns: - The identifier generated for the new product, or ``None`` when a - product with the same name already exists. In the ``None`` case - ``storage`` is left unchanged and a message naming the clashing - name is printed. - """ - # TODO: реализуйте функцию - return 0 + product_id = generate_product_id(storage) + storage.append((product_id, name, normalize_price(price), quantity)) + return product_id def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. - - Args: - storage: The product store to search. - product_id: The identifier to look up. - - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + return product + print(f"no product with id {product_id}") + return None def update_product( @@ -81,40 +57,22 @@ def update_product( product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. - - The identifier itself is preserved; only ``name``, ``price`` and - ``quantity`` are replaced. + name, price, quantity = fields - Args: - storage: The product store to modify; the matching record is - replaced in place on success. - product_id: The identifier of the product to change. - fields: A ``(name, price, quantity)`` tuple with the new values. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + updated = (product_id, name, normalize_price(price), quantity) + storage[i] = updated + return updated - Returns: - The updated ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (``storage`` is - left unchanged and a message is printed). - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + print(f"no product with id {product_id}") + return None def delete_product(storage: list[Product], product_id: int) -> int | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - ``product_id`` when a product was removed, or ``None`` when no - product carried that identifier (``storage`` is left unchanged and - a message is printed). - """ - # TODO: реализуйте функцию - return 0 + for i, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + del storage[i] + return product_id + print(f"no product with id {product_id}") + return None diff --git a/src/part2/storage.py b/src/part2/storage.py index b63d5fc7..35821c5f 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -26,9 +26,9 @@ # TODO: задайте позиции полей внутри кортежа Product PRODUCT_ID_INDEX: Final = 0 -NAME_INDEX: Final = 0 -PRICE_INDEX: Final = 0 -QUANTITY_INDEX: Final = 0 +NAME_INDEX: Final = 1 +PRICE_INDEX: Final = 2 +QUANTITY_INDEX: Final = 3 # TODO: задайте идентификатор первого товара в пустом хранилище -PRODUCT_ID_MIN: Final[int] = 0 +PRODUCT_ID_MIN: Final[int] = 1 diff --git a/src/part2/utils.py b/src/part2/utils.py index 11bd7a76..11b507bf 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,24 +6,14 @@ currency values free of binary floating-point error. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +from decimal import ROUND_HALF_UP, Decimal from typing import Final # TODO: задайте число знаков после запятой и шаг квантования -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) def normalize_price(price: Decimal) -> Decimal: - """Round a price to the precision every stored record uses. - - Args: - price: The raw price amount. - - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию - return Decimal(0) + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..a045aa33 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -20,68 +20,63 @@ from decimal import Decimal -from .storage import ( # noqa: F401 +from .storage import ( NAME_INDEX, PRODUCT_ID_INDEX, PRODUCT_ID_MIN, Product, ) -from .utils import normalize_price, normalize_product_name # noqa: F401 +from .utils import normalize_price, normalize_product_name def generate_product_id(storage: list[Product]) -> int: - """Choose the identifier for the next product added to ``storage``. - - Args: - storage: The product store to inspect. - - Returns: - One past the greatest identifier currently held in ``storage``, or - :data:`~src.part3.storage.PRODUCT_ID_MIN` when ``storage`` is - empty. - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if not storage: + return PRODUCT_ID_MIN + return max(p[PRODUCT_ID_INDEX] for p in storage) + 1 def create_product( storage: list[Product], fields: tuple[str, Decimal, int] ) -> int | None: - """Append a new product to ``storage`` and return its new identifier. - - Args: - storage: The product store to append to; modified in place on - success. - fields: A ``(name, price, quantity)`` tuple describing the product. - ``name`` is normalised (surrounding whitespace stripped, - lower-cased) before it is stored or compared. ``price`` is a - :class:`~decimal.Decimal` amount and is rounded to the stored - money precision before it is saved. - - Returns: - The identifier generated for the new product, or ``None`` when - ``name`` is blank once normalised or a product with the same - normalised name already exists. In the ``None`` case ``storage`` - is left unchanged and an explanatory message is printed. - """ - # TODO: реализуйте функцию - return 0 + name = normalize_product_name(fields[0]) + if not name: + print("product name must not be blank") + return None + if _name_taken(storage, name): + print(f"product name '{name}' is already taken") + return None + + product_id = generate_product_id(storage) + storage.append((product_id, name, normalize_price(fields[1]), fields[2])) + return product_id def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + return product + print(f"no product with id {product_id}") + return None + - Args: - storage: The product store to search. - product_id: The identifier to look up. +def _find_index(storage: list[Product], product_id: int) -> int | None: + return next( + ( + i + for i, product in enumerate(storage) + if product[PRODUCT_ID_INDEX] == product_id + ), + None, + ) - Returns: - The matching ``(product_id, name, price, quantity)`` record, or - ``None`` when no product carries that identifier (a message is - printed in that case). - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return (0, "", Decimal(0), 0) + +def _name_taken( + storage: list[Product], name: str, except_id: int | None = None +) -> bool: + return any( + product[NAME_INDEX] == name and product[PRODUCT_ID_INDEX] != except_id + for product in storage + ) def update_product( @@ -89,43 +84,29 @@ def update_product( product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. - - The identifier itself is preserved; only ``name``, ``price`` and - ``quantity`` are replaced. - - Args: - storage: The product store to modify; the matching record is - replaced in place on success. - product_id: The identifier of the product to change. - fields: A ``(name, price, quantity)`` tuple with the new values. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. - - Returns: - The updated ``(product_id, name, price, quantity)`` record, or - ``None`` when ``name`` is blank once normalised, no product - carries that identifier, or the normalised name is already taken - by another product. In every ``None`` case ``storage`` is left - unchanged and an explanatory message is printed. Renaming a - product to its own current name is allowed. - """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + name = normalize_product_name(fields[0]) + if not name: + print("product name must not be blank") + return None + + index = _find_index(storage, product_id) + if index is None: + print(f"no product with id {product_id}") + return None + + if _name_taken(storage, name, except_id=product_id): + print(f"product name '{name}' is already taken") + return None + + updated = (product_id, name, normalize_price(fields[1]), fields[2]) + storage[index] = updated + return updated def delete_product(storage: list[Product], product_id: int) -> int | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_id: The identifier of the product to remove. - - Returns: - ``product_id`` when a product was removed, or ``None`` when no - product carried that identifier (``storage`` is left unchanged and - a message is printed). - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + index = _find_index(storage, product_id) + if index is None: + print(f"no product with id {product_id}") + return None + del storage[index] + return product_id diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index c5feeb0b..a97085e8 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,69 +29,120 @@ it. """ -from decimal import Decimal, InvalidOperation # noqa: F401 +from collections.abc import Callable +from decimal import Decimal, InvalidOperation from typing import Final -from .crud import ( # noqa: F401 +from .crud import ( create_product, delete_product, read_product, update_product, ) from .storage import Product -from .utils import get_storage_str_representation # noqa: F401 +from .utils import get_storage_str_representation -# TODO: задайте приглашение и текст справки -PROMPT: Final[str] = "" -HELP_TEXT: Final[str] = "" +PROMPT: Final[str] = "admin> " +HELP_TEXT: Final[str] = """Available commands: + help show this message + exit leave the console + show print the whole store as a table + create add a product, print its new id + read print the product with that id + update overwrite that product's fields + delete remove the product with that id +For create and update the price and quantity are the last two words of the +line; everything before them is the product name, so it may contain spaces +(for example "Gibson SG Junior") and needs no quoting.""" -def show_help() -> None: - """Print the command reference to stdout. +_NAME_AND_TWO_NUMBERS: Final = 3 +_ID_AND_NAME_AND_TWO_NUMBERS: Final = 4 +_VARIADIC: Final = frozenset({"create", "update"}) - The text is the module-level :data:`HELP_TEXT` constant, printed as - is: a heading, one line per command with a short description, and a - note on how multi-word names are parsed. - """ - # TODO: реализуйте функцию + +def show_help() -> None: + print(HELP_TEXT) def print_result(result: object) -> None: - """Print a CRUD result to stdout unless it is ``None``. + if result is not None: + print(result) - Args: - result: The value returned by a CRUD operation. ``None`` means the - operation already reported its own failure, so nothing is - printed in that case. - """ - # TODO: реализуйте функцию +def _parse_fields(args: list[str]) -> tuple[str, Decimal, int]: + name = " ".join(args[:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + return name, price, quantity -def run_command(storage: list[Product], line: str) -> bool: - """Parse one console line and carry out the command it names. - - Args: - storage: The product store shared across the session; mutated in - place by the ``create``, ``update`` and ``delete`` commands. - line: One line of console input, already stripped of surrounding - whitespace. - - Returns: - ``True`` to keep the read-eval-print loop running, or ``False`` - once the ``exit`` command has been seen. A line that is not a - known command prints a notice and still returns ``True``. - - Raises: - ValueError: If an id or quantity argument of a CRUD command does - not parse as a base-10 integer. - decimal.InvalidOperation: If the price argument of ``create`` or - ``update`` does not parse as a decimal number. - """ - # TODO: реализуйте функцию + +def _run_read(storage: list[Product], args: list[str]) -> None: + print_result(read_product(storage, int(args[0]))) + + +def _run_delete(storage: list[Product], args: list[str]) -> None: + print_result(delete_product(storage, int(args[0]))) + + +def _run_create(storage: list[Product], args: list[str]) -> None: + print_result(create_product(storage, _parse_fields(args))) + + +def _run_update(storage: list[Product], args: list[str]) -> None: + product_id = int(args[0]) + fields = _parse_fields(args[1:]) + print_result(update_product(storage, product_id, fields)) + + +def _run_show(storage: list[Product], args: list[str]) -> None: + print(get_storage_str_representation(storage)) + + +def _run_help(storage: list[Product], args: list[str]) -> None: + show_help() + + +def _run_exit(storage: list[Product], args: list[str]) -> bool | None: return False +type _Handler = Callable[[list[Product], list[str]], bool | None] + + +_COMMANDS: Final[dict[str, tuple[_Handler, int | None]]] = { + "help": (_run_help, 0), + "exit": (_run_exit, 0), + "show": (_run_show, 0), + "read": (_run_read, 1), + "delete": (_run_delete, 1), + "create": (_run_create, _NAME_AND_TWO_NUMBERS), + "update": (_run_update, _ID_AND_NAME_AND_TWO_NUMBERS), +} + + +def _accepts(verb: str, args: list[str]) -> bool: + _, arity = _COMMANDS[verb] + if arity is None: + return True + if verb in _VARIADIC: + return len(args) >= arity + return len(args) == arity + + +def run_command(storage: list[Product], line: str) -> bool: + words = line.split() + verb = words[0] if words else "" + + if verb not in _COMMANDS or not _accepts(verb, words[1:]): + print(f"'{line}' is not a command") + return True + + handler, _ = _COMMANDS[verb] + return handler(storage, words[1:]) is not False + + def main() -> None: """Run the admin console until the ``exit`` command is entered. diff --git a/src/part3/storage.py b/src/part3/storage.py index c5e34be5..36e9af7f 100644 --- a/src/part3/storage.py +++ b/src/part3/storage.py @@ -27,9 +27,9 @@ # TODO: задайте позиции полей внутри кортежа Product (используйте своё решение # части 2) PRODUCT_ID_INDEX: Final = 0 -NAME_INDEX: Final = 0 -PRICE_INDEX: Final = 0 -QUANTITY_INDEX: Final = 0 +NAME_INDEX: Final = 1 +PRICE_INDEX: Final = 2 +QUANTITY_INDEX: Final = 3 # TODO: задайте идентификатор первого товара в пустом хранилище -PRODUCT_ID_MIN: Final[int] = 0 +PRODUCT_ID_MIN: Final[int] = 1 diff --git a/src/part3/utils.py b/src/part3/utils.py index 318ded0b..7d16258f 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,7 +18,8 @@ the longest value it holds in that particular call. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +import re +from decimal import ROUND_HALF_UP, Decimal from typing import Final from .storage import Product @@ -28,68 +29,47 @@ # Quantisation step derived from PRICE_PRECISION, e.g. Decimal("0.01"). # TODO: задайте число знаков после запятой и шаг квантования (используйте своё # решение части 2) -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) +_WHITESPACE_RUN: Final = re.compile(r"\s+") +_CELL_PADDING: Final = 2 # Column headers of the table produced by get_storage_str_representation, # left to right. The width of each column is not fixed here -- it is # measured per call from the data (see the function). # TODO: задайте заголовки столбцов таблицы -TABLE_HEADERS: Final[tuple[str, ...]] = () +TABLE_HEADERS: Final[tuple[str, ...]] = ("ID", "name", "price", "quantity") def normalize_price(price: Decimal) -> Decimal: - """Round a price to the precision every stored record uses. + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) - Args: - price: The raw price amount. - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return Decimal(0) +def normalize_product_name(name: str) -> str: + return _WHITESPACE_RUN.sub(" ", name.strip()).lower() -def normalize_product_name(name: str) -> str: - """Reduce a product name to the canonical form the store keeps. +def _measure_widths(rows: list[tuple[str, ...]]) -> list[int]: + return [ + max(len(header), *(len(row[i]) for row in rows)) + for i, header in enumerate(TABLE_HEADERS) + ] - Args: - name: The raw product name. - Returns: - ``name`` with every leading and trailing whitespace character - removed, every internal run of whitespace (spaces, tabs and the - like) collapsed to a single space, and the rest lower-cased. For - example ``"abc def\tghi\tjkl"`` becomes ``"abc def ghi jkl"``. - The result is an empty string when ``name`` holds nothing but - whitespace. - """ - # TODO: реализуйте функцию - return "" +def _render_row(cells: tuple[str, ...], widths: list[int]) -> str: + padded = (cell.ljust(width) for cell, width in zip(cells, widths)) + return "| " + " | ".join(padded) + " |" -# TODO: при необходимости добавьте свои вспомогательные функции +def _render_separator(widths: list[int]) -> str: + runs = ("-" * (width + _CELL_PADDING) for width in widths) + return "|" + "|".join(runs) + "|" def get_storage_str_representation(storage: list[Product]) -> str: - """Render the product store as a text table with data-sized columns. - - The table has the columns named by :data:`TABLE_HEADERS` -- id, name, - price and quantity. Each column is made exactly as wide as the longest - value it carries in this call (its header counted), so the columns - line up when the string is printed to a terminal and no value is ever - truncated. - - Args: - storage: The product store to render. - - Returns: - A multi-line string: a header row, a dashed separator row, then - one row per product in ``storage`` in list order. When ``storage`` - is empty only the header and separator rows are returned, sized to - the header labels. - """ - # TODO: реализуйте функцию - return "" + rows = [tuple(str(value) for value in product) for product in storage] + widths = _measure_widths(rows) + + lines = [_render_row(TABLE_HEADERS, widths), _render_separator(widths)] + lines.extend(_render_row(row, widths) for row in rows) + return "\n".join(lines)