dealSendSomeLIst202307threads.py 10.8 KB
import logging
import pandas as pdas
import os
import chardet
import datetime

import threading

import openpyxl
from openpyxl import Workbook

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder

print("sys config " + __name__)
log_name = './log/supplychain/dealSendSomeList.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)

class DealSupplychainSomeListMain:

    handleDescription = ''
    handleMonth = ''
    hmonth = ''

    db = None

    def __init__(self, handle_month):
        logging.info("init construct bean")
        self.handleDescription = "供应链批量打印发货单需求脚本执行..."
        self.handleMonth = handle_month
        self.hmonth = handle_month.replace('-', '')[2:6]
        #self.db = MysqlHelper(DbConect.current_month_DB)

    def initCurrentMonthTable(self):
        logging.info("初始化:暂无操作")
        
    # 判断文件编码
    def detect_file_encoding(self, filename):
        with open(filename, 'rb') as f:
            content = f.read()
            result = chardet.detect(content)
            return result['encoding']

    def dealDeviceEndDateList(self):
        return True

    # 定义修改函数
    def modify_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return x
        return x.replace("M{", "").replace("}", "")

    # 定义修改函数
    def modify_float_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return 0
        current = str(x).replace("`", "").replace(' ', '')
        if current == '':
            return 0
        return current

    # 定义修改函数
    def dealSendDate(self, sendDate):
        # 进行批量修改的逻辑
        if ',' in sendDate:
            return sendDate.split(',')[0]
        return sendDate

    def dealDataToExcel(self, sourceFile, exportPath, module_file_path):
        # 读取 Excel 文件
        dataframes_source = pdas.read_excel(sourceFile)

        sendMapper = {}
        currentKey = {}

        splitSize = 0
        for drow in dataframes_source.itertuples():
            # print(f'[DEBUG] {drow}')
            # 需求: 根据发货清单明细:(同一 下单客户,同一 发货时间,同一 出库仓库,同一 收货 联系人,收货 联系地址,同一 审核人,同一 结算主体),可打印在一张送货单
            sendDate = datetime.datetime.strptime(self.dealSendDate(drow.发货时间), "%Y-%m-%d %H:%M:%S")

            mapkey = "cus:%s,date:%s,stor:%s,peo:%s,add:%s,check:%s,main:%s" % (drow.下单客户, sendDate.strftime("%Y-%m-%d"), drow.出库仓库, drow.联系人, drow.联系地址, drow.审核人, drow.结算主体)
            curMapkey = currentKey.get(mapkey)
            if curMapkey is None:
                currentKey[mapkey] = mapkey
                curMapkey = mapkey
            # print(f'[DEBUG] curMapkey:{curMapkey}')

            dataList = sendMapper.get(curMapkey)

            if dataList is not None and len(dataList)==5:
                curMapkey = "%s_%s" % (mapkey, splitSize)
                currentKey[mapkey] = curMapkey

            if dataList is None:
                dataList = []
                dataList.append(drow)
                sendMapper[curMapkey] = dataList
            else:
                dataList.append(drow)
            splitSize+=1
        
        print('文件任务总数:%s' % len(sendMapper))
        default_dataframes = pdas.read_excel(module_file_path, sheet_name='发货签收单模板')

        mainMapper = {'广联数科': '深圳广联数科科技有限公司','广联赛讯': '深圳广联赛讯股份有限公司','嘀加智慧云': '深圳市嘀加智慧云服务有限公司'}
        storePeopleMapper = {}
        storePeople_dataframes = pdas.read_excel('D:\\work_doc\\003 - 商务脚本\\仓别-发研发.xlsx', skiprows=1)
        for drow in storePeople_dataframes.itertuples():
            # print(f'[DEBUG] {drow}')
            key1 = drow._2 + '2021制单人'
            key2 = drow._2 + '2021发货人'
            key3 = drow._2 + '2022制单人'
            key4 = drow._2 + '2022发货人'
            key5 = drow._2 + '2023制单人'
            key6 = drow._2 + '2023发货人'
            storePeopleMapper[key1] = drow.制单人
            storePeopleMapper[key2] = drow.发货人
            storePeopleMapper[key3] = drow._5
            storePeopleMapper[key4] = drow._6
            storePeopleMapper[key5] = drow._7
            storePeopleMapper[key6] = drow._8


        threadDataMapper = {}
        # 将业务数据通过规则进行拆分,多线程执行
        for sendKey,sendList in sendMapper.items():
            oneRow = sendList[0]
            # 发货日期
            sendDate = datetime.datetime.strptime(self.dealSendDate(oneRow.发货时间), "%Y-%m-%d %H:%M:%S")
            orkey = int(sendDate.strftime("%Y%m%d"))
            hashCode = orkey%6
            print('sendDate:%s  hashCode:%d' %(sendDate, hashCode))

            itemMapper = threadDataMapper.get(hashCode)
            if itemMapper is None:
                itemMapper = {}
                threadDataMapper[hashCode] = itemMapper
            itemMapper[sendKey] = sendList

        print(len(threadDataMapper))
        # 创建线程
        threads = []
        for threadKey, threadMapper in threadDataMapper.items():
            print(f'threadName:{threadKey} threadDataSize:{len(threadMapper)}')
            thread = threading.Thread(target=self.dealWriteContentFile, args=(threadMapper, mainMapper, storePeopleMapper, threadKey))
            threads.append(thread)
        
        # 启动线程
        for thread in threads:
            thread.start()

        # 等待线程结束
        for thread in threads:
            thread.join()

        # 处理完的数据在共享列表中
        print('[OK] data deal end.')




    def dealWriteContentFile(self, sendMapper, mainMapper, storePeopleMapper, threadKey):
        dealindex = 0
        write_dataframes = []
        orderNumMapper = {}
        expSizeMapper = {}
        for sendKey,sendList in sendMapper.items():
            oneRow = sendList[0]
            # 供货方
            mainName = mainMapper.get(oneRow.结算主体)
            # 发货日期
            sendDate = datetime.datetime.strptime(self.dealSendDate(oneRow.发货时间), "%Y-%m-%d %H:%M:%S")
            # 发货单号
            sendDateStr = sendDate.strftime("%Y-%m-%d")
            orkey = sendDate.strftime("%Y%m%d")
            orYear = sendDate.strftime("%Y")
            orderNum = orderNumMapper.get(orkey)
            if orderNum is None:
                orderNum = (int(orkey) * 10000)
            orderNum+=1
            orderNumMapper[orkey] = orderNum
            sendOrderCode = orderNum
            # 收货方
            reciverCustomer = oneRow.下单客户
            # 收货地址
            reciverAdd = oneRow.联系地址
            # 收货人
            reciverPeople = oneRow.联系人
            # 收货人电话
            reciverPeopleMobile = str(oneRow.联系电话)
            # 发货仓
            sendStore = oneRow.出库仓库

            curWorkBook = openpyxl.load_workbook(module_file_path)
            curSheet = curWorkBook.active
            curSheet['C3'] = mainName
            curSheet['H3'] = sendDateStr
            curSheet['J3'] = str(sendOrderCode)

            curSheet['C4'] = reciverCustomer
            curSheet['I4'] = sendStore

            curSheet['C5'] = reciverAdd
            curSheet['I5'] = reciverPeople
            curSheet['J5'] = reciverPeopleMobile

            loopIndex = 7
            for sendRow in sendList:
                # 物料编码
                marterCode = sendRow.实发物料编码
                # 销售编码
                saleMarterCode = sendRow.订单物料编码
                # 产品名称
                productName = sendRow.实发物料名称
                # 子订单号
                childOrderCode = sendRow.子订单号
                # 数量
                orderCount = sendRow.已发数量
                # 备注
                lineRemark = sendRow.发货单号
                # 制单人
                mlpKey = f'{sendRow.出库仓库}{orYear}制单人'
                markListPeople = storePeopleMapper.get(mlpKey)
                # 发货人
                slpKey = f'{sendRow.出库仓库}{orYear}发货人'
                sendListPeople = storePeopleMapper.get(slpKey)
                
                curSheet[f'C{loopIndex}'] = marterCode
                curSheet[f'D{loopIndex}'] = saleMarterCode
                curSheet[f'E{loopIndex}'] = productName
                curSheet[f'G{loopIndex}'] = childOrderCode
                curSheet[f'H{loopIndex}'] = orderCount
                curSheet[f'I{loopIndex}'] = lineRemark
                curSheet[f'I{loopIndex}'] = lineRemark
                curSheet['C14'] = markListPeople
                curSheet['F14'] = sendListPeople
                loopIndex+=1

            # 同订单号计数
            expSize = expSizeMapper.get(sendOrderCode)
            if expSize is None:
                expSize = 0
            expSize+=1
            expSizeMapper[sendOrderCode] = expSize
            orderNumValue = "%s_%s" % (sendOrderCode, expSize)
            exPath = "%s%s.xlsx" % (exportPath, orderNumValue)
            # write_dataframes.to_excel(exPath, index=False)
            curWorkBook.save(exPath)
            curWorkBook.close()
            dealindex+=1
            print('[%s] thread:%s 生成文件索引:%s' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), threadKey, dealindex))



if __name__ == "__main__":
    handle_month = '2021-2023'
    dedRes = False
    diRes = False
    urRes = False
    

    print('==========================多线程跑数据==========================')


    #启动初始化
    dealMain = DealSupplychainSomeListMain(handle_month)
    logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)

    
    # defaultExportPath = 'D:/work_doc/003 - 商务脚本/thrad_export_'
    defaultExportPath = 'C:/export_supplychain/thrad_export_'
    module_file_path = 'D:/work_doc/003 - 商务脚本/发货签收单-模板-rel.xlsx'

    # sourceFile = 'D:/work_doc/003 - 商务脚本/678018835261169664_商务订单 - 222.xlsx'
    # exportPath = defaultExportPath + 'test/'

    sourceFile = 'D:/work_doc/003 - 商务脚本/商务订单-2023年1月-系统导出.xlsx'
    exportPath = defaultExportPath + '2023年1月/'

    # 处理核心逻辑
    dealMain.dealDataToExcel(sourceFile, exportPath, module_file_path)