|
|
|
|
@ -0,0 +1,240 @@
|
|
|
|
|
import os
|
|
|
|
|
import json
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
# ==========================================
|
|
|
|
|
# 全局配置与文件路径
|
|
|
|
|
# ==========================================
|
|
|
|
|
PRODUCTS_FILE = "products.json" # 商品数据文件
|
|
|
|
|
SALES_FILE = "sales.log" # 销售记录日志
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ==========================================
|
|
|
|
|
# 核心功能函数
|
|
|
|
|
# ==========================================
|
|
|
|
|
|
|
|
|
|
def load_products():
|
|
|
|
|
"""
|
|
|
|
|
从文件加载商品数据。
|
|
|
|
|
如果文件不存在,则初始化一个默认商品列表。
|
|
|
|
|
"""
|
|
|
|
|
if os.path.exists(PRODUCTS_FILE):
|
|
|
|
|
with open(PRODUCTS_FILE, 'r', encoding='utf-8') as f:
|
|
|
|
|
return json.load(f)
|
|
|
|
|
else:
|
|
|
|
|
# 初始化一些默认商品 (商品ID: {信息})
|
|
|
|
|
default_products = {
|
|
|
|
|
"001": {"name": "Python编程书", "price": 59.9, "stock": 100},
|
|
|
|
|
"002": {"name": "无线鼠标", "price": 89.5, "stock": 50},
|
|
|
|
|
"003": {"name": "机械键盘", "price": 299.0, "stock": 30},
|
|
|
|
|
}
|
|
|
|
|
save_products(default_products)
|
|
|
|
|
return default_products
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_products(products):
|
|
|
|
|
"""
|
|
|
|
|
将商品数据保存到文件。
|
|
|
|
|
"""
|
|
|
|
|
with open(PRODUCTS_FILE, 'w', encoding='utf-8') as f:
|
|
|
|
|
json.dump(products, f, ensure_ascii=False, indent=4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_sales():
|
|
|
|
|
"""
|
|
|
|
|
读取销售记录(简单文本日志)。
|
|
|
|
|
"""
|
|
|
|
|
if os.path.exists(SALES_FILE):
|
|
|
|
|
with open(SALES_FILE, 'r', encoding='utf-8') as f:
|
|
|
|
|
return f.read()
|
|
|
|
|
return "暂无销售记录。"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def record_sale(record_text):
|
|
|
|
|
"""
|
|
|
|
|
记录销售流水到日志文件。
|
|
|
|
|
"""
|
|
|
|
|
with open(SALES_FILE, 'a', encoding='utf-8') as f:
|
|
|
|
|
f.write(f"[{datetime.now()}] {record_text}\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def display_menu():
|
|
|
|
|
"""
|
|
|
|
|
显示主菜单界面。
|
|
|
|
|
"""
|
|
|
|
|
print("\n" + "=" * 40)
|
|
|
|
|
print("欢迎使用简易商城管理系统")
|
|
|
|
|
print("=" * 40)
|
|
|
|
|
print("1. 浏览所有商品")
|
|
|
|
|
print("2. 添加商品到购物车")
|
|
|
|
|
print("3. 结算与购买")
|
|
|
|
|
print("4. 管理员:添加新商品")
|
|
|
|
|
print("5. 查看销售记录")
|
|
|
|
|
print("0. 退出系统")
|
|
|
|
|
print("-" * 40)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def show_products(products):
|
|
|
|
|
"""
|
|
|
|
|
格式化显示所有商品。
|
|
|
|
|
"""
|
|
|
|
|
print("\n当前商品列表:")
|
|
|
|
|
print(f"{'商品ID':<10}{'名称':<15}{'价格(元)':<10}{'库存'}")
|
|
|
|
|
print("-" * 40)
|
|
|
|
|
for pid, info in products.items():
|
|
|
|
|
print(f"{pid:<10}{info['name']:<15}{info['price']:<10}{info['stock']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def add_to_cart(products, cart):
|
|
|
|
|
"""
|
|
|
|
|
将商品加入购物车的逻辑。
|
|
|
|
|
cart 是一个列表,元素为字典 {product_id, quantity, product_info}
|
|
|
|
|
"""
|
|
|
|
|
pid = input("请输入要购买的商品ID: ").strip()
|
|
|
|
|
if pid in products:
|
|
|
|
|
try:
|
|
|
|
|
qty = int(input(f"请输入购买数量 (库存: {products[pid]['stock']}): "))
|
|
|
|
|
if qty <= 0:
|
|
|
|
|
print("数量必须大于0。")
|
|
|
|
|
return
|
|
|
|
|
if qty > products[pid]['stock']:
|
|
|
|
|
print(f"库存不足!当前库存为 {products[pid]['stock']}。")
|
|
|
|
|
else:
|
|
|
|
|
# 检查购物车是否已有该商品,如果有则叠加数量
|
|
|
|
|
for item in cart:
|
|
|
|
|
if item['id'] == pid:
|
|
|
|
|
item['quantity'] += qty
|
|
|
|
|
print(f"已更新购物车:{item['name']} 数量变为 {item['quantity']}")
|
|
|
|
|
return
|
|
|
|
|
# 如果购物车没有,则新增
|
|
|
|
|
cart.append({
|
|
|
|
|
'id': pid,
|
|
|
|
|
'name': products[pid]['name'],
|
|
|
|
|
'price': products[pid]['price'],
|
|
|
|
|
'quantity': qty
|
|
|
|
|
})
|
|
|
|
|
print(f"已成功添加 {qty} 个 [{products[pid]['name']}] 到购物车。")
|
|
|
|
|
except ValueError:
|
|
|
|
|
print("输入错误,请输入数字。")
|
|
|
|
|
else:
|
|
|
|
|
print("商品ID不存在,请重新输入。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def checkout(products, cart):
|
|
|
|
|
"""
|
|
|
|
|
结算功能。
|
|
|
|
|
1. 计算总价
|
|
|
|
|
2. 扣除库存
|
|
|
|
|
3. 保存数据
|
|
|
|
|
4. 清空购物车
|
|
|
|
|
"""
|
|
|
|
|
if not cart:
|
|
|
|
|
print("购物车为空,请先添加商品!")
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
print("\n" + "-" * 40)
|
|
|
|
|
print("收银台")
|
|
|
|
|
print("-" * 40)
|
|
|
|
|
total = 0.0
|
|
|
|
|
for item in cart:
|
|
|
|
|
subtotal = item['price'] * item['quantity']
|
|
|
|
|
total += subtotal
|
|
|
|
|
print(f"{item['name']} x{item['quantity']} = ¥{subtotal:.2f}")
|
|
|
|
|
|
|
|
|
|
print(f"\n总计:¥{total:.2f}")
|
|
|
|
|
|
|
|
|
|
confirm = input("\n确认购买吗?(y/n): ").lower()
|
|
|
|
|
if confirm == 'y':
|
|
|
|
|
# 更新库存并生成销售记录
|
|
|
|
|
sale_details = []
|
|
|
|
|
for item in cart:
|
|
|
|
|
products[item['id']]['stock'] -= item['quantity']
|
|
|
|
|
sale_details.append(f"{item['name']}x{item['quantity']}")
|
|
|
|
|
|
|
|
|
|
# 保存更新后的商品数据
|
|
|
|
|
save_products(products)
|
|
|
|
|
# 记录销售日志
|
|
|
|
|
record_sale(f"购买: {', '.join(sale_details)} | 总金额: ¥{total:.2f}")
|
|
|
|
|
print(f"\n购买成功!感谢惠顾。")
|
|
|
|
|
|
|
|
|
|
# 清空购物车
|
|
|
|
|
cart.clear()
|
|
|
|
|
else:
|
|
|
|
|
print("取消结算。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def admin_add_product(products):
|
|
|
|
|
"""
|
|
|
|
|
管理员功能:添加新商品。
|
|
|
|
|
"""
|
|
|
|
|
print("\n[管理员模式] 添加新商品")
|
|
|
|
|
pid = input("请输入新商品ID: ").strip()
|
|
|
|
|
if pid in products:
|
|
|
|
|
print("该ID已存在,请使用其他ID。")
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
name = input("请输入商品名称: ").strip()
|
|
|
|
|
try:
|
|
|
|
|
price = float(input("请输入商品价格: "))
|
|
|
|
|
stock = int(input("请输入初始库存: "))
|
|
|
|
|
if price <= 0 or stock < 0:
|
|
|
|
|
print("价格需大于0,库存不能为负。")
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
products[pid] = {
|
|
|
|
|
"name": name,
|
|
|
|
|
"price": price,
|
|
|
|
|
"stock": stock
|
|
|
|
|
}
|
|
|
|
|
save_products(products)
|
|
|
|
|
print(f"商品 [{name}] 添加成功!")
|
|
|
|
|
except ValueError:
|
|
|
|
|
print("输入格式错误,请输入正确的数字。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ==========================================
|
|
|
|
|
# 主程序入口
|
|
|
|
|
# ==========================================
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
"""
|
|
|
|
|
主函数,程序的入口点。
|
|
|
|
|
负责加载数据、显示菜单和处理用户输入。
|
|
|
|
|
"""
|
|
|
|
|
# 加载数据
|
|
|
|
|
products = load_products()
|
|
|
|
|
cart = [] # 临时购物车,程序关闭后清空
|
|
|
|
|
|
|
|
|
|
print("系统启动成功!")
|
|
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
display_menu()
|
|
|
|
|
choice = input("请选择功能 (0-5): ").strip()
|
|
|
|
|
|
|
|
|
|
if choice == '1':
|
|
|
|
|
show_products(products)
|
|
|
|
|
elif choice == '2':
|
|
|
|
|
show_products(products)
|
|
|
|
|
add_to_cart(products, cart)
|
|
|
|
|
elif choice == '3':
|
|
|
|
|
checkout(products, cart)
|
|
|
|
|
elif choice == '4':
|
|
|
|
|
# 简单的密码验证(可选,增加趣味性)
|
|
|
|
|
pwd = input("请输入管理员密码 (默认123): ")
|
|
|
|
|
if pwd == "123":
|
|
|
|
|
admin_add_product(products)
|
|
|
|
|
else:
|
|
|
|
|
print("密码错误!")
|
|
|
|
|
elif choice == '5':
|
|
|
|
|
print("\n销售记录:")
|
|
|
|
|
print(load_sales())
|
|
|
|
|
elif choice == '0':
|
|
|
|
|
print("感谢使用,再见!")
|
|
|
|
|
break
|
|
|
|
|
else:
|
|
|
|
|
print("无效选择,请重新输入。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 程序启动
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|