模拟实现ATM+购物商城程序

2018-04-28 09:52:10 浏览数 (1)

流程图:

需求:

ATM:模拟实现一个ATM 购物商城程序 额度 15000或自定义 实现购物商城,买东西加入 购物车,调用信用卡接口结账 可以提现,手续费5% 支持多账户登录 支持账户间转账 记录每月日常消费流水 提供还款接口 ATM记录操作日志 提供管理接口,包括添加账户、用户额度,冻结账户等。。。 用户认证用装饰器 程序目录结构

代码语言:javascript复制
../module2-ATM
├── ATM流程图.png   #流畅图
├── bin       #atm执行程序目录
│   ├── ATM_start.py
│   └── __init__.py
├── db            #数据库目录
│   ├── __init__.py
│   ├── shopping_car    #购物车文件
│   ├── shopping_data   #信用卡信息文件
│   └── user_data       #管理后台用户密码
├── __init__.py
├── log                #日志目录
│   ├── __init__.py
│   └── record.log
├── main             #主要目录,相关模块功能都在这里
│   ├── admin.py   #管理后台模块
│   ├── core.py        #调用各个模块的主模块
│   ├── credictcard.py  #信用卡模块
│   ├── __init__.py
│   ├── log.py           #日志模块
│   └── shopping_mall.py  #商城模块
└── README

 bin目录

atm_start.py执行程序

代码语言:javascript复制
#coding:utf-8
#Author:支文伟
'''执行ATM程序'''
import os,sys
core_path  = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   '/main'
sys.path.append(core_path)  #把该路径加到环境变量
from core import *
if __name__ == '__main__':
    core()

db目录

代码语言:javascript复制
{"66661111": {"locked": "False", "password": 666666, "totalbill": 998, "credictcard": 66661111, "deflimit": 15000, "personinfo": "zhiww", "limitcash": 6502, "limit": 14002}, "66668888": {"credictcard": 66668888, "password": 123456, "totalbill": 0, "locked": "False", "deflimit": 15000, "personinfo": "alex", "limitcash": 7500, "limit": 15000}}
代码语言:javascript复制
[["shoes", "998"]]
代码语言:javascript复制
oppoR9s 2500
ipad 5000
book 350
bike 1999
clothes 1600
shoes 998
代码语言:javascript复制
{"admin": "123"}

log目录

代码语言:javascript复制
2017-09-02 22:17:56,156 --- 购物---oppoR9s---价格---2500
2017-09-02 22:17:59,843 --- 购物---ipad---价格---5000
2017-09-02 22:19:27,083 --- 购物---oppoR9s---价格---2500
2017-09-02 22:19:27,667 --- 购物---ipad---价格---5000
2017-09-02 22:20:41,450 --- 购物---oppoR9s---价格---2500
2017-09-02 22:20:42,227 --- 购物---ipad---价格---5000
2017-09-02 22:21:03,874 --- 购物---oppoR9s---价格---2500
2017-09-02 22:21:04,307 --- 购物---ipad---价格---5000
2017-09-02 22:21:15,297 --- 购物---oppoR9s---价格---2500
2017-09-02 22:21:15,707 --- 购物---ipad---价格---5000
2017-09-02 22:21:43,529 --- 购物---oppoR9s---价格---2500
2017-09-02 22:21:43,778 --- 购物---ipad---价格---5000
2017-09-02 22:21:44,138 --- 购物---oppoR9s---价格---2500
2017-09-02 22:23:12,962 --- 购物---oppoR9s---价格---2500
2017-09-02 22:23:40,754 --- 购物---oppoR9s---价格---2500
2017-09-02 22:24:31,233 --- 购物---oppoR9s---价格---2500
2017-09-02 22:24:52,283 --- 购物---oppoR9s---价格---2500
2017-09-02 22:36:49,801 --- 购物---oppoR9s---价格---2500
2017-09-02 22:36:50,240 --- 购物---ipad---价格---5000
2017-09-02 22:37:14,768 --- 购物---oppoR9s---价格---2500
2017-09-02 22:37:15,385 --- 购物---ipad---价格---5000
2017-09-02 22:38:20,097 --- 购物---oppoR9s---价格---2500
2017-09-02 22:38:20,586 --- 购物---ipad---价格---5000
2017-09-02 22:39:09,520 --- 购物---oppoR9s---价格---2500
2017-09-02 22:39:09,841 --- 购物---ipad---价格---5000
2017-09-02 22:39:10,584 --- 购物---oppoR9s---价格---2500
2017-09-02 22:39:45,185 --- 购物---oppoR9s---价格---2500
2017-09-02 22:39:46,233 --- 购物---ipad---价格---5000
2017-09-02 22:39:59,344 --- 购物---bike---价格---1999
2017-09-02 22:40:16,728 --- 购物---oppoR9s---价格---2500
2017-09-02 22:41:28,536 --- 购物---oppoR9s---价格---2500
2017-09-02 22:44:09,529 --- 购物---oppoR9s---价格---2500
2017-09-02 22:44:10,210 --- 购物---ipad---价格---5000
2017-09-02 22:45:01,121 --- 购物---oppoR9s---价格---2500
2017-09-02 22:45:41,448 --- 购物---oppoR9s---价格---2500
2017-09-02 22:50:57,263 --- 购物---oppoR9s---价格---2500
2017-09-02 22:51:27,760 --- 购物---oppoR9s---价格---2500
2017-09-02 22:54:17,922 --- 购物---oppoR9s---价格---2500
2017-09-02 22:54:54,464 --- 购物---oppoR9s---价格---2500
2017-09-02 22:54:55,879 --- 购物---ipad---价格---5000
2017-09-02 22:54:57,209 --- 购物---book---价格---350
2017-09-02 22:55:36,530 --- 购物---shoes---价格---998
2017-09-02 22:55:37,552 --- 购物---book---价格---350
2017-09-02 22:55:38,208 --- 购物---bike---价格---1999
2017-09-02 22:55:38,680 --- 购物---oppoR9s---价格---2500
2017-09-06 14:37:00,639 --- 购物---oppoR9s---价格---2500
2017-09-06 14:37:01,162 --- 购物---book---价格---350
2017-09-06 14:37:01,570 --- 购物---clothes---价格---1600
2017-09-07 10:16:24,277 --- 12345678--信用卡商城结账--4450
2017-09-07 10:18:59,989 --- 12345678--信用卡商城结账--4450¥
2017-09-10 15:00:49,031 --- 购物---oppoR9s---价格---2500
2017-09-10 15:00:49,031 --- 购物---oppoR9s---价格---2500
2017-09-10 15:00:50,222 --- 购物---ipad---价格---5000
2017-09-10 15:00:50,222 --- 购物---ipad---价格---5000
2017-09-10 15:04:51,710 --- 购物---ipad---价格---5000
2017-09-10 15:04:51,710 --- 购物---ipad---价格---5000
2017-09-10 15:04:53,343 --- 购物---oppoR9s---价格---2500
2017-09-10 15:04:53,343 --- 购物---oppoR9s---价格---2500
2017-09-10 15:05:53,751 --- 购物---ipad---价格---5000
2017-09-10 15:05:53,751 --- 购物---ipad---价格---5000
2017-09-10 15:05:54,527 --- 购物---book---价格---350
2017-09-10 15:05:54,527 --- 购物---book---价格---350
2017-09-10 15:06:27,303 --- 购物---book---价格---350
2017-09-10 15:06:27,303 --- 购物---book---价格---350
2017-09-11 10:16:57,211 --- 购物---oppoR9s---价格---2500
2017-09-11 10:16:57,211 --- 购物---oppoR9s---价格---2500
2017-09-11 10:16:57,930 --- 购物---ipad---价格---5000
2017-09-11 10:16:57,930 --- 购物---ipad---价格---5000
2017-09-11 10:17:28,513 --- 购物---oppoR9s---价格---2500
2017-09-11 10:17:28,513 --- 购物---oppoR9s---价格---2500
2017-09-11 10:17:32,387 --- 购物---oppoR9s---价格---2500
2017-09-11 10:17:32,387 --- 购物---oppoR9s---价格---2500
2017-09-11 10:17:34,916 --- 购物---book---价格---350
2017-09-11 10:17:34,916 --- 购物---book---价格---350
2017-09-11 10:44:51,037 --- 购物---oppoR9s---价格---2500
2017-09-11 10:44:51,037 --- 购物---oppoR9s---价格---2500
2017-09-11 10:44:52,299 --- 购物---ipad---价格---5000
2017-09-11 10:44:52,299 --- 购物---ipad---价格---5000
2017-09-11 11:55:00,038 --- 购物---shoes---价格---998
2017-09-11 11:55:00,038 --- 购物---shoes---价格---998
2017-09-11 11:55:30,671 --- 66661111--信用卡商城结账--998¥
2017-09-11 11:55:30,671 --- 66661111--信用卡商城结账--998¥

main目录

代码语言:javascript复制
#coding:utf-8
#Author:zhiwenwei
import os,json
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
'''数据库文件的绝对路径'''
creditcard_data = base_dir   '/db/creditcard_data'
user_dir = base_dir   '/db/user_data'

'''管理员用户认证装饰器'''
def auth_admin(func):
    def wrapper(*args,**kwargs):
        while True:
            check = input("是否确认认证用户?y确认q退出认证")
            if check == "y":
                print("管理员用户认证".center(60,'-'))
                username = input("请输入管理员账户:").strip()
                passwd = input("请输入管理员密码:").strip()
                with open(user_dir, 'r', encoding='utf-8') as f:
                    _user_data = json.loads(f.read())
                    if username in _user_data.keys() and int(passwd) == int(_user_data[username]):
                        print("用户%s认证成功"%(username))
                    else:
                        print("用户名或密码有误")
                        continue
            else:
                print("已退出管理用户认证")
                break
            func(*args,**kwargs)
    return wrapper

'''申请信用卡'''
@auth_admin
def apply():
    while True:
        print("申请信用卡".center(40,'-'))
        with open(creditcard_data,'r ',encoding='utf-8') as f:
            _credictcard_data = json.loads(f.read())
            credictcard_id = input("请输入你要申请的信用卡号(八位数字):")
            if credictcard_id.isdigit() and len(credictcard_id) == 8:
                if credictcard_id not in _credictcard_data.keys():
                    apply_user = input("请输入信用卡申请人:").strip()
                    apply_passwd = input("请输入信用卡密码(六位数):").strip()
                    if len(apply_user) > 0:
                        if apply_passwd.isdigit() and len(apply_passwd) == 6:
                            _credictcard_data[credictcard_id] = {"limitcash": 7500, "password":int(apply_passwd), "personinfo": apply_user,"locked": "False",
                                                                 "deflimit": 15000, "credictcard": int(credictcard_id), "limit": 15000, "totalbill": 0}
                            dict = json.dumps(_credictcard_data)
                            f.seek(0)
                            f.truncate(0)
                            f.write(dict)
                            f.flush()
                            print("申请信用卡成功!n卡号:%st持卡人:%sn额度:15000t取现额度:7500"%(credictcard_id,apply_user))
                            break
                        else:
                            print("输入密码有误!")
                            continue
                    else:
                        print("申请人不能为空")
                else:
                    print("改信用卡已存在")
                    continue
            else:
                print("输入信用卡有误!")
'''修改信用卡密码'''
@auth_admin
def alter_pw():
    while True:
        print("修改信用卡密码".center(40,'-'))
        with open(creditcard_data,'r ',encoding='-utf8') as f:
            _creditcard_data = json.loads(f.read())
            creditcard_id = input("请输入你要修改的信用卡:").strip()
            if creditcard_id.isdigit() and len(creditcard_id) ==8:
                if creditcard_id in _creditcard_data.keys():
                    passwd = _creditcard_data[creditcard_id]["password"]
                    _passwd = input("请输入信用卡原密码:").strip()
                    if int(_passwd) == passwd:
                        passwd_new = input("请输入你要设置的信用卡密码:").strip()
                        _creditcard_data[creditcard_id]["password"] = int(passwd_new)
                        dict = json.dumps(_creditcard_data)
                        f.seek(0)
                        f.truncate(0)
                        f.write(dict)
                        f.flush()
                        print("密码修改成功!")
                        break
                    else:
                        print("你输入的原密码有误!")
                else:
                    print("你输入的信用卡不存在")
            else:
                print("你输入的信用卡有误")
'''添加管理员账户'''
@auth_admin
def alter_admin():
    while True:
        print("添加管理员账户".center(50,'-'))
        username = input("请设置管理员账户名:").strip()
        passwd = input("请设置账户密码:").strip()
        with open(user_dir,'r ',encoding='utf-8') as f:
            user_data = json.loads(f.read())
            if username not in user_data.keys():
                if len(username) >= 0 and len(passwd) >= 0:
                    user_data[username] = passwd
                    user_data = json.dumps(user_data)
                    f.seek(0)
                    f.truncate(0)
                    f.write(user_data)
                    f.flush()
                    print("成功添加[%s]管理员"%(username))
                    break
                else:
                    print("账户或密码不能为空")
            else:
                print("该管理账户名[%s]已存在!请换一个用户名!"%(username))
                continue
代码语言:javascript复制
#coding:utf-8
#Author:zhiwenwei
import os,sys
# base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# core_path = base_dir   'main'
# sys.path.insert(0,core_path)
from admin import *
from credictcard import *
from shopping_mall import *
'''主页面列表'''
def core_list():
    list = ["  ATM  ",
            "购物商城",
            "后台管理",
            "退出程序"]
    index = 0
    for i in list:
        print(index 1,i)
        index  =1

'''ATM页面列表'''
def atm_list():
    list = ["信用卡信息",
            "信用卡转账",
            "信用卡取现",
            "信用卡还款",
            ]
    index = 0
    for i in list:
        print(index 1,i)
        index  = 1
'''后台管理列表'''
def admin_list():
    list = [" 申请信用卡 ",
            "添加管理员账户",
            "修改信用卡密码"
            ]
    index = 0
    for i in list:
        print(index  1,i)
        index  = 1
'''购物商城列表'''
def shopping_list():
    list = ["购物商城",
            "购物结算",
            "清空购物车",
            "查看购物车"
            ]
    index = 0
    for i in list:
        print(index 1,i)
        index  = 1

'''主函数'''
def core():
    print("欢迎来到购物商城ATM系统".center(30,'-'))
    while True:
        core_list()
        choice = input("请选择ID:").strip()
        if choice == "q":
            print("已退出,欢迎下次使用!".center(40,'-'))
            exit()
        if choice.isdigit():
            choice = int(choice)
            if  1 <= choice <= 4:
                while True:
                    if choice == 1:
                        print("欢迎来到信用中心".center(40,'-'))
                        atm_list()
                        atm_choice = input("请选择ATM操作id:").strip()
                        if atm_choice == "q":break
                        if atm_choice == "exit":exit("已退出程序,欢迎下次使用!")
                        if atm_choice.isdigit():
                            atm_choice = int(atm_choice)
                            if 1 <= atm_choice <= 4:
                                while True:
                                    if atm_choice == 1:
                                        creditcard_info()
                                        break
                                    elif atm_choice == 2:
                                        transfer()
                                        break
                                    elif atm_choice == 3:
                                        takecash()
                                        break
                                    elif atm_choice == 4:
                                        repayment()
                                        break
                            else:
                                print("请输入正确的id")
                    elif choice ==2:
                        print("欢迎来到购物商城".center(40,'-'))
                        shopping_list()
                        shop_choice = input("请选择id:").strip()
                        if shop_choice == "q":break
                        if shop_choice == "exit":exit("已退出程序,欢迎下次使用!")
                        if shop_choice.isdigit():
                            shop_choice = int(shop_choice)
                            if 1 <= shop_choice <= 4:
                                while True:
                                    if shop_choice == 1:
                                        mall()
                                        break
                                    elif shop_choice == 2:
                                        shopping_pay()
                                        break
                                    elif shop_choice == 3:
                                        del_shoppingcar()
                                        break
                                    elif shop_choice == 4:
                                        search_shopppingcar()
                                        break
                            else:
                                print("请输入正确的id")
                        else:
                            print("请输入正确的id")
                    elif choice == 3:
                        print("欢迎来到管理后台中心".center(50,'-'))
                        admin_list()
                        admin_choice = input("请选择id(q返回exit退出)").strip()
                        if admin_choice == "q":break
                        if admin_choice == "exit":exit("已退出程序,欢迎下次使用!")
                        if admin_choice.isdigit():
                            admin_choice = int(admin_choice)
                            if 1 <= admin_choice <= 3:
                                while True:
                                    if admin_choice == 1:
                                        apply()
                                        break
                                    elif admin_choice == 2:
                                        alter_admin()
                                        break
                                    elif admin_choice == 3:
                                        alter_pw()
                                        break
                            else:
                                print("请输入正确的id")
                    elif choice == 4:
                        exit("已退出程序,欢迎下次使用!")
            else:
                print("请输入正确的id")
        else:
            print("你输入有误!")
代码语言:javascript复制
#coding:utf-8
#Author:支文伟
"""信用卡中心"""
import os
import json
import sys
from log import get_logger #导入日志模块

'''获取数据文件的绝对路径'''
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #获取当前目录的上级目录绝对路径
creditcard_path = base_dir   '/db/creditcard_data'
user_path = base_dir   '/db/user_data'
recordlog_path = base_dir   '/log/record.log'
logger = get_logger() #日志实例化对象

'''个人信用卡信息'''
def creditcard_info():
    while True:
        with open(creditcard_path,'r',encoding='utf8') as f:
            creditcard_data = json.loads(f.read())
            choice = input("请输入你要查询的信用卡卡号(8位数字)(退出输入q):").strip()
            if choice in creditcard_data.keys():
                print("我的信用卡信息:".center(50,'-'))
                print("持卡人:[ %s ]n卡号:[ %s ]n额度:[ %s ]n可用额度:[ %s ]n提现额度:[ %s ]"
                      % (creditcard_data[choice]["personinfo"],choice,creditcard_data[choice]["deflimit"],
                         creditcard_data[choice]["limit"],creditcard_data[choice]["limitcash"]))
            elif choice == "q":
                break
            else:
                print("你输入的信用卡不存在!")
'''信用卡转账'''
def transfer():
    while  True:
        print("信用卡转账".center(50, '-'))
        with open(creditcard_path,'r ',encoding='utf8') as f:
            creditcard_data = json.loads(f.read())
            choice = input("请输入你的信用卡账号('q'返回):").strip()
            if choice == 'q':
                break
            if choice in creditcard_data.keys():
                now_limit = creditcard_data[choice]["limit"]
                transfer_card = input("请输入你要转账的账户:").strip()
                if transfer_card.isdigit() and transfer_card in creditcard_data.keys() and len(transfer_card) == 8:
                    transfer_money = input("请输入转账金额:").strip()
                    if transfer_money.isdigit():
                        transfer_money = int(transfer_money)
                        creditcard_passwd = input("请输入信用卡密码:").strip()
                        creditcard_passwd = int(creditcard_passwd)
                        if creditcard_passwd == creditcard_data[choice]["password"]:
                            if transfer_money <= int(now_limit):
                                creditcard_data[choice]["limit"] -= transfer_money
                                creditcard_data[choice]["limitcash"] -= transfer_money
                                creditcard_data[transfer_card]["limit"]  = transfer_money
                                creditcard_data[transfer_card]["limitcash"]  = transfer_money
                                print("转账成功".center(50,'-'))
                                print("转账金额:[ %s ]n信用卡可用额度:[ %s ]" % (transfer_money,creditcard_data[choice]["limit"]))
                                '''转账信息记录到日志'''
                                transfer_info = ["信用卡转账",str(choice),str(transfer_money)]
                                transfer_info = '---'.join(transfer_info)
                                logger.debug(transfer_info)
                                f.seek(0)
                                #f.truncate(0)
                                creditcard_data_dumps = json.dumps(creditcard_data)
                                f.write(creditcard_data_dumps)
                            else:
                                print("转账额度不能大于信用额度")
                        else:
                            print("输入密码有误")
                    else:
                        print("请输入数字格式的金额!")
                else:
                    print("你输入的账户不存在")
            else:
                print("你输入的信用卡账号不存在!")
'''信用卡取现'''
def takecash():
    while True:
        print("信用卡取现".center(50,'-'))
        with open(creditcard_path,'r ',encoding='utf-8') as f:
            creditcard_data = json.loads(f.read())
            creditcard = input("请输入你的信用卡账号(q返回):").strip()
            if creditcard == 'q':break
            if creditcard in creditcard_data.keys():
                limit = creditcard_data[creditcard]["limit"]
                limitcash = creditcard_data[creditcard]["limitcash"]
                totalbill = creditcard_data[creditcard]["totalbill"]
                print("信用卡额度:[ %d ]n信用卡账单:[ %d ]n单信用卡可取现额度:[ %d ]" %(limit,totalbill,limitcash,))
                cash = input("请输入你要取现的额度,手续费%5:").strip()
                if cash.isdigit() and 0 < int(cash) <= limitcash:
                    passwd = input("请输入信用卡:%s的密码:" %(creditcard)).strip()
                    if int(passwd) == creditcard_data[creditcard]["password"]:
                        cash = int(cash)
                        fee = cash * 0.05  # 手续费
                        total_cash = cash   fee
                        totalbill  = cash
                        creditcard_data[creditcard]["limitcash"] -= total_cash
                        creditcard_data[creditcard]["limit"] -= total_cash
                        creditcard_data[creditcard]["totalbill"] = totalbill
                        print("成功取现:[%d]n收取手续费:[%d]" %(cash,fee))
                        '''取现信息记录到日志'''
                        takecash_info = ["信用卡取现",creditcard,str(cash)]
                        takecash_info = '---'.join(takecash_info)
                        logger.debug(takecash_info)
                        '''永久保存数据库'''
                        f.seek(0)
                        creditcard_data = json.dumps(creditcard_data)
                        f.write(creditcard_data)
                        f.flush()
                    else:
                        print("信用卡密码有误!")
                else:
                    print("你输入额度含有非数字或超过可取现额度")
            else:
                print("你输入的信用卡账号不存在")
'''信用卡还款'''
def repayment():
    while True:
        print("信用卡还款".center(50,'-'))
        creditcard = input("请输入信用卡账号:").strip()
        with open(creditcard_path,'r ',encoding='utf8') as f:
            creditcard_data = json.loads(f.read())
            print(creditcard_data)
            if creditcard in creditcard_data.keys():
                totalbill = creditcard_data[creditcard]["totalbill"]
                print("你的信用卡[%s]总账单:[%d]"%(creditcard,totalbill))
                repayments = input("请输入你要还款的额度:").strip()
                if repayments.isdigit() and 0 < int(repayments) <= totalbill:
                    passwd = input("请输入信用卡:[%s]的密码:"%(creditcard)).strip()
                    if int(passwd) == creditcard_data[creditcard]["password"]:
                        repayments = int(repayments)
                        creditcard_data[creditcard]["totalbill"] -= repayments
                        creditcard_data[creditcard]["limit"]  = repayments
                        creditcard_data[creditcard]["limitcash"]  = repayments
                        totalbill -= repayments
                        '''记录还款信息到日志'''
                        repayment_info = ["信用卡还款",creditcard,str(repayments)]
                        repayment_info = '---'.join(repayment_info)
                        logger.debug(repayment_info)
                        '''写到文件'''
                        f.seek(0)
                        creditcard_data = json.dumps(creditcard_data)
                        f.write(creditcard_data)
                        f.flush()
                        print("成功还款:[%d]n剩下总账单:[%d]"%(repayments,totalbill))
                    else:
                        print("你输入的密码有误")
                else:
                    print("你输入的额度非数字或超过还款额度!")
            else:
                print("你输入的信用卡账号不存在!")
代码语言:javascript复制
#coding:utf-8
#Author:Mr Zhi
import logging,os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #获取上级目录的绝对路径
log_dir = BASE_DIR   '/log/record.log'
def get_logger():
    fh = logging.FileHandler(log_dir,encoding='utf-8') #创建一个文件流并设置编码utf8
    logger = logging.getLogger() #获得一个logger对象,默认是root
    logger.setLevel(logging.DEBUG)  #设置最低等级debug
    fm = logging.Formatter("%(asctime)s --- %(message)s")  #设置日志格式
    logger.addHandler(fh) #把文件流添加进来,流向写入到文件
    fh.setFormatter(fm) #把文件流添加写入格式
    return logger
代码语言:javascript复制
#coding:utf-8
#Author:支文伟
import os,json
from log import get_logger
logger = get_logger() #日志模块实例化对象
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
'''数据库文件的绝对路径'''
shopping_data = base_dir   '/db/shopping_data'
shopping_car = base_dir   '/db/shopping_car'
creditcard_data = base_dir   '/db/creditcard_data'

'''购物商城'''
def mall():
    product_list = []
    product_list2 = []
    with open(shopping_data,'r',encoding='utf8') as f:
        for i in f:
            product_list.append(i.strip("n").split(' ')) #拆分为列表并添加到product_list
    def product_info():
        for index,item in enumerate(product_list):
            print(index  1,item[0],item[1])
    while True:
        print("欢迎来到购物商城".center(30, '-'))
        product_info()
        choice_id = input("请输入商品编号(q返回):").strip()
        if choice_id.isdigit():
            choice_id = int(choice_id)
            if 0 <= choice_id <= len(product_list):
                product_item = product_list[choice_id-1] #获取选择的商店
                print("商品 %s 加入购物车,价格 %s " % (product_item[0],product_item[1]))
                product_list2.append(product_item)
                '''购物信息记录到日志模块'''
                shopping_info = ["购物",str(product_item[0]),"价格",product_item[1]]
                shopping_info = "---".join(shopping_info)
                logger.debug(shopping_info)
            else:
                print("没有对应的商品编号,请重新输入!")
        elif choice_id == "q":
            with open(shopping_car,'r ',encoding='utf-8') as f:
                list = json.loads(f.read())
                list.extend(product_list2)
                f.seek(0)
                list = json.dumps(list)
                f.write(list)
                f.flush()
                break
        else:
            print("没有对应的商品编号,请重新输入!")

'''清空购物车'''
def del_shoppingcar():
    while True:
        choice = input("是否清空购物车?('y'确认'q'退出):").strip()
        if choice == 'q':break
        if choice == 'y':
            with open(shopping_car,"r ",encoding='utf-8') as f:
                res = json.loads(f.read())
                print(type(res))
                if res != []:
                    f.seek(0)
                    f.truncate(0)  #截断后面所有的字符也就是清空
                    list = json.dumps([])
                    f.write(list)
                    f.flush()
                    print("购物车已经清空!")
                    break
                else:
                    print("你还没有消费,购物车为空!")
        else:
            print("你输入指令有误!")
            break

'''购物结算'''
def shopping_pay():
    while True:
        print("购物结算".center(50,'-'))
        with open(shopping_car,'r ',encoding='utf-8') as f:
            data = json.loads(f.read())
            if data != []:
                print("t商品t价格")
                for index,item in enumerate(data):
                    print(index  1,item[0],item[1])
                money = sum([int(i[1]) for i in data])
            else:
                print("你还没消费,快去花钱吧!")
                break
        choice = input("商品总额:%s (y)确认支付,(q)返回:" %(money))
        if choice == 'q':break
        if choice == 'y':
            creditcard_id = input("请输入结算的信用卡账号:").strip()
            with open(creditcard_data,'r ',encoding='utf-8') as f2:
                _creditcard_data  = json.loads(f2.read())
                if creditcard_id in _creditcard_data.keys():
                    passwd = input("请输入信用卡 %s 支付密码:" % (_creditcard_data[creditcard_id]["credictcard"])).strip()
                    if int(passwd) == _creditcard_data[creditcard_id]["password"]:
                        limit = _creditcard_data[creditcard_id]["limit"]
                        limitcash = _creditcard_data[creditcard_id]["limitcash"]
                        if _creditcard_data[creditcard_id]["limit"] >= money:
                            _creditcard_data[creditcard_id]["limit"] -= money
                            _creditcard_data[creditcard_id]["limitcash"] -= money
                            _creditcard_data[creditcard_id]["totalbill"]  = money #账单
                            '''写入日志'''
                            shopping_info = [creditcard_id,"信用卡商城结账",str(money) "¥"]
                            shopping_info = '--'.join(shopping_info)
                            logger.debug(shopping_info)
                            '''写入数据'''
                            dict = json.dumps(_creditcard_data)
                            f2.seek(0)
                            f2.truncate(0)
                            f2.write(dict)
                            print("支付成功:%s¥"%(money))
                            break
                        else:
                            print("当前信用卡额度%s不足支付!"%(limit))
                    else:
                        print("密码有误,请重新输入!")
                else:
                    print("你输入的信用卡不存在!")

'''查看购物车'''
def search_shopppingcar():
    print("购物车".center(60,'-'))
    with open(shopping_car,'r',encoding='utf-8') as f:
        shopping_car_info = json.loads(f.read())
        if shopping_car_info != []:
            print("t商品t价格")
            for i in shopping_car_info:
                print(i)
        else:
            print("购物车为空,请去商城看看!!!")

0 人点赞