# sistema_inventario.py
# MODELO
class Item:
def __init__(self, name, quantity, price):
self.name = name
self.quantity = quantity
self.price = price
# REPOSITORIO
class ItemRepository:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def get_items(self):
return self.items
def find_item(self, name):
return next((item for item in self.items if item.name == name), None)
# SERVICIO
class InventarioService:
def __init__(self, repository: ItemRepository):
self.repository = repository
def add_item(self, name, quantity, price):
if quantity < 0 or price < 0:
raise ValueError("La cantidad y el precio deben ser mayores o iguales a cero.")
item = Item(name, quantity, price)
self.repository.add_item(item)
def listar_items(self):
return self.repository.get_items()
def buscar_item(self, name):
item = self.repository.find_item(name)
if not item:
raise ValueError("El artículo no se encontró en el inventario.")
return item
# CONTROLADOR
class InventarioController:
def __init__(self, service: InventarioService):
self.service = service
def agregar_item(self, name, quantity, price):
try:
self.service.add_item(name, quantity, price)
print(f"Artículo '{name}' agregado exitosamente.")
except ValueError as e:
print(f"Error al agregar el artículo: {e}")
def listar_items(self):
items = self.service.listar_items()
for item in items:
print(f"{item.name}: {item.quantity} unidades a ${item.price} cada uno")
def buscar_item(self, name):
try:
item = self.service.buscar_item(name)
print(f"Artículo encontrado: {item.name}, Cantidad: {item.quantity}, Precio: {item.price}")
except ValueError as e:
print(e)
# VISTA
class InventarioView:
def __init__(self, controller: InventarioController):
self.controller = controller
def mostrar_menu(self):
while True:
print("\n1. Agregar Item")
print("2. Listar Items")
print("3. Buscar Item")
print("4. Salir")
opcion = input("Seleccione una opción: ")
if opcion == "1":
name = input("Nombre del item: ")
quantity = int(input("Cantidad: "))
price = float(input("Precio: "))
self.controller.agregar_item(name, quantity, price)
elif opcion == "2":
self.controller.listar_items()
elif opcion == "3":
name = input("Nombre del item a buscar: ")
self.controller.buscar_item(name)
elif opcion == "4":
break
else:
print("Opción no válida.")
# EJECUCIÓN PRINCIPAL
def main():
repository = ItemRepository()
service = InventarioService(repository)
controller = InventarioController(service)
view = InventarioView(controller)
view.mostrar_menu()
if __name__ == "__main__":
main()
Click Run or press shift + ENTER to run code