Commit 4a3dd0f4 by Aeolus

Merge branch 'aeolus'

parents d351ecd1 92264414
......@@ -56,5 +56,10 @@ AGENT_STATUS = {
ACCOUNT_STATUS = {
'on_use': 1,
'delete': 2
'delete': -1
}
DISCOUNTS_TYPES = {
0: "暂无折扣",
1: "每日首单免费",
}
......@@ -12,6 +12,11 @@ SK_CONFIG = {
"app_secret": os.getenv("SK_MINI_PROGRAM_APPSECRET"),
}
XXZN_CONFIG = {
"app_id": os.getenv("XXZN_MINI_PROGRAM_APPID"),
"app_secret": os.getenv("XXZN_MINI_PROGRAM_APPSECRET"),
}
XX_PAY_CONFIG = {
"mch_id": os.getenv("XX_MCHID"),
"pay_key": os.getenv("XX_PAY_KEY"),
......@@ -28,19 +33,22 @@ pay_config_dict = {
"xx": XX_PAY_CONFIG,
}
platform_config_list = ["", "sukang24h", ]
platform_config_list = ["", "sukang24h", "xxzn"]
platform_config_dict = {
"sukang24h": SK_CONFIG,
"xxzn": XXZN_CONFIG
}
platform_appid_config_list = [
"",
SK_CONFIG["app_id"], # 苏康24H 平台序号 ==>1
XXZN_CONFIG["app_id"]
]
platform_appid_config_dict = {
"sukang24h": SK_CONFIG["app_id"],
"xxzn": XXZN_CONFIG["app_id"]
}
......
......@@ -57,7 +57,7 @@ class AdminMachine(Base):
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
machine_no = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
status = Column(INTEGER(1), default=1, nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
......@@ -69,7 +69,7 @@ class AdminPlace(Base):
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
place_id = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
status = Column(INTEGER(1), nullable=False, server_default=text("'1'"))
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
......@@ -130,9 +130,10 @@ class Machine(Base):
id = Column(INTEGER(10), primary_key=True)
machine_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False, unique=True, comment='机柜编号')
qrcode_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False, unique=True, comment='二维码编号')
mac = Column(String(30, 'utf8mb4_unicode_ci'), nullable=False, unique=True, comment='mac')
power = Column(TINYINT(3), nullable=False, server_default=text("'0'"), comment='电量')
device_id = Column(String(45, 'utf8mb4_unicode_ci'), unique=True)
qrcode_no = Column(String(20, 'utf8mb4_unicode_ci'), unique=True, comment='二维码编号')
mac = Column(String(30, 'utf8mb4_unicode_ci'), unique=True, comment='mac')
power = Column(TINYINT(3), server_default=text("'0'"), comment='电量')
short_address = Column(VARCHAR(45))
address = Column(String(191, 'utf8mb4_unicode_ci'), comment='机柜位置')
place_id = Column(INTEGER(10), nullable=False)
......@@ -140,10 +141,11 @@ class Machine(Base):
position = Column(String(20, 'utf8mb4_unicode_ci'), comment='机柜位置坐标')
hatch_number = Column(TINYINT(3), nullable=False, server_default=text("'0'"), comment='机柜的仓口数量')
type = Column(TINYINT(3), nullable=False, server_default=text("'1'"), comment='机柜类型1正常')
status = Column(TINYINT(1), server_default=text("'1'"), comment='状态: 1正常-1删除')
status = Column(TINYINT(1), default=text("'0'"), comment='状态: 0未激活 1正常-1删除')
created_at = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
command_time = Column(INTEGER(1), nullable=False)
command_time = Column(INTEGER(1), nullable=False, server_default=text("'1'"))
discounts_id = Column(INTEGER(11), nullable=False, server_default=text("'0'"), comment="折扣活动")
class MachineProduction(Base):
......@@ -208,14 +210,16 @@ class Place(Base):
__tablename__ = 'place'
id = Column(INTEGER(10), primary_key=True)
parent_id = Column(INTEGER(10), server_default=FetchedValue(), nullable=False)
place_name = Column(VARCHAR(191), nullable=False, index=True, comment='场所名')
img = Column(VARCHAR(191), comment='展示界面的图片')
logo = Column(VARCHAR(191), nullable=False, comment='微型头像')
address = Column(VARCHAR(255), nullable=False, server_default=text("''"))
logo = Column(VARCHAR(191), comment='微型头像')
address = Column(VARCHAR(255), server_default=text("''"))
position = Column(String(20, 'utf8mb4_unicode_ci'))
open_time = Column(VARCHAR(191), nullable=False, comment='开始时间')
close_time = Column(VARCHAR(191), nullable=False, comment='结束时间')
open_week = Column(VARCHAR(255), nullable=False, server_default=text("''"))
open_time = Column(VARCHAR(191), comment='开始时间')
close_time = Column(VARCHAR(191), comment='结束时间')
open_week = Column(VARCHAR(255), server_default=text("''"))
status = Column(INTEGER(1), nullable=False, server_default=text("'1'"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
......
#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2021/07/02
@file: __init__.py.py
@function:
@modify:
"""
\ No newline at end of file
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2021/07/02
@file: agent_modules.py
@function:
@modify:
"""
from mongodb_collections.base_collection import BaseCollection
class AdminModules(BaseCollection):
def __init__(self):
super().__init__(collection_name="admin_modules")
class Modules(BaseCollection):
def __init__(self):
super().__init__(collection_name="modules")
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2021/07/02
@file: base_collection.py
@function:
@modify:
"""
from pymongo import MongoClient
from config.base_config import MONGO_DATABASE_URI
class BaseCollection(object):
def __init__(self, collection_name, db_name="suishenwan", ):
mongodatabase = MongoClient(MONGO_DATABASE_URI).get_database(db_name)
self.collection = mongodatabase.get_collection(collection_name)
def find_one(self, where):
return self.collection.find_one(where)
......@@ -22,7 +22,7 @@ def create_app(config_name):
load_dotenv(dotenv_path=env_path, verbose=True, override=True)
set_logger()
app = Flask("sukang24h")
app = Flask("automat")
from config.app_config import config
app.config.from_object(config[config_name])
CORS(app)
......@@ -40,6 +40,6 @@ def create_app(config_name):
app.after_request(close_db_session)
# todo register blueprint
from myapps.sukang24h.api import register_sukang_blueprint
from myapps.automat.api import register_sukang_blueprint
register_sukang_blueprint(app)
return app
......@@ -7,17 +7,17 @@ author:Aeolus
"""
from flask import Flask
from myapps.sukang24h.api.wx_auth_portal import wx_auth_route
from myapps.sukang24h.api.hatch_portal import hatch_route
from myapps.sukang24h.api.rent_portal import rent_route
from myapps.sukang24h.api.tallyman_portal import tallyman_route
from myapps.sukang24h.api.machine_portal import machine_route
from myapps.sukang24h.api.nfc_card_portal import nfc_card_route
from myapps.sukang24h.api.card_edit_portal import card_edit_route
from myapps.automat.api.wx_auth_portal import wx_auth_route
from myapps.automat.api.hatch_portal import hatch_route
from myapps.automat.api.rent_portal import rent_route
from myapps.automat.api.tallyman_portal import tallyman_route
from myapps.automat.api.machine_portal import machine_route
from myapps.automat.api.nfc_card_portal import nfc_card_route
from myapps.automat.api.card_edit_portal import card_edit_route
def register_sukang_blueprint(app: Flask):
prefix = "/sukang"
prefix = "/automat"
app.register_blueprint(wx_auth_route, url_prefix=prefix + "/wx_auth")
app.register_blueprint(hatch_route, url_prefix=prefix + "/hatch")
app.register_blueprint(rent_route, url_prefix=prefix + "/rent")
......
......@@ -6,12 +6,14 @@ author:Aeolus
@file: hatch_portal.py
"""
import logging
import time
from flask import Blueprint, request, jsonify, g
from models.base_model import db
from models.models import Machine, Production, Hatch, RentDetail
from utils.error_code import MACHINE_NOT_EXIST_ERROR, HATCH_NOT_EXIST_ERROR
from utils.error_code import MACHINE_NOT_EXIST_ERROR, HATCH_NOT_EXIST_ERROR, MACHINE_NO_CREATE_ERROR, \
MACHINE_MAC_DUPLICATE_ERROR
from utils.my_response import BaseResponse
logger = logging.getLogger(__name__)
......@@ -92,3 +94,43 @@ def run_get_machine_no():
"command_time": machine.command_time, "type": machine.type})
else:
return jsonify(MACHINE_NOT_EXIST_ERROR)
@machine_route.route('create_machine_no', methods=["post"])
def run_create_machine_no():
json_data = request.get_json()
mac = json_data["iMEI"]
hatch_number = json_data["slotCount"]
machine = Machine.query.filter_by(mac=mac).first()
if machine:
return jsonify(MACHINE_MAC_DUPLICATE_ERROR)
for i in range(3):
machine_no = int(time.time())
machine = Machine.query.filter_by(machine_no=machine_no).first()
if not machine:
break
return jsonify(MACHINE_NO_CREATE_ERROR)
machine_model = Machine()
machine_model.machine_no = machine_no
machine_model.mac = mac
machine_model.hatch_number = hatch_number
db.session.add(machine_model)
db.session.commit()
return BaseResponse(data={"machine_no": machine_no})
@machine_route.route('bind_serial_num', methods=["post"])
def run_bind_serial_num():
json_data = request.get_json()
machine_no = json_data["machine_no"]
serial_num = json_data["serial_num"]
machine = Machine.query.filter_by(machine_no=machine_no).first()
if not machine:
return jsonify(MACHINE_NOT_EXIST_ERROR)
machine.device_id = serial_num
db.session.add(machine)
db.session.commit()
return BaseResponse(data={"machine_no": machine_no, "serial_num": serial_num})
......@@ -15,7 +15,7 @@ from functools import reduce
from flask import Blueprint, request, jsonify, g
from sqlalchemy import func
from config.commen_config import USER_RENT_PREPAY_ID, RENT_SALE_LOCK
from config.commen_config import USER_RENT_PREPAY_ID, RENT_SALE_LOCK, DISCOUNTS_TYPES
from config.wechat_config import platform_appid_config_list, pay_config_list
from models.base_model import db
from models.models import Machine, Hatch, Rent, WxUser, RentDetail
......@@ -31,6 +31,28 @@ logger = logging.getLogger(__name__)
rent_route = Blueprint('rent', __name__)
@rent_route.route("discounts_info", methods=["POST"])
def get_discount_info():
json_data = request.get_json()
machine_no = json_data["machine_no"]
user = g.user
# 验证机柜是否存在
machine = Machine.query.filter_by(machine_no=machine_no).first()
if not machine:
return jsonify(MACHINE_NOT_EXIST_ERROR)
if machine.discounts_id == 1:
rent = Rent.query.filter(db.cast(Rent.created_at, db.DATE) == db.cast(datetime.datetime.now(), db.DATE)).first()
if rent:
is_used = 1
else:
is_used = 0
return_data = {"discounts_id": machine.discounts_id,
"discounts_name": DISCOUNTS_TYPES[int(machine.discounts_id)],
"is_used": is_used}
return BaseResponse(data=return_data)
@rent_route.route("rent", methods=["POST"])
def create_rent():
json_data = request.get_json()
......@@ -43,6 +65,67 @@ def create_rent():
if not machine:
return jsonify(MACHINE_NOT_EXIST_ERROR)
if machine.discounts_id == 1:
rent = Rent.query.filter(db.cast(Rent.created_at, db.DATE) == db.cast(datetime.datetime.now(), db.DATE)).first()
if not rent:
if len(productions) != 1:
return jsonify(HATCH_COUNT_ERROR)
total_fee = 0
for id, count in productions.items():
count = int(count)
if count != 1:
return jsonify(HATCH_COUNT_ERROR)
id = int(id)
# 根据给的仓号去获取商品信息
open_hatch = Hatch.query.filter(Hatch.machine_no == machine_no, Hatch.production_id == id,
Hatch.left_count >= 1).order_by(func.random()).first()
if not open_hatch:
print("....")
return jsonify(HATCH_NOT_EXIST_ERROR)
break
rent_no = RentService.create_order_no()
rent = Rent()
rent.rent_no = rent_no
rent.machine_no = machine.machine_no
rent.user_id = g.user.id
rent.place_id = machine.place_id
rent.total = total_fee
rent.add_time = datetime.datetime.now()
rent.is_pay = 1
rent.pay_time = datetime.datetime.now()
rent.rent_type = type
rent.mch_platform = machine.mch_platform
rent_detail = RentDetail()
rent_detail.rent_no = rent_no
rent_detail.user_id = rent.user_id
rent_detail.machine_no = rent.machine_no
rent_detail.hatch_no = open_hatch.hatch_no
rent_detail.production_id = open_hatch.production_id
rent_detail.name = open_hatch.name
rent_detail.title = open_hatch.title
rent_detail.brand_id = open_hatch.brand_id
rent_detail.brand_name = open_hatch.brand_name
rent_detail.cate_id = open_hatch.cate_id
rent_detail.cate_name = open_hatch.cate_name
rent_detail.price = 0
rent_detail.rent_count = 1
rent_detail.img = open_hatch.img
rent_detail.tags = open_hatch.tags
rent_detail.content = open_hatch.content
rent_detail.summary = open_hatch.summary
open_hatch.left_count -= 1
if open_hatch.left_count <= 0:
open_hatch.status = 2
db.session.add(rent)
db.session.add(rent_detail)
db.session.commit()
return BaseResponse(data={"out_trade_no": rent_no, "free_order": True})
total_fee = 0
open_hatchs = {}
for id, count in productions.items():
......
......@@ -12,8 +12,12 @@ author:Aeolus
from flask import Flask
from myapps.pc_management.api.admin_portal import admin_route
from myapps.pc_management.api.place_portal import place_route
from myapps.pc_management.api.machine_portal import machine_route
def register_sukang_blueprint(app: Flask):
prefix = "/pc_management"
app.register_blueprint(admin_route, url_prefix=prefix + "/admin")
app.register_blueprint(place_route, url_prefix=prefix + "/place")
app.register_blueprint(machine_route, url_prefix=prefix + "/machine")
......@@ -6,14 +6,15 @@ from flask import Blueprint, jsonify, request, g
from pymongo import MongoClient, ASCENDING
from config.wechat_config import platform_config_list
from config.commen_config import LOGIN_TYPE, ACCOUNT_STATUS
from mongodb_collections.agent_modules import Modules, AdminModules
from service.admin_service import AdminService
from utils.error_code import ACCOUNT_AGENT_SPOT_NULL_ERROR, ACCOUNT_NOT_EXISTS_ERROR, \
ACCOUNT_ALREADY_EXISTS_ERROR, ACCOUNT_ALREADY_DELETE_ERROR, AGNET_MODULES_ERROR, MODULES_NOT_EXISTS_ERROR, \
OPERATE_LEVEL_ERROR
OPERATE_LEVEL_ERROR, Param_Invalid_Error, COMMON_MONGO_ERROR
from utils.error_code import PHONE_NOT_NULL_ERROR, PHONE_NOT_VALID_ERROR, TOKEN_NOT_VALID_ERROR, \
VERIFICATION_CODE_INVALID_ERROR, VERIFICATION_CODE_ERROR, PASSWORD_ERROR
from models.base_model import db
from models.models import AdminAccount, AdminLoginRecord, AdminMachine
from models.models import AdminAccount, AdminLoginRecord, AdminMachine, AdminPlace, Place
from utils.jwt_util import verify_jwt, generate_jwt
from utils.my_response import BaseResponse
from service.sms_service import SMSService
......@@ -80,15 +81,15 @@ def user_login():
new_token = generate_jwt(payload={"user_id": user_info.id}, expiry=time.time() + 24 * 60 * 60)
agent_log = AdminLoginRecord()
agent_log.phone = user_info.phone
agent_log.ip = cur_ip
agent_log.platform = platform_config_list.index(platform)
agent_log.last_login = datetime.datetime.now()
agent_log.login_type = LOGIN_TYPE['token_login']
agent_log.created_at = datetime.datetime.now()
agent_log.updated_at = datetime.datetime.now()
db.session.add(agent_log)
admin_log = AdminLoginRecord()
admin_log.phone = user_info.phone
admin_log.ip = cur_ip
admin_log.platform = platform_config_list.index(platform)
admin_log.last_login = datetime.datetime.now()
admin_log.login_type = LOGIN_TYPE['token_login']
admin_log.created_at = datetime.datetime.now()
admin_log.updated_at = datetime.datetime.now()
db.session.add(admin_log)
db.session.commit()
data['token'] = new_token
......@@ -109,7 +110,7 @@ def add_user():
return jsonify(OPERATE_LEVEL_ERROR)
password = json_data.get('password', "123456")
comment = json_data.get('comment', "")
parent_id = json_data.get("parent_id", 0)
parent_id = json_data.get("parent_id", admin.id)
draw = json_data.get("draw", 0)
rate = json_data.get("rate", 0)
......@@ -150,24 +151,23 @@ def get_account_list():
page_size = json_data.get("pageSize", None)
keyword = json_data.get("keyword", None)
select_sql = """select agent_account.user_name, agent_account.phone, agent_account.level, agent_account.status,
agent_account.comment, agent_account.created_at, agent_account.updated_at, agent_account.last_login,
agent_account.id
select_sql = """select admin_account.user_name, admin_account.phone, admin_account.level, admin_account.status,
admin_account.comment,admin_account.parent_id,admin_account.rate, admin_account.created_at,
admin_account.updated_at,admin_account.id, admin_account.user_no
"""
count_sql = "select count(agent_account.id) as total_count"
count_sql = "select count(admin_account.id) as total_count"
from_sql = " from agent_account where agent_account.id in ( select agent_account.id "
from_sql += " from agent_account "
from_sql += " left join agent_spot on agent_account.id = agent_spot.agent_no "
from_sql += " left join spot on spot.id = agent_spot.spot_no "
where_sql = " where 0=0 "
from_sql = " from admin_account where admin_account.id in ( select admin_account.id "
from_sql += " from admin_account "
where_sql = " where 0=0 and admin_account.level > {} and admin_account.parent_id = {}".format(g.user.level,
g.user.id)
if keyword:
where_sql += """
and CONCAT(agent_account.user_name,agent_account.phone,spot.spotname) LIKE '%{keyword}%'
and CONCAT(admin_account.user_name,admin_account.phone, admin_account.user_no) LIKE '%{keyword}%'
""".format(keyword=keyword)
where_sql += " ) "
order_sql = " ORDER BY agent_account.created_at ASC, agent_account.status ASC"
order_sql = " ORDER BY admin_account.id ASC, admin_account.status ASC"
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
......@@ -177,16 +177,17 @@ def get_account_list():
else:
total_count = count_result.total_count
print(select_sql + from_sql + where_sql + order_sql + limit_sql)
result = db.session.execute(select_sql + from_sql + where_sql + order_sql + limit_sql).fetchall()
return_data = []
for info in result:
return_data.append(
{"user_name": info.user_name, "phone": info.phone, "level": info.level, "status": info.status,
"comment": info.comment, "agent_id": info.id,
"create_time": info.created_at.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else "",
"update_time": info.updated_at.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else "",
"login_time": info.last_login.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else ""})
"comment": info.comment, "user_id": info.id, "user_no": info.user_no,
"create_time": info.created_at.strftime("%Y-%m-%d %H:%M:%S"),
"update_time": info.updated_at.strftime("%Y-%m-%d %H:%M:%S"),
})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
......@@ -195,33 +196,25 @@ def get_account_list():
def get_account_detail():
json_data = request.get_json()
phone = json_data["phone"]
agent_info = AdminAccount.query.filter_by(phone=phone).first()
if not agent_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
user_info = {}
user_info["agent_no"] = agent_info.agent_no
user_info["user_name"] = agent_info.user_name
user_info["phone"] = phone
user_info["level"] = agent_info.level
user_info["status"] = ACCOUNT_STATUS['on_use']
user_info["comment"] = agent_info.comment
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent_info.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
if phone == g.user.phone:
admin_info = g.user
else:
user_info["spot_list"] = []
return BaseResponse(data=user_info)
spot_list = db.session.query(Spot).filter(Spot.id.in_(spot_no_list)).all()
if spot_list:
spot_data_list = [
{"spot_name": i.spotname, "spot_id": i.id, "business_id": i.business_id, "spot_address": i.address} for i in
spot_list]
else:
spot_data_list = []
user_info["spot_list"] = spot_data_list
admin_info = AdminAccount.query.filter(AdminAccount.phone == phone,
AdminAccount.level > g.user.level,
AdminAccount.parent_id == g.user.id).first()
if not admin_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
user_info = {
"user_id": admin_info.id,
"user_no": admin_info.user_no,
"user_name": admin_info.user_name,
"phone": admin_info.phone,
"level": admin_info.level,
"status": admin_info.status,
"comment": admin_info.comment
}
return BaseResponse(data=user_info)
......@@ -230,12 +223,11 @@ def edit_user():
json_data = request.get_json()
old_phone = json_data['old_phone'] if 'old_phone' in json_data else ''
new_phone = json_data['new_phone'] if 'new_phone' in json_data else ''
user_name = json_data['name'] if 'name' in json_data else 'SSW'
user_name = json_data['user_name'] if 'user_name' in json_data else 'SSW'
password = json_data['password'] if 'password' in json_data else ''
comment = json_data['comment'] if 'comment' in json_data else ''
level = json_data['level'] if 'level' in json_data else ''
status = json_data['status'] if 'status' in json_data else ''
spot_list = json_data['spot_list'] if 'spot_list' in json_data else []
if not old_phone:
return BaseResponse(error_code=-1, error_message='old phone is null')
......@@ -245,51 +237,27 @@ def edit_user():
if not status:
return BaseResponse(**Param_Invalid_Error)
result = Helper.check_phone(new_phone)
if not result:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
if not spot_list:
return BaseResponse(**ACCOUNT_AGENT_SPOT_NULL_ERROR)
agent_info = AdminAccount.query.filter_by(phone=old_phone).first()
if not agent_info:
if old_phone == g.user.phone:
admin_info = g.user
if level:
admin_info.level = int(level)
else:
admin_info = AdminAccount.query.filter(AdminAccount.phone == old_phone,
AdminAccount.level > g.user.level,
AdminAccount.parent_id == g.user.id
).first()
if not admin_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
agent_info.user_name = user_name
agent_info.phone = new_phone
agent_info.status = status
agent_info.comment = comment
if level:
agent_info.level = int(level)
admin_info.user_name = user_name
admin_info.phone = new_phone
admin_info.status = status
admin_info.comment = comment
if password:
salt = AgentService.gene_salt()
agent_info.salt_pwd = salt
agent_info.password = AgentService.gene_pwd(password, salt)
db.session.add(agent_info)
agent_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id).all()
for info in agent_spot_info:
info.status = ACCOUNT_STATUS['delete']
db.session.add(info)
for i in spot_list:
cur_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id, spot_no=i).first()
if not cur_spot_info:
cur_agent_spot = AgentSpot()
cur_agent_spot.agent_no = agent_info.id
cur_agent_spot.spot_no = i
cur_agent_spot.status = ACCOUNT_STATUS['on_use']
cur_agent_spot.created_at = datetime.datetime.now()
cur_agent_spot.updated_at = datetime.datetime.now()
db.session.add(cur_agent_spot)
else:
cur_spot_info.status = ACCOUNT_STATUS['on_use']
db.session.add(cur_spot_info)
admin_info.password = password
db.session.add(admin_info)
db.session.commit()
return BaseResponse()
......@@ -301,215 +269,13 @@ def delete_user():
if not phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
agent_info = AdminAccount.query.filter_by(phone=phone).first()
if not agent_info:
admin_info = AdminAccount.query.filter(AdminAccount.phone == phone,
AdminAccount.level > g.user.level).first()
if not admin_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
agent_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id).all()
for info in agent_spot_info:
info.status = ACCOUNT_STATUS['delete']
db.session.add(info)
agent_info.status = ACCOUNT_STATUS['delete']
db.session.add(agent_info)
admin_info.status = ACCOUNT_STATUS['delete']
db.session.add(admin_info)
db.session.commit()
return BaseResponse()
@admin_route.route('/sendCode', methods=['GET', 'POST'])
def send_code():
json_data = request.get_json()
cur_ip = request.remote_addr
phone = json_data['phone'] if 'phone' in json_data else None
if not phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
# 判断该手机号是否再数据库中,不在返回无权限登录
agent = AdminAccount.query.filter_by(phone=phone).first()
if not agent:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
# 判断该账号是否已被删除
if agent.status == ACCOUNT_STATUS['delete']:
return BaseResponse(**ACCOUNT_ALREADY_DELETE_ERROR)
# result = Helper.check_phone(phone)
# if not result:
# return BaseResponse(**PHONE_NOT_VALID_ERROR)
sms = SMSService()
result = sms.phoneSendCode(phone, 520391, '灰兔智能')
logger.info(result)
agent_log = AdminLoginRecord()
agent_log.phone = phone
agent_log.ip = cur_ip
agent_log.last_login = datetime.datetime.now()
agent_log.login_type = LOGIN_TYPE['send_code']
agent_log.created_at = datetime.datetime.now()
agent_log.updated_at = datetime.datetime.now()
db.session.add(agent_log)
db.session.commit()
return BaseResponse()
@admin_route.route('/agent_module_list', methods=['GET', 'POST'])
def get_agent_module_list():
agent_id = g.user.id
platform = g.platform
if int(g.user.level) != 1:
agent_modules = AgentModules()
result = agent_modules.find_one({"agent_id": agent_id, "platform": platform})
return_data = {"agent_id": agent_id, "module_list": result["module_list"]}
if result:
return BaseResponse(data=return_data)
else:
return BaseResponse(**AGNET_MODULES_ERROR)
modules = Modules()
result = modules.collection.find({"platform": platform}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
module_list = list(tmp_data.values())
return_data = {"agent_id": agent_id, "module_list": module_list}
if result:
return BaseResponse(data=return_data)
else:
return BaseResponse(**AGNET_MODULES_ERROR)
@admin_route.route('/agent_module_list_by_agent_id', methods=['GET', 'POST'])
def get_agent_module_list_by_agent_id():
admin_user = g.user
if int(admin_user.level) != 1:
return BaseResponse(**OPERATE_LEVEL_ERROR)
platform = g.platform
json_data = request.get_json()
agent_id = json_data.get("agent_id", None)
agent_modules = AgentModules()
result = agent_modules.find_one({"agent_id": agent_id, "platform": platform})
if result:
return_data = {"agent_id": agent_id, "module_list": result["module_list"]}
else:
return_data = {"agent_id": agent_id, "module_list": []}
return BaseResponse(data=return_data)
@admin_route.route("/set_module_list", methods=['GET', 'POST'])
def set_agent_module_list():
parent_agent_id = g.user.id
platform = g.platform
platform_int = platform
json_data = request.get_json()
module_list = json_data.get("module_list", [])
agent_id = json_data.get("agent_id", None)
if not module_list or not agent_id:
return BaseResponse(**Param_Invalid_Error)
agent_modules = AgentModules()
modules = Modules()
if int(g.user.level) == 1:
result = modules.collection.find({"platform": platform}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
return_data = []
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["id"] in module_list:
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
return_data = list(tmp_data.values())
else:
result = agent_modules.collection.find_one({"platform": platform_int, "agent_id": parent_agent_id})
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = result["module_list"]
return_data = []
for i in parent_module_list:
if i["id"] in module_list:
tmp_data = i
children_list = i["children"]
tmp_data["children"] = []
for j in children_list:
if j["id"] in module_list:
tmp_data["children"].append(j)
return_data.append(tmp_data)
for i in range(3):
agent_modules.collection.replace_one({'agent_id': agent_id, "platform": platform_int},
{'agent_id': agent_id, "platform": platform_int,
"module_list": return_data},
upsert=True)
result = agent_modules.collection.find_one({'agent_id': agent_id, "platform": platform_int,
"module_list": return_data})
if result:
return BaseResponse()
else:
continue
return BaseResponse(**COMMON_MONGO_ERROR)
# @admin_route.route("/set_super_user_module_list", methods=['GET', 'POST'])
def set_super_agent_module_list():
platform = g.platform
platform_int = platform
json_data = request.get_json()
module_list = json_data.get("module_list", [])
agent_id_list = json_data.get("agent_id_list", None)
if not module_list or not agent_id_list:
return BaseResponse(**Param_Invalid_Error)
agent_modules = AgentModules()
modules = Modules()
result = modules.collection.find({"platform": platform_int, "id": {"$in": module_list}}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
return_data = list(tmp_data.values())
for agent_id in agent_id_list:
for i in range(3):
agent_modules.collection.replace_one({'agent_id': agent_id, "platform": platform_int},
{'agent_id': agent_id, "platform": platform_int,
"module_list": return_data},
upsert=True)
result = agent_modules.collection.find_one({'agent_id': agent_id, "platform": platform_int,
"module_list": return_data})
if result:
break
else:
continue
return BaseResponse()
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2022/01/12
@file: machine_portal.py
@function:
@modify:
"""
import logging
from flask import Blueprint, g, request, jsonify
from config.commen_config import DISCOUNTS_TYPES
from models.base_model import db
from models.models import AdminMachine, Machine
from utils.error_code import MACHINE_NOT_EXIST_ERROR
from utils.my_response import BaseResponse
logger = logging.getLogger(__name__)
machine_route = Blueprint('machine', __name__)
@machine_route.route("machine_list", methods=["POST"])
def run_machine_list():
"""
:return:
"""
json_data = request.get_json()
page = json_data.get("page", None)
page_size = json_data.get("pageSize", None)
keyword = json_data.get("keyword", None)
admin = g.user
select_sql = """select machine.id, machine.machine_no, machine.device_id, machine.qrcode_no,machine.status,
machine.mac, machine.power, machine.hatch_number, machine.type,machine.place_id,
place.place_name, machine.discounts_id
"""
count_sql = "select count(machine.id) as total_count"
from_sql = """ from machine left join place on machine.place_id = place.id
where machine.machine_no in ( select machine_no from admin_machine where
admin_machine.user_id = {user_id} and admin_machine.status = 1)
""".format(user_id=admin.id)
where_sql = " "
if keyword:
where_sql += """
and CONCAT(machine.machine_no,ifnull(machine.qrcode_no,'')) LIKE '%{keyword}%'
""".format(keyword=keyword)
order_sql = " ORDER BY machine.id ASC, machine.status ASC"
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
if not count_result:
return BaseResponse(data={"list": [], "page": page, "pageSize": page_size, "total_count": 0})
else:
total_count = count_result.total_count
print(select_sql + from_sql + where_sql + order_sql + limit_sql)
result = db.session.execute(select_sql + from_sql + where_sql + order_sql + limit_sql).fetchall()
return_data = []
for info in result:
return_data.append(
{"machine_no": info.machine_no, "device_id": info.device_id, "place_name": info.place_name,
"mac": info.mac, "power": info.power, "hatch_number": info.hatch_number, "type": info.type,
"status": info.status, "place_id": info.place_id,
"discounts_id": info.discounts_id,
"discounts_name": DISCOUNTS_TYPES.get(int(info.discounts_id), "无此优惠"),
})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
@machine_route.route("add_machine", methods=["POST"])
def run_add_machine():
"""
:return:
"""
json_data = request.get_json()
machine_no = json_data["machine_no"]
address = json_data.get("address", None)
device_id = json_data.get("device_id", None)
qrcode_no = json_data.get("qrcode_no", None)
mac = json_data.get("mac", None)
power = json_data.get("power", None)
hatch_number = json_data.get("hatch_number", None)
place_id = json_data.get("place_id", None)
type = json_data.get("type", 1)
discounts_id = json_data.get("type", 0)
machine_model = Machine()
machine_model.machine_no = machine_no
machine_model.device_id = device_id
machine_model.qrcode_no = qrcode_no
machine_model.mac = mac
machine_model.power = power
machine_model.place_id = place_id
machine_model.address = address
machine_model.mch_platform = 1
machine_model.hatch_number = hatch_number
machine_model.type = type
machine_model.discounts_id = discounts_id
db.session.add(machine_model)
admin_machine = AdminMachine()
admin_machine.user_id = g.user.id
admin_machine.user_no = g.user.user_no
admin_machine.machine_no = machine_model.machine_no
db.session.add(admin_machine)
db.session.commit()
return BaseResponse()
@machine_route.route("edit_machine", methods=["POST"])
def run_edit_machine():
"""
:return:
"""
json_data = request.get_json()
machine_no = json_data["machine_no"]
address = json_data.get("address", None)
device_id = json_data.get("device_id", None)
qrcode_no = json_data.get("qrcode_no", None)
mac = json_data.get("mac", None)
power = json_data.get("power", None)
hatch_number = json_data.get("hatch_number", None)
place_id = json_data.get("place_id", None)
type = json_data.get("type", None)
status = json_data.get("status", None)
discounts_id = json_data.get("discounts_id", None)
machine_model = Machine.query.filter_by(machine_no=machine_no).first()
if not machine_model:
return jsonify(MACHINE_NOT_EXIST_ERROR)
if device_id:
machine_model.device_id = device_id
if qrcode_no:
machine_model.qrcode_no = qrcode_no
if mac:
machine_model.mac = mac
if power:
machine_model.power = power
if place_id:
machine_model.place_id = place_id
if address:
machine_model.address = address
if hatch_number:
machine_model.hatch_number = hatch_number
if type:
machine_model.type = type
if status:
machine_model.status = status
if discounts_id:
machine_model.discounts_id = discounts_id
db.session.add(machine_model)
db.session.commit()
return BaseResponse()
@machine_route.route("machine_detail", methods=["POST"])
def get_machine_detail():
"""
:return:
"""
json_data = request.get_json()
machine_no = json_data["machine_no"]
admin = g.user
select_sql = """select machine.id, machine.machine_no, machine.device_id, machine.qrcode_no,machine.status,
machine.mac, machine.power, machine.hatch_number, machine.type,machine.place_id,
place.place_name, machine.discounts_id
"""
from_sql = """ from machine left join place on machine.place_id = place.id
where machine.machine_no in ( select machine_no from admin_machine where
admin_machine.user_id = {user_id} and admin_machine.status = 1)
""".format(user_id=admin.id)
where_sql = " and machine.machine_no = {}".format(machine_no)
result = db.session.execute(select_sql + from_sql + where_sql).fetchall()
if not result or len(result) != 1:
return jsonify(MACHINE_NOT_EXIST_ERROR)
info = result[0]
return BaseResponse(data={"machine_no": info.machine_no, "device_id": info.device_id, "place_name": info.place_name,
"mac": info.mac, "power": info.power, "hatch_number": info.hatch_number,
"type": info.type, "status": info.status, "place_id": info.place_id,
"discounts_id": info.discounts_id,
"discounts_name": DISCOUNTS_TYPES.get(int(info.discounts_id), "无此优惠"),
})
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2022/01/12
@file: place_portal.py
@function:
@modify:
"""
import logging
from flask import Blueprint, g, request, jsonify
from models.base_model import db
from models.models import AdminPlace, Place
from utils.error_code import NO_PLACE_ERROR
from utils.my_response import BaseResponse
logger = logging.getLogger(__name__)
place_route = Blueprint('place', __name__)
@place_route.route("place_list", methods=["POST"])
def run_place_list():
"""
:return:
"""
json_data = request.get_json()
page = json_data.get("page", None)
page_size = json_data.get("pageSize", None)
keyword = json_data.get("keyword", None)
admin = g.user
select_sql = "select place.place_name, place.address, place.parent_id,place.status, place.id "
count_sql = "select count(place.id) as total_count"
from_sql = " from place where place.id in ( select place_id from admin_place where admin_place.user_id = {} and admin_place.status = 1) ".format(
admin.id)
where_sql = " "
if keyword:
where_sql += """
and CONCAT(place.place_name, place.address) LIKE '%{keyword}%'
""".format(keyword=keyword)
order_sql = " ORDER BY place.id ASC, place.status ASC"
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
if not count_result:
return BaseResponse(data={"list": [], "page": page, "pageSize": page_size, "total_count": 0})
else:
total_count = count_result.total_count
result = db.session.execute(select_sql + from_sql + where_sql + order_sql + limit_sql).fetchall()
return_data = []
for info in result:
return_data.append(
{"place_name": info.place_name, "place_id": info.id, "address": info.address, "parent_id": info.parent_id,
"status": info.status
})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
@place_route.route("add_place", methods=["POST"])
def run_add_place():
"""
:return:
"""
json_data = request.get_json()
place_name = json_data["place_name"]
address = json_data.get("address", "")
parent_id = json_data.get("parent_id", 0)
place_model = Place()
place_model.place_name = place_name
place_model.address = address
place_model.parent_id = parent_id
db.session.add(place_model)
db.session.commit()
admin_place = AdminPlace()
admin_place.user_id = g.user.id
admin_place.user_no = g.user.user_no
admin_place.place_id = place_model.id
db.session.add(admin_place)
db.session.commit()
return BaseResponse()
@place_route.route("edit_place", methods=["POST"])
def run_edit_place():
"""
:return:
"""
json_data = request.get_json()
id = json_data["id"]
place_name = json_data.get("place_name", "")
address = json_data.get("address", "")
parent_id = json_data.get("parent_id", 0)
status = json_data.get("status", None)
place_model = Place.query.filter_by(id=id).first()
place_model.place_name = place_name
place_model.address = address
place_model.parent_id = parent_id
place_model.status = status
db.session.add(place_model)
db.session.commit()
return BaseResponse()
@place_route.route("place_detail", methods=["POST"])
def get_place_detail():
"""
:return:
"""
json_data = request.get_json()
id = json_data["id"]
place_model = Place.query.filter_by(id=id).first()
if place_model:
return BaseResponse(data={"place_name": place_model.place_name,
"address": place_model.address,
"parent_id": place_model.parent_id,
"status": place_model.status, })
else:
return jsonify(NO_PLACE_ERROR)
......@@ -6,11 +6,11 @@
"""
import os
import logging
from myapps.sukang24h import create_app
from myapps.automat import create_app
logger = logging.getLogger(__name__)
app = create_app(os.getenv('RUN_ENV', 'prod'))
logger.info("run server")
if __name__ == '__main__':
app.run('127.0.0.1', 8893, debug=False)
app.run('127.0.0.1', 8893, debug=True)
......@@ -13,4 +13,4 @@ app = create_app('prod')
logger.info("run server")
if __name__ == '__main__':
app.run('127.0.0.1', 8893, debug=False)
app.run('127.0.0.1', 8893, debug=True)
#!usr/bin/env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @file: error_code.py """ ### 通用错误相关 Param_Invalid_Error = { "error_code": "500", "error_message": "params is invalid, 参数无效" } TOKEN_NOT_VALID_ERROR = { "error_code": "1001", "error_message": "无效的token" } TOKEN_NOT_PROVIDED_ERROR = { "error_code": "1002", "error_message": "token未提供" } TOKEN_EXPIRE_ERROR = { "error_code": "1003", "error_message": "token超时" } PHONE_NOT_BINDING_ERROR = { "error_code": "1004", "error_message": "未绑定手机号" } PHONE_NOT_NULL_ERROR = { "error_code": "1005", "error_message": "手机号为空" } PHONE_NOT_VALID_ERROR = { "error_code": "1006", "error_message": "无效的手机号" } USER_ALREADY_REGISTER_ERROR = { "error_code": "1007", "error_message": "用户已注册" } VERIFICATION_CODE_NULL_ERROR = { "error_code": "1008", "error_message": "验证码为空" } VERIFICATION_CODE_INVALID_ERROR = { "error_code": "1009", "error_message": "验证码已失效" } VERIFICATION_CODE_ERROR = { "error_code": "1010", "error_message": "验证码错误" } PASSWORD_ERROR = { "error_code": "1011", "error_message": "账号或密码错误" } # 账号相关 12开头 ACCOUNT_ALREADY_EXISTS_ERROR = { "error_code": '1012', "error_message": "该账号已存在" } ACCOUNT_NOT_EXISTS_ERROR = { "error_code": '1013', "error_message": "账号不存在" } ACCOUNT_ALREADY_DELETE_ERROR = { "error_code": '1014', "error_message": "账号已被删除" } ACCOUNT_AGENT_SPOT_NULL_ERROR = { "error_code": '1015', "error_message": "代理商景点列表为空" } AGNET_MODULES_ERROR = { "error_code": '1016', "error_message": "用户未绑定模块" } OPERATE_TYPE_ERROR = { "error_code": '1017', "error_message": "type错误" } OPERATE_LEVEL_ERROR = { "error_code": '1018', "error_message": "权限错误" } OPERATE_ERROR = { "error_code": '1019', "error_message": "操作有误" } MODULES_NOT_EXISTS_ERROR = { "error_code": '1020', "error_message": "modules not exists,模块不存在" } ACCOUNT_AGENT_SPOT_NOT_EXIST = { "error_code": '1021', "error_message": "agent spot not exists,代理景区不存在" } AGENT_MACHINE_NOT_EXIST = { "error_code": '1022', "error_message": "agent machine not exists,代理机柜不存在" } ## 微信登陆相关 WX_LOGIN_DATA_ERROR = { "error_code": "3001", "error_message": "微信登录数据错误" } WX_LOGIN_CODE_ERROR = { "error_code": "3002", "error_message": "微信登录code值错误" } WX_OPENID_NOT_GET_ERROR = { "error_code": "3003", "error_message": "微信OpenId获取失败,请刷新重试" } WX_SESSION_KEY_ERROR = { "error_code": "3004", "error_message": "session key error" } ### 微信支付相关 WE_MINIAPP_PAY_FAIL = { "error_code": "3101", "error_message": "小程序下单失败" } ### 消息推送相关 WXBizMsgCrypt_OK = { "error_code": "0", "error_message": "WXBizMsgCrypt_OK" } WXBizMsgCrypt_ValidateSignature_Error = { "error_code": "4001", "error_message": "验证签名错误" } WXBizMsgCrypt_ParseXml_Error = { "error_code": "4002", "error_message": "解析xml错误" } WXBizMsgCrypt_ComputeSignature_Error = { "error_code": "4003", "error_message": "计算签名错误" } WXBizMsgCrypt_IllegalAesKey = { "error_code": "4004", "error_message": "Aes key非法错误" } WXBizMsgCrypt_ValidateAppid_Error = { "error_code": "4005", "error_message": "appid错误" } WXBizMsgCrypt_EncryptAES_Error = { "error_code": "4006", "error_message": "aes加密错误" } WXBizMsgCrypt_DecryptAES_Error = { "error_code": "4007", "error_message": "aes解密错误" } WXBizMsgCrypt_IllegalBuffer = { "error_code": "4008", "error_message": "illegal buffer" } WXBizMsgCrypt_EncodeBase64_Error = { "error_code": "4009", "error_message": "base64加密错误" } WXBizMsgCrypt_DecodeBase64_Error = { "error_code": "4010", "error_message": "base64解密错误" } WXBizMsgCrypt_GenReturnXml_Error = { "error_code": "4011", "error_message": "gen return xml error" } MACHINE_NOT_EXIST_ERROR = { "error_code": '5001', "error_message": "机柜不存在" } MACHINE_IS_USE_ERROR = { "error_code": '5002', "error_message": "已有他人正在租借中,请稍后" } MACHINE_IS_NOT_ONLINE_ERROR = { "error_code": '5003', "error_message": "机柜不在线" } MACHINE_ADD_ERROR = { "error_code": '5004', "error_message": "机柜添加失败" } MACHINE_NO_DUPLICATE_ERROR = { "error_code": '5005', "error_message": "machine_no duplicate,机柜编号重复" } MACHINE_EDIT_ERROR = { "error_code": '5006', "error_message": "machine edit error, 机柜修改错误" } HATCH_NOT_EXIST_ERROR = { "error_code": "5007", "error_message": "no hatch, 没有商品信息" } HATCH_NOT_ALL_EXIST_ERROR = { "error_code": "5008", "error_message": "no all hatch, 存在已售出商品" } HATCH_COUNT_ERROR = { "error_code": "5009", "error_message": "hatch count error, 商品数量错误,检查数量" } MACHINE_ACTIVATED_ERROR = { "error_code": '5010', "error_message": "machine activated, 机柜已激活" } ### 订单相关 RENT_ORDER_NOT_BACK_ERROR = { "error_code": '6101', "error_message": "有未归还的订单" } RENT_ORDER_NOT_TAKE_ERROR = { "error_code": '6102', "error_message": "有未取货的订单" } RENT_ORDER_NUMBER_MAX = { "error_code": '6103', "error_message": "订单数量达到上限" } TAKE_CODE_NOT_VALID = { "error_code": '6104', "error_message": "取货码错误请确认手机号及取货码是否匹配" } CODE_CANCEL_ERROR = { "error_code": '6105', "error_message": "取货码已取消" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } NO_POWER_ERROR = { "error_code": '6106', "error_message": "没有可租借设备" } NO_RENT_RECORD = { "error_code": '6107', "error_message": "订单不存在" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } RENT_ORDER_NUMBER_LIMIT = { "error_code": '6109', "error_message": "机柜只允许租借一台" } REFUND_NOT_RENT_INFO = { "error_code": "6301", "error_message": "没有该订单信息" } REFUND_BACK_TIME_ERROR = { "error_code": "6302", "error_message": "归还时间异常" } REFUND_NOT_PRODUCTION_INFO = { "error_code": "6303", "error_message": "没有该讲解器信息" } REFUND_MONEY_IS_ZERO = { "error_code": "6304", "error_message": "退款金额为零" } REFUND_NO_DUPLICATE = { "error_code": "6305", "error_message": "退款单号重复" } TALLYMAN_ACCOUNT_EXIST = { "error_code": "7001", "error_message": "tallyman account exist, 补货员账号已存在" } TALLYMAN_ACCOUNT_NOT_EXIST = { "error_code": "7002", "error_message": "tallyman account not exist, 补货员账号不存在" } NFC_CARD_NOT_EXIST = { "error_code": "8001", "error_message": "nfc card not exist, 卡号错误" } NFC_CARD_ACTIVATED_ERROR = { "error_code": "8002", "error_message": "nfc card activated, 卡片已激活" } NO_NFC_CARD_ERROR = { "error_code": "8003", "error_message": "no nfc card , 不存在卡片" } RE_NFC_CARD_ERROR = { "error_code": "8004", "error_message": "re nfc card , 卡片已存在" } NFC_PAY_LOAD_SECRET_ERROR = { "error_code": "8005", "error_message": "secret error , 身份验证失败" } NO_PLACE_ERROR = { "error_code": "9001", "error_message": "no place error,不存在场景" }
\ No newline at end of file
#!usr/bin/env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @file: error_code.py """ ### 通用错误相关 Param_Invalid_Error = { "error_code": "500", "error_message": "params is invalid, 参数无效" } TOKEN_NOT_VALID_ERROR = { "error_code": "1001", "error_message": "无效的token" } TOKEN_NOT_PROVIDED_ERROR = { "error_code": "1002", "error_message": "token未提供" } TOKEN_EXPIRE_ERROR = { "error_code": "1003", "error_message": "token超时" } PHONE_NOT_BINDING_ERROR = { "error_code": "1004", "error_message": "未绑定手机号" } PHONE_NOT_NULL_ERROR = { "error_code": "1005", "error_message": "手机号为空" } PHONE_NOT_VALID_ERROR = { "error_code": "1006", "error_message": "无效的手机号" } USER_ALREADY_REGISTER_ERROR = { "error_code": "1007", "error_message": "用户已注册" } VERIFICATION_CODE_NULL_ERROR = { "error_code": "1008", "error_message": "验证码为空" } VERIFICATION_CODE_INVALID_ERROR = { "error_code": "1009", "error_message": "验证码已失效" } VERIFICATION_CODE_ERROR = { "error_code": "1010", "error_message": "验证码错误" } PASSWORD_ERROR = { "error_code": "1011", "error_message": "账号或密码错误" } # 账号相关 12开头 ACCOUNT_ALREADY_EXISTS_ERROR = { "error_code": '1012', "error_message": "该账号已存在" } ACCOUNT_NOT_EXISTS_ERROR = { "error_code": '1013', "error_message": "账号不存在" } ACCOUNT_ALREADY_DELETE_ERROR = { "error_code": '1014', "error_message": "账号已被删除" } ACCOUNT_AGENT_SPOT_NULL_ERROR = { "error_code": '1015', "error_message": "代理商景点列表为空" } AGNET_MODULES_ERROR = { "error_code": '1016', "error_message": "用户未绑定模块" } OPERATE_TYPE_ERROR = { "error_code": '1017', "error_message": "type错误" } OPERATE_LEVEL_ERROR = { "error_code": '1018', "error_message": "权限错误" } OPERATE_ERROR = { "error_code": '1019', "error_message": "操作有误" } MODULES_NOT_EXISTS_ERROR = { "error_code": '1020', "error_message": "modules not exists,模块不存在" } ACCOUNT_AGENT_SPOT_NOT_EXIST = { "error_code": '1021', "error_message": "agent spot not exists,代理景区不存在" } AGENT_MACHINE_NOT_EXIST = { "error_code": '1022', "error_message": "agent machine not exists,代理机柜不存在" } ## 微信登陆相关 WX_LOGIN_DATA_ERROR = { "error_code": "3001", "error_message": "微信登录数据错误" } WX_LOGIN_CODE_ERROR = { "error_code": "3002", "error_message": "微信登录code值错误" } WX_OPENID_NOT_GET_ERROR = { "error_code": "3003", "error_message": "微信OpenId获取失败,请刷新重试" } WX_SESSION_KEY_ERROR = { "error_code": "3004", "error_message": "session key error" } ### 微信支付相关 WE_MINIAPP_PAY_FAIL = { "error_code": "3101", "error_message": "小程序下单失败" } ### 消息推送相关 WXBizMsgCrypt_OK = { "error_code": "0", "error_message": "WXBizMsgCrypt_OK" } WXBizMsgCrypt_ValidateSignature_Error = { "error_code": "4001", "error_message": "验证签名错误" } WXBizMsgCrypt_ParseXml_Error = { "error_code": "4002", "error_message": "解析xml错误" } WXBizMsgCrypt_ComputeSignature_Error = { "error_code": "4003", "error_message": "计算签名错误" } WXBizMsgCrypt_IllegalAesKey = { "error_code": "4004", "error_message": "Aes key非法错误" } WXBizMsgCrypt_ValidateAppid_Error = { "error_code": "4005", "error_message": "appid错误" } WXBizMsgCrypt_EncryptAES_Error = { "error_code": "4006", "error_message": "aes加密错误" } WXBizMsgCrypt_DecryptAES_Error = { "error_code": "4007", "error_message": "aes解密错误" } WXBizMsgCrypt_IllegalBuffer = { "error_code": "4008", "error_message": "illegal buffer" } WXBizMsgCrypt_EncodeBase64_Error = { "error_code": "4009", "error_message": "base64加密错误" } WXBizMsgCrypt_DecodeBase64_Error = { "error_code": "4010", "error_message": "base64解密错误" } WXBizMsgCrypt_GenReturnXml_Error = { "error_code": "4011", "error_message": "gen return xml error" } MACHINE_NOT_EXIST_ERROR = { "error_code": '5001', "error_message": "机柜不存在" } MACHINE_IS_USE_ERROR = { "error_code": '5002', "error_message": "已有他人正在租借中,请稍后" } MACHINE_IS_NOT_ONLINE_ERROR = { "error_code": '5003', "error_message": "机柜不在线" } MACHINE_ADD_ERROR = { "error_code": '5004', "error_message": "机柜添加失败" } MACHINE_NO_DUPLICATE_ERROR = { "error_code": '5005', "error_message": "machine_no duplicate,机柜编号重复" } MACHINE_EDIT_ERROR = { "error_code": '5006', "error_message": "machine edit error, 机柜修改错误" } HATCH_NOT_EXIST_ERROR = { "error_code": "5007", "error_message": "no hatch, 没有商品信息" } HATCH_NOT_ALL_EXIST_ERROR = { "error_code": "5008", "error_message": "no all hatch, 存在已售出商品" } HATCH_COUNT_ERROR = { "error_code": "5009", "error_message": "hatch count error, 商品数量错误,检查数量" } MACHINE_ACTIVATED_ERROR = { "error_code": '5010', "error_message": "machine activated, 机柜已激活" } MACHINE_NO_CREATE_ERROR = { "error_code": '5011', "error_message": "machine_no create error , 机柜编号生成错误" } MACHINE_MAC_DUPLICATE_ERROR = { "error_code": '5012', "error_message": "machine_mac duplicate,机柜mac重复" } ### 订单相关 RENT_ORDER_NOT_BACK_ERROR = { "error_code": '6101', "error_message": "有未归还的订单" } RENT_ORDER_NOT_TAKE_ERROR = { "error_code": '6102', "error_message": "有未取货的订单" } RENT_ORDER_NUMBER_MAX = { "error_code": '6103', "error_message": "订单数量达到上限" } TAKE_CODE_NOT_VALID = { "error_code": '6104', "error_message": "取货码错误请确认手机号及取货码是否匹配" } CODE_CANCEL_ERROR = { "error_code": '6105', "error_message": "取货码已取消" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } NO_POWER_ERROR = { "error_code": '6106', "error_message": "没有可租借设备" } NO_RENT_RECORD = { "error_code": '6107', "error_message": "订单不存在" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } RENT_ORDER_NUMBER_LIMIT = { "error_code": '6109', "error_message": "机柜只允许租借一台" } REFUND_NOT_RENT_INFO = { "error_code": "6301", "error_message": "没有该订单信息" } REFUND_BACK_TIME_ERROR = { "error_code": "6302", "error_message": "归还时间异常" } REFUND_NOT_PRODUCTION_INFO = { "error_code": "6303", "error_message": "没有该讲解器信息" } REFUND_MONEY_IS_ZERO = { "error_code": "6304", "error_message": "退款金额为零" } REFUND_NO_DUPLICATE = { "error_code": "6305", "error_message": "退款单号重复" } TALLYMAN_ACCOUNT_EXIST = { "error_code": "7001", "error_message": "tallyman account exist, 补货员账号已存在" } TALLYMAN_ACCOUNT_NOT_EXIST = { "error_code": "7002", "error_message": "tallyman account not exist, 补货员账号不存在" } NFC_CARD_NOT_EXIST = { "error_code": "8001", "error_message": "nfc card not exist, 卡号错误" } NFC_CARD_ACTIVATED_ERROR = { "error_code": "8002", "error_message": "nfc card activated, 卡片已激活" } NO_NFC_CARD_ERROR = { "error_code": "8003", "error_message": "no nfc card , 不存在卡片" } RE_NFC_CARD_ERROR = { "error_code": "8004", "error_message": "re nfc card , 卡片已存在" } NFC_PAY_LOAD_SECRET_ERROR = { "error_code": "8005", "error_message": "secret error , 身份验证失败" } NO_PLACE_ERROR = { "error_code": "9001", "error_message": "no place error,不存在场景" } # COMMON_MONGO_ERROR = { "error_code": 5001, "error_message": "mongodb operation error, mongodb操作错误" }
\ No newline at end of file
......
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/30 @file: jwt_util.py @function: @modify: """ import jwt from flask import current_app def generate_jwt(payload, expiry, secret=None): """ 生成jwt :param payload: dict 载荷 :param expiry: datetime 有效期 :param secret: 密钥 :return: jwt """ _payload = {'exp': expiry} _payload.update(payload) if not secret: secret = current_app.config['SECRET_KEY'] token = jwt.encode(_payload, secret, algorithm='HS256') return token def verify_jwt(token, secret=None): """ 检验jwt :param token: jwt :param secret: 密钥 :return: dict: payload """ if not secret: secret = current_app.config['SECRET_KEY'] try: payload = jwt.decode(token, secret, algorithms=['HS256']) except jwt.PyJWTError: payload = None return payload if __name__ == '__main__': import time from config.env_path_config import env_path from dotenv import load_dotenv load_dotenv(dotenv_path=env_path, verbose=True, override=True) import os SECRET_KEY = os.getenv('SECRET_KEY') token = generate_jwt({"user_id": 1}, time.time() + 6000, SECRET_KEY) # token = generate_jwt({"user_no": 'SK000007'}, time.time() + 6000, SECRET_KEY) print(token) # for i in range(10): # result = verify_jwt(token, 'secret') # print(result) # print(time.time()) # time.sleep(1)
\ No newline at end of file
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/30 @file: jwt_util.py @function: @modify: """ import jwt from flask import current_app def generate_jwt(payload, expiry, secret=None): """ 生成jwt :param payload: dict 载荷 :param expiry: datetime 有效期 :param secret: 密钥 :return: jwt """ _payload = {'exp': expiry} _payload.update(payload) if not secret: secret = current_app.config['SECRET_KEY'] token = jwt.encode(_payload, secret, algorithm='HS256') return token def verify_jwt(token, secret=None): """ 检验jwt :param token: jwt :param secret: 密钥 :return: dict: payload """ if not secret: secret = current_app.config['SECRET_KEY'] try: payload = jwt.decode(token, secret, algorithms=['HS256']) except jwt.PyJWTError: payload = None return payload if __name__ == '__main__': import time from config.env_path_config import env_path from dotenv import load_dotenv load_dotenv(dotenv_path=env_path, verbose=True, override=True) import os SECRET_KEY = os.getenv('SECRET_KEY') token = generate_jwt({"user_id": 4}, time.time() + 6000, SECRET_KEY) # token = generate_jwt({"user_no": 'SK000007'}, time.time() + 6000, SECRET_KEY) print(token) # for i in range(10): # result = verify_jwt(token, 'secret') # print(result) # print(time.time()) # time.sleep(1)
\ No newline at end of file
......
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/26 @file: middlewares.py @function: @modify: """ import logging from flask import g, request, url_for, current_app, make_response, jsonify from config.wechat_config import platform_config_list from models.models import WxUser, TallymanAccount, AdminAccount from utils.error_code import TOKEN_NOT_VALID_ERROR from utils.my_response import BaseResponse from utils.jwt_util import verify_jwt logger = logging.getLogger(__name__) def log_enter_interface(): """ 日志打印进入接口 :return: """ logger.info("######################### 进入 {} 接口 ################################ ".format(request.path)) def log_out_interface(environ): """ 日志打印退出接口 :return: """ logger.info("######################### 退出 {} 接口 ################################\n".format(request.path)) return environ def close_db_session(environ): from models.base_model import db db.session.close() return environ """用户认证机制==>每次请求前获取并校验token""" "@myapps.before_request 不使@调用装饰器 在 init文件直接装饰" def jwt_authentication(): """ 1.获取请求头Authorization中的token 2.判断是否以 Bearer开头 3.使用jwt模块进行校验 4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存 """ path_list = request.path.split("/") if current_app.name == "sukang24h": NO_AUTH_CHECK_URL = [url_for('wx_auth.my_test'), url_for('wx_auth.mini_login'), url_for('rent.wx_pay_callback'), url_for('hatch.get_production_list'), url_for('tallyman.run_tallyman_login'), url_for('machine.run_get_machine_no'), url_for('nfc_card.run_nfc_card_wx_pay_callback'), url_for('nfc_card.run_nfc_card_user_pay_record'), url_for('nfc_card.run_nfc_card_load_succeed'), url_for('nfc_card.run_nfc_card_user_load_record'), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" if request.path.split("/")[2] == "tallyman": user_no = payload.get('user_no') if not user_no: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) if request.path.split("/")[2] == "machine": user_no = payload.get('user_no', None) user_id = payload.get('user_id', None) if user_no: try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) if user_id: try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) return BaseResponse(**TOKEN_NOT_VALID_ERROR) user_id = payload.get('user_id') if not user_id: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: return BaseResponse(**TOKEN_NOT_VALID_ERROR) elif current_app.name == "pc_management": NO_AUTH_CHECK_URL = [url_for("admin.user_login"), url_for("admin.send_code"), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" user_id = payload.get('user_id', None) if user_id: g.user = AdminAccount.query.filter_by(id=user_id).first() if g.user: return return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: NO_AUTH_CHECK_URL = [] return def get_platform(): """ :return: """ g.platform = request.headers.get('platform', "sukang24h") def all_options_pass(): """ :return: """ if request.method == "OPTIONS": headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , platform', } return make_response((jsonify({'error_code': 0}), 200, headers))
\ No newline at end of file
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/26 @file: middlewares.py @function: @modify: """ import logging from flask import g, request, url_for, current_app, make_response, jsonify from config.wechat_config import platform_config_list from models.models import WxUser, TallymanAccount, AdminAccount from utils.error_code import TOKEN_NOT_VALID_ERROR from utils.my_response import BaseResponse from utils.jwt_util import verify_jwt logger = logging.getLogger(__name__) def log_enter_interface(): """ 日志打印进入接口 :return: """ logger.info("######################### 进入 {} 接口 ################################ ".format(request.path)) def log_out_interface(environ): """ 日志打印退出接口 :return: """ logger.info("######################### 退出 {} 接口 ################################\n".format(request.path)) return environ def close_db_session(environ): from models.base_model import db db.session.close() return environ """用户认证机制==>每次请求前获取并校验token""" "@myapps.before_request 不使@调用装饰器 在 init文件直接装饰" def jwt_authentication(): """ 1.获取请求头Authorization中的token 2.判断是否以 Bearer开头 3.使用jwt模块进行校验 4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存 """ path_list = request.path.split("/") if current_app.name == "automat": NO_AUTH_CHECK_URL = [url_for('wx_auth.my_test'), url_for('wx_auth.mini_login'), url_for('rent.wx_pay_callback'), url_for('hatch.get_production_list'), url_for('tallyman.run_tallyman_login'), url_for('machine.run_get_machine_no'), url_for('machine.run_create_machine_no'), url_for('machine.run_bind_serial_num'), url_for('nfc_card.run_nfc_card_wx_pay_callback'), url_for('nfc_card.run_nfc_card_user_pay_record'), url_for('nfc_card.run_nfc_card_load_succeed'), url_for('nfc_card.run_nfc_card_user_load_record'), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" if request.path.split("/")[2] == "tallyman": user_no = payload.get('user_no') if not user_no: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) if request.path.split("/")[2] == "machine": user_no = payload.get('user_no', None) user_id = payload.get('user_id', None) if user_no: try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) if user_id: try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) return BaseResponse(**TOKEN_NOT_VALID_ERROR) user_id = payload.get('user_id') if not user_id: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: return BaseResponse(**TOKEN_NOT_VALID_ERROR) elif current_app.name == "pc_management": NO_AUTH_CHECK_URL = [url_for("admin.user_login"), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" user_id = payload.get('user_id', None) if user_id: g.user = AdminAccount.query.filter_by(id=user_id).first() if g.user: return return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: NO_AUTH_CHECK_URL = [] return def get_platform(): """ :return: """ g.platform = request.headers.get('platform', "sukang24h") def all_options_pass(): """ :return: """ if request.method == "OPTIONS": headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , platform', } return make_response((jsonify({'error_code': 0}), 200, headers))
\ No newline at end of file
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment