diff --git a/src/part1/constants.py b/src/part1/constants.py index 9abfbba2..588fe9f8 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..85ea27f8 100644 --- a/src/part1/snowflake.py +++ b/src/part1/snowflake.py @@ -13,13 +13,16 @@ :func:`decode_node_id` and :func:`decode_sequence_id`. """ -import time # noqa: F401 +import time from .constants import ( # noqa: F401 EPOCH_MS_DEFAULT, + NODE_ID_BITS, NODE_ID_DEFAULT, NODE_ID_MAX, + SEQUENCE_ID_BITS, SEQUENCE_ID_MAX, + TIMESTAMP_BITS, TIMESTAMP_MS_MAX, ) @@ -35,7 +38,8 @@ def read_current_millis(epoch_ms: int) -> int: negative if ``epoch_ms`` lies in the future. """ # TODO: реализуйте функцию - return 0 + + return int(time.time() * 1000) - epoch_ms def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> int: @@ -51,7 +55,7 @@ def decode_timestamp_ms(snowflake_id: int, epoch_ms: int = EPOCH_MS_DEFAULT) -> generated. """ # TODO: реализуйте функцию - return 0 + return epoch_ms + (snowflake_id >> (NODE_ID_BITS + SEQUENCE_ID_BITS)) def decode_node_id(snowflake_id: int) -> int: @@ -65,7 +69,7 @@ def decode_node_id(snowflake_id: int) -> int: ``[0, NODE_ID_MAX]``. """ # TODO: реализуйте функцию - return 0 + return (snowflake_id >> SEQUENCE_ID_BITS) & NODE_ID_MAX def decode_sequence_id(snowflake_id: int) -> int: @@ -79,7 +83,7 @@ def decode_sequence_id(snowflake_id: int) -> int: the range ``[0, SEQUENCE_ID_MAX]``. """ # TODO: реализуйте функцию - return 0 + return snowflake_id & SEQUENCE_ID_MAX def generate_snowflake_id( @@ -111,4 +115,18 @@ def generate_snowflake_id( cases an explanatory message is printed to stdout first. """ # TODO: реализуйте функцию - return 0 + if not (0 <= node_id <= NODE_ID_MAX): + print(f"node_id must be in [0, {NODE_ID_MAX}], you have {node_id}") + return None + if not (0 <= sequence_id <= SEQUENCE_ID_MAX): + print(f"sequence_id must be in [0, {SEQUENCE_ID_MAX}], you have {sequence_id}") + return None + time_ms = read_current_millis(epoch_ms) + if time_ms > TIMESTAMP_MS_MAX: + print("Timestamp overflows") + return None + return ( + (time_ms << (NODE_ID_BITS + SEQUENCE_ID_BITS)) + | (node_id << (SEQUENCE_ID_BITS)) + | sequence_id + ) diff --git a/src/part2/cart.py b/src/part2/cart.py index 063f9aea..f1ecaa5b 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, @@ -24,7 +24,14 @@ # TODO: задайте позиции полей внутри кортежа CartLine LINE_PRODUCT_ID_INDEX: Final = 0 -LINE_QUANTITY_INDEX: Final = 0 +LINE_QUANTITY_INDEX: Final = 1 + + +def find_line(cart: list[CartLine], product_id: int) -> int | None: + for index, line in enumerate(cart): + if line[LINE_PRODUCT_ID_INDEX] == product_id: + return index + return None def add_to_cart( @@ -53,8 +60,33 @@ def add_to_cart( 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 + + stock_quantity = product[QUANTITY_INDEX] + if stock_quantity < quantity: + print( + f"not enough stock for product {product_id}: {stock_quantity} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], stock_quantity - quantity), + ) + + line_index = find_line(cart, product_id) + if line_index is not None: + new_quantity = cart[line_index][LINE_QUANTITY_INDEX] + quantity + new_line = (product_id, new_quantity) + cart[line_index] = new_line + return new_line + + new_line = (product_id, quantity) + cart.append(new_line) + return new_line def remove_from_cart( @@ -86,4 +118,35 @@ def remove_from_cart( line for the product or holds too few units. """ # TODO: реализуйте функцию - return (0, 0) + + line_index = find_line(cart, product_id) + if line_index is None: + print(f"product {product_id} is not in the cart") + return None + + line_quantity = cart[line_index][LINE_QUANTITY_INDEX] + if line_quantity < quantity: + print( + f"cart holds only {line_quantity} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + product = read_product(storage, product_id) + if product is None: + return None + + stock_quantity = product[QUANTITY_INDEX] + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], stock_quantity + quantity), + ) + + new_quantity = cart[line_index][LINE_QUANTITY_INDEX] - quantity + if new_quantity == 0: + del cart[line_index] + return (product_id, 0) + + new_line = (product_id, new_quantity) + cart[line_index] = new_line + return new_line diff --git a/src/part2/crud.py b/src/part2/crud.py index d026cbcb..1c8cfe23 100644 --- a/src/part2/crud.py +++ b/src/part2/crud.py @@ -14,13 +14,13 @@ 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: @@ -34,8 +34,9 @@ def generate_product_id(storage: list[Product]) -> int: :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию - return 0 + if not storage: + return PRODUCT_ID_MIN + return max(product[PRODUCT_ID_INDEX] for product in storage) + 1 def create_product( @@ -56,8 +57,18 @@ def create_product( ``storage`` is left unchanged and a message naming the clashing name is printed. """ - # TODO: реализуйте функцию - return 0 + name, price, quantity = fields + for product in storage: + if product[NAME_INDEX] == name: + print(f"product name {name} is already taken") + return None + + new_product_id = generate_product_id(storage) + normalized_price = normalize_price(price) + + new_product = (new_product_id, name, normalized_price, quantity) + storage.append(new_product) + return new_product_id def read_product(storage: list[Product], product_id: int) -> Product | None: @@ -72,8 +83,11 @@ def read_product(storage: list[Product], product_id: int) -> Product | None: ``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( @@ -94,13 +108,21 @@ def update_product( ``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) + name, price, quantity = fields + for index, product in enumerate(storage): + if product[PRODUCT_ID_INDEX] == product_id: + normalized_price = normalize_price(price) + updated_product = (product_id, name, normalized_price, quantity) + storage[index] = updated_product + return updated_product + print(f"no product with id {product_id}") + return None def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -116,5 +138,10 @@ def delete_product(storage: list[Product], product_id: int) -> int | None: product carried that identifier (``storage`` is left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return 0 + + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + storage.remove(product) + 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..b10a471e 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,13 +6,12 @@ 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: @@ -25,5 +24,4 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию - return Decimal(0) + return Decimal(price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP)) diff --git a/src/part3/crud.py b/src/part3/crud.py index 68811d7e..a33034d0 100644 --- a/src/part3/crud.py +++ b/src/part3/crud.py @@ -20,13 +20,13 @@ 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: @@ -37,11 +37,12 @@ def generate_product_id(storage: list[Product]) -> int: Returns: One past the greatest identifier currently held in ``storage``, or - :data:`~src.part3.storage.PRODUCT_ID_MIN` when ``storage`` is + :data:`~src.part2.storage.PRODUCT_ID_MIN` when ``storage`` is empty. """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + if not storage: + return PRODUCT_ID_MIN + return max(product[PRODUCT_ID_INDEX] for product in storage) + 1 def create_product( @@ -64,8 +65,22 @@ def create_product( normalised name already exists. In the ``None`` case ``storage`` is left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return 0 + + normalized_name = normalize_product_name(fields[0]) + if not normalized_name: + print("product name must not be blank") + return None + for product in storage: + if product[NAME_INDEX] == normalized_name: + print(f"product name {normalized_name} is already taken") + return None + + new_product_id = generate_product_id(storage) + normalized_price = normalize_price(fields[1]) + quantity = fields[2] + + storage.append((new_product_id, normalized_name, normalized_price, quantity)) + return new_product_id def read_product(storage: list[Product], product_id: int) -> Product | None: @@ -80,8 +95,11 @@ def read_product(storage: list[Product], product_id: int) -> Product | None: ``None`` when no product carries that identifier (a message is printed in that case). """ - # TODO: реализуйте функцию (используйте своё решение части 2) - 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( @@ -110,8 +128,30 @@ def update_product( unchanged and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию - return (0, "", Decimal(0), 0) + normalized_name = normalize_product_name(fields[0]) + + if not normalized_name: + print("product name must not be blank") + return None + target_index = -1 + for i, item in enumerate(storage): + if item[PRODUCT_ID_INDEX] == product_id: + target_index = i + elif item[NAME_INDEX] == normalized_name: + print(f"product name {normalized_name} is already taken") + return None + + if target_index == -1: + print(f"no product with id {product_id}") + return None + + normalized_price = normalize_price(fields[1]) + quantity = fields[2] + + updated_product = (product_id, normalized_name, normalized_price, quantity) + storage[target_index] = updated_product + + return updated_product def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -127,5 +167,10 @@ def delete_product(storage: list[Product], product_id: int) -> int | None: product carried that identifier (``storage`` is left unchanged and a message is printed). """ - # TODO: реализуйте функцию (используйте своё решение части 2) - return 0 + + for product in storage: + if product[PRODUCT_ID_INDEX] == product_id: + storage.remove(product) + 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..eb335c1a 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,22 +29,32 @@ 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: @@ -54,7 +64,7 @@ def show_help() -> None: is: a heading, one line per command with a short description, and a note on how multi-word names are parsed. """ - # TODO: реализуйте функцию + print(HELP_TEXT) def print_result(result: object) -> None: @@ -65,7 +75,8 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию + if result is not None: + print(result) def run_command(storage: list[Product], line: str) -> bool: @@ -88,8 +99,47 @@ def run_command(storage: list[Product], line: str) -> bool: decimal.InvalidOperation: If the price argument of ``create`` or ``update`` does not parse as a decimal number. """ - # TODO: реализуйте функцию - return False + words = line.split() + + if not words: + print(f"{line!r} is not a command") + return True + + command = words[0] + args = words[1:] + args_count = len(args) + + if command == "help" and args_count == 0: + show_help() + elif command == "exit" and args_count == 0: + return False + elif command == "show" and args_count == 0: + print(get_storage_str_representation(storage)) + elif command == "create" and args_count >= 3: + name = " ".join(args[:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + print_result(create_product(storage, (name, price, quantity))) + + elif command == "read" and args_count == 1: + product_id = int(args[0]) + print_result(read_product(storage, product_id)) + + elif command == "update" and args_count >= 4: + product_id = int(args[0]) + name = " ".join(args[1:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + print_result(update_product(storage, product_id, (name, price, quantity))) + + elif command == "delete" and args_count == 1: + product_id = int(args[0]) + print_result(delete_product(storage, product_id)) + + else: + print(f"{line!r} is not a command") + + return True def main() -> None: @@ -103,13 +153,13 @@ def main() -> None: ``exit`` ends it. """ storage: list[Product] = [] - running = True + is_running = True - while running: + while is_running: line = input(PROMPT).strip() try: - running = run_command(storage, line) + is_running = run_command(storage, line) except (ValueError, InvalidOperation): print(f"{line!r} names a command but its arguments are invalid") 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..735e20ad 100644 --- a/src/part3/utils.py +++ b/src/part3/utils.py @@ -18,24 +18,24 @@ 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: @@ -49,7 +49,7 @@ def normalize_price(price: Decimal) -> Decimal: with halves rounded up. """ # TODO: реализуйте функцию (используйте своё решение части 2) - return Decimal(0) + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -67,10 +67,7 @@ def normalize_product_name(name: str) -> str: whitespace. """ # TODO: реализуйте функцию - return "" - - -# TODO: при необходимости добавьте свои вспомогательные функции + return " ".join(name.split()).lower() def get_storage_str_representation(storage: list[Product]) -> str: @@ -92,4 +89,34 @@ def get_storage_str_representation(storage: list[Product]) -> str: the header labels. """ # TODO: реализуйте функцию - return "" + + rows = [] + + for product in storage: + rows.append( + [ + str(product[PRODUCT_ID_INDEX]), + str(product[NAME_INDEX]), + str(product[PRICE_INDEX]), + str(product[QUANTITY_INDEX]), + ] + ) + widths = [len(header) for header in TABLE_HEADERS] + for row in rows: + for index, cell in enumerate(row): + widths[index] = max(widths[index], len(cell)) + + lines = [] + header_cells = [ + f" {header:<{widths[index]}} " for index, header in enumerate(TABLE_HEADERS) + ] + lines.append("|" + "|".join(header_cells) + "|") + + separator = ["-" * (column_width + 2) for column_width in widths] + lines.append("|" + "|".join(separator) + "|") + + for row in rows: + cells = [f" {cell:<{widths[index]}} " for index, cell in enumerate(row)] + lines.append("|" + "|".join(cells) + "|") + + return "\n".join(lines) diff --git a/src/part4/cart.py b/src/part4/cart.py index aed9bb72..13aa27e2 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,7 +9,7 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product +from .storage import QUANTITY_KEY, Product # TODO: при необходимости добавьте свои вспомогательные функции @@ -46,8 +46,24 @@ def add_to_cart( ``None`` when the product is unknown or the store cannot cover the request. """ - # TODO: реализуйте функцию - return 0 + + if product_id not in storage: + print(f"no product with id {product_id}") + return None + + product = storage[product_id] + + if product[QUANTITY_KEY] < quantity: + print( + f"not enough stock for product {product_id}: " + f"{product[QUANTITY_KEY]} available, {quantity} requested" + ) + return None + + product[QUANTITY_KEY] -= quantity + cart[product_id] = cart.get(product_id, 0) + quantity + + return cart[product_id] def remove_from_cart( @@ -83,5 +99,27 @@ def remove_from_cart( (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 + + 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 product_id not in storage: + print(f"no product with id {product_id}") + return None + + storage[product_id][QUANTITY_KEY] += quantity + cart[product_id] -= quantity + + if cart[product_id] == 0: + del cart[product_id] + return 0 + + return cart[product_id] diff --git a/src/part4/crud.py b/src/part4/crud.py index 471eff00..a624055d 100644 --- a/src/part4/crud.py +++ b/src/part4/crud.py @@ -23,16 +23,16 @@ 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: @@ -41,8 +41,8 @@ def generate_product_id() -> str: Returns: A freshly generated UUID, stringified. """ - # TODO: реализуйте функцию - return "" + + return str(uuid.uuid4()) def create_product( @@ -73,8 +73,31 @@ def create_product( and ``product_names`` are left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return "" + + raw_name = fields[NAME_KEY] + normalized_name = normalize_product_name(raw_name) + + if not normalized_name: + print("product name must not be blank") + return None + + if normalized_name in product_names: + print(f"product name '{normalized_name}' is already taken") + return None + + product_id = generate_product_id() + normalized_price = normalize_price(fields[PRICE_KEY]) + + product_record: Product = { + NAME_KEY: normalized_name, + PRICE_KEY: normalized_price, + QUANTITY_KEY: fields[QUANTITY_KEY], + } + + storage[product_id] = product_record + product_names.add(normalized_name) + + return product_id def read_product(storage: dict[str, Product], product_id: str) -> Product | None: @@ -88,8 +111,11 @@ def read_product(storage: dict[str, Product], product_id: str) -> Product | None The matching product record, or ``None`` when no product carries that identifier (a message is printed in that case). """ - # TODO: реализуйте функцию - return {} + + if product_id not in storage: + print(f"no product with id {product_id}") + return None + return storage[product_id] def update_product( @@ -129,8 +155,42 @@ def update_product( 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 + + product = storage[product_id] + + if NAME_KEY in fields: + raw_name = fields[NAME_KEY] + normalized_name = normalize_product_name(raw_name) + + if not normalized_name: + print("product name must not be blank") + return None + + current_name = product[NAME_KEY] + if normalized_name != current_name and normalized_name in product_names: + print(f"product name '{normalized_name}' is already taken") + return None + + fields[NAME_KEY] = normalized_name + + if PRICE_KEY in fields: + fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + + old_name = product[NAME_KEY] + + for key, value in fields.items(): + product[key] = value + + new_name = product[NAME_KEY] + if old_name != new_name: + product_names.remove(old_name) + product_names.add(new_name) + + return product def delete_product( @@ -153,5 +213,11 @@ def delete_product( 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..75266d7c 100644 --- a/src/part4/run_admin.py +++ b/src/part4/run_admin.py @@ -28,22 +28,33 @@ 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: @@ -53,7 +64,7 @@ def show_help() -> None: is: a heading, one line per command with a short description, and a note on how multi-word names are parsed. """ - # TODO: реализуйте функцию (используйте своё решение части 3) + print(HELP_TEXT) def print_result(result: object) -> None: @@ -65,6 +76,8 @@ def print_result(result: object) -> None: printed in that case. """ # TODO: реализуйте функцию (используйте своё решение части 3) + if result is not None: + print(result) def run_command( @@ -92,7 +105,43 @@ def run_command( ``update`` does not parse as a decimal number. """ # TODO: реализуйте функцию - return False + words = line.split() + + if not words: + print(f"{line!r} is not a command") + return True + + command = words[0] + args = words[1:] + args_count = len(args) + + if command == "help" and args_count == 0: + show_help() + elif command == "exit" and args_count == 0: + return False + elif command == "show" and args_count == 0: + print(get_storage_str_representation(storage)) + elif command == "create" and args_count >= 3: + name = " ".join(args[:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + fields = {NAME_KEY: name, PRICE_KEY: price, QUANTITY_KEY: quantity} + print_result(create_product(storage, product_names, fields)) + elif command == "read" and args_count == 1: + print_result(read_product(storage, args[0])) + elif command == "update" and args_count >= 4: + product_id = args[0] + name = " ".join(args[1:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + fields = {NAME_KEY: name, PRICE_KEY: price, QUANTITY_KEY: quantity} + print_result(update_product(storage, product_names, product_id, fields)) + elif command == "delete" and args_count == 1: + print_result(delete_product(storage, product_names, args[0])) + else: + print(f"{line!r} is not a command") + + return True def main() -> None: diff --git a/src/part4/storage.py b/src/part4/storage.py index 9acedf07..f0034782 100644 --- a/src/part4/storage.py +++ b/src/part4/storage.py @@ -39,7 +39,6 @@ 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..3f261630 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,14 +33,14 @@ # 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: @@ -54,7 +54,7 @@ def normalize_price(price: Decimal) -> Decimal: with halves rounded up. """ # TODO: реализуйте функцию (используйте своё решение части 3) - return Decimal(0) + return price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP) def normalize_product_name(name: str) -> str: @@ -72,7 +72,7 @@ def normalize_product_name(name: str) -> str: whitespace. """ # TODO: реализуйте функцию (используйте своё решение части 3) - return "" + return " ".join(name.split()).lower() # TODO: при необходимости добавьте свои вспомогательные функции @@ -97,4 +97,32 @@ def get_storage_str_representation(storage: dict[str, Product]) -> str: returned, sized to the header labels. """ # TODO: реализуйте функцию (используйте своё решение части 3) - return "" + rows = [] + for product_id, product in storage.items(): + rows.append( + [ + str(product_id), + str(product[NAME_KEY]), + str(product[PRICE_KEY]), + str(product[QUANTITY_KEY]), + ] + ) + widths = [len(header) for header in TABLE_HEADERS] + for row in rows: + for index, cell in enumerate(row): + widths[index] = max(widths[index], len(cell)) + + lines = [] + header_cells = [ + f" {header:<{widths[index]}} " for index, header in enumerate(TABLE_HEADERS) + ] + lines.append("|" + "|".join(header_cells) + "|") + + separator = ["-" * (column_width + 2) for column_width in widths] + lines.append("|" + "|".join(separator) + "|") + + for row in rows: + cells = [f" {cell:<{widths[index]}} " for index, cell in enumerate(row)] + lines.append("|" + "|".join(cells) + "|") + + return "\n".join(lines)