예제 #1
0
파일: models.py 프로젝트: zhujingxiu/luffy
def update_pwd(user, **kwargs):
    """
    修改个人密码
    :param user: 
    :param kwargs: 
    :return: 
    """
    password = input("请输入新密码:>>").strip()
    confirm = input("请确认新密码:>>").strip()

    if not len(password):
        print("密码太短了")
        return False
    if password != confirm:
        print("新密码与确认密码不相符")
        return False

    db_handler.data_api(
        'update', settings.USER_TABLE, **{
            'set': {
                'password': utils.hash_md5(password)
            },
            'where': [{
                'field': 'id',
                'value': user['id']
            }]
        })
    return {
        'status': 0,
        'logger': kwargs.get('logger'),
        'msg': "用户 %s 修改了密码" % user['username']
    }
예제 #2
0
파일: models.py 프로젝트: zhujingxiu/luffy
def deactivate_product(**kwargs):
    """
    商品下架
    :param kwargs: 
    :return: 
    """
    records = view_products()
    if not records:
        print('没有找到结果')
        return False
    entry_id = input("请输入商品ID,(b,返回)::>>").strip()
    if entry_id.lower() == 'b':
        return False
    ret = db_handler.data_api(
        'update', settings.PRODUCT_TABLE, **{
            'set': {
                'status': 1
            },
            'where': [{
                'field': 'id',
                'value': int(entry_id)
            }]
        })
    if ret:
        return {
            'status': ret,
            'logger': kwargs.get('logger'),
            'msg': "管理员修改了商品ID %s 为下架状态" % entry_id
        }
    return False
예제 #3
0
파일: models.py 프로젝트: zhujingxiu/luffy
def update_user(**kwargs):
    """
    编辑用户信息
    :param kwargs: 
    :return: 
    """
    records = view_users()
    if not records:
        print('没有找到结果')
        return False
    entry_id = input("请输入用户ID,(b,返回):>>").strip()
    if entry_id.lower() == 'b':
        return False
    credit = input("请重新输入用户额度:>>").strip()
    if not credit.isdigit() and not utils.is_float_num(credit):
        print("请输入数字字符")
        return False
    ret = db_handler.data_api(
        'update', settings.USER_TABLE, **{
            'set': {
                'credit': float(credit)
            },
            'where': [{
                'field': 'id',
                'value': int(entry_id)
            }]
        })
    if ret:
        return {
            'status': ret,
            'logger': kwargs.get('logger'),
            'msg': "管理员修改用户ID: %s 的额度" % entry_id
        }
    return False
예제 #4
0
파일: models.py 프로젝트: zhujingxiu/luffy
def histories(user, fields=''):
    """
    查看个人信息
    :param user: 指定字段
    :param fields: 指定字段
    :return: 
    """
    if not len(fields):
        fields = ('username', 'transaction', 'amount', 'fee', 'balance',
                  'add_time', 'note')
    trans_logs = db_handler.data_api(
        'find', settings.HISTORY_TABLE, **{
            'fields': fields,
            'where': [{
                'field': 'user_id',
                'value': user['id']
            }]
        })
    if isinstance(trans_logs, int) or not len(trans_logs):
        print('没有交易记录')
        return False
    result = []
    for item in trans_logs:
        info = {}
        for i in fields:
            info[i] = item[i]
            if i == 'add_time':
                info[i] = time.strftime("%Y-%m-%d %H:%M:%S",
                                        time.localtime(item['add_time'] // 1))
            if i == 'transaction':
                info[i] = utils.format_transaction(item['transaction'])
        result.append(info)
    utils.format_table(fields, result)
    return True
예제 #5
0
파일: models.py 프로젝트: zhujingxiu/luffy
def load_user(user_id=0, username=''):
    """
    加载最新的用户信息
    :param user_id: 
    :param username: 
    :return: 
    """
    if not user_id and not username:
        return []
    field = 'username' if username else 'id'
    if user_id and username:
        field = 'id'
    value = username if field == 'username' else user_id

    ret = db_handler.data_api(
        'find', settings.USER_TABLE, **{
            'fields': ('*', ),
            'where': [{
                'field': field,
                'value': value
            }]
        })
    if isinstance(ret, int) or not len(ret):
        return []
    return ret[0]
예제 #6
0
파일: models.py 프로젝트: lxorz/ATM
def consume(user, **kwargs):
    """
    消费
    :param user:
    :param kwargs:
    :return:
    """
    product_id = kwargs.get('product_id')
    if not product_id:
        print('商品参数异常')
        return False

    product = load_product(product_id)
    if not product or product['status'] != 0 or product['number'] == 0:
        print("商品状态异常,无存货或已下架")
        return False
    amount = float(product['price'])
    kwargs['note'] = "购买商品:%s" % product['title']
    ret = transaction.make_transaction(user, 'consume', amount, **kwargs)
    if not ret:
        return False
    new_user = ret.get('user', False)
    if new_user:
        ret1 = add_cart(user, product)
        new_number = product['number'] - 1
        update = {'number': new_number}
        if not update['number']:
            update['status'] = 1
        ret3 = db_handler.data_api(
            'update', settings.PRODUCT_TABLE, **{
                'set': update,
                'where': [{
                    'field': 'id',
                    'value': product_id
                }]
            })
        history = {
            'user_id': user['id'],
            'username': user['username'],
            'transaction': 'consume',
            'amount': amount,
            'fee': ret.get('fee', 0),
            'balance': new_user['balance'],
            'add_time': time.time(),
            'note': kwargs['note'],
        }
        return {
            'status': 0,
            'history': history,
            'msg': '购买成功,余额 %s' % new_user['balance']
        }
    return False
예제 #7
0
파일: models.py 프로젝트: zhujingxiu/luffy
def check_exists(table, **kwargs):
    """
    验证是否存在记录
    :param table: 
    :param kwargs: 
    :return: 
    """
    ret = db_handler.data_api(
        'find', table, **{
            'fields': ('*', ),
            'where': kwargs.get('where')
        })

    return False if isinstance(ret, int) else len(ret)
예제 #8
0
파일: models.py 프로젝트: lxorz/ATM
def load_product(product_id):
    """
    加载最新的用户信息
    :param product_id:
    :return:
    """
    ret = db_handler.data_api(
        'find', settings.PRODUCT_TABLE, **{
            'fields': ('*', ),
            'where': [{
                'field': 'id',
                'value': product_id
            }]
        })
    if isinstance(ret, int) or not len(ret):
        return []
    return ret[0]
예제 #9
0
파일: models.py 프로젝트: lxorz/ATM
def view_products(user, **kwargs):
    """
    查看商品列表
    :param user:
    :param kwargs:
    :return:
    """
    fields = kwargs.get('fields', ())
    if not len(fields):
        fields = ('id', 'title', 'price', 'number', 'status')

    ret = db_handler.data_api(
        'find', settings.PRODUCT_TABLE, **{
            'fields': fields,
            'where': [{
                'field': 'status',
                'logic': '!=',
                'value': 1
            }]
        })
    if isinstance(ret, int):
        return ret
    if not len(ret):
        print('没有商品')
        return False
    result = []
    for i in ret:
        if 'status' in i:
            i.update({'status': utils.format_status(i['status'])})
        result.append(i)
    utils.format_table(fields, result)

    option = input("请输入要购买的商品ID,(0,注销;b,返回):>>").strip()
    if option.isdigit():
        if option == '0':
            logout(user, **kwargs)
        else:
            consume(
                user, **{
                    'product_id': int(option),
                    'logger': kwargs.get('logger')
                })
    elif option.lower() == 'b':
        return True
예제 #10
0
파일: models.py 프로젝트: zhujingxiu/luffy
def add_product(**kwargs):
    """
    添加商品信息
    :param kwargs: 
    :return: 
    """
    title = input("请输入商品名,(b,返回):>>").strip()
    if title.lower() == 'b':
        return False
    price = input("请输入单价:>>").strip()
    number = input("请输入数量:>>").strip()

    if check_exists(settings.PRODUCT_TABLE,
                    **{'where': [{
                        'field': 'title',
                        'value': title
                    }]}):
        print("商品%s已存在" % title)
        return False
    if not price.isdigit() and not utils.is_float_num(price):
        print("请输入数字字符")
        return False
    if not number.isdigit():
        print("请输入数字字符")
        return False
    entry = settings.DATABASE['tables'][settings.PRODUCT_TABLE]['structure']
    entry.update({
        'id': get_increment_id(settings.PRODUCT_TABLE),
        'title': title,
        'price': float(price),
        'number': int(number),
    })
    ret = db_handler.data_api('add', settings.PRODUCT_TABLE,
                              **{'fields': entry})
    if ret:
        return {
            'status': ret,
            'logger': kwargs.get('logger'),
            'msg': "管理员添加商品 %s" % title
        }
    return False
예제 #11
0
파일: models.py 프로젝트: zhujingxiu/luffy
def view_products(fields=''):
    """
    查看商品列表
    :param fields: 
    :return: 
    """
    if not len(fields):
        fields = ('id', 'title', 'price', 'number', 'status')
    ret = db_handler.data_api('find', settings.PRODUCT_TABLE,
                              **{'fields': fields})
    if isinstance(ret, int):
        return ret
    if not len(ret):
        return False
    result = []
    for i in ret:
        if 'status' in i:
            i.update({'status': utils.format_status(i['status'])})
        result.append(i)
    utils.format_table(fields, result)
    return ret
예제 #12
0
파일: models.py 프로젝트: zhujingxiu/luffy
def add_history(history):
    """
    添加交易流水记录
    :param history: 
    :return: 
    """
    records = []
    if isinstance(history, dict):
        records.append(history)
    else:
        records = history
    count_num = 0
    for item in records:

        if not set(item.keys()).issubset(settings.DATABASE['tables'][
                settings.HISTORY_TABLE]['structure'].keys()):
            continue
        ret = db_handler.data_api('add', settings.HISTORY_TABLE,
                                  **{'fields': item})
        if ret:
            count_num += 1
    return count_num
예제 #13
0
파일: models.py 프로젝트: zhujingxiu/luffy
def update_product(**kwargs):
    """
    编辑商品信息
    :param kwargs: 
    :return: 
    """
    records = view_products()
    if not records:
        print('没有找到结果')
        return False
    entry_id = input("请输入商品ID,(b,返回):>>").strip()
    if entry_id.lower() == 'b':
        return False
    price = input("请重新输入单价:>>").strip()
    number = input("请重新输入数量:>>").strip()
    if not price.isdigit() or not number.isdigit():
        print("请输入数字字符")
        return False
    ret = db_handler.data_api(
        'update', settings.PRODUCT_TABLE, **{
            'set': {
                'price': float(price),
                'number': int(number)
            },
            'where': [{
                'field': 'id',
                'value': int(entry_id)
            }]
        })
    if ret:
        return {
            'status': ret,
            'logger': kwargs.get('logger'),
            'msg': "管理员修改了商品ID: %s 的信息" % entry_id
        }
    return False
예제 #14
0
파일: models.py 프로젝트: lxorz/ATM
def add_cart(user, product):
    """
    添加商品到用户购物车
    :param user:
    :param product:
    :return:
    """
    user['cart'].append({
        'product_id': product['id'],
        'title': product['title'],
        'amount': product['price'],
        'number': 1,
        'created_at': utils.calculate_date(time_format=True)
    })
    return db_handler.data_api(
        'update', settings.USER_TABLE, **{
            'set': {
                'cart': user['cart']
            },
            'where': [{
                'field': 'id',
                'value': user['id']
            }]
        })
예제 #15
0
파일: main.py 프로젝트: zhujingxiu/luffy
# _DATE_    : 2018/1/16

import os
import sys

sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(
        os.path.abspath(__file__)))))

from conf import settings
from core import db_handler
from core import utils
from atm12 import models
import time
print(time.time())
# print(models.load_user('zhujingxiu'))
fields = ('id', 'title', 'price', 'number', 'status')
ret = db_handler.data_api('find', settings.PRODUCT_TABLE, **{'fields': fields})

user = {
    "id": 3,
    "username": "******",
    "password": "******",
    "credit": 12345.0,
    "balance": 12345.0,
    "enroll_date": "2018-01-16",
    "expire_date": "2023-01-16",
    "status": 0,
    "cart": {}
}