diff --git a/Install b/Install new file mode 100644 index 00000000..e69de29b diff --git a/Ruff b/Ruff new file mode 100644 index 00000000..e69de29b 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..c8a703fa 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,8 @@ 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 +70,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 +84,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 +116,19 @@ 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("Timestamps 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..4c5751b5 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 i, line in enumerate(cart): + if line[LINE_PRODUCT_ID_INDEX] == product_id: + return i + 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 + + left_product = product[QUANTITY_INDEX] + if left_product < quantity: + print( + f"not enough stock for product {product_id}: {left_product} available, {quantity} requested" + ) + return None + + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], left_product - 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 + + cart_quantity = cart[line_index][LINE_QUANTITY_INDEX] + if cart_quantity < quantity: + print( + f"cart holds only {cart_quantity} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + product = read_product(storage, product_id) + if product is None: + return None + + left_product = product[QUANTITY_INDEX] + update_product( + storage, + product_id, + (product[NAME_INDEX], product[PRICE_INDEX], left_product + 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..af9bee16 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 + + id_product = generate_product_id(storage) + normalized_price = normalize_price(price) + + new_product = (id_product, name, normalized_price, quantity) + storage.append(new_product) + return id_product 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( @@ -99,8 +113,15 @@ def update_product( ``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 i, 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[i] = 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 +137,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..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..30bf9055 100644 --- a/src/part2/utils.py +++ b/src/part2/utils.py @@ -6,13 +6,13 @@ 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 +25,5 @@ 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..05eb8bde 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 + normal_name = normalize_product_name(fields[0]) + if not normal_name: + print("product name must not be blank") + return None + + for item in storage: + if item[NAME_INDEX] == normal_name: + print(f"product name {normal_name} is already taken") + return None + + new_id = generate_product_id(storage) + normal_price = normalize_price(fields[1]) + quantity = fields[2] + + storage.append((new_id, normal_name, normal_price, quantity)) + return new_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,29 @@ 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) + normal_name = normalize_product_name(fields[0]) + + if not normal_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] == normal_name: + print(f"product name {normal_name} is already taken") + return None + + if target_index == -1: + print(f"no product with id {product_id}") + return None + + normal_price = normalize_price(fields[1]) + quantity = fields[2] + + updated_product = (product_id, normal_name, normal_price, quantity) + return updated_product def delete_product(storage: list[Product], product_id: int) -> int | None: @@ -127,5 +166,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..d384f3b1 100644 --- a/src/part3/run_admin.py +++ b/src/part3/run_admin.py @@ -29,22 +29,33 @@ 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 +65,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 +76,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 +100,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 + + cmd = words[0] + args = words[1:] + len_args = len(args) + + if cmd == "help" and len_args == 0: + show_help() + elif cmd == "exit" and len_args == 0: + return False + elif cmd == "show" and len_args == 0: + print(get_storage_str_representation(storage)) + elif cmd == "create" and len_args >= 3: + name = " ".join(args[:-2]) + price = Decimal(args[-2]) + quantity = int(args[-1]) + print_result(create_product(storage, (name, price, quantity))) + + elif cmd == "read" and len_args == 1: + product_id = int(args[0]) + print_result(read_product(storage, product_id)) + + elif cmd == "update" and len_args >= 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 cmd == "delete" and len_args == 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: 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..c1b0ffe3 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 Decimal(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: @@ -91,5 +88,32 @@ def get_storage_str_representation(storage: list[Product]) -> str: is empty only the header and separator rows are returned, sized to the header labels. """ - # TODO: реализуйте функцию - return "" + str_rows = [] + + for item in storage: + str_rows.append( + [ + str(item[PRODUCT_ID_INDEX]), + str(item[NAME_INDEX]), + str(item[PRICE_INDEX]), + str(item[QUANTITY_INDEX]), + ] + ) + + width = [len(i) for i in TABLE_HEADERS] + for row in str_rows: + for i, text in enumerate(row): + width[i] = max(width[i], len(text)) + + lines = [] + header_text = [f" {header:<{width[i]}} " for i, header in enumerate(TABLE_HEADERS)] + lines.append("|" + "|".join(header_text) + "|") + + stop_line = ["-" * (w + 2) for w in width] + lines.append("|" + "|".join(stop_line) + "|") + + for row in str_rows: + texts = [f" {text:<{width[i]}} " for i, text in enumerate(row)] + lines.append("|" + "|".join(texts) + "|") + + return "\n".join(lines) diff --git a/src/part4/cart.py b/src/part4/cart.py index aed9bb72..27877749 100644 --- a/src/part4/cart.py +++ b/src/part4/cart.py @@ -9,7 +9,8 @@ an explanatory message to stdout and returns ``None``. """ -from .storage import Product +from .storage import QUANTITY_KEY, Product +from .utils import in_storage # TODO: при необходимости добавьте свои вспомогательные функции @@ -46,8 +47,20 @@ def add_to_cart( ``None`` when the product is unknown or the store cannot cover the request. """ - # TODO: реализуйте функцию - return 0 + + if not in_storage(product_id, storage): + return None + + left_product = storage[product_id][QUANTITY_KEY] + if left_product < quantity: + print( + f"not enough stock for product {product_id}: {left_product} available, {quantity} requested" + ) + return None + + storage[product_id][QUANTITY_KEY] -= quantity + cart[product_id] = cart.get(product_id, 0) + quantity + return cart[product_id] def remove_from_cart( @@ -83,5 +96,24 @@ 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 + + in_cart = cart[product_id] + if in_cart < quantity: + print( + f"cart holds only {in_cart} unit(s) of product {product_id}, cannot remove {quantity}" + ) + return None + + if not in_storage(product_id, storage): + 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..826fd9d2 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 in_storage, normalize_price, normalize_product_name def generate_product_id() -> str: @@ -42,7 +42,8 @@ def generate_product_id() -> str: A freshly generated UUID, stringified. """ # TODO: реализуйте функцию - return "" + + return str(uuid.uuid4()) def create_product( @@ -73,8 +74,22 @@ def create_product( and ``product_names`` are left unchanged and an explanatory message is printed. """ - # TODO: реализуйте функцию - return "" + name = normalize_product_name(fields[NAME_KEY]) + if not name: + print("product name must not be blank") + return None + if name in product_names: + print(f"product name {name} is already taken") + return None + + product_id = generate_product_id() + price = normalize_price(fields[PRICE_KEY]) + quantity = fields[QUANTITY_KEY] + + storage[product_id] = {NAME_KEY: name, PRICE_KEY: price, QUANTITY_KEY: quantity} + product_names.add(name) + + return product_id def read_product(storage: dict[str, Product], product_id: str) -> Product | None: @@ -88,8 +103,9 @@ 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 not in_storage(product_id, storage): + return None + return storage[product_id] def update_product( @@ -129,8 +145,38 @@ def update_product( and an explanatory message is printed. Renaming a product to its own current name is allowed. """ - # TODO: реализуйте функцию - return {} + if not in_storage(product_id, storage): + return None + + product = storage[product_id] + + if NAME_KEY in fields: + name = normalize_product_name(fields[NAME_KEY]) + if not name: + print("product name must not be blank") + return None + if name != product[NAME_KEY] and name in product_names: + print(f"{name} is already taken") + return None + fields[NAME_KEY] = name + + if PRICE_KEY in fields: + fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY]) + + if NAME_KEY in fields: + old_name = product[NAME_KEY] + new_name = fields[NAME_KEY] + if old_name != new_name: + product_names.remove(old_name) + product_names.add(new_name) + product[NAME_KEY] = new_name + + if PRICE_KEY in fields: + product[PRICE_KEY] = fields[PRICE_KEY] + + if QUANTITY_KEY in fields: + product[QUANTITY_KEY] = fields[QUANTITY_KEY] + return product def delete_product( @@ -153,5 +199,11 @@ def delete_product( product carried that identifier (``storage`` and ``product_names`` are left unchanged and a message is printed). """ - # TODO: реализуйте функцию - return "" + if not in_storage(product_id, storage): + return None + + name = storage[product_id][NAME_KEY] + del storage[product_id] + product_names.remove(name) + + return product_id diff --git a/src/part4/run_admin.py b/src/part4/run_admin.py index 2247b29b..8d2569b5 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: @@ -64,7 +75,8 @@ def print_result(result: object) -> None: operation already reported its own failure, so nothing is printed in that case. """ - # TODO: реализуйте функцию (используйте своё решение части 3) + if result is not None: + print(result) def run_command( @@ -91,8 +103,62 @@ def run_command( 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: + return True + + cmd = words[0] + args = words[1:] + len_args = len(args) + + if cmd == "help" and len_args == 0: + show_help() + elif cmd == "exit" and len_args == 0: + return False + elif (cmd == "show" or cmd == "list") and len_args == 0: + print(get_storage_str_representation(storage)) + + elif cmd == "create" and len_args >= 3: + name = " ".join(args[:-2]) + try: + price = Decimal(args[-2]) + quantity = int(args[-1]) + except (ValueError, InvalidOperation): + print(f"'{line}' names a command but its arguments are invalid") + return True + + fields = {NAME_KEY: name, PRICE_KEY: price, QUANTITY_KEY: quantity} + print_result(create_product(storage, product_names, fields)) + + elif cmd == "read" and len_args == 1: + product_id = args[0] + print_result(read_product(storage, product_id)) + + elif cmd == "update" and len_args >= 4: + product_id = args[0] + name = " ".join(args[1:-2]) + try: + price = Decimal(args[-2]) + quantity = int(args[-1]) + except (ValueError, InvalidOperation): + print(f"'{line}' names a command but its arguments are invalid") + return True + + fields = {NAME_KEY: name, PRICE_KEY: price, QUANTITY_KEY: quantity} + print_result(update_product(storage, product_names, product_id, fields)) + + elif cmd == "delete" and len_args == 1: + product_id = args[0] + print_result(delete_product(storage, product_names, product_id)) + + else: + if cmd in ("create", "read", "update", "delete", "show", "list"): + print(f"'{line}' names a command but its arguments are invalid") + else: + 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..a25f6253 100644 --- a/src/part4/storage.py +++ b/src/part4/storage.py @@ -40,6 +40,6 @@ # 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..1acb3a18 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,15 @@ # 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: @@ -53,8 +54,8 @@ def normalize_price(price: Decimal) -> Decimal: ``price`` quantised to :data:`PRICE_PRECISION` fractional digits, with halves rounded up. """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return Decimal(0) + # TODO: реализуйте функцию (используйте своё решение части 2) + return Decimal(price.quantize(PRICE_STEP, rounding=ROUND_HALF_UP)) def normalize_product_name(name: str) -> str: @@ -71,11 +72,19 @@ def normalize_product_name(name: str) -> str: The result is an empty string when ``name`` holds nothing but whitespace. """ - # TODO: реализуйте функцию (используйте своё решение части 3) - return "" + # TODO: реализуйте функцию + return " ".join(name.split()).lower() # TODO: при необходимости добавьте свои вспомогательные функции +def in_storage( + product_id: str, + storage: dict[str, Product], +) -> bool: + if product_id not in storage: + print(f"no product with id {product_id}") + return False + return True def get_storage_str_representation(storage: dict[str, Product]) -> str: @@ -92,9 +101,36 @@ def get_storage_str_representation(storage: dict[str, Product]) -> str: 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. + 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: реализуйте функцию (используйте своё решение части 3) - return "" + str_rows = [] + + for product_id, item in storage.items(): + str_rows.append( + [ + str(product_id), + str(item[NAME_KEY]), + str(item[PRICE_KEY]), + str(item[QUANTITY_KEY]), + ] + ) + + width = [len(i) for i in TABLE_HEADERS] + for row in str_rows: + for i, text in enumerate(row): + width[i] = max(width[i], len(text)) + + lines = [] + header_text = [f" {header:<{width[i]}} " for i, header in enumerate(TABLE_HEADERS)] + lines.append("|" + "|".join(header_text) + "|") + + stop_line = ["-" * (w + 2) for w in width] + lines.append("|" + "|".join(stop_line) + "|") + + for row in str_rows: + texts = [f" {text:<{width[i]}} " for i, text in enumerate(row)] + lines.append("|" + "|".join(texts) + "|") + + return "\n".join(lines)