import datetime
import csv
# --- CLASE 1: PRODUCTO (CON GETTERS/SETTERS Y VALIDACIÓN) ---
class Producto:
def __init__(self, nombre, precio, existencia):
self.nombre = nombre
self.precio = precio
self.existencia = existencia
@property
def precio(self):
return getattr(self, '_precio', 0)
@precio.setter
def precio(self, valor):
if valor < 0: raise ValueError("Precio no puede ser negativo")
self._precio = valor
@property
def existencia(self):
return getattr(self, '_existencia', 0)
@existencia.setter
def existencia(self, valor):
if valor < 0: raise ValueError("Existencia no puede ser negativa")
self._existencia = valor
# --- CLASE 2: PEDIDO (MÉTODOS ESTÁTICOS Y DE CLASE) ---
class Pedido:
descuento_global = 0
MINIMO_COMPRA = 50
def __init__(self, items_nombres, total_final):
self.items = items_nombres
self.total = total_final
self.fecha = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@staticmethod
def es_monto_valido(monto):
return monto >= Pedido.MINIMO_COMPRA
@classmethod
def crear_con_descuento(cls, nombres, subtotal):
total_con_desc = subtotal * (1 - cls.descuento_global / 100)
return cls(nombres, total_con_desc)
# --- CLASE 3: CUENTA BANCARIA (ENCAPSULAMIENTO Y ARCHIVOS) ---
class CuentaEmpresa:
def __init__(self, saldo_inicial=0):
self.__saldo = saldo_inicial
self.__historial = []
def _actualizar_saldo(self, monto):
self.__saldo += monto
self.__registrar_log(f"Venta registrada: +${monto:.2f}")
def __registrar_log(self, mensaje):
self.__historial.append([datetime.datetime.now(), mensaje])
def obtener_saldo(self):
return self.__saldo
# --- SISTEMA INTEGRADO ---
class SistemaPOS:
def __init__(self):
self.inventario = {}
self.banco = CuentaEmpresa(1000) # Capital inicial
def menu_principal(self):
while True:
print(f"\n=== POS SYSTEM | SALDO EN CAJA: ${self.banco.obtener_saldo():.2f} ===")
print("1. Inventario (Agregar/Ver)")
print("2. Nueva Venta (Pedido)")
print("3. Configurar Descuento Global")
print("4. Salir")
op = input("Seleccione: ")
if op == "1": self.gestion_inventario()
elif op == "2": self.procesar_venta()
elif op == "3":
desc = float(input("Nuevo descuento global (%): "))
Pedido.descuento_global = desc
elif op == "4": break
def gestion_inventario(self):
print("\n--- INVENTARIO ---")
for p in self.inventario.values():
print(f"- {p.nombre}: ${p.precio} (Stock: {p.existencia})")
if input("\n¿Agregar producto? (s/n): ").lower() == 's':
try:
n = input("Nombre: ")
p = float(input("Precio: "))
e = int(input("Stock: "))
self.inventario[n] = Producto(n, p, e)
except ValueError as err: print(f"Error: {err}")
def procesar_venta(self):
print("\n--- NUEVA VENTA ---")
carrito_nombres = []
subtotal = 0
while True:
prod_nom = input("Nombre del producto (o 'fin' para cobrar): ")
if prod_nom.lower() == 'fin': break
if prod_nom in self.inventario and self.inventario[prod_nom].existencia > 0:
p = self.inventario[prod_nom]
subtotal += p.precio
p.existencia -= 1
carrito_nombres.append(prod_nom)
print(f"Agregado. Subtotal: ${subtotal}")
else:
print("No disponible o sin stock.")
if Pedido.es_monto_valido(subtotal):
venta = Pedido.crear_con_descuento(carrito_nombres, subtotal)
self.banco._actualizar_saldo(venta.total)
print(f"\n✅ VENTA REALIZADA")
print(f"Total con {Pedido.descuento_global}% desc: ${venta.total:.2f}")
else:
print(f"❌ Venta cancelada: No llega al mínimo de ${Pedido.MINIMO_COMPRA}")
if __name__ == "__main__":
pos = SistemaPOS()
pos.menu_principal()