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
83 changes: 33 additions & 50 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``.
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.
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

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
product[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 product_id not in cart:
print(f"product {product_id} is not in the cart")
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 cart[product_id] < quantity:
print(
f"cart holds only {cart[product_id]} unit(s) of product "
f"{product_id}, cannot remove {quantity}"
)
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.
if product_id not in storage:
print(f"no product with id {product_id}")
return None

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
storage[product_id][QUANTITY_KEY] += quantity
remainig = cart[product_id] - quantity
if remainig == 0:
del cart[product_id]
else:
cart[product_id] = remainig
return remainig
157 changes: 60 additions & 97 deletions src/part4/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,135 +23,98 @@
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 ""

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

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.
product_id = generate_product_id()
storage[product_id] = {
NAME_KEY: name,
PRICE_KEY: normalize_price(fields[PRICE_KEY]),
QUANTITY_KEY: fields[QUANTITY_KEY],
}
product_names.add(name)
return product_id

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

def read_product(storage: dict[str, Product], product_id: str) -> Product | None:
if product_id not in storage:
print(f"no product with id {product_id}")
return None
return storage[product_id]

def update_product(
storage: dict[str, Product],
product_names: set[str],
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

product = storage[product_id]
new_name: str | None = None

if NAME_KEY in fields:
new_name = normalize_product_name(fields[NAME_KEY])
if not new_name:
print("product name must not be blank")
return None
if new_name != product[NAME_KEY] and new_name in product_names:
print(f"product name '{new_name}' is already taken")
return None
fields[NAME_KEY] = new_name

if PRICE_KEY in fields:
fields[PRICE_KEY] = normalize_price(fields[PRICE_KEY])

if new_name is not None and new_name != product[NAME_KEY]:
product_names.discard(product[NAME_KEY])
product_names.add(new_name)

for key in (NAME_KEY, PRICE_KEY, QUANTITY_KEY):
if key in fields:
product[key] = fields[key]

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

product = storage.pop(product_id)
product_names.discard(product[NAME_KEY])
return product_id
Loading
Loading