⬅️ 上一课下一课 ➡️

第30课:阶段项目——智能收银系统

🎯 本课目标

  • 综合运用第三阶段所有条件判断知识
  • 制作完整的智能收银系统
  • 实现商品管理和选购功能
  • 添加折扣和优惠计算逻辑
  • 制作找零和小票打印功能

🤔 趣味引入:超市里的"智慧"

想象一下:你去超市购物时,收银员是怎么工作的?

  • 🛒 扫描商品 → 识别每件商品的价格
  • 💰 计算总额 → 把所有商品价格加起来
  • 🏷️ 打折优惠 → 根据促销活动减价
  • 💵 收取付款 → 收钱并计算找零
  • 🧾 打印小票 → 列出所有购物明细

今天,让我们一起用Python制作智能收银系统,成为超市的"金牌收银员"!


🔧 第一部分:商品管理系统

1.1 商品数据库

# 商品数据库
print("🏪 商品管理系统")
print("=" * 50)

# 商品数据:编号、名称、单价、单位
products = {
    "001": {"name": "苹果", "price": 5.00, "unit": "斤", "category": "水果"},
    "002": {"name": "香蕉", "price": 3.50, "unit": "斤", "category": "水果"},
    "003": {"name": "牛奶", "price": 12.00, "unit": "盒", "category": "饮品"},
    "004": {"name": "面包", "price": 8.00, "unit": "个", "category": "食品"},
    "005": {"name": "鸡蛋", "price": 1.50, "unit": "个", "category": "食品"},
    "006": {"name": "可乐", "price": 3.00, "unit": "瓶", "category": "饮品"},
    "007": {"name": "薯片", "price": 6.00, "unit": "袋", "category": "零食"},
    "008": {"name": "巧克力", "price": 15.00, "unit": "块", "category": "零食"},
    "009": {"name": "大米", "price": 3.00, "unit": "斤", "category": "粮油"},
    "010": {"name": "食用油", "price": 45.00, "unit": "桶", "category": "粮油"}
}

def display_products():
    """显示所有商品"""
    print(f"\n{'='*60}")
    print(f"{'📋 商品列表':^60}")
    print(f"{'='*60}")
    print(f"{'编号':<6} {'名称':<10} {'单价':>8} {'单位':<6} {'类别':<10}")
    print(f"{'-'*60}")
    
    for code, info in products.items():
        print(f"{code:<6} {info['name']:<10} ¥{info['price']:>6.2f} /{info['unit']:<4} {info['category']:<10}")

def search_product(keyword):
    """搜索商品"""
    results = []
    for code, info in products.items():
        if keyword in info['name'] or keyword in info['category']:
            results.append((code, info))
    return results

def get_product_by_code(code):
    """根据编号获取商品"""
    return products.get(code)

# 显示商品
display_products()

# 搜索功能演示
print("\n🔍 搜索示例:")
keyword = input("输入关键词搜索商品:")
results = search_product(keyword)

if results:
    print(f"\n找到{len(results)}个商品:")
    for code, info in results:
        print(f"  {code} {info['name']} ¥{info['price']}/ {info['unit']}")
else:
    print("❌ 未找到相关商品")

1.2 购物车管理

# 购物车管理
print("\n🛒 购物车管理系统")
print("=" * 50)

class ShoppingCart:
    """购物车类"""
    
    def __init__(self):
        self.items = {}  # {code: {"product": info, "quantity": 数量}}
        self.member_discount = 0  # 会员折扣(百分比)
        self.coupon_discount = 0  # 优惠券折扣(金额)
    
    def add_item(self, product_code, quantity=1):
        """添加商品到购物车"""
        product = get_product_by_code(product_code)
        
        if not product:
            return False, "❌ 商品编号不存在!"
        
        if quantity <= 0:
            return False, "❌ 数量必须大于0!"
        
        if product_code in self.items:
            self.items[product_code]["quantity"] += quantity
        else:
            self.items[product_code] = {
                "product": product,
                "quantity": quantity
            }
        
        return True, f"✅ 已添加 {product['name']} × {quantity}{product['unit']}"
    
    def remove_item(self, product_code, quantity=1):
        """移除商品"""
        if product_code not in self.items:
            return False, "❌ 购物车中没有该商品!"
        
        current_qty = self.items[product_code]["quantity"]
        
        if quantity >= current_qty:
            del self.items[product_code]
            return True, "✅ 已从购物车移除该商品"
        else:
            self.items[product_code]["quantity"] -= quantity
            product = self.items[product_code]["product"]
            return True, f"✅ 已移除 {product['name']} × {quantity}"
    
    def update_quantity(self, product_code, new_quantity):
        """更新商品数量"""
        if product_code not in self.items:
            return False, "❌ 购物车中没有该商品!"
        
        if new_quantity <= 0:
            return self.remove_item(product_code, self.items[product_code]["quantity"])
        
        self.items[product_code]["quantity"] = new_quantity
        product = self.items[product_code]["product"]
        return True, f"✅ 已更新 {product['name']} 数量为 {new_quantity}"
    
    def get_subtotal(self):
        """计算小计(折扣前)"""
        subtotal = 0
        for code, item in self.items.items():
            subtotal += item["product"]["price"] * item["quantity"]
        return subtotal
    
    def get_discount_amount(self):
        """计算折扣金额"""
        subtotal = self.get_subtotal()
        
        # 会员折扣
        member_saving = subtotal * (self.member_discount / 100)
        
        # 优惠券折扣
        coupon_saving = min(self.coupon_discount, subtotal - member_saving)
        
        return member_saving + coupon_saving
    
    def get_total(self):
        """计算应付总额"""
        subtotal = self.get_subtotal()
        discount = self.get_discount_amount()
        return subtotal - discount
    
    def set_member_discount(self, discount_percent):
        """设置会员折扣"""
        if 0 <= discount_percent <= 100:
            self.member_discount = discount_percent
            return True
        return False
    
    def set_coupon_discount(self, discount_amount):
        """设置优惠券"""
        if discount_amount >= 0:
            self.coupon_discount = discount_amount
            return True
        return False
    
    def clear_cart(self):
        """清空购物车"""
        self.items.clear()
        self.member_discount = 0
        self.coupon_discount = 0
    
    def get_items_count(self):
        """获取商品种类数"""
        return len(self.items)
    
    def get_total_quantity(self):
        """获取商品总数量"""
        return sum(item["quantity"] for item in self.items.values())
    
    def display_cart(self):
        """显示购物车内容"""
        if not self.items:
            print("🛒 购物车是空的")
            return
        
        print(f"\n{'='*60}")
        print(f"{'🛒 购物车内容':^60}")
        print(f"{'='*60}")
        print(f"{'编号':<6} {'商品':<10} {'单价':>8} {'数量':>6} {'小计':>10}")
        print(f"{'-'*60}")
        
        for code, item in self.items.items():
            product = item["product"]
            quantity = item["quantity"]
            line_total = product["price"] * quantity
            print(f"{code:<6} {product['name']:<10} ¥{product['price']:>6.2f} ×{quantity:>4} ¥{line_total:>8.2f}")
        
        print(f"{'-'*60}")
        print(f"{'小计':>38} ¥{self.get_subtotal():>8.2f}")
        
        if self.member_discount > 0:
            member_saving = self.get_subtotal() * (self.member_discount / 100)
            print(f"{'会员折扣':>38} -¥{member_saving:>8.2f}")
        
        if self.coupon_discount > 0:
            print(f"{'优惠券':>38} -¥{self.coupon_discount:>8.2f}")
        
        print(f"{'='*60}")
        print(f"{'应付总额':>38} ¥{self.get_total():>8.2f}")
        print(f"{'='*60}")

# 测试购物车
cart = ShoppingCart()

print("🛒 购物车操作演示:")
print("-" * 40)

# 添加商品
cart.add_item("001", 3)  # 3斤苹果
cart.add_item("003", 2)  # 2盒牛奶
cart.add_item("007", 1)  # 1袋薯片

# 显示购物车
cart.display_cart()

# 设置折扣
print("\n💡 设置会员折扣(9折):")
cart.set_member_discount(10)
cart.display_cart()

# 设置优惠券
print("\n💡 设置优惠券(减5元):")
cart.set_coupon_discount(5)
cart.display_cart()

📊 第二部分:收银结算系统

2.1 完整的收银流程

# 收银结算系统
print("\n💳 收银结算系统")
print("=" * 50)

class CashRegister:
    """收银机类"""
    
    def __init__(self):
        self.cart = ShoppingCart()
        self.receipt_number = 0
        self.daily_sales = 0
        self.transaction_history = []
    
    def scan_item(self):
        """扫描商品"""
        print("\n📦 扫描商品")
        print("输入商品编号添加,输入'done'完成扫描")
        
        while True:
            code = input("\n请输入商品编号(或'done'):")
            
            if code.lower() == "done":
                break
            
            product = get_product_by_code(code)
            
            if not product:
                print("❌ 商品编号不存在!")
                continue
            
            print(f"📋 {product['name']} ¥{product['price']}/{product['unit']}")
            
            try:
                quantity = float(input(f"数量({product['unit']}):"))
                success, message = self.cart.add_item(code, quantity)
                print(message)
            except ValueError:
                print("❌ 请输入有效的数量!")
    
    def apply_discounts(self):
        """应用折扣"""
        print("\n🏷️ 折扣优惠")
        print("1. 会员折扣")
        print("2. 优惠券")
        print("3. 跳过")
        
        choice = input("请选择(1-3):")
        
        if choice == "1":
            try:
                discount = float(input("会员折扣率(如9折输入10):"))
                if self.cart.set_member_discount(discount):
                    print(f"✅ 已设置会员折扣:{discount}%")
            except ValueError:
                print("❌ 请输入有效的折扣率!")
        
        elif choice == "2":
            try:
                amount = float(input("优惠券金额(元):"))
                if self.cart.set_coupon_discount(amount):
                    print(f"✅ 已使用优惠券:减{amount}元")
            except ValueError:
                print("❌ 请输入有效的金额!")
    
    def process_payment(self):
        """处理付款"""
        total = self.cart.get_total()
        
        print(f"\n💰 应收金额:¥{total:.2f}")
        
        try:
            payment = float(input("收到金额:¥"))
            
            if payment < total:
                print("❌ 金额不足!")
                return None
            
            change = payment - total
            
            print(f"\n{'='*50}")
            print(f"{'💵 交易完成':^50}")
            print(f"{'='*50}")
            print(f"应收:¥{total:.2f}")
            print(f"实收:¥{payment:.2f}")
            print(f"找零:¥{change:.2f}")
            
            return {
                "total": total,
                "payment": payment,
                "change": change
            }
            
        except ValueError:
            print("❌ 请输入有效的金额!")
            return None
    
    def print_receipt(self, payment_info):
        """打印小票"""
        self.receipt_number += 1
        receipt_no = f"{self.receipt_number:04d}"
        
        print(f"\n{'='*60}")
        print(f"{'🧾 购物小票':^60}")
        print(f"{'='*60}")
        print(f"小票号:{receipt_no}")
        print(f"日期:2024年1月")
        print(f"{'='*60}")
        print(f"{'商品':<12} {'单价':>8} {'数量':>6} {'小计':>10}")
        print(f"{'-'*60}")
        
        for code, item in self.cart.items.items():
            product = item["product"]
            quantity = item["quantity"]
            line_total = product["price"] * quantity
            print(f"{product['name']:<12} ¥{product['price']:>6.2f} ×{quantity:>4} ¥{line_total:>8.2f}")
        
        print(f"{'-'*60}")
        print(f"{'小计':>30} ¥{self.cart.get_subtotal():>8.2f}")
        
        if self.cart.member_discount > 0:
            saving = self.cart.get_subtotal() * (self.cart.member_discount / 100)
            print(f"{'会员折扣':>30} -¥{saving:>8.2f}")
        
        if self.cart.coupon_discount > 0:
            print(f"{'优惠券':>30} -¥{self.cart.coupon_discount:>8.2f}")
        
        print(f"{'='*60}")
        print(f"{'应付金额':>30} ¥{payment_info['total']:>8.2f}")
        print(f"{'实收金额':>30} ¥{payment_info['payment']:>8.2f}")
        print(f"{'找零金额':>30} ¥{payment_info['change']:>8.2f}")
        print(f"{'='*60}")
        print(f"{'感谢光临,欢迎下次惠顾!':^56}")
        print(f"{'='*60}")
        
        # 记录交易
        transaction = {
            "receipt_no": receipt_no,
            "items": dict(self.cart.items),
            "subtotal": self.cart.get_subtotal(),
            "member_discount": self.cart.member_discount,
            "coupon_discount": self.cart.coupon_discount,
            "total": payment_info["total"],
            "payment": payment_info["payment"],
            "change": payment_info["change"]
        }
        self.transaction_history.append(transaction)
        self.daily_sales += payment_info["total"]
        
        # 清空购物车
        self.cart.clear_cart()
    
    def show_daily_report(self):
        """显示日报表"""
        if not self.transaction_history:
            print("📊 今日暂无交易记录")
            return
        
        print(f"\n{'='*60}")
        print(f"{'📊 销售日报表':^60}")
        print(f"{'='*60}")
        print(f"交易笔数:{len(self.transaction_history)}笔")
        print(f"销售总额:¥{self.daily_sales:.2f}")
        
        print(f"\n交易明细:")
        for i, trans in enumerate(self.transaction_history, 1):
            items_count = len(trans["items"])
            print(f"  {i}. 小票{trans['receipt_no']} - {items_count}件商品 - ¥{trans['total']:.2f}")

# 运行收银系统
register = CashRegister()

print("🏪 欢迎使用智能收银系统!")
print("=" * 50)

while True:
    print("\n请选择操作:")
    print("1. 🛒 开始新订单")
    print("2. 📊 查看日报表")
    print("3. 🚪 下班结账")
    
    choice = input("\n请选择(1-3):")
    
    if choice == "3":
        register.show_daily_report()
        print("\n👋 下班了!辛苦了!")
        break
    
    elif choice == "2":
        register.show_daily_report()
    
    elif choice == "1":
        print(f"\n{'='*50}")
        print(f"{'🆕 新订单':^50}")
        print(f"{'='*50}")
        
        # 显示商品列表
        display_products()
        
        # 扫描商品
        register.scan_item()
        
        if register.cart.get_items_count() > 0:
            # 显示购物车
            register.cart.display_cart()
            
            # 应用折扣
            register.apply_discounts()
            
            # 显示最终金额
            register.cart.display_cart()
            
            # 处理付款
            payment_info = register.process_payment()
            
            if payment_info:
                # 打印小票
                register.print_receipt(payment_info)
        else:
            print("❌ 购物车为空,取消订单")
    
    else:
        print("❌ 请选择1-3!")

2.2 促销活动系统

# 促销活动系统
print("\n🎉 促销活动系统")
print("=" * 50)

class PromotionSystem:
    """促销活动系统"""
    
    def __init__(self):
        self.active_promotions = []
        self.promotion_history = []
    
    def add_buy_x_get_y_free(self, product_code, buy_qty, free_qty):
        """添加买X送Y活动"""
        promotion = {
            "type": "buy_x_get_y_free",
            "product_code": product_code,
            "buy_qty": buy_qty,
            "free_qty": free_qty,
            "description": f"买{buy_qty}送{free_qty}"
        }
        self.active_promotions.append(promotion)
        return True
    
    def add_discount_on_category(self, category, discount_percent, min_amount=0):
        """添加品类折扣"""
        promotion = {
            "type": "category_discount",
            "category": category,
            "discount_percent": discount_percent,
            "min_amount": min_amount,
            "description": f"{category}类{discount_percent}%折扣"
        }
        self.active_promotions.append(promotion)
        return True
    
    def add_full_reduction(self, threshold, reduction):
        """添加满减活动"""
        promotion = {
            "type": "full_reduction",
            "threshold": threshold,
            "reduction": reduction,
            "description": f"满¥{threshold}减¥{reduction}"
        }
        self.active_promotions.append(promotion)
        return True
    
    def add_time_limit_discount(self, product_code, discount_percent, start_hour, end_hour):
        """添加限时折扣"""
        promotion = {
            "type": "time_limit",
            "product_code": product_code,
            "discount_percent": discount_percent,
            "start_hour": start_hour,
            "end_hour": end_hour,
            "description": f"限时{discount_percent}%折扣"
        }
        self.active_promotions.append(promotion)
        return True
    
    def calculate_promotions(self, cart):
        """计算所有活动的优惠"""
        savings = []
        subtotal = cart.get_subtotal()
        
        for promo in self.active_promotions:
            if promo["type"] == "buy_x_get_y_free":
                # 买X送Y
                code = promo["product_code"]
                if code in cart.items:
                    qty = cart.items[code]["quantity"]
                    if qty >= promo["buy_qty"]:
                        free_count = (qty // promo["buy_qty"]) * promo["free_qty"]
                        product = cart.items[code]["product"]
                        saving = product["price"] * free_count
                        savings.append({
                            "description": f"{product['name']} {promo['description']}",
                            "amount": saving
                        })
            
            elif promo["type"] == "category_discount":
                # 品类折扣
                category = promo["category"]
                category_total = 0
                for code, item in cart.items.items():
                    if item["product"]["category"] == category:
                        category_total += item["product"]["price"] * item["quantity"]
                
                if category_total >= promo["min_amount"]:
                    saving = category_total * (promo["discount_percent"] / 100)
                    savings.append({
                        "description": f"{category}类{promo['discount_percent']}%折扣",
                        "amount": saving
                    })
            
            elif promo["type"] == "full_reduction":
                # 满减
                if subtotal >= promo["threshold"]:
                    savings.append({
                        "description": f"满¥{promo['threshold']}减¥{promo['reduction']}",
                        "amount": promo["reduction"]
                    })
        
        return savings
    
    def show_active_promotions(self):
        """显示当前活动"""
        if not self.active_promotions:
            print("📢 当前没有促销活动")
            return
        
        print(f"\n{'='*50}")
        print(f"{'🎉 当前促销活动':^50}")
        print(f"{'='*50}")
        
        for i, promo in enumerate(self.active_promotions, 1):
            print(f"{i}. {promo['description']}")

# 促销系统演示
promo_system = PromotionSystem()

print("🎉 促销活动设置:")
print("-" * 40)

# 添加促销活动
promo_system.add_buy_x_get_y_free("003", 2, 1)  # 牛奶买2送1
promo_system.add_discount_on_category("零食", 20)  # 零食8折
promo_system.add_full_reduction(50, 10)  # 满50减10

promo_system.show_active_promotions()

# 测试促销计算
test_cart = ShoppingCart()
test_cart.add_item("003", 3)  # 3盒牛奶
test_cart.add_item("007", 2)  # 2袋薯片

print("\n📋 测试购物车:")
test_cart.display_cart()

print("\n💰 促销优惠计算:")
savings = promo_system.calculate_promotions(test_cart)
total_saving = 0

for saving in savings:
    print(f"  🎉 {saving['description']}:省¥{saving['amount']:.2f}")
    total_saving += saving["amount"]

print(f"\n💵 总共节省:¥{total_saving:.2f}")

🎯 第三部分:智能收银系统整合

3.1 完整智能收银系统

# 完整智能收银系统
print("\n🏪 智能收银系统 V2.0")
print("=" * 50)

class SmartCashRegister(CashRegister):
    """智能收银系统"""
    
    def __init__(self):
        super().__init__()
        self.promotion_system = PromotionSystem()
        self.members = {}  # 会员系统
        self.current_member = None
    
    def member_login(self):
        """会员登录"""
        print("\n👤 会员登录")
        phone = input("请输入手机号:")
        
        if phone in self.members:
            member = self.members[phone]
            print(f"欢迎回来,{member['name']}!")
            print(f"积分:{member['points']}")
            self.current_member = member
            return member
        else:
            register = input("未注册,是否注册?(是/否):")
            if register == "是":
                name = input("请输入姓名:")
                self.members[phone] = {
                    "name": name,
                    "phone": phone,
                    "points": 0,
                    "level": "普通会员"
                }
                self.current_member = self.members[phone]
                print(f"✅ 注册成功!欢迎{name}!")
                return self.members[phone]
            else:
                return None
    
    def auto_apply_promotions(self):
        """自动应用最优促销方案"""
        savings = self.promotion_system.calculate_promotions(self.cart)
        
        total_saving = 0
        for saving in savings:
            total_saving += saving["amount"]
        
        # 自动应用满减
        if total_saving > 0:
            self.cart.set_coupon_discount(total_saving)
        
        return savings
    
    def suggest_combo(self):
        """智能推荐搭配"""
        if not self.cart.items:
            return
        
        suggestions = []
        categories_in_cart = set()
        
        for code, item in self.cart.items.items():
            categories_in_cart.add(item["product"]["category"])
        
        # 根据已有商品推荐搭配
        if "零食" in self.cart.items:
            suggestions.append("推荐搭配:可乐(¥3.00)- 零食好搭档!")
        
        if "水果" in categories_in_cart:
            suggestions.append("推荐搭配:酸奶(即将上架)- 水果沙拉必备!")
        
        if "食品" in categories_in_cart:
            suggestions.append("推荐搭配:饮料 - 用餐好伴侣!")
        
        if suggestions:
            print(f"\n💡 为您推荐:")
            for s in suggestions:
                print(f"  {s}")
    
    def checkout_with_points(self):
        """使用积分抵扣"""
        if not self.current_member:
            return False
        
        points = self.current_member["points"]
        if points < 100:
            print(f"💡 当前积分:{points}(满100积分可用)")
            return False
        
        use_points = input(f"当前积分{points},是否使用积分抵扣?(是/否):")
        
        if use_points == "是":
            max_deduct = points // 100 * 5  # 每100积分抵5元
            total = self.cart.get_total()
            deduct = min(max_deduct, total)
            
            self.cart.set_coupon_discount(deduct)
            self.current_member["points"] -= deduct * 20  # 每元消耗20积分
            
            print(f"✅ 使用积分抵扣¥{deduct:.2f}")
            return True
        
        return False
    
    def earn_points(self, amount):
        """赚取积分"""
        if self.current_member:
            earned = int(amount)
            self.current_member["points"] += earned
            print(f"⭐ 获得{earned}积分!当前积分:{self.current_member['points']}")
    
    def process_smart_checkout(self):
        """智能结账流程"""
        print(f"\n{'='*50}")
        print(f"{'🤖 智能结账':^50}")
        print(f"{'='*50}")
        
        # 显示购物车
        self.cart.display_cart()
        
        # 智能推荐
        self.suggest_combo()
        
        # 自动应用促销
        print("\n📢 正在计算优惠...")
        savings = self.auto_apply_promotions()
        
        if savings:
            print("🎉 已为您自动应用以下优惠:")
            for saving in savings:
                print(f"  ✅ {saving['description']}:省¥{saving['amount']:.2f}")
        
        # 会员积分
        if self.current_member:
            self.checkout_with_points()
        
        # 显示最终金额
        self.cart.display_cart()
        
        # 处理付款
        payment_info = self.process_payment()
        
        if payment_info:
            # 赚取积分
            self.earn_points(payment_info["total"])
            
            # 打印小票
            self.print_receipt(payment_info)

# 初始化促销活动
def init_promotions(system):
    """初始化促销活动"""
    system.promotion_system.add_buy_x_get_y_free("003", 2, 1)  # 牛奶买2送1
    system.promotion_system.add_discount_on_category("零食", 20)  # 零食8折
    system.promotion_system.add_full_reduction(50, 10)  # 满50减10
    system.promotion_system.add_full_reduction(100, 25)  # 满100减25

# 运行智能收银系统
smart_register = SmartCashRegister()
init_promotions(smart_register)

print("🏪 欢迎使用智能收银系统 V2.0!")
print("=" * 50)

while True:
    print("\n请选择操作:")
    print("1. 🛒 开始新订单")
    print("2. 👤 会员登录")
    print("3. 🎉 查看促销活动")
    print("4. 📊 查看日报表")
    print("5. 🚪 下班结账")
    
    choice = input("\n请选择(1-5):")
    
    if choice == "5":
        smart_register.show_daily_report()
        print("\n👋 下班了!辛苦了!")
        break
    
    elif choice == "4":
        smart_register.show_daily_report()
    
    elif choice == "3":
        smart_register.promotion_system.show_active_promotions()
    
    elif choice == "2":
        smart_register.member_login()
    
    elif choice == "1":
        print(f"\n{'='*50}")
        print(f"{'🆕 新订单':^50}")
        print(f"{'='*50}")
        
        # 显示商品
        display_products()
        
        # 扫描商品
        smart_register.scan_item()
        
        if smart_register.cart.get_items_count() > 0:
            # 智能结账
            smart_register.process_smart_checkout()
        else:
            print("❌ 购物车为空,取消订单")
    
    else:
        print("❌ 请选择1-5!")

3.2 收银系统管理后台

# 收银系统管理后台
print("\n⚙️ 收银系统管理后台")
print("=" * 50)

class ManagementConsole:
    """管理后台"""
    
    def __init__(self, cash_register):
        self.register = cash_register
        self.admin_password = "admin123"
    
    def admin_login(self):
        """管理员登录"""
        password = input("请输入管理员密码:")
        return password == self.admin_password
    
    def manage_products(self):
        """管理商品"""
        print(f"\n{'='*50}")
        print(f"{'📦 商品管理':^50}")
        print(f"{'='*50}")
        
        while True:
            print("\n请选择操作:")
            print("1. 📋 查看所有商品")
            print("2. ➕ 添加商品")
            print("3. ✏️ 修改商品价格")
            print("4. ❌ 下架商品")
            print("5. 🔙 返回")
            
            choice = input("请选择(1-5):")
            
            if choice == "5":
                break
            
            elif choice == "1":
                display_products()
            
            elif choice == "2":
                code = input("商品编号:")
                name = input("商品名称:")
                price = float(input("单价:"))
                unit = input("单位:")
                category = input("类别:")
                
                products[code] = {
                    "name": name,
                    "price": price,
                    "unit": unit,
                    "category": category
                }
                print(f"✅ 已添加商品:{name}")
            
            elif choice == "3":
                code = input("商品编号:")
                if code in products:
                    new_price = float(input("新价格:"))
                    old_price = products[code]["price"]
                    products[code]["price"] = new_price
                    print(f"✅ {products[code]['name']}:¥{old_price} → ¥{new_price}")
                else:
                    print("❌ 商品不存在!")
            
            elif choice == "4":
                code = input("商品编号:")
                if code in products:
                    confirm = input(f"确认下架 {products[code]['name']}?(是/否):")
                    if confirm == "是":
                        del products[code]
                        print("✅ 已下架")
                else:
                    print("❌ 商品不存在!")
    
    def manage_promotions(self):
        """管理促销活动"""
        print(f"\n{'='*50}")
        print(f"{'🎉 促销管理':^50}")
        print(f"{'='*50}")
        
        while True:
            print("\n请选择操作:")
            print("1. 📋 查看当前活动")
            print("2. ➕ 添加买赠活动")
            print("3. ➕ 添加品类折扣")
            print("4. ➕ 添加满减活动")
            print("5. ❌ 清除所有活动")
            print("6. 🔙 返回")
            
            choice = input("请选择(1-6):")
            
            if choice == "6":
                break
            
            elif choice == "1":
                self.register.promotion_system.show_active_promotions()
            
            elif choice == "2":
                code = input("商品编号:")
                buy = int(input("购买数量:"))
                free = int(input("赠送数量:"))
                self.register.promotion_system.add_buy_x_get_y_free(code, buy, free)
                print("✅ 已添加买赠活动")
            
            elif choice == "3":
                category = input("商品类别:")
                discount = float(input("折扣率(如8折输入20):"))
                min_amount = float(input("最低消费金额(0为不限):"))
                self.register.promotion_system.add_discount_on_category(category, discount, min_amount)
                print("✅ 已添加品类折扣")
            
            elif choice == "4":
                threshold = float(input("满多少元:"))
                reduction = float(input("减多少元:"))
                self.register.promotion_system.add_full_reduction(threshold, reduction)
                print("✅ 已添加满减活动")
            
            elif choice == "5":
                confirm = input("确认清除所有活动?(是/否):")
                if confirm == "是":
                    self.register.promotion_system.active_promotions.clear()
                    print("✅ 已清除所有活动")
    
    def view_transactions(self):
        """查看交易记录"""
        print(f"\n{'='*50}")
        print(f"{'📊 交易记录':^50}")
        print(f"{'='*50}")
        
        if not self.register.transaction_history:
            print("暂无交易记录")
            return
        
        for i, trans in enumerate(self.register.transaction_history, 1):
            print(f"\n交易{i}:")
            print(f"  小票号:{trans['receipt_no']}")
            print(f"  商品数:{len(trans['items'])}种")
            print(f"  小计:¥{trans['subtotal']:.2f}")
            
            if trans['member_discount'] > 0:
                print(f"  会员折扣:{trans['member_discount']}%")
            if trans['coupon_discount'] > 0:
                print(f"  优惠券:-¥{trans['coupon_discount']:.2f}")
            
            print(f"  实收:¥{trans['total']:.2f}")
            print(f"  找零:¥{trans['change']:.2f}")

# 管理后台入口
console = ManagementConsole(smart_register)

print("⚙️ 收银系统管理后台")
print("=" * 50)

if console.admin_login():
    print("✅ 登录成功!")
    
    while True:
        print("\n请选择管理功能:")
        print("1. 📦 商品管理")
        print("2. 🎉 促销管理")
        print("3. 📊 交易记录")
        print("4. 🔙 退出管理")
        
        choice = input("请选择(1-4):")
        
        if choice == "4":
            print("👋 管理后台已退出")
            break
        
        elif choice == "1":
            console.manage_products()
        
        elif choice == "2":
            console.manage_promotions()
        
        elif choice == "3":
            console.view_transactions()
        
        else:
            print("❌ 请选择1-4!")
else:
    print("❌ 密码错误!")

📅 第三阶段总结

🎯 本阶段学习成果

第21-30课:逻辑思维培养

| 课程 | 知识点 | 项目实践 |

|------|--------|---------|

| 第21课 | 单分支if语句 | 条件判断入门 |

| 第22课 | if-else语句 | 二选一决策 |

| 第23课 | if-elif-else多分支 | 多选一迷宫 |

| 第24课 | 条件嵌套 | 俄罗斯套娃逻辑 |

| 第25课 | 综合应用 | 成绩评定系统 |

| 第26课 | 错误处理 | 计算器升级版 |

| 第27课 | 多条件判断 | 年龄判断机 |

| 第28课 | 复合条件 | 闰年判断器 |

| 第29课 | 综合项目 | 猜拳游戏 |

| 第30课 | 终极项目 | 智能收银系统 |

🏆 核心能力提升

  1. 逻辑思维:掌握了条件判断的完整体系
  2. 问题分解:学会将复杂问题拆解为简单条件
  3. 系统设计:能够设计完整的应用程序
  4. 用户体验:注重交互设计和错误处理
  5. 工程实践:养成了良好的编程习惯

🚀 下一阶段展望

第四阶段:循环与数据结构

  • 学习for循环和while循环
  • 掌握列表、字典等数据结构
  • 制作批量数据处理程序
  • 开发更复杂的应用系统

💬 给家长的话

亲爱的家长

恭喜!孩子完成了第三阶段的学习,并成功制作了智能收银系统这个综合性项目!

孩子在本阶段学会了

  1. ✅ 完整的条件判断体系
  2. ✅ 多分支和嵌套逻辑
  3. ✅ 错误处理和异常捕获
  4. ✅ 系统化程序设计
  5. ✅ 综合项目管理能力

智能收银系统的教育价值

| 能力 | 项目应用 | 现实意义 |

|------|---------|---------|

| 逻辑思维 | 折扣计算逻辑 | 分析决策 |

| 数学应用 | 金额计算找零 | 实用数学 |

| 系统设计 | 完整收银流程 | 工程思维 |

| 用户体验 | 友好的交互 | 产品思维 |

| 商业意识 | 促销活动设计 | 商业思维 |

您可以这样做

  1. 角色扮演:和孩子玩超市收银游戏
  2. 实际应用:用程序管理家庭开支
  3. 创意扩展:一起设计新功能
  4. 职业启蒙:了解收银系统的工作原理

温馨提示

  • 第三阶段是编程思维的重要转折点
  • 条件判断是编程的核心能力
  • 鼓励孩子用编程解决实际问题
  • 为下一阶段学习做好准备

🏆 第三阶段成就

完成了第三阶段的学习,你:

🧠 培养了逻辑思维

🔧 掌握了条件判断

🏪 制作了收银系统

🎮 开发了猜拳游戏

📊 完成了数据分析

挑战任务

  1. 为收银系统添加更多支付方式
  2. 制作库存管理功能
  3. 添加数据可视化图表
  4. 实现多门店管理

🌟 编程心法

⬅️ 上一课下一课 ➡️