dealSendSomeLIst202307content.py 12.6 KB
import logging
import pandas as pdas
import os
import chardet
import datetime
import re

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 = ''
    module_file_path = ''
    defaultExportReleasePath = ''

    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):
        # 去除字符串中的汉字
        sendDate = re.sub(r'[\u4e00-\u9fa5]', '', sendDate)

        # 进行批量修改的逻辑
        if ',' in sendDate:
            return sendDate.split(',')[0]
        
        if len(sendDate)<19:
            sendDate = sendDate + ' 00:00:00'
        return sendDate
    
    # 定义修改函数
    def dealReadSendMapper(self, dataframes_source):
        sendMapper = {}
        currentKey = {}
        splitSize = 0
        for drow in dataframes_source.itertuples():
            # print(f'[DEBUG] {drow}')
            # 需求: 根据发货清单明细:(同一 下单客户,同一 发货时间,同一 出库仓库,同一 收货 联系人,收货 联系地址,同一 审核人,同一 结算主体),可打印在一张送货单
            sendDate = pdas.to_datetime(self.dealSendDate(drow.发货时间))
            # print(sendDate.strftime("%Y-%m-%d"))
            # 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)

            # 每个key包含6条数据,超过6条后用新的key存储
            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
        return sendMapper

    # 定义修改函数
    def dealStorePeopleMapper(self):
        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
        return storePeopleMapper

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

        # 读取原始数据:
        #   每个mapper value代表一个发货单(每个发货单最大6条发货信息),
        #   mapper key按照商务需求+数值的方式确保唯一用来表示一张发货单(业务操作中不会用到 mapper key,只是用来将原始数据分割成一个一个的 mapper value)
        sendMapper = self.dealReadSendMapper(dataframes_source)
        print('文件任务总数:%s' % len(sendMapper))
        # 不再使用pandas读取模板数据,换成后面的openpyxl  default_dataframes = pdas.read_excel(module_file_path, sheet_name='发货签收单模板')

        mainMapper = {'广联数科': '深圳广联数科科技有限公司','广联赛讯': '深圳广联赛讯股份有限公司','嘀加智慧云': '深圳市嘀加智慧云服务有限公司'}
        storePeopleMapper = self.dealStorePeopleMapper()

        dealindex = 0
        orderNumMapper = {}
        expSizeMapper = {}
        dataframes_source['自动生成单号'] = '-'
        # 打开模板文件
        curWorkBook = openpyxl.load_workbook(module_file_path)

        for sendKey,sendList in sendMapper.items():
            oneRow = sendList[0]
            # 供货方
            mainName = mainMapper.get(oneRow.结算主体)
            # 发货日期
            sendDate = pdas.to_datetime(self.dealSendDate(oneRow.发货时间))
            # 发货单号
            sendDateStr = sendDate.strftime("%Y-%m-%d")
            orYear = sendDate.strftime("%Y")

            # 每天的订单进行序号递增,并使用mapper存储
            orkey = sendDate.strftime("%Y%m%d")
            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.出库仓库

            curSheet = curWorkBook.active

            # ---清空内存中的表格 start---
            curSheet['C3'] = ''
            curSheet['H3'] = ''
            curSheet['J3'] = ''
            curSheet['C4'] = ''
            curSheet['I4'] = ''
            curSheet['C5'] = ''
            curSheet['I5'] = ''
            curSheet['J5'] = ''
            loopList = [7,8,9,10,11,12]
            for loopItem in loopList:
                curSheet[f'C{loopItem}'] = ''
                curSheet[f'D{loopItem}'] = ''
                curSheet[f'E{loopItem}'] = ''
                curSheet[f'G{loopItem}'] = ''
                curSheet[f'H{loopItem}'] = ''
                curSheet[f'I{loopItem}'] = ''
                curSheet[f'I{loopItem}'] = ''
                curSheet['C14'] = ''
                curSheet['F14'] = ''
            # ---清空内存中的表格 END---

            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
                # 在源文件中增加列:自动生成单号
                dataframes_source.loc[dataframes_source['发货单号'] == sendRow.发货单号, '自动生成单号'] = sendOrderCode

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

        # 关闭openpyxl的IO流操作
        curWorkBook.close()
        # 将源文件写出到新文件
        sourceExportFilePath = f'{exportPath}exportsource_{dealContentPath}.xlsx'
        dataframes_source.to_excel(sourceExportFilePath, index=False)


    # 定义修改函数
    def dealContentFile(self, contentPath):
        # 获取目录中的所有文件
        files = os.listdir(contentPath)
        for file in files:
            sourceFile = f'{contentPath}{file}'
            dealContentPath = file.split('-')[1].replace('.xlsx', '')
            # print("=1=文件名称:", sourceFile)
            # print("=2=DefaultExport:", self.defaultExportReleasePath)
            print('=3=dealContent:', dealContentPath)

            exportPath = self.defaultExportReleasePath + '' + dealContentPath + '/'
            if not os.path.exists(exportPath):
                # 创建目录
                os.makedirs(exportPath)
                print(f"Directory '{exportPath}' created.")
            else:
                print(f"Directory '{exportPath}' already exists.")

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



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)

    dealMain.module_file_path = 'D:/work_doc/003 - 商务脚本/发货签收单-模板-rel.xlsx'
    dealMain.defaultExportReleasePath = 'D:/work_doc/003 - 商务脚本/export_relaese/'

    contentPath = 'D:/work_doc/003 - 商务脚本/2021年-2023年发货清单明细/2023年/'
    dealMain.dealContentFile(contentPath)