Commit 2d09b31b authored by wang zhengwei's avatar wang zhengwei

添加app report

parent 37f8c2ae
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
import logging # import logging
import redis import redis
import os import os
import sys import sys
...@@ -100,12 +100,12 @@ redis_port=config[env]['celery']['port'], ...@@ -100,12 +100,12 @@ redis_port=config[env]['celery']['port'],
redis_db=config[env]['celery']['db'], redis_db=config[env]['celery']['db'],
redis_password=config[env]['celery']['password'] redis_password=config[env]['celery']['password']
logging.basicConfig(level=logging.INFO, # logging.basicConfig(level=logging.INFO,
filename=work_dir + config[env]['log']['filename'], # filename=work_dir + config[env]['log']['filename'],
filemode=config[env]['log']['filemode'], # filemode=config[env]['log']['filemode'],
format=config[env]['log']['format'], # format=config[env]['log']['format'],
datefmt=config[env]['log']['datefmt'] # datefmt=config[env]['log']['datefmt']
) # )
class TAMP_SQL(object): class TAMP_SQL(object):
"""[sqlalchemy 封装] """[sqlalchemy 封装]
......
...@@ -17,7 +17,8 @@ from flask import request, render_template, g ...@@ -17,7 +17,8 @@ from flask import request, render_template, g
from flask import make_response from flask import make_response
from app.api.engine import config from app.api.engine import config
from app.service.report_service import get_report_list, delete_report, get_one_report, edit_report, make_report, edit_report_name from app.service.report_service import get_report_list, delete_report, \
get_one_report, edit_report, make_report, edit_report_name, make_app_report
from app.service.template_manage_service import get_make_report_data from app.service.template_manage_service import get_make_report_data
from app.utils.auth import login_require from app.utils.auth import login_require
from app.utils.format_transfer import npEncoder from app.utils.format_transfer import npEncoder
...@@ -167,4 +168,50 @@ class FindReport(Resource): ...@@ -167,4 +168,50 @@ class FindReport(Resource):
"message": "成功", "message": "成功",
"attributes": data "attributes": data
} }
return resp return resp
\ No newline at end of file
class AppReportHandlers(Resource):
"""."""
def __init__(self):
"""."""
self.parser = reqparse.RequestParser()
@login_require
def get(self):
"""."""
self.parser.add_argument('customer_id', type=str, required=True, help='customer_id不能为空')
self.parser.add_argument('time', type=str, required=True, help='time不能为空')
args = self.parser.parse_args()
args['ifa_id'] = g.ifa_id
# 默认模版制作持仓报告
data = make_app_report(args)
if data:
url = data
resp = {
"code": 0,
"data": data,
"lang": "zh_CN",
"msg": "成功"
}
else:
resp = {
"code": 0,
"data": '',
"lang": "zh_CN",
"msg": "失败"
}
return resp
def post(self):
"""."""
pass
def put(self, id):
"""."""
pass
def delete(self, id):
"""."""
pass
\ No newline at end of file
...@@ -132,6 +132,7 @@ class HoldReport(Base, BaseModel): ...@@ -132,6 +132,7 @@ class HoldReport(Base, BaseModel):
report_data = Column(Text) report_data = Column(Text)
name = Column(String(100)) name = Column(String(100))
create_time = Column(DateTime) create_time = Column(DateTime)
custom_time = Column(DateTime)
def to_dict(self, allow_field=None): def to_dict(self, allow_field=None):
all_field = [r.name for r in self.__table__.columns] all_field = [r.name for r in self.__table__.columns]
...@@ -145,6 +146,12 @@ class HoldReport(Base, BaseModel): ...@@ -145,6 +146,12 @@ class HoldReport(Base, BaseModel):
data = {c: int(getattr(self, c).timestamp()) if isinstance(getattr(self, c), datetime.datetime) else getattr(self, c) for c in allow_field} data = {c: int(getattr(self, c).timestamp()) if isinstance(getattr(self, c), datetime.datetime) else getattr(self, c) for c in allow_field}
data['file'] = file data['file'] = file
return data return data
def get_file(self):
file = ''
if self.file:
file = pdf_folder + self.file
return file
class HoldDiagnoseReport(Base, BaseModel): class HoldDiagnoseReport(Base, BaseModel):
......
...@@ -22,4 +22,5 @@ def add_route(api): ...@@ -22,4 +22,5 @@ def add_route(api):
api.add_resource(CustomerList, '/api/customer_list') api.add_resource(CustomerList, '/api/customer_list')
api.add_resource(FundEvaluation, '/api/fund_evaluation') api.add_resource(FundEvaluation, '/api/fund_evaluation')
api.add_resource(StatementController, '/api/statement') api.add_resource(StatementController, '/api/statement')
api.add_resource(AppReportHandlers, '/fund_report/report')
...@@ -14,8 +14,8 @@ import uuid ...@@ -14,8 +14,8 @@ import uuid
from sqlalchemy import and_, or_ from sqlalchemy import and_, or_
# from sqlalchemy import union_all # from sqlalchemy import union_all
from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine, template_folder, temp_img_save_folder from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine, template_folder, temp_img_save_folder, pdf_save_folder
from app.model.tamp_diagnose_app import HoldReport, HoldDiagnoseReport, PeriodicReport, Customer, ReportView from app.model.tamp_diagnose_app import HoldReport, HoldDiagnoseReport, PeriodicReport, Customer, ReportView, FundReportManange
from app.utils.jinjia2html_v2 import DataIntegrate from app.utils.jinjia2html_v2 import DataIntegrate
from app.celery import save_pdf from app.celery import save_pdf
...@@ -289,3 +289,70 @@ def make_report(args): ...@@ -289,3 +289,70 @@ def make_report(args):
# }) # })
# else: # else:
# return {'record_id': record_id} # return {'record_id': record_id}
def make_app_report(args):
"""制作报告."""
ifa_id = args.get('ifa_id')
customer_id = args.get('customer_id')
type = 1
pdf_name = str(uuid.uuid4()) + '.pdf'
args['file'] = pdf_name
args['create_time'] = datetime.datetime.now()
args['update_status'] = 2
custom_time = args['time']
args['custom_time'] = custom_time
data = {}
record_id = 0
report_data = ''
default_template = ''
with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
tamp_diagnose_session = tamp_diagnose_app.session
# 查找当前时间是否有生成的pdf
hr = tamp_diagnose_session.query(HoldReport).filter(HoldReport.custom_time == custom_time,
HoldReport.ifa_id == ifa_id,
HoldReport.customer_id == customer_id).first()
if hr:
return hr.get_file()
customer_name = ''
type_name = '持仓报告'
create_date = str(datetime.datetime.now().date())
sql = "select customer_name from customer_view where id = '{}'".format(customer_id)
res = tamp_diagnose_session.execute(sql)
res = res.fetchone()
if res:
customer_name = res[0]
args['name'] = customer_name + type_name + create_date
template = tamp_diagnose_session.query(FundReportManange).filter(and_(
FundReportManange.ifa_id == ifa_id,
FundReportManange.type == 1,
FundReportManange.default == 1
)).first()
if template.default_template:
default_template = json.loads(template.default_template)
else:
default_template = json.loads(template.custom_template)
# save_pdf.delay(record_id, ifa_id, customer_id, pdf_name, type)
try:
dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, pdf_name=pdf_name, type=type, end_date = custom_time)
report_data = dt.get_template_data(default_template=default_template)
report_data = json.dumps(report_data, cls=npEncoder, ensure_ascii=False)
args['report_data'] = report_data
dt.render_data(data=json.loads(report_data.replace(template_folder, temp_img_save_folder)))
except OSError:
pass
except Exception as e:
return False
if os.path.exists(pdf_save_folder + pdf_name):
with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
tamp_diagnose_session = tamp_diagnose_app.session
args['update_time'] = datetime.datetime.now()
report_record = HoldReport(**args)
tamp_diagnose_session.add(report_record)
tamp_diagnose_session.flush()
# record_id = report_record.id
return report_record.get_file()
return False
\ No newline at end of file
...@@ -5,8 +5,8 @@ ...@@ -5,8 +5,8 @@
# pool_pre_ping=True) # pool_pre_ping=True)
# con = db.connect() # con = db.connect()
import logging # import logging
logging.basicConfig(level=logging.INFO) # logging.basicConfig(level=logging.INFO)
from app.api.engine import tamp_fund_engine, TAMP_SQL, tamp_product_engine from app.api.engine import tamp_fund_engine, TAMP_SQL, tamp_product_engine
from app.utils.week_evaluation import * from app.utils.week_evaluation import *
...@@ -73,7 +73,7 @@ def get_frequency(df): ...@@ -73,7 +73,7 @@ def get_frequency(df):
index_series = df.index.to_series() index_series = df.index.to_series()
# freq_series = index_series - index_series.shift(1) # freq_series = index_series - index_series.shift(1)
freq_series = index_series.diff(1) freq_series = index_series.diff(1)
logging.log(logging.DEBUG, freq_series.describe()) # logging.log(logging.DEBUG, freq_series.describe())
try: try:
f = freq_series.mode()[0].days f = freq_series.mode()[0].days
except: except:
...@@ -270,12 +270,12 @@ def fund_rank(start_date, end_date, invest_type=1): ...@@ -270,12 +270,12 @@ def fund_rank(start_date, end_date, invest_type=1):
try: try:
if df.index[-1] - df.index[0] < 0.6 * (end_date - start_date): if df.index[-1] - df.index[0] < 0.6 * (end_date - start_date):
skipped_funds.append(fund) skipped_funds.append(fund)
logging.log(logging.INFO, 'Skipped {}'.format(fund)) # logging.log(logging.INFO, 'Skipped {}'.format(fund))
continue continue
n = get_frequency(df) n = get_frequency(df)
except: except:
# logging.log(logging.ERROR, repr(e)) # logging.log(logging.ERROR, repr(e))
logging.log(logging.INFO, 'Skipped {}'.format(fund)) # logging.log(logging.INFO, 'Skipped {}'.format(fund))
continue continue
df = resample(df, trading_cal, n) df = resample(df, trading_cal, n)
...@@ -285,7 +285,7 @@ def fund_rank(start_date, end_date, invest_type=1): ...@@ -285,7 +285,7 @@ def fund_rank(start_date, end_date, invest_type=1):
except ValueError: except ValueError:
continue continue
logging.log(logging.INFO, "Dealing with {}".format(fund)) # logging.log(logging.INFO, "Dealing with {}".format(fund))
net_worth = df['adj_nav'].astype(float) net_worth = df['adj_nav'].astype(float)
end_df, begin_df = net_worth.values[-1], net_worth.values[0] end_df, begin_df = net_worth.values[-1], net_worth.values[0]
......
...@@ -12,7 +12,9 @@ import uuid ...@@ -12,7 +12,9 @@ import uuid
import oss2 import oss2
from app.api.engine import logging, pdf_folder, tamp_diagnose_app_engine, config, env # from app.api.engine import logging, pdf_folder, tamp_diagnose_app_engine, config, env
from app.api.engine import pdf_folder, tamp_diagnose_app_engine, config, env
import os import os
from app.api.engine import tamp_user_engine, tamp_order_engine, TAMP_SQL from app.api.engine import tamp_user_engine, tamp_order_engine, TAMP_SQL
...@@ -82,7 +84,7 @@ def call_month_report(ifauser_id, ifauser_name, customer_id, customer_name): ...@@ -82,7 +84,7 @@ def call_month_report(ifauser_id, ifauser_name, customer_id, customer_name):
except OSError: except OSError:
print('IFA: {}, 客户: {}的基金月报已经生成,耗时{}秒'.format(ifauser_name, customer_name, time.time()-start)) print('IFA: {}, 客户: {}的基金月报已经生成,耗时{}秒'.format(ifauser_name, customer_name, time.time()-start))
except Exception as e: except Exception as e:
logging.error("IFAID{}: IFAName{}, 客户ID{}, 客户Name: {}的基金月报生成异常,错误追踪:{}".format(ifauser_id, ifauser_name, customer_id, customer_name, traceback.format_exc())) # logging.error("IFAID{}: IFAName{}, 客户ID{}, 客户Name: {}的基金月报生成异常,错误追踪:{}".format(ifauser_id, ifauser_name, customer_id, customer_name, traceback.format_exc()))
print("IFA: {}, 客户: {}的基金月报生成异常,错误追踪:{}".format(ifauser_name, customer_name, traceback.format_exc())) print("IFA: {}, 客户: {}的基金月报生成异常,错误追踪:{}".format(ifauser_name, customer_name, traceback.format_exc()))
finally: finally:
auth = oss2.Auth(config[env]['oss']['account'], config[env]['oss']['password']) auth = oss2.Auth(config[env]['oss']['account'], config[env]['oss']['password'])
......
...@@ -10,7 +10,8 @@ import time ...@@ -10,7 +10,8 @@ import time
import traceback import traceback
import uuid import uuid
import pandas as pd import pandas as pd
from app.api.engine import logging, pdf_folder, tamp_diagnose_app_engine, config, env # from app.api.engine import logging, pdf_folder, tamp_diagnose_app_engine, config, env
from app.api.engine import pdf_folder, tamp_diagnose_app_engine, config, env
import os import os
from app.api.engine import tamp_user_engine, tamp_order_engine, TAMP_SQL from app.api.engine import tamp_user_engine, tamp_order_engine, TAMP_SQL
...@@ -71,7 +72,7 @@ def call_month_report(ifauser_id, ifauser_name, customer_id, customer_name): ...@@ -71,7 +72,7 @@ def call_month_report(ifauser_id, ifauser_name, customer_id, customer_name):
except OSError: except OSError:
print('IFA: {}, 客户: {}的基金月报已经生成,耗时{}秒'.format(ifauser_name, customer_name, time.time()-start)) print('IFA: {}, 客户: {}的基金月报已经生成,耗时{}秒'.format(ifauser_name, customer_name, time.time()-start))
except Exception as e: except Exception as e:
logging.error("IFAID{}: IFAName{}, 客户ID{}, 客户Name: {}的基金月报生成异常,错误追踪:{}".format(ifauser_id, ifauser_name, customer_id, customer_name, traceback.format_exc())) # logging.error("IFAID{}: IFAName{}, 客户ID{}, 客户Name: {}的基金月报生成异常,错误追踪:{}".format(ifauser_id, ifauser_name, customer_id, customer_name, traceback.format_exc()))
print("IFA: {}, 客户: {}的基金月报生成异常,错误追踪:{}".format(ifauser_name, customer_name, traceback.format_exc())) print("IFA: {}, 客户: {}的基金月报生成异常,错误追踪:{}".format(ifauser_name, customer_name, traceback.format_exc()))
finally: finally:
return return
......
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