浏览代码

财务账单对账

peng 1 年之前
父节点
当前提交
b7a64a25c9
共有 1 个文件被更改,包括 305 次插入56 次删除
  1. 305 56
      AdminController/ServeManagementController.py

+ 305 - 56
AdminController/ServeManagementController.py

@@ -5,6 +5,7 @@ import datetime
 import hashlib
 import time
 import uuid
+import json
 
 import paypalrestsdk
 import requests
@@ -47,8 +48,12 @@ class serveManagement(View):
             return self.exportCloudUserList(request_dict, response)
         elif operation == 'getCloudDataList':
             return self.getCloudDataList(request_dict, response)
-        elif operation == 'vodOrderReconcile':
-            return self.vodOrderReconcile(request, request_dict, response)
+        elif operation == 'paypalOrderReconcile':
+            return self.paypalOrderReconcile(request, request_dict, response)
+        elif operation == 'wechatOrderReconcile':
+            return self.wechatOrderReconcile(request, request_dict, response)
+        elif operation == 'alipayOrderReconcile':
+            return self.alipayOrderReconcile(request, request_dict, response)
         elif operation == 'cloudDataExport':  # 导出流失预警
             return self.cloudDataExport(request, response)
         elif operation == 'getDeviceOrderList':
@@ -987,7 +992,7 @@ class serveManagement(View):
         except Exception as e:
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
-    def vodOrderReconcile(self, request, request_dict, response):
+    def paypalOrderReconcile(self, request, request_dict, response):
 
         file = request.FILES.get('file', None)
         if not all([file]):
@@ -1005,43 +1010,44 @@ class serveManagement(View):
             start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
             end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
             wt_book = xlwt.Workbook(encoding='utf-8')
-            wt_sheet = wt_book.add_sheet('对账结果', cell_overwrite_ok=True)
+            wt_sheet = wt_book.add_sheet('paypal对账结果', cell_overwrite_ok=True)
             row_start = 0
             # 第一部分表格填写
             first_header = ['支付类型', '销售总金额', '销售总数量', '退款总额', '退款总数量', '应收金额', '平台手续费', '账务实收', '金额相差']
             for index, content in enumerate(first_header):
                 wt_sheet.write(row_start, index, content)
             row_start += 1
-            all_order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time,
-                                                      status__in=[1, 5, 6])
+            us_order_qs = Order_Model.objects.filter(addTime__gte=start_time, addTime__lt=end_time, payType=1,
+                                                     status__in=[1, 5, 6]).values('trade_no', 'orderID', 'UID',
+                                                                                  'userID__username',
+                                                                                  'userID__NickName', 'channel',
+                                                                                  'desc', 'payType',
+                                                                                  'price', 'status',
+                                                                                  'refunded_amount', 'addTime',
+                                                                                  'updTime')
+            while True:
+                eur_response = requests.get('https://www.zositeche.com/cron/compared/AnsjerOrder',
+                                            params={'time': start_time, 'end_time': end_time})
+                if eur_response.status_code == 200:
+                    result = eur_response.json()
+                    if result['result_code'] == 0:
+                        eur_order_list = result['result']
+                        break
+            all_order_qs = list(us_order_qs) + eur_order_list
+            deletion_trade_no_list = []
             trade_no_list = []
-            paid_order_qs = all_order_qs.filter(status=1)
-            for i in paid_order_qs:
-                if i.trade_no not in rd_sheet.col_values(9, 1):
-                    trade_no_list.append(i.trade_no)
-
-            # 已付款订单
-            paid = all_order_qs.filter(payType=1, status=1).aggregate(total=Sum('price'),
-                                                                      count=Count('UID'))
-            paid_total = paid['total'] if paid['total'] else 0
-            paid_count = paid['count'] if paid['count'] else 0
-            # 全额退款订单
-            refund = all_order_qs.filter(payType=1, status__in=[5, 6]).aggregate(total=Sum('refunded_amount'),
-                                                                                 count=Count('UID'))
-            refund_total = refund['total'] if refund['total'] else 0
-            refund_count = refund['count'] if refund['count'] else 0
+            for i in all_order_qs:
+                trade_no_list.append(i['trade_no'])
+                if i['trade_no'] not in rd_sheet.col_values(9, 1):
+                    deletion_trade_no_list.append(i)
             wt_sheet.write(row_start, 0, 'PayPal')
-            wt_sheet.write(row_start, 1, paid_total + refund_total)
-            wt_sheet.write(row_start, 2, paid_count + refund_count)
-            wt_sheet.write(row_start, 3, refund_total)
-            wt_sheet.write(row_start, 4, refund_count)
-            wt_sheet.write(row_start, 5, paid_total)
-            wt_sheet.write(row_start, 8, label=xlwt.Formula('f{row}-h{row}+g{row}'.format(row=row_start + 1)))
-            row_start += 1
             #  第二部分表格填写
             row_start += 2
             paypal_money = 0
+            paypal_count = 0
             fee_money = 0
+            refund_money = 0
+            refund_count = 0
             for row in range(rd_sheet.nrows):
                 if row == 0:
                     wt_sheet.write(row_start, 0, '是否匹配账单')
@@ -1051,12 +1057,128 @@ class serveManagement(View):
                         wt_sheet.write(row_start, temp_col, str(value))
                     row_start += 1
                     continue
-                if rd_sheet.cell_value(row, 0) == '合计':
+                if rd_sheet.cell_value(row, 1) == '' and rd_sheet.cell_value(row, 2) == '' and rd_sheet.cell_value(row,
+                                                                                                                   3) == '':
                     break
-                paypal_money += rd_sheet.cell_value(row, 7)
                 fee_money += rd_sheet.cell_value(row, 6)
-                transaction_id = rd_sheet.cell_value(row, 9)
-                order_qs = all_order_qs.filter(trade_no=transaction_id)
+                if rd_sheet.cell_value(row, 5) < 0:
+                    refund_money += rd_sheet.cell_value(row, 5)
+                    refund_count += 1
+                    continue
+                paypal_money += rd_sheet.cell_value(row, 5)
+                paypal_count += 1
+                if rd_sheet.cell_value(row, 9) not in trade_no_list:
+                    col_value_list = rd_sheet.row_values(row)
+                    col_value_list.insert(0, '否')
+                    for index, value in enumerate(col_value_list):
+                        wt_sheet.write(row_start, index, str(value))
+                    row_start += 1
+
+            # 第三部分表格填写
+            row_start += 1
+            third_header = ['是否匹配账单', '交易ID', '订单ID', '设备UID', '用户名', '账号昵称', '通道', '商品描述', '支付方式', '价格', '支付状态',
+                            '已退金额', '添加时间', '更新时间']
+
+            for index, content in enumerate(third_header):
+                wt_sheet.write(row_start, index, content)
+            row_start += 1
+            for item in deletion_trade_no_list:
+                values_list = item.values()
+                for col, content in enumerate(values_list):
+                    if col == 0:
+                        wt_sheet.write(row_start, col, '否')
+                    if col == 7:
+                        content = 'PayPal'
+                    if col == 9:
+                        if content == 1:
+                            content = '支付成功'
+                        elif content == 5:
+                            content = '全额退款'
+                        elif content == 6:
+                            content = '部分退款'
+                    if col in [11, 12]:
+                        content = CommonService.timestamp_to_str(int(content))
+                    wt_sheet.write(row_start, col + 1, str(content))
+                row_start += 1
+            wt_sheet.write(1, 1, paypal_money)
+            wt_sheet.write(1, 2, paypal_count + refund_count)
+            wt_sheet.write(1, 3, refund_money)
+            wt_sheet.write(1, 4, refund_count)
+            wt_sheet.write(1, 5, paypal_money + refund_money)
+            wt_sheet.write(1, 6, fee_money)
+            wt_sheet.write(1, 7, paypal_money + refund_money + fee_money)
+            wt_sheet.write(1, 8, refund_money + fee_money)
+
+            res = HttpResponse(content_type='application/vnd.ms-excel')
+            res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file.name))
+            wt_book.save(res)
+            return res
+        except Exception as e:
+            print(e)
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    def wechatOrderReconcile(self, request, request_dict, response):
+
+        file = request.FILES.get('file', None)
+        if not all([file]):
+            return response.json(444, {'error param': 'file'})
+
+        try:
+            rd_book = xlrd.open_workbook(filename=None, file_contents=file.read())
+            rd_sheet = rd_book.sheet_by_index(0)
+            date = rd_sheet.cell_value(1, 0)
+            year = int(date.split('-')[0].replace('`', ''))
+            month = int(date.split('-')[1])
+            last_day = calendar.monthrange(year, month)[1]
+            start_time = datetime.datetime(year, month, 1)
+            end_time = datetime.datetime(year, month, last_day) + datetime.timedelta(hours=24)
+            start_time = int(start_time.timestamp())
+            end_time = int(end_time.timestamp())
+            wt_book = xlwt.Workbook(encoding='utf-8')
+            wt_sheet = wt_book.add_sheet('微信对账结果', cell_overwrite_ok=True)
+            row_start = 0
+            # 第一部分表格填写
+            first_header = ['支付类型', '销售总金额', '销售总数量', '退款总额', '退款总数量', '应收金额', '平台手续费', '账务实收', '金额相差']
+            for index, content in enumerate(first_header):
+                wt_sheet.write(row_start, index, content)
+            row_start += 1
+            all_order_qs = Order_Model.objects.filter(payTime__gte=start_time, payTime__lt=end_time, payType=3,
+                                                      status__in=[1, 5, 6])
+            trade_no_list = []
+            order_id_list = []
+            for item in rd_sheet.col_values(6):
+                order_id_list.append(item.replace('`', ''))
+            for i in all_order_qs:
+                if i.orderID not in order_id_list:
+                    trade_no_list.append(i.orderID)
+            wt_sheet.write(row_start, 0, '微信')
+            #  第二部分表格填写
+            row_start += 2
+            wechat_money = 0
+            fee_money = 0
+            refund_money = 0
+            refund_count = 0
+            wechat_count = 0
+            for row in range(rd_sheet.nrows):
+                if row == 0:
+                    wt_sheet.write(row_start, 0, '是否匹配账单')
+                    for col in range(rd_sheet.ncols):
+                        value = rd_sheet.cell_value(row, col)
+                        temp_col = col + 1
+                        wt_sheet.write(row_start, temp_col, str(value))
+                    row_start += 1
+                    continue
+                if rd_sheet.cell_value(row, 0) == '总交易单数':
+                    break
+                fee_money += float(rd_sheet.cell_value(row, 22).replace('`', ''))
+                if rd_sheet.cell_value(row, 9) == '`REFUND':
+                    refund_money += float(rd_sheet.cell_value(row, 16).replace('`', ''))
+                    refund_count += 1
+                    continue
+                wechat_count += 1
+                wechat_money += float(rd_sheet.cell_value(row, 12).replace('`', ''))
+                transaction_id = rd_sheet.cell_value(row, 6).replace('`', '')
+                order_qs = all_order_qs.filter(orderID=transaction_id)
                 if not order_qs.exists():
                     col_value_list = rd_sheet.row_values(row)
                     col_value_list.insert(0, '否')
@@ -1068,13 +1190,13 @@ class serveManagement(View):
             row_start += 1
             third_header = ['是否匹配账单', '交易ID', '订单ID', '设备UID', '用户名', '账号昵称', '通道', '商品描述', '支付方式', '价格', '支付状态',
                             '已退金额', '添加时间', '更新时间']
-            diff_order_qs = all_order_qs.filter(trade_no__in=trade_no_list).values('trade_no', 'orderID', 'UID',
-                                                                                   'userID__username',
-                                                                                   'userID__NickName', 'channel',
-                                                                                   'desc', 'payType',
-                                                                                   'price', 'status',
-                                                                                   'refunded_amount', 'addTime',
-                                                                                   'updTime')
+            diff_order_qs = all_order_qs.filter(orderID__in=trade_no_list).values('trade_no', 'orderID', 'UID',
+                                                                                  'userID__username',
+                                                                                  'userID__NickName', 'channel',
+                                                                                  'desc', 'payType',
+                                                                                  'price', 'status',
+                                                                                  'refunded_amount', 'addTime',
+                                                                                  'updTime')
             for index, content in enumerate(third_header):
                 wt_sheet.write(row_start, index, content)
             row_start += 1
@@ -1084,7 +1206,128 @@ class serveManagement(View):
                     if col == 0:
                         wt_sheet.write(row_start, col, '否')
                     if col == 7:
-                        content = 'PayPal'
+                        content = '微信'
+                    if col == 9:
+                        if content == 1:
+                            content = '支付成功'
+                        elif content == 5:
+                            content = '全额退款'
+                        elif content == 6:
+                            content = '部分退款'
+                    if col in [11, 12]:
+                        content = CommonService.timestamp_to_str(int(content))
+                    wt_sheet.write(row_start, col + 1, str(content))
+                row_start += 1
+            wt_sheet.write(1, 1, wechat_money + refund_money)
+            wt_sheet.write(1, 2, wechat_count)
+            wt_sheet.write(1, 3, refund_money)
+            wt_sheet.write(1, 4, refund_count)
+            wt_sheet.write(1, 5, wechat_money)
+            wt_sheet.write(1, 6, fee_money)
+            wt_sheet.write(1, 7, wechat_money - fee_money)
+            wt_sheet.write(1, 8, fee_money + refund_money)
+
+            res = HttpResponse(content_type='application/vnd.ms-excel')
+            res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file.name))
+            wt_book.save(res)
+            return res
+        except Exception as e:
+            print(e)
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    def alipayOrderReconcile(self, request, request_dict, response):
+
+        file = request.FILES.get('file', None)
+        if not all([file]):
+            return response.json(444, {'error param': 'file'})
+
+        try:
+            rd_book = xlrd.open_workbook(filename=None, file_contents=file.read())
+            rd_sheet = rd_book.sheet_by_index(0)
+            date = rd_sheet.cell_value(3, 1)
+            year = int(date.split('-')[0])
+            month = int(date.split('-')[1])
+            last_day = calendar.monthrange(year, month)[1]
+            start_time = datetime.datetime(year, month, 1)
+            end_time = datetime.datetime(year, month, last_day) + datetime.timedelta(hours=24)
+            start_time = int(start_time.timestamp())
+            end_time = int(end_time.timestamp())
+            wt_book = xlwt.Workbook(encoding='utf-8')
+            wt_sheet = wt_book.add_sheet('支付宝对账结果', cell_overwrite_ok=True)
+            row_start = 0
+            # 第一部分表格填写
+            first_header = ['支付类型', '销售总金额', '销售总数量', '退款总额', '退款总数量', '应收金额', '平台手续费', '账务实收', '金额相差']
+            for index, content in enumerate(first_header):
+                wt_sheet.write(row_start, index, content)
+            row_start += 1
+            all_order_qs = Order_Model.objects.filter(payTime__gte=start_time, payTime__lt=end_time, payType=2,
+                                                      status__in=[1, 5, 6])
+            trade_no_list = []
+            order_id_list = []
+            for item in rd_sheet.col_values(4, 3):
+                if item not in order_id_list:
+                    order_id_list.append(item)
+            for i in all_order_qs:
+                if i.orderID not in order_id_list:
+                    trade_no_list.append(i.orderID)
+            wt_sheet.write(row_start, 0, '支付宝')
+            #  第二部分表格填写
+            row_start += 2
+            alipay_money = 0
+            fee_money = 0
+            refund_money = 0
+            refund_count = 0
+            alipay_count = 0
+            for row in range(2, rd_sheet.nrows):
+                if row == 2:
+                    wt_sheet.write(row_start, 0, '是否匹配账单')
+                    for col in range(rd_sheet.ncols):
+                        value = rd_sheet.cell_value(row, col)
+                        temp_col = col + 1
+                        wt_sheet.write(row_start, temp_col, str(value))
+                    row_start += 1
+                    continue
+                if rd_sheet.cell_value(row, 1) == '' and rd_sheet.cell_value(row, 2) == '':
+                    break
+                if rd_sheet.cell_value(row, 5) == '收费':
+                    continue
+                if rd_sheet.cell_value(row, 5) == '退款(交易退款)':
+                    refund_money += float(rd_sheet.cell_value(row, 10))
+                    refund_count += 1
+                    continue
+                fee_money += float(rd_sheet.cell_value(row, 12))
+                alipay_count += 1
+                alipay_money += float(rd_sheet.cell_value(row, 9))
+                transaction_id = rd_sheet.cell_value(row, 4)
+                order_qs = all_order_qs.filter(orderID=transaction_id)
+                if not order_qs.exists():
+                    col_value_list = rd_sheet.row_values(row)
+                    col_value_list.insert(0, '否')
+                    for index, value in enumerate(col_value_list):
+                        wt_sheet.write(row_start, index, str(value))
+                    row_start += 1
+
+            # 第三部分表格填写
+            row_start += 1
+            third_header = ['是否匹配账单', '交易ID', '订单ID', '设备UID', '用户名', '账号昵称', '通道', '商品描述', '支付方式', '价格', '支付状态',
+                            '已退金额', '添加时间', '更新时间']
+            diff_order_qs = all_order_qs.filter(orderID__in=trade_no_list).values('trade_no', 'orderID', 'UID',
+                                                                                  'userID__username',
+                                                                                  'userID__NickName', 'channel',
+                                                                                  'desc', 'payType',
+                                                                                  'price', 'status',
+                                                                                  'refunded_amount', 'addTime',
+                                                                                  'updTime')
+            for index, content in enumerate(third_header):
+                wt_sheet.write(row_start, index, content)
+            row_start += 1
+            for item in diff_order_qs:
+                values_list = item.values()
+                for col, content in enumerate(values_list):
+                    if col == 0:
+                        wt_sheet.write(row_start, col, '否')
+                    if col == 7:
+                        content = '支付宝'
                     if col == 9:
                         if content == 1:
                             content = '支付成功'
@@ -1096,8 +1339,14 @@ class serveManagement(View):
                         content = CommonService.timestamp_to_str(int(content))
                     wt_sheet.write(row_start, col + 1, str(content))
                 row_start += 1
+            wt_sheet.write(1, 1, alipay_money)
+            wt_sheet.write(1, 2, alipay_count)
+            wt_sheet.write(1, 3, refund_money)
+            wt_sheet.write(1, 4, refund_count)
+            wt_sheet.write(1, 5, alipay_money - refund_money)
             wt_sheet.write(1, 6, fee_money)
-            wt_sheet.write(1, 7, paypal_money)
+            wt_sheet.write(1, 7, alipay_money - fee_money - refund_money)
+            wt_sheet.write(1, 8, fee_money + refund_money)
 
             res = HttpResponse(content_type='application/vnd.ms-excel')
             res['Content-Disposition'] = 'attachment; filename={}'.format(escape_uri_path(file.name))
@@ -1964,21 +2213,21 @@ class serveManagement(View):
                 #  AI套餐
                 # if orderType == '1' and payType != '10':
                 #     return response.json(10059)
-                    # order_qs = Order_Model.objects.filter(orderID=orderID, userID__username=userName, UID=uid).values(
-                    #     'ai_rank_id')
-                    # order_qs = order_qs.objects.filter(UID=uid)
-                    # ai_service_qs = AiService.objects.filter(uid=uid, use_status=1).values('addTime', 'endTime')
-                    # ai_service_number = ai_service_qs.count()
-                    # if ai_service_number <= 1:
-                    #     ai_service_qs.update(endTime=nowTime)
-                    #     return response.json(0)
-                    # # 当设备套餐不唯一时
-                    # ai_service_qs = AiService.objects.filter(uid=uid, bucket_id=order_qs[0]['ai_rank_id'])
-                    # ai_serverice_number = ai_service_qs.count()
-                    # if ai_serverice_number == 1:
-                    #     ai_service_qs.update(endTime=nowTime)
-                    #     return response.json(0)
-                    # return response.json(10059)  # 未使用套餐类型重复
+                # order_qs = Order_Model.objects.filter(orderID=orderID, userID__username=userName, UID=uid).values(
+                #     'ai_rank_id')
+                # order_qs = order_qs.objects.filter(UID=uid)
+                # ai_service_qs = AiService.objects.filter(uid=uid, use_status=1).values('addTime', 'endTime')
+                # ai_service_number = ai_service_qs.count()
+                # if ai_service_number <= 1:
+                #     ai_service_qs.update(endTime=nowTime)
+                #     return response.json(0)
+                # # 当设备套餐不唯一时
+                # ai_service_qs = AiService.objects.filter(uid=uid, bucket_id=order_qs[0]['ai_rank_id'])
+                # ai_serverice_number = ai_service_qs.count()
+                # if ai_serverice_number == 1:
+                #     ai_service_qs.update(endTime=nowTime)
+                #     return response.json(0)
+                # return response.json(10059)  # 未使用套餐类型重复
                 #  联通4G套餐
                 if orderType == '2' and payType != '10':
                     now_time = int(time.time())