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
101 changes: 32 additions & 69 deletions src/part4/cart.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,4 @@
"""Shopping-cart operations layered on top of the product store.

The cart is a plain dictionary mapping each product identifier to the
number of units of that product in the cart. Moving units between the
store and the cart keeps the two sides in balance: :func:`add_to_cart` takes
units out of stock, :func:`remove_from_cart` puts them back.

Like the CRUD layer, the failure path never raises -- the operation prints
an explanatory message to stdout and returns ``None``.
"""

from .storage import Product


# TODO: при необходимости добавьте свои вспомогательные функции
from .storage import QUANTITY_KEY, Product


def add_to_cart(
Expand All @@ -22,32 +8,19 @@ 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
if storage[product_id][QUANTITY_KEY] < quantity:
print(
f"not enough stock for product {product_id}: "
f"{storage[product_id][QUANTITY_KEY]} available, "
f"{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 +30,21 @@ 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
if cart[product_id] < quantity:
print(
f"cart holds only {cart[product_id]} unit(s) "
f"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 not cart[product_id]:
del cart[product_id]
return 0
return cart[product_id]
177 changes: 55 additions & 122 deletions src/part4/crud.py
Original file line number Diff line number Diff line change
@@ -1,95 +1,48 @@
"""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 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 ""
price_product = normalize_price(fields[PRICE_KEY])
quantity_product = fields[QUANTITY_KEY]
name_product = normalize_product_name(fields[NAME_KEY])
if not name_product:
print("product name must not be blank")
return None
if name_product in product_names:
print(f"product name '{name_product}' is already taken")
return None
product_names.add(name_product)
new_id = generate_product_id()
storage[new_id] = {
NAME_KEY: name_product,
PRICE_KEY: price_product,
QUANTITY_KEY: quantity_product,
}
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.

Returns:
The matching product record, or ``None`` when no product carries
that identifier (a message is printed in that case).
"""
# TODO: реализуйте функцию
return {}
reading = storage.get(product_id)
if reading is None:
print(f"no product with id {product_id}")
return reading


def update_product(
Expand All @@ -98,60 +51,40 @@ 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
if fields.get(NAME_KEY) is not None:
fields[NAME_KEY] = normalize_product_name(fields[NAME_KEY])
if not fields[NAME_KEY]:
print("product name must not be blank")
return None
if (fields[NAME_KEY] != storage[product_id][NAME_KEY]) and (
fields[NAME_KEY] in product_names
):
print(f"product name '{fields[NAME_KEY]}' is already taken")
return None
if fields.get(PRICE_KEY) is not None:
fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY])
if fields.get(NAME_KEY) is not None:
product_names.discard(storage[product_id][NAME_KEY])
product_names.add(fields[NAME_KEY])
storage[product_id][NAME_KEY] = fields[NAME_KEY]
if fields.get(PRICE_KEY) is not None:
storage[product_id][PRICE_KEY] = fields[PRICE_KEY]
if fields.get(QUANTITY_KEY) is not None:
storage[product_id][QUANTITY_KEY] = fields[QUANTITY_KEY]
return storage[product_id]


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 not in storage:
print(f"no product with id {product_id}")
return None
product_names.discard(storage[product_id][NAME_KEY])
del storage[product_id]
return product_id
Loading
Loading