首页 > 其他分享 >【日常收支账本】【Day05】编辑账本界面增加删除、更新记录功能——提高代码复用性

【日常收支账本】【Day05】编辑账本界面增加删除、更新记录功能——提高代码复用性

时间:2023-10-11 23:33:21浏览次数:46  
标签:old self 复用 Day05 record dict value action 账本

一、项目地址

https://github.com/LinFeng-BingYi/DailyAccountBook

二、新增

1. 增加删除记录功能

1.1 功能详述

  • 点击删除按钮后,获取对应行的数据组成字典,用字典的键值对匹配到对应日期的记录元素;
  • 接着用该字典数据冲正存款账户余额(实现思路为新增记录时的反向操作),同时删除记录元素;
  • 最后再更新表格。

1.2 代码实现

    def deleteTableRow(self, triggeredBtn, tableWidget):
        print("触发了删除按钮")
        # 获取触发信号的控件所在行号
        current_row = tableWidget.indexAt(triggeredBtn.parent().pos()).row()
        if tableWidget == self.tableWidget_expense:
            const_class = expenseConst
            action = 'expense'
        elif tableWidget == self.tableWidget_income:
            const_class = incomeConst
            action = 'income'
        elif tableWidget == self.tableWidget_movement:
            const_class = movementConst
            action = 'movement'
        else:
            print('未知控件触发新增按钮!')
            return
        # 获取待删除行的数据
        old_data_dict = self.getExistTableCell(tableWidget, current_row, const_class)
        if old_data_dict is None:
            print("获取待删除数据失败!!")
            return
        print("待删除记录内容为: \n", old_data_dict)

        if self.file_processor.deleteRecord(old_data_dict, self.dateEdit.text().replace('/', ''), action):
            print("删除成功!")
            # 把删除结果写入文件
            self.file_processor.writeXMLFile(self.lineEdit_file_path.text())

            # 更新self.file_parse_result以及记录表
            records_list = self.file_parse_result[action + 's']
            records_list.pop(current_row)
            self.updateRecordTable(tableWidget, records_list, const_class)

其中处理xml文件的方法代码如下:

    def deleteRecord(self, old_record_dict, date_str, action):
        e_date = self.getSpecificDateElement(date_str)
        if isinstance(e_date, int):
            print("未找到这一天的数据!")
            return False

        if action == 'expense':
            action_path = ".//expenses"
            record_path = """.//expense[@necessity='{}'][@associatedFund='{}'][value='{}'][category='{}'][detail='{}'][describe='{}'][from='{}']""".format(
                old_record_dict['necessity'],
                old_record_dict['associatedFund'],
                old_record_dict['value'],
                old_record_dict['category'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['from'])
        elif action == 'income':
            action_path = ".//incomes"
            record_path = """.//income[@associatedFund='{}'][value='{}'][category='{}'][detail='{}'][describe='{}'][to='{}']""".format(
                old_record_dict['associatedFund'],
                old_record_dict['value'],
                old_record_dict['category'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['to'])
        elif action == 'movement':
            action_path = ".//movements"
            record_path = """.//movement[value='{}'][detail='{}'][describe='{}'][from='{}'][to='{}']""".format(
                old_record_dict['value'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['from'],
                old_record_dict['to'])
        else:
            print("未知的动账操作!!")
            return False
        # print(record_path)

        e_action = e_date.find(action_path)
        e_record = e_action.find(record_path)
        if e_record is None:
            print("未找到待删除的记录")
            return False
        e_action.remove(e_record)

        if action == 'movement':
            self.modifyBalance(old_record_dict['from'], Decimal(old_record_dict['value']))
            self.modifyBalance(old_record_dict['to'], Decimal(old_record_dict['value']) * (-1))
        else:
            self.reversalVariation(old_record_dict, e_date)
        return True

    def reversalVariation(self, change_dict, e_date):
        """
        Describe: 删除某条记录时,需要冲正原来的记录,将回退对应的存款账户数值变化、以及余额

        Args:
            change_dict: dict
                记录字典
            e_date: Element
                指定日期的day元素
        """
        e_variation = e_date.find(".//variation")
        if e_variation is None:
            print("冲正记录时异常!!该记录不存在余额变化")
            return
        if 'from' in change_dict:
            e_fund_variety = e_variation.find(".//fund[category='{}']/out".format(change_dict['from']))
            if e_fund_variety is None:
                print("冲正记录时异常!!该记录不存在余额变化")
                return
            e_fund_variety.text = str((Decimal(e_fund_variety.text) - Decimal(change_dict['value'])).quantize(Decimal('0.00')))
            self.modifyBalance(change_dict['from'], Decimal(change_dict['value']))

            self.reversalAssociatedFund(e_variation, change_dict, 'from')
        if 'to' in change_dict:
            e_fund_variety = e_variation.find(".//fund[category='{}']/in".format(change_dict['to']))
            if e_fund_variety is None:
                print("冲正记录时异常!!该记录不存在余额变化")
                return
            e_fund_variety.text = str((Decimal(e_fund_variety.text) - Decimal(change_dict['value'])).quantize(Decimal('0.00')))
            self.modifyBalance(change_dict['to'], Decimal(change_dict['value'])*(-1))

            self.reversalAssociatedFund(e_variation, change_dict, 'to')

    def reversalAssociatedFund(self, e_variation, change_dict, from_or_to):
        """
        Describe: 冲正关联账户

        Args:
            e_variation: Element
            change_dict: dict
            from_or_to: ['from', 'to']
        """
        # print(change_dict['associatedFund'])
        if 'associatedFund' in change_dict and change_dict['associatedFund'] != 'None':
            print('执行了associatedFund冲正,操作为', from_or_to)
            if e_variation.find(".//fund[category='{}']".format(change_dict['associatedFund'])) is None:
                print("冲正记录时异常!!该记录不存在关联账户余额变化")
                return
            if from_or_to == 'from':
                e_fund_variety = e_variation.find(".//fund[category='{}']/out".format(change_dict['associatedFund']))
                flag = 1
            elif from_or_to == 'to':
                e_fund_variety = e_variation.find(".//fund[category='{}']/in".format(change_dict['associatedFund']))
                flag = -1
            else:
                print('未知的收支动作!')
                return
            e_fund_variety.text = str((Decimal(e_fund_variety.text) - Decimal(change_dict['value'])).quantize(Decimal('0.00')))
            self.modifyBalance(change_dict['associatedFund'], Decimal(change_dict['value'])*flag)

2. 增加更新记录功能

2.1 功能详述

  • 点击更新按钮后,获取对应行的数据组成新记录字典;
  • 同时根据行号获取编辑账本界面的self.file_parse_result属性对应的旧记录字典(每次更新xml文件时,该属性都会同步);
  • 接着用旧字典数据冲正存款账户余额(实现思路为新增记录时的反向操作),再用新字典数据更新账户余额,>- 最后再更新self.file_parse_result属性。

2.2 代码实现

    def updateTableRow(self, triggeredBtn, tableWidget):
        print("触发了新增按钮")
        # 获取触发信号的控件所在行号
        current_row = tableWidget.indexAt(triggeredBtn.parent().pos()).row()
        if tableWidget == self.tableWidget_expense:
            const_class = expenseConst
            action = 'expense'
        elif tableWidget == self.tableWidget_income:
            const_class = incomeConst
            action = 'income'
        elif tableWidget == self.tableWidget_movement:
            const_class = movementConst
            action = 'movement'
        else:
            print('未知控件触发新增按钮!')
            return
        # 获取被更新的旧数据(文件解析后,记录顺序与表格顺序相同)
        old_data_dict = self.file_parse_result[action+'s'][current_row]
        print("旧记录内容为: \n", old_data_dict)
        # 获取更新后的新数据
        new_data_dict = self.getExistTableCell(tableWidget, current_row, const_class)
        if new_data_dict is None:
            print("获取更新后的数据失败!!")
            return
        print("更新后的记录内容为: \n", new_data_dict)

        if self.file_processor.updateRecord(old_data_dict, new_data_dict, self.dateEdit.text().replace('/', ''), action):
            print("更新成功!")
            # 把删除结果写入文件
            self.file_processor.writeXMLFile(self.lineEdit_file_path.text())

            # 更新self.file_parse_result
            self.file_parse_result[action+'s'][current_row] = new_data_dict
            # print(self.file_parse_result)

其中处理xml文件的方法代码如下:

    def updateRecord(self, old_record_dict, new_record_dict, date_str, action):
        e_date = self.getSpecificDateElement(date_str)
        if isinstance(e_date, int):
            print("未找到这一天的数据!")
            return False

        if action == 'expense':
            action_path = ".//expenses"
            record_path = """.//expense[@necessity='{}'][@associatedFund='{}'][value='{}'][category='{}'][detail='{}'][describe='{}'][from='{}']""".format(
                old_record_dict['necessity'],
                old_record_dict['associatedFund'],
                old_record_dict['value'],
                old_record_dict['category'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['from'])
        elif action == 'income':
            action_path = ".//incomes"
            record_path = """.//income[@associatedFund='{}'][value='{}'][category='{}'][detail='{}'][describe='{}'][to='{}']""".format(
                old_record_dict['associatedFund'],
                old_record_dict['value'],
                old_record_dict['category'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['to'])
        elif action == 'movement':
            action_path = ".//movements"
            record_path = """.//movement[value='{}'][detail='{}'][describe='{}'][from='{}'][to='{}']""".format(
                old_record_dict['value'],
                old_record_dict['detail'],
                old_record_dict['describe'],
                old_record_dict['from'],
                old_record_dict['to'])
        else:
            print("未知的动账操作!!")
            return False
        # print(record_path)

        e_action = e_date.find(action_path)
        e_record = e_action.find(record_path)
        if e_record is None:
            print("未找到待删除的记录")
            return False

        # 修改了数值则需要冲正
        if old_record_dict['value'] != new_record_dict['value']:
            # 先冲正原记录数据
            # 在用新数据修改账户变化和余额
            if action == 'movement':
                self.modifyBalance(old_record_dict['from'], Decimal(old_record_dict['value']))
                self.modifyBalance(old_record_dict['to'], Decimal(old_record_dict['value']) * (-1))
                self.modifyBalance(new_record_dict['from'], Decimal(new_record_dict['value']) * (-1))
                self.modifyBalance(new_record_dict['to'], Decimal(new_record_dict['value']))
            else:
                self.reversalVariation(old_record_dict, e_date)
                self.organizeVariation(new_record_dict, e_date)

        # 修改记录数据

        for key in new_record_dict.keys():
            if key == 'necessity':
                e_record.attrib['necessity'] = new_record_dict['necessity']
            elif key == 'associatedFund':
                e_record.attrib['associatedFund'] = new_record_dict['associatedFund']
            else:
                e_record.find(".//"+key).text = str(new_record_dict[key])
        return True

3. 优化界面控件(内置spinBox、增加按钮切换日期)

3.1 功能详述

将记录表格数值(value)列内置QSpinBox,以避免存于文件的数值小数点位不一致;增加按钮来控制日期的切换

3.2 效果展示


数值(value)列内置QSpinBox

增加按钮来控制日期的切换

3.3 代码实现

# 内置QDoubleSpinBox
spinBox = QDoubleSpinBox(decimals=2)# 设置保留小数后2位
# 设置范围,默认为[0.0, 100.0)。必须在调整数值前设置,否则大于等于100.0时会变成99.99
spinBox.setRange(0.0, 100000000.0)
spinBox.setSingleStep(0.1)          # 设置步长
spinBox.setValue(value)             # 调整数值
tableWidget.setCellWidget(current_row, keys_list.index(key), spinBox)

# 日期切换
# 利用QDate类的addDays(int)方法
self.pushButton_prev_day.clicked.connect(lambda: self.dateEdit.setDate(self.dateEdit.date().addDays(-1)))
self.pushButton_post_day.clicked.connect(lambda: self.dateEdit.setDate(self.dateEdit.date().addDays(1)))

三、开发总结

1. 提高代码复用性

最近几篇都没有技术含量,就不总结了。唯一值得一提的就是提高代码复用性。

  • 对于支出、收入、转移三种动账类型,字段大量重复,于是创建表格时,将所有列的初始化集中到一个函数中,根据列名执行对应初始化方式。
  • 通过设置ExpenseConst、IncomeConst、MovementConst三个具有同名常量的类,更好地支持代码复用
  • 第二章删除和新增记录时修改xml文件的方法deleteRecord(old_record_dict, date_str, action)updateRecord(self, old_record_dict, new_record_dict, date_str, action)是通过action区分动账类型,避免同一个功能需要实现三个方法

标签:old,self,复用,Day05,record,dict,value,action,账本
From: https://www.cnblogs.com/LinfengBingyi/p/17756104.html

相关文章

  • 关于CH32V307 PA6、7引脚复用为串口1和串口7配置方法
    1、复用为串口1配置方法关于PA6和PA7,重映射串口1时,最后下标为3,如下图。换算成二进制为11,重映射对应的就是PA6、PA7,如下图。由于库中没有直接定义该位,因此将PA6、PA7复用为USART1时,需要进行如下操作,如下图。可直接调用GPIO_PinRemapConfig函数,先调用该函数复用为USART1高位,再......
  • day05-字符串
    我们在上篇day04-数据类型中简单介绍了一下字符串,以及字符串的下标,今天我们来详细认识下字符串。字符串(str)可以使用单引号或双引号来创建字符串,并且字符串是不可变的数据类型,字符串也是Python中最常用的数据类型,所以我们一定学会它,学习字符串一定先熟悉概念,知道是怎么回事,然后......
  • 解锁 Vue 3 神奇技巧:让模板复用达到极致
    引出在vue的日常开发当中,我们可能会遇到这样的一种情况:某一部分的模版需要重复利用,但又不至于到新开1个组件的地步。比如:js复制代码<template><divv-for="iteminlist">//条件渲染<divv-if="isCase1(item.id)"class="case1Class...">......
  • Go每日一库之139:cmux (连接多路复用)
    如果一个应用需要同时对外提供HTTP和gRPC服务,通常情况下我们会为两个服务绑定不同的监听端口,而本文要介绍的cmux为我们提供了一种连接多路复用的新选择,使用cmux可以将不同服务绑定在同一个网络端口上!简介多路复用是个很常见的概念,我们在编写HTTP服务时通常会用http.S......
  • 【日常收支账本】【Day03】通过ElementTree+XPath实现对XML文件的读写
    一、项目地址https://github.com/LinFeng-BingYi/DailyAccountBook二、新增1.解析xml文件1.1功能详述解析所设计的xml文件格式,并将所得数据存入变量。点击查看xml格式<DailyAccountBook><balance><fund><value>5000.00</value>......
  • 光电复用口link错误
    现象:光电复用口,电口和光口接满线,电口与光口各亮一对serdes_link=0copper_link=0get_combo_link_status(){port1=$1#localtmp_reg=`bcmsh"linkscanoff;phy${port1}0x170xf7e;phy${port1}0x150;phy${port1}0x1e0x21;phy${port1}0x1f;linkscano......
  • 光电复用口查看当前是光还是电
    Sundray-SW[Undefine-0/32|LC]/#bcmshcomboge2excute:ovs-appctlplugin/bcmshcomboge2Portge2:ge2:Coppermedium(active)enable=1preferred=1force_speed=1000force_duplex=1master=Autoautoneg_enable=1autoneg_advert=(0x0)......
  • Day05 - Vue之动态组件、插槽、项目的创建
    动态组件//关键字: component//使用方法:<component:is="who"></component>//component标签的is属性等于组件名字,这里就会显示这个组件<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><link......
  • vue-day05
    补充1.图片在接口中返回一些数据和图片地址,而不是图片的二进制内容{code:100,msg:'成功',img:地址}2.md5不是加密,摘要算法动态组件<component:is="who"></component>component标签的is属性等于组件名字,这里就会显示这个组件HTML<!DOCTYPEhtml><html......
  • 【日常收支账本】【Day02】通过PyCharm集成QtDesigner和PyUIC快速创建界面
    一、集成QtDesigner和PyUICPyCharm集成QtDesigner和PyUIC教程二、在QtDesigner中画出窗体1.主界面编辑账本:新增、修改或删除记录可视化账本:通过不同角度查看收支情况全局配置:根据自身实际情况定义配置2.编辑账本界面三、创建项目项目结构将UI文件与窗体文件分......