当前位置: 首页 > 工具软件 > Dolphin Mini > 使用案例 >

GBA dolphin

柳景胜
2023-12-01
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Monox
 @Email: 627201584@qq.com
 @FileName: 20221207.py
 @DateTime: 2022/12/6 21:07
 @SoftWare: PyCharm
"""

import PySimpleGUI as sg
import xlwt
import hashlib
import json
from urllib.parse import urlencode
import pandas as pd
import requests
import urllib.parse
from requests.adapters import HTTPAdapter
from datetime import datetime
import threading


def shouye():
    """
    001
    首页函数
    """
    global GYurl
    GYurl = 'http://v2.api.guanyierp.com/rest/erp_open'  # 注册
    global GYappkey
    GYappkey = ''  # 注册
    global GYsecret
    GYsecret = ''  # 注册
    global GYsessionkey
    GYsessionkey = ''  # 注册
    global GYtenantcode
    GYtenantcode = ''  # 租户代码  # 注册
    global GYtenantname
    GYtenantname = ''  # 租户名称  # 注册
    global GYenvironment
    GYenvironment = 'V2'  # 租户环境  # 注册
    global Version
    Version = '10.0'  # 工具版本号
    global DueDate
    DueDate = '2023-12-07'  # 到期日期  # 注册
    DueDate_time = datetime.strptime(DueDate, '%Y-%m-%d').date()  # 到期日期
    global nowday
    nowday = datetime.now().date()
    global TimeRemaining
    TimeRemaining = int((DueDate_time-nowday).days)  # 剩余时间  # 注册



def main():
    """
    002
    软件主函数
    """

    shouye()

    # 首先设置窗口样式
    sg.theme('Reddit')
    # sg.theme('SystemDefaultForReal')LightGray1 Reddit
    # 创建布局
    fra_layout1 = [
        [sg.Text('租户代码', size=(10, 1)), sg.Input(GYtenantcode, key='-GYtenantcode-', size=(35, 1), disabled=True)],
        [sg.Text('租户名称', size=(10, 1)), sg.Input(GYtenantname, key='-GYtenantname-', size=(35, 1), disabled=True)],
        [sg.Text('租户环境', size=(10, 1)), sg.Input(GYenvironment, key='-GYenvironment-', size=(35, 1), disabled=True)],
        [sg.Btn('登陆', key='-Login-')]
    ]
    fra_layout2 = [
        [sg.Text('版本号', size=(10, 1)), sg.Text(Version, size=(35, 1))],
        [sg.Text('到期日期', size=(10, 1)), sg.Input(DueDate, size=(35, 1), disabled=True)],
        [sg.Text('剩余时间', size=(10, 1)), sg.Input(str(TimeRemaining) + '天', size=(35, 1), disabled=True)]
    ]
    layout1 = [[sg.Frame(title='管易云授权信息', layout=fra_layout1)],
               [sg.Frame(title='软件信息', layout=fra_layout2)]]
    # 窗口实例化 并设置窗口名,把布局内容放进去
    window1 = sg.Window('湾豚自动新增退货单管易专版', layout1, font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
    # 进入WIN1窗口循环
    while True:
        event, values = window1.read()  # 读取窗口所有内容,event为动作
        print("event:", event, "values:", values)
        if event == '-Login-':
            if TimeRemaining < 0:
                sg.popup('软件已到期,请联系售后续费', title='湾豚', font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
            else:
                window1.Hide()
                Format_List = ['排重平台单号', '不排重平台单号']
                huanhuo_List = ['新增换货类型订单', '不新增换货类型订单']
                fra1 = [
                    # sg.InputText(visible=False, key='-xiazai-'), sg.FileSaveAs('下载模板', target='-xiazai-')
                    [sg.Text('导入文件'), sg.InputText(size=(54, 1), key='-daoru-'),
                     sg.FileBrowse("导入", disabled=False, key='-Import-', size=(5, 1), file_types=(('EXCEL', '.xls'),))],
                    [sg.Text('批量备注'), sg.InputText(default_text=str(nowday) + '工具导入', size=(54, 1), key='-remarks-')],
                    [sg.Text('仓库代码'), sg.InputText(size=(54, 1), key='-warehousein_code-')],
                    [sg.Text('排重需求'), sg.Combo(Format_List, size=(30, 1), key='-Format-')],
                    [sg.Btn('提交', size=(5, 1), disabled=False, key='-Submit-')]
                ]
                fra2 = [
                    # sg.InputText(visible=False, key='-xiazai-'), sg.FileSaveAs('下载模板', target='-xiazai-')
                    [sg.Text('下载目录'), sg.InputText(size=(54, 1), key='-xiazai-'),
                     sg.FileSaveAs('另存为', size=(5, 1), file_types=(('EXCEL', '.xls'),))],
                    [sg.Btn('下载', size=(5, 1))]
                ]
                lc = 0  # 进度条默认长度
                fra3 = [
                    [sg.Text('任务完成进度')],
                    [sg.ProgressBar(lc, orientation='h', size=(55, 20), key='progressbar')],
                    [sg.ML(
                        default_text="",
                        # 默认显示的文本
                        disabled=True,
                        # 元素禁用状态设定
                        reroute_stdout=False,
                        # print语句内容会显示在此文本框内
                        reroute_cprint=True,
                        # 使用cprint将内容打印到此文本框内。详细参考sg.cprint()
                        size=(68, 20),
                        # 宽度和行高设定
                        key='-ml-'
                    )]
                ]
                layout2 = [[sg.B("导入退货单界面"), sg.B("下载导入模板")],
                           [sg.Frame(title='先点击导入选择文件,再点击提交', layout=fra1, key='-fra1-'),
                            sg.Frame(title='先点击另存为选择目录,再点击下载', layout=fra2, key='-fra2-', visible=False)],
                           [sg.Frame(title='任务中心', layout=fra3, key='-fra3-')],
                           ]
                # 窗口实例化 并设置窗口名,把布局内容放进去
                window2 = sg.Window('湾豚自动新增退货单管易专版', layout2, font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
                # 根据key值获取到进度条
                progress_bar = window2['progressbar']
                Submit = window2['-Submit-']
                Import = window2['-Import-']
                # 进入WIN2窗口循环
                while True:
                    event, values = window2.read()  # 读取窗口所有内容,event为动作
                    print("event:", event, "values:", values)
                    if event is None:  # WIN2窗口的右上关闭动作即None
                        break

                    if event == '下载导入模板':
                        window2['-fra2-'].update(visible=True)
                        window2['-fra1-'].update(visible=False)
                        window2['-fra3-'].update(visible=False)

                    if event == '导入退货单界面':
                        window2['-fra1-'].update(visible=True)
                        window2['-fra3-'].update(visible=True)
                        window2['-fra2-'].update(visible=False)

                    if event == '-Submit-':  # 点击提交
                        # print(values['-daoru-'])
                        # progress_bar.UpdateBar(0,100)
                        x = values['-daoru-']  # 导入路径
                        y = values['-Format-']  # 排重选择

                        if len(x) == 0 or len(y) == 0:
                            sg.popup('错误操作,注意导入文件或排重需求不能为空', title='错误', font=('微软雅黑', 10), icon='ico\GBAdolphin.ico')
                        else:
                            remarks = values['-remarks-']
                            warehousein_code = values['-warehousein_code-']
                            # print(len(x))
                            Submit.update(disabled=True)
                            Import.update(disabled=True)
                            window2['-daoru-'].update(value='')
                            # num2maint1 = threading.Thread(target=num2main, args=(x, progress_bar, remarks, window2,), daemon=True)
                            if y == '排重平台单号':
                                try:
                                    num2maint1 = threading.Thread(target=num3main, args=(
                                    x, progress_bar, remarks, warehousein_code, window2, Submit, Import), daemon=True)
                                    num2maint1.start()
                                    # Submit.update(disabled=False)
                                    # Import.update(disabled=False)
                                    # window2['-daoru-'].update(value='')
                                except Exception as e:
                                    sg.popup('错误操作,注意导入文件不能为空,或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                             icon='ico\GBAdolphin.ico')
                                    print("报错1:", e)
                                    Submit.update(disabled=False)
                                    Import.update(disabled=False)
                            elif y == '不排重平台单号':
                                try:
                                    num2maint1 = threading.Thread(target=num2main, args=(
                                    x, progress_bar, remarks, warehousein_code, window2, Submit, Import), daemon=True)
                                    num2maint1.start()
                                    # Submit.update(disabled=False)
                                    # Import.update(disabled=False)
                                    # window2['-daoru-'].update(value='')
                                except Exception as e:
                                    sg.popup('错误操作,注意导入文件不能为空,或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                             icon='ico\GBAdolphin.ico')
                                    print("报错1:", e)
                                    Submit.update(disabled=False)
                                    Import.update(disabled=False)
                    if event == '下载':
                        try:
                            # print(values['-xiazai-'])
                            mbml = values['-xiazai-']
                            nwb = xlwt.Workbook('utf-8')  # 新建工作簿
                            nws = nwb.add_sheet('Sheet1')  # 新建工作表
                            nws.write(0, 0, '平台单号')
                            nwb.save(mbml)
                            sg.popup_auto_close('模板已下载', icon='ico\GBAdolphin.ico')
                        except Exception as e:
                            sg.popup('错误操作,注意下载目录不能为空,或者联系技术处理', title='错误', font=('微软雅黑', 10),
                                     icon='ico\GBAdolphin.ico')
                            print("报错2:", e)

                    if event == '任务已完成':
                        sg.popup_auto_close('任务已完成', icon='ico\GBAdolphin.ico')

                window2.close()

        if event == None:  # WIN1窗口的右上关闭动作即None
            break

    window1.close()


def readExcel_pandas(x):
    """
    003
    读取EXCEL平台单号文件
    """
    excel_file = x  # 文件变量
    data = pd.read_excel(excel_file)  # 读取EXCEL文件
    platform_codeList = data['平台单号'].values  # EXCEL文件中指定列转为列表
    # print(datalist)
    print('一共有' + str(len(platform_codeList)) + '张单号')
    return platform_codeList


def tradereturnget01(platform_code):
    """
    003
    退货单查询,判断平台单号是否重复
    """
    method = "gy.erp.trade.return.get"
    cancel = 0
    detail_flag = False
    List1 = ["appkey", "sessionkey", "method", "platform_code", "cancel", "detail_flag"]
    List2 = [GYappkey, GYsessionkey, method, str(platform_code), cancel, detail_flag]
    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
    # print(f'dictdata{dictdata}')
    dictdata2 = NoJson(dictdata)
    dictdata3 = GYsecret + dictdata2 + GYsecret
    sign = genearteMD5(dictdata3)
    dictdata.setdefault("sign", sign)
    # print(dictdata)
    jsondata = NoJson(dictdata)
    # print(jsondata)
    return jsondata


def tradereturnget02(jsondata):
    response = RequestsApi(jsondata)
    total = response.get('total')
    return total


def datagy01(x):
    """
    003
    构造第一次请求data,method = "gy.erp.trade.get"
    """
    platform_code = str(x)
    method = "gy.erp.trade.get"
    List1 = ["appkey", "sessionkey", "method", "platform_code"]
    List2 = [GYappkey, GYsessionkey, method, platform_code]
    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
    dictdata2 = NoJson(dictdata)
    dictdata3 = GYsecret + dictdata2 + GYsecret
    sign = genearteMD5(dictdata3)
    dictdata.setdefault("sign", sign)
    # print(dictdata)
    jsondata = NoJson(dictdata)
    # print(jsondata)
    return jsondata


def datagy02(x):
    """
    003
    构造历史请求data,method = "gy.erp.trade.history.get"
    """
    platform_code = str(x)
    method = "gy.erp.trade.history.get"
    List1 = ["appkey", "sessionkey", "method", "platform_code"]
    List2 = [GYappkey, GYsessionkey, method, platform_code]
    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
    dictdata2 = NoJson(dictdata)
    dictdata3 = GYsecret + dictdata2 + GYsecret
    sign = genearteMD5(dictdata3)
    dictdata.setdefault("sign", sign)
    # print(dictdata)
    jsondata = NoJson(dictdata)
    # print(jsondata)
    return jsondata


def datagy03(x):
    """
    003
    调用发货单查询 ,method = "gy.erp.trade.deliverys.get"
    """
    code = str(x)
    method = "gy.erp.trade.deliverys.get"
    List1 = ["appkey", "sessionkey", "method", "code"]
    List2 = [GYappkey, GYsessionkey, method, code]
    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
    dictdata2 = NoJson(dictdata)
    dictdata3 = GYsecret + dictdata2 + GYsecret
    sign = genearteMD5(dictdata3)
    dictdata.setdefault("sign", sign)
    # print(dictdata)
    jsondata = NoJson(dictdata)
    # print(jsondata)
    return jsondata


def datagy04(x):
    """
    003
    调用历史发货单查询 ,method = "gy.erp.trade.deliverys.history.get"
    """
    code = str(x)
    method = "gy.erp.trade.deliverys.history.get"
    List1 = ["appkey", "sessionkey", "method", "code"]
    List2 = [GYappkey, GYsessionkey, method, code]
    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
    dictdata2 = NoJson(dictdata)
    dictdata3 = GYsecret + dictdata2 + GYsecret
    sign = genearteMD5(dictdata3)
    dictdata.setdefault("sign", sign)
    # print(dictdata)
    jsondata = NoJson(dictdata)
    # print(jsondata)
    return jsondata


def RequestsApi(data):
    """
    003
    请求Requests
    """
    print("请求报文:", data)
    payload = urllib.parse.quote(str(data))  # 转义特殊字符
    url = GYurl
    headers = {
        'Content-Type': 'application/json'
    }
    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))  # 设置重试次数为3次
    s.mount('https://', HTTPAdapter(max_retries=3))
    try:
        response = requests.request("POST", url, headers=headers, data=payload, timeout=15)
        print("返回报文:", response.text)  # 不用显示出来
        pyresponse = json.loads(response.text)  # json转python
        # print(pyresponse)  # 不用显示出来
        return pyresponse
    except Exception as e:
        print("请求Requests出现错误:", e)
        pyresponse = {'total': -1, 'deliverys': []}
        return pyresponse


def NoJson(a):
    """
    003
    转为没有空格的json格式
    """
    jsonData = json.dumps(a, separators=(',', ':'), ensure_ascii=False)  # 转为json,没有空格
    return jsonData


def genearteMD5(str):
    """
    003
    生成MD5(MD5加密)返回sign
    """
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为:hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))

    # print('MD5加密前为 :' + str)
    # print('MD5加密后为 :' + hl.hexdigest())
    return hl.hexdigest()  # 返回sign


def sjqx(code, platform_code, response, remarks, warehousein_code):
    """
    003
    数据清洗
    """
    List1 = response.get("deliverys")
    # print(List1)
    if len(List1) > 0:
        for dict1 in List1:  # 列表遍历
            # print(dict1)
            trade_code = code  # 销售订单编号
            shop_code = dict1.get("shop_code")  # 店铺代码
            warehousein_code = warehousein_code
            vip_code = dict1.get("vip_code")# 会员代码
            trade_platform_code = platform_code  # 平台单号
            businessman_code = ""
            refund_phase = 1
            return_type = 1
            type_code = "7001"  # 需要客户提前新增退货原因代码
            express_name = dict1.get("express_name")  # 在明细表
            express_num = dict1.get("express_no")  # 在明细表
            receiver_name = dict1.get("receiver_name")  # 收货人姓名
            receiver_mobile = dict1.get("receiver_mobile")
            receiver_phone = dict1.get("receiver_phone")
            area_list = dict1.get('area_name').split('-')
            receiver_province = area_list[0]
            receiver_city = area_list[1]
            receiver_district = area_list[2]
            receiver_address = dict1.get("receiver_address")
            note = remarks
            # print(dict1["details"])
            details1 = dict1.get("details")  # 赋值商品明细列表
            refund_detail = [
                {'pay_type_code': 'zhifubao', 'payment': float(dict1.get('payment') + dict1.get('unpaid_amount'))}]
            item_detail = []
            for details2 in details1:
                # trade_code = details2["trade_code"]
                # trade_platform_code = details2["platform_code"]  # 取表头的
                # print(type(details2))  # <class 'dict'>
                detail_batch = details2.get("detail_batch")
                # print("detail_batch:", detail_batch)
                if detail_batch == None or detail_batch == []:
                    # print("没有批次")
                    platform_code = details2["platform_code"]
                    qty = int(details2["qty"])
                    batch_code = ""
                    production_time = ""
                    valid_time = ""
                    warehousing_time = ""
                    item_code = details2["item_code"]
                    sku_code = details2["sku_code"]
                    amount = float(details2["amount_after"])
                    amountAfter = float(details2["amount_after"])
                    price = float(amountAfter / qty)
                    List1 = ["platform_code", "item_code", "sku_code", "qty", "price", "amount", "amountAfter",
                             "batch_code", "production_time", "valid_time", "warehousing_time", "note"]
                    List2 = [platform_code, item_code, sku_code, qty, price, amount, amountAfter, batch_code,
                             production_time, valid_time, warehousing_time, platform_code]
                    dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
                    item_detail.append(dictdata)
                else:
                    # print("有批次")
                    for ibatch in detail_batch:  # 遍历批次信息
                        qty = int(ibatch["qty"])
                        batch_code = ibatch["batchNumber"]
                        production_time = ibatch["productionTime"]
                        valid_time = ibatch["validTime"]
                        warehousing_time = ibatch["warehousingTime"]
                        item_code = details2["item_code"]
                        sku_code = details2["sku_code"]
                        amount = float(details2["amount_after"])
                        amountAfter = float(details2["amount_after"])
                        price = float(amountAfter / qty)
                        List1 = ["platform_code", "item_code", "sku_code", "qty", "price", "amount", "amountAfter",
                                 "batch_code", "production_time", "valid_time", "warehousing_time", "note"]
                        List2 = [platform_code, item_code, sku_code, qty, price, amount, amountAfter, batch_code,
                                 production_time, valid_time, warehousing_time, platform_code]
                        dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
                        item_detail.append(dictdata)

                # item_code = details2["item_code"]
                # sku_code = details2["sku_code"]
                # # qty = int(details2["qty"])
                # amount = float(details2["amount_after"])
                # amountAfter = float(details2["amount_after"])
                # price = float(details2["amount_after"]/qty)
                # List1 = ["item_code", "sku_code", "qty", "price", "amount", "amountAfter"]
                # List2 = [item_code, sku_code, qty, price, amount, amountAfter]
                # dictdata = dict(zip(List1, List2))  # 两个列表合并为字典
                # refund_detail.append(dictdata)

            # deliverys1 = dict1["deliverys"]  # 赋值发货信息列表  # 在表头
            # for deliverys2 in deliverys1:  # 在表头
            #     express_name = deliverys2["express_name"]  # 在明细表
            #     express_num = deliverys2["mail_no"]  # 在明细表

        print(item_detail)
        print(f"item_detail:{item_detail}")
        item_detail2 = item_detail_Merge(item_detail)  # 太力定制的排重
        print(f"item_detail2:{item_detail2}")

        method = "gy.erp.trade.return.add"
        List3 = ["appkey", "sessionkey", "method", "shop_code", "warehousein_code", "vip_code", "trade_code",
                 "trade_platform_code", "businessman_code", "refund_phase", "return_type", "type_code", "express_name", "express_num", "receiver_name", "receiver_mobile",
                 "receiver_phone", "receiver_province", "receiver_city", "receiver_district", "receiver_address", "note", "item_detail", "refund_detail"]
        List4 = [GYappkey, GYsessionkey, method, shop_code, warehousein_code, vip_code, trade_code, trade_platform_code, businessman_code, refund_phase, return_type,
                 type_code, express_name, express_num, receiver_name, receiver_mobile, receiver_phone, receiver_province, receiver_city, receiver_district, receiver_address,
                 note, item_detail2, refund_detail]
        dictdata2 = dict(zip(List3, List4))  # 两个列表合并为字典
        return dictdata2
    elif len(List1) == 0:
        dictdata2 = {"appkey": "", "sessionkey": "", "method": "", "shop_code": "", "vip_code": "", "trade_code": "",
                     "trade_platform_code": "", "type_code": "", "express_name": "", "express_num": "",
                     "receiver_name": "", "receiver_address": "", "note": "", "item_detail": ""}
        print('该订单的发货单列表为空!')
        return dictdata2
        #     print("出现错误:", e)
        # else:
        #     print("正常!")
        # finally:
        #     print("执行完毕")


# def item_detail_Merge(item_detail):
#     """
#     003
#     item_detail商品明细根据商品代码进行排重处理
#     """
#     print(item_detail)
#     info_dic = {}
#     for d in item_detail:
#         if d['item_code'] not in info_dic:
#             info_dic[d['item_code']] = str(d['qty']) +',' + str(d['price']) +',' + str(d['amount']) +',' + str(d['amountAfter'])
#         else:
#             list1 = info_dic[d['item_code']].split(",")
#             info_dic[d['item_code']] = str(int(list1[0]) + d['qty']) +',' + str(float(list1[1]) + d['price']) +',' + str(float(list1[2]) + d['amount']) +',' + str(float(list1[3]) + d['amountAfter'])
#     print(f"info_dic:{info_dic}")
#     new_info = []
#     for n, v in info_dic.items():
#         list1 = v.split(",")
#         new_info.append({'item_code': n,
#                          'qty': int(list1[0]),  # 数量
#                          'price': float(float(list1[2])/int(list1[0])),  # 单价
#                          'amount': float(list1[2]),  # 实际金额
#                          'amountAfter': float(list1[3])})  # 让利后金额
#     print(f"new_info:{new_info}")
#     return new_info
def item_detail_Merge(item_detail):
    """
    003
    item_detail商品明细根据商品代码进行排重处理
    """
    # print(f'原始item_detail:{item_detail}')
    info_dic = {}
    for d in item_detail:  # 遍历原始item_detail,d为字典
        d2 = f"{d.get('item_code')},{d.get('batch_code')},{d.get('production_time')},{d.get('valid_time')},{d.get('warehousing_time')}"  # 这个作为判断唯一的id
        if d2 not in info_dic:  # 如果d2不在info_dic字典内
            # info_dic[d2] = str(d['qty']) +',' + str(d['price']) +',' + str(d['amount']) +',' + str(d['amountAfter'])
            info_dic[d2] = f"{d.get('qty')},{d.get('price')},{d.get('amount')},{d.get('amountAfter')}"
            # print(f"不在,info_dic[d['item_code']]:{info_dic[d['item_code']]}")
        else:  # 如果d2在info_dic字典内
            list1 = info_dic.get(d2).split(",")
            # info_dic[d2] = str(int(list1[0]) + d['qty']) +',' + str(float(list1[1]) + d['price']) +',' + str(float(list1[2]) + d['amount']) +',' + str(float(list1[3]) + d['amountAfter'])
            info_dic[
                d2] = f"{str(int(list1[0]) + d.get('qty'))},{str(float(list1[1]) + d.get('price'))},{str(float(list1[2]) + d.get('amount'))},{str(float(list1[3]) + d.get('amountAfter'))}"
            # print(f"else,info_dic[d['item_code']]:{info_dic[d['item_code']]}")
    # print(f"info_dic:{info_dic}")
    # info_dic:{'P.TS0044': '5,0.0,0.0,0.0', 'P.TS0043': '13,399.0,3990.0,3990.0'}
    new_info = []
    for n, v in info_dic.items():
        list_n = n.split(",")
        list_v = v.split(",")
        new_info.append({'item_code': list_n[0],
                         'batch_code': list_n[1],
                         'production_time': list_n[2],
                         'valid_time': list_n[3],
                         'warehousing_time': list_n[4],
                         'qty': int(list_v[0]),  # 数量
                         'price': float(float(list_v[2]) / int(list_v[0])),  # 单价
                         'amount': float(list_v[2]),  # 实际金额
                         'amountAfter': float(list_v[3])})  # 让利后金额
    # print(f"new_info:{new_info}")
    # new_info:[{'item_code': 'P.TS0044', 'qty': 5, 'price': 0.0, 'amount': 0.0, 'amountAfter': 0.0}, {'item_code': 'P.TS0043', 'qty': 13, 'price': 306.9230769230769, 'amount': 3990.0, 'amountAfter': 3990.0}]
    return new_info


# 退货同步
def tbth(x):
    """
    003
    数据清洗
    """
    # print(x)
    jsonData = NoJson(x)
    jsonData2 = GYsecret + jsonData + GYsecret
    sign = genearteMD5(jsonData2)
    try:
        x.setdefault("sign", sign)
        # print(x)sg.popup_scrolled
        jsondata3 = NoJson(x)
        # print(jsondata3)
        return jsondata3
    except Exception as e:
        print("这里出错4:", e)
        # print("出现错误:", e)
    # else:
    #     print("正常!")
    # finally:
    #     print("执行完毕")


def log(logdata):
    """
    003
    日志函数
    """
    with open("log.txt", "a") as log:
        log.write(str(datetime.now()) + " " + str(logdata) + "\n\n")


def in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code):
    """
    003
    根据SDO单号先调用7天内发货单查询,如果total返回大于1,那么继续执行后续同步操作,如果total返回等于0,那么执行7天之前的发货单查询
    然后根据SDO单号调用7天之前的发货单查询,如果total返回大于1,那么继续执行后续同步操作,如果total返回等于0,那么响应没有该平台单号或者同步失败
    """
    FHD = datagy03(delivery_Code)  # 构造7天之内发货单请求参数
    FHDresponse = RequestsApi(FHD)  # 调用管易接口
    total = FHDresponse.get("total")
    print("7天之内发货单的total返回:", total)
    if total > 0:  # 代表7天之内发货单有
        FHDdictdata = sjqx(code=code, platform_code=platform_code, response=FHDresponse, remarks=remarks,
                           warehousein_code=warehousein_code)  # 数据清洗
        jsondata3 = tbth(FHDdictdata)  # 同步退货单for
        pyresponse = RequestsApi(jsondata3)
        logdata = success(platform_code, pyresponse)  # 判断是否同步成功并返回日志
        print(logdata)  # 打印日志
        sg.cprint(logdata)  # GUI打印更改到这里使用
        log(logdata)  # 生成日志文件
        return logdata  # 返回日志
    elif total == 0:  # 代表历史发货单查询
        FHD = datagy04(delivery_Code)  # 构造历史发货单请求参数
        FHDresponse = RequestsApi(FHD)  # 调用管易接口
        FHDdictdata = sjqx(code=code, platform_code=platform_code, response=FHDresponse, remarks=remarks,
                           warehousein_code=warehousein_code)  # 数据清洗
        jsondata3 = tbth(FHDdictdata)  # 同步退货单
        pyresponse = RequestsApi(jsondata3)
        logdata = success(platform_code, pyresponse)  # 判断是否同步成功并返回日志
        print(logdata)  # 打印日志
        sg.cprint(logdata)  # GUI打印更改到这里使用
        log(logdata)  # 生成日志文件
        return logdata  # 返回日志

    else:
        print("total数为:", total, "平台单号", platform_code, "接口处理失败")
        logdata = "平台单号" + str(platform_code) + ",系统没有发货单"
        sg.cprint(logdata)  # GUI打印更改到这里使用
        log(logdata)
        return logdata


def success(platform_code, pyresponse):
    """
    003
    判断是否同步成功并返回日志
    """
    success = pyresponse.get("success")
    if success == True:
        try:
            code = pyresponse.get("code")
            logdata = "平台单号" + str(platform_code) + "同步成功,退货单号为:" + str(code)
        except Exception as e:
            logdata = "平台单号" + str(platform_code) + ",接口处理失败"
        finally:
            return logdata
    elif success == False:
        try:
            errorDesc = pyresponse.get("errorDesc")
            logdata = "平台单号" + str(platform_code) + "同步失败,报错:" + str(errorDesc)
        except Exception as e:
            logdata = "平台单号" + str(platform_code) + ",接口处理失败"
        finally:
            return logdata
    else:
        logdata = "同步错误"
        return logdata


def num2main(x, progress_bar, remarks, warehousein_code, window2, Submit, Import):
    """
    003
    子线程执行函数,后端
    """
    print("不排重平台单号")
    platform_codeList = readExcel_pandas(x)  # 读取平台单号
    progress_bar.UpdateBar(0, len(platform_codeList) + 1)  # 更新进度条长度
    i = 1  # 进度
    for platform_code in platform_codeList:  # 遍历平台单号
        print('EXCEL的第' + str(i + 1) + '行')
        jsondata = datagy01(platform_code)  # 构造订单查询的json
        pyresponse = RequestsApi(jsondata)  # 调用管易,返回response
        total = int(pyresponse.get("total"))  # 最近7天
        if total > 0:
            orders = pyresponse["orders"]  # list
            for order in orders:
                # print("调用发货单查询")
                code = order["code"]
                platform_code = order["platform_code"]
                deliverys = order["deliverys"]  # 发货单信息
                if len(deliverys) > 0:
                    for delivery in deliverys:
                        delivery_Code = delivery["code"]
                        logdata = in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code)
                else:
                    lishidingdanchaxun(platform_code, remarks, warehousein_code)
        elif total == 0:
            jsondata = datagy02(platform_code)  # 构造历史订单查询的json
            pyresponse = RequestsApi(jsondata)  # 调用管易,返回response
            total = int(pyresponse.get("total"))  # 最近7天
            # orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
            if total > 0:
                orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
                for order in orders:
                    # print("调用历史发货单查询")
                    code = order["code"]
                    platform_code = order["platform_code"]
                    deliverys = order["deliverys"]
                    for delivery in deliverys:
                        delivery_Code = delivery["code"]
                        logdata = in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code)

            elif total == 0:  # 代表历史订单查询也搜索不到
                print("平台单号", platform_code, "系统不存在该平台单号")
                # logdata = "平台单号"+str(platform_code)+",系统不存在该平台单号"
                logdata = f'平台单号{platform_code}同步失败:系统不存在该平台单号'
                sg.cprint(logdata)  # GUI打印更改到这里使用
                log(logdata)
        else:
            print("平台单号", platform_code, "接口处理失败")
            logdata = "平台单号" + str(platform_code) + ",接口处理失败"
            sg.cprint(logdata)  # GUI打印更改到这里使用
            log(logdata)

        i = i + 1
        progress_bar.UpdateBar(i)
        # sg.cprint(logdata)  # 换in7out7_FHD函数后面使用
        # window2.write_event_value("progressbar", logdata)  # 多线程的话,我们需要让函数通知主窗体一个事件,当完成运算时发送一个事件来通知结果:
        if i == len(platform_codeList) + 1:
            Submit.update(disabled=False)
            Import.update(disabled=False)
            window2.write_event_value("任务已完成", "OK")  # 多线程的话,我们需要让函数通知主窗体一个事件,当完成运算时发送一个事件来通知结果:


def num3main(x, progress_bar, remarks, warehousein_code, window2, Submit, Import):
    """
    003
    子线程执行函数,后端
    """
    print("排重平台单号")
    platform_codeList = readExcel_pandas(x)  # 读取平台单号
    progress_bar.UpdateBar(0, len(platform_codeList) + 1)  # 更新进度条长度
    i = 1  # 进度
    for platform_code in platform_codeList:  # 遍历平台单号
        js_data = tradereturnget01(platform_code)
        platform_code_total = tradereturnget02(js_data)
        print('EXCEL的第' + str(i + 1) + '行')
        if platform_code_total > 0:
            sg.cprint(f"平台单号{platform_code}同步失败:系统退货单内已存在")
            log(f"平台单号{platform_code}同步失败:系统退货单内已存在")
            print(f"平台单号{platform_code}同步失败:系统退货单内已存在")
            i = i + 1
            progress_bar.UpdateBar(i)
        else:
            jsondata = datagy01(platform_code)  # 构造订单查询的json
            pyresponse = RequestsApi(jsondata)  # 调用管易,返回response
            total = int(pyresponse.get("total"))  # 最近7天
            if total > 0:
                orders = pyresponse["orders"]  # list
                for order in orders:
                    # print("调用发货单查询")
                    code = order["code"]
                    platform_code = order["platform_code"]
                    deliverys = order["deliverys"]
                    if len(deliverys) > 0:
                        for delivery in deliverys:
                            delivery_Code = delivery["code"]
                            logdata = in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code)
                    else:
                        lishidingdanchaxun(platform_code, remarks, warehousein_code)
            elif total == 0:
                jsondata = datagy02(platform_code)  # 构造历史订单查询的json
                pyresponse = RequestsApi(jsondata)  # 调用管易,返回response
                total = int(pyresponse.get("total"))  # 最近7天
                # orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
                if total > 0:
                    orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
                    for order in orders:
                        # print("调用历史发货单查询")
                        code = order["code"]
                        platform_code = order["platform_code"]
                        deliverys = order["deliverys"]
                        for delivery in deliverys:
                            delivery_Code = delivery["code"]
                            logdata = in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code)

                elif total == 0:  # 代表历史订单查询也搜索不到
                    print("平台单号", platform_code, "系统不存在该平台单号")
                    # logdata = "平台单号"+str(platform_code)+",系统不存在该平台单号"
                    logdata = f'平台单号{platform_code}同步失败:系统不存在该平台单号'
                    sg.cprint(logdata)  # GUI打印更改到这里使用
                    log(logdata)
            else:
                print("平台单号", platform_code, "接口处理失败")
                logdata = "平台单号" + str(platform_code) + ",接口处理失败"
                sg.cprint(logdata)  # GUI打印更改到这里使用
                log(logdata)

            i = i + 1
            progress_bar.UpdateBar(i)
            # sg.cprint(logdata)  # 换in7out7_FHD函数后面使用
            # window2.write_event_value("progressbar", logdata)  # 多线程的话,我们需要让函数通知主窗体一个事件,当完成运算时发送一个事件来通知结果:
        if i == len(platform_codeList) + 1:
            Submit.update(disabled=False)
            Import.update(disabled=False)
            window2.write_event_value("任务已完成", "OK")  # 多线程的话,我们需要让函数通知主窗体一个事件,当完成运算时发送一个事件来通知结果:


def lishidingdanchaxun(platform_code, remarks, warehousein_code):
    """
    003
    子线程执行函数,后端
    """
    jsondata = datagy02(platform_code)  # 构造历史订单查询的json
    pyresponse = RequestsApi(jsondata)  # 调用管易,返回response
    total = int(pyresponse.get("total"))  # 最近7天
    # orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
    if total > 0:
        orders = pyresponse["orders"]  # 如果orsers列表长度大于0,则查询7天之前
        for order in orders:
            # print("调用历史发货单查询")
            code = order["code"]
            platform_code = order["platform_code"]
            deliverys = order["deliverys"]
            for delivery in deliverys:
                delivery_Code = delivery["code"]
                logdata = in7out7_FHD(code, delivery_Code, platform_code, remarks, warehousein_code)

    elif total == 0:  # 代表历史订单查询也搜索不到
        logdata = f'平台单号{platform_code}同步失败:未生成发货单,无法同步退货单'
        print(logdata)
        sg.cprint(logdata)  # GUI打印更改到这里使用
        log(logdata)


if __name__ == '__main__':
    main()

 类似资料:

相关阅读

相关文章

相关问答