def admin_analysis():
    admin = request.cookies.get('user')
    adminpass = request.cookies.get('pass')
    
    if my_func.admin_coach_kakunin(admin, adminpass) \
        and not(len(admin) == 0 or len(adminpass) == 0):
        pass
    else:
        sentence = '初めからやり直してください。'
        index = render_template('error.html',
                                sentence = sentence)
        return make_response(index)
    
    day_list = []
    data_list = []
    for i in range(31):
        day = datetime.date.today() - datetime.timedelta(days=i)
        strday = day.strftime("%Y-%m-%d")
        data = my_func.sql_data_per_day(strday)
        dassui_data = [100*float((d['wa']-d['wb'])/d['wb']) for d in data]
        day_list.append(day.strftime("%m/%d"))
        if i == 0:
            today_list = dassui_data
        if len(dassui_data) > 0:
            data_list.append(float(sum(dassui_data) / len(dassui_data)))
        else:
            data_list.append(float(-100))
    # 脱水率平均の図を出力
    data_list.reverse()
    day_list.reverse()
    
    plt.figure()
    plt.plot(data_list,'o')
    plt.xticks(range(0,31)[::3], day_list[::3])
    plt.grid(color = 'gray')
    plt.ylim(-2.5,1.5)
    plt.ylabel('Dehydration rate')
    plt.xlabel('Date')
    plt.title('Daily average')
    filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S")\
                + 'ave.png'
    path_list = glob.glob('./static/img/analysis/*.png')
    for file in path_list:
        os.remove(file)
    plt.savefig('./static/img/analysis/'+filename)
    # 散布図
    plt.figure()
    plt.hist(today_list,bins=10,range=(-2,2))
    plt.ylabel('Frequency')
    plt.xlabel('Dehydration rate')
    plt.ylim(0,)
    plt.xlim(-2,2)
    plt.title('Today\'s Scatter plot')
    filename2 = datetime.datetime.now().strftime("%Y%m%d%H%M%S")\
                +'scatter.png'
    plt.savefig('./static/img/analysis/'+filename2)
    
    return make_response(render_template('admin_analysis.html',
                                         fname=filename,
                                         fname2=filename2))
def admin_show():
    admin = request.cookies.get('user')
    adminpass = request.cookies.get('pass')
    
    try:
        if my_func.admin_coach_kakunin(admin, adminpass):
            index = render_template('admin_main.html',
                                    title = 'taberube.jp for admin',
                                    user = admin,
                                    posts = [],
                                    serverhost = server_address)
            
            resp = make_response(index)
            resp.set_cookie('user', admin)
            resp.set_cookie('pass', adminpass)
        else:
            sentence = '管理者または監督・コーチのみログインできます。'
            index = render_template('error.html',
                                    sentence = sentence)
            resp = make_response(index)
        
    except Exception as error:
        sentence = 'do not connect sql server by your username \
                \n or making html error:\n{}'.format(error.__str__())
        index = render_template('error.html',
                                sentence = sentence)
        resp = make_response(index)
    
    return resp
def admin_latest():
    admin = request.cookies.get('user')
    adminpass = request.cookies.get('pass')
    
    if admin == '' or adminpass == '':
        sentence = 'ログアウトしています。'
        index = render_template('error.html',
                                sentence = sentence)
        return make_response(index)
    
    if not (my_func.admin_coach_kakunin(admin, adminpass)):
        sentence = '初めからやり直してください。'
        index = render_template('error.html',
                                sentence = sentence)
        return make_response(index)
    
    try:
        user_prof = my_func.sql_ALLuser_profile()
        try:
            data = my_func.sql_data_get_latest_all(user_prof[admin]['type'],
                                                   user_prof[admin]['org'])
            posts = []
            for d in reversed(data):
                neccessary1_tmp \
                    = round(float(d['wb']*0.01) + float(d['moi']),1)
                if neccessary1_tmp <= 0:
                    neccessary1_tmp = 0
                shitsudo = d['shitsudo']
                temp = d['temp']
                if int(shitsudo) == 1111:
                    shitsudo = ' '
                if int(temp) == 1111:
                    temp = ' '
                posts.append({
                  'date'         :d['day'],#日
                  'bweight'      :d['wb'],#運動前体重
                  'aweight'      :d['wa'],#運動後体重
                  'training'     :d['contents'][0:10],#トレーニング内容
                  'period'       :d['time'],#運動時間
                  'intake'       :d['moi'],#飲水量
                  'dehydraterate':my_func.dassui_ritu(d['wb'],d['wa']),#脱水率
                  'necessary'    :round(my_func.hakkann_ryo(d['wb'], d['wa'], d['moi']), 1),
                  'tenki'        :tenki_dic[str(d['tenki'])],#天気
                  'shitsudo'     :shitsudo,#湿度
                  'temp'         :temp,
                  'username'     :user_prof[d['username']]['rname'],
                  'w1'           :round(d['wb']*0.99,1),
                  'necessary1'   :neccessary1_tmp}# ユーザの本名
                )
            
            posts = reversed(sorted(posts, key=lambda x:x['date']))
            index = render_template('admin_latest.html', 
                                    title = 'taberube.jp', 
                                    posts = posts,
                                    serverhost = server_address)
            return make_response(index)
            
        except Exception as error:
            sentence = 'ERROR1: ' + error.__str__()
            index = render_template('error.html',
                                    sentence = sentence)
            return make_response(index)
        
    except Exception as error:
            sentence = 'ERROR2: '+error.__str__()
            index = render_template('error.html',
                                    sentence = sentence)
            return make_response(index)
def admin_watch_show():
    admin = request.cookies.get('user')# クッキーを保存
    adminpass = request.cookies.get('pass')# クッキーを保存
    
    if not(my_func.admin_coach_kakunin(admin, adminpass)):
        sentence = '初めからやり直してください。'
        index = render_template('error.html',
                                sentence = sentence)
        return make_response(index)
    
    try:
        user_prof = my_func.sql_ALLuser_profile()
        uid_get = request.args.get('name')# 見たいユーザ名
        real_name = user_prof[uid_get]['rname']# ユーザの本名
        
        if user_prof[admin]['type'] == 2 and user_prof[admin]['org'] != user_prof[uid_get]['org']:
            sentence = '機能制限: このユーザーのデータは閲覧できません。'
            index = render_template('error.html',
                                    sentence = sentence)
            return make_response(index)
        
        data = my_func.sql_data_get(uid_get)
        posts = []
        for d in reversed(data):# dataは辞書形式
            neccessary1_tmp \
                = round(float(d['wb']*0.01) + float(d['moi']), 1)
            
            if neccessary1_tmp <= 0:
                neccessary1_tmp = 0
            shitsudo = d['shitsudo']
            temp = d['temp']
            if int(shitsudo) == 1111:
                shitsudo = ' '
            if int(temp) == 1111:
                temp = ' '
            
            posts.append({
              'date'          :d['day'],#日
              'bweight'       :d['wb'],#運動前体重
              'aweight'       :d['wa'],#運動後体重
              'training'      :d['contents'][0:10],#トレーニング内容
              'period'        :d['time'],#運動時間
              'intake'        :d['moi'],#飲水量
              'dehydraterate' :my_func.dassui_ritu(d['wb'],d['wa']),#脱水率
              'necessary'    :round(my_func.hakkann_ryo(d['wb'], d['wa'], d['moi']), 1),
              'tenki'         :tenki_dic[str(d['tenki'])],#天気
              'shitsudo'      :shitsudo,#湿度
              'temp'          :temp,
              'w1'            :round(d['wb']*0.99,1),
              'necessary1'    :neccessary1_tmp
            })
        
        index = render_template('admin_show.html',
                                title = 'taberube.jp',
                                user = real_name,
                                posts = posts,
                                userid = uid_get,
                                serverhost = server_address)
        
        resp = make_response(index)
        
        resp.set_cookie('user', admin)# クッキーの再設定
        resp.set_cookie('pass', adminpass)# クッキーの再設定
        
        return resp
    except Exception as error:# SQLなどのエラー
        sentence = error.__str__()
        index = render_template('error.html',
                                sentence = sentence)
        return make_response(index)
def admin_watch():# ユーザリスト ユーザを選び -> admin_watch_show()
    admin = request.cookies.get('user')
    adminpass = request.cookies.get('pass')
    
    try:
        if not(my_func.admin_coach_kakunin(admin, adminpass)):
            sentence = '初めからやり直してください。'
            index = render_template('error.html',
                                    sentence = sentence)
            return make_response(index)
        user_prof = my_func.sql_ALLuser_profile()
        org_dic = my_func.get_org()
        
    except Exception as error:
        sentence = 'do not connect sql server by your username \
                \n or occur making html error:\n{}'.format(error.__str__())
        index = render_template('error.html',
                                sentence = sentence)
        resp = make_response(index)
    
    posts = []; posts_admin = [] 
    posts_coach = []; posts_unusable = []
    
    for name in user_prof.keys():
        dic = {'name'     :user_prof[name]['rname'],
                'org'     :org_dic[user_prof[name]['org']]['org_name'],
                'year'    :user_prof[name]['year'],
                'id'      :name,
                'keyword' :str(user_prof[name]['year']) \
                     + user_prof[name]['org'] + name,
               }
        if user_prof[admin]['type'] == 2 \
            and dic['org'] == org_dic[user_prof[admin]['org']]['org_name']:
            
            if user_prof[name]['type'] == 1:
                posts.append(dic)
            elif user_prof[name]['type'] == 2:
                posts_coach.append(dic)
            
        if user_prof[admin]['type'] == 0:
            
            if user_prof[name]['type'] == 0:
                posts_admin.append(dic)
            elif user_prof[name]['type'] == 1:
                posts.append(dic)
            elif user_prof[name]['type'] == 2:
                posts_coach.append(dic)
            elif user_prof[name]['type'] == -1:
                posts_unusable.append(dic)
    
    if user_prof[admin]['type'] == 2:
        posts_admin =[{'name':'非表示',
                       'org' :'XXXX',
                       'year':'XXXX',
                       'id'  :'XXXX'}]; 
    
    posts = reversed(sorted(posts, 
                            key = lambda x : x['keyword'])
            )
    resp = make_response(render_template(
            'admin_watch.html',
            serverhost = server_address,
            posts = posts,
            posts_admin = posts_admin,
            posts_coach = posts_coach,
            posts_unusable = posts_unusable))
    
    return resp