Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 38 additions & 55 deletions src/part4/cart.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
an explanatory message to stdout and returns ``None``.
"""

from .storage import Product
from .storage import QUANTITY_KEY, Product


# TODO: при необходимости добавьте свои вспомогательные функции
Expand All @@ -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``.

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.

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.

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
if product_id not in storage:
print(f"no product with id {product_id}")
return None

stock: int = storage[product_id][QUANTITY_KEY]
if stock < quantity:
print(
f"not enough stock for product {product_id}: {stock} 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(
Expand All @@ -57,31 +46,25 @@ def remove_from_cart(
product_id: str,
quantity: int,
) -> int | None:
"""Move ``quantity`` units of ``product_id`` from ``cart`` back to the store.

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.

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.

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
if product_id not in cart:
print(f"product {product_id} is not in the cart")
return None

cart_quantity: int = cart[product_id]
if cart_quantity < quantity:
print(
f"cart holds only {cart_quantity} unit(s) of product {product_id}, 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 cart.get(product_id, 0)
193 changes: 72 additions & 121 deletions src/part4/crud.py
Original file line number Diff line number Diff line change
@@ -1,95 +1,61 @@
"""Create/read/update/delete operations over the in-memory product store.

Every operation takes the store -- a dictionary mapping product id to its
:data:`~src.part4.storage.Product` record -- as its first argument and
works on it in place. ``create_product``, ``update_product`` and
``delete_product`` additionally take ``product_names``, the ``set[str]``
of normalised names currently in ``storage`` (see
:mod:`src.part4.storage`), and keep it in sync with ``storage`` on
every successful call. The failure path never raises: the operation
prints an explanatory message to stdout and returns ``None``.

The identifier of a new product is a freshly generated UUID string
(:func:`generate_product_id`), independent of insertion order or of any
identifier already in ``storage``.

Every product name that reaches the store is passed through
:func:`~src.part4.utils.normalize_product_name` first. A name that
normalises to an empty string is rejected -- the operation prints a
message and changes nothing. Names are also kept unique --
:func:`create_product` refuses a normalised name that is already taken,
and :func:`update_product` refuses one that is already taken by another
product -- via an O(1) membership test against ``product_names`` rather
than a scan over ``storage.values()``.
"""

import uuid # noqa: F401
import uuid
from decimal import Decimal
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(
storage: dict[str, 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 ""
name: str = fields[NAME_KEY]
price: Decimal = fields[PRICE_KEY]
quantity: int = fields[QUANTITY_KEY]

normalized_name = normalize_product_name(name)

def read_product(storage: dict[str, Product], product_id: str) -> Product | None:
"""Return the product stored under ``product_id``.
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

Args:
storage: The product store to search.
product_id: The identifier to look up.
product_id = generate_product_id()
normalized_price = normalize_price(price)

Returns:
The matching product record, or ``None`` when no product carries
that identifier (a message is printed in that case).
"""
# TODO: реализуйте функцию
return {}
new_product: Product = {
NAME_KEY: normalized_name,
PRICE_KEY: normalized_price,
QUANTITY_KEY: quantity,
}
storage[product_id] = new_product

return product_id


def read_product(storage: dict[str, Product], product_id: str) -> Product | None:
if product_id in storage:
return storage[product_id]

print(f"no product with id {product_id}")
return None


def update_product(
Expand All @@ -98,60 +64,45 @@ 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

current_product = storage[product_id]

if NAME_KEY in fields:
normalized_name = normalize_product_name(fields[NAME_KEY])
if not normalized_name:
print("product name must not be blank")
return None
if (
normalized_name != current_product[NAME_KEY]
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])

if NAME_KEY in fields and fields[NAME_KEY] != current_product[NAME_KEY]:
product_names.remove(current_product[NAME_KEY])
product_names.add(fields[NAME_KEY])

current_product.update(fields)
return current_product


def delete_product(
storage: dict[str, 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 in storage:
product = storage.pop(product_id)
product_names.remove(product[NAME_KEY])
return product_id

print(f"no product with id {product_id}")
return None
Loading
Loading