Python Pyside6 加Sqlite3 写一个 通用 进销存 系统 初型

 图:

 

说明:

进销存管理系统说明文档

功能模块

1. 首页

  • 显示关键业务数据
    • 商品总数
    • 供应商总数
    • 本月采购金额
    • 本月销售金额
  • 显示预警信息
    • 库存不足预警
    • 待付款采购单
    • 待收款销售单

2. 商品管理

  • 商品信息维护
    • 商品编码(唯一标识)
    • 商品名称
    • 规格型号
    • 单位
    • 分类
    • 进货价
    • 销售价
    • 库存数量
    • 预警数量
  • 支持批量导入导出
  • 支持搜索和筛选

3. 供应商管理

  • 供应商信息维护
    • 供应商名称(唯一标识)
    • 联系人
    • 联系电话
    • 地址
    • 账期
  • 支持批量导入导出
  • 支持搜索和筛选

4. 客户管理

  • 客户信息维护
    • 客户名称(唯一标识)
    • 联系人
    • 联系电话
    • 地址
    • 电子邮箱
    • 备注信息
  • 基本操作
    • 新建客户:添加新的客户信息
    • 编辑客户:修改现有客户信息
    • 删除客户:删除未使用的客户(已有销售订单的客户不能删除)
    • 搜索客户:按名称、联系人、电话等信息搜索
  • 数据导入导出
    • 支持从Excel导入客户数据
    • 支持导出客户数据到Excel
    • 导入时自动处理重复数据
  • 数据验证
    • 客户名称不能重复
    • 删除前检查销售订单关联
    • 导入数据格式验证

5. 采购管理

  • 采购单管理
    • 新建采购单
    • 编辑采购单
    • 删除采购单
    • 查看采购历史
  • 采购单信息
    • 采购单号(自动生成)
    • 供应商
    • 采购日期
    • 付款状态
    • 入库状态
    • 商品明细
      • 商品
      • 数量
      • 单价
      • 金额
  • 支持搜索和筛选

6. 销售管理

  • 销售单管理
    • 新建销售单
    • 编辑销售单
    • 删除销售单
    • 查看销售历史
  • 销售单信息
    • 销售单号(自动生成)
    • 客户信息
    • 销售日期
    • 收款状态
    • 出库状态
    • 商品明细
      • 商品
      • 数量
      • 单价
      • 金额
  • 支持搜索和筛选

7. 库存管理

  • 库存状态查看
    • 商品名称
    • 当前库存
    • 预警库存
    • 库存状态
  • 库存调整
    • 手动入库
    • 手动出库
    • 调整原因记录
  • 变动历史查询
    • 调整时间
    • 调整类型
    • 调整数量
    • 调整原因
  • 支持搜索和筛选

8. 系统备份

  • 数据备份功能
    • 创建备份:将当前数据库导出为备份文件
    • 自动生成包含时间戳的文件名
    • 可选择备份文件保存位置
  • 数据恢复功能
    • 从备份文件恢复数据
    • 恢复前自动创建当前数据的备份
    • 支持确认提示,防止误操作
  • 使用建议
    • 定期创建数据备份
    • 将备份文件保存在不同的存储设备上
    • 重要操作前先创建备份
    • 系统升级前创建备份

财务管理

财务管理模块提供了全面的财务操作和分析功能,包括收付款管理、财务统计、应收应付对账等功能。

收付款记录

  • 新建收款:记录客户的付款信息
    • 选择关联销售单号
    • 输入收款金额
    • 选择支付方式(现金/银行转账/支付宝/微信)
    • 添加备注信息
  • 新建付款:记录向供应商的付款信息
    • 选择关联采购单号
    • 输入付款金额
    • 选择支付方式
    • 添加备注信息
  • 搜索功能:支持按关键字搜索收付款记录

财务统计

  • 时间范围选择:
    • 本月
    • 上月
    • 最近7天
    • 最近30天
    • 全部
  • 统计指标:
    • 总收入
    • 总支出
    • 净收入

应收对账

  • 客户应收账款管理:
    • 按客户查看应收账款
    • 时间筛选(全部/本月/上月/本年/上年)
    • 显示销售总额、已收金额、应收金额
    • 详细的销售订单列表(含收款状态)
  • 导出功能:
    • 导出Excel格式的对账单
    • 支持打印对账单(含打印预览)

应付对账

  • 供应商应付账款管理:
    • 按供应商查看应付账款
    • 时间筛选(全部/本月/上月/本年/上年)
    • 显示采购总额、已付金额、应付金额
    • 详细的采购订单列表(含付款状态)
  • 导出功能:
    • 导出Excel格式的对账单
    • 支持打印对账单(含打印预览)

使用说明

  1. 收付款操作:
    • 点击"新建收款"或"新建付款"按钮
    • 选择关联单号,系统会自动填充相关金额
    • 填写实际收付款金额和支付方式
    • 可添加备注信息
    • 确认保存
  1. 财务统计:
    • 选择要查看的时间范围
    • 系统自动计算并显示收入、支出和净收入
  1. 应收对账:
    • 选择客户和时间范围
    • 查看应收账款汇总和明细
    • 可导出Excel或打印对账单
  1. 应付对账:
    • 选择供应商和时间范围
    • 查看应付账款汇总和明细
    • 可导出Excel或打印对账单

使用说明

1. 系统初始化

  1. 首次使用请先维护基础数据:
    • 添加商品信息
    • 添加供应商信息
    • 添加客户信息
  1. 设置商品库存预警值

2. 日常操作

  1. 采购入库
    • 新建采购单
    • 选择供应商
    • 添加商品明细
    • 设置入库状态
  1. 销售出库
    • 新建销售单
    • 选择客户
    • 添加商品明细
    • 设置出库状态
  1. 库存管理
    • 定期盘点库存
    • 及时处理库存预警
  1. 系统维护
    • 及时备份数据
    • 定期检查系统运行状态

3. 数据备份

  1. 定期备份
    • 进入"系统备份"页面
    • 点击"创建备份"按钮
    • 选择备份文件保存位置
    • 确认备份成功
  1. 数据恢复
    • 进入"系统备份"页面
    • 点击"恢复备份"按钮
    • 选择要恢复的备份文件
    • 确认恢复操作
    • 等待恢复完成

注意事项

  1. 数据安全
    • 定期备份数据库
    • 将备份文件保存在安全的位置
    • 定期检查备份文件的完整性
    • 重要操作前先创建备份
    • 定期备份数据库
    • 妥善保管系统账号密码
  1. 操作规范
    • 严格按照操作流程执行
    • 认真核对数据后再保存
  1. 异常处理
    • 遇到问题及时记录
    • 系统故障及时报修

代码:

主窗口 main.py

import sys
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,QHBoxLayout, QTabWidget, QPushButton, QLabel)
from PySide6.QtCore import Qt
from database import Database
from products import ProductsTab
from dashboard import DashboardTab
from suppliers import SuppliersTab
from customers import CustomersTab
from purchase import PurchaseTab
from sales import SalesTab
from inventory import InventoryTab
from finance import FinanceTab
from backup import BackupWidgetclass MainWindow(QMainWindow):def __init__(self, db):super().__init__()self.db = dbself.init_ui()def init_ui(self):self.setWindowTitle('进销存管理系统')self.resize(1200, 800)# Create tab widgettab_widget = QTabWidget()tab_widget.addTab(ProductsTab(self.db), '商品管理')tab_widget.addTab(SuppliersTab(self.db), '供应商管理')tab_widget.addTab(CustomersTab(self.db), '客户管理')tab_widget.addTab(PurchaseTab(self.db), '采购管理')tab_widget.addTab(SalesTab(self.db), '销售管理')tab_widget.addTab(InventoryTab(self.db), '库存管理')tab_widget.addTab(FinanceTab(self.db), '财务管理')tab_widget.addTab(BackupWidget('inventory.db'), '系统备份')self.setCentralWidget(tab_widget)def main():app = QApplication(sys.argv)db = Database()  # Create database instancewindow = MainWindow(db)  # Pass database instance to MainWindowwindow.show()sys.exit(app.exec())if __name__ == '__main__':main() 

 

商品管理 products.py

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,QLabel, QLineEdit, QTableWidget, QTableWidgetItem,QMessageBox, QHeaderView, QFileDialog, QDialog,QFormLayout, QDoubleSpinBox, QSpinBox)
from PySide6.QtCore import Qt
import openpyxl
from datetime import datetime
import osclass ProductEditDialog(QDialog):def __init__(self, product=None, parent=None):super().__init__(parent)self.product = productself.init_ui()def init_ui(self):self.setWindowTitle('编辑商品' if self.product else '新增商品')layout = QFormLayout(self)# Create input fieldsself.code = QLineEdit(self.product[0] if self.product else '')self.name = QLineEdit(self.product[1] if self.product else '')self.specification = QLineEdit(self.product[2] if self.product else '')self.unit = QLineEdit(self.product[3] if self.product else '')self.category = QLineEdit(self.product[4] if self.product else '')self.cost_price = QDoubleSpinBox()self.cost_price.setMaximum(999999.99)self.cost_price.setDecimals(2)if self.product:self.cost_price.setValue(float(self.product[5]))self.selling_price = QDoubleSpinBox()self.selling_price.setMaximum(999999.99)self.selling_price.setDecimals(2)if self.product:self.selling_price.setValue(float(self.product[6]))self.stock_quantity = QSpinBox()self.stock_quantity.setMaximum(999999)if self.product:self.stock_quantity.setValue(int(self.product[7]))self.warning_quantity = QSpinBox()self.warning_quantity.setMaximum(999999)if self.product:self.warning_quantity.setValue(int(self.product[8]))# Add fields to layoutlayout.addRow('商品编码:', self.code)layout.addRow('商品名称:', self.name)layout.addRow('规格型号:', self.specification)layout.addRow('单位:', self.unit)layout.addRow('分类:', self.category)layout.addRow('成本价:', self.cost_price)layout.addRow('销售价:', self.selling_price)layout.addRow('库存数量:', self.stock_quantity)layout.addRow('库存预警值:', self.warning_quantity)# Add buttonsbuttons_layout = QHBoxLayout()save_btn = QPushButton('保存')save_btn.clicked.connect(self.accept)cancel_btn = QPushButton('取消')cancel_btn.clicked.connect(self.reject)buttons_layout.addWidget(save_btn)buttons_layout.addWidget(cancel_btn)layout.addRow(buttons_layout)def get_data(self):return [self.code.text(),self.name.text(),self.specification.text(),self.unit.text(),self.category.text(),str(self.cost_price.value()),str(self.selling_price.value()),str(self.stock_quantity.value()),str(self.warning_quantity.value())]class ProductsTab(QWidget):def __init__(self, db):super().__init__()self.db = dbself.init_ui()self.load_products()self.editing = Falsedef init_ui(self):layout = QVBoxLayout(self)# Create top toolbartoolbar = QHBoxLayout()# Add product buttonself.add_btn = QPushButton('添加商品')self.add_btn.clicked.connect(self.add_product)toolbar.addWidget(self.add_btn)# Edit product buttonself.edit_btn = QPushButton('编辑商品')self.edit_btn.clicked.connect(self.edit_product)toolbar.addWidget(self.edit_btn)# Delete product buttonself.delete_btn = QPushButton('删除商品')self.delete_btn.clicked.connect(self.delete_product)toolbar.addWidget(self.delete_btn)# Export buttonself.export_btn = QPushButton('导出Excel')self.export_btn.clicked.connect(self.export_to_excel)toolbar.addWidget(self.export_btn)# Import buttonself.import_btn = QPushButton('导入Excel')self.import_btn.clicked.connect(self.import_from_excel)toolbar.addWidget(self.import_btn)# Search boxself.search_input = QLineEdit()self.search_input.setPlaceholderText('搜索商品...')self.search_input.textChanged.connect(self.search_products)toolbar.addWidget(self.search_input)toolbar.addStretch()layout.addLayout(toolbar)# Create tableself.table = QTableWidget()self.table.setColumnCount(9)self.table.setHorizontalHeaderLabels(['商品编码', '商品名称', '规格型号', '单位', '分类','成本价', '销售价', '库存数量', '库存预警值'])header = self.table.horizontalHeader()header.setSectionResizeMode(QHeaderView.Stretch)# Enable selection of entire rowsself.table.setSelectionBehavior(QTableWidget.SelectRows)self.table.setSelectionMode(QTableWidget.SingleSelection)layout.addWidget(self.table)def export_to_excel(self):try:# Create a new workbook and select the active sheetwb = openpyxl.Workbook()ws = wb.activews.title = "商品列表"# Write headersheaders = ['商品编码', '商品名称', '规格型号', '单位', '分类','成本价', '销售价', '库存数量', '库存预警值']for col, header in enumerate(headers, 1):ws.cell(row=1, column=col, value=header)# Write datafor row in range(self.table.rowCount()):for col in range(self.table.columnCount()):item = self.table.item(row, col)value = item.text() if item else ''ws.cell(row=row+2, column=col+1, value=value)# Get save file namefile_name = f"商品列表_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"file_path, _ = QFileDialog.getSaveFileName(self, "导出Excel", file_name, "Excel Files (*.xlsx)")if file_path:wb.save(file_path)QMessageBox.information(self, "成功", "导出成功!")except Exception as e:QMessageBox.warning(self, "错误", f"导出失败: {str(e)}")def import_from_excel(self):try:# Get file namefile_path, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xlsx)")if not file_path:return# Load workbookwb = openpyxl.load_workbook(file_path)ws = wb.active# Get all rowsrows = list(ws.rows)if len(rows) < 2:  # Check if file has data (header + at least one row)QMessageBox.warning(self, "错误", "Excel文件为空或格式不正确")return# Verify headersexpected_headers = ['商品编码', '商品名称', '规格型号', '单位', '分类','成本价', '销售价', '库存数量', '库存预警值']headers = [cell.value for cell in rows[0]]if headers != expected_headers:QMessageBox.warning(self, "错误", "Excel文件格式不正确,请使用导出的模板")return# Begin transactionconn = self.db.connect()cursor = conn.cursor()try:# Process each rowfor row in rows[1:]:  # Skip header rowvalues = [cell.value for cell in row]# Convert numeric valuesvalues[5] = float(values[5]) if values[5] else 0  # cost_pricevalues[6] = float(values[6]) if values[6] else 0  # selling_pricevalues[7] = int(values[7]) if values[7] else 0    # stock_quantityvalues[8] = int(values[8]) if values[8] else 0    # warning_quantity# Insert or update productquery = '''INSERT OR REPLACE INTO products (code, name, specification, unit, category,cost_price, selling_price, stock_quantity, warning_quantity)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'''cursor.execute(query, values)conn.commit()QMessageBox.information(self, "成功", "导入成功!")self.load_products()  # Refresh tableexcept Exception as e:conn.rollback()raise eexcept Exception as e:QMessageBox.warning(self, "错误", f"导入失败: {str(e)}")def load_products(self):self.table.setRowCount(0)query = '''SELECT code, name, specification, unit, category,cost_price, selling_price, stock_quantity, warning_quantityFROM products'''products = self.db.fetch_query(query)for row, product in enumerate(products):self.table.insertRow(row)for col, value in enumerate(product):item = QTableWidgetItem(str(value) if value is not None else '')self.table.setItem(row, col, item)def add_product(self):dialog = ProductEditDialog(parent=self)if dialog.exec_():values = dialog.get_data()try:# Check if product code existscursor = self.db.connect().cursor()cursor.execute("SELECT code FROM products WHERE code = ?", (values[0],))if cursor.fetchone():QMessageBox.warning(self, "错误", f"商品编码 '{values[0]}' 已存在")return# Insert new productquery = '''INSERT INTO products (code, name, specification, unit, category,cost_price, selling_price, stock_quantity, warning_quantity)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'''self.db.execute_query(query, tuple(values))self.load_products()except Exception as e:QMessageBox.warning(self, '错误', f'保存失败: {str(e)}')def edit_product(self):current_row = self.table.currentRow()if current_row < 0:QMessageBox.warning(self, "提示", "请先选择要编辑的商品")return# Get current product datavalues = []for col in range(self.table.columnCount()):item = self.table.item(current_row, col)values.append(item.text() if item else '')dialog = ProductEditDialog(values, self)if dialog.exec_():new_values = dialog.get_data()try:# Check if new code exists (if code was changed)if new_values[0] != values[0]:cursor = self.db.connect().cursor()cursor.execute("SELECT code FROM products WHERE code = ?", (new_values[0],))if cursor.fetchone():QMessageBox.warning(self, "错误", f"商品编码 '{new_values[0]}' 已存在")return# Update productquery = '''UPDATE products SET code = ?, name = ?, specification = ?, unit = ?, category = ?, cost_price = ?, selling_price = ?,stock_quantity = ?, warning_quantity = ?WHERE code = ?'''self.db.execute_query(query, tuple(new_values + [values[0]]))self.load_products()except Exception as e:QMessageBox.warning(self, '错误', f'保存失败: {str(e)}')def delete_product(self):current_row = self.table.currentRow()if current_row < 0:QMessageBox.warning(self, "提示", "请先选择要删除的商品")returnproduct_code = self.table.item(current_row, 0).text()product_name = self.table.item(current_row, 1).text()reply = QMessageBox.question(self, '确认删除',f'确定要删除商品 "{product_name}" 吗?',QMessageBox.Yes | QMessageBox.No)if reply == QMessageBox.Yes:try:# Check if product is referenced in other tablescursor = self.db.connect().cursor()# Check purchase orderscursor.execute("""SELECT COUNT(*) FROM purchase_order_details podJOIN products p ON pod.product_id = p.idWHERE p.code = ?""", (product_code,))if cursor.fetchone()[0] > 0:QMessageBox.warning(self, "错误", "该商品已存在采购记录,无法删除")return# Check sales orderscursor.execute("""SELECT COUNT(*) FROM sales_order_details sodJOIN products p ON sod.product_id = p.idWHERE p.code = ?""", (product_code,))if cursor.fetchone()[0] > 0:QMessageBox.warning(self, "错误", "该商品已存在销售记录,无法删除")return# Check inventory recordscursor.execute("""SELECT COUNT(*) FROM inventory_records irJOIN products p ON ir.product_id = p.idWHERE p.code = ?""", (product_code,))if cursor.fetchone()[0] > 0:QMessageBox.warning(self, "错误", "该商品已存在库存记录,无法删除")return# Delete the productself.db.execute_query("DELETE FROM products WHERE code = ?", (product_code,))self.load_products()QMessageBox.information(self, "成功", "商品已删除")except Exception as e:QMessageBox.warning(self, '错误', f'删除失败: {str(e)}')def search_products(self):search_text = self.search_input.text().lower()for row in range(self.table.rowCount()):match = Falsefor col in range(self.table.columnCount()):item = self.table.item(row, col)if item and search_text in item.text().lower():match = Truebreakself.table.setRowHidden(row, not match)def on_item_changed(self, item):row = item.row()try:# Get all values from the rowvalues = []for col in range(self.table.columnCount()):cell_item = self.table.item(row, col)values.append(cell_item.text() if cell_item else '')# Update or insert into databasequery = '''INSERT OR REPLACE INTO products (code, name, specification, unit, category,cost_price, selling_price, stock_quantity, warning_quantity)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'''# Convert numeric valuesvalues[5] = float(values[5]) if values[5] else 0  # cost_pricevalues[6] = float(values[6]) if values[6] else 0  # selling_pricevalues[7] = int(values[7]) if values[7] else 0    # stock_quantityvalues[8] = int(values[8]) if values[8] else 0    # warning_quantityself.db.execute_query(query, tuple(values))except Exception as e:QMessageBox.warning(self, '错误', f'保存失败: {str(e)}')self.load_products()  # Reload to revert changes 

 

供应商管理 suppliers.py

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,QLabel, QLineEdit, QTableWidget, QTableWidgetItem,QMessageBox, QHeaderView, QFileDialog, QDialog,QFormLayout)
from PySide6.QtCore import Qt
import openpyxl
from datetime import datetimeclass SupplierEditDialog(QDialog):def __init__(self, supplier=None, parent=None):super().__init__(parent)self.supplier = supplierself.init_ui()def init_ui(self):self.setWindowTitle('编辑供应商' if self.supplier else '新增供应商')layout = QFormLayout(self)# Create input fieldsself.name = QLineEdit(self.supplier[0] if self.supplier else '')self.contact_person = QLineEdit(self.supplier[1] if self.supplier else '')self.phone = QLineEdit(self.supplier[2] if self.supplier else '')self.address = QLineEdit(self.supplier[3] if self.supplier else '')self.payment_terms = QLineEdit(self.supplier[4] if self.supplier else '')# Add fields to layoutlayout.addRow('供应商名称:', self.name)layout.addRow('联系人:', self.contact_person)layout.addRow('联系电话:', self.phone)layout.addRow('地址:', self.address)layout.addRow('账期:', self.payment_terms)# Add buttonsbuttons_layout = QHBoxLayout()save_btn = QPushButton('保存')save_btn.clicked.connect(self.accept)cancel_btn = QPushButton('取消')cancel_btn.clicked.connect(self.reject)buttons_layout.addWidget(save_btn)buttons_layout.addWidget(cancel_btn)layout.addRow(buttons_layout)def get_data(self):return [self.name.text(),self.contact_person.text(),self.phone.text(),self.address.text(),self.payment_terms.text()]class SuppliersTab(QWidget):def __init__(self, db):super().__init__()self.db = dbself.init_ui()self.load_suppliers()self.editing = Falsedef init_ui(self):layout = QVBoxLayout(self)# Create toolbartoolbar = QHBoxLayout()# Add supplier buttonself.add_btn = QPushButton('新建供应商')self.add_btn.clicked.connect(self.add_supplier)toolbar.addWidget(self.add_btn)# Edit supplier buttonself.edit_btn = QPushButton('编辑供应商')self.edit_btn.clicked.connect(self.edit_supplier)toolbar.addWidget(self.edit_btn)# Delete supplier buttonself.delete_btn = QPushButton('删除供应商')self.delete_btn.clicked.connect(self.delete_supplier)toolbar.addWidget(self.delete_btn)# Import/Export buttonsself.import_btn = QPushButton('导入')self.import_btn.clicked.connect(self.import_from_excel)toolbar.addWidget(self.import_btn)self.export_btn = QPushButton('导出')self.export_btn.clicked.connect(self.export_to_excel)toolbar.addWidget(self.export_btn)# Search boxself.search_input = QLineEdit()self.search_input.setPlaceholderText('搜索供应商...')self.search_input.textChanged.connect(self.search_suppliers)toolbar.addWidget(self.search_input)toolbar.addStretch()layout.addLayout(toolbar)# Create tableself.table = QTableWidget()self.table.setColumnCount(5)self.table.setHorizontalHeaderLabels(['供应商名称', '联系人', '联系电话', '地址', '账期'])header = self.table.horizontalHeader()header.setSectionResizeMode(QHeaderView.Stretch)# Enable selection of entire rowsself.table.setSelectionBehavior(QTableWidget.SelectRows)self.table.setSelectionMode(QTableWidget.SingleSelection)layout.addWidget(self.table)def add_supplier(self):dialog = SupplierEditDialog(parent=self)if dialog.exec_():values = dialog.get_data()try:# Check if supplier name existscursor = self.db.connect().cursor()cursor.execute("SELECT name FROM suppliers WHERE name = ?", (values[0],))if cursor.fetchone():QMessageBox.warning(self, "错误", f"供应商 '{values[0]}' 已存在")return# Insert new supplierquery = '''INSERT INTO suppliers (name, contact_person, phone, address, payment_terms)VALUES (?, ?, ?, ?, ?)'''self.db.execute_query(query, tuple(values))self.load_suppliers()except Exception as e:QMessageBox.warning(self, '错误', f'保存失败: {str(e)}')def edit_supplier(self):current_row = self.table.currentRow()if current_row < 0:QMessageBox.warning(self, "提示", "请先选择要编辑的供应商")return# Get current supplier datavalues = []for col in range(self.table.columnCount()):item = self.table.item(current_row, col)values.append(item.text() if item else '')dialog = SupplierEditDialog(values, self)if dialog.exec_():new_values = dialog.get_data()try:# Check if new name exists (if name was changed)if new_values[0] != values[0]:cursor = self.db.connect().cursor()cursor.execute("SELECT name FROM suppliers WHERE name = ?", (new_values[0],))if cursor.fetchone():QMessageBox.warning(self, "错误", f"供应商 '{new_values[0]}' 已存在")return# Update supplierquery = '''UPDATE suppliers SET name = ?, contact_person = ?, phone = ?, address = ?, payment_terms = ?WHERE name = ?'''self.db.execute_query(query, tuple(new_values + [values[0]]))self.load_suppliers()except Exception as e:QMessageBox.warning(self, '错误', f'保存失败: {str(e)}')def delete_supplier(self):current_row = self.table.currentRow()if current_row < 0:QMessageBox.warning(self, "提示", "请先选择要删除的供应商")returnsupplier_name = self.table.item(current_row, 0).text()reply = QMessageBox.question(self, '确认删除',f'确定要删除供应商 "{supplier_name}" 吗?',QMessageBox.Yes | QMessageBox.No)if reply == QMessageBox.Yes:try:# Check if supplier is referenced in purchase orderscursor = self.db.connect().cursor()cursor.execute("""SELECT COUNT(*) FROM purchase_orders poJOIN suppliers s ON po.supplier_id = s.idWHERE s.name = ?""", (supplier_name,))if cursor.fetchone()[0] > 0:QMessageBox.warning(self, "错误", "该供应商已有采购记录,无法删除")return# Delete the supplierself.db.execute_query("DELETE FROM suppliers WHERE name = ?", (supplier_name,))self.load_suppliers()QMessageBox.information(self, "成功", "供应商已删除")except Exception as e:QMessageBox.warning(self, '错误', f'删除失败: {str(e)}')def export_to_excel(self):try:# Create a new workbook and select the active sheetwb = openpyxl.Workbook()ws = wb.activews.title = "供应商列表"# Write headersheaders = ['供应商名称', '联系人', '联系电话', '地址', '账期']for col, header in enumerate(headers, 1):ws.cell(row=1, column=col, value=header)# Write datafor row in range(self.table.rowCount()):for col in range(self.table.columnCount()):item = self.table.item(row, col)value = item.text() if item else ''ws.cell(row=row+2, column=col+1, value=value)# Get save file namefile_name = f"供应商列表_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"file_path, _ = QFileDialog.getSaveFileName(self, "导出Excel", file_name, "Excel Files (*.xlsx)")if file_path:wb.save(file_path)QMessageBox.information(self, "成功", "导出成功!")except Exception as e:QMessageBox.warning(self, "错误", f"导出失败: {str(e)}")def import_from_excel(self):try:# Get file namefile_path, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xlsx)")if not file_path:return# Load workbookwb = openpyxl.load_workbook(file_path)ws = wb.active# Get all rowsrows = list(ws.rows)if len(rows) < 2:  # Check if file has data (header + at least one row)QMessageBox.warning(self, "错误", "Excel文件为空或格式不正确")return# Verify headersexpected_headers = ['供应商名称', '联系人', '联系电话', '地址', '账期']headers = [cell.value for cell in rows[0]]if headers != expected_headers:QMessageBox.warning(self, "错误", "Excel文件格式不正确,请使用导出的模板")return# Begin transactionconn = self.db.connect()cursor = conn.cursor()try:# Process each rowduplicates = []new_suppliers = []for row in rows[1:]:  # Skip header rowvalues = [cell.value if cell.value is not None else '' for cell in row]supplier_name = values[0]# Check if supplier existscursor.execute("SELECT name FROM suppliers WHERE name = ?", (supplier_name,))if cursor.fetchone():duplicates.append(values)else:new_suppliers.append(values)# Handle duplicatesif duplicates:duplicate_names = "\n".join(d[0] for d in duplicates)reply = QMessageBox.question(self, "发现重复供应商",f"以下供应商已存在:\n{duplicate_names}\n\n是否更新这些供应商的信息?",QMessageBox.Yes | QMessageBox.No)if reply == QMessageBox.Yes:# Update existing suppliersfor values in duplicates:query = '''UPDATE suppliers SET contact_person = ?, phone = ?, address = ?, payment_terms = ?WHERE name = ?'''cursor.execute(query, (values[1], values[2], values[3], values[4], values[0]))# Insert new suppliersfor values in new_suppliers:query = '''INSERT INTO suppliers (name, contact_person, phone, address, payment_terms)VALUES (?, ?, ?, ?, ?)'''cursor.execute(query, values)conn.commit()# Show summarymsg = f"导入完成!\n新增供应商:{len(new_suppliers)}个"if duplicates:if reply == QMessageBox.Yes:msg += f"\n更新供应商:{len(duplicates)}个"else:msg += f"\n跳过重复供应商:{len(duplicates)}个"QMessageBox.information(self, "成功", msg)self.load_suppliers()  # Refresh tableexcept Exception as e:conn.rollback()raise eexcept Exception as e:QMessageBox.warning(self, "错误", f"导入失败: {str(e)}")def load_suppliers(self):self.editing = True  # Prevent triggering item change eventsself.table.setRowCount(0)query = '''SELECT name, contact_person, phone, address, payment_termsFROM suppliers'''suppliers = self.db.fetch_query(query)for row, supplier in enumerate(suppliers):self.table.insertRow(row)for col, value in enumerate(supplier):item = QTableWidgetItem(str(value) if value is not None else '')self.table.setItem(row, col, item)self.editing = False  # Re-enable item change eventsdef search_suppliers(self):search_text = self.search_input.text().lower()for row in range(self.table.rowCount()):# Only search in the supplier name column (column 0)item = self.table.item(row, 0)  # Get supplier name cellmatch = item and search_text in item.text().lower()self.table.setRowHidden(row, not match) 

客户管理 customers.py

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,QLabel, QLineEdit, QTableWidget, QTableWidgetItem,QMessageBox, QHeaderView, QFileDialog, QDialog,QFormLayout)
from PySide6.QtCore import Qt
import openpyxl
from datetime import datetimeclass SupplierEditDialog(QDialog):def __init__(self, supplier=None, parent=None):super().__init__(parent)self.supplier = supplierself.init_ui()def init_ui(self):self.setWindowTitle('编辑供应商' if self.supplier else '新增供应商')layout = QFormLayout(self)# Create input fieldsself.name = QLineEdit(self.supplier[0] if self.supplier else '')self.contact_person = QLineEdit(self.supplier[1] if self.supplier else '')self.phone = QLineEdit(self.supplier[2] if self.supplier else '')self.address = QLineEdit(self.supplier[3] if self.supplier else '')self.payment_terms = QLineEdit(self.supplier[4] if self.supplier else '')# Add fields to layoutlayout.addRow('供应商名称:', self.name)layout.addRow('联系人:', self.contact_person)layout.addRow('联系电话:', self.phone)layout.addRow('地址:', self.address)layout.addRow('账期:', self.payment_terms)# Add buttonsbuttons_layout = QHBoxLayout()save_btn = QPushButton('保存')save_btn.clicked.connect(self.accept)cancel_btn = QPushButton('取消')cancel_btn.clicked.connect(self.reject)buttons_layout.addWidget(save_btn)buttons_layout.addWidget(cancel_btn)layout.addRow(buttons_layout)def get_data(self):return [self.name.text(),self.contact_person.text(),self.phone.text(),self.address.text(),self.payment_terms.text()]class SuppliersTab(QWidget):def __init__(self, db):super().__init__()self.db = dbself.init_ui()self.load_suppliers()self.editing = Falsedef init_ui(self):layout = QVBoxLayout(self)# Create toolbartoolbar = QHBoxLayout()# Add supplier buttonself.add_btn = QPushButton('新建供应商')self.add_btn.clicked.connect(self.add_supplier)toolbar.addWidget(self.add_btn)# Edit supplier buttonself.edit_btn = QPushButton('编辑供应商')self.edit_btn.clicked.connect(self.edit_supplier)toolbar.addWidget(self.edit_btn)# Delete supplier buttonself.delete_btn = QPushButton('删除供应商')self.delete_btn.clicked.connect(self.delete_supplier)toolbar.addWidget(self.delete_btn)# Import/Export buttonsself.import_btn = QPushButton('导入')self.import_btn.clicked.connect(self.import_from_excel)toolbar.addWidget(self.import_btn)self.export_btn = QPushButton('导出')self.export_btn.clicked.connect(self.export_to_excel)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/3758.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

放大芯片参数阅读

一、芯片的增益能力 1. GBW&#xff08;增益带宽积&#xff09; 例如&#xff0c;GBW (typ) 1 MHz。 增益带宽积&#xff08;Gain Bandwidth Product&#xff09;是一个关键参数&#xff0c;用于计算在特定频率下的最大增益。 定义公式为&#xff1a; 增益带宽G…

编程工具箱(免费,离线可用)

https://www.yuque.com/huanmin-4bkaa/ii1hx1?# 《工具箱》 常用的大部分工具都有, 比如mysql可视化 redis可视化, json编辑器, 加解密等(免费,离线可用) 后续也会慢慢的集成

SpringBoot项目打war包要点

1. 修改pom文件packaging 2. 不使用内置tomcat 3. 加一个类 4. 修改外部tomcat配置文件 5. 修改nginx配置文件&#xff0c;构建集群 资料来自网络

探索与创作:2024年CSDN平台上的成长与突破

文章目录 我与CSDN的初次邂逅初学阶段的阅读CSDN&#xff1a;编程新手的避风港初学者的福音&#xff1a;细致入微的知识讲解考试复习神器&#xff1a;技术总结的“救命指南”曾经的自己&#xff1a;为何迟迟不迈出写博客的第一步兴趣萌芽&#xff1a;从“读”到“想写”的初体验…

Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲

随着 Java 技术栈的不断发展&#xff0c;Spring 框架在应用开发中占据了举足轻重的地位。Spring 提供了丰富的模块来支持不同的应用场景&#xff0c;其中 spring-instrument 模块作为其中的一部分&#xff0c;提供了强大的类加载器增强功能。该模块通过字节码操作和类加载期织入…

微信小程序

一、小程序文件结构 1.目录结构 pages文件夹&#xff1a;存放【页面文件夹】&#xff0c;一个【页面文件夹】就是一个页面&#xff0c;存放着小程序页面文件。即pages中的每一个文件夹都存放着一个小程序页面的文件&#xff08;js、wxml、json、wxss&#xff09; 页面文件夹…

计算机网络-数据链路层

重点内容&#xff1a; (1) 数据链路层的点对点信道和广播信道的特点&#xff0c;以及这两种信道所使用的协议&#xff08; PPP协议以及 CSMA/CD 协议&#xff09;的特点。 (2) 数据链路层的三个基本问题&#xff1a;封装成帧、透明传输和差错检测。 (3) 以太网 MAC 层的…

Linux提权-02 sudo提权

文章目录 1. sudo 提权原理1.1 原理1.2 sudo文件配置 2. 提权利用方式2.1 sudo权限分配不当2.2 sudo脚本篡改2.3 sudo脚本参数利用2.4 sudo绕过路径执行2.5 sudo LD_PRELOAD环境变量2.6 sudo caching2.7 sudo令牌进程注入 3. 参考 1. sudo 提权原理 1.1 原理 sudo是一个用于在…

如何学习网络安全?有哪些小窍门?

学好网络安全其实没有所谓的捷径&#xff0c;也没有什么小窍门。 入门网络安全首先要有浓厚的学习兴趣&#xff0c;不然很容易就变成了从入门到放弃了。 其次要能静下心&#xff0c;踏踏实实的打好基础。如果你是零基础&#xff0c;建议从Web安全入手&#xff0c;课程难度相对…

AV1视频编解码简介、码流结构(OBU)

我的音视频/流媒体开源项目(github) 目录 一、AV1编码技术 二、AV1码流结构(OBU) 三、IVF文件格式 四、ffmpeg支持AV1 五、关于常见格式对AV1的封装 一、AV1编码技术 AV1是由开放媒体联盟(AOM&#xff0c;Alliance for Open Media)在2018年发布的&#xff0c;AV1的前身…

软考高级5个资格、中级常考4个资格简介及难易程度排序

一、软考高级5个资格 01、网络规划设计师 资格简介&#xff1a;网络规划设计师要求考生具备全面的网络规划、设计、部署和管理能力&#xff1b;该资格考试适合那些在网络规划和设计方面具有较好理论基础和较丰富从业经验的人员参加。 02、系统分析师 资格简介&#xff1a;系统分…

【21】Word:德国旅游业务❗

目录 题目 NO1.2.3 NO4 NO5.6 NO7 NO8.9.10.11 题目 NO1.2.3 F12&#xff1a;另存为布局→页面设置→页边距&#xff1a;上下左右选中“德国主要城市”→开始→字体对话框→字体/字号→文本效果&#xff1a;段落对话框→对齐方式/字符间距/段落间距 NO4 布局→表对话框…

Flink(十):DataStream API (七) 状态

1. 状态的定义 在 Apache Flink 中&#xff0c;状态&#xff08;State&#xff09; 是指在数据流处理过程中需要持久化和追踪的中间数据&#xff0c;它允许 Flink 在处理事件时保持上下文信息&#xff0c;从而支持复杂的流式计算任务&#xff0c;如聚合、窗口计算、联接等。状…

【实践】操作系统智能助手OS Copilot新功能测评

一、引言 数字化加速发展&#xff0c;尤其人工智能的发展速度越来越快。操作系统智能助手成为提升用户体验与操作效率的关键因素。OS Copilot借助语言模型&#xff0c;人工智能等&#xff0c;对操作系统的自然语言交互操作 推出很多功能&#xff0c;值得开发&#xff0c;尤其运…

诡异的Spring @RequestBody驼峰命名字段映射失败为null问题记录

问题 一个非常常规的Spring Controller&#xff0c;代码如下&#xff1a; import lombok.RequiredArgsConstructor;Slf4j RestController RequiredArgsConstructor RequestMapping("/api/v1/config") public class ConfigController {private final ConfigService …

图形化界面MySQL(MySQL)(超级详细)

目录 1.官网地址 1.1在Linux直接点击NO thanks…? 1.2任何远端登录&#xff0c;再把jj数据库给授权 1.3建立新用户 优点和好处 示例代码&#xff08;MySQL Workbench&#xff09; 示例代码&#xff08;phpMyAdmin&#xff09; 总结 图形化界面 MySQL 工具大全及其功能…

flutter开发-figma交互设计图可以转换为flutter源代码-如何将设计图转换为flutter源代码-优雅草央千澈

flutter开发-figma交互设计图可以转换为flutter源代码-如何将设计图转换为flutter源代码-优雅草央千澈 开发背景 可能大家听过过蓝湖可以转ui设计图为vue.js&#xff0c;react native代码&#xff0c;那么请问听说过将figma的设计图转换为flutter源代码吗?本文优雅草央千澈带…

SpringBoot错误码国际化

先看测试效果&#xff1a; 1. 设置中文 2.设置英文 文件结构 1.中文和英文的错误消息配置 package com.ldj.mybatisflex.common;import lombok.Getter;/*** User: ldj* Date: 2025/1/12* Time: 17:50* Description: 异常消息枚举*/ Getter public enum ExceptionEnum {//…

Pytorch|YOLO

&#x1f368; 本文为&#x1f517;365天深度学习训练营中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊 一、 前期准备 1. 设置GPU 如果设备上支持GPU就使用GPU,否则使用CPU import torch import torch.nn as nn import torchvision.transforms as transforms im…

SpringBoot2 + Flowable(UI)

文章目录 引言I 技术栈软件架构基于 Vue.js 和 Element UI 的后台管理系统工程结构II 依赖rest,logic,conf 的依赖工作流flowable jar包flowable-ui所需jar包III 配置jdbc 配置 nullCatalogMeansCurrent = true引言 I 技术栈 软件架构 前端基于vue 、element-ui框架分模块设…