boxstate.py 5.4 KB
#!/usr/bin/env python
# encoding: utf-8
'''
@author: dongjie
@license: (C) Copyright 2013-2020, Node Supply Chain Manager Corporation Limited.
@contact: 503479457@qq.com
@software: garner
@file: boxstate.py
@time: 2020/9/17 13:45
@desc:
'''
from flask import jsonify,render_template,request,send_from_directory
from app.api import bp
from config import Config
from pyecharts.charts import Bar,Line,Grid, Liquid,Pie
from pyecharts.options.global_options import ThemeType
from pyecharts.faker import Faker
import pyecharts.options as opts
from pyecharts.commons.utils import JsCode
import urllib,json,operator,re
import os
import pymongo
import pandas as pd
import time

def open_url(url):
    resp = urllib.request.urlopen(url)
    ele_json = json.loads(resp.read())
    return ele_json

def format_data():
    url = Config.BOX_RATIO_URL
    ele_json = open_url(url)
    ratio_list = []
    for info in ele_json:
        current_type_list = []
        if info['type'] != 'PACKAGE':
            usecount = 0
            totalcount = 0
            for nummap in info['usageMap'].values():
                use_list = []
                # if int(nummap['usedCount'])
                use_list.append(nummap['sizeStr'])
                use_list.append(int(nummap['usedCount']))
                usecount += int(nummap['usedCount'])
                totalcount += int(nummap['totalCount'])
                current_type_list.append(use_list)
            current_ratio = usecount / totalcount
            current_ratio = round(float(current_ratio),4)
            # print (current_ratio)
            # current_ratio = float(('%.2f' % current_ratio))
            number = int(re.findall(r"\d+", info['cid'])[0])
            # name = info['cid']
            ratio_dict = {
                'name':info['name'],
                'type_map':current_type_list,
                'ratio': current_ratio,
                'box_num':totalcount,
                'number': number
            }
            ratio_list.append(ratio_dict)
    ratio_list = sorted(ratio_list, key=operator.itemgetter('number'))[0:20]
    print (ratio_list)
    return ratio_list

@bp.route('/boxstate')
def boxstate():
    data = format_data()
    # print (type(data[0]['ratio']))
    # print (data[0]['ratio'])
    grid_list = []
    for current in data:
        # print (current['ratio'])
        l = (
            Liquid()
                .add("lq", [current['ratio']], center=["75%", "50%"],is_outline_show=False,label_opts=opts.LabelOpts(formatter=JsCode(
            """function (param) {
                    return (Math.floor(param.value * 10000) / 100) + '%';
                }"""
        ),position="inside",font_size=50))
                .set_global_opts(title_opts=opts.TitleOpts(title='总容量' + str(current['box_num']),title_textstyle_opts=opts.TextStyleOpts(color="yellow"),))
                .set_series_opts(type='liquidFill',radius='80%'))
        c = (
            Pie()
                .add("", current['type_map'],center=["30%", "50%"])
                # .set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
                .set_global_opts(legend_opts=opts.LegendOpts(is_show=False))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}",color="rgba(255, 255, 255, 1)"))
        )
        grid = Grid().add(l, grid_opts=opts.GridOpts()).add(c, grid_opts=opts.GridOpts())
        grid_list.append(grid.dump_options())
    return render_template("boxstate.html",grid=grid_list)

# 连接数据库
def conn_mongo(table,path):
    mongo_client = pymongo.MongoClient(host='localhost', port=27017)
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    if table == 'alarmagv':
        cach = db.alarmagv
    elif table == 'ng':
        cach = db.collectNg
    else:
        cach = db.stockqty
    data=cach.find()
    mongo_client.close()
    df = pd.DataFrame(data)
    df = df.drop('_id', 1)
    if table == 'stock':
        cols = list(df)
        # move the column to head of list using index, pop and insert
        cols.insert(1, cols.pop(cols.index('qty_out')))
        # use ix to reorder
        df = df.loc[:, cols]
    df.to_csv(path,encoding="utf_8_sig")

# 下载agv错误信息
@bp.route('/downloadagv/', methods=['GET'], strict_slashes=False)
def downloadagv():
    # basepath = os.path.dirname(__file__)
    c_path = "D:/qisda_charts/app/static/data/"
    file_path = os.path.join(c_path, 'agverror.csv')
    table = 'alarmagv'
    conn_mongo(table,file_path)
    if request.method == "GET":
        if os.path.isfile(os.path.join(c_path, 'agverror.csv')):
            return send_from_directory(c_path, 'agverror.csv', as_attachment=True)

@bp.route('/downloadstock/', methods=['GET'], strict_slashes=False)
def downloadstock():
    c_path = "D:/qisda_charts/app/static/data/"
    file_path = os.path.join(c_path, 'stock.csv')
    table = 'stock'
    conn_mongo(table, file_path)
    if request.method == "GET":
        if os.path.isfile(os.path.join(c_path, 'stock.csv')):
            return send_from_directory(c_path, 'stock.csv', as_attachment=True)

@bp.route('/downloadng/', methods=['GET'], strict_slashes=False)
def downloadng():
    c_path = "D:/qisda_charts/app/static/data/"
    file_path = os.path.join(c_path, 'collectNg.csv')
    table = 'ng'
    conn_mongo(table, file_path)
    if request.method == "GET":
        if os.path.isfile(os.path.join(c_path, 'collectNg.csv')):
            return send_from_directory(c_path, 'collectNg.csv', as_attachment=True)