{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "39d71539",
   "metadata": {},
   "source": [
    "# Proyecto final: PyShop\n",
    "\n",
    "Este notebook es la **solución de referencia** del proyecto final. Constrúyelo primero por tu cuenta\n",
    "con el enunciado (PDF) y úsalo después para comparar.\n",
    "\n",
    "## Requisitos mínimos\n",
    "\n",
    "1. **Excepciones propias:** una raíz `ErrorTienda` y tres subclases: `PrecioInvalidoError`\n",
    "   (también `ValueError`), `StockInsuficienteError` (con `faltante`) y `ProductoNoEncontradoError`\n",
    "   (también `KeyError`).\n",
    "2. **Productos:** `Producto` abstracto con `precio` validado por una `property`, `stock` de solo\n",
    "   lectura y `costo_envio` abstracto; subclases `ProductoFisico` y `ProductoDigital`.\n",
    "3. **Descuentos:** `Descuento` abstracto con `DescuentoPorcentaje` y `DescuentoFijo`.\n",
    "4. **Carrito:** composición de líneas inmutables (`Linea`); `subtotal`, `envio`, `total` y un\n",
    "   `confirmar` **atómico**: o se surte todo el pedido o no se toca el stock.\n",
    "5. **Tienda:** catálogo por SKU y `buscar(sku)` que lanza `ProductoNoEncontradoError`.\n",
    "\n",
    "Solo se usa la biblioteca estándar (`abc`, `dataclasses`, `decimal`). Ejecuta las celdas en orden."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "909936e8",
   "metadata": {},
   "source": [
    "## 1. Excepciones\n",
    "\n",
    "Una raíz común permite atrapar cualquier error de la tienda con un solo `except ErrorTienda`.\n",
    "La herencia múltiple con `ValueError` y `KeyError` mantiene compatible el código que ya atrapaba\n",
    "esas excepciones estándar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cfa57c9c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.675613Z",
     "iopub.status.busy": "2026-10-05T18:23:07.675457Z",
     "iopub.status.idle": "2026-10-05T18:23:07.681542Z",
     "shell.execute_reply": "2026-10-05T18:23:07.680948Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PrecioInvalidoError -> ['ErrorTienda', 'ValueError', 'Exception']\n",
      "StockInsuficienteError -> ['ErrorTienda', 'Exception']\n",
      "ProductoNoEncontradoError -> ['ErrorTienda', 'KeyError', 'LookupError', 'Exception']\n"
     ]
    }
   ],
   "source": [
    "from abc import ABC, abstractmethod\n",
    "from dataclasses import dataclass, FrozenInstanceError\n",
    "\n",
    "\n",
    "class ErrorTienda(Exception):\n",
    "    \"\"\"Raíz de todos los errores de la tienda.\"\"\"\n",
    "\n",
    "\n",
    "class PrecioInvalidoError(ErrorTienda, ValueError):\n",
    "    \"\"\"Precio menor o igual a cero.\"\"\"\n",
    "\n",
    "\n",
    "class StockInsuficienteError(ErrorTienda):\n",
    "    def __init__(self, producto, disponible, solicitado):\n",
    "        super().__init__(\n",
    "            f\"{producto}: hay {disponible} y se pidieron {solicitado}\"\n",
    "        )\n",
    "        self.producto = producto\n",
    "        self.disponible = disponible\n",
    "        self.solicitado = solicitado\n",
    "        self.faltante = solicitado - disponible\n",
    "\n",
    "\n",
    "class ProductoNoEncontradoError(ErrorTienda, KeyError):\n",
    "    \"\"\"El SKU no existe en el catálogo.\"\"\"\n",
    "\n",
    "\n",
    "for exc in (PrecioInvalidoError, StockInsuficienteError,\n",
    "            ProductoNoEncontradoError):\n",
    "    print(exc.__name__, \"->\", [k.__name__ for k in exc.__mro__[1:-2]])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c12d677a",
   "metadata": {},
   "source": [
    "## 2. Productos\n",
    "\n",
    "`Producto` concentra lo común (nombre, precio validado, stock, SKU automático) y deja abstracto\n",
    "`costo_envio`. Además define `hay_stock(cantidad)`: el carrito la usa sin preguntar el tipo de\n",
    "producto, y `ProductoDigital` la sobrescribe porque un archivo no se agota."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "68eac9d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.682935Z",
     "iopub.status.busy": "2026-10-05T18:23:07.682795Z",
     "iopub.status.idle": "2026-10-05T18:23:07.690766Z",
     "shell.execute_reply": "2026-10-05T18:23:07.690078Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ProductoFisico', 'Producto', 'ABC', 'object']\n"
     ]
    }
   ],
   "source": [
    "class Producto(ABC):\n",
    "    moneda = \"MXN\"          # atributo de clase\n",
    "    _siguiente_sku = 100    # contador compartido\n",
    "\n",
    "    def __init__(self, nombre, precio, stock=0):\n",
    "        self.nombre = nombre\n",
    "        self.precio = precio        # pasa por el setter\n",
    "        self._stock = stock\n",
    "        self.sku = Producto._siguiente_sku\n",
    "        Producto._siguiente_sku += 1\n",
    "\n",
    "    @property\n",
    "    def precio(self):\n",
    "        return self._precio\n",
    "\n",
    "    @precio.setter\n",
    "    def precio(self, valor):\n",
    "        if valor <= 0:\n",
    "            raise PrecioInvalidoError(\n",
    "                f\"Precio inválido para {self.nombre}: {valor}\"\n",
    "            )\n",
    "        self._precio = round(valor, 2)\n",
    "\n",
    "    @property\n",
    "    def stock(self):             # solo lectura: no hay setter\n",
    "        return self._stock\n",
    "\n",
    "    def hay_stock(self, cantidad):\n",
    "        return cantidad <= self._stock\n",
    "\n",
    "    def reponer(self, cantidad):\n",
    "        self._stock += cantidad\n",
    "\n",
    "    def retirar(self, cantidad):\n",
    "        if not self.hay_stock(cantidad):\n",
    "            raise StockInsuficienteError(\n",
    "                self.nombre, self._stock, cantidad\n",
    "            )\n",
    "        self._stock -= cantidad\n",
    "\n",
    "    def subtotal(self, cantidad):\n",
    "        return round(self.precio * cantidad, 2)\n",
    "\n",
    "    @abstractmethod\n",
    "    def costo_envio(self, cantidad):\n",
    "        \"\"\"Cada tipo de producto calcula su envío.\"\"\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return (f\"{type(self).__name__}({self.nombre!r}, \"\n",
    "                f\"precio={self.precio}, stock={self._stock})\")\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.nombre} — ${self.precio:,.2f} {self.moneda}\"\n",
    "\n",
    "\n",
    "class ProductoFisico(Producto):\n",
    "    def __init__(self, nombre, precio, stock=0, peso_kg=1.0):\n",
    "        super().__init__(nombre, precio, stock)\n",
    "        self.peso_kg = peso_kg\n",
    "\n",
    "    def costo_envio(self, cantidad):\n",
    "        return round(49 + 15 * self.peso_kg * cantidad, 2)\n",
    "\n",
    "\n",
    "class ProductoDigital(Producto):\n",
    "    def __init__(self, nombre, precio):\n",
    "        super().__init__(nombre, precio, stock=0)\n",
    "\n",
    "    def hay_stock(self, cantidad):   # un archivo no se agota\n",
    "        return True\n",
    "\n",
    "    def retirar(self, cantidad):\n",
    "        pass\n",
    "\n",
    "    def costo_envio(self, cantidad):\n",
    "        return 0.0\n",
    "\n",
    "\n",
    "print([k.__name__ for k in ProductoFisico.__mro__])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43af07b2",
   "metadata": {},
   "source": [
    "## 3. Descuentos\n",
    "\n",
    "El carrito solo sabe que un descuento tiene `aplicar(subtotal)`, que devuelve **el monto a\n",
    "descontar**. Agregar un tipo nuevo de descuento no obliga a tocar el carrito."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ac2b97a4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.692289Z",
     "iopub.status.busy": "2026-10-05T18:23:07.692160Z",
     "iopub.status.idle": "2026-10-05T18:23:07.696799Z",
     "shell.execute_reply": "2026-10-05T18:23:07.696058Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "149.6 0.0\n"
     ]
    }
   ],
   "source": [
    "class Descuento(ABC):\n",
    "    @abstractmethod\n",
    "    def aplicar(self, subtotal):\n",
    "        \"\"\"Devuelve el monto a descontar.\"\"\"\n",
    "\n",
    "\n",
    "class DescuentoPorcentaje(Descuento):\n",
    "    def __init__(self, porcentaje):\n",
    "        if not 0 < porcentaje <= 100:\n",
    "            raise ValueError(\"El porcentaje va de 0 a 100\")\n",
    "        self.porcentaje = porcentaje\n",
    "\n",
    "    def aplicar(self, subtotal):\n",
    "        return round(subtotal * self.porcentaje / 100, 2)\n",
    "\n",
    "\n",
    "class DescuentoFijo(Descuento):\n",
    "    def __init__(self, monto, minimo=0):\n",
    "        self.monto = monto\n",
    "        self.minimo = minimo\n",
    "\n",
    "    def aplicar(self, subtotal):\n",
    "        if subtotal < self.minimo:\n",
    "            return 0.0\n",
    "        return min(self.monto, subtotal)   # nunca más que el subtotal\n",
    "\n",
    "\n",
    "print(DescuentoPorcentaje(10).aplicar(1496.0),\n",
    "      DescuentoFijo(200, minimo=1500).aplicar(1496.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f42c0f6",
   "metadata": {},
   "source": [
    "## 4. Carrito y tienda\n",
    "\n",
    "`Linea` es un `@dataclass(frozen=True)`: una vez creada no cambia. El `Carrito` **tiene** líneas\n",
    "(composición). `confirmar` trabaja en dos pasadas: primero suma lo pedido por producto y valida\n",
    "todo; solo si todo alcanza, descuenta el stock. Sumar por producto evita que dos líneas del mismo\n",
    "artículo pasen la validación por separado."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4d4863b2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.698076Z",
     "iopub.status.busy": "2026-10-05T18:23:07.697946Z",
     "iopub.status.idle": "2026-10-05T18:23:07.705669Z",
     "shell.execute_reply": "2026-10-05T18:23:07.704943Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clases listas: Linea Carrito Tienda\n"
     ]
    }
   ],
   "source": [
    "@dataclass(frozen=True)\n",
    "class Linea:\n",
    "    producto: Producto\n",
    "    cantidad: int\n",
    "\n",
    "    def subtotal(self):\n",
    "        return self.producto.subtotal(self.cantidad)\n",
    "\n",
    "\n",
    "class Carrito:\n",
    "    def __init__(self, cliente):\n",
    "        self.cliente = cliente\n",
    "        self._lineas = []\n",
    "        self.descuento = None\n",
    "\n",
    "    def agregar(self, producto, cantidad=1):\n",
    "        if cantidad <= 0:\n",
    "            raise ValueError(\"La cantidad debe ser positiva\")\n",
    "        self._lineas.append(Linea(producto, cantidad))\n",
    "\n",
    "    def subtotal(self):\n",
    "        return round(sum(l.subtotal() for l in self._lineas), 2)\n",
    "\n",
    "    def envio(self):\n",
    "        return round(sum(l.producto.costo_envio(l.cantidad)\n",
    "                         for l in self._lineas), 2)\n",
    "\n",
    "    def total(self):\n",
    "        rebaja = 0.0\n",
    "        if self.descuento is not None:\n",
    "            rebaja = self.descuento.aplicar(self.subtotal())\n",
    "        return round(self.subtotal() - rebaja + self.envio(), 2)\n",
    "\n",
    "    def confirmar(self):\n",
    "        pedido = {}                      # producto -> cantidad total\n",
    "        for l in self._lineas:\n",
    "            pedido[l.producto] = pedido.get(l.producto, 0) + l.cantidad\n",
    "        for producto, cantidad in pedido.items():   # 1) validar\n",
    "            if not producto.hay_stock(cantidad):\n",
    "                raise StockInsuficienteError(\n",
    "                    producto.nombre, producto.stock, cantidad\n",
    "                )\n",
    "        for producto, cantidad in pedido.items():   # 2) descontar\n",
    "            producto.retirar(cantidad)\n",
    "        return self.total()\n",
    "\n",
    "    def __len__(self):\n",
    "        return sum(l.cantidad for l in self._lineas)\n",
    "\n",
    "    def __iter__(self):\n",
    "        return iter(self._lineas)\n",
    "\n",
    "\n",
    "class Tienda:\n",
    "    def __init__(self, nombre):\n",
    "        self.nombre = nombre\n",
    "        self._catalogo = {}\n",
    "\n",
    "    def registrar(self, producto):\n",
    "        self._catalogo[producto.sku] = producto\n",
    "        return producto\n",
    "\n",
    "    def buscar(self, sku):\n",
    "        try:\n",
    "            return self._catalogo[sku]\n",
    "        except KeyError:\n",
    "            raise ProductoNoEncontradoError(sku) from None\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self._catalogo)\n",
    "\n",
    "\n",
    "print(\"Clases listas:\", Linea.__name__, Carrito.__name__,\n",
    "      Tienda.__name__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "592eaa3e",
   "metadata": {},
   "source": [
    "## 5. Un pedido de punta a punta\n",
    "\n",
    "Ana compra 2 tazas, 1 teclado y 1 ebook. Después Luis intenta llevarse 5 teclados cuando solo\n",
    "quedan 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fd73d8a2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.707688Z",
     "iopub.status.busy": "2026-10-05T18:23:07.707546Z",
     "iopub.status.idle": "2026-10-05T18:23:07.712649Z",
     "shell.execute_reply": "2026-10-05T18:23:07.712196Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ProductoFisico('Taza', precio=149.0, stock=20) | Taza — $149.00 MXN\n",
      "SKU: 100 101 102 | productos: 3\n",
      "  2 x Taza: 298.0\n",
      "  1 x Teclado: 899.0\n",
      "  1 x Ebook de Python: 299.0\n",
      "artículos: 4 | subtotal: 1496.0 | envío: 128.0 | total: 1624.0\n",
      "con 10 %: 1474.4\n",
      "con fijo 200 (mínimo 1500): 1624.0\n",
      "confirmar: 1624.0 | stock taza 18 teclado 2\n",
      "Error: Teclado: hay 2 y se pidieron 5 | faltante 3\n"
     ]
    }
   ],
   "source": [
    "tienda = Tienda(\"PyShop\")\n",
    "taza = tienda.registrar(\n",
    "    ProductoFisico(\"Taza\", 149.0, stock=20, peso_kg=0.4))\n",
    "teclado = tienda.registrar(\n",
    "    ProductoFisico(\"Teclado\", 899.0, stock=3, peso_kg=1.2))\n",
    "ebook = tienda.registrar(ProductoDigital(\"Ebook de Python\", 299.0))\n",
    "\n",
    "print(repr(taza), \"|\", taza)\n",
    "print(\"SKU:\", taza.sku, teclado.sku, ebook.sku,\n",
    "      \"| productos:\", len(tienda))\n",
    "\n",
    "carrito = Carrito(\"Ana\")\n",
    "carrito.agregar(tienda.buscar(100), 2)\n",
    "carrito.agregar(tienda.buscar(101), 1)\n",
    "carrito.agregar(tienda.buscar(102), 1)\n",
    "for linea in carrito:\n",
    "    print(f\"  {linea.cantidad} x {linea.producto.nombre}: \"\n",
    "          f\"{linea.subtotal()}\")\n",
    "print(\"artículos:\", len(carrito), \"| subtotal:\", carrito.subtotal(),\n",
    "      \"| envío:\", carrito.envio(), \"| total:\", carrito.total())\n",
    "\n",
    "carrito.descuento = DescuentoPorcentaje(10)\n",
    "print(\"con 10 %:\", carrito.total())\n",
    "carrito.descuento = DescuentoFijo(200, minimo=1500)\n",
    "print(\"con fijo 200 (mínimo 1500):\", carrito.total())\n",
    "\n",
    "print(\"confirmar:\", carrito.confirmar(),\n",
    "      \"| stock taza\", taza.stock, \"teclado\", teclado.stock)\n",
    "\n",
    "otro = Carrito(\"Luis\")\n",
    "otro.agregar(teclado, 5)\n",
    "try:\n",
    "    otro.confirmar()\n",
    "except StockInsuficienteError as e:\n",
    "    print(\"Error:\", e, \"| faltante\", e.faltante)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9508fba8",
   "metadata": {},
   "source": [
    "## 6. Pruebas con `assert`\n",
    "\n",
    "Cada prueba arma su propia tienda con `nueva_tienda()` para no depender del estado que dejaron\n",
    "las celdas anteriores. Si un `assert` falla, Python detiene la celda con `AssertionError` y te\n",
    "dice qué línea no se cumplió. Los errores esperados se comprueban dentro de `try/except`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "70d4f952",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.713975Z",
     "iopub.status.busy": "2026-10-05T18:23:07.713842Z",
     "iopub.status.idle": "2026-10-05T18:23:07.722360Z",
     "shell.execute_reply": "2026-10-05T18:23:07.721742Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK prueba_productos\n",
      "OK prueba_totales\n",
      "OK prueba_confirmar\n",
      "OK prueba_atomico\n",
      "OK prueba_errores\n",
      "5 pruebas pasaron\n"
     ]
    }
   ],
   "source": [
    "def nueva_tienda():\n",
    "    t = Tienda(\"PyShop\")\n",
    "    a = t.registrar(ProductoFisico(\"Taza\", 149.0, 20, peso_kg=0.4))\n",
    "    b = t.registrar(ProductoFisico(\"Teclado\", 899.0, 3, peso_kg=1.2))\n",
    "    c = t.registrar(ProductoDigital(\"Ebook de Python\", 299.0))\n",
    "    return t, a, b, c\n",
    "\n",
    "\n",
    "def carrito_de_ana(a, b, c):\n",
    "    car = Carrito(\"Ana\")\n",
    "    car.agregar(a, 2)\n",
    "    car.agregar(b, 1)\n",
    "    car.agregar(c, 1)\n",
    "    return car\n",
    "\n",
    "\n",
    "def lanza(tipo_error, funcion):\n",
    "    \"\"\"True si funcion() lanza tipo_error.\"\"\"\n",
    "    try:\n",
    "        funcion()\n",
    "    except tipo_error:\n",
    "        return True\n",
    "    return False\n",
    "\n",
    "\n",
    "def prueba_productos():\n",
    "    t, a, b, c = nueva_tienda()\n",
    "    assert str(a) == \"Taza — $149.00 MXN\"\n",
    "    assert repr(a) == \"ProductoFisico('Taza', precio=149.0, stock=20)\"\n",
    "    assert a.costo_envio(2) == 61.0\n",
    "    assert b.costo_envio(1) == 67.0\n",
    "    assert c.costo_envio(5) == 0.0\n",
    "    assert t.buscar(b.sku) is b\n",
    "    assert lanza(TypeError, lambda: Producto(\"X\", 10))\n",
    "\n",
    "\n",
    "def prueba_totales():\n",
    "    t, a, b, c = nueva_tienda()\n",
    "    car = carrito_de_ana(a, b, c)\n",
    "    assert len(car) == 4\n",
    "    assert car.subtotal() == 1496.0\n",
    "    assert car.envio() == 128.0\n",
    "    assert car.total() == 1624.0\n",
    "    car.descuento = DescuentoPorcentaje(10)\n",
    "    assert car.total() == 1474.4\n",
    "    car.descuento = DescuentoFijo(200, minimo=1500)\n",
    "    assert car.total() == 1624.0        # 1496 < 1500: no aplica\n",
    "    car.descuento = DescuentoFijo(200, minimo=1000)\n",
    "    assert car.total() == 1424.0\n",
    "\n",
    "\n",
    "def prueba_confirmar():\n",
    "    t, a, b, c = nueva_tienda()\n",
    "    assert carrito_de_ana(a, b, c).confirmar() == 1624.0\n",
    "    assert (a.stock, b.stock) == (18, 2)\n",
    "    luis = Carrito(\"Luis\")\n",
    "    luis.agregar(b, 5)\n",
    "    try:\n",
    "        luis.confirmar()\n",
    "    except StockInsuficienteError as e:\n",
    "        assert e.faltante == 3\n",
    "        assert str(e) == \"Teclado: hay 2 y se pidieron 5\"\n",
    "    else:\n",
    "        raise AssertionError(\"debió lanzar StockInsuficienteError\")\n",
    "\n",
    "\n",
    "def prueba_atomico():\n",
    "    t, a, b, c = nueva_tienda()\n",
    "    car = Carrito(\"Eva\")\n",
    "    car.agregar(a, 2)        # la taza sí alcanza...\n",
    "    car.agregar(b, 2)\n",
    "    car.agregar(b, 2)        # ...pero 4 teclados no (hay 3)\n",
    "    assert lanza(StockInsuficienteError, car.confirmar)\n",
    "    assert (a.stock, b.stock) == (20, 3)   # nada se descontó\n",
    "\n",
    "\n",
    "def prueba_errores():\n",
    "    t, a, b, c = nueva_tienda()\n",
    "\n",
    "    def precio_negativo():\n",
    "        a.precio = -10\n",
    "\n",
    "    def asignar_stock():\n",
    "        a.stock = 1000\n",
    "\n",
    "    assert lanza(PrecioInvalidoError, precio_negativo)\n",
    "    assert lanza(ValueError, precio_negativo)     # también es ValueError\n",
    "    assert a.precio == 149.0                       # no cambió\n",
    "    assert lanza(AttributeError, asignar_stock)\n",
    "    assert lanza(ProductoNoEncontradoError, lambda: t.buscar(999))\n",
    "    assert lanza(KeyError, lambda: t.buscar(999))\n",
    "    assert lanza(ErrorTienda, lambda: t.buscar(999))\n",
    "    linea = Linea(a, 2)\n",
    "    assert linea == Linea(a, 2)                    # igualdad por valor\n",
    "\n",
    "    def cambiar_linea():\n",
    "        linea.cantidad = 5\n",
    "\n",
    "    assert lanza(FrozenInstanceError, cambiar_linea)\n",
    "\n",
    "\n",
    "pruebas = [prueba_productos, prueba_totales, prueba_confirmar,\n",
    "           prueba_atomico, prueba_errores]\n",
    "for prueba in pruebas:\n",
    "    prueba()\n",
    "    print(\"OK\", prueba.__name__)\n",
    "print(f\"{len(pruebas)} pruebas pasaron\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5efac726",
   "metadata": {},
   "source": [
    "## 7. Dinero exacto\n",
    "\n",
    "Los `float` son binarios y no representan exactamente valores como 0.1. Para centavos que deben\n",
    "cuadrar, usa `decimal.Decimal` creado **desde texto**, o guarda los montos como centavos enteros."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e78c4c5e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-05T18:23:07.723638Z",
     "iopub.status.busy": "2026-10-05T18:23:07.723513Z",
     "iopub.status.idle": "2026-10-05T18:23:07.727735Z",
     "shell.execute_reply": "2026-10-05T18:23:07.727295Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "float: 0.30000000000000004 | igual a 0.3: False\n",
      "Decimal: 0.3\n",
      "Decimal desde float: 0.1000000000000000055511151231257827021181583404541015625\n",
      "total con 10 %: 1474.40\n",
      "subtotal en centavos: 149600 -> $1,496.00\n"
     ]
    }
   ],
   "source": [
    "from decimal import Decimal, ROUND_HALF_UP\n",
    "\n",
    "print(\"float:\", 0.1 + 0.2, \"| igual a 0.3:\", 0.1 + 0.2 == 0.3)\n",
    "print(\"Decimal:\", Decimal(\"0.1\") + Decimal(\"0.2\"))\n",
    "print(\"Decimal desde float:\", Decimal(0.1))\n",
    "\n",
    "subtotal = Decimal(\"1496.00\")\n",
    "rebaja = (subtotal * Decimal(\"10\") / 100).quantize(\n",
    "    Decimal(\"0.01\"), rounding=ROUND_HALF_UP)\n",
    "print(\"total con 10 %:\", subtotal - rebaja + Decimal(\"128.00\"))\n",
    "\n",
    "centavos = 2 * 14900 + 89900 + 29900      # todo en enteros\n",
    "print(\"subtotal en centavos:\", centavos,\n",
    "      \"->\", f\"${centavos / 100:,.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f619f157",
   "metadata": {},
   "source": [
    "## Extensiones sugeridas\n",
    "\n",
    "- **Dinero con `Decimal`:** cambia `precio`, `subtotal` y los descuentos a `Decimal` y comprueba\n",
    "  que los totales siguen cuadrando.\n",
    "- **Descuento por piezas:** `DescuentoPorPiezas(minimo_piezas, porcentaje)` sin modificar `Carrito`.\n",
    "- **Más tipos de producto:** `ProductoPerecedero` con fecha de caducidad que no se puede vender\n",
    "  vencido.\n",
    "- **Historial de pedidos:** que `Tienda` guarde cada pedido confirmado y calcule las ventas totales.\n",
    "- **Notas en errores:** usa `e.add_note(...)` (Python 3.11+) para añadir el nombre del cliente al\n",
    "  error de stock.\n",
    "- **Pruebas con `unittest` o `pytest`:** convierte las funciones `prueba_*` en pruebas formales.\n",
    "- **Carrito de un solo uso:** que un carrito confirmado no se pueda confirmar dos veces."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
