statement_service.py 25.7 KB
Newer Older
李宗熹's avatar
李宗熹 committed
1 2 3 4 5 6 7 8 9 10 11 12
# -*- coding: UTF-8 -*-
"""
@author:Zongxi.Li
@file:statement_service.py
@time:2021/02/01
"""
import json
import pandas as pd
import numpy as np

from datetime import datetime, date
from decimal import Decimal
13 14
from app.api.engine import tamp_order_engine, tamp_user_engine, \
    tamp_fund_engine, tamp_product_engine, tamp_diagnose_app_engine, TAMP_SQL
李宗熹's avatar
李宗熹 committed
15 16 17 18 19 20 21 22 23 24 25


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return obj.__str__()
        if isinstance(obj, Decimal):
            return obj.__float__()
        return json.JSONEncoder.default(self, obj)


李宗熹's avatar
李宗熹 committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
def get_fund_name(fund):
    with TAMP_SQL(tamp_fund_engine) as tamp_fund:
        tamp_fund_session = tamp_fund.session
        sql = "SELECT fund_short_name FROM fund_info WHERE id='{}'".format(fund)
        # df = pd.read_sql(sql, con)
        cur = tamp_fund_session.execute(sql)
        data = cur.fetchall()
        df = pd.DataFrame(list(data), columns=['fund_short_name'])
        if len(df) == 0:
            with TAMP_SQL(tamp_product_engine) as tamp_product:
                tamp_product_session = tamp_product.session
                sql = "SELECT fund_short_name FROM fund_info WHERE id='{}'".format(fund)
                # df = pd.read_sql(sql, con)
                cur = tamp_product_session.execute(sql)
                data = cur.fetchall()
                df = pd.DataFrame(list(data), columns=['fund_short_name'])
42
            if len(df) == 0:
李宗熹's avatar
李宗熹 committed
43 44 45
                with TAMP_SQL(tamp_fund_engine) as tamp_fund:
                    tamp_fund_session = tamp_fund.session
                    sql = "SELECT fund_short_name FROM tx_fund_info WHERE `id`='{}'".format(fund)
46
                    # df = pd.read_sql(sql, con)
李宗熹's avatar
李宗熹 committed
47
                    cur = tamp_fund_session.execute(sql)
48 49
                    data = cur.fetchall()
                    df = pd.DataFrame(list(data), columns=['fund_short_name'])
李宗熹's avatar
李宗熹 committed
50 51 52 53 54 55 56 57
                if len(df) == 0:
                    with TAMP_SQL(tamp_fund_engine) as tamp_fund:
                        tamp_fund_session = tamp_fund.session
                        sql = "SELECT fund_name FROM ifa_imported_fund_info WHERE id='{}'".format(fund)
                        # df = pd.read_sql(sql, con)
                        cur = tamp_fund_session.execute(sql)
                        data = cur.fetchall()
                        df = pd.DataFrame(list(data), columns=['fund_short_name'])
58 59 60 61 62 63 64

    if df.fund_short_name.count() > 0:
        return df.fund_short_name.values[0]
    else:
        return fund


李宗熹's avatar
李宗熹 committed
65 66 67
def get_order_info(user_id):
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_app_session = tamp_diagnose_app.session
68
        sql_user = """select f1.id, f1.fund_id, f2.realname, f3.customer_name, f1.customer_id, f3.valueSex,f1.type,f1.order_type,f1.pay_date,f1.subscription_fee,f1.confirm_share_date,f1.confirm_share,f1.confirm_amount,f1.nav,f1.folio_name from tamp_diagnose_app.customer_order_view f1, tamp_user.user_info f2,tamp_diagnose_app.customer_view f3   where f2.id=f1.user_id and f3.id=f1.customer_id  and f1.delete_tag=0 and user_id='{}'""".format(
李宗熹's avatar
李宗熹 committed
69 70 71 72
            user_id)
        cur = tamp_diagnose_app_session.execute(sql_user)
        data = cur.fetchall()
        order_df = pd.DataFrame(list(data),
73 74
                                columns=['order_id', 'fund_id', 'user_name', 'customer_name', 'customer_id', 'value_sex',
                                         'type', 'order_type', 'pay_date',
李宗熹's avatar
李宗熹 committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
                                         'subscription_fee', 'confirm_share_date', 'confirm_share',
                                         'confirm_amount', 'nav', 'folio_name'])
    return order_df


def get_provision_info(user_id):
    with TAMP_SQL(tamp_order_engine) as tamp_order, TAMP_SQL(tamp_user_engine) as tamp_user:
        tamp_order_session = tamp_order.session
        # sql = """select f1.ifa_id, f1.customer_id, f1.fund_id, f1.fund_nav,
        # f1.fund_nav_date, f1.predict_date, f1.pro_date, f1.manage_predict_fee, f1.permc_exc_predict_fee, f1.permc_rem_fee,
        # f1.recommend_ifa_id, f1.recommend_fee, f1.permc_recommend_fee, f1.incentive_fee_ratio, f1.retention_shares
        # from ifa_provision_day_info as f1 where f1.ifa_id='{}'""".format(user_id)
        sql = """SELECT * FROM `ifa_provision_day_info` WHERE `ifa_id` = '{}'""".format(user_id)
        cur = tamp_order_session.execute(sql)
        data = cur.fetchall()
        provision_df = pd.DataFrame(list(data),
91
                                columns=['id', 'ifa_id', 'customer_id', 'order_id', 'fund_id', 'fund_nav', 'fund_nav_date',
李宗熹's avatar
李宗熹 committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
                                         'predict_date', 'pro_date','pro_type',
                                         'manage_predict_fee', 'permc_exc_predict_fee', 'permc_rem_predict_fee',
                                         'manage_fee', 'permc_exc_fee','permc_rem_fee', 'recommend_ifa_id',
                                         'recommend_fee','permc_recommend_fee', 'incentive_fee_ratio',
                                         'deduction','retention_shares','status'])
    return provision_df


def get_end_date(year, month):
    if month == 12:
        end_date = datetime(year=year + 1, month=1, day=1)
    else:
        end_date = datetime(year=year, month=month + 1, day=1)
    return end_date


def get_month_list(quarter, year):
    if quarter == 4:
        year = year - 1
    else:
        year = year

    month_list = range((quarter - 1) * 3 + 1, quarter * 3 + 1)
    return year, month_list


def type2note(type):
119
    type2note_dict = {1: "买入",
李宗熹's avatar
李宗熹 committed
120 121
                      2: "赎回",
                      4: "分红"}
李宗熹's avatar
李宗熹 committed
122 123 124 125
    return type2note_dict.get(type)


def cal_total_amount(df):
李宗熹's avatar
李宗熹 committed
126 127
    purchase_amount = df[df['order_type'] == 1]['confirm_amount'].sum()
    redemption_amount = df[df['order_type'] == 2]['confirm_amount'].sum()
李宗熹's avatar
李宗熹 committed
128 129
    subscription_fee = df['subscription_fee'].sum()
    total_amount = purchase_amount - redemption_amount - subscription_fee
李宗熹's avatar
李宗熹 committed
130 131 132 133 134 135 136 137 138 139 140
    return total_amount


def num2chinese(number):
    num2chinese_dict = {1: '一',
                        2: '二',
                        3: '三',
                        4: '四'}
    return num2chinese_dict.get(number)


李宗熹's avatar
李宗熹 committed
141
def get_tax_rate():
李宗熹's avatar
李宗熹 committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    # with TAMP_SQL(tamp_order_engine) as tamp_order, TAMP_SQL(tamp_user_engine) as tamp_user:
    #     tamp_order_session = tamp_order.session
    #     # sql = """select f1.ifa_id, f1.customer_id, f1.fund_id, f1.fund_nav,
    #     # f1.fund_nav_date, f1.predict_date, f1.pro_date, f1.manage_predict_fee, f1.permc_exc_predict_fee, f1.permc_rem_fee,
    #     # f1.recommend_ifa_id, f1.recommend_fee, f1.permc_recommend_fee, f1.incentive_fee_ratio, f1.retention_shares
    #     # from ifa_provision_day_info as f1 where f1.ifa_id='{}'""".format(user_id)
    #     sql = """SELECT * FROM `ifa_provision_day_info` WHERE `ifa_id` = '{}'""".format(user_id)
    #     cur = tamp_order_session.execute(sql)
    #     data = cur.fetchall()
    #     provision_df = pd.DataFrame(list(data),
    #                             columns=['id', 'ifa_id', 'customer_id', 'fund_id', 'order_id', 'fund_nav', 'fund_nav_date',
    #                                      'predict_date', 'pro_date','pro_type',
    #                                      'manage_predict_fee', 'permc_exc_predict_fee', 'permc_rem_predict_fee',
    #                                      'manage_fee', 'permc_exc_fee','permc_rem_fee', 'recommend_ifa_id',
    #                                      'recommend_fee','permc_recommend_fee', 'incentive_fee_ratio',
    #                                      'deduction','retention_shares','status'])
158
    return 0
159 160


李宗熹's avatar
李宗熹 committed
161 162 163 164 165 166 167 168
class Statement(object):
    def __init__(self, user_id, year, month):
        self.user_id = user_id
        self.year = year
        self.month = month
        self.quarter = (self.month - 1) // 3
        if self.quarter == 0:
            self.quarter = 4
李宗熹's avatar
李宗熹 committed
169
        self.ifa_order, self.ifa_name, self.ifa_gender = self.order_history()
李宗熹's avatar
李宗熹 committed
170 171
        self.ifa_provision = self.provision_history()

李宗熹's avatar
李宗熹 committed
172 173 174 175 176 177 178 179 180 181
    def bill_month(self):
        return str(self.year) + '年' + str(self.month) + '月'

    def ifa_call(self):
        if self.ifa_gender == 0:
            ifa_gender = '女士'
        elif self.ifa_gender == 1:
            ifa_gender = '先生'
        else:
            ifa_gender = ''
李宗熹's avatar
李宗熹 committed
182 183 184
        if self.ifa_name is None:
            self.ifa_name = '用户'
        return ''.join([self.ifa_name, ifa_gender])
李宗熹's avatar
李宗熹 committed
185

李宗熹's avatar
李宗熹 committed
186 187
    def order_history(self):
        ifa_order = get_order_info(self.user_id)
李宗熹's avatar
李宗熹 committed
188 189 190 191
        try:
            ifa_name = ifa_order['user_name'].values[0]
        except:
            ifa_name = '用户'
李宗熹's avatar
李宗熹 committed
192 193 194 195
        try:
            ifa_gender = ifa_order['value_sex'].values[0]
        except:
            ifa_gender = 2
李宗熹's avatar
李宗熹 committed
196 197 198
        end_date = get_end_date(self.year, self.month)
        order_history = ifa_order[ifa_order['pay_date'] < end_date]
        # ifa_order['fund_name'] = ifa_order['fund_id'].apply(lambda x: get_fund_name(x, fund_type=2).values[0][0])
李宗熹's avatar
李宗熹 committed
199
        return order_history, ifa_name, ifa_gender
李宗熹's avatar
李宗熹 committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213

    def provision_history(self):
        ifa_provision = get_provision_info(self.user_id)
        end_date = get_end_date(self.year, self.month)
        provision_history = ifa_provision[ifa_provision['predict_date'] < end_date.date()]
        return provision_history

    def process_provision(self):
        year, month_list = get_month_list(self.quarter, self.year)
        start_date = date(year=year, month=min(month_list), day=1)
        end_date = get_end_date(year, max(month_list))
        provision_quarterly = self.ifa_provision[
            (self.ifa_provision['predict_date'] >= start_date) &
            (self.ifa_provision['predict_date'] < end_date.date())]
214
        return provision_quarterly
李宗熹's avatar
李宗熹 committed
215 216 217 218 219 220 221

    def trade_record(self):
        ifa_cus_order_info = list(self.ifa_order.groupby(self.ifa_order.customer_id))

        trade_record_data = []
        for customer in ifa_cus_order_info:
            customer_df = customer[1]
222
            customer_df = customer_df[customer_df['order_type']!=4]
李宗熹's avatar
李宗熹 committed
223 224 225 226
            df_length = customer_df['fund_id'].count()
            detail = []

            for i in range(df_length):
227
                detail.append({'fund': get_fund_name(customer_df['fund_id'].values[i]),
李宗熹's avatar
李宗熹 committed
228 229 230 231 232 233 234 235 236
                               'pay_date': np.datetime_as_string(customer_df['pay_date'].values[i], unit='D'),
                               'confirm_share_date': np.datetime_as_string(customer_df['confirm_share_date'].values[i],
                                                                           unit='D'),
                               'confirm_amount': customer_df['confirm_amount'].values[i],
                               'nav': customer_df['nav'].values[i],
                               'confirm_share': customer_df['confirm_share'].values[i],
                               'note': type2note(customer_df['order_type'].values[i])
                               })

李宗熹's avatar
李宗熹 committed
237
            total_amount = cal_total_amount(customer_df)
李宗熹's avatar
李宗熹 committed
238
            trade_record_data.append({'customer': customer_df['customer_name'].values[0],
239
                                      'total_amount': Decimal(round(float(total_amount) / 10000.0, 6)),
李宗熹's avatar
李宗熹 committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                                      'detail': detail})

        return trade_record_data

    def month_remain(self):
        year, month_list = get_month_list(self.quarter, self.year)
        month_remain_data = {}
        month_detail = []
        quarter_amount = 0
        for month in month_list:
            end_date = get_end_date(year, month)
            order_history = self.ifa_order[self.ifa_order['pay_date'] < end_date]
            df_length = order_history['fund_id'].count()

            if df_length > 0:
                month_amount = cal_total_amount(order_history)
            else:
                month_amount = 0

            single_month = {'month': str(month) + '月', 'month_amount': month_amount}
            quarter_amount += month_amount
            month_detail.append(single_month)

        quarter = num2chinese(self.quarter)
        month_detail.append(
            {'month': quarter + '季度月均存量', 'month_amount': Decimal(round(float(quarter_amount) / 3.0, 2))})
        month_remain_data['month_detail'] = month_detail

        bonus_policy = []
        bonus_policy.append({'month_achieve': '达到1000万以上', 'bonus_policy_item': '标准管理费分成+0.1%'})
李宗熹's avatar
李宗熹 committed
270 271 272 273
        bonus_policy.append({'month_achieve': '达到2000万以上', 'bonus_policy_item': '标准管理费分成+0.15%'})
        bonus_policy.append({'month_achieve': '达到3000万以上', 'bonus_policy_item': '标准管理费分成+0.2%'})
        bonus_policy.append({'month_achieve': '达到4000万以上', 'bonus_policy_item': '标准管理费分成+0.25%'})
        bonus_policy.append({'month_achieve': '达到5000万以上', 'bonus_policy_item': '标准管理费分成+0.3%'})
李宗熹's avatar
李宗熹 committed
274 275
        month_remain_data['bonus_policy'] = bonus_policy

李宗熹's avatar
李宗熹 committed
276
        bonus_image = []
277 278 279 280 281
        bonus_image.append({'goal_value': round(float(quarter_amount)/3.0/500000.0,2), 'goal': '5000万目标'})
        bonus_image.append({'goal_value': round(float(quarter_amount)/3.0/400000.0,2), 'goal': '4000万目标'})
        bonus_image.append({'goal_value': round(float(quarter_amount)/3.0/300000.0,2), 'goal': '3000万目标'})
        bonus_image.append({'goal_value': round(float(quarter_amount)/3.0/200000.0,2), 'goal': '2000万目标'})
        bonus_image.append({'goal_value': round(float(quarter_amount)/3.0/100000.0,2), 'goal': '1000万目标'})
李宗熹's avatar
李宗熹 committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295
        month_remain_data['bonus_image'] = bonus_image
        return month_remain_data

    def subscription_fee(self):
        year, month_list = get_month_list(self.quarter, self.year)

        subscription_data = {}
        customer_detail = []
        total_before_tax = 0
        total_after_tax = 0
        start_date = datetime(year=year, month=min(month_list), day=1)
        end_date = get_end_date(year, max(month_list))
        order_quarterly = self.ifa_order[(self.ifa_order['pay_date'] >= start_date) &
                                         (self.ifa_order['pay_date'] < end_date) &
李宗熹's avatar
李宗熹 committed
296
                                         (self.ifa_order['order_type'] == 1)]
李宗熹's avatar
李宗熹 committed
297 298 299 300 301 302 303 304 305
        ifa_cus_order_monthly = list(order_quarterly.groupby(order_quarterly.customer_id))

        for customer in ifa_cus_order_monthly:
            customer_df = customer[1]
            df_length = customer_df['fund_id'].count()
            before_tax = 0
            after_tax = 0
            detail = []
            for i in range(df_length):
李宗熹's avatar
李宗熹 committed
306
                tax_rate = get_tax_rate()
李宗熹's avatar
李宗熹 committed
307 308
                if customer_df['subscription_fee'].values[i] is None:
                    continue
李宗熹's avatar
李宗熹 committed
309

310
                detail.append({'fund': get_fund_name(customer_df['fund_id'].values[i]),
李宗熹's avatar
李宗熹 committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
                               'confirm_amount': customer_df['confirm_amount'].values[i],
                               'pay_date': np.datetime_as_string(customer_df['pay_date'].values[i], unit='D'),
                               'subscription_fee': customer_df['subscription_fee'].values[i],
                               'tax': customer_df['subscription_fee'].values[i] * tax_rate
                               })

                before_tax += customer_df['subscription_fee'].values[i]
                after_tax += customer_df['subscription_fee'].values[i] * (1 - tax_rate)

            customer_detail.append({'customer': customer_df['customer_name'].values[0],
                                    'before_tax': Decimal(round(float(before_tax), 2)),
                                    'after_tax': Decimal(round(float(after_tax), 2)),
                                    'detail': detail})
            total_before_tax += before_tax
            total_after_tax += after_tax

        subscription_data['total_before_tax'] = total_before_tax
        subscription_data['total_tax'] = total_before_tax - total_after_tax
        subscription_data['total_after_tax'] = total_after_tax
        subscription_data['customer_detail'] = customer_detail

李宗熹's avatar
李宗熹 committed
332
        return subscription_data, total_after_tax
李宗熹's avatar
李宗熹 committed
333 334 335 336 337 338 339

    def manage_fee(self):
        manage_data = {}
        total_before_tax = 0
        total_after_tax = 0
        customer_detail = []

340 341 342 343
        provision_quarterly = self.process_provision()
        processed_provision = list(provision_quarterly.groupby([provision_quarterly.customer_id,
                                   provision_quarterly.fund_id]))

李宗熹's avatar
李宗熹 committed
344
        for customer_fund in processed_provision:
李宗熹's avatar
李宗熹 committed
345 346
            customer_id = customer_fund[0][0]
            customer_name = self.ifa_order[self.ifa_order['customer_id'] == customer_id]['customer_name'].values[0]
347

李宗熹's avatar
李宗熹 committed
348
            customer_fund_df = customer_fund[1]
349
            fund_id = customer_fund_df['fund_id'].values[0]
350
            fund_name = get_fund_name(fund_id)
351

李宗熹's avatar
李宗熹 committed
352 353 354 355 356 357 358 359 360
            df_length = customer_fund_df['predict_date'].count()
            before_tax = 0
            after_tax = 0
            detail = []
            for i in range(df_length):
                try:
                    tax_rate = get_tax_rate()
                except:
                    tax_rate = 0
李宗熹's avatar
李宗熹 committed
361

李宗熹's avatar
李宗熹 committed
362
                detail.append({'date': customer_fund_df['predict_date'].values[i].strftime('%Y-%m-%d'),
李宗熹's avatar
李宗熹 committed
363
                               'hold_share': customer_fund_df['retention_shares'].values[i],
李宗熹's avatar
李宗熹 committed
364 365
                               'nav': customer_fund_df['fund_nav'].values[i],
                               'manage_fee_day': customer_fund_df['manage_fee'].values[i]})
李宗熹's avatar
李宗熹 committed
366 367 368 369

                before_tax += customer_fund_df['manage_fee'].values[i]
                after_tax += customer_fund_df['manage_fee'].values[i] * (1 - tax_rate)

李宗熹's avatar
李宗熹 committed
370 371
            customer_detail.append({'customer': customer_name,
                                    'fund': fund_name,
李宗熹's avatar
李宗熹 committed
372 373 374 375 376 377 378 379 380 381
                                    'before_tax': round(float(before_tax), 2),
                                    'after_tax': round(float(after_tax), 2),
                                    'detail': detail})
            total_before_tax += before_tax
            total_after_tax += after_tax

        manage_data['total_before_tax'] = total_before_tax
        manage_data['total_tax'] = total_before_tax - total_after_tax
        manage_data['total_after_tax'] = total_after_tax
        manage_data['customer_detail'] = customer_detail
李宗熹's avatar
李宗熹 committed
382
        return manage_data, total_after_tax
李宗熹's avatar
李宗熹 committed
383

李宗熹's avatar
李宗熹 committed
384 385 386 387 388
    def carry(self):
        carry_data = {}
        total_before_tax = 0
        total_after_tax = 0
        customer_detail = []
李宗熹's avatar
李宗熹 committed
389

李宗熹's avatar
李宗熹 committed
390 391 392 393 394 395 396
        year, month_list = get_month_list(self.quarter, self.year)
        start_date = date(year=year, month=min(month_list), day=1)
        end_date = get_end_date(year, max(month_list))
        provision_quarterly = self.ifa_provision[
            (self.ifa_provision['predict_date'] >= start_date) &
            (self.ifa_provision['predict_date'] < end_date.date())]
        processed_provision = list(provision_quarterly.groupby(provision_quarterly.fund_id))
李宗熹's avatar
李宗熹 committed
397

李宗熹's avatar
李宗熹 committed
398
        for fund in processed_provision:
399

李宗熹's avatar
李宗熹 committed
400 401 402 403 404 405
            fund_id = fund[0]
            fund_df = fund[1]
            carry_sum = fund_df['permc_exc_fee'].sum()
            if carry_sum == 0:
                continue
            try:
406
                fund_name = get_fund_name(fund_id)
李宗熹's avatar
李宗熹 committed
407 408 409 410 411 412 413 414 415 416
            except:
                fund_name = fund_id

            before_tax = 0
            after_tax = 0
            detail = []
            for _, row in fund_df.iterrows():
                provision_carry = row['permc_exc_fee']
                if provision_carry == 0:
                    continue
417 418 419

                tax_rate = get_tax_rate()

李宗熹's avatar
李宗熹 committed
420 421 422 423
                customer_id = row['customer_id']
                customer_name = self.ifa_order[self.ifa_order['customer_id'] == customer_id]['customer_name'].values[0]
                order_id = row['order_id']
                order_type = type2note(self.ifa_order[self.ifa_order['order_id'] == order_id]['order_type'].values[0])
李宗熹's avatar
李宗熹 committed
424
                confirm_date = self.ifa_order[self.ifa_order['order_id'] == order_id]['confirm_share_date'].values[0]
李宗熹's avatar
李宗熹 committed
425 426
                nav = self.ifa_order[self.ifa_order['order_id'] == order_id]['nav'].values[0]
                native_amount = nav
李宗熹's avatar
李宗熹 committed
427
                provision_date = self.ifa_order[self.ifa_order['order_id'] == order_id]['confirm_share_date'].values[0]
李宗熹's avatar
李宗熹 committed
428 429
                detail.append({'customer': customer_name,
                               'order_type': order_type,
李宗熹's avatar
李宗熹 committed
430
                               'confirm_date': np.datetime_as_string(confirm_date, unit='D'),
李宗熹's avatar
李宗熹 committed
431 432
                               'native_amount': native_amount,
                               'nav': nav,
李宗熹's avatar
李宗熹 committed
433
                               'provision_date': np.datetime_as_string(provision_date, unit='D'),
434
                               'provision_carry': provision_carry}
李宗熹's avatar
李宗熹 committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                              )

                before_tax += provision_carry
                after_tax += provision_carry * (1 - tax_rate)

            customer_detail.append({
                                    'fund': fund_name,
                                    'before_tax': round(float(before_tax), 2),
                                    'after_tax': round(float(after_tax), 2),
                                    'detail': detail})
            total_before_tax += before_tax
            total_after_tax += after_tax

        carry_data['total_before_tax'] = total_before_tax
        carry_data['total_tax'] = total_before_tax - total_after_tax
        carry_data['total_after_tax'] = total_after_tax
        carry_data['customer_detail'] = customer_detail
        return carry_data, total_after_tax

    def incentive(self):
        incentive_data = {}
        total_before_tax = 0
        total_after_tax = 0
        customer_detail = []

460 461 462 463
        provision_quarterly = self.process_provision()
        processed_provision = list(provision_quarterly.groupby([provision_quarterly.customer_id,
                                   provision_quarterly.fund_id]))

李宗熹's avatar
李宗熹 committed
464 465 466 467
        for customer_fund in processed_provision:
            customer_id = customer_fund[0][0]
            customer_name = self.ifa_order[self.ifa_order['customer_id'] == customer_id]['customer_name'].values[0]
            fund_id = customer_fund[0][1]
468
            fund_name = get_fund_name(fund_id)
469

李宗熹's avatar
李宗熹 committed
470 471 472 473 474 475 476 477 478 479 480 481
            customer_fund_df = customer_fund[1]
            incentive_rate_sum = customer_fund_df['incentive_fee_ratio'].sum()
            if incentive_rate_sum == 0:
                continue
            df_length = customer_fund_df['predict_date'].count()
            before_tax = 0
            after_tax = 0
            detail = []
            for i in range(df_length):
                incentive_rate = customer_fund_df['incentive_fee_ratio'].values[i]
                if incentive_rate == 0:
                    continue
482 483

                tax_rate = get_tax_rate()
李宗熹's avatar
李宗熹 committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

                detail.append({'date': customer_fund_df['predict_date'].values[i].strftime('%Y-%m-%d'),
                               'hold_share': customer_fund_df['retention_shares'].values[i],
                               'nav': customer_fund_df['fund_nav'].values[i],
                               'incentive_day': customer_fund_df['manage_fee'].values[i] * incentive_rate})

                before_tax += customer_fund_df['manage_fee'].values[i] * incentive_rate
                after_tax += customer_fund_df['manage_fee'].values[i] * incentive_rate * (1 - tax_rate)

            customer_detail.append({'customer': customer_name,
                                    'fund': fund_name,
                                    'before_tax': round(float(before_tax), 2),
                                    'after_tax': round(float(after_tax), 2),
                                    'detail': detail})
            total_before_tax += before_tax
            total_after_tax += after_tax

        incentive_data['total_before_tax'] = total_before_tax
        incentive_data['total_tax'] = total_before_tax - total_after_tax
        incentive_data['total_after_tax'] = total_after_tax
        incentive_data['customer_detail'] = customer_detail
        return incentive_data, total_after_tax
李宗熹's avatar
李宗熹 committed
506 507 508 509

    def summary(self):
        summary_data = {}
        summary_data['bill_month'] = self.bill_month()
李宗熹's avatar
李宗熹 committed
510
        summary_data['user_name'] = self.ifa_call()
李宗熹's avatar
李宗熹 committed
511 512 513
        summary_data['quarter'] = num2chinese(self.quarter)
        summary_data['trade_record'] = self.trade_record()
        summary_data['month_remain'] = self.month_remain()
李宗熹's avatar
李宗熹 committed
514 515
        summary_data['subscription_fee'], sub_after_tax = self.subscription_fee()
        summary_data['manage_fee'], man_after_tax = self.manage_fee()
李宗熹's avatar
李宗熹 committed
516 517
        summary_data['carry'], carry_after_tax = self.carry()
        summary_data['incentive'], incentive_after_tax = self.incentive()
李宗熹's avatar
李宗熹 committed
518 519 520
        summary_data['recommend_bonus'] = {'total_before_tax': Decimal('0'),
                                           'total_after_tax': Decimal('0'),
                                           'total_tax': Decimal('0.0'),
李宗熹's avatar
李宗熹 committed
521
                                           'referral_detail':[]}
李宗熹's avatar
李宗熹 committed
522

李宗熹's avatar
李宗熹 committed
523
        summary_after_tax = sub_after_tax + man_after_tax + carry_after_tax + incentive_after_tax
李宗熹's avatar
李宗熹 committed
524 525 526 527
        summary_data['summary'] = {'total_after_tax': summary_after_tax,
                                   'detail': [{'item': "已结算申购费用", 'amount': sub_after_tax, 'note': ''},
                                              {'item': "已结算管理费用", 'amount': man_after_tax, 'note': ''},
                                              {'item': "已结算业绩报酬费用", 'amount': carry_after_tax, 'note': ''},
李宗熹's avatar
李宗熹 committed
528
                                              {'item': "已结算业绩激励奖金", 'amount': incentive_after_tax, 'note': ''},
李宗熹's avatar
李宗熹 committed
529 530 531
                                              {'item': "已结算推荐费", 'amount': Decimal('0.00'), 'note': ''},
                                              {'item': "{}年{}季度待结算佣金".format(self.year, num2chinese(self.quarter)),
                                              'amount': Decimal('0.00'), 'note': ''}
李宗熹's avatar
李宗熹 committed
532 533 534 535 536 537 538
                                              ]}
        return summary_data


if __name__ == '__main__':
    ret = Statement(user_id='USER_INFO15914346866762', year=2020, month=12).summary()
    print(json.dumps(ret, cls=DateEncoder, ensure_ascii=False))