Commit 2d1c01b2 by Aeolus

Merge branch 'aeolus'

parents deb0e035 8b3f4d93
......@@ -24,6 +24,7 @@ class Config:
JWT_SECRET = SECRET_KEY
TENCENT_REDIS_URL = os.getenv("TENCENT_REDIS_URL")
MAX_CONTENT_LENGTH = 16 * 1024 * 1024
# SQLALCHEMY_ECHO = True
@staticmethod
def init_app(app):
......
......@@ -43,15 +43,13 @@ LOGIN_TYPE = {
AGENT_STATUS = {
'1': '超级管理员',
'2': '出库员',
'3': '渠道经理',
'4': '财务',
'5': '运维管理员',
'6': '推销员',
'7': '介绍人',
'8': '合伙人',
'9': '补货员',
'10': '场所',
'2': '管理员',
'3': '业务员',
'4': '商户管理员',
'5': '商户管理员',
'6': '财务',
'7': '运维管理员',
'8': '客服',
}
ACCOUNT_STATUS = {
......
......@@ -39,12 +39,12 @@ def get_production_list():
"machine_no": i.machine_no,
"hatch_no": [i.hatch_no],
"production_id": i.production_id,
"name": i.name,
"name": i.production_name,
"title": i.title,
"brand_id": i.brand_id,
"brand_name": i.brand_name,
"cate_id": i.cate_id,
"cate_name": i.cate_name,
"production_type_id": i.production_type_id,
"production_type_name": i.production_type_name,
"price": i.price,
"original_price": i.original_price,
"img": i.img,
......@@ -79,12 +79,12 @@ def get_production_info():
"machine_no": hatch_info.machine_no,
"hatch_no": hatch_info.hatch_no,
"production_id": hatch_info.production_id,
"name": hatch_info.name,
"name": hatch_info.production_name,
"title": hatch_info.title,
"brand_id": hatch_info.brand_id,
"brand_name": hatch_info.brand_name,
"cate_id": hatch_info.cate_id,
"cate_name": hatch_info.cate_name,
"production_type_id": hatch_info.production_type_id,
"production_type_name": hatch_info.production_type_name,
"price": hatch_info.price,
"original_price": hatch_info.original_price,
"img": hatch_info.img,
......
......@@ -40,6 +40,7 @@ def get_discount_info():
machine = Machine.query.filter_by(machine_no=machine_no).first()
if not machine:
return jsonify(MACHINE_NOT_EXIST_ERROR)
is_used = 1
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:
......@@ -82,7 +83,6 @@ def create_rent():
Hatch.left_count >= 1).order_by(func.random()).first()
if not open_hatch:
print("....")
return jsonify(HATCH_NOT_EXIST_ERROR)
break
......@@ -93,11 +93,13 @@ def create_rent():
rent.user_id = g.user.id
rent.place_id = machine.place_id
rent.total = total_fee
rent.real_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.place_id = machine.place_id
rent_detail = RentDetail()
rent_detail.rent_no = rent_no
......@@ -105,13 +107,15 @@ def create_rent():
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.production_name = open_hatch.production_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.production_type_id = open_hatch.production_type_id
rent_detail.production_type_name = open_hatch.production_type_name
rent_detail.price = 0
rent_detail.original_price = open_hatch.original_price
rent_detail.total = 0
rent_detail.rent_count = 1
rent_detail.img = open_hatch.img
rent_detail.tags = open_hatch.tags
......@@ -211,7 +215,6 @@ def wx_pay_callback():
logger.info(xml_data)
logger.info(callback_data)
attach = re.sub('\'', '\"', callback_data["attach"])
print(attach)
rent_data = json.loads(attach)
platform = rent_data["platform"]
machine_no = rent_data["machine_no"]
......@@ -261,13 +264,14 @@ def wx_pay_callback():
rent_detail.machine_no = rent.machine_no
rent_detail.hatch_no = i.hatch_no
rent_detail.production_id = i.production_id
rent_detail.name = i.name
rent_detail.production_name = i.production_name
rent_detail.title = i.title
rent_detail.brand_id = i.brand_id
rent_detail.brand_name = i.brand_name
rent_detail.cate_id = i.cate_id
rent_detail.cate_name = i.cate_name
rent_detail.price = i.price * open_hatchs[str(i.hatch_no)]
rent_detail.production_type_id = i.production_type_id
rent_detail.production_type_name = i.production_type_name
rent_detail.price = i.price
rent_detail.total = i.price * open_hatchs[str(i.hatch_no)]
rent_detail.rent_count = open_hatchs[str(i.hatch_no)]
rent_detail.img = i.img
rent_detail.tags = i.tags
......@@ -317,13 +321,17 @@ def get_rent_detail():
tmp_data["hatch_no"] = i.hatch_no
tmp_data["production_id"] = i.production_id
tmp_data["is_take"] = i.is_take
tmp_data["name"] = i.name
tmp_data["name"] = i.production_name
tmp_data["title"] = i.title
tmp_data["brand_id"] = i.brand_id
tmp_data["brand_name"] = i.brand_name
tmp_data["cate_id"] = i.cate_id
tmp_data["cate_name"] = i.cate_name
tmp_data["production_type_id"] = i.production_type_id
tmp_data["production_type_name"] = i.production_type_name
tmp_data["price"] = i.price
tmp_data["total"] = i.total
tmp_data["rent_count"] = i.rent_count
tmp_data["refund_total"] = i.refund_total
tmp_data["refund_count"] = i.refund_count
tmp_data["img"] = i.img
tmp_data["tags"] = i.tags
tmp_data["content"] = i.content
......@@ -359,9 +367,13 @@ def get_user_detail_record():
tmp_data["title"] = i.title
tmp_data["brand_id"] = i.brand_id
tmp_data["brand_name"] = i.brand_name
tmp_data["cate_id"] = i.cate_id
tmp_data["cate_name"] = i.cate_name
tmp_data["production_type_id"] = i.production_type_id
tmp_data["production_type_name"] = i.production_type_name
tmp_data["price"] = i.price
tmp_data["total"] = i.total
tmp_data["rent_count"] = i.rent_count
tmp_data["refund_total"] = i.refund_total
tmp_data["refund_count"] = i.refund_count
tmp_data["img"] = i.img
tmp_data["tags"] = i.tags
tmp_data["content"] = i.content
......
......@@ -16,6 +16,10 @@ from myapps.pc_management.api.place_portal import place_route
from myapps.pc_management.api.machine_portal import machine_route
from myapps.pc_management.api.file_protal import file_route
from myapps.pc_management.api.production_portal import production_route
from myapps.pc_management.api.hatch_portal import hatch_route
from myapps.pc_management.api.business_portal import business_route
from myapps.pc_management.api.rent_portal import rent_route
from myapps.pc_management.api.tallyman_portal import tallyman_route
def register_sukang_blueprint(app: Flask):
......@@ -25,3 +29,7 @@ def register_sukang_blueprint(app: Flask):
app.register_blueprint(machine_route, url_prefix=prefix + "/machine")
app.register_blueprint(file_route, url_prefix=prefix + "/file")
app.register_blueprint(production_route, url_prefix=prefix + "/production")
app.register_blueprint(hatch_route, url_prefix=prefix + "/hatch")
app.register_blueprint(business_route, url_prefix=prefix + "/business")
app.register_blueprint(rent_route, url_prefix=prefix + "/rent")
app.register_blueprint(tallyman_route, url_prefix=prefix + "/tallyman")
......@@ -13,11 +13,12 @@ from utils.error_code import ACCOUNT_AGENT_SPOT_NULL_ERROR, ACCOUNT_NOT_EXISTS_E
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, AdminPlace, Place
from models.base_model import db, Base
from models.models import AdminAccount, AdminLoginRecord, AdminMachine, AdminPlace, Place, Business, AdminBusiness
from utils.jwt_util import verify_jwt, generate_jwt
from utils.my_response import BaseResponse
from service.sms_service import SMSService
from utils.mytools import json2obj
logger = logging.getLogger(__name__)
......@@ -141,6 +142,10 @@ def add_user():
db.session.add(account)
db.session.commit()
business_ids = json_data.get("business_ids", [])
if business_ids:
AdminService.add_or_edit_admin_business(account, business_ids)
return BaseResponse()
......@@ -151,45 +156,9 @@ def get_account_list():
page_size = json_data.get("pageSize", None)
keyword = json_data.get("keyword", None)
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(admin_account.id) as total_count"
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(admin_account.user_name,admin_account.phone, admin_account.user_no) LIKE '%{keyword}%'
""".format(keyword=keyword)
where_sql += " ) "
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()
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(
{"user_name": info.user_name, "phone": info.phone, "level": info.level, "status": info.status,
"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_data = AdminService.get_admin_account_list(keyword=keyword, page=page, page_size=page_size)
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
return BaseResponse(return_data)
@admin_route.route('/account_detail', methods=["POST"])
......@@ -199,14 +168,13 @@ def get_account_detail():
if phone == g.user.phone:
admin_info = g.user
else:
admin_info = AdminAccount.query.filter(AdminAccount.phone == phone,
AdminAccount.level > g.user.level,
AdminAccount.parent_id == g.user.id).first()
if not admin_info:
result = AdminService.get_admin_account_list(phone=phone)
if result["total_count"] != 1:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
admin_info = json2obj(result["list"][0])
user_info = {
"user_id": admin_info.id,
"id": admin_info.id,
"user_no": admin_info.user_no,
"user_name": admin_info.user_name,
"phone": admin_info.phone,
......@@ -215,6 +183,13 @@ def get_account_detail():
"comment": admin_info.comment
}
business_list = db.session.query(Business).join(AdminBusiness, Business.id == AdminBusiness.business_id,
).filter(Business.status == 1,
AdminBusiness.user_id == admin_info.id,
AdminBusiness.status == 1).all()
user_info["business_list"] = []
for i in business_list:
user_info["business_list"].append({"business_id": i.id, "business_name": i.business_name})
return BaseResponse(data=user_info)
......@@ -223,7 +198,7 @@ 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['user_name'] if 'user_name' in json_data else 'SSW'
user_name = json_data['user_name'] if 'user_name' in json_data else 'XX'
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 ''
......@@ -239,26 +214,34 @@ def edit_user():
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()
result = AdminService.get_admin_account_list(phone=old_phone)
if result["total_count"] != 1:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
admin = json2obj(result["list"][0])
admin_info = AdminAccount.query.filter_by(id=admin.id).first()
if not admin_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
admin_info.user_name = user_name
admin_info.phone = new_phone
if level and level > g.user.level:
admin_info.level = level
if status:
admin_info.status = status
if comment:
admin_info.comment = comment
if user_name:
admin_info.user_name = user_name
if new_phone:
admin_info.phone = new_phone
if password:
admin_info.password = password
db.session.add(admin_info)
db.session.commit()
business_ids = json_data.get("business_ids", [])
if business_ids:
AdminService.add_or_edit_admin_business(admin_info, business_ids)
return BaseResponse()
......@@ -269,8 +252,11 @@ def delete_user():
if not phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
admin_info = AdminAccount.query.filter(AdminAccount.phone == phone,
AdminAccount.level > g.user.level).first()
result = AdminService.get_admin_account_list(phone=phone)
if result["total_count"] != 1:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
admin = json2obj(result["list"][0])
admin_info = AdminAccount.query.filter_by(id=admin.id).first()
if not admin_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
......
#!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, Business, AdminBusiness
from utils.error_code import NO_PLACE_ERROR, NO_BUSINESS_ERROR
from utils.my_response import BaseResponse
logger = logging.getLogger(__name__)
business_route = Blueprint('business', __name__)
@business_route.route("business_list", methods=["POST"])
def run_business_list():
"""
:return:
"""
json_data = request.get_json()
page = json_data.get("page", 1)
page_size = json_data.get("pageSize", 10)
keyword = json_data.get("keyword", None)
admin = g.user
select_sql = "select business.business_name,business.status, business.id "
count_sql = "select count(business.id) as total_count"
from_sql = """ from business """
if g.user.level == 1:
where_sql = " where 0=0 "
else:
where_sql = """ where business.id in (
select business_id from admin_business where
admin_business.user_id = {} and admin_business.status = 1
)""".format(admin.id)
if keyword:
where_sql += """ and CONCAT(business.business_name) LIKE '%{keyword}%' """.format(keyword=keyword)
order_sql = " ORDER BY business.id ASC, business.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({"business_name": info.business_name, "business_id": info.id, "status": info.status})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
@business_route.route("add_business", methods=["POST"])
def run_add_place():
"""
:return:
"""
json_data = request.get_json()
business_name = json_data["business_name"]
business_model = Business()
business_model.business_name = business_name
db.session.add(business_model)
db.session.commit()
admin_business = AdminBusiness()
admin_business.user_id = g.user.id
admin_business.user_no = g.user.user_no
admin_business.business_id = business_model.id
db.session.add(admin_business)
db.session.commit()
return BaseResponse()
@business_route.route("edit_business", methods=["POST"])
def run_edit_business():
"""
:return:
"""
json_data = request.get_json()
business_id = json_data["business_id"]
business_name = json_data.get("business_name", "")
status = json_data.get("status", None)
business_model = Business.query.filter_by(id=business_id).first()
if business_name:
business_model.business_name = business_name
if status:
business_model.status = status
db.session.add(business_model)
db.session.commit()
return BaseResponse()
@business_route.route("business_detail", methods=["POST"])
def get_business_detail():
"""
:return:
"""
json_data = request.get_json()
business_id = json_data["business_id"]
business_model = Business.query.filter_by(id=business_id).first()
if business_model:
return BaseResponse(data={"business_name": business_model.business_name,
"status": business_model.status, "business_id": business_id})
else:
return jsonify(NO_BUSINESS_ERROR)
......@@ -33,7 +33,6 @@ def run_upload_img():
if filetype and filetype in ALLOWED_EXTENSIONS: # 后缀格式必须是bmp结尾
uid = uuid.uuid4() # 生成随机名称
save_file_name = str(uid) + "." + filetype # 拼接名称
print(os.path.join(img_file_path, filename))
file.save(os.path.join(img_file_path, save_file_name)) # 保存文件
return BaseResponse(data={"filename": save_file_name})
......
......@@ -14,9 +14,11 @@ 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 models.models import AdminMachine, Machine, AdminAccount, AdminBusiness, TallymanMachine
from service.admin_service import AdminService
from utils.error_code import MACHINE_NOT_EXIST_ERROR, ACCOUNT_NOT_EXISTS_ERROR, ADMIN_BUSINESS_NOT_EXIST
from utils.my_response import BaseResponse
from utils.mytools import json2obj
logger = logging.getLogger(__name__)
......@@ -30,17 +32,19 @@ def run_machine_list():
:return:
"""
json_data = request.get_json()
page = json_data.get("page", None)
page_size = json_data.get("pageSize", None)
page = json_data.get("page", 1)
page_size = json_data.get("pageSize", 10)
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
place.place_name, machine.discounts_id, machine.business_id,business.business_name
"""
count_sql = "select count(machine.id) as total_count"
from_sql = """ from machine left join place on machine.place_id = place.id
from_sql = """ from machine
left join place on machine.place_id = place.id
left join business on machine.business_id = business.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)
......@@ -60,7 +64,6 @@ def run_machine_list():
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 = []
......@@ -71,6 +74,7 @@ def run_machine_list():
"status": info.status, "place_id": info.place_id,
"discounts_id": info.discounts_id,
"discounts_name": DISCOUNTS_TYPES.get(int(info.discounts_id), "无此优惠"),
"business_id": info.business_id, "business_name": info.business_name
})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
......@@ -179,9 +183,11 @@ def get_machine_detail():
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
place.place_name, machine.discounts_id,machine.business_id,business.business_name
"""
from_sql = """ from machine left join place on machine.place_id = place.id
from_sql = """ from machine
left join place on machine.place_id = place.id
left join business on machine.business_id = business.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)
......@@ -198,5 +204,81 @@ def get_machine_detail():
"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), "无此优惠"),
"business_id": info.business_id, "business_name": info.business_name
})
@machine_route.route("distribute_machine", methods=["POST"])
def run_distribute_machine():
"""
:return:
"""
json_data = request.get_json()
machine_nos = json_data["machine_nos"]
user_id = json_data["user_id"]
business_id = json_data["business_id"]
result = AdminService.get_admin_account_list(user_id=user_id)
if result["total_count"] != 1:
return jsonify(ACCOUNT_NOT_EXISTS_ERROR)
admin_info = json2obj(result["list"][0])
admin_business = AdminBusiness.query.filter_by(user_id=g.user.id, business_id=business_id, status=1).first()
if not admin_business:
return jsonify(ADMIN_BUSINESS_NOT_EXIST)
return_machine_no = []
for i in machine_nos:
admin_machines = AdminMachine.query.filter_by(user_id=g.user.id, machine_no=i, status=1).first()
if not admin_machines:
continue
machine = Machine.query.filter_by(machine_no=i).first()
if not machine:
continue
insert_sql = " insert into admin_machine (user_id, user_no, machine_no) values "
insert_sql += "('{}','{}','{}'),".format(admin_info.id, admin_info.user_no, i)
insert_sql = insert_sql[:-1]
insert_sql += " ON DUPLICATE KEY UPDATE status = 1"
db.session.execute(insert_sql)
if admin_info.level == 4:
machine.business_id = business_id
db.session.commit()
return_machine_no.append(i)
return BaseResponse(data={"add_machine_nos": return_machine_no})
@machine_route.route("distribute_tallyman_machine", methods=["POST"])
def run_distribute_tallyman_machine():
"""
:return:
"""
json_data = request.get_json()
machine_nos = json_data["machine_nos"]
user_id = json_data["user_id"]
result = AdminService.get_tallyman_account_list(user_id=user_id)
if result["total_count"] != 1:
return jsonify(ACCOUNT_NOT_EXISTS_ERROR)
admin_info = json2obj(result["list"][0])
return_machine_no = []
for i in machine_nos:
admin_machines = AdminMachine.query.filter_by(user_id=g.user.id, machine_no=i, status=1).first()
if not admin_machines:
continue
machine = Machine.query.filter_by(machine_no=i).first()
if not machine:
continue
insert_sql = " insert into tallyman_machine (user_id, machine_no) values "
insert_sql += "('{}','{}'),".format(admin_info.id, i)
insert_sql = insert_sql[:-1]
insert_sql += " ON DUPLICATE KEY UPDATE status = 1"
db.session.execute(insert_sql)
db.session.commit()
return_machine_no.append(i)
return BaseResponse(data={"add_machine_nos": return_machine_no})
......@@ -77,7 +77,7 @@ def run_production_list():
return_data = []
for info in result:
return_data.append(
{"production_name": info.production_name, "prodcution_id": info.id, "production_no": info.production_no,
{"production_name": info.production_name, "production_id": info.id, "production_no": info.production_no,
"title": info.title, "brand_id": info.brand_id, "brand_name": info.brand_name,
"production_type_id": info.production_type_id, "production_type_name": info.production_type_name,
"price": info.price, "original_price": info.original_price, "weight": info.weight,
......@@ -248,7 +248,7 @@ def get_production_detail():
info = result[0]
return BaseResponse(
data={"production_name": info.production_name, "prodcution_id": info.id, "production_no": info.production_no,
data={"production_name": info.production_name, "production_id": info.id, "production_no": info.production_no,
"title": info.title, "brand_id": info.brand_id, "brand_name": info.brand_name,
"production_type_id": info.production_type_id, "production_type_name": info.production_type_name,
"price": info.price, "original_price": info.original_price, "weight": info.weight,
......@@ -370,7 +370,7 @@ def get_brand_detail():
brand_id = json_data["brand_id"]
admin = g.user
select_sql = """select b.id,b.brand_name,b.status
select_sql = """select b.id,b.brand_name,b.status, b.img
"""
from_sql = """ from brand b """
......@@ -384,7 +384,7 @@ def get_brand_detail():
return BaseResponse(
data={"brand_id": info.id, "brand_name": info.brand_name,
"status": info.status,
"status": info.status, "img": info.img
})
......
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2022/01/12
@file: place_portal.py
@function:
@modify:
"""
import datetime
import logging
from flask import Blueprint, g, request, jsonify
from models.base_model import db
from models.models import AdminPlace, Place, TallymanMachine, Machine, TallymanAccount
from service.admin_service import AdminService
from utils.error_code import NO_PLACE_ERROR, TALLYMAN_ACCOUNT_NOT_EXIST, TALLYMAN_ACCOUNT_EXIST, OPERATE_LEVEL_ERROR, \
ACCOUNT_NOT_EXISTS_ERROR
from utils.my_response import BaseResponse
from utils.mytools import json2obj
logger = logging.getLogger(__name__)
tallyman_route = Blueprint('tallyman', __name__)
@tallyman_route.route('/tallyman_list', methods=["POST"])
def get_account_list():
json_data = request.get_json()
page = json_data.get("page", 1)
page_size = json_data.get("pageSize", 10)
keyword = json_data.get("keyword", None)
return_data = AdminService.get_tallyman_account_list(keyword=keyword, page=page, page_size=page_size)
return BaseResponse(return_data)
@tallyman_route.route('/edit_tallyman_account', methods=['GET', 'POST'])
def run_tallyman_edit_account():
admin = g.user
if g.user.level not in (1, 2, 4):
return jsonify(OPERATE_LEVEL_ERROR)
json_data = request.get_json()
old_phone = json_data['old_phone']
new_phone = json_data.get('new_phone', None)
user_name = json_data.get('user_name', None)
password = json_data.get('password', None)
business_id = json_data.get('business_id', None)
status = json_data.get('status', None)
tallyman_info = TallymanAccount.query.filter_by(phone=old_phone).first()
if not tallyman_info:
return jsonify(TALLYMAN_ACCOUNT_NOT_EXIST)
if new_phone:
tallyman_info.phone = new_phone
if user_name:
tallyman_info.user_name = user_name
if password:
tallyman_info.password = password
if status:
tallyman_info.status = status
if business_id:
tallyman_info.business_id = business_id
db.session.add(tallyman_info)
db.session.commit()
return BaseResponse()
@tallyman_route.route('/add_tallyman_account', methods=['GET', 'POST'])
def run_add_tallyman_account():
admin = g.user
if g.user.level not in (1, 2, 4):
return jsonify(OPERATE_LEVEL_ERROR)
json_data = request.get_json()
user_name = json_data['user_name'] if 'user_name' in json_data else 'SSW'
phone = json_data['phone'] if 'phone' in json_data else None
level = int(json_data['level']) if 'level' in json_data else 2
password = json_data['password'] if 'password' in json_data else None
comment = json_data['comment'] if 'comment' in json_data else ''
business_id = json_data["business_id"]
tallyman = TallymanAccount.query.filter_by(phone=phone).first()
if tallyman:
if tallyman.status != -1:
return jsonify(TALLYMAN_ACCOUNT_EXIST)
else:
tallyman = TallymanAccount()
tallyman.user_no = "todo"
tallyman.user_name = user_name
tallyman.phone = phone
tallyman.level = level
tallyman.business_id = business_id
tallyman.status = 1
tallyman.comment = comment
tallyman.created_at = datetime.datetime.now()
tallyman.updated_at = datetime.datetime.now()
if password:
tallyman.password = password
db.session.add(tallyman)
db.session.commit()
tallyman.user_no = "XXTM" + str(tallyman.id).zfill(6)
db.session.add(tallyman)
db.session.commit()
return BaseResponse()
@tallyman_route.route('/delete_tallyman_account', methods=['GET', 'POST'])
def run_delete_tallyman_account():
json_data = request.get_json()
if g.user.level not in (1, 2, 4):
return jsonify(OPERATE_LEVEL_ERROR)
phone = json_data['phone']
tallyman = TallymanAccount.query.filter_by(phone=phone).first()
if not tallyman:
return BaseResponse()
tallyman.status = -1
db.session.add(tallyman)
tallyman_machine_info = TallymanMachine.query.filter_by(user_id=tallyman.id).all()
for info in tallyman_machine_info:
info.status = -1
db.session.add(info)
db.session.commit()
return BaseResponse()
@tallyman_route.route('/tallyman_account_detail', methods=["POST"])
def get_tallyman_account_detail():
json_data = request.get_json()
if g.user.level not in (1, 2, 4):
return jsonify(OPERATE_LEVEL_ERROR)
phone = json_data["phone"]
if phone == g.user.phone:
admin_info = g.user
else:
result = AdminService.get_tallyman_account_list(phone=phone)
if result["total_count"] != 1:
return BaseResponse(ACCOUNT_NOT_EXISTS_ERROR)
admin_info = json2obj(result["list"][0])
user_info = {
"id": admin_info.id,
"user_no": admin_info.user_no,
"user_name": admin_info.user_name,
"phone": admin_info.phone,
"level": admin_info.level,
"business_id": admin_info.business_id,
"status": admin_info.status,
"comment": admin_info.comment
}
return BaseResponse(data=user_info)
......@@ -5,98 +5,174 @@ import hashlib
import random
import string
from flask import g
from config.commen_config import ACCOUNT_STATUS
from models.models import AdminAccount
from models.models import AdminAccount, Business, AdminBusiness
from models.base_model import db
from models.models import Place
# from models.user_models import AgentAccount
# from service.spot_service import SpotService
class AdminService():
@staticmethod
def gene_salt(length=16):
key_list = [random.choice((string.ascii_letters + string.digits)) for i in range(length)]
return ("".join(key_list))
class AdminService(object):
@staticmethod
def gene_agent_code(agent_info, salt):
def get_business_id_list():
"""
:param agent_info:
:param salt:
:param business_ids:
:return:
"""
m = hashlib.md5()
str = "%s-%s-%s-%s" % (agent_info.id, agent_info.user_name, agent_info.phone, salt)
m.update(str.encode("utf-8"))
return m.hexdigest()
@staticmethod
def gene_pwd(pwd, salt):
"""
if g.user.level == 1:
business_list = Business.query.filter().all()
if business_list:
business_id_list = [i.id for i in business_list]
else:
business_id_list = []
:param pwd:
:param salt:
:return:
"""
m = hashlib.md5()
str = "%s-%s" % (base64.encodebytes(pwd.encode("utf-8")), salt)
m.update(str.encode("utf-8"))
return m.hexdigest()
else:
admin_business_list = AdminBusiness.query.filter_by(user_id=g.user.id, status=1).all()
if admin_business_list:
business_id_list = [i.business_id for i in admin_business_list]
else:
business_id_list = []
return business_id_list
@staticmethod
def check_agent_token(token):
def add_or_edit_admin_business(admin_account, business_ids):
"""
:param token:
:param business_ids:
:return:
"""
token = base64.b64decode(token).decode("utf-8")
try:
agent_info = AgentAccount.query.filter_by(access_token=token).first()
except Exception as e:
return 1
if not agent_info:
return 1
my_business_id_list = AdminService.get_business_id_list()
right_busines_ids = list(set(business_ids).intersection(set(my_business_id_list)))
s = token.split("#")
if len(s) != 2:
return 1
if AgentService.gene_agent_code(agent_info, agent_info.salt) != s[0]:
return 1
if agent_info.expire_time < datetime.datetime.now():
return 2
return agent_info
insert_sql = " insert into admin_business (user_id, user_no, business_id) values "
for i in right_busines_ids:
insert_sql += "('{}','{}','{}'),".format(admin_account.id, admin_account.user_no, i)
insert_sql = insert_sql[:-1]
insert_sql += " ON DUPLICATE KEY UPDATE status = 1"
db.session.execute(insert_sql)
db.session.commit()
@staticmethod
def create_agent_no():
'''
生成用户编号
def get_admin_account_list(user_id=None, phone=None, keyword=None, page=None, page_size=None):
"""
:return:
'''
ran_int = str(random.randint(1, 999999)).zfill(6)
return 'ssw' + ran_int
"""
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(admin_account.id) as total_count"
from_sql = " from admin_account "
if g.user.level == 1:
where_sql = " where 0=0 "
else:
where_sql = """
where
admin_account.id in (
select user_id from admin_business where business_id in (
select business_id from admin_business where user_id = {user_id} and status = 1
)
)
and admin_account.level > {level}
""".format(user_id=g.user.id, level=g.user.level)
if user_id:
where_sql += " and admin_account.id = '{id}'".format(id=user_id)
if phone:
where_sql += " and phone = '{phone}'".format(phone=phone)
if keyword:
where_sql += """
and CONCAT( admin_account.user_name,
admin_account.phone,
admin_account.user_no) LIKE '%{keyword}%'
""".format(keyword=keyword)
order_sql = " ORDER BY admin_account.id ASC, admin_account.status ASC"
if page and page_size:
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
else:
limit_sql = " "
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
if not count_result:
return {"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(
{"user_name": info.user_name, "phone": info.phone, "level": info.level, "status": info.status,
"comment": info.comment, "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 {"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count}
@staticmethod
def get_spot_info(agent_info):
def get_tallyman_account_list(user_id=None, phone=None, keyword=None, page=None, page_size=None):
"""
:param agent_info:
:return:
"""
spot_info = []
infos = db.session.query(AgentSpot, Spot).join(
Spot, Spot.id == AgentSpot.spot_no).filter(AgentSpot.agent_no == agent_info.id,
AgentSpot.status == ACCOUNT_STATUS['on_use']).all()
for info in infos:
cur_info = {}
cur_info['id'] = info.Spot.id
cur_info['spotname'] = info.Spot.spotname
cur_info['letter'] = SpotService.get_pinyin(info.Spot.spotname)
spot_info.append(cur_info)
return spot_info
select_sql = """select tallyman_account.user_name, tallyman_account.phone, tallyman_account.level,
tallyman_account.status,tallyman_account.created_at, tallyman_account.updated_at,
tallyman_account.id, tallyman_account.user_no, tallyman_account.comment,
tallyman_account.business_id
"""
count_sql = "select count(tallyman_account.id) as total_count"
from_sql = " from tallyman_account "
if g.user.level == 1:
where_sql = " where 0=0 "
else:
where_sql = """
where
tallyman_account.business_id in (
select business_id from admin_business where user_id = {user_id} and status = 1
)
""".format(user_id=g.user.id)
if user_id:
where_sql += " and tallyman_account.id = '{id}'".format(id=user_id)
if phone:
where_sql += " and phone = '{phone}'".format(phone=phone)
if keyword:
where_sql += """
and CONCAT( tallyman_account.user_name,
tallyman_account.phone) LIKE '%{keyword}%'
""".format(keyword=keyword)
order_sql = " ORDER BY tallyman_account.id ASC, tallyman_account.status ASC"
if page and page_size:
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
else:
limit_sql = " "
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
if not count_result:
return {"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(
{"user_name": info.user_name, "phone": info.phone, "level": info.level, "status": info.status,
"comment": info.comment, "id": info.id, "user_no": info.user_no, "business_id": info.business_id,
"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 {"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count}
#!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/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": 10}, 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
......
# -*- coding: utf-8 -*-
class UpdateParams:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __getattr__(self, item):
print(f"没有该属性:{item}")
return None
def json2obj(json_data):
d = UpdateParams.__new__(UpdateParams)
d.__dict__.update(json_data)
return d
import base64import jsonfrom Crypto.Cipher import AES class WXBizDataCrypt: def __init__(self, appId, sessionKey): self.appId = appId self.sessionKey = sessionKey def decrypt(self, encryptedData, iv): sessionKey = base64.decodebytes(bytes(self.sessionKey, encoding='utf8')) encryptedData = base64.decodebytes(bytes(encryptedData, encoding='utf8')) iv = base64.decodebytes(bytes(iv, encoding='utf8')) cipher = AES.new(sessionKey, AES.MODE_CBC, iv) des_str = cipher.decrypt(encryptedData) print("==================================") print(des_str) des_str = self._unpad(des_str) print(des_str) des_str = str(des_str,encoding='utf-8') decrypted = json.loads(des_str) if decrypted['watermark']['appid'] != self.appId: raise Exception('Invalid Buffer') return decrypted def _unpad(self, s): return s[:-ord(s[len(s) - 1:])] if __name__ == '__main__': appId = 'wx3185fb4a3633beb0' sessionKey='S7CMDfC6jXJKSaWKanG8oQ==' encryptedData='E7LZhvK7mOcaYsv9xcAfsBN9eSbzFh9FyMtFJ0zsFB0M62zRJ0cosZWksUujUR5WYUmNoIfIJnTIF8gRskxxbFU3fm5X7z4ChZecMSaFM65aEK1suRUD1U0ubB7mOwBBlY4ftdPT5kRwWgXKVkM4VAkYGN8A4fjWE93yGtjzxXs9dypQkCLSNWs6Kw5USEzjhtDZnptVy+lHF5fTXRuzoCstW2Cto4YI3G9hmnS64QuWjRteSqIgh8GN1zEPN0dROJjaWBjqraBCt/BfMsk4HBeL4PA75K8WdqVgKGfQ7/rnmPFOsNXWfajx9jl7XcrfoPaaPL1DmIJ1BlQne2GuLFtzZ3O4/8cdVQ9Lb0N/3kFAzjgzNFNLSYj2VNctmWyLdWi8hH90yslvrODIhMzIsuux2GIAfp0rQd/iVIVvtd7PXBOCe5iZ7aaqD0b0mLF4CmsuBpl8Eh20ZHkYw2SqO0x9uFrS/gy1vwtkmsTpcDw=' iv = 'DQcmcXyQkU+VKqb2mKmasQ==' pc = WXBizDataCrypt(appId, sessionKey) pc.decrypt(encryptedData, iv)#
\ No newline at end of file
import base64import jsonfrom Crypto.Cipher import AES class WXBizDataCrypt: def __init__(self, appId, sessionKey): self.appId = appId self.sessionKey = sessionKey def decrypt(self, encryptedData, iv): sessionKey = base64.decodebytes(bytes(self.sessionKey, encoding='utf8')) encryptedData = base64.decodebytes(bytes(encryptedData, encoding='utf8')) iv = base64.decodebytes(bytes(iv, encoding='utf8')) cipher = AES.new(sessionKey, AES.MODE_CBC, iv) des_str = cipher.decrypt(encryptedData) des_str = self._unpad(des_str) des_str = str(des_str, encoding='utf-8') decrypted = json.loads(des_str) if decrypted['watermark']['appid'] != self.appId: raise Exception('Invalid Buffer') return decrypted def _unpad(self, s): return s[:-ord(s[len(s) - 1:])] if __name__ == '__main__': appId = 'wx3185fb4a3633beb0' sessionKey = 'S7CMDfC6jXJKSaWKanG8oQ==' encryptedData = 'E7LZhvK7mOcaYsv9xcAfsBN9eSbzFh9FyMtFJ0zsFB0M62zRJ0cosZWksUujUR5WYUmNoIfIJnTIF8gRskxxbFU3fm5X7z4ChZecMSaFM65aEK1suRUD1U0ubB7mOwBBlY4ftdPT5kRwWgXKVkM4VAkYGN8A4fjWE93yGtjzxXs9dypQkCLSNWs6Kw5USEzjhtDZnptVy+lHF5fTXRuzoCstW2Cto4YI3G9hmnS64QuWjRteSqIgh8GN1zEPN0dROJjaWBjqraBCt/BfMsk4HBeL4PA75K8WdqVgKGfQ7/rnmPFOsNXWfajx9jl7XcrfoPaaPL1DmIJ1BlQne2GuLFtzZ3O4/8cdVQ9Lb0N/3kFAzjgzNFNLSYj2VNctmWyLdWi8hH90yslvrODIhMzIsuux2GIAfp0rQd/iVIVvtd7PXBOCe5iZ7aaqD0b0mLF4CmsuBpl8Eh20ZHkYw2SqO0x9uFrS/gy1vwtkmsTpcDw=' iv = 'DQcmcXyQkU+VKqb2mKmasQ==' pc = WXBizDataCrypt(appId, sessionKey) pc.decrypt(encryptedData, iv)#
\ 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