Esempio n. 1
0
 def on_CmdDelete_clicked(self):
     uid = self.getCurrentSelectPKValue()
     if uid is None:
         return
     sql = """select a.archives_pk from t_archives as a 
             right join t_archives_project as p 
             on a.archives_pk=p.archives_pk  
             where p.project_pk={}"""
     lst = JPDb().getDataList(sql.format(uid))
     if lst:
         lst1 = []
         for i in lst:
             for y in i:
                 lst1.append(str(y))
         s = ",".join(lst1)
         errStr = '以下档案关联本项目,无法删除\n' + s
         msgBox = QMessageBox(QMessageBox.Critical, u'错误', errStr)
         msgBox.exec_()
         return
     del_txt = '确认要删除此项目?\n'
     del_txt = del_txt + 'Are you sure you want to delete this Project?'
     sql = "DELETE FROM t_project_base_info WHERE project_pk = {}"
     if QMessageBox.question(self, '提示', del_txt,
                             (QMessageBox.Yes | QMessageBox.No),
                             QMessageBox.Yes) == QMessageBox.Yes:
         JPDb().executeTransaction(sql.format(uid))
         self.refreshTable()
Esempio n. 2
0
 def on_CmdCancel_clicked(self):
     cu_id = self.getCurrentSelectPKValue()
     sql = "update t_order set fCanceled=1 where fOrderID='{pk}'"
     db = JPDb()
     sql = sql.format(pk=cu_id)
     msg = '您确认要作废此订单?\n'
     msg = msg + "Are you sure you want to cancel this order?"
     msg = msg.format(pk=cu_id)
     if QMessageBox.question(JPPub().MainForm, '确认', msg,
                             QMessageBox.Yes | QMessageBox.No,
                             QMessageBox.No) == QMessageBox.Yes:
         db.executeTransaction(sql)
         self.refreshListForm()
Esempio n. 3
0
    def on_butSave_clicked(self):
        try:
            lst0 = self.getSqls(self.PKRole)
            lst = lst0 + [JPDb().LAST_INSERT_ID_SQL()]
            isOK, result = JPDb().executeTransaction(lst)
            if isOK:
                self.ui.butSave.setEnabled(False)
                self.afterSaveData.emit(str(result))
                QMessageBox.information(self, '完成',
                                        '保存数据完成!\nSave data complete!')

        except Exception as e:
            msgBox = QMessageBox(QMessageBox.Critical, u'提示', str(e))
            msgBox.exec_()
Esempio n. 4
0
 def readAddtionalFromDatabase(self):
     """从数据库中加载给定PK的一个文档的所有附件信息到一个列表中"""
     sql = """
     select additional_pk,
         archives_pk,
         file_index,
         file_type,
         file_pk,
         original_name,
         '' as original_path,
         file_name,
         False as deleted
     from v_additional_archives
     where archives_pk={}
     order by file_index
     """
     if not self.isNewMode:
         # 从数据库取数据,生成多个addtionalInfo对象
         pk = self.ui.archives_pk.text().replace(",", "")
         d_path = self.archivesPathInDatabase
         dic = JPDb().getDict(sql.format(pk))
         for r in dic:
             add = addtionalInfo()
             for k in add.__dict__.keys():
                 if k in r:
                     add.__dict__[k] = r[k]
             add.md5FilePath = os.path.join(d_path, r['file_name'])
             add.md5FileName = os.path.splitext(r['file_name'])[0]
             add.isNew = False
             self.addtionalInfo.append(add)
Esempio n. 5
0
 def on_CmdDelete_clicked(self):
     uid = self.getCurrentSelectPKValue()
     if uid is None:
         return
     sql0 = """
         SELECT fCustomerID
         FROM (
             SELECT fCustomerID
             FROM v_order
             UNION ALL
             SELECT fCustomerID
             FROM v_quotation
         ) Q
         WHERE Q.fCustomerID = {}
         LIMIT 1"""
     tab = JPQueryFieldInfo(sql0.format(uid))
     if len(tab):
         txt = '该客户已经存在订单,无法删除!\n'
         txt = txt + "The customer already has an order and can not delete it!"
         QMessageBox.warning(self, '提示', txt, QMessageBox.Cancel,
                             QMessageBox.Cancel)
         return
     del_txt = '确认要删除此客户?\n'
     del_txt = del_txt + 'Are you sure you want to delete this customer?'
     sql = "DELETE FROM t_customer WHERE fCustomerID = {}"
     if QMessageBox.question(self, '提示', del_txt,
                             (QMessageBox.Yes | QMessageBox.No),
                             QMessageBox.Yes) == QMessageBox.Yes:
         JPDb().executeTransaction(sql.format(uid))
         self.refreshTable()
Esempio n. 6
0
 def on_CmdDelete_clicked(self):
     pid = self.getCurrentSelectPKValue()
     if pid is None:
         return
     sql0 = f"""
         select fProductID from 
         t_product_outbound_order_detail 
         where fProductID={pid} Limit 1 
         union all 
         select fProductID 
         from t_product_warehousereceipt_order_detail 
         where fProductID={pid} Limit 1 """
     tab = JPQueryFieldInfo(sql0)
     if len(tab):
         txt = '该产品已经存在订单,无法删除!\n'
         txt = txt + "The product already has an order and can not delete it!"
         QMessageBox.warning(self, '提示', txt, QMessageBox.Cancel,
                             QMessageBox.Cancel)
         return
     del_txt = '确认要删除此产品?\n'
     del_txt = del_txt + 'Are you sure you want to delete this product?'
     sql = f"DELETE FROM t_product_information WHERE fID = {pid}"
     if QMessageBox.question(self, '提示', del_txt,
                             (QMessageBox.Yes | QMessageBox.No),
                             QMessageBox.Yes) == QMessageBox.Yes:
         JPDb().executeTransaction(sql)
         self.refreshTable()
Esempio n. 7
0
    def on_butSave_clicked(self):
        try:
            s1 = self.getSqls(self.PKRole)
        except Exception as e:
            t = '生成保存档案数据SQL命令出错,错误信息:\n{}'
            msgBox = QMessageBox(QMessageBox.Critical, u'提示', t.format(str(e)))
            msgBox.exec_()
            return

        try:
            s2 = self.CopyPicAndGetSaveFileSQL()
        except Exception as e:
            t = '复制文件或生成保存文件数据SQL命令出错,错误信息:\n{}'
            msgBox = QMessageBox(QMessageBox.Critical, u'提示', t.format(str(e)))
            msgBox.exec_()
            return
        pkSQL = []
        if self.isNewMode:
            sPK = JPDb().LAST_INSERT_ID_SQL()
            pkSQL.append("{} into @archives_pk;".format(sPK))
        if self.isEditMode:
            cur_pk = self.ui.archives_pk.text().replace(",", "")
            pkSQL.append('Select {} into @archives_pk;'.format(cur_pk))
        # 更新关联项目的SQL
        up_projectSQL = self.getUpdateProjectSQL()
        # 拼接所有SQL
        SQLS = s1[0:len(s1) - 1] + pkSQL + up_projectSQL + s2
        SQLS.append("Select @archives_pk;")

        # 执行sql
        try:
            print(SQLS)
            isOK, result = JPDb().executeTransaction(SQLS)
            if isOK:
                self.ui.butSave.setEnabled(False)
                self.afterSaveData.emit(result)
                self.currentRowEditComplete.emit(self._currentEditModelRow)
                QMessageBox.information(self, '完成',
                                        '保存数据完成!\nSave data complete!')
        except Exception as e:
            msgBox = QMessageBox(QMessageBox.Critical, u'提示', str(e))
            msgBox.exec_()
        finally:
            self.close()
Esempio n. 8
0
 def on_CmdConfirm_clicked(self):
     us = JPUser()
     uid = us.currentUserID()
     cu_id = self.getCurrentSelectPKValue()
     if self.getCurrentColumnValue(13) == 1:
         msg = '单据已经确认,无法重复确认!\n'
         msg = msg + 'The payment has been confirmed and cannot be repeated.'
         QMessageBox.information(JPPub().MainForm, '提示', msg)
         return
     sql0 = f"select '{cu_id}';"
     sql1 = f"update t_order set fConfirmed=1,fConfirmID={uid} where fOrderID='{cu_id}'"
     sql2 = f"update t_product_outbound_order set fConfirmed=1,fConfirmID={uid} where fOrderID='{cu_id}'"
     sql3 = f"""
         UPDATE t_product_information AS p,
             (SELECT fProductID,
                 sum(fQuant) AS sum_sl
             FROM t_product_outbound_order_detail
             WHERE fOrderID='{cu_id}'
             GROUP BY  fProductID) AS q1 SET p.fCurrentQuantity=p.fCurrentQuantity-q1.sum_sl
         WHERE p.fID=q1.fProductID;
         """
     if not cu_id:
         return
     else:
         sql = [sql2, sql3, sql0] if cu_id[0:2] == 'PO' else [sql1, sql0]
     db = JPDb()
     msg = "单据【{pk}】确认后将不能修改。是否要确认此付款单?" + '\n'
     msg = msg + 'The bill [{pk}] of payment will not be amended after confirmation.'
     msg = msg + "  Do you want to confirm this payment form?"
     msg = msg.format(pk=cu_id)
     if QMessageBox.question(JPPub().MainForm, '确认', msg,
                             QMessageBox.Yes | QMessageBox.No,
                             QMessageBox.No) == QMessageBox.Yes:
         db.executeTransaction(sql)
         if cu_id[0:2] == 'PO':
             JPPub().broadcastMessage(tablename="t_product_outbound_order",
                                      PK=cu_id,
                                      action='confirmation')
         else:
             JPPub().broadcastMessage(tablename="t_order",
                                      action='confirmation',
                                      PK=cu_id)
         self.refreshListForm()
Esempio n. 9
0
 def onGetFieldsRowSources(self):
     pub = JPPub()
     sql = """select CONCAT(rpad(org_simple_name,7,'  '),'->',org_name), org_pk
                 from t_org_info 
                 order by CONVERT(org_simple_name USING gbk)"""
     lstOrg = JPDb().getDataList(sql)
     return [('state', pub.getEnumList(1), 1),
             ('category', pub.getEnumList(2), 1),
             ('key_project_level', pub.getEnumList(3), 1),
             ('construction_mode', pub.getEnumList(4), 1),
             ('org_pk', lstOrg, 1)]
Esempio n. 10
0
 def on_CmdOrder_clicked(self):
     cu_id = self.getCurrentSelectPKValue()
     newPKSQL = JPDb().NewPkSQL(1)
     sql = [
         """
     INSERT INTO t_order (fOrderID, fOrderDate, fVendedorID
         , fRequiredDeliveryDate, fCustomerID
         , fContato, fCelular, fTelefone, fAmount, fTax
         , fPayable, fDesconto, fNote, fEntryID)
         SELECT @PK, fOrderDate, fVendedorID
             , fRequiredDeliveryDate, fCustomerID
             , fContato, fCelular, fTelefone, fAmount, fTax
             , fPayable, fDesconto, fNote, fEntryID
             FROM t_quotation
             WHERE fOrderID = '{id}';""".format(id=cu_id), """
     INSERT INTO t_order_detail (fOrderID, fQuant, fProductName
         , fLength, fWidth, fPrice, fAmount)
         SELECT @PK, fQuant, fProductName, fLength, fWidth
             , fPrice, fAmount
         FROM t_quotation_detail
         WHERE fOrderID = '{id}';""".format(id=cu_id), """
     UPDATE t_quotation SET fCreatedOrder=1 WHERE fOrderID = '{id}';
     """.format(id=cu_id)
     ]
     sql = newPKSQL[0:2] + sql + newPKSQL[2:]
     for q in sql:
         print(q)
     try:
         isOK, result = JPDb().executeTransaction(sql)
         if isOK:
             info = '已经根据报价单生成了订单【{id}】,请修改此订单信息!\n'
             info = info + 'The order [{id}] has been generated according '
             info = info + 'to the quotation. Please modify the order information.'
             QMessageBox.information(self, "提示", info.format(id=result))
             JPPub().broadcastMessage(tablename="t_order",
                                      action='createOrder',
                                      PK=data)
             self.refreshListForm()
     except Exception as e:
         msgBox = QMessageBox(QMessageBox.Critical, u'提示', str(e))
         msgBox.exec_()
Esempio n. 11
0
 def on_CmdDelete_clicked(self):
     uid = self.getCurrentSelectPKValue()
     if uid is None:
         return
     del_txt = '确认要删除此公司?\n'
     del_txt = del_txt + 'Are you sure you want to delete this company?'
     sql = "update t_org_info set deleted=1 where org_pk='{}'"
     if QMessageBox.question(self, '提示', del_txt,
                             (QMessageBox.Yes | QMessageBox.No),
                             QMessageBox.Yes) == QMessageBox.Yes:
         JPDb().executeTransaction(sql.format(uid))
         self.refreshTable()
Esempio n. 12
0
def md5Exist(filepath: str, con_path):
    """检查文件是否在数据库中已经存在"""
    sql = """select file_Pk
            from t_additionals
            where filemd5=unhex('{}') limit 1;"""
    md5BaseName = GetFileMd5(filepath)
    md5FileName = '.'.join((md5BaseName, getExName(filepath)))
    sql = sql.format(md5BaseName)
    sql = sql.replace('\n', '')
    isOK, pk = JPDb().executeTransaction(sql)
    exist = True if pk else False
    file_pk = pk
    return exist, md5FileName, md5BaseName, file_pk
Esempio n. 13
0
 def __init__(self, selected_project=[]):
     super().__init__()
     self.ListWidget = None
     # self.buttonBox.accepted.connect(self.okClick)
     sql = "Select pk,nm,par from v_project_tree order by pk"
     tree_data = JPDb().getDict(sql)
     self.Dialog = QDialog()
     self.setupUi(self.Dialog)
     self.Dialog.setWindowModality(Qt.ApplicationModal)
     self.treeWidget.setColumnWidth(0, 450)
     self.lineEdit.textChanged.connect(self.actionClick)
     loadTreeview(self.treeWidget, tree_data, selected_project)
     self.butOK.clicked.connect(self.okClicked)
     self.butCancel.clicked.connect(self.onCancelClick)
Esempio n. 14
0
 def readProject(self, pklst):
     self.projectKeyList = pklst
     if pklst:
         sql = """
             SELECT group_concat(project_pk) as pks,
                 group_concat(project_simple_name) as nms
             FROM t_project_base_info
             WHERE project_pk IN ({})
             """
         sql = sql.format(',\n'.join(pklst))
         data = JPDb().getDataList(sql)
         self.ui.label_ProjectLink.setText(data[0][1])
     else:
         self.ui.label_ProjectLink.setText("")
     return
Esempio n. 15
0
 def md5Exist(filepath: str) -> dict:
     """检查文件是否在数据库中已经存在"""
     sql = """select file_pk, file_type,concat('{md5}','.',file_type)  md5FileShortName
     from t_additionals as f where filemd5=unhex('{md5}') limit 1;"""
     md5FileName = GetFileMd5(filepath)
     dic = JPDb().getDict(sql.format(md5=md5FileName))
     dPath = self.archivesPathInDatabase
     if dic:
         r0 = dic[0]
         r0['md5FilePath'] = os.path.join(dPath, r0['md5FileShortName'])
         r0['md5FileName'] = md5FileName
         return r0
     else:
         r0 = {'md5FileName': md5FileName}
         r0['md5FilePath'] = os.path.join(
             dPath, md5FileName + "." + getExName(filepath))
         return r0
Esempio n. 16
0
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(1057, 722)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(Dialog)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.tableView = QtWidgets.QTableView(Dialog)
        self.tableView.setObjectName("tableView")
        self.verticalLayout_3.addWidget(self.tableView)
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout_3.addWidget(self.pushButton)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        self.pushButton.clicked.connect(self.dispData)
        JPDb().getQSqlDatabase()
        self.Model = QtSql.QSqlRelationalTableModel()
        self.Model.setTable('ttt')
        # Relation = QtSql.QSqlRelation("t_enumeration", "fItemID", "fTitle")
        # self.Model.setRelation(3, Relation)
        #Model.setFilter("False")
        self.Model.setSort(1, Qt.DescendingOrder)
        # header = ['文档编号',
        #           '发文日期',
        #           '文号',
        #           '文件类型',
        #           '文件标题',
        #           '发文单位',
        #           '关键字',
        #           '是否手续文件',
        #           '是否任务来源',
        #           '是否进度文件',
        #           '涉及项目数',
        #           '涉及项目']
        # for i, r in enumerate(header):
        #     self.Model.setHeaderData(i, Qt.Horizontal, r)

        self.tableView.setModel(self.Model)
Esempio n. 17
0
 def on_butPathImport_clicked(self):
     path_lst = self.getAndCheckPaths()
     newPKString = JPDb().LAST_INSERT_ID_SQL()
     self.showInfo(len(path_lst))
     hasError = 0
     SQLS = []
     for i, path in enumerate(path_lst):
         dic = self.getFieldsValues(path)
         fns = ["CONCAT('包含文件:',char(10),REPEAT('-',150))"]
         addFileSQL = []
         subPath = os.listdir(path)
         subPath = ["/".join((path, item)) for item in subPath]
         s = "正在处理{}".format(path)
         logging.getLogger().debug(s)
         self.dispInfo(s, i+1)
         for j, sub in enumerate(subPath):
             fns.append(sqm(os.path.basename(sub)+";"))
             exist, md5FileName, md5BaseName, file_pk = md5Exist(
                 sub, self.con_path)
             if not exist:
                 s = "--->复制【{}】".format(sub)
                 self.dispInfo(s, i+1)
                 logging.getLogger().debug(s)
                 try:
                     toPath = "{}/{}".format(self.con_path, md5FileName)
                     myCopy(sub, toPath)
                     s2 = "insert into t_additionals (original_name,filemd5,"
                     s2 = s2+"file_type) VALUES ('{}',unhex('{}'),'{}');"
                     s2 = [s2.format(os.path.basename(sub),
                                     md5BaseName, getExName(sub)), newPKString]
                     isOK, pk = JPDb().executeTransaction(s2)
                     addFileSQL.append(
                         "select {} into @file_pk{};".format(pk, j))
                 except Exception as e:
                     hasError += 1
                     t = '上传文件过程出现错误,档案未上传,错误信息为:\n{}'
                     logging.getLogger().debug(t)
                     msgBox = QMessageBox(QMessageBox.Critical,
                                          u'提示', t.format(str(e)))
                     msgBox.exec_()
                     print(t)
             else:
                 addFileSQL.append(
                     "SELECT {} INTO @file_pk{};".format(file_pk, j))
             s1 = "insert into t_additionals_archives(archives_pk, file_pk)"
             s1 = s1 + " VALUES(@archive_pk, @file_pk{})"
             addFileSQL.append(s1.format(j))
         dic['archive_describe'] = "CONCAT({})".format(
             (",char(10),").join(fns))
         dic['archive_type'] = sqm(self.archive_type)
         SQLS.append(self.getInsertArchiveSQL('50', dic))
         SQLS.append("{} INTO @archive_pk;".format(newPKString))
         SQLS = SQLS + addFileSQL
         try:
             JPDb().executeTransaction(SQLS)
             SQLS = []
         except Exception as e:
             hasError += 1
             t = '执行增加档案SQL中出现错误,档案并未实际添加,错误信息为:\n{}\n执行SQL为\n{}'
             strSql = '\n'.join(SQLS)
             errStr = t.format(str(e), strSql)
             msgBox = QMessageBox(QMessageBox.Critical,
                                  u'提示', errStr)
             msgBox.exec_()
     QMessageBox.information(self, '提示', "OK")
Esempio n. 18
0
    def on_butFileImport_clicked(self):

        def getInsertAndFileSQL():
            return
        QF = QFileDialog.getOpenFileNames
        fns, filetype = QF(self,
                           "Select a File",
                           JPPub().getOrSetlastOpenDir(),  # 起始路径
                           "Files (*.jpg *.PDF *.doc *.docx *.xls *.xlsx)")
        if not fns:
            return
        JPPub().getOrSetlastOpenDir(fns[0])
        newPKString = JPDb().LAST_INSERT_ID_SQL()
        self.showInfo(len(fns))
        hasError = 0
        for i, original_path in enumerate(fns):
            SQLS = []
            s = "检查是否存在数据库中{}".format(original_path)
            logging.getLogger().debug(s)
            self.dispInfo(s, i+1)
            exist, md5FileName, md5BaseName, file_pk = md5Exist(
                original_path, self.con_path)
            fldValues = self.getFieldsValues(original_path)
            SQLS.append(self.getInsertArchiveSQL(self.archive_type, fldValues))
            SQLS.append("{} INTO @archive_pk;".format(newPKString))
            if exist:
                SQLS.append("select {} into @file_pk;".format(file_pk))
            else:
                s2 = "insert into t_additionals (original_name,filemd5"
                s2 = s2 + ",file_type) VALUES ('{}',unhex('{}'),'{}');"
                SQLS.append(s2.format(os.path.basename(original_path),
                                      md5BaseName, getExName(original_path)))
                SQLS.append("{} INTO @file_pk;".format(newPKString))
            s1 = "insert into t_additionals_archives(archives_pk, file_pk)"
            s1 = s1+" VALUES (@archive_pk,@file_pk);"
            SQLS.append(s1)
            if not exist:
                s = "复制【{}】".format(original_path)
                logging.getLogger().debug(s)
                self.dispInfo(s, i+1)
                try:
                    toPath = "{}/{}".format(self.con_path, md5FileName)
                    myCopy(original_path, toPath)
                except Exception as e:
                    hasError += 1
                    t = '上传文件过程出现错误,档案未上传,错误信息为:\n{}'
                    logging.getLogger().debug(t)
                    msgBox = QMessageBox(QMessageBox.Critical,
                                         u'提示', t.format(str(e)))
                    msgBox.exec_()
            try:
                JPDb().executeTransaction(SQLS)
            except Exception as e:
                hasError += 1
                t = '执行增加档案SQL中出现错误,档案并未实际添加,错误信息为:\n{}\n执行SQL为\n{}'
                strSql = '\n'.join(SQLS)
                errStr = t.format(str(e), strSql)
                logging.getLogger().error("生成的导入文件夹SQL错误:"+strSql)
                msgBox = QMessageBox(QMessageBox.Critical,
                                     u'提示', errStr)
                msgBox.exec_()

        # 循环执行完后报告
        else:
            self.hideInfo()
            okStr = "完成但出现{}个错误".format(hasError) if hasError else "完成"
            QMessageBox.information(self, '提示', okStr)
Esempio n. 19
0
 def onGetFieldsRowSources(self):
     db = JPDb()
     lst = db.getDataList(
         "select fTypeName,fTypeID from t_enumeration_type")
     return [('fTypeID', lst, 1)]
Esempio n. 20
0
 def onGetFieldsRowSources(self):
     sql = """select CONCAT(rpad(org_simple_name,7,'  '),'->',org_name), org_pk
                 from t_org_info 
                 order by CONVERT(org_simple_name USING gbk)"""
     lstOrg = JPDb().getDataList(sql)
     return [('org_parent', lstOrg, 1)]
Esempio n. 21
0
 def fileIsUsed(file_pk, archives_pk):
     s = used_sql.format(file_pk=file_pk, archives_pk=archives_pk)
     return JPDb().executeTransaction(s)
Esempio n. 22
0
    def CopyPicAndGetSaveFileSQL(self) -> list:
        sqls = []
        if not self.addtionalChanged:
            return sqls
        used_sql = """
                select archives_pk from t_additionals_archives
                where file_pk={file_pk}
                    and archives_pk<>{archives_pk} limit 1;
                """
        del_sql = """
                delete from t_additionals_archives
                where archives_pk={archives_pk}
                    and file_pk={file_pk};
                """
        ins_file = """
                insert into t_additionals
                    (original_name,filemd5,file_type)
                    Values ('{original_name}',
                    unhex('{filemd5}'),'{file_type}');
                """
        ins_add = """
                insert into t_additionals_archives
                    (archives_pk,file_pk,file_index)
                    Values ({archives_pk},{file_pk},{file_index});
                """
        up_index = """update t_additionals_archives
                        set file_index={file_index}
                        where archives_pk={archives_pk}
                            and file_pk={file_pk}"""
        temp_id = self.ui.archives_pk.text()
        cur_pk = temp_id.replace(",", "") if self.isEditMode else ''
        if self.isNewMode:

            cur_pk = '@archives_pk'

        def fileIsUsed(file_pk, archives_pk):
            s = used_sql.format(file_pk=file_pk, archives_pk=archives_pk)
            return JPDb().executeTransaction(s)

        # self.setCursor(Qt.WaitCursor)
        for iRow, r in enumerate(self.addtionalInfo):
            # 删除情况1:用户删除了一个数据库已经存在的文件
            if r.archives_pk and r.deleted:
                # 删除本附件对文件的引用
                tempsql = del_sql.format(file_pk=r.file_pk,
                                         archives_pk=r.archives_pk)
                sqls.append(tempsql)
                if fileIsUsed(r.file_pk, r.archives_pk):
                    # 如果文件已经被其他附件引用,则只删除本附件的引用
                    continue
                else:
                    # 如果没有没有被其他用户引用,物理删除之
                    filePath = r.md5FilePath
                    if os.path.exists(filePath):
                        self.ui.Label_Info.setText("正在删除【{}】".format(filePath))
                        os.remove(filePath)
                        self.self.ui.Label_Info.setText('')
            # 删除情况2:如果是刚刚增加的文件被用户删除,则跳过不处理本行数据
            if not r.archives_pk and r.deleted:
                continue

            # 增加情况1:增加的文件数据库中已经有其他附件引用
            # if r.file_pk and not r.deleted:
            if r.isNew and r.file_pk:
                p_s = ins_add.format(archives_pk=cur_pk,
                                     file_pk=r.file_pk,
                                     file_index=iRow)
                sqls.append(p_s)
            # 增加情况2:增加的文件数据库中不存在,进行物理复制
            # if not r.file_pk and not r.archives_pk:
            if r.isNew and not r.file_pk:
                p_s = "{con_path}/{filemd5}.{file_type}"
                # newPath = p_s.format(
                #     con_path=self.archivesPathInDatabase,
                #     filemd5=r.md5FileName,
                #     file_type=r.file_type)
                self.ui.Label_Info.setText("正在复制【{}】".format(r.original_path))
                myCopy(r.original_path, r.md5FilePath)
                self.ui.Label_Info.setText('')
                # 先增加一个文件,后面要用到自动生成的文件PK
                tempsql = ins_file.format(original_name=r.original_name,
                                          filemd5=r.md5FileName,
                                          file_type=r.file_type)
                sqls.append(tempsql)
                tempsql = ins_add.format(archives_pk=cur_pk,
                                         file_pk='({})'.format(
                                             JPDb().LAST_INSERT_ID_SQL()),
                                         file_index=iRow)
                sqls.append(tempsql)

            # 如果没有删除并且是一个已经存在的文件,修改显示顺序
            if r.archives_pk and not r.deleted:
                tempsql = up_index.format(archives_pk=cur_pk,
                                          file_pk=r.file_pk,
                                          file_index=iRow)
                sqls.append(tempsql)

        return sqls
Esempio n. 23
0
    def __init__(self, sql_main, PKValue, edit_mode, flags=Qt.WindowFlags()):
        super().__init__(Ui_Form_Edit(),
                         sql_main=sql_main,
                         PKValue=PKValue,
                         edit_mode=edit_mode,
                         flags=flags)
        self.MainForm = JPPub().MainForm
        self.MainForm.addLogoToLabel(self.ui.label_logo)
        self.MainForm.addOneButtonIcon(self.ui.butSave, 'save.png')
        self.MainForm.addOneButtonIcon(self.ui.butCancel, 'cancel.png')

        # 设置listWidget的格式
        cfg = ConfigInfo()
        temp = [int(r) for r in cfg.viewpdf.pagesize.split(',')]
        self.pdfPageSize = QSize(temp[0], temp[1])
        self.icoSize = QSize(96, 96)
        self.ui.listWidget.setSpacing(5)
        self.ui.listWidget.setGridSize(self.pdfPageSize)
        self.ui.listWidget.setResizeMode(QListWidget.Adjust)
        self.ui.listWidget.setIconSize(self.pdfPageSize)
        self.ui.listWidget.setViewMode(QListWidget.IconMode)
        self.ui.listWidget.itemDoubleClicked.connect(
            self.listItemDoubleClicked)
        # 保存最后一次点击的信息,时间和节点,防止重复点击
        self.laseDoubleInfo = []
        self.ui.listWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.listWidget.customContextMenuRequested[QPoint].connect(
            self.rightClicked)
        # 标签文本自动换行
        self.ui.listWidget.setFlow(QListView.LeftToRight)
        self.ui.listWidget.setWrapping(True)
        self.ui.label_ProjectLink.setWordWrap(True)
        self._currentEditModelRow = None
        self.ui.fUserID.hide()
        # 附件有无修改的标志
        self.addtionalChanged = False
        self.pop: FormPopProgressBar = None
        # 存放用户已经选择的关联项目
        self.projectKeyList = []
        self.projectKeyListChanged = False

        editStyle = """border: 1px groove gray;
                        border-radius: 3px;
                        padding: 2px 4px;
                        border-width: 1px;
                        border-style: solid;
                        background-color: white;
                        border-color: rgb(171, 171, 171);"""
        readStyle = """border: 1px groove gray;
                        border-radius: 3px;
                        padding: 2px 4px;
                        border-width: 1px;
                        border-style: solid;
                        border-color: rgb(171, 171, 171);"""
        if self.isNewMode or self.isEditMode:
            self.ui.label_ProjectLink.setStyleSheet(editStyle)
            self.ui.label_ProjectLink.mouseDoubleClickEvent = self.on_but_SelectProject_clicked
        else:
            self.ui.label_ProjectLink.setStyleSheet(readStyle)
            self.ui.listWidget.setStyleSheet(
                "background-color: rgb(239, 239, 239);")
        # addtionalInfo用来以文件为行,保存档案的附件数据,用于保存命令等
        self.addtionalInfo = []
        # listIcos是一个列表,内部存放所有在listWidget中显示的图标
        #self.listIcos = []
        # 下面的链表,用于存放listIcos中可用于放大显示的图片
        self.viewPicInfos = BilateralLinkList()
        # # 一个只包含PDF页面和图片的列表,由编辑窗体维护,用于放大显示时用
        # self.ViewPdfAndPic = []

        #
        self.archivesPathInDatabase = os.path.abspath(
            JPPub().getConfigData()["archives_path"])
        if self.isNewMode:
            self.ui.fUserID.setText(str(JPUser().currentUserID()))
        self.readData()
        if (not self.isNewMode) and self.ui.archives_pk.text():
            sql = "select project_pk from "
            sql = sql + "t_archives_project where archives_pk={}"
            dic = JPDb().getDict(
                sql.format(self.ui.archives_pk.text().replace(",", "")))
            projects = [str(r['project_pk']) for r in dic]
            if projects:
                self.readProject(projects)

        self.ui.archives_pk.setEnabled(False)
        self.ui.issuing_date.setFocus()
        QGuiApplication.processEvents()
        # QGuiApplication.processEvents()
        # self.repaint()
        self.readAddtionalFromDatabase()
        self.initAdditional(self.addtionalInfo)

        # 根据窗体编辑状态设置窗体中按钮的显示状态
        if self.isReadOnlyMode:
            self.ui.but_SelectProject.setEnabled(False)
            # self.ui.btn_Download.setEnabled(False)
            self.ui.btn_Add.setEnabled(False)
            self.ui.btn_Delete.setEnabled(False)