diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..7a112a77 100644 --- a/src/part1/constants.py +++ b/src/part1/constants.py @@ -19,20 +19,20 @@ # Все константы, зависящие от ёмкостей *_BITS, должны вычисляться из них. # Twitter's original Snowflake epoch: 2010-11-04 01:42:54.657 UTC. -EPOCH_MS_DEFAULT: Final[int] = 0 +EPOCH_MS_DEFAULT: Final[int] = 1288834974657 # Node identifier used when the caller does not supply one. -NODE_ID_DEFAULT: Final[int] = 0 +NODE_ID_DEFAULT: Final[int] = 1 # Width of each field, in bits. -TIMESTAMP_BITS: Final[int] = 0 -NODE_ID_BITS: Final[int] = 0 -SEQUENCE_ID_BITS: Final[int] = 0 +TIMESTAMP_BITS: Final[int] = 41 +NODE_ID_BITS: Final[int] = 10 +SEQUENCE_ID_BITS: Final[int] = 12 # Largest value each field can hold. -TIMESTAMP_MS_MAX: Final[int] = 0 -NODE_ID_MAX: Final[int] = 0 -SEQUENCE_ID_MAX: Final[int] = 0 +TIMESTAMP_MS_MAX: Final[int] = 2**TIMESTAMP_BITS - 1 +NODE_ID_MAX: Final[int] = 2**NODE_ID_BITS - 1 +SEQUENCE_ID_MAX: Final[int] = 2**SEQUENCE_ID_BITS - 1 # Здесь можно добавить собственные вспомогательные константы # (например, сдвиги полей при сборке идентификатора). diff --git a/src/part1/snowflake.py b/src/part1/snowflake.py index d3abf050..5b67e6f9 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -13,73 +13,42 @@ :func:`decode_node_id` and :func:`decode_sequence_id`. """ -import time # noqa: F401 +import time -from .constants import ( # noqa: F401 +from .constants import ( EPOCH_MS_DEFAULT, + NODE_ID_BITS, NODE_ID_DEFAULT, NODE_ID_MAX, + SEQUENCE_ID_BITS, SEQUENCE_ID_MAX, TIMESTAMP_MS_MAX, ) def read_current_millis(epoch_ms: int) -> int: - """Read the number of milliseconds elapsed since the custom epoch. + current_time = int(time.time() * 1000) - Args: - epoch_ms: The custom epoch expressed as Unix milliseconds. - - Returns: - The count of whole milliseconds between ``epoch_ms`` and now. May be - negative if ``epoch_ms`` lies in the future. - """ - # TODO: реализуйте функцию - return 0 + return current_time - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: - """Read the timestamp field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced against the same epoch. - epoch_ms: The epoch the identifier was generated against. Defaults to - the original Twitter epoch (2010-11-04 01:42:54.657 UTC). + time_mark = snowflake_id >> (NODE_ID_BITS + SEQUENCE_ID_BITS) - Returns: - The absolute Unix time in milliseconds at which the identifier was - generated. - """ - # TODO: реализуйте функцию - return 0 + return time_mark + epoch_ms def decode_node_id(snowflake_id: int) -> int: - """Read the node identifier field out of a Snowflake identifier. + without_seq = snowflake_id >> SEQUENCE_ID_BITS + node_id = without_seq & NODE_ID_MAX - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. - - Returns: - The node identifier packed into ``snowflake_id``, in the range - ``[0, NODE_ID_MAX]``. - """ - # TODO: реализуйте функцию - return 0 + return node_id def decode_sequence_id(snowflake_id: int) -> int: - """Read the sequence counter field out of a Snowflake identifier. - - Args: - snowflake_id: An identifier produced by :func:`generate_snowflake_id`. + sequence_id = snowflake_id & SEQUENCE_ID_MAX - Returns: - The per-millisecond sequence counter packed into ``snowflake_id``, in - the range ``[0, SEQUENCE_ID_MAX]``. - """ - # TODO: реализуйте функцию - return 0 + return sequence_id def generate_snowflake_id( @@ -87,28 +56,20 @@ def generate_snowflake_id( node_id: int = NODE_ID_DEFAULT, epoch_ms: int = EPOCH_MS_DEFAULT, ) -> int | None: - """Build and return a Snowflake identifier for the current millisecond. - - The function is stateless: the caller passes the per-millisecond sequence - counter explicitly. It is the caller's responsibility to increment - ``sequence_id`` for identifiers minted within the same millisecond and to - reset it once the clock advances. - - Args: - sequence_id: The per-millisecond sequence counter, in the range - ``[0, SEQUENCE_ID_MAX]``. - node_id: The identifier of this node, in the range ``[0, NODE_ID_MAX]``. - Optional; defaults to ``NODE_ID_DEFAULT``. - epoch_ms: The start of the epoch as Unix milliseconds. Optional; - defaults to the original Twitter epoch (2010-11-04 01:42:54.657 - UTC). - - Returns: - The Snowflake identifier as a positive 63-bit integer, or ``None`` if - ``node_id`` is outside ``[0, NODE_ID_MAX]``, ``sequence_id`` is outside - ``[0, SEQUENCE_ID_MAX]``, or the elapsed time no longer fits in the - timestamp field (roughly 69 years after ``epoch_ms``). In each of those - cases an explanatory message is printed to stdout first. - """ - # TODO: реализуйте функцию - return 0 + time_stamp = read_current_millis(epoch_ms) + if not (0 <= node_id <= NODE_ID_MAX): + print("node_id must be in [0, 2**10-1]") + return None + elif not (0 <= sequence_id <= SEQUENCE_ID_MAX): + print("sequence_id must be in [0, 2**12-1]") + return None + elif time_stamp > TIMESTAMP_MS_MAX: + print("overflows") + return None + snowflake_id = ( + (time_stamp << (NODE_ID_BITS + SEQUENCE_ID_BITS)) + | (node_id << SEQUENCE_ID_BITS) + | sequence_id + ) + + return snowflake_id diff --git a/src/part2/TASK.md b/src/part2/TASK.md deleted file mode 100644 index 25736d9c..00000000 --- a/src/part2/TASK.md +++ /dev/null @@ -1,213 +0,0 @@ -# Задача: CRUD и корзина для интернет-магазина - -## Легенда - -Наше хранилище данных уже умеет выдавать уникальные идентификаторы, но пока это -лишь «голая» база: записи лежат в памяти, и работать с ними приходится вручную. -Чтобы проверить, что хранилище годится для настоящей прикладной задачи, мы -построим на нём серверную часть простого интернет-магазина: каталог товаров и -корзину покупателя. - -Если писать такой код «в лоб», быстро возникают проблемы: - -- записи о товарах разбросаны по программе, и каждый кусок кода сам решает, как - их создавать, менять и удалять, — в итоге в каталоге появляются дубликаты и - «осиротевшие» идентификаторы; -- деньги хранят во `float`, и суммы вроде `0.1 + 0.2` начинают расходиться с - копейками, а в бухгалтерии такое недопустимо; -- товар «переезжает» между складом и корзиной в два отдельных действия, и если - одно из них не выполнилось, товар пропадает или появляется из воздуха. - -Именно эти вопросы решают классические CRUD-операции (create, read, update, -delete) над единым хранилищем, аккуратная работа с ценой через `Decimal` и -операции корзины, которые сохраняют общее количество товара. Их нам и предстоит -написать. Позже на этих функциях мы построим интерфейс работы с нашей базой. - -## Контекст - -Нужно реализовать серверную часть простого интернет-магазина: хранилище товаров, -операции CRUD над ним и работу с корзиной покупателя. Настоящая база данных не -используется — хранилище это список кортежей в оперативной памяти. - -Решение состоит из четырёх модулей: - -- `storage.py` — форма записи о товаре и связанные с ней константы; -- `utils.py` — округление денежных сумм; -- `crud.py` — создание, чтение, изменение и удаление записей о товарах; -- `cart.py` — перенос товаров между хранилищем и корзиной. - -Все функции, кроме `find_cart_line` и `change_cart_quantity`, на неуспешном пути -ничего не бросают: печатают сообщение об ошибке в stdout и возвращают `None`. - -## Формат записи о товаре - -Запись о товаре (`Product`) — кортеж из четырёх полей, перечисленных по порядку: - -| Поле | Тип | Что хранит | -| ------------- | --------- | ------------------------------------------------------------------ | -| идентификатор | `int` | уникальный положительный ключ, назначается при создании записи | -| наименование | `str` | человекочитаемое имя, уникальное в пределах хранилища | -| цена | `Decimal` | цена за единицу, округлённая до фиксированного числа знаков дроби | -| количество | `int` | число единиц товара на складе | - -Позиции полей задаются константами `*_INDEX`, чтобы обращение к кортежу не -использовало числовые литералы. - -Строка корзины (`CartLine`) — кортеж `(идентификатор товара, количество)`. В -корзине не более одной строки на каждый товар. - -## Модуль `storage.py` - -Определите: - -- `Product` — псевдоним типа `tuple[int, str, Decimal, int]`. -- `PRODUCT_ID_INDEX`, `NAME_INDEX`, `PRICE_INDEX`, `QUANTITY_INDEX` — позиции - полей в кортеже `Product`: `0`, `1`, `2`, `3`. Каждая аннотирована - `typing.Final`. -- `PRODUCT_ID_MIN: Final[int] = 1` — идентификатор, который получает первый - товар, добавленный в пустое хранилище. - -## Модуль `utils.py` - -- `PRICE_PRECISION: Final[int] = 2` — число знаков после запятой, до которого - округляется каждая сохраняемая цена. -- `PRICE_STEP: Final` — шаг квантования. Вычисляется из `PRICE_PRECISION` - (`Decimal(1).scaleb(-PRICE_PRECISION)`, то есть `Decimal("0.01")` при значении - по умолчанию), а не задаётся числом напрямую; при изменении `PRICE_PRECISION` - шаг меняется согласованно. - -### `normalize_price(price: Decimal) -> Decimal` - -- **Вход:** `price` — произвольная денежная сумма типа `Decimal`. -- **Выход:** та же сумма, приведённая к `PRICE_PRECISION` знакам после запятой; - ровно половина шага округляется вверх (режим `ROUND_HALF_UP`). - -Примеры: `Decimal("12.999") → Decimal("13.00")`, -`Decimal("2.3451") → Decimal("2.35")`, `Decimal("2.3449") → Decimal("2.34")`, -`Decimal("5") → Decimal("5.00")` (число знаков дроби в результате всегда равно -`PRICE_PRECISION`). - -## Модуль `crud.py` - -Каждая функция получает хранилище `storage: list[Product]` первым параметром и -меняет его на месте. - -### `generate_product_id(storage: list[Product]) -> int` - -- **Вход:** хранилище. -- **Выход:** если хранилище пустое — `PRODUCT_ID_MIN`; иначе — наибольший - идентификатор среди записей плюс `1`. Пропуски в нумерации (например, - оставшиеся после удаления) не переиспользуются — берётся именно максимум. - -### `create_product(storage: list[Product], fields: tuple[str, Decimal, int]) -> int | None` - -- **Вход:** `fields` — кортеж `(наименование, цена, количество)`; `цена` типа - `Decimal`. -- **Выход:** сгенерированный идентификатор новой записи, либо `None`. - -**Поведение.** - -1. Если в хранилище уже есть запись с таким же наименованием — новая запись не - создаётся, хранилище не меняется, печатается сообщение об ошибке, содержащее - это наименование, возвращается `None`. (Например: - `product name '<имя>' is already taken`.) -2. Иначе идентификатор вычисляется через `generate_product_id`, цена приводится - через `normalize_price`, кортеж - `(идентификатор, наименование, нормализованная цена, количество)` добавляется - в хранилище, возвращается идентификатор. - -### `read_product(storage: list[Product], product_id: int) -> Product | None` - -- **Вход:** целочисленный идентификатор. -- **Выход:** запись с этим идентификатором, либо `None`. Если записи нет — - печатается сообщение об ошибке, содержащее переданный идентификатор (например, - `no product with id `). - -### `update_product(storage: list[Product], product_id: int, fields: tuple[str, Decimal, int]) -> Product | None` - -- **Вход:** идентификатор и кортеж `(наименование, цена, количество)` с новыми - значениями полей. -- **Выход:** изменённая запись - `(идентификатор, наименование, нормализованная цена, количество)` — сам - идентификатор сохраняется прежним, остальные три поля заменяются, цена - приводится через `normalize_price`. Если записи с таким идентификатором нет — - хранилище не меняется, печатается сообщение об ошибке с идентификатором - (`no product with id `), возвращается `None`. Уникальность нового - наименования не проверяется. - -### `delete_product(storage: list[Product], product_id: int) -> int | None` - -- **Вход:** идентификатор. -- **Выход:** тот же идентификатор, если запись была найдена и удалена из - хранилища. Если записи нет — хранилище не меняется, печатается сообщение об - ошибке с идентификатором (`no product with id `), возвращается `None`. - -## Модуль `cart.py` - -- `CartLine` — псевдоним типа `tuple[int, int]` - (`(идентификатор товара, количество)`). -- `LINE_PRODUCT_ID_INDEX`, `LINE_QUANTITY_INDEX` — позиции полей строки корзины - (`0`, `1`), аннотированы `typing.Final`. - -### `add_to_cart(storage: list[Product], cart: list[CartLine], product_id: int, quantity: int) -> CartLine | None` - -Переносит `quantity` единиц товара `product_id` со склада в корзину. - -- **Вход:** хранилище, корзина, идентификатор товара, количество для добавления. -- **Выход:** строка корзины для `product_id` после добавления, либо `None`. - -**Поведение.** Проверки выполняются в этом порядке; при первой же неудаче -остальные действия не выполняются: - -1. Товар ищется в хранилище (через `read_product`). Если его нет — `read_product` - печатает сообщение с идентификатором, `add_to_cart` возвращает `None`, больше - ничего не меняется. -2. Иначе количество на складе сравнивается с запрошенным. Если на складе строго - меньше, чем `quantity` — печатается сообщение об ошибке, содержащее - идентификатор товара (например: - `not enough stock for product : <склад> available, requested`), - возвращается `None`, ничего не меняется. Запрос ровно на всё имеющееся - количество (`quantity == склад`) допустим. -3. Иначе количество товара в хранилище уменьшается на `quantity` (наименование и - цена не меняются), а в корзину добавляется `quantity` единиц: если строка для - товара уже была — увеличивается её количество, иначе создаётся новая строка. - Возвращается получившаяся строка корзины. - -### `remove_from_cart(storage: list[Product], cart: list[CartLine], product_id: int, quantity: int) -> CartLine | None` - -Переносит `quantity` единиц товара `product_id` из корзины обратно на склад. -Принимает тот же набор аргументов, что и `add_to_cart`. - -- **Выход:** строка корзины для `product_id` после удаления (количество `0` - означает, что строка удалена), либо `None`. - -**Поведение.** Проверки в этом порядке: - -1. Строка корзины для `product_id` ищется через `find_cart_line`. Если её нет — - печатается сообщение об ошибке, содержащее идентификатор (например: - `product is not in the cart`), возвращается `None`, ничего не меняется. -2. Иначе количество в строке корзины сравнивается с запрошенным. Если в корзине - строго меньше, чем `quantity` — печатается сообщение об ошибке с - идентификатором (например: - `cart holds only <в корзине> unit(s) of product , cannot remove `), - возвращается `None`, ничего не меняется. -3. Товар ищется в хранилище через `read_product`; если его там нет — - возвращается `None` (сообщение печатает `read_product`). -4. Иначе количество товара в хранилище увеличивается на `quantity`, а из строки - корзины вычитается `quantity` (наименование и цена не меняются); если - количество в строке стало `0`, строка удаляется. Возвращается получившаяся - строка корзины. - -## Инварианты - -- Для любой успешно созданной записи - `read_product(storage, create_product(storage, (name, price, qty)))` возвращает - `(id, name, normalize_price(price), qty)`. -- После `delete_product(storage, id)` вызов `read_product(storage, id)` - возвращает `None`. -- Цена в хранилище всегда нормализована: `normalize_price` применяется при - каждом создании и изменении записи. -- Сохранение количества: при успешном `add_to_cart` или `remove_from_cart` сумма - «количество товара на складе + количество этого товара в корзине» не меняется. -- `add_to_cart(...)` и следующий за ним `remove_from_cart(...)` с тем же - `quantity` возвращают склад и корзину к исходному состоянию. diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..2f8e11f9 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,8 @@ type CartLine = tuple[int, int] -# TODO: задайте позиции полей внутри кортежа CartLine LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 def add_to_cart( @@ -33,28 +32,42 @@ 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) + item = read_product(storage, product_id) + if item is None: + return None + + available = item[QUANTITY_INDEX] + if available < quantity: + print( + f"not enough stock for product {product_id}: {available} available, {quantity} requested" + ) + return None + + new_quantity = available - quantity + new_fields = (item[NAME_INDEX], item[PRICE_INDEX], new_quantity) + update_product(storage, product_id, new_fields) + + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + prev_cart_quant = cart[i][LINE_QUANTITY_INDEX] + new_cart_item = (product_id, prev_cart_quant + quantity) + cart[i] = new_cart_item + return cart[i] + + new_cart_item = (product_id, quantity) + cart.append(new_cart_item) + return new_cart_item + + +def find_cart_line( + cart: list[CartLine], + product_id: int, +) -> CartLine | None: + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + return cart[i] + + return None def remove_from_cart( @@ -63,27 +76,29 @@ 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 not line: + print(f"product {product_id} is not in the cart") + return None + + if quantity > line[LINE_QUANTITY_INDEX]: + print( + f"cart holds only {line[LINE_QUANTITY_INDEX]} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + product = read_product(storage, product_id) + if not product: + return None + + new_quantity = product[QUANTITY_INDEX] + quantity + new_fields = (product[NAME_INDEX], product[PRICE_INDEX], new_quantity) + update_product(storage, product_id, new_fields) + for i in range(len(cart)): + if cart[i][LINE_PRODUCT_ID_INDEX] == product_id: + cart[i] = (product_id, line[LINE_QUANTITY_INDEX] - quantity) + if cart[i][LINE_QUANTITY_INDEX] == 0: + cart.pop(i) + return (product_id, 0) + return cart[i] + return None diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..4e3a9b3e 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -14,66 +14,46 @@ 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``. + if not storage: + return PRODUCT_ID_MIN - 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 + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 + return max_storage 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. - ``price`` is a :class:`~decimal.Decimal` amount and is rounded - to the stored money precision before it is saved. + name, price, quantity = fields + for item in storage: + if name == item[NAME_INDEX]: + 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 + new_id = generate_product_id(storage) + new_price = normalize_price(price) + new_product = (new_id, name, new_price, quantity) + storage.append(new_product) + return new_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. + for i in range(len(storage)): + if storage[i][PRODUCT_ID_INDEX] == product_id: + return storage[i] - 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) + print(f"no product with id '{product_id}'") + return None def update_product( @@ -81,40 +61,23 @@ def update_product( product_id: int, fields: tuple[str, Decimal, int], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. + name, price, quantity = fields + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + new_price = normalize_price(price) + new_item = (product_id, name, new_price, quantity) + storage[i] = new_item + return new_item - 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 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 item in storage: + if item[PRODUCT_ID_INDEX] == product_id: + storage.remove(item) + 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..e4bceff1 100644 --- a/src/part2/storage.py +++ b/src/part2/storage.py @@ -24,11 +24,9 @@ type Product = tuple[int, str, Decimal, int] -# 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..480443e0 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,24 +6,15 @@ 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. + true_price = 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: реализуйте функцию - return Decimal(0) + return true_price diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..d3a42410 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -20,68 +20,51 @@ 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``. + if not storage: + return PRODUCT_ID_MIN - 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 + max_storage = max(product[PRODUCT_ID_INDEX] for product in storage) + 1 + return max_storage 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, price, quantity = fields + new_name = normalize_product_name(name) + if not new_name: + print("product name must not be blank") + return None + for item in storage: + if new_name == item[NAME_INDEX]: + print(f"product name '{new_name}' is already taken") + return None -def read_product(storage: list[Product], product_id: int) -> Product | None: - """Return the product stored under ``product_id``. + new_id = generate_product_id(storage) + new_price = normalize_price(price) + new_product = (new_id, new_name, new_price, quantity) + storage.append(new_product) + return new_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: реализуйте функцию (используйте своё решение части 2) - return (0, "", Decimal(0), 0) +def read_product(storage: list[Product], product_id: int) -> Product | None: + for i in range(len(storage)): + if storage[i][PRODUCT_ID_INDEX] == product_id: + return storage[i] + + print(f"no product with id '{product_id}'") + return None def update_product( @@ -89,43 +72,44 @@ 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, price, quantity = fields + new_name = normalize_product_name(name) + if not new_name: + print("product name must not be blank") + return None + + f = False + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + f = True + break + if f == False: + print(f"no product with id {product_id}") + return None + + for i in range(len(storage)): + if ( + new_name == storage[i][NAME_INDEX] + and product_id != storage[i][PRODUCT_ID_INDEX] + ): + print(f"product name '{new_name}' is already taken") + return None + + for i in range(len(storage)): + if product_id == storage[i][PRODUCT_ID_INDEX]: + new_price = normalize_price(price) + new_item = (product_id, new_name, new_price, quantity) + storage[i] = new_item + return new_item + + 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: реализуйте функцию (используйте своё решение части 2) - return 0 + for item in storage: + if item[PRODUCT_ID_INDEX] == product_id: + storage.remove(item) + return product_id + + print(f"no product with id '{product_id}'") + return None diff --git a/src/part3/run_admin.py b/src/part3/run_admin.py index c5feeb0b..556e2d36 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,67 +29,81 @@ it. """ -from decimal import Decimal, InvalidOperation # noqa: F401 +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. - 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``. - - 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: реализуйте функцию + if result is not None: + print(result) + return 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: реализуйте функцию - return False + match line.split(): + case ["read", prod_id]: + print_result(read_product(storage, int(prod_id))) + return True + + case ["create", *name, price, quantity] if name: + name_str = " ".join(name) + fields_case = (name_str, Decimal(price), int(quantity)) + print_result(create_product(storage, fields_case)) + return True + + case ["update", prod_id, *name, price, quantity] if name: + name_str = " ".join(name) + fields_case = (name_str, Decimal(price), int(quantity)) + print_result(update_product(storage, int(prod_id), fields_case)) + return True + + case ["delete", prod_id]: + print_result(delete_product(storage, int(prod_id))) + return True + + case ["exit"]: + return False + + case ["help"]: + show_help() + return True + + case ["show"]: + print(get_storage_str_representation(storage)) + return True + + case _: + print(f"'{line}' is not a command") + return True def main() -> None: 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..e397a034 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,78 +18,59 @@ the longest value it holds in that particular call. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +from decimal import ROUND_HALF_UP, Decimal from typing import Final -from .storage import Product +from .storage import ( + NAME_INDEX, + PRICE_INDEX, + PRODUCT_ID_INDEX, + QUANTITY_INDEX, + Product, +) -# Number of fractional digits every stored price is rounded to. -# 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) -# 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. - Args: - price: The raw price amount. +def normalize_price(price: Decimal) -> Decimal: + true_price = price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) - Returns: - ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, - with halves rounded up. - """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return Decimal(0) + return true_price def normalize_product_name(name: str) -> str: - """Reduce a product name to the canonical form the store keeps. - - 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 "" - + new_name = " ".join(name.split()).lower() -# TODO: при необходимости добавьте свои вспомогательные функции + return new_name 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 "" + mx_len_id = len(TABLE_HEADERS[0]) + 2 + mx_len_name = len(TABLE_HEADERS[1]) + 2 + mx_len_price = len(TABLE_HEADERS[2]) + 2 + mx_len_quantity = len(TABLE_HEADERS[3]) + 2 + for item in storage: + mx_len_id = max(mx_len_id, len(str(item[PRODUCT_ID_INDEX])) + 2) + mx_len_name = max(mx_len_name, len(item[NAME_INDEX]) + 2) + mx_len_price = max(mx_len_price, len(str(item[PRICE_INDEX])) + 2) + mx_len_quantity = max(mx_len_quantity, len(str(item[QUANTITY_INDEX])) + 2) + + s = ( + f"| {TABLE_HEADERS[0]}{' ' * (mx_len_id - 3)}| {TABLE_HEADERS[1]}{' ' * (mx_len_name - 5)}| {TABLE_HEADERS[2]}{' ' * (mx_len_price - 6)}| {TABLE_HEADERS[3]}{' ' * (mx_len_quantity - 9)}|\n" + f"|{'-' * mx_len_id}|{'-' * mx_len_name}|{'-' * mx_len_price}|{'-' * mx_len_quantity}|" + ) + + for item in storage: + s_new = ( + f"\n| {item[PRODUCT_ID_INDEX]}{' ' * (mx_len_id - len(str(item[PRODUCT_ID_INDEX])) - 1)}" + f"| {item[NAME_INDEX]}{' ' * (mx_len_name - len(str(item[NAME_INDEX])) - 1)}" + f"| {item[PRICE_INDEX]}{' ' * (mx_len_price - len(str(item[PRICE_INDEX])) - 1)}" + f"| {item[QUANTITY_INDEX]}{' ' * (mx_len_quantity - len(str(item[QUANTITY_INDEX])) - 1)}|" + ) + s += s_new + return s diff --git a/src/part4/cart.py b/src/part4/cart.py index aed9bb72..7cec6be7 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,10 +9,10 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product - - -# TODO: при необходимости добавьте свои вспомогательные функции +from .storage import ( + QUANTITY_KEY, + Product, +) def add_to_cart( @@ -22,32 +22,21 @@ def add_to_cart( product_id: str, quantity: int, ) -> int | None: - """Move ``quantity`` units of ``product_id`` from the store into ``cart``. + if product_id not in storage: + print(f"no product with id {product_id}") + return None - The product is looked up in ``storage``. If it is missing, a message is - printed 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 - gains ``quantity`` units of ``product_id`` -- the product is added when - the cart had none of it. + curr_product = storage[product_id] + if curr_product[QUANTITY_KEY] < quantity: + print( + f"not enough stock for product {product_id}: {curr_product[QUANTITY_KEY]} available, {quantity} requested" + ) + return None - Args: - storage: The product store to draw stock from; modified in place on - success. - product_names: The normalised names in ``storage``; a - quantity-only change never renames a product, so it is left - unchanged here. - 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. + curr_product[QUANTITY_KEY] -= quantity + cart[product_id] = cart.get(product_id, 0) + quantity - Returns: - The quantity of ``product_id`` in the cart after the addition, or - ``None`` when the product is unknown or the store cannot cover the - request. - """ - # TODO: реализуйте функцию - return 0 + return cart[product_id] def remove_from_cart( @@ -57,31 +46,26 @@ def remove_from_cart( product_id: str, quantity: int, ) -> int | None: - """Move ``quantity`` units of ``product_id`` from ``cart`` back to the store. + if product_id not in cart: + print(f"product {product_id} is not in the cart") + return None + + if cart[product_id] < quantity: + print( + f"cart holds only {cart[product_id]} unit(s) of product {product_id}, " + f"cannot remove {quantity}" + ) + return None - If the cart holds no units of ``product_id``, a message is printed and - nothing changes. If it holds fewer units than requested, an explanatory - message is printed and nothing changes. If the product is missing from - ``storage``, a message is printed and nothing changes. Otherwise the cart loses - ``quantity`` units of the product -- the product is dropped from the - cart when its quantity reaches zero -- and the store record gains - ``quantity`` units back. + if product_id not in storage: + print(f"no product with id {product_id}") + return None - Args: - storage: The product store to return stock to; modified in place on - success. - product_names: The normalised names in ``storage``; a - quantity-only change never renames a product, so it is left - unchanged here. - 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. + curr_product = storage[product_id] + curr_product[QUANTITY_KEY] += quantity + cart[product_id] -= quantity + if cart[product_id] == 0: + del cart[product_id] + return 0 - Returns: - The quantity of ``product_id`` left in the cart after the removal - (zero means the product was dropped from the cart), or ``None`` when - the cart does not hold the product or holds too few units. - """ - # TODO: реализуйте функцию - return 0 + return cart[product_id] diff --git a/src/part4/crud.py b/src/part4/crud.py index 471eff00..472645a0 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -23,26 +23,20 @@ than a scan over ``storage.values()``. """ -import uuid # noqa: F401 +import uuid from typing import Any -from .storage import ( # noqa: F401 +from .storage import ( NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product, ) -from .utils import normalize_price, normalize_product_name # noqa: F401 +from .utils import normalize_price, normalize_product_name def generate_product_id() -> str: - """Generate an identifier for a new product. - - Returns: - A freshly generated UUID, stringified. - """ - # TODO: реализуйте функцию - return "" + return str(uuid.uuid4()) def create_product( @@ -50,46 +44,33 @@ def create_product( product_names: set[str], fields: dict[str, Any], ) -> str | None: - """Add a new product to ``storage`` and return its new identifier. - - Args: - storage: The product store to add to; modified in place on - success. - product_names: The normalised names already in ``storage``; the - new name is added to it in place on success. - fields: A dictionary with the ``name``, ``price`` and ``quantity`` - keys (see :data:`~src.part4.storage.NAME_KEY`, - :data:`~src.part4.storage.PRICE_KEY` and - :data:`~src.part4.storage.QUANTITY_KEY`) 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`` - and ``product_names`` are left unchanged and an explanatory - message is printed. - """ - # TODO: реализуйте функцию - return "" + form_name = normalize_product_name(fields[NAME_KEY]) + if not form_name: + print("product name must not be blank") + return None + + if form_name in product_names: + print(f"product name {form_name!r} is already taken") + return None + + new_id = generate_product_id() + form_price = normalize_price(fields[PRICE_KEY]) + normalized_fields = { + NAME_KEY: form_name, + PRICE_KEY: form_price, + QUANTITY_KEY: fields[QUANTITY_KEY], + } + storage[new_id] = normalized_fields + product_names.add(form_name) + return new_id def read_product(storage: dict[str, Product], product_id: str) -> Product | None: - """Return the product stored under ``product_id``. - - Args: - storage: The product store to search. - product_id: The identifier to look up. + if product_id in storage: + return storage[product_id] - Returns: - The matching product record, or ``None`` when no product carries - that identifier (a message is printed in that case). - """ - # TODO: реализуйте функцию - return {} + print(f"no product with id {product_id}") + return None def update_product( @@ -98,39 +79,34 @@ def update_product( product_id: str, fields: dict[str, Any], ) -> Product | None: - """Overwrite the fields of the product stored under ``product_id``. - - The identifier itself is preserved. ``fields`` may carry any subset of - ``name``, ``price`` and ``quantity``; a key that is missing keeps the - value the product already has, so a caller can update a single field - without repeating the other two. - - Args: - storage: The product store to modify; the matching record is - updated in place on success. - product_names: The normalised names already in ``storage``; on a - successful rename the old name is removed from it and the new - one added. - product_id: The identifier of the product to change. - fields: A dictionary with any of the ``name``, ``price`` and - ``quantity`` keys (see :data:`~src.part4.storage.NAME_KEY`, - :data:`~src.part4.storage.PRICE_KEY` and - :data:`~src.part4.storage.QUANTITY_KEY`) holding the new - values. ``price`` is a :class:`~decimal.Decimal` amount and is - rounded to the stored money precision before it is saved. - Mutated in place: a ``name`` or ``price`` value present in - ``fields`` is overwritten with its normalised form. - - Returns: - The updated product record, or ``None`` when ``name`` is present - and blank once normalised, no product carries that identifier, or - the normalised name is already taken by another product. In every - ``None`` case ``storage`` and ``product_names`` are left unchanged - and an explanatory message is printed. Renaming a product to its - own current name is allowed. - """ - # TODO: реализуйте функцию - return {} + if product_id not in storage: + print(f"no product with id {product_id}") + return None + curr_product = storage[product_id] + curr_name = curr_product[NAME_KEY] + + if NAME_KEY in fields: + form_name = normalize_product_name(fields[NAME_KEY]) + if not form_name: + print("product name must not be blank") + return None + + if form_name != curr_name and form_name in product_names: + print(f"product name {form_name!r} is already taken") + return None + + fields[NAME_KEY] = form_name + + if PRICE_KEY in fields: + form_price = normalize_price(fields[PRICE_KEY]) + fields[PRICE_KEY] = form_price + + if NAME_KEY in fields and fields[NAME_KEY] != curr_name: + product_names.remove(curr_name) + product_names.add(fields[NAME_KEY]) + + curr_product.update(fields) + return curr_product def delete_product( @@ -138,20 +114,10 @@ def delete_product( product_names: set[str], product_id: str, ) -> str | None: - """Remove the product stored under ``product_id`` from ``storage``. - - Args: - storage: The product store to remove from; modified in place on - success. - product_names: The normalised names already in ``storage``; the - departing product's name is removed from it 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`` and ``product_names`` - are left unchanged and a message is printed). - """ - # TODO: реализуйте функцию - return "" + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + product = storage.pop(product_id) + product_names.remove(product[NAME_KEY]) + return product_id diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index 2247b29b..8f021266 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -28,71 +28,91 @@ is left untouched and the loop keeps running; only ``exit`` stops it. """ -from decimal import Decimal, InvalidOperation # noqa: F401 +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 NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product # noqa: F401 -from .utils import get_storage_str_representation # noqa: F401 +from .storage import NAME_KEY, PRICE_KEY, QUANTITY_KEY, Product +from .utils import get_storage_str_representation -# TODO: задайте приглашение и текст справки (используйте своё решение части 3) -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. - 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: реализуйте функцию (используйте своё решение части 3) +def show_help() -> None: + print(HELP_TEXT) def print_result(result: object) -> None: - """Print a CRUD result to stdout unless it is ``None``. - - 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: реализуйте функцию (используйте своё решение части 3) + if result is not None: + print(result) + return def run_command( storage: dict[str, Product], product_names: set[str], 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. - product_names: The normalised names already in ``storage``; kept - in sync 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 the 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: реализуйте функцию - return False + match line.split(): + case ["read", prod_id]: + print_result(read_product(storage, prod_id)) + return True + + case ["create", *name, price, quantity] if name: + name_str = " ".join(name) + fields_case = { + NAME_KEY: name_str, + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + } + print_result(create_product(storage, product_names, fields_case)) + return True + + case ["update", prod_id, *name, price, quantity] if name: + name_str = " ".join(name) + fields_case = { + NAME_KEY: name_str, + PRICE_KEY: Decimal(price), + QUANTITY_KEY: int(quantity), + } + print_result(update_product(storage, product_names, prod_id, fields_case)) + return True + + case ["delete", prod_id]: + print_result(delete_product(storage, product_names, prod_id)) + return True + + case ["exit"]: + return False + + case ["help"]: + show_help() + return True + + case ["show"]: + print(get_storage_str_representation(storage)) + return True + + case _: + print(f"'{line}' is not a command") + return True def main() -> None: diff --git a/src/part4/storage.py b/src/part4/storage.py index 9acedf07..5375750b 100644 --- a/src/part4/storage.py +++ b/src/part4/storage.py @@ -38,8 +38,7 @@ type Product = dict[str, Any] -# Name of each field inside a Product record. -# TODO: задайте имена полей записи -NAME_KEY: Final = "" -PRICE_KEY: Final = "" -QUANTITY_KEY: Final = "" + +NAME_KEY: Final = "name" +PRICE_KEY: Final = "price" +QUANTITY_KEY: Final = "quantity" diff --git a/src/part4/utils.py b/src/part4/utils.py index d2a940ea..e827b16c 100644 --- a/src/part4/utils.py +++ b/src/part4/utils.py @@ -18,10 +18,10 @@ the longest value it holds in that particular call. """ -from decimal import ROUND_HALF_UP, Decimal # noqa: F401 +from decimal import ROUND_HALF_UP, Decimal from typing import Final -from .storage import ( # noqa: F401 +from .storage import ( NAME_KEY, PRICE_KEY, QUANTITY_KEY, @@ -33,68 +33,57 @@ # Quantisation step derived from PRICE_PRECISION, e.g. Decimal("0.01"). # TODO: задайте число знаков после запятой и шаг квантования (используйте своё # решение части 3) -PRICE_PRECISION: Final[int] = 0 -PRICE_STEP: Final = Decimal(0) +PRICE_PRECISION: Final[int] = 2 +PRICE_STEP: Final = Decimal(1).scaleb(-PRICE_PRECISION) # 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: задайте заголовки столбцов таблицы (используйте своё решение части 3) -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. + true_price = 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: реализуйте функцию (используйте своё решение части 3) - return Decimal(0) + return true_price def normalize_product_name(name: str) -> str: - """Reduce a product name to the canonical form the store keeps. - - 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: реализуйте функцию (используйте своё решение части 3) - return "" - + new_name = " ".join(name.split()).lower() -# TODO: при необходимости добавьте свои вспомогательные функции + return new_name def get_storage_str_representation(storage: dict[str, 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 insertion order. When - ``storage`` is empty only the header and separator rows are - returned, sized to the header labels. - """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return "" + mx_len_id = len(TABLE_HEADERS[0]) + mx_len_name = len(TABLE_HEADERS[1]) + mx_len_price = len(TABLE_HEADERS[2]) + mx_len_quantity = len(TABLE_HEADERS[3]) + + for key, prod in storage.items(): + mx_len_id = max(mx_len_id, len(key)) + mx_len_name = max(mx_len_name, len(prod[NAME_KEY])) + mx_len_price = max(mx_len_price, len(str(prod[PRICE_KEY]))) + mx_len_quantity = max(mx_len_quantity, len(str(prod[QUANTITY_KEY]))) + + s = ( + f"| {TABLE_HEADERS[0]:<{mx_len_id}} " + f"| {TABLE_HEADERS[1]:<{mx_len_name}} " + f"| {TABLE_HEADERS[2]:<{mx_len_price}} " + f"| {TABLE_HEADERS[3]:<{mx_len_quantity}} |\n" + f"|{'-' * (mx_len_id + 2)}" + f"|{'-' * (mx_len_name + 2)}" + f"|{'-' * (mx_len_price + 2)}" + f"|{'-' * (mx_len_quantity + 2)}|" + ) + + for key, prod in storage.items(): + s_new = ( + f"\n| {key:<{mx_len_id}} " + f"| {prod[NAME_KEY]:<{mx_len_name}} " + f"| {prod[PRICE_KEY]!s:<{mx_len_price}} " + f"| {prod[QUANTITY_KEY]!s:<{mx_len_quantity}} |" + ) + s += s_new + return s